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