@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,226 +1,435 @@
1
1
  """Project-owned audio evidence, exact source sampling and local mix execution."""
2
- from fractions import Fraction
2
+
3
3
  import json
4
4
  import math
5
5
  import os
6
- from pathlib import Path
7
6
  import secrets
7
+ from fractions import Fraction
8
+ from pathlib import Path
8
9
 
9
10
  from clipen.domain import MediaClip, TrackKind
10
- from clipen.projects import ProjectError
11
11
  from clipen.finishing.audio import open_asset, run_process
12
12
  from clipen.finishing.models import digest, encoded
13
+ from clipen.projects import ProjectError
13
14
 
14
15
 
15
- def atomic_json(path,value):
16
- if path.is_symlink():raise ProjectError('storage_unsafe','製作檔案不安全。',status_code=409)
17
- temporary=path.parent/('.write-'+secrets.token_hex(16))
16
+ def atomic_json(path, value):
17
+ if path.is_symlink():
18
+ raise ProjectError("storage_unsafe", "製作檔案不安全。", status_code=409)
19
+ temporary = path.parent / (".write-" + secrets.token_hex(16))
18
20
  try:
19
- fd=os.open(temporary,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
20
- with os.fdopen(fd,'w') as out:
21
- out.write(encoded(value));out.flush();os.fsync(out.fileno())
22
- os.replace(temporary,path)
23
- finally:temporary.unlink(missing_ok=True)
21
+ fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
22
+ with os.fdopen(fd, "w") as out:
23
+ out.write(encoded(value))
24
+ out.flush()
25
+ os.fsync(out.fileno())
26
+ os.replace(temporary, path)
27
+ finally:
28
+ temporary.unlink(missing_ok=True)
24
29
 
25
30
 
26
31
  class AgentAudioStore:
27
- def __init__(self,projects,project_id):
28
- self.directory=projects.root/project_id/'agent-audio'
29
- if self.directory.is_symlink():raise ProjectError('storage_unsafe','音訊目錄不安全。',status_code=409)
30
- self.directory.mkdir(mode=0o700,exist_ok=True)
31
- self.manifest=self.directory/'assets.json'
32
+ def __init__(self, projects, project_id):
33
+ self.directory = projects.root / project_id / "agent-audio"
34
+ if self.directory.is_symlink():
35
+ raise ProjectError("storage_unsafe", "音訊目錄不安全。", status_code=409)
36
+ self.directory.mkdir(mode=0o700, exist_ok=True)
37
+ self.manifest = self.directory / "assets.json"
32
38
 
33
39
  def records(self):
34
- if self.manifest.is_symlink():raise ProjectError('storage_unsafe','音訊索引不安全。',status_code=409)
35
- if not self.manifest.exists():return []
36
- if self.manifest.stat().st_size>8*1024*1024:raise ProjectError('storage_corrupt','音訊索引超過上限。',status_code=409)
40
+ if self.manifest.is_symlink():
41
+ raise ProjectError("storage_unsafe", "音訊索引不安全。", status_code=409)
42
+ if not self.manifest.exists():
43
+ return []
44
+ if self.manifest.stat().st_size > 8 * 1024 * 1024:
45
+ raise ProjectError("storage_corrupt", "音訊索引超過上限。", status_code=409)
37
46
  return json.loads(self.manifest.read_text())
38
47
 
39
- def add(self,assets,reference):
40
- records=self.records();known={r['asset']['asset_id'] for r in records}
41
- records.extend({'asset':a,'reference':reference} for a in assets if a['asset_id'] not in known)
42
- if len(records)>48:raise ProjectError('agent_audio_limit','這個作品已達 48 個音訊候選上限。',status_code=409)
43
- atomic_json(self.manifest,records)
48
+ def add(self, assets, reference):
49
+ records = self.records()
50
+ known = {r["asset"]["asset_id"] for r in records}
51
+ records.extend({"asset": a, "reference": reference} for a in assets if a["asset_id"] not in known)
52
+ if len(records) > 48:
53
+ raise ProjectError("agent_audio_limit", "這個作品已達 48 個音訊候選上限。", status_code=409)
54
+ atomic_json(self.manifest, records)
44
55
 
45
56
  def public_assets(self):
46
- return [{k:v for k,v in r['asset'].items() if k not in {'relative_path','fingerprint','mtime_ns','size_bytes'}} for r in self.records()]
57
+ return [
58
+ {k: v for k, v in r["asset"].items() if k not in {"relative_path", "fingerprint", "mtime_ns", "size_bytes"}}
59
+ for r in self.records()
60
+ ]
47
61
 
48
- def context(self,asset_id):
49
- record=next((r for r in self.records() if r['asset']['asset_id']==asset_id),None)
50
- if record is None:raise ProjectError('agent_audio_missing','找不到這個作品已取得的音訊。',status_code=404)
51
- asset=record['asset'];reference=record['reference']
52
- path=Path(reference['canonical_path'])
53
- if path.parent!=self.directory or path.is_symlink():raise ProjectError('storage_unsafe','音訊來源不在本作品的管理範圍。',status_code=409)
54
- return {'assets':[asset],'directories':{asset['role']:reference}}
62
+ def context(self, asset_id):
63
+ record = next((r for r in self.records() if r["asset"]["asset_id"] == asset_id), None)
64
+ if record is None:
65
+ raise ProjectError("agent_audio_missing", "找不到這個作品已取得的音訊。", status_code=404)
66
+ asset = record["asset"]
67
+ reference = record["reference"]
68
+ path = Path(reference["canonical_path"])
69
+ if path.parent != self.directory or path.is_symlink():
70
+ raise ProjectError("storage_unsafe", "音訊來源不在本作品的管理範圍。", status_code=409)
71
+ return {"assets": [asset], "directories": {asset["role"]: reference}}
55
72
 
56
73
 
57
- def sample_frames(media,project_id,span,offsets,directory,cancel):
58
- source=media.open(project_id,span.version_id)
59
- paths=[];manifest=[]
74
+ def sample_frames(media, project_id, span, offsets, directory, cancel):
75
+ source = media.open(project_id, span.version_id)
76
+ paths = []
77
+ manifest = []
60
78
  try:
61
79
  if span.stream_index not in source.video_stream_indices:
62
- raise ProjectError('agent_video_missing','指定來源沒有這個影像串流。',status_code=409)
63
- unit=Fraction(span.time_base.numerator,span.time_base.denominator)
80
+ raise ProjectError("agent_video_missing", "指定來源沒有這個影像串流。", status_code=409)
81
+ unit = Fraction(span.time_base.numerator, span.time_base.denominator)
64
82
  for offset in offsets:
65
- seconds=int(span.start_pts)*unit+Fraction(str(offset))
66
- path=directory/('frame-'+secrets.token_hex(12)+'.png')
67
- run_process(['ffmpeg','-v','error','-nostdin','-seek_timestamp','1','-ss',f'{float(seconds):.9f}',
68
- '-i',f'/dev/fd/{source.descriptor}','-map',f'0:{span.stream_index}',
69
- '-frames:v','1','-vf','scale=640:-2','-threads','1',str(path)],cancel,pass_fds=(source.descriptor,),timeout=30)
70
- if not path.is_file() or not path.stat().st_size:raise ProjectError('agent_sample_missing','取樣時間沒有可解碼畫面。',status_code=409)
71
- paths.append(path);manifest.append({'offset_seconds':offset,'source_seconds':float(seconds),'version_id':span.version_id})
72
- finally:source.close()
73
- return tuple(paths),manifest
74
-
75
-
76
- def transcript_cues(projects,project_id,timeline,*,include_drafts=False):
83
+ seconds = int(span.start_pts) * unit + Fraction(str(offset))
84
+ path = directory / ("frame-" + secrets.token_hex(12) + ".png")
85
+ run_process(
86
+ [
87
+ "ffmpeg",
88
+ "-v",
89
+ "error",
90
+ "-nostdin",
91
+ "-seek_timestamp",
92
+ "1",
93
+ "-ss",
94
+ f"{float(seconds):.9f}",
95
+ "-i",
96
+ f"/dev/fd/{source.descriptor}",
97
+ "-map",
98
+ f"0:{span.stream_index}",
99
+ "-frames:v",
100
+ "1",
101
+ "-vf",
102
+ "scale=640:-2",
103
+ "-threads",
104
+ "1",
105
+ str(path),
106
+ ],
107
+ cancel,
108
+ pass_fds=(source.descriptor,),
109
+ timeout=30,
110
+ )
111
+ if not path.is_file() or not path.stat().st_size:
112
+ raise ProjectError("agent_sample_missing", "取樣時間沒有可解碼畫面。", status_code=409)
113
+ paths.append(path)
114
+ manifest.append({"offset_seconds": offset, "source_seconds": float(seconds), "version_id": span.version_id})
115
+ finally:
116
+ source.close()
117
+ return tuple(paths), manifest
118
+
119
+
120
+ def transcript_cues(projects, project_id, timeline, *, include_drafts=False):
77
121
  from .speech_quality import speech_flags
78
- cues=[];limitations=[];fps=Fraction(timeline.frame_rate.numerator,timeline.frame_rate.denominator)
122
+
123
+ cues = []
124
+ limitations = []
125
+ fps = Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
79
126
  with projects.connect(project_id) as db:
80
127
  for track in timeline.tracks:
81
- if track.kind is not TrackKind.VIDEO:continue
128
+ if track.kind is not TrackKind.VIDEO:
129
+ continue
82
130
  for clip in track.items:
83
- source_mode=next((e.parameters['mode'] for e in clip.effects if e.effect_id=='audio.source'),'keep')
84
- if source_mode=='mute':continue
85
- if any(e.effect_id=='video.speed_ramp' for e in clip.effects):
86
- limitations.append({'item_id':clip.item_id,'reason':'speed_ramp_requires_new_transcription'});continue
87
- span=clip.source.span
88
- rows=db.execute("SELECT tr.*,pi.review_required FROM transcription_revisions tr JOIN preparation_items pi ON pi.transcript_revision_id=tr.revision_id JOIN current_preparation cp ON cp.run_id=pi.run_id WHERE tr.version_id=? AND tr.status IN ('transcribed','needs_review') AND tr.stream_index=(SELECT MIN(stream_index) FROM media_streams WHERE version_id=tr.version_id AND kind='audio') ORDER BY tr.stream_index",(span.version_id,)).fetchall()
89
- if not rows:continue
90
- row=rows[0]
91
- annotation=db.execute('SELECT * FROM transcript_annotations WHERE version_id=? AND stream_index=? AND source_revision_id=?',(span.version_id,row['stream_index'],row['revision_id'])).fetchone()
92
- if annotation and annotation['discarded']:continue
93
- needs_review=bool((row['review_required'] or row['status']=='needs_review') and not (annotation and annotation['confirmed']))
94
- corrections={} if annotation is None else {str(c['ordinal']):c['text'] for c in json.loads(annotation['corrections_json'])}
95
- src=json.loads(row['source_span_json']);tb=Fraction(src['time_base']['num'],src['time_base']['den'])
96
- unit=Fraction(span.time_base.numerator,span.time_base.denominator)
97
- start,end=int(span.start_pts)*unit,int(span.end_pts)*unit
98
- for seg in db.execute('SELECT * FROM transcript_segments WHERE revision_id=? ORDER BY ordinal',(row['revision_id'],)):
99
- left,right=int(seg['start_pts'])*tb,int(seg['end_pts'])*tb
100
- if right<=start or left>=end:continue
101
- complete_span={'version_id':span.version_id,'stream_index':span.stream_index,
102
- 'start_pts':str(math.floor(left/unit)),'end_pts':str(math.ceil(right/unit)),
103
- 'time_base':span.time_base.to_storage()}
131
+ source_mode = next(
132
+ (e.parameters["mode"] for e in clip.effects if e.effect_id == "audio.source"), "keep"
133
+ )
134
+ if source_mode == "mute":
135
+ continue
136
+ if any(e.effect_id == "video.speed_ramp" for e in clip.effects):
137
+ limitations.append({"item_id": clip.item_id, "reason": "speed_ramp_requires_new_transcription"})
138
+ continue
139
+ span = clip.source.span
140
+ rows = db.execute(
141
+ "SELECT tr.*,pi.review_required FROM transcription_revisions tr JOIN preparation_items pi ON pi.transcript_revision_id=tr.revision_id JOIN current_preparation cp ON cp.run_id=pi.run_id WHERE tr.version_id=? AND tr.status IN ('transcribed','needs_review') AND tr.stream_index=(SELECT MIN(stream_index) FROM media_streams WHERE version_id=tr.version_id AND kind='audio') ORDER BY tr.stream_index",
142
+ (span.version_id,),
143
+ ).fetchall()
144
+ if not rows:
145
+ continue
146
+ row = rows[0]
147
+ annotation = db.execute(
148
+ "SELECT * FROM transcript_annotations WHERE version_id=? AND stream_index=? AND source_revision_id=?",
149
+ (span.version_id, row["stream_index"], row["revision_id"]),
150
+ ).fetchone()
151
+ if annotation and annotation["discarded"]:
152
+ continue
153
+ needs_review = bool(
154
+ (row["review_required"] or row["status"] == "needs_review")
155
+ and not (annotation and annotation["confirmed"])
156
+ )
157
+ corrections = (
158
+ {}
159
+ if annotation is None
160
+ else {str(c["ordinal"]): c["text"] for c in json.loads(annotation["corrections_json"])}
161
+ )
162
+ src = json.loads(row["source_span_json"])
163
+ tb = Fraction(src["time_base"]["num"], src["time_base"]["den"])
164
+ unit = Fraction(span.time_base.numerator, span.time_base.denominator)
165
+ start, end = int(span.start_pts) * unit, int(span.end_pts) * unit
166
+ for seg in db.execute(
167
+ "SELECT * FROM transcript_segments WHERE revision_id=? ORDER BY ordinal", (row["revision_id"],)
168
+ ):
169
+ left, right = int(seg["start_pts"]) * tb, int(seg["end_pts"]) * tb
170
+ if right <= start or left >= end:
171
+ continue
172
+ complete_span = {
173
+ "version_id": span.version_id,
174
+ "stream_index": span.stream_index,
175
+ "start_pts": str(math.floor(left / unit)),
176
+ "end_pts": str(math.ceil(right / unit)),
177
+ "time_base": span.time_base.to_storage(),
178
+ }
104
179
  # Video cuts are quantized to frames while ASR uses audio
105
180
  # samples. A trailing AAC/sample remainder below one frame
106
181
  # is not a cut-off utterance; clamp displayed timing only.
107
- tolerance=1/fps
108
- partial=left<start-tolerance or right>end+tolerance
182
+ tolerance = 1 / fps
183
+ partial = left < start - tolerance or right > end + tolerance
109
184
  if needs_review:
110
- limitations.append({'item_id':clip.item_id,'reason':'transcript_needs_review',
111
- 'segment_id':seg['segment_id'],'provisional_text':corrections.get(str(seg['ordinal']),seg['text']),
112
- 'source_revision_id':row['revision_id'],
113
- 'source_start_seconds':float(left),'source_end_seconds':float(right),
114
- 'complete_source_span':complete_span,'partial':partial,
115
- 'policy':'Low-confidence ASR. Explicit include_drafts/allow_asr_draft can produce a labelled draft; never claim human confirmation.'})
116
- if not include_drafts or partial:continue
185
+ limitations.append(
186
+ {
187
+ "item_id": clip.item_id,
188
+ "reason": "transcript_needs_review",
189
+ "segment_id": seg["segment_id"],
190
+ "provisional_text": corrections.get(str(seg["ordinal"]), seg["text"]),
191
+ "source_revision_id": row["revision_id"],
192
+ "source_start_seconds": float(left),
193
+ "source_end_seconds": float(right),
194
+ "complete_source_span": complete_span,
195
+ "partial": partial,
196
+ "policy": "Low-confidence ASR. Explicit include_drafts/allow_asr_draft can produce a labelled draft; never claim human confirmation.",
197
+ }
198
+ )
199
+ if not include_drafts or partial:
200
+ continue
117
201
  if partial:
118
- limitations.append({'item_id':clip.item_id,'reason':'partial_utterance','segment_id':seg['segment_id'],
119
- 'text':corrections.get(str(seg['ordinal']),seg['text']),
120
- 'complete_source_span':{'version_id':span.version_id,'stream_index':span.stream_index,
121
- 'start_pts':str(math.floor(left/unit)),'end_pts':str(math.ceil(right/unit)),
122
- 'time_base':span.time_base.to_storage()},
123
- 'repair':'Use replace_clip_source with this complete_source_span; inspect the expanded shot, then rebuild subtitles. Alternatively remove/mute this speech for an explicit editorial reason.'});continue
124
- begin=max(clip.start_frame,clip.start_frame+math.floor((left-start)*fps))
125
- finish=min(clip.start_frame+clip.duration_frames,clip.start_frame+math.ceil((right-start)*fps))
126
- cues.append({'cue_id':digest([clip.item_id,row['revision_id'],seg['segment_id']])[:24],
127
- 'item_id':clip.item_id,'start_frame':begin,'duration_frames':finish-begin,
128
- 'text':corrections.get(str(seg['ordinal']),seg['text']),'segment_id':seg['segment_id'],'source_revision_id':row['revision_id'],
129
- 'verification':'asr_draft' if needs_review else 'reviewed_source','confidence':seg['confidence'],
130
- 'quality_flags':speech_flags(corrections.get(str(seg['ordinal']),seg['text'])) if needs_review else [],
131
- 'source':complete_span,'boundary_adjustment_seconds':float(max(start-left,0)+max(right-end,0))})
132
- return sorted(cues,key=lambda c:c['start_frame']),limitations
133
-
134
-
135
- PRODUCTION_EFFECTS={'video.punch_in','video.slow_push','video.reframe','video.speed_ramp','video.grade','video.mosaic','video.transition','video.fade','audio.source','audio.layers'}
136
-
137
- def validate_production_timeline(timeline,*,max_texts=96):
138
- issues=[];cursor=0
139
- video=next((t for t in timeline.tracks if t.kind is TrackKind.VIDEO),None)
140
- if video is None:return [{'code':'video_required','message':'至少需要一個畫面軌。'}]
141
- if not video.items:return [{'code':'video_required','message':'空白草稿尚無可渲染畫面;請先加入來源片段。'}]
142
- if len([t for t in timeline.tracks if t.kind is TrackKind.VIDEO])!=1:issues.append({'code':'multiple_video_tracks_unsupported'})
143
- if any(t.items for t in timeline.tracks if t.kind is TrackKind.GRAPHIC):issues.append({'code':'graphics_delivery_unsupported'})
202
+ limitations.append(
203
+ {
204
+ "item_id": clip.item_id,
205
+ "reason": "partial_utterance",
206
+ "segment_id": seg["segment_id"],
207
+ "text": corrections.get(str(seg["ordinal"]), seg["text"]),
208
+ "complete_source_span": {
209
+ "version_id": span.version_id,
210
+ "stream_index": span.stream_index,
211
+ "start_pts": str(math.floor(left / unit)),
212
+ "end_pts": str(math.ceil(right / unit)),
213
+ "time_base": span.time_base.to_storage(),
214
+ },
215
+ "repair": "Use replace_clip_source with this complete_source_span; inspect the expanded shot, then rebuild subtitles. Alternatively remove/mute this speech for an explicit editorial reason.",
216
+ }
217
+ )
218
+ continue
219
+ begin = max(clip.start_frame, clip.start_frame + math.floor((left - start) * fps))
220
+ finish = min(
221
+ clip.start_frame + clip.duration_frames, clip.start_frame + math.ceil((right - start) * fps)
222
+ )
223
+ cues.append(
224
+ {
225
+ "cue_id": digest([clip.item_id, row["revision_id"], seg["segment_id"]])[:24],
226
+ "item_id": clip.item_id,
227
+ "start_frame": begin,
228
+ "duration_frames": finish - begin,
229
+ "text": corrections.get(str(seg["ordinal"]), seg["text"]),
230
+ "segment_id": seg["segment_id"],
231
+ "source_revision_id": row["revision_id"],
232
+ "verification": "asr_draft" if needs_review else "reviewed_source",
233
+ "confidence": seg["confidence"],
234
+ "quality_flags": speech_flags(corrections.get(str(seg["ordinal"]), seg["text"]))
235
+ if needs_review
236
+ else [],
237
+ "source": complete_span,
238
+ "boundary_adjustment_seconds": float(max(start - left, 0) + max(right - end, 0)),
239
+ }
240
+ )
241
+ return sorted(cues, key=lambda c: c["start_frame"]), limitations
242
+
243
+
244
+ PRODUCTION_EFFECTS = {
245
+ "video.punch_in",
246
+ "video.slow_push",
247
+ "video.reframe",
248
+ "video.speed_ramp",
249
+ "video.grade",
250
+ "video.mosaic",
251
+ "video.transition",
252
+ "video.fade",
253
+ "audio.source",
254
+ "audio.layers",
255
+ }
256
+
257
+
258
+ def validate_production_timeline(timeline, *, max_texts=96):
259
+ issues = []
260
+ cursor = 0
261
+ video = next((t for t in timeline.tracks if t.kind is TrackKind.VIDEO), None)
262
+ if video is None:
263
+ return [{"code": "video_required", "message": "至少需要一個畫面軌。"}]
264
+ if not video.items:
265
+ return [{"code": "video_required", "message": "空白草稿尚無可渲染畫面;請先加入來源片段。"}]
266
+ if len([t for t in timeline.tracks if t.kind is TrackKind.VIDEO]) != 1:
267
+ issues.append({"code": "multiple_video_tracks_unsupported"})
268
+ if any(t.items for t in timeline.tracks if t.kind is TrackKind.GRAPHIC):
269
+ issues.append({"code": "graphics_delivery_unsupported"})
144
270
  for i in video.items:
145
- if i.start_frame!=cursor:issues.append({'code':'video_gap_or_overlap','item_id':i.item_id})
146
- cursor=i.start_frame+i.duration_frames
147
- if cursor!=timeline.duration_frames:issues.append({'code':'video_end_mismatch'})
148
- texts=[]
271
+ if i.start_frame != cursor:
272
+ issues.append({"code": "video_gap_or_overlap", "item_id": i.item_id})
273
+ cursor = i.start_frame + i.duration_frames
274
+ if cursor != timeline.duration_frames:
275
+ issues.append({"code": "video_end_mismatch"})
276
+ texts = []
149
277
  for t in timeline.tracks:
150
278
  for i in t.items:
151
- if i.start_frame+i.duration_frames>timeline.duration_frames:issues.append({'code':'item_out_of_bounds','item_id':i.item_id})
152
- if t.kind is TrackKind.TITLE:texts.append(i)
153
- if isinstance(i,MediaClip):
279
+ if i.start_frame + i.duration_frames > timeline.duration_frames:
280
+ issues.append({"code": "item_out_of_bounds", "item_id": i.item_id})
281
+ if t.kind is TrackKind.TITLE:
282
+ texts.append(i)
283
+ if isinstance(i, MediaClip):
154
284
  for e in i.effects:
155
- if e.effect_id not in PRODUCTION_EFFECTS:issues.append({'code':'unsupported_effect','item_id':i.item_id,'effect_id':e.effect_id})
156
- for n,a in enumerate(texts):
157
- for b in texts[n+1:]:
158
- if a.style_id==b.style_id and a.start_frame<b.start_frame+b.duration_frames and b.start_frame<a.start_frame+a.duration_frames:
159
- issues.append({'code':'text_layout_collision','items':[a.item_id,b.item_id],'message':'相同位置文字同時顯示;請調整時間或樣式。'})
160
- if len(texts)>max_texts:issues.append({'code':'text_limit_96' if max_texts==96 else 'production_text_limit'})
285
+ if e.effect_id not in PRODUCTION_EFFECTS:
286
+ issues.append({"code": "unsupported_effect", "item_id": i.item_id, "effect_id": e.effect_id})
287
+ for n, a in enumerate(texts):
288
+ for b in texts[n + 1 :]:
289
+ if (
290
+ a.style_id == b.style_id
291
+ and a.start_frame < b.start_frame + b.duration_frames
292
+ and b.start_frame < a.start_frame + a.duration_frames
293
+ ):
294
+ issues.append(
295
+ {
296
+ "code": "text_layout_collision",
297
+ "items": [a.item_id, b.item_id],
298
+ "message": "相同位置文字同時顯示;請調整時間或樣式。",
299
+ }
300
+ )
301
+ if len(texts) > max_texts:
302
+ issues.append({"code": "text_limit_96" if max_texts == 96 else "production_text_limit"})
161
303
  return issues
162
304
 
163
305
 
164
- def mix_audio_layers(media,project_id,timeline,base,output,cancel):
306
+ def mix_audio_layers(media, project_id, timeline, base, output, cancel):
165
307
  if timeline.production_session_id is not None:
166
308
  from .program_audio import mix_program_audio
167
- return mix_program_audio(media,project_id,timeline,base,output,cancel)
168
- store=AgentAudioStore(media.projects,project_id)
169
- fps=timeline.frame_rate.numerator/timeline.frame_rate.denominator;seconds=timeline.duration_frames/fps
170
- layers=[(i,l) for t in timeline.tracks for i in t.items if isinstance(i,MediaClip) for e in i.effects if e.effect_id=='audio.layers' for l in e.parameters['layers']]
171
- if len(layers)>24:raise ProjectError('agent_audio_limit','單次輸出最多 24 個混音片段。',status_code=409)
172
- command=['ffmpeg','-v','error','-nostdin','-y','-filter_complex_threads','2','-i',str(base)]
173
- opened=[];filters=['[0:a]anull[original]'];labels=['[original]']
309
+
310
+ return mix_program_audio(media, project_id, timeline, base, output, cancel)
311
+ store = AgentAudioStore(media.projects, project_id)
312
+ fps = timeline.frame_rate.numerator / timeline.frame_rate.denominator
313
+ seconds = timeline.duration_frames / fps
314
+ layers = [
315
+ (i, l)
316
+ for t in timeline.tracks
317
+ for i in t.items
318
+ if isinstance(i, MediaClip)
319
+ for e in i.effects
320
+ if e.effect_id == "audio.layers"
321
+ for l in e.parameters["layers"]
322
+ ]
323
+ if len(layers) > 24:
324
+ raise ProjectError("agent_audio_limit", "單次輸出最多 24 個混音片段。", status_code=409)
325
+ command = ["ffmpeg", "-v", "error", "-nostdin", "-y", "-filter_complex_threads", "2", "-i", str(base)]
326
+ opened = []
327
+ filters = ["[0:a]anull[original]"]
328
+ labels = ["[original]"]
174
329
  try:
175
- for index,(clip,layer) in enumerate(layers,1):
176
- context=store.context(layer['asset_id']);fd,asset=open_asset(context,layer['asset_id']);opened.append(fd)
177
- duration=layer['duration_frames']/fps;start=(clip.start_frame+layer['start_frame'])/fps
178
- if start+duration>seconds or layer['source_offset_seconds']+duration>asset['duration_seconds']:
179
- raise ProjectError('agent_audio_out_of_bounds','混音片段超出影片或來源長度。',status_code=409)
180
- command+=['-ss',str(layer['source_offset_seconds']),'-t',str(duration),'-i',f'/dev/fd/{fd}']
181
- fade=min(layer['fade_seconds'],duration/2)
182
- chain=f'[{index}:{asset["stream_index"]}]asetpts=PTS-STARTPTS,aresample=48000,aformat=channel_layouts=stereo,volume={layer["gain_db"]:.4f}dB'
183
- if fade:chain+=f',afade=t=in:d={fade:.6f},afade=t=out:st={duration-fade:.6f}:d={fade:.6f}'
184
- chain+=f',adelay={round(start*1000)}|{round(start*1000)}[layer{index}]';filters.append(chain)
185
- if layer['duck']:
186
- filters.append(f'[0:a]anull[side{index}]')
187
- filters.append(f'[layer{index}][side{index}]sidechaincompress=threshold=0.025:ratio=8:attack=20:release=350[duck{index}]')
188
- labels.append(f'[duck{index}]')
189
- else:labels.append(f'[layer{index}]')
190
- filters.append(''.join(labels)+f'amix=inputs={len(labels)}:duration=first:normalize=0,alimiter=limit=0.841395:level=0[aout]')
191
- command+=['-filter_complex',';'.join(filters),'-map','0:v:0','-map','[aout]','-c:v','copy','-c:a','aac','-t',str(seconds),'-movflags','+faststart',str(output)]
192
- run_process(command,cancel,pass_fds=tuple(opened),timeout=300)
330
+ for index, (clip, layer) in enumerate(layers, 1):
331
+ context = store.context(layer["asset_id"])
332
+ fd, asset = open_asset(context, layer["asset_id"])
333
+ opened.append(fd)
334
+ duration = layer["duration_frames"] / fps
335
+ start = (clip.start_frame + layer["start_frame"]) / fps
336
+ if start + duration > seconds or layer["source_offset_seconds"] + duration > asset["duration_seconds"]:
337
+ raise ProjectError("agent_audio_out_of_bounds", "混音片段超出影片或來源長度。", status_code=409)
338
+ command += ["-ss", str(layer["source_offset_seconds"]), "-t", str(duration), "-i", f"/dev/fd/{fd}"]
339
+ fade = min(layer["fade_seconds"], duration / 2)
340
+ chain = f"[{index}:{asset['stream_index']}]asetpts=PTS-STARTPTS,aresample=48000,aformat=channel_layouts=stereo,volume={layer['gain_db']:.4f}dB"
341
+ if fade:
342
+ chain += f",afade=t=in:d={fade:.6f},afade=t=out:st={duration - fade:.6f}:d={fade:.6f}"
343
+ chain += f",adelay={round(start * 1000)}|{round(start * 1000)}[layer{index}]"
344
+ filters.append(chain)
345
+ if layer["duck"]:
346
+ filters.append(f"[0:a]anull[side{index}]")
347
+ filters.append(
348
+ f"[layer{index}][side{index}]sidechaincompress=threshold=0.025:ratio=8:attack=20:release=350[duck{index}]"
349
+ )
350
+ labels.append(f"[duck{index}]")
351
+ else:
352
+ labels.append(f"[layer{index}]")
353
+ filters.append(
354
+ "".join(labels)
355
+ + f"amix=inputs={len(labels)}:duration=first:normalize=0,alimiter=limit=0.841395:level=0[aout]"
356
+ )
357
+ command += [
358
+ "-filter_complex",
359
+ ";".join(filters),
360
+ "-map",
361
+ "0:v:0",
362
+ "-map",
363
+ "[aout]",
364
+ "-c:v",
365
+ "copy",
366
+ "-c:a",
367
+ "aac",
368
+ "-t",
369
+ str(seconds),
370
+ "-movflags",
371
+ "+faststart",
372
+ str(output),
373
+ ]
374
+ run_process(command, cancel, pass_fds=tuple(opened), timeout=300)
193
375
  finally:
194
- for fd in opened:os.close(fd)
376
+ for fd in opened:
377
+ os.close(fd)
195
378
 
196
379
 
197
- def text_style_path(projects,project_id):
198
- return projects.root/project_id/'agent-text-styles.json'
380
+ def text_style_path(projects, project_id):
381
+ return projects.root / project_id / "agent-text-styles.json"
199
382
 
200
383
 
201
- def load_text_styles(projects,project_id):
202
- if projects is None:return {}
203
- path=text_style_path(projects,project_id)
204
- if path.is_symlink():raise ProjectError('storage_unsafe','文字樣式檔案不安全。',status_code=409)
205
- if not path.exists():return {}
206
- if path.stat().st_size>16*1024*1024:raise ProjectError('storage_corrupt','文字樣式超出上限。',status_code=409)
384
+ def load_text_styles(projects, project_id):
385
+ if projects is None:
386
+ return {}
387
+ path = text_style_path(projects, project_id)
388
+ if path.is_symlink():
389
+ raise ProjectError("storage_unsafe", "文字樣式檔案不安全。", status_code=409)
390
+ if not path.exists():
391
+ return {}
392
+ if path.stat().st_size > 16 * 1024 * 1024:
393
+ raise ProjectError("storage_corrupt", "文字樣式超出上限。", status_code=409)
207
394
  return json.loads(path.read_text())
208
395
 
209
396
 
210
- def source_rows(projects,project_id):
397
+ def source_rows(projects, project_id):
211
398
  """The live inventory is the authority; prior planning windows are not a source boundary."""
212
399
  with projects.connect(project_id) as db:
213
- rows=db.execute("SELECT i.version_id,i.display_name,s.stream_index,s.kind,s.details_json,v.probe_json FROM current_inventory c JOIN inventory_runs r ON r.run_id=c.run_id JOIN inventory_items i ON i.run_id=r.run_id JOIN assets a ON a.asset_id=i.asset_id JOIN asset_versions v ON v.version_id=i.version_id JOIN media_streams s ON s.version_id=i.version_id WHERE c.slot=1 AND r.state='succeeded' AND a.role='source' AND i.status='usable' AND s.kind IN ('video','audio') ORDER BY i.display_name,i.version_id,s.stream_index LIMIT 10001").fetchall()
214
- if len(rows)>10000:raise ProjectError('agent_source_limit','素材串流超過上限,請拆分作品。',status_code=409)
215
- result=[]
400
+ rows = db.execute(
401
+ "SELECT i.version_id,i.display_name,s.stream_index,s.kind,s.details_json,v.probe_json FROM current_inventory c JOIN inventory_runs r ON r.run_id=c.run_id JOIN inventory_items i ON i.run_id=r.run_id JOIN assets a ON a.asset_id=i.asset_id JOIN asset_versions v ON v.version_id=i.version_id JOIN media_streams s ON s.version_id=i.version_id WHERE c.slot=1 AND r.state='succeeded' AND a.role='source' AND i.status='usable' AND s.kind IN ('video','audio') ORDER BY i.display_name,i.version_id,s.stream_index LIMIT 10001"
402
+ ).fetchall()
403
+ if len(rows) > 10000:
404
+ raise ProjectError("agent_source_limit", "素材串流超過上限,請拆分作品。", status_code=409)
405
+ result = []
216
406
  for row in rows:
217
- details=json.loads(row['details_json']);probe=json.loads(row['probe_json'] or '{}')
218
- if details.get('attached_pic') or details.get('timed_thumbnails'):continue
407
+ details = json.loads(row["details_json"])
408
+ probe = json.loads(row["probe_json"] or "{}")
409
+ if details.get("attached_pic") or details.get("timed_thumbnails"):
410
+ continue
219
411
  try:
220
- base=Fraction(details['time_base']);start=int(details.get('start_pts',0))
221
- duration=int(details['duration_ts']) if 'duration_ts' in details else int(Fraction(str(probe['duration_seconds']))/base)
222
- if duration<=0 or base<=0:continue
223
- except (KeyError,ValueError,TypeError,ZeroDivisionError):continue
224
- result.append({'version_id':row['version_id'],'display_name':row['display_name'],'stream_index':row['stream_index'],'kind':row['kind'],
225
- 'start_pts':str(start),'end_pts':str(start+duration),'time_base':{'num':base.numerator,'den':base.denominator},'duration_seconds':float(duration*base)})
412
+ base = Fraction(details["time_base"])
413
+ start = int(details.get("start_pts", 0))
414
+ duration = (
415
+ int(details["duration_ts"])
416
+ if "duration_ts" in details
417
+ else int(Fraction(str(probe["duration_seconds"])) / base)
418
+ )
419
+ if duration <= 0 or base <= 0:
420
+ continue
421
+ except (KeyError, ValueError, TypeError, ZeroDivisionError):
422
+ continue
423
+ result.append(
424
+ {
425
+ "version_id": row["version_id"],
426
+ "display_name": row["display_name"],
427
+ "stream_index": row["stream_index"],
428
+ "kind": row["kind"],
429
+ "start_pts": str(start),
430
+ "end_pts": str(start + duration),
431
+ "time_base": {"num": base.numerator, "den": base.denominator},
432
+ "duration_seconds": float(duration * base),
433
+ }
434
+ )
226
435
  return result