diff --git a/AGENTS.md b/AGENTS.md index 99d445c..ddec187 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -289,6 +289,15 @@ voice_transport.py lazy-imported, keeping the module stdlib-only; the engine interfaces are plain classes so tests inject fakes. Knows nothing about the scheduler or the gateway. +voice_train.py + neutral recording helpers for training a custom Piper voice + (optional, off-bootstrap): LJSpeech dataset writer + (`metadata.csv` + `wavs/NNNN.wav`), prompt loading, WAV I/O, + level math for the mic check, and the silence-endpointing + capture loop. Stdlib-only (numpy lazy in `resample_pcm16`); + `scripts/voice-record.py` is the CLI front end and + `scripts/voice-train.sh` the GPU fine-tune/export pipeline. See + docs/VOICE-TRAIN.md. Knows nothing about the scheduler. ``` ## Run / verify @@ -549,6 +558,22 @@ CLI, unit tests (24) + integration tests (2). the venv under `.runtime/venv`, the Piper voice under `.runtime/voice/tts`, the faster-whisper model in the `.runtime/hf` cache). See "### gateway (messenger intake)". +- **Custom Piper voice (train your own)** (Oct 2026): the TTS voice is + replaceable with one fine-tuned on the user's own recordings. This is an + optional, off-bootstrap pipeline (`scripts/voice-record.py` records an + LJSpeech dataset; `scripts/voice-train.sh` fine-tunes from the checkpoint + pinned in `pins.json` `voice` and exports ONNX on a GPU host; + `semif_agent/voice_train.py` holds the neutral recording helpers). + Deployment needs **no gateway code change**: `cli._build_gateway_adapter` + anchors `tts.voice_dir` to `.runtime/voice/tts`, so a trained `.onnx` + + `.onnx.json` dropped there is selected by setting + `gateway.voice.tts.voice` to ``. Only a real spoken reply proves it. + The recorder has three modes: interactive (default), `--speak-prompts` + (TTS reads each line) and `--read-prompts` (prints each line + beeps, no + speech). Two field gotchas: a mic that re-enumerates (usually on a USB hub) + drops the stream — reads take a `--read-timeout` so a take ends instead of + hanging, and prefer a direct port; and prompt/reply audio needs the ALSA + output unmuted (PortAudio has no volume control). See `docs/VOICE-TRAIN.md`. - **Bridge services (SimpleX first)** (Sep 2026): messaging *UX* — invite links, reading incoming messages, composing sends — is decoupled from the command gateway. `semif_agent.bridges` is a folder of standalone third-party API @@ -1220,7 +1245,10 @@ CLI, unit tests (24) + integration tests (2). `simplex.connect_link`. `tests/test_voice_gateway.py` drives the voice loop with injected fake engines (wake gating, endpointing, half-duplex, follow-up window, `speak` truncation/failure, adapter + CLI wiring) — no - hardware, network, or heavy packages. The live `websockets` transport against + hardware, network, or heavy packages. `tests/test_voice_record.py` covers the + recording helpers (`semif_agent/voice_train.py`) — prompt loading, WAV I/O, + level math, the silence-endpointing loop, and the LJSpeech dataset writer — + with a scripted fake audio source. The live `websockets` transport against a real daemon, the live LXMF transport against a real Reticulum network, and the live voice pipeline against a real microphone are live-integration concerns. diff --git a/docs/VOICE-TRAIN.md b/docs/VOICE-TRAIN.md new file mode 100644 index 0000000..8ab17be --- /dev/null +++ b/docs/VOICE-TRAIN.md @@ -0,0 +1,237 @@ +# Training a custom Piper voice + +The voice gateway speaks through **Piper** (`gateway.voice.tts.voice`). You can +replace the stock voice with one trained on your own recordings. This guide is +the end-to-end procedure; the tooling is: + +- `scripts/voice-record.py` — record an LJSpeech dataset from a microphone. +- `scripts/voice-verify.py` — transcribe the takes with Whisper and flag the ones + to re-record. +- `scripts/voice-train.sh` — fine-tune + export a Piper voice on a GPU host. +- `pins.json` `voice` block — the pinned piper1-gpl commit and base checkpoint. + +None of this runs as part of `scripts/bootstrap.sh`; training is a one-off, +hardware-specific job. The gateway needs **no code change** to use the result. + +## The three hosts + +| Role | What it needs | +|---|---| +| **Record** | a microphone + the optional voice stack (`scripts/bootstrap.sh --voice`) | +| **Train** | a CUDA/ROCm GPU + PyTorch | +| **Use** | the voice gateway host | + +Only the training host needs PyTorch; the recording host only needs the voice +stack for `sounddevice`. Per-deployment host choices live in the gitignored +`local/` notes, not here. + +## Important expectations + +- **Piper cannot clone a voice from a clip.** It fine-tunes a new voice from a + recorded dataset, starting from an existing checkpoint. Budget real recording + time. +- **Data quality beats quantity.** A quiet room, one consistent mic and + distance, and a steady tone matter more than raw minutes. ~1 h gives a good + voice; ~15–30 min gives a usable but rougher one; below ~50 utterances is + barely worth it. +- **Training is an overnight job**, even for a small dataset (hours on the GPU). + +## 1. Record + +On the recording host, with the voice stack installed. Three modes: + +```sh +# interactive (default): shows each prompt; Enter to record, then accept/redo/skip +.runtime/venv/bin/python scripts/voice-record.py --list-devices +.runtime/venv/bin/python scripts/voice-record.py + +# hands-free, spoken: the recorder reads each sentence aloud, you repeat it +.runtime/venv/bin/python scripts/voice-record.py --speak-prompts + +# hands-free, read-along: prints each line + beeps (no speech), you read it +.runtime/venv/bin/python scripts/voice-record.py --read-prompts +``` + +- Prompts default to `scripts/voice-prompts-en.txt` — the 720 public-domain + Harvard (IEEE) sentences, phonetically balanced and ideal for TTS. Override + with `--prompts FILE` (one sentence per line; `#` comments skipped). +- `--device`/`--output-device` default to the voice gateway's configured + `gateway.voice.audio.input_device`/`output_device` from `config.json`; set + them by PortAudio name substring or index. +- The dataset is written as `metadata.csv` + `wavs/NNNN.wav`, and **resumes**: + re-running skips prompts already recorded and prints `N of 720 prompt(s) to + record` up front, so a resume over a nearly-complete dataset is never mistaken + for a fresh run (`--overwrite` re-records everything). +- **Interactive**: a mic check runs first (reports RMS/peak/dBFS, warns on + clipping / too-quiet); `Enter` records, then `Enter` accept / `r` redo / + `p` play / `s` skip / `q` quit. +- **Hands-free** (`--speak-prompts` / `--read-prompts`): no keypresses. Each + prompt waits for you to speak (up to `--max-seconds`), records until you stop, + saves, and moves on. It stops after `--max-misses` consecutive silent prompts + (default 3). `--read-prompts` prints the line and beeps and needs no TTS voice. +- `Ctrl-C` stops and keeps what is saved. + +Output is under the gitignored `.runtime/` tree by default. **Recordings are +biometric — never commit them.** + +Tuning: `--max-seconds` (hard cap per take), `--silence-ms` (trailing silence +that ends a take), `--vad-threshold` (int16 RMS speech gate), `--read-timeout` +(seconds with no audio frame before a take is abandoned — guards a dropped +device), `--limit N`. + +## 1b. Verify (Whisper fidelity check) + +The recorder trusts you to accept each take, so a silent false start or a line +read with a word or two wrong slips in silently. Transcribe every take and +compare it to its prompt before training: + +```sh +.runtime/venv/bin/python scripts/voice-verify.py --model small.en \ + --json .runtime/voice-train/verify.json +``` + +- `--model` picks the faster-whisper size; `base.en` is the gateway default and + is cached, but `small.en` is noticeably more accurate (a one-time ~700 MB + download into `.runtime/hf`) and is the better choice here — it resolves most + of base's false positives. +- Each take is classified: `empty` (Whisper heard nothing — a silent/false-start + take), `mismatch` (word error rate above `--max-wer`, default 0.5), `review` + (between `--review-wer` 0.35 and `--max-wer` — worth a listen, because + Whisper's own spelling/number variants land here: "two plus seven" -> "2 plus + 7", "junk yard" -> "junkyard"), and `ok`. Number words are normalized to + digits before comparison. +- The flagged lines print the prompt and the transcript side by side, so a + spelling/number variant (`review`) is obvious versus a real word swap. +- `--json FILE` writes the full report (every transcript + WER), `--limit N` + does a quick smoke test. + +To re-record the flagged takes, mark them first — this moves their wavs into +`/rejected/` and drops their metadata rows, so the recorder resumes and +re-records exactly those prompts: + +```sh +# --prune-review also marks the 'review' band; drop it to only redo hard fails +.runtime/venv/bin/python scripts/voice-verify.py \ + --from-json .runtime/voice-train/verify.json --prune --prune-review + +.runtime/venv/bin/python scripts/voice-record.py --read-prompts # only the gaps +``` + +Nothing is deleted (the rejected wavs stay under `dataset/rejected/`), and +re-running the verifier after re-recording confirms the fixes. Recordings are +biometric — never commit them. + +## 2. Train + +Copy the dataset to the training host, then run the trainer there. It installs +everything under `.runtime/voice-train/` (gitignored) and fine-tunes from the +checkpoint pinned in `pins.json`. + +```sh +rsync -av .runtime/voice-train/dataset :'/.runtime/voice-train/dataset' + +# on the training host, from the checkout: +scripts/voice-train.sh --name en_US-myvoice-medium \ + --dataset .runtime/voice-train/dataset \ + --max-epochs 2000 --batch-size 16 --free-gpu +``` + +- `--name` becomes the `.onnx` basename and the `gateway.voice.tts.voice` value. + Use Piper's convention `--`, e.g. `en_US-myvoice-medium`. +- **`--free-gpu`** stops `winnow.service` and unloads ollama models first. On a + host that also serves the decision engine / codegen, the GPU must be free or + training OOMs (without the flag the script only warns). +- **Quality must match the checkpoint**: the pinned base is `medium` (22050 Hz). + A `high`/`low` checkpoint needs `--quality` and a matching `--checkpoint`. +- **torch must be a ROCm/CUDA build.** The script installs torch from + `--torch-index-url` (default `https://download.pytorch.org/whl/nightly/rocm7.1`, + matching this deployment's ROCm). If the device check reports + `cuda_available=False`, change the index for your GPU/ROCm version — this is + the one host-specific piece. +- Stages are skippable (`--skip-setup`, `--skip-train`, `--skip-export`) and + `--resume` continues from the newest run checkpoint. + +The run writes checkpoints under `.runtime/voice-train/runs/` and exports: + +- `.runtime/voice-train/out/.onnx` +- `.runtime/voice-train/out/.onnx.json` + +Fine-tuning from the base checkpoint, ~1000–3000 epochs is the useful range; +watch `loss_disc_all` level off (tensorboard logs under `runs/`). + +## 3. Deploy and verify + +The gateway resolves `tts.voice` inside `.runtime/voice/tts/` automatically +(`cli._build_gateway_adapter` anchors `voice_dir`), so deploy is just two files: + +```sh +rsync -av .runtime/voice-train/out/.onnx .runtime/voice-train/out/.onnx.json \ + :'/.runtime/voice/tts/' +``` + +Then on the gateway host set: + +```json +"gateway": { "voice": { "tts": { "voice": "" } } } +``` + +Restart the gateway and speak a reply. **Only a real spoken reply proves the +integration** — a generated test passing proves mechanics, not that the voice +loads and sounds right. + +## Troubleshooting + +- **`could not open input device` / silence**: `--list-devices`; on a host where + PortAudio hides a held device, pin by name substring. Another process may hold + the mic (`arecord -l` shows `Subdevices: 0/1`) — e.g. the running gateway + (`gateway --platform all`); stop it for the recording session. +- **No prompt audio** (`--speak-prompts`): the output is muted at the ALSA + level. Unmute with `alsamixer`, or `amixer -c sset Master 100% unmute` + and set `Auto-Mute Mode Disabled` (it silences the speakers when the headphone + jack is sensed). PortAudio has no volume control, so this is the only knob. +- **Recorder hangs mid-session**: usually the audio device dropped (a USB + re-enumeration) and a blocking read stalled. `--read-timeout` (default 3 s) + now ends the take instead of hanging. Prefer a **direct USB port** over a hub, + and check `journalctl -k | grep 'USB disconnect'` for re-enumeration storms. +- **Training `cuda_available=False`**: wrong torch wheel for the GPU — set + `--torch-index-url` to a ROCm/CUDA build matching the host (e.g. + `https://download.pytorch.org/whl/cu124` on a CUDA cloud instance). +- **Training OOMs**: pass `--free-gpu`; lower `--batch-size` (16 → 8). +- **`Weights only load failed` / `Unsupported global: pathlib.PosixPath`**: + PyTorch ≥ 2.6 defaults `torch.load` to `weights_only=True` and Lightning passes + it explicitly, so the pinned base checkpoint's hyperparameters are rejected. + `scripts/voice-train.sh` handles this with a `sitecustomize.py` that + allowlists `PosixPath` on `PYTHONPATH` for the train/export commands; if you + run `piper.train` by hand, do the same. +- **`--ckpt_path` aborts with `does not accept option 'model.sample_bytes'`**: + the pinned older checkpoint's saved model hyperparameters predate the current + `VitsModel` signature, so `LightningCLI._parse_ckpt_path` fails. The script + fine-tunes with `--model.warmstart_ckpt` (non-strict weight copy) instead and + reserves `--ckpt_path` for `--resume`. +- **`ImportError: cannot import name 'espeakbridge'`**: the editable install + builds the CMake extension in its isolated env but does not expose it. Run the + documented dev build in the piper checkout: + `python setup.py build_ext --inplace` (install `scikit-build cmake ninja + cython` first). `scripts/voice-train.sh` does this automatically when the + import fails. +- **Training aborts at epoch 0 with `ModelCheckpoint(monitor='val_mos') could + not find the monitored key`**, or finishes having written **no checkpoints**: + piper's default callbacks monitor `val_mel` (from the validation split) and + `val_mos` (scored over the test split), and Lightning ≥ 2.5 raises rather than + skips when a monitor is missing. Do not zero those splits + (`--data.validation_split` / `--data.num_test_examples`) — leave piper's + defaults. `val_mos` also needs the UTMOS predictor, which downloads on first + use (`torch.hub`, ~392 MB); a host that cannot reach it will not log + `val_mos`. +- **Voice loads but sounds wrong**: too little/clipped data, or too many epochs + (artifacts). Re-record quieter/cleaner; stop training earlier. +- **`piper1-gpl` checkout fails to build**: it needs `espeak-ng`, + `build-essential`, `cmake`, `python3-dev` (the script apt-installs them) and a + compatible Python. Very new interpreters may need a dedicated venv or the + project's Docker image. + +## Maintenance + +The piper1-gpl commit and base checkpoint are pinned in `pins.json` (`voice`). +Bump them via git and rerun `scripts/voice-train.sh`; the checkpoint sha256 is +verified on download. diff --git a/pins.json b/pins.json index 191d00e..759e264 100644 --- a/pins.json +++ b/pins.json @@ -1,5 +1,5 @@ { - "_comment": "Committed pin manifest for the external artifacts this repo downloads: the SemIf engine ref, the pinned GGUF, the HF tokenizer revision, and the simplex-chat binary. These are code-owned, deployment-independent values bumped by a git change and picked up on the next `scripts/bootstrap.sh` run. They are deliberately NOT in config.json (per-machine user config): a ref that changes with every update is not user configuration. The agent reads engine.source/revision from here; the GGUF path is derived from engine.gguf_url unless config.json overrides engine.gguf.", + "_comment": "Committed pin manifest for the external artifacts this repo downloads: the SemIf engine ref, the pinned GGUF, the HF tokenizer revision, the simplex-chat binary, and the voice-training toolchain/checkpoint. These are code-owned, deployment-independent values bumped by a git change and picked up on the next `scripts/bootstrap.sh` run (the voice refs by `scripts/voice-train.sh`). They are deliberately NOT in config.json (per-machine user config): a ref that changes with every update is not user configuration. The agent reads engine.source/revision from here; the GGUF path is derived from engine.gguf_url unless config.json overrides engine.gguf.", "engine": { "semif_repo": "https://github.com/TheoLeeCJ/SemIf.git", "semif_ref": "23cf1f39fc9534fe81437200959b6dfc7106e45a", @@ -12,5 +12,12 @@ "version": "v7.0.3", "bin_url": "https://github.com/simplex-chat/simplex-chat/releases/download/v7.0.3/simplex-chat-ubuntu-24_04-x86_64", "sha256": "895fb14cfaa662d1c0947f2f871141fc89680fe3e70bff64c366cbe9e59aa4f0" + }, + "voice": { + "_comment": "Piper TTS voice-training refs used by scripts/voice-train.sh (optional, off-bootstrap): the piper1-gpl training toolchain commit and the medium base checkpoint it fine-tunes from. See docs/VOICE-TRAIN.md.", + "piper_train_repo": "https://github.com/OHF-Voice/piper1-gpl.git", + "piper_train_ref": "efffbfb226bfb511ebbcf55d0cecd8b35a89743d", + "base_checkpoint_url": "https://huggingface.co/datasets/rhasspy/piper-checkpoints/resolve/main/en/en_US/lessac/medium/epoch=2164-step=1355540.ckpt", + "base_checkpoint_sha256": "ab7e5b8dab40f834b7cc58ae4ad7b7009c954b901e4ddbb784bbe11ce379a1cd" } } diff --git a/scripts/voice-prompts-en.txt b/scripts/voice-prompts-en.txt new file mode 100644 index 0000000..d2b86c6 --- /dev/null +++ b/scripts/voice-prompts-en.txt @@ -0,0 +1,727 @@ +# English recording prompts for a Piper TTS voice (one utterance per line). +# +# Source: the Harvard (IEEE) sentences, from "IEEE Recommended Practice for +# Speech Quality Measurements" (IEEE Std 297-1969, Appendix C) - 720 +# phonetically balanced, public-domain sentences. scripts/voice-record.py reads +# this file to record an LJSpeech-format dataset. Lines starting with "#" and +# blank lines are skipped. A 15-30 minute voice uses roughly 200-450 of them. +The birch canoe slid on the smooth planks. +Glue the sheet to the dark blue background. +It's easy to tell the depth of a well. +These days a chicken leg is a rare dish. +Rice is often served in round bowls. +The juice of lemons makes fine punch. +The box was thrown beside the parked truck. +The hogs were fed chopped corn and garbage. +Four hours of steady work faced us. +A large size in stockings is hard to sell. +The boy was there when the sun rose. +A rod is used to catch pink salmon. +The source of the huge river is the clear spring. +Kick the ball straight and follow through. +Help the woman get back to her feet. +A pot of tea helps to pass the evening. +Smoky fires lack flame and heat. +The soft cushion broke the man's fall. +The salt breeze came across from the sea. +The girl at the booth sold fifty bonds. +The small pup gnawed a hole in the sock. +The fish twisted and turned on the bent hook. +Press the pants and sew a button on the vest. +The swan dive was far short of perfect. +The beauty of the view stunned the young boy. +Two blue fish swam in the tank. +Her purse was full of useless trash. +The colt reared and threw the tall rider. +It snowed, rained, and hailed the same morning. +Read verse out loud for pleasure. +Hoist the load to your left shoulder. +Take the winding path to reach the lake. +Note closely the size of the gas tank. +Wipe the grease off his dirty face. +Mend the coat before you go out. +The wrist was badly strained and hung limp. +The stray cat gave birth to kittens. +The young girl gave no clear response. +The meal was cooked before the bell rang. +What joy there is in living. +A king ruled the state in the early days. +The ship was torn apart on the sharp reef. +Sickness kept him home the third week. +The wide road shimmered in the hot sun. +The lazy cow lay in the cool grass. +Lift the square stone over the fence. +The rope will bind the seven books at once. +Hop over the fence and plunge in. +The friendly gang left the drug store. +Mesh wire keeps chicks inside. +The frosty air passed through the coat. +The crooked maze failed to fool the mouse. +Adding fast leads to wrong sums. +The show was a flop from the very start. +A saw is a tool used for making boards. +The wagon moved on well oiled wheels. +March the soldiers past the next hill. +A cup of sugar makes sweet fudge. +Place a rosebush near the porch steps. +Both lost their lives in the raging storm. +We talked of the side show in the circus. +Use a pencil to write the first draft. +He ran half way to the hardware store. +The clock struck to mark the third period. +A small creek cut across the field. +Cars and busses stalled in snow drifts. +The set of china hit the floor with a crash. +This is a grand season for hikes on the road. +The dune rose from the edge of the water. +Those words were the cue for the actor to leave. +A yacht slid around the point into the bay. +The two met while playing on the sand. +The ink stain dried on the finished page. +The walled town was seized without a fight. +The lease ran out in sixteen weeks. +A tame squirrel makes a nice pet. +The horn of the car woke the sleeping cop. +The heart beat strongly and with firm strokes. +The pearl was worn in a thin silver ring. +The fruit peel was cut in thick slices. +The Navy attacked the big task force. +See the cat glaring at the scared mouse. +There are more than two factors here. +The hat brim was wide and too droopy. +The lawyer tried to lose his case. +The grass curled around the fence post. +Cut the pie into large parts. +Men strive but seldom get rich. +Always close the barn door tight. +He lay prone and hardly moved a limb. +The slush lay deep along the street. +A wisp of cloud hung in the blue air. +A pound of sugar costs more than eggs. +The fin was sharp and cut the clear water. +The play seems dull and quite stupid. +Bail the boat to stop it from sinking. +The term ended in late June that year. +A tusk is used to make costly gifts. +Ten pins were set in order. +The bill was paid every third week. +Oak is strong and also gives shade. +Cats and dogs each hate the other. +The pipe began to rust while new. +Open the crate but don't break the glass. +Add the sum to the product of these three. +Thieves who rob friends deserve jail. +The ripe taste of cheese improves with age. +Act on these orders with great speed. +The hog crawled under the high fence. +Move the vat over the hot fire. +The bark of the pine tree was shiny and dark. +Leaves turn brown and yellow in the fall. +The pennant waved when the wind blew. +Split the log with a quick, sharp blow. +Burn peat after the logs give out. +He ordered peach pie with ice cream. +Weave the carpet on the right hand side. +Hemp is a weed found in parts of the tropics. +A lame back kept his score low. +We find joy in the simplest things. +Type out three lists of orders. +The harder he tried the less he got done. +The boss ran the show with a watchful eye. +The cup cracked and spilled its contents. +Paste can cleanse the most dirty brass. +The slang word for raw whiskey is booze. +It caught its hind paw in a rusty trap. +The wharf could be seen at the farther shore. +Feel the heat of the weak dying flame. +The tiny girl took off her hat. +A cramp is no small danger on a swim. +He said the same phrase thirty times. +Pluck the bright rose without leaves. +Two plus seven is less than ten. +The glow deepened in the eyes of the sweet girl. +Bring your problems to the wise chief. +Write a fond note to the friend you cherish. +Clothes and lodging are free to new men. +We frown when events take a bad turn. +Port is a strong wine with a smoky taste. +The young kid jumped the rusty gate. +Guess the results from the first scores. +A salt pickle tastes fine with ham. +The just claim got the right verdict. +These thistles bend in a high wind. +Pure bred poodles have curls. +The tree top waved in a graceful way. +The spot on the blotter was made by green ink. +Mud was spattered on the front of his white shirt. +The cigar burned a hole in the desk top. +The empty flask stood on the tin tray. +A speedy man can beat this track mark. +He broke a new shoelace that day. +The coffee stand is too high for the couch. +The urge to write short stories is rare. +The pencils have all been used. +The pirates seized the crew of the lost ship. +We tried to replace the coin but failed. +She sewed the torn coat quite neatly. +The sofa cushion is red and of light weight. +The jacket hung on the back of the wide chair. +At that high level the air is pure. +Drop the two when you add the figures. +A filing case is now hard to buy. +An abrupt start does not win the prize. +Wood is best for making toys and blocks. +The office paint was a dull, sad tan. +He knew the skill of the great young actress. +A rag will soak up spilled water. +A shower of dirt fell from the hot pipes. +Steam hissed from the broken valve. +The child almost hurt the small dog. +There was a sound of dry leaves outside. +The sky that morning was clear and bright blue. +Torn scraps littered the stone floor. +Sunday is the best part of the week. +The doctor cured him with these pills. +The new girl was fired today at noon. +They felt gay when the ship arrived in port. +Add the store's account to the last cent. +Acid burns holes in wool cloth. +Fairy tales should be fun to write. +Eight miles of woodland burned to waste. +The third act was dull and tired the players. +A young child should not suffer fright. +Add the column and put the sum here. +We admire and love a good cook. +There the flood mark is ten inches. +He carved a head from the round block of marble. +She has a smart way of wearing clothes. +The fruit of a fig tree is apple-shaped. +Corn cobs can be used to kindle a fire. +Where were they when the noise started. +The paper box is full of thumb tacks. +Sell your gift to a buyer at a good gain. +The tongs lay beside the ice pail. +The petals fall with the next puff of wind. +Bring your best compass to the third class. +They could laugh although they were sad. +Farmers came in to thresh the oat crop. +The brown house was on fire to the attic. +The lure is used to catch trout and flounder. +Float the soap on top of the bath water. +A blue crane is a tall wading bird. +A fresh start will work such wonders. +The club rented the rink for the fifth night. +After the dance, they went straight home. +The hostess taught the new maid to serve. +He wrote his last novel there at the inn. +Even the worst will beat his low score. +The cement had dried when he moved it. +The loss of the second ship was hard to take. +The fly made its way along the wall. +Do that with a wooden stick. +Live wires should be kept covered. +The large house had hot water taps. +It is hard to erase blue or red ink. +Write at once or you may forget it. +The doorknob was made of bright clean brass. +The wreck occurred by the bank on Main Street. +A pencil with black lead writes best. +Coax a young calf to drink from a bucket. +Schools for ladies teach charm and grace. +The lamp shone with a steady green flame. +They took the axe and the saw to the forest. +The ancient coin was quite dull and worn. +The shaky barn fell with a loud crash. +Jazz and swing fans like fast music. +Rake the rubbish up and then burn it. +Slash the gold cloth into fine ribbons. +Try to have the court decide the case. +They are pushed back each time they attack. +He broke his ties with groups of former friends. +They floated on the raft to sun their white backs. +The map had an X that meant nothing. +Whitings are small fish caught in nets. +Some ads serve to cheat buyers. +Jerk the rope and the bell rings weakly. +A waxed floor makes us lose balance. +Madam, this is the best brand of corn. +On the islands the sea breeze is soft and mild. +The play began as soon as we sat down. +This will lead the world to more sound and fury. +Add salt before you fry the egg. +The rush for funds reached its peak Tuesday. +The birch looked stark white and lonesome. +The box is held by a bright red snapper. +To make pure ice, you freeze water. +The first worm gets snapped early. +Jump the fence and hurry up the bank. +Yell and clap as the curtain slides back. +They are men who walk the middle of the road. +Both brothers wear the same size. +In some form or other we need fun. +The prince ordered his head chopped off. +The houses are built of red clay bricks. +Ducks fly north but lack a compass. +Fruit flavors are used in fizz drinks. +These pills do less good than others. +Canned pears lack full flavor. +The dark pot hung in the front closet. +Carry the pail to the wall and spill it there. +The train brought our hero to the big town. +We are sure that one war is enough. +Gray paint stretched for miles around. +The rude laugh filled the empty room. +High seats are best for football fans. +Tea served from the brown jug is tasty. +A dash of pepper spoils beef stew. +A zestful food is the hot-cross bun. +The horse trotted around the field at a brisk pace. +Find the twin who stole the pearl necklace. +Cut the cord that binds the box tightly. +The red tape bound the smuggled food. +Look in the corner to find the tan shirt. +The cold drizzle will halt the bond drive. +Nine men were hired to dig the ruins. +The junk yard had a mouldy smell. +The flint sputtered and lit a pine torch. +Soak the cloth and drown the sharp odor. +The shelves were bare of both jam or crackers. +A joy to every child is the swan boat. +All sat frozen and watched the screen. +A cloud of dust stung his tender eyes. +To reach the end he needs much courage. +Shape the clay gently into block form. +A ridge on a smooth surface is a bump or flaw. +Hedge apples may stain your hands green. +Quench your thirst, then eat the crackers. +Tight curls get limp on rainy days. +The mute muffled the high tones of the horn. +The gold ring fits only a pierced ear. +The old pan was covered with hard fudge. +Watch the log float in the wide river. +The node on the stalk of wheat grew daily. +The heap of fallen leaves was set on fire. +Write fast if you want to finish early. +His shirt was clean but one button was gone. +The barrel of beer was a brew of malt and hops. +Tin cans are absent from store shelves. +Slide the box into that empty space. +The plant grew large and green in the window. +The beam dropped down on the workmen's head. +Pink clouds floated with the breeze. +She danced like a swan, tall and graceful. +The tube was blown and the tire flat and useless. +It is late morning on the old wall clock. +Let's all join as we sing the last chorus. +The last switch cannot be turned off. +The fight will end in just six minutes. +The store walls were lined with colored frocks. +The peace league met to discuss their plans. +The rise to fame of a person takes luck. +Paper is scarce, so write with much care. +The quick fox jumped on the sleeping cat. +The nozzle of the fire hose was bright brass. +Screw the round cap on as tight as needed. +Time brings us many changes. +The purple tie was ten years old. +Men think and plan and sometimes act. +Fill the ink jar with sticky glue. +He smoke a big pipe with strong contents. +We need grain to keep our mules healthy. +Pack the records in a neat thin case. +The crunch of feet in the snow was the only sound. +The copper bowl shone in the sun's rays. +Boards will warp unless kept dry. +The plush chair leaned against the wall. +Glass will clink when struck by metal. +Bathe and relax in the cool green grass. +Nine rows of soldiers stood in line. +The beach is dry and shallow at low tide. +The idea is to sew both edges straight. +The kitten chased the dog down the street. +Pages bound in cloth make a book. +Try to trace the fine lines of the painting. +Women form less than half of the group. +The zones merge in the central part of town. +A gem in the rough needs work to polish. +Code is used when secrets are sent. +Most of the news is easy for us to hear. +He used the lathe to make brass objects. +The vane on top of the pole revolved in the wind. +Mince pie is a dish served to children. +The clan gathered on each dull night. +Let it burn, it gives us warmth and comfort. +A castle built from sand fails to endure. +A child's wit saved the day for us. +Tack the strip of carpet to the worn floor. +Next Tuesday we must vote. +Pour the stew from the pot into the plate. +Each penny shone like new. +The man went to the woods to gather sticks. +The dirt piles were lines along the road. +The logs fell and tumbled into the clear stream. +Just hoist it up and take it away. +A ripe plum is fit for a king's palate. +Our plans right now are hazy. +Brass rings are sold by these natives. +It takes a good trap to capture a bear. +Feed the white mouse some flower seeds. +The thaw came early and freed the stream. +He took the lead and kept it the whole distance. +The key you designed will fit the lock. +Plead to the council to free the poor thief. +Better hash is made of rare beef. +This plank was made for walking on. +The lake sparkled in the red hot sun. +He crawled with care along the ledge. +Tend the sheep while the dog wanders. +It takes a lot of help to finish these. +Mark the spot with a sign painted red. +Take two shares as a fair profit. +The fur of cats goes by many names. +North winds bring colds and fevers. +He asks no person to vouch for him. +Go now and come here later. +A sash of gold silk will trim her dress. +Soap can wash most dirt away. +That move means the game is over. +He wrote down a long list of items. +A siege will crack the strong defense. +Grape juice and water mix well. +Roads are paved with sticky tar. +Fake stones shine but cost little. +The drip of the rain made a pleasant sound. +Smoke poured out of every crack. +Serve the hot rum to the tired heroes. +Much of the story makes good sense. +The sun came up to light the eastern sky. +Heave the line over the port side. +A lathe cuts and trims any wood. +It's a dense crowd in two distinct ways. +His hip struck the knee of the next player. +The stale smell of old beer lingers. +The desk was firm on the shaky floor. +It takes heat to bring out the odor. +Beef is scarcer than some lamb. +Raise the sail and steer the ship northward. +A cone costs five cents on Mondays. +A pod is what peas always grow in. +Jerk the dart from the cork target. +No cement will hold hard wood. +We now have a new base for shipping. +A list of names is carved around the base. +The sheep were led home by a dog. +Three for a dime, the young peddler cried. +The sense of smell is better than that of touch. +No hardship seemed to keep him sad. +Grace makes up for lack of beauty. +Nudge gently but wake her now. +The news struck doubt into restless minds. +Once we stood beside the shore. +A chink in the wall allowed a draft to blow. +Fasten two pins on each side. +A cold dip restores health and zest. +He takes the oath of office each March. +The sand drifts over the sill of the old house. +The point of the steel pen was bent and twisted. +There is a lag between thought and act. +Seed is needed to plant the spring corn. +Draw the chart with heavy black lines. +The boy owed his pal thirty cents. +The chap slipped into the crowd and was lost. +Hats are worn to tea and not to dinner. +The ramp led up to the wide highway. +Beat the dust from the rug onto the lawn. +Say it slowly but make it ring clear. +The straw nest housed five robins. +Screen the porch with woven straw mats. +This horse will nose his way to the finish. +The dry wax protects the deep scratch. +He picked up the dice for a second roll. +These coins will be needed to pay his debt. +The nag pulled the frail cart along. +Twist the valve and release hot steam. +The vamp of the shoe had a gold buckle. +The smell of burned rags itches my nose. +New pants lack cuffs and pockets. +The marsh will freeze when cold enough. +They slice the sausage thin with a knife. +The bloom of the rose lasts a few days. +A gray mare walked before the colt. +Breakfast buns are fine with a hot drink. +Bottles hold four kinds of rum. +The man wore a feather in his felt hat. +He wheeled the bike past the winding road. +Drop the ashes on the worn old rug. +The desk and both chairs were painted tan. +Throw out the used paper cup and plate. +A clean neck means a neat collar. +The couch cover and hall drapes were blue. +The stems of the tall glasses cracked and broke. +The wall phone rang loud and often. +The clothes dried on a thin wooden rack. +Turn on the lantern which gives us light. +The cleat sank deeply into the soft turf. +The bills were mailed promptly on the tenth of the month. +To have is better than to wait and hope. +The price is fair for a good antique clock. +The music played on while they talked. +Dispense with a vest on a day like this. +The bunch of grapes was pressed into wine. +He sent the figs, but kept the ripe cherries. +The hinge on the door creaked with old age. +The screen before the fire kept in the sparks. +Fly by night, and you waste little time. +Thick glasses helped him read the print. +Birth and death mark the limits of life. +The chair looked strong but had no bottom. +The kite flew wildly in the high wind. +A fur muff is stylish once more. +The tin box held priceless stones. +We need an end of all such matter. +The case was puzzling to the old and wise. +The bright lanterns were gay on the dark lawn. +We don't get much money but we have fun. +The youth drove with zest, but little skill. +Five years he lived with a shaggy dog. +A fence cuts through the corner lot. +The way to save money is not to spend much. +Shut the hatch before the waves push it in. +The odor of spring makes young hearts jump. +Crack the walnut with your sharp side teeth. +He offered proof in the form of a large chart. +Send the stuff in a thick paper bag. +A quart of milk is water for the most part. +They told wild tales to frighten him. +The three story house was built of stone. +In the rear of the ground floor was a large passage. +A man in a blue sweater sat at the desk. +Oats are a food eaten by horse and man. +Their eyelids droop for want of sleep. +A sip of tea revives his tired friend. +There are many ways to do these things. +Tuck the sheet under the edge of the mat. +A force equal to that would move the earth. +We like to see clear weather. +The work of the tailor is seen on each side. +Take a chance and win a china doll. +Shake the dust from your shoes, stranger. +She was kind to sick old people. +The square wooden crate was packed to be shipped. +The dusty bench stood by the stone wall. +We dress to suit the weather of most days. +Smile when you say nasty words. +A bowl of rice is free with chicken stew. +The water in this well is a source of good health. +Take shelter in this tent, but keep still. +That guy is the writer of a few banned books. +The little tales they tell are false. +The door was barred, locked, and bolted as well. +Ripe pears are fit for a queen's table. +A big wet stain was on the round carpet. +The kite dipped and swayed, but stayed aloft. +The pleasant hours fly by much too soon. +The room was crowded with a wild mob. +This strong arm shall shield your honor. +She blushed when he gave her a white orchid. +The beetle droned in the hot June sun. +Press the pedal with your left foot. +Neat plans fail without luck. +The black trunk fell from the landing. +The bank pressed for payment of the debt. +The theft of the pearl pin was kept secret. +Shake hands with this friendly child. +The vast space stretched into the far distance. +A rich farm is rare in this sandy waste. +His wide grin earned many friends. +Flax makes a fine brand of paper. +Hurdle the pit with the aid of a long pole. +A strong bid may scare your partner stiff. +Even a just cause needs power to win. +Peep under the tent and see the clowns. +The leaf drifts along with a slow spin. +Cheap clothes are flashy but don't last. +A thing of small note can cause despair. +Flood the mails with requests for this book. +A thick coat of black paint covered all. +The pencil was cut to be sharp at both ends. +Those last words were a strong statement. +He wrote his name boldly at the top of the sheet. +Dill pickles are sour but taste fine. +Down that road is the way to the grain farmer. +Either mud or dust are found at all times. +The best method is to fix it in place with clips. +If you mumble your speech will be lost. +At night the alarm roused him from a deep sleep. +Read just what the meter says. +Fill your pack with bright trinkets for the poor. +The small red neon lamp went out. +Clams are small, round, soft, and tasty. +The fan whirled its round blades softly. +The line where the edges join was clean. +Breathe deep and smell the piny air. +It matters not if he reads these words or those. +A brown leather bag hung from its strap. +A toad and a frog are hard to tell apart. +A white silk jacket goes with any shoes. +A break in the dam almost caused a flood. +Paint the sockets in the wall dull green. +The child crawled into the dense grass. +Bribes fail where honest men work. +Trample the spark, else the flames will spread. +The hilt of the sword was carved with fine designs. +A round hole was drilled through the thin board. +Footprints showed the path he took up the beach. +She was waiting at my front lawn. +A vent near the edge brought in fresh air. +Prod the old mule with a crooked stick. +It is a band of steel three inches wide. +The pipe ran almost the length of the ditch. +It was hidden from sight by a mass of leaves and shrubs. +The weight of the package was seen on the high scale. +Wake and rise, and step into the green outdoors. +The green light in the brown box flickered. +The brass tube circled the high wall. +The lobes of her ears were pierced to hold rings. +Hold the hammer near the end to drive the nail. +Next Sunday is the twelfth of the month. +Every word and phrase he speaks is true. +He put his last cartridge into the gun and fired. +They took their kids from the public school. +Drive the screw straight into the wood. +Keep the hatch tight and the watch constant. +Sever the twine with a quick snip of the knife. +Paper will dry out when wet. +Slide the catch back and open the desk. +Help the weak to preserve their strength. +A sullen smile gets few friends. +Stop whistling and watch the boys march. +Jerk the cord, and out tumbles the gold. +Slide the tray across the glass top. +The cloud moved in a stately way and was gone. +Light maple makes for a swell room. +Set the piece here and say nothing. +Dull stories make her laugh. +A stiff cord will do to fasten your shoe. +Get the trust fund to the bank early. +Choose between the high road and the low. +A plea for funds seems to come again. +He lent his coat to the tall gaunt stranger. +There is a strong chance it will happen once more. +The duke left the park in a silver coach. +Greet the new guests and leave quickly. +When the frost has come it is time for turkey. +Sweet words work better than fierce. +A thin stripe runs down the middle. +A six comes up more often than a ten. +Lush fern grow on the lofty rocks. +The ram scared the school children off. +The team with the best timing looks good. +The farmer swapped his horse for a brown ox. +Sit on the perch and tell the others what to do. +A steep trail is painful for our feet. +The early phase of life moves fast. +Green moss grows on the northern side. +Tea in thin china has a sweet taste. +Pitch the straw through the door of the stable. +The latch on the back gate needed a nail. +The goose was brought straight from the old market. +The sink is the thing in which we pile dishes. +A whiff of it will cure the most stubborn cold. +The facts don't always show who is right. +She flaps her cape as she parades the street. +The loss of the cruiser was a blow to the fleet. +Loop the braid to the left and then over. +Plead with the lawyer to drop the lost cause. +Calves thrive on tender spring grass. +Post no bills on this office wall. +Tear a thin sheet from the yellow pad. +A cruise in warm waters in a sleek yacht is fun. +A streak of color ran down the left edge. +It was done before the boy could see it. +Crouch before you jump or miss the mark. +Pack the kits and don't forget the salt. +The square peg will settle in the round hole. +Fine soap saves tender skin. +Poached eggs and tea must suffice. +Bad nerves are jangled by a door slam. +Ship maps are different from those for planes. +Dimes showered down from all sides. +They sang the same tunes at each party. +The sky in the west is tinged with orange red. +The pods of peas ferment in bare fields. +The horse balked and threw the tall rider. +The hitch between the horse and cart broke. +Pile the coal high in the shed corner. +A gold vase is both rare and costly. +The knife was hung inside its bright sheath. +The rarest spice comes from the far East. +The roof should be tilted at a sharp slant. +A smatter of French is worse than none. +The mule trod the treadmill day and night. +The aim of the contest is to raise a great fund. +To send it now in large amounts is bad. +There is a fine hard tang in salty air. +Cod is the main business of the north shore. +The slab was hewn from heavy blocks of slate. +Dunk the stale biscuits into strong drink. +Hang tinsel from both branches. +Cap the jar with a tight brass cover. +The poor boy missed the boat again. +Be sure to set the lamp firmly in the hole. +Pick a card and slip it under the pack. +A round mat will cover the dull spot. +The first part of the plan needs changing. +A good book informs of what we ought to know. +The mail comes in three batches per day. +You cannot brew tea in a cold pot. +Dots of light betrayed the black cat. +Put the chart on the mantel and tack it down. +The night shift men rate extra pay. +The red paper brightened the dim stage. +See the player scoot to third base. +Slide the bill between the two leaves. +Many hands help get the job done. +We don't like to admit our small faults. +No doubt about the way the wind blows. +Dig deep in the earth for pirate's gold. +The steady drip is worse than a drenching rain. +A flat pack takes less luggage space. +Green ice frosted the punch bowl. +A stuffed chair slipped from the moving van. +The stitch will serve but needs to be shortened. +A thin book fits in the side pocket. +The gloss on top made it unfit to read. +The hail pattered on the burnt brown grass. +Seven seals were stamped on great sheets. +Our troops are set to strike heavy blows. +The store was jammed before the sale could start. +It was a bad error on the part of the new judge. +One step more and the board will collapse. +Take the match and strike it against your shoe. +The pot boiled, but the contents failed to jell. +The baby puts his right foot in his mouth. +The bombs left most of the town in ruins. +Stop and stare at the hard working man. +The streets are narrow and full of sharp turns. +The pup jerked the leash as he saw a feline shape. +Open your book to the first page. +Fish evade the net and swim off. +Dip the pail once and let it settle. +Will you please answer that phone. +The big red apple fell to the ground. +The curtain rose and the show was on. +The young prince became heir to the throne. +He sent the boy on a short errand. +Leave now and you will arrive on time. +The corner store was robbed last night. +A gold ring will please most any girl. +The long journey home took a year. +She saw a cat in the neighbor's house. +A pink shell was found on the sandy beach. +Small children came to see him. +The grass and bushes were wet with dew. +The blind man counted his old coins. +A severe storm tore down the barn. +She called his name many times. +When you hear the bell, come quickly. diff --git a/scripts/voice-record.py b/scripts/voice-record.py new file mode 100755 index 0000000..e783a6a --- /dev/null +++ b/scripts/voice-record.py @@ -0,0 +1,410 @@ +#!/usr/bin/env python3 +"""Record a personal Piper TTS dataset (LJSpeech format) from the microphone. + +This is the recording front end for the voice-training pipeline: it reads a +prompts file (default `scripts/voice-prompts-en.txt`, the public-domain Harvard +sentences) and walks the prompts one at a time, writing an LJSpeech dataset +(`metadata.csv` + `wavs/NNNN.wav`) that `scripts/voice-train.sh` consumes on the +training host. See `docs/VOICE-TRAIN.md`. + +Two modes: + +- **Interactive** (default): a mic check, then each prompt is shown; `Enter` + records, then `Enter` accept / `r` redo / `p` play / `s` skip / `q` quit. +- **Hands-free** (`--speak-prompts` or `--read-prompts`): no keypresses. With + `--speak-prompts` the recorder reads each sentence aloud and you repeat it; + with `--read-prompts` it **prints** each line and beeps (no speech) — read it + aloud. Either way it records until you stop speaking and moves on. It stops + after `--max-misses` consecutive silent prompts. + +Recordings are **biometric** and stay under the checkout's gitignored +`.runtime/` tree (default output) — never commit them. + +Run it from the checkout with the voice stack installed: + + .runtime/venv/bin/python scripts/voice-record.py --list-devices + .runtime/venv/bin/python scripts/voice-record.py --speak-prompts + +`Ctrl-C` stops and keeps what is already saved; re-running resumes. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(REPO_ROOT)) + +from semif_agent.voice_train import ( # noqa: E402 + DEFAULT_MAX_SECONDS, + DEFAULT_MIN_SPEECH_MS, + DEFAULT_SILENCE_MS, + SAMPLE_RATE, + DatasetStore, + duration_s, + level_report, + load_prompts, + record_until_silence, +) +from semif_agent.voice_transport import ( # noqa: E402 + PiperSynthesizer, + SoundDeviceAudio, + _tone_pcm, + resolve_model_path, +) + +DEFAULT_PROMPT_VOICE = "en_US-lessac-medium" + + +def _voice_config(config_path: Path) -> dict: + try: + return ((json.loads(config_path.read_text()).get("gateway", {}) or {}).get( + "voice", {} + ) or {}) + except Exception: + return {} + + +def _voice_audio_defaults(config_path: Path) -> tuple[str, str]: + """The voice gateway's configured input/output devices, if present.""" + audio = (_voice_config(config_path).get("audio", {}) or {}) + return ( + str(audio.get("input_device", "") or ""), + str(audio.get("output_device", "") or ""), + ) + + +def _prompt_voice_default(config_path: Path) -> str: + tts = (_voice_config(config_path).get("tts", {}) or {}) + return str(tts.get("voice", "") or DEFAULT_PROMPT_VOICE) + + +def _list_devices() -> int: + try: + import sounddevice as sd + except Exception as exc: # pragma: no cover - depends on the host stack + print(f"sounddevice is not installed: {exc}") + print("install the voice stack: scripts/bootstrap.sh --voice") + return 2 + print(sd.query_devices()) + return 0 + + +def _play(audio: SoundDeviceAudio, pcm16: bytes, sample_rate: int) -> None: + if not pcm16: + return + try: + audio.write(pcm16, sample_rate) + except Exception as exc: + print(f" (playback failed: {exc})") + + +def _level_note(report: dict) -> str: + if report["peak_dbfs"] is None: + return "" + if report["peak_dbfs"] > -1.0: + return " WARNING: clipping — lower the mic gain." + if report["peak_dbfs"] < -30.0: + return " WARNING: very quiet — raise the mic gain." + return "" + + +# --------------------------------------------------------------------------- # +# interactive mode +# --------------------------------------------------------------------------- # + + +def _mic_check(audio: SoundDeviceAudio, args: argparse.Namespace) -> bool: + """Record a short sample, report levels, and let the user accept or retry.""" + while True: + print( + f"\nMic check: say a sentence (ends on ~{args.silence_ms} ms of silence, " + f"max {args.mic_check_seconds:.0f}s)." + ) + input(" press Enter to record… ") + pcm = record_until_silence( + audio, + sample_rate=args.sample_rate, + frame_ms=args.frame_ms, + max_seconds=args.mic_check_seconds, + silence_ms=args.silence_ms, + min_speech_ms=args.min_speech_ms, + threshold=args.vad_threshold, + read_timeout=args.read_timeout, + ) + if not pcm: + print(" no speech detected. Check the input device and mic level") + print(" (alsamixer; PortAudio has no volume control), then retry.") + else: + report = level_report(pcm, args.sample_rate) + print( + f" captured {report['seconds']}s rms={report['rms']} " + f"peak={report['peak']} ({report['peak_dbfs']} dBFS)" + + _level_note(report) + ) + choice = input(" [Enter] start recording, p play back, r retry, q quit: ").strip().lower() + if choice == "q": + return False + if choice == "p": + _play(audio, pcm, args.sample_rate) + continue + if choice == "r": + continue + return True + + +def _record_prompt(audio: SoundDeviceAudio, args: argparse.Namespace) -> bytes: + """Record one prompt, letting the user accept / redo / play / skip.""" + while True: + input(" press Enter to record… ") + pcm = record_until_silence( + audio, + sample_rate=args.sample_rate, + frame_ms=args.frame_ms, + max_seconds=args.max_seconds, + silence_ms=args.silence_ms, + min_speech_ms=args.min_speech_ms, + threshold=args.vad_threshold, + read_timeout=args.read_timeout, + ) + if not pcm: + print(" no speech detected; try again.") + continue + report = level_report(pcm, args.sample_rate) + print(f" recorded {report['seconds']}s peak={report['peak_dbfs']} dBFS") + choice = input(" [Enter] accept, r redo, p play, s skip, q quit: ").strip().lower() + if choice == "q": + raise KeyboardInterrupt + if choice == "r": + continue + if choice == "p": + _play(audio, pcm, args.sample_rate) + continue + if choice == "s": + return b"" + return pcm + + +# --------------------------------------------------------------------------- # +# hands-free (read-aloud) mode +# --------------------------------------------------------------------------- # + + +def _say(tts, audio: SoundDeviceAudio, text: str, args: argparse.Namespace) -> None: + """Speak `text` through the output device, then beep (mic is flushed).""" + try: + pcm, rate = tts.synthesize(text) + audio.flush() + audio.write(pcm, rate) + except Exception as exc: + print(f" (prompt playback failed: {exc})") + audio.flush() + cue = _tone_pcm(880, 120, args.sample_rate, 0.4) + if cue: + try: + audio.write(cue, args.sample_rate) + except Exception: + pass + audio.flush() + + +def _beep(audio: SoundDeviceAudio, args: argparse.Namespace) -> None: + """Short attention beep (the 'read now' cue) — no speech.""" + cue = _tone_pcm(880, 120, args.sample_rate, 0.4) + if not cue: + return + audio.flush() + try: + audio.write(cue, args.sample_rate) + except Exception as exc: + print(f" (beep failed: {exc})") + audio.flush() + + +def _pending_prompts(prompts, store: DatasetStore, args) -> list[tuple[int, str, str]]: + """The ``(index, uid, text)`` prompts still to record. + + A prompt is pending when its id is not in the dataset, or when `--overwrite` + is set. `--limit` caps how many are returned. This is what the session + prints up front so a resume over a mostly-complete dataset is never + mistaken for a fresh run. + """ + pending: list[tuple[int, str, str]] = [] + for index, text in enumerate(prompts, start=1): + uid = f"{index:04d}" + if args.overwrite or uid not in store.ids(): + pending.append((index, uid, text)) + if args.limit: + pending = pending[: args.limit] + return pending + + +def _hands_free_session(audio, tts, store: DatasetStore, prompts, args) -> int: + """Walk prompts: speak (or show + beep) each, record the repeat. + + In `--read-prompts` mode the line is printed and a beep cues the take + (no text-to-speech). Stops after `--max-misses` consecutive silent prompts. + """ + speak = not args.read_prompts + recorded = 0 + misses = 0 + pending = _pending_prompts(prompts, store, args) + if not pending: + print("every prompt is already recorded (pass --overwrite to redo them).") + return 0 + print(f"{len(pending)} of {len(prompts)} prompt(s) to record.", flush=True) + if speak: + _say(tts, audio, "Let's begin. Repeat each sentence after the beep.", args) + for position, (_index, uid, text) in enumerate(pending, start=1): + print(f"\n[{position}/{len(pending)}] {text}", flush=True) + pcm = b"" + for attempt in range(2): + if speak: + _say(tts, audio, text, args) + else: + _beep(audio, args) + pcm = record_until_silence( + audio, + sample_rate=args.sample_rate, + frame_ms=args.frame_ms, + max_seconds=args.max_seconds, + silence_ms=args.silence_ms, + min_speech_ms=args.min_speech_ms, + threshold=args.vad_threshold, + read_timeout=args.read_timeout, + ) + if pcm: + break + if attempt == 0: + print(" no speech heard; repeating the cue…", flush=True) + if not pcm: + misses += 1 + print( + f" no speech ({misses}/{args.max_misses}) — skipping; re-run to resume.", + flush=True, + ) + if misses >= args.max_misses: + print(" too many silent prompts — stopping so it doesn't run away.", flush=True) + break + continue + misses = 0 + store.save(uid, text, pcm) + recorded += 1 + report = level_report(pcm, args.sample_rate) + print( + f" saved {uid}.wav ({store.count()} total, {report['seconds']}s)" + + _level_note(report), + flush=True, + ) + return recorded + + +def main(argv: list[str] | None = None) -> int: + default_in, default_out = _voice_audio_defaults(REPO_ROOT / "config.json") + parser = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--out", default=str(REPO_ROOT / ".runtime" / "voice-train" / "dataset"), + help="dataset directory (metadata.csv + wavs/)") + parser.add_argument("--prompts", default=str(REPO_ROOT / "scripts" / "voice-prompts-en.txt"), + help="prompts file (one sentence per line; # comments skipped)") + parser.add_argument("--device", default=default_in, + help="input device (PortAudio name substring or index; default: config)") + parser.add_argument("--output-device", default=default_out, + help="output device for playback (default: config)") + parser.add_argument("--sample-rate", type=int, default=SAMPLE_RATE) + parser.add_argument("--frame-ms", type=int, default=40) + parser.add_argument("--max-seconds", type=float, default=DEFAULT_MAX_SECONDS, + help="hard cap per utterance") + parser.add_argument("--silence-ms", type=int, default=DEFAULT_SILENCE_MS, + help="trailing silence that ends an utterance") + parser.add_argument("--min-speech-ms", type=int, default=DEFAULT_MIN_SPEECH_MS) + parser.add_argument("--vad-threshold", type=float, default=200.0, + help="int16 RMS above which a frame counts as speech") + parser.add_argument("--read-timeout", type=float, default=3.0, + help="seconds with no audio frame before a take is ended (guards a dropped device)") + parser.add_argument("--mic-check-seconds", type=float, default=20.0, + help="hard cap for the mic-check sample") + parser.add_argument("--skip-mic-check", action="store_true") + parser.add_argument("--limit", type=int, default=0, help="record at most N prompts") + parser.add_argument("--overwrite", action="store_true", + help="re-record prompts whose id is already saved") + parser.add_argument("--speak-prompts", action="store_true", + help="hands-free: speak each prompt aloud and record the repeat (no keypresses)") + parser.add_argument("--read-prompts", action="store_true", + help="hands-free: print each line and beep (no speech); read it aloud, recorded") + parser.add_argument("--max-misses", type=int, default=3, + help="stop after this many consecutive silent prompts in --speak-prompts mode") + parser.add_argument("--prompt-voice", default=_prompt_voice_default(REPO_ROOT / "config.json"), + help="Piper voice used to read the prompts in --speak-prompts mode") + parser.add_argument("--list-devices", action="store_true") + args = parser.parse_args(argv) + + if args.list_devices: + return _list_devices() + + prompts = load_prompts(args.prompts) + if not prompts: + print(f"no prompts found in {args.prompts}") + return 2 + store = DatasetStore(args.out, sample_rate=args.sample_rate) + print(f"dataset: {store.out} ({store.count()} already recorded)") + print(f"prompts: {len(prompts)} target rate: {args.sample_rate} Hz") + + audio = SoundDeviceAudio(input_device=args.device, output_device=args.output_device) + try: + audio.open_input(args.sample_rate, args.frame_ms, "") + except Exception as exc: + print(f"could not open input device {args.device!r}: {exc}") + print("list devices with --list-devices; install the stack with scripts/bootstrap.sh --voice") + return 2 + + tts = None + if args.speak_prompts: + voice_path = resolve_model_path( + args.prompt_voice, str(REPO_ROOT / ".runtime" / "voice" / "tts"), (".onnx",) + ) + try: + tts = PiperSynthesizer(voice_path) + except Exception as exc: + print(f"could not load the prompt voice {voice_path!r}: {exc}") + print("download it with scripts/voice-models.py, or pass --prompt-voice ") + audio.close() + return 2 + + recorded = 0 + try: + if args.speak_prompts or args.read_prompts: + recorded = _hands_free_session(audio, tts, store, prompts, args) + else: + if not args.skip_mic_check and not _mic_check(audio, args): + print("aborted at mic check.") + return 1 + pending = _pending_prompts(prompts, store, args) + if not pending: + print("every prompt is already recorded (pass --overwrite to redo them).") + return 0 + print(f"{len(pending)} of {len(prompts)} prompt(s) to record.") + for position, (_index, uid, text) in enumerate(pending, start=1): + print(f"\n[{position}/{len(pending)}] Say: {text}") + pcm = _record_prompt(audio, args) + if not pcm: + print(" skipped.") + continue + path = store.save(uid, text, pcm) + recorded += 1 + print(f" saved {path.name} ({store.count()} total, {duration_s(pcm, args.sample_rate):.1f}s)") + except KeyboardInterrupt: + print("\nstopping (already-recorded prompts are saved).") + finally: + audio.close() + + print(f"\ndone: {recorded} recorded this session, {store.count()} total in {store.out}") + print(f"metadata: {store.metadata}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/voice-train.sh b/scripts/voice-train.sh new file mode 100755 index 0000000..9ef8cc4 --- /dev/null +++ b/scripts/voice-train.sh @@ -0,0 +1,345 @@ +#!/usr/bin/env bash +# Train a custom Piper TTS voice for the voice gateway from a recorded dataset. +# +# Runs on the TRAINING host (a machine with a real GPU), NOT on the gateway host +# that will use the voice. Everything it installs lives inside this checkout +# under .runtime/voice-train/ (gitignored): the piper1-gpl clone, its venv, the +# base checkpoint, the training cache, runs, and the exported voice. Only the +# finished .onnx + .onnx.json are copied to a gateway host. +# +# It fine-tunes from a pinned "medium" checkpoint (Piper has no zero-shot +# cloning; ~15-60 min of recorded audio gives a usable voice). The dataset is an +# LJSpeech directory (metadata.csv + wavs/) produced by scripts/voice-record.py. +# See docs/VOICE-TRAIN.md. +# +# Pinned external refs (piper1-gpl commit, base checkpoint url+sha256) live in the +# committed pins.json; bump those via git and rerun to upgrade. +# +# Usage: +# scripts/voice-train.sh --name en_US-myvoice-medium [--dataset DIR] [--work DIR] +# [--quality medium] [--espeak-voice en-us] +# [--batch-size 16] [--max-epochs 2000] +# [--checkpoint PATH_OR_URL] [--torch-index-url URL] +# [--torch-spec "torch torchaudio"] +# [--free-gpu] [--resume] [--skip-setup|--skip-train|--skip-export] [-h] +set -euo pipefail + +NAME="en_US-custom-medium" +DATASET="" +WORK="" +QUALITY="medium" +ESPEAK_VOICE="en-us" +SAMPLE_RATE="22050" +BATCH_SIZE="16" +MAX_EPOCHS="2000" +CHECKPOINT="" +TORCH_INDEX_URL="https://download.pytorch.org/whl/nightly/rocm7.1" +TORCH_SPEC="torch torchaudio" +FREE_GPU=0 +RESUME=0 +SKIP_SETUP=0 +SKIP_TRAIN=0 +SKIP_EXPORT=0 + +usage() { + sed -n '2,24p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//' + echo + echo " --name ID voice id / output basename (default: $NAME)" + echo " --dataset DIR LJSpeech dataset dir (metadata.csv + wavs/)" + echo " --work DIR scratch dir (default: .runtime/voice-train)" + echo " --quality Q medium|high|low (must match the checkpoint; default medium)" + echo " --espeak-voice V espeak-ng voice (default en-us)" + echo " --sample-rate HZ dataset sample rate (default 22050)" + echo " --batch-size N training batch size (default 16; 16 GB VRAM)" + echo " --max-epochs N trainer.max_epochs (default 2000; fine-tune ~1000-3000)" + echo " --checkpoint P|URL base .ckpt to fine-tune from (default: pinned in pins.json)" + echo " --torch-index-url U ROCm wheel index for torch (default: $TORCH_INDEX_URL)" + echo " --torch-spec SPEC torch packages to install (default: \"$TORCH_SPEC\")" + echo " --free-gpu stop winnow + unload ollama models before training" + echo " --resume resume from the newest run checkpoint under --work" + echo " --skip-setup skip apt/clone/venv/torch/deps (reuse an existing env)" + echo " --skip-train skip training (e.g. export an existing run)" + echo " --skip-export stop after training" + echo " -h this help" + exit "${1:-0}" +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --name) NAME="$2"; shift 2 ;; + --dataset) DATASET="$2"; shift 2 ;; + --work) WORK="$2"; shift 2 ;; + --quality) QUALITY="$2"; shift 2 ;; + --espeak-voice) ESPEAK_VOICE="$2"; shift 2 ;; + --sample-rate) SAMPLE_RATE="$2"; shift 2 ;; + --batch-size) BATCH_SIZE="$2"; shift 2 ;; + --max-epochs) MAX_EPOCHS="$2"; shift 2 ;; + --checkpoint) CHECKPOINT="$2"; shift 2 ;; + --torch-index-url) TORCH_INDEX_URL="$2"; shift 2 ;; + --torch-spec) TORCH_SPEC="$2"; shift 2 ;; + --free-gpu) FREE_GPU=1; shift ;; + --resume) RESUME=1; shift ;; + --skip-setup) SKIP_SETUP=1; shift ;; + --skip-train) SKIP_TRAIN=1; shift ;; + --skip-export) SKIP_EXPORT=1; shift ;; + -h|--help) usage 0 ;; + *) echo "unknown option: $1" >&2; usage 1 ;; + esac +done + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +# apt/systemctl as root directly when the container has no sudo (common on cloud +# GPU images); fall back to sudo on a normal host. +if [[ "$(id -u)" -eq 0 ]]; then + SUDO="" +elif command -v sudo >/dev/null 2>&1; then + SUDO="sudo" +else + SUDO="" +fi +PINS="$REPO_ROOT/pins.json" +[[ -f "$PINS" ]] || { echo "pins.json not found at $PINS — run from a semif-agent checkout" >&2; exit 1; } + +WORK="${WORK:-$REPO_ROOT/.runtime/voice-train}" +DATASET="${DATASET:-$WORK/dataset}" +PIPER_DIR="$WORK/piper1-gpl" +VENV="$WORK/venv" +PY="$VENV/bin/python" +PIP="$VENV/bin/pip" +CACHE="$WORK/cache" +RUNS="$WORK/runs" +OUT="$WORK/out" +CKPTS="$WORK/checkpoints" +COMPAT="$WORK/torch_compat" + +# --- read the voice pins from the committed pins.json ----------------------- +IFS=$'\x1f' read -r PIPER_REPO PIPER_REF CKPT_URL CKPT_SHA < <( + python3 - "$PINS" <<'PY' +import json, sys +pins = json.load(open(sys.argv[1])) +v = pins.get("voice", {}) +print("\x1f".join([ + str(v.get("piper_train_repo", "")), + str(v.get("piper_train_ref", "")), + str(v.get("base_checkpoint_url", "")), + str(v.get("base_checkpoint_sha256", "")), +])) +PY +) +[[ -n "$PIPER_REPO" && -n "$PIPER_REF" ]] || { + echo "pins.json is missing the voice.piper_train_repo/ref entries" >&2; exit 1; } + +echo "== voice training: $NAME" +echo " work: $WORK" +echo " dataset: $DATASET" +echo " piper: $PIPER_REPO @ ${PIPER_REF:0:12}" + +mkdir -p "$WORK" "$CKPTS" "$OUT" "$RUNS" "$COMPAT" + +# PyTorch >=2.6 defaults `torch.load` to weights_only=True, and Lightning passes +# it explicitly, so loading the pinned base checkpoint fails on the +# `pathlib.PosixPath` pickled into its hyperparameters. Allowlist it for the +# training/export interpreter only (via a sitecustomize on PYTHONPATH), which is +# the fix PyTorch's own error recommends. See docs/VOICE-TRAIN.md. +cat > "$COMPAT/sitecustomize.py" <<'PY' +import pathlib + +try: + from torch.serialization import add_safe_globals + + add_safe_globals([pathlib.PosixPath]) +except Exception: # pragma: no cover - best effort; old torch has no such API + pass +PY + +# --- stage 1: dataset check (only needed to actually train) ----------------- +if [[ "$SKIP_TRAIN" != "1" ]]; then + if [[ ! -f "$DATASET/metadata.csv" ]]; then + echo "no dataset at $DATASET/metadata.csv — record one first:" >&2 + echo " python scripts/voice-record.py --out '$DATASET'" >&2 + exit 1 + fi + N_UTT=$(grep -c '|' "$DATASET/metadata.csv" || true) + echo "== dataset: $N_UTT utterances" + if [[ "$N_UTT" -lt 50 ]]; then + echo "WARN: fewer than 50 utterances — the voice will be rough (aim for 200-450+)" >&2 + fi +elif [[ -f "$DATASET/metadata.csv" ]]; then + echo "== dataset present ($(grep -c '|' "$DATASET/metadata.csv" || true) utterances); --skip-train set" +else + echo "== no dataset yet; --skip-train set, so this is a setup/GPU smoke test" +fi + +# --- stage 2: free the GPU (opt-in) ----------------------------------------- +if [[ "$FREE_GPU" == "1" ]]; then + echo "== freeing the GPU" + if systemctl list-unit-files 2>/dev/null | grep -q '^winnow\.service'; then + $SUDO systemctl stop winnow 2>/dev/null || true + fi + if command -v ollama >/dev/null 2>&1; then + ollama ps 2>/dev/null | tail -n +2 | awk '{print $1}' | while read -r m; do + [[ -n "$m" ]] && ollama stop "$m" 2>/dev/null || true + done + fi +else + if systemctl is-active --quiet winnow 2>/dev/null; then + echo "WARN: winnow.service is active and holds the GPU; pass --free-gpu (or stop it) to avoid OOM" >&2 + fi +fi + +# --- stage 3: system prerequisites + piper checkout + venv ------------------ +if [[ "$SKIP_SETUP" != "1" ]]; then + missing=() + for pkg in espeak-ng build-essential cmake python3-dev python3-venv git; do + dpkg -s "$pkg" >/dev/null 2>&1 || missing+=("$pkg") + done + if [[ ${#missing[@]} -gt 0 ]]; then + echo "== installing system prereqs: ${missing[*]}" + $SUDO apt-get update -qq + $SUDO apt-get install -y "${missing[@]}" + fi + + if [[ ! -d "$PIPER_DIR/.git" ]]; then + echo "== cloning piper1-gpl" + git clone "$PIPER_REPO" "$PIPER_DIR" + fi + echo "== checking out piper1-gpl @ ${PIPER_REF:0:12}" + git -C "$PIPER_DIR" fetch --all --tags --quiet + git -C "$PIPER_DIR" checkout --quiet "$PIPER_REF" + + if [[ ! -x "$PY" ]]; then + echo "== creating venv at $VENV" + python3 -m venv "$VENV" + "$PIP" install --upgrade pip wheel setuptools >/dev/null + fi + + if ! "$PY" -c 'import torch' >/dev/null 2>&1; then + echo "== installing torch from $TORCH_INDEX_URL (this may take a while)" + # shellcheck disable=SC2086 + "$PIP" install --index-url "$TORCH_INDEX_URL" $TORCH_SPEC + fi + echo "== installing piper1-gpl [train]" + "$PIP" install -e "${PIPER_DIR}[train]" + + # The editable install builds the CMake extension `espeakbridge` in its + # isolated build env but does not expose it from the source tree, so + # `from piper import espeakbridge` fails at run time. Run the documented + # in-place dev build to place the compiled extensions under src/. + if ! "$PY" -c 'from piper import espeakbridge' >/dev/null 2>&1; then + echo "== building piper1-gpl C extensions in place (espeakbridge)" + "$PIP" install -q scikit-build cmake ninja "cython>=3,<4" + ( cd "$PIPER_DIR" && "$PY" setup.py build_ext --inplace ) + fi + + if [[ -x "$PIPER_DIR/build_monotonic_align.sh" ]]; then + echo "== building monotonic_align" + ( source "$VENV/bin/activate" && cd "$PIPER_DIR" && ./build_monotonic_align.sh ) + fi + + echo "== torch device check" + "$PY" - <<'PY' +import torch +print(f" torch {torch.__version__} hip={getattr(torch.version, 'hip', None)} " + f"cuda_available={torch.cuda.is_available()}") +if not torch.cuda.is_available(): + print(" WARN: no GPU visible to torch — training will be CPU-only and very slow.") + print(" check the ROCm torch wheel matches this GPU (gfx target).") +else: + print(f" device: {torch.cuda.get_device_name(0)}") +PY +fi + +# --- stage 4: base checkpoint ------------------------------------------------ +if [[ -z "$CHECKPOINT" ]]; then + if [[ -n "$CKPT_URL" ]]; then + CHECKPOINT="$CKPTS/$(basename "$CKPT_URL")" + if [[ ! -f "$CHECKPOINT" ]]; then + echo "== downloading base checkpoint" + curl -fL --retry 3 -o "$CHECKPOINT" "$CKPT_URL" + fi + if [[ -n "$CKPT_SHA" ]]; then + echo "== verifying checkpoint sha256" + echo "$CKPT_SHA $CHECKPOINT" | sha256sum -c - + fi + fi +fi +if [[ -n "$CHECKPOINT" ]]; then + echo "== fine-tuning from: $CHECKPOINT" +else + echo "== WARN: no base checkpoint; training from scratch (much slower, lower quality)" >&2 +fi + +# --- stage 5: train ---------------------------------------------------------- +if [[ "$SKIP_TRAIN" != "1" ]]; then + # `--resume` continues a run (Lightning `--ckpt_path`, which also restores the + # optimizer/loop state). A fresh fine-tune warmstarts the model weights from + # the base checkpoint with `--model.warmstart_ckpt`: unlike `--ckpt_path` it + # does not re-parse the base checkpoint's hyperparameters, which is required + # for the pinned older checkpoints on a newer piper1-gpl (their saved + # `model.*` config no longer matches the current model signature). + WARMSTART_CKPT="$CHECKPOINT" + RESUME_CKPT="" + if [[ "$RESUME" == "1" ]]; then + LATEST="$(find "$RUNS" -name '*.ckpt' -printf '%T@ %p\n' 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2- || true)" + [[ -n "$LATEST" ]] && { echo "== resuming from $LATEST"; RESUME_CKPT="$LATEST"; } + fi + echo "== training ($MAX_EPOCHS epochs, batch $BATCH_SIZE) — this runs for hours; Ctrl-C is safe" + FIT_ARGS=( + --data.voice_name "$NAME" + --data.csv_path "$DATASET/metadata.csv" + --data.audio_dir "$DATASET/wavs" + --data.cache_dir "$CACHE" + --data.config_path "$OUT/$NAME.onnx.json" + --data.espeak_voice "$ESPEAK_VOICE" + --data.batch_size "$BATCH_SIZE" + # Keep piper's held-out validation (default 0.1) and test (default 5) + # splits. The default ModelCheckpoint callbacks monitor `val_mel` and + # `val_mos`; `val_mos` is scored over the *test* split, so zeroing either + # split leaves the callback without its metric and Lightning aborts the + # run — and no checkpoint is written for the export step to use. + --model.sample_rate "$SAMPLE_RATE" + --trainer.max_epochs "$MAX_EPOCHS" + --trainer.accelerator gpu + --trainer.devices 1 + --trainer.default_root_dir "$RUNS" + ) + if [[ -n "$RESUME_CKPT" ]]; then + FIT_ARGS+=( --ckpt_path "$RESUME_CKPT" ) + elif [[ -n "$WARMSTART_CKPT" ]]; then + FIT_ARGS+=( --model.warmstart_ckpt "$WARMSTART_CKPT" ) + fi + PYTHONPATH="$COMPAT${PYTHONPATH:+:$PYTHONPATH}" "$PY" -m piper.train fit "${FIT_ARGS[@]}" +fi + +# --- stage 6: export --------------------------------------------------------- +if [[ "$SKIP_EXPORT" != "1" ]]; then + CKPT="$(find "$RUNS" -name '*.ckpt' -printf '%T@ %p\n' 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2- || true)" + if [[ -z "$CKPT" ]]; then + echo "no training checkpoint found under $RUNS — nothing to export" >&2 + exit 1 + fi + echo "== exporting $CKPT -> $OUT/$NAME.onnx" + PYTHONPATH="$COMPAT${PYTHONPATH:+:$PYTHONPATH}" "$PY" -m piper.train.export_onnx --checkpoint "$CKPT" --output-file "$OUT/$NAME.onnx" + if [[ ! -f "$OUT/$NAME.onnx.json" ]]; then + echo "WARN: $OUT/$NAME.onnx.json missing (config is written during training)" >&2 + fi +fi + +echo +echo "== done. voice files:" +ls -la "$OUT" 2>/dev/null || true +cat <:'/.runtime/voice/tts/' + +Then set in that host's config.json (gateway.voice.tts.voice_dir is anchored to +.runtime/voice/tts automatically): + + "tts": { "voice": "$NAME", ... } + +Restart the gateway and speak a reply to verify — a passing skill test is not +proof the integration works; only a real spoken reply is. +EOF diff --git a/scripts/voice-verify.py b/scripts/voice-verify.py new file mode 100755 index 0000000..4905267 --- /dev/null +++ b/scripts/voice-verify.py @@ -0,0 +1,241 @@ +#!/usr/bin/env python3 +"""Check a recorded Piper dataset against its prompts with Whisper. + +The recording front end (`scripts/voice-record.py`) resumes by prompt id and +trusts you to accept each take, so a silent false start or a take read from the +wrong line slips in silently. This verifier transcribes every `wavs/.wav` +with faster-whisper and compares it to the prompt recorded for that id in +`metadata.csv`, flagging the ones to re-record. + +Statuses: + +- ``missing`` — a metadata row whose wav is gone. +- ``empty`` — Whisper heard no speech (a silent / false-start take). +- ``mismatch`` — the transcript differs from the prompt by more than `--max-wer`. +- ``review`` — between `--review-wer` and `--max-wer`: listen, because + Whisper's own spelling/number variants land here (e.g. "two plus seven" -> + "2 plus 7"); not treated as a failure. +- ``ok`` — below `--review-wer`. + +Run it from the checkout with the voice stack installed: + + .runtime/venv/bin/python scripts/voice-verify.py --model small.en + .runtime/venv/bin/python scripts/voice-verify.py --json .runtime/voice-train/verify.json + # mark the flagged takes for re-recording (bad + review) from that report: + .runtime/venv/bin/python scripts/voice-verify.py \ + --from-json .runtime/voice-train/verify.json --prune --prune-review + +`--prune` moves each flagged wav into `/rejected/` and drops its +metadata row, so re-running the recorder re-records exactly those prompts; it is +off by default (run once and listen, or keep the `--json` report, first). +`--prune-review` also marks the `review` band. `--from-json` reuses a previous +report instead of transcribing again. Recordings are biometric — never commit +them. +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(REPO_ROOT)) +# The voice models live in the checkout's .runtime/hf cache (bootstrap sets this +# for the gateway); default it here so the verifier finds the cached Whisper +# model instead of downloading one into ~/.cache. +os.environ.setdefault("HF_HOME", str(REPO_ROOT / ".runtime" / "hf")) + +from semif_agent.voice_train import ( # noqa: E402 + BAD_STATUSES, + SAMPLE_RATE, + DatasetStore, + compare_transcript, + duration_s, + read_wav, + resample_pcm16, +) +from semif_agent.voice_transport import WhisperTranscriber # noqa: E402 + +#: faster-whisper's model input rate (the transcriber contract). +WHISPER_RATE = 16000 + + +def _parse_args(argv: list[str] | None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument( + "--dataset", default=str(REPO_ROOT / ".runtime" / "voice-train" / "dataset"), + help="LJSpeech dataset dir (metadata.csv + wavs/)", + ) + parser.add_argument("--model", default="base.en", + help="faster-whisper model size or path (default: base.en)") + parser.add_argument("--device", default="cpu", help="inference device (default: cpu)") + parser.add_argument("--compute-type", default="int8", + help="CTranslate2 compute type (default: int8)") + parser.add_argument("--language", default="en", help="spoken language (default: en)") + parser.add_argument("--beam-size", type=int, default=5, + help="Whisper beam size; higher is more accurate/slower (default: 5)") + parser.add_argument("--max-wer", type=float, default=0.5, + help="word error rate above which a take fails (default: 0.5)") + parser.add_argument("--review-wer", type=float, default=0.35, + help="word error rate at/above which a take is listed for " + "review but does not fail (default: 0.35)") + parser.add_argument("--limit", type=int, default=0, + help="verify at most N recordings (for a quick smoke test)") + parser.add_argument("--all", action="store_true", + help="print every recording, not just the flagged ones") + parser.add_argument("--json", dest="json_path", default="", + help="write the full report to this JSON file") + parser.add_argument("--prune", action="store_true", + help="move flagged wavs to /rejected/ and drop their rows") + parser.add_argument("--prune-review", action="store_true", + help="also prune the 'review' band (Whisper-variant candidates)") + parser.add_argument("--reject-dir", default="", + help="where --prune moves bad takes (default: /rejected)") + parser.add_argument("--from-json", default="", + help="reuse a previous --json report instead of transcribing again") + parser.add_argument("--quiet", action="store_true", + help="suppress the per-file progress and print only the summary") + return parser.parse_args(argv) + + +def _resample_to_whisper(pcm16: bytes, rate: int) -> bytes: + if rate == WHISPER_RATE: + return pcm16 + return resample_pcm16(pcm16, rate, WHISPER_RATE) + + +def _transcribe_dataset(store, ids, args) -> tuple[list[dict], float]: + """Transcribe each wav and compare it to its prompt.""" + transcriber = WhisperTranscriber( + model=args.model, + device=args.device, + compute_type=args.compute_type, + language=args.language, + beam_size=args.beam_size, + ) + report: list[dict] = [] + total_seconds = 0.0 + for index, uid in enumerate(ids, start=1): + reference = store.entries[uid] + wav = store.wav_path(uid) + result = {"id": uid, "reference": reference} + if not wav.is_file(): + result.update(compare_transcript(reference, "", args.max_wer, args.review_wer)) + result["status"] = "missing" + result["hypothesis"] = "" + result["seconds"] = 0.0 + else: + pcm16, rate = read_wav(wav) + seconds = duration_s(pcm16, rate) + total_seconds += seconds + hypothesis = transcriber.transcribe(_resample_to_whisper(pcm16, rate)) + result.update( + compare_transcript(reference, hypothesis, args.max_wer, args.review_wer) + ) + result["hypothesis"] = hypothesis + result["seconds"] = round(seconds, 2) + report.append(result) + if not args.quiet and sys.stderr.isatty() and index % 25 == 0: + print(f"\r {index}/{len(ids)} …", end="", file=sys.stderr) + if not args.quiet and sys.stderr.isatty(): + print("\r" + " " * 24 + "\r", end="", file=sys.stderr) + return report, total_seconds + + +def _prune(store, ids, reject_dir: Path) -> int: + """Move each id's wav aside and drop its metadata row; return how many moved.""" + reject_dir.mkdir(parents=True, exist_ok=True) + moved = 0 + for uid in ids: + src = store.wav_path(uid) + if src.is_file(): + src.replace(reject_dir / src.name) + moved += 1 + store.remove(uid) + return moved + + +def main(argv: list[str] | None = None) -> int: + args = _parse_args(argv) + store = DatasetStore(args.dataset, sample_rate=SAMPLE_RATE) + if store.count() == 0: + print(f"no dataset at {store.out} (metadata.csv is empty or missing)", file=sys.stderr) + print("record one first: python scripts/voice-record.py", file=sys.stderr) + return 2 + + if args.from_json: + payload = json.loads(Path(args.from_json).read_text(encoding="utf-8")) + report = payload.get("results", []) + counts = dict(payload.get("counts", {})) + bad = list(payload.get("bad_ids", [])) + review = list(payload.get("review_ids", [])) + total_seconds = sum(float(r.get("seconds", 0.0)) for r in report) + args.model = payload.get("model", args.model) + args.beam_size = payload.get("beam_size", args.beam_size) + else: + ids = sorted(store.entries) + if args.limit: + ids = ids[: args.limit] + report, total_seconds = _transcribe_dataset(store, ids, args) + counts = {} + bad, review = [], [] + for result in report: + counts[result["status"]] = counts.get(result["status"], 0) + 1 + if result["status"] in BAD_STATUSES: + bad.append(result["id"]) + elif result["status"] == "review": + review.append(result["id"]) + + if not args.quiet: + for result in report: + status = result["status"] + if args.all or status in BAD_STATUSES or status == "review": + print(f"{result['id']} {status:<8} wer={result['wer']:.2f} " + f"ref: {result['reference']}") + print(f" hyp: {result['hypothesis']!r}") + + prune_ids = list(bad) + (list(review) if args.prune_review else []) + if args.prune and prune_ids: + reject_dir = Path(args.reject_dir) if args.reject_dir else store.out / "rejected" + moved = _prune(store, prune_ids, reject_dir) + print(f"pruned {moved} take(s) to {reject_dir}; re-run the recorder to redo them") + + print( + f"\nchecked {len(report)} recording(s), {total_seconds / 60:.1f} min audio " + f"model={args.model} beam={args.beam_size} " + f"max-wer={args.max_wer} review-wer={args.review_wer}" + ) + order = ["ok", "review", "mismatch", "empty", "missing"] + print(" " + " ".join(f"{name}: {counts.get(name, 0)}" for name in order)) + if bad: + print(f" re-record {len(bad)}: {' '.join(bad)}") + else: + print(" no take failed the fidelity check.") + if review: + print(f" review (listen; likely Whisper variants) {len(review)}: {' '.join(review)}") + + if args.json_path: + payload = { + "dataset": str(store.out), + "model": args.model, + "beam_size": args.beam_size, + "max_wer": args.max_wer, + "review_wer": args.review_wer, + "counts": counts, + "bad_ids": bad, + "review_ids": review, + "results": report, + } + Path(args.json_path).write_text(json.dumps(payload, indent=2), encoding="utf-8") + print(f"report: {args.json_path}") + + return 1 if bad else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/semif_agent/voice_train.py b/semif_agent/voice_train.py new file mode 100644 index 0000000..c2ced97 --- /dev/null +++ b/semif_agent/voice_train.py @@ -0,0 +1,453 @@ +"""Recording helpers for a personal Piper TTS voice (training data only). + +This is the neutral, stdlib-only half of the voice-training pipeline: it turns a +list of prompts plus recorded audio into an **LJSpeech-format dataset** +(``metadata.csv`` + ``wavs/NNNN.wav``) that ``piper.train fit`` consumes, and it +provides the mic-check level math and the silence-endpointing loop. It knows +nothing about the voice gateway's runtime (`semif_agent.voice_transport`) or +about the training host. + +Heavy deps stay lazy: numpy is imported only inside `resample_pcm16`, so +importing this module is safe on a machine without the optional voice stack. +`scripts/voice-record.py` is the thin CLI front end; the real capture path +reuses `voice_transport.SoundDeviceAudio` (which resamples the device's native +rate down to the target 22050 Hz for us). + +Audio is mono signed 16-bit little-endian PCM throughout. + +Dataset format note: piper's loader reads column 1 as the audio filename (looked +up under its ``--data.audio_dir``) and the **last** column as the text, so a row +is ``0001.wav|`` and the wavs live in ``wavs/``. +""" + +from __future__ import annotations + +import math +import re +import time +import wave +from pathlib import Path +from typing import Callable + +#: The sample rate the recorder targets (Piper "medium" quality). +SAMPLE_RATE = 22050 +BYTES_PER_SAMPLE = 2 + +#: Endpointing defaults (see `record_until_silence`). +DEFAULT_SILENCE_MS = 800 +DEFAULT_MIN_SPEECH_MS = 150 +DEFAULT_MAX_SECONDS = 15.0 +#: int16 RMS above which a frame counts as speech (the energy VAD threshold). +SPEECH_RMS_THRESHOLD = 200.0 + +#: An `is_speech(pcm16, sample_rate) -> bool` predicate (injected in tests). +SpeechPredicate = Callable[[bytes, int], bool] + + +# --------------------------------------------------------------------------- # +# prompts +# --------------------------------------------------------------------------- # + + +def load_prompts(path: str | Path) -> list[str]: + """Read one prompt per line; skip blanks and ``#`` comments.""" + lines: list[str] = [] + for raw in Path(path).read_text(encoding="utf-8").splitlines(): + line = raw.strip() + if line and not line.startswith("#"): + lines.append(line) + return lines + + +# --------------------------------------------------------------------------- # +# wav io (stdlib `wave`) +# --------------------------------------------------------------------------- # + + +def write_wav(path: str | Path, pcm16: bytes, sample_rate: int = SAMPLE_RATE) -> None: + """Write mono 16-bit PCM as a WAV file (creating parent dirs).""" + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + with wave.open(str(target), "wb") as handle: + handle.setnchannels(1) + handle.setsampwidth(BYTES_PER_SAMPLE) + handle.setframerate(int(sample_rate)) + handle.writeframes(pcm16) + + +def read_wav(path: str | Path) -> tuple[bytes, int]: + """Read a WAV file back as ``(pcm16, sample_rate)``.""" + with wave.open(str(path), "rb") as handle: + return handle.readframes(handle.getnframes()), handle.getframerate() + + +def resample_pcm16(pcm16: bytes, source_rate: int, target_rate: int) -> bytes: + """Linear-interpolate int16 PCM from `source_rate` to `target_rate`. + + numpy is a voice-stack dependency and this is only reached by the real + capture path, so the module stays stdlib-only on import. + """ + if source_rate == target_rate or not pcm16: + return pcm16 + import numpy as np + + source = np.frombuffer(pcm16, dtype=np.int16).astype(np.float32) + count = int(round(len(source) * target_rate / source_rate)) + if count <= 0: + return b"" + positions = np.linspace(0.0, len(source) - 1, count) + resampled = np.interp(positions, np.arange(len(source)), source) + return np.clip(resampled, -32768, 32767).astype(np.int16).tobytes() + + +# --------------------------------------------------------------------------- # +# levels (mic check) +# --------------------------------------------------------------------------- # + + +def _samples(pcm16: bytes): + """Yield int16 sample values from little-endian PCM.""" + for offset in range(0, len(pcm16) - BYTES_PER_SAMPLE + 1, BYTES_PER_SAMPLE): + yield int.from_bytes( + pcm16[offset : offset + BYTES_PER_SAMPLE], "little", signed=True + ) + + +def rms_int16(pcm16: bytes) -> float: + """Root-mean-square level of int16 PCM (0.0 for empty input).""" + count = len(pcm16) // BYTES_PER_SAMPLE + if count == 0: + return 0.0 + total = sum(sample * sample for sample in _samples(pcm16)) + return math.sqrt(total / count) + + +def peak_int16(pcm16: bytes) -> int: + """Peak absolute sample value of int16 PCM.""" + return max((abs(sample) for sample in _samples(pcm16)), default=0) + + +def duration_s(pcm16: bytes, sample_rate: int = SAMPLE_RATE) -> float: + """Playback duration of int16 PCM in seconds.""" + if sample_rate <= 0: + return 0.0 + return (len(pcm16) // BYTES_PER_SAMPLE) / float(sample_rate) + + +def level_report(pcm16: bytes, sample_rate: int = SAMPLE_RATE) -> dict: + """Mic-check summary: RMS, peak, dBFS, and duration.""" + peak = peak_int16(pcm16) + rms = rms_int16(pcm16) + peak_dbfs = 20.0 * math.log10(peak / 32768.0) if peak > 0 else float("-inf") + return { + "rms": round(rms, 1), + "peak": peak, + "peak_dbfs": None if peak <= 0 else round(peak_dbfs, 1), + "seconds": round(duration_s(pcm16, sample_rate), 2), + } + + +# --------------------------------------------------------------------------- # +# capture loops +# --------------------------------------------------------------------------- # + + +def _read_frame(audio, timeout: float | None): + """Read one frame, passing a `timeout` only if the source supports it. + + The real `SoundDeviceAudio.read(timeout=...)` returns `None` on a stall so a + dropped device cannot hang the loop; test doubles take no argument. + """ + if timeout is None: + return audio.read() + try: + return audio.read(timeout) + except TypeError: + return audio.read() + + +def _default_is_speech(threshold: float) -> SpeechPredicate: + def is_speech(pcm16: bytes, sample_rate: int) -> bool: + return rms_int16(pcm16) >= threshold + + return is_speech + + +def record_for( + audio, + *, + sample_rate: int = SAMPLE_RATE, + frame_ms: int = 40, + seconds: float = 5.0, + read_timeout: float | None = None, + clock: Callable[[], float] = time.monotonic, + on_frame: Callable[[int, float], None] | None = None, +) -> bytes: + """Read frames for `seconds` regardless of content (the mic check). + + `audio` is any object with a blocking ``read() -> bytes | None`` (the + `voice_transport.AudioIO` contract); a ``None`` frame ends capture early. + `read_timeout` bounds each read so a stalled device ends capture instead of + blocking forever. + """ + frames: list[bytes] = [] + started = clock() + while True: + pcm = _read_frame(audio, read_timeout) + if pcm is None: + break + frames.append(pcm) + if on_frame is not None: + on_frame(len(frames), clock() - started) + if seconds > 0 and (clock() - started) >= seconds: + break + return b"".join(frames) + + +def record_until_silence( + audio, + *, + sample_rate: int = SAMPLE_RATE, + frame_ms: int = 40, + max_seconds: float = DEFAULT_MAX_SECONDS, + silence_ms: int = DEFAULT_SILENCE_MS, + min_speech_ms: int = DEFAULT_MIN_SPEECH_MS, + threshold: float = SPEECH_RMS_THRESHOLD, + is_speech: SpeechPredicate | None = None, + read_timeout: float | None = None, + clock: Callable[[], float] = time.monotonic, + on_frame: Callable[[int, int], None] | None = None, +) -> bytes: + """Accumulate frames until trailing silence or `max_seconds`. + + Returns the captured PCM, or ``b""`` when less than `min_speech_ms` of + speech was heard (a false start / silence). `is_speech` defaults to an int16 + RMS threshold; tests inject a scripted predicate. `read_timeout` bounds each + read so a stalled/dropped device ends the take instead of hanging. + """ + predicate = is_speech or _default_is_speech(threshold) + frames: list[bytes] = [] + speech_ms = 0 + trailing_silence_ms = 0 + started = clock() + while True: + pcm = _read_frame(audio, read_timeout) + if pcm is None: + break + frames.append(pcm) + if predicate(pcm, sample_rate): + speech_ms += frame_ms + trailing_silence_ms = 0 + else: + trailing_silence_ms += frame_ms + if on_frame is not None: + on_frame(speech_ms, trailing_silence_ms) + if speech_ms >= min_speech_ms and trailing_silence_ms >= silence_ms: + break + if max_seconds > 0 and (clock() - started) >= max_seconds: + break + if speech_ms < min_speech_ms: + return b"" + return b"".join(frames) + + +# --------------------------------------------------------------------------- # +# dataset on disk +# --------------------------------------------------------------------------- # + + +class DatasetStore: + """An LJSpeech-format dataset directory: ``metadata.csv`` + ``wavs/``. + + Survives across runs (the recorder resumes where it left off): the existing + ``metadata.csv`` is parsed on construction and rewritten (sorted by id) + after every save. + """ + + def __init__(self, out_dir: str | Path, sample_rate: int = SAMPLE_RATE): + self.out = Path(out_dir) + self.sample_rate = int(sample_rate) + self.wavs = self.out / "wavs" + self.metadata = self.out / "metadata.csv" + self._entries: dict[str, str] = {} + self._load() + + # ---- loading ---- + + def _load(self) -> None: + if not self.metadata.is_file(): + return + for raw in self.metadata.read_text(encoding="utf-8").splitlines(): + if "|" not in raw: + continue + uid, text = raw.split("|", 1) + uid = uid.strip() + if uid.endswith(".wav"): + uid = uid[:-4] # metadata stores the filename; ids stay bare + if uid: + self._entries[uid] = text.strip() + + # ---- queries ---- + + @property + def entries(self) -> dict[str, str]: + return dict(self._entries) + + def ids(self) -> set[str]: + return set(self._entries) + + def count(self) -> int: + return len(self._entries) + + def next_id(self) -> str: + """The lowest zero-padded 4-digit id not yet recorded.""" + index = 1 + while f"{index:04d}" in self._entries: + index += 1 + return f"{index:04d}" + + def wav_path(self, uid: str) -> Path: + return self.wavs / f"{uid}.wav" + + # ---- mutation ---- + + def save(self, uid: str, text: str, pcm16: bytes) -> Path: + """Write ``wavs/.wav`` and record ``.wav|``.""" + uid = str(uid) + path = self.wav_path(uid) + write_wav(path, pcm16, self.sample_rate) + self._entries[uid] = text.strip() + self.rewrite() + return path + + def remove(self, uid: str) -> bool: + """Drop a recording: delete ``wavs/.wav`` and its metadata row. + + Returns whether the id was present. Used by the verifier's ``--prune`` to + take a bad take out of the dataset so the recorder re-records it (the + recorder resumes by id). The caller may move the wav aside first; the + unlink here tolerates it already being gone. + """ + uid = str(uid) + if uid not in self._entries: + return False + try: + self.wav_path(uid).unlink() + except FileNotFoundError: + pass + del self._entries[uid] + self.rewrite() + return True + + def rewrite(self) -> None: + self.out.mkdir(parents=True, exist_ok=True) + lines = [f"{uid}.wav|{self._entries[uid]}" for uid in sorted(self._entries)] + self.metadata.write_text( + "\n".join(lines) + ("\n" if lines else ""), encoding="utf-8" + ) + + +# --------------------------------------------------------------------------- # +# fidelity check (transcript vs. prompt) +# --------------------------------------------------------------------------- # + +#: Statuses the verifier flags as needing a re-record. +BAD_STATUSES = frozenset({"missing", "empty", "mismatch"}) + +_WORD_RE = re.compile(r"[a-z0-9]+(?:'[a-z]+)?") + +#: Number words -> digits, so Whisper's "2 plus 7 is less than 10" matches a +#: prompt that spells them out. Comparison-only; never used for output. +_NUMBER_WORDS = { + "zero": "0", "one": "1", "two": "2", "three": "3", "four": "4", + "five": "5", "six": "6", "seven": "7", "eight": "8", "nine": "9", + "ten": "10", "eleven": "11", "twelve": "12", "thirteen": "13", + "fourteen": "14", "fifteen": "15", "sixteen": "16", "seventeen": "17", + "eighteen": "18", "nineteen": "19", "twenty": "20", "thirty": "30", + "forty": "40", "fifty": "50", "sixty": "60", "seventy": "70", + "eighty": "80", "ninety": "90", +} + + +def normalize_text(text: str) -> str: + """Lowercase, strip punctuation, collapse whitespace, digitize number words. + + Whisper's output differs from the prompt in capitalization, punctuation, + spacing, and (for numbers) digits-vs-words; this reduces both to a comparable + word sequence. Apostrophes are kept so ``it's`` does not silently become + ``its``. + """ + words = _WORD_RE.findall(text.lower()) + return " ".join(_NUMBER_WORDS.get(word, word) for word in words) + + +def word_tokens(text: str) -> list[str]: + """The normalized word sequence of `text`.""" + return normalize_text(text).split() + + +def word_error_rate(reference: str, hypothesis: str) -> float: + """Word-level Levenshtein distance divided by the reference word count. + + 0.0 is an exact match; 1.0 means every reference word was wrong (or the + hypothesis was empty). An empty reference scores 0.0 for an empty + hypothesis, else 1.0. + """ + ref = word_tokens(reference) + hyp = word_tokens(hypothesis) + if not ref: + return 0.0 if not hyp else 1.0 + previous = list(range(len(hyp) + 1)) + for i, ref_word in enumerate(ref, start=1): + current = [i] + for j, hyp_word in enumerate(hyp, start=1): + substitution = previous[j - 1] + (0 if ref_word == hyp_word else 1) + current.append(min(previous[j] + 1, current[j - 1] + 1, substitution)) + previous = current + return previous[-1] / len(ref) + + +def compare_transcript( + reference: str, + hypothesis: str, + max_wer: float = 0.3, + review_wer: float | None = None, +) -> dict: + """Classify a Whisper transcript against the prompt it was read from. + + Returns ``{"status", "wer", "similarity", "ref_words", "hyp_words"}`` where + status is one of: + + - ``empty`` — Whisper heard nothing (a silent / false-start take); + - ``mismatch`` — word error rate above `max_wer` (a wrong or truncated take); + - ``review`` — between `review_wer` and `max_wer`: worth a listen, because + Whisper's own spelling/number variants live in this band (e.g. "two plus + seven" -> "2 plus 7"); + - ``ok`` — below `review_wer` (or below `max_wer` when no review band). + + `similarity` is ``1 - min(wer, 1)``, a friendlier 0..1 score. + """ + ref = word_tokens(reference) + hyp = word_tokens(hypothesis) + if not hyp: + return { + "status": "empty", + "wer": 1.0, + "similarity": 0.0, + "ref_words": len(ref), + "hyp_words": 0, + } + wer = word_error_rate(reference, hypothesis) + if wer > max_wer: + status = "mismatch" + elif review_wer is not None and wer >= review_wer: + status = "review" + else: + status = "ok" + return { + "status": status, + "wer": round(wer, 3), + "similarity": round(max(0.0, 1.0 - min(wer, 1.0)), 3), + "ref_words": len(ref), + "hyp_words": len(hyp), + } diff --git a/semif_agent/voice_transport.py b/semif_agent/voice_transport.py index 65ae642..afc2498 100644 --- a/semif_agent/voice_transport.py +++ b/semif_agent/voice_transport.py @@ -226,10 +226,14 @@ class WhisperTranscriber(Transcriber): device: str = "cpu", compute_type: str = "int8", language: str = "en", + beam_size: int = 1, + vad_filter: bool = True, ): from faster_whisper import WhisperModel self.language = str(language or "en") or None + self.beam_size = int(beam_size) + self.vad_filter = bool(vad_filter) self._model = WhisperModel(str(model or "base.en"), device=str(device or "cpu"), compute_type=str(compute_type or "int8")) @@ -240,8 +244,8 @@ class WhisperTranscriber(Transcriber): segments, _info = self._model.transcribe( audio, language=self.language, - beam_size=1, - vad_filter=True, + beam_size=self.beam_size, + vad_filter=self.vad_filter, ) return " ".join(segment.text.strip() for segment in segments).strip() @@ -435,8 +439,19 @@ class SoundDeviceAudio(AudioIO): except queue.Full: pass # a slow consumer (STT) drops stale frames; the mic is real-time - def read(self) -> bytes | None: - return self._frames.get() + def read(self, timeout: float | None = None) -> bytes | None: + """Block for the next frame (or up to `timeout` seconds). + + Returns `None` once the input is closed, or on a `timeout` with no + frame — a caller that passes a timeout can detect a stalled stream + instead of blocking forever. + """ + if timeout is None: + return self._frames.get() + try: + return self._frames.get(timeout=timeout) + except queue.Empty: + return None def open_output(self, sample_rate: int, device: str = "") -> None: pass # a raw stream is opened per utterance in `write` diff --git a/tests/test_voice_record.py b/tests/test_voice_record.py new file mode 100644 index 0000000..71ee2f9 --- /dev/null +++ b/tests/test_voice_record.py @@ -0,0 +1,309 @@ +"""Pure-stdlib tests for the voice-recording helpers (`semif_agent.voice_train`). + +The recording front end (`scripts/voice-record.py`) drives real hardware; these +tests exercise the neutral helpers it builds on — prompt loading, WAV I/O, level +math, the endpointing loop, and the LJSpeech dataset writer — with a scripted +fake audio source, so no microphone, numpy, or sounddevice is required. +""" + +import itertools + +from semif_agent.voice_train import ( + DatasetStore, + compare_transcript, + duration_s, + level_report, + load_prompts, + normalize_text, + peak_int16, + read_wav, + record_for, + record_until_silence, + resample_pcm16, + rms_int16, + word_error_rate, + word_tokens, + write_wav, +) + + +class FakeAudio: + """A scripted `AudioIO`: `read()` pops frames, then returns None.""" + + def __init__(self, frames): + self.frames = list(frames) + + def read(self): + return self.frames.pop(0) if self.frames else None + + +def _pcm(*values): + return b"".join(int(v).to_bytes(2, "little", signed=True) for v in values) + + +# ---- prompts --------------------------------------------------------------- + + +def test_load_prompts_skips_comments_and_blanks(tmp_path): + path = tmp_path / "prompts.txt" + path.write_text("# a comment\n\nHello there.\n \nSecond line.\n", encoding="utf-8") + assert load_prompts(path) == ["Hello there.", "Second line."] + + +def test_load_prompts_missing_file_raises(tmp_path): + import pytest + + with pytest.raises(FileNotFoundError): + load_prompts(tmp_path / "nope.txt") + + +# ---- wav io ---------------------------------------------------------------- + + +def test_wav_roundtrip(tmp_path): + pcm = _pcm(0, 100, -100, 32767, -32768) + path = tmp_path / "nested" / "clip.wav" + write_wav(path, pcm, 22050) + assert path.is_file() + got, rate = read_wav(path) + assert got == pcm + assert rate == 22050 + + +# ---- levels ---------------------------------------------------------------- + + +def test_rms_peak_duration(): + pcm = _pcm(3, 4) # rms = sqrt((9+16)/2) = 3.535..., peak 4 + assert abs(rms_int16(pcm) - 3.5355) < 1e-3 + assert peak_int16(pcm) == 4 + assert duration_s(_pcm(*([0] * 22050)), 22050) == 1.0 + + +def test_levels_empty(): + assert rms_int16(b"") == 0.0 + assert peak_int16(b"") == 0 + assert duration_s(b"", 22050) == 0.0 + assert level_report(b"")["peak_dbfs"] is None + + +def test_level_report_dbfs(): + report = level_report(_pcm(32767), 22050) + assert report["peak"] == 32767 + assert report["peak_dbfs"] == 0.0 + assert report["seconds"] == 0.0 + + +# ---- resampling ------------------------------------------------------------ + + +def test_resample_pcm16(): + import pytest + + np = pytest.importorskip("numpy") + pcm = np.arange(441, dtype=np.int16).tobytes() + assert len(resample_pcm16(pcm, 44100, 16000)) // 2 == 160 + assert resample_pcm16(pcm, 44100, 44100) == pcm + assert resample_pcm16(b"", 44100, 16000) == b"" + + +# ---- endpointing ----------------------------------------------------------- + + +def test_record_until_silence_stops_on_trailing_silence(): + frames = [b"s"] * 5 + [b"_"] * 25 + audio = FakeAudio(frames) + got = record_until_silence( + audio, + frame_ms=40, + silence_ms=800, # 20 silent frames + min_speech_ms=150, # 4 speech frames + is_speech=lambda pcm, rate: pcm == b"s", + ) + assert got == b"".join(frames[:25]) # 5 speech + 20 trailing silence + + +def test_record_until_silence_rejects_all_silence(): + audio = FakeAudio([b"_"] * 30) + got = record_until_silence( + audio, frame_ms=40, min_speech_ms=150, is_speech=lambda pcm, rate: False + ) + assert got == b"" + + +def test_record_until_silence_max_seconds_caps(): + ticks = iter([0.0, 0.0, 1.0, 1.0, 1.0]) + audio = FakeAudio([b"s"] * 5) + got = record_until_silence( + audio, + frame_ms=40, + max_seconds=1.0, + min_speech_ms=0, + is_speech=lambda pcm, rate: True, + clock=lambda: next(ticks), + ) + assert got == b"ss" # stopped after the second frame when elapsed hit 1.0 + + +def test_record_for_reads_until_clock_or_end(): + ticks = iter([0.0, 0.0, 1.0, 1.0]) + audio = FakeAudio([b"a", b"b", b"c", b"d"]) + assert record_for(audio, seconds=1.0, clock=lambda: next(ticks)) == b"ab" + + +def test_record_until_silence_returns_on_none_frame(): + audio = FakeAudio([b"s"]) # only one frame, then None + got = record_until_silence( + audio, frame_ms=40, min_speech_ms=0, is_speech=lambda pcm, rate: True + ) + assert got == b"s" + + +def test_record_until_silence_passes_read_timeout(): + # A source that supports `read(timeout=...)` receives the timeout, so a + # stalled device returns None and ends the take instead of hanging. + class TimeoutAudio: + def __init__(self, frames): + self.frames = list(frames) + self.saw_timeout = False + + def read(self, timeout=None): + self.saw_timeout = timeout is not None + return self.frames.pop(0) if self.frames else None + + audio = TimeoutAudio([b"s"]) + got = record_until_silence( + audio, + frame_ms=40, + min_speech_ms=0, + is_speech=lambda pcm, rate: True, + read_timeout=2.0, + ) + assert got == b"s" + assert audio.saw_timeout is True + + +def test_record_for_passes_read_timeout(): + class TimeoutAudio: + def __init__(self, frames): + self.frames = list(frames) + self.saw_timeout = False + + def read(self, timeout=None): + self.saw_timeout = timeout is not None + return self.frames.pop(0) if self.frames else None + + audio = TimeoutAudio([b"a", b"b"]) + assert record_for(audio, seconds=0.001, read_timeout=1.5) == b"ab" + assert audio.saw_timeout is True + + +# ---- dataset store --------------------------------------------------------- + + +def test_dataset_store_save_and_reload(tmp_path): + store = DatasetStore(tmp_path / "ds", sample_rate=22050) + assert store.count() == 0 + assert store.next_id() == "0001" + + store.save("0001", "Hello there.", _pcm(1, 2, 3)) + assert (tmp_path / "ds" / "wavs" / "0001.wav").is_file() + assert store.next_id() == "0002" + + # metadata uses the piper loader's `filename|text` shape. + lines = (tmp_path / "ds" / "metadata.csv").read_text().splitlines() + assert lines == ["0001.wav|Hello there."] + + # A fresh store resumes from disk. + resumed = DatasetStore(tmp_path / "ds", sample_rate=22050) + assert resumed.ids() == {"0001"} + assert resumed.entries == {"0001": "Hello there."} + + +def test_dataset_store_rewrite_sorted(tmp_path): + store = DatasetStore(tmp_path / "ds") + store.save("0002", "second", _pcm(0)) + store.save("0001", "first", _pcm(0)) + lines = (tmp_path / "ds" / "metadata.csv").read_text().splitlines() + assert lines == ["0001.wav|first", "0002.wav|second"] + + +def test_dataset_store_next_id_fills_gaps(tmp_path): + store = DatasetStore(tmp_path / "ds") + store.save("0001", "a", _pcm(0)) + store.save("0003", "c", _pcm(0)) + assert store.next_id() == "0002" + + +def test_dataset_store_remove_drops_wav_and_row(tmp_path): + store = DatasetStore(tmp_path / "ds") + store.save("0001", "first", _pcm(0)) + store.save("0002", "second", _pcm(0)) + assert store.remove("0001") is True + assert not (tmp_path / "ds" / "wavs" / "0001.wav").exists() + assert store.ids() == {"0002"} + assert (tmp_path / "ds" / "metadata.csv").read_text().splitlines() == ["0002.wav|second"] + assert store.remove("9999") is False + + +def test_dataset_store_remove_tolerates_missing_wav(tmp_path): + store = DatasetStore(tmp_path / "ds") + store.save("0001", "first", _pcm(0)) + (tmp_path / "ds" / "wavs" / "0001.wav").unlink() + assert store.remove("0001") is True + assert store.ids() == set() + + +# ---- transcript fidelity --------------------------------------------------- + + +def test_normalize_text_strips_punctuation_and_case(): + assert normalize_text(" The birch canoe, slid! ") == "the birch canoe slid" + assert normalize_text("It's easy.") == "it's easy" + assert normalize_text("") == "" + assert word_tokens("Well-done, yes?") == ["well", "done", "yes"] + + +def test_normalize_text_digitizes_number_words(): + assert normalize_text("Two plus seven is less than ten.") == "2 plus 7 is less than 10" + assert normalize_text("2 plus 7 is less than 10") == "2 plus 7 is less than 10" + assert word_error_rate("Two plus seven is less than ten.", "2 plus 7 is less than 10") == 0.0 + + +def test_word_error_rate(): + assert word_error_rate("the hog crawled under", "the hog crawled under") == 0.0 + assert word_error_rate("the hog crawled under", "the dog crawled under") == 0.25 + assert word_error_rate("the hog crawled under", "") == 1.0 + assert word_error_rate("", "") == 0.0 + assert word_error_rate("", "extra") == 1.0 + + +def test_compare_transcript_statuses(): + ref = "The hog crawled under the high fence." + assert compare_transcript(ref, "The hog crawled under the high fence.")["status"] == "ok" + # A near-miss within the tolerance still passes. + assert compare_transcript(ref, "the hog crawled under the high fence")["status"] == "ok" + empty = compare_transcript(ref, "") + assert empty["status"] == "empty" + assert empty["similarity"] == 0.0 + mismatch = compare_transcript(ref, "The whole Craig under the high sense.") + assert mismatch["status"] == "mismatch" + assert mismatch["wer"] > 0.3 + assert 0.0 <= mismatch["similarity"] < 1.0 + + +def test_compare_transcript_review_band(): + ref = "The junk yard had a mouldy smell." + # A spelling/spacing variant sits in the review band, not a failure. + got = compare_transcript( + ref, "The junkyard had a moldy smell.", max_wer=0.5, review_wer=0.35 + ) + assert got["status"] == "review" + # Without a review band the same take is ok. + assert compare_transcript( + ref, "The junkyard had a moldy smell.", max_wer=0.5 + )["status"] == "ok" + # Above max_wer it is a mismatch regardless of the review band. + assert compare_transcript( + ref, "The junkyard smell.", max_wer=0.5, review_wer=0.35 + )["status"] == "mismatch"