@clipen/clipen-cli 1.0.0 → 1.0.2

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 (132) hide show
  1. package/README.md +56 -48
  2. package/apps/web/dist/assets/{index-D5D2HiB1.js → index-DPHwA954.js} +1 -1
  3. package/apps/web/dist/index.html +1 -1
  4. package/bin/clipen.js +1 -1
  5. package/package.json +7 -6
  6. package/pyproject.toml +18 -2
  7. package/requirements/dev.txt +2 -0
  8. package/src/clipen/__init__.py +1 -1
  9. package/src/clipen/analysis/__init__.py +7 -7
  10. package/src/clipen/analysis/artifacts.py +4 -10
  11. package/src/clipen/analysis/audio.py +10 -8
  12. package/src/clipen/analysis/evidence_service.py +345 -167
  13. package/src/clipen/analysis/image_similarity.py +5 -14
  14. package/src/clipen/analysis/keyframes.py +5 -17
  15. package/src/clipen/analysis/models.py +5 -7
  16. package/src/clipen/analysis/qwen_worker.py +19 -54
  17. package/src/clipen/analysis/resources.py +2 -1
  18. package/src/clipen/analysis/runtime.py +1 -3
  19. package/src/clipen/analysis/service.py +16 -48
  20. package/src/clipen/analysis/setup.py +11 -25
  21. package/src/clipen/analysis/setup_cli.py +5 -15
  22. package/src/clipen/analysis/storage.py +96 -278
  23. package/src/clipen/analysis/transcription.py +40 -82
  24. package/src/clipen/analysis/visual.py +109 -48
  25. package/src/clipen/annotations/__init__.py +5 -2
  26. package/src/clipen/annotations/models.py +1 -1
  27. package/src/clipen/annotations/storage.py +132 -84
  28. package/src/clipen/annotations/suggestions.py +3 -8
  29. package/src/clipen/asr_release.py +4 -11
  30. package/src/clipen/bootstrap.py +71 -61
  31. package/src/clipen/{planning/models.py → candidates.py} +29 -47
  32. package/src/clipen/cli.py +4 -9
  33. package/src/clipen/controller/app.py +401 -214
  34. package/src/clipen/controller/server.py +28 -38
  35. package/src/clipen/domain/__init__.py +1 -1
  36. package/src/clipen/domain/media_time.py +3 -10
  37. package/src/clipen/domain/timeline.py +45 -47
  38. package/src/clipen/domain/validation.py +0 -1
  39. package/src/clipen/editing/__init__.py +1 -1
  40. package/src/clipen/editing/agent_models.py +4 -11
  41. package/src/clipen/editing/agent_repository.py +393 -172
  42. package/src/clipen/editing/agent_tools.py +180 -99
  43. package/src/clipen/editing/alignment.py +92 -52
  44. package/src/clipen/editing/alignment_setup.py +118 -70
  45. package/src/clipen/editing/alignment_worker.py +11 -9
  46. package/src/clipen/editing/change_report.py +95 -38
  47. package/src/clipen/editing/compiler.py +0 -1
  48. package/src/clipen/editing/component_looks.py +58 -34
  49. package/src/clipen/editing/component_review.py +34 -38
  50. package/src/clipen/editing/coordinator.py +213 -92
  51. package/src/clipen/editing/editorial_review.py +217 -95
  52. package/src/clipen/editing/evidence_jobs.py +457 -200
  53. package/src/clipen/editing/history_changes.py +129 -68
  54. package/src/clipen/editing/music_choices.py +8 -5
  55. package/src/clipen/editing/production_catalog.py +573 -136
  56. package/src/clipen/editing/production_limits.py +43 -17
  57. package/src/clipen/editing/production_media.py +376 -167
  58. package/src/clipen/editing/production_preview.py +322 -129
  59. package/src/clipen/editing/production_progress.py +164 -69
  60. package/src/clipen/editing/production_requirements.py +106 -39
  61. package/src/clipen/editing/production_tools.py +1064 -462
  62. package/src/clipen/editing/program_audio.py +211 -81
  63. package/src/clipen/editing/program_direction.py +59 -25
  64. package/src/clipen/editing/program_story.py +83 -45
  65. package/src/clipen/editing/program_subtitles.py +194 -96
  66. package/src/clipen/editing/programme_review.py +98 -50
  67. package/src/clipen/editing/prompt_history.py +64 -27
  68. package/src/clipen/editing/recut.py +65 -25
  69. package/src/clipen/editing/refinement_references.py +176 -86
  70. package/src/clipen/editing/resolve_export.py +449 -218
  71. package/src/clipen/editing/resolve_titles.py +162 -105
  72. package/src/clipen/editing/skill_tools.py +530 -154
  73. package/src/clipen/editing/source_dialogue.py +177 -67
  74. package/src/clipen/editing/speech_coverage.py +42 -22
  75. package/src/clipen/editing/speech_quality.py +6 -1
  76. package/src/clipen/editing/tool_receipts.py +78 -32
  77. package/src/clipen/editing/versions.py +122 -64
  78. package/src/clipen/editing/visual_preview.py +157 -61
  79. package/src/clipen/editing/workbench.py +104 -42
  80. package/src/clipen/finishing/audio.py +69 -30
  81. package/src/clipen/finishing/catalog.py +176 -93
  82. package/src/clipen/finishing/models.py +1 -1
  83. package/src/clipen/finishing/renderer.py +33 -14
  84. package/src/clipen/mcp_editing/__main__.py +3 -1
  85. package/src/clipen/mcp_editing/server.py +77 -34
  86. package/src/clipen/media/__init__.py +3 -3
  87. package/src/clipen/media/discovery.py +7 -20
  88. package/src/clipen/media/models.py +7 -18
  89. package/src/clipen/media/preview.py +14 -24
  90. package/src/clipen/media/probe.py +16 -44
  91. package/src/clipen/media/service.py +6 -19
  92. package/src/clipen/media/storage.py +33 -81
  93. package/src/clipen/music_vocabulary.py +33 -4
  94. package/src/clipen/power.py +8 -3
  95. package/src/clipen/projects/__init__.py +1 -1
  96. package/src/clipen/projects/deletion.py +19 -32
  97. package/src/clipen/projects/finishing_schema.py +3 -1
  98. package/src/clipen/projects/models.py +2 -5
  99. package/src/clipen/projects/picker.py +13 -37
  100. package/src/clipen/projects/service.py +8 -24
  101. package/src/clipen/projects/storage.py +226 -246
  102. package/src/clipen/provider_registry.py +9 -20
  103. package/src/clipen/providers/account.py +86 -35
  104. package/src/clipen/providers/claude.py +59 -25
  105. package/src/clipen/providers/claude_editing.py +14 -7
  106. package/src/clipen/providers/codex.py +73 -118
  107. package/src/clipen/providers/codex_editing.py +2 -2
  108. package/src/clipen/providers/editing_agent.py +19 -17
  109. package/src/clipen/providers/recovery.py +7 -8
  110. package/src/clipen/rendering/cover.py +18 -5
  111. package/src/clipen/rendering/custom_components.py +167 -79
  112. package/src/clipen/rendering/custom_render.py +62 -41
  113. package/src/clipen/rendering/production_effects.py +77 -45
  114. package/src/clipen/rendering/program_components.py +134 -73
  115. package/src/clipen/rendering/program_creator.py +432 -277
  116. package/src/clipen/rendering/program_identities.py +277 -182
  117. package/src/clipen/rendering/program_motion.py +140 -95
  118. package/src/clipen/rendering/program_studio.py +175 -116
  119. package/src/clipen/rendering/program_styles.py +231 -145
  120. package/src/clipen/rendering/program_subtitles.py +71 -34
  121. package/src/clipen/rendering/renderer.py +150 -121
  122. package/src/clipen/rendering/storage.py +9 -22
  123. package/src/clipen/rendering/titles.py +193 -86
  124. package/src/clipen/skills/__init__.py +1 -0
  125. package/src/clipen/skills/catalog.py +151 -55
  126. package/src/clipen/skills/library.py +13 -7
  127. package/src/clipen/skills/package.py +46 -23
  128. package/src/clipen/skills/visual_styles.py +29 -18
  129. package/src/clipen/workspace.py +15 -44
  130. package/install +0 -25
  131. package/src/clipen/planning/__init__.py +0 -9
  132. package/uninstall +0 -25
@@ -6,14 +6,11 @@ Shots whose look cannot be rebuilt from the original footage (mosaic, speed
6
6
  ramps) are rendered to ProRes first so nothing hidden by a mosaic is revealed.
7
7
  Everything Resolve cannot take from FCPXML is left as a marker and in 說明.txt.
8
8
  """
9
+
9
10
  from __future__ import annotations
10
11
 
11
- from dataclasses import replace
12
- from datetime import datetime
13
- from fractions import Fraction
14
12
  import json
15
13
  import os
16
- from pathlib import Path
17
14
  import re
18
15
  import shutil
19
16
  import subprocess
@@ -21,32 +18,36 @@ import tempfile
21
18
  import threading
22
19
  import time
23
20
  import xml.etree.ElementTree as ET
21
+ from dataclasses import replace
22
+ from datetime import datetime
23
+ from fractions import Fraction
24
+ from pathlib import Path
24
25
 
25
26
  from clipen.domain import MediaClip, Track, TrackKind
26
27
  from clipen.projects import ProjectError
27
28
 
28
29
  # Effects that change which pixels or frames appear, so the shot is rendered as is.
29
- BURNED = frozenset({'video.mosaic', 'video.speed_ramp'})
30
- _FRAMING = frozenset({'video.punch_in', 'video.reframe', 'video.slow_push'})
31
- _UNSAFE_NAME = re.compile(r'[\x00-\x1f/:\\]+')
30
+ BURNED = frozenset({"video.mosaic", "video.speed_ramp"})
31
+ _FRAMING = frozenset({"video.punch_in", "video.reframe", "video.slow_push"})
32
+ _UNSAFE_NAME = re.compile(r"[\x00-\x1f/:\\]+")
32
33
 
33
34
 
34
35
  def seconds(value: Fraction) -> str:
35
36
  """An exact FCPXML time value."""
36
37
  if value == 0:
37
- return '0s'
38
- return f'{value.numerator}s' if value.denominator == 1 else f'{value.numerator}/{value.denominator}s'
38
+ return "0s"
39
+ return f"{value.numerator}s" if value.denominator == 1 else f"{value.numerator}/{value.denominator}s"
39
40
 
40
41
 
41
42
  def timecode_seconds(timecode: str, rate: Fraction) -> Fraction:
42
43
  """Seconds from a file's start timecode, so Resolve and the FCPXML agree on source time."""
43
- match = re.fullmatch(r'(\d{1,2}):(\d{2}):(\d{2})([:;.])(\d{2,3})', timecode.strip())
44
+ match = re.fullmatch(r"(\d{1,2}):(\d{2}):(\d{2})([:;.])(\d{2,3})", timecode.strip())
44
45
  if not match:
45
46
  return Fraction(0)
46
47
  hours, minutes, secs, separator, frames = match.groups()
47
48
  nominal = max(1, round(rate))
48
49
  count = ((int(hours) * 60 + int(minutes)) * 60 + int(secs)) * nominal + int(frames)
49
- if separator in ';.' and rate.denominator == 1001:
50
+ if separator in ";." and rate.denominator == 1001:
50
51
  dropped = nominal // 15
51
52
  total_minutes = int(hours) * 60 + int(minutes)
52
53
  count -= dropped * (total_minutes - total_minutes // 10)
@@ -56,35 +57,48 @@ def timecode_seconds(timecode: str, rate: Fraction) -> Fraction:
56
57
  def probe(path: Path) -> dict:
57
58
  """Timecode, rotation and display size, which the project inventory does not keep."""
58
59
  completed = subprocess.run(
59
- ['ffprobe', '-v', 'error', '-print_format', 'json', '-show_entries',
60
- 'format_tags=timecode:stream=index,codec_type,width,height:stream_tags=timecode,rotate:stream_side_data=rotation',
61
- str(path)],
62
- stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=60, check=False)
60
+ [
61
+ "ffprobe",
62
+ "-v",
63
+ "error",
64
+ "-print_format",
65
+ "json",
66
+ "-show_entries",
67
+ "format_tags=timecode:stream=index,codec_type,width,height:stream_tags=timecode,rotate:stream_side_data=rotation",
68
+ str(path),
69
+ ],
70
+ stdin=subprocess.DEVNULL,
71
+ capture_output=True,
72
+ text=True,
73
+ timeout=60,
74
+ check=False,
75
+ )
63
76
  if completed.returncode != 0:
64
- raise ProjectError('resolve_source_unreadable', f'無法讀取素材 {path.name},請確認檔案還在。', status_code=409)
65
- data = json.loads(completed.stdout or '{}')
66
- streams = data.get('streams', [])
67
- timecode = data.get('format', {}).get('tags', {}).get('timecode') or next(
68
- (s.get('tags', {}).get('timecode') for s in streams if s.get('tags', {}).get('timecode')), None)
69
- return {'timecode': timecode, 'streams': {s.get('index'): s for s in streams}}
77
+ raise ProjectError("resolve_source_unreadable", f"無法讀取素材 {path.name},請確認檔案還在。", status_code=409)
78
+ data = json.loads(completed.stdout or "{}")
79
+ streams = data.get("streams", [])
80
+ timecode = data.get("format", {}).get("tags", {}).get("timecode") or next(
81
+ (s.get("tags", {}).get("timecode") for s in streams if s.get("tags", {}).get("timecode")), None
82
+ )
83
+ return {"timecode": timecode, "streams": {s.get("index"): s for s in streams}}
70
84
 
71
85
 
72
86
  def _rotation(stream: dict) -> int:
73
- for side in stream.get('side_data_list', []):
74
- if 'rotation' in side:
75
- return int(float(side['rotation']))
76
- return int(float(stream.get('tags', {}).get('rotate', 0) or 0))
87
+ for side in stream.get("side_data_list", []):
88
+ if "rotation" in side:
89
+ return int(float(side["rotation"]))
90
+ return int(float(stream.get("tags", {}).get("rotate", 0) or 0))
77
91
 
78
92
 
79
93
  def _safe_name(value: str) -> str:
80
- return _UNSAFE_NAME.sub(' ', value).strip(' .') or 'Clipen'
94
+ return _UNSAFE_NAME.sub(" ", value).strip(" .") or "Clipen"
81
95
 
82
96
 
83
97
  def _unique(directory: Path, name: str) -> Path:
84
98
  candidate, number = directory / name, 2
85
99
  while candidate.exists():
86
100
  stem, suffix = os.path.splitext(name)
87
- candidate, number = directory / f'{stem} ({number}){suffix}', number + 1
101
+ candidate, number = directory / f"{stem} ({number}){suffix}", number + 1
88
102
  return candidate
89
103
 
90
104
 
@@ -93,7 +107,7 @@ def _srt_time(value: Fraction) -> str:
93
107
  hours, rest = divmod(milliseconds, 3_600_000)
94
108
  minutes, rest = divmod(rest, 60_000)
95
109
  secs, milliseconds = divmod(rest, 1000)
96
- return f'{hours:02d}:{minutes:02d}:{secs:02d},{milliseconds:03d}'
110
+ return f"{hours:02d}:{minutes:02d}:{secs:02d},{milliseconds:03d}"
97
111
 
98
112
 
99
113
  def _lanes(intervals, first: int, step: int) -> list[int]:
@@ -114,19 +128,22 @@ def _lanes(intervals, first: int, step: int) -> list[int]:
114
128
 
115
129
  def _framing(item: MediaClip):
116
130
  """Clipen's zoom and crop window as Resolve zoom and position (FCPXML position is % of frame height)."""
117
- scale, center_x, center_y, push = 1.0, .5, .5, None
131
+ scale, center_x, center_y, push = 1.0, 0.5, 0.5, None
118
132
  for effect in item.effects:
119
133
  p = effect.parameters
120
- if effect.effect_id == 'video.punch_in':
121
- scale = min(2.0, max(1.01, float(p.get('scale', 1.08))))
122
- center_x = min(1.0, max(0.0, float(p.get('center_x', .5))))
123
- center_y = min(1.0, max(0.0, float(p.get('center_y', .5))))
124
- elif effect.effect_id == 'video.reframe':
134
+ if effect.effect_id == "video.punch_in":
135
+ scale = min(2.0, max(1.01, float(p.get("scale", 1.08))))
136
+ center_x = min(1.0, max(0.0, float(p.get("center_x", 0.5))))
137
+ center_y = min(1.0, max(0.0, float(p.get("center_y", 0.5))))
138
+ elif effect.effect_id == "video.reframe":
125
139
  scale = 1.08
126
- center_x = min(1.0, max(0.0, float(p.get('x', .5))))
127
- center_y = min(1.0, max(0.0, float(p.get('y', .5))))
128
- elif effect.effect_id == 'video.slow_push':
129
- push = (min(2.0, max(1.0, float(p.get('scale_from', 1.0)))), min(2.0, max(1.0, float(p.get('scale_to', 1.08)))))
140
+ center_x = min(1.0, max(0.0, float(p.get("x", 0.5))))
141
+ center_y = min(1.0, max(0.0, float(p.get("y", 0.5))))
142
+ elif effect.effect_id == "video.slow_push":
143
+ push = (
144
+ min(2.0, max(1.0, float(p.get("scale_from", 1.0)))),
145
+ min(2.0, max(1.0, float(p.get("scale_to", 1.08)))),
146
+ )
130
147
  return scale, center_x, center_y, push
131
148
 
132
149
 
@@ -134,19 +151,26 @@ class _Builder:
134
151
  def __init__(self, timeline, name):
135
152
  self.timeline = timeline
136
153
  self.fps = Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
137
- self.root = ET.Element('fcpxml', version='1.10')
138
- self.resources = ET.SubElement(self.root, 'resources')
154
+ self.root = ET.Element("fcpxml", version="1.10")
155
+ self.resources = ET.SubElement(self.root, "resources")
139
156
  self.formats: dict[tuple, str] = {}
140
157
  self.assets: dict[str, str] = {}
141
158
  self.count = 0
142
- self.sequence_format = self.format(timeline.width, timeline.height, 1 / self.fps, 'Clipen')
143
- library = ET.SubElement(self.root, 'library')
144
- event = ET.SubElement(library, 'event', name='Clipen')
145
- project = ET.SubElement(event, 'project', name=name)
146
- self.sequence = ET.SubElement(project, 'sequence', format=self.sequence_format,
147
- duration=seconds(self.time(timeline.duration_frames)),
148
- tcStart='0s', tcFormat='NDF', audioLayout='stereo', audioRate='48k')
149
- self.spine = ET.SubElement(self.sequence, 'spine')
159
+ self.sequence_format = self.format(timeline.width, timeline.height, 1 / self.fps, "Clipen")
160
+ library = ET.SubElement(self.root, "library")
161
+ event = ET.SubElement(library, "event", name="Clipen")
162
+ project = ET.SubElement(event, "project", name=name)
163
+ self.sequence = ET.SubElement(
164
+ project,
165
+ "sequence",
166
+ format=self.sequence_format,
167
+ duration=seconds(self.time(timeline.duration_frames)),
168
+ tcStart="0s",
169
+ tcFormat="NDF",
170
+ audioLayout="stereo",
171
+ audioRate="48k",
172
+ )
173
+ self.spine = ET.SubElement(self.sequence, "spine")
150
174
  self.parents: list[tuple[int, int, ET.Element, Fraction]] = []
151
175
 
152
176
  def time(self, frames) -> Fraction:
@@ -154,20 +178,20 @@ class _Builder:
154
178
 
155
179
  def ident(self) -> str:
156
180
  self.count += 1
157
- return f'r{self.count}'
181
+ return f"r{self.count}"
158
182
 
159
183
  def format(self, width, height, frame_duration: Fraction | None, name=None) -> str:
160
184
  key = (width, height, frame_duration)
161
185
  if key not in self.formats:
162
186
  ident = self.ident()
163
- attributes = {'id': ident, 'width': str(width), 'height': str(height)}
187
+ attributes = {"id": ident, "width": str(width), "height": str(height)}
164
188
  if frame_duration is None:
165
- attributes['name'] = 'FFVideoFormatRateUndefined'
189
+ attributes["name"] = "FFVideoFormatRateUndefined"
166
190
  else:
167
- attributes['frameDuration'] = seconds(frame_duration)
191
+ attributes["frameDuration"] = seconds(frame_duration)
168
192
  if name:
169
- attributes['name'] = name
170
- ET.SubElement(self.resources, 'format', attributes)
193
+ attributes["name"] = name
194
+ ET.SubElement(self.resources, "format", attributes)
171
195
  self.formats[key] = ident
172
196
  return self.formats[key]
173
197
 
@@ -176,14 +200,14 @@ class _Builder:
176
200
  if key in self.assets:
177
201
  return self.assets[key]
178
202
  ident = self.ident()
179
- attributes = {'id': ident, 'name': name, 'start': seconds(start), 'duration': seconds(duration)}
203
+ attributes = {"id": ident, "name": name, "start": seconds(start), "duration": seconds(duration)}
180
204
  if video:
181
- attributes.update(hasVideo='1', videoSources='1', format=video)
205
+ attributes.update(hasVideo="1", videoSources="1", format=video)
182
206
  if audio:
183
207
  channels, rate = audio
184
- attributes.update(hasAudio='1', audioSources='1', audioChannels=str(channels), audioRate=str(rate))
185
- element = ET.SubElement(self.resources, 'asset', attributes)
186
- ET.SubElement(element, 'media-rep', kind='original-media', src=path.resolve().as_uri())
208
+ attributes.update(hasAudio="1", audioSources="1", audioChannels=str(channels), audioRate=str(rate))
209
+ element = ET.SubElement(self.resources, "asset", attributes)
210
+ ET.SubElement(element, "media-rep", kind="original-media", src=path.resolve().as_uri())
187
211
  self.assets[key] = ident
188
212
  return ident
189
213
 
@@ -192,29 +216,40 @@ class _Builder:
192
216
  self.parents.append((offset_frames, duration_frames, element, local_start))
193
217
 
194
218
  def gap(self, offset_frames, duration_frames):
195
- element = ET.Element('gap', name='Gap', offset=seconds(self.time(offset_frames)),
196
- start='0s', duration=seconds(self.time(duration_frames)))
219
+ element = ET.Element(
220
+ "gap",
221
+ name="Gap",
222
+ offset=seconds(self.time(offset_frames)),
223
+ start="0s",
224
+ duration=seconds(self.time(duration_frames)),
225
+ )
197
226
  self.place(element, offset_frames, duration_frames, Fraction(0))
198
227
 
199
228
  def connect(self, tag, attributes, frame):
200
229
  """Attach an item at a timeline frame to the storyline clip under it."""
201
230
  parent = next((p for p in self.parents if p[0] <= frame < p[0] + p[1]), self.parents[-1])
202
231
  offset_frames, _, element, local_start = parent
203
- attributes = {**attributes, 'offset': seconds(local_start + self.time(frame - offset_frames))}
232
+ attributes = {**attributes, "offset": seconds(local_start + self.time(frame - offset_frames))}
204
233
  return ET.SubElement(element, tag, attributes)
205
234
 
206
- def marker(self, element, local_start: Fraction, frames, value, note=''):
207
- ET.SubElement(element, 'marker', start=seconds(local_start + self.time(frames)),
208
- duration=seconds(1 / self.fps), value=value, **({'note': note} if note else {}))
235
+ def marker(self, element, local_start: Fraction, frames, value, note=""):
236
+ ET.SubElement(
237
+ element,
238
+ "marker",
239
+ start=seconds(local_start + self.time(frames)),
240
+ duration=seconds(1 / self.fps),
241
+ value=value,
242
+ **({"note": note} if note else {}),
243
+ )
209
244
 
210
245
  def write(self, path: Path):
211
246
  ET.indent(self.root)
212
- body = ET.tostring(self.root, encoding='unicode')
213
- path.write_text('<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE fcpxml>\n\n' + body + '\n', encoding='utf-8')
247
+ body = ET.tostring(self.root, encoding="unicode")
248
+ path.write_text('<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE fcpxml>\n\n' + body + "\n", encoding="utf-8")
214
249
 
215
250
 
216
251
  def _is_caption(track, item, styles) -> bool:
217
- return track.track_id == 'agent-subtitles' or styles.get(item.style_id, {}).get('kind') == 'program_subtitle'
252
+ return track.track_id == "agent-subtitles" or styles.get(item.style_id, {}).get("kind") == "program_subtitle"
218
253
 
219
254
 
220
255
  def export_folder(repository, project_id: str) -> Path:
@@ -222,15 +257,20 @@ def export_folder(repository, project_id: str) -> Path:
222
257
  so one 'Locate' on the footage folder lets it find the footage and the package together."""
223
258
  from clipen.media.discovery import EXPORT_FOLDER
224
259
  from clipen.projects import DirectoryRole
225
- source = next((d for d in repository.projects.get_project(project_id).directories if d.role is DirectoryRole.SOURCE), None)
260
+
261
+ source = next(
262
+ (d for d in repository.projects.get_project(project_id).directories if d.role is DirectoryRole.SOURCE), None
263
+ )
226
264
  if source is None or not Path(source.canonical_path).is_dir():
227
- raise ProjectError('resolve_source_offline', '找不到毛片資料夾,請確認外接硬碟已連接。', status_code=409)
265
+ raise ProjectError("resolve_source_offline", "找不到毛片資料夾,請確認外接硬碟已連接。", status_code=409)
228
266
  folder = Path(source.canonical_path) / EXPORT_FOLDER
229
267
  folder.mkdir(exist_ok=True)
230
268
  return folder
231
269
 
232
270
 
233
- def export_resolve(repository, project_id: str, run_id: str, destination: Path | None = None, cancel: threading.Event | None = None) -> dict:
271
+ def export_resolve(
272
+ repository, project_id: str, run_id: str, destination: Path | None = None, cancel: threading.Event | None = None
273
+ ) -> dict:
234
274
  """Write a Resolve package into a new folder (beside the footage unless told otherwise) and describe it."""
235
275
  cancel = cancel or threading.Event()
236
276
  destination = destination or export_folder(repository, project_id)
@@ -238,10 +278,10 @@ def export_resolve(repository, project_id: str, run_id: str, destination: Path |
238
278
  timeline = revision.timeline
239
279
  video = next((t for t in timeline.tracks if t.kind is TrackKind.VIDEO and t.items), None)
240
280
  if video is None:
241
- raise ProjectError('resolve_video_required', '這一版還沒有畫面,無法匯出。', status_code=409)
281
+ raise ProjectError("resolve_video_required", "這一版還沒有畫面,無法匯出。", status_code=409)
242
282
  project_name = repository.projects.get_project(project_id).name
243
- name = _safe_name(f'{project_name} {datetime.now():%Y-%m-%d %H%M}')
244
- package = _unique(destination, f'{name} DaVinci Resolve')
283
+ name = _safe_name(f"{project_name} {datetime.now():%Y-%m-%d %H%M}")
284
+ package = _unique(destination, f"{name} DaVinci Resolve")
245
285
  package.mkdir()
246
286
  try:
247
287
  return _write(repository, project_id, package, name, timeline, video, cancel)
@@ -255,7 +295,9 @@ def _write(repository, project_id, package, name, timeline, video, cancel):
255
295
  from clipen.media.preview import MediaPreviewRepository
256
296
  from clipen.rendering.renderer import FfmpegPreviewRenderer, PreviewRenderError
257
297
  from clipen.rendering.titles import TitleCardRenderer, TitleRenderError
298
+
258
299
  from .production_media import AgentAudioStore, load_text_styles
300
+
259
301
  media = MediaPreviewRepository(repository.projects)
260
302
  styles = load_text_styles(repository.projects, project_id)
261
303
  build = _Builder(timeline, name)
@@ -267,33 +309,52 @@ def _write(repository, project_id, package, name, timeline, video, cancel):
267
309
  cursor = 0
268
310
  for index, item in enumerate(sorted(video.items, key=lambda i: i.start_frame), 1):
269
311
  if cancel.is_set():
270
- raise ProjectError('cancelled', '已取消匯出。', status_code=409)
312
+ raise ProjectError("cancelled", "已取消匯出。", status_code=409)
271
313
  if item.start_frame > cursor:
272
314
  build.gap(cursor, item.start_frame - cursor)
273
315
  duration = build.time(item.duration_frames)
274
- clock = f'{int(build.time(item.start_frame) // 60)}:{int(build.time(item.start_frame) % 60):02d}'
316
+ clock = f"{int(build.time(item.start_frame) // 60)}:{int(build.time(item.start_frame) % 60):02d}"
275
317
  if any(e.effect_id in BURNED for e in item.effects):
276
- directory = package / '已處理片段'
318
+ directory = package / "已處理片段"
277
319
  directory.mkdir(exist_ok=True)
278
- output = directory / f'{index:03d} {clock.replace(":", "m")}s.mov'
320
+ output = directory / f"{index:03d} {clock.replace(':', 'm')}s.mov"
279
321
  kept = tuple(e for e in item.effects if e.effect_id in BURNED | _FRAMING)
280
- single = replace(timeline, duration_frames=item.duration_frames, markers=(),
281
- tracks=(Track(video.track_id, TrackKind.VIDEO, (replace(item, start_frame=0, effects=kept),)),))
322
+ single = replace(
323
+ timeline,
324
+ duration_frames=item.duration_frames,
325
+ markers=(),
326
+ tracks=(Track(video.track_id, TrackKind.VIDEO, (replace(item, start_frame=0, effects=kept),)),),
327
+ )
282
328
  try:
283
- FfmpegPreviewRenderer(media, master=True)._render_media(project_id, single, output, cancel, lambda _: None, preserve_audio_gain=True)
329
+ FfmpegPreviewRenderer(media, master=True)._render_media(
330
+ project_id, single, output, cancel, lambda _: None, preserve_audio_gain=True
331
+ )
284
332
  except PreviewRenderError as error:
285
- raise ProjectError('resolve_render_failed', f'{clock} 的片段無法輸出({error.code})。', status_code=500) from error
333
+ raise ProjectError(
334
+ "resolve_render_failed", f"{clock} 的片段無法輸出({error.code})。", status_code=500
335
+ ) from error
286
336
  info = probe(output)
287
- has_audio = any(s.get('codec_type') == 'audio' for s in info['streams'].values())
288
- ref = build.asset(output, output.stem, Fraction(0), duration,
289
- video=build.sequence_format, audio=(2, 48000) if has_audio else None)
337
+ has_audio = any(s.get("codec_type") == "audio" for s in info["streams"].values())
338
+ ref = build.asset(
339
+ output,
340
+ output.stem,
341
+ Fraction(0),
342
+ duration,
343
+ video=build.sequence_format,
344
+ audio=(2, 48000) if has_audio else None,
345
+ )
290
346
  start = Fraction(0)
291
347
  burned += 1
292
- what = '、'.join(label for effect, label in (('video.mosaic', '馬賽克'), ('video.speed_ramp', '變速'))
293
- if any(e.effect_id == effect for e in item.effects))
294
- notes.append(f'{clock} 的鏡頭已先輸出成 ProRes(含{what}與構圖),放在「已處理片段」;原始素材不會出現在時間軸上。')
348
+ what = "、".join(
349
+ label
350
+ for effect, label in (("video.mosaic", "馬賽克"), ("video.speed_ramp", "變速"))
351
+ if any(e.effect_id == effect for e in item.effects)
352
+ )
353
+ notes.append(
354
+ f"{clock} 的鏡頭已先輸出成 ProRes(含{what}與構圖),放在「已處理片段」;原始素材不會出現在時間軸上。"
355
+ )
295
356
  framing = None
296
- label = f'{clock} 已處理'
357
+ label = f"{clock} 已處理"
297
358
  else:
298
359
  path, streams = media.locate(project_id, item.source.span.version_id)
299
360
  span = item.source.span
@@ -301,71 +362,115 @@ def _write(repository, project_id, package, name, timeline, video, cancel):
301
362
  if path not in probes:
302
363
  probes[path] = probe(path)
303
364
  info = probes[path]
304
- shown = info['streams'].get(span.stream_index, {})
365
+ shown = info["streams"].get(span.stream_index, {})
305
366
  try:
306
- rate = Fraction(stream.get('r_frame_rate') or stream.get('avg_frame_rate') or '30')
367
+ rate = Fraction(stream.get("r_frame_rate") or stream.get("avg_frame_rate") or "30")
307
368
  except (ValueError, ZeroDivisionError):
308
369
  rate = Fraction(0)
309
370
  rate = rate or build.fps
310
- width, height = shown.get('width') or stream.get('width'), shown.get('height') or stream.get('height')
371
+ width, height = shown.get("width") or stream.get("width"), shown.get("height") or stream.get("height")
311
372
  if _rotation(shown) % 180:
312
373
  width, height = height, width
313
374
  time_base = Fraction(span.time_base.numerator, span.time_base.denominator)
314
- stream_start = int(stream.get('start_pts', 0) or 0)
315
- origin = timecode_seconds(info['timecode'], rate) if info['timecode'] else Fraction(0)
316
- length = int(stream['duration_ts']) * Fraction(stream['time_base']) if stream.get('duration_ts') and stream.get('time_base') else duration
317
- audio = next((s for s in streams.values() if s['kind'] == 'audio'), None)
318
- ref = build.asset(path, path.stem, origin, length,
319
- video=build.format(width, height, 1 / rate),
320
- audio=(audio.get('channels', 2), audio.get('sample_rate', 48000)) if audio else None)
375
+ stream_start = int(stream.get("start_pts", 0) or 0)
376
+ origin = timecode_seconds(info["timecode"], rate) if info["timecode"] else Fraction(0)
377
+ length = (
378
+ int(stream["duration_ts"]) * Fraction(stream["time_base"])
379
+ if stream.get("duration_ts") and stream.get("time_base")
380
+ else duration
381
+ )
382
+ audio = next((s for s in streams.values() if s["kind"] == "audio"), None)
383
+ ref = build.asset(
384
+ path,
385
+ path.stem,
386
+ origin,
387
+ length,
388
+ video=build.format(width, height, 1 / rate),
389
+ audio=(audio.get("channels", 2), audio.get("sample_rate", 48000)) if audio else None,
390
+ )
321
391
  start = origin + (int(span.start_pts) - stream_start) * time_base
322
392
  framing = _framing(item)
323
393
  label = path.stem
324
- clip = ET.Element('asset-clip', ref=ref, offset=seconds(build.time(item.start_frame)), name=label,
325
- start=seconds(start), duration=seconds(duration), tcFormat='NDF', audioRole='dialogue')
326
- ET.SubElement(clip, 'adjust-conform', type='fit')
394
+ clip = ET.Element(
395
+ "asset-clip",
396
+ ref=ref,
397
+ offset=seconds(build.time(item.start_frame)),
398
+ name=label,
399
+ start=seconds(start),
400
+ duration=seconds(duration),
401
+ tcFormat="NDF",
402
+ audioRole="dialogue",
403
+ )
404
+ ET.SubElement(clip, "adjust-conform", type="fit")
327
405
  if framing:
328
406
  scale, center_x, center_y, push = framing
329
- shift_x = (scale - 1) * timeline.width * (.5 - center_x) / timeline.height * 100
330
- shift_y = -(scale - 1) * (.5 - center_y) * 100 + 0.0 # no '-0.0000'
407
+ shift_x = (scale - 1) * timeline.width * (0.5 - center_x) / timeline.height * 100
408
+ shift_y = -(scale - 1) * (0.5 - center_y) * 100 + 0.0 # no '-0.0000'
331
409
  if scale != 1 or push:
332
- transform = ET.SubElement(clip, 'adjust-transform', position=f'{shift_x:.4f} {shift_y:.4f}', scale=f'{scale:.4f} {scale:.4f}')
410
+ transform = ET.SubElement(
411
+ clip, "adjust-transform", position=f"{shift_x:.4f} {shift_y:.4f}", scale=f"{scale:.4f} {scale:.4f}"
412
+ )
333
413
  if push:
334
- animation = ET.SubElement(ET.SubElement(transform, 'param', name='scale'), 'keyframeAnimation')
414
+ animation = ET.SubElement(ET.SubElement(transform, "param", name="scale"), "keyframeAnimation")
335
415
  for at, value in ((start, push[0] * scale), (start + duration - 1 / build.fps, push[1] * scale)):
336
- ET.SubElement(animation, 'keyframe', time=seconds(at), value=f'{value:.4f} {value:.4f}')
337
- policy = next((e.parameters for e in item.effects if e.effect_id == 'audio.source'), None)
416
+ ET.SubElement(animation, "keyframe", time=seconds(at), value=f"{value:.4f} {value:.4f}")
417
+ policy = next((e.parameters for e in item.effects if e.effect_id == "audio.source"), None)
338
418
  if policy:
339
- gain = -96 if policy['mode'] == 'mute' else float(policy['gain_db'])
340
- ET.SubElement(clip, 'adjust-volume', amount=f'{gain:g}dB')
419
+ gain = -96 if policy["mode"] == "mute" else float(policy["gain_db"])
420
+ ET.SubElement(clip, "adjust-volume", amount=f"{gain:g}dB")
341
421
  build.place(clip, item.start_frame, item.duration_frames, start)
342
422
 
343
423
  # Looks Resolve cannot take from FCPXML stay as markers on the shot.
344
424
  if framing is None:
345
- build.marker(clip, start, 0, 'Clipen 已處理片段', '這段已套用馬賽克或變速並輸出成 ProRes;原始素材不在時間線上。')
346
- if policy and policy['mode'] == 'dialogue':
347
- build.marker(clip, start, 0, 'Clipen 對白處理', '高通 85 Hz、低通 11 kHz、輕微壓縮;請在 Fairlight 重做。')
348
- grade = next((e.parameters for e in item.effects if e.effect_id == 'video.grade'), None)
425
+ build.marker(
426
+ clip, start, 0, "Clipen 已處理片段", "這段已套用馬賽克或變速並輸出成 ProRes;原始素材不在時間線上。"
427
+ )
428
+ if policy and policy["mode"] == "dialogue":
429
+ build.marker(clip, start, 0, "Clipen 對白處理", "高通 85 Hz、低通 11 kHz、輕微壓縮;請在 Fairlight 重做。")
430
+ grade = next((e.parameters for e in item.effects if e.effect_id == "video.grade"), None)
349
431
  if grade:
350
- build.marker(clip, start, 0, 'Clipen 調色',
351
- f'對比 {float(grade["contrast"]):.2f}、飽和度 {float(grade["saturation"]):.2f}、亮度 {float(grade["brightness"]):+.2f};請在調色頁重調。')
352
- notes.append(f'{clock} 的鏡頭有調色,數值記在標記裡。')
432
+ build.marker(
433
+ clip,
434
+ start,
435
+ 0,
436
+ "Clipen 調色",
437
+ f"對比 {float(grade['contrast']):.2f}、飽和度 {float(grade['saturation']):.2f}、亮度 {float(grade['brightness']):+.2f};請在調色頁重調。",
438
+ )
439
+ notes.append(f"{clock} 的鏡頭有調色,數值記在標記裡。")
353
440
  for effect in item.effects:
354
441
  p = effect.parameters
355
- if effect.effect_id == 'video.transition' and p.get('kind') != 'none':
356
- color = '白' if p['kind'] == 'dip_white' else '黑'
357
- build.marker(clip, start, 0, f'Clipen 轉場:淡入淡出{color}場', f'共 {p["duration_frames"]} 格,前後兩個鏡頭各一半。')
358
- notes.append(f'{clock} 有淡入淡出{color}場轉場,請在 Resolve 加上 Dip to Color Dissolve。')
359
- elif effect.effect_id == 'video.transition_out':
360
- color = '白' if p.get('kind') == 'dip_white' else '黑'
361
- build.marker(clip, start, max(0, item.duration_frames - p['duration_frames'] // 2), f'Clipen 轉場:淡出到{color}場', f'共 {p["duration_frames"] // 2} 格。')
362
- elif effect.effect_id == 'video.fade':
363
- if p.get('fade_in_frames'):
364
- build.marker(clip, start, 0, 'Clipen 淡入', f'從黑場淡入 {p["fade_in_frames"]} 格。')
365
- if p.get('fade_out_frames'):
366
- build.marker(clip, start, item.duration_frames - p['fade_out_frames'], 'Clipen 淡出', f'淡出到黑場 {p["fade_out_frames"]} 格。')
367
- if p.get('fade_in_frames') or p.get('fade_out_frames'):
368
- notes.append(f'{clock} 的鏡頭有淡入或淡出,請在 Resolve 補上。')
442
+ if effect.effect_id == "video.transition" and p.get("kind") != "none":
443
+ color = "白" if p["kind"] == "dip_white" else "黑"
444
+ build.marker(
445
+ clip,
446
+ start,
447
+ 0,
448
+ f"Clipen 轉場:淡入淡出{color}場",
449
+ f"共 {p['duration_frames']} 格,前後兩個鏡頭各一半。",
450
+ )
451
+ notes.append(f"{clock} 有淡入淡出{color}場轉場,請在 Resolve 加上 Dip to Color Dissolve。")
452
+ elif effect.effect_id == "video.transition_out":
453
+ color = "白" if p.get("kind") == "dip_white" else "黑"
454
+ build.marker(
455
+ clip,
456
+ start,
457
+ max(0, item.duration_frames - p["duration_frames"] // 2),
458
+ f"Clipen 轉場:淡出到{color}場",
459
+ f"共 {p['duration_frames'] // 2} 格。",
460
+ )
461
+ elif effect.effect_id == "video.fade":
462
+ if p.get("fade_in_frames"):
463
+ build.marker(clip, start, 0, "Clipen 淡入", f"從黑場淡入 {p['fade_in_frames']} 格。")
464
+ if p.get("fade_out_frames"):
465
+ build.marker(
466
+ clip,
467
+ start,
468
+ item.duration_frames - p["fade_out_frames"],
469
+ "Clipen 淡出",
470
+ f"淡出到黑場 {p['fade_out_frames']} 格。",
471
+ )
472
+ if p.get("fade_in_frames") or p.get("fade_out_frames"):
473
+ notes.append(f"{clock} 的鏡頭有淡入或淡出,請在 Resolve 補上。")
369
474
  cursor = item.start_frame + item.duration_frames
370
475
  if cursor < timeline.duration_frames:
371
476
  build.gap(cursor, timeline.duration_frames - cursor)
@@ -379,7 +484,7 @@ def _write(repository, project_id, package, name, timeline, video, cancel):
379
484
  (captions if _is_caption(track, item, styles) else overlays).append((track, item))
380
485
  rendered, editable = [], 0
381
486
  if overlays:
382
- directory = package / '元件'
487
+ directory = package / "元件"
383
488
  directory.mkdir()
384
489
  with tempfile.TemporaryDirectory(dir=package) as temporary:
385
490
  images = []
@@ -387,85 +492,164 @@ def _write(repository, project_id, package, name, timeline, video, cancel):
387
492
  # The renderer caps one pass for FFmpeg's sake; stills for Resolve go batch by batch.
388
493
  size = TitleCardRenderer._MAX_TITLES
389
494
  for first in range(0, len(overlays), size):
390
- batch = overlays[first:first + size]
391
- only = replace(timeline, tracks=tuple(Track(f'overlay-{n}', TrackKind.TITLE, (item,)) for n, (_, item) in enumerate(batch)))
495
+ batch = overlays[first : first + size]
496
+ only = replace(
497
+ timeline,
498
+ tracks=tuple(
499
+ Track(f"overlay-{n}", TrackKind.TITLE, (item,)) for n, (_, item) in enumerate(batch)
500
+ ),
501
+ )
392
502
  folder = Path(temporary) / str(first)
393
503
  folder.mkdir()
394
504
  images += TitleCardRenderer(styles).render(only, folder)
395
505
  except TitleRenderError as error:
396
- raise ProjectError('resolve_overlay_failed', f'元件圖片無法產生({error.code})。', status_code=500) from error
506
+ raise ProjectError(
507
+ "resolve_overlay_failed", f"元件圖片無法產生({error.code})。", status_code=500
508
+ ) from error
397
509
  for number, ((_, item), image) in enumerate(zip(overlays, images), 1):
398
- label = _safe_name(item.text.split('\n', 1)[0])[:40]
399
- target = directory / f'{number:03d} {label}.png'
510
+ label = _safe_name(item.text.split("\n", 1)[0])[:40]
511
+ target = directory / f"{number:03d} {label}.png"
400
512
  shutil.move(str(image.path), target)
401
513
  rendered.append((item, target, label))
402
514
  editable = _editable_titles(directory, rendered, styles, timeline)
403
515
  still = build.format(timeline.width, timeline.height, None)
404
- for (item, target, label), lane in zip(rendered, _lanes([(i.start_frame, i.start_frame + i.duration_frames) for i, _, _ in rendered], 1, 1)):
516
+ for (item, target, label), lane in zip(
517
+ rendered, _lanes([(i.start_frame, i.start_frame + i.duration_frames) for i, _, _ in rendered], 1, 1)
518
+ ):
405
519
  ref = build.asset(target, target.stem, Fraction(0), Fraction(0), video=still)
406
- build.connect('video', {'ref': ref, 'lane': str(lane), 'name': label, 'start': '0s',
407
- 'duration': seconds(build.time(item.duration_frames))}, item.start_frame)
408
- notes.append(f'畫面元件 {len(rendered)} 個先以透明 PNG 放在影片上層,位置和外觀與 Clipen 相同,彈出動畫不會保留。'
409
- + (f'其中 {editable} 個可以換成能改字的 DaVinci 標題,做法見上面「想在 Resolve 改元件的字」。' if editable else ''))
520
+ build.connect(
521
+ "video",
522
+ {
523
+ "ref": ref,
524
+ "lane": str(lane),
525
+ "name": label,
526
+ "start": "0s",
527
+ "duration": seconds(build.time(item.duration_frames)),
528
+ },
529
+ item.start_frame,
530
+ )
531
+ notes.append(
532
+ f"畫面元件 {len(rendered)} 個先以透明 PNG 放在影片上層,位置和外觀與 Clipen 相同,彈出動畫不會保留。"
533
+ + (
534
+ f"其中 {editable} 個可以換成能改字的 DaVinci 標題,做法見上面「想在 Resolve 改元件的字」。"
535
+ if editable
536
+ else ""
537
+ )
538
+ )
410
539
  if captions:
411
540
  lines = []
412
541
  for number, (_, item) in enumerate(sorted(captions, key=lambda pair: pair[1].start_frame), 1):
413
- lines += [str(number), f'{_srt_time(build.time(item.start_frame))} --> {_srt_time(build.time(item.start_frame + item.duration_frames))}', item.text.strip(), '']
414
- (package / '字幕.srt').write_text('\n'.join(lines), encoding='utf-8')
542
+ lines += [
543
+ str(number),
544
+ f"{_srt_time(build.time(item.start_frame))} --> {_srt_time(build.time(item.start_frame + item.duration_frames))}",
545
+ item.text.strip(),
546
+ "",
547
+ ]
548
+ (package / "字幕.srt").write_text("\n".join(lines), encoding="utf-8")
415
549
 
416
550
  # 3. Music: the stem Clipen mixed (ducked under speech), plus each source muted for rework.
417
- layers = [(i, l) for t in timeline.tracks for i in t.items if isinstance(i, MediaClip)
418
- for e in i.effects if e.effect_id == 'audio.layers' for l in e.parameters['layers']]
551
+ layers = [
552
+ (i, l)
553
+ for t in timeline.tracks
554
+ for i in t.items
555
+ if isinstance(i, MediaClip)
556
+ for e in i.effects
557
+ if e.effect_id == "audio.layers"
558
+ for l in e.parameters["layers"]
559
+ ]
419
560
  if layers:
420
561
  from .program_audio import render_music_stem
421
- directory = package / '音樂'
562
+
563
+ directory = package / "音樂"
422
564
  directory.mkdir()
423
- stem = directory / '配樂(Clipen 混音).wav'
565
+ stem = directory / "配樂(Clipen 混音).wav"
424
566
  settings, _ = render_music_stem(media, project_id, timeline, stem, cancel)
425
567
  total = build.time(timeline.duration_frames)
426
568
  ref = build.asset(stem, stem.stem, Fraction(0), total, audio=(2, 48000))
427
- build.connect('asset-clip', {'ref': ref, 'lane': '-1', 'name': stem.stem, 'start': '0s',
428
- 'duration': seconds(total), 'audioRole': 'music'}, 0)
569
+ build.connect(
570
+ "asset-clip",
571
+ {
572
+ "ref": ref,
573
+ "lane": "-1",
574
+ "name": stem.stem,
575
+ "start": "0s",
576
+ "duration": seconds(total),
577
+ "audioRole": "music",
578
+ },
579
+ 0,
580
+ )
429
581
  store = AgentAudioStore(repository.projects, project_id)
430
582
  copies: dict[str, tuple[Path, dict]] = {}
431
- spans = [(clip.start_frame + layer['start_frame'], clip.start_frame + layer['start_frame'] + layer['duration_frames']) for clip, layer in layers]
583
+ spans = [
584
+ (
585
+ clip.start_frame + layer["start_frame"],
586
+ clip.start_frame + layer["start_frame"] + layer["duration_frames"],
587
+ )
588
+ for clip, layer in layers
589
+ ]
432
590
  for (clip, layer), setting, lane in zip(layers, settings, _lanes(spans, -2, -1)):
433
- if layer['asset_id'] not in copies:
434
- fd, asset = open_asset(store.context(layer['asset_id']), layer['asset_id'])
435
- with os.fdopen(fd, 'rb') as source:
436
- target = _unique(directory, _safe_name(Path(asset['relative_path']).name))
437
- with target.open('wb') as copy:
591
+ if layer["asset_id"] not in copies:
592
+ fd, asset = open_asset(store.context(layer["asset_id"]), layer["asset_id"])
593
+ with os.fdopen(fd, "rb") as source:
594
+ target = _unique(directory, _safe_name(Path(asset["relative_path"]).name))
595
+ with target.open("wb") as copy:
438
596
  shutil.copyfileobj(source, copy)
439
- copies[layer['asset_id']] = (target, asset)
440
- target, asset = copies[layer['asset_id']]
441
- length = Fraction(round(asset['duration_seconds'] * 48000), 48000)
597
+ copies[layer["asset_id"]] = (target, asset)
598
+ target, asset = copies[layer["asset_id"]]
599
+ length = Fraction(round(asset["duration_seconds"] * 48000), 48000)
442
600
  ref = build.asset(target, target.stem, Fraction(0), length, audio=(2, 48000))
443
- element = build.connect('asset-clip', {'ref': ref, 'lane': str(lane), 'name': f'{target.stem}(原始)', 'enabled': '0',
444
- 'start': seconds(Fraction(round(layer['source_offset_seconds'] * 48000), 48000)),
445
- 'duration': seconds(build.time(layer['duration_frames'])), 'audioRole': 'music'},
446
- clip.start_frame + layer['start_frame'])
447
- ET.SubElement(element, 'adjust-volume', amount=f'{setting["normalization_db"] + layer["gain_db"]:.2f}dB')
448
- notes.append('配樂分兩層:「配樂(Clipen 混音)」是 Clipen 混好的成品(講話時自動壓低、含淡入淡出);下方停用的「原始」音軌是各段原始音樂,要重新混音時啟用它們並關掉混音層。')
449
-
450
- fcpxml = package / f'{name}.fcpxml'
601
+ element = build.connect(
602
+ "asset-clip",
603
+ {
604
+ "ref": ref,
605
+ "lane": str(lane),
606
+ "name": f"{target.stem}(原始)",
607
+ "enabled": "0",
608
+ "start": seconds(Fraction(round(layer["source_offset_seconds"] * 48000), 48000)),
609
+ "duration": seconds(build.time(layer["duration_frames"])),
610
+ "audioRole": "music",
611
+ },
612
+ clip.start_frame + layer["start_frame"],
613
+ )
614
+ ET.SubElement(element, "adjust-volume", amount=f"{setting['normalization_db'] + layer['gain_db']:.2f}dB")
615
+ notes.append(
616
+ "配樂分兩層:「配樂(Clipen 混音)」是 Clipen 混好的成品(講話時自動壓低、含淡入淡出);下方停用的「原始」音軌是各段原始音樂,要重新混音時啟用它們並關掉混音層。"
617
+ )
618
+
619
+ fcpxml = package / f"{name}.fcpxml"
451
620
  build.write(fcpxml)
452
621
  _guide(package, fcpxml, bool(captions), editable, notes)
453
- return {'folder': str(package), 'fcpxml': str(fcpxml), 'shots': len(video.items), 'burned': burned,
454
- 'overlays': len(rendered), 'editable_overlays': editable, 'captions': len(captions),
455
- 'music_layers': len(layers), 'notes': notes}
622
+ return {
623
+ "folder": str(package),
624
+ "fcpxml": str(fcpxml),
625
+ "shots": len(video.items),
626
+ "burned": burned,
627
+ "overlays": len(rendered),
628
+ "editable_overlays": editable,
629
+ "captions": len(captions),
630
+ "music_layers": len(layers),
631
+ "notes": notes,
632
+ }
456
633
 
457
634
 
458
635
  def _editable_titles(directory: Path, rendered, styles, timeline) -> int:
459
636
  """Record each component's type beside its PNG so a .drt from Resolve can carry it as editable titles."""
460
637
  from clipen.rendering import program_creator
461
638
  from clipen.rendering.titles import TitleCardRenderer, TitleRenderError
639
+
462
640
  from .resolve_titles import MANIFEST
641
+
463
642
  font_path = TitleCardRenderer._font_path()
464
643
  manifest = {}
465
644
  for item, target, _ in rendered:
466
645
  profile = styles.get(item.style_id)
467
646
  # A graphic a person resized stays a picture: Resolve's titles would come back at the designed size.
468
- if not profile or profile.get('kind') != 'program_component' or not program_creator.is_creator(profile) or profile.get('scale', 1) != 1:
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
+ ):
469
653
  continue
470
654
  try:
471
655
  plan = program_creator.editable(font_path, timeline, item, profile)
@@ -474,16 +658,21 @@ def _editable_titles(directory: Path, rendered, styles, timeline) -> int:
474
658
  if plan is None:
475
659
  continue
476
660
  picture = None
477
- if plan['picture']:
478
- picture = f'{target.stem}(底圖).png'
479
- plan['picture'].save(directory / picture, 'PNG', optimize=True)
480
- manifest[target.name] = {'rows': plan['rows'], 'picture': picture, 'width': timeline.width, 'height': timeline.height}
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
+ }
481
670
  if manifest:
482
- (directory / MANIFEST).write_text(json.dumps(manifest, ensure_ascii=False, indent=1), encoding='utf-8')
671
+ (directory / MANIFEST).write_text(json.dumps(manifest, ensure_ascii=False, indent=1), encoding="utf-8")
483
672
  return len(manifest)
484
673
 
485
674
 
486
- RESOLVE_DEFAULT_FOLDER = Path.home() / 'Movies' / 'DaVinci Resolve'
675
+ RESOLVE_DEFAULT_FOLDER = Path.home() / "Movies" / "DaVinci Resolve"
487
676
 
488
677
 
489
678
  def _timeline_folders(package: Path) -> list[Path]:
@@ -491,23 +680,32 @@ def _timeline_folders(package: Path) -> list[Path]:
491
680
  and, for a package in「Clipen 匯出」, that folder and the footage folder around it, since the
492
681
  save dialog often opens beside the footage the timeline was relinked to."""
493
682
  from clipen.media.discovery import EXPORT_FOLDER
683
+
494
684
  folders = [package, RESOLVE_DEFAULT_FOLDER]
495
685
  if package.parent.name == EXPORT_FOLDER:
496
686
  folders += [package.parent, package.parent.parent]
497
687
  return folders
498
688
 
499
689
 
500
- def _exported_timeline(package: Path, since: float = 0.) -> Path | None:
690
+ def _exported_timeline(package: Path, since: float = 0.0) -> Path | None:
501
691
  """The newest .drt saved from this package's timeline after since (a time stamp).
502
692
 
503
693
  A .drt counts when its clips point at this package's components, so other films' timelines
504
694
  in the same folders are passed over."""
505
695
  from .resolve_titles import uses
696
+
506
697
  # Skip dot files such as the「._」copies macOS leaves beside files on exFAT drives.
507
- candidates = [p for folder in _timeline_folders(package) for p in folder.glob('*.drt')
508
- if '(可改字)' not in p.stem and not p.name.startswith('.')]
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
+ ]
509
704
  candidates = [p for p in candidates if p.stat().st_mtime > since]
510
- return next((p for p in sorted(candidates, key=lambda p: p.stat().st_mtime, reverse=True) if uses(p, package / '元件')), None)
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
+ )
511
709
 
512
710
 
513
711
  def timeline_status(package: Path) -> dict:
@@ -516,42 +714,60 @@ def timeline_status(package: Path) -> dict:
516
714
  state is waiting (nothing saved yet), found (a .drt is newer than any editable copy) or
517
715
  converted (the editable copy covers the newest save)."""
518
716
  package = Path(package)
519
- names = ['這份匯出的資料夾', 'Resolve 預設的資料夾', '「Clipen 匯出」資料夾', '毛片資料夾']
520
- folders = [{'label': label, 'path': str(folder)} for label, folder in zip(names, _timeline_folders(package))]
717
+ names = ["這份匯出的資料夾", "Resolve 預設的資料夾", "「Clipen 匯出」資料夾", "毛片資料夾"]
718
+ folders = [{"label": label, "path": str(folder)} for label, folder in zip(names, _timeline_folders(package))]
521
719
  source = _exported_timeline(package)
522
- copies = sorted((p for p in package.glob('*(可改字).drt') if not p.name.startswith('.')), key=lambda p: p.stat().st_mtime, reverse=True)
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
+ )
523
725
  converted = copies[0] if copies else None
524
726
  if converted is not None and (source is None or converted.stat().st_mtime >= source.stat().st_mtime):
525
- state = 'converted'
727
+ state = "converted"
526
728
  else:
527
- state = 'found' if source is not None else 'waiting'
528
- return {'state': state, 'folders': folders,
529
- 'source': str(source) if source else None, 'converted': str(converted) if converted else None}
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
+ }
530
736
 
531
737
 
532
738
  def convert_timeline(package: Path, source: Path | None = None) -> tuple[Path, int]:
533
739
  """Write a copy of the .drt exported from this package's timeline with editable component titles."""
534
740
  from .resolve_titles import MANIFEST, convert
741
+
535
742
  package = Path(package)
536
- if not (package / '元件' / MANIFEST).is_file():
537
- raise ProjectError('resolve_titles_missing', '這份匯出沒有可以換成文字的元件。', status_code=409)
743
+ if not (package / "元件" / MANIFEST).is_file():
744
+ raise ProjectError("resolve_titles_missing", "這份匯出沒有可以換成文字的元件。", status_code=409)
538
745
  source = source or _exported_timeline(package)
539
746
  if source is None:
540
- raise ProjectError('resolve_timeline_missing', '還找不到這份匯出的 .drt。請先在 DaVinci Resolve 用「檔案 > 匯出 > 時間線…」把時間線存成 .drt。', status_code=409)
541
- target = _unique(package, f'{source.stem}(可改字).drt')
542
- temporary = target.with_suffix('.partial')
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")
543
754
  try:
544
755
  replaced = convert(source, temporary)
545
756
  if not replaced:
546
- raise ProjectError('resolve_titles_unmatched', f'「{source.name}」裡找不到這份匯出的元件。請確認匯出的是從這個資料夾匯入的時間線。', status_code=409)
757
+ raise ProjectError(
758
+ "resolve_titles_unmatched",
759
+ f"「{source.name}」裡找不到這份匯出的元件。請確認匯出的是從這個資料夾匯入的時間線。",
760
+ status_code=409,
761
+ )
547
762
  temporary.replace(target)
548
763
  finally:
549
764
  temporary.unlink(missing_ok=True)
550
765
  return target, replaced
551
766
 
552
767
 
553
- def watch_timeline(package: Path, since: float, stop: threading.Event | None = None,
554
- timeout: float = 4 * 3600, interval: float = 2.) -> Path | None:
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:
555
771
  """Wait for the person to save this package's timeline as .drt in Resolve, then convert and show it.
556
772
 
557
773
  A save counts once its size holds still for one interval, so a half-written file is never read.
@@ -578,39 +794,54 @@ def watch_timeline(package: Path, since: float, stop: threading.Event | None = N
578
794
  def start_watching(package: Path) -> threading.Thread:
579
795
  """Watch for the .drt in the background so the person never has to come back to Clipen for it."""
580
796
  since = time.time()
581
- thread = threading.Thread(target=watch_timeline, args=(Path(package), since), name='resolve-titles', daemon=True)
797
+ thread = threading.Thread(target=watch_timeline, args=(Path(package), since), name="resolve-titles", daemon=True)
582
798
  thread.start()
583
799
  return thread
584
800
 
585
801
 
586
802
  def reveal(path: Path) -> None:
587
803
  """Show the new timeline file in Finder; a missing Finder only skips this courtesy."""
588
- if os.uname().sysname == 'Darwin':
589
- subprocess.run(['/usr/bin/open', '-R', str(path)], stdin=subprocess.DEVNULL, capture_output=True, timeout=10, check=False)
804
+ if os.uname().sysname == "Darwin":
805
+ subprocess.run(
806
+ ["/usr/bin/open", "-R", str(path)], stdin=subprocess.DEVNULL, capture_output=True, timeout=10, check=False
807
+ )
590
808
 
591
809
 
592
810
  def _guide(package: Path, fcpxml: Path, captions: bool, editable: int, notes: list[str]):
593
811
  steps = [
594
- '在 DaVinci Resolve 匯入',
595
- '',
596
- f'1. 選「檔案 > 匯入 > 時間線…」(File > Import > Timeline),選擇「{fcpxml.name}」。',
597
- '2. 匯入視窗保持預設,確認「自動將素材匯入媒體池」有勾選。',
812
+ "在 DaVinci Resolve 匯入",
813
+ "",
814
+ f"1. 選「檔案 > 匯入 > 時間線…」(File > Import > Timeline),選擇「{fcpxml.name}」。",
815
+ "2. 匯入視窗保持預設,確認「自動將素材匯入媒體池」有勾選。",
598
816
  ]
599
817
  if captions:
600
- steps += ['3. 選「檔案 > 匯入 > 字幕…」(File > Import > Subtitle),選擇「字幕.srt」,再把它拖到時間線最上方的字幕軌。',
601
- ' 字幕會變成 Resolve 的字幕軌,可以直接改字和時間;外觀請在字幕軌的檢查器設定。']
602
- steps += ['', '如果 Resolve 顯示「clips were not yet found」,按「Locate」(尋找),選擇毛片資料夾(也就是「Clipen 匯出」所在的資料夾)。',
603
- 'App Store 版的 Resolve 只能讀取你打開過的資料夾,選一次毛片資料夾,素材和這裡的元件、音樂就都找得到。',
604
- '', '影片片段直接指向原始素材,前後保留可延長的長度。若搬動了素材,Resolve 會請你重新連結。',
605
- '這個資料夾裡的元件、音樂和已處理片段也被時間線使用,請保持資料夾完整。']
818
+ steps += [
819
+ "3. 選「檔案 > 匯入 > 字幕…」(File > Import > Subtitle),選擇「字幕.srt」,再把它拖到時間線最上方的字幕軌。",
820
+ " 字幕會變成 Resolve 的字幕軌,可以直接改字和時間;外觀請在字幕軌的檢查器設定。",
821
+ ]
822
+ steps += [
823
+ "",
824
+ "如果 Resolve 顯示「clips were not yet found」,按「Locate」(尋找),選擇毛片資料夾(也就是「Clipen 匯出」所在的資料夾)。",
825
+ "App Store 版的 Resolve 只能讀取你打開過的資料夾,選一次毛片資料夾,素材和這裡的元件、音樂就都找得到。",
826
+ "",
827
+ "影片片段直接指向原始素材,前後保留可延長的長度。若搬動了素材,Resolve 會請你重新連結。",
828
+ "這個資料夾裡的元件、音樂和已處理片段也被時間線使用,請保持資料夾完整。",
829
+ ]
606
830
  if editable:
607
- steps += ['', '想在 Resolve 改元件的字(需要時再做)', '',
608
- f'匯入後元件已經和 Clipen 一模一樣,只是以圖片呈現。要改其中的字,再做兩步,{editable} 個元件會一起換成可以改字的標題:',
609
- '1. 選「檔案 > 匯出 > 時間線…」(File > Export > Timeline),格式選「DaVinci Resolve Timeline Files (*.drt)」,按儲存。',
610
- ' Clipen 開著的話會自動做好一份名稱有「(可改字)」的 .drt,並在 Finder 打開它;沒出現的話,到 Clipen 的「到 DaVinci Resolve 自己剪」按「把元件換成可改字的標題」。',
611
- '2. 選「檔案 > 匯入 > 時間線…」,選那份「(可改字)」的 .drt。選取元件後,在右邊「檢查器」改字。',
612
- ' 改字只會改文字本身;底框、細線這類圖形是固定的圖片,字數差很多時可能要自己調整位置。']
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
+ ]
613
841
  if notes:
614
- steps += ['', '需要留意', ''] + [f'・{note}' for note in notes]
615
- steps += ['', '時間線上的標記(Marker)記下了 Clipen 有、但 Resolve 無法直接帶入的處理,例如調色數值、轉場與淡入淡出。']
616
- (package / '說明.txt').write_text('\n'.join(steps) + '\n', encoding='utf-8')
842
+ steps += ["", "需要留意", ""] + [f"・{note}" for note in notes]
843
+ steps += [
844
+ "",
845
+ "時間線上的標記(Marker)記下了 Clipen 有、但 Resolve 無法直接帶入的處理,例如調色數值、轉場與淡入淡出。",
846
+ ]
847
+ (package / "說明.txt").write_text("\n".join(steps) + "\n", encoding="utf-8")