@clipen/clipen-cli 0.0.0-stage → 1.0.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 (232) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -2
  3. package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
  4. package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
  5. package/apps/web/dist/favicon.svg +1 -0
  6. package/apps/web/dist/index.html +16 -0
  7. package/bin/clipen.js +157 -0
  8. package/clipen +18 -0
  9. package/install +25 -0
  10. package/package.json +55 -4
  11. package/pyproject.toml +44 -0
  12. package/requirements/asr-runtime.txt +13 -0
  13. package/requirements/dev.txt +2 -0
  14. package/requirements/runtime.txt +20 -0
  15. package/src/clipen/__init__.py +3 -0
  16. package/src/clipen/analysis/__init__.py +89 -0
  17. package/src/clipen/analysis/artifacts.py +410 -0
  18. package/src/clipen/analysis/audio.py +394 -0
  19. package/src/clipen/analysis/evidence.py +102 -0
  20. package/src/clipen/analysis/evidence_service.py +929 -0
  21. package/src/clipen/analysis/image_similarity.py +134 -0
  22. package/src/clipen/analysis/keyframes.py +159 -0
  23. package/src/clipen/analysis/models.py +228 -0
  24. package/src/clipen/analysis/qwen_worker.py +594 -0
  25. package/src/clipen/analysis/resources.py +22 -0
  26. package/src/clipen/analysis/runtime.py +62 -0
  27. package/src/clipen/analysis/service.py +594 -0
  28. package/src/clipen/analysis/setup.py +921 -0
  29. package/src/clipen/analysis/setup_cli.py +107 -0
  30. package/src/clipen/analysis/storage.py +1864 -0
  31. package/src/clipen/analysis/transcription.py +906 -0
  32. package/src/clipen/analysis/visual.py +237 -0
  33. package/src/clipen/annotations/__init__.py +13 -0
  34. package/src/clipen/annotations/models.py +22 -0
  35. package/src/clipen/annotations/storage.py +428 -0
  36. package/src/clipen/annotations/suggestions.py +115 -0
  37. package/src/clipen/asr_release.py +132 -0
  38. package/src/clipen/bootstrap.py +978 -0
  39. package/src/clipen/candidates.py +222 -0
  40. package/src/clipen/cli.py +84 -0
  41. package/src/clipen/controller/__init__.py +17 -0
  42. package/src/clipen/controller/app.py +1657 -0
  43. package/src/clipen/controller/server.py +533 -0
  44. package/src/clipen/domain/__init__.py +30 -0
  45. package/src/clipen/domain/errors.py +5 -0
  46. package/src/clipen/domain/media_time.py +110 -0
  47. package/src/clipen/domain/timeline.py +582 -0
  48. package/src/clipen/domain/validation.py +14 -0
  49. package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
  50. package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
  51. package/src/clipen/editing/README.md +115 -0
  52. package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
  53. package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
  54. package/src/clipen/editing/__init__.py +15 -0
  55. package/src/clipen/editing/agent.py +13 -0
  56. package/src/clipen/editing/agent_models.py +127 -0
  57. package/src/clipen/editing/agent_repository.py +978 -0
  58. package/src/clipen/editing/agent_tools.py +613 -0
  59. package/src/clipen/editing/alignment.py +150 -0
  60. package/src/clipen/editing/alignment_setup.py +156 -0
  61. package/src/clipen/editing/alignment_worker.py +24 -0
  62. package/src/clipen/editing/change_report.py +128 -0
  63. package/src/clipen/editing/compiler.py +40 -0
  64. package/src/clipen/editing/component_looks.py +131 -0
  65. package/src/clipen/editing/component_review.py +74 -0
  66. package/src/clipen/editing/coordinator.py +497 -0
  67. package/src/clipen/editing/editorial_review.py +309 -0
  68. package/src/clipen/editing/evidence_jobs.py +552 -0
  69. package/src/clipen/editing/history_changes.py +192 -0
  70. package/src/clipen/editing/music_choices.py +18 -0
  71. package/src/clipen/editing/production_catalog.py +629 -0
  72. package/src/clipen/editing/production_limits.py +85 -0
  73. package/src/clipen/editing/production_media.py +435 -0
  74. package/src/clipen/editing/production_preview.py +373 -0
  75. package/src/clipen/editing/production_progress.py +236 -0
  76. package/src/clipen/editing/production_requirements.py +117 -0
  77. package/src/clipen/editing/production_tools.py +1198 -0
  78. package/src/clipen/editing/program_audio.py +248 -0
  79. package/src/clipen/editing/program_direction.py +83 -0
  80. package/src/clipen/editing/program_story.py +91 -0
  81. package/src/clipen/editing/program_subtitles.py +232 -0
  82. package/src/clipen/editing/programme_review.py +121 -0
  83. package/src/clipen/editing/prompt_history.py +84 -0
  84. package/src/clipen/editing/recut.py +167 -0
  85. package/src/clipen/editing/refinement_references.py +278 -0
  86. package/src/clipen/editing/resolve_export.py +847 -0
  87. package/src/clipen/editing/resolve_titles.py +291 -0
  88. package/src/clipen/editing/skill_tools.py +951 -0
  89. package/src/clipen/editing/source_dialogue.py +192 -0
  90. package/src/clipen/editing/speech_coverage.py +50 -0
  91. package/src/clipen/editing/speech_quality.py +11 -0
  92. package/src/clipen/editing/tool_receipts.py +98 -0
  93. package/src/clipen/editing/versions.py +219 -0
  94. package/src/clipen/editing/visual_preview.py +189 -0
  95. package/src/clipen/editing/workbench.py +136 -0
  96. package/src/clipen/filesystem.py +25 -0
  97. package/src/clipen/finishing/README.md +103 -0
  98. package/src/clipen/finishing/__init__.py +1 -0
  99. package/src/clipen/finishing/audio.py +188 -0
  100. package/src/clipen/finishing/catalog.py +264 -0
  101. package/src/clipen/finishing/models.py +14 -0
  102. package/src/clipen/finishing/renderer.py +45 -0
  103. package/src/clipen/mcp_editing/__init__.py +5 -0
  104. package/src/clipen/mcp_editing/__main__.py +42 -0
  105. package/src/clipen/mcp_editing/server.py +396 -0
  106. package/src/clipen/media/__init__.py +50 -0
  107. package/src/clipen/media/discovery.py +253 -0
  108. package/src/clipen/media/models.py +349 -0
  109. package/src/clipen/media/preview.py +137 -0
  110. package/src/clipen/media/probe.py +418 -0
  111. package/src/clipen/media/service.py +304 -0
  112. package/src/clipen/media/storage.py +694 -0
  113. package/src/clipen/music_vocabulary.py +34 -0
  114. package/src/clipen/power.py +28 -0
  115. package/src/clipen/projects/__init__.py +26 -0
  116. package/src/clipen/projects/agent_schema.py +94 -0
  117. package/src/clipen/projects/annotation_schema.py +40 -0
  118. package/src/clipen/projects/deletion.py +256 -0
  119. package/src/clipen/projects/evidence_schema.py +52 -0
  120. package/src/clipen/projects/finishing_schema.py +36 -0
  121. package/src/clipen/projects/models.py +189 -0
  122. package/src/clipen/projects/picker.py +232 -0
  123. package/src/clipen/projects/preview_schema.py +29 -0
  124. package/src/clipen/projects/service.py +159 -0
  125. package/src/clipen/projects/storage.py +1458 -0
  126. package/src/clipen/projects/timeline_schema.py +32 -0
  127. package/src/clipen/projects/validation_schema.py +28 -0
  128. package/src/clipen/provider_registry.py +77 -0
  129. package/src/clipen/providers/__init__.py +43 -0
  130. package/src/clipen/providers/account.py +245 -0
  131. package/src/clipen/providers/claude.py +409 -0
  132. package/src/clipen/providers/claude_editing.py +118 -0
  133. package/src/clipen/providers/codex.py +991 -0
  134. package/src/clipen/providers/codex_editing.py +91 -0
  135. package/src/clipen/providers/editing_agent.py +567 -0
  136. package/src/clipen/providers/errors.py +51 -0
  137. package/src/clipen/providers/recovery.py +269 -0
  138. package/src/clipen/py.typed +1 -0
  139. package/src/clipen/rendering/__init__.py +12 -0
  140. package/src/clipen/rendering/cover.py +139 -0
  141. package/src/clipen/rendering/custom_components.py +328 -0
  142. package/src/clipen/rendering/custom_render.py +218 -0
  143. package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
  144. package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
  145. package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
  146. package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
  147. package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
  148. package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
  149. package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
  150. package/src/clipen/rendering/fonts/manifest.json +145 -0
  151. package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
  152. package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
  153. package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
  154. package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
  155. package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
  156. package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
  157. package/src/clipen/rendering/production_effects.py +96 -0
  158. package/src/clipen/rendering/program_components.py +254 -0
  159. package/src/clipen/rendering/program_creator.py +804 -0
  160. package/src/clipen/rendering/program_identities.py +350 -0
  161. package/src/clipen/rendering/program_motion.py +186 -0
  162. package/src/clipen/rendering/program_studio.py +227 -0
  163. package/src/clipen/rendering/program_styles.py +321 -0
  164. package/src/clipen/rendering/program_subtitles.py +89 -0
  165. package/src/clipen/rendering/renderer.py +737 -0
  166. package/src/clipen/rendering/storage.py +230 -0
  167. package/src/clipen/rendering/titles.py +467 -0
  168. package/src/clipen/skills/__init__.py +5 -0
  169. package/src/clipen/skills/builtin/SKILL.md +72 -0
  170. package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
  171. package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
  172. package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
  173. package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
  174. package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
  175. package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
  176. package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
  177. package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
  178. package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
  179. package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
  180. package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
  181. package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
  182. package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
  183. package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
  184. package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
  185. package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
  186. package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
  187. package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
  188. package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
  189. package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
  190. package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
  191. package/src/clipen/skills/builtin/components.json +133 -0
  192. package/src/clipen/skills/builtin/font_sources.json +20 -0
  193. package/src/clipen/skills/builtin/font_styles.json +329 -0
  194. package/src/clipen/skills/builtin/manifest.json +32 -0
  195. package/src/clipen/skills/builtin/presets.json +8 -0
  196. package/src/clipen/skills/builtin/references/captions.md +14 -0
  197. package/src/clipen/skills/builtin/references/channel-design.md +37 -0
  198. package/src/clipen/skills/builtin/references/editing.md +30 -0
  199. package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
  200. package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
  201. package/src/clipen/skills/builtin/references/graphics.md +59 -0
  202. package/src/clipen/skills/builtin/references/review.md +16 -0
  203. package/src/clipen/skills/builtin/references/sound.md +8 -0
  204. package/src/clipen/skills/builtin/references/story.md +7 -0
  205. package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
  206. package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
  207. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
  208. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
  209. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
  210. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
  211. package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
  212. package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
  213. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
  214. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
  215. package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
  216. package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
  217. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
  218. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
  219. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
  220. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
  221. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
  222. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
  223. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
  224. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
  225. package/src/clipen/skills/builtin/templates.json +284 -0
  226. package/src/clipen/skills/builtin/visual_styles.json +1074 -0
  227. package/src/clipen/skills/catalog.py +314 -0
  228. package/src/clipen/skills/library.py +137 -0
  229. package/src/clipen/skills/package.py +254 -0
  230. package/src/clipen/skills/visual_styles.py +55 -0
  231. package/src/clipen/workspace.py +181 -0
  232. package/uninstall +25 -0
@@ -0,0 +1,291 @@
1
+ """Turn Clipen's components into DaVinci Resolve titles whose words stay editable.
2
+
3
+ Resolve keeps Fusion titles only in its own timeline format (.drt), which it
4
+ writes but never reads from FCPXML. So the hand-off goes through Resolve: the
5
+ FCPXML places each component as a transparent PNG, the person exports that
6
+ timeline from Resolve as .drt, and convert() swaps every component PNG on it
7
+ for a Fusion title. The title draws the component's rows with Text+ (font,
8
+ size, tracking, colour and shadow as Clipen set them) over a picture of
9
+ everything else (boxes, rules, icons), and publishes each row's words to the
10
+ Edit page Inspector.
11
+
12
+ A .drt is a zip of XML. A clip's Fusion composition is a qCompress'd Qt
13
+ QVariantMap whose "0_data" is the composition header, a NUL, a little-endian
14
+ length and the zlib'd tool list; DaVinci Resolve 21 writes and reads that.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import html
20
+ import json
21
+ import re
22
+ import struct
23
+ import unicodedata
24
+ import uuid
25
+ import zipfile
26
+ import zlib
27
+ from pathlib import Path
28
+
29
+ from clipen.projects import ProjectError
30
+
31
+ MANIFEST = ".clipen 元件.json"
32
+ # Text+ Size is a fraction of the frame width, and a glyph's em is 1/1.76 of it; Text+ tracking adds
33
+ # (CharacterSpacing - 1) x Size x width between letters. Measured in Resolve 21 on PingFang TC and Songti TC.
34
+ _SIZE = 1.76
35
+ _ITEM = re.compile(r'<Sm2TiVideoClip DbId="[^"]+">.*?</Sm2TiVideoClip>', re.S)
36
+
37
+
38
+ def _lua(value: str) -> str:
39
+ return '"' + value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"'
40
+
41
+
42
+ def _number(value: float) -> str:
43
+ return f"{value:.6g}"
44
+
45
+
46
+ def tools(rows: list[dict], picture: Path | None, width: int, height: int, frames: int) -> str:
47
+ """The Fusion tool list for one component: rows of Text+ merged over its picture."""
48
+ last = frames - 1
49
+ frame = f"GlobalOut = Input {{ Value = {last}, }}, Width = Input {{ Value = {width}, }}, Height = Input {{ Value = {height}, }}, UseFrameFormatSettings = Input {{ Value = 1, }}, "
50
+ nodes, inputs = [], []
51
+ if picture:
52
+ nodes.append(
53
+ f'Picture = Loader {{ Clips = {{ Clip {{ ID = "Clip1", Filename = {_lua(str(picture))}, FormatID = "PNGFormat", '
54
+ f"StartFrame = -1, LengthSetManually = true, TrimIn = 0, TrimOut = 0, ExtendFirst = 0, ExtendLast = {last}, "
55
+ f"Loop = 0, AspectMode = 0, Depth = 0, TimeCode = 0, GlobalStart = 0, GlobalEnd = {last} }} }}, "
56
+ "ViewInfo = OperatorInfo { Pos = { 0, 0 } }, }"
57
+ )
58
+ # Each row merges over what lies below it: the picture, or the first row when there is none.
59
+ below = "Picture" if picture else None
60
+ for number, row in enumerate(rows, 1):
61
+ name, label = f"Row{number}", "" if len(rows) == 1 else f"第 {number} 行"
62
+ red, green, blue, alpha = (v / 255 for v in row["fill"])
63
+ shading = ""
64
+ if row["shadow"]:
65
+ sr, sg, sb, sa = (v / 255 for v in row["shadow"]["colour"])
66
+ offset = row["shadow"]["offset"]
67
+ shading = (
68
+ f'Enabled2 = Input {{ Value = 1, }}, Name2 = Input {{ Value = "Shadow", }}, ElementShape2 = Input {{ Value = 0, }}, '
69
+ f"Red2 = Input {{ Value = {_number(sr)}, }}, Green2 = Input {{ Value = {_number(sg)}, }}, Blue2 = Input {{ Value = {_number(sb)}, }}, "
70
+ f"Alpha2 = Input {{ Value = {_number(sa)}, }}, Offset2 = Input {{ Value = {{ {_number(offset / width)}, {_number(-offset / height)} }}, }}, "
71
+ f"Softness2 = Input {{ Value = 1, }}, SoftnessX2 = Input {{ Value = {row['shadow']['blur']}, }}, SoftnessY2 = Input {{ Value = {row['shadow']['blur']}, }}, "
72
+ )
73
+ nodes.append(
74
+ f"{name} = TextPlus {{ Inputs = {{ {frame}"
75
+ f"Center = Input {{ Value = {{ {_number(row['x'] / width)}, {_number(1 - row['baseline'] / height)} }}, }}, "
76
+ "CenterOnBaseOfFirstLine = Input { Value = 1, }, HorizontalLeftCenterRight = Input { Value = -1, }, "
77
+ "VerticalJustificationNew = Input { Value = 3, }, HorizontalJustificationNew = Input { Value = 3, }, "
78
+ f"StyledText = Input {{ Value = {_lua(row['text'])}, }}, Font = Input {{ Value = {_lua(row['family'])}, }}, "
79
+ f"Style = Input {{ Value = {_lua(row['style'])}, }}, Size = Input {{ Value = {_number(row['size'] * _SIZE / width)}, }}, "
80
+ f"CharacterSpacing = Input {{ Value = {_number(1 + row['track'] / _SIZE)}, }}, "
81
+ f"Red1 = Input {{ Value = {_number(red)}, }}, Green1 = Input {{ Value = {_number(green)}, }}, Blue1 = Input {{ Value = {_number(blue)}, }}, "
82
+ f"Alpha1 = Input {{ Value = {_number(alpha)}, }}, {shading}}}, ViewInfo = OperatorInfo {{ Pos = {{ 110, {60 * number} }} }}, }}"
83
+ )
84
+ if below:
85
+ nodes.append(
86
+ f'Merge{number} = Merge {{ Inputs = {{ Background = Input {{ SourceOp = "{below}", Source = "Output", }}, '
87
+ f'Foreground = Input {{ SourceOp = "{name}", Source = "Output", }}, PerformDepthMerge = Input {{ Value = 0, }}, }}, '
88
+ f"ViewInfo = OperatorInfo {{ Pos = {{ 220, {60 * number} }} }}, }}"
89
+ )
90
+ below = f"Merge{number}" if below else name
91
+ group = 10 * number
92
+ inputs += [
93
+ f'{name}Text = InstanceInput {{ SourceOp = "{name}", Source = "StyledText", Name = {_lua((label + " 文字").strip())}, }}',
94
+ f'{name}Font = InstanceInput {{ SourceOp = "{name}", Source = "Font", Name = {_lua((label + " 字型").strip())}, ControlGroup = {group}, }}',
95
+ f'{name}Style = InstanceInput {{ SourceOp = "{name}", Source = "Style", ControlGroup = {group}, }}',
96
+ f'{name}Size = InstanceInput {{ SourceOp = "{name}", Source = "Size", Name = {_lua((label + " 大小").strip())}, }}',
97
+ f'{name}Red = InstanceInput {{ SourceOp = "{name}", Source = "Red1Clone", Name = {_lua((label + " 顏色").strip())}, ControlGroup = {group + 1}, }}',
98
+ f'{name}Green = InstanceInput {{ SourceOp = "{name}", Source = "Green1Clone", ControlGroup = {group + 1}, }}',
99
+ f'{name}Blue = InstanceInput {{ SourceOp = "{name}", Source = "Blue1Clone", ControlGroup = {group + 1}, }}',
100
+ f'{name}Alpha = InstanceInput {{ SourceOp = "{name}", Source = "Alpha1Clone", ControlGroup = {group + 1}, }}',
101
+ ]
102
+ # Resolve shows a Text+ title's controls from a tool called Template, and MediaOut reads the tool inside the group.
103
+ return (
104
+ "{ Template = GroupOperator { CtrlWZoom = false, Inputs = ordered() { " + ", ".join(inputs) + " }, "
105
+ f'Outputs = {{ MainOutput1 = InstanceOutput {{ SourceOp = "{below}", Source = "Output", }} }}, '
106
+ "ViewInfo = GroupInfo { Pos = { 0, 0 } }, Tools = ordered() { " + ", ".join(nodes) + " }, }, "
107
+ f'MediaOut1 = MediaOut {{ Inputs = {{ Index = Input {{ Value = "0", }}, Input = Input {{ SourceOp = "{below}", Source = "Output", }} }}, '
108
+ "ViewInfo = OperatorInfo { Pos = { 330, 0 } }, } }"
109
+ )
110
+
111
+
112
+ def _qstring(value: str) -> bytes:
113
+ data = value.encode("utf-16-be")
114
+ return struct.pack(">I", len(data)) + data
115
+
116
+
117
+ def composition(tool_list: str, width: int, height: int, frames: int) -> str:
118
+ """A clip's CompositionBA: the tool list wrapped the way Resolve stores a Text+ title's comp."""
119
+ last = frames - 1
120
+ header = (
121
+ f"Composition {{ CurrentTime = 0, RenderRange = {{ 0, {last} }}, GlobalRange = {{ 0, {last} }}, CurrentID = 1, HiQ = true, "
122
+ 'PlaybackUpdateMode = 0, StereoMode = false, Version = "DaVinci Resolve 21.1.2.0010", SavedOutputs = 1, HeldTools = 0, '
123
+ 'DisabledTools = 0, LockedTools = 0, AudioOffset = 0, Resumable = true, OutputClips = { }, CustomData = { TEMPLATE_ID = "Text+" }, '
124
+ f"Prefs = {{ Comp = {{ FrameFormat = {{ Width = {width}, Height = {height}, GuideRatio = {_number(width / height)}, "
125
+ f"DepthFull = 3, DepthPreview = 3, DepthInteractive = 3, }}, Unsorted = {{ GlobalEnd = {last} }}, }} }}, Compressed = true, }}"
126
+ )
127
+ inner = tool_list.encode("utf-8")
128
+ data = header.encode("utf-8") + b"\x00" + struct.pack("<I", len(inner)) + zlib.compress(inner, 9)
129
+ variant = struct.pack(">II", 1, 4)
130
+ variant += _qstring("count") + struct.pack(">IBi", 2, 0, 1)
131
+ variant += _qstring("0_name") + struct.pack(">IB", 10, 0) + _qstring("Composition 1")
132
+ variant += _qstring("0_mediaIdList") + struct.pack(">IBI", 11, 0, 0)
133
+ variant += _qstring("0_data") + struct.pack(">IBI", 12, 0, len(data)) + data
134
+ return (struct.pack(">I", len(variant)) + zlib.compress(variant, 9)).hex()
135
+
136
+
137
+ def _varint(value: int) -> bytes:
138
+ out = bytearray()
139
+ while True:
140
+ byte, value = value & 0x7F, value >> 7
141
+ out.append(byte | (0x80 if value else 0))
142
+ if not value:
143
+ return bytes(out)
144
+
145
+
146
+ def _fields(start: int) -> str:
147
+ """A Text+ Fusion Title clip's FieldsBlob: its template name and the frame it starts on."""
148
+ name = b"Text+"
149
+ title = b"\x22" + bytes([len(name)]) + name + b"\x4a" + bytes([len(name)]) + name + b"\xa8\x01" + _varint(start)
150
+ clip = b"\x0a" + _varint(len(title)) + title + b"\x20\x01"
151
+ body = b"\x0a" + _varint(len(clip)) + clip + b"\x12\x10" + bytes.fromhex("0000000000000006ffffffffffffffff")
152
+ return (struct.pack(">II", 2, len(body) + 1) + b"\x80" + body).hex()
153
+
154
+
155
+ def title_item(start: int, duration: int, frame_rate: str, comp: str, indent: str) -> str:
156
+ """A Fusion Title clip in a .drt sequence, shaped like the ones Resolve 21 writes."""
157
+ lines = [
158
+ f'<Sm2TiVideoClip DbId="{uuid.uuid4()}">',
159
+ f" <FieldsBlob>{_fields(start)}</FieldsBlob>",
160
+ " <PrettyType>Fusion Title</PrettyType>",
161
+ " <Name>Fusion Title</Name>",
162
+ f" <Start>{start}</Start>",
163
+ f" <Duration>{duration}</Duration>",
164
+ " <LinkedItemSync/>",
165
+ " <WasDisbanded>false</WasDisbanded>",
166
+ " <MarkersBA/>",
167
+ " <UiMemento>0</UiMemento>",
168
+ " <Flags>0</Flags>",
169
+ " <PriorityIndex>0</PriorityIndex>",
170
+ " <EffectFiltersBA/>",
171
+ " <ImportExportMetadataBA/>",
172
+ " <RenderTextEnabled>true</RenderTextEnabled>",
173
+ " <RenderTextGanged>true</RenderTextGanged>",
174
+ " <RenderTextPrefixed>true</RenderTextPrefixed>",
175
+ " <CompositionTable>",
176
+ f' <Sm2TiCompositionTable DbId="{uuid.uuid4()}">',
177
+ " <FieldsBlob>000000010000000200000016004c006100730074004d006f006400540069006d0065000000040000000000b5a8a2230000002c00460075007300"
178
+ "69006f006e00530074006100720074004600720061006d0065004f00660066007300650074000000020000000000</FieldsBlob>",
179
+ " <DbSavedTime>0</DbSavedTime>",
180
+ f" <CompositionBA>{comp}</CompositionBA>",
181
+ " <ActiveCompositionIdx>0</ActiveCompositionIdx>",
182
+ " </Sm2TiCompositionTable>",
183
+ " </CompositionTable>",
184
+ " <In/>",
185
+ " <MixedFrameRateAlignment>0</MixedFrameRateAlignment>",
186
+ " <MediaStartTime>0</MediaStartTime>",
187
+ " <MediaFilePath/>",
188
+ " <MediaReelNumber/>",
189
+ f" <MediaFrameRate>{frame_rate}</MediaFrameRate>",
190
+ " <MediaTimemapBA>024013ddddddddddde</MediaTimemapBA>",
191
+ " <LastChangedTime>0</LastChangedTime>",
192
+ " <LastRenderedTime>0</LastRenderedTime>",
193
+ " <IsMarkedForCaching>false</IsMarkedForCaching>",
194
+ " <IsForceConformed>true</IsForceConformed>",
195
+ " <MatchConflictState>0</MatchConflictState>",
196
+ " <UseOppositeSrcForLeftEye>false</UseOppositeSrcForLeftEye>",
197
+ " <UseOppositeSrcForRightEye>false</UseOppositeSrcForRightEye>",
198
+ " <RenderCacheBA/>",
199
+ " <CurrentSelectorIdx>1</CurrentSelectorIdx>",
200
+ " <IsPreConformed>false</IsPreConformed>",
201
+ " <PreConformMediaExtents>00000100000030c20000010000003042</PreConformMediaExtents>",
202
+ " <MediaMetadata/>",
203
+ " <Thumbnail>",
204
+ f' <BtThumnail DbId="{uuid.uuid4()}">',
205
+ " <FieldsBlob/>",
206
+ " <ImgWidth>-1</ImgWidth>",
207
+ " <ImgHeight>-1</ImgHeight>",
208
+ " <Buffer/>",
209
+ " </BtThumnail>",
210
+ " </Thumbnail>",
211
+ " <ThumbnailDirtyFlag>true</ThumbnailDirtyFlag>",
212
+ "</Sm2TiVideoClip>",
213
+ ]
214
+ return ("\n" + indent).join(lines)
215
+
216
+
217
+ def _tag(item: str, name: str) -> str | None:
218
+ found = re.search(f"<{name}>([^<]*)</{name}>", item)
219
+ return html.unescape(found.group(1)) if found else None
220
+
221
+
222
+ def _sequences(archive: zipfile.ZipFile):
223
+ return [
224
+ info
225
+ for info in archive.infolist()
226
+ if info.filename.startswith("SeqContainer/") and info.filename.endswith(".xml")
227
+ ]
228
+
229
+
230
+ def uses(source: Path, components: Path) -> bool:
231
+ """Whether a .drt has clips that point at the component PNGs in components."""
232
+ marker = "<MediaFilePath>" + unicodedata.normalize("NFC", html.escape(str(components), quote=False)) + "/"
233
+ try:
234
+ with zipfile.ZipFile(source) as archive:
235
+ return any(
236
+ marker in unicodedata.normalize("NFC", archive.read(info).decode("utf-8", "replace"))
237
+ for info in _sequences(archive)
238
+ )
239
+ except (OSError, zipfile.BadZipFile):
240
+ return False
241
+
242
+
243
+ def convert(source: Path, target: Path) -> int:
244
+ """Write target: the Resolve timeline at source with every Clipen component PNG made a Fusion title.
245
+
246
+ The components' type lives in the manifest beside their PNGs, found through each clip's file
247
+ path. Returns how many clips were replaced."""
248
+ manifests: dict[Path, dict] = {}
249
+
250
+ def entry(path: Path):
251
+ folder = path.parent
252
+ if folder not in manifests:
253
+ try:
254
+ manifests[folder] = json.loads((folder / MANIFEST).read_text(encoding="utf-8"))
255
+ except (OSError, ValueError):
256
+ manifests[folder] = {}
257
+ return manifests[folder].get(path.name)
258
+
259
+ replaced = 0
260
+
261
+ def swap(match: re.Match) -> str:
262
+ nonlocal replaced
263
+ item = match.group(0)
264
+ path = _tag(item, "MediaFilePath")
265
+ component = entry(Path(path)) if path else None
266
+ if not component:
267
+ return item
268
+ start, duration = int(_tag(item, "Start")), int(_tag(item, "Duration"))
269
+ picture = Path(path).parent / component["picture"] if component["picture"] else None
270
+ width, height = component["width"], component["height"]
271
+ comp = composition(tools(component["rows"], picture, width, height, duration), width, height, duration)
272
+ indent = match.string[match.string.rfind("\n", 0, match.start()) + 1 : match.start()]
273
+ replaced += 1
274
+ return title_item(
275
+ start, duration, _tag(item, "MediaFrameRate") or "0000000000003e400000000000000000", comp, indent
276
+ )
277
+
278
+ try:
279
+ archive = zipfile.ZipFile(source)
280
+ except (OSError, zipfile.BadZipFile) as error:
281
+ raise ProjectError(
282
+ "resolve_timeline_unreadable", "這個檔案不是 DaVinci Resolve 匯出的 .drt 時間線。", status_code=409
283
+ ) from error
284
+ with archive, zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as out:
285
+ sequences = {info.filename for info in _sequences(archive)}
286
+ for info in archive.infolist():
287
+ data = archive.read(info)
288
+ if info.filename in sequences:
289
+ data = _ITEM.sub(swap, data.decode("utf-8")).encode("utf-8")
290
+ out.writestr(info, data)
291
+ return replaced