@clipen/clipen-cli 1.0.8 → 1.0.9

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 (80) hide show
  1. package/README.md +13 -4
  2. package/apps/web/dist/assets/index-DPgSvXZ1.js +15 -0
  3. package/apps/web/dist/assets/index-DmPWV61v.css +1 -0
  4. package/apps/web/dist/index.html +2 -2
  5. package/bin/clipen.js +6 -15
  6. package/package.json +1 -1
  7. package/pyproject.toml +1 -1
  8. package/src/clipen/__init__.py +1 -1
  9. package/src/clipen/bootstrap.py +130 -23
  10. package/src/clipen/controller/app.py +83 -21
  11. package/src/clipen/controller/server.py +5 -0
  12. package/src/clipen/editing/agent_tools.py +1 -1
  13. package/src/clipen/editing/caption_design.py +134 -0
  14. package/src/clipen/editing/component_looks.py +3 -3
  15. package/src/clipen/editing/component_review.py +0 -38
  16. package/src/clipen/editing/coordinator.py +14 -0
  17. package/src/clipen/editing/production_catalog.py +67 -13
  18. package/src/clipen/editing/production_media.py +13 -2
  19. package/src/clipen/editing/production_preview.py +11 -9
  20. package/src/clipen/editing/production_progress.py +2 -0
  21. package/src/clipen/editing/production_tools.py +11 -20
  22. package/src/clipen/editing/program_subtitles.py +5 -13
  23. package/src/clipen/editing/resolve_export.py +2 -183
  24. package/src/clipen/editing/skill_tools.py +142 -218
  25. package/src/clipen/editing/tool_receipts.py +2 -1
  26. package/src/clipen/editing/versions.py +2 -0
  27. package/src/clipen/editing/visual_preview.py +62 -0
  28. package/src/clipen/editing/workbench.py +21 -1
  29. package/src/clipen/locale_en.py +18 -0
  30. package/src/clipen/media/storage.py +2 -2
  31. package/src/clipen/own_ffmpeg.py +113 -0
  32. package/src/clipen/providers/editing_agent.py +6 -4
  33. package/src/clipen/rendering/custom_components.py +216 -25
  34. package/src/clipen/rendering/custom_render.py +90 -54
  35. package/src/clipen/rendering/fetched_fonts.py +127 -0
  36. package/src/clipen/rendering/production_effects.py +24 -2
  37. package/src/clipen/rendering/program_components.py +18 -240
  38. package/src/clipen/rendering/renderer.py +23 -17
  39. package/src/clipen/rendering/titles.py +29 -12
  40. package/src/clipen/skills/builtin/SKILL.md +3 -3
  41. package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
  42. package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
  43. package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
  44. package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
  45. package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
  46. package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
  47. package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
  48. package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
  49. package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
  50. package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
  51. package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
  52. package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
  53. package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
  54. package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
  55. package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
  56. package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
  57. package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
  58. package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
  59. package/src/clipen/skills/builtin/references/captions.md +12 -0
  60. package/src/clipen/skills/builtin/references/graphics.md +6 -5
  61. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +9 -4
  62. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +10 -5
  63. package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +9 -4
  64. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +10 -6
  65. package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +10 -6
  66. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +9 -7
  67. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +10 -5
  68. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +10 -5
  69. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +10 -7
  70. package/src/clipen/skills/catalog.py +0 -8
  71. package/src/clipen/skills/package.py +1 -10
  72. package/apps/web/dist/assets/index-CJ80KHsQ.css +0 -1
  73. package/apps/web/dist/assets/index-C_4u_hVf.js +0 -16
  74. package/src/clipen/editing/resolve_titles.py +0 -291
  75. package/src/clipen/rendering/program_creator.py +0 -804
  76. package/src/clipen/rendering/program_identities.py +0 -350
  77. package/src/clipen/rendering/program_motion.py +0 -186
  78. package/src/clipen/rendering/program_studio.py +0 -227
  79. package/src/clipen/rendering/program_styles.py +0 -321
  80. package/src/clipen/skills/builtin/components.json +0 -133
@@ -382,6 +382,10 @@ class EditAgentCoordinator:
382
382
  def workbench_render(self, project_id, run_id, expected_revision_id):
383
383
  from .workbench import idle, tools_for
384
384
 
385
+ # A person tuning a graphic saves again and again; the newest version replaces a render still under way.
386
+ earlier = self._user_previews.get((project_id, run_id))
387
+ if earlier is not None:
388
+ self._stop_user_renders(project_id, earlier)
385
389
  with self._lock:
386
390
  run = idle(self.repository, project_id, run_id)
387
391
  if run.current_revision_id != expected_revision_id:
@@ -395,6 +399,16 @@ class EditAgentCoordinator:
395
399
  del tools._session_cache
396
400
  return tools.production_call("render_preview", {}).payload
397
401
 
402
+ def _stop_user_renders(self, project_id, tools):
403
+ from clipen.rendering import PreviewRenderRepository
404
+
405
+ store = PreviewRenderRepository(self.repository.projects)
406
+ for render_id, (cancel, thread) in list(getattr(tools, "_preview_jobs", {}).items()):
407
+ if thread.is_alive():
408
+ store.request_cancel(project_id, render_id)
409
+ cancel.set()
410
+ thread.join(timeout=30)
411
+
398
412
  def resume(self, project_id: str, run_id: str, consent: object) -> AgentRun:
399
413
  if consent is not True:
400
414
  raise ProjectError(
@@ -255,6 +255,11 @@ EXTRA_TOOLS = (
255
255
  "additionalProperties": False,
256
256
  },
257
257
  "delivery": {"enum": ["dialogue", "punchline", "quiet"]},
258
+ "design_id": {
259
+ "type": "string",
260
+ "maxLength": 80,
261
+ "description": "A caption design from set_caption_design; default the latest.",
262
+ },
258
263
  "emphasis": {
259
264
  "type": "array",
260
265
  "items": {"type": "string", "minLength": 1, "maxLength": 16},
@@ -310,14 +315,23 @@ EXTRA_TOOLS = (
310
315
  ),
311
316
  schema(
312
317
  "set_color_grade",
313
- "Set explicit per-clip exposure/contrast/saturation; neutral values remove the visual grade.",
318
+ "Grade one clip: contrast, saturation, brightness and gamma; colour temperature (-1 cool to 1 warm) and tint (-1 magenta to 1 green); "
319
+ "shadows and highlights (-1 darker to 1 lighter); vignette and film grain (0-1). Leave out what you do not change; neutral values remove the grade.",
314
320
  {
315
321
  "item_id": ID,
316
322
  "contrast": {"type": "number", "minimum": 0.5, "maximum": 2},
317
323
  "saturation": {"type": "number", "minimum": 0, "maximum": 2},
318
324
  "brightness": {"type": "number", "minimum": -0.3, "maximum": 0.3},
325
+ "gamma": {"type": "number", "minimum": 0.5, "maximum": 2},
326
+ "temperature": {"type": "number", "minimum": -1, "maximum": 1},
327
+ "tint": {"type": "number", "minimum": -1, "maximum": 1},
328
+ "shadows": {"type": "number", "minimum": -1, "maximum": 1},
329
+ "highlights": {"type": "number", "minimum": -1, "maximum": 1},
330
+ "vignette": {"type": "number", "minimum": 0, "maximum": 1},
331
+ "grain": {"type": "number", "minimum": 0, "maximum": 1},
319
332
  **SUMMARY,
320
333
  },
334
+ ["item_id", "summary"],
321
335
  ),
322
336
  schema(
323
337
  "set_mosaic",
@@ -426,19 +440,32 @@ EXTRA_TOOLS = (
426
440
  "Save native editable timeline JSON and source/license credits for the current revision. This is not a Resolve project.",
427
441
  ),
428
442
  )
443
+ CAPTION_DESIGN_HELP = (
444
+ "Design how every caption of the film looks, as one self-contained web page (HTML, CSS, SVG, JS), before replace_subtitles; "
445
+ "there is no built-in caption style. Put one element with data-clipen-caption where the words go: Clipen fills it with each "
446
+ "caption's words, its emphasis words wrapped in <em>, and sets data-delivery on <html> to dialogue, punchline or quiet, so "
447
+ "style em and [data-delivery=punchline] / [data-delivery=quiet] yourself. The page is the whole picture; draw only the caption "
448
+ "and keep the rest transparent; place and style it however the film calls for. Any typeface works, as for graphics (installed, "
449
+ "carried, or fetched with get_font); look_id is optional. Motion: by default Clipen draws the first entry_frames and the last "
450
+ "exit_frames (0-60 each) and one still frame between, so render stays fast; set throughout: true to let it move on every frame. "
451
+ "--clipen-duration (seconds) lets an exit start at var(--clipen-duration) minus its length. A new design restyles every caption "
452
+ "on the film unless apply_to_existing is false; each design gets a design_id, and replace_subtitles rows may pick one per caption "
453
+ "with design_id, so a film may use several. Render and watch them."
454
+ )
429
455
  CUSTOM_COMPONENT_HELP = (
430
456
  "Design an in-picture graphic freely as one self-contained web page: any HTML, CSS, SVG, Canvas or JavaScript, any layout, "
431
- "typeface, colour, shape or motion. Use it when the built-in components cannot give the look the film needs. "
457
+ "typeface, colour, shape or motion. Every graphic in the film is made this way; there are no built-in components. "
432
458
  "The page is the whole picture (window.clipen.width x window.clipen.height pixels, e.g. 1920x1080); draw only the graphic and leave "
433
459
  "the rest transparent, so the footage shows through. Clipen sets the time: CSS animations and the Web Animations API play by "
434
460
  "themselves, frame-accurately; for script-driven drawing define window.clipenFrame = (frame, seconds) => {...} (may be async) "
435
461
  "and draw that exact frame there. requestAnimationFrame loops, timers and real clocks do not advance. Frame 0 is the first frame "
436
462
  "of the graphic; window.clipen also gives fps and durationFrames. The page has no network: inline everything (data: URLs, inline SVG). "
437
- "Looks: graphics of one kind (chapters, places, reactions...) share a look you define first with set_component_look: its typefaces and "
438
- "colours. Pass its look_id; Clipen gives the page that look as CSS variables, font-family: var(--look-font-<key>) and colour var(--look-<key>). "
439
- "Text may only use the look's typefaces (anything else is refused); colours, layout, shapes and motion stay free. To use another typeface, "
440
- "change the look or make a new one; every graphic using a look follows its changes. Only technical checks apply otherwise: the page must load, run without "
441
- "errors, draw each frame within 10 seconds, draw something, and stay under 200 KB. The result returns two images: a still of the graphic at rest over the footage, and a sheet of frames from entry to exit (labelled by frame number), so you can judge the motion; look at both and fix what does not read. "
463
+ "Type: use any typeface by its name: every font installed on this Mac, the fonts Clipen carries, and any open font from "
464
+ "Google Fonts once you fetch it with get_font (then font-family: '<its name>'). Looks are optional: graphics of one kind may share a look "
465
+ "made with set_component_look (pass look_id; Clipen gives its fonts and colours as var(--look-font-<key>) and var(--look-<key>), and every "
466
+ "graphic using it follows its changes), or a page may set its own type and colour. A graphic may run across a cut: a full-picture design "
467
+ "that covers the cut is a transition of your own design (set_transition only offers dips). Only technical checks apply: the page must load, run without "
468
+ "errors, draw each frame within 10 seconds, draw something, and stay under 2 MB. The result returns two images: a still of the graphic at rest over the footage, and a sheet of frames from entry to exit (labelled by frame number), so you can judge the motion; look at both and fix what does not read. "
442
469
  'Mark what people may change themselves: put each main wording as plain text in an element with data-clipen-text="key" '
443
470
  '(optional data-clipen-label="主標"), and declare main colours as :root custom properties named --clipen-<name> (e.g. --clipen-主色) used via var(). '
444
471
  "Their changes are applied before your scripts run; split text into letters on DOMContentLoaded or later, from the element's current text."
@@ -457,10 +484,10 @@ CUSTOM_COMPONENT_FIELDS = {
457
484
  "maxLength": 40,
458
485
  "description": "Short label people see on the timeline, e.g. 澀谷地標標題.",
459
486
  },
460
- "html": {"type": "string", "minLength": 1, "maxLength": 200000},
487
+ "html": {"type": "string", "minLength": 1, "maxLength": 2000000},
461
488
  "look_id": {
462
489
  **ID,
463
- "description": "The look (typefaces and colours) this graphic uses, from set_component_look. Required when adding.",
490
+ "description": "Optional: a shared look (typefaces and colours) from set_component_look.",
464
491
  },
465
492
  "evidence": TEXT,
466
493
  **SUMMARY,
@@ -469,9 +496,8 @@ LOOK_KEY = {"type": "string", "minLength": 1, "maxLength": 24}
469
496
  LOOK_HELP = (
470
497
  "Create or change a look: a named set of typefaces and colours that graphics of one kind share (e.g. a chapter look, a place look, "
471
498
  "a reaction look). Design each look for its role; looks may differ completely. Pages use the look through CSS variables: "
472
- "font-family: var(--look-font-<key>) and color var(--look-<key>). Graphics already using this look_id are redrawn with it; a change is "
473
- "refused if one of them would then need a typeface the look no longer has. Typefaces: list_program_components gives font_choices "
474
- "(system fonts, plus fonts Clipen carries: Chinese handwriting 'Clipen Chenyu' and brush 'Clipen Iansui', Japanese handwriting "
499
+ "font-family: var(--look-font-<key>) and color var(--look-<key>). Graphics already using this look_id are redrawn with it. A typeface may be any font "
500
+ "installed on this Mac, any open font fetched with get_font, or one Clipen carries (list_program_components lists them; carried: Chinese handwriting 'Clipen Chenyu' and brush 'Clipen Iansui', Japanese handwriting "
475
501
  "'Yusei Magic', 'Yomogi', 'Zen Kurenaido', 'Hachi Maru Pop', Japanese display 'Dela Gothic One', 'RocknRoll One', 'Zen Maru Gothic', "
476
502
  "Latin 'Bebas Neue', 'Anton', 'Caveat', 'Playfair Display'). When a typeface lacks a Chinese or Japanese character the graphic "
477
503
  "shows, that font key draws all its Chinese and Japanese in the next face of the same feel that has them all (Clipen Chenyu "
@@ -536,11 +562,39 @@ SKILL_TOOLS = (
536
562
  },
537
563
  ["look_id", "name", "fonts", "summary"],
538
564
  ),
565
+ schema(
566
+ "get_font",
567
+ "Fetch an open-licensed font family from Google Fonts by its exact name (e.g. 'Noto Serif TC', 'LXGW WenKai TC', 'Bricolage Grotesque') "
568
+ "so graphics and captions can use it as font-family: '<name>'. Clipen downloads it once, checks it is OFL, Apache or UFL licensed, "
569
+ "and keeps it on this Mac; pages stay offline. Fonts installed on the Mac need no fetching.",
570
+ {"family": {"type": "string", "minLength": 1, "maxLength": 60}},
571
+ ["family"],
572
+ ),
573
+ schema(
574
+ "set_caption_design",
575
+ CAPTION_DESIGN_HELP,
576
+ {
577
+ "html": {"type": "string", "minLength": 1, "maxLength": 2000000},
578
+ "look_id": ID,
579
+ "entry_frames": {"type": "integer", "minimum": 0, "maximum": 60},
580
+ "exit_frames": {"type": "integer", "minimum": 0, "maximum": 60},
581
+ "throughout": {
582
+ "type": "boolean",
583
+ "description": "true: the caption may move on every frame (slower to render).",
584
+ },
585
+ "apply_to_existing": {
586
+ "type": "boolean",
587
+ "description": "false: keep the captions already on the film as they are; default true.",
588
+ },
589
+ **SUMMARY,
590
+ },
591
+ ["html", "summary"],
592
+ ),
539
593
  schema(
540
594
  "add_custom_component",
541
595
  CUSTOM_COMPONENT_HELP,
542
596
  CUSTOM_COMPONENT_FIELDS,
543
- ["element_id", "item_id", "start_offset_frames", "duration_frames", "name", "html", "look_id", "summary"],
597
+ ["element_id", "item_id", "start_offset_frames", "duration_frames", "name", "html", "summary"],
544
598
  ),
545
599
  schema(
546
600
  "update_custom_component",
@@ -83,9 +83,20 @@ class AgentAudioStore:
83
83
  raise ProjectError("agent_audio_missing", "找不到這個作品已取得的音訊。", status_code=404)
84
84
  asset = record["asset"]
85
85
  reference = record["reference"]
86
- path = Path(reference["canonical_path"])
87
- if path.parent != self.directory or path.is_symlink():
86
+ path = self.directory / Path(reference["canonical_path"]).name
87
+ if path.is_symlink():
88
88
  raise ProjectError("storage_unsafe", "音訊來源不在本作品的管理範圍。", status_code=409)
89
+ if not path.is_dir():
90
+ raise ProjectError("agent_audio_missing", "找不到這個作品已取得的音訊。", status_code=404)
91
+ # The folder is this project's own, so it is found where the project now is: a project copied,
92
+ # restored or moved to another Mac keeps its music although the path, inode and mtimes change.
93
+ # The file is still checked against its saved size and fingerprint.
94
+ info = path.stat()
95
+ reference = {**reference, "canonical_path": str(path), "device": info.st_dev, "inode": info.st_ino}
96
+ try:
97
+ asset = {**asset, "mtime_ns": (path / asset["relative_path"]).lstat().st_mtime_ns}
98
+ except OSError:
99
+ pass
89
100
  return {"assets": [asset], "directories": {asset["role"]: reference}}
90
101
 
91
102
 
@@ -30,10 +30,6 @@ def render_recipe_id():
30
30
  from clipen.rendering import (
31
31
  production_effects,
32
32
  program_components,
33
- program_identities,
34
- program_motion,
35
- program_studio,
36
- program_styles,
37
33
  program_subtitles,
38
34
  renderer,
39
35
  titles,
@@ -46,10 +42,6 @@ def render_recipe_id():
46
42
  renderer,
47
43
  titles,
48
44
  program_components,
49
- program_motion,
50
- program_styles,
51
- program_studio,
52
- program_identities,
53
45
  program_subtitles,
54
46
  production_effects,
55
47
  program_audio,
@@ -65,7 +57,17 @@ def render_preview(tools):
65
57
  validation = tools._production_validate_sequence({}).payload
66
58
  issues = validation["render_issues"]
67
59
  if issues:
68
- raise ProjectError("agent_sequence_invalid", "請先使用 validate_sequence 修正時間軸。", status_code=422)
60
+ if not getattr(tools, "_user_edit", False):
61
+ raise ProjectError("agent_sequence_invalid", "請先使用 validate_sequence 修正時間軸。", status_code=422)
62
+ # The person never sees validate_sequence; say what they can do about it.
63
+ audio = {"finishing_library_offline", "finishing_asset_missing", "agent_audio_missing", "media_changed"}
64
+ if any(issue.get("code") in audio for issue in issues):
65
+ raise ProjectError(
66
+ "sequence_audio_missing", "這一版用到的配樂或音效找不到了,請重新選一首配樂再輸出。", status_code=422
67
+ )
68
+ raise ProjectError(
69
+ "sequence_invalid", "這一版有地方需要修正才能輸出,請交給 AI 修改,或回到上一個版本。", status_code=422
70
+ )
69
71
  store = PreviewRenderRepository(tools.repository.projects)
70
72
  # The exact revision is the cache key. Polling/reviewing never rerenders it.
71
73
  with tools.repository.projects.connect(tools.project_id) as db:
@@ -55,6 +55,8 @@ _TOOL_GROUPS = (
55
55
  (
56
56
  "製作字幕與畫面設計",
57
57
  (
58
+ "get_font",
59
+ "set_caption_design",
58
60
  "replace_subtitles",
59
61
  "remove_program_component",
60
62
  "add_custom_component",
@@ -417,9 +417,6 @@ class ProductionTools:
417
417
  "cues"
418
418
  ]
419
419
  }
420
- from .program_direction import direction_for
421
-
422
- program = direction_for(self).get("subtitle_style") == "program"
423
420
  from .program_subtitles import make_subtitle_items
424
421
 
425
422
  captions = []
@@ -433,22 +430,7 @@ class ProductionTools:
433
430
  raise problem("單段字幕請分成可閱讀的句子,最多 80 字。")
434
431
  if any(word not in row["text"] for word in row.get("emphasis", [])):
435
432
  raise problem("重點字必須實際存在於字幕句內。")
436
- if (
437
- program
438
- or cue.get("verification") == "asr_draft"
439
- or any(k in row for k in ("source_excerpt", "delivery", "emphasis"))
440
- ):
441
- captions.extend(make_subtitle_items(self, cue, row))
442
- else:
443
- captions.append(
444
- TextClip(
445
- "subtitle-" + row["cue_id"],
446
- cue["start_frame"],
447
- cue["duration_frames"],
448
- row["text"],
449
- "title.caption",
450
- )
451
- )
433
+ captions.extend(make_subtitle_items(self, cue, row))
452
434
  from .production_limits import limits_for
453
435
 
454
436
  if len(captions) > limits_for(self).titles:
@@ -550,7 +532,16 @@ class ProductionTools:
550
532
  return self._effect(
551
533
  args["item_id"],
552
534
  "video.grade",
553
- {k: args[k] for k in ("contrast", "saturation", "brightness")},
535
+ {
536
+ "contrast": args.get("contrast", 1),
537
+ "saturation": args.get("saturation", 1),
538
+ "brightness": args.get("brightness", 0),
539
+ **{
540
+ k: args[k]
541
+ for k in ("gamma", "temperature", "tint", "shadows", "highlights", "vignette", "grain")
542
+ if k in args and args[k] != (1 if k == "gamma" else 0)
543
+ },
544
+ },
554
545
  args["summary"],
555
546
  )
556
547
 
@@ -75,6 +75,9 @@ def make_subtitle_items(tools, cue, row):
75
75
  frame_rate = tools._timeline().frame_rate
76
76
  aligned = aligned_pages(original, text, excerpt, pages, frame_rate.numerator / frame_rate.denominator)
77
77
  pages = [(left, right) for left, right, _, _ in aligned]
78
+ from .caption_design import chosen_id
79
+
80
+ design = chosen_id(tools, row)
78
81
  styles = load_text_styles(tools.repository.projects, tools.project_id)
79
82
  items = []
80
83
  for n, (left, right) in enumerate(pages):
@@ -85,7 +88,7 @@ def make_subtitle_items(tools, cue, row):
85
88
  delivery = row.get("delivery", "dialogue")
86
89
  profile = {
87
90
  "kind": "program_subtitle",
88
- "font_size_ratio": 0.075 if delivery == "punchline" else 0.05 if delivery == "quiet" else 0.06,
91
+ "design": design,
89
92
  "delivery": delivery,
90
93
  "emphasis": [s for s in row.get("emphasis", []) if s in text[left:right]],
91
94
  "verification": cue.get("verification", "reviewed_source"),
@@ -102,7 +105,6 @@ def make_subtitle_items(tools, cue, row):
102
105
  if excerpt or len(pages) > 1
103
106
  else "asr_segment",
104
107
  "caption_text_edited": text != original["text"],
105
- "motion": "none" if delivery == "quiet" else "pop",
106
108
  }
107
109
  profile.update(
108
110
  {
@@ -111,17 +113,7 @@ def make_subtitle_items(tools, cue, row):
111
113
  if key in original
112
114
  }
113
115
  )
114
- skill = tools._skill_value()
115
- preset = skill["presets"]["subtitle"]
116
- profile.update(
117
- {
118
- "font_size_ratio": preset["font_size_ratio"]
119
- * (1.25 if delivery == "punchline" else 0.9 if delivery == "quiet" else 1),
120
- "emphasis_color": preset["emphasis_color"],
121
- "outline_color": preset["outline_color"],
122
- "skill_hash": skill["content_hash"],
123
- }
124
- )
116
+ profile["skill_hash"] = tools._skill_value()["content_hash"]
125
117
  identifier = "agent.text." + digest(profile)[:24]
126
118
  styles[identifier] = profile
127
119
  items.append(
@@ -16,7 +16,6 @@ import shutil
16
16
  import subprocess
17
17
  import tempfile
18
18
  import threading
19
- import time
20
19
  import xml.etree.ElementTree as ET
21
20
  from dataclasses import replace
22
21
  from datetime import datetime
@@ -511,7 +510,6 @@ def _write(repository, project_id, package, name, timeline, video, cancel):
511
510
  target = directory / f"{number:03d} {label}.png"
512
511
  shutil.move(str(image.path), target)
513
512
  rendered.append((item, target, label))
514
- editable = _editable_titles(directory, rendered, styles, timeline)
515
513
  still = build.format(timeline.width, timeline.height, None)
516
514
  for (item, target, label), lane in zip(
517
515
  rendered, _lanes([(i.start_frame, i.start_frame + i.duration_frames) for i, _, _ in rendered], 1, 1)
@@ -618,187 +616,19 @@ def _write(repository, project_id, package, name, timeline, video, cancel):
618
616
 
619
617
  fcpxml = package / f"{name}.fcpxml"
620
618
  build.write(fcpxml)
621
- _guide(package, fcpxml, bool(captions), editable, notes)
619
+ _guide(package, fcpxml, bool(captions), notes)
622
620
  return {
623
621
  "folder": str(package),
624
622
  "fcpxml": str(fcpxml),
625
623
  "shots": len(video.items),
626
624
  "burned": burned,
627
625
  "overlays": len(rendered),
628
- "editable_overlays": editable,
629
626
  "captions": len(captions),
630
627
  "music_layers": len(layers),
631
628
  "notes": notes,
632
629
  }
633
630
 
634
631
 
635
- def _editable_titles(directory: Path, rendered, styles, timeline) -> int:
636
- """Record each component's type beside its PNG so a .drt from Resolve can carry it as editable titles."""
637
- from clipen.rendering import program_creator
638
- from clipen.rendering.titles import TitleCardRenderer, TitleRenderError
639
-
640
- from .resolve_titles import MANIFEST
641
-
642
- font_path = TitleCardRenderer._font_path()
643
- manifest = {}
644
- for item, target, _ in rendered:
645
- profile = styles.get(item.style_id)
646
- # A graphic a person resized stays a picture: Resolve's titles would come back at the designed size.
647
- if (
648
- not profile
649
- or profile.get("kind") != "program_component"
650
- or not program_creator.is_creator(profile)
651
- or profile.get("scale", 1) != 1
652
- ):
653
- continue
654
- try:
655
- plan = program_creator.editable(font_path, timeline, item, profile)
656
- except TitleRenderError:
657
- plan = None
658
- if plan is None:
659
- continue
660
- picture = None
661
- if plan["picture"]:
662
- picture = f"{target.stem}(底圖).png"
663
- plan["picture"].save(directory / picture, "PNG", optimize=True)
664
- manifest[target.name] = {
665
- "rows": plan["rows"],
666
- "picture": picture,
667
- "width": timeline.width,
668
- "height": timeline.height,
669
- }
670
- if manifest:
671
- (directory / MANIFEST).write_text(json.dumps(manifest, ensure_ascii=False, indent=1), encoding="utf-8")
672
- return len(manifest)
673
-
674
-
675
- RESOLVE_DEFAULT_FOLDER = Path.home() / "Movies" / "DaVinci Resolve"
676
-
677
-
678
- def _timeline_folders(package: Path) -> list[Path]:
679
- """Where a .drt saved from this package's timeline may land: the package, Resolve's own folder,
680
- and, for a package in「Clipen 匯出」, that folder and the footage folder around it, since the
681
- save dialog often opens beside the footage the timeline was relinked to."""
682
- from clipen.media.discovery import EXPORT_FOLDER
683
-
684
- folders = [package, RESOLVE_DEFAULT_FOLDER]
685
- if package.parent.name == EXPORT_FOLDER:
686
- folders += [package.parent, package.parent.parent]
687
- return folders
688
-
689
-
690
- def _exported_timeline(package: Path, since: float = 0.0) -> Path | None:
691
- """The newest .drt saved from this package's timeline after since (a time stamp).
692
-
693
- A .drt counts when its clips point at this package's components, so other films' timelines
694
- in the same folders are passed over."""
695
- from .resolve_titles import uses
696
-
697
- # Skip dot files such as the「._」copies macOS leaves beside files on exFAT drives.
698
- candidates = [
699
- p
700
- for folder in _timeline_folders(package)
701
- for p in folder.glob("*.drt")
702
- if "(可改字)" not in p.stem and not p.name.startswith(".")
703
- ]
704
- candidates = [p for p in candidates if p.stat().st_mtime > since]
705
- return next(
706
- (p for p in sorted(candidates, key=lambda p: p.stat().st_mtime, reverse=True) if uses(p, package / "元件")),
707
- None,
708
- )
709
-
710
-
711
- def timeline_status(package: Path) -> dict:
712
- """Where Clipen looks for this package's .drt, the newest one it found, and the editable copy.
713
-
714
- state is waiting (nothing saved yet), found (a .drt is newer than any editable copy) or
715
- converted (the editable copy covers the newest save)."""
716
- package = Path(package)
717
- names = ["這份匯出的資料夾", "Resolve 預設的資料夾", "「Clipen 匯出」資料夾", "毛片資料夾"]
718
- folders = [{"label": label, "path": str(folder)} for label, folder in zip(names, _timeline_folders(package))]
719
- source = _exported_timeline(package)
720
- copies = sorted(
721
- (p for p in package.glob("*(可改字).drt") if not p.name.startswith(".")),
722
- key=lambda p: p.stat().st_mtime,
723
- reverse=True,
724
- )
725
- converted = copies[0] if copies else None
726
- if converted is not None and (source is None or converted.stat().st_mtime >= source.stat().st_mtime):
727
- state = "converted"
728
- else:
729
- state = "found" if source is not None else "waiting"
730
- return {
731
- "state": state,
732
- "folders": folders,
733
- "source": str(source) if source else None,
734
- "converted": str(converted) if converted else None,
735
- }
736
-
737
-
738
- def convert_timeline(package: Path, source: Path | None = None) -> tuple[Path, int]:
739
- """Write a copy of the .drt exported from this package's timeline with editable component titles."""
740
- from .resolve_titles import MANIFEST, convert
741
-
742
- package = Path(package)
743
- if not (package / "元件" / MANIFEST).is_file():
744
- raise ProjectError("resolve_titles_missing", "這份匯出沒有可以換成文字的元件。", status_code=409)
745
- source = source or _exported_timeline(package)
746
- if source is None:
747
- raise ProjectError(
748
- "resolve_timeline_missing",
749
- "還找不到這份匯出的 .drt。請先在 DaVinci Resolve 用「檔案 > 匯出 > 時間線…」把時間線存成 .drt。",
750
- status_code=409,
751
- )
752
- target = _unique(package, f"{source.stem}(可改字).drt")
753
- temporary = target.with_suffix(".partial")
754
- try:
755
- replaced = convert(source, temporary)
756
- if not replaced:
757
- raise ProjectError(
758
- "resolve_titles_unmatched",
759
- f"「{source.name}」裡找不到這份匯出的元件。請確認匯出的是從這個資料夾匯入的時間線。",
760
- status_code=409,
761
- )
762
- temporary.replace(target)
763
- finally:
764
- temporary.unlink(missing_ok=True)
765
- return target, replaced
766
-
767
-
768
- def watch_timeline(
769
- package: Path, since: float, stop: threading.Event | None = None, timeout: float = 4 * 3600, interval: float = 2.0
770
- ) -> Path | None:
771
- """Wait for the person to save this package's timeline as .drt in Resolve, then convert and show it.
772
-
773
- A save counts once its size holds still for one interval, so a half-written file is never read.
774
- Gives up after timeout or when stop is set; returns the converted timeline."""
775
- stop = stop or threading.Event()
776
- deadline, seen = time.monotonic() + timeout, None
777
- while not stop.wait(interval) and time.monotonic() < deadline:
778
- source = _exported_timeline(package, since)
779
- if source is None:
780
- continue
781
- size = source.stat().st_size
782
- if seen != (source, size):
783
- seen = (source, size)
784
- continue
785
- try:
786
- target, _ = convert_timeline(package, source)
787
- except ProjectError:
788
- return None
789
- reveal(target)
790
- return target
791
- return None
792
-
793
-
794
- def start_watching(package: Path) -> threading.Thread:
795
- """Watch for the .drt in the background so the person never has to come back to Clipen for it."""
796
- since = time.time()
797
- thread = threading.Thread(target=watch_timeline, args=(Path(package), since), name="resolve-titles", daemon=True)
798
- thread.start()
799
- return thread
800
-
801
-
802
632
  def reveal(path: Path) -> None:
803
633
  """Show the new timeline file in Finder; a missing Finder only skips this courtesy."""
804
634
  if os.uname().sysname == "Darwin":
@@ -807,7 +637,7 @@ def reveal(path: Path) -> None:
807
637
  )
808
638
 
809
639
 
810
- def _guide(package: Path, fcpxml: Path, captions: bool, editable: int, notes: list[str]):
640
+ def _guide(package: Path, fcpxml: Path, captions: bool, notes: list[str]):
811
641
  steps = [
812
642
  "在 DaVinci Resolve 匯入",
813
643
  "",
@@ -827,17 +657,6 @@ def _guide(package: Path, fcpxml: Path, captions: bool, editable: int, notes: li
827
657
  "影片片段直接指向原始素材,前後保留可延長的長度。若搬動了素材,Resolve 會請你重新連結。",
828
658
  "這個資料夾裡的元件、音樂和已處理片段也被時間線使用,請保持資料夾完整。",
829
659
  ]
830
- if editable:
831
- steps += [
832
- "",
833
- "想在 Resolve 改元件的字(需要時再做)",
834
- "",
835
- f"匯入後元件已經和 Clipen 一模一樣,只是以圖片呈現。要改其中的字,再做兩步,{editable} 個元件會一起換成可以改字的標題:",
836
- "1. 選「檔案 > 匯出 > 時間線…」(File > Export > Timeline),格式選「DaVinci Resolve Timeline Files (*.drt)」,按儲存。",
837
- " Clipen 開著的話會自動做好一份名稱有「(可改字)」的 .drt,並在 Finder 打開它;沒出現的話,到 Clipen 的「到 DaVinci Resolve 自己剪」按「把元件換成可改字的標題」。",
838
- "2. 選「檔案 > 匯入 > 時間線…」,選那份「(可改字)」的 .drt。選取元件後,在右邊「檢查器」改字。",
839
- " 改字只會改文字本身;底框、細線這類圖形是固定的圖片,字數差很多時可能要自己調整位置。",
840
- ]
841
660
  if notes:
842
661
  steps += ["", "需要留意", ""] + [f"・{note}" for note in notes]
843
662
  steps += [