@yasaswy.nagavolu/agents 0.18.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/content/skills/edit-videos/SKILL.md +16 -10
  2. package/content/skills/edit-videos/engine/blur.py +8 -5
  3. package/content/skills/edit-videos/engine/cache.py +43 -0
  4. package/content/skills/edit-videos/engine/captions.py +296 -34
  5. package/content/skills/edit-videos/engine/cli.py +229 -56
  6. package/content/skills/edit-videos/engine/detect_idle.py +3 -19
  7. package/content/skills/edit-videos/engine/export_plan.py +93 -0
  8. package/content/skills/edit-videos/engine/fcpxml_writer.py +139 -0
  9. package/content/skills/edit-videos/engine/ffmpeg_io.py +31 -1
  10. package/content/skills/edit-videos/engine/filter_chain.py +19 -0
  11. package/content/skills/edit-videos/engine/map_time.py +30 -6
  12. package/content/skills/edit-videos/engine/naming.py +25 -0
  13. package/content/skills/edit-videos/engine/otio_writer.py +65 -0
  14. package/content/skills/edit-videos/engine/probe.py +37 -4
  15. package/content/skills/edit-videos/engine/render.py +62 -22
  16. package/content/skills/edit-videos/engine/resolve_export.py +5 -309
  17. package/content/skills/edit-videos/engine/schema.py +54 -6
  18. package/content/skills/edit-videos/engine/timeline.py +82 -89
  19. package/content/skills/edit-videos/engine/timeline_math.py +161 -0
  20. package/content/skills/edit-videos/engine/zoom.py +5 -4
  21. package/content/skills/edit-videos/pyproject.toml +2 -0
  22. package/content/skills/edit-videos/resolve_ui/act.py +461 -0
  23. package/content/skills/edit-videos/resolve_ui/assets/master_bin_row.png +0 -0
  24. package/content/skills/edit-videos/resolve_ui/assets/master_breadcrumb.png +0 -0
  25. package/content/skills/edit-videos/resolve_ui/assets/st1_badge.png +0 -0
  26. package/content/skills/edit-videos/resolve_ui/banner.py +243 -0
  27. package/content/skills/edit-videos/resolve_ui/cli.py +165 -70
  28. package/content/skills/edit-videos/resolve_ui/flows.py +485 -0
  29. package/content/skills/edit-videos/resolve_ui/gc.py +144 -0
  30. package/content/skills/edit-videos/resolve_ui/guards.py +813 -0
  31. package/content/skills/edit-videos/resolve_ui/locate.py +269 -0
  32. package/content/skills/edit-videos/resolve_ui/poll.py +29 -0
  33. package/content/skills/edit-videos/resolve_ui/virtual_desktop.py +59 -0
  34. package/content/skills/edit-videos/tests/conftest.py +22 -0
  35. package/content/skills/edit-videos/tests/fixtures/dr25/master_nested_bad.png +0 -0
  36. package/content/skills/edit-videos/tests/fixtures/dr25/master_selected_good.png +0 -0
  37. package/content/skills/edit-videos/tests/fixtures/dr29/st1_absent.png +0 -0
  38. package/content/skills/edit-videos/tests/fixtures/dr29/st1_present.png +0 -0
  39. package/content/skills/edit-videos/tests/test_cache.py +54 -0
  40. package/content/skills/edit-videos/tests/test_captions.py +240 -6
  41. package/content/skills/edit-videos/tests/test_cli.py +169 -1
  42. package/content/skills/edit-videos/tests/test_cli_job_gc.py +108 -0
  43. package/content/skills/edit-videos/tests/test_detect_idle.py +12 -3
  44. package/content/skills/edit-videos/tests/test_dr26_vfr_time_alignment.py +121 -0
  45. package/content/skills/edit-videos/tests/test_dr31_duration_drift.py +101 -0
  46. package/content/skills/edit-videos/tests/test_dr32_last_frame_overlay.py +113 -0
  47. package/content/skills/edit-videos/tests/test_engine_refactor_goldens.py +156 -0
  48. package/content/skills/edit-videos/tests/test_map_time.py +25 -0
  49. package/content/skills/edit-videos/tests/test_naming.py +33 -0
  50. package/content/skills/edit-videos/tests/test_probe.py +16 -0
  51. package/content/skills/edit-videos/tests/test_resolve_ui_act_coord_clicks.py +206 -0
  52. package/content/skills/edit-videos/tests/test_resolve_ui_act_cursor_free.py +155 -0
  53. package/content/skills/edit-videos/tests/test_resolve_ui_act_input_primitives.py +83 -0
  54. package/content/skills/edit-videos/tests/{test_resolve_ui_menu.py → test_resolve_ui_act_menu.py} +2 -2
  55. package/content/skills/edit-videos/tests/test_resolve_ui_act_menu_interrupt.py +80 -0
  56. package/content/skills/edit-videos/tests/{test_resolve_ui_menu_retry.py → test_resolve_ui_act_menu_retry.py} +2 -2
  57. package/content/skills/edit-videos/tests/test_resolve_ui_act_pages.py +55 -0
  58. package/content/skills/edit-videos/tests/test_resolve_ui_banner_frame_geometry.py +46 -0
  59. package/content/skills/edit-videos/tests/test_resolve_ui_cli.py +75 -4
  60. package/content/skills/edit-videos/tests/test_resolve_ui_cli_ack.py +88 -0
  61. package/content/skills/edit-videos/tests/test_resolve_ui_cli_ack_grace.py +113 -0
  62. package/content/skills/edit-videos/tests/test_resolve_ui_cli_gc.py +107 -0
  63. package/content/skills/edit-videos/tests/test_resolve_ui_cli_lock_order.py +70 -0
  64. package/content/skills/edit-videos/tests/test_resolve_ui_cli_operator_interrupt.py +157 -0
  65. package/content/skills/edit-videos/tests/test_resolve_ui_flows_importing_dialog_titles.py +39 -0
  66. package/content/skills/edit-videos/tests/{test_resolve_ui_jobs_bin_guard.py → test_resolve_ui_flows_jobs_bin_guard.py} +2 -2
  67. package/content/skills/edit-videos/tests/{test_resolve_ui_jobs_naming.py → test_resolve_ui_flows_jobs_naming.py} +1 -1
  68. package/content/skills/edit-videos/tests/test_resolve_ui_flows_jobs_subtitle.py +100 -0
  69. package/content/skills/edit-videos/tests/{test_resolve_ui_project_guard.py → test_resolve_ui_flows_project_guard.py} +3 -3
  70. package/content/skills/edit-videos/tests/test_resolve_ui_flows_select_timeline.py +270 -0
  71. package/content/skills/edit-videos/tests/test_resolve_ui_gc.py +203 -0
  72. package/content/skills/edit-videos/tests/test_resolve_ui_guards_ack.py +172 -0
  73. package/content/skills/edit-videos/tests/test_resolve_ui_guards_ack_grace.py +51 -0
  74. package/content/skills/edit-videos/tests/{test_resolve_ui_window.py → test_resolve_ui_guards_denylist.py} +2 -2
  75. package/content/skills/edit-videos/tests/test_resolve_ui_guards_desktop_move.py +209 -0
  76. package/content/skills/edit-videos/tests/test_resolve_ui_guards_dialog_allowlist.py +114 -0
  77. package/content/skills/edit-videos/tests/{test_resolve_ui_focus_guard.py → test_resolve_ui_guards_focus.py} +2 -2
  78. package/content/skills/edit-videos/tests/test_resolve_ui_guards_interrupt.py +162 -0
  79. package/content/skills/edit-videos/tests/test_resolve_ui_guards_menu_ready.py +48 -0
  80. package/content/skills/edit-videos/tests/{test_resolve_ui_proc_lock.py → test_resolve_ui_guards_proc_lock.py} +2 -2
  81. package/content/skills/edit-videos/tests/test_resolve_ui_guards_takeover.py +274 -0
  82. package/content/skills/edit-videos/tests/test_resolve_ui_guards_target_window.py +53 -0
  83. package/content/skills/edit-videos/tests/test_resolve_ui_live.py +8 -8
  84. package/content/skills/edit-videos/tests/test_resolve_ui_locate_image.py +52 -0
  85. package/content/skills/edit-videos/tests/test_resolve_ui_locate_search_edit.py +67 -0
  86. package/content/skills/edit-videos/tests/test_resolve_ui_poll.py +82 -0
  87. package/content/skills/edit-videos/tests/test_resolve_ui_virtual_desktop.py +54 -0
  88. package/content/skills/edit-videos/tests/test_schema.py +22 -0
  89. package/content/skills/edit-videos/tests/test_time_mapping.py +1 -1
  90. package/content/skills/edit-videos/tests/test_timeline.py +42 -1
  91. package/content/skills/edit-videos/tests/test_timeline_math.py +33 -0
  92. package/content/skills/edit-videos/tests/test_timeline_math_boundary.py +16 -0
  93. package/content/skills/edit-videos/tests/test_workspace.py +61 -0
  94. package/content/skills/edit-videos/tests/test_workspace_gc.py +222 -0
  95. package/content/skills/edit-videos/uv.lock +120 -0
  96. package/content/skills/edit-videos/workspace.py +347 -1
  97. package/package.json +1 -1
  98. package/content/skills/edit-videos/resolve_ui/coord_clicks.py +0 -77
  99. package/content/skills/edit-videos/resolve_ui/dialogs.py +0 -72
  100. package/content/skills/edit-videos/resolve_ui/focus_guard.py +0 -48
  101. package/content/skills/edit-videos/resolve_ui/idle.py +0 -42
  102. package/content/skills/edit-videos/resolve_ui/importing.py +0 -73
  103. package/content/skills/edit-videos/resolve_ui/jobs.py +0 -144
  104. package/content/skills/edit-videos/resolve_ui/menu.py +0 -80
  105. package/content/skills/edit-videos/resolve_ui/pages.py +0 -30
  106. package/content/skills/edit-videos/resolve_ui/proc_lock.py +0 -33
  107. package/content/skills/edit-videos/resolve_ui/project.py +0 -202
  108. package/content/skills/edit-videos/resolve_ui/screenshot.py +0 -66
  109. package/content/skills/edit-videos/resolve_ui/window.py +0 -102
  110. package/content/skills/edit-videos/tests/test_resolve_ui_coord_clicks.py +0 -66
  111. package/content/skills/edit-videos/tests/test_resolve_ui_idle.py +0 -41
  112. package/content/skills/edit-videos/tests/test_resolve_ui_jobs_subtitle.py +0 -90
  113. package/content/skills/edit-videos/tests/test_resolve_ui_pages.py +0 -22
@@ -13,14 +13,14 @@ $PY = "$HOME\.claude\skills\edit-videos\.venv\Scripts\python.exe"
13
13
  & $PY -m resolve_ui <cmd> ... # drives the Resolve 21.1 free window through its normal UI
14
14
  ```
15
15
 
16
- Every command prints one JSON object. Read it; do not parse free text.
16
+ Every command prints exactly one JSON object on stdout; pass `--job <slug>` to every command (accepted even where unused). Read the JSON; do not parse free text. A usage error is also JSON, on stdout, non-zero exit. Add `--verbose` (before the subcommand) to see the underlying ffmpeg/ffprobe commands on stderr; omit it for a clean pipe.
17
17
 
18
18
  ## Workflow
19
19
 
20
- 1. **Job.** Pick a short slug for the job (e.g. `tiktok-audit-demo`). Pass `--job <slug>` to every command. All files land in `D:\davinci\claude-space\<job>\` (`spec\`, `work\`, `handoff\`, `renders\`, `contact-sheets\`, `screenshots\`).
21
- 2. **Look before you cut.** `probe <video>` each source. Build a first spec with `sources` + `segments`, and mark every stretch whose text the viewer must read (URLs, settings, consent lines) as `keep_1x`. `detect-idle --spec <spec> --edit-timeline` proposes idle ranges and a ready-to-paste `speed` array — start there instead of guessing a factor. Then `contact-sheet --spec <spec> --edit-timeline --frames 24` (add `--from/--to`, edit-timeline seconds, to zoom into one stretch) and Read the PNG; `probe --spec <spec> --edit-timeline --from/--to` gives exact numbers for that window. Pick every time and box from the sheet; if a time comes from the *source* clip instead, convert it with `map-time --spec <spec> --source <id> --t <sec>` (or `--edit-t <sec>` the other way).
22
- 3. **Write the spec** (JSON) to `D:\davinci\claude-space\<job>\spec\draft.json`, then `validate` it.
23
- 4. **Render.** `render <spec> --job <slug> --contact-sheet <sheet.png>`. Read the output contact sheet and check that every blur box covers what it must and every caption reads correctly. Fix the spec and re-render until correct.
20
+ 1. **Job.** Pick a short slug for the job (e.g. `tiktok-audit-demo`). All files land in `D:\davinci\claude-space\<job>\` (`spec\`, `work\`, `handoff\`, `renders\`, `contact-sheets\`, `screenshots\`). Two commands sharing a job's `work\` wait for each other; a stale lock from a crashed run clears itself after an hour.
21
+ 2. **Look before you cut.** `probe <video>` each source; a `"vfr": true` result carries a `hint` (e.g. adb screenrecord) — set `fps` explicitly in the spec if you don't want the average rate. Build a first spec with `sources` + `segments`, and mark every stretch whose text the viewer must read (URLs, settings, consent lines) as `keep_1x`. `detect-idle --spec <spec> --edit-timeline` proposes idle ranges at the default 2x factor (`--factor` to change it) — start there instead of guessing. Then `contact-sheet --spec <spec> --edit-timeline --frames 24` (add `--from/--to`, edit-timeline seconds, to zoom into one stretch; a low-res proxy is built once per job and reused) and Read the PNG; `probe --spec <spec> --edit-timeline --from/--to` gives exact numbers for that window. Pick every time and box from the sheet; if a time comes from the *source* clip instead, convert it with `map-time --spec <spec> --source <id> --t <sec>` (`--edit-t <sec>` or `--render-t <sec>`, from a rendered MP4, the other way).
22
+ 3. **Write the spec** (JSON) to `D:\davinci\claude-space\<job>\spec\draft.json` with the Write tool — never a shell heredoc or `echo` — then `validate` it.
23
+ 4. **Render.** `render <spec> --job <slug> --contact-sheet`. Each render/sheet auto-versions (`<spec>-v1.mp4`, `-v2.mp4`, ...) so nothing is silently overwritten; the JSON reports the `version`. Pass `--out` for an explicit path (`--overwrite` to replace it). Read the output contact sheet and check that every blur box covers what it must and every caption reads correctly. Re-verify every splice/cut with `contact-sheet --from/--to` on the **rendered MP4**, not only on the spec's edit timeline — a correct spec can still render wrong. Fix the spec and re-render until correct.
24
24
  5. **Resolve** (only when the user wants the edit in Resolve):
25
25
  `export-timeline <spec> --format fcpxml --job <slug>` → `resolve_ui status` → `resolve_ui open-project` → `resolve_ui new-job <slug> <fcpxml> [--srt <srt>]` (creates the `<slug>` bin+timeline inside claude-space, imports, saves in one call) → `resolve_ui screenshot --job <slug>` and Read it to confirm. If the JSON has `"subtitles": "failed: ..."` (exit 0, timeline already created), retry just that step with `resolve_ui import-subtitle <slug> <srt>` - do not re-run `new-job`.
26
26
  6. **Report** the absolute paths: final MP4 (size MB, duration), contact sheet, Resolve screenshot, and every `warnings` entry.
@@ -31,11 +31,12 @@ Every command prints one JSON object. Read it; do not parse free text.
31
31
  |---|---|
32
32
  | `sources` | `{id: absolute path}`; inputs may be anywhere (read-only) |
33
33
  | `segments` | `[{source, start, end}]` in **source** seconds, joined in order |
34
- | `speed` | `[{t_start, t_end, factor}]`, e.g. factor 4 over idle stretches |
34
+ | `speed` | `[{t_start, t_end, factor}]`; default factor 2x over idle stretches of an agent-driven screen recording — a `keep_1x` range always stays 1x regardless |
35
35
  | `crop` | `{x, y, w, h}` or null |
36
- | `zoom` | `[{t_start, t_end, x, y, w, h, ease}]`; region fills the frame during the range (ease default 0.3s, 0 = hard cut); ranges may not overlap; not yet supported together with `crop` |
36
+ | `zoom` | `[{t_start, t_end, x, y, w, h, ease}]`; region fills the frame during the range (ease default 0.3s, 0 = hard cut); ranges may not overlap; not yet supported together with `crop`; magnification on a wide single line of text is capped at roughly `frame_w / box_w` — do not expect more |
37
37
  | `blur.fixed` / `blur.tracked` | `[{t_start, t_end, x, y, w, h, strength}]`; tracked follows the region from `t_start` |
38
- | `captions` | `[{t_start, t_end, text, x, y, font_size, color, box_color}]`; `srt` = path to an .srt |
38
+ | `captions` | `[{t_start, t_end, text, x, y, font_size, font_file, layout, exclude}]`; rendered as a PIL image (rounded band, soft shadow, hairline, off-white text) composited with `overlay`, auto-wrapped and shrunk to fit inside a safe margin; `layout: {position, margin_pct, bottom_margin_pct, min_font_size, max_lines, fill_color, fill_alpha, text_color, accent}` (`accent`: `true`/hex/`null` for an optional left accent bar); `exclude: [{t_start, t_end}]` hides this one caption during those edit-timeline windows without splitting it by hand; `render`/`validate` fail with the offending caption if it still cannot fit at `min_font_size`; `srt` = path to an .srt, wrapped/banded the same way |
39
+ | `caption_free` | `[{t_start, t_end}]` edit-timeline windows where no caption of any kind is shown; an overlapping caption is clipped, reported in `warnings`, not hard-errored |
39
40
  | `keep_1x` | `[{t_start, t_end}]` stretches that must play at 1x; a `speed` range overlapping one fails `validate` |
40
41
  | `max_size_mb`, `target_width`, `fps` | export limits (default 50 MB) |
41
42
 
@@ -52,15 +53,20 @@ Every command prints one JSON object. Read it; do not parse free text.
52
53
  | 3 | path outside the claude-space workspace | use the default paths; never work around it |
53
54
  | 4 (`resolve_ui`) | blocked dialog (upgrade/database/licence/activation/studio/purchase) | report the screenshot path to the user and stop; never click it yourself |
54
55
  | 5 (`resolve_ui`) | wrong Resolve project open (not `claude-space`) | run `resolve_ui open-project` first |
55
- | 6 (`resolve_ui`) | user busy (not idle within the timeout) | tell the user and retry later; do not pass `--now` unless the user asked for it |
56
+ | 6 (`resolve_ui`) | the operator did not click Go within the timeout | tell the user and retry later; do not pass `--now` unless the user asked for it |
56
57
  | 7 (`resolve_ui`) | Resolve busy (another resolve_ui invocation is driving it) | wait and retry; never run two `resolve_ui` commands concurrently on purpose |
57
58
  | 8 (`resolve_ui`) | the PC has no active desktop (screen off/away) | tell the user; retry when they are back |
59
+ | 9 (`resolve_ui`) | the operator used the mouse/keyboard during the run | tell the user the step was aborted safely; re-run when they are done |
60
+ | 10 (`resolve_ui`) | Resolve was not the foreground window/target point right before a click - refused rather than risk hitting the wrong app | check the screenshot path in the JSON; re-run once Resolve is frontmost |
61
+ | 11 (`resolve_ui`) | a flow step failed - a bin/tile navigation did not land, or Resolve's own popup (e.g. "New Timeline Backup") was unrecognized/would not close - screenshot path always included | check the screenshot path in the JSON; report to the user and stop |
58
62
  | other non-zero | see the JSON `error` | fix the cause; for `resolve_ui` guard codes, report to the user and stop |
59
63
 
60
- `resolve_ui` refuses to act on any Resolve project except `claude-space`, never clicks upgrade/licence/activation dialogs, and waits until the user is idle before any step that needs window focus.
64
+ `resolve_ui` refuses to act on any Resolve project except `claude-space`, never clicks upgrade/licence/activation dialogs, asks for Go (toast + banner, noting if Resolve is on another virtual desktop so Go will switch to it for the burst and back) before touching the mouse/keyboard - reusing that ack for `--ack-grace` seconds (default 300) across the next commands instead of a new card each time, until an abort (exit 9/10) - and shows an orange frame around the Resolve window while driving it, stopping at the next step if the operator touches the mouse/keyboard.
61
65
 
62
66
  ## Limits
63
67
 
68
+ - Jobs have a state (`active`|`complete`|`stale`, `engine job set-state`); the skill sweeps stale jobs at every invocation and complete jobs after 30 days (`engine gc`), which flags their Resolve bin/timeline for cleanup; `resolve_ui gc` (no `--apply`, read-only) shows that list, `resolve_ui gc --apply [--extra <name> ...]` deletes each one's bin and timeline with a named confirm before ever confirming a delete; mark your job complete when the user accepted the output, stale when you abandon it.
64
69
  - Resolve 21.1 free has no scripting API (Studio-only). The skill uses only the normal UI and File > Import > Timeline. Never write scripts into Resolve's Scripts folders (a guard hook blocks it).
70
+ - Live Resolve driving is beta: `new-job` can leave the new bin unnamed (DR-65). On any non-zero `resolve_ui` exit, do not retry more than once; tell the user the supported path: in Resolve (project claude-space) File > Import > Timeline > `<job>\handoff\timeline.fcpxml`, then File > Import > Subtitle > `<job>\handoff\<job>.srt`.
65
71
  - Tracked blur uses template matching: fine for slow or moderate motion. For fast motion, split the range into several fixed boxes.
66
72
  - Studio-only features (Magic Mask, AI transcription, optical flow) are not used.
@@ -1,9 +1,11 @@
1
1
  import json
2
+ import math
2
3
 
3
4
  import cv2
4
5
  import numpy as np
5
6
 
6
7
  from engine.ffmpeg_io import ffmpeg_cmd, run
8
+ from engine.filter_chain import LabelChain
7
9
 
8
10
 
9
11
  def build_blur_filter(v_label, blur_boxes, out_label):
@@ -11,11 +13,10 @@ def build_blur_filter(v_label, blur_boxes, out_label):
11
13
  if not blur_boxes:
12
14
  return "", v_label
13
15
  stages = []
14
- cur = v_label
16
+ chain = LabelChain(v_label, out_label, "blur")
15
17
  for i, b in enumerate(blur_boxes):
18
+ cur, nxt = chain.advance(i, len(blur_boxes))
16
19
  enable = f"between(t,{b['t_start']},{b['t_end']})"
17
- is_last = i == len(blur_boxes) - 1
18
- nxt = out_label if is_last else f"blur{i}"
19
20
  strength = b.get("strength", 20)
20
21
  # chroma planes are half-resolution (4:2:0), so their boxblur radius cap is tighter than luma's.
21
22
  min_dim = min(b["w"], b["h"])
@@ -28,7 +29,6 @@ def build_blur_filter(v_label, blur_boxes, out_label):
28
29
  f"chroma_radius={chroma_strength}:chroma_power=2:enable='{enable}'[bb{i}blurred];"
29
30
  f"[bb{i}main][bb{i}blurred]overlay={b['x']}:{b['y']}:enable='{enable}'[{nxt}]"
30
31
  )
31
- cur = nxt
32
32
  return ";".join(stages), out_label
33
33
 
34
34
 
@@ -77,7 +77,10 @@ def track_boxes(input_path, tracked_boxes, fps):
77
77
  per_box_frames = {}
78
78
  for bi, box in enumerate(tracked_boxes):
79
79
  start_frame = int(round(box["t_start"] * fps))
80
- end_frame = int(round(box["t_end"] * fps))
80
+ # OPEN_END (DR-32: a box that reaches the edit timeline's true end)
81
+ # is float('inf') - round()/int() reject infinity, so track through
82
+ # every remaining frame instead of a computed cutoff.
83
+ end_frame = math.inf if math.isinf(box["t_end"]) else int(round(box["t_end"] * fps))
81
84
  per_box_frames[bi] = {
82
85
  "tracker": TemplateTracker((box["x"], box["y"], box["w"], box["h"])),
83
86
  "start": start_frame,
@@ -0,0 +1,43 @@
1
+ import hashlib
2
+ import json
3
+ from pathlib import Path
4
+
5
+ CACHE_FILE = "cache.json"
6
+
7
+
8
+ def compute_spec_hash(spec, sources, extra=None):
9
+ """Hash of everything that determines a rebuildable intermediate: each
10
+ segment's source+trim points, the spec's fps override, and every
11
+ referenced source file's own mtime/size (a content change on disk must
12
+ invalidate the cache even if the spec text didn't change) (DR-52)."""
13
+ source_state = {}
14
+ for source_id, path in sources.items():
15
+ p = Path(path)
16
+ try:
17
+ st = p.stat()
18
+ source_state[source_id] = {"path": str(p.resolve()), "mtime": st.st_mtime, "size": st.st_size}
19
+ except OSError:
20
+ source_state[source_id] = {"path": str(p)}
21
+ payload = {
22
+ "segments": spec.get("segments", []),
23
+ "fps": spec.get("fps"),
24
+ "sources": source_state,
25
+ "extra": extra or {},
26
+ }
27
+ blob = json.dumps(payload, sort_keys=True, default=str)
28
+ return hashlib.sha256(blob.encode("utf-8")).hexdigest()
29
+
30
+
31
+ def load_cache(workdir):
32
+ path = Path(workdir) / CACHE_FILE
33
+ if not path.exists():
34
+ return {}
35
+ try:
36
+ return json.loads(path.read_text(encoding="utf-8"))
37
+ except (json.JSONDecodeError, OSError):
38
+ return {}
39
+
40
+
41
+ def save_cache(workdir, cache):
42
+ path = Path(workdir) / CACHE_FILE
43
+ path.write_text(json.dumps(cache, indent=2), encoding="utf-8")
@@ -1,10 +1,33 @@
1
1
  import re
2
2
  from pathlib import Path
3
3
 
4
+ from PIL import Image, ImageDraw, ImageFilter, ImageFont
5
+
6
+ from engine.filter_chain import LabelChain
7
+ from engine.schema import SpecValidationError, apply_layout_defaults
8
+ from engine.timeline_math import subtract_ranges
9
+
10
+ MIN_FONT_SIZE_REFERENCE_WIDTH = 1440
11
+ LINE_SPACING_FACTOR = 1.25
12
+
13
+ BAND_CORNER_RADIUS_FACTOR = 0.35 # x line height
14
+ BAND_PAD_X_FACTOR = 0.6 # x font size
15
+ BAND_PAD_Y_FACTOR = 0.45 # x font size
16
+ BAND_HAIRLINE_ALPHA = 0.12
17
+ ACCENT_WIDTH = 4
18
+ ACCENT_DEFAULT_COLOR = "#FF7A1A"
19
+ SHADOW_OFFSET = (0, 6)
20
+ SHADOW_BLUR_RADIUS = 10
21
+ SHADOW_ALPHA = 90
22
+ SHADOW_MARGIN = SHADOW_BLUR_RADIUS * 3 + max(abs(v) for v in SHADOW_OFFSET)
23
+ SHADOW_BLEED_ALLOWANCE = SHADOW_BLUR_RADIUS + max(abs(v) for v in SHADOW_OFFSET)
24
+
4
25
  DEFAULT_FONT_CANDIDATES = [
5
- "C:/Windows/Fonts/arial.ttf",
26
+ "C:/Windows/Fonts/seguisb.ttf", # Segoe UI Semibold
27
+ "C:/Windows/Fonts/segoeuib.ttf", # Segoe UI Bold
6
28
  "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
7
- "/System/Library/Fonts/Supplemental/Arial.ttf",
29
+ "/System/Library/Fonts/Supplemental/Arial Bold.ttf",
30
+ "C:/Windows/Fonts/arial.ttf",
8
31
  ]
9
32
 
10
33
 
@@ -20,13 +43,17 @@ def resolve_font(font_file):
20
43
 
21
44
 
22
45
  def escape_drawtext(text):
23
- """Value is wrapped in single quotes by the caller; ffmpeg's quoting does
24
- not support backslash-escaping a quote inside quotes, so a literal quote
25
- must close/reopen the quoted string instead (same trick as POSIX sh)."""
46
+ """Value is wrapped in single quotes by the caller. ffmpeg's own
47
+ filtergraph tokenizer (not a shell) has no way to embed a literal quote
48
+ inside a quoted value - both '\\'' and \\' desync the parser and swallow
49
+ every option after it into the text, verified empirically since neither
50
+ is caught by ffmpeg with a parse error. Swap the ASCII apostrophe for the
51
+ Unicode one instead, which is not a tokenizer metacharacter. Callers must
52
+ also set drawtext's expansion=none, or a literal '%' triggers a 'Stray %'
53
+ warning and drops the rest of the text."""
26
54
  text = text.replace("\\", "\\\\")
27
55
  text = text.replace(":", "\\:")
28
- text = text.replace("%", "\\%")
29
- text = text.replace("'", r"'\''")
56
+ text = text.replace("'", "’")
30
57
  return text
31
58
 
32
59
 
@@ -36,39 +63,274 @@ def escape_path(path):
36
63
  return str(path).replace("\\", "/").replace(":", "\\:")
37
64
 
38
65
 
39
- def _position_expr(value, axis_size_var, text_size_var):
40
- if value == "center":
41
- return f"({axis_size_var}-{text_size_var})/2"
42
- return str(value)
66
+ class CaptionFitError(ValueError):
67
+ def __init__(self, text, lines, max_lines, line_w, max_width, block_h=None, max_height=None):
68
+ if line_w > max_width:
69
+ msg = (f"caption {text!r} does not fit at minimum font size: widest wrapped "
70
+ f"line is {line_w:.0f}px, max width is {max_width:.0f}px")
71
+ elif block_h is not None and max_height is not None and block_h > max_height:
72
+ msg = (f"caption {text!r} does not fit at minimum font size: wrapped block is "
73
+ f"{block_h:.0f}px tall, max height is {max_height:.0f}px")
74
+ else:
75
+ msg = (f"caption {text!r} does not fit at minimum font size: wraps to "
76
+ f"{len(lines)} lines, max_lines is {max_lines}")
77
+ super().__init__(msg)
78
+
79
+
80
+ def _text_size(font, text):
81
+ bbox = font.getbbox(text)
82
+ return bbox[2] - bbox[0], bbox[3] - bbox[1]
83
+
84
+
85
+ def wrap_text_to_width(font, text, max_width):
86
+ """Greedy word wrap; a single word wider than max_width is kept on its
87
+ own (overflowing) line so the caller's fit check can catch it."""
88
+ words = text.split()
89
+ if not words:
90
+ return [""]
91
+ lines = []
92
+ cur = words[0]
93
+ for word in words[1:]:
94
+ candidate = f"{cur} {word}"
95
+ width, _ = _text_size(font, candidate)
96
+ if width <= max_width:
97
+ cur = candidate
98
+ else:
99
+ lines.append(cur)
100
+ cur = word
101
+ lines.append(cur)
102
+ return lines
103
+
104
+
105
+ def _band_padding(font_size):
106
+ return font_size * BAND_PAD_X_FACTOR, font_size * BAND_PAD_Y_FACTOR
107
+
108
+
109
+ def fit_caption_text(text, font_file, start_size, min_size, max_lines, avail_w, avail_h):
110
+ """Wraps text at start_size; shrinks in 2px steps down to min_size (or
111
+ start_size, whichever is smaller, so an explicit small font is honoured)
112
+ until the wrapped block fits inside avail_w/avail_h. Padding scales with
113
+ font_size (item 3's look), so the per-size text budget - and therefore
114
+ the wrap width and height budget - is recomputed at every candidate
115
+ size, not fixed up front."""
116
+ floor = min(min_size, start_size)
117
+ lines, sizes, max_line_w, block_h = [text], [], 0.0, 0.0
118
+ max_text_w = max_text_h = 0.0
119
+ for size in range(start_size, floor - 1, -2):
120
+ pad_x, pad_y = _band_padding(size)
121
+ max_text_w = max(1.0, avail_w - 2 * pad_x)
122
+ max_text_h = max(1.0, avail_h - 2 * pad_y)
123
+ font = ImageFont.truetype(font_file, size)
124
+ lines = wrap_text_to_width(font, text, max_text_w)
125
+ sizes = [_text_size(font, ln) for ln in lines]
126
+ max_line_w = max(w for w, _h in sizes)
127
+ line_h = max(h for _w, h in sizes)
128
+ block_h = line_h * LINE_SPACING_FACTOR * len(lines)
129
+ if max_line_w <= max_text_w and len(lines) <= max_lines and block_h <= max_text_h:
130
+ return {
131
+ "font_size": size,
132
+ "lines": lines,
133
+ "line_sizes": sizes,
134
+ "line_height": line_h,
135
+ "block_width": max_line_w,
136
+ "block_height": block_h,
137
+ }
138
+ raise CaptionFitError(text, lines, max_lines, max_line_w, max_text_w, block_h, max_text_h)
139
+
140
+
141
+ def compute_caption_layout(cap, frame_w, frame_h):
142
+ """Resolves one caption's band size/style and per-line pixel positions
143
+ (local to the band) plus its placement on the frame. Pure function: no
144
+ ffmpeg/filesystem side effects beyond reading the font file for metrics."""
145
+ layout = apply_layout_defaults(cap.get("layout"))
146
+ font_file = resolve_font(cap.get("font_file"))
147
+ margin = layout["margin_pct"] / 100 * frame_w
148
+ bottom_margin = layout["bottom_margin_pct"] / 100 * frame_h
149
+ # the soft drop shadow extends past the band's own box by roughly
150
+ # offset+blur_radius; a band sized/anchored right up to the margin line
151
+ # would leave the shadow crossing it, so both the text's fit budget and
152
+ # the frame placement below use this slightly tighter safe edge instead
153
+ # of the margin itself.
154
+ safe_margin = margin + SHADOW_BLEED_ALLOWANCE
155
+ safe_bottom_margin = bottom_margin + SHADOW_BLEED_ALLOWANCE
156
+ avail_w = max(1.0, frame_w - 2 * safe_margin)
157
+ avail_h = max(1.0, frame_h - 2 * safe_bottom_margin)
158
+ min_font_size = max(1, round(layout["min_font_size"] * frame_w / MIN_FONT_SIZE_REFERENCE_WIDTH))
159
+
160
+ fit = fit_caption_text(cap["text"], font_file, cap.get("font_size", 48), min_font_size, layout["max_lines"], avail_w, avail_h)
161
+ pad_x, pad_y = _band_padding(fit["font_size"])
162
+ corner_radius = fit["line_height"] * BAND_CORNER_RADIUS_FACTOR
163
+
164
+ # Rounded once, here, so the same integer size drives both the
165
+ # frame-placement clamp below and the PNG canvas built later - a
166
+ # float/rounded mismatch between the two is exactly the kind of 1px
167
+ # slop that can push the rendered band a pixel past the safe margin.
168
+ band_w = float(round(min(avail_w, fit["block_width"] + 2 * pad_x)))
169
+ band_h = float(round(fit["block_height"] + 2 * pad_y))
170
+
171
+ x, y = cap.get("x", "center"), cap.get("y", "auto")
172
+ band_x = (frame_w - band_w) / 2 if x == "center" else float(x)
173
+ if y == "auto":
174
+ if layout["position"] == "top":
175
+ band_y = safe_bottom_margin
176
+ elif layout["position"] == "center":
177
+ band_y = (frame_h - band_h) / 2
178
+ else:
179
+ band_y = frame_h - safe_bottom_margin - band_h
180
+ else:
181
+ band_y = float(y)
182
+
183
+ band_x = min(max(safe_margin, band_x), max(safe_margin, frame_w - safe_margin - band_w))
184
+ band_y = min(max(safe_bottom_margin, band_y), max(safe_bottom_margin, frame_h - safe_bottom_margin - band_h))
185
+ band_x = min(max(0.0, band_x), max(0.0, frame_w - band_w))
186
+ band_y = min(max(0.0, band_y), max(0.0, frame_h - band_h))
187
+
188
+ line_local_positions = []
189
+ line_y = pad_y
190
+ for w, _h in fit["line_sizes"]:
191
+ line_x = min(max(0.0, (band_w - w) / 2), max(0.0, band_w - w))
192
+ line_local_positions.append((line_x, line_y))
193
+ line_y += fit["line_height"] * LINE_SPACING_FACTOR
194
+
195
+ accent = layout["accent"]
196
+ if accent is True:
197
+ accent = ACCENT_DEFAULT_COLOR
198
+ elif not accent:
199
+ accent = None
200
+
201
+ return {
202
+ "font_file": font_file,
203
+ "font_size": fit["font_size"],
204
+ "lines": fit["lines"],
205
+ "line_local_positions": line_local_positions,
206
+ "band_w": band_w,
207
+ "band_h": band_h,
208
+ "corner_radius": corner_radius,
209
+ "fill_color": layout["fill_color"],
210
+ "fill_alpha": layout["fill_alpha"],
211
+ "text_color": layout["text_color"],
212
+ "accent": accent,
213
+ "overlay_x": band_x,
214
+ "overlay_y": band_y,
215
+ }
216
+
217
+
218
+ def validate_caption_fit(captions, frame_w, frame_h):
219
+ for cap in captions:
220
+ try:
221
+ compute_caption_layout(cap, frame_w, frame_h)
222
+ except CaptionFitError as e:
223
+ raise SpecValidationError([str(e)]) from e
224
+
225
+
226
+ def split_captions_for_exclusions(captions, caption_free):
227
+ """Expands each caption into one entry per sub-range still shown after
228
+ subtracting its own `exclude` windows and the spec-wide `caption_free`
229
+ windows - holding a caption off during e.g. a keep_1x consent screen
230
+ without the caller splitting it into two entries by hand (DR-58). Must
231
+ run on edit-timeline (pre-speed-ramp) captions, before map_time_fields."""
232
+ global_free = [(cf["t_start"], cf["t_end"]) for cf in caption_free]
233
+ expanded, warnings = [], []
234
+ for cap in captions:
235
+ own_exclude = [(e["t_start"], e["t_end"]) for e in cap.get("exclude", [])]
236
+ pieces = subtract_ranges((cap["t_start"], cap["t_end"]), own_exclude + global_free)
237
+ if not pieces:
238
+ warnings.append(f"caption {cap['text']!r} fully excluded by exclude/caption_free ranges; dropped")
239
+ continue
240
+ if pieces != [(cap["t_start"], cap["t_end"])]:
241
+ warnings.append(f"caption {cap['text']!r} clipped by exclude/caption_free ranges: {cap['t_start']}-{cap['t_end']} -> {pieces}")
242
+ for t0, t1 in pieces:
243
+ piece = {k: v for k, v in cap.items() if k != "exclude"}
244
+ piece["t_start"], piece["t_end"] = t0, t1
245
+ expanded.append(piece)
246
+ return expanded, warnings
247
+
248
+
249
+ def _hex_to_rgb(hex_color):
250
+ hex_color = hex_color.lstrip("#")
251
+ return tuple(int(hex_color[i:i + 2], 16) for i in (0, 2, 4))
252
+
253
+
254
+ def render_caption_image(layout):
255
+ """Renders one caption as a standalone RGBA PNG: a rounded band (fill,
256
+ inner hairline, optional left accent bar) with a soft drop shadow,
257
+ canvas-padded so the shadow's blur isn't clipped at the edge. drawbox/
258
+ drawtext can't produce rounded corners or a blurred shadow, and drawtext's
259
+ own tokenizer corrupts on a quote or a bare '%' (DR-34-followup) - PIL
260
+ sidesteps both."""
261
+ band_w = int(round(layout["band_w"]))
262
+ band_h = int(round(layout["band_h"]))
263
+ radius = layout["corner_radius"]
264
+ canvas_w = band_w + 2 * SHADOW_MARGIN
265
+ canvas_h = band_h + 2 * SHADOW_MARGIN
266
+ x0, y0 = SHADOW_MARGIN, SHADOW_MARGIN
267
+ x1, y1 = x0 + band_w, y0 + band_h
268
+
269
+ shadow_alpha = Image.new("L", (canvas_w, canvas_h), 0)
270
+ ImageDraw.Draw(shadow_alpha).rounded_rectangle(
271
+ [x0 + SHADOW_OFFSET[0], y0 + SHADOW_OFFSET[1], x1 + SHADOW_OFFSET[0], y1 + SHADOW_OFFSET[1]],
272
+ radius=radius, fill=SHADOW_ALPHA,
273
+ )
274
+ shadow_alpha = shadow_alpha.filter(ImageFilter.GaussianBlur(SHADOW_BLUR_RADIUS))
275
+ canvas = Image.new("RGBA", (canvas_w, canvas_h), (0, 0, 0, 0))
276
+ canvas.paste((0, 0, 0, 255), mask=shadow_alpha)
277
+
278
+ band_mask = Image.new("L", (canvas_w, canvas_h), 0)
279
+ ImageDraw.Draw(band_mask).rounded_rectangle([x0, y0, x1, y1], radius=radius, fill=255)
280
+
281
+ band_layer = Image.new("RGBA", (canvas_w, canvas_h), (0, 0, 0, 0))
282
+ band_draw = ImageDraw.Draw(band_layer)
283
+ fill_alpha = int(round(layout["fill_alpha"] * 255))
284
+ band_draw.rounded_rectangle([x0, y0, x1, y1], radius=radius, fill=_hex_to_rgb(layout["fill_color"]) + (fill_alpha,))
285
+ if layout["accent"]:
286
+ band_draw.rectangle([x0, y0, x0 + ACCENT_WIDTH, y1], fill=_hex_to_rgb(layout["accent"]) + (255,))
287
+ hairline_alpha = int(round(BAND_HAIRLINE_ALPHA * 255))
288
+ band_draw.rounded_rectangle([x0, y0, x1 - 1, y1 - 1], radius=radius, outline=(255, 255, 255, hairline_alpha), width=1)
289
+
290
+ masked_band = Image.new("RGBA", (canvas_w, canvas_h), (0, 0, 0, 0))
291
+ masked_band.paste(band_layer, (0, 0), mask=band_mask)
292
+ canvas = Image.alpha_composite(canvas, masked_band)
293
+
294
+ font = ImageFont.truetype(layout["font_file"], layout["font_size"])
295
+ text_rgb = _hex_to_rgb(layout["text_color"])
296
+ draw = ImageDraw.Draw(canvas)
297
+ for line, (lx, ly) in zip(layout["lines"], layout["line_local_positions"]):
298
+ draw.text((x0 + lx, y0 + ly), line, font=font, fill=text_rgb + (255,))
299
+
300
+ return canvas
43
301
 
44
302
 
45
- def build_caption_filter(v_label, captions, out_label):
303
+ def build_caption_overlay_filter(v_label, captions, out_label, frame_w, frame_h, workdir):
304
+ """Each caption is a PIL-rendered PNG (render_caption_image) composited
305
+ with ffmpeg's overlay filter. Returns (filter_str, out_label, png_paths);
306
+ the caller must add an '-i <path>' for each png_paths entry, in order,
307
+ immediately after the main video input - the filter references them as
308
+ ffmpeg input indices 1..N."""
46
309
  if not captions:
47
- return "", v_label
310
+ return "", v_label, []
311
+ workdir = Path(workdir)
312
+ workdir.mkdir(parents=True, exist_ok=True)
313
+ chain = LabelChain(v_label, out_label, "cap")
48
314
  stages = []
49
- cur = v_label
315
+ png_paths = []
50
316
  for i, cap in enumerate(captions):
51
- font_file = resolve_font(cap.get("font_file"))
52
- x_expr = _position_expr(cap.get("x", "center"), "w", "text_w")
53
- y_expr = _position_expr(cap.get("y", 100), "h", "text_h")
317
+ layout = compute_caption_layout(cap, frame_w, frame_h)
318
+ image = render_caption_image(layout)
319
+ png_path = workdir / f"caption_{i}.png"
320
+ image.save(png_path)
321
+ png_paths.append(png_path)
322
+ # overlay_x/y are already clamped (compute_caption_layout) to keep
323
+ # the band itself inside the frame's safe margins; the PNG canvas is
324
+ # bigger than the band (SHADOW_MARGIN of transparent padding for the
325
+ # blur), and ffmpeg's overlay silently clips content past the frame
326
+ # edge, so the canvas offset can go negative/overflow without a
327
+ # second clamp that would otherwise squeeze the shadow into the band.
328
+ ox = layout["overlay_x"] - SHADOW_MARGIN
329
+ oy = layout["overlay_y"] - SHADOW_MARGIN
54
330
  enable = f"between(t,{cap['t_start']},{cap['t_end']})"
55
- is_last = i == len(captions) - 1
56
- nxt = out_label if is_last else f"cap{i}"
57
- parts = [
58
- f"drawtext=fontfile='{escape_path(font_file)}'",
59
- f"text='{escape_drawtext(cap['text'])}'",
60
- f"x={x_expr}",
61
- f"y={y_expr}",
62
- f"fontsize={cap.get('font_size', 48)}",
63
- f"fontcolor={cap.get('color', 'white')}",
64
- f"enable='{enable}'",
65
- ]
66
- box_color = cap.get("box_color")
67
- if box_color:
68
- parts += ["box=1", f"boxcolor={box_color}", "boxborderw=10"]
69
- stages.append(f"[{cur}]{':'.join(parts)}[{nxt}]")
70
- cur = nxt
71
- return ";".join(stages), out_label
331
+ cur, nxt = chain.advance(i, len(captions))
332
+ stages.append(f"[{cur}][{i + 1}:v]overlay=x={ox:.1f}:y={oy:.1f}:enable='{enable}'[{nxt}]")
333
+ return ";".join(stages), out_label, png_paths
72
334
 
73
335
 
74
336
  SRT_TIME_RE = re.compile(r"(\d{2}):(\d{2}):(\d{2}),(\d{3})")