Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
*.snap
*.comp
.workshop.lock
.workshop.lock
__pycache__/
7 changes: 5 additions & 2 deletions .workshop/audible.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,18 @@ sdks:
endpoint: $XDG_RUNTIME_DIR/pulse/native

actions:
install: tasks/install_snaps.sh "$@"

# Same regression test as the silent workshop, but audible: speech plays
# through the tunneled host pulse server. See the README's Testing section
# for the one-time tunnel setup.
test: tasks/test_snap_interfaces.sh --host-audio

# Speaks test phrases with piper voices through the tunneled host pulse
# server, installing each voice's snap component on demand; see
# tasks/speak_piper_voices.py. With no arguments every voice in
# speech-provider-piper/tests/speak_piper_voices.py. With no arguments
# every voice in
# speech-provider-piper/voices.yaml is spoken:
# workshop run audible speak
# workshop run audible speak en_GB-alan-medium fr_FR-siwis-medium
speak: tasks/speak_piper_voices.py "$@"
speak: speech-provider-piper/tests/speak_piper_voices.py "$@"
5 changes: 3 additions & 2 deletions .workshop/silent.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,15 @@ actions:
install: tasks/install_snaps.sh "$@"

# Speaks test phrases with piper voices, installing each voice's snap
# component on demand; see tasks/speak_piper_voices.py. The snaps must
# component on demand; see speech-provider-piper/tests/speak_piper_voices.py.
# The snaps must
# already be installed and connected (the test action does that), and the
# components must have been built into output/snaps (make build). With no
# arguments every voice in speech-provider-piper/voices.yaml is spoken
# (PIPER_VOICES selects the default subset):
# workshop run silent speak
# workshop run silent speak en_GB-alan-medium fr_FR-siwis-medium
speak: tasks/speak_piper_voices.py "$@"
speak: speech-provider-piper/tests/speak_piper_voices.py "$@"

# Speaks a test phrase with the espeak speech provider (installed and
# connected like any other provider, via the install action plus
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@ The workshops have a `speak` action that speaks test phrases with piper voices (
workshop run silent speak en_GB-alan-medium fr_FR-siwis-medium
```

By default the test action also speaks every piper voice, one per locale in `speech-provider-piper/voices.yaml`. To have it test only certain languages (or a single voice), pass a subset via the `PIPER_VOICES` environment variable, from outside the workshop via `workshop run --env` (the `speak` action takes the voices as plain arguments instead):
Multi-speaker models list one voice identifier per speaker, suffixed with `#<speaker>` (e.g. `sr_RS-serbski_institut-medium#0` and `#1` for the Serbian voice's two speakers): speaking a plain identifier tests every speaker the model config declares — failing if the provider lists fewer — while a suffixed identifier tests just that one.

By default the test action also speaks every piper voice in `speech-provider-piper/voices.yaml`, testing each speaker of multi-speaker models individually. To have it test only certain languages (or a single voice), pass a subset via the `PIPER_VOICES` environment variable, from outside the workshop via `workshop run --env` (the `speak` action takes the voices as plain arguments instead):

```bash
workshop run --env PIPER_VOICES="en_GB-alan-medium fr_FR-siwis-medium" audible test
Expand Down
9 changes: 8 additions & 1 deletion speech-provider-piper/generate_snapcraft.sh
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,14 @@ while IFS=$'\t' read -r locale voice_id; do

name_lower="${voice_id%-*}"
quality_lower="${voice_id##*-}"
comp_name="voices-${language_lower}-${country_lower}-${name_lower}-${quality_lower}"
# Snap component names only allow lowercase alphanumerics and hyphens, so
# underscores in piper voice names and qualities (e.g. serbski_institut,
# x_low) become hyphens in the component name. The voice directory and
# .onnx file keep the piper spelling: that basename is the voice ID piper
# and Spiel use.
comp_name_voice="${name_lower//_/-}"
comp_name_quality="${quality_lower//_/-}"
comp_name="voices-${language_lower}-${country_lower}-${comp_name_voice}-${comp_name_quality}"
if [[ ! "$comp_name" =~ ^[a-z0-9]+(-[a-z0-9]+)*$ || ${#comp_name} -gt 40 ]]; then
echo "Error: invalid snap component name for $locale $voice_id: $comp_name" >&2
exit 1
Expand Down
31 changes: 31 additions & 0 deletions speech-provider-piper/snapcraft.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,28 @@ parts:
meta/hooks/install: (component/voices-ru-ru-irina-medium)/meta/hooks/install
meta/hooks/post-refresh: (component/voices-ru-ru-irina-medium)/meta/hooks/post-refresh

voices-sr-rs-serbski-institut-medium:
plugin: dump
source: ./component-base
build-packages:
- curl
- ca-certificates
override-build: |
craftctl default
set -eu
mkdir -p "$CRAFT_PART_INSTALL/sr_RS-serbski_institut-medium"
curl -L --fail --retry 3 \
-o "$CRAFT_PART_INSTALL/sr_RS-serbski_institut-medium/sr_RS-serbski_institut-medium.onnx" \
"https://huggingface.co/rhasspy/piper-voices/resolve/main/sr/sr_RS/serbski_institut/medium/sr_RS-serbski_institut-medium.onnx"
curl -L --fail --retry 3 \
-o "$CRAFT_PART_INSTALL/sr_RS-serbski_institut-medium/sr_RS-serbski_institut-medium.onnx.json" \
"https://huggingface.co/rhasspy/piper-voices/resolve/main/sr/sr_RS/serbski_institut/medium/sr_RS-serbski_institut-medium.onnx.json"
organize:
sr_RS-serbski_institut-medium/sr_RS-serbski_institut-medium.onnx: (component/voices-sr-rs-serbski-institut-medium)/sr_RS-serbski_institut-medium.onnx
sr_RS-serbski_institut-medium/sr_RS-serbski_institut-medium.onnx.json: (component/voices-sr-rs-serbski-institut-medium)/sr_RS-serbski_institut-medium.onnx.json
meta/hooks/install: (component/voices-sr-rs-serbski-institut-medium)/meta/hooks/install
meta/hooks/post-refresh: (component/voices-sr-rs-serbski-institut-medium)/meta/hooks/post-refresh

voices-sv-se-nst-medium:
plugin: dump
source: ./component-base
Expand Down Expand Up @@ -821,6 +843,15 @@ components:
install: {}
post-refresh: {}

voices-sr-rs-serbski-institut-medium:
type: standard
summary: sr-RS serbski_institut voice for Piper
description: sr-RS serbski_institut voice for Piper
version: '0.1'
hooks:
install: {}
post-refresh: {}

voices-sv-se-nst-medium:
type: standard
summary: sv-SE nst voice for Piper
Expand Down
161 changes: 139 additions & 22 deletions tasks/piper_speech.py → speech-provider-piper/tests/piper_speech.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import argparse
import array
import json
import math
import os
import re
Expand All @@ -17,8 +18,11 @@
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
VOICE_CATALOG = ROOT / "speech-provider-piper" / "voices.yaml"
# The voices directory speech-provider-piper is built with (meson
# -Dvoices_dir, populated by the voice components' install hooks).
VOICES_DIR = Path("/var/snap/speech-provider-piper/current/voices")
PIPER_PROVIDER = "ai.piper.Speech.Provider"
DBUS_INTERFACE = "org.freedesktop.Speech.Provider"
DBUS_MATCH = f"type='method_call',interface='{DBUS_INTERFACE}',member='Synthesize'"
Expand Down Expand Up @@ -112,7 +116,72 @@ def validate_synthesis_calls(


def component_name_for_voice(voice: str) -> str:
return f"voices-{voice.lower().replace('_', '-')}"
return f"voices-{voice.partition('#')[0].lower().replace('_', '-')}"


def list_provider_voices() -> list[str]:
"""Return the voice identifiers Spiel lists for the Piper provider."""
output = run_checked(
["orca-spiel.spiel", "-V"], "could not list Spiel voices"
)
identifiers = []
for line in output.splitlines():
fields = line.split()
# The last two columns are the identifier and the provider; the
# name and language columns may contain spaces.
if len(fields) >= 2 and fields[-1] == PIPER_PROVIDER:
identifiers.append(fields[-2])
return identifiers


def model_speaker_count(voice: str) -> int:
"""Speakers declared by the model config piper loads for this voice."""
config_path = VOICES_DIR / voice / f"{voice}.onnx.json"
try:
config = json.loads(config_path.read_text())
except (OSError, ValueError) as error:
raise SpeechCheckError(
f"could not read the model config for {voice} ({config_path}):"
f" {error}"
) from error
try:
return int(config["num_speakers"])
except (KeyError, TypeError, ValueError) as error:
raise SpeechCheckError(
f"{config_path} declares no usable speaker count: {error}"
) from error


def speaker_variants(voice: str, identifiers: list[str]) -> list[str]:
"""Expand a catalog voice ID to the identifiers the provider lists.

Multi-speaker models expose one identifier per speaker, suffixed with
"#<index>" (e.g. sr_RS-serbski_institut-medium#0): a plain ID expands
to every listed speaker of the model, a suffixed ID selects exactly
that speaker.
"""
if voice in identifiers:
return [voice]
if "#" in voice:
# An explicitly suffixed request must match a listed identifier.
raise SpeechCheckError(
f"voice {voice} is not provided by {PIPER_PROVIDER} "
f"(listed: {', '.join(identifiers) or 'none'})"
)
variants = sorted(
(
identifier
for identifier in identifiers
if identifier.partition("#")[0] == voice
),
key=lambda identifier: int(identifier.partition("#")[2] or 0),
)
if not variants:
raise SpeechCheckError(
f"voice {voice} is not provided by {PIPER_PROVIDER} "
f"(listed: {', '.join(identifiers) or 'none'})"
)
return variants


def run_checked(
Expand Down Expand Up @@ -156,6 +225,21 @@ def ensure_voice_component(voice: str, snap_output_dir: Path) -> None:
):
return

# snapd rejects component files the installed snap does not declare;
# that means the installed speech-provider-piper predates this voice.
if not re.search(
rf"^speech-provider-piper\+{re.escape(component)}\s",
installed_components,
re.MULTILINE,
):
raise SpeechCheckError(
f"the installed speech-provider-piper snap does not declare "
f"component {component}, so it predates this voice; reinstall "
"the snaps from the current build first (the test action does, "
"or in a workshop: workshop run <workshop> install "
"speech-provider-piper)"
)

component_files = sorted(
snap_output_dir.glob(f"speech-provider-piper+{component}_*.comp")
)
Expand Down Expand Up @@ -468,22 +552,54 @@ def run_monitored_speech(

def verify_voice(
voice: str, capture_audio: bool, snap_output_dir: Path
) -> AudioStats | None:
) -> list[tuple[str, AudioStats | None]]:
ensure_voice_component(voice, snap_output_dir)
phrase = phrase_for_voice(voice)
# Spiel matches -v against the identifiers the provider lists, which
# carry a "#<speaker>" suffix for multi-speaker models; an unresolved
# ID would silently fall back to the provider's default voice. Test
# every listed speaker unless one is requested explicitly.
identifiers = list_provider_voices()
variants = speaker_variants(voice, identifiers)
if "#" not in voice:
# An unsuffixed request covers the whole model: require the
# provider to list every speaker the model config declares, so a
# speaker vanishing from the listing fails the test instead of
# silently shrinking its coverage. Single-speaker models are
# listed without a suffix.
num_speakers = model_speaker_count(voice)
if num_speakers == 1:
expected = {voice}
else:
expected = {f"{voice}#{index}" for index in range(num_speakers)}
listed = {
identifier
for identifier in identifiers
if identifier.partition("#")[0] == voice
}
if listed != expected:
raise SpeechCheckError(
f"{voice}: expected {num_speakers} speaker identifier(s)"
f" {sorted(expected)}, provider lists {sorted(listed)}"
)
results: list[tuple[str, AudioStats | None]] = []
with tempfile.TemporaryDirectory() as directory:
recording_path = Path(directory) / "speech.wav"
monitor_output = run_monitored_speech(
voice, phrase, capture_audio, recording_path
)
calls = parse_synthesis_calls(monitor_output)
validate_synthesis_calls(calls, get_service_owner(PIPER_PROVIDER), voice)
for number, identifier in enumerate(variants):
recording_path = Path(directory) / f"speech-{number}.wav"
monitor_output = run_monitored_speech(
identifier, phrase, capture_audio, recording_path
)
calls = parse_synthesis_calls(monitor_output)
validate_synthesis_calls(
calls, get_service_owner(PIPER_PROVIDER), identifier
)

if not capture_audio:
return None
stats = audio_stats(recording_path)
validate_audio(stats)
return stats
stats = None
if capture_audio:
stats = audio_stats(recording_path)
validate_audio(stats)
results.append((identifier, stats))
return results


def handle_sigterm(signum: int, _frame: object) -> None:
Expand All @@ -494,20 +610,21 @@ def run_voice_check(voice: str, capture_audio: bool, snap_output_dir: Path) -> i
previous_sigterm_handler = signal.signal(signal.SIGTERM, handle_sigterm)
try:
try:
stats = verify_voice(voice, capture_audio, snap_output_dir)
results = verify_voice(voice, capture_audio, snap_output_dir)
except (SpeechCheckError, OSError, EOFError, wave.Error) as error:
print(f"{voice}: {error}", file=sys.stderr)
return 1
finally:
signal.signal(signal.SIGTERM, previous_sigterm_handler)

if stats is not None:
print(
f"{voice}: verified Piper request and audio "
f"(RMS {stats.rms:.2f}, peak {stats.peak})"
)
else:
print(f"{voice}: verified Piper request")
for identifier, stats in results:
if stats is not None:
print(
f"{identifier}: verified Piper request and audio "
f"(RMS {stats.rms:.2f}, peak {stats.peak})"
)
else:
print(f"{identifier}: verified Piper request")
return 0


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@
# workshop run silent speak en_GB-alan-medium # one voice
# workshop run silent speak en_GB-alan-medium fr_FR-siwis-medium
#
# Voice identifiers are as shown by `orca-spiel.spiel -V`
# (<locale with _>-<name>, e.g. en_GB-alan-medium); with none given, the
# Voice identifiers are the catalog IDs as shown by `orca-spiel.spiel -V`
# (<locale with _>-<name>, e.g. en_GB-alan-medium). Multi-speaker models list
# one identifier per speaker with a "#<speaker>" suffix (e.g.
# sr_RS-serbski_institut-medium#1): a plain catalog ID speaks every speaker
# the model config declares (failing if the provider lists fewer), a
# suffixed ID speaks just that one. With none given, the
# PIPER_VOICES environment variable's voices are spoken if it is set, and
# otherwise every voice in speech-provider-piper/voices.yaml. The snaps must
# already be installed and connected (the test action does that), and
Expand All @@ -30,7 +34,9 @@


def main(argv):
os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
os.chdir(
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")
)
snap_output_dir = Path(os.environ.get("SNAP_OUTPUT_DIR", "output/snaps"))
capture_audio = os.environ.get("PIPER_CAPTURE_AUDIO") == "1"

Expand All @@ -47,9 +53,14 @@ def main(argv):
# `workshop run --env PIPER_VOICES=... <workshop> test|speak`.
requested = argv[1:] or shlex.split(os.environ.get("PIPER_VOICES", "")) or voices
for voice in requested:
if voice not in voices:
base, separator, suffix = voice.partition("#")
# "#<speaker>" selects one speaker of a multi-speaker model; the
# speaker index itself is validated against the provider later.
if base not in voices or (separator and not suffix.isdigit()):
print(
f"unknown voice '{voice}'; valid voices:\n" + "\n".join(voices),
f"unknown voice '{voice}'; valid voices:\n" + "\n".join(voices)
+ "\n(multi-speaker models also accept \"#<speaker>\" suffixes,"
' e.g. sr_RS-serbski_institut-medium#1)',
file=sys.stderr,
)
return 1
Expand Down
Loading
Loading