@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
@@ -1,10 +1,11 @@
1
1
  """Bounded dialogue-driven envelopes and inspectable stems for skill productions."""
2
- from array import array
2
+
3
3
  import math
4
4
  import os
5
5
  import sys
6
- from types import SimpleNamespace
7
6
  import wave
7
+ from array import array
8
+ from types import SimpleNamespace
8
9
 
9
10
  from clipen.domain import MediaClip
10
11
  from clipen.projects import ProjectError
@@ -13,106 +14,235 @@ from clipen.projects import ProjectError
13
14
  def dialogue_regions(projects, project_id, timeline):
14
15
  from .evidence_jobs import local_cues
15
16
  from .production_media import transcript_cues
16
- tools=SimpleNamespace(repository=SimpleNamespace(projects=projects),project_id=project_id,run_id=timeline.production_session_id)
17
- local,_=local_cues(tools,timeline,include_drafts=True)
18
- legacy,_=transcript_cues(projects,project_id,timeline,include_drafts=True)
19
- fps=timeline.frame_rate.numerator/timeline.frame_rate.denominator
20
- intervals=[]
21
- for cue in local+legacy:
22
- intervals.extend((w['start_frame']/fps,w['end_frame']/fps) for w in cue.get('words',[]))
17
+
18
+ tools = SimpleNamespace(
19
+ repository=SimpleNamespace(projects=projects), project_id=project_id, run_id=timeline.production_session_id
20
+ )
21
+ local, _ = local_cues(tools, timeline, include_drafts=True)
22
+ legacy, _ = transcript_cues(projects, project_id, timeline, include_drafts=True)
23
+ fps = timeline.frame_rate.numerator / timeline.frame_rate.denominator
24
+ intervals = []
25
+ for cue in local + legacy:
26
+ intervals.extend((w["start_frame"] / fps, w["end_frame"] / fps) for w in cue.get("words", []))
23
27
  # Legacy long ASR windows are deliberately not treated as speech activity.
24
28
  # Missing activity leaves music at its chosen gain instead of permanently
25
29
  # compressing it under noise. Report that limitation in the mix evidence.
26
- merged=[]
27
- for start,end in sorted(intervals):
28
- if merged and start<=merged[-1][1]+.18:
29
- merged[-1]=(merged[-1][0],max(end,merged[-1][1]))
30
- elif end>start:merged.append((start,end))
30
+ merged = []
31
+ for start, end in sorted(intervals):
32
+ if merged and start <= merged[-1][1] + 0.18:
33
+ merged[-1] = (merged[-1][0], max(end, merged[-1][1]))
34
+ elif end > start:
35
+ merged.append((start, end))
31
36
  return merged
32
37
 
33
38
 
34
- def duck_expression(regions, *, attenuation_db=7, attack=.12, release=.4):
35
- if not regions:return '1'
36
- pieces=[f"min(1,max(0,(t-{start-attack:.6f})/{attack}))*min(1,max(0,({end+release:.6f}-t)/{release}))" for start,end in regions]
39
+ def duck_expression(regions, *, attenuation_db=7, attack=0.12, release=0.4):
40
+ if not regions:
41
+ return "1"
42
+ pieces = [
43
+ f"min(1,max(0,(t-{start - attack:.6f})/{attack}))*min(1,max(0,({end + release:.6f}-t)/{release}))"
44
+ for start, end in regions
45
+ ]
37
46
  return f"pow(10,-{attenuation_db}*min(1,({'+'.join(pieces)}))/20)"
38
47
 
39
48
 
40
49
  def measure_stem(path):
41
- windows=[];total=0;count=0;peak=0
42
- with wave.open(str(path),'rb') as source:
43
- if source.getsampwidth()!=2:raise ValueError('stem requires PCM16')
44
- block=max(1,source.getframerate()//2)
45
- while chunk:=source.readframes(block):
46
- samples=array('h');samples.frombytes(chunk)
47
- if sys.byteorder!='little':samples.byteswap()
48
- power=sum(v*v for v in samples)
49
- rms=math.sqrt(power/max(1,len(samples)))/32768
50
- windows.append(round(20*math.log10(rms),2) if rms else None)
51
- total+=power;count+=len(samples);peak=max(peak,max((abs(v) for v in samples),default=0))
52
- rms=math.sqrt(total/max(1,count))/32768
53
- return {'rms_dbfs':round(20*math.log10(rms),2) if rms else None,
54
- 'peak_dbfs':round(20*math.log10(peak/32768),2) if peak else None,
55
- 'window_seconds':.5,'window_rms_dbfs':windows}
50
+ windows = []
51
+ total = 0
52
+ count = 0
53
+ peak = 0
54
+ with wave.open(str(path), "rb") as source:
55
+ if source.getsampwidth() != 2:
56
+ raise ValueError("stem requires PCM16")
57
+ block = max(1, source.getframerate() // 2)
58
+ while chunk := source.readframes(block):
59
+ samples = array("h")
60
+ samples.frombytes(chunk)
61
+ if sys.byteorder != "little":
62
+ samples.byteswap()
63
+ power = sum(v * v for v in samples)
64
+ rms = math.sqrt(power / max(1, len(samples))) / 32768
65
+ windows.append(round(20 * math.log10(rms), 2) if rms else None)
66
+ total += power
67
+ count += len(samples)
68
+ peak = max(peak, max((abs(v) for v in samples), default=0))
69
+ rms = math.sqrt(total / max(1, count)) / 32768
70
+ return {
71
+ "rms_dbfs": round(20 * math.log10(rms), 2) if rms else None,
72
+ "peak_dbfs": round(20 * math.log10(peak / 32768), 2) if peak else None,
73
+ "window_seconds": 0.5,
74
+ "window_rms_dbfs": windows,
75
+ }
56
76
 
57
77
 
58
78
  def render_music_stem(media, project_id, timeline, music, cancel):
59
79
  """Write the music and effects under dialogue as one PCM stem; returns its settings and speech regions."""
60
80
  from clipen.finishing.audio import open_asset, run_process
81
+
61
82
  from .production_media import AgentAudioStore
62
- fps=timeline.frame_rate.numerator/timeline.frame_rate.denominator
63
- seconds=timeline.duration_frames/fps
64
- layers=[(i,l) for t in timeline.tracks for i in t.items if isinstance(i,MediaClip)
65
- for e in i.effects if e.effect_id=='audio.layers' for l in e.parameters['layers']]
66
- if len(layers)>24:raise ProjectError('agent_audio_limit','單次最多 24 個混音片段。',status_code=422)
67
- regions=dialogue_regions(media.projects,project_id,timeline)
68
- if len(regions)>(1024 if seconds>75 else 256):raise ProjectError('audio_envelope_limit','語音包絡過多,請縮小預覽區間。',status_code=422)
69
- store=AgentAudioStore(media.projects,project_id)
70
- command=['ffmpeg','-v','error','-nostdin','-y','-filter_complex_threads','2','-f','lavfi','-i',f'anullsrc=r=48000:cl=stereo:d={seconds}']
71
- filters=[];labels=['[0:a]'];duck_labels=[];opened=[];settings=[]
83
+
84
+ fps = timeline.frame_rate.numerator / timeline.frame_rate.denominator
85
+ seconds = timeline.duration_frames / fps
86
+ layers = [
87
+ (i, l)
88
+ for t in timeline.tracks
89
+ for i in t.items
90
+ if isinstance(i, MediaClip)
91
+ for e in i.effects
92
+ if e.effect_id == "audio.layers"
93
+ for l in e.parameters["layers"]
94
+ ]
95
+ if len(layers) > 24:
96
+ raise ProjectError("agent_audio_limit", "單次最多 24 個混音片段。", status_code=422)
97
+ regions = dialogue_regions(media.projects, project_id, timeline)
98
+ if len(regions) > (1024 if seconds > 75 else 256):
99
+ raise ProjectError("audio_envelope_limit", "語音包絡過多,請縮小預覽區間。", status_code=422)
100
+ store = AgentAudioStore(media.projects, project_id)
101
+ command = [
102
+ "ffmpeg",
103
+ "-v",
104
+ "error",
105
+ "-nostdin",
106
+ "-y",
107
+ "-filter_complex_threads",
108
+ "2",
109
+ "-f",
110
+ "lavfi",
111
+ "-i",
112
+ f"anullsrc=r=48000:cl=stereo:d={seconds}",
113
+ ]
114
+ filters = []
115
+ labels = ["[0:a]"]
116
+ duck_labels = []
117
+ opened = []
118
+ settings = []
72
119
  try:
73
- for index,(clip,layer) in enumerate(layers,1):
74
- context=store.context(layer['asset_id']);fd,asset=open_asset(context,layer['asset_id']);opened.append(fd)
75
- duration=layer['duration_frames']/fps;start=(clip.start_frame+layer['start_frame'])/fps
76
- if start+duration>seconds+.0001 or layer['source_offset_seconds']+duration>asset['duration_seconds']+.0001:
77
- raise ProjectError('agent_audio_out_of_bounds','混音範圍超出來源或影片。',status_code=422)
78
- command+=['-ss',str(layer['source_offset_seconds']),'-t',str(duration),'-i',f'/dev/fd/{fd}']
79
- normalization=max(-18,min(18,-18-asset['rms_db']))
80
- chain=f'[{index}:{asset["stream_index"]}]asetpts=PTS-STARTPTS,aresample=48000,aformat=channel_layouts=stereo,volume={normalization+layer["gain_db"]:.4f}dB'
81
- fade=min(layer['fade_seconds'],duration/2)
82
- if fade:chain+=f',afade=t=in:d={fade:.6f},afade=t=out:st={duration-fade:.6f}:d={fade:.6f}'
83
- chain+=f',adelay={round(start*1000)}|{round(start*1000)}'
84
- chain+=f'[layer{index}]';filters.append(chain)
85
- (duck_labels if layer['duck'] else labels).append(f'[layer{index}]')
86
- settings.append({'layer_id':layer['layer_id'],'start_seconds':start,'duration_seconds':duration,
87
- 'gain_db':layer['gain_db'],'normalization_db':normalization,'duck':layer['duck'],
88
- 'duck_attenuation_db':7 if layer['duck'] and regions else 0})
120
+ for index, (clip, layer) in enumerate(layers, 1):
121
+ context = store.context(layer["asset_id"])
122
+ fd, asset = open_asset(context, layer["asset_id"])
123
+ opened.append(fd)
124
+ duration = layer["duration_frames"] / fps
125
+ start = (clip.start_frame + layer["start_frame"]) / fps
126
+ if (
127
+ start + duration > seconds + 0.0001
128
+ or layer["source_offset_seconds"] + duration > asset["duration_seconds"] + 0.0001
129
+ ):
130
+ raise ProjectError("agent_audio_out_of_bounds", "混音範圍超出來源或影片。", status_code=422)
131
+ command += ["-ss", str(layer["source_offset_seconds"]), "-t", str(duration), "-i", f"/dev/fd/{fd}"]
132
+ normalization = max(-18, min(18, -18 - asset["rms_db"]))
133
+ chain = f"[{index}:{asset['stream_index']}]asetpts=PTS-STARTPTS,aresample=48000,aformat=channel_layouts=stereo,volume={normalization + layer['gain_db']:.4f}dB"
134
+ fade = min(layer["fade_seconds"], duration / 2)
135
+ if fade:
136
+ chain += f",afade=t=in:d={fade:.6f},afade=t=out:st={duration - fade:.6f}:d={fade:.6f}"
137
+ chain += f",adelay={round(start * 1000)}|{round(start * 1000)}"
138
+ chain += f"[layer{index}]"
139
+ filters.append(chain)
140
+ (duck_labels if layer["duck"] else labels).append(f"[layer{index}]")
141
+ settings.append(
142
+ {
143
+ "layer_id": layer["layer_id"],
144
+ "start_seconds": start,
145
+ "duration_seconds": duration,
146
+ "gain_db": layer["gain_db"],
147
+ "normalization_db": normalization,
148
+ "duck": layer["duck"],
149
+ "duck_attenuation_db": 7 if layer["duck"] and regions else 0,
150
+ }
151
+ )
89
152
  if duck_labels:
90
- prefix=''.join(duck_labels)
91
- if len(duck_labels)>1:prefix+=f'amix=inputs={len(duck_labels)}:duration=longest:normalize=0,'
92
- filters.append(prefix+f"volume='{duck_expression(regions)}':eval=frame[ducked]")
93
- labels.append('[ducked]')
94
- filters.append(''.join(labels)+f'amix=inputs={len(labels)}:duration=first:normalize=0[music]')
95
- run_process(command+['-filter_complex',';'.join(filters),'-map','[music]','-c:a','pcm_s16le',str(music)],cancel,pass_fds=tuple(opened),timeout=300)
153
+ prefix = "".join(duck_labels)
154
+ if len(duck_labels) > 1:
155
+ prefix += f"amix=inputs={len(duck_labels)}:duration=longest:normalize=0,"
156
+ filters.append(prefix + f"volume='{duck_expression(regions)}':eval=frame[ducked]")
157
+ labels.append("[ducked]")
158
+ filters.append("".join(labels) + f"amix=inputs={len(labels)}:duration=first:normalize=0[music]")
159
+ run_process(
160
+ command + ["-filter_complex", ";".join(filters), "-map", "[music]", "-c:a", "pcm_s16le", str(music)],
161
+ cancel,
162
+ pass_fds=tuple(opened),
163
+ timeout=300,
164
+ )
96
165
  finally:
97
- for fd in opened:os.close(fd)
98
- return settings,regions
166
+ for fd in opened:
167
+ os.close(fd)
168
+ return settings, regions
99
169
 
100
170
 
101
171
  def mix_program_audio(media, project_id, timeline, base, output, cancel):
102
172
  from clipen.finishing.audio import run_process
173
+
103
174
  from .production_media import atomic_json
104
- seconds=timeline.duration_frames/(timeline.frame_rate.numerator/timeline.frame_rate.denominator)
105
- music=output.with_suffix('.music.wav');camera=output.with_suffix('.camera.wav');final=output.with_suffix('.mix.wav')
106
- settings,regions=render_music_stem(media,project_id,timeline,music,cancel)
107
- run_process(['ffmpeg','-v','error','-nostdin','-y','-i',str(base),'-i',str(music),
108
- '-filter_complex','[0:a][1:a]amix=inputs=2:duration=first:normalize=0,alimiter=limit=0.750:level=0[a]',
109
- '-map','0:v','-map','[a]','-c:v','copy','-c:a','aac','-t',str(seconds),'-movflags','+faststart',str(output)],cancel,timeout=300)
110
- for source,destination in ((base,camera),(output,final)):
111
- run_process(['ffmpeg','-v','error','-nostdin','-y','-i',str(source),'-vn','-ac','2','-ar','48000','-c:a','pcm_s16le',str(destination)],cancel,timeout=120)
112
- measured={name:measure_stem(path) for name,path in (('camera',camera),('music',music),('mix',final))}
113
- issues=[]
114
- if measured['music']['peak_dbfs'] is None or measured['music']['peak_dbfs'] < -50:
115
- issues.append({'code':'music_effectively_silent','message':'渲染後的配樂 stem 幾乎無聲,請調整來源與音量。'})
116
- atomic_json(output.with_suffix('.mix.json'), {'measurements':measured,'layers':settings,
117
- 'dialogue_regions_seconds':regions,'duck_basis':'aligned_source_words' if regions else 'unavailable_no_attenuation',
118
- 'issues':issues,'audio_listened':False,'scope':'Rendered stems and numeric levels; audibility and musical taste still require listening.'})
175
+
176
+ seconds = timeline.duration_frames / (timeline.frame_rate.numerator / timeline.frame_rate.denominator)
177
+ music = output.with_suffix(".music.wav")
178
+ camera = output.with_suffix(".camera.wav")
179
+ final = output.with_suffix(".mix.wav")
180
+ settings, regions = render_music_stem(media, project_id, timeline, music, cancel)
181
+ run_process(
182
+ [
183
+ "ffmpeg",
184
+ "-v",
185
+ "error",
186
+ "-nostdin",
187
+ "-y",
188
+ "-i",
189
+ str(base),
190
+ "-i",
191
+ str(music),
192
+ "-filter_complex",
193
+ "[0:a][1:a]amix=inputs=2:duration=first:normalize=0,alimiter=limit=0.750:level=0[a]",
194
+ "-map",
195
+ "0:v",
196
+ "-map",
197
+ "[a]",
198
+ "-c:v",
199
+ "copy",
200
+ "-c:a",
201
+ "aac",
202
+ "-t",
203
+ str(seconds),
204
+ "-movflags",
205
+ "+faststart",
206
+ str(output),
207
+ ],
208
+ cancel,
209
+ timeout=300,
210
+ )
211
+ for source, destination in ((base, camera), (output, final)):
212
+ run_process(
213
+ [
214
+ "ffmpeg",
215
+ "-v",
216
+ "error",
217
+ "-nostdin",
218
+ "-y",
219
+ "-i",
220
+ str(source),
221
+ "-vn",
222
+ "-ac",
223
+ "2",
224
+ "-ar",
225
+ "48000",
226
+ "-c:a",
227
+ "pcm_s16le",
228
+ str(destination),
229
+ ],
230
+ cancel,
231
+ timeout=120,
232
+ )
233
+ measured = {name: measure_stem(path) for name, path in (("camera", camera), ("music", music), ("mix", final))}
234
+ issues = []
235
+ if measured["music"]["peak_dbfs"] is None or measured["music"]["peak_dbfs"] < -50:
236
+ issues.append({"code": "music_effectively_silent", "message": "渲染後的配樂 stem 幾乎無聲,請調整來源與音量。"})
237
+ atomic_json(
238
+ output.with_suffix(".mix.json"),
239
+ {
240
+ "measurements": measured,
241
+ "layers": settings,
242
+ "dialogue_regions_seconds": regions,
243
+ "duck_basis": "aligned_source_words" if regions else "unavailable_no_attenuation",
244
+ "issues": issues,
245
+ "audio_listened": False,
246
+ "scope": "Rendered stems and numeric levels; audibility and musical taste still require listening.",
247
+ },
248
+ )
@@ -1,27 +1,41 @@
1
1
  """User-selected programme direction, separate from model-authored treatments."""
2
+
2
3
  from clipen.projects import ProjectError
3
4
 
4
5
  PROGRAM_DIRECTION = {
5
- 'format': 'travel_program',
6
- 'title_cards': False,
7
- 'subtitle_style': 'program',
8
- 'direction': '以人物對話、期待、實際體驗與回應串起故事;不用獨立字卡交代行程。',
6
+ "format": "travel_program",
7
+ "title_cards": False,
8
+ "subtitle_style": "program",
9
+ "direction": "以人物對話、期待、實際體驗與回應串起故事;不用獨立字卡交代行程。",
9
10
  }
10
11
 
11
- FULL_PRODUCTION_REQUIREMENTS = {'music': True, 'editing': True, 'transitions': True}
12
+ FULL_PRODUCTION_REQUIREMENTS = {"music": True, "editing": True, "transitions": True}
12
13
 
13
14
 
14
15
  def validate_direction(value):
15
16
  if value is None:
16
17
  return None
17
- if (not isinstance(value, dict) or set(value) not in (set(PROGRAM_DIRECTION),set(PROGRAM_DIRECTION)|{'production_requirements'})
18
- or value['format'] != 'travel_program' or value['title_cards'] is not False
19
- or value['subtitle_style'] != 'program' or not isinstance(value['direction'], str)
20
- or not 1 <= len(value['direction'].strip()) <= 1000):
21
- raise ProjectError('editing_direction_invalid', '節目方向需要明確的格式、字幕樣式與不使用字卡設定。', status_code=422)
22
- requirements=value.get('production_requirements')
23
- if 'production_requirements' in value and (not isinstance(requirements,dict) or set(requirements)!=set(FULL_PRODUCTION_REQUIREMENTS) or any(type(v) is not bool for v in requirements.values())):
24
- raise ProjectError('editing_direction_invalid','後製需求需明確指定 music、editing、transitions。',status_code=422)
18
+ if (
19
+ not isinstance(value, dict)
20
+ or set(value) not in (set(PROGRAM_DIRECTION), set(PROGRAM_DIRECTION) | {"production_requirements"})
21
+ or value["format"] != "travel_program"
22
+ or value["title_cards"] is not False
23
+ or value["subtitle_style"] != "program"
24
+ or not isinstance(value["direction"], str)
25
+ or not 1 <= len(value["direction"].strip()) <= 1000
26
+ ):
27
+ raise ProjectError(
28
+ "editing_direction_invalid", "節目方向需要明確的格式、字幕樣式與不使用字卡設定。", status_code=422
29
+ )
30
+ requirements = value.get("production_requirements")
31
+ if "production_requirements" in value and (
32
+ not isinstance(requirements, dict)
33
+ or set(requirements) != set(FULL_PRODUCTION_REQUIREMENTS)
34
+ or any(type(v) is not bool for v in requirements.values())
35
+ ):
36
+ raise ProjectError(
37
+ "editing_direction_invalid", "後製需求需明確指定 music、editing、transitions。", status_code=422
38
+ )
25
39
  return dict(value)
26
40
 
27
41
 
@@ -30,20 +44,40 @@ def direction_for(tools):
30
44
 
31
45
 
32
46
  def direction_issues(tools):
33
- if direction_for(tools).get('title_cards') is not False:
47
+ if direction_for(tools).get("title_cards") is not False:
34
48
  return []
35
49
  from clipen.domain import TrackKind
36
- issues=[{'code':'title_cards_disabled', 'item_id':i.item_id}
37
- for t in tools._timeline().tracks if t.kind is TrackKind.TITLE and t.track_id not in {'agent-subtitles','program-components'} and not t.track_id.startswith('program-components-') for i in t.items]
50
+
51
+ issues = [
52
+ {"code": "title_cards_disabled", "item_id": i.item_id}
53
+ for t in tools._timeline().tracks
54
+ if t.kind is TrackKind.TITLE
55
+ and t.track_id not in {"agent-subtitles", "program-components"}
56
+ and not t.track_id.startswith("program-components-")
57
+ for i in t.items
58
+ ]
38
59
  from .production_media import load_text_styles
39
- styles=load_text_styles(tools.repository.projects,tools.project_id)
40
- issues += [{'code':'program_subtitle_style_required','item_id':i.item_id}
41
- for t in tools._timeline().tracks if t.track_id=='agent-subtitles' for i in t.items
42
- if styles.get(i.style_id,{}).get('kind')!='program_subtitle']
60
+
61
+ styles = load_text_styles(tools.repository.projects, tools.project_id)
62
+ issues += [
63
+ {"code": "program_subtitle_style_required", "item_id": i.item_id}
64
+ for t in tools._timeline().tracks
65
+ if t.track_id == "agent-subtitles"
66
+ for i in t.items
67
+ if styles.get(i.style_id, {}).get("kind") != "program_subtitle"
68
+ ]
43
69
  from .speech_quality import speech_flags
44
- issues += [{'code':'subtitle_draft_unreliable','item_id':i.item_id,
45
- 'message':'ASR 有可疑重複詞。請以 source_excerpt 選擇可用字串,或移除這段字幕並保留原音。'}
46
- for t in tools._timeline().tracks if t.track_id=='agent-subtitles' for i in t.items
47
- if (p:=styles.get(i.style_id,{})).get('verification')=='asr_draft'
48
- and speech_flags(i.text if p.get('source_excerpt') else p.get('source_text',i.text))]
70
+
71
+ issues += [
72
+ {
73
+ "code": "subtitle_draft_unreliable",
74
+ "item_id": i.item_id,
75
+ "message": "ASR 有可疑重複詞。請以 source_excerpt 選擇可用字串,或移除這段字幕並保留原音。",
76
+ }
77
+ for t in tools._timeline().tracks
78
+ if t.track_id == "agent-subtitles"
79
+ for i in t.items
80
+ if (p := styles.get(i.style_id, {})).get("verification") == "asr_draft"
81
+ and speech_flags(i.text if p.get("source_excerpt") else p.get("source_text", i.text))
82
+ ]
49
83
  return issues
@@ -1,53 +1,91 @@
1
1
  """A source-bound episode treatment; never a synthetic aesthetic score."""
2
+
2
3
  import json
4
+
3
5
  from clipen.domain import TrackKind
4
- from clipen.projects import ProjectError
5
6
  from clipen.finishing.models import digest
6
- from .production_media import atomic_json
7
+ from clipen.projects import ProjectError
8
+
7
9
  from .agent_models import ToolResult
10
+ from .production_media import atomic_json
8
11
 
9
12
 
10
13
  def cut_signature(timeline):
11
- return digest([{'item_id':i.item_id,'start_frame':i.start_frame,'duration_frames':i.duration_frames,
12
- 'source':i.source.span.to_storage(),
13
- 'source_audio_muted':any(e.effect_id=='audio.source' and e.parameters['mode']=='mute' for e in i.effects)}
14
- for t in timeline.tracks if t.kind is TrackKind.VIDEO for i in t.items])
15
-
16
-
17
- def read_episode(projects,project_id,run_id,timeline):
18
- base=projects.root/project_id/'agent-production'
19
- path=base/run_id/'analysis'/'episode.json'
20
- if any(p.is_symlink() for p in (base,base/run_id,base/run_id/'analysis',path)):
21
- raise ProjectError('storage_unsafe','節目規劃路徑不安全。',status_code=409)
22
- if not path.is_file():return None
23
- if path.stat().st_size>128000:raise ProjectError('storage_corrupt','節目規劃超過上限。',status_code=409)
24
- value=json.loads(path.read_text())
25
- return value if value['cut_signature']==cut_signature(timeline) else None
26
-
27
-
28
- def plan_episode(tools,args):
29
- clips={i.item_id:i for i in tools._video().items}
30
- cursor=0;beat_ids=[]
31
- cues={c['cue_id']:c for c in tools._production_list_transcripts({'include_drafts':True}).payload['cues']}
32
- for beat in args['beats']:
33
- if beat['beat_id'] in beat_ids:raise ProjectError('episode_invalid','節目段落 ID 不可重複。',status_code=422)
34
- beat_ids.append(beat['beat_id'])
35
- if any(i not in clips for i in beat['item_ids']):raise ProjectError('episode_invalid','節目段落引用了不在目前剪輯的鏡頭。',status_code=422)
36
- selected=[clips[i] for i in beat['item_ids']]
37
- explicit='start_frame' in beat or 'duration_frames' in beat
38
- if explicit and not {'start_frame','duration_frames'}<=set(beat):
39
- raise ProjectError('episode_invalid','段內敘事時間需要同時提供起點與時長。',status_code=422)
40
- left=beat['start_frame'] if explicit else selected[0].start_frame
41
- right=left+beat['duration_frames'] if explicit else selected[-1].start_frame+selected[-1].duration_frames
42
- overlapping=[i.item_id for i in clips.values() if i.start_frame<right and left<i.start_frame+i.duration_frames]
43
- if left!=cursor or right>tools._timeline().duration_frames or overlapping!=beat['item_ids']:
44
- raise ProjectError('episode_invalid','段落需依序覆蓋時間軸,並引用該範圍內的所有鏡頭;同一連續鏡頭可用明確時間分成不同敘事段落。',status_code=422)
45
- for cue_id in beat['dialogue_ids']:
46
- if cue_id not in cues or cues[cue_id]['item_id'] not in beat['item_ids'] or not (cues[cue_id]['start_frame']<right and left<cues[cue_id]['start_frame']+cues[cue_id]['duration_frames']):
47
- raise ProjectError('episode_invalid','對話證據必須來自這個段落實際保留的完整口語。',status_code=422)
48
- cursor=right
49
- if cursor!=tools._timeline().duration_frames:
50
- raise ProjectError('episode_invalid','每個鏡頭都需要明確的節目用途,不可遺漏或重複歸類。',status_code=422)
51
- value={'authority':'model_authored','cut_signature':cut_signature(tools._timeline()),**args}
52
- atomic_json(tools._workdir('analysis')/'episode.json',value)
53
- return ToolResult({'episode':value,'review_scope':'Source links and treatment only; semantic causality and entertainment value still need review.'})
14
+ return digest(
15
+ [
16
+ {
17
+ "item_id": i.item_id,
18
+ "start_frame": i.start_frame,
19
+ "duration_frames": i.duration_frames,
20
+ "source": i.source.span.to_storage(),
21
+ "source_audio_muted": any(
22
+ e.effect_id == "audio.source" and e.parameters["mode"] == "mute" for e in i.effects
23
+ ),
24
+ }
25
+ for t in timeline.tracks
26
+ if t.kind is TrackKind.VIDEO
27
+ for i in t.items
28
+ ]
29
+ )
30
+
31
+
32
+ def read_episode(projects, project_id, run_id, timeline):
33
+ base = projects.root / project_id / "agent-production"
34
+ path = base / run_id / "analysis" / "episode.json"
35
+ if any(p.is_symlink() for p in (base, base / run_id, base / run_id / "analysis", path)):
36
+ raise ProjectError("storage_unsafe", "節目規劃路徑不安全。", status_code=409)
37
+ if not path.is_file():
38
+ return None
39
+ if path.stat().st_size > 128000:
40
+ raise ProjectError("storage_corrupt", "節目規劃超過上限。", status_code=409)
41
+ value = json.loads(path.read_text())
42
+ return value if value["cut_signature"] == cut_signature(timeline) else None
43
+
44
+
45
+ def plan_episode(tools, args):
46
+ clips = {i.item_id: i for i in tools._video().items}
47
+ cursor = 0
48
+ beat_ids = []
49
+ cues = {c["cue_id"]: c for c in tools._production_list_transcripts({"include_drafts": True}).payload["cues"]}
50
+ for beat in args["beats"]:
51
+ if beat["beat_id"] in beat_ids:
52
+ raise ProjectError("episode_invalid", "節目段落 ID 不可重複。", status_code=422)
53
+ beat_ids.append(beat["beat_id"])
54
+ if any(i not in clips for i in beat["item_ids"]):
55
+ raise ProjectError("episode_invalid", "節目段落引用了不在目前剪輯的鏡頭。", status_code=422)
56
+ selected = [clips[i] for i in beat["item_ids"]]
57
+ explicit = "start_frame" in beat or "duration_frames" in beat
58
+ if explicit and not {"start_frame", "duration_frames"} <= set(beat):
59
+ raise ProjectError("episode_invalid", "段內敘事時間需要同時提供起點與時長。", status_code=422)
60
+ left = beat["start_frame"] if explicit else selected[0].start_frame
61
+ right = left + beat["duration_frames"] if explicit else selected[-1].start_frame + selected[-1].duration_frames
62
+ overlapping = [
63
+ i.item_id for i in clips.values() if i.start_frame < right and left < i.start_frame + i.duration_frames
64
+ ]
65
+ if left != cursor or right > tools._timeline().duration_frames or overlapping != beat["item_ids"]:
66
+ raise ProjectError(
67
+ "episode_invalid",
68
+ "段落需依序覆蓋時間軸,並引用該範圍內的所有鏡頭;同一連續鏡頭可用明確時間分成不同敘事段落。",
69
+ status_code=422,
70
+ )
71
+ for cue_id in beat["dialogue_ids"]:
72
+ if (
73
+ cue_id not in cues
74
+ or cues[cue_id]["item_id"] not in beat["item_ids"]
75
+ or not (
76
+ cues[cue_id]["start_frame"] < right
77
+ and left < cues[cue_id]["start_frame"] + cues[cue_id]["duration_frames"]
78
+ )
79
+ ):
80
+ raise ProjectError("episode_invalid", "對話證據必須來自這個段落實際保留的完整口語。", status_code=422)
81
+ cursor = right
82
+ if cursor != tools._timeline().duration_frames:
83
+ raise ProjectError("episode_invalid", "每個鏡頭都需要明確的節目用途,不可遺漏或重複歸類。", status_code=422)
84
+ value = {"authority": "model_authored", "cut_signature": cut_signature(tools._timeline()), **args}
85
+ atomic_json(tools._workdir("analysis") / "episode.json", value)
86
+ return ToolResult(
87
+ {
88
+ "episode": value,
89
+ "review_scope": "Source links and treatment only; semantic causality and entertainment value still need review.",
90
+ }
91
+ )