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
10 changes: 10 additions & 0 deletions .github/workflows/build-snaps.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ jobs:
- name: Checkout
uses: actions/checkout@v4

- name: Check Piper voice manifest
run: |
set -euo pipefail
sudo apt-get update
sudo apt-get install --yes yq
python3 tests/test_generate_snapcraft.py
generated_manifest="${RUNNER_TEMP}/speech-provider-piper-snapcraft.yaml"
speech-provider-piper/generate_snapcraft.sh "$generated_manifest"
diff -u speech-provider-piper/snapcraft.yaml "$generated_manifest"

- name: Discover directories with snapcraft.yaml
id: discover
shell: bash
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ clean-snaps: $(SNAPS:%=%-clean)
# speech-provider-piper's snapcraft.yaml is generated: it bundles one voice
# component per voice listed in voices.yaml, appended to the static template.
speech-provider-piper/snapcraft.yaml: speech-provider-piper/snapcraft.yaml.in speech-provider-piper/voices.yaml speech-provider-piper/generate_snapcraft.sh
cd speech-provider-piper && ./generate_snapcraft.sh > snapcraft.yaml
cd speech-provider-piper && ./generate_snapcraft.sh

speech-provider-piper-snap: speech-provider-piper/snapcraft.yaml

Expand Down
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,13 @@ $ sudo snap install --dangerous ./output/snaps/speech-provider-piper_0.1_amd64.s
$ sudo snap install --dangerous ./output/snaps/speech-provider-piper+voices-es-mx-claude-high_0.1.comp
```
### Packaging a new voice
Adding a new voice involves simply editing the voices.yaml file in the speech-provider-piper directory. speech-provider-piper/snapcraft.yaml is generated from snapcraft.yaml.in and voices.yaml by generate_snapcraft.sh, and is regenerated automatically as part of `make build`/`make speech-provider-piper-snap` whenever either input file changes.
Adding a new voice involves editing `speech-provider-piper/voices.yaml`. The
manifest comes from that catalog and `snapcraft.yaml.in`. Install the jq-based
`yq` (`sudo apt install yq` on Ubuntu), then run
`./speech-provider-piper/generate_snapcraft.sh` and commit the regenerated
Comment on lines +40 to +41

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can add a workshop action for this. Ideally we'd capture all the build dependencies in there so the user doesn't have to install any other dependencies outside of their environment.

`speech-provider-piper/snapcraft.yaml`. Invalid input leaves the existing manifest
unchanged. The build targets also regenerate it when the inputs change, and CI
checks that the committed manifest is up to date.

## Testing

Expand Down
116 changes: 91 additions & 25 deletions speech-provider-piper/generate_snapcraft.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,100 @@
# listed in voices.yaml to the static template in snapcraft.yaml.in.
#
# Usage:
# ./generate_snapcraft.sh > snapcraft.yaml
# ./generate_snapcraft.sh [output-file]
set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
template="${script_dir}/snapcraft.yaml.in"
voices_yaml="${script_dir}/voices.yaml"
output="${1:-${script_dir}/snapcraft.yaml}"

cat <<'EOF'
if [[ $# -gt 1 ]]; then
echo "Usage: $0 [output-file]" >&2
exit 2
fi

if ! command -v yq >/dev/null 2>&1; then
echo "Error: jq-based yq is required to generate the Piper snap manifest." >&2
exit 1
fi

for input_file in "$template" "$voices_yaml"; do
if [[ ! -r "$input_file" ]]; then
echo "Error: required input is missing or unreadable: $input_file" >&2
exit 1
fi
done

if ! python3 "${script_dir}/validate_yaml.py" "$voices_yaml"; then
echo "Error: duplicate or invalid YAML in $voices_yaml." >&2
exit 1
fi

# Validate YAML values before converting them to line-based shell input.
if ! voice_rows="$(yq -ers '
if length != 1 or (.[0] | type != "object" or length == 0) then
error("expected a single non-empty mapping of locales")
else
.[0] | to_entries[]
| .key as $locale
| if ($locale | test("\\A[a-z]{2}-[A-Z]{2}\\z") | not) then
error("invalid locale: \($locale | @json)")
elif (.value | type != "object"
or (.test_phrase | type != "string" or (test("\\S") | not))
or (.voices | type != "array" or length == 0)) then
error("locale \($locale) must have a non-empty test_phrase and voices list")
else
.value.voices[]
end
| if type == "string" and test("\\A[a-z0-9_-]+-(x_low|low|medium|high)\\z") then
[$locale, .] | @tsv
else
error("invalid voice ID for locale \($locale): \(. | @json)")
end
end
' "$voices_yaml")"; then
echo "Error: invalid Piper voice catalog: $voices_yaml" >&2
exit 1
fi

tmp_file="$(mktemp -- "${output}.tmp.XXXXXX")"
trap 'rm -f -- "$tmp_file"' EXIT

cat > "$tmp_file" <<'EOF'
# This file is generated by generate_snapcraft.sh from snapcraft.yaml.in and
# voices.yaml. Do not hand-edit the "parts" entries or "components" section
# below; edit snapcraft.yaml.in or voices.yaml and re-run generate_snapcraft.sh.
EOF
cat "$template"
cat "$template" >> "$tmp_file"

components_yaml=""
declare -A component_names=()

mapfile -t locales < <(yq -r 'keys_unsorted[]' "$voices_yaml")

for locale in "${locales[@]}"; do
language_raw="${locale%-*}"
country_raw="${locale##*-}"
language_lower="$(printf '%s' "$language_raw" | tr '[:upper:]' '[:lower:]')"
country_lower="$(printf '%s' "$country_raw" | tr '[:upper:]' '[:lower:]')"
country_upper="$(printf '%s' "$country_raw" | tr '[:lower:]' '[:upper:]')"
while IFS=$'\t' read -r locale voice_id; do
language_lower="${locale%-*}"
country_upper="${locale##*-}"
country_lower="$(printf '%s' "$country_upper" | LC_ALL=C tr 'A-Z' 'a-z')"
locale_underscore="${language_lower}_${country_upper}"

mapfile -t voice_ids < <(yq -r --arg locale "$locale" '.[$locale].voices[]' "$voices_yaml")

for voice_id in "${voice_ids[@]}"; do
name_lower="${voice_id%-*}"
quality_lower="${voice_id##*-}"
name_lower="${voice_id%-*}"
quality_lower="${voice_id##*-}"
comp_name="voices-${language_lower}-${country_lower}-${name_lower}-${quality_lower}"
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
fi
if [[ -n "${component_names[$comp_name]+x}" ]]; then
echo "Error: duplicate voice component in $voices_yaml: $comp_name" >&2
exit 1
fi
component_names["$comp_name"]=1

comp_name="voices-${language_lower}-${country_lower}-${name_lower}-${quality_lower}"
dir_name="${locale_underscore}-${name_lower}-${quality_lower}"
onnx_file="${dir_name}.onnx"
base_url="https://huggingface.co/rhasspy/piper-voices/resolve/main/${language_lower}/${locale_underscore}/${name_lower}/${quality_lower}"
dir_name="${locale_underscore}-${name_lower}-${quality_lower}"
onnx_file="${dir_name}.onnx"
base_url="https://huggingface.co/rhasspy/piper-voices/resolve/main/${language_lower}/${locale_underscore}/${name_lower}/${quality_lower}"

cat <<EOF
cat >> "$tmp_file" <<EOF

${comp_name}:
plugin: dump
Expand All @@ -65,7 +121,7 @@ for locale in "${locales[@]}"; do
meta/hooks/post-refresh: (component/${comp_name})/meta/hooks/post-refresh
EOF

components_yaml+="
components_yaml+="
${comp_name}:
type: standard
summary: ${locale} ${name_lower} voice for Piper
Expand All @@ -75,7 +131,17 @@ EOF
install: {}
post-refresh: {}
"
done
done
done <<< "$voice_rows"

printf '\ncomponents:%s' "$components_yaml" >> "$tmp_file"

if ! yq -es 'length == 1 and (.[0] | type == "object"
and (.parts | type == "object") and (.components | type == "object" and length > 0))' \
"$tmp_file" >/dev/null; then
echo "Error: generated manifest must be a single YAML mapping with parts and components." >&2
exit 1
fi

printf '\ncomponents:%s' "$components_yaml"
chmod 0644 "$tmp_file"
mv -fT -- "$tmp_file" "$output"
trap - EXIT
72 changes: 72 additions & 0 deletions speech-provider-piper/validate_yaml.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Reject duplicate mapping keys in the Piper voice catalog."""

import sys
from pathlib import Path
from typing import Any

import yaml
from yaml.nodes import MappingNode


class DuplicateKeyError(ValueError):
"""Raised when a YAML mapping defines the same key more than once."""


class UniqueKeyLoader(yaml.SafeLoader):
"""Safe YAML loader that rejects duplicate mapping keys."""


def construct_unique_mapping(
loader: UniqueKeyLoader, node: MappingNode, deep: bool = False
) -> dict[Any, Any]:
mapping: dict[Any, Any] = {}
first_key_lines: dict[Any, int] = {}

for key_node, value_node in node.value:
key = loader.construct_object(key_node, deep=deep)
try:
first_line = first_key_lines.get(key)
except TypeError as exc:
raise yaml.constructor.ConstructorError(
"while constructing a mapping",
node.start_mark,
"found an unhashable key",
key_node.start_mark,
) from exc

if first_line is not None:
raise DuplicateKeyError(
f"{key_node.start_mark.name}:{key_node.start_mark.line + 1}: "
f"duplicate YAML key {key!r} (first defined at line {first_line})"
)

first_key_lines[key] = key_node.start_mark.line + 1
mapping[key] = loader.construct_object(value_node, deep=deep)

return mapping


UniqueKeyLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_unique_mapping
)


def main() -> int:
if len(sys.argv) != 2:
print(f"Usage: {Path(sys.argv[0]).name} <yaml-file>", file=sys.stderr)
return 2

path = Path(sys.argv[1])
try:
with path.open(encoding="utf-8") as yaml_file:
yaml.load(yaml_file, Loader=UniqueKeyLoader)
except (OSError, yaml.YAMLError, DuplicateKeyError) as error:
print(f"Error: {error}", file=sys.stderr)
return 1

return 0


if __name__ == "__main__":
raise SystemExit(main())
118 changes: 118 additions & 0 deletions tests/test_generate_snapcraft.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
#!/usr/bin/env python3
"""Failure and atomicity tests for the Piper manifest generator."""

import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
PIPER_DIR = ROOT / "speech-provider-piper"


class GenerateSnapcraftTests(unittest.TestCase):
def setUp(self) -> None:
self.temp_dir = tempfile.TemporaryDirectory()
self.fixture = Path(self.temp_dir.name)
for filename in (
"generate_snapcraft.sh",
"snapcraft.yaml.in",
"validate_yaml.py",
):
shutil.copy2(PIPER_DIR / filename, self.fixture / filename)

self.output = self.fixture / "snapcraft.yaml"
self.output.write_text("existing manifest\n", encoding="utf-8")
self.expected_output = self.output.read_bytes()
self.voices = self.fixture / "voices.yaml"

def tearDown(self) -> None:
self.temp_dir.cleanup()

def assert_generation_fails(self, diagnostic: str) -> None:
result = subprocess.run(
["bash", str(self.fixture / "generate_snapcraft.sh")],
capture_output=True,
check=False,
text=True,
)

self.assertNotEqual(result.returncode, 0)
self.assertIn(diagnostic, result.stdout + result.stderr)
self.assertEqual(self.expected_output, self.output.read_bytes())

def test_missing_input_leaves_existing_manifest_unchanged(self) -> None:
self.assert_generation_fails("required input is missing or unreadable")

def test_invalid_yaml_leaves_existing_manifest_unchanged(self) -> None:
self.voices.write_text("en-US: [\n", encoding="utf-8")
self.assert_generation_fails("duplicate or invalid YAML in")

def test_duplicate_locale_leaves_existing_manifest_unchanged(self) -> None:
self.voices.write_text(
"en-US:\n test_phrase: Hello\n voices: [amy-medium]\n"
"en-US:\n test_phrase: Hello\n voices: [ryan-medium]\n",
encoding="utf-8",
)
self.assert_generation_fails(
"duplicate YAML key 'en-US' (first defined at line 1)"
)

def test_duplicate_mapping_key_leaves_existing_manifest_unchanged(self) -> None:
self.voices.write_text(
"en-US:\n test_phrase: Hello\n voices: [amy-medium]\n"
" voices: [ryan-medium]\n",
encoding="utf-8",
)
self.assert_generation_fails(
"duplicate YAML key 'voices' (first defined at line 3)"
)

def test_empty_voice_list_leaves_existing_manifest_unchanged(self) -> None:
self.voices.write_text(
"en-US: {test_phrase: Hello, voices: []}\n", encoding="utf-8"
)
self.assert_generation_fails(
"must have a non-empty test_phrase and voices list"
)

def test_invalid_voice_id_leaves_existing_manifest_unchanged(self) -> None:
self.voices.write_text(
'en-US: {test_phrase: Hello, voices: ["amy-medium\\nryan-medium"]}\n',
encoding="utf-8",
)
self.assert_generation_fails("invalid voice ID for locale en-US")

def test_invalid_component_name_leaves_existing_manifest_unchanged(self) -> None:
self.voices.write_text(
"en-US: {test_phrase: Hello, voices: [test_voice-x_low]}\n",
encoding="utf-8",
)
self.assert_generation_fails(
"invalid snap component name for en-US test_voice-x_low"
)

def test_duplicate_component_leaves_existing_manifest_unchanged(self) -> None:
self.voices.write_text(
"en-US: {test_phrase: Hello, voices: [amy-medium, amy-medium]}\n",
encoding="utf-8",
)
self.assert_generation_fails("duplicate voice component")

def test_invalid_template_leaves_existing_manifest_unchanged(self) -> None:
self.voices.write_text(
"en-US: {test_phrase: Hello, voices: [amy-medium]}\n",
encoding="utf-8",
)
(self.fixture / "snapcraft.yaml.in").write_text(
"not: valid: yaml: [\n", encoding="utf-8"
)
self.assert_generation_fails(
"generated manifest must be a single YAML mapping with parts and components"
)


if __name__ == "__main__":
unittest.main()
Loading