⏳ This skill is pending AI review.

Scores will appear once the review pipeline completes.

v1.0.0

edit

jakeschincariol@jakeschincariol⭐ 180 stars· last commit 1mo ago· 1 open issues

>

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

—/10

// RATINGS

⭐GitHub Stars
⭐⭐⭐ 180 on GitHubGitHub ↗

Popular

🟢ProSkills Score
—
📍

Not yet listed on ClawHub or SkillsMP

// README

Master skills

Three Claude master skills. Free, MIT, no signup, no API key, nothing to connect.

skills/edit skills/virality skills/build

Edit cuts the dead space, adds captions and dynamic visuals, and generates any type of stop motion. Virality fuses the LinkedIn agent and YouTube agent skills: it finds what's working, then rewrites it in your voice for your audience. Build merges the best design and coding skills into one, so you get apps and websites that actually work.

Install

Paste this repo link into Claude and say install skills.

https://github.com/Jakeschincariol/master-skills

install skills

Or do it yourself, in Claude Code:

git clone https://github.com/Jakeschincariol/master-skills.git
cp -r master-skills/skills/* ~/.claude/skills/

Or as a plugin:

/plugin marketplace add Jakeschincariol/master-skills
/plugin install master-skills

Then just ask: "edit this video", "make this go viral", "build me a site that...". Or call them directly with /edit, /virality, /build.

The three

/edit

Hand it a raw take. It cuts the dead space and filler without clipping words, writes 1 to 3 word captions that sit in the safe zone instead of on your face, plans dynamic visuals that show the thing you're saying at the moment you say it, and turns frames or a live clip into stop motion in any style (clay, paper cut-out, bricks, sticky notes, pixel). Finishes the audio at -14 LUFS with no compression on the voice.

Merges the three best editing skills: HyperFrames (motion engine), Remotion's agent skills and video-use (transcript-driven editing).

Needs ffmpeg. Transcription uses faster-whisper if you have it installed, otherwise it takes a transcript you already have.

/virality

Fuses the LinkedIn agent and YouTube agent skills into one loop: find the outliers in your niche (views as a multiple of each creator's own median, so one huge account doesn't drown out the signal), break down why they worked (hook formula, format, structure, CTA), rewrite the winner in your voice for your audience, score the hook, and hand you a shoot-ready script with on-screen text, visuals per beat, a caption and a comment-a-keyword CTA.

Fill in templates/voice.md once (or paste three of your own captions and say "write my voice file"). Everything reads it.

/build

Merges the best design skills (impeccable, Anthropic's frontend-design) with the best coding skills (gstack, superpowers) into one path from "I want an app that does X" to a deployed product: a one-page plain-English spec, the simplest stack that works, a real design direction before any code, small verified build steps, a real-browser QA pass at phone, tablet and desktop widths, then ship. tools/sitecheck.py crawls the result for broken links, missing alt text, missing meta tags and other things that quietly break a launch.

The fine print

  • Virality can't be guaranteed by anyone. This raises the odds by copying structure from what is already working in your niche and rewriting it in your voice. Results depend on the idea, the delivery and the account.
  • Nothing logs into your accounts or scrapes behind a login. Post data comes from what you paste or export, or from public pages.
  • The upstream skills are credited and linked, not copied. Install them alongside for the deep versions; each master skill tells Claude when to use them.
  • Tools are Python standard library only. Media tools need ffmpeg on your PATH.

Credits

Edit: HyperFrames by HeyGen (Apache-2.0), Remotion agent skills by Remotion, video-use by Browser Use (MIT). Virality: linkedin-agent-skill and youtube-agent-skill by Jake Schincariol (MIT). Build: impeccable by Paul Bakaus (Apache-2.0), frontend-design by Anthropic (Apache-2.0), gstack by Garry Tan (MIT), superpowers by Jesse Vincent (MIT).

License

MIT

// HOW IT'S BUILT

// FILES

9 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • skills/edit/SKILL.md17 KB208c8aa6d7f9upstream ↗
    ---
    name: edit
    description: >
      Edit talking-head and short-form video end to end: cut dead space, ums and retakes, add
      word-timed captions, dynamic visuals and stop motion, then finish the audio at -14 LUFS and
      export for Reels, TikTok and Shorts. Combines the HyperFrames, Remotion and video-use editing
      skills with local ffmpeg tools. Use whenever someone wants to edit, cut, tighten or caption a
      video, or says "cut the dead space", "remove the silences", "cut the ums", "jump cuts", "add
      captions" or "subtitles", "make this a reel", "add b-roll" or "motion graphics", "make a stop
      motion", "fix my audio", or drops raw footage that needs to become postable.
    ---
    
    # Edit
    
    You are the editor. This skill is an opinionated workflow plus small local tools (Python 3
    standard library + ffmpeg). The tools do the measurable work: dead-space cuts, caption files,
    stop-motion timing, probing. You do the judgement: what to cut, what to show, when. For motion
    graphics you route to HyperFrames (default), Remotion, or video-use.
    
    You cannot watch or listen. Measure, extract stills, read the transcript, and say plainly what
    you checked and what you could not.
    
    Tools live in `tools/` next to this file. Below, `T` means that folder:
    `python3 "$T/deadspace.py" --help` works for every tool. All tools exit 0 on success, 1 on an
    ffmpeg/runtime failure, 2 on bad input, 3 when a program or feature is missing.
    
    | Tool | Does | Writes |
    |---|---|---|
    | `probe.py` | media facts (rotation, VFR, HDR, audio layout, loudness); `--doctor` checks the machine | stdout / JSON |
    | `deadspace.py` | cuts silences, plus fillers and retakes with a transcript; frame-accurate, crossfaded joins | `<name>.cut.mp4`, `.edl.json`, `.words.json` |
    | `captions.py` | transcribes (faster-whisper, optional) or reads word timings; 1-3 word phrases | `.srt`, `.ass`, `.cues.json`, `.words.json`, `.phrases.txt` |
    | `stopmotion.py` | frames folder or live clip to stop motion: 8/10/12 drawings/s, holds, seeded jitter | `.mp4` |
    
    ## 0. Setup check (once per session)
    
    ```bash
    python3 "$T/probe.py" --doctor
    ```
    It reports: ffmpeg filters (is `ass`/`subtitles` there for burned-in captions?), encoders,
    faster-whisper, and Node (HyperFrames needs Node 22+). Do not install anything without asking.
    Put every output in `<footage folder>/edit/`, never inside this skill's folder.
    
    ## 1. Brief, then a plan the user approves
    
    Infer what you can, ask only what changes the edit: platform (default Reels/TikTok/Shorts,
    1080x1920), target length, pace (`tight` for shorts, `normal`, `loose` for talks), caption style,
    how much motion. Then state the plan in 3 to 6 lines (what gets cut, caption style, which beats
    get visuals, the engine) and wait for an OK before rendering, unless the user said "just do it".
    
    ## 2. Probe
    
    ```bash
    python3 "$T/probe.py" take.mov --loudness
    ```
    Note the display size after rotation, fps and VFR, HDR, channels and loudness. The tools handle
    rotation (ffmpeg autorotates), VFR (deadspace renders constant frame rate), mono/stereo (kept as
    recorded) and HDR (kept as 10-bit HEVC with its tags). If there is no audio stream, dead-space
    cutting is impossible: say so and cut by hand from stills.
    
    ## 3. Transcribe once, read the take
    
    ```bash
    python3 "$T/captions.py" take.mov --words-only --verbatim -o edit/
    ```
    - Writes `edit/take.words.json` (cached: reruns reuse it unless the file changed) and
      `edit/take.phrases.txt`, one timed line per phrase. Read phrases.txt; it is your view of the
      take at a fraction of the tokens.
    - `--verbatim` nudges Whisper to keep "um/uh" so they can be cut. Whisper still drops some, so
      never promise every filler is caught.
    - `--model small` is the default; use `--model medium` or `large-v3` when words matter (finals,
      accents). `--prompt "Claude, HyperFrames, Remotion"` helps with names and brands.
    - No faster-whisper? Exit 3 with install steps. Any word-level JSON works instead via `--words`
      (ElevenLabs Scribe, Whisper, whisper.cpp, Deepgram, AssemblyAI, HyperFrames transcript.json),
      and SRT/VTT works with approximate word times.
    - Proofread names and brands in words.json by hand (keep the timings). A wrong word on screen is
      worse than no caption.
    
    ## 4. Cut the dead space (dry run, review, render)
    
    ```bash
    python3 "$T/deadspace.py" take.mov -o edit/take.cut.mp4 --transcript edit/take.words.json --dry-run
    # read the printed cuts and edit/take.cut.edl.json, then:
    python3 "$T/deadspace.py" take.mov -o edit/take.cut.mp4 --from-edl edit/take.cut.edl.json
    ```
    How it decides:
    - A 10 ms envelope with an adaptive gate: the noise floor is the 10th percentile, speech the loud
      frames, and the gate sits 30 dB under speech but never within 8 dB of the floor. It works on
      quiet phone takes and noisy rooms. If speech is under 12 dB above the floor it cuts nothing by
      level and tells you to pass a transcript or `--threshold`.
    - Pace presets (pause cut when longer than / air kept before speech / after speech):
      `tight` 0.25 / 0.06 / 0.10 s, `normal` 0.35 / 0.08 / 0.14 s, `loose` 0.60 / 0.12 / 0.22 s.
      A cut pause leaves about 0.2 s of air at normal: tight, never breathless.
    - With a transcript: fillers are cut with their gap, and repeated lines are cut so the last take
      wins (`--retakes exact` for stutters and false starts only, `fuzzy` (default) also catches a
      re-said sentence with small changes, `off`). Silence cuts never pass through a transcribed word
      that has real energy.
    - Joins: keep ranges snap to the frame grid, audio gets 30 ms equal-power crossfades (no clicks),
      and A/V stays in sync (the summary prints the drift, normally under 1 ms).
    
    Review before rendering. The tool is mechanical: you read phrases.txt and also cut semantic
    retakes it missed (a line said twice with different words, a restart after "wait, let me redo
    that"). The EDL's `cuts[]` is the source of truth: set `"apply": false` to veto a cut, append
    `{"start": s, "end": e, "reason": "manual"}` to add one, then render with `--from-edl`. Keep
    the speaker's best delivery, keep laughs and reactions after punchlines.
    
    After rendering, `edit/take.cut.words.json` holds the words on the cut timeline. Use it for
    captions and visuals; never re-transcribe the cut.
    
    ## 5. Pace and structure
    
    - Hook: the first 1 to 2 s land a concrete payoff (a number, money made or saved, the result).
      Keep the face on screen during the hook (split screen or cutout), no slow push-in.
    - Cut, don't hold: in a short, no shot runs past about 1.5 s; aim for a median shot of 1 s or
      less. A beat longer than that gets 2 or 3 genuinely different shots (a reframe of the same
      take counts, two moments of a locked camera do not).
    - Plan with a beat table keyed to the words: time, the noun being said, the visual. Measure the
      finished cut: `ffmpeg -i final.mp4 -vf "select='gt(scene,0.25)',showinfo" -f null - 2>&1 | grep -o "pts_time:[0-9.]*"`
      lists cut times; compute the median gap.
    
    ## 6. Captions
    
    ```bash
    python3 "$T/captions.py" edit/take.cut.mp4 --words edit/take.cut.words.json -o edit/
    ```
    - 1 to 3 word phrases. They break after `. ! ?`, after commas once a phrase has 2 words, on
      pauses of 0.3 s or more, and at 18 characters. A phrase never ends on a weak opener ("the",
      "to", "a"), and a phrase too quick to read grows by a word.
    - Default look: UPPERCASE bold, white with a black outline, the spoken word in an accent colour
      (`--accent`), fillers hidden. The text bottom sits at y 1440 of 1920 (chest or collar) with
      140 px side margins, so it stays inside the safe zone. `--position seam --y 960` centres the
      captions on a split-screen seam, and `--position top` puts them under the header.
    - Never over the face. Extract a still to check:
      `ffmpeg -ss 3 -i edit/take.cut.mp4 -frames:v 1 edit/check.png`. If the chin sits low, move the
      captions with `--y`.
    - Burn in: `--burn edit/captioned.mp4` works only when ffmpeg has libass. Without it, the tool
      exits 3 with the routes. HyperFrames route: render the captions in HyperFrames
      (`/embedded-captions`). Copy `take.cut.words.json` into that project as `transcript.json`; it
      uses the same `{text, language_code, words[{text, start, end}]}` shape, so the proofread words
      are reused instead of re-transcribed. For custom kinetic captions in any engine, feed
      `take.cut.cues.json` (phrases, per-word times, size, safe area). On macOS, an ffmpeg with
      libass comes from the homebrew-ffmpeg tap: `brew uninstall ffmpeg`, `brew trust homebrew-ffmpeg/ffmpeg`,
      `brew tap homebrew-ffmpeg/ffmpeg`, `brew install homebrew-ffmpeg/ffmpeg/ffmpeg`.
    
    ## 7. Dynamic visuals (route to an engine)
    
    | Situation | Engine | Install (verified from each repo's README) |
    |---|---|---|
    | Default: overlays, kinetic type, b-roll cards, zooms, captions on footage | HyperFrames (HTML to video, deterministic render) | `claude plugin marketplace add heygen-com/hyperframes` then `claude plugin install hyperframes@hyperframes`, or standalone `npx skills add heygen-com/hyperframes` (agents: `npx hyperframes skills update`). Needs Node.js 22+ and FFmpeg. |
    | The user already has a Remotion project or React brand components | Remotion agent skills | `npx skills add remotion-dev/skills` |
    | Many takes, transcript-driven selection, a self-checking render loop | video-use | `git clone https://github.com/browser-use/video-use ~/Developer/video-use`, `ln -sfn ~/Developer/video-use ~/.claude/skills/video-use`, then in that folder `uv sync` (or `pip install -e .`). Needs an ElevenLabs API key in `.env` (`cp .env.example .env`). |
    
    In HyperFrames, start at `/hyperframes`. It routes designed overlays on footage to
    `/talking-head-recut`, plain captions to `/embedded-captions`, short motion graphics to
    `/motion-graphics`, and re-cuts or reframes to `/general-video`. Hand every engine the same data:
    the cut video, `*.cut.words.json` (output timeline), `*.cues.json`, the EDL.
    
    House rules for visuals:
    - Show the noun on the word: the visual lands on the frame the word is said, and shows the
      literal thing named (sales means a cart and money, a schedule means something landing on a
      calendar). If no honest asset exists, stay on the face and reframe.
    - Real UI at real proportions: capture the real page or app and zoom uniformly. Never invent a
      condensed card with inflated type, never slice text with a card edge.
    - No scanner effects: no light sweeps, sheens, glows, halos, pulse rings. Crisp motion is a fast
      entrance (4 to 8 frames, strong ease out, 2 to 4 frame stagger), then a clean hold.
    - Safe zone on 1080x1920: keep text and key UI inside x 90 to 950, y 240 to 1470. The header
      covers the top, the caption block the bottom, and the button rail covers x > 950 below y 1000.
      Text under about 30 px is texture, not information.
    - Every beat gets a different object, not one template repeated. Keep the main element on screen
      from frame 1 of its beat. A face shown between two graphics needs at least 0.8 s.
    - Several animations: brief one sub-agent per animation in parallel, each writing its own file.
    
    ## 8. Stop motion
    
    ```bash
    python3 "$T/stopmotion.py" frames/ -o edit/stop.mp4                  # 12 drawings/s on twos, 24 fps
    python3 "$T/stopmotion.py" frames/ -o edit/loop.mp4 --fps 8 --hold 3 --pingpong --loop 2
    python3 "$T/stopmotion.py" --from-video edit/take.cut.mp4 -o edit/take.stop.mp4 --fps 12
    ```
    - `--fps` sets drawings per second (8 for chunky, 10, 12 for smooth). `--hold` sets frames per
      drawing (2 means "on twos"). Output fps = fps x hold.
    - The hand-made feel comes from per-drawing jitter (`--jitter` px, default 0.5% of the short
      side) and rotation (`--rotate` deg, default 0.5). It is seeded: the same `--seed` gives an
      identical render, and each loop pass wobbles differently. `--flicker 0.01` adds exposure drift;
      it is off by default. `--end-hold 1` holds the last pose.
    - Mixed sizes and formats are fitted to the canvas (`--size 1080x1920 --fit cover|contain`).
      Transparent PNGs go on `--bg`. From-video mode keeps the original audio in sync.
    
    Making the frames, any style:
    - One subject, locked: write a model sheet first (shape, palette as hex, materials, camera
      height and lens, light direction). Every frame prompt or drawing reuses it word for word, and
      only the pose or position changes. Keep the camera locked; movement belongs to the subject.
    - With the user's image tool: generate a hero frame, then each next frame from the previous one
      as a reference with one small change (2 to 5% motion). Use 8 to 24 frames for a 1 to 2 s move.
      Styles: clay (fingerprints, soft key light, matte), paper cut-out (flat layers, drop shadows,
      visible paper grain), bricks (studs, plastic sheen, snapped positions), sticky notes (one note
      per frame on a wall, marker text), pixel (fixed grid, limited palette, no anti-aliasing).
    - Drawing it yourself: write each frame as SVG with the character as reusable `<g>` groups and
      move only transforms between frames. Add 1 to 2 px random offsets to path points for line
      boil. Rasterize with what exists (`rsvg-convert`, ImageMagick, headless Chrome screenshots) or
      build it as a HyperFrames composition with stepped timing. Then run `stopmotion.py` on the PNGs.
    
    ## 9. Audio finishing (one fixed gain, -14 LUFS, limiter)
    
    Rules: never compress, gate or AGC the voice (it lifts room echo between words and chops word
    tails). Never use single-pass `loudnorm`, which is dynamic and acts as an AGC. Apply one fixed
    gain to -14 LUFS integrated, then a look-ahead limiter at -1.5 dBTP oversampled for true peak.
    A music bed sits about 15 dB under the voice at a fixed level.
    
    ```bash
    # 1) measure (same pre-filter as the master)
    ffmpeg -hide_banner -nostats -i edit/final.mp4 -map 0:a:0 -af "highpass=f=75,ebur128=peak=true:framelog=verbose" -f null - 2>&1 | grep -E "^\s+(I|Peak):"
    # 2) G = -14 - I   (example: I = -21.3 gives G = 7.3)
    ffmpeg -i edit/final.mp4 -map 0:v -map 0:a -c:v copy \
      -af "highpass=f=75,volume=7.3dB,aresample=192000,alimiter=limit=0.841:attack=5:release=50:level=false:latency=true,aresample=48000" \
      -c:a aac -b:a 256k -movflags +faststart edit/final.master.mp4
    # 3) measure again: I within 0.5 LU of -14, Peak at or under -1.5 (AAC can add a few tenths)
    ```
    - `level=false` matters: the limiter's default auto-level raises everything. `latency=true`
      removes its 5 ms delay. Older ffmpeg builds lack it: check `probe.py --doctor`.
    - Music bed: measure the voice (I_v) and the music (I_m), then gain the music by
      `I_v - 15 - I_m` dB and mix with `amix=inputs=2:duration=first:normalize=0`, then master the
      mix as above. Fade the bed out about 1 s before the end. Use a bed at least as long as the
      video; a looped file with a faded ending dips every loop.
    - `-ac 1` sums stereo without scaling (+6 dB). Downmix with `pan=mono|c0=0.5*c0+0.5*c1`.
    - If peaks would be limited by more than about 6 dB, say so and offer -16 LUFS instead.
    - You cannot hear the result. Report the numbers, and when a change is a judgement by ear, give
      the user a short A/B of the same excerpt.
    
    ## 10. Export and self-check before showing anything
    
    Reels / TikTok / Shorts: 1080x1920 (9:16), H.264 High `yuv420p`, 30 fps (or the source rate up
    to 60), AAC 48 kHz, `-movflags +faststart`, -14 LUFS, -1.5 dBTP. Platform limits change, so
    check length limits when they matter.
    - Reframe 16:9 to 9:16 without bars: `-vf "scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920"`.
      With bars: `-vf "scale=1080:1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2"`.
    - Encode: `-c:v libx264 -crf 18 -preset slow -profile:v high -pix_fmt yuv420p -r 30`.
    
    Before you show the user, check:
    1. `probe.py final.mp4`: right size, fps and duration, audio present, video and audio durations
       within a frame.
    2. Loudness measured (step 9), numbers reported.
    3. Stills at the first frame, each join, and 3 caption moments: nothing over the face, all text
       inside the safe zone, no frozen hold over 1.5 s, and the first frame works as a cover.
    4. Captions read the words actually said (spot-check against words.json).
    5. Fix and re-check at most 3 times, then hand over with the open issues listed.
    
    ## Failure handling
    
    - `probe.py --doctor` says ffmpeg is missing: give the install command and stop.
    - No audio: no dead-space cut; offer a manual cut list from stills.
    - "Unreliable" gate (noisy room or music under the voice): use `--transcript`, or set
      `--threshold` from the printed levels.
    - Too much cut (clipped words): use `--pace loose` or larger `--pad-before/--pad-after`. Too
      little: use `--pace tight`.
    - VFR phone footage: fine, it is rendered at constant frame rate. HDR: kept 10-bit; convert to
      SDR once before an engine that renders SDR.
    - No libass: use the HyperFrames route (step 6). No faster-whisper: use `--words` or the venv
      install it prints. Node under 22: HyperFrames will not run; use Remotion if installed, or ship
      captions + cuts without overlays and say so.
    
    ## Limits (honest)
    
    - The tools never watch or listen. Cuts come from levels and word timings, so review the EDL.
      Retake detection is a heuristic and the last take wins.
    - Transcripts are only as good as the model. Whisper drops some fillers and misspells names.
    - No generative video or images are made here. Stop-motion frames come from your image tool or
      from SVG you draw.
    - Nothing logs into or posts to any account.
    
    Credits and licenses for the merged upstream skills: [CREDITS.md](CREDITS.md).
    
  • skills/edit/CREDITS.md1.2 KB731edb754ccfupstream ↗
    # Credits
    
    The edit skill combines ideas from three editing skills. No upstream text or code is copied into
    this folder. The workflow, tools and wording are original, and each upstream project is linked
    for its deep version.
    
    | Project | License | What this skill learned from it | Link |
    |---|---|---|---|
    | HyperFrames (HeyGen) | Apache-2.0 | HTML-to-video as the default motion engine; route captions, overlays and motion graphics to its skills; word-level transcript reuse | https://github.com/heygen-com/hyperframes |
    | Remotion Agent Skills | no license file: linked only, nothing copied | React-based motion for users already on Remotion | https://github.com/remotion-dev/skills |
    | video-use (Browser Use) | MIT | transcript-first editing, cut at word boundaries with padding, short fades at every join, an EDL, confirm the plan first, self-check the render | https://github.com/browser-use/video-use |
    
    Install commands quoted in SKILL.md come from each repository's README (checked October 2026).
    
    House taste rules (pacing, safe zone, captions, motion, audio chain) come from the shipped reels
    of Jake Schincariol (@opusjake).
    
    The tools in `tools/` are MIT licensed as part of
    [Jakeschincariol/master-skills](https://github.com/Jakeschincariol/master-skills).
    
  • skills/edit/tools/captions.py18 KBec2ee6369c85upstream ↗
    #!/usr/bin/env python3
    """Word-timed captions: 1-3 word phrases as SRT, styled ASS and a JSON cue list.
    
      python3 captions.py take.cut.mp4 --words take.cut.words.json     # from word timings
      python3 captions.py take.mp4 --words-only                         # transcribe once (faster-whisper)
      python3 captions.py take.cut.mp4 --words w.json --burn final.mp4  # burn in if ffmpeg has libass
    
    Writes <stem>.srt, <stem>.ass (bold, active word highlighted, inside the 9:16 safe zone),
    <stem>.cues.json (phrases + per-word times for HyperFrames/Remotion), and when it
    transcribes, <stem>.words.json + <stem>.phrases.txt. Burning in needs ffmpeg's ass or
    subtitles filter (libass); without it the tool says so and you use the HyperFrames route.
    
    Part of github.com/Jakeschincariol/master-skills (MIT).
    """
    from __future__ import annotations
    
    import argparse
    import json
    import os
    import re
    import shutil
    import sys
    import tempfile
    
    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    import mediakit as mk  # noqa: E402
    
    FILLERS = {"um", "umm", "ummm", "uh", "uhh", "uhm", "er", "erm", "ah", "ahh", "hmm", "hm", "mm", "mmm"}
    # words that open a phrase: a chunk should not end on them when the sentence continues
    WEAK_ENDINGS = {"a", "an", "the", "to", "of", "and", "or", "but", "for", "in", "on", "at", "with",
                    "from", "by", "into", "my", "your", "our", "their", "his", "her", "its", "if", "as",
                    "is", "are", "was", "were", "will", "can"}
    VERBATIM_PROMPT = "Um, so, uh, I mean, like, you know, uh, okay. Hmm, um, let me, uh, think."
    INSTALL_HINT = (
        "faster-whisper is not installed, so I cannot transcribe. Either install it "
        "(python3 -m venv ~/.venvs/edit && ~/.venvs/edit/bin/pip install faster-whisper, then run this "
        "tool with ~/.venvs/edit/bin/python; the model downloads on first use), or pass --words with "
        "word timings from any transcriber: ElevenLabs Scribe, Whisper/faster-whisper JSON with word "
        "timestamps, whisper.cpp JSON, Deepgram, AssemblyAI, HyperFrames transcript.json, or an SRT/VTT "
        "(word times approximated inside each cue)."
    )
    
    
    def norm(text: str) -> str:
        return re.sub(r"[^\w']+", "", text.lower()).strip("'")
    
    
    def display_text(text: str, case: str, keep_punct: bool) -> str:
        if not keep_punct:
            text = re.sub(r"[,;:]+$", "", text)
            if text.endswith(".") and text.count(".") == 1:
                text = text[:-1]
        return text.upper() if case == "upper" else text.lower() if case == "lower" else text
    
    
    def chunk_words(words: list, max_words: int = 3, max_chars: int = 18, pause: float = 0.3,
                    min_dur: float = 0.3) -> list:
        """Group words into caption phrases. Break after . ! ? (and after commas once a phrase
        has 2 words), on pauses >= `pause`, at max_words / max_chars, never end a full phrase
        on a weak opener ('the', 'to', ...), and grow a phrase rather than flash it < min_dur."""
        chunks, cur = [], []
        for i, word in enumerate(words):
            nxt = words[i + 1] if i + 1 < len(words) else None
            cur.append(word)
            text_len = len(" ".join(w["text"] for w in cur))
            hard = word["text"][-1:] in ".!?" or nxt is None or nxt["start"] - word["end"] >= pause
            soft = word["text"][-1:] in ",;:" and len(cur) >= 2
            nxt_len = text_len + 1 + len(nxt["text"]) if nxt else 0
            full = len(cur) >= max_words or (nxt is not None and nxt_len > max_chars)
            if not (hard or soft or full):
                continue
            if (not hard and len(cur) < max_words and nxt is not None and nxt_len <= max_chars + 4
                    and nxt["end"] - cur[0]["start"] < 1.2 and word["end"] - cur[0]["start"] < min_dur):
                continue  # too quick to read: let it grow by one word
            if full and not hard and len(cur) >= 2 and norm(word["text"]) in WEAK_ENDINGS:
                carry = cur.pop()
                chunks.append(cur)
                cur = [carry]
                continue
            chunks.append(cur)
            cur = []
        if cur:
            chunks.append(cur)
        cues = []
        for i, group in enumerate(chunks):
            start = group[0]["start"]
            end = group[-1]["end"]
            if i + 1 < len(chunks):
                next_start = chunks[i + 1][0]["start"]
                end = next_start if next_start - end <= 0.5 else end + 0.25
                end = min(max(end, start + min_dur), next_start)
            else:
                end = max(end + 0.25, start + min_dur)
            cues.append({"start": round(start, 3), "end": round(end, 3), "words": group})
        return cues
    
    
    def srt_time(t: float) -> str:
        ms = int(round(max(0.0, t) * 1000))
        return f"{ms // 3600000:02d}:{ms // 60000 % 60:02d}:{ms // 1000 % 60:02d},{ms % 1000:03d}"
    
    
    def ass_time(t: float) -> str:
        cs = int(round(max(0.0, t) * 100))
        return f"{cs // 360000}:{cs // 6000 % 60:02d}:{cs // 100 % 60:02d}.{cs % 100:02d}"
    
    
    def ass_color(hex_color: str, alpha: int = 0) -> str:
        h = hex_color.lstrip("#")
        if not re.fullmatch(r"[0-9a-fA-F]{6}", h):
            raise mk.EditError(f"bad colour {hex_color!r}, use #RRGGBB", mk.EXIT_USAGE)
        return f"&H{alpha:02X}{h[4:6]}{h[2:4]}{h[0:2]}".upper()
    
    
    def layout(width: int, height: int, position: str, y: int | None) -> dict:
        """Caption anchor. 9:16: lower = text bottom at 75% height (y 1440 of 1920, chest or collar,
        under the IG caption block line of 1470); seam = centred on a split-screen seam; top = just
        under the 240 px header. Side margins keep text clear of the right-hand button rail."""
        vertical = height > width
        margin_x = int(round(width * (0.13 if vertical else 0.08)))
        if position == "lower":
            bottom = y if y is not None else int(round(height * (0.75 if vertical else 0.92)))
            return {"align": 2, "margin_v": height - bottom, "anchor_y": bottom, "margin_x": margin_x}
        if position == "top":
            top = y if y is not None else int(round(height * (0.135 if vertical else 0.06)))
            return {"align": 8, "margin_v": top, "anchor_y": top, "margin_x": margin_x}
        centre = y if y is not None else height // 2
        return {"align": 5, "margin_v": 0, "anchor_y": centre, "margin_x": margin_x, "pos": True}
    
    
    def build_ass(cues: list, width: int, height: int, args) -> str:
        lay = layout(width, height, args.position, args.y)
        size = args.font_size or int(round(height * (0.044 if height > width else 0.06)))
        outline = max(2, int(round(size * 0.075)))
        head = [
            "[Script Info]", "; made by master-skills edit/captions.py", "ScriptType: v4.00+",
            f"PlayResX: {width}", f"PlayResY: {height}", "WrapStyle: 0", "ScaledBorderAndShadow: yes",
            "YCbCr Matrix: TV.709", "",
            "[V4+ Styles]",
            "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, "
            "Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, "
            "Shadow, Alignment, MarginL, MarginR, MarginV, Encoding",
            f"Style: Caption,{args.font},{size},{ass_color(args.color)},{ass_color(args.color)},"
            f"&H00000000,&H64000000,-1,0,0,0,100,100,0,0,1,{outline},2,{lay['align']},"
            f"{lay['margin_x']},{lay['margin_x']},{lay['margin_v']},1",
            "", "[Events]",
            "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
        ]
        pos = f"{{\\an5\\pos({width // 2},{lay['anchor_y']})}}" if lay.get("pos") else ""
        accent = ass_color(args.accent)
        events = []
        for cue in cues:
            texts = [w["display"] for w in cue["words"]]
            if args.no_highlight:
                events.append((cue["start"], cue["end"], pos + " ".join(texts)))
                continue
            for k, word in enumerate(cue["words"]):
                start = cue["start"] if k == 0 else word["start"]
                end = cue["end"] if k == len(cue["words"]) - 1 else cue["words"][k + 1]["start"]
                if end <= start:
                    continue
                parts = [f"{{\\c{accent}&}}{t}{{\\r}}" if j == k else t for j, t in enumerate(texts)]
                events.append((start, end, pos + " ".join(parts)))
        lines = [f"Dialogue: 0,{ass_time(s)},{ass_time(e)},Caption,,0,0,0,,{text}" for s, e, text in events]
        return "\n".join(head + lines) + "\n"
    
    
    def transcribe(media: str, args) -> tuple:
        try:
            from faster_whisper import WhisperModel  # optional extra
        except ImportError:
            raise mk.EditError(INSTALL_HINT, mk.EXIT_MISSING)
        prompt = " ".join(p for p in (VERBATIM_PROMPT if args.verbatim else "", args.prompt or "") if p) or None
        print(f"transcribing with faster-whisper {args.model} (first run downloads the model)...", file=sys.stderr)
        model = WhisperModel(args.model, device=args.device, compute_type="auto")
        segments, info = model.transcribe(media, word_timestamps=True, vad_filter=True, beam_size=5,
                                          language=args.language, initial_prompt=prompt,
                                          condition_on_previous_text=False)
        words = []
        for seg in segments:
            for w in seg.words or []:
                words.append({"text": w.word.strip(), "start": w.start, "end": w.end, "prob": w.probability})
        return mk._clean_words(words), getattr(info, "language", None) or args.language or "en"
    
    
    def main() -> int:
        p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], epilog=mk.EXIT_CODES_HELP,
                                    formatter_class=argparse.RawDescriptionHelpFormatter)
        p.add_argument("input", help="video/audio file (or a words JSON/SRT/VTT when there is no media)")
        p.add_argument("--words", help="word timings (JSON/SRT/VTT); skips transcription")
        p.add_argument("-o", "--outdir", help="output folder (default: next to the input)")
        p.add_argument("--name", help="output file stem (default: input stem)")
        p.add_argument("--words-only", action="store_true", help="just transcribe: write words.json + phrases.txt")
        p.add_argument("--model", default="small", help="faster-whisper model (small; medium/large-v3 for finals)")
        p.add_argument("--language", help="language code, e.g. en (default: auto)")
        p.add_argument("--prompt", help="vocabulary hint: names, brands, jargon")
        p.add_argument("--verbatim", action="store_true", help="nudge Whisper to keep ums/uhs (for deadspace)")
        p.add_argument("--device", default="auto", help="faster-whisper device: auto, cpu, cuda")
        p.add_argument("--retranscribe", action="store_true", help="ignore a cached words.json")
        p.add_argument("--max-words", type=int, default=3, help="words per caption (1-3 recommended)")
        p.add_argument("--max-chars", type=int, default=18, help="characters per caption line")
        p.add_argument("--pause", type=float, default=0.3, help="a pause this long starts a new caption (s)")
        p.add_argument("--case", choices=["upper", "lower", "keep"], default="upper")
        p.add_argument("--keep-fillers", action="store_true", help="show um/uh in captions")
        p.add_argument("--keep-punctuation", action="store_true", help="keep trailing commas and periods")
        p.add_argument("--size", help="canvas WxH (default: the video's display size, else 1080x1920)")
        p.add_argument("--position", choices=["lower", "seam", "top"], default="lower")
        p.add_argument("--y", type=int, help="anchor y in px (lower: text bottom, seam: centre, top: text top)")
        p.add_argument("--font", default="Arial", help="font family (must be installed for libass)")
        p.add_argument("--font-size", type=int, help="px (default 4.4%% of height, 84 on 1920)")
        p.add_argument("--color", default="#FFFFFF", help="text colour")
        p.add_argument("--accent", default="#FFD400", help="active-word colour")
        p.add_argument("--no-highlight", action="store_true", help="no active-word highlight")
        p.add_argument("--burn", metavar="OUT", help="burn the ASS into a copy of the video (needs libass)")
        p.add_argument("--json", action="store_true", help="print a JSON summary")
        args = p.parse_args()
        if not 1 <= args.max_words <= 8:
            p.error("--max-words must be 1-8")
    
        is_text_input = os.path.splitext(args.input)[1].lower() in (".json", ".srt", ".vtt")
        info = None if is_text_input else mk.probe(args.input)
        outdir = args.outdir or os.path.dirname(os.path.abspath(args.input))
        os.makedirs(outdir, exist_ok=True)
        stem = args.name or mk.stem_of(args.input)
        base = os.path.join(outdir, stem)
        summary = {"files": {}}
    
        if args.words or is_text_input:
            words = mk.load_words(args.words or args.input, info["duration"] if info else None)
            language = None
        else:
            if not info.get("audio"):
                raise mk.EditError("no audio stream to transcribe; pass --words", mk.EXIT_USAGE)
            cache = base + ".words.json"
            words, language = None, None
            if os.path.isfile(cache) and not args.retranscribe:
                with open(cache, encoding="utf-8") as handle:
                    doc = json.load(handle)
                src = doc.get("source") or {}
                stat = os.stat(args.input)
                if src.get("size") == stat.st_size and abs((src.get("mtime") or 0) - stat.st_mtime) < 1:
                    words, language = mk.load_words(cache), doc.get("language_code")
                    print(f"using cached transcript {cache}", file=sys.stderr)
            if words is None:
                words, language = transcribe(args.input, args)
                mk.save_words(cache, words, source=args.input, language=language,
                              engine=f"faster-whisper {args.model}")
            summary["files"]["words"] = cache
            with open(base + ".phrases.txt", "w", encoding="utf-8") as handle:
                handle.write("\n".join(mk.phrase_lines(words)) + "\n")
            summary["files"]["phrases"] = base + ".phrases.txt"
        if not words:
            raise mk.EditError("no words to caption", mk.EXIT_USAGE)
        summary["words"] = len(words)
        if args.words_only:
            print(json.dumps(summary, indent=2) if args.json else
                  f"transcript: {len(words)} words -> {summary['files'].get('words')}")
            return mk.EXIT_OK
    
        shown = [w for w in words if args.keep_fillers or norm(w["text"]) not in FILLERS]
        for w in shown:
            w["display"] = display_text(w["text"], args.case, args.keep_punctuation)
        shown = [w for w in shown if w["display"]]
        cues = chunk_words(shown, args.max_words, args.max_chars, args.pause)
        if args.size:
            width, height = mk.parse_size(args.size)
        elif info and info.get("video"):
            width, height = info["video"]["display_width"], info["video"]["display_height"]
        else:
            width, height = 1080, 1920
    
        with open(base + ".srt", "w", encoding="utf-8") as handle:
            for i, cue in enumerate(cues, 1):
                text = " ".join(w["display"] for w in cue["words"])
                handle.write(f"{i}\n{srt_time(cue['start'])} --> {srt_time(cue['end'])}\n{text}\n\n")
        with open(base + ".ass", "w", encoding="utf-8") as handle:
            handle.write(build_ass(cues, width, height, args))
        lay = layout(width, height, args.position, args.y)
        safe = mk.SAFE_AREA_9x16 if (width, height) == (1080, 1920) else None
        mk.write_json(base + ".cues.json", {
            "version": 1, "kind": "caption-cues", "source": info["path"] if info else None,
            "width": width, "height": height, "safe_area": safe,
            "style": {"case": args.case, "font": args.font, "color": args.color, "accent": args.accent,
                      "position": args.position, "anchor_y": lay["anchor_y"],
                      "align": {2: "bottom", 8: "top", 5: "middle"}[lay["align"]]},
            "cues": [{"i": i, "start": c["start"], "end": c["end"],
                      "text": " ".join(w["display"] for w in c["words"]),
                      "words": [{"text": w["display"], "start": w["start"], "end": w["end"]} for w in c["words"]]}
                     for i, c in enumerate(cues)],
        })
        summary["files"].update({"srt": base + ".srt", "ass": base + ".ass", "cues": base + ".cues.json"})
        summary["cues"] = len(cues)
    
        code = mk.EXIT_OK
        if args.burn:
            if not info or not info.get("video"):
                raise mk.EditError("--burn needs a video input", mk.EXIT_USAGE)
            flt = "ass" if mk.has_filter("ass") else "subtitles" if mk.has_filter("subtitles") else None
            if not flt:
                print("cannot burn in: this ffmpeg has no libass (no 'ass' or 'subtitles' filter). The SRT, "
                      "ASS and cues files are written. Route: render the captions with HyperFrames "
                      "(/embedded-captions, reusing the words.json as transcript.json), or install an ffmpeg "
                      "with libass (macOS: brew uninstall ffmpeg, then brew trust homebrew-ffmpeg/ffmpeg, "
                      "brew tap homebrew-ffmpeg/ffmpeg, brew install homebrew-ffmpeg/ffmpeg/ffmpeg; most "
                      "Linux distro ffmpeg builds include libass).", file=sys.stderr)
                summary["burned"] = False
                code = mk.EXIT_MISSING
            else:
                with tempfile.TemporaryDirectory() as tmp:  # relative name avoids filter path escaping
                    shutil.copy(base + ".ass", os.path.join(tmp, "captions.ass"))
                    vargs, _ = mk.video_codec_args(info["video"], crf=17)
                    mk.run([mk.ffmpeg_bin(), "-nostdin", "-hide_banner", "-v", "error", "-y",
                            "-i", os.path.abspath(args.input), "-vf", f"{flt}=captions.ass",
                            "-map", "0:v:0", "-map", "0:a?"] + vargs +
                           ["-c:a", "copy", "-movflags", "+faststart", os.path.abspath(args.burn)], cwd=tmp)
                summary["burned"] = True
                summary["files"]["burned"] = os.path.abspath(args.burn)
        if args.json:
            print(json.dumps(summary, indent=2))
        else:
            print(f"captions: {len(cues)} phrases from {len(words)} words")
            for key, path in summary["files"].items():
                print(f"  {key}: {path}")
        return code
    
    
    if __name__ == "__main__":
        sys.exit(mk.run_main(main))
    
  • skills/edit/tools/deadspace.py23 KB516872780b96upstream ↗
    #!/usr/bin/env python3
    """Cut dead space (silences, plus ums and retakes when word timings are given).
    
      python3 deadspace.py take.mp4                           # analyze + render take.cut.mp4
      python3 deadspace.py take.mp4 --dry-run                 # only write take.cut.edl.json to review
      python3 deadspace.py take.mp4 --transcript take.words.json   # also cut fillers + retakes
      python3 deadspace.py take.mp4 --from-edl take.cut.edl.json   # render an EDL you edited
    
    How it works: a 10 ms speech envelope with an adaptive gate (noise floor + speech level,
    tuned for phone talking-head takes) finds pauses; each cut keeps a breath pad on both
    sides so words are never clipped; keep ranges snap to the video frame grid; audio joins
    get short equal-power crossfades (no clicks) while video stays frame-accurate, so A/V
    stays in sync. Writes an edit decision list (JSON). With a transcript it also writes
    the words re-timed to the cut (<output>.words.json) for captions.
    
    Part of github.com/Jakeschincariol/master-skills (MIT).
    """
    from __future__ import annotations
    
    import argparse
    import difflib
    import json
    import math
    import os
    import re
    import sys
    from fractions import Fraction
    
    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    import mediakit as mk  # noqa: E402
    
    PACES = {  # min_silence, pad_before, pad_after, min_cut (seconds)
        "tight": (0.25, 0.06, 0.10, 0.10),
        "normal": (0.35, 0.08, 0.14, 0.12),
        "loose": (0.60, 0.12, 0.22, 0.20),
    }
    DEFAULT_FILLERS = "um,umm,ummm,uh,uhh,uhm,er,erm,ah,ahh,hmm,hm,mm,mmm"
    VIDEO_EXTS = (".mp4", ".mov", ".m4v", ".mkv")
    AUDIO_CODECS = {".wav": ["-c:a", "pcm_s24le"], ".flac": ["-c:a", "flac"],
                    ".m4a": ["-c:a", "aac", "-b:a", "256k"], ".aac": ["-c:a", "aac", "-b:a", "256k"],
                    ".mp3": ["-c:a", "libmp3lame", "-q:a", "2"], ".opus": ["-c:a", "libopus", "-b:a", "160k"]}
    
    
    # ---------------------------------------------------------------- interval helpers
    
    def merge_cuts(cuts: list) -> list:
        """Union of cut dicts {start, end, reason, text}; overlapping cuts merge their reasons."""
        out = []
        for cut in sorted(cuts, key=lambda c: c["start"]):
            if out and cut["start"] <= out[-1]["end"] + 1e-6:
                last = out[-1]
                last["end"] = max(last["end"], cut["end"])
                reasons = last["reason"].split("+")
                if cut["reason"] not in reasons:
                    last["reason"] = "+".join(reasons + [cut["reason"]])
                if cut.get("text"):
                    last["text"] = ((last.get("text") or "") + " " + cut["text"]).strip()
            else:
                out.append(dict(cut))
        return out
    
    
    def keeps_from_cuts(cuts: list, start: float, end: float) -> list:
        keeps, cursor = [], start
        for cut in merge_cuts([c for c in cuts if c.get("apply", True)]):
            cs, ce = max(start, cut["start"]), min(end, cut["end"])
            if ce <= cs:
                continue
            if cs > cursor:
                keeps.append([cursor, cs])
            cursor = max(cursor, ce)
        if end > cursor:
            keeps.append([cursor, end])
        return keeps
    
    
    def find_silences(levels: list, hop: float, threshold: float, min_sound: float = 0.06) -> tuple:
        """Return (silent runs as (start, end) seconds from the first sample, first sound, last sound)."""
        loud = [v >= threshold for v in levels]
        runs, i = [], 0
        while i < len(loud):
            j = i
            while j < len(loud) and loud[j] == loud[i]:
                j += 1
            runs.append([loud[i], i, j])
            i = j
        for k, run in enumerate(runs):  # a click shorter than min_sound inside silence is still silence
            if run[0] and 0 < k < len(runs) - 1 and (run[2] - run[1]) * hop < min_sound:
                run[0] = False
        merged = []
        for run in runs:
            if merged and merged[-1][0] == run[0]:
                merged[-1][2] = run[2]
            else:
                merged.append(run)
        sound = [r for r in merged if r[0]]
        if not sound:
            return [], None, None
        silences = [(r[1] * hop, r[2] * hop) for r in merged if not r[0]]
        return silences, sound[0][1] * hop, sound[-1][2] * hop
    
    
    # ---------------------------------------------------------------- transcript cuts
    
    def norm_token(text: str) -> str:
        return re.sub(r"[^\w']+", "", text.lower()).strip("'")
    
    
    def _edges(words: list, k: int, pad_before: float, pad_after: float, t0: float, t1: float) -> tuple:
        """Cut boundaries in the gap before word k: (left edge keeping word k-1's pad,
        right edge keeping word k's pad). Pads shrink to half the gap when words are close."""
        if k <= 0:
            return t0, max(t0, words[0]["start"] - pad_before)
        if k >= len(words):
            return min(t1, words[-1]["end"] + pad_after), t1
        prev_end, start = words[k - 1]["end"], words[k]["start"]
        gap = max(0.0, start - prev_end)
        return prev_end + min(pad_after, gap / 2), start - min(pad_before, gap / 2)
    
    
    def transcript_cuts(words: list, fillers: set, retakes: str, pad_before: float, pad_after: float,
                        t0: float, t1: float) -> list:
        cuts = []
        for k, word in enumerate(words):
            if norm_token(word["text"]) in fillers:
                left, _ = _edges(words, k, pad_before, pad_after, t0, t1)
                _, right = _edges(words, k + 1, pad_before, pad_after, t0, t1)
                if right > left:
                    cuts.append({"start": left, "end": right, "reason": "filler", "text": word["text"]})
        if retakes == "off":
            return cuts
        idx = [k for k, w in enumerate(words) if norm_token(w["text"]) not in fillers and norm_token(w["text"])]
        tokens = [norm_token(words[k]["text"]) for k in idx]
        j = 1
        while j < len(tokens):
            found = None
            for length in range(min(25, j), 1, -1):  # longest abandoned attempt first
                a, b = tokens[j - length:j], tokens[j:j + length]
                first, restart = words[idx[j - length]], words[idx[j]]
                if restart["start"] - first["start"] > 15.0:
                    continue
                if a == b:
                    found = (length, "exact")
                    break
                if (retakes == "fuzzy" and length >= 4 and len(b) == length and a[:2] == b[:2]
                        and restart["start"] - words[idx[j - 1]]["end"] >= 0.25
                        and difflib.SequenceMatcher(None, a, b).ratio() >= 0.8):
                    found = (length, "fuzzy")
                    break
            if found:
                length = found[0]
                left, _ = _edges(words, idx[j - length], pad_before, pad_after, t0, t1)
                _, right = _edges(words, idx[j], pad_before, pad_after, t0, t1)
                text = " ".join(words[idx[m]]["text"] for m in range(j - length, j))
                if right > left:
                    cuts.append({"start": left, "end": right, "reason": "retake", "text": text})
            j += 1
        return cuts
    
    
    def remap_words(words: list, keeps: list) -> list:
        """Move word times from the source onto the cut timeline; words inside cuts are dropped."""
        out, offset, segments = [], 0.0, []
        for start, end in keeps:
            segments.append((start, end, offset))
            offset += end - start
        for word in words:
            mid = (word["start"] + word["end"]) / 2
            for start, end, out_start in segments:
                if start <= mid < end:
                    ws = out_start + max(word["start"], start) - start
                    we = out_start + min(word["end"], end) - start
                    item = dict(word, start=round(ws, 3), end=round(max(we, ws + 0.01), 3))
                    out.append(item)
                    break
        return out
    
    
    # ---------------------------------------------------------------- analysis
    
    def analyze(path: str, info: dict, args, words: list | None) -> dict:
        audio = info["audio_streams"][args.audio_stream]
        a_off = audio["offset"]
        t0 = 0.0
        t1 = info["end"] or info["duration"]
        levels = mk.audio_envelope(path, info, stream=args.audio_stream, hop=0.01)
        stats = mk.speech_levels(levels)
        threshold = args.threshold if args.threshold is not None else stats["threshold_db"]
        if not stats["reliable"] and args.threshold is None:
            mk.warn(f"speech is only {stats['spread_db']} dB above the noise floor; detection is "
                    "unreliable here, pass --transcript or --threshold")
        silences, first, last = find_silences(levels, 0.01, threshold)
        cuts = []
        if not stats["reliable"] and args.threshold is None:
            first = None  # no trustworthy gate: cut nothing by level rather than guess
        elif first is None:
            mk.warn("no speech found above the gate; nothing to cut")
        else:
            first, last = first + a_off, last + a_off
            head_end = first - args.pad_before
            if head_end - t0 >= args.min_cut:
                cuts.append({"start": t0, "end": head_end, "reason": "silence", "text": None})
            tail_start = last + args.pad_after
            if t1 - tail_start >= args.min_cut:
                cuts.append({"start": tail_start, "end": t1, "reason": "silence", "text": None})
            for s, e in silences:
                s, e = s + a_off, e + a_off
                if s <= first or e >= last or e - s < args.min_silence:
                    continue
                cs, ce = s + args.pad_after, e - args.pad_before
                if ce - cs >= args.min_cut:
                    cuts.append({"start": cs, "end": ce, "reason": "silence", "text": None})
        if words:
            shifted = [dict(w, start=w["start"] + a_off, end=w["end"] + a_off) for w in words]
            guarded = []
            for cut in cuts:  # never cut through a transcribed word that has real energy
                pieces = [[cut["start"], cut["end"]]]
                for w in shifted:
                    core_s, core_e = w["start"] + 0.06, w["end"] - 0.06
                    if core_e <= core_s or norm_token(w["text"]) in args.filler_set:
                        continue
                    lo = int((core_s - a_off) / 0.01)
                    hi = int((core_e - a_off) / 0.01) + 1
                    if not levels[max(0, lo):hi] or max(levels[max(0, lo):hi]) < stats["noise_db"] + 6:
                        continue
                    nxt = []
                    for ps, pe in pieces:
                        if core_e <= ps or core_s >= pe:
                            nxt.append([ps, pe])
                            continue
                        if core_s - ps >= args.min_cut:
                            nxt.append([ps, core_s])
                        if pe - core_e >= args.min_cut:
                            nxt.append([core_e, pe])
                    pieces = nxt
                guarded += [dict(cut, start=ps, end=pe) for ps, pe in pieces]
            cuts = guarded + transcript_cuts(shifted, args.filler_set, args.retakes,
                                             args.pad_before, args.pad_after, t0, t1)
        return {"levels": stats, "threshold_db": round(threshold, 1), "cuts": cuts, "start": t0, "end": t1}
    
    
    def snap(keeps: list, info: dict, min_keep: float) -> tuple:
        """Snap keep ranges outward to the CFR frame grid; drop cuts that leave slivers."""
        video = info.get("video")
        if not video:
            return [[round(s, 6), round(e, 6)] for s, e in keeps if e - s > 1e-3], None
        rate = mk.cfr_rate(video)
        g0 = Fraction(round(video["offset"] * float(rate))) / rate
        total = int(math.floor((info["end"] - float(g0)) * float(rate) + 1e-6))
        frames = []
        for s, e in keeps:
            k = max(0, int(math.floor((s - float(g0)) * float(rate) + 1e-6)))
            m = min(total, int(math.ceil((e - float(g0)) * float(rate) - 1e-6)))
            if m <= k:
                continue
            if frames and k <= frames[-1][1]:
                frames[-1][1] = max(frames[-1][1], m)
            else:
                frames.append([k, m])
        min_frames = max(2, int(math.ceil(min_keep * float(rate))))
        changed = True
        while changed and len(frames) > 1:  # merge slivers into a neighbour by removing the smaller cut
            changed = False
            for i, (k, m) in enumerate(frames):
                if m - k >= min_frames:
                    continue
                gap_l = k - frames[i - 1][1] if i > 0 else None
                gap_r = frames[i + 1][0] - m if i + 1 < len(frames) else None
                if gap_r is None or (gap_l is not None and gap_l <= gap_r):
                    frames[i - 1][1] = m
                else:
                    frames[i + 1][0] = k
                del frames[i]
                changed = True
                break
        secs = [[float(g0 + Fraction(k) / rate), float(g0 + Fraction(m) / rate)] for k, m in frames]
        return secs, {"rate": str(rate), "frames": frames}
    
    
    # ---------------------------------------------------------------- render
    
    def render(path: str, info: dict, keeps: list, grid: dict | None, out: str, args) -> None:
        ext = os.path.splitext(out)[1].lower()
        has_video = bool(info.get("video")) and ext in VIDEO_EXTS
        if info.get("video") and not has_video and ext not in AUDIO_CODECS:
            raise mk.EditError(f"unsupported output extension {ext}; use .mp4/.mov/.mkv or an audio type",
                               mk.EXIT_USAGE)
        xf = args.crossfade_ms / 1000.0
        n = len(keeps)
        a = f"0:a:{args.audio_stream}"
        parts = []
        if has_video:
            rate = grid["rate"]
            if n == 1:
                k, m = grid["frames"][0]
                parts.append(f"[0:v:0]fps={rate},trim=start_frame={k}:end_frame={m},setpts=PTS-STARTPTS[v]")
            else:
                parts.append(f"[0:v:0]fps={rate},split={n}" + "".join(f"[s{i}]" for i in range(n)))
                for i, (k, m) in enumerate(grid["frames"]):
                    parts.append(f"[s{i}]trim=start_frame={k}:end_frame={m},setpts=PTS-STARTPTS[v{i}]")
                parts.append("".join(f"[v{i}]" for i in range(n)) + f"concat=n={n}:v=1:a=0[v]")
        for i, (s, e) in enumerate(keeps):
            s2 = s - (xf / 2 if i > 0 else 0)
            e2 = e + (xf / 2 if i < n - 1 else 0)
            parts.append(f"[{a}]atrim=start={s2:.6f}:end={e2:.6f},asetpts=PTS-STARTPTS[a{i}]")
        cur = "a0"
        for i in range(1, n):
            parts.append(f"[{cur}][a{i}]acrossfade=d={xf:.4f}:c1=qsin:c2=qsin[x{i}]")
            cur = f"x{i}"
        total = sum(e - s for s, e in keeps)
        fades = []
        if keeps[0][0] > 0.001:
            fades.append("afade=t=in:d=0.005")
        if keeps[-1][1] < info["end"] - 0.001:
            fades.append(f"afade=t=out:st={max(0.0, total - 0.005):.6f}:d=0.005")
        parts.append(f"[{cur}]" + (",".join(fades) if fades else "anull") + "[a]")
        graph = ";".join(parts)
        cmd = [mk.ffmpeg_bin(), "-nostdin", "-hide_banner", "-v", "error", "-y", "-i", path]
        if len(graph) > 100000:
            script = out + ".graph.txt"
            with open(script, "w") as handle:
                handle.write(graph)
            ver = mk.ffmpeg_version()
            cmd += (["-/filter_complex", script] if (ver is None or ver[0] >= 7)
                    else ["-filter_complex_script", script])
        else:
            cmd += ["-filter_complex", graph]
        if has_video:
            vargs, _ = mk.video_codec_args(info["video"], crf=args.crf)
            cmd += ["-map", "[v]", "-map", "[a]"] + vargs + ["-c:a", "aac", "-b:a", "256k"]
            if ext in (".mp4", ".mov", ".m4v"):
                cmd += ["-movflags", "+faststart"]
        else:
            codec = AUDIO_CODECS.get(ext)
            if not codec:
                raise mk.EditError(f"unsupported audio output {ext}", mk.EXIT_USAGE)
            cmd += ["-map", "[a]"] + codec
        cmd.append(out)
        mk.run(cmd)
    
    
    # ---------------------------------------------------------------- main
    
    def main() -> int:
        p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], epilog=mk.EXIT_CODES_HELP,
                                    formatter_class=argparse.RawDescriptionHelpFormatter)
        p.add_argument("input", help="video or audio file")
        p.add_argument("-o", "--output", help="output file (default: <input>.cut.<ext>)")
        p.add_argument("--edl", help="EDL JSON path (default: <output stem>.edl.json)")
        p.add_argument("--transcript", help="word timings JSON/SRT/VTT for filler + retake cuts")
        p.add_argument("--pace", choices=sorted(PACES), default="normal",
                       help="preset: tight (shorts), normal (default), loose (talks)")
        p.add_argument("--threshold", type=float, help="silence gate in dBFS (default: adaptive)")
        p.add_argument("--min-silence", type=float, help="pauses shorter than this are kept (s)")
        p.add_argument("--pad-before", type=float, help="air kept before speech starts (s)")
        p.add_argument("--pad-after", type=float, help="air kept after speech ends (s)")
        p.add_argument("--min-cut", type=float, help="skip cuts shorter than this (s)")
        p.add_argument("--crossfade-ms", type=float, default=30.0, help="audio crossfade at joins (ms)")
        p.add_argument("--fillers", default=DEFAULT_FILLERS, help="comma list of filler words to cut")
        p.add_argument("--no-fillers", action="store_true", help="do not cut filler words")
        p.add_argument("--retakes", choices=["off", "exact", "fuzzy"], default="fuzzy",
                       help="repeated-line detection (needs --transcript); last take wins")
        p.add_argument("--audio-stream", type=int, default=0, help="which audio stream to analyze")
        p.add_argument("--dry-run", action="store_true", help="write the EDL only, do not render")
        p.add_argument("--from-edl", help="render the cuts in this EDL (apply=false vetoes a cut)")
        p.add_argument("--crf", type=int, default=16, help="video quality, lower is better (default 16)")
        p.add_argument("--json", action="store_true", help="print a JSON summary")
        args = p.parse_args()
    
        min_silence, pad_before, pad_after, min_cut = PACES[args.pace]
        args.min_silence = args.min_silence if args.min_silence is not None else min_silence
        args.pad_before = args.pad_before if args.pad_before is not None else pad_before
        args.pad_after = args.pad_after if args.pad_after is not None else pad_after
        args.min_cut = args.min_cut if args.min_cut is not None else min_cut
        args.filler_set = set() if args.no_fillers else {norm_token(f) for f in args.fillers.split(",") if f.strip()}
    
        info = mk.probe(args.input)
        if not info["audio_streams"]:
            raise mk.EditError("no audio stream: dead space is found in the audio. Use a transcript-driven "
                               "edit or cut by hand.", mk.EXIT_USAGE)
        if args.audio_stream >= len(info["audio_streams"]):
            raise mk.EditError(f"there is no audio stream #{args.audio_stream}", mk.EXIT_USAGE)
        out = args.output or mk.default_output(args.input, ".cut")
        edl_path = args.edl or mk.default_output(out, "", ".edl.json")
        words = mk.load_words(args.transcript, info["duration"]) if args.transcript else None
    
        if args.from_edl:
            with open(args.from_edl, encoding="utf-8") as handle:
                edl = json.load(handle)
            cuts = edl.get("cuts") or []
            analysis = {"start": 0.0, "end": info["end"], "cuts": cuts,
                        "levels": edl.get("analysis", {}).get("levels"),
                        "threshold_db": edl.get("analysis", {}).get("threshold_db")}
        else:
            analysis = analyze(args.input, info, args, words)
            cuts = merge_cuts(analysis["cuts"])
            for cut in cuts:
                cut["start"], cut["end"] = round(cut["start"], 4), round(cut["end"], 4)
                cut["apply"] = True
        raw_keeps = keeps_from_cuts(cuts, analysis["start"], analysis["end"])
        if not raw_keeps:
            raise mk.EditError("every second would be cut; check --threshold", mk.EXIT_USAGE)
        min_keep = max(0.07, args.crossfade_ms / 1000.0 + 0.04)
        keeps, grid = snap(raw_keeps, info, min_keep)
        src_len = analysis["end"] - analysis["start"]
        out_len = sum(e - s for s, e in keeps)
        applied = [c for c in cuts if c.get("apply", True)]
        counts = {}
        for cut in applied:
            for reason in cut["reason"].split("+"):
                counts[reason] = counts.get(reason, 0) + 1
        edl = {
            "version": 1,
            "tool": "master-skills edit/deadspace.py",
            "source": info["path"],
            "duration": round(src_len, 4),
            "fps": grid["rate"] if grid else None,
            "settings": {k: getattr(args, k) for k in ("pace", "min_silence", "pad_before", "pad_after",
                                                         "min_cut", "crossfade_ms", "retakes")},
            "analysis": {"levels": analysis.get("levels"), "threshold_db": analysis.get("threshold_db")},
            "note": "cuts[] is the source of truth: set apply=false to veto a cut, append "
                    "{start, end, reason: 'manual'} to add one, then run --from-edl.",
            "cuts": cuts,
            "keep": [{"start": round(s, 4), "end": round(e, 4)} for s, e in keeps],
            "output": {"path": os.path.abspath(out), "duration": round(out_len, 4),
                       "saved": round(src_len - out_len, 4)},
        }
        mk.write_json(edl_path, edl)
        summary = {"input": info["path"], "edl": os.path.abspath(edl_path), "cuts": len(applied),
                   "by_reason": counts, "source_s": round(src_len, 2), "output_s": round(out_len, 2),
                   "saved_s": round(src_len - out_len, 2),
                   "saved_pct": round(100 * (src_len - out_len) / src_len, 1) if src_len else 0.0,
                   "threshold_db": analysis.get("threshold_db"), "rendered": False}
        if not args.dry_run:
            render(args.input, info, keeps, grid, out, args)
            result = mk.probe(out)
            summary["rendered"] = True
            summary["output"] = result["path"]
            durations = [s["duration"] for s in ([result["video"]] if result["video"] else []) +
                         result["audio_streams"] if s and s.get("duration")]
            if len(durations) == 2:
                summary["av_drift_ms"] = round(abs(durations[0] - durations[1]) * 1000, 1)
            if words:
                words_out = mk.default_output(out, "", ".words.json")
                a_off = info["audio_streams"][args.audio_stream]["offset"]
                shifted = [dict(w, start=w["start"] + a_off, end=w["end"] + a_off) for w in words]
                mk.save_words(words_out, remap_words(shifted, keeps), source=out,
                              engine="remapped by deadspace.py")
                summary["words"] = os.path.abspath(words_out)
        if args.json:
            print(json.dumps(summary, indent=2))
        else:
            reasons = ", ".join(f"{k} {v}" for k, v in sorted(counts.items())) or "none"
            print(f"deadspace: {len(applied)} cuts ({reasons}), threshold {summary['threshold_db']} dBFS")
            print(f"  {src_len:.2f} s -> {out_len:.2f} s, saved {summary['saved_s']:.2f} s "
                  f"({summary['saved_pct']}%)")
            print(f"  edl: {edl_path}")
            if summary["rendered"]:
                print(f"  wrote: {out}" + (f"  (A/V drift {summary.get('av_drift_ms')} ms)"
                                            if "av_drift_ms" in summary else ""))
            if summary.get("words"):
                print(f"  words on the cut timeline: {summary['words']}")
            for cut in applied:
                if cut["reason"] != "silence":
                    print(f"  {cut['reason']:>15} {mk.fmt_time(cut['start'])}-{mk.fmt_time(cut['end'])}  "
                          f"{cut.get('text') or ''}")
        return mk.EXIT_OK
    
    
    if __name__ == "__main__":
        sys.exit(mk.run_main(main))
    
  • skills/edit/tools/mediakit.py27 KB19f96facb552upstream ↗
    """Shared helpers for the edit skill's tools. Python 3.8+ standard library only.
    
    Not a command line tool. probe.py, deadspace.py, captions.py, stopmotion.py and
    finish.py import it for: finding ffmpeg/ffprobe, running them with readable
    errors, probing media (rotation, VFR, HDR, audio layout), detecting which
    filters this ffmpeg build has, a fast speech envelope, loudness measurement,
    and loading word timings from any common transcript format.
    
    Part of github.com/Jakeschincariol/master-skills (MIT).
    """
    from __future__ import annotations
    
    import array
    import json
    import math
    import operator
    import os
    import re
    import shlex
    import shutil
    import subprocess
    import sys
    import tempfile
    from fractions import Fraction
    
    EXIT_OK = 0
    EXIT_FAIL = 1
    EXIT_USAGE = 2
    EXIT_MISSING = 3
    
    EXIT_CODES_HELP = """exit codes:
      0  success
      1  ffmpeg or runtime failure
      2  bad input or arguments (missing file, no audio stream, ...)
      3  a required program or feature is missing (ffmpeg, faster-whisper, libass)"""
    
    FFMPEG_INSTALL_HINT = (
        "Install ffmpeg first (macOS: brew install ffmpeg, Debian/Ubuntu: sudo apt install ffmpeg), "
        "or point EDIT_FFMPEG / EDIT_FFPROBE at the binaries."
    )
    
    # Instagram Reels / TikTok / Shorts safe area on a 1080x1920 canvas (house rule):
    # the header covers y < 240, the caption/username block covers y > 1470,
    # the like/comment/share rail covers x > 950 from y 1000 down, and tall phones
    # crop about 8% off each side (x < 90 and x > 990 can disappear).
    SAFE_AREA_9x16 = {"x0": 90, "y0": 240, "x1": 950, "y1": 1470}
    
    STANDARD_RATES = [
        Fraction(24000, 1001), Fraction(24), Fraction(25), Fraction(30000, 1001), Fraction(30),
        Fraction(48), Fraction(50), Fraction(60000, 1001), Fraction(60), Fraction(120),
    ]
    
    
    class EditError(Exception):
        """An error with a message for the user and the exit code to return."""
    
        def __init__(self, message: str, code: int = EXIT_FAIL):
            super().__init__(message)
            self.code = code
    
    
    def run_main(main_fn) -> int:
        """Run a tool's main(), turning EditError into a clean message + exit code."""
        try:
            return int(main_fn() or 0)
        except EditError as err:
            print(f"error: {err}", file=sys.stderr)
            return err.code
        except KeyboardInterrupt:
            print("interrupted", file=sys.stderr)
            return 130
    
    
    def warn(message: str) -> None:
        print(f"warning: {message}", file=sys.stderr)
    
    
    # ---------------------------------------------------------------------------
    # ffmpeg / ffprobe
    # ---------------------------------------------------------------------------
    
    def _find_binary(name: str, env_var: str) -> str:
        override = os.environ.get(env_var)
        if override:
            return override
        found = shutil.which(name)
        if not found:
            raise EditError(f"{name} not found on PATH. {FFMPEG_INSTALL_HINT}", EXIT_MISSING)
        return found
    
    
    def ffmpeg_bin() -> str:
        return _find_binary("ffmpeg", "EDIT_FFMPEG")
    
    
    def ffprobe_bin() -> str:
        return _find_binary("ffprobe", "EDIT_FFPROBE")
    
    
    def _short_cmd(cmd) -> str:
        text = shlex.join(str(c) for c in cmd)
        return text if len(text) < 1500 else text[:1500] + " ..."
    
    
    def run(cmd, *, cwd=None, check=True, timeout=None) -> subprocess.CompletedProcess:
        """Run a command, capture text output, raise EditError with the stderr tail on failure."""
        try:
            proc = subprocess.run(
                [str(c) for c in cmd], cwd=cwd, capture_output=True, text=True,
                errors="replace", timeout=timeout,
            )
        except FileNotFoundError as err:
            raise EditError(f"cannot run {cmd[0]}: {err}", EXIT_MISSING)
        if check and proc.returncode != 0:
            tail = (proc.stderr or "").strip()[-2500:]
            raise EditError(
                f"{os.path.basename(str(cmd[0]))} failed (exit {proc.returncode}):\n{tail}\n"
                f"command: {_short_cmd(cmd)}",
                EXIT_FAIL,
            )
        return proc
    
    
    _CACHE: dict = {}
    
    
    def ffmpeg_version() -> tuple | None:
        """(major, minor) of ffmpeg, or None for git builds without a release number."""
        if "version" not in _CACHE:
            first = run([ffmpeg_bin(), "-hide_banner", "-version"]).stdout.splitlines()[:1]
            match = re.search(r"version\s+n?(\d+)\.(\d+)", first[0] if first else "")
            _CACHE["version"] = (int(match.group(1)), int(match.group(2))) if match else None
            _CACHE["version_line"] = first[0] if first else ""
        return _CACHE["version"]
    
    
    def ffmpeg_filters() -> set:
        """Names of every filter this ffmpeg build has (ass, subtitles, drawtext vary by build)."""
        if "filters" not in _CACHE:
            out = run([ffmpeg_bin(), "-hide_banner", "-filters"]).stdout
            names = set()
            for line in out.splitlines():
                match = re.match(r"^\s*[A-Z.|]{2,3}\s+(\S+)\s+\S*->\S*", line)
                if match:
                    names.add(match.group(1))
            _CACHE["filters"] = names
        return _CACHE["filters"]
    
    
    def has_filter(name: str) -> bool:
        return name in ffmpeg_filters()
    
    
    def filter_options(name: str) -> set:
        """Option names a filter accepts on this build (e.g. alimiter 'latency' is newer)."""
        key = f"opts:{name}"
        if key not in _CACHE:
            out = run([ffmpeg_bin(), "-hide_banner", "-h", f"filter={name}"], check=False).stdout
            _CACHE[key] = set(re.findall(r"^\s{2,}([a-z_0-9]+)\s+<", out, flags=re.M))
        return _CACHE[key]
    
    
    def ffmpeg_encoders() -> set:
        if "encoders" not in _CACHE:
            out = run([ffmpeg_bin(), "-hide_banner", "-encoders"]).stdout
            _CACHE["encoders"] = set(re.findall(r"^\s*[VAS][A-Z.]{5}\s+(\S+)", out, flags=re.M))
        return _CACHE["encoders"]
    
    
    def has_encoder(name: str) -> bool:
        return name in ffmpeg_encoders()
    
    
    # ---------------------------------------------------------------------------
    # Probing
    # ---------------------------------------------------------------------------
    
    def _num(value, default=None):
        try:
            out = float(value)
        except (TypeError, ValueError):
            return default
        return out if math.isfinite(out) else default
    
    
    def _frac(value):
        try:
            out = Fraction(str(value))
        except (TypeError, ValueError, ZeroDivisionError):
            return None
        return out if out > 0 else None
    
    
    def _video_info(s: dict, fmt_start: float) -> dict:
        width, height = int(s.get("width") or 0), int(s.get("height") or 0)
        rotation = 0
        for side in s.get("side_data_list") or []:
            if "rotation" in side:
                rotation = int(round(_num(side["rotation"], 0)))
        tags = s.get("tags") or {}
        if not rotation and "rotate" in tags:
            rotation = int(_num(tags["rotate"], 0))
        rotation %= 360
        disp_w, disp_h = (height, width) if rotation in (90, 270) else (width, height)
        r_rate, avg_rate = _frac(s.get("r_frame_rate")), _frac(s.get("avg_frame_rate"))
        fps = avg_rate or r_rate
        vfr = bool(r_rate and avg_rate and abs(float(r_rate) - float(avg_rate)) > 0.01 * float(r_rate))
        pix_fmt = s.get("pix_fmt") or ""
        depth = int(_num(s.get("bits_per_raw_sample"), 0) or 0)
        if not depth:
            depth = 12 if "12" in pix_fmt else 10 if "10" in pix_fmt else 8
        transfer = s.get("color_transfer")
        start = _num(s.get("start_time"), fmt_start)
        nb_frames = s.get("nb_frames")
        return {
            "index": s.get("index"),
            "codec": s.get("codec_name"),
            "profile": s.get("profile"),
            "width": width,
            "height": height,
            "rotation": rotation,
            "display_width": disp_w,
            "display_height": disp_h,
            "pix_fmt": pix_fmt,
            "bit_depth": depth,
            "fps": float(fps) if fps else None,
            "r_frame_rate": str(r_rate) if r_rate else None,
            "avg_frame_rate": str(avg_rate) if avg_rate else None,
            "vfr": vfr,
            "color_primaries": s.get("color_primaries"),
            "color_transfer": transfer,
            "color_space": s.get("color_space"),
            "color_range": s.get("color_range"),
            "hdr": transfer in ("arib-std-b67", "smpte2084"),
            "start": start,
            "offset": max(0.0, start - fmt_start),
            "duration": _num(s.get("duration")),
            "nb_frames": int(nb_frames) if str(nb_frames or "").isdigit() else None,
        }
    
    
    def _audio_info(s: dict, fmt_start: float, order: int) -> dict:
        start = _num(s.get("start_time"), fmt_start)
        return {
            "index": s.get("index"),
            "order": order,
            "codec": s.get("codec_name"),
            "sample_rate": int(_num(s.get("sample_rate"), 0) or 0),
            "channels": int(s.get("channels") or 0),
            "channel_layout": s.get("channel_layout"),
            "start": start,
            "offset": max(0.0, start - fmt_start),
            "duration": _num(s.get("duration")),
            "bit_rate": int(_num(s.get("bit_rate"), 0) or 0) or None,
        }
    
    
    def probe(path: str) -> dict:
        """Summarize a media file. Times use ffmpeg's filter timeline (format start = 0)."""
        if not os.path.isfile(path):
            raise EditError(f"file not found: {path}", EXIT_USAGE)
        proc = run([ffprobe_bin(), "-v", "error", "-print_format", "json", "-show_format",
                    "-show_streams", path], check=False)
        if proc.returncode != 0:
            raise EditError(f"ffprobe cannot read {path}: {(proc.stderr or '').strip()[-400:]}", EXIT_USAGE)
        data = json.loads(proc.stdout or "{}")
        fmt = data.get("format") or {}
        fmt_start = _num(fmt.get("start_time"), 0.0)
        video, audio_streams = None, []
        for stream in data.get("streams") or []:
            kind = stream.get("codec_type")
            if kind == "video":
                if (stream.get("disposition") or {}).get("attached_pic"):
                    continue  # cover art inside an audio file, not a picture track
                if video is None:
                    video = _video_info(stream, fmt_start)
            elif kind == "audio":
                audio_streams.append(_audio_info(stream, fmt_start, len(audio_streams)))
        duration = _num(fmt.get("duration"))
        ends = []
        if video and video["duration"]:
            ends.append(video["offset"] + video["duration"])
        if audio_streams and audio_streams[0]["duration"]:
            ends.append(audio_streams[0]["offset"] + audio_streams[0]["duration"])
        if not ends and duration:
            ends.append(duration)
        return {
            "path": os.path.abspath(path),
            "format": fmt.get("format_name"),
            "duration": duration,
            "end": min(ends) if ends else duration,
            "size": int(_num(fmt.get("size"), 0) or 0),
            "bit_rate": int(_num(fmt.get("bit_rate"), 0) or 0) or None,
            "video": video,
            "audio": audio_streams[0] if audio_streams else None,
            "audio_streams": audio_streams,
        }
    
    
    def cfr_rate(video: dict) -> Fraction:
        """The constant frame rate to edit at: the source rate, snapped to a standard rate if close."""
        r_rate, avg_rate = _frac(video.get("r_frame_rate")), _frac(video.get("avg_frame_rate"))
        base = r_rate if (r_rate and r_rate <= 121) else (avg_rate or r_rate or Fraction(30))
        best = min(STANDARD_RATES, key=lambda c: abs(float(c - base)) / float(c))
        if abs(float(best - base)) / float(best) <= 0.02:
            return best
        return Fraction(base).limit_denominator(1001)
    
    
    def is_image_file(path: str) -> bool:
        return os.path.splitext(path)[1].lower() in IMAGE_EXTS
    
    
    IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff")
    
    
    def parse_size(text: str) -> tuple:
        match = re.fullmatch(r"\s*(\d+)\s*[xX:]\s*(\d+)\s*", text or "")
        if not match:
            raise EditError(f"bad size {text!r}, expected WIDTHxHEIGHT like 1080x1920", EXIT_USAGE)
        width, height = int(match.group(1)), int(match.group(2))
        if width < 16 or height < 16 or width % 2 or height % 2:
            raise EditError(f"size {width}x{height} must be even and at least 16 px", EXIT_USAGE)
        return width, height
    
    
    def video_codec_args(video: dict, crf: int = 18, preset: str = "medium") -> tuple:
        """Encoder arguments that keep the picture honest: HDR stays 10-bit HEVC with its
        colour tags, everything else becomes H.264 yuv420p with the source's colour tags."""
        tags = []
        for key, flag in (("color_primaries", "-color_primaries"), ("color_transfer", "-color_trc"),
                          ("color_space", "-colorspace")):
            value = video.get(key)
            if value and value not in ("unknown", "reserved", "unspecified"):
                tags += [flag, value]
        if video.get("hdr") and has_encoder("libx265"):
            return (["-c:v", "libx265", "-crf", str(crf), "-preset", preset, "-pix_fmt", "yuv420p10le",
                     "-tag:v", "hvc1", "-x265-params", "log-level=error"] + tags,
                    "HEVC 10-bit (HDR kept)")
        if has_encoder("libx264"):
            note = "H.264 8-bit"
            if video.get("hdr"):
                note += " (HDR source without libx265: colours are not tone mapped)"
            return (["-c:v", "libx264", "-crf", str(crf), "-preset", preset, "-pix_fmt", "yuv420p"] + tags,
                    note)
        raise EditError("this ffmpeg has no libx264 encoder; install a full ffmpeg build", EXIT_MISSING)
    
    
    # ---------------------------------------------------------------------------
    # Audio envelope and loudness
    # ---------------------------------------------------------------------------
    
    def audio_envelope(path: str, info: dict, stream: int = 0, hop: float = 0.01,
                       rate: int = 16000, highpass: float = 70.0) -> list:
        """Short-term level in dBFS every `hop` seconds (power averaged over channels, so
        stereo phase never cancels). Frame i covers [offset + i*hop, offset + (i+1)*hop)."""
        streams = info.get("audio_streams") or []
        if stream >= len(streams):
            raise EditError(f"{os.path.basename(path)} has no audio stream #{stream}", EXIT_USAGE)
        channels = max(1, streams[stream]["channels"] or 1)
        filters = ([f"highpass=f={highpass:g}"] if highpass else []) + [f"aresample={rate}"]
        cmd = [ffmpeg_bin(), "-nostdin", "-hide_banner", "-v", "error", "-i", path,
               "-map", f"0:a:{stream}", "-vn", "-sn", "-dn", "-af", ",".join(filters),
               "-f", "s16le", "-acodec", "pcm_s16le", "pipe:1"]
        hop_samples = max(1, int(round(rate * hop))) * channels
        frame_bytes = hop_samples * 2
        full_scale = 32768.0 * 32768.0
        swap = sys.byteorder == "big"
        mul = operator.mul
        levels = []
        with tempfile.TemporaryFile() as errfile:
            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=errfile)
            pending = b""
            while True:
                chunk = proc.stdout.read(frame_bytes * 1024)
                if not chunk:
                    break
                pending += chunk
                whole = len(pending) // frame_bytes
                if not whole:
                    continue
                samples = array.array("h")
                samples.frombytes(pending[: whole * frame_bytes])
                pending = pending[whole * frame_bytes:]
                if swap:
                    samples.byteswap()
                for i in range(whole):
                    window = samples[i * hop_samples:(i + 1) * hop_samples]
                    power = sum(map(mul, window, window))
                    levels.append(10 * math.log10(power / hop_samples / full_scale) if power else -120.0)
            tail = len(pending) - len(pending) % 2
            if tail >= 2:
                samples = array.array("h")
                samples.frombytes(pending[:tail])
                if swap:
                    samples.byteswap()
                power = sum(map(mul, samples, samples))
                levels.append(10 * math.log10(power / len(samples) / full_scale) if power else -120.0)
            proc.stdout.close()
            code = proc.wait()
            errfile.seek(0)
            err = errfile.read().decode("utf-8", "replace").strip()
        if code != 0:
            raise EditError(f"ffmpeg could not decode the audio of {path}:\n{err[-1500:]}", EXIT_FAIL)
        return levels
    
    
    def percentile(sorted_values: list, fraction: float) -> float:
        if not sorted_values:
            return float("nan")
        pos = min(len(sorted_values) - 1, max(0, int(round(fraction * (len(sorted_values) - 1)))))
        return sorted_values[pos]
    
    
    def speech_levels(levels: list) -> dict:
        """Adaptive gate for phone talking-head takes: noise floor = 10th percentile of
        10 ms frames, speech = loud frames. The gate sits 30 dB under speech but never
        closer than 8 dB to the noise floor, so quiet takes and noisy rooms both work."""
        values = sorted(levels)
        if not values:
            raise EditError("the audio stream is empty", EXIT_USAGE)
        noise = percentile(values, 0.10)
        speech = max(percentile(values, 0.95), percentile(values, 0.99) - 6.0, values[-1] - 12.0)
        spread = speech - noise
        if spread >= 18.0:
            threshold = max(noise + 8.0, speech - 30.0)
        else:
            threshold = noise + spread * 0.5
        return {
            "noise_db": round(noise, 1),
            "speech_db": round(speech, 1),
            "threshold_db": round(threshold, 1),
            "spread_db": round(spread, 1),
            "reliable": spread >= 12.0,
        }
    
    
    def measure_loudness(path: str, *, stream: int = 0, pre_filter: str = "") -> dict:
        """EBU R128 integrated loudness (LUFS), loudness range (LU) and true peak (dBTP)."""
        chain = (pre_filter + "," if pre_filter else "") + "ebur128=peak=true:framelog=verbose"
        proc = run([ffmpeg_bin(), "-nostdin", "-hide_banner", "-nostats", "-i", path,
                    "-map", f"0:a:{stream}", "-af", chain, "-f", "null", "-"])
        return parse_ebur128(proc.stderr)
    
    
    def parse_ebur128(stderr: str) -> dict:
        summary = stderr[stderr.rfind("Summary:"):] if "Summary:" in stderr else stderr
    
        def grab(label):
            match = re.search(rf"{label}:\s+(-?inf|-?\d+(?:\.\d+)?)", summary)
            if not match:
                return None
            return None if "inf" in match.group(1) else float(match.group(1))
    
        return {"integrated_lufs": grab("I"), "lra_lu": grab("LRA"), "true_peak_dbtp": grab("Peak")}
    
    
    # ---------------------------------------------------------------------------
    # Word timings (transcripts)
    # ---------------------------------------------------------------------------
    
    _START_KEYS = ("start", "start_time", "startTime", "t0", "begin")
    _END_KEYS = ("end", "end_time", "endTime", "t1", "stop")
    _TEXT_KEYS = ("punctuated_word", "text", "word", "token")
    
    
    def _first(item: dict, keys):
        for key in keys:
            if key in item and item[key] is not None:
                return item[key]
        return None
    
    
    def _wordish(item) -> bool:
        if not isinstance(item, dict):
            return False
        has_time = _first(item, _START_KEYS) is not None or isinstance(item.get("offsets"), dict)
        return has_time and _first(item, _TEXT_KEYS) is not None
    
    
    def _find_word_list(data):
        """Locate the word list in Scribe, Whisper, faster-whisper, whisper.cpp, Deepgram,
        AssemblyAI, HyperFrames or this skill's own JSON. Returns (items, kind)."""
        if isinstance(data, list):
            if data and all(_wordish(x) for x in data[:50]):
                return data, "list"
        if isinstance(data, dict):
            if isinstance(data.get("words"), list) and data["words"] and _wordish(data["words"][0]):
                return data["words"], "words"
            segments = data.get("segments")
            if isinstance(segments, list) and any(isinstance(s, dict) and s.get("words") for s in segments):
                return [w for s in segments if isinstance(s, dict) for w in (s.get("words") or [])], "segments"
            try:
                words = data["results"]["channels"][0]["alternatives"][0]["words"]
                if isinstance(words, list):
                    return words, "deepgram"
            except (KeyError, IndexError, TypeError):
                pass
            if isinstance(data.get("transcription"), list):
                return data["transcription"], "whisper.cpp"
        best = []
    
        def walk(node):
            nonlocal best
            if isinstance(node, list):
                if len(node) > len(best) and node and all(_wordish(x) for x in node[:20]):
                    best = node
                for child in node:
                    walk(child)
            elif isinstance(node, dict):
                for child in node.values():
                    walk(child)
    
        walk(data)
        if best:
            return best, "search"
        raise EditError("no word timings found in that JSON (expected a list of {text, start, end})",
                        EXIT_USAGE)
    
    
    def _clean_words(words: list) -> list:
        out = []
        for word in sorted(words, key=lambda w: (w["start"], w["end"])):
            text = re.sub(r"\s+", " ", str(word["text"])).strip()
            if not text:
                continue
            start = max(0.0, float(word["start"]))
            end = max(start + 0.01, float(word["end"]))
            item = {"text": text, "start": round(start, 3), "end": round(end, 3)}
            if word.get("prob") is not None:
                item["prob"] = round(float(word["prob"]), 3)
            out.append(item)
        return out
    
    
    def load_words(path: str, media_duration: float | None = None) -> list:
        """Load word timings as [{text, start, end, prob?}] in seconds, sorted.
        Accepts JSON transcripts, or .srt/.vtt (word times spread inside each cue)."""
        if not os.path.isfile(path):
            raise EditError(f"transcript not found: {path}", EXIT_USAGE)
        ext = os.path.splitext(path)[1].lower()
        with open(path, encoding="utf-8-sig") as handle:
            raw = handle.read()
        if ext in (".srt", ".vtt"):
            return words_from_subtitles(raw)
        try:
            data = json.loads(raw)
        except json.JSONDecodeError as err:
            raise EditError(f"{path} is not valid JSON: {err}", EXIT_USAGE)
        items, kind = _find_word_list(data)
        words, all_int, max_end = [], True, 0.0
        for item in items:
            if not isinstance(item, dict) or item.get("type") in ("spacing", "audio_event"):
                continue
            text = _first(item, _TEXT_KEYS)
            if isinstance(item.get("offsets"), dict):
                start, end = item["offsets"].get("from"), item["offsets"].get("to")
                start, end = _num(start), _num(end)
                if start is not None:
                    start, end = start / 1000.0, (end if end is not None else start) / 1000.0
            else:
                start, end = _num(_first(item, _START_KEYS)), _num(_first(item, _END_KEYS))
            if text is None or start is None:
                continue
            if end is None:
                end = start
            if isinstance(item.get("offsets"), dict):
                all_int = False
            elif not (float(start).is_integer() and float(end).is_integer()):
                all_int = False
            max_end = max(max_end, end)
            prob = _num(_first(item, ("probability", "confidence", "prob", "logprob")))
            words.append({"text": text, "start": start, "end": end,
                          "prob": prob if prob is not None and 0 <= prob <= 1 else None})
        if not words:
            raise EditError(f"{path} has no usable word timings", EXIT_USAGE)
        in_ms = max_end > 36000 or (all_int and max_end > 1000)
        if media_duration and max_end > media_duration * 2 and max_end / 1000.0 <= media_duration * 1.5:
            in_ms = True
        if in_ms:
            for word in words:
                word["start"] /= 1000.0
                word["end"] /= 1000.0
        return _clean_words(words)
    
    
    _TS = r"(?:(\d+):)?(\d{1,2}):(\d{2})[,.](\d{1,3})"
    
    
    def _ts_seconds(match, offset: int) -> float:
        hours = int(match.group(offset) or 0)
        minutes, seconds = int(match.group(offset + 1)), int(match.group(offset + 2))
        frac = match.group(offset + 3)
        return hours * 3600 + minutes * 60 + seconds + int(frac) / (10 ** len(frac))
    
    
    def words_from_subtitles(text: str) -> list:
        """SRT/VTT cues to approximate word timings (spread by character length).
        Good enough for caption chunking; cue boundaries stay exact."""
        words = []
        pattern = re.compile(_TS + r"\s*-->\s*" + _TS)
        blocks = re.split(r"\n\s*\n", text.replace("\r\n", "\n").replace("\r", "\n"))
        for block in blocks:
            lines = [ln for ln in block.split("\n") if ln.strip()]
            for i, line in enumerate(lines):
                match = pattern.search(line)
                if not match:
                    continue
                start, end = _ts_seconds(match, 1), _ts_seconds(match, 5)
                body = " ".join(lines[i + 1:])
                body = re.sub(r"<[^>]+>|\{[^}]*\}", "", body)
                tokens = body.split()
                if not tokens or end <= start:
                    break
                weights = [len(t) + 1 for t in tokens]
                total, cursor = float(sum(weights)), start
                for token, weight in zip(tokens, weights):
                    span = (end - start) * weight / total
                    words.append({"text": token, "start": cursor, "end": cursor + span * 0.92})
                    cursor += span
                break
        if not words:
            raise EditError("no cues found in that subtitle file", EXIT_USAGE)
        return _clean_words(words)
    
    
    def save_words(path: str, words: list, *, source: str | None = None, engine: str | None = None,
                   language: str | None = None, extra: dict | None = None) -> dict:
        """Write word timings in a schema HyperFrames' caption workflow can also reuse as
        transcript.json: {text, language_code, words: [{text, start, end, type}]}."""
        doc = {
            "version": 1,
            "kind": "words",
            "text": " ".join(w["text"] for w in words),
            "language_code": language or "en",
            "engine": engine or "unknown",
        }
        if source and os.path.isfile(source):
            stat = os.stat(source)
            doc["source"] = {"path": os.path.abspath(source), "size": stat.st_size,
                             "mtime": round(stat.st_mtime, 3)}
        if extra:
            doc.update(extra)
        doc["words"] = []
        for word in words:
            item = {"text": word["text"], "start": round(word["start"], 3),
                    "end": round(word["end"], 3), "type": "word"}
            if word.get("prob") is not None:
                item["prob"] = round(word["prob"], 3)
            doc["words"].append(item)
        write_json(path, doc)
        return doc
    
    
    def phrase_lines(words: list, gap: float = 0.5, max_words: int = 16) -> list:
        """A packed, phrase-per-line view of a transcript: '[012.34-015.67] text'.
        Phrases break on pauses >= gap seconds, or at sentence ends once a line is long."""
        lines, current = [], []
    
        def flush():
            if current:
                lines.append(f"[{current[0]['start']:07.2f}-{current[-1]['end']:07.2f}] "
                             + " ".join(w["text"] for w in current))
                current.clear()
    
        for i, word in enumerate(words):
            if current:
                pause = word["start"] - current[-1]["end"]
                sentence_end = current[-1]["text"][-1:] in ".!?"
                if pause >= gap or len(current) >= max_words or (sentence_end and len(current) >= 8):
                    flush()
            current.append(word)
        flush()
        return lines
    
    
    # ---------------------------------------------------------------------------
    # Small utilities
    # ---------------------------------------------------------------------------
    
    def write_json(path: str, obj) -> None:
        folder = os.path.dirname(os.path.abspath(path))
        os.makedirs(folder, exist_ok=True)
        fd, tmp = tempfile.mkstemp(prefix=".tmp-", suffix=".json", dir=folder)
        with os.fdopen(fd, "w", encoding="utf-8") as handle:
            json.dump(obj, handle, indent=2, ensure_ascii=False)
            handle.write("\n")
        os.replace(tmp, path)
    
    
    def fmt_time(seconds: float) -> str:
        seconds = max(0.0, float(seconds))
        minutes, rest = divmod(seconds, 60)
        return f"{int(minutes)}:{rest:05.2f}"
    
    
    def default_output(path: str, suffix: str, ext: str | None = None) -> str:
        stem, original_ext = os.path.splitext(path)
        return f"{stem}{suffix}{ext if ext is not None else original_ext}"
    
    
    def stem_of(path: str) -> str:
        return os.path.splitext(os.path.basename(path))[0]
    
  • skills/edit/tools/probe.py8.4 KBf3ec9efac58cupstream ↗
    #!/usr/bin/env python3
    """Probe media before editing, or check what this machine can do (--doctor).
    
      python3 probe.py clip.mov                 # dims after rotation, fps + VFR, HDR, audio layout
      python3 probe.py clip.mov --loudness      # + integrated loudness and true peak
      python3 probe.py --doctor                 # ffmpeg filters, faster-whisper, Node for HyperFrames
      python3 probe.py clip.mov --json          # machine-readable
    
    Part of github.com/Jakeschincariol/master-skills (MIT).
    """
    from __future__ import annotations
    
    import argparse
    import importlib.util
    import json
    import os
    import platform
    import re
    import shutil
    import subprocess
    import sys
    
    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    import mediakit as mk  # noqa: E402
    
    KEY_FILTERS = ["ass", "subtitles", "drawtext", "silencedetect", "acrossfade", "alimiter", "loudnorm",
                   "ebur128", "rotate", "crop", "zscale", "tonemap"]
    KEY_ENCODERS = ["libx264", "libx265", "aac", "libmp3lame", "libopus"]
    
    
    def notes_for(info: dict) -> list:
        """Plain-English warnings an editor should know before cutting."""
        notes = []
        video, audio = info.get("video"), info.get("audio")
        if not audio:
            notes.append("no audio stream: dead-space cutting and transcription need audio")
        if audio and audio["channels"] == 1:
            notes.append("mono audio: fine for voice; finish.py keeps it mono unless a music bed is added")
        if audio and len(info.get("audio_streams") or []) > 1:
            notes.append(f"{len(info['audio_streams'])} audio streams: tools use the first (--audio-stream to change)")
        if video:
            if video["rotation"]:
                notes.append(f"rotation {video['rotation']} deg: displays as "
                             f"{video['display_width']}x{video['display_height']} (ffmpeg rotates automatically)")
            if video["vfr"]:
                notes.append(f"variable frame rate (avg {video['avg_frame_rate']} vs {video['r_frame_rate']}): "
                             f"deadspace.py renders constant {mk.cfr_rate(video)} fps")
            if video["hdr"]:
                notes.append("HDR (HLG/PQ) footage: tools keep it 10-bit HEVC; motion engines that render SDR "
                             "need one SDR conversion first, done once, not per step")
            if video["display_height"] and video["display_width"]:
                ratio = video["display_width"] / video["display_height"]
                if abs(ratio - 9 / 16) > 0.01:
                    notes.append(f"aspect {video['display_width']}x{video['display_height']} is not 9:16: "
                                 "reframe for Reels/TikTok/Shorts (finish.py --fit cover|contain)")
        return notes
    
    
    def describe(info: dict) -> str:
        lines = [f"{info['path']}",
                 f"  container {info['format']}, {info['duration'] or 0:.2f} s, {info['size'] / 1e6:.1f} MB"]
        video, audio = info.get("video"), info.get("audio")
        if video:
            rate = f"{video['fps']:.3f}".rstrip("0").rstrip(".") if video["fps"] else "?"
            lines.append(f"  video  {video['codec']} {video['display_width']}x{video['display_height']} "
                         f"@ {rate} fps{' (VFR)' if video['vfr'] else ''}, {video['pix_fmt']}, "
                         f"{video['bit_depth']}-bit{', HDR' if video['hdr'] else ''}")
        if audio:
            lines.append(f"  audio  {audio['codec']} {audio['sample_rate']} Hz, {audio['channels']} ch"
                         f"{' (' + audio['channel_layout'] + ')' if audio['channel_layout'] else ''}")
        loud = info.get("loudness")
        if loud:
            lines.append(f"  loudness {loud['integrated_lufs']} LUFS integrated, true peak "
                         f"{loud['true_peak_dbtp']} dBTP, range {loud['lra_lu']} LU")
        for note in info.get("notes", []):
            lines.append(f"  note: {note}")
        return "\n".join(lines)
    
    
    def _version_of(cmd) -> str | None:
        try:
            out = subprocess.run(cmd, capture_output=True, text=True, timeout=20)
        except (OSError, subprocess.SubprocessError):
            return None
        text = (out.stdout or out.stderr or "").strip().splitlines()
        return text[0] if text else None
    
    
    def doctor() -> dict:
        report = {"python": platform.python_version(), "platform": platform.platform(terse=True)}
        try:
            mk.ffmpeg_version()
            report["ffmpeg"] = {"path": mk.ffmpeg_bin(), "version": mk._CACHE.get("version_line"),
                                "ffprobe": mk.ffprobe_bin()}
            filters = mk.ffmpeg_filters()
            report["filters"] = {name: name in filters for name in KEY_FILTERS}
            report["alimiter_latency"] = "latency" in mk.filter_options("alimiter")
            encoders = mk.ffmpeg_encoders()
            report["encoders"] = {name: name in encoders for name in KEY_ENCODERS}
        except mk.EditError as err:
            report["ffmpeg"] = {"error": str(err)}
        report["faster_whisper"] = importlib.util.find_spec("faster_whisper") is not None
        node = _version_of(["node", "--version"]) if shutil.which("node") else None
        report["node"] = node
        major = int(re.sub(r"\D", "", node.split(".")[0]) or 0) if node else 0
        report["hyperframes_ready"] = major >= 22
        report["npx"] = shutil.which("npx") is not None
        return report
    
    
    def describe_doctor(report: dict) -> str:
        out = [f"python {report['python']} on {report['platform']}"]
        ff = report.get("ffmpeg", {})
        if "error" in ff:
            out.append(f"ffmpeg: MISSING ({ff['error']})")
        else:
            out.append(f"ffmpeg: {ff['version']} ({ff['path']})")
            missing = [k for k, v in report["filters"].items() if not v]
            out.append("  filters missing: " + (", ".join(missing) if missing else "none"))
            if not (report["filters"]["ass"] or report["filters"]["subtitles"]):
                out.append("  captions: no libass, so captions.py --burn cannot burn in here; "
                           "use the HyperFrames route or a libass ffmpeg (see SKILL.md)")
            if not report["alimiter_latency"]:
                out.append("  alimiter has no latency option: finish.py compensates the 5 ms delay itself")
            missing_enc = [k for k, v in report["encoders"].items() if not v]
            out.append("  encoders missing: " + (", ".join(missing_enc) if missing_enc else "none"))
        out.append("faster-whisper: " + ("installed" if report["faster_whisper"] else
                                         "not installed (captions.py needs --words, or pip install faster-whisper)"))
        if report["node"]:
            out.append(f"node {report['node']}: " + ("ok for HyperFrames" if report["hyperframes_ready"]
                                                      else "HyperFrames needs Node 22+"))
        else:
            out.append("node: not found (HyperFrames and Remotion need Node; HyperFrames needs 22+)")
        return "\n".join(out)
    
    
    def main() -> int:
        parser = argparse.ArgumentParser(
            description="Probe media for editing, or check this machine's editing toolchain.",
            epilog=mk.EXIT_CODES_HELP, formatter_class=argparse.RawDescriptionHelpFormatter)
        parser.add_argument("files", nargs="*", help="media files to probe")
        parser.add_argument("--doctor", action="store_true", help="report ffmpeg filters, encoders, "
                            "faster-whisper and Node availability")
        parser.add_argument("--loudness", action="store_true",
                            help="also measure integrated loudness and true peak (decodes the audio)")
        parser.add_argument("--json", action="store_true", help="print JSON")
        args = parser.parse_args()
        if not args.files and not args.doctor:
            parser.error("give a media file or --doctor")
    
        results = {}
        if args.doctor:
            results["doctor"] = doctor()
        probes = []
        for path in args.files:
            info = mk.probe(path)
            if args.loudness and info.get("audio"):
                info["loudness"] = mk.measure_loudness(path)
            info["notes"] = notes_for(info)
            probes.append(info)
        if args.json:
            if args.doctor and not probes:
                print(json.dumps(results["doctor"], indent=2))
            elif not args.doctor and len(probes) == 1:
                print(json.dumps(probes[0], indent=2))
            else:
                results["files"] = probes
                print(json.dumps(results, indent=2))
        else:
            if args.doctor:
                print(describe_doctor(results["doctor"]))
            for info in probes:
                print(describe(info))
        if args.doctor and "error" in results["doctor"].get("ffmpeg", {}):
            return mk.EXIT_MISSING
        return mk.EXIT_OK
    
    
    if __name__ == "__main__":
        sys.exit(mk.run_main(main))
    
  • skills/edit/tools/stopmotion.py10 KB1c26dbe0b7faupstream ↗
    #!/usr/bin/env python3
    """Stop motion with ffmpeg filters only (no Pillow).
    
      python3 stopmotion.py frames/ -o clay.mp4                   # 12 drawings/s on twos = 24 fps
      python3 stopmotion.py frames/ -o loop.mp4 --fps 8 --hold 3 --loop 3 --pingpong
      python3 stopmotion.py --from-video clip.mp4 -o clip.stop.mp4 # live action -> stop-motion look
    
    Frames mode: images (png/jpg/webp/...) in natural order are fitted to a canvas
    (default 1080x1920, cover), each held `--hold` frames, with deterministic per-drawing
    jitter and rotation (same --seed = same output), optional loop / ping-pong / end hold.
    From-video mode: drops the frame rate to --fps, adds the same jitter, holds each frame,
    keeps the original audio in sync.
    
    Part of github.com/Jakeschincariol/master-skills (MIT).
    """
    from __future__ import annotations
    
    import argparse
    import json
    import math
    import os
    import random
    import re
    import shutil
    import sys
    import tempfile
    from concurrent.futures import ThreadPoolExecutor
    
    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    import mediakit as mk  # noqa: E402
    
    
    def natural_key(name: str):
        return [int(p) if p.isdigit() else p.lower() for p in re.split(r"(\d+)", name)]
    
    
    def list_frames(folder: str) -> list:
        if not os.path.isdir(folder):
            raise mk.EditError(f"not a folder: {folder}", mk.EXIT_USAGE)
        files = sorted((f for f in os.listdir(folder) if mk.is_image_file(f) and not f.startswith(".")),
                       key=natural_key)
        if not files:
            raise mk.EditError(f"no images in {folder} (png, jpg, webp, bmp, tif)", mk.EXIT_USAGE)
        return [os.path.join(folder, f) for f in files]
    
    
    def hash_expr(var: str, a: float, b: float) -> str:
        """Deterministic pseudo-random 0..1 per drawing: fract(sin(i*a + b) * 43758.5453)."""
        inner = f"sin({var}*{a:.4f}+{b:.4f})*43758.5453"
        return f"({inner}-floor({inner}))"
    
    
    def jitter_chain(width: int, height: int, jitter: float, rotate_deg: float, flicker: float,
                     seed: int, index_var: str) -> str:
        """rotate + crop + scale: each drawing sits a few px off and a fraction of a degree
        askew, like a hand-placed frame. The crop margin hides rotation corners."""
        rng = random.Random(seed)
        offsets = [rng.uniform(0.0, 100.0) for _ in range(4)]
        h_rot = hash_expr(index_var, 12.9898, offsets[0])
        h_x = hash_expr(index_var, 78.2330, offsets[1])
        h_y = hash_expr(index_var, 39.3468, offsets[2])
        margin = int(math.ceil(jitter + max(width, height) / 2 * math.sin(math.radians(rotate_deg)) + 2))
        margin += margin % 2
        parts = []
        if rotate_deg > 0:
            parts.append(f"rotate=a='{rotate_deg * math.pi / 180:.6f}*(2*{h_rot}-1)':c=black:ow=iw:oh=ih")
        if jitter > 0 or rotate_deg > 0:
            parts.append(f"crop=w=iw-{2 * margin}:h=ih-{2 * margin}:"
                         f"x='{margin}+{jitter:.3f}*(2*{h_x}-1)':y='{margin}+{jitter:.3f}*(2*{h_y}-1)'")
            parts.append(f"scale={width}:{height}:flags=bicubic")
        if flicker > 0:
            h_b = hash_expr(index_var, 93.9898, offsets[3])
            parts.append(f"eq=brightness='{flicker:.4f}*(2*{h_b}-1)':eval=frame")
        parts.append("setsar=1")
        return ",".join(parts)
    
    
    def normalize(src: str, dst: str, width: int, height: int, fit: str, bg: str) -> None:
        scale = "increase" if fit == "cover" else "decrease"
        graph = (f"color=c={bg}:s={width}x{height}:d=1[bg];"
                 f"[0:v]scale={width}:{height}:force_original_aspect_ratio={scale},format=rgba[fg];"
                 f"[bg][fg]overlay=(W-w)/2:(H-h)/2:format=auto,format=rgb24")
        mk.run([mk.ffmpeg_bin(), "-nostdin", "-hide_banner", "-v", "error", "-y", "-i", src,
                "-filter_complex", graph, "-frames:v", "1", dst])
    
    
    def encode_args(crf: int) -> list:
        return ["-c:v", "libx264", "-crf", str(crf), "-preset", "medium", "-pix_fmt", "yuv420p",
                "-movflags", "+faststart"]
    
    
    def main() -> int:
        p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], epilog=mk.EXIT_CODES_HELP,
                                    formatter_class=argparse.RawDescriptionHelpFormatter)
        p.add_argument("frames", nargs="?", help="folder of frame images")
        p.add_argument("--from-video", metavar="CLIP", help="turn a live clip into a stop-motion look")
        p.add_argument("-o", "--output", required=True, help="output .mp4/.mov")
        p.add_argument("--fps", type=float, default=12, help="drawings per second: 8, 10 or 12 (default 12)")
        p.add_argument("--hold", type=int, default=2, help="frames each drawing is held (2 = on twos)")
        p.add_argument("--size", help="canvas WxH (frames default 1080x1920; video keeps its size)")
        p.add_argument("--fit", choices=["cover", "contain"], default="cover", help="fit images to the canvas")
        p.add_argument("--bg", default="#F4EFE6", help="background colour for contain / transparent PNGs")
        p.add_argument("--jitter", type=float, help="max position wobble in px (default 0.5%% of the short side)")
        p.add_argument("--rotate", type=float, default=0.5, help="max rotation wobble in degrees")
        p.add_argument("--flicker", type=float, default=0.0, help="exposure flicker, e.g. 0.01 (off by default)")
        p.add_argument("--seed", type=int, default=1, help="same seed, same wobble")
        p.add_argument("--loop", type=int, default=1, help="play the frames N times (wobble differs per pass)")
        p.add_argument("--pingpong", action="store_true", help="forward then backward (seamless loop)")
        p.add_argument("--end-hold", type=float, default=0.0, help="hold the last frame this many seconds")
        p.add_argument("--crf", type=int, default=18, help="H.264 quality (0 = lossless)")
        p.add_argument("--json", action="store_true", help="print a JSON summary")
        args = p.parse_args()
    
        if bool(args.frames) == bool(args.from_video):
            p.error("give a frames folder or --from-video CLIP (one of them)")
        if not 1 <= args.fps <= 30 or not 1 <= args.hold <= 8:
            p.error("--fps must be 1-30 and --hold 1-8")
        out_fps = args.fps * args.hold
        if out_fps > 60:
            p.error("fps x hold must be <= 60")
        rate = f"{out_fps:g}"
        os.makedirs(os.path.dirname(os.path.abspath(args.output)) or ".", exist_ok=True)
        summary = {"output": os.path.abspath(args.output), "drawing_fps": args.fps, "hold": args.hold,
                   "output_fps": out_fps, "seed": args.seed}
    
        if args.from_video:
            info = mk.probe(args.from_video)
            if not info.get("video"):
                raise mk.EditError("that file has no video", mk.EXIT_USAGE)
            width, height = (mk.parse_size(args.size) if args.size else
                             (info["video"]["display_width"], info["video"]["display_height"]))
            width -= width % 2
            height -= height % 2
            jitter = args.jitter if args.jitter is not None else min(width, height) * 0.005
            pre = (f"scale={width}:{height}:force_original_aspect_ratio="
                   f"{'increase' if args.fit == 'cover' else 'decrease'},"
                   f"{'crop' if args.fit == 'cover' else 'pad'}={width}:{height}"
                   + ("" if args.fit == "cover" else f":(ow-iw)/2:(oh-ih)/2:color={args.bg}") + ",")
            vf = (f"{pre}fps={args.fps:g}," + jitter_chain(width, height, jitter, args.rotate, args.flicker,
                                                              args.seed, "n") + f",fps={rate},format=yuv420p")
            cmd = [mk.ffmpeg_bin(), "-nostdin", "-hide_banner", "-v", "error", "-y", "-i", args.from_video,
                   "-map", "0:v:0", "-map", "0:a?", "-vf", vf] + encode_args(args.crf)
            audio = info.get("audio")
            cmd += ["-c:a", "copy"] if audio and audio["codec"] == "aac" else ["-c:a", "aac", "-b:a", "256k"]
            mk.run(cmd + [args.output])
            summary.update({"mode": "from-video", "size": f"{width}x{height}"})
        else:
            width, height = mk.parse_size(args.size or "1080x1920")
            jitter = args.jitter if args.jitter is not None else min(width, height) * 0.005
            frames = list_frames(args.frames)
            order = list(range(len(frames)))
            if args.pingpong and len(frames) > 2:
                order += list(range(len(frames) - 2, 0, -1))
            order *= max(1, args.loop)
            with tempfile.TemporaryDirectory() as tmp:
                norm_dir, seq_dir = os.path.join(tmp, "norm"), os.path.join(tmp, "seq")
                os.makedirs(norm_dir)
                os.makedirs(seq_dir)
                normed = [os.path.join(norm_dir, f"{i:05d}.png") for i in range(len(frames))]
                with ThreadPoolExecutor(max_workers=min(8, os.cpu_count() or 2)) as pool:
                    list(pool.map(lambda pair: normalize(pair[0], pair[1], width, height, args.fit, args.bg),
                                  zip(frames, normed)))
                n = 0
                for idx in order:  # each drawing repeated `hold` times: exact frame counts, no fps filter
                    for _ in range(args.hold):
                        link = os.path.join(seq_dir, f"{n:06d}.png")
                        try:
                            os.symlink(normed[idx], link)
                        except OSError:
                            shutil.copy(normed[idx], link)
                        n += 1
                vf = jitter_chain(width, height, jitter, args.rotate, args.flicker, args.seed,
                                  f"floor(n/{args.hold})")
                if args.end_hold > 0:
                    vf += f",tpad=stop_mode=clone:stop_duration={args.end_hold:g}"
                vf += ",format=yuv420p"
                mk.run([mk.ffmpeg_bin(), "-nostdin", "-hide_banner", "-v", "error", "-y",
                        "-framerate", rate, "-i", os.path.join(seq_dir, "%06d.png"), "-vf", vf, "-r", rate]
                       + encode_args(args.crf) + [args.output])
            summary.update({"mode": "frames", "images": len(frames), "drawings": len(order),
                            "frames": n, "size": f"{width}x{height}",
                            "duration_s": round(n / out_fps + args.end_hold, 3)})
        if args.json:
            print(json.dumps(summary, indent=2))
        else:
            print(f"stopmotion: {summary['mode']}, {args.fps:g} drawings/s held {args.hold} "
                  f"-> {out_fps:g} fps, {summary['size']}\n  wrote: {summary['output']}")
        return mk.EXIT_OK
    
    
    if __name__ == "__main__":
        sys.exit(mk.run_main(main))
    
  • skills/edit/tools/test_edit.py13 KBaf16687024ebupstream ↗
    """Tests for the edit skill tools. Fixtures are generated with ffmpeg lavfi (tone, silence,
    testsrc). Run: cd skills/edit && python3 -m unittest discover -s tools -p "test_*.py"
    """
    from __future__ import annotations
    
    import hashlib
    import json
    import os
    import shutil
    import subprocess
    import sys
    import tempfile
    import unittest
    
    HERE = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, HERE)
    import captions  # noqa: E402
    import deadspace  # noqa: E402
    import mediakit as mk  # noqa: E402
    
    FFMPEG = shutil.which("ffmpeg")
    # tone bursts stand in for speech: 0.5-2.0, 3.2-4.5, 4.8-6.0 s; a faint 7.9 kHz floor stands in for room noise
    SPEECH = "between(t,0.5,2.0)+between(t,3.2,4.5)+between(t,4.8,6.0)"
    TONE = f"aevalsrc='0.3*sin(2*PI*220*t)*({SPEECH})+0.0005*sin(2*PI*7919*t)':s=48000:d=7"
    
    
    def ff(*args):
        subprocess.run([FFMPEG, "-nostdin", "-hide_banner", "-v", "error", "-y", *args], check=True)
    
    
    def tool(name, *args):
        return subprocess.run([sys.executable, os.path.join(HERE, name), *map(str, args)],
                              capture_output=True, text=True)
    
    
    def frame_md5s(path):
        out = subprocess.run([FFMPEG, "-v", "error", "-i", path, "-map", "0:v", "-f", "framemd5", "-"],
                             capture_output=True, text=True, check=True).stdout
        return [line.split(",")[-1].strip() for line in out.splitlines() if line and not line.startswith("#")]
    
    
    @unittest.skipUnless(FFMPEG and shutil.which("ffprobe"), "ffmpeg/ffprobe not on PATH")
    class EditToolsTest(unittest.TestCase):
        @classmethod
        def setUpClass(cls):
            cls.tmp = tempfile.mkdtemp(prefix="edit-test-")
            cls.talk = os.path.join(cls.tmp, "talk.mp4")
            ff("-f", "lavfi", "-i", "testsrc2=s=180x320:r=30:d=7", "-f", "lavfi", "-i", TONE,
               "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", "-shortest", cls.talk)
            cls.wav = os.path.join(cls.tmp, "talk.wav")
            ff("-f", "lavfi", "-i", TONE, "-c:a", "pcm_s16le", cls.wav)
            cls.silent_video = os.path.join(cls.tmp, "noaudio.mp4")
            ff("-f", "lavfi", "-i", "testsrc2=s=180x320:r=30:d=1", "-c:v", "libx264", "-pix_fmt", "yuv420p",
               cls.silent_video)
            # words aligned to the bursts: burst 2 is "um", burst 1 is an abandoned attempt that burst 3 repeats
            cls.words = os.path.join(cls.tmp, "talk.words.json")
            words = [
                {"word": " So", "start": 0.5, "end": 0.8}, {"word": " the", "start": 0.85, "end": 1.1},
                {"word": " first", "start": 1.15, "end": 1.5}, {"word": " thing", "start": 1.55, "end": 1.95},
                {"word": " um", "start": 3.25, "end": 4.45},
                {"word": " So", "start": 4.8, "end": 5.0}, {"word": " the", "start": 5.05, "end": 5.2},
                {"word": " first", "start": 5.25, "end": 5.5}, {"word": " thing", "start": 5.55, "end": 5.75},
                {"word": " works.", "start": 5.8, "end": 5.98},
            ]
            with open(cls.words, "w") as handle:
                json.dump({"segments": [{"words": words}]}, handle)
    
        @classmethod
        def tearDownClass(cls):
            shutil.rmtree(cls.tmp, ignore_errors=True)
    
        # ------------------------------------------------------------ probe
        def test_probe_reports_streams(self):
            info = mk.probe(self.talk)
            self.assertEqual(info["video"]["display_width"], 180)
            self.assertAlmostEqual(info["video"]["fps"], 30.0)
            self.assertFalse(info["video"]["vfr"])
            self.assertEqual(info["audio"]["channels"], 1)
            self.assertIsNone(mk.probe(self.wav)["video"])
    
        # ------------------------------------------------------------ deadspace
        def test_deadspace_dry_run_cuts_long_pause_only(self):
            res = tool("deadspace.py", self.talk, "--dry-run", "--json", "-o", os.path.join(self.tmp, "dry.mp4"))
            self.assertEqual(res.returncode, 0, res.stderr)
            summary = json.loads(res.stdout)
            with open(summary["edl"]) as handle:
                edl = json.load(handle)
            cuts = [(c["start"], c["end"]) for c in edl["cuts"]]
            self.assertEqual(len(cuts), 3, cuts)  # head, the 1.2 s gap, tail; the 0.3 s gap stays
            self.assertTrue(any(2.0 < s < 2.3 and 3.0 < e < 3.2 for s, e in cuts), cuts)
            self.assertFalse(any(s < 4.6 and e > 4.6 for s, e in cuts), cuts)
            self.assertGreater(summary["saved_s"], 1.8)
            self.assertFalse(os.path.exists(os.path.join(self.tmp, "dry.mp4")))
    
        def test_deadspace_render_keeps_speech_and_sync(self):
            out = os.path.join(self.tmp, "cut.mp4")
            res = tool("deadspace.py", self.talk, "-o", out, "--json")
            self.assertEqual(res.returncode, 0, res.stderr)
            summary = json.loads(res.stdout)
            info = mk.probe(out)
            self.assertLess(abs(info["video"]["duration"] - info["audio"]["duration"]), 0.04)
            self.assertAlmostEqual(info["video"]["duration"], summary["output_s"], delta=0.05)
            levels = mk.audio_envelope(out, info)
            speech = sum(1 for v in levels if v > -25) * 0.01
            self.assertAlmostEqual(speech, 4.0, delta=0.12)  # all 4.0 s of "speech" survived
    
        def test_deadspace_audio_only_and_no_clicks(self):
            out = os.path.join(self.tmp, "cut.wav")
            res = tool("deadspace.py", self.wav, "-o", out)
            self.assertEqual(res.returncode, 0, res.stderr)
            import array
            self.assertEqual(mk.probe(out)["audio"]["codec"], "pcm_s24le")
            raw = subprocess.run([FFMPEG, "-v", "error", "-i", out, "-f", "f32le", "-acodec", "pcm_f32le", "-"],
                                 capture_output=True, check=True).stdout
            samples = array.array("f")
            samples.frombytes(raw)
            if sys.byteorder == "big":
                samples.byteswap()
            max_step = max(abs(b - a) for a, b in zip(samples, samples[1:]))
            self.assertLess(max_step, 0.3 * 2 * 3.1416 * 220 / 48000 * 1.5)  # no step beyond the tone's own slope
            self.assertLess(len(samples) / 48000, 5.2)
    
        def test_deadspace_no_audio_is_usage_error(self):
            res = tool("deadspace.py", self.silent_video, "--dry-run")
            self.assertEqual(res.returncode, 2)
            self.assertIn("no audio", res.stderr)
    
        def test_deadspace_transcript_fillers_retakes_and_edl_veto(self):
            out = os.path.join(self.tmp, "tx.mp4")
            res = tool("deadspace.py", self.talk, "-o", out, "--transcript", self.words, "--json")
            self.assertEqual(res.returncode, 0, res.stderr)
            summary = json.loads(res.stdout)
            self.assertIn("filler", summary["by_reason"])
            self.assertIn("retake", summary["by_reason"])
            self.assertLess(summary["output_s"], 1.6)  # only the last take "so the first thing works" remains
            with open(summary["words"]) as handle:
                kept = [w["text"] for w in json.load(handle)["words"]]
            self.assertEqual(kept, ["So", "the", "first", "thing", "works."])
            with open(summary["edl"]) as handle:
                edl = json.load(handle)
            for cut in edl["cuts"]:
                if "retake" in cut["reason"]:
                    cut["apply"] = False
            edited = os.path.join(self.tmp, "edited.edl.json")
            with open(edited, "w") as handle:
                json.dump(edl, handle)
            res2 = tool("deadspace.py", self.talk, "-o", os.path.join(self.tmp, "veto.mp4"),
                        "--from-edl", edited, "--json")
            self.assertEqual(res2.returncode, 0, res2.stderr)
            self.assertGreater(json.loads(res2.stdout)["output_s"], summary["output_s"] + 1.2)
    
        def test_retake_detection_unit(self):
            def w(texts):
                return [{"text": t, "start": i * 0.5, "end": i * 0.5 + 0.3} for i, t in enumerate(texts)]
            cuts = deadspace.transcript_cuts(w("so the first so the first thing".split()), set(), "exact",
                                             0.08, 0.14, 0.0, 10.0)
            self.assertEqual([c["text"] for c in cuts], ["so the first"])
            none = deadspace.transcript_cuts(w("we build tools and we ship them".split()), set(), "fuzzy",
                                             0.08, 0.14, 0.0, 10.0)
            self.assertEqual(none, [])
            merged = deadspace.merge_cuts([{"start": 0, "end": 1, "reason": "silence"},
                                           {"start": 0.5, "end": 2, "reason": "filler", "text": "um"}])
            self.assertEqual(merged, [{"start": 0, "end": 2, "reason": "silence+filler", "text": "um"}])
    
        # ------------------------------------------------------------ captions
        def test_chunking_rules(self):
            words = [{"text": t, "start": i * 0.4, "end": i * 0.4 + 0.35} for i, t in
                     enumerate("Stop editing videos by hand. I built a tool for the job".split())]
            cues = captions.chunk_words(words, 3, 18, 0.3)
            texts = [" ".join(w["text"] for w in c["words"]) for c in cues]
            self.assertTrue(all(len(c["words"]) <= 3 for c in cues), texts)
            self.assertTrue(any(t.endswith("hand.") for t in texts), texts)  # breaks after the sentence end
            self.assertTrue(texts[texts.index(next(t for t in texts if t.endswith("hand."))) + 1].startswith("I"))
            self.assertFalse(any(t.split()[-1] in ("a", "the", "for") for t in texts[:-1]), texts)
            for a, b in zip(cues, cues[1:]):
                self.assertLessEqual(a["end"], b["start"] + 1e-9)
    
        def test_captions_files_and_safe_zone(self):
            outdir = os.path.join(self.tmp, "caps")
            res = tool("captions.py", self.talk, "--words", self.words, "-o", outdir, "--size", "1080x1920",
                       "--json")
            self.assertEqual(res.returncode, 0, res.stderr)
            with open(os.path.join(outdir, "talk.cues.json")) as handle:
                cues = json.load(handle)
            self.assertEqual(cues["height"], 1920)
            self.assertTrue(all(1 <= len(c["words"]) <= 3 for c in cues["cues"]))
            self.assertNotIn("UM", " ".join(c["text"] for c in cues["cues"]))
            with open(os.path.join(outdir, "talk.ass")) as handle:
                ass = handle.read()
            self.assertIn("PlayResY: 1920", ass)
            self.assertIn(",2,140,140,480,1", ass)  # bottom-centre, text bottom at y 1440, clear of the rail
            self.assertIn("\\c&H0000D4FF&", ass)  # active word in the accent colour
            with open(os.path.join(outdir, "talk.srt")) as handle:
                self.assertTrue(handle.read().startswith("1\n00:00:00,500 --> "))
    
        def test_captions_burn_needs_libass(self):
            out = os.path.join(self.tmp, "burned.mp4")
            res = tool("captions.py", self.talk, "--words", self.words, "-o", os.path.join(self.tmp, "b"),
                       "--burn", out)
            if mk.has_filter("ass") or mk.has_filter("subtitles"):
                self.assertEqual(res.returncode, 0, res.stderr)
                self.assertTrue(os.path.isfile(out))
            else:
                self.assertEqual(res.returncode, 3)
                self.assertIn("HyperFrames", res.stderr)
                self.assertTrue(os.path.isfile(os.path.join(self.tmp, "b", "talk.srt")))
    
        def test_srt_input_gives_words(self):
            srt = os.path.join(self.tmp, "in.srt")
            with open(srt, "w") as handle:
                handle.write("1\n00:00:01,000 --> 00:00:02,000\nhello there world\n\n")
            words = mk.load_words(srt)
            self.assertEqual([w["text"] for w in words], ["hello", "there", "world"])
            self.assertAlmostEqual(words[0]["start"], 1.0)
            self.assertLessEqual(words[-1]["end"], 2.0)
    
        # ------------------------------------------------------------ stop motion
        def test_stopmotion_frames_holds_and_determinism(self):
            frames = os.path.join(self.tmp, "frames")
            os.makedirs(frames, exist_ok=True)
            for i in range(4):  # mixed sizes and formats on purpose
                ext = "png" if i % 2 else "jpg"
                size = "320x240" if i % 2 else "240x320"
                ff("-f", "lavfi", "-i", f"testsrc2=s={size}:d=1", "-ss", str(i * 0.2), "-frames:v", "1",
                   os.path.join(frames, f"frame{i + 1}.{ext}"))
            a, b, c = (os.path.join(self.tmp, n) for n in ("sm_a.mp4", "sm_b.mp4", "sm_c.mp4"))
            for out, seed in ((a, 3), (b, 3), (c, 4)):
                res = tool("stopmotion.py", frames, "-o", out, "--size", "180x320", "--crf", "0",
                           "--seed", seed, "--loop", 2)
                self.assertEqual(res.returncode, 0, res.stderr)
            md5 = frame_md5s(a)
            self.assertEqual(len(md5), 4 * 2 * 2)  # 4 images x 2 loops x held on twos
            self.assertEqual(md5[0], md5[1])
            self.assertNotEqual(md5[1], md5[2])
            self.assertNotEqual(md5[0], md5[8])  # second loop wobbles differently
            self.assertEqual(md5, frame_md5s(b))
            self.assertNotEqual(md5, frame_md5s(c))
            self.assertEqual(mk.probe(a)["video"]["fps"], 24.0)
    
        def test_stopmotion_from_video_and_bad_folder(self):
            out = os.path.join(self.tmp, "live.mp4")
            res = tool("stopmotion.py", "--from-video", self.talk, "-o", out, "--crf", "0", "--fps", "8",
                       "--hold", "3")
            self.assertEqual(res.returncode, 0, res.stderr)
            info = mk.probe(out)
            self.assertEqual(info["video"]["fps"], 24.0)
            self.assertIsNotNone(info["audio"])
            md5 = frame_md5s(out)
            self.assertEqual(md5[0], md5[2])
            self.assertNotEqual(md5[2], md5[3])
            empty = os.path.join(self.tmp, "empty")
            os.makedirs(empty, exist_ok=True)
            self.assertEqual(tool("stopmotion.py", empty, "-o", out).returncode, 2)
    
    
    if __name__ == "__main__":
        unittest.main()
    
  • README.mdupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

Plain-text copy, no login: /skill-bundles/jakeschincariol-master-skills-skills-edit.md

// REPO STATS

180 stars
1 open issues
Last commit: 1mo ago