AIStoreHub Package Vault: Real SFX: Motion Video Sound Design
Package Slug: real-sfx
Archetype: skill
Upstream Repository: https://github.com/Clipwing/skills/tree/main/skills/real-sfx
Workspace Files & Specifications (69 files)
- aistorehub.json (1707 bytes)
{ "name": "Real SFX: Motion Video Sound Design", "slug": "real-sfx", "version": "1.0.0", "type": "skill", "description": "Sound design for motion videos with REAL recorded sounds from the user's own libraries (a sorted main pack of whooshes, hits, risers, pops, chimes, keystrokes, foley, ambiences plus fallback libraries) and UI cues from uisfx, never synthesized. Finds the moments from the project's own cue list or from the synthesizer script that makes its sound, from a HyperFrames composition, from a screen recording (regions: typing, toasts, scrolls, clicks) or from the picture itself, picks and processes the sounds, places them on the exact frame at the level the author's own sounds had, keeps the music and voice, takes a synthesized layer baked into the render OUT instead of doubling it, and returns a new MP4, a separate SFX WAV track, a cue report and a self-critique scoreboard. Use whenever the user asks to add sound effects or SFX, sound-design, \"озвучь\", \"добавь звуки\", \"сфх\", whoosh/hit/riser/click/typing sounds, UI sounds, to replace synthesized or generated sounds with real ones, or to make a motion graphic, promo, explainer, UI animation, screencast, HyperFrames render, After Effects or Premiere project sound better, or complains the sound is synthetic, generic or out of sync, even if they do not say \"skill\" or name a library.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/Clipwing/skills/tree/main/skills/real-sfx", "tags": [ "claude-code", "foley", "skill", "python", "sound-design", "cursor", "motion" ], "imported_at": "2026-11-23T02:54:59.599Z" } - INSTRUCTIONS.md (49821 bytes)
--- name: real-sfx description: Sound design for motion videos with REAL recorded sounds from the user's own libraries (a sorted main pack of whooshes, hits, risers, pops, chimes, keystrokes, foley, ambiences plus fallback libraries) and UI cues from uisfx, never synthesized. Finds the moments from the project's own cue list or from the synthesizer script that makes its sound, from a HyperFrames composition, from a screen recording (regions: typing, toasts, scrolls, clicks) or from the picture itself, picks and processes the sounds, places them on the exact frame at the level the author's own sounds had, keeps the music and voice, takes a synthesized layer baked into the render OUT instead of doubling it, and returns a new MP4, a separate SFX WAV track, a cue report and a self-critique scoreboard. Use whenever the user asks to add sound effects or SFX, sound-design, "озвучь", "добавь звуки", "сфх", whoosh/hit/riser/click/typing sounds, UI sounds, to replace synthesized or generated sounds with real ones, or to make a motion graphic, promo, explainer, UI animation, screencast, HyperFrames render, After Effects or Premiere project sound better, or complains the sound is synthetic, generic or out of sync, even if they do not say "skill" or name a library. --- # real-sfx: real sounds for a motion video The goal: the film sounds as if a person with a good library had cut it. So: - **Sound is never synthesized.** Sources: the user's libraries (`config.json`) and uisfx (a ready CC0 pack of interface sounds, itself synthesized: the one exception, only for interface moments; "no synthesis" turns it off: `--ui library`). No fitting sound: the moment stays quiet and goes into the report. This overrides "no track: synthesize" from motion-standards. - **You cannot hear.** Sound is read as numbers, words and pictures (`references/listening.md`). Do not present a pick as listened to: say what was checked by eye and by measurement, and what the user should listen to. - **Keep the music and voice** when they carry the film. The result is always a new MP4 **and a separate WAV track**. - **Do not double.** Synthesis baked into the render's audio is replaced by the real sounds, not layered under them (step 1). The critique measures this as a number (the `doubling` axis). - **Do not change the project or the skill folder.** Put all working files in your own folder (`work/`, `result/`). ## Quick path First `python scripts/setup.py check` (ffmpeg, main/extra libraries, index, uisfx) and `python scripts/look.py FILM.mp4 --out work/look` (frames with time + the original sound under them). Then, by what you have: ``` # 1. the project has an event list (docs/cues.json, scripts/cues.json) OR a script that synthesizes its sound (audio.cjs) python scripts/from_cues.py PROJECT_FOLDER|docs/cues.json --video RENDER.mp4 --out work/cues.json # 2. screen recording without a list: ui_events.py ... (references/screencast.md), then from_cues.py work/ui/events.json # 3. picture only: find_moments.py FILM.mp4 --out work/moments; suggest_cues.py work/moments/moments.json --out work/cues.json # 3b. SOFT COLOURED ANIMATION without a list (UI preview, illustration, motion graphics): automation sees 5-6 moves of 40. # step 2, "Silent animation without a list": find_moments.py FILM --out work/moments --fine; look.py FILM --at T --span 2.4 # --step 0.1 --out work/at.png; YOUR OWN event list from the frames (references/typed-cues.md) -> from_cues.py - --ui library python scripts/mix.py work/cues.json --out result/film_sfx.mp4 --plan # what goes where; then without --plan python scripts/critique.py result/film_sfx_resolved_cues.json result/film_sfx_sfx_track.wav python scripts/levels.py result/film_sfx_resolved_cues.json result/film_sfx_sfx_track.wav --json work/edits.json # a film whose sound is ONLY SFX (no music or voice of its own): small sounds in the holes, then mix.py again (step 4, "Small-sound layer") python scripts/texture.py work/cues.json --moments work/moments/moments.json # the same film: a bed (one long dark real recording under the whole film; step 4, "Bed"), then mix.py again python scripts/bed.py work/cues.json [--list] # numbers against nine finished SFX reels (step 6, "Against the reference"): no scores, does not affect the verdict python scripts/critique.py RESOLVED.json WAV --style clean-sfx-refs # human ears made cheap (step 6): a page with the critique's questions and a one-tap verdict; the masking model python scripts/listen_page.py build work/listen --moments result/film_sfx.mp4 --critique RESOLVED.json WAV python scripts/listen_page.py serve work/listen [--lan] # then: listen_page.py results work/listen --log python scripts/mix.py work/cues.json --out result/film_sfx.mp4 --masking # which sounds the rest hides (needs the venv) ``` A project folder finds its own event list (`docs/`, `scripts/`, `assets/`); the synthesizer script is read only when there is no list. **Choose all `from_cues.py` flags before editing the sheet**: running it again wipes manual edits (then `sheet.py apply`). Voice in the film: `mix.py ... --voice-safe` (depth `normal`; `--voice-depth light` when there are many quiet textures, `deep` only for rare sounds in pauses: it takes the interface out of the mix entirely). Music carries the film: `--duck`. Loudness: a rebuilt base matches the original by default; your own: `--target-lufs NUMBER`. No index, or the libraries moved: `python scripts/build_index.py`, then `python scripts/listen.py tag-index`. No uisfx: `setup.py init --uisfx`. Another machine: `setup.py scan FOLDER`, `setup.py add-library NAME PATH [--tier main|extra] --index`. Run scripts from the skill folder; quote paths with spaces or non-Latin characters; your own Python with non-Latin paths on Windows: `PYTHONUTF8=1`. In PowerShell, quotes break JSON arguments: put them in a file. ## Where the sounds come from | What is needed | Where from | |---|---| | The base: whooshes, hits, risers, pops, chimes, keys, paper, foley, ambience | **the main library** (`tier: main`, path in `config.json`). A sorted pack with `catalog.json` / `catalog.csv` gives every sound its type and source recording, which beats guessing from file names | | What the main library lacks: low drops, coins, short glitches | fallback libraries (`tier: extra`, marked `~` in results): only when the main library has fewer than three fitting sounds | | Designed packs with their own roles | roles `granular`, `atmosphere`, `power`, `music_transition`, `voice` are never requested by auto-picking: take them explicitly (`--role`, `"pick": {"role": ...}`) | | An interface moment: click, tick, window, notification | uisfx (`--ui auto`) when the list itself names interface kinds (click, chime...): `from_cues` says why and where (`routes: key -> library:click, pop -> uisfx:select`) | | Typing | always the library's real keyboard, even with `--ui auto`; a run of 8+ `click` events 35–170 ms apart is recognized as typing by `from_cues` itself (`--no-typing-detect`) | | Physical contact: ball, step, bead, object | always the library: a ball on the floor is a dull thud, not `select` (recipe below) | No library yet: `setup.py init --uisfx` alone gives 78 CC0 UI cues. Free real-recording sources worth checking (read each licence): Freesound (CC0 filter), Sonniss GDC bundles, Mixkit, Pixabay sound effects. "From my library", "no synthesis" or "sounds synthetic": **`--ui library`**. An accent on the logo or a "cha-ching" in a project with uisfx interface sounds: `--from-library pop,bell` (**kind names from the list**); for one sound: `sheet.py set --at T --label bell id=65`. Under tonal music: - the pitch steps of uisfx repeats and of the library's tonal sounds (chime, pop, glass, coin) turn off by themselves when the project has a score (`--ui-pitch off|cycle`); - **the pitch of a real sound is tuned to the notes of the music**: `mix.py` takes the sheet's `music_ref` (the bed without effects, the music stem) or `--music-ref FILE` and shifts a tonal sound by whole semitones up to 2 plus the cents that put it on a note (2.5 in total), if that puts it on a note; noise is left alone (`--no-tonal-fit`; `scripts/tonal.py SOUND --music FILE --at T` shows the notes); - the intervals of the author's own frequencies (`tick(t, 1800 * 2 ** (4 * i / 12))`) become the pitch steps of the replacement (`melody:`). ## Workflow ### 1. What is already in the sound `look.py` shows the spectrogram of the native sound (voice is bands of phrases, music a carpet with a beat, silence is black); `listen.py voice FILM.mp4` gives the share of speech and music. Three cases: - **The author's music or voice**: they stay, SFX go on top (`--duck` / `--voice-safe`). **Exception (a person's answer on a real film, 2026-10-19)**: the film was sent "to be sound-designed", its native sound is music only (`listen.py voice`: speech 0 %), and the person wants it **without** the music, like their own clean SFX reels. Make a version without music (`from_cues.py ... --ui library --drop-original`, then `bed.py --id ... --level -46` with a favourite atmosphere), and a version with music if useful, and say which is which. In a blind choice of three (original / effects over music / effects only) the person chose the last one without a single complaint. `from_cues` prints `BAKED:` on such a film although there is no baked synthesis (speech 0 %, music 84 %, the attacks do not match the events: 7 % against 9 % by chance): this is a false alarm. - **Synthesis baked into the track** (the project was written for a synthesized score): real sounds on top of it are doubling. `from_cues.py` checks this itself (`BAKED:`, `unbake:`) and removes the synthesis from the base without touching music and voice; how exactly, and what to do if the script fails or the synthesis sits inside the music stem (`--extra-synth`): **`references/project-audio.md`** (read it as soon as the output has `BAKED`, `WARN stems`, `unbake: not possible`, or the project synthesizes its sound with a script). After the build `critique.py` prints the `doubling` axis: the correlation of the layer with the original and with the new film (should be about 0). - **The sound of clips playing inside a screen recording's window**: native, stays; events inside those windows are dropped. ### 2. Find the moments (from the best source to the worst) - **The project's event list or synthesizer script** → `from_cues.py` (below). In detail: `references/typed-cues.md`. - **A screen recording** → `references/screencast.md` (`ui_events.py` regions, matching keystrokes to characters, clip sound). - **HyperFrames with `data-start`** and no list: `from_hyperframes.py PROJECT --out work/moments.json`. "1 moments" with 18 elements means the motion does not follow `data-start`: look for a synthesizer script. - **Video only**: `find_moments.py FILM --out work/moments [--roi x,y,w,h] [--from A --to B] [--fine]`; kinds `cut`, `burst`, `onset`, `settle` (`settle` also fires on an empty frame or a loop at rest: look at the frame); `look.py --moments ...` draws the frames of the moments. Skeleton: `suggest_cues.py` (`references/recipes.md`); a draft is a start, not an answer. **`--fine`** for soft coloured animation (gradients, glows, pastel shapes that change colour rather than brightness): it also reads chroma changes, moments get `src=chroma|luma`; on three such films it finds 33–69 % of the events an agent wrote down from the frames (within 80 ms), against 13–25 % from brightness alone; 3–4 times more candidates (15–25 per 10 s). These are candidates: the frames decide. - **Under music**: `beats.py FILM --out work/beats.json --plot work/beats.png`; with `usable: true`, `mix.py --snap-beats` (±50 ms). The grid **is checked against the kick** (the low band < 125 Hz separately): it prints how many beats landed on a kick within 40 ms. A grid next to the kick (the tracker sat on the hats, "0.22 s off") is moved onto it; a grid that lands on nothing gets `usable: false`, and `--snap-beats` ignores it. `--plot` draws the band, the kicks (green marks) and the grid (red lines): the marks sit on the lines, or do not trust the grid. If the music is yours and can be fitted to the picture: `beats.py FILM --suggest-offset work/moments.json` says how far to shift the music so cuts and hits land on beats (advice only; the music is not touched). **`from_cues.py`**: `python scripts/from_cues.py LIST|PROJECT_FOLDER|SCRIPT.cjs|- --video RENDER.mp4 --out work/cues.json` (`-` reads the list from stdin; a BOM from PowerShell is understood). What it does and says by itself: - **is it the right render**: the list misses the picture (`VERDICT`); **a design-time list against a render timed to the voice**: a time map from the project's anchors (`timing.json` with `anchors` or `WARP`, `src/timing.js`) or from the onsets of the synthesized stems, each event lands on its own onset (`time map`); `--time-map FILE`, `--warp off|stems|audio`; - **synthesis under the list**: a whoosh lands on the peak of the synthesized sound, its length is measured from it (`retime:`); no move if the peak belongs to another sound (pop, bell) or the list time is already the centre of the whoosh: named with the reason; synthesis onsets with no event in the list are listed (`--add-unlisted tick` turns them into events); - **timbre**: the brightness of the whooshes being replaced (centroid of the synthesized layer) feeds the pick (`timbre:`); `--tone airy|dark` sets it by hand; - **an unknown kind** (`bead`, `soft`): it shows how the project defines it. Say it in one line, no file needed: `--kind bead=click`, `--kind soft=pop`, a role with limits `--kind bead=role:click,max_dur=0.3,onsets_max=1`, `--kind bead=slices:740,763` (single sounds from these recordings; the quietest ones, 12 dB down, are not taken), `--map '{"glass":{"ids":[65,54],"role":"chime"}}'` (`ids` in turn; an element `{"id":800,"slice":[0.78,0.12]}`); `--remember` keeps it. Summary: `declared N events: M voiced, K silent`; the critique counts silent kinds as a hole; - **clusters**: events of one kind closer than 25 ms are one sound (`--fuse`), runs faster than 14/s are thinned (`--max-rate`), the output says how many of each (`thinned: key 23, tick 11`); - **a typing stretch** (`{"t":19.99,"type":"typing","len":0.36,"n":99}`) unfolds into keystrokes (`--type-rate`). **Silent animation without a list** (UI preview, illustration, motion graphics; all four blind tests on 2026-10-15 were like this). Automation reads brightness and sees 5–6 moves of ~40 in soft coloured animation, and `suggest_cues` draws only whooshes from them: the draft here is a skeleton, not an answer. The path on which four agents out of four finished the film: 1. `look.py FILM --out work/look`, then `find_moments.py FILM --out work/moments --fine`. 2. **Close-up frames in 2–3 s windows**: - README.md (49820 bytes)
--- name: real-sfx description: Sound design for motion videos with REAL recorded sounds from the user's own libraries (a sorted main pack of whooshes, hits, risers, pops, chimes, keystrokes, foley, ambiences plus fallback libraries) and UI cues from uisfx, never synthesized. Finds the moments from the project's own cue list or from the synthesizer script that makes its sound, from a HyperFrames composition, from a screen recording (regions: typing, toasts, scrolls, clicks) or from the picture itself, picks and processes the sounds, places them on the exact frame at the level the author's own sounds had, keeps the music and voice, takes a synthesized layer baked into the render OUT instead of doubling it, and returns a new MP4, a separate SFX WAV track, a cue report and a self-critique scoreboard. Use whenever the user asks to add sound effects or SFX, sound-design, "озвучь", "добавь звуки", "сфх", whoosh/hit/riser/click/typing sounds, UI sounds, to replace synthesized or generated sounds with real ones, or to make a motion graphic, promo, explainer, UI animation, screencast, HyperFrames render, After Effects or Premiere project sound better, or complains the sound is synthetic, generic or out of sync, even if they do not say "skill" or name a library. --- # real-sfx: real sounds for a motion video The goal: the film sounds as if a person with a good library had cut it. So: - **Sound is never synthesized.** Sources: the user's libraries (`config.json`) and uisfx (a ready CC0 pack of interface sounds, itself synthesized: the one exception, only for interface moments; "no synthesis" turns it off: `--ui library`). No fitting sound: the moment stays quiet and goes into the report. This overrides "no track: synthesize" from motion-standards. - **You cannot hear.** Sound is read as numbers, words and pictures (`references/listening.md`). Do not present a pick as listened to: say what was checked by eye and by measurement, and what the user should listen to. - **Keep the music and voice** when they carry the film. The result is always a new MP4 **and a separate WAV track**. - **Do not double.** Synthesis baked into the render's audio is replaced by the real sounds, not layered under them (step 1). The critique measures this as a number (the `doubling` axis). - **Do not change the project or the skill folder.** Put all working files in your own folder (`work/`, `result/`). ## Quick path First `python scripts/setup.py check` (ffmpeg, main/extra libraries, index, uisfx) and `python scripts/look.py FILM.mp4 --out work/look` (frames with time + the original sound under them). Then, by what you have: ``` # 1. the project has an event list (docs/cues.json, scripts/cues.json) OR a script that synthesizes its sound (audio.cjs) python scripts/from_cues.py PROJECT_FOLDER|docs/cues.json --video RENDER.mp4 --out work/cues.json # 2. screen recording without a list: ui_events.py ... (references/screencast.md), then from_cues.py work/ui/events.json # 3. picture only: find_moments.py FILM.mp4 --out work/moments; suggest_cues.py work/moments/moments.json --out work/cues.json # 3b. SOFT COLOURED ANIMATION without a list (UI preview, illustration, motion graphics): automation sees 5-6 moves of 40. # step 2, "Silent animation without a list": find_moments.py FILM --out work/moments --fine; look.py FILM --at T --span 2.4 # --step 0.1 --out work/at.png; YOUR OWN event list from the frames (references/typed-cues.md) -> from_cues.py - --ui library python scripts/mix.py work/cues.json --out result/film_sfx.mp4 --plan # what goes where; then without --plan python scripts/critique.py result/film_sfx_resolved_cues.json result/film_sfx_sfx_track.wav python scripts/levels.py result/film_sfx_resolved_cues.json result/film_sfx_sfx_track.wav --json work/edits.json # a film whose sound is ONLY SFX (no music or voice of its own): small sounds in the holes, then mix.py again (step 4, "Small-sound layer") python scripts/texture.py work/cues.json --moments work/moments/moments.json # the same film: a bed (one long dark real recording under the whole film; step 4, "Bed"), then mix.py again python scripts/bed.py work/cues.json [--list] # numbers against nine finished SFX reels (step 6, "Against the reference"): no scores, does not affect the verdict python scripts/critique.py RESOLVED.json WAV --style clean-sfx-refs # human ears made cheap (step 6): a page with the critique's questions and a one-tap verdict; the masking model python scripts/listen_page.py build work/listen --moments result/film_sfx.mp4 --critique RESOLVED.json WAV python scripts/listen_page.py serve work/listen [--lan] # then: listen_page.py results work/listen --log python scripts/mix.py work/cues.json --out result/film_sfx.mp4 --masking # which sounds the rest hides (needs the venv) ``` A project folder finds its own event list (`docs/`, `scripts/`, `assets/`); the synthesizer script is read only when there is no list. **Choose all `from_cues.py` flags before editing the sheet**: running it again wipes manual edits (then `sheet.py apply`). Voice in the film: `mix.py ... --voice-safe` (depth `normal`; `--voice-depth light` when there are many quiet textures, `deep` only for rare sounds in pauses: it takes the interface out of the mix entirely). Music carries the film: `--duck`. Loudness: a rebuilt base matches the original by default; your own: `--target-lufs NUMBER`. No index, or the libraries moved: `python scripts/build_index.py`, then `python scripts/listen.py tag-index`. No uisfx: `setup.py init --uisfx`. Another machine: `setup.py scan FOLDER`, `setup.py add-library NAME PATH [--tier main|extra] --index`. Run scripts from the skill folder; quote paths with spaces or non-Latin characters; your own Python with non-Latin paths on Windows: `PYTHONUTF8=1`. In PowerShell, quotes break JSON arguments: put them in a file. ## Where the sounds come from | What is needed | Where from | |---|---| | The base: whooshes, hits, risers, pops, chimes, keys, paper, foley, ambience | **the main library** (`tier: main`, path in `config.json`). A sorted pack with `catalog.json` / `catalog.csv` gives every sound its type and source recording, which beats guessing from file names | | What the main library lacks: low drops, coins, short glitches | fallback libraries (`tier: extra`, marked `~` in results): only when the main library has fewer than three fitting sounds | | Designed packs with their own roles | roles `granular`, `atmosphere`, `power`, `music_transition`, `voice` are never requested by auto-picking: take them explicitly (`--role`, `"pick": {"role": ...}`) | | An interface moment: click, tick, window, notification | uisfx (`--ui auto`) when the list itself names interface kinds (click, chime...): `from_cues` says why and where (`routes: key -> library:click, pop -> uisfx:select`) | | Typing | always the library's real keyboard, even with `--ui auto`; a run of 8+ `click` events 35–170 ms apart is recognized as typing by `from_cues` itself (`--no-typing-detect`) | | Physical contact: ball, step, bead, object | always the library: a ball on the floor is a dull thud, not `select` (recipe below) | No library yet: `setup.py init --uisfx` alone gives 78 CC0 UI cues. Free real-recording sources worth checking (read each licence): Freesound (CC0 filter), Sonniss GDC bundles, Mixkit, Pixabay sound effects. "From my library", "no synthesis" or "sounds synthetic": **`--ui library`**. An accent on the logo or a "cha-ching" in a project with uisfx interface sounds: `--from-library pop,bell` (**kind names from the list**); for one sound: `sheet.py set --at T --label bell id=65`. Under tonal music: - the pitch steps of uisfx repeats and of the library's tonal sounds (chime, pop, glass, coin) turn off by themselves when the project has a score (`--ui-pitch off|cycle`); - **the pitch of a real sound is tuned to the notes of the music**: `mix.py` takes the sheet's `music_ref` (the bed without effects, the music stem) or `--music-ref FILE` and shifts a tonal sound by whole semitones up to 2 plus the cents that put it on a note (2.5 in total), if that puts it on a note; noise is left alone (`--no-tonal-fit`; `scripts/tonal.py SOUND --music FILE --at T` shows the notes); - the intervals of the author's own frequencies (`tick(t, 1800 * 2 ** (4 * i / 12))`) become the pitch steps of the replacement (`melody:`). ## Workflow ### 1. What is already in the sound `look.py` shows the spectrogram of the native sound (voice is bands of phrases, music a carpet with a beat, silence is black); `listen.py voice FILM.mp4` gives the share of speech and music. Three cases: - **The author's music or voice**: they stay, SFX go on top (`--duck` / `--voice-safe`). **Exception (a person's answer on a real film, 2026-10-19)**: the film was sent "to be sound-designed", its native sound is music only (`listen.py voice`: speech 0 %), and the person wants it **without** the music, like their own clean SFX reels. Make a version without music (`from_cues.py ... --ui library --drop-original`, then `bed.py --id ... --level -46` with a favourite atmosphere), and a version with music if useful, and say which is which. In a blind choice of three (original / effects over music / effects only) the person chose the last one without a single complaint. `from_cues` prints `BAKED:` on such a film although there is no baked synthesis (speech 0 %, music 84 %, the attacks do not match the events: 7 % against 9 % by chance): this is a false alarm. - **Synthesis baked into the track** (the project was written for a synthesized score): real sounds on top of it are doubling. `from_cues.py` checks this itself (`BAKED:`, `unbake:`) and removes the synthesis from the base without touching music and voice; how exactly, and what to do if the script fails or the synthesis sits inside the music stem (`--extra-synth`): **`references/project-audio.md`** (read it as soon as the output has `BAKED`, `WARN stems`, `unbake: not possible`, or the project synthesizes its sound with a script). After the build `critique.py` prints the `doubling` axis: the correlation of the layer with the original and with the new film (should be about 0). - **The sound of clips playing inside a screen recording's window**: native, stays; events inside those windows are dropped. ### 2. Find the moments (from the best source to the worst) - **The project's event list or synthesizer script** → `from_cues.py` (below). In detail: `references/typed-cues.md`. - **A screen recording** → `references/screencast.md` (`ui_events.py` regions, matching keystrokes to characters, clip sound). - **HyperFrames with `data-start`** and no list: `from_hyperframes.py PROJECT --out work/moments.json`. "1 moments" with 18 elements means the motion does not follow `data-start`: look for a synthesizer script. - **Video only**: `find_moments.py FILM --out work/moments [--roi x,y,w,h] [--from A --to B] [--fine]`; kinds `cut`, `burst`, `onset`, `settle` (`settle` also fires on an empty frame or a loop at rest: look at the frame); `look.py --moments ...` draws the frames of the moments. Skeleton: `suggest_cues.py` (`references/recipes.md`); a draft is a start, not an answer. **`--fine`** for soft coloured animation (gradients, glows, pastel shapes that change colour rather than brightness): it also reads chroma changes, moments get `src=chroma|luma`; on three such films it finds 33–69 % of the events an agent wrote down from the frames (within 80 ms), against 13–25 % from brightness alone; 3–4 times more candidates (15–25 per 10 s). These are candidates: the frames decide. - **Under music**: `beats.py FILM --out work/beats.json --plot work/beats.png`; with `usable: true`, `mix.py --snap-beats` (±50 ms). The grid **is checked against the kick** (the low band < 125 Hz separately): it prints how many beats landed on a kick within 40 ms. A grid next to the kick (the tracker sat on the hats, "0.22 s off") is moved onto it; a grid that lands on nothing gets `usable: false`, and `--snap-beats` ignores it. `--plot` draws the band, the kicks (green marks) and the grid (red lines): the marks sit on the lines, or do not trust the grid. If the music is yours and can be fitted to the picture: `beats.py FILM --suggest-offset work/moments.json` says how far to shift the music so cuts and hits land on beats (advice only; the music is not touched). **`from_cues.py`**: `python scripts/from_cues.py LIST|PROJECT_FOLDER|SCRIPT.cjs|- --video RENDER.mp4 --out work/cues.json` (`-` reads the list from stdin; a BOM from PowerShell is understood). What it does and says by itself: - **is it the right render**: the list misses the picture (`VERDICT`); **a design-time list against a render timed to the voice**: a time map from the project's anchors (`timing.json` with `anchors` or `WARP`, `src/timing.js`) or from the onsets of the synthesized stems, each event lands on its own onset (`time map`); `--time-map FILE`, `--warp off|stems|audio`; - **synthesis under the list**: a whoosh lands on the peak of the synthesized sound, its length is measured from it (`retime:`); no move if the peak belongs to another sound (pop, bell) or the list time is already the centre of the whoosh: named with the reason; synthesis onsets with no event in the list are listed (`--add-unlisted tick` turns them into events); - **timbre**: the brightness of the whooshes being replaced (centroid of the synthesized layer) feeds the pick (`timbre:`); `--tone airy|dark` sets it by hand; - **an unknown kind** (`bead`, `soft`): it shows how the project defines it. Say it in one line, no file needed: `--kind bead=click`, `--kind soft=pop`, a role with limits `--kind bead=role:click,max_dur=0.3,onsets_max=1`, `--kind bead=slices:740,763` (single sounds from these recordings; the quietest ones, 12 dB down, are not taken), `--map '{"glass":{"ids":[65,54],"role":"chime"}}'` (`ids` in turn; an element `{"id":800,"slice":[0.78,0.12]}`); `--remember` keeps it. Summary: `declared N events: M voiced, K silent`; the critique counts silent kinds as a hole; - **clusters**: events of one kind closer than 25 ms are one sound (`--fuse`), runs faster than 14/s are thinned (`--max-rate`), the output says how many of each (`thinned: key 23, tick 11`); - **a typing stretch** (`{"t":19.99,"type":"typing","len":0.36,"n":99}`) unfolds into keystrokes (`--type-rate`). **Silent animation without a list** (UI preview, illustration, motion graphics; all four blind tests on 2026-10-15 were like this). Automation reads brightness and sees 5–6 moves of ~40 in soft coloured animation, and `suggest_cues` draws only whooshes from them: the draft here is a skeleton, not an answer. The path on which four agents out of four finished the film: 1. `look.py FILM --out work/look`, then `find_moments.py FILM --out work/moments --fine`. 2. **Close-up frames in 2–3 s windows**: - SKILL.md (6987 bytes)
--- name: hyperframes-to-after-effects description: Convert a HyperFrames project (HTML/GSAP video compositions) into an editable Adobe After Effects project (.aep) with real layers and keyframes, not a rendered video. Text stays live text, cards become shape layers, images and video become footage, sub-compositions become precomps, animation becomes keyframes, and the result is checked against the HyperFrames render frame by frame. Use this whenever someone wants to move, port, export or "hand off" a HyperFrames / HTML video to After Effects or AE, wants an .aep from their HyperFrames composition, wants to keep editing a HyperFrames film in After Effects, or asks why an AE import of their HTML animation is slow or broken, even if they do not say "skill" or name the tool. Windows and macOS. --- # HyperFrames to After Effects A HyperFrames film is a paused GSAP timeline over HTML. This skill plays it in headless Chrome frame by frame, records what every element looks like, and rebuilds that in After Effects as native, editable layers: | HyperFrames | After Effects | |---|---| | sub-composition (`data-composition-src`, nested `data-composition-id`) | precomp at its start, trimmed to its visible window | | text node (each rendered line) | text layer, live font; changing strings become native recipes (below) | | box with background / border / radius / outline / hard shadow | shape layer (rounded rect, fill, stroke, dashes) | | soft `box-shadow` / `text-shadow`, `filter: blur()`, `mix-blend-mode` | Drop Shadow, Gaussian Blur (keyed), blending mode | | gradients, background images, inset or multiple shadows, mixed radii | PNG painted by Chrome (transform and opacity still keyed) | | `<img>` (`object-fit`, rounded corners), `<video>` (trim, rate, volume) | footage layer with fit, crop mask, timing, audio level | | inline `<svg>` | PNG at 4x (a few looks: one layer each; many: a sequence) | | `<canvas>` (2D, three.js, Lottie) | PNG sequence with time remap | | `overflow: hidden`, `clip-path` (polygon, inset, circle, ellipse) | track matte (nested clips nest) | | `<audio>` | audio layer at its start, with its volume | Changing text never becomes per-frame Source Text keys: After Effects slows down project-wide once any layer has them (one 150-key layer makes every later scripted edit ~200x slower, a 3,000-key film took hours). Instead: counters → a Count slider + expression (or pure `time` expression when the number follows time), typing → Text Animator, a few strings or captions → one trimmed layer per string, scrambles → a small `[time, text]` expression table, colour changes → Fill Color animator. ## Before you start Run the doctor and read it to the user in plain words: ```bash node <skill>/scripts/hf2ae.mjs doctor <project> ``` - **Node 18+, the project's HyperFrames CLI and its Chrome.** The tool reuses what HyperFrames already installed (puppeteer-core, fontkit, sharp, Chrome) from the npx cache. If Chrome is missing, `npx hyperframes browser ensure` downloads it: ask the user before running it. - **After Effects** (any recent version; 2023+ for the track-matte API) with *Preferences → Scripting & Expressions → Allow Scripts to Write Files and Access Network* switched on. Ask the user to check it; the build cannot set it. - **ffmpeg** for verification (HyperFrames rendering needs it anyway) and for converting WebM/OGG media. Ask the user (only what you cannot infer): 1. Where to save the `.aep` (default `<project>/after-effects/project.aep`). 2. If After Effects is open with a project: build into that open project (`--into-open`), or save and close it first. Never close, save over or discard the user's open project yourself. 3. Frame rate: the project's render rate if known (`hyperframes render -f`), else 30. Use 60 for fast UI motion. ## Workflow ```bash node <skill>/scripts/hf2ae.mjs export <project> --out <dir> [--fps 30] # Chrome only, no After Effects node <skill>/scripts/hf2ae.mjs build --out <dir> [--aep <file>] [--into-open] node <skill>/scripts/hf2ae.mjs verify <project> --out <dir> [--frames 8] node <skill>/scripts/hf2ae.mjs all <project> --out <dir> ... # the three in a row ``` `<skill>` is this skill's folder. Run steps one at a time the first time on a project, so problems surface at the step that caused them. 1. **Export** writes `<dir>/manifest.json`, `<dir>/comps/*.json`, `<dir>/assets/`, `<dir>/fonts/` and `<dir>/export_report.txt`. Read the report before building: its *fonts* list says which real face every CSS family resolves to (aliases such as `"Brand Sans"` are read from the font files), and *warnings* lists what was approximated. Tell the user about warnings that affect what they will see. 2. **Build** starts After Effects (or uses the open one), writes progress to `<dir>/ae_status.txt` and a log to `<dir>/ae_build_log.txt`, saves after every composition. Typical films build in under a minute. If it runs for minutes on one layer, stop and read the log rather than waiting: see `references/troubleshooting.md`. 3. **Verify** renders the `.aep` with `aerender` and puts After Effects and HyperFrames side by side in `<dir>/verify/compare.png`, with SSIM per moment in `<dir>/verify/report.txt`. Open the sheet and look at it. SSIM tells you where to look, your eyes tell you what is wrong: typical numbers are 0.98+ with the original fonts and 0.95–0.99 with substitutes. Fix causes in the export or build (not by hand in After Effects), rebuild, re-verify. ## Fonts After Effects only sees fonts installed **for all users** (on Windows a per-user install is invisible to it). The build uses the real face when After Effects has it; otherwise it picks the closest installed face of the same kind (sans / serif / mono), fits each line to the width it had in the film (so words placed side by side keep their spaces), and writes the original font into the layer comment. The files to install are in `<dir>/fonts/` (Google Fonts are fetched as TTF). Offer the user that choice: install them for all users, restart After Effects, run `build` again (no re-export needed). Installing fonts is the user's action, not yours. ## Reporting back Tell the user, briefly: where the `.aep` is; what became what (precomps, text, shapes, footage); which fonts were substituted and how to get the originals; the warnings that matter; the verify result with the sheet. Mention what stays approximate (3D transforms flattened to 2D, CSS filters other than blur, painted PNGs for gradients, blend modes that After Effects mixes slightly differently) so nothing surprises them in After Effects. ## Going deeper - `references/how-it-works.md`: the export format, keyframe reduction, text recipes, mattes, timing of precomps and media. Read it before changing the scripts. - `references/troubleshooting.md`: slow or stuck builds, After Effects not running the script, fonts, mismatched frames, macOS specifics.
- skills/hyperframes-to-after-effects/README.md (1270 bytes)
# hyperframes-to-after-effects A Claude Code skill that turns a HyperFrames project into an editable After Effects project: live text, shape layers, footage, precomps and keyframes, checked frame by frame against the HyperFrames render. ## Install Copy this folder to your Claude Code skills folder and restart Claude Code: - Windows: `%USERPROFILE%\.claude\skills\hyperframes-to-after-effects` - macOS: `~/.claude/skills/hyperframes-to-after-effects` Or install the `.skill` package from the Claude app (Save skill). Then ask Claude, in your HyperFrames project: "convert this to an After Effects project". ## Needs - Node 18+ and a HyperFrames project that renders (`npx hyperframes render` works). The skill reuses HyperFrames' own Chrome, puppeteer, fontkit and sharp; it installs nothing. - Adobe After Effects (2023 or newer) on Windows or macOS, with *Preferences → Scripting & Expressions → Allow Scripts to Write Files and Access Network* on. - ffmpeg (for the frame-by-frame check and WebM/OGG media). ## Run by hand ```bash node scripts/hf2ae.mjs doctor <project> node scripts/hf2ae.mjs all <project> --out <folder> [--fps 30] [--aep <file.aep>] ``` See `SKILL.md` for what maps to what and `references/` for internals and troubleshooting.
- skills/hyperframes-to-after-effects/references/how-it-works.md (8371 bytes)
# How hyperframes-to-after-effects works Read this before changing the scripts. Files: | File | Role | |---|---| | `scripts/hf2ae.mjs` | CLI: `doctor`, `export`, `build`, `verify`, `all` | | `scripts/lib/env.mjs` | finds the hyperframes package in the npx cache (runtime, puppeteer-core, fontkit, sharp), its Chrome, After Effects, aerender, ffmpeg | | `scripts/lib/page.mjs` | serves the raw project with the HyperFrames runtime injected at the start of `<head>` (as Studio does), waits for `window.__renderReady`, seeks with `__player.renderSeek(t, {exact:true})` → `__hf.seek` → timelines; fetches Google Fonts the page uses but does not declare | | `scripts/lib/sampler.js` | runs in the page: `prepare()` (composition tree; `::before/::after` and one-sided borders rewritten as real elements), `sample()` (one frame), `canvases()`, `audio()`, `fontFaces()` | | `scripts/lib/export.mjs` | frame loop, keyframe reduction, assets, text plans, fonts, `manifest.json` | | `scripts/lib/text.mjs` | text recipes | | `scripts/lib/fonts.mjs` | CSS family/weight/style → real family/style/PostScript name from the font file (fontkit) | | `scripts/lib/ae.mjs` | writes `<out>/run_build.jsx` (sets `$.global.HF2AE`, evaluates `scripts/ae/build.jsx`) and runs it: Windows `AfterFX.exe -r`, macOS `osascript … DoScriptFile`; polls `<out>/ae_status.txt` | | `scripts/ae/build.jsx` | ExtendScript (ES3) builder | | `scripts/lib/verify.mjs` | aerender → frames → SSIM + `verify/compare.png` | ## Loader parity The page is the same thing Studio previews, so it matches `hyperframes snapshot` (SSIM 0.99+ measured). The loader reads authored timing from the runtime: each sub-composition's start is `__timelines[id].startTime()` within its parent; its visible window comes from sampling the host's `visibility` per frame (the runtime strips the host's `data-duration`). ## Sampling model Every frame `f` of the root (at `--fps`), `sample()` walks each visible composition from its root element: - **Placement.** For each element the composed 2×2 linear transform `L` (product of CSS transforms down the tree) and the top-left of its untransformed box in the composition (`placement()`); After Effects gets anchor (0,0), position X/Y (separated, so nothing curves in space), scale from `|L col 1|` and `det/|col 1|`, rotation from `atan2`. Skew is not representable and is folded into scale. - **Opacity** multiplies down the tree; `visibility: hidden` is 0; text colour alpha multiplies in. - **Blur** combines down the tree as `sqrt(Σσ²)` and goes on every layer below the filtered element. - **Keys** are reduced per track with Ramer–Douglas–Peucker (position 0.25 px, scale 0.15 %, rotation 0.05°, opacity 0.4 %). Linear keys between samples reproduce any easing at the sample rate. Absent frames hold the nearest state at opacity 0. - **Paint order** inside a composition: the list of `z-index` values of every positioned ancestor that sets one, outermost first (so a cursor at `z-index: 2` inside a rig at `z-index: 50` stays above a card at `z-index: 3`), compared level by level with a missing level as 0, then document order. Stacking contexts made by opacity, transforms or filters without a `z-index` are not modelled. - **Keys** (`k`): composition-relative DOM path with tag, `#id` or first class, and sibling index. Text lines add `#t<node>.<line>`; variants add `@<signature>`. ## Entry types to layers | Type | Export | Build | |---|---|---| | `comp` | host placement, child `cid`, `startF`, `inF`/`outF` from the child's visible frames | precomp layer, `startTime`, in/out | | `box` | size, radius (top-left), bg RGBA, border (top side), dashed flag, outline, hard shadow, soft shadow | shape layer: Box / Outline / Shadow groups; Drop Shadow effect for soft shadows | | `bake` | computed background / border / radius / shadow / outline, padding for the shadow | PNG at 2x painted in a blank page, `scaleMul` 0.5, anchor offset by the padding | | `svg` | serialized markup with `currentColor` resolved | PNG at 4x (`scaleMul` 0.25) | | `still` | (svg or bake with ≤ 6 looks) | footage layer; one per look, opacity switches between them | | `seq` | (svg or bake with > 6 looks) PNG per distinct look + per-frame index | sequence + time remap | | `canvas` | backing size, CSS-to-backing scale folded into `L`; PNGs only when pixels change | sequence (`canvasFps`) + time remap | | `image` / `video` | natural size, `object-fit`, `object-position`, radius; video: `data-start`, `data-duration`, `data-media-start`, `data-playback-rate`, muted, `data-has-audio`, `data-volume` | footage, scale = fit, anchor = −offset/scale, mask for crop/radius; video `stretch`, `startTime`, in/out, Audio Levels dB | | `text` | per rendered line: string, family list, weight, style, size, letter-spacing, ink width in the real face, colour, stroke, text-shadow, baseline origin `lx/ly` | text layer, left-justified at the baseline origin; recipes below | | `clip` | overflow box (rounded rect) or `clip-path` (polygon → path, inset → rounded rect, circle/ellipse) in the element's local box, plus its own `clip` parent | disabled shape layer used as alpha track matte by every layer under it; nested clips matte the matte | Text that is uppercase via CSS is exported uppercase. A line that changes font, weight or size mid-layer keeps the first style (warned). ## Text recipes (`text.mjs`) Holds of the string over the layer's frames give runs. Then: 1. one run → static; 2. every run has the same template with digits (`"#%"`, `"About # min left"`, `"#:#"`, `"#:#:#:#"`) → **counter**: digit groups read as one mixed-radix number (radix 60 / 100 / 1000 from the largest value seen); if `value == floor(a + b·frame)` for all keys the expression reads `time` (no keys at all), else a Count slider with hold keys drives it; padding is kept; 3. a tail of runs where each extends the previous by characters (≥ 3) → **typing**: final text + Text Animator (opacity 0, Range Start in %, hold keys); earlier runs (placeholders) become trimmed layers; 4. ≤ 4 runs, or ≤ 60 runs that each stay ≥ 0.3 s (captions) → **split**: one trimmed layer per string; 5. otherwise → **table**: `[time, text]` expression. Colour changes add a Fill Color animator; a key holds unless the next comes within 2 frames (a fade). ## Fonts `fonts.mjs` resolves each used (family list, weight, style): the `@font-face` rule the page declares (weight ranges honoured) → read the file with fontkit (typographic family name ID 16, else family with any default-instance style word removed for variable fonts) → real family/style/PostScript name. Families not declared but available on the system keep their CSS name. Google families fetched by `page.mjs` have TTF copies in `<out>/fonts`. `build.jsx` matches against `app.fonts.allFonts` by family (then CSS family), nearest weight, same italic, avoiding substitutes. Missing → first installed of the category list (sans: Inter, Helvetica Neue, Helvetica, Arial, Segoe UI, Roboto; serif: Playfair Display, Georgia, Times New Roman; mono: JetBrains Mono, Roboto Mono, SF Mono, Menlo, Consolas, Courier New) and the line is scaled horizontally to the ink width measured in the real face (`sourceRectAtTime` vs `tw`, kept within 0.6–1.4). ## After Effects rules learned the hard way - **No Source Text keyframes** from scripts (project-wide slowdown, see SKILL.md). Expressions on Source Text are fine. - **Time Remap**: never remove the two default keys in a loop (`while (numKeys) removeKey(1)` can spin forever); overwrite them with `setValueAtKey`. - **`setValuesAtTimes`** per property, not `setValueAtTime` per key. No undo group around a whole build. - Static numbers in tracks are `{v: …}`; test `v !== undefined`, never truthiness (a `0` value is real). - `AfterFX.exe -r` started cold runs the script and quits; with After Effects open it runs in that window. - `CompItem.saveFrameToPng` is asynchronous and unreliable under `-r`: verify with aerender instead. - Drop Shadow opacity is 0–255; Gaussian Blur needs *Repeat Edge Pixels* off to blur edges like CSS. - CSS `blur(σ)` → Blurriness `2σ` (`BLUR_K` in `build.jsx`). - The build refuses to run into a non-empty open project unless `--into-open`: it never closes or saves over the user's work. - skills/hyperframes-to-after-effects/references/troubleshooting.md (2981 bytes)
# Troubleshooting ## The build sits on one step for minutes Read `<out>/ae_status.txt` (current layer) and `<out>/ae_build_log.txt` (layers over 3 s are logged as "slow layer"). A healthy build is ~10–50 ms per layer. If one layer type is slow, the usual cause is a property written key by key or Source Text keys; fix the builder, do not wait it out. To stop a stuck build, ask the user to press *Cancel* in After Effects' "Executing script" dialog or to close After Effects (their own projects are their call). ## After Effects never starts the script ("never started the script") - *Preferences → Scripting & Expressions → Allow Scripts to Write Files and Access Network* must be on. - A modal dialog in After Effects (crash recovery, missing fonts, update) blocks scripts: close it. - macOS: the first `osascript` call asks for permission to control After Effects (System Settings → Privacy & Security → Automation). The app name must match the installed one (`Adobe After Effects 2026`). ## "After Effects has a project open with items in it" The builder will not mix the film into someone's open project uninvited. Ask the user: save and close their project, or rerun `build` with `--into-open` to add the film to it (it is then saved under the `--aep` path). ## Fonts look wrong - `export_report.txt` → *fonts* shows what each CSS family resolved to. A web font the page fetched from Google is saved as TTF in `<out>/fonts`. - `ae_build_log.txt` → "fonts substituted" lists faces After Effects could not find. Install those files **for all users** (Windows: right click → *Install for all users*), restart After Effects, run `build` again. - Text a few pixels off: substitutes are fitted per line to the original width; the fit factor is in the layer comment. ## A frame does not match in `verify/compare.png` 1. Confirm the right side (HyperFrames) is correct: it comes from the same loader as `hyperframes snapshot`. 2. Find the element in `<out>/comps/<cid>.json` by its key path and check the sampled tracks at that frame (`frame = t × fps` minus the composition's start). 3. Wrong everywhere in a precomp → check its `startF` / `inF` / `outF` in the parent. 4. Element missing → `export_report.txt` warnings (unsupported clip-path, tainted canvas, filters). 5. Blur strength off → adjust `BLUR_K` in `scripts/ae/build.jsx`. ## The export is slow Sampling costs one page evaluation per frame (~15–30 frames/s). A long film at 60 fps takes minutes; use `--fps 30` unless the motion needs 60. Canvases are captured at `--canvas-fps` (default: fps, halved above 30). ## A canvas exports blank WebGL canvases without `preserveDrawingBuffer` can read back empty. Set `preserveDrawingBuffer: true` on the renderer in the project, or accept a still. ## Media WebM / OGG video and audio are converted with ffmpeg (H.264 / WAV). WebP / AVIF / SVG images are converted to PNG with sharp. Remote URLs are downloaded into `<out>/assets`. - skills/hyperframes-to-after-effects/scripts/ae/build.jsx (31333 bytes)
// build.jsx: builds an editable After Effects project from a hyperframes-to-after-effects export folder. // Run through scripts/hf2ae.mjs (it writes a small wrapper that sets HF2AE before evaluating this file): // HF2AE = { out: "<export folder>", aep: "<file to save>", intoOpen: false } // Progress: <out>/ae_status.txt (current step), <out>/ae_build_log.txt (per composition, timings, problems). // ExtendScript is ES3: no let/const, arrow functions, Array.map/indexOf or JSON. // Never writes Source Text keyframes: they make every later scripted edit in the project crawl (see text recipes). (function () { var CFG = $.global.HF2AE; var OUT = CFG.out.replace(/\\/g, "/").replace(/\/$/, "") + "/"; var T0 = new Date().getTime(); function sec() { return ((new Date().getTime() - T0) / 1000).toFixed(1) + "s"; } function writeFile(p, s, mode) { var f = new File(p); f.encoding = "UTF-8"; f.open(mode || "w"); f.write(s); f.close(); } function log(s) { writeFile(OUT + "ae_build_log.txt", "[" + sec() + "] " + s + "\n", "a"); } function status(s) { writeFile(OUT + "ae_status.txt", "[" + sec() + "] " + s); } function readJSON(p) { var f = new File(p); f.encoding = "UTF-8"; f.open("r"); var s = f.read(); f.close(); return eval("(" + s + ")"); } writeFile(OUT + "ae_build_log.txt", ""); log("start, After Effects " + app.version); app.beginSuppressDialogs(); try { build(); log("DONE"); status("DONE"); } catch (e) { log("FAILED: " + e.toString() + (e.line ? " (line " + e.line + ")" : "")); status("FAILED: " + e.toString()); } finally { app.endSuppressDialogs(false); } function build() { var M = readJSON(OUT + "manifest.json"); var FPS = M.fps; var proj = app.project; if (!CFG.intoOpen && proj.numItems > 0) throw new Error("After Effects has a project open with items in it; save and close it (File > Close Project), or build with --into-open"); var aepFile = new File(CFG.aep); proj.save(aepFile); log("saving to " + aepFile.fsName); var HOLD = KeyframeInterpolationType.HOLD, LINEAR = KeyframeInterpolationType.LINEAR; function folder(name, parent) { var f = proj.items.addFolder(name); if (parent) f.parentFolder = parent; return f; } var projName = M.project.replace(/\\/g, "/").split("/").pop(); var fRoot = folder(projName + " (HyperFrames)"), fComps = folder("Compositions", fRoot), fFoot = folder("Footage", fRoot), fSeq = folder("Sequences", fRoot), fAudio = folder("Audio", fRoot), fSolids = folder("Solids", fRoot); // ------------------------------------------------------------ helpers function cssRGB(s) { var m = String(s).match(/[\d.]+/g); if (!m) return null; return { c: [m[0] / 255, m[1] / 255, m[2] / 255], a: m.length > 3 ? +m[3] : 1 }; } function isStatic(tr) { return tr.v !== undefined; } function first(tr) { return tr.v !== undefined ? tr.v : tr.k[0][1]; } function anyOf(tr, fn) { if (!tr) return false; if (tr.v !== undefined) return fn(tr.v); for (var i = 0; i < tr.k.length; i++) if (fn(tr.k[i][1])) return true; return false; } function apply(prop, tr, map, hold) { if (!tr) return; if (tr.v !== undefined) { prop.setValue(map(tr.v)); return; } var times = [], vals = []; for (var i = 0; i < tr.k.length; i++) { times.push(tr.k[i][0] / FPS); vals.push(map(tr.k[i][1])); } prop.setValuesAtTimes(times, vals); if (hold) holdAll(prop); } function holdAll(prop) { for (var j = 1; j <= prop.numKeys; j++) prop.setInterpolationTypeAtKey(j, HOLD, HOLD); } // position split into X / Y so nothing curves in space; scale multiplied by [mx, my] (footage scale, fit) function transform(layer, L, mul, anchor) { var tg = layer.property("ADBE Transform Group"); tg.property("ADBE Anchor Point").setValue(anchor || [0, 0]); tg.property("ADBE Position").dimensionsSeparated = true; apply(tg.property("ADBE Position_0"), L.pos, function (v) { return v[0]; }); apply(tg.property("ADBE Position_1"), L.pos, function (v) { return v[1]; }); var m = mul || [1, 1]; apply(tg.property("ADBE Scale"), L.scale, function (v) { return [v[0] * m[0], v[1] * m[1]]; }); apply(tg.property("ADBE Rotate Z"), L.rot, function (v) { return v[0]; }); apply(tg.property("ADBE Opacity"), L.op, function (v) { return v[0]; }); } // CSS blur(σ) -> Gaussian Blur; mix-blend-mode -> blending mode var BLEND = { "multiply": "MULTIPLY", "screen": "SCREEN", "overlay": "OVERLAY", "darken": "DARKEN", "lighten": "LIGHTEN", "color-dodge": "COLOR_DODGE", "color-burn": "COLOR_BURN", "hard-light": "HARD_LIGHT", "soft-light": "SOFT_LIGHT", "difference": "DIFFERENCE", "exclusion": "EXCLUSION", "hue": "HUE", "saturation": "SATURATION", "color": "COLOR", "luminosity": "LUMINOSITY" }; var BLUR_K = 2.0; // After Effects Blurriness per CSS blur px (calibrated by verify) function effects(layer, L) { if (L.blur && anyOf(L.blur, function (v) { return v[0] > 0.05; })) { var gb = layer.property("ADBE Effect Parade").addProperty("ADBE Gaussian Blur 2"); apply(gb.property("ADBE Gaussian Blur 2-0001"), L.blur, function (v) { return v[0] * BLUR_K; }); gb.property("ADBE Gaussian Blur 2-0003").setValue(0); } if (L.blend && BLEND[L.blend]) layer.blendingMode = BlendingMode[BLEND[L.blend]]; if (L.soft) { // soft shadow [x, y, blur, r, g, b, a] -> Drop Shadow var ds = layer.property("ADBE Effect Parade").addProperty("ADBE Drop Shadow"); apply(ds.property("ADBE Drop Shadow-0001"), L.soft, function (v) { return [v[3], v[4], v[5]]; }); apply(ds.property("ADBE Drop Shadow-0002"), L.soft, function (v) { return v[6] * 255; }); apply(ds.property("ADBE Drop Shadow-0003"), L.soft, function (v) { return (Math.atan2(v[0], -v[1]) * 180) / Math.PI; }); apply(ds.property("ADBE Drop Shadow-0004"), L.soft, function (v) { return Math.sqrt(v[0] * v[0] + v[1] * v[1]); }); apply(ds.property("ADBE Drop Shadow-0005"), L.soft, function (v) { return v[2]; }); } } function rectGroup(contents, name) { var g = contents.addProperty("ADBE Vector Group"); g.name = name; var c = g.property("ADBE Vectors Group"); return { g: g, c: c, r: c.addProperty("ADBE Vector Shape - Rect") }; } // a rounded rectangle as a bezier Shape (masks have no roundness of their own) function rrectShape(x, y, w, h, r) { r = Math.max(0, Math.min(r, w / 2, h / 2)); var s = new Shape(), k = 0.5523 * r; if (r < 0.01) { s.vertices = [[x, y], [x + w, y], [x + w, y + h], [x, y + h]]; s.closed = true; return s; } s.vertices = [[x + r, y], [x + w - r, y], [x + w, y + r], [x + w, y + h - r], [x + w - r, y + h], [x + r, y + h], [x, y + h - r], [x, y + r]]; s.inTangents = [[-k, 0], [0, 0], [0, -k], [0, 0], [k, 0], [0, 0], [0, k], [0, 0]]; s.outTangents = [[0, 0], [k, 0], [0, 0], [0, k], [0, 0], [-k, 0], [0, 0], [0, -k]]; s.closed = true; return s; } function ellipseShape(cx, cy, rx, ry) { var s = new Shape(), kx = 0.5523 * rx, ky = 0.5523 * ry; s.vertices = [[cx, cy - ry], [cx + rx, cy], [cx, cy + ry], [cx - rx, cy]]; s.inTangents = [[-kx, 0], [0, -ky], [kx, 0], [0, ky]]; s.outTangents = [[kx, 0], [0, ky], [-kx, 0], [0, -ky]]; s.closed = true; return s; } function polyShape(pts) { var s = new Shape(); s.vertices = pts.length ? pts : [[0, 0]]; s.closed = true; return s; } // ------------------------------------------------------------ fonts: the real face when After Effects has it, // else the closest installed face of the same kind (and its width is fitted to the original, per text layer) var AEF = []; try { var all = app.fonts.allFonts; for (var a = 0; a < all.length; a++) for (var b = 0; b < all[a].length; b++) AEF.push(all[a][b]); } catch (eF) {} function styleWeight(s) { s = String(s).toLowerCase().replace(/[\s_-]/g, ""); var w = 400; if (/thin|hairline/.test(s)) w = 100; else if (/extralight|ultralight/.test(s)) w = 200; else if (/light/.test(s)) w = 300; else if (/semibold|demibold/.test(s)) w = 600; else if (/extrabold|ultrabold/.test(s)) w = 800; else if (/black|heavy/.test(s)) w = 900; else if (/bold/.test(s)) w = 700; else if (/medium/.test(s)) w = 500; return w; } function faceIn(family, weight, italic) { var best = null, bs = 1e9, fam = String(family).toLowerCase(); for (var i = 0; i < AEF.length; i++) { var f = AEF[i]; if (String(f.familyName).toLowerCase() !== fam && String(f.nativeFamilyName || "").toLowerCase() !== fam) continue; var it = /italic|oblique/i.test(f.styleName); var s = Math.abs(styleWeight(f.styleName) - weight) + (it !== italic ? 1000 : 0) + (f.isSubstitute ? 5000 : 0); if (s < bs) { bs = s; best = f; } } return best; } var FALLBACK = { sans: ["Inter", "Helvetica Neue", "Helvetica", "Arial", "Segoe UI", "Roboto"], serif: ["Playfair Display", "Georgia", "Times New Roman", "Times"], mono: ["JetBrains Mono", "Roboto Mono", "SF Mono", "Menlo", "Consolas", "Courier New"] }; var FONTS = {}, fontNotes = []; for (var fi = 0; fi < M.fonts.length; fi++) { var R = M.fonts[fi], face = faceIn(R.family, R.weight, R.italic), sub = false; if (!face && R.cssFamily !== R.family) face = faceIn(R.cssFamily, R.weight, R.italic); if (!face) { var list = FALLBACK[R.category] || FALLBACK.sans; for (var li = 0; li < list.length && !face; li++) face = faceIn(list[li], R.weight, R.italic); sub = true; } FONTS[R.css] = { ps: face ? face.postScriptName : "ArialMT", sub: sub || !face, name: face ? face.familyName + " " + face.styleName : "Arial" }; if (sub) fontNotes.push(R.family + " " + R.style + " -> " + FONTS[R.css].name + (R.file ? " (install " + R.file + " to use the original)" : "")); } if (fontNotes.length) log("fonts substituted (width fitted per layer): " + fontNotes.join("; ")); // ------------------------------------------------------------ footage (imported once each) var footage = {}; function importFile(rel, opts) { var key = rel + (opts && opts.seq ? "#seq" : ""); if (footage[key]) return footage[key]; var io = new ImportOptions(new File(OUT + rel)); if (opts && opts.seq) { io.sequence = true; io.forceAlphabetical = true; } var it = proj.importFile(io); it.parentFolder = opts && opts.folder ? opts.folder : fFoot; if (opts && opts.seq && opts.fps) it.mainSource.conformFrameRate = opts.fps; footage[key] = it; return it; } // ------------------------------------------------------------ text function jsStr(s) { return '"' + String(s).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\r?\n/g, "\\r") + '"'; } function srcOf(layer) { return layer.property("ADBE Text Properties").property("ADBE Text Document"); } function makeText(comp, L, txt) { var D = L.doc0, F = FONTS[D.ff + "|" + D.fw + "|" + D.fst] || { ps: "ArialMT", sub: true }; var layer = comp.layers.addText(txt || " "); var sp = srcOf(layer), td = sp.value; td.resetCharStyle(); td.resetParagraphStyle(); td.text = txt || " "; try { td.font = F.ps; } catch (e) {} td.fontSize = D.fs; td.applyFill = true; td.fillColor = D.col; if (L.stroke) { td.applyStroke = true; td.strokeColor = [L.stroke.c[0], L.stroke.c[1], L.stroke.c[2]]; td.strokeWidth = L.stroke.w; td.strokeOverFill = false; } else td.applyStroke = false; td.tracking = Math.round(D.ls * 1000); td.justification = ParagraphJustification.LEFT_JUSTIFY; // a substitute face is fitted to the width the text had in the film; measure the string the film measured var fitK = 1; if (F.sub && D.tw > 0 && D.txt) { td.text = D.txt; sp.setValue(td); var rw = layer.sourceRectAtTime(0, false).width; if (rw > 0) fitK = D.tw / rw; td.text = txt || " "; } sp.setValue(td); transform(layer, L); apply(layer.property("ADBE Transform Group").property("ADBE Anchor Point"), L.anchor, function (v) { return [v[0], v[1]]; }); effects(layer, L); layer.comment = "font: " + F.ps + (F.sub ? " (stands in for " + D.ff.split(",")[0] + ")" : ""); // so words set side by side keep their spaces if (F.sub && txt) { var k = fitK; if (k > 0.6 && k < 1.4 && Math.abs(k - 1) > 0.005) { var sc = layer.property("ADBE Transform Group").property("ADBE Scale"); if (sc.numKeys === 0) { var sv = sc.value; sc.setValue([sv[0] * k, sv[1]]); } else for (var j = 1; j <= sc.numKeys; j++) { var kv = sc.keyValue(j); sc.setValueAtKey(j, [kv[0] * k, kv[1]]); } layer.comment += ", width x" + k.toFixed(3); } } layer.name = (txt || "text").substr(0, 40); return layer; } function trim(layer, from, to) { layer.inPoint = from / FPS; if (to !== null && to !== undefined) layer.outPoint = to / FPS; return { l: layer, trimmed: true }; } function animator(layer, name) { var an = layer.property("ADBE Text Properties").property("ADBE Text Animators").addProperty("ADBE Text Animator"); an.name = name; return { an: an, sel: an.property("ADBE Text Selectors").addProperty("ADBE Text Selector"), props: an.property("ADBE Text Animator Properties") }; } function colourAnimator(layer, colors) { var fc = animator(layer, "Colour").props.addProperty("ADBE Text Fill Color"); var t = [], v = []; for (var i = 0; i < colors.length; i++) { t.push(colors[i][0] / FPS); v.push(colors[i][1]); } fc.setValuesAtTimes(t, v); for (var j = 0; j < colors.length; j++) if (colors[j][2]) fc.setInterpolationTypeAtKey(j + 1, LINEAR, HOLD); } function textLayers(comp, L) { var P = L.plan, out = [], lay, i; if (P.mode === "static") out.push({ l: makeText(comp, L, P.txt) }); else if (P.mode === "counter") { lay = makeText(comp, L, L.doc0.txt); var src; if (P.linear) src = "// the number follows time\nvar v = Math.floor(" + P.linear.a.toFixed(6) + " + " + P.linear.b.toFixed(6) + " * time + 1e-6);\n"; else { var sl = lay.property("ADBE Effect Parade").addProperty("ADBE Slider Control"); sl.name = "Count"; var spp = sl.property("ADBE Slider Control-0001"), ts = [], vs = []; for (i = 0; i < P.keys.length; i++) { ts.push(P.keys[i][0] / FPS); vs.push(P.keys[i][1]); } spp.setValuesAtTimes(ts, vs); holdAll(spp); src = "// the Count slider drives the number\nvar v = Math.round(effect(\"Count\")(1));\n"; } var rad = [], pads = [], parts = []; for (i = 0; i < P.rad.length; i++) { rad.push(P.rad[i] === null ? 0 : P.rad[i]); pads.push(P.pads[i]); } for (i = 0; i < P.part - skills/hyperframes-to-after-effects/scripts/hf2ae.mjs (3671 bytes)
#!/usr/bin/env node // hf2ae: HyperFrames project -> editable After Effects project. // node hf2ae.mjs doctor <project> what is installed, what is missing // node hf2ae.mjs export <project> --out <dir> [--fps 30] sample the film into <dir> (Chrome only, no After Effects) // node hf2ae.mjs build --out <dir> [--aep file.aep] [--into-open] [--ae "2026"] build the .aep in After Effects // node hf2ae.mjs verify <project> --out <dir> [--frames 8] render the .aep with aerender, compare with HyperFrames // node hf2ae.mjs all <project> --out <dir> ... export + build + verify import { resolve, join } from "node:path"; import { existsSync, readFileSync } from "node:fs"; import { resolveHyperframes, resolveChrome, resolveAE, resolveFfmpeg, aeRunning, IS_WIN, IS_MAC } from "./lib/env.mjs"; const argv = process.argv.slice(2); const cmd = argv[0]; const opt = (name, def) => { const i = argv.indexOf("--" + name); return i >= 0 ? (argv[i + 1] && !argv[i + 1].startsWith("--") ? argv[i + 1] : true) : def; }; const positional = argv.slice(1).filter((a, i, arr) => !a.startsWith("--") && !(i > 0 && arr[i - 1].startsWith("--") && !["--into-open", "--no-verify"].includes(arr[i - 1]))); const project = positional[0] ? resolve(positional[0]) : null; const out = opt("out") ? resolve(opt("out")) : project ? join(project, "after-effects") : null; function needProject() { if (!project || !existsSync(join(project, "index.html"))) { console.error("give the HyperFrames project folder (the one with index.html)"); process.exit(2); } } async function main() { if (cmd === "doctor") { needProject(); const hf = resolveHyperframes(project); const chrome = resolveChrome(hf), ae = resolveAE(opt("ae")), ff = resolveFfmpeg(); console.log(JSON.stringify({ platform: process.platform, node: process.version, hyperframes: hf.version, chrome: chrome || null, afterEffects: ae ? ae.name : null, aerender: ae?.aerender || null, ffmpeg: ff, aeRunning: aeRunning() }, null, 1)); if (!chrome) console.log("Chrome for HyperFrames is missing: `npx hyperframes browser ensure` downloads it (ask the user first)."); if (!ae) console.log("After Effects not found: export still works; build needs After Effects on this machine."); return; } if (cmd === "export" || cmd === "all") { needProject(); const { exportProject } = await import("./lib/export.mjs"); const hf = resolveHyperframes(project); const chrome = resolveChrome(hf); if (!chrome) throw new Error("Chrome for HyperFrames not found: run `npx hyperframes browser ensure` (after asking the user)"); await exportProject({ hf, chrome, projectDir: project, out, fps: +opt("fps", 30), canvasFps: opt("canvas-fps") ? +opt("canvas-fps") : undefined }); } if (cmd === "build" || cmd === "all") { const { buildInAE } = await import("./lib/ae.mjs"); await buildInAE({ out, aep: opt("aep") ? resolve(opt("aep")) : join(out, "project.aep"), intoOpen: opt("into-open", false) === true, prefer: opt("ae") }); } if (cmd === "verify" || (cmd === "all" && !opt("no-verify"))) { needProject(); const { verify } = await import("./lib/verify.mjs"); await verify({ project, out, aep: opt("aep") ? resolve(opt("aep")) : join(out, "project.aep"), frames: +opt("frames", 8), prefer: opt("ae") }); } if (!["doctor", "export", "build", "verify", "all"].includes(cmd)) { console.log(readFileSync(new URL(import.meta.url), "utf8").split("\n").slice(1, 8).map((l) => l.replace(/^\/\/ ?/, "")).join("\n")); } } main().catch((e) => { console.error("hf2ae: " + (e.stack || e.message)); process.exit(1); }); - skills/hyperframes-to-after-effects/scripts/lib/ae.mjs (3660 bytes)
// ae.mjs: runs scripts/ae/build.jsx in After Effects and waits for it. // Windows: AfterFX.exe -r <wrapper.jsx> (hands the script to a running After Effects, or starts one that runs it and quits) // macOS: osascript: tell application "Adobe After Effects <year>" to DoScript "$.evalFile(<wrapper.jsx>)" // After Effects needs Preferences > Scripting & Expressions > "Allow Scripts to Write Files and Access Network". import { writeFileSync, existsSync, readFileSync, rmSync } from "node:fs"; import { join, dirname } from "node:path"; import { fileURLToPath } from "node:url"; import { spawn } from "node:child_process"; import { resolveAE, aeRunning, IS_WIN, IS_MAC } from "./env.mjs"; const HERE = dirname(fileURLToPath(import.meta.url)); const fwd = (p) => p.replace(/\\/g, "/"); const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); export async function runJsx({ jsx, prefer, statusFile, timeoutMs = 30 * 60 * 1000, log = console.log }) { const ae = resolveAE(prefer); if (!ae) throw new Error("After Effects not found (looked in " + (IS_WIN ? "C:/Program Files/Adobe" : "/Applications") + ")"); if (statusFile && existsSync(statusFile)) rmSync(statusFile); const running = aeRunning(); log(`${ae.name}${running ? " (already open: the script runs in that window)" : " (starting it; it quits when the script ends)"}`); if (IS_WIN) spawn(ae.afterfx, ["-r", jsx], { detached: true, stdio: "ignore" }).unref(); // DoScript with $.evalFile sidesteps AppleScript's HFS / POSIX path formats else if (IS_MAC) spawn("osascript", ["-e", `with timeout of 7200 seconds\ntell application "${ae.appName}" to DoScript "$.evalFile(new File(${JSON.stringify(fwd(jsx)).replace(/"/g, "'")}))"\nend timeout`], { detached: true, stdio: "ignore" }).unref(); else throw new Error("After Effects runs on Windows and macOS only"); if (!statusFile) return; const t0 = Date.now(); let last = ""; while (Date.now() - t0 < timeoutMs) { await sleep(2000); if (!existsSync(statusFile)) { if (Date.now() - t0 > 180000) throw new Error("After Effects never started the script: enable Preferences > Scripting & Expressions > \"Allow Scripts to Write Files and Access Network\", close any open dialog in After Effects, and retry"); continue; } const s = readFileSync(statusFile, "utf8"); if (s !== last) { last = s; if (Date.now() - t0 > 5000) log(" " + s); } if (/\]\s*(DONE|FAILED)/.test(s)) return s; } throw new Error("After Effects script timed out; see " + statusFile); } export async function buildInAE({ out, aep, intoOpen, prefer, log = console.log }) { if (!existsSync(join(out, "manifest.json"))) throw new Error(`no export in ${out}: run the export step first`); const wrapper = join(out, "run_build.jsx"); writeFileSync(wrapper, `// written by hf2ae: runs the shared builder on this export\n$.global.HF2AE = ${JSON.stringify({ out: fwd(out), aep: fwd(aep), intoOpen: !!intoOpen })};\n$.evalFile(new File(${JSON.stringify(fwd(join(HERE, "..", "ae", "build.jsx")))}));\n`); const t0 = Date.now(); const st = await runJsx({ jsx: wrapper, prefer, statusFile: join(out, "ae_status.txt"), log }); const buildLog = existsSync(join(out, "ae_build_log.txt")) ? readFileSync(join(out, "ae_build_log.txt"), "utf8") : ""; log(buildLog.trim()); log(`build ${/DONE/.test(st) ? "finished" : "FAILED"} in ${((Date.now() - t0) / 1000).toFixed(0)} s -> ${aep}`); if (!/DONE/.test(st)) throw new Error("After Effects build failed: " + st); // After Effects writes the .aep asynchronously right after the script returns for (let i = 0; i < 30 && !existsSync(aep); i++) await sleep(1000); } - skills/hyperframes-to-after-effects/scripts/lib/env.mjs (6152 bytes)
// env.mjs: finds the tools a HyperFrames install already ships, so the converter installs nothing of its own: // the hyperframes package (runtime, puppeteer-core, fontkit, sharp) in the npx cache, its Chrome, After Effects, // aerender and ffmpeg. Works on Windows and macOS. import { execFileSync, spawnSync } from "node:child_process"; import { createRequire } from "node:module"; import { existsSync, readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { homedir, platform } from "node:os"; export const IS_WIN = platform() === "win32"; export const IS_MAC = platform() === "darwin"; // npm / npx are .cmd shims on Windows and need a shell; one quoted command string keeps Node from warning about it function sh(cmd, args, opts = {}) { const q = (a) => (/[\s"&|<>^]/.test(a) ? `"${a.replace(/"/g, '\\"')}"` : a); const r = IS_WIN ? spawnSync([cmd, ...args].map(q).join(" "), { encoding: "utf8", shell: true, ...opts }) : spawnSync(cmd, args, { encoding: "utf8", ...opts }); return { code: r.status, out: (r.stdout || "") + (r.stderr || "") }; } // the version the project pins in its package.json scripts ([email protected]), else null export function projectPin(projectDir) { const p = join(projectDir, "package.json"); if (!existsSync(p)) return null; const m = readFileSync(p, "utf8").match(/hyperframes@(\d+\.\d+\.\d+)/); return m ? m[1] : null; } function npxCacheDirs() { const dirs = []; const r = sh("npm", ["config", "get", "cache"]); const cache = r.code === 0 ? r.out.trim().split(/\r?\n/).pop() : null; for (const c of [cache, IS_WIN ? join(process.env.LOCALAPPDATA || "", "npm-cache") : join(homedir(), ".npm")]) { if (c && existsSync(join(c, "_npx")) && !dirs.includes(join(c, "_npx"))) dirs.push(join(c, "_npx")); } return dirs; } function findHyperframesPackages() { const found = []; for (const npx of npxCacheDirs()) { for (const d of readdirSync(npx)) { const pj = join(npx, d, "node_modules", "hyperframes", "package.json"); if (!existsSync(pj)) continue; try { found.push({ version: JSON.parse(readFileSync(pj, "utf8")).version, dir: join(npx, d, "node_modules", "hyperframes") }); } catch {} } } const num = (v) => v.split(".").map(Number).reduce((a, x) => a * 1000 + x, 0); return found.sort((a, b) => num(b.version) - num(a.version)); } // hyperframes package for this project: the pinned version if cached (fetched once via npx if not), else the newest export function resolveHyperframes(projectDir, { log = console.log } = {}) { const pin = projectPin(projectDir); let pkgs = findHyperframesPackages(); let pkg = pin ? pkgs.find((p) => p.version === pin) : pkgs[0]; if (!pkg) { const spec = pin ? `hyperframes@${pin}` : "hyperframes@latest"; log(`fetching ${spec} into the npx cache (same package the project's own scripts use)...`); sh("npx", ["--yes", spec, "--version"]); pkgs = findHyperframesPackages(); pkg = pin ? pkgs.find((p) => p.version === pin) : pkgs[0]; } if (!pkg) throw new Error("hyperframes package not found in the npx cache; run `npx hyperframes --version` once and retry"); const req = createRequire(join(pkg.dir, "package.json")); const runtime = ["dist/hyperframe-runtime.js", "dist/hyperframe.runtime.iife.js"].map((f) => join(pkg.dir, f)).find(existsSync); if (!runtime) throw new Error(`no HyperFrames runtime in ${pkg.dir}`); return { version: pkg.version, dir: pkg.dir, runtime, require: req }; } // Chrome that hyperframes renders with. `browser path` only reports; `browser ensure` may download (ask the user first). export function resolveChrome(hf) { const r = sh("npx", ["--yes", `hyperframes@${hf.version}`, "browser", "path"]); const line = r.out.split(/\r?\n/).map((s) => s.trim()).reverse().find((s) => /chrome|chromium/i.test(s) && existsSync(s)); if (line) return line; const cache = join(homedir(), ".cache", "puppeteer", "chrome"); if (existsSync(cache)) { for (const v of readdirSync(cache).sort().reverse()) { for (const rel of ["chrome-win64/chrome.exe", "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing", "chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing", "chrome-linux64/chrome"]) { if (existsSync(join(cache, v, rel))) return join(cache, v, rel); } } } return null; } // After Effects: the newest install unless one is named. Returns { app, version, afterfx (win), appName (mac), aerender } export function resolveAE(prefer) { const roots = IS_WIN ? ["C:/Program Files/Adobe"] : IS_MAC ? ["/Applications"] : []; const found = []; for (const root of roots) { if (!existsSync(root)) continue; for (const d of readdirSync(root)) { const m = d.match(/^Adobe After Effects (\d{4}|CC \d{4}|\d+(\.\d+)?)$/); if (!m) continue; const year = parseInt(m[1].replace("CC ", ""), 10); if (IS_WIN) { const afterfx = join(root, d, "Support Files", "AfterFX.exe"), aerender = join(root, d, "Support Files", "aerender.exe"); if (existsSync(afterfx)) found.push({ name: d, year, afterfx, aerender: existsSync(aerender) ? aerender : null }); } else { const app = join(root, d, `${d}.app`), aerender = join(root, d, "aerender"); if (existsSync(app)) found.push({ name: d, year, appName: d, app, aerender: existsSync(aerender) ? aerender : null }); } } } found.sort((a, b) => b.year - a.year); if (prefer) return found.find((f) => f.name.includes(prefer)) || null; return found[0] || null; } export function resolveFfmpeg() { for (const c of ["ffmpeg", "/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg"]) { const r = spawnSync(c, ["-version"], { encoding: "utf8" }); if (r.status === 0) return c; } return null; } export function aeRunning() { if (IS_WIN) { const r = sh("tasklist", ["/FI", "IMAGENAME eq AfterFX.exe", "/FO", "CSV", "/NH"]); return /AfterFX\.exe/i.test(r.out); } if (IS_MAC) return sh("pgrep", ["-f", "After Effects"]).code === 0; return false; } export { sh, execFileSync }; - skills/hyperframes-to-after-effects/scripts/lib/export.mjs (22909 bytes)
// export.mjs: drives a HyperFrames project frame by frame in headless Chrome and writes everything After Effects needs // to rebuild it as editable layers: <out>/manifest.json, <out>/comps/<cid>.json, <out>/assets/... and a report. import { mkdirSync, writeFileSync, existsSync, rmSync, copyFileSync, readFileSync } from "node:fs"; import { join, dirname, extname, basename, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { createHash } from "node:crypto"; import { spawnSync } from "node:child_process"; import { openProject } from "./page.mjs"; import { planText } from "./text.mjs"; import { resolveFonts } from "./fonts.mjs"; import { resolveFfmpeg } from "./env.mjs"; const HERE = dirname(fileURLToPath(import.meta.url)); const r4 = (v) => Math.round(v * 1e4) / 1e4; const md5 = (s) => createHash("md5").update(s).digest("hex").slice(0, 12); const AE_IMAGE = new Set([".png", ".jpg", ".jpeg", ".tif", ".tiff", ".psd", ".bmp", ".tga", ".exr"]); const AE_VIDEO = new Set([".mp4", ".mov", ".m4v", ".avi", ".mxf"]); const AE_AUDIO = new Set([".wav", ".mp3", ".aif", ".aiff", ".m4a", ".aac"]); const VARIANT_LIMIT = 6; // more distinct looks than this and an svg / baked box becomes a PNG sequence // ---- keyframe reduction: Ramer-Douglas-Peucker per track, tolerance per component function rdp(vals, tol) { const n = vals.length, keep = new Uint8Array(n); keep[0] = 1; keep[n - 1] = 1; const dev = (i, a, b) => { const p = (i - a) / (b - a); let m = 0; for (let k = 0; k < vals[i].length; k++) m = Math.max(m, Math.abs(vals[a][k] + (vals[b][k] - vals[a][k]) * p - vals[i][k]) / tol[k]); return m; }; const stack = [[0, n - 1]]; while (stack.length) { const [a, b] = stack.pop(); let mi = -1, mv = 1; for (let i = a + 1; i < b; i++) { const v = dev(i, a, b); if (v > mv) { mv = v; mi = i; } } if (mi >= 0) { keep[mi] = 1; stack.push([a, mi], [mi, b]); } } const out = []; for (let i = 0; i < n; i++) if (keep[i]) out.push(i); return out; } function track(frames, fn, tol) { const vals = frames.map(fn); const first = JSON.stringify(vals[0]); if (vals.every((v) => JSON.stringify(v) === first)) return { v: vals[0].map(r4) }; return { k: rdp(vals, tol).map((i) => [i, vals[i].map(r4)]) }; } function holds(frames, fn) { const out = []; let last; frames.forEach((f, i) => { const v = fn(f); const s = JSON.stringify(v); if (s !== last) { out.push([i, v]); last = s; } }); return out.length === 1 ? { v: out[0][1] } : { k: out }; } // any clip shape as polygon points (rounded corners and ellipses as short arcs) function shapeToPts(s) { if (s.kind === "poly") return s.pts; const arc = (cx, cy, rx, ry, a0, a1, n) => Array.from({ length: n + 1 }, (_, i) => { const a = a0 + ((a1 - a0) * i) / n; return [cx + rx * Math.cos(a), cy + ry * Math.sin(a)]; }); if (s.kind === "ellipse") return arc(s.cx, s.cy, s.rx, s.ry, -Math.PI / 2, (3 * Math.PI) / 2, 32).slice(0, -1); const { x, y, w, h } = s, r = Math.min(s.r || 0, w / 2, h / 2); if (r < 0.5) return [[x, y], [x + w, y], [x + w, y + h], [x, y + h]]; const P = Math.PI; return [...arc(x + w - r, y + r, r, r, -P / 2, 0, 6), ...arc(x + w - r, y + h - r, r, r, 0, P / 2, 6), ...arc(x + r, y + h - r, r, r, P / 2, P, 6), ...arc(x + r, y + r, r, r, P, 1.5 * P, 6)]; } const sx = (L) => Math.hypot(L[0], L[1]); const det = (L) => L[0] * L[3] - L[1] * L[2]; function transformTracks(fr) { return { pos: track(fr, (e) => [e.x, e.y], [0.25, 0.25]), scale: track(fr, (e) => [sx(e.L) * 100, (sx(e.L) > 1e-6 ? det(e.L) / sx(e.L) : Math.hypot(e.L[2], e.L[3])) * 100], [0.15, 0.15]), rot: track(fr, (e) => [(Math.atan2(e.L[1], e.L[0]) * 180) / Math.PI], [0.05]), op: track(fr, (e) => [e.o * 100], [0.4]), }; } export async function exportProject({ hf, chrome, projectDir, out, fps = 30, canvasFps, only, log = console.log }) { projectDir = resolve(projectDir); out = resolve(out); // retries: antivirus / indexers briefly hold freshly written files on Windows // a file still open elsewhere (the last .aep in After Effects, a stray aerender) is overwritten in place instead if (existsSync(out)) for (const d of ["comps", "assets"]) { try { rmSync(join(out, d), { recursive: true, force: true, maxRetries: 10, retryDelay: 300 }); } catch (e) { log(`note: could not clear ${join(out, d)} (${e.code}: a file is open in another program); overwriting in place`); } } for (const d of ["comps", "assets/images", "assets/svg", "assets/bake", "assets/seq", "assets/video", "assets/audio", "fonts"]) mkdirSync(join(out, d), { recursive: true }); const warnings = new Set(); const warn = (s) => { if (!warnings.has(s)) { warnings.add(s); log("warning: " + s); } }; const T0 = Date.now(); const P = await openProject({ hf, chrome, projectDir, log, fontsDir: join(out, "fonts") }); const { page, seek } = P; for (const e of P.errors) warn("page error: " + e); await page.addScriptTag({ path: join(HERE, "sampler.js") }); const prep = await page.evaluate(() => window.__hf2ae.prepare()); log(`project ${basename(projectDir)}: ${prep.comps.length} composition(s), ${P.width}x${P.height}, ${P.duration.toFixed(3)} s; ${prep.pseudo} pseudo-elements and ${prep.lines} one-sided borders turned into elements`); const CF = canvasFps || (fps > 30 && fps % 2 === 0 ? fps / 2 : fps); const step = fps / CF; if (!Number.isInteger(step)) throw new Error(`canvas fps ${CF} must divide fps ${fps}`); const N = Math.max(1, Math.round(P.duration * fps)); // ---- 1. sample every frame const comps = new Map(prep.comps.map((c) => [c.cid, { ...c, frames: new Array(N).fill(null), vis: new Uint8Array(N), bg: null }])); const canv = {}; // ckey -> { seq: [png index per canvas frame (global)], n, dir } let lastLog = Date.now(); for (let f = 0; f < N; f++) { await seek(Math.min(f / fps, P.duration - 1e-4)); const s = await page.evaluate(() => window.__hf2ae.sample()); for (const [cid, rec] of Object.entries(s)) { const c = comps.get(cid); if (!c) continue; if (rec.visible) { c.vis[f] = 1; c.frames[f] = rec.entries; if (!c.bg && rec.bg) c.bg = rec.bg; } } if (f % step === 0) { const res = await page.evaluate(() => window.__hf2ae.canvases()); for (const [k, url] of Object.entries(res)) { const c = (canv[k] ||= { seq: new Array(Math.ceil(N / step)).fill(-1), n: 0, dir: `c${Object.keys(canv).length}` }); if (url) { mkdirSync(join(out, "assets/seq", c.dir), { recursive: true }); writeFileSync(join(out, "assets/seq", c.dir, `f_${String(c.n).padStart(5, "0")}.png`), Buffer.from(url.split(",")[1], "base64")); c.n++; } c.seq[f / step] = c.n - 1; } } if (Date.now() - lastLog > 10000) { log(` sampled ${f + 1}/${N} frames`); lastLog = Date.now(); } } for (const w of await page.evaluate(() => window.__hf2ae.warnings())) warn(w); // ---- 2. composition timing (global start frame, visible window, duration) const rootC = [...comps.values()].find((c) => !c.parent); const globalStart = (c) => (c.parent ? globalStart(comps.get(c.parent)) + c.start : 0); for (const c of comps.values()) { c.gs = Math.round(globalStart(c) * fps); const visF = []; c.vis.forEach((v, i) => v && visF.push(i)); c.firstVis = visF.length ? visF[0] : null; c.lastVis = visF.length ? visF[visF.length - 1] : null; c.n = c.parent ? Math.max(1, (c.lastVis ?? c.gs) + 1 - c.gs, Math.round((c.dur || 0) * fps)) : N; } // ---- 3. per composition: entries -> layers with tracks const fetchUrl = (u) => fetch(u); const origin = new URL(page.url()).origin; const fileFor = async (url, sub) => { // project-local file for a page URL, or a download into assets/<sub> if (url.startsWith(origin)) return join(projectDir, decodeURIComponent(new URL(url).pathname)); if (url.startsWith("data:")) { const m = url.match(/^data:([^;,]+)[^,]*,(.*)$/s); const ext = (m[1].split("/")[1] || "bin").replace("svg+xml", "svg"); const p = join(out, "assets", sub, md5(url) + "." + ext); writeFileSync(p, url.includes(";base64,") ? Buffer.from(m[2], "base64") : decodeURIComponent(m[2])); return p; } const p = join(out, "assets", sub, md5(url) + extname(new URL(url).pathname)); if (!existsSync(p)) writeFileSync(p, Buffer.from(await (await fetchUrl(url)).arrayBuffer())); return p; }; const sharp = (() => { try { return hf.require("sharp"); } catch { return null; } })(); const ffmpeg = resolveFfmpeg(); const images = new Map(), videos = new Map(); async function imageAsset(src) { if (images.has(src)) return images.get(src); let p = await fileFor(src, "images"), ext = extname(p).toLowerCase(), res; if (AE_IMAGE.has(ext)) { res = rel(copyInto(p, "assets/images")); } else if (sharp) { const dst = join(out, "assets/images", md5(src) + ".png"); await sharp(p, ext === ".svg" ? { density: 288 } : {}).png().toFile(dst); res = rel(dst); } else { warn(`image ${basename(p)}: format ${ext} not importable and sharp is unavailable`); res = null; } images.set(src, res); return res; } function copyInto(p, sub) { const dst = join(out, sub, basename(p)); if (!existsSync(dst)) copyFileSync(p, dst); return dst; } const rel = (p) => p.slice(out.length + 1).replace(/\\/g, "/"); async function videoAsset(src) { if (videos.has(src)) return videos.get(src); const p = await fileFor(src, "video"), ext = extname(p).toLowerCase(); let res = null; if (AE_VIDEO.has(ext)) res = rel(copyInto(p, "assets/video")); else if (ffmpeg) { const dst = join(out, "assets/video", basename(p, ext) + ".mp4"); const r = spawnSync(ffmpeg, ["-y", "-loglevel", "error", "-i", p, "-c:v", "libx264", "-crf", "14", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "256k", dst], { encoding: "utf8" }); if (r.status === 0) res = rel(dst); else warn(`video ${basename(p)}: conversion to mp4 failed`); } else warn(`video ${basename(p)}: ${ext} is not importable in After Effects and ffmpeg is missing`); videos.set(src, res); return res; } // svg / bake rasterisation const svgPng = new Map(); async function rasterSvg(svg, w, h) { const id = md5(svg); if (!svgPng.has(id)) { const url = await page.evaluate(async (src, w, h) => { const img = new Image(); img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(src); await img.decode(); const c = document.createElement("canvas"); c.width = Math.max(1, Math.ceil(w * 4)); c.height = Math.max(1, Math.ceil(h * 4)); c.getContext("2d").drawImage(img, 0, 0, c.width, c.height); return c.toDataURL("image/png"); }, svg, w, h); writeFileSync(join(out, "assets/svg", id + ".png"), Buffer.from(url.split(",")[1], "base64")); svgPng.set(id, `assets/svg/${id}.png`); } return svgPng.get(id); } let bakePage = null; const bakePng = new Map(); async function rasterBake(e) { if (bakePng.has(e.sig)) return bakePng.get(e.sig); if (!bakePage) { bakePage = await P.browser.newPage(); await bakePage.setViewport({ width: 64, height: 64, deviceScaleFactor: 2 }); await bakePage.goto(origin + "/__hf2ae_blank__", { waitUntil: "load" }).catch(() => {}); await bakePage.setContent(`<html><head><base href="${origin}/"></head><body style="margin:0;background:transparent"></body></html>`); } const W = Math.ceil(e.w + 2 * e.pad), H = Math.ceil(e.h + 2 * e.pad); await bakePage.setViewport({ width: Math.max(1, W), height: Math.max(1, H), deviceScaleFactor: 2 }); await bakePage.evaluate((st, pad) => { document.body.innerHTML = ""; const d = document.createElement("div"); Object.assign(d.style, st, { position: "absolute", left: pad + "px", top: pad + "px", boxSizing: "border-box", margin: "0" }); document.body.appendChild(d); return Promise.all([...document.images].map((i) => i.decode().catch(() => {}))); }, e.style, e.pad); await new Promise((r) => setTimeout(r, 30)); await bakePage.evaluate(() => document.fonts.ready); const file = join(out, "assets/bake", e.sig + ".png"); await bakePage.screenshot({ path: file, omitBackground: true, clip: { x: 0, y: 0, width: Math.max(1, W), height: Math.max(1, H) } }); bakePng.set(e.sig, `assets/bake/${e.sig}.png`); return bakePng.get(e.sig); } const fontUse = new Map(); const manifest = { tool: "hyperframes-to-after-effects", version: 1, project: projectDir, fps, canvasFps: CF, width: P.width, height: P.height, duration: N / fps, root: rootC.cid, comps: [], audio: [], fonts: [], warnings: [] }; let totalLayers = 0; for (const c of comps.values()) { if (only && !only.includes(c.cid) && c.parent) continue; const local = (gf) => gf - c.gs; // collect entries by key over the composition's own frames const byKey = new Map(); for (let gf = Math.max(0, c.gs); gf < Math.min(N, c.gs + c.n); gf++) { const ents = c.frames[gf]; if (!ents) continue; for (const e of ents) { if (!byKey.has(e.k)) byKey.set(e.k, { first: e, at: new Array(c.n).fill(null) }); byKey.get(e.k).at[local(gf)] = e; } } const layers = [], clips = []; for (const [k, { first, at }] of byKey) { // absent frames hold the nearest known state, invisible const firstSeen = at.find(Boolean); let last = firstSeen; const fr = at.map((e) => { if (e) { last = e; return e; } return { ...last, o: 0 }; }); if (first.t === "clip") { // one clip can change kind over time (a clip-path wipe that ends as plain overflow: hidden): then every frame // becomes a path, so the matte never goes empty const kinds = new Set(fr.map((e) => e.shape.kind)); if (kinds.size > 1) for (let i = 0; i < fr.length; i++) fr[i] = { ...fr[i], shape: { kind: "poly", pts: shapeToPts(fr[i].shape) } }; const shapeKind = fr[0].shape.kind; const cl = { k, t: "clip", clip: first.clip || null, kind: shapeKind, ...transformTracks(fr) }; cl.op = { v: [100] }; if (shapeKind === "rrect") { cl.rect = track(fr, (e) => (e.shape.kind === "rrect" ? [e.shape.x, e.shape.y, e.shape.w, e.shape.h, e.shape.r] : [0, 0, e.w, e.h, 0]), [0.3, 0.3, 0.3, 0.3, 0.3]); } else if (shapeKind === "ellipse") { cl.ellipse = track(fr, (e) => [e.shape.cx, e.shape.cy, e.shape.rx, e.shape.ry], [0.3, 0.3, 0.3, 0.3]); } else { cl.path = holds(fr, (e) => (e.shape.pts || []).map((p) => [r4(p[0]), r4(p[1])])); } clips.push(cl); continue; } // svg and baked boxes that change look: per-variant layers, or a PNG sequence past the limit if ((first.t === "svg" || first.t === "bake")) { const sigs = [...new Set(fr.map((e) => e.sig))]; if (sigs.length > VARIANT_LIMIT) { const dir = `v${md5(c.cid + k)}`; mkdirSync(join(out, "assets/seq", dir), { recursive: true - skills/hyperframes-to-after-effects/scripts/lib/fonts.mjs (5674 bytes)
// fonts.mjs: what After Effects needs to set the same type: for every (CSS family, weight, style) the text uses, the real // family / style / PostScript name read from the font file itself (CSS aliases like "Brand Sans" point at Inter files), // a category for picking a fallback, and the files to install when After Effects cannot see the face. import { writeFileSync, mkdirSync, existsSync, readdirSync } from "node:fs"; import { join, basename } from "node:path"; import { fileURLToPath } from "node:url"; const WEIGHT_NAMES = { 100: "Thin", 200: "ExtraLight", 300: "Light", 400: "Regular", 500: "Medium", 600: "SemiBold", 700: "Bold", 800: "ExtraBold", 900: "Black" }; function firstFamily(ff) { return ff.split(",")[0].trim().replace(/^["']|["']$/g, ""); } function genericOf(ff) { const g = ff.split(",").map((s) => s.trim().replace(/^["']|["']$/g, "").toLowerCase()); if (g.includes("monospace") || g.some((s) => /mono|code|consol|courier/.test(s))) return "mono"; if (g.includes("serif") && !g.includes("sans-serif")) return "serif"; if (g.some((s) => /serif|garamond|georgia|times|playfair|baskerville|caslon|bodoni|didot/.test(s)) && !g.some((s) => /sans/.test(s))) return "serif"; return "sans"; } const wnum = (w) => (w === "normal" ? 400 : w === "bold" ? 700 : parseInt(w, 10) || 400); // pick the @font-face rule for a family / weight / style (weight ranges "100 900" allowed) function pickFace(faces, fam, w, italic) { const c = faces.filter((f) => f.family.toLowerCase() === fam.toLowerCase()); if (!c.length) return null; const score = (f) => { const [lo, hi] = f.weight.split(/\s+/).map(wnum); const d = w < lo ? lo - w : w > (hi ?? lo) ? w - (hi ?? lo) : 0; return d + ((f.style === "italic" || f.style === "oblique") !== italic ? 1000 : 0); }; return c.sort((a, b) => score(a) - score(b))[0]; } export async function resolveFonts({ hf, usage, faces, fetchUrl, serverOrigin, projectDir, fontsDir, log }) { const fontkit = hf.require("fontkit"); const out = []; mkdirSync(fontsDir, { recursive: true }); for (const u of usage) { const fam = firstFamily(u.ff), w = wnum(u.fw), italic = u.fst === "italic" || u.fst === "oblique"; const rec = { css: `${u.ff}|${u.fw}|${u.fst}`, cssFamily: fam, weight: w, italic, category: genericOf(u.ff), family: fam, style: (WEIGHT_NAMES[Math.round(w / 100) * 100] || "Regular") + (italic ? " Italic" : ""), ps: null, file: null }; const face = pickFace(faces, fam, w, italic); if (face && face.src.length) { for (const src of face.src) { try { let buf, local = null; if (src.startsWith(serverOrigin)) { local = join(projectDir, decodeURIComponent(new URL(src).pathname)); buf = await import("node:fs").then((fs) => fs.readFileSync(local)); } else if (src.startsWith("file:")) { local = fileURLToPath(src); buf = await import("node:fs").then((fs) => fs.readFileSync(local)); } else buf = Buffer.from(await (await fetchUrl(src)).arrayBuffer()); let font = fontkit.create(buf); if (font.fonts) font = font.fonts[0]; // collections // typographic family (name ID 16) when present: "Outfit", not the default instance's "Outfit Thin" const nm = (id) => { const r = font.name?.records?.[id]; return r ? r.en || Object.values(r)[0] : null; }; let family = nm("preferredFamily") || font.familyName; // variable fonts often name the family after their default instance ("Outfit Thin"): drop the style word if (font.variationAxes && font.variationAxes.wght && !nm("preferredFamily")) family = family.replace(/\s+(Thin|Hairline|ExtraLight|UltraLight|Light|Regular|Book|Medium|SemiBold|DemiBold|Bold|ExtraBold|UltraBold|Black|Heavy)$/i, ""); if (font.variationAxes && font.variationAxes.wght) { // variable font: the named instance closest to the weight (After Effects lists instances by style name) const inst = Object.entries(font.namedVariations || {}).map(([name, axes]) => ({ name, w: axes.wght })).sort((a, b) => Math.abs(a.w - w) - Math.abs(b.w - w))[0]; rec.family = family; rec.style = inst ? inst.name + (italic && !/italic/i.test(inst.name) ? " Italic" : "") : rec.style; } else { rec.family = family; rec.style = nm("preferredSubfamily") || font.subfamilyName; rec.ps = font.postscriptName; } if (font["OS/2"] && font.post && font.post.isFixedPitch) rec.category = "mono"; // keep a copy to install (After Effects reads TTF / OTF; WOFF / WOFF2 must be installed from the original files) const ext = (local || src).split("?")[0].split(".").pop().toLowerCase(); if (["ttf", "otf", "ttc"].includes(ext)) { const name = (rec.ps || `${rec.family}-${rec.style}`).replace(/[^\w.-]+/g, "") + "." + ext; if (!existsSync(join(fontsDir, name))) writeFileSync(join(fontsDir, name), buf); rec.file = name; } else { // a Google family fetched by page.mjs already has TrueType copies in fontsDir const stem = fam.replace(/\s+/g, "") + "-", have = readdirSync(fontsDir).filter((f) => f.startsWith(stem) && f.endsWith(".ttf")); const g = have.find((f) => f.startsWith(stem + w + (italic ? "Italic" : ""))) || have.find((f) => /Italic/.test(f) === italic) || have[0]; rec.file = g || basename(local || src.split("?")[0]) + " (web font: install the TTF/OTF of this family)"; } break; } catch (e) { log(`font ${fam}: could not read ${src} (${e.message})`); } } } out.push(rec); } return out; } - skills/hyperframes-to-after-effects/scripts/lib/page.mjs (9923 bytes)
// page.mjs: opens a HyperFrames project in headless Chrome the way Studio previews it (the raw project served as is, // the HyperFrames runtime injected at the start of <head>; the runtime mounts sub-compositions itself), waits for // window.__renderReady, and seeks with the renderer's own cascade (__player.renderSeek -> __hf.seek -> timelines). // Font families the page uses but neither declares (@font-face) nor finds on the system are fetched from Google Fonts, // like the HyperFrames compiler does at render time; their TTFs are kept for installing on the After Effects machine. import { createServer } from "node:http"; import { existsSync, readFileSync, statSync, mkdirSync, writeFileSync } from "node:fs"; import { join, extname, normalize, resolve, sep } from "node:path"; const TYPES = { ".html": "text/html; charset=utf-8", ".js": "text/javascript", ".mjs": "text/javascript", ".css": "text/css", ".json": "application/json", ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".avif": "image/avif", ".ttf": "font/ttf", ".otf": "font/otf", ".woff": "font/woff", ".woff2": "font/woff2", ".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime", ".mp3": "audio/mpeg", ".wav": "audio/wav", ".m4a": "audio/mp4", ".ogg": "audio/ogg", ".lottie": "application/zip" }; export function serveProject(projectDir, runtimePath, entry = "index.html") { const root = resolve(projectDir); const server = createServer((req, res) => { const url = decodeURIComponent((req.url || "/").split("?")[0]); if (url === "/__hf2ae_runtime.js") { res.writeHead(200, { "content-type": TYPES[".js"] }); return res.end(readFileSync(runtimePath)); } const rel = url === "/" ? entry : url.replace(/^\/+/, ""); const file = normalize(join(root, rel)); if (!file.startsWith(root + sep) && file !== root) { res.writeHead(403); return res.end(); } if (!existsSync(file) || statSync(file).isDirectory()) { res.writeHead(404); return res.end(); } if (rel === entry) { const html = readFileSync(file, "utf8").replace(/<head([^>]*)>/i, `<head$1><script src="/__hf2ae_runtime.js"></script>`); res.writeHead(200, { "content-type": TYPES[".html"] }); return res.end(html); } // byte ranges, so <video> can seek const size = statSync(file).size, type = TYPES[extname(file).toLowerCase()] || "application/octet-stream"; const m = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range || ""); if (m) { const start = m[1] ? +m[1] : Math.max(0, size - +m[2]), end = m[2] && m[1] ? Math.min(+m[2], size - 1) : size - 1; res.writeHead(206, { "content-type": type, "accept-ranges": "bytes", "content-range": `bytes ${start}-${end}/${size}`, "content-length": end - start + 1 }); return res.end(readFileSync(file).subarray(start, end + 1)); } res.writeHead(200, { "content-type": type, "accept-ranges": "bytes", "content-length": size }); res.end(readFileSync(file)); }); return new Promise((ok) => server.listen(0, "127.0.0.1", () => ok({ server, url: `http://127.0.0.1:${server.address().port}/` }))); } export async function openProject({ hf, chrome, projectDir, log = console.log, fontsDir }) { const puppeteer = hf.require("puppeteer-core"); const { server, url } = await serveProject(projectDir, hf.runtime); const browser = await puppeteer.launch({ executablePath: chrome, headless: true, args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--autoplay-policy=no-user-gesture-required", "--hide-scrollbars"] }); const page = await browser.newPage(); const errors = []; page.on("pageerror", (e) => errors.push(String(e))); // size the viewport from the root composition before anything lays out const html = readFileSync(join(projectDir, "index.html"), "utf8"); const rootTag = html.match(/<[^>]+data-composition-id="[^"]+"[^>]*>/); const W = +(rootTag?.[0].match(/data-width="(\d+)"/)?.[1] || 1920), H = +(rootTag?.[0].match(/data-height="(\d+)"/)?.[1] || 1080); await page.setViewport({ width: W, height: H, deviceScaleFactor: 1 }); await page.goto(url, { waitUntil: "load", timeout: 120000 }); const ready = await page.waitForFunction(() => Boolean(window.__renderReady), { timeout: 120000 }).then(() => true, () => false); if (!ready) log("warning: the runtime never set __renderReady (continuing with what loaded)"); const fonts = await ensureFonts(page, fontsDir, log); await page.evaluate(() => document.fonts.ready); // media: wait for <video> frames (verify screenshots); the export only reads geometry and skips the wait const seek = (t, { media = false } = {}) => page.evaluate((t, media) => { const p = window.__player, hfw = window.__hf; if (p && typeof p.renderSeek === "function") p.renderSeek(t, { exact: true }); else if (hfw && typeof hfw.seek === "function") hfw.seek(t); else if (p && typeof p.seek === "function") p.seek(t); else for (const tl of Object.values(window.__timelines || {})) { tl.pause?.(); tl.seek?.(t); } window.gsap?.ticker?.tick?.(); if (!media) return; // visible videos: wait until the seek lands (screenshots of a stale frame mislead verify) const vids = [...document.querySelectorAll("video")].filter((v) => v.getClientRects().length && getComputedStyle(v).visibility !== "hidden" && v.seeking); return Promise.race([ Promise.all(vids.map((v) => new Promise((ok) => v.addEventListener("seeked", ok, { once: true })))), new Promise((ok) => setTimeout(ok, 1500)), ]).then(() => new Promise((ok) => requestAnimationFrame(() => requestAnimationFrame(() => ok())))); }, t, media); const duration = await page.evaluate(() => { const p = window.__player; const d = p?.getDuration?.(); if (d > 0) return d; const root = document.querySelector("body > [data-composition-id], [data-composition-id]"); return parseFloat(root?.getAttribute("data-duration")) || 0; }); return { browser, page, server, seek, duration, width: W, height: H, errors, fonts, close: async () => { await browser.close(); server.close(); } }; } // families used by text but missing (no @font-face, not installed): fetch from Google Fonts into the page (woff2) and // keep TTF copies for the After Effects machine async function ensureFonts(page, fontsDir, log) { const info = await page.evaluate(async () => { await document.fonts.ready; const declared = new Set([...document.fonts].map((f) => f.family.replace(/^["']|["']$/g, ""))); const used = new Map(); const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); for (let n = walker.nextNode(); n; n = walker.nextNode()) { if (!n.textContent.trim() || !n.parentElement) continue; const cs = getComputedStyle(n.parentElement); const fam = cs.fontFamily.split(",")[0].trim().replace(/^["']|["']$/g, ""); if (!used.has(fam)) used.set(fam, new Set()); used.get(fam).add(`${cs.fontStyle === "italic" ? 1 : 0},${cs.fontWeight}`); } const generic = new Set(["serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui", "ui-sans-serif", "ui-serif", "ui-monospace", "-apple-system", "BlinkMacSystemFont"]); const c = document.createElement("canvas").getContext("2d"), probe = "mmmmmmmmmlli1WQ@#&"; const installed = (f) => ["monospace", "serif", "sans-serif"].some((g) => { c.font = `40px ${g}`; const a = c.measureText(probe).width; c.font = `40px "${f}", ${g}`; return c.measureText(probe).width !== a; }); const out = []; for (const [fam, styles] of used) out.push({ family: fam, styles: [...styles], declared: declared.has(fam), generic: generic.has(fam), installed: !declared.has(fam) && !generic.has(fam) && installed(fam) }); return out; }); const fetched = []; for (const f of info) { if (f.declared || f.generic || f.installed) continue; const axes = [...new Set(f.styles)].map((s) => s.split(",")).sort((a, b) => a[0] - b[0] || a[1] - b[1]); const q = `family=${encodeURIComponent(f.family).replace(/%20/g, "+")}:ital,wght@${axes.map((a) => a.join(",")).join(";")}`; try { const css = await (await fetch(`https://fonts.googleapis.com/css2?${q}&display=block`, { headers: { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36" } })).text(); if (!/@font-face/.test(css)) { log(`font "${f.family}": not declared, not installed, not on Google Fonts (text will use a fallback)`); continue; } await page.addStyleTag({ content: css }); await page.evaluate(async (fam, axes) => { await Promise.all(axes.map(([i, w]) => document.fonts.load(`${i === "1" ? "italic " : ""}${w} 40px "${fam}"`))); }, f.family, axes); // TTF copies for After Effects (Google serves TrueType to non-browser clients) if (fontsDir) { mkdirSync(fontsDir, { recursive: true }); const ttfCss = await (await fetch(`https://fonts.googleapis.com/css2?${q}`)).text(); const seen = new Set(); for (const m of ttfCss.matchAll(/font-style:\s*(\w+);\s*font-weight:\s*(\d+);[^}]*?src:\s*url\(([^)]+)\)/g)) { if (seen.has(m[3])) continue; // one file can serve several weights (variable fonts) seen.add(m[3]); const buf = Buffer.from(await (await fetch(m[3])).arrayBuffer()); let name = `${f.family.replace(/\s+/g, "")}-${m[2]}${m[1] === "italic" ? "Italic" : ""}.ttf`; if (existsSync(join(fontsDir, name))) name = name.replace(".ttf", `-${seen.size}.ttf`); writeFileSync(join(fontsDir, name), buf); } } fetched.push(f.family); log(`font "${f.family}": loaded from Google Fonts (as the HyperFrames compiler does)`); } catch (e) { log(`font "${f.family}": Google Fonts fetch failed (${e.message})`); } } return { used: info, fetched }; } - skills/hyperframes-to-after-effects/scripts/lib/sampler.js (23599 bytes)
// sampler.js: runs inside the HyperFrames page (added with page.addScriptTag). Defines window.__hf2ae: // prepare() once after load: discovers the composition tree and rewrites what the sampler cannot see into real // elements (::before/::after with content -> spans, one-sided borders -> line spans; layout unchanged) // sample() one frame: every visible element of every visible composition, in that composition's own space // canvases(fps) changed <canvas> pixels as PNG data URLs // Entry types: box, text, svg, image, video, canvas, bake (painted by the browser into a PNG), comp (a nested // composition placed in its parent), clip (overflow / clip-path geometry other entries are matted by). (() => { const rgba = (s) => { const m = (s || "").match(/[\d.]+/g); if (!m) return [0, 0, 0, 0]; return [m[0] / 255, m[1] / 255, m[2] / 255, m.length > 3 ? +m[3] : 1]; }; const mul = (P, E) => [P[0] * E[0] + P[2] * E[1], P[1] * E[0] + P[3] * E[1], P[0] * E[2] + P[2] * E[3], P[1] * E[2] + P[3] * E[3]]; const ctx = document.createElement("canvas").getContext("2d"); const ascentCache = {}; const ascent = (cs) => { const f = `${cs.fontStyle} ${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`; if (!(f in ascentCache)) { ctx.font = f; const m = ctx.measureText("Hg"); ascentCache[f] = m.fontBoundingBoxAscent; } return ascentCache[f]; }; const hash = (s) => { let h = 2166136261; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return (h >>> 0).toString(36); }; // top-left of an element's local box in the composition's space, given its composed linear transform L const placement = (rect, L, w, h, base) => { const xs = [0, w * L[0], h * L[2], w * L[0] + h * L[2]], ys = [0, w * L[1], h * L[3], w * L[1] + h * L[3]]; return [rect.left - base.left - Math.min(...xs), rect.top - base.top - Math.min(...ys)]; }; const px = (v, ref) => (String(v).endsWith("%") ? (parseFloat(v) / 100) * ref : parseFloat(v) || 0); const radius = (cs, w, h) => Math.min(px(cs.borderTopLeftRadius.split(" ")[0], Math.min(w, h)), Math.min(w, h) / 2); const shadows = (s) => { if (!s || s === "none") return []; return s.split(/,(?![^(]*\))/).map((part) => { const col = part.match(/rgba?\([^)]*\)/), rest = part.replace(/rgba?\([^)]*\)/, "").trim(); const inset = /\binset\b/.test(rest), n = rest.replace("inset", "").trim().split(/\s+/).map(parseFloat); return { x: n[0] || 0, y: n[1] || 0, blur: n[2] || 0, spread: n[3] || 0, c: rgba(col ? col[0] : "rgb(0,0,0)"), inset }; }); }; const filterOf = (s) => { if (!s || s === "none") return { blur: 0, other: [] }; let blur = 0; const other = []; for (const m of s.matchAll(/([a-z-]+)\(([^)]*)\)/g)) { if (m[1] === "blur") blur = parseFloat(m[2]) || 0; else other.push(m[1]); } return { blur, other }; }; const textCase = (t, tt) => (tt === "uppercase" ? t.toUpperCase() : tt === "lowercase" ? t.toLowerCase() : tt === "capitalize" ? t.replace(/\b\p{L}/gu, (c) => c.toUpperCase()) : t); // clip-path basic shapes in the element's local box: polygon / inset / circle / ellipse const clipShape = (s, w, h) => { if (!s || s === "none") return null; let m; if ((m = s.match(/^polygon\((.*)\)$/))) { const body = m[1].replace(/^(nonzero|evenodd)\s*,/, ""); return { kind: "poly", pts: body.split(",").map((p) => { const [a, b] = p.trim().split(/\s+/); return [px(a, w), px(b, h)]; }) }; } if ((m = s.match(/^inset\((.*)\)$/))) { const [box, round] = m[1].split(/\s+round\s+/); const v = box.trim().split(/\s+/); const t = px(v[0], h), r = px(v[1] ?? v[0], w), b = px(v[2] ?? v[0], h), l = px(v[3] ?? v[1] ?? v[0], w); return { kind: "rrect", x: l, y: t, w: Math.max(0, w - l - r), h: Math.max(0, h - t - b), r: round ? px(round.trim().split(/\s+/)[0], Math.min(w, h)) : 0 }; } if ((m = s.match(/^(circle|ellipse)\((.*)\)$/))) { const [size, at] = m[2].split(/\s+at\s+/); const sz = (size || "").trim().split(/\s+/).filter(Boolean), c = (at || "50% 50%").trim().split(/\s+/); const ref = Math.hypot(w, h) / Math.SQRT2; const rx = m[1] === "circle" ? px(sz[0] || "50%", ref) : px(sz[0] || "50%", w), ry = m[1] === "circle" ? rx : px(sz[1] || "50%", h); const pos = (v, ref2) => (v === "center" ? ref2 / 2 : v === "left" || v === "top" ? 0 : v === "right" || v === "bottom" ? ref2 : px(v, ref2)); return { kind: "ellipse", cx: pos(c[0], w), cy: pos(c[1] ?? "50%", h), rx, ry }; } return { kind: "unsupported", css: s.slice(0, 60) }; }; const BLENDS = new Set(["multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity"]); let tree = null; // [{ cid, el, parent }] const warnings = new Set(); function prepare() { const all = [...document.querySelectorAll("[data-composition-id]")]; const rootEl = all.find((el) => !el.parentElement.closest("[data-composition-id]")); tree = all.map((el) => ({ cid: el.getAttribute("data-composition-id"), el, parent: el === rootEl ? null : el.parentElement.closest("[data-composition-id]").getAttribute("data-composition-id") })); // duplicate composition ids (the same sub-composition mounted twice) get an instance suffix const seen = {}; for (const c of tree) { seen[c.cid] = (seen[c.cid] || 0) + 1; if (seen[c.cid] > 1) c.cid += "#" + seen[c.cid]; } const style = document.createElement("style"); style.textContent = ".__hf2ae-nops::before, .__hf2ae-nops::after { display: none !important; }"; document.head.appendChild(style); let pseudo = 0, lines = 0; for (const el of [...rootEl.querySelectorAll("*")]) { if (el.namespaceURI !== "http://www.w3.org/1999/xhtml" || /^(SCRIPT|STYLE|TEMPLATE|VIDEO|AUDIO|CANVAS|IMG|IFRAME)$/.test(el.tagName)) continue; const made = []; for (const which of ["::before", "::after"]) { const ps = getComputedStyle(el, which); if (ps.content === "none" || ps.content === "normal" || ps.display === "none") continue; const text = ps.content.match(/^"(.*)"$/s)?.[1] ?? ""; if (!text && ps.position !== "absolute") continue; // an empty in-flow pseudo is layout glue, nothing to see const s = document.createElement(text && ps.position !== "absolute" ? "span" : "span"); s.className = "__hf2ae-pseudo"; const copy = ["position", "display", "left", "top", "right", "bottom", "width", "height", "backgroundColor", "backgroundImage", "opacity", "borderRadius", "borderTop", "borderRight", "borderBottom", "borderLeft", "boxShadow", "transform", "transformOrigin", "color", "font", "letterSpacing", "textTransform", "zIndex", "margin", "padding", "filter", "mixBlendMode", "verticalAlign", "lineHeight"]; for (const p of copy) s.style[p] = ps[p]; s.style.pointerEvents = "none"; if (text) s.textContent = text.replace(/\\"/g, '"').replace(/\\a /g, "\n"); made.push([which, s]); } if (made.length) { el.classList.add("__hf2ae-nops"); for (const [which, s] of made) which === "::before" ? el.prepend(s) : el.append(s); pseudo += made.length; } const cs = getComputedStyle(el); const side = (n) => ({ w: parseFloat(cs["border" + n + "Width"]) || 0, c: cs["border" + n + "Color"], s: cs["border" + n + "Style"] }); const B = { Top: side("Top"), Right: side("Right"), Bottom: side("Bottom"), Left: side("Left") }; const vis = (b) => b.w > 0 && b.s !== "none" && b.s !== "hidden" && rgba(b.c)[3] > 0.001; const uniform = ["Right", "Bottom", "Left"].every((n) => B[n].w === B.Top.w && B[n].s === B.Top.s && B[n].c === B.Top.c); if (uniform || !Object.values(B).some(vis)) continue; if (cs.position === "static") el.style.position = "relative"; for (const n of ["Top", "Right", "Bottom", "Left"]) { const b = B[n]; if (!vis(b)) continue; const s = document.createElement("span"); s.className = "__hf2ae-border"; const st = { position: "absolute", display: "block", background: b.c, pointerEvents: "none", margin: "0" }; if (n === "Top" || n === "Bottom") Object.assign(st, { left: -B.Left.w + "px", width: `calc(100% + ${B.Left.w + B.Right.w}px)`, height: b.w + "px", [n.toLowerCase()]: -b.w + "px" }); else Object.assign(st, { top: -B.Top.w + "px", height: `calc(100% + ${B.Top.w + B.Bottom.w}px)`, width: b.w + "px", [n.toLowerCase()]: -b.w + "px" }); Object.assign(s.style, st); el.append(s); el.style["border" + n + "Color"] = "transparent"; lines++; } } return { comps: tree.map((c) => ({ cid: c.cid, parent: c.parent, label: c.el.getAttribute("data-label") || c.el.getAttribute("data-composition-id"), src: c.el.getAttribute("data-composition-src"), w: +c.el.getAttribute("data-width") || c.el.offsetWidth, h: +c.el.getAttribute("data-height") || c.el.offsetHeight, start: (() => { const tl = (window.__timelines || {})[c.el.getAttribute("data-composition-id")]; const s = tl?.startTime?.(); return Number.isFinite(s) ? s : parseFloat(c.el.getAttribute("data-start")) || 0; })(), tlDur: (window.__timelines || {})[c.el.getAttribute("data-composition-id")]?.duration?.() || 0, dur: parseFloat(c.el.getAttribute("data-duration")) || 0 })), pseudo, lines }; } function sample() { const out = {}; for (const c of tree) out[c.cid] = { entries: [], visible: false, bg: null }; const compOf = new Map(tree.map((c) => [c.el, c])); const walkComp = (c, opIn) => { const rec = out[c.cid]; const cs = getComputedStyle(c.el); rec.visible = cs.visibility !== "hidden" && cs.display !== "none" && opIn > 0; if (!rec.visible) return; rec.bg = cs.backgroundColor; // the page shows through a transparent root: its colour comes from <body> or <html> if (!c.parent && rgba(rec.bg)[3] < 0.01) for (const p of [document.body, document.documentElement]) { const b = getComputedStyle(p).backgroundColor; if (rgba(b)[3] > 0.01) { rec.bg = b; break; } } if (cs.transform !== "none" && c.parent) warnings.add(`composition "${c.cid}" host is transformed: its content is exported flattened`); const base = c.el.getBoundingClientRect(); let order = 0; const walk = (el, key, Lp, opp, blurp, zp, clip) => { const cs = getComputedStyle(el); if (cs.display === "none") return; let L = Lp; if (cs.transform && cs.transform !== "none") { const m = new DOMMatrix(cs.transform); if (!m.is2D) warnings.add("3D transforms are flattened to their 2D projection"); L = mul(Lp, [m.a, m.b, m.c, m.d]); } const hidden = cs.visibility === "hidden"; const op = opp * parseFloat(cs.opacity); const f = filterOf(cs.filter); const blur = Math.hypot(blurp, f.blur); // paint order key: the z-index of every positioned ancestor that sets one, outermost first (CSS stacking contexts), // compared element by element with a missing level as 0, then document order const z = cs.position !== "static" && cs.zIndex !== "auto" ? zp.concat(parseInt(cs.zIndex, 10) || 0) : zp; const isRoot = el === c.el; const nested = !isRoot && compOf.get(el); const rect = el.getBoundingClientRect(); const w = el.offsetWidth ?? rect.width, h = el.offsetHeight ?? rect.height; const tag = el.tagName.toLowerCase(); const blend = BLENDS.has(cs.mixBlendMode) ? cs.mixBlendMode : null; const common = (extra) => Object.assign({ n: order++, z, o: hidden ? 0 : op, L, clip, blur: Math.round(blur * 100) / 100, blend }, extra); if (nested) { const [x, y] = placement(rect, L, w, h, base); rec.entries.push(common({ k: key, t: "comp", cid: nested.cid, x, y, w, h })); walkComp(nested, hidden ? 0 : op); return; } if (f.other.length) warnings.add(`CSS filter ${f.other.join(", ")} is not converted (only blur is)`); if (tag === "svg") { const sw = parseFloat(cs.width) || rect.width, sh = parseFloat(cs.height) || rect.height; const clone = el.cloneNode(true); clone.setAttribute("width", sw); clone.setAttribute("height", sh); clone.style.color = cs.color; const src = new XMLSerializer().serializeToString(clone).replace(/currentColor/g, cs.color); const [x, y] = placement(rect, L, sw, sh, base); rec.entries.push(common({ k: key, t: "svg", x, y, w: sw, h: sh, svg: src, sig: hash(src) })); return; } if (tag === "canvas") { const sx = el.width ? w / el.width : 1, sy = el.height ? h / el.height : 1; // CSS size over backing size const Lc = mul(L, [sx, 0, 0, sy]); const [x, y] = placement(rect, Lc, el.width, el.height, base); if (!el.__hf2aeKey) el.__hf2aeKey = c.cid + "|" + key; rec.entries.push(common({ k: key, t: "canvas", L: Lc, x, y, w: el.width, h: el.height, ckey: el.__hf2aeKey })); return; } if (tag === "img" || tag === "video") { const [x, y] = placement(rect, L, w, h, base); const nw = tag === "img" ? el.naturalWidth : el.videoWidth, nh = tag === "img" ? el.naturalHeight : el.videoHeight; const op2 = cs.objectPosition.split(/\s+/); const e = common({ k: key, t: tag === "img" ? "image" : "video", x, y, w, h, src: el.currentSrc || el.src, nw, nh, fit: cs.objectFit, opos: [op2[0] || "50%", op2[1] || "50%"], r: radius(cs, w, h) }); if (tag === "video") Object.assign(e, { start: parseFloat(el.getAttribute("data-start")) || 0, dur: parseFloat(el.getAttribute("data-duration")) || 0, mediaStart: parseFloat(el.getAttribute("data-media-start")) || 0, rate: parseFloat(el.getAttribute("data-playback-rate")) || 1, muted: el.muted || el.hasAttribute("muted"), audio: el.getAttribute("data-has-audio") === "true", vol: parseFloat(el.getAttribute("data-volume") ?? "1") }); rec.entries.push(e); return; } const [x, y] = placement(rect, L, w, h, base); // clip-path clips the element itself and everything in it; overflow clips only what is inside (own text included) const cpAll = !isRoot ? clipShape(cs.clipPath, w, h) : null; const hasCp = cpAll && cpAll.kind !== "unsupported"; const ownClip = (!isRoot && (hasCp || cs.overflow !== "visible" || cs.overflowX !== "visible")) ? "clip:" + key : clip; const boxClip = hasCp ? "clip:" + key : clip; if (!isRoot && w > 0 && h > 0) { const bg = rgba(cs.backgroundColor), bw = parseFloat(cs.borderTopWidth) || 0, bc = rgba(cs.borderTopColor); const ow = c - skills/hyperframes-to-after-effects/scripts/lib/text.mjs (4292 bytes)
// text.mjs: turns a text layer whose string changes into a native After Effects recipe. Per-frame Source Text keys make // After Effects scripting crawl project-wide (one layer with ~150 of them slows every later scripted edit ~200x), so the // builder never writes them. Recipes: // counter digits inside a fixed template ("12%", "About 3 min left", "01:59", "00:00:03:31"): a Count slider and an // expression that formats it; when the value just follows time, the expression reads time and needs no keys // typing a string growing by characters: the final text plus a Text Animator (opacity 0, range start keyed) // split a few distinct strings: one plain text layer per string, trimmed in time // table anything else (decode, scramble): a short [time, text] table in an expression // colours colour changes ride on a Fill Color text animator (step keys; a run of consecutive frames is a fade) const same = (a, b) => a.join(",") === b.join(","); const groups = (t) => t.match(/\d+/g) || []; const tpl = (t) => t.replace(/\d+/g, "#"); // radix for each digit group of a clock-like template, from the largest value seen in it function radices(runs, n) { const max = Array(n).fill(0); for (const [, t] of runs) groups(t).forEach((g, i) => { max[i] = Math.max(max[i], +g); }); return max.map((m, i) => (i === 0 ? null : m < 24 && n === 4 && i === 1 ? 60 : m < 60 ? 60 : m < 100 ? 100 : 1000)); } export function planText(K, fps) { // K: [[frame, {txt, col, ...}], ...] in layer-local frames const txts = K.map((k) => k[1].txt); const fin = txts[txts.length - 1]; const cols = []; for (const [f, d] of K) if (!cols.length || !same(cols[cols.length - 1][1], d.col.slice(0, 3))) cols.push([f, d.col.slice(0, 3)]); const runs = []; for (const [f, d] of K) if (!runs.length || runs[runs.length - 1][1] !== d.txt) runs.push([f, d.txt]); let r; if (runs.length === 1) r = { mode: "static", txt: fin }; else { const t0 = tpl(runs[0][1]); const ng = groups(runs[0][1]).length; const allTpl = ng > 0 && runs.every(([, t]) => tpl(t) === t0); if (allTpl && (ng === 1 ? runs.length >= 3 : runs.length >= 3)) { // one number, or a clock: digit groups read as one mixed-radix value const rad = ng > 1 ? radices(runs, ng) : [null]; const value = (t) => groups(t).reduce((v, g, i) => (i === 0 ? +g : v * rad[i] + +g), 0); const pads = groups(runs[0][1]).map((g, i) => (runs.every(([, t]) => groups(t)[i].length === g.length) && runs.some(([, t]) => groups(t)[i][0] === "0" && groups(t)[i].length > 1) ? g.length : 0)); const parts = t0.split("#"); const keys = runs.map(([f, t]) => [f, value(t)]); // does the value simply follow time? v = floor(a + b * frame) const [f0, v0] = keys[0], [f1, v1] = keys[keys.length - 1]; const slope = f1 > f0 ? (v1 - v0) / (f1 - f0) : 0; let linear = null; if (slope > 0) { for (const off of [0, 0.5, 0.999]) { const a = v0 + off; if (K.every(([f, d]) => value(d.txt) === Math.floor(a + slope * (f - f0) + 1e-6))) { linear = { a: a - slope * f0, b: slope * fps }; break; } } } r = { mode: "counter", parts, rad, pads, keys: linear ? null : keys, linear }; } else { let i0 = runs.length - 1; while (i0 > 0 && runs[i0][1].startsWith(runs[i0 - 1][1]) && runs[i0 - 1][1].length < runs[i0][1].length) i0--; if (runs.length - i0 >= 3) { r = { mode: "typing", final: fin, from: runs[i0][0], keys: runs.slice(i0).map(([f, t]) => [f, t.length]), before: runs.slice(0, i0).map(([f, t], j) => [t, f, runs[j + 1][0]]) }; } else if (runs.length <= 4 || (runs.length <= 60 && runs.every(([f], j) => j + 1 >= runs.length || runs[j + 1][0] - f >= fps * 0.3))) { // a few strings, or strings that each stay up long enough to read (captions): plain layers, one per string r = { mode: "split", parts: runs.map(([f, t], j) => [t, f, j + 1 < runs.length ? runs[j + 1][0] : null]) }; } else { r = { mode: "table", rows: runs.map(([f, t]) => [f, t]) }; } } } if (cols.length > 1) r.colors = cols.map(([f, c], i) => [f, c, i + 1 < cols.length && cols[i + 1][0] - f > 2 ? 1 : 0]); // [frame, rgb, holdOut] return r; } - skills/hyperframes-to-after-effects/scripts/lib/verify.mjs (3758 bytes)
// verify.mjs: renders the built .aep with aerender, takes the same moments from the HyperFrames page (the loader matches // `hyperframes snapshot` to SSIM 0.99+), and writes <out>/verify/compare.png (After Effects left, HyperFrames right, one // row per moment) plus SSIM per moment. Look at compare.png; SSIM only says where to look. import { mkdirSync, existsSync, readFileSync, writeFileSync } from "node:fs"; import { join, basename } from "node:path"; import { spawnSync } from "node:child_process"; import { resolveHyperframes, resolveChrome, resolveAE, resolveFfmpeg } from "./env.mjs"; import { openProject } from "./page.mjs"; export async function verify({ project, out, aep, frames = 8, prefer, log = console.log }) { const M = JSON.parse(readFileSync(join(out, "manifest.json"), "utf8")); const ae = resolveAE(prefer), ff = resolveFfmpeg(); if (!ae?.aerender) throw new Error("aerender not found next to After Effects"); if (!ff) throw new Error("ffmpeg not found (HyperFrames renders need it too)"); const vdir = join(out, "verify"); mkdirSync(vdir, { recursive: true }); const rootName = M.project.replace(/\\/g, "/").split("/").pop(); const mp4 = join(vdir, "ae.mp4"); log(`rendering "${rootName}" with aerender...`); const t0 = Date.now(); const r = spawnSync(ae.aerender, ["-project", aep, "-comp", rootName, "-OMtemplate", "H.264 - Match Render Settings - 15 Mbps", "-output", mp4], { encoding: "utf8", maxBuffer: 64 << 20 }); if (!existsSync(mp4)) throw new Error("aerender produced nothing:\n" + (r.stdout || "").split("\n").slice(-15).join("\n") + (r.stderr || "")); log(` aerender ${((Date.now() - t0) / 1000).toFixed(0)} s`); const times = Array.from({ length: frames }, (_, i) => +(((i + 0.5) * M.duration) / frames).toFixed(3)); const hf = resolveHyperframes(project); const P = await openProject({ hf, chrome: resolveChrome(hf), projectDir: project, log: () => {} }); for (const t of times) { await P.seek(t, { media: true }); await P.page.screenshot({ path: join(vdir, `hf_${t}.png`) }); } await P.close(); const rows = []; for (const t of times) { const a = join(vdir, `ae_${t}.png`), b = join(vdir, `hf_${t}.png`); // the frame index, not -ss: exact frame from the H.264 const fi = Math.round(t * M.fps); spawnSync(ff, ["-y", "-loglevel", "error", "-i", mp4, "-vf", `select=eq(n\\,${fi})`, "-frames:v", "1", "-fps_mode", "passthrough", a]); const s = spawnSync(ff, ["-i", a, "-i", b, "-lavfi", "[0]format=gray[x];[1]format=gray[y];[x][y]ssim", "-f", "null", "-"], { encoding: "utf8" }); const ssim = +((s.stderr || "").match(/All:([\d.]+)/)?.[1] || 0); rows.push({ t, ssim, a, b }); } // compare sheet: one row per moment, After Effects | HyperFrames, 800 px each const inputs = rows.flatMap((r) => ["-i", r.a, "-i", r.b]); const n = rows.length; const fc = rows.map((r, i) => `[${2 * i}]scale=800:-2[a${i}];[${2 * i + 1}]scale=800:-2[b${i}];[a${i}][b${i}]hstack[r${i}]`).join(";") + ";" + rows.map((_, i) => `[r${i}]`).join("") + `vstack=inputs=${n}[o]`; spawnSync(ff, ["-y", "-loglevel", "error", ...inputs, "-filter_complex", n > 1 ? fc : fc.replace(/;\[r0\]vstack=inputs=1\[o\]$/, "").replace("[r0]", "[o]"), "-map", "[o]", join(vdir, "compare.png")]); const mean = rows.reduce((s, r) => s + r.ssim, 0) / n; const report = [`verify ${basename(aep)}: mean SSIM ${mean.toFixed(4)} (1 = identical; text in a substitute font typically lands 0.95-0.99)`, ...rows.map((r) => ` t=${r.t}s SSIM ${r.ssim.toFixed(4)}${r.ssim < 0.93 ? " <- look here" : ""}`), `sheet: ${join(vdir, "compare.png")} (After Effects left, HyperFrames right)`].join("\n"); writeFileSync(join(vdir, "report.txt"), report); log(report); return { mean, rows }; } - skills/hyperframes-to-after-effects/SKILL.md (6987 bytes)
--- name: hyperframes-to-after-effects description: Convert a HyperFrames project (HTML/GSAP video compositions) into an editable Adobe After Effects project (.aep) with real layers and keyframes, not a rendered video. Text stays live text, cards become shape layers, images and video become footage, sub-compositions become precomps, animation becomes keyframes, and the result is checked against the HyperFrames render frame by frame. Use this whenever someone wants to move, port, export or "hand off" a HyperFrames / HTML video to After Effects or AE, wants an .aep from their HyperFrames composition, wants to keep editing a HyperFrames film in After Effects, or asks why an AE import of their HTML animation is slow or broken, even if they do not say "skill" or name the tool. Windows and macOS. --- # HyperFrames to After Effects A HyperFrames film is a paused GSAP timeline over HTML. This skill plays it in headless Chrome frame by frame, records what every element looks like, and rebuilds that in After Effects as native, editable layers: | HyperFrames | After Effects | |---|---| | sub-composition (`data-composition-src`, nested `data-composition-id`) | precomp at its start, trimmed to its visible window | | text node (each rendered line) | text layer, live font; changing strings become native recipes (below) | | box with background / border / radius / outline / hard shadow | shape layer (rounded rect, fill, stroke, dashes) | | soft `box-shadow` / `text-shadow`, `filter: blur()`, `mix-blend-mode` | Drop Shadow, Gaussian Blur (keyed), blending mode | | gradients, background images, inset or multiple shadows, mixed radii | PNG painted by Chrome (transform and opacity still keyed) | | `<img>` (`object-fit`, rounded corners), `<video>` (trim, rate, volume) | footage layer with fit, crop mask, timing, audio level | | inline `<svg>` | PNG at 4x (a few looks: one layer each; many: a sequence) | | `<canvas>` (2D, three.js, Lottie) | PNG sequence with time remap | | `overflow: hidden`, `clip-path` (polygon, inset, circle, ellipse) | track matte (nested clips nest) | | `<audio>` | audio layer at its start, with its volume | Changing text never becomes per-frame Source Text keys: After Effects slows down project-wide once any layer has them (one 150-key layer makes every later scripted edit ~200x slower, a 3,000-key film took hours). Instead: counters → a Count slider + expression (or pure `time` expression when the number follows time), typing → Text Animator, a few strings or captions → one trimmed layer per string, scrambles → a small `[time, text]` expression table, colour changes → Fill Color animator. ## Before you start Run the doctor and read it to the user in plain words: ```bash node <skill>/scripts/hf2ae.mjs doctor <project> ``` - **Node 18+, the project's HyperFrames CLI and its Chrome.** The tool reuses what HyperFrames already installed (puppeteer-core, fontkit, sharp, Chrome) from the npx cache. If Chrome is missing, `npx hyperframes browser ensure` downloads it: ask the user before running it. - **After Effects** (any recent version; 2023+ for the track-matte API) with *Preferences → Scripting & Expressions → Allow Scripts to Write Files and Access Network* switched on. Ask the user to check it; the build cannot set it. - **ffmpeg** for verification (HyperFrames rendering needs it anyway) and for converting WebM/OGG media. Ask the user (only what you cannot infer): 1. Where to save the `.aep` (default `<project>/after-effects/project.aep`). 2. If After Effects is open with a project: build into that open project (`--into-open`), or save and close it first. Never close, save over or discard the user's open project yourself. 3. Frame rate: the project's render rate if known (`hyperframes render -f`), else 30. Use 60 for fast UI motion. ## Workflow ```bash node <skill>/scripts/hf2ae.mjs export <project> --out <dir> [--fps 30] # Chrome only, no After Effects node <skill>/scripts/hf2ae.mjs build --out <dir> [--aep <file>] [--into-open] node <skill>/scripts/hf2ae.mjs verify <project> --out <dir> [--frames 8] node <skill>/scripts/hf2ae.mjs all <project> --out <dir> ... # the three in a row ``` `<skill>` is this skill's folder. Run steps one at a time the first time on a project, so problems surface at the step that caused them. 1. **Export** writes `<dir>/manifest.json`, `<dir>/comps/*.json`, `<dir>/assets/`, `<dir>/fonts/` and `<dir>/export_report.txt`. Read the report before building: its *fonts* list says which real face every CSS family resolves to (aliases such as `"Brand Sans"` are read from the font files), and *warnings* lists what was approximated. Tell the user about warnings that affect what they will see. 2. **Build** starts After Effects (or uses the open one), writes progress to `<dir>/ae_status.txt` and a log to `<dir>/ae_build_log.txt`, saves after every composition. Typical films build in under a minute. If it runs for minutes on one layer, stop and read the log rather than waiting: see `references/troubleshooting.md`. 3. **Verify** renders the `.aep` with `aerender` and puts After Effects and HyperFrames side by side in `<dir>/verify/compare.png`, with SSIM per moment in `<dir>/verify/report.txt`. Open the sheet and look at it. SSIM tells you where to look, your eyes tell you what is wrong: typical numbers are 0.98+ with the original fonts and 0.95–0.99 with substitutes. Fix causes in the export or build (not by hand in After Effects), rebuild, re-verify. ## Fonts After Effects only sees fonts installed **for all users** (on Windows a per-user install is invisible to it). The build uses the real face when After Effects has it; otherwise it picks the closest installed face of the same kind (sans / serif / mono), fits each line to the width it had in the film (so words placed side by side keep their spaces), and writes the original font into the layer comment. The files to install are in `<dir>/fonts/` (Google Fonts are fetched as TTF). Offer the user that choice: install them for all users, restart After Effects, run `build` again (no re-export needed). Installing fonts is the user's action, not yours. ## Reporting back Tell the user, briefly: where the `.aep` is; what became what (precomps, text, shapes, footage); which fonts were substituted and how to get the originals; the warnings that matter; the verify result with the sheet. Mention what stays approximate (3D transforms flattened to 2D, CSS filters other than blur, painted PNGs for gradients, blend modes that After Effects mixes slightly differently) so nothing surprises them in After Effects. ## Going deeper - `references/how-it-works.md`: the export format, keyframe reduction, text recipes, mattes, timing of precomps and media. Read it before changing the scripts. - `references/troubleshooting.md`: slow or stuck builds, After Effects not running the script, fonts, mismatched frames, macOS specifics.
- skills/real-sfx/config.example.json (196 bytes)
{ "libraries": [], "uisfx": { "path": "vendor/node_modules/uisfx", "default_pack": "studio" }, "skip_dir_names": ["_mister horse previews"], "index_path": "library_index.json" } - skills/real-sfx/config.json (196 bytes)
{ "libraries": [], "uisfx": { "path": "vendor/node_modules/uisfx", "default_pack": "studio" }, "skip_dir_names": ["_mister horse previews"], "index_path": "library_index.json" } - skills/real-sfx/evals/evals.json (3390 bytes)
{ "skill_name": "real-sfx", "evals": [ { "id": 1, "name": "cuts-and-hook-silent-render", "prompt": "Вот отрендеренный ролик <VIDEO> (моушен-графика, без звука). Озвучь его реальными звуками из моих библиотек: свуши на склейки, хиты на тяжёлые моменты, UI-звуки на появление элементов. Мне нужен новый mp4 и отдельный wav.", "expected_output": "New mp4 with SFX on the cuts and appearances, a separate wav, a cue report, critique scoreboard with every axis >= 8, no synthesized sound.", "assertions": [ "Output mp4 has the original video stream and an audio stream, same duration (+-0.2 s)", "A separate WAV with the SFX is delivered", "There is a sound within the first 2 seconds", "At least 80% of strong cuts have a sound within 120 ms", "No sound is synthesized (every sound is a library file or a uisfx cue)", "True peak is at or below -1 dBTP", "The run used verify and critique before presenting, and reported scores" ] }, { "id": 2, "name": "voiceover-keep-and-duck", "prompt": "Ролик <VIDEO> с дикторским голосом. Добавь звуковой дизайн реальными звуками, голос должен остаться чистым и разборчивым.", "expected_output": "Voice-over preserved (correlation with source > 0.9 outside SFX), SFX ducked under speech (--voice-safe), SFX 6-10 dB below the voice, no ambience bed.", "assertions": [ "Original voice audio is present in the output", "--voice-safe (or equivalent ducking) was used", "SFX are quieter than the original audio by 3-11 LU", "No ambience bed is placed under speech", "Separate WAV delivered" ] }, { "id": 3, "name": "music-led-beat-snap", "prompt": "Ролик <VIDEO> под музыку. Добавь звуки на склейки и акценты, музыку оставь, попади в бит там, где это уместно.", "expected_output": "Music kept, beats detected, hits snapped to the beat when within 50 ms, no extra rhythmic layer on top of the music.", "assertions": [ "Original music is preserved", "beats.py was used and its usable flag respected", "Hits within 50 ms of a beat are on the beat (or the reason for not snapping is given)", "Music is ducked or SFX trimmed so the SFX do not bury it" ] }, { "id": 4, "name": "hyperframes-native-clips", "prompt": "Вот проект HyperFrames <PROJECT>. Добавь звуки прямо в композицию, чтобы они переживали перерендер.", "expected_output": "Moments read from the composition (no frame analysis), clips exported to assets/sfx, <audio> elements with ids and data-start/data-duration, no composition rule broken.", "assertions": [ "from_hyperframes.py was used rather than frame analysis", "Every <audio> has a unique id", "Overlapping audio clips use different data-track-index values", "Processed clips are files in assets/sfx and referenced with relative paths", "The agent asked before calling another skill or running render" ] } ] } - skills/real-sfx/evals/trigger_eval.json (3157 bytes)
[ { "query": "ok so i rendered my product launch animation from hyperframes (promo.mp4, 28s) and its dead silent. can you add proper sound effects, whooshes on the cuts and some ui clicks? i have a folder of sfx packs on D:\\sfx", "should_trigger": true }, { "query": "озвучь этот ролик, у меня есть папка со звуками, музыку оставь как есть", "should_trigger": true }, { "query": "my after effects logo sting sounds cheap, the whoosh is synthetic. can you replace it with real recorded sounds from my library and line them up to the frames", "should_trigger": true }, { "query": "add impact hits and risers to this trailer cut, sync them to the scene changes, and give me the SFX as a separate wav so i can tweak it in premiere", "should_trigger": true }, { "query": "накидай сфх на моушен: свуши на склейки, клики на появление кнопок, ничего синтетического", "should_trigger": true }, { "query": "can you do sound design for my ui animation? the button presses and toggles need little tick sounds", "should_trigger": true }, { "query": "this tiktok edit has music but zero sound effects, put hits on the drops and whooshes on the transitions, keep the song", "should_trigger": true }, { "query": "я сделал ролик в hyperframes, добавь звуки в композицию прямо в проект, чтобы они не пропали при рендере", "should_trigger": true }, { "query": "the sfx in my video are out of sync by like 100ms and they all sound the same, fix the sound design", "should_trigger": true }, { "query": "i have a bunch of Mister Horse and Epidemic SFX packs, set up something that picks sounds for my motion graphics automatically", "should_trigger": true }, { "query": "write a python script that generates a 440hz sine wave and saves it as a wav file", "should_trigger": false }, { "query": "transcribe this interview video and burn subtitles into it", "should_trigger": false }, { "query": "normalize the loudness of this podcast episode to -16 LUFS and remove the hiss", "should_trigger": false }, { "query": "make a 30 second promo video for my app from this URL", "should_trigger": false }, { "query": "cut the silences out of this talking head video and tighten the pacing", "should_trigger": false }, { "query": "recommend some royalty free background music for a corporate explainer", "should_trigger": false }, { "query": "color grade this footage to a teal and orange look and add film grain", "should_trigger": false }, { "query": "generate a text-to-speech voiceover for this script in a warm female voice", "should_trigger": false }, { "query": "convert my mp4 to a gif at 15 fps, max 5 MB", "should_trigger": false }, { "query": "my react web app should play a sound when a user clicks save, implement it with the web audio api", "should_trigger": false } ] - skills/real-sfx/README.md (6358 bytes)
# real-sfx A Claude Code skill that sound-designs motion videos with **real** recorded sounds from your own library instead of generated ones. Claude finds the moments in the picture, picks and processes real recordings, puts them on the exact frame, keeps your music and voice, and hands you a new MP4 plus a separate SFX track. ## Install Copy this folder to your Claude Code skills folder and restart Claude Code: - Windows: `%USERPROFILE%\.claude\skills\real-sfx` - macOS: `~/.claude/skills/real-sfx` Or install the `.skill` package from the Claude app (Save skill). ## Needs - Python 3.9+ and FFmpeg (with ffprobe) in PATH. - Windows: `winget install Python.Python.3.12` and `winget install Gyan.FFmpeg`. - macOS: `brew install ffmpeg-full` and put it first in PATH (`export PATH="$(brew --prefix ffmpeg-full)/bin:$PATH"`). The plain `ffmpeg` formula has no `drawtext` and `rubberband` filters, which the frame sheets and pitch shifts use. - Node.js only for the optional UI-sound package. ## Add your sounds The skill ships without a sound library. Tell it where yours lives: ``` python scripts/setup.py scan "D:/Sounds" # which folders look like sound libraries python scripts/setup.py init --library main="D:/Sounds/SFX" --library ui="D:/Sounds/UI" --uisfx --index python scripts/setup.py check ``` No library yet? `--uisfx` alone gives 78 UI cues (CC0). Free real-recording sources worth checking (read each licence): Freesound (CC0 filter), Sonniss GDC bundles, Mixkit, Pixabay sound effects. **Main pack and fallbacks.** A library is `"tier": "main"` (default) or `"tier": "extra"`. Extras are used only where the main libraries have fewer than three fitting sounds. A sorted pack that carries `catalog.json` / `catalog.csv` (columns `file`, `type`, `source`, `hit`, `hits_in_source`) gives every sound its type and source recording, which is more reliable than guessing from file names: ``` python scripts/setup.py add-library montage "D:/Sounds_sorted" --tier main --index python scripts/setup.py add-library old_packs "D:/Packs" --tier extra --index python scripts/listen.py tag-index # meaning tags for the new sounds (needs listen.py install --yes once) ``` ## Use Just ask Claude: *"add sound design to this render"*, *"sound-design my HyperFrames project"*, *"озвучь этот ролик"*. Under the hood: ``` look.py (see the film) -> from_cues.py (the project's event list, or the calls of its synthesizer script) ui_events.py (a screen recording, region by region) from_hyperframes.py (data-start timeline) -> suggest_cues.py -> (you and Claude edit) find_moments.py (frame analysis) -> mix.py -> verify.py, review.py, critique.py (loop until 8+) ``` If the project already writes a typed list of its sound events (`docs/cues.json`: whoosh, wipe, click, key, coins ...), `from_cues.py` swaps the synthesis for real sounds on the same timestamps and cuts real keystrokes out of your typing recordings. See `references/typed-cues.md`. If the sound is made by a script (`audio.cjs`: `whoosh(4.2)`, `click(18.35)`), `from_cues.py PROJECT_FOLDER` records those calls as the list, and the synthesized layer is taken OUT of the render (the project's `sfx.wav` stem subtracted from its mix, or the score rebuilt from the script without the effects) so music and voice stay and nothing doubles. See `references/project-audio.md`. The new sounds are placed at the level the author's own sounds had, event by event (`levels.py`; the critique checks it as `match`, and checks that the synthesized layer is really gone as `doubling`), pitched sounds are tuned to the notes of the score under them (`tonal.py`), typing written as clicks goes to the real keyboard, and a sound is placed by its audible start. The beat grid is checked against the kicks before anything snaps to it (`beats.py --plot` draws it), the film is checked in mono (a sound whose channels cancel vanishes on a phone speaker; `mix.py` plays its louder channel), and the critique ends with the five moments to listen to. For a film whose sound is only SFX, `texture.py` voices the picture's small moves that were left quiet and sit in holes, and `critique.py --style clean-sfx-refs` sets the film against nine finished SFX reels in numbers (gestures per 10 s, gaps, level spread, low end, the floor, digital silence): no scores, it says where the film differs, not that it is worse. `bed.py` puts ONE long, dark, steady real recording under such a film. Claude cannot hear, so the ears are made of two things. `listen_page.py` makes the one pair of ears there is cheap: a page of blind A/B versions and of the critique's listen-list moments, one tap per verdict (`serve --lan` reaches a phone). `maskmodel.py` (`mix.py --masking`, needs the skill's venv) turns the mix into numbers about what the ear would miss. `taste_test.py` turns the same page into a taste test by category; the answers go to `taste.json` (love is preferred, never is never taken). You get: `*_sfx.mp4`, `*_sfx_track.wav` (always), optional stems and per-sound clips, a cue report, a critique scoreboard. Sounds you dislike: `taste.py ban ID`; the next video starts from your taste. ## What it will not do It does not synthesize sound, and Claude cannot hear: sounds are chosen by measured character, plain words, spectrogram pictures and (optionally) YAMNet tags. Listen to the five places its critique lists (`critique.py --listen-out FILE.wav` cuts them into one file). Details: `references/listening.md`. ## Test ``` python tests/selftest.py # builds a tiny fixture library, runs the whole pipeline (189 checks, 188 without the skill's venv), ~5 min ``` `tests/resound.py` takes finished videos with a professional sound design, strips all audio, lets a fresh agent sound the picture from `SKILL.md` alone, and sets the result against the original sound in numbers (`tests/resound.md`). ## Licences Scripts: MIT. uisfx (bundled mp3): code MIT, sounds CC0. Your own sound libraries keep their own licences; this skill never copies them anywhere, it only reads them. Made by Alexander Korbanov at [Clipwing](https://clipwing.pro). - skills/real-sfx/references/event-map.md (5632 bytes)
# What happens on screen → which sound Roles (`search.py --roles`): whoosh, hit, design, sub_drop, riser, click, ui, pop, chime, typing, water, meme, glitch, error, data, paper, glass, coin, camera, ambience, foley, scifi, vehicle, cartoon. `design` is screams/sustains/textures for trailer accents, `meme` is reactions and meme sounds, `pop` bubbles and soft pop-ins, `chime` bells, rings, sparkles, harp, `typing` keystrokes, `water` drops and splashes. A sound can have several roles; `--role X` finds every sound with X among its tags, the ones where X is the main role first. A sorted library with a catalog (`catalog.json` / `catalog.csv`) gets its roles from the catalog's types, other libraries from the words in their file and folder names. ## The map | Event on screen | kind from find_moments | Source | What to look for | |---|---|---|---| | A hard cut, a scene change | cut | library | `whoosh` 0.3–0.8 s (fast), `hit` if the cut is heavy | | A smooth or long transition | cut + burst | library | `whoosh` 0.8–1.5 s, the peak anchored to the middle of the transition (`anchor: peak`) | | A big title / logo lands | settle | library, in layers | `hit` + a `sub_drop` under it (−6 dB, `anchor: peak`), at most 2 layers. **A product / UI film: a light bright accent** (`chime`, a ringing short `hit` up to 1.5 s, a ding); `sub_drop` only if the person asks for cinematic lows: a taste test on 2026-10-15 on a cut to a title gave "love" to a music box (as the hit) and "not here" to 5 of 9 sub drops (long ones); a short 1.2 s bass and a bright rumble were loved | | A build to a reveal (a card grows, a counter speeds up) | onset … settle | library | a `riser` lasting until the moment, `anchor: end` puts its end on t | | An interface element appeared | onset | uisfx | `open`, `select`, `notification`, `expand`; in a "cinematic" film `ui`/`glass` from the library | | A click, a button press, the cursor | onset | uisfx or library | uisfx `press`, `toggle-on`; library `click` (mouse clicks, button presses). A mouse click recording is two clicks (press, release, the second louder): `"slice": "first"` or `"anchor": "peak"` | | Typing text | a run of onsets | library (pieces of typing recordings) | Each key is a separate piece of a real recording (`slice`), 8–14 per second, no more: `from_cues.py` cuts them itself. Live typing from a screen recording: one sound per character, `ui_events.py`. Without an event list: 2–4 sounds per phrase or uisfx `typing` | | A bubble, a soft appearance, a drop | onset | library | `pop` (plop, bubble), `water` (drops of 0.1–0.7 s as a soft tick) | | Small plastic, a bead, a clasp | onset | library | an exact recording is rare: `--query lego` (spilling Lego blocks, cut into single hits), `--query plastic`, single `click`s | | A bouncing ball, a step, an object on the floor | contact | library, **one family** | a dull thud: `--says "thunk\|thump"`, the surface at the end of the name (wood / concrete / carpet); `from_cues.py --one-source thump,pop` | | Sparkles, magic, a reveal, "restoring" | onset/settle | library | `chime`, `--query magic` / `harp` / `music`; a success "ding": `chime` with the Ding tag | | A counter, digits, data | burst/onset | library | `data`; uisfx `progress-step` for steps | | Success, done | settle | uisfx | `success`, `complete`, `achievement`, `reward` | | An error, a warning | burst | uisfx or library | uisfx `error`, `warning`, `blocked`; library `error` | | A glitch, interference, VHS | burst | library | `glitch` | | Paper, a sticker, tape, a page | onset/burst | library | `paper` (seal & peel, textured elements) | | A flash, a photo | burst | library | `camera` (flash/shutter) | | Money, a price, a purchase | onset | uisfx or library | uisfx `purchase`, `add-to-cart`; library `coin` | | A glass ping (a panel or layer turned to glass) | onset | library | `chime` (star, music box ding), kind `glass`; the `glass` role in a library is breaking glass (`shatter`) | | Contact: a ball on the floor, a step, an object knocking | contact | library, **clean single hits** | `--one-source thump,pop`; `listen.py onsets ID` shows a recording's clean hits; rolling and rubber are rare in libraries | | The scene's background, a sense of place | no moment | library | `ambience` at −24 dB peak, only if the film has no music | The full list of uisfx signals: `python scripts/search.py --uisfx`. Looping signals (`loading`, `processing`, `recording`, `connecting`, `scanning`, `streaming`) sound forever: take them into a film only with `max_dur` and deliberately. ## Libraries: what to watch for - **Main and fallback.** One sorted library as `tier: main`; older or rougher packs as `tier: extra`, used only where the main library has fewer than three fitting sounds. - **Long files.** Cinematic packs hold many long (10–40 s) ambiences and whooshes: for one-shots set `--max-dur`. - **Names lie.** A folder called "transitions" can hold 20–40 ms clicks, not whooshes; a UI pack's "swipe" can be a ratchet. Check tags (`search.py --paths`) before trusting a name. - **Pack files with silence.** Some packs pad files to 1.07 / 2.09 / 3.06 s while the sound inside takes 0.06–0.4 s. The index stores `active_dur` (until the decay 40 dB under the peak); picking by length, `fit_dur`, `loop_to` and `words` use it, and the mixer cuts off the silent tail. In search results `0.36*` means "the file is longer, the audible part is 0.36 s". The index skips preview PNGs, HTML ads and folders named in `skip_dir_names` (`config.json`). Files like `X.wav new` are deduplicated: they are a re-export of `X`.
- skills/real-sfx/references/handoff.md (3900 bytes)
# Handing the result to an editor The skill's main result: a new MP4 and a separate WAV (`*_sfx_track.wav`, 48 kHz, 24 bit, the track starts at the video's 0:00). The WAV always sits next to it so it can be dropped into any project without re-encoding. Optionally: - `--stems`: `*_stem_impacts.wav`, `_motion.wav`, `_interface.wav`, `_atmos.wav`, to remix the groups separately without rebuilding everything - `--export-clips DIR`: each sound as its own WAV with the processing and loudness already applied, `sfx_clips.json` with timecodes, and `sfx_clips_hyperframes.html` (`<audio>` tags to paste) Before calling another skill or a paid or installing tool, ask the user: name the skill and why it is needed. Local checks need no question. ## The source was made in HyperFrames **First check whether the project has its own event list** (`docs/cues.json`, `scripts/cues.json`): a project written for a synthesized score usually keeps one, and then the `from_cues.py` path (SKILL.md, step 2) is more precise than anything else: the event kinds are named, not guessed, and the script handles baked-in synthesis itself. **No list: the moments come from the composition itself**, with no frame analysis and no render. ``` python scripts/from_hyperframes.py path/to/project --out work/moments.json [--video render.mp4] python scripts/suggest_cues.py work/moments.json --out work/cues.json ``` `from_hyperframes.py` reads `data-start`/`data-duration` (including relative `intro + 2` and nested sub-compositions with offsets added up) and the positions of GSAP tweens (numbers, `<`, `>`, `+=0.3`, labels). Scenes give `cut`, elements appearing `onset`, fast moves `burst`; `hint` carries ids/classes/text, from which a uisfx signal is chosen. What it could not parse it writes into `warnings` instead of guessing. Then two options: 1. **Mix over the render** (as with any MP4): render, then `mix.py` with `video` = the render. 2. **Sounds inside the project** (survive a re-render, editable in Studio): `mix.py cues.json --out work/x.mp4 --export-clips work/clips`, then copy the `clips/` folder into `assets/sfx/` and paste the contents of `sfx_clips_hyperframes.html` into the root composition. The composition rules are kept: every `<audio>` has an `id`, identical tracks do not overlap (different `data-track-index`, starting at 20), loudness in `data-volume`. The processing (pitch, reverse, filters) is already baked into the files, because HyperFrames does not know such operations. **Remove the old `<audio ... src="assets/audio/sfx.wav">` (and transition tracks) from `index.html` if the project had a synthesized score:** otherwise the real sounds land on top of the synthesis and the doubling moves inside the project. Keep the voice and music (`voice.wav`, `music.wav`). After pasting: `npx hyperframes check`, then `snapshot`, and `render` only with the user's consent. Fine-tuning loudness and ducking inside the composition: the `hyperframes-audio` skill (ask before calling it). ## After Effects Import `*_sfx_track.wav` (or the stems) into the project and put it as a layer in the root composition starting at 0. Through the `after-effects` MCP: `run-script` with `app.project.importFile(new ImportOptions(File(path)))`, then `comp.layers.add(footageItem)`. To edit sound by sound: `--export-clips` and `sfx_clips.json` (it has each clip's `start` and `duration`). ## Premiere Pro First `verify_premiere_connection`. Then use `search_tools` to find the tool for importing and placing on an audio track (`import_media`, then the clip on A2 with zero offset) and put `*_sfx_track.wav` on a track above the main one. If one sound per clip is more convenient, take `sfx_clips.json` (`file`, `start`, `duration`) and lay out the clips. ## MP4 only Nothing is needed: the file is ready. The WAV can be handed over so the client can rebalance it themselves.
- skills/real-sfx/references/listening.md (7371 bytes)
# How the skill "hears" sound The honest baseline: in this environment the model has no audio input. Files, pictures and PDFs are read, sound is not. So "hearing" here means ways to turn sound into something readable: numbers, words, pictures, classifier tags, or the report of another model that does perceive sound. ## Levels | Level | What it gives | Cost | Status | |---|---|---|---| | 0. Numbers | attack, tail, brightness, share of lows, noisiness, pulsing, peak, duration | none | always works | | 1. Words and pictures | `words` (punchy, dark, heavy, long-tail, pulsing…), `--says`, `contact_sheet.py`, `review.py`: waveform + spectrogram for the model to look at | none | always works | | 2. Tags and meaning | YAMNet: 521 AudioSet classes for every second (Whoosh, Explosion, Click, Glass, Typing…) and a 1024-number vector for "find a similar one by meaning" | ~45 MB, CPU, its own venv | optional: `listen.py install --yes` (on the author's machine: 31 s to install, ~4 min to tag 1,627 sounds) | | 3. An external "listener" | Gemini (or another model with audio input) describes and critiques the sound in words | an API key, the audio leaves the machine | optional, see below | ### How to read a spectrogram (level 1) Time to the right, pitch up, brightness is energy. - a bright spot at the bottom: sub, boom, weight; a bright band at the top: air, hiss - a diagonal going up: a riser or a sweep; vertical strokes: clicks, glitches, ticks - horizontal lines: a tone, a bell, a hum; blurred noise: a whoosh, wind, a texture - a long plateau in the waveform: a bed; a sharp peak and a fast decay: a hit ### What is left to the human ear The critique ends with a list of five moments (`critique.py --listen-out FILE.wav` cuts them into one file, 3 s each). The list is built from measurements of this particular render: the hook, the loudest sound, misses in sync, balance, speech and mono, sounds pulled up by 4+ dB or retuned in pitch; different kinds of risk, not one. The script cannot hear and does not say "sounds good": each line is a question for the ear (is it harsh, is it thin, is it in tune with the music, can the words be heard). The beat grid is checked against the kick by a number, but look at the `beats.py --plot` picture yourself: the green kick marks sit on the red grid lines. One listen on a phone speaker checks what headphones do not reveal: mono. ## Level 2: what gets installed and from where `python scripts/listen.py status` shows the state. Installation only on an explicit command: ``` python scripts/listen.py install --yes python scripts/listen.py tag-index # tags + embeddings of the whole library, ~5-10 minutes on a CPU ``` Downloaded (all into the skill folder, the system is not touched): - `onnxruntime` and `numpy` from PyPI into `vendor/venv`: ~25 MB - `yamnet.onnx` 16.1 MB and `yamnet_class_map.csv`: https://huggingface.co/audiomagic/yamnet-onnx, licence Apache-2.0, AudioSet labels CC BY 4.0. This is a third-party conversion of Google's model, so the script checks the file size. The model takes a raw 16 kHz waveform, the spectrogram is built into the graph. After `tag-index`, every sound in the index has `tags` with confidence (`tag_scores`), and `--says "glass"` and `--like ID` also work by meaning: a word counts if the model is at least 30 % sure of the tag, and the surer it is, the higher the result. Only the **audible** part of a file is listened to (pack files with seconds of silence would give "Silence 100 %", this is cut off), and environment classes (Silence, Sound effect, Inside small room) do not become tags. What this gives in picking, checked on the author's library: - `--says typing` / `glass` / `ding` find typing recordings, glass and bells by meaning, not by folder name. - Duplicates of a recording under different names show in the embedding: four takes of "Glass Crack 01–04" (six pairs) give a cosine of 0.83–0.92, two random whooshes 0.55 on average (90th percentile 0.78). The picker pushes a candidate back if it is closer than 0.82 to a sound already on the sheet, so variety is counted by meaning. - Weak spots: YAMNet tags short single clicks at random ("Rodents", "Mouse"); do not use tags for them, look at the words and the picture. Camera, coin and click often get junk tags. YAMNet is smaller and less accurate than AST/PANN (mAP 0.31 against 0.44–0.46 on AudioSet), but it has 3.7 M parameters instead of 80+ and runs on any CPU. ## Level 3: external "listeners" Only if the user explicitly wants it and understands that the audio leaves the computer. - **Claudio** (MCP, Gemini): the tool `listen_to_audio(path, question)`, `ask_about_audio` to follow up. Needs `GEMINI_API_KEY`; files up to 20 MB go inline, larger ones through the Files API. The user connects it: `claude mcp add claudio -e GEMINI_API_KEY=... -- uvx claudio`. Package: https://pypi.org/project/claudio/ (one maintainer, version 0.2.3, no trusted publishing: check the code before installing). - **audio-analysis MCP** (librosa, Claude Code): onsets, spectra, pitch, file comparison, pictures. Nothing new beyond `scripts/`, but may help those who already use it. - **Freesound MCP** (there are several, e.g. mushan-bit/freesound-mcp): search and download CC sounds with a Freesound API key. Useful for those without their own library; check the licence of every sound. Send only `*_sfx_track.wav` and specific short pieces to such a model, not the whole project, and ask the user first. ## Separating "music / effects / speech" in references (researched, not built in) This is what learning from finished films lacks: in them the music buries the SFX. What was found: - **Bandit / Bandit v2** (cinematic audio source separation, trained on DnR): three stems speech/music/effects. Code https://github.com/kwatcharasupat/bandit-v2 (Apache-2.0), weights on Zenodo (https://zenodo.org/records/12701995). Research code, needs PyTorch, the API is unstable. Paper: https://arxiv.org/abs/2407.07275 - **MVSep** (a web service) offers DnR v3 (SCNet, MelBand RoFormer, Bandit v2) with no install, but it means uploading films to a third-party cloud. - For the SFX stem of references the simplest thing works best: take versions **without music** or **with a separate SFX track**; authors often have them. If such references appear, `learn_style.py` computes an exact profile from them in a minute. ## What else was found online (researched 2026-10-14, not adopted) - **songsee** (a skill/CLI, steipete/songsee): draws spectrograms and feature panels (mel, chroma, MFCC). Does the same as `review.py` / `contact_sheet.py` / `zoom.py`, only without ties to frames and the cue sheet. - **A local audio LLM**: Qwen3-Omni (30B MoE, 3B active) runs through llama.cpp in GGUF and can describe sound effects in words. A quantized version takes about 17–20 GB, more than 8 GB VRAM + 16 GB RAM allow without heavy speed compromises. Check the model page and llama.cpp releases before trying. - **Hosted models** (Qwen3-Omni-Captioner via Alibaba's API, Gemini): describe sound with no install, but the audio leaves the machine and a key is needed. - No ready "skill that listens" was found: every option is either spectrogram pictures or a call to an external model. Hence the chosen path: numbers, words, pictures, optionally YAMNet. - skills/real-sfx/references/profiles/clean-sfx-refs.json (4954 bytes)
{ "name": "clean-sfx-refs", "n_refs": 9, "basis": "finished mix of each video", "note": "The references' own music, if any, is part of what was measured; a film that keeps its own music and voice is not meant to match a reel that is only sound design. Digital silence = 250 ms windows under -70 dBFS (re-measured; it was -55).", "measures": { "gest10": { "median": 11.41, "p25": 9.03, "p75": 12.14, "min": 6.94, "max": 15.11, "n": 9 }, "gap_med": { "median": 0.71, "p25": 0.58, "p75": 0.83, "min": 0.47, "max": 1.21, "n": 9 }, "gap_p90": { "median": 1.29, "p25": 1.21, "p75": 1.72, "min": 1.1, "max": 3.05, "n": 9 }, "gap_max": { "median": 2.5, "p25": 2.0, "p75": 2.7, "min": 1.4, "max": 5.8, "n": 9 }, "spread_db": { "median": 12.2, "p25": 10.0, "p75": 19.4, "min": 3.7, "max": 21.3, "n": 9 }, "typ_db": { "median": -5.0, "p25": -8.7, "p75": -3.8, "min": -12.3, "max": -2.7, "n": 9 }, "first_s": { "median": 0.21, "p25": 0.14, "p75": 0.28, "min": 0.08, "max": 1.21, "n": 9 }, "low_share": { "median": 72.0, "p25": 67.0, "p75": 80.0, "min": 11.0, "max": 88.0, "n": 9 }, "bed": { "median": 59.0, "p25": 18.0, "p75": 82.0, "min": 12.0, "max": 96.0, "n": 9 }, "floor_db": { "median": -23.9, "p25": -26.2, "p75": -20.8, "min": -89.5, "max": -14.9, "n": 9 }, "silent": { "median": 0.0, "p25": 0.0, "p75": 0.0, "min": 0.0, "max": 15.0, "n": 9 }, "lufs": { "median": -14.8, "p25": -15.9, "p75": -14.3, "min": -17.4, "max": -14.1, "n": 9 } }, "per_ref": [ { "file": "reference 1", "dur": 11.07, "events10": 16.25, "gest10": 9.03, "gap_med": 1.04, "gap_p90": 1.72, "gap_max": 2.2, "first_s": 0.19, "low_share": 70.0, "n_gestures": 10, "spread_db": 9.3, "typ_db": -6.7, "floor_db": -15.2, "silent": 0.0, "bed": 96.0, "lufs": -14.8 }, { "file": "reference 2", "dur": 30.37, "events10": 35.23, "gest10": 13.17, "gap_med": 0.72, "gap_p90": 1.25, "gap_max": 1.8, "first_s": 0.14, "low_share": 88.0, "n_gestures": 40, "spread_db": 12.2, "typ_db": -12.3, "floor_db": -32.0, "silent": 2.0, "bed": 12.0, "lufs": -16.5 }, { "file": "reference 3", "dur": 14.98, "events10": 31.38, "gest10": 12.02, "gap_med": 0.83, "gap_p90": 1.21, "gap_max": 1.4, "first_s": 0.08, "low_share": 72.0, "n_gestures": 18, "spread_db": 15.4, "typ_db": -4.5, "floor_db": -26.2, "silent": 0.0, "bed": 59.0, "lufs": -14.7 }, { "file": "reference 4", "dur": 10.71, "events10": 18.68, "gest10": 12.14, "gap_med": 0.47, "gap_p90": 1.12, "gap_max": 3.1, "first_s": 0.26, "low_share": 77.0, "n_gestures": 13, "spread_db": 11.6, "typ_db": -8.7, "floor_db": -89.5, "silent": 15.0, "bed": 16.0, "lufs": -15.9 }, { "file": "reference 5", "dur": 12.97, "events10": 10.02, "gest10": 6.94, "gap_med": 0.58, "gap_p90": 3.05, "gap_max": 5.8, "first_s": 0.12, "low_share": 11.0, "n_gestures": 9, "spread_db": 3.7, "typ_db": -5.0, "floor_db": -14.9, "silent": 0.0, "bed": 88.0, "lufs": -14.1 }, { "file": "reference 6", "dur": 12.07, "events10": 13.25, "gest10": 8.28, "gap_med": 1.21, "gap_p90": 1.68, "gap_max": 2.0, "first_s": 1.21, "low_share": 60.0, "n_gestures": 10, "spread_db": 10.0, "typ_db": -3.1, "floor_db": -22.3, "silent": 0.0, "bed": 58.0, "lufs": -14.2 }, { "file": "reference 7", "dur": 13.14, "events10": 31.96, "gest10": 11.41, "gap_med": 0.71, "gap_p90": 1.29, "gap_max": 2.5, "first_s": 0.21, "low_share": 80.0, "n_gestures": 15, "spread_db": 21.3, "typ_db": -2.7, "floor_db": -23.9, "silent": 0.0, "bed": 65.0, "lufs": -14.8 }, { "file": "reference 8", "dur": 67.5, "events10": 29.93, "gest10": 15.11, "gap_med": 0.54, "gap_p90": 1.1, "gap_max": 2.7, "first_s": 0.35, "low_share": 83.0, "n_gestures": 102, "spread_db": 19.4, "typ_db": -10.4, "floor_db": -25.6, "silent": 0.0, "bed": 18.0, "lufs": -17.4 }, { "file": "reference 9", "dur": 12.54, "events10": 12.76, "gest10": 9.57, "gap_med": 0.65, "gap_p90": 2.43, "gap_max": 2.7, "first_s": 0.28, "low_share": 67.0, "n_gestures": 12, "spread_db": 19.9, "typ_db": -3.8, "floor_db": -20.8, "silent": 0.0, "bed": 82.0, "lufs": -14.3 } ] } - skills/real-sfx/references/project-audio.md (9585 bytes)
# Sound already in the project: synthesis, stems, a synthesizer script A project written for a synthesized score keeps music, voice and effects in one track file. Real sounds on top of it are double sound. The task: remove **only** the synthesized effects layer and keep the music and voice as the author mixed them (levels, the music ducked under the voice). ## What the project has → what the script does `from_cues.py` looks for the project's audio (`assets/audio/stems`, `audio/stems`, `assets/audio`, `audio`, `assets`; the root is taken from the list's folder, then from `--video`, or `--project FOLDER`) and classifies files by name: voice (`voice`, `vo_track`), music (`music`, `bed`), the synthesized layer (`sfx`, `transitions`, `impacts`, `whoosh`...), a finished mix (`final_mix`, `premix`, `mix_raw`). Then: | What was found | What happens | What the output looks like | |---|---|---| | The synthesized layer as a separate file (`sfx.wav`, `transitions.wav`) | **`unbake`**: the mix minus the stem. Source: the render or, if the project keeps the same mix lossless (`final_mix.wav`), that file. The gain is found by least squares, the delay to the sample (a stem can lag: an AAC render by one codec frame, 21.3 ms). Music and voice stay **with the author's levels and ducking**. A mono stem is taken as is (3 dB used to be lost) | `unbake: mix final_mix.wav minus sfx.wav (+2.2 dB) ... correlation 0.43 -> -0.00` | | What is left after subtraction is quieter than −60 dBFS | the render was that layer: the base is empty, `keep_audio: no` | `what is left is silent: the render's audio WAS the synthesized layer` | | The same, but the render lacks this layer (no correlation) or the stem has another length | refused, the reason named (stems from another version) | `unbake: not possible (...)` + `WARN stems ... do NOT belong` and a list of the project's renders the stems fit | | The mix went through a fast limiter or compressor (the synthesis envelope remains after subtraction) | refused: one multiplier does not follow a limiter; if the render is synthesis only, `keep_audio: no`, otherwise a rebuild from stems or the script | `unbake: not possible (... the mix is limited or compressed ...)` | | Only voice and music stems (no effects stem) | the base is rebuilt from the stems; levels are fitted by the loudness shape, not taken as one; a stem that is not in the mix (an old `bed.wav`) is dropped | `stems: ... belong to this render`, `levels that fit: {...}` | | Music and effects are synthesized by **one script** (`audio.cjs`), no separate files | `from_synth.py`: the script runs without writing files, a second run with the effects off gives the music without them (`_synth/bed_only.wav`); the base = that + the voice file, levels fitted in the voice's pauses, the music ducks under the voice (`--duck-music`) | `events from the project's synthesizer script ...`, `rebuilt from that script WITHOUT the effects` | | **Effects placed inside the music stem** (a riser, a bell, a drone on the music bus: `music.wav` contains them) | the music stem keeps them: real risers would land on top. Make a file with only those effects (run the score twice: once with the effects, once with those calls sent to a "trash" bus, without changing the random number sequence; the difference of the two `music.wav` files) and pass `--extra-synth FILE`: it is subtracted the same way as `sfx.wav` | the correlation of `music.wav` with the riser after unbake stays well above zero; risers are visible in the stem's spectrogram | | None of this: the render's track is synthesis plus voice, no stems and no script | said honestly; `NOTE: could not hear` or `BAKED`. Ask for a render without effects, the voice and music files (`mix.py --base-audio music.wav:-7 vo.wav --duck-music`) or the script; if the whole track is synthesis: `--drop-original` (in this case `from_cues` writes `keep_audio: no` itself if the render is quiet between events) | `BAKED`, `NOTE: ...` | After the build the mixer prints what the base became (`base audio rebuilt ... (the synthesized layer was subtracted ... | rebuilt from the project's script WITHOUT the effects, levels fitted | rebuilt from the project's stems)`) and warns if the base was raised by more than 1.5 dB "to match the original" (`WARN the rebuilt base was moved ...`): that means voice and music moved relative to each other; check the levels (`--base-audio FILE:dB`). Even when the list did not come from `from_cues` (frames, `suggest_cues`), `mix.py` compares the original with the cue times and warns that synthesis sits under them (`the original audio has a sound at N% of the cue times`). **What the sheet holds for the base.** `base_audio` is a list of files or objects `{"file", "gain_db", "offset", "keep_level", "key_only"}`: `keep_level` does not pull the base's loudness to the original (it was subtracted, not rebuilt), `key_only` means the stem is not heard, it only drives the ducking (`voice_key`). `from_cues` writes these fields itself; to lay in your own base: `sheet.py top SHEET 'base_audio=[{"file":"D:/p/music.wav","keep_level":true}]' duck_music=false`. `mix.py --base-audio` knows only `FILE[:dB][@sec]` and loses `key_only`. ## An event list without a list file If the project does not write `cues.json` but a script makes the sound, the events are in it: calls like `whoosh(4.2, 1, 0.3, 0.5)`, `click(18.35)`, `key(t, i)` or objects `cues.push({t, type, gain, len})`. Do not extract them by hand: ``` python scripts/from_synth.py PROJECT_FOLDER --out work/events.json [--bed-only work/bed.wav] [--dry] python scripts/from_cues.py PROJECT_FOLDER --video RENDER.mp4 --out work/cues.json # the same in one step ``` The script is found in the `scripts/`, `audio/` folders; functions with time as the first argument (`t`, `time`, `at`, `start`) and no generator parameter are recorded; helpers (an `add` that every effect calls) and functions that return a number (a loudness curve) are not events. Numeric arguments `f`/`freq`/`hz` and the `up` flag are recorded too: the author's frequency intervals become the replacement's pitch steps. File writing and process launching inside the script are disabled, the project is not changed. An ES module (`.mjs`) does not run; if a list sits next to it (`scripts/cues.json`), `from_cues` on the folder takes it: a list beats a script. The output names the kinds and counts (`click x101, whoosh x16`): check them against what you see in the frame. A run of `click` 62 ms apart in a project is often typing (a comment in the script says so): `from_cues` recognizes such a run itself (`typing:`). **Time in the list.** A script often converts "author time" to "film time" (`W(t)`, `timing.json`), and the recorded times are author time. `from_cues` takes the project's map (`assets/timing.json`: `anchors` or `DUR` + `WARP`, pairs `[film_time, author_time]`, its own monotonic cubic curve) when the script reads it. Otherwise: a map from the stems' onsets (`references/typed-cues.md`). The time of a whoosh in a script can be its **start, peak or centre**: `from_cues` moves it to the peak of the synthesized sound only if that is not another sound (a pop, a bell at the same moment) and there is no loudness dip on the way; a refusal is printed with the reason (`retime: ... NOT moved ...`). ## The loudness of the replaced layer and the author's chain `from_cues` measures the loudness of the synthesized layer as it sat in the mix (`_draft.layer_lufs`), and `mix.py` raises the real SFX to it (`SFX layer: ... -> +N dB`): the author mixed "quiet and sparse" (g 0.07–0.3), and without this everything would sit at −30 dBFS. Only upward. `--no-match-layer` or `--sfx-trim-db X` turn it off. Then `levels.py` compares event by event (each kind against the author's layer) and writes edits for `sheet.py apply`. **The author's mix chain.** A rebuild from the script or stems does not know it: `--duck-music` (threshold 0.04, ratio 4, 15/350 ms) does not repeat the `sidechaincompress` and limiter from the project's `scripts/mix.sh`: the music under speech may sit 1–2 dB differently. If the project has a `mix.sh` or an ffmpeg graph: run `bed_only.wav` and the voice through the same graph without the effects, put the result into `base_audio` (`keep_level: true`) and remove `duck_music`. The final loudness of such a base is pulled to the original by itself (the original's peak ceiling is kept). ## Rules - Stems cannot be trusted by name: length and loudness shape are checked. Stems from a late edit with a render from an early one give `do NOT belong`; voice the render they fit (the script names it). - The project has a voice but this render does not (`listen.py voice RENDER`): another version of the film. Tell the user that "keep the voice" has nothing to act on here. - Tonal music: the pitch steps of uisfx and of the library's tonal sounds turn off by themselves when the render has 30 % or more music or there is a score (`bed_only.wav`, a music stem); pitches are tuned to its notes (`tonal fit`). - Checking that "the synthesis is gone": the critique's `doubling` axis (the correlation of the layer with the original and with the new film; about zero) and the `unbake` numbers (before and after). An AAC codec residue around events (−15…−25 dB from the synthesis peak) is possible if the source is the render itself (an MP4 has no lossless mix); it is not heard under music and voice. - Start time: a stem from an AAC render lags by 21.3 ms (one codec frame); the new MP4's sound is exactly on the timeline. - skills/real-sfx/references/recipes.md (5699 bytes)
# Sound design recipes and what backs them Source of the numbers: the author's profile of 13 reference films, 308 picture events (`learn_style.py`; the profile itself is not shipped). It gives few numbers, and they are honest: below it says what was measured and what is taken from common practice (marked "practice"). ## What was measured on the references | Measure | Value | How to use it | |---|---|---| | Mix loudness | on average −18 dB RMS per second, ~10 dB spread between seconds | A reference for balance: SFX should not "shout" over the music. Master the result to −14 LUFS | | The sound's peak relative to the picture event | median +6…+20 ms, 25–75 % = −60…+80 ms | The loud point of the sound sits on the moment or 10–20 ms later. Peak alignment already takes this into account; for hits on a cut you can use `t + 0.015` | | Sounds with "air" against lows on an event | on 65–70 % of bursts and onsets the band < 120 Hz (sub) grew, on cuts 41 % | Not every hit is heavy: lows only on significant moments | | Density of sound events | ~15 per 10 s including music, picture events ~7 per 10 s | No more than one sound per picture event, and not on every one | | Hook | a sound event in the first 2 s in 100 % of the films | Do not leave the first 2 s quiet | | Long pause | median between events 0.4 s, the longest 3.2 s | Emptiness longer than 3–4 s without a reason looks like a hole | ## What could not be measured (important not to make it up) - **Which exact sound sits on an event.** In the references the music covers the SFX; after correcting for chance coincidences, "a sound exactly on the event" is distinguishable from noise in only 4 films of 13, ~12 % on average. Detailed recipes like "cut = such-and-such sound" cannot be derived from this data. - **The "riser → dip → hit" rule** looks impressive in one film, but across 13 films it occurred only 13 times (0.3 per 10 s). It is a device for main moments, not a norm. - Learning this needs references without music, with a separate SFX track, or the user's manual labels (which sound is heard there). `learn_style.py` recomputes the profile in a minute. ## Recipes (practice, use deliberately) ### 1. A cut (the default) A short `whoosh` of 0.3–0.7 s, peak at `t − 0.06`, and a `hit` at `t + 0.015` if the cut is heavy. ```json {"t": 2.0, "label": "cut", "pick": {"role": "whoosh", "target_dur": 0.5, "max_dur": 0.9}, "fit_dur": 0.5, "anchor": "peak"}, {"t": 2.015, "label": "cut hit", "pick": {"role": "hit", "punchy": true, "max_dur": 1.2}, "gain_db": -3} ``` ### 2. The main accent (a title, a logo, the finale), in layers `hit` + `sub_drop` (lows, filtered) + a short bit of "air" (`glitch`/`glass`) on top, no more than 3 layers. **This is a recipe for a cinematic film.** In a product / UI film, a person in blind tests (2026-10-15) called a low hit "off topic" (the bed and bass boosts in four films, then "not here" for 5 of 9 sub_drops on the final cut), and chose a music box as the hit on a scene change: there the accent is a `chime` / a short bright `hit`, without a `sub_drop`, until the person asks for lows. If lows are needed, they are short (about 1.2 s), not a 3 s sub drop. ```json {"t": 5.0, "label": "title lands", "pick": {"role": "hit", "punchy": true, "max_dur": 1.5}, "layers": [ {"dt": 0.0, "pick": {"role": "sub_drop", "max_dur": 2.0}, "gain_db": -7, "lowpass": 150}, {"dt": 0.02, "pick": {"role": "glass", "max_dur": 0.8}, "gain_db": -12} ]} ``` ### 3. Riser → dip → hit (for one or two heroic moments per film) The riser ends 0.15–0.25 s before the hit, then a short silence, then a hit with a sub layer. Make the silence by trimming the riser with `max_dur` while the hit stands on `t`. ```json {"t": 9.8, "label": "build", "pick": {"role": "riser", "target_dur": 1.8}, "fit_dur": 1.8, "anchor": "end"}, {"t": 10.0, "label": "drop", "pick": {"role": "hit", "dark": true, "max_dur": 1.5}, "layers": [{"dt": 0.0, "pick": {"role": "sub_drop", "max_dur": 2.0}, "gain_db": -6, "lowpass": 150}]} ``` Put the riser with `anchor: end` on `t − 0.2`, not `t`: there must be a pause between them. ### 4. An interface cluster (clicks, panels appearing) One `click` or uisfx signal per significant appearance, the rest quiet. Three clicks in a row on the same appearance sound like mush. ```json {"t": 3.5, "label": "panel", "uisfx": "open", "pitch": 0}, {"t": 3.68, "label": "tick", "pick": {"role": "click", "max_dur": 0.3}, "gain_db": -9} ``` ### 5. Music carries the film If the picture's events sit on the music's beats, do not add your own pulse on top: keep only the hits of significant moments in the SFX and leave the rest to the music. A heavy low hit under the music's heavy bass is not heard: take a brighter hit (`--bright`) or cut the layer's lows (`highpass`). ### 6. Voice carries the film (a narrator on top) The voice leads, the SFX serve it. `mix.py --voice-safe`; no beds; UI ticks and whooshes 6–10 dB quieter (`gain_db` −6…−10 in the cue); heavy hits only in speech pauses or on phrase changes (look at the original's spectrogram with `zoom.py`); `masking.py` lists the sounds lying on top of speech: move them into a pause, shorten them (`max_dur`) or cut them with `highpass: 400`. ### 7. What `suggest_cues.py` does by default It takes no more than 5 sounds per 10 s, skips weak moments, puts a hit only on the top third of cuts (by `pct`, not by `strength`: `strength` hits 1.0 for many), a sub layer only under the heaviest, alternates pitch (0, −2, +2, −3, +1, −1), takes UI from uisfx by a hint (`hint`: button, card, toggle, success…). This is a skeleton; a person then corrects it by eye. - skills/real-sfx/references/screencast.md (8209 bytes)
# Screen recordings: events by region A screen recording has no event list, and its picture is noisy: a blinking indicator, a caret, the cursor, the recorder's duplicate frames. Over the whole frame `find_moments.py` calls such noise "the strongest moment", so events are searched **by region**: each with its own threshold and its own event kind. `suggest_cues.py` on a whole screen recording does not work (dozens of sounds on blinking indicators). ## 1. Find the regions ``` python scripts/look.py FILM --out work/look # frames + the original sound python scripts/look.py FILM --at 12.4 --crop x,y,w,h --tile-w 480 --out work/at12.png python scripts/ui_events.py FILM --out work/ui --grid 6x4 [--from A --to B] # where the picture is alive ``` The grid prints a "share of time / events" table by cell and **suggests regions** (`--roi area1=x,y,w,h`): neighbouring cells with events are merged, video and animation (changing almost all the time without events) are dropped. This is a starting point: refine the box from the frames with `look.py --at ... --crop`. A `--from/--to` window cuts the recording before the analysis (seconds instead of minutes); on a short window the grid may suggest nothing (this is not an error). **You set the regions from the frames**: for a chat the grid will suggest the whole feed column (600 events), while what is needed is the input field as one line (`typing`), the corners with toasts (`popup`), the feed column as `scroll@A-B`, the tab bar (`click`). `timeline.png` and the cell table help decide where and when. ## 2. Regions and their kinds ``` python scripts/ui_events.py FILM --out work/ui \ --roi input=x,y,w,h:typing@0-91 --roi toast=x,y,w,h:popup --roi layers=x,y,w,h:scroll@93-173 \ --roi dialog=x,y,w,h:toggle@18-22 [--roi play=x,y,w,h:click --roi screen=0,0,W,H:window] ``` | kind | what counts | sound | |---|---|---| | `typing` | a pulse per keystroke; caret, spinners, blinking dots are dropped by position; big changes (clearing the field) are not keystrokes | `key` (−30 ms: the picture lags) | | `popup` | something appeared (a toast, a dialog, a menu); `len` how long it stays | `pop` | | `toggle` | like `popup`, and **disappearing** is an event too (a dialog closed, an option chosen) | `pop` + a quiet `click` | | `scroll` | continuous motion, one event per stretch, with a length | `whoosh` | | `click` | a short local change (a button, a highlight) | `click` | | `window` | the whole picture changed (ffmpeg scene score); echoes in other regions do not count | `wipe` | `@A-B` goes anywhere after the box (`box@0-91:typing` and `box:typing@0-91` are the same): the range cuts the recording to the scene before the analysis, and noise and threshold are taken where the region means something. **Start a typing range before the first letter**: `NOTE: keys already run at the very start of the range` means typing began earlier (the first word was eaten, the count is low). Take the typing region along the **line of text**, without the icons on the right and the panel under the field. `NOTE: something was already showing at the start` means the first change may be a disappearance and the threshold is inflated by noise: narrow `@A-B` to a few seconds around the event (on a dialog at 18–22 s the threshold missed the opening at 19.17 s, with `@19-20.5` it found it). A third part `:kind:sound` changes the sound (`toast=...:popup:chime`). **The kind is chosen by the region's type, not by the picture.** Answer text growing in a `scroll` region gives a "scroll", scrolling a layer list in a `click` region gives a run of clicks, a player in the chat gives a "scroll": look at the frames around the events and reassign the kind (`--kind` in from_cues) or replace the run with one layer (a scroll wheel recording from the library: `search.py --query wheel`, role `click`; a layer with `loop_to`/the event's length). ## 3. What the script cleans up itself and what to check - events of several regions in the same frame (a redraw) are merged into one; an echo two frames later is removed; - **timers and spinners**: a run of 6 or more (8 for clicks) evenly spaced pulses in `scroll`/`click` (period 0.25–2.5 s) is not a scroll and not a click; dropped, times named (`--keep-periodic` keeps them); for typing there is `--drop-periodic`; - **the sound of clips playing in the recording's window** (`native sound`): if the recording's own sound plays rarely (up to 40 % of the time) and without speech, events inside its windows are dropped: those moments already have sound (`--no-native-gate` turns this off); the window times are printed and stored in `ui_events.json` (`native_windows`); - **windows** (`window`): an event's scene score is in `NOTE: scene scores ...`; weak ones (< 0.5) are a redraw of one window, not a change (`--scene 0.5` keeps the strong ones); the event's loudness follows the score; - `timeline.png`: one row per region (activity, threshold, events in red); `checkpoints.png`: the input field at several places with a keystroke count (`--check 50,60,70,85`, any times). **Count the characters on screen and compare.** Fewer keystrokes: the recording was sped up, frames merged keystrokes (the count is a lower bound). More: deletions and spaces (keystrokes too), spell-check underlines, icons or another scene inside the region. Animated typing (the film draws text at 50 characters a second) gives few pulses: write a stretch by hand (`{"t":19.99,"type":"typing","len":0.36,"n":99}`), `from_cues` unfolds it into keystrokes (`--type-rate`, 8–14 a second). - **Look at the events with your own eyes before `from_cues`**: `look.py FILM --moments work/ui/events.json --out work/ev.png [--crop x,y,w,h --tile-w 320]` draws the frame BEFORE and AFTER each event (sampled by kind and region). A raw list for a 170 s recording holds dozens of false ones (mouse hover, the chat redrawing after Enter, a status timer); you see them at once, and the critique will not show them (the sound sits on its event). ## 4. Next ``` python scripts/from_cues.py work/ui/events.json --video FILM --ui library --out work/cues.json ``` The "is this the right render" check is skipped for a list that was itself measured from the picture. `--ui library`: clicks from the main pack (double-click recordings: the press is the first click, `"slice": "first"` is set automatically), keys from typing recordings. One mouse, one keyboard and one wheel are marked `same_source` by themselves: variety is not judged for them. A missing moment (Enter, Space, a missed click): `sheet.py add SHEET --event [email protected]`. ## 5. What the script cannot see - **Animation in a window that plays without sound** (silent preview runs in After Effects): there is no sound, but the picture carries events. `find_moments.py FILM --roi x,y,w,h --from A --to B` on the player's region gives moments (calibrate on bursts of native sound where there is some; `ui_events.py` prints the native sound windows); write the events in by hand (`sheet.py add --event` or `--from`). Ask the user whether those windows need sound: they were silent in the original too. - Space, Enter, Backspace, paste rarely exist as separate recordings in a library: they are taken from the general keyboard pool. - "A dialog opened" has no sound of its own: a `pop` from the library. ## 6. Screen recording metrics The critique counts the hook from the picture's first event (`first_event_t`: the frames are still until then, a sound on it is a hook of 10), a long layer (the wheel) holds its place while it sounds, a run of keystrokes counts as one event. `pacing` is not judged for a screen recording (`n/a`): the pace is the person's work, the agent waits for a model's answer, 10 s of silence in the feed is right. Axes that may fall short with the right sound: `loudness` (BS.1770 gating: new quiet sounds in the original's silence pull the integrated loudness down while the native sound is untouched; the critique compares the original's windows and will say it is gating). `--ceiling-db -0.5` if the native sound peaks above −1 dB: otherwise the master gain moves the native sound. - skills/real-sfx/references/typed-cues.md (15789 bytes)
# The project's event list (typed cues) If a film is made with code (HyperFrames, Remotion, "a film as a function of time"), the author usually knows what happens and when. Projects written for a synthesized score keep this knowledge in a list `docs/cues.json` or in the calls of a synthesizer script (`audio.cjs`: `whoosh(4.2)`, `click(18.35)`): time, event kind, relative loudness. Such a list is more precise than any frame analysis: a keystroke, a click, a coin, a wipe are named, not guessed. `from_cues.py` takes the times and kinds and replaces the synthesis with **real** sounds (interface moments from uisfx, the rest from the library). ``` python scripts/from_cues.py docs/cues.json --video renders/film.mp4 --out work/cues.json # the list in a file python scripts/from_cues.py PROJECT_FOLDER --video renders/film.mp4 --out work/cues.json # the project's own list, otherwise the script's calls echo '[{"t":1.2,"type":"click"}]' | python scripts/from_cues.py - --video film.mp4 --out work/cues.json python scripts/mix.py work/cues.json --out result/film_sfx.mp4 --voice-safe ``` Sound already in the render (synthesis, stems, a script): `references/project-audio.md`. Screen recordings: `references/screencast.md`. ## No project list: write it from the frames Soft coloured animation (a UI preview, an illustration, motion graphics) has no list from the author, and automation (`find_moments`, `suggest_cues`) sees 5–6 moves of ~40 and draws only whooshes. Then the event list **is written by whoever looks at the frames** and fed to the same `from_cues.py`: the sounds are chosen by the same rules as for a project list (typing from a real keyboard, levels by role, one render with the critique). All four blind tests on 2026-10-15 went this way. ``` python scripts/find_moments.py FILM.mp4 --out work/moments --fine # candidates; chroma+luma, src in the moments python scripts/look.py FILM.mp4 --at 2.2 --span 2.4 --step 0.1 --out work/at.png # 24 frames, 0.1 s apart cat work/events.json | python scripts/from_cues.py - --video FILM.mp4 --out work/cues.json --ui library \ --moments work/moments/moments.json ``` `work/events.json` (any keys from the table below, nothing extra needed): ``` [{"t": 0.06, "type": "whoosh", "len": 0.7}, {"t": 0.80, "type": "pop"}, {"t": 1.12, "type": "whoosh", "len": 0.5, "g": 0.8}, {"t": 2.19, "type": "key", "len": 1.4, "n": 17}, {"t": 4.10, "type": "hit"}, {"t": 5.53, "type": "wipe"}, {"t": 9.60, "type": "chime"}] ``` What to write down: an element entering and leaving (`whoosh`, `pop`), a morph and a landing (a quieter `hit`, `thump`), a cursor press (`click`; the cursor is visible by colour), a run of counter digits (`tick`), typing (`key` with a stretch: `len` seconds, `n` characters), a scene change (`wipe`, `hit`), success or a badge appearing (`chime`). **The time is the frame where something starts to happen**, not the still frame after it. Do not write down what the ear does not need: flicker, background drift, static. `--ui library`: interface kinds from real recordings (otherwise `click`, `pop`, `chime` go to uisfx, that is, to synthesis). Pitch of repeats: `from_cues` cycles the pitch of repeated sounds by ±1–3 semitones; `--ui-pitch off` keeps the own pitch of uisfx repeats and of the library's tonal sounds (chime, pop, glass, coin); for one sound: `sheet.py set --at T pitch=0`. ## Format A JSON list (or `{"cues": [...]}` / `{"events": [...]}`) of objects: | key | synonyms | meaning | |---|---|---| | `t` | `time`, `at`, `start` | seconds on the timeline of **the render you are voicing** (or in the author's time, see the time map) | | `type` | `name`, `kind`, `event`, `sound` | the event kind, table below | | `g` | `gain`, `volume`, `vol` | 1.0 = nominal; converted to dB relative to the role | | `len` | `dur`, `duration`, `length` | seconds: the build of a riser, the length of a whoosh; for `key` the length = the typing stretch | | `n` | `chars`, `count` | for a typing stretch, the number of keystrokes (otherwise `--type-rate` per second, 11 by default) | Other fields (`notes`, `f0`, `seed`: synthesis parameters) are ignored. If a whoosh has no `len` in the list or in the script, it is measured from the synthesized sound it replaces (`length: N ... measured`). ## Kinds and what they become | kind (synonyms) | source | pick | |---|---|---| | `whoosh` (swoosh, swipe, slide, move, zoom, push, pan) | library | `whoosh`, length from `len`, pitch cycled | | `wipe` (transition, scene, cut) | library | `whoosh` 0.7 s, 4 dB quieter | | `hit` (impact, slam, stamp, stinger, boom) | library | `hit` with a sharp attack, pitch cycled | | `thump` (kick, bass_hit) | library | **clean single foley hits** (body, floor, wood; 150 Hz highpass under music), otherwise a dark `hit`, otherwise `sub_drop` | | `riser` (build, swell, tension) | library | `riser` of length `len`, starting at `t` | | `drop` (sub_drop) | library | `sub_drop`, otherwise a dark `hit` of 1–3.5 s | | `click` (press, tap, button, select) | uisfx `press` | pitch ±1–2 semitones cycled; from the library: single clicks of the main pack, then the first click of double-click recordings | | `pop` (bubble, blip, appear) | uisfx `select` | the same; from the library the `pop` role (mouth pops are not taken without a word in the query) | | `tick`, `tock` | uisfx `progress-step`, `snap` | the same; from the library `click`, then `water` drops | | `chime` (bell, ding, notify) | uisfx `notification` | from the library the `chime` role (bell, ring) | | `success` (ok, done, complete) | uisfx `success` | from the library `chime` with the Ding tag | | `glass` (crystal) | library `chime` (a ringing "glass" ping, Star/Ding) | | | `shatter` (smash, break) | library `glass`: **breaking** glass | | | `magic` (sparkle, shimmer, glow, heal, reveal) | library `chime`, the word magic | sparkles, music box, harp | | `water` (drip, splash, droplet) | library `water` | drops of 0.1–0.7 s | | `coins` (cash, money, purchase) | library `coin`, otherwise uisfx `purchase` | | | `key` (keystroke, type, typing) | **pieces of real typing recordings** | see below | | `glitch` | library `glitch`; if there are no short ones, a piece (0.12–0.5 s) of static or noise | | | `error`, `camera`, `paper`, `data`, `ambience` | library, the role of the same name | | The script does not guess an unknown kind: it stays quiet and goes into the "NOT mapped" list (and into the summary line `declared N events: M voiced, K silent`; the critique counts silent kinds as a hole in coverage). You can say what it is **in one line, without a file**: ``` --kind bead=click the project's kind = a kind the script knows --kind soft=role:click,max_dur=0.3,onsets_max=1 a role with limits (any pick key) --kind boop=uisfx:select one uisfx signal --kind bead=slices:740,763,804 single sounds of these recordings in turn (ids from search.py); the quietest, 12 dB under the loud ones, do not go into the bank: "clean singles" only for recordings where `listen.py onsets` showed them --kind pop=key a contact tick from real keystrokes --map '{"stomp": {"pick": {"role": "hit", "dark": true}, "gain_db": 2}}' JSON as a string or a file --map '{"ball": {"ids": [800, 779, {"id": 780, "slice": [0.1, 0.12]}], "role": "hit"}}' takes in turn; an id has its own slice --map '{"click": {"pick": {"role": "click", "max_dur": 0.7, "tier": "main"}, "slice": "first"}}' ``` `--remember` keeps the mapping for all later projects. `--ui library` takes interface kinds from real recordings instead of uisfx, `--from-library pop,bell` only these kinds (**kind names from the list**, not roles), `--only` / `--skip` select kinds. `--one-source thump,pop` for one physical object (a ball, steps): **one family of recordings** is picked (takes of one recording in turn), `same_source` in the cue: variety is not judged for them; it works the same for a kind defined via `--map`/`--kind` (`--kind soft=role:pop --one-source soft`). One detail: `from_cues` prints `routes: kind -> uisfx:name | library:role` so the route is visible. **The source of interface kinds** (`click`, `pop`, `tick`, `tock`, `chime`, `success`): uisfx, **if the list itself names real interface events** (`click`, `key`, `tick`, `tock`, `chime`, `success`, `error`); a mapping via `--kind` does not count as interface: a ball and beads stay in the library. `from_cues` prints `ui: auto -> ...` with the reason. `--ui uisfx|library` overrides it. For "one click" from the library it takes recordings with one sound inside, then double-click recordings with `"slice": "first"`, not three-click gestures and not typing recordings. ## Typing A run of `key` becomes separate real keystrokes: bursts are found in typing recordings (the `typing` role, folders Keyboard, Typing, «клав»), each is cut to 40–85 ms and placed on the key's time with 6 ms of headroom for the attack. **One keyboard per film**: the longest recording of the main pack is taken, the next one is added only while the first ones have fewer keystrokes than the film needs; a real keyboard before a phone one, not too quiet ones. Keystrokes already cut by the pack (one per file) go into the bank when the recordings run short. The recording's dynamics are kept: weak keystrokes are quieter than strong ones. A run faster than `--max-rate` (14/s) is thinned: the eye reads 24 characters a second, the ear needs 10–14. If the library has no typing recordings, the keys stay quiet and the script says so (`--kind key=...`). **Typing written as `click`** (in the script `for (c...) click(6.94 + c / 48, ...)` with a "typing" comment): a run of 8 or more `click` events 35–170 ms apart and at least 0.4 s long is recognized by `from_cues` as typing and given to the keyboard (`typing: N click events ... are typing`); the author's `g` stays, `--no-typing-detect` keeps the clicks. A single click does not count as typing. **Clusters.** Events of one kind closer than `--fuse` (25 ms) are one sound: five beads in 40 ms are a rattle, not five hits. `--fuse 0` keeps them all. The output shows `fused: N` and `thinned: kind N` (what the rate rule thinned). ## Checking "is this the right render" A list of times belongs to one version of the film. After fitting to the voice or a retime, the times drift. The script compares the declared structural events (`wipe`, `hit`, `thump`, `drop`, `camera`: they happen **on** a picture change) with the picture changes in the render (`--video` runs the analysis, `--moments` takes a ready one). For a list that was itself measured from the picture (`ui_events.py`), the check is skipped. - "list belongs to this render": 60 % or more within 120 ms. - "consistently ±X s from the picture": an even offset, rerun with `--shift ∓X`. - "written for another cut": less than 60 % match and no offset explains it. Take the list written for this render, or moments from the picture. Whooshes and interface ticks do not take part in the check (they are placed relative to motion). Next, `--moments` prints **strong picture changes without sound** (±150 ms): events the project forgot to declare. One final verdict is printed after the time map (before it, the picture may have complained about an offset the map already removed). ### A design-time list, a render fitted to the voice: the time map Projects with a voice write the list in "design time", then stretch the scenes to the voice: stems and render are new, the list is old, and the offset is uneven (up to +2.9 s along the film). A constant `--shift` does not cure it. What `from_cues.py` does: 1. **The project's anchors**: `timing.js|json`, `timemap.*`, `retime.*` (searched in `src/`, `assets/`, the root, `docs/`) with `{"anchors": [[design_t, actual_t], ...]}` or `{"DUR": ..., "WARP": [[film_time, author_time], ...]}` (for `WARP`, its own monotonic cubic curve). Used if they improve the match with the stems' onsets (or when the list came from a script that reads this map). 2. Otherwise an **estimate from the onsets** of the synthesized stems: in 6 s windows it finds the offset at which most events land on an onset, with a smooth path (Viterbi); then the events (not whooshes and risers) take onsets by **one monotonic matching over the whole film** (one event per onset; layers of one moment share an onset), not greedily one by one. 3. The map is applied only if afterwards at least 60 % of events meet an onset and that is 20 points better than without it. It prints the range of offsets, the share before and after, the number of events that took an onset, and the picture's verdict. `--time-map FILE.json` (`[[list_time, render_time], ...]`) sets the map by hand, `--warp off` turns it off, `--warp stems|audio` forces it on. An event keeps `t_declared`. **Onsets without an event.** Synthesis can be richer than the list (a stopwatch from the beat grid): `NOTE: N onsets in the synthesized stems have no declared event` lists the times. `--add-unlisted tick` turns them into `tick` events (loudness from the level in the stem); without the flag nothing replaces them: look at the frames there. ## The event time and the synthesized sound `t` in a list made for synthesis can be the **peak** of the sound (the synthesis started earlier), its **start** or its **centre** (`add(t - len * 0.5, ...)`); `len` and `dir` are often lost. A real sound is placed with its peak on `t`, so without a correction a whoosh arrives 0.2–0.4 s before what the author heard. When the synthesis can be measured (stems, or a track made of it alone), `from_cues.py` finds where the synthesized whoosh or wipe really peaks and moves the event there (`retime: whoosh 6.00 -> 6.50 s (+0.50)`). **No move is made** when: on the way to the peak the loudness drops by 6 dB or more and something already sounds at the declared time (it is another sound: a pop, a bell, a click, not the tail of a whoosh); a whoosh is already heard at the declared time and another declared event sits on its peak (the time was its centre); the move is longer than the sound itself. Every reason is named (`retime: whoosh at 18.70 s NOT moved to 19.30 s: ...`), every move over 0.15 s is printed. `--no-retime` turns it off. If the list is not from this render, retiming is skipped. **The author's melody.** If events of one kind have a numeric `freq` (in the script `tick(t, 1800 * 2 ** (4 * i / 12))`), the frequency ratios become pitch steps of the real sound (`melody: N event(s) ...`): a rise of ticks export → build → check stays a rise. ## How to give a new project such a list When you write a composition yourself (HyperFrames, Remotion, your own engine), register sound events at the moment you set the motion, and write them to `docs/cues.json` with `g` and `len`. Then the sound design does not guess from frames - skills/real-sfx/scripts/adjust_test.py (25370 bytes)
#!/usr/bin/env python3 """A test of another kind: the person SETS the levels by ear, on a looping excerpt of a real film with the film's own music and voice, instead of judging finished versions. python adjust_test.py build OUT --items ITEMS.json [--title T] [--seed N] [--no-page] python adjust_test.py plan OUT --items ITEMS.json # the stems and the plan only (no page) Why. Rounds of "which of these is better" answer WHICH sound, not HOW LOUD, and every complaint of the person so far was a level or a place ("громко", "пусто", "не в тему"). Here the stems of a film (its own audio, the sounds, the bed, the variants of one accent) are separate and play on one clock; the person moves a slider until it sits right and marks the accents they would keep. The answer is a number in dB against the film as the skill planned it, which can be written into a default, and a verdict on the accents heard at the same level. ITEMS.json: a list of {"id": "launch", "title": "...", "why": "...", "question": "...", "sheet": "cue sheet of the film as the skill plans it now", # from_cues.py's output "video": "the picture (its own sound is not used)", "base_audio": [...], # base_audio: as in a sheet, optional "t0": 9.0, "dur": 6.0, # the excerpt "voice_safe": true, "voice_depth": "normal", "accent": {"t": 11.9, "label": "thump", # the cue of the sheet the variants stand for "default_db": -4, # level of the variants against the planned one "variants": [{"id": "cur", "label": "as planned"}, {"id": "soft", "label": "...", "derive": {"gain_db": -9, "highpass": 150}}, {"id": "fill", "label": "...", "cue": {"id": 177, "role": "hit", "anchor": "peak"}}, {"id": "none", "label": "nothing", "none": true}]}, "sliders": {"sfx": [-18, 12], "bed": [-30, 18], "acc": [-24, 12]}} What it makes, per film: the film is rendered the way the skill renders it (mix.py, the sheet, --voice-safe), the cue clips it exports are summed into stems at the planned levels (the layer match applied, the voice-safe dip applied the way the pipeline does: the same sidechain, per stem), the stems are checked against the real mix (the residual is printed), the excerpt is cut, and the variants of the accent are equalised by momentary loudness (BS.1770, 400 ms). The page (listen_page.py --adjust-plan) plays them with Web Audio on one clock and writes the answers. """ import argparse import copy import json import re import shutil import subprocess import sys import time from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) import common def _need_numpy(): try: import numpy # noqa: F401 except ImportError: vp = common.venv_python() if vp is None: sys.exit("adjust_test.py needs numpy, which the skill's venv has: python scripts/listen.py install --yes " "(about 45 MB), then run this again") sys.exit(subprocess.run([str(vp), str(Path(__file__)), *sys.argv[1:]]).returncode) _need_numpy() import numpy as np # noqa: E402 import mix # noqa: E402 SR = 48000 HERE = Path(__file__).parent K1 = ([1.53512485958697, -2.69169618940638, 1.19839281085285], [1.0, -1.69065929318241, 0.73248077421585]) K2 = ([1.0, -2.0, 1.0], [1.0, -1.99004745483398, 0.99007225036621]) # ------------------------------------------------------------------------------------------------ small helpers def ff(args): r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-nostdin", *[str(x) for x in args]], capture_output=True) if r.returncode: sys.exit("ffmpeg failed: " + r.stderr.decode("utf-8", "replace")[-400:]) return r def read_pcm(path): """A file as float32 stereo [n, 2] at 48 kHz (a stereo file keeps its level).""" r = subprocess.run(["ffmpeg", "-v", "error", "-nostdin", "-i", str(path), "-vn", "-ac", "2", "-ar", str(SR), "-f", "f32le", "-"], capture_output=True) if r.returncode: sys.exit(f"cannot read {path}: " + r.stderr.decode("utf-8", "replace")[-300:]) return np.frombuffer(r.stdout, dtype="<f4").reshape(-1, 2).astype(np.float32) def write_wav(path, arr): r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-nostdin", "-f", "f32le", "-ar", str(SR), "-ac", "2", "-i", "-", "-c:a", "pcm_s24le", str(path)], input=np.ascontiguousarray(arr, dtype="<f4").tobytes(), capture_output=True) if r.returncode: sys.exit("ffmpeg failed: " + r.stderr.decode("utf-8", "replace")[-300:]) def db(x): return 20.0 * np.log10(max(float(x), 1e-12)) def iir(x, b, a): try: from scipy.signal import lfilter return lfilter(b, a, x) except ImportError: pass b0, b1, b2, a1, a2 = b[0], b[1], b[2], a[1], a[2] x1 = x2 = y1 = y2 = 0.0 out = [] for xn in x.tolist(): yn = b0 * xn + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2 out.append(yn) x2, x1, y2, y1 = x1, xn, y1, yn return np.array(out) def momentary_max(stereo): """The loudest 400 ms of a short sound, BS.1770 K-weighted, LUFS (a click is averaged over the 400 ms, as the standard does: that is how long the ear integrates). Only the sounding part of the array is measured.""" act = np.where(np.abs(stereo).max(axis=1) > 1e-5)[0] if len(act): stereo = stereo[max(0, act[0] - int(0.05 * SR)):act[-1] + int(0.2 * SR)] n = max(len(stereo), int(0.4 * SR)) st = np.zeros((n, 2), dtype=np.float64) st[:len(stereo)] = stereo p = np.zeros(n) for c in (0, 1): y = st[:, c] for b, a in (K1, K2): y = iir(y, b, a) p += y * y cs = np.concatenate([[0.0], np.cumsum(p)]) w, hop, best = int(0.4 * SR), int(0.05 * SR), -200.0 for s in range(0, max(1, n - w + 1), hop): best = max(best, -0.691 + 10.0 * np.log10((cs[s + w] - cs[s]) / w + 1e-12)) return best def excerpt(arr, t0, dur): n, s = int(round(dur * SR)), int(round(t0 * SR)) seg = arr[s:s + n] if len(seg) < n: seg = np.pad(seg, ((0, n - len(seg)), (0, 0))) seg = seg.copy() f = int(0.012 * SR) # the loop point: a short fade each side, no click ramp = np.linspace(0.0, 1.0, f, dtype=np.float32)[:, None] seg[:f] *= ramp seg[-f:] *= ramp[::-1] return seg def place(rows, clips_dir, n, gain=1.0): """Sum exported clips into one stereo stem of n samples.""" out = np.zeros((n, 2), dtype=np.float32) for r in rows: x = read_pcm(Path(clips_dir) / r["file"]) s = int(round(float(r["start"]) * SR)) if s >= n: continue e = min(n, s + len(x)) out[s:e] += x[:e - s] return out * np.float32(gain) # ------------------------------------------------------------------------------------------------ one film def run_mix(sheet_path, out_mp4, extra, label): cmd = [sys.executable, str(HERE / "mix.py"), str(sheet_path), "--out", str(out_mp4), *extra] r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace") if r.returncode: sys.exit(f"mix.py failed for {label}:\n" + (r.stdout + r.stderr)[-900:]) return r.stdout def duck_stem(stem, key_wav, depth, work, tag): """The voice-safe dip of the pipeline, on one stem: the same sidechain, keyed by the same voice.""" n = len(stem) raw_in, raw_out = work / f"{tag}_in.raw", work / f"{tag}_out.raw" raw_in.write_bytes(np.ascontiguousarray(stem, dtype="<f4").tobytes()) graph = ("[1:a]aformat=sample_rates=48000:channel_layouts=stereo,highpass=f=250,lowpass=f=3800[vsc];" f"[0:a][vsc]sidechaincompress={mix.VOICE_DEPTH[depth]}[o]") ff(["-f", "f32le", "-ar", SR, "-ac", 2, "-i", raw_in, "-i", key_wav, "-filter_complex", graph, "-map", "[o]", "-f", "f32le", "-ar", SR, "-ac", 2, raw_out]) out = np.frombuffer(raw_out.read_bytes(), dtype="<f4").reshape(-1, 2).astype(np.float32) raw_in.unlink(missing_ok=True) raw_out.unlink(missing_ok=True) if len(out) < n: out = np.pad(out, ((0, n - len(out)), (0, 0))) return out[:n] def build_film(film, out_dir, work_root): fid = film["id"] work = work_root / fid shutil.rmtree(work, ignore_errors=True) work.mkdir(parents=True) sheet = json.loads(Path(film["sheet"]).read_text(encoding="utf-8-sig")) sheet["video"] = str(film["video"]) sheet["keep_audio"] = "auto" if film.get("base_audio"): sheet["base_audio"] = film["base_audio"] sheet.update(film.get("sheet_extra") or {}) # e.g. {"duck_music": true}, as the film's author has it sheet_path = work / "sheet.json" sheet_path.write_text(json.dumps(sheet, ensure_ascii=False, indent=1), encoding="utf-8") t0, dur = float(film["t0"]), float(film["dur"]) depth = film.get("voice_depth", "normal") # 1. the film as the skill renders it: the real mix, the base, the clips of every cue extra = ["--export-clips", str(work / "clips")] if film.get("voice_safe", True): extra += ["--voice-safe", "--voice-depth", depth] print(f"[{fid}] rendering the film as the skill does ...", flush=True) log = run_mix(sheet_path, work / "film.mp4", extra, fid) report = (work / "film_cue_report.md").read_text(encoding="utf-8") m = re.search(r"final mix\s+(-?[\d.]+) LUFS \(true peak\s+(-?[\d.]+) dBTP, gain\s+([+-]?[\d.]+) dB\)", report) if not m: sys.exit(f"[{fid}] the cue report has no loudness line: {report[:300]}") final_lufs, master_db = float(m.group(1)), float(m.group(3)) m2 = re.search(r"whole SFX bus\s+([+-]?[\d.]+) dB", log) match_db = float(m2.group(1)) if m2 else 0.0 rows = json.loads((work / "clips" / "sfx_clips.json").read_text(encoding="utf-8")) base_wav = work / "film_base.wav" if not base_wav.exists(): sys.exit(f"[{fid}] mix.py wrote no base: give base_audio (the film's own audio without the sounds)") base = read_pcm(base_wav) n = len(base) print(f"[{fid}] final mix {final_lufs:.1f} LUFS, master {master_db:+.1f} dB, layer match {match_db:+.1f} dB, " f"{len(rows)} cues", flush=True) # 2. the stems: bed, the accent cue(s), everything else; the layer match and the voice-safe dip as the pipeline acc = film.get("accent") acc_rows = [] if acc: want_t = float(acc["t"]) acc_rows = [r for r in rows if abs(float(r["t_moment"]) - want_t) < 0.08 and not r.get("bed") and r["role"] in ("hit", "sub_drop", "design", "foley", "other") and (not acc.get("label") or str(r["label"]).lower().startswith(str(acc["label"]).lower()))] if not acc_rows: sys.exit(f"[{fid}] no cue near {want_t} s with the label {acc.get('label')!r} in the sheet") acc_ids = {r["id"] for r in acc_rows} bed_rows = [r for r in rows if r.get("bed") or r["role"] == "ambience"] sfx_rows = [r for r in rows if r["id"] not in acc_ids and r not in bed_rows] g = 10 ** (match_db / 20.0) stems = {"sfx": place(sfx_rows, work / "clips", n, g), "bed": place(bed_rows, work / "clips", n, g)} acc_raw = place(acc_rows, work / "clips", n, g) if acc_rows else None # the film's own accent, not yet dipped acc_cur = acc_raw voice_items = [] for it in sheet.get("base_audio") or []: if isinstance(it, dict): stem_name = Path(str(it["file"])).stem.lower() if it.get("key_only") or any(w in stem_name for w in mix.VOICE_STEM_WORDS): voice_items.append({"file": str(it["file"]), "gain_db": float(it.get("gain_db", 0.0))}) key_wav = None if film.get("voice_safe", True) and voice_items: key_wav = work / "voice_key.wav" mix.build_voice_key(voice_items, n / SR, 0.0, key_wav, work) for k in list(stems): stems[k] = duck_stem(stems[k], key_wav, depth, work, f"duck_{k}") if acc_cur is not None: acc_cur = duck_stem(acc_cur, key_wav, depth, work, "duck_acc") # 3. the check: base + stems at the master gain against the real film's own audio recon = (base + stems["sfx"] + stems["bed"] + (acc_cur if acc_cur is not None else 0)) * 10 ** (master_db / 20.0) real = read_pcm(work / "film.mp4") m_ = min(len(real), len(recon)) res = recon[:m_] - real[:m_] resid_db = db(np.sqrt(np.mean(res ** 2))) - db(np.sqrt(np.mean(real[:m_] ** 2))) print(f"[{fid}] stems against the real mix: residual {resid_db:.1f} dB under the film " f"({'good' if resid_db < -20 else 'CHECK: the stems do not add up to the film'})", flush=True) # 4. the accent variants: rendered once (every one in the same sheet at its own time), equalised by loudness variants = [] if acc: cur_clip = acc_raw if acc_raw is not None else np.zeros((n, 2), dtype=np.float32) vs = acc["variants"] need = [v for v in vs if v.get("cue")] vclips = {} if need: cues = [] for k, v in enumerate(need): c = copy.deepcopy(v["cue"]) c["t"] = 2.0 + 4.0 * k c.setdefault("label", v["id"]) cues.append(c) vsheet = {"duration": 4.0 * len(need) + 4.0, "keep_audio": "no", "cues": cues} vp = work / "variants.json" vp.write_text(json.dumps(vsheet, ensure_ascii=False, indent=1), encoding="utf-8") print(f"[{fid}] rendering {len(need)} accent variant(s) ...", flush=True) run_mix(vp, work / "variants.mp4", ["--export-clips", str(work / "vclips"), "--no-loudnorm"], f"{fid} variants") vrows = json.loads((work / "vclips" / "sfx_clips.json").read_text(encoding="utf-8")) for k, v in enumerate(need): t_v = 2.0 + 4.0 * k r = min(vrows, key=lambda r_: abs(float(r_["t_moment"]) - t_v)) clip = read_pcm(work / "vclips" / r["file"]) # the clip where the cue would put it if the cue stood at the accent's time (a sound that lands on its # peak starts before it) put = np.zeros((n, 2), dtype=np.float32) s0 = max(0, int(round((float(acc["t"]) + float(r["start"]) - t_v) * SR))) e0 = min(n, s0 + len(clip)) put[s0:e0] = clip[:e0 - s0] vclips[v["id"]] = put * np.float32(g) for v in vs: if v.get("none"): variants.append((v, np.zeros((n, 2), dtype=np.float32))) elif v.get("derive"): d = v["derive"] tmp = work / f"derive_{v['id']}.wav" write_wav(tmp, cur_clip) outp = - skills/real-sfx/scripts/beats.py (22716 bytes)
#!/usr/bin/env python3 """Find the beat grid of the music in a video or audio file (no extra packages needed), and check it against the kicks. python beats.py film.mp4 --out work/beats.json [--plot work/beats.png] python beats.py film.mp4 --check 5.0 12.4 20.1 # distance of these moments to the nearest beat python beats.py film.mp4 --suggest-offset work/moments.json # how far to move the music so cuts land on beats Output: {"tempo": 118.4, "confidence": 0.62, "usable": true, "beats": [...seconds...], "downbeats": [...], "kick_check": {"kicks": 97, "within40": 0.98, "median_ms": 1, "shifted_ms": 0}} `usable` is false when no steady, accented pulse was found: do not snap to such a grid. The tempo can be off by an octave (88 vs 176 BPM); the beat positions themselves stay valid. Method: spectral flux onset strength -> autocorrelation for the tempo (60..200 BPM, gently preferring 80..160) -> best phase -> every beat nudged to the nearest onset peak. Downbeats are the 1-in-4 phase with the most low-frequency energy. Good enough to decide whether a picture event sits on the beat; it is not a transcription tool. The grid is then CHECKED against the kicks, independently: the low band (< 125 Hz) alone gives its own onsets, and the share of beats that sit within 40 ms of one is reported. A tracker that locks onto the off-beat (hats stronger than the kick) is a classic failure: when the grid is steady but sits beside the kicks, it is moved onto them (`phase_shift` in kick_check) when that makes most beats land on a kick. `--plot` draws the low band against the grid so the picture can be looked at, the way a person would zoom in on a few bars. """ import argparse import array import json import math import subprocess import sys import zlib import struct from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import _fft # noqa: E402 RATE = 16000 N = 1024 # 64 ms window: resolves a 55 Hz kick (15.6 Hz bins) HOP = 320 # 20 ms hop = 50 frames per second FPS = RATE / HOP LAT = (N / 2 + HOP / 2) / RATE # a frame describes the sound around its middle, not its start KICK_BINS = 7 # bins 2..8 = ~31..125 Hz: the kick, not the bass line's upper notes def decode(path, max_seconds=900): r = subprocess.run(["ffmpeg", "-v", "error", "-nostdin", "-i", str(path), "-vn", "-ac", "1", "-ar", str(RATE), "-t", str(max_seconds), "-f", "s16le", "-"], capture_output=True) a = array.array("h") a.frombytes(r.stdout[: len(r.stdout) // 2 * 2]) return a def onset_strength(x): """Return (full-band flux, low-band flux, kick-band flux) per hop.""" hann = [0.5 - 0.5 * math.cos(2 * math.pi * i / (N - 1)) for i in range(N)] prev = None flux, low, kick = [], [], [] nb = N // 2 for s in range(0, len(x) - N, HOP): re_ = [x[s + i] * hann[i] for i in range(N)] im_ = [0.0] * N _fft(re_, im_) mag = [math.log1p(0.01 * math.sqrt(re_[k] * re_[k] + im_[k] * im_[k])) for k in range(2, nb)] if prev is not None: d = [m - p for m, p in zip(mag, prev)] flux.append(sum(v for v in d if v > 0)) low.append(sum(v for v in d[:26] if v > 0)) # bins 2..27 = ~30..420 Hz kick.append(sum(v for v in d[:KICK_BINS] if v > 0)) else: flux.append(0.0) low.append(0.0) kick.append(0.0) prev = mag return flux, low, kick def detrend(o, win=31): out = [] n = len(o) csum = [0.0] for v in o: csum.append(csum[-1] + v) for i in range(n): a, b = max(0, i - win // 2), min(n, i + win // 2 + 1) out.append(max(0.0, o[i] - (csum[b] - csum[a]) / (b - a))) return out def tempo_from(o): n = len(o) lo, hi = int(FPS * 60 / 200), int(FPS * 60 / 60) mean = sum(o) / n x = [v - mean for v in o] var = sum(v * v for v in x) or 1.0 best, best_lag, scores = -1e9, None, {} for lag in range(lo, min(hi, n // 2)): r = sum(x[i] * x[i + lag] for i in range(n - lag)) / var bpm = 60.0 * FPS / lag prior = math.exp(-0.5 * (math.log2(bpm / 120.0) / 0.9) ** 2) # gentle bias to the 80..160 range scores[lag] = r * (0.5 + 0.5 * prior) if scores[lag] > best: best, best_lag = scores[lag], lag if best_lag is None: return None, 0.0 # parabolic interpolation of the peak l0 = best_lag if l0 - 1 in scores and l0 + 1 in scores: a, b, c = scores[l0 - 1], scores[l0], scores[l0 + 1] den = a - 2 * b + c l0 = l0 + (0.5 * (a - c) / den if den else 0.0) return l0, best def beat_grid(o, low, lag): n = len(o) ilag = max(1, int(round(lag))) # phase: offset that collects the most onset energy best, off = -1.0, 0 for p in range(ilag): s = sum(o[i] for i in range(p, n, ilag) if True) if s > best: best, off = s, p beats, t = [], float(off) while t < n: i = int(round(t)) lo_i, hi_i = max(0, i - ilag // 4), min(n, i + ilag // 4 + 1) j = max(range(lo_i, hi_i), key=lambda k: o[k]) if hi_i > lo_i else i # follow the music gently (drift) but never jump more than a quarter beat t_adj = 0.7 * t + 0.3 * j beats.append(t_adj) t += lag times = [round(b / FPS + LAT, 3) for b in beats] # downbeats: which of 4 phases has the most low-end flux on its beats down = [] if len(beats) >= 8: sc = [] for ph in range(4): idx = beats[ph::4] sc.append(sum(low[min(len(low) - 1, int(round(b)))] for b in idx) / max(1, len(idx))) ph = max(range(4), key=lambda k: sc[k]) down = times[ph::4] return times, down # ------------------------------------------------------------------ the check against the kicks def kick_peaks(k, pct=0.93, min_gap=0.18): """Times (s) of the kick onsets: peaks of the detrended kick-band flux above its 93rd percentile.""" if len(k) < 10: return [] s = sorted(k) thr = s[int(pct * (len(s) - 1))] if thr <= 0: return [] out, last = [], -9.0 for i in range(1, len(k) - 1): if k[i] >= thr and k[i] >= k[i - 1] and k[i] > k[i + 1]: t = i / FPS + LAT if t - last >= min_gap: out.append(round(t, 3)) last = t return out def kick_stats(grid, kicks, tol=0.04): """(share of grid points with a kick within tol, median signed offset in s: kick minus beat).""" if not grid or not kicks: return 0.0, 0.0 import bisect ds = [] for b in grid: j = bisect.bisect_left(kicks, b) cands = [kicks[x] for x in (j - 1, j) if 0 <= x < len(kicks)] k = min(cands, key=lambda v: abs(v - b)) ds.append(k - b) share = sum(1 for d in ds if abs(d) <= tol) / len(ds) srt = sorted(ds) return share, srt[len(srt) // 2] def kick_phase_shift(grid, kicks, period): """The shift (s) that brings the grid onto the kicks: the most crowded offset of the kicks against their nearest beat (10 ms bins, +-20 ms smoothed), None when the kicks have no one offset.""" import bisect res = [] for kk in kicks: j = bisect.bisect_left(grid, kk) cands = [grid[x] for x in (j - 1, j) if 0 <= x < len(grid)] b = min(cands, key=lambda v: abs(v - kk)) d = kk - b if abs(d) <= period / 2: res.append(d) if len(res) < 8: return None nb = max(8, int(period / 0.01)) hist = [0] * nb lo = -period / 2 for d in res: hist[min(nb - 1, int((d - lo) / 0.01))] += 1 best, bi = -1, 0 for i in range(nb): s = sum(hist[(i + j) % nb] for j in range(-2, 3)) if s > best: best, bi = s, i if best < 0.4 * len(res): return None # the centre of the crowd, not the first bin of a plateau: the mean of the offsets that sit around the best window c = lo + (bi + 0.5) * 0.01 near = [] for d in res: e = d - c e = (e + period / 2) % period - period / 2 # wrapped distance to the window centre if abs(e) <= 0.03: near.append(e) return c + (sum(near) / len(near) if near else 0.0) def check_grid(res, kicks): """Fill res['kick_check'] and, for a usable but misplaced grid, move it onto the kicks.""" beats = res.get("beats") or [] chk = {"kicks": len(kicks), "checked": False} res["kick_check"] = chk if len(beats) < 8 or len(kicks) < 8 or not res.get("tempo"): return res period = 60.0 / res["tempo"] share, med = kick_stats(beats, kicks) chk.update({"checked": True, "within40": round(share, 2), "median_ms": round(1000 * med), "shifted_ms": 0}) if share < 0.5: shift = kick_phase_shift(beats, kicks, period) if shift is not None and abs(shift) > 0.015: moved = [round(b + shift, 3) for b in beats] s2, m2 = kick_stats(moved, kicks) if s2 >= 0.6 and s2 >= share + 0.2: res["beats"] = moved res["downbeats"] = [round(b + shift, 3) for b in res.get("downbeats") or []] res["half_beats"] = [round(b + shift, 3) for b in res.get("half_beats") or []] chk.update({"shifted_ms": round(1000 * shift), "within40_before": round(share, 2), "within40": round(s2, 2), "median_ms": round(1000 * m2)}) share = s2 if share < 0.5 and res.get("usable"): # a grid that sits beside the kicks and cannot be moved onto them: snapping to it would put every big move # beside the beat the ear hears, so the safe answer is to not snap at all res["usable"] = False res["unusable_reason"] = "kick check" chk["rejected"] = True return res def say_check(res): """The line a person (or an agent) reads.""" c = res.get("kick_check") or {} if not c.get("checked"): return f"kick check: not enough beats or kicks ({c.get('kicks', 0)} kicks) to compare the grid with them" if c.get("shifted_ms"): return (f"kick check: the grid sat {c['shifted_ms']:+d} ms beside the kicks ({c['within40_before']:.0%} of the " f"beats on a kick): moved onto them, now {c['within40']:.0%} within 40 ms") if c["within40"] >= 0.7: return (f"kick check: {c['within40']:.0%} of the beats sit within 40 ms of a kick (< 125 Hz), median " f"{c['median_ms']:+d} ms: the grid is on the kick") if c["within40"] >= 0.5: return (f"kick check: {c['within40']:.0%} of the beats sit within 40 ms of a kick, median {c['median_ms']:+d} ms: " f"only loosely on the kick (syncopated kicks, or a mix with a lot on top); look at --plot before " f"you lean on it") why = "marked unusable, --snap-beats will not use it" if c.get("rejected") else "it was not usable anyway" return (f"WARN kick check: only {c['within40']:.0%} of the beats sit within 40 ms of a kick: the grid is not on the " f"kick ({why}); look at --plot (music with no kick drum gives no check: then judge by ear)") # ------------------------------------------------------------------ music offset for the cuts def music_offset(times, beats, period, tol=0.04): """How far to move the music (later: positive) so that the most of `times` land on a beat. Returns {"shift_s", "before", "after", "n"}; the move is a suggestion, the music is not touched.""" import bisect if len(times) < 3 or len(beats) < 4: return None srt = sorted(beats) def score(shift): """(share of the moves within tol of a beat, mean distance of the moves to their beat, capped at 100 ms)""" ok, dsum = 0, 0.0 for t in times: j = bisect.bisect_left(srt, t - shift) cands = [srt[x] for x in (j - 1, j) if 0 <= x < len(srt)] d = min(abs(c + shift - t) for c in cands) if cands else 0.1 ok += d <= tol dsum += min(d, 0.1) return ok / len(times), dsum / len(times) before = score(0.0)[0] # the most moves on a beat; among equals the one that puts them closest to it (the middle of a plateau), then the # smallest move of the music best_key, bs = None, 0.0 steps = int(period / 2 / 0.005) for k in range(-steps, steps + 1): s = k * 0.005 sh, dm = score(s) key = (round(sh, 6), -round(dm, 4), -abs(s)) if best_key is None or key > best_key: best_key, bs = key, s n = len(times) k = int(round(best_key[0] * n)) p0 = min(0.5, 2 * tol / period) # a move lands within tol of a beat by chance with this share tail = sum(math.comb(n, i) * p0 ** i * (1 - p0) ** (n - i) for i in range(k, n + 1)) # the best of ~period/(2 tol) independent shifts: it has to beat chance, or any music "fits" ten random moves significant = tail * max(1.0, period / (2 * tol)) < 0.01 return {"shift_s": round(bs, 3), "before": round(before, 2), "after": round(best_key[0], 2), "n": n, "chance": round(p0, 2), "significant": bool(significant)} def detect(path, max_seconds=900): x = decode(path, max_seconds) if len(x) < RATE * 4: return {"tempo": None, "confidence": 0.0, "beats": [], "downbeats": [], "fps": FPS} flux, low, kick = onset_strength(x) f_d, l_d, k_d = detrend(flux), detrend(low), detrend(kick) mf = (sum(f_d) / len(f_d)) or 1e-9 ml = (sum(l_d) / len(l_d)) or 1e-9 # kicks live in the low band and carry the pulse; hats/noise only add broadband flux: weight both o = [a / mf + 3.0 * b / ml for a, b in zip(f_d, l_d)] lag, r_best = tempo_from(o) if not lag: return {"tempo": None, "confidence": 0.0, "beats": [], "downbeats": [], "fps": FPS} beats, down = beat_grid(o, low, lag) mean_all = sum(o) / len(o) or 1e-9 on_beats = [o[max(0, min(len(o) - 1, int(round((b - LAT) * FPS))))] for b in beats] ratio = (sum(on_beats) / max(1, len(on_beats))) / mean_all # confidence = how periodic the onsets are (autocorrelation peak) and how much stronger the beats are than # the average moment; each half of the score alone is fooled by either steady hats or sparse accents periodic = max(0.0, min(1.0, (r_best - 0.05) / 0.30)) onbeat = max(0.0, min(1.0, (ratio - 1.0) / 1.2)) conf = 0.6 * periodic + 0.4 * onbeat # a 140 BPM song is often read as 70 (the strongest autocorrelation is two beats): the positions in between # are real beats when they carry as much onset energy as the beats do half = [] if len(beats) >= 8: def at(t): return o[max(0, min(len(o) - 1, int(round((t - LAT) * FPS))))] mids = [b + (lag / FPS) / 2 for b in beats] ms = sum(at(m) for m in mids) / len(mids) bs - skills/real-sfx/scripts/bed.py (18428 bytes)
#!/usr/bin/env python3 """A bed under a film whose sound is only SFX: one long, dark, steady REAL recording of the library, never synthesized. python bed.py work/cues.json --list # the candidates, with their tags: choose by numbers and tags python bed.py work/cues.json # choose the best, add the bed, write the sheet python bed.py work/cues.json --id 641 [--level -54 | --floor -24] # a sound you chose (ids with commas take turns) python bed.py work/cues.json --dry | --remove Why. The finished SFX reels never go quiet: their quietest tenth of the film sits about 24 dB under the loudest 250 ms (median of nine; the SFX-only renders of this skill: 33-87 dB under), and they have no digital silence (0-2 % of the time under -70 dBFS, one at 15 %; ours 4-67 %). Between the events the sound of such a film does not stop, a person hears a room, a wind, a hum, a pad. A film with silence between its sounds reads as bare ("пусто": the listener's word for the version without a bed). HOW LOUD is the person's answer, not the references': in three blind ladders of one bed at -56 / -50 / -44 / -36 dBFS (median 250 ms) the listener chose -56 every time, called -50 "всё хорошо" and -44 and louder "громко", while a bed 24 dB under the loudest 250 ms of a dense film (about -34 dBFS) had been "гул мешает" before. So the level is ABSOLUTE: `--level` (default -54 dBFS, the bed's own median 250 ms in the finished master). `--floor DB` is the old relative rule (that many dB under the loudest 250 ms) for a film that wants it. What it does and does not do * adds cues with `"bed": true` that cover the film (or --from/--to) with the chosen recording, in overlapping pieces when the recording is shorter than the film (equal-power cross-fades, no loop seam), around the sheet's `quiet` ranges; every other cue is left exactly as it was; running it again replaces the bed, --remove takes it out; * the LEVEL is not guessed here: `mix.py` renders the film without the bed, as the finished master will have it, and puts the bed's own median 250 ms level at `level_dbfs` (default -54; `bed:` line of the output), or with --floor that many dB under the loudest 250 ms, so it follows every later change of the sounds; * a dark, STEADY, long recording is chosen (centroid under 900 Hz, nothing that sounds like a person, an animal or a song: by name and by the model's tags; and one whose level does not throb: `ripple` of the 50 ms levels at most 4 dB, `swing` at most 12; --list shows the numbers); --list shows the others, --id or --query overrides. Why: the listener's own verdict on four films was "гул мешает" for a sub recording that moves 5-8 dB about twice a second; steady recordings measure 2-3 dB (`--scan` measures the whole library once, the picker reads it too); * a film that keeps its own music or voice is refused (--even-with-audio overrides): there the music is the bed; * the critique does not count a bed as an event (no gesture, no hook, no variety, no hierarchy); the table against the references shows its effect (`floor`, `digital silence`, `sub bed`). Listen to the film with and without it (--remove): the script cannot hear that a bed is not in the way. """ import argparse import json import math import re import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import STEADY_PATH, effective_dur, load_json, load_steady, norm_path, save_steady, steady_of # a bed must not be a THING: no person, animal, song, weather, fire, water, footsteps (by the model's tags and by name) AVOID = ("speech", "animal", "bird", "insect", "cricket", "crowd", "child", "music", "singing", "siren", "alarm", "laughter", "cough", "snoring", "cat", "dog", "fire", "storm", "thunder", "rain", "water", "ocean", "wave", "forest", "beach", "bubbl", "footstep", "walk", "crack", "explosion", "ringing") # whole words of a NAME or FOLDER that say it is a thing, not a floor (the model's tags on a low drone are unreliable: # a plain drone gets "whale vocalization", so these are not looked for in the tags) AVOID_WORDS = ("whale", "dolphin", "wolf", "howl", "voice", "vocal", "choir", "chant", "breath", "heartbeat", "baby", "applause", "traffic", "train", "engine", "motor", "plane", "helicopter", "street", "city", "market", "cafe", "restaurant", "kitchen", "machine") _WORDS = re.compile(r"\b(" + "|".join(AVOID_WORDS) + r")(s|es|ing)?\b") MAX_CENTROID = 900.0 MAX_RIPPLE = 4.0 # dB: a floor that moves faster than this is a throb, not a floor (see common.steadiness) MAX_SWING = 12.0 # dB: a fade, a gap or a rise inside the recording OK_RIPPLE = 2.5 # steady up to here costs nothing; above, the score pays 0.3 per dB def tags_of(rec): return [str(t).lower() for t in (rec.get("tags") or [])[:4]] def usable(rec, tone): names = [str(rec.get("name", "")).lower(), str(rec.get("folder", "")).lower()] if any(a in t for t in tags_of(rec) + names for a in AVOID) or any(_WORDS.search(n) for n in names): return False if tone == "dark" and rec.get("centroid", 1e9) > MAX_CENTROID: return False return rec.get("bumps", 0) <= 8 # a steady recording, not a rhythm or a flutter def candidates(index, film_len, tone="dark", query=None, steady=True): """[(score, record)] best first; each record carries `_steady` ({ripple, flutter, swing}) when it was measured. A recording that throbs (ripple > MAX_RIPPLE) or drifts (swing > MAX_SWING) is left out, `steady=False` keeps it.""" from picker import load_taste, rank spec = {"role": "ambience", "min_dur": min(8.0, max(3.0, film_len * 0.4))} if query: spec["query"] = query loved = set(load_taste().get("love", [])) # a bed the person said "всё хорошо" to needs no tag to pass out = [] for score, rec in rank(index, spec): if "centroid" not in rec or not (rec["path"] in loved or usable(rec, tone)): continue d = effective_dur(rec) chain = 0.0 if d >= film_len + 0.5 else 0.4 + 0.15 * math.ceil(film_len / max(1.0, d)) # darker and lower under the small sounds of the film (they live at 0.5-6 kHz: a rumble does not mask them), # steadier, without a chain of pieces s = (score + chain + 0.6 * max(0.0, math.log(max(rec["centroid"], 30.0) / 120.0)) + 0.08 * rec.get("bumps", 0) + 0.8 * (1.0 - min(1.0, rec.get("low", 0.0)))) out.append((round(s, 3), rec)) out.sort(key=lambda t: (t[0], t[1]["id"])) if not steady: return out cache = load_steady() before = len(cache) kept = [] for s, rec in out[:80]: # ~0.1 s each, once: the cache keeps the numbers st = steady_of(rec, cache) if st is None or st["ripple"] > MAX_RIPPLE or st["swing"] > MAX_SWING: continue rec = dict(rec, _steady=st) kept.append((round(s + 0.3 * max(0.0, st["ripple"] - OK_RIPPLE), 3), rec)) if len(cache) != before: try: save_steady(cache) except OSError: pass kept.sort(key=lambda t: (t[0], t[1]["id"])) return kept def pieces(a0, a1, plen, xf): """Cover [a0, a1] with pieces of length plen that overlap by at least xf; the last one ends at a1. [(start, length)]. One piece when the recording is long enough.""" span = a1 - a0 if plen >= span + 0.2: return [(a0, span + 0.2)] n = max(2, int(math.ceil((span - xf) / max(0.5, plen - xf)))) step = (span - plen) / (n - 1) return [(a0 + i * step, plen) for i in range(n)] def scan(): """Measure every ambience recording of the library once (the cache is what the picker reads) and say which throb.""" from picker import load_index cache = load_steady() rows = [] for rec in load_index(): if "ambience" not in (rec.get("roles") or []) and rec.get("role") != "ambience": continue if effective_dur(rec) < 3.0 or not Path(rec["path"]).exists(): continue st = steady_of(rec, cache) if st: rows.append((st["ripple"], st["flutter"], st["swing"], rec)) save_steady(cache) rows.sort(key=lambda r: (r[0], r[1])) throb = [r for r in rows if r[0] > MAX_RIPPLE] print(f"{len(rows)} ambience recordings measured -> {STEADY_PATH}") print(f"steady (ripple up to {OK_RIPPLE:g} dB): {sum(1 for r in rows if r[0] <= OK_RIPPLE)}; " f"throb (over {MAX_RIPPLE:g}): {len(throb)}") print("the steadiest:") for rp, fl, sw, r in rows[:8]: print(f" {r['id']:5d} ripple {rp:4.1f} flutter {fl:4.2f} swing {sw:5.1f} {r['name'][:46]} ({r.get('tier', 'main')})") mains = [r for r in throb if r[3].get("tier", "main") == "main"] print(f"the throbbing ones of the main pack ({len(mains)}):") for rp, fl, sw, r in sorted(mains, key=lambda r: -r[0])[:8]: print(f" {r['id']:5d} ripple {rp:4.1f} flutter {fl:4.2f} swing {sw:5.1f} {r['name'][:46]}") def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("sheet", nargs="?", help="the cue sheet (not needed for --scan)") ap.add_argument("--id", help="the sound(s) to use: an id, or ids with commas (they take turns)") ap.add_argument("--query", help="words of the name or folder (picker --query)") ap.add_argument("--level", type=float, default=-54.0, help="where the bed's own median 250 ms level sits in the finished master, dBFS (the listener " "chose -56, called -50 good and -44 and louder loud)") ap.add_argument("--floor", type=float, default=None, help="instead of --level: that many dB under the loudest 250 ms of the film (the references: -24)") ap.add_argument("--xfade", type=float, default=1.5, help="seconds of cross-fade between the pieces") ap.add_argument("--from", dest="t_from", type=float, help="start of the bed, seconds (default: the film's start)") ap.add_argument("--to", dest="t_to", type=float, help="end of the bed, seconds (default: the film's end)") ap.add_argument("--highpass", type=float, default=30.0, help="highpass Hz on every piece (0 = none)") ap.add_argument("--lowpass", type=float, default=0.0, help="lowpass Hz on every piece (0 = none)") ap.add_argument("--tone", choices=["dark", "any"], default="dark") ap.add_argument("--list", action="store_true", help="print the candidates and stop") ap.add_argument("--any-steadiness", action="store_true", help=f"keep recordings that throb (ripple over {MAX_RIPPLE:g} dB) or drift (swing over {MAX_SWING:g})") ap.add_argument("--scan", action="store_true", help="measure the steadiness of every ambience recording once (about 0.1 s each) and print the " "steadiest and the ones that throb; the picker reads the result (ambience_steady.json)") ap.add_argument("--dry", action="store_true") ap.add_argument("--remove", action="store_true") ap.add_argument("--even-with-audio", action="store_true") a = ap.parse_args() if a.scan: return scan() if not a.sheet: ap.error("the sheet is required (except for --scan)") sp = Path(a.sheet) if not sp.exists(): sys.exit(f"sheet not found: {sp}") sheet = load_json(sp) if isinstance(sheet, list): sheet = {"cues": sheet} cues = sheet.setdefault("cues", []) old = [c for c in cues if c.get("bed")] base = [c for c in cues if not c.get("bed")] if a.remove: sheet["cues"] = base sheet.pop("_bed", None) if not a.dry: sp.write_text(json.dumps(sheet, ensure_ascii=False, indent=1), encoding="utf-8") print(f"removed {len(old)} bed piece(s); {len(base)} cues remain" + (" (dry run)" if a.dry else "")) return video = sheet.get("video") if video: v_ = Path(norm_path(video)) video = str(v_ if v_.is_absolute() or v_.exists() else sp.parent / v_) dur = sheet.get("duration") if not dur and video and Path(video).exists(): from find_moments import probe dur = probe(video)["duration"] if not dur: dur = max([float(c["t"]) for c in base] + [0.0]) + 1.0 dur = float(dur) from texture import sfx_led led, why = sfx_led(sheet, video) if not led and not a.even_with_audio and not a.list: sys.exit(f"not added: {why}. A bed goes under a film whose sound is only SFX; over music or voice the music " f"is the bed. --even-with-audio adds it anyway.") from picker import load_index index = load_index() a0 = max(0.0, a.t_from or 0.0) a1 = min(dur, a.t_to if a.t_to else dur) if a1 - a0 < 2.0: sys.exit("the bed would be shorter than 2 s: check --from/--to") if a.id: want = [int(x) for x in a.id.replace(" ", "").split(",") if x] recs = [] for i in want: rec = next((s for s in index if s["id"] == i), None) if rec is None: sys.exit(f"no sound with id {i} in the index (ids change when the index is rebuilt)") recs.append(rec) else: cand = candidates(index, a1 - a0, a.tone, a.query, steady=not a.any_steadiness) if a.list: print(f"{'id':>5} {'score':>6} {'tier':5s} {'dur':>6} {'cent':>6} {'low':>5} {'ripple':>6} {'flut':>5} {'swing':>6} " f"name | tags") for sc, r in cand[:12]: st = r.get("_steady") or {} print(f"{r['id']:5d} {sc:6.2f} {r.get('tier', 'main'):5s} {effective_dur(r):6.1f} {r['centroid']:6.0f} " f"{r.get('low', 0):5.2f} {st.get('ripple', float('nan')):6.1f} {st.get('flutter', float('nan')):5.2f} " f"{st.get('swing', float('nan')):6.1f} {r['name'][:38]} | {', '.join(tags_of(r)[:3])}") if not cand: print("no steady dark recording of the library fits (--tone any, --any-steadiness, --query WORDS or " "--id N)") return if not cand: sys.exit("no steady dark recording of role ambience in the library fits: --tone any, --query WORDS, " "--id N (search.py --role ambience --paths shows what there is)") best = cand[0][1] recs = [best] if effective_dur(best) < (a1 - a0) + 0.5: # the film is longer than the recording: a chain of pieces, and three DIFFERENT recordings take turns, so # that no cycle of 13 seconds can be heard seen = {best.get("dup_key") or best["name"].replace("(alt)", "").strip()} for _, r in cand[1:]: key = r.get("dup_key") or r["name"].replace("(alt)", "").strip() if key in seen: - skills/real-sfx/scripts/build_index.py (12754 bytes)
#!/usr/bin/env python3 """Scan the sound libraries from config.json and write library_index.json. Skips preview PNGs, HTML ads, readmes, macOS '._' stubs and the "_Mister Horse Previews" folders. Every sound gets a primary role (whoosh, hit, riser, click ...), all matching roles, duration and levels, so the picker can search by role/duration instead of guessing from folder names. python build_index.py # all libraries in config.json python build_index.py --quick # skip level analysis (fast, but no peak/anchor data cached) python build_index.py --full # re-measure every file instead of reusing the old index Libraries in config.json: {"name": "montage", "path": "D:/Sounds_sorted", "tier": "main"} tier "main" (default) or "extra" (fallback: used only where the main libraries have nothing for a role) A library folder that carries catalog.json or catalog.csv (rows: type, file, source, hit, hits_in_source ...; the output of a sorter script) gives every sound its pack type and its source recording. The pack type decides the primary role (it was taken from the folder the sound came from), the words of the source path become search words (Russian ones too), and slices of one source recording count as one recording when variety is judged. """ import argparse import csv import json import os import re import sys from concurrent.futures import ThreadPoolExecutor from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import (SKIP_DIRS, SKILL_DIR, aliases_for, analyse_sound, fix_mojibake, index_path, is_sound_file, load_config, nfc, onsets, roles_for_catalog, tag_roles, words) # sounds that are meant to be ONE click/tick/pop: how many separate sounds are inside is worth knowing CLICKISH = {"click", "ui", "data", "glitch", "foley", "camera", "paper", "coin", "glass", "cartoon", "typing", "pop", "water"} NEW_COPY = re.compile(r"\.wav[ _]new$", re.I) FEATURE_KEYS = ("duration", "peak_db", "mean_db", "peak_time", "attack_ms", "decay_ms", "centroid", "rolloff", "low", "high", "flat", "bumps", "active_dur", "lr_corr", "onset_count", "mono_ref") def scan(lib, skip_dirs): root = Path(lib["path"]) if not root.is_dir(): print(f"WARN library '{lib['name']}' not found: {root}", file=sys.stderr) return [] out = [] for dirpath, dirnames, filenames in os.walk(root): dirnames[:] = [d for d in dirnames if d.lower() not in skip_dirs and d.lower() not in SKIP_DIRS] for fn in filenames: p = Path(dirpath) / fn if is_sound_file(p): out.append((lib, root, p)) return out # ------------------------------------------------------------------ catalogs of sorted packs def _catalog_key(rel): """The same key for a file on disk and for its row in the catalog: repaired name, composed form, forward slashes, lower case.""" return nfc(fix_mojibake(str(rel))).replace("\\", "/").lower() def _read_catalog(path): if path.suffix.lower() == ".json": rows = json.loads(path.read_text(encoding="utf-8-sig")) return rows.get("sounds", rows.get("rows", [])) if isinstance(rows, dict) else rows with open(path, encoding="utf-8-sig", newline="") as f: return list(csv.DictReader(f)) def load_catalog(root): """(folder the catalog sits in, {key: row}) for catalog.json / catalog.csv found in the library folder or one or two levels below it (an unzipped archive nests its folder twice). (None, {}) when there is none.""" root = Path(root) spots, seen = [root], {root} for _ in range(2): nxt = [] for d in spots: try: for c in sorted(d.iterdir()): if c.is_dir() and c.name.lower() not in SKIP_DIRS and c not in seen: nxt.append(c) seen.add(c) except OSError: pass spots = nxt[:40] for d in [root] + sorted(seen - {root}, key=lambda p: (len(p.parts), str(p))): for name in ("catalog.json", "catalog.csv"): f = d / name if f.is_file(): try: rows = _read_catalog(f) except (OSError, ValueError, csv.Error) as e: print(f"WARN cannot read catalog {f}: {e}", file=sys.stderr) continue table = {} for r in rows: if isinstance(r, dict) and r.get("file"): table[_catalog_key(r["file"])] = r if table: return d, table return None, {} def _num(v, default=0): try: return float(v) except (TypeError, ValueError): return default def pack_record(row, rel, root_rel): """Fields a catalog row adds: names from the source recording (not from the sorter's shortened file name).""" src = nfc(row.get("source", "")).replace("\\", "/") parent, _, leaf = src.rpartition("/") stem = re.sub(r"\.(wav|mp3|flac|aiff?|ogg|m4a|aac|opus)$", "", leaf, flags=re.I) or Path(rel).stem hit, hits = int(_num(row.get("hit"))), int(_num(row.get("hits_in_source"), 1)) name = stem.replace("_", " ").strip() if hits > 1: name += f" #{hit}" folder = " / ".join(x for x in (nfc(fix_mojibake(root_rel)), parent.replace("_", " ")) if x) return {"name": name, "folder": folder, "pack_type": str(row.get("type", "")).lower(), "type_by": str(row.get("by", "")), "source": src, "hit": hit, "hits_in_source": hits, "src_start_s": round(_num(row.get("src_start_s")), 3), "_text": f"{parent} {stem}"} def describe(item, quick, known=None, carry=None, catalogs=None): lib, root, p = item rel = p.relative_to(root) folder = nfc(fix_mojibake(str(rel.parent))) if str(rel.parent) != "." else "" name = nfc(fix_mojibake(p.stem.replace("_", " "))).strip() rec = { "library": lib["name"], "tier": lib.get("tier", "main"), "path": str(p), "folder": folder, "name": name, } cat_root, table = (catalogs or {}).get(lib["name"], (None, {})) row = None if cat_root is not None: try: row = table.get(_catalog_key(p.relative_to(cat_root))) except ValueError: row = None if row is not None: pk = pack_record(row, str(p.relative_to(cat_root)), str(p.relative_to(cat_root).parent)) text = pk.pop("_text") rec.update(pk) roles = roles_for_catalog(pk["pack_type"], text) or tag_roles(f"{pk['folder']} / {pk['name']}") else: roles = tag_roles(f"{folder} / {name}") rec["role"] = roles[0] if roles else "misc" rec["roles"] = roles old = (known or {}).get(str(p)) # a sound whose channels cancel was measured on a mono sum that is silence (before 0.11.1): measure it again stale_ = bool(old) and (old.get("lr_corr") or 0.0) < -0.3 and "mono_ref" not in old if old and "bumps" in old and "active_dur" in old and "lr_corr" in old and not stale_: # measured: keep, redo tags rec.update({k: old[k] for k in FEATURE_KEYS if k in old}) elif not quick: info = analyse_sound(p) if info is None: return None rec.update(info) keep_ = (carry or {}).get(str(p)) or old if keep_: # what the ears said about this file stays with it, even on --full for k in ("tags", "tag_scores", "tags_v"): if k in keep_: rec[k] = keep_[k] if rec.get("onset_count") is None and rec["role"] in CLICKISH and 0 < rec.get("duration", 99) <= 3.5 and not quick: rec["onset_count"] = len(onsets(p)[0]) rec["words"] = words(rec) al = aliases_for(f"{rec['folder']} {rec['name']}") if al: rec["aliases"] = al return rec def main(): ap = argparse.ArgumentParser() ap.add_argument("--quick", action="store_true") ap.add_argument("--out") ap.add_argument("--workers", type=int, default=8) ap.add_argument("--full", action="store_true", help="re-measure every file instead of reusing the old index") args = ap.parse_args() cfg = load_config() skip = {s.lower() for s in cfg.get("skip_dir_names", [])} items, catalogs, libs_meta = [], {}, [] for lib in cfg["libraries"]: if lib.get("enabled", True) is False: print(f"{lib['name']}: disabled in config.json, skipped") continue found = scan(lib, skip) cat_root, table = load_catalog(lib["path"]) if Path(lib["path"]).is_dir() else (None, {}) if cat_root is not None: catalogs[lib["name"]] = (cat_root, table) skip_packs = {str(x).lower() for x in lib.get("skip_packs") or []} if skip_packs and cat_root is None: print(f"WARN {lib['name']}: skip_packs needs a catalog with a 'pack' column and none was found: " f"nothing is skipped", file=sys.stderr) elif skip_packs: # a sorted folder that also holds copies of sounds another library indexes in place keep = [] for it in found: try: row = table.get(_catalog_key(it[2].relative_to(cat_root))) or {} except ValueError: row = {} if str(row.get("pack", "")).lower() not in skip_packs: keep.append(it) print(f"{lib['name']}: skip_packs {sorted(skip_packs)} leaves {len(keep)} of {len(found)} files") found = keep print(f"{lib['name']}: {len(found)} audio files, tier {lib.get('tier', 'main')}" + (f", catalog with {len(table)} rows ({cat_root})" if cat_root is not None else "")) libs_meta.append({"name": lib["name"], "path": lib["path"], "tier": lib.get("tier", "main"), "files": len(found), "catalog": cat_root is not None}) items += found out_p = Path(args.out) if args.out else index_path(cfg) known, carry = {}, {} if out_p.exists(): carry = {s["path"]: s for s in json.loads(out_p.read_text(encoding="utf-8"))["sounds"]} if not args.full: known = carry with ThreadPoolExecutor(args.workers) as ex: recs = [r for r in ex.map(lambda it: describe(it, args.quick, known, carry, catalogs), items) if r] # "X.wav new" files are re-exports of "X"; packs that ship a sound as both WAV and MP3 give the same name twice. # Drop the copy when identical (the lossless one stays), keep as "(alt)" when not. seen, kept = {}, [] lossy = {".mp3", ".m4a", ".aac", ".ogg", ".opus"} for r in sorted(recs, key=lambda r: (bool(NEW_COPY.search(r["name"])), Path(r["path"]).suffix.lower() in lossy)): clean = NEW_COPY.sub("", r["name"]).strip() key = (r["library"], r["folder"], clean.lower()) if key in seen: o = seen[key] if abs(o.get("duration", 0) - r.get("duration", 0)) < 0.02 and abs(o.get("peak_db", 0) - r.get("peak_db", 0)) < 0.5: continue clean += " (alt)" r["name"] = clean seen[key] = r kept.append(r) dropped = len(recs) - len(kept) recs = kept # near-identical recordings under different names (same length, level, brightness): mark them as one group # so the picker does not count a copy as a "different" sound groups = {} for r in recs: if r.get("duration", 0) >= 0.05 and "centroid" in r: key = f"{round(r['duration'], 2)}|{round(r['peak_db'] * 2) / 2}|{round(r['mean_db'] * 2) / 2}|{r['centroid'] // 20}" groups.setdefault(key, []).append(r) for key, members in groups.items(): if len(members) > 1: for r in members: r["dup_key"] = key for i, r in enumerate(recs): r["id"] = i out = out_p out.write_text(json.dumps({"count": len(recs), "libraries": libs_meta, "sounds": recs}, ensure_ascii=False, indent=1), encoding="utf-8") by_role, by_lib = {}, {} for r in recs: by_role[r["role"]] = by_role.get(r["role"], 0) + 1 by_lib[r["library"]] = by_lib.get(r["library"], 0) + 1 print(f"indexed {len(recs)} sounds ({dropped} duplicate re-exports dropped) -> {out}") print("by library:", ", ".join(f"{k}={v}" for k, v in by_lib.items())) print("by primary role:", ", ".join(f"{k}={v}" for k, v in sorted(by_role.items(), key=lambda kv: -kv[1]))) if __name__ == "__main__": main() - skills/real-sfx/scripts/common.py (54962 bytes)
"""Shared helpers: skill paths, config, role tagging, ffmpeg PCM decoding.""" import array import json import math import os import re import shutil import subprocess import sys import unicodedata from pathlib import Path if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8") sys.stderr.reconfigure(encoding="utf-8") SKILL_DIR = Path(__file__).resolve().parent.parent AUDIO_EXT = {".wav", ".mp3", ".flac", ".aif", ".aiff", ".ogg", ".m4a", ".aac", ".opus"} SKIP_DIRS = {"__macosx", ".git", "node_modules"} # archive leftovers, never sound libraries def is_sound_file(path): """An audio file that really is one: not a macOS AppleDouble stub ('._name.wav': a few hundred bytes of metadata that every unzip from a Mac leaves behind) and not inside an archive-leftover folder.""" p = Path(path) if p.suffix.lower() not in AUDIO_EXT or p.name.startswith("._"): return False return not any(part.lower() in SKIP_DIRS for part in p.parts) _MOJIBAKE = re.compile("[╒-╬▀-▓]") # box-drawing characters = UTF-8 bytes shown as CP437 def fix_mojibake(text): """'╨╝╨╡╨┤╨╗╨╡╨╜╨╜╨░╤Å' -> 'медленная'. A zip made on a Mac stores UTF-8 names without the flag and Windows unpacks them as CP437: the file on disk then has a garbled name, while a catalog written at the source has the right one. Returns the text unchanged when it does not look garbled or does not decode cleanly.""" s = str(text) if not _MOJIBAKE.search(s): return s try: return s.encode("cp437").decode("utf-8") except (UnicodeEncodeError, UnicodeDecodeError): return s def nfc(text): """Composed form. macOS writes 'й' as 'и' + a combining mark, which breaks every Russian word match.""" return unicodedata.normalize("NFC", str(text)) def show_name(path): """A file name for people to read: a garbled CP437 name repaired, composed form.""" return nfc(fix_mojibake(Path(str(path)).name)) _CH_CACHE = {} def channel_count(path): """Channels of the first audio stream of a file (ffprobe); 2 when it cannot be told.""" k = str(path) if k not in _CH_CACHE: try: r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "a:0", "-show_entries", "stream=channels", "-of", "csv=p=0", k], capture_output=True, text=True) _CH_CACHE[k] = int(r.stdout.strip().split(",")[0]) except Exception: _CH_CACHE[k] = 2 return _CH_CACHE[k] def stereo_fmt(path, rate=48000): """The head of a filter chain that makes `path` a stereo stream at `rate` WITHOUT changing its level. ffmpeg's own mono -> stereo (aformat, -ac 2) takes 3 dB off: a mono voice stem, a mono library sound and a mono synth stem were all 3 dB under what the plan, the gain fit and the subtraction assumed.""" pre = "pan=stereo|c0=c0|c1=c0," if channel_count(path) == 1 else "" return f"{pre}aformat=sample_rates={rate}:channel_layouts=stereo" def _decode_text(b): """UTF-8 with or without a BOM, or UTF-16 (what Windows PowerShell 5.1 writes with `>` and Out-File).""" if b.startswith(b"\xef\xbb\xbf"): return b[3:].decode("utf-8", errors="replace") if b[:2] in (b"\xff\xfe", b"\xfe\xff"): return b.decode("utf-16", errors="replace") return b.decode("utf-8", errors="replace") def read_text_any(path): """The text of a file whatever tool wrote it (a BOM in front of the JSON is a JSONDecodeError otherwise).""" return _decode_text(Path(path).read_bytes()) def read_stdin_text(): return _decode_text(sys.stdin.buffer.read()) def load_json(path): return json.loads(read_text_any(path)) def norm_path(p): """A Git-Bash / MSYS path ('/e/proj/a.wav') written by hand on Windows: Python there wants 'E:/proj/a.wav'.""" s = str(p) if os.name == "nt": m = re.match(r"^/([a-zA-Z])/(.*)$", s) if m and not Path(s).exists(): return f"{m.group(1).upper()}:/{m.group(2)}" return s # Ordered rules. A sound gets every role whose pattern matches "<folder path> / <file name>"; # the first match is its primary role. Folder names are EN and RU, so patterns cover both. ROLE_RULES = [ ("error", r"error|ошибк|alarm|тревог|warning|fail"), ("click", r"щелч|\bsnap\b"), # before whoosh: "Щелчок перехода кадров" is a click, not a swoosh ("glitch", r"glitch|глитч|помех|interference|static|vhs|distort"), ("sub_drop", r"sub ?drop|bass ?drop|басс|earthquake|low[- ]end|rumble|deep impact|abyss"), ("hit", r"\bhit\b|impact|punch|slam|braaam|stinger|удар|thud|boom|cinematic hits|transient|expld|explosion|\bcrack|shatter|drum end"), ("design", r"dsgn|b00m|brute force|scream|sustain"), ("riser", r"riser|\brise\b|rising|build ?up|swell|ascend|glide up|reverse"), ("whoosh", r"wh?oo?sh|swish|swoosh|\brush\b|transition|переход|flick|swipe|blitz|sweep|tear|slide|burst|wrap|\[t\]|3d box|bounce|zoom|shake|\bpan\b|perspective|stretch|\bsplit\b|blur|parallax|multiscreen|light leaks|warp"), ("cartoon", r"cartoon"), ("vehicle", r"transportation|\bcar\b|motorcycle|\bbike|airport|wiper|tyre|road|scooter"), ("camera", r"camera|shutter|flash|projector|проектор|плен|film"), ("click", r"click|клик|mouse|мыш|нажати|button|\btap\b|keyboard|клавиатур|клавиаутр|typing"), ("ui", r"\bui\b|interface|notification|уведомл|icon|иконк|\bbell|колокольч|chime|\bping|\bpop\b|bubble|пузыр|bleep|beep|success|\bding\b|incoming|message|\bsent\b|dialing|phone|ringing|time over|gear dial"), ("meme", r"laugh|giggl|bruh|\bsus\b|trap|gunshot|\bgun\b|\bwow\b|oh no|yeah|yea hoe|\bhey\b|\bkid|duck|censor|loser|chant|hood|drank|turnt|uhhh|\bcaw|vroom|\bdrill\b|satisfied|edit sound|shing|generic sound|tritone|certified"), ("data", r"\bdata\b|данн|digit|цифр|computer|compute|scan|hologram"), ("paper", r"paper|бумаг|\bpage|страниц|book|книг|письм|pencil|карандаш|tape|peel|seal"), ("glass", r"glass|стекл|crystal"), ("coin", r"coin|монет|деньги|касса|\bcash|money|кэш|кеш"), ("ambience", r"ambien|backgrou|nature|\bcity|crowd|street|traffic|\bwind|\brain|fire|crackl|campfire|space|texture|atmo|birds|waves|river|waterfall|beach|cricket|seagull|forest|shore|\blake\b|\bdog"), ("foley", r"foley|\bdoor|chair|drawer|creak|cooler|plastic|пластик|clock|часы|часов|курант|neon|неон|шипени|hiss|keys|footstep|splash|dragged|debris|metal|squeak|lighter|jump into|throwing stones|balloon|knock|typewriter|heartbeat"), ("scifi", r"sci-?fi|alien|hover|machine|\bship|engine|siren|galactic|futur"), # secondary roles: they never take the primary place from the rules above, they only make a sound findable # by what it is (a bubble pop is "ui" for the old rules and "pop" here) ("pop", r"\bpops?\b|plop|bubble|пузыр|\bпоп|клоп|блоп"), ("chime", r"chime|\bbells?\b|sparkle|twinkle|shimmer|\bding\b|harp|glock|music ?box|колокольч|куранты|дзынь|блест"), ("typing", r"typing|keyboard|keystroke|typewriter|клавиатур|клавиаутр|печат|клавиш|клавы|клаве"), ("water", r"water|splash|drip|droplet|\bpour|faucet|вода|воды|капл|всплеск"), ] _COMPILED = [(role, re.compile(rx, re.I)) for role, rx in ROLE_RULES] # Peak level each role is normalised to before the per-cue gain_db offset (dBFS). ROLE_TARGET_PEAK_DB = { "hit": -4, "sub_drop": -4, "whoosh": -9, "riser": -12, "glitch": -12, "error": -10, "click": -14, "ui": -14, "data": -14, "camera": -10, "paper": -12, "glass": -10, "coin": -12, "ambience": -24, "foley": -12, "scifi": -12, "cartoon": -12, "vehicle": -18, "design": -6, "meme": -8, "pop": -14, "chime": -13, "typing": -14, "water": -14, "atmosphere": -24, "granular": -12, "music_transition": -12, "default": -10, } # Where in the sound the moment of the video should land. ROLE_ANCHOR = {"click": "start", "ui": "start", "ambience": "start", "vehicle": "start", "pop": "start", "typing": "start", "water": "start"} # everything else: loudest point on the moment; # riser stays on "peak" too, because many risers decay or ring out long before the end of the file # A sorted pack (catalog.json / catalog.csv at its root) already says what each sound is: its type was taken from the # folder it came from. That is more reliable than a pattern over a file name, so it decides the primary role. PACK_TYPE_ROLES = { "whoosh": ["whoosh"], "impact": ["hit"], "riser": ["riser"], "pop": ["pop", "ui"], "chime": ["chime", "ui"], "ui": ["ui"], "click": ["click"], "typing": ["typing"], "error": ["error"], "camera": ["camera"], "paper": ["paper"], "glass": ["glass"], "cartoon": ["cartoon"], "foley": ["foley"], "water": ["water"], "ambience": ["ambience"], "nature": ["foley"], "glitch": ["glitch"], "other": [], # types the sorted library Sounds_by_tag has and the first pack did not: each is a role of its own, found by # --role NAME and never picked for a cue that asks for another role (granular textures are not whooshes) "atmosphere": ["atmosphere"], "granular": ["granular"], "music_transition": ["music_transition"], "power": ["power"], "scifi": ["scifi"], "voice": ["voice"], } # The sorter's coarse type is wrong for some sources (a white-noise loop filed under "impact", broom sweeps under # "nature"). The words of the source path decide first: (pattern, roles that replace the pack type's roles, the pack # types this correction is allowed to touch). A whoosh keeps its role even when its name says "fire". SOURCE_ROLE_OVERRIDES = [ (r"static|white noise|tv tuning|ear ringing|creepy|помех|глитч|glitch", ["glitch", "ambience"], ("impact", "nature", "other", "foley", "ambience")), (r"water ?drop|faucet|dripping|капл|\bвода\b", ["water"], ("impact", "nature", "other", "foley", "water")), # a body falling is foley that can serve as a dark hit (not first in line when a hit is asked for) (r"body ?fall|thud|падение тела|lego|лего", ["foley", "hit"], ("impact", "nature", "other", "foley")), (r"sword ?hit", ["hit", "foley"], ("impact", "nature", "other", "foley")), (r"\bfire\b|огонь|acid|bubbling|crackl|ambien|эмбиент|forest|\bwind\b|ветер\b", ["ambience"], ("nature", "other", "impact")), (r"drum ?fill|барик", ["hit"], ("pop", "other", "impact")), (r"digital|диджитал|data ?processing|sci ?fi", ["ui", "data"], ("ui", "other")), ] _OVERRIDES = [(re.compile(rx, re.I), roles, set(types)) for rx, roles, types in SOURCE_ROLE_OVERRIDES] _SECONDARY = ("pop", "chime", "typing", "water", "glass", "coin") def roles_for_catalog(pack_type, text): """Roles of a sound that comes with a catalog: the pack type, corrected by the words of its source path where the type is a known misfit. The first role is the primary one.""" ptype = str(pack_type).lower() base = list(PACK_TYPE_ROLES.get(ptype, [])) low = nfc(text).lower().replace("_", " ") for rx, roles, types in _OVERRIDES: if ptype in types and rx.search(low): base = roles + [r for r in base if r not in roles] break if not base or ptype in ("other", "ui", "click", "pop", "chime", "typing"): base += [r for r in tag_roles(low) if r in _SECONDARY and r not in base] return base def config_path(): """REAL_SFX_CONFIG lets tests and other setups point at their own config without touching the skill.""" env = os.environ.get("REAL_SFX_CONFIG") return Path(env) if env else SKILL_DIR / "config.json" def load_config(): p = config_path() if not p.exists(): sys.exit(f"config not found: {p} (run: python scripts/setup.py --help)") return json.loads(read_text_any(p)) def index_path(cfg=None): env = os.environ.get("REAL_SFX_INDEX") if env: return Path(env) cfg = cfg or load_config() p = Path(cfg.get("index_path", "library_index.json")) return p if p.is_absolute() else SKILL_DIR / p def require_tools(*names): """Stop early with a clear message instead of a cryptic failure in the middle of a run.""" names = names or ("ffmpeg", "ffprobe") missing = [n for n in names if shutil.which(n) is None] if missing: sys.exit("missing tools in PATH: " + ", ".join(missing) + ". Install FFmpeg (https://ffmpeg.org/download.html) and reopen the terminal.") def venv_python(): """The Python of the skill's own venv (numpy, onnxruntime: `listen.py install`), or None. REAL_SFX_VENV_PYTHON names one explicitly (a working copy has no venv of its own).""" env = os.environ.get("REAL_SFX_VENV_PYTHON") if env and Path(env).exists(): return Path(env) p = SKILL_DIR / "vendor" / "venv" / ("Scripts/python.exe" if os.name == "nt" else "bin/python") return p if p.exists() else None def events_track(sheet, track): """The track the SOUNDS of a film are judged on. A film with a bed (bed.py) has a second track without it, which mix.py writes and names in the resolved cues: a bed fills every window of the full track, so the onset of a sound is not clear in it, and a sound the render lost would not be missed.""" p = ((sheet or {}).get("bed") or {}).get("track_nobed") if isinstance(sheet, dict) else None if p and Path(str(p)).exists(): return str(p) return track def measure_loudness(path): """Integrated loudness (LUFS), loudness range (LU) and true peak (dBFS) of an audio file via ebur128.""" r = subprocess.run(["ffmpeg", "-hide_banner", "-nostats", "-nostdin", "-i", str(path), "-vn", "-af", "ebur128=peak=true", "-f", "null", "-"], capture_output=True, text=True, errors="replace") tail = r.stderr.split("Summary:")[-1] def grab(label): m = re.search(label + r":\s+(-?[\d.]+|-inf)", tail) if not m or m.group(1) == "-inf": return None return float(m.group(1)) return {"lufs": grab("I"), "lra": grab("LRA"), "true_peak": grab("Peak")} # Russian words of folder and file names -> English search words (the libraries of this skill's users mix both) RU_EN = { "переход": "transition", "перехода": "transition", "переходов": "transition", "помеха": "interference glitch static", "глитч": "glitch", "эффект": "effect", "эффектом": "effect", "нажатие": "press click tap", "мышкой": "mouse", "мышка": "mouse", "техно": "techno", "ошибка": "error", "техническая": "technical", "длительный": "long", "быстрый": "fast quick", "быстро": "fast quick", "компьютерные": "computer", "данные": "data", "басс": "bass", "иконку": "icon", "бумага": "paper", "бумаги": "paper", "бумаге": "paper", - skills/real-sfx/scripts/contact_sheet.py (6911 bytes)
#!/usr/bin/env python3 """Draw candidate sounds side by side (waveform + spectrogram) so they can be compared by eye. python contact_sheet.py 239 254 249 --out work/candidates.png python contact_sheet.py --role whoosh --target-dur 0.7 --limit 8 --out work/whooshes.png [--like 412] python search.py --role hit --punchy --limit 8 --sheet work/hits.png # same, from the search What to read in a picture (this is how a sound is "heard" without ears): * waveform: a hit is a tall spike and a quick fall; a whoosh swells and fades; a riser grows to the end; a flat block is a bed or noise. Where the tallest point sits is where the moment will land. * spectrogram (time to the right, low pitch at the bottom, brightness = energy): - bright blob at the bottom = sub/boom, weight - bright band at the top = air, sizzle, hiss - diagonal streak rising = riser / pitch sweep - vertical bars = clicks, ticks, glitches - horizontal lines = tone, bell, hum - smeared noise = whoosh, wind, texture * the label gives id, role, length, library and name; loud sounds are not drawn louder, all are normalised. """ import argparse import subprocess import sys import tempfile from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import effective_dur, require_tools from picker import find, load_index, load_taste, rank W, H_WAVE, H_SPEC, H_BAR = 460, 60, 110, 22 H = H_BAR + H_WAVE + H_SPEC def find_font(): for p in ("C:/Windows/Fonts/arial.ttf", "C:/Windows/Fonts/segoeui.ttf", "C:/Windows/Fonts/calibri.ttf", "/System/Library/Fonts/Supplemental/Arial.ttf", "/Library/Fonts/Arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/dejavu/DejaVuSans.ttf"): if Path(p).exists(): return p return None def esc(path): """Escape a path for use inside an ffmpeg filter argument.""" return str(path).replace("\\", "/").replace(":", "\\:").replace("'", "\\'") def one_row(src, label, out_png, font, tmp, peak_db=None): lab = Path(tmp) / (out_png.stem + ".txt") lab.write_text(label, encoding="utf-8") bar = f"color=c=0x1b1f24:s={W}x{H_BAR}:d=1" if font: bar += f",drawtext=fontfile='{esc(font)}':textfile='{esc(lab)}':expansion=none:fontcolor=white:fontsize=13:x=6:y=4" # every sound is drawn at the same peak level, otherwise a quiet recording looks like silence norm = f",volume={max(-6.0, min(40.0, -1.0 - peak_db)):.1f}dB" if peak_db is not None else "" graph = (f"[0:a]aformat=channel_layouts=mono{norm},asplit=2[a][b];" # showwavespic is a gray image whatever 'colors' says: go to rgb first, then tint it green f"[a]showwavespic=s={W}x{H_WAVE}:colors=white,format=rgb24,colorchannelmixer=rr=0.29:gg=0.87:bb=0.5[w];" f"[b]showspectrumpic=s={W}x{H_SPEC}:legend=0:fscale=log:scale=log:color=magma,format=rgb24[s];" f"{bar},format=rgb24[bar];[bar][w][s]vstack=inputs=3[row]") gs = Path(tmp) / (out_png.stem + "_g.txt") gs.write_text(graph, encoding="utf-8") cmd = ["ffmpeg", "-v", "error", "-y", "-nostdin", "-t", "8", "-i", str(src)] for flag in ("-/filter_complex", "-filter_complex_script"): r = subprocess.run(cmd + [flag, str(gs), "-map", "[row]", "-frames:v", "1", str(out_png)], capture_output=True, text=True, errors="replace") if r.returncode == 0: return True return False def render_sheet(records, out, cols=2, taste=None): require_tools() out = Path(out).resolve() out.parent.mkdir(parents=True, exist_ok=True) font = find_font() taste = taste or load_taste() loved = set(taste.get("love", [])) rows = [] with tempfile.TemporaryDirectory() as tmp: for s in records: png = Path(tmp) / f"r{s['id']}.png" ad = effective_dur(s) dur_ = f"{ad:.2f}s" + ("*" if ad < s["duration"] - 0.15 else "") # '*': the file is longer head = f"#{s['id']}{' +' if s['path'] in loved else ''} {s['role']} {dur_} {s['library']}: " lab = head + s["name"][-max(12, 64 - len(head)):] if one_row(s["path"], lab, png, font, tmp, s.get("peak_db")): rows.append(png) if not rows: sys.exit("could not draw any of the sounds") n = len(rows) cols = max(1, min(cols, n)) lay = "|".join(f"{(i % cols) * W}_{(i // cols) * H}" for i in range(n)) cmd = ["ffmpeg", "-v", "error", "-y", "-nostdin"] for p in rows: cmd += ["-i", str(p)] if n == 1: cmd += ["-c:v", "png", str(out)] else: cmd += ["-filter_complex", "".join(f"[{i}:v]" for i in range(n)) + f"xstack=inputs={n}:layout={lay}:fill=0x101418[o]", "-map", "[o]", "-frames:v", "1", str(out)] r = subprocess.run(cmd, capture_output=True, text=True, errors="replace") if r.returncode: sys.exit("ffmpeg failed:\n" + r.stderr[-1200:]) return out def main(): ap = argparse.ArgumentParser() ap.add_argument("ids", nargs="*", help="sound ids from search.py (or path fragments)") ap.add_argument("--out", required=True) ap.add_argument("--cols", type=int, default=2) ap.add_argument("--role") ap.add_argument("--library") ap.add_argument("--min-dur", type=float, default=0) ap.add_argument("--max-dur", type=float, default=1e9) ap.add_argument("--target-dur", type=float) ap.add_argument("--like") ap.add_argument("--bright", action="store_true") ap.add_argument("--dark", action="store_true") ap.add_argument("--punchy", action="store_true") ap.add_argument("--query") ap.add_argument("--limit", type=int, default=8) a = ap.parse_args() index = load_index() if a.ids: recs = [find(index, i) for i in a.ids] recs = [r for r in recs if r] else: spec = {"role": a.role, "library": a.library, "min_dur": a.min_dur, "max_dur": a.max_dur, "target_dur": a.target_dur, "bright": a.bright, "dark": a.dark, "punchy": a.punchy, "query": a.query} if a.like is not None: ref = find(index, a.like) if ref: spec["like"] = ref["id"] recs = [s for _, s in rank(index, spec)[: a.limit]] if not recs: sys.exit("no sounds to draw") out = render_sheet(recs, a.out, a.cols) print(f"{len(recs)} sounds -> {out}") for i, r in enumerate(recs): print(f" [{i // a.cols + 1},{i % a.cols + 1}] #{r['id']} {r['role']} {r['duration']:.2f}s {r['name']}") if __name__ == "__main__": main() - skills/real-sfx/scripts/critique.py (64023 bytes)
#!/usr/bin/env python3 """Scoreboard for a finished sound design: objective axes 1..10, three worst problems with timecodes. python critique.py result/film_sfx_resolved_cues.json result/film_sfx_sfx_track.wav [--moments work/moments/moments.json] [--rounds 1] [--out result/critique.md] The same discipline as the video self-critique loop: look at the numbers AND at review.png, list the three worst problems with timecodes, fix only those, re-render only what changed, repeat until every axis is >= 8. This script covers the axes that can be measured. Three axes need your eyes on review.png and are listed at the end: character fit (does each sound suit its picture), cleanliness (masking, mud in the low end under music or voice) and taste (does it feel designed or sprayed on). """ import argparse import json import math import statistics import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import ROLE_TARGET_PEAK_DB, events_track, gesture_times, load_json, measure_loudness from verify import offsets PASS = 8.0 def clamp(v, lo=1.0, hi=10.0): return max(lo, min(hi, v)) def lead_level(video, seconds=2.0): """Mean level (dB) of the first seconds of the original audio, or None when there is none.""" import re import subprocess if not video or not Path(video).exists(): return None r = subprocess.run(["ffmpeg", "-hide_banner", "-nostdin", "-t", f"{seconds}", "-i", str(video), "-vn", "-af", "volumedetect", "-f", "null", "-"], capture_output=True, text=True, errors="replace") m = re.search(r"mean_volume:\s*(-?[\d.]+) dB", r.stderr) return float(m.group(1)) if m else None def is_key_cue(c): """A keystroke: a cue of the keyboard (labelled key..., a piece of a typing recording, or role typing).""" return str(c.get("label", "")).lower().startswith("key") or "typing" in str(c.get("file", "")).lower() \ or c.get("role") == "typing" def collapse_runs(cues, gap=0.25, key_gap=0.7): """A run of the same kind of sound closer than `gap` (typing, a row of ticks) is one event for pacing. The keystrokes of a person typing live (2-4 a second, gaps of 0.3-0.6 s) are one run at `key_gap`.""" ev, last = [], None is_key = is_key_cue def tail(c): # a long layer (a scroll wheel, a bed) fills the film until it ends sg = c.get("seg") or 0.0 return min(6.0, sg) if sg >= 1.0 else 0.0 cs = sorted(cues, key=lambda c: c["t"]) for i, c in enumerate(cs): g_ = key_gap if (last is not None and is_key(c) and is_key(last)) else gap # a cue that HEADS a run of its own kind (the first key of a row of typing) is not a layer of the sound a few # ms before it: merged there, the whole row would be counted as that sound's, and every pair of keys # would be called a smear nxt = cs[i + 1] if i + 1 < len(cs) else None heads_run = nxt is not None and nxt["role"] == c["role"] and \ nxt["t"] - c["t"] <= (key_gap if (is_key(c) and is_key(nxt)) else gap) if last is not None and c["role"] == last["role"] and c["t"] - last["t"] <= g_ and ev[-1]["role"] == c["role"]: ev[-1]["n"] += 1 ev[-1]["end"] = max(ev[-1]["end"], c["t"] + tail(c)) elif last is not None and c["t"] - last["t"] <= 0.08 and not heads_run: # the layers of ONE moment (a hit, its pop and a puff of dust): the ear counts one event ev[-1]["end"] = max(ev[-1]["end"], c["t"] + tail(c)) ev[-1]["layers"] = ev[-1].get("layers", 1) + 1 else: # a texture sound (texture.py: a small drop on a small move) is light, like a tick, for the pace ev.append({"t": c["t"], "end": c["t"] + tail(c), "n": 1, "role": c["role"], "short": c.get("seg", 1.0) < 0.15, "texture": bool(c.get("texture"))}) last = c return ev def fmt(t): return f"{int(t // 60)}:{t % 60:05.2f}" if t >= 60 else f"{t:.2f}s" def typed_row(r): return r.get("role") == "typing" or str(r.get("label", "")).lower().startswith("key") def rows_as_events(rs, run_gap=0.7): """Verify rows as the ear counts them: a row of keystrokes (`run_gap` s apart at most) is ONE thing to judge, not 185. (The sync axis stays n/a when too few of the rows could be measured; 185 keys must not hide 126 sounds.)""" keys = sorted(r["t"] for r in rs if typed_row(r)) runs_ = sum(1 for i, t_ in enumerate(keys) if i == 0 or t_ - keys[i - 1] > run_gap) return sum(1 for r in rs if not typed_row(r)) + runs_ def listen_list(cues, sync_rows=(), match_rows=(), speech_groups=(), mono_bad=(), n=5, apart=1.5, first=None, masked=()): """The moments where the numbers are least certain: [(score, t, label, why, ask)], at most n, `apart` seconds apart, in time order. A script cannot hear. This is what a person listens to on headphones and then once on a phone speaker, built from the measurements of this very render (not a fixed set of timestamps). Different KINDS of risk come first (the worst of each kind), then the worst ones again; two reasons at one moment share one entry.""" cand = [] def add(cat, score, t, label, why, ask): cand.append({"cat": cat, "score": float(score), "t": float(t), "label": str(label or ""), "why": why, "ask": ask}) ordered = sorted(cues, key=lambda c: c["t"]) if not ordered: return [] c0 = first or ordered[0] # `first`: the earliest AUDIBLE sound, a layer that leads its parent included add("hook", 5.0, c0["t"], c0.get("label"), "the first sound of the film: the hook", "does it land with the picture at once, and is it clearly there under the music or the voice?") peaked = [c for c in ordered if c.get("peak_after_db") is not None] if peaked: top = max(peaked, key=lambda c: c["peak_after_db"]) add("loud", 4.5, top["t"], top.get("label"), f"the highest peak of the film ({top['peak_after_db']:+.0f} dBFS " f"before the master)", "is it big without hurting on headphones, and does the music under it pump?") for r in sync_rows: if r.get("judged") and not r.get("ok") and r.get("off_ms") is not None: add("sync", 8.0 + min(2.0, abs(r["off_ms"]) / 100.0), r["t"], r.get("label"), f"its {'arrival' if r.get('note') == 'arrival' else 'peak'} sits {r['off_ms']:+d} ms from the moment", "does it feel early or late against the picture?") for r in match_rows: if abs(r["e"]) > 6.0: add("match", 6.0 + min(3.0, abs(r["e"]) / 4.0), r["t0"], r.get("kind"), f"{abs(r['e']):.0f} dB {'quieter' if r['e'] > 0 else 'louder'} than the author's own sound it replaces", "is it still the right size for what happens on the picture?") for gr in speech_groups: m = max(gr, key=lambda m_: m_["over_db"]) add("speech", 6.0 + min(3.0, m["over_db"] / 3.0), gr[0]["t"], m.get("label"), f"{len(gr)} sound(s) on top of the voice, {m['over_db']:+.1f} dB against it", "is every word still understood?") for c, loss, _lvl in mono_bad: add("mono", 7.0 + min(2.0, (loss - 6.0) / 3.0), c["t"], c.get("label"), f"loses {loss:.0f} dB when folded to mono", "play it from one speaker: is it still there?") for r in masked: # the masking model (maskmodel.py): a sound under the threshold of the rest by = r.get("by") or "the rest of the mix" extra = (f"; {r['margin_wo_bed_db']:+.0f} dB without it" if by == "bed" and r.get("margin_wo_bed_db") is not None else "") add("masked", 6.5 + min(2.5, abs(min(0.0, r["margin_db"])) / 6.0), r["t"], r.get("label"), f"the masking model puts it {abs(r['margin_db']):.0f} dB under the threshold set by {by}{extra}", "can you hear it at all?") tonal = [c for c in ordered if c.get("tonal") and c.get("pitch")] if tonal: c = max(tonal, key=lambda c_: abs(c_.get("pitch") or 0)) add("tonal", 5.0, c["t"], c.get("label"), f"retuned {c['pitch']:+g} st to the note {c['tonal']} of the score " f"under it", "does it sit in the key of the music, or does it clash?") adj = [c for c in ordered if abs(c.get("level_adj_db") or 0) >= 4.0] if adj: c = max(adj, key=lambda c_: abs(c_["level_adj_db"])) up_ = c["level_adj_db"] > 0 add("level", 4.0 + min(2.0, abs(c["level_adj_db"]) / 4.0), c["t"], c.get("label"), f"brought {abs(c['level_adj_db']):.0f} dB {'up' if up_ else 'down'} to the perceived level of its role", "a thin recording lifted that far can turn harsh: is it clean?" if up_ else "a sound brought down that far can get lost: does it still carry its moment?") lifted = [c for c in ordered if (c.get("gain_applied_db") or 0) >= 14.0 and c.get("role") not in ("click", "typing")] if lifted: c = max(lifted, key=lambda c_: c_["gain_applied_db"]) add("lift", 4.0 + min(2.0, (c["gain_applied_db"] - 14.0) / 4.0), c["t"], c.get("label"), f"a quiet recording lifted by {c['gain_applied_db']:.0f} dB", "does its noise floor come up with it (hiss)?") held = [c for c in ordered if (c.get("capped_db") or 0) >= 3.0] if held: c = max(held, key=lambda c_: c_["capped_db"]) add("held", 4.0, c["t"], c.get("label"), f"sits {c['capped_db']:.0f} dB under its plan (a very quiet recording " f"lifted to the +18 dB cap)", "is it big enough for its picture?") moved = [c for c in ordered if abs(c.get("onset_shift_ms") or 0) >= 60] if moved: c = max(moved, key=lambda c_: abs(c_["onset_shift_ms"])) add("shift", 4.5, c["t"], c.get("label"), f"its attack was moved {abs(c['onset_shift_ms']):.0f} ms so that it " f"lands on the moment", "does the lead-in still read as part of the sound?") pitched = [c for c in ordered if abs(c.get("pitch") or 0) >= 4 and not c.get("tonal")] if pitched: c = max(pitched, key=lambda c_: abs(c_["pitch"])) add("pitch", 3.5, c["t"], c.get("label"), f"pitched {c['pitch']:+g} st (its character changes)", "is it still the same kind of sound?") snapped = [c for c in ordered if abs(c.get("snapped_ms") or 0) >= 30] if snapped: c = max(snapped, key=lambda c_: abs(c_["snapped_ms"])) add("snap", 3.0, c["t"], c.get("label"), f"moved {abs(c['snapped_ms']):.0f} ms to the beat", "does it feel on the beat, or pulled off the picture?") # fillers: where it is busiest, and the quietest sound that is not a tick ts = [c["t"] for c in ordered] best_n, best_i = 0, 0 for i, t in enumerate(ts): k = sum(1 for u in ts if t <= u < t + 2.0) if k > best_n: best_n, best_i = k, i if best_n >= 4: add("busy", 2.5, ts[best_i] + 0.5, "", f"the busiest two seconds ({best_n} sounds)", "is every sound still distinct, or does it turn to mud?") quiet = [c for c in ordered if c.get("role") not in ("click", "ui", "data", "typing", "ambience", "vehicle") and c.get("loud_after_db") is not None] if quiet: c = min(quiet, key=lambda c_: c_["loud_after_db"]) add("quiet", 2.0, c["t"], c.get("label"), "the quietest by perceived loudness among the sounds that are not " "ticks", "can it be heard at all?") cand.sort(key=lambda x: -x["score"]) chosen = [] # {"t", "label", "score", "why": [...], "ask": [...], "cats": {...}} placed = set() def place(item): for ch in chosen: if abs(ch["t"] - item["t"]) < apart: # the same moment: one entry, both reasons if item["cat"] not in ch["cats"] and len(ch["why"]) < 2: # the second reason may belong to ANOTHER sound a second away: it says which, and when same = item["label"] == ch["label"] and abs(item["t"] - ch["t"]) < 0.05 ch["why"].append(item["why"] if same else f"also '{item['label'][:24]}' at {fmt(item['t'])}: {item['why']}") ch["ask"].append(item["ask"]) ch["cats"].add(item["cat"]) return True if len(chosen) >= n: return False chosen.append({"t": item["t"], "label": item["label"], "score": item["score"], "why": [item["why"]], "ask": [item["ask"]], "cats": {item["cat"]}}) return True seen = set() for item in cand: # the worst of every kind first if item["cat"] in seen: continue seen.add(item["cat"]) if place(item): placed.add(id(item)) per = {} for ch in chosen: for ccat in ch["cats"]: per[ccat] = per.get(ccat, 0) + 1 for item in cand: # then more of the worst kinds (at most 3 of a kind that is certain) if id(item) in placed: continue cap = 3 if item["cat"] in ("sync", "mono", "speech") else 2 if per.get(item["cat"], 0) >= cap: continue if place(item): per[item["cat"]] = per.get(item["cat"], 0) + 1 out = [] for ch in sorted(chosen, key=lambda x: x["t"]): out.append((ch["score"], ch["t"], ch["label"], "; ".join(ch["why"]), " / ".join(ch["ask"]))) return out def cut_listen(src, items, out, pre=1.0, post=2.0, dur=None): """The listen-list moments, one after the other (3 s each and a pause) in one wav of the film's own sound.""" import subprocess parts, labels = [], [] for i, it in enumerate(items): s = max(0.0, it[1] - pre) if dur: s = max(0.0, min(s, dur - (pre + post))) # a moment near the end: the window slides back parts.append(f"[0:a]atrim=start={s:.3f}:end={s + pre + post:.3f},asetpts=PTS-STARTPTS,apad=pad_dur=0.4[a{i}]") labels.append(f"[a{i}]") fc = ";".join(parts) + ";" + "".join(labels) + f"concat=n={len(items)}:v=0:a=1[o]" r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-nostdin", "-i", str(src), "-filter_complex", fc, "-map", "[o]", "-c:a", "pcm_s16le", str(out)], capture_output=True, text=True, errors="replace") return r.returncode == 0 def style_block(name, sheet, track, final_lufs, keep): """This film's SFX layer set against a reference style: (rows, text lines). Numbers, no scores, no verdict.""" try: import refstyle ex - skills/real-sfx/scripts/find_moments.py (17449 bytes)
#!/usr/bin/env python3 """Frame-by-frame analysis of a video: find the moments that deserve a sound. Outputs <out>/moments.json and one JPG per moment in <out>/frames/ so they can be looked at. Moment kinds: cut hard scene change or full-frame swap -> whoosh / transition / hit burst sharp spike of motion above the local level -> hit, whoosh, pop onset picture was still, then something starts -> ui, click, pop-in, riser end settle motion ended and the picture came to rest -> landing hit, click, soft thud Only needs ffmpeg/ffprobe. Everything is measured at a reduced size and 15 fps, so it is fast. python find_moments.py video.mp4 --out work/moments [--max 40] [--fps 15] [--fine] --fine is for soft, coloured animations (gradients, glows, pastel shapes that change hue): the default reads the brightness only and sees 5-6 moves of the 40 a person finds there. It also reads the chroma change; moments it adds carry src=chroma|luma. It is a candidate list: the frames (look.py --at T --span S) still decide. """ import argparse import json import re import statistics import subprocess import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import run def probe(video): p = run(["ffprobe", "-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height,r_frame_rate", "-of", "json", str(video)]) j = json.loads(p.stdout) v = next((s for s in j["streams"] if s["codec_type"] == "video"), {}) num, _, den = v.get("r_frame_rate", "30/1").partition("/") return { "duration": float(j["format"]["duration"]), "width": v.get("width"), "height": v.get("height"), "fps": round(float(num) / float(den or 1), 3), "has_audio": any(s["codec_type"] == "audio" for s in j["streams"]), } def audio_level(video): p = run(["ffmpeg", "-hide_banner", "-nostats", "-i", str(video), "-vn", "-af", "volumedetect", "-f", "null", "-"]) m = re.search(r"mean_volume:\s*(-?[\d.]+) dB", p.stderr) return float(m.group(1)) if m else None def _span_args(t0, t1): out = [] if t0: out += ["-ss", f"{t0:.3f}"] if t1: out += ["-t", f"{max(0.1, t1 - (t0 or 0.0)):.3f}"] return out def ydif_series(video, fps, roi=None, t0=0.0, t1=None): # metadata goes to stdout (file=-): no temp files and no cwd, so long Windows paths cannot break it r = run(["ffmpeg", "-v", "error", "-nostdin"] + _span_args(t0, t1) + ["-i", str(video), "-an", "-vf", (f"crop={roi[2]}:{roi[3]}:{roi[0]}:{roi[1]}," if roi else "") + f"fps={fps},scale=160:-2,signalstats,metadata=print:key=lavfi.signalstats.YDIF:file=-", "-f", "null", "-"]) if "YDIF" not in r.stdout: sys.exit("motion analysis failed:\n" + r.stderr[-1500:]) ts, ys, t = [], [], None for line in r.stdout.splitlines(): m = re.search(r"pts_time:([\d.]+)", line) if m: t = float(m.group(1)) m = re.search(r"YDIF=([\d.]+)", line) if m and t is not None: ts.append(t + (t0 or 0.0)) ys.append(float(m.group(1))) return ts, ys def diff_series(video, fps, roi=None, t0=0.0, t1=None): """Luma AND chroma change per frame: (times, YDIF, UDIF + VDIF). Soft, coloured animations (gradients, glows, pastel shapes that change hue, not brightness) move the chroma planes and hardly the luma.""" r = run(["ffmpeg", "-v", "error", "-nostdin"] + _span_args(t0, t1) + ["-i", str(video), "-an", "-vf", (f"crop={roi[2]}:{roi[3]}:{roi[0]}:{roi[1]}," if roi else "") + f"fps={fps},scale=160:-2,signalstats,metadata=print:file=-", "-f", "null", "-"]) if "YDIF" not in r.stdout: sys.exit("motion analysis failed:\n" + r.stderr[-1500:]) ts, ys, cs = [], [], [] t = y = u = v = None for line in r.stdout.splitlines(): m = re.search(r"pts_time:([\d.]+)", line) if m: if t is not None and y is not None: ts.append(t + (t0 or 0.0)) ys.append(y) cs.append((u or 0.0) + (v or 0.0)) t, y, u, v = float(m.group(1)), None, None, None continue m = re.search(r"signalstats\.([YUV])DIF=([\d.]+)", line) if m: val = float(m.group(2)) if m.group(1) == "Y": y = val elif m.group(1) == "U": u = val else: v = val if t is not None and y is not None: ts.append(t + (t0 or 0.0)) ys.append(y) cs.append((u or 0.0) + (v or 0.0)) return ts, ys, cs def series_peaks(ts, sig, fps, k=3.0, floor=0.3, min_gap=0.12): """Local maxima of the rise of a change signal over its +-0.5 s median that stand k robust sigmas above the noise: [(t, rise)]. The floor keeps a still picture's compression noise from becoming events.""" n = len(sig) if n < 5: return [] half = max(2, int(0.5 * fps)) base = [statistics.median(sig[max(0, i - half): i + half + 1]) for i in range(n)] res = [s - b for s, b in zip(sig, base)] med = statistics.median(res) mad = statistics.median(abs(r - med) for r in res) thr = max(floor, k * 1.4826 * mad) out = [] for i in range(1, n - 1): if res[i] > thr and res[i] >= res[i - 1] and res[i] >= res[i + 1]: if out and ts[i] - out[-1][0] < min_gap: if res[i] > out[-1][1]: out[-1] = (ts[i], res[i]) continue out.append((ts[i], res[i])) return out def scene_cuts(video, threshold, t0=0.0, t1=None): r = run(["ffmpeg", "-v", "error", "-nostdin"] + _span_args(t0, t1) + ["-i", str(video), "-an", "-vf", f"scale=320:-2,select='gt(scene,{threshold})',metadata=print:file=-", "-f", "null", "-"]) cuts, t = [], None for line in r.stdout.splitlines(): m = re.search(r"pts_time:([\d.]+)", line) if m: t = float(m.group(1)) m = re.search(r"scene_score=([\d.]+)", line) if m and t is not None: cuts.append((t + (t0 or 0.0), float(m.group(1)))) return cuts def refine(video, t, kind, span=0.2): """Re-measure a +-span window at the source frame rate and return the exact frame time.""" t0 = max(0.0, t - span) r = run(["ffmpeg", "-v", "error", "-nostdin", "-ss", f"{t0:.3f}", "-t", f"{2 * span:.3f}", "-i", str(video), "-an", "-vf", "scale=160:-2,signalstats,metadata=print:key=lavfi.signalstats.YDIF:file=-", "-f", "null", "-"]) pts, cur = [], None for line in r.stdout.splitlines(): m = re.search(r"pts_time:([\d.]+)", line) if m: cur = float(m.group(1)) m = re.search(r"YDIF=([\d.]+)", line) if m and cur is not None: pts.append((t0 + cur, float(m.group(1)))) if not pts: return t peak = max(y for _, y in pts) if kind == "onset": # first frame that reaches half of the window's peak return next(tt for tt, y in pts if y >= 0.5 * peak) return max(pts, key=lambda p: p[1])[0] def detect(ts, ys, fps): n = len(ys) if n < 5: return [] half = max(2, int(fps)) # +-1 s rolling median = "the usual amount of motion here" base = [statistics.median(ys[max(0, i - half): i + half + 1]) for i in range(n)] res = [y - b for y, b in zip(ys, base)] mad = statistics.median(abs(r) for r in res) or 0.05 thr = max(1.2, 4 * 1.4826 * mad) still = 0.6 # mean luma change per frame below this = a held frame look = max(2, int(0.4 * fps)) out = [] # bursts: local maxima of the residual, at least 0.2 s apart last_t = -9 for i in range(1, n - 1): if res[i] > thr and res[i] >= res[i - 1] and res[i] >= res[i + 1]: if ts[i] - last_t < 0.2 and out and out[-1]["kind"] == "burst": if res[i] > out[-1]["raw"]: out[-1].update(t=ts[i], raw=res[i]) last_t = ts[i] continue out.append({"t": ts[i], "kind": "burst", "raw": res[i]}) last_t = ts[i] # onsets and settles around held frames for i in range(look, n - look): before = sum(ys[i - look:i]) / look after = sum(ys[i:i + look]) / look if before < still and ys[i] > 2.0: out.append({"t": ts[i], "kind": "onset", "raw": ys[i]}) elif before > 2.0 and after < still and ys[i] < still: out.append({"t": ts[i], "kind": "settle", "raw": before}) # thin out repeats of the same kind closer than 0.25 s out.sort(key=lambda m: m["t"]) thin = [] for m in out: if thin and thin[-1]["kind"] == m["kind"] and m["t"] - thin[-1]["t"] < 0.25: if m["raw"] > thin[-1]["raw"]: thin[-1] = m continue thin.append(m) return thin def visual_moments(video, fps=15.0, scene=0.30, max_other=40, roi=None, t0=0.0, t1=None, fine=False): """Cuts, bursts, onsets and settles of a video, strongest non-cut moments first-limited. Returns (moments sorted by time, mean frame-to-frame luma change). Each moment: t, kind, strength. fine: the picture is soft and coloured (gradients, glows, shapes that change hue): the chroma change is read as well as the luma, and its peaks (and the luma's at a lower bar) become `burst` moments of their own, marked `src`. On three such reels this found 42-50 % of the events a person reading the frames wrote down, against 25 % for luma alone. """ if fine: ts, ys, cs = diff_series(video, fps, roi, t0, t1) else: ts, ys = ydif_series(video, fps, roi, t0, t1) cs = None cuts = scene_cuts(video, scene, t0, t1) if not roi else [] moments = [{"t": t, "kind": "cut", "raw": s, "exact": True} for t, s in cuts] cut_ts = [c["t"] for c in moments] prio = {"onset": 0, "burst": 1, "settle": 2} kept = [] for m in sorted(detect(ts, ys, fps), key=lambda m: (prio[m["kind"]], m["t"])): if any(abs(m["t"] - c) < 0.15 for c in cut_ts): continue # the cut itself is the event if m["kind"] == "settle" and any(0 <= m["t"] - c < 0.5 for c in cut_ts): continue # motion that merely decays after a cut if any(abs(m["t"] - k["t"]) < 0.12 for k in kept): continue # burst/onset/settle describing one and the same event kept.append(m) moments += kept if fine and cs is not None: # the extra moves: peaks of the chroma change and of the luma change at a lower bar, none within 0.1 s of a # moment already found. Their `raw` is brought to the luma scale (the 90th percentile of the signal's own # peaks = 6) so that the strengths below mean the same for all of them. extras = [] for src_, sig_, floor_, k_ in (("chroma", cs, 0.3, 3.0), ("luma", ys, 1.0, 2.0)): pk_ = series_peaks(ts, sig_, fps, k=k_, floor=floor_) if not pk_: continue rises = sorted(r_ for _, r_ in pk_) p90_ = rises[int(0.9 * (len(rises) - 1))] or 1.0 for t_, r_ in pk_: extras.append({"t": t_, "kind": "burst", "raw": 6.0 * r_ / p90_, "src": src_}) extras.sort(key=lambda m: (-m["raw"], m["t"])) for m in extras: if any(abs(m["t"] - k["t"]) < 0.10 for k in moments): continue if any(abs(m["t"] - c) < 0.12 for c in cut_ts): continue moments.append(m) # refine bursts/onsets at the video's own frame rate: +-1 frame instead of +-1/fps (not the chroma ones: the # refinement reads the luma, which did not move there) for m in moments: if m["kind"] in ("burst", "onset") and m.get("src") != "chroma": m["t"] = refine(video, m["t"], m["kind"]) # refinement can move an onset/burst onto the very frame of a cut: the cut then is the event, drop the twin cut_ts = [m["t"] for m in moments if m["kind"] == "cut"] moments = [m for m in moments if m["kind"] == "cut" or all(abs(m["t"] - c) >= 0.12 for c in cut_ts)] thin = [] for m in sorted((m for m in moments if m["kind"] != "cut"), key=lambda m: (prio[m["kind"]], m["t"])): if all(abs(m["t"] - k["t"]) >= 0.10 for k in thin): thin.append(m) moments = [m for m in moments if m["kind"] == "cut"] + thin # strengths are comparable only inside a group: cuts use the scene score, the rest use motion for group in (["cut"], ["burst", "onset", "settle"]): g = [m for m in moments if m["kind"] in group] if not g: continue top = sorted(m["raw"] for m in g)[int(0.9 * (len(g) - 1))] or 1 # absolute floor: in a calm film a single twitch must not become "strength 1.0" just because it is the only # one (busy UI films have bursts of 2-40, noise stays under 2; scene scores of real cuts are 0.3-1) top = max(top, 0.6 if group == ["cut"] else 6.0) order = sorted(g, key=lambda m: m["raw"]) for rank, m in enumerate(order): m["strength"] = round(min(1.0, m["raw"] / top), 2) # rank within its group (0 = weakest, 1 = strongest): strength saturates at 1.0 for many moments, # the rank still tells which ones are really the biggest m["pct"] = round(rank / max(1, len(order) - 1), 2) cuts_k = [m for m in moments if m["kind"] == "cut"] rest = sorted((m for m in moments if m["kind"] != "cut"), key=lambda m: -m["strength"])[: max_other] moments = sorted(cuts_k + rest, key=lambda m: m["t"]) activity_mean = sum(ys) / max(1, len(ys)) return moments, activity_mean def main(): ap = argparse.ArgumentParser() ap.add_argument("video") ap.add_argument("--out", required=True) ap.add_argument("--max", type=int, default=0, help="max non-cut moments to keep, strongest first (0 = auto: 15 per 10 s, at least 40)") ap.add_argument("--fps", type=float, default=None, help="analysis rate (default 15; 30 with --fine)") ap.add_argument("--fine", action="store_true", help="a soft, coloured animation (gradients, glows, pastel shapes): also read the CHROMA change " "and a lower luma bar, so that moves that change hue and not brightness are found " "(moments carry src=chroma|luma). More moments: 25 per 10 s are kept instead of 15") ap.add_argument(" - skills/real-sfx/scripts/from_cues.py (118630 bytes)
#!/usr/bin/env python3 """Turn a project's own typed cue list into a cue sheet with REAL sounds on the same timestamps. python from_cues.py docs/cues.json --video renders/film.mp4 --out work/cues.json [--ui auto|uisfx|library] [--max-rate 14] [--moments work/moments/moments.json] [--map my_map.json [--remember]] [--only key,click] [--skip tick] Why: a film that is generated by code (HyperFrames, Remotion, a "film as a function of time" engine) usually knows what happens when. If the project already writes a design-time cue list, that list is better than any frame analysis: exact times, and the kind of event (a keystroke, a click, a wipe, a coin) is stated, not guessed. The projects written for a synthesised score keep such a list; this script keeps its times and kinds and swaps the synthesis for sounds from the library (never synthesised) and uisfx (UI moments). Input: a JSON list (or {"cues": [...]} / {"events": [...]}) of objects. Recognised keys: time t | time | at | start seconds on the video timeline kind type | name | kind | event | sound see ALIASES below; unknown kinds are listed, never guessed gain g | gain | volume | vol 1.0 = nominal; becomes dB relative to the role's level length len | dur | duration | length seconds (riser build-up, whoosh length) What it also does, because the list is only half of the truth: * checks that the list belongs to THIS render (structural events must sit on picture changes) and where it drifts (a re-time or voice fit moves the end of a list first); * finds the project's audio stems and checks that they belong to this render too (duration, and the shape of the loudness over time); stems of another cut would put another voice and music under the new sounds; * says whether the render's own audio already holds the synthesized layer (the new sounds must replace it, not double it) and whether there is a voice in the render at all; * moves whooshes to where the synthesized sound really peaked (the author synchronised to what he heard); * turns runs of "key" events into single REAL keystrokes cut out of the library's typing recordings. --map file.json extends or overrides the table: {"zap": "glitch", "boop": {"uisfx": "select"}, "stomp": {"pick": {"role": "hit", "dark": true}, "gain_db": 2}} (--remember keeps it) --moments optional: picture moments (find_moments.py) with no sound within 150 ms are listed, so strong events the project forgot to declare do not stay silent. """ import argparse import json import math import os import random import re import subprocess import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import (SKILL_DIR, decode_mono, effective_dur, family_key, load_config, measure_loudness, onsets, voice_share) from common import load_json, read_stdin_text from picker import load_index, load_taste, rank from search import taste_pack, taste_ui_source, uisfx_file from unbake import fit_stems, scan_audio, unbake as unbake_audio KIND_MAP = SKILL_DIR / "kind_map.json" # the user's own kinds, remembered with --remember SKIP_DIRS = {"node_modules", ".git", ".hyperframes", "renders", "assets", "dist", "snapshots", ".thumbnails", ".waveform-cache", "export", "__pycache__", "vendor"} # (projects keep timing.js under src/) IFACE_KINDS = {"click", "key", "tick", "tock", "chime", "success", "error"} # events only an interface produces PITCH_CYCLE = [0, -2, 2, -3, 1, -1] UI_PITCH = [0, 1, -1, 2, -2, 1] # round-robin for a repeated interface sound: same family, never the same twice THIN_GAP = 0.25 # events of one kind closer than this form a run # canonical kind -> words that mean it ALIASES = { "whoosh": ("whoosh", "swoosh", "swish", "flyby", "slide", "swipe", "move", "fly", "zoom", "push", "pan", "sweep"), "wipe": ("wipe", "transition", "scene", "scene_change", "page_turn", "cut"), "hit": ("hit", "impact", "slam", "punch", "stamp", "stinger", "boom", "thud", "slap", "bang"), "thump": ("thump", "kick", "low_hit", "bass_hit", "sub_hit"), "riser": ("riser", "build", "buildup", "build_up", "swell", "rise", "tension", "sweep_up"), "drop": ("drop", "sub_drop", "subdrop", "bass_drop"), "click": ("click", "press", "tap", "button", "mouse", "mouse_click", "select"), "pop": ("pop", "bubble", "blip", "appear", "plop", "bloop"), "tick": ("tick",), "tock": ("tock", "tack", "tick_tock"), "key": ("key", "keystroke", "type", "typing", "keypress", "key_press", "keyboard"), "chime": ("chime", "bell", "ding", "ping", "notify", "notification", "bleep"), "success": ("success", "ok", "done", "complete", "win", "confirm"), "magic": ("magic", "sparkle", "shimmer", "twinkle", "glitter", "fairy", "glow", "heal", "reveal"), "water": ("water", "drip", "droplet", "splash", "liquid", "drop_water"), "coins": ("coins", "coin", "cash", "money", "purchase", "cha_ching", "register", "payment"), "glitch": ("glitch", "stutter", "datamosh", "static"), "error": ("error", "fail", "warning", "alert", "denied", "wrong", "buzz"), "camera": ("camera", "shutter", "photo"), "ambience": ("ambience", "ambient", "bed", "room", "atmos", "atmosphere", "drone"), "paper": ("paper", "page", "flip", "card", "sheet", "receipt"), "glass": ("glass", "crystal", "glassy"), "shatter": ("shatter", "smash", "glass_break", "break"), "data": ("data", "scan", "compute", "processing", "loading"), } CANON = {w: k for k, ws in ALIASES.items() for w in ws} # canonical kind -> how it becomes a cue. "specs" are tried in order; the first with candidates wins. # "ui": the uisfx cue used when --ui says interface sounds come from uisfx. # "onsets_max": the library sounds for these kinds must be ONE sound (not a three-click gesture or a typing take). ROUTES = { "whoosh": {"specs": [{"role": "whoosh", "target_dur": 0.5, "max_dur": 1.3, "prefer_tag": "whoosh"}], "base": -2.0, "vary": True, "peak_kind": True}, "wipe": {"specs": [{"role": "whoosh", "target_dur": 0.7, "max_dur": 1.4, "prefer_tag": "whoosh"}], "base": -4.0, "vary": True, "peak_kind": True}, "hit": {"specs": [{"role": "hit", "punchy": True, "max_dur": 1.3}], "base": 0.0, "vary": True}, "thump": {"specs": [{"role": "hit", "dark": True, "punchy": True, "max_dur": 0.9}, {"role": "sub_drop", "max_dur": 1.2}], "base": -2.0, "vary": True}, "riser": {"specs": [{"role": "riser", "target_dur": 0.8, "max_dur": 3.0}], "base": -4.0, "start": True}, "drop": {"specs": [{"role": "sub_drop", "max_dur": 2.0}, {"role": "hit", "dark": True, "min_dur": 1.0, "max_dur": 3.5}], "base": -2.0}, "click": {"ui": "press", "specs": [{"role": "click", "max_dur": 0.4, "onsets_max": 1, "tier": "main", "_min": 3}, {"role": "click", "max_dur": 0.7, "onsets_max": 3, "tier": "main", "_first": True, "_min": 3}, {"role": "click", "max_dur": 0.4, "onsets_max": 1}], "base": 0.0}, "pop": {"ui": "select", "specs": [{"role": "pop", "max_dur": 0.6, "onsets_max": 1}, {"role": "ui", "query": "pop", "max_dur": 0.6, "onsets_max": 1}, {"role": "click", "max_dur": 0.3, "punchy": True, "onsets_max": 1}, {"role": "ui", "query": "bubble", "max_dur": 0.6, "onsets_max": 1}], "base": 0.0, "vary": True}, "tick": {"ui": "progress-step", "specs": [{"role": "click", "max_dur": 0.25, "bright": True, "onsets_max": 1}, {"role": "water", "max_dur": 0.25, "onsets_max": 1}], "base": -2.0}, "tock": {"ui": "snap", "specs": [{"role": "click", "max_dur": 0.3, "onsets_max": 1}, {"role": "water", "max_dur": 0.3, "onsets_max": 1}], "base": -1.0}, "chime": {"ui": "notification", "specs": [{"role": "chime", "prefer_tag": "bell", "max_dur": 2.0}, {"role": "ui", "query": "bell", "max_dur": 2.0}, {"role": "ui", "max_dur": 2.0}], "base": 0.0}, "success": {"ui": "success", "specs": [{"role": "chime", "prefer_tag": "ding", "max_dur": 1.8}, {"role": "ui", "query": "success", "max_dur": 2.0}], "base": 0.0}, "magic": {"specs": [{"role": "chime", "query": "magic", "max_dur": 2.5}, {"role": "chime", "max_dur": 2.5}], "base": -2.0, "vary": True}, "water": {"specs": [{"role": "water", "max_dur": 0.8, "onsets_max": 1}], "base": 0.0, "vary": True}, "coins": {"specs": [{"role": "coin", "max_dur": 3.0}], "ui": "purchase", "base": 0.0, "prefer_library": True}, # a short glitch from the main libraries; else a burst cut out of a static / noise loop of the main libraries # (a real recording of TV static, 0.12-0.5 s of it); else any short glitch of the fallback libraries "glitch": {"specs": [{"role": "glitch", "max_dur": 1.0, "tier": "main"}, {"role": "glitch", "min_dur": 2.0, "tier": "main", "burst": True}, {"role": "glitch", "max_dur": 1.0}], "base": -2.0, "vary": True}, "error": {"ui": "error", "specs": [{"role": "error", "max_dur": 1.5}], "base": 0.0}, "camera": {"specs": [{"role": "camera", "max_dur": 1.0}], "base": 0.0}, "ambience": {"specs": [{"role": "ambience", "min_dur": 2.0}], "base": -6.0, "loop": True}, "paper": {"specs": [{"role": "paper", "max_dur": 1.2}], "base": 0.0, "vary": True}, # a glassy ping (a layer "becomes glass", a UI pane): tonal chimes first; the pack's `glass` role is BREAKING glass "glass": {"specs": [{"role": "chime", "prefer_tag": "ding", "query": "star", "max_dur": 1.8}, {"role": "chime", "prefer_tag": "ding", "max_dur": 1.8}], "base": -2.0, "vary": True}, "shatter": {"specs": [{"role": "glass", "max_dur": 1.5}], "base": 0.0}, "data": {"specs": [{"role": "data", "max_dur": 1.5}], "base": -2.0}, "key": {"specs": [], "base": 0.0}, # real keystrokes cut from typing recordings, see keystroke_bank } # a physical object (a bouncing ball, footsteps, a knock): the recordings are foley and body falls, and they hold # several hits each: only the CLEAN single hits are used (common.clean_hits), the way keystrokes are cut from a take PHYS_SPECS = { "thump": [{"role": "foley", "says": "thud|thump|thunk|knock|fall|drop|bump", "max_dur": 4.0}, {"role": "hit", "says": "thud|thump|knock|bump|fall", "max_dur": 4.0}], "hit": [{"role": "foley", "says": "thud|thump|thunk|knock|impact|slam|fall|drop", "max_dur": 4.0}, {"role": "hit", "says": "thud|knock|impact|slam", "max_dur": 4.0}], "pop": [{"role": "foley", "says": "tap|tick|knock|click|clack|drop|thunk", "max_dur": 3.0}, {"role": "click", "max_dur": 1.5}], "tick": [{"role": "foley", "says": "tap|tick|knock|click|clack|drop", "max_dur": 3.0}, {"role": "click", "max_dur": 1.5}], "tock": [{"role": "foley", "says": "tap|tick|knock|click|clack|drop", "max_dur": 3.0}, {"role": "click", "max_dur": 1.5}], } PHYS_LOW = {"thump", "hit"} # these take the darker hits of the pool, the others the brighter ones def clean_pool(index, kinds, used, taste, need=18, max_files=12): """Clean single hits of the best foley recordings for the given physical kinds, one recording family first (a ball is one object: its takes are the takes of one family). [{file, id, name, start, len, zcr, level_db, role}]""" from common import clean_hits specs = [] for k in kinds: specs += PHYS_SPECS.get(k, []) seen, pool, fam0 = set(), [], None for spec in specs: for _, s in rank(index, spec, used, taste)[:max_files]: if s["path"] in seen: continue seen.add(s["path"]) fk = (s["library"], family_key(s["name"])) fam0 = fam0 or fk hits, _ = clean_hits(s["path"]) for h in hits: if h["clean"]: pool.append(dict(h, file=s["path"], id=s["id"], name=s["name"], role=spec.get("role", "foley"), same_family=(fk == fam0))) if len(pool) >= need: break same = [h for h in pool if h["same_family"]] return same if len(same) >= 4 else pool def bank_from_ids(index, ids): """Single hits of the named sounds: the clean ones, else every separate sound (granular material: poured beads).""" from common import clean_hits out = [] for i in ids: s = next((x for x in index if x["id"] == i), None) if s is None: sys.exit(f"--kind ...=slices:{i}: no sound with that id in the index") hits, _ = clean_hits(s["path"]) good = [h for h in hits if h["clean"]] or [h for h in hits if h["level_db"] >= -18.0] if not good: # a sound that is one hit from its first sample: all of it good = [{"t": 0.0, "start": 0.0, "len": round(min(0.3, max(0.04, effective_dur(s))), 3), "level_db": 0.0, "clean": True, "decay_ms": 0, "zcr": 0}] for h in good: out.append(dict(h, file=s["path"], id=s["id"], name=s["name"], role=s.get("role", "foley"), len=round(min(h["len"], 0.12), 3) if not h["clean"] else h["len"], abs_db=round((s.get("peak_db") or 0.0) + h.get("level_db", 0.0), 1))) bank_from_ids.dropped = 0 if len(out) >= 6: # the quietest slices come up with their noise: leave them out of the bank top = max(h["abs_db"] for h in out) keep = [h for h in out if h["abs_db"] >= top - 12.0] if len(keep) >= 4: bank_from_ids.dropped = len(out) - len(keep) out = keep return out def parse_kind_arg(text): """'bead=click' -> ('bead', 'click'); 'zap=role:glitch,max_dur=0.6' -> a pick; 'boop=uisfx:select' -> uisfx.""" name, _, target = str(text).partition("=") name = name.strip().lower().replace("-", "_").replace(" ", "_") target = target.strip() if not name or not target: - skills/real-sfx/scripts/from_hyperframes.py (16406 bytes)
#!/usr/bin/env python3 """Read the moments straight out of a HyperFrames composition (no rendering, no frame analysis). python from_hyperframes.py path/to/project/index.html --out work/moments.json [--video render.mp4] Timings are exact because they come from the composition itself: * every scene (a timed element directly under the root, or a sub-composition host) -> a "cut" at its start * every other timed element (`data-start`) -> an "onset" * every GSAP tween on a registered timeline with a numeric/relative position -> "onset" (entrances), "burst" (fast moves/scales), exits are ignored Relative starts (`data-start="intro + 2"`), sub-compositions (offsets are added up) and GSAP positions ("<", ">", "+=0.3", labels) are resolved. Anything it cannot resolve is reported, never guessed. The output has the same shape as find_moments.py's moments.json, so suggest_cues.py, mix.py and critique.py work on it unchanged. `hint` carries the element's id/classes/text so UI cues can be chosen. """ import os import argparse import json import re import sys from html.parser import HTMLParser from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) VOID = {"br", "hr", "img", "input", "meta", "link", "source", "area", "base", "col", "embed", "track", "wbr"} STRONG = ("title", "headline", "logo", "hero", "cta", "h1", "wordmark", "brand") MEDIUM = ("card", "panel", "modal", "stat", "number", "counter", "button", "btn", "badge", "chart", "icon", "device") WEAK = ("caption", "subtitle", "sub", "text", "label", "body", "copy", "bg", "background", "shape") class Collector(HTMLParser): def __init__(self): super().__init__(convert_charrefs=True) self.stack, self.elements, self.scripts, self._script = [], [], [], None def handle_starttag(self, tag, attrs): a = dict(attrs) if tag == "script": self._script = [] return el = {"tag": tag, "attrs": a, "depth": len(self.stack), "text": "", "parent": self.stack[-1] if self.stack else None} self.elements.append(el) if tag not in VOID: self.stack.append(el) def handle_endtag(self, tag): if tag == "script": if self._script is not None: self.scripts.append("".join(self._script)) self._script = None return for i in range(len(self.stack) - 1, -1, -1): if self.stack[i]["tag"] == tag: del self.stack[i:] break def handle_data(self, data): if self._script is not None: self._script.append(data) elif self.stack: for el in self.stack: if len(el["text"]) < 60: el["text"] = (el["text"] + " " + data.strip()).strip() def num(x): try: return float(x) except (TypeError, ValueError): return None def hint_of(el): a = el["attrs"] bits = [a.get("id", ""), a.get("class", "").replace("clip", ""), el["tag"], (el.get("text") or "")[:30]] return " ".join(b for b in bits if b).strip() def strength_of(hint, dur=None): h = hint.lower() if any(k in h for k in STRONG): return 0.9 if any(k in h for k in MEDIUM): return 0.7 if any(k in h for k in WEAK): return 0.4 return 0.55 # ------------------------------------------------------------------ GSAP tweens (best effort) def split_args(s): """Split a call's argument text on top-level commas.""" out, depth, cur, q = [], 0, [], None i = 0 while i < len(s): ch = s[i] if q: cur.append(ch) if ch == "\\": cur.append(s[i + 1]) i += 1 elif ch == q: q = None elif ch in "\"'`": q = ch cur.append(ch) elif ch in "([{": depth += 1 cur.append(ch) elif ch in ")]}": depth -= 1 cur.append(ch) elif ch == "," and depth == 0: out.append("".join(cur).strip()) cur = [] else: cur.append(ch) i += 1 if "".join(cur).strip(): out.append("".join(cur).strip()) return out def find_calls(js): """Yield (method, [args]) for .to/.from/.fromTo/.set/.addLabel calls in source order.""" for m in re.finditer(r"\.(to|from|fromTo|set|addLabel)\s*\(", js): i, depth, q = m.end(), 1, None while i < len(js) and depth: ch = js[i] if q: if ch == "\\": i += 1 elif ch == q: q = None elif ch in "\"'`": q = ch elif ch == "(": depth += 1 elif ch == ")": depth -= 1 i += 1 yield m.group(1), split_args(js[m.end():i - 1]) def tween_moments(js, offset, warn): """Return moments from the GSAP calls of one script, times shifted by offset (sub-composition start).""" out, labels, cursor, prev_start = [], {}, 0.0, 0.0 for method, args in find_calls(js): if method == "addLabel": if args: name = args[0].strip("\"'`") pos = args[1] if len(args) > 1 else None labels[name] = num(pos) if num(pos) is not None else cursor continue if method == "set": continue if not args: continue pos_arg = args[3] if method == "fromTo" and len(args) > 3 else (args[2] if method != "fromTo" and len(args) > 2 else None) vars_txt = args[2] if method == "fromTo" and len(args) > 2 else (args[1] if len(args) > 1 else "") dm = re.search(r"duration\s*:\s*([\d.]+)", vars_txt) dur = float(dm.group(1)) if dm else 0.5 # --- position start = None if pos_arg is None: start = cursor else: p = pos_arg.strip().strip("\"'`") if num(p) is not None: start = float(p) elif p == "<": start = prev_start elif p == ">": start = cursor elif re.fullmatch(r"<[+-]?[\d.]+", p): start = prev_start + float(p[1:]) elif re.fullmatch(r">[+-]?[\d.]+", p): start = cursor + float(p[1:]) elif re.fullmatch(r"[+-]=[\d.]+", p): start = cursor + (float(p[2:]) if p[0] == "+" else -float(p[2:])) else: lm = re.fullmatch(r"([A-Za-z_][\w-]*)(?:([+-])=([\d.]+))?", p) if lm and lm.group(1) in labels: start = labels[lm.group(1)] + (float(lm.group(3)) * (1 if lm.group(2) == "+" else -1) if lm.group(3) else 0) if start is None: warn.append(f"GSAP position not understood: {pos_arg!r}") continue prev_start = start cursor = max(cursor, start + dur) tgt = args[0].strip() target = tgt.strip("\"'`") if tgt[:1] in "\"'`" else tgt low = vars_txt.lower() entering = method in ("from", "fromTo") and bool(re.search(r"opacity|autoalpha|scale|\by\b|\bx\b|yPercent|xPercent|clip", vars_txt)) exiting = method == "to" and re.search(r"(opacity|autoalpha)\s*:\s*0\b", low) moving = method == "to" and re.search(r"\b(x|y|xpercent|ypercent|scale|rotation|rotate)\s*:", low) if exiting: continue if not (entering or moving): continue hint = re.sub(r"[#.\[\]=\"'>~+*]", " ", target).strip() st = strength_of(hint) kind = "onset" if entering else "burst" if dur <= 0.25 and kind == "burst": st = min(1.0, st + 0.15) out.append({"t": round(offset + start, 3), "kind": kind, "strength": round(st, 2), "hint": hint[:60], "source": "gsap", "tween_s": round(dur, 2)}) return out # ------------------------------------------------------------------ composition tree def load(path, offset, depth, warn, seen): path = Path(path) if path in seen or depth > 6 or not path.exists(): if not path.exists(): warn.append(f"sub-composition not found: {path}") return [], [], None seen = seen | {path} text = path.read_text(encoding="utf-8", errors="replace") p = Collector() p.feed(text) els = p.elements root = next((e for e in els if "data-composition-id" in e["attrs"]), None) root_dur = num(root["attrs"].get("data-duration")) if root else None starts, ends = {}, {} ids = {e["attrs"]["id"]: e for e in els if "id" in e["attrs"]} def resolve(el, stack=()): a = el["attrs"] raw = a.get("data-start") if raw is None: return None if num(raw) is not None: return float(raw) m = re.fullmatch(r"\s*([\w-]+)\s*(?:([+-])\s*([\d.]+))?\s*", raw) if not m or m.group(1) not in ids or m.group(1) in stack: warn.append(f"unresolved data-start={raw!r}") return 0.0 ref = ids[m.group(1)] s = resolve(ref, stack + (m.group(1),)) d = num(ref["attrs"].get("data-duration")) base = (s or 0.0) + (d if d is not None else 0.0) if m.group(2): base += float(m.group(3)) * (1 if m.group(2) == "+" else -1) return base clips = [] for el in els: if "data-start" not in el["attrs"] or el["tag"] in ("audio",): continue s = resolve(el) if s is None: continue d = num(el["attrs"].get("data-duration")) clips.append({"el": el, "start": s, "dur": d}) moments, subs = [], [] root_children = [c for c in clips if c["el"]["parent"] is root] for c in clips: el, a = c["el"], c["el"]["attrs"] t = offset + c["start"] # inside a sub-composition the root's children are elements of that scene, not scenes of the film is_scene = depth == 0 and c in root_children and (c["dur"] or 0) >= 0.5 h = hint_of(el) if "data-composition-src" in a: sub_path = path.parent / a["data-composition-src"] sm, _, sdur = load(sub_path, t, depth + 1, warn, seen) subs.append(sm) moments.append({"t": round(t, 3), "kind": "cut", "strength": 0.85, "hint": h, "source": "scene", "scene_s": c["dur"]}) elif is_scene: moments.append({"t": round(t, 3), "kind": "cut", "strength": 0.85, "hint": h, "source": "scene", "scene_s": c["dur"]}) elif el["tag"] not in ("video",): moments.append({"t": round(t, 3), "kind": "onset", "strength": strength_of(h), "hint": h, "source": "clip", "tween_s": c["dur"]}) for js in p.scripts: if "gsap" in js or ".to(" in js or ".from(" in js: moments += tween_moments(js, offset, warn) for sm in subs: moments += sm return moments, clips, root_dur def main(): ap = argparse.ArgumentParser() ap.add_argument("composition", help="index.html or the project folder") ap.add_argument("--out", required=True) ap.add_argument("--video", help="rendered video of this composition (needed later by mix.py)") ap.add_argument("--merge-ms", type=float, default=60, help="merge moments of the same kind closer than this") a = ap.parse_args() p = Path(a.composition) if p.is_dir(): p = p / "index.html" if not p.exists(): sys.exit(f"composition not found: {p}") warn = [] moments, clips, root_dur = load(p, 0.0, 0, warn, frozenset()) # the first scene at t=0 is the hook, not a cut for m in moments: if m["kind"] == "cut" and m["t"] < 0.05: m["kind"], m["strength"] = "onset", 0.8 moments.sort(key=lambda m: (m["t"], -m["strength"])) merged = [] for m in moments: near = next((x for x in reversed(merged) if abs(x["t"] - m["t"]) * 1000 <= a.merge_ms), None) if near and (near["kind"] == m["kind"] or {near["kind"], m["kind"]} == {"cut", "onset"}): if m["strength"] > near["strength"] or (m["kind"] == "cut" and near["kind"] == "onset"): near.update(m) continue merged.append(m) tmax = max((m["t"] for m in merged), default=0.0) dur = root_dur or max(tmax + 1.0, 1.0) merged = [m for m in merged if m["t"] <= dur + 0.001] ranked = sorted(m["strength"] for m in merged) for i, m in enumerate(merged): m["id"] = i m["pct"] = round(sum(1 for s in ranked if s <= m["strength"]) / max(1, len(ranked)), 2) res = {"video": str(Path(a.video).resolve()) if a.video else None, "composition": str(p.resolve()), "info": {"duration": dur, "source": "hyperframes", "has_audio": None}, "moments": merged, "warnings": sorted(set(warn))} Path(a.out).parent.mkdir(parents=True, exist_ok=True) Path(a.out).write_text(json.dumps(res, ensure_ascii=False, indent=1), encoding="utf-8") kinds = {} for m in merged: kinds[m["kind"]] = kinds.get(m["kind"], 0) + 1 print(f"{p.name}: {dur:.1f} s, {len(merged)} moments ({', '.join(f'{k}={v}' for k, v in kinds.items())}), " f"{len(clips)} timed elements") for w in res["warnings"]: print("WARN", w) if len(merged) <= 2 and len(clips) <= 3: # one element, no timeline tweens: the film is drawn by a script (a function of time), so the HTML holds # no timings. Look for the project's own cue list, else the picture is the only source. proj = p.parent found = [proj / rel for rel in ("docs/cues.json", "cues.json", "scripts/cues.json", "sfx/cues.json", "src/cues.json", "docs/sfx_cues.json", "sound_cues.json", "docs/sound_cues.json") if (proj / rel).exists()] if not found: # a bounded search: any cues*.json / *sfx*.json that looks like a list skip = {"node_modules", ".git", ".hyperframes", "renders", "assets", "dist", "snapshots", "vendor"} for dp, dns, fns in os.walk(proj): dns[:] = [d for d in dns if d not in skip and len(Path(dp, d).relative_to(proj).parts) < 3] for fn in fns: if fn.lower().endswith(".json") and ("cue" in fn.lower() or "sfx" in fn.lower()): found.append(Path(dp) / fn) print("NOTE: the composition has one timed element and no - skills/real-sfx/scripts/from_synth.py (26343 bytes)
#!/usr/bin/env python3 """The event list of a project that synthesizes its sound in a script (Node): which sound, at what time, how loud. python from_synth.py PROJECT_OR_SCRIPT [--out work/events.json] [--bed-only work/bed.wav] [--args ...] Why: a film generated by code usually has no cue file. Its sound lives in a script (audio.cjs, sfx.cjs) as calls like `whoosh(4.2, 1, 0.3, 0.5)`, `click(18.35)`, `key(t, i)`: the TIME and the KIND of every sound are in the code, and nowhere else in a form a tool can read. This script finds those functions, runs the script once with every file write and child process switched off, records each outermost call (name, time, gain, length) and writes the list in the format from_cues.py reads. Nothing in the project is changed or created. --bed-only OUT.wav runs the script a second time with the event functions switched OFF and keeps the WAV it would have written: the author's score (music, drones, beds) without the effects. That is the music to keep when it is synthesized by the same script and baked into one file, and not a stem of its own (use it with mix.py --base-audio OUT.wav voice.wav --duck-music). --dry only list the functions it would record, run nothing. It executes the project's own script (Node, CommonJS). The functions are found by their shape: a first parameter that is a time (t, time, at, start ...) and no parameter that is a sample generator (fn, cb, gen ...). Functions that are also called from inside another recorded function (the `add` that every effect uses) are helpers and not events. A project whose cues are written as objects (`cues.push({t, type, gain})`) is read from those objects. ES modules (.mjs) are not run: such a script usually reads its list from a file, which is then the list. """ import argparse import json import os import re import shutil import subprocess import sys import tempfile from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import stereo_fmt TIME_FIRST = {"t", "t0", "time", "at", "start", "when", "begin", "onset", "sec", "seconds", "ts", "tt", "tm", "tstart", "t_start", "startt", "start_t", "time_s"} GAIN_NAMES = {"g", "gain", "vol", "volume", "amp", "level", "v"} LEN_NAMES = {"len", "length", "dur", "duration", "d", "l", "sustain"} GENERATOR_PARAMS = {"fn", "cb", "callback", "gen", "generator", "osc", "shape", "f_", "func", "sample", "env_fn"} FREQ_NAMES = {"f", "freq", "frequency", "hz", "f0", "fq", "pitch_hz", "tone", "note_hz"} DIR_NAMES = {"up", "rise", "rising", "dir", "direction", "ascending"} DENY_NAMES = {"add", "mix", "render", "write", "synth", "env", "envelope", "noise", "rnd", "rand", "rng", "bp", "lp", "hp", "mapt", "w", "warp", "word", "at", "plan", "pan", "play", "emit", "voice", "seed", "clamp", "lerp"} SCRIPT_DIRS = ("scripts", "script", "tools", "audio", "src", "build", ".") SKIP = {"node_modules", ".git", "renders", "snapshots", "dist", "vendor", ".hyperframes"} # ------------------------------------------------------------------ a small JS scanner: strings, comments, brackets def _skip_string(src, i): q = src[i] i += 1 n = len(src) while i < n: c = src[i] if c == "\\": i += 2 continue if q == "`" and c == "$" and i + 1 < n and src[i + 1] == "{": i = _balanced(src, i + 1, "{", "}") continue if c == q: return i + 1 i += 1 return n def _regex_allowed(src, i): j = i - 1 while j >= 0 and src[j] in " \t\r\n": j -= 1 if j < 0: return True if src[j] in "(,=:[!&|?{};+-*%<>~^": return True m = re.search(r"(?:return|typeof|case|of|in)$", src[max(0, j - 7):j + 1]) return bool(m) def _balanced(src, i, open_ch, close_ch): """src[i] == open_ch. Index just after the matching close, skipping strings, comments and regex literals.""" n = len(src) depth = 0 while i < n: c = src[i] if c in "\"'`": i = _skip_string(src, i) continue if c == "/" and i + 1 < n: d = src[i + 1] if d == "/": j = src.find("\n", i) i = n if j < 0 else j continue if d == "*": j = src.find("*/", i + 2) i = n if j < 0 else j + 2 continue if _regex_allowed(src, i): j = i + 1 in_class = False while j < n and src[j] != "\n": if src[j] == "\\": j += 2 continue if src[j] == "[": in_class = True elif src[j] == "]": in_class = False elif src[j] == "/" and not in_class: break j += 1 i = j + 1 continue if c == open_ch: depth += 1 elif c == close_ch: depth -= 1 if depth == 0: return i + 1 i += 1 return n def _split_params(text): out, depth, cur, i, n = [], 0, "", 0, len(text) while i < n: c = text[i] if c in "\"'`": j = _skip_string(text, i) cur += text[i:j] i = j continue if c in "([{": depth += 1 elif c in ")]}": depth -= 1 if c == "," and depth == 0: out.append(cur) cur = "" else: cur += c i += 1 if cur.strip(): out.append(cur) return out def _param(p): p = p.strip() if not p or p.startswith(("{", "[", "...")): return None, None name, eq, default = p.partition("=") name = name.strip() if not re.match(r"^[A-Za-z_$][\w$]*$", name): return None, None val = None if eq: try: val = float(default.strip()) except ValueError: val = None return name, val def _statement_end(src, i): """End of an expression-bodied arrow function / initialiser that starts at i: a `;` at depth 0, or the end of the line when the next line does not continue it.""" n = len(src) depth = 0 while i < n: c = src[i] if c in "\"'`": i = _skip_string(src, i) continue if c == "/" and i + 1 < n and src[i + 1] in "/*": if src[i + 1] == "/": j = src.find("\n", i) i = n if j < 0 else j else: j = src.find("*/", i + 2) i = n if j < 0 else j + 2 continue if c in "([{": depth += 1 elif c in ")]}": depth -= 1 if depth < 0: return i elif c == ";" and depth == 0: return i + 1 elif c == "\n" and depth == 0: j = i + 1 while j < n and src[j] in " \t\r\n": j += 1 nxt = src[j:j + 2] prev = src[:i].rstrip()[-1:] if src[:i].strip() else "" if not (nxt[:1] in ".?:+-*/%&|,)" or prev in "=+-*/%&|,?:(["): return i i += 1 return n DEF_FN = re.compile(r"(?m)^([ \t]*)(?:export\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)\s*\(") DEF_VAR = re.compile(r"(?m)^([ \t]*)(?:export\s+)?(const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*" r"(?:async\s+)?(?:function\s*\*?\s*[A-Za-z_$\w]*\s*)?\(") DEF_VAR1 = re.compile(r"(?m)^([ \t]*)(?:export\s+)?(const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s+)?" r"([A-Za-z_$][\w$]*)\s*=>") def find_functions(src): """[(name, params[(pname, default)], insert_at, kw_span)] for functions whose first parameter is a time.""" found = [] seen = set() def take(name, params, end, kw_span): pn = [_param(p) for p in params] pn = [(a, b) for a, b in pn if a] if not pn or pn[0][0].lower() not in TIME_FIRST: return if name.lower() in DENY_NAMES or any(a.lower() in GENERATOR_PARAMS for a, _ in pn): return if name in seen: return seen.add(name) found.append((name, pn, end, kw_span)) for m in DEF_FN.finditer(src): po = m.end() - 1 pe = _balanced(src, po, "(", ")") params = _split_params(src[po + 1:pe - 1]) k = pe while k < len(src) and src[k] in " \t\r\n": k += 1 if k < len(src) and src[k] == "{": take(m.group(2), params, _balanced(src, k, "{", "}"), None) for m in DEF_VAR.finditer(src): po = m.end() - 1 pe = _balanced(src, po, "(", ")") params = _split_params(src[po + 1:pe - 1]) k = pe while k < len(src) and src[k] in " \t\r\n": k += 1 if src[k:k + 2] == "=>": k += 2 while k < len(src) and src[k] in " \t\r\n": k += 1 end = _balanced(src, k, "{", "}") if src[k:k + 1] == "{" else _statement_end(src, k) elif src[k:k + 1] == "{": end = _balanced(src, k, "{", "}") else: continue kw = (m.start(2), m.end(2)) if m.group(2) == "const": take(m.group(3), params, end, kw) else: take(m.group(3), params, end, None) for m in DEF_VAR1.finditer(src): k = m.end() while k < len(src) and src[k] in " \t\r\n": k += 1 end = _balanced(src, k, "{", "}") if src[k:k + 1] == "{" else _statement_end(src, k) kw = (m.start(2), m.end(2)) if m.group(2) == "const" else None take(m.group(3), [m.group(4)], end, kw) return found def instrument(src, funcs): """Source with every found function re-bound to a recording wrapper right after its definition.""" edits = [] for name, params, end, kw in funcs: pj = json.dumps([[a, b] for a, b in params]) edits.append((end, f"\n;{name} = globalThis.__fs_wrap({json.dumps(name)}, {name}, {pj});")) if kw: edits.append((kw[0], None, kw[1])) out = src for e in sorted(edits, key=lambda x: -x[0]): if e[1] is None: out = out[:e[0]] + "let" + out[e[2]:] else: out = out[:e[0]] + e[1] + out[e[0]:] return out HOOK = r""" 'use strict'; const fs = require('fs'), path = require('path'), Module = require('module'); const cfg = JSON.parse(fs.readFileSync(process.env.FROM_SYNTH_CFG, 'utf8')); const ev = [], called = {}, nested = {}, valued = {}, writes = [], pushed = []; const realWrite = fs.writeFileSync; let depth = 0; globalThis.__fs_wrap = function (name, fn, params) { if (typeof fn !== 'function') return fn; const stub = cfg.stub.indexOf(name) >= 0; const w = function (...args) { if (depth === 0) { ev.push({name: name, args: args.slice(0, 10).map(a => typeof a === 'number' ? a : null)}); called[name] = (called[name] || 0) + 1; if (stub) return undefined; } else { nested[name] = (nested[name] || 0) + 1; } depth++; try { const r = fn.apply(this, args); if (r !== undefined && r !== null && depth === 1) valued[name] = (valued[name] || 0) + 1; return r; } finally { depth--; } }; return w; }; fs.writeFileSync = function (p, data) { const pp = String(p); writes.push({path: pp, bytes: (data && data.length) || 0}); if (cfg.saveWav && /\.wav$/i.test(pp)) realWrite.call(fs, path.join(cfg.saveWav, path.basename(pp)), data); }; fs.writeFile = function (p, d) { const cb = Array.prototype.slice.call(arguments).filter(x => typeof x === 'function')[0]; fs.writeFileSync(p, d); if (cb) cb(null); }; fs.appendFileSync = function () {}; fs.mkdirSync = function () {}; fs.copyFileSync = function () {}; fs.renameSync = function () {}; fs.unlinkSync = function () {}; fs.rmSync = function () {}; fs.createWriteStream = function () { const s = {write() { return true; }, end() {}, on() { return s; }, once() { return s; }, emit() {}}; return s; }; const cp = require('child_process'); for (const k of ['exec', 'execFile', 'spawn', 'fork']) cp[k] = function () { return {on() {}, stdout: {on() {}}, stderr: {on() {}}, kill() {}}; }; for (const k of ['execSync', 'execFileSync']) cp[k] = function () { return Buffer.alloc(0); }; cp.spawnSync = function () { return {status: 0, stdout: Buffer.alloc(0), stderr: Buffer.alloc(0)}; }; const T = ['t', 'time', 'at', 'start'], K = ['type', 'kind', 'name', 'event', 'sound']; const origPush = Array.prototype.push; Array.prototype.push = function () { for (let i = 0; i < arguments.length; i++) { const a = arguments[i]; if (a && typeof a === 'object' && !Array.isArray(a) && pushed.length < 20000) { let t = null, k = null; for (const key of T) if (typeof a[key] === 'number') { t = a[key]; break; } for (const key of K) if (typeof a[key] === 'string') { k = a[key]; break; } if (t !== null && k !== null) origPush.call(pushed, {t: t, type: k, g: a.gain !== undefined ? a.gain : a.g, len: a.len !== undefined ? a.len : a.dur}); } } return origPush.apply(this, arguments); }; const origCompile = Module.prototype._compile; Module.prototype._compile = function (content, filename) { const swap = cfg.swap[path.resolve(filename)]; if (swap) content = fs.readFileSync(swap, 'utf8'); return origCompile.call(this, content, filename); }; process.on('exit', function () { Array.prototype.push = origPush; realWrite.call(fs, cfg.out, JSON.stringify({events: ev, called: called, nested: nested, valued: valued, writes: writes, pushed: pushed})); }); """ def find_scripts(root): """Candidate synthesizer scripts of a project: JS files that write a WAV or a sample buffer.""" root = Path(root) out = [] for sub in SCRIPT_DIRS: d = root / sub if not d.is_dir(): continue depth0 = len(d.parts) for dp, dns, fns in os.walk(d): dns[:] = [x for x in dns if x not in SKIP and len(Path(dp, x).parts) - depth0 < 3] for fn in fns: if not fn.endswith((".cjs", ".js")): continue p = Path(dp) / fn try: if p.stat().st_size > 300_000: continue t = p.read_text(encoding="utf-8", errors="replace") except OSError: - skills/real-sfx/scripts/hear.py (23044 bytes)
#!/usr/bin/env python3 """A model that describes a sound in words, locally, on the CPU: MiDashengLM-0.6B (Xiaomi, Apache-2.0). python hear.py status python hear.py install --yes # ~3.1 GB: a venv of its own, the model at a pinned revision python hear.py describe FILE [--span T0 T1] [--ask "question"] [--tokens 80] python hear.py bench [--n 2] [--json OUT] # does it tell what we need told? library sounds + synthetic cases Why. Claude takes no audio in here. A caption model is a middleman: it turns a sound into words ("a short dry click, then a low hum") that can be read, compared and asked questions. It is small, it is not a person: it can be wrong, and the way to find out how wrong for THIS skill's questions is `bench`, which uses sounds whose truth is known (the category of a library sound, a bed that is there or is not, how many clicks, which of two is louder). Nothing is built into the critique before that answer is in. What `bench` showed (2026-10-15, this model, CPU, 1.3 s per answer after a 2 s load; 51 questions on known sounds): * what kind of sound: 12 of 27 right. Impacts and drums 3/3, glass 3/3, typing 2/3; whoosh, click, pop, riser 1/3 each, paper 0/3, ambience 0/3 (a bell for a room tone, a vacuum cleaner for a whoosh). Part of that is the library's own labels, part is the model. * is there a hum under the sounds (yes / no): 6 of 12 = chance, it answers "yes" to everything. * how many separate clicks: 0 of 6, it answers "1" to everything. Which of two is louder: 3 of 6 = chance, "first". * the same bed question as a caption (the task it was trained on): the caption of a dry sound never mentions a hum or a background (0 of 8), the caption of the same sound over a bed does in 3-4 of 8: no false alarms, and it misses more than half. Captions also invent things (a cat, a person speaking). So it is NOT an ear for what this skill needs told (is the bed there, how many, how loud against what): that is what measuring is for (the critique, the masking model). It can be a rough second opinion on WHAT a sound is, and it is not built into the critique. A larger model might do better on the category; counting and loudness are hard for any of them. Where it lives. `vendor/venv-audiolm` (torch CPU, transformers 4.57, numpy: not the skill's other venv) and `vendor/models/midashenglm-0.6b`, both left out of the package. REAL_SFX_AUDIOLM_HOME names another folder for them. The model's own python files run on load (trust_remote_code): the revision is pinned, the files were read, and their SHA-256 are in CODE_SHA256 below; the model is refused when one differs. It runs offline. """ import argparse import hashlib import json import os import random import subprocess import sys import tempfile from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import SKILL_DIR HOME = Path(os.environ.get("REAL_SFX_AUDIOLM_HOME") or (SKILL_DIR / "vendor")) VENV = HOME / "venv-audiolm" MODEL_DIR = HOME / "models" / "midashenglm-0.6b" REPO = "mispeech/midashenglm-0.6b-fp32" REVISION = "3969e451d1c62618089c1135fe4c58ed33af2457" # 2026-04-03 FILES = {"model.safetensors": 2748851080} # size in bytes CODE_FILES = ("configuration_midashenglm.py", "modeling_midashenglm.py", "processing_midashenglm.py") # the three python files of the model, READ IN FULL on 2026-10-15 (revision above): model definition, config and # processor; no network, no subprocess, no eval/exec, no pickle, no file writes, no environment reads CODE_SHA256 = { "configuration_midashenglm.py": "ca740ad2dd13be0deea2e76c418ffc06f5734b2a0e446b828ae421d100dce6d2", "modeling_midashenglm.py": "0d0b62bd987fea96785b963f91d89dc8a2661f16e7eb45e50ddbb9123adc238e", "processing_midashenglm.py": "926d1a81d60b4ba1f64a027719201e8cd08c4af808dc6c92bb4e0776b85ee1b4", } PIP_TORCH = ["torch==2.11.0", "torchaudio==2.11.0"] PIP_REST = ["transformers==4.57.6", "numpy", "huggingface_hub"] DEFAULT_ASK = "Describe this sound: what it is, how it starts and ends, whether it is dark or bright, clean or noisy. One or two sentences." def venv_py(): p = VENV / ("Scripts/python.exe" if os.name == "nt" else "bin/python") return p if p.exists() else None def sha256(p): return hashlib.sha256(Path(p).read_bytes()).hexdigest() def have_model(): return all((MODEL_DIR / f).exists() and (MODEL_DIR / f).stat().st_size == n for f, n in FILES.items()) and \ all((MODEL_DIR / f).exists() for f in CODE_FILES) def status(): print(f"audio-language model (MiDashengLM-0.6B, CPU): {'READY' if venv_py() and have_model() else 'not installed'}") print(f" venv : {'yes' if venv_py() else 'no'} {VENV}") print(f" model : {'yes' if have_model() else 'no'} {MODEL_DIR} ({REPO} @ {REVISION[:8]})") if have_model(): for f in CODE_FILES: h = sha256(MODEL_DIR / f) ok = CODE_SHA256.get(f) == h print(f" code : {f} {h[:16]} {'matches the reviewed file' if ok else 'NOT REVIEWED / CHANGED'}") if not (venv_py() and have_model()): print(f"\nTo install (about 3.1 GB: the model 2.75 GB, torch CPU 0.2 GB, the rest 0.1 GB):\n" f" python {Path(__file__).name} install --yes") def install(yes): if not yes: sys.exit("install downloads about 3.1 GB (the model 2.75 GB from huggingface.co, torch and transformers into a new " "venv); run again with --yes to confirm") if not venv_py(): print("creating the venv ...", flush=True) VENV.parent.mkdir(parents=True, exist_ok=True) subprocess.check_call([sys.executable, "-m", "venv", str(VENV)]) py = str(venv_py()) print("installing torch and torchaudio (CPU) ...", flush=True) subprocess.check_call([py, "-m", "pip", "install", "--disable-pip-version-check", "-q", "--index-url", "https://download.pytorch.org/whl/cpu"] + PIP_TORCH) print("installing transformers, numpy, huggingface_hub ...", flush=True) subprocess.check_call([py, "-m", "pip", "install", "--disable-pip-version-check", "-q"] + PIP_REST) print(f"downloading {REPO} @ {REVISION[:8]} ...", flush=True) code = ("from huggingface_hub import snapshot_download; " f"snapshot_download(repo_id={REPO!r}, revision={REVISION!r}, local_dir=r'{MODEL_DIR}', " "allow_patterns=['*.json','*.py','*.safetensors','*.jinja','merges.txt','vocab.json','LICENSE*'])") MODEL_DIR.parent.mkdir(parents=True, exist_ok=True) subprocess.check_call([py, "-c", code]) bad = [f for f, n in FILES.items() if not (MODEL_DIR / f).exists() or (MODEL_DIR / f).stat().st_size != n] if bad: sys.exit(f"the download is incomplete or not the expected files: {bad}") print("done. The model's own python files, to be read before the first run:") for f in CODE_FILES: print(f" {MODEL_DIR / f} sha256 {sha256(MODEL_DIR / f)}") print("then add the hashes to CODE_SHA256 in this script (or run with --trust-unreviewed once).") # ------------------------------------------------------------------------------------------------ run (in the venv) def run_jobs(jobs_path, out_path, trust_unreviewed): """Inside the venv: load the model once, answer every job. jobs: [{file, t0, t1, ask, tokens}] -> [{text, secs}].""" import time os.environ["HF_HUB_OFFLINE"] = "1" os.environ["TRANSFORMERS_OFFLINE"] = "1" for f in CODE_FILES: h = sha256(MODEL_DIR / f) if CODE_SHA256.get(f) != h and not trust_unreviewed: sys.exit(f"{f} is not the file that was read (sha256 {h[:16]}): not run. Read it, put the hash into " f"CODE_SHA256, or --trust-unreviewed.") import numpy as np import torch from transformers import AutoModelForCausalLM, AutoProcessor, AutoTokenizer t_load = time.time() model = AutoModelForCausalLM.from_pretrained(str(MODEL_DIR), trust_remote_code=True, local_files_only=True) model.eval() tok = AutoTokenizer.from_pretrained(str(MODEL_DIR), local_files_only=True) proc = AutoProcessor.from_pretrained(str(MODEL_DIR), trust_remote_code=True, local_files_only=True) sr = int(getattr(proc, "sampling_rate", None) or proc.feature_extractor.sampling_rate) load_s = time.time() - t_load def load_audio(path, t0, t1): cmd = ["ffmpeg", "-v", "error", "-nostdin"] if t0: cmd += ["-ss", f"{float(t0):.3f}"] cmd += ["-i", str(path)] if t1 is not None: cmd += ["-t", f"{max(0.1, float(t1) - float(t0 or 0)):.3f}"] cmd += ["-vn", "-ac", "1", "-ar", str(sr), "-f", "f32le", "-"] r = subprocess.run(cmd, capture_output=True) x = np.frombuffer(r.stdout, dtype="<f4").astype(np.float32).copy() return x[: sr * 60] # one minute is plenty for a question about a moment out = [] for j in json.loads(Path(jobs_path).read_text(encoding="utf-8")): t = time.time() x = load_audio(j["file"], j.get("t0"), j.get("t1")) if x.size < sr // 20: out.append({"text": "", "secs": 0.0, "error": "no audio"}) continue msgs = [{"role": "user", "content": [{"type": "text", "text": j.get("ask") or DEFAULT_ASK}, {"type": "audio", "audio": x}]}] with torch.no_grad(): inp = proc.apply_chat_template(msgs, tokenize=True, add_generation_prompt=True, add_special_tokens=True, return_dict=True).to(device=model.device, dtype=model.dtype) gen = model.generate(**inp, max_new_tokens=int(j.get("tokens") or 80), do_sample=False, repetition_penalty=1.05) n_in = inp["input_ids"].shape[1] if "input_ids" in inp else 0 text = tok.batch_decode(gen[:, n_in:] if gen.shape[1] > n_in else gen, skip_special_tokens=True)[0].strip() out.append({"text": text, "secs": round(time.time() - t, 1)}) Path(out_path).write_text(json.dumps({"load_s": round(load_s, 1), "answers": out}, ensure_ascii=False), encoding="utf-8") def ask_model(jobs, trust_unreviewed=False): """Run jobs through the model in the venv. -> list of {text, secs}.""" py = venv_py() if not py or not have_model(): sys.exit("the model is not installed: python hear.py install --yes") with tempfile.TemporaryDirectory() as td: jp, op = Path(td) / "jobs.json", Path(td) / "out.json" jp.write_text(json.dumps(jobs, ensure_ascii=False), encoding="utf-8") cmd = [str(py), str(Path(__file__).resolve()), "_run", str(jp), str(op)] + \ (["--trust-unreviewed"] if trust_unreviewed else []) r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", env=dict(os.environ, PYTHONUTF8="1", REAL_SFX_AUDIOLM_HOME=str(HOME))) if r.returncode or not op.exists(): sys.exit("the model did not run:\n" + (r.stderr or r.stdout)[-1500:]) return json.loads(op.read_text(encoding="utf-8")) # ------------------------------------------------------------------------------------------------ bench KEYWORDS = { "whoosh": ("whoosh", "swoosh", "swish", "air", "wind", "sweep", "swipe", "rush", "swipe", "movement"), "hit": ("hit", "impact", "thud", "boom", "punch", "slam", "knock", "bang", "thump", "drum", "explosion", "strike"), "click": ("click", "tick", "tap", "snap", "button", "switch", "pop", "beep"), "pop": ("pop", "bubble", "plop", "burst", "blip", "bloop", "drop", "water", "bubbl"), "glass": ("glass", "clink", "ring", "chime", "bell", "shatter", "crystal", "ping", "metal", "tinkl"), "paper": ("paper", "rustle", "crumple", "page", "crinkle", "foil", "fabric", "cloth", "scrap", "rub"), "typing": ("typing", "keyboard", "key", "type", "tap", "click", "typewriter"), "riser": ("rise", "riser", "swell", "build", "sweep", "whoosh", "tension", "increas", "crescendo", "sci"), "ambience": ("hum", "drone", "ambient", "noise", "rumble", "room", "wind", "background", "static", "hiss", "engine", "tone", "buzz"), } def ffmpeg(args): r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-nostdin"] + [str(a) for a in args], capture_output=True, text=True) if r.returncode: raise RuntimeError(r.stderr[-300:]) def bench(n, json_out, trust_unreviewed): from picker import load_index index = [s for s in load_index() if s.get("tier", "main") == "main"] rnd = random.Random(7) td = Path(tempfile.mkdtemp(prefix="hear_bench_")) items = [] # {kind, truth, file, ask, check} # A: what kind of sound is this (the category of the library) for role, words in KEYWORDS.items(): pool = [s for s in index if s.get("role") == role and 0.25 <= (s.get("active_dur") or s.get("duration") or 0) <= 4.0 and Path(s["path"]).exists()] for s in rnd.sample(pool, min(n, len(pool))): items.append({"kind": "category", "truth": role, "file": s["path"], "name": s.get("name", ""), "ask": "What kind of sound is this? Answer in one short sentence.", "words": list(words)}) # B: a bed under short sounds, there or not shorts = [s for s in index if s.get("role") in ("click", "pop", "glass") and 0.1 <= (s.get("active_dur") or 0) <= 1.0 and Path(s["path"]).exists()] beds = [s for s in index if s.get("role") == "ambience" and (s.get("centroid") or 9e9) < 400 and Path(s["path"]).exists()] for k, s in enumerate(rnd.sample(shorts, min(2 * n, len(shorts)))): base = td / f"b{k}_dry.wav" ffmpeg(["-i", s["path"], "-af", "apad=whole_dur=4,atrim=end=4", "-ac", "2", "-ar", "16000", base]) items.append({"kind": "bed", "truth": "no", "file": str(base), "ask": "Is there a continuous low hum or rumble under the sounds? Answer yes or no."}) if beds: b = rnd.choice(beds) wet = td / f"b{k}_wet.wav" ffmpeg(["-i", s["path"], "-stream_loop", "-1", "-i", b["path"], "-filter_complex", "[0:a]apad=whole_dur=4,atrim=end=4,aformat=channel_layouts=stereo[a];" "[1:a]atrim=end=4,aformat=channel_layouts=stereo,volume=-14dB[b];[a][b]amix=inputs=2:normalize=0", "-ar", "16000", wet]) items.append({"kind": "bed", "truth": "yes", "file": str(wet), "ask": "Is there a continuous low hum or rumble under the sounds? Answer yes or no."}) # C: how many separate clicks clicks = [s for s in index if s.get("role") == "click" and 0.03 <= (s.get("active_dur") or 0) <= 0.3 and Path(s["path"]).exists()] for k in range(n * 2): cnt = 2 + k % 4 s = rnd.choice(clicks - skills/real-sfx/scripts/learn_style.py (17981 bytes)
#!/usr/bin/env python3 """Learn a sound-design style from finished reference videos. python learn_style.py refs.txt --name my-style # refs.txt: one video path per line python learn_style.py a.mp4 b.mp4 c.mp4 --name punchy refs.txt line with an SFX-only stem: C:/refs/launch.mp4 | C:/refs/launch_sfx_only.wav refs.txt line with a picture region: C:/refs/reel.mp4 | | 0,0.05,1,0.5 (x0,y0,x1,y1 as fractions: a reel with the After Effects timeline under the animation; stem may stay empty) Writes styles/<name>.json and prints a readable summary. The file also carries `measures` (median and range over the references of the numbers `refstyle.py` / `critique.py --style NAME` set a film against: gestures per 10 s, gaps, level spread, low end, sub bed, loudness). For every reference it measures, from the finished mix, using the same frame analysis as find_moments.py: * how many sound events per 10 s, and how many of them sit on a picture event (cut/burst/onset/settle) * where a sound's loudest point lands relative to the picture event (lead_ms; negative = sound first) * how often a cut carries a low-end impact (hit + sub layering) * hook: is there a sound in the first 2 s; longest silent gap * loudness and dynamic range of the whole mix * character of the sounds on each kind of picture event (brightness, attack, low-end, noisiness) Limits, stated honestly: the reference mix contains music, so "sound events" are anything that rises sharply above the surrounding level: SFX but also music hits. Timing and density are reliable; "which exact sound it is" is only approximated by its measured character. """ import argparse import json import math import statistics import subprocess import sys import array from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import SKILL_DIR, avg_power, character_from_power from find_moments import probe, visual_moments RATE = 16000 def decode(video, af=None): cmd = ["ffmpeg", "-v", "error", "-nostdin", "-i", str(video), "-vn", "-ac", "1", "-ar", str(RATE)] if af: cmd += ["-af", af] r = subprocess.run(cmd + ["-f", "s16le", "-"], capture_output=True) a = array.array("h") a.frombytes(r.stdout[: len(r.stdout) // 2 * 2]) return a def env_db(x, ms=10): w = RATE * ms // 1000 out = [] for i in range(0, len(x) - w + 1, w): e = math.sqrt(sum(v * v for v in x[i:i + w]) / w) / 32768.0 out.append(20 * math.log10(e) if e > 1e-5 else -100.0) return out def local_base(env, i, back=40, gap=5): seg = env[max(0, i - back):max(0, i - gap)] return statistics.median(seg) if seg else env[i] def audio_events(env, lo_env, min_rise=9.0, floor=-48.0): """Sharp rises above the recent level. Returns events with the time of their loudest point.""" ev, last = [], -99 n = len(env) for i in range(6, n - 6): if env[i] < floor: continue rise = env[i] - local_base(env, i) if rise < min_rise: continue window = env[i - 5:i + 6] if env[i] < max(window): continue # not the local peak if i - last < 12: # 120 ms spacing if ev and env[i] > ev[-1]["level"]: ev.pop() else: continue # when did the rise start? walk back until 10 dB below the peak j = i while j > 0 and env[j] > env[i] - 10 and i - j < 80: j -= 1 lo_rise = lo_env[i] - local_base(lo_env, i) if i < len(lo_env) else 0.0 ev.append({"i": i, "t": round(i * 0.01, 3), "rise": round(rise, 1), "level": env[i], "build_ms": (i - j) * 10, "lo_rise": round(lo_rise, 1)}) last = i return ev def median(v, default=None): v = [x for x in v if x is not None] return round(statistics.median(v), 3) if v else default def merge_events(hi, lo): """Combine high-band and low-band events; a sound with both is an impact with air on top.""" out = [] for e in hi: out.append(dict(e, band="hi")) for e in lo: mate = next((o for o in out if abs(o["t"] - e["t"]) <= 0.06), None) if mate: mate["band"] = "both" mate["lo_rise"] = e["rise"] else: out.append(dict(e, band="lo", lo_rise=e["rise"])) for e in out: e.setdefault("lo_rise", 0.0) return sorted(out, key=lambda e: e["t"]) BANDS = (("sub", 20, 120), ("low", 120, 400), ("mid", 400, 2000), ("high", 2000, 7500)) def band_db(power, n=1024, rate=16000): hz = rate / n return {name: 10 * math.log10(sum(p for k, p in enumerate(power) if lo <= k * hz < hi) + 1e-6) for name, lo, hi in BANDS} def added_character(full, t): """What the event adds, per frequency band, in dB above the sound just before it. The music keeps playing under the event, so a band that did not change shows ~0 dB and the bands that jump are the sound effect: sub +15 = impact, high +10 = air/whoosh/click.""" bg = avg_power(full[max(0, int((t - 0.7) * RATE)):max(0, int((t - 0.15) * RATE))]) ev = avg_power(full[max(0, int((t - 0.05) * RATE)):int((t + 0.40) * RATE)]) if not bg or not ev: return None b0, b1 = band_db(bg), band_db(ev) # against silence (an SFX-only stem) the difference is meaningless and huge: cap it return {f"d_{k}": round(max(-40.0, min(40.0, b1[k] - b0[k])), 1) for k in b0} def analyse(video, stem=None, roi=None): """stem: an audio file with ONLY the sound effects (no music) for this video; far more reliable. roi: (x0, y0, x1, y1) as fractions of the picture: look only there (a reel with the After Effects timeline under the animation: the timeline's own movement is not a picture event). Cuts are not searched inside a region.""" info = probe(video) dur = info["duration"] roi_px = None if roi: w_, h_ = info["width"], info["height"] x0, y0, x1, y1 = roi roi_px = (int(x0 * w_) // 2 * 2, int(y0 * h_) // 2 * 2, max(2, int((x1 - x0) * w_) // 2 * 2), max(2, int((y1 - y0) * h_) // 2 * 2)) moments, act = visual_moments(video, max_other=60, roi=roi_px) src = stem or video full = decode(src) hi_env = env_db(decode(src, "highpass=f=400")) lo_env = env_db(decode(src, "lowpass=f=150")) ev = merge_events(audio_events(hi_env, lo_env, min_rise=9.0, floor=-55.0), audio_events(lo_env, lo_env, min_rise=10.0, floor=-45.0)) rows, used = [], set() for m in moments: best = None for k, e in enumerate(ev): d = (e["t"] - m["t"]) * 1000 if -200 <= d <= 200 and (best is None or abs(d) < abs(best[0])): best = (d, k) row = {"t": m["t"], "kind": m["kind"], "strength": m["strength"], "matched": best is not None} if best: d, k = best e = ev[k] used.add(k) row.update({"lead_ms": round(d), "band": e["band"], "rise": e["rise"], "build_ms": e["build_ms"]}) ch = added_character(full, e["t"]) if ch: row.update(ch) rows.append(row) # chance level: how often a sound peak sits within +-200 ms of a picture event that is NOT there etimes = [e["t"] for e in ev] def hit(t): return any(abs(x - t) <= 0.2 for x in etimes) shifts = (-1.1, -0.6, 0.6, 1.1) chance_n = chance_hit = 0 for m in moments: for sh in shifts: t2 = m["t"] + sh if 0.2 < t2 < dur - 0.2: chance_n += 1 chance_hit += hit(t2) times = [e["t"] for e in ev] gaps = [b - a for a, b in zip([0.0] + times, times + [dur])] sec = [20 * math.log10(max(1e-5, math.sqrt(sum(v * v for v in full[i:i + RATE]) / RATE) / 32768)) for i in range(0, max(1, len(full) - RATE), RATE)] sec = [x for x in sec if x > -60] per10 = lambda n: round(n / dur * 10, 2) def rate(sel): r = [x for x in rows if sel(x)] return (round(sum(1 for x in r if x["matched"]) / len(r), 2), len(r)) if r else (None, 0) # the numbers `critique.py --style` and `refstyle.py` compare a film with (same code on both sides) measures = {} try: import refstyle from common import measure_loudness measures = refstyle.measure(src, lufs=measure_loudness(video).get("lufs")) except Exception as ex: # the older numbers above are still worth keeping print(f" measures failed: {ex}", file=sys.stderr) return { "video": str(video), "duration": round(dur, 1), "w": info["width"], "h": info["height"], "roi": list(roi) if roi else None, "measures": measures, "visual_per10": per10(len(moments)), "events_per10": per10(len(ev)), "synced_per10": per10(len(used)), "free_events_per10": per10(len(ev) - len(used)), "hook": any(t <= 2.0 for t in times), "first_event_s": times[0] if times else None, "max_gap_s": round(max(gaps), 1), "median_gap_s": round(statistics.median(gaps), 2), "mean_db": round(statistics.mean(sec), 1) if sec else None, "dyn_range_db": round(sorted(sec)[int(0.9 * (len(sec) - 1))] - sorted(sec)[int(0.1 * (len(sec) - 1))], 1) if len(sec) > 3 else None, "band_mix": {b: sum(1 for e in ev if e["band"] == b) for b in ("hi", "lo", "both")}, "motion_activity": round(act, 2), "chance_hits": chance_hit, "chance_n": chance_n, "rows": rows, "stem": str(stem) if stem else None, } def aggregate(per_ref): out = {} for key in ("visual_per10", "events_per10", "synced_per10", "free_events_per10", "max_gap_s", "median_gap_s", "mean_db", "dyn_range_db"): out[key] = median([r[key] for r in per_ref]) out["hook_rate"] = round(sum(1 for r in per_ref if r["hook"]) / len(per_ref), 2) # pool all picture events so strong ones are judged over hundreds of samples, not over 13 medians rows = [x for r in per_ref for x in r["rows"]] out["n_picture_events"] = len(rows) cn, ch = sum(r["chance_n"] for r in per_ref), sum(r["chance_hits"] for r in per_ref) obs = sum(1 for x in rows if x["matched"]) / max(1, len(rows)) out["chance_rate"] = round(ch / cn, 2) if cn else None out["observed_rate"] = round(obs, 2) # share of picture events that really carry their own sound = (obs - chance) / (1 - chance) out["lift_rate"] = round(max(0.0, (obs - out["chance_rate"]) / (1 - out["chance_rate"])), 2) if cn else None sb = {} for name, lo, hi in (("weak<0.4", 0, 0.4), ("mid", 0.4, 0.7), ("strong>=0.7", 0.7, 1.01)): r = [x for x in rows if lo <= x["strength"] < hi] sb[name] = {"n": len(r), "sync_rate": round(sum(x["matched"] for x in r) / len(r), 2) if r else None} out["sync_by_strength"] = sb kinds = {} for k in ("cut", "burst", "onset", "settle"): r = [x for x in rows if x["kind"] == k] got = [x for x in r if x["matched"]] if not r: continue strong = [x for x in r if x["strength"] >= 0.7] leads = [x["lead_ms"] for x in got] kinds[k] = { "n": len(r), "sync_rate": round(len(got) / len(r), 2), "strong_sync_rate": round(sum(x["matched"] for x in strong) / len(strong), 2) if strong else None, "lead_ms": median(leads), "lead_p25": round(statistics.quantiles(leads, n=4)[0]) if len(leads) >= 4 else None, "lead_p75": round(statistics.quantiles(leads, n=4)[2]) if len(leads) >= 4 else None, "lo_share": round(sum(1 for x in got if x["band"] in ("lo", "both")) / len(got), 2) if got else None, "d_sub": median([x.get("d_sub") for x in got]), "d_low": median([x.get("d_low") for x in got]), "d_mid": median([x.get("d_mid") for x in got]), "d_high": median([x.get("d_high") for x in got]), "build_ms": median([x["build_ms"] for x in got]), "within60": round(sum(1 for l in leads if abs(l) <= 60) / len(leads), 2) if leads else None, } out["kinds"] = kinds bands = {"hi": 0, "lo": 0, "both": 0} for r in per_ref: for b in bands: bands[b] += r["band_mix"][b] out["band_mix"] = bands return out def main(): ap = argparse.ArgumentParser() ap.add_argument("videos", nargs="+", help="video files, or one text file with a path per line") ap.add_argument("--name", required=True) a = ap.parse_args() paths = [] for v in a.videos: p = Path(v) if p.suffix.lower() in (".txt", ".list"): paths += [l.strip() for l in p.read_text(encoding="utf-8-sig").splitlines() # a PowerShell BOM is fine if l.strip() and not l.strip().startswith("#")] else: paths.append(v) per_ref = [] for i, line in enumerate(paths, 1): # "video.mp4 | sfx_only.wav | 0,0.05,1,0.5": the stem and the picture region (fractions x0,y0,x1,y1) are optional parts = [x.strip() for x in line.split("|")] p, stem = parts[0], (parts[1] if len(parts) > 1 else "") roi = None if len(parts) > 2 and parts[2]: try: roi = tuple(float(v) for v in parts[2].split(",")) if len(roi) != 4 or not (0 <= roi[0] < roi[2] <= 1 and 0 <= roi[1] < roi[3] <= 1): raise ValueError if roi == (0.0, 0.0, 1.0, 1.0): roi = None # the whole picture: cuts are searched as usual except ValueError: print(f"skip (region must be x0,y0,x1,y1 as fractions): {line}", file=sys.stderr) continue if not Path(p).exists() or (stem and not Path(stem).exists()): print(f"skip (missing): {line}", file=sys.stderr) continue print(f"[{i}/{len(paths)}] {Path(p).name[:70]}{' (with SFX stem)' if stem else ''}" f"{' (region ' + str(roi) + ')' if roi else ''}", flush=True) try: per_ref.append(analyse(p, stem or None, roi)) except Exception as ex: # one broken file must not lose the others print(f" failed: {ex}", file=sys.stderr) if not per_ref: sys.exit("no reference could be analysed") style = {"name": a.name, "n_refs": len(per_ref), "profile": aggregate(per_ref), "per_ref": per_ref} try: import refstyle style["measures"] = refstyle.aggregate([r.get("meas - skills/real-sfx/scripts/levels.py (7358 bytes)
#!/usr/bin/env python3 """How loud is each new sound against the synthesized sound it replaces? (the author's own balance, event by event) The layer match brings the WHOLE new layer to the integrated loudness of the old one. It cannot see that the ticks came out 8 dB too loud and the bells 4 dB too quiet, or that typing stands 17 dB over the author's. This reads the momentary loudness (BS.1770, 400 ms, K-weighted, every 100 ms) of both layers around every event and says, per event, how far the new sound is from the one the author mixed once the average offset is taken out. python levels.py RESOLVED.json SFX_TRACK.wav [--reference FILE ...] [--json OUT.json] Importable: compare(cues, ref_files, new_track) -> (rows, overall_offset_db); edits(rows) -> a batch for sheet.py apply. The reference is the synthesized layer the mix replaced: the stems from_cues subtracted (`_draft.reference_layer` of the sheet) or the effects-only render of the project's script. Its gain inside the mix does not matter: only the differences between events count. """ import argparse import bisect import json import math import re import statistics import subprocess import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import load_json SILENT = -60.0 def momentary(path): """[(t, M LUFS)] every 100 ms: the loudness of the 400 ms that ENDS at t. Silence is -200.""" r = subprocess.run(["ffmpeg", "-hide_banner", "-nostats", "-nostdin", "-i", str(path), "-vn", "-af", "ebur128=framelog=info", "-f", "null", "-"], capture_output=True, text=True, errors="replace") out = [] for m in re.finditer(r"t:\s*([\d.]+)\s+TARGET:\s*-?\d+\s+LUFS\s+M:\s*(-?[\d.]+|-inf)", r.stderr): v = -200.0 if m.group(2) == "-inf" else float(m.group(2)) out.append((float(m.group(1)), max(-200.0, v))) return out def combine(series_list, gains_db=None): """Energy sum of several momentary series on their common 100 ms grid (a layer made of several stems).""" acc = {} for k, s in enumerate(series_list): g = (gains_db or [0.0] * len(series_list))[k] for t, v in s: key = round(t * 10) acc[key] = acc.get(key, 0.0) + (10 ** ((v + g) / 10.0) if v > -150 else 0.0) return [(k / 10.0, 10 * math.log10(e) if e > 0 else -200.0) for k, e in sorted(acc.items())] def level_in(series, t0, t1): """The loudest momentary value of the windows that contain the first 100 ms .. 0.5 s after the event began.""" if not series: return None ts = [t for t, _ in series] i0 = bisect.bisect_left(ts, t0 + 0.1) i1 = bisect.bisect_right(ts, t1 + 0.5) vals = [v for _, v in series[i0:i1]] return max(vals) if vals else None def groups(cues, run_gap=0.3, layer_gap=0.08): """Events as a listener hears them: a run of the same kind (typing, ticks) and the layers of one moment are one group. [{t0, t1, kind, n}]. A texture sound (texture.py) has no sound of the author's to be matched against.""" main = sorted((c for c in cues if not c.get("_layer") and not c.get("texture")), key=lambda c: c["t"]) def kind_of(c): w = str(c.get("label", "")).split() return (w[0] if w else c.get("role") or "?").lower() out = [] for c in main: k = kind_of(c) g = out[-1] if out else None if g and ((k == g["kind"] and c["t"] - g["t1"] <= run_gap) or c["t"] - g["t1"] <= layer_gap): g["t1"] = max(g["t1"], c["t"]) g["n"] += 1 else: out.append({"t0": c["t"], "t1": c["t"], "kind": k, "n": 1}) return out def compare(cues, ref_files, new_track, ref_gains_db=None): """Rows [{t0, t1, kind, n, ref, new, d, e}] and the overall offset D (median of d: how much quieter, in dB, the new layer is than the old one on average). e = d - D: what this event is off, once the average is taken out (positive: the new sound is too quiet against the author's balance, negative: too loud).""" ref = combine([momentary(f) for f in ref_files], ref_gains_db) new = momentary(new_track) rows = [] for g in groups(cues): lr, ln = level_in(ref, g["t0"], g["t1"]), level_in(new, g["t0"], g["t1"]) if lr is None or ln is None or lr < SILENT or ln < SILENT: continue rows.append(dict(g, ref=round(lr, 1), new=round(ln, 1), d=round(lr - ln, 1))) if not rows: return [], 0.0 D = statistics.median(r["d"] for r in rows) for r in rows: r["e"] = round(r["d"] - D, 1) return rows, round(D, 1) def edits(rows, min_db=1.5, max_db=8.0): """A batch for `sheet.py apply`: the gain that brings every group that is off by min_db or more to the author's balance (clamped to max_db).""" ops = [] for r in rows: if abs(r["e"]) < min_db: continue g = round(max(-max_db, min(max_db, r["e"])) * 2) / 2.0 if g == 0: continue sel = {"label": r["kind"]} if r["n"] > 1: sel["between"] = [round(r["t0"] - 0.01, 3), round(r["t1"] + 0.01, 3)] else: sel["at"] = round(r["t0"], 3) ops.append(dict(sel, gain=g)) return ops def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("cues") ap.add_argument("track") ap.add_argument("--reference", nargs="+", help="the synthesized layer (default: _draft.reference_layer of the sheet)") ap.add_argument("--json", help="write the batch for sheet.py apply here") ap.add_argument("--min-db", type=float, default=1.5) ap.add_argument("--max-db", type=float, default=8.0) a = ap.parse_args() sheet = load_json(a.cues) ref = a.reference or (sheet.get("_draft") or {}).get("reference_layer") or [] ref = [f for f in ref if Path(f).exists()] if not ref: sys.exit("no reference: the synthesized layer the sounds replace is not known for this sheet (from_cues " "records it when it took the layer out; or give --reference FILE ...)") rows, D = compare(sheet["cues"], ref, a.track) if not rows: sys.exit("no event could be compared (silent in one of the two layers)") print(f"{len(rows)} events; the new layer is {D:+.1f} dB against the replaced one on average " f"(the layer match / master decide that; below is each event against that average)") by = {} for r in rows: by.setdefault(r["kind"], []).append(r["e"]) print(f"{'kind':14s} {'events':>6} {'median':>7} {'worst':>7} (e > 0: the new sound is too quiet against the author's)") for k, es in sorted(by.items(), key=lambda kv: -abs(statistics.median(kv[1]))): worst = max(es, key=abs) print(f"{k[:14]:14s} {len(es):6d} {statistics.median(es):+7.1f} {worst:+7.1f}") ops = edits(rows, a.min_db, a.max_db) if a.json: Path(a.json).parent.mkdir(parents=True, exist_ok=True) Path(a.json).write_text(json.dumps(ops, indent=1), encoding="utf-8") print(f"{len(ops)} event(s) are off by {a.min_db:g} dB or more" + (f": batch written to {a.json} -> sheet.py apply SHEET {a.json}, render again" if a.json and ops else ("" if ops else ": the balance is the author's"))) return 0 if __name__ == "__main__": sys.exit(main()) - skills/real-sfx/scripts/listen_page.py (58669 bytes)
#!/usr/bin/env python3 """A listening page: the person's ears, made cheap. Versions of a film to compare blind, and the moments the critique sends the ear to, each with a question and a verdict in one tap; the answers land in a file this skill can read. python listen_page.py build OUT --ab "bed on or off" without.mp4 with.mp4 [--ab LABEL V1 V2 [V3 ..]] ... [--moments FILM.mp4 --critique RESOLVED.json TRACK.wav | --list LIST.json] [--rate-plan PLAN.json] # sounds to rate one by one (taste_test.py page) [--title T] [--labels "without a bed" "with a bed"] [--picture-height 720] # a picture shared by the versions is shown this tall at most python listen_page.py serve OUT [--port 8765] [--lan] [--open] python listen_page.py results OUT [--log] Why. The skill measures and cannot hear. What it can do is to ask the one pair of ears there is a precise question and to keep the answer. A pair is shown as "1" and "2" in a random order (the key stays in the manifest), the picture is the same, you switch the sound without stopping. A moment is a 3 s piece of the film with the question of the critique's listen list. Verdicts are saved on every tap (POST to this script's own tiny server, or a download when the page is opened from a file), and `results` unblinds them: which version won, which tags it got. `--log` appends a run to `listening_log.json` of the skill (personal, never packaged): the data to calibrate the numbers against. Versions of a film that differ in sound only (the video streams are byte-identical, which `build` checks) are built as ONE picture, no taller than --picture-height, and the sound of each version beside it: the page plays them all together and the one heard is the one not muted, so a switch is instant and no video is decoded twice. (Two copies of a 1080p60 film, one of them hidden, stalled in the browser and were re-seeked every 250 ms: the page stuttered on version 2.) Versions with pictures of their own play one at a time, and a switch is a seek. `serve --lan` makes the page reachable from a phone on the same network (the critique asks for one listen on a phone speaker). The server serves only the folder it was given and writes only verdicts.json there. """ import argparse import html import json import mimetypes import random import shutil import socket import subprocess import sys import threading import time import urllib.parse from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import SKILL_DIR VIDEO = (".mp4", ".mov", ".m4v", ".webm", ".mkv") AUDIO = (".wav", ".mp3", ".m4a", ".flac", ".ogg", ".aac") LOG = SKILL_DIR / "listening_log.json" MOMENT_VERDICTS = ["ok", "loud", "masked", "harsh", "extra", "missing"] TAGS = ["offtheme", "quiet", "masked", "loud", "heavy", "voice", "empty", "harsh", "distracting", "synthetic", "hum", "noise", "early", "late", "good"] LOOP_UNDER = 8.0 # a comparison of clips shorter than this loops by itself PICTURE_HEIGHT = 720 # the picture the versions of a pair share is shown this tall at most (0 = as it is) # a sound rated on its own in a picture (taste_test.py): the verdict, the reasons, where it would fit better RATE_VERDICTS = [{"key": "love", "label": "👍 Класс"}, {"key": "ok", "label": "👌 Нормально"}, {"key": "notfit", "label": "↔ Не здесь"}, {"key": "never", "label": "🚫 Не брать"}] RATE_REASONS = [{"key": "harsh", "label": "резкий"}, {"key": "dull", "label": "глухой / тусклый"}, {"key": "long", "label": "слишком длинный"}, {"key": "short", "label": "слишком короткий"}, {"key": "loud", "label": "громкий"}, {"key": "quiet", "label": "тихий"}, {"key": "dirty", "label": "грязный / шумный"}, {"key": "synthetic", "label": "синтетика"}, {"key": "cliche", "label": "заезженный"}, {"key": "sync", "label": "не попал в картинку"}] RATE_CONTEXTS = [{"key": "click", "label": "клик / нажатие"}, {"key": "appear", "label": "появление элемента"}, {"key": "transition", "label": "переход / свайп"}, {"key": "impact", "label": "удар / акцент"}, {"key": "success", "label": "успех / подтверждение"}, {"key": "build", "label": "нарастание"}, {"key": "typing", "label": "ввод текста"}, {"key": "error", "label": "ошибка / предупреждение"}, {"key": "ambience", "label": "фон / атмосфера"}] # what the person can mark WHILE an adjust excerpt plays (a tap logs the time of the loop) ADJUST_MARKS = [{"key": "loud", "label": "громко"}, {"key": "harsh", "label": "резко"}, {"key": "extra", "label": "лишнее"}, {"key": "missing", "label": "не хватает"}, {"key": "off", "label": "не в тему"}] # ------------------------------------------------------------------------------------------------ build def kind_of(path): return "video" if str(path).lower().endswith(VIDEO) else "audio" def duration_of(path): """Seconds of a media file by ffprobe, 0.0 when it cannot be told.""" try: r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)], capture_output=True, text=True, errors="replace") return float(r.stdout.strip().splitlines()[0]) except (OSError, ValueError, IndexError): return 0.0 def probe_stream(path, fields, stream="v:0"): """Fields of the first video (or audio) stream by ffprobe, as a dict; {} when it cannot be told.""" try: r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", stream, "-show_entries", f"stream={fields}", "-of", "json", str(path)], capture_output=True, text=True, errors="replace") return (json.loads(r.stdout).get("streams") or [{}])[0] except (OSError, ValueError, IndexError): return {} def video_md5(path): """MD5 of the packets of the first video stream (copied, not decoded): files with the same picture share it.""" try: r = subprocess.run(["ffmpeg", "-v", "error", "-nostdin", "-i", str(path), "-map", "0:v:0", "-c", "copy", "-f", "md5", "-"], capture_output=True, text=True, errors="replace") except OSError: return "" last = (r.stdout.strip().splitlines() or [""])[-1] return last[4:] if r.returncode == 0 and last.startswith("MD5=") else "" def make_picture(src, dst, height=PICTURE_HEIGHT): """The picture of a film without its sound: copied as it is when it is no taller than `height`, else scaled down (a 1080p60 decode drops frames in a browser pane, and the page shows it a few hundred pixels wide), with a key frame every half second so that a seek costs little. The frames keep their times.""" h = int(probe_stream(src, "height").get("height") or 0) if height and h > height: v = ["-vf", f"scale=-2:{int(height)}", "-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-pix_fmt", "yuv420p", "-g", "30", "-fps_mode", "passthrough"] else: v = ["-c:v", "copy"] r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-nostdin", "-i", str(src), "-map", "0:v:0", "-an", *v, "-movflags", "+faststart", str(dst)], capture_output=True, text=True, errors="replace") return r.returncode == 0 and Path(dst).exists() def extract_audio(src, dst): """The sound of a film alone, as .m4a: its AAC stream copied (nothing is encoded twice), else encoded to AAC.""" codec = probe_stream(src, "codec_name", "a:0").get("codec_name", "") if not codec: return False a = ["-c:a", "copy"] if codec == "aac" else ["-c:a", "aac", "-b:a", "192k"] r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-nostdin", "-i", str(src), "-map", "0:a:0", "-vn", *a, "-movflags", "+faststart", str(dst)], capture_output=True, text=True, errors="replace") return r.returncode == 0 and Path(dst).exists() def cut_moment(src, t, out, dur=3.0, pre=1.0): """A 3 s piece of the film around a moment, picture and sound, small enough to play at once.""" t0 = max(0.0, float(t) - pre) if kind_of(src) == "video": cmd = ["ffmpeg", "-v", "error", "-y", "-nostdin", "-ss", f"{t0:.3f}", "-t", f"{dur:.3f}", "-i", str(src), "-c:v", "libx264", "-preset", "veryfast", "-crf", "24", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "160k", "-movflags", "+faststart", str(out)] else: cmd = ["ffmpeg", "-v", "error", "-y", "-nostdin", "-ss", f"{t0:.3f}", "-t", f"{dur:.3f}", "-i", str(src), "-c:a", "aac", "-b:a", "160k", str(out)] r = subprocess.run(cmd, capture_output=True, text=True, errors="replace") return r.returncode == 0 and Path(out).exists() def moments_from(args): if args.list: d = json.loads(Path(args.list).read_text(encoding="utf-8-sig")) return d.get("listen", d) if isinstance(d, dict) else d res, trk = args.critique r = subprocess.run([sys.executable, str(Path(__file__).parent / "critique.py"), res, trk, "--json"], capture_output=True, text=True, encoding="utf-8", errors="replace") for line in reversed(r.stdout.strip().splitlines()): if line.startswith("{"): return json.loads(line).get("listen", []) sys.exit("critique.py gave no JSON: " + (r.stderr or r.stdout)[-300:]) def build(a): out = Path(a.out) media = out / "media" media.mkdir(parents=True, exist_ok=True) rnd = random.Random(a.seed if a.seed is not None else time.time_ns()) items = [] for n, spec in enumerate(a.ab or [], 1): label, files = spec[0], spec[1:] if len(files) < 2: sys.exit(f"--ab {label!r}: at least two versions") question, own = a.question, None if " ## " in label: # "title ## the question of this pair [## name 1 | name 2 | ...]" parts = [x.strip() for x in label.split(" ## ")] label, question = parts[0], parts[1] if len(parts) > 2: own = [x.strip() for x in parts[2].split(" | ")] # several --labels sets may be given (4 versions here, 2 there): the one that fits the number of versions sets = [s for s in (a.labels or []) if len(s) == len(files)] names = (own if own and len(own) == len(files) else sets[0] if sets else [f"version {i}" for i in range(1, len(files) + 1)]) for f in files: if not Path(f).exists(): sys.exit(f"not found: {f}") vers, picture = [], None # versions of one film that differ in sound only: ONE picture and the sound of each, played together if all(kind_of(f) == "video" for f in files) and not a.separate_pictures: sums = [video_md5(f) for f in files] if sums[0] and len(set(sums)) == 1: pic = media / f"ab{n}_pic.mp4" snd = [media / f"ab{n}_v{i + 1}.m4a" for i in range(len(files))] if make_picture(files[0], pic, a.picture_height) and all(extract_audio(f, d) for f, d in zip(files, snd)): picture = f"media/{pic.name}" vers = [{"label": names[i], "file": f"media/{d.name}", "kind": "audio"} for i, d in enumerate(snd)] else: for p in [pic, *snd]: p.unlink(missing_ok=True) if not vers: # pictures of their own (or sounds only): the files as they are for i, f in enumerate(files): dst = media / f"ab{n}_v{i + 1}{Path(f).suffix.lower()}" shutil.copyfile(f, dst) vers.append({"label": names[i], "file": f"media/{dst.name}", "kind": kind_of(f)}) order = list(range(len(vers))) rnd.shuffle(order) short = 0.0 < duration_of(files[0]) <= LOOP_UNDER items.append({"id": f"ab{n}", "kind": "ab", "title": label, "versions": vers, "order": order, "loop": short, **({"picture": picture} if picture else {}), "question": question or ("Какая звучит лучше? Картинка одна, различается звук: " "переключайте 1 / 2 на ходу.")}) if a.moments: listen = moments_from(a) if not listen: print("the critique has no listen list for this film: no moments added") for k, m in enumerate(listen, 1): dst = media / f"m{k}{'.mp4' if kind_of(a.moments) == 'video' else '.m4a'}" if not cut_moment(a.moments, m["t"], dst): print(f"moment {k} ({m['t']} s) could not be cut", file=sys.stderr) continue lab = (m.get("label") or "").strip() items.append({"id": f"m{k}", "kind": "moment", "title": f"{float(m['t']):.2f} с" + (f", «{lab}»" if lab else ""), "versions": [{"label": "film", "file": f"media/{dst.name}", "kind": kind_of(dst)}], "order": [0], "why": m.get("why", ""), "question": m.get("ask", "")}) sections, rate_ctx = [], RATE_CONTEXTS if a.rate_plan: plan = json.loads(Path(a.rate_plan).read_text(encoding="utf-8-sig")) rate_ctx = plan.get("contexts") or RATE_CONTEXTS base = Path(a.rate_plan).parent n_r = 0 for sec in plan.get("sections", []): first = len(items) for k, it in enumerate(sec.get("items", []), 1): f = Path(it["file"]) f = f if f.is_absolute() else base / f if not f.exists(): sys.exit(f"not found: {f}") n_r += 1 dst = media / f"r{n_r}{f.suffix.lower()}" shutil.copyfile(f, dst) items.append({"id": f"r{n_r}", "kind": "rate", "section": sec["id"], "title": f"{sec['title']}: {k} из {len(sec['items'])}", "versions": [{"label": "sound", "file": f"media/{dst.name}", "kind": kind_of(f)}], "order": [0], "loop": True, "question": sec.get("question", ""), "why": sec.get("about", ""), "meta": it.get("meta", {})}) sections.append({"id": sec["id"], "title": sec["title"], "first": first, "n": len(items) - first}) if a.adjust_plan: # levels set by ear on a looping excerpt (adjust_test.py) plan = json.loads(Path(a.adjust_plan).read_text(encoding="utf-8-sig")) base = Path(a.adjust_plan).parent def put(rel, name): f = Path(rel) f = f if f.is_absolute() else base / f if not f.exists(): - skills/real-sfx/scripts/listen.py (14993 bytes)
#!/usr/bin/env python3 """The skill's ears: describe what a sound is, in words, without playing it. listen.py status what works now and what an install would add listen.py describe FILE [--sheet PNG] numbers, plain words, a picture and (if installed) AudioSet tags listen.py tag-index add tags + embeddings for every indexed sound (needs install) listen.py compare A B how alike two sounds are listen.py onsets FILE where separate sounds start inside a recording (and their slices) listen.py install --yes create vendor/venv, install onnxruntime + numpy, fetch yamnet.onnx Two levels of "hearing": 1. always available, no downloads: measured character -> words (punchy / dark / heavy / long-tail ...) plus the spectrogram picture that the model can look at (contact_sheet.py / --sheet). 2. after `install --yes` (about 45 MB, runs on CPU in the skill's own venv, nothing else on the system is touched): YAMNet gives the 521 AudioSet labels per second of audio (Whoosh, Explosion, Click, Glass, Typing ...) and a 1024-number embedding, so sounds can be found and compared by meaning. `install` is never run implicitly. It downloads: onnxruntime and numpy wheels from PyPI (~25 MB) and yamnet.onnx (16.1 MB, Apache-2.0, https://huggingface.co/audiomagic/yamnet-onnx) with its class map. """ import argparse import csv import json import os import subprocess import sys import urllib.request from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import SKILL_DIR, analyse_sound, index_path, load_config, words VENV = SKILL_DIR / "vendor" / "venv" MODEL_DIR = SKILL_DIR / "vendor" / "models" MODEL = MODEL_DIR / "yamnet.onnx" CLASSES = MODEL_DIR / "yamnet_class_map.csv" MODEL_URL = "https://huggingface.co/audiomagic/yamnet-onnx/resolve/main/yamnet.onnx" CLASSES_URL = "https://huggingface.co/audiomagic/yamnet-onnx/resolve/main/yamnet_class_map.csv" MODEL_BYTES = 16_093_355 EMB_BIN = SKILL_DIR / "library_embeddings.bin" EMB_JSON = SKILL_DIR / "library_embeddings.json" def venv_python(): from common import venv_python as _venv_python # one place, with REAL_SFX_VENV_PYTHON return _venv_python() def have_runtime(): try: import numpy # noqa: F401 import onnxruntime # noqa: F401 return True except Exception: return False def reexec_in_venv(): """Heavy commands run inside the skill's venv, so the system Python stays untouched.""" py = venv_python() if py and Path(sys.executable).resolve() != py.resolve(): raise SystemExit(subprocess.call([str(py), __file__] + sys.argv[1:])) def status(): print("ears, level 1 (always on): measured character -> words, spectrogram pictures") print(f"ears, level 2 (YAMNet tags + embeddings): " f"{'READY' if MODEL.exists() and (have_runtime() or venv_python()) else 'not installed'}") print(f" model file : {'yes' if MODEL.exists() else 'no'} {MODEL}") print(f" venv : {'yes' if venv_python() else 'no'} {VENV}") print(f" runtime in use : {'yes' if have_runtime() else 'no (will use venv if present)'}") emb = EMB_BIN.exists() print(f" library tagged : {'yes' if emb else 'no'}") if not (MODEL.exists() and venv_python()): print("\nTo add level 2 (about 45 MB, asks nothing else of the system):\n" f" python {Path(__file__).name} install --yes") def install(yes): if not yes: sys.exit("install downloads ~45 MB (onnxruntime, numpy, yamnet.onnx); run again with --yes to confirm") if not venv_python(): print("creating venv ...", flush=True) subprocess.check_call([sys.executable, "-m", "venv", str(VENV)]) py = venv_python() print("installing onnxruntime and numpy into the skill's venv ...", flush=True) subprocess.check_call([str(py), "-m", "pip", "install", "--disable-pip-version-check", "-q", "onnxruntime", "numpy"]) MODEL_DIR.mkdir(parents=True, exist_ok=True) for url, dst in ((MODEL_URL, MODEL), (CLASSES_URL, CLASSES)): if dst.exists() and (dst != MODEL or dst.stat().st_size == MODEL_BYTES): continue print(f"downloading {dst.name} ...", flush=True) urllib.request.urlretrieve(url, dst) if MODEL.stat().st_size != MODEL_BYTES: MODEL.unlink() sys.exit("yamnet.onnx has an unexpected size, removed it; try again or check the connection") print("done. try: listen.py describe <file>") # ------------------------------------------------------------------ YAMNet class Yamnet: def __init__(self): import numpy as np import onnxruntime as ort self.np = np self.sess = ort.InferenceSession(str(MODEL), providers=["CPUExecutionProvider"]) with open(CLASSES, encoding="utf-8") as f: rows = list(csv.reader(f)) self.names = [r[2] for r in rows[1:]] def run(self, path, max_seconds=12.0): np = self.np r = subprocess.run(["ffmpeg", "-v", "error", "-nostdin", "-i", str(path), "-vn", "-ac", "1", "-ar", "16000", "-t", f"{max_seconds:.2f}", "-f", "f32le", "-"], capture_output=True) x = np.frombuffer(r.stdout, dtype="<f4") if len(x) < 480: # under 30 ms: nothing to listen to return None if len(x) < 15600: # the model needs about one frame (0.975 s): pad short sounds x = np.concatenate([x, np.zeros(15600 - len(x), dtype="<f4")]) scores, emb, _ = self.sess.run(None, {"waveform": x.astype("float32")}) return scores, emb # classes that describe the surroundings or the absence of sound, not the sound STOP = {"Silence", "Sound effect", "Inside, small room", "Inside, large room or hall", "Inside, public space", "Outside, urban or manmade", "Outside, rural or natural", "Environmental noise", "Static"} def tags(self, path, top=6, active_s=None): """Top AudioSet classes and the mean embedding of the AUDIBLE part (pack files carry seconds of silence after the sound, and 'Silence 100 %' tells nothing about what the sound is).""" limit = 12.0 if active_s: limit = min(limit, max(1.0, active_s + 0.1)) out = self.run(path, limit) if out is None: return [], None scores, emb = out np = self.np peak = scores.max(axis=0) order = np.argsort(-peak) tags = [(self.names[i], float(peak[i])) for i in order if peak[i] > 0.08 and self.names[i] not in self.STOP][:top] return tags, emb.mean(axis=0) def describe(path, sheet=None, top=6): p = Path(path) if not p.exists(): sys.exit(f"file not found: {p}") info = analyse_sound(p) if not info: sys.exit(f"cannot decode {p}") info["words"] = words(info) print(f"{p.name}") print(f" length {info['duration']}s peak {info['peak_db']} dBFS loudest point at {info['peak_time']}s") print(f" attack {info['attack_ms']} ms, tail {info['decay_ms']} ms, centroid {info['centroid']} Hz, " f"low-end share {info['low']}, noisiness {info['flat']}") print(f" in words: {', '.join(info['words'])}") if MODEL.exists() and (have_runtime() or venv_python()): if not have_runtime(): reexec_in_venv() tags, _ = Yamnet().tags(p, top, info.get("active_dur")) if tags: print(" tags : " + "; ".join(f"{n} ({s:.0%})" for n, s in tags)) else: print(" tags : (level 2 not installed: listen.py install --yes)") if sheet: from contact_sheet import render_sheet rec = dict(info, id=0, path=str(p), role="?", library="file", name=p.stem, folder="") print(" picture :", render_sheet([rec], sheet, 1)) def voice_cmd(path): """JSON line: share of the file in which YAMNet hears speech / music (frames with a score of 0.35 or more).""" if not (MODEL.exists() and (have_runtime() or venv_python())): sys.exit("level 2 is not installed: listen.py install --yes") if not have_runtime(): reexec_in_venv() y = Yamnet() out = y.run(path, max_seconds=240.0) if out is None: sys.exit("nothing to listen to") scores, _ = out np = y.np names = y.names def share(*cls): idx = [i for i, n in enumerate(names) if n in cls] return float(np.mean(np.max(scores[:, idx], axis=1) >= 0.35)) if idx else 0.0 print(json.dumps({"speech": round(share("Speech", "Narration, monologue", "Conversation"), 3), "music": round(share("Music"), 3), "seconds": round(len(scores) * 0.48, 1)})) def tag_index(): if not (MODEL.exists() and (have_runtime() or venv_python())): sys.exit("level 2 is not installed: listen.py install --yes") if not have_runtime(): reexec_in_venv() import array y = Yamnet() idx_file = index_path(load_config()) data = json.loads(idx_file.read_text(encoding="utf-8")) sounds = data["sounds"] old = {} if EMB_JSON.exists() and EMB_BIN.exists(): paths = json.loads(EMB_JSON.read_text(encoding="utf-8"))["paths"] raw = array.array("f") raw.frombytes(EMB_BIN.read_bytes()) for i, pth in enumerate(paths): old[pth] = list(raw[i * 1024:(i + 1) * 1024]) emb_out, paths_out = array.array("f"), [] done = 0 for n, s in enumerate(sounds): pth = s["path"] if pth in old and s.get("tags") is not None and s.get("tags_v") == 3: e = old[pth] else: tags, e = y.tags(pth, 5, s.get("active_dur")) s["tags_v"] = 3 s["tags"] = [t for t, _ in tags] s["tag_scores"] = [round(c, 2) for _, c in tags] e = e.tolist() if e is not None else None done += 1 if e is None: continue emb_out.extend(e) paths_out.append(pth) if n % 100 == 0: print(f" {n}/{len(sounds)}", flush=True) idx_file.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8") EMB_BIN.write_bytes(emb_out.tobytes()) EMB_JSON.write_text(json.dumps({"dim": 1024, "paths": paths_out}), encoding="utf-8") print(f"tagged {done} new sounds, {len(paths_out)} embeddings in {EMB_BIN.name}") def onsets_cmd(path, min_level): """Where do the separate sounds inside a recording start (keystrokes, knocks, ticks)? Times and levels, and the cue-sheet slice for each one. Works at level 1, no model needed. FILE can be an id from search.py.""" from common import clean_hits, onsets if not Path(str(path)).exists() and str(path).isdigit(): try: from picker import find, load_index rec = find(load_index(), int(path)) except SystemExit: rec = None if rec is None: sys.exit(f"no sound with id {path} in the index (and no file of that name)") print(f"id {path}: {rec['path']}") path = rec["path"] ons, dur = onsets(path) ons = [(t, lvl) for t, lvl in ons if lvl >= min_level] print(f"{Path(path).name}: {dur:.2f} s, {len(ons)} sounds (level in dB under the loudest of the recording)") for i, (t, lvl) in enumerate(ons): nxt = ons[i + 1][0] if i + 1 < len(ons) else t + 0.2 ln = round(min(0.12, max(0.04, nxt - t - 0.004)), 3) print(f" {i:2d} {t:6.3f} s {lvl:+5.1f} dB \"slice\": [{max(0.0, t - 0.006):.3f}, {ln}]") print("use in a cue: {\"file\": \"" + str(path).replace("\\", "/") + "\", \"slice\": [start, length], " "\"role\": \"hit\", \"anchor\": \"start\"}") hits, _ = clean_hits(path) good = [h for h in hits if h["clean"]] print(f"clean single hits (out of silence, dying away, no second hit within 150 ms): {len(good)} of {len(hits)}") for h in good: print(f" t {h['t']:6.3f} s {h['level_db']:+5.1f} dB decay {h['decay_ms']:3d} ms " f"\"slice\": [{h['start']:.3f}, {h['len']:.3f}]") if hits and not good: print(" (none: every hit is a tumble or rides on the one before it; take another recording)") def compare(a, b): ia, ib = analyse_sound(a), analyse_sound(b) keys = ("centroid", "rolloff", "low", "high", "flat", "attack_ms", "decay_ms", "duration") import math d = 0.0 for k in keys: x, y = float(ia[k]), float(ib[k]) if k in ("centroid", "rolloff", "attack_ms", "decay_ms", "duration"): x, y = math.log1p(x), math.log1p(y) d += (x - y) ** 2 print(f"character distance {math.sqrt(d / len(keys)):.2f} (0 = same, >1.5 = clearly different)") print(f" A: {', '.join(words(ia))}\n B: {', '.join(words(ib))}") if MODEL.exists() and (have_runtime() or venv_python()): if not have_runtime(): reexec_in_venv() y = Yamnet() _, ea = y.tags(a, 6, ia.get("active_dur")) _, eb = y.tags(b, 6, ib.get("active_dur")) if ea is not None and eb is not None: np = y.np cos = float(np.dot(ea, eb) / (np.linalg.norm(ea) * np.linalg.norm(eb) + 1e-9)) print(f"semantic similarity (YAMNet embedding cosine) {cos:.2f} (1 = same kind of sound)") def main(): ap = argparse.ArgumentParser() sub = ap.add_subparsers(dest="cmd", required=True) sub.add_parser("status") i = sub.add_parser("install") i.add_argument("--yes", action="store_true") d = sub.add_parser("describe") d.add_argument("file") d.add_argument("--sheet") d.add_argument("--top", type=int, default=6) sub.add_parser("tag-index") v = sub.add_parser("voice") v.add_argument("file") o = sub.add_parser("onsets") o.add_argument("file") o.add_argument("--min-level", type=float, default=-24.0) c = sub.add_parser("compare") c.add_argument("a") c.add_argument("b") a = ap.parse_args() # the heavy commands run in the skill's venv; switch BEFORE anything is printed (the block was printed twice) if a.cmd in ("describe", "compare", "tag-index", "voice") and MODEL.exists() and not have_runtime() \ and venv_python(): reexec_in_venv() {"status": lambda: status(), "install": lambda: install(a.yes), "describe": lambda: describe(a.file, a.sheet, a.top), "tag-index": tag_index, "compare": lambda: compare(a.a, a.b), "onsets": lambda: onsets_cmd(a.file, a.min_level), "voice": lambda: voice_cmd(a.file)}[a.cmd]() if __name__ == "__main__": main() - skills/real-sfx/scripts/look.py (18106 bytes)
#!/usr/bin/env python3 """Look at a video the way a sound designer does: frames with timestamps and, under them, the sound that is already there. python look.py film.mp4 --out work/look # the whole film: rows of frames + original audio spectrogram python look.py film.mp4 --at 12.4 --span 3 --out work/at12.png # eight frames around a moment + spectrogram python look.py film.mp4 --at 12.4 --span 2.4 --step 0.1 --out work/at12.png # 24 frames, a frame every 0.1 s python look.py --moments work/moments/moments.json --out work/moments.png [--per 12 --cols 4] What it is for (before any sound is placed, so it needs no cue sheet): * the story sheet shows what happens when and where the original audio (voice, music) is busy, so the placement of sounds is decided from pictures, not from numbers alone; * --at is the close look at a fast action or a doubtful moment, the same strip zoom.py draws for a finished mix; * --moments tiles the frames that find_moments.py / from_hyperframes.py picked, labelled with id, time, kind and strength, so a draft cue sheet can be checked against the picture in a few images. Reading the spectrogram (low pitch at the bottom, time to the right, brightness = energy): a voice is a stack of horizontal bands that come and go as phrases; music is a steady carpet with a beat as vertical bars; silence is black. Thin white ticks mark the frame boundaries so the two halves line up. """ import argparse import os import json import math import subprocess import sys import tempfile from pathlib import Path W_TILE, H_TILE, PER_ROW, H_SPEC = 240, 135, 8, 72 def find_font(): for p in ("C:/Windows/Fonts/arial.ttf", "C:/Windows/Fonts/segoeui.ttf", "C:/Windows/Fonts/calibri.ttf", "/System/Library/Fonts/Supplemental/Arial.ttf", "/Library/Fonts/Arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/dejavu/DejaVuSans.ttf"): if Path(p).exists(): return p return None def esc(path): return str(path).replace("\\", "/").replace(":", "\\:").replace("'", "\\'") def ff(args): r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-nostdin"] + [str(a) for a in args], capture_output=True, text=True, errors="replace") if r.returncode: sys.exit("ffmpeg failed:\n" + r.stderr[-1500:]) def probe(video): r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration:stream=codec_type,duration,r_frame_rate", "-of", "json", str(video)], capture_output=True, text=True) j = json.loads(r.stdout or "{}") kinds = [s["codec_type"] for s in j.get("streams", [])] if "video" not in kinds: sys.exit(f"{video} has no picture: look.py shows frames. For a sound file use zoom.py or contact_sheet.py " f"(waveform and spectrogram).") dur = float(j.get("format", {}).get("duration", 0) or 0) # a reel's audio is often a few tenths of a second longer than its picture: a frame asked for after the last # picture is not written (and ffmpeg still says 0, the sheet then dies on a missing row): measure by the picture vs = [s for s in j.get("streams", []) if s.get("codec_type") == "video"] vd = float(vs[0].get("duration") or 0) if vs else 0.0 if 0 < vd < dur: dur = vd try: # the last picture STARTS one frame before the end of the stream num, den = str(vs[0].get("r_frame_rate", "30/1")).split("/") fps = float(num) / float(den) if 1.0 <= fps <= 240.0 and dur > 1.0: dur -= 1.2 / fps except (ValueError, ZeroDivisionError, IndexError): pass return dur, "audio" in kinds def label_filter(text, font, tmp, name, size=14): """drawtext fragment that writes `text` in the top-left corner on a dark bar (text goes through a file).""" if not font: return "" f = Path(tmp) / f"{name}.txt" f.write_text(text, encoding="utf-8") return (f",drawbox=x=0:y=0:w=iw:h={size + 8}:[email protected]:t=fill," f"drawtext=fontfile='{esc(font)}':textfile='{esc(f)}':expansion=none:fontcolor=yellow:fontsize={size}:x=5:y=4") CROP = None # (x, y, w, h) of the picture, set by --crop def frames_row(video, t_list, tmp, name, font, labels, w=None, h=None): """One horizontal strip: a frame at each time of t_list, each labelled.""" inp, chain = [], [] w, h = w or W_TILE, h or H_TILE crop = f"crop={CROP[2]}:{CROP[3]}:{CROP[0]}:{CROP[1]}," if CROP else "" for i, t in enumerate(t_list): inp += ["-ss", f"{max(0.0, t):.3f}", "-i", str(video)] lab = label_filter(labels[i], font, tmp, f"{name}_{i}") chain.append(f"[{i}:v]setpts=PTS-STARTPTS,{crop}scale={w}:{h}:force_original_aspect_ratio=decrease," f"pad={w}:{h}:(ow-iw)/2:(oh-ih)/2:color=0x101010,format=rgb24{lab}[f{i}]") n = len(t_list) stack = "".join(f"[f{i}]" for i in range(n)) + (f"hstack=inputs={n}[row]" if n > 1 else "") graph = ";".join(chain + ([stack] if n > 1 else [])) out = Path(tmp) / f"{name}.png" mapped = "[row]" if n > 1 else "[f0]" ff(inp + ["-filter_complex", graph, "-map", mapped, "-frames:v", "1", out]) return out def spec_row(video, t0, span, width, tmp, name, ticks): """Spectrogram of the original audio over [t0, t0+span], with tick marks at the tile boundaries.""" out = Path(tmp) / f"{name}.png" marks = ",".join(f"drawbox=x={min(width - 1, int(width * k / ticks))}:y=0:w=1:h=ih:[email protected]:t=fill" for k in range(ticks + 1)) ff(["-ss", f"{max(0.0, t0):.3f}", "-t", f"{span:.3f}", "-i", str(video), "-vn", "-filter_complex", f"[0:a]aformat=channel_layouts=mono,showspectrumpic=s={width}x{H_SPEC}:legend=0:fscale=log:scale=log:" f"color=viridis,format=rgb24,{marks}", "-frames:v", "1", out]) return out def stack_png(parts, out): cmd = [] for p in parts: cmd += ["-i", str(p)] n = len(parts) if n == 1: ff(cmd + ["-frames:v", "1", out]) else: ff(cmd + ["-filter_complex", "".join(f"[{i}:v]" for i in range(n)) + f"vstack=inputs={n}", "-frames:v", "1", out]) def story(video, out_prefix, step=None, rows_per_sheet=4): dur, has_audio = probe(video) if dur <= 0: sys.exit(f"cannot read {video}") font = find_font() if step is None: step = max(0.5, math.ceil(dur / 48 * 2) / 2) # at most 48 frames in all n_tiles = max(1, int(math.ceil(dur / step))) rows = [list(range(i, min(i + PER_ROW, n_tiles))) for i in range(0, n_tiles, PER_ROW)] sheets = [] with tempfile.TemporaryDirectory() as tmp: row_imgs = [] for ri, tiles in enumerate(rows): ts = [min(dur - 0.05, (k + 0.5) * step) for k in tiles] labels = [(f"{t:.2f}".rstrip("0").rstrip(".") + "s") for t in ts] # the time of the frame shown parts = [frames_row(video, ts, tmp, f"r{ri}", font, labels)] if has_audio: t0 = tiles[0] * step span = (tiles[-1] + 1) * step - t0 # pad a short last row so tile boundaries still line up with the spectrogram width = W_TILE * len(tiles) parts.append(spec_row(video, t0, span, width, tmp, f"s{ri}", len(tiles))) img = Path(tmp) / f"row{ri}.png" stack_png(parts, img) row_imgs.append(img) for si in range(0, len(row_imgs), rows_per_sheet): chunk = row_imgs[si:si + rows_per_sheet] dst = Path(f"{out_prefix}_{si // rows_per_sheet + 1}.png") dst.parent.mkdir(parents=True, exist_ok=True) if len(chunk) == 1: stack_png(chunk, dst) else: # rows can differ in width (last row shorter): pad to the widest one wmax = W_TILE * PER_ROW cmd, g = [], [] for i, p in enumerate(chunk): cmd += ["-i", str(p)] g.append(f"[{i}:v]pad={wmax}:ih:0:0:color=0x101010[p{i}]") g.append("".join(f"[p{i}]" for i in range(len(chunk))) + f"vstack=inputs={len(chunk)}") ff(cmd + ["-filter_complex", ";".join(g), "-frames:v", "1", dst]) sheets.append(dst) print(f"{dur:.1f} s, a frame every {step:g} s, {len(rows)} rows, original audio " f"{'shown under each row' if has_audio else 'absent'}") for s in sheets: print("sheet:", s) return sheets def at(video, centre, span, out, step=None): """Frames around a moment: eight in one row, or with `step` one frame every `step` s (up to 24, rows of eight, the original sound under each row): the way to read a fast, dense animation frame by frame.""" dur, has_audio = probe(video) font = find_font() t0 = max(0.0, centre - span / 2) n = PER_ROW if not step else max(2, min(24, int(round(span / step)))) dt = span / n ts = [t0 + dt * (i + 0.5) for i in range(n)] with tempfile.TemporaryDirectory() as tmp: parts = [] rows = [ts[i:i + PER_ROW] for i in range(0, n, PER_ROW)] for ri, row_ts in enumerate(rows): row = frames_row(video, row_ts, tmp, f"at{ri}", font, [f"{t:.2f}s" for t in row_ts]) sub = [row] if has_audio: sub.append(spec_row(video, row_ts[0] - dt / 2, dt * len(row_ts), W_TILE * len(row_ts), tmp, f"atspec{ri}", len(row_ts))) img = Path(tmp) / f"atrow{ri}.png" stack_png(sub, img) parts.append(img) out = Path(out) out.parent.mkdir(parents=True, exist_ok=True) if len(parts) == 1: stack_png(parts, out) else: # the last row may be shorter: pad to the widest wmax = W_TILE * PER_ROW cmd, g = [], [] for i, p in enumerate(parts): cmd += ["-i", str(p)] g.append(f"[{i}:v]pad={wmax}:ih:0:0:color=0x101010[p{i}]") g.append("".join(f"[p{i}]" for i in range(len(parts))) + f"vstack=inputs={len(parts)}") ff(cmd + ["-filter_complex", ";".join(g), "-frames:v", "1", out]) print(f"window {t0:.2f}-{t0 + span:.2f} s, a frame every {dt:.2f} s ->", out) def events_sheet(video, events, out, per, cols): """An event list of ui_events.py (no frame images): a BEFORE and an AFTER frame of the picture (or of --crop) for every event, so the false ones (a hover, a redraw, a timer) are seen at once. `per` events to a sheet.""" font = find_font() evs = sorted((e for e in events if isinstance(e, dict) and "t" in e), key=lambda e: float(e["t"])) if not evs: sys.exit("no events with a time in that file") n_cols = max(2, cols - cols % 2) # tiles come in pairs w = W_TILE if W_TILE >= 200 else 240 h = H_TILE total = len(evs) limit = max(6, per) # a hundred keystrokes are not a hundred pictures if total > limit: groups = {} for e in evs: groups.setdefault((e.get("type"), e.get("roi")), []).append(e) take = max(2, limit // max(1, len(groups))) chosen = [] for g in groups.values(): if len(g) <= take: chosen += g else: chosen += [g[round(i * (len(g) - 1) / (take - 1))] for i in range(take)] evs = sorted(chosen, key=lambda e: float(e["t"]))[:max(limit, len(groups) * 2)] print(f"{total} events: an even sample of {len(evs)} from every region and kind (--per N shows more)") per = 6 # events on one sheet (two tiles each) outs = [] with tempfile.TemporaryDirectory() as tmp: for si in range(0, len(evs), per): chunk = evs[si:si + per] tiles = [] for k, e in enumerate(chunk): t = float(e["t"]) name = f"{e.get('type', '?')}" + (f" {e['roi']}" if e.get("roi") else "") tiles.append((max(0.0, t - 0.25), f"#{si + k} {t:.2f}s {name[:22]} before")) tiles.append((t + 0.2, f"#{si + k} after")) rows = [tiles[i:i + n_cols] for i in range(0, len(tiles), n_cols)] parts = [] for ri, row in enumerate(rows): p = frames_row(video, [t for t, _ in row], tmp, f"ev{si}_{ri}", font, [l for _, l in row], w=w, h=h) if len(row) < n_cols and len(rows) > 1: full = Path(tmp) / f"ev{si}_{ri}_pad.png" ff(["-i", p, "-vf", f"pad={n_cols * w}:ih:0:0:color=0x101010", "-frames:v", "1", full]) p = full parts.append(p) dst = Path(f"{Path(out).with_suffix('')}_{si // per + 1}.png") if len(evs) > per else Path(out) dst.parent.mkdir(parents=True, exist_ok=True) stack_png(parts, dst) outs.append(dst) print(f"{len(evs)} events on {len(outs)} sheet(s) (a frame before and after each):") for o in outs: print("sheet:", o) def moments_sheet(mj, out, per, cols): d = json.loads(Path(mj).read_text(encoding="utf-8-sig")) base = Path(mj).parent if isinstance(d, list): # an event list (ui_events.py events.json), not a moments.json return d ms = [m for m in d["moments"] if m.get("frame")] if not ms: sys.exit("no moment in this file has a frame image (from_hyperframes.py has none: use find_moments.py " "or look.py FILM --out ...)") font = find_font() W, H = 400, 225 outs = [] with tempfile.TemporaryDirectory() as tmp: for si in range(0, len(ms), per): chunk = ms[si:si + per] inp, chain, pos = [], [], [] for i, m in enumerate(chunk): inp += ["-i", str(base / m["frame"])] text = f"#{m['id']} {m['t']:.2f}s {m['kind']} s={m.get('strength', 0):.2f} p={m.get('pct', 0):.2f}" if m.get("hint"): text += f" {m['hint'][:24]}" lab = label_filter(text, font, tmp, f"m{si}_{i}", size=15) chain.append(f"[{i}:v]scale={W}:{H}:force_original_aspect_ratio=decrease," f"pad={W}:{H}:(ow-iw)/2:(oh-ih)/2:color=0x101010,format=rgb24{lab}[t{i}]") pos.append(f"{(i % cols) * W}_{(i // cols) * H}") n = len(chunk) i - skills/real-sfx/scripts/masking.py (13934 bytes)
#!/usr/bin/env python3 """Does a sound cover speech (or the music's body)? Objective check for voice-led videos. python masking.py result/film_sfx_resolved_cues.json result/film_sfx_sfx_track.wav --video film.mp4 For every cue the speech band (250-3800 Hz) of the original audio is compared with the same band of the SFX track in the window where the sound is audible. A cue masks when the original is speaking there (its band rises 8 dB above its own local floor, so a pause over a music bed does not count) and the SFX is within 3 dB of it or louder. Returns the list so critique.py and the agent can fix those cues first: lower gain_db, add highpass, shorten, move into a pause, or run mix.py with --voice-safe. Importable: masked_cues(cues, sfx_wav, video) -> list of dicts. """ import argparse import array import json import math import subprocess import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import load_json RATE = 8000 def band_env(path, hop=0.05): """RMS in dB of the 250-3800 Hz band per hop, for a file's audio.""" r = subprocess.run(["ffmpeg", "-v", "error", "-nostdin", "-i", str(path), "-vn", "-ac", "1", "-ar", str(RATE), "-af", "highpass=f=250,lowpass=f=3800", "-f", "s16le", "-"], capture_output=True) a = array.array("h") a.frombytes(r.stdout[: len(r.stdout) // 2 * 2]) w = int(RATE * hop) out = [] for i in range(0, len(a) - w + 1, w): e = math.sqrt(sum(v * v for v in a[i:i + w]) / w) / 32768.0 out.append(20 * math.log10(e) if e > 1e-5 else -100.0) return out def speech_active(orig, hop=0.05, rise_db=8.0, window_s=3.0, below_peak=26.0): """True where the original's speech band rises clearly above its own local floor: voice bursts over a bed. A pause (music bed or room tone only) stays False, so a sound in a pause is not 'masking speech'.""" n = len(orig) half = max(1, int(window_s / hop / 2)) act = [False] * n live = sorted(v for v in orig if v > -70.0) # the speech itself sets the scale: the tail of a word in a pause (20 dB under the speech) is not speech ref = live[int(0.9 * (len(live) - 1))] if live else -50.0 floor_abs = max(-50.0, ref - below_peak) # a clean voice stem: breath and noise sit 20+ dB under the words for i in range(n): win = sorted(orig[max(0, i - half):i + half + 1]) floor = win[int(0.10 * (len(win) - 1))] act[i] = orig[i] > max(floor + rise_db, floor_abs) return act VOICE_WORDS = ("voice", "vo_", "_vo", "vox", "dialog", "narrat", "speech", "speak") def voice_stem(sheet): """The speech stem among the files the original was rebuilt from: a clean voice, its pauses are real pauses (the music under it is not mistaken for speech). None when there is none.""" given = sheet.get("voice_stems") or [] if isinstance(given, str): given = [given] for f in given: # the mixer wrote which files are speech if Path(f).exists(): return f for f in sheet.get("base_audio") or []: f = f.get("file") if isinstance(f, dict) else f s = Path(str(f)).stem.lower() if any(w in s for w in VOICE_WORDS) and Path(f).exists(): return f return None def speech_activity(sheet, orig_src, hop=0.05): """The speech mask of a sheet on a grid of `hop`: from the voice stem when the mixer rebuilt from one, else from the original audio. Returns a function t -> bool, or None when there is nothing to read.""" src = voice_stem(sheet) or orig_src if not src or not Path(src).exists(): return None act = speech_active(band_env(src, hop), hop) return lambda t: bool(0 <= int(t / hop) < len(act) and act[int(t / hop)]) def active_level_diff(orig, final, hop=0.1, floor_db=-50.0): """Mean level of `final` minus `orig` (dB, energy mean) over the frames where the ORIGINAL sounds. The integrated LUFS of a file with new quiet sounds in the original's silence drops (BS.1770 gating) although the original's own sound was not touched; this says which of the two it is. None when it cannot be read.""" try: eo, ef = full_env(orig, hop), full_env(final, hop) except Exception: return None n = min(len(eo), len(ef)) idx = [i for i in range(n) if eo[i] > floor_db] if len(idx) < 10: return None po = sum(10 ** (eo[i] / 10.0) for i in idx) / len(idx) pf = sum(10 ** (ef[i] / 10.0) for i in idx) / len(idx) if po <= 0 or pf <= 0: return None return 10 * math.log10(pf / po) def masked_cues(cues, sfx_wav, video, hop=0.05, margin_db=3.0, speech_floor_db=-48.0, gain_db=0.0, clean_voice=False): """Cues whose sound sits within margin_db of (or above) the original while the original is SPEAKING. gain_db: what the mix added to `video` (a stem enters the mix at the base gain). clean_voice: `video` is a voice stem (no music): breath and noise between words are not speech (a stricter floor under the words). The voice is read 100 ms ahead (the first frame of a word is its attack, the word is what masks), and a cue is only judged until the next cue begins (the next cue's own energy is not this cue's).""" orig = [v + gain_db for v in band_env(video, hop)] sfx = band_env(sfx_wav, hop) act = speech_active(orig, hop, below_peak=20.0 if clean_voice else 26.0) n = min(len(orig), len(sfx)) ahead = [max(orig[i:i + 3]) for i in range(len(orig))] mains = sorted((c for c in cues if not c.get("_layer")), key=lambda c: c.get("start", c["t"])) res = [] for k_, c in enumerate(mains): t0 = c.get("start", c["t"]) t1 = t0 + min(c.get("seg", 0.4), 0.6) nxt = next((m_.get("start", m_["t"]) for m_ in mains[k_ + 1:] if m_.get("start", m_["t"]) > t0 + 0.03), None) if nxt is not None and nxt < t1: t1 = max(t0 + hop, nxt - 0.01) i0, i1 = int(t0 / hop), max(int(t0 / hop) + 1, int(t1 / hop)) worst, where = None, None for i in range(i0, min(i1, n)): if act[i] and orig[i] > speech_floor_db and sfx[i] > -60: d = sfx[i] - ahead[i] if worst is None or d > worst: worst, where = d, i * hop if worst is not None and worst > -margin_db: res.append({"t": c["t"], "label": c.get("label", ""), "role": c.get("role"), "over_db": round(worst, 1), "at": round(where, 2)}) return res def full_env(path, hop=0.1, rate=16000): """RMS in dB of the whole band per hop (for loudness relations, not for masking).""" r = subprocess.run(["ffmpeg", "-v", "error", "-nostdin", "-i", str(path), "-vn", "-ac", "1", "-ar", str(rate), "-f", "s16le", "-"], capture_output=True) a = array.array("h") a.frombytes(r.stdout[: len(r.stdout) // 2 * 2]) w = int(rate * hop) out = [] for i in range(0, len(a) - w + 1, w): e = math.sqrt(sum(v * v for v in a[i:i + w]) / w) / 32768.0 out.append(20 * math.log10(e) if e > 1e-5 else -100.0) return out def cue_levels(cues, sfx_wav, video, hop=0.1, around_s=3.0): # silent windows are reported with silent=True """For every cue: how loud is the sound at its loudest 100 ms compared with the original's median level in the 3 s around it. This is the balance a mixer judges: a tick sits 8-12 dB under the picture's sound, a big hit around it or a little above. Integrated LUFS of a sparse SFX track cannot say that.""" orig, sfx = full_env(video, hop), full_env(sfx_wav, hop) half = max(1, int(around_s / hop / 2)) res = [] for c in cues: if c.get("_layer"): continue t0 = c.get("start", c["t"]) i0 = int(t0 / hop) i1 = max(i0 + 1, int((t0 + min(c.get("seg", 0.4), 0.6)) / hop)) s = max(sfx[i0:i1], default=-100.0) win = sorted(orig[max(0, i0 - half):i0 + half + 1]) o = win[len(win) // 2] if win else -100.0 if s > -70 and o > -70: res.append({"t": c["t"], "role": c.get("role"), "label": c.get("label", ""), "delta_db": round(s - o, 1)}) elif s > -70: # the original is silent around this sound: nothing to bury or mask res.append({"t": c["t"], "role": c.get("role"), "label": c.get("label", ""), "delta_db": None, "silent": True}) return res def sub_env(path, hop=0.05): """RMS in dB of the 30-140 Hz band per hop.""" r = subprocess.run(["ffmpeg", "-v", "error", "-nostdin", "-i", str(path), "-vn", "-ac", "1", "-ar", str(RATE), "-af", "highpass=f=30,lowpass=f=140", "-f", "s16le", "-"], capture_output=True) a = array.array("h") a.frombytes(r.stdout[: len(r.stdout) // 2 * 2]) w = int(RATE * hop) out = [] for i in range(0, len(a) - w + 1, w): e = math.sqrt(sum(v * v for v in a[i:i + w]) / w) / 32768.0 out.append(20 * math.log10(e) if e > 1e-5 else -100.0) return out def lowend_collisions(cues, sfx_wav, video, hop=0.05, floor_db=-38.0): """Heavy cues (hit, sub_drop, design) that land where the original audio already has strong sub/bass. Two bass sources on top of each other make mud; the original stays, so the SFX has to make room: highpass the sound (about 90 Hz), lower it, move it between bass notes, or drop the sub layer.""" orig, sfx = sub_env(video, hop), sub_env(sfx_wav, hop) n = min(len(orig), len(sfx)) res = [] for c in cues: if c.get("role") not in ("hit", "sub_drop", "design"): continue t0 = c.get("start", c["t"]) i0 = int(t0 / hop) i1 = max(i0 + 1, int((t0 + min(c.get("seg", 0.5), 0.6)) / hop)) pairs = [(orig[i], sfx[i]) for i in range(i0, min(i1, n)) if sfx[i] > -60] if not pairs: continue o = max(p[0] for p in pairs) s = max(p[1] for p in pairs) if o > floor_db and s > o - 6.0: res.append({"t": c["t"], "label": c.get("label", ""), "role": c["role"], "orig_sub_db": round(o, 1), "sfx_sub_db": round(s, 1), "need_db": round(s - (o - 6.0) + 1.0, 1)}) return res def main(): ap = argparse.ArgumentParser() ap.add_argument("cues") ap.add_argument("track") ap.add_argument("--video") ap.add_argument("--json", action="store_true") ap.add_argument("--lowend", action="store_true", help="also report heavy cues that collide with bass in the original") ap.add_argument("--dry-track", action="store_true", help="judge the raw SFX track even when the sheet has the ducked one (the default is what is in the mix)") a = ap.parse_args() sheet = load_json(a.cues) video = a.video or sheet.get("original_audio") or sheet.get("video") if not video: sys.exit("need the video (--video) to read the original audio") from common import voice_share vstem = voice_stem(sheet) if not a.video else None speech_src = vstem or video speech_gain = float(sheet.get("voice_stem_gain_db", sheet.get("base_gain_db")) or 0.0) if vstem else 0.0 track = a.track if sheet.get("sfx_ducked") and Path(sheet["sfx_ducked"]).exists() and not a.dry_track: track = sheet["sfx_ducked"] # what is IN the mix after the voice-safe ducking print(f"track: {Path(track).name} (the SFX as they sit in the mix, after ducking; --dry-track for the raw bus)") if vstem: print(f"speech reference: the voice stem {Path(vstem).name} (not the whole original, music is not speech)") vs = voice_share(speech_src) if vs is not None and vs.get("speech", 1.0) < 0.05 and not a.lowend: print(f"no speech in the original audio (speech {vs['speech']:.0%}, music {vs.get('music', 0):.0%}): " f"nothing to mask. --lowend still checks the bass.") return if (sheet.get("flags") or {}).get("voice_safe") and track == a.track and not a.dry_track: print("WARN: this mix was made with --voice-safe but its ducked SFX file (*_sfx_ducked.wav) is missing: the " "dry track overstates the masking (the mix ducks it by several dB)") res = masked_cues(sheet["cues"], track, speech_src, gain_db=speech_gain, clean_voice=bool(vstem)) \ if (vs is None or vs.get("speech", 1.0) >= 0.05) else [] if a.lowend: low = lowend_collisions(sheet["cues"], track, video) if low: print(f"{len(low)} heavy cue(s) collide with bass already in the original audio:") for r in low: print(f" {r['t']:7.2f}s {r['role']:8s} {r['label'][:28]:28s} original sub {r['orig_sub_db']:.0f} dB, " f"SFX sub {r['sfx_sub_db']:.0f} dB: lower it {r['need_db']:.0f} dB, or highpass >= 140 Hz " f"(90 Hz leaves the 100-140 Hz band the check measures), or drop the sub layer") else: print("no heavy cue collides with bass in the original audio") if a.json: print(json.dumps(res, ensure_ascii=False, indent=1)) elif not res: print("no cue masks the original audio") else: print(f"{len(res)} cue(s) sit on top of the original audio (speech band):") for r in res: print(f" {r['t']:7.2f}s {r['role'] or '?':8s} {r['label'][:28]:28s} SFX {r['over_db']:+.1f} dB vs original" f" -> lower by {max(1.0, r['over_db'] + 3.0 + 1.0):.0f} dB, shorten, or move into a pause") sys.exit(1 if res else 0) if __name__ == "__main__": main() - skills/real-sfx/scripts/maskmodel.py (16766 bytes)
#!/usr/bin/env python3 """Is every sound of the film audible in the mix, or is it under the masked threshold of the rest? A model of simultaneous and forward masking in critical bands, run on the processed cues of a render. python mix.py cues.json --out film.mp4 --masking # does everything below python maskmodel.py film_resolved_cues.json CLIPS_DIR [--gain-db G] [--original WAV --original-gain-db G] [--spl-full-scale 80] [--offset-db 0] [--json OUT] CLIPS_DIR is what `mix.py --export-clips` writes (sfx_clips.json + one wav per cue, its own gain baked in). What it computes. Every cue is a target; everything else that sounds at that time (the other cues, the bed, the film's own music and voice when it is kept) is the masker, band by band (24 Bark bands, 1536-point STFT at 48 kHz, 16 ms hop). The masker is spread over the neighbouring bands with Schroeder's spreading function (-27 dB/Bark downwards, steeper upwards), lowered by the noise-masker offset of the MPEG-1 psychoacoustic model (6 dB + 0.275 dB per Bark), held on after it stops (forward masking, 12 dB per 50 ms) and put over the absolute threshold of hearing (Terhardt) at the playback level given by --spl-full-scale. A target is audible where its power over a 192 ms window (the ear integrates that long: a 5 ms click is judged by its energy) stands over that threshold. Per cue: margin_db the best band's power over the masked threshold (>= 10 clear, 3..10 ok, 0..3 marginal, < 0 masked) share the part of the sound's power that sits in bands where it is over the threshold bed_cost_db what the bed takes off the margin (the margin without it minus the margin with it) masked_by where the threshold power at the best band comes from: bed, other cues, original audio What it is not: a listening test. It is a textbook model of tones and noise applied to transients; its use is the order of the places (which sound is under which), and to be CALIBRATED against the verdicts of listen_page.py (--offset-db). """ import argparse import json import math import sys import wave from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) try: import numpy as np except ImportError: # the system Python of this skill has none: the venv of listen.py has np = None SR = 48000 NFFT = 1536 # 32 ms: 31.25 Hz per bin at 48 kHz HOP = 768 # 16 ms INTEG = 12 # frames of the energy window: 192 ms EDGES = [0, 100, 200, 300, 400, 510, 630, 770, 920, 1080, 1270, 1480, 1720, 2000, 2320, 2700, 3150, 3700, 4400, 5300, 6400, 7700, 9500, 12000, 15500] # Zwicker's critical bands NB = len(EDGES) - 1 FWD_DB_PER_FRAME = 0.24 * 16 # forward masking: 12 dB per 50 ms PRE = 0.4 # seconds of masker history before a sound EPS = 1e-12 def need_numpy(): if np is None: sys.exit("maskmodel.py needs numpy: run it with the Python of the skill's venv " "(`python scripts/listen.py install --yes` makes it), mix.py --masking does that by itself") # ------------------------------------------------------------------------------------------------ the model def bark(f): return 13.0 * math.atan(0.00076 * f) + 3.5 * math.atan((f / 7500.0) ** 2) def tables(): """Band matrix (bins x bands), spreading matrix (target band x masker band, power), offsets, absolute threshold.""" freqs = np.fft.rfftfreq(NFFT, 1.0 / SR) B = np.zeros((len(freqs), NB)) for b in range(NB): B[(freqs >= EDGES[b]) & (freqs < EDGES[b + 1]), b] = 1.0 z = np.array([bark(0.5 * (EDGES[b] + EDGES[b + 1])) for b in range(NB)]) dz = z[:, None] - z[None, :] # target - masker, Bark sf = 15.81 + 7.5 * (dz + 0.474) - 17.5 * np.sqrt(1.0 + (dz + 0.474) ** 2) S = 10.0 ** (sf / 10.0) offset = 6.025 + 0.275 * z # dB under the spread masker (noise-like masker) fc = np.array([0.5 * (EDGES[b] + EDGES[b + 1]) for b in range(NB)]) / 1000.0 ath = 3.64 * fc ** -0.8 - 6.5 * np.exp(-0.6 * (fc - 3.3) ** 2) + 1e-3 * fc ** 4 # dB SPL return B, S, offset, ath def band_power(x, tab): """x: (samples, channels) float -> (frames, bands) mean-square power, channels averaged. A full-scale sine is 0.5.""" B = tab[0] if x.shape[0] < NFFT: x = np.vstack([x, np.zeros((NFFT - x.shape[0], x.shape[1]))]) win = np.hanning(NFFT + 1)[:-1] norm = 1.0 / (NFFT ** 2 * np.mean(win ** 2)) out = None for c in range(x.shape[1]): fr = np.lib.stride_tricks.sliding_window_view(x[:, c], NFFT)[::HOP] * win p = np.abs(np.fft.rfft(fr, axis=1)) ** 2 * norm * 2.0 p[:, 0] *= 0.5 pb = p @ B out = pb if out is None else out + pb return out / x.shape[1] def threshold(P, tab, offset_extra_db=0.0): """Masked threshold power per band from the masker's band power (frames x bands): spread, offset, held on.""" _, S, offset, _ = tab T = (P @ S.T) * 10.0 ** (-(offset + offset_extra_db) / 10.0) dec = 10.0 ** (-FWD_DB_PER_FRAME / 10.0) for t in range(1, T.shape[0]): T[t] = np.maximum(T[t], T[t - 1] * dec) return T def ath_power(tab, spl_full_scale): return 0.5 * 10.0 ** ((tab[3] - spl_full_scale) / 10.0) CARRY = 1e-3 # a band counts for a sound when it holds this much of the strongest band's power def margin(Pt, T, onset, length): """Best margin of a target over a threshold: windows of INTEG frames from the onset to `length` frames after it, over the bands that carry the sound (not its leakage skirts: a pure low tone has none above the threshold). -> (margin_db, share, window_start, band)""" best = (-99.0, 0.0, onset, 0) n = Pt.shape[0] js = list(range(max(0, onset - 2), min(n - 1, onset + max(1, length)) + 1)) power = {j: float(Pt[j:min(n, j + INTEG)].mean(axis=0).sum()) for j in js} top = max(power.values()) if power else 0.0 for j in js: if power[j] <= 1e-16 or power[j] < 0.1 * top: # a window with (almost) none of the sound in it continue a, b = j, min(n, j + INTEG) pt, tt = Pt[a:b].mean(axis=0), T[a:b].mean(axis=0) carry = pt >= pt.max() * CARRY r = np.where(carry, 10.0 * np.log10((pt + EPS) / (tt + EPS)), -999.0) k = int(np.argmax(r)) if r[k] > best[0] or best[0] <= -99.0: tot = float(pt.sum()) + EPS best = (float(r[k]), float(pt[carry & (pt > tt)].sum() / tot), j, k) return best # ------------------------------------------------------------------------------------------------ audio in def read_wav(path): """-> (samples, channels) float32 at SR, or None. 16/24/32-bit PCM through the wave module, anything else via ffmpeg.""" try: with wave.open(str(path), "rb") as w: ch, sw, sr, n = w.getnchannels(), w.getsampwidth(), w.getframerate(), w.getnframes() raw = w.readframes(n) if sr == SR and sw in (2, 3, 4): if sw == 2: v = np.frombuffer(raw, dtype="<i2").astype(np.float32) / 32768.0 elif sw == 4: v = np.frombuffer(raw, dtype="<i4").astype(np.float32) / 2147483648.0 else: a = np.frombuffer(raw, dtype=np.uint8).reshape(-1, 3) i = a[:, 0].astype(np.int32) | (a[:, 1].astype(np.int32) << 8) | (a[:, 2].astype(np.int32) << 16) v = (np.where(i >= 1 << 23, i - (1 << 24), i) / float(1 << 23)).astype(np.float32) return v.reshape(-1, ch) except Exception: pass return decode(path) def decode(path): import subprocess r = subprocess.run(["ffmpeg", "-v", "error", "-nostdin", "-i", str(path), "-vn", "-ac", "2", "-ar", str(SR), "-f", "f32le", "-"], capture_output=True) if r.returncode or not r.stdout: return None return np.frombuffer(r.stdout, dtype="<f4").reshape(-1, 2).copy() def stereo(x): if x.shape[1] == 1: return np.repeat(x, 2, axis=1) return x[:, :2] def put(dst, src, start_s): i0 = int(round(start_s * SR)) if i0 >= dst.shape[0] or i0 + src.shape[0] <= 0: return a = max(0, -i0) b = min(src.shape[0], dst.shape[0] - i0) dst[i0 + a:i0 + b] += src[a:b] # ------------------------------------------------------------------------------------------------ the film def analyse(clips, dur, gain_db=0.0, original=None, original_gain_db=0.0, spl_full_scale=80.0, offset_db=0.0): """clips: [{start, wav (array), bed, texture, layer, ...}] -> per-cue result list.""" need_numpy() tab = tables() ath = ath_power(tab, spl_full_scale) g = 10.0 ** (gain_db / 20.0) n = int(math.ceil(dur * SR)) + NFFT bed = np.zeros((n, 2), dtype=np.float32) rest = np.zeros((n, 2), dtype=np.float32) for c in clips: put(bed if c.get("bed") else rest, c["wav"] * g, c["start"]) orig = np.zeros((n, 2), dtype=np.float32) if original is not None: o = original[: n] * (10.0 ** (original_gain_db / 20.0)) orig[: o.shape[0]] = o out = [] for c in clips: w = c["wav"] * g if w.shape[0] == 0 or c.get("bed"): continue s0 = max(0.0, c["start"] - PRE) keep = min(w.shape[0] / SR, 1.0) # the first second of the sound s1 = min(dur, c["start"] + keep + INTEG * HOP / SR) i0, i1 = int(s0 * SR), max(int(s1 * SR), int(s0 * SR) + NFFT) tgt = np.zeros((i1 - i0, 2), dtype=np.float32) put(tgt, w, c["start"] - s0) r_c = rest[i0:i1] - tgt # everyone else, exactly (the sum is linear) P_t = band_power(tgt, tab) P_c, P_b, P_o = band_power(r_c, tab), band_power(bed[i0:i1], tab), band_power(orig[i0:i1], tab) T_c, T_b, T_o = (threshold(P, tab, offset_db) for P in (P_c, P_b, P_o)) T_all = T_c + T_b + T_o + ath T_nb = T_c + T_o + ath onset = int(round((c["start"] - s0) * SR / HOP)) length = int(round(keep * SR / HOP)) m, share, j, band = margin(P_t, T_all, onset, length) m_nb, share_nb, _, _ = margin(P_t, T_nb, onset, length) # where the threshold at the best band comes from (a, b: the frames of the best window) a_, b_ = j, min(P_t.shape[0], j + INTEG) parts = {"bed": float(T_b[a_:b_, band].mean()), "cues": float(T_c[a_:b_, band].mean()), "original": float(T_o[a_:b_, band].mean()), "quiet": float(ath[band])} tot = sum(parts.values()) + EPS by = {k: round(v / tot, 2) for k, v in parts.items()} out.append({"id": c.get("id"), "label": c.get("label", ""), "role": c.get("role", ""), "t": c.get("t_moment"), "start": c["start"], "layer": bool(c.get("layer")), "texture": bool(c.get("texture")), "margin_db": round(m, 1), "share": round(share, 2), "margin_wo_bed_db": round(m_nb, 1), "bed_cost_db": round(m_nb - m, 1), "band_hz": [EDGES[band], EDGES[band + 1]], "masked_by": by, "class": klass(m)}) return out def klass(m): return "clear" if m >= 10.0 else "ok" if m >= 3.0 else "marginal" if m >= 0.0 else "masked" BACKDROP = ("ambience", "vehicle") # meant to sit under everything: their margin is not a problem def judged(r): """A sound whose audibility is a question: no layer (it joins its parent), no texture (quiet by design), no backdrop.""" return not r["layer"] and not r["texture"] and r.get("role") not in BACKDROP def summary(rows): real = [r for r in rows if judged(r)] cnt = {k: sum(1 for r in real if r["class"] == k) for k in ("clear", "ok", "marginal", "masked")} costs = [r["bed_cost_db"] for r in real if r["margin_wo_bed_db"] > -50] freed = [r for r in real if r["class"] in ("masked", "marginal") and r["margin_wo_bed_db"] >= 3.0] worst = sorted(real, key=lambda r: r["margin_db"])[:8] return {"n": len(real), "classes": cnt, "n_layers": sum(1 for r in rows if r["layer"]), "n_texture": sum(1 for r in rows if r["texture"] and not r["layer"]), "n_backdrop": sum(1 for r in rows if r.get("role") in BACKDROP and not r["layer"] and not r["texture"]), "bed_cost_mean_db": round(sum(costs) / len(costs), 1) if costs else 0.0, "bed_cost_max_db": round(max(costs), 1) if costs else 0.0, "freed_without_bed": [{"t": r["t"], "label": r["label"], "margin_db": r["margin_db"], "margin_wo_bed_db": r["margin_wo_bed_db"]} for r in freed], "worst": [{"t": r["t"], "label": r["label"], "role": r["role"], "margin_db": r["margin_db"], "masked_by": max(r["masked_by"], key=r["masked_by"].get), "band_hz": r["band_hz"]} for r in worst]} def text(sm, has_bed): c = sm["classes"] apart = [f"{sm[k]} {lab}" for k, lab in (("n_layers", "layers"), ("n_texture", "texture"), ("n_backdrop", "backdrop")) if sm.get(k)] lines = [f"Masking model (critical bands, 192 ms energy window): {sm['n']} sounds" f"{' (+' + ', '.join(apart) + ' not judged: they are meant to sit under or inside others)' if apart else ''}", f" clear (10 dB and more over the masked threshold) {c['clear']}, ok (3..10) {c['ok']}, " f"marginal (0..3) {c['marginal']}, masked (under it) {c['masked']}"] if has_bed: lines.append(f" the bed takes {sm['bed_cost_mean_db']:.1f} dB of margin on average (up to {sm['bed_cost_max_db']:.1f}); " f"{len(sm['freed_without_bed'])} sound(s) would be clearly audible without it") for r in sm["freed_without_bed"][:4]: lines.append(f" {r['t']:.2f}s '{str(r['label'])[:28]}': {r['margin_db']:+.1f} dB with the bed, " f"{r['margin_wo_bed_db']:+.1f} without") lines.append(" the least audible (the bed, layers and the texture layer left out):") for r in sm["worst"][:5]: lines.append(f" {r['t']:.2f}s {str(r['label'])[:28]:28s} {r['role']:8s} {r['margin_db']:+6.1f} dB " f"at {r['band_hz'][0]}-{r['band_hz'][1]} Hz, under: {r['masked_by']}") lines.append(" A textbook model of tones and noise on transients: it orders the places, it does not hear. " "Check the first ones by ear (listen_page.py).") return lines def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("resolved") ap.add_argument("clips", help="the folder of mix.py --export-clips") ap.add_argument("--gain-db", type=float, default=None, help="the level of the clips in the film (layer match + master gain); de - skills/real-sfx/scripts/mix.py (86109 bytes)
#!/usr/bin/env python3 """Turn a cue sheet into a mixed MP4 plus a standalone SFX track, report and (optionally) separate clips. python mix.py cues.json --out result/film_sfx.mp4 [--duck | --voice-safe] [--snap-beats] [--stems] [--export-clips result/clips] [--target-lufs -14] [--sfx-trim-db -2] cues.json { "video": "C:/path/film.mp4", # omit for audio-only; then give "duration": 12.0 "keep_audio": "auto", # auto | yes | no (auto = keep if the video has audio) "base_audio": ["stems/voice.wav", "stems/music.wav"], # optional: the original audio WITHOUT the synthesized # sound effects (project stems); replaces the video's own audio track "cues": [ {"t": 1.20, "label": "title wipe", "file": "C:/.../Woosh 3.wav", "role": "whoosh", "gain_db": 0, "anchor": "peak", "max_dur": 1.5}, {"t": 3.40, "label": "toggle", "uisfx": "toggle-on", "pack": "studio"}, {"t": 5.00, "label": "cut", "pick": {"role": "hit", "punchy": true, "max_dur": 1.2}}, {"t": 6.20, "label": "chosen by eye", "id": 412} ] } t seconds on the video timeline where the moment happens anchor which point of the sound lands on t: start | peak | arrive | end (default depends on the role). The default of a role that is placed by its peak is chosen per sound: one that gets loud fast (a hit with a body, a bleep, a texture) goes by its ARRIVAL (the first 60 ms within 6 dB of the loudest), one that builds to a climax (a riser, a swell) by its peak; an explicit "peak" or "arrive" is taken as it is (round 9, the sync test) gain_db offset on top of the role's normalised level (negative = quieter) max_dur cut the sound after N seconds with a short fade fade_in / fade_out seconds, to override the role's default fades loop_to repeat a short bed until it lasts N seconds (ambience under a scene) bed true: a cue of bed.py (one long dark real recording under a film whose sound is only SFX). Its level is not the role's: this script renders the film without it, as the finished master will have it, and puts the bed's own median 250 ms level at `level_dbfs` (bed.py: -54; the listener chose -56, called -50 good and -44 and louder loud) or, with `floor_db`, that many dB under the loudest 250 ms (`bed:` line of the output) fade_curve "qsin": equal-power fades, for pieces that overlap (bed.py sets it); default linear Processing, all optional, applied to the real sample before placement: fit_dur stretch/squeeze (pitch kept) so the sound lasts this many seconds; factor limited to 0.5..2 pitch semitones, -12..12, length kept (lower = heavier, higher = lighter) reverse true: play backwards (turns a hit into a swell that lands on t) lowpass / highpass cut-off in Hz (tame a harsh whoosh under a voice, thin out a boomy hit) layers list of extra cues placed relative to this one: {"dt": 0.0, "gain_db": -6, ...any cue field} pan -1 (left) .. 1 (right), constant power: a sound that follows an object across the picture mono true: both sides play the louder channel of a stereo sound; "left" / "right" pick one. A sound whose channels are in opposite phase vanishes on a phone speaker: mix.py does this itself for correlation under -0.3 (--no-mono-fix keeps them as recorded, "mono": false keeps one) Which sound: "file" (path), "id" (the number search.py printed), "uisfx" (a UI cue name), or "pick". Automatic choice: instead of "file"/"uisfx" give "pick", the same spec as search.py / picker.py. Picks are varied across the sheet (a file already used is penalised) and respect taste.json. Options that change the mix --duck dip the original audio under the SFX (sidechain): for music-led videos --voice-safe dip the SFX under speech in the original audio: for voice-over videos --snap-beats move hits/clicks to the music's beat when within --snap-tol-ms (only if the pulse is reliable) --lead-ms N shift every cue by N ms (negative = earlier), e.g. to compensate a laggy player --target-lufs X gain the final mix towards X LUFS (limited so that at most 4 dB of limiting is needed); default -14 when the video has no sound of its own, none when it has (author's balance) Writes: <out>.mp4 (video stream copied, new audio), <stem>_sfx_track.wav (SFX only, 48 kHz 24-bit), <stem>_cue_report.md, <stem>_resolved_cues.json (every cue with the file, role and anchor used), and with --stems <stem>_stem_<name>.wav, with --export-clips <dir>/sfx_NNN_role.wav + sfx_clips.json/html; with a bed also <stem>_sfx_track_nobed.wav (the sounds are judged on it: a bed fills every window). The file's true peak is checked after the AAC encode. An encoder sometimes throws ONE frame 2-4 dB above its input, which the limiter in front of it cannot see: that place is dipped by what it overshoots (about 0.1 s, a raised cosine), and the whole ceiling comes down only when the overshoot is everywhere. """ import argparse import json import re import math import shutil import subprocess import sys import tempfile from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) import beats as beatmod from common import (show_name, ROLE_ANCHOR, ROLE_TARGET_PEAK_DB, SKILL_DIR, analyse_sound, index_path, load_config, measure_loudness, require_tools, run) from common import (arrival_landmarks, arrive_offset, channel_count, load_json, louder_channel, norm_path, onset_time, stereo_fmt, venv_python, window_levels) from picker import load_index, load_taste, pick from search import uisfx_file SR = 48000 BATCH = 48 # most cue files ffmpeg is asked to open at once LIMIT = 0.891 # -1 dBFS ceiling for the limiter ROLE_FADES = {"ambience": (0.30, 0.60), "vehicle": (0.20, 0.40)} # (fade in, fade out) in seconds BEAT_ROLES = {"hit", "sub_drop", "click", "ui", "design", "glass", "coin", "data", "error"} VOICE_DEPTH = {"light": "threshold=0.05:ratio=2:attack=8:release=160", # about -3..-5 dB: textures stay heard "normal": "threshold=0.025:ratio=3.5:attack=6:release=180", # about -9 dB at the cues "deep": "threshold=0.012:ratio=8:attack=4:release=240"} # for loud sounds over speech STEMS = {"impacts": {"hit", "sub_drop", "design"}, "motion": {"whoosh", "riser", "glitch", "scifi", "camera"}, "interface": {"click", "ui", "data", "error", "glass", "coin", "paper", "cartoon", "meme", "pop", "chime", "typing", "water"}, "atmos": {"ambience", "vehicle", "foley"}} # ------------------------------------------------------------------ cue preparation def _atempo(factor): """atempo chain for any factor (each stage must stay within 0.5..2).""" parts = [] while factor > 2.0: parts.append("atempo=2.0") factor /= 2.0 while factor < 0.5: parts.append("atempo=0.5") factor /= 0.5 parts.append(f"atempo={factor:.5f}") return parts def process_chain(c, info, warns, n): """Return (ffmpeg filter fragments, info as it will be after processing).""" f, info = [], dict(info) act = info.get("active_dur") if act and act < info["duration"] - 0.15 and c.get("role") not in ("ambience", "vehicle") and not c.get("keep_tail"): cut = round(min(info["duration"], act + 0.03), 3) # padded pack file: drop the silence after the sound, f += [f"atrim=end={cut:.3f}", "asetpts=PTS-STARTPTS"] # so fit_dur, loop_to and max_dur act on real content info["duration"] = cut if c.get("reverse"): f.append("areverse") info["peak_time"] = max(0.0, info["duration"] - info["peak_time"]) info["onset_t"] = 0.0 info["arrival"] = None semis = float(c.get("pitch", 0) or 0) if semis: semis = max(-12.0, min(12.0, semis)) ratio = 2 ** (semis / 12) f += [f"asetrate={int(SR * ratio)}", f"aresample={SR}"] + _atempo(1 / ratio) if c.get("fit_dur"): want = float(c["fit_dur"]) factor = info["duration"] / want # >1 speeds up (shorter), <1 slows down (longer) if not 0.5 <= factor <= 2.0: warns.append(f"cue {n}: fit_dur {want}s needs a stretch of x{factor:.2f}, limited to 0.5..2 (pick a closer length)") factor = max(0.5, min(2.0, factor)) f += _atempo(factor) info["peak_time"] = info["peak_time"] / factor info["onset_t"] = float(info.get("onset_t") or 0.0) / factor info["duration"] = info["duration"] / factor if info.get("arrival"): info["arrival"] = {k_: v_ / factor for k_, v_ in info["arrival"].items()} if c.get("highpass"): f.append(f"highpass=f={float(c['highpass']):.0f}") if c.get("lowpass"): f.append(f"lowpass=f={float(c['lowpass']):.0f}") return f, info def expand(cues): """Flatten 'layers' into ordinary cues placed relative to their parent.""" out = [] for c in cues: out.append(c) for lay in c.get("layers", []): l = dict(lay) l["t"] = c["t"] + l.pop("dt", 0.0) l["_layer"] = True l.setdefault("label", (c.get("label", "") + " (layer)").strip()) out.append(l) return out def resolve_cue(c, cfg, index_by_path): if "uisfx" in c: f = uisfx_file(cfg, c["uisfx"], c.get("pack")) if not f: raise SystemExit(f"uisfx cue not found: {c['uisfx']} (pack {c.get('pack') or cfg['uisfx']['default_pack']})") c["_source"] = "uisfx" c.setdefault("role", "ui") else: f = Path(norm_path(c["file"])) if not f.exists(): raise SystemExit(f"file not found: {f} (was the library moved? run scripts/build_index.py)") c["_source"] = "library" rec = index_by_path.get(str(f)) if "role" not in c: c["role"] = rec["role"] if rec else "default" return Path(f) DUCK_UNDER_VOICE = "threshold=0.04:ratio=4:attack=15:release=350:makeup=1" def build_base(items, video, has_audio, dur, dst, work, match=True, duck_under=None): """Sum the given stems into one 48 kHz stereo bed of length dur and bring it to the loudness of the video's own audio (the synthesized layer that was taken out is quiet, so the match is a fraction of a dB). A base built by subtraction (unbake.py) keeps the original's level: match=False. duck_under: the items that are NOT speech dip under the items whose name says speech (a score rebuilt from stems has lost the author's sidechain).""" args, g = [], [] speech = [i for i, it in enumerate(items) if any(w in Path(str(it["file"])).stem.lower() for w in VOICE_STEM_WORDS)] if duck_under else [] for i, it in enumerate(items): args += ["-i", str(it["file"])] off, gdb = float(it.get("offset", 0.0)), float(it.get("gain_db", 0.0)) pre = (f"adelay={int(round(off * 1000))}|{int(round(off * 1000))}," if off > 0.0005 else f"atrim=start={-off:.4f},asetpts=PTS-STARTPTS," if off < -0.0005 else "") vol = f"volume={gdb:.2f}dB," if abs(gdb) > 0.01 else "" g.append(f"[{i}:a]{stereo_fmt(it['file'], SR)},{pre}{vol}apad=whole_dur={dur:.3f}," f"atrim=end={dur:.3f}[b{i}]") labels = [f"[b{i}]" for i in range(len(items))] if speech and len(speech) < len(items): keys = [f"[k{j}]" for j in range(len(speech))] outs_ = "".join(f"[v{j}]" for j in range(len(speech))) for j, i in enumerate(speech): # each speech item is heard AND keys the ducking of the rest g.append(f"[b{i}]asplit=2[v{j}][k{j}]") labels[i] = f"[v{j}]" if len(speech) > 1: g.append("".join(keys) + f"amix=inputs={len(speech)}:normalize=0:dropout_transition=0[key]") else: g.append(f"{keys[0]}anull[key]") n_k = 0 for i in range(len(items)): if i in speech: continue n_k += 1 if n_k > 1: g.append("[key]" + f"asplit={n_k}" + "".join(f"[kk{q}]" for q in range(n_k))) q = 0 for i in range(len(items)): if i in speech: continue ksrc = f"[kk{q}]" if n_k > 1 else "[key]" g.append(f"[b{i}]{ksrc}sidechaincompress={duck_under}[d{i}]") labels[i] = f"[d{i}]" q += 1 if len(items) > 1: g.append("".join(labels) + f"amix=inputs={len(items)}:normalize=0:dropout_transition=0[base]") else: g.append(f"{labels[0]}anull[base]") raw = Path(work) / f"{Path(dst).stem}__raw.wav" run_ffmpeg(args + ["@@GRAPH@@", "-map", "[base]", "-c:a", "pcm_s24le", "-ar", str(SR), str(raw)], ";\n".join(g), work) gain = 0.0 if match and has_audio and video: ref, got = measure_loudness(video)["lufs"], measure_loudness(raw)["lufs"] if ref is not None and got is not None: gain = max(-12.0, min(12.0, ref - got)) run_ffmpeg(["-i", str(raw), "-af", f"volume={gain:.2f}dB", "-c:a", "pcm_s24le", "-ar", str(SR), str(dst)]) raw.unlink(missing_ok=True) return gain VOICE_STEM_WORDS = ("voice", "vo_", "_vo", "vox", "dialog", "narrat", "speech", "speak") def lib_fields(p, by_path): """Which library and which recording a placed sound comes from (the report and the critique name them).""" c = p["c"] src = c.get("_slice_of") or str(p["file"]) if p["source"] == "uisfx": return {"library": "uisfx", "tier": "uisfx", "source_file": src} rec = by_path.get(src) or by_path.get(str(p["file"])) if rec is None: return {"library": "?", "tier": "?", "source_file": src} return {"library": rec.get("library", "?"), "tier": rec.get("tier", "main"), "source_file": src} def build_voice_key(items, dur, gain_db, dst, work): """The speech stem(s) alone at the level they have inside the rebuilt base: the key of the ducking. Music under a phrase must not duck the effects (the whole base as a key did).""" args, g = [], [] for i, it in enumerate(items): args += ["-i", str(it["file"])] off = float(it.get("offset", 0.0)) gdb = float(it.get("gain_db", 0.0)) + gain_db pre = (f"adelay={int(round(off * 1000))}|{int(round(off * 1000))}," if off > 0.0005 else f"atrim=start={-off:.4f},asetpts=PTS-STARTPTS," if off < -0.0005 else "") g.append(f"[{i}:a]{stereo_fmt(it['file'], SR)},{pre}vol - skills/real-sfx/scripts/moment_test.py (15888 bytes)
#!/usr/bin/env python3 """A test of the CHOICE of a sound for a moment of a real film: not how loud, which sound. python moment_test.py build OUT --films FILMS.json --moments MOMENTS.json [--n 5] [--seed N] [--no-page] For each moment (a place of a film where a sound belongs: the 3D layers split, the "Cha-ching", a wipe, the typing of a command) the page plays the same few seconds of the film with its own music and voice and ONE sound on the moment, the candidates blind as 1, 2, 3 ...: the film's current sound, the library's best by the person's taste and some far from them, a few named by hand, and nothing. The person says which one belongs and what is wrong with the rest. The candidates sit at ONE level (the loudest 150 ms, K-weighted, a fixed number of LU under the film's own 400 ms at that moment, a different number for a click, a whoosh, a hit ...), so that what is heard is the character of the sound and not how loud it happens to be. The level of the class is where the person put the layer in the earlier rounds (adjust_test.py): a typical sound about 12 LU under the film, a hit not more than 6. FILMS.json {"launch": {"video": "...", "base": "film_base.wav (the film's own audio)", "resolved": "..._resolved_cues.json"}} MOMENTS.json [{"id": "boom", "film": "launch", "t": 11.9, "t0": 9.9, "dur": 4.5, "title": "...", "about": "...", "class": "hit", "current": {"window": 0.12, "roles": ["hit"]}, # the cues of the film near t, together "picks": [{"role": "whoosh", "n": 4}], # the library by taste_test.choose "fixed": [{"id": "fill", "label": "SoftDrumFill 1", "cue": {"id": 177, "role": "hit"}}], "derive": [{"id": "soft", "label": "...", "gain_db": -9, "highpass": 150}], "none": true}] """ import argparse import copy import json import random import subprocess import sys import time from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) import common def _need_numpy(): try: import numpy # noqa: F401 except ImportError: vp = common.venv_python() if vp is None: sys.exit("moment_test.py needs numpy, which the skill's venv has: python scripts/listen.py install --yes") sys.exit(subprocess.run([str(vp), str(Path(__file__)), *sys.argv[1:]]).returncode) _need_numpy() import numpy as np # noqa: E402 import adjust_test as AT # noqa: E402 (read_pcm, write_wav, ff, K filters) import picker # noqa: E402 import taste_test as TT # noqa: E402 SR = AT.SR HERE = Path(__file__).parent # loudest 150 ms of the candidate, K-weighted, against the film's own 400 ms at the moment (LU) CLASS_DELTA = {"hit": -6.0, "accent": -6.0, "whoosh": -11.0, "chime": -10.0, "coin": -10.0, "click": -13.0, "ui": -13.0, "pop": -12.0, "typing": -15.0, "data": -12.0, "riser": -10.0, "default": -12.0} SPACE = 7.0 # seconds between the candidates in the sheet that renders them # ------------------------------------------------------------------------------------------------ loudness def _ir(n=16384): x = np.zeros(n) x[0] = 1.0 for b, a in (AT.K1, AT.K2): x = AT.iir(x, b, a) return x _IR = None def kpower(stereo): """K-weighted power per sample (both channels summed), by FFT convolution with the filter's impulse response.""" global _IR if _IR is None: _IR = _ir() n = len(stereo) m = 1 while m < n + len(_IR): m *= 2 H = np.fft.rfft(_IR, m) p = np.zeros(n) for c in (0, 1): y = np.fft.irfft(np.fft.rfft(stereo[:, c].astype(np.float64), m) * H, m)[:n] p += y * y return p def lufs_of(power, s, e): s, e = max(0, int(s)), min(len(power), int(e)) return -0.691 + 10.0 * np.log10(power[s:e].mean() + 1e-12) if e > s else -120.0 def loud150(stereo): """The loudest 150 ms (K-weighted), LUFS-like; a sound shorter than that is averaged over the 150 ms.""" act = np.where(np.abs(stereo).max(axis=1) > 1e-5)[0] if not len(act): return -120.0 x = stereo[max(0, act[0] - 480):act[-1] + 4800] p = kpower(x) w = int(0.15 * SR) if len(p) < w: p = np.concatenate([p, np.zeros(w - len(p))]) cs = np.concatenate([[0.0], np.cumsum(p)]) best = (cs[w:] - cs[:-w]).max() / w return -0.691 + 10.0 * np.log10(best + 1e-12) # ------------------------------------------------------------------------------------------------ candidates def current_cues(resolved, t, spec): """The film's own cues at the moment (all of them, together: the "Cha-ching" is a chime and coins and a thump).""" d = json.loads(Path(resolved).read_text(encoding="utf-8-sig")) rows = d.get("cues", d) if isinstance(d, dict) else d win = float(spec.get("window", 0.12)) roles = set(spec.get("roles") or []) out = [] for c in rows: if c.get("bed") or abs(float(c["t"]) - t) > win: continue if roles and c.get("role") not in roles: continue cue = {"file": c["file"], "role": c["role"], "dt": round(float(c["t"]) - t, 3)} if c.get("anchor"): cue["anchor"] = c["anchor"] if c.get("gain_db") is not None: cue["gain_db"] = float(c["gain_db"]) if c.get("pitch"): cue["pitch"] = c["pitch"] out.append(cue) return out def candidates_for(m, film, index, scales, rng, n_default): """[(id, label, [cue, ...] or None for silence, meta)] in a fixed order (the page shuffles them).""" cands = [] cur = [] if m.get("current") is not None: cur = current_cues(film["resolved"], float(m["t"]), m["current"]) if cur: cands.append(("cur", "как сейчас в фильме: " + " + ".join( Path(str(c["file"])).stem.split("_", 1)[-1][:34] for c in cur), cur, {"kind": "current"})) for p in m.get("picks", []): role = p["role"] if role not in TT.ROLE_SPEC: # a role the taste test has no spec for: a plain pool of it TT.ROLE_SPEC[role] = {"pool": p.get("pool") or {"role": role, "max_dur": 3.0}, "cue": {}, "wrong": None} want = int(p.get("n", n_default)) picks, pool_n = TT.choose(index, role, want, rng, scales, {str(c["file"]) for c in cur}) picks = picks[:want] # choose() always starts with the picker's first three spec_cue = dict(TT.ROLE_SPEC[role]["cue"]) spec_cue.update(p.get("cue", {})) for rec, rank in picks: cue = {"file": rec["path"], "role": p.get("as_role", role), "dt": 0.0, **spec_cue} cands.append((f"p{len(cands)}", rec["name"], [cue], {"kind": "library", "sound_id": rec["id"], "path": rec["path"], "role": role, "picker_rank": rank, "pool": pool_n})) for f in m.get("fixed", []): cue = dict(f["cue"]) cue.setdefault("dt", 0.0) cands.append((f["id"], f.get("label", f["id"]), [cue], {"kind": "fixed"})) for dv in m.get("derive", []): base = [dict(c) for c in cur] if not base: continue for c in base: c["gain_db"] = float(c.get("gain_db", 0.0)) + float(dv.get("gain_db", 0.0)) if dv.get("highpass"): c["highpass"] = dv["highpass"] if dv.get("lowpass"): c["lowpass"] = dv["lowpass"] cands.append((dv["id"], dv.get("label", dv["id"]), base, {"kind": "derived"})) if m.get("none", True): cands.append(("none", "без звука", None, {"kind": "none"})) return cands def render_candidates(cands, work, label): """One mix.py run for every candidate (each at its own time of a silent sheet), the clips of each by time.""" cues, spans = [], {} k = 0 for cid, _lab, cs, _meta in cands: if not cs: continue T = 2.0 + SPACE * k for j, c in enumerate(cs): cue = {kk: vv for kk, vv in c.items() if kk != "dt"} cue["t"] = round(T + float(c.get("dt", 0.0)), 3) cue["label"] = f"{cid}:{j}" cues.append(cue) spans[cid] = T k += 1 sheet = {"duration": 2.0 + SPACE * k + 3.0, "keep_audio": "no", "cues": cues} sp = work / f"{label}_sheet.json" sp.write_text(json.dumps(sheet, ensure_ascii=False, indent=1), encoding="utf-8") clips = work / f"{label}_clips" log = AT.run_mix(sp, work / f"{label}.mp4", ["--export-clips", str(clips), "--no-loudnorm", "--no-match-layer"], label) rows = json.loads((clips / "sfx_clips.json").read_text(encoding="utf-8")) by = {} for r in rows: cid = str(r["label"]).split(":")[0] by.setdefault(cid, []).append(r) return by, spans, clips, log # ------------------------------------------------------------------------------------------------ one moment def build_moment(m, films, out, work, index, scales, rng, n_default, with_base=False): film = films[m["film"]] t, t0, dur = float(m["t"]), float(m["t0"]), float(m["dur"]) n = int(round(dur * SR)) cands = candidates_for(m, film, index, scales, rng, n_default) if len(cands) < 3: sys.exit(f"[{m['id']}] only {len(cands)} candidate(s)") print(f"[{m['id']}] {len(cands)} candidates: " + "; ".join(f"{c[0]}={c[1][:30]}" for c in cands), flush=True) by, spans, clips, _log = render_candidates(cands, work, m["id"]) # the candidates as the skill renders them, each placed on the moment arrays = {} for cid, lab, cs, meta in cands: arr = np.zeros((n, 2), dtype=np.float32) if cs: for r in by.get(cid, []): clip = AT.read_pcm(clips / r["file"]) s = int(round((t - t0 + float(r["start"]) - spans[cid]) * SR)) if s < 0: clip = clip[-s:] s = 0 e = min(n, s + len(clip)) if e > s: arr[s:e] += clip[:e - s] arrays[cid] = arr if with_base: # the film's own music and voice under it: a fixed number of LU under the film base_full = AT.read_pcm(film["base"]) s0 = int(round(t0 * SR)) base = base_full[s0:s0 + n] if len(base) < n: base = np.pad(base, ((0, n - len(base)), (0, 0))) m_base = lufs_of(kpower(base), (t - t0 - 0.75) * SR, (t - t0 + 0.75) * SR) target = m_base + CLASS_DELTA.get(m.get("class", "default"), CLASS_DELTA["default"]) what = f"film at the moment {m_base:.1f} LUFS (400 ms), candidates at {target:.1f}" else: # clean SFX: the candidates as rendered, brought to the median of their loudness base = np.zeros((n, 2), dtype=np.float32) lv_all = sorted(v for v in (loud150(a_) for a_ in arrays.values()) if v > -100) target = max(-24.0, lv_all[len(lv_all) // 2]) # a card of quiet things (keys) is not left to the volume knob m_base = None what = f"clean sfx, candidates at {target:.1f} LUFS (the median of the card, not under -24)" for cid, lab, cs, meta in cands: lv = loud150(arrays[cid]) if lv > -100: g = 10 ** ((target - lv) / 20.0) pk = float(np.abs(arrays[cid]).max()) if pk * g > 0.89: # never over -1 dBFS: a hit that is peaky is held at its peak g = 0.89 / pk arrays[cid] = arrays[cid] * np.float32(g) meta["scaled_db"] = round(20 * np.log10(g), 1) print(f"[{m['id']}] {what}", flush=True) d = out / m["id"] d.mkdir(parents=True, exist_ok=True) pic = d / "pic.mp4" AT.ff(["-ss", f"{t0:.3f}", "-i", film["video"], "-t", f"{dur:.3f}", "-an", "-vf", "scale=-2:720", "-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-pix_fmt", "yuv420p", "-g", "30", "-fps_mode", "passthrough", "-movflags", "+faststart", pic]) files, names = [], [] for cid, lab, cs, meta in cands: wav = d / f"{cid}.wav" AT.write_wav(wav, AT.excerpt(base + arrays[cid], 0.0, dur)) mp4 = d / f"{cid}.mp4" AT.ff(["-i", pic, "-i", wav, "-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-af", "alimiter=limit=0.89:level=0:latency=1", "-c:a", "aac", "-b:a", "256k", "-shortest", mp4]) wav.unlink(missing_ok=True) files.append(str(mp4)) names.append(lab.replace("|", "/").replace(" ## ", " ")) return {"id": m["id"], "title": m["title"], "about": m.get("about", ""), "question": m.get("question") or ( ("Какой звук подходит на этот момент? Музыка и голос родные, звук один и тот же по громкости. " if with_base else "Какой звук подходит на этот момент? Только звук, без музыки и голоса, громкость выровнена. ") + "Выберите лучший, у остальных отметьте, что не так."), "files": files, "names": names, "meta": {c[0]: dict(c[3], label=c[1]) for c in cands}, "level": {"film_lufs": None if m_base is None else round(m_base, 1), "target_lufs": round(target, 1), "with_base": with_base}} def cmd_build(a): out = Path(a.out) out.mkdir(parents=True, exist_ok=True) films = json.loads(Path(a.films).read_text(encoding="utf-8-sig")) moments = json.loads(Path(a.moments).read_text(encoding="utf-8-sig")) work = out / "_work" work.mkdir(exist_ok=True) index = picker.load_index() scales = picker._scales(index) rng = random.Random(a.seed) items = [] for m in moments: items.append(build_moment(m, films, out, work, index, scales, rng, a.n, with_base=a.with_base)) (out / "moments_plan.json").write_text(json.dumps(items, ensure_ascii=False, indent=1), encoding="utf-8") print(f"plan: {out / 'moments_plan.json'}") if a.no_page: return ab = [] for it in items: ab += ["--ab", f"{it['title']} ## {it['question']} ## " + " | ".join(it["names"]), *it["files"]] cmd = [sys.executable, str(HERE / "listen_page.py"), "build", str(out / "page"), "--title", a.title, "--note", a.note, "--seed", str(a.seed), "--ab-tags", "offtheme,harsh,loud,quiet,heavy,synthetic,good", *ab] r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace") print((r.stdout + r.stderr).strip()) if r.returncode: sys.exit(r.returncode) def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) sub = ap.add_subparsers(dest="cmd", required=True) b = sub.add_parser("build") b.add_argument("out") b.add_argument("--films", required=True) b.add_argument("--moments", required=True) b.add_argument("--n", type=int, default=4, help="library sounds pe - skills/real-sfx/scripts/package.py (3415 bytes)
#!/usr/bin/env python3 """Build a clean, shareable copy of the skill: no personal paths, indexes, taste or reference analyses. python package.py --out dist/real-sfx.skill [--no-uisfx] Included: SKILL.md, README.md, config.example.json (as config.json with no libraries), scripts, references, tests, evals, vendor/package.json and (unless --no-uisfx) the CC0 uisfx sounds as mp3 + manifest, so UI cues work out of the box. Excluded: library_index.json, taste.json, listening_log.json, styles/*, library_embeddings.*, vendor/venv, vendor/models, caches, __pycache__, evals results. The result is a zip with a top folder real-sfx/, the shape Claude skill installers expect. """ import argparse import json import sys import zipfile from pathlib import Path SKILL = Path(__file__).resolve().parent.parent SKIP_DIRS = {"__pycache__", "venv", "models", "styles", "dist", ".git", "node_modules"} SKIP_FILES = {"library_index.json", "taste.json", "config.json", "library_embeddings.bin", "library_embeddings.json", "analysis_cache.json", "kind_map.json", "listening_log.json", "ambience_steady.json", "taste_ratings.json"} def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", default=str(SKILL / "dist" / "real-sfx.skill")) ap.add_argument("--no-uisfx", action="store_true") a = ap.parse_args() out = Path(a.out) out.parent.mkdir(parents=True, exist_ok=True) n = 0 with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z: for p in sorted(SKILL.rglob("*")): if not p.is_file(): continue rel = p.relative_to(SKILL) parts = set(rel.parts) if parts & SKIP_DIRS or p.name in SKIP_FILES or p.suffix in (".pyc",): continue if rel.parts[0] == "vendor": continue # handled below z.writestr(f"real-sfx/{rel.as_posix()}", p.read_bytes()) n += 1 # a neutral config: the user adds libraries with setup.py ex = SKILL / "config.example.json" cfg = ex.read_text(encoding="utf-8") if ex.exists() else json.dumps( {"libraries": [], "uisfx": {"path": "vendor/node_modules/uisfx", "default_pack": "studio"}, "skip_dir_names": ["_mister horse previews"], "index_path": "library_index.json"}, indent=2) z.writestr("real-sfx/config.json", cfg) z.writestr("real-sfx/vendor/package.json", '{"name":"real-sfx-vendor","private":true,"version":"1.0.0"}') if not a.no_uisfx: ui = SKILL / "vendor" / "node_modules" / "uisfx" if (ui / "manifest.json").exists(): for p in sorted(ui.rglob("*")): if p.is_file() and (p.suffix == ".mp3" or p.name in ("manifest.json", "LICENSE", "LICENSE-AUDIO", "README.md", "package.json")): z.writestr(f"real-sfx/vendor/node_modules/uisfx/{p.relative_to(ui).as_posix()}", p.read_bytes()) n += 1 else: print("note: uisfx is not installed here, the package will ask the user to run setup.py init --uisfx") mb = out.stat().st_size / 1e6 print(f"{out} ({n} files, {mb:.1f} MB)") if __name__ == "__main__": main() - skills/real-sfx/scripts/picker.py (17989 bytes)
"""Choose sounds from the index by role, length and character, with variety and taste memory. A spec is a dict: role required, e.g. "whoosh" target_dur preferred length in seconds (ranks by closeness; sounds can be stretched to fit) min_dur / max_dur hard limits library restrict to one library name tier "main" | "extra" | "all". Default: libraries of tier "main" first; "extra" libraries (the fallback tier of config.json) only where fewer than 3 main sounds fit like id or path of a sound whose character should be matched bright / dark True: prefer brighter or darker sounds punchy True: attack <= 40 ms query substring of folder/name """ import json import math import os import re import statistics from operator import mul as _mul import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import ROLE_TARGET_PEAK_DB, SKILL_DIR, effective_dur, family_key, index_path, load_config TASTE_PATH = Path(os.environ.get("REAL_SFX_TASTE") or SKILL_DIR / "taste.json") # (the env: the selftest) _FEATS = ("centroid", "rolloff", "low", "high", "flat", "attack_ms", "decay_ms", "duration") def load_index(): p = index_path(load_config()) if not p.exists(): sys.exit("library_index.json missing, run: python scripts/build_index.py") return json.loads(p.read_text(encoding="utf-8"))["sounds"] _EMB = None def embeddings(): """path -> 1024-number YAMNet embedding, if listen.py tag-index has been run (pure python, no numpy).""" global _EMB if _EMB is not None: return _EMB _EMB = {} jp, bp = SKILL_DIR / "library_embeddings.json", SKILL_DIR / "library_embeddings.bin" if jp.exists() and bp.exists(): import array meta = json.loads(jp.read_text(encoding="utf-8")) raw = array.array("f") raw.frombytes(bp.read_bytes()) dim = meta.get("dim", 1024) for i, pth in enumerate(meta["paths"]): v = raw[i * dim:(i + 1) * dim] n = math.sqrt(sum(x * x for x in v)) or 1.0 _EMB[pth] = [x / n for x in v] return _EMB _STEADY = None def steady_numbers(): """path -> {ripple, flutter, swing} from the cache `bed.py --scan` writes ({} when it was never run).""" global _STEADY if _STEADY is None: from common import load_steady _STEADY = load_steady() return _STEADY def load_taste(): if TASTE_PATH.exists(): return json.loads(TASTE_PATH.read_text(encoding="utf-8")) return {"ban": [], "love": [], "notes": {}} def _vec(s): return [ math.log(max(s["centroid"], 50)), math.log(max(s["rolloff"], 50)), s["low"], s["high"], s["flat"], math.log1p(s["attack_ms"]), math.log1p(s["decay_ms"]), math.log(max(effective_dur(s), 0.02)), ] def _scales(index): cols = list(zip(*[_vec(s) for s in index if "centroid" in s])) return [statistics.pstdev(c) or 1.0 for c in cols] def _passes_numbers(s, spec): """Numeric limits on measured character (attack in ms, centroid in Hz, shares 0..1) and a YAMNet tag.""" for key, field, upper in (("attack_max", "attack_ms", True), ("attack_min", "attack_ms", False), ("centroid_max", "centroid", True), ("centroid_min", "centroid", False), ("low_max", "low", True), ("low_min", "low", False), ("flat_max", "flat", True), ("flat_min", "flat", False)): lim = spec.get(key) if lim is None: continue v = s.get(field) if v is None or (v > lim if upper else v < lim): return False om = spec.get("onsets_max") if om is not None and s.get("onset_count") is not None and s["onset_count"] > om: return False # a three-click gesture or a typing take is not "a click" tag = spec.get("tag") if tag: wanted = [x.strip().lower() for x in str(tag).replace("|", ",").split(",") if x.strip()] conf = s.get("tag_scores") or [0.5] * len(s.get("tags", [])) if not any(any(t in n.lower() for t in wanted) and c >= 0.2 for n, c in zip(s.get("tags", []), conf)): return False return True # sounds of a role that are a joke or a voice, not the thing the role names: kept out of an automatic pick unless the # spec asks for them by words (query / says): a mouth pop is not a UI pop AVOID_UNLESS_ASKED = {"pop": re.compile(r"ртом|mouth|lips|губ", re.I), # a chime for "ready" must not be a "magic protection BREAKING" or an alarm "chime": re.compile(r"break|shatter|crack|smash|destroy|crash|explo|alarm|siren|fail|error|" r"denied|warning|buzzer|ломан|разбив", re.I), # the censor bleep is a joke the library files under error: round 8, "never" for one of them, "ok" for # another, and the one the person loved was Kenyset's "erreur" "error": re.compile(r"censor|цензур", re.I), # a rubber stretch or a belt creak is not a cartoon hit: round 8, three "not here" on a bouncing ball # ("растягивание какое-то") and a "never" for the belt "cartoon": re.compile(r"stretch|friction|belt|растяж", re.I)} # musical drum fills that the library also files under ui / pop / click / chime: the person's verdict in the taste test # was "барабаны какие-то / барабаны опять" (a fill as the impact of a cut they loved, so only these roles keep them out) AVOID_IN_ROLE = {r: re.compile(r"drums?\s*fills?|барабан", re.I) for r in ("ui", "pop", "click", "chime")} def find(index, ref): """Resolve an id or a path/name fragment to an index record.""" if isinstance(ref, int) or str(ref).isdigit(): return next((s for s in index if s["id"] == int(ref)), None) ref = str(ref).lower() return next((s for s in index if s["path"].lower() == ref), None) or \ next((s for s in index if ref in s["path"].lower()), None) def twins_of(paths, index=None): """The paths and every other copy of the same recording (the same dup_key in the index): a ban or a love of one copy covers them all (a recording lies in the library twice when two packs or two folders hold it).""" index = index if index is not None else load_index() by_path = {s["path"]: s for s in index} groups = {} for s in index: if s.get("dup_key"): groups.setdefault(s["dup_key"], []).append(s["path"]) out = set(paths) for p in list(paths): dk = (by_path.get(p) or {}).get("dup_key") if dk: out.update(groups.get(dk, [])) return out def rank(index, spec, used=None, taste=None, include_banned=False): """Return candidates best first as (score, record).""" used = used or {} taste = taste or load_taste() banned, loved = set(taste.get("ban", [])), set(taste.get("love", [])) sc = _scales(index) like = find(index, spec["like"]) if spec.get("like") is not None else None lv = _vec(like) if like and "centroid" in like else None emb = embeddings() if like else {} lemb = emb.get(like["path"]) if like else None cent = [s["centroid"] for s in index if "centroid" in s and spec.get("role") in s["roles"]] med_c = statistics.median(cent) if cent else 1000 out = [] dup_of = {s["path"]: s.get("dup_key") for s in index if s.get("dup_key")} used_dups = {dup_of[pth] for pth in used if pth in dup_of} # takes of one recording ("Glass Crack - 01..04") count as one family: used ones push their siblings down by_path = {s["path"]: s for s in index} fam_used = {} for pth, cnt in used.items(): r_ = by_path.get(pth) if r_: k_ = (r_["library"], family_key(r_["name"])) fam_used[k_] = fam_used.get(k_, 0) + cnt tier = spec.get("tier") for s in index: role = spec.get("role") if role and role not in s["roles"]: continue if spec.get("library") and s["library"] != spec["library"]: continue if tier in ("main", "extra") and s.get("tier", "main") != tier: continue d = effective_dur(s) # the audible length: pack files padded with silence count as short if d < spec.get("min_dur", 0) or d > spec.get("max_dur", 1e9): continue if spec.get("query"): hay_ = (s["folder"] + " " + s["name"] + " " + " ".join(s.get("aliases", []))).lower() if not any(q_.strip().lower() in hay_ for q_ in str(spec["query"]).split("|") if q_.strip()): continue # "lego|thud": any of the parts is enough if not _passes_numbers(s, spec): continue # the name guards: a sound asked for by words (query / says / like) or LOVED by the person passes them (round 8: # a soft drum fill was loved as a pop and a chime while the guard kept every drum fill out of those roles) guarded = not (spec.get("query") or spec.get("says") or spec.get("like")) and s["path"] not in loved hay_g = s["name"] + " " + s.get("folder", "") av_ = AVOID_UNLESS_ASKED.get(role) if role else None if guarded and av_ is not None and av_.search(hay_g): continue av2_ = AVOID_IN_ROLE.get(role) if role else None if guarded and av2_ is not None and av2_.search(hay_g): continue # the same protection when the pool is another role that holds these sounds too: role `ui` is ui + pop + chime, # and a mouth pop is no more a UI sound than it is a pop if guarded and any(r_ != role and r_ in s.get("roles", []) and rx_.search(hay_g) for r_, rx_ in AVOID_UNLESS_ASKED.items()): continue tag_bonus = 0.0 if spec.get("says"): # plain words always count; a YAMNet tag counts when the model was at least 30 % sure of it tconf = {t.lower(): c for t, c in zip(s.get("tags", []), s.get("tag_scores") or [0.5] * len(s.get("tags", [])))} have = set(s.get("words", [])) | set(s.get("aliases", [])) | {t for t, c in tconf.items() if c >= 0.30} # the words of its own folder and name count too ('boom' finds 'Cinematic Boom Hits') have |= set(re.findall(r"[a-zа-я0-9]{3,}", (s.get("folder", "") + " " + s.get("name", "")).lower())) groups = [[x for x in w.lower().split("|") if x] for w in str(spec["says"]).replace(",", " ").split()] if not all(any(x in have or any(x in h for h in have) for x in grp) for grp in groups): continue # the more certain the model is, the better the match (a bonus of up to 1.0) want = [x for grp in groups for x in grp] hit = [c for t, c in tconf.items() if any(w in t for w in want)] tag_bonus = min(1.0, max(hit)) if hit else 0.0 if not include_banned and s["path"] in banned: continue if like and s["id"] == like["id"]: continue score = 0.0 if (not role or s["role"] == role) else 1.0 if spec.get("target_dur"): score += 1.2 * abs(math.log(max(d, 0.02) / spec["target_dur"])) if lv and "centroid" in s: v = _vec(s) score += 0.9 * math.sqrt(sum(((a - b) / k) ** 2 for a, b, k in zip(v, lv, sc)) / len(v)) if lemb is not None and s["path"] in emb: cos = sum(a * b for a, b in zip(lemb, emb[s["path"]])) score += 1.5 * (1.0 - max(0.0, cos)) # meaning, not just spectrum if "centroid" in s and spec.get("centroid"): # the author's own sound had this brightness: the replacement of a similar timbre keeps the mix's balance score += 0.7 * abs(math.log(max(s["centroid"], 50) / max(float(spec["centroid"]), 50.0))) if "centroid" in s: if spec.get("bright"): score += 0.5 * max(0.0, math.log(med_c / max(s["centroid"], 50))) if spec.get("dark"): score += 0.5 * max(0.0, math.log(max(s["centroid"], 50) / med_c)) if spec.get("punchy") and s["attack_ms"] > 40: score += 0.4 + min(1.0, s["attack_ms"] / 400) if s.get("bumps", 0) >= 8 and d >= 0.5 and role in ("whoosh", "riser", "hit", "sub_drop") and "pulsing" not in str(spec.get("says", "")): score += 0.8 # rhythmic/tremolo texture, not a smooth swell if role == "ambience": # a floor must be steady: a recording that moves 5-8 dB about twice a second was heard as "гул" (a drone # that throbs); measured by bed.py --scan, a recording nobody has measured is not judged st_ = steady_numbers().get(s["path"]) if st_: score += min(2.0, 0.3 * max(0.0, st_["ripple"] - 3.5)) + min(1.0, 0.04 * max(0.0, st_["swing"] - 12.0)) if "peak_db" in s and role: boost = ROLE_TARGET_PEAK_DB.get(role, -10) - s["peak_db"] if boost > 8: score += min(2.0, 0.12 * (boost - 8)) # a quiet recording: its noise floor comes up with it if role in ("whoosh", "riser") and s.get("mean_db") is not None and "peak_db" in s and s.get("duration"): act_ = max(0.05, min(s["duration"], s.get("active_dur") or s["duration"])) crest = s["peak_db"] - (s["mean_db"] + 10 * math.log10(max(s["duration"], 0.05) / act_)) if crest > 28.0: score += min(0.8, 0.07 * (crest - 28.0)) # a thin swipe: all peak, no body (a crest of 35 dB) score += 1.5 * used.get(s["path"], 0) if s.get("dup_key") in used_dups and s["path"] not in used: score += 1.5 # a copy of a sound that is already used fk = (s["library"], family_key(s["name"])) if fam_used.get(fk) and s["path"] not in used: score += 0.6 * min(3, fam_used[fk]) # another take of a family that is already on the sheet if s["path"] in loved: score -= 1.0 if role and role in (taste.get("not_for") or {}).get(s["path"], ()): score += 1.2 # "not here" for this role, said by the person score -= tag_bonus if spec.get("tag") and s.get("tags"): wanted_ = [x.strip().lower() for x in str(spec["tag"]).replace("|", ",").split(",") if x.strip()] conf2 = s.get("tag_scores") - skills/real-sfx/scripts/refstyle.py (17871 bytes)
#!/usr/bin/env python3 """Set the sound of a film against a reference style, in numbers, with no scores. python refstyle.py FILM.mp4|SFX_TRACK.wav --style clean-sfx-refs [--json] python refstyle.py --export styles/mine.json --out references/profiles/mine.json (a compact, shippable copy) `critique.py --style NAME` prints the same table at the end of its scoreboard. A style is the median and the range of a handful of measures over a set of finished reference videos (`learn_style.py` writes them, `clean-sfx-refs` ships with the skill: nine SFX-led reels). Every number is measured by the SAME code on the reference and on the film: sharp rises of the level are sound events, events closer than 0.25 s are one gesture, and the table reads this film | reference: median (range) | inside / below / above It does not say that the film sounds good or bad: a film with its own music and voice is not meant to match a reel that is only sound design. It says where the film differs, and what usually moves that number. Pure python (ffmpeg only), like the rest of the measuring scripts. """ import argparse import json import math import statistics import subprocess import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import SKILL_DIR, measure_loudness GESTURE_GAP = 0.25 # events closer than this are one gesture (the critique's own pacing gap) RATE = 16000 # key, label, unit, number format, what usually moves it when the film is BELOW / ABOVE the references MEASURES = ( ("gest10", "gestures per 10 s", "", "{:.1f}", "texture.py puts small real sounds on the picture moves nobody voiced (films whose sound is only SFX)", "busier than the references: drop the weakest sounds (the pacing axis)"), ("gap_med", "gap between gestures, median", "s", "{:.2f}", "sounds crowd each other more than in the references: thin the series, give the big moments room", "the film breathes more than the references: texture.py fills holes where the picture moves"), ("gap_p90", "gap between gestures, P90", "s", "{:.2f}", "", "long holes: texture.py fills them where the picture moves; where it does not, the stillness is the " "picture's"), ("gap_max", "longest gap", "s", "{:.1f}", "", "the longest hole is longer than the references' (the pacing axis); texture.py fills it where the picture " "moves"), ("spread_db", "level spread of gestures (P90 - P10)", "dB", "{:.1f}", "the loud and the quiet sounds are close: raise the big moments, lower the ticks (the hierarchy axis)", "more spread than the references: the quietest sounds may vanish on a phone speaker"), ("typ_db", "typical gesture vs the loudest", "dB", "{:+.1f}", "most sounds sit far under the loudest one: one hit sets the level; bring the small sounds up or that hit down", "most sounds sit close to the loudest: little hierarchy"), ("first_s", "first sound", "s", "{:.2f}", "", "the first sound comes later than in the references (the hook axis)"), ("low_share", "gestures with low end", "%", "{:.0f}", "few gestures carry low end: sub_drop under the heavy hits (suggest_cues layers them)", "nearly every gesture has low end: the small sounds may be heavier than they need to be (the low-end axis)"), ("bed", "sub bed 30-100 Hz present", "% of time", "{:.0f}", "no steady low bed; the references hold one in most reels: bed.py puts a long dark real ambience under the film " "(a film whose sound is only SFX)", "a steady low bed under the film: check the low-end axis"), ("floor_db", "the quietest tenth under the loudest, dB", "dB", "{:+.1f}", "the film falls far under its own sounds between them (the references do not): bed.py puts a steady layer " "under the film; texture.py fills the holes where the picture moves", "the film never gets quiet: the references have a floor, a bed this loud may be masking the small sounds"), ("silent", "digital silence, % of time", "%", "{:.0f}", "", "stretches of digital silence (the references have none): bed.py, or a tail that rings on (see the pacing " "axis for the holes)"), ("lufs", "loudness of this file", "LUFS", "{:.1f}", "quieter than the references (the loudness axis judges the film)", "louder than the references (the loudness axis)"), ) LABELS = {k: (lab, unit, fmt, lo, hi) for k, lab, unit, fmt, lo, hi in MEASURES} # ---------------------------------------------------------------------------------------------------- measuring def _band(path, af, rate=2000): import array r = subprocess.run(["ffmpeg", "-v", "error", "-nostdin", "-i", str(path), "-vn", "-ac", "1", "-ar", str(rate), "-af", af, "-f", "s16le", "-"], capture_output=True) a = array.array("h") a.frombytes(r.stdout[: len(r.stdout) // 2 * 2]) return a def bed_share(path): """Share of the film where a steady low bed (30-100 Hz) is present: 100 ms windows within 20 dB of the strongest low moment of the file. One drop that rings for a second is a few percent; a drone under the film is most of it.""" x = _band(path, "highpass=f=30,lowpass=f=100") w = 200 if len(x) < 4 * w: return None lv = [] for i in range(0, len(x) - w + 1, w): e = math.sqrt(sum(v * v for v in x[i:i + w]) / w) / 32768.0 lv.append(20 * math.log10(e) if e > 1e-6 else -120.0) top = max(lv) if top < -70.0: return 0.0 return 100.0 * sum(1 for v in lv if v >= top - 20.0) / len(lv) def sound_events(path, full=None): """(full, full_env, events) of an audio file: the decoded track (16 kHz mono), its 10 ms envelope in dB, and the sound events (sharp rises of the level, high band and low band).""" import learn_style as L full = full if full is not None else L.decode(path) full_env = L.env_db(full) hi_env = L.env_db(L.decode(path, "highpass=f=400")) lo_env = L.env_db(L.decode(path, "lowpass=f=150")) ev = L.merge_events(L.audio_events(hi_env, lo_env, min_rise=9.0, floor=-55.0), L.audio_events(lo_env, lo_env, min_rise=10.0, floor=-45.0)) return full, full_env, ev def group_gestures(ev): """Events closer than GESTURE_GAP are one gesture: [[event, ...], ...].""" ges, cur = [], [] for e in ev: if cur and e["t"] - cur[-1]["t"] <= GESTURE_GAP: cur.append(e) else: if cur: ges.append(cur) cur = [e] if cur: ges.append(cur) return ges def gestures(path): """([{t, on, t0, on0, pk, n, low}], seconds) for one audio file, by the detector of measure(): t = the time of the loudest point of the gesture's loudest event (a riser or a lead-in starts earlier, the sync point is the hit), on = when that event came within 10 dB of its peak (its onset: what a designer puts on the picture), t0 / on0 the same for the gesture's first event, pk = its level in dBFS (the loudest 10 ms), n = events in it, low = low end.""" full, _env, ev = sound_events(path) out = [] for g in group_gestures(ev): loud = max(g, key=lambda e: e["level"]) out.append({"t": loud["t"], "on": round(max(0.0, loud["t"] - loud.get("build_ms", 0) / 1000.0), 3), "t0": g[0]["t"], "on0": round(max(0.0, g[0]["t"] - g[0].get("build_ms", 0) / 1000.0), 3), "pk": round(loud["level"], 1), "n": len(g), "low": any(e["band"] in ("lo", "both") for e in g)}) import learn_style as L return out, len(full) / L.RATE # A 250 ms window under this is digital silence. It was -55 until a bed of -54 dBFS (what the listener chose: -56 and # -50 "good", -44 "loud") counted as half silence by its own median. SILENT_DB = -70.0 def measure(path, lufs=None, with_lufs=True): """The measures of MEASURES for one audio file (a film's mp4 or an SFX track). `lufs` overrides the file's own loudness (the film's final figure when `path` is its SFX track); with_lufs=False leaves the loudness out (an SFX track is measured before the master gain: its own figure says nothing about the film).""" import learn_style as L full = L.decode(path) dur = len(full) / L.RATE if dur < 1.0: return {"dur": round(dur, 2)} full, full_env, ev = sound_events(path, full) out = {"dur": round(dur, 2), "events10": round(len(ev) / dur * 10, 2)} if not ev: out.update({"gest10": 0.0, "gap_max": round(dur, 1)}) else: ges = group_gestures(ev) times = [g[0]["t"] for g in ges] gaps = [b - a for a, b in zip([0.0] + times, times + [dur])] sg = sorted(gaps) def pct(v, q): return v[min(len(v) - 1, max(0, int(round(q * (len(v) - 1)))))] lv = [] for g in ges: # the full-band level of the gesture's loudest 10 ms i0, i1 = int((g[0]["t"] - 0.03) * 100), int((g[-1]["t"] + 0.15) * 100) + 1 seg = full_env[max(0, i0):min(len(full_env), i1 + 1)] lv.append(max(seg) if seg else -100.0) out.update({ "gest10": round(len(ges) / dur * 10, 2), "gap_med": round(statistics.median(gaps), 2), "gap_p90": round(pct(sg, 0.9), 2), "gap_max": round(max(gaps), 1), "first_s": round(times[0], 2), "low_share": round(100.0 * sum(1 for g in ges if any(e["band"] in ("lo", "both") for e in g)) / len(ges), 0), "n_gestures": len(ges)}) if len(ges) >= 6: sl = sorted(lv) out["spread_db"] = round(pct(sl, 0.9) - pct(sl, 0.1), 1) out["typ_db"] = round(statistics.median(lv) - max(lv), 1) # presence: 250 ms windows, the last half second (the fade-out of any film) left out env250 = L.env_db(full, 250) body = env250[: max(0, len(env250) - 2)] if len(body) >= 8: sb = sorted(body) out["floor_db"] = round(sb[int(0.1 * (len(sb) - 1))] - sb[-1], 1) out["silent"] = round(100.0 * sum(1 for v in body if v < SILENT_DB) / len(body), 0) b = bed_share(path) if b is not None: out["bed"] = round(b, 0) try: v = lufs if lufs is not None else (measure_loudness(path).get("lufs") if with_lufs else None) except Exception: v = None if v is not None: out["lufs"] = round(float(v), 1) return out # ---------------------------------------------------------------------------------------------------- styles def aggregate(per_ref): """{key: {median, p25, p75, min, max, n}} over the references that have the measure.""" agg = {} for k, *_ in MEASURES: v = sorted(r[k] for r in per_ref if r.get(k) is not None) if v: q = statistics.quantiles(v, n=4, method="inclusive") if len(v) >= 4 else [v[0], statistics.median(v), v[-1]] agg[k] = {"median": round(statistics.median(v), 2), "p25": round(q[0], 2), "p75": round(q[2], 2), "min": v[0], "max": v[-1], "n": len(v)} return agg def find_style(name): """$REAL_SFX_STYLES/NAME.json (a folder named by the environment: the re-sound test uses it to hand an agent the references WITHOUT the reel it is sounding), then styles/NAME.json (learned on this machine), then references/profiles/NAME.json (shipped). The first file that carries measures wins; an older style without them is returned only when nothing better exists.""" import os fallback = (None, None) where = [SKILL_DIR / "styles" / f"{name}.json", SKILL_DIR / "references" / "profiles" / f"{name}.json"] if os.environ.get("REAL_SFX_STYLES"): where.insert(0, Path(os.environ["REAL_SFX_STYLES"]) / f"{name}.json") for p in where: if p.exists(): try: d = json.loads(p.read_text(encoding="utf-8")) except ValueError: continue if d.get("measures"): return d, p if fallback[0] is None: fallback = (d, p) # an older style: the caller says it has no measures return fallback def compare(m, style): """Rows for the measures both sides have. `where`: inside (the middle half of the references), low/high (outside the middle half, still inside the references' range), BELOW/ABOVE (outside every reference).""" ref = (style or {}).get("measures") or {} rows = [] for k, label, unit, fmt, lo_hint, hi_hint in MEASURES: v, r = m.get(k), ref.get(k) if v is None or not r or r.get("n", 0) < 3: continue lo, hi, med = r["min"], r["max"], r["median"] q1, q3 = r.get("p25", lo), r.get("p75", hi) pad = max(0.05 * (hi - lo), 0.02 * abs(med), 0.05) # a hair outside the range is not "outside" if v < lo - pad: where = "BELOW" elif v > hi + pad: where = "ABOVE" elif v < q1 - 1e-9: where = "low" elif v > q3 + 1e-9: where = "high" else: where = "inside" lever = lo_hint if where in ("BELOW", "low") else hi_hint if where in ("ABOVE", "high") else "" span = max(q3 - q1, 0.05 * abs(med), 0.05) # how far out, in widths of the middle half off = 0.0 if where == "inside" else (q1 - v if where in ("BELOW", "low") else v - q3) / span rows.append({"key": k, "label": label, "unit": unit, "fmt": fmt, "value": v, "median": med, "p25": q1, "p75": q3, "min": lo, "max": hi, "n": r["n"], "where": where, "lever": lever, "off": round(off, 2)}) return rows def render(rows, style, note=None): if not rows: return [] name = style.get("name", "?") n = style.get("n_refs") or max(r["n"] for r in rows) durs = [r.get("dur") or r.get("duration") for r in style.get("per_ref", []) if r.get("dur") or r.get("duration")] span = f", {min(durs):.0f}-{max(durs):.0f} s" if durs else "" lines = [f"Against the reference style '{name}' ({n} finished videos{span}). Not scored: it says where this film " f"differs, not that it is better or worse."] lines.append(f" {'measure':38s} {'this film':>10s} {'reference: median (middle half) [range]':44s} where") for r in rows: f = r["fmt"] unit = {"": "", "%": "%"}.get(r["unit"], f" {r['unit']}") cell = f"{f.format(r['value'])}{unit}" refc = (f"{f.format(r['median'])} ({f.format(r['p25'])} .. {f.format(r['p75'])}) " f"[{f.format(r['min'])} .. {f.format(r['max'])}]") lines.append(f" {r['label']:38s} {cell:>10s} {refc:44s} {r['where']}") out = [r for r in rows if r["where"] != "inside" and r["lever"]] out.sort(key=lambda r: -r["off"]) if out: lines.append(" What usually moves these (farthest from the references first):") for r in out[:4]: sid - skills/real-sfx/scripts/review.py (5881 bytes)
#!/usr/bin/env python3 """Make one picture of the finished sound design so it can be judged by eye. python review.py result/film_sfx_resolved_cues.json result/film_sfx_sfx_track.wav --out result/review.png python review.py ... --out result/review.png --from 90 --to 120 # a window of a long film python review.py ... --out result/review.png --chunk 30 # one picture per 30 s (review_0000-0030.png ...) From top to bottom: video frames at the moments that carry a sound (placed at their time), the SFX waveform and its spectrogram with a red line at every cue, and (if the video has its own audio) the loudness of that audio. Open the PNG and check: is the first 2 s alive, is the density even, do big sounds sit on the right frames, are there long empty stretches or piles of overlapping sounds, do the low frequencies (bottom of the spectrogram) only appear where a big moment happens. Also prints a per-2-seconds density strip. A film longer than about 90 s on one picture is a red wall: use --chunk 30 (or look at one stretch with --from/--to or with zoom.py). """ import argparse import json import subprocess import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import load_json, run W = 1600 def ff(args): r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-nostdin"] + args, capture_output=True, text=True, errors="replace") if r.returncode: sys.exit("ffmpeg failed:\n" + r.stderr[-1500:]) def render(sheet, track, out, t_lo, t_hi): """One picture of the window [t_lo, t_hi] of the film.""" cues = sorted((c for c in sheet["cues"] if t_lo - 1e-6 <= c["t"] <= t_hi + 1e-6), key=lambda c: c["t"]) span = max(0.5, t_hi - t_lo) video = sheet.get("video") out = Path(out).resolve() out.parent.mkdir(parents=True, exist_ok=True) tmp = out.parent / (out.stem + "_parts") tmp.mkdir(exist_ok=True) xs = [int((c["t"] - t_lo) / span * W) for c in cues] marks = ",".join(f"drawbox=x={min(W - 2, x)}:y=0:w=2:h=ih:[email protected]:t=fill" for x in xs) or "null" wave, spec = tmp / "wave.png", tmp / "spec.png" win = ["-ss", f"{t_lo:.3f}", "-t", f"{span:.3f}"] ff(win + ["-i", str(track), "-filter_complex", f"[0:a]aformat=channel_layouts=mono,showwavespic=s={W}x170:colors=0x4ade80,{marks}", "-frames:v", "1", str(wave)]) ff(win + ["-i", str(track), "-filter_complex", f"[0:a]aformat=channel_layouts=mono,showspectrumpic=s={W}x240:legend=0:fscale=log:scale=log:color=magma," f"{marks}", "-frames:v", "1", str(spec)]) parts = [] if video and Path(video).exists() and cues: # frames at their time position; skip a frame when it would overlap the previous one fw, fh, kept, last_x = 176, 99, [], -999 for c, x in zip(cues, xs): if x - last_x >= fw + 4 and c["t"] < t_hi - 0.02: kept.append((c, x)) last_x = x if kept: inp = ["-f", "lavfi", "-i", f"color=c=0x111418:s={W}x{fh + 6}:d=1"] for i, (c, x) in enumerate(kept): inp += ["-ss", f"{max(0.0, c['t'] + 0.05):.3f}", "-i", str(video)] chain, prev = [], "[0:v]" for i, (c, x) in enumerate(kept): chain.append(f"[{i + 1}:v]setpts=PTS-STARTPTS,scale={fw}:{fh}," f"drawbox=x=0:y=0:w={fw}:h={fh}:[email protected]:t=1[f{i}]") px = max(0, min(W - fw, x - fw // 2)) chain.append(f"{prev}[f{i}]overlay=x={px}:y=3[o{i}]") prev = f"[o{i}]" strip = tmp / "strip.png" ff(inp + ["-filter_complex", ";".join(chain), "-map", prev, "-frames:v", "1", str(strip)]) parts.append(strip) parts += [wave, spec] cmd = [] for p in parts: cmd += ["-i", str(p)] ff(cmd + ["-filter_complex", "".join(f"[{i}:v]" for i in range(len(parts))) + f"vstack=inputs={len(parts)}", "-frames:v", "1", str(out)]) # density strip, 2 s buckets n = max(1, int(-(-span // 2))) buckets = [0] * n for c in cues: if not c.get("_layer"): buckets[min(n - 1, int((c["t"] - t_lo) // 2))] += 1 print(f"{t_lo:g}-{t_hi:g} s, {sum(buckets)} sounds; density per 2 s: " + " ".join(f"{b}" for b in buckets)) quiet = [f"{t_lo + i * 2:g}-{t_lo + i * 2 + 2:g}s" for i, b in enumerate(buckets) if b == 0] if quiet: print("empty windows: ", ", ".join(quiet)) print("image:", out) def main(): ap = argparse.ArgumentParser() ap.add_argument("cues") ap.add_argument("track") ap.add_argument("--out", required=True) ap.add_argument("--from", dest="t_from", type=float, help="start of the window, seconds") ap.add_argument("--to", dest="t_to", type=float, help="end of the window, seconds") ap.add_argument("--chunk", type=float, help="one picture per this many seconds (a long film)") a = ap.parse_args() sheet = load_json(a.cues) cues = sheet["cues"] dur = sheet.get("duration") or (max(c["t"] for c in cues) + 1 if cues else 1.0) if a.chunk: out = Path(a.out) t = a.t_from or 0.0 end = a.t_to or dur while t < end - 0.5: hi = min(end, t + a.chunk) render(sheet, a.track, out.with_name(f"{out.stem}_{int(t):04d}-{int(hi):04d}{out.suffix}"), t, hi) t = hi return t_lo = a.t_from or 0.0 t_hi = a.t_to or dur if t_hi - t_lo > 90 and not (a.t_from or a.t_to): print("note: a film this long on one picture is a red wall; --chunk 30 gives one picture per 30 s") render(sheet, a.track, a.out, t_lo, t_hi) if __name__ == "__main__": main() - skills/real-sfx/scripts/search.py (9716 bytes)
#!/usr/bin/env python3 """Search the indexed library by role, length and character, or list uisfx cues. search.py --role whoosh --target-dur 0.7 # closest in length first search.py --role hit --punchy --dark --limit 5 # short attack, low centroid search.py --role whoosh --like 412 --limit 5 # sounds that resemble sound #412 search.py --query "glitch" --library sfx --max-dur 1 search.py --roles # role overview with counts search.py --uisfx # all uisfx cues by category search.py --uisfx success # one cue: file in the default pack Output columns: id, library, role, length, peak, centroid (Hz, high = bright), attack (ms, low = punchy), low-end share, name. Sounds the user banned (taste.py) are hidden, loved ones are marked +. """ import argparse import json import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import SKILL_DIR, effective_dur, load_config from picker import find, load_index, load_taste, rank def uisfx_dir(cfg): d = Path(cfg["uisfx"]["path"]) return d if d.is_absolute() else SKILL_DIR / d def uisfx_manifest(cfg): p = uisfx_dir(cfg) / "manifest.json" if not p.exists(): sys.exit(f"uisfx not installed: run `npm install uisfx --prefix {SKILL_DIR / 'vendor'}`") return json.loads(p.read_text(encoding="utf-8")) def uisfx_file(cfg, cue, pack=None): pack = pack or cfg["uisfx"]["default_pack"] f = uisfx_dir(cfg) / "sounds" / pack / f"{cue}.mp3" return f if f.exists() else None # an interface cue that was not tried on its own takes the verdict of the cue it is closest to (a notification is a # success that was not asked for) UI_ALIAS = {"notification": "success", "complete": "success"} def taste_pack(taste, cue, default): """The pack the person rated best for this cue (taste.json "uisfx": {cue: {pack: verdict}}), else the default; a tie that holds the default keeps the default.""" prefs = (taste.get("uisfx") or {}).get(cue) or {} score = {"love": 2, "ok": 1} best = max((score.get(v, -1) for v in prefs.values()), default=-1) if best < 1: return default cands = sorted(p for p, v in prefs.items() if score.get(v, -1) == best) return default if default in cands else cands[0] def taste_ui_source(taste, cue): """"library" / "uisfx" / None: where the person liked this interface cue better (taste.json "ui_source").""" src = taste.get("ui_source") or {} return src.get(cue) or src.get(UI_ALIAS.get(cue)) def main(): ap = argparse.ArgumentParser() ap.add_argument("--role") ap.add_argument("--query", help="substring of folder/name, case-insensitive; 'a|b' = either") ap.add_argument("--library") ap.add_argument("--min-dur", type=float, default=0) ap.add_argument("--max-dur", type=float, default=1e9) ap.add_argument("--target-dur", type=float, help="rank by closeness to this length in seconds") ap.add_argument("--like", help="id or path of a sound whose character to match") ap.add_argument("--says", help='words it must be described by, e.g. "punchy dark heavy" (see the words column)') ap.add_argument("--bright", action="store_true") ap.add_argument("--dark", action="store_true") ap.add_argument("--punchy", action="store_true", help="attack of 40 ms or less") ap.add_argument("--attack-max", type=float, help="most ms from the first sound to the peak (punchy = 30)") ap.add_argument("--attack-min", type=float) ap.add_argument("--centroid-max", type=float, help="highest brightness in Hz (dark/heavy = under 1000)") ap.add_argument("--centroid-min", type=float) ap.add_argument("--low-min", type=float, help="least share of energy under 250 Hz, 0..1 (heavy = 0.6)") ap.add_argument("--low-max", type=float) ap.add_argument("--tag", help="a YAMNet tag it must have (needs level 2): knock, glass, thump ...; several " "with commas (thunk,thump = either); the surer the model, the higher the rank") ap.add_argument("--tier", choices=["main", "extra", "all"], help="main: only the main libraries; extra: only the fallback ones; all: both, no preference " "(default: main first, extras only where fewer than 3 main sounds fit)") ap.add_argument("--include-banned", action="store_true") ap.add_argument("--limit", type=int, default=15) ap.add_argument("--json", action="store_true") ap.add_argument("--paths", action="store_true", help="print the file path (and the YAMNet tags) under every row") ap.add_argument("--sheet", metavar="PNG", help="also draw the results as a waveform/spectrogram contact sheet") ap.add_argument("--roles", action="store_true") ap.add_argument("--uisfx", nargs="?", const="__list__") ap.add_argument("--pack") a = ap.parse_args() cfg = load_config() if a.uisfx: m = uisfx_manifest(cfg) if a.uisfx == "__list__": cats = {} for c in m["cues"]: cats.setdefault(c["category"], []).append(c["name"] + ("*" if c["loop"] else "")) for k, v in cats.items(): print(f"{k}: {', '.join(v)}") print("(* = loop) packs:", ", ".join(p if isinstance(p, str) else p.get("name", "?") for p in m["packs"])) else: f = uisfx_file(cfg, a.uisfx, a.pack) print(f if f else f"no uisfx cue '{a.uisfx}' in pack '{a.pack or cfg['uisfx']['default_pack']}'") if f and a.sheet: from common import analyse_sound from contact_sheet import render_sheet rec = dict(analyse_sound(f) or {}, id=0, path=str(f), role="ui", library="uisfx", name=a.uisfx, folder=a.pack or cfg["uisfx"]["default_pack"]) print("sheet:", render_sheet([rec], a.sheet, 1)) return index = load_index() if a.roles: counts = {} for s in index: counts[s["role"]] = counts.get(s["role"], 0) + 1 for r, n in sorted(counts.items(), key=lambda kv: -kv[1]): print(f"{r:10s} {n}") return spec = {"role": a.role, "library": a.library, "min_dur": a.min_dur, "max_dur": a.max_dur, "target_dur": a.target_dur, "bright": a.bright, "dark": a.dark, "punchy": a.punchy, "query": a.query, "says": a.says, "attack_max": a.attack_max, "attack_min": a.attack_min, "centroid_max": a.centroid_max, "centroid_min": a.centroid_min, "low_min": a.low_min, "low_max": a.low_max, "tag": a.tag, "tier": a.tier} if a.like is not None: ref = find(index, a.like) if not ref: sys.exit(f"--like: not found: {a.like}") spec["like"] = ref["id"] print(f"like [{ref['id']}] {ref['library']}/{ref['name']} centroid {ref.get('centroid')} Hz, " f"attack {ref.get('attack_ms')} ms, {ref['duration']:.2f}s") taste = load_taste() ranked = rank(index, spec, taste=taste, include_banned=a.include_banned)[: a.limit] if not ranked: print("0 sounds match.") if a.says: words_ = a.says.replace(",", " ").split() for w in words_: rest = " ".join(x for x in words_ if x != w) n = len(rank(index, dict(spec, says=rest or None), taste=taste, include_banned=a.include_banned)) print(f" without the word '{w}': {n} sound(s)") print(" --says needs EVERY word to be in a sound's plain-word description or sure YAMNet tags; " "--punchy / --dark / --bright are soft preferences and never empty the list.") else: print(" loosen --max-dur / --role / --query, or check the library name with --roles") if a.tag: print(" --tag is an AudioSet class as listen.py describe prints it (Knock, Thunk, Thump, Tick, Whoosh, " "Plop, Typing ...), matched as part of the name; --query looks into file and folder names instead") if a.sheet and ranked: from contact_sheet import render_sheet print("sheet:", render_sheet([s for _, s in ranked], a.sheet)) loved = set(taste.get("love", [])) if a.json: print(json.dumps([dict(s, score=sc) for sc, s in ranked], ensure_ascii=False, indent=1)) return for sc, s in ranked: print(f"[{s['id']:>4}]{'+' if s['path'] in loved else ' '}{s['library'][:9]:9s}{'' if s.get('tier', 'main') == 'main' else '~'} {s['role']:8s} " f"{effective_dur(s):6.2f}{'*' if effective_dur(s) < s['duration'] - 0.15 else 's'} pk{s['peak_db']:>6.1f} c{s.get('centroid', 0):>5} a{s.get('attack_ms', 0):>4} " f"lo{s.get('low', 0):.2f} {s['folder'][-24:]}/{s['name'][-42:]} [{' '.join(s.get('words', []))}]") if a.paths: tg = ", ".join(n for n, c in zip(s.get("tags", []), s.get("tag_scores") or [0.5] * len(s.get("tags", []))) if c >= 0.2) print(f" {s['path']}" + (f" tags: {tg}" if tg else "") + (f" source: {s['source']}" + (f" hit {s['hit']}/{s['hits_in_source']}" if s.get('hit') else "") if s.get("source") else "")) print(f"-- {len(ranked)} shown (a '*' after the length: the file is longer, the rest is silence)") if __name__ == "__main__": main() - skills/real-sfx/scripts/setup.py (7835 bytes)
#!/usr/bin/env python3 """First-run setup and health check, for any machine and any sound library. python setup.py check python setup.py scan "D:/Sounds" # which folders look like sound libraries? python setup.py init --library main="D:/Sounds/SFX" --library ui="D:/Sounds/UI" [--uisfx] [--index] python setup.py add-library packs "D:/More packs" [--index] `check` reports every dependency and what is missing, in plain words. `init` writes config.json (it will not overwrite an existing one unless --force) and can build the index (--index) and install the uisfx UI sound package from npm into the skill's own folder (--uisfx, ~9 MB, needs Node.js). """ import argparse import json import os import shutil import subprocess import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import AUDIO_EXT, SKILL_DIR, config_path, is_sound_file EXAMPLE = { "libraries": [], "uisfx": {"path": "vendor/node_modules/uisfx", "default_pack": "studio"}, "skip_dir_names": ["_mister horse previews"], "index_path": "library_index.json", } def tool(name): p = shutil.which(name) if not p: return None, None try: out = subprocess.run([name, "-version" if name.startswith("ff") else "--version"], capture_output=True, text=True, timeout=10).stdout.splitlines() return p, (out[0] if out else "") except Exception: return p, "" def check(): ok = True print("tools") for t, need in (("ffmpeg", True), ("ffprobe", True), ("node", False), ("npm", False)): p, v = tool(t) flag = "ok " if p else ("MISSING" if need else "missing (only needed to install uisfx)") print(f" {t:8s} {flag:8s} {v[:60] if p else ''}") ok &= bool(p) or not need print(f" python ok {sys.version.split()[0]}") cfgp = config_path() print("config") if not cfgp.exists(): print(f" {cfgp}: not found -> python setup.py init --library name=PATH --index") return False cfg = json.loads(cfgp.read_text(encoding="utf-8")) for lib in cfg.get("libraries", []): n = sum(1 for _ in Path(lib["path"]).rglob("*") if is_sound_file(_)) if Path(lib["path"]).is_dir() else None cat = "" if n is not None and any((d / c).is_file() for d in [Path(lib["path"])] + [x for x in Path(lib["path"]).iterdir() if x.is_dir()][:20] for c in ("catalog.json", "catalog.csv")): cat = ", catalog" tier = lib.get("tier", "main") off = ", DISABLED" if lib.get("enabled", True) is False else "" print(f" library {lib['name']:18s} {'NOT FOUND' if n is None else f'{n} audio files'} " f"[{tier}{cat}{off}] {lib['path']}") ok &= n is not None or lib.get("enabled", True) is False if not cfg.get("libraries"): print(" no libraries configured: only uisfx UI cues will be available") idx = Path(cfg.get("index_path", "library_index.json")) idx = idx if idx.is_absolute() else SKILL_DIR / idx if idx.exists(): d = json.loads(idx.read_text(encoding="utf-8")) print(f" index {d['count']} sounds ({idx.name})") else: print(" index MISSING -> python scripts/build_index.py") ok = False ui = Path(cfg["uisfx"]["path"]) ui = ui if ui.is_absolute() else SKILL_DIR / ui print(f" uisfx {'ok' if (ui / 'manifest.json').exists() else 'not installed -> setup.py init --uisfx'}") print(f" taste {'yes' if (SKILL_DIR / 'taste.json').exists() else 'empty'}") print(f" styles {', '.join(p.stem for p in (SKILL_DIR / 'styles').glob('*.json')) or 'none'}") return ok def scan(root, min_files): root = Path(root) if not root.is_dir(): sys.exit(f"not a folder: {root}") found = [] for top in sorted(p for p in root.iterdir() if p.is_dir()): n = size = 0 for dp, dn, fn in os.walk(top): if "previews" in dp.lower(): continue for f in fn: if is_sound_file(Path(dp) / f): n += 1 try: size += os.path.getsize(os.path.join(dp, f)) except OSError: pass if n >= min_files: found.append((top, n, size)) if not found: print(f"no folder under {root} has {min_files}+ audio files") return print(f"{'files':>6} {'MB':>7} folder (suggested option)") for top, n, size in sorted(found, key=lambda x: -x[1]): nm = "".join(ch if ch.isalnum() else "_" for ch in top.name.lower())[:24].strip("_") or "lib" print(f"{n:6d} {size / 1e6:7.0f} {top} --library {nm}=\"{top}\"") print("\nMusic folders and plugin preview audio also match: pick only the sound-effect packs.") def write_config(libs, force, tier="main"): p = config_path() if p.exists() and not force: cfg = json.loads(p.read_text(encoding="utf-8")) else: cfg = json.loads(json.dumps(EXAMPLE)) have = {l["name"]: l for l in cfg["libraries"]} for name, path in libs: if not Path(path).is_dir(): print(f"warning: {path} is not a folder (kept anyway)") have[name] = {"name": name, "path": str(path), "tier": tier} cfg["libraries"] = list(have.values()) p.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8") print(f"config written: {p} ({len(cfg['libraries'])} libraries)") def install_uisfx(): vendor = SKILL_DIR / "vendor" vendor.mkdir(exist_ok=True) if not (vendor / "package.json").exists(): (vendor / "package.json").write_text('{"name":"real-sfx-vendor","private":true,"version":"1.0.0"}', encoding="utf-8") npm = shutil.which("npm") if not npm: sys.exit("npm not found: install Node.js first (https://nodejs.org), then run this again") print("installing uisfx (CC0 UI sounds, ~9 MB) ...", flush=True) subprocess.check_call([npm, "install", "uisfx", "--prefix", str(vendor), "--no-audit", "--no-fund"]) def main(): ap = argparse.ArgumentParser() sub = ap.add_subparsers(dest="cmd", required=True) sub.add_parser("check") s = sub.add_parser("scan") s.add_argument("root") s.add_argument("--min-files", type=int, default=20) i = sub.add_parser("init") i.add_argument("--library", action="append", default=[], metavar="NAME=PATH") i.add_argument("--uisfx", action="store_true") i.add_argument("--index", action="store_true") i.add_argument("--force", action="store_true") ad = sub.add_parser("add-library") ad.add_argument("name") ad.add_argument("path") ad.add_argument("--tier", choices=["main", "extra"], default="main", help="extra = a fallback library: used only where the main libraries have nothing for a role") ad.add_argument("--index", action="store_true") a = ap.parse_args() if a.cmd == "check": sys.exit(0 if check() else 1) if a.cmd == "scan": return scan(a.root, a.min_files) if a.cmd == "init": libs = [] for item in a.library: if "=" not in item: sys.exit(f"--library expects NAME=PATH, got {item!r}") n, p = item.split("=", 1) libs.append((n.strip(), p.strip().strip('"'))) write_config(libs, a.force) if a.uisfx: install_uisfx() else: write_config([(a.name, a.path)], False, a.tier) if getattr(a, "index", False): subprocess.check_call([sys.executable, str(Path(__file__).parent / "build_index.py")]) check() if __name__ == "__main__": main() - skills/real-sfx/scripts/sheet.py (25845 bytes)
#!/usr/bin/env python3 """Edit a cue sheet from the command line: a one-line way to add, change, move and drop cues without opening the JSON (for a shell with no editor, and for scripted rounds of the self-critique loop). sheet.py new SHEET --video film.mp4 [--duration 10] an empty sheet sheet.py show SHEET one line per cue with its index (time order) sheet.py add SHEET '{"t": 1.2, "pick": {"role": "whoosh"}, "gain_db": -3}' ['{...}' ...] sheet.py add SHEET --from cues.json many cues at once (a JSON list; '-' = stdin) sheet.py add SHEET --event [email protected] --event [email protected]:0.8 moments by kind and time, routed like from_cues does sheet.py set SHEET (--at 1.2 [--label bead] | --index 7 | --label bead) gain_db=-4 pitch=2 anchor=start pick.role=click sheet.py set SHEET --label bead --unset slice fit_dur delete keys sheet.py drop SHEET (--at 1.2 | --index 7 | --label bead | --between 10 20 [--role click]) sheet.py shift SHEET --by 0.12 [--between 5 20] [--role whoosh] move cues in time sheet.py gain SHEET --db -3 [--between 5 20] [--role click] add dB to cues sheet.py move SHEET --at 1.2 --to 1.25 one cue to another time sheet.py top SHEET keep_audio=no 'base_audio=["music.wav"]' keys of the sheet itself sheet.py apply SHEET edits.json a batch (below); one write, one numbering sheet.py freeze SHEET RESOLVED.json pin the sounds a render picked (file/slice/pitch) sheet.py repick SHEET [--keep 3] [--roles click ui ...] [--dry] swap the sounds the person's taste ranks low Values are JSON when they parse as JSON (numbers, true, [0.1, 0.05]), else text. A key like pick.role writes into the pick. Setting id, file or uisfx replaces an automatic `pick` (a named sound beats an automatic choice). The sheet is kept in time order (ties by label, then as written), and `show` prints that order: an index printed by `show` is valid for every later edit. Selectors combine (--at 1.2 --label thump = the thump at 1.2 s); --at alone is a time within 30 ms and must name one cue when the command changes or drops it. `--backup` keeps SHEET.bak. apply: a JSON list of operations, every selector resolved against the sheet as it was before the batch: [{"at": 1.2, "label": "thump", "set": {"id": 800, "slice": [0.78, 0.12]}}, {"label": "bead", "gain": -3}, {"between": [5, 6], "drop": true}, {"index": 3, "unset": ["slice"]}, {"at": 2.0, "label": "whoosh", "shift": 0.04}, {"at": 3.0, "move": 3.05}] """ import argparse import json import re import shutil import subprocess import sys import tempfile from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import load_json, norm_path, read_stdin_text, read_text_any SOURCE_KEYS = ("pick", "id", "file", "uisfx") # exactly one of these names the sound of a cue def order_key(pair): n, c = pair return (float(c.get("t", 0.0)), str(c.get("label", "")), n) def load(path): p = Path(path) if not p.exists(): sys.exit(f"sheet not found: {p}") d = load_json(p) if isinstance(d, list): d = {"cues": d} d.setdefault("cues", []) d["cues"] = [c for _, c in sorted(enumerate(d["cues"]), key=order_key)] # the numbering `show` prints return d def save(path, d, backup): p = Path(path) if backup and p.exists(): shutil.copyfile(p, str(p) + ".bak") d["cues"] = [c for _, c in sorted(enumerate(d["cues"]), key=order_key)] p.write_text(json.dumps(d, ensure_ascii=False, indent=1), encoding="utf-8") def value(text): try: return json.loads(text) except ValueError: return text _ROLES = None def _index_roles(): """{id: role}, {path: role} of the library index: a cue that names a sound by id has no role of its own.""" global _ROLES if _ROLES is None: try: from picker import load_index idx = load_index() _ROLES = ({s["id"]: s["role"] for s in idx}, {s["path"]: s["role"] for s in idx}) except (SystemExit, Exception): _ROLES = ({}, {}) return _ROLES def role_of(c): r = c.get("role") or (c.get("pick") or {}).get("role") if r: return r if "uisfx" in c: return "ui" by_id, by_path = _index_roles() return by_id.get(c.get("id")) or by_path.get(str(c.get("file", ""))) def cues_from_events(specs, kinds_user=None): """--event KIND@T[:G]: the moments are routed the way from_cues routes a list (key = the real keyboard, bell = a chime ...): the same picks, the same levels, no cue to write by hand. kinds_user: the kinds the sheet's own from_cues call declared with --kind / --map (`_draft.kinds_user`), so a kind such as `chip` routes as it did.""" evs = [] for s in specs: m = re.fullmatch(r"([A-Za-z_][\w-]*)@(\d+(?:\.\d+)?)(?::(\d+(?:\.\d+)?))?", s.strip()) if not m: sys.exit(f"--event {s!r}: expected KIND@SECONDS[:GAIN], e.g. [email protected] or [email protected]:0.8") e = {"t": float(m.group(2)), "type": m.group(1)} if m.group(3): e["g"] = float(m.group(3)) evs.append(e) with tempfile.TemporaryDirectory() as tmp: ep, cp = Path(tmp) / "events.json", Path(tmp) / "cues.json" ep.write_text(json.dumps(evs), encoding="utf-8") cmd = [sys.executable, str(Path(__file__).with_name("from_cues.py")), str(ep), "--out", str(cp), "--no-check", "--no-stems", "--no-retime", "--max-rate", "100", "--fuse", "0", "--no-typing-detect"] if kinds_user: km = Path(tmp) / "kinds.json" # a file: a JSON argument is mangled by PowerShell km.write_text(json.dumps(kinds_user, ensure_ascii=False), encoding="utf-8") cmd += ["--map", str(km)] r = subprocess.run(cmd, capture_output=True, text=True, errors="replace") if r.returncode or not cp.exists(): sys.exit("from_cues could not route those events:\n" + (r.stdout + r.stderr)[-700:]) for ln in r.stdout.splitlines(): if ln.startswith(("WARN", "NOT mapped")): print(ln) got = load_json(cp)["cues"] for c in got: c.pop("_g", None) return got def fix_base_audio(d): """A path typed in Git-Bash form (/e/proj/x.wav) is not one for Windows Python: made right, and what does not exist is said at once, not at render time.""" items = d.get("base_audio") if not isinstance(items, list): return for k, it in enumerate(items): if isinstance(it, dict) and "file" in it: it["file"] = norm_path(it["file"]) f = it["file"] elif isinstance(it, str): items[k] = norm_path(it) f = re.split(r":-?\d|@-?\d", items[k])[0] else: continue if f and not Path(f).exists() and not Path(str(d.get("video", "."))).parent.joinpath(f).exists(): print(f"WARN base_audio: {f} does not exist") def select(d, index=None, at=None, label=None, between=None, role=None, id_=None, need_one=False, what="", exact_first=False): cues = d["cues"] idx = list(range(len(cues))) given = False if index is not None: given = True if not 0 <= index < len(cues): sys.exit(f"{what}index {index}: the sheet has {len(cues)} cues (0..{len(cues) - 1})") idx = [index] if at is not None: given = True idx = [i for i in idx if abs(cues[i].get("t", 0.0) - at) <= 0.03] if not idx: sys.exit(f"{what}no cue within 30 ms of t={at}") if label: given = True low_ = label.lower() sub_ = [i for i in idx if low_ in str(cues[i].get("label", "")).lower()] exact_ = [i for i in sub_ if str(cues[i].get("label", "")).lower() == low_] # a command that changes ONE cue (set, move) takes the cue whose label IS this, not the ones that merely # contain it ('monitor lands' must not catch 'monitor lands sub'); drop, gain, shift keep the substring idx = exact_ if (exact_first and exact_) else sub_ if between: given = True lo, hi = between idx = [i for i in idx if lo <= cues[i].get("t", 0.0) <= hi] if role: given = True idx = [i for i in idx if role_of(cues[i]) == role] if id_ is not None: given = True idx = [i for i in idx if cues[i].get("id") == id_] if not idx: sys.exit(f"{what}no cue matches") time_only = at is not None and index is None and not label and not between and not role and id_ is None if need_one and time_only and len(idx) > 1: # layers at one time: a time alone does not say which rows = "\n".join(" " + line(i, cues[i]) for i in idx[:8]) sys.exit(f"{what}{len(idx)} cues within 30 ms of t={at}, name one (add --label / --role / --index):\n{rows}") return idx, given def put(c, key, val): node = c parts = key.split(".") for part in parts[:-1]: node = node.setdefault(part, {}) node[parts[-1]] = val if len(parts) == 1 and parts[0] in ("id", "file", "uisfx"): # a named sound replaces an automatic choice for other in SOURCE_KEYS: if other != parts[0] and other != "pick": c.pop(other, None) c.pop("pick", None) if parts[0] == "pick" and len(parts) >= 1: for other in ("id", "file", "uisfx"): c.pop(other, None) def unset(c, key): node = c parts = key.split(".") for part in parts[:-1]: node = node.get(part) if not isinstance(node, dict): return node.pop(parts[-1], None) def line(i, c): what = c.get("uisfx") and f"uisfx:{c['uisfx']}" or c.get("id") and f"id {c['id']}" or \ c.get("file") and Path(c["file"]).name or c.get("pick") and f"pick {json.dumps(c['pick'], ensure_ascii=False)}" or "?" extra = " ".join(f"{k}={json.dumps(c[k], ensure_ascii=False)}" for k in ("gain_db", "pitch", "anchor", "slice", "fit_dur") if k in c) return f"{i:3d} t={c.get('t', 0.0):8.3f} {str(c.get('label', ''))[:22]:22s} {what[:48]:48s} {extra}" def freeze(d, resolved_path): """Pin the sounds the last render picked: every library cue gets the file (and slice, pitch) the render used.""" r = load_json(resolved_path) rc = r.get("cues", r) if isinstance(r, dict) else r pool = [c for c in rc if isinstance(c, dict) and not c.get("_layer")] lpool = [c for c in rc if isinstance(c, dict) and c.get("_layer")] done = skipped = 0 def find(p, t, label): for q in p: if abs(float(q.get("t", 0)) - t) <= 0.002 and str(q.get("label", "")) == label: return q for q in p: # a cue that was moved or relabelled since: the nearest within 20 ms if abs(float(q.get("t", 0)) - t) <= 0.02: return q return None def pin(c, match): """True when c is now a named sound (or already is one).""" if "uisfx" in c or match.get("source") == "uisfx": return True # a uisfx cue is already a name, nothing to pin src = match.get("slice_of") or match.get("file") if not src: return False c.pop("pick", None) c.pop("id", None) c["file"] = src if match.get("slice_of") and match.get("slice"): c["slice"] = match["slice"] if match.get("pitch"): c["pitch"] = match["pitch"] if match.get("role") and not c.get("role"): c["role"] = match["role"] return True for c in d["cues"]: t0 = float(c.get("t", 0)) match = find(pool, t0, str(c.get("label", ""))) if match is None: skipped += 1 else: pool.remove(match) if pin(c, match): done += 1 else: skipped += 1 # the layers of the cue (a shimmer, a sub drop under a hit) are pinned the same way: their ids drift too for lay in c.get("layers") or []: if not isinstance(lay, dict): continue lt = t0 + float(lay.get("dt", 0.0)) lm = find(lpool, lt, str(lay.get("label") or (str(c.get("label", "")) + " (layer)").strip())) if lm is None: skipped += 1 continue lpool.remove(lm) if pin(lay, lm): done += 1 else: skipped += 1 return done, skipped def apply_batch(d, ops): cues = d["cues"] chosen = [] for n, op in enumerate(ops): if not isinstance(op, dict): sys.exit(f"operation {n}: expected an object") wants_one = any(k in op for k in ("set", "unset", "drop", "move")) idx, given = select(d, op.get("index"), op.get("at"), op.get("label"), op.get("between"), op.get("role"), op.get("id"), need_one=wants_one, what=f"operation {n}: ", exact_first=any(k in op for k in ("set", "unset", "move"))) if not given and ("drop" in op): sys.exit(f"operation {n}: drop needs a selector") chosen.append((op, [cues[i] for i in idx])) drop_ids = set() for op, targets in chosen: for c in targets: for k, v in (op.get("set") or {}).items(): put(c, k, v) for k in op.get("unset") or []: unset(c, k) if "shift" in op: c["t"] = round(float(c.get("t", 0.0)) + float(op["shift"]), 4) if "gain" in op: c["gain_db"] = round(float(c.get("gain_db", 0.0)) + float(op["gain"]), 2) if "move" in op: c["t"] = round(float(op["move"]), 4) if op.get("drop"): drop_ids.add(id(c)) d["cues"] = [c for c in cues if id(c) not in drop_ids] return len(ops), len(drop_ids) def repick(d, roles=None, keep=3, dry=False): """Swap the sound of every cue whose current sound the person's taste (taste.json: love, ban, not_for) puts outside the first `keep` of its role, for the best-ranked sound of that role of a similar length and brightness. A loved sound stays; a banned one always goes; a typing key (slice), a uisfx cue and a bed are left alone. Everything else of the cue (time, gain, fit, layers) s - skills/real-sfx/scripts/speech_map.py (6261 bytes)
#!/usr/bin/env python3 """Where does the voice speak and where are the pauses? A map of the original audio. python speech_map.py film.mp4 [--cues result/film_sfx_resolved_cues.json] [--json work/speech.json] Output: speech segments and pauses (seconds). Heavy sounds belong in pauses or on the change between phrases, light ticks may sit under speech. With --cues it also says, for every cue, whether it sits in speech or in a pause and how far the nearest pause is. How: the 250-3800 Hz band of the original audio, 25 ms steps, adaptive threshold = quiet floor + 12 dB, short gaps (< 150 ms, breaths, consonants) are bridged, blips (< 150 ms) removed. Not a speech recogniser: music in that band counts as "speech". If the track is active more than ~92 % of the time it is reported as continuous content (music or room tone), where pauses are not meaningful. """ import argparse import array import json import math import subprocess import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import load_json RATE = 8000 HOP = 0.025 def band_db(path): r = subprocess.run(["ffmpeg", "-v", "error", "-nostdin", "-i", str(path), "-vn", "-ac", "1", "-ar", str(RATE), "-af", "highpass=f=250,lowpass=f=3800", "-f", "s16le", "-"], capture_output=True) a = array.array("h") a.frombytes(r.stdout[: len(r.stdout) // 2 * 2]) w = int(RATE * HOP) out = [] for i in range(0, len(a) - w + 1, w): e = math.sqrt(sum(v * v for v in a[i:i + w]) / w) / 32768.0 out.append(20 * math.log10(e) if e > 1e-5 else -100.0) return out def segments(db, bridge=0.15, minlen=0.15): if not db: return [], 0.0, -100.0 s = sorted(db) floor = s[int(0.10 * (len(s) - 1))] thr = max(floor + 12.0, -50.0) # median smoothing over 5 steps sm = [sorted(db[max(0, i - 2):i + 3])[len(db[max(0, i - 2):i + 3]) // 2] for i in range(len(db))] active = [v > thr for v in sm] segs, start = [], None for i, a in enumerate(active + [False]): if a and start is None: start = i elif not a and start is not None: segs.append([start * HOP, i * HOP]) start = None merged = [] for sg in segs: if merged and sg[0] - merged[-1][1] < bridge: merged[-1][1] = sg[1] else: merged.append(sg) merged = [s_ for s_ in merged if s_[1] - s_[0] >= minlen] ratio = sum(e - s_ for s_, e in merged) / (len(db) * HOP) if db else 0.0 return merged, ratio, thr def pauses_of(segs, dur, min_pause=0.25): out, t = [], 0.0 for s_, e in segs: if s_ - t >= min_pause: out.append([round(t, 3), round(s_, 3)]) t = e if dur - t >= min_pause: out.append([round(t, 3), round(dur, 3)]) return out def main(): ap = argparse.ArgumentParser() ap.add_argument("media") ap.add_argument("--cues") ap.add_argument("--json") ap.add_argument("--min-pause", type=float, default=0.25) ap.add_argument("--from-film", action="store_true", help="read the film's own audio even when the cue sheet names a voice stem") a = ap.parse_args() src, stem_note = a.media, None if a.cues and not a.from_film: vs_ = load_json(a.cues).get("voice_stems") or [] vs_ = [vs_] if isinstance(vs_, str) else vs_ vs_ = [v for v in vs_ if Path(v).exists()] if vs_: src = vs_[0] stem_note = (f"speech map from the voice stem {Path(src).name} named in the cue sheet (music under the " f"voice is not speech; --from-film reads the film's own audio)") print(stem_note) db = band_db(src) dur = len(db) * HOP segs, ratio, thr = segments(db) pauses = pauses_of(segs, dur, a.min_pause) srt = sorted(db) p10, p90 = (srt[int(0.1 * (len(srt) - 1))], srt[int(0.9 * (len(srt) - 1))]) if srt else (-100.0, -100.0) # the band never gets quiet: a bed (music, room tone) runs under everything and level alone cannot find pauses continuous = (ratio > 0.92 or (p90 - p10) < 15.0 or p10 > -40.0) and stem_note is None res = {"duration": round(dur, 2), "threshold_db": round(thr, 1), "active_ratio": round(ratio, 2), "quiet_floor_db": round(p10, 1), "continuous": continuous, "speech": [[round(s, 2), round(e, 2)] for s, e in segs], "pauses": pauses} print(f"{dur:.1f} s, active {ratio:.0%} of the time, {len(segs)} segments, {len(pauses)} pauses >= {a.min_pause} s") if res["continuous"]: print(f"WARNING: the speech band never goes quiet (quiet floor {p10:.0f} dB): a music or ambience bed runs " f"under the voice, so level alone cannot tell speech from pauses. The lists below are NOT reliable;") print(" look at the original spectrogram with zoom.py (voice shows as horizontal bands, " "phrases as gaps between them)") print("speech:", ", ".join(f"{s:.1f}-{e:.1f}" for s, e in res["speech"][:24]), "..." if len(segs) > 24 else "") print("pauses:", ", ".join(f"{s:.1f}-{e:.1f}" for s, e in pauses[:24]), "..." if len(pauses) > 24 else "") if a.cues: sheet = load_json(a.cues) print("\ncue placement:") for c in sorted(sheet["cues"], key=lambda c: c["t"]): if c.get("_layer"): continue t = c["t"] inside = next((s for s in segs if s[0] <= t <= s[1]), None) if inside: near = min(pauses, key=lambda p: min(abs(p[0] - t), abs(p[1] - t)), default=None) hint = f"nearest pause {near[0]:.1f}-{near[1]:.1f}" if near else "no pause" print(f" {t:7.2f}s {c.get('role', '?'):9s} UNDER SPEECH ({inside[0]:.1f}-{inside[1]:.1f}); {hint}") else: print(f" {t:7.2f}s {c.get('role', '?'):9s} in a pause") if a.json: Path(a.json).parent.mkdir(parents=True, exist_ok=True) Path(a.json).write_text(json.dumps(res, indent=1), encoding="utf-8") if __name__ == "__main__": main() - skills/real-sfx/scripts/suggest_cues.py (9295 bytes)
#!/usr/bin/env python3 """Draft a cue sheet from detected moments, following references/recipes.md. python suggest_cues.py work/moments/moments.json --out work/cues.json [--density 5] [--beats work/beats.json] The draft is a starting point, not the answer: open the frames next to it (moments.json lists them), delete what should stay quiet, and fix any moment the detector misread. It encodes the parts that are the same in every video: what to leave out, hook in the first 2 s, no two sounds smeared together, heavy moments layered, repeated roles varied in pitch, UI moments from uisfx. Options --density N sounds per 10 s of video (default 5; 'auto' = 60 % of the picture events per 10 s) --min-gap S minimum spacing between two non-layer cues (default 0.35 s) --ui MODE uisfx (default) or library: where UI moments come from --pack NAME uisfx pack for UI cues (default from config.json) --beats FILE beats.json from beats.py; cues get "beat_off_ms" so you can see what is on the pulse --no-layers never add sub/air layers """ import argparse import json import math import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import load_config, load_json KIND_BASE = {"cut": 1.0, "settle": 0.85, "onset": 0.7, "burst": 0.6} PITCH_CYCLE = [0, -2, 2, -3, 1, -1] UI_HINTS = [ # (substrings in the element hint, uisfx cue) (("toggle", "switch"), "toggle-on"), (("success", "done", "complete", "check"), "success"), (("error", "fail", "warning", "alert"), "error"), (("cart", "basket"), "add-to-cart"), (("message", "chat", "bubble", "reply"), "receive"), (("button", "cta", "click", "press"), "press"), (("notification", "toast", "badge"), "notification"), (("card", "panel", "modal", "sheet", "window", "popup"), "open"), (("menu", "dropdown", "expand", "accordion"), "expand"), (("coin", "price", "buy", "pay", "checkout"), "purchase"), (("progress", "loader", "loading", "percent"), "progress-step"), ] UI_ROTATION = ["select", "open", "expand", "check", "notification"] def ui_cue(hint, k): h = (hint or "").lower() for keys, cue in UI_HINTS: if any(x in h for x in keys): return cue return UI_ROTATION[k % len(UI_ROTATION)] def main(): ap = argparse.ArgumentParser() ap.add_argument("moments") ap.add_argument("--out", required=True) ap.add_argument("--density", default="5") ap.add_argument("--min-gap", type=float, default=0.35) ap.add_argument("--ui", choices=["uisfx", "library"], default="uisfx") ap.add_argument("--pack") ap.add_argument("--beats") ap.add_argument("--no-layers", action="store_true") a = ap.parse_args() cfg = load_config() pack = a.pack or cfg["uisfx"]["default_pack"] d = load_json(a.moments) moments = d["moments"] dur = d.get("info", {}).get("duration") or max((m["t"] for m in moments), default=0) + 1 grid = load_json(a.beats) if a.beats else None if grid and not grid.get("usable"): print("note: the beat grid is not reliable (usable=false); beat offsets are shown but should not drive decisions") if a.density == "auto": per10 = len(moments) / dur * 10 density = max(3.0, min(8.0, 0.6 * per10)) else: density = float(a.density) cap = max(2, math.ceil(density * dur / 10.0)) # --- which moments get a sound scored = [] for m in moments: s = KIND_BASE.get(m["kind"], 0.5) * (0.4 + 0.6 * m.get("strength", 0.5)) if m["t"] <= 2.0: s *= 1.3 # the hook must not be silent scored.append((s, m)) scored.sort(key=lambda x: (-x[0], x[1]["t"])) chosen = [] for s, m in scored: if len(chosen) >= cap: break if all(abs(m["t"] - c["t"]) >= a.min_gap for _, c in chosen): chosen.append((s, m)) chosen.sort(key=lambda x: x[1]["t"]) skipped = [m for _, m in scored if m not in [c for _, c in chosen]] # --- turn them into cues cues, count = [], {} # an impact on every cut turns the film into a drum machine: only the top third of the chosen cuts get one cut_ranks = sorted((m.get("pct", m.get("strength", 0)) for s, m in chosen if m["kind"] == "cut"), reverse=True) pct_cut = cut_ranks[max(0, math.ceil(len(cut_ranks) / 3) - 1)] if cut_ranks else 1.0 strong_cut_ids = {id(m) for s, m in chosen if m["kind"] == "cut" and m.get("pct", m.get("strength", 0)) >= pct_cut and m.get("strength", 0) >= 0.6} ui_k = 0 for i, (s, m) in enumerate(chosen): nxt = chosen[i + 1][1]["t"] - m["t"] if i + 1 < len(chosen) else 1.0 kind, st, t = m["kind"], m.get("strength", 0.5), m["t"] base_gain = round(-7 + 5 * st, 1) label = f"{kind} {st:.2f}" + (f" [{m['hint']}]" if m.get("hint") else "") n_role = lambda r: count.setdefault(r, 0) def vary(role): k = count[role] = count.get(role, 0) + 1 return PITCH_CYCLE[(k - 1) % len(PITCH_CYCLE)] if kind == "cut": cue = {"t": round(max(0.0, t - 0.05), 3), "label": label, "frame": m.get("frame"), "pick": {"role": "whoosh", "target_dur": round(min(0.9, max(0.3, nxt * 0.8)), 2), "max_dur": 1.2}, "gain_db": base_gain - 2} p = vary("whoosh") if p: cue["pitch"] = p cues.append(cue) if id(m) in strong_cut_ids: hit = {"t": round(t + 0.015, 3), "label": label + " impact", "frame": m.get("frame"), "pick": {"role": "hit", "punchy": True, "max_dur": 1.3}, "gain_db": base_gain} p = vary("hit") if p: hit["pitch"] = p if not a.no_layers and m.get("pct", st) >= 0.8: hit["layers"] = [{"dt": 0.0, "pick": {"role": "sub_drop", "max_dur": 1.8}, "gain_db": -7, "lowpass": 150}] cues.append(hit) elif kind == "settle": hit = {"t": round(t + 0.015, 3), "label": label, "frame": m.get("frame"), "pick": {"role": "hit", "punchy": True, "max_dur": 1.2}, "gain_db": base_gain - 1} p = vary("hit") if p: hit["pitch"] = p if not a.no_layers and m.get("pct", st) >= 0.66 and st >= 0.5: hit["layers"] = [{"dt": 0.0, "pick": {"role": "sub_drop", "max_dur": 1.5}, "gain_db": -8, "lowpass": 150}] cues.append(hit) elif kind == "onset": if not m.get("hint") and st < 0.8: continue # a weak change with no named element: a blinking indicator, a caret if a.ui == "uisfx": cues.append({"t": round(t, 3), "label": label, "frame": m.get("frame"), "uisfx": ui_cue(m.get("hint"), ui_k), "pack": pack, "gain_db": base_gain + 1}) ui_k += 1 else: cues.append({"t": round(t, 3), "label": label, "frame": m.get("frame"), "pick": {"role": "click", "max_dur": 0.6, "punchy": True}, "gain_db": base_gain}) else: # burst cue = {"t": round(max(0.0, t - 0.03), 3), "label": label, "frame": m.get("frame"), "pick": {"role": "whoosh", "target_dur": 0.4, "max_dur": 0.8}, "gain_db": base_gain - 3} p = vary("whoosh") if p: cue["pitch"] = p cues.append(cue) for c in cues: # torn paper is not a whoosh: prefer what the ears call one pk = c.get("pick") if pk and pk.get("role") == "whoosh": pk.setdefault("prefer_tag", "whoosh") if grid and grid.get("beats"): for c in cues: b = min(grid["beats"], key=lambda v: abs(v - c["t"])) c["beat_off_ms"] = round((c["t"] - b) * 1000) sheet = {"video": d.get("video"), "keep_audio": "auto", "cues": cues, "_draft": {"source": str(a.moments), "density_per_10s": density, "moments": len(moments), "chosen": len(chosen), "skipped": len(skipped)}} Path(a.out).parent.mkdir(parents=True, exist_ok=True) Path(a.out).write_text(json.dumps(sheet, ensure_ascii=False, indent=1), encoding="utf-8") hook = [c for c in cues if c["t"] <= 2.0] print(f"{len(moments)} moments -> {len(chosen)} get a sound ({len(cues)} cues incl. impacts), " f"{len(skipped)} left quiet; target {density:g} per 10 s over {dur:.1f} s") print("hook (first 2 s):", "yes at " + ", ".join(f"{c['t']:.2f}s" for c in hook) if hook else "NONE: no moment in the first 2 s, consider adding one by hand") if skipped: weak = ", ".join(f"{m['t']:.1f}s {m['kind']}" for m in skipped[:10]) print(f"left quiet (weakest/closest first): {weak}{' ...' if len(skipped) > 10 else ''}") print("->", a.out, " (review the frames, then run mix.py)") if __name__ == "__main__": main() - skills/real-sfx/scripts/taste_test.py (47134 bytes)
#!/usr/bin/env python3 """A taste test by category: ten sounds of one role, the same picture, one tap each; the answers become the skill's taste. python taste_test.py plan OUT --hosts HOSTS.json [--roles click ui ...] [-n 10] [--seed N] [--exclude-rated] python taste_test.py render OUT [--jobs 4] # one short film per sound: the picture + that sound, as mix.py places it python taste_test.py page OUT # OUT/page for `listen_page.py serve` (sections, one tap per sound) python taste_test.py results OUT [--apply] # unblind, taste_ratings.json; --apply writes taste.json (love / ban) python taste_test.py hosts VIDEO [VIDEO ...] # picture events of silent videos to choose the hosts from python taste_test.py round OUT --hosts HOSTS.json [--roles ...] [-n 8] [--title T] # the next round in one go Why. Which sound is good for a click, a transition, an impact is a matter of taste, and the taste is one person's. The library holds hundreds of sounds of a role; the skill's picker orders them by numbers (nearness in brightness, attack, length). Here the person's ears give the order directly, and what they say about ten sounds says something about the others. How the test is built (so that the answers are worth having). * One HOST picture per role: a short moment of a silent film of the person's own (a button press, a wipe, a title slam), the same in all clips of the role, so only the sound changes and the sounds can be compared with each other. hosts.json says which moment (video, start, length, the event times) and how to describe it. * Ten sounds per role: the three the picker would take first (what the skill does by default is tested too) and seven chosen to be as far from each other as possible in brightness, attack, length and weight (farthest-first), so that the ten cover the role and the taste shows along which direction it runs. One family of recordings once. * Two controls per role, marked only in the results: a REPEAT of one sound (does the same ear say the same twice; how much a single answer is worth) and ONE SOUND OF ANOTHER ROLE (a click in the whoosh set: does the picture decide, or does everything get "class"). The person is told that they are there. * The sound is placed by mix.py as the skill would place it (the role's level and anchor), no loudness gain, no layer match: the clip is the sound in the picture, nothing else. * Four verdicts, not five stars: love (take it gladly), ok, not here (a good sound, wrong for THIS picture: say what it is better for), never (not in any film). Reasons are chips (harsh, dull, long, short, loud, quiet, dirty, synthetic, cliche, off the picture). What comes out. `results` writes taste_ratings.json (personal, never packaged): per sound the verdict, the reasons and the better-for, with the sound's measured character; with --apply the "love" sounds go to taste.json `love` (the picker prefers them) and the "never" sounds to `ban` (the picker never takes them), the rest as notes. The next round can leave the rated ones out (--exclude-rated) and the answers say along which measured direction the taste runs. """ import argparse import json import math import os import random import shutil import subprocess import sys import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import SKILL_DIR, effective_dur, family_key import picker RATINGS = Path(os.environ.get("REAL_SFX_RATINGS") or SKILL_DIR / "taste_ratings.json") # (the env: the selftest) SCORE_ORDER = {"love": 2, "ok": 1, "notfit": 0, "never": -1} HERE = Path(__file__).parent # how a role is drawn from the library for the test, how its cue is given to mix.py, which role is the "wrong" control ROLE_SPEC = { "click": {"pool": {"role": "click", "max_dur": 0.9, "onsets_max": 1}, "cue": {}, "wrong": "whoosh"}, "ui": {"pool": {"role": "ui", "max_dur": 1.6, "onsets_max": 2}, "cue": {}, "wrong": "hit"}, "pop": {"pool": {"role": "pop", "max_dur": 1.3}, "cue": {}, "wrong": "riser"}, "whoosh": {"pool": {"role": "whoosh", "min_dur": 0.3, "max_dur": 2.0}, "cue": {"anchor": "peak"}, "wrong": "click"}, "hit": {"pool": {"role": "hit", "min_dur": 0.2, "max_dur": 3.5}, "cue": {"max_dur": 2.5}, "wrong": "chime"}, # 6 dB under the role's level: how the skill's event map places a sub drop (under a hit), not alone at full level "sub_drop": {"pool": {"role": "sub_drop", "min_dur": 0.4, "max_dur": 4.0}, "cue": {"max_dur": 2.5, "gain_db": -6}, "wrong": "pop"}, "chime": {"pool": {"role": "chime", "max_dur": 3.0}, "cue": {"max_dur": 2.2}, "wrong": "hit"}, "riser": {"pool": {"role": "riser", "min_dur": 1.2, "max_dur": 4.5}, "cue": {"anchor": "end"}, "wrong": "click"}, # typing: a take of typing, its first 0.7 s (the skill slices single keys; here the touch of the keys is judged) "typing": {"pool": {"role": "typing", "min_dur": 0.3, "max_dur": 8.0}, "cue": {"max_dur": 0.7}, "wrong": "whoosh"}, "glitch": {"pool": {"role": "glitch", "max_dur": 1.5}, "cue": {"max_dur": 1.0}, "wrong": "chime"}, "paper": {"pool": {"role": "paper", "max_dur": 2.0}, "cue": {"max_dur": 1.5}, "wrong": "hit"}, "data": {"pool": {"role": "data", "max_dur": 2.0}, "cue": {"max_dur": 1.5}, "wrong": "whoosh"}, "error": {"pool": {"role": "error", "max_dur": 1.5}, "cue": {"max_dur": 1.2}, "wrong": "pop"}, # a bed: a steady recording under the picture AND three fixed sounds the person already loved (the host names them), # levelled by mix.py as in a film; the "known" control is the recording heard as a hum in the first listening round "ambience": {"pool": {"role": "ambience", "min_dur": 5.0}, "cue": {}, "wrong": None, "bed": True, "known": 646, "known_label": "the old drone (heard as a hum)"}, } DEFAULT_ROLES = ["click", "ui", "pop", "whoosh", "hit", "sub_drop", "chime", "riser"] ROLE_TITLE = {"click": "Клики", "ui": "Интерфейс", "pop": "Поп / пузыри", "whoosh": "Переходы (whoosh)", "hit": "Удары", "sub_drop": "Низкие удары (sub drop)", "chime": "Успех / колокольчики", "riser": "Нарастания (riser)", "typing": "Печать", "glitch": "Глитч", "paper": "Бумага", "data": "Данные", "error": "Ошибка", "ambience": "Подложка (фон)"} HOST_CONTEXT = {"click": "click", "ui": "appear", "pop": "appear", "whoosh": "transition", "hit": "impact", "sub_drop": "impact", "chime": "success", "riser": "build", "typing": "typing", "error": "error"} PLAN_NOTE = ("В каждой категории несколько звуков на один и тот же момент картинки: меняется только звук. Оцените " "каждый: «Класс» (брать охотно), «Нормально», «Не здесь» (звук сам по себе нормальный, но к этой картинке " "не подходит: отметьте, для чего он лучше) или «Не брать» (не нужен нигде). В каждой категории есть один " "повтор и один звук для проверки теста (чужой, или тот, что вы уже слышали): это не ошибка. Можно " "отвечать по частям, ответы сохраняются на каждый тап (список разделов сверху).") # ------------------------------------------------------------------------------------------------ choosing the sounds def feat(rec, scales): return [v / s for v, s in zip(picker._vec(rec), scales)] def dist(a, b): return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b))) def families(ranked): """Best first, one record per family of takes and per duplicate.""" seen, out = set(), [] for score, rec in ranked: k = (rec.get("library"), family_key(rec["name"])) d = rec.get("dup_key") if k in seen or (d and ("dup", d) in seen): continue seen.add(k) if d: seen.add(("dup", d)) out.append((score, rec)) return out def choose(index, role, n, rng, scales, skip_paths=()): """n sounds of a role: the picker's first three, then farthest-first through the feature space.""" spec = dict(ROLE_SPEC[role]["pool"]) ranked = [(s, r) for s, r in picker.rank(index, spec) if "centroid" in r and r["path"] not in skip_paths] if ROLE_SPEC[role].get("bed"): # a bed: steady (not a throb) and not a person, an animal, a song ... from bed import AVOID, MAX_RIPPLE, MAX_SWING, _WORDS from common import load_steady, save_steady, steady_of cache = load_steady() keep = [] for s, r in ranked[:140]: nm = str(r.get("name", "")).lower() # by NAME: the folder says "City" of a recording of a rumble if any(w in nm for w in AVOID) or _WORDS.search(nm): continue st = steady_of(r, cache) if st and st["ripple"] <= MAX_RIPPLE and st["swing"] <= MAX_SWING: keep.append((s, r)) try: save_steady(cache) except OSError: pass ranked = keep fam = families(ranked) if len(fam) < n + 2: # a small role: the other takes of a family may stand in have = {r["path"] for _, r in fam} fam = fam + [x for x in ranked if x[1]["path"] not in have] main = [x for x in fam if x[1].get("tier", "main") == "main"] pool = (main if len(main) >= n + 4 else fam)[:90] # the worst of the ranking is not the point chosen = pool[:3] rest = pool[3:] vec = {id(r): feat(r, scales) for _, r in pool} while len(chosen) < n and rest: best = max(rest, key=lambda sr: (min(dist(vec[id(sr[1])], vec[id(c[1])]) for c in chosen), -sr[0])) chosen.append(best) rest.remove(best) rank_of = {r["path"]: i + 1 for i, (_, r) in enumerate(fam)} return [(r, rank_of.get(r["path"])) for _, r in chosen], len(fam) def describe(rec, rank=None, pool=None): return {"sound_id": rec["id"], "path": rec["path"], "name": rec["name"], "library": rec.get("library"), "tier": rec.get("tier", "main"), "role": rec.get("role"), "dur": round(effective_dur(rec), 2), "centroid": rec.get("centroid"), "rolloff": rec.get("rolloff"), "low": rec.get("low"), "high": rec.get("high"), "flat": rec.get("flat"), "attack_ms": rec.get("attack_ms"), "decay_ms": rec.get("decay_ms"), "picker_rank": rank, "pool": pool} # ------------------------------------------------------------------------------------------------ plan def plan_uisfx(index, key, h, rng): """A section of ONE uisfx cue in every pack (12 characters of the same meaning), plus library sounds the person already loved as anchors, so that the pack and the library can be compared by the same ear on the same picture.""" from common import load_config from search import uisfx_dir, uisfx_file cfg = load_config() packs = h.get("packs") or sorted(p.name for p in (uisfx_dir(cfg) / "sounds").iterdir() if p.is_dir()) items = [] for pk in packs: if not uisfx_file(cfg, h["cue"], pk): continue items.append({"sound": {"sound_id": None, "path": f"uisfx:{pk}/{h['cue']}", "name": f"uisfx {h['cue']} / {pk}", "library": "uisfx", "tier": "uisfx", "role": h.get("role", "ui"), "dur": None, "centroid": None, "picker_rank": None, "pool": len(packs), "pack": pk, "cue": h["cue"]}, "control": None}) by_path = {x["path"]: x for x in index} for pth in h.get("anchors", []): rec = by_path.get(pth) if rec: d_ = describe(rec, None, None) d_["anchor"] = "library favourite" items.append({"sound": d_, "control": None}) rng.shuffle(items) if len(items) >= 4: # a repeat of one of the packs, a few places later rep = rng.choice([i for i in items if i["sound"].get("pack")] or items) items.insert(min(len(items), items.index(rep) + 5), {"sound": dict(rep["sound"]), "control": "repeat"}) for k, it in enumerate(items, 1): it["n"] = k return {"role": key, "title": h.get("title") or key, "about": h.get("about", ""), "host": h, "items": items} def cmd_plan(a): out = Path(a.out) out.mkdir(parents=True, exist_ok=True) hosts = json.loads(Path(a.hosts).read_text(encoding="utf-8-sig")) roles = a.roles or [r for r in DEFAULT_ROLES if r in hosts] index = picker.load_index() scales = picker._scales(index) rng = random.Random(a.seed if a.seed is not None else time.time_ns()) rated_keys = set() if a.exclude_rated and RATINGS.exists(): rated_keys = set(json.loads(RATINGS.read_text(encoding="utf-8")).get("sounds", {})) sections = [] for role in roles: if role not in hosts: print(f"{role}: no host picture in {a.hosts}: skipped") continue if hosts[role].get("kind") == "uisfx": sec_ = plan_uisfx(index, role, hosts[role], rng) sections.append(sec_) print(f"{role}: {len(sec_['items'])} clips (uisfx {hosts[role]['cue']} in {len(sec_['items'])} versions)") continue if role not in ROLE_SPEC: print(f"{role}: no spec for this role in taste_test.py: skipped") continue skip = {k.split("::", 1)[1] for k in rated_keys if k.startswith(role + "::")} again = [] if a.reuse and RATINGS.exists(): # the same sounds in another picture: does the verdict belong to the sound or to the picture? old = [(e, k.split("::", 1)[1]) for k, e in json.loads(RATINGS.read_text(encoding="utf-8")).get("sounds", {}).items() if k.startswith(role + "::") and e.get("verdict") in SCORE_ORDER] by_path_ = {x["path"]: x for x in index} old = [(e, p_) for e, p_ in old if p_ in by_path_] old.sort(key=lambda ep: -SCORE_ORDER[ep[0]["verdict"]]) half = max(1, a.reuse // 2) chosen_old = old[:half] + old[::-1][:a.reuse - half] seen_ = set() for e, p_ in chosen_old: if p_ not in seen_: seen_.add(p_) again.append((by_path_[p_], e["meta"].get("picker_rank"), e["verdict"])) picks, pool_n = choose(index, role, max(0, a.n - len(again)), rng, scales, skip | {r["path"] for r, _, _ in again}) picks = [(r, rk, None) for r, rk in picks] picks = again + picks if len(picks) < 4: print(f"{role}: only {len(picks)} sounds fit: skipped") continue items = [] for r, rk, prev in picks: d_ = describe(r, rk, pool_n) if prev: d_["prev"] = prev # what it got in the earlier picture items.append({"sound": d_, "control": None}) # a repeat of one (not the first) sound, and - skills/real-sfx/scripts/taste.py (2547 bytes)
#!/usr/bin/env python3 """Remember what the user likes and hates, so the next video starts from their taste. taste.py ban 412 --why "too boomy under voice" # id from search.py, or a path fragment taste.py love "Woosh 3" taste.py unban 412 taste.py list taste.py clear Bans are hidden from search and auto-pick; loved sounds are ranked first (and pass the name guards of the picker). A ban or a love covers every copy of the recording (the same dup_key). Stored by file path in taste.json next to the skill, so it survives re-indexing. """ import argparse import json import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from picker import TASTE_PATH, find, load_index, load_taste, twins_of def main(): ap = argparse.ArgumentParser() ap.add_argument("action", choices=["ban", "unban", "love", "unlove", "list", "clear"]) ap.add_argument("ref", nargs="?") ap.add_argument("--why", default="") a = ap.parse_args() t = load_taste() if a.action == "list": for k in ("ban", "love"): print(f"{k} ({len(t[k])}):") for p in t[k]: note = t["notes"].get(p, "") print(" " + Path(p).name + (f" // {note}" if note else "") + f" [{p}]") return if a.action == "clear": TASTE_PATH.write_text(json.dumps({"ban": [], "love": [], "notes": {}}), encoding="utf-8") print("taste cleared") return if not a.ref: sys.exit("need an id or a path fragment") index = load_index() s = find(index, a.ref) if not s: sys.exit(f"not found in the index: {a.ref}") p = s["path"] group = sorted(twins_of([p], index)) # every copy of the recording ban, love = a.action in ("ban", "unban"), a.action in ("love", "unlove") key = "ban" if ban else "love" if a.action in ("ban", "love"): other = "love" if key == "ban" else "ban" for q in group: if q in t[other]: t[other].remove(q) if q not in t[key]: t[key].append(q) if a.why: t["notes"][p] = a.why else: for q in group: if q in t[key]: t[key].remove(q) t["notes"].pop(p, None) TASTE_PATH.write_text(json.dumps(t, ensure_ascii=False, indent=1), encoding="utf-8") print(f"{a.action}: {s['library']}/{s['folder']}/{s['name']}" + (f" (+{len(group) - 1} copies of the recording)" if len(group) > 1 else "")) if __name__ == "__main__": main() - skills/real-sfx/scripts/texture.py (15709 bytes)
#!/usr/bin/env python3 """A layer of small real sounds on the picture's small moves that nobody voiced, for films whose sound is only SFX. python texture.py work/cues.json --moments work/moments/moments.json # add the layer, write the sheet python texture.py work/cues.json --moments work/moments/moments.json --dry # only say what it would add python texture.py work/cues.json --remove # take the layer out again Why. Nine finished SFX reels (`critique.py --style clean-sfx-refs`) have a gesture about every 0.7 s and no hole longer than 2-3 s; the same pictures voiced by this skill have a gesture every 1.2-1.5 s and holes of 4-6 s, because the small moves of the picture (a settle, a small pop-in, a nudge) were left quiet on purpose. A film that is only sound design has nothing else to fill them. This script voices the quiet moves that sit in the holes, longest hole first, with a short drop or bubble from the main pack (never synthesized), a few dB under the real events. What it does and does not do * only moments of the PICTURE that no cue sits on (find_moments' bursts, onsets and settles): every sound lands on a frame where something moves, nothing is sprayed on a still picture; * only up to the pace of the references, counted the way the references are counted: GESTURES per 10 s (sounds with no pause of 0.25 s in them; `--target`, default the lower edge of the middle half of the nine reels, 9.0): a film that is dense already gets nothing, and the pacing axis counts these sounds at half weight like ticks; * cues carry `"texture": true` (and `same_source`: the variety axis does not judge them); running it again replaces the layer, `--remove` takes it out; every other cue is left exactly as it was; * a film that keeps its own music or voice is refused (the layer is for films where the sound is the SFX): `--even-with-audio` overrides, and then the sounds are left to the tonal fit and the ducking; * strong moments with no sound (a cut with no whoosh) are NOT texture: they are listed, voice them for real. """ import argparse import json import math import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import gesture_times, load_json, norm_path MAX_DUR = 0.30 # audible length of a texture sound, seconds DEFAULT_TARGET = 9.0 # gestures per 10 s: the lower edge of the middle half of the nine reference reels PITCH_CYCLE = [0, -2, 2, -1, 1, -3, 3] # kind of picture moment -> (role, extra pick keys) in turn; the first with sounds in the index is used KIND_CYCLE = { "burst": [("water", {}), ("pop", {"bright": True}), ("water", {})], "onset": [("pop", {}), ("water", {}), ("click", {"punchy": True})], "settle": [("pop", {"dark": True}), ("water", {"dark": True})], } def role_of(c): if c.get("role"): return c["role"] pk = c.get("pick") or {} if pk.get("role"): return pk["role"] if "uisfx" in c: return "ui" return "default" def gestures_per10(cues, dur): """Gestures per 10 s of a sheet: the number refstyle.py measures on the sound of the references.""" plain = [dict(c, role=role_of(c)) for c in cues if not c.get("_layer")] g = gesture_times(plain) return len(g) / max(dur, 1.0) * 10, len(g) def reference_target(): """The pace to reach: the lower edge of the middle half of the shipped reference style, else DEFAULT_TARGET.""" try: import refstyle st = refstyle.find_style("clean-sfx-refs")[0] or {} p25 = ((st.get("measures") or {}).get("gest10") or {}).get("p25") if p25: return float(p25) except Exception: pass return DEFAULT_TARGET def sfx_led(sheet, video): """True when the film's sound is only the SFX: no original audio kept, or an original that is silent.""" ka = sheet.get("keep_audio", "auto") if ka in ("no", False, 0): return True, "keep_audio is off" if sheet.get("base_audio"): return False, "the sheet has base_audio (music or voice stems)" if not video or not Path(video).exists(): return True, "no video to look at" try: from find_moments import audio_level, probe info = probe(video) if not info.get("has_audio"): return True, "the video has no audio" lvl = audio_level(video) if lvl is None or lvl < -50.0: return True, f"the video's own audio is silent ({lvl} dB)" if lvl is not None else "the video's audio is silent" return False, f"the video's own audio is {lvl:.0f} dB mean (music or voice)" except Exception: return True, "audio not measurable" FALLBACK = [("click", {"punchy": True})] # a library with no drops and no bubbles still has clicks def spec_options(index, kind, k): """The (role, pick spec) for the k-th texture sound of this kind of moment: the cycle's turn if the index has sounds for it, else the next option, else a click; None when the library has nothing short enough.""" from picker import rank cyc = KIND_CYCLE[kind] order = [cyc[(k + step) % len(cyc)] for step in range(len(cyc))] + FALLBACK for role, extra in order: spec = {"role": role, "max_dur": MAX_DUR, "min_dur": 0.03, **extra} if rank(index, spec): return role, spec return None, None def moments_of(args, sheet, sheet_dir): if args.moments: p = Path(args.moments) if not p.is_file(): sys.exit(f"--moments: {p} not found (find_moments.py FILM --out work/moments writes moments.json)") d = load_json(p) return d["moments"], (d.get("info") or {}).get("duration") vid = sheet.get("video") if not vid: sys.exit("no --moments and the sheet names no video: run find_moments.py on the film first") v = Path(norm_path(vid)) if not v.is_absolute() and not v.exists(): v = sheet_dir / v if not v.exists(): sys.exit(f"the sheet's video {v} was not found; pass --moments") from find_moments import probe, visual_moments print(f"moments: measuring the picture of {v.name} ...", flush=True) moms, _ = visual_moments(str(v), max_other=80) return moms, probe(str(v))["duration"] def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("sheet", help="the cue sheet (work/cues.json) the layer is added to") ap.add_argument("--moments", help="moments.json of find_moments.py (measured from the sheet's video if omitted)") ap.add_argument("--target", type=float, default=None, help="gestures per 10 s to reach (default: the lower edge of the middle half of the reference " "reels, 9.0; the references run 6.9-15.1)") ap.add_argument("--max-per10", type=float, default=4.0, help="at most this many texture sounds per 10 s") ap.add_argument("--level", type=float, default=-2.0, help="gain_db of a texture sound at full strength, relative to its role's level (weaker moves: " "up to 4 dB lower)") ap.add_argument("--min-hole", type=float, default=0.9, help="only fill holes (seconds between the sounds around) at least this long") ap.add_argument("--min-strength", type=float, default=0.2, help="ignore picture moves weaker than this") ap.add_argument("--max-strength", type=float, default=0.7, help="a stronger move than this is not texture: it is listed, voice it for real") ap.add_argument("--kinds", default="burst,onset,settle", help="moment kinds that may get a texture sound") ap.add_argument("--dry", action="store_true", help="say what would be added, write nothing") ap.add_argument("--remove", action="store_true", help="take the texture layer out of the sheet") ap.add_argument("--even-with-audio", action="store_true", help="add the layer although the film keeps its own music or voice") ap.add_argument("--no-pitch", action="store_true", help="no semitone steps between repeats") a = ap.parse_args() sp = Path(a.sheet) if not sp.exists(): sys.exit(f"sheet not found: {sp}") sheet = load_json(sp) if isinstance(sheet, list): sheet = {"cues": sheet} cues = sheet.setdefault("cues", []) old = [c for c in cues if c.get("texture")] base = [c for c in cues if not c.get("texture")] if a.remove: sheet["cues"] = base sheet.pop("_texture", None) if not a.dry: sp.write_text(json.dumps(sheet, ensure_ascii=False, indent=1), encoding="utf-8") print(f"removed {len(old)} texture sound(s); {len(base)} cues remain" + (" (dry run)" if a.dry else "")) return video = sheet.get("video") if video: v_ = Path(norm_path(video)) video = str(v_ if v_.is_absolute() or v_.exists() else sp.parent / v_) led, why = sfx_led(sheet, video) if not led and not a.even_with_audio: sys.exit(f"not added: {why}. The texture layer is for films whose sound is only SFX (the references it follows " f"are such films); over music or voice it clutters. --even-with-audio adds it anyway.") moms, mdur = moments_of(a, sheet, sp.parent) dur = sheet.get("duration") or mdur or (max([c["t"] for c in base] + [m["t"] for m in moms]) + 1.0) kinds = {k.strip() for k in a.kinds.split(",") if k.strip()} quiet = sheet.get("quiet") or [] in_quiet = lambda t: any(q[0] <= t <= q[1] for q in quiet) parents = [c for c in base if not c.get("_layer") and not c.get("bed")] times = sorted(float(c["t"]) for c in parents) if len(parents) < 3: sys.exit(f"not added: the sheet has {len(parents)} real cue(s). The texture layer goes under real events; " f"voice the film first (from_cues.py / suggest_cues.py), then add it.") target = a.target if a.target is not None else reference_target() w0, n_ev0 = gestures_per10(base, dur) cap = int(math.floor(a.max_per10 * max(dur, 10.0) / 10.0 + 1e-9)) need = int(math.ceil(max(0.0, target - w0) * max(dur, 1.0) / 10.0 - 1e-9)) n_add = min(need, cap) # candidates: moves of the picture that no cue sits on (the critique's own 0.18 s), not in a quiet range, not # inside a run of typing, not at the very start or end typing = [float(c["t"]) for c in parents if role_of(c) == "typing" or str(c.get("label", "")).lower().startswith("key")] def in_typing(t): return any(abs(t - x) <= 0.35 for x in typing) cand, strong_cuts, strong_moves = [], [], [] for m in moms: t, kind, st = float(m["t"]), m["kind"], float(m.get("strength", 0.5)) if any(abs(c - t) <= 0.18 for c in times): continue if kind == "cut": if m.get("pct", st) >= 0.5 and not in_quiet(t): strong_cuts.append(t) continue if kind not in kinds or in_quiet(t) or in_typing(t): continue if st > a.max_strength: strong_moves.append((t, kind)) # the coverage axis calls these a hole: not texture continue if st < a.min_strength or t < 0.05 or t > dur - 0.25: continue cand.append(m) chosen = [] taken = list(times) for _ in range(n_add): pts = sorted(taken + [0.0, float(dur)]) best, best_s = None, -1.0 for m in cand: if m in chosen: continue t = float(m["t"]) prev = max(p for p in pts if p <= t) nxt = min(p for p in pts if p > t) gap = nxt - prev clear = min(t - prev, nxt - t) if gap < a.min_hole or clear < 0.25: continue s = gap + 0.6 * float(m.get("strength", 0.5)) + 0.3 * min(clear, 1.0) if s > best_s: best, best_s = m, s if best is None: break chosen.append(best) taken.append(float(best["t"])) chosen.sort(key=lambda m: m["t"]) # sounds: from the index, short, by the kind of the move index = [] if chosen: try: from picker import load_index index = load_index() except SystemExit as ex: sys.exit(str(ex)) turn, new, skipped = {}, [], [] use_pitch = led and not a.no_pitch for i, m in enumerate(chosen): kind = m["kind"] k = turn.get(kind, 0) role, spec = spec_options(index, kind, k) if role is None: skipped.append(m) continue turn[kind] = k + 1 st = float(m.get("strength", 0.5)) c = {"t": round(float(m["t"]), 3), "label": f"texture {kind} {st:.2f}", "frame": m.get("frame"), "pick": spec, "gain_db": round(a.level - 4.0 * (1.0 - min(1.0, st)), 1), "texture": True, "same_source": True} if use_pitch and PITCH_CYCLE[i % len(PITCH_CYCLE)]: c["pitch"] = PITCH_CYCLE[i % len(PITCH_CYCLE)] if not c["frame"]: c.pop("frame") new.append(c) after = base + new w1, n_ev1 = gestures_per10(after, dur) print(f"pace: {w0:.1f} gestures per 10 s ({n_ev0} in {dur:.1f} s); target {target:g}, " f"cap {cap} texture sounds" + (f" ({len(old)} earlier ones replaced)" if old else "")) print(f"film: {'only SFX' if led else 'keeps its own audio'} ({why})") print(f"candidates: {len(cand)} unvoiced moves of the picture; holes of {a.min_hole:g} s and more are filled " f"longest first") if not new: if w0 >= target: print("nothing added: the film is at or above the target pace already") elif not cand: print("nothing added: no unvoiced move of the picture is strong enough (--min-strength) or all sit " "beside a sound") else: print("nothing added: no unvoiced move sits in a hole (--min-hole) or the library has no short sound") else: for c in new: print(f" {c['t']:7.2f}s {c['pick']['role']:6s} {c['gain_db']:+5.1f} dB" f"{' ' + format(c['pitch'], '+d') + ' st' if c.get('pitch') else ''} {c['label']}") print(f"added {len(new)}: pace {w0:.1f} -> {w1:.1f} gestures per 10 s") if skipped: print(f"no short sound in the library for {len(skipped)} move(s) of kind " f"{', '.join(sorted({m['kind'] for m in skipped}))}: left quiet") if strong_cuts or strong_moves: parts_ = [f"{t:.2f}s cut" for t in sorted(strong_cuts)] + [f"{t:.2f}s {k}" for t, k in sorted(strong_moves)] print(f"NOT texture: {len(parts_)} strong moment(s) have no sound ({', '.join(parts_[:8])}" f"{' ...' if len(parts_) > 8 else ''}): a small sound there is a hole, not a texture; voice them for " f"real (sheet.py add a whoosh - skills/real-sfx/scripts/tonal.py (7347 bytes)
#!/usr/bin/env python3 """Does a pitched sound sit in the key of the music under it? A chime, a pop, a UI blip over a tonal score is either a chord tone or a wrong note; a semitone or two of retuning decides which. python tonal.py SOUND.wav [--music score.wav --at 12.4] the pitches of a sound (and what the score has there) python tonal.py --id 63 --music bed.wav --at 25.84 the same for a library sound by its id mix.py does this by itself for the tonal roles (chime, pop, glass, coin, ui) when the sheet names the score (`_draft.music_ref`, written by from_cues; --music-ref FILE): the sound is retuned by up to 2 whole semitones plus the cents that put its strongest partial exactly on its note (so at most 2.5 st in all; a sound that is 40 cents flat is put on the note) when that puts its strong partials on the pitch classes the music holds at that moment and takes them off the ones a semitone beside a held note. Noise has no pitch and is left alone. How: the partials are peaks of the 8192-point spectrum of the sound's loudest 0.5 s (80-3000 Hz, 12 dB over the median); the music is a chroma (energy per pitch class, 80-2000 Hz) of 0.9 s from the moment on. Importable: sound_partials(path), chroma(path, t0, dur), best_shift(partials, chroma) -> (shift, gain, why). """ import argparse import array import math import subprocess import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import _fft NOTES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] N = 8192 RATE = 16000 _CACHE = {} def midi_name(m): k = int(round(m)) return f"{NOTES[k % 12]}{k // 12 - 1}" def _decode(path, t0=0.0, dur=None): cmd = ["ffmpeg", "-v", "error", "-nostdin"] if t0 > 0: cmd += ["-ss", f"{t0:.3f}"] if dur: cmd += ["-t", f"{dur:.3f}"] cmd += ["-i", str(path), "-vn", "-ac", "1", "-ar", str(RATE), "-f", "s16le", "-"] p = subprocess.run(cmd, capture_output=True) a = array.array("h") a.frombytes(p.stdout[: len(p.stdout) // 2 * 2]) return a def _mags(seg): n = N seg = list(seg[:n]) + [0] * max(0, n - len(seg)) re_ = [seg[k] * (0.5 - 0.5 * math.cos(2 * math.pi * k / (n - 1))) for k in range(n)] im_ = [0.0] * n _fft(re_, im_) return [math.hypot(re_[k], im_[k]) for k in range(n // 2)] def sound_partials(path, max_partials=3): """The strongest steady partials: [(midi float, weight)], weights sum to 1. [] for a noise (no pitch).""" key = ("p", str(path)) if key in _CACHE: return _CACHE[key] a = _decode(path, 0.0, 1.5) if len(a) < 800: _CACHE[key] = [] return [] w = 8000 # the loudest half second best, bi = -1.0, 0 for i in range(0, max(1, len(a) - w), 1600): e = sum(v * v for v in a[i:i + w]) if e > best: best, bi = e, i mags = _mags(a[bi:bi + w]) lo, hi = int(80 * N / RATE), int(3000 * N / RATE) band = mags[lo:hi] if not band or max(band) <= 0: _CACHE[key] = [] return [] med = sorted(band)[len(band) // 2] or 1e-9 top = max(band) peaks = [] for k in range(lo + 1, hi - 1): m = mags[k] if m >= mags[k - 1] and m > mags[k + 1] and m >= 4.0 * med and m >= 0.12 * top: a0, b0, c0 = mags[k - 1], m, mags[k + 1] d = 0.5 * (a0 - c0) / (a0 - 2 * b0 + c0) if (a0 - 2 * b0 + c0) != 0 else 0.0 f = (k + d) * RATE / N peaks.append((m, f)) peaks.sort(reverse=True) chosen = [] for m, f in peaks: if all(abs(12 * math.log2(f / g)) > 0.6 for _, g in chosen): chosen.append((m, f)) if len(chosen) >= max_partials: break if not chosen: _CACHE[key] = [] return [] tot = sum(m for m, _ in chosen) out = [(69.0 + 12.0 * math.log2(f / 440.0), m / tot) for m, f in chosen] _CACHE[key] = out return out def chroma(path, t0, dur=0.9): """Energy per pitch class (12 values, largest = 1.0) of [t0, t0 + dur] of a music file, 80-2000 Hz.""" key = ("c", str(path), round(t0 * 4)) if key in _CACHE: return _CACHE[key] a = _decode(path, max(0.0, t0), dur) out = [0.0] * 12 if len(a) >= 1600: step = max(N // 2, (len(a) - N) // 2 if len(a) > N else N) starts = list(range(0, max(1, len(a) - N // 2), step))[:3] for s in starts: mags = _mags(a[s:s + N]) for k in range(int(80 * N / RATE), int(2000 * N / RATE)): f = k * RATE / N pc = int(round(69.0 + 12.0 * math.log2(f / 440.0))) % 12 out[pc] += mags[k] ** 2 m = max(out) res = [v / m for v in out] if m > 0 else [0.0] * 12 _CACHE[key] = res return res def _score(partials, ch, shift): sc = 0.0 for m, w in partials: pc = int(round(m + shift)) % 12 beside = max(ch[(pc + 1) % 12], ch[(pc - 1) % 12]) sc += w * (ch[pc] - 0.6 * max(0.0, beside - ch[pc])) return sc def best_shift(partials, ch, max_shift=2): """(shift in semitones incl. cents, score gain over leaving it, why) or (0, 0, reason).""" if not partials: return 0.0, 0.0, "no pitch (noise)" mean = sum(ch) / 12.0 if mean <= 0 or max(ch) / mean < 1.6: return 0.0, 0.0, "the music has no clear tonal centre there" m0 = max(partials, key=lambda p: p[1])[0] cents = round(m0) - m0 # what puts the strongest partial exactly on its note base = _score(partials, ch, 0.0) best = (0.0, 0.0) for k in range(-max_shift, max_shift + 1): s = k + cents gain = _score(partials, ch, s) - base - 0.04 * abs(k) if gain > best[1]: best = (s, gain) if best[1] < 0.15: return 0.0, 0.0, "already in the key" return round(best[0], 2), round(best[1], 2), "retuned" def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("sound", nargs="?") ap.add_argument("--id", type=int) ap.add_argument("--music") ap.add_argument("--at", type=float, default=0.0) a = ap.parse_args() path = a.sound if a.id is not None: from picker import load_index, find rec = find(load_index(), a.id) if rec is None: sys.exit(f"no sound with id {a.id}") path = rec["path"] if not path: sys.exit("give a sound file or --id") pa = sound_partials(path) if not pa: print("no pitch: a noise or a click (nothing to tune)") return 0 print("partials: " + ", ".join(f"{midi_name(m)} ({440 * 2 ** ((m - 69) / 12):.0f} Hz, {100 * w:.0f} %)" for m, w in pa)) if a.music: ch = chroma(a.music, a.at) print("the music at %.2f s holds: " % a.at + ", ".join(f"{NOTES[i]} {ch[i]:.2f}" for i in sorted(range(12), key=lambda i: -ch[i])[:5])) s, g, why = best_shift(pa, ch) print(f"fit: {s:+.2f} semitones ({why}, gain {g:.2f})") return 0 if __name__ == "__main__": sys.exit(main()) - skills/real-sfx/scripts/ui_events.py (50326 bytes)
#!/usr/bin/env python3 """Interface events of a screen recording, region by region: keystrokes, toasts and dialogs, scrolls, button presses, window switches. Writes a typed cue list that from_cues.py turns into sounds. A screencast has no cut list and almost no motion in the usual sense: one text field is typed into, a corner shows a toast, a status dot blinks once a second. find_moments.py watches the whole frame and calls the blinking dot "the strongest moment". Here every region is watched on its own, with its own threshold, and a region says what kind of event it can produce. python ui_events.py rec.mp4 --out work/ui \\ --roi input=420,980,1080,60:typing --roi toast=1500,60,400,120:popup --roi chat=40,120,380,820:scroll python ui_events.py rec.mp4 --out work/ui --grid 4x3 # no regions yet: which parts of the picture move? --roi NAME=x,y,w,h[:kind[:sound]][@from-to] pixels, or fractions of the frame when all four numbers are <= 1; @from-to keeps only that part of the recording (a field that exists while one window is on screen: input=...:typing@0-91) kind typing a pulse per keystroke (spinners, status dots and a blinking caret are recognised by their place and left out) -> "key" popup something appears (toast, dialog, menu, tooltip); its length is how long it stays -> "pop" scroll continuous motion, one event per stretch, with its length -> "whoosh" click a short local change (button state, highlight) -> "click" window the whole picture changes (tab, app, page switch; ffmpeg's scene score, --scene 0.3) -> "wipe" any every pulse -> "tick" toggle like popup, and the disappearance is an event too (a dialog closes, an option is chosen) -> "pop" + "click" sound the cue kind written to events.json (default as above, any kind from_cues.py knows) The time range may stand anywhere after the box: input=420,980,1080,60@0-91:typing, same as :typing@0-91. When no kind is given it is guessed from the name (input/field -> typing, toast/dialog -> popup, ...). Output (in --out): events.json typed cue list: [{"t": 12.34, "type": "key", "g": 0.8, "roi": "input"}, ...] -> from_cues.py ui_events.json everything measured: per region the noise floor, threshold, events, counts per 10 s, flags timeline.png one row per region: activity (bars), the threshold (dashes) and the events found (red). Look at it before you trust the list. checkpoints.png the typing region at a few moments, labelled with how many keystrokes were counted so far: count the characters in the picture and compare. Counts that fall short mean frames merged (a sped-up recording); counts above mean flicker. Times are the first frame that shows the change. Keystrokes are moved earlier by --lead (0.03 s): the picture lags the key that caused it. A change that a window switch causes in every region at once is reported once, as the switch. Measured at the recording's own frame rate (up to 60 fps), nothing but ffmpeg is needed. """ import argparse import json import re import statistics import struct import sys import tempfile import zlib from concurrent.futures import ThreadPoolExecutor from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import run KIND_BY_NAME = [ (r"input|field|text|prompt|typ|compos|editor|search|command|terminal|code", "typing"), (r"toast|popup|pop|modal|dialog|menu|tooltip|notif|banner|snack|alert|badge", "popup"), (r"scroll|list|feed|chat|panel|side|timeline|layers|preview|log", "scroll"), (r"button|click|btn|play|send|cta|tab", "click"), (r"window|screen|app|full|page|frame", "window"), ] SOUND = {"typing": "key", "popup": "pop", "toggle": "pop", "scroll": "whoosh", "click": "click", "window": "wipe", "any": "tick"} GAIN = {"typing": 0.8, "popup": 0.9, "toggle": 0.9, "scroll": 0.5, "click": 0.8, "window": 1.0, "any": 0.5} # mean luma change per frame (0..255, over the whole region) that counts as a change at all MIN_DIFF = {"typing": 0.06, "popup": 0.15, "toggle": 0.15, "scroll": 0.25, "click": 0.12, "window": 6.0, "any": 0.15} # ------------------------------------------------------------------ regions def parse_roi(text, width, height): name, _, rest = text.partition("=") if not rest: sys.exit(f"--roi expects NAME=x,y,w,h[:kind[:sound]][@from-to], got {text!r}") t_lo = t_hi = None m_ = re.search(r"@([0-9.]*)-([0-9.]*)", rest) # the range may stand anywhere: box@0-4:popup:key if m_: try: t_lo = float(m_.group(1)) if m_.group(1) else None t_hi = float(m_.group(2)) if m_.group(2) else None except ValueError: sys.exit(f"--roi {name}: the time range after @ is from-to in seconds, got {m_.group(0)!r}") rest = rest[:m_.start()] + rest[m_.end():] elif "@" in rest: sys.exit(f"--roi {name}: the time range after @ is from-to in seconds, e.g. @0-91 or @19-20.5") parts = rest.split(":") try: nums = [float(v) for v in parts[0].split(",")] except ValueError: sys.exit(f"--roi {name}: the box must be four numbers x,y,w,h, got {parts[0]!r}") if len(nums) != 4: sys.exit(f"--roi {name}: the box must be four numbers x,y,w,h") if all(v <= 1.0 for v in nums): nums = [nums[0] * width, nums[1] * height, nums[2] * width, nums[3] * height] x, y, w, h = (int(round(v)) for v in nums) x, y = max(0, min(x, width - 2)), max(0, min(y, height - 2)) w, h = max(2, min(w, width - x)), max(2, min(h, height - y)) kind = parts[1].strip().lower() if len(parts) > 1 and parts[1].strip() else None if kind is None: kind = next((k for rx, k in KIND_BY_NAME if re.search(rx, name, re.I)), "any") if kind not in SOUND: sys.exit(f"--roi {name}: kind must be one of {', '.join(SOUND)}") sound = parts[2].strip() if len(parts) > 2 and parts[2].strip() else SOUND[kind] return {"name": name.strip(), "box": [x, y, w, h], "kind": kind, "sound": sound, "range": [t_lo, t_hi]} def grid_rois(cols, rows, width, height): out = [] cw, ch = width // cols, height // rows for r in range(rows): for c in range(cols): out.append({"name": f"r{r + 1}c{c + 1}", "box": [c * cw, r * ch, cw, ch], "kind": "any", "sound": "tick"}) return out # ------------------------------------------------------------------ measuring def probe(video): p = run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,r_frame_rate:format=duration", "-of", "json", str(video)]) try: j = json.loads(p.stdout) v = j["streams"][0] num, _, den = v.get("r_frame_rate", "30/1").partition("/") return {"width": int(v["width"]), "height": int(v["height"]), "fps": float(num) / float(den or 1), "duration": float(j["format"]["duration"])} except (ValueError, KeyError, IndexError): sys.exit(f"cannot read the picture of {video}") def series(video, box, fps, t_from, t_to): """(times, ydif): mean absolute luma change from the previous frame, over the box, at fps.""" x, y, w, h = box vf = [f"crop={w}:{h}:{x}:{y}", f"fps={fps:g}"] if w > 960: vf.append("scale=960:-2:flags=area") vf.append("signalstats,metadata=print:key=lavfi.signalstats.YDIF:file=-") cmd = ["ffmpeg", "-v", "error", "-nostdin"] if t_from: cmd += ["-ss", f"{t_from:.3f}"] if t_to: cmd += ["-t", f"{t_to - (t_from or 0):.3f}"] cmd += ["-i", str(video), "-an", "-vf", ",".join(vf), "-f", "null", "-"] r = run(cmd) ts, yd, t = [], [], None for line in r.stdout.splitlines(): m = re.search(r"pts_time:([\d.]+)", line) if m: t = float(m.group(1)) + (t_from or 0.0) continue m = re.search(r"YDIF=([\d.]+)", line) if m and t is not None: ts.append(t) yd.append(float(m.group(1))) t = None if not ts: sys.exit("motion analysis failed:\n" + r.stderr[-1200:]) return ts, yd def profile_series(video, box, fps, t_from, t_to): """(times, residual, static_x): the mean luma change per frame of the box with the FIXED sources of change taken out. The change of every frame is looked at per column: a keystroke is a few columns that move to the right from key to key, a spinner, a status dot or a blinking caret is the same few columns again and again. Within every 15 seconds the places that change far more often than the rest are static and their share is subtracted (a caret blinks only while a field has the focus, a spinner only while something runs). static_x: those places in pixels of the picture.""" import subprocess x, y, w, h = box wo = min(w, 960) # gray FIRST: a tv-range recording (most screen recorders) differenced in YUV and scaled afterwards comes out # with a constant offset of about 45 levels vf = f"crop={w}:{h}:{x}:{y},fps={fps:g},format=gray,tblend=all_mode=difference,scale={wo}:1:flags=area" cmd = ["ffmpeg", "-v", "error", "-nostdin"] if t_from: cmd += ["-ss", f"{t_from:.3f}"] if t_to: cmd += ["-t", f"{t_to - (t_from or 0):.3f}"] cmd += ["-i", str(video), "-an", "-vf", vf, "-f", "rawvideo", "-pix_fmt", "gray", "-"] raw = subprocess.run(cmd, capture_output=True).stdout n = len(raw) // wo if n < 3: sys.exit("motion analysis failed (no frames came out of the region)") t0 = (t_from or 0.0) + 1.0 / fps # the first difference is the second frame ts = [t0 + i / fps for i in range(n)] rows = [raw[i * wo:(i + 1) * wo] for i in range(n)] narrow = max(16, 0.04 * wo) def spans(row): mx = max(row) if mx < 4: return [] lim = max(4, 0.25 * mx) out, start, last = [], None, -99 for xx, v in enumerate(row): if v >= lim: if start is None: start = xx elif xx - last > 4: out.append((start, last)) start = xx last = xx if start is not None: out.append((start, last)) return out part = max(30, int(15 * fps)) vals, all_static, geo = [], {}, [] for p0 in range(0, n, part): chunk = rows[p0:p0 + part] bins = {} for row in chunk: for a_, b_ in spans(row): if b_ - a_ + 1 <= narrow: k = ((a_ + b_) // 2) // 10 bins[k] = bins.get(k, 0) + 1 static = [] if bins: counts = sorted(bins.values()) med = counts[len(counts) // 2] for k, c in bins.items(): near = c + bins.get(k - 1, 0) + bins.get(k + 1, 0) # the same place again and again: far more often than the typical place, or the only place there is if c >= 6 and (len(bins) <= 2 or c >= 4 * max(1, med)) and near >= 6: static.append(k) ranges = sorted({(max(0, k * 10 - 6), min(wo, k * 10 + 16)) for k in static}) for k in static: all_static[k] = all_static.get(k, 0) + 1 for row in chunk: total = sum(row) for lo, hi in ranges: total -= sum(row[lo:hi]) vals.append(max(0.0, total) / wo) # where the change that is left sits and how wide it is: a glyph is wide, a caret toggling is a thin bar best = None for a_, b_ in spans(row): if any(lo <= (a_ + b_) // 2 < hi for lo, hi in ranges): continue if best is None or (b_ - a_) > (best[1] - best[0]): best = (a_, b_) geo.append(None if best is None else (((best[0] + best[1]) / 2.0) * w / wo, (best[1] - best[0] + 1) * w / wo)) return ts, vals, sorted(int(round((k * 10 + 5) * w / wo)) for k in all_static), geo def scene_times(video, box, thr, t_from, t_to): x, y, w, h = box cmd = ["ffmpeg", "-v", "error", "-nostdin"] if t_from: cmd += ["-ss", f"{t_from:.3f}"] if t_to: cmd += ["-t", f"{t_to - (t_from or 0):.3f}"] cmd += ["-i", str(video), "-an", "-vf", f"crop={w}:{h}:{x}:{y},scale=320:-2,select='gt(scene,{thr})',metadata=print:file=-", "-f", "null", "-"] r = run(cmd) out, t = [], None for line in r.stdout.splitlines(): m = re.search(r"pts_time:([\d.]+)", line) if m: t = float(m.group(1)) + (t_from or 0.0) m = re.search(r"scene_score=([\d.]+)", line) if m and t is not None: out.append((t, float(m.group(1)))) return out def noise_floor(ys): """(residual, spread): the series minus its median over the whole recording (a static interface sits at ~0, and a rolling median would swallow a long scroll), and the robust spread of that residual.""" med = statistics.median(ys) if ys else 0.0 res = [max(0.0, y - med) for y in ys] mad = statistics.median(abs(y - med) for y in ys) if ys else 0.0 return res, 1.4826 * mad def pulses(ts, res, thr, min_gap): """Local maxima of the residual above thr, at least min_gap apart (the larger one wins): [(t, strength)].""" out = [] n = len(res) for i in range(n): if res[i] < thr: continue if (i > 0 and res[i] < res[i - 1]) or (i + 1 < n and res[i] <= res[i + 1]): continue if out and ts[i] - out[-1][0] < min_gap: if res[i] > out[-1][1]: out[-1] = (ts[i], res[i]) continue out.append((ts[i], res[i])) return out KEEP_PERIODIC = False def periodic_trains(times, min_n=6, lo=0.25, hi=2.5, tol=0.06): """Evenly spaced trains: at least `min_n` consecutive events whose gaps all equal one period (0.25-2.5 s) within `tol`. A timer or a spinner redrawing every second looks like that; a person scrolling or clicking does not. Returns (set of indices, [(first t, last t, period)]).""" n = len(times) gone, trains = set(), [] i = 0 while i < n - 1: p = times[i + 1] - times[i] if not (lo <= p <= hi): - skills/real-sfx/scripts/unbake.py (29444 bytes)
#!/usr/bin/env python3 """Take a synthesized layer OUT of a finished mix: the render's audio (or the project's own lossless mix) minus the project's synthesized stem, at the gain and the lag found by correlation. python unbake.py film.mp4 --synth assets/audio/sfx.wav [more.wav ...] --out work/base_unbaked.wav [--mix assets/audio/final_mix.wav] [--keep-voice VOICE.wav ...] python unbake.py film.mp4 --project E:/proj --out work/base_unbaked.wav (stems found in the project) Why: a film built from a score script mixes music, voice and a synthesized effect layer into ONE track. New real sounds on top of it would double the synthesis. When the project keeps the synthesized layer as its own file (sfx.wav, transitions.wav), the mix is linear up to the master gain and the delay, so `mix - g * stem` is the original without it: music and voice keep the ducking and the level the author gave them, which a rebuild from separate stems does not (the sidechain is the author's, not ours). What it checks, because a subtraction that does not cancel is worse than none: the correlation of the stem with the audio must be clearly above chance, the gain must be plausible, and after the subtraction the stem must be (almost) uncorrelated with what is left. Exit status 0 = a base was written, 2 = the stem is not in this audio. Also here: `scan_audio` (which files of a project are voice, music, synthesized layer, a finished mix) and `fit_stems` (the stems' levels that best explain the render, so a stem that is not in the mix is seen as such). Pure Python + ffmpeg: no numpy. """ import argparse import array import json import math import os import re import subprocess import sys from operator import mul from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import decode_mono, stereo_fmt AUDIO_SUFFIX = (".wav", ".mp3", ".flac", ".aif", ".aiff", ".ogg", ".m4a") SYNTH_TOKENS = ("sfx", "fx", "effect", "effects", "transition", "transitions", "whoosh", "foley", "impact", "impacts", "sound_design", "ui", "click", "clicks", "cues", "synth", "stinger", "stingers", "hits") VOICE_TOKENS = ("voice", "vo", "vox", "dialog", "dialogue", "narrat", "narration", "speech", "voiceover", "narrator") MUSIC_TOKENS = ("music", "score", "bed", "song", "ambien", "atmos", "ambience", "ambient", "track") MIX_TOKENS = ("mix", "premix", "master", "mastered", "final", "full", "mixdown", "bounce") FOLDERS = ("assets/audio/stems", "audio/stems", "assets/stems", "stems", "assets/audio", "audio", "assets/sound", "assets") SR = 48000 # ------------------------------------------------------------------ which file is what def _tokens(stem): return [t for t in re.split(r"[^a-z0-9]+", stem.lower()) if t] def _has(tokens, words): return any(t == w or t.startswith(w) for t in tokens for w in words) def classify(path): """'synth' | 'voice' | 'music' | 'mix' | 'other' from the file name (a guess: fit_stems / unbake check it).""" tk = _tokens(Path(path).stem) if not tk: return "other" mixlike = _has(tk, MIX_TOKENS) and not _has(tk, ("music",)) if mixlike: return "mix" if _has(tk, SYNTH_TOKENS): return "synth" if _has(tk, VOICE_TOKENS): return "voice" if _has(tk, MUSIC_TOKENS): return "music" return "other" def scan_audio(root): """The project's audio files by what they are. The first folder of FOLDERS that holds a synthesized layer or a mix wins. Returns {'folder', 'voice', 'music', 'synth', 'mix', 'other'} (lists of Paths).""" best = None for rel in FOLDERS: d = Path(root) / rel if not d.is_dir(): continue found = {"folder": d, "voice": [], "music": [], "synth": [], "mix": [], "other": []} for f in sorted(d.iterdir()): if f.is_file() and f.suffix.lower() in AUDIO_SUFFIX: found[classify(f)].append(f) n_all = sum(len(found[k]) for k in ("voice", "music", "synth", "mix")) if n_all == 0: continue if found["synth"] or found["mix"]: return found best = best or found return best or {"folder": None, "voice": [], "music": [], "synth": [], "mix": [], "other": []} # ------------------------------------------------------------------ small signal helpers (stdlib only) def _dot(a, b): return sum(map(mul, a, b)) def _energy_env(samples, rate, hop): """RMS in dB (re full scale) per hop seconds, floor -100.""" w = max(1, int(rate * hop)) out = [] for i in range(0, len(samples) - w + 1, w): seg = samples[i:i + w] e = _dot(seg, seg) / w out.append(10.0 * math.log10(e / (32768.0 ** 2)) if e > 1.0 else -100.0) return out def _power_env(samples, rate, hop): w = max(1, int(rate * hop)) return [_dot(samples[i:i + w], samples[i:i + w]) / w / (32768.0 ** 2) for i in range(0, len(samples) - w + 1, w)] def _corr(x, y): n = min(len(x), len(y)) if n < 8: return 0.0 x, y = x[:n], y[:n] mx, my = sum(x) / n, sum(y) / n sxx = sum((v - mx) ** 2 for v in x) syy = sum((v - my) ** 2 for v in y) if sxx <= 0 or syy <= 0: return 0.0 return sum((a - mx) * (b - my) for a, b in zip(x, y)) / math.sqrt(sxx * syy) def _overlap(a, b, lag): """Samples of a and b that sit on the same instants when b is delayed by `lag` samples: a[i] <-> b[i - lag].""" i0 = max(0, lag) i1 = min(len(a), len(b) + lag) if i1 <= i0: return a[0:0], b[0:0] return a[i0:i1], b[i0 - lag:i1 - lag] def _decode(path, rate): pcm, _ = decode_mono(path, rate) return pcm def _duration(path): r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)], capture_output=True, text=True) try: return float(r.stdout.strip()) except ValueError: return 0.0 def _flux(env): return [max(0.0, env[i] - env[i - 1]) if i else 0.0 for i in range(len(env))] def coarse_lag(ref, test, rate=16000, max_s=0.6, hop=0.01, top=1): """Lags (seconds) that delay `test` onto `ref`, best first, from the attack envelopes. A regular pattern (ticks every 0.4 s) makes the envelope correlation ambiguous, so several candidates are returned: the caller decides with the waveform. Returns [(lag_s, score), ...].""" fr = _flux(_energy_env(ref, rate, hop)) ft = _flux(_energy_env(test, rate, hop)) nlag = int(max_s / hop) scores = {} for lag in range(-nlag, nlag + 1): a, b = _overlap(fr, ft, lag) if len(a) < 50: continue scores[lag] = _dot(a, b) / math.sqrt(max(1e-9, _dot(a, a) * _dot(b, b))) peaks = [lag for lag, s in scores.items() if s >= scores.get(lag - 1, -9) and s >= scores.get(lag + 1, -9) and s > 0] peaks.sort(key=lambda l: -scores[l]) out = [] for l in peaks: if all(abs(l - q) > 2 for q, _ in out): out.append((l, scores[l])) if len(out) >= top: break return [(l * hop, sc) for l, sc in out] def _loud_windows(stem, rate, win=0.25, k=14): """Start samples of the k loudest non-overlapping windows of the stem.""" n = int(rate * win) cand = [] for i in range(0, len(stem) - n, n): seg = stem[i:i + n] cand.append((_dot(seg, seg), i)) cand.sort(reverse=True) return sorted(i for e, i in cand[:k] if e > 0), n def _lag_search(ref, test, rate, lo, hi, windows, n): """Best integer lag in [lo, hi] samples by the normalised correlation over the windows (positions in `test`).""" tw = [test[w:w + n] for w in windows if len(test[w:w + n]) == n] den_t = sum(_dot(t, t) for t in tw) best = (-2.0, 0) if den_t <= 0: return best for lag in range(lo, hi + 1): num = den_r = 0.0 for w, ti in zip(windows, tw): ri = ref[w + lag:w + lag + n] if len(ri) < n: continue num += _dot(ri, ti) den_r += _dot(ri, ri) if den_r > 0: c = num / math.sqrt(den_r * den_t) if c > best[0]: best = (c, lag) return best def _rho(ref, test, windows, n, lag): """Normalised correlation of `ref` (delayed view) and `test` inside the windows, at one lag (samples).""" num = den_r = den_t = 0.0 for w in windows: a = ref[w + lag:w + lag + n] b = test[w:w + n] if len(a) == n and len(b) == n: num += _dot(a, b) den_r += _dot(a, a) den_t += _dot(b, b) return num / math.sqrt(den_r * den_t) if den_r > 0 and den_t > 0 else 0.0 def _best_lag(ref, test, rate, windows, n, max_s): """(rho, lag in samples): coarse candidates from the attack envelopes (and 0), the waveform decides.""" cands = [c for c, _ in coarse_lag(ref, test, rate, max_s, 0.01, top=6)] + [0.0] ws = windows[:10] best = (-2.0, 0) seen = set() half = int(0.012 * rate) for cl in cands: centre = int(round(cl * rate)) if centre in seen: continue seen.add(centre) c, l = _lag_search(ref, test, rate, centre - half, centre + half, ws, n) if c > best[0]: best = (c, l) return best def _solve(A, b): """Gauss elimination for the small normal equations (K <= 6).""" n = len(b) M = [row[:] + [b[i]] for i, row in enumerate(A)] for c in range(n): p = max(range(c, n), key=lambda r: abs(M[r][c])) if abs(M[p][c]) < 1e-12: return None M[c], M[p] = M[p], M[c] for r in range(c + 1, n): f = M[r][c] / M[c][c] for k in range(c, n + 1): M[r][k] -= f * M[c][k] x = [0.0] * n for r in range(n - 1, -1, -1): x[r] = (M[r][n] - sum(M[r][k] * x[k] for k in range(r + 1, n))) / M[r][r] return x # ------------------------------------------------------------------ which stems explain the render def fit_stems(video, stems, hop=0.05): """Non-negative levels of the stems that best explain the render's power over time (stems are summed in power: music, voice and effects are not correlated). Constant gains cannot follow a sidechain, but the shape is right for the right stems and wrong for stems of another cut. Returns {corr, lag_s, gains_db{name}, used[], unused[]}.""" rate = 8000 r = _decode(video, rate) P = [_power_env(_decode(s, rate), rate, hop) for s in stems] pr = _power_env(r, rate, hop) if not pr or not any(P): return {"corr": None, "lag_s": None, "gains_db": {}, "used": [], "unused": [Path(s).name for s in stems]} # lag from the summed stems (unit gains are enough to find it) n = min(len(pr), max(len(p) for p in P)) tot = [sum(p[i] for p in P if i < len(p)) for i in range(n)] cand_ = coarse_lag(_decode(video, 8000), _decode_sum(stems, 8000), 8000, 0.4, 0.02, top=1) lag_f = cand_[0][0] if cand_ else 0.0 lag_i = int(round(lag_f / hop)) cols = [] for p in P: a, b = _overlap(pr, p, lag_i) cols.append(b) y, _ = _overlap(pr, tot, lag_i) m = min([len(y)] + [len(c) for c in cols]) y = y[:m] cols = [c[:m] for c in cols] w = [0.0] * len(cols) gram = [[_dot(ci, cj) for cj in cols] for ci in cols] rhs = [_dot(ci, y) for ci in cols] for _ in range(400): # coordinate descent on 0.5*|y - sum w c|^2, w >= 0 for j in range(len(cols)): if gram[j][j] <= 0: continue g = rhs[j] - sum(gram[j][k] * w[k] for k in range(len(cols)) if k != j) w[j] = max(0.0, g / gram[j][j]) fit = [sum(w[k] * cols[k][i] for k in range(len(cols))) for i in range(m)] loud = [i for i in range(m) if y[i] > 1e-7] xs = [10 * math.log10(max(y[i], 1e-10)) for i in loud] ys = [10 * math.log10(max(fit[i], 1e-10)) for i in loud] corr = _corr(xs, ys) top = max(w) if w else 0.0 gains, used, unused = {}, [], [] for s, wj in zip(stems, w): nm = Path(s).name if top > 0 and wj > 0.02 * top: gains[nm] = round(10 * math.log10(wj), 1) # power ratio = amplitude gain squared used.append(nm) else: unused.append(nm) return {"corr": round(corr, 2), "lag_s": round(lag_i * hop, 2), "gains_db": gains, "used": used, "unused": unused} def fit_levels(video, music, voice, hop=0.05): """The level each rebuilt stem has inside the render. The music's level comes from the frames where the voice stem is silent (nothing ducks it there), the voice's from the frames where it dominates the render. Returns {"corr", "gains_db": {name: dB}, "lag_s"} or None. The music's own sidechain is not modelled: that is mix.py --duck-music.""" rate = 8000 r = _decode(video, rate) pr = _power_env(r, rate, hop) mus = [(Path(f), _power_env(_decode(f, rate), rate, hop)) for f in music] voc = [(Path(f), _power_env(_decode(f, rate), rate, hop)) for f in voice] if not pr or not mus or not voc: return None n = len(pr) cand = coarse_lag(r, _decode_sum([f for f, _ in mus] + [f for f, _ in voc], rate), rate, 0.4, 0.02, top=1) lag = int(round((cand[0][0] if cand else 0.0) / hop)) def col(p): a, b = _overlap(pr, p, lag) return b m_cols = [col(p) for _, p in mus] v_cols = [col(p) for _, p in voc] y, _ = _overlap(pr, pr, lag) m = min([len(y)] + [len(c) for c in m_cols + v_cols]) y = y[:m] m_cols = [c[:m] for c in m_cols] v_cols = [c[:m] for c in v_cols] vsum = [sum(c[i] for c in v_cols) for i in range(m)] pause = [i for i in range(m) if vsum[i] < 1e-9 and y[i] > 1e-9] if len(pause) < 20: return None # music: non-negative least squares on the pause frames (a few columns: coordinate descent) cols = [[c[i] for i in pause] for c in m_cols] yp = [y[i] for i in pause] w = [0.0] * len(cols) gram = [[_dot(a, b) for b in cols] for a in cols] rhs = [_dot(a, yp) for a in cols] for _ in range(300): for j in range(len(cols)): if gram[j][j] > 0: g = rhs[j] - sum(gram[j][k] * w[k] for k in range(len(cols)) if k != j) w[j] = max(0.0, g / gram[j][j]) music_part = [sum(w[k] * m_cols[k][i] for k in range(len(cols))) for i in range(m)] # voice: frames where the voice is clearly the loudest thing (music under it is a tenth of the render) act = [i for i in range(m) i - skills/real-sfx/scripts/verify.py (16448 bytes)
#!/usr/bin/env python3 """Check a finished mix: does every peak-anchored sound land on its moment, is anything clipping? python verify.py result/film_sfx_resolved_cues.json result/film_sfx_sfx_track.wav [--tol-ms 40] [--json] Exit code 1 when a cue is off by more than the tolerance or the track clips. A sound placed by its ARRIVAL (anchor `arrive`: the first 60 ms within 6 dB of its loudest, the default of a sound that gets loud fast) is judged by where that happens around t. Cues anchored on start/end are listed but not judged, since their loudest point is not meant to sit on t. Broad sounds (whoosh, riser, ambience, design) have a flat top, so their tolerance is 2.25x; textures longer than 0.6 s (paper, broom, rubber, static, drips) have no real peak at all: 4x. A sound counts as present when anything above -60 dBFS sounds in its first three seconds (a bed fades in). """ import argparse import json import math import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) from common import (ROLE_ANCHOR, ROLE_TARGET_PEAK_DB, decode_mono, events_track, index_path, load_config, load_json) BROAD = ("whoosh", "riser", "ambience", "design", "scifi") # textures (paper, broom, rubber, static) have a flat top once they are longer than a click: where their loudest # 20 ms sits is arbitrary, so they get the broad tolerance too BROAD_IF_LONG = ("paper", "foley", "cartoon", "glitch", "vehicle", "water", "chime") def _level(x): """Loudness of a placed sound: its real peak plus the gain mix.py applied (nominal when unresolved).""" if x.get("peak_db") is not None and x.get("gain_applied_db") is not None: return x["peak_db"] + x["gain_applied_db"] return ROLE_TARGET_PEAK_DB.get(x.get("role"), -10) + x.get("gain_db", 0.0) def offsets(cues, track, tol_ms=40.0): """For every cue: where the loudest 20 ms of the track really is, around the moment (+-250 ms).""" samples, rate = decode_mono(track, 16000) # the same view as the library analysis (peak_time) win = rate // 50 # 20 ms windows, hop of half a window out = [] sides = None # the two channels, decoded only if a sound looks missing # a bed (bed.py) is the floor under the film, not a sound with a moment: it is not judged, and it is no neighbour # (as a long quiet "similar" sound it would make every quiet key look masked) ordered = sorted((c for c in cues if not c.get("bed")), key=lambda c: c["t"]) ts = [c["t"] for c in ordered] for n, c in enumerate(ordered): role = c.get("role") or "default" anchor = c.get("anchor") or ROLE_ANCHOR.get(role, "peak") row = {"n": n, "t": c["t"], "label": c.get("label", ""), "role": role, "anchor": anchor, "judged": False, "off_ms": None, "ok": True, "layer": bool(c.get("_layer"))} # look only half-way towards the neighbouring sounds, otherwise a louder neighbour is measured instead others = [abs(x - c["t"]) for x in ts if abs(x - c["t"]) > 0.03] # within 30 ms: the same event half = min(0.25, 0.5 * min(others)) if others else 0.25 if anchor in ("peak", "arrive") and half < 0.04: row["note"] = "crowded: a neighbour is closer than 80 ms" elif anchor == "peak": lo = max(0, int((c["t"] - half) * rate)) hi = min(len(samples) - win, int((c["t"] + half) * rate)) if hi > lo: best = max(range(lo, hi, win // 2), key=lambda i: sum(s * s for s in samples[i:i + win])) tm = best / rate + win / rate / 2 off = (tm - c["t"]) * 1000 silent_ = not any(samples[best:best + win]) # the mono sum of channels that cancel is silence textured = role in BROAD_IF_LONG and (c.get("seg") or 0) >= 0.6 tol = tol_ms * (2.25 if role in BROAD else 4.0 if textured else 1.0) def level(x): # loudness of the sound as placed: its real peak plus the gain mix.py applied if x.get("peak_db") is not None and x.get("gain_applied_db") is not None: return x["peak_db"] + x["gain_applied_db"] return ROLE_TARGET_PEAK_DB.get(x.get("role"), -10) + x.get("gain_db", 0.0) masker = next((o for o in ordered if o is not c and "start" in o and "seg" in o and o["start"] <= tm <= o["start"] + o["seg"] and level(o) > level(c) + 1.0), None) # a bouncy sound has several peaks within a few dB of each other; if the one at the moment is # within 3 dB of the loudest, the moment is on a peak of this sound and it counts as in sync a0 = max(0, int((c["t"] - tol / 1000.0) * rate)) a1 = min(len(samples) - win, int((c["t"] + tol / 1000.0) * rate)) e_best = sum(s_ * s_ for s_ in samples[best:best + win]) e_at = max((sum(s_ * s_ for s_ in samples[i:i + win]) for i in range(a0, a1 + 1, max(1, win // 2))), default=0) co_peak = e_best > 0 and e_at > 0 and 10 * math.log10(e_at / e_best) >= -3.0 if silent_: row["note"] = "silent in the mono sum (its channels are in opposite phase)" elif masker is not None and abs(off) > tol and not co_peak: # the loudest point belongs to a louder sound that is still ringing: not this cue's peak row["note"] = f"masked by the louder sound at {masker['t']:.2f}s" else: ok = abs(off) <= tol or co_peak row.update(judged=True, off_ms=round(off), ok=ok, tol_ms=tol) if co_peak and abs(off) > tol: row["note"] = "another peak of the same sound sits on the moment" elif anchor == "arrive": # placed by its arrival: the first 60 ms within 6 dB of the loudest, around the moment (as the placement measured it) if any(o is not c and "start" in o and "seg" in o and "start" in c and abs(o["t"] - c["t"]) > 0.03 and o["start"] < c["t"] + half and o["start"] + o["seg"] > c["t"] - half and _level(o) >= _level(c) - 6.0 for o in ordered): row["note"] = "a neighbour of similar level still sounds here: the arrival cannot be told apart" else: lo = max(0, int((c["t"] - half) * rate)) hi = min(len(samples) - 3 * win, int((c["t"] + half) * rate)) if hi > lo: step_ = max(1, win // 2) idx_ = list(range(lo, hi, step_)) en_ = [sum(s_ * s_ for s_ in samples[i:i + 3 * win]) for i in idx_] top_ = max(en_) if top_ > 0: k_ = next(j for j, e_ in enumerate(en_) if e_ >= top_ * 0.251) # within 6 dB off = (idx_[k_] / rate + 0.01 - c["t"]) * 1000 tol = tol_ms * (2.25 if role in BROAD else 1.5) # the local loudest is not always the sound's own: the arrival reads a little early row.update(judged=True, off_ms=round(off), ok=abs(off) <= tol, tol_ms=tol, note="arrival") elif anchor == "start" and half >= 0.03 and any( o is not c and "start" in o and "seg" in o and "start" in c and abs(o["t"] - c["t"]) > 0.03 # layers of the SAME moment start together: one onset and o["start"] < c["t"] + 0.05 and o["start"] + o["seg"] > c["t"] - 0.05 and _level(o) >= _level(c) - 6.0 for o in ordered): row["note"] = "a neighbour of similar level still sounds here: the onset cannot be told apart" elif anchor == "start" and half >= 0.03: # a sound anchored on its start is judged by its first onset: it has to begin on the moment lo = max(0, int((c["t"] - min(0.05, half)) * rate)) hi = min(len(samples), int((c["t"] + min(0.15, half)) * rate)) seg_ = samples[lo:hi] pk_ = max((abs(v) for v in seg_), default=0) if pk_ >= 100: w2 = max(1, rate // 500) # 2 ms windows step = max(1, w2 // 2) env_ = [max(abs(v) for v in seg_[i:i + w2]) for i in range(0, len(seg_) - w2, step)] if len(env_) >= 4: db_ = [20 * math.log10(max(e, 1) / 32768.0) for e in env_] top_ = max(db_) best_i, best_rise = None, 6.0 # the FIRST rise of at least 6 dB that is not just noise for i in range(2, len(db_)): # (a two-note sound is on its moment by its first note) rise = db_[i] - min(db_[i - 1], db_[i - 2]) if db_[i] >= top_ - 20.0 and rise > best_rise: best_i, best_rise = i, rise break if best_i is not None: off = ((lo + best_i * step) / rate - c["t"]) * 1000 row.update(judged=True, off_ms=round(off), ok=-12.0 <= off <= 30.0, tol_ms=30.0, note="onset") # presence: whatever happens to the rest, the sound must be audible where it was placed. Three seconds are # looked at: a bed or a riser fades in, its first 300 ms may sit under -60 dBFS and is not "lost" if "start" in c and "seg" in c: i0 = max(0, int(c["start"] * rate)) i1 = min(len(samples), int((c["start"] + min(c["seg"], 3.0)) * rate)) seg_peak = max((abs(v) for v in samples[i0:i1]), default=0) row["present"] = seg_peak >= 30 # about -60 dBFS if not row["present"]: # silent in the mono sum: is it in the channels? if sides is None: from common import stereo_samples sides = stereo_samples(track, rate) lft_, rgt_ = sides j1_ = min(len(lft_), i1) if max(max((abs(v) for v in lft_[i0:j1_]), default=0), max((abs(v) for v in rgt_[i0:j1_]), default=0)) >= 30: row["present"] = True row["note"] = "present only as the difference of the channels: it cancels in mono" if not row["present"]: row.update(judged=True, ok=False, off_ms=None, note="MISSING from the track (the render lost it)") out.append(row) peak = max(max(samples), -min(samples)) / 32768 if len(samples) else 0 return out, (20 * math.log10(peak) if peak else -120.0), peak def main(): ap = argparse.ArgumentParser() ap.add_argument("cues") ap.add_argument("track") ap.add_argument("--tol-ms", type=float, default=40) ap.add_argument("--json", action="store_true") ap.add_argument("--all", action="store_true", help="also list the cues that could not be judged") a = ap.parse_args() sheet = load_json(a.cues) cues = sheet["cues"] # a raw (unresolved) cue sheet has no roles: fall back to the library index cfg = load_config() idx = index_path(cfg) by_path = {} if idx.exists(): by_path = {s["path"]: s["role"] for s in json.loads(idx.read_text(encoding="utf-8"))["sounds"]} for c in cues: if not c.get("role"): c["role"] = "ui" if "uisfx" in c else by_path.get(c.get("file", ""), "default") ev_track = events_track(sheet, a.track) # without the bed when the film has one rows, peak_db, peak = offsets(cues, ev_track, a.tol_ms) if ev_track != a.track: # clipping belongs to the whole track, the bed included full_, rate_ = decode_mono(a.track, 16000) pk_ = max(max(full_), -min(full_)) / 32768 if len(full_) else 0 peak_db, peak = (20 * math.log10(pk_) if pk_ else -120.0), pk_ bad = sum(1 for r in rows if r["judged"] and not r["ok"]) mono_ = None try: # a mono playback (a phone speaker): does anything cancel? from common import fold_cues fr_, fc_ = fold_cues(a.track, [c for c in cues if not c.get("_layer") and not c.get("bed")]) if fr_.get("loss_db") is not None: mono_ = {"loss_db": round(fr_["loss_db"], 1), "bad": [{"t": c["t"], "label": c.get("label", ""), "loss_db": round(l_, 1)} for c, l_, v_ in fc_ if l_ is not None and l_ > 6.0 and v_ > -45.0]} except Exception: mono_ = None if a.json: print(json.dumps({"rows": rows, "peak_db": peak_db, "bad": bad, "mono": mono_}, indent=1)) else: why = {} for r in rows: if r.get("present") is False: print(f"{r['n']:2d} t={r['t']:7.3f} {r['label'][:24]:24s} MISSING from the track (the render lost it)") elif not r["judged"]: note = r.get("note") or f"anchor={r['anchor']}: its peak is not on the moment by design" key = ("a louder or similar neighbour sounds there" if ("neighbour" in note or "masked" in note) else "crowded (a neighbour closer than 80 ms)" if "crowded" in note else "no clear onset to measure" if r["anchor"] == "start" else "the peak is not the moment by design (end / long layer)") why[key] = why.get(key, 0) + 1 if a.all: print(f"{r['n']:2d} t={r['t']:7.3f} {r['label'][:24]:24s} not judged ({key})") else: if a.all or not r["ok"]: kind = {"onset": "onset", "arrival": "arrival"}.get(r.get("note"), "loudest") print(f"{r['n']:2d} t={r['t']:7.3f} {r['label'][:24]:24s} {kind} {r['off_ms']:+5d} ms " f"{'ok' if r['ok'] else 'OFF'}") judged_ = [r for r in rows if r["judged"]] missing_ = [r for r in rows if r.get("present") is False] print(f"{len(rows)} cues: {len(rows) - len(missing_)} present, {len(judged_)} judged " f"({sum(1 for r in judged_ if not r['ok'])} off), {len(rows) - len(judged_)} not judged" + (": " + "; ".join(f"{v} {k}" for k, v in why.items()) if why else "")) print(f"track peak {peak_db:.1f} dBFS (16 kHz view)" + (" CLIPPING" if peak >= 0.999 else "") + (" (sounds judged on the track without the bed)" if ev_track != a.track else "")) if mono_ i - skills/real-sfx/SKILL.md (49821 bytes)
--- name: real-sfx description: Sound design for motion videos with REAL recorded sounds from the user's own libraries (a sorted main pack of whooshes, hits, risers, pops, chimes, keystrokes, foley, ambiences plus fallback libraries) and UI cues from uisfx, never synthesized. Finds the moments from the project's own cue list or from the synthesizer script that makes its sound, from a HyperFrames composition, from a screen recording (regions: typing, toasts, scrolls, clicks) or from the picture itself, picks and processes the sounds, places them on the exact frame at the level the author's own sounds had, keeps the music and voice, takes a synthesized layer baked into the render OUT instead of doubling it, and returns a new MP4, a separate SFX WAV track, a cue report and a self-critique scoreboard. Use whenever the user asks to add sound effects or SFX, sound-design, "озвучь", "добавь звуки", "сфх", whoosh/hit/riser/click/typing sounds, UI sounds, to replace synthesized or generated sounds with real ones, or to make a motion graphic, promo, explainer, UI animation, screencast, HyperFrames render, After Effects or Premiere project sound better, or complains the sound is synthetic, generic or out of sync, even if they do not say "skill" or name a library. --- # real-sfx: real sounds for a motion video The goal: the film sounds as if a person with a good library had cut it. So: - **Sound is never synthesized.** Sources: the user's libraries (`config.json`) and uisfx (a ready CC0 pack of interface sounds, itself synthesized: the one exception, only for interface moments; "no synthesis" turns it off: `--ui library`). No fitting sound: the moment stays quiet and goes into the report. This overrides "no track: synthesize" from motion-standards. - **You cannot hear.** Sound is read as numbers, words and pictures (`references/listening.md`). Do not present a pick as listened to: say what was checked by eye and by measurement, and what the user should listen to. - **Keep the music and voice** when they carry the film. The result is always a new MP4 **and a separate WAV track**. - **Do not double.** Synthesis baked into the render's audio is replaced by the real sounds, not layered under them (step 1). The critique measures this as a number (the `doubling` axis). - **Do not change the project or the skill folder.** Put all working files in your own folder (`work/`, `result/`). ## Quick path First `python scripts/setup.py check` (ffmpeg, main/extra libraries, index, uisfx) and `python scripts/look.py FILM.mp4 --out work/look` (frames with time + the original sound under them). Then, by what you have: ``` # 1. the project has an event list (docs/cues.json, scripts/cues.json) OR a script that synthesizes its sound (audio.cjs) python scripts/from_cues.py PROJECT_FOLDER|docs/cues.json --video RENDER.mp4 --out work/cues.json # 2. screen recording without a list: ui_events.py ... (references/screencast.md), then from_cues.py work/ui/events.json # 3. picture only: find_moments.py FILM.mp4 --out work/moments; suggest_cues.py work/moments/moments.json --out work/cues.json # 3b. SOFT COLOURED ANIMATION without a list (UI preview, illustration, motion graphics): automation sees 5-6 moves of 40. # step 2, "Silent animation without a list": find_moments.py FILM --out work/moments --fine; look.py FILM --at T --span 2.4 # --step 0.1 --out work/at.png; YOUR OWN event list from the frames (references/typed-cues.md) -> from_cues.py - --ui library python scripts/mix.py work/cues.json --out result/film_sfx.mp4 --plan # what goes where; then without --plan python scripts/critique.py result/film_sfx_resolved_cues.json result/film_sfx_sfx_track.wav python scripts/levels.py result/film_sfx_resolved_cues.json result/film_sfx_sfx_track.wav --json work/edits.json # a film whose sound is ONLY SFX (no music or voice of its own): small sounds in the holes, then mix.py again (step 4, "Small-sound layer") python scripts/texture.py work/cues.json --moments work/moments/moments.json # the same film: a bed (one long dark real recording under the whole film; step 4, "Bed"), then mix.py again python scripts/bed.py work/cues.json [--list] # numbers against nine finished SFX reels (step 6, "Against the reference"): no scores, does not affect the verdict python scripts/critique.py RESOLVED.json WAV --style clean-sfx-refs # human ears made cheap (step 6): a page with the critique's questions and a one-tap verdict; the masking model python scripts/listen_page.py build work/listen --moments result/film_sfx.mp4 --critique RESOLVED.json WAV python scripts/listen_page.py serve work/listen [--lan] # then: listen_page.py results work/listen --log python scripts/mix.py work/cues.json --out result/film_sfx.mp4 --masking # which sounds the rest hides (needs the venv) ``` A project folder finds its own event list (`docs/`, `scripts/`, `assets/`); the synthesizer script is read only when there is no list. **Choose all `from_cues.py` flags before editing the sheet**: running it again wipes manual edits (then `sheet.py apply`). Voice in the film: `mix.py ... --voice-safe` (depth `normal`; `--voice-depth light` when there are many quiet textures, `deep` only for rare sounds in pauses: it takes the interface out of the mix entirely). Music carries the film: `--duck`. Loudness: a rebuilt base matches the original by default; your own: `--target-lufs NUMBER`. No index, or the libraries moved: `python scripts/build_index.py`, then `python scripts/listen.py tag-index`. No uisfx: `setup.py init --uisfx`. Another machine: `setup.py scan FOLDER`, `setup.py add-library NAME PATH [--tier main|extra] --index`. Run scripts from the skill folder; quote paths with spaces or non-Latin characters; your own Python with non-Latin paths on Windows: `PYTHONUTF8=1`. In PowerShell, quotes break JSON arguments: put them in a file. ## Where the sounds come from | What is needed | Where from | |---|---| | The base: whooshes, hits, risers, pops, chimes, keys, paper, foley, ambience | **the main library** (`tier: main`, path in `config.json`). A sorted pack with `catalog.json` / `catalog.csv` gives every sound its type and source recording, which beats guessing from file names | | What the main library lacks: low drops, coins, short glitches | fallback libraries (`tier: extra`, marked `~` in results): only when the main library has fewer than three fitting sounds | | Designed packs with their own roles | roles `granular`, `atmosphere`, `power`, `music_transition`, `voice` are never requested by auto-picking: take them explicitly (`--role`, `"pick": {"role": ...}`) | | An interface moment: click, tick, window, notification | uisfx (`--ui auto`) when the list itself names interface kinds (click, chime...): `from_cues` says why and where (`routes: key -> library:click, pop -> uisfx:select`) | | Typing | always the library's real keyboard, even with `--ui auto`; a run of 8+ `click` events 35–170 ms apart is recognized as typing by `from_cues` itself (`--no-typing-detect`) | | Physical contact: ball, step, bead, object | always the library: a ball on the floor is a dull thud, not `select` (recipe below) | No library yet: `setup.py init --uisfx` alone gives 78 CC0 UI cues. Free real-recording sources worth checking (read each licence): Freesound (CC0 filter), Sonniss GDC bundles, Mixkit, Pixabay sound effects. "From my library", "no synthesis" or "sounds synthetic": **`--ui library`**. An accent on the logo or a "cha-ching" in a project with uisfx interface sounds: `--from-library pop,bell` (**kind names from the list**); for one sound: `sheet.py set --at T --label bell id=65`. Under tonal music: - the pitch steps of uisfx repeats and of the library's tonal sounds (chime, pop, glass, coin) turn off by themselves when the project has a score (`--ui-pitch off|cycle`); - **the pitch of a real sound is tuned to the notes of the music**: `mix.py` takes the sheet's `music_ref` (the bed without effects, the music stem) or `--music-ref FILE` and shifts a tonal sound by whole semitones up to 2 plus the cents that put it on a note (2.5 in total), if that puts it on a note; noise is left alone (`--no-tonal-fit`; `scripts/tonal.py SOUND --music FILE --at T` shows the notes); - the intervals of the author's own frequencies (`tick(t, 1800 * 2 ** (4 * i / 12))`) become the pitch steps of the replacement (`melody:`). ## Workflow ### 1. What is already in the sound `look.py` shows the spectrogram of the native sound (voice is bands of phrases, music a carpet with a beat, silence is black); `listen.py voice FILM.mp4` gives the share of speech and music. Three cases: - **The author's music or voice**: they stay, SFX go on top (`--duck` / `--voice-safe`). **Exception (a person's answer on a real film, 2026-10-19)**: the film was sent "to be sound-designed", its native sound is music only (`listen.py voice`: speech 0 %), and the person wants it **without** the music, like their own clean SFX reels. Make a version without music (`from_cues.py ... --ui library --drop-original`, then `bed.py --id ... --level -46` with a favourite atmosphere), and a version with music if useful, and say which is which. In a blind choice of three (original / effects over music / effects only) the person chose the last one without a single complaint. `from_cues` prints `BAKED:` on such a film although there is no baked synthesis (speech 0 %, music 84 %, the attacks do not match the events: 7 % against 9 % by chance): this is a false alarm. - **Synthesis baked into the track** (the project was written for a synthesized score): real sounds on top of it are doubling. `from_cues.py` checks this itself (`BAKED:`, `unbake:`) and removes the synthesis from the base without touching music and voice; how exactly, and what to do if the script fails or the synthesis sits inside the music stem (`--extra-synth`): **`references/project-audio.md`** (read it as soon as the output has `BAKED`, `WARN stems`, `unbake: not possible`, or the project synthesizes its sound with a script). After the build `critique.py` prints the `doubling` axis: the correlation of the layer with the original and with the new film (should be about 0). - **The sound of clips playing inside a screen recording's window**: native, stays; events inside those windows are dropped. ### 2. Find the moments (from the best source to the worst) - **The project's event list or synthesizer script** → `from_cues.py` (below). In detail: `references/typed-cues.md`. - **A screen recording** → `references/screencast.md` (`ui_events.py` regions, matching keystrokes to characters, clip sound). - **HyperFrames with `data-start`** and no list: `from_hyperframes.py PROJECT --out work/moments.json`. "1 moments" with 18 elements means the motion does not follow `data-start`: look for a synthesizer script. - **Video only**: `find_moments.py FILM --out work/moments [--roi x,y,w,h] [--from A --to B] [--fine]`; kinds `cut`, `burst`, `onset`, `settle` (`settle` also fires on an empty frame or a loop at rest: look at the frame); `look.py --moments ...` draws the frames of the moments. Skeleton: `suggest_cues.py` (`references/recipes.md`); a draft is a start, not an answer. **`--fine`** for soft coloured animation (gradients, glows, pastel shapes that change colour rather than brightness): it also reads chroma changes, moments get `src=chroma|luma`; on three such films it finds 33–69 % of the events an agent wrote down from the frames (within 80 ms), against 13–25 % from brightness alone; 3–4 times more candidates (15–25 per 10 s). These are candidates: the frames decide. - **Under music**: `beats.py FILM --out work/beats.json --plot work/beats.png`; with `usable: true`, `mix.py --snap-beats` (±50 ms). The grid **is checked against the kick** (the low band < 125 Hz separately): it prints how many beats landed on a kick within 40 ms. A grid next to the kick (the tracker sat on the hats, "0.22 s off") is moved onto it; a grid that lands on nothing gets `usable: false`, and `--snap-beats` ignores it. `--plot` draws the band, the kicks (green marks) and the grid (red lines): the marks sit on the lines, or do not trust the grid. If the music is yours and can be fitted to the picture: `beats.py FILM --suggest-offset work/moments.json` says how far to shift the music so cuts and hits land on beats (advice only; the music is not touched). **`from_cues.py`**: `python scripts/from_cues.py LIST|PROJECT_FOLDER|SCRIPT.cjs|- --video RENDER.mp4 --out work/cues.json` (`-` reads the list from stdin; a BOM from PowerShell is understood). What it does and says by itself: - **is it the right render**: the list misses the picture (`VERDICT`); **a design-time list against a render timed to the voice**: a time map from the project's anchors (`timing.json` with `anchors` or `WARP`, `src/timing.js`) or from the onsets of the synthesized stems, each event lands on its own onset (`time map`); `--time-map FILE`, `--warp off|stems|audio`; - **synthesis under the list**: a whoosh lands on the peak of the synthesized sound, its length is measured from it (`retime:`); no move if the peak belongs to another sound (pop, bell) or the list time is already the centre of the whoosh: named with the reason; synthesis onsets with no event in the list are listed (`--add-unlisted tick` turns them into events); - **timbre**: the brightness of the whooshes being replaced (centroid of the synthesized layer) feeds the pick (`timbre:`); `--tone airy|dark` sets it by hand; - **an unknown kind** (`bead`, `soft`): it shows how the project defines it. Say it in one line, no file needed: `--kind bead=click`, `--kind soft=pop`, a role with limits `--kind bead=role:click,max_dur=0.3,onsets_max=1`, `--kind bead=slices:740,763` (single sounds from these recordings; the quietest ones, 12 dB down, are not taken), `--map '{"glass":{"ids":[65,54],"role":"chime"}}'` (`ids` in turn; an element `{"id":800,"slice":[0.78,0.12]}`); `--remember` keeps it. Summary: `declared N events: M voiced, K silent`; the critique counts silent kinds as a hole; - **clusters**: events of one kind closer than 25 ms are one sound (`--fuse`), runs faster than 14/s are thinned (`--max-rate`), the output says how many of each (`thinned: key 23, tick 11`); - **a typing stretch** (`{"t":19.99,"type":"typing","len":0.36,"n":99}`) unfolds into keystrokes (`--type-rate`). **Silent animation without a list** (UI preview, illustration, motion graphics; all four blind tests on 2026-10-15 were like this). Automation reads brightness and sees 5–6 moves of ~40 in soft coloured animation, and `suggest_cues` draws only whooshes from them: the draft here is a skeleton, not an answer. The path on which four agents out of four finished the film: 1. `look.py FILM --out work/look`, then `find_moments.py FILM --out work/moments --fine`. 2. **Close-up frames in 2–3 s windows**: