@clipen/clipen-cli 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -2
  3. package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
  4. package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
  5. package/apps/web/dist/favicon.svg +1 -0
  6. package/apps/web/dist/index.html +16 -0
  7. package/bin/clipen.js +157 -0
  8. package/clipen +18 -0
  9. package/install +25 -0
  10. package/package.json +55 -4
  11. package/pyproject.toml +44 -0
  12. package/requirements/asr-runtime.txt +13 -0
  13. package/requirements/dev.txt +2 -0
  14. package/requirements/runtime.txt +20 -0
  15. package/src/clipen/__init__.py +3 -0
  16. package/src/clipen/analysis/__init__.py +89 -0
  17. package/src/clipen/analysis/artifacts.py +410 -0
  18. package/src/clipen/analysis/audio.py +394 -0
  19. package/src/clipen/analysis/evidence.py +102 -0
  20. package/src/clipen/analysis/evidence_service.py +929 -0
  21. package/src/clipen/analysis/image_similarity.py +134 -0
  22. package/src/clipen/analysis/keyframes.py +159 -0
  23. package/src/clipen/analysis/models.py +228 -0
  24. package/src/clipen/analysis/qwen_worker.py +594 -0
  25. package/src/clipen/analysis/resources.py +22 -0
  26. package/src/clipen/analysis/runtime.py +62 -0
  27. package/src/clipen/analysis/service.py +594 -0
  28. package/src/clipen/analysis/setup.py +921 -0
  29. package/src/clipen/analysis/setup_cli.py +107 -0
  30. package/src/clipen/analysis/storage.py +1864 -0
  31. package/src/clipen/analysis/transcription.py +906 -0
  32. package/src/clipen/analysis/visual.py +237 -0
  33. package/src/clipen/annotations/__init__.py +13 -0
  34. package/src/clipen/annotations/models.py +22 -0
  35. package/src/clipen/annotations/storage.py +428 -0
  36. package/src/clipen/annotations/suggestions.py +115 -0
  37. package/src/clipen/asr_release.py +132 -0
  38. package/src/clipen/bootstrap.py +978 -0
  39. package/src/clipen/candidates.py +222 -0
  40. package/src/clipen/cli.py +84 -0
  41. package/src/clipen/controller/__init__.py +17 -0
  42. package/src/clipen/controller/app.py +1657 -0
  43. package/src/clipen/controller/server.py +533 -0
  44. package/src/clipen/domain/__init__.py +30 -0
  45. package/src/clipen/domain/errors.py +5 -0
  46. package/src/clipen/domain/media_time.py +110 -0
  47. package/src/clipen/domain/timeline.py +582 -0
  48. package/src/clipen/domain/validation.py +14 -0
  49. package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
  50. package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
  51. package/src/clipen/editing/README.md +115 -0
  52. package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
  53. package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
  54. package/src/clipen/editing/__init__.py +15 -0
  55. package/src/clipen/editing/agent.py +13 -0
  56. package/src/clipen/editing/agent_models.py +127 -0
  57. package/src/clipen/editing/agent_repository.py +978 -0
  58. package/src/clipen/editing/agent_tools.py +613 -0
  59. package/src/clipen/editing/alignment.py +150 -0
  60. package/src/clipen/editing/alignment_setup.py +156 -0
  61. package/src/clipen/editing/alignment_worker.py +24 -0
  62. package/src/clipen/editing/change_report.py +128 -0
  63. package/src/clipen/editing/compiler.py +40 -0
  64. package/src/clipen/editing/component_looks.py +131 -0
  65. package/src/clipen/editing/component_review.py +74 -0
  66. package/src/clipen/editing/coordinator.py +497 -0
  67. package/src/clipen/editing/editorial_review.py +309 -0
  68. package/src/clipen/editing/evidence_jobs.py +552 -0
  69. package/src/clipen/editing/history_changes.py +192 -0
  70. package/src/clipen/editing/music_choices.py +18 -0
  71. package/src/clipen/editing/production_catalog.py +629 -0
  72. package/src/clipen/editing/production_limits.py +85 -0
  73. package/src/clipen/editing/production_media.py +435 -0
  74. package/src/clipen/editing/production_preview.py +373 -0
  75. package/src/clipen/editing/production_progress.py +236 -0
  76. package/src/clipen/editing/production_requirements.py +117 -0
  77. package/src/clipen/editing/production_tools.py +1198 -0
  78. package/src/clipen/editing/program_audio.py +248 -0
  79. package/src/clipen/editing/program_direction.py +83 -0
  80. package/src/clipen/editing/program_story.py +91 -0
  81. package/src/clipen/editing/program_subtitles.py +232 -0
  82. package/src/clipen/editing/programme_review.py +121 -0
  83. package/src/clipen/editing/prompt_history.py +84 -0
  84. package/src/clipen/editing/recut.py +167 -0
  85. package/src/clipen/editing/refinement_references.py +278 -0
  86. package/src/clipen/editing/resolve_export.py +847 -0
  87. package/src/clipen/editing/resolve_titles.py +291 -0
  88. package/src/clipen/editing/skill_tools.py +951 -0
  89. package/src/clipen/editing/source_dialogue.py +192 -0
  90. package/src/clipen/editing/speech_coverage.py +50 -0
  91. package/src/clipen/editing/speech_quality.py +11 -0
  92. package/src/clipen/editing/tool_receipts.py +98 -0
  93. package/src/clipen/editing/versions.py +219 -0
  94. package/src/clipen/editing/visual_preview.py +189 -0
  95. package/src/clipen/editing/workbench.py +136 -0
  96. package/src/clipen/filesystem.py +25 -0
  97. package/src/clipen/finishing/README.md +103 -0
  98. package/src/clipen/finishing/__init__.py +1 -0
  99. package/src/clipen/finishing/audio.py +188 -0
  100. package/src/clipen/finishing/catalog.py +264 -0
  101. package/src/clipen/finishing/models.py +14 -0
  102. package/src/clipen/finishing/renderer.py +45 -0
  103. package/src/clipen/mcp_editing/__init__.py +5 -0
  104. package/src/clipen/mcp_editing/__main__.py +42 -0
  105. package/src/clipen/mcp_editing/server.py +396 -0
  106. package/src/clipen/media/__init__.py +50 -0
  107. package/src/clipen/media/discovery.py +253 -0
  108. package/src/clipen/media/models.py +349 -0
  109. package/src/clipen/media/preview.py +137 -0
  110. package/src/clipen/media/probe.py +418 -0
  111. package/src/clipen/media/service.py +304 -0
  112. package/src/clipen/media/storage.py +694 -0
  113. package/src/clipen/music_vocabulary.py +34 -0
  114. package/src/clipen/power.py +28 -0
  115. package/src/clipen/projects/__init__.py +26 -0
  116. package/src/clipen/projects/agent_schema.py +94 -0
  117. package/src/clipen/projects/annotation_schema.py +40 -0
  118. package/src/clipen/projects/deletion.py +256 -0
  119. package/src/clipen/projects/evidence_schema.py +52 -0
  120. package/src/clipen/projects/finishing_schema.py +36 -0
  121. package/src/clipen/projects/models.py +189 -0
  122. package/src/clipen/projects/picker.py +232 -0
  123. package/src/clipen/projects/preview_schema.py +29 -0
  124. package/src/clipen/projects/service.py +159 -0
  125. package/src/clipen/projects/storage.py +1458 -0
  126. package/src/clipen/projects/timeline_schema.py +32 -0
  127. package/src/clipen/projects/validation_schema.py +28 -0
  128. package/src/clipen/provider_registry.py +77 -0
  129. package/src/clipen/providers/__init__.py +43 -0
  130. package/src/clipen/providers/account.py +245 -0
  131. package/src/clipen/providers/claude.py +409 -0
  132. package/src/clipen/providers/claude_editing.py +118 -0
  133. package/src/clipen/providers/codex.py +991 -0
  134. package/src/clipen/providers/codex_editing.py +91 -0
  135. package/src/clipen/providers/editing_agent.py +567 -0
  136. package/src/clipen/providers/errors.py +51 -0
  137. package/src/clipen/providers/recovery.py +269 -0
  138. package/src/clipen/py.typed +1 -0
  139. package/src/clipen/rendering/__init__.py +12 -0
  140. package/src/clipen/rendering/cover.py +139 -0
  141. package/src/clipen/rendering/custom_components.py +328 -0
  142. package/src/clipen/rendering/custom_render.py +218 -0
  143. package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
  144. package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
  145. package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
  146. package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
  147. package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
  148. package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
  149. package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
  150. package/src/clipen/rendering/fonts/manifest.json +145 -0
  151. package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
  152. package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
  153. package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
  154. package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
  155. package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
  156. package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
  157. package/src/clipen/rendering/production_effects.py +96 -0
  158. package/src/clipen/rendering/program_components.py +254 -0
  159. package/src/clipen/rendering/program_creator.py +804 -0
  160. package/src/clipen/rendering/program_identities.py +350 -0
  161. package/src/clipen/rendering/program_motion.py +186 -0
  162. package/src/clipen/rendering/program_studio.py +227 -0
  163. package/src/clipen/rendering/program_styles.py +321 -0
  164. package/src/clipen/rendering/program_subtitles.py +89 -0
  165. package/src/clipen/rendering/renderer.py +737 -0
  166. package/src/clipen/rendering/storage.py +230 -0
  167. package/src/clipen/rendering/titles.py +467 -0
  168. package/src/clipen/skills/__init__.py +5 -0
  169. package/src/clipen/skills/builtin/SKILL.md +72 -0
  170. package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
  171. package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
  172. package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
  173. package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
  174. package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
  175. package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
  176. package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
  177. package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
  178. package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
  179. package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
  180. package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
  181. package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
  182. package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
  183. package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
  184. package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
  185. package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
  186. package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
  187. package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
  188. package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
  189. package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
  190. package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
  191. package/src/clipen/skills/builtin/components.json +133 -0
  192. package/src/clipen/skills/builtin/font_sources.json +20 -0
  193. package/src/clipen/skills/builtin/font_styles.json +329 -0
  194. package/src/clipen/skills/builtin/manifest.json +32 -0
  195. package/src/clipen/skills/builtin/presets.json +8 -0
  196. package/src/clipen/skills/builtin/references/captions.md +14 -0
  197. package/src/clipen/skills/builtin/references/channel-design.md +37 -0
  198. package/src/clipen/skills/builtin/references/editing.md +30 -0
  199. package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
  200. package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
  201. package/src/clipen/skills/builtin/references/graphics.md +59 -0
  202. package/src/clipen/skills/builtin/references/review.md +16 -0
  203. package/src/clipen/skills/builtin/references/sound.md +8 -0
  204. package/src/clipen/skills/builtin/references/story.md +7 -0
  205. package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
  206. package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
  207. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
  208. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
  209. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
  210. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
  211. package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
  212. package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
  213. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
  214. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
  215. package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
  216. package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
  217. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
  218. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
  219. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
  220. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
  221. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
  222. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
  223. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
  224. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
  225. package/src/clipen/skills/builtin/templates.json +284 -0
  226. package/src/clipen/skills/builtin/visual_styles.json +1074 -0
  227. package/src/clipen/skills/catalog.py +314 -0
  228. package/src/clipen/skills/library.py +137 -0
  229. package/src/clipen/skills/package.py +254 -0
  230. package/src/clipen/skills/visual_styles.py +55 -0
  231. package/src/clipen/workspace.py +181 -0
  232. package/uninstall +25 -0
@@ -0,0 +1,248 @@
1
+ """Bounded dialogue-driven envelopes and inspectable stems for skill productions."""
2
+
3
+ import math
4
+ import os
5
+ import sys
6
+ import wave
7
+ from array import array
8
+ from types import SimpleNamespace
9
+
10
+ from clipen.domain import MediaClip
11
+ from clipen.projects import ProjectError
12
+
13
+
14
+ def dialogue_regions(projects, project_id, timeline):
15
+ from .evidence_jobs import local_cues
16
+ from .production_media import transcript_cues
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", []))
27
+ # Legacy long ASR windows are deliberately not treated as speech activity.
28
+ # Missing activity leaves music at its chosen gain instead of permanently
29
+ # compressing it under noise. Report that limitation in the mix evidence.
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))
36
+ return merged
37
+
38
+
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
+ ]
46
+ return f"pow(10,-{attenuation_db}*min(1,({'+'.join(pieces)}))/20)"
47
+
48
+
49
+ def measure_stem(path):
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
+ }
76
+
77
+
78
+ def render_music_stem(media, project_id, timeline, music, cancel):
79
+ """Write the music and effects under dialogue as one PCM stem; returns its settings and speech regions."""
80
+ from clipen.finishing.audio import open_asset, run_process
81
+
82
+ from .production_media import AgentAudioStore
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 = []
119
+ try:
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
+ )
152
+ if duck_labels:
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
+ )
165
+ finally:
166
+ for fd in opened:
167
+ os.close(fd)
168
+ return settings, regions
169
+
170
+
171
+ def mix_program_audio(media, project_id, timeline, base, output, cancel):
172
+ from clipen.finishing.audio import run_process
173
+
174
+ from .production_media import atomic_json
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
+ )
@@ -0,0 +1,83 @@
1
+ """User-selected programme direction, separate from model-authored treatments."""
2
+
3
+ from clipen.projects import ProjectError
4
+
5
+ PROGRAM_DIRECTION = {
6
+ "format": "travel_program",
7
+ "title_cards": False,
8
+ "subtitle_style": "program",
9
+ "direction": "以人物對話、期待、實際體驗與回應串起故事;不用獨立字卡交代行程。",
10
+ }
11
+
12
+ FULL_PRODUCTION_REQUIREMENTS = {"music": True, "editing": True, "transitions": True}
13
+
14
+
15
+ def validate_direction(value):
16
+ if value is None:
17
+ return None
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
+ )
39
+ return dict(value)
40
+
41
+
42
+ def direction_for(tools):
43
+ return tools.repository.creative_direction(tools.project_id, tools.run_id)
44
+
45
+
46
+ def direction_issues(tools):
47
+ if direction_for(tools).get("title_cards") is not False:
48
+ return []
49
+ from clipen.domain import TrackKind
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
+ ]
59
+ from .production_media import load_text_styles
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
+ ]
69
+ from .speech_quality import speech_flags
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
+ ]
83
+ return issues
@@ -0,0 +1,91 @@
1
+ """A source-bound episode treatment; never a synthetic aesthetic score."""
2
+
3
+ import json
4
+
5
+ from clipen.domain import TrackKind
6
+ from clipen.finishing.models import digest
7
+ from clipen.projects import ProjectError
8
+
9
+ from .agent_models import ToolResult
10
+ from .production_media import atomic_json
11
+
12
+
13
+ def cut_signature(timeline):
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
+ )
@@ -0,0 +1,232 @@
1
+ """Source-linked programme captions; draft ASR never becomes human approval."""
2
+
3
+ import math
4
+ import re
5
+ import unicodedata
6
+
7
+ from clipen.domain import TextClip
8
+ from clipen.finishing.models import digest
9
+ from clipen.projects import ProjectError
10
+
11
+ from .production_media import atomic_json, load_text_styles, text_style_path
12
+
13
+
14
+ def make_subtitle_items(tools, cue, row):
15
+ text = row["text"].strip()
16
+ if not text:
17
+ raise ProjectError("agent_input_invalid", "字幕不可空白。", status_code=422)
18
+
19
+ def spoken_content(value):
20
+ return "".join(
21
+ c.casefold() for c in unicodedata.normalize("NFKC", value) if unicodedata.category(c)[0] not in "PZC"
22
+ )
23
+
24
+ original = cue
25
+ excerpt = row.get("source_excerpt")
26
+ source_text = cue["text"]
27
+ if excerpt:
28
+ left, right = excerpt["start"], excerpt["end"]
29
+ if not 0 <= left < right <= len(source_text):
30
+ raise ProjectError("subtitle_source_mismatch", "字幕引用字元範圍超出來源句。", status_code=422)
31
+ begin = cue["duration_frames"] * left // len(source_text)
32
+ end = cue["duration_frames"] * right // len(source_text)
33
+ cue = {
34
+ **cue,
35
+ "text": source_text[left:right],
36
+ "start_frame": cue["start_frame"] + begin,
37
+ "duration_frames": end - begin,
38
+ }
39
+ if (excerpt or cue.get("verification") == "asr_draft") and spoken_content(text) != spoken_content(cue["text"]):
40
+ raise ProjectError(
41
+ "subtitle_source_mismatch",
42
+ "未核對字幕草稿可以調整標點與分句,不能改寫原話內容或加入新事實;請先核對來源逐字稿。",
43
+ status_code=422,
44
+ )
45
+ from .speech_quality import speech_flags
46
+
47
+ if cue.get("verification") == "asr_draft" and speech_flags(text):
48
+ raise ProjectError(
49
+ "subtitle_draft_unreliable",
50
+ "這段 ASR 有可疑的連續重複詞,不能直接作為字幕。請用 source_excerpt 引用原句中可用的部分,或略過這段字幕並保留原音;不可編造替代台詞。",
51
+ status_code=422,
52
+ )
53
+ # Page boundaries are an explicit estimate inside the original ASR segment,
54
+ # not invented word-level alignment. The original audio remains untouched.
55
+ spans = []
56
+ cursor = 0
57
+ for match in re.finditer(r"[^,,。!?!?;;]+[,,。!?!?;;]*", text):
58
+ end = match.end()
59
+ phrase = text[cursor:end]
60
+ count = max(1, math.ceil(len(phrase) / 18))
61
+ spans.extend((cursor + len(phrase) * n // count, cursor + len(phrase) * (n + 1) // count) for n in range(count))
62
+ cursor = end
63
+ if cursor < len(text):
64
+ spans.append((cursor, len(text)))
65
+ pages = []
66
+ for left, right in spans:
67
+ if pages and pages[-1][1] - pages[-1][0] < 6 and right - pages[-1][0] <= 18:
68
+ pages[-1] = (pages[-1][0], right)
69
+ else:
70
+ pages.append((left, right))
71
+ if cue["duration_frames"] < len(pages):
72
+ raise ProjectError("subtitle_too_short", "口語時間不足以顯示分句字幕。", status_code=422)
73
+ aligned = None
74
+ if original.get("words"):
75
+ frame_rate = tools._timeline().frame_rate
76
+ aligned = aligned_pages(original, text, excerpt, pages, frame_rate.numerator / frame_rate.denominator)
77
+ pages = [(left, right) for left, right, _, _ in aligned]
78
+ styles = load_text_styles(tools.repository.projects, tools.project_id)
79
+ items = []
80
+ for n, (left, right) in enumerate(pages):
81
+ start = cue["start_frame"] + cue["duration_frames"] * left // len(text)
82
+ end = cue["start_frame"] + cue["duration_frames"] * right // len(text)
83
+ if aligned:
84
+ start, end = aligned[n][2:]
85
+ delivery = row.get("delivery", "dialogue")
86
+ profile = {
87
+ "kind": "program_subtitle",
88
+ "font_size_ratio": 0.075 if delivery == "punchline" else 0.05 if delivery == "quiet" else 0.06,
89
+ "delivery": delivery,
90
+ "emphasis": [s for s in row.get("emphasis", []) if s in text[left:right]],
91
+ "verification": cue.get("verification", "reviewed_source"),
92
+ "source_revision_id": cue.get("source_revision_id"),
93
+ "segment_id": cue.get("segment_id"),
94
+ "source": cue.get("source"),
95
+ "source_text": source_text,
96
+ "source_excerpt": excerpt,
97
+ "cue_id": cue["cue_id"],
98
+ "anchor_item_id": original.get("item_id"),
99
+ "timing_basis": "forced_alignment"
100
+ if aligned
101
+ else "character_proportional_within_asr_segment"
102
+ if excerpt or len(pages) > 1
103
+ else "asr_segment",
104
+ "caption_text_edited": text != original["text"],
105
+ "motion": "none" if delivery == "quiet" else "pop",
106
+ }
107
+ profile.update(
108
+ {
109
+ key: original[key]
110
+ for key in ("wording_authority", "source_asr_text", "correction_evidence")
111
+ if key in original
112
+ }
113
+ )
114
+ skill = tools._skill_value()
115
+ preset = skill["presets"]["subtitle"]
116
+ profile.update(
117
+ {
118
+ "font_size_ratio": preset["font_size_ratio"]
119
+ * (1.25 if delivery == "punchline" else 0.9 if delivery == "quiet" else 1),
120
+ "emphasis_color": preset["emphasis_color"],
121
+ "outline_color": preset["outline_color"],
122
+ "skill_hash": skill["content_hash"],
123
+ }
124
+ )
125
+ identifier = "agent.text." + digest(profile)[:24]
126
+ styles[identifier] = profile
127
+ items.append(
128
+ TextClip("subtitle-" + cue["cue_id"] + "-" + str(n), start, end - start, text[left:right], identifier)
129
+ )
130
+ from .production_limits import limits_for
131
+
132
+ if len(styles) > max(256, limits_for(tools).titles * 2):
133
+ raise ProjectError("agent_input_invalid", "自訂字幕樣式索引超過上限。", status_code=422)
134
+ atomic_json(text_style_path(tools.repository.projects, tools.project_id), styles)
135
+ return items
136
+
137
+
138
+ def aligned_pages(cue, text, excerpt, pages, fps=30):
139
+ """Snap display page boundaries to actual words; pauses get no invented duration."""
140
+ from .alignment import significant
141
+
142
+ original = cue["text"]
143
+ left, right = (excerpt["start"], excerpt["end"]) if excerpt else (0, len(original))
144
+ if significant(text) != significant(original[left:right]):
145
+ raise ProjectError("subtitle_alignment_text_changed", "文字已改變,請重新對齊後再建立字幕。", status_code=422)
146
+ words = [w for w in cue["words"] if w["char_end"] > left and w["char_start"] < right]
147
+ if not words or words[0]["char_start"] < left or words[-1]["char_end"] > right:
148
+ raise ProjectError(
149
+ "subtitle_word_boundary_required", "摘錄需包含完整對齊字詞,不能在詞內估算時間。", status_code=422
150
+ )
151
+ display_positions = [n for n, c in enumerate(text) if significant(c)]
152
+ start_count = len(significant(original[:left]))
153
+ counts = [
154
+ (
155
+ len(significant(original[: w["char_start"]])) - start_count,
156
+ len(significant(original[: w["char_end"]])) - start_count,
157
+ w,
158
+ )
159
+ for w in words
160
+ ]
161
+ endings = set()
162
+ for previous, following in zip(counts, counts[1:]):
163
+ if following[2]["start_frame"] - previous[2]["end_frame"] > 0.6 * fps:
164
+ endings.add(previous[1])
165
+ for _, end in pages:
166
+ desired = len(significant(text[:end]))
167
+ ending = next((b for a, b, _ in counts if b >= desired), len(display_positions))
168
+ endings.add(ending)
169
+ endings.add(len(display_positions))
170
+ result = []
171
+ previous = 0
172
+ previous_count = 0
173
+ for count in sorted(endings):
174
+ if count <= previous_count:
175
+ continue
176
+ end = display_positions[count] if count < len(display_positions) else len(text)
177
+ included = [word for a, b, word in counts if a >= previous_count and b <= count]
178
+ if not included:
179
+ raise ProjectError("subtitle_alignment_incomplete", "分頁沒有完整對齊字詞。", status_code=422)
180
+ first, last = included[0]["start_frame"], included[-1]["end_frame"]
181
+ if last <= first:
182
+ raise ProjectError("subtitle_too_short", "對齊字詞不足一格,請調整分句。", status_code=422)
183
+ result.append((previous, end, first, last))
184
+ previous = end
185
+ previous_count = count
186
+ # Word evidence can put pauses inside a short phrase (我 / 們, 伴手 / 禮).
187
+ # Join tiny pages using the existing first/last word boundaries; no word
188
+ # timestamps are stretched or estimated, and long pauses remain separate.
189
+ merged = []
190
+ for current in result:
191
+ if merged:
192
+ before = merged[-1]
193
+ short = (
194
+ min(len(significant(text[before[0] : before[1]])), len(significant(text[current[0] : current[1]]))) <= 5
195
+ )
196
+ sentence_end = text[before[0] : before[1]].rstrip().endswith(("。", "!", "?", "!", "?", "."))
197
+ tiny_reply = len(significant(text[current[0] : current[1]])) <= 1
198
+ if (
199
+ short
200
+ and (not sentence_end or tiny_reply)
201
+ and current[2] - before[3] < 1.5 * fps
202
+ and len(significant(text[before[0] : current[1]])) <= 18
203
+ ):
204
+ merged[-1] = (before[0], current[1], before[2], current[3])
205
+ continue
206
+ merged.append(current)
207
+ return merged
208
+
209
+
210
+ def subtitle_status(projects, project_id, timeline):
211
+ from clipen.domain import TrackKind
212
+
213
+ styles = load_text_styles(projects, project_id)
214
+ items = [
215
+ i for t in timeline.tracks if t.kind is TrackKind.TITLE and t.track_id == "agent-subtitles" for i in t.items
216
+ ]
217
+ drafts = [i.item_id for i in items if styles.get(i.style_id, {}).get("verification") == "asr_draft"]
218
+ aligned = [i.item_id for i in items if styles.get(i.style_id, {}).get("timing_basis") == "forced_alignment"]
219
+ manual = [i.item_id for i in items if styles.get(i.style_id, {}).get("timing_basis") == "user_adjusted"]
220
+ timed = set(aligned + manual)
221
+ unaligned = [i.item_id for i in items if i.item_id not in timed]
222
+ return {
223
+ "count": len(items),
224
+ "draft_count": len(drafts),
225
+ "draft_item_ids": drafts,
226
+ "unaligned_item_ids": unaligned,
227
+ "aligned_count": len(aligned),
228
+ "manual_timing_item_ids": manual,
229
+ "manual_timing_count": len(manual),
230
+ "audio_listened": False,
231
+ "review_scope": "Source-linked draft captions are not human-verified transcription.",
232
+ }