tts-director
Direct a script for text-to-speech so it sounds like a real, engaged human, not a narrator reading. Persian (Farsi) first, English supported. It rewrites the text for the ear, maps the beats of a short-form video (reel, TikTok, Short), and adds ElevenLabs v3/v4 audio tags only where they earn their place ([excited], [whispers], [laughs], [chuckles], [gasps], [sighs], [sarcastic]...). It checks for over-tagging with a free linter and A/B-tests risky lines on the real voice before a full run. It also covers model rules (eleven_v4 ignores speed and style; multilingual_v2, flash and turbo read tags aloud) and converts the result for other TTS engines (OpenAI, Azure, Google). Use for ANY script headed to ElevenLabs or another TTS, and whenever someone wants a voice that is more exciting, emotional, expressive, human or viral, or asks about tone, emotion, laughter, pauses or pacing in TTS: «لحن»، «احساس»، «هیجان»، «خنده»، «تگ»، «انسانیتر»، «گوینده»، «صداگذاری».
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/aligh98--tts-director)HTML
<a href="/listings/aligh98--tts-director"><img src="/api/listings/aligh98--tts-director/badge.svg" alt="findsafeskills safety rating" /></a>Install
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 185 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- ---
- name: tts-director
- description: Direct a script for text-to-speech so it sounds like a real, engaged human, not a narrator reading. Persian (Farsi) first, English supported. It rewrites the text for the ear, maps the beats of a short-form video (reel, TikTok, Short), and adds ElevenLabs v3/v4 audio tags only where they earn their place ([excited], [whispers], [laughs], [chuckles], [gasps], [sighs], [sarcastic]...). It checks for over-tagging with a free linter and A/B-tests risky lines on the real voice before a full run. It also covers model rules (eleven_v4 ignores speed and style; multilingual_v2, flash and turbo read tags aloud) and converts the result for other TTS engines (OpenAI, Azure, Google). Use for ANY script headed to ElevenLabs or another TTS, and whenever someone wants a voice that is more exciting, emotional, expressive, human or viral, or asks about tone, emotion, laughter, pauses or pacing in TTS: «لحن»، «احساس»، «هیجان»، «خنده»، «تگ»، «انسانیتر»، «گوینده»، «صداگذاری».
- ---
- # TTS director: write for the ear, tag the beats, test by ear
- A great voiceover is about 80% text and 20% tags. The text sets the rhythm, the register and where the energy goes. Tags only push a delivery the text has already set up. A script with a tag on every line sounds like an over-acted ad and loses the viewer. A script with none often sounds read.
- This skill does not replace your TTS pipeline. It prepares the text that goes into it. Scripts are stdlib Python 3.9+; ffmpeg/ffprobe are optional and give durations.
- ## Workflow
- Do the steps in order. The tools check them, so none can be skipped silently:
- - `tag_lint.py` gives an ERROR when a line has no beat label;
- - `tag_lint.py --check-approved` fails until the person has approved the exact text. Gate your TTS call on it.
- Before step 1, read the delivery reference for the script's language (`references/persian-delivery.md` or `references/english-delivery.md`) and `references/audio-tags.md`. The linter checks only part of them.
- 1. **Beat map, inside the script.** End every spoken line with « # ROLE ENERGY» (energy 1–5):
- ```
- [excited] Wait, this ends Friday... and it's not coming back! # HOOK 5
- [whispers] Here's the trick... # TIP 2
- ```
- The roles are:
- - HOOK
- - SETUP
- - REVEAL
- - ITEM (a list point)
- - TIP (insider advice)
- - JOKE or IRONY
- - WARNING
- - CTA
- Plan the arc before touching words. See [Viral arc](#viral-arc). Strip the labels before the text goes to the TTS: `tag_lint.strip_beats(text)` does it, or remove everything from « #» to the end of each line. For a script that is not a short-form video, pass `--no-beats`.
- 2. **Rewrite for the ear.** Keep the meaning and every fact. Rewriting means:
- - shorter sentences;
- - the punch word moved to the end;
- - the interjections a native speaker would actually use;
- - punctuation that marks breaths.
- For Persian, follow the **alef rule** in `persian-delivery.md`: the voice reads every «ا» as a long «آ», and a short /a/ is a fatha only. Some words are spelled unlike they sound («بالاخره»، «حتی»، «فوقالعاده»; see `references/fa-traps.tsv`). Treat a respelling as a guess until a human confirms it by ear; mark confirmed rows in your lexicon with a note that starts with «✓».
- 3. **Tag pass.** Tag only the beats the text alone cannot carry, within the [Tag budget](#tag-budget). For tag names and what each one is for, see `references/audio-tags.md`.
- 4. **Lint (free):**
- ```
- python scripts/tag_lint.py SCRIPT --model eleven_v4 --tempo 1.15 [--lexicon words.tsv] [--ab-budget 160]
- ```
- It prints the beat map with estimated times, then checks:
- - **Beats and arc:**
- - a missing or invalid label (ERROR);
- - a first line that is not a HOOK at energy 4–5 (ERROR);
- - a TIP above energy 3;
- - a flat arc;
- - more than 14 s without a change of delivery;
- - a low tag on a high beat, or a high tag on a low beat;
- - a whisper or sigh not followed by a line that lifts the energy.
- - **Tags:**
- - over-tagging;
- - laughs that are too many or too close together;
- - a repeated tag;
- - staging tags;
- - SSML on v3/v4, and tags on models that read them aloud.
- - **Ear rewrite:**
- - written register («را»، «است»، «میشود»; uncontracted English);
- - fewer than 2 interjections, or a repeated one;
- - «!» on every line, and too many ellipses;
- - long sentences;
- - written laughter («هاها», "haha");
- - stretched letters;
- - an opening greeting.
- - **Persian readings:**
- - unconfirmed respellings that change the number of «ا/آ»;
- - `{written|spoken}` overrides that do the same;
- - trap words;
- - tanwin.
- Fix every ERROR. Keep a WARN only when you can say why. The **A/B PLAN** at the end lists the lines to test, in priority order, with their cost; see [A/B priority](#ab-priority).
- 5. **Approval.** Show the person the full text with its beat map and the A/B plan. Generating audio costs them credits, and the wording is theirs to approve. After their OK:
- ```
- python scripts/tag_lint.py SCRIPT --approve
- ```
- This writes `SCRIPT.approved.json`, the SHA-256 of the stripped file text. `--approve` refuses while there is an ERROR. Before every TTS call, run `tag_lint.py SCRIPT --check-approved`: exit 0 means approved, exit 3 means no stamp or a changed text. Any edit needs a new OK. A pipeline can also compare the hash itself: `sha256(file_text.strip())`. Choosing an A/B take does not approve the whole text.
- 6. **A/B the risky lines** in the A/B plan's order. Check the cost first; `--dry-run` sends nothing:
- ```
- python scripts/ab.py "VARIANT A" "VARIANT B" --voice VOICE_ID --stability 0.35 --stability 0.5 --prev "line before" --next "line after" --out probe/ab --dry-run
- ```
- Remove `--dry-run` to generate. Every clip uses the same `--seed`, so the differences come from the text and the settings, not from chance. Each clip is transcribed:
- - `LEAK` means a tag was read aloud as a word. Drop or rephrase that tag.
- - An event such as `[laughter]` or `[خنده]` means the sound was performed.
- - `LISTEN FOR` (Persian) names the words whose reading is unconfirmed.
- Speech-to-text cannot judge excitement or vowel length, so let a human ear pick the winner. If the chosen take changes the text, lint and approve again.
- 7. **Generate the full script** with the chosen variants and settings, after `--check-approved` passes. Then:
- - Set the pacing with `ffmpeg -af atempo=1.1` (1.10–1.20 keeps pitch), not with a speed setting. If you have word timings, divide them by the same factor.
- - To fix one line, regenerate only that chunk with `previous_text`/`next_text` and splice it in.
- ## Tag budget
- **Never over-tag.** Every tag must help retention or make the voice more human. A tag that repeats what the text already says is noise.
- - **Density:** about 1 tag per 3–4 sentences, which is 4–8 tags in a 60–90 s reel. The linter errors above 0.5 tags per sentence and warns above 0.34.
- - **Baseline energy is not a tag.** The voice, a stability of 0.3–0.4 and punchy text set the overall energy. Do not put `[excited]` on every line. Save it for 2–3 peaks: the hook, the big reveal and the CTA push.
- - **Laughs: 0 to 2 per reel, and never forced.** Laugh only where a person would:
- - after a real joke or irony;
- - on a self-aware aside;
- - for relief after a tense point.
- Never laugh on numbers, dates, prices, the offer itself or the CTA keyword. Keep laughs 20 s or more apart. Pick the tag by size: `[chuckles]` is the safe, light one; `[laughs]` is a clear laugh; use `[laughs harder]` for one big moment at most.
- - **Contrast beats intensity.** Attention comes from change. Use one change of delivery every 8–12 s; this is the pattern interrupt. For example:
- - a whisper after an energetic line;
- - a pause before a reveal;
- - a sigh before a pain point;
- - a gasp before an unbelievable fact.
- - **One or two tags at a spot, never three.** Put the tag right before the words it colours. Its effect runs to about the end of that sentence.
- - **Bring the energy back after `[whispers]` or `[sighs]`.** Do it on the next line with the text (a «!», a short punch) or with a delivery tag. Check it by ear.
- - **Keep clarity lines clean.** Numbers, dates, prices, product names and the CTA keyword are said plainly. A warm tag may come before the CTA sentence, never inside the keyword.
- - **Never tag staging or music** (`[music]`, `[standing]`), and never tag sensitive topics such as grief, illness or tragedy.
- ## A/B priority
- Test credits are often limited. Spend them in this order; the linter's A/B PLAN lists the lines the same way, and `--ab-budget N` marks what fits:
- 1. **The hook.** It decides the watch. Test two variants: a tag against none, or two wordings.
- 2. **The first use of each risky tag**: whisper, sigh, laugh, sarcasm, gasp. A tag you have already tested on this voice goes lower.
- 3. **Unconfirmed readings** (Persian): test the word alone, which costs about 15 characters.
- 4. **The lift after a low tag**: the line after a whisper or sigh, with `--prev` set to the low line. Does the voice come back up?
- 5. **The CTA**, unless the person already approved it word for word.
- When a line does not fit, shorten the clip to the risky words alone; `--prev`/`--next` give the context and are not spoken. Never skip a level-1 or level-2 item to test a lower one. Tell the person what was not tested.
- ## Viral arc
- For a 60–90 s vertical video:
- | Time | Beat | Energy | Typical device |
- | --- | --- | --- | --- |
- | 0–3 s | HOOK | 5 | Urgency or curiosity in the first words: an interjection, a bold claim, a question, `[gasps]` or `[excited]`. No greeting. |
- | 3–10 s | SETUP | 4 | Why it matters now: a deadline, or what they lose if they skip it. Short and fast. |
- | every 8–12 s | INTERRUPT | ± | A change of delivery: a whisper, a sigh, a chuckle, a «...» pause, a rhetorical question. |
- | list | ITEM | 4 | A punchy numbered title, then one line of reason. Don't tag every item, and vary the openers. |
- | ~70% | TIP | 3, intimate | `[whispers]` plus "here's the trick...", then back up. Lower energy here reads as a secret and lifts retention. |
- | end | CTA | 4, warm | Clear and friendly, with the keyword said unhurried. A smile in the voice; one light tag at most. |
- For long-form narration (an audiobook, an explainer), halve the tag budget and drop the pattern-interrupt rule. Let the text carry it.
- ## Settings (ElevenLabs)
- - **eleven_v4** is ElevenLabs' recommended model. It reads only `stability` and `similarity_boost`; its help page says **Style and Speed are not available**. A test on 2026-11-03 confirmed this: speed 0.8 and 1.2 gave clips of 6.32 s and 6.40 s. Set the pace with short sentences and fewer commas, then `atempo`.
- - **Stability:** lower means more expressive delivery and closer tag-following, but takes vary more from one to the next.
- - 0.3–0.4: hype reels.
- - 0.5: neutral narration.
- - Above 0.7: tags are followed weakly.
- - Below about 0.25: takes can wobble, so A/B first.
- - **eleven_v3:** the same tags work. The ElevenLabs UI names three stability presets: Creative (low), Natural (0.5) and Robust (high, follows tags weakly). If the API rejects a value, use 0.0, 0.5 or 1.0.
- - **No SSML on v3/v4.** `<break>` is not supported. Use «...» or «—» for pauses, «،»/«,» for a breath, and `[short pause]` when punctuation is not enough.
- - **multilingual_v2, flash, turbo:** these read `[tags]` aloud, so strip every tag. Steer with `style` (0–1), `speed` (0.7–1.2) and `<break time="0.5s"/>` (3 s at most, and only a few).
- - **Chunks:** when you generate part of a script, send `previous_text`/`next_text` so the energy and intonation join up. That context is not spoken.
- - **Seed:** `seed` makes sampling close to repeatable, though not guaranteed. Fix it for A/B tests.
- ## Other TTS engines
- Convert the directed script into whatever the engine accepts:
- - **OpenAI `gpt-4o-mini-tts`:** no inline tags, so remove them. Put the delivery into the `instructions` field, for example: "energetic young narrator, fast, smiling, one short laugh after the joke".
- - **Azure or Google SSML:** use `<break>`, `<prosody rate pitch>` and `<emphasis>`. Use Azure's `<mstts:express-as style>` only on voices that list that style; check the voice's style list first.
- - **Prompt-driven engines** (e.g. Gemini TTS): a natural-language style prompt plus the clean text.
- Whatever the engine, the step 2 rewrite does most of the work.
- ## Calibrate for a new voice
- Tag behaviour and speaking rate depend on the voice. Once per voice:
- - Run `tag_lint.py SCRIPT --calibrate AUDIO.mp3`. It measures the voice's real characters per second from one finished take, for free. Pass that number as `--cps` from then on.
- - A/B the tags you plan to use with `ab.py`. Record what works in the tested-voices table in `references/audio-tags.md`.
- ## Files
- | Path | What |
- | --- | --- |
- | `references/persian-delivery.md` | Persian for the ear: colloquial register, interjections, punctuation as a score, emphasis without capitals, before/after examples |
- | `references/english-delivery.md` | The same for English |
- | `references/audio-tags.md` | Tag catalogue by job, tested-voices table, what never to tag |
- | `references/fa-traps.tsv` | Persian words spelled unlike they sound (Arabic «ال», final «ی» said «ا»); the reading checks warn on them |
- | `scripts/tag_lint.py` | Free checker: required beat labels and arc, ear-rewrite rules, tags, model errors, Persian readings, A/B plan, `--approve` / `--check-approved`, `--calibrate` |
- | `scripts/ab.py` | Variants × stability on the real voice with a fixed seed, STT leak and event detection, `LISTEN FOR`, `--dry-run`, `--lexicon` |
- | `scripts/reading.py` | Shared lexicon loading (✓ = confirmed by ear), respelling and the Persian reading checks |
- | `examples/` | A directed Persian and English reel script, with beat labels |
README.md · README · 112 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- <p align="center"><img src="assets/banner.jpg" alt="tts-director: a microphone, a clapperboard and a waveform tagged [laughs], [whispers], [excited]" width="100%"></p>
- <div dir="rtl">
- # tts-director
- [English](README.en.md) · **فارسی**
- **یه اسکیل برای ایجنتهای هوش مصنوعی که متن رو قبل از تبدیل به صدا کارگردانی میکنه.** نتیجهاش صدای یه آدم واقعی و پرانرژیه، نه کسی که از رو کاغذ میخونه.
- اول برای فارسی ساخته شده و انگلیسی رو هم پشتیبانی میکنه. روی تگهای صوتی ElevenLabs v3/v4 تمرکز داره و برای سرویسهای دیگهی TTS هم راهنما داره.
- ## مشکل چیه؟
- بیشتر متنهایی که به TTS داده میشن به یکی از این دو دلیل خراب میشن:
- - **برای چشم نوشته شدن، نه برای گوش.** جملهها رسمی و طولانیان، پس خروجی شبیه خوندن اخبار میشه.
- - **تگگذاری زیادی دارن.** وقتی سر هر خط `[excited]` باشه، صدا شبیه یه تبلیغ اغراقآمیز میشه و بیننده رد میکنه.
- ## این اسکیل چی کار میکنه؟
- ۱. **نقشهی ضربآهنگ ویدیو رو میکشه.** نقش هر خط رو مشخص میکنه: هوک، مقدمه، آیتمهای لیست، نکتهی طلایی، شوخی، دعوت به اقدام.
- ۲. **متن رو برای گوش بازنویسی میکنه.** متن محاورهای میشه، جملهها کوتاه میشن، کلمهی اصلی میره آخر جمله، و صوتهای واقعی مثل «وای»، «ببین» و «دیگه» اضافه میشن. هیچ واقعیتی از متن عوض نمیشه.
- ۳. **تگها رو با بودجهی سفتوسخت میذاره:**
- - حدود یه تگ برای هر ۳ تا ۴ جمله؛
- - تو هر ریلز صفر تا دو خنده، فقط جایی که یه آدم واقعی میخنده؛
- - هر ۸ تا ۱۲ ثانیه یه تغییر لحن، مثلاً پچپچ، آه یا مکث، تا بیننده رد نکنه.
- ۴. **یه لینتر رایگان داره** که بدون مصرف اعتبار اینها رو پیدا میکنه:
- - خطی که برچسب نقش و انرژی (` # HOOK 5`) نداره، و قوس انرژیای که هوک قوی، افتوخیز یا تغییر لحن نداره؛
- - زیادهروی در تگگذاری، و خندههای زیادی یا خیلی نزدیک به هم؛
- - نثر نوشتاری («را»، «است»، «میشود»)، کمبود یا تکرار صوتها، «هاها»ی نوشتاری و شروع ویدیو با «سلام»؛
- - کلمههایی که املاشون با تلفظشون نمیخونه («بالاخره»، «حتی»، «فوقالعاده»)، و هر املای حدسیای که یه «ا» اضافه یا کم میکنه؛
- - خطاهای مخصوص هر مدل، مثل SSML روی v4 یا تگ روی مدلهایی که تگ رو بلند میخونن.
- آخرش هم یه **برنامهی A/B** میده: کدوم خطها اول تست بشن و هر کدوم چند کاراکتر خرج داره (`--ab-budget` نشون میده چی تو بودجه جا میشه).
- ۵. **بدون تأیید، صدا ساخته نمیشه.** بعد از اینکه متن و نقشهی بیتها رو تأیید کردی، `--approve` یه مهر با هش همون متن میسازه. `--check-approved` تا وقتی مهر با متن نخونه شکست میخوره، پس هر پایپلاین TTS میتونه ساخت صدا رو به اون وصل کنه.
- ۶. **قبل از ساخت کل ویس، جملههای حساس رو A/B تست میکنه** و با صدای خودت چند نسخه میسازه:
- - همهی نسخهها با یه seed ثابت ساخته میشن تا مقایسه منصفانه باشه؛
- - `--dry-run` هزینه رو قبل از ارسال نشون میده؛
- - هر کلیپ به متن تبدیل میشه و معلوم میشه کدوم تگ بلند خونده شده و کدوم خنده واقعاً اجرا شده.
- با [Claude Code](https://claude.com/claude-code) و هر ایجنتی که اسکیلهای `SKILL.md` رو بخونه کار میکنه. اسکریپتها با Python 3.9+ نوشته شدن و هیچ وابستگیای ندارن؛ ffmpeg اختیاریه.
- ## نصب
- برای Claude Code بهعنوان اسکیل شخصی:
- <div dir="ltr">
- ```bash
- git clone https://github.com/aligh98/tts-director ~/.claude/skills/tts-director
- ```
- </div>
- یا داخل `.claude/skills/` یه پروژه کلونش کن. هر وقت متنی قراره به TTS بره، یا ازش بخوای صدا انسانیتر و پرهیجانتر بشه، خودش فعال میشه.
- ## استفادهی مستقیم از اسکریپتها
- <div dir="ltr">
- ```bash
- # Free: beat map, arc, ear-rewrite and reading checks, A/B plan
- python scripts/tag_lint.py examples/reel-fa.txt --model eleven_v4 --tempo 1.15 --ab-budget 160
- # After the text is approved: stamp it, and gate every TTS call on the stamp
- python scripts/tag_lint.py script.txt --approve
- python scripts/tag_lint.py script.txt --check-approved # exit 0 approved, 3 not
- # Free: measure your voice's real speaking rate from one finished take
- python scripts/tag_lint.py script.txt --calibrate voice.mp3
- # Check the cost first (sends nothing)
- python scripts/ab.py "[excited] وای! فقط تا جمعه وقت داری!" "وای... فقط تا جمعه وقت داری!" --stability 0.35 --stability 0.5 --out probe --dry-run
- # Generate and transcribe each variant (uses ElevenLabs credits)
- export ELEVENLABS_API_KEY=...
- python scripts/ab.py "[excited] وای! فقط تا جمعه وقت داری!" --voice YOUR_VOICE_ID --lang fa --en-check --out probe
- ```
- </div>
- گزینههای `ab.py`:
- - `--prev` و `--next`: خط قبل و بعد رو بهعنوان زمینه به مدل میدن تا لحن جملهها به هم بچسبه.
- - `--lexicon words.tsv`: یه فایل `نوشتار<TAB>گفتار<TAB>یادداشت` برای درست کردن تلفظ اسمها و کلمههای خارجی، مثل `اپ ← اَپْ`. یادداشتی که با «✓» شروع بشه یعنی یه نفر با گوش تأییدش کرده؛ برای بقیه `LISTEN FOR` چاپ میشه. همین گزینه رو `tag_lint.py` هم میگیره.
- - `--en-check`: کلیپ رو بهصورت انگلیسی هم به متن تبدیل میکنه تا اگه یه تگ انگلیسی بلند خونده شده باشه، معلوم بشه.
- تستهای آفلاین: `python -m unittest discover tests`
- ## چیزهایی که با آزمون و خطا فهمیدیم
- - **`eleven_v4` تنظیم سرعت و style رو نادیده میگیره.** یه جمله رو با سرعت ۰.۸ و ۱.۲ ساختیم و طولش تقریباً یکی شد (۶.۳۲ و ۶.۴۰ ثانیه). روی v4 فقط stability اثر داره. سرعت رو بعد از ساخت با `ffmpeg -af atempo=1.1` تنظیم کن؛ زیر و بمی صدا عوض نمیشه.
- - **`multilingual_v2`، flash و turbo تگها رو بلند میخونن.** v3 و v4 هم `<break>` رو نمیشناسن؛ به جاش از «...» استفاده کن.
- - **تگها رو حتی تو متن فارسی انگلیسی بنویس.** مدل با تگهای انگلیسی آموزش دیده.
- - **خندهی نوشتاری («هاها») حرفبهحرف خونده میشه.** به جاش `[laughs]` یا `[chuckles]` بذار.
- - **تبدیل صدا به متن فقط ثابت میکنه که خنده اجرا شده.** اینکه صدا واقعاً هیجانزدهست یا نه رو فقط گوش آدم میفهمه.
- ## مشارکت
- مفیدترین کمک، اضافه کردن یه ردیف به جدول صداهای تستشده توی `references/audio-tags.md` است: صدا، مدل و زبان؛ کدوم تگها اجرا شدن و کدوم نه؛ و سرعت حرف زدن اون صدا. راهنمای زبانهای دیگه هم با نام `references/<زبان>-delivery.md` خوشاومده.
- ## مجوز
- MIT. این پروژه هیچ ارتباطی با ElevenLabs نداره و «ElevenLabs» علامت تجاری صاحبش است.
- </div>
scripts/tag_lint.py · Bundled script · 349 lines
- #!/usr/bin/env python3
- """Check a directed TTS script before any credits are spent. Free, no API call.
- tag_lint.py SCRIPT [--model eleven_v4] [--lang auto] [--tempo 1.0] [--cps N] [--lexicon F] [--ab-budget N]
- tag_lint.py SCRIPT --approve after the person approved this exact text: write SCRIPT.approved.json
- tag_lint.py SCRIPT --check-approved exit 0 if the stamp matches the text, 3 if not (gate any TTS call on it)
- tag_lint.py SCRIPT --calibrate AUDIO measure the voice's real chars/second from one finished take
- Prints the beat map (estimated time, role, energy, tags per line), ERROR / WARN / INFO lines and an A/B PLAN
- (the lines to test first, in priority order, with their cost). Fix every ERROR. Weigh every WARN: a WARN may be
- right for this script, say why if you keep it.
- Beat labels: every spoken line ends with « # ROLE ENERGY», e.g. «[excited] Wait, this ends Friday! # HOOK 5».
- ROLE is HOOK SETUP REVEAL ITEM TIP JOKE IRONY WARNING CTA; ENERGY is 1-5. Strip « #...» before sending the text to a
- TTS (`strip_beats()` here does it). --no-beats for a script that is not a short-form video.
- --lexicon F (repeatable): TSV written<TAB>spoken<TAB>note, the respellings your pipeline applies. A note that starts
- with «✓» means the reading was confirmed by ear; the reading checks (scripts/reading.py) warn on the rest.
- --tempo: the atempo factor you will apply after generation (1.15 = 15% faster), for the time estimate.
- --cps: spoken characters (no spaces, pauses included) per second before atempo. Defaults: fa 9.6
- (measured, one Persian ElevenLabs voice), en 14 (rough estimate). Calibrate your voice once.
- --lang: fa or en for the language-specific checks; auto guesses.
- Markup understood: [tag] audio tag, {written|spoken} override (counted as spoken), " -- " pause token.
- """
- from __future__ import annotations
- import argparse
- import datetime as dt
- import hashlib
- import json
- import re
- import shutil
- import subprocess
- import sys
- from pathlib import Path
- sys.path.insert(0, str(Path(__file__).resolve().parent))
- from reading import load_lexicon, reading_checks, respell # noqa: E402
- TAG = re.compile(r"\[([^\[\]\n]{1,40})\]")
- OVERRIDE = re.compile(r"\{([^{}|]+)\|([^{}]+)\}")
- SENT = re.compile(r"[^.!?؟…]+(?:\.\.\.|[.!?؟…]+|$)")
- DIAC = re.compile("[ً-ْٰ]")
- BEAT = re.compile(r"[ \t]+#\s*([A-Za-z]+)\s*([0-9])?[^\n]*$")
- ROLES = {"HOOK", "SETUP", "REVEAL", "ITEM", "TIP", "JOKE", "IRONY", "WARNING", "CTA"}
- LAUGH = {"laughs", "laughs harder", "starts laughing", "chuckles", "giggles", "wheezing", "snorts", "laughing"}
- NONVERBAL = LAUGH | {"sighs", "exhales", "exhales sharply", "inhales deeply", "gasps", "gulps", "swallows", "clears throat",
- "short pause", "long pause", "pause"}
- DELIVERY = {"excited", "whispers", "whispering", "shouting", "shouts", "sarcastic", "curious", "surprised", "happy", "sad",
- "angry", "annoyed", "thoughtful", "mischievously", "dramatic", "calm", "conversational", "warmly", "playfully",
- "confident", "impressed", "amazed", "nervous", "serious", "crying", "frustrated", "relieved", "proud",
- "deadpan", "hyped", "fast", "slowly", "teasing", "matter-of-fact", "awe", "in awe", "rushed"}
- SFX = {"applause", "clapping", "explosion", "gunshot"}
- STAGING = {"music", "standing", "sitting", "walking", "background music", "intro", "outro"}
- KNOWN = NONVERBAL | DELIVERY | SFX
- RISKY = LAUGH | {"whispers", "whispering", "sarcastic", "gasps", "sighs", "shouting", "shouts", "crying", "teasing"}
- LOW = {"whispers", "whispering", "sighs", "sad", "calm", "thoughtful", "slowly"}
- HIGH = {"excited", "shouting", "shouts", "hyped", "amazed"}
- # references/*-delivery.md «Register»: written forms that make the voice sound read
- FORMAL = {
- "fa": [(r"می?خواهی", "میخوای"), (r"نمی?شود", "نمیشه"), (r"(?<![\w])می?شود", "میشه"), (r"\sرا(?=[\s.!؟،]|$)", "رو"),
- (r"(?<![\w])است(?=[\s.!؟،]|$)", "ـه / هست"), (r"(?<![\w])هستند(?=[\s.!؟،]|$)", "هستن"), (r"می?باشد", "ـه"),
- (r"بنابراین", "پس"), (r"لازم است", "باید"), (r"پس از", "بعد از"), (r"نخواهد", "نمی"),
- (r"(?<![\w])آن(?=[\s.!؟،]|$)", "اون"), (r"کاربران|دوستان عزیز|مخاطبان", "تو")],
- "en": [(r"\b(?:do|does|did|is|are|was|were|have|has|would|should|could) not\b", "a contraction (don't, isn't...)"),
- (r"\bit is\b", "it's"), (r"\byou are\b", "you're"), (r"\bwe are\b", "we're"), (r"\bthat is\b", "that's"),
- (r"\b(?:therefore|furthermore|moreover|hence)\b", "so / and"), (r"\b(?:users|one should)\b", "you")],
- }
- # references/*-delivery.md «Interjections»: 2-4 per reel, none repeated
- INTERJ = {
- "fa": ["وای", "اوه", "باورت نمیشه", "جدی میگم", "ببین", "دقت کن", "گوش کن", "خب", "راستی", "حالا", "آها", "آخه",
- "اِه", "ای بابا", "آره", "عه"],
- "en": ["wait", "okay", "no way", "look", "listen", "here's the thing", "so", "now", "oh", "sure", "honestly", "seriously"],
- }
- class Report:
- def __init__(self):
- self.rows: list[tuple[str, str]] = []
- def add(self, level: str, msg: str):
- self.rows.append((level, msg))
- def split_beat(line: str) -> tuple[str, str | None, int | None]:
- m = BEAT.search(line)
- if not m:
- return line, None, None
- return line[:m.start()], m.group(1).upper(), int(m.group(2)) if m.group(2) else None
- def strip_beats(text: str) -> str:
- """The text to send to a TTS: beat labels and whole «#» comment lines removed."""
- return "\n".join(split_beat(l)[0] for l in text.splitlines() if not l.lstrip().startswith("#"))
- def stamp_path(script: Path) -> Path:
- return script.with_name(script.name + ".approved.json")
- def text_hash(script: Path) -> str:
- return hashlib.sha256(script.read_text(encoding="utf-8").strip().encode("utf-8")).hexdigest()
- def approval_problem(script: Path) -> str:
- """'' when the stamp holds the hash of this exact text; otherwise why not. Any TTS pipeline can call this."""
- f = stamp_path(script)
- if not f.exists():
- return f"no approval stamp ({f.name}): the text has not been approved."
- if json.loads(f.read_text(encoding="utf-8")).get("sha256") != text_hash(script):
- return f"{script.name} changed after it was approved ({f.name})."
- return ""
- def spoken_text(s: str) -> str:
- return OVERRIDE.sub(lambda m: m.group(2), s)
- def plain(s: str) -> str:
- return re.sub(r"\s+", " ", DIAC.sub("", TAG.sub("", spoken_text(s)).replace("--", " "))).strip()
- def main():
- if hasattr(sys.stdout, "reconfigure"):
- sys.stdout.reconfigure(encoding="utf-8")
- ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- ap.add_argument("script")
- ap.add_argument("--model", default="eleven_v4")
- ap.add_argument("--tempo", type=float, default=1.0)
- ap.add_argument("--cps", type=float)
- ap.add_argument("--lang", default="auto", choices=["auto", "fa", "en"])
- ap.add_argument("--lexicon", action="append", help="TSV written<TAB>spoken<TAB>note (✓ = confirmed by ear); repeatable")
- ap.add_argument("--no-beats", action="store_true", help="do not require « # ROLE ENERGY» labels")
- ap.add_argument("--ab-budget", type=int, default=0, help="characters allowed for A/B tests: mark what fits")
- ap.add_argument("--approve", action="store_true", help="write SCRIPT.approved.json (only after the person's OK)")
- ap.add_argument("--check-approved", action="store_true", help="exit 0 if the approval stamp matches the text, else 3")
- ap.add_argument("--calibrate", metavar="AUDIO", help="print the chars/second of AUDIO for this script, then exit")
- a = ap.parse_args()
- path = Path(a.script)
- if a.check_approved:
- problem = approval_problem(path)
- print(problem or f"approved: {stamp_path(path).name} matches {path.name}")
- sys.exit(3 if problem else 0)
- raw = path.read_text(encoding="utf-8")
- lines = [l.rstrip() for l in raw.splitlines()]
- lex = load_lexicon(a.lexicon)
- text = TAG.sub("", strip_beats(raw))
- lang = a.lang if a.lang != "auto" else ("fa" if len(re.findall(r"[-ۿ]", text)) > len(re.findall(r"[A-Za-z]", text)) else "en")
- chars = sum(len(plain(l).replace(" ", "")) for l in strip_beats(raw).splitlines())
- if a.calibrate:
- if not shutil.which("ffprobe"):
- sys.exit("--calibrate needs ffprobe (ffmpeg) on PATH.")
- out = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", a.calibrate],
- capture_output=True, text=True).stdout.strip()
- dur = float(out or 0)
- if not dur:
- sys.exit(f"could not read the duration of {a.calibrate}")
- print(f"{chars} chars / {dur:.2f}s = {chars / dur:.2f} chars/s. Use --cps {chars / dur:.1f} for this voice.")
- return
- cps = a.cps or {"fa": 9.6, "en": 14.0}[lang]
- r = Report()
- tags_model = a.model.startswith(("eleven_v3", "eleven_v4"))
- t = 0.0
- events: list[tuple[float, str, int]] = [] # (time, tag, line)
- beats: list[dict] = []
- n_sent = n_excl = n_ell = 0
- print(f"{'line':>4} {'time':>6} {'' if a.no_beats else 'beat':<10} tags / marks")
- for i, full in enumerate(lines, 1):
- if not full.strip() or full.lstrip().startswith("#"):
- continue
- line, role, energy = split_beat(full)
- body = plain(line)
- dur = len(body.replace(" ", "")) / cps / a.tempo
- tags = [x.strip().lower() for x in TAG.findall(line)]
- sents = [s for s in SENT.findall(body) if s.strip()]
- n_sent += len(sents)
- n_excl += body.count("!")
- n_ell += body.count("...") + body.count("…")
- marks = [f"[{x}]" for x in tags] + (["..."] if "..." in body else []) + (["--"] if "--" in line else [])
- bl = "" if a.no_beats else f"{role or '?'} {energy or '?'}"
- print(f"{i:>4} {t:6.1f}s {bl:<10} {' '.join(marks) or '-'} {body[:56]}")
- beats.append({"line": i, "t": t, "role": role, "e": energy, "tags": tags, "text": line.strip(), "body": body})
- if not a.no_beats:
- if role is None or energy is None:
- r.add("ERROR", f"line {i}: no beat label. End the line with « # ROLE ENERGY» (e.g. « # HOOK 5»): plan the arc before the tags.")
- elif role not in ROLES or not 1 <= energy <= 5:
- r.add("ERROR", f"line {i}: «{role} {energy}» is not a beat. Roles: {' '.join(sorted(ROLES))}; energy 1-5.")
- if not tags_model and tags:
- r.add("ERROR", f"line {i}: {a.model} reads [tags] aloud. Remove them; steer with style/stability or SSML <break>.")
- if tags_model and re.search(r"<break|<phoneme|<speak|<prosody", line):
- r.add("ERROR", f"line {i}: {a.model} has no SSML. Use ... or a [short pause] tag.")
- if re.search(r"(\]\s*\[[^\]]*\]\s*\[)", line):
- r.add("ERROR", f"line {i}: three tags stacked. Use one, two at most.")
- for x in tags:
- if x in STAGING:
- r.add("ERROR", f"line {i}: [{x}] is staging, not voice. The model may play or say it. Remove.")
- elif re.search(r"[-ۿ]", x):
- r.add("WARN", f"line {i}: [{x}] is a Persian tag. It is not read aloud, but English tags are what the model was trained on: use one.")
- elif x not in KNOWN and not x.startswith("strong "):
- r.add("WARN", f"line {i}: [{x}] is not in the tested set. Probe it with ab.py before the full run.")
- if energy and x in LOW and energy >= 4:
- r.add("WARN", f"line {i}: [{x}] on an energy-{energy} beat. A low tag needs a low beat (1-3), or drop it.")
- if energy and x in HIGH and energy <= 2:
- r.add("WARN", f"line {i}: [{x}] on an energy-{energy} beat. Raise the beat or drop the tag.")
- events.append((t, x, i))
- for rx, fix in FORMAL[lang]:
- m = re.search(rx, body, re.I)
- if m:
- r.add("WARN", f"line {i}: «{m.group(0).strip()}» is written register; say «{fix}» ({lang}-delivery.md, Register).")
- if re.search(r"(?:ها){2,}|ههه|خخخ|قاه|\b(?:ha){2,}\b|\bhehe+\b|\blol\b|\blmao\b", body, re.I):
- r.add("WARN", f"line {i}: written laughter («هاها», haha, lol) is read as letters. Use [laughs] or [chuckles].")
- if re.search(r"([اوی])\1\1|([a-z])\2\2\2", body, re.I):
- r.add("WARN", f"line {i}: stretched letters («وااای», «sooooo») read unpredictably; A/B them or write the word normally.")
- for s in sents:
- if len(s.split()) > 22:
- r.add("WARN", f"line {i}: a {len(s.split())}-word sentence. Split it: a reel voice breathes every 8-14 words.")
- if lang == "fa":
- for w in reading_checks(line, lex):
- r.add("WARN", f"line {i}: reading not confirmed by ear: {w}")
- t += dur
- total = t
- n_tags = len(events)
- ratio = n_tags / max(n_sent, 1)
- laughs = [e for e in events if e[1] in LAUGH]
- if ratio > 0.5:
- r.add("ERROR", f"{n_tags} tags for {n_sent} sentences ({ratio:.2f}/sentence). Over-tagged: keep the beats only (aim <= 0.3).")
- elif ratio > 0.34:
- r.add("WARN", f"{n_tags} tags for {n_sent} sentences ({ratio:.2f}/sentence). Aim <= 0.3; drop tags that do not change the delivery.")
- if total > 20 and n_tags == 0:
- r.add("INFO", "no tags at all. Fine if the text carries the energy; consider one on the hook and one pattern-interrupt.")
- if len(laughs) > 2:
- r.add("WARN", f"{len(laughs)} laughs. More than two in a reel sounds forced: keep the one on the real joke.")
- for x, y in zip(laughs, laughs[1:]):
- if y[0] - x[0] < 20:
- r.add("WARN", f"laughs on lines {x[2]} and {y[2]} are ~{y[0] - x[0]:.0f}s apart. Space them 20s+ or keep one.")
- for x, y in zip(events, events[1:]):
- if x[1] == y[1] and x[1] not in ("short pause",):
- r.add("WARN", f"[{x[1]}] twice in a row (lines {x[2]}, {y[2]}). The second adds nothing: drop it or change the delivery.")
- for w in [e for e in events if e[1] in LOW]:
- nxt = next((b for b in beats if b["line"] > w[2]), None)
- if nxt and not ("!" in nxt["body"] or set(nxt["tags"]) & HIGH or (nxt["e"] or 0) >= 4):
- r.add("WARN", f"[{w[1]}] on line {w[2]}: the next line (line {nxt['line']}) does not lift the energy back up "
- f"(no «!», high tag or energy 4+). Lift it, and A/B the pair.")
- if n_sent and n_excl / n_sent > 0.7:
- r.add("WARN", f"«!» on {n_excl} of {n_sent} sentences. When everything shouts nothing does: keep «!» for the peaks, use «.» between.")
- if n_sent and n_ell / n_sent > 0.34:
- r.add("WARN", f"{n_ell} «...» for {n_sent} sentences. Ellipses are pauses: too many and the reel drags.")
- hook = beats[0]["text"] if beats else ""
- hook_words = {"fa": r"وای|اوه|ببین|باورت|میدونستی|میدونستی|نکنه", "en": r"\b(?:wait|no way|okay|ok|look|stop|did you know|imagine|never)\b"}[lang]
- if total > 20 and not (TAG.search(hook) or re.search(hook_words + r"|\?|؟|!", hook, re.I)):
- r.add("INFO", "the first line has no hook energy (no tag, question, «!» or interjection). The first 2 seconds decide the watch.")
- greeting = {"fa": r"\W*سلام", "en": r"\W*(?:hi|hey|hello|welcome back)\b"}[lang]
- if re.match(greeting, plain(hook), re.I):
- r.add("WARN", "the video opens with a greeting. Viewers swipe in the first 2 seconds: open on the hook.")
- alltext = " ".join(b["body"] for b in beats)
- found = {w: len(re.findall(rf"(?<![\w]){re.escape(w)}(?![\w])", alltext, re.I)) for w in INTERJ[lang]}
- if total > 20 and sum(found.values()) < 2:
- r.add("WARN", f"{sum(found.values())} interjection(s). 2-4 natural ones make the voice human ({lang}-delivery.md, Interjections).")
- for w, n in found.items():
- if n > 1 and w not in ("so", "now", "خب", "حالا"):
- r.add("WARN", f"interjection «{w}» used {n} times. Vary them: a repeated one sounds scripted.")
- # the viral arc (SKILL.md «Viral arc»)
- if not a.no_beats and beats and all(b["role"] and b["e"] for b in beats):
- if beats[0]["role"] != "HOOK" or beats[0]["e"] < 4:
- r.add("ERROR", f"the first line is «{beats[0]['role']} {beats[0]['e']}». A short-form video opens on a HOOK at energy 4-5.")
- if total > 20 and not any(b["role"] == "CTA" for b in beats):
- r.add("INFO", "no CTA beat. Fine for pure content; most short-form videos end with one.")
- for b in beats:
- if b["role"] == "TIP" and b["e"] > 3:
- r.add("WARN", f"line {b['line']}: a TIP at energy {b['e']}. A tip lands as a secret at 2-3, then lifts.")
- if b["role"] == "CTA" and b["e"] not in (3, 4):
- r.add("INFO", f"line {b['line']}: CTA at energy {b['e']}. Warm and clear is 3-4; a shouted CTA sounds like an ad.")
- es = [b["e"] for b in beats]
- if len(es) > 4 and max(es) - min(es) < 2:
- r.add("WARN", f"every beat is energy {min(es)}-{max(es)}. A flat arc loses the viewer: add a low beat (tip, sigh, whisper).")
- changes = [0.0]
- for x, y in zip(beats, beats[1:]):
- if abs(y["e"] - x["e"]) >= 2 or set(y["tags"]) & RISKY or "؟" in y["body"] or "?" in y["body"] or "..." in y["body"]:
- changes.append(y["t"])
- changes.append(total)
- for x, y in zip(changes, changes[1:]):
- if y - x > 14:
- r.add("WARN", f"no change of delivery between ~{x:.0f}s and ~{y:.0f}s. Add a pattern interrupt every 8-12 s.")
- # A/B PLAN (SKILL.md «A/B priority»)
- rows: list[tuple[int, str, dict]] = []
- seen: set[str] = set()
- for b in beats:
- if b["role"] == "HOOK" and not any(p[2]["role"] == "HOOK" for p in rows):
- rows.append((1, "hook", b))
- for x in b["tags"]:
- if x in RISKY and x not in seen:
- seen.add(x)
- rows.append((2, f"first [{x}]", b))
- if lang == "fa" and reading_checks(b["text"], lex):
- rows.append((3, "unconfirmed reading (test the word alone)", b))
- for w in [e for e in events if e[1] in LOW]:
- nxt = next((b for b in beats if b["line"] > w[2]), None)
- if nxt:
- rows.append((4, f"lift after [{w[1]}] (with --prev)", nxt))
- cta = next((b for b in beats if b["role"] == "CTA"), None)
- if cta:
- rows.append((5, "CTA (skip if already approved word for word)", cta))
- if not beats or a.no_beats:
- rows = [p for p in rows if p[0] != 1]
- rows.sort(key=lambda p: (p[0], p[2]["line"]))
- if rows:
- print("\nA/B PLAN (priority order; cost = spoken characters per clip):")
- used, done = 0, set()
- for pri, why, b in rows:
- if b["line"] in done:
- continue
- done.add(b["line"])
- cost = len(respell(spoken_text(b["text"]), lex))
- note = ""
- if a.ab_budget:
- ok = used + cost <= a.ab_budget
- used += cost if ok else 0
- note = " fits" if ok else " OVER BUDGET: shorten the clip to the risky words, or skip and say so"
- print(f" {pri}. line {b['line']:<3} {why:<42} ~{cost} ch{note}")
- if a.ab_budget:
- print(f" budget {a.ab_budget}: {used} used by the lines that fit (one clip each; a second variant doubles it)")
- print(f"\nlang {lang} | {cps} chars/s | estimated length {total:.1f}s at tempo {a.tempo} | sentences {n_sent} | tags {n_tags} ({ratio:.2f}/sentence) | laughs {len(laughs)}")
- for level, msg in sorted(r.rows, key=lambda x: ("ERROR", "WARN", "INFO").index(x[0])):
- print(f"{level:5} {msg}")
- errors = any(lv == "ERROR" for lv, _ in r.rows)
- if a.approve:
- if errors:
- sys.exit("\nNot approved: fix every ERROR first.")
- stamp_path(path).write_text(json.dumps({
- "sha256": text_hash(path),
- "approved": dt.datetime.now().isoformat(timespec="seconds"),
- "warnings_kept": [m for lv, m in r.rows if lv == "WARN"],
- }, ensure_ascii=False, indent=1), encoding="utf-8")
- print(f"\napproved: {stamp_path(path).name} (any edit to {path.name} needs a new OK and a new --approve)")
- sys.exit(1 if errors else 0)
- if __name__ == "__main__":
- main()
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.