voice: add custom Piper voice training pipeline
Record an LJSpeech dataset from the microphone, fine-tune a Piper voice from the pinned base checkpoint on a GPU host, and verify every take against its prompt with Whisper before training. - semif_agent/voice_train.py: neutral, stdlib-only recording helpers (LJSpeech dataset writer, prompt loading, WAV I/O, mic-check level math, silence-endpointing capture loop) plus transcript-fidelity helpers (normalize_text, word_error_rate, compare_transcript). - scripts/voice-record.py: interactive + hands-free (--speak-prompts / --read-prompts) recording; resumes by prompt id and announces how many of the 720 prompts remain, so a resume is never mistaken for a rerun. - scripts/voice-train.sh: piper1-gpl checkout + venv, warmstart fine-tune of the pinned medium checkpoint, ONNX export. Handles torch>=2.6 weights_only (PosixPath allowlist), the older checkpoint's hyperparameters (--model.warmstart_ckpt, not --ckpt_path), the espeakbridge in-place dev build, and piper's validation/test splits (needed for the default checkpoint callbacks). - scripts/voice-verify.py: transcribe-and-compare fidelity check (empty/mismatch/review/ok), --json report, --from-json + --prune to mark bad takes for re-recording without deleting them. - pins.json: voice block (piper1-gpl ref + medium base checkpoint). - voice_transport.py: WhisperTranscriber beam_size/vad_filter knobs; SoundDeviceAudio.read(timeout=) so a dropped device ends a take instead of hanging. - AGENTS.md: architecture map + roadmap entries; docs/VOICE-TRAIN.md the end-to-end guide; tests/test_voice_record.py the helper tests.
This commit is contained in:
1 parent
aa25693091
commit
b7d405454a
10 files changed
+2778
-6
No files matched your search
@@ -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.
|
||||
Executable
+410
@@ -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 <path>")
|
||||
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())
|
||||
Executable
+345
@@ -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 <name>.onnx + <name>.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 <<EOF
|
||||
|
||||
Next: copy the voice to a gateway host and select it.
|
||||
|
||||
rsync -av '$OUT/$NAME.onnx' '$OUT/$NAME.onnx.json' \\
|
||||
<gateway-host>:'<checkout>/.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
|
||||
Executable
+241
@@ -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/<id>.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 `<dataset>/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 <dataset>/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: <dataset>/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())
|
||||
Reference in new issue
Block a user