@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,596 +1,1198 @@
1
1
  """Executable production tools. The model chooses actions; this layer owns IO and revisions."""
2
- from dataclasses import replace
3
- from fractions import Fraction
2
+
4
3
  import json
5
4
  import os
6
5
  import secrets
7
6
  import threading
7
+ from dataclasses import replace
8
+ from fractions import Fraction
8
9
 
9
10
  from clipen.domain import ClipSource, EffectRequest, MediaClip, SourceSpan, TextClip, Track, TrackKind
10
11
  from clipen.projects import ProjectError
12
+
11
13
  from .agent_models import ToolResult
12
14
  from .production_catalog import validate_arguments
13
15
 
14
16
 
15
17
  def problem(message):
16
- return ProjectError('agent_input_invalid',message,status_code=422)
18
+ return ProjectError("agent_input_invalid", message, status_code=422)
17
19
 
18
20
 
19
21
  class ProductionTools:
20
- def production_call(self,name,arguments):
21
- validate_arguments(name,arguments)
22
- return getattr(self,'_production_'+name)(arguments)
22
+ def production_call(self, name, arguments):
23
+ validate_arguments(name, arguments)
24
+ return getattr(self, "_production_" + name)(arguments)
23
25
 
24
26
  def _timeline(self):
25
- return self.repository.current_revision(self.project_id,self.run_id).timeline
27
+ return self.repository.current_revision(self.project_id, self.run_id).timeline
26
28
 
27
- def _save(self,timeline,summary,**details):
28
- revision,created=self.repository.save_revision(self.project_id,self.run_id,timeline,summary,
29
- expected_revision_id=getattr(self,'_expected_revision_id',None),allow_user_edit=getattr(self,'_user_edit',False))
30
- return ToolResult({'revision':revision.to_public(),'created':created,**details})
29
+ def _save(self, timeline, summary, **details):
30
+ revision, created = self.repository.save_revision(
31
+ self.project_id,
32
+ self.run_id,
33
+ timeline,
34
+ summary,
35
+ expected_revision_id=getattr(self, "_expected_revision_id", None),
36
+ allow_user_edit=getattr(self, "_user_edit", False),
37
+ )
38
+ return ToolResult({"revision": revision.to_public(), "created": created, **details})
31
39
 
32
40
  def _video(self):
33
41
  return next(t for t in self._timeline().tracks if t.kind is TrackKind.VIDEO)
34
42
 
35
- def _item(self,item_id):
43
+ def _item(self, item_id):
36
44
  for t in self._timeline().tracks:
37
45
  for item in t.items:
38
- if item.item_id==item_id:return item
39
- raise ProjectError('timeline_item_not_found','找不到指定片段。',status_code=404)
40
-
41
- def _change_item(self,item,summary):
42
- timeline=self._timeline()
43
- return self._save(replace(timeline,tracks=tuple(replace(t,items=tuple(item if i.item_id==item.item_id else i for i in t.items)) for t in timeline.tracks)),summary)
44
-
45
- def _effect(self,item_id,effect_id,parameters,summary):
46
- item=self._item(item_id)
47
- if not isinstance(item,MediaClip):raise problem('效果需要媒體片段。')
48
- if parameters is not None and (effect_id.startswith('video.') or effect_id=='audio.source') and item not in self._video().items:
49
- raise problem('這項處理只能套用於主畫面片段。')
50
- if parameters is not None and effect_id=='audio.source' and any(t.items for t in self._timeline().tracks if t.kind is TrackKind.AUDIO):
51
- raise problem('既有獨立音軌會取代原音;請先重剪或移除獨立音軌項目,再設定鏡頭原音。')
52
- effects=tuple(e for e in item.effects if e.effect_id!=effect_id)
53
- if parameters is not None:effects+=(EffectRequest(effect_id,parameters),)
54
- return self._change_item(replace(item,effects=effects),summary)
55
-
56
- def _recut(self,items,summary):
57
- if not items:raise problem('至少保留一個畫面片段。')
46
+ if item.item_id == item_id:
47
+ return item
48
+ raise ProjectError("timeline_item_not_found", "找不到指定片段。", status_code=404)
49
+
50
+ def _change_item(self, item, summary):
51
+ timeline = self._timeline()
52
+ return self._save(
53
+ replace(
54
+ timeline,
55
+ tracks=tuple(
56
+ replace(t, items=tuple(item if i.item_id == item.item_id else i for i in t.items))
57
+ for t in timeline.tracks
58
+ ),
59
+ ),
60
+ summary,
61
+ )
62
+
63
+ def _effect(self, item_id, effect_id, parameters, summary):
64
+ item = self._item(item_id)
65
+ if not isinstance(item, MediaClip):
66
+ raise problem("效果需要媒體片段。")
67
+ if (
68
+ parameters is not None
69
+ and (effect_id.startswith("video.") or effect_id == "audio.source")
70
+ and item not in self._video().items
71
+ ):
72
+ raise problem("這項處理只能套用於主畫面片段。")
73
+ if (
74
+ parameters is not None
75
+ and effect_id == "audio.source"
76
+ and any(t.items for t in self._timeline().tracks if t.kind is TrackKind.AUDIO)
77
+ ):
78
+ raise problem("既有獨立音軌會取代原音;請先重剪或移除獨立音軌項目,再設定鏡頭原音。")
79
+ effects = tuple(e for e in item.effects if e.effect_id != effect_id)
80
+ if parameters is not None:
81
+ effects += (EffectRequest(effect_id, parameters),)
82
+ return self._change_item(replace(item, effects=effects), summary)
83
+
84
+ def _recut(self, items, summary):
85
+ if not items:
86
+ raise problem("至少保留一個畫面片段。")
58
87
  from .recut import remap_cut
59
- timeline,invalidated=remap_cut(self,items)
60
- return self._save(timeline,summary,invalidated=invalidated,
61
- next_step='Unchanged post-production was remapped. Review changed boundaries and repair listed dependencies.')
62
88
 
63
- def _production_list_editing_tools(self,args):
89
+ timeline, invalidated = remap_cut(self, items)
90
+ return self._save(
91
+ timeline,
92
+ summary,
93
+ invalidated=invalidated,
94
+ next_step="Unchanged post-production was remapped. Review changed boundaries and repair listed dependencies.",
95
+ )
96
+
97
+ def _production_list_editing_tools(self, args):
64
98
  from dataclasses import asdict
65
- from .production_limits import limits_for
99
+
66
100
  from clipen.mcp_editing.server import _TOOLS
67
- return ToolResult({'tools':[{'name':t['name'],'description':t['description']} for t in _TOOLS],'decision_owner':'LLM','execution_owner':'Clipen',
68
- 'limits':{'production':asdict(limits_for(self)), 'target_duration_seconds':self._session_value()['intent'].get('target_duration_seconds',60), 'max_tool_calls':self.repository.get(self.project_id,self.run_id).max_tool_calls,
69
- 'max_preview_renders':self.repository.get(self.project_id,self.run_id).max_preview_renders,
70
- 'preview_scope':'SDR production within session limits; technical validation is not aesthetic approval'},
71
- 'unsupported':{'automatic_object_tracking':'Use explicit time intervals and rectangles; inspect every affected interval.',
72
- 'audio_listening':'This provider receives measured audio evidence, not audio perception.',
73
- 'generated_media_or_voice':'No generation provider configured.',
74
- 'resolve_project':'Native timeline JSON only; no verified Resolve exporter.',
75
- 'HDR_mastering':'SDR preview pipeline only.'}})
76
-
77
- def _production_set_target_duration(self,args):
78
- updated=self.repository.set_target_duration(self.project_id,self.run_id,
79
- self._expected_revision_id,**args)
80
- self._session_cache=self.repository.production_session(self.project_id,self.run_id)
101
+
102
+ from .production_limits import limits_for
103
+
104
+ return ToolResult(
105
+ {
106
+ "tools": [{"name": t["name"], "description": t["description"]} for t in _TOOLS],
107
+ "decision_owner": "LLM",
108
+ "execution_owner": "Clipen",
109
+ "limits": {
110
+ "production": asdict(limits_for(self)),
111
+ "target_duration_seconds": self._session_value()["intent"].get("target_duration_seconds", 60),
112
+ "max_tool_calls": self.repository.get(self.project_id, self.run_id).max_tool_calls,
113
+ "max_preview_renders": self.repository.get(self.project_id, self.run_id).max_preview_renders,
114
+ "preview_scope": "SDR production within session limits; technical validation is not aesthetic approval",
115
+ },
116
+ "unsupported": {
117
+ "automatic_object_tracking": "Use explicit time intervals and rectangles; inspect every affected interval.",
118
+ "audio_listening": "This provider receives measured audio evidence, not audio perception.",
119
+ "generated_media_or_voice": "No generation provider configured.",
120
+ "resolve_project": "Native timeline JSON only; no verified Resolve exporter.",
121
+ "HDR_mastering": "SDR preview pipeline only.",
122
+ },
123
+ }
124
+ )
125
+
126
+ def _production_set_target_duration(self, args):
127
+ updated = self.repository.set_target_duration(self.project_id, self.run_id, self._expected_revision_id, **args)
128
+ self._session_cache = self.repository.production_session(self.project_id, self.run_id)
81
129
  from dataclasses import asdict
130
+
82
131
  from .production_limits import limits_for
83
- return ToolResult({**updated,'limits':asdict(limits_for(self))})
132
+
133
+ return ToolResult({**updated, "limits": asdict(limits_for(self))})
84
134
 
85
135
  def _custom_candidates(self):
86
- from clipen.planning.models import PlanningCandidate
87
- path=self._workdir('analysis')/'candidates.json'
88
- if path.is_symlink():raise problem('候選索引不安全。')
89
- if not path.exists():return ()
90
- if path.stat().st_size>2*1024*1024:raise problem('候選索引超過上限。')
91
- return tuple(PlanningCandidate.from_storage(v) for v in json.loads(path.read_text()))
92
-
93
- def _production_list_source_media(self,args):
94
- rows=self._source_rows();offset=args.get('offset',0);limit=args.get('limit',20)
95
- return ToolResult({'sources':rows[offset:offset+limit],'total':len(rows),'next_offset':offset+limit if offset+limit<len(rows) else None,
96
- 'next_step':'register_source_range creates candidates for sample_source, transcripts and editing; no prior analysis window is required.'})
97
-
98
- def _production_search_source_dialogue(self,args):
136
+ from clipen.candidates import SourceCandidate
137
+
138
+ path = self._workdir("analysis") / "candidates.json"
139
+ if path.is_symlink():
140
+ raise problem("候選索引不安全。")
141
+ if not path.exists():
142
+ return ()
143
+ if path.stat().st_size > 2 * 1024 * 1024:
144
+ raise problem("候選索引超過上限。")
145
+ return tuple(SourceCandidate.from_storage(v) for v in json.loads(path.read_text()))
146
+
147
+ def _production_list_source_media(self, args):
148
+ rows = self._source_rows()
149
+ offset = args.get("offset", 0)
150
+ limit = args.get("limit", 20)
151
+ return ToolResult(
152
+ {
153
+ "sources": rows[offset : offset + limit],
154
+ "total": len(rows),
155
+ "next_offset": offset + limit if offset + limit < len(rows) else None,
156
+ "next_step": "register_source_range creates candidates for sample_source, transcripts and editing; no prior analysis window is required.",
157
+ }
158
+ )
159
+
160
+ def _production_search_source_dialogue(self, args):
99
161
  from .source_dialogue import search_dialogue
100
- return search_dialogue(self,args)
101
162
 
102
- def _production_register_source_range(self,args):
103
- from .production_media import atomic_json
104
- from clipen.finishing.models import digest
163
+ return search_dialogue(self, args)
164
+
165
+ def _production_register_source_range(self, args):
166
+ from clipen.candidates import SourceCandidate, TranscriptReliability
105
167
  from clipen.domain import Rational
106
- from clipen.planning.models import PlanningCandidate,TranscriptReliability
107
- row=next((r for r in self._source_rows() if r['version_id']==args['version_id'] and r['stream_index']==args['stream_index']),None)
108
- if row is None:raise problem('來源不在目前作品的可用原片清單。')
109
- base=Fraction(row['time_base']['num'],row['time_base']['den']);offset=Fraction(str(args['start_offset_seconds']));duration=Fraction(str(args['duration_seconds']))
110
- start=int(row['start_pts'])+round(offset/base);end=start+round(duration/base)
111
- if end==int(row['end_pts'])+1:end=int(row['end_pts'])
112
- if start<int(row['start_pts']) or end>int(row['end_pts']) or end<=start:raise problem('指定範圍超出原片串流。')
113
- span=SourceSpan(row['version_id'],row['stream_index'],str(start),str(end),Rational(base.numerator,base.denominator))
114
- identifier='candidate-'+digest(span.to_storage())[:32]
115
- candidate=PlanningCandidate(identifier,span,row['display_name'],row['kind'],'LLM observation (not independently verified): '+args['description'],TranscriptReliability.UNAVAILABLE)
116
- candidates={c.candidate_id:c for c in self._custom_candidates()};candidates[identifier]=candidate
117
- if len(candidates)>512:raise problem('本次新增候選已達上限。')
118
- atomic_json(self._workdir('analysis')/'candidates.json',[c.to_storage() for c in candidates.values()])
119
- return ToolResult({'candidate':candidate.to_provider(),'authority':'model_authored_observation','source':span.to_storage()})
120
-
121
- def _production_record_story_plan(self,args):
168
+ from clipen.finishing.models import digest
169
+
170
+ from .production_media import atomic_json
171
+
172
+ row = next(
173
+ (
174
+ r
175
+ for r in self._source_rows()
176
+ if r["version_id"] == args["version_id"] and r["stream_index"] == args["stream_index"]
177
+ ),
178
+ None,
179
+ )
180
+ if row is None:
181
+ raise problem("來源不在目前作品的可用原片清單。")
182
+ base = Fraction(row["time_base"]["num"], row["time_base"]["den"])
183
+ offset = Fraction(str(args["start_offset_seconds"]))
184
+ duration = Fraction(str(args["duration_seconds"]))
185
+ start = int(row["start_pts"]) + round(offset / base)
186
+ end = start + round(duration / base)
187
+ if end == int(row["end_pts"]) + 1:
188
+ end = int(row["end_pts"])
189
+ if start < int(row["start_pts"]) or end > int(row["end_pts"]) or end <= start:
190
+ raise problem("指定範圍超出原片串流。")
191
+ span = SourceSpan(
192
+ row["version_id"], row["stream_index"], str(start), str(end), Rational(base.numerator, base.denominator)
193
+ )
194
+ identifier = "candidate-" + digest(span.to_storage())[:32]
195
+ candidate = SourceCandidate(
196
+ identifier,
197
+ span,
198
+ row["display_name"],
199
+ row["kind"],
200
+ "LLM observation (not independently verified): " + args["description"],
201
+ TranscriptReliability.UNAVAILABLE,
202
+ )
203
+ candidates = {c.candidate_id: c for c in self._custom_candidates()}
204
+ candidates[identifier] = candidate
205
+ if len(candidates) > 512:
206
+ raise problem("本次新增候選已達上限。")
207
+ atomic_json(self._workdir("analysis") / "candidates.json", [c.to_storage() for c in candidates.values()])
208
+ return ToolResult(
209
+ {
210
+ "candidate": candidate.to_provider(),
211
+ "authority": "model_authored_observation",
212
+ "source": span.to_storage(),
213
+ }
214
+ )
215
+
216
+ def _production_record_story_plan(self, args):
122
217
  from .production_media import atomic_json
123
- for section in args['sections']:
124
- for identifier in section['candidate_ids']:self._candidate(identifier)
125
- plan={'authority':'model_authored','user_intent':self._context_value().brief,**args}
126
- atomic_json(self._workdir('analysis')/'story-plan.json',plan)
127
- return ToolResult({'story_plan':plan})
128
-
129
- def _production_read_story_plan(self,args):
130
- path=self._workdir('analysis')/'story-plan.json'
131
- if path.is_symlink():raise problem('敘事計畫檔案不安全。')
132
- if path.is_file() and path.stat().st_size>512000:raise problem('敘事計畫超過上限。')
218
+
219
+ for section in args["sections"]:
220
+ for identifier in section["candidate_ids"]:
221
+ self._candidate(identifier)
222
+ plan = {"authority": "model_authored", "user_intent": self._context_value().brief, **args}
223
+ atomic_json(self._workdir("analysis") / "story-plan.json", plan)
224
+ return ToolResult({"story_plan": plan})
225
+
226
+ def _production_read_story_plan(self, args):
227
+ path = self._workdir("analysis") / "story-plan.json"
228
+ if path.is_symlink():
229
+ raise problem("敘事計畫檔案不安全。")
230
+ if path.is_file() and path.stat().st_size > 512000:
231
+ raise problem("敘事計畫超過上限。")
133
232
  from .program_story import read_episode
134
- return ToolResult({'story_plan':json.loads(path.read_text()) if path.is_file() else None,
135
- 'episode':read_episode(self.repository.projects,self.project_id,self.run_id,self._timeline())})
136
233
 
137
- def _production_set_canvas(self,args):
138
- if args['width']*9!=args['height']*16:raise problem('目前樣片畫布需要 16:9。')
139
- return self._save(replace(self._timeline(),width=args['width'],height=args['height']),args['summary'])
234
+ return ToolResult(
235
+ {
236
+ "story_plan": json.loads(path.read_text()) if path.is_file() else None,
237
+ "episode": read_episode(self.repository.projects, self.project_id, self.run_id, self._timeline()),
238
+ }
239
+ )
240
+
241
+ def _production_set_canvas(self, args):
242
+ if args["width"] * 9 != args["height"] * 16:
243
+ raise problem("目前樣片畫布需要 16:9。")
244
+ return self._save(replace(self._timeline(), width=args["width"], height=args["height"]), args["summary"])
140
245
 
141
- def _production_plan_episode(self,args):
246
+ def _production_plan_episode(self, args):
142
247
  from .program_story import plan_episode
143
- return plan_episode(self,args)
144
248
 
145
- def _production_sample_source(self,args):
249
+ return plan_episode(self, args)
250
+
251
+ def _production_sample_source(self, args):
146
252
  from clipen.media import MediaPreviewRepository
253
+
147
254
  from .production_media import sample_frames
148
- candidate=self._candidate(args['candidate_id']);span=candidate.source
149
- base=Fraction(span.time_base.numerator,span.time_base.denominator)
150
- duration=span.duration_pts*base
151
- if any(Fraction(str(o))>=duration for o in args['offsets_seconds']):raise problem('取樣時間超出候選來源範圍。')
152
- media=getattr(self,'media',None) or MediaPreviewRepository(self.repository.projects)
153
- paths,manifest=sample_frames(media,self.project_id,span,args['offsets_seconds'],self._workdir('samples'),self._cancel_event())
154
- return ToolResult({'candidate_id':candidate.candidate_id,'samples':manifest,'coverage':'selected instants, not continuous motion'},paths)
155
-
156
- def _production_inspect_cut(self,args):
255
+
256
+ candidate = self._candidate(args["candidate_id"])
257
+ span = candidate.source
258
+ base = Fraction(span.time_base.numerator, span.time_base.denominator)
259
+ duration = span.duration_pts * base
260
+ if any(Fraction(str(o)) >= duration for o in args["offsets_seconds"]):
261
+ raise problem("取樣時間超出候選來源範圍。")
262
+ media = getattr(self, "media", None) or MediaPreviewRepository(self.repository.projects)
263
+ paths, manifest = sample_frames(
264
+ media, self.project_id, span, args["offsets_seconds"], self._workdir("samples"), self._cancel_event()
265
+ )
266
+ return ToolResult(
267
+ {
268
+ "candidate_id": candidate.candidate_id,
269
+ "samples": manifest,
270
+ "coverage": "selected instants, not continuous motion",
271
+ },
272
+ paths,
273
+ )
274
+
275
+ def _production_inspect_cut(self, args):
157
276
  from .editorial_review import inspect_cut
158
- return inspect_cut(self,args)
159
-
160
- def _production_inspect_candidates(self,args):
161
- candidates=[];images=[]
162
- for identifier in args['candidate_ids']:
163
- candidate=self._candidate(identifier)
164
- if candidate.media_kind!='video':raise problem('畫面試剪需要影片候選。')
165
- span=candidate.source;duration=float(span.duration_pts*Fraction(span.time_base.numerator,span.time_base.denominator))
166
- offsets=[duration*.05,duration*.5,duration*.95]
167
- result=self._production_sample_source({'candidate_id':identifier,'offsets_seconds':offsets})
168
- speech=self._production_list_transcripts({'candidate_id':identifier}).payload
169
- candidates.append({'candidate':candidate.to_provider(),'samples':result.payload['samples'],'transcripts':speech,'image_count':len(result.images)})
277
+
278
+ return inspect_cut(self, args)
279
+
280
+ def _production_inspect_candidates(self, args):
281
+ candidates = []
282
+ images = []
283
+ for identifier in args["candidate_ids"]:
284
+ candidate = self._candidate(identifier)
285
+ if candidate.media_kind != "video":
286
+ raise problem("畫面試剪需要影片候選。")
287
+ span = candidate.source
288
+ duration = float(span.duration_pts * Fraction(span.time_base.numerator, span.time_base.denominator))
289
+ offsets = [duration * 0.05, duration * 0.5, duration * 0.95]
290
+ result = self._production_sample_source({"candidate_id": identifier, "offsets_seconds": offsets})
291
+ speech = self._production_list_transcripts({"candidate_id": identifier}).payload
292
+ candidates.append(
293
+ {
294
+ "candidate": candidate.to_provider(),
295
+ "samples": result.payload["samples"],
296
+ "transcripts": speech,
297
+ "image_count": len(result.images),
298
+ }
299
+ )
170
300
  images.extend(result.images)
171
- return ToolResult({'candidates':candidates,'image_order':'candidate order, then sample order','coverage':'three source stills per range, not continuous motion or audio listening'},tuple(images))
301
+ return ToolResult(
302
+ {
303
+ "candidates": candidates,
304
+ "image_order": "candidate order, then sample order",
305
+ "coverage": "three source stills per range, not continuous motion or audio listening",
306
+ },
307
+ tuple(images),
308
+ )
172
309
 
173
- def _production_inspect_pacing(self,args):
310
+ def _production_inspect_pacing(self, args):
174
311
  from .programme_review import pacing
312
+
175
313
  return ToolResult(pacing(self._timeline()))
176
314
 
177
- def _production_review_cut(self,args):
315
+ def _production_review_cut(self, args):
178
316
  from .editorial_review import review_cut
179
- return review_cut(self,args)
180
317
 
181
- def _production_replace_clip_source(self,args):
318
+ return review_cut(self, args)
319
+
320
+ def _production_replace_clip_source(self, args):
182
321
  from clipen.domain import Rational
183
- item=self._item(args['item_id']);source=args['source']
184
- if item not in self._video().items:raise problem('只能替換主畫面來源。')
185
- row=next((r for r in self._source_rows() if r['version_id']==source['version_id'] and r['stream_index']==source['stream_index']),None)
186
- if row is None or row['kind']!='video' or row['time_base']!=source['time_base']:raise problem('指定來源不在目前影像原片清單,或時間基準不符。')
187
- start,end=int(source['start_pts']),int(source['end_pts'])
188
- if not int(row['start_pts'])<=start<end<=int(row['end_pts']):raise problem('來源範圍超出原片。')
189
- unit=Fraction(source['time_base']['num'],source['time_base']['den'])
190
- duration=(end-start)*unit
191
- if duration>30:raise problem('樣片單鏡最多 30 秒;請選擇完整且合適的口語或重新安排敘事。')
192
- span=SourceSpan(source['version_id'],source['stream_index'],str(start),str(end),Rational(unit.numerator,unit.denominator))
193
- fps=Fraction(self._timeline().frame_rate.numerator,self._timeline().frame_rate.denominator)
194
- updated=replace(item,source=ClipSource(span),duration_frames=max(1,round(duration*fps)))
195
- return self._recut([updated if i.item_id==item.item_id else i for i in self._video().items],args['summary'])
196
-
197
- def _production_list_transcripts(self,args):
322
+
323
+ item = self._item(args["item_id"])
324
+ source = args["source"]
325
+ if item not in self._video().items:
326
+ raise problem("只能替換主畫面來源。")
327
+ row = next(
328
+ (
329
+ r
330
+ for r in self._source_rows()
331
+ if r["version_id"] == source["version_id"] and r["stream_index"] == source["stream_index"]
332
+ ),
333
+ None,
334
+ )
335
+ if row is None or row["kind"] != "video" or row["time_base"] != source["time_base"]:
336
+ raise problem("指定來源不在目前影像原片清單,或時間基準不符。")
337
+ start, end = int(source["start_pts"]), int(source["end_pts"])
338
+ if not int(row["start_pts"]) <= start < end <= int(row["end_pts"]):
339
+ raise problem("來源範圍超出原片。")
340
+ unit = Fraction(source["time_base"]["num"], source["time_base"]["den"])
341
+ duration = (end - start) * unit
342
+ if duration > 30:
343
+ raise problem("樣片單鏡最多 30 秒;請選擇完整且合適的口語或重新安排敘事。")
344
+ span = SourceSpan(
345
+ source["version_id"],
346
+ source["stream_index"],
347
+ str(start),
348
+ str(end),
349
+ Rational(unit.numerator, unit.denominator),
350
+ )
351
+ fps = Fraction(self._timeline().frame_rate.numerator, self._timeline().frame_rate.denominator)
352
+ updated = replace(item, source=ClipSource(span), duration_frames=max(1, round(duration * fps)))
353
+ return self._recut([updated if i.item_id == item.item_id else i for i in self._video().items], args["summary"])
354
+
355
+ def _production_list_transcripts(self, args):
198
356
  from .production_media import transcript_cues
199
- timeline=self._timeline()
200
- if args.get('candidate_id'):
201
- candidate=self._candidate(args['candidate_id']);span=candidate.source
202
- if candidate.media_kind!='video':raise problem('候選字幕目前需要影片來源。')
203
- frames=max(1,round(span.duration_pts*Fraction(span.time_base.numerator,span.time_base.denominator)*Fraction(timeline.frame_rate.numerator,timeline.frame_rate.denominator)))
204
- timeline=replace(timeline,duration_frames=frames,tracks=(Track('source-inspection',TrackKind.VIDEO,(MediaClip(candidate.candidate_id,0,frames,ClipSource(span)),)),))
205
- cues,limitations=transcript_cues(self.repository.projects,self.project_id,timeline,**({'include_drafts':True} if args.get('include_drafts') else {}))
357
+
358
+ timeline = self._timeline()
359
+ if args.get("candidate_id"):
360
+ candidate = self._candidate(args["candidate_id"])
361
+ span = candidate.source
362
+ if candidate.media_kind != "video":
363
+ raise problem("候選字幕目前需要影片來源。")
364
+ frames = max(
365
+ 1,
366
+ round(
367
+ span.duration_pts
368
+ * Fraction(span.time_base.numerator, span.time_base.denominator)
369
+ * Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
370
+ ),
371
+ )
372
+ timeline = replace(
373
+ timeline,
374
+ duration_frames=frames,
375
+ tracks=(
376
+ Track(
377
+ "source-inspection",
378
+ TrackKind.VIDEO,
379
+ (MediaClip(candidate.candidate_id, 0, frames, ClipSource(span)),),
380
+ ),
381
+ ),
382
+ )
383
+ cues, limitations = transcript_cues(
384
+ self.repository.projects,
385
+ self.project_id,
386
+ timeline,
387
+ **({"include_drafts": True} if args.get("include_drafts") else {}),
388
+ )
206
389
  from .evidence_jobs import local_cues
207
- local,local_limits=local_cues(self,timeline,include_drafts=args.get('include_drafts',False))
390
+
391
+ local, local_limits = local_cues(self, timeline, include_drafts=args.get("include_drafts", False))
208
392
  if local:
209
- cues=[c for c in cues if not any(c['item_id']==l['item_id'] and c['start_frame']<l['start_frame']+l['duration_frames'] and l['start_frame']<c['start_frame']+c['duration_frames'] for l in local)]+local
210
- cues.sort(key=lambda c:c['start_frame'])
211
- limitations+=local_limits
212
- return ToolResult({'cues':cues,'limitations':limitations,'policy':'Complete source utterances only. asr_draft is provisional, never human-approved. No fabricated speech.'})
393
+ cues = [
394
+ c
395
+ for c in cues
396
+ if not any(
397
+ c["item_id"] == l["item_id"]
398
+ and c["start_frame"] < l["start_frame"] + l["duration_frames"]
399
+ and l["start_frame"] < c["start_frame"] + c["duration_frames"]
400
+ for l in local
401
+ )
402
+ ] + local
403
+ cues.sort(key=lambda c: c["start_frame"])
404
+ limitations += local_limits
405
+ return ToolResult(
406
+ {
407
+ "cues": cues,
408
+ "limitations": limitations,
409
+ "policy": "Complete source utterances only. asr_draft is provisional, never human-approved. No fabricated speech.",
410
+ }
411
+ )
213
412
 
214
- def _production_replace_subtitles(self,args):
215
- available={c['cue_id']:c for c in self._production_list_transcripts({'include_drafts':args.get('allow_asr_draft',False)}).payload['cues']}
413
+ def _production_replace_subtitles(self, args):
414
+ available = {
415
+ c["cue_id"]: c
416
+ for c in self._production_list_transcripts({"include_drafts": args.get("allow_asr_draft", False)}).payload[
417
+ "cues"
418
+ ]
419
+ }
216
420
  from .program_direction import direction_for
217
- program=direction_for(self).get('subtitle_style')=='program'
421
+
422
+ program = direction_for(self).get("subtitle_style") == "program"
218
423
  from .program_subtitles import make_subtitle_items
219
- captions=[];seen=set()
220
- for row in args['captions']:
221
- cue=available.get(row['cue_id'])
222
- if cue is None or row['cue_id'] in seen:raise problem('字幕引用了不存在、不完整或重複的口語。')
223
- seen.add(row['cue_id'])
224
- if len(row['text'])>80:raise problem('單段字幕請分成可閱讀的句子,最多 80 字。')
225
- if any(word not in row['text'] for word in row.get('emphasis',[])):raise problem('重點字必須實際存在於字幕句內。')
226
- if program or cue.get('verification')=='asr_draft' or any(k in row for k in ('source_excerpt','delivery','emphasis')):captions.extend(make_subtitle_items(self,cue,row))
227
- else:captions.append(TextClip('subtitle-'+row['cue_id'],cue['start_frame'],cue['duration_frames'],row['text'],'title.caption'))
424
+
425
+ captions = []
426
+ seen = set()
427
+ for row in args["captions"]:
428
+ cue = available.get(row["cue_id"])
429
+ if cue is None or row["cue_id"] in seen:
430
+ raise problem("字幕引用了不存在、不完整或重複的口語。")
431
+ seen.add(row["cue_id"])
432
+ if len(row["text"]) > 80:
433
+ raise problem("單段字幕請分成可閱讀的句子,最多 80 字。")
434
+ if any(word not in row["text"] for word in row.get("emphasis", [])):
435
+ raise problem("重點字必須實際存在於字幕句內。")
436
+ if (
437
+ program
438
+ or cue.get("verification") == "asr_draft"
439
+ or any(k in row for k in ("source_excerpt", "delivery", "emphasis"))
440
+ ):
441
+ captions.extend(make_subtitle_items(self, cue, row))
442
+ else:
443
+ captions.append(
444
+ TextClip(
445
+ "subtitle-" + row["cue_id"],
446
+ cue["start_frame"],
447
+ cue["duration_frames"],
448
+ row["text"],
449
+ "title.caption",
450
+ )
451
+ )
228
452
  from .production_limits import limits_for
229
- if len(captions)>limits_for(self).titles:raise problem('分句後超過本次製作的字幕上限。')
230
- timeline=self._timeline()
231
- retained=tuple(t for t in timeline.tracks if t.track_id!='agent-subtitles')
232
- if captions:retained+=(Track('agent-subtitles',TrackKind.TITLE,tuple(captions)),)
233
- return self._save(replace(timeline,tracks=retained),args['summary'])
234
-
235
- def _production_remove_item(self,args):
236
- item=self._item(args['item_id'])
237
- if item in self._video().items:return self._recut([i for i in self._video().items if i.item_id!=item.item_id],args['summary'])
238
- timeline=self._timeline()
239
- return self._save(replace(timeline,tracks=tuple(replace(t,items=tuple(i for i in t.items if i.item_id!=item.item_id)) for t in timeline.tracks)),args['summary'])
240
-
241
- def _trim(self,item,offset,duration):
242
- if not isinstance(item,MediaClip) or offset+duration>item.duration_frames:raise problem('裁切超出片段範圍。')
243
- timeline=self._timeline();span=item.source.span
244
- unit=Fraction(span.time_base.numerator,span.time_base.denominator)
245
- fps=Fraction(timeline.frame_rate.numerator,timeline.frame_rate.denominator)
246
- start=int(span.start_pts)+round(Fraction(offset,1)/fps/unit)
247
- end=start+round(Fraction(duration,1)/fps/unit)
248
- if end>int(span.end_pts):raise problem('裁切超出原片時間範圍。')
249
- return replace(item,duration_frames=duration,source=ClipSource(replace(span,start_pts=str(start),end_pts=str(end))))
250
-
251
- def _production_trim_clip(self,args):
252
- item=self._item(args['item_id'])
253
- if item not in self._video().items:raise problem('只能精剪主畫面片段。')
254
- trimmed=self._trim(item,args['start_offset_frames'],args['duration_frames'])
255
- return self._recut([trimmed if i.item_id==item.item_id else i for i in self._video().items],args['summary'])
256
-
257
- def _production_reorder_clips(self,args):
258
- clips={i.item_id:i for i in self._video().items}
259
- if len(args['item_ids'])!=len(clips) or set(args['item_ids'])!=set(clips):raise problem('必須完整且不重複地列出畫面片段。')
260
- return self._recut([clips[i] for i in args['item_ids']],args['summary'])
261
-
262
- def _production_split_clip(self,args):
263
- item=self._item(args['item_id']);offset=args['offset_frames']
264
- if item not in self._video().items or not offset<item.duration_frames:raise problem('分割點必須在畫面片段內。')
265
- left=self._trim(item,0,offset);right=replace(self._trim(item,offset,item.duration_frames-offset),item_id='split-'+secrets.token_hex(12),
266
- effects=tuple(e for e in item.effects if e.effect_id in {'video.grade','audio.source','video.punch_in','video.reframe'}))
267
- items=[]
268
- for i in self._video().items:items.extend([left,right] if i.item_id==item.item_id else [i])
269
- return self._recut(items,args['summary'])
270
-
271
- def _production_insert_clip(self,args):
272
- candidate,span,_=self._trimmed_candidate({k:args[k] for k in ('candidate_id','start_offset_seconds','duration_seconds')})
273
- if candidate.media_kind!='video':raise problem('主畫面需要影片來源。')
274
- timeline=self._timeline();fps=Fraction(timeline.frame_rate.numerator,timeline.frame_rate.denominator)
275
- frames=round(span.duration_pts*Fraction(span.time_base.numerator,span.time_base.denominator)*fps)
276
- item=MediaClip('insert-'+secrets.token_hex(12),0,frames,ClipSource(span))
277
- items=list(self._video().items)
278
- before=args['before_item_id']
279
- if before is None:items.append(item)
453
+
454
+ if len(captions) > limits_for(self).titles:
455
+ raise problem("分句後超過本次製作的字幕上限。")
456
+ timeline = self._timeline()
457
+ retained = tuple(t for t in timeline.tracks if t.track_id != "agent-subtitles")
458
+ if captions:
459
+ retained += (Track("agent-subtitles", TrackKind.TITLE, tuple(captions)),)
460
+ return self._save(replace(timeline, tracks=retained), args["summary"])
461
+
462
+ def _production_remove_item(self, args):
463
+ item = self._item(args["item_id"])
464
+ if item in self._video().items:
465
+ return self._recut([i for i in self._video().items if i.item_id != item.item_id], args["summary"])
466
+ timeline = self._timeline()
467
+ return self._save(
468
+ replace(
469
+ timeline,
470
+ tracks=tuple(
471
+ replace(t, items=tuple(i for i in t.items if i.item_id != item.item_id)) for t in timeline.tracks
472
+ ),
473
+ ),
474
+ args["summary"],
475
+ )
476
+
477
+ def _trim(self, item, offset, duration):
478
+ if not isinstance(item, MediaClip) or offset + duration > item.duration_frames:
479
+ raise problem("裁切超出片段範圍。")
480
+ timeline = self._timeline()
481
+ span = item.source.span
482
+ unit = Fraction(span.time_base.numerator, span.time_base.denominator)
483
+ fps = Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
484
+ start = int(span.start_pts) + round(Fraction(offset, 1) / fps / unit)
485
+ end = start + round(Fraction(duration, 1) / fps / unit)
486
+ if end > int(span.end_pts):
487
+ raise problem("裁切超出原片時間範圍。")
488
+ return replace(
489
+ item, duration_frames=duration, source=ClipSource(replace(span, start_pts=str(start), end_pts=str(end)))
490
+ )
491
+
492
+ def _production_trim_clip(self, args):
493
+ item = self._item(args["item_id"])
494
+ if item not in self._video().items:
495
+ raise problem("只能精剪主畫面片段。")
496
+ trimmed = self._trim(item, args["start_offset_frames"], args["duration_frames"])
497
+ return self._recut([trimmed if i.item_id == item.item_id else i for i in self._video().items], args["summary"])
498
+
499
+ def _production_reorder_clips(self, args):
500
+ clips = {i.item_id: i for i in self._video().items}
501
+ if len(args["item_ids"]) != len(clips) or set(args["item_ids"]) != set(clips):
502
+ raise problem("必須完整且不重複地列出畫面片段。")
503
+ return self._recut([clips[i] for i in args["item_ids"]], args["summary"])
504
+
505
+ def _production_split_clip(self, args):
506
+ item = self._item(args["item_id"])
507
+ offset = args["offset_frames"]
508
+ if item not in self._video().items or not offset < item.duration_frames:
509
+ raise problem("分割點必須在畫面片段內。")
510
+ left = self._trim(item, 0, offset)
511
+ right = replace(
512
+ self._trim(item, offset, item.duration_frames - offset),
513
+ item_id="split-" + secrets.token_hex(12),
514
+ effects=tuple(
515
+ e
516
+ for e in item.effects
517
+ if e.effect_id in {"video.grade", "audio.source", "video.punch_in", "video.reframe"}
518
+ ),
519
+ )
520
+ items = []
521
+ for i in self._video().items:
522
+ items.extend([left, right] if i.item_id == item.item_id else [i])
523
+ return self._recut(items, args["summary"])
524
+
525
+ def _production_insert_clip(self, args):
526
+ candidate, span, _ = self._trimmed_candidate(
527
+ {k: args[k] for k in ("candidate_id", "start_offset_seconds", "duration_seconds")}
528
+ )
529
+ if candidate.media_kind != "video":
530
+ raise problem("主畫面需要影片來源。")
531
+ timeline = self._timeline()
532
+ fps = Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
533
+ frames = round(span.duration_pts * Fraction(span.time_base.numerator, span.time_base.denominator) * fps)
534
+ item = MediaClip("insert-" + secrets.token_hex(12), 0, frames, ClipSource(span))
535
+ items = list(self._video().items)
536
+ before = args["before_item_id"]
537
+ if before is None:
538
+ items.append(item)
280
539
  else:
281
- index=next((i for i,v in enumerate(items) if v.item_id==before),None)
282
- if index is None:raise problem('找不到插入位置。')
283
- items.insert(index,item)
284
- return self._recut(items,args['summary'])
540
+ index = next((i for i, v in enumerate(items) if v.item_id == before), None)
541
+ if index is None:
542
+ raise problem("找不到插入位置。")
543
+ items.insert(index, item)
544
+ return self._recut(items, args["summary"])
285
545
 
286
- def _production_set_source_audio(self,args):
287
- return self._effect(args['item_id'],'audio.source',{k:args[k] for k in ('mode','gain_db')},args['summary'])
546
+ def _production_set_source_audio(self, args):
547
+ return self._effect(args["item_id"], "audio.source", {k: args[k] for k in ("mode", "gain_db")}, args["summary"])
288
548
 
289
- def _production_set_color_grade(self,args):
290
- return self._effect(args['item_id'],'video.grade',{k:args[k] for k in ('contrast','saturation','brightness')},args['summary'])
549
+ def _production_set_color_grade(self, args):
550
+ return self._effect(
551
+ args["item_id"],
552
+ "video.grade",
553
+ {k: args[k] for k in ("contrast", "saturation", "brightness")},
554
+ args["summary"],
555
+ )
291
556
 
292
- def _production_set_mosaic(self,args):
293
- item=self._item(args['item_id'])
294
- for r in args['regions']:
295
- if r['x']+r['width']>1 or r['y']+r['height']>1 or r['start_frame']+r['duration_frames']>item.duration_frames:raise problem('馬賽克超出畫面或片段時間。')
296
- return self._effect(item.item_id,'video.mosaic',{'regions':args['regions']} if args['regions'] else None,args['summary'])
557
+ def _production_set_mosaic(self, args):
558
+ item = self._item(args["item_id"])
559
+ for r in args["regions"]:
560
+ if (
561
+ r["x"] + r["width"] > 1
562
+ or r["y"] + r["height"] > 1
563
+ or r["start_frame"] + r["duration_frames"] > item.duration_frames
564
+ ):
565
+ raise problem("馬賽克超出畫面或片段時間。")
566
+ return self._effect(
567
+ item.item_id, "video.mosaic", {"regions": args["regions"]} if args["regions"] else None, args["summary"]
568
+ )
297
569
 
298
- def _production_set_transition(self,args):
299
- item=self._item(args['item_id']);clips=list(self._video().items)
300
- if item not in clips or clips.index(item)==0:raise problem('轉場需要有效的前後鏡頭。')
301
- if args['duration_frames']>min(item.duration_frames,clips[clips.index(item)-1].duration_frames):raise problem('轉場超出相鄰鏡頭長度。')
302
- return self._effect(item.item_id,'video.transition',{'kind':args['kind'],'duration_frames':args['duration_frames']} if args['kind']!='none' else None,args['summary'])
570
+ def _production_set_transition(self, args):
571
+ item = self._item(args["item_id"])
572
+ clips = list(self._video().items)
573
+ if item not in clips or clips.index(item) == 0:
574
+ raise problem("轉場需要有效的前後鏡頭。")
575
+ if args["duration_frames"] > min(item.duration_frames, clips[clips.index(item) - 1].duration_frames):
576
+ raise problem("轉場超出相鄰鏡頭長度。")
577
+ return self._effect(
578
+ item.item_id,
579
+ "video.transition",
580
+ {"kind": args["kind"], "duration_frames": args["duration_frames"]} if args["kind"] != "none" else None,
581
+ args["summary"],
582
+ )
303
583
 
304
- def _production_set_fade(self,args):
305
- item=self._item(args['item_id'])
306
- if args['fade_in_frames']+args['fade_out_frames']>item.duration_frames:raise problem('淡入與淡出合計不可超過片段長度。')
307
- return self._effect(item.item_id,'video.fade',{k:args[k] for k in ('fade_in_frames','fade_out_frames')} if args['fade_in_frames'] or args['fade_out_frames'] else None,args['summary'])
584
+ def _production_set_fade(self, args):
585
+ item = self._item(args["item_id"])
586
+ if args["fade_in_frames"] + args["fade_out_frames"] > item.duration_frames:
587
+ raise problem("淡入與淡出合計不可超過片段長度。")
588
+ return self._effect(
589
+ item.item_id,
590
+ "video.fade",
591
+ {k: args[k] for k in ("fade_in_frames", "fade_out_frames")}
592
+ if args["fade_in_frames"] or args["fade_out_frames"]
593
+ else None,
594
+ args["summary"],
595
+ )
308
596
 
309
- def _production_remove_clip_effect(self,args):
310
- return self._effect(args['item_id'],args['effect_id'],None,args['summary'])
597
+ def _production_remove_clip_effect(self, args):
598
+ return self._effect(args["item_id"], args["effect_id"], None, args["summary"])
311
599
 
312
600
  def _asset_store(self):
313
601
  from .production_media import AgentAudioStore
314
- return AgentAudioStore(self.repository.projects,self.project_id)
315
602
 
316
- def _production_search_music(self,args):
317
- choice=self._session_value()['intent'].get('music_choice')
318
- if choice and choice.get('mode')=='user':raise problem('使用者已指定配樂,請使用 list_audio_assets 取得該曲,不要另行搜尋替換。')
603
+ return AgentAudioStore(self.repository.projects, self.project_id)
604
+
605
+ def _production_search_music(self, args):
606
+ choice = self._session_value()["intent"].get("music_choice")
607
+ if choice and choice.get("mode") == "user":
608
+ raise problem("使用者已指定配樂,請使用 list_audio_assets 取得該曲,不要另行搜尋替換。")
319
609
  from clipen.finishing.catalog import PublicMusicCatalog
320
- store=self._asset_store()
321
- assets,reference=PublicMusicCatalog().search_and_prepare({'music_tags':args['tags']},store.directory/('search-'+secrets.token_hex(12)),self._cancel_event(),lambda _:None)
322
- store.add(assets,reference)
323
- found={a['asset_id'] for a in assets}
324
- return ToolResult({'assets':[a for a in store.public_assets() if a['asset_id'] in found],
325
- 'query_tags':args['tags'],'other_available_asset_ids':[a['asset_id'] for a in store.public_assets() if a['asset_id'] not in found],
326
- 'selection_policy':'These are results of THIS search, not the oldest acquired tracks. Compare genre, tags and measured tempo with the requested mood; metadata is not listening.'})
327
-
328
- def _production_list_audio_assets(self,args):
329
- return ToolResult({'assets':self._asset_store().public_assets(),'perception':'measured evidence only; no audio listening'})
330
-
331
- def _production_inspect_audio(self,args):
332
- value=next((a for a in self._asset_store().public_assets() if a['asset_id']==args['asset_id']),None)
333
- if value is None:raise problem('找不到已取得的音訊。')
334
- return ToolResult({'asset':value,'heard_by_model':False})
335
-
336
- def _production_extract_audio(self,args):
610
+
611
+ store = self._asset_store()
612
+ assets, reference = PublicMusicCatalog().search_and_prepare(
613
+ {"music_tags": args["tags"]},
614
+ store.directory / ("search-" + secrets.token_hex(12)),
615
+ self._cancel_event(),
616
+ lambda _: None,
617
+ )
618
+ store.add(assets, reference)
619
+ found = {a["asset_id"] for a in assets}
620
+ return ToolResult(
621
+ {
622
+ "assets": [a for a in store.public_assets() if a["asset_id"] in found],
623
+ "query_tags": args["tags"],
624
+ "other_available_asset_ids": [
625
+ a["asset_id"] for a in store.public_assets() if a["asset_id"] not in found
626
+ ],
627
+ "selection_policy": "These are results of THIS search, not the oldest acquired tracks. Compare genre, tags and measured tempo with the requested mood; metadata is not listening.",
628
+ }
629
+ )
630
+
631
+ def _production_list_audio_assets(self, args):
632
+ return ToolResult(
633
+ {"assets": self._asset_store().public_assets(), "perception": "measured evidence only; no audio listening"}
634
+ )
635
+
636
+ def _production_inspect_audio(self, args):
637
+ value = next((a for a in self._asset_store().public_assets() if a["asset_id"] == args["asset_id"]), None)
638
+ if value is None:
639
+ raise problem("找不到已取得的音訊。")
640
+ return ToolResult({"asset": value, "heard_by_model": False})
641
+
642
+ def _production_extract_audio(self, args):
643
+ from clipen.finishing.audio import inspect_library, run_process
337
644
  from clipen.media import MediaPreviewRepository
338
- from clipen.projects import DirectoryReference,DirectoryRole
645
+ from clipen.projects import DirectoryReference, DirectoryRole
339
646
  from clipen.projects.storage import utc_now
340
- from clipen.finishing.audio import inspect_library,run_process
341
- candidate=self._candidate(args['candidate_id']);span=candidate.source
342
- unit=Fraction(span.time_base.numerator,span.time_base.denominator)
343
- if Fraction(str(args['start_offset_seconds']))+Fraction(str(args['duration_seconds']))>span.duration_pts*unit:raise problem('擷取音訊超過候選範圍。')
344
- source=(getattr(self,'media',None) or MediaPreviewRepository(self.repository.projects)).open(self.project_id,span.version_id)
345
- store=self._asset_store();directory=store.directory/('extract-'+secrets.token_hex(12));directory.mkdir(mode=0o700)
647
+
648
+ candidate = self._candidate(args["candidate_id"])
649
+ span = candidate.source
650
+ unit = Fraction(span.time_base.numerator, span.time_base.denominator)
651
+ if (
652
+ Fraction(str(args["start_offset_seconds"])) + Fraction(str(args["duration_seconds"]))
653
+ > span.duration_pts * unit
654
+ ):
655
+ raise problem("擷取音訊超過候選範圍。")
656
+ source = (getattr(self, "media", None) or MediaPreviewRepository(self.repository.projects)).open(
657
+ self.project_id, span.version_id
658
+ )
659
+ store = self._asset_store()
660
+ directory = store.directory / ("extract-" + secrets.token_hex(12))
661
+ directory.mkdir(mode=0o700)
346
662
  try:
347
- if not source.audio_stream_indices:raise problem('指定來源沒有音軌。')
348
- stream=span.stream_index if candidate.media_kind=='audio' else source.audio_stream_indices[0]
349
- if stream not in source.audio_stream_indices:raise problem('指定來源沒有這個音訊串流。')
350
- start=float(int(span.start_pts)*unit)+args['start_offset_seconds']
351
- run_process(['ffmpeg','-v','error','-nostdin','-seek_timestamp','1','-ss',f'{start:.9f}','-i',f'/dev/fd/{source.descriptor}',
352
- '-map',f'0:{stream}','-t',str(args['duration_seconds']),'-vn','-c:a','pcm_s16le',str(directory/'source.wav')],self._cancel_event(),pass_fds=(source.descriptor,),timeout=120)
353
- finally:source.close()
354
- info=directory.stat();reference=DirectoryReference(DirectoryRole.SOURCE,str(directory),directory.name,directory.name,info.st_dev,info.st_ino,utc_now()).to_storage()
355
- assets,issues=inspect_library('sfx',reference,self._cancel_event(),lambda _:None)
356
- if not assets:raise problem('來源音訊無法分析或沒有可用聲音。')
663
+ if not source.audio_stream_indices:
664
+ raise problem("指定來源沒有音軌。")
665
+ stream = span.stream_index if candidate.media_kind == "audio" else source.audio_stream_indices[0]
666
+ if stream not in source.audio_stream_indices:
667
+ raise problem("指定來源沒有這個音訊串流。")
668
+ start = float(int(span.start_pts) * unit) + args["start_offset_seconds"]
669
+ run_process(
670
+ [
671
+ "ffmpeg",
672
+ "-v",
673
+ "error",
674
+ "-nostdin",
675
+ "-seek_timestamp",
676
+ "1",
677
+ "-ss",
678
+ f"{start:.9f}",
679
+ "-i",
680
+ f"/dev/fd/{source.descriptor}",
681
+ "-map",
682
+ f"0:{stream}",
683
+ "-t",
684
+ str(args["duration_seconds"]),
685
+ "-vn",
686
+ "-c:a",
687
+ "pcm_s16le",
688
+ str(directory / "source.wav"),
689
+ ],
690
+ self._cancel_event(),
691
+ pass_fds=(source.descriptor,),
692
+ timeout=120,
693
+ )
694
+ finally:
695
+ source.close()
696
+ info = directory.stat()
697
+ reference = DirectoryReference(
698
+ DirectoryRole.SOURCE, str(directory), directory.name, directory.name, info.st_dev, info.st_ino, utc_now()
699
+ ).to_storage()
700
+ assets, issues = inspect_library("sfx", reference, self._cancel_event(), lambda _: None)
701
+ if not assets:
702
+ raise problem("來源音訊無法分析或沒有可用聲音。")
357
703
  for a in assets:
358
- a['name']=candidate.display_name
359
- a['provenance']={'source':'project_media','candidate_id':candidate.candidate_id,'version_id':span.version_id,
360
- 'source_offset_seconds':args['start_offset_seconds'],'duration_seconds':args['duration_seconds'],
361
- 'license':'user_source_rights_unknown','attribution':'使用者提供的來源素材;權利條件未由系統確認。','changes':'截取並轉為 PCM 音訊。'}
362
- store.add(assets,reference)
363
- return ToolResult({'assets':[{k:v for k,v in a.items() if k not in {'relative_path','fingerprint','mtime_ns','size_bytes'}} for a in assets],'issues':issues})
364
-
365
- def _production_place_audio(self,args):
704
+ a["name"] = candidate.display_name
705
+ a["provenance"] = {
706
+ "source": "project_media",
707
+ "candidate_id": candidate.candidate_id,
708
+ "version_id": span.version_id,
709
+ "source_offset_seconds": args["start_offset_seconds"],
710
+ "duration_seconds": args["duration_seconds"],
711
+ "license": "user_source_rights_unknown",
712
+ "attribution": "使用者提供的來源素材;權利條件未由系統確認。",
713
+ "changes": "截取並轉為 PCM 音訊。",
714
+ }
715
+ store.add(assets, reference)
716
+ return ToolResult(
717
+ {
718
+ "assets": [
719
+ {k: v for k, v in a.items() if k not in {"relative_path", "fingerprint", "mtime_ns", "size_bytes"}}
720
+ for a in assets
721
+ ],
722
+ "issues": issues,
723
+ }
724
+ )
725
+
726
+ def _production_place_audio(self, args):
366
727
  from clipen.finishing.audio import open_asset
367
- context=self._asset_store().context(args['asset_id'])
368
- fd,asset=open_asset(context,args['asset_id']);os.close(fd)
369
- item=self._item(args['item_id'])
370
- if item not in self._video().items:raise problem('音訊必須錨定於畫面片段。')
371
- fps=self._timeline().frame_rate.numerator/self._timeline().frame_rate.denominator
372
- if item.start_frame+args['start_frame']+args['duration_frames']>self._timeline().duration_frames:raise problem('音訊超過影片結尾。')
373
- if args['source_offset_seconds']+args['duration_frames']/fps>asset['duration_seconds']:raise problem('音訊來源長度不足。')
374
- timeline=self._timeline();tracks=[]
728
+
729
+ context = self._asset_store().context(args["asset_id"])
730
+ fd, asset = open_asset(context, args["asset_id"])
731
+ os.close(fd)
732
+ item = self._item(args["item_id"])
733
+ if item not in self._video().items:
734
+ raise problem("音訊必須錨定於畫面片段。")
735
+ fps = self._timeline().frame_rate.numerator / self._timeline().frame_rate.denominator
736
+ if item.start_frame + args["start_frame"] + args["duration_frames"] > self._timeline().duration_frames:
737
+ raise problem("音訊超過影片結尾。")
738
+ if args["source_offset_seconds"] + args["duration_frames"] / fps > asset["duration_seconds"]:
739
+ raise problem("音訊來源長度不足。")
740
+ timeline = self._timeline()
741
+ tracks = []
375
742
  for t in timeline.tracks:
376
- items=[]
743
+ items = []
377
744
  for i in t.items:
378
- if not isinstance(i,MediaClip):items.append(i);continue
379
- layers=[l for e in i.effects if e.effect_id=='audio.layers' for l in e.parameters['layers'] if l['layer_id']!=args['layer_id']]
380
- if i.item_id==item.item_id:layers.append({k:v for k,v in args.items() if k not in {'item_id','summary'}})
381
- effects=tuple(e for e in i.effects if e.effect_id!='audio.layers')
382
- if layers:effects+=(EffectRequest('audio.layers',{'layers':layers}),)
383
- items.append(replace(i,effects=effects))
384
- tracks.append(replace(t,items=tuple(items)))
385
- return self._save(replace(timeline,tracks=tuple(tracks)),args['summary'])
386
-
387
- def _production_remove_audio(self,args):
388
- timeline=self._timeline();tracks=[]
745
+ if not isinstance(i, MediaClip):
746
+ items.append(i)
747
+ continue
748
+ layers = [
749
+ l
750
+ for e in i.effects
751
+ if e.effect_id == "audio.layers"
752
+ for l in e.parameters["layers"]
753
+ if l["layer_id"] != args["layer_id"]
754
+ ]
755
+ if i.item_id == item.item_id:
756
+ layers.append({k: v for k, v in args.items() if k not in {"item_id", "summary"}})
757
+ effects = tuple(e for e in i.effects if e.effect_id != "audio.layers")
758
+ if layers:
759
+ effects += (EffectRequest("audio.layers", {"layers": layers}),)
760
+ items.append(replace(i, effects=effects))
761
+ tracks.append(replace(t, items=tuple(items)))
762
+ return self._save(replace(timeline, tracks=tuple(tracks)), args["summary"])
763
+
764
+ def _production_remove_audio(self, args):
765
+ timeline = self._timeline()
766
+ tracks = []
389
767
  for t in timeline.tracks:
390
- items=[]
768
+ items = []
391
769
  for i in t.items:
392
- if not isinstance(i,MediaClip):items.append(i);continue
393
- layers=[l for e in i.effects if e.effect_id=='audio.layers' for l in e.parameters['layers'] if l['layer_id']!=args['layer_id']]
394
- effects=tuple(e for e in i.effects if e.effect_id!='audio.layers')
395
- if layers:effects+=(EffectRequest('audio.layers',{'layers':layers}),)
396
- items.append(replace(i,effects=effects))
397
- tracks.append(replace(t,items=tuple(items)))
398
- return self._save(replace(timeline,tracks=tuple(tracks)),args['summary'])
399
-
400
- def _production_validate_sequence(self,args):
401
- from .production_media import validate_production_timeline,load_text_styles
402
- from .production_preview import finish_review_status
770
+ if not isinstance(i, MediaClip):
771
+ items.append(i)
772
+ continue
773
+ layers = [
774
+ l
775
+ for e in i.effects
776
+ if e.effect_id == "audio.layers"
777
+ for l in e.parameters["layers"]
778
+ if l["layer_id"] != args["layer_id"]
779
+ ]
780
+ effects = tuple(e for e in i.effects if e.effect_id != "audio.layers")
781
+ if layers:
782
+ effects += (EffectRequest("audio.layers", {"layers": layers}),)
783
+ items.append(replace(i, effects=effects))
784
+ tracks.append(replace(t, items=tuple(items)))
785
+ return self._save(replace(timeline, tracks=tuple(tracks)), args["summary"])
786
+
787
+ def _production_validate_sequence(self, args):
403
788
  from clipen.finishing.audio import open_asset
404
- from .production_limits import limits_for,production_limit_issues
405
- issues=validate_production_timeline(self._timeline(),max_texts=limits_for(self).titles)
406
- limit_issues=production_limit_issues(self,self._timeline())
407
- issues+=limit_issues
408
- component_issues=self._component_issues()
409
- content_codes={'program_component_collision','component_restates_subtitle'}
410
- issues+=[i for i in component_issues if i['code'] not in content_codes]
789
+
790
+ from .production_limits import limits_for, production_limit_issues
791
+ from .production_media import load_text_styles, validate_production_timeline
792
+ from .production_preview import finish_review_status
793
+
794
+ issues = validate_production_timeline(self._timeline(), max_texts=limits_for(self).titles)
795
+ limit_issues = production_limit_issues(self, self._timeline())
796
+ issues += limit_issues
797
+ component_issues = self._component_issues()
798
+ content_codes = {"program_component_collision", "component_restates_subtitle"}
799
+ issues += [i for i in component_issues if i["code"] not in content_codes]
411
800
  from .program_direction import direction_issues
412
- delivery_issues=direction_issues(self)
413
- invalid_fields={i['field'] for i in limit_issues}
414
- delivery_issues += [i for i in production_limit_issues(self,self._timeline(),complete=True) if i['field'] not in invalid_fields]
801
+
802
+ delivery_issues = direction_issues(self)
803
+ invalid_fields = {i["field"] for i in limit_issues}
804
+ delivery_issues += [
805
+ i
806
+ for i in production_limit_issues(self, self._timeline(), complete=True)
807
+ if i["field"] not in invalid_fields
808
+ ]
415
809
  # Overlaps and echoes of a subtitle are the Agent's call: advice, never a blocker.
416
- advisories=[i for i in component_issues if i['code'] in content_codes]
810
+ advisories = [i for i in component_issues if i["code"] in content_codes]
417
811
  from .production_requirements import requirement_issues
418
- delivery_issues+=requirement_issues(self)
419
- if not any(t.items for t in self._timeline().tracks if (t.track_id=='program-components' or t.track_id.startswith('program-components-'))):
420
- delivery_issues.append({'code':'program_graphics_missing','message':'節目 Skill 需要有用途的後製畫面,請檢視素材後選擇合適元件。'})
812
+
813
+ delivery_issues += requirement_issues(self)
814
+ if not any(
815
+ t.items
816
+ for t in self._timeline().tracks
817
+ if (t.track_id == "program-components" or t.track_id.startswith("program-components-"))
818
+ ):
819
+ delivery_issues.append(
820
+ {
821
+ "code": "program_graphics_missing",
822
+ "message": "節目 Skill 需要有用途的後製畫面,請檢視素材後選擇合適元件。",
823
+ }
824
+ )
421
825
  from .speech_coverage import speech_coverage
422
- coverage=speech_coverage(self)
423
- if not coverage['complete']:delivery_issues.append({'code':'source_speech_evidence_missing','ranges':coverage['unknown_ranges'],
424
- 'message':'保留的原音仍有未取證範圍,請按需轉寫或明確調整剪輯;空搜尋不能視為沒有對話。'})
826
+
827
+ coverage = speech_coverage(self)
828
+ if not coverage["complete"]:
829
+ delivery_issues.append(
830
+ {
831
+ "code": "source_speech_evidence_missing",
832
+ "ranges": coverage["unknown_ranges"],
833
+ "message": "保留的原音仍有未取證範圍,請按需轉寫或明確調整剪輯;空搜尋不能視為沒有對話。",
834
+ }
835
+ )
425
836
  from .program_subtitles import subtitle_status
426
- subtitle_review=subtitle_status(self.repository.projects,self.project_id,self._timeline())
427
- pending=subtitle_review['unaligned_item_ids']
428
- if pending:delivery_issues.append({'code':'subtitle_alignment_required','item_ids':pending,
429
- 'message':'字幕時間尚未核對,或修改文字後原對齊已失效。請核對來源並修復相關字幕;可以先看草稿。'})
430
- if not subtitle_review['count'] and self._production_list_transcripts({'include_drafts':True}).payload['cues']:
431
- delivery_issues.append({'code':'program_subtitles_missing','message':'目前保留口語但沒有節目字幕,請依來源建立並對齊字幕。'})
837
+
838
+ subtitle_review = subtitle_status(self.repository.projects, self.project_id, self._timeline())
839
+ pending = subtitle_review["unaligned_item_ids"]
840
+ if pending:
841
+ delivery_issues.append(
842
+ {
843
+ "code": "subtitle_alignment_required",
844
+ "item_ids": pending,
845
+ "message": "字幕時間尚未核對,或修改文字後原對齊已失效。請核對來源並修復相關字幕;可以先看草稿。",
846
+ }
847
+ )
848
+ if not subtitle_review["count"] and self._production_list_transcripts({"include_drafts": True}).payload["cues"]:
849
+ delivery_issues.append(
850
+ {"code": "program_subtitles_missing", "message": "目前保留口語但沒有節目字幕,請依來源建立並對齊字幕。"}
851
+ )
432
852
  from .programme_review import caption_coverage
433
- captions=caption_coverage(self,self._production_list_transcripts({'include_drafts':True}).payload)
434
- if captions['missing_cues']:
435
- delivery_issues.append({'code':'subtitle_coverage_incomplete','ranges':captions['missing_cues'],
436
- 'message':'保留口語仍有缺漏字幕;少數已對齊字幕不能代表整片完成。請修復來源辨識/對齊並重建字幕,或明確調整原音剪輯。'})
437
- if captions['unresolved_item_ids']:
438
- delivery_issues.append({'code':'subtitle_source_range_unresolved','item_ids':captions['unresolved_item_ids'],
439
- 'message':'部分原音切在尚未對齊的句段內,尚無完整可用字幕;請按需重新轉寫該區間,不能以刪除字幕消除待辦。'})
440
- from .production_media import load_text_styles
441
- profiles=load_text_styles(self.repository.projects,self.project_id)
442
- shots={i.item_id:i for i in self._video().items}
443
- caption_items=[i for t in self._timeline().tracks if t.track_id=='agent-subtitles' for i in t.items]
853
+
854
+ captions = caption_coverage(self, self._production_list_transcripts({"include_drafts": True}).payload)
855
+ if captions["missing_cues"]:
856
+ delivery_issues.append(
857
+ {
858
+ "code": "subtitle_coverage_incomplete",
859
+ "ranges": captions["missing_cues"],
860
+ "message": "保留口語仍有缺漏字幕;少數已對齊字幕不能代表整片完成。請修復來源辨識/對齊並重建字幕,或明確調整原音剪輯。",
861
+ }
862
+ )
863
+ if captions["unresolved_item_ids"]:
864
+ delivery_issues.append(
865
+ {
866
+ "code": "subtitle_source_range_unresolved",
867
+ "item_ids": captions["unresolved_item_ids"],
868
+ "message": "部分原音切在尚未對齊的句段內,尚無完整可用字幕;請按需重新轉寫該區間,不能以刪除字幕消除待辦。",
869
+ }
870
+ )
871
+
872
+ profiles = load_text_styles(self.repository.projects, self.project_id)
873
+ shots = {i.item_id: i for i in self._video().items}
874
+ caption_items = [i for t in self._timeline().tracks if t.track_id == "agent-subtitles" for i in t.items]
444
875
  for clip in shots.values():
445
- anchored=[i.item_id for i in caption_items if profiles.get(i.style_id,{}).get('anchor_item_id')==clip.item_id]
446
- muted=any(e.effect_id=='audio.source' and e.parameters['mode']=='mute' for e in clip.effects)
447
- if muted and anchored:delivery_issues.append({'code':'subtitle_muted_source','item_ids':anchored,'message':'字幕所引用的原音已靜音,請確認聲音安排並重建對應字幕。'})
448
- if any(e.effect_id=='video.speed_ramp' for e in clip.effects) and (not muted or anchored):
449
- delivery_issues.append({'code':'retimed_speech_mapping_unavailable','item_id':clip.item_id,
450
- 'message':'這段變速尚無可靠的語音時間映射。請移除語音鏡頭的變速,或將它改為不帶口語字幕的靜音畫面。'})
876
+ anchored = [
877
+ i.item_id for i in caption_items if profiles.get(i.style_id, {}).get("anchor_item_id") == clip.item_id
878
+ ]
879
+ muted = any(e.effect_id == "audio.source" and e.parameters["mode"] == "mute" for e in clip.effects)
880
+ if muted and anchored:
881
+ delivery_issues.append(
882
+ {
883
+ "code": "subtitle_muted_source",
884
+ "item_ids": anchored,
885
+ "message": "字幕所引用的原音已靜音,請確認聲音安排並重建對應字幕。",
886
+ }
887
+ )
888
+ if any(e.effect_id == "video.speed_ramp" for e in clip.effects) and (not muted or anchored):
889
+ delivery_issues.append(
890
+ {
891
+ "code": "retimed_speech_mapping_unavailable",
892
+ "item_id": clip.item_id,
893
+ "message": "這段變速尚無可靠的語音時間映射。請移除語音鏡頭的變速,或將它改為不帶口語字幕的靜音畫面。",
894
+ }
895
+ )
451
896
  with self.repository.projects.connect(self.project_id) as db:
452
- corrections=db.execute("SELECT request_json FROM production_evidence_jobs WHERE run_id=? AND kind='align' AND state='succeeded'",(self.run_id,)).fetchall()
453
- changed={(value['transcript_job_id'],str(value['correction']['segment_ordinal'])) for row in corrections
454
- if 'correction' in (value:=json.loads(row['request_json']))}
455
- stale_text=[i.item_id for t in self._timeline().tracks if t.track_id=='agent-subtitles' for i in t.items
456
- if (profiles.get(i.style_id,{}).get('source_revision_id'),str(profiles.get(i.style_id,{}).get('segment_id'))) in changed]
457
- if stale_text:delivery_issues.append({'code':'subtitle_source_changed','item_ids':stale_text,'message':'來源口語已有更正,請使用最新證據重新建立相關字幕。'})
458
- revision_id=self.repository.current_revision(self.project_id,self.run_id).revision_id
897
+ corrections = db.execute(
898
+ "SELECT request_json FROM production_evidence_jobs WHERE run_id=? AND kind='align' AND state='succeeded'",
899
+ (self.run_id,),
900
+ ).fetchall()
901
+ changed = {
902
+ (value["transcript_job_id"], str(value["correction"]["segment_ordinal"]))
903
+ for row in corrections
904
+ if "correction" in (value := json.loads(row["request_json"]))
905
+ }
906
+ stale_text = [
907
+ i.item_id
908
+ for t in self._timeline().tracks
909
+ if t.track_id == "agent-subtitles"
910
+ for i in t.items
911
+ if (
912
+ profiles.get(i.style_id, {}).get("source_revision_id"),
913
+ str(profiles.get(i.style_id, {}).get("segment_id")),
914
+ )
915
+ in changed
916
+ ]
917
+ if stale_text:
918
+ delivery_issues.append(
919
+ {
920
+ "code": "subtitle_source_changed",
921
+ "item_ids": stale_text,
922
+ "message": "來源口語已有更正,請使用最新證據重新建立相關字幕。",
923
+ }
924
+ )
925
+ revision_id = self.repository.current_revision(self.project_id, self.run_id).revision_id
459
926
  with self.repository.projects.connect(self.project_id) as db:
460
- rows=db.execute("SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='mix_review' ORDER BY sequence DESC",(self.run_id,)).fetchall()
927
+ rows = db.execute(
928
+ "SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='mix_review' ORDER BY sequence DESC",
929
+ (self.run_id,),
930
+ ).fetchall()
461
931
  from .production_preview import render_recipe_id
462
- recipe_id=render_recipe_id()
463
- mix=next((value for r in rows if (value:=json.loads(r['payload_json']))['revision_id']==revision_id and value.get('recipe_id')==recipe_id),None)
464
- if mix is None:delivery_issues.append({'code':'mix_review_required','message':'請在預覽完成後呼叫 inspect_mix,檢查實際配樂與混音量測。'})
465
- else:delivery_issues+=mix['issues']
466
- issues+=delivery_issues
467
- styles=load_text_styles(self.repository.projects,self.project_id)
468
- fps=self._timeline().frame_rate.numerator/self._timeline().frame_rate.denominator
932
+
933
+ recipe_id = render_recipe_id()
934
+ mix = next(
935
+ (
936
+ value
937
+ for r in rows
938
+ if (value := json.loads(r["payload_json"]))["revision_id"] == revision_id
939
+ and value.get("recipe_id") == recipe_id
940
+ ),
941
+ None,
942
+ )
943
+ if mix is None:
944
+ delivery_issues.append(
945
+ {"code": "mix_review_required", "message": "請在預覽完成後呼叫 inspect_mix,檢查實際配樂與混音量測。"}
946
+ )
947
+ else:
948
+ delivery_issues += mix["issues"]
949
+ issues += delivery_issues
950
+ styles = load_text_styles(self.repository.projects, self.project_id)
951
+ fps = self._timeline().frame_rate.numerator / self._timeline().frame_rate.denominator
469
952
  with self.repository.projects.connect(self.project_id) as db:
470
953
  for clip in self._video().items:
471
- row=db.execute("SELECT details_json FROM media_streams WHERE version_id=? AND stream_index=? AND kind='video'",(clip.source.span.version_id,clip.source.span.stream_index)).fetchone()
472
- if row and json.loads(row['details_json']).get('color_transfer') in {'smpte2084','arib-std-b67'}:
473
- issues.append({'code':'hdr_preview_unsupported','item_id':clip.item_id})
954
+ row = db.execute(
955
+ "SELECT details_json FROM media_streams WHERE version_id=? AND stream_index=? AND kind='video'",
956
+ (clip.source.span.version_id, clip.source.span.stream_index),
957
+ ).fetchone()
958
+ if row and json.loads(row["details_json"]).get("color_transfer") in {"smpte2084", "arib-std-b67"}:
959
+ issues.append({"code": "hdr_preview_unsupported", "item_id": clip.item_id})
474
960
  for t in self._timeline().tracks:
475
961
  for item in t.items:
476
- if isinstance(item,TextClip) and item.style_id.startswith('agent.text.') and item.style_id not in styles:
477
- issues.append({'code':'text_style_missing','item_id':item.item_id})
478
- if not isinstance(item,MediaClip):continue
962
+ if (
963
+ isinstance(item, TextClip)
964
+ and item.style_id.startswith("agent.text.")
965
+ and item.style_id not in styles
966
+ ):
967
+ issues.append({"code": "text_style_missing", "item_id": item.item_id})
968
+ if not isinstance(item, MediaClip):
969
+ continue
479
970
  for e in item.effects:
480
- if e.effect_id!='audio.layers':continue
481
- for layer in e.parameters['layers']:
971
+ if e.effect_id != "audio.layers":
972
+ continue
973
+ for layer in e.parameters["layers"]:
482
974
  try:
483
- fd,asset=open_asset(self._asset_store().context(layer['asset_id']),layer['asset_id']);os.close(fd)
484
- if item.start_frame+layer['start_frame']+layer['duration_frames']>self._timeline().duration_frames or layer['source_offset_seconds']+layer['duration_frames']/fps>asset['duration_seconds']:
485
- issues.append({'code':'audio_out_of_bounds','layer_id':layer['layer_id']})
486
- except ProjectError as error:issues.append({'code':error.code,'layer_id':layer['layer_id']})
975
+ fd, asset = open_asset(self._asset_store().context(layer["asset_id"]), layer["asset_id"])
976
+ os.close(fd)
977
+ if (
978
+ item.start_frame + layer["start_frame"] + layer["duration_frames"]
979
+ > self._timeline().duration_frames
980
+ or layer["source_offset_seconds"] + layer["duration_frames"] / fps
981
+ > asset["duration_seconds"]
982
+ ):
983
+ issues.append({"code": "audio_out_of_bounds", "layer_id": layer["layer_id"]})
984
+ except ProjectError as error:
985
+ issues.append({"code": error.code, "layer_id": layer["layer_id"]})
487
986
  from .production_requirements import production_contents
488
- validation={'valid':not issues,'issues':issues,'render_issues':[i for i in issues if i not in delivery_issues],
489
- 'delivery_issues':delivery_issues,'advisories':advisories,'design_notes':self._component_design_notes(),'production_contents':production_contents(self.repository.projects,self.project_id,self._timeline()),'revision_id':self.repository.current_revision(self.project_id,self.run_id).revision_id,'render_review':finish_review_status(self),'aesthetic_review':'not performed'}
987
+
988
+ validation = {
989
+ "valid": not issues,
990
+ "issues": issues,
991
+ "render_issues": [i for i in issues if i not in delivery_issues],
992
+ "delivery_issues": delivery_issues,
993
+ "advisories": advisories,
994
+ "design_notes": self._component_design_notes(),
995
+ "production_contents": production_contents(self.repository.projects, self.project_id, self._timeline()),
996
+ "revision_id": self.repository.current_revision(self.project_id, self.run_id).revision_id,
997
+ "render_review": finish_review_status(self),
998
+ "aesthetic_review": "not performed",
999
+ }
490
1000
  from .production_preview import _event
491
- _event(self,'sequence_validation',{k:validation[k] for k in ('revision_id','valid','issues','render_issues','delivery_issues')})
1001
+
1002
+ _event(
1003
+ self,
1004
+ "sequence_validation",
1005
+ {k: validation[k] for k in ("revision_id", "valid", "issues", "render_issues", "delivery_issues")},
1006
+ )
492
1007
  return ToolResult(validation)
493
1008
 
494
- def _production_get_edit_history(self,args):
1009
+ def _production_get_edit_history(self, args):
495
1010
  # A long run holds thousands of events; return versions and one page of
496
1011
  # recent events so the result always fits a single tool response.
497
1012
  from .versions import versions
498
- limit=args.get('limit',40);before=args.get('before_sequence')
1013
+
1014
+ limit = args.get("limit", 40)
1015
+ before = args.get("before_sequence")
499
1016
  with self.repository.projects.connect(self.project_id) as db:
500
- film=versions(db,self.run_id,self.repository.get(self.project_id,self.run_id).provider)
501
- rows=db.execute('SELECT sequence,event_type,payload_json,created_at FROM edit_agent_events WHERE run_id=? AND sequence<? ORDER BY sequence DESC LIMIT ?',
502
- (self.run_id,before if before is not None else 2**62,limit+1)).fetchall()
503
- revisions=db.execute('SELECT COUNT(*) FROM edit_agent_revisions WHERE run_id=?',(self.run_id,)).fetchone()[0]
504
- page=rows[:limit]
505
- events=[{'sequence':r['sequence'],'event_type':r['event_type'],'created_at':r['created_at'],
506
- 'payload':r['payload_json'] if len(r['payload_json'])<=400 else r['payload_json'][:400]+'…'} for r in page]
507
- return ToolResult({'current_revision_id':self.repository.current_revision(self.project_id,self.run_id).revision_id,
508
- 'versions':film,'revision_count':revisions,'events':events,
509
- 'next_before_sequence':page[-1]['sequence'] if len(rows)>limit else None,
510
- 'note':'Versions are complete edits a person can restore; events are newest first and payloads over 400 characters are shortened.'})
511
-
512
- def _production_read_mutation_receipt(self,args):
1017
+ film = versions(db, self.run_id, self.repository.get(self.project_id, self.run_id).provider)
1018
+ rows = db.execute(
1019
+ "SELECT sequence,event_type,payload_json,created_at FROM edit_agent_events WHERE run_id=? AND sequence<? ORDER BY sequence DESC LIMIT ?",
1020
+ (self.run_id, before if before is not None else 2**62, limit + 1),
1021
+ ).fetchall()
1022
+ revisions = db.execute(
1023
+ "SELECT COUNT(*) FROM edit_agent_revisions WHERE run_id=?", (self.run_id,)
1024
+ ).fetchone()[0]
1025
+ page = rows[:limit]
1026
+ events = [
1027
+ {
1028
+ "sequence": r["sequence"],
1029
+ "event_type": r["event_type"],
1030
+ "created_at": r["created_at"],
1031
+ "payload": r["payload_json"] if len(r["payload_json"]) <= 400 else r["payload_json"][:400] + "…",
1032
+ }
1033
+ for r in page
1034
+ ]
1035
+ return ToolResult(
1036
+ {
1037
+ "current_revision_id": self.repository.current_revision(self.project_id, self.run_id).revision_id,
1038
+ "versions": film,
1039
+ "revision_count": revisions,
1040
+ "events": events,
1041
+ "next_before_sequence": page[-1]["sequence"] if len(rows) > limit else None,
1042
+ "note": "Versions are complete edits a person can restore; events are newest first and payloads over 400 characters are shortened.",
1043
+ }
1044
+ )
1045
+
1046
+ def _production_read_mutation_receipt(self, args):
513
1047
  with self.repository.projects.connect(self.project_id) as db:
514
- row=db.execute('SELECT mutation_id,tool_name,state,result_json FROM production_tool_receipts WHERE run_id=? AND mutation_id=?',(self.run_id,args['mutation_id'])).fetchone()
515
- if row is None:raise ProjectError('mutation_not_found','找不到這次操作的回報紀錄。',status_code=404)
516
- return ToolResult({'mutation_id':row['mutation_id'],'tool':row['tool_name'],'state':row['state'],
517
- 'result':json.loads(row['result_json']) if row['result_json'] else None,
518
- 'current_revision_id':self.repository.current_revision(self.project_id,self.run_id).revision_id})
1048
+ row = db.execute(
1049
+ "SELECT mutation_id,tool_name,state,result_json FROM production_tool_receipts WHERE run_id=? AND mutation_id=?",
1050
+ (self.run_id, args["mutation_id"]),
1051
+ ).fetchone()
1052
+ if row is None:
1053
+ raise ProjectError("mutation_not_found", "找不到這次操作的回報紀錄。", status_code=404)
1054
+ return ToolResult(
1055
+ {
1056
+ "mutation_id": row["mutation_id"],
1057
+ "tool": row["tool_name"],
1058
+ "state": row["state"],
1059
+ "result": json.loads(row["result_json"]) if row["result_json"] else None,
1060
+ "current_revision_id": self.repository.current_revision(self.project_id, self.run_id).revision_id,
1061
+ }
1062
+ )
519
1063
 
520
- def _production_restore_revision(self,args):
1064
+ def _production_restore_revision(self, args):
521
1065
  with self.repository.projects.connect(self.project_id) as db:
522
- row=db.execute('SELECT payload_json FROM edit_agent_revisions WHERE revision_id=? AND run_id=?',(args['revision_id'],self.run_id)).fetchone()
523
- if row is None:raise problem('版本不屬於這次剪輯。')
1066
+ row = db.execute(
1067
+ "SELECT payload_json FROM edit_agent_revisions WHERE revision_id=? AND run_id=?",
1068
+ (args["revision_id"], self.run_id),
1069
+ ).fetchone()
1070
+ if row is None:
1071
+ raise problem("版本不屬於這次剪輯。")
524
1072
  from clipen.domain import EditTimeline
525
- return self._save(EditTimeline.from_payload(json.loads(row['payload_json'])),args['summary'])
526
1073
 
527
- def _production_export_edit(self,args):
1074
+ return self._save(EditTimeline.from_payload(json.loads(row["payload_json"])), args["summary"])
1075
+
1076
+ def _production_export_edit(self, args):
528
1077
  from .production_media import atomic_json
529
- revision=self.repository.current_revision(self.project_id,self.run_id)
530
- assets=self._asset_store().public_assets()
531
- used={l['asset_id'] for t in revision.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']}
532
- credits=[a['provenance'] for a in assets if a['asset_id'] in used]
533
- path=self._workdir('exports')/(revision.revision_id+'.json')
1078
+
1079
+ revision = self.repository.current_revision(self.project_id, self.run_id)
1080
+ assets = self._asset_store().public_assets()
1081
+ used = {
1082
+ l["asset_id"]
1083
+ for t in revision.timeline.tracks
1084
+ for i in t.items
1085
+ if isinstance(i, MediaClip)
1086
+ for e in i.effects
1087
+ if e.effect_id == "audio.layers"
1088
+ for l in e.parameters["layers"]
1089
+ }
1090
+ credits = [a["provenance"] for a in assets if a["asset_id"] in used]
1091
+ path = self._workdir("exports") / (revision.revision_id + ".json")
534
1092
  from .production_media import load_text_styles
1093
+ from .production_requirements import production_contents
535
1094
  from .program_story import read_episode
536
1095
  from .program_subtitles import subtitle_status
537
- from .production_requirements import production_contents
538
- styles=load_text_styles(self.repository.projects,self.project_id)
539
- used_styles={i.style_id for t in revision.timeline.tracks if t.kind is TrackKind.TITLE for i in t.items}
540
- atomic_json(path,{'timeline':revision.timeline.to_payload(),'credits':credits,'text_styles':{k:v for k,v in styles.items() if k in used_styles},
541
- 'production_contents':production_contents(self.repository.projects,self.project_id,revision.timeline),
542
- 'production_skill':self._skill_value(),'production_intent':self._session_value()['intent'],
543
- 'creative_direction':self.repository.creative_direction(self.project_id,self.run_id),
544
- 'episode':read_episode(self.repository.projects,self.project_id,self.run_id,revision.timeline),
545
- 'subtitle_review':subtitle_status(self.repository.projects,self.project_id,revision.timeline),'format':'clipen.native.v1'})
546
- return ToolResult({'revision_id':revision.revision_id,'export_id':revision.revision_id,'format':'clipen.native.v1','credits':credits,
547
- 'download_url':f'/api/projects/{self.project_id}/edit-agent/{self.run_id}/exports/{revision.revision_id}'})
548
-
549
- def _workdir(self,name):
550
- base=self.repository.projects.root/self.project_id/'agent-production'
551
- for p in (base,base/self.run_id,base/self.run_id/name):
552
- if p.is_symlink():raise problem('製作目錄不安全。')
553
- p.mkdir(mode=0o700,exist_ok=True)
554
- return base/self.run_id/name
1096
+
1097
+ styles = load_text_styles(self.repository.projects, self.project_id)
1098
+ used_styles = {i.style_id for t in revision.timeline.tracks if t.kind is TrackKind.TITLE for i in t.items}
1099
+ atomic_json(
1100
+ path,
1101
+ {
1102
+ "timeline": revision.timeline.to_payload(),
1103
+ "credits": credits,
1104
+ "text_styles": {k: v for k, v in styles.items() if k in used_styles},
1105
+ "production_contents": production_contents(
1106
+ self.repository.projects, self.project_id, revision.timeline
1107
+ ),
1108
+ "production_skill": self._skill_value(),
1109
+ "production_intent": self._session_value()["intent"],
1110
+ "creative_direction": self.repository.creative_direction(self.project_id, self.run_id),
1111
+ "episode": read_episode(self.repository.projects, self.project_id, self.run_id, revision.timeline),
1112
+ "subtitle_review": subtitle_status(self.repository.projects, self.project_id, revision.timeline),
1113
+ "format": "clipen.native.v1",
1114
+ },
1115
+ )
1116
+ return ToolResult(
1117
+ {
1118
+ "revision_id": revision.revision_id,
1119
+ "export_id": revision.revision_id,
1120
+ "format": "clipen.native.v1",
1121
+ "credits": credits,
1122
+ "download_url": f"/api/projects/{self.project_id}/edit-agent/{self.run_id}/exports/{revision.revision_id}",
1123
+ }
1124
+ )
1125
+
1126
+ def _workdir(self, name):
1127
+ base = self.repository.projects.root / self.project_id / "agent-production"
1128
+ for p in (base, base / self.run_id, base / self.run_id / name):
1129
+ if p.is_symlink():
1130
+ raise problem("製作目錄不安全。")
1131
+ p.mkdir(mode=0o700, exist_ok=True)
1132
+ return base / self.run_id / name
555
1133
 
556
1134
  def _cancel_event(self):
557
- if not hasattr(self,'_production_cancel'):self._production_cancel=threading.Event()
1135
+ if not hasattr(self, "_production_cancel"):
1136
+ self._production_cancel = threading.Event()
558
1137
  return self._production_cancel
559
1138
 
560
- def _production_render_preview(self,args):
1139
+ def _production_render_preview(self, args):
561
1140
  from .production_preview import render_preview
1141
+
562
1142
  return render_preview(self)
563
1143
 
564
- def _production_inspect_preview(self,args):
1144
+ def _production_inspect_preview(self, args):
565
1145
  from .production_preview import inspect_preview
566
- return inspect_preview(self,args)
567
1146
 
568
- def _production_inspect_mix(self,args):
569
- from clipen.rendering import PreviewRenderRepository
1147
+ return inspect_preview(self, args)
1148
+
1149
+ def _production_inspect_mix(self, args):
570
1150
  from clipen.projects.storage import utc_now
1151
+ from clipen.rendering import PreviewRenderRepository
1152
+
571
1153
  with self.repository.projects.connect(self.project_id) as db:
572
- entries=[json.loads(r['payload_json']) for r in db.execute("SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='production_preview'",(self.run_id,))]
573
- entry=next((v for v in entries if v['render_id']==args['render_id']),None)
574
- if entry is None:raise problem('混音預覽不屬於這次製作。')
575
- store=PreviewRenderRepository(self.repository.projects)
576
- if store.get(self.project_id,args['render_id'])['state']!='succeeded':raise problem('請先等待預覽完成。')
577
- path=store.output_path(self.project_id,args['render_id'],prepare=False).with_suffix('.mix.json')
578
- if path.is_symlink() or not path.is_file() or path.stat().st_size>512000:
579
- raise ProjectError('mix_evidence_unavailable','這版預覽沒有保存分軌混音證據。',status_code=409)
1154
+ entries = [
1155
+ json.loads(r["payload_json"])
1156
+ for r in db.execute(
1157
+ "SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='production_preview'",
1158
+ (self.run_id,),
1159
+ )
1160
+ ]
1161
+ entry = next((v for v in entries if v["render_id"] == args["render_id"]), None)
1162
+ if entry is None:
1163
+ raise problem("混音預覽不屬於這次製作。")
1164
+ store = PreviewRenderRepository(self.repository.projects)
1165
+ if store.get(self.project_id, args["render_id"])["state"] != "succeeded":
1166
+ raise problem("請先等待預覽完成。")
1167
+ path = store.output_path(self.project_id, args["render_id"], prepare=False).with_suffix(".mix.json")
1168
+ if path.is_symlink() or not path.is_file() or path.stat().st_size > 512000:
1169
+ raise ProjectError("mix_evidence_unavailable", "這版預覽沒有保存分軌混音證據。", status_code=409)
580
1170
  from .production_preview import render_recipe_id
581
- payload={**json.loads(path.read_text()),'revision_id':entry['revision_id'],'render_id':args['render_id'],'recipe_id':entry.get('recipe_id'),
582
- 'stale':entry['revision_id']!=self.repository.current_revision(self.project_id,self.run_id).revision_id or entry.get('recipe_id')!=render_recipe_id()}
1171
+
1172
+ payload = {
1173
+ **json.loads(path.read_text()),
1174
+ "revision_id": entry["revision_id"],
1175
+ "render_id": args["render_id"],
1176
+ "recipe_id": entry.get("recipe_id"),
1177
+ "stale": entry["revision_id"] != self.repository.current_revision(self.project_id, self.run_id).revision_id
1178
+ or entry.get("recipe_id") != render_recipe_id(),
1179
+ }
583
1180
  with self.repository.projects.connect(self.project_id) as db:
584
- self.repository._append_event(db,self.run_id,'mix_review',payload,utc_now())
1181
+ self.repository._append_event(db, self.run_id, "mix_review", payload, utc_now())
585
1182
  return ToolResult(payload)
586
1183
 
587
- def _production_cancel_preview(self,args):
1184
+ def _production_cancel_preview(self, args):
588
1185
  from .production_preview import cancel_preview
589
- return cancel_preview(self,args)
1186
+
1187
+ return cancel_preview(self, args)
590
1188
 
591
1189
  def close_production(self):
592
1190
  self._cancel_event().set()
593
- for cancel,thread in getattr(self,'_evidence_jobs',{}).values():cancel.set()
594
- for cancel,thread in getattr(self,'_preview_jobs',{}).values():cancel.set()
595
- for cancel,thread in getattr(self,'_evidence_jobs',{}).values():thread.join(3)
596
- for cancel,thread in getattr(self,'_preview_jobs',{}).values():thread.join(3)
1191
+ for cancel, thread in getattr(self, "_evidence_jobs", {}).values():
1192
+ cancel.set()
1193
+ for cancel, thread in getattr(self, "_preview_jobs", {}).values():
1194
+ cancel.set()
1195
+ for cancel, thread in getattr(self, "_evidence_jobs", {}).values():
1196
+ thread.join(3)
1197
+ for cancel, thread in getattr(self, "_preview_jobs", {}).values():
1198
+ thread.join(3)