Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.
Edit video đợt 1: lõi + CLI dựng lại video tự quay theo thẻ kiểu edit
Lumtek82354d298be8
diff --git a/.gitignore b/.gitignoreindex c828142..4532018 100644--- a/.gitignore+++ b/.gitignore@@ -43,3 +43,10 @@ jobs/*/audio/_pr/_plans/_final/++# LumReels Edit: môi trường + model + font dựng lúc cài (node edit/setup.mjs), dữ liệu chạy+edit/.venv/+edit/askeditor/models/+edit/askeditor/.cache/+edit/askeditor/fonts/BeVietnamPro/+edits/diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex d27df01..5a3aea9 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -17,9 +17,17 @@ It depends on the third-party software below. These packages are **not bundled i| VieNeu via `pip install vieneu` | Optional Vietnamese voices | Apache-2.0 (package); model weights per their model card || [edge-tts](https://github.com/rany2/edge-tts) | Optional online voice fallback (uses Microsoft's online TTS service) | LGPL-3.0 (package); service subject to Microsoft's terms || ffmpeg, Google Chrome | Installed separately by the user | Their own licenses |+| Edit video (`node edit/setup.mjs`, into `edit/.venv`): [faster-whisper](https://github.com/SYSTRAN/faster-whisper), [CTranslate2](https://github.com/OpenNMT/CTranslate2) | Speech to text with word times | MIT |+| Edit video: [MediaPipe](https://github.com/google-ai-edge/mediapipe), [OpenCV](https://opencv.org), NumPy, Pillow, fontTools, brotli | Face/person detection, frames, drawing, building fonts | Apache-2.0, Apache-2.0, BSD-3-Clause, MIT-CMU, MIT, MIT |+| Edit video, GPU only: `nvidia-cublas-cu12`, `nvidia-cudnn-cu12` | CUDA libraries for whisper on NVIDIA GPUs | NVIDIA proprietary license (redistribution terms of the CUDA/cuDNN EULA) |+| Edit video model: [Whisper large-v3](https://huggingface.co/Systran/faster-whisper-large-v3) (CTranslate2 conversion of OpenAI Whisper) | Vietnamese transcription | MIT |+| Edit video models: MediaPipe BlazeFace short range, Selfie Segmenter, Selfie Multiclass 256×256, Face Landmarker (fetched into `edit/askeditor/models/`, SHA-256 pinned) | Face and person | Apache-2.0 (model cards) |## Files in this repository that are not MIT+- `edit/askeditor/`: code copied from [AskEditor ai-video-editing-skills](https://github.com/AskEditor/ai-video-editing-skills) (commit `e20000b2`), © AskEditor, **MIT License** (`edit/askeditor/LICENSE`, `edit/askeditor/NOTICE.md`). LumReels' changes are listed in `edit/askeditor/VENDORED.md`.+- `edit/askeditor/fonts/*`: Anton, DM Serif Display, Instrument Serif, Poppins, Caveat Brush, VT323, IBM Plex Mono from Google Fonts, SIL Open Font License 1.1 (an `OFL.txt` beside each). `edit/askeditor/fonts/BeVietnamPro/` is built at install time from `@fontsource/be-vietnam-pro` (OFL 1.1) and is not in the repository.+- `site/src/fonts/be-vietnam-pro-*.woff2`: Be Vietnam Pro, © The Be Vietnam Pro Project Authors, SIL Open Font License 1.1 (see `site/src/fonts/OFL.txt`).## Contentdiff --git a/cli.mjs b/cli.mjsindex 988b6d6..f4a3e1f 100644--- a/cli.mjs+++ b/cli.mjs@@ -8,7 +8,9 @@// node cli.mjs list [--json]// node cli.mjs show <jobId>// node cli.mjs templates [--json]+// node cli.mjs edit <video> --style <id> [--music file] [--content "dặn thêm"] [--draft] [--llm off] [--json]import fs from 'node:fs';+import path from 'node:path';import { createJob, runJob, renderJob, runDue, listJobs, readJob, readLog, jobPaths, loadCatalog, hasGuidance, exportOutput } from './generator/jobs.mjs';import { parseArgs, probe } from './engine/lib.mjs';import { rewriteScript } from './generator/rewrite.mjs';@@ -43,7 +45,11 @@ function usage() {audio-options [--json] style nhạc + giọng đọc có trên máylist [--json] danh sách jobshow <jobId> trạng thái + log + đường dẫn- templates [--json] mẫu nào đã có guidance`);+ templates [--json] mẫu nào đã có guidance+ edit <video> --style <id> [--music file] [--content "dặn thêm"] [--draft] [--llm off] [--json]+ dựng lại video tự quay theo thẻ kiểu edit (edit-styles/<id>.md) → edits/<id>/out.mp4+ cắt ngập ngừng/nói lại (LLM), phụ đề tiếng Việt, zoom, reframe 9:16, nhạc tự hạ, sfx, −14 LUFS.+ --draft: phụ đề PIL vẽ thẳng (nhanh), mặc định phụ đề HyperFrames. Cài trước: node edit/setup.mjs`);}const readContent = (c) => (fs.existsSync(c) && fs.statSync(c).isFile() ? fs.readFileSync(c, 'utf8') : c);@@ -76,6 +82,17 @@ try {else if (done.error) console.log('Lỗi: ' + done.error);}process.exit(done.status === 'error' ? 1 : 0);+ } else if (cmd === 'edit') {+ if (!pos[0]) { usage(); process.exit(2); }+ const { editVideo } = await import('./edit/pipeline.mjs');+ const r = await editVideo(pos[0], { style: typeof opt.style === 'string' ? opt.style : 'sach-gon', music: typeof opt.music === 'string' ? opt.music : undefined,+ content: typeof opt.content === 'string' ? readContent(opt.content) : undefined, draft: !!opt.draft, llm: opt.llm === 'off' ? 'off' : 'on',+ log: opt.json ? () => {} : console.log });+ if (opt.json) out(r);+ else console.log(r.ok ? `MP4: ${r.out}+EDL: ${r.edl}+Xem trước: ${path.join(r.dir, 'preview.jpg')}` : 'Lỗi: ' + r.error);+ process.exit(r.ok ? 0 : 1);} else if (cmd === 'render') {if (!pos[0]) { usage(); process.exit(2); }const done = await renderJob(pos[0], { quality: opt.quality || 'looks', audio: opt.audio });diff --git a/docs/CHI-TIET.md b/docs/CHI-TIET.mdindex 158c049..e1e91e3 100644--- a/docs/CHI-TIET.md+++ b/docs/CHI-TIET.md@@ -48,6 +48,36 @@ Trạng thái: `scheduled → queued → generating → (waiting_agent) → prevNút **Viết lại kịch bản** cạnh ô Nội dung (và `POST /api/rewrite {templateId, content, durationS}` → `{script, notes, engine, usage}`, CLI `node cli.mjs rewrite`, MCP `rewrite_script`): AI đọc §1–§3 và §10 guidance của mẫu, viết lại nội dung thành các ô nội dung đúng giới hạn ký tự, chia cảnh theo thời lượng; giữ ý, số liệu, thương hiệu, CTA; không bịa số liệu thật. Nội dung ≤ 4000 ký tự, tối đa 90 giây/lượt, server chỉ chạy 1 lượt một lúc (cách nhau ≥ 3 giây). Lõi: `generator/rewrite.mjs`.Engine: `api` (có `ANTHROPIC_API_KEY`, model `REWRITE_MODEL`) → `claude` (Claude Code headless `claude -p --tools ""`, không tool, không MCP, chạy trong thư mục tạm trống) → chưa có cả hai thì báo "Chưa cấu hình AI". Ở `auto`, khoá API bị từ chối (401/403) mà máy có Claude Code thì tự chuyển sang `claude` và ghi rõ trong kết quả (`fallbackFrom`).+## Edit video (dựng lại video tự quay) — đợt 1: lõi + CLI+Người dùng đưa video tự quay (nói trước máy), chọn **thẻ kiểu edit**; LumReels tự cắt chỗ ngập ngừng/nói lại, thêm phụ đề tiếng Việt, zoom, reframe 9:16, nhạc tự hạ khi nói, tiếng động, chỉnh −14 LUFS. Chưa có UI/REST/MCP (đợt 2).++- Cài (một lần, chạy lại được): `node edit/setup.mjs [--cpu]` → venv riêng `edit/.venv` (không đụng Python hệ thống; cần Python 3.10–3.12 + ffmpeg), gói Python (~670 MB), cuBLAS + cuDNN nếu có GPU NVIDIA (~2 GB), model mặt/người MediaPipe (21 MB, kiểm SHA-256), font Be Vietnam Pro TTF (ghép từ `engine/fonts`), whisper **large-v3** (~3 GB, vào `~/.cache/huggingface`). Dòng cuối: `READY` / `NEED_PYTHON` / `NEED_FFMPEG` / `NEED_NETWORK` / `NEED_NPM`.+- Chạy: `node cli.mjs edit <video> --style sach-gon|phu-de-nay-mau [--music nhac.mp3] [--content "dặn thêm"] [--draft] [--llm off] [--json]` → `edits/<id>/`.+- Thẻ kiểu: `edit-styles/<id>.md` = khối `---json` (preset có version: ngưỡng lặng, số chữ phụ đề, zoom, mật độ, sfx, nhạc) + hướng dẫn cho LLM. Có `sach-gon` (cắt ngập ngừng, phụ đề 2–3 chữ, zoom nhẹ) và `phu-de-nay-mau` (từng chữ nảy màu, zoom 1–2 giây/cú, sfx mỗi cú).++```+video ─ edit/ingest.mjs : ffprobe đủ (xoay, VFR, HDR, start_time) + SHA-256 → proxy.mov CFR 30 fps, H.264 SDR BT.709,+ đã xoay, GOP 1 s, tiếng PCM 48 kHz, cùng trục thời gian với nguồn (t = PTS − start_time)+ ─ lumedit analyze : whisper large-v3 tiếng Việt (GPU) + nghe lại chỗ nghi ngờ + canh mốc theo tiếng (AskEditor),+ khoảng lặng, mặt (BlazeFace) → analysis.json+ ─ edit/planner.mjs : Claude (Sonnet, không tool, `--tools ""`) đọc lời chép đánh số + thẻ kiểu → ĐỀ XUẤT NGỮ NGHĨA+ (bỏ khoảng chữ nào, chữ nhấn, zoom/sfx ở chữ nào, sửa chính tả). Code kiểm; sai → LLM sửa 1 vòng;+ vẫn sai → bỏ mục hỏng. Code dựng EDL: biên cắt (+0,18 s sau chữ, −0,10 s trước chữ), rút lặng,+ mật độ zoom, sfx theo zoom → edl.json (kiểm bằng edit/edl.mjs)+ ─ lumedit stills : preview.jpg (lưới 16 khung, phụ đề nháp)+ ─ lumedit render : 1 lượt: Timeline (đoạn giữ, tiếng gốc nối crossfade 20 ms) + Framing (cửa sổ 9:16 theo mặt) + zoom+ (+ phụ đề PIL nếu --draft) → base.mp4; rồi NGHE LẠI bản cắt, so từng chữ (lẹm/mất chữ ở vết cắt)+ ─ edit/captions-hf : phụ đề bản chính = cảnh HyperFrames nền trong suốt → captions.webm (VP9 alpha)+ ─ edit/audio.mjs : giọng gốc + nhạc người dùng (sidechain theo giọng, fade cuối) + sfx engine/audio/sfx.mjs → −14 LUFS, ≤ −1,5 dBTP+ ─ ffmpeg : base + phụ đề + tiếng → out.mp4 (1080×1920, 30 fps, H.264 + AAC)+ ─ kiểm : ffprobe kích thước/fps, đo LUFS, qc-check (AskEditor: khung đen/đứng, lặng, clipping, vùng an toàn…),+ preview-final.jpg (lưới 16 khung bản ra) → result.json+```+- **EDL** (`edit/edl.schema.json`, nguồn sự thật là zod trong `edit/edl.mjs`; `node edit/edl.mjs <edl.json>` để kiểm): `version`, `source` (sha256, xoay, VFR, HDR…), `proxy`, `output`, `keep[]` (đoạn giữ, giây nguồn), `removed[]` (lý do + chữ bị bỏ), `reframe`, `zooms[]`, `captions{style, renderer, maxWords, position, words[], highlights[]}`, `sfx[]`, `music`, `audio{crossfadeMs: 20, keepSourceAudio}`. Mọi mốc là **giây của nguồn**.+- Mã AskEditor (MIT) chép vào `edit/askeditor/` (chỉ lõi + clean-cut/captions/qc-check); chỗ sửa ghi trong `edit/askeditor/VENDORED.md`. Python luôn chạy với `-X utf8` (Windows cp1252 làm vỡ chữ Việt). Biến: `LUMEDIT_WHISPER` (mặc định `large-v3`), `FX_DEVICE` (`auto|cuda|cpu`), `EDIT_MODEL` (model Claude, mặc định Sonnet), `LUMEDIT_PYTHON` (Python dùng để tạo venv).+- Clip thử tổng hợp (khi chưa có clip người thật): `node edit/test/make-synth.mjs edits/_synth/synth.mp4 [--wide]` (nối hình + giọng sạch của vài job, chèn 1 khoảng lặng 1,6 s và 1 câu nói dở rồi nói lại; ghi kèm `.truth.json`).+- Giới hạn đợt 1: 1 người nói, tiếng Việt; footage có nhạc nền to làm bước nghe lại loại nhiều chữ; reframe từ 1080p ngang phóng cửa sổ 608×1080 lên 1080×1920 (mờ hơn); chưa có sửa EDL bằng lời, UI, MCP.+## Cổng cho agent**MCP** (stdio): `node mcp/server.mjs` — tool `list_templates`, `get_template`, `rewrite_script`, `create_video` (`durationS` 3–600 hoặc `"1:30"`), `submit_scene`, `preview_job` (trả ảnh), `render_job`, `get_job`, `list_jobs`. Thử: `node scripts/mcp-smoke.mjs`.diff --git a/edit-styles/phu-de-nay-mau.md b/edit-styles/phu-de-nay-mau.mdnew file mode 100644index 0000000..209f863--- /dev/null+++ b/edit-styles/phu-de-nay-mau.md@@ -0,0 +1,35 @@+---json+{+ "id": "phu-de-nay-mau",+ "name": "Phụ đề nảy màu, zoom dồn dập",+ "version": 1,+ "pause": 0.25,+ "cutFillers": true,+ "captions": { "style": "phu-de-nay-mau", "maxWords": 1, "position": "middle", "font": "Anton", "highlightsPerMinute": 12 },+ "zoom": { "kind": "punch", "scale": 1.22, "dur": 0.9, "minGap": 1.2, "perMinute": [25, 45] },+ "sfx": { "onZoom": "swoosh", "max": 60, "gainDb": -9 },+ "music": { "gainDb": -18, "duckDb": 8, "fadeOut": 1.0 }+}+---+# Phụ đề nảy màu, zoom dồn dập++Kiểu "giữ chân người xem" cho kênh kinh doanh, tài chính. Nhịp nhanh, mỗi 1–2 giây có một cú zoom, phụ đề từng chữ to giữa khung, chữ đang nói nảy lên và đổi màu.++## Cắt+- Cắt gắt: bỏ mọi chỗ nói lại (giữ lần sau cùng), câu nói dở, câu nói về buổi quay, từ đệm, câu chào rườm rà ở đầu nếu không mang ý.+- Khoảng lặng code tự rút còn rất ngắn.+- Không bỏ chữ mang ý (số, tên, phủ định).++## Phụ đề+- Từng chữ một, chữ hoa đậm (Anton), giữa khung hơi thấp, chữ đang nói nảy lên.+- Chữ nhấn (đổi màu vàng, to hơn): số tiền, con số, động từ mạnh, từ gây tò mò. Khoảng 1 chữ mỗi 5 giây.++## Zoom+- Zoom punch vào hầu hết các chữ mạnh, cách nhau 1,2–2 giây, 25–45 lần mỗi phút. Chọn đúng chữ nặng nhất của cụm, không chọn trợ từ.++## Tiếng động+- Code tự gắn "swoosh" vào mỗi cú zoom. Mày có thể thêm "pop" hoặc "ding" ở con số quan trọng (tối đa vài cái).++## Tự kiểm+- Câu giữ lại phải trọn nghĩa.+- Zoom không rơi vào chữ đệm.diff --git a/edit-styles/sach-gon.md b/edit-styles/sach-gon.mdnew file mode 100644index 0000000..0caafa8--- /dev/null+++ b/edit-styles/sach-gon.md@@ -0,0 +1,38 @@+---json+{+ "id": "sach-gon",+ "name": "Sạch và gọn",+ "version": 1,+ "pause": 0.35,+ "cutFillers": true,+ "captions": { "style": "sach-gon", "maxWords": 3, "position": "lower", "font": "Be Vietnam Pro", "highlightsPerMinute": 6 },+ "zoom": { "kind": "punch", "scale": 1.1, "dur": 1.6, "minGap": 5, "perMinute": [3, 8] },+ "sfx": { "onZoom": null, "max": 3, "gainDb": -10 },+ "music": { "gainDb": -22, "duckDb": 10, "fadeOut": 1.5 }+}+---+# Sạch và gọn++Cho người mới, video nói trước máy. Mục tiêu: người xem nghe một mạch, không thấy chỗ vấp, không bị hiệu ứng làm phân tâm.++## Cắt+- Bỏ mọi chỗ nói lại: một câu hoặc nửa câu nói hỏng rồi nói lại thì **giữ lần nói sau cùng**, bỏ các lần trước (kể cả phần nói dở).+- Bỏ câu nói về chính buổi quay ("đợi tí", "quay lại nhé", "thử mic", "để nói lại").+- Bỏ từ đệm "ờ, ừm, à…" khi đứng riêng. Không bỏ "à, ạ, nhé, nha" khi là trợ từ cuối câu.+- Khoảng lặng dài code tự rút, đừng liệt kê.+- Không bao giờ bỏ chữ mang ý (số liệu, tên, phủ định "không", "chưa").++## Phụ đề+- 2–3 chữ một lần, chữ trắng viền đen, chữ nhấn vàng.+- Chữ nhấn: con số, tên riêng, từ then chốt của câu. Khoảng 1 chữ mỗi 10 giây, không nhấn trợ từ.+- Sửa chính tả tên riêng/thuật ngữ mà máy nghe sai (vd "luôn phin" → "Lumfin" nếu người dùng dặn).++## Zoom+- Zoom nhẹ (1,1×) vào chữ quan trọng nhất của một ý, cách nhau ít nhất 5 giây, 3–8 lần mỗi phút.++## Tiếng động+- Gần như không dùng; tối đa 3 tiếng "pop" ở những ý chính.++## Tự kiểm+- Đọc lại phần giữ: câu nào cũng trọn nghĩa, không mất chữ đầu/cuối.+- Không zoom hai lần liền nhau.diff --git a/edit/askeditor/LICENSE b/edit/askeditor/LICENSEnew file mode 100644index 0000000..2d51f38--- /dev/null+++ b/edit/askeditor/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 AskEditor++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/edit/askeditor/NOTICE.md b/edit/askeditor/NOTICE.mdnew file mode 100644index 0000000..e4b1069--- /dev/null+++ b/edit/askeditor/NOTICE.md@@ -0,0 +1,56 @@+# Notices++The code in this pack is written for it and is MIT licensed (`LICENSE`). No code from any other+project is copied or adapted into it. If that ever changes, the adapted lines and their licence are+listed here.++## Sounds (in `sounds/`)++The eight sound effects are made by `sounds/make_sounds.py`, from noise and sine waves shaped in+code. No recording, sample or sound library from anywhere else is in them, and they are part of this+pack under its MIT licence. The pack ships no music: `music-bed` plays the track a person brings.++A few sounds are made while a video renders, because they follow its own timing (a neon sign's hum+switches on and off with its letters): the light switch, the record scratch, the neon's hum and+crackle, the LED sign's ticks and the shimmer of light, in `fx/core/synth.py`. They are made the+same way, from noise and sine waves, with no recording in them.++## Fonts (in `fonts/`, each with its licence beside it)++All seven come from Google Fonts' own repository (`github.com/google/fonts`, commit+`ddf386ba1b9fbc6b2c818f1ddcd9148f54ced94b`; VT323 at commit `9862abc066c9b83bf84c3e8ed1fc2d8d48f9bbf0`) and are licensed under the SIL Open Font License,+Version 1.1. The full licence is the `OFL.txt` in each font's folder.++| Font | Files | Copyright |+|---|---|---|+| Anton | `Anton-Regular.ttf` | Copyright 2020 The Anton Project Authors |+| DM Serif Display | `DMSerifDisplay-Regular.ttf`, `DMSerifDisplay-Italic.ttf` | Copyright 2014-2018 Adobe, with Reserved Font Name 'Source'; Copyright 2019 Google LLC |+| Instrument Serif | `InstrumentSerif-Regular.ttf`, `InstrumentSerif-Italic.ttf` | Copyright 2022 The Instrument Serif Project Authors |+| Poppins | `Poppins-SemiBold.ttf`, `Poppins-Bold.ttf`, `Poppins-ExtraBold.ttf`, `Poppins-Black.ttf` | Copyright 2020 The Poppins Project Authors |+| Caveat Brush | `CaveatBrush-Regular.ttf` | Copyright 2015 Google Inc. All Rights Reserved. |+| VT323 | `VT323-Regular.ttf` | Copyright 2011, The VT323 Project Authors ([email protected]) |+| IBM Plex Mono | `IBMPlexMono-Medium.ttf`, `IBMPlexMono-Bold.ttf` | Copyright © 2017 IBM Corp. with Reserved Font Name "Plex" |++## Models (fetched by `setup.sh` into `models/`; not part of this repository)++Each file is downloaded from its official home at a pinned version and checked against the SHA-256+recorded in `fx/core/models.py`.++| Model | What it does here | From | Licence |+|---|---|---|---|+| BlazeFace (short range) | finds the face in each frame | MediaPipe model storage (`storage.googleapis.com/mediapipe-models`) | Apache License 2.0 (its model card) |+| Selfie Segmenter | the person mask | MediaPipe model storage | Apache License 2.0 (its model card) |+| Selfie Multiclass 256×256 | the detailed person mask (hair, skin, clothes), optional | MediaPipe model storage | Apache License 2.0 (its model card) |+| Face Landmarker | where each mouth is, to tell who is talking when two people are in the picture | MediaPipe model storage | Apache License 2.0 (its model card) |+| faster-whisper small.en | word timings from speech | Hugging Face, `Systran/faster-whisper-small.en`, revision `d1d751a5f8271d482d14ca55d9e2deeebbae577f` | MIT (its model card). It is a conversion of OpenAI's Whisper small.en, which is also MIT licensed |++## Python packages (installed by `setup.sh` into `.venv`; not part of this repository)++`requirements.txt` pins them. The ones the pack uses directly are faster-whisper (MIT), CTranslate2+(MIT), MediaPipe (Apache License 2.0), OpenCV (Apache License 2.0), NumPy (BSD) and Pillow+(MIT-CMU). Everything they bring with them keeps its own licence.++## Programs (installed by the person, not by this pack)++ffmpeg and ffprobe read and write the video. They are run as separate programs and are not+distributed with this pack.diff --git a/edit/askeditor/VENDORED.md b/edit/askeditor/VENDORED.mdnew file mode 100644index 0000000..35ebfc8--- /dev/null+++ b/edit/askeditor/VENDORED.md@@ -0,0 +1,17 @@+# Mã chép từ AskEditor (MIT)++- Nguồn: https://github.com/AskEditor/ai-video-editing-skills, commit `e20000b262fb5f2b7e0e87f9354d44bc00e545ca` (chép ngày 28/11/2026).+- Giấy phép: mã MIT (`LICENSE`, © AskEditor). Font OFL 1.1 (mỗi font có `OFL.txt` đi kèm). Model tải lúc cài, mỗi model giữ giấy phép riêng (`NOTICE.md`).+- Phần đã chép: `fx/core/` (toàn bộ), `fx/effects/{__init__,options,clean_cut,captions,qc_check}.py`, `fx/run.py`, `fx/meta.py`, `effects/{clean-cut,captions,qc-check}/effect.json`, `fonts/`, `requirements.txt`. 38 hiệu ứng còn lại KHÔNG chép.+- LumReels gọi phần này qua `edit/py/lumedit.py` (không qua `fx/run.py`).++## Chỗ LumReels đã sửa (đánh dấu `[LumReels]` trong mã)+1. `fx/core/words.py`+ - Ngôn ngữ và model chép lời lấy từ biến môi trường: `FX_LANG` (vd `vi`), `FX_WHISPER` (vd `large-v3`), `FX_DEVICE` (`auto|cuda|cpu`). Không đặt thì giữ nguyên như gốc (`small.en`, tiếng Anh, CPU).+ - Chạy GPU khi có CUDA: `cuda_libraries()` nạp DLL cuBLAS/cuDNN từ wheel `nvidia-*` (Windows); Linux dùng `LD_LIBRARY_PATH` do `edit/env.mjs` đặt; macOS chạy CPU. GPU lỗi thì tự chuyển CPU.+ - Khoá cache chữ (`model_key`) gồm model + ngôn ngữ, nên đổi model thì chép lại.+ - Không dùng câu mồi (`initial_prompt`) ngoài tiếng Anh (làm whisper bịa câu tiếng Việt).+ - Từ đệm tiếng Việt (ờ, ờm, ừm, ơ, hừm); câu whisper hay bịa ("hãy subscribe…", "ghiền mì gõ"…) bị bỏ ngay ở lượt nghe đầu.+2. `fx/core/text.py`: khi `FX_LANG=vi`, các mặt chữ Poppins (thiếu dấu Việt) vẽ bằng Be Vietnam Pro (OFL), do `node edit/setup.mjs` ghép từ `engine/fonts`.+3. `fx/core/models.py`: thêm lệnh `fetch-vision` (chỉ tải model mặt/người; model giọng do `FX_WHISPER` lo).+4. Mọi `read_text()` ghi rõ `encoding="utf-8"`. Ngoài ra LumReels luôn chạy Python với `-X utf8` / `PYTHONUTF8=1` vì Windows mặc định cp1252 làm vỡ chữ Việt ở các chỗ `write_text()`.diff --git a/edit/askeditor/effects/captions/effect.json b/edit/askeditor/effects/captions/effect.jsonnew file mode 100644index 0000000..f812a12--- /dev/null+++ b/edit/askeditor/effects/captions/effect.json@@ -0,0 +1,33 @@+{+ "name": "captions",+ "title": "Captions",+ "line": "Word-timed captions in four looks, kept clear of your face",+ "card": "Every word on screen, clear of your face",+ "do": "caption",+ "category": "text",+ "needs": [+ "words",+ "face"+ ],+ "say": [+ "add captions",+ "add subtitles",+ "caption this",+ "put words on screen",+ "burn in captions"+ ],+ "options": {+ "look": "stacked",+ "color": "auto",+ "position": "auto",+ "max_words": 0,+ "frame": "keep",+ "size": "auto",+ "fix": ""+ },+ "type_this": "/video-editing captions my-talk.mp4 look=serif-chip",+ "askeditor": {+ "what": "Add captions to my video",+ "why": "move, restyle and retype any line on the canvas without prompting or rendering again"+ }+}diff --git a/edit/askeditor/effects/clean-cut/effect.json b/edit/askeditor/effects/clean-cut/effect.jsonnew file mode 100644index 0000000..15e605f--- /dev/null+++ b/edit/askeditor/effects/clean-cut/effect.json@@ -0,0 +1,39 @@+{+ "name": "clean-cut",+ "title": "Clean cut",+ "line": "Dead air, retakes and false starts cut out, captions on, framed 9:16",+ "card": "Pauses and retakes out, captions on",+ "do": "clean cut",+ "category": "talking",+ "needs": [+ "words",+ "face"+ ],+ "say": [+ "cut the pauses",+ "remove the dead air",+ "cut my retakes",+ "tighten this talking video",+ "make this a clean reel",+ "jump cut this"+ ],+ "options": {+ "pause": 0.35,+ "keep_retakes": "off",+ "fillers": "cut",+ "asides": "cut",+ "captions": "on",+ "look": "stacked",+ "color": "auto",+ "position": "auto",+ "max_words": 0,+ "frame": "9:16",+ "size": "auto",+ "fix": ""+ },+ "type_this": "/video-editing clean-cut my-talk.mp4",+ "askeditor": {+ "what": "Clean up my talking video",+ "why": "every cut stays on the timeline to nudge or undo, and the captions stay words you can move and retype"+ }+}diff --git a/edit/askeditor/effects/qc-check/effect.json b/edit/askeditor/effects/qc-check/effect.jsonnew file mode 100644index 0000000..230e468--- /dev/null+++ b/edit/askeditor/effects/qc-check/effect.json@@ -0,0 +1,30 @@+{+ "name": "qc-check",+ "title": "Checks before done",+ "line": "Checks a finished video before you post it: black or frozen frames, silence, loudness, clipping, words over the face, the safe zone, washed-out HDR",+ "card": "Finds faults before you post",+ "do": "run the final checks on",+ "category": "checks",+ "needs": [+ "face"+ ],+ "say": [+ "check this before I post it",+ "is this ready to post",+ "check my video",+ "quality check this",+ "is anything over my face",+ "is it loud enough for Reels",+ "check the safe zone"+ ],+ "options": {+ "source": "",+ "platform": "reels",+ "strict": "off"+ },+ "type_this": "/video-editing qc-check my-reel.mp4 source=my-take.mp4",+ "askeditor": {+ "what": "Check my edit before I post it",+ "why": "it watches the edit as it will export at every moment that matters, and each fix is a move on the canvas, not a new render"+ }+}diff --git a/edit/askeditor/fonts/.source-commit b/edit/askeditor/fonts/.source-commitnew file mode 100644index 0000000..8dd1b0d--- /dev/null+++ b/edit/askeditor/fonts/.source-commit@@ -0,0 +1 @@+ddf386ba1b9fbc6b2c818f1ddcd9148f54ced94bdiff --git a/edit/askeditor/fonts/Anton/Anton-Regular.ttf b/edit/askeditor/fonts/Anton/Anton-Regular.ttfnew file mode 100644index 0000000..4d65707Binary files /dev/null and b/edit/askeditor/fonts/Anton/Anton-Regular.ttf differdiff --git a/edit/askeditor/fonts/Anton/OFL.txt b/edit/askeditor/fonts/Anton/OFL.txtnew file mode 100644index 0000000..93fedde--- /dev/null+++ b/edit/askeditor/fonts/Anton/OFL.txt@@ -0,0 +1,93 @@+Copyright 2020 The Anton Project Authors (https://github.com/googlefonts/AntonFont.git)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/edit/askeditor/fonts/CaveatBrush/CaveatBrush-Regular.ttf b/edit/askeditor/fonts/CaveatBrush/CaveatBrush-Regular.ttfnew file mode 100644index 0000000..fa60b56Binary files /dev/null and b/edit/askeditor/fonts/CaveatBrush/CaveatBrush-Regular.ttf differdiff --git a/edit/askeditor/fonts/CaveatBrush/OFL.txt b/edit/askeditor/fonts/CaveatBrush/OFL.txtnew file mode 100644index 0000000..25cc0c2--- /dev/null+++ b/edit/askeditor/fonts/CaveatBrush/OFL.txt@@ -0,0 +1,93 @@+Copyright 2015 Google Inc. All Rights Reserved.++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/edit/askeditor/fonts/DMSerifDisplay/DMSerifDisplay-Italic.ttf b/edit/askeditor/fonts/DMSerifDisplay/DMSerifDisplay-Italic.ttfnew file mode 100644index 0000000..5369414Binary files /dev/null and b/edit/askeditor/fonts/DMSerifDisplay/DMSerifDisplay-Italic.ttf differdiff --git a/edit/askeditor/fonts/DMSerifDisplay/DMSerifDisplay-Regular.ttf b/edit/askeditor/fonts/DMSerifDisplay/DMSerifDisplay-Regular.ttfnew file mode 100644index 0000000..bc5ed0cBinary files /dev/null and b/edit/askeditor/fonts/DMSerifDisplay/DMSerifDisplay-Regular.ttf differdiff --git a/edit/askeditor/fonts/DMSerifDisplay/OFL.txt b/edit/askeditor/fonts/DMSerifDisplay/OFL.txtnew file mode 100644index 0000000..be384f0--- /dev/null+++ b/edit/askeditor/fonts/DMSerifDisplay/OFL.txt@@ -0,0 +1,93 @@+Copyright 2014-2018 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries. Copyright 2019 Google LLC.++This Font Software is licensed under the SIL Open Font License, Version 1.1.++This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/edit/askeditor/fonts/IBMPlexMono/IBMPlexMono-Bold.ttf b/edit/askeditor/fonts/IBMPlexMono/IBMPlexMono-Bold.ttfnew file mode 100644index 0000000..17b406dBinary files /dev/null and b/edit/askeditor/fonts/IBMPlexMono/IBMPlexMono-Bold.ttf differdiff --git a/edit/askeditor/fonts/IBMPlexMono/IBMPlexMono-Medium.ttf b/edit/askeditor/fonts/IBMPlexMono/IBMPlexMono-Medium.ttfnew file mode 100644index 0000000..33c546fBinary files /dev/null and b/edit/askeditor/fonts/IBMPlexMono/IBMPlexMono-Medium.ttf differdiff --git a/edit/askeditor/fonts/IBMPlexMono/OFL.txt b/edit/askeditor/fonts/IBMPlexMono/OFL.txtnew file mode 100644index 0000000..c35c4c6--- /dev/null+++ b/edit/askeditor/fonts/IBMPlexMono/OFL.txt@@ -0,0 +1,93 @@+Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"++This Font Software is licensed under the SIL Open Font License, Version 1.1.++This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/edit/askeditor/fonts/InstrumentSerif/InstrumentSerif-Italic.ttf b/edit/askeditor/fonts/InstrumentSerif/InstrumentSerif-Italic.ttfnew file mode 100644index 0000000..192c3edBinary files /dev/null and b/edit/askeditor/fonts/InstrumentSerif/InstrumentSerif-Italic.ttf differdiff --git a/edit/askeditor/fonts/InstrumentSerif/InstrumentSerif-Regular.ttf b/edit/askeditor/fonts/InstrumentSerif/InstrumentSerif-Regular.ttfnew file mode 100644index 0000000..36fac00Binary files /dev/null and b/edit/askeditor/fonts/InstrumentSerif/InstrumentSerif-Regular.ttf differdiff --git a/edit/askeditor/fonts/InstrumentSerif/OFL.txt b/edit/askeditor/fonts/InstrumentSerif/OFL.txtnew file mode 100644index 0000000..337c35a--- /dev/null+++ b/edit/askeditor/fonts/InstrumentSerif/OFL.txt@@ -0,0 +1,93 @@+Copyright 2022 The Instrument Serif Project Authors (https://github.com/Instrument/instrument-serif)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+https://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/edit/askeditor/fonts/Poppins/OFL.txt b/edit/askeditor/fonts/Poppins/OFL.txtnew file mode 100644index 0000000..246c977--- /dev/null+++ b/edit/askeditor/fonts/Poppins/OFL.txt@@ -0,0 +1,93 @@+Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/edit/askeditor/fonts/Poppins/Poppins-Black.ttf b/edit/askeditor/fonts/Poppins/Poppins-Black.ttfnew file mode 100644index 0000000..6612e52Binary files /dev/null and b/edit/askeditor/fonts/Poppins/Poppins-Black.ttf differdiff --git a/edit/askeditor/fonts/Poppins/Poppins-Bold.ttf b/edit/askeditor/fonts/Poppins/Poppins-Bold.ttfnew file mode 100644index 0000000..1982f38Binary files /dev/null and b/edit/askeditor/fonts/Poppins/Poppins-Bold.ttf differdiff --git a/edit/askeditor/fonts/Poppins/Poppins-ExtraBold.ttf b/edit/askeditor/fonts/Poppins/Poppins-ExtraBold.ttfnew file mode 100644index 0000000..167667dBinary files /dev/null and b/edit/askeditor/fonts/Poppins/Poppins-ExtraBold.ttf differdiff --git a/edit/askeditor/fonts/Poppins/Poppins-SemiBold.ttf b/edit/askeditor/fonts/Poppins/Poppins-SemiBold.ttfnew file mode 100644index 0000000..c30ad10Binary files /dev/null and b/edit/askeditor/fonts/Poppins/Poppins-SemiBold.ttf differdiff --git a/edit/askeditor/fonts/VT323/OFL.txt b/edit/askeditor/fonts/VT323/OFL.txtnew file mode 100644index 0000000..aa11445--- /dev/null+++ b/edit/askeditor/fonts/VT323/OFL.txt@@ -0,0 +1,93 @@+Copyright 2011, The VT323 Project Authors ([email protected])++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/edit/askeditor/fonts/VT323/VT323-Regular.ttf b/edit/askeditor/fonts/VT323/VT323-Regular.ttfnew file mode 100644index 0000000..afa6909Binary files /dev/null and b/edit/askeditor/fonts/VT323/VT323-Regular.ttf differdiff --git a/edit/askeditor/fx/__init__.py b/edit/askeditor/fx/__init__.pynew file mode 100644index 0000000..d44683d--- /dev/null+++ b/edit/askeditor/fx/__init__.py@@ -0,0 +1,3 @@+"""The renderer behind the video-editing skills: a shared core and one module per effect."""++__version__ = "0.1.0"diff --git a/edit/askeditor/fx/core/__init__.py b/edit/askeditor/fx/core/__init__.pynew file mode 100644index 0000000..bc1ba98--- /dev/null+++ b/edit/askeditor/fx/core/__init__.py@@ -0,0 +1,46 @@+"""The core every effect shares.++- video.py: frames and sound in and out through ffmpeg pipes, at the clip's own frame rate.+- hdr.py: HDR footage (HLG or PQ, what phones film) turned into ordinary SDR as it is read.+- audio.py: the speech envelope that finds pauses, and joins that never click.+- sound.py: a track read in, loudness (BS.1770) in numpy, a sound laid on a moment, where the voice talks.+- loudness.py: a finished mix measured and set with ffmpeg's two-pass loudnorm, peaks limited first.+- soundsheet.py: what a sound effect did, as a picture: frames over a lane per sound, and close-ups.+- words.py: word times, cached next to the clip as JSON.+- moments.py: the word or line an effect sets by itself: what the speaker took back (a word replaced,+ a first attempt said again, an aside) is never it, and how strong each word and line is.+- asides.py: the sentences where the speaker talks about the recording ("testing, testing", "give+ me a second"), not to the viewer: clean-cut cuts them, and no picker sets one.+- amounts.py: the amounts said in the words, or typed, each with its unit, and how a card writes them.+- counting.py: a number that counts: figures that change every frame, when a figure said begins, and+ soft ticks under the count (chart and number-counter).+- items.py: the things an effect shows one by one (cards, rows, steps), given or found in the words,+ when each lands, lists said in order, steps said done, and an item made shorter by whole words.+- parts.py: the parts of a talk: where the speaker moves on to a new idea, each with a title.+- match.py: a person's own files matched to the words said: a map, the words in file names, a+ tags.txt, or the strongest things named, in folder order; a brand's logo on its whole name.+- face.py: a face box per frame, smoothed, cached next to the clip.+- person.py: a person mask per frame, soft-edged, cached next to the clip.+- matte.py: the person over a whole new room: a firm edge with no rim of the old room, held+ steady, two models agreeing; `Cutout` makes it for a render frame, `face_shown` checks it.+- shots.py: the clip's own cuts, where the picture jumps from one shot to the next.+- layout.py: the safe zone and placing text clear of the face.+- text.py: fonts and drawing words.+- phrasing.py: which words share a caption card, cut where a reader expects; every caption uses it.+- compose.py: laying images over frames, and behind the person.+- depth.py: pictures laid in depth in the room behind the person: cards in perspective, their soft+ shadows, how much of each the person leaves seen, and the room's drift with the head.+- glass.py: frosted glass panes: what is behind blurred and bent at the rim, toned so type reads, edge-lit.+- timeline.py: which source seconds are kept, where they land in the output, and where the picture+ stops for a moment (a freeze) before playing on.+- framing.py: the output's shape and size, and a window that follows the face calmly (it holds, then+ glides; it cuts where the clip cuts); or the whole picture fitted over a blurred copy.+- speakers.py: who is talking when two people are in the picture: the mouth that moves with the sound.+- clip.py: one clip with everything above found once and kept.+- view.py: the clip as a layout shows it (a canvas or one panel), for effects laid inside the layout.+- glitch.py: a broken signal torn over a frame (bands, blocks, split colours, scan lines) and its+ crackle; shared by transitions and glitch.+- zoom.py: a closer framing on the face (the whole head kept), how it moves, and the picture in it.+- render.py: the whole video, or a few stills, drawn by the same code.+- models.py: the model files, pinned by checksum; paths.py: where things live.+"""diff --git a/edit/askeditor/fx/core/amounts.py b/edit/askeditor/fx/core/amounts.pynew file mode 100644index 0000000..aba6ff1--- /dev/null+++ b/edit/askeditor/fx/core/amounts.py@@ -0,0 +1,666 @@+"""Numbers: the amounts said in a clip, and the ones a person types, each as a value with its unit.++ said = amounts.spoken(words) # every amount heard, in order, with the words that said it+ run = amounts.series(said, words) # the amounts a chart would show: "from 2K to 197K"+ typed = amounts.parse_list("2K, 15K") # amounts a person typed+ unit = amounts.Unit.of(run.amounts) # how the run is written: "$", "K", "%", decimals+ unit.exact(197000) -> "197K" # a value as it lands; unit.during(57312) while counting++What counts as an amount: figures as the transcriber writes them ("2,000", "197K", "$5", "15%",+"1.5", "10x"), the same with a word after them ("1.5 million", "15 percent", "5 dollars"), and+numbers said in words ("two hundred and fifty thousand", "one point five million"). What does not:+years ("2024", "twenty twenty-four"), lengths of time ("six months", "3 weeks"), and a small number+said on its own ("one of them", "two things"), which is only taken inside a pair ("from two to ten").++Nothing here rounds or converts an amount for the screen: a value is written the way it was said+or typed, shortened ("197,000" to "197K") only when the short form says exactly the same number.+"""++from __future__ import annotations++import math+import re+from dataclasses import dataclass, field, replace+from typing import Optional, Sequence++from .words import Word, normalize++# ---- the words numbers are said with ---------------------------------------------------------------++SMALL = {w: i for i, w in enumerate(+ "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen "+ "sixteen seventeen eighteen nineteen".split())}+TENS = {w: 10 * (i + 2) for i, w in enumerate("twenty thirty forty fifty sixty seventy eighty ninety".split())}+SCALE_WORDS = {"thousand": (1e3, "K"), "million": (1e6, "M"), "billion": (1e9, "B"),+ "k": (1e3, "K"), "mil": (1e6, "M"), "bn": (1e9, "B")}+SCALE_LETTERS = {"K": 1e3, "M": 1e6, "B": 1e9}+CURRENCY_WORDS = {"dollars": "$", "dollar": "$", "bucks": "$", "usd": "$", "pounds": "£", "quid": "£",+ "gbp": "£", "euros": "€", "euro": "€", "eur": "€"}+PERCENT_WORDS = {"percent", "per-cent", "pc"}+TIME_WORDS = {"second", "seconds", "sec", "secs", "minute", "minutes", "min", "mins", "hour", "hours", "hr",+ "hrs", "day", "days", "week", "weeks", "month", "months", "year", "years", "yr", "yrs", "decade",+ "decades", "am", "pm", "o'clock", "oclock", "weekend", "weekends", "night", "nights", "morning",+ "mornings", "quarter", "quarters"}+# Words that may sit between a number and the time word after it ("six whole months", "3 more weeks").+TIME_FILLERS = {"more", "whole", "full", "long", "short", "straight", "or", "so", "and", "a", "half", "extra"}+_TYPED = re.compile(+ r"^(?P<sign>[-+−])?(?P<pre>[$£€])?(?P<sign2>[-+−])?"+ r"(?P<int>\d{1,3}(?:,\d{3})+|\d+)?(?:\.(?P<dec>\d+))?"+ r"(?P<scale>k|m|b|bn|thousand|million|billion)?(?P<suf>%|x|percent)?$", re.I)+_EDGE = re.compile(r"^[\"“'(\[]+|[\"”')\].,!?;:…]+$")+++@dataclass(frozen=True)+class Amount:+ """One amount: its value, how it is written, and (when heard) the words that said it."""+ value: float+ prefix: str = "" # "$", "£", "€" or ""+ suffix: str = "" # "%", "x" or ""+ scale: str = "" # "K", "M", "B" when it was said or typed that way ("197K", "1.5 million"), else ""+ decimals: int = 0 # decimal places as said, in its scale ("1.5M" has 1)+ said: str = "" # the words as heard, or the text as typed+ first: int = -1 # the first and last word that said it (indices into the words given)+ last: int = -1+ start: float = 0.0 # when its first word starts and its last word ends+ end: float = 0.0+ kind: str = "amount" # "amount", or "year" or "time", which a chart never shows+ weak: bool = False # a small number with no unit: only taken inside a pair+ label: str = "" # a typed name for the point ("Jan")++ @property+ def family(self) -> str:+ """What amounts on one chart must share: a percentage, a multiple, a currency, or a count."""+ if self.suffix == "%":+ return "%"+ if self.suffix == "x":+ return "x"+ return self.prefix or "#"++ @property+ def marked(self) -> bool:+ """Said or typed with a unit or a scale, so it is plainly an amount."""+ return bool(self.prefix or self.suffix or self.scale)+++# ---- what a person types -----------------------------------------------------------------------------++def parse(text: str) -> Amount:+ """One typed amount: "197000", "197K", "$2.5M", "12%", "3.5x", "1,200", "-4". Raises ValueError+ with a plain message when it is not one."""+ raw = text.strip()+ t = raw.replace(" ", "").replace("−", "-")+ m = _TYPED.fullmatch(t)+ if not m or not (m.group("int") or m.group("dec")):+ raise ValueError(f"{raw!r} is not a number; write it like 2000, 2K, $2.5M or 12%")+ whole = (m.group("int") or "0").replace(",", "")+ dec = m.group("dec") or ""+ value = float(f"{whole}.{dec}" if dec else whole)+ if "-" in ((m.group("sign") or "") + (m.group("sign2") or "")):+ value = -value+ scale = ""+ if m.group("scale"):+ mult, scale = SCALE_WORDS.get(m.group("scale").lower(), (0, ""))+ if not scale: # "m" or "b" on their own+ scale = m.group("scale").upper()[:1]+ mult = SCALE_LETTERS[scale]+ value *= mult+ suf = (m.group("suf") or "").lower()+ suffix = "%" if suf in ("%", "percent") else ("x" if suf == "x" else "")+ return Amount(value=value, prefix=m.group("pre") or "", suffix=suffix, scale=scale, decimals=len(dec),+ said=raw)+++def _split_values(text: str) -> list[str]:+ """A typed list split into its items. Commas followed by a space, semicolons, bars and spaces+ separate items, so "2,000, 15,000" is two; a bare comma does too ("2000,15000"), except before+ a group of three digits that starts with a nought ("2,000,15,000" is 2,000 and 15,000)."""+ t = text.strip().strip("[]()")+ if re.search(r"[;|]|,\s|\s", t):+ parts = re.split(r"\s*[;|]\s*|,\s+|\s+(?=[$£€\d+\-−]|[A-Za-z][\w ]*:)", t)+ else:+ bits = t.split(",")+ parts = []+ for b in bits:+ if parts and re.fullmatch(r"0\d\d(?:\.\d+)?[kKmMbB%x]?", b):+ parts[-1] += "," + b # a thousands group, not a new item+ else:+ parts.append(b)+ return [p.strip() for p in parts if p.strip()]+++def parse_list(text: str) -> list[Amount]:+ """Typed amounts: "2000,15000,197000", "2K, 15K, 197K", "$2K | $197K", "[12%, 3.5%]", or each+ with a name for its point: "Jan:2K, Feb:15K, Mar:197K"."""+ out = []+ for item in _split_values(text):+ label = ""+ if ":" in item:+ label, item = (s.strip() for s in item.split(":", 1))+ a = parse(item)+ out.append(replace(a, label=label))+ if not out:+ raise ValueError("give at least one number, like 2000,15000,197000")+ return out+++# ---- what is said ---------------------------------------------------------------------------------++def _bare(word: Word) -> str:+ """The word without the punctuation around it, keeping a leading currency sign and a trailing %."""+ t = word.text.strip().replace("’", "'")+ return _EDGE.sub("", t)+++def _word_value(tokens: list[str]) -> Optional[tuple[float, int, bool, int, str]]:+ """Numbers said in words at the start of `tokens` (each one lower case, hyphenated words split):+ (value, tokens used, a year said in two halves, decimals, the scale letter said), or None."""+ total, current, used, seen, decimals = 0.0, 0.0, 0, False, 0+ letter = ""+ last_kind = "" # "small", "tens", "hundred", "scale"+ i = 0+ while i < len(tokens):+ tok = tokens[i]+ nxt = tokens[i + 1] if i + 1 < len(tokens) else ""+ if tok in SMALL or tok in TENS:+ small = SMALL.get(tok, TENS.get(tok))+ # "twenty twenty-four", "nineteen ninety": two numbers in a row with no hundred between+ # them is a year said in halves.+ if seen and last_kind in ("small", "tens") and not (last_kind == "tens" and tok in SMALL and SMALL[tok] < 10):+ first = current+ second, k = small, 1+ if tok in TENS and nxt in SMALL and SMALL[nxt] < 10:+ second, k = small + SMALL[nxt], 2+ if 10 <= first <= 20 and second < 100:+ return first * 100 + second, i + k, True, 0, ""+ break+ current += small+ seen, last_kind = True, ("tens" if tok in TENS else "small")+ elif tok == "hundred" and (seen or (i > 0 and tokens[i - 1] == "a")):+ current = (current or 1) * 100+ seen, last_kind = True, "hundred"+ elif tok in ("thousand", "million", "billion") and (seen or (i > 0 and tokens[i - 1] == "a")):+ total += (current or 1) * SCALE_WORDS[tok][0]+ current = 0+ letter = letter or SCALE_WORDS[tok][1]+ seen, last_kind = True, "scale"+ elif tok == "a" and not seen and nxt in ("hundred", "thousand", "million", "billion"):+ pass+ elif tok == "and" and seen and (nxt in SMALL or nxt in TENS):+ pass+ elif tok == "point" and seen and nxt in SMALL and SMALL[nxt] < 10:+ # "one point five million": the digits after the point, then any scale word+ frac, j = "", i + 1+ while j < len(tokens) and tokens[j] in SMALL and SMALL[tokens[j]] < 10:+ frac += str(SMALL[tokens[j]])+ j += 1+ current += float("0." + frac)+ decimals = len(frac)+ i = j+ used = j+ last_kind = "small"+ continue+ else:+ break+ i += 1+ if seen:+ used = i+ if not seen:+ return None+ value = total + current+ if letter: # decimals as written in its scale: "one million two hundred thousand" is 1.2M+ decimals = _exact_places(value / SCALE_LETTERS[letter], 2) or 0+ return value, used, False, decimals, letter+++def _tokens_from(words: list[Word], i: int, limit: int = 12) -> tuple[list[str], list[int]]:+ """The keys of the words from `i`, hyphenated words split, and which word each piece came from."""+ toks, owner = [], []+ for k in range(i, min(len(words), i + limit)):+ for piece in normalize(words[k].text).split("-"):+ if piece:+ toks.append(piece)+ owner.append(k)+ return toks, owner+++def _read(words: list[Word], i: int) -> Optional[tuple[Amount, int]]:+ """An amount said from word `i`, and the index of the word after it."""+ bare = _bare(words[i])+ m = _TYPED.fullmatch(bare.replace("−", "-"))+ prefix = suffix = scale = ""+ decimals = 0+ digits = False+ comma = False+ if m and (m.group("int") or m.group("dec")) and not m.group("sign"):+ digits = True+ whole = (m.group("int") or "0")+ comma = "," in whole+ dec = m.group("dec") or ""+ value = float(f"{whole.replace(',', '')}.{dec}" if dec else whole.replace(",", ""))+ decimals = len(dec)+ prefix = m.group("pre") or ""+ if m.group("scale"):+ mult, scale = SCALE_WORDS.get(m.group("scale").lower(), (SCALE_LETTERS.get(m.group("scale").upper()[:1], 0),+ m.group("scale").upper()[:1]))+ value *= mult+ suf = (m.group("suf") or "").lower()+ suffix = "%" if suf in ("%", "percent") else ("x" if suf == "x" else "")+ j = i + 1+ year_halves = False+ else:+ toks, owner = _tokens_from(words, i)+ got = _word_value(toks)+ if got is None:+ return None+ value, used, year_halves, decimals, scale = got+ j = owner[used - 1] + 1+ # "a" before "hundred" counts as the number's first word only when it is followed by one+ if toks[0] == "a" and used <= 1:+ return None+ # what follows the figure: a hundred or a scale ("2 hundred", "1.5 million"), a unit ("15 percent",+ # "5 dollars"), a lone "K" or "x"+ while j < len(words):+ k = normalize(words[j].text)+ if (k == "and" and j + 2 < len(words) and normalize(words[j + 1].text) == "a"+ and normalize(words[j + 2].text) == "half" and not scale and not suffix and float(value).is_integer()):+ value += 0.5 # "three and a half percent", "two and a half million"+ decimals = max(decimals, 1)+ j += 2+ elif digits and k == "hundred" and not scale:+ value *= 100+ elif k in SCALE_WORDS and not scale and not suffix:+ mult, scale = SCALE_WORDS[k]+ value *= mult+ elif k in PERCENT_WORDS or _bare(words[j]) == "%":+ suffix = "%"+ elif k == "per" and j + 1 < len(words) and normalize(words[j + 1].text) == "cent":+ suffix = "%"+ j += 1+ elif k in CURRENCY_WORDS and not prefix:+ prefix = CURRENCY_WORDS[k]+ elif k == "x" and not suffix:+ suffix = "x"+ else:+ break+ j += 1+ if suffix == "%" or prefix:+ # a unit closes the amount ("15 percent", "five million dollars")+ nk = normalize(words[j].text) if j < len(words) else ""+ if not (nk in SCALE_WORDS and not scale):+ break+ first, last = i, j - 1+ said = " ".join(w.text.strip() for w in words[first:last + 1])+ kind = "amount"+ whole_number = float(value).is_integer()+ if year_halves:+ kind = "year"+ elif digits and not comma and not prefix and not suffix and not scale and whole_number and 1900 <= value <= 2099 \+ and len(bare.strip("$£€%")) == 4:+ kind = "year"+ else:+ # a length of time: "six months", "3 more weeks", "two and a half years"+ k = j+ skipped = 0+ while k < len(words) and skipped <= 2:+ key = normalize(words[k].text)+ if key in TIME_WORDS:+ kind = "time"+ break+ if key in TIME_FILLERS:+ skipped += 1+ k += 1+ continue+ break+ if kind == "amount" and i > 0 and normalize(words[i - 1].text) in ("at", "by", "until", "till") \+ and not (prefix or suffix or scale) and value <= 12:+ kind = "time" # "at five", "by 3": a time of day+ weak = kind == "amount" and not (prefix or suffix or scale) and abs(value) < 10+ return Amount(value=value, prefix=prefix, suffix=suffix, scale=scale, decimals=decimals, said=said,+ first=first, last=last, start=words[first].start, end=words[last].end, kind=kind,+ weak=weak), j+++_PIECE = re.compile(r"^(?:[,.]\d|%)") # ",000", ".5", ".5%,", "%": the rest of a figure split off+_LETTER = re.compile(r"^[kKmMbB][.,!?;:]?$")+++def glue(words: Sequence[Word]) -> list[tuple[Word, int, int]]:+ """The words with each figure made whole again: (word, first, last) for each.++ The transcriber writes a figure as several words when it times each piece: "2,000" comes as+ "2" and ",000", "12%" as "12" and "%", "2.5" as "2" and ".5", "$5" sometimes as "$" and "5".+ A piece that follows a figure with no gap is joined back to it (and its times with it)."""+ out: list[tuple[Word, int, int]] = []+ for i, w in enumerate(words):+ t = w.text.strip()+ if out:+ prev, f, _ = out[-1]+ pt = prev.text.strip()+ close = w.start - prev.end <= 0.25+ joined = None+ if close and re.search(r"\d$", pt) and (_PIECE.match(t) or _LETTER.match(t)):+ joined = pt + t+ elif close and pt in ("$", "£", "€") and re.match(r"\d", t):+ joined = pt + t+ if joined is not None:+ out[-1] = (Word(joined, prev.start, w.end, min(prev.prob, w.prob)), f, i)+ continue+ out.append((w, i, i))+ return out+++def spoken(words: Sequence[Word]) -> list[Amount]:+ """Every amount heard in `words`, in order (years and lengths of time included, marked by `kind`).+ Each amount's `first` and `last` are indices into `words` as given.++ Read the transcriber's own words (a clip's `heard`), not words that have been tidied for+ captions: a lone "%" has no letters and is dropped from those."""+ pieces = glue(words)+ joined = [w for w, _, _ in pieces]+ out, i = [], 0+ while i < len(joined):+ got = _read(joined, i)+ if got is None:+ i += 1+ continue+ a, j = got+ f, l = pieces[a.first][1], pieces[a.last][2]+ out.append(replace(a, first=f, last=l, start=words[f].start, end=words[l].end))+ i = max(j, i + 1)+ return out+++# ---- the run a chart shows -------------------------------------------------------------------------++MAX_GAP = 3.5 # seconds between one amount and the next in the same run+MAX_WORDS_BETWEEN = 10+_JOIN = {"to", "then", "and", "now", "today", "->", "into", "reaching", "hit", "at", "over"}+# Words that may follow a clause's end and still carry on the same run of amounts ("15,000, and+# today we are at 197,000"); anything else after a comma or a full stop starts something new+# ("197K, sales are up 19%").+_LINK = {"and", "then", "now", "to", "today", "tonight", "we", "we're", "i", "i'm", "it", "it's", "they", "are",+ "is", "was", "were", "at", "hit", "reached", "up", "down", "from", "by", "over", "nearly", "almost", "about",+ "around", "just", "finally", "eventually", "that", "this", "last", "next", "year", "month", "week", "on",+ "of", "with", "into", "went", "grew", "rose", "jumped", "fell", "dropped", "climbed", "a", "the", "so",+ "but", "only", "even", "more", "than", "less", "compared", "versus", "vs", "still", "already", "all"}+_CURRENCIES = {"$", "£", "€"}+++@dataclass+class Series:+ amounts: list[Amount] # in the order they are drawn: oldest first+ said_order: list[int] = field(default_factory=list) # their indices in the order they were said+ reversed: bool = False # said newest first ("1.5M, up from 200K")+ pattern: str = "" # "from-to" when said as "from X to Y"++ @property+ def start(self) -> float:+ return min(a.start for a in self.amounts)++ @property+ def end(self) -> float:+ return max(a.end for a in self.amounts)+++def _between(words: Sequence[Word], a: Amount, b: Amount) -> list[str]:+ return [normalize(w.text) for w in words[a.last + 1:b.first]]+++def _before(words: Sequence[Word], a: Amount, n: int = 2) -> list[str]:+ return [normalize(w.text) for w in words[max(0, a.first - n):a.first]]+++def _carries_on(words: Sequence[Word], prev: Amount, a: Amount) -> bool:+ """Whether `a` carries on the run `prev` is in: said soon after it, and with no clause ended+ between them that something other than a linking word follows."""+ if a.start - prev.end > MAX_GAP or a.first - prev.last - 1 > MAX_WORDS_BETWEEN:+ return False+ stop = None+ for k in range(prev.last, a.first):+ if words[k].ends_clause:+ stop = k+ if stop is None:+ return True+ return all(normalize(w.text) in _LINK for w in words[stop + 1:a.first])+++def _runs(amounts: list[Amount], words: Sequence[Word]) -> list[list[Amount]]:+ """Amounts close together, of one family and in one train of thought, in the order said."""+ runs: list[list[Amount]] = []+ for a in amounts:+ if a.kind != "amount":+ continue # a year or a length of time is passed over: "from 2K in 2023 to 197K in 2024"+ cur = runs[-1] if runs else None+ if cur and _carries_on(words, cur[-1], a):+ prev = cur[-1]+ linked = any(k in _LINK for k in _between(words, prev, a))+ fam = {x.family for x in cur} | {a.family}+ # "$3 million, up from 500,000": a currency said once holds for a plain amount linked to it+ mixed = fam <= _CURRENCIES | {"#"} and len(fam & _CURRENCIES) == 1 and linked+ if prev.family == a.family or mixed:+ cur.append(a)+ continue+ runs.append([a])+ return [r for r in runs if r]+++def _from_to(words: Sequence[Word], run: list[Amount]) -> bool:+ if len(run) < 2:+ return False+ return "from" in _before(words, run[0], 3) and all(+ any(k in _JOIN for k in _between(words, a, b)[-2:]) for a, b in zip(run, run[1:]))+++def series(amounts: list[Amount], words: Sequence[Word], near: Optional[float] = None) -> Optional[Series]:+ """The run of amounts a chart would show, or None when nothing said is worth charting.++ A run is amounts of one family (all per cent, all dollars, all counts) said within a few seconds+ of each other. Two or more beat one; "from X to Y" beats a list; a single amount is taken only+ when it is plainly an amount (a unit, a scale, or 100 and up). Small numbers said alone ("two+ things") are taken only as a pair said "from … to …". With `near` (seconds), the run closest to+ that moment is taken. "X, up from Y" is drawn oldest first, Y then X."""+ words = list(words)+ scored = []+ for run in _runs(amounts, words):+ ft = _from_to(words, run)+ if not ft: # a small number said on its own is only taken inside "from … to …"+ run = [a for a in run if not a.weak]+ plain = any(a.marked or abs(a.value) >= 1000 for a in run) # plainly an amount, not a count of things+ if len(run) >= 2:+ score = 10.0 + 2.0 * len(run) + (3.0 if ft else 0.0) + (1.0 if plain else 0.0)+ elif len(run) == 1 and (run[0].marked or abs(run[0].value) >= 100):+ score = 4.0 + (1.0 if plain else 0.0)+ else:+ continue+ scored.append((score, run, ft))+ if not scored:+ return None+ if near is not None:+ def distance(item) -> float:+ # the amounts said at or just after `near` ("when=revenue grew" names the words before them)+ return min(abs(a.start - near) + (1.0 if a.start < near - 0.3 else 0.0) for a in item[1])+ scored.sort(key=lambda it: (distance(it), -it[0]))+ else:+ scored.sort(key=lambda it: (-it[0], it[1][0].start))+ score, run, ft = scored[0]+ order = list(range(len(run)))+ rev = False+ if len(run) == 2 and not ft:+ # "1.5 million, up from 200,000": the second is the older one+ if "from" in _before(words, run[1], 2) and "from" not in _before(words, run[0], 3):+ rev = True+ if rev:+ return Series(amounts=[run[1], run[0]], said_order=[1, 0], reversed=True, pattern="up-from")+ return Series(amounts=list(run), said_order=order, pattern="from-to" if ft else "")+++# ---- the words that say what the amounts are -----------------------------------------------------++_STOP = {"the", "a", "an", "and", "or", "but", "to", "from", "in", "on", "at", "of", "for", "with", "by", "up",+ "down", "than", "that", "this", "these", "those", "it", "it's", "is", "was", "were", "are", "be", "been",+ "we", "i", "you", "they", "he", "she", "our", "my", "your", "their", "its", "so", "just", "now", "then",+ "over", "under", "about", "around", "nearly", "almost", "only", "per", "each", "every", "more", "less",+ "like", "as", "have", "has", "had", "do", "did", "get", "got", "went", "go", "goes", "grew", "rose",+ "jumped", "fell", "dropped", "climbed", "hit", "reached", "which", "who", "what", "when", "where", "there",+ "here", "very", "really", "all", "some", "no", "not", "if", "into", "out", "after", "before", "since",+ "uh", "um", "okay", "yeah", "right", "new", "total", "already", "still", "even", "also", "too", "plus"}+_GROW = {"went", "grew", "rose", "jumped", "climbed", "fell", "dropped", "increased", "decreased", "doubled",+ "tripled", "went", "go", "goes", "is", "was", "are", "were", "hit", "reached", "from"}+++def _not_a_name(key: str) -> bool:+ """A word that cannot be part of what the amounts are called: a small word, a time, a number."""+ return (not key or key in _STOP or key in TIME_WORDS or key in SMALL or key in TENS or key in SCALE_WORDS+ or key in CURRENCY_WORDS or key in PERCENT_WORDS or any(ch.isdigit() for ch in key))+++def _name_after(a: Amount, words: list[Word]) -> str:+ """The word or two said straight after an amount ("197K *followers*", "$15,000 *in revenue*")."""+ after = []+ k = a.last + 1+ if k < len(words) and normalize(words[k].text) in ("in", "of") and k + 1 < len(words):+ nk = normalize(words[k + 1].text)+ if nk and not _not_a_name(nk) and not words[k].ends_clause and not words[a.last].ends_clause:+ k += 1+ while k < len(words) and len(after) < 2 and not words[k - 1].ends_clause:+ key = normalize(words[k].text)+ if _not_a_name(key):+ break+ after.append(words[k].clean.strip(",.;:!?"))+ k += 1+ return " ".join(after)+++def label_for(run: Series, words: Sequence[Word]) -> str:+ """What the amounts are, in the speaker's own words, when they say it: the word or two after+ an amount (the last said first), or the thing named before the first ("our *revenue* went+ from…"). Empty when nothing plain is said: a label is never made up."""+ words = list(words)+ for a in sorted(run.amounts, key=lambda a: -a.last):+ name = _name_after(a, words)+ if name:+ return name+ first = min(run.amounts, key=lambda a: a.first)+ k = first.first - 1+ while k >= 0 and normalize(words[k].text) in _GROW | {"to", "at", "by", "up", "down"} and first.first - k <= 3:+ k -= 1+ if k == first.first - 1:+ return "" # only a name joined to the amounts by a verb: "revenue grew from", "sales are up"+ before = []+ while k >= 0 and len(before) < 2:+ key = normalize(words[k].text)+ if _not_a_name(key) or words[k].ends_clause:+ break+ before.insert(0, words[k].clean.strip(",.;:!?"))+ k -= 1+ return " ".join(before)+++# ---- writing values ---------------------------------------------------------------------------------++def _exact_places(x: float, most: int) -> Optional[int]:+ """The fewest decimal places (up to `most`) that write `x` exactly, or None."""+ for d in range(most + 1):+ if abs(round(x, d) - x) < 1e-9 * max(1.0, abs(x)):+ return d+ return None+++def _group(n: float, decimals: int) -> str:+ s = f"{abs(n):,.{decimals}f}"+ return ("-" if n < 0 else "") + s+++@dataclass(frozen=True)+class Unit:+ """How one chart writes its values: the sign before, the scale letter and sign after, and the+ decimal places, chosen once from its amounts so every value on the card reads the same way."""+ prefix: str = ""+ suffix: str = "" # "%", "x", or the person's own (" users")+ scale: str = "" # "K", "M", "B" or ""+ decimals: int = 0 # in that scale++ @staticmethod+ def of(amounts: Sequence[Amount], prefix: Optional[str] = None, suffix: Optional[str] = None) -> "Unit":+ """The unit for `amounts`. `prefix` and `suffix` (when not None) are the person's own; a+ suffix of K, M or B is a scale."""+ last = amounts[-1]+ pre = next((a.prefix for a in amounts if a.prefix), "") if prefix is None else prefix+ suf = next((a.suffix for a in amounts if a.suffix), "") if suffix is None else suffix+ scale = ""+ if suf.strip().upper() in SCALE_LETTERS:+ scale, suf = suf.strip().upper(), ""+ elif suf not in ("%", "x") and not (suffix is not None and suf):+ said = [a.scale for a in amounts if a.scale]+ big = max(abs(a.value) for a in amounts)+ if said:+ scale = said[-1]+ elif big >= 1e9 and all(_exact_places(a.value / 1e9, 2) is not None for a in amounts if abs(a.value) >= 1e9):+ scale = "B"+ elif big >= 1e6 and all(_exact_places(a.value / 1e6, 2) is not None for a in amounts if abs(a.value) >= 1e6):+ scale = "M"+ elif big >= 1e4 and all(_exact_places(a.value / 1e3, 1) is not None for a in amounts if abs(a.value) >= 1e3):+ scale = "K"+ mult = SCALE_LETTERS.get(scale, 1.0)+ places = [p for a in amounts if (p := _exact_places(a.value / mult, 2)) is not None] if scale else \+ [a.decimals if not a.scale else (_exact_places(a.value, 2) or 0) for a in amounts]+ decimals = _exact_places(last.value / mult, 2)+ if decimals is None:+ decimals = max(places) if places else 0+ return Unit(prefix=pre, suffix=suf, scale=scale, decimals=decimals)++ @property+ def mult(self) -> float:+ return SCALE_LETTERS.get(self.scale, 1.0)++ def _letter(self, v: float, most: int) -> tuple[str, Optional[int]]:+ """The largest scale, up to the unit's own, that writes `v` exactly with at most `most`+ decimals (a smaller scale with at most one), and those decimals; ("", None) for none."""+ if not self.scale:+ return "", None+ ladder = [k for k in ("B", "M", "K") if SCALE_LETTERS[k] <= self.mult]+ for k in ladder:+ m = SCALE_LETTERS[k]+ if abs(v) >= m:+ d = _exact_places(v / m, most if k == self.scale else 1)+ if d is not None:+ return k, d+ return "", None++ def _write(self, v: float, letter: str, d: int) -> tuple[str, str, str, str]:+ n = v / SCALE_LETTERS[letter] if letter else v+ sign = "-" if n < 0 and abs(n) >= 0.5 * 10 ** -d else ""+ return sign + self.prefix, _group(abs(n), d), letter, self.suffix++ def exact(self, v: float) -> tuple[str, str, str, str]:+ """A value where it lands, written exactly: in a scale when the short form is exact ("2K",+ "197.5K", "$500K" beside "$3M"), plain when it is not ("500", "197,450"), with the decimals+ it needs and no more ("3.5%")."""+ letter, d = self._letter(v, 2)+ if letter:+ return self._write(v, letter, d)+ d = _exact_places(v, 2)+ return self._write(v, "", d if d is not None else 2)++ def during(self, v: float, toward: float) -> tuple[str, str, str, str]:+ """A value while counting toward `toward`: in the scale and with the decimals that value is+ written with, so the count settles on it without the figures changing shape; below that+ scale, in the next one down, whole."""+ _, digits, letter, _ = self.exact(toward)+ d = len(digits.split(".")[1]) if "." in digits else 0+ if letter and abs(v) >= SCALE_LETTERS[letter]:+ return self._write(v, letter, d)+ if letter:+ for k in ("M", "K"):+ if SCALE_LETTERS[k] < SCALE_LETTERS[letter] and abs(v) >= SCALE_LETTERS[k]:+ return self._write(v, k, 0)+ return self._write(v, "", 0)+ return self._write(v, "", d)++ @staticmethod+ def join(parts: tuple[str, str, str, str]) -> str:+ return "".join(parts)+++def text(unit: Unit, v: float) -> str:+ return Unit.join(unit.exact(v))diff --git a/edit/askeditor/fx/core/asides.py b/edit/askeditor/fx/core/asides.pynew file mode 100644index 0000000..6ef6868--- /dev/null+++ b/edit/askeditor/fx/core/asides.py@@ -0,0 +1,471 @@+"""Asides: where the speaker talks about the recording, not to the viewer.++"Testing, testing", "give me a second", "let me start again", "I've got the audio set up", "are+we rolling?": said while a take is being made, never meant for the film. clean-cut cuts them+(`asides=cut`), and no picker ever sets one: `moments.taken_back` passes over them as it passes+over a word taken back.++A sentence is judged whole, never by one word in it ("testing our product" is no mic check, and+"cut the pauses" no call to a crew), on four things:++1. **What it says.** Every word of it must belong to one of the forms an aside takes (`FORMS`) or+ say nothing ("okay", "all right", "I think", "so"). Each form is of one kind: a mic check,+ asking for a moment, starting again, the equipment, or talk to a crew. A form is *strong* when+ its words are about the recording wherever they are said ("give me a second", "let me start+ again", "I've got the audio set up"), *weak* when the same words could make a point of their+ own ("check", "again", "cut", "one, two", "hold on a second"), and *faint* when they are said to+ the viewer as often as not ("hold on", "wait").+2. **What the take is about.** A remark about a thing the take talks about elsewhere belongs to+ the talk: in a talk about editing audio, "I think this audio works better" is the point. A form+ whose own words ("audio", "testing", "cut") are said in a sentence that is not an aside counts+ two steps fainter.+3. **Where it sits.** Asides gather at the start and the end of a take, sit between pauses, and+ come together. Each of these counts one: in the opening or the closing (the first or last fifth+ of the speech, `EDGE_LEAST` to `EDGE_MOST` seconds), set off by a pause of `SET_OFF` or more on+ both sides, and next to another aside. A strong form needs one of them, a weak one two, a faint+ one all three.+4. **It is short:** at most `MOST_WORDS` words.++A sentence of words that say nothing ("All right.") next to an aside goes with it.++ python -m fx.core.asides <clip> [<clip> …] [--fix wrong=right] # every sentence, and its verdict+"""++from __future__ import annotations++import re+import sys+from dataclasses import dataclass, field+from typing import Optional++from .words import HESITATIONS, Word, pause_after++STRONG, WEAK, FAINT = 2, 1, 0+NEEDED = 3 # a form's strength plus what the shape of the take says must reach this+MOST_WORDS = 12 # the longest sentence that can be an aside+SET_OFF = 0.30 # seconds of quiet on both sides that set a sentence apart+EDGE_SHARE = 0.20 # the opening and the closing: this share of the speech at each end,+EDGE_LEAST = 8.0 # never less than this many seconds,+EDGE_MOST = 30.0 # nor more+TOPIC_COST = 2 # what a form loses when the take talks about its words elsewhere++# ---- the forms -----------------------------------------------------------------------------------+#+# Each is a regular expression over the sentence's words: lower case, no punctuation, one space+# apart, with the fillers ("um") out (`_tokens`). Written for this pack.++GEAR_WORDS = ("audio sound mic mics microphone microphones camera cameras cam lighting lens tripod battery lav "+ "lavalier headphones earphones airpods recorder recording setup levels volume gain wifi "+ "connection internet signal").split()+_GEAR = "(?:" + "|".join(GEAR_WORDS) + ")"+_DET = r"(?:the|this|my|our|that|some|a)"+_ADJ = r"(?:better|new|proper|good|other|different|external|second|backup|spare|right)"+_NP = rf"(?:{_DET} )?(?:{_ADJ} )*{_GEAR}"+_SOON = r"(?: (?:now|then|first|again|properly|quickly|real quick|a bit|a little))*"+_TIME = r"(?:second|seconds|sec|secs|moment|moments|minute|minutes|min|mins|mo|tick)"+_BRIEF = r"(?:second|sec|moment|mo|tick)"+_MEANS = (r"(?:let me|let's|let us|i'll|i will|i'm going to|i am going to|i'm going to have to|i need to|i have to|"+ r"i've got to|i got to|we'll|we need to|we have to|i should|can i|can we|i want to|i'm just going to|"+ r"let me just|i'm trying to|we should|i'll just)")+_THAT = (r"(?:that|this|it|the whole thing|that bit|that part|that line|that one|this bit|this part|this line|"+ r"the intro|the start|the beginning|the take)")+_AGAIN = r"(?:again|over|once more|one more time|from the top|from the beginning|from the start)"+_COUNT = r"(?:one|two|three|four|five)"+_FIX = (r"(?:fix|adjust|set up|setup|sort out|sort|check|test|turn on|turn up|turn down|turn off|switch on|switch off|"+ r"plug in|unplug|clip on|connect|reposition|charge|get closer to|move closer to|raise|lower)")+_GET = r"(?:get|grab|use|try|change|switch|swap|move|find|bring|put on)"+_STATE = r"(?:on|off|working|recording|plugged in|connected|fixed|sorted|set up|charged)"+_BETTER = r"(?:better|worse|clearer|louder|quieter|crisper|cleaner)"+_FINE = r"(?:fine|okay|good|all right|great)"+_MUCH = r"(?: (?:a lot|much|way|so much|a bit|a little|loads|heaps|so))?"+_SAYS = r"(?:works|is working|sounds|is|seems|looks|should be|should sound|feels)"++# Words that say nothing, said around an aside or between two ("Okay, give me a second.").+FILL = (r"(?:okay|all right|right|so|yeah|yes|yep|oh|ah|well|sorry|now|just|and|cool|great|perfect|nice|good|"+ r"there we go|here we go|i think|i guess|actually|anyway|hey|guys|everyone|everybody|real quick|quickly|"+ r"wait|hmm|okay then|right then|let's see|let me see)")++MIC, WAIT, AGAIN, GEAR, CREW = ("a mic check", "asking for a moment", "starting again", "the equipment",+ "talk to a crew")+# The words of each kind that a take could be about: when the take says them elsewhere, the form+# belongs to the talk (rule 2 above).+TOPICS = {MIC: {"testing", "test", "tests", "check", "checking", "mic", "microphone", "hear"},+ GEAR: set(GEAR_WORDS), CREW: {"cut", "action", "rolling", "recording", "speed"}, WAIT: set(), AGAIN: set()}+++@dataclass(frozen=True)+class Form:+ kind: str+ strength: int+ pattern: str+ rx: re.Pattern = field(init=False, repr=False, compare=False)++ def __post_init__(self):+ object.__setattr__(self, "rx", re.compile(self.pattern))+++FORMS = [+ # A mic check: the words of one and nothing else.+ Form(MIC, STRONG, rf"(?:mic |sound )?(?:testing|test)(?: (?:testing|test|{_COUNT}|mic|check))+"),+ Form(MIC, STRONG, rf"(?:mic|sound) check(?: (?:{_COUNT}|check|mic))*"),+ Form(MIC, STRONG, rf"check(?: (?:check|{_COUNT}|mic))+"),+ Form(MIC, WEAK, r"(?:testing|test)"),+ Form(MIC, FAINT, r"check"),+ Form(MIC, WEAK, r"one two(?: three(?: four)?)?"),+ Form(MIC, STRONG, r"is (?:this|this thing|the mic|my mic|the microphone|my microphone|the camera|this camera|"+ r"the audio|my audio) (?:still )?(?:on|working|recording|picking (?:me|this) up)"),+ Form(MIC, STRONG, r"(?:can|could) (?:you|everyone|everybody|anyone|you all|you guys|y'all) (?:hear|see) me"+ r"(?: (?:okay|all right|now|well|clearly|properly))?"),+ Form(MIC, STRONG, rf"(?:does|do) (?:this|the|my) (?:mic|microphone|audio|sound) (?:work|sound (?:{_FINE}|{_BETTER}|clear))"),+ # Asking for a moment, to whoever is in the room.+ # "Give me a second" asks for one. "Give me two minutes", "one second" and "hold on a second"+ # open a pitch as often ("Hold on a second. Did you know…"), so alone they count for little.+ Form(WAIT, STRONG, rf"give (?:me|us) (?:a|one|just a|just one|a quick) {_BRIEF}"),+ Form(WAIT, STRONG, r"(?:one|just one|one quick) (?:sec|secs|moment|tick|mo)|just a (?:sec|moment)"),+ Form(WAIT, STRONG, r"(?:hold on|hang on|wait|just wait) (?:a|one|just a) (?:sec|secs|tick|mo)"),+ Form(WAIT, WEAK, rf"just a second|bear with me (?:a|one) {_TIME}"),+ Form(WAIT, FAINT, rf"give (?:me|us) (?:a|one|just a|a few|a couple of) (?:minute|seconds|moments)|one second|"+ rf"(?:one|just a) minute|(?:hold on|hang on|wait|just wait) (?:a|one|just a) (?:second|moment|minute)|"+ rf"bear with me"),+ Form(WAIT, WEAK, rf"(?:i'll|i will|i'm going to) be (?:right back|back in a {_TIME}|one {_TIME})"),+ Form(WAIT, FAINT, r"(?:hold on|hang on|wait|just wait)"),+ # Starting again.+ Form(AGAIN, STRONG, rf"{_MEANS} (?:start|begin|do|try|take|redo|record|film|shoot)(?: {_THAT})? {_AGAIN}"),+ Form(AGAIN, STRONG, rf"{_MEANS} (?:redo|retake|re record|reshoot|re do) {_THAT}"),+ Form(AGAIN, STRONG, rf"(?:let's|let me|we'll|i'll|can we|can i|should i|should we|shall we|shall i) (?:go|try|try it|try that|do it|do that) again"),+ Form(AGAIN, STRONG, r"(?:take|attempt) (?:two|three|four|five|six|seven|eight|nine|ten)"),+ Form(AGAIN, STRONG, r"(?:another|one more|a new|new) take"),+ Form(AGAIN, STRONG, r"(?:i|i've) (?:lost|forgot) my (?:train of thought|place|line|lines)"),+ Form(AGAIN, WEAK, rf"(?:start|starting|begin|beginning) (?:again|over)|from the top|from the beginning|one more time"),+ Form(AGAIN, FAINT, r"again|once more"),+ Form(AGAIN, WEAK, r"i (?:messed|screwed|mucked|stuffed) (?:that|this|it) up|i (?:fluffed|botched|flubbed) (?:that|this|it)"),+ # The equipment, said in the first person or of the one in use now. "The audio was great" is+ # neither: it says how something was, not what is being done to the recording.+ Form(GEAR, STRONG, rf"(?:i've|i have|we've|we have|i now have|now i've)(?: got)? {_NP} "+ rf"(?:set up|setup|sorted|sorted out|fixed|working|on|ready|plugged in|connected|in place|going|running|back on|charged)"+ rf"{_SOON}"),+ Form(GEAR, WEAK, rf"(?:i've|i have|we've|we have)(?: got)? (?:{_DET} )?better {_GEAR}{_SOON}"),+ Form(GEAR, STRONG, rf"{_MEANS}(?: just| quickly| quick)? {_FIX}(?: up| on| off| in)? {_NP}"+ rf"(?: (?:set up|on|up|down|off|in|closer|working|sorted|better|right))?{_SOON}"),+ Form(GEAR, STRONG, rf"(?:{_MEANS}|i'm going to|i'm just going to)(?: just| quickly| quick)? {_GET} "+ rf"(?:{_DET} )?(?:better|proper|different|another|other|new|second|backup) {_GEAR}"+ rf"(?: (?:set up|on|in|working))?{_SOON}"),+ Form(GEAR, WEAK, rf"{_MEANS}(?: just| quickly| quick)? {_GET} {_NP}(?: (?:set up|on|in|closer))?{_SOON}"),+ Form(GEAR, STRONG, rf"(?:this|my|our|that|the new|this new) {_GEAR} {_SAYS}{_MUCH} (?:{_BETTER}|{_FINE}|{_STATE}){_SOON}"),+ Form(GEAR, STRONG, rf"the {_GEAR} {_SAYS}{_MUCH} {_BETTER}{_SOON}"),+ Form(GEAR, STRONG, rf"the {_GEAR} (?:is|seems|should be) {_STATE}{_SOON}"),+ Form(GEAR, WEAK, rf"the {_GEAR} (?:is|sounds|seems|looks) {_FINE} now"),+ Form(GEAR, STRONG, rf"(?:is|are) (?:this|we|you|the camera|this camera|the mic|my mic|this mic|the audio|my audio|"+ rf"the recording) (?:still )?(?:recording|rolling|on|picking (?:me|this) up)"),+ Form(GEAR, WEAK, r"is it (?:still )?(?:recording|rolling|on|working)"),+ Form(GEAR, STRONG, r"(?:how|what) (?:is|does|do) (?:the|this|my) (?:audio|sound|mic|microphone) (?:sound|look|seem)(?: like)?(?: now)?"),+ Form(GEAR, STRONG, rf"(?:is|does) (?:the|this|my) (?:audio|sound|mic|microphone) (?:sound )?(?:{_FINE}|clear|working|"+ rf"{_BETTER}|too loud|too quiet|loud enough)(?: now)?"),+ # Talk to a crew.+ Form(CREW, STRONG, r"(?:are we|we're|we are|is it|is the camera|are you|you're) (?:still )?(?:rolling|recording)"),+ Form(CREW, STRONG, r"and action"),+ Form(CREW, WEAK, r"(?:and )?(?:cut|action)(?: cut)*"),+ # As often asked of the viewer ("Was that good? Let me know in the comments").+ Form(CREW, FAINT, r"rolling|did you get that|did you get it|did that record|was that okay|was that all right|"+ r"was that good|how was that|was that better|that was better|that one was better"),+]+_FILL_RX = re.compile(FILL)++# Words written several ways, read one way.+_SAME = {"alright": "all right", "ok": "okay", "okey": "okay", "mike": "mic", "gonna": "going to",+ "wanna": "want to", "gotta": "got to", "lemme": "let me", "gimme": "give me", "1": "one", "2": "two",+ "3": "three", "4": "four", "5": "five", "set-up": "set up", "re-record": "re record", "redo": "redo"}+++def _tokens(words: list[Word], idx: list[int]) -> list[str]:+ """The words of a sentence as the forms read them: lower case, no punctuation, fillers out,+ hyphens and the spellings in `_SAME` evened out, and "the audio's" read as "the audio is"."""+ out: list[str] = []+ for i in idx:+ k = words[i].key+ if not k or k in HESITATIONS:+ continue+ k = _SAME.get(k, k)+ for part in k.replace("-", " ").split():+ part = _SAME.get(part, part)+ if part.endswith("'s") and part[:-2] in GEAR_WORDS:+ out += [part[:-2], "is"]+ else:+ out += part.split()+ return out+++def _stem(k: str) -> str:+ """A word without its ending, so "testing", "tests" and "test" are one word."""+ for end in ("ing", "ed"):+ if k.endswith(end) and len(k) - len(end) >= 3:+ k = k[:-len(end)]+ break+ if k.endswith("s") and not k.endswith("ss") and len(k) >= 4:+ k = k[:-1]+ return k+++@dataclass+class Reading:+ """What a sentence says, read against the forms."""+ forms: list # the forms its words make, in order (empty when it is not made of them)+ only_fillers: bool # every word of it says nothing ("All right.")+ tokens: list++ @property+ def strength(self) -> int:+ return max((f.strength for f in self.forms), default=-1)++ @property+ def kind(self) -> Optional[str]:+ best = max(self.forms, key=lambda f: f.strength, default=None)+ return best.kind if best else None++ def topic(self) -> set:+ """The words of the sentence that a take could be about (`TOPICS`), by their stem."""+ kinds = {f.kind for f in self.forms}+ return {_stem(t) for t in self.tokens if any(t in TOPICS[k] for k in kinds)}+++def read(tokens: list[str]) -> Reading:+ """Which forms the words make, covering every one of them with forms and fillers (the reading+ with the strongest form, then the most words in forms), or none."""+ n = len(tokens)+ if n == 0:+ return Reading([], True, tokens)+ if n > MOST_WORDS:+ return Reading([], False, tokens)+ best: list = [None] * (n + 1) # best[j]: (strength, words in forms, forms) covering tokens[:j]+ best[0] = (-1, 0, ())+ for i in range(n):+ if best[i] is None:+ continue+ s0, c0, f0 = best[i]+ for j in range(i + 1, n + 1):+ part = " ".join(tokens[i:j])+ options = [(s0, c0, f0)] if _FILL_RX.fullmatch(part) else []+ options += [(max(s0, f.strength), c0 + j - i, f0 + (f,)) for f in FORMS if f.rx.fullmatch(part)]+ for o in options:+ if best[j] is None or o[:2] > best[j][:2]:+ best[j] = o+ if best[n] is None:+ return Reading([], False, tokens)+ return Reading(list(best[n][2]), not best[n][2], tokens)+++# ---- the take ------------------------------------------------------------------------------------++@dataclass(frozen=True)+class Aside:+ first: int # its first word, an index into the words given+ last: int # its last word (inclusive)+ start: float+ end: float+ kind: str # what it is: "a mic check", "asking for a moment", "starting again", "about the audio", …+ said: str # the sentence, as heard+ where: str # what the shape of the take adds: "in the opening, next to another aside"++ @property+ def why(self) -> str:+ return f"{self.kind}, {self.where}" if self.where else self.kind+++def sentences(words: list[Word]) -> list[list[int]]:+ """Word indexes, one list per sentence (to each full stop, question or exclamation mark)."""+ out, cur = [], []+ for i, w in enumerate(words):+ cur.append(i)+ if w.ends_sentence:+ out.append(cur)+ cur = []+ if cur:+ out.append(cur)+ return out+++def _split_long(words: list[Word], idx: list[int], quiet) -> list[list[int]]:+ """A sentence too long to be an aside, cut where the transcriber lost its punctuation: at its+ longest pause of `SET_OFF` or more after a word it marked with nothing (no comma, no full+ stop), until every piece is short enough or no such pause is left. It does not always mark a+ sentence's end: hearing take 33 afresh, it ran "…edit to them I think this audio works better"+ together with no full stop, 0.79 s of quiet between, and the aside at the end went unseen (the+ cached hearing had "them. I think…"). A pause it did mark, with a comma, is a clause it heard+ as one sentence, and a long sentence is never cut there. Each piece is judged as any sentence+ is."""+ said = [i for i in idx if words[i].key and words[i].key not in HESITATIONS]+ if len(said) <= MOST_WORDS or len(idx) < 2:+ return [idx]+ k, longest = None, SET_OFF+ for n in range(len(idx) - 1):+ if words[idx[n]].ends_clause:+ continue+ g = _gap(words, idx[n], quiet)+ if g >= longest:+ k, longest = n, g+ if k is None:+ return [idx]+ return _split_long(words, idx[:k + 1], quiet) + _split_long(words, idx[k + 1:], quiet)+++def _gap(words: list[Word], i: int, quiet) -> float:+ """The quiet after word i: from the sound when the quiet stretches are known, else the gap+ between the word times."""+ if i + 1 >= len(words):+ return 0.0+ if quiet is not None:+ return pause_after(words, i, quiet)+ return max(0.0, words[i + 1].start - words[i].end)+++@dataclass+class _Sentence:+ idx: list+ reading: Reading+ strength: int = -1 # after the take's topic is taken into account+ opening: bool = False+ closing: bool = False+ set_off: bool = False+ aside: bool = False+ beside: bool = False+++def _judge(words: list[Word], quiet) -> list[_Sentence]:+ """Every sentence of the take, read, placed and judged (`asides` returns the ones found)."""+ said = [w for w in words if w.key and w.key not in HESITATIONS]+ out = [_Sentence(piece, read(_tokens(words, piece)))+ for idx in sentences(words) for piece in _split_long(words, idx, quiet)]+ if not said:+ return out+ t0, t1 = said[0].start, said[-1].end+ edge = min(EDGE_MOST, max(EDGE_LEAST, EDGE_SHARE * (t1 - t0)))+ # What the take talks about: the words of every sentence that is not made of asides' forms.+ talk = {_stem(t) for s in out if not s.reading.forms and not s.reading.only_fillers for t in s.reading.tokens}+ for n, s in enumerate(out):+ a, b = s.idx[0], s.idx[-1]+ s.strength = s.reading.strength+ if s.reading.forms and s.reading.topic() & talk:+ s.strength -= TOPIC_COST+ s.opening = words[a].start <= t0 + edge+ s.closing = words[b].end >= t1 - edge+ before = _gap(words, a - 1, quiet) if a > 0 else float("inf")+ after = _gap(words, b, quiet) if b + 1 < len(words) else float("inf")+ s.set_off = before >= SET_OFF and after >= SET_OFF+ # Asides come together: a sentence next to one (with nothing but words that say nothing+ # between) counts one more, so the run is found from its strongest member outwards.+ changed = True+ while changed:+ changed = False+ for n, s in enumerate(out):+ if s.aside or not s.reading.forms or s.strength < FAINT:+ continue+ s.beside = _next_to_aside(out, n)+ if s.strength + (s.opening or s.closing) + s.set_off + s.beside >= NEEDED:+ s.aside = changed = True+ # A sentence of words that say nothing next to an aside goes with it.+ changed = True+ while changed:+ changed = False+ for n, s in enumerate(out):+ if not s.aside and s.reading.only_fillers and _next_to_aside(out, n, through_fillers=False):+ s.aside = changed = True+ for n, s in enumerate(out):+ s.beside = s.aside and _next_to_aside(out, n)+ return out+++def _next_to_aside(out: list[_Sentence], n: int, through_fillers: bool = True) -> bool:+ for step in (-1, 1):+ k = n + step+ while 0 <= k < len(out):+ if out[k].aside:+ return True+ if not (through_fillers and out[k].reading.only_fillers):+ break+ k += step+ return False+++def _label(out: list[_Sentence], n: int) -> str:+ s = out[n]+ if s.reading.only_fillers:+ both = 0 < n < len(out) - 1 and out[n - 1].aside and out[n + 1].aside+ return "nothing said, between two asides" if both else "nothing said, beside an aside"+ kind = s.reading.kind+ if kind == GEAR:+ gear = next((t for t in s.reading.tokens if t in GEAR_WORDS), None)+ return f"about the {gear}" if gear else "about the equipment"+ return kind or ""+++def _where(s: _Sentence) -> str:+ bits = []+ if s.opening and s.closing:+ bits.append("in a take this short, at an end")+ elif s.opening:+ bits.append("in the opening")+ elif s.closing:+ bits.append("in the closing")+ if s.set_off:+ bits.append("set off by pauses")+ if s.beside and not s.reading.only_fillers:+ bits.append("next to another aside")+ return ", ".join(bits)+++def asides(words: list[Word], quiet=None) -> list[Aside]:+ """The sentences of a take where the speaker talks about the recording itself (a mic check,+ asking for a moment, starting again, the equipment, talk to a crew), in order: each judged+ whole by what it says, what the take is about and where it sits (see the module's notes).+ Give a clip's whole `words` and its `quiet` stretches; without `quiet` the pauses are read+ from the gaps between the word times."""+ out = []+ judged = _judge(words, quiet)+ for n, s in enumerate(judged):+ if s.aside:+ a, b = s.idx[0], s.idx[-1]+ out.append(Aside(a, b, words[a].start, words[b].end, _label(judged, n),+ " ".join(words[i].text for i in s.idx), _where(s)))+ return out+++def report(words: list[Word], quiet=None) -> list[dict]:+ """Every sentence made of asides' forms, found or not, with what decided it: for reading a+ take's verdicts (`python -m fx.core.asides`)."""+ rows = []+ judged = _judge(words, quiet)+ for n, s in enumerate(judged):+ if not (s.reading.forms or (s.aside and s.reading.only_fillers)):+ continue+ a, b = s.idx[0], s.idx[-1]+ rows.append({"start": round(words[a].start, 2), "end": round(words[b].end, 2),+ "said": " ".join(words[i].text for i in s.idx), "aside": s.aside, "kind": _label(judged, n),+ "forms": [f"{f.kind} ({['faint', 'weak', 'strong'][f.strength]})" for f in s.reading.forms],+ "strength": s.strength, "topic_said_elsewhere": s.strength < s.reading.strength,+ "opening": s.opening, "closing": s.closing, "set_off": s.set_off, "beside": s.beside})+ return rows+++def main(argv: Optional[list[str]] = None) -> int:+ import argparse++ from .clip import Clip++ ap = argparse.ArgumentParser(prog="python -m fx.core.asides", description="The asides in a take, and why.")+ ap.add_argument("clips", nargs="+")+ ap.add_argument("--fix", default=None)+ args = ap.parse_args(argv)+ for path in args.clips:+ clip = Clip(path, fix=args.fix)+ rows = report(clip.words, clip.quiet)+ print(f"{path}: {sum(r['aside'] for r in rows)} aside(s)")+ for r in rows:+ shape = ", ".join(k for k in ("opening", "closing", "set_off", "beside") if r[k])+ print(f" {'ASIDE' if r['aside'] else 'kept '} {r['start']:6.2f}-{r['end']:6.2f} \"{r['said']}\" "+ f"[{r['kind']}; {', '.join(r['forms']) or 'fillers'}; strength {r['strength']}"+ f"{'; its words are the talk' if r['topic_said_elsewhere'] else ''}; {shape or 'no shape'}]")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/edit/askeditor/fx/core/audio.py b/edit/askeditor/fx/core/audio.pynew file mode 100644index 0000000..2b6fc5d--- /dev/null+++ b/edit/askeditor/fx/core/audio.py@@ -0,0 +1,213 @@+"""Sound: the speech envelope that finds pauses, and joins that never click.++The envelope is the loudness of the speech band (100 Hz to 7.5 kHz) in 10 ms steps, in dB. Wind+rumble sits below the band and hiss is mostly above it, so a pause reads as a pause on a windy+path too, as long as the voice is louder than the wind.+"""++from __future__ import annotations++from dataclasses import dataclass++import numpy as np++HOP = 0.01 # seconds per envelope step+++@dataclass(frozen=True)+class Envelope:+ db: np.ndarray # loudness per step+ hop: float+ floor: float # the quiet between words+ speech: float # a typical spoken syllable+ threshold: float # below this is a pause++ @property+ def voiced(self) -> float:+ """A sound has to reach this, somewhere, to count as speech rather than wind or a knock."""+ return self.floor + 0.5 * (self.speech - self.floor)++ def at(self, t: float) -> float:+ i = int(min(len(self.db) - 1, max(0, round(t / self.hop))))+ return float(self.db[i])++ def mean(self, t0: float, t1: float) -> float:+ i0 = int(max(0, round(t0 / self.hop)))+ i1 = int(min(len(self.db), max(i0 + 1, round(t1 / self.hop))))+ return float(self.db[i0:i1].mean()) if i1 > i0 else self.at(t0)++ def quietest(self, t0: float, t1: float) -> float:+ """The time of the quietest 30 ms between t0 and t1: the best place for a cut."""+ i0 = int(max(0, round(t0 / self.hop)))+ i1 = int(min(len(self.db), round(t1 / self.hop) + 1))+ if i1 - i0 < 3:+ return (t0 + t1) / 2+ seg = np.convolve(self.db[i0:i1], np.ones(3) / 3, mode="same")+ return (i0 + int(np.argmin(seg))) * self.hop+++def envelope(mono: np.ndarray, rate: int, hop: float = HOP, win: float = 0.025,+ band: tuple[float, float] = (100.0, 7500.0)) -> Envelope:+ n_hop = max(1, int(round(rate * hop)))+ n_win = max(n_hop, int(round(rate * win)))+ steps = int(np.ceil(len(mono) / n_hop))+ x = np.pad(mono.astype(np.float32), (n_win // 2, n_win + n_hop))+ frames = np.lib.stride_tricks.sliding_window_view(x, n_win)[::n_hop][:steps]+ window = np.hanning(n_win).astype(np.float32)+ spectrum = np.fft.rfft(frames * window, axis=1)+ freqs = np.fft.rfftfreq(n_win, 1.0 / rate)+ keep = (freqs >= band[0]) & (freqs <= band[1])+ power = (np.abs(spectrum[:, keep]) ** 2).sum(axis=1) / (window ** 2).sum()+ db = 10.0 * np.log10(power + 1e-12)+ # A 30 ms median takes out clicks and lip noise without moving the edges of words.+ padded = np.pad(db, 1, mode="edge")+ db = np.median(np.stack([padded[:-2], padded[1:-1], padded[2:]]), axis=0)++ floor = float(np.percentile(db, 5))+ speech = float(np.percentile(db, 90))+ # A pause is close to the floor: a third of the way up to speech, but always at least 18 dB+ # under it, so a take with hardly any pauses never has its quiet words called silence.+ threshold = min(floor + max(6.0, 0.33 * (speech - floor)), speech - 18.0)+ return Envelope(db=db.astype(np.float32), hop=hop, floor=floor, speech=speech, threshold=threshold)+++def quiet_runs(env: Envelope, min_len: float = 0.08, bridge: float = 0.05, sustained: float = 0.25,+ protect: list[tuple[float, float]] | None = None) -> list[tuple[float, float]]:+ """Stretches with no speech in them, as (start, end) seconds.++ A stretch above the pause threshold is speech when it reaches `env.voiced` somewhere, lasts+ `sustained` seconds, or overlaps one of the `protect` spans (the middles of heard words);+ anything else (a gust of wind, a click, a breath catch, a knock) is part of the quiet around+ it. A blip shorter than `bridge` never breaks a quiet stretch.+ """+ quiet = env.db < env.threshold+ loud = ~quiet+ n_bridge = int(round(bridge / env.hop))+ n_sustained = int(round(sustained / env.hop))+ guarded = np.zeros(len(quiet), bool)+ for a, b in protect or []:+ guarded[int(max(0, a / env.hop)):int(min(len(quiet), b / env.hop + 1))] = True+ edges = np.flatnonzero(np.diff(np.concatenate([[0], loud.astype(np.int8), [0]])))+ for s, e in zip(edges[::2], edges[1::2]):+ inner = s > 0 and e < len(quiet)+ is_speech = (env.db[s:e].max() >= env.voiced or (e - s) >= n_sustained or guarded[s:e].any())+ if (inner and e - s <= n_bridge) or not is_speech:+ quiet[s:e] = True+ runs = []+ edges = np.flatnonzero(np.diff(np.concatenate([[0], quiet.astype(np.int8), [0]])))+ for s, e in zip(edges[::2], edges[1::2]):+ if (e - s) * env.hop >= min_len:+ runs.append((s * env.hop, e * env.hop))+ return runs+++def join(samples: np.ndarray, rate: int, ranges: list[tuple[int, int]], fade: float = 0.02) -> np.ndarray:+ """Join sample ranges [(start, end), …] end to end with short equal-power crossfades.++ The result is exactly as long as the ranges added up, so the sound stays in step with the+ picture. Each join borrows `fade / 2` from either side of the cut and blends across it; the very+ start and end get a 5 ms fade so they never click either.+ """+ ranges = [(int(s), int(e)) for s, e in ranges if e > s]+ channels = samples.shape[1]+ total = sum(e - s for s, e in ranges)+ out = np.zeros((total, channels), np.float32)+ if not ranges:+ return out+ half = max(1, int(round(fade * rate / 2)))+ lengths = [e - s for s, e in ranges]+ # Each join's half-width, never more than half of either neighbouring piece.+ joins = [min(half, lengths[k] // 2, lengths[k + 1] // 2) for k in range(len(ranges) - 1)]+ edge = max(1, int(round(0.005 * rate)))+ n = len(samples)+ pos = 0+ for k, (s, e) in enumerate(ranges):+ length = lengths[k]+ pre = joins[k - 1] if k > 0 else 0+ post = joins[k] if k < len(joins) else 0+ a, b = s - pre, e + post+ chunk = np.zeros((b - a, channels), np.float32)+ src0, src1 = max(0, a), min(n, b)+ if src1 > src0:+ chunk[src0 - a:src1 - a] = samples[src0:src1]+ gain = np.ones(b - a, np.float32)+ if pre:+ gain[: 2 * pre] = np.sin(np.linspace(0, np.pi / 2, 2 * pre, dtype=np.float32))+ elif k == 0:+ m = min(edge, len(gain))+ gain[:m] = np.linspace(0, 1, m, dtype=np.float32)+ if post:+ gain[len(gain) - 2 * post:] *= np.cos(np.linspace(0, np.pi / 2, 2 * post, dtype=np.float32))+ elif k == len(ranges) - 1:+ m = min(edge, len(gain))+ gain[len(gain) - m:] *= np.linspace(1, 0, m, dtype=np.float32)+ chunk *= gain[:, None]+ o0 = pos - pre+ out[o0:o0 + len(chunk)] += chunk+ pos += length+ return out+++# ---- room tone ---------------------------------------------------------------------------------------++@dataclass(frozen=True)+class RoomTone:+ samples: np.ndarray # (n, channels): as long as was asked for+ taken: tuple[float, float] # the stretch of the clip it was looped from, in seconds+ level_db: float # its level (RMS, dBFS) as laid+ gain_db: float # what was added to the stretch to bring it to the room's level+++def _rms_db(x: np.ndarray) -> float:+ return float(10.0 * np.log10(np.mean(np.square(x, dtype=np.float64)) + 1e-12))+++def room_tone(samples: np.ndarray, rate: int, seconds: float, quiet: list[tuple[float, float]],+ least: float = 0.25, longest: float = 1.0, edge: float = 0.06, fade: float = 0.08,+ most_gain: float = 6.0) -> RoomTone:+ """The clip's own room sound, `seconds` long: its quietest stretch with nobody speaking (from the+ `quiet` runs, `edge` seconds in from either end so no word's tail comes with it), looped with+ equal-power crossfades of `fade` seconds and brought to the room's level (the median of the+ quiet runs, never more than `most_gain` dB up). What fills a hold in the picture so it plays as+ the room holding still, not as the sound dropping out."""+ channels = samples.shape[1]+ n_out = max(0, int(round(seconds * rate)))+ hop = max(1, int(round(0.01 * rate)))+ win = int(round(0.05 * rate))+ runs = [(int((a + edge) * rate), int((b - edge) * rate)) for a, b in quiet]+ runs = [(max(0, a), min(len(samples), b)) for a, b in runs]+ runs = [(a, b) for a, b in runs if b - a >= int(least * rate)]+ if not runs: # nobody is ever quiet for long: the quietest stretch of the whole clip+ runs = [(0, len(samples))]+ want = int(longest * rate)+ best, best_db = None, np.inf+ levels: list[float] = []+ for a, b in runs:+ length = min(want, b - a)+ for s in range(a, b - length + 1, hop):+ d = _rms_db(samples[s:s + length])+ if -120.0 < d < best_db: # digital zero is not a room+ best, best_db = (s, s + length), d+ levels += [_rms_db(samples[s:s + win]) for s in range(a, b - win + 1, win)]+ if best is None or n_out == 0:+ return RoomTone(np.zeros((n_out, channels), np.float32), (0.0, 0.0), -120.0, 0.0)+ room = float(np.median([v for v in levels if v > -120.0])) if levels else best_db+ gain_db = float(np.clip(room - best_db, 0.0, most_gain))+ piece = samples[best[0]:best[1]].astype(np.float32) * np.float32(10 ** (gain_db / 20))+ p = len(piece)+ f = max(1, min(int(round(fade * rate)), p // 4))+ up = np.sin(np.linspace(0, np.pi / 2, f, dtype=np.float32))[:, None]+ down = np.cos(np.linspace(0, np.pi / 2, f, dtype=np.float32))[:, None]+ out = np.zeros((n_out + p, channels), np.float32)+ pos, first = 0, True+ while pos < n_out:+ c = piece.copy()+ if not first:+ c[:f] *= up+ if pos + p - f < n_out: # another copy follows: fade out under it (the last one runs to the end)+ c[p - f:] *= down+ out[pos:pos + p] += c+ pos += p - f+ first = False+ out = out[:n_out]+ return RoomTone(out, (best[0] / rate, best[1] / rate), _rms_db(out) if n_out else -120.0, gain_db)diff --git a/edit/askeditor/fx/core/clip.py b/edit/askeditor/fx/core/clip.pynew file mode 100644index 0000000..e63ca12--- /dev/null+++ b/edit/askeditor/fx/core/clip.py@@ -0,0 +1,74 @@+"""One clip, with everything about it found once and kept: its picture, sound, words, face and person."""++from __future__ import annotations++import os+from functools import cached_property+from typing import Optional++import numpy as np++from . import audio, video+from . import face as facemod+from . import person as personmod+from . import words as wordsmod+++class Clip:+ def __init__(self, path: str | os.PathLike, fix: Optional[str] = None):+ self.path = str(path)+ self.info = video.probe(self.path)+ self.fix = fix or ""++ # ---- sound ----+ @cached_property+ def sound(self) -> np.ndarray:+ """The clip's sound at 48 kHz stereo, lined up with frame 0 and as long as the picture."""+ return video.read_audio(self.info)++ @cached_property+ def envelope(self) -> audio.Envelope:+ return audio.envelope(video.mono(self.sound, video.AUDIO_RATE, 16000), 16000)++ # ---- words ----+ def _quiet_for(self, heard: list[wordsmod.Word]) -> list[tuple[float, float]]:+ middles = [((w.start + w.end) / 2 - 0.03, (w.start + w.end) / 2 + 0.03) for w in heard]+ return audio.quiet_runs(self.envelope, protect=middles)++ @cached_property+ def heard(self) -> list[wordsmod.Word]:+ """Every word heard, times as heard: the transcriber's words, with the stretches it could+ not explain heard a second time (`words.relisten`) and judged (`words.merge`), and any+ corrections applied. What the second listen heard but could not be sure of is here too,+ marked `unsure`; nothing reads it but a report (`words` leaves it out)."""+ first = wordsmod.load(self.path)+ quiet = self._quiet_for(first)+ spans = wordsmod.doubtful_spans(wordsmod.timed(first, quiet), quiet, self.info.frames / self.info.rate)+ words = wordsmod.merge(first, wordsmod.relisten(self.path, spans), self.envelope) if spans else first+ self.second_listen = spans+ return wordsmod.apply_fixes(words, self.fix)++ @cached_property+ def unsure(self) -> list[wordsmod.Word]:+ """The words heard but not used, each with why (`Word.unsure`): never shown or cut on."""+ return [w for w in self.heard if w.unsure]++ @cached_property+ def quiet(self) -> list[tuple[float, float]]:+ """Stretches where nobody is speaking, from the sound. An unsure word never keeps a+ stretch from counting as quiet."""+ return self._quiet_for(wordsmod.sure(self.heard))++ @cached_property+ def words(self) -> list[wordsmod.Word]:+ """The words as effects use them: the sure ones, corrected for the transcriber's lateness+ and checked against the sound (`words.timed`)."""+ return wordsmod.timed(self.heard, self.quiet)++ # ---- picture ----+ @cached_property+ def face(self) -> facemod.FaceTrack:+ return facemod.track(self.info)++ def person(self, model: str = personmod.MODEL) -> personmod.PersonMasks:+ return personmod.masks(self.info, model)diff --git a/edit/askeditor/fx/core/compose.py b/edit/askeditor/fx/core/compose.pynew file mode 100644index 0000000..5849ca5--- /dev/null+++ b/edit/askeditor/fx/core/compose.py@@ -0,0 +1,186 @@+"""Laying small images over frames, and laying a whole layer behind the person.++A `Sprite` is a small premultiplied RGBA image. Effects build their sprites once (a word, a box, a+card) and lay them on each frame with `over()`, so nothing is drawn again per frame.++Something that takes its look from what is behind it (frosted glass) is drawn behind the person+another way: on the picture `without_person()`, then laid back with `behind()`.+"""++from __future__ import annotations++from dataclasses import dataclass++import numpy as np+++@dataclass+class Sprite:+ rgb: np.ndarray # float32 (h, w, 3), 0..255, already multiplied by alpha+ a: np.ndarray # float32 (h, w), 0..1++ @property+ def w(self) -> int:+ return int(self.a.shape[1])++ @property+ def h(self) -> int:+ return int(self.a.shape[0])++ @staticmethod+ def from_rgba(rgba: np.ndarray) -> "Sprite":+ rgba = np.asarray(rgba)+ a = rgba[..., 3].astype(np.float32) / 255.0+ rgb = rgba[..., :3].astype(np.float32) * a[..., None]+ return Sprite(rgb=rgb, a=a)++ def scaled(self, s: float) -> "Sprite":+ """The sprite scaled by `s` (about its centre when laid with `over(..., centre=True)`)."""+ if abs(s - 1.0) < 1e-3:+ return self+ import cv2++ w, h = max(1, int(round(self.w * s))), max(1, int(round(self.h * s)))+ interp = cv2.INTER_AREA if s < 1 else cv2.INTER_LINEAR+ return Sprite(rgb=cv2.resize(self.rgb, (w, h), interpolation=interp),+ a=cv2.resize(self.a, (w, h), interpolation=interp))+++def rotated(sprite: Sprite, degrees: float) -> tuple[Sprite, float, float]:+ """`sprite` turned by `degrees` (positive turns it anticlockwise, as a protractor reads) about its+ centre, on a canvas grown to hold all of it, and how far that canvas's top-left moved: lay the+ result at (x - dx, y - dy) to keep the centre where the unturned sprite's was. Turned once, when+ a look is built, never per frame."""+ if abs(degrees) < 1e-3:+ return sprite, 0.0, 0.0+ import cv2++ h, w = sprite.h, sprite.w+ m = cv2.getRotationMatrix2D((w / 2, h / 2), degrees, 1.0)+ c, s = abs(m[0, 0]), abs(m[0, 1])+ W, H = int(np.ceil(w * c + h * s)) + 2, int(np.ceil(w * s + h * c)) + 2+ m[0, 2] += W / 2 - w / 2+ m[1, 2] += H / 2 - h / 2+ rgb = cv2.warpAffine(sprite.rgb, m, (W, H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=0)+ a = cv2.warpAffine(sprite.a, m, (W, H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=0)+ return Sprite(rgb=rgb.astype(np.float32), a=np.clip(a, 0, 1).astype(np.float32)), (W - w) / 2, (H - h) / 2+++def over(frame: np.ndarray, sprite: Sprite, x: float, y: float, opacity: float = 1.0) -> None:+ """Lay `sprite` on `frame` (uint8 RGB, changed in place) with its top-left at (x, y)."""+ if opacity <= 0.0:+ return+ H, W = frame.shape[:2]+ x0, y0 = int(round(x)), int(round(y))+ x1, y1 = x0 + sprite.w, y0 + sprite.h+ cx0, cy0, cx1, cy1 = max(0, x0), max(0, y0), min(W, x1), min(H, y1)+ if cx1 <= cx0 or cy1 <= cy0:+ return+ sx0, sy0 = cx0 - x0, cy0 - y0+ sx1, sy1 = sx0 + (cx1 - cx0), sy0 + (cy1 - cy0)+ a = sprite.a[sy0:sy1, sx0:sx1]+ rgb = sprite.rgb[sy0:sy1, sx0:sx1]+ if opacity < 1.0:+ a = a * opacity+ rgb = rgb * opacity+ region = frame[cy0:cy1, cx0:cx1].astype(np.float32)+ region *= 1.0 - a[..., None]+ region += rgb+ frame[cy0:cy1, cx0:cx1] = np.clip(region + 0.5, 0, 255).astype(np.uint8)+++def over_centred(frame: np.ndarray, sprite: Sprite, cx: float, cy: float, scale: float = 1.0,+ opacity: float = 1.0) -> None:+ """Lay `sprite` with its centre at (cx, cy), scaled about that centre."""+ s = sprite.scaled(scale)+ over(frame, s, cx - s.w / 2, cy - s.h / 2, opacity)+++def behind_person(frame: np.ndarray, layer_rgb: np.ndarray, layer_a: np.ndarray, person_a: np.ndarray) -> np.ndarray:+ """A full-frame layer laid behind the person: it covers the background and the person stays+ on top. `layer_rgb` is premultiplied (float32 0..255), `layer_a` and `person_a` are 0..1."""+ keep = person_a[..., None]+ a = layer_a[..., None] * (1.0 - keep)+ out = frame.astype(np.float32) * (1.0 - a) + layer_rgb * (1.0 - keep)+ return np.clip(out + 0.5, 0, 255).astype(np.uint8)+++def _smoothstep(x: np.ndarray) -> np.ndarray:+ x = np.clip(x, 0.0, 1.0)+ return x * x * (3.0 - 2.0 * x)+++def _fill_from(img: np.ndarray, known: np.ndarray) -> np.ndarray:+ """`img` (float32, h x w x 3) with every pixel that is not `known` (0..1) filled from the known+ pixels round it: each level of a pyramid, half the size of the one above, fills that one's holes,+ so a small gap takes its colour from close by and a large one from further out."""+ import cv2++ h, w = known.shape+ if known.min() >= 0.999:+ return img+ if h <= 3 or w <= 3:+ total = float(known.sum())+ mean = (img * known[..., None]).reshape(-1, 3).sum(axis=0) / total if total > 1e-6 else np.full(3, 128.0)+ return img * known[..., None] + mean.astype(np.float32) * (1.0 - known[..., None])+ half = (max(1, w // 2), max(1, h // 2))+ k_small = cv2.resize(known, half, interpolation=cv2.INTER_AREA)+ i_small = cv2.resize(img * known[..., None], half, interpolation=cv2.INTER_AREA)+ i_small = i_small / np.maximum(k_small, 1e-6)[..., None]+ # a coarse pixel with some of the known picture in it counts as known one level down+ filled = _fill_from(i_small.astype(np.float32), np.clip(k_small * 4.0, 0.0, 1.0).astype(np.float32))+ up = cv2.resize(filled, (w, h), interpolation=cv2.INTER_LINEAR)+ return img * known[..., None] + up * (1.0 - known[..., None])+++def without_person(frame: np.ndarray, person_a: np.ndarray, sure: float = 0.04) -> np.ndarray:+ """The picture with the person taken out: what is behind them continued in from the wall round+ them, and every pixel of plain wall (`person_a` at most `sure`) left exactly as it was. float32+ RGB, the frame's size. On the person's edge a pixel is part person and part wall; it leans to+ the wall the more of it is the person, as `behind()` expects.++ What it is for: something drawn behind the person that takes its look from what is behind it (a+ pane of glass blurs the room through it) must be drawn on this, or the person's own hair and+ shoulders show through it as a dark smear round them."""+ import cv2++ picture = frame.astype(np.float32)+ h, w = person_a.shape+ known = (person_a <= sure).astype(np.float32)+ # the fill is only ever seen blurred, or under the person's soft edge: a quarter size is plenty+ q = (max(1, w // 4), max(1, h // 4))+ small = cv2.resize(picture * known[..., None], q, interpolation=cv2.INTER_AREA)+ k_small = cv2.resize(known, q, interpolation=cv2.INTER_AREA)+ small = small / np.maximum(k_small, 1e-6)[..., None]+ wall = _fill_from(small.astype(np.float32), np.clip(k_small * 2.0, 0.0, 1.0).astype(np.float32))+ wall = cv2.resize(wall, (w, h), interpolation=cv2.INTER_LINEAR)+ lean = _smoothstep((person_a - sure) / 0.5)[..., None]+ return picture * (1.0 - lean) + wall * lean+++def behind(frame: np.ndarray, drawn: np.ndarray, clean: np.ndarray, person_a: np.ndarray) -> np.ndarray:+ """What was drawn on `clean` (the frame `without_person`, float32) laid behind the person: `drawn`+ is `clean` with things drawn on it, and only the wall's share of each pixel takes the change, so+ the person stays in front and where nothing was drawn the frame comes back exactly. uint8."""+ out = frame.astype(np.float32) + (1.0 - person_a[..., None]) * (drawn.astype(np.float32) - clean)+ return np.clip(out + 0.5, 0, 255).astype(np.uint8)+++def blank_layer(width: int, height: int) -> tuple[np.ndarray, np.ndarray]:+ """An empty full-frame layer to lay sprites on before putting it behind the person."""+ return np.zeros((height, width, 3), np.float32), np.zeros((height, width), np.float32)+++def onto_layer(layer: tuple[np.ndarray, np.ndarray], sprite: Sprite, x: float, y: float, opacity: float = 1.0) -> None:+ """Lay a sprite onto a full-frame layer (premultiplied 'over' in float)."""+ rgb, a = layer+ H, W = a.shape+ x0, y0 = int(round(x)), int(round(y))+ cx0, cy0, cx1, cy1 = max(0, x0), max(0, y0), min(W, x0 + sprite.w), min(H, y0 + sprite.h)+ if cx1 <= cx0 or cy1 <= cy0:+ return+ sx0, sy0 = cx0 - x0, cy0 - y0+ sa = sprite.a[sy0:sy0 + cy1 - cy0, sx0:sx0 + cx1 - cx0] * opacity+ srgb = sprite.rgb[sy0:sy0 + cy1 - cy0, sx0:sx0 + cx1 - cx0] * opacity+ rgb[cy0:cy1, cx0:cx1] = rgb[cy0:cy1, cx0:cx1] * (1.0 - sa[..., None]) + srgb+ a[cy0:cy1, cx0:cx1] = a[cy0:cy1, cx0:cx1] * (1.0 - sa) + sadiff --git a/edit/askeditor/fx/core/contrasts.py b/edit/askeditor/fx/core/contrasts.pynew file mode 100644index 0000000..7951ca2--- /dev/null+++ b/edit/askeditor/fx/core/contrasts.py@@ -0,0 +1,234 @@+"""Contrasts said aloud: the two sides of a comparison, and the if/then of a rule, found in the words.++ grids = contrasts.find(clip.words, clip.quiet) # every comparison heard, the fullest first++Three ways people say them, each read the same way, a clause at a time:++- **This versus that.** "Editing by hand versus editing with a tool", "phone compared to camera": the+ words before the marker, back to the start of their clause, and the words after it, up to the end+ of theirs. Each side lands on its own first word. Said once, it makes the two heads of a grid.+- **If, then.** "If your hook is slow, cut the first second", "When it's quiet, then add music", and+ the question form "Want something more editorial? Then just ask for it.": the condition is the+ clause after "if" (or the question), the result the clause after "then" or after the comma. Rules+ said one after another (no more than `RUN_GAP` apart) are rows of one grid.+- **Before, after.** "Before, I edited for hours. Now, it takes minutes.": a clause opened by+ "before," and the next opened by "now," "after," or "today,". Each pair is a row.++What is never a cell: a side with no word that says anything (`moments.NOT_KEY` alone: "this versus+that"), more than `MOST_WORDS` words, a word the speaker took back (`moments.taken_back`), or a word+the transcriber was unsure of (`Clip.words` leaves those out already). An "if" that does not open a+clause ("see if", "as if", "even if" inside a sentence) is not a rule.++Nothing here draws or decides a layout; `comparison-grid` does.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Optional, Sequence++from . import moments+from .words import HESITATIONS, Word, pause_after++MOST_WORDS = 6 # the most words a cell holds as said (a cell is a few words, never a sentence)+REACH = 9 # how far a clause is read for its comma or its "then"+RUN_GAP = 25.0 # seconds between two rules of one grid, at most++_VERSUS = {"versus", "vs"}+_COMPARED = ("compared", ("to", "with"))+_CONDITIONS = {"if", "when", "whenever", "once"}+_OPENS = {"and", "so", "but", "because", "now", "okay", "ok", "well", "then", "also", "plus", "or"}+_NOW = {"now", "after", "afterwards", "today", "these"}+# Words a side stops at, reading away from its marker: they belong to the clause around it.+_STOP_LEFT = {"is", "are", "was", "were", "it's", "that's", "and", "but", "so", "because", "or", "of", "between",+ "about", "like", "i", "we", "you", "they", "think", "say", "said", "comes", "come", "choose", "pick"}+_STOP_RIGHT = {"is", "are", "was", "were", "and", "but", "so", "because", "which", "where", "when", "will", "would",+ "can", "could", "for", "in", "on", "at"}+_LEAD_WORDS = {"just", "like", "um", "uh", "so", "and"}+++@dataclass+class Cell:+ text: str # as a cell shows it: the words said, no punctuation at the edges, a capital first+ at: float # when it lands: the start of its first word+ words: tuple[int, int] # its first and last word+++@dataclass+class Grid:+ kind: str # "versus", "if-then" or "before-after"+ heads: tuple[str, str] # the two column heads: the two sides of a versus, or "If" / "Then"+ head_cells: Optional[tuple[Cell, Cell]] = None # a versus' heads are said, and land on their words+ rows: list[tuple[Cell, Cell]] = field(default_factory=list)+ phrase: str = "" # what was said, for a person reading the plan++ @property+ def start(self) -> float:+ cells = list(self.head_cells or ()) + [c for r in self.rows for c in r]+ return min(c.at for c in cells)+++def _clean(words: Sequence[Word], a: int, b: int) -> str:+ out = " ".join(words[i].clean.strip() for i in range(a, b + 1) if words[i].key not in HESITATIONS)+ out = out.strip().strip(",.;:!?\"“”'’")+ return out[:1].upper() + out[1:]+++def _says_something(words: Sequence[Word], a: int, b: int) -> bool:+ return any(words[i].key and words[i].key not in moments.NOT_KEY for i in range(a, b + 1))+++def _trim(words: Sequence[Word], a: int, b: int) -> tuple[int, int]:+ """Lead-in words off the front ("the", "just", "um") and a dangling one off the end."""+ while a < b and words[a].key in _LEAD_WORDS:+ a += 1+ while b > a and (words[b].key in moments.LEADS_ON or words[b].key in HESITATIONS):+ b -= 1+ return a, b+++def _ok(words, a, b, back) -> bool:+ return (0 <= a <= b and b - a + 1 <= MOST_WORDS and _says_something(words, a, b)+ and not back.holds(list(words), a, b))+++def _opens_clause(words: Sequence[Word], i: int, quiet) -> bool:+ if i == 0:+ return True+ prev = words[i - 1]+ return prev.ends_clause or prev.key in _OPENS or (quiet is not None and pause_after(list(words), i - 1, quiet) >= 0.3)+++def _clause_end(words: Sequence[Word], a: int, limit: int = REACH) -> int:+ b = a+ while b < len(words) - 1 and b - a < limit and not words[b].ends_clause and words[b + 1].key != "then":+ b += 1+ return b+++def _versus(words, quiet, back) -> list[Grid]:+ out = []+ for i, w in enumerate(words):+ k = w.key+ skip = 1+ if k in _VERSUS:+ pass+ elif k == _COMPARED[0] and i + 1 < len(words) and words[i + 1].key in _COMPARED[1]:+ skip = 2+ else:+ continue+ # the left side: back to the start of its clause+ a = i - 1+ while a > 0 and i - a < MOST_WORDS and not words[a - 1].ends_clause and words[a - 1].key not in _STOP_LEFT:+ a -= 1+ if a < 0 or words[i - 1].ends_sentence:+ continue+ la, lb = _trim(words, a, i - 1)+ # the right side: up to the end of its clause+ c = i + skip+ if c >= len(words):+ continue+ d = c+ while d < len(words) - 1 and d - c + 1 < MOST_WORDS and not words[d].ends_clause \+ and words[d + 1].key not in _STOP_RIGHT:+ d += 1+ ra, rb = _trim(words, c, d)+ if not (_ok(words, la, lb, back) and _ok(words, ra, rb, back)):+ continue+ left = Cell(_clean(words, la, lb), words[la].start, (la, lb))+ right = Cell(_clean(words, ra, rb), words[ra].start, (ra, rb))+ out.append(Grid("versus", (left.text, right.text), (left, right),+ phrase=" ".join(x.text for x in words[la:rb + 1])))+ return out+++def _rules(words, quiet, back) -> list[tuple[Cell, Cell, str]]:+ rules = []+ n = len(words)+ i = 0+ while i < n:+ w = words[i]+ cond = None+ if w.key in _CONDITIONS and _opens_clause(words, i, quiet) and i + 1 < n:+ a = i + 1+ b = _clause_end(words, a)+ if b + 1 < n and (words[b].ends_clause and not words[b].ends_sentence or words[b + 1].key == "then"):+ cond = (a, b)+ elif w.text.rstrip().endswith("?") and i + 1 < n and words[i + 1].key == "then":+ # "Want something more editorial? Then just ask for it."+ a = i+ while a > 0 and i - a < REACH and not words[a - 1].ends_sentence:+ a -= 1+ cond = (a, i)+ b = i+ if cond is None:+ i += 1+ continue+ a, b = cond+ r0 = b + 1+ if r0 < n and words[r0].key == "then":+ r0 += 1+ if r0 >= n:+ break+ r1 = _clause_end(words, r0)+ ca, cb = _trim(words, a, b)+ ra, rb = _trim(words, r0, r1)+ if _ok(words, ca, cb, back) and _ok(words, ra, rb, back):+ rules.append((Cell(_clean(words, ca, cb), words[ca].start, (ca, cb)),+ Cell(_clean(words, ra, rb), words[ra].start, (ra, rb)),+ " ".join(x.text for x in words[a:r1 + 1])))+ i = r1 + 1+ continue+ i += 1+ return rules+++def _then_and_now(words, quiet, back) -> list[tuple[Cell, Cell, str]]:+ pairs = []+ n = len(words)+ for i, w in enumerate(words):+ if w.key != "before" or not w.ends_clause or w.ends_sentence or not _opens_clause(words, i, quiet):+ continue+ a = i + 1+ b = _clause_end(words, a)+ for j in range(b + 1, min(n, b + 40)):+ if words[j].key in _NOW and words[j].ends_clause and not words[j].ends_sentence \+ and _opens_clause(words, j, quiet) and words[j].start - words[i].start <= RUN_GAP:+ c = j + 1+ if c >= n:+ break+ d = _clause_end(words, c)+ ba, bb = _trim(words, a, b)+ na, nb = _trim(words, c, d)+ if _ok(words, ba, bb, back) and _ok(words, na, nb, back):+ pairs.append((Cell(_clean(words, ba, bb), words[ba].start, (ba, bb)),+ Cell(_clean(words, na, nb), words[na].start, (na, nb)),+ " ".join(x.text for x in words[i:d + 1])))+ break+ return pairs+++def _runs(rows: list[tuple[Cell, Cell, str]]) -> list[list[tuple[Cell, Cell, str]]]:+ out: list = []+ for r in rows:+ if out and r[0].at - out[-1][-1][1].at <= RUN_GAP:+ out[-1].append(r)+ else:+ out.append([r])+ return out+++def find(words: Sequence[Word], quiet=None, back: Optional[moments.TakenBack] = None) -> list[Grid]:+ """Every comparison heard in `words` (a clip's whole words), as grids: a versus said with its two+ sides, a run of if/then rules, a run of before/after pairs. The fullest grid first, then the+ earliest."""+ words = list(words)+ back = moments.taken_back(words, quiet or []) if back is None else back+ grids = _versus(words, quiet, back)+ for run in _runs(_rules(words, quiet, back)):+ grids.append(Grid("if-then", ("If", "Then"), None, [(c, r) for c, r, _ in run],+ phrase=" … ".join(p for _, _, p in run)))+ for run in _runs(_then_and_now(words, quiet, back)):+ grids.append(Grid("before-after", ("Before", "Now"), None, [(c, r) for c, r, _ in run],+ phrase=" … ".join(p for _, _, p in run)))+ return sorted(grids, key=lambda g: (-(len(g.rows) + (1 if g.head_cells else 0)), g.start))diff --git a/edit/askeditor/fx/core/counting.py b/edit/askeditor/fx/core/counting.pynew file mode 100644index 0000000..3386643--- /dev/null+++ b/edit/askeditor/fx/core/counting.py@@ -0,0 +1,241 @@+"""A number that counts: its figures drawn so they can change on every frame, when each figure said+begins, and the soft ticks laid under a count. Shared by `chart` and `number-counter`.++ figs = counting.Figures(px, s) # the figures, set once at a size+ figs.draw(frame, ("$", "197", "K", ""), x, baseline, alpha)+ heard, corrected = counting.first_listen(clip) # the transcriber's own words, and their true starts+ at = counting.start_of(amount, heard, corrected) # when the voice begins on an amount+ ticks = counting.tick_times(segments, ease, start, end)+ sound, under = counting.mix_ticks(sound, rate, ticks)++**The figures** are drawn from single characters, so a count changes them on every frame without+setting the number again: each figure in a cell of one width (so the count does not wobble), the+sign before and the scale and unit after smaller.++**When a figure is said** is read from the transcriber's first listen, not from the words a second+listen changed: a figure read aloud takes far longer than its few characters suggest ("197" is "one+hundred and ninety-seven"), so a second listen can take it for a stretched word and bring it back+wrong ("19.5%" as "19 17 .5"). Its start is the core's corrected one (the transcriber marks a word+late; the core pulls it back and checks it against the sound).++**The ticks** run under the count, spaced by how fast it moves (they bunch while it runs and slow+as it settles), with a rounder one where it lands. Each is set by how loud it is heard over 30 ms,+as the voice's loud syllables are measured, never by its peak: a click's peak says little about how+loud it sounds. Every sound here is made in code, the same every time.+"""++from __future__ import annotations++import math+from typing import Callable, Optional, Sequence++import numpy as np++from . import text as textmod+from . import words as wordsmod+from .compose import over+from .words import unheard++FACE = "poppins-bold"+SMALL = 0.6 # the sign, the scale letter and the unit, beside the figures+WHITE = (255, 255, 255)+UNDER = 20.0 # dB: how far under the voice's loud syllables a tick is heard+++# ---- the figures -----------------------------------------------------------------------------------++class Figures:+ """The big number drawn from single characters, so it can count on every frame without being+ set again: figures at full size, each in a cell of one width (so the count does not wobble), the+ sign before it and the scale and unit after it smaller."""++ def __init__(self, px: int, s: float, face: str = FACE, fill=WHITE, small: float = SMALL):+ self.px = px+ self.face = face+ self.fill = tuple(fill)+ self.small_px = max(8, int(round(px * small)))+ self.shadow = (0.0, 2.2 * s, 5.0 * s, 0.38)+ self.cap = textmod.cap_height(face, px)+ self.small_cap = textmod.cap_height(face, self.small_px)+ # every figure but 1 in a cell of one width, so the count does not wobble; 1 is narrow in+ # this face, and in a full cell it would stand apart from its neighbours ("1 97K")+ widths = [textmod.advance(c, face, px) for c in "023456789"]+ self.cell = sum(widths) / len(widths)+ self.cell_one = textmod.advance("1", face, px) + 0.06 * px+ self._glyphs: dict[tuple[str, bool], textmod.Word] = {}+ self._cache: dict[str, tuple[list, float]] = {}++ def glyph(self, ch: str, small: bool = False) -> textmod.Word:+ """One character, drawn once and kept: at full size, or `small` (the sign, the scale, the unit)."""+ return self._glyph(ch, small)++ def _glyph(self, ch: str, small: bool) -> textmod.Word:+ # every character is drawn through here (glass-widgets re-inks the figures by replacing it)+ key = (ch, small)+ if key not in self._glyphs:+ self._glyphs[key] = textmod.draw_word(ch, self.face, self.small_px if small else self.px, fill=self.fill,+ shadow=self.shadow)+ return self._glyphs[key]++ def layout(self, parts: tuple[str, str, str, str]) -> tuple[list, float]:+ """Where each character of (sign, figures, scale, unit) goes: [(glyph, x, raise)] and the width."""+ key = "\x00".join(parts)+ if key in self._cache:+ return self._cache[key]+ pre, digits, scale, suf = parts+ items, x = [], 0.0+ lift = self.cap - self.small_cap # a sign before the figures sits up, its top level with theirs+ for ch in pre:+ if ch == "-":+ g = self._glyph(ch, False)+ items.append((g, x, 0.0))+ x += g.width+ else:+ g = self._glyph(ch, True)+ items.append((g, x, lift))+ x += g.width + 0.04 * self.px+ for ch in digits:+ g = self._glyph(ch, False)+ if ch.isdigit():+ cell = self.cell_one if ch == "1" else self.cell+ items.append((g, x + (cell - g.width) / 2, 0.0))+ x += cell+ else:+ items.append((g, x, 0.0))+ x += g.width+ tail = scale + suf+ if tail:+ x += 0.01 * self.px+ for ch in tail:+ g = self._glyph(ch, True)+ items.append((g, x, 0.0))+ x += g.width+ self._cache[key] = (items, x)+ return items, x++ def width(self, parts) -> float:+ return self.layout(parts)[1]++ def draw(self, frame, parts, x: float, baseline: float, alpha: float) -> None:+ items, _ = self.layout(parts)+ for g, dx, up in items:+ over(frame, g.sprite, x + dx - g.ox, baseline - up - g.oy, alpha)+++# ---- when a figure is said ---------------------------------------------------------------------------++def first_listen(clip) -> tuple[list, dict[int, float]]:+ """The transcriber's own words (with the corrections given), and for each, where the voice+ begins on it once the core has corrected its timing. Amounts are read from these (see above)."""+ first = wordsmod.apply_fixes(wordsmod.load(clip.path), clip.fix)+ quiet = clip.quiet+ kept = [i for i, w in enumerate(first) if w.key and not unheard(w, quiet)]+ timed = wordsmod.timed(first, quiet)+ return first, ({i: w.start for i, w in zip(kept, timed)} if len(kept) == len(timed) else {})+++def start_of(amount, heard, corrected: dict[int, float]) -> float:+ """When the voice begins on `amount` (an `amounts.Amount` read from `heard`): its first word's+ corrected start, else the transcriber's start pulled back by how late it marks a word."""+ for i in range(amount.first, amount.last + 1):+ if i in corrected:+ return corrected[i]+ return max(0.0, heard[amount.first].start - wordsmod.HEARD_LATE)+++# ---- the ticks ---------------------------------------------------------------------------------------++def tick(rate: int, rng: np.random.Generator, level: float) -> np.ndarray:+ """A small, rounded tick: a short knock of a tone with a breath of noise at its start."""+ n = int(0.018 * rate)+ t = np.arange(n) / rate+ body = np.sin(2 * np.pi * rng.uniform(1750, 2050) * t) * np.exp(-t / 0.0036)+ edge = rng.standard_normal(n) * np.exp(-t / 0.0006) * 0.22+ s = body + edge+ s *= np.minimum(1.0, t / 0.0004)+ return (s / max(1e-9, np.abs(s).max()) * level).astype(np.float32)+++def land(rate: int, rng: np.random.Generator, level: float) -> np.ndarray:+ """The tick the count settles on: rounder and a little longer."""+ n = int(0.06 * rate)+ t = np.arange(n) / rate+ s = (np.sin(2 * np.pi * 1560 * t) * np.exp(-t / 0.011) * 0.8+ + np.sin(2 * np.pi * 2340 * t) * np.exp(-t / 0.007) * 0.35+ + rng.standard_normal(n) * np.exp(-t / 0.0007) * 0.2)+ s *= np.minimum(1.0, t / 0.0006)+ return (s / max(1e-9, np.abs(s).max()) * level).astype(np.float32)+++def tick_times(segments: Sequence[tuple], ease: Callable[[float], float], start: float = -math.inf,+ end: float = math.inf) -> list[tuple[float, bool]]:+ """Each tick of the counts in `segments` ((from s, to s, from value, to value, …) each), as+ (seconds, is it the landing one): spaced by how fast `ease` moves the count, so they bunch while+ it runs and slow as it settles. Only the ticks from `start` to before `end` are kept."""+ out = []+ for seg in segments:+ a, b, v0, v1 = seg[0], seg[1], seg[2], seg[3]+ if b - a < 0.15 or abs(v1 - v0) < 1e-12:+ continue+ m = int(np.clip(round((b - a) * 15), 4, 16))+ qs = np.linspace(0, 1, 400)+ e = np.array([ease(q) for q in qs])+ for i in range(1, m):+ q = qs[int(np.searchsorted(e, i / m))] if i / m <= e[-1] else 1.0+ out.append((a + q * (b - a), False))+ out.append((b, True))+ return [(t, is_land) for t, is_land in out if start <= t < end]+++def voice_level(sound: np.ndarray, rate: int) -> float:+ """How loud the voice's loud syllables are (the 90th percentile of 30 ms windows above the room)."""+ mono = sound.mean(axis=1)+ win = int(0.03 * rate)+ n = len(mono) // win+ rms = np.sqrt((mono[:n * win].reshape(n, win) ** 2).mean(axis=1) + 1e-12) if n else np.array([1e-3])+ loud = rms[rms > 10 ** (-45 / 20)]+ return float(np.percentile(loud, 90)) if loud.size else 0.05+++def mix_under(sound: np.ndarray, rate: int, hits: Sequence[tuple[float, Callable, float]], under: float = UNDER,+ seed: int = 5) -> tuple[np.ndarray, Optional[float]]:+ """`sound` with a short sound laid at each of `hits` ((seconds, make, lift dB) each, where+ `make(rate, rng, level)` makes it), each heard `under - lift` dB under the voice, and how far+ under the voice the loudest of them sit (dB, negative), measured as they are heard."""+ if not hits:+ return sound, None+ win = int(0.03 * rate)+ voice = voice_level(sound, rate)++ def heard(x: np.ndarray) -> float:+ return float(np.sqrt((x[:win] ** 2).sum() / win))++ gains: dict[tuple[Callable, float], float] = {}+ rng = np.random.default_rng(seed)+ out = sound.copy()+ added = np.zeros(len(sound), np.float32)+ for t, make, lift in hits:+ key = (make, lift)+ if key not in gains:+ gains[key] = voice * 10 ** (-(under - lift) / 20) / max(1e-9, heard(make(rate, np.random.default_rng(0), 1.0)))+ s = make(rate, rng, gains[key])+ if s.ndim > 1:+ s = s.mean(axis=1)+ i = int(round(t * rate))+ if i >= len(out):+ continue+ k = min(len(s), len(out) - i)+ added[i:i + k] += s[:k]+ out += added[:, None]+ m = len(added) // win+ hit_rms = np.sqrt((added[:m * win].reshape(m, win) ** 2).mean(axis=1) + 1e-12) if m else np.array([0.0])+ busy = hit_rms[hit_rms > 1e-6]+ db = 20 * math.log10(max(1e-9, float(np.percentile(busy, 90)) if busy.size else 1e-9) / max(1e-9, voice))+ return np.clip(out, -1.0, 1.0), db+++def mix_ticks(sound: np.ndarray, rate: int, ticks: Sequence[tuple[float, bool]], under: float = UNDER+ ) -> tuple[np.ndarray, Optional[float]]:+ """`sound` with a tick at each of `ticks` (from `tick_times`), the landing ones rounder and 2 dB+ nearer the voice; and how far under the voice they sit (dB, negative)."""+ return mix_under(sound, rate, [(t, land, 2.0) if is_land else (t, tick, 0.0) for t, is_land in ticks], under)diff --git a/edit/askeditor/fx/core/depth.py b/edit/askeditor/fx/core/depth.pynew file mode 100644index 0000000..7931e2a--- /dev/null+++ b/edit/askeditor/fx/core/depth.py@@ -0,0 +1,164 @@+"""Pictures laid in depth in the room behind the person: cards that sit at a distance, turn, cast a+soft shadow on the wall and move a little with the camera.++What is here was first built for `backdrop`'s screens and is shared so every effect that lays+pictures in the room draws them the same way:++- `Card`: a rectangle in the room (its middle, size, turn about its upright axis, roll in its own+ plane, and depth), and `Card.corners()`: where its four corners fall on the screen, in+ perspective.+- `draw_card()`: a picture laid into such a quad on a canvas, with its soft shadow put into a+ shade map below it, or (`darken`) cast at once on what is already drawn, so a card on a pile+ shades the cards under it and never itself.+- `rounded_alpha()`: a rounded rectangle's alpha.+- `seen_share()`: how much of a box the person leaves in view over the clip, from a coverage map+ (the share of frames the person covers each spot).+- `head_path()`: per output frame, how far the head is from where it usually is, smoothed.+- `drift()`: the room's sideways and upward drift at a moment: a slow sway plus part of the head's+ own movement. A card at depth d moves by the drift divided by d (parallax).+"""++from __future__ import annotations++import math+from dataclasses import dataclass+from typing import Optional++import numpy as np++from .layout import Rect # noqa: F401 (head_path takes the usual head as a Rect)+++def seen_share(coverage: Optional[np.ndarray], box: tuple[float, float, float, float], size: tuple[int, int]) -> float:+ """How much of `box` (x0, y0, x1, y1, output pixels) the person leaves in view over the clip,+ from the coverage map (the share of frames the person covers each spot), counting only the+ part inside the frame."""+ W, H = size+ x0, y0, x1, y1 = max(0.0, box[0]), max(0.0, box[1]), min(float(W), box[2]), min(float(H), box[3])+ if x1 <= x0 or y1 <= y0:+ return 0.0+ if coverage is None:+ return 1.0+ ch, cw = coverage.shape+ a, b = int(y0 * ch / H), max(int(y0 * ch / H) + 1, int(math.ceil(y1 * ch / H)))+ c, d = int(x0 * cw / W), max(int(x0 * cw / W) + 1, int(math.ceil(x1 * cw / W)))+ inside = (x1 - x0) * (y1 - y0) / max(1.0, (box[2] - box[0]) * (box[3] - box[1]))+ return float((1.0 - coverage[a:b, c:d].mean()) * inside)++++def rounded_alpha(w: int, h: int, radius: float) -> np.ndarray:+ """A rounded rectangle's alpha (0..1), smooth at the corners."""+ from PIL import Image, ImageDraw++ k = 4+ img = Image.new("L", (w * k, h * k), 0)+ ImageDraw.Draw(img).rounded_rectangle((0, 0, w * k - 1, h * k - 1), radius=max(0.0, radius * k), fill=255)+ return np.asarray(img.resize((w, h), Image.LANCZOS), np.float32) / 255.0++++@dataclass+class Card:+ """A rectangle laid in the room: where it sits, its tilt and depth, and its picture."""+ cx: float+ cy: float+ w: float+ h: float+ tilt: float = 0.0 # degrees about its upright axis (the far side turned away)+ roll: float = 0.0 # degrees in the picture's plane+ depth: float = 1.0 # 1 is nearest; larger moves less with the camera+ radius: float = 0.02 # corner radius as a share of its width++ def corners(self, scale: float = 1.0, dx: float = 0.0, dy: float = 0.0, focal: float = 2000.0) -> np.ndarray:+ """Its four corners on the screen (top-left, top-right, bottom-right, bottom-left)."""+ w, h = self.w * scale / 2, self.h * scale / 2+ pts = np.array([[-w, -h], [w, -h], [w, h], [-w, h]], np.float32)+ a = math.radians(self.tilt)+ x3, z3 = pts[:, 0] * math.cos(a), pts[:, 0] * math.sin(a)+ px = focal * x3 / (focal + z3)+ py = focal * pts[:, 1] / (focal + z3)+ r = math.radians(self.roll)+ rx = px * math.cos(r) - py * math.sin(r)+ ry = px * math.sin(r) + py * math.cos(r)+ return np.stack([rx + self.cx + dx, ry + self.cy + dy], axis=1).astype(np.float32)+++def draw_card(canvas: np.ndarray, shade: np.ndarray, img: np.ndarray, alpha: np.ndarray, quad: np.ndarray,+ opacity: float = 1.0, shadow: float = 0.45, shadow_px: float = 18.0, dim: float = 0.0,+ darken: float = 0.0) -> None:+ """Lay `img` (with its rounded `alpha`) onto `canvas` (float32, changed in place) inside `quad`,+ and its soft shadow into `shade` (0..1, deepened in place) below it."""+ import cv2++ H, W = canvas.shape[:2]+ pad = int(3 * shadow_px) + 4+ x0, y0 = np.floor(quad.min(axis=0)).astype(int) - pad+ x1, y1 = np.ceil(quad.max(axis=0)).astype(int) + pad+ x0, y0, x1, y1 = max(0, x0), max(0, y0), min(W, x1), min(H, y1)+ if x1 <= x0 or y1 <= y0 or opacity <= 0.002:+ return+ ih, iw = img.shape[:2]+ src = np.array([[0, 0], [iw, 0], [iw, ih], [0, ih]], np.float32)+ M = cv2.getPerspectiveTransform(src, quad - np.array([x0, y0], np.float32))+ size = (x1 - x0, y1 - y0)+ col = cv2.warpPerspective(img, M, size, flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)+ a = cv2.warpPerspective(alpha, M, size, flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT) * opacity+ if shadow > 0: # soft, so it is worked out at a quarter size+ q = 4+ qs = (max(2, size[0] // q), max(2, size[1] // q))+ s = cv2.resize(a, qs, interpolation=cv2.INTER_AREA)+ s = cv2.warpAffine(s, np.float32([[1, 0, 0], [0, 1, shadow_px * 0.6 / q]]), qs,+ borderMode=cv2.BORDER_CONSTANT)+ s = cv2.GaussianBlur(s, (0, 0), max(0.8, shadow_px / q))+ s = cv2.resize(s, size, interpolation=cv2.INTER_LINEAR)+ if darken > 0: # the shadow falls now, on what is already drawn, and under this card only+ canvas[y0:y1, x0:x1] *= (1 - darken * shadow * s)[..., None]+ else:+ shade[y0:y1, x0:x1] = 1 - (1 - shade[y0:y1, x0:x1]) * (1 - shadow * s)+ region = canvas[y0:y1, x0:x1]+ region *= 1 - a[..., None]+ c = col.astype(np.float32)+ if dim > 0:+ c *= 1 - dim+ region += c * a[..., None]++++def head_path(clip, framing, n_out: int, fps: float, head: Optional[Rect]) -> Optional[np.ndarray]:+ """Per output frame, how far the head is from where it usually is (output pixels), smoothed:+ what the screens' parallax follows."""+ if head is None or not clip.face.any():+ return None+ pts = []+ for j in range(n_out):+ k = min(clip.info.frames - 1, j)+ b = clip.face.box(k)+ if b is None:+ pts.append((0.0, 0.0))+ continue+ r = framing.to_output(b, k)+ pts.append((r.cx - head.cx, r.cy - (head.y0 + head.y1) / 2))+ p = np.array(pts, np.float64)+ sigma = 0.35 * fps+ rad = max(1, int(3 * sigma))+ kern = np.exp(-0.5 * (np.arange(-rad, rad + 1) / sigma) ** 2)+ kern /= kern.sum()+ for c in (0, 1):+ p[:, c] = np.convolve(np.pad(p[:, c], rad, mode="edge"), kern, mode="valid")+ return p++++def drift(t: float, size: tuple[int, int], head: Optional[np.ndarray], fps: float) -> tuple[float, float]:+ """The room's sideways and upward drift at t (output pixels): a slow sway, plus a part of the+ head's own movement (`head` is `head_path()`, or None), so cards move a little as a real room+ would behind someone filmed by hand."""+ W, H = size+ dx = 0.010 * W * math.sin(2 * math.pi * t / 9.0)+ dy = 0.004 * H * math.sin(2 * math.pi * t / 7.0 + 1.0)+ if head is not None and len(head):+ j = int(np.clip(round(t * fps), 0, len(head) - 1))+ dx += 0.22 * float(head[j, 0])+ dy += 0.12 * float(head[j, 1])+ return dx, dydiff --git a/edit/askeditor/fx/core/face.py b/edit/askeditor/fx/core/face.pynew file mode 100644index 0000000..5b0e5be--- /dev/null+++ b/edit/askeditor/fx/core/face.py@@ -0,0 +1,283 @@+"""A face box for every frame, smoothed, cached next to the clip as `<clip>.face.json`.++The detector's box is tight: brows to mouth, cheek to cheek. Text has to keep clear of the whole+head, so `head()` grows it to take in the hair or a cap above, the chin and beard below, and the+ears at the sides. Effects place text against `heads(first, last)`: the union of the head over+every frame the text is on screen, from the raw detections and the smoothed track together, so a+quick movement never brings the face under the words.+"""++from __future__ import annotations++import contextlib+import json+import os+import time+from dataclasses import dataclass+from pathlib import Path+from typing import Optional++import numpy as np++from . import paths+from .layout import Rect+from .video import FrameReader, VideoInfo++os.environ.setdefault("GLOG_minloglevel", "2")+os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "3")++CACHE_VERSION = 1+DETECT_WIDTH = 480+# How far the head reaches past the detector's box, as fractions of the box's own size. The box+# runs from the brows to about the chin; drawn on clips A, B and C (28 October 2026) the hair, a cap+# and braids reach up to 0.6 of its height above it, and a beard about 0.1 below it.+HEAD = {"left": 0.20, "top": 0.60, "right": 0.20, "bottom": 0.16}+++def quiet_native():+ """Silence the C++ start-up chatter of the vision library (it writes straight to stderr)."""+ try:+ saved = os.dup(2)+ except OSError:+ yield+ return+ devnull = os.open(os.devnull, os.O_WRONLY)+ try:+ os.dup2(devnull, 2)+ yield+ finally:+ os.dup2(saved, 2)+ os.close(devnull)+ os.close(saved)+++@dataclass+class FaceTrack:+ width: int+ height: int+ fps: float+ raw: np.ndarray # (n, 5): x, y, w, h, score, as detected; NaN where no face was found+ boxes: np.ndarray # (n, 4): x, y, w, h, smoothed and filled across gaps+ seconds: float = 0.0 # how long finding the faces took (0 when read from the cache)+ trusted: Optional[np.ndarray] = None # `raw` without the detections that leap away from the rest++ def __post_init__(self) -> None:+ if self.trusted is None:+ self.trusted = trust(self.raw, self.fps)++ @property+ def n(self) -> int:+ return len(self.boxes)++ @property+ def found(self) -> np.ndarray:+ return ~np.isnan(self.trusted[:, 0])++ @property+ def found_share(self) -> float:+ return float(self.found.mean()) if self.n else 0.0++ def any(self) -> bool:+ return bool(self.found.any())++ def box(self, i: int) -> Optional[Rect]:+ if not self.any():+ return None+ x, y, w, h = self.boxes[int(np.clip(i, 0, self.n - 1))]+ return Rect(x, y, x + w, y + h)++ @staticmethod+ def _grow(r: Rect) -> Rect:+ return r.grow(HEAD["left"] * r.w, HEAD["top"] * r.h, HEAD["right"] * r.w, HEAD["bottom"] * r.h)++ def head(self, i: int) -> Optional[Rect]:+ b = self.box(i)+ if b is None:+ return None+ head = self._grow(b)+ x, y, w, h, _ = self.trusted[int(np.clip(i, 0, self.n - 1))]+ if not np.isnan(x):+ head = head.union(self._grow(Rect(x, y, x + w, y + h)))+ return head++ def heads(self, first: int, last: int) -> Optional[Rect]:+ """The head's box over frames first..last (inclusive): what text on screen then must avoid."""+ first, last = int(np.clip(first, 0, self.n - 1)), int(np.clip(last, 0, self.n - 1))+ return Rect.around(r for i in range(first, last + 1) if (r := self.head(i)) is not None)++ def center(self, i: int) -> Optional[tuple[float, float]]:+ b = self.box(i)+ return (b.cx, b.cy) if b else None++ def boxes_between(self, first: int, last: int) -> np.ndarray:+ """Smoothed boxes (x, y, w, h) for frames first..last-1, found from those frames' own+ detections only: across a cut in the clip, the face is not glided from one shot to the next.+ Rows of zeros where the stretch has no face at all."""+ raw = self.raw[first:last]+ trusted = trust(raw, self.fps)+ return _fill_and_smooth(trusted, self.fps)++ def to_json(self, signature: dict) -> dict:+ rows = [None if np.isnan(r[0]) else [round(float(v), 1) for v in r[:4]] + [round(float(r[4]), 3)]+ for r in self.raw]+ return {"version": CACHE_VERSION, "source": signature, "width": self.width, "height": self.height,+ "fps": self.fps, "frames": self.n, "boxes": rows}+++def _smooth(series: np.ndarray, sigma: float) -> np.ndarray:+ if sigma <= 0 or len(series) < 3:+ return series.copy()+ radius = int(3 * sigma)+ k = np.exp(-0.5 * (np.arange(-radius, radius + 1) / sigma) ** 2)+ k /= k.sum()+ padded = np.pad(series, (radius, radius), mode="edge")+ return np.convolve(padded, k, mode="valid")+++def trust(raw: np.ndarray, fps: float, window: float = 0.5, size_jump: float = 0.3, move: float = 0.45,+ min_score: float = 0.6) -> np.ndarray:+ """`raw` with the detections that cannot be the same face set to NaN.++ A finger over the lens or a blur of skin can make the detector report a "face" twice the size,+ somewhere else, for a frame or two (clip C, 9.2 s). Each detection is compared with the median+ of the detections within `window` seconds around it: one whose size differs by more than+ `size_jump`, or whose centre is more than `move` face-widths away, or whose score is under+ `min_score`, is dropped, and the track is bridged across it from the faces either side.+ """+ out = raw.copy()+ found = np.flatnonzero(~np.isnan(raw[:, 0]))+ if len(found) < 3:+ return out+ r = max(1, int(round(window * fps)))+ w = raw[:, 2]+ cx = raw[:, 0] + raw[:, 2] / 2+ cy = raw[:, 1] + raw[:, 3] / 2+ for i in found:+ near = found[(found >= i - r) & (found <= i + r)]+ mw, mx, my = np.median(w[near]), np.median(cx[near]), np.median(cy[near])+ if (raw[i, 4] < min_score or abs(w[i] - mw) > size_jump * mw+ or np.hypot(cx[i] - mx, cy[i] - my) > move * mw):+ out[i] = np.nan+ return out+++def _fill_and_smooth(raw: np.ndarray, fps: float, max_gap: float = 1.0, sigma_s: float = 0.08) -> np.ndarray:+ n = len(raw)+ found = ~np.isnan(raw[:, 0])+ boxes = np.zeros((n, 4), np.float64)+ if not found.any():+ return boxes+ idx = np.flatnonzero(found)+ cx = raw[:, 0] + raw[:, 2] / 2+ cy = raw[:, 1] + raw[:, 3] / 2+ series = [cx, cy, raw[:, 2], raw[:, 3]]+ frames = np.arange(n)+ out = []+ for s in series:+ filled = np.interp(frames, idx, s[idx]) # holds the nearest value past either end+ out.append(_smooth(filled, sigma_s * fps))+ cx, cy, w, h = out+ # Across a long gap the box holds still rather than gliding between far-apart detections.+ gap_start = None+ for i in range(n + 1):+ missing = i < n and not found[i]+ if missing and gap_start is None:+ gap_start = i+ elif not missing and gap_start is not None:+ if (i - gap_start) / fps > max_gap:+ before = gap_start - 1 if gap_start > 0 else i+ hold = before if before < n else gap_start+ for v in (cx, cy, w, h):+ v[gap_start:i] = v[hold]+ gap_start = None+ boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3] = cx - w / 2, cy - h / 2, w, h+ return boxes+++def _iou(a: np.ndarray, b: np.ndarray) -> float:+ ax1, ay1, bx1, by1 = a[0] + a[2], a[1] + a[3], b[0] + b[2], b[1] + b[3]+ iw = max(0.0, min(ax1, bx1) - max(a[0], b[0]))+ ih = max(0.0, min(ay1, by1) - max(a[1], b[1]))+ inter = iw * ih+ union = a[2] * a[3] + b[2] * b[3] - inter+ return inter / union if union > 0 else 0.0+++def detect(info: VideoInfo, min_score: float = 0.5) -> np.ndarray:+ """Runs the face model on every frame. Returns (n, 5) rows of x, y, w, h, score in the clip's+ own pixels, NaN where no face was found. The main face is the largest one, followed from frame+ to frame so a passer-by never takes its place."""+ from .models import vision_path++ with quiet_native():+ import mediapipe as mp+ from mediapipe.tasks import python as mp_tasks+ from mediapipe.tasks.python import vision++ dw = min(DETECT_WIDTH, info.width)+ dw -= dw % 2+ dh = int(round(info.height * dw / info.width / 2)) * 2+ scale = info.width / dw+ rows = []+ previous = None+ with quiet_native():+ options = vision.FaceDetectorOptions(+ base_options=mp_tasks.BaseOptions(model_asset_path=str(vision_path("face"))),+ running_mode=vision.RunningMode.VIDEO,+ min_detection_confidence=min_score,+ )+ with vision.FaceDetector.create_from_options(options) as detector:+ for i, frame in enumerate(FrameReader(info, size=(dw, dh))):+ image = mp.Image(image_format=mp.ImageFormat.SRGB, data=np.ascontiguousarray(frame))+ result = detector.detect_for_video(image, int(round(i * 1000 / info.rate)))+ cands = []+ for d in result.detections:+ b = d.bounding_box+ cands.append(np.array([b.origin_x * scale, b.origin_y * scale, b.width * scale,+ b.height * scale, d.categories[0].score if d.categories else 0.0]))+ choice = None+ if cands:+ largest = max(cands, key=lambda c: c[2] * c[3])+ choice = largest+ if previous is not None:+ linked = [c for c in cands if _iou(c, previous) > 0.3]+ if linked and _iou(largest, previous) < 0.1:+ choice = max(linked, key=lambda c: _iou(c, previous))+ if choice is None:+ rows.append([np.nan] * 5)+ else:+ rows.append(list(choice))+ previous = choice+ raw = np.array(rows, np.float64) if rows else np.zeros((0, 5))+ # The reader can come up a frame short or long of the estimate; line it up with the clip.+ if len(raw) < info.frames:+ pad = np.full((info.frames - len(raw), 5), np.nan)+ raw = np.vstack([raw, pad]) if len(raw) else pad+ return raw[: info.frames]+++def track(info: VideoInfo, refresh: bool = False) -> FaceTrack:+ """The clip's face track, from the cache beside the clip or found now."""+ cache = paths.beside(info.path, "face.json")+ signature = paths.source_signature(info.path)+ if not refresh and cache.exists():+ try:+ data = json.loads(cache.read_text(encoding="utf-8"))+ if (data.get("version") == CACHE_VERSION and data.get("source", {}).get("bytes") == signature["bytes"]+ and data.get("frames") == info.frames):+ raw = np.array([r if r else [np.nan] * 5 for r in data["boxes"]], np.float64)+ trusted = trust(raw, info.rate)+ return FaceTrack(info.width, info.height, info.rate, raw, _fill_and_smooth(trusted, info.rate),+ trusted=trusted)+ except (json.JSONDecodeError, KeyError, TypeError, ValueError):+ pass+ started = time.time()+ raw = detect(info)+ trusted = trust(raw, info.rate)+ t = FaceTrack(info.width, info.height, info.rate, raw, _fill_and_smooth(trusted, info.rate),+ seconds=time.time() - started, trusted=trusted)+ tmp = Path(str(cache) + ".part")+ tmp.write_text(json.dumps(t.to_json(signature), separators=(",", ":")) + "\n")+ tmp.replace(cache)+ return tdiff --git a/edit/askeditor/fx/core/framing.py b/edit/askeditor/fx/core/framing.pynew file mode 100644index 0000000..051775f--- /dev/null+++ b/edit/askeditor/fx/core/framing.py@@ -0,0 +1,507 @@+"""The output's shape and size, and a window into the clip that keeps the face in frame.++- The output is 1080 wide at most (1080×1920 for 9:16, 1080×1350 for 4:5, 1080×1080 square,+ 1920×1080 for 16:9), and the clip's own pixels when that is smaller: a picture is never enlarged+ unless `size` asks for it.+- A clip wider than the shape asked for keeps its full height, and the window slides across. A+ clip taller than it keeps its full width, and the window slides up and down, keeping the top of+ the head inside with a tenth of the frame to spare above it (a crown a few pixels from the edge+ reads as cut).+- The window moves like a calm camera operator (`follow`): it holds still while the face stays+ near where it is (a dead zone, so a nod or a small lean moves nothing), and when the face settles+ somewhere new it eases there, starting and stopping gently, a little before the head arrives+ rather than after. Whatever the moves, the face never leaves the window: where a quick lean+ would take it out, the window is pushed along with it. Where the clip itself cuts, so does the+ window, instead of gliding across the cut.+- When the face is found in too few frames to follow, the window stays centred and says so.+- `fill` keeps the whole picture: it is fitted inside the shape, over a blurred, darkened copy of+ itself that fills the rest.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Optional, Sequence++import numpy as np++from .face import FaceTrack+from .layout import Rect++PORTRAIT = (1080, 1920)+SHAPES = {"9:16": 9 / 16, "4:5": 4 / 5, "1:1": 1.0, "16:9": 16 / 9}+CROWN_ROOM = 0.10 # the room kept above the top of the head, as a share of the frame's height+MIN_FOUND = 0.5 # the face must be found in at least this share of frames to be followed++# How the window follows (shares of the window's own size, and seconds).+DEAD_ZONE = 0.10 # the face may wander this far from where the window sits before it moves+PATIENCE = 0.40 # a wander shorter than this (a gesture, a quick look away) is ignored+SETTLE = 1.00 # where the face settles: the middle of where it is over this long,+AHEAD = 0.25 # starting this long after it left the dead zone+MOVE_MIN, MOVE_MAX = 0.40, 1.20 # a move lasts this long at least and at most+MOVE_SPEED = 0.9 # windows a second, before the limits above+LEAD = 0.35 # a move starts this share of its length before the face leaves the dead zone+MERGE = 1.5 # a glide the same way within this long of the last one becomes one longer glide+EDGE = 0.04 # the face is kept at least this far inside the window's edges+CUT_JUMP = 0.35 # the face jumping this far in a moment, and staying, is a cut in the clip+CUT_HOLD = 0.5 # seconds the face must stay put on each side of a jump for it to be a cut+++def _even(v: float) -> int:+ return max(2, int(round(v / 2)) * 2)+++def _smooth(series: np.ndarray, sigma: float) -> np.ndarray:+ if sigma <= 0 or len(series) < 3:+ return series.copy()+ radius = max(1, int(3 * sigma))+ k = np.exp(-0.5 * (np.arange(-radius, radius + 1) / sigma) ** 2)+ k /= k.sum()+ return np.convolve(np.pad(series, (radius, radius), mode="edge"), k, mode="valid")+++def ease(u):+ """0 to 1 with no jolt at either end: zero speed and zero acceleration where it starts and stops."""+ u = np.clip(u, 0.0, 1.0)+ return u * u * u * (u * (u * 6 - 15) + 10)+++@dataclass+class Move:+ start: int # the first frame of the move+ end: int # the frame it arrives on+ a: float+ b: float+ cut: bool = False # the clip itself cuts here, so the window cuts instead of gliding++ def as_dict(self, fps: float) -> dict:+ return {"from_s": round(self.start / fps, 3), "to_s": round(self.end / fps, 3), "from": round(self.a, 1),+ "to": round(self.b, 1), "kind": "cut" if self.cut else "glide"}+++@dataclass+class Path:+ """Where the window's centre sits on one axis, frame by frame, and why."""++ pos: np.ndarray # the window's centre (source pixels)+ target: np.ndarray # where the face would put it+ lo: np.ndarray # the range the centre must stay inside for the face to stay in the window+ hi: np.ndarray+ moves: list[Move] = field(default_factory=list)+ pushed: int = 0 # frames where the face would have left the window, so the window was pushed++ def stats(self, fps: float, size: float) -> dict:+ """How calm it is: the share of frames the window is still, its fastest move, and how many+ times it turns back while moving (jitter shows as turns)."""+ v = np.diff(self.pos) if len(self.pos) > 1 else np.zeros(1)+ moving = np.abs(v) > 0.05+ both = moving[1:] & moving[:-1]+ turns = int(np.sum(np.sign(v[1:][both]) != np.sign(v[:-1][both])))+ cut_frames = {m.start for m in self.moves if m.cut}+ speed = np.abs(v).copy()+ for c in cut_frames: # a cut is not a speed+ if 0 < c <= len(speed):+ speed[c - 1] = 0.0+ return {"still_share": round(1.0 - float(moving.mean()), 3),+ "glides": sum(1 for m in self.moves if not m.cut), "cuts": len(cut_frames),+ "fastest_per_s": round(float(speed.max() * fps / size), 3) if len(speed) else 0.0,+ "turns_while_moving": turns, "pushed_frames": self.pushed}+++def follow(target: np.ndarray, lo: np.ndarray, hi: np.ndarray, size: float, fps: float,+ cuts: Sequence[int] = ()) -> Path:+ """A calm path for the window's centre on one axis.++ `target` is where the face would put the centre in each frame; `lo` and `hi` bound where the+ centre may be for the face to stay inside the window (and the window inside the clip); `size`+ is the window's length on this axis. The window holds still while the target stays within the+ dead zone of it; when the target leaves it for longer than `PATIENCE`, the window eases to where+ the target settles. A frame listed in `cuts` (a cut in the clip itself) makes the window cut+ there too. Last, the face is kept inside: a frame where the path would leave it out is pushed+ in, and the push is spread over the frames around it, so it reads as a move and not a jolt.+ """+ n = len(target)+ target = np.asarray(target, np.float64)+ lo, hi = np.minimum(lo, hi), np.maximum(lo, hi)+ dz = DEAD_ZONE * size+ patience = max(1, int(round(PATIENCE * fps)))+ settle = max(1, int(round(SETTLE * fps)))+ ahead = int(round(AHEAD * fps))+ merge = int(round(MERGE * fps))+ cut_set = sorted(set(int(c) for c in cuts if 0 < c < n))++ def settle_at(i: int, until: int) -> float:+ # Where the face ends up, not where it is half-way: the middle of a stretch that starts a+ # moment after it left.+ a0 = min(until - 1, i + ahead)+ j = max(a0 + 1, min(until, a0 + settle))+ v = float(np.median(target[a0:j]))+ a, b = float(np.max(lo[a0:j])), float(np.min(hi[a0:j]))+ return float(np.clip(v, a, b)) if a <= b else v++ def ok(i: int, p: float) -> bool:+ return abs(target[i] - p) <= dz and lo[i] - 0.5 <= p <= hi[i] + 0.5++ pos = np.empty(n)+ moves: list[Move] = []+ bounds = [0] + cut_set + [n]+ for s0, s1 in zip(bounds, bounds[1:]): # each stretch between the clip's own cuts on its own+ p = settle_at(s0, s1)+ if s0 > 0:+ moves.append(Move(s0, s0, float(pos[s0 - 1]), p, cut=True))+ decided = s0 # frames before this are fixed (a glide already written)+ i = s0+ while i < s1:+ if ok(i, p):+ pos[i] = p+ i += 1+ continue+ # The face has left the dead zone. A wander that comes back within the patience is+ # ignored, unless the window would lose the face meanwhile.+ limit = min(s1, i + patience)+ j = i+ while j < limit and not ok(j, p):+ j += 1+ lost = not (lo[i] - 0.5 <= p <= hi[i] + 0.5)+ if j < limit and not lost:+ pos[i:j] = p+ i = j+ continue+ new = settle_at(i, s1)+ dist = abs(new - p)+ if dist < 1.0:+ pos[i] = p+ i += 1+ continue+ last = moves[-1] if moves else None+ if (last is not None and not last.cut and last.start >= s0 and (new - p) * (last.b - last.a) > 0+ and i - last.end <= merge):+ # The face moved on the same way soon after the last glide: make the two one glide.+ moves.pop()+ a, start = last.a, last.start+ dist = abs(new - a)+ else:+ a, start = None, None+ seconds = float(np.clip(MOVE_MIN + dist / (MOVE_SPEED * size), MOVE_MIN, MOVE_MAX))+ length = max(2, int(round(fps * seconds)))+ merged = start is not None+ if start is None:+ start = max(decided, i - int(round(LEAD * length)))+ a = float(pos[start - 1]) if start > s0 else p+ # The glide must keep the face in all the way: where the face moves faster than it, the+ # glide goes quicker (down to a quarter of a second), so the window never has to be+ # yanked after it.+ quickest = max(2, int(round(0.25 * fps)))+ while True:+ end = min(s1 - 1, max(start + length, i))+ u = (np.arange(start, end + 1) - start) / max(1, end - start)+ glide = a + (new - a) * ease(u)+ lost = (glide < lo[start:end + 1] - 0.5) | (glide > hi[start:end + 1] + 0.5)+ if not lost.any() or length <= quickest:+ break+ length = max(quickest, int(length * 0.75))+ if not merged:+ start = max(decided, i - int(round(LEAD * length)))+ a = float(pos[start - 1]) if start > s0 else p+ pos[start:end + 1] = glide+ moves.append(Move(start, end, a, new))+ p = new+ decided = end + 1+ i = end + 1+ # Keep the face in: whatever a glide could not hold (a face moving faster than a quarter-second+ # glide) is pushed inside [lo, hi] frame by frame. The bounds follow the smoothed face, so the+ # push moves with it, without the turn-backs a smoothed correction makes.+ out = np.clip(pos, lo, hi)+ pushed = int(np.sum(np.abs(out - pos) > 0.5))+ return Path(out, target, lo, hi, moves, pushed)+++@dataclass+class Framing:+ src_w: int+ src_h: int+ out_w: int+ out_h: int+ windows: Optional[np.ndarray] # (n, 4) x, y, w, h per source frame; None = the whole frame+ note: str = ""+ fill: Optional[tuple[float, float, float]] = None # fill mode: (scale, x, y) of the fitted picture+ path: Optional[Path] = None # how the window moved, for the path sheet and the checks+ axis: str = "" # "x" or "y": the axis the window moves on+ face_out: float = 0.0 # the share of frames where the face is not wholly inside the window+ head_cut: float = 0.0 # the share of frames where the top of the head is above the window+ # The part of the clip that is picture (x0, y0, x1, y1), when black bars were filmed or+ # exported into it: everything above (windows, the fill) is measured inside this part.+ content: Optional[tuple[int, int, int, int]] = None++ @property+ def reframed(self) -> bool:+ return self.windows is not None or self.fill is not None++ def window(self, i: int) -> tuple[float, float, float, float]:+ if self.windows is None:+ return 0.0, 0.0, float(self.src_w), float(self.src_h)+ x, y, w, h = self.windows[int(np.clip(i, 0, len(self.windows) - 1))]+ return float(x), float(y), float(w), float(h)++ def apply(self, frame: np.ndarray, i: int) -> np.ndarray:+ """Source frame `i` as an output frame."""+ import cv2++ if self.content is not None:+ x0, y0, x1, y1 = self.content+ frame = frame[y0:y1, x0:x1]+ if self.fill is not None:+ return self._fill(frame)+ x, y, w, h = self.window(i)+ if self.windows is not None:+ scale = self.out_w / w+ if scale > 1.001: # enlarged: place the window to the sub-pixel, or a slow glide steps+ m = np.array([[scale, 0.0, -x * scale], [0.0, scale, -y * scale]], np.float64)+ return cv2.warpAffine(frame, m, (self.out_w, self.out_h), flags=cv2.INTER_CUBIC,+ borderMode=cv2.BORDER_REPLICATE)+ x0, y0 = int(round(x)), int(round(y))+ frame = frame[y0:y0 + int(round(h)), x0:x0 + int(round(w))]+ fh, fw = frame.shape[:2]+ if (fw, fh) == (self.out_w, self.out_h):+ return np.ascontiguousarray(frame)+ interp = cv2.INTER_AREA if fw > self.out_w else cv2.INTER_CUBIC+ return cv2.resize(frame, (self.out_w, self.out_h), interpolation=interp)++ def _fill(self, frame: np.ndarray) -> np.ndarray:+ import cv2++ s, fx, fy = self.fill+ W, H = self.out_w, self.out_h+ # The ground: the picture scaled to cover, blurred at an eighth of the size (fast), and+ # darkened, so the fitted picture stays what the eye goes to.+ cover = max(W / self.src_w, H / self.src_h)+ cw, ch = int(np.ceil(self.src_w * cover)), int(np.ceil(self.src_h * cover))+ small = cv2.resize(frame, (max(8, cw // 8), max(8, ch // 8)), interpolation=cv2.INTER_AREA)+ small = cv2.GaussianBlur(small, (0, 0), 5)+ ground = cv2.resize(small, (cw, ch), interpolation=cv2.INTER_LINEAR)+ gx, gy = (cw - W) // 2, (ch - H) // 2+ out = (ground[gy:gy + H, gx:gx + W].astype(np.float32) * 0.55).astype(np.uint8)+ fw, fh = int(round(self.src_w * s)), int(round(self.src_h * s))+ pic = cv2.resize(frame, (fw, fh), interpolation=cv2.INTER_AREA if s < 1 else cv2.INTER_CUBIC)+ x0, y0 = int(round(fx)), int(round(fy))+ out[y0:y0 + fh, x0:x0 + fw] = pic[:H - y0, :W - x0]+ return np.ascontiguousarray(out)++ def to_output(self, r: Rect, i: int) -> Rect:+ """A box in source frame `i`'s pixels, in output pixels."""+ if self.content is not None:+ r = r.shift(-self.content[0], -self.content[1])+ if self.fill is not None:+ s, fx, fy = self.fill+ return r.scale(s, s, fx, fy)+ x, y, w, h = self.window(i)+ sx, sy = self.out_w / w, self.out_h / h+ return Rect((r.x0 - x) * sx, (r.y0 - y) * sy, (r.x1 - x) * sx, (r.y1 - y) * sy)+++def output_size(w: float, h: float, size: Optional[tuple[int, int]] = None) -> tuple[int, int]:+ """The output size for a picture of w×h: `size` when given, else no larger than 1080×1920+ (1920×1080 on its side), keeping the shape."""+ if size:+ return size+ long_side, short_side = (PORTRAIT[1], PORTRAIT[0])+ if h >= w:+ k = min(1.0, long_side / h, short_side / w)+ else:+ k = min(1.0, long_side / w, short_side / h)+ return _even(w * k), _even(h * k)+++def shape_size(aspect: float, size: Optional[tuple[int, int]] = None) -> tuple[int, int]:+ """A shape's full size: 1080 wide when it is upright or square, 1920 wide on its side."""+ if size:+ return size+ if aspect > 1.0 + 1e-6:+ return 1920, _even(1920 / aspect)+ return 1080, _even(1080 / aspect)+++def find_cuts(face: FaceTrack, size: float, axis: int) -> list[int]:+ """Frames where the clip itself cuts: the face jumps more than `CUT_JUMP` of the window across+ the frame between two detections a moment apart, and stays near each place for `CUT_HOLD`+ seconds on either side (a blip of a false face does not)."""+ raw = face.raw+ good = ~np.isnan(raw[:, 0]) & (raw[:, 4] >= 0.6)+ found = np.flatnonzero(good)+ if len(found) < 4:+ return []+ c = raw[:, axis] + raw[:, axis + 2] / 2+ hold = max(2, int(round(CUT_HOLD * face.fps)))+ out = []+ for k in range(1, len(found)):+ a, b = found[k - 1], found[k]+ if b - a > max(2, int(0.1 * face.fps)) or abs(c[b] - c[a]) <= CUT_JUMP * size:+ continue+ before = found[(found <= a) & (found > a - hold)]+ after = found[(found >= b) & (found < b + hold)]+ if len(before) < hold // 2 or len(after) < hold // 2:+ continue+ if (np.abs(c[before] - c[a]).max() < CUT_JUMP * size / 2+ and np.abs(c[after] - c[b]).max() < CUT_JUMP * size / 2):+ out.append(int(b))+ return out+++def faces_with_cuts(face: FaceTrack, n: int, info_w: int, info_h: int, aspect: float,+ cuts: Optional[Sequence[int]] = None) -> tuple[list[Optional[Rect]], list[int]]:+ """The face's box in every frame, and the frames where the clip itself cuts (found when not+ given). Each stretch between cuts is followed from its own detections, so the face is never+ glided from one shot into the next."""+ wide = info_w / info_h > aspect+ size_axis = _even(min(info_w, info_h * aspect)) if wide else _even(min(info_h, info_w / aspect))+ cuts = list(cuts) if cuts is not None else find_cuts(face, size_axis, 0 if wide else 1)+ faces = [face.box(i) for i in range(n)]+ if cuts:+ segments = [0] + cuts + [n]+ for s0, s1 in zip(segments, segments[1:]):+ boxes = face.boxes_between(s0, s1)+ for k in range(s1 - s0):+ x, y, w, h = boxes[k]+ faces[s0 + k] = Rect(x, y, x + w, y + h) if w > 0 else None+ return faces, cuts+++def plan(info_w: int, info_h: int, fps: float, n: int, face: Optional[FaceTrack], shape: str = "9:16",+ size: Optional[tuple[int, int]] = None, mode: str = "track",+ faces: Optional[Sequence[Optional[Rect]]] = None, cuts: Optional[Sequence[int]] = None) -> Framing:+ """The framing for a clip of info_w×info_h.++ `shape` is "9:16", "4:5", "1:1" or "16:9" (reframed when the clip is another shape), or "keep"+ (the clip's own shape). `mode` is "track" (the window follows the face), "center" (it stays+ put in the middle) or "fill" (the whole picture, fitted over a blurred copy of itself).+ `faces` (a face box per frame, or None where there is none) replaces the face track, for a+ caller that decides whom to follow (the speaker, when there are two people); `cuts` lists the+ frames where the window cuts instead of gliding (found in the face track when not given).+ """+ if shape == "keep" or shape not in SHAPES:+ ow, oh = output_size(info_w, info_h, size)+ return Framing(info_w, info_h, ow, oh, None, "the clip's own shape")+ aspect = SHAPES[shape]+ if abs(info_w / info_h - aspect) < 0.01 * aspect:+ ow, oh = output_size(info_w, info_h, size)+ return Framing(info_w, info_h, ow, oh, None, f"already {shape}")+ if mode == "fill":+ ow, oh = shape_size(aspect, size)+ s = min(ow / info_w, oh / info_h)+ fw, fh = info_w * s, info_h * s+ return Framing(info_w, info_h, ow, oh, None, f"fitted inside {shape} over a blurred copy of itself",+ fill=(s, (ow - fw) / 2, (oh - fh) / 2))++ if faces is None and face is not None and face.any() and face.found_share >= MIN_FOUND:+ faces, found = faces_with_cuts(face, n, info_w, info_h, aspect, cuts)+ cuts = found if cuts is None else cuts+ following = mode == "track" and faces is not None and any(f is not None for f in faces)+ cuts = list(cuts or [])++ windows = np.zeros((n, 4), np.float64)+ path = None+ rule = ""+ if info_w / info_h > aspect: # wider: full height, slide across+ axis = "x"+ h = float(info_h)+ w = float(_even(min(info_w, info_h * aspect)))+ half = w / 2+ if following:+ boxes = _held(faces, n)+ target = np.clip(np.array([b.cx for b in boxes]), half, info_w - half)+ # The centres that keep the face inside, never narrower than the dead zone (so the+ # window can still hold still when a big face nearly fills it).+ lo, hi = _band([b.x1 + EDGE * w - half for b in boxes], [b.x0 - EDGE * w + half for b in boxes],+ DEAD_ZONE * w, half, info_w - half)+ path = follow(target, lo, hi, w, fps, cuts)+ cx = path.pos+ elif mode == "center":+ cx = np.full(n, info_w / 2.0)+ else:+ cx = np.full(n, info_w / 2.0)+ x = np.clip(cx - half, 0, info_w - w)+ windows[:] = np.stack([x, np.zeros(n), np.full(n, w), np.full(n, h)], axis=1)+ else: # taller: full width, keep the crown in with room above it+ axis = "y"+ w = float(info_w)+ h = float(_even(min(info_h, info_w / aspect)))+ half = h / 2+ if following:+ boxes = _held(faces, n)+ heads = [FaceTrack._grow(b) for b in boxes]+ room = CROWN_ROOM * h+ # One rule for the whole clip, so the frame never hops between two compositions: the+ # whole head with room above it when it fits in most frames; else brows to chin, the+ # brows a little under the top, and the top of the hair let go (the note says so).+ fits = np.mean([(b.y1 + EDGE * h) - (hd.y0 - 0.5 * room) <= h for b, hd in zip(boxes, heads)])+ rule = "head" if fits >= 0.7 else "face"+ if rule == "head":+ target = np.array([hd.y0 - room + half for hd in heads])+ tops = [min(b.y0 - EDGE * h, hd.y0 - 0.5 * room) + half for b, hd in zip(boxes, heads)]+ else:+ target = np.array([b.y0 - 0.12 * h + half for b in boxes])+ tops = [b.y0 - EDGE * h + half for b in boxes]+ lo, hi = _band([b.y1 + EDGE * h - half for b in boxes], tops, DEAD_ZONE * h, half, info_h - half)+ target = np.clip(target, half, info_h - half)+ path = follow(target, lo, hi, h, fps, cuts)+ cy = path.pos+ elif mode == "center":+ cy = np.full(n, info_h / 2.0)+ else: # no face to follow: the upper part, where a head usually is+ cy = np.full(n, (info_h - h) * 0.3 + half)+ y = np.clip(cy - half, 0, info_h - h)+ windows[:] = np.stack([np.zeros(n), y, np.full(n, w), np.full(n, h)], axis=1)+ ow, oh = output_size(w, h, size)+ fr = Framing(info_w, info_h, ow, oh, windows, "", path=path, axis=axis)+ if following:+ fr.face_out, fr.head_cut = _measure(fr, _held(faces, n))+ note = f"reframed to {shape}, following the face"+ if rule == "face":+ note += (f"; the head is taller than a {shape} frame, so the face is kept and the top of the "+ f"hair is cut")+ elif mode == "center":+ note = f"reframed to {shape}, centred (as asked)"+ elif face is not None and face.any():+ note = f"reframed to {shape}, centred: the face was found in only {face.found_share:.0%} of frames"+ else:+ note = f"reframed to {shape}, centred: no face was found"+ fr.note = note+ return fr+++def _band(lo: Sequence[float], hi: Sequence[float], least: float, floor: float, ceil: float) -> tuple[np.ndarray, np.ndarray]:+ """Per-frame bounds for the window's centre, each at least `least` wide (widened evenly about its+ middle where the face leaves less room than that) and inside [floor, ceil]."""+ lo, hi = np.asarray(lo, np.float64), np.asarray(hi, np.float64)+ short = hi - lo < least+ mid = (lo + hi) / 2+ lo = np.where(short, mid - least / 2, lo)+ hi = np.where(short, mid + least / 2, hi)+ lo, hi = np.clip(lo, floor, ceil), np.clip(hi, floor, ceil)+ return np.minimum(lo, hi), np.maximum(lo, hi)+++def _measure(fr: "Framing", boxes: Sequence[Rect]) -> tuple[float, float]:+ """The share of frames where the face box is not wholly inside the window, and where the top of+ the head (the face box grown to take in the hair) is above the window's top."""+ out = cut = 0+ for i, b in enumerate(boxes):+ x, y, w, h = fr.window(i)+ if b.x0 < x - 0.5 or b.x1 > x + w + 0.5 or b.y0 < y - 0.5 or b.y1 > y + h + 0.5:+ out += 1+ if fr.axis == "y" and FaceTrack._grow(b).y0 < y - 0.5:+ cut += 1+ n = max(1, len(boxes))+ return round(out / n, 3), round(cut / n, 3)+++def _held(faces: Sequence[Optional[Rect]], n: int) -> list[Rect]:+ """A box for every frame: where there is none, the nearest one before (or after, at the start)."""+ out: list[Optional[Rect]] = list(faces[:n]) + [None] * max(0, n - len(faces))+ last = next((f for f in out if f is not None), None)+ for i in range(n):+ if out[i] is None:+ out[i] = last+ else:+ last = out[i]+ return out # type: ignore[return-value]diff --git a/edit/askeditor/fx/core/glass.py b/edit/askeditor/fx/core/glass.pynew file mode 100644index 0000000..687e1a5--- /dev/null+++ b/edit/askeditor/fx/core/glass.py@@ -0,0 +1,365 @@+"""Frosted glass: a pane that blurs the picture behind it, with light along its edge and a soft shadow+under it, so a card reads as a sheet of glass held over the video rather than a sticker on it.++ pane = glass.Pane(w, h, radius, unit=s) # its shape, its light, its shadow: made once+ pane.tone_over(frames, x, y) # smoked just enough for white type over these+ pane.draw(frame, x, y) # each frame: what is behind, blurred, bent, lit+ pane.draw(frame, x, y, opacity=a, frost=f, scale=k) # arriving: fading in, frosting over, growing++`unit` is the size of one design pixel on the real frame (the frame's width over 1080, times the+pane's own scale); the blur, the edge and the shadow follow it, so a pane looks the same at any size.++What the glass does to what is behind it is its `Tone`:++ Tone(smoke=0.55) # dark smoked glass, for white type: what `tone_over` chooses+ Tone(smoke=0.0, lift=0.35) # light frosted glass, for dark type: what `light_tone_for` chooses+ Tone(smoke=0.5, tint=(48, 12, 24)) # smoked toward a colour of your own++What makes it glass, each part made once from the pane's shape (a rounded rectangle measured as a+distance from its edge, so every part follows the same curve):++- **the blur** of whatever is behind it, worked out on every frame, because the picture moves;+- **the bend at the rim:** near the edge the pane shows the picture just outside it, pulled in,+ the way a thick pane bends light at its edge;+- **the tone:** smoked toward a cool slate just enough that white type on it stays readable however+ bright the room is (`tone_over` measures the brightest of the moments it is given), graded a+ little lighter at the top; over a dark room, a faint white frost instead, so it still reads as glass;+- **the light:** a thin rim lit from the upper left and faintly from below, a second line inside+ it, a sheen across the top, and a little shade inside the lower edge, which gives it thickness;+- **the shadow:** soft and a little below, with a hairline at the edge that parts it from a bright room.++Only the picture under the pane (and a margin) is blurred, a quarter size and brought back up, so a+pane costs a few milliseconds a frame however large the video is. `frosted=False` is a plain pane of+`fill` with the same edge and shadow, for when the picture behind should not show through.+"""++from __future__ import annotations++import math+from dataclasses import dataclass+from typing import Optional, Sequence++import numpy as np++from .compose import Sprite, over++LIGHT = (-0.55, -0.83) # where the light comes from: the upper left+SLATE = (16.0, 19.0, 28.0) # what the glass is smoked toward unless told otherwise+TARGET = 116.0 # the brightest the glass may be (0..255) for white type on it to read at about 4.5 : 1+GRADE = 0.06 # the top of a pane is this much less smoked than its middle, the bottom this much more+++@dataclass(frozen=True)+class Tone:+ """What the glass does to the picture behind it, after the blur."""+ smoke: float = 0.0 # how far it is taken toward `tint` (0..1), at the pane's middle+ lift: float = 0.0 # then how much white is laid over it (0..1): a frost+ vivid: float = 1.15 # colour kept a little stronger, as it is through real glass+ tint: tuple[float, float, float] = SLATE++ def brightest(self, behind: float) -> float:+ """The pane's brightness (0..255) at its lightest, the top, over a picture of `behind`."""+ k = max(0.0, self.smoke - GRADE)+ return (behind * (1 - k) + brightness(self.tint) * k) * (1 - self.lift) + 255 * self.lift++ def darkest(self, behind: float) -> float:+ """The pane's brightness (0..255) at its darkest, the bottom, over a picture of `behind`."""+ k = min(0.95, self.smoke + GRADE)+ return (behind * (1 - k) + brightness(self.tint) * k) * (1 - self.lift) + 255 * self.lift+++def brightness(colour: Sequence[float]) -> float:+ """How bright a colour is (0..255), as the eye weighs red, green and blue."""+ return float(np.dot(np.asarray(colour, np.float32)[:3], (0.2126, 0.7152, 0.0722)))+++def luma(img: np.ndarray) -> np.ndarray:+ """The brightness of every pixel of an RGB picture (0..255)."""+ return img[..., 0] * 0.2126 + img[..., 1] * 0.7152 + img[..., 2] * 0.0722+++def _linear(v: float) -> float:+ c = max(0.0, min(1.0, v / 255.0))+ return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4+++def contrast_with_white(ground: float) -> float:+ """How well white type stands out on a ground of brightness `ground` (0..255): 21 on black,+ 1 on white; 4.5 reads comfortably."""+ return 1.05 / (_linear(ground) + 0.05)+++def contrast(a: float, b: float) -> float:+ """How well two brightnesses (0..255) stand apart, type on a ground: 1 for the same, 21 for black+ on white; 4.5 reads comfortably."""+ hi, lo = max(_linear(a), _linear(b)), min(_linear(a), _linear(b))+ return (hi + 0.05) / (lo + 0.05)+++def _sdf(w: int, h: int, r: float, pad: int = 0) -> np.ndarray:+ """The signed distance from the edge of a w x h rounded rectangle (negative inside), on a grid+ `pad` pixels larger on every side."""+ ys, xs = np.mgrid[-pad:h + pad, -pad:w + pad].astype(np.float32)+ xs += 0.5+ ys += 0.5+ qx = np.abs(xs - w / 2.0) - (w / 2.0 - r)+ qy = np.abs(ys - h / 2.0) - (h / 2.0 - r)+ outside = np.hypot(np.maximum(qx, 0), np.maximum(qy, 0))+ inside = np.minimum(np.maximum(qx, qy), 0)+ return outside + inside - r+++def _blur(img: np.ndarray, sigma: float) -> np.ndarray:+ """A wide blur, worked out on a quarter-size copy and brought back up (much faster, and a blur+ this wide loses nothing by it)."""+ import cv2++ h, w = img.shape[:2]+ k = 4 if min(h, w) >= 64 else 1+ small = cv2.resize(img, (max(1, w // k), max(1, h // k)), interpolation=cv2.INTER_AREA) if k > 1 else img+ small = cv2.GaussianBlur(small, (0, 0), max(0.5, sigma / k))+ return cv2.resize(small, (w, h), interpolation=cv2.INTER_LINEAR) if k > 1 else small+++SHADOW_PAD = 22.0 # the shadow's canvas past the pane on each side, in units+SHADOW_DY = 7.0 # how far below the pane its shadow falls, in units+++class Pane:+ """One pane of glass, w x h pixels, with corners of `radius` (half the shorter side makes a pill+ or a circle). `shadow` is how dark its shadow is (0 for none); `light` where its light comes from."""++ @staticmethod+ def reach(unit: float = 1.0) -> tuple[float, float, float, float]:+ """How far a pane's drawing (its shadow and edge) reaches past the pane itself, in pixels:+ (left, top, right, bottom). What is kept inside the safe zone is the pane with this round it."""+ sp = math.ceil(SHADOW_PAD * unit)+ return float(sp), float(max(0.0, sp - SHADOW_DY * unit)), float(sp), float(sp + SHADOW_DY * unit)++ def __init__(self, w: int, h: int, radius: float, unit: float = 1.0, frosted: bool = True,+ fill: Sequence[int] = (20, 20, 25), shadow: float = 0.34,+ light: tuple[float, float] = LIGHT):+ import cv2++ self.w, self.h = max(1, int(w)), max(1, int(h))+ self.r = float(max(0.0, min(radius, self.w / 2, self.h / 2)))+ self.u = float(unit)+ self.frosted = frosted+ self.fill = np.array(fill, np.float32)[:3]+ self.shadow_strength = float(shadow)+ self.light_from = light+ self.sigma = 15.0 * self.u # the blur+ self.bend = 11.0 * self.u # how wide the rim that bends the picture is+ self.pad = int(math.ceil(self.bend * 1.2 + 4))+ self._sizes: dict[float, Pane] = {}+ d = _sdf(self.w, self.h, self.r)+ self.mask = np.clip(0.5 - d, 0.0, 1.0).astype(np.float32)+ inside = np.maximum(0.0, -d)+ gy, gx = np.gradient(d) # the outward normal, from the distance's slope+ n = np.hypot(gx, gy) + 1e-6+ nx, ny = gx / n, gy / n+ facing = nx * light[0] + ny * light[1] # 1 on the edge the light falls on, -1 opposite+ # the light: a thin rim (bright where the light falls, fainter below), a second line inside+ # it where the glass's thickness catches the light, a glow, a sheen across the top, a glare+ rim_w = max(1.0, 1.5 * self.u)+ rim = np.clip(1.0 - np.abs(inside - rim_w * 0.55) / rim_w, 0.0, 1.0)+ rim *= 0.22 + 0.66 * np.maximum(0, facing) ** 1.3 + 0.34 * np.maximum(0, -facing) ** 2+ inner = 0.10 * np.clip(1.0 - np.abs(inside - 3.2 * self.u) / (1.1 * self.u), 0, 1) * np.maximum(0, facing)+ glow = 0.06 * np.exp(-inside / (7.0 * self.u)) * (0.4 + 0.6 * np.maximum(0, facing))+ ys = np.arange(self.h, dtype=np.float32)[:, None] / self.h+ xs = np.arange(self.w, dtype=np.float32)[None, :] / self.w+ sheen = 0.07 * np.clip(1.0 - ys / 0.45, 0, 1) ** 2+ glare = 0.035 * np.clip(1.0 - ((xs * self.w + ys * self.h) / (0.9 * (self.w + self.h))) ** 2 * 2.2, 0, 1)+ self.light = np.clip(rim + inner + glow + sheen + glare, 0, 0.92).astype(np.float32)[..., None]+ # the smoke grades from the top (lighter) to the bottom (darker), as light falls through it+ self.grade = ((ys - 0.5) * 2.0 * GRADE).astype(np.float32)[..., None]+ # thickness: a little shade inside the lower edge+ self.shade = (0.13 * np.exp(-inside / (7.0 * self.u)) * np.maximum(0, ny) ** 1.5).astype(np.float32)[..., None]+ # the bend: near the rim the pane shows the picture just outside it, pulled in+ t = np.clip(1.0 - inside / self.bend, 0.0, 1.0) ** 2+ gx_, gy_ = np.meshgrid(np.arange(self.w, dtype=np.float32), np.arange(self.h, dtype=np.float32))+ self.map_x = (gx_ + self.pad + nx * t * self.bend * 1.05).astype(np.float32)+ self.map_y = (gy_ + self.pad + ny * t * self.bend * 1.05).astype(np.float32)+ # a fine grain, the same on every frame, so a smooth blur never shows bands+ self.grain = (np.random.default_rng(11).standard_normal((self.h, self.w, 1)) * 1.3).astype(np.float32)+ # the shadow, soft and a little below, and the hairline at the edge+ sp = int(math.ceil(SHADOW_PAD * self.u))+ self.shadow_pad = sp+ sd = _sdf(self.w, self.h, self.r, pad=sp)+ soft = cv2.GaussianBlur(np.clip(0.5 - sd, 0.0, 1.0).astype(np.float32), (0, 0), max(1.0, 9.0 * self.u))+ black = np.zeros(sd.shape + (3,), np.float32)+ self.shadow = Sprite(rgb=black, a=(soft * self.shadow_strength).astype(np.float32))+ self.shadow_dy = SHADOW_DY * self.u+ hairline = np.clip(1.0 - np.abs(sd - 0.6) / 0.9, 0.0, 1.0) * (sd > 0)+ self.edge = Sprite(rgb=black, a=(hairline * 0.16 * min(1.0, self.shadow_strength / 0.34)).astype(np.float32))+ self.tone = Tone()++ # -- the tone -----------------------------------------------------------------------------------+ @property+ def tone(self) -> Tone:+ return self._tone++ @tone.setter+ def tone(self, tone: Tone) -> None:+ """Setting the tone works out, once, everything about the pane's colour that does not change+ from frame to frame; per frame it is then one multiply and one add."""+ self._tone = tone+ smoke = np.clip(tone.smoke + self.grade, 0.0, 0.95)+ lit = 1.0 - self.light - self.shade+ self._mul = ((1.0 - smoke) * (1.0 - tone.lift) * lit).astype(np.float32)+ add = np.asarray(tone.tint, np.float32) * smoke * (1.0 - tone.lift) + 255.0 * tone.lift + self.grain+ self._add = (add * lit + 255.0 * self.light).astype(np.float32)+ for p in self._sizes.values():+ p.tone = tone++ def tone_over(self, frames: Sequence[np.ndarray], x: float, y: float, target: float = TARGET) -> float:+ """Choose the tone for the pane at (x, y) over `frames` (the moments it is up, uint8 RGB): see+ `tone_for`. Sets it, and returns the pane's brightest brightness under it (0..255), which+ `contrast_with_white` turns into how well white type reads on it."""+ x, y = int(round(x)), int(round(y))+ regions = []+ for f in frames:+ H, W = f.shape[:2]+ regions.append(f[max(0, y - self.pad):min(H, y + self.h + self.pad),+ max(0, x - self.pad):min(W, x + self.w + self.pad)])+ if not self.frosted:+ return brightness(self.fill)+ tone, bright = tone_for(regions, self.sigma, target)+ self.tone = tone+ return bright++ # -- drawing ------------------------------------------------------------------------------------+ def behind(self, frame: np.ndarray, x: int, y: int) -> np.ndarray:+ """What is behind the pane at (x, y), with the margin round it, as float32; the frame's edge+ is mirrored where the margin runs off it."""+ import cv2++ H, W = frame.shape[:2]+ p = self.pad+ x0, y0, x1, y1 = x - p, y - p, x + self.w + p, y + self.h + p+ cx0, cy0, cx1, cy1 = max(0, x0), max(0, y0), min(W, x1), min(H, y1)+ if cx1 <= cx0 or cy1 <= cy0:+ return np.zeros((y1 - y0, x1 - x0, 3), np.float32)+ region = frame[cy0:cy1, cx0:cx1]+ if (cx0, cy0, cx1, cy1) != (x0, y0, x1, y1):+ region = cv2.copyMakeBorder(region, cy0 - y0, y1 - cy1, cx0 - x0, x1 - cx1, cv2.BORDER_REFLECT)+ return region.astype(np.float32)++ def colours(self, frame: np.ndarray, x: int, y: int, frost: float = 1.0) -> np.ndarray:+ """The pane's own colours at (x, y), before it is laid on the frame: what is behind it+ blurred, bent at the rim, toned and lit (float32, h x w x 3). With `frost` under 1 the pane+ is part way from clear to frosted."""+ import cv2++ if not self.frosted:+ base = np.broadcast_to(self.fill, (self.h, self.w, 3)).astype(np.float32)+ return np.clip(base * (1.0 - self.light - self.shade) + 255.0 * self.light, 0, 255)+ region = self.behind(frame, x, y)+ soft = _blur(region, self.sigma)+ if frost < 1.0:+ soft = region * (1.0 - frost) + soft * frost+ base = cv2.remap(soft, self.map_x, self.map_y, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)+ tone = self.tone+ vivid = 1.0 + (tone.vivid - 1.0) * frost+ if abs(vivid - 1.0) > 1e-3:+ g = luma(base)[..., None]+ base = g + (base - g) * vivid+ if frost >= 1.0:+ return np.clip(base * self._mul + self._add, 0, 255)+ smoke = np.clip((tone.smoke + self.grade) * frost, 0.0, 0.95)+ lift = tone.lift * frost+ base = base * (1.0 - smoke) + np.asarray(tone.tint, np.float32) * smoke+ base = base * (1.0 - lift) + 255.0 * lift + self.grain * frost+ return np.clip(base * (1.0 - self.light - self.shade) + 255.0 * self.light, 0, 255)++ def scaled(self, k: float) -> "Pane":+ """The same pane drawn `k` times its size (made once for each size and kept), for a pane+ that grows into place."""+ k = round(float(k) / 0.02) * 0.02+ if abs(k - 1.0) < 0.01:+ return self+ k = max(0.1, k)+ if k not in self._sizes:+ p = Pane(round(self.w * k), round(self.h * k), self.r * k, self.u * k, self.frosted, tuple(self.fill),+ self.shadow_strength, self.light_from)+ p.tone = self.tone+ self._sizes[k] = p+ return self._sizes[k]++ def draw(self, frame: np.ndarray, x: float, y: float, opacity: float = 1.0, frost: float = 1.0,+ scale: float = 1.0) -> None:+ """Lay the pane on `frame` (uint8 RGB, changed in place) with its top-left at (x, y).+ `opacity` fades it, `frost` takes it from clear (0) to frosted (1), and `scale` grows it+ about its middle, which stays where it is at full size."""+ if opacity <= 0.0:+ return+ if abs(scale - 1.0) >= 0.01:+ p = self.scaled(scale)+ cx, cy = x + self.w / 2, y + self.h / 2+ if p is not self:+ p.draw(frame, cx - p.w / 2, cy - p.h / 2, opacity, frost)+ return+ x, y = int(round(x)), int(round(y))+ over(frame, self.shadow, x - self.shadow_pad, y - self.shadow_pad + self.shadow_dy, opacity)+ over(frame, self.edge, x - self.shadow_pad, y - self.shadow_pad, opacity)+ H, W = frame.shape[:2]+ cx0, cy0, cx1, cy1 = max(0, x), max(0, y), min(W, x + self.w), min(H, y + self.h)+ if cx1 <= cx0 or cy1 <= cy0:+ return+ g = self.colours(frame, x, y, frost)+ sx0, sy0 = cx0 - x, cy0 - y+ sx1, sy1 = sx0 + (cx1 - cx0), sy0 + (cy1 - cy0)+ a = self.mask[sy0:sy1, sx0:sx1, None] * float(opacity)+ region = frame[cy0:cy1, cx0:cx1].astype(np.float32)+ region = region * (1.0 - a) + g[sy0:sy1, sx0:sx1] * a+ frame[cy0:cy1, cx0:cx1] = np.clip(region + 0.5, 0, 255).astype(np.uint8)+++def tone_for(regions: Sequence[Optional[np.ndarray]], sigma: float, target: float = TARGET,+ tint: tuple[float, float, float] = SLATE) -> tuple[Tone, float]:+ """The tone for a pane over `regions` (what is behind it at a few moments, uint8 RGB), blurred+ by `sigma` as the pane blurs them: smoked toward `tint` just enough that the brightest of them+ comes to `target` at the pane's top, where it is lightest; over a dark room hardly smoked, with a+ faint white frost so it still reads as glass. Returns the tone and the pane's brightest+ brightness under it (0..255)."""+ lows = []+ for reg in regions:+ if reg is None or not reg.size:+ continue+ soft = _blur(reg.astype(np.float32), sigma)+ lows.append(float(np.percentile(luma(soft), 92)))+ behind = max(lows) if lows else 128.0+ lift = 0.03+ if behind <= target:+ tone = Tone(smoke=0.18, lift=lift + 0.05 * (1.0 - behind / target), tint=tint)+ else:+ # (behind (1 - k) + tint k)(1 - lift) + 255 lift = target, for the smoke k at the pane's top+ want = (target - 255 * lift) / (1 - lift)+ k = (behind - want) / max(1e-3, behind - brightness(tint))+ tone = Tone(smoke=min(0.9, max(0.18, k + GRADE)), lift=lift, tint=tint)+ return tone, tone.brightest(behind)+++LIGHT_TARGET = 178.0 # the darkest light glass may be (0..255): dark type on it reads at about 7 : 1+LIGHT_FROST = 0.24 # light glass is lifted at least this much, so over a bright room it still reads as glass+++def light_tone_for(regions: Sequence[Optional[np.ndarray]], sigma: float, target: float = LIGHT_TARGET,+ tint: tuple[float, float, float] = SLATE) -> tuple[Tone, float]:+ """The tone for light frosted glass, for dark type: lifted toward white just enough that the+ darkest of `regions` (what is behind the pane at a few moments, uint8 RGB, blurred as the pane+ blurs them) comes to `target` at the pane's bottom, where it is darkest; over a bright room a+ little frost still, so the pane reads as glass. Returns the tone and the pane's darkest+ brightness under it (0..255), which `contrast` sets against the type's."""+ lows = []+ for reg in regions:+ if reg is None or not reg.size:+ continue+ soft = _blur(reg.astype(np.float32), sigma)+ lows.append(float(np.percentile(luma(soft), 8)))+ behind = min(lows) if lows else 128.0+ # (behind (1 - g) + tint g)(1 - lift) + 255 lift = target, with the bottom's own smoke g+ base = behind * (1 - GRADE) + brightness(tint) * GRADE+ lift = (target - base) / max(1e-3, 255.0 - base)+ tone = Tone(smoke=0.0, lift=min(0.9, max(LIGHT_FROST, lift)), vivid=1.05, tint=tint)+ return tone, tone.darkest(behind)diff --git a/edit/askeditor/fx/core/glitch.py b/edit/askeditor/fx/core/glitch.pynew file mode 100644index 0000000..6c7429d--- /dev/null+++ b/edit/askeditor/fx/core/glitch.py@@ -0,0 +1,119 @@+"""A broken signal drawn over a frame, and the crackle it makes. Shared by `transitions` (a glitch at+a join) and `glitch` (a glitch on a word or a cut).++ rng = np.random.default_rng(seed)+ out = glitch.tear(frame, other, e, rng) # e: how broken, 0 (clean) to 1 (at its worst)+ x, peak = glitch.crackle(seconds, seed) # its sound, and the second it is thickest++**The tear** is a burst of broken signal on one frame: bands of the picture torn sideways, some from+`other` (the other shot flashing through, or the same frame), a few with their colour channels+swapped, coarse blocks as when a picture loses its data, the red and blue pulled apart, and scan+lines. Everything scales with `e`; under 0.03 the frame comes back unchanged. The random draws are+taken from `rng` in a fixed order, so one seed always tears the same way.++`colour` other than "auto" tints what would be a channel swap or a colour split with that colour.++**The crackle** is short bursts of crushed noise and buzzing tones, stuttering, thickest at its+peak, each burst somewhere else across the stereo field. Made from noise in code, nothing recorded.+"""++from __future__ import annotations++import math++import numpy as np++from .text import colour as _colour+from .video import AUDIO_RATE++RATE = AUDIO_RATE+++def rgb(hex_colour: str) -> np.ndarray:+ """A colour by name or hex as three floats from 0 to 1."""+ return np.array(_colour(hex_colour), np.float32) / 255.0+++def tint(img: np.ndarray, hex_colour: str) -> np.ndarray:+ """`img` as its own brightness in one colour, a little lifted."""+ c = rgb(hex_colour)+ lum = img.astype(np.float32).mean(axis=2, keepdims=True) / 255.0+ return np.clip(lum * c * 255.0 * 1.3, 0, 255).astype(np.uint8)+++def tear(base: np.ndarray, other: np.ndarray, e: float, rng: np.random.Generator,+ colour: str = "auto") -> np.ndarray:+ """`base` (uint8 RGB, changed in place and returned) torn by a broken signal of strength `e`,+ with bands of `other` flashing through."""+ import cv2++ h, w = base.shape[:2]+ if e < 0.03:+ return base+ out = base+ bands = 2 + int(round(9 * e))+ for _ in range(bands):+ bh = max(2, int(h * rng.uniform(0.01, 0.09)))+ y0 = int(rng.integers(0, max(1, h - bh)))+ src = other if rng.random() < 0.15 + 0.5 * e else out # the other shot flashing through+ dx = int(round(rng.normal(0, 0.07 * w * e)))+ band = np.roll(src[y0:y0 + bh], dx, axis=1)+ if rng.random() < 0.18 * e: # a band with its channels swapped+ band = band[..., ::-1] if colour == "auto" else tint(band, colour)+ out[y0:y0 + bh] = band+ for _ in range(int(round(3 * e))): # coarse blocks, as when a picture loses its data+ bw, bh = int(w * rng.uniform(0.15, 0.45)), int(h * rng.uniform(0.04, 0.12))+ x0, y0 = int(rng.integers(0, w - bw)), int(rng.integers(0, h - bh))+ cell = max(4, int(w * 0.03))+ part = out[y0:y0 + bh, x0:x0 + bw]+ small = cv2.resize(part, (max(1, bw // cell), max(1, bh // cell)), interpolation=cv2.INTER_AREA)+ out[y0:y0 + bh, x0:x0 + bw] = cv2.resize(small, (bw, bh), interpolation=cv2.INTER_NEAREST)+ split = int(round(0.02 * w * e * (1 + rng.random())))+ if split:+ if colour == "auto":+ out[..., 0] = np.roll(out[..., 0], split, axis=1)+ out[..., 2] = np.roll(out[..., 2], -split, axis=1)+ else:+ ghost = tint(np.roll(out, split, axis=1), colour)+ out = np.maximum(out, (ghost.astype(np.float32) * 0.6).astype(np.uint8))+ lines = np.ones((h, 1, 1), np.float32)+ lines[::3] = 1.0 - 0.35 * e+ out = np.clip(out.astype(np.float32) * lines * (1 + 0.12 * e * rng.uniform(-1, 1)), 0, 255).astype(np.uint8)+ return out+++def _stereo(mono: np.ndarray, pan) -> np.ndarray:+ theta = (np.clip(pan, -1, 1) + 1) * np.pi / 4+ return (np.stack([mono * np.cos(theta), mono * np.sin(theta)], axis=1) * np.sqrt(2)).astype(np.float32)+++def crackle(d: float, seed: int) -> tuple[np.ndarray, float]:+ """A digital crackle about `d` seconds long: (float32 (n, 2) at 48 kHz, the second it is thickest)."""+ rng = np.random.default_rng(seed)+ T = d + 0.18+ n = int(T * RATE)+ out = np.zeros((n, 2), np.float32)+ peak = 0.5 * d + 0.06+ t_now = 0.02+ while t_now < T - 0.02:+ closeness = math.exp(-((t_now - peak) / (0.45 * d + 0.02)) ** 2)+ length = rng.uniform(0.008, 0.035 + 0.03 * closeness)+ a, b = int(t_now * RATE), min(n, int((t_now + length) * RATE))+ m = b - a+ if m > 8 and rng.random() < 0.35 + 0.65 * closeness:+ hold = int(rng.integers(3, 24))+ noise = np.repeat(rng.uniform(-1, 1, m // hold + 1), hold)[:m]+ steps = rng.choice([4, 6, 8])+ crushed = np.round(noise * steps) / steps+ if rng.random() < 0.4: # a buzzing tone instead+ f = rng.uniform(90, 1400)+ crushed = np.sign(np.sin(2 * np.pi * f * np.arange(m) / RATE)) * 0.7+ gate = np.ones(m)+ k = min(m // 2, int(0.002 * RATE))+ if k > 0:+ gate[:k] = np.linspace(0, 1, k)+ gate[-k:] = np.linspace(1, 0, k)+ level = (0.35 + 0.65 * closeness) * rng.uniform(0.5, 1.0)+ out[a:b] += _stereo((crushed * gate * level).astype(np.float32), rng.uniform(-0.8, 0.8))+ t_now += length + rng.uniform(0.0, 0.03 * (1.2 - closeness))+ return out, peakdiff --git a/edit/askeditor/fx/core/hdr.py b/edit/askeditor/fx/core/hdr.pynew file mode 100644index 0000000..cd17ca4--- /dev/null+++ b/edit/askeditor/fx/core/hdr.py@@ -0,0 +1,134 @@+"""HDR footage (HLG or PQ) read as ordinary SDR, so it never comes out flat and grey.++Phones film HDR by default (an iPhone's HLG, often with Dolby Vision on top). Its numbers are+coded on another curve and in wider primaries than an ordinary video's, so a tool that reads them+as if they were ordinary BT.709 shows the picture washed out and a little grey, and the pack writes+every video as BT.709. So the reader converts first, with one table (a 3D LUT, applied by ffmpeg's+`lut3d`, which every ffmpeg build has):++1. the coded value back to light: HLG's inverse curve then its display gamma (BT.2100, a 1000-nit+ display), or PQ's curve, which is light already;+2. BT.2020's primaries to BT.709's;+3. a white becomes SDR's white, and anything brighter is rolled off smoothly into the top of the+ range instead of clipping, so walls and shirts keep their detail. Phones place a room's white+ well above broadcast's reference (203 nits): on our iPhone takes (the hotel wall, the+ train, the white room; 28 October 2026) 203 nits blew the walls out and lifted skin by half a+ stop, while 300 nits kept skin where the phone shows it and the walls white, not grey;+4. coded for an ordinary screen (BT.1886, gamma 2.4).++The table is made once per kind and kept in the pack's cache, named by everything that shapes it.+"""++from __future__ import annotations++import atexit+import hashlib+import os+import shutil+import tempfile+from pathlib import Path++import numpy as np++VERSION = 2 # raise whenever the maths below changes, so no cached table is reused+SIZE = 33+WHITE = 300.0 # nits that become SDR's white (see 3. above)+SHOULDER = 0.6 # SDR light (0-1) where the roll-off of highlights begins++# BT.2020 to BT.709, for linear light.+TO_709 = np.array([[1.6605, -0.5876, -0.0728],+ [-0.1246, 1.1329, -0.0083],+ [-0.0182, -0.1006, 1.1187]])+LUMA_2020 = np.array([0.2627, 0.6780, 0.0593])++# The names ffprobe gives a stream's transfer, and the kind each is.+TRANSFERS = {"arib-std-b67": "hlg", "smpte2084": "pq"}+++def kind(transfer: str | None) -> str:+ """"hlg", "pq", or "sdr" for anything else (BT.709, sRGB, unknown)."""+ return TRANSFERS.get((transfer or "").lower(), "sdr")+++def _hlg_light(e: np.ndarray) -> np.ndarray:+ """HLG's coded value to display light in nits, per channel (the inverse curve, then BT.2100's+ display gamma of 1.2 on a 1000-nit display)."""+ a, b = 0.17883277, 0.28466892+ c = 0.55991073+ e = np.clip(e, 0.0, 1.0)+ scene = np.where(e <= 0.5, e * e / 3.0, (np.exp((e - c) / a) + b) / 12.0)+ y = np.maximum((scene * LUMA_2020).sum(axis=-1, keepdims=True), 1e-9)+ return 1000.0 * y ** 0.2 * scene+++def _pq_light(e: np.ndarray) -> np.ndarray:+ """PQ's coded value to light in nits (SMPTE ST 2084)."""+ m1, m2 = 0.1593017578125, 78.84375+ c1, c2, c3 = 0.8359375, 18.8515625, 18.6875+ p = np.clip(e, 0.0, 1.0) ** (1.0 / m2)+ return 10000.0 * (np.maximum(p - c1, 0.0) / (c2 - c3 * p)) ** (1.0 / m1)+++def roll_off(x: np.ndarray) -> np.ndarray:+ """SDR light, linear up to SHOULDER and then easing towards 1 without ever reaching a hard clip+ (the slope is continuous at the shoulder)."""+ k = SHOULDER+ return np.where(x <= k, x, k + (1.0 - k) * (1.0 - np.exp(-(x - k) / (1.0 - k))))+++def to_sdr(coded: np.ndarray, what: str) -> np.ndarray:+ """Coded HDR R'G'B' (0-1, BT.2020) to coded SDR R'G'B' (0-1, BT.709). Shape (..., 3)."""+ light = _hlg_light(coded) if what == "hlg" else _pq_light(coded)+ rel = light / WHITE+ rel = np.einsum("ij,...j->...i", TO_709, rel)+ peak = np.maximum(rel.max(axis=-1, keepdims=True), 1e-9)+ rel = rel * (roll_off(peak) / peak) # by the brightest channel, so hues do not shift+ rel = np.clip(rel, 0.0, 1.0)+ return rel ** (1.0 / 2.4)+++def _folder() -> Path:+ from .paths import CACHE++ for folder in (CACHE / "hdr", Path(tempfile.gettempdir()) / "video-editing-hdr"):+ try:+ folder.mkdir(parents=True, exist_ok=True)+ if os.access(folder, os.W_OK):+ return folder+ except OSError:+ continue+ folder = Path(tempfile.mkdtemp(prefix="hdr-"))+ atexit.register(shutil.rmtree, folder, ignore_errors=True)+ return folder+++def lut_name(what: str) -> str:+ key = hashlib.sha1(repr((VERSION, SIZE, WHITE, SHOULDER)).encode()).hexdigest()[:10]+ return f"{what}-to-sdr-{key}.cube"+++def write_lut(folder: Path, what: str) -> Path:+ """The table for `what` ("hlg" or "pq") in `folder`, written there if it is not there yet."""+ path = Path(folder) / lut_name(what)+ if path.exists():+ return path+ g = np.linspace(0.0, 1.0, SIZE)+ b, gg, r = np.meshgrid(g, g, g, indexing="ij") # a .cube lists red fastest, then green, then blue+ table = to_sdr(np.stack([r, gg, b], axis=-1), what).reshape(-1, 3)+ lines = [f'TITLE "{what.upper()} to SDR"', f"LUT_3D_SIZE {SIZE}", "DOMAIN_MIN 0.0 0.0 0.0",+ "DOMAIN_MAX 1.0 1.0 1.0"]+ lines += [f"{v[0]:.6f} {v[1]:.6f} {v[2]:.6f}" for v in table]+ tmp = path.with_name(path.name + f".{os.getpid()}.part")+ tmp.write_text("\n".join(lines) + "\n")+ tmp.replace(path)+ return path+++def reader_filter(what: str, cwd: str | os.PathLike | None) -> tuple[str, str]:+ """The ffmpeg filter that turns coded HDR RGB (as `scale` makes it with the BT.2020 matrix, at+ 16 bits) into SDR RGB, and the folder ffmpeg must run in for the table's bare name to resolve:+ `cwd` when the caller already runs it in a folder of its own (the table is put there too),+ else the cache."""+ folder = Path(cwd) if cwd else _folder()+ path = write_lut(folder, what)+ return f"lut3d=file={path.name}:interp=tetrahedral", str(folder)diff --git a/edit/askeditor/fx/core/items.py b/edit/askeditor/fx/core/items.pynew file mode 100644index 0000000..45f3446--- /dev/null+++ b/edit/askeditor/fx/core/items.py@@ -0,0 +1,810 @@+"""Items: the things an effect shows one by one (cards, rows, steps), given or found in the words,+and the moment each one lands.++Two ways to get them, one way to time them:++- **Given** (`items=`): a `.json` file, JSON text, or an effect's own short form. `load()` reads the+ JSON, `entry()` reads one item (a name, `[email protected]`, a picture, or `{"text", "at", "image"}`).+- **Heard**: an effect's grammar finds them in the words (`tier-list`'s rankings, `in_order()`'s+ lists said in order) and returns each as a `Heard`: its words, the word that makes it known, when.+- **Timed** (`time_items`): an item given a time lands on the word that starts nearest it; one given+ none lands where it was heard, else where its name is said (`name_spans`, which finds a name the+ transcriber split or joined), else between the others, and the run says so.++Words are always `clip.words`: corrected for the transcriber's lateness, checked against the sound,+and without the words a second listen could not be sure of. `tokens()` and `card_text()` are the+pieces every grammar shares: the words as keys to match on, and a span of them as a card shows it.+"""++from __future__ import annotations++import difflib+import json+import re+from dataclasses import dataclass+from pathlib import Path+from typing import Callable, Optional, Sequence++from . import moments+from .words import Word, normalize+++class ItemsError(ValueError):+ """Items that cannot be used; the message says what to change."""+++# ---- reading the items given -----------------------------------------------------------------------++def load(spec: str, clip_dir: Path) -> tuple[object, Optional[Path]]:+ """The items as data when they are JSON: from a `.json` file (looked for as given, then beside+ the clip) or JSON text. Returns (data, the file's folder or None), or (None, None) when `spec`+ is empty or is an effect's own short form, which the effect reads itself."""+ s = spec.strip()+ if not s:+ return None, None+ if s.lower().endswith(".json") and not s.startswith(("{", "[")):+ path = None+ for candidate in (Path(s).expanduser(), clip_dir / s):+ if candidate.exists():+ path = candidate.resolve()+ break+ if path is None:+ raise ItemsError(f"there is no items file at {s}")+ try:+ return json.loads(path.read_text(encoding="utf-8")), path.parent+ except ValueError as e:+ raise ItemsError(f"{path.name} is not valid JSON: {e}") from None+ if s.startswith(("{", "[")):+ try:+ return json.loads(s), None+ except ValueError as e:+ raise ItemsError(f"the items are not valid JSON: {e}") from None+ return None, None+++def entry(raw, base: Optional[Path], clip_dir: Path) -> tuple[str, Optional[float], Optional[str]]:+ """One item: (words, time or None, picture or None). A name may carry its time (`[email protected]`);+ a name that is a picture's file name is a picture card."""+ if isinstance(raw, str):+ m = re.fullmatch(r"\s*(.*?)\s*@\s*([0-9]+(?:\.[0-9]+)?)\s*s?\s*", raw)+ name, at = (m.group(1), float(m.group(2))) if m else (raw.strip(), None)+ if re.search(r"\.(png|jpe?g|webp|gif|bmp)$", name, re.I):+ return "", at, picture(name, base, clip_dir)+ return name, at, None+ if isinstance(raw, dict):+ name = str(raw.get("text") or raw.get("name") or "").strip()+ at = raw.get("at", raw.get("time"))+ if at is not None:+ try:+ at = float(at)+ except (TypeError, ValueError):+ raise ItemsError(f"the time for {name!r} is not a number of seconds (got {at!r})") from None+ pic = raw.get("image") or raw.get("picture")+ return name, at, (picture(str(pic), base, clip_dir) if pic else None)+ raise ItemsError(f"an item must be a name or an object with text, image and at (got {raw!r})")+++def picture(name: str, base: Optional[Path], clip_dir: Path) -> str:+ """The full path of a picture named in the items: as given, beside the items file, or beside the clip."""+ tried = [Path(name).expanduser()] + ([base / name] if base else []) + [clip_dir / name]+ for p in tried:+ if p.exists():+ from PIL import Image++ try:+ with Image.open(p) as im:+ im.verify()+ except Exception:+ raise ItemsError(f"{p} is not a picture that can be read") from None+ return str(p.resolve())+ raise ItemsError(f"there is no picture at {name}")+++# ---- the words as a grammar reads them --------------------------------------------------------------++@dataclass+class Tok:+ key: str+ w: int # the word it is part of+ stop: str = "" # "." or "," when its word ends a sentence or a clause (on the word's last part)+ colon: bool = False # its word ends with ":"+ cap: bool = False # its word starts with a capital letter+++def tokens(words: list[Word], glued: set[str] = frozenset()) -> list[Tok]:+ """The words as keys to match on: lower case, a hyphenated or slashed word split in its parts,+ "espresso's" as "espresso" and "'s", and a key in `glued` stuck to "tier" ("stier") split off."""+ out = []+ for i, w in enumerate(words):+ raw = w.text.strip()+ k = normalize(raw)+ if not k:+ continue+ tail = raw.rstrip()+ stop = "." if tail.endswith((".", "?", "!")) else ("," if tail.endswith((",", ";", ":", "—", "…")) else "")+ parts = [p for p in re.split(r"[-/]", k) if p]+ expanded: list[str] = []+ for p in parts:+ m = re.fullmatch(r"(.+)'s", p)+ if m:+ expanded += [m.group(1), "'s"]+ elif len(p) > 4 and p.endswith("tier") and p[:-4] in glued: # "stier"+ expanded += [p[:-4], "tier"]+ else:+ expanded.append(p)+ for n, p in enumerate(expanded):+ last = n == len(expanded) - 1+ out.append(Tok(p, i, stop if last else "", tail.endswith(":") and last, raw[:1].isupper()))+ return out+++def card_text(words: list[Word], toks: list[Tok], a: int, b: int) -> str:+ """The words of tokens [a, b) as a card shows them: no punctuation at the edges, no "'s" carried+ over from "espresso's", and a capital letter when the transcriber wrote none."""+ w0, w1 = toks[a].w, toks[b - 1].w+ out = " ".join(words[i].clean.strip() for i in range(w0, w1 + 1)).strip().strip(",.;:!?\"“”")+ if b < len(toks) and toks[b].key == "'s" and toks[b].w == w1:+ out = re.sub(r"['’]s$", "", out)+ out = out.strip().strip(",.;:!?\"“”'’")+ if out and out == out.lower():+ out = " ".join(p[:1].upper() + p[1:] for p in out.split())+ return out+++@dataclass+class Heard:+ """An item a grammar found in the words."""+ text: str+ group: int # the effect's own grouping: a tier-list row, the number said in a list (0 when none)+ at: float # when it is known: the start of the word that makes it known+ words: tuple[int, int] # the item's own first and last word+ anchor: int # the word that makes it known (a ranking's row; a list item's first word)+ phrase: str # what was said, for a person reading the plan+++# ---- where a name is said, and when each item lands -------------------------------------------------++def squash(s: str) -> str:+ return re.sub(r"[^a-z0-9]", "", s.lower())+++def similar(a: str, b: str) -> float:+ if a == b:+ return 1.0+ if a in (b + "s", b + "es") or b in (a + "s", a + "es"):+ return 0.96+ if min(len(a), len(b)) < 4:+ return 0.0+ return difflib.SequenceMatcher(a=a, b=b, autojunk=False).ratio()+++def name_spans(words: list[Word], name: str) -> list[tuple[int, int, float]]:+ """Where `name` is said: (first word, last word, how close), closest first, then earliest. A+ name split by the transcriber ("Chat GPT") or joined ("Google Docs" as "GoogleDocs") is found."""+ target = squash(name)+ if not target:+ return []+ out = []+ for i in range(len(words)):+ acc = ""+ for j in range(i, min(len(words), i + 6)):+ acc += squash(words[j].text)+ if not acc:+ continue+ s = similar(acc, target)+ if s >= 0.84:+ out.append((i, j, s))+ if len(acc) >= len(target) + 3:+ break+ return sorted(out, key=lambda c: (-round(c[2], 2), words[c[0]].start))+++@dataclass+class Timed:+ """When one item lands, and why then."""+ n: int # the item's place in the list given+ at: float+ how: str # "given" (a time was given), "said" (its name is said), "placed" (never said), or the+ # grammar's own word for an item heard (`time_items(heard_how=…)`)+ word: str # the word it lands on, as heard+ asked: Optional[float] = None # the time it was given, before it was moved onto a word+ heard: Optional[Heard] = None+++def snap(words: list[Word], t: float, within: float = 0.25) -> tuple[float, str]:+ """`t` moved onto the start of the word that starts nearest it, when one starts within `within`+ seconds; else `t` itself. Returns (time, that word or "")."""+ if not words:+ return t, ""+ k = min(range(len(words)), key=lambda i: abs(words[i].start - t))+ if abs(words[k].start - t) <= within:+ return words[k].start, words[k].clean+ return t, ""+++def time_items(items: Sequence, words: list[Word], heard: list[Heard], duration: float,+ heard_how: str = "heard", mismatch: Optional[Callable[[object, Heard], Optional[str]]] = None,+ apart: float = 0.2, back: Optional[moments.TakenBack] = None) -> tuple[list[Timed], list[str]]:+ """Each item's moment. `items` are anything with `text`, `at` and `image`. Given a time: the word+ starting nearest it (within a quarter second). Given none: where it was heard (its `Heard`, matched+ by name), else its name where it is said, else between the others in the order given. Returns+ them in time order, two never within `apart` seconds of each other, and notes for a person.+ `mismatch(item, heard)` may return a note when an item is heard somewhere other than it was given.+ A name said where the speaker took it back (`back`, the shared picker's `moments.taken_back` of+ the clip's whole words: a word replaced, a first attempt said again, an aside) never lands+ there: on its saying that was kept, or, said nowhere else, between the others, and a note says+ so. A time given is kept as given."""+ back = moments.TakenBack() if back is None else back++ def taken(a: int, b: int) -> bool:+ return back.holds(words, a, b)++ notes: list[str] = []+ out: list[Optional[Timed]] = [None] * len(items)+ used: set[int] = set()+ said_back: set[int] = set() # the items whose name is said only where the speaker took it back+ for n, it in enumerate(items):+ if it.at is not None:+ if not 0 <= it.at <= duration:+ raise ItemsError(f"{it.text or 'a picture'} is given {it.at:g} s, outside the clip's {duration:.2f} s")+ at, word = snap(words, it.at)+ out[n] = Timed(n, at, "given", word, asked=it.at)+ # Names said in the clip, the longest first so "Town car" is found before "Town".+ order = sorted((n for n, it in enumerate(items) if it.at is None and it.text), key=lambda n: -len(squash(items[n].text)))+ for n in order:+ it = items[n]+ found = [f for f in heard if similar(squash(f.text), squash(it.text)) >= 0.84+ and not any(i in used for i in range(f.words[0], f.words[1] + 1))]+ kept = [g for g in found if not taken(g.words[0], g.words[1])]+ if found and not kept:+ said_back.add(n)+ if kept:+ f = kept[-1]+ used.update(range(f.words[0], f.words[1] + 1))+ out[n] = Timed(n, f.at, heard_how, words[f.anchor].clean, heard=f)+ note = mismatch(it, f) if mismatch is not None else None+ if note:+ notes.append(note)+ continue+ for i, j, _ in name_spans(words, it.text):+ if any(k in used for k in range(i, j + 1)):+ continue+ if taken(i, j):+ said_back.add(n)+ continue+ used.update(range(i, j + 1))+ out[n] = Timed(n, words[i].start, "said", " ".join(words[k].clean for k in range(i, j + 1)))+ break+ # Never said, or a picture with no words: between the items before and after it in the order+ # given, on a word, and the run says so.+ for n, it in enumerate(items):+ if out[n] is not None:+ continue+ before = [c.at for c in out[:n] if c is not None]+ after = [c.at for c in out[n + 1:] if c is not None]+ lo = max(before) if before else (words[0].start if words else 0.0)+ hi = min([a for a in after if a > lo], default=(words[-1].start if words else duration))+ target = (lo + hi) / 2 if hi > lo else min(duration - 0.5, lo + 0.8)+ at, word = snap([w for w in words if w not in back], target)+ out[n] = Timed(n, at, "placed", word)+ what = it.text or Path(it.image or "").name+ said = "is said only where you took it back" if n in said_back else "is never said"+ notes.append(f"{what!r} {said}, so it drops in at {at:.2f} s; give it a time with {what}@seconds")+ timed = sorted((c for c in out if c is not None), key=lambda c: c.at)+ for k in range(1, len(timed)):+ if timed[k].at - timed[k - 1].at < apart:+ timed[k].at = timed[k - 1].at + apart+ return timed, notes+++# ---- lists said in order ------------------------------------------------------------------------------+#+# A list is said with markers: "number five", "step two", "tip number three", "first", "the second+# thing", "lastly", "and finally", a bare "Five, Canva.", or "then" and "next" once a list is under+# way. "Then" alone starts a list only as a chain ("drop your clip in, then type, then pick"): the+# clause before the first "then" is the first item. A run of items after a colon or with commas and+# a last "and" ("three apps: Notion, Figma and Canva") is a list too. Each item is the clause after+# its marker, without the words that only lead into it ("is going to be", "you want", "we have").+# What is never a list: a "then" after "if" or "when", "the first time", "a second", "a number of",+# a count with nothing after its numbers ("one, two, three, test").++CARDINALS = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9,+ "ten": 10, "eleven": 11, "twelve": 12, "thirteen": 13, "fourteen": 14, "fifteen": 15, "sixteen": 16,+ "seventeen": 17, "eighteen": 18, "nineteen": 19, "twenty": 20}+ORDINALS = {"first": 1, "firstly": 1, "1st": 1, "second": 2, "secondly": 2, "2nd": 2, "third": 3, "thirdly": 3, "3rd": 3,+ "fourth": 4, "fourthly": 4, "4th": 4, "fifth": 5, "fifthly": 5, "5th": 5, "sixth": 6, "6th": 6,+ "seventh": 7, "7th": 7, "eighth": 8, "8th": 8, "ninth": 9, "9th": 9, "tenth": 10, "10th": 10}+LAST = {"lastly", "finally"}+# What a numbered item is called: "step two", "tip number three", "the first thing".+LIST_NOUNS = {"step", "tip", "rule", "point", "reason", "thing", "lesson", "mistake", "hack", "tool", "idea", "secret",+ "habit", "way", "part", "pick", "app", "option", "item", "question", "trick", "sign", "spot", "place",+ "one", "stop", "day", "phase", "stage", "move", "fact", "myth", "book", "product", "feature"}+_DETERMINERS = {"the", "my", "our", "your", "their", "his", "her", "a", "an", "this"}+# Words that start a clause without saying anything yet ("and then", "so first", "okay, number one").+_LEADERS = {"and", "so", "okay", "ok", "um", "uh", "erm", "well", "now", "but", "alright", "right", "at", "coming",+ "in", "plus", "also", "oh"}+_SUBJECTS = {"i", "we", "you", "they", "he", "she"}+# Words that only lead into an item: "number one is going to be X", "first, you want X", "we have X".+_FILLERS = {"um", "uh", "erm", "so", "and", "okay", "ok", "well", "now", "like", "just", "simply", "basically",+ "actually", "eventually", "finally", "then", "really", "also", "definitely", "obviously", "of", "course",+ "oh"}+_PRONOUNS = {"i", "we", "you", "they", "it", "he", "she"}+_AUX = {"is", "are", "was", "were", "'s", "would", "will", "be", "going", "to", "gonna", "'ll", "'d", "can", "could",+ "should", "must", "might", "shall"}+_HAVE = {"we've", "i've", "you've", "they've", "have", "has"}+_SAY_THERE = {"there", "here", "that", "this"} # "there's", "that's": with the "'s" after them+# An item whose first word, once the lead-in is gone, is one of these said nothing ("and then I was like").+_EMPTY_START = {"there", "here", "it", "that", "this", "like", "so", "okay", "ok", "kind", "sort", "yeah", "yes", "no",+ "um", "uh", "something", "anything", "stuff", "things", "one", "two", "three", "four", "five", "six",+ "seven", "eight", "nine", "ten", "again", "too"}+# What ends an item's clause once it has two words: "I went to the station and for a while I waited".+_CLAUSE_ENDS = {"and", "but", "so", "because", "while", "which", "when", "where", "until", "once", "though",+ "although", "whereas", "cause", "'cause", "before", "after", "if"}+# A clause never ends on these: "went to, of course, my hotel" runs on past the aside.+_OPEN_ENDED = {"to", "of", "at", "in", "on", "for", "with", "from", "into", "onto", "the", "a", "an", "my", "your", "our",+ "their", "his", "her", "its", "and", "or", "by", "about", "is", "are", "was"}+_ASIDES = {"of", "course", "um", "uh", "erm", "like", "you", "know", "basically", "actually", "i", "mean"}+_CONDITIONS = {"if", "when", "whenever", "once", "unless"}+_NOT_NEXT = {"week", "time", "year", "month", "day", "video", "episode", "morning", "night", "weekend", "one"}+MAX_ITEM_WORDS = 8+RUN_GAP = 25.0 # seconds between two items of one list, at most+CHAIN_STEP = 8.0 # a chain of "then"s with no list opened before it is said briskly: this far apart at most+CHAIN_LEAD = 6.0 # the clause before a chain's first "then" counts when it started this close before it+_SUBORDINATE = {"but", "because", "so", "which", "when", "while", "if", "although", "though", "since", "as",+ "where", "unless", "until", "whereas", "cause"}+++@dataclass+class Step(Heard):+ """One item of a list said in order (a `Heard`: `group` is the number said, 0 when none)."""+ marker: str = "" # the words that mark it, as said ("Number five", "then"); "" for a chain's first+ marker_at: float = 0.0 # when its marker starts: where the next item starts, for a checklist's tick+ ends: float = 0.0 # when its own words end+ kind: str = "" # number, step, ordinal, last, count, then, lead or series+++@dataclass+class _Mark:+ kind: str+ number: int+ a: int # its first token+ b: int # the token after it+ loose: bool = False # "X and then Y" mid-sentence: an item only inside a list already under way+++def _cardinal(key: str) -> Optional[int]:+ if key in CARDINALS:+ return CARDINALS[key]+ if re.fullmatch(r"[0-9]{1,2}", key):+ return int(key)+ return None+++def _clause_start(toks: list[Tok], j: int) -> bool:+ """Token j begins a clause: it is the first, or only leaders ("and", "so", "okay") stand between+ it and the end of the last clause."""+ k = j - 1+ while k >= 0:+ if toks[k].stop:+ return True+ if toks[k].key not in _LEADERS:+ return False+ k -= 1+ return True+++def _after_subject(toks: list[Tok], j: int) -> bool:+ """Token j follows a subject that begins its clause: "I then boarded", "we finally got"."""+ return j >= 1 and toks[j - 1].key in _SUBJECTS and not toks[j - 1].stop and _clause_start(toks, j - 1)+++def _conditional(toks: list[Tok], j: int) -> bool:+ """"then" in "if you want X, then ask": a condition said earlier in the same sentence."""+ k = j - 1+ while k >= 0 and toks[k].stop != ".":+ if toks[k].key in _CONDITIONS:+ return True+ k -= 1+ return False+++def _mark_at(toks: list[Tok], j: int) -> Optional[_Mark]:+ t = toks[j]+ nxt = toks[j + 1] if j + 1 < len(toks) else None+ prev = toks[j - 1] if j >= 1 else None+ # "number five", "at number three", "No. 2"+ if t.key in ("number", "no", "num") and nxt is not None and not t.stop:+ n = _cardinal(nxt.key)+ if n is not None and not (prev is not None and prev.key == "a" and not prev.stop):+ after = toks[j + 2] if j + 2 < len(toks) else None+ if not (after is not None and after.key == "of" and not nxt.stop):+ return _Mark("number", n, j, j + 2)+ # "step two", "tip number three", "reason 4"+ if t.key in LIST_NOUNS and t.key != "one" and nxt is not None and not t.stop:+ k = j + 1+ if nxt.key == "number" and not nxt.stop and k + 1 < len(toks):+ k += 1+ n = _cardinal(toks[k].key)+ if n is not None and (prev is None or prev.key not in ("a", "an") or prev.stop):+ return _Mark("step", n, j, k + 1)+ # "first", "firstly", "first of all", "the second thing", "my first pick", "lastly", "and finally"+ if t.key in ORDINALS or t.key in LAST or t.key in ("last", "final", "next"):+ number = ORDINALS.get(t.key, 0)+ kind = "ordinal" if t.key in ORDINALS else ("then" if t.key == "next" else "last")+ a = j+ if prev is not None and prev.key in _DETERMINERS and not prev.stop:+ # "the first thing", "my first pick", "the last step": only with the name of an item after it+ if not (nxt is not None and nxt.key in LIST_NOUNS and not t.stop) or prev.key in ("a", "an"):+ return None+ if not _clause_start(toks, j - 1) and not (j >= 2 and toks[j - 2].key in ("is", "was", "'s")):+ return None+ return _Mark(kind, number, j - 1, j + 2)+ if t.key == "next" and nxt is not None and nxt.key in _NOT_NEXT:+ return None+ if t.key == "last" and not (nxt is not None and nxt.key in ("but", "one", "thing", "step", "up")+ or t.stop):+ return None+ if not _clause_start(toks, j) and not (t.key in ("finally", "lastly") and _after_subject(toks, j)):+ return None+ b = j + 1+ if t.key in ("first", "last") and b + 1 < len(toks) and toks[b].key in ("of", "but") and not t.stop:+ b += 2 if toks[b].key == "of" else 3 # "first of all", "last but not least"+ elif b < len(toks) and toks[b].key in ("off", "up", "thing", "things", "step", "one") and not t.stop:+ b += 1 # "first off", "next up", "first thing", "last one"+ return _Mark(kind, number, a, b)+ # "then", "and then", "after that", "afterwards", "from there", "I then boarded", "I eventually went"+ if t.key in ("then", "afterwards", "eventually") or (t.key == "after" and nxt is not None and nxt.key == "that"):+ if t.key == "then" and (_conditional(toks, j) or (nxt is not None and nxt.key == "again")):+ return None+ if _clause_start(toks, j) or _after_subject(toks, j):+ return _Mark("then", 0, j, j + (2 if t.key == "after" else 1))+ if t.key == "then" and prev is not None and prev.key == "and" and not prev.stop:+ return _Mark("then", 0, j - 1, j + 1, loose=True)+ return None+ if t.key == "from" and nxt is not None and nxt.key == "there" and _clause_start(toks, j):+ return _Mark("then", 0, j, j + 2)+ # A bare count at the start of a clause, with a stop after it: "Five, Canva."+ n = _cardinal(t.key)+ if n is not None and t.stop and _clause_start(toks, j) and nxt is not None and _cardinal(nxt.key) is None:+ return _Mark("count", n, j, j + 1)+ return None+++def _lead_in(toks: list[Tok], b: int, limit: int) -> int:+ """The first token of the item itself, from token b: fillers, a subject and its helping verbs,+ "you want", "we've got", "there's", "is going to be" and an article are skipped."""+ a = b+ subject = False+ while a < limit:+ t = toks[a]+ nxt = toks[a + 1].key if a + 1 < limit else ""+ if t.key in _FILLERS and not (t.key == "of" and nxt != "course") and not (t.key == "course" and a == b):+ pass+ elif t.key in _PRONOUNS and not subject:+ subject = True+ elif t.key in _AUX:+ pass+ elif t.key in ("want", "need") and subject:+ pass+ elif t.key in _HAVE and (subject or a == b or toks[a - 1].key in _PRONOUNS):+ subject = True+ elif t.key == "got" and a > b and toks[a - 1].key in _HAVE:+ pass+ elif t.key in _SAY_THERE and nxt == "'s":+ pass+ elif t.key in ("comes", "goes", "the", "a", "an"):+ pass+ else:+ break+ if t.stop == "." and a + 1 < limit:+ return limit # the sentence ended before anything was named+ a += 1+ return a+++def _item_span(toks: list[Tok], b: int, limit: int) -> Optional[tuple[int, int]]:+ """The item said from token b (before token `limit`): the lead-in skipped, to the end of its clause."""+ a = _lead_in(toks, b, limit)+ if a >= limit or toks[a].key in _EMPTY_START:+ return None+ e = a+ while e < limit:+ t = toks[e]+ n_words = toks[e].w - toks[a].w + 1+ if e > a and t.key in _CLAUSE_ENDS and n_words >= 3:+ break+ if n_words > MAX_ITEM_WORDS:+ break+ e += 1+ if t.stop:+ if t.key in _OPEN_ENDED and t.stop != "." and e < limit:+ # "went to, of course, my hotel": past the aside to the words it was leading to+ k = e+ while k < limit and toks[k].key in _ASIDES:+ k += 1+ if k < limit and k > e - 1:+ e = k+ continue+ break+ # a clause cut short (by "and", by its length, by the next marker) never ends on a word that+ # leads somewhere; one that ends where the speaker stopped keeps its last word ("care about")+ if not toks[e - 1].stop:+ while e - 1 > a and toks[e - 1].key in _OPEN_ENDED:+ e -= 1+ return (a, e) if e > a else None+++def _words_of(words: list[Word], toks: list[Tok], a: int, b: int) -> str:+ """Tokens [a, b) as an item shows them, with any aside the clause ran past left out."""+ keep = []+ k = a+ while k < b:+ if toks[k].key in ("of",) and k + 1 < b and toks[k + 1].key == "course":+ k += 2+ continue+ if toks[k].key in ("um", "uh", "erm"):+ k += 1+ continue+ keep.append(toks[k].w)+ k += 1+ seen, idx = set(), []+ for w in keep:+ if w not in seen:+ seen.add(w)+ idx.append(w)+ out = " ".join(words[i].clean.strip().strip(",.;:!?\"“”") for i in idx).strip()+ out = re.sub(r"\s+", " ", out)+ return out[:1].upper() + out[1:] if out else out+++def _step(words, toks, mark: Optional[_Mark], span: tuple[int, int], kind: str, number: int) -> Step:+ a, b = span+ w0, w1 = toks[a].w, toks[b - 1].w+ m_at = words[toks[mark.a].w].start if mark is not None else words[w0].start+ m_txt = " ".join(words[i].clean for i in range(toks[mark.a].w, toks[mark.b - 1].w + 1)) if mark is not None else ""+ lo = toks[mark.a].w if mark is not None else w0+ phrase = " ".join(words[i].text.strip() for i in range(lo, w1 + 1))+ return Step(_words_of(words, toks, a, b), number, words[w0].start, (w0, w1), w0, phrase,+ marker=m_txt.strip(",.;: "), marker_at=m_at, ends=words[w1].end, kind=kind)+++def _sentence_before(toks: list[Tok], j: int) -> int:+ """The first token of the sentence that token j sits in."""+ k = j - 1+ while k >= 0 and toks[k].stop != ".":+ k -= 1+ return k + 1+++def _series(words: list[Word], toks: list[Tok]) -> list[list[Step]]:+ """Items run together in one sentence: after a colon ("three apps: Notion, Figma and Canva"), or+ three or more parts with commas and a last "and" or "or" ("picks your best line, cuts you out,+ and pops you right out")."""+ out = []+ j = 0+ while j < len(toks):+ s = j+ while j < len(toks) and toks[j].stop != ".":+ j += 1+ e = min(len(toks), j + 1) # the sentence is tokens [s, e)+ j = e+ colon = next((k for k in range(s, e) if toks[k].colon), None)+ start = colon + 1 if colon is not None else s+ parts, cur = [], []+ for k in range(start, e):+ t = toks[k]+ if t.key in ("and", "or") and cur and k + 1 < e:+ parts.append(cur)+ cur = []+ continue+ cur.append(k)+ if t.stop == ",":+ parts.append(cur)+ cur = []+ if cur:+ parts.append(cur)+ parts = [p for p in parts if p]+ commas = sum(1 for k in range(start, e - 1) if toks[k].stop == ",")+ if colon is None and commas < 1:+ continue+ joined = colon is not None or any(toks[k].key in ("and", "or") and k > start for k in range(start, e)+ if toks[k - 1].stop == "," or (k + 1 < e and parts and k < parts[-1][0]))+ spans = []+ for p in parts:+ a, b = p[0], p[-1] + 1+ while a < b and toks[a].key in ("for", "example", "or", "and", "such", "as", "including"):+ a += 1+ if a < b and toks[a].key in _SUBORDINATE:+ spans = []+ break+ a = _lead_in(toks, a, b)+ if a >= b:+ if spans: # an empty part after the first: not a run of items+ spans = []+ break+ continue # an introduction ("for example,", "oh,")+ while b - 1 > a and toks[b - 1].key in _OPEN_ENDED:+ b -= 1+ if toks[b - 1].w - toks[a].w + 1 > 7 or (b - a == 1 and _cardinal(toks[a].key) is not None):+ spans = []+ break+ spans.append((a, b))+ last_joined = len(parts) >= 2 and any(toks[k].key in ("and", "or") for k in range(parts[-2][-1] + 1, parts[-1][0] + 1))+ if not (colon is not None or last_joined):+ continue+ if len(spans) >= 3 or (colon is not None and len(spans) >= 2):+ out.append([_step(words, toks, None, sp, "series", 0) for sp in spans])+ return out+++def lists(words: list[Word]) -> list[list[Step]]:+ """Every list said in the words, in the order said: each two items or more."""+ toks = tokens(words)+ marks = []+ j = 0+ while j < len(toks):+ m = _mark_at(toks, j)+ if m is not None:+ marks.append(m)+ j = m.b+ else:+ j += 1+ starts = [m.a for m in marks]+ runs: list[list[Step]] = []+ cur: list[Step] = []+ chain: list[tuple[_Mark, Step]] = [] # "then"s heard before any list started++ def close() -> None:+ nonlocal cur+ kept = _dedupe(cur)+ if len(kept) >= 2:+ runs.append(kept)+ cur = []++ for i, m in enumerate(marks):+ limit = starts[i + 1] if i + 1 < len(marks) else len(toks)+ span = _item_span(toks, m.b, limit)+ if span is None:+ continue+ step = _step(words, toks, m, span, m.kind, m.number)+ strong = m.kind in ("number", "step", "ordinal", "count", "last")+ if cur and step.marker_at - cur[-1].marker_at > RUN_GAP:+ close()+ if m.loose and not cur:+ continue+ if strong:+ numbers = [s.group for s in cur if s.group]+ restart = False+ if numbers and step.group:+ last = numbers[-1]+ way = (numbers[-1] - numbers[-2]) if len(numbers) >= 2 else 0+ carries = (step.group - last) * way > 0 if way else abs(step.group - last) == 1+ restart = not carries+ if restart or (m.kind == "last" and not cur and not chain):+ close()+ if m.kind == "last":+ continue+ if not cur and chain:+ chain = []+ cur.append(step)+ continue+ # a "then": part of the list under way, or a chain+ if cur:+ cur.append(step)+ continue+ if chain and step.marker_at - chain[-1][1].marker_at > CHAIN_STEP:+ chain = []+ chain.append((m, step))+ if len(chain) >= 2:+ first_mark = chain[0][0]+ s0 = _sentence_before(toks, first_mark.a)+ lead = _item_span(toks, s0, first_mark.a)+ if lead is not None and chain[0][1].marker_at - words[toks[lead[0]].w].start <= CHAIN_LEAD:+ cur = [_step(words, toks, None, lead, "lead", 0)] + [s for _, s in chain]+ else:+ cur = [s for _, s in chain]+ chain = []+ close()+ marked = runs+ series = _series(words, toks)+ taken = {w for r in marked for s in r for w in range(s.words[0], s.words[1] + 1)}+ for r in series:+ if not any(w in taken for s in r for w in range(s.words[0], s.words[1] + 1)):+ marked.append(r)+ return sorted(marked, key=lambda r: r[0].marker_at)+++def _dedupe(run: list[Step]) -> list[Step]:+ """A retake keeps the item said last: "Then just say…", then "Then just say the look you want"."""+ out: list[Step] = []+ for s in run:+ if out:+ a, b = squash(out[-1].text), squash(s.text)+ if a and b and (b.startswith(a) or a.startswith(b)) and s.group == out[-1].group:+ out[-1] = s if len(b) >= len(a) else out[-1]+ continue+ out.append(s)+ return out+++def in_order(words: list[Word]) -> list[Step]:+ """The list said in the words: the longest run of items (marked ones before a run of commas), the+ later on a tie, since a retake is usually the better take. [] when none is said."""+ runs = lists(words)+ if not runs:+ return []+ return max(runs, key=lambda r: (r[0].kind != "series", len(r), sum(len(s.text) for s in r), r[0].marker_at))+++# Said once a step is done: "Done.", "Check.", "and that's it", "sorted".+DONE = {"done", "check", "checked", "tick", "ticked", "sorted", "finished", "complete", "completed", "boom", "nailed",+ "easy", "ready", "dusted"}+_DONE_PHRASES = (("that", "'s", "it"), ("that", "'s", "done"), ("all", "done"), ("job", "done"), ("we're", "done"),+ ("it", "'s", "done"), ("there", "we", "go"))+++def done_after(words: list[Word], steps: list[Step]) -> list[Optional[tuple[float, int]]]:+ """For each step, the word that says it is done, as (its start, its index), or None: a done word+ standing on its own after the step's words ("Plug in the mic. Done.", "press record, and that's+ it"), before the next step's marker (within six seconds for the last)."""+ toks = tokens(words)+ out: list[Optional[tuple[float, int]]] = []+ for n, s in enumerate(steps):+ until = steps[n + 1].marker_at if n + 1 < len(steps) else s.ends + 6.0+ found = None+ for k, t in enumerate(toks):+ w = words[t.w]+ if t.w <= s.words[1] or w.start >= until:+ continue+ alone = t.stop != "" or k + 1 >= len(toks) or toks[k + 1].stop == "." or (k >= 1 and toks[k - 1].stop != "")+ if t.key in DONE and alone and t.key != "ready":+ found = (w.start, t.w)+ break+ for ph in _DONE_PHRASES:+ if [x.key for x in toks[k:k + len(ph)]] == list(ph):+ found = (w.start, t.w)+ break+ if found:+ break+ out.append(found)+ return out+++# ---- an item made shorter, never cut inside a word ------------------------------------------------------++_SOFT_WORDS = {"just", "really", "actually", "basically", "simply", "literally", "very", "pretty", "quite", "also",+ "even", "eventually", "finally", "then", "like", "so", "totally", "definitely", "obviously"}+_ARTICLE_WORDS = {"the", "a", "an", "my", "your", "our", "their", "his", "her", "its", "some"}+++def shorter(text: str) -> list[str]:+ """`text`, then lighter forms of it: without the softeners ("just", "really", "of course"), then+ without articles ("the", "your"). Every form is whole words; repeats are left out."""+ words = text.split()+ forms = [" ".join(words)]+ cleaned = " ".join(text.replace(", of course,", "").replace("of course", "").split())+ soft = [w for w in cleaned.split() if normalize(w) not in _SOFT_WORDS] or cleaned.split()+ forms.append(" ".join(soft))+ lean = [w for i, w in enumerate(soft) if normalize(w) not in _ARTICLE_WORDS or i == len(soft) - 1] or soft+ forms.append(" ".join(lean))+ out = []+ for f in forms:+ f = f[:1].upper() + f[1:]+ if f and f not in out:+ out.append(f)+ return out+++def cut_to(text: str, fits: Callable[[str], bool], mark: str = "…") -> str:+ """The most of `text` that fits, cut only between words and never after a word that leads+ somewhere ("to", "the"), with `mark` where words were left off. The first word alone if nothing+ shorter fits."""+ words = text.split()+ for n in range(len(words), 0, -1):+ head = words[:n]+ while len(head) > 1 and normalize(head[-1]) in _OPEN_ENDED:+ head = head[:-1]+ cand = " ".join(head).rstrip(",;:") + ("" if len(head) == len(words) else mark)+ if fits(cand):+ return cand+ return words[0] if words else textdiff --git a/edit/askeditor/fx/core/layout.py b/edit/askeditor/fx/core/layout.pynew file mode 100644index 0000000..e5b86cc--- /dev/null+++ b/edit/askeditor/fx/core/layout.py@@ -0,0 +1,176 @@+"""The safe zone, and placing text where it never covers the face.++Instagram's safe zone, the rule every effect keeps: important text sits between x = 120 and+x = 960 on a 1080-wide frame and above the bottom fifth, where the caption and buttons sit. The top+tenth holds the app's own bar, so text stays below it too. On any other size the same fractions+apply.++**A panel's own safe part.** When an effect is drawn inside one panel of a layout (a chart in the+top half of a split screen), its frame is the panel, and the app's fractions of the panel are not+where text is safe on the screen. The layout says where it is with `zone_for(w, h, rect)`; inside+that block every `SafeZone(w, h)` of that size is `rect`, so the effects prepared there keep to it+without knowing they are inside anything.+"""++from __future__ import annotations++import contextlib+from contextvars import ContextVar+from dataclasses import dataclass+from typing import Iterable, Optional, Sequence+++@dataclass(frozen=True)+class Rect:+ x0: float+ y0: float+ x1: float+ y1: float++ @property+ def w(self) -> float:+ return self.x1 - self.x0++ @property+ def h(self) -> float:+ return self.y1 - self.y0++ @property+ def cx(self) -> float:+ return (self.x0 + self.x1) / 2++ @property+ def cy(self) -> float:+ return (self.y0 + self.y1) / 2++ def intersects(self, other: "Rect", margin: float = 0.0) -> bool:+ return (self.x0 - margin < other.x1 and other.x0 < self.x1 + margin+ and self.y0 - margin < other.y1 and other.y0 < self.y1 + margin)++ def overlap(self, other: "Rect") -> float:+ w = min(self.x1, other.x1) - max(self.x0, other.x0)+ h = min(self.y1, other.y1) - max(self.y0, other.y0)+ return max(0.0, w) * max(0.0, h)++ def inside(self, other: "Rect", slack: float = 0.5) -> bool:+ return (self.x0 >= other.x0 - slack and self.x1 <= other.x1 + slack+ and self.y0 >= other.y0 - slack and self.y1 <= other.y1 + slack)++ def union(self, other: "Rect") -> "Rect":+ return Rect(min(self.x0, other.x0), min(self.y0, other.y0), max(self.x1, other.x1), max(self.y1, other.y1))++ def grow(self, left: float, top: float, right: float, bottom: float) -> "Rect":+ return Rect(self.x0 - left, self.y0 - top, self.x1 + right, self.y1 + bottom)++ def shift(self, dx: float, dy: float) -> "Rect":+ return Rect(self.x0 + dx, self.y0 + dy, self.x1 + dx, self.y1 + dy)++ def scale(self, sx: float, sy: float, dx: float = 0.0, dy: float = 0.0) -> "Rect":+ """Map into another frame: x' = x * sx + dx."""+ return Rect(self.x0 * sx + dx, self.y0 * sy + dy, self.x1 * sx + dx, self.y1 * sy + dy)++ def as_list(self) -> list[float]:+ return [round(self.x0, 1), round(self.y0, 1), round(self.x1, 1), round(self.y1, 1)]++ @staticmethod+ def of(values: Sequence[float]) -> "Rect":+ return Rect(*map(float, values[:4]))++ @staticmethod+ def around(rects: Iterable["Rect"]) -> Optional["Rect"]:+ out = None+ for r in rects:+ out = r if out is None else out.union(r)+ return out+++# The safe parts given for frames that are panels of a layout: ((width, height), rect), newest last.+_GIVEN: ContextVar[tuple] = ContextVar("given_safe_zones", default=())+++def zone_for(width: int, height: int, rect: Rect):+ """Inside this block, `SafeZone(width, height)` is `rect` (in that frame's own pixels) rather+ than the app's fractions of it. Frames of any other size are not touched."""+ size = (int(round(width)), int(round(height)))+ token = _GIVEN.set(_GIVEN.get() + ((size, rect),))+ try:+ yield+ finally:+ _GIVEN.reset(token)+++class SafeZone:+ LEFT = 120 / 1080+ RIGHT = 960 / 1080+ TOP = 0.10+ BOTTOM = 0.80++ def __init__(self, width: int, height: int):+ self.width, self.height = width, height+ self.rect = Rect(width * self.LEFT, height * self.TOP, width * self.RIGHT, height * self.BOTTOM)+ size = (int(round(width)), int(round(height)))+ for given, rect in reversed(_GIVEN.get()):+ if given == size:+ self.rect = rect+ break++ def contains(self, r: Rect) -> bool:+ return r.inside(self.rect)+++def halo_room(room: Rect, zone: Rect, halo: tuple[float, float, float, float]) -> Rect:+ """Where a thing whose drawing (its shadow, say) reaches `halo` (left, top, right, bottom) past its+ box may go in `room` so that the drawing stays inside the safe zone `zone`: the room, kept `halo`+ in from the zone's edges. A side of the room inside the zone (towards the head, a neighbour) is+ left as it is, since a shadow may fall towards it."""+ left, top, right, bottom = halo+ x0, y0 = max(room.x0, zone.x0 + left), max(room.y0, zone.y0 + top)+ x1, y1 = min(room.x1, zone.x1 - right), min(room.y1, zone.y1 - bottom)+ return Rect(x0, y0, max(x0, x1), max(y0, y1))+++@dataclass(frozen=True)+class Placement:+ rect: Rect+ where: str # "chest", "lower-third", "top" or "fallback"+++ORDERS = {+ "auto": ("chest", "lower-third", "top"),+ "bottom": ("lower-third", "chest", "top"),+ "top": ("top", "chest", "lower-third"),+}+++def place(block_w: float, block_h: float, zone: SafeZone, head: Optional[Rect],+ order: Sequence[str] = ORDERS["auto"], gap: Optional[float] = None) -> Optional[Placement]:+ """Where a block of `block_w` x `block_h` goes: centred across the safe zone, at the first spot+ in `order` that stays inside the zone and clear of `head` (the head's box over every frame the+ block is on screen). None when no spot fits; the caller then makes the block smaller."""+ z = zone.rect+ gap = zone.height * 0.02 if gap is None else gap+ if block_w > z.w + 0.5 or block_h > z.h + 0.5:+ return None+ x0 = z.cx - block_w / 2+ for where in order:+ if head is None:+ # No face found: the lower third is the usual place.+ y1 = z.y1 - zone.height * 0.01+ return Placement(Rect(x0, y1 - block_h, x0 + block_w, y1), "lower-third")+ if where == "chest":+ y0 = max(head.y1 + gap, z.y0)+ r = Rect(x0, y0, x0 + block_w, y0 + block_h)+ elif where == "lower-third":+ y1 = z.y1 - zone.height * 0.01+ r = Rect(x0, y1 - block_h, x0 + block_w, y1)+ if r.y0 < head.y1 + gap:+ continue+ elif where == "top":+ y1 = min(head.y0 - gap, z.y1)+ r = Rect(x0, y1 - block_h, x0 + block_w, y1)+ else:+ continue+ if zone.contains(r) and not r.intersects(head):+ return Placement(r, where)+ return Nonediff --git a/edit/askeditor/fx/core/loudness.py b/edit/askeditor/fx/core/loudness.pynew file mode 100644index 0000000..d6c6455--- /dev/null+++ b/edit/askeditor/fx/core/loudness.py@@ -0,0 +1,256 @@+"""The loudness of a finished mix: measured and set with ffmpeg's `loudnorm`, in two passes.++The first pass measures the mix (integrated loudness, true peak, range). The second applies one+gain to reach the target, and is asked to stay linear: the same gain everywhere, so nothing in the+mix moves. `loudnorm` only stays linear when that gain would not push the true peak over the+ceiling; otherwise it quietly switches to a dynamic mode that rides the level up and down (it+pumps). So before the second pass the few peaks that would go over are brought down here, by a+true-peak limiter that looks ahead and lets go slowly, and the mix is measured again.++True peak is the height the waveform reaches between its samples, which is what a player's+converter and a platform's encoder see. It is estimated here at four times the sample rate.++ python -m fx.core.loudness <file> # print the integrated loudness and the true peak+"""++from __future__ import annotations++import json+import subprocess+from typing import Optional+import sys+import tempfile+from dataclasses import dataclass+from pathlib import Path++import numpy as np++from .video import AUDIO_RATE, MediaError, need_ffmpeg++# The video's own sound is encoded (AAC), and so is every upload again, and a coded waveform can+# overshoot the one it was given: by 0.54 dB on the airport clip at 128 kbps, and by 1.1 dB on the+# hotel clip, a quiet voice lifted 12 dB and limited hard (28 October 2026). The mix starts this far+# under the ceiling a person asks for; a trial encode then says whether that was enough.+ENCODE_ROOM = 1.0+LRA = 11.0 # loudnorm's loudness-range target; it plays no part in the linear pass+++@dataclass(frozen=True)+class Measure:+ i: float # integrated loudness, LUFS+ tp: float # true peak, dBTP+ lra: float # loudness range, LU+ thresh: float # the gate's threshold, LUFS+ offset: float # loudnorm's own offset for a second pass++ def as_dict(self) -> dict:+ return {"lufs": round(self.i, 2), "true_peak_dbtp": round(self.tp, 2), "lra": round(self.lra, 2)}+++def _json_tail(text: str) -> dict:+ try:+ return json.loads(text[text.rindex("{"):text.rindex("}") + 1])+ except ValueError:+ raise MediaError("ffmpeg's loudnorm did not report a measurement") from None+++def _number(v) -> float:+ try:+ return float(v)+ except (TypeError, ValueError): # "-inf" for silence+ return -99.0+++def _measure_args(src: list[str]) -> Measure:+ need_ffmpeg()+ run = subprocess.run(["ffmpeg", "-hide_banner", "-nostdin", *src, "-vn", "-af",+ f"loudnorm=I=-14:TP=-1:LRA={LRA}:print_format=json", "-f", "null", "-"],+ capture_output=True, text=True)+ if run.returncode != 0:+ raise MediaError("ffmpeg could not measure the loudness")+ d = _json_tail(run.stderr)+ return Measure(_number(d["input_i"]), _number(d["input_tp"]), _number(d["input_lra"]),+ _number(d["input_thresh"]), _number(d["target_offset"]))+++def _raw(samples: np.ndarray, folder: str, name: str) -> list[str]:+ path = Path(folder) / name+ np.ascontiguousarray(samples, np.float32).tofile(path)+ return ["-f", "f32le", "-ar", str(AUDIO_RATE), "-ac", str(samples.shape[1]), "-i", str(path)]+++def measure(samples: np.ndarray) -> Measure:+ """The first pass: loudnorm's measurement of 48 kHz float samples (n, channels)."""+ with tempfile.TemporaryDirectory(prefix="fx-loud-") as tmp:+ return _measure_args(_raw(samples, tmp, "mix.f32"))+++def measure_file(path: str | Path) -> Measure:+ """loudnorm's measurement of a file's sound: what a finished video is checked with."""+ return _measure_args(["-i", str(path)])+++# ---- true peak and the limiter -------------------------------------------------------------------++def _oversampler(factor: int = 4, taps: int = 12) -> np.ndarray:+ """A windowed-sinc interpolator: `factor` phases of `taps` taps each."""+ n = factor * taps+ m = np.arange(n) - (n - 1) / 2+ h = np.sinc(m / factor) * np.kaiser(n, 8.0)+ return (h.reshape(taps, factor).T * factor / h.sum()).astype(np.float64)+++def peak_envelope(samples: np.ndarray, factor: int = 4) -> np.ndarray:+ """For each sample, the highest the waveform reaches between it and the next, on any channel."""+ x = samples if samples.ndim == 2 else samples[:, None]+ phases = _oversampler(factor)+ taps = phases.shape[1]+ env = np.abs(x).max(axis=1).astype(np.float64)+ for ch in range(x.shape[1]):+ col = x[:, ch].astype(np.float64)+ for p in phases:+ y = np.convolve(col, p[::-1], mode="full")[taps // 2:taps // 2 + len(col)]+ np.maximum(env, np.abs(y), out=env)+ return env+++def true_peak_db(samples: np.ndarray) -> float:+ return 20.0 * float(np.log10(max(1e-12, float(peak_envelope(samples).max()))))+++def limit(samples: np.ndarray, ceiling_db: float, attack: float = 0.004, release: float = 0.12,+ rate: int = AUDIO_RATE) -> tuple[np.ndarray, float]:+ """Bring every true peak under `ceiling_db` with a smooth gain: it starts going down `attack`+ seconds before a peak and comes back at a steady rate over about `release` seconds per 6 dB,+ so a peak is turned down, not chopped. The result is measured again, and a peak the waveform+ still makes between its samples is taken down by a second pass. Returns the samples and the+ most it turned down (dB)."""+ out, most = samples, 0.0+ for _ in range(3):+ out, cut = _limit_once(out, ceiling_db, attack, release, rate)+ most += cut+ if cut <= 0 or true_peak_db(out) <= ceiling_db + 0.01:+ break+ return out, most+++def _limit_once(samples: np.ndarray, ceiling_db: float, attack: float, release: float,+ rate: int) -> tuple[np.ndarray, float]:+ env = peak_envelope(samples)+ need = np.maximum(0.0, 20.0 * np.log10(np.maximum(env, 1e-12)) - ceiling_db) # dB to take off+ if need.max() <= 0:+ return samples, 0.0+ k = np.arange(len(need), dtype=np.float64)+ down = 6.0 / max(1.0, release * rate) # dB per sample on the way back+ up = need.max() / max(1.0, attack * rate) + 1e-9 # dB per sample on the way in+ after = np.maximum.accumulate(need + down * k) - down * k # each peak's reduction, let go slowly+ before = (np.maximum.accumulate((need - up * k)[::-1])[::-1]) + up * k # and reached early+ cut = np.maximum(np.maximum(after, before), 0.0)+ w = max(1, int(0.001 * rate)) # round the corners off over a millisecond, never under the need+ cut = np.maximum(np.convolve(cut, np.ones(w) / w, mode="same"), need)+ g = (10.0 ** (-cut / 20.0)).astype(np.float32)+ out = samples * (g[:, None] if samples.ndim == 2 else g)+ return out.astype(np.float32), float(cut.max())+++# ---- the two passes ------------------------------------------------------------------------------++def encoded_peak(samples: np.ndarray, kbps: int = 128) -> float:+ """The true peak the sound will have once encoded as AAC at `kbps` (a trial encode, measured by+ loudnorm): the lowest rate the pack writes, where the coded waveform overshoots the most. It is+ encoded exactly as `video.FrameWriter` encodes it: in bit-exact mode the encoder overshoots more+ (0.94 against 1.74 dB under full scale for the same mix, 28 October 2026)."""+ with tempfile.TemporaryDirectory(prefix="fx-loud-") as tmp:+ src = _raw(samples, tmp, "mix.f32")+ coded = Path(tmp) / "trial.mp4"+ run = subprocess.run(["ffmpeg", "-v", "error", "-nostdin", "-y", *src, "-c:a", "aac", "-b:a", f"{kbps}k",+ "-movflags", "+faststart", "-map_metadata", "-1", "-fflags", "+bitexact",+ "-flags:a", "+bitexact", str(coded)], capture_output=True, text=True)+ if run.returncode != 0:+ raise MediaError("ffmpeg could not make a trial encode of the sound")+ return measure_file(coded).tp+++def normalize(samples: np.ndarray, target_i: float = -14.0, target_tp: float = -1.0) -> tuple[np.ndarray, dict]:+ """The mix at `target_i` LUFS with its true peak under `target_tp` dBTP, through loudnorm's two+ passes. The result is encoded on trial; when the encoded waveform would still go over (a quiet+ voice lifted a long way and limited hard overshoots most), the ceiling comes down by the excess+ and the passes run again, so the video's own sound is encoded once, already under. Same length,+ same timing."""+ first = measure(samples)+ if first.i < -70:+ return samples, {"skipped": "the sound is silent", "first": first.as_dict()}+ ceiling = target_tp - ENCODE_ROOM+ for _ in range(3):+ y, report = _two_passes(samples, first, target_i, ceiling)+ coded = encoded_peak(y)+ report.update(target_lufs=target_i, target_true_peak=target_tp, ceiling=round(ceiling, 2),+ encoded_true_peak=round(coded, 2))+ if coded <= target_tp - 0.1:+ break+ ceiling -= coded - (target_tp - 0.1) + 0.1+ return y, report+++_SOXR: Optional[bool] = None+++def _resampler() -> str:+ """soxr where this ffmpeg has it (the better resampler), else ffmpeg's own: many builds, Homebrew's+ ffmpeg 9 among them, ship without soxr, and asking for it fails the whole loudness pass."""+ global _SOXR+ if _SOXR is None:+ run = subprocess.run(["ffmpeg", "-hide_banner", "-nostdin", "-v", "error", "-f", "lavfi", "-i",+ "anullsrc=d=0.1", "-af", "aresample=48000:resampler=soxr", "-f", "null", "-"],+ capture_output=True, text=True)+ _SOXR = run.returncode == 0+ return ":resampler=soxr" if _SOXR else ""+++def _two_passes(samples: np.ndarray, first: Measure, target_i: float, ceiling: float) -> tuple[np.ndarray, dict]:+ x, limited, slack = samples, 0.0, 0.0+ m = first+ for _ in range(4): # limit, measure again (limiting lowers the loudness a little), repeat+ room = ceiling - 0.2 - (target_i - m.i) # the peak the mix may have before its gain+ if m.tp <= room:+ break+ x, cut = limit(x, room - slack)+ limited = max(limited, cut)+ m = measure(x)+ # loudnorm finds peaks at a finer rate than the estimate here; aim under by the difference+ slack = max(slack, m.tp - true_peak_db(x) + 0.05)+ af = (f"loudnorm=I={target_i}:TP={ceiling}:LRA={LRA}:measured_I={m.i}:measured_TP={m.tp}:"+ f"measured_LRA={m.lra}:measured_thresh={m.thresh}:offset={m.offset}:linear=true:print_format=json,"+ f"aresample={AUDIO_RATE}{_resampler()}")+ with tempfile.TemporaryDirectory(prefix="fx-loud-") as tmp:+ src = _raw(x, tmp, "mix.f32")+ out = Path(tmp) / "out.f32"+ run = subprocess.run(["ffmpeg", "-hide_banner", "-nostdin", "-y", *src, "-af", af, "-f", "f32le",+ "-ar", str(AUDIO_RATE), "-ac", str(x.shape[1]), str(out)], capture_output=True, text=True)+ if run.returncode != 0:+ raise MediaError("ffmpeg could not set the loudness")+ second = _json_tail(run.stderr)+ y = np.fromfile(out, np.float32).reshape(-1, x.shape[1])+ if len(y) < len(x):+ y = np.concatenate([y, np.zeros((len(x) - len(y), x.shape[1]), np.float32)])+ y = np.ascontiguousarray(y[:len(x)])+ report = {"before": first.as_dict(), "limited_db": round(limited, 2),+ "second_pass": second.get("normalization_type", "?"),+ "after": {"lufs": round(_number(second.get("output_i")), 2),+ "true_peak_dbtp": round(_number(second.get("output_tp")), 2)}}+ return y, report+++def main(argv: list[str] | None = None) -> int:+ args = list(sys.argv[1:] if argv is None else argv)+ if not args:+ print(__doc__)+ return 0+ for p in args:+ m = measure_file(p)+ print(f"{p}: {m.i:.2f} LUFS integrated, true peak {m.tp:.2f} dBTP, range {m.lra:.1f} LU")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/edit/askeditor/fx/core/match.py b/edit/askeditor/fx/core/match.pynew file mode 100644index 0000000..038c9b0--- /dev/null+++ b/edit/askeditor/fx/core/match.py@@ -0,0 +1,473 @@+"""Matching a person's own files to the words they say: which file goes on which word.++The pack never looks at the pictures to decide. A file lands on a word because the person said so,+or because its name or its tags name what is said:++1. **`map`**: a word said -> a file, given by the person (`lake=lake.mp4; city=rooftops.mp4`).+2. **The file's name and `tags.txt`**: the words in a file's name (`rice-fields.mov` -> rice,+ fields) and the phrases a `tags.txt` beside it lists for it, matched to the words said, a plural+ matching its singular. A file named only with a camera's number (`IMG_5922.MOV`) says nothing,+ so it is "unnamed"; a named file whose words are never said is left out, with that reason.+3. **The things named**: the strongest words that name a thing (nouns, places, things, found by+ rules: never grammar, filler or a doing word, never a word said again). The unnamed files go+ on these, in folder order, once an effect has placed them in time (`folder_order`).++**Never on a word taken back.** Given what the speaker took back (`moments.taken_back`, from the+clip's whole words), a file's name or tags never land on a word the speaker replaced ("the lively+town, or the lively city": a clip tagged "town" is not laid on "town"), a first attempt said again+or an aside about the recording, and the things named are weighed by the shared picker's measure+(`moments.strength`), so the word said instead counts as what its line says new. A word the person+maps lands where it is not taken back, or where it is taken back when it is said nowhere else.++**A logo** names one brand, so it lands only where that brand's whole name is said: `AskEditor.png`+on "AskEditor" or "Ask Editor", never on "ask" or "editor" alone (`brand_words`, `said_whole`). An+item marked `whole` is matched this way, and is never laid on one of the things named.++What an effect does with it:++ pool, named = match.pool(spec, mapping, KIND, load) # the files, and the words mapped to them+ said = match.said(clip.words) # the words a file may land on+ back = moments.taken_back(clip.words, clip.quiet) # what the speaker took back+ cands, unnamed = match.candidates(said, quiet, pool, named, "keywords", left, back)+ ... the effect places the candidates in time, by its own rules ...+ for moment, idx in match.folder_order(keyword_moments, unnamed): ...++Every item in a pool is the effect's own (a B-roll clip, a picture): anything with `path`, `names`+(the words of its file name), `tags` (its phrases in tags.txt) and `named` (either is there), and+optionally `whole` (True: its names are one brand's name, said whole).+"""++from __future__ import annotations++import json+import os+import re+from dataclasses import dataclass+from functools import lru_cache+from pathlib import Path+from typing import Callable, Optional++from . import moments+from .words import HESITATIONS, Word, normalize++# Words in a file name that say nothing about what a file shows: cameras, phones, and editing.+_CAMERA = set("""+img dsc dscf dscn dji mvi mov pxl vid video videos gopr gp clip clips broll roll final edit edited copy export+untitled new raw take shot cam camera iphone android photo pic image hdr sdr lut graded proxy screen recording+footage stock version+screenshot screenshots snapshot capture photos pics images picture pictures scan scanned download downloaded+file unnamed+""".split())+# Apps whose own names a phone or a laptop writes, joined, into the files it saves ("WhatsApp Image…",+# "CleanShot 2026…"): taken out before a name is split into its words, so no half of one is a name.+_SAVED_BY = re.compile(r"(?i)whatsapp|cleanshot|screenshot|snapchat|telegram|messenger")+_STOP = set("""+a an the and or of in on at to for with from by into my your our their his her its this that these those+is are was were be been it i we you they me us them+""".split())+# Doing words: never the thing a file shows.+_DOING = set("""+make makes made making build builds built create creates created show shows grow grows learn learns use uses+start starts work works run runs change changes find finds get gets give gives take takes want wants need needs+try tries love loves like likes watch watches improve improves help helps edit edits went go goes going come+comes came talk talks talked think thinks thought say says said+""".split())+_SUBJECTS = set("that which who it he she they we you i".split())+# Words that describe or count rather than name: never what a file shows.+_NOT_THINGS = set("""+good better best great nice bad worse worst real big bigger biggest small smaller little large huge new newer old+older young hot cold cool warm easy easier hard harder simple fast faster quick slow slower cheap cheaper expensive+high higher low lower long longer short shorter early late ready sure true false right wrong happy sad different+same whole entire full empty free main important actual possible amazing awesome beautiful lovely perfect crazy+second seconds minute minutes hour hours day days week weeks month months year years time times moment moments+""".split())+_HELPERS = set("was were is are be been being had have has got gets".split())+# Said straight before a word that describes what was just named ("the sea was calm", "it looks great").+_BE = set("is are was were am be been being seems seemed looks looked feels felt became becomes stays stayed".split())+# Said just before a person's own name ("it's Sam", "I'm Jo", "my name is…"): the person, not a file.+_INTRO = set("it's i'm im name's".split())+KEY_MIN = 7.0 # a word must score this to carry a file of its own (the pack's word scorer)+RUN_MIN = 4.0 # words scoring this belong to one named thing ("lively city", "production quality")+++# ---- the words -----------------------------------------------------------------------------------++def stem(k: str) -> str:+ """A word in its singular, near enough to match: cities -> city, trains -> train, boxes -> box."""+ if len(k) > 4 and k.endswith("ies"):+ return k[:-3] + "y"+ if len(k) > 4 and k.endswith(("ches", "shes", "xes", "sses", "zes")):+ return k[:-2]+ if len(k) > 3 and k.endswith("s") and not k.endswith(("ss", "us", "is")):+ return k[:-1]+ return k+++def name_words(path: str | Path) -> tuple[str, ...]:+ """The words a file name says about what the file shows: `rice-fields_mountains.mov` -> rice,+ fields, mountains; `IMG_5922.MOV` -> nothing."""+ s = re.sub(r"([a-z])([A-Z])", r"\1 \2", _SAVED_BY.sub(" ", Path(path).stem))+ out = []+ for tok in re.split(r"[^A-Za-z]+", s):+ t = tok.lower()+ if len(t) >= 3 and t not in _CAMERA and t not in _STOP and t not in out:+ out.append(t)+ return tuple(out)+++def phrase(text: str) -> tuple[str, ...]:+ """A phrase as it is matched: each word in its singular, the little words left out."""+ return tuple(stem(normalize(x)) for x in str(text).split() if normalize(x) and normalize(x) not in _STOP)+++# Words in a logo's file name that describe the file, not the brand: `askeditor-logo-dark.png`.+_LOGO_FILE = set("""+logo logos logotype icon icons mark wordmark lettermark symbol brand brandmark badge emblem glyph favicon+light dark white black mono monochrome colour color colored coloured full horizontal vertical stacked square round+circle transparent primary secondary main alt small large big rgb cmyk svg png print web app the+""".split())+++def brand_words(path: str | Path) -> tuple[str, ...]:+ """A logo's brand, from its file name, as the words its name is said in: `AskEditor.png` ->+ ask, editor; `notion-logo-dark.png` -> notion; `3M.png` -> 3m. Short names and figures are+ kept (a brand can be two letters); what describes the file (logo, dark, icon) is not."""+ stem_ = Path(path).stem+ if _SAVED_BY.search(stem_):+ return () # a file an app named: its name is a date, not a brand+ s = re.sub(r"([a-z])([A-Z])", r"\1 \2", stem_)+ out = []+ for tok in re.split(r"[^A-Za-z0-9]+", s):+ t = tok.lower()+ if not t or t in _LOGO_FILE or t in _CAMERA or t.isdigit():+ continue+ out.append(t)+ if all(t in _STOP for t in out):+ return () # only the little words of a name a camera or an app wrote ("Screen Shot … at …")+ return tuple(out)+++def _squash(key: str) -> str:+ """A said word with nothing but its letters and figures, and no possessive: AskEditor's -> askeditor."""+ k = key.lower().replace("’", "'")+ if k.endswith("'s"):+ k = k[:-2]+ elif k.endswith("s'"):+ k = k[:-1]+ return re.sub(r"[^a-z0-9]", "", k)+++def said_whole(said_words: list[Word], brand: tuple[str, ...]) -> list[int]:+ """Where a brand's whole name is said, by the index of its first word: as one word+ ("AskEditor", "Ask-Editor's") or as its words in a row ("Ask Editor"), heard in at most one+ piece more than it has."""+ target = "".join(brand)+ if not target:+ return []+ keys = [_squash(w.key) for w in said_words]+ out = []+ for i in range(len(keys)):+ acc = ""+ for j in range(i, min(len(keys), i + len(brand) + 1)):+ acc += keys[j]+ if acc == target:+ out.append(i)+ break+ if not target.startswith(acc):+ break+ return out+++def said(words: list[Word]) -> list[Word]:+ """The words a file may land on: every word heard for sure, without the ums."""+ return [w for w in words if w.key and w.key not in HESITATIONS and not getattr(w, "unsure", "")]+++def occurrences(stems: list[str], wanted: tuple) -> list[int]:+ """Where the run of words `wanted` is said, by the index of its first word in `stems`."""+ n = len(wanted)+ if not n:+ return []+ return [i for i in range(len(stems) - n + 1) if tuple(stems[i:i + n]) == wanted]+++# ---- the files -----------------------------------------------------------------------------------++@dataclass(frozen=True)+class Kind:+ """The kind of file an effect takes, and how its messages name it."""+ exts: frozenset # the endings it reads, lower case with the dot+ plural: str # "clips or photos": there are no … in a folder+ one: str # "B-roll": there is no … at a path+ reads: str # "a clip or a photo this pack reads (…)": a file that is not one is not …+ yours: str # "your B-roll": map names a file which is not among …+ ask: str # what to say when nothing was given+++def natural(name: str) -> list:+ """A file name's sort key, numbers in number order: IMG_2 before IMG_10."""+ return [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", name)]+++def files(spec: str, kind: Kind) -> list[Path]:+ """The files `spec` names: a folder's files of this kind in name order, or a list of files."""+ spec = str(spec).strip().strip("\"'")+ if not spec:+ return []+ one = Path(os.path.expanduser(spec))+ if one.is_dir():+ found = sorted((p for p in one.iterdir() if p.suffix.lower() in kind.exts and not p.name.startswith(".")),+ key=lambda p: natural(p.name))+ if not found:+ raise ValueError(f"there are no {kind.plural} in {one}")+ return found+ out = []+ for part in [p.strip().strip("\"'") for p in re.split(r"[,;\n]", spec) if p.strip()]:+ p = Path(os.path.expanduser(part))+ if p.is_dir():+ out += files(str(p), kind)+ elif not p.exists():+ raise ValueError(f"there is no {kind.one} at {p}")+ elif p.suffix.lower() not in kind.exts:+ raise ValueError(f"{p.name} is not {kind.reads}. A HEIC photo needs saving as JPEG first")+ else:+ out.append(p)+ return out+++@lru_cache(maxsize=64)+def read_tags(folder: str) -> dict[str, tuple]:+ """`tags.txt` in a folder: one file a line, `lake.mp4: lake, water, sunset` (a name without its+ ending works too). Lines starting with # are notes."""+ f = Path(folder) / "tags.txt"+ if not f.exists():+ return {}+ out: dict[str, tuple] = {}+ for line in f.read_text(errors="replace").splitlines():+ line = line.strip()+ if not line or line.startswith("#"):+ continue+ m = re.match(r"^(.+?)\s*[:=]\s*(.*)$", line)+ if not m:+ continue+ phrases = tuple(p for p in (phrase(x) for x in re.split(r"[,;]", m.group(2))) if p)+ if phrases:+ out[m.group(1).strip().strip("\"'").lower()] = phrases+ return out+++def tags_for(path: Path) -> tuple:+ """The phrases the `tags.txt` beside `path` lists for it."""+ tags = read_tags(str(path.parent))+ return tags.get(path.name.lower()) or tags.get(path.stem.lower()) or ()+++def parse_map(text: str, noun: str = "clip",+ examples: tuple = (("lake", "lake.mp4"), ("city", "rooftops.mp4"))) -> list[tuple[str, str]]:+ """`{"lake": "lake.mp4"}` or `lake=lake.mp4; city=rooftops.mp4` -> [("lake", "lake.mp4"), …].+ `noun` and `examples` are how the messages name a file. Raises ValueError, saying what would work."""+ (w1, f1), (w2, f2) = examples+ t = str(text).strip()+ if not t:+ return []+ if t.startswith("{"):+ try:+ data = json.loads(t)+ except ValueError:+ raise ValueError(f'map is not valid JSON; write {{"{w1}": "{f1}"}} or {w1}={f1}; {w2}={f2}') from None+ if not isinstance(data, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in data.items()):+ raise ValueError(f'map needs words and {noun} names, such as {{"{w1}": "{f1}"}}')+ pairs = list(data.items())+ else:+ pairs = []+ for part in re.split(r"[;\n]|,(?=[^,]*=)", t):+ part = part.strip()+ if not part:+ continue+ if "=" not in part:+ raise ValueError(f"map pairs go as word={noun} (got {part!r}); for example {w1}={f1}; {w2}={f2}")+ word, name = part.split("=", 1)+ pairs.append((word, name))+ out = []+ for word, name in pairs:+ word, name = word.strip().strip("\"'"), name.strip().strip("\"'")+ if not [normalize(x) for x in word.split() if normalize(x)]:+ raise ValueError(f"map needs a word you say before each {noun} (got {word!r})")+ if not name:+ raise ValueError(f"map needs a {noun} for “{word}”")+ out.append((word, name))+ return out+++def pool(spec: str, mapping: list[tuple[str, str]], kind: Kind, load: Callable[[Path], object]):+ """The files in folder order, each made by `load`, and which file each mapped word names+ (word -> index). A file the map gives by its full path joins the pool after the folder's."""+ paths = files(spec, kind)+ if not paths and not mapping:+ raise ValueError(kind.ask)+ items = [load(p) for p in paths]+ where = {str(Path(it.path).resolve()): i for i, it in enumerate(items)}+ by_name: dict[str, list[int]] = {}+ for i, it in enumerate(items):+ by_name.setdefault(Path(it.path).name.lower(), []).append(i)+ by_name.setdefault(Path(it.path).stem.lower(), []).append(i)+ named: dict[str, int] = {}+ for word, name in mapping:+ p = Path(os.path.expanduser(name))+ idx = None+ if p.exists() and p.is_file():+ idx = where.get(str(p.resolve()))+ if idx is None:+ items.append(load(p))+ idx = len(items) - 1+ where[str(p.resolve())] = idx+ else:+ hits = by_name.get(name.lower()) or by_name.get(Path(name).stem.lower())+ if hits:+ idx = hits[0]+ if idx is None:+ raise ValueError(f"map names {name}, which is not among {kind.yours}"+ + (f" ({spec})" if spec else "") + "; give its full path or put it in the folder")+ named[word] = idx+ return items, named+++# ---- the things named ----------------------------------------------------------------------------++@dataclass+class Keyword:+ index: int+ start: float+ word: str+ score: float+++def keyword_scores(words: list[Word], quiet, back: Optional[moments.TakenBack] = None) -> list[float]:+ """How well each word names a thing a picture could show: the shared picker's measure+ (`moments.strength`: specific, at the end of its phrase, after "the" or "a"; nothing for a word+ in `back`, what the speaker took back), less for doing words."""+ back = moments.TakenBack() if back is None else back+ scores = [0.0] * len(words)+ for ln in moments.lines(words, quiet):+ for i in ln:+ s = moments.strength(words, i, ln, quiet, back)+ if s <= 0:+ continue+ k = words[i].key+ if k in _DOING or (k.endswith("ing") and len(k) > 5):+ s -= 4+ if i > 0 and words[i - 1].key in _SUBJECTS and k.endswith("s"):+ s -= 3 # "an editor that edits": doing, not naming+ if i > 0 and len(k) > 4 and k.endswith("ed") and words[i - 1].key in _SUBJECTS | _HELPERS:+ s -= 5 # "than I expected", "it was packed": doing or describing+ if i > 0 and words[i - 1].key in _BE and not bare(words[i])[:1].isupper():+ s -= 5 # "my hotel was tiny", "the sea was calm": describing what was named (a name stays)+ if k in _NOT_THINGS:+ s = 0.0+ if (i > 0 and words[i - 1].key in _INTRO) or (i > 1 and words[i - 2].key == "name"+ and words[i - 1].key == "is"):+ s = 0.0 # introducing yourself: your face, not a picture+ scores[i] = max(0.0, s)+ return scores+++def bare(word: Word) -> str:+ """A word as a check or a sheet shows it, with nothing at either edge (the captions' own rule)."""+ from ..effects.captions import bare as captions_bare++ return captions_bare(word)+++def keywords(words: list[Word], quiet, back: Optional[moments.TakenBack] = None) -> list[Keyword]:+ """The things named, in order: a run of naming words ("the lively city") is one thing, landing+ on its strongest word (a tie goes to the later one, where English puts the thing named). A+ thing said again is not new. `back`: what the speaker took back, never a thing named."""+ scores = keyword_scores(words, quiet, back)+ out, seen = [], set()+ i, n = 0, len(words)+ while i < n:+ if scores[i] < RUN_MIN:+ i += 1+ continue+ j = i+ while j + 1 < n and scores[j + 1] >= RUN_MIN and not words[j].ends_clause:+ j += 1+ best = max(range(i, j + 1), key=lambda m: (scores[m], m))+ k = stem(words[best].key)+ if scores[best] >= KEY_MIN and k not in seen:+ out.append(Keyword(best, float(words[best].start), bare(words[best]), float(scores[best])))+ seen.add(k)+ i = j + 1+ return out+++# ---- which file on which word --------------------------------------------------------------------++@dataclass+class Candidate:+ """A moment a file could land on: the word's start, the file (None: one of the things named,+ waiting for an unnamed file), and why."""+ start: float+ item: Optional[int]+ word: str+ why: str # map, tags, name, keyword+ priority: int # 3: mapped; 2: its name or tags said; 1: a thing named+ score: float = 0.0+++def candidates(said_words: list[Word], quiet, items: list, named: dict[str, int], on: str,+ left: dict[int, str], back: Optional[moments.TakenBack] = None) -> tuple[list[Candidate], list[int]]:+ """Every moment each file could land on, and the unnamed files (in folder order) for the things+ named. `on` is "keywords" (map, names, tags and the things named) or "map" (map, names and tags+ only). `left` holds the files already ruled out (index -> why), and gains the ones that can+ never land, each with its reason; a file in it is never matched. `back`: what the speaker took+ back (`moments.taken_back` of the clip's whole words): a name or a tag never lands there, and a+ word mapped lands there only when it is said nowhere else."""+ back = moments.TakenBack() if back is None else back+ stems = [stem(w.key) for w in said_words]++ def kept(occ: list[int], n: int) -> list[int]:+ return [i for i in occ if not any(w in back for w in said_words[i:i + max(1, n)])]++ cands: list[Candidate] = []+ mapped = set(named.values())+ for word, idx in named.items():+ occ = occurrences(stems, phrase(word))+ if not occ:+ left.setdefault(idx, f"map: “{word}” is never said")+ occ = kept(occ, len(phrase(word))) or occ+ for i in occ:+ cands.append(Candidate(float(said_words[i].start), idx, bare(said_words[i]), "map", 3))+ for idx, it in enumerate(items):+ if idx in mapped or idx in left or not it.named:+ continue+ heard = [(occurrences(stems, ph), len(ph), "tags") for ph in it.tags]+ if getattr(it, "whole", False):+ heard.append((said_whole(said_words, it.names), 1, "name"))+ else:+ heard += [(occurrences(stems, (stem(n),)), 1, "name") for n in it.names]+ hits = [(i, why) for occ, n, why in heard for i in kept(occ, n)]+ if not hits:+ left[idx] = ("its name and tags are said only where the speaker took them back"+ if any(occ for occ, _, _ in heard) else "its name and tags are never said")+ continue+ for i, why in sorted(set(hits)):+ cands.append(Candidate(float(said_words[i].start), idx, bare(said_words[i]), why, 2))+ if on == "keywords":+ for kw in keywords(said_words, quiet, back):+ cands.append(Candidate(kw.start, None, kw.word, "keyword", 1, kw.score))+ for i, it in enumerate(items):+ if getattr(it, "whole", False) and not it.named and i not in mapped:+ left.setdefault(i, "a logo lands only on its brand's name, and this file's name gives none")+ unnamed = [i for i, it in enumerate(items) if not it.named and i not in mapped and i not in left]+ if on == "map":+ for i in unnamed:+ left[i] = "nothing in its name to match, and on=map"+ unnamed = []+ return cands, unnamed+++def folder_order(moments: list, unnamed: list[int]) -> list[tuple[object, int]]:+ """The unnamed files paired with the keyword moments an effect placed: the first file in folder+ order on the earliest moment, and so on (each moment has a `start`)."""+ return list(zip(sorted(moments, key=lambda c: c.start), unnamed))diff --git a/edit/askeditor/fx/core/matte.py b/edit/askeditor/fx/core/matte.pynew file mode 100644index 0000000..9a3dc26--- /dev/null+++ b/edit/askeditor/fx/core/matte.py@@ -0,0 +1,346 @@+"""The person over a whole new room: an edge with no rim of the old room, solid inside, and steady.++`person.full()` gives the edge for a layer that covers part of the frame (a word behind a head).+A new room behind the whole person shows every pixel of the edge, against a colour that may be+nothing like the old wall, so it needs more. Each point below was measured on the test clips+(28 October 2026):++- **Firm.** Across a dark cap on clip B's bright ceiling, the guided edge keeps a 10–20% tail of+ the old wall for eight pixels outside (a pale halo on the new room) and lets the new room 10–35%+ into the cap for six pixels inside. `alpha()` firms the edge round its middle, so the tail goes+ and the inside is solid, without the jagged edge a pixel-by-pixel colour decision gave on hair.+- **No old wall in the edge.** A pixel on the edge is part person, part old wall. `over()` takes+ the old wall's share out, using the wall's colour from nearby, and puts the new room's in. Where+ a pixel is mostly wall its own colour says little about the person, so it leans on the person's+ colour just inside instead (otherwise the old wall's texture rides along in the halo).+- **Steady.** With nothing moving, the model's edge on clip D changed by 10% a frame on average.+ `Steady` averages each mask with its neighbours wherever the picture itself did not change, so a+ still edge holds and a moving one does not trail behind.+- **Only the speaker.** A passer-by or a stray patch that is not joined to the speaker is dropped+ (`main_only`); the speaker's own arms and a held microphone stay.+- **Two models agreeing.** `Steady` takes several masks of the clip and keeps only what all of them+ call the person: the core's two models take different parts of a room for a person.++ steady = matte.Steady(clip.person(), clip.info)+ m = matte.main_only(steady.get(k), head_box_in_mask_pixels)+ a = matte.alpha(masks, m, (w, h), guide=frame)+ out = matte.over(frame, a, room) # room: float32 (h, w, 3), 0..255+"""++from __future__ import annotations++from collections import deque+from typing import Optional++import numpy as np++from .person import PersonMasks, _read_gray+from .video import FrameReader, VideoInfo++# The edge is firmed between these levels of the guided mask: below LOW is wall, above HIGH is+# the person. Half way stays where the guided edge put it.+LOW, HIGH = 0.25, 0.75+# Steady: how far each side neighbours are averaged (seconds; at least 2 and at most 6 frames),+# and how much a pixel may change (grey levels, 0..255, at the mask's size, softened) before it+# counts as movement rather than noise. Measured on A, B and D: two frames each side cut the+# still edge's wobble by a fifth, four by about a half; further changes little.+REACH_S = 0.1+STILL = 8.0+++def _smoothstep(e0: float, e1: float, x: np.ndarray) -> np.ndarray:+ u = np.clip((x - e0) / (e1 - e0), 0.0, 1.0)+ return u * u * (3.0 - 2.0 * u)+++def main_only(m: np.ndarray, head: Optional[tuple[float, float, float, float]]) -> np.ndarray:+ """The small mask `m` with only the speaker kept: the part under the head box (x0, y0, x1, y1+ in the mask's own pixels), else the largest part, and any part at least a sixth of its size+ (an arm the frame's edge has cut off, say). A smaller patch apart from them goes."""+ import cv2++ hard = (m >= 0.5).astype(np.uint8)+ n, lab, stats, _ = cv2.connectedComponentsWithStats(hard, connectivity=8)+ if n <= 2:+ return m+ keep: set[int] = set()+ if head is not None:+ x0, y0, x1, y1 = (int(round(v)) for v in head)+ x0, y0 = max(0, x0), max(0, y0)+ sub = lab[y0:max(y0 + 1, y1), x0:max(x0 + 1, x1)]+ ids, counts = np.unique(sub[sub > 0], return_counts=True)+ if len(ids):+ keep.add(int(ids[np.argmax(counts)]))+ if not keep:+ keep.add(int(1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])))+ main = max(int(stats[i, cv2.CC_STAT_AREA]) for i in keep)+ keep |= {i for i in range(1, n) if stats[i, cv2.CC_STAT_AREA] >= main / 6}+ if len(keep) == n - 1:+ return m+ sel = np.isin(lab, sorted(keep)).astype(np.float32)+ sel = cv2.dilate(sel, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)))+ sel = cv2.GaussianBlur(sel, (0, 0), 1.0)+ return (m * np.clip(sel * 1.5, 0.0, 1.0)).astype(np.float32)+++class Steady:+ """The clip's small person masks, each averaged with its neighbours either side wherever the+ picture did not change between them. Read in order (`get(k)` with k rising one at a time), it+ keeps a short window; asked for any other frame it reads that frame's window afresh, so a still+ and the same frame of the render are the same.++ Given several masks of the same clip (from different models, the same size), a pixel is the+ person only as far as every one of them says so. The two models the core has fail in different+ places: on the test clips the plain one took a vase by the hair (A), a ceiling sprinkler (D) and+ a train's window panel (F) for the person, the detailed one did not, and what both agree on+ kept every hand, microphone and strand of hair the plain one had."""++ def __init__(self, masks, info: VideoInfo, reach: Optional[int] = None, still: float = STILL):+ self.all = list(masks) if isinstance(masks, (list, tuple)) else [masks]+ self.masks, self.info = self.all[0], info+ if any((m.width, m.height) != (self.masks.width, self.masks.height) for m in self.all):+ raise ValueError("masks to combine must be the same size")+ self.reach = int(reach) if reach is not None else int(np.clip(round(REACH_S * info.rate), 2, 6))+ self.still = float(still)+ self.n = self.masks.n+ d = np.arange(-self.reach, self.reach + 1, dtype=np.float32)+ self.time_w = np.exp(-0.5 * (d / max(0.5, self.reach / 1.5)) ** 2)+ self._win: deque = deque() # (k, mask, grey) for consecutive frames+ self._next = 0 # the next frame the readers give+ self._mreaders: list = []+ self._freader = None++ # ---- reading ----+ def _open(self, start: int) -> None:+ self._close()+ start = int(np.clip(start, 0, self.n - 1))+ t = max(0.0, (start - 0.25) / self.info.rate)+ size = (self.masks.width, self.masks.height)+ self._mreaders = [iter(_read_gray(m.path, size[0], size[1], start=t)) for m in self.all]+ self._freader = iter(FrameReader(self.info, size=size, start=t, gray=True))+ self._next = start+ self._win.clear()++ def _close(self) -> None:+ for r in self._mreaders + [self._freader]:+ if r is not None and hasattr(r, "close"):+ r.close()+ self._mreaders, self._freader = [], None++ def _pull(self) -> None:+ """Read the next frame into the window (holding the last one if the clip runs short)."""+ import cv2++ ms = [next(r, None) for r in self._mreaders]+ g = next(self._freader, None)+ m = None if any(x is None for x in ms) else (ms[0] if len(ms) == 1 else np.minimum.reduce(ms))+ if m is None or g is None:+ if self._win:+ _, m0, g0 = self._win[-1]+ self._win.append((self._next, m0, g0))+ else:+ z = np.zeros((self.masks.height, self.masks.width), np.float32)+ self._win.append((self._next, z, z))+ else: # the grey picture is softened once, here: only its slow changes count as movement+ self._win.append((self._next, m.astype(np.float32) / 255.0,+ cv2.GaussianBlur(g.astype(np.float32), (0, 0), 1.5)))+ self._next += 1++ def get(self, k: int) -> np.ndarray:+ """Frame k's steadied mask (float32 0..1, the masks' small size)."""+ k = int(np.clip(k, 0, self.n - 1))+ lo, hi = max(0, k - self.reach), min(self.n - 1, k + self.reach)+ first = self._win[0][0] if self._win else None+ if (not self._mreaders or (first is not None and lo < first)+ or (first is None and self._next != lo) or lo > self._next + 4 * self.reach + 8):+ self._open(lo) # back before the window, or far ahead: start reading there+ while self._win and self._win[0][0] < lo:+ self._win.popleft()+ while self._next <= hi:+ self._pull()+ frames = {w[0]: w for w in self._win}+ _, mk, gk = frames[k]+ if self.reach <= 0:+ return mk+ num = mk * self.time_w[self.reach]+ den = np.full_like(mk, self.time_w[self.reach])+ for i, d in enumerate(range(-self.reach, self.reach + 1)):+ j = k + d+ if d == 0 or j not in frames: # the clip's first and last frames have fewer neighbours+ continue+ _, mj, gj = frames[j]+ w = self.time_w[i] * np.exp(-((np.abs(gj - gk) / self.still) ** 2))+ num += w * mj+ den += w+ return (num / den).astype(np.float32)++ def close(self) -> None:+ self._close()+++def alpha(masks: PersonMasks, m: np.ndarray, size: tuple[int, int], guide: Optional[np.ndarray] = None,+ crop: Optional[tuple[float, float, float, float]] = None, reach: Optional[float] = None,+ low: float = LOW, high: float = HIGH) -> np.ndarray:+ """The person at `size` (w, h), float32 0..1: the guided edge (`PersonMasks.full`, the soft edge+ kept within `reach` output pixels of where the model is sure), firmed between `low` and `high`."""+ a = masks.full(m, size, guide=guide, crop=crop, lean=0.5, reach=reach)+ lut = _firm_table(low, high)+ return lut[np.clip(a * 1023.0 + 0.5, 0, 1023).astype(np.int16)]++++_TABLES: dict = {}+++def _firm_table(low: float, high: float) -> np.ndarray:+ key = (round(low, 4), round(high, 4))+ if key not in _TABLES:+ _TABLES[key] = _smoothstep(low, high, np.linspace(0.0, 1.0, 1024, dtype=np.float32)).astype(np.float32)+ return _TABLES[key]+++def _norm_blur(img: np.ndarray, w: np.ndarray, sigma: float) -> tuple[np.ndarray, np.ndarray]:+ import cv2++ num = cv2.GaussianBlur(img * w[..., None], (0, 0), sigma)+ den = cv2.GaussianBlur(w, (0, 0), sigma)+ return num / np.maximum(den, 1e-4)[..., None], den+++def colours_near_edge(frame: np.ndarray, a: np.ndarray, sigma: float) -> tuple[np.ndarray, np.ndarray]:+ """At a quarter of the frame's size: under each spot, the old wall's colour from the nearby+ pixels that are all wall, and the person's colour from the nearby pixels that are all person+ (float32). Both change slowly across the frame, so a quarter size loses nothing."""+ import cv2++ h, w = a.shape+ sw, sh = max(2, w // 4), max(2, h // 4)+ a_s = cv2.resize(a, (sw, sh), interpolation=cv2.INTER_AREA)+ I_s = cv2.resize(np.ascontiguousarray(frame, np.float32), (sw, sh), interpolation=cv2.INTER_AREA)+ s = max(1.0, sigma / 4)+ wall, dw = _norm_blur(I_s, (a_s < 0.04).astype(np.float32), s)+ body, db = _norm_blur(I_s, (a_s > 0.96).astype(np.float32), s)+ wall = np.where((dw > 0.02)[..., None], wall, I_s)+ body = np.where((db > 0.02)[..., None], body, I_s)+ return wall, body+++def sample(img: np.ndarray, ys: np.ndarray, xs: np.ndarray, sy: float, sx: float) -> np.ndarray:+ """`img` (a smaller map: `sy`, `sx` times the frame's size) read at the frame's pixels (ys, xs),+ blended between its four nearest points."""+ h, w = img.shape[:2]+ fy = np.clip((ys + 0.5) * sy - 0.5, 0, max(0.0, h - 1.001))+ fx = np.clip((xs + 0.5) * sx - 0.5, 0, max(0.0, w - 1.001))+ y0, x0 = fy.astype(np.int32), fx.astype(np.int32)+ wy, wx = (fy - y0).astype(np.float32), (fx - x0).astype(np.float32)+ if img.ndim == 3:+ wy, wx = wy[:, None], wx[:, None]+ top = img[y0, x0] * (1 - wx) + img[y0, x0 + 1] * wx+ bot = img[y0 + 1, x0] * (1 - wx) + img[y0 + 1, x0 + 1] * wx+ return top * (1 - wy) + bot * wy+++def over(frame: np.ndarray, a: np.ndarray, room: np.ndarray, sigma: Optional[float] = None,+ gains: Optional[np.ndarray] = None) -> np.ndarray:+ """The person (from `frame`, RGB, times `gains` per channel when given) over `room` (float32+ 0..255, the same size), with `a` the person (0..1). Returns float32 0..255. On the edge only the+ old wall's share of each pixel is swapped for the room; a pixel that is mostly wall takes the+ person's colour from just inside. Only the edge's own pixels are worked out one by one."""+ import cv2++ h, w = a.shape+ sigma = sigma if sigma is not None else max(4.0, 0.012 * w)+ I = frame.astype(np.float32)+ if gains is not None:+ I *= np.asarray(gains, np.float32)+ out = cv2.blendLinear(I, room, a, 1.0 - a)+ edge = (a > 0.004) & (a < 0.996)+ ys, xs = np.nonzero(edge)+ if not len(ys):+ return out+ pad = int(3 * sigma)+ y0, y1 = max(0, int(ys.min()) - pad), min(h, int(ys.max()) + pad + 1)+ x0, x1 = max(0, int(xs.min()) - pad), min(w, int(xs.max()) + pad + 1)+ y0, x0 = y0 - y0 % 4, x0 - x0 % 4+ wall, body = colours_near_edge(I[y0:y1, x0:x1], a[y0:y1, x0:x1], sigma)+ ly, lx = ys - y0, xs - x0+ sy, sx = wall.shape[0] / max(1, y1 - y0), wall.shape[1] / max(1, x1 - x0)+ wall_e = sample(wall, ly, lx, sy, sx)+ body_e = sample(body, ly, lx, sy, sx)+ a_e = a[ys, xs][:, None]+ I_e = I[ys, xs]+ own = np.clip((I_e - (1.0 - a_e) * wall_e) / np.maximum(a_e, 1e-3), 0.0, 255.0)+ lean = _smoothstep(0.08, 0.45, a_e)+ fg = own * lean + body_e * (1.0 - lean)+ out[ys, xs] = fg * a_e + room[ys, xs] * (1.0 - a_e)+ return out+++class Cutout:+ """The speaker cut out for a frame of a render, the way `backdrop` cuts them out for a whole new+ room: the steadied mask (both models agreeing when `careful`), only the speaker kept (the part+ under the head), then the guided edge firmed. Any effect that lays something behind the person+ over much of the frame uses this, so its edge is measured and made the same way.++ cut = matte.Cutout(clip, framing, careful=True)+ a = cut.alpha(frame, k) # frame: the output frame; k: the source frame+ shown, worst = matte.face_shown(a, face_box_in_output)+ """++ def __init__(self, clip, framing, careful: bool = True):+ self.clip, self.framing = clip, framing+ self.W, self.H = framing.out_w, framing.out_h+ self.masks = clip.person()+ self.steady = Steady([self.masks, clip.person("person-parts")] if careful else self.masks, clip.info)+ self._sx = self.masks.width / clip.info.width++ def alpha(self, frame: np.ndarray, k: int) -> np.ndarray:+ """The person at the output's size (float32 0..1) for source frame `k`, on `frame`."""+ m = self.steady.get(k)+ head = self.clip.face.head(k)+ if head is not None:+ s = self._sx+ m = main_only(m, (head.x0 * s, head.y0 * s, head.x1 * s, head.y1 * s))+ crop = self.framing.window(k) if self.framing.reframed else None+ return alpha(self.masks, m, (self.W, self.H), guide=frame, crop=crop, reach=0.012 * self.W)+++def face_shown(a: np.ndarray, box) -> Optional[float]:+ """How much of the face (its box in output pixels, a little inside it) the cut-out misses: the+ share of those pixels under half sure, where whatever is behind the person would show through+ the face. Over 2% counts as a frame over the face. None when the box is too small to judge."""+ H, W = a.shape+ x0, x1 = int(max(0, box.x0 + 0.15 * box.w)), int(min(W, box.x1 - 0.15 * box.w))+ y0, y1 = int(max(0, box.y0 + 0.1 * box.h)), int(min(H, box.y1 - 0.1 * box.h))+ if x1 - x0 < 4 or y1 - y0 < 4:+ return None+ return float((a[y0:y1, x0:x1] < 0.5).mean())+++def over_where(frame: np.ndarray, a: np.ndarray, room: np.ndarray, where: np.ndarray,+ sigma: Optional[float] = None) -> np.ndarray:+ """The person (alpha `a`) over `room` (float32 0..255: the clip's own picture with things laid+ in it behind the person), worked out only where `where` (0..1, the share of each pixel that+ something was laid on) says the room changed, and a little round it. Everywhere else the frame+ comes back exactly as filmed, so an effect laid behind part of the picture leaves the rest of it+ untouched; where something was laid, the edge has no rim of the old wall (`over`). uint8."""+ import cv2++ h, w = a.shape+ sigma = sigma if sigma is not None else max(4.0, 0.012 * w)+ ys, xs = np.nonzero(where > 0.002)+ if not len(ys):+ return frame+ pad = int(4 * sigma)+ y0, y1 = max(0, int(ys.min()) - pad), min(h, int(ys.max()) + pad + 1)+ x0, x1 = max(0, int(xs.min()) - pad), min(w, int(xs.max()) + pad + 1)+ sub = (slice(y0, y1), slice(x0, x1))+ done = over(frame[sub], a[sub], room[sub], sigma=sigma)+ # the edge is worked out against the room only near where the room changed: further off, the+ # frame as filmed (a soft step, so no seam shows where the two meet)+ near = cv2.GaussianBlur((where[sub] > 0.002).astype(np.float32), (0, 0), sigma)+ near = np.clip(near * 3.0, 0.0, 1.0)[..., None]+ out = frame.copy()+ f = frame[sub].astype(np.float32)+ out[sub] = np.clip(f + near * (done - f) + 0.5, 0, 255).astype(np.uint8)+ return outdiff --git a/edit/askeditor/fx/core/models.py b/edit/askeditor/fx/core/models.pynew file mode 100644index 0000000..f007737--- /dev/null+++ b/edit/askeditor/fx/core/models.py@@ -0,0 +1,194 @@+"""The model files, where each comes from, and fetching them (setup.sh runs `python -m fx.core.models fetch`).++Every file comes from its official home only, at a pinned version, and is checked against its+SHA-256 before it is used:++- the face, face landmark and person models from MediaPipe's model storage+ (storage.googleapis.com/mediapipe-models);+- the speech model from Hugging Face, `Systran/faster-whisper-small.en`, at a pinned revision.++A file already present with the right checksum is never fetched again, so running setup twice+touches the network once at most.+"""++from __future__ import annotations++import argparse+import hashlib+import json+import sys+import urllib.request+from pathlib import Path++from .paths import MODELS, NeedSetup++_STORE = "https://storage.googleapis.com/mediapipe-models"++VISION = {+ "face": {+ "file": "blaze_face_short_range.tflite",+ "url": f"{_STORE}/face_detector/blaze_face_short_range/float16/1/blaze_face_short_range.tflite",+ "sha256": "b4578f35940bf5a1a655214a1cce5cab13eba73c1297cd78e1a04c2380b0152f",+ "what": "the face model",+ },+ "person": {+ "file": "selfie_segmenter.tflite",+ "url": f"{_STORE}/image_segmenter/selfie_segmenter/float16/1/selfie_segmenter.tflite",+ "sha256": "191ac9529ae506ee0beefa6b2c945a172dab9d07d1e802a290a4e4038226658b",+ "what": "the person model",+ },+ "person-parts": {+ "file": "selfie_multiclass_256x256.tflite",+ "url": f"{_STORE}/image_segmenter/selfie_multiclass_256x256/float32/1/selfie_multiclass_256x256.tflite",+ "sha256": "c6748b1253a99067ef71f7e26ca71096cd449baefa8f101900ea23016507e0e0",+ "what": "the detailed person model (hair, skin, clothes)",+ },+ "landmarks": {+ "file": "face_landmarker.task",+ "url": f"{_STORE}/face_landmarker/face_landmarker/float16/1/face_landmarker.task",+ "sha256": "64184e229b263107bc2b804c6625db1341ff2bb731874b0bcc2fe6544e0bc9ff",+ "what": "the face landmark model (where each mouth is, for who is talking)",+ },+}++# The speech model's files at one revision, each with its SHA-256 (model.bin's is the one Hugging+# Face records for it; the others were checked against Hugging Face's own records on 28 October 2026).+SPEECH = {+ "small.en": {+ "repo": "Systran/faster-whisper-small.en",+ "revision": "d1d751a5f8271d482d14ca55d9e2deeebbae577f",+ "files": {+ "config.json": "666a9605530ac1f61fa8177f3702b4dacec9966749e42610839fcc32661d5fae",+ "model.bin": "62b2a45b05ee59acb4a5341b33ee35e041395d378d418a18acfe4c9e768ee37a",+ "tokenizer.json": "929c5252409436dce1b38a75d1abbcb5e132d170d8e324e4e04ed915fa2d22df",+ "vocabulary.txt": "ff77588746d3a2595d32ab5b69ffd7b95ce2441ac57533cb66fc3eb575a115cf",+ "README.md": "c87ff776137c2ecb30ee3b324b4cf5f38abf9423464613641ee45430bf580851",+ },+ },+}+DEFAULT_SPEECH = "small.en"+_VERIFIED = ".verified.json" # what was checked, so the next run need not hash 480 MB again+++def vision_path(name: str) -> Path:+ entry = VISION[name]+ path = MODELS / entry["file"]+ if not path.exists():+ raise NeedSetup(f"{entry['what']} is missing. Run setup.sh first.")+ return path+++def speech_path(name: str = DEFAULT_SPEECH) -> Path:+ if name not in SPEECH:+ raise ValueError(f"unknown speech model {name!r}; choose one of {', '.join(SPEECH)}")+ path = MODELS / f"faster-whisper-{name}"+ if not (path / "model.bin").exists():+ raise NeedSetup(f"the speech model {name} is missing. Run setup.sh first.")+ return path+++def _sha256(path: Path) -> str:+ h = hashlib.sha256()+ with open(path, "rb") as f:+ for chunk in iter(lambda: f.read(1 << 20), b""):+ h.update(chunk)+ return h.hexdigest()+++def _download(url: str, path: Path, sha256: str, what: str) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ part = path.with_name(path.name + ".part")+ print(f" fetching {what}…", flush=True)+ with urllib.request.urlopen(url, timeout=120) as r, open(part, "wb") as f:+ while chunk := r.read(1 << 20):+ f.write(chunk)+ got = _sha256(part)+ if got != sha256:+ part.unlink(missing_ok=True)+ raise RuntimeError(f"{what} did not match its checksum (got {got[:12]}…); nothing was kept")+ part.replace(path)+++def _verified(folder: Path) -> dict:+ try:+ return json.loads((folder / _VERIFIED).read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return {}+++def _present(path: Path, sha256: str, record: dict) -> bool:+ """The file is there and is the right one. A file checked before is trusted while its size and+ modification time are unchanged; anything else is hashed."""+ if not path.exists():+ return False+ st = path.stat()+ stamp = [sha256, st.st_size, int(st.st_mtime)]+ if record.get(path.name) == stamp:+ return True+ if _sha256(path) != sha256:+ return False+ record[path.name] = stamp+ return True+++def fetch_vision(name: str) -> Path:+ entry = VISION[name]+ path = MODELS / entry["file"]+ record = _verified(MODELS)+ if not _present(path, entry["sha256"], record):+ _download(entry["url"], path, entry["sha256"], entry["what"])+ _present(path, entry["sha256"], record)+ (MODELS / _VERIFIED).write_text(json.dumps(record, indent=1) + "\n")+ return path+++def fetch_speech(name: str = DEFAULT_SPEECH) -> Path:+ entry = SPEECH[name]+ target = MODELS / f"faster-whisper-{name}"+ target.mkdir(parents=True, exist_ok=True)+ record = _verified(target)+ for file, sha256 in entry["files"].items():+ if not _present(target / file, sha256, record):+ url = f"https://huggingface.co/{entry['repo']}/resolve/{entry['revision']}/{file}"+ _download(url, target / file, sha256, f"the speech model ({name}): {file}")+ _present(target / file, sha256, record)+ record["revision"] = entry["revision"]+ (target / _VERIFIED).write_text(json.dumps(record, indent=1) + "\n")+ return target+++def missing() -> list[str]:+ """What setup still has to fetch (by presence only; `fetch` checks the contents)."""+ out = [VISION[n]["what"] for n in VISION if not (MODELS / VISION[n]["file"]).exists()]+ folder = MODELS / f"faster-whisper-{DEFAULT_SPEECH}"+ if any(not (folder / f).exists() for f in SPEECH[DEFAULT_SPEECH]["files"]):+ out.append(f"the speech model ({DEFAULT_SPEECH})")+ return out+++def main(argv: list[str] | None = None) -> int:+ ap = argparse.ArgumentParser(prog="python -m fx.core.models")+ sub = ap.add_subparsers(dest="cmd", required=True)+ sub.add_parser("fetch", help="fetch the models this pack needs, checking each file")+ sub.add_parser("fetch-vision", help="[LumReels] fetch only the face and person models (the speech "+ "model comes from FX_WHISPER instead)")+ sub.add_parser("check", help="say which models are present")+ args = ap.parse_args(argv)+ if args.cmd == "fetch":+ for name in VISION:+ fetch_vision(name)+ fetch_speech(DEFAULT_SPEECH)+ print(" models ready (each file checked against its pinned checksum)")+ return 0+ if args.cmd == "fetch-vision":+ for name in VISION:+ fetch_vision(name)+ print(" vision models ready (each file checked against its pinned checksum)")+ return 0+ gone = missing()+ print("models: " + ("all present" if not gone else "missing " + ", ".join(gone)))+ return 0 if not gone else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/edit/askeditor/fx/core/moments.py b/edit/askeditor/fx/core/moments.pynew file mode 100644index 0000000..6da14c1--- /dev/null+++ b/edit/askeditor/fx/core/moments.py@@ -0,0 +1,824 @@+"""The moment that matters: the word or the line an effect sets by itself, chosen the same way by all.++What no picker ever sets, wherever it looks:++- **A word the speaker takes back** straight after saying it (`restated`): "the lively town, or+ the lively city" takes "town" back for "city", and a creator would say "I said city".+- **The words of a first attempt** said again (`find_retakes`): the take that clean-cut cuts.+- **An aside** (`asides.asides`): a sentence about the recording rather than to the viewer ("Give+ me a second.", "Testing, testing.", "I think this audio works better."), which clean-cut cuts too.+- Fillers ("um", "uh"), and the words the transcriber was unsure of (`Clip.words` leaves those+ out already, so nothing here reads the words' cache).++`taken_back(words, quiet)` gathers the first three, each with why.++How strong a word or a line is, for every picker:++- `word_strength`: how well one word stands alone, large, for its line: a noun at the end of its+ phrase, a name, a number; never grammar, a filler or a vague word (`NOT_KEY`). The measure+ words-behind was built on, moved here.+- `line_strength`: how well a short stretch of words stands as a line of its own: a whole clause,+ short, its words strong, not cut out of the middle of a phrase. The measure headline was built+ on, moved here, with its words weighed by `word_strength` rather than by their letters.+- In context (`TakenBack`): a word taken back counts for nothing and no line holds it, and the+ word said instead of it counts as what its line says that is new, as the end of a phrase does.++The pickers on top:++- `pick_word`: words-behind's word (the opening line's, unless another is asked for);+- `pick_line`: headline's line (the strongest in the clip, a scrap of a sentence begun before the+ clip only when nothing else stands);+- `strong_starts`: where prompt-box may send a prompt (the start of a spoken line, weighed by the+ line that starts there).+"""++from __future__ import annotations++import math+from dataclasses import dataclass, field+from typing import Callable, Optional++from .asides import asides+from .words import FILLERS, HESITATIONS, Word, pause_after++# ---- the words that are never the point of a line --------------------------------------------+#+# Grammar, filler and words too vague to be the point of a line. Written for this pack. (Captions,+# headline and clean-cut read these through `fx/effects/captions.py` under their old names.)+NOT_KEY = set("""+a an the this that these those my your his her its our their some any no every each all both either neither+few many much more most less least other another such what which whose whatever whichever+i me you he him she it we us they them myself yourself himself herself itself ourselves yourselves themselves+mine yours hers ours theirs who whom someone somebody something anyone anybody anything everyone everybody+everything nobody nothing one ones+i'm i've i'll i'd you're you've you'll you'd he's she's it's we're we've we'll we'd they're they've they'll+they'd that's there's here's what's who's let's isn't aren't wasn't weren't don't doesn't didn't can't couldn't+won't wouldn't shouldn't haven't hasn't hadn't ain't gonna wanna gotta kinda sorta dunno+am is are was were be been being do does did doing done have has had having can could will would shall should+may might must get gets got getting go goes going gone went+about above across after against along among around as at before behind below beneath beside between beyond by+down during except for from in inside into like near of off on onto out outside over past since through+throughout till to toward towards under until up upon with within without via per+and but or nor so yet because although though while whereas if unless than then whether once when whenever+where wherever why how+just really very quite pretty actually basically literally totally simply still even also too only already+almost always never ever often sometimes maybe perhaps probably here there now today again back away well else+instead rather kind sort lot lots bit thing things stuff way ways okay ok yeah yes oh hey hi hello right sure+alright guys+make makes made making take takes took taking put puts say says said saying tell told see saw seen know knew+known think thought want wants wanted need needs let lets come comes came give gives gave look looks mean means+meant use used try tried keep kept feel felt seem seems start started+""".split()) | FILLERS++NUMBER_WORDS = set("""+zero two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen+eighteen nineteen twenty thirty forty fifty sixty seventy eighty ninety hundred thousand million billion+first second third half double triple percent+""".split())++# Words that lead into the next word: a phrase that ends on one of these ("how to make a") leaves+# the reader hanging, so the cut avoids it.+LEADS_ON = set("""+a an the my your his her its our their this these those every each some any no+to of in on at for with from by into onto about over under after before between through without+and but or nor so because if than as while when where whether although though that which who+i we they he she i'm i've i'll i'd we're we've we'll we'd they're they've they'll they'd you're you've you'll+you'd he's she's it's there's here's let's+am is are was were be been being have has had do does did will would can could should may might must+gonna wanna gotta very really just quite such+""".split())++# Words that open a new clause: a break just before one is a natural place to breathe, and the+# word before it ("draws people in | and all the way") does not lead on, whatever it is.+OPENS = set("""+and but or so because then which who what when where while although though if unless+i we you they he she it's that's there's here's let's i'm i've we're we've+""".split())++SPECIFIC = 5 # a key word must score at least this (letters, plus extra for numbers and names)+EDGE_PUNCT = "\"'“”‘’.,;:!?()[]{}…-–—"+++def shown(word: Word) -> str:+ """The word as a caption shows it: no commas or full stops, but questions and exclamations kept."""+ t = word.clean.strip()+ t = t.rstrip(",.;:…").lstrip("\"“‘(")+ return t.rstrip("\"”’)") or word.text.strip()+++def bare(word: Word) -> str:+ """The word with nothing at either edge: how a key word is shown."""+ return word.clean.strip().strip(EDGE_PUNCT) or shown(word)+++def key_score(words: list[Word], i: int) -> int:+ """How specific word `i` is: its letters, plus extra for a number, an acronym or a name; 0 for+ grammar and filler."""+ w = words[i]+ k = w.key+ if not k or k in NOT_KEY:+ return 0+ raw = bare(w)+ score = sum(c.isalpha() for c in k)+ if any(c.isdigit() for c in k) or k in NUMBER_WORDS:+ score += 4+ if len(raw) >= 2 and raw.isupper():+ score += 6 # an acronym is nearly always the thing being named (UGC, AI)+ elif raw[:1].isupper() and i > 0 and not words[i - 1].ends_sentence:+ score += 2 # a name in the middle of a sentence+ if w.text.rstrip().endswith("!"):+ score += 1+ return score+++# ---- first attempts said again ---------------------------------------------------------------+#+# Moved here from clean-cut, which cuts what this finds, so a picker passes over what a cut takes out.++# Words people repeat on purpose: a double one is kept.+ON_PURPOSE = set("""+very really so no yes yeah ha haha bye go more that had many much again over on far too hey oh wow well blah+knock tick tock boom bang run now quick fast please come hello hi okay ok testing check one two+""".split())+RETAKE_WINDOW = 8.0 # a restart counts when it comes within this many seconds of the first attempt+LONGEST_TAKE = 16 # the most words a first attempt can have+++def _broken_off(words: list[Word], a: int, b: int, quiet) -> bool:+ """Does the speech break between words[a] and words[b] (b > a)? A cut-off word, a comma or a+ full stop, a filler between them, or a real pause in the sound."""+ w = words[a]+ if w.text.rstrip().endswith(("-", "—", "–", "…", "...", ",", ".", "?", "!", ";", ":")):+ return True+ if any(x.key in HESITATIONS for x in words[a + 1:b]):+ return True+ return pause_after(words, b - 1, quiet) >= 0.12 or (b - 1 != a and pause_after(words, a, quiet) >= 0.12)+++def find_retakes(words: list[Word], quiet) -> list[tuple[int, int, int, str]]:+ """(first, last, restart, reason) for each first attempt to drop: words[first..last] (inclusive)+ are said again from words[restart].++ A phrase begun and then said again within `RETAKE_WINDOW` seconds keeps only its last take.+ The first attempt must be mostly said again, must break off (a cut-off word, a comma, an "um",+ or a real pause), and must not run across a full stop unless every word of it is said again.+ A list ("most ads, most people") repeats one word only and is never taken for a retake. A word+ said twice in a stammer ("the the") is one too, unless people double it on purpose ("very+ very", "no no")."""+ idx = [i for i, w in enumerate(words) if w.key not in HESITATIONS]+ keys = [words[i].key for i in idx]+ found: list[tuple[int, int, int, str]] = []+ floor = 0 # a first attempt never starts before the last restart found+ for j in range(1, len(idx)):+ best = None+ for i in range(j - 1, floor - 1, -1):+ if words[idx[j]].start - words[idx[i]].start > RETAKE_WINDOW or j - i > LONGEST_TAKE:+ break+ span = j - i+ k = 0+ while k < span and j + k < len(idx) and keys[i + k] == keys[j + k]:+ k += 1+ if k == 0:+ continue+ first, restart = words[idx[i]], words[idx[j]]+ last = words[idx[j - 1]]+ inside = [words[idx[x]] for x in range(i, j - 1)]+ whole = k == span and span >= 3 # every word of the first attempt said again, in order+ if any(w.ends_sentence for w in inside) and not whole:+ continue # a partial match across a full stop is two sentences, not one phrase+ broke = _broken_off(words, idx[j - 1], idx[j], quiet)+ if span == 1:+ # A word said twice: a stammer, unless the word is one people double on purpose or+ # the first ends a clause ("Testing, testing.").+ if (k >= 1 and first.key not in ON_PURPOSE and len(first.key) <= 12+ and not first.text.rstrip().endswith((",", ".", "?", "!", ";", ":"))+ and restart.start - first.end < 1.0):+ cand = (k, i, "stammer")+ else:+ continue+ else:+ if k < 2:+ continue+ divergent = span - k+ if divergent > max(2, span // 3):+ continue # most of the first attempt is not said again: not a retake+ matched = [words[idx[x]] for x in range(j, j + k)]+ specific = any(w.key not in NOT_KEY for w in matched)+ if not (k >= 4 or (broke and (k >= 3 or specific))):+ continue+ # A whole phrase said again is a retake; one broken off before its end and begun+ # again (the restart carries on past where it stopped) is a false start.+ reason = "retake" if divergent == 0 and last.ends_clause else "false start"+ cand = (k, i, reason)+ if best is None or cand[0] > best[0]:+ best = cand+ # A word cut off part-way and started again: "pro- product".+ if best is None:+ prev, cur = words[idx[j - 1]], words[idx[j]]+ if (prev.text.rstrip().endswith(("-", "—", "–")) and len(prev.key) >= 2+ and cur.key.startswith(prev.key) and cur.key != prev.key):+ best = (1, j - 1, "false start")+ if best is not None:+ _, i, reason = best+ found.append((idx[i], idx[j - 1], idx[j], reason))+ floor = j+ return found+++# ---- words taken back straight after they are said ---------------------------------------------+#+# A speaker who corrects one word says it again in a few set ways, each with a break before the+# correction: "the lively town, or the lively city", "on Tuesday, I mean Wednesday", "three, sorry,+# four", "red — no, blue". What reads as the same thing but is not one: alternatives ("the red one,+# or the blue one", "a train or a bus", "now or never"), a phrase said again to stress it ("fast, I+# mean really fast"), an answer to a question ("Red? No, blue."), an apology ("I'm late, sorry,+# the traffic"). The rules below keep to the shapes that are corrections; a hit is a strong penalty+# for a picker, so a correction missed costs a little more than one wrongly found, which costs+# little (the picker takes another word).++BREAK = 0.2 # a gap in the voice at least this long, with no comma written, still sets off a correction+LEAD_IN = 4 # the most words of the lead-in a correction says again ("the lively" town, or "the lively" city)+# The words that set a correction off, longest first. "or" alone needs the lead-in said again+# (with a word in it that is not grammar); the others say "this replaces that" by themselves.+_MARKERS = (("or", "rather"), ("or", "i", "mean"), ("i", "mean"), ("i", "meant"), ("sorry",), ("no",), ("or",))+# Before an "or", these make it a choice between two things, not a correction.+_CHOICE = {"either", "whether", "between", "choose", "pick", "prefer", "rather", "than"}+_DASHES = ("-", "—", "–")+++def _content(w: Word) -> bool:+ return bool(w.key) and w.key not in NOT_KEY+++def _set_off(words: list[Word], a: int, b: int, quiet) -> bool:+ """Is there a break in the voice between words[a] and words[b] (b > a)? A comma, a dash or+ another stop written after words[a], a filler between them, or a pause."""+ if words[a].text.rstrip().endswith((",", ";", ":", "…", "...") + _DASHES):+ return True+ if any(x.key in HESITATIONS for x in words[a + 1:b]):+ return True+ if quiet is not None:+ return pause_after(words, b - 1, quiet) >= BREAK or pause_after(words, a, quiet) >= BREAK+ return words[b].start - words[a].end >= BREAK+++def _same_word(a: str, b: str) -> bool:+ """One word said again rather than replaced: the same, or the same with an s."""+ return a == b or (min(len(a), len(b)) >= 3 and a.rstrip("s") == b.rstrip("s"))+++def restated(words: list[Word], quiet=None) -> dict[int, int]:+ """The words a speaker replaces straight after saying them: {index of the word taken back:+ index of the word said instead}.++ The word taken back (X) is the word just before the correction, set off from it by a break (a+ comma, a dash, a filler or a pause), never the end of a sentence; the correction is one of:++ - "X, or" with the lead-in before X said again and a new word after it: "the lively town, or+ the lively city" (town -> city). The lead-in must hold a word that is not grammar: "a train+ or a bus" and "the red one, or the blue one" are a choice between two things, as is any+ "or" after "either", "whether" or "between", or in a question.+ - "X, or rather Y", "X, I mean Y", "X, sorry, Y" and "X — no, Y" (after "sorry" or "no", a+ second break): the lead-in may be said again ("on Tuesday, I mean on Wednesday") or not.+ After these, a correction may say its last word again: in "ten dollars, sorry, twelve+ dollars" the word taken back is "ten", and "dollars" is said again with "twelve".++ Either way the new word (Y) must be one that is not grammar, said straight after the marker and+ the lead-in, and not X again: "fast, I mean really fast" stresses "fast" and takes nothing back.+ `quiet` (the clip's quiet stretches) tells a pause from a word ending; without it the gaps+ between the word times are read."""+ return {x: y for x, y, _ in _corrections(words, quiet)}+++def _corrections(words: list[Word], quiet) -> list[tuple[int, int, list[int]]]:+ """Each correction `restated` finds: (the word taken back, the word said instead, the lead-in+ before the word taken back that the correction says again: "the lively" of "the lively town,+ or the lively city")."""+ idx = [i for i, w in enumerate(words) if w.key and w.key not in HESITATIONS]+ keys = [words[i].key for i in idx]+ out: list[tuple[int, int, list[int]]] = []+ seen: set[int] = set()+ for p in range(1, len(idx)):+ x = idx[p - 1]+ X = words[x]+ if not _content(X) or X.ends_sentence or x in seen:+ continue+ marker = next((m for m in _MARKERS if tuple(keys[p:p + len(m)]) == m), None)+ if marker is None:+ continue+ m0, m1 = idx[p], idx[p + len(marker) - 1]+ if not _set_off(words, x, m0, quiet):+ continue+ after = p + len(marker) # the first word after the marker, in idx+ if after >= len(idx):+ continue+ if marker in (("sorry",), ("no",)) and not _set_off(words, m1, idx[after], quiet):+ continue # "sorry" and "no" set off on both sides: "three, sorry, four"+ # The lead-in said again: the longest run of the words before X that the correction opens with.+ k = next((k for k in range(min(LEAD_IN, p - 1), 0, -1)+ if keys[p - 1 - k:p - 1] == keys[after:after + k]), 0)+ if after + k >= len(idx):+ continue+ y = idx[after + k]+ Y = words[y]+ if not _content(Y) or _same_word(Y.key, X.key):+ continue+ if any(_same_word(keys[q], X.key) for q in range(after + k + 1, min(len(idx), after + k + 4))):+ tail = _tail_form(words, idx, keys, p, after, marker)+ if tail is not None and tail[0] not in seen:+ out.append(tail)+ seen.add(tail[0])+ continue # X said again just after: stressed or explained, not replaced+ if marker == ("or",):+ lead = keys[p - 1 - k:p - 1]+ if k == 0 or not any(key not in NOT_KEY for key in lead):+ continue # "a train or a bus", "now or never": two things, not a correction+ before = keys[max(0, p - 1 - k - 6):p - 1 - k]+ if any(key in _CHOICE for key in before):+ continue+ # A question offering both ("Do you want the red car, or the red bus?").+ end = next((q for q in range(after + k, min(len(idx), after + k + 10)) if words[idx[q]].ends_sentence), None)+ if end is not None and words[idx[end]].text.rstrip().endswith("?"):+ continue+ out.append((x, y, idx[p - 1 - k:p - 1]))+ seen.add(x)+ return out+++def _tail_form(words: list[Word], idx: list[int], keys: list[str], p: int, after: int,+ marker: tuple) -> Optional[tuple[int, int, list[int]]]:+ """A correction that says its last word again: "ten dollars, sorry, twelve dollars", "2,000+ followers, no, 3,000 followers", "on the train, I mean on the bus" is not this (the word replaced+ is the last). Here the word before X is replaced (ten -> twelve) and X ("dollars") is said again+ straight after the new word, with the lead-in before them said again too, if any. Only after a+ marker that says "this replaces that" by itself: a bare "or" offers a choice ("the red car, or the+ blue car"). (taken back, said instead, the lead-in said again with X), or None."""+ if marker == ("or",) or p < 2:+ return None+ x2, X = idx[p - 2], words[idx[p - 1]]+ k = next((k for k in range(min(LEAD_IN, p - 2), 0, -1) if keys[p - 2 - k:p - 2] == keys[after:after + k]), 0)+ if after + k + 1 >= len(idx) or not _same_word(keys[after + k + 1], X.key):+ return None+ y = idx[after + k]+ if not _content(words[x2]) or not _content(words[y]) or _same_word(words[y].key, words[x2].key):+ return None+ return x2, y, idx[p - 2 - k:p - 2] + [idx[p - 1]]+++# ---- everything a picker passes over ----------------------------------------------------------++@dataclass+class TakenBack:+ """The words a picker never sets, each with why, and the words said instead of one."""+ why: dict = field(default_factory=dict) # Word -> why it is passed over+ instead: dict = field(default_factory=dict) # Word taken back -> the Word said instead++ def __contains__(self, w: Word) -> bool:+ return w in self.why++ @property+ def said_instead(self) -> set:+ return set(self.instead.values())++ def holds(self, words: list[Word], first: int, last: int) -> bool:+ """Does `words[first..last]` hold a word passed over: a figure said and taken back ("ten,+ sorry, twelve"), a name in a first attempt, a phrase in an aside. For an effect that keeps its+ own reason for choosing (a figure for a chart, a file's name) and only needs the filter."""+ return any(w in self.why for w in words[max(0, first):last + 1])+++def taken_back(words: list[Word], quiet) -> TakenBack:+ """What the speaker took back in `words` (give a clip's whole `words`, fillers and all, so a+ first attempt broken off by an "um" is found): the words replaced straight after they were said+ (`restated`) with the lead-in the correction says again ("the lively" of "the lively town, or+ the lively city"), the words of every first attempt said again (`find_retakes`), and every+ word of an aside, said about the recording rather than to the viewer (`asides`). Words are+ kept by themselves, not by their place, so an effect that leaves fillers out can ask of its own+ list."""+ out = TakenBack()+ for x, y, lead in _corrections(words, quiet):+ out.why[words[x]] = f"taken back for \"{bare(words[y])}\" ({words[y].start:.2f} s)"+ out.instead[words[x]] = words[y]+ for i in lead: # "the lively" town, or the lively city: said again with the word that replaces it+ out.why.setdefault(words[i], f"said again with \"{bare(words[y])}\" ({words[y].start:.2f} s)")+ for first, last, restart, reason in find_retakes(words, quiet):+ for i in range(first, last + 1):+ out.why.setdefault(words[i], f"a {reason}, said again from {words[restart].start:.2f} s")+ for a in asides(words, quiet):+ for i in range(a.first, a.last + 1):+ out.why.setdefault(words[i], f"an aside ({a.kind}), said about the recording, not to the viewer")+ return out+++# ---- how strong a word is ---------------------------------------------------------------------+#+# Specific is not enough: "perspective" is longer than "hooks", and "professionally" longer than+# "videos". What lands is the thing named, which in English sits at the end of its phrase.++_GENERIC = set("""+perspective perspectives issue issues way ways part parts kind kinds type types sort sorts thing things aspect+aspects point points side sides term terms case cases matter fact facts example examples reason reasons amount+lot lots bit bits stuff rest sense regard respect basis manner instance couple while bunch piece pieces number+level levels process situation question questions problem+""".split())+_LY_NOUNS = set("family supply reply ally rally belly jelly italy july lily assembly anomaly butterfly monopoly "+ "holly reality ugly early".split())+_DETERMINERS = set("a an the my your our their his her its this that these those every each some any no another "+ "one".split())+_PREPOSITIONS = set("of in on at for with from by into onto about over under after before between through "+ "without to".split())+# A word straight after one of these is usually doing, not naming.+_BEFORE_VERBS = set("i you we they he she to will would can could should must may might while when "+ "i'll you'll we'll they'll don't didn't can't won't".split())+# Two words that say nothing apart from each other: "of course" names no course.+_IDIOMS = {("of", "course"), ("at", "least"), ("at", "all"), ("in", "fact"), ("you", "know"), ("by", "far"),+ ("for", "sure"), ("no", "doubt"), ("in", "general"), ("at", "first"), ("in", "total")}+PHRASE_END = 3.0 # what the end of a phrase adds: where a sentence puts what is new+++# Public names for other effects: words too general to be the point, and words that come before a verb.+GENERIC = _GENERIC+BEFORE_VERBS = _BEFORE_VERBS+++def _letters(k: str) -> int:+ return sum(c.isalpha() for c in k) or sum(c.isdigit() for c in k)+++def ends_phrase(words: list[Word], i: int, line: list[int], quiet) -> bool:+ """Is word `i` the end of a phrase: a stop written after it, the end of its line, or a pause?"""+ return (words[i].text.rstrip().endswith((",", ".", "!", "?", ";", ":")) or i == line[-1]+ or pause_after(words, i, quiet) >= 0.25)+++def _alone(words: list[Word], i: int) -> Optional[float]:+ """What word `i` says by itself, wherever it sits: how specific it is (`key_score`), a long word+ no better than one of eight letters, less for a vague word ("perspective", "issue") or an+ adverb in -ly; None for a word that never counts (grammar, a filler, half of an idiom such as+ "of course", or a word the transcriber gave less than 0.4)."""+ w = words[i]+ k = w.key+ if w.prob < 0.4 or k in HESITATIONS:+ return None+ base = key_score(words, i) # letters, plus numbers, acronyms and names; 0 for grammar and filler+ if base <= 0:+ return None+ n = _letters(k)+ score = base - n + min(n, 8) # a longer word is not a better one past eight letters+ if n > 10:+ score -= 0.5 * (n - 10)+ if k in _GENERIC:+ score -= 4+ if k.endswith("ly") and len(k) > 4 and k not in _LY_NOUNS:+ score -= 4+ prev = words[i - 1].key if i > 0 else ""+ if (prev, k) in _IDIOMS:+ return None+ return float(score)+++def word_strength(words: list[Word], i: int, line: list[int], quiet) -> float:+ """How well word `i` stands alone, giant, for the line it is in (`line`: its indexes). 0 for a+ word that never should. What it says by itself (`_alone`), and where it sits: the thing named+ is at the end of its phrase, after "the" or "a", not straight after "I" or "to" (doing, not+ naming) nor before "of". The word by itself: `strength` weighs it with what was taken back."""+ score = _alone(words, i)+ if score is None:+ return 0.0+ nxt = words[i + 1].key if i + 1 < len(words) else ""+ prev = words[i - 1].key if i > 0 else ""+ if ends_phrase(words, i, line, quiet):+ score += PHRASE_END+ if nxt == "of":+ score -= 3 # "the perspective of hooks": the noun after "of" is the one named+ if prev in _BEFORE_VERBS:+ score -= 4+ elif prev in _PREPOSITIONS:+ score += 1+ for back in range(1, 4): # "a video", "your production quality"+ if i - back < line[0]:+ break+ if words[i - back].key in _DETERMINERS:+ score += 2+ break+ if words[i - back].ends_clause:+ break+ return max(0.0, float(score))+++def _a_length_of_time(words: list[Word], i: int) -> float:+ """What a number word loses when it is not a figure: "give me a second" names a length of time,+ not a place in a row, so "second" there earns nothing as a number (`key_score` gives 4)."""+ return 4.0 if words[i].key == "second" and i > 0 and words[i - 1].key in ("a", "one") else 0.0+++def strength(words: list[Word], i: int, line: list[int], quiet, back: TakenBack) -> float:+ """`word_strength` with what was taken back: nothing for a word taken back, and the end of a+ phrase's weight for the word said instead of one ("the lively *city*"), which is the new thing+ its line says however it is placed."""+ w = words[i]+ if w in back or w.key in HESITATIONS:+ return 0.0+ s = word_strength(words, i, line, quiet)+ if s > 0 and w in back.said_instead and not ends_phrase(words, i, line, quiet):+ s += PHRASE_END+ return max(0.0, s - _a_length_of_time(words, i))+++# Adverbs that say how the speaker stands to a line, not what it says: a line of these and grammar+# says nothing ("I eventually went to,"). An adverb of manner says something ("edit your videos+# professionally") and counts like any word.+_HOLLOW = set("""+eventually finally honestly obviously usually recently currently generally definitely certainly seriously+hopefully personally apparently clearly essentially exactly absolutely completely entirely fully nearly mostly+mainly especially particularly specifically ultimately initially originally typically naturally normally+possibly likely surely truly merely barely hardly lately frankly fortunately unfortunately luckily sadly+interestingly importantly additionally consequently previously+""".split())+++def line_weight(words: list[Word], i: int, back: TakenBack) -> float:+ """What word `i` adds to a line, wherever it sits, since a line needs its verb as much as its+ noun ("*edit* your videos"): how specific it is (`key_score`: its letters, more for a number,+ an acronym or a name), less for a vague word ("perspective", "issue"); nothing for grammar, a+ filler, half of an idiom ("of course"), an adverb that says nothing (`_HOLLOW`), a word the+ transcriber gave less than 0.4, or a word taken back; and the end of a phrase's weight more for+ the word said instead of one ("the lively *city*")."""+ w = words[i]+ k = w.key+ if w in back or w.prob < 0.4 or k in HESITATIONS or k in _HOLLOW:+ return 0.0+ if i > 0 and (words[i - 1].key, k) in _IDIOMS:+ return 0.0+ base = key_score(words, i)+ if base <= 0:+ return 0.0+ s = base - (4 if k in _GENERIC else 0) - _a_length_of_time(words, i)+ return max(0.0, float(s)) + (PHRASE_END if w in back.said_instead else 0.0)+++# ---- lines --------------------------------------------------------------------------------------++def lines(words: list[Word], quiet) -> list[list[int]]:+ """Word indexes split into lines: at the end of a sentence or a clause, where the voice stops,+ and at a filler (which belongs to no line)."""+ out, cur = [], []+ for i, w in enumerate(words):+ if w.key in HESITATIONS:+ if cur:+ out.append(cur)+ cur = []+ continue+ cur.append(i)+ if w.ends_clause or pause_after(words, i, quiet) >= 0.3:+ out.append(cur)+ cur = []+ if cur:+ out.append(cur)+ return out+++def scrap_lines(words: list[Word], runs: list[list[int]]) -> set[int]:+ """The lines (by number) of a sentence the clip came in on halfway: a scrap, not a line of its+ own. A clip that opens on a word in lower case, within a quarter second of its start, opens+ in the middle of a sentence; its lines up to the first full stop are the scrap."""+ if not words or words[0].start > 0.25:+ return set()+ first = words[0].clean.strip("\"'“‘(")+ if not first or not first[0].islower() or words[0].key == "i":+ return set()+ out = set()+ for n, ln in enumerate(runs):+ out.add(n)+ if words[ln[-1]].ends_sentence:+ break+ return out if len(out) < len(runs) else set()+++# Words a line never opens on: it would hang off the line before.+_JOINS = ("and", "but", "or", "so", "because", "then")+MAX_LINE = 6 # the most words a line is weighed over+# A line the speaker opens by hedging is an opinion said in passing, not the point ("I think this+# audio works better"): it loses HEDGE.+_HEDGES = (("i", "think"), ("i", "guess"), ("i", "suppose"), ("i", "feel"), ("maybe",), ("perhaps",), ("probably",))+HEDGE = 3.0+++def line_strength(words: list[Word], run: list[int], a: int, b: int, quiet, back: TakenBack) -> Optional[float]:+ """How well words run[a:b] (a stretch of the line `run`) stands as a line of its own, or None+ when it never should: under two words; ending on a word that leads into the next ("the", "to")+ unless a comma closes it, or on a word broken off; opening on "and" or "so"; holding a word+ taken back; or holding a word the transcriber was unsure of.++ Its words count by what each says by itself (`line_weight`: grammar and fillers add nothing, a+ vague word or an adverb little), and one of them must be specific enough to be the point+ (`SPECIFIC`). A clause said whole counts too: a fragment of two long words ("marketing+ campaign") is a label, a whole clause is a line. A line is short, so every letter past eighteen+ costs a little, a line opened by a hedge ("I think…") costs `HEDGE`, and a+ stretch cut out of the middle of a phrase ("your | videos professionally") costs more, unless+ what it leaves behind is the "and" or "or" that joins it to the line before ("or | the lively+ city come to life")."""+ idx = run[a:b]+ n = len(idx)+ if n < 2:+ return None+ first, last = words[idx[0]], words[idx[-1]]+ if (last.key in LEADS_ON and not last.ends_clause) or last.text.rstrip().endswith(("-", "—", "…")):+ return None+ if first.key in _JOINS:+ return None+ if any(words[i] in back for i in idx):+ return None # never a word the speaker took back+ probs = [words[i].prob for i in idx]+ if min(probs) < 0.5 or sum(probs) / n < 0.75:+ return None # never words the transcriber was unsure of+ weights = [line_weight(words, i, back) for i in idx]+ content = sum(weights)+ if max(weights) < SPECIFIC:+ return None # no word in it says enough to be the point of a line ("I eventually went to")+ score = 0.5 * content + 1.2 * content / n+ score += 5.0 if (a == 0 and b == len(run)) else 0.0+ score += 1.5 if a == 0 else 0.0+ score += 2.0 if last.ends_sentence else (1.0 if last.ends_clause else 0.0)+ score -= 4.0 if n < 3 else 0.0+ score -= 1.5 * max(0, n - 5)+ if any(tuple(words[i].key for i in idx[:len(h)]) == h for h in _HEDGES):+ score -= HEDGE+ letters = sum(len(words[i].clean) for i in idx) + n - 1+ score -= 0.25 * max(0, letters - 18)+ # cut out of the middle of a phrase: "your | videos professionally", "edit your videos | professionally"+ before = words[idx[0] - 1] if idx[0] > 0 else None+ after = words[idx[-1] + 1] if idx[-1] + 1 < len(words) else None+ if a > 0 and before is not None and not before.ends_clause:+ if before.key in LEADS_ON and before.key not in _JOINS:+ score -= 3.0+ elif first.key in LEADS_ON:+ score -= 2.0 # "improve | your production quality": the verb left behind+ if b < len(run) and after is not None and not last.ends_clause and after.key not in OPENS:+ score -= 1.5+ return score+++SCRAP = 6.0 # what a scrap of a sentence begun before the clip loses, as a line+++def pick_line(words: list[Word], quiet, reach: Optional[Callable[[int, int], float]] = None,+ back: Optional[TakenBack] = None, ranked: Optional[list] = None) -> Optional[tuple[int, int]]:+ """The line that makes the point: (first, last) word indexes of the strongest stretch of two to+ six words (`line_strength`), a scrap of a sentence the clip came in on halfway losing `SCRAP`.+ When `reach(first, last)` says how large a line could be set where it would sit (1 at full+ size), a line that would come out small loses to one that would not. `back`: what was taken+ back, from the clip's whole words (found from `words` when not given). `ranked`, when given a+ list, is filled with every line weighed, strongest first: (score, (first, last))."""+ back = taken_back(words, quiet) if back is None else back+ runs = lines(words, quiet)+ scraps = scrap_lines(words, runs)+ scored = []+ for n_run, run in enumerate(runs):+ for a in range(len(run)):+ for b in range(a + 2, min(len(run), a + MAX_LINE) + 1):+ s = line_strength(words, run, a, b, quiet, back)+ if s is not None:+ scored.append((s - (SCRAP if n_run in scraps else 0.0), (run[a], run[b - 1])))+ if not scored:+ return None+ scored.sort(key=lambda s: -s[0])+ if ranked is not None:+ ranked.extend(scored)+ if reach is None:+ return scored[0][1]+ best, best_score = None, -math.inf+ for score, span in scored[:10]:+ r = max(1e-3, reach(*span))+ total = score + 6.0 * math.log(min(1.0, r))+ if total > best_score:+ best, best_score = span, total+ return best+++# ---- the word for a line -----------------------------------------------------------------------++MIN_HERO = 8.0 # a line's best word must score this to be chosen without being asked for+++@dataclass+class Candidate:+ index: int+ word: Word+ score: float+ line: list[int]+ scrap: bool = False+++def best_in(words: list[Word], line: list[int], quiet, back: Optional[TakenBack] = None) -> Optional[Candidate]:+ """The strongest word of a line (a tie goes to the later word), or None when none stands."""+ back = TakenBack() if back is None else back+ best = None+ for i in line:+ s = strength(words, i, line, quiet, back)+ if s > 0 and (best is None or s >= best.score):+ best = Candidate(i, words[i], s, line)+ return best+++def pick_word(words: list[Word], quiet, back: Optional[TakenBack] = None, start_after: float = 0.0,+ within: Optional[tuple[float, float]] = None) -> tuple[Optional[Candidate], list[Candidate]]:+ """The word for the line that lands, and up to three runners-up: the best word of the first+ whole line whose best word scores `MIN_HERO`, else the best that does anywhere, else none.+ `within` limits it to a stretch the person named (the best word there, however plain);+ `start_after` to the lines from a time on. `back`: what was taken back, from the clip's whole+ words (found from `words` when not given)."""+ back = taken_back(words, quiet) if back is None else back+ runs = lines(words, quiet)+ scrap = scrap_lines(words, runs)+ cands = []+ for n, ln in enumerate(runs):+ if within is not None:+ ln = [i for i in ln if within[0] - 0.05 <= words[i].start <= within[1] + 0.05]+ if not ln:+ continue+ elif words[ln[-1]].end < start_after:+ continue+ c = best_in(words, ln, quiet, back)+ if c is not None:+ c.scrap = n in scrap+ cands.append(c)+ ranked = sorted(cands, key=lambda c: -c.score)+ if within is not None:+ return (ranked[0] if ranked else None), ranked[1:4]+ for c in cands: # the first whole line whose word is strong enough+ if not c.scrap and c.score >= MIN_HERO:+ return c, [r for r in ranked if r is not c][:3]+ good = [c for c in ranked if c.score >= MIN_HERO]+ if good:+ return good[0], [r for r in ranked if r is not good[0]][:3]+ return None, ranked[:3]+++def key_word(words: list[Word], quiet, back: Optional[TakenBack] = None, least: float = SPECIFIC) -> Optional[int]:+ """The word of a line given whole (`words` is the line) to set in the accent: its strongest,+ a tie going to the later word, or None when none reaches `least`."""+ c = best_in(words, list(range(len(words))), quiet, back)+ return c.index if c is not None and c.score >= least else None+++# ---- where a moment may land ----------------------------------------------------------------------++@dataclass+class Start:+ at: float # when the word that starts the line begins+ index: int # that word, in the words given+ strength: Optional[float] # of the line it opens; None when no line stands there+ line: Optional[tuple[int, int]] = None # that line: (first, last) word indexes+ sentence: bool = False # it opens a sentence (the clip's first word, or the first after a full stop)+++OPENS_WITHIN = 1.0 # seconds: a moment lands on a line that begins this soon after it, in the same sentence+++def strong_starts(words: list[Word], quiet, back: Optional[TakenBack] = None, pause: float = 0.18) -> list[Start]:+ """Where a spoken line begins, each weighed by the line it opens: a word after a pause of+ `pause` seconds, after the end of a clause, or after a filler (the filler itself is never the+ moment). The line it opens is the strongest that begins on it or within `OPENS_WITHIN` seconds+ after it, in the same sentence, so the start of "Here's a clean, bold subtitle for everyday+ posts" opens "bold subtitle for everyday posts" and the "or" of "or the lively city come to+ life" opens "city come to life". A start the speaker took back (a word replaced, or the first+ word of an attempt said again) is left out."""+ back = taken_back(words, quiet) if back is None else back+ runs = lines(words, quiet)+ run_of = {i: (r, pos) for r in runs for pos, i in enumerate(r)}+ best_from: dict[int, tuple[Optional[float], Optional[tuple[int, int]]]] = {}++ def from_word(k: int) -> tuple[Optional[float], Optional[tuple[int, int]]]:+ """The strongest line that begins on word k."""+ if k not in best_from:+ best, line = None, None+ if k in run_of:+ run, pos = run_of[k]+ for b in range(pos + 2, min(len(run), pos + MAX_LINE) + 1):+ s = line_strength(words, run, pos, b, quiet, back)+ if s is not None and (best is None or s > best):+ best, line = s, (run[pos], run[b - 1])+ best_from[k] = (best, line)+ return best_from[k]++ out = []+ for i, w in enumerate(words):+ if w.key in HESITATIONS or w in back or i not in run_of:+ continue+ if i > 0:+ prev = words[i - 1]+ if not (pause_after(words, i - 1, quiet) >= pause or prev.ends_clause or prev.key in HESITATIONS):+ continue+ best, line = None, None+ k = i+ while k < len(words) and words[k].start - w.start <= OPENS_WITHIN:+ s, ln = from_word(k)+ if s is not None and (best is None or s > best):+ best, line = s, ln+ if words[k].ends_sentence:+ break+ k += 1+ before = [x for x in words[:i] if x.key not in HESITATIONS]+ out.append(Start(w.start, i, best, line, sentence=not before or before[-1].ends_sentence))+ return outdiff --git a/edit/askeditor/fx/core/parts.py b/edit/askeditor/fx/core/parts.pynew file mode 100644index 0000000..569c4eb--- /dev/null+++ b/edit/askeditor/fx/core/parts.py@@ -0,0 +1,731 @@+"""The parts of a talk: where the speaker moves on to a new idea, found from the words and the sound+alone. No model runs beyond the transcriber, nothing is paid for and nothing leaves the computer.++ found = parts.find(clip.words, clip.quiet, duration) # the parts, each with a title+ count, given = parts.parse_titles("Intro | 0:31 The train") # what a person typed as titles=+ found = parts.find(clip.words, clip.quiet, duration, count=count, titles=given)+ lines = parts.chapter_lines(found, duration) # "00:00 Intro", ... for YouTube+ parts.check_chapters(lines, duration) # [] when YouTube would take them++Between every two sentences, and at every real stop in the voice, three kinds of evidence are+weighed:++1. **The voice stops.** A sentence that ends, and how long the quiet after it lasts, read from the+ sound (`clip.quiet`, through `words.pause_after`; the transcriber's own gaps are nearly always+ zero). A long breath between two ideas is the commonest sign of a new one.+2. **A signpost opens the next sentence.** Ordinals and announcements ("first of all", "the second+ thing", "next", "let's talk about", "finally") count fully; "now", "then", "after that" and a+ short question count part way; "so" and "and" barely, since people open every other sentence+ with them.+3. **The words change.** The content words said in the stretch before and the stretch after+ (grammar, filler and vague words left out, plurals folded) are compared: the less they share,+ the likelier a new idea. The measure is a plain cosine between their word counts, each word+ weighted by how rare it is across the talk's sentences (TF-IDF). That is the TextTiling idea+ (Hearst, 1997) at the size of a short talk; on a minute of speech it is the noisiest of the+ three, so it weighs least and mostly decides between two pauses.++The boundaries are then chosen together, by dynamic programming over the candidates: every part+lasts at least `min_part` seconds, and a boundary is taken only when its evidence clears a bar+(`BAR`), so a talk about one thing stays one part. When a number of parts is asked for (as many as+the person gives titles, or a count), exactly that many are made, at the strongest boundaries that+keep every part long enough.++Each part gets a short title of its own key words: the word or pair of words said in it that is+most specific to it and least said elsewhere in the talk (so the part about the hotel is "Hotel",+not "Went"), never a word the speaker took back (`moments.taken_back`). A title the person gives+replaces it, and may carry the time its part begins.++Nothing here draws: the chapter cards, the post copy and anything later read the same parts.+"""++from __future__ import annotations++import math+import re+from collections import Counter+from dataclasses import dataclass, field+from typing import Optional, Sequence++from . import moments+from .words import HESITATIONS, Word, normalize, pause_after++# ---- the numbers that decide -------------------------------------------------------------------++BAR = 1.2 # the evidence a boundary must carry to be taken when nobody says how many parts+SPLIT_PAUSE = 0.45 # a stop in the voice this long is a candidate boundary even mid-sentence+PAUSE_FULL = 1.4 # a pause this long counts fully; shorter ones count in proportion+WEIGHTS = {"pause": 1.0, "sentence": 0.6, "signpost": 1.0, "shift": 0.7, "question": 0.35}+SHORTEST = 4.0 # no part is ever shorter than this, whatever is asked+YOUTUBE_SHORTEST = 10.0 # YouTube Help, "Video Chapters", read 28 October 2026: chapters last 10 s or more+++def auto_min_part(duration: float) -> float:+ """The shortest a part may be when nobody says: a tenth of the video, kept between 6 and 15+ seconds. A 30-second reel can then be cut where its ideas change, and a talk of a few minutes+ gets parts of a quarter of a minute or more."""+ return float(min(15.0, max(6.0, duration / 10.0)))+++def most_parts(duration: float) -> int:+ """The most parts a video is split into when nobody says how many: it grows more slowly than the+ video (4 in half a minute, 6 in two minutes, 9 in five, 18 in half an hour), so a long talk gets+ chapters, not a list of every sentence."""+ return max(2, int(round(0.6 * max(1.0, duration) ** 0.45 + 1.0)))+++# ---- the words that carry no subject -------------------------------------------------------------++# Grammar, filler and the vague verbs and nouns people say about anything: two stretches that share+# only these are not on the same subject, and no title is made of them. Written for this pack.+_PLAIN = set("""+a an the this that these those my your his her its our their some any no every each all both either neither+few many much more most less least other another such what which whose whatever whichever+i me you he him she it we us they them myself yourself himself herself itself ourselves yourselves themselves+mine yours hers ours theirs who whom someone somebody something anyone anybody anything everyone everybody+everything nobody nothing one ones+i'm i've i'll i'd you're you've you'll you'd he's she's it's we're we've we'll we'd they're they've they'll+they'd that's there's here's what's who's let's isn't aren't wasn't weren't don't doesn't didn't can't couldn't+won't wouldn't shouldn't haven't hasn't hadn't ain't gonna wanna gotta kinda sorta dunno+am is are was were be been being do does did doing done have has had having can could will would shall should+may might must get gets got getting go goes going gone went+about above across after against along among around as at before behind below beneath beside between beyond by+down during except for from in inside into like near of off on onto out outside over past since through+throughout till to toward towards under until up upon with within without via per+and but or nor so yet because although though while whereas if unless than then whether once when whenever+where wherever why how+just really very quite pretty actually basically literally totally simply still even also too only already+almost always never ever often sometimes maybe perhaps probably here there now today again back away well else+instead rather kind sort lot lots bit thing things stuff way ways okay ok yeah yes oh hey hi hello right sure+alright guys+make makes made making take takes took taking put puts say says said saying tell told see saw seen know knew+known think thought want wants wanted need needs let lets come comes came give gives gave look looks mean means+meant use used try tried keep kept feel felt seem seems start started+good great nice cool real big little new old first second third next last+eventually finally slowly obviously anyway course+perspective aspect point case fact idea sense side level part piece matter terms example instance issue+actual whole entire certain different same own main mainly best better worse worst nicest lovely amazing+awesome super dot com people person+""".split())++_ORDINALS = ("one two three four five six seven eight nine ten 1 2 3 4 5 6 7 8 9 10 "+ "first second third fourth fifth sixth seventh eighth ninth tenth").split()+++def _stem(key: str) -> str:+ """A word folded for comparing: "trains" and "train", "cities" and "city" count as one."""+ k = key.replace("'s", "").strip("'")+ if len(k) > 4 and k.endswith("ies"):+ return k[:-3] + "y"+ if len(k) > 4 and k.endswith("s") and not k.endswith(("ss", "us", "is")):+ return k[:-1]+ return k+++def content(w: Word) -> Optional[str]:+ """The word's folded form when it carries subject matter, else None. A piece the transcriber+ broke off a longer word ("in -built", "askeditor .com") carries none on its own."""+ k = w.key+ if not k or k in _PLAIN or k in HESITATIONS or w.text.strip()[:1] in "-.":+ return None+ if len(k) < 3 and not any(c.isdigit() for c in k) and not w.clean.isupper():+ return None+ return _stem(k)+++# ---- signposts ---------------------------------------------------------------------------------------++def _phrases(text: str) -> list[tuple[str, ...]]:+ return [tuple(p.split()) for p in text.split(",") if p.strip()]+++# The words a new part is announced with, by how much they say so. Written for this pack.+_FULL = _phrases(+ "first of all, firstly, first, first up, first off, to start, to start with, to begin, to begin with, "+ "let's start, let's begin, let's kick off, second, secondly, third, thirdly, fourth, fifth, next, next up, "+ "moving on, let's move on, on to, onto, now let's, let's talk about, let's look at, let's get into, "+ "let's dive into, let's jump into, let's go over, let's go through, finally, lastly, last but not least, "+ "to finish, to wrap up, to sum up, to recap, in summary, in conclusion, in short, bottom line, "+ "the bottom line, one more thing, another thing, the other thing, the next thing, the last thing, "+ "the final thing, the next step, the last step, the final step, the next one, the last one"+)+_FULL += [("the", o, n) for o in ("first", "second", "third", "fourth", "fifth", "next", "last", "final")+ for n in ("thing", "step", "tip", "part", "one", "reason", "mistake", "rule", "way", "lesson", "idea")]+_FULL += [(lead, n) for lead in ("number", "step", "tip", "part", "rule", "lesson", "reason", "chapter")+ for n in _ORDINALS]+_PART = _phrases(+ "now, so now, okay so, ok so, alright so, all right so, right so, after that, after this, afterwards, "+ "and then, then, eventually, later, later on, meanwhile, once, here's, here is, here are, but here's, "+ "on top of that, what about, how about, now that, at the end, in the end"+)+_SLIGHT = _phrases("so, and so, anyway, anyways, oh and, but, and also, also, plus, and, okay, alright, well")+_LEADS = {"and", "so", "but", "okay", "ok", "alright", "right", "well", "oh", "yeah", "now"} | HESITATIONS+_SUBJECTS = {"i", "we", "you", "they", "he", "she"}+_MOVES_ON = {"then", "eventually", "later", "next", "finally", "also", "afterwards", "now"}+# A new part can begin in the middle of a sentence the transcriber ran on ("...and [pause] after that I+# went..."), but only where a clause can open: never between "I" and "got off", nor before "while".+_OPENERS = set("""+and but so then now after afterwards eventually later meanwhile also plus anyway anyways okay ok alright first+next finally lastly second third another one i we you they he she it it's there here here's this that's let's+what how why my our+""".split()) | HESITATIONS+# Words a part cannot end on, unless the voice stopped after them: "and [pause] I was also..." is the+# speaker holding the floor, and the "and" goes with what came before.+_DANGLING = set("""+a an the my your his her its our their this these those to of in on at for with from by into about over+under after before between through without i we they he she you is are was were be been am have has had do+does did will would can could should may might must very really just that which who whose+""".split())+_CONNECTIVES = {"and", "so", "but", "or", "then", "because"}+# Words a named thing follows: two words after one of these are a thing ("the train station").+_NAMES_THINGS = set("""+the a an my your his her our their its this that these those some any every each no of for to at in on with+from about into onto by one two three four five six seven eight nine ten more most new own whole first last+next another+""".split())+++def signpost(keys: Sequence[str]) -> tuple[str, float]:+ """The signpost a sentence opens with, and how strongly it says a new part begins (0 to 1):+ ("first of all", 1.0), ("then", 0.6), ("so", 0.25), or ("", 0)."""+ keys = [k for k in keys if k]++ def match(seq: Sequence[str]) -> tuple[str, float]:+ best = ("", 0.0)+ for table, strength in ((_FULL, 1.0), (_PART, 0.6), (_SLIGHT, 0.25)):+ for p in table:+ longer = strength == best[1] and len(p) > len(best[0].split())+ if tuple(seq[:len(p)]) == p and (strength > best[1] or longer):+ best = (" ".join(p), strength)+ return best++ found = match(keys)+ # "And finally", "so first", "okay, next": a connective in front never hides the signpost.+ rest = list(keys)+ while rest and rest[0] in _LEADS:+ rest = rest[1:]+ inner = match(rest)+ if inner[1] > found[1]:+ found = (" ".join(keys[:len(keys) - len(rest)] + inner[0].split()), inner[1])+ # A story moves on after its subject: "I then boarded", "we eventually got there". Only words+ # that move a story along count there, and only part way.+ if rest and rest[0] in _SUBJECTS and len(rest) > 1 and rest[1] in _MOVES_ON:+ if 0.6 > found[1]:+ found = (" ".join(keys[:len(keys) - len(rest) + 2]), 0.6)+ return found+++# ---- candidates --------------------------------------------------------------------------------------++@dataclass(frozen=True)+class Boundary:+ """A place a new part could begin: between word `after` and the word after it."""+ after: int # the last word before it+ at: float # when the next part's first word begins (seconds)+ room: tuple[float, float] # the quiet between the two words: where a card can sit with nobody speaking+ pause: float # how long the voice stops there, read from the sound+ sentence: bool # the word before ends a sentence+ signpost: str # the words the next sentence opens with, when they announce something+ strength: float # how strongly that signpost announces a new part (0 to 1)+ question: bool # the next sentence is a short question+ shift: float = 0.0 # how little the words either side share (0: the same subject, 1: nothing in common)+ score: float = 0.0 # all of it weighed++ def why(self) -> str:+ bits = []+ if self.pause >= 0.15:+ bits.append(f"a {self.pause:.1f} s pause")+ if self.signpost:+ bits.append(f"“{self.signpost}”")+ if self.question:+ bits.append("a question")+ bits.append(f"the words change {self.shift:.0%}")+ return ", ".join(bits)+++def _quiet_between(a: float, b: float, quiet: Sequence[tuple[float, float]]) -> tuple[float, float]:+ """The longest quiet stretch between two words, clipped to the gap between them."""+ best = (a, a)+ for q0, q1 in quiet:+ lo, hi = max(q0, a - 0.06), min(q1, b + 0.06)+ if hi - lo > best[1] - best[0]:+ best = (max(lo, a), min(hi, b)) if min(hi, b) > max(lo, a) else (lo, hi)+ return best+++def candidates(words: Sequence[Word], quiet: Sequence[tuple[float, float]]) -> list[Boundary]:+ """Every place a new part could begin, with its evidence (`score` is filled in by `weigh`)."""+ words = list(words)+ ends = set()+ for i in range(len(words) - 1):+ if words[i].ends_sentence or pause_after(words, i, quiet) >= SPLIT_PAUSE:+ ends.add(i)+ # A stop just before an "um" and one just after it are the same place: keep the one before it,+ # so the part (and anything announcing it) starts with the hesitation, never in the middle of it.+ for i in sorted(ends):+ if i - 1 in ends and words[i].key in HESITATIONS:+ ends.discard(i)+ out = []+ for i in sorted(ends):+ nxt = i + 1+ pause = pause_after(words, i, quiet)+ if not words[i].ends_sentence:+ opens = words[nxt].key in _OPENERS or words[i].ends_clause+ dangles = words[i].key in _DANGLING or (words[i].key in _CONNECTIVES and pause < 0.5)+ if not opens or dangles:+ continue+ # The next sentence's opening words, up to its first stop.+ opening = []+ j = nxt+ while j < len(words) and len(opening) < 7:+ opening.append(words[j].key)+ if words[j].ends_sentence:+ break+ j += 1+ sp, strength = signpost(opening)+ if strength and not words[i].ends_sentence and pause < 1.0:+ strength *= 0.35 # "...which is good, the next step is...": said inside a sentence, not announced+ # A short question opens a part ("Want something more editorial?") more often than not.+ k, n = nxt, 0+ while k < len(words) and n < 9 and not words[k].ends_sentence:+ k, n = k + 1, n + 1+ question = k < len(words) and n < 9 and words[k].text.rstrip().endswith("?")+ room = _quiet_between(words[i].end, words[nxt].start, quiet)+ out.append(Boundary(after=i, at=words[nxt].start, room=room, pause=pause, sentence=words[i].ends_sentence,+ signpost=sp, strength=round(strength, 3), question=question))+ return out+++# ---- the words changing --------------------------------------------------------------------------------++def _sentences(words: Sequence[Word], cuts: Sequence[int]) -> list[list[int]]:+ out, cur = [], []+ marks = set(cuts)+ for i in range(len(words)):+ cur.append(i)+ if i in marks:+ out.append(cur)+ cur = []+ if cur:+ out.append(cur)+ return out+++def _idf(words: Sequence[Word], units: list[list[int]]) -> dict[str, float]:+ df: Counter = Counter()+ for u in units:+ df.update({c for i in u if (c := content(words[i]))})+ n = max(1, len(units))+ return {w: math.log((1 + n) / (1 + d)) + 1.0 for w, d in df.items()}+++def _vector(words: Sequence[Word], idx: Sequence[int], idf: dict[str, float]) -> dict[str, float]:+ counts = Counter(c for i in idx if (c := content(words[i])))+ return {w: n * idf.get(w, 1.0) for w, n in counts.items()}+++def _cosine(a: dict[str, float], b: dict[str, float]) -> Optional[float]:+ if not a or not b:+ return None+ dot = sum(v * b.get(k, 0.0) for k, v in a.items())+ na = math.sqrt(sum(v * v for v in a.values()))+ nb = math.sqrt(sum(v * v for v in b.values()))+ return dot / (na * nb) if na and nb else None+++def weigh(words: Sequence[Word], cands: list[Boundary], window: float) -> list[Boundary]:+ """Each candidate with how much the words change across it and its whole score."""+ words = list(words)+ units = _sentences(words, [c.after for c in cands])+ idf = _idf(words, units)+ shifts = []+ for c in cands:+ before = [i for i in range(c.after + 1) if words[i].start >= c.at - window]+ after = [i for i in range(c.after + 1, len(words)) if words[i].start < c.at + window]+ sim = _cosine(_vector(words, before, idf), _vector(words, after, idf))+ shifts.append(None if sim is None else 1.0 - sim)+ known = sorted(s for s in shifts if s is not None)+ usual = known[len(known) // 2] if known else 0.5+ out = []+ for c, shift in zip(cands, shifts):+ # Measured against how much the words usually change in this talk: someone who never repeats a+ # word changes them "completely" at every sentence, which says nothing.+ telling = 0.5 if shift is None else min(1.0, max(0.0, 0.5 + (shift - usual)))+ score = (WEIGHTS["pause"] * min(1.0, c.pause / PAUSE_FULL)+ + WEIGHTS["sentence"] * (1.0 if c.sentence else 0.0)+ + WEIGHTS["signpost"] * c.strength+ + WEIGHTS["shift"] * telling+ + WEIGHTS["question"] * (1.0 if c.question else 0.0))+ out.append(Boundary(**{**c.__dict__, "shift": round(0.5 if shift is None else shift, 3),+ "score": round(score, 3)}))+ return out+++# ---- choosing the boundaries ------------------------------------------------------------------------------++def opening_min(min_part: float) -> float:+ """The shortest the first part may be. An opening that says what is coming ("Today, three ways to+ edit faster.") is often only a sentence long, so it may be shorter than the parts after it."""+ return min(min_part, max(SHORTEST, 0.6 * min_part))+++def choose(cands: Sequence[Boundary], duration: float, min_part: float, count: Optional[int] = None,+ bar: float = BAR, first_min: Optional[float] = None) -> list[Boundary]:+ """The boundaries that make the parts: every part at least `min_part` long (the last to+ `duration`), the first at least `first_min` (by default `opening_min`). With `count` (the+ number of parts), exactly count - 1 boundaries, the strongest set that fits; otherwise the+ boundaries whose score clears `bar`, the set worth most. Fewer than asked come back when the+ video cannot hold that many parts of that length."""+ if count is not None and count <= 1:+ return []+ first_min = opening_min(min_part) if first_min is None else first_min+ cs = sorted((c for c in cands if first_min <= c.at <= duration - min_part), key=lambda c: c.at)+ n = len(cs)+ if not n:+ return []+ # earlier[j]: the candidates far enough before j to sit with it+ earlier = [[i for i in range(j) if cs[j].at - cs[i].at >= min_part] for j in range(n)]+ if count is None:+ # A chain of boundaries, each worth its score less the bar: the best chain ending at each one.+ best = [0.0] * n+ back = [-1] * n+ for j in range(n):+ prev = max(earlier[j], key=lambda i: best[i], default=-1)+ gain = cs[j].score - bar+ if prev >= 0 and best[prev] > 0:+ best[j], back[j] = best[prev] + gain, prev+ else:+ best[j] = gain+ j = max(range(n), key=lambda j: best[j])+ if best[j] <= 0:+ return []+ else:+ want = count - 1+ # best[k][j]: the most a chain of k boundaries ending at candidate j is worth.+ best_k = [[-math.inf] * n for _ in range(want + 1)]+ back_k = [[-1] * n for _ in range(want + 1)]+ for j in range(n):+ best_k[1][j] = cs[j].score+ for k in range(2, want + 1):+ for j in range(n):+ for i in earlier[j]:+ if best_k[k - 1][i] + cs[j].score > best_k[k][j]:+ best_k[k][j], back_k[k][j] = best_k[k - 1][i] + cs[j].score, i+ k = next((k for k in range(want, 0, -1) if max(best_k[k]) > -math.inf), 0) # the most that fit+ if not k:+ return []+ j = max(range(n), key=lambda j: best_k[k][j])+ chain = []+ while k >= 1 and j >= 0:+ chain.append(cs[j])+ j, k = back_k[k][j], k - 1+ return sorted(chain, key=lambda c: c.at)+ chain = []+ while j >= 0:+ chain.append(cs[j])+ j = back[j]+ return sorted(chain, key=lambda c: c.at)+++# ---- titles ------------------------------------------------------------------------------------------------++@dataclass(frozen=True)+class Given:+ """A title the person typed, and the time its part begins when they gave one."""+ title: str+ at: Optional[float] = None+++_TIME = re.compile(r"^\s*(?:(\d+):)?(\d{1,2}):(\d{2}(?:\.\d+)?)\s+(.*)$|^\s*(\d+(?:\.\d+)?)s\s+(.*)$")+++def parse_time(text: str) -> Optional[float]:+ """"1:05", "01:02:03" or "65s" as seconds, else None."""+ m = re.fullmatch(r"\s*(?:(\d+):)?(\d{1,2}):(\d{2}(?:\.\d+)?)\s*", text)+ if m:+ return int(m.group(1) or 0) * 3600 + int(m.group(2)) * 60 + float(m.group(3))+ m = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*s\s*", text)+ return float(m.group(1)) if m else None+++def parse_titles(spec: str) -> tuple[Optional[int], list[Given]]:+ """What `titles=` says: ("auto" or empty) nothing; a number, how many parts; or titles separated+ by |, each of which may start with the time its part begins ("0:31 The train", "31s The train").+ Returns (count or None, the titles)."""+ s = (spec or "").strip()+ if not s or s.lower() == "auto":+ return None, []+ if re.fullmatch(r"\d{1,2}", s):+ return int(s), []+ out = []+ for piece in s.split("|"):+ piece = piece.strip()+ if not piece:+ continue+ m = _TIME.match(piece)+ if m and m.group(4) is not None and m.group(4).strip():+ at = int(m.group(1) or 0) * 3600 + int(m.group(2)) * 60 + float(m.group(3))+ out.append(Given(m.group(4).strip(), at))+ elif m and m.group(6) is not None and m.group(6).strip():+ out.append(Given(m.group(6).strip(), float(m.group(5))))+ else:+ out.append(Given(piece))+ return (len(out) or None), out+++def _display(w: Word, after: Optional[Word] = None) -> str:+ """A word as a title shows it: as heard, without punctuation at its edges, and joined to an+ ending the transcriber split off it ("askeditor" ".com" is "askeditor.com")."""+ t = w.clean.strip().strip("\"'“”‘’.,;:!?()[]{}…-–—")+ if after is not None and after.text.strip().startswith(".") and len(after.key) <= 4 and after.key.isalpha():+ t = f"{t}.{after.key}"+ return t or w.key+++def _is_name(words: Sequence[Word], i: int) -> bool:+ t = _display(words[i])+ if len(t) >= 2 and t.isupper():+ return True # an acronym: DJI, UGC+ if t[:1].isupper() and i > 0 and not words[i - 1].ends_sentence and t.lower() != "i":+ return True # capitalised in the middle of a sentence: a name or a place+ return any(c.isupper() for c in t[1:]) # GoPro, AskEditor+++def _title_case(text: str) -> str:+ return text[:1].upper() + text[1:] if text else text+++@dataclass+class Part:+ """One part of the talk."""+ index: int+ start: float # when it begins on the video's timeline (0 for the first)+ end: float # when the next one begins (the video's end for the last)+ first: int # its first word (an index into the words it was found from)+ last: int # its last word+ title: str+ given: bool = False # the title is the person's own+ boundary: Optional[Boundary] = None # what showed it begins here (None for the first)+ keys: list[str] = field(default_factory=list) # its key words, most specific first++ @property+ def seconds(self) -> float:+ return self.end - self.start++ @property+ def room(self) -> Optional[tuple[float, float]]:+ """The quiet just before it begins, where nobody is speaking."""+ return self.boundary.room if self.boundary else None++ def said(self, words: Sequence[Word]) -> str:+ return " ".join(w.text for w in words[self.first:self.last + 1] if w.key not in HESITATIONS)++ def to_json(self) -> dict:+ b = self.boundary+ return {"index": self.index + 1, "start": round(self.start, 3), "end": round(self.end, 3),+ "title": self.title, "given": self.given, "words": [self.first, self.last],+ "keys": self.keys[:5],+ **({"pause_before": [round(b.room[0], 3), round(b.room[1], 3)], "why": b.why(),+ "score": b.score} if b else {})}+++def key_words(words: Sequence[Word], spans: Sequence[tuple[int, int]], quiet=(),+ skip: frozenset = frozenset()) -> list[list[tuple[str, float]]]:+ """For each span of words (a part), its key words and pairs of words, most telling first, each+ with its weight: said in this part more than in the others, specific (long, a name, a figure),+ and said more than once. Pairs are two content words said together in one breath ("train+ station", "flip camera"); a pair outranks either of its words when both are telling. The words+ at the indexes in `skip` (what the speaker took back) count for nothing."""+ words = list(words)+ per_part: list[Counter] = []+ shows: list[dict[str, str]] = []+ for a, b in spans:+ c: Counter = Counter()+ show: dict[str, str] = {}+ for i in range(a, b + 1):+ k = None if i in skip else content(words[i])+ if k:+ c[k] += 1+ d = _display(words[i], words[i + 1] if i + 1 < len(words) else None)+ show.setdefault(k, d if _is_name(words, i) else d.lower())+ per_part.append(c)+ shows.append(show)+ n = max(1, len(spans))+ df: Counter = Counter()+ for c in per_part:+ df.update(set(c))+ out = []+ for p, ((a, b), c) in enumerate(zip(spans, per_part)):+ weight: dict[str, float] = {}+ for k, tf in c.items():+ spec = 1.0 + 0.06 * min(len(k), 10)+ if any(ch.isdigit() for ch in k):+ spec += 0.6+ if k.endswith(("ing", "ed")) and len(k) > 5:+ spec *= 0.7 # most likely a verb ("chilling", "boarded"): a part is named by a thing+ idf = math.log((n + 1) / (df[k] + 0.5)) + 0.4+ weight[k] = (1.0 + 0.6 * math.log(tf)) * idf * spec+ names = {content(words[i]) for i in range(a, b + 1)+ if i not in skip and content(words[i]) and _is_name(words, i)}+ for k in names:+ weight[k] = weight.get(k, 0.0) * 1.35+ ranked: dict[str, float] = {shows[p][k]: v for k, v in weight.items()}+ # pairs said together, where a thing can be named: after "the", "my", "of", a number, or at+ # the start of a sentence ("the train station", "a chicken patty"), never a subject and its+ # verb ("so captions carry", "and pauses add up")+ for i in range(a, b):+ k1, k2 = content(words[i]), content(words[i + 1])+ if not (k1 and k2) or k1 == k2 or words[i].ends_clause or i in skip or i + 1 in skip:+ continue+ if pause_after(words, i, quiet) >= 0.3:+ continue+ before = words[i - 1] if i > 0 else None+ names = _is_name(words, i) and _is_name(words, i + 1)+ if not (names or before is None or before.ends_sentence or before.key in _NAMES_THINGS+ or any(ch.isdigit() for ch in before.key)):+ continue+ pair = f"{shows[p][k1]} {shows[p][k2]}"+ v = 0.62 * (weight[k1] + weight[k2])+ if v > ranked.get(pair, 0.0):+ ranked[pair] = v+ order = sorted(ranked.items(), key=lambda kv: (-kv[1], kv[0]))+ # A lone word that is half of a pair said here ("lively" in "lively city") gives way to the+ # pair when the pair is nearly as telling: a title reads as a thing, not an adjective.+ if order and " " not in order[0][0]:+ top, v = order[0]+ for text, w in order[1:]:+ if " " in text and top in text.split() and w >= 0.8 * v:+ order.remove((text, w))+ order.insert(0, (text, w))+ break+ out.append(order)+ return out+++def _pick_titles(ranked: list[list[tuple[str, float]]], most_letters: int = 22) -> list[str]:+ """One title a part, never the same as an earlier part's, never longer than `most_letters`."""+ used: set[str] = set()+ out = []+ for options in ranked:+ title = ""+ for text, _ in options:+ if len(text) > most_letters:+ continue+ folded = {_stem(normalize(x)) for x in text.split()}+ if any(folded & {_stem(normalize(x)) for x in u.split()} for u in used):+ continue+ title = text+ break+ if not title and options:+ title = options[0][0][:most_letters].rstrip()+ used.add(title)+ out.append(_title_case(title) if title else "")+ return out+++# ---- the whole thing ---------------------------------------------------------------------------------------++def _snap(cands: Sequence[Boundary], words: Sequence[Word], quiet, t: float) -> Boundary:+ """The candidate nearest a time the person gave (within 2.5 s), else a boundary made there, at+ the first word that starts at or after it."""+ near = [c for c in cands if abs(c.at - t) <= 2.5]+ if near:+ return min(near, key=lambda c: (abs(c.at - t), -c.score))+ j = next((i for i, w in enumerate(words) if w.start >= t - 0.05), len(words) - 1)+ i = max(0, j - 1)+ room = _quiet_between(words[i].end, words[j].start, quiet) if j > i else (t, t)+ return Boundary(after=i, at=words[j].start if j > i else t, room=room, pause=pause_after(list(words), i, quiet),+ sentence=words[i].ends_sentence, signpost="", strength=0.0, question=False, shift=0.0, score=0.0)+++def find(words: Sequence[Word], quiet: Sequence[tuple[float, float]], duration: float,+ min_part: Optional[float] = None, count: Optional[int] = None,+ titles: Sequence[Given] = (), first_min: Optional[float] = None) -> list[Part]:+ """The parts of the talk, in order, each with a title.++ `min_part`: the shortest a part may be (None: `auto_min_part`); `first_min` the shortest the+ opening part may be (None: `opening_min`; YouTube chapters pass 10). `count`: how many parts to+ make (None: as many as the evidence holds, at most `most_parts`). `titles`: the person's own,+ which also set the count; one that carries a time pins where its part begins (snapped to the+ nearest real boundary within 2.5 s). A video with no words is one part."""+ words = list(words)+ if not words:+ return [Part(0, 0.0, duration, 0, -1, titles[0].title if titles else "", bool(titles))]+ floor = auto_min_part(duration) if min_part is None else max(SHORTEST, float(min_part))+ cands = weigh(words, candidates(words, quiet), window=max(6.0, min(20.0, floor)))+ if titles:+ count = len(titles)+ pinned = [g for g in titles[1:] if g.at is not None]+ if titles and pinned and len(pinned) == len(titles) - 1:+ chosen = [_snap(cands, words, quiet, g.at) for g in titles[1:]]+ else:+ chosen = choose(cands, duration, floor, count, first_min=first_min)+ if count is None and len(chosen) + 1 > most_parts(duration):+ chosen = choose(cands, duration, floor, most_parts(duration), first_min=first_min)+ if count and len(chosen) < count - 1:+ # The video cannot hold that many parts that long: shorter parts, down to the floor of all.+ for shorter in (floor * 0.75, floor * 0.5, SHORTEST):+ chosen = choose(cands, duration, max(SHORTEST, shorter), count,+ first_min=None if first_min is None else min(first_min, max(SHORTEST, shorter)))+ if len(chosen) >= count - 1:+ break+ starts = [0.0] + [c.at for c in chosen]+ ends = starts[1:] + [duration]+ firsts = [0] + [c.after + 1 for c in chosen]+ lasts = [c.after for c in chosen] + [len(words) - 1]+ spans = list(zip(firsts, lasts))+ # A part is never named by what the speaker took back ("the lively town, or the lively city")+ # or by the words of a first attempt said again: the same rule every picker in the core keeps.+ back = moments.taken_back(words, quiet)+ ranked = key_words(words, spans, quiet, skip=frozenset(i for i, w in enumerate(words) if w in back))+ auto = _pick_titles(ranked)+ out = []+ for k, (s, e, (a, b)) in enumerate(zip(starts, ends, spans)):+ given = titles[k].title if k < len(titles) else ""+ out.append(Part(index=k, start=s, end=e, first=a, last=b, title=given or auto[k], given=bool(given),+ boundary=chosen[k - 1] if k else None, keys=[t for t, _ in ranked[k][:6]]))+ return out+++# ---- chapters as YouTube reads them ---------------------------------------------------------------------------++def stamp(seconds: float, hours: bool = False) -> str:+ """A time as a chapter line writes it: "00:00", "01:05", or "1:02:03" in a video of an hour or more."""+ s = int(math.floor(max(0.0, seconds) + 1e-6))+ h, m, sec = s // 3600, (s // 60) % 60, s % 60+ return f"{h}:{m:02d}:{sec:02d}" if hours else f"{s // 60:02d}:{sec:02d}"+++def chapter_lines(found: Sequence[Part], duration: float) -> list[str]:+ """The parts as YouTube chapter lines ("00:00 Title"), each at the second its part begins (the+ first at 00:00)."""+ hours = duration >= 3600+ return [f"{stamp(0.0 if p.index == 0 else p.start, hours)} {p.title}" for p in found]+++def check_chapters(lines: Sequence[str], duration: float) -> list[str]:+ """What is wrong with chapter lines by YouTube's own rules (YouTube Help, "Video Chapters", read+ 28 October 2026: the first timestamp 00:00, at least three in ascending order, each chapter at+ least 10 seconds). Empty when they pass."""+ problems = []+ times = []+ for ln in lines:+ m = re.match(r"^\s*((?:\d+:)?\d{1,2}:\d{2})\s+(\S.*)$", ln)+ if not m:+ problems.append(f"“{ln.strip()}” is not a time and a title")+ continue+ t = parse_time(m.group(1))+ times.append(0.0 if t is None else t)+ if not times:+ return problems or ["no chapter lines"]+ if times[0] != 0:+ problems.append("the first chapter must start at 00:00")+ if len(times) < 3:+ problems.append(f"YouTube needs at least three chapters; there are {len(times)}")+ for k in range(1, len(times)):+ if times[k] <= times[k - 1]:+ problems.append(f"chapter {k + 1} does not come after chapter {k}")+ for k, t in enumerate(times):+ nxt = times[k + 1] if k + 1 < len(times) else duration+ if nxt - t < YOUTUBE_SHORTEST - 1e-6:+ problems.append(f"chapter {k + 1} lasts {max(0.0, nxt - t):.0f} s; YouTube needs at least 10")+ return problemsdiff --git a/edit/askeditor/fx/core/paths.py b/edit/askeditor/fx/core/paths.pynew file mode 100644index 0000000..f81ffb5--- /dev/null+++ b/edit/askeditor/fx/core/paths.py@@ -0,0 +1,38 @@+"""Where the pack keeps things: its own folder, the models, the fonts, and the caches next to a clip."""++from __future__ import annotations++import hashlib+import os+from pathlib import Path++PACK = Path(__file__).resolve().parents[2]+MODELS = PACK / "models"+FONTS = PACK / "fonts"+CACHE = PACK / ".cache"+++class NeedSetup(RuntimeError):+ """Something setup.sh provides is missing."""+++def beside(clip: str | os.PathLike, suffix: str) -> Path:+ """The cache file for `suffix` next to the clip (`talk.mp4` -> `talk.words.json`).++ When the clip's folder cannot be written, the file goes in the pack's own `.cache/` instead,+ under a folder named after the clip's full path.+ """+ clip = Path(clip).resolve()+ target = clip.with_name(f"{clip.stem}.{suffix}")+ if os.access(clip.parent, os.W_OK):+ return target+ key = hashlib.sha1(str(clip).encode()).hexdigest()[:12]+ folder = CACHE / key+ folder.mkdir(parents=True, exist_ok=True)+ return folder / target.name+++def source_signature(clip: str | os.PathLike) -> dict:+ """What a cache records about its clip, so a changed clip is never read with a stale cache."""+ st = Path(clip).stat()+ return {"name": Path(clip).name, "bytes": st.st_size}diff --git a/edit/askeditor/fx/core/person.py b/edit/askeditor/fx/core/person.pynew file mode 100644index 0000000..7321936--- /dev/null+++ b/edit/askeditor/fx/core/person.py@@ -0,0 +1,311 @@+"""The person in every frame as a soft mask, cached next to the clip as `<clip>.person.mkv`.++What words-behind and every later "behind you" effect stands on:++ masks = person.masks(info) # found once, then read from the cache+ for i, m in enumerate(masks.frames()): # one small mask per frame, 0..1, in order+ alpha = masks.full(m, (w, h), guide=frame) # at the output size, edges following the frame+ out = compose.behind_person(frame, layer, alpha)++**The range is the whole range.** A mask that never quite reaches 1 inside the person lets+whatever is drawn "behind" show through them: a mask stored as 16..235 instead of 0..255 once put a+faint copy of a word over a speaker's face in AskEditor. So the model's confidence is stretched and+clamped before it is stored (inside the person is exactly 1, the background exactly 0), the cache is+written lossless in a grey format no video player re-ranges, and the first frame is read back and+compared before the cache is trusted.++The masks are kept small (`WORK_WIDTH` across) and cheap to store; `full()` brings one up to the+output size with a guided filter, so the edge follows the hair and the shoulders in the real frame+rather than the blocky small mask.+"""++from __future__ import annotations++import json+import os+import shutil+import subprocess+import tempfile+import time+from dataclasses import dataclass+from pathlib import Path+from typing import Iterator, Optional++import numpy as np++from . import paths+from .face import quiet_native+from .video import FrameReader, MediaError, VideoInfo, need_ffmpeg++CACHE_VERSION = 1+WORK_WIDTH = 360+MODEL = "person" # the plain person model: reaches a clean 0..1 and is several times faster+# The model's confidence is stretched from LOW..HIGH to 0..1 and clamped: below LOW is background,+# above HIGH is certainly the person. The detailed model never goes above about 0.94.+STRETCH = {"person": (0.10, 0.85), "person-parts": (0.10, 0.80)}+# Where the edge sits after the upsample: the level of the guided mask that becomes half opaque.+# Below 0.5 leans the edge outward, onto the background, by a pixel or two at 1080 across.+EDGE_LEAN = 0.36+# How sure a pixel of the stored mask (0..1) must be to count as surely the person, for `reach`.+SURE = 0.8+++@dataclass+class PersonMasks:+ info: VideoInfo+ path: Path+ width: int+ height: int+ model: str+ seconds: float = 0.0 # how long finding the masks took (0 when read from the cache)++ @property+ def n(self) -> int:+ return self.info.frames++ def frames(self) -> Iterator[np.ndarray]:+ """Every frame's mask in order, float32 0..1 at the work size. Always exactly `n` of them."""+ last = np.zeros((self.height, self.width), np.float32)+ count = 0+ for m in _read_gray(self.path, self.width, self.height):+ if count >= self.n:+ break+ last = m.astype(np.float32) / 255.0+ count += 1+ yield last+ while count < self.n: # the cache is a frame short of the picture: hold the last one+ count += 1+ yield last++ def at(self, i: int) -> np.ndarray:+ """One frame's mask (float32 0..1, work size)."""+ i = int(np.clip(i, 0, self.n - 1))+ start = max(0.0, (i - 0.25) / self.info.rate)+ for m in _read_gray(self.path, self.width, self.height, start=start, count=1):+ return m.astype(np.float32) / 255.0+ return np.zeros((self.height, self.width), np.float32)++ def full(self, mask: np.ndarray, size: tuple[int, int], guide: Optional[np.ndarray] = None,+ crop: Optional[tuple[float, float, float, float]] = None, lean: float = EDGE_LEAN,+ reach: Optional[float] = None) -> np.ndarray:+ """The mask at `size` (w, h), float32 0..1.++ `crop` (x, y, w, h, in the clip's own pixels) takes the part of the mask under a reframed+ picture first. `guide` is the output frame itself (RGB, at `size`): with it the edge is+ rebuilt from the real picture, so hair and collars keep their shape. `lean` moves the edge+ toward the background: for anything laid behind the person a sliver of the real background+ at the edge is invisible, and a sliver of the layer on the person is not.++ `reach` (output pixels) keeps the soft edge only that close to where the model is sure of+ the person; further out, a faint guess is dropped. The model half-takes a vase or a plant+ behind a head for hair, in a flame that flickers from frame to frame (clip A, 28 October+ 2026: up to 35 rows of the small mask above the head, never more than 0.6 sure), and+ anything laid behind the person goes see-through there. A real hair edge sits within a few+ pixels of the sure part.+ """+ import cv2++ m = mask+ if crop is not None:+ sx, sy = self.width / self.info.width, self.height / self.info.height+ x, y, w, h = crop+ x0, y0 = int(np.floor(x * sx)), int(np.floor(y * sy))+ x1, y1 = int(np.ceil((x + w) * sx)), int(np.ceil((y + h) * sy))+ m = m[max(0, y0):min(self.height, y1), max(0, x0):min(self.width, x1)]+ out = cv2.resize(m, size, interpolation=cv2.INTER_LINEAR)+ if guide is not None:+ g = cv2.cvtColor(guide, cv2.COLOR_RGB2GRAY).astype(np.float32) / 255.0+ radius = max(2, int(round(size[0] / 220)))+ out = cv2.ximgproc.guidedFilter(guide=g, src=out, radius=radius, eps=2e-3)+ if reach is not None and reach > 0:+ r = max(1, int(round(reach * m.shape[1] / size[0]))) # in the small mask's pixels+ sure = (m >= SURE).astype(np.uint8)+ near = cv2.dilate(sure, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * r + 1, 2 * r + 1)))+ near = cv2.GaussianBlur(near.astype(np.float32), (0, 0), max(0.7, r / 2))+ out = out * np.clip(cv2.resize(near, size, interpolation=cv2.INTER_LINEAR) * 2.0, 0.0, 1.0)+ # The filter can ring a little past 0 and 1: clamp, keep the inside exactly opaque, and+ # put the half-way point where `lean` says (0.5 is the model's own edge).+ lo = 0.02+ hi = max(lo + 0.05, 2 * lean - lo)+ return np.clip((out - lo) / (hi - lo), 0.0, 1.0).astype(np.float32)++ def crown(self, mask: np.ndarray, x0: float, x1: float, level: float = 0.5) -> Optional[float]:+ """The top of the person between x0 and x1 (the clip's own pixels): where the head ends,+ hair and hat included. None when nobody is in that band."""+ sx = self.width / self.info.width+ a, b = int(max(0, x0 * sx)), int(min(self.width, np.ceil(x1 * sx)))+ if b <= a:+ return None+ rows = np.flatnonzero((mask[:, a:b] > level).mean(axis=1) > 0.15)+ return float(rows[0] * self.info.height / self.height) if len(rows) else None+++def _work_size(info: VideoInfo) -> tuple[int, int]:+ w = min(WORK_WIDTH, info.width)+ w -= w % 2+ h = int(round(info.height * w / info.width / 2)) * 2+ return w, h+++def _read_gray(path: Path, width: int, height: int, start: float = 0.0, count: Optional[int] = None) -> Iterator[np.ndarray]:+ cmd = ["ffmpeg", "-v", "error", "-nostdin"]+ if start > 0:+ cmd += ["-ss", f"{start:.6f}"]+ cmd += ["-i", str(path)]+ if count is not None:+ cmd += ["-frames:v", str(count)]+ cmd += ["-f", "rawvideo", "-pix_fmt", "gray", "-"]+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)+ size = width * height+ try:+ assert proc.stdout is not None+ while True:+ buf = proc.stdout.read(size)+ if len(buf) < size:+ break+ yield np.frombuffer(buf, np.uint8).reshape(height, width)+ finally:+ if proc.poll() is None:+ proc.kill()+ proc.wait()+++def _segment(info: VideoInfo, model: str, size: tuple[int, int]) -> Iterator[np.ndarray]:+ """The model's person confidence per frame (float32 0..1, work size), unprocessed."""+ import cv2++ from .models import vision_path++ with quiet_native():+ import mediapipe as mp+ from mediapipe.tasks import python as mp_tasks+ from mediapipe.tasks.python import vision++ options = vision.ImageSegmenterOptions(+ base_options=mp_tasks.BaseOptions(model_asset_path=str(vision_path(model))),+ running_mode=vision.RunningMode.VIDEO,+ output_confidence_masks=True,+ output_category_mask=False,+ )+ segmenter = vision.ImageSegmenter.create_from_options(options)+ try:+ for i, frame in enumerate(FrameReader(info, size=size)):+ image = mp.Image(image_format=mp.ImageFormat.SRGB, data=np.ascontiguousarray(frame))+ result = segmenter.segment_for_video(image, int(round(i * 1000 / info.rate)))+ masks = result.confidence_masks+ if len(masks) == 1:+ p = masks[0].numpy_view()+ else: # the detailed model: everything that is not background is the person+ p = 1.0 - masks[0].numpy_view()+ p = np.asarray(p, np.float32).reshape(size[1], size[0])+ if p.shape != (size[1], size[0]):+ p = cv2.resize(p, size, interpolation=cv2.INTER_LINEAR)+ yield p+ finally:+ segmenter.close()+++def _clean(p: np.ndarray, model: str) -> np.ndarray:+ """Stretch to the full range, clamp, and soften the stair-steps a little."""+ import cv2++ lo, hi = STRETCH[model]+ m = np.clip((p - lo) / (hi - lo), 0.0, 1.0)+ return cv2.GaussianBlur(m, (0, 0), 0.8)+++def _find(info: VideoInfo, model: str, size: tuple[int, int], target: Path, meta: dict) -> None:+ """Segment every frame, steady each pixel across three frames (a median, which removes+ one-frame flicker without dragging a moving edge), and write the masks lossless."""+ need_ffmpeg()+ w, h = size+ tmpdir = tempfile.mkdtemp(prefix="fx-person-")+ partial = Path(tmpdir) / "person.mkv"+ cmd = ["ffmpeg", "-v", "error", "-nostdin", "-y", "-f", "rawvideo", "-pix_fmt", "gray",+ "-s", f"{w}x{h}", "-framerate", f"{info.fps.numerator}/{info.fps.denominator}", "-i", "-",+ "-c:v", "ffv1", "-level", "3", "-g", "1", "-pix_fmt", "gray",+ "-metadata", "comment=" + json.dumps(meta, separators=(",", ":")), str(partial)]+ proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)+ assert proc.stdin is not None+ first: Optional[np.ndarray] = None+ written = 0+ try:+ window: list[np.ndarray] = []++ def emit(m: np.ndarray) -> None:+ nonlocal first, written+ q = np.round(m * 255.0).astype(np.uint8)+ if first is None:+ first = q+ proc.stdin.write(q.tobytes()) # type: ignore[union-attr]+ written += 1++ for p in _segment(info, model, size):+ window.append(_clean(p, model))+ if len(window) == 2 and written == 0:+ emit(window[0]) # the first frame has no frame before it+ if len(window) == 3:+ emit(np.median(np.stack(window), axis=0))+ window.pop(0)+ if window:+ emit(window[-1]) # the last frame has no frame after it+ while written < info.frames: # the reader can come up a frame short+ emit(window[-1] if window else np.zeros((h, w), np.float32))+ proc.stdin.close()+ if proc.wait() != 0:+ err = proc.stderr.read().decode(errors="replace").strip() if proc.stderr else ""+ raise MediaError("the person masks could not be written" + (f": {err.splitlines()[-1]}" if err else ""))+ # Read the first frame back: the cache is trusted only if it is bit for bit what was written.+ back = next(_read_gray(partial, w, h, count=1), None)+ if first is None or back is None or not np.array_equal(back, first):+ raise MediaError("the person masks did not read back exactly; they were not kept")+ shutil.move(str(partial), str(target))+ finally:+ if proc.poll() is None:+ proc.kill()+ proc.wait()+ shutil.rmtree(tmpdir, ignore_errors=True)+++def _cached_meta(path: Path) -> dict:+ out = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format_tags=comment", "-of", "json", str(path)],+ capture_output=True, text=True)+ try:+ tags = json.loads(out.stdout).get("format", {}).get("tags", {})+ return json.loads(tags.get("comment") or tags.get("COMMENT") or "{}")+ except (ValueError, AttributeError):+ return {}+++def masks(info: VideoInfo, model: str = MODEL, refresh: bool = False) -> PersonMasks:+ """The clip's person masks, from the cache beside the clip or found now (once)."""+ if model not in STRETCH:+ raise ValueError(f"unknown person model {model!r}")+ size = _work_size(info)+ cache = paths.beside(info.path, "person.mkv" if model == MODEL else f"person-{model}.mkv")+ meta = {"version": CACHE_VERSION, "model": model, "source": paths.source_signature(info.path),+ "frames": info.frames, "size": list(size)}+ if not refresh and cache.exists() and _cached_meta(cache) == meta:+ return PersonMasks(info, cache, size[0], size[1], model)+ started = time.time()+ _find(info, model, size, cache, meta)+ return PersonMasks(info, cache, size[0], size[1], model, seconds=time.time() - started)+++def check_range(m: PersonMasks, sample: int = 12) -> dict:+ """What the stored masks span across a few frames: the inside must be exactly 1 and the far+ background exactly 0 (the ghost check)."""+ lows, highs, full = [], [], []+ for i in np.linspace(0, m.n - 1, min(sample, m.n)).astype(int):+ a = m.at(int(i))+ lows.append(float(a.min()))+ highs.append(float(a.max()))+ full.append(float((a >= 1.0).mean()))+ return {"min": min(lows), "max": max(highs), "opaque_share": round(float(np.mean(full)), 3)}+++def _env_quiet() -> None:+ os.environ.setdefault("GLOG_minloglevel", "2")+++_env_quiet()diff --git a/edit/askeditor/fx/core/phrasing.py b/edit/askeditor/fx/core/phrasing.pynew file mode 100644index 0000000..dc92fb6--- /dev/null+++ b/edit/askeditor/fx/core/phrasing.py@@ -0,0 +1,422 @@+"""Where a caption breaks a sentence into cards: the words shown together, cut where a reader expects.++Every caption the pack draws comes through here (`captions`, clean-cut's captions, split-layout's+panel, the answers prompt-box lays down, and any effect that puts the pack's captions over itself).+A card is the words on screen at once. Where one card ends and the next begins is decided by how+the words hang together first, and only then by how even the cards are:++1. **A sentence ends a card, and so does a long silence** (`HOLD_ACROSS`): a card is never held+ on screen across one. A shorter pause is a good place to cut, never a forced one: unscripted+ speech stops after "the", "and" or "who" while the next word is found, and a card cut there+ leaves the reader hanging on a word that points at nothing.+2. **The best cuts, in order:** after a comma (a dash, a colon) or a real pause in the voice;+ before a word that opens a clause ("and", "but", "so", "because", "which", "who", "once",+ "if", "we"); before a word that opens a phrase ("to", "in", "with", "the", "my", "is"). A cut+ between two words of one phrase ("an inbuilt | video edit") is worse, and one just before a+ word that finishes the phrase in front of it ("set | up", "makes | you", "bigger | than") is+ worse again.+3. **A card does not end on a word that leans forward** ("the", "of", "is", "and", "my", "to",+ "with", "really"), unless something closes it: a comma after it, or a word such as "and" after+ it that shows what it began is over ("the next step is | and what makes you").+4. **What is said as one is never split:** "right now", "kind of", "going to", "thank you", a first+ and last name, a number and what it counts, two pieces of one figure ("500" ",000", "in" "-built").+5. **Cards are even, within the look's number of words.** That number may be passed by one word+ where it keeps a phrase whole; a number the person sets (`max_words`) is never passed. One word+ is alone on a card only when it was said alone: a sentence of its own, or between long silences.++Only which words go together is decided here. When a card shows and for how long stays with the+captions: it starts on its first word and ends after its last.++The word lists are written for this pack, from how people talk on camera: the test clips and+our own takes, read card by card (`tests/phrasing.py` counts what still reads badly).+"""++from __future__ import annotations++import math+import re++from .words import Word, pause_after++BREAK_PAUSE = 0.30 # a real stop in the voice: as good a place to cut as a comma+LIST_PAUSE = 0.12 # a comma said with less than this after it runs straight on ("a clean, bold one")+HOLD_ACROSS = 1.5 # a silence this long between two words always ends the card before it+LONGEST_RUN = 48 # a run of more words than this is halved at its best cut before it is cut into cards+++def _set(text: str) -> frozenset[str]:+ return frozenset(text.split())+++# ---- the words, by what they do at the edge of a card ------------------------------------------++# Words that open a clause: a cut just before one is where a speaker would breathe.+OPENS_CLAUSE = _set("""+and but or nor so yet then because although though while whereas if unless until once when whenever where+wherever whether which who whom whose what why how that+""")+# Words that show the phrase before them is over: "draws people in | and", "the next step is | and".+COORDINATORS = _set("and but or nor so then")+# The one doing something, at the head of a clause: a cut before is good, a cut after leaves the+# reader waiting for the verb. ("you" and "it" can be either end of a verb, so they are not here.)+SUBJECTS = _set("""+i we they he she i'm i've i'll i'd we're we've we'll we'd they're they've they'll they'd he's he'll he'd+she's she'll she'd you're you've you'll you'd it's it'll that's there's here's what's who's let's+""")+# Words that open a phrase and lean into it.+PREPOSITIONS = _set("""+to of in on at for with from by about into onto through throughout over under after before without within+between among against during toward towards upon via per across around behind beyond below above beside near+like as than since till despite except inside outside along+""")+# Words that usually finish a verb ("set up", "stand out", "come back") rather than start a phrase.+PARTICLES = _set("up down out off back away")+# Words that always begin a noun phrase.+DETERMINERS = _set("a an the my your our their its his every each")+# Words that begin a noun phrase or are one ("this product" / "just like this"): they lean forward+# only into a word that carries their phrase on.+EITHER = _set("""+this that these those some any all both her much many more most less least few another other such no+""")+# Verbs that need what follows them. "have" and "do" can also be the verb itself, with a thing+# after them ("we have | an editor"): then they finish their clause's start and do not lean.+AUXILIARIES = _set("""+am is are was were be been being have has had do does did will would can could should shall may might must+isn't aren't wasn't weren't don't doesn't didn't won't wouldn't can't couldn't shouldn't haven't hasn't hadn't+ain't gonna wanna gotta+""")+HAVE_DO = _set("have has had do does did")+# Words that bend the word after them ("really good", "just ask", "not sure").+BENDS_NEXT = _set("""+very really real so too quite pretty super extremely totally absolutely incredibly just not never even only+also almost still already always+""")+# Words that end the phrase in front of them when they follow its verb: "makes | you" splits one.+OBJECTS = _set("me him us them you it her")+# Words that stand for a noun, so a verb after them is their own: "it | is" splits a clause's start.+PRONOUNS = OBJECTS | _set("""+this that these those there here what who which one everyone everybody someone somebody everything something+anything anyone nothing nobody+""")+NUMBER_WORDS = _set("""+zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen+seventeen eighteen nineteen twenty thirty forty fifty sixty seventy eighty ninety hundred thousand million+billion trillion dozen half+""")+# Words that open a phrase or a clause firmly enough that the word before them is finished.+STARTS = OPENS_CLAUSE | SUBJECTS | PREPOSITIONS | AUXILIARIES+# A full stop after these is the word's own, not the end of a sentence: "Mr. Smith" is one name.+TITLES = _set("mr mrs ms dr st prof")++# Two words said as one: a cut between them reads as two thoughts where the speaker had one. Only+# pairs the rules above would let a cut fall inside are listed ("of course" is safe already: "of"+# leans forward).+SAID_AS_ONE = frozenset(tuple(p.split()) for p in """+right now|right here|right there|right away|right back|right after|right before+kind of|sort of|type of|out of|because of|instead of|lot of|lots of|bunch of|couple of|front of|ahead of+top of|all of|most of|some of|none of|each of|both of|any of|many of|few of|half of|one of|rest of|part of+going to|want to|wants to|wanted to|have to|has to|had to|need to|needs to|needed to|got to|used to|able to+trying to|try to|tried to|supposed to|ought to|like to|love to|hate to|plan to|planning to|seem to|seems to+start to|started to|begin to|began to|happen to|happened to|manage to|managed to|learn to|decided to+thank you|you know|no one|each other|one another|make sure|pretty much|rather than|more than|less than+other than|all right|real quick|real big|real good|up to+out there|up there|down there|over there|back there|out here|up here|down here|over here|back here+""".replace("\n", "|").split("|") if p.strip())++# How good a cut is, by where it falls (lower is better), and what each fault costs on top. Where+# the cuts fall comes first; how even the cards are only settles between cuts nearly as good.+AT_A_STOP = 0.0 # after a comma, a dash, a colon or a real pause+BEFORE_A_CLAUSE = 1.5 # before "and", "because", "which", "we"...+BEFORE_A_PHRASE = 3.0 # before "to", "the", "is"...+INSIDE_A_PHRASE = 4.5 # between two words of one phrase, as far as the words can tell+MAY_HAVE_ENDED = 5.25 # two words into a noun phrase that may have ended: "the lively city | come"+FINISHES_IT = 9.0 # before the word that finishes the phrase in front: "set | up", "makes | you"+LEANS = 15.0 # a card ending on a word that leans forward+SAID_TOGETHER = 15.0 # a cut between two words said as one+GLUED = 100.0 # a cut between two pieces of one word or figure: only if nothing else can be done+EVEN = 0.5 # each word a card is away from the even share of its run: evenness settles ties+OVER = 3.0 # a card past the look's number of words (allowed by one, where it keeps a phrase whole)+EXTRA_CARD = 1.0 # each card more than the look's number of words needs+LONE = 12.0 # one word alone on a card+LONE_POINT = 1.0 # ... when it is the point of its line: "Distribution | is a real big issue"+ONE_TOO_EARLY = 3.0 # a card that opens on the last word of the thought before it+QUICK = 3.0 # each word (up to three) of a card on screen for less than `QUICK_S`: it flashes by+QUICK_S = 0.4+WAITING = 2.0 # a second of silence held inside one card, beyond `WAIT_S`+WAIT_S = 0.5++_EDGE = re.compile(r"^[-–—,.%]") # a word that is the rest of the one before ("-built", ",000", "%")+_SIGNS = {"$", "£", "€", "#", "@"} # a word that is the start of the one after+++# ---- reading one edge ----------------------------------------------------------------------------++def is_number(w: Word) -> bool:+ return any(c.isdigit() for c in w.key) or w.key in NUMBER_WORDS+++def _title(w: Word) -> bool:+ return w.key in TITLES and w.text.rstrip().endswith(".")+++def ends_sentence(words: list[Word], i: int) -> bool:+ """Does a sentence end after word i? A full stop after a title ("Dr.") does not end one."""+ return words[i].ends_sentence and not _title(words[i])+++def _closed(w: Word) -> bool:+ """A comma, a dash, a colon or a full stop after the word: nothing it began runs on."""+ return w.ends_clause and not _title(w)+++def _name(words: list[Word], i: int) -> bool:+ """A word written with a capital that is not there because it starts a sentence."""+ w = words[i]+ t = w.text.strip().lstrip("\"'“‘(")+ if not t[:1].isupper() or w.key in ("i", "i'm", "i've", "i'll", "i'd"):+ return False+ return i > 0 and not ends_sentence(words, i - 1)+++_CLOSED_CLASS = (OPENS_CLAUSE | SUBJECTS | PREPOSITIONS | PARTICLES | DETERMINERS | EITHER | AUXILIARIES+ | BENDS_NEXT | PRONOUNS | COORDINATORS)+++def _content(w: Word) -> bool:+ """A word that carries meaning (a thing, an action, a quality), as far as the lists can tell."""+ return bool(w.key) and w.key not in _CLOSED_CLASS and not is_number(w)+++def _opens_noun(w: Word) -> bool:+ """A word that begins a noun phrase: "the", "my", "that" (issue), "two" (ways)."""+ return w.key in DETERMINERS or w.key in EITHER or is_number(w)+++def _start_of(words: list[Word], i: int) -> int:+ """The first piece of the word that ends at i ("in" for "in" "-built")."""+ while i > 0 and glued(words, i - 1):+ i -= 1+ return i+++def into_noun(words: list[Word], i: int, quiet: list[tuple[float, float]]) -> tuple[int, bool]:+ """How far into a noun phrase a cut after word i would fall, and whether the phrase is sure to+ run on: (1, True) for "the lively | city", (2, False) for "an inbuilt video | edit", (2, True)+ for "a real big | issue" and "a clean, bold | subtitle", whose words still wait for their noun.+ (0, False) when no phrase opened by "the", "my", "two" and the like is open, or the next word+ does not carry it on. A comma said without a pause does not close the phrase; one with a pause+ after it does."""+ if i + 1 >= len(words) or not _content(words[i + 1]):+ return 0, False+ if i + 2 < len(words) and words[i + 2].key in PARTICLES:+ return 0, False # "the audio | set up": a verb and its particle, not more of the thing+ depth, k, waiting = 0, i, False+ while k >= 0 and depth < 3:+ end, k = k, _start_of(words, k)+ w = words[k]+ if _opens_noun(w) and depth and k == end:+ return (depth, waiting or depth == 1) if not _closed(w) else (0, False)+ if not (_content(w) or w.key in BENDS_NEXT or k < end): # a word in pieces ("in" "-built") is one word+ return 0, False+ w = words[end]+ if end < i and _closed(w):+ if pause_after(words, end, quiet) >= LIST_PAUSE:+ return 0, False+ waiting = True # "clean, bold": a list of what the thing is like, the thing still to come+ waiting = waiting or w.key in BENDS_NEXT # "real big": a word that bends the next is not the noun+ depth += 1+ k -= 1+ return 0, False+++def stands_alone(w: Word) -> bool:+ """A word that can be the whole of a card, said as the point of its line: a long word that is+ not grammar, an acronym, or a number."""+ raw = w.text.strip().strip("\"'“”‘’.,;:!?()")+ return (_content(w) and (len(w.key) >= 7 or (raw.isupper() and len(raw) >= 2))) or is_number(w)+++def glued(words: list[Word], i: int) -> bool:+ """Are word i and the next two pieces of one word or figure ("in" "-built", "500" ",000", "$" "5")?"""+ nxt = words[i + 1].text.strip()+ return bool(_EDGE.match(nxt)) or not any(c.isalnum() for c in nxt) or words[i].text.strip() in _SIGNS+++def said_as_one(words: list[Word], i: int) -> bool:+ """Are word i and the next said as one: a fixed pair, a name, a number and what it counts?"""+ a, b = words[i], words[i + 1]+ if (a.key, b.key) in SAID_AS_ONE:+ return True+ if is_number(a) and (is_number(b) or b.key in ("point", "percent", "k", "x")):+ return True # "five million", "one point five", "ten percent"+ if a.key == "point" and is_number(b) and i > 0 and is_number(words[i - 1]):+ return True+ if is_number(a) and b.key == "and" and i + 2 < len(words) and is_number(words[i + 2]):+ return True # "two hundred and fifty"+ return _name(words, i) and _name(words, i + 1) and not _closed(a)+++def leans(words: list[Word], i: int) -> bool:+ """Does word i lean into the next, so that a card ending on it leaves the reader hanging?"""+ if i + 1 >= len(words):+ return False+ w, nxt = words[i], words[i + 1]+ if _closed(w):+ return False+ k, n = w.key, nxt.key+ if k in DETERMINERS:+ return True # "the |" is never finished+ if k in HAVE_DO and _opens_noun(nxt):+ return False # "we have | an inbuilt video edit": the verb itself, then what it has+ if k in OPENS_CLAUSE or k in SUBJECTS or k in PREPOSITIONS or k in AUXILIARIES or k in BENDS_NEXT:+ return n not in COORDINATORS # "is | and what" and "in | and all": what it began is over+ if k in PARTICLES:+ # "out | of", "down | the hill" go on; "set up | and", "all the way down | to" do not.+ return n == "of" or n in DETERMINERS or is_number(nxt)+ if k in EITHER or is_number(w):+ return n not in STARTS # "that | issue", "two | ways"; but "like this | and", "in 2024 | we"+ return False+++def where_cut(words: list[Word], i: int, quiet: list[tuple[float, float]]) -> float:+ """How good a place the cut between word i and the next is, from `AT_A_STOP` (0, the best) to+ `FINISHES_IT`, before anything the cut breaks is counted (`cut_cost`)."""+ w, nxt = words[i], words[i + 1]+ k, n = w.key, nxt.key+ paused = pause_after(words, i, quiet) >= BREAK_PAUSE+ depth, open_ = into_noun(words, i, quiet)+ if depth and not paused:+ # "the lively | city", "a clean, | bold subtitle": a comma between two words of one thing+ # is no place to stop. Two words in, the phrase may have ended ("the lively city | come"),+ # unless what it has so far still waits for its noun; three words in, it likely has.+ cost = FINISHES_IT if open_ else MAY_HAVE_ENDED if depth == 2 else INSIDE_A_PHRASE+ elif _closed(w) or paused:+ cost = AT_A_STOP+ elif n == "that" and i + 2 < len(words) and _content(words[i + 2]):+ cost = BEFORE_A_PHRASE # "solve | that issue": "that" begins a thing here, not a clause+ elif n in OPENS_CLAUSE or n in SUBJECTS:+ cost = BEFORE_A_CLAUSE+ elif n in PARTICLES or n == "than":+ cost = FINISHES_IT+ elif n in OBJECTS and k not in STARTS and k not in DETERMINERS and k not in EITHER:+ cost = FINISHES_IT # "makes | you", "give | me"+ elif n in AUXILIARIES and k in PRONOUNS:+ cost = FINISHES_IT # "it | is", "you | can"+ elif n == "of":+ cost = INSIDE_A_PHRASE # "of" belongs to the word before it more than to the word after+ elif n in PREPOSITIONS or n in DETERMINERS or n in EITHER or n in AUXILIARIES:+ cost = BEFORE_A_PHRASE+ else:+ cost = INSIDE_A_PHRASE+ return cost+++def cut_cost(words: list[Word], i: int, quiet: list[tuple[float, float]]) -> float:+ """What a cut between word i and the next costs: where it falls, and anything it breaks."""+ cost = where_cut(words, i, quiet)+ if leans(words, i):+ cost += LEANS+ if said_as_one(words, i):+ cost += SAID_TOGETHER+ if glued(words, i):+ cost += GLUED+ return cost+++# ---- the cards ---------------------------------------------------------------------------------++def runs(words: list[Word]) -> list[list[int]]:+ """Word indexes split where no card may run on: at the end of each sentence, and at each+ silence of `HOLD_ACROSS` or more."""+ out, cur = [], []+ for i, w in enumerate(words):+ cur.append(i)+ if i == len(words) - 1 or ends_sentence(words, i) or words[i + 1].start - w.end >= HOLD_ACROSS:+ out.append(cur)+ cur = []+ return out+++def _card_cost(words: list[Word], run: list[int], j: int, i: int, share: float, most: int,+ place: list[float]) -> float:+ """What the card of run[j:i] costs, apart from the cut at its end. `place[k]` is how good a+ place the cut after run[k] is."""+ size = i - j+ if size == 1 and stands_alone(words[run[j]]):+ cost = LONE_POINT # a word set apart on purpose is not held to the others' length+ else:+ cost = EVEN * abs(size - share) + (LONE if size == 1 else 0.0)+ if size > most:+ cost += OVER+ if (size >= 2 and j > 0 and place[j - 1] > BEFORE_A_CLAUSE and place[j] <= BEFORE_A_CLAUSE+ and not leans(words, run[j])):+ # "big | issue and most ads": the card opens on the last word of the thought before it,+ # one word short of a good place to start.+ cost += ONE_TOO_EARLY+ first, last = words[run[j]], words[run[i - 1]]+ # How long the card is up: until the next card's first word when one follows straight on.+ shown = (words[run[i]].start if i < len(run) else last.end + QUICK_S) - first.start+ if shown < QUICK_S:+ cost += QUICK * min(size, 3)+ for a, b in zip(run[j:i - 1], run[j + 1:i]):+ cost += WAITING * max(0.0, words[b].start - words[a].end - WAIT_S)+ return cost+++def split_run(words: list[Word], run: list[int], quiet: list[tuple[float, float]], most: int,+ over: int = 1) -> list[list[int]]:+ """One run of words as cards of at most `most + over` words, the cuts where they read best."""+ n = len(run)+ if n <= most:+ return [run]+ cap = most + over+ cuts = [cut_cost(words, run[k], quiet) for k in range(n - 1)] # cuts[k]: after run[k]+ if n > LONGEST_RUN:+ # A long run with no full stop (a list, a take said in one breath) is halved first at its+ # best place to cut near the middle, so the search below only ever weighs a few cards.+ lo, hi = n // 3, n - n // 3+ k = min(range(lo, hi), key=lambda k: (cuts[k], abs(k - n / 2)))+ return (split_run(words, run[:k + 1], quiet, most, over)+ + split_run(words, run[k + 1:], quiet, most, over))+ place = [where_cut(words, run[k], quiet) for k in range(n - 1)]+ fewest, aim = math.ceil(n / cap), math.ceil(n / most)+ best_total, best_cards = math.inf, [run]+ for parts in range(max(fewest, aim - 1), aim + 3):+ if parts > n:+ break+ share = n / parts+ # cost[p][i]: the cheapest way to make the first i words into p cards.+ cost = [[math.inf] * (n + 1) for _ in range(parts + 1)]+ back = [[0] * (n + 1) for _ in range(parts + 1)]+ cost[0][0] = 0.0+ for p in range(1, parts + 1):+ for i in range(p, n + 1):+ for j in range(max(p - 1, i - cap), i):+ if cost[p - 1][j] == math.inf:+ continue+ c = cost[p - 1][j] + _card_cost(words, run, j, i, share, most, place) + (cuts[i - 1] if i < n else 0.0)+ if c < cost[p][i]:+ cost[p][i], back[p][i] = c, j+ total = cost[parts][n] + EXTRA_CARD * max(0, parts - aim)+ if total < best_total:+ cards, i = [], n+ for p in range(parts, 0, -1):+ j = back[p][i]+ cards.append(run[j:i])+ i = j+ best_total, best_cards = total, cards[::-1]+ return best_cards+++def phrases(words: list[Word], quiet: list[tuple[float, float]], most: int, over: int = 1) -> list[list[int]]:+ """Word indexes grouped into the cards shown together, each of at most `most` words, or+ `most + over` where that keeps a phrase whole (pass `over=0` when the person chose `most`)."""+ if not words:+ return []+ if most <= 1:+ return [[i] for i in range(len(words))]+ out: list[list[int]] = []+ for run in runs(words):+ out.extend(split_run(words, run, quiet, most, over))+ return out+diff --git a/edit/askeditor/fx/core/render.py b/edit/askeditor/fx/core/render.pynew file mode 100644index 0000000..762433b--- /dev/null+++ b/edit/askeditor/fx/core/render.py@@ -0,0 +1,174 @@+"""Running a clip through an effect: every output frame, or a few stills.++Both paths call the same `draw(frame, j, t)` on the same output frame, so a still is exactly the+frame the finished video shows at that moment (a preview drawn by other code is a preview of+something else).+"""++from __future__ import annotations++import time+from pathlib import Path+from typing import Callable, Optional++import numpy as np++from . import audio, video+from .clip import Clip+from .framing import Framing+from .timeline import Timeline++Draw = Callable[[np.ndarray, int, float], None]+++HOLD_FADE = 0.12 # seconds the sound fades out over before a held last frame, so it never stops dead+FREEZE_FADE = 0.025 # seconds the sound fades out over into a freeze, and back in after it+++def with_freezes(s: np.ndarray, rate: int, timeline: Timeline) -> np.ndarray:+ """The joined sound `s` with silence laid in for each freeze, faded out into it and back in+ after it, so the sound stops and starts with the picture and nothing clicks."""+ n = max(1, int(round(FREEZE_FADE * rate)))+ s = np.array(s, np.float32)+ pieces, last = [], 0+ for p, seconds, _ in timeline.freezes_in_play():+ cut = int(np.clip(round(p * rate), last, len(s)))+ m = min(n, cut - last)+ if m:+ s[cut - m:cut] *= np.cos(np.linspace(0, np.pi / 2, m, dtype=np.float32))[:, None]+ m = min(n, len(s) - cut)+ if m:+ s[cut:cut + m] *= np.sin(np.linspace(0, np.pi / 2, m, dtype=np.float32))[:, None]+ pieces += [s[last:cut], np.zeros((int(round(seconds * rate)), s.shape[1]), np.float32)]+ last = cut+ pieces.append(s[last:])+ return np.concatenate(pieces)+++def sound_for(clip: Clip, timeline: Timeline, fade: float = 0.02) -> np.ndarray:+ """The output's sound: the kept stretches joined with short crossfades, exactly as long as the+ output's frames. A freeze inside the clip is silent, the sound fading out into it and back in+ after it; a held last frame (`timeline.hold`) is silent, and the sound fades out into it."""+ rate = video.AUDIO_RATE+ n_out = timeline.output_frames(clip.info.rate)+ want = int(round(n_out / clip.info.rate * rate))+ if timeline.is_identity(clip.info.frames / clip.info.rate):+ s = clip.sound+ else:+ s = audio.join(clip.sound, rate, timeline.sample_ranges(rate), fade=fade)+ if timeline.freezes:+ s = with_freezes(s, rate, timeline)+ if timeline.hold > 0:+ s = np.array(s[:int(round(timeline.played * rate))], np.float32)+ n = min(len(s), int(round(HOLD_FADE * rate)))+ if n:+ s[len(s) - n:] *= np.cos(np.linspace(0, np.pi / 2, n, dtype=np.float32))[:, None]+ if len(s) < want:+ s = np.concatenate([s, np.zeros((want - len(s), s.shape[1]), np.float32)])+ return np.ascontiguousarray(s[:want])+++def frames(info: video.VideoInfo):+ """Every frame of the clip, in order: decoded from its file, or asked of a drawn picture+ (`info.picture`: a film put together from several clips, say) one frame at a time."""+ if info.picture is not None:+ return (np.asarray(info.picture(i)) for i in range(info.frames))+ return iter(video.FrameReader(info))+++def render(clip: Clip, timeline: Timeline, framing: Framing, draw: Optional[Draw], out: Path,+ fade: float = 0.02, crf: int = 18, audio_kbps: int = 192,+ mix: Optional[Callable[[np.ndarray, int], np.ndarray]] = None) -> dict:+ """Write the whole output video. Returns what was written and how long it took. `crf` is the+ picture's quality (lower is better and larger: 18 is near the source, 23 half the size). `mix`,+ when given, lays the effect's own sounds under the clip's (it gets the output's sound and its+ rate and returns the sound to write; the length is kept). A clip whose picture is drawn+ (`clip.info.picture`) is rendered from what it draws."""+ info = clip.info+ fps = info.rate+ n_out = timeline.output_frames(fps)+ started = time.time()+ sound = sound_for(clip, timeline, fade)+ if mix is not None:+ mixed = np.asarray(mix(sound, video.AUDIO_RATE), np.float32)+ if mixed.shape != sound.shape:+ raise ValueError("an effect's sound changed the length of the video's sound")+ sound = np.ascontiguousarray(mixed)+ writer = video.FrameWriter(out, framing.out_w, framing.out_h, info.fps, audio=sound, crf=crf,+ audio_kbps=audio_kbps)+ reader = frames(info)+ current, k_read = None, -1+ try:+ for j in range(n_out):+ k = timeline.source_frame(j, fps, info.frames)+ while k_read < k:+ nxt = next(reader, None)+ if nxt is None: # the clip ran a frame short of its stated length: hold the last+ k_read = k+ break+ current, k_read = nxt, k_read + 1+ if current is None:+ raise video.MediaError(f"could not read the picture of {info.path}")+ frame = framing.apply(current, k)+ if frame is current or not frame.flags.writeable:+ frame = frame.copy()+ if draw is not None:+ draw(frame, j, j / fps)+ writer.write(frame)+ path = writer.close()+ except BaseException:+ writer.abort()+ raise+ return {"path": str(path), "frames": n_out, "seconds_out": round(n_out / fps, 3),+ "render_s": round(time.time() - started, 2)}+++def still_frames(clip: Clip, timeline: Timeline, framing: Framing, draw: Optional[Draw],+ times: list[float]) -> list[tuple[float, np.ndarray]]:+ """The output frames at `times` (output seconds), drawn exactly as the render draws them."""+ info = clip.info+ fps = info.rate+ n_out = timeline.output_frames(fps)+ out = []+ for t in times:+ j = int(min(n_out - 1, max(0, round(t * fps))))+ k = timeline.source_frame(j, fps, info.frames)+ frame = framing.apply(video.read_frame(info, k), k).copy()+ if draw is not None:+ draw(frame, j, j / fps)+ out.append((j / fps, frame))+ return out+++def save_stills(frames: list[tuple[float, np.ndarray]], out: Path) -> list[Path]:+ """Each still as its own JPEG beside `out`, plus one image with all of them side by side+ (`<out>.stills.jpg`), which is the one to look at."""+ from PIL import Image, ImageDraw++ paths = []+ stem = out.with_suffix("")+ for t, f in frames:+ p = Path(f"{stem}.still-{t:06.2f}s.jpg")+ video.save_jpeg(p, f, quality=90)+ paths.append(p)+ if frames:+ h = 960+ tiles = []+ for t, f in frames:+ scale = h / f.shape[0]+ img = Image.fromarray(f).resize((int(round(f.shape[1] * scale)), h), Image.LANCZOS)+ label = Image.new("RGB", (img.width, 44), (18, 18, 18))+ ImageDraw.Draw(label).text((12, 10), f"{t:.2f} s", fill=(235, 235, 235))+ tile = Image.new("RGB", (img.width, h + 44))+ tile.paste(img, (0, 0))+ tile.paste(label, (0, h))+ tiles.append(tile)+ sheet = Image.new("RGB", (sum(t.width for t in tiles) + 8 * (len(tiles) - 1), h + 44), (40, 40, 40))+ x = 0+ for tile in tiles:+ sheet.paste(tile, (x, 0))+ x += tile.width + 8+ p = Path(f"{stem}.stills.jpg")+ sheet.save(p, quality=88)+ paths.insert(0, p)+ return pathsdiff --git a/edit/askeditor/fx/core/shots.py b/edit/askeditor/fx/core/shots.pynew file mode 100644index 0000000..0dc49e1--- /dev/null+++ b/edit/askeditor/fx/core/shots.py@@ -0,0 +1,102 @@+"""The clip's own cuts: where the picture jumps from one shot to the next.++ times = shots.cuts(clip) # seconds where a new shot starts, in order++How much each frame differs from the one before is measured once (every frame read small and grey)+and cached beside the clip as `<clip>.shots.json`; the cuts are decided from it each time.++- **A cut is a jump, not a change.** A camera that moves or a hand that waves changes the picture+ over several frames; a cut changes it all at once. A frame is a cut when it differs from the one+ before several times more than the frames around it differ from theirs (the median over half a+ second either side), and by enough to see.+- **The speaker is there on both sides.** These are films of somebody talking, so the face is found+ in the quarter second before a cut and in the quarter second after it. A hand over the lens+ (clip C, 9.2 s) jumps like a cut, but the face is lost behind it, so it is not one. A film with+ nobody talking in it (scenery cut together) has no face to look for: `speaker=False` finds its+ cuts by the jump alone.+- **One cut per jump.** A joined clip sometimes keeps a stray frame of what was taken out, which+ makes two jumps a frame apart; they are one cut, at the first.++Jump cuts inside one camera set-up, where the person barely moved, change too little to tell from+talking: on clip 33 the cut finds 9 of its 10 joins, and the one it misses changes nothing a viewer+would see either.+"""++from __future__ import annotations++import json+import time+from pathlib import Path++import numpy as np++from . import paths+from .video import FrameReader++CACHE_VERSION = 1+READ_WIDTH = 96+AROUND = 0.5 # seconds either side that say how much the picture usually changes+JUMP = 2.2 # a cut changes the picture at least this many times more than usual...+SEEN = 5.0 # ...and by at least this much (mean change of a pixel, 0..255)+FACE_SIDE = 0.25 # seconds either side of a cut in which the face must be found...+FACE_SHARE = 0.6 # ...in at least this share of the frames+APART = 0.3 # seconds: cuts closer than this are one+++def changes(info, refresh: bool = False) -> np.ndarray:+ """How much each frame differs from the one before (mean of the pixels, 0..255; 0 for the+ first frame), from the cache beside the clip or measured now."""+ cache = paths.beside(info.path, "shots.json")+ signature = paths.source_signature(info.path)+ if not refresh and cache.exists():+ try:+ data = json.loads(cache.read_text(encoding="utf-8"))+ if (data.get("version") == CACHE_VERSION and data.get("source", {}).get("bytes") == signature["bytes"]+ and len(data.get("change", [])) == info.frames):+ return np.asarray(data["change"], np.float32)+ except (json.JSONDecodeError, KeyError, TypeError, ValueError):+ pass+ started = time.time()+ w = READ_WIDTH+ h = max(2, int(round(info.height * w / info.width / 2)) * 2)+ out = np.zeros(info.frames, np.float32)+ prev = None+ for i, f in enumerate(FrameReader(info, size=(w, h), gray=True)):+ if i >= info.frames:+ break+ g = f.astype(np.float32)+ if prev is not None:+ out[i] = float(np.abs(g - prev).mean())+ prev = g+ data = {"version": CACHE_VERSION, "source": signature, "frames": info.frames,+ "seconds": round(time.time() - started, 2), "change": [round(float(v), 2) for v in out]}+ tmp = Path(str(cache) + ".part")+ tmp.write_text(json.dumps(data, separators=(",", ":")) + "\n")+ tmp.replace(cache)+ return out+++def cuts(clip, refresh: bool = False, speaker: bool = True) -> list[float]:+ """The seconds at which a new shot starts in `clip` (a Clip: its picture and its face). With+ `speaker=False` the face is not looked for, for a film with nobody talking in it."""+ info = clip.info+ d = changes(info, refresh)+ fps = info.rate+ n = len(d)+ r = max(2, int(round(AROUND * fps)))+ q = max(2, int(round(FACE_SIDE * fps)))+ found = clip.face.found if speaker and clip.face.n == n else np.ones(n, bool)+ picked: list[int] = []+ for i in range(1, n):+ if d[i] < SEEN:+ continue+ near = np.r_[d[max(1, i - r):max(1, i - 1)], d[i + 2:i + r + 1]]+ usual = float(np.median(near)) if len(near) else 0.0+ if d[i] < JUMP * (usual + 2.0):+ continue+ if found[max(0, i - q):i].mean() < FACE_SHARE or found[i:i + q].mean() < FACE_SHARE:+ continue+ if picked and (i - picked[-1]) / fps < APART:+ continue+ picked.append(i)+ return [round(i / fps, 3) for i in picked]diff --git a/edit/askeditor/fx/core/sound.py b/edit/askeditor/fx/core/sound.pynew file mode 100644index 0000000..aa9a26b--- /dev/null+++ b/edit/askeditor/fx/core/sound.py@@ -0,0 +1,254 @@+"""Sound an effect adds under the clip's own: reading a track, its loudness, laying a sound on a+moment, and where somebody is talking.++- `read(path)`: any sound file, or the sound of a video, as 48 kHz stereo float32.+- `loudness`: K-weighted loudness after ITU-R BS.1770, computed here in numpy, for setting one sound+ against another while a mix is being built. The finished mix is measured by ffmpeg itself+ (`loudness.py`), so the numbers a person reads come from the tool everybody uses.+- `lay()`: a sound added so that the moment it lands (the attack of a struck sound, the peak of a+ swell) falls on a given time, to the sample.+- `speech_spans()`: the stretches where somebody is talking, from the word times and the quiet+ stretches the core already finds, joined across the short gaps between phrases.+- `library(kind)`: one of the pack's own sounds in `sounds/` (a whoosh, a hit, a pop), read once,+ with the second it lands at.+"""++from __future__ import annotations++import subprocess+from dataclasses import dataclass+from pathlib import Path+from typing import Iterable, Optional++import numpy as np++from .video import AUDIO_CHANNELS, AUDIO_RATE, MediaError, need_ffmpeg++SILENCE_DB = -120.0+++# ---- reading -----------------------------------------------------------------------------------++def read(path: str | Path, rate: int = AUDIO_RATE, channels: int = AUDIO_CHANNELS) -> np.ndarray:+ """A sound file (mp3, wav, m4a, flac, ogg…) or a video's sound as float32 of shape (n, channels)."""+ need_ffmpeg()+ path = Path(path)+ if not path.exists():+ raise MediaError(f"there is no file at {path}")+ run = subprocess.run(+ ["ffmpeg", "-v", "error", "-nostdin", "-i", str(path), "-map", "0:a:0", "-vn", "-ac", str(channels),+ "-ar", str(rate), "-f", "f32le", "-"],+ capture_output=True,+ )+ if run.returncode != 0 or not run.stdout:+ raise MediaError(f"could not read any sound from {path}")+ return np.frombuffer(run.stdout, np.float32).reshape(-1, channels).copy()+++def db(x: float) -> float:+ return 20.0 * np.log10(max(float(x), 1e-12))+++def gain(decibels: float) -> float:+ return float(10.0 ** (decibels / 20.0))+++# ---- loudness (BS.1770, in numpy) --------------------------------------------------------------++# The two filters that make "K-weighting" at 48 kHz, as the standard gives them: a shelf that lifts+# what the head makes louder, then a high-pass that drops what we hardly hear.+_SHELF = ((1.53512485958697, -2.69169618940638, 1.19839281085285), (1.0, -1.69065929318241, 0.73248077421585))+_HIGHPASS = ((1.0, -2.0, 1.0), (1.0, -1.99004745483398, 0.99007225036621))+++def _response(coeffs, n_fft: int) -> np.ndarray:+ (b0, b1, b2), (_, a1, a2) = coeffs+ z = np.exp(-2j * np.pi * np.arange(n_fft // 2 + 1) / n_fft)+ return (b0 + b1 * z + b2 * z * z) / (1.0 + a1 * z + a2 * z * z)+++_IR_LENGTH = 1 << 13 # 0.17 s: the two filters' response has died away long before this+_CHUNK = 1 << 18+++def _k_impulse() -> np.ndarray:+ n_fft = 1 << 16+ h = _response(_SHELF, n_fft) * _response(_HIGHPASS, n_fft)+ return np.fft.irfft(h, n_fft)[:_IR_LENGTH]+++def k_weight(samples: np.ndarray, rate: int = AUDIO_RATE) -> np.ndarray:+ """The samples through the K-weighting filters, as float64 (n, channels). The filters' impulse+ response is applied by FFT, a chunk at a time, which gives what running them would give."""+ if rate != 48000:+ raise ValueError("k_weight works at 48 kHz, the rate every sound in the pack is read at")+ x = samples if samples.ndim == 2 else samples[:, None]+ n, ir = len(x), _k_impulse()+ n_fft = 1 << int(np.ceil(np.log2(_CHUNK + len(ir))))+ spec = np.fft.rfft(ir, n_fft)[:, None]+ y = np.zeros((n + len(ir), x.shape[1]))+ for a in range(0, n, _CHUNK):+ part = x[a:a + _CHUNK].astype(np.float64)+ conv = np.fft.irfft(np.fft.rfft(part, n_fft, axis=0) * spec, n_fft, axis=0)[:len(part) + len(ir) - 1]+ y[a:a + len(conv)] += conv+ return y[:n]+++@dataclass(frozen=True)+class Blocks:+ """The mean square of the K-weighted sound in overlapping blocks (summed over the channels)."""+ power: np.ndarray+ starts: np.ndarray # seconds+ length: float # seconds per block++ @property+ def lufs(self) -> np.ndarray:+ return -0.691 + 10.0 * np.log10(np.maximum(self.power, 1e-15))++ def centres(self) -> np.ndarray:+ return self.starts + self.length / 2+++def blocks(samples: np.ndarray, rate: int = AUDIO_RATE, length: float = 0.4, hop: float = 0.1,+ weighted: Optional[np.ndarray] = None) -> Blocks:+ """`length`-second blocks every `hop` seconds (0.4 and 0.1 are the standard's own)."""+ y = k_weight(samples, rate) if weighted is None else weighted+ n_block, n_hop = int(round(length * rate)), int(round(hop * rate))+ if len(y) < n_block:+ y = np.concatenate([y, np.zeros((n_block - len(y), y.shape[1]))])+ cs = np.concatenate([np.zeros((1, y.shape[1])), np.cumsum(y * y, axis=0)])+ idx = np.arange(0, len(y) - n_block + 1, n_hop)+ power = ((cs[idx + n_block] - cs[idx]) / n_block).sum(axis=1)+ return Blocks(power=power, starts=idx / rate, length=length)+++def integrated(b: Blocks, spans: Optional[Iterable[tuple[float, float]]] = None) -> float:+ """Gated loudness in LUFS (absolute gate at -70, relative gate 10 LU under), over the blocks whose+ middle falls in `spans` when given. -120 when there is nothing to measure."""+ keep = np.ones(len(b.power), bool)+ if spans is not None:+ c = b.centres()+ keep = np.zeros(len(b.power), bool)+ for a, e in spans:+ keep |= (c >= a) & (c <= e)+ p = b.power[keep]+ lufs = -0.691 + 10.0 * np.log10(np.maximum(p, 1e-15))+ p = p[lufs > -70.0]+ if not len(p):+ return SILENCE_DB+ relative = -0.691 + 10.0 * np.log10(p.mean()) - 10.0+ p = p[-0.691 + 10.0 * np.log10(p) > relative]+ return float(-0.691 + 10.0 * np.log10(p.mean())) if len(p) else SILENCE_DB+++def loudest(samples: np.ndarray, rate: int = AUDIO_RATE, window: float = 0.1) -> float:+ """The loudness of the loudest `window` seconds, in LUFS: what a short sound is levelled by, since+ the ear judges a click or a whoosh by about its loudest tenth of a second."""+ return float(blocks(samples, rate, length=window, hop=0.005).lufs.max())+++# ---- laying a sound ------------------------------------------------------------------------------++def lay(out: np.ndarray, sound: np.ndarray, at: float, rate: int = AUDIO_RATE, anchor: float = 0.0,+ level: float = 1.0) -> tuple[int, int]:+ """Add `sound` into `out` (both (n, channels)) so that its sample at `anchor` seconds falls exactly+ at `at` seconds. What would fall before the start or after the end is left off; a sound cut at+ the start gets a 3 ms fade so it never clicks. Returns the samples it covers in `out`."""+ s = sound if sound.ndim == 2 else sound[:, None]+ if s.shape[1] != out.shape[1]:+ s = np.repeat(s[:, :1], out.shape[1], axis=1)+ start = int(round(at * rate)) - int(round(anchor * rate))+ a, b = max(0, start), min(len(out), start + len(s))+ if b <= a:+ return a, a+ piece = s[a - start:b - start].astype(np.float32) * level+ if a > start:+ m = min(len(piece), int(0.003 * rate))+ piece[:m] *= np.linspace(0, 1, m, dtype=np.float32)[:, None]+ out[a:b] += piece+ return a, b+++def resample(sound: np.ndarray, factor: float) -> np.ndarray:+ """The sound played `factor` times faster (higher and shorter when above 1), band-limited."""+ if abs(factor - 1.0) < 1e-6:+ return sound+ n = len(sound)+ m = max(2, int(round(n / factor)))+ spec = np.fft.rfft(sound, axis=0)+ keep = min(len(spec), m // 2 + 1)+ out_spec = np.zeros((m // 2 + 1,) + sound.shape[1:], complex)+ out_spec[:keep] = spec[:keep]+ return (np.fft.irfft(out_spec, m, axis=0) * (m / n)).astype(np.float32)+++# ---- where the voice is ------------------------------------------------------------------------++def speech_spans(words, quiet: list[tuple[float, float]], duration: float, join: float = 1.2,+ edge: float = 0.05) -> list[tuple[float, float]]:+ """Where somebody is talking, as (start, end) seconds.++ A stretch counts when the sound says a voice is there (it lies between the quiet runs) and a+ heard word sits in it; it then runs from just before its first word to just after its last. A+ word the transcriber put in a stretch the sound calls quiet (a breath, a word it invented) does+ not count, and a gust or a knock with no word in it does not either. Stretches closer than+ `join` seconds are one: a short breath between phrases is part of talking.+ """+ voiced, t = [], 0.0+ for q0, q1 in sorted(quiet):+ if q0 > t:+ voiced.append((t, q0))+ t = max(t, q1)+ if t < duration:+ voiced.append((t, duration))+ spans = []+ for v0, v1 in voiced:+ inside = [w for w in words if min(v1, w.end) - max(v0, w.start) >= min(0.06, 0.5 * (w.end - w.start))]+ if not inside:+ continue+ a = max(v0, min(w.start for w in inside) - edge)+ b = min(v1, max(w.end for w in inside) + edge)+ if b > a:+ spans.append((a, b))+ spans.sort()+ merged: list[tuple[float, float]] = []+ for a, b in spans:+ if merged and a - merged[-1][1] < join:+ merged[-1] = (merged[-1][0], max(merged[-1][1], b))+ else:+ merged.append((a, b))+ return [(round(a, 3), round(b, 3)) for a, b in merged]+++def envelope_db(samples: np.ndarray, rate: int = AUDIO_RATE, hop: float = 0.01) -> np.ndarray:+ """The level of the sound in dB (full scale) every `hop` seconds: the RMS of each step, for drawing."""+ x = samples.mean(axis=1) if samples.ndim == 2 else samples+ n = max(1, int(round(hop * rate)))+ steps = int(np.ceil(len(x) / n))+ x = np.pad(x, (0, steps * n - len(x)))+ rms = np.sqrt(np.mean(x.reshape(steps, n).astype(np.float64) ** 2, axis=1))+ return 20.0 * np.log10(np.maximum(rms, 1e-9))+++# ---- the pack's own sounds ------------------------------------------------------------------------++_LIBRARY: dict = {}+++def library(kind: str) -> tuple[np.ndarray, float]:+ """One of the pack's own sounds in `sounds/` (made by sounds/make_sounds.py), as float32 (n, 2)+ at 48 kHz, and the second it lands at (its anchor)."""+ import json+ import wave++ from .paths import PACK++ if kind not in _LIBRARY:+ meta = json.loads((PACK / "sounds" / "sounds.json").read_text(encoding="utf-8"))[kind]+ with wave.open(str(PACK / "sounds" / meta["file"])) as w:+ pcm = np.frombuffer(w.readframes(w.getnframes()), "<i2").reshape(-1, w.getnchannels())+ x = pcm.astype(np.float32) / 32768.0+ if x.shape[1] == 1:+ x = np.repeat(x, 2, axis=1)+ _LIBRARY[kind] = (x, float(meta["anchor_s"]))+ return _LIBRARY[kind]diff --git a/edit/askeditor/fx/core/soundsheet.py b/edit/askeditor/fx/core/soundsheet.pynew file mode 100644index 0000000..63d5ab7--- /dev/null+++ b/edit/askeditor/fx/core/soundsheet.py@@ -0,0 +1,253 @@+"""A picture of what a sound effect did, for the eye of somebody who cannot hear it (or an agent+that cannot): six frames of the video, and under them, on one time line, a lane for each sound (the+clip's own voice, the music, the sounds laid), each drawn as its level in dB, so a duck under the+speech, a swell in a pause and every hit show as shapes. Marks cross the lanes at the moments that+matter (a cut, a card, a splice, the film's last frame), and a row of close-ups shows a few of them+at the scale of single frames: the frame before, the frame on the moment, and the waveform with a+line for every frame boundary, so a sound landing on its frame can be seen to.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from pathlib import Path+from typing import Callable, Optional, Sequence++import numpy as np++from .paths import FONTS+from .sound import envelope_db+from .video import AUDIO_RATE++Colour = tuple[int, int, int]+BG = (18, 18, 20)+PANEL = (30, 30, 34)+GRID = (60, 60, 66)+TEXT = (232, 232, 236)+DIM = (150, 150, 158)+++@dataclass+class Lane:+ name: str+ samples: np.ndarray # (n,) or (n, channels) at 48 kHz, lined up with the video's frame 0+ colour: Colour+ curve: Optional[tuple[np.ndarray, np.ndarray]] = None # (seconds, dB): a gain drawn over the lane+ curve_label: str = ""+ spans: Sequence[tuple[float, float]] = () # shaded behind the level (where the voice talks)+++@dataclass+class Mark:+ t: float+ label: str = ""+ colour: Colour = (255, 206, 84)+ lanes: Optional[Sequence[str]] = None # None: across every lane+++@dataclass+class Zoom:+ t: float # the moment: the start of the frame an event lands on+ label: str+ lanes: Sequence[str] = ()+ onset: Optional[float] = None # where the sound was found to land, if measured+ before: float = 0.10+ after: float = 0.18+ note: str = ""+ frame: Optional[int] = None # the frame shown as "the moment" (default: the one starting at `t`)+++@dataclass+class Sheet:+ title: str+ duration: float+ fps: float+ frame_at: Callable[[float], np.ndarray]+ lanes: list[Lane]+ frames: Sequence[float] = ()+ marks: list[Mark] = field(default_factory=list)+ zooms: list[Zoom] = field(default_factory=list)+ lines: list[str] = field(default_factory=list)+++def _font(size: int, bold: bool = False):+ from PIL import ImageFont++ name = "Poppins-Bold.ttf" if bold else "Poppins-SemiBold.ttf"+ return ImageFont.truetype(str(FONTS / "Poppins" / name), size)+++def _tile(img: np.ndarray, h: int):+ from PIL import Image++ pic = Image.fromarray(img)+ return pic.resize((max(1, int(round(pic.width * h / pic.height))), h), Image.LANCZOS)+++def draw(sheet: Sheet, out: Path) -> Path:+ from PIL import Image, ImageDraw++ pad, label_w, tile_h = 24, 150, 520+ frames = list(sheet.frames)[:6]+ tiles = [(t, _tile(sheet.frame_at(t), tile_h)) for t in frames]+ tiles_w = sum(p.width for _, p in tiles) + 8 * max(0, len(tiles) - 1)+ width = max(1800, tiles_w + 2 * pad)+ lane_h, ruler_h = 120, 34+ zoom_w, zoom_h = 300, 330+ zooms = sheet.zooms[:12]+ per_row = max(1, (width - 2 * pad + 12) // (zoom_w + 12))+ zoom_rows = (len(zooms) + per_row - 1) // per_row+ head_h = 46 + 30 * len(sheet.lines)+ height = (head_h + tile_h + 44 + ruler_h + len(sheet.lanes) * (lane_h + 10) + 20+ + zoom_rows * (zoom_h + 14) + pad)+ img = Image.new("RGB", (width, height), BG)+ d = ImageDraw.Draw(img)+ f_title, f_text, f_small = _font(30, True), _font(21), _font(17)++ y = 14+ d.text((pad, y), sheet.title, fill=TEXT, font=f_title)+ y += 46+ for line in sheet.lines:+ d.text((pad, y), line, fill=DIM, font=f_text)+ y += 30++ # the six frames+ x = (width - tiles_w) // 2+ tile_x = []+ for t, pic in tiles:+ img.paste(pic, (x, y))+ d.rectangle([x, y + tile_h, x + pic.width, y + tile_h + 34], fill=PANEL)+ d.text((x + 10, y + tile_h + 6), f"{t:.2f} s", fill=TEXT, font=f_small)+ tile_x.append((t, x + pic.width / 2))+ x += pic.width + 8+ y += tile_h + 44++ # the time line+ x0, x1 = pad + label_w, width - pad+ span = max(sheet.duration, 1e-3)++ def tx(t: float) -> float:+ return x0 + (x1 - x0) * min(max(t, 0.0), span) / span++ ruler_y = y+ step = 1.0 if span <= 20 else 2.0 if span <= 45 else 5.0+ k = 0.0+ while k <= span + 1e-6:+ xx = tx(k)+ d.line([xx, ruler_y + 18, xx, ruler_y + ruler_h], fill=GRID, width=1)+ d.text((xx + 3, ruler_y), f"{k:g}s", fill=DIM, font=f_small)+ k += step+ for t, cx in tile_x: # where each frame above sits on the time line+ xx = tx(t)+ d.polygon([(xx - 7, ruler_y + 20), (xx + 7, ruler_y + 20), (xx, ruler_y + 32)], fill=TEXT)+ y = ruler_y + ruler_h++ lanes_top = y+ hop = 1.0 / max(1.0, (x1 - x0) / span) / 2 # two level steps a pixel+ for lane in sheet.lanes:+ top, bot = y, y + lane_h+ d.rectangle([x0, top, x1, bot], fill=PANEL)+ d.text((pad, top + 8), lane.name, fill=lane.colour, font=f_text)+ for a, b in lane.spans:+ d.rectangle([tx(a), top, tx(b), bot], fill=(44, 44, 52))+ for db_line in (-48, -36, -24, -12):+ yy = bot - (db_line + 60) / 60 * lane_h+ d.line([x0, yy, x1, yy], fill=GRID, width=1)+ if len(lane.samples):+ env = envelope_db(lane.samples, AUDIO_RATE, hop=max(0.002, hop))+ times = (np.arange(len(env)) + 0.5) * max(0.002, hop)+ cols = np.clip(((times / span) * (x1 - x0)).astype(int), 0, int(x1 - x0) - 1)+ top_db = np.full(int(x1 - x0), -120.0)+ np.maximum.at(top_db, cols, env)+ for c in range(len(top_db)):+ if top_db[c] <= -60:+ continue+ h = (min(0.0, top_db[c]) + 60) / 60 * lane_h+ d.line([x0 + c, bot, x0 + c, bot - h], fill=lane.colour, width=1)+ if lane.curve is not None:+ ts, gdb = lane.curve+ pts = [(tx(float(t)), top + 6 + (6.0 - min(6.0, max(-30.0, float(g)))) / 36.0 * (lane_h - 12))+ for t, g in zip(ts, gdb)]+ if len(pts) > 1:+ d.line(pts, fill=(255, 255, 255), width=2)+ if lane.curve_label:+ d.text((pad, top + 40), lane.curve_label, fill=DIM, font=f_small)+ y = bot + 10+ lanes_bot = y - 10++ for m in sheet.marks:+ xx = tx(m.t)+ if m.lanes is None:+ d.line([xx, lanes_top, xx, lanes_bot], fill=m.colour, width=2)+ else:+ yy = lanes_top+ for lane in sheet.lanes:+ if lane.name in m.lanes:+ d.line([xx, yy, xx, yy + lane_h], fill=m.colour, width=2)+ yy += lane_h + 10+ if m.label:+ d.text((xx + 4, lanes_bot - 22), m.label, fill=m.colour, font=f_small)+ y = lanes_bot + 20++ # close-ups at single-frame scale+ by_name = {lane.name: lane for lane in sheet.lanes}+ for n, z in enumerate(zooms):+ col, row = n % per_row, n // per_row+ zx, zy = pad + col * (zoom_w + 12), y + row * (zoom_h + 14)+ d.rectangle([zx, zy, zx + zoom_w, zy + zoom_h], fill=PANEL)+ th = 132+ j_at = int(round(z.t * sheet.fps)) if z.frame is None else int(z.frame)+ before = _tile(sheet.frame_at(max(0.0, (j_at - 1) / sheet.fps)), th)+ on = _tile(sheet.frame_at(j_at / sheet.fps), th)+ img.paste(before, (zx + 8, zy + 8))+ img.paste(on, (zx + 16 + before.width, zy + 8))+ d.rectangle([zx + 15 + before.width, zy + 7, zx + 16 + before.width + on.width, zy + 8 + th],+ outline=(255, 206, 84), width=2)+ tx_note = zx + 26 + before.width + on.width+ d.text((tx_note, zy + 10), f"frame {j_at - 1}", fill=DIM, font=f_small)+ d.text((tx_note, zy + 32), f"frame {j_at}", fill=(255, 206, 84), font=f_small)+ d.text((tx_note, zy + 54), "(the moment)", fill=DIM, font=f_small)+ wy0, wy1 = zy + th + 22, zy + zoom_h - 52+ wx0, wx1 = zx + 8, zx + zoom_w - 8+ t0, t1 = z.t - z.before, z.t + z.after++ def zx_of(t: float) -> float:+ return wx0 + (wx1 - wx0) * (t - t0) / (t1 - t0)++ j0 = int(np.floor(t0 * sheet.fps))+ while j0 / sheet.fps <= t1:+ xx = zx_of(j0 / sheet.fps)+ if wx0 <= xx <= wx1:+ d.line([xx, wy0, xx, wy1], fill=GRID, width=1)+ j0 += 1+ mid = (wy0 + wy1) / 2+ for name in z.lanes:+ lane = by_name.get(name)+ if lane is None or not len(lane.samples):+ continue+ s = lane.samples.mean(axis=1) if lane.samples.ndim == 2 else lane.samples+ a, b = max(0, int(t0 * AUDIO_RATE)), min(len(s), int(t1 * AUDIO_RATE))+ if b <= a:+ continue+ peak = max(1e-6, float(np.abs(s[a:b]).max()))+ cols = int(wx1 - wx0)+ edges = (np.linspace(t0, t1, cols + 1) * AUDIO_RATE).astype(int)+ for c in range(cols):+ ia, ib = max(0, edges[c]), min(len(s), max(edges[c] + 1, edges[c + 1]))+ if ib <= ia:+ continue+ part = s[ia:ib]+ lo, hi = float(part.min()) / peak, float(part.max()) / peak+ d.line([wx0 + c, mid - hi * (wy1 - wy0) / 2.1, wx0 + c, mid - lo * (wy1 - wy0) / 2.1], fill=lane.colour)+ xx = zx_of(z.t)+ d.line([xx, wy0 - 4, xx, wy1 + 4], fill=(255, 206, 84), width=2)+ if z.onset is not None:+ xo = zx_of(z.onset)+ d.line([xo, wy0, xo, wy1], fill=(120, 230, 160), width=2)+ d.text((zx + 8, wy1 + 6), z.label, fill=TEXT, font=f_small)+ if z.note:+ d.text((zx + 8, wy1 + 26), z.note, fill=DIM, font=f_small)+ out = Path(out)+ out.parent.mkdir(parents=True, exist_ok=True)+ img.save(out, quality=86)+ return outdiff --git a/edit/askeditor/fx/core/speakers.py b/edit/askeditor/fx/core/speakers.pynew file mode 100644index 0000000..1c1caf7--- /dev/null+++ b/edit/askeditor/fx/core/speakers.py@@ -0,0 +1,450 @@+"""Who is talking, when two people are in the picture: the one whose mouth moves with the sound.++1. **Every face, every frame.** The face landmark model finds up to four faces in each frame and+ where each mouth is. For each face it keeps a box (the same shape as `face.py`'s: cheek to+ cheek, forehead to chin), how open the jaw is, and how much the mouth itself changed since the+ last frame (the pixels of a patch fixed to the mouth, so a head turning does not count). Kept+ beside the clip as `<clip>.mouths.json`.+2. **Faces become people.** Each face is linked to the nearest face of the frame before; a person+ seen in too few frames (a passer-by) is dropped.+3. **The mouth that moves with the sound.** Over windows of six seconds, how far each person's+ mouth is open (the jaw, the gap between the lips and the area inside them) is compared with the+ loudness of the voice, and how much their mouth moves with the moments the voice starts. The+ sound and the picture of a recording are often a few frames apart, so that offset is found for+ the clip first: the one at which some mouth fits the sound best. Measured on two of+ our own takes (28 October 2026), with both people talking at once and one voice heard,+ the person whose voice it was fitted it better in 95% of six-second windows (86 to 93% with+ any one of the four signals alone, or with four-second windows). A listener whose mouth rests is+ easier than that.+4. **Turns, not flicker.** A window decides only when the voice is there and one person fits clearly+ better; turns shorter than two seconds are merged into their neighbours, and each change of+ speaker is moved to the nearest pause, so a cut lands between words.++When it cannot tell (both mouths fit the sound about as well, or nobody's does), it says so and the+caller follows the larger face.+"""++from __future__ import annotations++import json+import time+from dataclasses import dataclass, field+from pathlib import Path+from typing import Optional++import numpy as np++from . import audio, paths+from .face import quiet_native+from .layout import Rect+from .video import AUDIO_RATE, FrameReader, VideoInfo, mono, read_audio++CACHE_VERSION = 2+DETECT_WIDTH = 640+HOP = 0.5 # seconds between decisions+MAX_LAG = 0.35 # the most the sound and the picture are allowed to be apart, seconds+WINDOW = 6.0 # seconds a decision looks at+MARGIN = 0.08 # how much better one person must fit the sound for a window to decide+MIN_TURN = 2.0 # a turn shorter than this is merged into its neighbours+MIN_SHARE = 0.25 # a person must be in this share of frames to count+SNAP = 0.6 # a change of speaker moves to a pause up to this far away++# The mouth's inner edge, and the points that give the box (see the module's docstring).+INNER_UPPER, INNER_LOWER = 13, 14+INNER = [78, 95, 88, 178, 87, 14, 317, 402, 318, 324, 308, 415, 310, 311, 312, 13, 82, 81, 80, 191]+TOP, CHIN = 151, 152+++@dataclass+class Mouths:+ """Every face found in every frame: rows of [x0, y0, x1, y1, jaw, motion, gap, area], the box in+ clip pixels."""++ fps: float+ width: int+ height: int+ frames: list[list[list[float]]]+ seconds: float = 0.0+++@dataclass+class Person:+ boxes: list[Optional[Rect]] # per frame+ jaw: np.ndarray # per frame, NaN where not seen: how open the jaw is (the model's own estimate)+ motion: np.ndarray # how much the mouth's pixels changed since the frame before+ gap: np.ndarray # the gap between the lips, as a share of the face's height+ area: np.ndarray # the area inside the lips, as a share of the face's height squared++ @property+ def share(self) -> float:+ return float(np.mean([b is not None for b in self.boxes]))++ def width(self) -> float:+ ws = [b.w for b in self.boxes if b is not None]+ return float(np.median(ws)) if ws else 0.0++ def cx(self) -> float:+ xs = [b.cx for b in self.boxes if b is not None]+ return float(np.median(xs)) if xs else 0.0+++@dataclass+class Talk:+ """Who talks when: `who` per frame (an index into `people`), and how sure."""++ people: list[Person]+ who: np.ndarray+ switches: list[int] = field(default_factory=list)+ lag: float = 0.0 # seconds the sound is behind the picture+ decided: float = 0.0 # the share of voiced time a window could decide+ margin: float = 0.0 # how much better the speaker fitted, on average+ note: str = ""+ turns: list[dict] = field(default_factory=list)++ def boxes(self) -> list[Optional[Rect]]:+ """The speaker's face box in each frame (the other person's when the speaker is not seen)."""+ out = []+ for i, k in enumerate(self.who):+ b = self.people[int(k)].boxes[i]+ if b is None:+ b = next((p.boxes[i] for p in self.people if p.boxes[i] is not None), None)+ out.append(b)+ return out+++# ---- finding the faces and mouths ---------------------------------------------------------------++def find(info: VideoInfo) -> Mouths:+ """Run the landmark model on every frame (or read what an earlier run kept beside the clip)."""+ cache = paths.beside(info.path, "mouths.json")+ sig = paths.source_signature(info.path)+ if cache.exists():+ try:+ d = json.loads(cache.read_text(encoding="utf-8"))+ if d.get("version") == CACHE_VERSION and d.get("source", {}).get("bytes") == sig["bytes"] \+ and len(d.get("frames", [])) == info.frames:+ return Mouths(info.rate, info.width, info.height, d["frames"])+ except (json.JSONDecodeError, KeyError, TypeError, ValueError):+ pass+ import cv2++ from .models import vision_path++ with quiet_native():+ import mediapipe as mp+ from mediapipe.tasks import python as mp_tasks+ from mediapipe.tasks.python import vision++ dw = min(DETECT_WIDTH, info.width)+ dw -= dw % 2+ dh = int(round(info.height * dw / info.width / 2)) * 2+ s = info.width / dw+ started = time.time()+ frames: list[list[list[float]]] = []+ prev: list[tuple[float, float, np.ndarray]] = [] # (cx, cy, mouth patch) of the frame before+ with quiet_native():+ options = vision.FaceLandmarkerOptions(+ base_options=mp_tasks.BaseOptions(model_asset_path=str(vision_path("landmarks"))),+ running_mode=vision.RunningMode.VIDEO, num_faces=4, output_face_blendshapes=True,+ min_face_detection_confidence=0.4, min_face_presence_confidence=0.4, min_tracking_confidence=0.4)+ with vision.FaceLandmarker.create_from_options(options) as model:+ for i, f in enumerate(FrameReader(info, size=(dw, dh))):+ r = model.detect_for_video(mp.Image(image_format=mp.ImageFormat.SRGB, data=np.ascontiguousarray(f)),+ int(round(i * 1000 / info.rate)))+ gray = f.mean(axis=2).astype(np.float32)+ rows, now = [], []+ for k, pts in enumerate(r.face_landmarks):+ xs = np.array([p.x for p in pts]) * dw+ ys = np.array([p.y for p in pts]) * dh+ jaw = 0.0+ if r.face_blendshapes and k < len(r.face_blendshapes):+ jaw = next((c.score for c in r.face_blendshapes[k] if c.category_name == "jawOpen"), 0.0)+ fh = max(1.0, float(ys[CHIN] - ys[TOP]))+ mx = (xs[INNER_UPPER] + xs[INNER_LOWER]) / 2+ my = (ys[INNER_UPPER] + ys[INNER_LOWER]) / 2+ half = max(4, int(0.22 * fh))+ y0, y1 = int(my - half), int(my + half)+ x0, x1 = int(mx - 1.4 * half), int(mx + 1.4 * half)+ patch = gray[max(0, y0):max(1, y1), max(0, x0):max(1, x1)]+ if patch.size < 16:+ patch = np.zeros((32, 48), np.float32)+ patch = cv2.resize(patch, (48, 32), interpolation=cv2.INTER_AREA)+ patch = (patch - patch.mean()) / (patch.std() + 1e-6)+ near = min(prev, key=lambda q: (q[0] - mx) ** 2 + (q[1] - my) ** 2, default=None)+ motion = -1.0+ if near is not None and np.hypot(near[0] - mx, near[1] - my) < 0.5 * fh:+ motion = float(np.abs(patch - near[2]).mean())+ now.append((mx, my, patch))+ gap = float(np.hypot(xs[INNER_UPPER] - xs[INNER_LOWER], ys[INNER_UPPER] - ys[INNER_LOWER])) / fh+ px, py = xs[INNER], ys[INNER]+ area = 0.5 * abs(float(np.dot(px, np.roll(py, 1)) - np.dot(py, np.roll(px, 1)))) / fh ** 2+ rows.append([round(float(xs.min() * s), 1), round(float(ys[TOP] * s), 1),+ round(float(xs.max() * s), 1), round(float(ys[CHIN] * s), 1),+ round(float(jaw), 4), round(motion, 4), round(gap, 5), round(area, 6)])+ frames.append(rows)+ prev = now+ frames = (frames + [[] for _ in range(info.frames)])[:info.frames]+ m = Mouths(info.rate, info.width, info.height, frames, seconds=time.time() - started)+ tmp = Path(str(cache) + ".part")+ tmp.write_text(json.dumps({"version": CACHE_VERSION, "source": sig, "frames": frames}, separators=(",", ":")))+ tmp.replace(cache)+ return m+++def people(m: Mouths) -> list[Person]:+ """Faces linked frame to frame into people, the most-seen first; passers-by dropped."""+ n = len(m.frames)+ tracks: list[dict] = [] # each: last box, rows by frame+ for i, rows in enumerate(m.frames):+ free = list(range(len(rows)))+ # each live track takes the nearest face that is close enough+ for t in sorted(tracks, key=lambda t: -t["seen"]):+ if i - t["last_i"] > int(1.0 * m.fps) or not free:+ continue+ lx0, ly0, lx1, ly1 = t["last"]+ cx, cy, w = (lx0 + lx1) / 2, (ly0 + ly1) / 2, lx1 - lx0+ best = min(free, key=lambda k: np.hypot((rows[k][0] + rows[k][2]) / 2 - cx, (rows[k][1] + rows[k][3]) / 2 - cy))+ r = rows[best]+ if np.hypot((r[0] + r[2]) / 2 - cx, (r[1] + r[3]) / 2 - cy) < 0.6 * max(w, 1.0):+ t["rows"][i] = r+ t["last"], t["last_i"] = r[:4], i+ t["seen"] += 1+ free.remove(best)+ for k in free:+ tracks.append({"rows": {i: rows[k]}, "last": rows[k][:4], "last_i": i, "seen": 1})+ out = []+ for t in sorted(tracks, key=lambda t: -t["seen"]):+ if t["seen"] < MIN_SHARE * n:+ continue+ boxes: list[Optional[Rect]] = [None] * n+ jaw, motion, gap, area = (np.full(n, np.nan) for _ in range(4))+ for i, r in t["rows"].items():+ boxes[i] = Rect(r[0], r[1], r[2], r[3])+ jaw[i], gap[i], area[i] = r[4], r[6], r[7]+ motion[i] = r[5] if r[5] >= 0 else np.nan+ out.append(Person(boxes, jaw, motion, gap, area))+ return out+++# ---- who fits the sound -------------------------------------------------------------------------++def _corr(a: np.ndarray, b: np.ndarray) -> float:+ ok = ~np.isnan(a) & ~np.isnan(b)+ if ok.sum() < 0.7 * len(a):+ return np.nan+ a, b = a[ok] - a[ok].mean(), b[ok] - b[ok].mean()+ d = np.sqrt((a * a).sum() * (b * b).sum())+ return float((a * b).sum() / d) if d > 1e-12 else 0.0+++def _shift(x: np.ndarray, lag: int) -> np.ndarray:+ """x moved earlier by `lag` frames (x[t + lag] at t), NaN past the end."""+ out = np.full_like(x, np.nan)+ if lag >= 0:+ out[:len(x) - lag] = x[lag:]+ else:+ out[-lag:] = x[:len(x) + lag]+ return out+++def talk(info: VideoInfo, sound: np.ndarray, quiet: list[tuple[float, float]], who: list[Person]) -> Talk:+ """Who talks in each frame, of `who` (two or more people)."""+ n, fps = info.frames, info.rate+ env = audio.envelope(mono(sound, AUDIO_RATE, 16000), 16000)+ per = 1.0 / fps+ level = np.clip(np.array([env.mean(i * per, (i + 1) * per) for i in range(n)]) - env.floor, 0, None)+ onset = np.clip(np.diff(level, prepend=level[0]), 0, None)+ voiced = level > (env.threshold - env.floor)+ w, hop = int(round(WINDOW * fps)), max(1, int(round(HOP * fps)))+ starts = list(range(0, max(1, n - w + 1), hop))+ max_lag = int(round(MAX_LAG * fps))++ open_ = ("jaw", "gap", "area") # how open the mouth is, against how loud the voice is++ def fit(p: Person, s: int, lag_level: int, lag_onset: int) -> float:+ lv, on = shifted[("level", lag_level)], shifted[("onset", lag_onset)]+ cs = [_corr(getattr(p, f)[s:s + w], lv[s:s + w]) for f in open_]+ cs.append(_corr(p.motion[s:s + w], on[s:s + w]))+ cs = [c for c in cs if not np.isnan(c)]+ return float(np.mean(cs)) if cs else np.nan++ shifted = {(name, lag): _shift(x, lag) for name, x in (("level", level), ("onset", onset))+ for lag in range(-max_lag, max_lag + 1)}++ # The offset between sound and picture: the one at which the people differ most in how well+ # they fit the sound, window by window (at a wrong offset every mouth fits about equally badly).+ # Found for openness and for movement separately: they peak frames apart.+ def best_lag(feature: str) -> int:+ best, best_v = 0, -np.inf+ for lag in range(-max_lag, max_lag + 1):+ x = shifted[("level" if feature == "level" else "onset", lag)]+ vals = []+ for s in starts:+ if voiced[s:s + w].mean() < 0.3:+ continue+ if feature == "level":+ cs = [np.nanmean([_corr(getattr(p, f)[s:s + w], x[s:s + w]) for f in open_]) for p in who]+ else:+ cs = [_corr(p.motion[s:s + w], x[s:s + w]) for p in who]+ cs = sorted((c for c in cs if not np.isnan(c)), reverse=True)+ if len(cs) >= 2:+ vals.append(cs[0] - cs[1])+ v = float(np.mean(vals)) if vals else -np.inf+ if v > best_v:+ best, best_v = lag, v+ return best++ lag_level, lag_onset = best_lag("level"), best_lag("onset")+ # Each window of six seconds: the person who fits the sound clearly best, while the voice is+ # there; else undecided.+ pick = np.full(len(starts), -1)+ margins = []+ for j, s in enumerate(starts):+ if voiced[s:s + w].mean() < 0.3:+ continue+ col = np.array([fit(p, s, lag_level, lag_onset) for p in who])+ if np.all(np.isnan(col)):+ continue+ order = np.argsort(-np.nan_to_num(col, nan=-9))+ top = col[order[0]]+ second = col[order[1]] if len(order) > 1 and not np.isnan(col[order[1]]) else -1.0+ if top - second >= MARGIN and top > 0.05:+ pick[j] = order[0]+ margins.append(top - second)+ decided = float(np.mean(pick >= 0)) if len(pick) else 0.0+ margin = float(np.mean(margins)) if margins else 0.0+ largest = int(np.argmax([p.width() * p.share for p in who]))+ if not margins:+ return Talk(who, np.full(n, largest), [], lag_level / fps, 0.0, 0.0,+ "could not tell who is talking from the mouths and the sound; following the larger face")+ filled = pick.copy()+ last = next((k for k in pick if k >= 0), largest)+ for j in range(len(filled)):+ if filled[j] < 0:+ filled[j] = last+ else:+ last = filled[j]+ centres = np.array([s + w / 2 for s in starts])+ frames_who = np.array([filled[int(np.argmin(np.abs(centres - i)))] for i in range(n)])+ frames_who = _merge_short(frames_who, int(round(MIN_TURN * fps)))+ # A window of six seconds knows who talked, but only roughly when the turn changed. Each change+ # is placed where the evidence changes sides: frame by frame, how well each mouth agrees with+ # the sound, summed from the turn before up to a point and from there to the turn after.+ agree = np.stack([_agreement(p, shifted[("level", lag_level)], shifted[("onset", lag_onset)], voiced, fps)+ for p in who])+ frames_who = _place_changes(frames_who, agree, int(round(WINDOW * fps / 2)))+ switches = [i for i in range(1, n) if frames_who[i] != frames_who[i - 1]]+ snapped = []+ for sw in switches: # each change of speaker on the nearest pause+ t = sw / fps+ best = None+ for q0, q1 in quiet:+ mid = (q0 + q1) / 2+ if abs(mid - t) <= SNAP and (best is None or abs(mid - t) < abs(best - t)):+ best = mid+ snapped.append(int(round((best if best is not None else t) * fps)))+ out = frames_who.copy()+ for old, new in zip(switches, snapped):+ if new > old: # the previous speaker keeps the frames up to the pause+ out[old:new] = frames_who[old - 1]+ elif new < old: # the next speaker takes them from the pause+ out[new:old] = frames_who[old]+ switches = [i for i in range(1, n) if out[i] != out[i - 1]]+ turns = []+ edges = [0] + switches + [n]+ for a, b in zip(edges, edges[1:]):+ turns.append({"from_s": round(a / fps, 2), "to_s": round(b / fps, 2), "person": int(out[a]) + 1})+ note = (f"followed whoever is talking: {len(turns)} turn{'s' if len(turns) != 1 else ''}, "+ f"decided in {decided:.0%} of voiced windows")+ return Talk(who, out, switches, lag_level / fps, decided, margin, note, turns)+++def _z(x: np.ndarray, span: int) -> np.ndarray:+ """x less its local mean, over its local spread (both over `span` frames either side), NaN kept."""+ out = np.full(len(x), np.nan)+ for i in range(len(x)):+ seg = x[max(0, i - span):i + span + 1]+ seg = seg[~np.isnan(seg)]+ if len(seg) > 5 and not np.isnan(x[i]):+ sd = seg.std()+ out[i] = (x[i] - seg.mean()) / sd if sd > 1e-9 else 0.0+ return out+++def _agreement(p: Person, level: np.ndarray, onset: np.ndarray, voiced: np.ndarray, fps: float) -> np.ndarray:+ """Per frame, how well this mouth agrees with the sound: the products of their deviations, the+ same terms a correlation adds up, averaged over the four signals; 0 where nobody speaks."""+ span = int(round(3 * fps))+ zl, zo = _z(level, span), _z(onset, span)+ terms = [_z(getattr(p, f), span) * zl for f in ("jaw", "gap", "area")] + [_z(p.motion, span) * zo]+ with np.errstate(all="ignore"):+ a = np.nanmean(np.stack(terms), axis=0)+ a = np.nan_to_num(a, nan=0.0)+ return np.where(voiced, a, 0.0)+++def _place_changes(who: np.ndarray, agree: np.ndarray, reach: int) -> np.ndarray:+ """Each change of speaker moved to the frame, within `reach` of where it was, that best splits+ the evidence: the frames before favouring the speaker before, the frames after the one after."""+ out = who.copy()+ changes = [i for i in range(1, len(who)) if who[i] != who[i - 1]]+ for k, c in enumerate(changes):+ a, b = int(who[c - 1]), int(who[c])+ lo = max(changes[k - 1] + 1 if k > 0 else 1, c - reach)+ hi = min(changes[k + 1] - 1 if k + 1 < len(changes) else len(who) - 1, c + reach)+ if hi <= lo:+ continue+ seg = agree[a][lo:hi] - agree[b][lo:hi] # positive where the earlier speaker fits better+ before = np.concatenate([[0.0], np.cumsum(seg)])+ gain = before - (before[-1] - before)+ s = lo + int(np.argmax(gain))+ out[lo:s] = a+ out[s:hi] = b+ return out+++def _gauss(x: np.ndarray, sigma: float) -> np.ndarray:+ if sigma <= 0 or len(x) < 3:+ return x.copy()+ r = max(1, int(3 * sigma))+ k = np.exp(-0.5 * (np.arange(-r, r + 1) / sigma) ** 2)+ k /= k.sum()+ return np.convolve(np.pad(x, (r, r), mode="edge"), k, mode="valid")+++def _best_order(evidence: np.ndarray, cost: float) -> np.ndarray:+ """The speaker in each frame that collects the most evidence, paying `cost` for each change."""+ k, n = evidence.shape+ score = evidence[:, 0].copy()+ back = np.zeros((k, n), int)+ for t in range(1, n):+ stay = score+ move = score.max() - cost+ src = np.where(stay >= move, np.arange(k), int(np.argmax(score)))+ score = np.maximum(stay, move) + evidence[:, t]+ back[:, t] = src+ out = np.zeros(n, int)+ out[-1] = int(np.argmax(score))+ for t in range(n - 1, 0, -1):+ out[t - 1] = back[out[t], t]+ return out+++def _merge_short(who: np.ndarray, least: int) -> np.ndarray:+ """Turns shorter than `least` frames given to the longer neighbour, until none is left."""+ who = who.copy()+ for _ in range(20):+ edges = [0] + [i for i in range(1, len(who)) if who[i] != who[i - 1]] + [len(who)]+ runs = [(a, b) for a, b in zip(edges, edges[1:])]+ short = [(b - a, k) for k, (a, b) in enumerate(runs) if b - a < least and len(runs) > 1]+ if not short:+ break+ _, k = min(short)+ a, b = runs[k]+ left = runs[k - 1] if k > 0 else None+ right = runs[k + 1] if k + 1 < len(runs) else None+ if left is None or (right is not None and right[1] - right[0] > left[1] - left[0]):+ who[a:b] = who[right[0]]+ else:+ who[a:b] = who[left[0]]+ return whodiff --git a/edit/askeditor/fx/core/synth.py b/edit/askeditor/fx/core/synth.pynew file mode 100644index 0000000..fda6445--- /dev/null+++ b/edit/askeditor/fx/core/synth.py@@ -0,0 +1,333 @@+"""Sounds made in code at the moment an effect needs them, shaped to its own timing.++The library in `sounds/` holds fixed one-shots (a whoosh, a pop). Some sounds cannot be fixed files:+a neon tube's hum has to switch on and off with the flicker of its own letters, and a sign that+types out ticks once per letter. Those are made here, from noise and sine waves, every time the same+for the same timing (fixed seeds), with no recording or sample from anywhere.++- `clunk()`: a heavy light switch thrown, the lights going out: a lever's first click, the contact+ slamming home with a low knock in the box behind it, a short metal ring and a rattle.+- `scratch()`: a record dragged back under the needle and stopped: music played at a speed that+ falls through nothing to backwards and then dies, with the groove's noise growing as it is dragged.+- `tube(lit)`: a neon sign's sound from how lit it is at each sample (0 to 1): the mains buzz of its+ transformer and the hiss of the gas while it is on, and apart from it a crackle wherever a tube+ strikes on.+- `tick()`: one letter of a dot-matrix sign: a small, dry electronic tick.+- `shimmer()`: light arriving: a soft, high, golden chord with a sprinkle of tiny pings.+- `slap(weight)`: a sticker slapped onto glass or a rubber stamp brought down: a flat smack of+ air and skin, a low thud under it (heavier with `weight`), and a tiny paper rustle after.+- `paper()`: a card or a cutting laid down: a soft slide of paper over a desk that ends on a light tap.+- `beep()`: a camcorder starting to record: two short, clean high tones, the second a step higher.+- `whirr(seconds)`: a tape deck running, as a bed: the motor's low hum wavering with its flutter, the+ heads' soft hiss, and a light mechanical clunk at the start as it begins to play.+- `projector(seconds)`: a film projector running, as a bed: the shutter's quick soft clatter, the+ motor's hum and a faint, uneven rattle of the reel.+- `printer(seconds)`: a small receipt printer printing one line: the print head's fast, dry chatter+ over a little motor whine as the paper feeds, ending on the soft stop of the feed.++The one-shots return float32 (n, 2) at 48 kHz and the second the sound lands at (its anchor).+`at_level()` sets a sound's loudest tenth of a second against a loudness, as the library's sounds+are set (`sound.loudest`).+"""++from __future__ import annotations++import numpy as np++from .sound import gain, loudest++RATE = 48000+++def times(seconds: float) -> np.ndarray:+ return np.arange(int(round(seconds * RATE))) / RATE+++def _rng(seed: int) -> np.random.Generator:+ return np.random.default_rng(seed)+++def band(x: np.ndarray, lo: float, hi: float, soft: float = 0.3) -> np.ndarray:+ """`x` (mono) kept between `lo` and `hi` Hz, with edges `soft` octaves wide (no ringing)."""+ n = len(x)+ if n == 0:+ return x+ spec = np.fft.rfft(x)+ f = np.maximum(np.fft.rfftfreq(n, 1.0 / RATE), 1.0)+ lf = np.log2(f)+ up = np.clip((lf - (np.log2(lo) - soft / 2)) / soft, 0, 1)+ down = np.clip(((np.log2(hi) + soft / 2) - lf) / soft, 0, 1)+ mask = (up * up * (3 - 2 * up)) * (down * down * (3 - 2 * down))+ return np.fft.irfft(spec * mask, n)+++def snap(n: int, decay: float, seed: int) -> np.ndarray:+ """A very short, bright burst (the tick at the front of anything struck), `decay` seconds long."""+ t = np.arange(n) / RATE+ x = np.diff(_rng(seed).standard_normal(n + 1))+ return x * np.exp(-t / max(decay, 1e-5)) * 0.5+++def ring(t: np.ndarray, hz: float, decay: float, end_hz: float | None = None, glide: float = 0.03) -> np.ndarray:+ """A sine that dies away over `decay` seconds, bending from `hz` to `end_hz` over `glide`."""+ f = np.full(len(t), float(hz)) if end_hz is None else end_hz + (hz - end_hz) * np.exp(-t / glide)+ return np.sin(2 * np.pi * np.cumsum(f) / RATE) * np.exp(-t / decay)+++def _at(out: np.ndarray, x: np.ndarray, start: float) -> None:+ a = int(round(start * RATE))+ b = min(len(out), a + len(x))+ if b > a:+ out[a:b] += x[: b - a]+++def _stereo(mono: np.ndarray, width: float = 0.0, seed: int = 0) -> np.ndarray:+ """Centre, or a touch wide: each side a hair apart in time (never more than half a millisecond)."""+ if width <= 0:+ return np.stack([mono, mono], axis=1).astype(np.float32)+ d = int(round(width * 0.0005 * RATE))+ left = mono+ right = np.concatenate([np.zeros(d), mono[: len(mono) - d]]) if d else mono+ return np.stack([left, right], axis=1).astype(np.float32)+++def _peak(x: np.ndarray, to: float = 0.89) -> np.ndarray:+ return x * (to / max(1e-9, float(np.abs(x).max())))+++# ---- the sounds ------------------------------------------------------------------------------------++def clunk(seed: int = 11) -> tuple[np.ndarray, float]:+ """A heavy switch thrown: the lever's first click, then the contact slamming home 28 ms later+ (the anchor: the moment the lights go), with a low knock, a short ring of the metal box and a+ last small rattle."""+ t = times(0.42)+ out = np.zeros(len(t))+ hit = 0.028+ _at(out, 0.30 * snap(len(t), 0.0011, seed), 0.0)+ u = t[: len(t) - int(hit * RATE)]+ knock = 0.95 * ring(u, 210.0, 0.034, end_hz=150.0, glide=0.02) + 0.55 * ring(u, 72.0, 0.075)+ metal = (0.22 * ring(u, 1380.0, 0.045) + 0.15 * ring(u, 2930.0, 0.03) + 0.10 * ring(u, 4470.0, 0.022)+ + 0.06 * ring(u, 6120.0, 0.016))+ grit = band(_rng(seed + 1).standard_normal(len(u)), 500.0, 3200.0) * np.exp(-u / 0.018) * 0.55+ _at(out, np.tanh(1.6 * (knock + metal + grit)) + snap(len(u), 0.0018, seed + 2), hit)+ _at(out, 0.12 * snap(len(t), 0.0009, seed + 3) + 0.05 * ring(t, 1650.0, 0.02), hit + 0.047)+ out *= np.clip((t[-1] - t) / 0.04, 0, 1)+ return _stereo(_peak(out), width=0.4), hit+++def _music(seconds: float, seed: int) -> np.ndarray:+ """A few seconds of something that sounds like a record playing: a chord with a beat under it and+ the groove's hiss, rich in overtones so a change of speed is heard as a change of pitch."""+ t = times(seconds)+ chord = np.zeros(len(t))+ for hz, amp in ((130.8, 1.0), (155.6, 0.8), (196.0, 0.8), (261.6, 0.55), (311.1, 0.4)):+ for k in range(1, 16):+ if hz * k > 9000:+ break+ chord += amp * np.sin(2 * np.pi * hz * k * t + 0.7 * k) / k+ pulse = np.zeros(len(t))+ for beat in np.arange(0.0, seconds, 0.25):+ u = t - beat+ on = u >= 0+ pulse[on] += np.sin(2 * np.pi * 55 * u[on] * (1 + 2.5 * np.exp(-u[on] / 0.02))) * np.exp(-u[on] / 0.09)+ hiss = band(_rng(seed).standard_normal(len(t)), 2500.0, 11000.0) * 0.18+ return 0.35 * chord / np.abs(chord).max() + 0.6 * pulse + hiss+++def scratch(seed: int = 23) -> tuple[np.ndarray, float]:+ """A record dragged back and stopped: the music slows from its own speed through nothing to+ backwards and dies, the groove's noise rising with how hard it is dragged. It lands (its anchor)+ on its first instant: the moment the record is caught."""+ src = _music(1.6, seed)+ t = times(0.46)+ # The record's speed: caught (1 to 0 in 40 ms), dragged back hard (to -3.2), let go to a stop.+ v = np.interp(t, [0.0, 0.04, 0.075, 0.13, 0.22, 0.34, 0.46], [1.0, 0.0, -3.2, -2.6, -0.8, -0.05, 0.0])+ v = np.convolve(v, np.ones(96) / 96, mode="same")+ pos = 1.1 * RATE + np.cumsum(v)+ i0 = np.clip(np.floor(pos).astype(int), 0, len(src) - 2)+ frac = pos - np.floor(pos)+ played = src[i0] * (1 - frac) + src[i0 + 1] * frac+ speed = np.abs(v)+ groove = band(_rng(seed + 1).standard_normal(len(t)), 900.0, 7000.0) * np.clip(speed / 3.0, 0, 1) ** 1.5+ out = played * np.clip(speed, 0, 1.6) ** 0.8 + 0.55 * groove+ out *= np.clip((t[-1] - t) / 0.03, 0, 1)+ return _stereo(_peak(np.tanh(1.3 * out)), width=0.6), 0.0+++def tube(lit: np.ndarray, strikes: list[int] | None = None, mains: float = 120.0,+ seed: int = 31) -> tuple[np.ndarray, np.ndarray]:+ """A neon sign's sound, sample by sample, from `lit` (0 to 1 at 48 kHz: how lit the sign is):+ its hum, the transformer's buzz (the mains frequency and its overtones, slightly rough) and the+ gas's hiss while it is on; and apart from it, a crackle at each sample in `strikes` (where a+ tube strikes on; by default wherever `lit` rises through a half). Both mono, so each can be set+ at its own level."""+ n = len(lit)+ t = np.arange(n) / RATE+ rng = _rng(seed)+ wobble = 1.0 + 0.002 * np.sin(2 * np.pi * 0.7 * t)+ phase = 2 * np.pi * mains * np.cumsum(wobble) / RATE+ buzz = np.zeros(n)+ for k in range(1, 22):+ amp = (1.0 / k ** 1.4) * (1.5 if k % 2 == 0 else 1.0)+ buzz += amp * np.sin(k * phase + 0.4 * k)+ buzz = np.tanh(1.4 * buzz / max(1e-9, float(np.abs(buzz).max())))+ hiss = band(rng.standard_normal(n), 3000.0, 12000.0) * 0.05+ level = np.convolve(np.clip(lit, 0, 1), np.ones(48) / 48, mode="same") # 1 ms: no clicks+ hum = (0.5 * buzz + hiss) * level+ if strikes is None:+ strikes = list(np.flatnonzero(np.diff(np.concatenate([[0.0], (lit > 0.5).astype(float)])) > 0))+ crackle = np.zeros(n)+ for k, i in enumerate(strikes):+ m = int(RATE * rng.uniform(0.012, 0.03))+ u = np.arange(m) / RATE+ fizz = band(rng.standard_normal(m), 1800.0, 9000.0) * np.exp(-u / (m / RATE / 3))+ fizz = 0.5 * fizz / max(1e-9, float(np.abs(fizz).max()))+ piece = fizz + 0.7 * snap(m, 0.0012, seed + 7 * k + 1)+ crackle[i:i + m] += piece[: max(0, min(m, n - i))]+ return hum.astype(np.float32), (0.9 * np.tanh(crackle / 0.9)).astype(np.float32)+++def tick(seed: int = 41) -> tuple[np.ndarray, float]:+ """One letter of a dot-matrix sign typing: a small, dry tick with a faint electronic blip."""+ t = times(0.05)+ x = 0.8 * ring(t, 3600.0, 0.0018) + 0.4 * ring(t, 1250.0, 0.004) + 0.3 * snap(len(t), 0.0006, seed)+ return _stereo(_peak(x, 0.7)), 0.0+++def shimmer(seed: int = 53) -> tuple[np.ndarray, float]:+ """Light arriving: a soft high chord that swells in over a tenth of a second and rings away, with+ tiny pings scattered through it. It lands (its anchor) at the top of its swell."""+ t = times(1.8)+ rng = _rng(seed)+ swell = np.clip(t / 0.11, 0, 1) ** 1.5+ x = np.zeros(len(t))+ for hz, amp, decay in ((1567.98, 0.7, 0.9), (1975.53, 0.55, 0.8), (2349.32, 0.5, 0.7), (3135.96, 0.35, 0.5),+ (3951.07, 0.22, 0.4), (4698.64, 0.15, 0.3)):+ shake = 1.0 + 0.003 * np.sin(2 * np.pi * rng.uniform(4, 7) * t)+ x += amp * np.sin(2 * np.pi * hz * np.cumsum(shake) / RATE) * np.exp(-t / decay)+ x *= swell+ for _ in range(22):+ at = rng.uniform(0.03, 1.0)+ u = t[: int(0.12 * RATE)]+ _at(x, 0.10 * ring(u, rng.uniform(5200, 9800), rng.uniform(0.01, 0.03)), at)+ x *= np.clip((t[-1] - t) / 0.2, 0, 1)+ return _stereo(_peak(x), width=0.8), 0.11+++def slap(weight: float = 0.5, seed: int = 61) -> tuple[np.ndarray, float]:+ """A sticker slapped on, or a rubber stamp brought down (`weight` 0 to 1: a light sticker to a+ heavy stamp): a flat smack of noise in the middle of the range, a low thud whose pitch falls,+ and a tiny rustle of paper after it. It lands (its anchor) on the smack, a hair after the start."""+ t = times(0.32)+ rng = _rng(seed)+ hit = 0.004+ out = np.zeros(len(t))+ u = t[: len(t) - int(hit * RATE)]+ smack = band(rng.standard_normal(len(u)), 700.0, 5200.0) * np.exp(-u / (0.010 + 0.006 * weight))+ thud = (0.55 + 0.6 * weight) * ring(u, 150.0 - 50.0 * weight, 0.045 + 0.04 * weight, end_hz=70.0, glide=0.025)+ _at(out, np.tanh(2.2 * smack + thud) + 0.4 * snap(len(u), 0.0009, seed + 1), hit)+ rustle = band(rng.standard_normal(len(t)), 2500.0, 9000.0) * np.exp(-((t - 0.05) / 0.03) ** 2) * 0.10+ out += rustle+ out[: int(hit * RATE)] *= np.linspace(0, 1, int(hit * RATE))+ out *= np.clip((t[-1] - t) / 0.05, 0, 1)+ return _stereo(_peak(out), width=0.3), hit+++def paper(seed: int = 67) -> tuple[np.ndarray, float]:+ """A card or a cutting laid down: paper sliding over a desk for a fifth of a second, its hiss+ rising and brightening, ending on a light tap (the anchor) as it comes to rest."""+ t = times(0.42)+ rng = _rng(seed)+ slide_end = 0.22+ grow = np.clip(t / slide_end, 0, 1) ** 1.6 * (t < slide_end)+ hiss = band(rng.standard_normal(len(t)), 1800.0, 7000.0) * grow * 0.55+ grain = band(rng.standard_normal(len(t)), 300.0, 1200.0) * grow * 0.25+ out = hiss + grain+ u = t[: len(t) - int(slide_end * RATE)]+ tap = 0.7 * ring(u, 420.0, 0.012, end_hz=260.0, glide=0.01) + 0.45 * snap(len(u), 0.0012, seed + 1)+ tap += band(rng.standard_normal(len(u)), 1500.0, 6000.0) * np.exp(-u / 0.02) * 0.25+ _at(out, tap, slide_end)+ out *= np.clip((t[-1] - t) / 0.05, 0, 1)+ return _stereo(_peak(out, 0.8), width=0.5), slide_end+++def beep(seed: int = 71) -> tuple[np.ndarray, float]:+ """A camcorder starting to record: two short high tones (the anchor is the first one's start)."""+ t = times(0.26)+ out = np.zeros(len(t))+ for start, hz in ((0.0, 2093.0), (0.11, 2637.0)):+ u = times(0.075)+ env = np.clip(u / 0.004, 0, 1) * np.clip((u[-1] - u) / 0.008, 0, 1)+ tone = np.sin(2 * np.pi * hz * u) + 0.12 * np.sin(2 * np.pi * 2 * hz * u)+ _at(out, tone * env, start)+ return _stereo(_peak(out, 0.7)), 0.0+++def whirr(seconds: float, seed: int = 73) -> np.ndarray:+ """A tape deck running, `seconds` long: a wavering motor hum, the heads' hiss and a soft clunk as+ it starts to play. A bed: it starts and ends with short fades, and is meant to sit far under a voice."""+ t = times(seconds)+ rng = _rng(seed)+ flutter = 1.0 + 0.012 * np.sin(2 * np.pi * 5.7 * t) + 0.006 * np.sin(2 * np.pi * 0.9 * t + 1.3)+ phase = 2 * np.pi * np.cumsum(np.full(len(t), 100.0) * flutter) / RATE+ hum = 0.5 * np.sin(phase) + 0.25 * np.sin(2 * phase + 0.4) + 0.12 * np.sin(3 * phase + 1.1)+ hiss = band(rng.standard_normal(len(t)), 3000.0, 12000.0) * 0.35+ rumble = band(rng.standard_normal(len(t)), 40.0, 220.0) * 0.6 * (0.8 + 0.2 * np.sin(2 * np.pi * 1.4 * t))+ out = 0.35 * hum + hiss + rumble+ knock, _ = clunk(seed + 1)+ k = knock[:, 0] * 0.6+ out[: min(len(out), len(k))] += k[: min(len(out), len(k))]+ fade = np.clip(t / 0.15, 0, 1) * np.clip((t[-1] - t) / 0.3, 0, 1) if len(t) else t+ return _stereo(_peak(out * fade, 0.6), width=0.6)+++def projector(seconds: float, seed: int = 79) -> np.ndarray:+ """A film projector running, `seconds` long: the shutter's soft clatter 24 times a second, the+ motor's hum and a faint uneven rattle of the reel. A bed, faded in and out."""+ t = times(seconds)+ rng = _rng(seed)+ out = np.zeros(len(t))+ click = band(rng.standard_normal(int(0.012 * RATE)), 600.0, 5000.0) * np.exp(-np.arange(int(0.012 * RATE)) / (0.0025 * RATE))+ step = 1.0 / 24.0+ for k, at in enumerate(np.arange(0.0, seconds, step)):+ at = at + 0.0015 * rng.standard_normal()+ _at(out, click * (0.55 + 0.25 * rng.random()) * (1.0 if k % 2 else 0.7), max(0.0, at))+ hum = 0.20 * np.sin(2 * np.pi * 50.0 * t) + 0.08 * np.sin(2 * np.pi * 150.0 * t)+ rattle = band(rng.standard_normal(len(t)), 150.0, 900.0) * 0.18 * (0.5 + 0.5 * np.sin(2 * np.pi * 0.8 * t) ** 2)+ out = out + hum + rattle+ fade = np.clip(t / 0.25, 0, 1) * np.clip((t[-1] - t) / 0.3, 0, 1) if len(t) else t+ return _stereo(_peak(out * fade, 0.6), width=0.5)+++def printer(seconds: float = 0.22, seed: int = 71) -> tuple[np.ndarray, float]:+ """One line of a receipt printer: the head's chatter (dry clicks at about 190 a second, each a+ little different, rising and falling in strength as the line crosses the paper) over a faint+ feed-motor whine, then the feed's soft stop. It lands (its anchor) where the line is done."""+ rng = _rng(seed)+ T = seconds + 0.09+ t = times(T)+ out = np.zeros(len(t))+ rate = rng.uniform(175.0, 205.0)+ k = 0+ while k / rate < seconds:+ at = k / rate + rng.uniform(-0.0006, 0.0006)+ q = (k / rate) / max(1e-6, seconds)+ level = (0.55 + 0.45 * np.sin(np.pi * min(1.0, q))) * rng.uniform(0.7, 1.0)+ u = t[: int(0.006 * RATE)]+ click = 0.7 * ring(u, rng.uniform(3000.0, 3800.0), 0.0007) + 0.5 * snap(len(u), 0.0005, seed + k)+ _at(out, level * click, max(0.0, at))+ k += 1+ feed = t < seconds + 0.02+ whine = (0.05 * np.sin(2 * np.pi * 930.0 * t) + 0.03 * np.sin(2 * np.pi * 1860.0 * t)) * feed+ whine *= np.clip(t / 0.015, 0, 1) * np.clip((seconds + 0.02 - t) / 0.015, 0, 1)+ out += whine + band(rng.standard_normal(len(t)), 2000.0, 7000.0) * 0.04 * feed+ u = t[: len(t) - int(seconds * RATE)]+ _at(out, 0.35 * ring(u, 310.0, 0.010, end_hz=220.0, glide=0.008) + 0.2 * snap(len(u), 0.0008, seed + 999), seconds)+ out *= np.clip((t[-1] - t) / 0.03, 0, 1)+ return _stereo(_peak(out, 0.8), width=0.3), seconds+++def at_level(x: np.ndarray, lufs: float) -> np.ndarray:+ """`x` set so its loudest tenth of a second measures `lufs`."""+ return (x * gain(lufs - loudest(np.asarray(x, np.float32)))).astype(np.float32)diff --git a/edit/askeditor/fx/core/text.py b/edit/askeditor/fx/core/text.pynew file mode 100644index 0000000..a030e3c--- /dev/null+++ b/edit/askeditor/fx/core/text.py@@ -0,0 +1,171 @@+"""Fonts and drawing words.++Every face comes from the pack's own `fonts/` folder (OFL licensed, licences beside each). A face+that is missing stops the render with a plain message: it is never swapped for whatever the+computer has, because a fallback face looks right only on the machine that happens to have the+real one installed.+"""++from __future__ import annotations++from dataclasses import dataclass+from functools import lru_cache+from pathlib import Path+from typing import Optional++import numpy as np++from .compose import Sprite+from .paths import FONTS, NeedSetup++FACES = {+ "anton": "Anton/Anton-Regular.ttf",+ "poppins-semibold": "Poppins/Poppins-SemiBold.ttf",+ "poppins-bold": "Poppins/Poppins-Bold.ttf",+ "poppins-extrabold": "Poppins/Poppins-ExtraBold.ttf",+ "poppins-black": "Poppins/Poppins-Black.ttf",+ "dm-serif": "DMSerifDisplay/DMSerifDisplay-Regular.ttf",+ "dm-serif-italic": "DMSerifDisplay/DMSerifDisplay-Italic.ttf",+ "instrument-serif": "InstrumentSerif/InstrumentSerif-Regular.ttf",+ "instrument-serif-italic": "InstrumentSerif/InstrumentSerif-Italic.ttf",+ "caveat-brush": "CaveatBrush/CaveatBrush-Regular.ttf", # handwriting in marker: labels drawn on a picture+ "vt323": "VT323/VT323-Regular.ttf", # a screen's own lettering: a camcorder's or a tape deck's readout+ "plex-mono": "IBMPlexMono/IBMPlexMono-Medium.ttf", # one width for every letter: a receipt, a count+ "plex-mono-bold": "IBMPlexMono/IBMPlexMono-Bold.ttf",+}+++# [LumReels] Vietnamese: Poppins has no Vietnamese letters (ơ, ư, ạ, ằ…), so with FX_LANG=vi its+# faces are drawn in Be Vietnam Pro (OFL), which `node edit/setup.mjs` builds into+# fonts/BeVietnamPro/ from LumReels' own font files.+import os as _os++if _os.environ.get("FX_LANG", "").strip().lower() == "vi":+ FACES.update({+ "poppins-semibold": "BeVietnamPro/BeVietnamPro-600.ttf",+ "poppins-bold": "BeVietnamPro/BeVietnamPro-700.ttf",+ "poppins-extrabold": "BeVietnamPro/BeVietnamPro-800.ttf",+ "poppins-black": "BeVietnamPro/BeVietnamPro-800.ttf",+ })+++def face_path(name: str) -> Path:+ if name not in FACES:+ raise ValueError(f"unknown face {name!r}")+ path = FONTS / FACES[name]+ if not path.exists():+ raise NeedSetup(f"the font {FACES[name]} is missing from the pack's fonts folder; get the pack again")+ return path+++@lru_cache(maxsize=256)+def font(name: str, px: int):+ from PIL import ImageFont++ return ImageFont.truetype(str(face_path(name)), max(4, int(px)))+++@lru_cache(maxsize=64)+def cap_height(name: str, px: int) -> float:+ """How tall a capital H stands in this face at this size, in pixels."""+ l, t, r, b = font(name, px).getbbox("H", anchor="ls")+ return float(-t)+++def advance(text: str, name: str, px: int) -> float:+ """How far the pen moves for `text`: the width to lay the next word after."""+ return float(font(name, px).getlength(text))+++def ink(text: str, name: str, px: int) -> tuple[float, float, float, float]:+ """The ink's box (left, top, right, bottom) relative to the start of the baseline."""+ l, t, r, b = font(name, px).getbbox(text, anchor="ls")+ return float(l), float(t), float(r), float(b)+++def fit_px(text: str, name: str, width: float, lo: int = 6, hi: int = 1200) -> int:+ """The largest size at which `text` is at most `width` pixels across."""+ while lo < hi:+ mid = (lo + hi + 1) // 2+ if advance(text, name, mid) <= width:+ lo = mid+ else:+ hi = mid - 1+ return lo+++@dataclass+class Word:+ """A drawn word: its sprite, and where the start of its baseline sits inside the sprite."""+ sprite: Sprite+ ox: float+ oy: float+ width: float # the pen's advance+ ascent: float # the face's cap height at this size: what lines are spaced by+++def draw_word(text: str, name: str, px: int, fill=(255, 255, 255), outline: float = 0.0,+ outline_fill=(0, 0, 0), shadow: Optional[tuple[float, float, float, float]] = None) -> Word:+ """One word as a sprite. `outline` is the stroke in pixels; `shadow` is (dx, dy, blur, opacity)."""+ from PIL import Image, ImageDraw, ImageFilter++ f = font(name, px)+ stroke = int(round(outline))+ l, t, r, b = f.getbbox(text, anchor="ls", stroke_width=stroke)+ pad = 2 + stroke+ if shadow:+ dx, dy, blur, _ = shadow+ pad += int(np.ceil(blur * 3 + max(abs(dx), abs(dy))))+ w, h = int(np.ceil(r - l)) + 2 * pad, int(np.ceil(b - t)) + 2 * pad+ ox, oy = pad - l, pad - t+ img = Image.new("RGBA", (w, h), (0, 0, 0, 0))+ if shadow:+ dx, dy, blur, opacity = shadow+ m = Image.new("L", (w, h), 0)+ ImageDraw.Draw(m).text((ox + dx, oy + dy), text, font=f, fill=255, anchor="ls",+ stroke_width=stroke, stroke_fill=255)+ if blur > 0:+ m = m.filter(ImageFilter.GaussianBlur(blur))+ alpha = (np.asarray(m, np.float32) * opacity).astype(np.uint8)+ dark = np.zeros((h, w, 4), np.uint8)+ dark[..., 3] = alpha+ img = Image.alpha_composite(img, Image.fromarray(dark, "RGBA"))+ layer = Image.new("RGBA", (w, h), (0, 0, 0, 0))+ ImageDraw.Draw(layer).text((ox, oy), text, font=f, fill=tuple(fill) + (255,), anchor="ls",+ stroke_width=stroke, stroke_fill=tuple(outline_fill) + (255,))+ img = Image.alpha_composite(img, layer)+ return Word(Sprite.from_rgba(np.asarray(img)), ox, oy, advance(text, name, px), cap_height(name, px))+++def rounded_box(w: float, h: float, radius: float, fill=(0, 0, 0), opacity: float = 1.0) -> Sprite:+ """A filled box with round corners, drawn four times larger and brought down so its edge is smooth."""+ from PIL import Image, ImageDraw++ k = 4+ W, H = max(1, int(round(w))), max(1, int(round(h)))+ img = Image.new("RGBA", (W * k, H * k), (0, 0, 0, 0))+ ImageDraw.Draw(img).rounded_rectangle((0, 0, W * k - 1, H * k - 1), radius=max(0, radius * k),+ fill=tuple(fill) + (int(round(255 * opacity)),))+ img = img.resize((W, H), Image.LANCZOS)+ return Sprite.from_rgba(np.asarray(img))+++def hex_rgb(value: str) -> tuple[int, int, int]:+ """'#ffd400', 'ffd400' or '#fd0' -> (255, 212, 0)."""+ v = value.strip().lstrip("#")+ if len(v) == 3:+ v = "".join(c * 2 for c in v)+ if len(v) != 6 or any(c not in "0123456789abcdefABCDEF" for c in v):+ raise ValueError(f"{value!r} is not a colour; use a hex colour like #ffd400")+ return int(v[0:2], 16), int(v[2:4], 16), int(v[4:6], 16)+++COLOURS = {+ "white": "#ffffff", "yellow": "#ffd400", "green": "#3ddc84", "red": "#ff4d4d", "blue": "#4da3ff",+ "pink": "#ff6fb5", "orange": "#ff9a1f", "purple": "#a678ff", "cyan": "#33e0e0", "black": "#111111",+}+++def colour(value: str) -> tuple[int, int, int]:+ """A colour by name ('yellow') or hex ('#ffd400')."""+ return hex_rgb(COLOURS.get(value.strip().lower(), value))diff --git a/edit/askeditor/fx/core/timeline.py b/edit/askeditor/fx/core/timeline.pynew file mode 100644index 0000000..25aebbe--- /dev/null+++ b/edit/askeditor/fx/core/timeline.py@@ -0,0 +1,212 @@+"""Which seconds of the clip are kept, and where each lands in the output.++The output plays the kept stretches one after another. Sound is cut at exactly these times (with+short crossfades); each output frame shows the source frame on screen at the matching source time,+so picture and sound never drift apart however many cuts there are.++`hold` adds seconds after the last kept stretch in which its last frame stays on screen, in+silence: an end card, or a finished graphic held long enough to read or screenshot.++`freezes` stop the picture inside a kept stretch: at a source moment the frame on screen holds for+a number of seconds, in silence, and then the clip plays on from exactly where it stopped. Picture+and sound stop and start together, so nothing said is lost and nothing drifts; the output is that+much longer. A timeline without freezes behaves exactly as it did before they existed.+"""++from __future__ import annotations++import bisect+import math+from dataclasses import dataclass+from typing import Optional+++@dataclass(frozen=True)+class Timeline:+ segments: tuple[tuple[float, float], ...] # kept source seconds [start, end), in order+ hold: float = 0.0 # seconds the last frame stays on screen after the last stretch, in silence+ # Moments where the picture stops inside a kept stretch: (source seconds, seconds held), in order.+ freezes: tuple[tuple[float, float], ...] = ()++ @staticmethod+ def whole(duration: float) -> "Timeline":+ return Timeline(((0.0, float(duration)),))++ def held(self, seconds: float) -> "Timeline":+ """The same stretches, with the last frame held for `seconds` at the end."""+ return Timeline(self.segments, max(0.0, float(seconds)), self.freezes)++ def frozen(self, at: float, seconds: float) -> "Timeline":+ """The same, with the picture stopped on the frame at source time `at` for `seconds`, in+ silence, before it plays on from there. `at` must be inside a kept stretch."""+ if seconds <= 0:+ return self+ if self._play(at) is None:+ raise ValueError(f"a freeze at {at:.3f} s falls in a stretch that was cut")+ freezes = tuple(sorted(self.freezes + ((float(at), float(seconds)),)))+ return Timeline(self.segments, self.hold, freezes)++ @property+ def kept(self) -> float:+ """Seconds of the clip that play: the output's length without the hold or the freezes."""+ return sum(b - a for a, b in self.segments)++ @property+ def stills(self) -> float:+ """Seconds the picture stands still inside the clip (the freezes, without the end hold)."""+ return sum(s for _, s in self.freezes)++ @property+ def played(self) -> float:+ """The output's length before the end hold: the kept stretches and the freezes in them."""+ return self.kept + self.stills++ @staticmethod+ def keeping(duration: float, removed: list[tuple[float, float]]) -> "Timeline":+ """Everything except the `removed` stretches."""+ cuts = sorted((max(0.0, a), min(duration, b)) for a, b in removed if b > a)+ segs, t = [], 0.0+ for a, b in cuts:+ if a > t:+ segs.append((t, a))+ t = max(t, b)+ if t < duration:+ segs.append((t, duration))+ return Timeline(tuple(segs))++ @property+ def duration(self) -> float:+ """The output's length, the freezes and the hold included."""+ return self.kept + self.stills + self.hold++ # ---- play time: where a source moment would land with no freezes ---------------------------++ @property+ def _play_starts(self) -> list[float]:+ out, t = [], 0.0+ for a, b in self.segments:+ out.append(t)+ t += b - a+ return out++ def _play(self, t: float) -> Optional[float]:+ starts = [a for a, _ in self.segments]+ k = bisect.bisect_right(starts, t) - 1+ if k < 0:+ return None+ a, b = self.segments[k]+ if t > b + 1e-9:+ return None+ return self._play_starts[k] + (t - a)++ def freezes_in_play(self) -> list[tuple[float, float, float]]:+ """Each freeze as (play time, seconds, source time), in order. Play time is where the frozen+ moment falls in the kept stretches joined end to end, before any freeze: where the sound+ made from them (`render.sound_for`) is opened up for the freeze's silence."""+ out = []+ for at, seconds in self.freezes:+ p = self._play(at)+ if p is not None:+ out.append((p, seconds, at))+ return sorted(out)++ def _shift(self, p: float) -> float:+ """The seconds of freezes that play before play time `p` (a freeze at `p` itself does not:+ a moment that is frozen lands at the start of its freeze)."""+ return sum(s for q, s, _ in self.freezes_in_play() if q < p - 1e-9)++ # ---- the output ------------------------------------------------------------------------------++ @property+ def out_starts(self) -> list[float]:+ """Where each kept stretch begins in the output."""+ return [p + self._shift(p) for p in self._play_starts]++ @property+ def joins(self) -> list[float]:+ """Output times where one kept stretch meets the next."""+ return self.out_starts[1:]++ def still_spans(self) -> list[tuple[float, float]]:+ """Each freeze as the output seconds it fills: silent, the picture standing still."""+ out, shift = [], 0.0+ for p, s, _ in self.freezes_in_play():+ out.append((p + shift, p + shift + s))+ shift += s+ return out++ def is_identity(self, duration: float) -> bool:+ return (len(self.segments) == 1 and self.segments[0][0] <= 1e-6 and abs(self.segments[0][1] - duration) < 1e-6+ and self.hold <= 0.0 and not self.freezes)++ def to_output(self, t: float) -> Optional[float]:+ """Where source time `t` plays in the output; None when it was cut. A frozen moment lands at+ the start of its freeze."""+ p = self._play(t)+ if p is None:+ return None+ return p + self._shift(p) if self.freezes else p++ def to_output_nearest(self, t: float) -> float:+ """Like `to_output`, but a time inside a cut moves to the nearest kept edge."""+ got = self.to_output(t)+ if got is not None:+ return got+ best, best_d = 0.0, math.inf+ for a, b in self.segments:+ for src in (a, b):+ if abs(src - t) < best_d:+ best, best_d = self.to_output(src), abs(src - t)+ return best++ def to_source(self, t_out: float) -> float:+ """The source time that plays at output time `t_out`. In a freeze it is the frozen moment.+ In the hold it is a hair before the end of the last stretch, so the frame on screen there is+ the last one that was kept."""+ if self.hold > 0 and t_out >= self.played:+ a, b = self.segments[-1]+ return max(a, b - 1e-4)+ p = t_out+ if self.freezes:+ shift = 0.0+ for q, s, at in self.freezes_in_play():+ if t_out < q + shift:+ break+ if t_out < q + shift + s:+ return at+ shift += s+ p = t_out - shift+ starts = self._play_starts+ k = max(0, bisect.bisect_right(starts, p) - 1)+ a, b = self.segments[k]+ return min(b, a + (p - starts[k]))++ def output_frames(self, fps: float) -> int:+ return max(1, int(round(self.duration * fps)))++ def source_frame(self, j: int, fps: float, n_source: int) -> int:+ """The source frame on screen at output frame `j`."""+ t = self.to_source(j / fps)+ return int(min(n_source - 1, max(0, math.floor(t * fps + 1e-6))))++ def sample_ranges(self, rate: int) -> list[tuple[int, int]]:+ return [(int(round(a * rate)), int(round(b * rate))) for a, b in self.segments]++ def map_spans(self, spans: list[tuple[float, float]]) -> list[tuple[float, float]]:+ """Source stretches (quiet runs, say) as output stretches: the parts that were kept,+ where they now play. A stretch broken by a cut comes out as the pieces either side; a+ stretch that runs across a freeze takes the freeze in with it (a freeze is silent)."""+ out = []+ for a, b in spans:+ for s0, s1 in self.segments:+ lo, hi = max(a, s0), min(b, s1)+ if hi > lo:+ out.append((self.to_output(lo), self.to_output(hi)))+ out.sort()+ merged: list[tuple[float, float]] = []+ for a, b in out:+ if merged and a <= merged[-1][1] + 1e-6:+ merged[-1] = (merged[-1][0], max(merged[-1][1], b))+ else:+ merged.append((a, b))+ return mergeddiff --git a/edit/askeditor/fx/core/video.py b/edit/askeditor/fx/core/video.pynew file mode 100644index 0000000..6b969ac--- /dev/null+++ b/edit/askeditor/fx/core/video.py@@ -0,0 +1,383 @@+"""Video in and out through ffmpeg pipes, keeping the clip's frame rate and its sound.++Frames are RGB `uint8` arrays of shape (height, width, 3). Frame `i` is the picture at `i / fps`+seconds: every reader runs the clip through ffmpeg's `fps` filter at the clip's own rate, so a+clip with a dropped or doubled frame still reads as a steady run, and the frame count always+matches the sound.++A `VideoInfo` can also stand for a picture that is drawn rather than read from its file: the+canvas of a layout, as an effect laid inside it sees it (`view.py`). Its `picture` gives frame `i`;+`read_frame` asks it, and `FrameReader` refuses it in plain words.+"""++from __future__ import annotations++import json+import os+import shutil+import subprocess+import tempfile+from dataclasses import dataclass, field+from fractions import Fraction+from pathlib import Path+from typing import Callable, Iterator, Optional++import numpy as np++from . import hdr++# On a busy machine, FX_THREADS caps the threads each ffmpeg (and OpenCV) uses; unset, they choose.+THREADS = os.environ.get("FX_THREADS", "").strip()+++def threads() -> list[str]:+ return ["-threads", THREADS, "-filter_threads", THREADS] if THREADS.isdigit() else []+++if THREADS.isdigit():+ try:+ import cv2++ cv2.setNumThreads(int(THREADS))+ except ImportError:+ pass++AUDIO_RATE = 48000+AUDIO_CHANNELS = 2+++class MediaError(RuntimeError):+ """ffmpeg could not read or write something; the message says what in plain words."""+++def need_ffmpeg() -> None:+ for tool in ("ffmpeg", "ffprobe"):+ if shutil.which(tool) is None:+ raise MediaError("ffmpeg is not installed. Run setup.sh: it says how to get it.")+++@dataclass(frozen=True)+class VideoInfo:+ path: str+ width: int # as displayed, after any rotation flag+ height: int+ fps: Fraction+ duration: float # seconds of picture+ frames: int # frames at `fps` across `duration`+ has_audio: bool+ audio_offset: float # when the sound starts, relative to the first frame (seconds)+ color_matrix: str # how the clip's colours are coded: "bt709", "bt601" or "bt2020"+ transfer: str = "sdr" # "hlg" or "pq" for HDR footage, which every reader turns into SDR (hdr.py)+ # A picture drawn rather than read from `path` (a layout's canvas): frame number -> RGB frame.+ picture: Optional[Callable[[int], np.ndarray]] = field(default=None, compare=False, repr=False)++ @property+ def rate(self) -> float:+ return float(self.fps)++ def time(self, frame: int) -> float:+ return frame / self.rate++ def frame_at(self, t: float) -> int:+ return int(min(self.frames - 1, max(0, round(t * self.rate))))++ @property+ def aspect(self) -> float:+ return self.width / self.height+++def _fraction(text: str | None) -> Fraction:+ try:+ num, _, den = (text or "0/1").partition("/")+ f = Fraction(int(num), int(den or 1))+ return f if f > 0 else Fraction(0)+ except (ValueError, ZeroDivisionError):+ return Fraction(0)+++def probe(path: str | os.PathLike) -> VideoInfo:+ need_ffmpeg()+ path = str(path)+ if not Path(path).exists():+ raise MediaError(f"there is no file at {path}")+ out = subprocess.run(+ ["ffprobe", "-v", "error", "-print_format", "json", "-show_streams", "-show_format", path],+ capture_output=True,+ text=True,+ )+ if out.returncode != 0:+ raise MediaError(f"this file could not be read as a video: {path}")+ data = json.loads(out.stdout)+ streams = data.get("streams", [])+ video = next(+ (s for s in streams if s.get("codec_type") == "video" and not s.get("disposition", {}).get("attached_pic")),+ None,+ )+ if video is None:+ raise MediaError(f"this file has no picture: {path}")+ audio = next((s for s in streams if s.get("codec_type") == "audio"), None)++ width, height = int(video["width"]), int(video["height"])+ rotation = 0+ for side in video.get("side_data_list", []) or []:+ if "rotation" in side:+ rotation = int(round(float(side["rotation"])))+ if not rotation and "rotate" in video.get("tags", {}):+ rotation = int(video["tags"]["rotate"])+ if abs(rotation) % 180 == 90:+ width, height = height, width++ fps = _fraction(video.get("r_frame_rate"))+ avg = _fraction(video.get("avg_frame_rate"))+ if fps == 0 or fps > 240 or (avg > 0 and fps > 2 * avg):+ fps = avg+ if fps == 0:+ raise MediaError(f"could not tell the frame rate of {path}")++ duration = float(video.get("duration") or data.get("format", {}).get("duration") or 0)+ if duration <= 0:+ raise MediaError(f"could not tell how long {path} is")+ v_start = float(video.get("start_time") or 0)+ a_start = float(audio.get("start_time") or 0) if audio else 0.0++ space = (video.get("color_space") or "").lower()+ transfer = hdr.kind(video.get("color_transfer"))+ if space in ("smpte170m", "bt470bg", "bt601"):+ matrix = "bt601"+ elif space in ("bt2020nc", "bt2020c") or transfer != "sdr":+ matrix = "bt2020"+ elif space in ("bt709",) or height >= 720 or width >= 1280:+ matrix = "bt709"+ else:+ matrix = "bt601"++ return VideoInfo(+ path=path,+ width=width,+ height=height,+ fps=fps,+ duration=duration,+ frames=max(1, int(round(duration * float(fps)))),+ has_audio=audio is not None,+ audio_offset=a_start - v_start,+ color_matrix=matrix,+ transfer=transfer,+ )+++def _fps_text(fps: Fraction) -> str:+ return f"{fps.numerator}/{fps.denominator}"+++class FrameReader:+ """Frames of a clip, one after another, optionally scaled, from `start` seconds for `duration`.++ `extra` is more of ffmpeg's filters, run on the picture once it is RGB at its final size (a 3D+ LUT, say: `lut3d=file=look.cube`); they must keep it in the same format. `cwd` is the folder+ ffmpeg runs in, so a filter can name its file by a bare name: a full path inside a filter needs+ escaping that differs between systems (a Windows drive's colon breaks it).++ HDR footage (HLG or PQ) comes out as ordinary SDR, converted before anything else sees it+ (`hdr.py`), so every effect, the face finder and the person mask see the picture as a phone+ shows it rather than flat and grey.+ """++ def __init__(+ self,+ info: VideoInfo,+ size: Optional[tuple[int, int]] = None,+ start: float = 0.0,+ duration: Optional[float] = None,+ gray: bool = False,+ extra: Optional[str] = None,+ cwd: Optional[str | os.PathLike] = None,+ ):+ if info.picture is not None:+ raise MediaError("this picture is drawn by the layout it sits in, so it cannot be streamed from a "+ "file: lay this effect on the clip before the layout, or run it on the layout's result")+ self.info = info+ self.width, self.height = size or (info.width, info.height)+ self.channels = 1 if gray else 3+ self.frame_bytes = self.width * self.height * self.channels+ cmd = ["ffmpeg", "-v", "error", "-nostdin", *threads()]+ if start > 0:+ cmd += ["-ss", f"{start:.6f}"]+ cmd += ["-i", str(Path(info.path).resolve())]+ if duration is not None:+ cmd += ["-t", f"{duration:.6f}"]+ scale = f"scale={self.width}:{self.height}:flags=bicubic+accurate_rnd+full_chroma_int"+ scale += f":in_color_matrix={info.color_matrix}"+ fmt = "gray" if gray else "rgb24"+ if info.transfer in ("hlg", "pq"):+ to_sdr, cwd = hdr.reader_filter(info.transfer, cwd)+ vf = f"fps={_fps_text(info.fps)},{scale},format=rgb48le,{to_sdr},format={fmt}"+ else:+ vf = f"fps={_fps_text(info.fps)},{scale},format={fmt}"+ if extra:+ vf += f",{extra},format={fmt}"+ cmd += ["-map", "0:v:0", "-vf", vf, "-f", "rawvideo", "-pix_fmt", fmt, "-"]+ self._proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=self.frame_bytes * 2,+ cwd=str(cwd) if cwd else None)++ def __iter__(self) -> Iterator[np.ndarray]:+ assert self._proc.stdout is not None+ shape = (self.height, self.width) if self.channels == 1 else (self.height, self.width, 3)+ try:+ while True:+ buf = self._proc.stdout.read(self.frame_bytes)+ if len(buf) < self.frame_bytes:+ break+ yield np.frombuffer(buf, np.uint8).reshape(shape)+ finally:+ self.close()++ def close(self) -> None:+ if self._proc.poll() is None:+ self._proc.kill()+ self._proc.wait()+++def read_frame(info: VideoInfo, index: int, size: Optional[tuple[int, int]] = None,+ extra: Optional[str] = None, cwd: Optional[str | os.PathLike] = None) -> np.ndarray:+ """One frame by its number, at the clip's size or `size` (`extra` and `cwd` as for FrameReader).+ A drawn picture (`info.picture`) is asked for the frame instead."""+ index = max(0, min(info.frames - 1, index))+ if info.picture is not None:+ if extra:+ raise MediaError("a picture drawn by a layout cannot be run through more filters")+ frame = np.asarray(info.picture(index))+ if size is not None and (frame.shape[1], frame.shape[0]) != tuple(size):+ import cv2++ frame = cv2.resize(frame, tuple(size), interpolation=cv2.INTER_AREA)+ return np.ascontiguousarray(frame, np.uint8).copy()+ # Seek a quarter of a frame early: the first frame at or after that time is frame `index`.+ start = max(0.0, (index - 0.25) / info.rate)+ for frame in FrameReader(info, size=size, start=start, duration=2.0 / info.rate + 0.5, extra=extra, cwd=cwd):+ return frame.copy()+ # Past the last decodable frame: fall back to the last one there is.+ frames = list(FrameReader(info, size=size, start=max(0.0, info.duration - 1.0), extra=extra, cwd=cwd))+ if not frames:+ raise MediaError(f"could not read frame {index} of {info.path}")+ return frames[-1].copy()+++def read_audio(info: VideoInfo, rate: int = AUDIO_RATE, channels: int = AUDIO_CHANNELS) -> np.ndarray:+ """The clip's sound as float32 samples of shape (n, channels), lined up with frame 0 and+ exactly as long as the picture. A clip with no sound gives silence."""+ n = int(round(info.frames / info.rate * rate))+ if not info.has_audio:+ return np.zeros((n, channels), np.float32)+ out = subprocess.run(+ ["ffmpeg", "-v", "error", "-nostdin", "-i", info.path, "-map", "0:a:0", "-ac", str(channels),+ "-ar", str(rate), "-f", "f32le", "-"],+ capture_output=True,+ )+ if out.returncode != 0:+ raise MediaError(f"could not read the sound of {info.path}")+ samples = np.frombuffer(out.stdout, np.float32).reshape(-1, channels)+ shift = int(round(info.audio_offset * rate))+ if shift > 0:+ samples = np.concatenate([np.zeros((shift, channels), np.float32), samples])+ elif shift < 0:+ samples = samples[-shift:]+ if len(samples) < n:+ samples = np.concatenate([samples, np.zeros((n - len(samples), channels), np.float32)])+ return np.ascontiguousarray(samples[:n])+++def mono(samples: np.ndarray, rate: int, to_rate: int = 16000) -> np.ndarray:+ """Mix down to one channel and resample by simple averaging (used only for analysis)."""+ x = samples.mean(axis=1) if samples.ndim == 2 else samples+ if rate == to_rate:+ return x.astype(np.float32)+ n_out = int(len(x) * to_rate / rate)+ pos = np.arange(n_out) * (rate / to_rate)+ return np.interp(pos, np.arange(len(x)), x).astype(np.float32)+++class FrameWriter:+ """Writes RGB frames to an MP4 (H.264, the clip's frame rate) with the given sound (AAC).++ The file is written under a temporary name and moved into place only when it is complete, so a+ render that stops halfway never leaves a broken file with the final name.+ """++ def __init__(+ self,+ out_path: str | os.PathLike,+ width: int,+ height: int,+ fps: Fraction,+ audio: Optional[np.ndarray] = None,+ audio_rate: int = AUDIO_RATE,+ crf: int = 18,+ preset: str = "medium",+ audio_kbps: int = 192,+ ):+ need_ffmpeg()+ self.out_path = Path(out_path)+ self.out_path.parent.mkdir(parents=True, exist_ok=True)+ self.width, self.height = width, height+ self.frames = 0+ self._tmpdir = tempfile.mkdtemp(prefix="fx-")+ self._partial = Path(self._tmpdir) / ("partial" + self.out_path.suffix)+ cmd = ["ffmpeg", "-v", "error", "-nostdin", "-y",+ "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{width}x{height}",+ "-framerate", _fps_text(fps), "-i", "-"]+ self._audio_file = None+ if audio is not None and len(audio):+ self._audio_file = Path(self._tmpdir) / "sound.f32"+ np.ascontiguousarray(audio, np.float32).tofile(self._audio_file)+ cmd += ["-f", "f32le", "-ar", str(audio_rate), "-ac", str(audio.shape[1]), "-i", str(self._audio_file)]+ cmd += ["-map", "0:v:0"]+ if self._audio_file:+ cmd += ["-map", "1:a:0", "-c:a", "aac", "-b:a", f"{int(audio_kbps)}k"]+ cmd += ["-vf", "scale=out_color_matrix=bt709:out_range=tv,format=yuv420p",+ *(["-threads", THREADS] if THREADS.isdigit() else []),+ "-c:v", "libx264", "-preset", preset, "-crf", str(crf), "-pix_fmt", "yuv420p",+ "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv",+ "-movflags", "+faststart", "-map_metadata", "-1", "-fflags", "+bitexact",+ "-flags:v", "+bitexact", "-flags:a", "+bitexact", str(self._partial)]+ self._proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)++ def write(self, frame: np.ndarray) -> None:+ if frame.shape != (self.height, self.width, 3) or frame.dtype != np.uint8:+ raise ValueError(f"frame is {frame.shape} {frame.dtype}, expected ({self.height}, {self.width}, 3) uint8")+ assert self._proc.stdin is not None+ try:+ self._proc.stdin.write(np.ascontiguousarray(frame).tobytes())+ except BrokenPipeError as e:+ raise MediaError(self._error()) from e+ self.frames += 1++ def _error(self) -> str:+ err = (self._proc.stderr.read().decode(errors="replace") if self._proc.stderr else "").strip()+ return "the video could not be written" + (f": {err.splitlines()[-1]}" if err else "")++ def close(self) -> Path:+ assert self._proc.stdin is not None+ self._proc.stdin.close()+ code = self._proc.wait()+ try:+ if code != 0:+ raise MediaError(self._error())+ shutil.move(str(self._partial), str(self.out_path))+ return self.out_path+ finally:+ shutil.rmtree(self._tmpdir, ignore_errors=True)++ def abort(self) -> None:+ if self._proc.poll() is None:+ self._proc.kill()+ self._proc.wait()+ shutil.rmtree(self._tmpdir, ignore_errors=True)+++def save_jpeg(path: str | os.PathLike, frame: np.ndarray, quality: int = 90) -> Path:+ from PIL import Image++ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ Image.fromarray(frame).save(path, quality=quality)+ return pathdiff --git a/edit/askeditor/fx/core/view.py b/edit/askeditor/fx/core/view.pynew file mode 100644index 0000000..3f69b76--- /dev/null+++ b/edit/askeditor/fx/core/view.py@@ -0,0 +1,158 @@+"""A clip as a layout shows it: what an effect laid inside a layout is prepared on.++A layout moves the speaker into a panel and fills the rest of the frame with other pictures. An+effect laid inside it (captions over the whole frame, a chart in the top panel) has to be prepared+for the picture it will be drawn on, not for the clip as it was shot: its words must keep clear of+the face where the face now is, and stay inside the part of the panel where text is safe.++ view = View(clip, (w, h), place=where_each_frame_goes, picture=draw_frame, zone=safe_rect)+ layer = layers.prepare(view, spec, start, end, view_framing) # applies the zone too++A `View` is the clip with everything about its picture replaced and everything else kept:++- `info`: the picture's own size (the whole canvas, or one panel of it). Frame rate, length, sound+ and file stay the clip's. Its `picture` draws frame i, so an effect that looks at what it sits on+ (to choose a tone, to tint glass) sees the composed picture; one that streams the clip's own+ picture from its file cannot be laid on a view, and says so.+- `face`: the clip's face track moved to where each frame shows it, or no face at all.+- `person()`: the person masks moved the same way, or empty.+- `zone`: where text is safe in this picture, in its own pixels (None: the app's fractions, which+ is right for a whole frame).+- `words`, `quiet`, `sound` and everything else: the clip's own.++`place(i)` says where frame i of the clip is shown: `(window, rect)`, the window of the clip's own+picture (x, y, w, h in the clip's pixels) shown in `rect` (a Rect in the view's pixels) at one+scale, or None when the clip is not in this view at that frame. Only what lands inside `rect` is+in the view: a face whose middle falls outside it is not there.+"""++from __future__ import annotations++import dataclasses+import os+from functools import cached_property+from pathlib import Path+from typing import Callable, Iterator, Optional++import numpy as np++from . import person as personmod+from .face import FaceTrack+from .layout import Rect++Window = tuple[float, float, float, float]+Place = Callable[[int], Optional[tuple[Window, Rect]]]+++def _move(box: np.ndarray, window: Window, rect: Rect) -> np.ndarray:+ """x, y, w, h in the clip's pixels -> the same box where `rect` shows `window`."""+ wx, wy, ww, _ = window+ s = rect.w / ww+ return np.array([(box[0] - wx) * s + rect.x0, (box[1] - wy) * s + rect.y0, box[2] * s, box[3] * s])+++def moved_faces(face: FaceTrack, place: Optional[Place], size: tuple[int, int]) -> FaceTrack:+ """The face track as the view shows it: every box moved to where its frame is placed. Frames+ where the face is not in the view hold the nearest frame where it is (as the clip's own track+ holds across a gap), and count as not found."""+ n = face.n+ raw = np.full((n, 5), np.nan)+ trusted = np.full((n, 5), np.nan)+ boxes = np.zeros((n, 4))+ shown = np.zeros(n, bool)+ if place is not None and face.any():+ for i in range(n):+ p = place(i)+ if p is None:+ continue+ window, rect = p+ b = _move(face.boxes[i], window, rect)+ if not (rect.x0 <= b[0] + b[2] / 2 <= rect.x1 and rect.y0 <= b[1] + b[3] / 2 <= rect.y1):+ continue+ boxes[i], shown[i] = b, True+ for src, dst in ((face.raw, raw), (face.trusted, trusted)):+ if not np.isnan(src[i, 0]):+ dst[i, :4] = _move(src[i, :4], window, rect)+ dst[i, 4] = src[i, 4]+ if shown.any() and not shown.all():+ idx = np.flatnonzero(shown)+ for c in range(4):+ boxes[:, c] = np.interp(np.arange(n), idx, boxes[idx, c])+ return FaceTrack(int(size[0]), int(size[1]), face.fps, raw, boxes, trusted=trusted)+++class MovedMasks(personmod.PersonMasks):+ """The clip's person masks as the view shows them: each frame's mask moved to where its frame is+ placed, and nothing anywhere else. With no masks to move (a panel the person is not in), every+ frame is empty."""++ def __init__(self, base: Optional[personmod.PersonMasks], info, place: Optional[Place]):+ w = personmod.WORK_WIDTH+ h = max(2, int(round(w * info.height / info.width)))+ super().__init__(info=info, path=base.path if base is not None else Path(os.devnull), width=w, height=h,+ model=base.model if base is not None else personmod.MODEL)+ self.base, self.place = base, place++ def _moved(self, m: np.ndarray, i: int) -> np.ndarray:+ import cv2++ p = self.place(i) if self.place is not None else None+ if p is None:+ return np.zeros((self.height, self.width), np.float32)+ (wx, wy, ww, _), rect = p+ b = self.base+ bx, by = b.width / b.info.width, b.height / b.info.height # the clip's pixels -> its small mask+ k = self.width / self.info.width # the view's pixels -> its small mask+ s = rect.w / ww+ m2 = np.float32([[s * k / bx, 0, (rect.x0 - wx * s) * k], [0, s * k / by, (rect.y0 - wy * s) * k]])+ out = cv2.warpAffine(m, m2, (self.width, self.height), flags=cv2.INTER_LINEAR, borderValue=0)+ inside = np.zeros_like(out)+ x0, y0 = int(max(0, np.floor(rect.x0 * k))), int(max(0, np.floor(rect.y0 * k)))+ x1, y1 = int(min(self.width, np.ceil(rect.x1 * k))), int(min(self.height, np.ceil(rect.y1 * k)))+ inside[y0:y1, x0:x1] = out[y0:y1, x0:x1]+ return inside++ def frames(self) -> Iterator[np.ndarray]:+ n = self.n+ if self.base is None or self.place is None:+ empty = np.zeros((self.height, self.width), np.float32)+ for _ in range(n):+ yield empty+ return+ count = 0+ for i, m in enumerate(self.base.frames()):+ if count >= n:+ break+ count += 1+ yield self._moved(m, i)++ def at(self, i: int) -> np.ndarray:+ i = int(np.clip(i, 0, self.n - 1))+ if self.base is None or self.place is None:+ return np.zeros((self.height, self.width), np.float32)+ return self._moved(self.base.at(i), i)+++class View:+ """The clip as a picture of `size` (w, h) shows it. See the module's notes."""++ def __init__(self, clip, size: tuple[int, int], place: Optional[Place] = None,+ picture: Optional[Callable[[int], np.ndarray]] = None, zone: Optional[Rect] = None):+ self.base = clip+ self.size = (int(size[0]), int(size[1]))+ self.info = dataclasses.replace(clip.info, width=self.size[0], height=self.size[1], picture=picture)+ self.place = place+ self.zone = zone++ @cached_property+ def face(self) -> FaceTrack:+ return moved_faces(self.base.face, self.place, self.size)++ def person(self, model: str = personmod.MODEL) -> MovedMasks:+ return MovedMasks(self.base.person(model) if self.place is not None else None, self.info, self.place)++ def __getattr__(self, name: str):+ # Everything that is not about the picture (words, sound, the file, the fixes) is the clip's.+ if name == "base":+ raise AttributeError(name)+ return getattr(self.base, name)diff --git a/edit/askeditor/fx/core/words.py b/edit/askeditor/fx/core/words.pynew file mode 100644index 0000000..727bf00--- /dev/null+++ b/edit/askeditor/fx/core/words.py@@ -0,0 +1,820 @@+"""Word times from the clip's speech, cached next to the clip as JSON.++The transcription runs once per clip, in its own process (the speech package and the picture+package each carry their own copy of the video libraries, and loading both in one process makes+macOS print warnings). The result is `<clip>.words.json` beside the clip: the transcriber's words+exactly as it heard them, and what a second listen heard (`relisten`). Corrections (`fix`), the+judging of the second listen (`merge`) and the timing checked against the sound (`timed`) are+applied each time the words are read, never written back, so the cache stays the raw record.++A word the second listen heard but could not be sure of is kept with the words, marked `unsure`+with the reason, and is never shown or cut on: `timed` (what every effect reads) leaves it out.++ python -m fx.core.words <clip> [--model small.en] [--refresh] # transcribe and print+"""++from __future__ import annotations++import argparse+import json+import os+import re+import subprocess+import sys+import time+from dataclasses import dataclass, replace+from pathlib import Path+from typing import Iterable, Optional++from . import paths++CACHE_VERSION = 1+# A short, neutral prompt in the way people really talk. It nudges the transcriber into keeping+# the "um"s, the restarts and the repeated words instead of tidying them away, which is what lets+# clean-cut find them.+PROMPT = "Um, so, uh, I- I think, like... okay."+# [LumReels] The language and the speech model come from the environment, so the same code serves+# English (the pack's default: small.en on the CPU) and Vietnamese (large-v3, on the GPU when there+# is one). FX_LANG: "en" | "vi" | another Whisper code. FX_WHISPER: a faster-whisper model name or+# path ("large-v3"); unset keeps the pack's own pinned model. FX_DEVICE: "cuda" | "cpu" | "auto".+LANG = os.environ.get("FX_LANG", "en").strip().lower() or "en"+# No nudging prompt outside English: on Vietnamese a prompt made large-v3-turbo invent a whole+# "subscribe to the channel" sentence over real speech (LumReels spike, 28 November 2026).+PROMPTS = {"en": PROMPT}+# Sentences Whisper says over sound it cannot make out, per language (lower case, no punctuation).+# A first-listen segment containing one of them is dropped before anything reads the words.+INVENTED = {+ "vi": ("subscribe", "đăng ký kênh", "đăng kí kênh", "ghiền mì gõ", "cảm ơn các bạn đã theo dõi",+ "hẹn gặp lại các bạn", "like và share", "la la school", "bỏ lỡ những video"),+}++_APOSTROPHES = str.maketrans({"’": "'", "‘": "'", "“": '"', "”": '"'})+_PUNCT_EDGES = re.compile(r"^[^\w']+|[^\w']+$")+FILLERS = {"um", "umm", "uh", "uhh", "erm", "er", "ah", "hmm", "mm", "mhm", "eh",+ "ờ", "ờm", "ừm", "ơ", "hừm", "ừa"} # [LumReels] Vietnamese fillers+# The sounds that hold a place while the speaker thinks: never shown as a caption, and cut by+# clean-cut unless asked to keep them. ("ah" and "eh" can be real interjections, so they stay.)+HESITATIONS = {"um", "umm", "uhm", "uh", "uhh", "erm", "er", "hmm", "hm", "mm", "mhm",+ "ờ", "ờm", "ừm", "ơ", "hừm"} # [LumReels] Vietnamese ("à", "ừ" can be words, so they stay)+++@dataclass(frozen=True)+class Word:+ text: str # as heard, with its punctuation ("product.")+ start: float+ end: float+ prob: float = 1.0+ # Why the word is doubted, or "" when it is not: a word the second listen heard and could not+ # be sure of (`judge`). It stays with the words, so nothing heard is lost, and is never shown+ # or cut on.+ unsure: str = ""++ @property+ def key(self) -> str:+ """The word for comparing: lower case, no punctuation, no trailing hyphen."""+ return normalize(self.text)++ @property+ def length(self) -> float:+ return self.end - self.start++ @property+ def ends_sentence(self) -> bool:+ return self.text.rstrip().endswith((".", "?", "!"))++ @property+ def ends_clause(self) -> bool:+ return self.text.rstrip().endswith((",", ";", ":", "—", "-", "…")) or self.ends_sentence++ @property+ def is_filler(self) -> bool:+ return self.key in FILLERS++ @property+ def clean(self) -> str:+ """The word to show on screen: as heard, without a dangling hyphen or ellipsis."""+ t = self.text.strip().translate(_APOSTROPHES)+ return t.rstrip("-—…").rstrip(".") if t.endswith(("-", "—", "…", "...")) else t+++def normalize(text: str) -> str:+ t = text.strip().lower().translate(_APOSTROPHES)+ t = _PUNCT_EDGES.sub("", t)+ return t.strip("'")+++def to_json(words: Iterable[Word]) -> list[dict]:+ return [{"w": w.text, "s": round(w.start, 3), "e": round(w.end, 3), "p": round(w.prob, 3),+ **({"unsure": w.unsure} if w.unsure else {})} for w in words]+++def from_json(items: Iterable[dict]) -> list[Word]:+ return [Word(text=str(i["w"]), start=float(i["s"]), end=float(i["e"]), prob=float(i.get("p", 1.0)),+ unsure=str(i.get("unsure", ""))) for i in items]+++def sure(words: Iterable[Word]) -> list[Word]:+ """The words that may be shown and cut on: all but the unsure ones."""+ return [w for w in words if not w.unsure]+++def in_time(words: list[Word], extra: Iterable[Word]) -> list[Word]:+ """`words` in their own order, with each of `extra` put in after the last word that starts no+ later than it does."""+ import bisect++ out = list(words)+ for w in sorted(extra, key=lambda w: (w.start, w.end)):+ out.insert(bisect.bisect_right([x.start for x in out], w.start), w)+ return out+++def unsure_stretches(words: Iterable[Word], most: int = 8) -> list[dict]:+ """The unsure words, for a person to read: one entry per run of them doubted for the same+ reason (a loop of forty words is one line), each with what was heard, when, and why."""+ runs: list[list[Word]] = []+ for w in sorted((w for w in words if w.unsure), key=lambda w: (w.start, w.end)):+ if runs and runs[-1][-1].unsure == w.unsure and w.start - runs[-1][-1].end < 0.3:+ runs[-1].append(w)+ else:+ runs.append([w])+ out = []+ for run in runs:+ said = " ".join(w.text for w in run[:most]) + (" …" if len(run) > most else "")+ out.append({"w": said, "s": round(run[0].start, 3), "e": round(max(w.end for w in run), 3),+ "why": run[0].unsure + (f" ({len(run)} words)" if len(run) > 1 else "")})+ return out+++def _cache_path(clip: Path) -> Path:+ return paths.beside(clip, "words.json")+++def _valid(data: dict, clip: Path, model: str) -> bool:+ return (+ data.get("version") == CACHE_VERSION+ and data.get("model") == model_key(model)+ and data.get("source", {}).get("bytes") == paths.source_signature(clip)["bytes"]+ )+++def load(clip: str | os.PathLike, model: str = "small.en", refresh: bool = False,+ out: Optional[Path] = None) -> list[Word]:+ """The clip's words: from the cache beside it, or by transcribing it now (once)."""+ clip = Path(clip).resolve()+ cache = out or _cache_path(clip)+ if not refresh and cache.exists():+ try:+ data = json.loads(cache.read_text(encoding="utf-8"))+ if _valid(data, clip, model):+ return from_json(data["words"])+ except (json.JSONDecodeError, KeyError, TypeError, ValueError):+ pass+ env = dict(os.environ, PYTHONPATH=str(paths.PACK) + os.pathsep + os.environ.get("PYTHONPATH", ""))+ env.setdefault("TOKENIZERS_PARALLELISM", "false")+ run = subprocess.run(+ [sys.executable, "-m", "fx.core.words", str(clip), "--model", model, "--out", str(cache), "--quiet"]+ + (["--refresh"] if refresh else []),+ env=env, capture_output=True, text=True,+ )+ if run.returncode != 0 or not cache.exists():+ lines = [ln for ln in (run.stderr or "").splitlines() if ln.strip() and "objc[" not in ln]+ raise RuntimeError("could not find the words: " + (lines[-1] if lines else "the transcriber stopped"))+ return from_json(json.loads(cache.read_text(encoding="utf-8"))["words"])+++def _engine(model: str):+ from faster_whisper import WhisperModel++ from . import models++ threads = max(1, min(8, (os.cpu_count() or 4)))+ override = os.environ.get("FX_WHISPER", "").strip()+ if not override:+ return WhisperModel(str(models.speech_path(model)), device="cpu", compute_type="int8", cpu_threads=threads)+ device = os.environ.get("FX_DEVICE", "auto").strip().lower() or "auto"+ if device in ("auto", "cuda"):+ try:+ import ctranslate2++ if ctranslate2.get_cuda_device_count() > 0:+ cuda_libraries()+ return WhisperModel(override, device="cuda", compute_type="float16", cpu_threads=threads)+ except Exception as e: # no CUDA libraries, an old driver, no room on the card+ if device == "cuda":+ raise+ print(f"speech model: the GPU could not be used ({e}); using the CPU", file=sys.stderr)+ return WhisperModel(override, device="cpu", compute_type="int8", cpu_threads=threads)+++def model_key(model: str) -> str:+ """[LumReels] What a words cache records as its model: the model and the language when they come+ from the environment, so changing either transcribes again."""+ override = os.environ.get("FX_WHISPER", "").strip()+ return f"{override}:{LANG}" if override else model+++def cuda_libraries() -> None:+ """[LumReels] CTranslate2 loads cuBLAS and cuDNN at run time. pip's nvidia-cublas-cu12 and+ nvidia-cudnn-cu12 wheels put them in site-packages/nvidia/*/bin (Windows) or */lib (Linux).+ On Windows they are added here; on Linux the caller sets LD_LIBRARY_PATH before Python starts+ (a library path cannot change inside a running process). macOS has no CUDA."""+ if os.name != "nt" or not hasattr(os, "add_dll_directory"):+ return+ import site++ roots = [Path(p) / "nvidia" for p in site.getsitepackages()]+ for root in roots:+ for sub in ("cublas", "cudnn", "cuda_nvrtc", "cuda_runtime"):+ d = root / sub / "bin"+ if d.is_dir():+ os.add_dll_directory(str(d))+ os.environ["PATH"] = str(d) + os.pathsep + os.environ.get("PATH", "")+++def _listen(engine, samples) -> list[dict]:+ """What the transcriber hears in `samples`, one entry per segment: its text, its words, and its+ own confidence in it (`no_speech_prob`: how likely it thought the sound was not speech at all;+ `avg_logprob`: how sure it was of the words, 0 being certain; `compression_ratio`: above about+ 2.4 the text is the same few words over and over)."""+ segments, _ = engine.transcribe(+ samples,+ language=LANG,+ word_timestamps=True,+ beam_size=5,+ temperature=0.0, # no sampling: the same clip gives the same words every time+ condition_on_previous_text=False,+ initial_prompt=PROMPTS.get(LANG),+ vad_filter=False,+ )+ out = []+ invented = INVENTED.get(LANG, ())+ for seg in segments:+ said = " ".join(seg.text.lower().split())+ if invented and any(x in said for x in invented):+ continue # [LumReels] a sentence the transcriber makes up over noise or music+ words = [Word(w.word.strip(), float(w.start), float(w.end), float(w.probability))+ for w in seg.words or [] if w.word.strip()]+ out.append({"text": seg.text.strip(), "no_speech_prob": float(seg.no_speech_prob),+ "avg_logprob": float(seg.avg_logprob), "compression_ratio": float(seg.compression_ratio),+ "words": words})+ return out+++def _hear(engine, samples) -> tuple[list[Word], str]:+ segments = _listen(engine, samples)+ return [w for s in segments for w in s["words"]], " ".join(s["text"] for s in segments)+++def transcribe(clip: Path, model: str = "small.en") -> dict:+ """Runs the transcriber (in this process). Use `load()` from everywhere else."""+ import numpy as np # noqa: F401 (the speech package needs it loaded first)++ from . import video++ info = video.probe(clip)+ samples = video.read_audio(info, rate=16000, channels=1)[:, 0]+ started = time.time()+ words, text = _hear(_engine(model), samples)+ return {+ "version": CACHE_VERSION,+ "model": model_key(model),+ "source": dict(paths.source_signature(clip), seconds=round(info.duration, 3)),+ "seconds_to_transcribe": round(time.time() - started, 2),+ "text": text,+ "words": to_json(words),+ }+++# ---- a second listen -----------------------------------------------------------------------------+#+# The transcriber tidies speech up. A false start it hears as part of the take ("from the+# perspective of- from the perspective of hooks") often comes out written once, with one word+# stretched across both attempts and the rest of the voice left without words. Nothing that reads+# only the words can find a retake that was never written down. So the stretches the words cannot+# explain are listened to again, each on its own, and what is heard there replaces what was there.+#+# Out of its sentence, a second of sound is also where the transcriber invents. On clip D it heard+# "Town car." where the take says "town, or", "Hotel." again in the tail of "hotel", and a second+# "went" at the edge of a stretch that began just after "went"; on clean speech it hears "I'll be+# safe." for "lively city". How sure it says it is does not tell these apart from real words, so+# nothing heard the second time is used until it is judged (`judge`, below). A word that fails is+# kept with the words, marked `unsure` with the reason, and never shown or cut on.++SECOND_PAD = 0.12 # sound either side of a stretch, so its first and last words are whole+# How a stretch is heard again, and what is kept of it. Each version's results live in the clip's+# cache under their own name: a cache from before this version (whose "second_listen" holds words+# without the transcriber's confidence) is heard again automatically, and an older copy of the pack+# reading the same clip keeps its own results and never undoes these.+SECOND_VERSION = 2+SECOND_KEY = f"second_listen_v{SECOND_VERSION}"++# What a word heard the second time must pass to be used (`judge`). The numbers come from hearing+# 280 short stretches of the eight test clips exactly as the second listen does+# (`tests/second_listen.py --calibrate`, 28 October 2026): 503 words heard over speech were what the+# first listen heard there, and 709 were heard over the clips' own quiet, where nothing is said.+#+# - The voice under a word tells them apart: 707 of the 709 sit under the clip's voiced level+# (rule 1), against 4 of the 503.+# - The transcriber's confidence barely does. Real words go down to 0.001 in probability (13 of them+# under 0.05, nearly all the first word of a stretch, heard without its sentence), up to 0.63 in+# no_speech_prob and down to -1.12 in avg_logprob, so the bounds of rule 2 sit at that edge and+# catch only what almost no real word looks like.+# - The words invented on D sit on real voice with real-looking confidence (probability 0.41-0.99,+# no_speech_prob 0.002-0.09, avg_logprob -0.43 to -0.49): rules 3 and 4 catch them, and rule 4+# catches 99 of the 121 other words heard over speech, with voice under them, that the first+# listen did not hear there.+#+# `tests/second_listen.py --evidence` prints every word the second listen hears on the test clips,+# with these values and its verdict.+SURE_PROB = 0.05 # 2. the word's own probability, at least+SURE_NO_SPEECH = 0.60 # 2. its segment's no_speech_prob, at most+SURE_LOGPROB = -1.00 # 2. its segment's avg_logprob, at least+LOOP_RATIO = 2.4 # 3. a segment that compresses more than this is a few words over and over+MOST_PER_SECOND = 5.0 # 3. more words than this per second of the stretch is a loop too+NEARBY = 8.0 # 4. a word added is one said within this many seconds (clean-cut's retake window)+# 3. What the transcriber says to sound it cannot make out.+_HALLUCINATIONS = {"thank you", "thanks for watching", "you", "bye", "thank you for watching", "so",+ "cảm ơn các bạn", "cảm ơn các bạn đã theo dõi", "hẹn gặp lại"} # [LumReels] + Vietnamese+++def plausible_length(word: Word) -> float:+ """The longest a word of this many letters is usually said for (a slow speaker, plus slack)."""+ return 0.18 + 0.1 * max(1, len(word.key))+++def _key(span: tuple[float, float]) -> str:+ return f"{span[0]:.2f}-{span[1]:.2f}"+++def doubtful_spans(words: list[Word], quiet: list[tuple[float, float]], duration: float) -> list[tuple[float, float]]:+ """Stretches the words cannot explain: one word lasting far longer than its letters allow, or+ voice that no word covers."""+ spans = []+ for w in words:+ if w.end - w.start > max(0.6, plausible_length(w) + 0.3):+ spans.append((w.start, w.end))+ # Voice: everything between the quiet stretches.+ voiced, t = [], 0.0+ for q0, q1 in quiet:+ if q0 > t:+ voiced.append((t, q0))+ t = max(t, q1)+ if t < duration:+ voiced.append((t, duration))+ for v0, v1 in voiced:+ if v1 - v0 < 0.3:+ continue+ cuts = sorted((max(v0, w.start), min(v1, w.end)) for w in words if w.end > v0 and w.start < v1)+ pos = v0+ for a, b in cuts + [(v1, v1)]:+ if a - pos >= 0.3:+ spans.append((pos, a))+ pos = max(pos, b)+ spans.sort()+ merged: list[tuple[float, float]] = []+ for a, b in spans:+ if merged and a <= merged[-1][1] + 0.1:+ merged[-1] = (merged[-1][0], max(merged[-1][1], b))+ else:+ merged.append((a, b))+ return [(round(float(a), 2), round(float(b), 2)) for a, b in merged]+++def relisten(clip: str | os.PathLike, spans: list[tuple[float, float]], model: str = "small.en") -> dict:+ """What is heard in each span on its own, as {"a-b": [segments]}: each segment's text, the+ transcriber's confidence in it and its words (`_listen`). Kept in the clip's cache under+ `SECOND_KEY`, so each span is heard once per version."""+ clip = Path(clip).resolve()+ cache = _cache_path(clip)+ want = {_key(s) for s in spans}+ have = _second_store(json.loads(cache.read_text(encoding="utf-8")), model)["spans"]+ todo = [s for s in spans if _key(s) not in have]+ if todo:+ env = dict(os.environ, PYTHONPATH=str(paths.PACK) + os.pathsep + os.environ.get("PYTHONPATH", ""))+ env.setdefault("TOKENIZERS_PARALLELISM", "false")+ tmp = cache.with_name(f"{cache.stem}.second-{os.getpid()}.json.part")+ run = subprocess.run(+ [sys.executable, "-m", "fx.core.words", str(clip), "--model", model, "--quiet", "--out", str(tmp),+ "--spans", ",".join(_key(s) for s in todo)],+ env=env, capture_output=True, text=True,+ )+ if run.returncode == 0 and tmp.exists():+ heard = json.loads(tmp.read_text(encoding="utf-8"))+ tmp.unlink(missing_ok=True)+ # Read again before writing: another run may have added to the cache meanwhile.+ data = json.loads(cache.read_text(encoding="utf-8"))+ store = _second_store(data, model)+ store["spans"].update(heard)+ data[SECOND_KEY] = store+ part = cache.with_name(f"{cache.name}.{os.getpid()}.part")+ part.write_text(json.dumps(data, indent=1, ensure_ascii=False) + "\n")+ part.replace(cache)+ have = store["spans"]+ return {k: [_segment_from_json(seg) for seg in have[k]] for k in sorted(want) if k in have}+++def _second_store(data: dict, model: str) -> dict:+ """This version's second listen from a cache, or an empty one when it has none (or another's)."""+ store = data.get(SECOND_KEY)+ if (isinstance(store, dict) and store.get("version") == SECOND_VERSION and store.get("model") == model_key(model)+ and store.get("pad") == SECOND_PAD and isinstance(store.get("spans"), dict)):+ return store+ return {"version": SECOND_VERSION, "model": model_key(model), "pad": SECOND_PAD, "spans": {}}+++def _segment_json(seg: dict, offset: float) -> dict:+ return {"text": seg["text"], "no_speech_prob": round(seg["no_speech_prob"], 4),+ "avg_logprob": round(seg["avg_logprob"], 4), "compression_ratio": round(seg["compression_ratio"], 3),+ "words": to_json(Word(w.text, w.start + offset, w.end + offset, w.prob) for w in seg["words"])}+++def _segment_from_json(seg: dict) -> dict:+ return dict(seg, words=from_json(seg.get("words", [])))+++def _transcribe_spans(clip: Path, spans: list[tuple[float, float]], model: str) -> dict:+ from . import video++ info = video.probe(clip)+ samples = video.read_audio(info, rate=16000, channels=1)[:, 0]+ engine = _engine(model)+ out = {}+ for a, b in spans:+ lo = max(0.0, a - SECOND_PAD)+ chunk = samples[int(lo * 16000):int(min(len(samples) / 16000, b + SECOND_PAD) * 16000)]+ out[_key((a, b))] = [_segment_json(seg, lo) for seg in _listen(engine, chunk)]+ return out+++def _middle(w: Word) -> float:+ return (w.start + w.end) / 2+++def _overlap(a: Word, b: Word) -> float:+ return min(a.end, b.end) - max(a.start, b.start)+++def _loudest(env, t0: float, t1: float) -> float:+ """The level the sound between t0 and t1 reaches, in the envelope's dB: the loudest tenth of+ it, so one click does not count as a voice."""+ import numpy as np++ i0 = int(min(len(env.db) - 1, max(0, round(t0 / env.hop))))+ i1 = int(min(len(env.db), max(i0 + 1, round(t1 / env.hop))))+ return float(np.percentile(env.db[i0:i1], 90))+++def _sentence(seg: dict) -> bool:+ """A whole sentence of one or two words: "Hotel.", "Town car.", "Thanks.", "Why?"."""+ ws = [w for w in seg["words"] if w.key]+ return (1 <= len(ws) <= 2 and ws[0].text.lstrip("\"'")[:1].isupper()+ and ws[-1].text.rstrip("\"'").endswith((".", "!", "?")) and not ws[-1].text.endswith("..."))+++_DASHES = ("-", "—", "–")+++def _said_nearby(w: Word, said: list[Word], cut_off: bool) -> bool:+ """Is this word said in `said` (the first listen's words around the stretch)? A word cut off+ part-way ("perspec-") counts when a word said nearby begins with it."""+ if any(x.key == w.key for x in said):+ return True+ return cut_off and len(w.key) >= 2 and any(x.key.startswith(w.key) for x in said)+++def judge(segments: list[dict], span: tuple[float, float], first: list[Word], settled: list[Word],+ env, voiced: float) -> tuple[list[Word], list[Word]]:+ """What the second listen heard in `span`, each word left sure or marked unsure with the reason:+ (the stretch's own words, words it heard again from just outside the stretch).++ `first` is the first listen's words, `settled` those of them no stretch is heard again over,+ and `voiced` the level a word's sound must reach. A word is sure when all of these hold:++ 1. **There is voice under it.** The loudest tenth of its sound, inside the stretch, reaches+ `voiced`: the level the clip's own words reach (the core's speech envelope, halfway from+ the quiet between words to a typical syllable). A word with no length has no sound to hear.+ 2. **The transcriber was not unsure.** Its probability is at least `SURE_PROB`, and its+ segment's no_speech_prob at most `SURE_NO_SPEECH` and avg_logprob at least `SURE_LOGPROB`.+ 3. **It is not one of the transcriber's known inventions.** Kept narrow, because a real+ false start comes back from a second listen as a fragment ("From the perspective of-"),+ never as these:+ - a loop: the same few words over and over (`LOOP_RATIO`, `MOST_PER_SECOND`);+ - a stock phrase ("Thank you.", "Bye.");+ - a whole sentence of one or two words, the only thing heard in the stretch ("Hotel.",+ "Town car."): what it says to a sound it cannot place;+ - the first listen's own word beside the stretch, heard again: the same word, over the+ same sound ("Hotel." inside the first listen's "hotel.", 16.6-18.1 s on D).+ 4. **It is said nearby.** The second listen is there to find words said twice (a false start+ and its restart, a retake, a stammer), so a word it adds is one the speaker says within+ `NEARBY` seconds. One the speaker never says there is the transcriber guessing.+ """+ a, b = span+ heard = [] # (segment, word, cut off): a dash after a word comes back as a word of its own+ for seg in segments:+ ws = seg["words"]+ for i, w in enumerate(ws):+ if w.key:+ after = ws[i + 1].text.strip() if i + 1 < len(ws) else ""+ heard.append((seg, w, w.text.rstrip().endswith(_DASHES) or after in _DASHES))+ # The padding is there to make the first and last words whole: a word belongs to the stretch+ # when its middle is inside it.+ inside = [(seg, w, cut) for seg, w, cut in heard if a - 0.05 <= _middle(w) <= b + 0.05]+ alone = len([seg for seg in segments if any(w.key for w in seg["words"])]) == 1+ said = " ".join(w.key for _, w, _ in inside)+ nearby = [x for x in first if a - NEARBY <= x.start <= b + NEARBY]+ content, echoes = [], []+ # Each word keeps the first reason it fails, the most telling first.+ for seg, w, cut in inside:+ twin = next((x for x in settled if x.key == w.key and _overlap(x, w) > 0.02), None)+ if twin is not None:+ echoes.append(replace(w, unsure=f"the first listen's \"{twin.text}\" ({twin.start:.2f}-{twin.end:.2f} s) "+ f"heard again"))+ continue+ why = ""+ s0, s1 = max(w.start, a), min(w.end, b)+ if s1 - s0 < 0.02:+ s0, s1 = w.start, w.end+ if seg["compression_ratio"] > LOOP_RATIO or len(inside) > MOST_PER_SECOND * max(0.4, b - a):+ why = "a loop: the same few words over and over"+ elif said in _HALLUCINATIONS:+ why = f"\"{said}\" is what the transcriber says to sound it cannot make out"+ elif alone and _sentence(seg):+ why = f"\"{seg['text']}\", a whole sentence of one or two words alone in the stretch"+ elif w.end - w.start < 0.02:+ why = "no length of its own"+ elif _loudest(env, s0, s1) < voiced:+ why = f"no voice under it ({_loudest(env, s0, s1) - voiced:+.1f} dB from the clip's voiced level)"+ elif w.prob < SURE_PROB:+ why = f"the transcriber gave it {w.prob:.2f}"+ elif seg["no_speech_prob"] > SURE_NO_SPEECH:+ why = f"the transcriber put {seg['no_speech_prob']:.0%} on there being no speech"+ elif seg["avg_logprob"] < SURE_LOGPROB:+ why = f"the transcriber was unsure of the whole stretch (avg_logprob {seg['avg_logprob']:.2f})"+ elif not _said_nearby(w, nearby, cut):+ why = f"\"{w.clean}\" is not said within {NEARBY:.0f} s"+ content.append(replace(w, unsure=why))+ return content, echoes+++_FIGURE = re.compile(r"[\d%$£€]")+++def _figure(w: Word) -> bool:+ """A word that is a figure or a piece of one ("19", ".5%,", ",000", "$", "%")."""+ return bool(_FIGURE.search(w.text))+++def merge(words: list[Word], second: dict, env, voiced: Optional[float] = None) -> list[Word]:+ """The words, with what the second listen heard (`relisten`) judged (`judge`) and used.++ A stretch whose words are all sure replaces what the first listen wrote there; one where any+ word is unsure keeps the first listen's words, so a real word is never lost to a half-trusted+ hearing. Every word heard there that is not used is kept beside them, marked unsure.++ Figures are the first listen's. A figure read aloud is long ("197" is "one hundred and+ ninety-seven"), so it is often taken for a stretched word, and heard again out of its sentence+ its digits come back wrong: "19.5%" as "19 17 .5", "500,000" as "500 100,000". So where a+ stretch holds a figure, in either listen, and the second listen does not hear there exactly the+ words the first wrote, the first listen's words stay."""+ voiced = env.voiced if voiced is None else voiced+ spans = sorted((tuple(float(x) for x in k.split("-")), k) for k in second)+ heard_again = [any(a <= _middle(w) <= b for (a, b), _ in spans) for w in words]+ settled = [w for w, again in zip(words, heard_again) if not again]+ replaced: set[int] = set()+ added: list[Word] = []+ doubted: list[Word] = []+ for (a, b), key in spans:+ content, echoes = judge(second[key], (a, b), words, settled, env, voiced)+ doubted += echoes+ if not content:+ continue+ old = [i for i, w in enumerate(words) if heard_again[i] and a <= _middle(w) <= b]+ # A piece with no letters ("%", "-") is not a word heard differently: it never makes a+ # stretch differ, so a stretch heard the same keeps it.+ same = [w.key for w in content] == [words[i].key for i in old if words[i].key]+ figure = [x for x in words if _figure(x) and min(x.end, b) - max(x.start, a) > 0]+ if not same and (figure or any(_figure(w) for w in content)):+ first_said = " ".join(x.text for x in figure) or "no figure"+ content = [replace(w, unsure=f"inside a figure, heard as \"{' '.join(c.text for c in content)}\" where "+ f"the first listen heard \"{first_said}\", which stays") for w in content]+ why = next((w.unsure for w in content if w.unsure), "")+ if why:+ doubted += [w if w.unsure else replace(w, unsure=f"heard with an unsure word ({why})") for w in content]+ elif not same:+ replaced.update(old)+ added += content+ # (heard the same again: nothing changes)+ kept = [w for i, w in enumerate(words) if i not in replaced]+ # A word added that is the same as a word kept over the same sound would be shown twice.+ for w in list(added):+ twin = next((x for x in kept if x.key == w.key and _overlap(x, w) > 0.02), None)+ if twin is not None:+ added.remove(w)+ doubted.append(replace(w, unsure=f"the first listen's \"{twin.text}\" heard again"))+ return in_time(kept, added + doubted)+++# ---- corrections ---------------------------------------------------------------------------++def parse_fixes(spec: str | None) -> list[tuple[list[str], list[str]]]:+ """`"Jon=John; ask editor=AskEditor"` -> [(['jon'], ['John']), (['ask', 'editor'], ['AskEditor'])]."""+ fixes = []+ for part in re.split(r"[;\n]", spec or ""):+ if "=" not in part:+ continue+ wrong, right = part.split("=", 1)+ wrong_keys = [normalize(x) for x in wrong.split() if normalize(x)]+ right_words = right.split()+ if wrong_keys and right_words:+ fixes.append((wrong_keys, right_words))+ return fixes+++def apply_fixes(words: list[Word], spec: str | None) -> list[Word]:+ """Replace misheard words. Punctuation after the last replaced word is kept; the times of the+ words replaced are shared out across the words that replace them."""+ fixes = parse_fixes(spec)+ if not fixes:+ return list(words)+ if any(w.unsure for w in words) and not all(w.unsure for w in words):+ # The sure and the unsure words are corrected apart, so an unsure word heard in the middle+ # of a name never stops the name being put right. Each half is then all one kind and is+ # corrected below: splitting a half that is all unsure again would never end.+ return in_time(apply_fixes(sure(words), spec), apply_fixes([w for w in words if w.unsure], spec))+ out: list[Word] = []+ i = 0+ while i < len(words):+ for wrong, right in fixes:+ n = len(wrong)+ if [w.key for w in words[i:i + n]] == wrong:+ group = words[i:i + n]+ tail = re.search(r"[^\w']+$", group[-1].text)+ span0, span1 = group[0].start, group[-1].end+ step = (span1 - span0) / len(right)+ for k, r in enumerate(right):+ text = r + (tail.group(0) if tail and k == len(right) - 1 else "")+ out.append(Word(text, span0 + k * step, span0 + (k + 1) * step, min(w.prob for w in group),+ group[0].unsure))+ i += n+ break+ else:+ out.append(words[i])+ i += 1+ return out+++# ---- timing, refined against the sound ---------------------------------------------------------++# A speech recogniser marks a word's start after its sound has already begun. AskEditor measured+# about 50 ms on its own transcriber and pulls every start 0.1 s earlier; on this pack's test clips+# the transcriber here marked starts a median 0.13 s late after a real pause (39 onsets, 28 October+# 2026). Uncorrected, a cut or a word that appears on its start lands one to four frames late. So+# every start is pulled 0.1 s earlier, and then the sound has the last word: a start that the pull+# puts in the quiet before the word moves forward again to where the voice begins (`refine`).+HEARD_LATE = 0.10+# A quiet stretch at least this long inside a word's span is a real pause the transcriber folded+# into the word, not the short closure inside a word like "ex-pect".+FOLDED_PAUSE = 0.18+++def pull_starts(words: list[Word], by: float = HEARD_LATE) -> list[Word]:+ """Each start `by` seconds earlier, never before the word before it began. Ends are kept as heard."""+ out: list[Word] = []+ floor = 0.0+ for w in words:+ s = max(floor, w.start - by, 0.0)+ out.append(replace(w, start=s, end=max(w.end, s + 0.02)))+ floor = s + 0.02+ return out+++def refine(words: list[Word], quiet: list[tuple[float, float]]) -> list[Word]:+ """Pull word edges out of the quiet around them.++ The transcriber's word edges drift: it reports nearly every word as touching the next, so a+ word often 'starts' in the pause before it, 'ends' in the pause after it, or carries a whole+ pause inside its span. Where the sound says an edge sits in a quiet stretch, the edge moves to+ where the speech really begins or stops.+ """+ out = []+ for w in words:+ s, e = w.start, w.end+ for q0, q1 in quiet:+ if q1 <= s or q0 >= e:+ continue+ if q0 <= s and e <= q1: # the whole word sits in quiet: the sound is too soft to say+ continue+ if q0 <= s < q1: # starts in a quiet stretch: speech begins at its end+ s = q1 - 0.02+ elif q0 < e <= q1: # ends in a quiet stretch: speech stops at its start+ e = q0 + 0.03+ elif q1 - q0 >= FOLDED_PAUSE: # a pause folded inside the word+ # The transcriber stretches a word until the next one begins, so the word's own+ # sound is the part before the pause, unless almost nothing comes before it.+ if q0 - s >= 0.10:+ e = q0 + 0.03+ else:+ s = q1 - 0.02+ if e - s < 0.05:+ s, e = w.start, w.end+ out.append(replace(w, start=s, end=e))+ # A start still marked a little after the voice came back from a pause moves back to where it+ # came back, as long as no other word sits in between.+ for k, w in enumerate(out):+ prev_end = out[k - 1].end if k else 0.0+ for q0, q1 in quiet:+ if w.start - 0.15 <= q1 < w.start and q1 - q0 >= 0.08 and prev_end <= q1:+ out[k] = replace(w, start=max(prev_end, q1 - 0.02))+ break+ # Keep them in order and never overlapping. The start is the better-known edge (corrected, then+ # checked against the sound), so where two words overlap the earlier one's end gives way.+ for k in range(1, len(out)):+ if out[k].start < out[k - 1].end:+ prev = out[k - 1]+ if out[k].start - prev.start >= 0.05:+ out[k - 1] = replace(prev, end=out[k].start)+ else: # the earlier word would all but vanish: split the overlap instead+ mid = (out[k].start + prev.end) / 2+ out[k - 1] = replace(prev, end=max(prev.start + 0.02, mid))+ out[k] = replace(out[k], start=min(out[k].end - 0.02, mid))+ return out+++def unheard(word: Word, quiet: list[tuple[float, float]], prob: float = 0.5) -> bool:+ """A word the transcriber is unsure of whose whole span is quiet: a breath or a knock it put a+ word to. It is never captioned, and clean-cut treats it as part of the silence around it."""+ if word.prob >= prob:+ return False+ return any(q0 <= word.start + 0.02 and word.end - 0.02 <= q1 for q0, q1 in quiet)+++def timed(words: list[Word], quiet: list[tuple[float, float]]) -> list[Word]:+ """The words as the effects use them: starts corrected for the transcriber's lateness, both+ edges checked against the sound, and words nobody said left out, the unsure ones with them."""+ kept = [w for w in words if w.key and not w.unsure and not unheard(w, quiet)] # a lone "-" is not a word+ return refine(pull_starts(kept), quiet)+++def pause_after(words: list[Word], i: int, quiet: list[tuple[float, float]]) -> float:+ """How long the voice really stops after word `i`, read from the sound: the transcriber's own+ gaps are nearly always zero. 0 when the next word follows straight on."""+ if i + 1 >= len(words):+ return 0.0+ a, b = words[i].end, words[i + 1].start+ best = 0.0+ for q0, q1 in quiet:+ lo, hi = max(q0, a - 0.06), min(q1, b + 0.06)+ if hi > lo:+ best = max(best, hi - lo)+ return best+++def numbered(words: list[Word], per_line: int = 12) -> str:+ """The transcript with word numbers and times, for reading a plan."""+ lines, line = [], []+ for i, w in enumerate(words):+ if not line:+ line.append(f"[{i:>3} {w.start:6.2f}s]")+ line.append(w.text)+ if len(line) > per_line or w.ends_sentence:+ lines.append(" ".join(line))+ line = []+ if line:+ lines.append(" ".join(line))+ return "\n".join(lines)+++def main(argv: list[str] | None = None) -> int:+ ap = argparse.ArgumentParser(prog="python -m fx.core.words", description="Find the words of a clip.")+ ap.add_argument("clip")+ ap.add_argument("--model", default="small.en")+ ap.add_argument("--out", help="where to write the JSON (default: next to the clip)")+ ap.add_argument("--refresh", action="store_true", help="transcribe again even if a cache exists")+ ap.add_argument("--quiet", action="store_true")+ ap.add_argument("--spans", help="listen again to these stretches only (a-b,c-d) and write what is heard")+ args = ap.parse_args(argv)+ clip = Path(args.clip).resolve()+ if args.spans:+ spans = [tuple(float(x) for x in s.split("-")) for s in args.spans.split(",") if s]+ Path(args.out).write_text(json.dumps(_transcribe_spans(clip, spans, args.model), ensure_ascii=False) + "\n")+ return 0+ out = Path(args.out) if args.out else _cache_path(clip)+ try:+ fresh = out.exists() and _valid(json.loads(out.read_text(encoding="utf-8")), clip, args.model)+ except (json.JSONDecodeError, OSError):+ fresh = False+ if args.refresh or not fresh:+ data = transcribe(clip, args.model)+ tmp = out.with_suffix(".json.part")+ tmp.write_text(json.dumps(data, indent=1, ensure_ascii=False) + "\n")+ tmp.replace(out)+ if not args.quiet:+ words = from_json(json.loads(out.read_text(encoding="utf-8"))["words"])+ print(numbered(words))+ print(f"\n{len(words)} words · {out}")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/edit/askeditor/fx/core/zoom.py b/edit/askeditor/fx/core/zoom.pynew file mode 100644index 0000000..9ad0d1d--- /dev/null+++ b/edit/askeditor/fx/core/zoom.py@@ -0,0 +1,250 @@+"""A closer framing on the face: where the window goes, how it moves, and the picture inside it.++Shared by every effect that moves the camera (`transitions`' punch, `punch-in`, `hook`'s snap):++- `punch_window(size, zoom, head, centre)`: the window for a framing `zoom` times closer, about the+ face where it already is, with the whole head in, a tenth of the window above the crown and the+ band under the chin kept free for captions. A crown the recording already cut is left as shot.+ It answers with the zoom it could take, and says why when that is less than asked.+- `place_window(...)`: the same window at a zoom already decided (no search).+- `between(w0, w1, p, size)`: a window part of the way from one framing to another, never wider+ than the picture.+- `punch_progress(tau, d)`: how far a punch has gone, `tau` seconds after it lands: a short wind-up,+ past the new framing on the moment, and settled back onto it.+- `crop(img, window)`: the window filling the frame (an exact affine warp, so a window between+ pixels never steps).+- `ease(x)`: smooth in and out, 0 to 1.+- `CameraPath(size, moves)`: a camera over time: the whole frame, then each `Move` (a snap, a slow+ push, a cut, a smooth return) in turn, holding between them; `frame(img, t, fps)` is the picture+ it shows, smeared along the move while it moves fast.+- `aim(face, framing, first, last)`: the head over a stretch of frames, in output pixels, and where+ to aim at it.+"""++from __future__ import annotations++import math+from dataclasses import dataclass+from typing import Optional++import numpy as np++from .layout import Rect++CROWN = 0.10 # the room kept above the top of the head in a punched frame, as a share of its height+CHIN_LINE = 0.70 # a punch keeps the bottom of the head above this share of the frame's height+++def ease(x):+ """Smooth in and out, 0 to 1 (numbers or arrays)."""+ x = np.clip(x, 0.0, 1.0)+ return x * x * (3.0 - 2.0 * x)+++def place_window(size: tuple[int, int], z: float, head: Optional[Rect], cx: float, cy: float,+ line: Optional[float] = None) -> tuple[float, float, float, float]:+ W, H = size+ w, h = W / z, H / z+ # Zoom about the face where it already is: it grows on the spot instead of being moved to the+ # middle of the frame (which would drop the chin towards the captions' band and the bottom fifth).+ x, y = cx - (cx / W) * w, cy - (cy / H) * h+ if head is not None:+ top = head.y0 - CROWN * h # the window may start no lower than this (the crown's room)...+ chin = head.y1 + 0.04 * h - h # ...and no higher than this (the chin in)+ if line is not None: # nor so high that the chin drops past the line: the face rises instead+ chin = max(chin, head.y1 - line / z)+ y = min(y, top)+ if chin <= top:+ y = max(y, chin)+ x = min(x, head.x0 - 0.04 * w)+ x = max(x, head.x1 + 0.04 * w - w)+ x = min(max(0.0, x), W - w)+ y = min(max(0.0, y), H - h)+ return x, y, w, h+++def punch_window(size: tuple[int, int], zoom: float, head: Optional[Rect], centre: Optional[tuple[float, float]]+ ) -> tuple[tuple[float, float, float, float], float, str]:+ """The window for a framing `zoom` times closer, about the face (it grows where it is), keeping+ the whole head in with a tenth of the window above the crown, and the band under the chin free+ for the captions that come after (the bottom of the head above 70% of the frame, or no lower+ than it already was). A crown the recording itself already cut is left as it was shot (the+ window keeps to the top edge) rather than holding the punch back. Returns the window (x, y, w,+ h), the zoom it could take, and a note when that is less than asked."""+ W, H = size+ note = ""+ z = max(1.0, zoom)+ cx, cy = centre if centre is not None else (W / 2, H * 0.45)+ crown_cut = head is not None and head.y0 <= 0.01 * H+ if head is not None and z > 1.0:+ seen = Rect(head.x0, max(0.0, head.y0), head.x1, head.y1)+ room = 0.94 if crown_cut else (1 - CROWN - 0.06) # the crown's room, and a little under the chin+ most = max(1.0, min(0.86 * W / max(1.0, seen.w), room * H / max(1.0, seen.h)))+ if most < z - 1e-3:+ note = f"the head leaves room for {most:.2f}x, not {z:.2f}x"+ z = most+ line = max(CHIN_LINE * H, head.y1)+ roomy = z+ while z > 1.0:+ x, y, w, h = place_window(size, z, head, cx, cy, line)+ if (head.y1 - y) * (H / h) <= line + 0.5:+ break+ z = max(1.0, z - 0.01)+ if z < roomy - 1e-3:+ note = f"{z:.2f}x, to keep the band under the chin free for captions"+ return place_window(size, z, head, cx, cy, line), z, note+ return place_window(size, z, head, cx, cy), z, note+++def crop(img: np.ndarray, win: tuple[float, float, float, float]) -> np.ndarray:+ """The window of `img`, filling the frame: an affine warp, so a window between pixels is exact."""+ import cv2++ H, W = img.shape[:2]+ x, y, w, h = win+ if w >= W - 0.5 and h >= H - 0.5 and abs(x) < 0.5 and abs(y) < 0.5:+ return img+ sx, sy = W / w, H / h+ mat = np.float32([[sx, 0, -x * sx], [0, sy, -y * sy]])+ return cv2.warpAffine(img, mat, (W, H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)+++def between(w0, w1, p: float, size: Optional[tuple[int, int]] = None):+ """The window `p` of the way from w0 to w1 (past 1 overshoots), kept inside the picture: a+ framing can go closer than the shot, never wider than it."""+ x, y, w, h = (a + (b - a) * p for a, b in zip(w0, w1))+ if size is not None:+ W, H = size+ k = min(1.0, W / max(1e-6, w), H / max(1e-6, h))+ cx, cy = x + w / 2, y + h / 2+ w, h = w * k, h * k+ x = min(max(0.0, cx - w / 2), W - w)+ y = min(max(0.0, cy - h / 2), H - h)+ return x, y, w, h+++def punch_progress(tau: float, d: float) -> float:+ """How far a punch has gone (0 to 1, with a little overshoot), `tau` seconds after its join: it+ starts just before, lands past the new framing on the join, and settles back onto it."""+ pre = 0.2 * d+ if tau < -pre:+ return 0.0+ if tau < 0:+ return 0.45 * float(ease((tau + pre) / pre)) ** 1.5+ settle = max(0.05, 0.8 * d)+ return 1.0 + 0.09 * math.exp(-tau / (0.35 * settle)) * math.cos(math.pi * tau / settle)+++# ---- a camera that moves over time: a path of framings ------------------------------------------++Window = tuple[float, float, float, float]++CURVES = ("smooth", "snap", "slow", "cut")+++def curve(kind: str, u: float) -> float:+ """How far (0 to 1) a move of this kind has gone `u` of the way through its time.++ - smooth: eased in and out, for going back to the whole frame;+ - snap: fast off the mark and landing softly, for a quick punch onto a word;+ - slow: a gentle start and finish with a steady middle, for a push or a drift across a line;+ - cut: all at once, at its start."""+ u = min(1.0, max(0.0, u))+ if kind == "cut":+ return 1.0+ if kind == "snap":+ return 1.0 - (1.0 - u) ** 3+ if kind == "slow": # smootherstep: zero speed and zero acceleration at both ends+ return u * u * u * (u * (6.0 * u - 15.0) + 10.0)+ return float(ease(u))+++@dataclass+class Move:+ """The camera going from wherever it is at `start` to the framing `to`, arriving at `end`+ (output seconds). `settle` (seconds) lets a snap land a touch past `to` and settle back onto it,+ as a hand-held punch does."""+ start: float+ end: float+ to: Window+ kind: str = "smooth"+ settle: float = 0.0+++class CameraPath:+ """The framing at every moment, from the whole frame through each move in turn. Between moves+ the framing holds. A move that starts before the last one arrived leaves from where the camera+ is at that moment, so moves never jump."""++ def __init__(self, size: tuple[int, int], moves: list[Move]):+ self.size = (int(size[0]), int(size[1]))+ self.full: Window = (0.0, 0.0, float(self.size[0]), float(self.size[1]))+ self.moves = sorted(moves, key=lambda m: m.start)+ self._from: list[Window] = []+ for k, m in enumerate(self.moves):+ self._from.append(self._chain(k, m.start))++ def _chain(self, upto: int, t: float) -> Window:+ w = self.full+ for k in range(upto):+ m = self.moves[k]+ if t < m.start:+ break+ w = self._through(k, t)+ return w++ def _through(self, k: int, t: float) -> Window:+ m, w0 = self.moves[k], self._from[k]+ if m.kind == "cut" or t >= m.end:+ if m.settle > 0 and m.kind != "cut" and t < m.end + m.settle:+ tau = (t - m.end) / m.settle # a small overshoot past `to`, then back onto it+ return between(w0, m.to, 1.0 + 0.06 * math.sin(math.pi * tau) * (1.0 - tau), self.size)+ return m.to+ u = (t - m.start) / max(1e-6, m.end - m.start)+ return between(w0, m.to, curve(m.kind, u), self.size)++ def at(self, t: float) -> Window:+ """The framing at output second `t`."""+ return self._chain(len(self.moves), t)++ def zoom(self, t: float) -> float:+ return self.size[0] / max(1e-6, self.at(t)[2])++ def moving(self, t: float, dt: float) -> bool:+ a, b = self.at(t - dt), self.at(t)+ return max(abs(p - q) for p, q in zip(a, b)) > 0.004 * self.size[0]++ def frame(self, img: np.ndarray, t: float, fps: float, blur: bool = True) -> np.ndarray:+ """`img` (a whole output frame) as the camera frames it at `t`. While the framing moves fast+ enough to show, the frame is smeared over the second half of its own movement, as a camera's+ shutter would: a zoom blur that follows the move, never a fixed amount."""+ here = self.at(t)+ out = crop(img, here)+ dt = 1.0 / fps+ if not blur or t < dt or not self.moving(t, dt):+ return out+ if any(m.kind == "cut" and t - dt < m.start <= t + 1e-9 for m in self.moves):+ return out # a cut is a new framing, not a movement: nothing to smear+ prev = self.at(t - dt)+ acc = out.astype(np.float32)+ travel = max(abs(p - q) for p, q in zip(prev, here)) / max(1.0, self.size[0])+ steps = np.linspace(0.5, 0.95, int(np.clip(round(travel * 160), 6, 18))) # enough steps that the smear never bands+ for s in steps:+ acc += crop(img, between(prev, here, float(s))).astype(np.float32)+ return (acc / (len(steps) + 1)).astype(np.uint8)+++def aim(face, framing, first: int, last: int) -> tuple[Optional[Rect], Optional[tuple[float, float]]]:+ """The head to frame over source frames first..last, in output pixels: the box round it in every+ frame (so a movement inside a held framing never takes the crown out), and where to aim (the+ middle of the face, a little below the eyes). (None, None) when no face is found there."""+ if face is None or not face.any():+ return None, None+ step = max(1, (last - first) // 40 or 1)+ heads = [framing.to_output(h, j) for j in range(first, last + 1, step) if (h := face.head(j)) is not None]+ if not heads:+ return None, None+ union = Rect.around(heads)+ cx = float(np.median([h.cx for h in heads]))+ cy = float(np.median([h.y0 + 0.55 * h.h for h in heads]))+ return union, (cx, cy)diff --git a/edit/askeditor/fx/effects/__init__.py b/edit/askeditor/fx/effects/__init__.pynew file mode 100644index 0000000..84b46ef--- /dev/null+++ b/edit/askeditor/fx/effects/__init__.py@@ -0,0 +1,103 @@+"""The effects, one module each, and what each hands the runner.++An effect is two things, found by its id (say `words-behind`):++- `effects/words-behind/effect.json`: its manifest entry (title, line, options and their defaults,+ what to type, the AskEditor ask). `tools/build_manifest.py` assembles every entry into+ `effects.json`, the README's gallery and the table in SKILL.md;+- `fx/effects/words_behind.py`: `NAME`, `OPTIONS` (`{name: kind}` from `options.py`, the same+ names as the entry's options) and `prepare(clip, opts, plan=None) -> Job`, everything decided+ before a frame is drawn. A `plan` (the JSON a previous run wrote) is checked and used instead of+ deciding again. `run.py` renders the job, or draws its stills, through the same code.+ An effect that writes a file instead of a video (`post-copy`) sets `Job.writes`, and names the+ file's ending as `WRITES` (`".post.md"`), so its file sits beside the video as `<video>.post.md`.+ An effect that makes several files at once (`reframe` in every shape) returns a list of jobs, each+ with a `label`; one that only reads a video and reports (`qc-check`) sets `REPORTS = True` and+ gives `report(video, opts, out, still)` instead, which returns the exit code.++Nothing else needs touching to add an effect.+"""++from __future__ import annotations++import importlib+import json+from dataclasses import dataclass, field+from pathlib import Path+from typing import Callable, Optional++from ..core.clip import Clip+from ..core.framing import Framing+from ..core.paths import PACK+from ..core.render import Draw+from ..core.timeline import Timeline++EFFECTS = PACK / "effects"+++class PlanError(ValueError):+ """A plan that cannot be rendered; the message says what is wrong with it."""+++@dataclass+class Job:+ effect: str+ clip: Clip+ timeline: Timeline+ framing: Framing+ draw: Optional[Draw]+ plan: dict+ checks: dict = field(default_factory=dict)+ still_times: Callable[[], list[float]] = lambda: []+ after: Optional[Callable[[dict, Path], dict]] = None # runs once the video is written+ # Sounds the effect lays under the clip's own (a click on a press): given the output's sound+ # (samples, 48 kHz stereo float32) and its rate, returns the sound to write, the same length.+ sound: Optional[Callable] = None+ # What a `--still` run shows besides the frames, for an effect whose work is not in a frame (a+ # sound effect draws the planned mix as a picture): given the output path, writes its files and+ # returns {what: where} to print. Nothing is rendered.+ preview: Optional[Callable[[Path], dict]] = None+ # An effect whose work is words, not pictures (the copy to post with a video): given the output+ # path, writes its file there and returns {what: value} to print. No video is rendered and+ # `--still` draws nothing. A `failed` key that is true makes the command exit with 1.+ writes: Optional[Callable[[Path], dict]] = None+ # When `prepare` hands back several jobs (one file each), what tells this one's file from the+ # others: `talk-reframe-4x5.mp4` for the label "4x5". The first job's file is the output itself.+ label: str = ""+++def names() -> list[str]:+ """Every effect with a manifest entry, by id."""+ return sorted(p.parent.name for p in EFFECTS.glob("*/effect.json"))+++def manifest() -> list[dict]:+ """Every effect's manifest entry, read from its own folder (the source `effects.json` is built from)."""+ return [json.loads(p.read_text(encoding="utf-8")) for p in sorted(EFFECTS.glob("*/effect.json"))]+++def entry(name: str) -> dict:+ path = EFFECTS / name / "effect.json"+ if not path.exists():+ raise KeyError(name)+ return json.loads(path.read_text(encoding="utf-8"))+++def module_name(name: str) -> str:+ return "fx.effects." + name.replace("-", "_")+++def load(name: str):+ entry(name) # an effect is only runnable once it has a manifest entry+ try:+ module = importlib.import_module(module_name(name))+ except ModuleNotFoundError as e:+ if e.name == module_name(name):+ raise KeyError(name) from None+ raise+ spec = set(module.OPTIONS)+ defaults = set(entry(name)["options"])+ if spec != defaults:+ raise RuntimeError(f"{name}: effects/{name}/effect.json and {module_name(name)} disagree on the options "+ f"({', '.join(sorted(spec ^ defaults))})")+ return modulediff --git a/edit/askeditor/fx/effects/captions.py b/edit/askeditor/fx/effects/captions.pynew file mode 100644index 0000000..030758e--- /dev/null+++ b/edit/askeditor/fx/effects/captions.py@@ -0,0 +1,820 @@+"""captions: word-timed captions in four looks, placed where they never cover the face.++How a transcript becomes captions:++1. **Phrases are cut where a reader expects** (`fx/core/phrasing.py`, which every caption in the+ pack shares): at the end of a sentence or a long silence, then after a comma or a real pause in+ the voice, before a word that opens a clause, before one that opens a phrase. A card never ends+ on a word that leans forward ("the", "of", "is") in the middle of a sentence, never splits what+ is said as one ("right now", a name, a number and its unit), and holds at most `max_words`; the+ look's own number may be passed by one word to keep a phrase whole. A word is alone on a card+ only when it was said alone or is the point of its line.+2. **One key word, or none.** The key word is the most specific word in the phrase: a long word+ that is not grammar or filler, a number, a name. A phrase with nothing specific enough gets no+ key word rather than a highlighted "basically".+3. **Each look lays its phrase out** (`one-word`, `stacked`, `serif-chip`, `fitted`), bounded so+ a two-letter word is never huge and a long word never overflows.+4. **Placement keeps clear of the head** over every frame the phrase is on screen, not just its+ first: below the face at chest level, else in the lower third, else above the head, always+ inside the safe zone. The clip gets one steady place; a phrase moves only if it must.+5. **A short band is not a reason to squeeze.** When the head fills the frame (a close selfie, a+ tight wide-to-tall reframe) the band clear of it can be too short for a stacked card of two or+ three lines, which used to be drawn at half size or pushed out of the safe zone. Such a card is+ set flatter instead: on one line, else on two even lines. Where an effect gives the face itself (hairline to chin) and even one+ line cannot clear the whole head, the line may cross the top of the hair, never the face, and+ the report counts those frames as over the hair.+"""++from __future__ import annotations++import math+from dataclasses import dataclass, field+from typing import Callable, Optional++import numpy as np++from ..core import layout, moments, phrasing, text+from ..core.compose import Sprite, over+from ..core.layout import Rect, SafeZone+from ..core.moments import LEADS_ON as _LEADS_ON+from ..core.moments import NOT_KEY as _NOT_KEY+from ..core.moments import OPENS as _OPENS+from ..core.moments import bare, key_score, shown # noqa: F401 (key_score is read by other effects)+from ..core.words import HESITATIONS, Word, pause_after+from . import options as O++NAME = "captions"+LOOKS = ("stacked", "one-word", "serif-chip", "fitted")++OPTIONS = {+ "look": O.Choice(LOOKS, "stacked: two or three lines, the key word larger · one-word: one big word at a time · "+ "serif-chip: serif words in a dark rounded box, the spoken word brighter · "+ "fitted: one big accent word with the rest fitted around it"),+ "color": O.Colour("the accent colour (the key word; the spoken word in serif-chip): auto, a name such as "+ "yellow, green or pink, or a hex colour such as #ffd400"),+ "position": O.Choice(("auto", "bottom", "top"), "auto: below the face, else the lower third, else above the "+ "head · bottom · top. Never over the face, whichever you pick"),+ "max_words": O.Whole(0, 12, "the most words on screen at once; 0 lets the look decide"),+ "frame": O.Choice(("keep", "9:16"), "keep the clip's own shape, or make it 9:16 following the face"),+ "size": O.Size("auto (1080x1920 at most, never enlarged) or a size such as 1080x1920"),+ "fix": O.Text("misheard words as wrong=right, separated by ; e.g. \"Jon=John; ask editor=AskEditor\""),+}++# ---- the words no caption ever makes its key word -------------------------------------------+# Grammar, filler and words too vague to be the point of a line (`_NOT_KEY`), the words that lead+# into the next (`_LEADS_ON`) or open a clause (`_OPENS`), and how specific a word is (`key_score`)+# live in the core (`fx/core/moments.py`), where every picker reads them; they keep their names here.+++def key_word(words: list[Word], quiet=None, back: Optional[moments.TakenBack] = None) -> Optional[int]:+ """The word of a phrase set in the accent, or None when nothing stands out enough: the shared+ picker's (`moments.key_word`), the one headline and words-behind set: the thing named, at the end+ of its phrase, a tie going to the later word. Never a word the speaker took back (`back`, from+ the clip's whole words: "town" of "the lively town, or the lively city"); the word said instead+ counts as what its line says new. `quiet`: the clip's quiet stretches (a pause ends a phrase)."""+ return moments.key_word(words, [] if quiet is None else quiet, back)+++def _is_scrap(w: Word) -> bool:+ """A word that must never stand alone on screen or on a line."""+ return w.key in _NOT_KEY or len(w.key) <= 2+++# ---- phrasing --------------------------------------------------------------------------------+# Which words share a card is the core's (`fx/core/phrasing.py`), so every caption in the pack is+# cut the same way. What stays here is how long a card is on screen.++HOLD = 0.30 # how long a phrase stays after its last word when nothing follows straight away+MIN_ON = 0.55 # no phrase flashes by quicker than this+SHRINK, SHRINK_STEPS = 0.88, 6 # a card that does not fit is drawn this much smaller, up to this many times+# A stacked card drawn smaller than this for want of height (not width) is set flatter instead,+# and one drawn smaller than OVER_HAIR_BELOW (or not placed at all) may cross the top of the hair.+FLAT_BELOW = SHRINK ** 2 - 1e-9+OVER_HAIR_BELOW = SHRINK ** 3 - 1e-9+FLAT_STEPS = 2 # a one-line card is drawn at most this many steps smaller+++def phrases(words: list[Word], quiet: list[tuple[float, float]], most: int, over: int = 1) -> list[list[int]]:+ """Word indexes grouped into the phrases shown together: at most `most` words a card, or one+ more where that keeps a phrase whole (`over=0` when the person chose `most`)."""+ return phrasing.phrases(words, quiet, most, over)+++# ---- the looks -------------------------------------------------------------------------------++@dataclass+class Look:+ name: str+ most: int # words on screen at once, unless max_words says otherwise+ accent: str # the colour when color=auto+ reveal: bool # words appear one by one as they are said+++LOOK = {+ "stacked": Look("stacked", 4, "#ffd400", True),+ "one-word": Look("one-word", 1, "#ffd400", True),+ "serif-chip": Look("serif-chip", 6, "#ffffff", False),+ "fitted": Look("fitted", 5, "#ffd400", True),+}++INK = (255, 255, 255)+EDGE = (12, 12, 12)+DIM = (150, 150, 152) # the words of a serif chip that are not being said+++@dataclass+class Piece:+ sprite: Sprite+ x: float # top-left, relative to the card+ y: float+ on: float # when it appears (seconds)+ word: Optional[int] = None # the phrase's word it shows+ lit: Optional[Sprite] = None # how it looks while it is being said (serif-chip)+ pop: bool = True+++@dataclass+class Card:+ start: float+ end: float+ words: list[Word]+ key: Optional[int]+ w: float = 0.0+ h: float = 0.0+ pieces: list[Piece] = field(default_factory=list)+ x: float = 0.0+ y: float = 0.0+ where: str = ""+ scale: float = 1.0+ flat: int = 0 # a stacked card set flatter, for a band too short for it: 1 on one line, 2 on two even lines++ @property+ def rect(self) -> Rect:+ return Rect(self.x, self.y, self.x + self.w, self.y + self.h)+++def _shadow(px: float) -> tuple[float, float, float, float]:+ return (0.0, 0.045 * px, 0.055 * px, 0.55)+++def _bounds(pieces: list[Piece]) -> tuple[float, float, float, float]:+ x0 = min(p.x for p in pieces)+ y0 = min(p.y for p in pieces)+ x1 = max(p.x + p.sprite.w for p in pieces)+ y1 = max(p.y + p.sprite.h for p in pieces)+ return x0, y0, x1, y1+++def _finish(card: Card, pieces: list[Piece]) -> None:+ x0, y0, x1, y1 = _bounds(pieces)+ for p in pieces:+ p.x -= x0+ p.y -= y0+ card.pieces = pieces+ card.w, card.h = x1 - x0, y1 - y0+++def _even_lines(idx: list[int], widths: list[float], space: float, limit: float,+ scrap: Callable[[int], bool], fit_one: int = 3) -> list[list[int]]:+ """Break word indexes into one or two lines, as even in width as possible, never leaving a+ short word alone on a line, and within `limit` if it can be. Up to `fit_one` words that fit+ stay on one line."""+ n = len(idx)+ total = sum(widths) + space * (n - 1)+ if n <= 1 or (total <= limit and n <= fit_one):+ return [idx]+ best, best_cost = [idx], math.inf+ for cut in range(1, n):+ a, b = idx[:cut], idx[cut:]+ wa = sum(widths[:cut]) + space * (cut - 1)+ wb = sum(widths[cut:]) + space * (n - cut - 1)+ cost = abs(wa - wb) + (10 * limit if max(wa, wb) > limit else 0)+ for part in (a, b):+ if len(part) == 1 and scrap(part[0]):+ cost += 3 * limit+ if cost < best_cost:+ best, best_cost = [a, b], cost+ return best+++def _layout_stacked(card: Card, W: int, H: int, zone_w: float, accent, scale: float, flat: int = 0) -> None:+ # The key word is larger, but the words around it stay at about 70% of its height so the line+ # still reads at phone size, and they are never taken below that to make the key word fit.+ base = max(8, int(round(0.046 * H * scale)))+ big = max(base + 2, int(round(base * 1.42)))+ limit = 0.94 * zone_w+ words = card.words+ k = card.key+ labels = [shown(w).upper() if i != k else bare(w).upper() for i, w in enumerate(words)]++ def style(i: int) -> tuple[str, int, tuple]:+ return ("poppins-black", big, accent) if i == k else ("poppins-extrabold", base, INK)++ # Lines: the words before the key word, the key word, the words after it. A short word that+ # would sit alone on a line rides with the key word instead.+ if flat == 1: # every word on one line, the key word still larger+ lines = [list(range(len(words)))]+ elif flat == 2: # two lines as even as can be, the key word larger inside its line+ idx = list(range(len(words)))+ widths = [text.advance(labels[i], *style(i)[:2]) for i in idx]+ lines = _even_lines(idx, widths, text.advance(" ", "poppins-extrabold", base), limit,+ lambda i: _is_scrap(words[i]), fit_one=0)+ elif k is not None:+ before, after = list(range(0, k)), list(range(k + 1, len(words)))+ middle = [k]+ if len(before) == 1 and _is_scrap(words[before[0]]):+ middle, before = before + middle, []+ if len(after) == 1 and _is_scrap(words[after[0]]):+ middle, after = middle + after, []+ lines = [ln for ln in (before, middle, after) if ln]+ else:+ idx = list(range(len(words)))+ widths = [text.advance(labels[i], "poppins-extrabold", base) for i in idx]+ lines = _even_lines(idx, widths, text.advance(" ", "poppins-extrabold", base), limit,+ lambda i: _is_scrap(words[i]))+ # Shrink the key word (and only it) if its line would run past the width.+ for ln in lines:+ if k in ln:+ while big > base + 2:+ width = sum(text.advance(labels[i], *style(i)[:2]) for i in ln) + text.advance(" ", "poppins-extrabold", base) * (len(ln) - 1)+ if width <= limit:+ break+ big -= 2+ pieces: list[Piece] = []+ y_base = 0.0+ gap = 0.26 * text.cap_height("poppins-extrabold", base)+ for li, ln in enumerate(lines):+ caps = [text.cap_height(style(i)[0], style(i)[1]) for i in ln]+ y_base += (gap if li else 0) + max(caps)+ space = text.advance(" ", "poppins-extrabold", base)+ widths = [text.advance(labels[i], style(i)[0], style(i)[1]) for i in ln]+ line_w = sum(widths) + space * (len(ln) - 1)+ pen = -line_w / 2+ for i, wdt in zip(ln, widths):+ face, px, fill = style(i)+ d = text.draw_word(labels[i], face, px, fill=fill, outline=0.075 * px, outline_fill=EDGE, shadow=_shadow(px))+ pieces.append(Piece(d.sprite, pen - d.ox, y_base - d.oy, words[i].start, word=i))+ pen += wdt + space+ _finish(card, pieces)+++def _layout_one_word(card: Card, W: int, H: int, zone_w: float, accent, scale: float) -> None:+ w = card.words[0]+ label = (bare(w) if card.key == 0 else shown(w)).upper()+ px = int(round(0.098 * H * scale))+ px = min(px, text.fit_px(label, "anton", 0.92 * zone_w))+ fill = accent if card.key == 0 else INK+ d = text.draw_word(label, "anton", px, fill=fill, outline=0.06 * px, outline_fill=EDGE, shadow=_shadow(px))+ _finish(card, [Piece(d.sprite, -d.ox, -d.oy, w.start, word=0)])+++def _layout_serif_chip(card: Card, W: int, H: int, zone_w: float, accent, scale: float) -> None:+ face = "dm-serif"+ px = max(8, int(round(0.037 * H * scale)))+ labels = [shown(w) for w in card.words]+ space = text.advance(" ", face, px)+ pad_x, pad_y = 0.42 * px, 0.24 * px+ limit = 0.94 * zone_w - 2 * pad_x+ widths = [text.advance(s, face, px) for s in labels]+ while sum(widths) + space * (len(widths) - 1) > 2 * limit and px > 8: # two full lines at most+ px -= 1+ space = text.advance(" ", face, px)+ widths = [text.advance(s, face, px) for s in labels]+ pad_x, pad_y = 0.42 * px, 0.24 * px+ idx_lines = _even_lines(list(range(len(card.words))), widths, space, limit,+ lambda i: _is_scrap(card.words[i]), fit_one=4)+ # One line's height from the face's own letters: the top of a tall letter to the foot of a+ # letter that hangs below the line.+ top = -text.ink("Hdlk", face, px)[1]+ foot = text.ink("gjpqy", face, px)[3]+ pitch = (top + foot) * 1.06+ dim = DIM+ block_w = max(sum(widths[i] for i in ln) + space * (len(ln) - 1) for ln in idx_lines)+ box_w = block_w + 2 * pad_x+ box_h = pitch * (len(idx_lines) - 1) + top + foot + 2 * pad_y+ box = text.rounded_box(box_w, box_h, radius=0.34 * px, fill=(16, 16, 18), opacity=0.84)+ pieces = [Piece(box, -box_w / 2, 0.0, card.start, pop=False)]+ for li, ln in enumerate(idx_lines):+ y_base = pad_y + top + li * pitch+ line_w = sum(widths[i] for i in ln) + space * (len(ln) - 1)+ pen = -line_w / 2+ for i in ln:+ plain = text.draw_word(labels[i], face, px, fill=dim)+ lit = text.draw_word(labels[i], face, px, fill=accent)+ pieces.append(Piece(plain.sprite, pen - plain.ox, y_base - plain.oy, card.start, word=i,+ lit=lit.sprite, pop=False))+ pen += widths[i] + space+ _finish(card, pieces)+++def _balanced(idx: list[int], widths: list[float], parts: int, scrap: Callable[[int], bool]) -> list[list[int]]:+ """Split word indexes into `parts` lines as even in width as possible, no short word alone."""+ n = len(idx)+ if parts <= 1 or n <= 1:+ return [idx]+ parts = min(parts, n)+ best: Optional[list[list[int]]] = None+ best_cost = math.inf++ def walk(start: int, left: int, acc: list[list[int]]) -> None:+ nonlocal best, best_cost+ if left == 1:+ lines = acc + [idx[start:]]+ ws = [sum(widths[idx.index(i)] for i in ln) for ln in lines]+ cost = max(ws) - min(ws) + sum(10 ** 6 for ln in lines if len(ln) == 1 and scrap(ln[0]))+ if cost < best_cost:+ best, best_cost = lines, cost+ return+ for cut in range(start + 1, n - left + 2):+ walk(cut, left - 1, acc + [idx[start:cut]])++ walk(0, parts, [])+ return best or [idx]+++def _layout_fitted(card: Card, W: int, H: int, zone_w: float, accent, scale: float) -> None:+ """The key word big in the accent, the words before it above and after it below, each line+ set as wide as the key word where it can be, so the phrase reads as one block. The words+ around the key word stay between 58% and 72% of its height: a line too long for that is split+ in two rather than shrunk. With no key word the phrase is one or two lines of one size."""+ face = "anton"+ words, k = card.words, card.key+ per_px = text.cap_height(face, 200) / 200.0 # cap height per pixel of size+ wmax = 0.9 * zone_w+ labels = [(bare(w) if i == k else shown(w)).upper() for i, w in enumerate(words)]+ gap_k = 0.28 # the space between words, as a share of the size++ def joined(ln: list[int]) -> str:+ return " ".join(labels[i] for i in ln)++ def scrap(i: int) -> bool:+ return _is_scrap(words[i])++ if k is not None:+ before, middle, after = list(range(0, k)), [k], list(range(k + 1, len(words)))+ # A short word that would stand alone on a line rides on the key word's line instead.+ if len(before) == 1 and scrap(before[0]):+ middle, before = before + middle, []+ if len(after) == 1 and scrap(after[0]):+ middle, after = middle + after, []+ key_px = int(0.084 * H * scale / per_px)+ if text.advance(joined(middle), face, key_px) > wmax:+ key_px = text.fit_px(joined(middle), face, wmax)+ block = max(text.advance(joined(middle), face, key_px), 0.55 * wmax)+ lo, hi = 0.58 * key_px, 0.72 * key_px+ groups: list = [before, None, after]+ else:+ key_px, middle = 0, []+ hi = 0.062 * H * scale / per_px+ lo = 0.8 * hi+ block = 0.8 * wmax+ groups = [list(range(len(words)))]+ lines: list[tuple[list[int], int]] = []+ for g in groups:+ if g is None:+ lines.append((middle, key_px))+ continue+ if not g:+ continue+ widths = [text.advance(labels[i], face, 100) for i in g]+ done = None+ for parts in range(1, min(3, len(g)) + 1):+ sized = []+ for part in _balanced(g, widths, parts, scrap):+ px = min(hi, text.fit_px(joined(part), face, block))+ if px < lo:+ if text.advance(joined(part), face, int(lo)) > wmax:+ sized = None+ break+ px = lo # wider than the key word, but still inside the safe zone+ sized.append((part, int(px)))+ if sized:+ done = sized+ break+ if done is None: # three lines at the smallest size still do not fit: fit each line+ done = [(part, text.fit_px(joined(part), face, wmax)) for part in _balanced(g, widths, 3, scrap)]+ lines.extend(done)+ pieces: list[Piece] = []+ y_base = 0.0+ prev_cap = None+ for ln, px in lines:+ cap = px * per_px+ y_base += (0.17 * min(cap, prev_cap) if prev_cap else 0.0) + cap+ prev_cap = cap+ space = px * gap_k+ ws = [text.advance(labels[i], face, px) for i in ln]+ pen = -(sum(ws) + space * (len(ln) - 1)) / 2+ for i, wdt in zip(ln, ws):+ fill = accent if i == k else INK+ d = text.draw_word(labels[i], face, px, fill=fill, outline=0.05 * px, outline_fill=EDGE, shadow=_shadow(px))+ pieces.append(Piece(d.sprite, pen - d.ox, y_base - d.oy, words[i].start, word=i))+ pen += wdt + space+ _finish(card, pieces)+++LAYOUTS: dict[str, Callable] = {+ "stacked": _layout_stacked,+ "one-word": _layout_one_word,+ "serif-chip": _layout_serif_chip,+ "fitted": _layout_fitted,+}+++# ---- the captions of one output --------------------------------------------------------------++def _ease(x: float) -> float:+ x = min(1.0, max(0.0, x))+ return 1.0 - (1.0 - x) ** 3+++class Captions:+ """Every card of one output, laid out and placed, ready to draw on its frames."""++ def __init__(self, words: list[Word], quiet: list[tuple[float, float]], size: tuple[int, int], fps: float,+ n_frames: int, head_at: Callable[[int], Optional[Rect]], look: str = "stacked",+ color: str = "auto", position: str = "auto", max_words: int = 0,+ cards: Optional[list[dict]] = None, face_at: Optional[Callable[[int], Optional[Rect]]] = None):+ self.W, self.H = size+ self.fps = fps+ self.n = n_frames+ self.look = LOOK[look]+ self.accent = text.colour(self.look.accent if color in ("auto", "", None) else color)+ self.position = position+ self.zone = SafeZone(self.W, self.H)+ self.heads = [head_at(j) for j in range(n_frames)]+ # The face alone (hairline to chin), when the effect gives it: what a line may never cross even+ # where the head leaves no room (see `_flatter`).+ self.faces = [face_at(j) for j in range(n_frames)] if face_at is not None else None+ self.warnings: list[str] = []+ # What the speaker took back is never the accent: read from the words given, fillers and all.+ self.back = moments.taken_back(words, quiet)+ self.quiet = quiet+ # An "um" is heard, never shown; nor is a word the second listen could not be sure of.+ words = [w for w in words if w.key not in HESITATIONS and not w.unsure]+ most = max_words or self.look.most+ if cards is not None:+ self.cards = [self._card_from_plan(c) for c in cards]+ else: # a number the person chose is never passed; the look's own may be, by one word+ self.cards = self._cards(words, quiet, most, over=0 if max_words else 1)+ self._time()+ for c in self.cards:+ self._layout(c, 1.0)+ self._place()++ # -- which words go together, and for how long+ def _cards(self, words: list[Word], quiet, most: int, over: int = 1) -> list[Card]:+ if self.look.name == "one-word":+ # Key words are chosen among the phrases a reader would hear, then shown one at a time.+ keys = set()+ for ph in phrases(words, quiet, 4):+ k = key_word([words[i] for i in ph], quiet, self.back)+ if k is not None:+ keys.add(ph[k])+ return [Card(w.start, w.end, [w], 0 if i in keys else None) for i, w in enumerate(words)]+ out = []+ for ph in phrases(words, quiet, most, over):+ for part in self._at_full_size(ph, words, quiet, most):+ ws = [words[i] for i in part]+ out.append(Card(ws[0].start, ws[-1].end, ws, key_word(ws, quiet, self.back)))+ return out++ def _at_full_size(self, ph: list[int], words: list[Word], quiet, most: int) -> list[list[int]]:+ """A phrase given one word more than the look's number keeps it, unless that costs its type+ its size. The stacked look sets the words either side of its key word on one line each, and+ four there can run so far past the safe zone that the card is drawn at half size. When the+ phrase's halves could each be drawn at least two steps larger, and its best place to cut+ breaks nothing, it is cut there instead ("The marketing platform | of UGC")."""+ if len(ph) <= most:+ return [ph]+ whole = self._fitting_scale([words[i] for i in ph])+ if whole >= 1.0:+ return [ph]+ parts = phrasing.split_run(words, ph, quiet, most, over=0)+ if any(len(p) < 2 for p in parts) or any(+ phrasing.cut_cost(words, p[-1], quiet) > phrasing.INSIDE_A_PHRASE for p in parts[:-1]):+ return [ph]+ halves = min(self._fitting_scale([words[i] for i in p]) for p in parts)+ return parts if halves >= whole / SHRINK ** 2 - 1e-9 else [ph]++ def _fitting_scale(self, ws: list[Word]) -> float:+ """The size these words would be drawn at, as one card, to stay inside the safe zone's width:+ full size (1), or one of the steps `_place` shrinks a card by."""+ card = Card(ws[0].start, ws[-1].end, ws, key_word(ws, self.quiet, self.back))+ scale = 1.0+ for step in range(SHRINK_STEPS + 1):+ if step:+ scale *= SHRINK+ self._layout(card, scale)+ if card.w <= self.zone.rect.w:+ break+ return scale++ def _card_from_plan(self, c: dict) -> Card:+ ws = [Word(str(x["w"]), float(x["s"]), float(x["e"])) for x in c["words"]]+ key = c.get("key")+ if key is not None and not (0 <= int(key) < len(ws)):+ raise ValueError(f"a card's key {key} is not one of its {len(ws)} words")+ return Card(ws[0].start, ws[-1].end, ws, None if key is None else int(key))++ def _time(self) -> None:+ cards = self.cards+ for i, c in enumerate(cards):+ nxt = cards[i + 1].start if i + 1 < len(cards) else math.inf+ last = c.words[-1]+ if self.look.name == "one-word":+ end = nxt if nxt - last.end < 0.45 else last.end + 0.25+ end = max(end, min(nxt, c.start + 0.2))+ else:+ end = min(nxt, last.end + HOLD)+ if end - c.start < MIN_ON:+ end = min(nxt, c.start + MIN_ON)+ c.end = max(c.start + 1.0 / self.fps, end)++ def _layout(self, c: Card, scale: float) -> None:+ c.scale = scale+ if c.flat:+ _layout_stacked(c, self.W, self.H, self.zone.rect.w, self.accent, scale, flat=c.flat)+ return+ LAYOUTS[self.look.name](c, self.W, self.H, self.zone.rect.w, self.accent, scale)++ def _width_scale(self, c: Card) -> float:+ """The size the card must be drawn at to fit the safe zone's width (1, or a shrink step); the+ card is left laid out at full size."""+ scale = 1.0+ for step in range(SHRINK_STEPS + 1):+ if step:+ scale *= SHRINK+ self._layout(c, scale)+ if c.w <= self.zone.rect.w:+ break+ self._layout(c, 1.0)+ return scale++ def _frames(self, c: Card) -> tuple[int, int]:+ first = int(max(0, math.floor(c.start * self.fps)))+ last = int(min(self.n - 1, math.ceil(c.end * self.fps)))+ return first, max(first, last)++ def _head_over(self, c: Card, boxes: Optional[list] = None) -> Optional[Rect]:+ a, b = self._frames(c)+ boxes = self.heads if boxes is None else boxes+ return Rect.around(h for h in boxes[a:b + 1] if h is not None)++ @staticmethod+ def _every(boxes: list) -> Optional[Rect]:+ found = [h for h in boxes if h is not None]+ if not found:+ return None+ arr = np.array([[h.x0, h.y0, h.x1, h.y1] for h in found])+ return Rect(float(np.percentile(arr[:, 0], 2)), float(np.percentile(arr[:, 1], 2)),+ float(np.percentile(arr[:, 2], 98)), float(np.percentile(arr[:, 3], 98)))++ # -- where each card goes+ def _place(self) -> None:+ zone = self.zone+ gap = 0.024 * self.H+ every = self._every(self.heads)+ order = layout.ORDERS[self.position]+ tallest = max((c.h for c in self.cards), default=0.0)+ widest = max((c.w for c in self.cards), default=0.0)+ anchor = None+ if every is not None and self.cards:+ for where in order:+ if layout.place(widest, tallest, zone, every, order=(where,), gap=gap):+ anchor = where+ break+ self.anchor = anchor or ("lower-third" if every is None else order[0])+ for c in self.cards:+ stacked = self.look.name == "stacked" and len(c.words) > 1+ wide = self._width_scale(c) if stacked else 1.0+ placed = False+ for attempt in range(SHRINK_STEPS + 1):+ if attempt:+ self._layout(c, c.scale * SHRINK)+ if self._try_place(c, every, gap, order):+ placed = True+ break+ if placed and (not stacked or c.scale >= FLAT_BELOW or c.scale >= wide - 1e-9):+ continue # drawn at its size, or as small as its width (not the band's height) asks+ was = (c.scale, c.x, c.y, c.where)+ hair = not placed or c.scale < OVER_HAIR_BELOW+ if stacked and self._flatter(c, every, gap, order, hair):+ continue+ c.flat = 0+ self._layout(c, was[0])+ if placed:+ c.x, c.y, c.where = was[1], was[2], was[3]+ else:+ self._last_resort(c)++ def _flatter(self, c: Card, every: Optional[Rect], gap: float, order, hair: bool) -> bool:+ """A stacked card the band clear of the head is too short for, set flatter (on one line, else on+ two even lines): clear of the whole head if it fits there, else (when `hair`, and the effect gave+ the face) clear of the face alone, over the top of the hair. False, with the card as it was,+ when none of these fits."""+ tries = [(None, every, "")]+ if hair and self.faces is not None:+ tries.append((self.faces, self._every(self.faces), " over the hair"))+ for boxes, ev, said in tries:+ for flat in (1, 2):+ c.flat = flat+ for step in range(FLAT_STEPS + 1):+ self._layout(c, SHRINK ** step)+ if self._try_place(c, ev, gap, order, boxes):+ c.where += said+ return True+ c.flat = 0+ return False+ def _last_resort(self, c: Card) -> None:+ """Nothing fits inside the safe zone clear of the head. Covering the face is the one thing+ never done, so the words go into the margin the app's own buttons use, the side away from+ the head, and the report says so."""+ head = self._head_over(c)+ c.x = self.zone.rect.cx - c.w / 2+ room_above = head.y0 if head is not None else 0.0+ room_below = self.H - head.y1 if head is not None else self.H+ if room_below >= room_above:+ c.y = min(self.H - c.h - 0.01 * self.H, max(head.y1 + 0.01 * self.H if head else 0.0, self.zone.rect.y1 - c.h))+ else:+ c.y = max(0.01 * self.H, min(head.y0 - 0.01 * self.H - c.h, self.zone.rect.y0))+ c.where = "outside the safe zone"+ clear = head is None or not c.rect.intersects(head)+ self.warnings.append(f"the words at {c.start:.2f} s did not fit inside the safe zone clear of the face; "+ + ("they sit outside the safe zone" if clear else "they could not be kept off the face"))++ def _try_place(self, c: Card, every: Optional[Rect], gap: float, order, boxes: Optional[list] = None) -> bool:+ zone = self.zone+ head = self._head_over(c, boxes)+ x0 = zone.rect.cx - c.w / 2+ # The clip's steady place first.+ if every is not None:+ if self.anchor == "chest":+ y0 = max(every.y1 + gap, zone.rect.y0)+ elif self.anchor == "lower-third":+ y0 = zone.rect.y1 - 0.01 * self.H - c.h+ else:+ y0 = min(every.y0 - gap, zone.rect.y1) - c.h+ r = Rect(x0, y0, x0 + c.w, y0 + c.h)+ if zone.contains(r) and (head is None or not r.intersects(head, margin=gap * 0.5)):+ c.x, c.y, c.where = r.x0, r.y0, self.anchor+ return True+ if head is None:+ y0 = zone.rect.y1 - 0.01 * self.H - c.h+ r = Rect(x0, y0, x0 + c.w, y0 + c.h)+ if zone.contains(r):+ c.x, c.y, c.where = r.x0, r.y0, "lower-third"+ return True+ return False+ rest = (self.anchor,) + tuple(o for o in order if o != self.anchor)+ p = layout.place(c.w, c.h, zone, head, order=rest, gap=gap)+ if p is None:+ return False+ c.x, c.y, c.where = p.rect.x0, p.rect.y0, p.where+ return True++ # -- drawing+ def active(self, t: float) -> list[Card]:+ return [c for c in self.cards if c.start <= t < c.end]++ def _look_of(self, c: Card, p: Piece, t: float) -> tuple[float, float]:+ """A piece's opacity and scale at time t. A frame shows the moment it starts, so the frame a+ word appears on already counts as one frame into its pop: starting from nothing would leave+ a blank frame wherever one phrase follows straight on from another."""+ step = 1.0 / self.fps+ if p.pop and self.look.reveal:+ k = t - p.on + step+ return _ease(k / 0.06), 0.9 + 0.1 * _ease(k / 0.1)+ return _ease((t - c.start + step) / 0.08), 1.0++ def draw(self, frame: np.ndarray, j: int, t: float) -> None:+ for c in self.active(t):+ current = None+ if self.look.name == "serif-chip":+ said = [i for i, w in enumerate(c.words) if w.start <= t]+ current = said[-1] if said else None+ for p in c.pieces:+ if self.look.reveal and t < p.on:+ continue+ alpha, scale = self._look_of(c, p, t)+ sprite = p.lit if (p.lit is not None and p.word == current) else p.sprite+ if scale < 0.999:+ s = sprite.scaled(scale)+ cx = c.x + p.x + sprite.w / 2+ cy = c.y + p.y + sprite.h / 2+ over(frame, s, cx - s.w / 2, cy - s.h / 2, alpha)+ else:+ over(frame, sprite, c.x + p.x, c.y + p.y, alpha)++ # -- what a person (or the matrix) checks+ def report(self) -> dict:+ over_face = 0+ over_hair = 0+ outside = 0+ for j in range(self.n):+ t = j / self.fps+ act = self.active(t)+ if not act:+ continue+ h = self.heads[j]+ f = self.faces[j] if self.faces is not None else h+ for c in act:+ if f is not None and c.rect.intersects(f):+ over_face += 1+ elif h is not None and c.rect.intersects(h):+ over_hair += 1+ if not self.zone.contains(c.rect):+ outside += 1+ # How visible each phrase is on the first frame it is on screen: a phrase that starts+ # invisible right after another one ends is a blank frame, a flicker.+ first_frame = []+ for c in self.cards:+ t0 = math.ceil(c.start * self.fps - 1e-6) / self.fps+ shown = [self._look_of(c, p, t0)[0] for p in c.pieces if not (self.look.reveal and t0 < p.on)]+ first_frame.append(max(shown, default=0.0))+ where = {}+ for c in self.cards:+ where[c.where] = where.get(c.where, 0) + 1+ out = {"cards": len(self.cards), "with_key_word": sum(c.key is not None for c in self.cards),+ "frames_over_face": over_face, "frames_outside_safe_zone": outside, "placed": where,+ "least_visible_first_frame": round(min(first_frame, default=1.0), 2),+ "shrunk": sum(c.scale < 1 for c in self.cards), "warnings": list(self.warnings)}+ if self.faces is not None:+ out["frames_over_hair"] = over_hair+ if any(c.flat for c in self.cards):+ out["set_flatter"] = {"one line": sum(c.flat == 1 for c in self.cards),+ "two lines": sum(c.flat == 2 for c in self.cards)}+ return out++ def plan(self) -> list[dict]:+ return [{"start": round(c.start, 3), "end": round(c.end, 3), "where": c.where,+ "rect": c.rect.as_list(), "key": c.key, **({"lines": c.flat} if c.flat else {}),+ "text": " ".join(shown(w) for w in c.words),+ "words": [{"w": w.text, "s": round(w.start, 3), "e": round(w.end, 3)} for w in c.words]}+ for c in self.cards]++ def busy_times(self, count: int = 6) -> list[float]:+ """`count` moments spread across the output, each in the middle of a card with all its+ words showing: what a contact sheet should show."""+ if not self.cards:+ return []+ picks = np.linspace(0, len(self.cards) - 1, min(count, len(self.cards))).round().astype(int)+ out = []+ for i in picks:+ c = self.cards[int(i)]+ t = max(c.words[-1].start + 0.12, (c.start + c.end) / 2)+ out.append(min(c.end - 0.5 / self.fps, t))+ return out+++# ---- the effect --------------------------------------------------------------------------------++def unsure_words(clip) -> list[dict]:+ """The words heard but never shown, with why: what a plan records so nothing heard is lost."""+ from ..core.words import unsure_stretches++ return unsure_stretches(clip.unsure)+++def head_in_output(clip, timeline, fr):+ """The head's box at each output frame, in output pixels (None where no face is known)."""+ face = clip.face+ fps, n_src = clip.info.rate, clip.info.frames++ def at(j: int) -> Optional[Rect]:+ k = timeline.source_frame(j, fps, n_src)+ h = face.head(k)+ return fr.to_output(h, k) if h is not None else None++ return at+++def prepare(clip, opts: dict, plan: Optional[dict] = None):+ from ..core import framing as framing_mod+ from ..core.timeline import Timeline+ from . import Job, PlanError++ info = clip.info+ fr = framing_mod.plan(info.width, info.height, info.rate, info.frames, clip.face, shape=opts["frame"],+ size=O.size_of(opts["size"]))+ tl = Timeline.whole(info.frames / info.rate)+ cards = None+ if plan is not None:+ cards = plan.get("cards")+ if not isinstance(cards, list) or not cards:+ raise PlanError("the plan has no cards; run once without --plan to get one to edit")+ for c in cards:+ ws = c.get("words") or []+ if not ws:+ raise PlanError("every card needs at least one word")+ for w in ws:+ if not (0 <= float(w["s"]) <= float(w["e"]) <= tl.duration + 0.5):+ raise PlanError(f"the word {w.get('w')!r} has times outside the clip")+ caps = Captions(clip.words, clip.quiet, (fr.out_w, fr.out_h), info.rate, tl.output_frames(info.rate),+ head_in_output(clip, tl, fr), look=opts["look"], color=opts["color"],+ position=opts["position"], max_words=opts["max_words"], cards=cards)+ out_plan = {"effect": NAME, "clip": clip.path, "options": opts,+ "output": {"width": fr.out_w, "height": fr.out_h, "fps": round(info.rate, 3),+ "seconds": round(tl.duration, 3), "framing": fr.note},+ "anchor": caps.anchor, "cards": caps.plan(), "unsure": unsure_words(clip)}+ return Job(NAME, clip, tl, fr, caps.draw, out_plan, checks=caps.report(),+ still_times=lambda: caps.busy_times(4))diff --git a/edit/askeditor/fx/effects/clean_cut.py b/edit/askeditor/fx/effects/clean_cut.pynew file mode 100644index 0000000..b37a706--- /dev/null+++ b/edit/askeditor/fx/effects/clean_cut.py@@ -0,0 +1,564 @@+"""clean-cut: dead air, retakes and false starts cut out, captions on, framed 9:16.++What is cut, and how:++- **Dead air.** A pause longer than `pause` seconds (read from the sound, not from the+ transcriber, which reports almost every gap as zero) is shortened to a breath: a little after+ the last word, so it ends naturally, and a little before the next, so its first sound is whole.+ Pauses shorter than `pause` are the speaker's own rhythm and are left alone.+- **Retakes and false starts.** A phrase begun and then said again within a few seconds keeps only+ its last take: "so the product is- so the product is really fast" keeps "so the product is really+ fast", and a line said three times keeps the third. The first attempt must be mostly said again,+ must break off (a cut-off word, a comma, an "um", or a real pause), and must not run across a+ full stop unless every word of it is said again. A list ("most ads, most people")+ repeats one word only and is never taken for a retake. A word said twice in a stammer ("the+ the") keeps one; words repeated on purpose ("very very", "no no") are kept.+- **Fillers** (um, uh, erm) when `fillers=cut`.+- **Asides** when `asides=cut`: the sentences where the speaker talks about the recording rather+ than to the viewer ("Testing, testing.", "Give me a second.", "Let me start again.", "I've got+ the audio set up."), found by the core (`asides.asides`). Each is a cut of its own, listed with+ what it is, so one can be put back by deleting it from the plan and running again with `--plan`.++Every cut lands where the voice is quiet, at a word boundary, and the two sides are joined with a+20 ms crossfade, so nothing clicks and no word is clipped. After the render the output is heard+again, word by word, against the words that were meant to be kept: any word lost or chopped at a+cut is reported (the over-cut check).+"""++from __future__ import annotations++import difflib+import json+import math+from dataclasses import dataclass+from pathlib import Path+from typing import Optional++from ..core import framing as framing_mod+from ..core import words as wordsmod+from ..core.asides import Aside+from ..core.asides import asides as find_asides+from ..core.moments import LONGEST_TAKE, ON_PURPOSE, find_retakes # noqa: F401 (kept importable from here)+from ..core.moments import RETAKE_WINDOW as WINDOW # noqa: F401+from ..core.timeline import Timeline+from ..core.words import Word, pause_after+from . import captions as cap+from . import options as O++NAME = "clean-cut"++OPTIONS = {+ "pause": O.Number(0.15, 3.0, "pauses longer than this many seconds are shortened to a breath"),+ "keep_retakes": O.Switch("on keeps every take; off keeps only the last take of a phrase said twice"),+ "fillers": O.Choice(("cut", "keep"), "cut or keep um, uh and erm"),+ "asides": O.Choice(("cut", "keep"), "cut or keep talk about the recording itself: a mic check, "+ "\"give me a second\", \"let me start again\""),+ "captions": O.Switch("on or off"),+ "look": cap.OPTIONS["look"],+ "color": cap.OPTIONS["color"],+ "position": cap.OPTIONS["position"],+ "max_words": cap.OPTIONS["max_words"],+ "frame": O.Choice(("9:16", "keep"), "9:16 follows the face when the clip is wider; keep leaves its shape"),+ "size": cap.OPTIONS["size"],+ "fix": cap.OPTIONS["fix"],+}++# The breath left where a pause is shortened: after the last word, and before the next.+TAIL = 0.12+LEAD = 0.08+TAIL_SENTENCE = 0.18 # a full stop earns a slightly longer breath+LEAD_SENTENCE = 0.12+MIN_CUT = 0.12 # a cut that would take out less than this is not worth a jump in the picture+EDGE_KEEP_START = 0.10 # kept before the first word+EDGE_KEEP_END = 0.35 # kept after the last word+FADE = 0.02 # the crossfade at every join++FILLERS_CUT = wordsmod.HESITATIONS+++@dataclass+class Removal:+ start: float+ end: float+ reason: str+ words: str = ""+ detail: str = ""+ apart: bool = False # one of an aside's cuts: kept apart from the cut beside it, never merged++ @property+ def seconds(self) -> float:+ return self.end - self.start++ def as_dict(self) -> dict:+ return {"start": round(self.start, 3), "end": round(self.end, 3), "seconds": round(self.seconds, 3),+ "reason": self.reason, "words": self.words, "detail": self.detail}+++# ---- finding what to cut -------------------------------------------------------------------------++# Retakes and false starts are found by the core (`moments.find_retakes`), so the words clean-cut+# cuts are the words every picker passes over.+++def _quiet_between(quiet, a: float, b: float) -> Optional[tuple[float, float]]:+ """The longest quiet stretch overlapping [a, b], clipped to it."""+ best = None+ for q0, q1 in quiet:+ lo, hi = max(q0, a), min(q1, b)+ if hi > lo and (best is None or hi - lo > best[1] - best[0]):+ best = (lo, hi)+ return best+++def _cut_after(word: Word, until: float, quiet, env, sentence: bool, whole_gap: bool = False) -> float:+ """Where a cut may start after `word`: a breath into the quiet that follows it, or, if the next+ sound follows straight on, the quietest moment at the boundary. With `whole_gap` (what follows+ is a sentence cut whole, an aside), the quietest moment anywhere before `until`: the word's own+ end can be marked early when nothing quiet comes after it."""+ q = _quiet_between(quiet, word.end - 0.06, until)+ tail = TAIL_SENTENCE if sentence else TAIL+ if q is not None:+ return min(q[0] + tail, q[1])+ return env.quietest(word.end - 0.03, until if whole_gap else min(until, word.end + 0.05))+++def _cut_before(word: Word, since: float, quiet, env, sentence: bool, whole_gap: bool = False) -> float:+ q = _quiet_between(quiet, since, word.start + 0.06)+ lead = LEAD_SENTENCE if sentence else LEAD+ if q is not None:+ return max(q[1] - lead, q[0])+ return env.quietest(since if whole_gap else max(since, word.start - 0.05), word.start + 0.02)+++def _apart(r: Removal, idx: list[int], words: list[Word], gone: dict, aside_of: dict, quiet, env,+ kept_next: Optional[Word]) -> list[Removal]:+ """A removal that holds an aside, as one cut per aside: split where one aside (or what else is+ cut beside it) meets the next, in the quiet between them, so the cut report lists each aside+ with what it is and the plan can put one back on its own. The cuts touch, so the video is the+ same as with one. A removal without an aside is returned as it is."""+ if not any(x in aside_of for x in idx):+ return [r]++ def cause(x: int) -> tuple:+ return ("aside", aside_of[x].first) if x in aside_of else ("other", gone[x])++ groups: list[list[int]] = []+ for x in idx:+ if groups and cause(groups[-1][-1]) == cause(x):+ groups[-1].append(x)+ else:+ groups.append([x])+ edges = [r.start]+ for g, h in zip(groups, groups[1:]):+ a, b = words[g[-1]].end, words[h[0]].start+ q = _quiet_between(quiet, a, b) if b > a else None+ t = (q[0] + q[1]) / 2 if q is not None else env.quietest(min(a, b) - 0.03, max(a, b) + 0.03)+ edges.append(min(max(t, edges[-1]), r.end))+ edges.append(r.end)+ out = []+ for g, s, e in zip(groups, edges, edges[1:]):+ said = " ".join(words[x].text for x in g)+ a = aside_of.get(g[0])+ if a is not None:+ out.append(Removal(s, e, "aside", said, a.why, apart=True))+ continue+ reasons = [gone[x] for x in g]+ reason = max(set(reasons), key=reasons.count)+ detail = (f"the take kept starts at {kept_next.start:.2f} s"+ if kept_next is not None and reason in ("retake", "false start", "stammer") else "")+ out.append(Removal(s, e, reason, said, detail, apart=True))+ return out+++def plan_cuts(clip, opts: dict) -> tuple[list[Removal], list[Word]]:+ """What to remove, and the words that stay."""+ words = clip.words+ quiet = clip.quiet+ env = clip.envelope+ duration = clip.info.frames / clip.info.rate+ gone: dict[int, str] = {}+ restarts: dict[int, int] = {}+ aside_of: dict[int, Aside] = {}+ if opts.get("asides", "cut") == "cut":+ for a in find_asides(words, quiet):+ for x in range(a.first, a.last + 1):+ gone[x] = "aside"+ aside_of[x] = a+ if not opts["keep_retakes"]:+ for first, last, restart, reason in find_retakes(words, quiet):+ for x in range(first, last + 1):+ gone.setdefault(x, reason)+ restarts.setdefault(x, restart)+ if opts["fillers"] == "cut":+ for x, w in enumerate(words):+ if w.key in FILLERS_CUT:+ gone.setdefault(x, "filler")+ kept_idx = [x for x in range(len(words)) if x not in gone]+ removals: list[Removal] = []+ if not kept_idx:+ return removals, []+ kept = [words[x] for x in kept_idx]++ # Before the first word and after the last.+ first, last = kept[0], kept[-1]+ head_cut = first.start - EDGE_KEEP_START+ lead_words = [words[x] for x in range(kept_idx[0])]+ if any(x in aside_of for x in range(kept_idx[0])):+ # An aside just before the first word kept: the cut ends after it, however close the two are.+ head_cut = max(head_cut, _cut_after(lead_words[-1], first.start, quiet, env, True, whole_gap=True))+ if head_cut >= MIN_CUT:+ removals += _apart(Removal(0.0, head_cut, "dead air at the start" if not lead_words else gone[0],+ " ".join(w.text for w in lead_words),+ f"the take kept starts at {first.start:.2f} s" if lead_words else ""),+ list(range(kept_idx[0])), words, gone, aside_of, quiet, env, first)+ tail_cut = last.end + EDGE_KEEP_END+ trail_words = [words[x] for x in range(kept_idx[-1] + 1, len(words))]+ if any(x in aside_of for x in range(kept_idx[-1] + 1, len(words))):+ # An aside just after the last word kept: the cut starts before it, however close the two are.+ tail_cut = min(tail_cut, _cut_before(trail_words[0], last.end, quiet, env, True, whole_gap=True))+ if duration - tail_cut >= MIN_CUT or trail_words:+ tail_cut = min(tail_cut, duration)+ if duration - tail_cut > 1e-3:+ removals += _apart(Removal(tail_cut, duration, "dead air at the end" if not trail_words+ else gone[kept_idx[-1] + 1], " ".join(w.text for w in trail_words)),+ list(range(kept_idx[-1] + 1, len(words))), words, gone, aside_of, quiet, env, None)++ # Between each pair of kept words.+ for a, b in zip(kept_idx, kept_idx[1:]):+ p, n = words[a], words[b]+ between = list(range(a + 1, b))+ sentence = p.ends_sentence+ if between:+ r0, r1 = words[between[0]], words[between[-1]]+ whole = any(x in aside_of for x in between) # a sentence cut whole: its edges anywhere in the gap+ cut_in = _cut_after(p, r0.start + 0.03, quiet, env, sentence, whole_gap=whole)+ cut_out = _cut_before(n, r1.end - 0.03, quiet, env, sentence, whole_gap=whole)+ reasons = [gone[x] for x in between]+ reason = max(set(reasons), key=reasons.count)+ said = " ".join(words[x].text for x in between)+ detail = f"the take kept starts at {n.start:.2f} s" if reason in ("retake", "false start", "stammer") else ""+ if cut_out - cut_in >= 0.04:+ removals += _apart(Removal(cut_in, cut_out, reason, said, detail), between, words, gone, aside_of,+ quiet, env, n)+ continue+ gap = pause_after(words, a, quiet)+ if gap <= opts["pause"]:+ continue+ cut_in = _cut_after(p, n.start, quiet, env, sentence)+ cut_out = _cut_before(n, p.end, quiet, env, sentence)+ if cut_out - cut_in >= MIN_CUT:+ removals.append(Removal(cut_in, cut_out, "pause", "", f"a {gap:.2f} s pause made {gap - (cut_out - cut_in):.2f} s"))+ removals = _tidy(removals, kept, duration)+ return removals, kept+++def _tidy(removals: list[Removal], kept: list[Word], duration: float) -> list[Removal]:+ """In order, inside the clip, never over a kept word, and never leaving a sliver between two cuts."""+ out: list[Removal] = []+ for r in sorted(removals, key=lambda r: r.start):+ r.start, r.end = max(0.0, r.start), min(duration, r.end)+ for w in kept: # a cut never takes any part of a word that stays+ if w.start < r.end and r.start < w.end:+ if w.start - r.start >= r.end - w.end:+ r.end = w.start+ else:+ r.start = w.end+ if r.end - r.start < 0.04:+ continue+ if (out and r.start - out[-1].end < 0.08 and not any(out[-1].end <= w.start < r.start for w in kept)+ and not (r.apart and out[-1].apart)): # an aside's cut stays its own, to be put back on its own+ prev = out[-1]+ prev.end = max(prev.end, r.end)+ if r.reason != prev.reason:+ prev.reason = f"{prev.reason} + {r.reason}"+ prev.words = " ".join(x for x in (prev.words, r.words) if x)+ continue+ out.append(r)+ return out+++def _from_plan(plan: dict, clip, duration: float) -> tuple[list[Removal], list[Word]]:+ from . import PlanError++ raw = plan.get("removals")+ if not isinstance(raw, list):+ raise PlanError("the plan has no removals list; run once without --plan to get one to edit")+ removals = []+ for r in raw:+ try:+ s, e = float(r["start"]), float(r["end"])+ except (KeyError, TypeError, ValueError):+ raise PlanError(f"a removal needs a start and an end in seconds: {r!r}") from None+ if not (0 <= s < e <= duration + 1e-3):+ raise PlanError(f"the removal {s:.2f}-{e:.2f} s is not inside the clip (0-{duration:.2f} s)")+ removals.append(Removal(s, e, str(r.get("reason", "by hand")), str(r.get("words", "")), str(r.get("detail", ""))))+ removals.sort(key=lambda r: r.start)+ for a, b in zip(removals, removals[1:]):+ if b.start < a.end:+ raise PlanError(f"two removals overlap at {b.start:.2f} s; merge them or move one")+ kept = [w for w in clip.words if not any(r.start <= (w.start + w.end) / 2 < r.end for r in removals)]+ return removals, kept+++# ---- the effect ------------------------------------------------------------------------------++def prepare(clip, opts: dict, plan: Optional[dict] = None):+ from . import Job++ info = clip.info+ fps = info.rate+ duration = info.frames / fps+ if plan is not None:+ removals, kept = _from_plan(plan, clip, duration)+ else:+ removals, kept = plan_cuts(clip, opts)+ tl = Timeline.keeping(duration, [(r.start, r.end) for r in removals])+ fr = framing_mod.plan(info.width, info.height, fps, info.frames, clip.face, shape=opts["frame"],+ size=O.size_of(opts["size"]))+ # The kept words where they now play.+ out_words = []+ for w in kept:+ s, e = tl.to_output_nearest(w.start), tl.to_output_nearest(w.end)+ out_words.append(Word(w.text, s, max(e, s + 0.02), w.prob))+ out_quiet = tl.map_spans(clip.quiet)+ n_out = tl.output_frames(fps)+ caps = None+ checks: dict = {}+ if opts["captions"]:+ caps = cap.Captions(out_words, out_quiet, (fr.out_w, fr.out_h), fps, n_out,+ cap.head_in_output(clip, tl, fr), look=opts["look"], color=opts["color"],+ position=opts["position"], max_words=opts["max_words"])+ checks = caps.report()+ # Every aside found, and whether this render cuts it (an aside put back through the plan is kept).+ found = [{"start": round(a.start, 3), "end": round(a.end, 3), "said": a.said, "what": a.why,+ "cut": all(any(r.start <= (w.start + w.end) / 2 < r.end for r in removals)+ for w in clip.words[a.first:a.last + 1])}+ for a in find_asides(clip.words, clip.quiet)]+ removed = sum(r.seconds for r in removals)+ by_reason: dict[str, float] = {}+ for r in removals:+ by_reason[r.reason] = by_reason.get(r.reason, 0.0) + r.seconds+ summary = {"cuts": len(removals), "seconds_in": round(duration, 2), "seconds_out": round(tl.duration, 2),+ "seconds_removed": round(removed, 2),+ "by_reason": {k: round(v, 2) for k, v in sorted(by_reason.items(), key=lambda kv: -kv[1])},+ "framing": fr.note}+ out_plan = {"effect": NAME, "clip": clip.path, "options": opts,+ "output": {"width": fr.out_w, "height": fr.out_h, "fps": round(fps, 3),+ "seconds": round(tl.duration, 3), "framing": fr.note},+ "summary": summary,+ "removals": [r.as_dict() for r in removals],+ "asides": found,+ "kept_words": [{"w": w.text, "s": round(w.start, 3), "e": round(w.end, 3)} for w in kept],+ "unsure": cap.unsure_words(clip),+ "cards": caps.plan() if caps else []}++ def stills() -> list[float]:+ """The first line, a moment just after a cut in the middle, and the last line."""+ times = []+ if caps and caps.cards:+ c0 = caps.cards[0]+ times.append(min(c0.end - 0.5 / fps, max(c0.words[-1].start + 0.1, (c0.start + c0.end) / 2)))+ joins = tl.joins+ if joins:+ mid = joins[len(joins) // 2]+ times.append(min(tl.duration - 0.05, mid + 0.15))+ if caps and len(caps.cards) > 2:+ c = caps.cards[len(caps.cards) * 2 // 3]+ times.append(min(c.end - 0.5 / fps, max(c.words[-1].start + 0.1, (c.start + c.end) / 2)))+ if caps and caps.cards:+ c1 = caps.cards[-1]+ times.append(min(c1.end - 0.5 / fps, max(c1.words[-1].start + 0.1, (c1.start + c1.end) / 2)))+ return sorted(set(round(t, 3) for t in times)) or [tl.duration / 2]++ def after(result: dict, out: Path) -> dict:+ check = overcut_check(clip, kept, tl, out, opts.get("fix"))+ report = write_report(out, clip, summary, removals, check)+ return {"cut report": str(report), "over-cut check": check["verdict"]}++ head = {"cuts": f"{len(removals)} ({removed:.1f} s of {duration:.1f} s)"}+ if found:+ n_cut = sum(a["cut"] for a in found)+ head["asides"] = (f"{len(found)} found, {n_cut} cut" + (f", {len(found) - n_cut} kept" if n_cut < len(found) else "")+ + ": " + "; ".join(f"{a['start']:.2f} s \"{a['said']}\"" for a in found))+ checks = {**head, **checks}+ return Job(NAME, clip, tl, fr, caps.draw if caps else None, out_plan, checks=checks,+ still_times=stills, after=after)+++# ---- the over-cut check ----------------------------------------------------------------------------++# Below this share of the kept words heard again, the first listen of the output is taken to have+# stopped early (a working run hears 96 % or more) and the output is heard again in pieces. It only+# decides whether to listen again: what is lost or chopped is judged as before, on what is heard.+HEARD_AGAIN = 0.8+++def _matched(a: list[str], b: list[str]) -> int:+ """How many words of `a` are heard, in order, in `b`."""+ return sum(m.size for m in difflib.SequenceMatcher(a=a, b=b, autojunk=False).get_matching_blocks())+++def _heard_in_pieces(out: Path, bounds: list[float], fix: Optional[str]) -> list[Word]:+ """The output's words heard piece by piece: each stretch between two of `bounds` (output+ seconds, at joins cut in silence) is written to a temporary file with its sound untouched (PCM),+ heard on its own (`Clip.heard`, so with the second listen, as the whole output is), and its words'+ times are moved back to the output's."""+ import dataclasses+ import subprocess+ import tempfile++ from ..core.clip import Clip++ words: list[Word] = []+ with tempfile.TemporaryDirectory(prefix="fx-overcut-") as tmp:+ for k, (t0, t1) in enumerate(zip(bounds, bounds[1:])):+ if t1 - t0 < 0.05:+ continue+ piece = Path(tmp) / f"piece-{k:02d}.mkv"+ run = subprocess.run(+ ["ffmpeg", "-v", "error", "-nostdin", "-y", "-ss", f"{t0:.4f}", "-i", str(out),+ "-t", f"{t1 - t0:.4f}", "-map", "0:v:0", "-map", "0:a:0", "-vf", "scale=-2:64",+ "-c:v", "libx264", "-preset", "ultrafast", "-crf", "40", "-threads", "4",+ "-c:a", "pcm_s16le", str(piece)],+ capture_output=True)+ if run.returncode != 0:+ continue+ for w in wordsmod.pull_starts(wordsmod.sure(Clip(piece, fix=fix).heard)):+ if w.key:+ words.append(dataclasses.replace(w, start=w.start + t0, end=w.end + t0))+ return words+++def overcut_check(clip, kept: list[Word], tl: Timeline, out: Path, fix: Optional[str]) -> dict:+ """Hear the output again and compare it, word by word, with the words meant to be kept.++ A word missing or changed within a quarter second of a join is a suspect, and the sound+ decides: if both sides of that join were cut in silence, no part of any word was taken there,+ and the difference is the transcriber hearing the same sound another way (in a new context it+ may hear "them" as "demo"). If either side was cut while the voice was sounding, the word is+ reported as lost or chopped. Differences away from every join are listed apart.+ """+ # The output's words with the same lateness correction the kept words had, so the timing+ # comparison is like with like.+ from ..core.clip import Clip++ joins = tl.joins+ near = 0.25+ quiet = clip.quiet+ # Was each join cut in silence on both sides? (the end of one kept stretch and the start of the+ # next, each inside a stretch where nobody speaks: the same quiet the cuts were placed in)+ def in_quiet(t: float) -> bool:+ return any(q0 + 0.005 <= t <= q1 - 0.005 for q0, q1 in quiet)++ silent = {}+ for (a0, a1), (b0, b1), j in zip(tl.segments, tl.segments[1:], joins):+ silent[j] = in_quiet(a1) and in_quiet(b0)++ a = [w.key for w in kept]+ heard = [w for w in wordsmod.pull_starts(wordsmod.sure(Clip(out, fix=fix).heard)) if w.key]+ pieces = 0+ first_matched = _matched(a, [w.key for w in heard])+ if kept and first_matched < HEARD_AGAIN * len(kept):+ # The first listen heard far fewer of the kept words than a working run does (every run on+ # the test clips heard 96 % or more). The transcriber can end its window early on sound that+ # is all there: on 33 with its asides cut it heard one sentence of the first 30 s, 18 words in+ # all. So the output is heard again in pieces, split where both sides of a join were cut in+ # silence (no word is split there), and the pieces' words are compared as before.+ cuts = [j for j in joins if silent[j]]+ again = _heard_in_pieces(out, [0.0] + cuts + [tl.duration], fix)+ if _matched(a, [w.key for w in again]) > first_matched:+ heard, pieces = again, len(cuts) + 1+ b = [w.key for w in heard]++ def by_join(t: float) -> Optional[float]:+ if not joins:+ return None+ j = min(joins, key=lambda x: abs(x - t))+ return j if abs(j - t) <= near else None++ lost, chopped, extra, elsewhere = [], [], [], []+ offsets = []+ for op, i1, i2, j1, j2 in difflib.SequenceMatcher(a=a, b=b, autojunk=False).get_opcodes():+ if op == "equal":+ for i, j in zip(range(i1, i2), range(j1, j2)):+ expect = tl.to_output_nearest(kept[i].start)+ offsets.append(heard[j].start - expect)+ continue+ for i in range(i1, i2):+ t = tl.to_output_nearest(kept[i].start)+ t_end = tl.to_output_nearest(kept[i].end)+ jn = by_join(t) if by_join(t) is not None else by_join(t_end)+ item = {"word": kept[i].text, "at": round(t, 2)}+ if jn is None or silent.get(jn):+ elsewhere.append(dict(item, heard_as=" ".join(heard[j].text for j in range(j1, j2)),+ **({"next_to_silent_cut": round(jn, 2)} if jn is not None else {})))+ elif op == "delete":+ lost.append(dict(item, join=round(jn, 2)))+ else:+ chopped.append(dict(item, join=round(jn, 2), heard_as=" ".join(heard[j].text for j in range(j1, j2))))+ if op == "insert":+ for j in range(j1, j2):+ jn = by_join(heard[j].start)+ item = {"word": heard[j].text, "at": round(heard[j].start, 2)}+ (extra if jn is not None and not silent.get(jn) else elsewhere).append(item)+ offsets.sort()+ median = offsets[len(offsets) // 2] if offsets else 0.0+ matched = len(offsets)+ if lost or chopped:+ verdict = (f"{len(lost)} word(s) lost and {len(chopped)} chopped at a cut: "+ + ", ".join(f"'{x['word']}' at {x['at']} s" for x in lost + chopped))+ elif joins:+ quiet_joins = sum(1 for v in silent.values() if v)+ verdict = (f"no word lost or chopped at any of the {len(joins)} joins, {quiet_joins} of them cut in silence "+ f"on both sides ({matched} of {len(kept)} kept words heard again)")+ else:+ verdict = f"nothing was cut inside the take ({matched} of {len(kept)} kept words heard again)"+ if extra:+ verdict += f"; {len(extra)} sound(s) of a removed word left at a cut"+ if pieces:+ verdict += (f"; heard again in {pieces} pieces split at the joins cut in silence, because the "+ f"first listen heard only {first_matched} of {len(kept)}")+ return {"verdict": verdict, "heard_in_pieces": pieces, "first_listen_matched": first_matched, "lost": lost, "chopped": chopped, "left_at_cut": extra,+ "joins_cut_in_silence": sum(1 for v in silent.values() if v), "joins": len(joins),+ "heard_differently_away_from_cuts": elsewhere, "matched": matched, "kept": len(kept),+ "median_start_offset_s": round(median, 3)}+++def write_report(out: Path, clip, summary: dict, removals: list[Removal], check: dict) -> Path:+ path = out.with_suffix(".cuts.md")+ lines = [f"# Cut report: {Path(clip.path).name}", "",+ f"{summary['seconds_in']:.2f} s in, {summary['seconds_out']:.2f} s out: "+ f"{summary['cuts']} cuts took out {summary['seconds_removed']:.2f} s. {summary['framing'].capitalize()}.", ""]+ if summary["by_reason"]:+ lines.append("By reason: " + ", ".join(f"{k} {v:.2f} s" for k, v in summary["by_reason"].items()) + ".")+ lines.append("")+ lines += ["| # | From | To | Seconds | Why | What was said |", "|---|---|---|---|---|---|"]+ for n, r in enumerate(removals, 1):+ said = (r.words or "").replace("|", "/")+ why = r.reason + (f" ({r.detail})" if r.detail else "")+ lines.append(f"| {n} | {r.start:.2f} | {r.end:.2f} | {r.seconds:.2f} | {why} | {said} |")+ if any(r.reason == "aside" for r in removals):+ lines += ["", "An aside is talk about the recording rather than to the viewer. To keep one, delete its row from "+ "the plan's `removals` and run again with `--plan`; `asides=keep` keeps them all."]+ lines += ["", "## The over-cut check", "", f"The output was transcribed again and compared, word by word, with the words kept: {check['verdict']}.", ""]+ if check["lost"] or check["chopped"]:+ for x in check["lost"]:+ lines.append(f"- lost: '{x['word']}' at {x['at']} s (cut at {x['join']} s)")+ for x in check["chopped"]:+ lines.append(f"- chopped: '{x['word']}' at {x['at']} s, heard as '{x['heard_as']}' (cut at {x['join']} s)")+ lines.append("")+ if check["left_at_cut"]:+ lines.append("Left at a cut: " + ", ".join(f"'{x['word']}' at {x['at']} s" for x in check["left_at_cut"]) + ".")+ lines.append("")+ if check["heard_differently_away_from_cuts"]:+ def said(x: dict) -> str:+ heard_as = f", heard as '{x['heard_as']}'" if x.get("heard_as") else ""+ beside = f" (beside the cut at {x['next_to_silent_cut']} s, made in silence)" if "next_to_silent_cut" in x else ""+ return f"'{x['word']}' at {x['at']} s{heard_as}{beside}"+ lines.append("Heard differently where no sound was cut (the transcriber, not the cut): "+ + "; ".join(said(x) for x in check["heard_differently_away_from_cuts"]) + ".")+ lines.append("")+ lines.append(f"Words heard again in place: {check['matched']} of {check['kept']}; the median start "+ f"differs from the plan by {check['median_start_offset_s'] * 1000:.0f} ms.")+ path.write_text("\n".join(lines) + "\n")+ return pathdiff --git a/edit/askeditor/fx/effects/options.py b/edit/askeditor/fx/effects/options.pynew file mode 100644index 0000000..d2cddee--- /dev/null+++ b/edit/askeditor/fx/effects/options.py@@ -0,0 +1,135 @@+"""The kinds of option an effect takes, each able to read what a person typed and say plainly+what is wrong with it.++An effect lists its options as `{name: kind}`; the defaults live in `effects.json`, the one+manifest, and `run.py` checks both agree before anything renders.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Sequence++from ..core.text import colour+++class OptionError(ValueError):+ """An option value that cannot be used; the message says what would work."""+++@dataclass(frozen=True)+class Choice:+ values: Sequence[str]+ help: str++ def parse(self, raw: Any) -> str:+ v = str(raw).strip().lower()+ if v not in self.values:+ raise OptionError(f"choose one of {', '.join(self.values)} (got {raw!r})")+ return v+++@dataclass(frozen=True)+class Number:+ lo: float+ hi: float+ help: str++ def parse(self, raw: Any) -> float:+ try:+ v = float(str(raw).strip().rstrip("s"))+ except ValueError:+ raise OptionError(f"give a number between {self.lo:g} and {self.hi:g} (got {raw!r})") from None+ if not self.lo <= v <= self.hi:+ raise OptionError(f"give a number between {self.lo:g} and {self.hi:g} (got {raw!r})")+ return v+++@dataclass(frozen=True)+class Whole:+ lo: int+ hi: int+ help: str++ def parse(self, raw: Any) -> int:+ try:+ v = int(str(raw).strip())+ except ValueError:+ raise OptionError(f"give a whole number from {self.lo} to {self.hi} (got {raw!r})") from None+ if not self.lo <= v <= self.hi:+ raise OptionError(f"give a whole number from {self.lo} to {self.hi} (got {raw!r})")+ return v+++@dataclass(frozen=True)+class Switch:+ help: str++ def parse(self, raw: Any) -> bool:+ if isinstance(raw, bool):+ return raw+ v = str(raw).strip().lower()+ if v in ("on", "yes", "true", "1"):+ return True+ if v in ("off", "no", "false", "0"):+ return False+ raise OptionError(f"say on or off (got {raw!r})")+++@dataclass(frozen=True)+class Colour:+ help: str++ def parse(self, raw: Any) -> str:+ v = str(raw).strip()+ if v.lower() in ("auto", ""):+ return "auto"+ try:+ r, g, b = colour(v)+ except ValueError as e:+ raise OptionError(str(e)) from None+ return f"#{r:02x}{g:02x}{b:02x}"+++@dataclass(frozen=True)+class Text:+ help: str++ def parse(self, raw: Any) -> str:+ return str(raw)+++@dataclass(frozen=True)+class Size:+ help: str++ def parse(self, raw: Any) -> str:+ v = str(raw).strip().lower()+ if v == "auto":+ return v+ try:+ w, h = (int(x) for x in v.split("x"))+ except ValueError:+ raise OptionError(f"give auto or a size like 1080x1920 (got {raw!r})") from None+ if not (64 <= w <= 4096 and 64 <= h <= 4096) or w % 2 or h % 2:+ raise OptionError(f"give even sides between 64 and 4096, like 1080x1920 (got {raw!r})")+ return v+++def size_of(value: str):+ return None if value == "auto" else tuple(int(x) for x in value.split("x"))+++def parse_all(spec: dict, defaults: dict, given: dict) -> dict:+ """The options to render with: the defaults, overridden by what was given, every value checked."""+ unknown = [k for k in given if k not in spec]+ if unknown:+ raise OptionError(f"no option called {', '.join(unknown)}; this effect takes {', '.join(spec)}")+ out = {}+ for name, kind in spec.items():+ raw = given.get(name, defaults[name])+ try:+ out[name] = kind.parse(raw)+ except OptionError as e:+ raise OptionError(f"{name}: {e}") from None+ return outdiff --git a/edit/askeditor/fx/effects/qc_check.py b/edit/askeditor/fx/effects/qc_check.pynew file mode 100644index 0000000..873ee2c--- /dev/null+++ b/edit/askeditor/fx/effects/qc_check.py@@ -0,0 +1,1674 @@+"""qc-check: the checks before "done". It reads a finished video, and the clip it was made from when+it is given, says in plain words what would embarrass it once posted, and changes nothing.++What it checks:++- **The file:** its shape for the platform, its size, its frame rate (a changing one, or a change+ from the source's), its codec and its length.+- **The sound:** loudness (integrated, measured exactly as the pack sets it) and true peak against+ the platform's target; samples at full scale (clipping); silence where there should be a voice+ (with the source: the voice in the source and not in the video); long dead air.+- **The picture:** black frames; frozen frames (a picture that stops while the sound goes on);+ rapid flashing; HDR or log footage that was never converted and so looks flat and grey.+- **With the source:** the video is lined up with the source in time (by the sound, so cuts and+ trims are found) and in space (the same frame, a crop that moves, or the picture fitted inside a+ bigger frame), and then, frame by frame:+ - **the face:** inside the face box, anything in the video that was not in the source (words, a+ card, a sticker) is measured; a frame where it covers enough of the face is flagged. A colour+ grade does not count: the comparison is of shapes, not of colours;+ - **the safe zone:** anything added outside it (the bottom fifth, where the caption and buttons+ sit, the side margins, the top bar) is flagged.++It writes `<video>.qc.md` (the verdict first, then what to fix, then every check with what was+measured) and `<video>.qc.jpg` (the frames that matter, with the safe zone and the face box drawn+and anything added over the face tinted, over a strip of the whole video). It exits with 1 when a+check fails (or, with `strict=on`, warns), so a script or an agent can stop on it.+"""++from __future__ import annotations++import json+import subprocess+import time+from dataclasses import dataclass, field+from pathlib import Path+from typing import Optional++import numpy as np++from ..core import audio, loudness, video+from ..core import face as facemod+from ..core.layout import Rect, SafeZone+from . import options as O++NAME = "qc-check"+REPORTS = True++PLATFORMS = {+ "reels": {"name": "Instagram Reels", "aspect": 9 / 16, "lufs": -14.0, "tp": -1.0, "longest": 180, "zone": True},+ "tiktok": {"name": "TikTok", "aspect": 9 / 16, "lufs": -14.0, "tp": -1.0, "longest": 600, "zone": True},+ "shorts": {"name": "YouTube Shorts", "aspect": 9 / 16, "lufs": -14.0, "tp": -1.0, "longest": 180, "zone": True},+ "youtube": {"name": "YouTube", "aspect": 16 / 9, "lufs": -14.0, "tp": -1.0, "longest": None, "zone": False},+ "any": {"name": "any platform", "aspect": None, "lufs": None, "tp": -1.0, "longest": None, "zone": False},+}++OPTIONS = {+ "source": O.Text("the clip the video was made from (a full path). With it the face and the safe zone are "+ "checked frame by frame, and missing sound or a changed frame rate is found"),+ "platform": O.Choice(tuple(PLATFORMS), "where it will be posted: reels, tiktok, shorts (9:16, -14 LUFS, "+ "-1 dBTP), youtube (16:9), or any (no shape or loudness target)"),+ "strict": O.Switch("on: a warning fails the check too"),+}++ANALYSIS = 640 # the longer side of the picture as it is examined+LOUD_OK, LOUD_WARN = 3.0, 6.0 # LU from the target: within the first is right, past the second fails+TP_FAIL = 0.5 # dBTP: a true peak over this fails; between the target and this warns+FACE_FLAG = 0.08 # a frame is flagged when something not in the source spans this share of the face box+FACE_FAIL = 0.12 # a flagged stretch fails when it spans this much of the face at its worst, for long enough+FACE_LONG = 0.25 # seconds a stretch must last to fail (a word sliding past the chin is a warning)+BLOB = 0.0015 # an addition outside the safe zone counts from this share of the frame+REPLACED = 0.40 # a frame where this share changed is a new picture (a new room, a full card), not an overlay+ELSEWHERE = 0.15 # a frame where fewer of its textured blocks than this still match the source shows another+# picture (a cutaway): cutaways measured 0-1%, overlays 93-100%, a new room round you 36-43%+DEAD = -70.0 # dBFS: sound under this is dead silence (a room, however quiet, is louder)+BLACK_PIX, BLACK_SHARE = 26, 0.98 # a frame is black when this share of its pixels is under this level+FROZEN = 0.06 # a frame changing less than this (0-255, on a small grey copy) from the one before is frozen:+# a repeated frame changes by 0.03 at most, a person sitting still at 60 fps by 0.1 or more+SPECK = 6 # changed pixels in a clump smaller than this are the encoder's noise, not something added+++@dataclass+class Finding:+ check: str+ level: str # "fail", "warn", "pass", "skip" or "info"+ what: str+ fix: str = ""+ spans: list = field(default_factory=list) # [(start_s, end_s), …]+ at: Optional[float] = None # the moment to show on the sheet+++LEVEL_ORDER = {"fail": 0, "warn": 1, "info": 2, "pass": 3, "skip": 4}+++# ---- small helpers ---------------------------------------------------------------------------------++def _spans(flags: np.ndarray, fps: float, gap: int = 1, least: int = 1) -> list[tuple[int, int]]:+ """Runs of True as (first, last+1) frame pairs, joining runs `gap` frames apart, keeping those of+ at least `least` frames."""+ out: list[list[int]] = []+ idx = np.flatnonzero(flags)+ for i in idx:+ if out and i - out[-1][1] <= gap:+ out[-1][1] = i + 1+ else:+ out.append([int(i), int(i) + 1])+ return [(a, b) for a, b in out if b - a >= least]+++def _secs(spans: list[tuple[int, int]], fps: float) -> list[tuple[float, float]]:+ return [(round(a / fps, 2), round(b / fps, 2)) for a, b in spans]+++def _say_spans(spans: list[tuple[float, float]], most: int = 3) -> str:+ parts = [f"{a:.2f}-{b:.2f} s" for a, b in spans[:most]]+ more = len(spans) - most+ return ", ".join(parts) + (f" and {more} more" if more > 0 else "")+++def _probe(path: str) -> dict:+ run = subprocess.run(["ffprobe", "-v", "error", "-print_format", "json", "-show_streams", "-show_format", path],+ capture_output=True, text=True)+ if run.returncode != 0:+ raise video.MediaError(f"this file could not be read as a video: {path}")+ return json.loads(run.stdout)+++def _rate(text: Optional[str]) -> float:+ try:+ a, _, b = (text or "0/1").partition("/")+ return float(a) / float(b or 1)+ except (ValueError, ZeroDivisionError):+ return 0.0+++def _gray(rgb: np.ndarray) -> np.ndarray:+ return (0.299 * rgb[..., 0] + 0.587 * rgb[..., 1] + 0.114 * rgb[..., 2]).astype(np.float32)+++def _structure(g: np.ndarray) -> np.ndarray:+ """The shapes in a grey picture, without its brightness or contrast: each pixel less the local+ mean, over the local spread (plus a floor, so flat areas stay near nought). A grade changes+ colours and contrast but not shapes; words and cards change shapes."""+ import cv2++ mu = cv2.GaussianBlur(g, (0, 0), 4)+ d = g - mu+ sd = np.sqrt(cv2.GaussianBlur(d * d, (0, 0), 4))+ return d / (sd + 6.0)+++def _changed(r: np.ndarray, s: np.ndarray) -> np.ndarray:+ """Where the video adds shapes the source does not have, as a 0-1 mask. A pixel of misalignment,+ the encoder's noise and a grade are all forgiven. Thick letters change only at their edges (inside a+ white stroke there is no shape in either picture), so what is found is closed up: a word counts by+ the area it covers, not by its outline."""+ import cv2++ nr, ns = _structure(r), _structure(s)+ diff = np.abs(nr - ns)+ for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):+ diff = np.minimum(diff, np.abs(nr - np.roll(np.roll(ns, dy, axis=0), dx, axis=1)))+ diff = cv2.GaussianBlur(diff, (0, 0), 1.0)+ # Only what the video adds: more shape than the source has there. A background made plain (a+ # flat colour where a room was) takes shapes away and is not something laid over the picture.+ more = cv2.GaussianBlur(np.abs(nr), (0, 0), 2.0) > cv2.GaussianBlur(np.abs(ns), (0, 0), 2.0) + 0.25+ m = ((diff > 0.9) & more).astype(np.uint8)+ count, labels, stats, _ = cv2.connectedComponentsWithStats(m, connectivity=8)+ if count > 1:+ specks = stats[:, cv2.CC_STAT_AREA] < SPECK+ specks[0] = False+ m[specks[labels]] = 0+ k = max(3, int(round(r.shape[1] / 50)) | 1) # about a stroke's width at the size examined+ return cv2.morphologyEx(m, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k, k)))+++# ---- the file, the sound and the picture -----------------------------------------------------------++class Facts:+ def __init__(self, path: str):+ self.path = path+ d = _probe(path)+ streams = d.get("streams", [])+ self.v = next((s for s in streams if s.get("codec_type") == "video"+ and not s.get("disposition", {}).get("attached_pic")), None)+ if self.v is None:+ raise video.MediaError(f"this file has no picture: {path}")+ self.a = next((s for s in streams if s.get("codec_type") == "audio"), None)+ self.format = d.get("format", {})+ self.info = video.probe(path)+ self.rotation = 0+ for side in self.v.get("side_data_list", []) or []:+ if "rotation" in side:+ self.rotation = int(round(float(side["rotation"])))+ self.r_rate = _rate(self.v.get("r_frame_rate"))+ self.avg_rate = _rate(self.v.get("avg_frame_rate"))+ self.transfer = (self.v.get("color_transfer") or "").lower()+ self.space = (self.v.get("color_space") or "").lower()+ self.pix_fmt = self.v.get("pix_fmt") or ""+ self.codec = self.v.get("codec_name") or ""+ self.sar = self.v.get("sample_aspect_ratio") or "1:1"+++def file_checks(f: Facts, platform: dict, src: Optional[Facts]) -> list[Finding]:+ out = []+ W, H = f.info.width, f.info.height+ shape = W / H+ want = platform["aspect"]+ if want is None:+ out.append(Finding("shape", "pass", f"{W}x{H} ({shape:.3g}:1); no shape is asked of this platform"))+ elif abs(shape - want) <= 0.02 * want:+ out.append(Finding("shape", "pass", f"{W}x{H}, {'9:16' if want < 1 else '16:9'} as {platform['name']} expects"))+ else:+ out.append(Finding("shape", "warn", f"{W}x{H} is not the {'9:16' if want < 1 else '16:9'} shape "+ f"{platform['name']} fills the screen with; it will be cropped or shown with bars",+ "make it that shape (the reframe effect does, following the face)"))+ long_side, short_side = max(W, H), min(W, H)+ if W % 2 or H % 2:+ out.append(Finding("size", "fail", f"{W}x{H} has an odd side, which some platforms and players refuse",+ "render it again at an even size"))+ elif short_side < 720:+ out.append(Finding("size", "warn", f"{W}x{H} is small: under 720 on its short side it looks soft on a phone",+ "render from a bigger source, or at size=1080x1920"))+ elif short_side < 1080:+ out.append(Finding("size", "info", f"{W}x{H}: the platform enlarges it to {1080 if W < H else 1920} "+ f"wide; fine, a little softer than full size"))+ else:+ out.append(Finding("size", "pass", f"{W}x{H}"))+ if f.sar not in ("1:1", "0:1", "N/A"):+ out.append(Finding("pixels", "warn", f"its pixels are not square ({f.sar}): some apps show it stretched",+ "export with square pixels"))+ if f.rotation:+ out.append(Finding("rotation", "warn", f"it is stored on its side and turned by a {f.rotation}° flag, which "+ f"some apps ignore", "export it upright"))+ fps = f.info.rate+ vfr = f.avg_rate > 0 and abs(f.r_rate - f.avg_rate) > 0.01 * f.avg_rate+ if vfr:+ out.append(Finding("frame rate", "warn", f"the frame rate changes (it averages {f.avg_rate:.3g} fps): edits "+ f"and uploads can drift out of sync", "export at a constant frame rate"))+ elif fps < 23:+ out.append(Finding("frame rate", "warn", f"{fps:.3g} fps looks choppy", "export at 24, 25 or 30 fps"))+ elif fps > 60.5:+ out.append(Finding("frame rate", "warn", f"{fps:.3g} fps is above what platforms play; they convert it",+ "export at 60 fps or less"))+ elif src is not None and abs(src.info.rate - fps) > 0.01 * fps:+ out.append(Finding("frame rate", "warn", f"{fps:.3g} fps, but the source is {src.info.rate:.3g} fps: motion "+ f"stutters when frames are dropped or doubled", "keep the source's frame rate"))+ elif min(abs(fps - c) for c in (23.976, 24, 25, 29.97, 30, 50, 59.94, 60)) > 0.05:+ out.append(Finding("frame rate", "info", f"{fps:.4g} fps is unusual; platforms play it, or convert it to 30"))+ else:+ out.append(Finding("frame rate", "pass", f"{fps:.4g} fps, constant"))+ if f.codec not in ("h264", "hevc"):+ out.append(Finding("codec", "warn", f"the picture is {f.codec}; platforms want H.264 or HEVC", "export as H.264"))+ elif f.pix_fmt not in ("yuv420p", "yuvj420p", "yuv420p10le"):+ out.append(Finding("codec", "warn", f"its pixel format is {f.pix_fmt}, which some phones do not play",+ "export as yuv420p"))+ else:+ out.append(Finding("codec", "pass", f"{f.codec.upper() if f.codec == 'hevc' else 'H.264'}, {f.pix_fmt}"))+ dur = f.info.duration+ if platform["longest"] and dur > platform["longest"]:+ out.append(Finding("length", "warn", f"{dur:.1f} s is longer than {platform['name']} takes "+ f"({platform['longest']} s)", "cut it down, or post it elsewhere"))+ else:+ out.append(Finding("length", "pass", f"{dur:.2f} s"))+ if f.a is not None:+ a_dur = float(f.a.get("duration") or dur)+ if abs(a_dur - dur) > 0.25:+ out.append(Finding("sound length", "warn", f"the sound is {a_dur:.2f} s and the picture {dur:.2f} s: one "+ f"ends early", "render it again so they match"))+ return out+++def sound_checks(f: Facts, platform: dict, src: Optional[Facts], tmap, quiet_src,+ still: Optional[np.ndarray] = None) -> tuple[list[Finding], dict]:+ """Loudness, true peak, clipping and silence. Returns the findings and what the sheet draws."""+ out: list[Finding] = []+ drawn: dict = {}+ if f.a is None:+ if src is not None and src.a is not None:+ out.append(Finding("sound", "fail", "the video has no sound at all, and its source had a voice",+ "render it again keeping the sound"))+ else:+ out.append(Finding("sound", "warn", "the video has no sound", "add the voice or music back"))+ return out, drawn+ m = loudness.measure_file(f.path)+ target, tp_target = platform["lufs"], platform["tp"]+ if m.i < -70:+ out.append(Finding("loudness", "fail", "the sound is silent from start to end", "render it again with its sound"))+ return out, drawn+ if target is None:+ out.append(Finding("loudness", "info", f"{m.i:.1f} LUFS integrated (no target for this platform)"))+ else:+ off = m.i - target+ say = f"{m.i:.1f} LUFS integrated, {abs(off):.1f} LU {'under' if off < 0 else 'over'} the {target:g} LUFS " \+ f"{platform['name']} plays at"+ if abs(off) <= LOUD_OK:+ out.append(Finding("loudness", "pass", say))+ elif abs(off) <= LOUD_WARN:+ out.append(Finding("loudness", "warn", say + (": it will sound quiet next to other posts" if off < 0+ else ": loud, and the platform may turn it down"),+ f"set it to {target:g} LUFS (the music-bed effect does this for a whole mix)"))+ else:+ out.append(Finding("loudness", "fail", say + (": far too quiet; people will skip it or turn it up and "+ "hear noise" if off < 0 else ": far too loud"),+ f"set it to {target:g} LUFS before posting"))+ if m.tp > TP_FAIL:+ out.append(Finding("true peak", "fail", f"the true peak is {m.tp:+.1f} dBTP, over full scale: it distorts "+ f"when the platform encodes it again", f"limit the peaks to {tp_target:g} dBTP"))+ elif m.tp > tp_target:+ out.append(Finding("true peak", "warn", f"the true peak is {m.tp:+.1f} dBTP, over the {tp_target:g} dBTP "+ f"platforms ask for; the loudest moments may crackle after upload",+ f"limit the peaks to {tp_target:g} dBTP"))+ else:+ out.append(Finding("true peak", "pass", f"{m.tp:+.1f} dBTP"))+ # Clipping and silence, from the samples themselves.+ info = f.info+ s = video.read_audio(info)+ peak = np.abs(s).max(axis=1)+ clipped = peak >= 0.999+ rate = video.AUDIO_RATE+ events = _spans(clipped, rate, gap=int(0.005 * rate))+ if events:+ first = events[0][0] / rate+ say = (f"{len(events)} moment{'s' if len(events) != 1 else ''} where the sound hits full scale and clips "+ f"({clipped.sum()} samples), the first at {first:.2f} s")+ level = "fail" if len(events) >= 10 or clipped.mean() > 1e-4 else "warn"+ out.append(Finding("clipping", level, say, "turn the sound down before the peaks, or limit it",+ spans=[(a / rate, b / rate) for a, b in events], at=first))+ else:+ out.append(Finding("clipping", "pass", "no sample reaches full scale"))+ mono = video.mono(s, rate, 16000)+ env = audio.envelope(mono, 16000)+ drawn["envelope"] = env+ # Dead silence: the whole sound under -60 dBFS for a second or more, not at the very end (an end+ # card held in silence is the pack's own way to finish).+ hop = 0.05+ n_hop = int(len(mono) / (16000 * hop))+ rms = np.array([np.sqrt(np.mean(mono[int(k * hop * 16000):int((k + 1) * hop * 16000)] ** 2) + 1e-12)+ for k in range(n_hop)])+ dead = 20 * np.log10(rms + 1e-12) < DEAD+ dur = info.duration+ runs = [(a * hop, b * hop) for a, b in _spans(dead, 1 / hop, least=int(1.0 / hop))]+ inner = [(a, b) for a, b in runs if b < dur - 0.25 and a > 0.25]+ ends = [(a, b) for a, b in runs if (a, b) not in inner]+ drawn["dead"] = runs+ missing = []+ if src is not None and tmap is not None and quiet_src is not None and src.a is not None:+ # The voice is in the source at that moment, and not in the video.+ speech_src = _voiced_mask(quiet_src, tmap, info.frames, info.rate)+ vq = audio.quiet_runs(env)+ quiet_here = np.zeros(info.frames, bool)+ for a, b in vq:+ quiet_here[int(a * info.rate):int(np.ceil(b * info.rate))] = True+ # A hold (the source's moment stands still: a freeze, an end card past the source's last+ # frame) has no speech of the source's to lose.+ t_src = np.asarray(tmap.src, float)[:info.frames]+ held = np.zeros(info.frames, bool)+ held[1:len(t_src)] = np.abs(np.diff(t_src)) < 0.25 / src.info.rate+ held[:len(t_src)] |= t_src >= src.info.duration - 1.5 / src.info.rate+ if still is not None: # a freeze for effect: the picture stands still while the sound is quiet+ held[:min(len(still), info.frames)] |= still[:info.frames]+ lost = speech_src & quiet_here & ~tmap.near_cut & ~held+ missing = _secs(_spans(lost, info.rate, gap=2, least=int(0.3 * info.rate)), info.rate)+ if missing:+ out.append(Finding("silence", "fail", f"the voice is missing at {_say_spans(missing)}: the source has speech "+ f"there and the video is silent", "render it again; check the sound was not muted or cut",+ spans=missing, at=missing[0][0]))+ elif inner:+ level = "warn"+ out.append(Finding("silence", level, f"dead silence at {_say_spans(inner)}: nothing at all is heard there",+ "cut the silence, or put sound under it", spans=inner, at=inner[0][0]))+ else:+ note = "no dead silence" + (f" (a silent end of {ends[-1][1] - ends[-1][0]:.1f} s, as an end card has)"+ if ends and ends[-1][1] >= dur - 0.3 else "")+ out.append(Finding("silence", "pass", note))+ # Long dead air in a talking video: a pause of 2.5 s or more between words.+ q = audio.quiet_runs(env)+ voiced_share = 1 - sum(b - a for a, b in q) / max(dur, 1e-3)+ long_q = [(a, b) for a, b in q if b - a >= 2.5 and a > 0.3 and b < dur - 0.3]+ if voiced_share > 0.3 and long_q:+ out.append(Finding("pauses", "warn", f"long pauses at {_say_spans(_round(long_q))}: dead air loses people",+ "cut them (the clean-cut effect shortens pauses to a breath)", spans=_round(long_q),+ at=long_q[0][0]))+ elif voiced_share > 0.3:+ out.append(Finding("pauses", "pass", "no pause of 2.5 s or more"))+ drawn["clipped"] = [a / rate for a, _ in events[:200]]+ drawn["lufs"], drawn["tp"] = m.i, m.tp+ return out, drawn+++def _round(spans):+ return [(round(a, 2), round(b, 2)) for a, b in spans]+++def _voiced_mask(quiet_src, tmap, n: int, fps: float) -> np.ndarray:+ """Per video frame: does the source have speech at the moment that frame shows?"""+ out = np.zeros(n, bool)+ starts = np.array([a for a, _ in quiet_src]) if quiet_src else np.zeros(0)+ ends = np.array([b for _, b in quiet_src]) if quiet_src else np.zeros(0)+ for j in range(n):+ t = tmap.src[j]+ k = np.searchsorted(starts, t, side="right") - 1+ out[j] = not (k >= 0 and t < ends[k])+ return out+++class Picture:+ """One pass over the video's frames: what the black, frozen, flash and colour checks need."""++ def __init__(self, f: Facts):+ info = f.info+ k = ANALYSIS / max(info.width, info.height)+ self.size = (max(2, int(round(info.width * k / 2)) * 2), max(2, int(round(info.height * k / 2)) * 2))+ n = info.frames+ self.mean = np.zeros(n)+ self.dark = np.zeros(n)+ self.diff = np.full(n, np.inf)+ self.hist = [] # (frame, p2, p50, p98, saturation) every so often+ step = max(1, int(round(info.rate / 2)))+ prev = None+ import cv2++ for j, fr in enumerate(video.FrameReader(info, size=self.size)):+ if j >= n:+ break+ g = _gray(fr)+ self.mean[j] = g.mean()+ self.dark[j] = (g < BLACK_PIX).mean()+ small = cv2.resize(g, (64, max(2, int(64 * g.shape[0] / g.shape[1]))), interpolation=cv2.INTER_AREA)+ if prev is not None:+ self.diff[j] = float(np.abs(small - prev).mean())+ prev = small+ if j % step == 0:+ mx = fr.max(axis=2).astype(np.float32)+ mn = fr.min(axis=2).astype(np.float32)+ sat = float(np.mean((mx - mn) / np.maximum(mx, 1.0)))+ p2, p50, p98 = np.percentile(g, (2, 50, 98))+ self.hist.append((j, float(p2), float(p50), float(p98), sat))+++def fingerprint(path) -> str:+ """The video's own bytes, in short: its size and the start of their SHA-256. Two reports of "the+ same file" with different fingerprints were of two renders."""+ import hashlib++ h = hashlib.sha256()+ with open(path, "rb") as fh:+ for block in iter(lambda: fh.read(1 << 20), b""):+ h.update(block)+ return f"{Path(str(path)).stat().st_size} bytes, sha256 {h.hexdigest()[:12]}"+++def planned_source(path) -> Optional[str]:+ """The clip the plan beside the video says it was made from, when that file is there."""+ plan = Path(str(path)).with_suffix(".plan.json")+ try:+ clip = json.loads(plan.read_text(encoding="utf-8")).get("clip")+ except (OSError, ValueError, AttributeError):+ return None+ if isinstance(clip, str) and clip and Path(clip).is_file() and Path(clip).resolve() != Path(str(path)).resolve():+ return clip+ return None+++def _planned_holds(path) -> list[tuple[float, float]]:+ """The holds the plan beside the video says it made (`<video>.plan.json`: a freeze's `output_at`+ and `hold`, or a list of `holds` as [start, end] seconds), so a freeze made on purpose is not+ taken for an export fault."""+ import json++ plan = Path(str(path)).with_suffix(".plan.json")+ try:+ p = json.loads(plan.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return []+ out = []+ fr = p.get("freeze") if isinstance(p, dict) else None+ if isinstance(fr, dict) and "output_at" in fr and "hold" in fr:+ out.append((float(fr["output_at"]), float(fr["output_at"]) + float(fr["hold"])))+ for h in (p.get("holds") or []) if isinstance(p, dict) else []:+ if isinstance(h, (list, tuple)) and len(h) == 2:+ out.append((float(h[0]), float(h[1])))+ return out+++def picture_checks(f: Facts, pic: Picture, src: Optional[Facts], tmap, voiced_frames: Optional[np.ndarray]) -> list[Finding]:+ out = []+ info = f.info+ fps, n = info.rate, info.frames+ # Black.+ black = (pic.dark >= BLACK_SHARE) & (pic.mean < 0.08 * 255)+ spans = _spans(black, fps)+ if spans:+ secs = _secs(spans, fps)+ inner = [s for s in spans if s[0] > 0 and s[1] < n]+ worst = max(b - a for a, b in spans) / fps+ if inner and max(b - a for a, b in inner) >= 2:+ out.append(Finding("black frames", "fail", f"black frames at {_say_spans(secs)} (the longest "+ f"{worst:.2f} s)", "cut them, or put the picture back", spans=secs, at=secs[0][0]))+ else:+ out.append(Finding("black frames", "warn", f"black frames at {_say_spans(secs)}, at "+ f"{'the start' if spans[0][0] == 0 else 'the end'}: fine for a fade, but the first "+ f"frame is the cover some apps show", spans=secs, at=secs[0][0]))+ else:+ out.append(Finding("black frames", "pass", "none"))+ # Frozen: the picture stops changing (a black stretch is reported as black, not twice).+ frozen = (pic.diff < FROZEN) & ~black+ runs = _spans(frozen, fps, gap=0, least=max(2, int(round(0.25 * fps))))+ end_hold = None+ bad, soft, paused, spoken = [], [], [], False+ meant = _planned_holds(f.info.path)+ for a, b in runs:+ start, stop = a - 1, b # the frame before the first unchanged one is part of the freeze+ if stop >= n - 1 and (stop - start) / fps <= 6.0:+ end_hold = (start / fps, stop / fps)+ continue+ talking = voiced_frames is not None and voiced_frames[a:b].mean() > 0.3+ if src is not None and tmap is not None and np.min(np.asarray(tmap.src)[a:b]) >= src.info.duration - 1.5 / src.info.rate:+ continue # past the source's last frame: an end card held, not a freeze+ if any(h0 - 0.3 <= start / fps and stop / fps <= h1 + 0.3 for h0, h1 in meant):+ paused.append((start / fps, stop / fps)) # the plan beside the video holds the picture here+ continue+ if voiced_frames is not None and not talking:+ # Picture and sound stop together (a freeze for effect, the clip carrying on after it). An+ # export fault freezes the picture while the sound plays on.+ paused.append((start / fps, stop / fps))+ continue+ spoken |= talking+ source_moves = False+ if src is not None and tmap is not None:+ source_moves = tmap.source_moving(a, b)+ if not source_moves and not tmap.held(a, b):+ continue # the source is as still there: nothing was lost+ if talking or source_moves or (b - a) / fps >= 1.0:+ bad.append((start / fps, stop / fps))+ elif src is None:+ soft.append((start / fps, stop / fps))+ # else: the source holds still there too, so nothing was lost+ singles = int(np.sum(frozen & ~np.convolve(frozen, [1, 0, 1], "same").astype(bool)))+ if bad:+ bad = _round(bad)+ why = "while the voice goes on" if spoken else "where the source moves on"+ out.append(Finding("frozen frames", "fail", f"the picture freezes at {_say_spans(bad)} {why}".strip(),+ "render it again; a freeze in the middle is an export fault", spans=bad, at=bad[0][0]))+ elif paused:+ paused = _round(paused)+ out.append(Finding("frozen frames", "warn", f"the picture holds at {_say_spans(paused)}, a freeze for effect (the plan "+ "beside it says so, or the sound stops with it)", "check it is meant to", spans=paused, at=paused[0][0]))+ elif soft:+ soft = _round(soft)+ out.append(Finding("frozen frames", "warn", f"the picture holds still at {_say_spans(soft)}",+ "check it is meant to (a held frame for effect)", spans=soft, at=soft[0][0]))+ elif singles > 0.08 * n:+ out.append(Finding("frozen frames", "warn", f"{singles} single frames repeat ({singles / n:.0%} of them): the "+ f"video was converted from another frame rate, and motion stutters a little",+ "export at the source's own frame rate"))+ else:+ out.append(Finding("frozen frames", "pass", "none" + (f" (the last {end_hold[1] - end_hold[0]:.1f} s hold one "+ f"frame, as an end card does)" if end_hold else "")))+ # Flashes: changes of brightness that reverse, more than three in a second.+ lum = pic.mean / 255.0+ big = np.abs(np.diff(lum)) >= 0.10+ sign = np.sign(np.diff(lum))+ flips = [i for i in range(1, len(sign)) if big[i] and sign[i] != 0 and sign[i] != sign[i - 1]]+ worst = 0+ for i in flips:+ worst = max(worst, sum(1 for k in flips if i <= k < i + fps) // 2)+ if worst > 3:+ out.append(Finding("flashes", "warn", f"{worst} flashes within one second: rapid flashing can harm people "+ f"with photosensitive epilepsy", "slow the flashes to three a second or fewer"))+ else:+ out.append(Finding("flashes", "pass", "no rapid flashing"))+ return out+++def colour_checks(f: Facts, pic: Picture, src: Optional[Facts], aligned: Optional[list] = None) -> list[Finding]:+ """HDR or log footage shown as ordinary video looks flat and grey. `aligned` is a few frames of+ the video beside the part of the source they show, read converted and raw (`_aligned_samples`)."""+ from ..core import hdr++ out = []+ kind = hdr.kind(f.transfer)+ h = np.array([r[1:] for r in pic.hist]) if pic.hist else np.zeros((0, 4))+ p2, p50, p98, sat = (np.median(h[:, k]) if len(h) else 0.0 for k in range(4))+ measured = f"darkest {p2:.0f}, middle {p50:.0f}, brightest {p98:.0f} (of 255), colour {sat:.2f}"+ if kind != "sdr":+ out.append(Finding("colour", "warn", f"the video is HDR ({kind.upper()}): HDR phones show it bright, others "+ f"and many apps show it flat and grey ({measured})",+ "deliver it as SDR (BT.709); the pack converts HDR clips to SDR as it reads them"))+ return out+ if src is not None and hdr.kind(src.transfer) != "sdr":+ # Was the HDR source converted, or written out as it was? Compare the video's picture with the+ # source read both ways, at the same moments.+ verdict = _hdr_verdict(aligned) if aligned else _hdr_converted(f, src, pic)+ if verdict is not None:+ conv, raw, grey = verdict+ if raw < conv:+ level = "fail" if grey else "warn"+ out.append(Finding("colour", level, f"the source is HDR ({hdr.kind(src.transfer).upper()}) and the video "+ f"is its picture unconverted: {'washed out and grey' if grey else 'a little flat and grey'}"+ f" ({measured})", "render it again with the current pack: it converts HDR as it reads"))+ return out+ out.append(Finding("colour", "pass", f"the HDR source was converted to SDR ({measured})"))+ return out+ flat = p98 - p2 < 150 and p2 > 28 and sat < 0.12+ if src is None:+ # Alone, the picture cannot say whether an HDR clip was converted: tier-list's old D, drawn+ # unconverted, reads PASS here and WARN against its source. Say which was judged.+ measured += "; judged on the picture alone: give source= to check an HDR clip was converted"+ if flat:+ out.append(Finding("colour", "warn", f"the picture looks flat and grey, like HDR or log footage that was never "+ f"converted ({measured})", "convert it to BT.709 (or grade it) before posting"))+ else:+ out.append(Finding("colour", "pass", measured))+ return out+++def _aligned_samples(f: Facts, src: Facts, tmap: "TimeMap", geo: "Geometry", size: tuple[int, int]) -> list:+ """For six moments: the video's frame, and the part of the source it shows, read converted and+ read raw (as a tool that ignores HDR would), each grey and the same size."""+ import dataclasses++ aw, ah = size+ sw, sh = geo.src_size+ raw_info = dataclasses.replace(src.info, transfer="sdr", color_matrix="bt709")+ out = []+ for j in np.linspace(0, f.info.frames - 1, 8).astype(int)[1:-1]:+ v = _gray(video.read_frame(f.info, int(j), size=(aw, ah)))+ k = tmap.frame(int(j))+ a = _gray(video.read_frame(src.info, k, size=(sw, sh)))+ b = _gray(video.read_frame(raw_info, k, size=(sw, sh)))+ if geo.kind in ("a crop that moves across", "a crop that moves up and down"):+ across = geo.kind == "a crop that moves across"+ p = _crop_pos(v, a, across, None)+ win = (slice(0, ah), slice(p, p + aw)) if across else (slice(p, p + ah), slice(0, aw))+ a, b = a[win], b[win]+ elif geo.kind == "the whole picture fitted inside":+ x, y = int(round(geo.fit[1])), int(round(geo.fit[2]))+ hh, ww = min(sh, ah - y), min(sw, aw - x)+ v, a, b = v[y:y + hh, x:x + ww], a[:hh, :ww], b[:hh, :ww]+ if a.shape == v.shape:+ out.append((v, a, b))+ return out+++def _hdr_verdict(samples: list):+ """(distance to the converted source, to the raw source, washed out?) from aligned samples."""+ conv = float(np.median([np.abs(v - a).mean() for v, a, _ in samples]))+ raw = float(np.median([np.abs(v - b).mean() for v, _, b in samples]))+ # How grey the unconverted picture is depends on the footage: a white room read raw loses its+ # whites (washed out), a darker scene only a little. Measured on the source itself, so a new+ # background in the video does not change the answer.+ grey = float(np.median([np.percentile(a, 98) - np.percentile(b, 98) for _, a, b in samples])) > 15+ return conv, raw, grey+++def _hdr_converted(f: Facts, src: Facts, pic: Picture):+ """(distance to the converted source, distance to the raw source, washed out?) over a few frames,+ or None when the two cannot be compared (another shape, another length)."""+ import dataclasses++ if abs(f.info.duration - src.info.duration) > 0.5:+ return None+ raw_info = dataclasses.replace(src.info, transfer="sdr", color_matrix="bt709")+ conv, raw, greys = [], [], []+ for j, *_ in pic.hist[:: max(1, len(pic.hist) // 6)][:6]:+ t = j / f.info.rate+ v = _gray(video.read_frame(f.info, j, size=(160, int(160 * f.info.height / f.info.width))))+ k = src.info.frame_at(t)+ size = (160, int(160 * src.info.height / src.info.width))+ a = _gray(video.read_frame(src.info, k, size=size))+ b = _gray(video.read_frame(raw_info, k, size=size))+ hv, ha, hb = (np.percentile(x, (2, 25, 50, 75, 98)) for x in (v, a, b))+ conv.append(float(np.abs(hv - ha).mean()))+ raw.append(float(np.abs(hv - hb).mean()))+ greys.append(float(ha[-1] - hv[-1])) # how much darker its whites are than the converted ones+ grey = np.median(greys) > 15+ return float(np.median(conv)), float(np.median(raw)), bool(grey)+++# ---- lining the video up with its source -----------------------------------------------------------++class TimeMap:+ """For every frame of the video, the moment of the source it shows."""++ def __init__(self, src_times: np.ndarray, kind: str, cuts: list[int], n_src: int, fps_src: float,+ src_diff: Optional[np.ndarray] = None, source: Optional["Facts"] = None):+ self.src = src_times+ self.kind = kind+ self.cuts = cuts+ self.near_cut = np.zeros(len(src_times), bool)+ for c in cuts:+ self.near_cut[max(0, c - 3):c + 3] = True+ self.n_src, self.fps_src = n_src, fps_src+ self.src_diff = src_diff+ self.source = source # read for its motion only when a freeze needs judging++ def frame(self, j: int) -> int:+ return int(min(self.n_src - 1, max(0, round(self.src[j] * self.fps_src))))++ def snap(self, diff: np.ndarray, fps: float, reach: float = 0.8) -> None:+ """The sound places a cut to within half a second; the picture shows exactly where it is (the+ biggest jump from one frame to the next nearby). Each cut moves there, and the frames between+ take the offset of their own side."""+ n = len(self.src)+ t = np.arange(n) / fps+ off = self.src - t+ moved = []+ for c in self.cuts:+ lo, hi = max(1, c - int(reach * fps)), min(n - 1, c + int(reach * fps))+ if hi <= lo:+ moved.append(c)+ continue+ d = np.nan_to_num(diff[lo:hi + 1], nan=0.0, posinf=0.0)+ new = lo + int(np.argmax(d))+ before, after = off[max(0, lo - 1)], off[min(n - 1, hi)]+ off[lo:new] = before+ off[new:hi + 1] = after+ moved.append(new)+ self.src = np.clip(t + off, 0, (self.n_src - 1) / self.fps_src)+ self.cuts = moved+ self.near_cut = np.zeros(n, bool)+ for c in moved:+ self.near_cut[max(0, c - 3):c + 3] = True++ def held(self, a: int, b: int) -> bool:+ """Do video frames a..b show one and the same source frame (a frame held on purpose)?"""+ return len({self.frame(j) for j in range(a, b)}) <= 1++ def source_moving(self, a: int, b: int) -> bool:+ """Does the source move over the moments video frames a..b show?"""+ if self.src_diff is None and self.source is not None:+ self.src_diff = _source_motion(self.source)+ if self.src_diff is None:+ return False+ ks = sorted({self.frame(j) for j in range(a, b)})+ if len(ks) <= 1:+ return False # the video shows one source frame there: a held frame, not a freeze+ vals = self.src_diff[[k for k in ks if k < len(self.src_diff)]]+ return bool(np.nanmean(vals) > 3 * FROZEN)+++def _norm_env(env) -> np.ndarray:+ """The speech envelope on a common scale: everything more than 45 dB under the voice is one+ floor (so a muted stretch cannot swamp the rest), centred and scaled by its middle half."""+ top = float(np.percentile(env.db, 90))+ x = np.maximum(env.db, top - 45.0)+ spread = float(np.percentile(x, 75) - np.percentile(x, 25))+ return ((x - np.median(x)) / (spread + 1e-6)).astype(np.float32)+++def _held_before(holds: list[tuple[float, float]], t) -> np.ndarray:+ """Seconds of the holds that lie before each moment `t` of the video."""+ t = np.asarray(t, float)+ return sum((np.clip(t - a, 0.0, b - a) for a, b in holds), np.zeros_like(t))+++def time_map(f: Facts, src: Facts, env_v, env_s, holds: list[tuple[float, float]] = ()) -> Optional[TimeMap]:+ """Line the video up with the source by their sound: the same moment, a trim, or cuts.++ `holds` are the stretches of the video where the plan beside it says the picture is held on one+ frame (a freeze). The sound there is not the source's (a scratch, the room's tone looped), so it+ places nothing, and after a hold the video shows the source later by the hold's length: the one+ place the offset falls instead of growing. Without them a freeze's room tone matched the source+ anywhere, and the clip after it was lined up with the source's last frame (freeze-point on D:+ a false 13% face FAIL, the outline of the person counted as something over the face)."""+ n, fps = f.info.frames, f.info.rate+ holds = sorted((float(a), float(b)) for a, b in holds if b > a)+ hop = env_v.hop+ a, b = _norm_env(env_v), _norm_env(env_s)+ dur_v, dur_s = f.info.duration, src.info.duration+ t = np.arange(n) / fps+ # Window by window, where in the source each stretch of the video's sound is.+ L, step = int(1.5 / hop), int(0.5 / hop)+ if len(b) < L or len(a) < L:+ return None+ starts = list(range(0, len(a) - L + 1, step))+ found = [] # (centre time, offset seconds, score)+ fb = np.fft.rfft(np.concatenate([b, np.zeros(L)]))+ csum = np.concatenate([[0.0], np.cumsum(b)])+ csum2 = np.concatenate([[0.0], np.cumsum(b * b)])+ raw = env_v.db+ at_zero = [] # how well each window matches the source at no offset+ for s0 in starts:+ if any(s0 * hop < h1 and (s0 + L) * hop > h0 for h0, h1 in holds):+ continue # its sound is the hold's, not the source's+ w = a[s0:s0 + L]+ seg = raw[s0:s0 + L]+ if float(np.percentile(seg, 90) - np.percentile(seg, 10)) < 6.0 or w.std() < 1e-3:+ continue # nothing but a level here: no shape to place+ if s0 + L <= len(b):+ z = b[s0:s0 + L]+ at_zero.append(float(np.corrcoef(w, z)[0, 1]) if z.std() > 1e-6 else 0.0)+ w = (w - w.mean()) / (w.std() + 1e-6)+ corr = np.fft.irfft(fb * np.conj(np.fft.rfft(np.concatenate([w, np.zeros(len(b))]), len(b) + L)),+ len(b) + L)[:len(b) - L + 1]+ mu = (csum[L:] - csum[:-L]) / L+ # A flat stretch of the source (a long pause at the floor) cannot be where a voice is: its+ # spread is given a floor, or dividing by almost nothing would make it the best match.+ sd = np.sqrt(np.maximum((csum2[L:] - csum2[:-L]) / L - mu * mu, 0.0))+ ncc = corr / (L * np.maximum(sd, 0.25))+ p = int(np.argmax(ncc))+ if ncc[p] > 0.6:+ found.append(((s0 + L / 2) * hop, (p - s0) * hop, float(ncc[p])))+ same = TimeMap(np.minimum(t, dur_s - 1 / src.info.rate), "the same frames", [], src.info.frames, src.info.rate)+ # The same timing (the common case): the lengths match and most stretches match the source at no+ # offset. A stretch whose sound was changed (muted, music laid over) does not count against it.+ if abs(dur_v - dur_s) < 0.2 and (not at_zero or np.mean([r_ >= 0.7 for r_ in at_zero]) >= 0.7):+ return same+ if len(found) < 3:+ return same if abs(dur_v - dur_s) < 0.2 else None+ # The offset only grows (a cut takes source time out; nothing is played twice): keep the longest+ # run of windows whose offsets never fall, then give every frame the offset of the nearest window.+ cen = np.array([c for c, _, _ in found])+ off = np.array([o for _, o, _ in found])+ keep = _longest_rising(off + _held_before(holds, cen), tol=0.03)+ cen, off = cen[keep], off[keep]+ per_frame = off[np.clip(np.searchsorted(cen, t), 0, len(cen) - 1)]+ near = np.abs(cen[np.clip(np.searchsorted(cen, t), 0, len(cen) - 1)] - t)+ alt = off[np.clip(np.searchsorted(cen, t) - 1, 0, len(cen) - 1)]+ near_alt = np.abs(cen[np.clip(np.searchsorted(cen, t) - 1, 0, len(cen) - 1)] - t)+ per_frame = np.where(near_alt < near, alt, per_frame)+ per_frame = _median(per_frame, 5)+ src_t = np.clip(t + per_frame, 0, dur_s - 1 / src.info.rate)+ in_hold = np.zeros(n, bool)+ for h0, h1 in holds:+ a0, a1 = int(round(h0 * fps)), min(n, int(round(h1 * fps)))+ if 0 <= a0 < a1:+ # The frame held is the source's moment where the hold begins (the offset before it).+ k = max(0, a0 - 1)+ src_t[a0:a1] = min(max(0.0, t[a0] + per_frame[k]), dur_s - 1 / src.info.rate)+ in_hold[a0:a1 + 1] = True+ cuts = [j for j in range(1, n) if abs(per_frame[j] - per_frame[j - 1]) > 0.5 / fps and not in_hold[j]]+ if cuts or not in_hold.any():+ kind = "cuts found by the sound" if cuts else f"offset by {per_frame[0]:+.2f} s"+ else:+ kind = "the same frames, with the planned hold" + ("s" if len(holds) > 1 else "")+ return TimeMap(src_t, kind, cuts, src.info.frames, src.info.rate)+++def _longest_rising(x: np.ndarray, tol: float) -> np.ndarray:+ """Indices of the longest subsequence of x that never falls by more than `tol`."""+ n = len(x)+ best = np.ones(n, int)+ prev = np.full(n, -1)+ for i in range(n):+ for j in range(i):+ if x[i] >= x[j] - tol and best[j] + 1 > best[i]:+ best[i], prev[i] = best[j] + 1, j+ i = int(np.argmax(best))+ out = []+ while i >= 0:+ out.append(i)+ i = prev[i]+ return np.array(out[::-1])+++def _median(x: np.ndarray, k: int) -> np.ndarray:+ pad = np.pad(x, (k // 2, k // 2), mode="edge")+ return np.median(np.lib.stride_tricks.sliding_window_view(pad, k), axis=1)+++class Geometry:+ """Where the video's picture sits in the source's: the whole frame, a crop that moves across (or+ up and down), or the whole source fitted inside a bigger frame."""++ def __init__(self, kind: str, src_size: tuple[int, int], fit: Optional[tuple[float, float, float]] = None):+ self.kind = kind+ self.src_size = src_size # the size the source is read at for the comparison+ self.fit = fit # for "fit": scale, x, y of the source inside the video (analysis pixels)+++def _grad(g: np.ndarray) -> np.ndarray:+ import cv2++ g = cv2.GaussianBlur(g, (0, 0), 1.0)+ gx = cv2.Sobel(g, cv2.CV_32F, 1, 0, ksize=3)+ gy = cv2.Sobel(g, cv2.CV_32F, 0, 1, ksize=3)+ return np.sqrt(gx * gx + gy * gy)+++def geometry(f: Facts, src: Facts, tmap: TimeMap, size: tuple[int, int]) -> tuple[Optional[Geometry], float]:+ """Try each way the video could sit in the source on a few frames; keep the one that fits best."""+ import cv2++ aw, ah = size+ W, H = src.info.width, src.info.height+ va = aw / ah+ sa = W / H+ picks = np.linspace(0, f.info.frames - 1, 8).astype(int)+ tries = {}+ same = abs(va - sa) < 0.01 * sa+ if same:+ tries["the same frame"] = (aw, ah)+ elif sa > va: # the source is wider: a crop sliding across, at full height+ tries["a crop that moves across"] = (max(aw + 2, int(round(ah * sa))), ah)+ else:+ tries["a crop that moves up and down"] = (aw, max(ah + 2, int(round(aw / sa))))+ # The whole source fitted inside the video (a fill, or bars).+ s = min(aw / W, ah / H)+ tries["the whole picture fitted inside"] = (max(2, int(round(W * s))), max(2, int(round(H * s))))+ scores = {k: [] for k in tries}+ for j in picks:+ v = _grad(_gray(video.read_frame(f.info, int(j), size=(aw, ah))))+ k = tmap.frame(int(j))+ for name, (sw, sh) in tries.items():+ g = _grad(_gray(video.read_frame(src.info, k, size=(sw, sh))))+ if name == "the same frame":+ sc = float(cv2.matchTemplate(v, g, cv2.TM_CCOEFF_NORMED).max())+ elif name == "the whole picture fitted inside":+ if sw > aw or sh > ah:+ continue+ sc = float(cv2.matchTemplate(v, g, cv2.TM_CCOEFF_NORMED).max())+ else:+ sc = float(cv2.matchTemplate(g, v, cv2.TM_CCOEFF_NORMED).max())+ scores[name].append(sc)+ best, best_v = None, -1.0+ for name, vals in scores.items():+ if vals and np.median(vals) > best_v:+ best, best_v = name, float(np.median(vals))+ if best is None or best_v < 0.3:+ return None, best_v+ sw, sh = tries[best]+ if best == "the whole picture fitted inside":+ g = _grad(_gray(video.read_frame(src.info, tmap.frame(int(picks[len(picks) // 2])), size=(sw, sh))))+ v = _grad(_gray(video.read_frame(f.info, int(picks[len(picks) // 2]), size=(aw, ah))))+ res = cv2.matchTemplate(v, g, cv2.TM_CCOEFF_NORMED)+ _, _, _, loc = cv2.minMaxLoc(res)+ return Geometry(best, (sw, sh), fit=(s, float(loc[0]), float(loc[1]))), best_v+ return Geometry(best, (sw, sh)), best_v+++# ---- the face and the safe zone, frame by frame ----------------------------------------------------++class Compare:+ """Every frame of the video against the moment of the source it shows."""++ def __init__(self):+ self.face_cover = None # per frame: the share of the face box showing something new (NaN: not judged)+ self.outside = None # per frame: the share of the frame added outside the safe zone+ self.where = None # per frame: where outside (bottom, top, left, right) as a short word+ self.wordy = None # per frame: True when what is outside looks like a line of words+ self.word_where = None # per frame: where those words are+ self.replaced = None # per frame: True where the whole picture changed (a new room, a card)+ self.elsewhere = None # per frame: True where the video shows another picture (a cutaway)+ self.boxes = None # per frame: the face box in the video's pixels (Rect or None)+ self.maps = {} # frame -> the added-shapes mask at analysis size, for the sheet+ self.judged = 0.0+ self.aligned_by = ""+++def compare(f: Facts, src: Facts, src_face: facemod.FaceTrack, tmap: TimeMap, geo: Geometry,+ size: tuple[int, int], zone_on: bool) -> Compare:+ import cv2++ info, n = f.info, f.info.frames+ aw, ah = size+ sw, sh = geo.src_size+ k_src = sw / src.info.width # source pixels to the size the source is read at+ zone = SafeZone(aw, ah).rect+ c = Compare()+ c.face_cover = np.full(n, np.nan)+ c.outside = np.zeros(n)+ c.where = [""] * n+ c.wordy = np.zeros(n, bool)+ c.word_where = [""] * n+ c.replaced = np.zeros(n, bool)+ c.elsewhere = np.zeros(n, bool)+ c.boxes = [None] * n+ crop_x = geo.kind == "a crop that moves across"+ crop_y = geo.kind == "a crop that moves up and down"+ # The source's frames are read once, in order: the timing only moves forwards.+ reader = iter(video.FrameReader(src.info, size=(sw, sh)))+ buf: dict[int, np.ndarray] = {}+ read_upto = -1++ def src_frame(k: int) -> Optional[np.ndarray]:+ nonlocal read_upto+ k = int(min(max(k, 0), src.info.frames - 1))+ while read_upto < k + 1:+ nxt = next(reader, None)+ if nxt is None:+ break+ read_upto += 1+ buf[read_upto] = _gray(nxt)+ for old in [x for x in buf if x < read_upto - 4]:+ del buf[old]+ return buf.get(k, buf.get(read_upto))++ keep_best: list[tuple[float, int, np.ndarray]] = []+ pos_prev = None+ judged = 0++ def small(img: np.ndarray) -> np.ndarray:+ return cv2.resize(img, (max(8, img.shape[1] // 4), max(8, img.shape[0] // 4)), interpolation=cv2.INTER_AREA)++ for j, fr in enumerate(video.FrameReader(info, size=(aw, ah))):+ if j >= n:+ break+ v = _gray(fr)+ k = tmap.frame(j)+ centre = src_frame(k)+ if centre is None:+ continue+ # Where the video's frame sits in the source's (found once a frame, on the middle candidate).+ if crop_x or crop_y:+ pos = _crop_pos(v, centre, crop_x, pos_prev)+ pos_prev = pos+ dx, dy = (-pos, 0) if crop_x else (0, -pos)+ elif geo.kind == "the whole picture fitted inside":+ dx, dy = int(round(geo.fit[1])), int(round(geo.fit[2]))+ else:+ dx = dy = 0++ def place(sf: np.ndarray) -> Optional[np.ndarray]:+ if crop_x or crop_y:+ a = sf[-dy:-dy + ah, -dx:-dx + aw]+ return a if a.shape == v.shape else None+ if geo.kind == "the whole picture fitted inside":+ a = v.copy()+ hh, ww = min(sf.shape[0], ah - dy), min(sf.shape[1], aw - dx)+ a[dy:dy + hh, dx:dx + ww] = sf[:hh, :ww]+ return a+ return sf if sf.shape == v.shape else None++ # A frame early or late is forgiven: of the three, the one closest in shape.+ best = None+ sv = _structure(small(v))+ for kk in (k - 1, k, k + 1):+ sf = src_frame(kk)+ if sf is None:+ continue+ aligned = place(sf)+ if aligned is None:+ continue+ err = float(np.abs(sv - _structure(small(aligned))).mean())+ if best is None or err < best[0]:+ best = (err, kk, aligned)+ if best is None:+ continue+ _, kk, aligned = best+ mask = _changed(v, aligned)+ if geo.kind == "the whole picture fitted inside":+ s, fx, fy = geo.fit+ outside_fit = np.ones_like(mask)+ yy, xx = int(round(fy)), int(round(fx))+ outside_fit[yy + 2:yy + sh - 2, xx + 2:xx + sw - 2] = 0+ mask = mask * (1 - outside_fit) # the fill around the fitted picture is not an overlay+ share = float(mask.mean())+ c.elsewhere[j] = _matching(v, aligned) < ELSEWHERE+ c.replaced[j] = share > REPLACED or c.elsewhere[j]+ # The face: the source's face box (brows to chin), a little narrower than cheek to cheek, so+ # the outline of the head against a new background is not taken for something over the face.+ b = src_face.box(kk)+ if b is not None and src_face.found_share > 0.3 and not c.elsewhere[j]:+ r = Rect(b.x0 + 0.05 * b.w, b.y0, b.x1 - 0.05 * b.w, b.y1 + 0.03 * b.h)+ r = r.scale(k_src, k_src, dx, dy)+ x0, y0 = int(max(0, r.x0)), int(max(0, r.y0))+ x1, y1 = int(min(aw, r.x1)), int(min(ah, r.y1))+ if x1 - x0 > 8 and y1 - y0 > 8 and not tmap.near_cut[j]:+ c.face_cover[j] = _covered(mask[y0:y1, x0:x1])+ c.boxes[j] = Rect(x0, y0, x1, y1)+ judged += 1+ # Anything added that reaches outside the safe zone (only where the picture is not wholly new).+ if zone_on and not c.replaced[j] and not tmap.near_cut[j]:+ inside = np.zeros_like(mask)+ inside[int(zone.y0):int(zone.y1), int(zone.x0):int(zone.x1)] = 1+ # The letters of a line are joined into one shape first, so a caption counts as a caption.+ line = cv2.getStructuringElement(cv2.MORPH_RECT, (max(3, int(0.04 * aw)) | 1, max(3, int(0.01 * ah)) | 1))+ joined = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, line)+ count, labels, stats, _ = cv2.connectedComponentsWithStats(joined, connectivity=8)+ strokes = np.abs(_structure(v)) > 1.0 # the video's own edges: letters are many strokes+ # Pieces of one picture (a screenshot's title bar, a card's edge) join up at a coarser scale:+ # a line that belongs to a big added region is part of a picture, not a caption.+ coarse = cv2.morphologyEx(joined, cv2.MORPH_CLOSE, cv2.getStructuringElement(+ cv2.MORPH_RECT, (max(3, int(0.05 * aw)) | 1, max(3, int(0.03 * ah)) | 1)))+ _, regions, region_stats, _ = cv2.connectedComponentsWithStats(coarse, connectivity=8)+ where, word_where, area = set(), set(), 0+ for i in range(1, count):+ st = stats[i]+ bx, by, bw, bh = (int(st[cv2.CC_STAT_LEFT]), int(st[cv2.CC_STAT_TOP]), int(st[cv2.CC_STAT_WIDTH]),+ int(st[cv2.CC_STAT_HEIGHT]))+ if _rule(st, aw, ah) or bw * bh > 0.30 * aw * ah:+ continue # a divider, or a whole new background: drawn on purpose, not an overlay+ blob = labels[by:by + bh, bx:bx + bw] == i+ out_px = int((blob & (inside[by:by + bh, bx:bx + bw] == 0)).sum())+ if out_px < BLOB * aw * ah:+ continue+ area += out_px+ # A line of words placed out there (mostly outside the zone), not a picture that+ # reaches into the margin from inside it.+ ys, xs = np.nonzero(blob)+ region = regions[by + int(ys[0]), bx + int(xs[0])]+ in_picture = region_stats[region, cv2.CC_STAT_AREA] > 0.08 * aw * ah+ # A line of words crosses many edges along a row (2.9 every 10 px for a caption,+ # measured); a border or a roofline barely any (0.2).+ rows = (strokes[by:by + bh, bx:bx + bw] & blob)[bh // 4:max(bh // 4 + 1, 3 * bh // 4)]+ crossings = np.abs(np.diff(rows.astype(np.int8), axis=1)).sum(axis=1).mean() / max(1, bw) * 10+ words = (0.015 * ah <= bh <= 0.15 * ah and bw >= 1.5 * bh and not in_picture and crossings >= 1.0+ and out_px >= 0.6 * int(st[cv2.CC_STAT_AREA]))+ here = set()+ if by + bh > zone.y1:+ here.add("bottom")+ if by < zone.y0:+ here.add("top")+ if bx < zone.x0:+ here.add("left")+ if bx + bw > zone.x1:+ here.add("right")+ where |= here+ if words:+ word_where |= here+ if area:+ c.outside[j] = area / (aw * ah)+ c.where[j] = "+".join(sorted(where))+ c.wordy[j] = bool(word_where)+ c.word_where[j] = "+".join(sorted(word_where))+ # Keep the masks of the frames most worth showing.+ worth = max(np.nan_to_num(c.face_cover[j]), c.outside[j] * 20)+ if worth > 0.02:+ keep_best.append((worth, j, mask))+ keep_best.sort(key=lambda t_: -t_[0])+ del keep_best[12:]+ c.maps = {j: m for _, j, m in keep_best}+ c.judged = judged / max(1, n)+ c.aligned_by = geo.kind+ return c+++def _rule(stat, aw: int, ah: int) -> bool:+ """A thin line running most of the frame's length (a wipe's divider, a border): drawn on purpose+ and not words, so not counted against the safe zone."""+ import cv2++ w, h = int(stat[cv2.CC_STAT_WIDTH]), int(stat[cv2.CC_STAT_HEIGHT])+ return (w <= 0.02 * aw and h >= 0.4 * ah) or (h <= 0.02 * ah and w >= 0.4 * aw)+++def _matching(v: np.ndarray, s: np.ndarray, rows: int = 12) -> float:+ """The share of the frame's textured blocks whose shapes still follow the source's there (a+ correlation over 0.3), on a copy 360 high. An overlay leaves most blocks matching; a cutaway to+ another picture leaves almost none, whatever it adds or takes away."""+ import cv2++ h = 360+ w = max(8, int(round(v.shape[1] * h / v.shape[0])))+ a = _structure(cv2.resize(v, (w, h), interpolation=cv2.INTER_AREA))+ b = _structure(cv2.resize(s, (w, h), interpolation=cv2.INTER_AREA))+ cols = max(4, round(rows * w / h))+ ok = tot = 0+ for y in range(rows):+ for x in range(cols):+ pa = a[y * h // rows:(y + 1) * h // rows, x * w // cols:(x + 1) * w // cols].ravel()+ pb = b[y * h // rows:(y + 1) * h // rows, x * w // cols:(x + 1) * w // cols].ravel()+ if pa.std() < 0.15 and pb.std() < 0.15:+ continue # flat in both: says nothing+ tot += 1+ if pa.std() > 1e-6 and pb.std() > 1e-6 and float(np.corrcoef(pa, pb)[0, 1]) > 0.3:+ ok += 1+ return ok / tot if tot else 1.0+++def _covered(part: np.ndarray) -> float:+ """How much of a box something added covers: the area each added shape spans (its bounding box,+ so a word counts by the band it sits in, letters and gaps alike), as a share of the box. Shapes+ too small to be anything but noise are left out."""+ import cv2++ count, _, stats, _ = cv2.connectedComponentsWithStats(part.astype(np.uint8), connectivity=8)+ span = np.zeros(part.shape, bool)+ for i in range(1, count):+ if stats[i, cv2.CC_STAT_AREA] >= 20:+ x, y, w, h = (int(stats[i, cv2.CC_STAT_LEFT]), int(stats[i, cv2.CC_STAT_TOP]),+ int(stats[i, cv2.CC_STAT_WIDTH]), int(stats[i, cv2.CC_STAT_HEIGHT]))+ span[y:y + h, x:x + w] = True+ return float(span.mean())+++def _crop_pos(v: np.ndarray, sf: np.ndarray, across: bool, prev: Optional[int]) -> int:+ """Where the video's frame sits in the source's, along the one axis a crop moves on: near where+ it was in the frame before (a crop glides), or searched for across the whole frame (at a quarter+ of the size, then refined) when it is not found there."""+ import cv2++ gv = _grad(v)+ span = sf.shape[1] - v.shape[1] if across else sf.shape[0] - v.shape[0]+ if prev is not None:+ lo, hi = max(0, prev - 24), min(span, prev + 24)+ part = sf[:, lo:hi + v.shape[1]] if across else sf[lo:hi + v.shape[0], :]+ res = cv2.matchTemplate(_grad(part), gv, cv2.TM_CCOEFF_NORMED)+ line = res[0] if across else res[:, 0]+ if line.max() > 0.5:+ return lo + int(np.argmax(line))+ q = 4+ small_s = cv2.resize(sf, (max(8, sf.shape[1] // q), max(8, sf.shape[0] // q)), interpolation=cv2.INTER_AREA)+ small_v = cv2.resize(v, (max(4, v.shape[1] // q), max(4, v.shape[0] // q)), interpolation=cv2.INTER_AREA)+ res = cv2.matchTemplate(_grad(small_s), _grad(small_v), cv2.TM_CCOEFF_NORMED)+ line = res[0] if across else res[:, 0]+ guess = int(np.argmax(line)) * q+ lo, hi = max(0, guess - 2 * q), min(span, guess + 2 * q)+ part = sf[:, lo:hi + v.shape[1]] if across else sf[lo:hi + v.shape[0], :]+ res = cv2.matchTemplate(_grad(part), gv, cv2.TM_CCOEFF_NORMED)+ line = res[0] if across else res[:, 0]+ return lo + int(np.argmax(line))+++def face_and_zone_checks(c: Compare, fps: float, zone_on: bool, n: int) -> list[Finding]:+ out = []+ cover = np.nan_to_num(c.face_cover, nan=0.0)+ flagged = cover >= FACE_FLAG+ spans = _spans(flagged, fps, gap=2, least=3)+ judged = f"judged in {c.judged:.0%} of frames, the video lined up with the source as {c.aligned_by}"+ away = float(c.elsewhere.mean()) if c.elsewhere is not None and len(c.elsewhere) else 0.0+ if away > 0.02:+ judged += (f"; {away:.0%} of frames show another picture (a cutaway), where the source says nothing about "+ "the face or the margins, so they were left out")+ if spans:+ secs = _secs(spans, fps)+ worst = max(float(cover[a:b].max()) for a, b in spans)+ bad = any(float(cover[a:b].max()) >= FACE_FAIL and (b - a) / fps >= FACE_LONG for a, b in spans)+ level = "fail" if bad else "warn"+ j = max(range(n), key=lambda i: cover[i])+ out.append(Finding("face", level, f"something not in the source covers the face at {_say_spans(secs)} (up to "+ f"{worst:.0%} of the face box); {judged}",+ "move the words or the graphic off the face, or put them behind the person",+ spans=secs, at=round(j / fps, 2)))+ elif c.judged > 0:+ peak = float(cover.max()) if len(cover) else 0.0+ out.append(Finding("face", "pass", f"nothing covers the face (at most {peak:.0%} of the face box changed in "+ f"any frame); {judged}"))+ else:+ out.append(Finding("face", "skip", "the face could not be checked: no face was found in the source"))+ if zone_on:+ flagged = c.outside > 0+ spans = _spans(flagged, fps, gap=2, least=max(3, int(0.2 * fps)))+ if spans:+ secs = _secs(spans, fps)+ wheres = sorted({w for a, b in spans for w in c.where[a:b] if w})+ parts = {"bottom": "the bottom fifth, where the caption and buttons sit",+ "top": "the top tenth, under the app's bar", "left": "the left margin",+ "right": "the right margin, where the buttons sit"}+ said = "; ".join(sorted({parts.get(w, w) for p in wheres for w in p.split("+")}))+ words = any(c.wordy[a:b].any() for a, b in spans)+ # Words under the caption and the buttons (the bottom fifth, the right margin) for half a+ # second or more fail; words under the top bar or in the left margin, and pictures, warn.+ long_bad = any(sum(1 for w in c.word_where[a:b] if "bottom" in w or "right" in w) >= 0.5 * fps+ for a, b in spans)+ what = "words" if words else "a picture or graphic"+ j = int(np.argmax(c.outside))+ out.append(Finding("safe zone", "fail" if long_bad else "warn",+ f"{what} added outside the safe zone at {_say_spans(secs)} ({said})"+ + ("" if words else ": the app's buttons and caption may cover part of it"),+ "move it inside: x 120-960 on a 1080-wide frame, above the bottom fifth, below the top "+ "tenth", spans=secs, at=round(j / fps, 2)))+ else:+ rep = float(c.replaced.mean())+ extra = f" ({rep:.0%} of frames are a whole new picture and were left out)" if rep > 0.05 else ""+ out.append(Finding("safe zone", "pass", "nothing is added outside it" + extra))+ return out+++def face_alone(f: Facts) -> tuple[list[Finding], Optional[facemod.FaceTrack]]:+ """Without the source: the face is found in the video itself, and a face that vanishes for a+ moment between frames where it is plain may be covered."""+ raw = facemod.detect(f.info)+ trusted = facemod.trust(raw, f.info.rate)+ track = facemod.FaceTrack(f.info.width, f.info.height, f.info.rate, raw,+ facemod._fill_and_smooth(trusted, f.info.rate), trusted=trusted)+ fps = f.info.rate+ if track.found_share < 0.3:+ return [Finding("face", "skip", "no face in most of the video, so there is no face to keep clear "+ "(give source= to check against the clip)")], track+ lost = ~track.found+ inner = []+ for a, b in _spans(lost, fps, gap=1, least=max(3, int(0.15 * fps))):+ before = track.found[max(0, a - int(0.5 * fps)):a].mean() if a > 0 else 0+ after = track.found[b:b + int(0.5 * fps)].mean() if b < len(lost) else 0+ if before > 0.8 and after > 0.8:+ inner.append((a, b))+ if inner:+ secs = _secs(inner, fps)+ return [Finding("face", "warn", f"the face disappears for a moment at {_say_spans(secs)}: something may cover "+ f"it (give source= to measure it against the clip)",+ "look at those moments", spans=secs, at=secs[0][0])], track+ return [Finding("face", "pass", f"the face is found in {track.found_share:.0%} of frames and never vanishes "+ f"between them (give source= to measure words over it against the clip)")], track+++# ---- the report and the sheet ----------------------------------------------------------------------++def verdict(findings: list[Finding], strict: bool) -> tuple[str, list[Finding], list[Finding]]:+ fails = [x for x in findings if x.level == "fail"]+ warns = [x for x in findings if x.level == "warn"]+ if fails or (strict and warns):+ return "FAIL", fails + (warns if strict else []), [] if strict else warns+ return "PASS", [], warns+++def write_report(path: Path, f: Facts, src: Optional[Facts], platform: dict, findings: list[Finding],+ strict: bool, sheet: Path, took: float) -> str:+ word, fix, know = verdict(findings, strict)+ name = Path(f.path).name+ lines = [f"# Checks before done: {name}", ""]+ if word == "PASS":+ head = f"**PASS**: ready to post on {platform['name']}."+ if know:+ head += f" {len(know)} thing{'s' if len(know) != 1 else ''} worth knowing, below."+ else:+ head = f"**FAIL**: {len(fix)} thing{'s' if len(fix) != 1 else ''} to fix before posting on {platform['name']}."+ lines += [head, ""]+ if fix:+ lines += ["## Fix first", ""]+ for k, x in enumerate(fix, 1):+ lines.append(f"{k}. **{x.check.capitalize()}**: {x.what}." + (f" Fix: {x.fix}." if x.fix else ""))+ lines.append("")+ if know:+ lines += ["## Worth knowing", ""]+ for x in know:+ lines.append(f"- **{x.check.capitalize()}**: {x.what}." + (f" Fix: {x.fix}." if x.fix else ""))+ lines.append("")+ lines += ["## Every check", "", "| Check | Result | What was measured |", "|---|---|---|"]+ for x in sorted(findings, key=lambda y: LEVEL_ORDER[y.level]):+ lines.append(f"| {x.check} | {x.level.upper()} | {x.what.replace('|', '/')} |")+ lines += ["", f"The contact sheet `{sheet.name}` shows the frames that matter, with the safe zone (dashed) and "+ f"the face box (yellow) drawn; anything in the video over the face that is not in the source is "+ f"tinted red.", ""]+ src_line = f" against its source `{Path(src.path).name}`" if src else " (no source given: the face and the " \+ "safe zone were not measured against it)"+ lines.append(f"Checked{src_line} in {took:.1f} s. The video was not changed.")+ lines += ["", f"The video checked: {fingerprint(f.path)}."]+ path.write_text("\n".join(lines) + "\n")+ return word+++def draw_sheet(path: Path, f: Facts, findings: list[Finding], comp: Optional[Compare], drawn: dict,+ word: str, zone_on: bool, render_face: Optional[facemod.FaceTrack]) -> Path:+ import cv2+ from PIL import Image, ImageDraw, ImageFont++ from ..core.paths import FONTS++ info = f.info+ fps, n, dur = info.rate, info.frames, info.duration+ font = ImageFont.truetype(str(FONTS / "Poppins" / "Poppins-SemiBold.ttf"), 22)+ bold = ImageFont.truetype(str(FONTS / "Poppins" / "Poppins-Bold.ttf"), 30)+ small = ImageFont.truetype(str(FONTS / "Poppins" / "Poppins-SemiBold.ttf"), 16)+ # The moments: each problem's worst frame first, then even fill.+ moments: list[tuple[float, str, str]] = []+ for x in sorted(findings, key=lambda y: LEVEL_ORDER[y.level]):+ if x.level in ("fail", "warn") and x.at is not None and len(moments) < 5:+ if all(abs(x.at - m[0]) > 0.15 for m in moments):+ moments.append((float(x.at), x.check, x.level))+ k = 0+ while len(moments) < 6 and k < 12:+ t = dur * (k + 0.5) / 6 if k < 6 else dur * (k - 5.75) / 6+ if all(abs(t - m[0]) > 0.5 for m in moments):+ moments.append((t, "", "pass"))+ k += 1+ moments.sort()+ tile_h = 520+ tiles = []+ colours = {"fail": (255, 90, 90), "warn": (255, 196, 70), "pass": (200, 200, 205)}+ for t, what, level in moments[:6]:+ j = info.frame_at(t)+ fr = video.read_frame(info, j)+ scale = tile_h / fr.shape[0]+ tw = max(1, int(round(fr.shape[1] * scale)))+ img = cv2.resize(fr, (tw, tile_h), interpolation=cv2.INTER_AREA)+ if comp is not None and j in comp.maps:+ m = cv2.resize(comp.maps[j].astype(np.float32), (tw, tile_h), interpolation=cv2.INTER_NEAREST) > 0.5+ img = img.copy()+ img[m] = (0.45 * img[m] + 0.55 * np.array([255, 40, 40])).astype(np.uint8)+ pil = Image.fromarray(img)+ d = ImageDraw.Draw(pil, "RGBA")+ if zone_on:+ z = SafeZone(tw, tile_h).rect+ _dashed(d, [z.x0, z.y0, z.x1, z.y1], (255, 255, 255, 200))+ box = None+ if comp is not None and comp.boxes is not None and comp.boxes[j] is not None:+ b = comp.boxes[j]+ ax = tw / comp_size(comp, f)[0]+ box = [b.x0 * ax, b.y0 * ax, b.x1 * ax, b.y1 * ax]+ elif render_face is not None and render_face.box(j) is not None and render_face.found[j]:+ b = render_face.box(j)+ box = [b.x0 * scale, b.y0 * scale, b.x1 * scale, b.y1 * scale]+ if box:+ d.rectangle(box, outline=(255, 210, 60, 255), width=3)+ d.rectangle([0, tile_h - 34, tw, tile_h], fill=(0, 0, 0, 180))+ label = f"{t:.2f} s" + (f" {what}" if what else "")+ d.text((8, tile_h - 31), label, fill=colours.get(level, (220, 220, 220)), font=small)+ tiles.append(pil)+ width = max(1700, sum(t.width for t in tiles) + 10 * (len(tiles) - 1) + 40)+ lane_h, lanes = 46, ["picture", "face", "safe zone", "sound"]+ height = 70 + 40 + tile_h + 40 + len(lanes) * (lane_h + 8) + 60+ sheet = Image.new("RGB", (width, height), (18, 18, 20))+ d = ImageDraw.Draw(sheet)+ fails = sum(1 for x in findings if x.level == "fail")+ warns = sum(1 for x in findings if x.level == "warn")+ d.text((20, 14), f"{word}", fill=(255, 90, 90) if word == "FAIL" else (120, 230, 160), font=bold)+ d.text((120, 20), f"{Path(f.path).name} · {info.width}x{info.height}, {fps:.3g} fps, {dur:.2f} s · "+ f"{fails} to fix, {warns} worth knowing", fill=(230, 230, 236), font=font)+ if "lufs" in drawn:+ d.text((20, 60), f"{drawn['lufs']:.1f} LUFS, true peak {drawn['tp']:+.1f} dBTP", fill=(160, 160, 170), font=small)+ x = 20+ y0 = 100+ for tile in tiles:+ sheet.paste(tile, (x, y0))+ x += tile.width + 10+ top = y0 + tile_h + 30+ x0, x1 = 140, width - 20++ def tx(t: float) -> float:+ return x0 + (x1 - x0) * min(max(t, 0.0), dur) / max(dur, 1e-3)++ by = {x_.check: x_ for x_ in findings}+ lane_spans = {+ "picture": [(s, (90, 90, 100)) for k_ in ("black frames", "frozen frames") if k_ in by for s in by[k_].spans],+ "face": [(s, (255, 90, 90)) for s in (by["face"].spans if "face" in by else [])],+ "safe zone": [(s, (255, 170, 60)) for s in (by["safe zone"].spans if "safe zone" in by else [])],+ }+ for k_, name in enumerate(lanes):+ yy = top + k_ * (lane_h + 8)+ d.rectangle([x0, yy, x1, yy + lane_h], fill=(30, 30, 34))+ d.text((20, yy + 12), name, fill=(190, 190, 198), font=small)+ if name == "sound" and "envelope" in drawn:+ env = drawn["envelope"]+ db = env.db+ cols = int(x1 - x0)+ for cx in range(cols):+ a = int(cx / cols * len(db))+ b_ = max(a + 1, int((cx + 1) / cols * len(db)))+ v = float(np.max(db[a:b_])) if b_ <= len(db) else -100+ h = np.clip((v - env.floor) / max(1.0, env.speech - env.floor + 10), 0, 1) * (lane_h - 4)+ d.line([x0 + cx, yy + lane_h - 2, x0 + cx, yy + lane_h - 2 - h], fill=(110, 170, 255))+ for a, b_ in drawn.get("dead", []):+ d.rectangle([tx(a), yy, tx(b_), yy + lane_h], outline=(255, 196, 70), width=2)+ for t in drawn.get("clipped", [])[:100]:+ d.line([tx(t), yy, tx(t), yy + lane_h], fill=(255, 90, 90), width=1)+ for (a, b_), col in lane_spans.get(name, []):+ d.rectangle([tx(a), yy + 4, max(tx(b_), tx(a) + 3), yy + lane_h - 4], fill=col)+ for t, _, _ in moments[:6]:+ xx = tx(t)+ d.polygon([(xx - 7, top - 14), (xx + 7, top - 14), (xx, top - 2)], fill=(230, 230, 230))+ yy = top + len(lanes) * (lane_h + 8) + 6+ sec, stepped = 0.0, (1.0 if dur <= 20 else 5.0 if dur <= 90 else 15.0)+ while sec <= dur + 1e-6:+ d.text((tx(sec) - 6, yy), f"{sec:g}s", fill=(150, 150, 158), font=small)+ sec += stepped+ path = Path(path)+ sheet.save(path, quality=86)+ return path+++def comp_size(c: Compare, f: Facts) -> tuple[int, int]:+ k = ANALYSIS / max(f.info.width, f.info.height)+ return max(2, int(round(f.info.width * k / 2)) * 2), max(2, int(round(f.info.height * k / 2)) * 2)+++def _dashed(d, box, colour, dash: int = 14) -> None:+ x0, y0, x1, y1 = box+ for a, b, c_, e in ((x0, y0, x1, y0), (x0, y1, x1, y1), (x0, y0, x0, y1), (x1, y0, x1, y1)):+ length = max(abs(c_ - a), abs(e - b))+ steps = int(length // dash)+ for k in range(0, steps, 2):+ t0, t1 = k / max(1, steps), min(1.0, (k + 1) / max(1, steps))+ d.line([a + (c_ - a) * t0, b + (e - b) * t0, a + (c_ - a) * t1, b + (e - b) * t1], fill=colour, width=2)+++# ---- the run -------------------------------------------------------------------------------------++def check(video_path: str | Path, source: Optional[str] = None, platform: str = "reels", strict: bool = False,+ out: Optional[Path] = None) -> dict:+ """Every check on `video_path`; writes the report and the sheet and returns what was found."""+ started = time.time()+ plat = PLATFORMS[platform]+ f = Facts(str(video_path))+ src = None+ # The same source whoever asks: given, or else the clip the plan beside the video names (as+ # review-notes takes it), so the command line and review-notes judge the same file alike.+ source = source or planned_source(video_path)+ if source:+ sp = Path(source).expanduser()+ if not sp.exists():+ raise video.MediaError(f"there is no source at {sp}")+ src = Facts(str(sp.resolve()))+ findings = file_checks(f, plat, src)+ zone_on = plat["zone"] and f.info.height > f.info.width * 1.5+ # Line the video up with its source in time, by the sound.+ tmap = None+ quiet_src = None+ comp = None+ render_face = None+ sclip = None+ if src is not None:+ from ..core.clip import Clip++ sclip = Clip(src.path)+ if f.a is not None and src.a is not None:+ env_v = audio.envelope(video.mono(video.read_audio(f.info), video.AUDIO_RATE, 16000), 16000)+ env_s = sclip.envelope+ tmap = time_map(f, src, env_v, env_s, _planned_holds(f.info.path))+ quiet_src = audio.quiet_runs(env_s)+ elif abs(f.info.duration - src.info.duration) < 0.2:+ t = np.arange(f.info.frames) / f.info.rate+ tmap = TimeMap(np.minimum(t, src.info.duration - 1 / src.info.rate), "the same frames (no sound to "+ "line up by; the lengths match)", [], src.info.frames, src.info.rate)+ pic = Picture(f)+ still = np.zeros(f.info.frames, bool)+ for a, b in _spans(pic.diff[:f.info.frames] < FROZEN, f.info.rate, gap=0, least=max(2, int(round(0.25 * f.info.rate)))):+ still[max(0, a - 1):b] = True+ sound, drawn = sound_checks(f, plat, src, tmap, quiet_src, still)+ findings += sound+ voiced = None+ if "envelope" in drawn:+ env = drawn["envelope"]+ voiced = np.ones(f.info.frames, bool)+ for a, b in audio.quiet_runs(env):+ voiced[int(a * f.info.rate):int(np.ceil(b * f.info.rate))] = False+ if tmap is not None and src is not None:+ tmap.source = src+ if tmap.cuts:+ tmap.snap(pic.diff, f.info.rate)+ findings += picture_checks(f, pic, src, tmap, voiced)+ geo, score = (None, 0.0)+ if src is not None and tmap is not None:+ geo, score = geometry(f, src, tmap, pic.size)+ from ..core import hdr++ aligned = (_aligned_samples(f, src, tmap, geo, pic.size)+ if geo is not None and src is not None and hdr.kind(src.transfer) != "sdr" else None)+ findings += colour_checks(f, pic, src, aligned)+ if src is not None and tmap is not None:+ size = pic.size+ if geo is None:+ findings.append(Finding("face", "skip", f"the video does not line up with the source (the best fit scored "+ f"{score:.2f}): a layout or a new picture, so the face was not measured"))+ if zone_on:+ findings.append(Finding("safe zone", "skip", "not measured: the video does not line up with the source"))+ else:+ comp = compare(f, src, sclip.face, tmap, geo, size, zone_on)+ findings += face_and_zone_checks(comp, f.info.rate, zone_on, f.info.frames)+ if tmap.kind != "the same frames":+ findings.append(Finding("lined up", "info", f"in time: {tmap.kind}"+ + (f" ({len(tmap.cuts)} cuts; the frames either side of each were not judged)"+ if tmap.cuts else "") + f"; in space: {geo.kind}"))+ elif src is not None:+ findings.append(Finding("face", "skip", "the video could not be lined up with the source by its sound, so the "+ "face and the safe zone were not measured"))+ else:+ found, render_face = face_alone(f)+ findings += found+ if zone_on:+ findings.append(Finding("safe zone", "skip", "not measured: give source= (the clip it was made from) and "+ "anything added outside the safe zone is found"))+ vid = Path(f.path)+ if out is None:+ report_path = vid.with_name(vid.stem + ".qc.md")+ else:+ out = Path(out)+ report_path = out if out.suffix == ".md" else out.with_name(out.stem + ".qc.md")+ sheet_path = report_path.with_name(report_path.name[:-len(".qc.md")] + ".qc.jpg") \+ if report_path.name.endswith(".qc.md") else report_path.with_suffix(".jpg")+ report_path.parent.mkdir(parents=True, exist_ok=True)+ word, _, _ = verdict(findings, strict)+ sheet = draw_sheet(sheet_path, f, findings, comp, drawn, word, zone_on, render_face)+ took = time.time() - started+ word = write_report(report_path, f, src, plat, findings, strict, sheet, took)+ return {"verdict": word, "findings": findings, "report": report_path, "sheet": sheet, "seconds": took}+++# ---- the same file is checked once ----------------------------------------------------------------++CACHE_VERSION = 1+++def _code_key() -> str:+ """What the checks are made of: this file and the core it reads with. A changed pack checks again."""+ import hashlib++ h = hashlib.sha256()+ for f in [Path(__file__)] + sorted((Path(__file__).resolve().parents[1] / "core").glob("*.py")):+ h.update(f.name.encode())+ h.update(f.read_bytes())+ return h.hexdigest()[:16]+++def _cache_key(video_path, source: Optional[str], platform: str, strict: bool) -> str:+ """The video's bytes, the plan beside it (it names the holds), the source (its path, size and+ time), the platform, strict, and the code."""+ import hashlib++ v = Path(str(video_path))+ plan = v.with_suffix(".plan.json")+ src = source or planned_source(v)+ parts = [str(CACHE_VERSION), fingerprint(v), platform, str(bool(strict)), _code_key(),+ hashlib.sha256(plan.read_bytes()).hexdigest()[:16] if plan.exists() else "no plan"]+ if src:+ sp = Path(src).expanduser().resolve()+ st = sp.stat()+ parts += [str(sp), str(st.st_size), str(st.st_mtime_ns)]+ return hashlib.sha256("|".join(parts).encode()).hexdigest()+++def check_once(video_path: str | Path, source: Optional[str] = None, platform: str = "reels", strict: bool = False,+ out: Optional[Path] = None) -> dict:+ """`check`, remembered by the video's bytes: a file checked before, unchanged, with the same source,+ plan, settings and pack, gives back the findings it had (and its report and sheet, which must still+ be there) without being read again. The memory is kept beside the video (`<video>.qc-cache.json`).+ The result says `cached`."""+ from ..core import paths++ store = paths.beside(video_path, "qc-cache.json")+ key = _cache_key(video_path, source, platform, strict)+ try:+ saved = json.loads(store.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ saved = {}+ hit = saved.get(key) if isinstance(saved, dict) else None+ want = str(Path(out)) if out is not None else None+ if hit and hit.get("out") == want and Path(hit["report"]).exists() and Path(hit["sheet"]).exists():+ findings = [Finding(d["check"], d["level"], d["what"], d.get("fix", ""),+ [tuple(x) for x in d.get("spans", [])], d.get("at")) for d in hit["findings"]]+ return {"verdict": hit["verdict"], "findings": findings, "report": Path(hit["report"]),+ "sheet": Path(hit["sheet"]), "seconds": hit["seconds"], "cached": True}+ r = check(video_path, source, platform, strict, out)+ entry = {"verdict": r["verdict"], "report": str(r["report"]), "sheet": str(r["sheet"]), "seconds": r["seconds"],+ "out": want, "findings": [{"check": x.check, "level": x.level, "what": x.what, "fix": x.fix,+ "spans": [list(map(float, sp)) for sp in x.spans],+ "at": None if x.at is None else float(x.at)} for x in r["findings"]]}+ saved = saved if isinstance(saved, dict) else {}+ saved[key] = entry+ try:+ part = store.with_name(f"{store.name}.{__import__('os').getpid()}.part")+ part.write_text(json.dumps(saved, indent=1))+ part.replace(store)+ except OSError:+ pass # a folder that cannot be written only means checking again next time+ return {**r, "cached": False}+++def _source_motion(src: Facts) -> np.ndarray:+ """How much each frame of the source changes from the one before (on a small grey copy)."""+ import cv2++ info = src.info+ out = np.full(info.frames, np.nan)+ prev = None+ w = 64+ h = max(2, int(w * info.height / info.width))+ for j, fr in enumerate(video.FrameReader(info, size=(w * 2, h * 2))):+ if j >= info.frames:+ break+ g = cv2.resize(_gray(fr), (w, h), interpolation=cv2.INTER_AREA)+ if prev is not None:+ out[j] = float(np.abs(g - prev).mean())+ prev = g+ return out+++def report(video_path, opts: dict, out: Optional[Path], still=None) -> int:+ """What `python -m fx.run qc-check <video>` runs. Prints a line per check, then where the report+ and the sheet are; returns 1 when the verdict is FAIL."""+ r = check(video_path, opts.get("source") or None, opts["platform"], opts["strict"], out)+ word = r["verdict"]+ fails = [x for x in r["findings"] if x.level == "fail"]+ warns = [x for x in r["findings"] if x.level == "warn"]+ print(f"effect: qc-check · {Path(str(video_path)).name} · {opts['platform']}")+ print(f"check: verdict: {word} ({len(fails)} to fix, {len(warns)} worth knowing)")+ for x in sorted(r["findings"], key=lambda y: LEVEL_ORDER[y.level]):+ print(f"check: {x.check}: {x.level.upper()} {x.what}")+ print(f"report: {r['report']}")+ print(f"sheet: {r['sheet']}")+ print(f"checked in {r['seconds']:.1f} s; the video was not changed.")+ print("To fix what it found without rendering again, open the edit in AskEditor: https://askeditor.com, then ask "+ "\"Check my edit before I post it\".")+ return 1 if word == "FAIL" else 0diff --git a/edit/askeditor/fx/meta.py b/edit/askeditor/fx/meta.pynew file mode 100644index 0000000..c49fb4b--- /dev/null+++ b/edit/askeditor/fx/meta.py@@ -0,0 +1,27 @@+"""Where the pack lives, in one place: the repository's address and the pages that show each effect.++`tools/build_manifest.py` (the manifest, the READMEs) and `fx/run.py` (the line after a render) both+read these, so a rename of the repository is a change to `REPO` alone. Standard library only, and+importing it loads nothing else from `fx`.+"""++from __future__ import annotations++REPO = "github.com/AskEditor/ai-video-editing-skills"+REPO_URL = f"https://{REPO}"++PAGES = "askeditor.com/skills" # the directory; each effect has its own page at PAGES/<id>+# Off until askeditor.com/skills/<id> answers: while off, no README and no render points at the pages.+PAGES_LIVE = False+++def prompt(do: str) -> str:+ """The one paste a page offers: install the pack, then do one effect (`do` is the effect's+ request in the person's words, as its effect.json gives it: "clean cut")."""+ # It names the folder, so the agent installs the pack where Claude Code loads skills from.+ return f"Install the free video editing skills from {REPO} into ~/.claude/skills/video-editing, then {do} my video:"+++def page(name: str) -> str:+ """The effect's own page (it answers only once PAGES_LIVE is on)."""+ return f"{PAGES}/{name}"diff --git a/edit/askeditor/fx/run.py b/edit/askeditor/fx/run.pynew file mode 100644index 0000000..7edb202--- /dev/null+++ b/edit/askeditor/fx/run.py@@ -0,0 +1,216 @@+"""Run one effect on one video.++ python -m fx.run <effect> <video> [--opt k=v …] [--plan plan.json] [--still t,…|auto] [-o out.mp4] [--crf 18]+ python -m fx.run list # the effects and their options+ python -m fx.run words <video> [--opt fix=wrong=right] # the words with their times++`--still` draws a few frames exactly as the render will and writes them beside the output+(`<out>.stills.jpg` has them side by side); nothing else is rendered. Every run writes+`<out>.plan.json`: what was decided, which `--plan` takes back after an edit.++The last lines say where the file is and how to keep changing it in AskEditor.+"""++from __future__ import annotations++import argparse+import json+import os+import sys+import time+from pathlib import Path++os.environ.setdefault("GLOG_minloglevel", "2")+os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "3")++from . import meta # noqa: E402+from .core.paths import NeedSetup # noqa: E402+from .core.video import MediaError # noqa: E402++ASKEDITOR = "https://askeditor.com"+++def askeditor_line(effect: str, what: str, lead: str = "To change it without rendering again") -> str:+ """The last line after a render: where to keep changing it in AskEditor. Once the skills pages+ answer (`meta.PAGES_LIVE`), it points at the effect's own page; until then, at AskEditor itself."""+ where = f"https://{meta.page(effect)}" if meta.PAGES_LIVE else ASKEDITOR+ return f"{lead}, open it in AskEditor: {where}, then ask \"{what}\"."+++def _opts(pairs: list[str]) -> dict:+ out = {}+ for p in pairs:+ if "=" not in p:+ raise SystemExit(f"--opt needs name=value (got {p!r})")+ k, v = p.split("=", 1)+ out[k.strip().replace("-", "_")] = v.strip()+ return out+++def _default_out(video: Path, effect: str, ending: str | None = None) -> Path:+ """Beside the video: `<video>-<effect>.mp4`, or `<video><ending>` for an effect that writes a file."""+ folder = video.parent if os.access(video.parent, os.W_OK) else Path.cwd()+ return folder / (f"{video.stem}{ending}" if ending else f"{video.stem}-{effect}.mp4")+++def _still_times(spec: str, job) -> list[float]:+ if spec.strip().lower() in ("auto", ""):+ return job.still_times()+ try:+ return [float(x.strip().rstrip("s")) for x in spec.split(",") if x.strip()]+ except ValueError:+ raise SystemExit(f"--still takes seconds like 1.2,3.5,6 or auto (got {spec!r})") from None+++def cmd_list() -> int:+ from . import effects++ for e in effects.manifest():+ module = effects.load(e["name"])+ print(f"{e['name']}: {e['line']}")+ print(f" type: {e['type_this']}")+ for name, kind in module.OPTIONS.items():+ print(f" {name}={e['options'][name]!s:<8} {kind.help}")+ print()+ return 0+++def cmd_words(video: Path, given: dict) -> int:+ from .core import words+ from .core.clip import Clip++ clip = Clip(video, fix=given.get("fix"))+ ws = clip.words+ print(words.numbered(ws))+ print(f"\n{len(ws)} words, {clip.info.duration:.2f} s. Times are seconds into the clip; each start is when the voice begins.")+ if clip.unsure:+ print("\nHeard on a second listen but not sure, so never shown or cut on:")+ for u in words.unsure_stretches(clip.unsure):+ print(f" {u['s']:6.2f} s \"{u['w']}\": {u['why']}")+ return 0+++def cmd_effect(effect: str, video: Path, given: dict, plan_path: str | None, still: str | None,+ out: Path | None, crf: int = 18, audio_kbps: int = 192) -> int:+ from . import effects+ from .core import render+ from .core.clip import Clip+ from .effects.options import parse_all++ try:+ module = effects.load(effect)+ except KeyError:+ raise SystemExit(f"there is no effect called {effect!r}; the effects are {', '.join(effects.names())}") from None+ entry = effects.entry(effect)+ # Every effect takes fix=, so a person's spelling can go with every command (SKILL.md says to):+ # an effect that does not list it still reads the words put right.+ given = dict(given)+ fix = None+ if "fix" not in module.OPTIONS:+ fix = given.pop("fix", None)+ opts = parse_all(module.OPTIONS, entry["options"], given)+ plan = None+ if plan_path:+ plan = json.loads(Path(plan_path).read_text(encoding="utf-8"))+ if plan.get("effect") != effect:+ raise effects.PlanError(f"that plan is for {plan.get('effect')!r}, not {effect!r}")+ if getattr(module, "REPORTS", False):+ # An effect that only reads the video and reports on it (qc-check): it renders nothing and+ # its exit code is its verdict.+ return module.report(video, opts, out, still=still)+ out = out or _default_out(video, effect, getattr(module, "WRITES", None))+ started = time.time()+ clip = Clip(video, fix=opts.get("fix") or fix)+ made = module.prepare(clip, opts, plan)+ # An effect may make several files from one run (one per shape, say): the first is written to+ # `out` and each other one beside it, named with its label (`talk-reframe-4x5.mp4`).+ jobs = made if isinstance(made, list) else [made]+ out.parent.mkdir(parents=True, exist_ok=True)+ first = jobs[0]+ if first.writes is not None: # words, not pictures: the file is the result+ info = clip.info+ print(f"effect: {effect} · {info.width}x{info.height} at {info.rate:.3g} fps, {info.duration:.2f} s")+ for k, v in first.checks.items():+ print(f"check: {k}: {v}")+ if still is not None:+ print("(this effect draws nothing: it writes a file, so --still makes no stills)")+ extra = first.writes(out) or {}+ for k, v in extra.items():+ if k != "failed":+ print(f"{k}: {v}")+ what = entry["askeditor"]["what"]+ print(askeditor_line(effect, what, "To keep this with the video and change it there"))+ return 1 if extra.get("failed") else 0+ info = first.clip.info+ print(f"effect: {effect} · {info.width}x{info.height} at {info.rate:.3g} fps, {info.duration:.2f} s")+ for n, job in enumerate(jobs):+ target = out if n == 0 else out.with_name(f"{out.stem}-{job.label}{out.suffix}")+ tag = f"{job.label} " if len(jobs) > 1 and job.label else ""+ plan_file = target.with_suffix(".plan.json")+ plan_file.write_text(json.dumps(job.plan, indent=1, ensure_ascii=False) + "\n")+ for k, v in job.checks.items():+ print(f"check: {tag}{k}: {v}")+ print(f"plan: {plan_file}")+ if still is not None:+ times = _still_times(still, job)+ # The job's clip: the clip given, or a film the effect put together from it (several clips joined).+ frames = render.still_frames(job.clip, job.timeline, job.framing, job.draw, times)+ paths = render.save_stills(frames, target)+ print(f"stills: {paths[0]}")+ if job.preview is not None:+ for k, v in (job.preview(target) or {}).items():+ print(f"{k}: {v}")+ continue+ result = render.render(job.clip, job.timeline, job.framing, job.draw, target, crf=crf, audio_kbps=audio_kbps,+ mix=job.sound)+ extra = job.after(result, target) if job.after else {}+ for k, v in (extra or {}).items():+ print(f"{k}: {v}")+ took = time.time() - started+ print(f"video: {result['path']} ({result['seconds_out']:.2f} s, {job.framing.out_w}x{job.framing.out_h}) "+ f"in {took:.1f} s")+ if still is not None:+ print("(stills only: nothing was rendered. Look at them, then run again without --still.)")+ return 0+ what = entry["askeditor"]["what"]+ print(askeditor_line(effect, what))+ return 0+++def main(argv: list[str] | None = None) -> int:+ argv = list(sys.argv[1:] if argv is None else argv)+ if not argv or argv[0] in ("-h", "--help"):+ print(__doc__)+ return 0+ if argv[0] == "list":+ return cmd_list()+ ap = argparse.ArgumentParser(prog="python -m fx.run")+ ap.add_argument("effect")+ ap.add_argument("video")+ ap.add_argument("--opt", action="append", default=[], metavar="NAME=VALUE")+ ap.add_argument("--plan")+ ap.add_argument("--still", nargs="?", const="auto")+ ap.add_argument("-o", "--out")+ ap.add_argument("--crf", type=int, default=18, help="picture quality: 18 (default) is near the source, 23 is half the size")+ ap.add_argument("--audio-kbps", type=int, default=192)+ args = ap.parse_args(argv)+ video = Path(args.video).expanduser().resolve()+ try:+ given = _opts(args.opt)+ if args.effect == "words":+ return cmd_words(video, given)+ out = Path(args.out).expanduser().resolve() if args.out else None+ return cmd_effect(args.effect, video, given, args.plan, args.still, out, crf=args.crf, audio_kbps=args.audio_kbps)+ except NeedSetup as e:+ print(f"NEED_SETUP: {e}", file=sys.stderr)+ return 3+ except MediaError as e:+ print(f"error: {e}", file=sys.stderr)+ return 2+ except ValueError as e: # an option or a plan that cannot be used+ print(f"error: {e}", file=sys.stderr)+ return 2+++if __name__ == "__main__":+ sys.exit(main())diff --git a/edit/askeditor/requirements.txt b/edit/askeditor/requirements.txtnew file mode 100644index 0000000..73d001c--- /dev/null+++ b/edit/askeditor/requirements.txt@@ -0,0 +1,52 @@+# The pack's Python packages, pinned to the versions it is tested with (Python 3.10-3.12).+# setup.sh installs these into .venv, inside the pack's own folder, and nowhere else.++# What the pack imports:+faster-whisper==1.2.1+mediapipe==1.2.0+numpy==2.2.6+opencv-contrib-python==5.0.0.93+pillow==12.3.0++# What those bring with them:+absl-py==2.5.1+anyio==4.15.1+av==17.1.0+certifi==2026.10.23+cffi==2.1.1+click==8.5.0+coloredlogs==15.0.1+contourpy==1.3.2+ctranslate2==4.8.4+cycler==0.12.1+exceptiongroup==1.3.1+filelock==4.1.0+flatbuffers==25.12.19+fonttools==4.65.0+fsspec==2026.9.0+h11==0.16.0+hf-xet==1.7.0+httpcore2==2.14.0+httpx2==2.14.0+huggingface_hub==2.3.0+humanfriendly==10.0+idna==3.20+kiwisolver==1.5.1+matplotlib==3.10.9+mpmath==1.3.0+onnxruntime==1.23.2+packaging==26.3+protobuf==7.36.2+pycparser==3.11+pyparsing==3.3.3+python-dateutil==3.0.0+PyYAML==6.0.3+six==1.17.0+sounddevice==0.5.6+sympy==1.14.0+tokenizers==0.23.3+tomli==2.5.0+tqdm==4.70.1+truststore==0.10.5+typing_extensions==4.16.0+tzdata==2026.5diff --git a/edit/audio.mjs b/edit/audio.mjsnew file mode 100644index 0000000..fb268b9--- /dev/null+++ b/edit/audio.mjs@@ -0,0 +1,60 @@+// Tiếng của bản dựng: GIỌNG GỐC (đã cắt + nối crossfade 20 ms trong bản nền) + nhạc người dùng (tự hạ khi nói,+// khoá theo giọng) + tiếng động LumReels (engine/audio/sfx.mjs) → chỉnh về −14 LUFS, đỉnh ≤ −1,5 dBTP.+// Giọng không bị nén hay đổi; chỉ cả bản trộn được nâng/hạ một mức chung và chặn đỉnh.+import fs from 'node:fs';+import path from 'node:path';+import { run } from '../engine/lib.mjs';+import { writeSfx } from '../engine/audio/sfx.mjs';+import { measureLoudness } from '../engine/audio/mix.mjs';++const ff = async (args, what, timeoutMs = 20 * 60e3) => {+ const r = await run('ffmpeg', ['-hide_banner', '-y', ...args], { timeoutMs });+ if (r.code !== 0) throw new Error(`${what} lỗi: ${r.out.trim().split(/\r?\n/).slice(-3).join(' | ')}`);+ return r;+};++/**+ * base: video nền có tiếng gốc đã cắt. sfx: [{t (giây bản ra), name, gainDb}]. music: {file, gainDb, duckDb, fadeOut}|null.+ * Trả {wav, lufs, truePeak, gainDb}.+ */+export async function buildEditMix({ base, duration, sfx = [], music = null, workDir, lufs = -14, log = console.log }) {+ fs.mkdirSync(workDir, { recursive: true });+ const dlg = path.join(workDir, 'dialogue.wav');+ await ff(['-i', base, '-vn', '-ac', '2', '-ar', '48000', '-c:a', 'pcm_s16le', dlg], 'tách giọng gốc');+ const inputs = ['-i', dlg]; const chains = []; const mixIn = ['[dlg]'];+ chains.push('[0:a]aformat=sample_fmts=fltp:sample_rates=48000:channel_layouts=stereo,asplit=2[dlg][key]');+ let k = 1;+ if (music) {+ inputs.push('-stream_loop', '-1', '-i', music.file);+ const fadeAt = Math.max(0, duration - music.fadeOut);+ // hạ nhạc khi có giọng: sidechain theo giọng gốc; ratio quy đổi gần đúng từ duckDb+ const ratio = Math.min(20, Math.max(1.5, 1 + music.duckDb / 3));+ chains.push(`[${k}:a]aformat=sample_fmts=fltp:sample_rates=48000:channel_layouts=stereo,atrim=0:${duration.toFixed(3)},asetpts=PTS-STARTPTS,volume=${music.gainDb}dB[mraw]`);+ chains.push(`[mraw][key]sidechaincompress=threshold=0.015:ratio=${ratio.toFixed(1)}:attack=15:release=350:makeup=1[mduck]`);+ chains.push(`[mduck]afade=t=out:st=${fadeAt.toFixed(3)}:d=${music.fadeOut}[mus]`);+ mixIn.push('[mus]'); k++;+ } else {+ chains.push('[key]anullsink');+ }+ const sfxDir = path.join(workDir, 'sfx');+ fs.mkdirSync(sfxDir, { recursive: true });+ sfx.forEach((s, n) => {+ const file = path.join(sfxDir, `${s.name}.wav`);+ if (!fs.existsSync(file)) writeSfx(s.name, file, 7);+ inputs.push('-i', file);+ chains.push(`[${k}:a]aformat=sample_fmts=fltp:sample_rates=48000:channel_layouts=stereo,adelay=${Math.round(s.t * 1000)}:all=1,volume=${s.gainDb}dB[s${n}]`);+ mixIn.push(`[s${n}]`); k++;+ });+ chains.push(`${mixIn.join('')}amix=inputs=${mixIn.length}:normalize=0:duration=first,atrim=0:${duration.toFixed(3)}[pre]`);+ const pre = path.join(workDir, 'premix.wav');+ await ff([...inputs, '-filter_complex', chains.join(';'), '-map', '[pre]', '-c:a', 'pcm_f32le', '-ar', '48000', pre], 'trộn tiếng');+ const m = await measureLoudness(pre);+ const gainDb = +(lufs - m.lufs).toFixed(2);+ const wav = path.join(workDir, 'mix.wav');+ // một mức nâng/hạ chung rồi chặn đỉnh −1,5 dBTP (alimiter đo đỉnh mẫu, để thêm 1 dB đệm vì AAC làm đỉnh nhích lên)+ await ff(['-i', pre, '-af', `volume=${gainDb}dB,alimiter=limit=${Math.pow(10, -2.5 / 20).toFixed(4)}:attack=5:release=50:level=disabled`,+ '-c:a', 'pcm_s16le', '-ar', '48000', wav], 'chỉnh độ lớn');+ const after = await measureLoudness(wav);+ log(`tiếng: trước ${m.lufs.toFixed(1)} LUFS → sau ${after.lufs.toFixed(1)} LUFS, đỉnh ${after.truePeak.toFixed(1)} dBTP${music ? ', có nhạc tự hạ khi nói' : ''}, ${sfx.length} tiếng động`);+ return { wav, lufs: after.lufs, truePeak: after.truePeak, gainDb };+}diff --git a/edit/captions-hf.mjs b/edit/captions-hf.mjsnew file mode 100644index 0000000..42e0b7c--- /dev/null+++ b/edit/captions-hf.mjs@@ -0,0 +1,119 @@+// Phụ đề bản chính: một cảnh HyperFrames nền trong suốt (chỉ có chữ), render ra WebM VP9 có alpha,+// rồi ffmpeg chồng lên video nền. Font tiếng Việt lấy từ engine/fonts (fonts.css của LumReels).+// Mốc chữ đổi từ giây nguồn sang giây bản ra theo keep[] của EDL — cùng luật chia thẻ với phụ đề nháp (lumedit.py).+import fs from 'node:fs';+import path from 'node:path';+import { syncLib, runHF } from '../engine/lib.mjs';+import { toOutputNearest, outputDuration, SAFE, OUT } from './edl.mjs';++const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));++/** Cùng luật với caption_cards trong edit/py/lumedit.py. */+export function captionCards(edl) {+ const cap = edl.captions; const keep = edl.keep;+ const groups = []; let cur = [];+ cap.words.forEach((w, n) => {+ cur.push(w);+ const nx = cap.words[n + 1];+ const ends = /[.?!,:;…]$/.test(w.w.trim());+ const gap = nx ? nx.start - w.end : 99;+ if (cur.length >= cap.maxWords || ends || gap > 0.45 || !nx) { groups.push(cur); cur = []; }+ });+ const cards = groups.map((g) => ({ words: g, start: toOutputNearest(keep, g[0].start), end: toOutputNearest(keep, g[g.length - 1].end) }));+ for (let k = 0; k + 1 < cards.length; k++) {+ const gap = cards[k + 1].start - cards[k].end;+ if (gap >= 0 && gap < 0.4) cards[k].end = cards[k + 1].start;+ }+ for (const c of cards) {+ c.end = Math.max(c.end, c.start + 0.25);+ c.wordOut = c.words.map((w) => toOutputNearest(keep, w.start));+ }+ return cards;+}++const LOOKS = {+ 'sach-gon': { font: "'Be Vietnam Pro'", weight: 800, size: 76, upper: false, color: '#FFFFFF', hi: '#FCE802', karaoke: false, cy: 0.70, enter: 'fade' },+ 'phu-de-nay-mau': { font: "'Anton'", weight: 400, size: 150, upper: true, color: '#FFFFFF', hi: '#FCE802', karaoke: true, cy: 0.58, enter: 'pop' },+};++/** Ghi cảnh vào sceneDir. Trả {duration, cards, box}. */+export function writeCaptionScene(edl, sceneDir) {+ const look = LOOKS[edl.captions.style] || LOOKS['sach-gon'];+ const cards = captionCards(edl);+ const dur = Math.max(1 / OUT.fps, Math.round(outputDuration(edl.keep) * OUT.fps) / OUT.fps);+ const hi = new Set(edl.captions.highlights);+ const x0 = Math.round(SAFE.x0 * OUT.width); const w = Math.round((SAFE.x1 - SAFE.x0) * OUT.width);+ const cy = Math.round(look.cy * OUT.height); const yMax = Math.round(SAFE.y1 * OUT.height);+ const html = cards.map((c, ci) => {+ // dấu , . ; : cuối chữ không hiện trên phụ đề (giữ ? ! …)+ const text = c.words.map((wd) => { const t = wd.w.replace(/[,.;:]+$/u, '') || wd.w; return look.upper ? t.toUpperCase() : t; });+ // cỡ chữ: thẻ 1 chữ dài thì thu nhỏ để vừa vùng an toàn (Anton ~0,48 em mỗi ký tự hoa)+ const longest = Math.max(...text.map((t) => t.length));+ const size = c.words.length === 1 ? Math.min(look.size, Math.floor(w / (longest * 0.5 + 0.5))) : look.size;+ const spans = c.words.map((wd, k) => `<span class="w${hi.has(wd.i) ? ' hi' : ''}" id="c${ci}w${k}">${esc(text[k])}</span>`).join(' ');+ return `<div class="card" id="c${ci}" style="font-size:${size}px">${spans}</div>`;+ }).join('\n ');+ const timeline = cards.map((c, ci) => {+ const lines = [`tl.set('#c${ci}', {autoAlpha: 1}, ${c.start.toFixed(3)});`];+ if (look.enter === 'pop') lines.push(`tl.fromTo('#c${ci}', {scale: 0.55}, {scale: 1, duration: 0.18, ease: 'back.out(3)'}, ${c.start.toFixed(3)});`);+ else lines.push(`tl.fromTo('#c${ci}', {y: 18, opacity: 0}, {y: 0, opacity: 1, duration: 0.12, ease: 'power2.out'}, ${c.start.toFixed(3)});`);+ if (look.karaoke && c.words.length > 1) {+ c.words.forEach((wd, k) => {+ const t0 = c.wordOut[k]; const t1 = k + 1 < c.words.length ? c.wordOut[k + 1] : c.end;+ lines.push(`tl.set('#c${ci}w${k}', {color: '${look.hi}'}, ${t0.toFixed(3)}); tl.set('#c${ci}w${k}', {color: '${hi.has(wd.i) ? look.hi : look.color}'}, ${t1.toFixed(3)});`);+ });+ }+ lines.push(`tl.set('#c${ci}', {autoAlpha: 0}, ${c.end.toFixed(3)});`);+ return lines.join(' ');+ }).join('\n ');+ const doc = `<!doctype html>+<html lang="vi">+<head>+<meta charset="UTF-8" />+<meta name="viewport" content="width=${OUT.width}, height=${OUT.height}" />+<link rel="stylesheet" href="./lib/fonts/fonts.css" />+<script src="./lib/vendor/gsap.min.js"></script>+<style>+ html, body { margin:0; width:${OUT.width}px; height:${OUT.height}px; overflow:hidden; background:transparent; }+ #root { position:relative; width:${OUT.width}px; height:${OUT.height}px; overflow:hidden; background:transparent; }+ .card { position:absolute; left:${x0}px; width:${w}px; top:${cy}px; transform-origin:50% 50%;+ margin-top:-0.6em; text-align:center; line-height:1.18; visibility:hidden; opacity:0;+ font-family:${look.font}, sans-serif; font-weight:${look.weight}; color:${look.color};+ -webkit-text-stroke: ${look.upper ? 10 : 8}px #000; paint-order: stroke fill;+ text-shadow: 0 6px 18px rgba(0,0,0,.55); max-height:${yMax - cy}px; }+ .card .w { display:inline-block; }+ .card .hi { color:${look.hi}; }+</style>+</head>+<body>+<div id="root" data-composition-id="main" data-start="0" data-duration="${dur.toFixed(3)}" data-fps="${OUT.fps}" data-width="${OUT.width}" data-height="${OUT.height}">+ ${html}+</div>+<script>+ const tl = gsap.timeline({ paused: true });+ tl.set({}, {}, ${dur.toFixed(3)});+ ${timeline}+ window.__timelines = window.__timelines || {};+ window.__timelines.main = tl;+</script>+</body>+</html>+`;+ fs.mkdirSync(sceneDir, { recursive: true });+ fs.writeFileSync(path.join(sceneDir, 'index.html'), doc);+ syncLib(sceneDir);+ return { duration: dur, cards: cards.length, box: { x0, x1: x0 + w, cy, yMax } };+}++/** Render lớp chữ trong suốt → WebM VP9 alpha. */+export async function renderCaptionLayer(sceneDir, outWebm, { log = console.log } = {}) {+ let last = -1;+ const r = await runHF(['render', sceneDir, '-o', outWebm, '--format', 'webm', '-f', String(OUT.fps), '-q', 'looks', '--quiet'], {+ onLine: (l) => {+ const m = /^@hf-progress (.*)$/.exec(l);+ if (m) { try { const p = JSON.parse(m[1]); const b = Math.floor(p.pct / 20) * 20; if (b !== last) { last = b; log(`phụ đề HyperFrames ${p.pct}% ${p.code}`); } } catch { /* bỏ qua */ } }+ },+ });+ if (r.code !== 0 || !fs.existsSync(outWebm)) throw new Error('HyperFrames render phụ đề lỗi: ' + r.out.trim().split(/\r?\n/).slice(-5).join(' | '));+ return outWebm;+}diff --git a/edit/edl.mjs b/edit/edl.mjsnew file mode 100644index 0000000..a565912--- /dev/null+++ b/edit/edl.mjs@@ -0,0 +1,153 @@+// EDL của LumReels Edit (bản 1): một file JSON mô tả trọn bản dựng từ 1 video nguồn.+// - Mọi mốc thời gian là GIÂY CỦA NGUỒN (timestamp thật, trừ start_time), không phải giây của bản ra.+// Video điện thoại (VFR, xoay, HEVC, HDR) được chuẩn hoá trước thành proxy CFR 30 fps cùng trục thời gian+// (proxy t = nguồn PTS − start_time), nên mốc trong EDL đọc thẳng được trên proxy.+// - Bản ra: hình snap theo khung 30 fps, tiếng snap theo mẫu 48 kHz; âm gốc đi qua mọi vết cắt, nối crossfade 20 ms.+// Nguồn sự thật của schema là zod ở đây; `node edit/edl.mjs --schema` ghi ra edl.schema.json.+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { z } from 'zod';++export const EDL_VERSION = 1;+export const OUT = { width: 1080, height: 1920, fps: 30, audioRate: 48000, lufs: -14 };+export const REMOVE_REASONS = ['pause', 'filler', 'retake', 'false-start', 'aside', 'edge', 'by-hand'];+export const SAFE = { x0: 120 / 1080, x1: 960 / 1080, y0: 0.10, y1: 0.80 }; // vùng an toàn Reels/Shorts/TikTok++const sec = z.number().finite().min(0);+const span = z.object({ start: sec, end: sec }).strict();++export const EdlSchema = z.object({+ version: z.literal(EDL_VERSION),+ id: z.string().min(1),+ createdAt: z.string(),+ style: z.string().min(1).describe('id thẻ kiểu edit (edit-styles/<id>.md)'),+ source: z.object({+ file: z.string(), sha256: z.string().regex(/^[0-9a-f]{64}$/), size: z.number().int().nonnegative(),+ duration: sec, startTime: z.number().describe('start_time của nguồn, đã trừ khi làm proxy'),+ fps: z.number().positive().describe('avg_frame_rate'), vfr: z.boolean(),+ rotation: z.number().describe('độ xoay trong metadata, đã áp vào proxy'),+ width: z.number().int().positive().describe('chiều ngang khi hiển thị (sau xoay)'), height: z.number().int().positive(),+ codec: z.string(), hdr: z.boolean(), hasAudio: z.boolean(),+ }).strict(),+ proxy: z.object({+ file: z.string(), width: z.number().int().positive(), height: z.number().int().positive(),+ fps: z.literal(30), audioRate: z.literal(48000),+ }).strict(),+ output: z.object({+ width: z.literal(OUT.width), height: z.literal(OUT.height), fps: z.literal(OUT.fps),+ audioRate: z.literal(OUT.audioRate), lufs: z.number().min(-30).max(-8),+ }).strict(),+ keep: z.array(span).min(1).describe('đoạn nguồn được giữ, theo thứ tự, không chồng nhau'),+ removed: z.array(span.extend({ reason: z.enum(REMOVE_REASONS), words: z.string().default('') }).strict())+ .describe('đoạn bị bỏ, để người xem lại và đặt lại'),+ reframe: z.object({ mode: z.enum(['face', 'center', 'fill', 'none']) }).strict(),+ zooms: z.array(z.object({+ at: sec.describe('giây nguồn lúc zoom chạm'), dur: z.number().min(0.2).max(8),+ scale: z.number().min(1).max(1.6), kind: z.enum(['punch', 'push']),+ word: z.number().int().nonnegative().optional(),+ }).strict()),+ captions: z.object({+ style: z.string(), renderer: z.enum(['hyperframes', 'pil']),+ maxWords: z.number().int().min(1).max(8), position: z.enum(['lower', 'middle']),+ words: z.array(z.object({ i: z.number().int().nonnegative(), w: z.string().min(1), start: sec, end: sec }).strict()),+ highlights: z.array(z.number().int().nonnegative()).describe('chỉ số i của chữ nhấn'),+ }).strict(),+ sfx: z.array(z.object({ at: sec, name: z.string(), gainDb: z.number().min(-30).max(6) }).strict()),+ music: z.object({+ file: z.string(), gainDb: z.number().min(-40).max(0), duckDb: z.number().min(0).max(30), fadeOut: z.number().min(0).max(10),+ }).strict().nullable(),+ audio: z.object({ crossfadeMs: z.number().min(5).max(80), keepSourceAudio: z.literal(true) }).strict(),+ notes: z.string().optional(),+}).strict();++// ---- ánh xạ thời gian nguồn → bản ra -------------------------------------------------------------------+export function outputDuration(keep) { return keep.reduce((s, k) => s + (k.end - k.start), 0); }+/** Giây nguồn → giây bản ra; null nếu rơi vào đoạn bỏ. */+export function toOutput(keep, t) {+ let acc = 0;+ for (const k of keep) {+ if (t < k.start - 1e-9) return null;+ if (t <= k.end + 1e-9) return acc + (t - k.start);+ acc += k.end - k.start;+ }+ return null;+}+/** Như toOutput nhưng mốc rơi vào đoạn bỏ thì dời về mép giữ gần nhất. */+export function toOutputNearest(keep, t) {+ const got = toOutput(keep, t);+ if (got !== null) return got;+ let best = 0; let bd = Infinity; let acc = 0;+ for (const k of keep) {+ for (const [src, o] of [[k.start, acc], [k.end, acc + k.end - k.start]]) {+ if (Math.abs(src - t) < bd) { bd = Math.abs(src - t); best = o; }+ }+ acc += k.end - k.start;+ }+ return best;+}+export const inKeep = (keep, t) => keep.some((k) => t >= k.start - 1e-6 && t <= k.end + 1e-6);++/**+ * Kiểm EDL: schema + luật thời gian. Trả {ok, errors:[{code, path, msg}], edl}.+ * opts.sfxNames: tên sfx hợp lệ; opts.checkFiles: kiểm file nguồn/nhạc có thật.+ */+export function validateEdl(input, { sfxNames, checkFiles = true } = {}) {+ const errors = [];+ const add = (code, p, msg) => errors.push({ code, path: p, msg });+ const parsed = EdlSchema.safeParse(input);+ if (!parsed.success) {+ for (const i of parsed.error.issues) add('schema', i.path.join('.'), i.message);+ return { ok: false, errors };+ }+ const e = parsed.data;+ const dur = e.source.duration;+ const frame = 1 / e.output.fps;+ e.keep.forEach((k, i) => {+ if (k.end - k.start < frame) add('keep-short', `keep.${i}`, `đoạn giữ ${k.start}–${k.end} ngắn hơn 1 khung`);+ if (k.end > dur + 0.05) add('keep-out', `keep.${i}`, `đoạn giữ vượt quá độ dài nguồn (${dur.toFixed(2)} s)`);+ if (i && k.start < e.keep[i - 1].end - 1e-6) add('keep-overlap', `keep.${i}`, `đoạn giữ chồng/ngược thứ tự với đoạn trước`);+ });+ const outDur = outputDuration(e.keep);+ if (outDur < 1) add('too-short', 'keep', `bản ra chỉ ${outDur.toFixed(2)} s`);+ e.zooms.forEach((zm, i) => {+ if (!inKeep(e.keep, zm.at)) add('zoom-cut', `zooms.${i}`, `zoom ở ${zm.at} s rơi vào đoạn bị bỏ`);+ if (i && zm.at < e.zooms[i - 1].at) add('zoom-order', `zooms.${i}`, 'zoom phải theo thứ tự thời gian');+ });+ const ids = new Set();+ e.captions.words.forEach((w, i) => {+ if (w.end < w.start) add('word-time', `captions.words.${i}`, `chữ "${w.w}" kết thúc trước khi bắt đầu`);+ if (!inKeep(e.keep, (w.start + w.end) / 2)) add('word-cut', `captions.words.${i}`, `chữ "${w.w}" ở ${w.start} s nằm trong đoạn bị bỏ`);+ if (i && w.start < e.captions.words[i - 1].start - 1e-6) add('word-order', `captions.words.${i}`, 'chữ phải theo thứ tự thời gian');+ ids.add(w.i);+ });+ e.captions.highlights.forEach((h, i) => { if (!ids.has(h)) add('highlight', `captions.highlights.${i}`, `chữ nhấn ${h} không có trong phụ đề`); });+ e.sfx.forEach((s, i) => {+ if (sfxNames && !sfxNames.includes(s.name)) add('sfx-name', `sfx.${i}`, `không có tiếng "${s.name}"`);+ if (!inKeep(e.keep, s.at)) add('sfx-cut', `sfx.${i}`, `tiếng "${s.name}" ở ${s.at} s rơi vào đoạn bị bỏ`);+ });+ if (checkFiles) {+ if (!fs.existsSync(e.proxy.file)) add('file', 'proxy.file', `không thấy proxy ${e.proxy.file}`);+ if (e.music && !fs.existsSync(e.music.file)) add('file', 'music.file', `không thấy file nhạc ${e.music.file}`);+ }+ return { ok: errors.length === 0, errors, edl: e };+}++export function writeJsonSchema(file = path.join(path.dirname(fileURLToPath(import.meta.url)), 'edl.schema.json')) {+ const schema = z.toJSONSchema(EdlSchema, { target: 'draft-2020-12', io: 'input' });+ schema.$id = 'https://reels.lumtek.net/schema/edl-v1.json';+ schema.title = 'LumReels Edit EDL v1';+ schema.description = 'Bản dựng từ 1 video nguồn. Mọi mốc thời gian là giây của nguồn (đã trừ start_time).';+ fs.writeFileSync(file, JSON.stringify(schema, null, 2) + '\n');+ return file;+}++if (path.resolve(process.argv[1] || '') === fileURLToPath(import.meta.url)) {+ const a = process.argv.slice(2);+ if (a[0] === '--schema') console.log(writeJsonSchema());+ else if (a[0]) {+ const r = validateEdl(JSON.parse(fs.readFileSync(a[0], 'utf8')));+ console.log(r.ok ? 'EDL hợp lệ' : r.errors.map((x) => `${x.code} ${x.path}: ${x.msg}`).join('\n'));+ process.exit(r.ok ? 0 : 1);+ } else console.log('node edit/edl.mjs --schema | <edl.json>');+}diff --git a/edit/edl.schema.json b/edit/edl.schema.jsonnew file mode 100644index 0000000..525911d--- /dev/null+++ b/edit/edl.schema.json@@ -0,0 +1,468 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "version": {+ "type": "number",+ "const": 1+ },+ "id": {+ "type": "string",+ "minLength": 1+ },+ "createdAt": {+ "type": "string"+ },+ "style": {+ "type": "string",+ "minLength": 1,+ "description": "id thẻ kiểu edit (edit-styles/<id>.md)"+ },+ "source": {+ "type": "object",+ "properties": {+ "file": {+ "type": "string"+ },+ "sha256": {+ "type": "string",+ "pattern": "^[0-9a-f]{64}$"+ },+ "size": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "duration": {+ "type": "number",+ "minimum": 0+ },+ "startTime": {+ "type": "number",+ "description": "start_time của nguồn, đã trừ khi làm proxy"+ },+ "fps": {+ "type": "number",+ "exclusiveMinimum": 0,+ "description": "avg_frame_rate"+ },+ "vfr": {+ "type": "boolean"+ },+ "rotation": {+ "type": "number",+ "description": "độ xoay trong metadata, đã áp vào proxy"+ },+ "width": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991,+ "description": "chiều ngang khi hiển thị (sau xoay)"+ },+ "height": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "codec": {+ "type": "string"+ },+ "hdr": {+ "type": "boolean"+ },+ "hasAudio": {+ "type": "boolean"+ }+ },+ "required": [+ "file",+ "sha256",+ "size",+ "duration",+ "startTime",+ "fps",+ "vfr",+ "rotation",+ "width",+ "height",+ "codec",+ "hdr",+ "hasAudio"+ ],+ "additionalProperties": false+ },+ "proxy": {+ "type": "object",+ "properties": {+ "file": {+ "type": "string"+ },+ "width": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "height": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "fps": {+ "type": "number",+ "const": 30+ },+ "audioRate": {+ "type": "number",+ "const": 48000+ }+ },+ "required": [+ "file",+ "width",+ "height",+ "fps",+ "audioRate"+ ],+ "additionalProperties": false+ },+ "output": {+ "type": "object",+ "properties": {+ "width": {+ "type": "number",+ "const": 1080+ },+ "height": {+ "type": "number",+ "const": 1920+ },+ "fps": {+ "type": "number",+ "const": 30+ },+ "audioRate": {+ "type": "number",+ "const": 48000+ },+ "lufs": {+ "type": "number",+ "minimum": -30,+ "maximum": -8+ }+ },+ "required": [+ "width",+ "height",+ "fps",+ "audioRate",+ "lufs"+ ],+ "additionalProperties": false+ },+ "keep": {+ "minItems": 1,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "start": {+ "type": "number",+ "minimum": 0+ },+ "end": {+ "type": "number",+ "minimum": 0+ }+ },+ "required": [+ "start",+ "end"+ ],+ "additionalProperties": false+ },+ "description": "đoạn nguồn được giữ, theo thứ tự, không chồng nhau"+ },+ "removed": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "start": {+ "type": "number",+ "minimum": 0+ },+ "end": {+ "type": "number",+ "minimum": 0+ },+ "reason": {+ "type": "string",+ "enum": [+ "pause",+ "filler",+ "retake",+ "false-start",+ "aside",+ "edge",+ "by-hand"+ ]+ },+ "words": {+ "default": "",+ "type": "string"+ }+ },+ "required": [+ "start",+ "end",+ "reason"+ ],+ "additionalProperties": false+ },+ "description": "đoạn bị bỏ, để người xem lại và đặt lại"+ },+ "reframe": {+ "type": "object",+ "properties": {+ "mode": {+ "type": "string",+ "enum": [+ "face",+ "center",+ "fill",+ "none"+ ]+ }+ },+ "required": [+ "mode"+ ],+ "additionalProperties": false+ },+ "zooms": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "at": {+ "type": "number",+ "minimum": 0,+ "description": "giây nguồn lúc zoom chạm"+ },+ "dur": {+ "type": "number",+ "minimum": 0.2,+ "maximum": 8+ },+ "scale": {+ "type": "number",+ "minimum": 1,+ "maximum": 1.6+ },+ "kind": {+ "type": "string",+ "enum": [+ "punch",+ "push"+ ]+ },+ "word": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ }+ },+ "required": [+ "at",+ "dur",+ "scale",+ "kind"+ ],+ "additionalProperties": false+ }+ },+ "captions": {+ "type": "object",+ "properties": {+ "style": {+ "type": "string"+ },+ "renderer": {+ "type": "string",+ "enum": [+ "hyperframes",+ "pil"+ ]+ },+ "maxWords": {+ "type": "integer",+ "minimum": 1,+ "maximum": 8+ },+ "position": {+ "type": "string",+ "enum": [+ "lower",+ "middle"+ ]+ },+ "words": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "i": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "w": {+ "type": "string",+ "minLength": 1+ },+ "start": {+ "type": "number",+ "minimum": 0+ },+ "end": {+ "type": "number",+ "minimum": 0+ }+ },+ "required": [+ "i",+ "w",+ "start",+ "end"+ ],+ "additionalProperties": false+ }+ },+ "highlights": {+ "type": "array",+ "items": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "description": "chỉ số i của chữ nhấn"+ }+ },+ "required": [+ "style",+ "renderer",+ "maxWords",+ "position",+ "words",+ "highlights"+ ],+ "additionalProperties": false+ },+ "sfx": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "at": {+ "type": "number",+ "minimum": 0+ },+ "name": {+ "type": "string"+ },+ "gainDb": {+ "type": "number",+ "minimum": -30,+ "maximum": 6+ }+ },+ "required": [+ "at",+ "name",+ "gainDb"+ ],+ "additionalProperties": false+ }+ },+ "music": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "file": {+ "type": "string"+ },+ "gainDb": {+ "type": "number",+ "minimum": -40,+ "maximum": 0+ },+ "duckDb": {+ "type": "number",+ "minimum": 0,+ "maximum": 30+ },+ "fadeOut": {+ "type": "number",+ "minimum": 0,+ "maximum": 10+ }+ },+ "required": [+ "file",+ "gainDb",+ "duckDb",+ "fadeOut"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "audio": {+ "type": "object",+ "properties": {+ "crossfadeMs": {+ "type": "number",+ "minimum": 5,+ "maximum": 80+ },+ "keepSourceAudio": {+ "type": "boolean",+ "const": true+ }+ },+ "required": [+ "crossfadeMs",+ "keepSourceAudio"+ ],+ "additionalProperties": false+ },+ "notes": {+ "type": "string"+ }+ },+ "required": [+ "version",+ "id",+ "createdAt",+ "style",+ "source",+ "proxy",+ "output",+ "keep",+ "removed",+ "reframe",+ "zooms",+ "captions",+ "sfx",+ "music",+ "audio"+ ],+ "additionalProperties": false,+ "$id": "https://reels.lumtek.net/schema/edl-v1.json",+ "title": "LumReels Edit EDL v1",+ "description": "Bản dựng từ 1 video nguồn. Mọi mốc thời gian là giây của nguồn (đã trừ start_time)."+}diff --git a/edit/env.mjs b/edit/env.mjsnew file mode 100644index 0000000..977befc--- /dev/null+++ b/edit/env.mjs@@ -0,0 +1,115 @@+// Môi trường Python riêng của LumReels Edit: đường dẫn venv, biến môi trường khi gọi Python,+// và hàm chạy `lumedit` (CLI Python) theo giao thức dòng: "@progress {...}" và dòng cuối "@result {...}".+import fs from 'node:fs';+import path from 'node:path';+import { spawn } from 'node:child_process';+import { fileURLToPath } from 'node:url';++export const EDIT = path.dirname(fileURLToPath(import.meta.url));+export const ROOT = path.dirname(EDIT);+export const PACK = path.join(EDIT, 'askeditor'); // mã AskEditor đã chép vào (MIT)+export const VENV = path.join(EDIT, '.venv');+export const LUMEDIT = path.join(EDIT, 'py', 'lumedit.py');+export const WHISPER_MODEL = process.env.LUMEDIT_WHISPER || 'large-v3';++/** Python trong venv riêng (không bao giờ là Python hệ thống). */+export function venvPython() {+ const win = path.join(VENV, 'Scripts', 'python.exe');+ const nix = path.join(VENV, 'bin', 'python');+ return process.platform === 'win32' ? win : nix;+}++export function venvReady() { return fs.existsSync(venvPython()); }++/** Thư mục chứa thư viện CUDA của wheel nvidia-* trong venv (Linux cần LD_LIBRARY_PATH trước khi Python chạy). */+function cudaLibDirs() {+ if (process.platform !== 'linux') return [];+ const lib = path.join(VENV, 'lib');+ if (!fs.existsSync(lib)) return [];+ const out = [];+ for (const py of fs.readdirSync(lib)) {+ const nv = path.join(lib, py, 'site-packages', 'nvidia');+ if (!fs.existsSync(nv)) continue;+ for (const sub of fs.readdirSync(nv)) {+ const d = path.join(nv, sub, 'lib');+ if (fs.existsSync(d)) out.push(d);+ }+ }+ return out;+}++/** Biến môi trường cho mọi tiến trình Python của Edit. */+export function pyEnv(extra = {}) {+ const env = { ...process.env };+ delete env.ANTHROPIC_API_KEY;+ const libs = cudaLibDirs();+ return {+ ...env,+ PYTHONUTF8: '1', // Windows: mặc định cp1252 làm vỡ chữ Việt+ PYTHONIOENCODING: 'utf-8',+ PYTHONPATH: PACK + (env.PYTHONPATH ? path.delimiter + env.PYTHONPATH : ''),+ FX_LANG: env.FX_LANG || 'vi',+ FX_WHISPER: env.FX_WHISPER || WHISPER_MODEL,+ FX_DEVICE: env.FX_DEVICE || 'auto',+ GLOG_minloglevel: '2',+ TF_CPP_MIN_LOG_LEVEL: '3',+ HF_HUB_DISABLE_SYMLINKS_WARNING: '1',+ HF_HUB_DISABLE_TELEMETRY: '1',+ ...(libs.length ? { LD_LIBRARY_PATH: [...libs, env.LD_LIBRARY_PATH].filter(Boolean).join(':') } : {}),+ ...extra,+ };+}++/**+ * Chạy `python -X utf8 edit/py/lumedit.py <args>`. onProgress nhận object của mỗi dòng "@progress".+ * Trả {ok, result, code, log}. result = JSON của dòng "@result" cuối cùng.+ */+export function runLumedit(args, { onProgress, onLine, timeoutMs = 3 * 60 * 60 * 1000 } = {}) {+ return new Promise((resolve) => {+ if (!venvReady()) return resolve({ ok: false, code: 3, error: 'Chưa cài môi trường Edit: chạy node edit/setup.mjs', log: '' });+ const p = spawn(venvPython(), ['-X', 'utf8', LUMEDIT, ...args], { cwd: PACK, env: pyEnv(), windowsHide: true });+ let log = ''; let buf = ''; let result = null;+ const timer = setTimeout(() => { log += '\n[lumedit] quá thời gian, dừng\n'; p.kill(); }, timeoutMs);+ const feed = (d) => {+ const s = d.toString();+ log += s; buf += s;+ let i;+ while ((i = buf.indexOf('\n')) >= 0) {+ const line = buf.slice(0, i).replace(/\r$/, ''); buf = buf.slice(i + 1);+ if (line.startsWith('@progress ')) { try { onProgress?.(JSON.parse(line.slice(10))); } catch { /* bỏ qua */ } }+ else if (line.startsWith('@result ')) { try { result = JSON.parse(line.slice(8)); } catch { /* bỏ qua */ } }+ else if (line.trim()) onLine?.(line);+ }+ };+ p.stdout.on('data', feed);+ p.stderr.on('data', feed);+ p.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, code: -1, error: String(e), log }); });+ p.on('close', (code) => {+ clearTimeout(timer);+ if (buf.startsWith('@result ')) { try { result = JSON.parse(buf.slice(8)); } catch { /* bỏ qua */ } }+ const ok = code === 0 && result?.ok === true;+ resolve({ ok, code, result, log, error: ok ? undefined : (result?.error || log.trim().split(/\r?\n/).slice(-6).join('\n')) });+ });+ });+}++/** Tổng dung lượng 1 thư mục (byte), đi theo cây thư mục, bỏ symlink. */+export function dirSize(dir) {+ let total = 0;+ if (!fs.existsSync(dir)) return 0;+ const stack = [dir];+ while (stack.length) {+ const d = stack.pop();+ let ents = [];+ try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch { continue; }+ for (const e of ents) {+ const f = path.join(d, e.name);+ if (e.isSymbolicLink()) continue;+ if (e.isDirectory()) stack.push(f);+ else { try { total += fs.statSync(f).size; } catch { /* bỏ qua */ } }+ }+ }+ return total;+}++export const fmtBytes = (n) => (n >= 1e9 ? `${(n / 1e9).toFixed(2)} GB` : n >= 1e6 ? `${Math.round(n / 1e6)} MB` : `${Math.round(n / 1e3)} KB`);diff --git a/edit/ingest.mjs b/edit/ingest.mjsnew file mode 100644index 0000000..a135b9b--- /dev/null+++ b/edit/ingest.mjs@@ -0,0 +1,98 @@+// Nạp video nguồn: đọc đủ metadata (xoay, VFR, HDR, start_time, âm), băm SHA-256, rồi dựng proxy+// CFR 30 fps · H.264 yuv420p SDR BT.709 · đã xoay đúng chiều · GOP 1 s · âm 48 kHz stereo+// cùng trục thời gian với nguồn (proxy t = PTS nguồn − start_time). Nguồn giữ nguyên, không sửa.+import fs from 'node:fs';+import crypto from 'node:crypto';+import { run } from '../engine/lib.mjs';++const num = (v) => (v === undefined || v === null || v === 'N/A' ? NaN : Number(v));+const ratio = (s) => { const [a, b] = String(s || '0/1').split('/').map(Number); return b ? a / b : NaN; };++export function sha256File(file) {+ return new Promise((resolve, reject) => {+ const h = crypto.createHash('sha256');+ fs.createReadStream(file).on('data', (d) => h.update(d)).on('end', () => resolve(h.digest('hex'))).on('error', reject);+ });+}++/** ffprobe đầy đủ: luồng hình/tiếng, xoay (side data hoặc tag), màu, fps thật và trung bình. */+export async function probeSource(file) {+ const r = await run('ffprobe', ['-v', 'error', '-show_format', '-show_streams', '-of', 'json', file]);+ let j;+ try { j = JSON.parse(r.out); } catch { throw new Error(`ffprobe không đọc được ${file}`); }+ const v = (j.streams || []).find((s) => s.codec_type === 'video' && !s.disposition?.attached_pic);+ const a = (j.streams || []).find((s) => s.codec_type === 'audio');+ if (!v) throw new Error('file không có luồng hình');+ let rotation = 0;+ for (const sd of v.side_data_list || []) if (typeof sd.rotation === 'number') rotation = sd.rotation;+ if (!rotation && v.tags?.rotate) rotation = Number(v.tags.rotate) || 0;+ rotation = ((Math.round(rotation) % 360) + 360) % 360;+ const sar = ratio(v.sample_aspect_ratio && v.sample_aspect_ratio !== '0:1' ? v.sample_aspect_ratio.replace(':', '/') : '1/1') || 1;+ let w = Math.round(v.width * (sar > 0 ? sar : 1)); let h = v.height;+ if (rotation === 90 || rotation === 270) [w, h] = [h, w];+ const rFps = ratio(v.r_frame_rate); const aFps = ratio(v.avg_frame_rate);+ const transfer = v.color_transfer || '';+ const hdr = ['smpte2084', 'arib-std-b67'].includes(transfer) || /bt2020/.test(v.color_primaries || '');+ const duration = num(j.format?.duration) || num(v.duration);+ return {+ duration, startTime: num(j.format?.start_time) || num(v.start_time) || 0,+ fps: Number.isFinite(aFps) && aFps > 0 ? aFps : rFps,+ vfr: Number.isFinite(rFps) && Number.isFinite(aFps) && aFps > 0 && Math.abs(rFps - aFps) / aFps > 0.01,+ rotation, width: w, height: h, codec: v.codec_name, pixFmt: v.pix_fmt,+ color: { primaries: v.color_primaries || '', transfer, matrix: v.color_space || '', range: v.color_range || '' },+ hdr, hasAudio: !!a, audio: a ? { codec: a.codec_name, rate: num(a.sample_rate), channels: a.channels, layout: a.channel_layout || '' } : null,+ };+}++let zscaleOk = null;+async function hasZscale() {+ if (zscaleOk === null) { const r = await run('ffmpeg', ['-hide_banner', '-filters']); zscaleOk = / zscale /.test(r.out); }+ return zscaleOk;+}++/**+ * Proxy CFR 30 fps. Cạnh ngắn tối đa 1080 (dọc: rộng ≤ 1080; ngang: cao ≤ 1080). HDR → tonemap về SDR BT.709+ * (cần ffmpeg có zscale). Nguồn không có tiếng → chèn tiếng lặng để mọi bước sau có luồng âm.+ */+export async function makeProxy(file, info, out, { log = console.log } = {}) {+ const portrait = info.height >= info.width;+ const scale = portrait ? "scale='min(1080,iw)':-2:flags=lanczos" : "scale=-2:'min(1080,ih)':flags=lanczos";+ const vf = [];+ if (info.hdr) {+ if (await hasZscale()) vf.push('zscale=t=linear:npl=100', 'format=gbrpf32le', 'zscale=p=bt709', 'tonemap=hable:desat=0', 'zscale=t=bt709:m=bt709:r=tv');+ else log('cảnh báo: video HDR nhưng ffmpeg không có zscale, màu có thể nhạt');+ }+ vf.push(scale, 'setsar=1', 'fps=30', 'format=yuv420p');+ // -ss/-itsoffset không dùng: ffmpeg tự trừ start_time khi ghi (avoid_negative_ts), xoay được áp tự động (autorotate).+ const args = ['-hide_banner', '-y', '-i', file];+ if (!info.hasAudio) args.push('-f', 'lavfi', '-i', 'anullsrc=r=48000:cl=stereo');+ args.push('-map', '0:v:0', '-map', info.hasAudio ? '0:a:0' : '1:a:0',+ '-vf', vf.join(','), '-fps_mode', 'cfr',+ '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '16', '-g', '30', '-keyint_min', '30', '-sc_threshold', '0',+ '-color_primaries', 'bt709', '-color_trc', 'bt709', '-colorspace', 'bt709',+ '-c:a', 'pcm_s16le', '-ar', '48000', '-ac', '2',+ '-t', String(info.duration), '-avoid_negative_ts', 'make_zero', '-movflags', '+faststart', out);+ const movOut = out;+ const r = await run('ffmpeg', args, { timeoutMs: Math.max(10 * 60e3, info.duration * 20e3) });+ if (r.code !== 0 || !fs.existsSync(movOut)) throw new Error('dựng proxy lỗi: ' + r.out.trim().split(/\r?\n/).slice(-4).join(' | '));+ return movOut;+}++/** Nạp: probe + băm + proxy (.mov, tiếng PCM để không lệch mốc như AAC). Trả {source, proxy} đúng dạng EDL. */+export async function ingest(file, proxyOut, { log = console.log } = {}) {+ const info = await probeSource(file);+ if (!Number.isFinite(info.duration) || info.duration <= 0) throw new Error('không đọc được độ dài video');+ log(`nguồn: ${info.width}×${info.height} ${info.codec} ${info.fps.toFixed(2)} fps${info.vfr ? ' (VFR)' : ''}${info.rotation ? ` xoay ${info.rotation}°` : ''}${info.hdr ? ' HDR' : ''} · ${info.duration.toFixed(2)} s${info.hasAudio ? '' : ' · KHÔNG có tiếng'}`);+ const [sha, proxyFile] = await Promise.all([sha256File(file), makeProxy(file, info, proxyOut, { log })]);+ const pr = await run('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height', '-of', 'json', proxyFile]);+ const ps = JSON.parse(pr.out).streams[0];+ return {+ info,+ source: {+ file, sha256: sha, size: fs.statSync(file).size, duration: +info.duration.toFixed(3), startTime: info.startTime,+ fps: +info.fps.toFixed(3), vfr: info.vfr, rotation: info.rotation, width: info.width, height: info.height,+ codec: info.codec, hdr: info.hdr, hasAudio: info.hasAudio,+ },+ proxy: { file: proxyFile, width: ps.width, height: ps.height, fps: 30, audioRate: 48000 },+ };+}diff --git a/edit/pipeline.mjs b/edit/pipeline.mjsnew file mode 100644index 0000000..8c99c69--- /dev/null+++ b/edit/pipeline.mjs@@ -0,0 +1,153 @@+// LumReels Edit — luồng dựng video người dùng tự quay theo một thẻ kiểu edit.+// 1 nạp (probe, băm, proxy CFR 30) 2 phân tích (whisper large-v3 tiếng Việt, khoảng lặng, mặt)+// 3 LLM lập đề xuất → code dựng EDL → kiểm 4 xem trước lưới 16 khung+// 5 render nền 1 lượt (cắt + reframe 9:16 + zoom; tiếng gốc nối 20 ms) + kiểm lẹm chữ (nghe lại)+// 6 phụ đề: HyperFrames lớp trong suốt (bản chính) hoặc PIL vẽ thẳng (--draft)+// 7 tiếng: giọng gốc + nhạc tự hạ + sfx → −14 LUFS 8 ghép → out.mp4 9 kiểm (qc-check + kích thước + lưới khung)+// Đầu ra: edits/<id>/ (edl.json, preview.jpg, out.mp4, preview-final.jpg, qc.json, result.json, log.txt)+import fs from 'node:fs';+import path from 'node:path';+import crypto from 'node:crypto';+import { run } from '../engine/lib.mjs';+import { SFX_NAMES } from '../engine/audio/sfx.mjs';+import { measureLoudness } from '../engine/audio/mix.mjs';+import { ROOT, runLumedit } from './env.mjs';+import { ingest } from './ingest.mjs';+import { loadStyle, wordList, propose, compileEdl } from './planner.mjs';+import { validateEdl, toOutputNearest, outputDuration, OUT } from './edl.mjs';+import { writeCaptionScene, renderCaptionLayer } from './captions-hf.mjs';+import { buildEditMix } from './audio.mjs';++export const EDITS = path.join(ROOT, 'edits');++function newId() {+ const d = new Date(); const p = (n) => String(n).padStart(2, '0');+ return `${String(d.getFullYear()).slice(2)}${p(d.getMonth() + 1)}${p(d.getDate())}${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}-${crypto.randomBytes(2).toString('hex')}`;+}++/**+ * opts: {style, music?, content?, draft?, llm?: 'on'|'off', id?, log?}+ * Trả {ok, id, dir, out, timings, checks, error?}+ */+export async function editVideo(video, opts = {}) {+ const id = opts.id || newId();+ const dir = path.join(EDITS, id);+ fs.mkdirSync(dir, { recursive: true });+ const logFile = path.join(dir, 'log.txt');+ const log = (s) => { const line = `[${new Date().toISOString().slice(11, 19)}] ${s}`; fs.appendFileSync(logFile, line + '\n'); (opts.log || console.log)(line); };+ const timings = {}; const checks = {}; const warnings = [];+ const step = async (name, fn) => { const t = Date.now(); log(`— ${name}`); const r = await fn(); timings[name] = +((Date.now() - t) / 1000).toFixed(1); log(` xong ${name}: ${timings[name]} s`); return r; };+ const result = { ok: false, id, dir, video: path.resolve(video), style: opts.style, draft: !!opts.draft, timings, checks, warnings };+ const save = () => fs.writeFileSync(path.join(dir, 'result.json'), JSON.stringify(result, null, 2));+ try {+ if (!fs.existsSync(video)) throw new Error(`không thấy video ${video}`);+ if (opts.music && !fs.existsSync(opts.music)) throw new Error(`không thấy file nhạc ${opts.music}`);+ const style = { ...loadStyle(opts.style || 'sach-gon'), sfxNames: SFX_NAMES };+ log(`edit ${id}: ${path.basename(video)} · kiểu ${style.id}${opts.draft ? ' · bản nháp (phụ đề PIL)' : ''}${opts.music ? ' · nhạc ' + path.basename(opts.music) : ''}`);++ const ing = await step('nạp', () => ingest(path.resolve(video), path.join(dir, 'proxy.mov'), { log }));++ const analysisFile = path.join(dir, 'analysis.json');+ const an = await step('phân tích', async () => {+ const r = await runLumedit(['analyze', ing.proxy.file, '--out', analysisFile], { onProgress: (p) => log(` ${p.step}${p.note ? ': ' + p.note : ''}`) });+ if (!r.ok) throw new Error('phân tích lỗi: ' + r.error);+ return { ...r.result, data: JSON.parse(fs.readFileSync(analysisFile, 'utf8')) };+ });+ log(` ${an.words} chữ chắc + ${an.unsure} chữ không chắc · whisper ${an.seconds.words} s · mặt ${an.seconds.face} s (thấy mặt ${Math.round(an.data.face.found_share * 100)}% khung)`);+ if (!an.words) throw new Error('không nghe được lời nào trong video');++ const words = wordList(an.data);+ style.hesitations = new Set(an.data.hesitations || []);+ const plan = await step('LLM lập EDL', () => propose({ words, style, content: opts.content, duration: ing.source.duration, llm: opts.llm || 'on', log }));+ fs.writeFileSync(path.join(dir, 'proposal.json'), JSON.stringify({ ...plan, words: words.map((w) => `${w.i}:${w.w}${w.unsure ? '?' : ''}`) }, null, 1));+ warnings.push(...plan.warnings);+ log(` đề xuất (vòng ${plan.rounds}): bỏ ${plan.proposal.drop.length} khoảng, ${plan.proposal.zooms.length} zoom, ${plan.proposal.highlights.length} chữ nhấn, ${plan.proposal.fixes.length} chữ sửa${plan.proposal.notes ? ' · ' + plan.proposal.notes : ''}`);++ const byI = new Map(words.map((w) => [w.i, w.w]));+ checks.fixes = plan.proposal.fixes.map((f) => `${byI.get(f.word)} → ${f.text || '(ẩn)'}`);+ if (checks.fixes.length) log(` chữ LLM sửa (cần người xem lại): ${checks.fixes.join(', ')}`);+ const edl = compileEdl({ id, ingestRes: ing, analysis: an.data, words, proposal: plan.proposal, style, music: opts.music, draft: opts.draft });+ const v = validateEdl(edl, { sfxNames: SFX_NAMES });+ if (!v.ok) throw new Error('EDL không hợp lệ (lỗi code dựng EDL): ' + v.errors.map((e) => `${e.code} ${e.path}: ${e.msg}`).join('; '));+ const edlFile = path.join(dir, 'edl.json');+ fs.writeFileSync(edlFile, JSON.stringify(edl, null, 1));+ const outDur = outputDuration(edl.keep);+ checks.edl = { keep: edl.keep.length, removed: edl.removed.length, removedSeconds: +(ing.source.duration - outDur).toFixed(2), zooms: edl.zooms.length, sfx: edl.sfx.length, captionWords: edl.captions.words.length };+ log(` EDL: ${ing.source.duration.toFixed(2)} s → ${outDur.toFixed(2)} s, ${edl.keep.length} đoạn giữ, ${edl.zooms.length} zoom, ${edl.sfx.length} sfx`);+ for (const r of edl.removed) log(` bỏ ${r.start.toFixed(2)}–${r.end.toFixed(2)} s (${r.reason})${r.words ? ': ' + r.words : ''}`);++ await step('xem trước', async () => {+ const r = await runLumedit(['stills', edlFile, '--out', path.join(dir, 'preview.jpg'), '--count', '16', '--draft-captions']);+ if (!r.ok) throw new Error('xem trước lỗi: ' + r.error);+ });++ const base = path.join(dir, 'base.mp4');+ const rb = await step('render nền', async () => {+ const r = await runLumedit(['render', edlFile, '--out', base, ...(opts.draft ? ['--draft-captions'] : [])], {+ onProgress: (p) => { if (p.step === 'render' && p.pct % 25 === 0) log(` render ${p.pct}% (${p.done}/${p.total})`); else if (p.step !== 'render') log(` ${p.step}${p.note ? ': ' + p.note : ''}`); },+ });+ if (!r.ok) throw new Error('render nền lỗi: ' + r.error);+ return r.result;+ });+ timings['render nền (vẽ khung)'] = rb.seconds.render;+ if (rb.seconds.overcut_check !== undefined) timings['kiểm lẹm chữ (nghe lại)'] = rb.seconds.overcut_check;+ checks.overcut = rb.overcut;+ log(` lẹm chữ: ${rb.overcut?.verdict}`);++ let overlay = null;+ if (!opts.draft && edl.captions.words.length) {+ overlay = await step('phụ đề HyperFrames', async () => {+ const sc = writeCaptionScene(edl, path.join(dir, 'captions'));+ checks.captions = { cards: sc.cards, box: sc.box, safeZone: 'trong 120–960 px, đáy ≤ 80% khung' };+ return renderCaptionLayer(path.join(dir, 'captions'), path.join(dir, 'captions.webm'), { log });+ });+ }++ const mix = await step('tiếng', () => buildEditMix({+ base, duration: rb.seconds_out, workDir: path.join(dir, 'audio'), lufs: edl.output.lufs, log,+ sfx: edl.sfx.map((s) => ({ t: toOutputNearest(edl.keep, s.at), name: s.name, gainDb: s.gainDb })),+ music: edl.music,+ }));++ const out = path.join(dir, 'out.mp4');+ await step('ghép', async () => {+ const args = ['-hide_banner', '-y', '-i', base];+ if (overlay) args.push('-c:v', 'libvpx-vp9', '-i', overlay);+ args.push('-i', mix.wav);+ const ai = overlay ? 2 : 1;+ if (overlay) args.push('-filter_complex', '[0:v][1:v]overlay=0:0:format=auto:eof_action=pass,format=yuv420p[v]', '-map', '[v]', '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', '-r', String(OUT.fps));+ else args.push('-map', '0:v:0', '-c:v', 'copy');+ args.push('-map', `${ai}:a:0`, '-c:a', 'aac', '-b:a', '192k', '-ar', '48000', '-ac', '2', '-shortest', '-movflags', '+faststart', out);+ const r = await run('ffmpeg', args, { timeoutMs: 60 * 60e3 });+ if (r.code !== 0) throw new Error('ghép lỗi: ' + r.out.trim().split(/\r?\n/).slice(-3).join(' | '));+ });++ await step('kiểm', async () => {+ const pr = await run('ffprobe', ['-v', 'error', '-show_entries', 'stream=codec_type,codec_name,width,height,r_frame_rate:format=duration', '-of', 'json', out]);+ const j = JSON.parse(pr.out);+ const vs = j.streams.find((s) => s.codec_type === 'video'); const as = j.streams.find((s) => s.codec_type === 'audio');+ checks.file = { width: vs.width, height: vs.height, fps: vs.r_frame_rate, video: vs.codec_name, audio: as?.codec_name || null, duration: +Number(j.format.duration).toFixed(2) };+ checks.file.ok = vs.width === OUT.width && vs.height === OUT.height && vs.r_frame_rate === '30/1' && !!as;+ const loud = await measureLoudness(out);+ checks.loudness = { lufs: +loud.lufs.toFixed(1), truePeak: +loud.truePeak.toFixed(1), ok: Math.abs(loud.lufs - OUT.lufs) <= 1 && loud.truePeak <= -1 };+ const n = 16; const d = checks.file.duration;+ const sel = Array.from({ length: n }, (_, k) => `eq(n\\,${Math.floor(((k + 0.5) / n) * d * OUT.fps)})`).join('+');+ await run('ffmpeg', ['-hide_banner', '-y', '-i', out, '-vf', `select='${sel}',scale=270:480,tile=4x4:padding=6:color=0x181818`, '-frames:v', '1', '-q:v', '3', path.join(dir, 'preview-final.jpg')]);+ const q = await runLumedit(['qc', out, '--out', path.join(dir, 'qc.json')]);+ if (q.ok) {+ checks.qc = { verdict: q.result.verdict, fails: q.result.findings.filter((f) => f.level === 'fail').map((f) => `${f.check}: ${f.what}`), warns: q.result.findings.filter((f) => f.level === 'warn').map((f) => `${f.check}: ${f.what}`) };+ } else warnings.push('qc-check lỗi: ' + q.error);+ log(` file ${checks.file.width}×${checks.file.height} ${checks.file.fps} ${checks.file.duration} s · ${checks.loudness.lufs} LUFS / ${checks.loudness.truePeak} dBTP · qc ${checks.qc?.verdict || '?'}`);+ for (const f of checks.qc?.fails || []) log(` qc FAIL ${f}`);+ });+ // proxy + nền là file trung gian lớn; giữ lại để sửa EDL rồi render lại không phải phân tích lại+ result.ok = true; result.out = out; result.edl = edlFile;+ timings.total = +Object.entries(timings).filter(([k]) => !k.includes('(')).reduce((s, [, v]) => s + v, 0).toFixed(1);+ log(`XONG ${out} (${timings.total} s)`);+ } catch (e) {+ result.error = e.message;+ log('LỖI: ' + e.message);+ }+ save();+ return result;+}diff --git a/edit/planner.mjs b/edit/planner.mjsnew file mode 100644index 0000000..f2fdc34--- /dev/null+++ b/edit/planner.mjs@@ -0,0 +1,289 @@+// LLM lập đề xuất ngữ nghĩa (bỏ đoạn nào, nhấn chữ nào, zoom/sfx ở chữ nào, sửa chính tả) → code dựng EDL.+// LLM chỉ quyết Ý NGHĨA theo chỉ số chữ; mọi mốc thời gian, đệm biên cắt, khoảng lặng, mật độ zoom do code (compileEdl).+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { spawnClaude, findClaude } from '../generator/claude.mjs';+import { MODEL_IDS } from '../generator/config.mjs';+import { ROOT } from './env.mjs';+import { EDL_VERSION, OUT, REMOVE_REASONS } from './edl.mjs';++export const STYLES_DIR = path.join(ROOT, 'edit-styles');+const LLM_TIMEOUT_MS = 6 * 60 * 1000;++// ---- thẻ kiểu edit -------------------------------------------------------------------------------------------+/** edit-styles/<id>.md: khối ```---json … ---``` đầu file là preset có version; phần còn lại là hướng dẫn cho LLM. */+export function loadStyle(id) {+ const file = path.join(STYLES_DIR, `${id}.md`);+ if (!fs.existsSync(file)) throw new Error(`không có kiểu edit "${id}" (có: ${listStyles().join(', ')})`);+ const text = fs.readFileSync(file, 'utf8');+ const m = /^---json\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/.exec(text.replace(/\r\n/g, '\n'));+ if (!m) throw new Error(`${file}: thiếu khối ---json ở đầu`);+ const preset = JSON.parse(m[1]);+ if (preset.id !== id) throw new Error(`${file}: id trong preset là "${preset.id}"`);+ return { ...preset, guide: m[2].trim(), file };+}+export function listStyles() {+ return fs.existsSync(STYLES_DIR) ? fs.readdirSync(STYLES_DIR).filter((f) => f.endsWith('.md')).map((f) => f.slice(0, -3)) : [];+}++// ---- transcript cho LLM ------------------------------------------------------------------------------------------+const key = (w) => w.toLowerCase().normalize('NFC').replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, '');++/** Gộp chữ chắc chắn + chữ "không chắc" (nghe lại lần 2) thành 1 dãy đánh số theo thời gian. */+export function wordList(analysis) {+ const all = analysis.words.map((w) => ({ w: w.w, s: w.s, e: w.e, unsure: false }))+ .concat((analysis.unsure || []).map((w) => ({ w: w.w, s: w.s, e: w.e, unsure: true })));+ all.sort((a, b) => a.s - b.s || a.e - b.e);+ // whisper tách số "50.000" thành "50" + ".000": gộp lại thành một chữ+ const merged = [];+ for (const w of all) {+ const prev = merged[merged.length - 1];+ if (prev && !prev.unsure && !w.unsure && /^[.,]\d{3}/.test(w.w) && /\d$/.test(prev.w)) {+ prev.w += w.w; prev.e = Math.max(prev.e, w.e);+ } else merged.push({ ...w });+ }+ return merged.map((w, i) => ({ ...w, i }));+}++function transcriptText(words) {+ const lines = []; let line = [];+ const flush = () => { if (line.length) { lines.push(line.join(' ')); line = []; } };+ for (let k = 0; k < words.length; k++) {+ const w = words[k];+ if (!line.length) line.push(`(${w.s.toFixed(2)}s)`);+ line.push(`[${w.i}]${w.w}${w.unsure ? '?' : ''}`);+ const nx = words[k + 1];+ const gap = nx ? nx.s - w.e : 0;+ if (gap >= 0.6) { flush(); lines.push(`… lặng ${gap.toFixed(1)} s …`); }+ else if (/[.?!]$/.test(w.w) || line.length > 16) flush();+ }+ flush();+ return lines.join('\n');+}++export function buildPrompt({ words, style, content, duration, errors, previous }) {+ const sfx = style.sfxNames.join(', ');+ return `Mày là biên tập viên video ngắn tiếng Việt. Video người dùng tự quay, nói trước máy, dài ${duration.toFixed(1)} giây.+Nhiệm vụ: đọc lời chép (có số thứ tự từng chữ) và quyết theo THẺ KIỂU EDIT: bỏ đoạn nào, nhấn chữ nào, zoom và đặt tiếng động ở chữ nào, sửa chữ máy nghe sai.+Chỉ trả về MỘT khối JSON, không giải thích ngoài JSON.++# THẺ KIỂU EDIT: ${style.name} (${style.id})+${style.guide}++# Lời dặn của người dùng+${content?.trim() || '(không có)'}++# Lời chép (máy nghe, có thể sai chính tả; [i] là số thứ tự chữ; chữ có dấu "?" là chữ máy nghe lại lần 2 nhưng không chắc, thường nằm ở chỗ nói lại hoặc nói vấp)+${transcriptText(words)}++# Định dạng trả về+{+ "drop": [{"from": <i>, "to": <i>, "reason": "retake|false-start|filler|aside", "why": "<ngắn>"}],+ "highlights": [<i>, ...],+ "zooms": [<i>, ...],+ "sfx": [{"word": <i>, "name": "<một trong: ${sfx}>"}],+ "fixes": [{"word": <i>, "text": "<chữ đúng>"}],+ "notes": "<1–2 câu: đã bỏ gì, vì sao>"+}+Luật:+- "drop" là các khoảng chữ liền nhau [from..to] (gồm cả hai đầu) cần bỏ CẢ TIẾNG LẪN HÌNH. Nói lại: bỏ lần nói trước (kể cả phần nói dở), giữ lần sau cùng. Không chồng nhau. "filler" chỉ dùng cho từ đệm đứng riêng (ờ, ừm, ơ…).+- KHÔNG dùng "drop" để sửa chữ: tên riêng bị máy nghe tách thành 2 chữ (vd "luôn phin") thì giữ tiếng, dùng "fixes": chữ đầu → tên đúng, chữ sau → "" (ẩn khỏi phụ đề).+- Không cần liệt kê khoảng lặng: code tự rút. Không bỏ quá nửa số chữ.+- "highlights", "zooms", "sfx", "fixes" chỉ dùng chữ KHÔNG bị bỏ. Zoom theo mật độ của thẻ kiểu (${style.zoom.perMinute[0]}–${style.zoom.perMinute[1]} lần mỗi phút, cách nhau ≥ ${style.zoom.minGap} giây).+- "fixes" (text "" = ẩn chữ đó khỏi phụ đề, vẫn giữ tiếng): CHỈ sửa chữ mà máy nghe sai rõ ràng: chữ vô nghĩa trong câu, hoặc tên riêng/thuật ngữ người dùng đã dặn. Chữ đang hợp nghĩa (dù mày nghĩ người nói muốn chữ khác) thì GIỮ NGUYÊN — sửa sai còn tệ hơn không sửa. Mỗi mục 1 chữ → 1 chữ đúng (có thể vài tiếng).+${errors ? `\n# LẦN TRƯỚC SAI, SỬA LẠI\nJSON lần trước:\n${previous}\nLỗi:\n${errors.map((e) => '- ' + e).join('\n')}\n` : ''}`;+}++// ---- gọi Claude (không tool) -----------------------------------------------------------------------------------+export function callClaude(prompt, { model = process.env.EDIT_MODEL || MODEL_IDS.sonnet, log = console.log } = {}) {+ if (!findClaude()) return Promise.reject(new Error('Không tìm thấy lệnh claude (cài Claude Code hoặc đặt CLAUDE_BIN)'));+ const args = ['-p', '--output-format', 'json', '--permission-mode', 'default', '--tools', '',+ '--setting-sources', 'project', '--strict-mcp-config', '--no-session-persistence', '--max-turns', '2', '--model', model];+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'lumreels-edit-'));+ log(`LLM: ${model}`);+ return new Promise((resolve, reject) => {+ const p = spawnClaude(args, { cwd, windowsHide: true, env: (({ ANTHROPIC_API_KEY, ...e }) => e)(process.env) });+ let out = ''; let err = '';+ const timer = setTimeout(() => { p.kill(); reject(new Error(`Claude quá ${LLM_TIMEOUT_MS / 1000}s`)); }, LLM_TIMEOUT_MS);+ p.stdout.on('data', (d) => { out += d; });+ p.stderr.on('data', (d) => { err += d; });+ p.on('error', (e) => { clearTimeout(timer); reject(new Error('spawn claude lỗi: ' + e.message)); });+ p.on('close', (code) => {+ clearTimeout(timer);+ fs.rm(cwd, { recursive: true, force: true }, () => {});+ let r = null;+ try { r = JSON.parse(out.trim().split(/\r?\n/).pop()); } catch { /* không phải JSON */ }+ if (code !== 0 || !r || r.is_error) return reject(new Error(`claude thoát mã ${code}: ${(r?.result || err || out).toString().trim().slice(-500)}`));+ resolve({ text: String(r.result || ''), costUSD: r.total_cost_usd ?? null, usage: r.usage || {} });+ });+ p.stdin.end(prompt);+ });+}++export function parseProposal(text) {+ const m = /```(?:json)?\s*([\s\S]*?)```/.exec(text);+ const raw = (m ? m[1] : text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1)).trim();+ return JSON.parse(raw);+}++// ---- kiểm đề xuất (ngữ nghĩa) -----------------------------------------------------------------------------------+/** Trả {errors[], clean}: clean là đề xuất đã bỏ mục hỏng (dùng khi LLM sửa 1 vòng vẫn sai). */+export function checkProposal(p, words, style) {+ const errors = []; const n = words.length;+ const isIdx = (i) => Number.isInteger(i) && i >= 0 && i < n;+ const clean = { drop: [], highlights: [], zooms: [], sfx: [], fixes: [], notes: typeof p?.notes === 'string' ? p.notes : '' };+ if (!p || typeof p !== 'object') return { errors: ['không phải object JSON'], clean };+ const dropped = new Set();+ const drops = Array.isArray(p.drop) ? [...p.drop].sort((a, b) => a.from - b.from) : [];+ if (p.drop !== undefined && !Array.isArray(p.drop)) errors.push('"drop" phải là mảng');+ let lastTo = -1;+ for (const d of drops) {+ if (!isIdx(d.from) || !isIdx(d.to) || d.from > d.to) { errors.push(`drop ${JSON.stringify(d)}: from/to không hợp lệ (0..${n - 1}, from ≤ to)`); continue; }+ if (d.from <= lastTo) { errors.push(`drop ${d.from}–${d.to} chồng lên khoảng trước`); continue; }+ const reason = ['retake', 'false-start', 'filler', 'aside'].includes(d.reason) ? d.reason : 'retake';+ if (reason !== d.reason) errors.push(`drop ${d.from}–${d.to}: reason "${d.reason}" không hợp lệ`);+ if (reason === 'filler') {+ const notFiller = words.slice(d.from, d.to + 1).filter((w) => !style.hesitations.has(key(w.w)));+ if (notFiller.length) { errors.push(`drop ${d.from}–${d.to} (filler): "${notFiller.map((w) => w.w).join(' ')}" không phải từ đệm; sửa chữ thì dùng fixes`); continue; }+ }+ clean.drop.push({ from: d.from, to: d.to, reason, why: String(d.why || '') });+ for (let i = d.from; i <= d.to; i++) dropped.add(i);+ lastTo = d.to;+ }+ const sure = words.filter((w) => !w.unsure).length;+ if (dropped.size > Math.max(3, 0.5 * n)) errors.push(`bỏ ${dropped.size}/${n} chữ, quá nửa`);+ if (sure && words.filter((w) => !w.unsure && !dropped.has(w.i)).length === 0) errors.push('không còn chữ nào được giữ');+ const keptIdx = (i, what) => {+ if (!isIdx(i)) { errors.push(`${what} ${i}: không có chữ này`); return false; }+ if (dropped.has(i)) { errors.push(`${what} ${i} ("${words[i].w}") nằm trong đoạn bị bỏ`); return false; }+ return true;+ };+ for (const i of p.highlights || []) if (keptIdx(i, 'highlight')) clean.highlights.push(i);+ for (const i of p.zooms || []) if (keptIdx(i, 'zoom')) clean.zooms.push(i);+ for (const s of p.sfx || []) {+ if (!style.sfxNames.includes(s?.name)) { errors.push(`sfx "${s?.name}" không có trong danh sách`); continue; }+ if (keptIdx(s.word, 'sfx')) clean.sfx.push({ word: s.word, name: s.name });+ }+ for (const f of p.fixes || []) {+ const t = typeof f?.text === 'string' ? f.text.trim() : '';+ if (typeof f?.text !== 'string' || t.length > 40) { errors.push(`fix ${JSON.stringify(f)}: chữ sửa không hợp lệ hoặc quá dài`); continue; }+ if (keptIdx(f.word, 'fix')) clean.fixes.push({ word: f.word, text: t });+ }+ return { errors, clean };+}++/** Đề xuất khi không dùng LLM (--llm off, hoặc LLM lỗi): không bỏ chữ nào, zoom đều theo mật độ thẻ kiểu. */+export function fallbackProposal(words, style) {+ const zooms = []; let last = -Infinity;+ const gap = Math.max(style.zoom.minGap, 60 / style.zoom.perMinute[0] / 1.5);+ for (const w of words) {+ if (w.unsure || key(w.w).length < 3) continue;+ if (w.s - last >= gap) { zooms.push(w.i); last = w.s; }+ }+ return { drop: [], highlights: [], zooms, sfx: [], fixes: [], notes: 'không dùng LLM: chỉ rút khoảng lặng, zoom đều' };+}++/** LLM lập đề xuất; sai thì gửi lỗi cho LLM sửa đúng 1 vòng; vẫn sai thì bỏ mục hỏng. */+export async function propose({ words, style, content, duration, llm = 'on', log = console.log }) {+ if (llm === 'off') return { proposal: fallbackProposal(words, style), rounds: 0, warnings: ['LLM tắt'], costUSD: 0 };+ const warnings = [];+ let text = ''; let cost = 0; let prev = null;+ for (let round = 1; round <= 2; round++) {+ const prompt = buildPrompt({ words, style, content, duration, errors: prev?.errors, previous: prev ? text.slice(0, 6000) : '' });+ let checked;+ try {+ const r = await callClaude(prompt, { log });+ text = r.text; cost += r.costUSD || 0;+ checked = checkProposal(parseProposal(text), words, style);+ } catch (e) {+ checked = { errors: [`không đọc được JSON: ${e.message}`], clean: null };+ }+ if (!checked.errors.length) return { proposal: checked.clean, rounds: round, warnings, costUSD: cost, raw: text };+ log(`LLM vòng ${round}: ${checked.errors.length} lỗi: ${checked.errors.slice(0, 3).join('; ')}`);+ prev = checked;+ }+ warnings.push(...prev.errors.map((e) => 'bỏ mục hỏng: ' + e));+ return { proposal: prev.clean || fallbackProposal(words, style), rounds: 2, warnings, costUSD: cost, raw: text };+}++// ---- code dựng EDL từ đề xuất ------------------------------------------------------------------------------------+const LEAD = 0.10; // giữ trước chữ đầu mỗi đoạn+const TAIL = 0.22; // giữ sau chữ cuối (whisper hay báo hết chữ sớm ~0,15 s; spike đo 0,10–0,21 s)+const MIN_CUT = 0.12; // cắt ngắn hơn thế thì không đáng một cú nhảy hình+const EDGE_END = 0.35; // giữ sau chữ cuối cùng của video++export function compileEdl({ id, ingestRes, analysis, words, proposal, style, music, draft }) {+ const dur = ingestRes.source.duration;+ const hes = new Set(analysis.hesitations || []);+ const reasonOf = new Map();+ for (const d of proposal.drop) for (let i = d.from; i <= d.to; i++) reasonOf.set(i, d.reason);+ for (const w of words) {+ if (style.cutFillers && hes.has(key(w.w)) && !reasonOf.has(w.i)) reasonOf.set(w.i, 'filler');+ }+ const kept = words.filter((w) => !reasonOf.has(w.i));+ if (!kept.length) throw new Error('không còn chữ nào để giữ');+ const keep = []; const removed = [];+ let segStart = Math.max(0, kept[0].s - LEAD);+ if (segStart > 0.3) removed.push({ start: 0, end: +segStart.toFixed(3), reason: 'edge', words: words.filter((w) => w.e <= segStart).map((w) => w.w).join(' ') });+ for (let k = 0; k + 1 < kept.length; k++) {+ const a = kept[k]; const b = kept[k + 1];+ const between = words.filter((w) => w.i > a.i && w.i < b.i);+ const gap = b.s - a.e;+ if (!between.length && gap <= style.pause) continue;+ let cs = a.e + TAIL; let ce = b.s - LEAD;+ if (between.length) {+ const f = between[0]; const l = between[between.length - 1];+ cs = Math.max(a.e + 0.04, Math.min(cs, f.s - 0.005));+ ce = Math.min(b.s - 0.04, Math.max(ce, l.e + 0.005));+ }+ if (ce - cs < MIN_CUT) continue;+ keep.push({ start: +segStart.toFixed(3), end: +cs.toFixed(3) });+ const reasons = [...new Set(between.map((w) => reasonOf.get(w.i)).filter(Boolean))];+ removed.push({ start: +cs.toFixed(3), end: +ce.toFixed(3), reason: reasons[0] || 'pause', words: between.map((w) => w.w).join(' ') });+ segStart = ce;+ }+ const endT = Math.min(dur, kept[kept.length - 1].e + EDGE_END);+ keep.push({ start: +segStart.toFixed(3), end: +endT.toFixed(3) });+ if (dur - endT > 0.3) removed.push({ start: +endT.toFixed(3), end: +dur.toFixed(3), reason: 'edge', words: '' });++ // zoom: theo đề xuất, ép khoảng cách tối thiểu của thẻ kiểu+ const byIdx = new Map(words.map((w) => [w.i, w]));+ const zooms = []; let lastZ = -Infinity;+ for (const i of [...new Set(proposal.zooms)].sort((x, y) => x - y)) {+ const w = byIdx.get(i);+ if (!w || reasonOf.has(i) || w.s - lastZ < style.zoom.minGap) continue;+ zooms.push({ at: +w.s.toFixed(3), dur: style.zoom.dur, scale: style.zoom.scale, kind: style.zoom.kind, word: i });+ lastZ = w.s;+ }+ // zoom không được tràn sang cú sau+ for (let k = 0; k + 1 < zooms.length; k++) zooms[k].dur = +Math.max(0.2, Math.min(zooms[k].dur, zooms[k + 1].at - zooms[k].at - 0.05)).toFixed(3);++ const fixes = new Map(proposal.fixes.map((f) => [f.word, f.text]));+ const capWords = kept.filter((w) => !hes.has(key(w.w)) && fixes.get(w.i) !== '')+ .map((w) => ({ i: w.i, w: fixes.get(w.i) || w.w, start: +w.s.toFixed(3), end: +Math.max(w.e, w.s + 0.05).toFixed(3) }));+ const capIds = new Set(capWords.map((w) => w.i));++ const sfx = [];+ for (const s of proposal.sfx) { const w = byIdx.get(s.word); if (w && !reasonOf.has(s.word)) sfx.push({ at: +w.s.toFixed(3), name: s.name, gainDb: style.sfx.gainDb }); }+ if (style.sfx.onZoom) for (const z of zooms) sfx.push({ at: z.at, name: style.sfx.onZoom, gainDb: style.sfx.gainDb });+ sfx.sort((a, b) => a.at - b.at);+ const sfxOut = sfx.filter((s, k) => k === 0 || s.at - sfx[k - 1].at > 0.15).slice(0, style.sfx.max);++ return {+ version: EDL_VERSION, id, createdAt: new Date().toISOString(), style: style.id,+ source: ingestRes.source, proxy: ingestRes.proxy,+ output: { ...OUT },+ keep, removed: removed.filter((r) => REMOVE_REASONS.includes(r.reason)),+ reframe: { mode: 'face' },+ zooms,+ captions: {+ style: style.captions.style, renderer: draft ? 'pil' : 'hyperframes', maxWords: style.captions.maxWords,+ position: style.captions.position, words: capWords, highlights: [...new Set(proposal.highlights)].filter((i) => capIds.has(i)),+ },+ sfx: sfxOut,+ music: music ? { file: path.resolve(music), gainDb: style.music.gainDb, duckDb: style.music.duckDb, fadeOut: style.music.fadeOut } : null,+ audio: { crossfadeMs: 20, keepSourceAudio: true },+ notes: proposal.notes || '',+ };+}diff --git a/edit/py/fonts.py b/edit/py/fonts.pynew file mode 100644index 0000000..e304b01--- /dev/null+++ b/edit/py/fonts.py@@ -0,0 +1,46 @@+"""Builds Be Vietnam Pro TTF files (600, 700, 800) for the draft captions, by joining LumReels' own+woff2 subsets (latin, latin-ext, vietnamese) from engine/fonts with fontTools. PIL needs one file+per face; the subsets split the letters across three.++ python fonts.py <engine/fonts> <out dir>+"""+import sys+from pathlib import Path++from fontTools.merge import Merger+from fontTools.ttLib import TTFont++NEED = "ăâđêôơưàảãáạằẳẵắặầẩẫấậèẻẽéẹềểễếệìỉĩíịòỏõóọồổỗốộờởỡớợùủũúụừửữứựỳỷỹýỵĂÂĐÊÔƠƯ"+++def build(src: Path, weight: int, out: Path) -> None:+ parts = []+ for sub in ("latin", "latin-ext", "vietnamese"):+ f = TTFont(src / f"be-vietnam-pro-{sub}-{weight}-normal.woff2")+ f.flavor = None+ p = out.with_name(f"{out.stem}.{sub}.part.ttf")+ f.save(p)+ parts.append(p)+ merged = Merger().merge([str(p) for p in parts])+ merged.save(out)+ for p in parts:+ p.unlink()+ cmap = TTFont(out).getBestCmap()+ missing = [c for c in NEED + "AZaz09" if ord(c) not in cmap]+ if missing:+ raise SystemExit(f"{out.name} is missing {''.join(missing)}")+++def main() -> int:+ src, dest = Path(sys.argv[1]), Path(sys.argv[2])+ dest.mkdir(parents=True, exist_ok=True)+ for w in (600, 700, 800):+ out = dest / f"BeVietnamPro-{w}.ttf"+ if not out.exists():+ build(src, w, out)+ print(f" fonts ready: Be Vietnam Pro 600/700/800 in {dest}")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/edit/py/lumedit.py b/edit/py/lumedit.pynew file mode 100644index 0000000..3d402d2--- /dev/null+++ b/edit/py/lumedit.py@@ -0,0 +1,413 @@+"""LumReels Edit: the Python side, built on the AskEditor pack's core (edit/askeditor/fx, MIT).++ python -X utf8 lumedit.py analyze <proxy.mp4> --out analysis.json+ python -X utf8 lumedit.py render <edl.json> --out base.mp4 [--draft-captions] [--no-check]+ python -X utf8 lumedit.py stills <edl.json> --out preview.jpg [--count 16] [--draft-captions]+ python -X utf8 lumedit.py qc <final.mp4> --out qc.json++Talks to Node line by line: `@progress {json}` while it works, and one `@result {json}` at the end+({"ok": true, ...} or {"ok": false, "error": "..."}). Exit 0 on success, 2 on bad input, 3 when setup+is missing, 1 on any other failure.++Everything in an EDL is in source seconds; the proxy shares the source's time axis. The render is+one pass: AskEditor's Timeline (the kept stretches, with the source sound joined by 20 ms+crossfades) and Framing (9:16 window following the face), then our zooms and draft captions drawn+on each output frame.+"""++from __future__ import annotations++import argparse+import json+import math+import os+import sys+import time+import traceback+from functools import lru_cache+from pathlib import Path++PACK = Path(__file__).resolve().parents[1] / "askeditor"+sys.path.insert(0, str(PACK))+os.environ.setdefault("GLOG_minloglevel", "2")+os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "3")++OUT_W, OUT_H, OUT_FPS = 1080, 1920, 30+SAFE = (120 / 1080, 0.10, 960 / 1080, 0.80) # x0, y0, x1, y1 as shares of the frame+++def emit(kind: str, obj: dict) -> None:+ print(f"@{kind} " + json.dumps(obj, ensure_ascii=False), flush=True)+++def progress(step: str, **kw) -> None:+ emit("progress", {"step": step, **kw})+++# ---- analyze ---------------------------------------------------------------------------------------------++def cmd_analyze(proxy: Path, out: Path) -> dict:+ from fx.core.clip import Clip+ from fx.core import words as wordsmod++ t0 = time.time()+ clip = Clip(proxy)+ info = clip.info+ progress("words", note=f"chép lời ({os.environ.get('FX_WHISPER') or 'small.en'}, {wordsmod.LANG})")+ ws = clip.words+ t_words = time.time() - t0+ progress("quiet")+ quiet = clip.quiet+ progress("face")+ t1 = time.time()+ face = clip.face+ t_face = time.time() - t1+ fps = info.rate+ faces = []+ step = max(1, int(round(fps / 2)))+ for i in range(0, info.frames, step):+ b = face.box(i) if face.any() else None+ faces.append(None if b is None else [round(i / fps, 2), round(b.x0), round(b.y0), round(b.w), round(b.h)])+ data = {+ "proxy": str(proxy), "duration": round(info.duration, 3), "fps": fps, "frames": info.frames,+ "width": info.width, "height": info.height,+ "words": [{"i": i, "w": w.text, "s": round(w.start, 3), "e": round(w.end, 3), "p": round(w.prob, 3)}+ for i, w in enumerate(ws)],+ "unsure": [{"w": w.text, "s": round(w.start, 3), "e": round(w.end, 3), "why": w.unsure} for w in clip.unsure],+ "quiet": [[round(a, 3), round(b, 3)] for a, b in quiet],+ "face": {"found_share": round(float(face.found_share), 3) if face.any() else 0.0,+ "every_half_second": [f for f in faces if f is not None]},+ "hesitations": sorted(wordsmod.HESITATIONS),+ "model": wordsmod.model_key("small.en"), "lang": wordsmod.LANG,+ "seconds": {"words": round(t_words, 1), "face": round(t_face, 1), "total": round(time.time() - t0, 1)},+ }+ out.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")+ return {"out": str(out), "words": len(ws), "unsure": len(clip.unsure), "seconds": data["seconds"]}+++# ---- shared: the EDL as AskEditor objects ------------------------------------------------------------------++def load_edl(path: Path) -> dict:+ edl = json.loads(path.read_text(encoding="utf-8"))+ if edl.get("version") != 1:+ raise ValueError(f"EDL version {edl.get('version')!r} is not supported (want 1)")+ return edl+++def build(edl: dict, draft_captions: bool):+ from fx.core import framing as framing_mod+ from fx.core.clip import Clip+ from fx.core.timeline import Timeline++ clip = Clip(edl["proxy"]["file"])+ info = clip.info+ if abs(info.rate - OUT_FPS) > 0.01:+ raise ValueError(f"the proxy runs at {info.rate} fps; it must be the 30 fps proxy")+ segs = tuple((float(k["start"]), min(float(k["end"]), info.duration)) for k in edl["keep"])+ tl = Timeline(tuple((a, b) for a, b in segs if b - a > 1e-3))+ mode = edl["reframe"]["mode"]+ face = clip.face if mode == "face" else None+ fr = framing_mod.plan(info.width, info.height, info.rate, info.frames, face, shape="9:16",+ size=(OUT_W, OUT_H), mode={"face": "track", "center": "center", "fill": "fill",+ "none": "center"}[mode])+ if (fr.out_w, fr.out_h) != (OUT_W, OUT_H):+ fr.out_w, fr.out_h = OUT_W, OUT_H+ zooms = Zooms(edl, tl, fr, clip)+ caps = DraftCaptions(edl, tl) if draft_captions and edl["captions"]["words"] else None++ def draw(frame, j, t):+ zooms.apply(frame, j, t)+ if caps is not None:+ caps.draw(frame, t)++ return clip, tl, fr, draw+++# ---- zooms ---------------------------------------------------------------------------------------------------++def _ease(x: float) -> float:+ x = min(1.0, max(0.0, x))+ return x * x * (3 - 2 * x)+++class Zooms:+ """Each zoom of the EDL on the output picture: a punch (in fast, hold, out) or a slow push, about+ the face where the zoom begins (or the upper middle of the frame when no face is found)."""++ PUNCH_IN, PUNCH_OUT = 0.08, 0.12++ def __init__(self, edl: dict, tl, fr, clip):+ self.items = []+ fps = clip.info.rate+ for z in edl["zooms"]:+ t0 = tl.to_output_nearest(float(z["at"]))+ k = tl.source_frame(int(round(t0 * fps)), fps, clip.info.frames)+ cx, cy = OUT_W / 2, OUT_H * 0.40+ head = clip.face.head(k) if clip.face.any() else None+ if head is not None:+ r = fr.to_output(head, k)+ cx, cy = (r.x0 + r.x1) / 2, (r.y0 + r.y1) / 2+ self.items.append((t0, float(z["dur"]), float(z["scale"]), z["kind"], cx, cy))++ def scale_at(self, t: float):+ for t0, dur, s, kind, cx, cy in self.items:+ if t0 <= t < t0 + dur:+ u = t - t0+ if kind == "punch":+ k = _ease(u / self.PUNCH_IN) if u < self.PUNCH_IN else 1.0+ if u > dur - self.PUNCH_OUT:+ k = min(k, _ease((dur - u) / self.PUNCH_OUT))+ else: # push: a slow ease in over the whole stretch, a short way back at the end+ back = min(0.3, dur * 0.2)+ k = _ease(u / (dur - back)) if u < dur - back else _ease((dur - u) / back)+ return 1.0 + (s - 1.0) * k, cx, cy+ return 1.0, 0.0, 0.0++ def apply(self, frame, j: int, t: float) -> None:+ s, cx, cy = self.scale_at(t)+ if s <= 1.001:+ return+ import cv2+ import numpy as np++ w, h = OUT_W / s, OUT_H / s+ x0 = min(max(cx - w / 2, 0.0), OUT_W - w)+ y0 = min(max(cy - h * 0.42, 0.0), OUT_H - h)+ m = np.array([[s, 0.0, -x0 * s], [0.0, s, -y0 * s]], np.float64)+ frame[:] = cv2.warpAffine(frame, m, (OUT_W, OUT_H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)+++# ---- draft captions (PIL) -------------------------------------------------------------------------------------++STYLE_DRAFT = {+ # text colour, highlight colour, active-word colour (None = no karaoke), size, uppercase+ "sach-gon": ((255, 255, 255), (252, 232, 2), None, 76, False),+ "phu-de-nay-mau": ((255, 255, 255), (252, 232, 2), (252, 232, 2), 92, True),+}+++@lru_cache(maxsize=8)+def _font(size: int):+ from PIL import ImageFont++ path = PACK / "fonts" / "BeVietnamPro" / "BeVietnamPro-800.ttf"+ if not path.exists():+ raise FileNotFoundError("Be Vietnam Pro is missing: run node edit/setup.mjs")+ return ImageFont.truetype(str(path), size)+++def caption_cards(edl: dict, tl) -> list[dict]:+ """The caption words in cards of at most maxWords, broken at a sentence end or a pause, timed+ in output seconds. Shared by the draft and (through the same rule in Node) the main captions."""+ cap = edl["captions"]+ most = int(cap["maxWords"])+ cards, cur = [], []+ words = cap["words"]+ for n, w in enumerate(words):+ cur.append(w)+ nxt = words[n + 1] if n + 1 < len(words) else None+ ends = w["w"].rstrip().endswith((".", "?", "!", ",", ":", ";", "…"))+ gap = (nxt["start"] - w["end"]) if nxt else 99+ if len(cur) >= most or ends or gap > 0.45 or nxt is None:+ cards.append(cur)+ cur = []+ out = []+ for c in cards:+ out.append({"words": c, "start": tl.to_output_nearest(c[0]["start"]),+ "end": tl.to_output_nearest(c[-1]["end"])})+ for a, b in zip(out, out[1:]): # no flicker between cards close together+ if 0 <= b["start"] - a["end"] < 0.4:+ a["end"] = b["start"]+ for c in out:+ c["end"] = max(c["end"], c["start"] + 0.25)+ c["word_out"] = [tl.to_output_nearest(w["start"]) for w in c["words"]]+ return out+++class DraftCaptions:+ def __init__(self, edl: dict, tl):+ cap = edl["captions"]+ self.cards = caption_cards(edl, tl)+ self.hi = set(cap["highlights"])+ self.base, self.hcol, self.active, self.size, self.upper = STYLE_DRAFT.get(cap["style"], STYLE_DRAFT["sach-gon"])+ self.cy = OUT_H * (0.70 if cap["position"] == "lower" else 0.58)+ self.cache: dict = {}++ def sprite(self, ci: int, active: int):+ key = (ci, active)+ if key in self.cache:+ return self.cache[key]+ import numpy as np+ from PIL import Image, ImageDraw++ card = self.cards[ci]+ font = _font(self.size)+ maxw = (SAFE[2] - SAFE[0]) * OUT_W - 20+ # trailing , . ; : are not shown (? ! … stay), as in the HyperFrames captions+ toks = [((w["w"].rstrip(",.;:") or w["w"]), w["i"]) for w in card["words"]]+ toks = [(t.upper() if self.upper else t, i) for t, i in toks]+ space = font.getlength(" ")+ lines, line, lw = [], [], 0.0+ for text, i in toks:+ tw = font.getlength(text)+ if line and lw + space + tw > maxw:+ lines.append(line)+ line, lw = [], 0.0+ line.append((text, i, tw))+ lw += (space if len(line) > 1 else 0) + tw+ if line:+ lines.append(line)+ lh = int(self.size * 1.22)+ stroke = max(4, self.size // 11)+ W, H = int(maxw + 2 * stroke + 8), lh * len(lines) + 2 * stroke + 8+ img = Image.new("RGBA", (W, H), (0, 0, 0, 0))+ d = ImageDraw.Draw(img)+ for li, ln in enumerate(lines):+ total = sum(t[2] for t in ln) + space * (len(ln) - 1)+ x = (W - total) / 2+ y = stroke + 4 + li * lh+ for k, (text, i, tw) in enumerate(ln):+ col = self.base+ if i in self.hi:+ col = self.hcol+ if self.active is not None and i == active:+ col = self.active+ d.text((x, y), text, font=font, fill=col + (255,), stroke_width=stroke, stroke_fill=(0, 0, 0, 255))+ x += tw + space+ arr = np.asarray(img)+ self.cache[key] = arr+ return arr++ def rect(self, ci: int):+ a = self.sprite(ci, -1)+ h, w = a.shape[:2]+ x0 = int(round((OUT_W - w) / 2))+ y0 = int(round(min(self.cy - h / 2, SAFE[3] * OUT_H - h)))+ return x0, y0, w, h++ def draw(self, frame, t: float) -> None:+ import numpy as np++ for ci, c in enumerate(self.cards):+ if c["start"] <= t < c["end"]:+ active = -1+ for w, wo in zip(c["words"], c["word_out"]):+ if t >= wo:+ active = w["i"]+ spr = self.sprite(ci, active)+ x0, y0, w, h = self.rect(ci)+ region = frame[y0:y0 + h, x0:x0 + w]+ alpha = spr[:, :, 3:4].astype(np.float32) / 255.0+ region[:] = (spr[:, :, :3] * alpha + region * (1 - alpha)).astype(np.uint8)+ return+++# ---- render / stills --------------------------------------------------------------------------------------------++def cmd_render(edl_path: Path, out: Path, draft_captions: bool, check: bool) -> dict:+ from fx.core import render as rmod++ edl = load_edl(edl_path)+ t0 = time.time()+ clip, tl, fr, draw = build(edl, draft_captions)+ n = tl.output_frames(clip.info.rate)+ last = [0.0]++ def drawing(frame, j, t):+ draw(frame, j, t)+ now = time.time()+ if now - last[0] > 2.0 or j == n - 1:+ last[0] = now+ progress("render", done=j + 1, total=n, pct=round(100 * (j + 1) / n))++ out.parent.mkdir(parents=True, exist_ok=True)+ fade = float(edl["audio"]["crossfadeMs"]) / 1000.0+ res = rmod.render(clip, tl, fr, drawing, out, fade=fade, crf=18)+ t_render = time.time() - t0+ result = {"out": res["path"], "frames": res["frames"], "seconds_out": res["seconds_out"],+ "joins": len(tl.joins), "framing": fr.note, "seconds": {"render": round(t_render, 1)}}+ if check:+ progress("overcut-check", note="nghe lại bản cắt, so từng chữ")+ from fx.effects.clean_cut import overcut_check++ t1 = time.time()+ kept = [w for w in clip.words if tl.to_output((w.start + w.end) / 2) is not None]+ oc = overcut_check(clip, kept, tl, Path(out), None)+ result["overcut"] = {k: oc[k] for k in ("verdict", "lost", "chopped", "left_at_cut", "matched", "kept",+ "joins", "joins_cut_in_silence", "median_start_offset_s")}+ result["seconds"]["overcut_check"] = round(time.time() - t1, 1)+ return result+++def cmd_stills(edl_path: Path, out: Path, count: int, draft_captions: bool) -> dict:+ from PIL import Image, ImageDraw++ from fx.core import render as rmod++ edl = load_edl(edl_path)+ clip, tl, fr, draw = build(edl, draft_captions)+ dur = tl.duration+ times = [dur * (i + 0.5) / count for i in range(count)]+ frames = rmod.still_frames(clip, tl, fr, draw, times)+ cols = int(math.ceil(math.sqrt(count)))+ rows = int(math.ceil(count / cols))+ tw, th = 270, 480+ sheet = Image.new("RGB", (cols * tw + (cols + 1) * 6, rows * (th + 32) + (rows + 1) * 6), (24, 24, 24))+ d = ImageDraw.Draw(sheet)+ for n, (t, f) in enumerate(frames):+ img = Image.fromarray(f).resize((tw, th), Image.LANCZOS)+ x, y = 6 + (n % cols) * (tw + 6), 6 + (n // cols) * (th + 32)+ sheet.paste(img, (x, y))+ d.text((x + 4, y + th + 6), f"{t:5.2f} s", fill=(230, 230, 230))+ sheet.save(out, quality=88)+ return {"out": str(out), "times": [round(t, 2) for t in times]}+++# ---- qc ---------------------------------------------------------------------------------------------------------++def cmd_qc(video_path: Path, out: Path) -> dict:+ from fx.effects import qc_check++ r = qc_check.check(video_path, None, "reels", False, out.with_suffix(".md"))+ findings = [{"check": f.check, "level": f.level, "what": f.what, "fix": f.fix} for f in r["findings"]]+ data = {"verdict": r["verdict"], "findings": findings, "report": str(r["report"]), "sheet": str(r["sheet"]),+ "seconds": round(r["seconds"], 1)}+ out.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")+ return data+++def main(argv=None) -> int:+ ap = argparse.ArgumentParser(prog="lumedit")+ sub = ap.add_subparsers(dest="cmd", required=True)+ a = sub.add_parser("analyze"); a.add_argument("proxy"); a.add_argument("--out", required=True)+ r = sub.add_parser("render"); r.add_argument("edl"); r.add_argument("--out", required=True)+ r.add_argument("--draft-captions", action="store_true"); r.add_argument("--no-check", action="store_true")+ s = sub.add_parser("stills"); s.add_argument("edl"); s.add_argument("--out", required=True)+ s.add_argument("--count", type=int, default=16); s.add_argument("--draft-captions", action="store_true")+ q = sub.add_parser("qc"); q.add_argument("video"); q.add_argument("--out", required=True)+ args = ap.parse_args(argv)+ try:+ if args.cmd == "analyze":+ res = cmd_analyze(Path(args.proxy).resolve(), Path(args.out).resolve())+ elif args.cmd == "render":+ res = cmd_render(Path(args.edl).resolve(), Path(args.out).resolve(), args.draft_captions, not args.no_check)+ elif args.cmd == "stills":+ res = cmd_stills(Path(args.edl).resolve(), Path(args.out).resolve(), args.count, args.draft_captions)+ else:+ res = cmd_qc(Path(args.video).resolve(), Path(args.out).resolve())+ except (ValueError, KeyError, FileNotFoundError) as e:+ emit("result", {"ok": False, "error": f"{type(e).__name__}: {e}"})+ traceback.print_exc()+ return 2+ except Exception as e: # noqa: BLE001+ from fx.core.paths import NeedSetup++ emit("result", {"ok": False, "error": f"{type(e).__name__}: {e}"})+ traceback.print_exc()+ return 3 if isinstance(e, NeedSetup) else 1+ emit("result", {"ok": True, **res})+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/edit/setup.mjs b/edit/setup.mjsnew file mode 100644index 0000000..719365e--- /dev/null+++ b/edit/setup.mjs@@ -0,0 +1,131 @@+#!/usr/bin/env node+// Cài môi trường cho LumReels Edit (chạy được nhiều lần, chỉ làm phần còn thiếu):+// 1. tìm Python 3.10–3.12 (KHÔNG cài gì vào Python hệ thống) → tạo edit/.venv+// 2. pip install edit/askeditor/requirements.txt (+ brotli để đọc font woff2)+// 3. có GPU NVIDIA (Windows/Linux) → thêm cuBLAS + cuDNN (wheel nvidia-*) để whisper chạy GPU; --cpu để bỏ qua+// 4. model MediaPipe (mặt, người) — tải từ kho chính thức, kiểm SHA-256+// 5. font Be Vietnam Pro TTF (ghép từ engine/fonts) cho phụ đề bản nháp+// 6. whisper large-v3 (~2,9 GB, vào ~/.cache/huggingface) — tải lần đầu+// Dòng cuối: READY | NEED_PYTHON | NEED_FFMPEG | NEED_NETWORK | NEED_NPM+// node edit/setup.mjs [--cpu] [--skip-model]+import fs from 'node:fs';+import path from 'node:path';+import os from 'node:os';+import crypto from 'node:crypto';+import { spawnSync } from 'node:child_process';+import { EDIT, ROOT, PACK, VENV, venvPython, pyEnv, dirSize, fmtBytes, WHISPER_MODEL } from './env.mjs';++const args = new Set(process.argv.slice(2));+const say = (s) => console.log(s);+const sh = (cmd, a, opts = {}) => spawnSync(cmd, a, { encoding: 'utf8', windowsHide: true, ...opts });+const has = (cmd) => { const r = sh(cmd, ['-version']); return !r.error && r.status === 0; };+const fail = (word, msg) => { say(msg); say(word); process.exit(word === 'NEED_NETWORK' ? 3 : 2); };++// ---- 0. ffmpeg -------------------------------------------------------------------------------------+if (!has('ffmpeg') || !has('ffprobe')) {+ fail('NEED_FFMPEG', 'Thiếu ffmpeg/ffprobe. Windows: winget install Gyan.FFmpeg · macOS: brew install ffmpeg · Ubuntu: sudo apt install ffmpeg');+}++// ---- 1. Python 3.10–3.12 → venv ----------------------------------------------------------------------+const okVersion = (cmd, pre = []) => {+ const r = sh(cmd, [...pre, '-c', 'import sys; print("%d.%d" % sys.version_info[:2])']);+ if (r.error || r.status !== 0) return null;+ const v = r.stdout.trim();+ return ['3.10', '3.11', '3.12'].includes(v) ? v : null;+};+function findPython() {+ if (process.env.LUMEDIT_PYTHON && okVersion(process.env.LUMEDIT_PYTHON)) return { cmd: process.env.LUMEDIT_PYTHON, pre: [] };+ for (const v of ['3.12', '3.11', '3.10']) {+ if (process.platform === 'win32' && okVersion('py', [`-${v}`])) return { cmd: 'py', pre: [`-${v}`] };+ if (okVersion(`python${v}`)) return { cmd: `python${v}`, pre: [] };+ }+ for (const c of ['python3', 'python']) if (okVersion(c)) return { cmd: c, pre: [] };+ return null;+}++let PY = venvPython();+if (!fs.existsSync(PY) || !okVersion(PY)) {+ const base = findPython();+ if (!base) {+ fail('NEED_PYTHON', 'Cần Python 3.10, 3.11 hoặc 3.12 (thư viện mặt/người/giọng chưa có bản cho 3.13+).\n'+ + ' Windows: winget install Python.Python.3.12 · macOS: brew install [email protected] · Ubuntu: sudo apt install python3.12-venv\n'+ + ' Hoặc đặt LUMEDIT_PYTHON=<đường dẫn python>.');+ }+ say(`Tạo môi trường Python riêng: ${path.relative(ROOT, VENV)} (bằng ${[base.cmd, ...base.pre].join(' ')})…`);+ const r = sh(base.cmd, [...base.pre, '-m', 'venv', '--clear', VENV], { stdio: 'inherit' });+ if (r.status !== 0) fail('NEED_PYTHON', 'Không tạo được venv.');+ PY = venvPython();+}+const pip = (a, what) => {+ say(what);+ const r = sh(PY, ['-m', 'pip', 'install', '--disable-pip-version-check', '--quiet', ...a], { stdio: 'inherit' });+ if (r.status !== 0) fail('NEED_NETWORK', 'pip install lỗi. Kiểm tra mạng rồi chạy lại: node edit/setup.mjs');+};++// ---- 2. gói Python (chỉ cài lại khi requirements đổi) -------------------------------------------------+const reqFile = path.join(PACK, 'requirements.txt');+const stamp = path.join(VENV, '.lumedit-requirements.sha256');+const want = crypto.createHash('sha256').update(fs.readFileSync(reqFile)).update('brotli').digest('hex');+const importsOk = () => sh(PY, ['-c', 'import mediapipe, faster_whisper, cv2, PIL, numpy, brotli, fontTools']).status === 0;+if ((fs.existsSync(stamp) ? fs.readFileSync(stamp, 'utf8').trim() : '') !== want || !importsOk()) {+ pip(['-r', reqFile, 'brotli'], 'Cài gói Python (lần đầu vài trăm MB)…');+ fs.writeFileSync(stamp, want + '\n');+}++// ---- 3. CUDA cho whisper -------------------------------------------------------------------------------+const gpu = !args.has('--cpu') && process.platform !== 'darwin' && sh('nvidia-smi', ['-L']).status === 0;+if (gpu) {+ const cudaOk = sh(PY, ['-c', 'import importlib.util as u, sys; sys.exit(0 if u.find_spec("nvidia.cublas") and u.find_spec("nvidia.cudnn") else 1)']).status === 0;+ if (!cudaOk) pip(['nvidia-cublas-cu12==12.9.*', 'nvidia-cudnn-cu12==9.*'], 'Có GPU NVIDIA: cài cuBLAS + cuDNN vào venv (~2 GB) để chép lời bằng GPU…');+} else {+ say(args.has('--cpu') ? 'Bỏ qua GPU (--cpu).' : 'Không thấy GPU NVIDIA: whisper chạy CPU (chậm hơn nhiều).');+}++// ---- 4. model MediaPipe ------------------------------------------------------------------------------+{+ const r = sh(PY, ['-X', 'utf8', '-m', 'fx.core.models', 'fetch-vision'], { cwd: PACK, env: pyEnv(), stdio: 'inherit' });+ if (r.status !== 0) fail('NEED_NETWORK', 'Không tải được model mặt/người.');+}++// ---- 5. font Be Vietnam Pro TTF -------------------------------------------------------------------------+{+ const fontsSrc = path.join(ROOT, 'engine', 'fonts');+ if (!fs.existsSync(path.join(fontsSrc, 'be-vietnam-pro-vietnamese-700-normal.woff2'))) {+ fail('NEED_NPM', 'Thiếu engine/fonts (chưa chạy npm install ở thư mục gốc LumReels).');+ }+ const dest = path.join(PACK, 'fonts', 'BeVietnamPro');+ const r = sh(PY, ['-X', 'utf8', path.join(EDIT, 'py', 'fonts.py'), fontsSrc, dest], { env: pyEnv(), stdio: 'inherit' });+ if (r.status !== 0) fail('NEED_PYTHON', 'Không dựng được font Be Vietnam Pro.');+ const lic = path.join(ROOT, 'node_modules', '@fontsource', 'be-vietnam-pro', 'LICENSE');+ if (fs.existsSync(lic)) fs.copyFileSync(lic, path.join(dest, 'OFL.txt'));+}++// ---- 6. whisper -------------------------------------------------------------------------------------+let modelDir = '';+if (!args.has('--skip-model')) {+ say(`Model chép lời: ${WHISPER_MODEL} (lần đầu tải ~2,9 GB vào bộ nhớ đệm Hugging Face)…`);+ const r = sh(PY, ['-X', 'utf8', '-c', `from faster_whisper import download_model; print(download_model(${JSON.stringify(WHISPER_MODEL)}))`],+ { env: pyEnv(), stdio: ['ignore', 'pipe', 'inherit'] });+ if (r.status !== 0) fail('NEED_NETWORK', 'Không tải được model whisper.');+ modelDir = r.stdout.trim().split(/\r?\n/).pop();+}++// ---- dung lượng ------------------------------------------------------------------------------------------+const venvB = dirSize(VENV);+const modelsB = dirSize(path.join(PACK, 'models'));+const fontsB = dirSize(path.join(PACK, 'fonts', 'BeVietnamPro'));+let whisperB = 0;+if (modelDir) {+ // snapshot trên Linux/macOS là symlink tới blobs: đo cả thư mục model trong cache+ const repoDir = modelDir.split(/[\\/]snapshots[\\/]/)[0];+ whisperB = dirSize(repoDir);+}+say('');+say('Dung lượng:');+say(` ${path.relative(ROOT, VENV)}: ${fmtBytes(venvB)}${gpu ? ' (gồm cuBLAS + cuDNN)' : ''}`);+say(` model mặt/người (${path.relative(ROOT, path.join(PACK, 'models'))}): ${fmtBytes(modelsB)}`);+say(` font Be Vietnam Pro: ${fmtBytes(fontsB)}`);+if (modelDir) say(` whisper ${WHISPER_MODEL}: ${fmtBytes(whisperB)} (${modelDir.replace(os.homedir(), '~')})`);+say(` tổng: ${fmtBytes(venvB + modelsB + fontsB + whisperB)}`);+say(`PYTHON ${PY}`);+say('READY');diff --git a/edit/test/check-truth.mjs b/edit/test/check-truth.mjsnew file mode 100644index 0000000..3ca1959--- /dev/null+++ b/edit/test/check-truth.mjs@@ -0,0 +1,22 @@+#!/usr/bin/env node+// So EDL với đáp án của clip tổng hợp (make-synth.mjs): câu trọn phải nằm trọn trong đoạn giữ,+// câu nói dở phải bị bỏ hết. node edit/test/check-truth.mjs <edits/<id>/edl.json> <synth.truth.json>+import fs from 'node:fs';+const [edlFile, truthFile] = process.argv.slice(2);+const edl = JSON.parse(fs.readFileSync(edlFile, 'utf8'));+const truth = JSON.parse(fs.readFileSync(truthFile, 'utf8'));+const covered = (a, b) => { let t = a; for (const k of edl.keep) if (k.start <= t + 0.02 && k.end > t) t = Math.max(t, k.end); return t >= b - 0.02; };+const kept = (a, b) => edl.keep.reduce((s, k) => s + Math.max(0, Math.min(b, k.end) - Math.max(a, k.start)), 0);+let bad = 0;+for (const l of truth) {+ if (l.partial) {+ const k = kept(l.start, l.end);+ const ok = k < 0.05; bad += !ok;+ console.log(`${ok ? 'PASS' : 'FAIL'} câu nói dở ${l.start}–${l.end} s bị bỏ (còn giữ ${k.toFixed(2)} s)`);+ } else {+ const ok = covered(l.start, l.end); bad += !ok;+ console.log(`${ok ? 'PASS' : 'FAIL'} giữ trọn ${l.start}–${l.end} s "${l.text}"`);+ }+}+console.log(bad ? `${bad} lỗi` : 'tất cả PASS');+process.exit(bad ? 1 : 0);diff --git a/edit/test/make-synth.mjs b/edit/test/make-synth.mjsnew file mode 100644index 0000000..d40eda6--- /dev/null+++ b/edit/test/make-synth.mjs@@ -0,0 +1,67 @@+#!/usr/bin/env node+// Dựng clip thử tổng hợp cho LumReels Edit khi chưa có clip người thật:+// nối hình (out.silent.mp4) + giọng sạch (voice-*.wav đặt đúng mốc t) của vài job có giọng,+// chèn 1 khoảng lặng dài và 1 câu nói hỏng (nói dở rồi nói lại từ đầu).+// node edit/test/make-synth.mjs <out.mp4> [--wide] (--wide: khung 16:9 nền mờ, để thử reframe)+// Cần thư mục jobs/ có các job dưới (dữ liệu máy dựng, không nằm trong repo).+import fs from 'node:fs';+import path from 'node:path';+import os from 'node:os';+import { run } from '../../engine/lib.mjs';+import { ROOT } from '../env.mjs';++const JOBS = path.join(ROOT, 'jobs');+const PARTS = [+ { job: '261127153822-100-08b4' }, // "Tháng nào cũng hụt tiền? …"+ { pause: 1.6 }, // lặng dài (hình đứng)+ { job: '261127140923-092-bcd1', cut: 1.35, then: 0.5 }, // nói dở "Để 5 triệu đồng trong…" rồi im+ { job: '261127140923-092-bcd1' }, // nói lại trọn câu+ { job: '261127134703-010-4701' },+ { job: '261127135408-059-bc9d' },+];+const outFile = path.resolve(process.argv[2] || path.join(ROOT, 'edits', '_synth', 'synth.mp4'));+const wide = process.argv.includes('--wide');+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'lumedit-synth-'));+const ff = async (args) => { const r = await run('ffmpeg', ['-hide_banner', '-y', ...args]); if (r.code !== 0) throw new Error(r.out.slice(-800)); };++function voiceOf(job) {+ const lines = JSON.parse(fs.readFileSync(path.join(JOBS, job, 'scene', 'audio.json'), 'utf8')).voice.lines;+ const meta = Object.entries(JSON.parse(fs.readFileSync(path.join(JOBS, job, 'audio', 'voice-meta.json'), 'utf8'))).slice(-lines.length);+ return lines.map((l, k) => ({ t: l.t, file: path.join(JOBS, job, 'audio', meta[k][0]), dur: meta[k][1].dur, text: l.text }));+}++const pieces = []; const truth = []; let at = 0; let lastJob = null;+for (const [n, p] of PARTS.entries()) {+ const f = path.join(tmp, `p${n}.mp4`);+ const vfFor = (pre) => (wide+ ? `[0:v]${pre}split[s0][s1];[s0]scale=1920:1080:force_original_aspect_ratio=increase,crop=1920:1080,boxblur=20[bg];[s1]scale=-2:1080[fg];[bg][fg]overlay=(W-w)/2:0,fps=30,format=yuv420p[v]`+ : `[0:v]${pre}fps=30,format=yuv420p[v]`);+ const vf = vfFor('');+ if (p.pause) {+ const src = path.join(JOBS, lastJob, 'out.silent.mp4');+ await ff(['-sseof', '-0.1', '-i', src, '-f', 'lavfi', '-i', 'anullsrc=r=48000:cl=stereo', '-filter_complex', vfFor('tpad=stop_mode=clone:stop_duration=5,'),+ '-map', '[v]', '-map', '1:a', '-t', String(p.pause), '-c:v', 'libx264', '-crf', '18', '-c:a', 'pcm_s16le', f.replace('.mp4', '.mov')]);+ pieces.push(f.replace('.mp4', '.mov')); at += p.pause; continue;+ }+ const v = voiceOf(p.job); lastJob = p.job;+ const len = p.cut ? p.cut + p.then : 8;+ const ins = ['-i', path.join(JOBS, p.job, 'out.silent.mp4')]; const ch = []; const lab = [];+ v.forEach((l, k) => {+ if (l.t >= len) return;+ ins.push('-i', l.file);+ const keepDur = p.cut ? Math.max(0, p.cut - l.t) : l.dur;+ ch.push(`[${k + 1}:a]aresample=48000,aformat=channel_layouts=stereo,atrim=0:${keepDur.toFixed(3)},afade=t=out:st=${Math.max(0, keepDur - 0.03).toFixed(3)}:d=0.03,adelay=${Math.round(l.t * 1000)}:all=1[a${k}]`);+ lab.push(`[a${k}]`);+ truth.push({ start: +(at + l.t).toFixed(3), end: +(at + l.t + keepDur).toFixed(3), text: l.text, partial: !!p.cut });+ });+ ch.push(`${lab.join('')}amix=inputs=${lab.length}:normalize=0,apad[a]`);+ await ff([...ins, '-filter_complex', vf + ';' + ch.join(';'), '-map', '[v]', '-map', '[a]', '-t', String(len), '-c:v', 'libx264', '-crf', '18', '-c:a', 'pcm_s16le', f.replace('.mp4', '.mov')]);+ pieces.push(f.replace('.mp4', '.mov')); at += len;+}+const list = path.join(tmp, 'list.txt');+fs.writeFileSync(list, pieces.map((p) => `file '${p.replace(/\\/g, '/')}'`).join('\n'));+fs.mkdirSync(path.dirname(outFile), { recursive: true });+await ff(['-f', 'concat', '-safe', '0', '-i', list, '-c:v', 'libx264', '-crf', '18', '-r', '30', '-c:a', 'aac', '-b:a', '192k', '-ar', '48000', outFile]);+fs.writeFileSync(outFile.replace(/\.mp4$/, '.truth.json'), JSON.stringify(truth, null, 1));+fs.rmSync(tmp, { recursive: true, force: true });+console.log(`${outFile} (${at.toFixed(2)} s, ${truth.length} câu; câu nói dở ở ${truth.find((t) => t.partial)?.start} s)`);