@clipen/clipen-cli 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +56 -48
  2. package/apps/web/dist/assets/{index-D5D2HiB1.js → index-DPHwA954.js} +1 -1
  3. package/apps/web/dist/index.html +1 -1
  4. package/bin/clipen.js +1 -1
  5. package/package.json +7 -6
  6. package/pyproject.toml +18 -2
  7. package/requirements/dev.txt +2 -0
  8. package/src/clipen/__init__.py +1 -1
  9. package/src/clipen/analysis/__init__.py +7 -7
  10. package/src/clipen/analysis/artifacts.py +4 -10
  11. package/src/clipen/analysis/audio.py +10 -8
  12. package/src/clipen/analysis/evidence_service.py +345 -167
  13. package/src/clipen/analysis/image_similarity.py +5 -14
  14. package/src/clipen/analysis/keyframes.py +5 -17
  15. package/src/clipen/analysis/models.py +5 -7
  16. package/src/clipen/analysis/qwen_worker.py +19 -54
  17. package/src/clipen/analysis/resources.py +2 -1
  18. package/src/clipen/analysis/runtime.py +1 -3
  19. package/src/clipen/analysis/service.py +16 -48
  20. package/src/clipen/analysis/setup.py +11 -25
  21. package/src/clipen/analysis/setup_cli.py +5 -15
  22. package/src/clipen/analysis/storage.py +96 -278
  23. package/src/clipen/analysis/transcription.py +40 -82
  24. package/src/clipen/analysis/visual.py +109 -48
  25. package/src/clipen/annotations/__init__.py +5 -2
  26. package/src/clipen/annotations/models.py +1 -1
  27. package/src/clipen/annotations/storage.py +132 -84
  28. package/src/clipen/annotations/suggestions.py +3 -8
  29. package/src/clipen/asr_release.py +4 -11
  30. package/src/clipen/bootstrap.py +71 -61
  31. package/src/clipen/{planning/models.py → candidates.py} +29 -47
  32. package/src/clipen/cli.py +4 -9
  33. package/src/clipen/controller/app.py +401 -214
  34. package/src/clipen/controller/server.py +28 -38
  35. package/src/clipen/domain/__init__.py +1 -1
  36. package/src/clipen/domain/media_time.py +3 -10
  37. package/src/clipen/domain/timeline.py +45 -47
  38. package/src/clipen/domain/validation.py +0 -1
  39. package/src/clipen/editing/__init__.py +1 -1
  40. package/src/clipen/editing/agent_models.py +4 -11
  41. package/src/clipen/editing/agent_repository.py +393 -172
  42. package/src/clipen/editing/agent_tools.py +180 -99
  43. package/src/clipen/editing/alignment.py +92 -52
  44. package/src/clipen/editing/alignment_setup.py +118 -70
  45. package/src/clipen/editing/alignment_worker.py +11 -9
  46. package/src/clipen/editing/change_report.py +95 -38
  47. package/src/clipen/editing/compiler.py +0 -1
  48. package/src/clipen/editing/component_looks.py +58 -34
  49. package/src/clipen/editing/component_review.py +34 -38
  50. package/src/clipen/editing/coordinator.py +213 -92
  51. package/src/clipen/editing/editorial_review.py +217 -95
  52. package/src/clipen/editing/evidence_jobs.py +457 -200
  53. package/src/clipen/editing/history_changes.py +129 -68
  54. package/src/clipen/editing/music_choices.py +8 -5
  55. package/src/clipen/editing/production_catalog.py +573 -136
  56. package/src/clipen/editing/production_limits.py +43 -17
  57. package/src/clipen/editing/production_media.py +376 -167
  58. package/src/clipen/editing/production_preview.py +322 -129
  59. package/src/clipen/editing/production_progress.py +164 -69
  60. package/src/clipen/editing/production_requirements.py +106 -39
  61. package/src/clipen/editing/production_tools.py +1064 -462
  62. package/src/clipen/editing/program_audio.py +211 -81
  63. package/src/clipen/editing/program_direction.py +59 -25
  64. package/src/clipen/editing/program_story.py +83 -45
  65. package/src/clipen/editing/program_subtitles.py +194 -96
  66. package/src/clipen/editing/programme_review.py +98 -50
  67. package/src/clipen/editing/prompt_history.py +64 -27
  68. package/src/clipen/editing/recut.py +65 -25
  69. package/src/clipen/editing/refinement_references.py +176 -86
  70. package/src/clipen/editing/resolve_export.py +449 -218
  71. package/src/clipen/editing/resolve_titles.py +162 -105
  72. package/src/clipen/editing/skill_tools.py +530 -154
  73. package/src/clipen/editing/source_dialogue.py +177 -67
  74. package/src/clipen/editing/speech_coverage.py +42 -22
  75. package/src/clipen/editing/speech_quality.py +6 -1
  76. package/src/clipen/editing/tool_receipts.py +78 -32
  77. package/src/clipen/editing/versions.py +122 -64
  78. package/src/clipen/editing/visual_preview.py +157 -61
  79. package/src/clipen/editing/workbench.py +104 -42
  80. package/src/clipen/finishing/audio.py +69 -30
  81. package/src/clipen/finishing/catalog.py +176 -93
  82. package/src/clipen/finishing/models.py +1 -1
  83. package/src/clipen/finishing/renderer.py +33 -14
  84. package/src/clipen/mcp_editing/__main__.py +3 -1
  85. package/src/clipen/mcp_editing/server.py +77 -34
  86. package/src/clipen/media/__init__.py +3 -3
  87. package/src/clipen/media/discovery.py +7 -20
  88. package/src/clipen/media/models.py +7 -18
  89. package/src/clipen/media/preview.py +14 -24
  90. package/src/clipen/media/probe.py +16 -44
  91. package/src/clipen/media/service.py +6 -19
  92. package/src/clipen/media/storage.py +33 -81
  93. package/src/clipen/music_vocabulary.py +33 -4
  94. package/src/clipen/power.py +8 -3
  95. package/src/clipen/projects/__init__.py +1 -1
  96. package/src/clipen/projects/deletion.py +19 -32
  97. package/src/clipen/projects/finishing_schema.py +3 -1
  98. package/src/clipen/projects/models.py +2 -5
  99. package/src/clipen/projects/picker.py +13 -37
  100. package/src/clipen/projects/service.py +8 -24
  101. package/src/clipen/projects/storage.py +226 -246
  102. package/src/clipen/provider_registry.py +9 -20
  103. package/src/clipen/providers/account.py +86 -35
  104. package/src/clipen/providers/claude.py +59 -25
  105. package/src/clipen/providers/claude_editing.py +14 -7
  106. package/src/clipen/providers/codex.py +73 -118
  107. package/src/clipen/providers/codex_editing.py +2 -2
  108. package/src/clipen/providers/editing_agent.py +19 -17
  109. package/src/clipen/providers/recovery.py +7 -8
  110. package/src/clipen/rendering/cover.py +18 -5
  111. package/src/clipen/rendering/custom_components.py +167 -79
  112. package/src/clipen/rendering/custom_render.py +62 -41
  113. package/src/clipen/rendering/production_effects.py +77 -45
  114. package/src/clipen/rendering/program_components.py +134 -73
  115. package/src/clipen/rendering/program_creator.py +432 -277
  116. package/src/clipen/rendering/program_identities.py +277 -182
  117. package/src/clipen/rendering/program_motion.py +140 -95
  118. package/src/clipen/rendering/program_studio.py +175 -116
  119. package/src/clipen/rendering/program_styles.py +231 -145
  120. package/src/clipen/rendering/program_subtitles.py +71 -34
  121. package/src/clipen/rendering/renderer.py +150 -121
  122. package/src/clipen/rendering/storage.py +9 -22
  123. package/src/clipen/rendering/titles.py +193 -86
  124. package/src/clipen/skills/__init__.py +1 -0
  125. package/src/clipen/skills/catalog.py +151 -55
  126. package/src/clipen/skills/library.py +13 -7
  127. package/src/clipen/skills/package.py +46 -23
  128. package/src/clipen/skills/visual_styles.py +29 -18
  129. package/src/clipen/workspace.py +15 -44
  130. package/install +0 -25
  131. package/src/clipen/planning/__init__.py +0 -9
  132. package/uninstall +0 -25
@@ -1,295 +1,552 @@
1
1
  """On-demand local source speech jobs, independent of the legacy preparation stage."""
2
- from fractions import Fraction
3
- import json
2
+
4
3
  import hashlib
4
+ import json
5
5
  import math
6
- from pathlib import Path
7
6
  import threading
8
7
  import time
9
8
  import wave
9
+ from fractions import Fraction
10
+ from pathlib import Path
10
11
 
11
12
  from clipen.domain import TrackKind
12
13
  from clipen.projects import ProjectError
13
14
  from clipen.projects.storage import utc_now
15
+
14
16
  from .agent_models import ToolResult, encoded, make_id
15
17
 
16
18
 
17
19
  class EvidenceTools:
18
- def _production_prepare_local_speech(self,args):
19
- session=self._session_value()
20
- if not session['intent'].get('allow_local_model_downloads'):
21
- raise ProjectError('local_model_grant_required','這次製作尚未授權準備本機模型。',status_code=409)
22
- return self._start_evidence('setup',{'target':args['target'],'release':'clipen-local-speech-v1'},None)
20
+ def _production_prepare_local_speech(self, args):
21
+ session = self._session_value()
22
+ if not session["intent"].get("allow_local_model_downloads"):
23
+ raise ProjectError("local_model_grant_required", "這次製作尚未授權準備本機模型。", status_code=409)
24
+ return self._start_evidence("setup", {"target": args["target"], "release": "clipen-local-speech-v1"}, None)
23
25
 
24
26
  def _production_transcribe_source_range(self, args):
25
- candidate = self._candidate(args['candidate_id'])
27
+ candidate = self._candidate(args["candidate_id"])
26
28
  span = candidate.source
27
- duration = float(span.duration_pts*Fraction(span.time_base.numerator,span.time_base.denominator))
28
- if duration>60:
29
- raise ProjectError('speech_range_too_large', '單次按需語音分析最多 60 秒,請縮小來源範圍。', status_code=422)
30
- binding = getattr(self, 'transcriber_binding', None)
31
- if binding is None or (runtime:=binding()) is None:
32
- raise ProjectError('asr_unavailable', '本機語音辨識尚未就緒,請先安裝或修復本機語音環境。', status_code=409)
33
- request = {'source':span.to_storage(), 'language':args.get('language','zh'),
34
- 'align_words':args.get('align_words',True), 'model':runtime[1]}
35
- if request['align_words']:
29
+ duration = float(span.duration_pts * Fraction(span.time_base.numerator, span.time_base.denominator))
30
+ if duration > 60:
31
+ raise ProjectError(
32
+ "speech_range_too_large", "單次按需語音分析最多 60 秒,請縮小來源範圍。", status_code=422
33
+ )
34
+ binding = getattr(self, "transcriber_binding", None)
35
+ if binding is None or (runtime := binding()) is None:
36
+ raise ProjectError("asr_unavailable", "本機語音辨識尚未就緒,請先安裝或修復本機語音環境。", status_code=409)
37
+ request = {
38
+ "source": span.to_storage(),
39
+ "language": args.get("language", "zh"),
40
+ "align_words": args.get("align_words", True),
41
+ "model": runtime[1],
42
+ }
43
+ if request["align_words"]:
36
44
  from .alignment import REVISION
37
- request['alignment_revision']=REVISION
38
- return self._start_evidence('transcribe', request, runtime[0])
45
+
46
+ request["alignment_revision"] = REVISION
47
+ return self._start_evidence("transcribe", request, runtime[0])
39
48
 
40
49
  def _production_align_source_speech(self, args):
41
- job = self._evidence_job(args['transcript_job_id'])
42
- if job['state']!='succeeded' or job['kind']!='transcribe':
43
- raise ProjectError('transcript_job_required', '請指定已完成的來源轉寫工作。', status_code=422)
50
+ job = self._evidence_job(args["transcript_job_id"])
51
+ if job["state"] != "succeeded" or job["kind"] != "transcribe":
52
+ raise ProjectError("transcript_job_required", "請指定已完成的來源轉寫工作。", status_code=422)
44
53
  from .alignment import REVISION
45
- request = {**job['request'], 'transcript_job_id':job['job_id'], 'alignment_revision':REVISION}
46
- return self._start_evidence('align', request, None)
47
54
 
48
- def _production_retry_evidence_job(self,args):
49
- job=self._evidence_job(args['job_id'])
50
- if job['state'] not in {'failed','cancelled','interrupted'}:
51
- raise ProjectError('evidence_retry_invalid','只能重試已失敗、取消或中斷的本機工作。',status_code=409)
52
- request={**job['request'],'retry_request_id':args['request_id']}
53
- factory=None
54
- if job['kind']=='transcribe':
55
- binding=getattr(self,'transcriber_binding',None)
56
- runtime=binding() if binding else None
57
- if runtime is None:raise ProjectError('asr_unavailable','請先準備本機語音環境。',status_code=409)
58
- factory=runtime[0];request['model']=runtime[1]
59
- return self._start_evidence(job['kind'],request,factory)
55
+ request = {**job["request"], "transcript_job_id": job["job_id"], "alignment_revision": REVISION}
56
+ return self._start_evidence("align", request, None)
57
+
58
+ def _production_retry_evidence_job(self, args):
59
+ job = self._evidence_job(args["job_id"])
60
+ if job["state"] not in {"failed", "cancelled", "interrupted"}:
61
+ raise ProjectError("evidence_retry_invalid", "只能重試已失敗、取消或中斷的本機工作。", status_code=409)
62
+ request = {**job["request"], "retry_request_id": args["request_id"]}
63
+ factory = None
64
+ if job["kind"] == "transcribe":
65
+ binding = getattr(self, "transcriber_binding", None)
66
+ runtime = binding() if binding else None
67
+ if runtime is None:
68
+ raise ProjectError("asr_unavailable", "請先準備本機語音環境。", status_code=409)
69
+ factory = runtime[0]
70
+ request["model"] = runtime[1]
71
+ return self._start_evidence(job["kind"], request, factory)
60
72
 
61
- def _production_revise_source_speech(self,args):
62
- job=self._evidence_job(args['transcript_job_id'])
63
- if job['state']!='succeeded' or job['kind'] not in {'transcribe','align'}:
64
- raise ProjectError('transcript_job_required','請指定已完成的來源口語工作。',status_code=422)
65
- index=args['segment_ordinal']
66
- if index>=len(job['result']['segments']):
67
- raise ProjectError('speech_segment_missing','指定口語段落不存在。',status_code=422)
73
+ def _production_revise_source_speech(self, args):
74
+ job = self._evidence_job(args["transcript_job_id"])
75
+ if job["state"] != "succeeded" or job["kind"] not in {"transcribe", "align"}:
76
+ raise ProjectError("transcript_job_required", "請指定已完成的來源口語工作。", status_code=422)
77
+ index = args["segment_ordinal"]
78
+ if index >= len(job["result"]["segments"]):
79
+ raise ProjectError("speech_segment_missing", "指定口語段落不存在。", status_code=422)
68
80
  from .alignment import REVISION
69
- request={**job['request'],'transcript_job_id':job['job_id'],'alignment_revision':REVISION,
70
- 'correction':{key:args[key] for key in ('segment_ordinal','text','evidence')}}
71
- return self._start_evidence('align',request,None)
81
+
82
+ request = {
83
+ **job["request"],
84
+ "transcript_job_id": job["job_id"],
85
+ "alignment_revision": REVISION,
86
+ "correction": {key: args[key] for key in ("segment_ordinal", "text", "evidence")},
87
+ }
88
+ return self._start_evidence("align", request, None)
72
89
 
73
90
  def _evidence_job(self, job_id):
74
91
  with self.repository.projects.connect(self.project_id) as db:
75
- row = db.execute('SELECT * FROM production_evidence_jobs WHERE job_id=? AND run_id=?', (job_id,self.run_id)).fetchone()
92
+ row = db.execute(
93
+ "SELECT * FROM production_evidence_jobs WHERE job_id=? AND run_id=?", (job_id, self.run_id)
94
+ ).fetchone()
76
95
  if row is None:
77
- raise ProjectError('evidence_job_not_found','證據工作不屬於這次製作。',status_code=404)
78
- return {'job_id':row['job_id'], 'kind':row['kind'], 'state':row['state'],
79
- 'request':json.loads(row['request_json']), 'result':json.loads(row['result_json']) if row['result_json'] else None,
80
- 'error_code':row['error_code']}
96
+ raise ProjectError("evidence_job_not_found", "證據工作不屬於這次製作。", status_code=404)
97
+ return {
98
+ "job_id": row["job_id"],
99
+ "kind": row["kind"],
100
+ "state": row["state"],
101
+ "request": json.loads(row["request_json"]),
102
+ "result": json.loads(row["result_json"]) if row["result_json"] else None,
103
+ "error_code": row["error_code"],
104
+ }
81
105
 
82
106
  def _start_evidence(self, kind, request, factory):
83
107
  from clipen.analysis import transcription
84
- recipe=hashlib.sha256()
85
- for path in (Path(__file__),Path(__file__).with_name('alignment.py'),Path(__file__).with_name('alignment_worker.py'),
86
- Path(transcription.__file__),Path(transcription.__file__).with_name('qwen_worker.py')):
108
+
109
+ recipe = hashlib.sha256()
110
+ for path in (
111
+ Path(__file__),
112
+ Path(__file__).with_name("alignment.py"),
113
+ Path(__file__).with_name("alignment_worker.py"),
114
+ Path(transcription.__file__),
115
+ Path(transcription.__file__).with_name("qwen_worker.py"),
116
+ ):
87
117
  recipe.update(path.read_bytes())
88
- key = make_id('evidence_', [kind,request,recipe.hexdigest()])
89
- identifier = make_id('speech_', [self.run_id,key])
118
+ key = make_id("evidence_", [kind, request, recipe.hexdigest()])
119
+ identifier = make_id("speech_", [self.run_id, key])
90
120
  with self.repository.projects.connect(self.project_id) as db:
91
- db.execute('BEGIN IMMEDIATE')
92
- existing = db.execute('SELECT job_id FROM production_evidence_jobs WHERE run_id=? AND cache_key=?', (self.run_id,key)).fetchone()
121
+ db.execute("BEGIN IMMEDIATE")
122
+ existing = db.execute(
123
+ "SELECT job_id FROM production_evidence_jobs WHERE run_id=? AND cache_key=?", (self.run_id, key)
124
+ ).fetchone()
93
125
  if existing:
94
126
  db.rollback()
95
- return ToolResult({'job':self._evidence_job(existing['job_id']), 'reused':True})
96
- cached=db.execute("SELECT job_id,run_id,result_json FROM production_evidence_jobs WHERE cache_key=? AND state='succeeded' AND kind!='setup' ORDER BY rowid DESC LIMIT 1",(key,)).fetchone()
127
+ return ToolResult({"job": self._evidence_job(existing["job_id"]), "reused": True})
128
+ cached = db.execute(
129
+ "SELECT job_id,run_id,result_json FROM production_evidence_jobs WHERE cache_key=? AND state='succeeded' AND kind!='setup' ORDER BY rowid DESC LIMIT 1",
130
+ (key,),
131
+ ).fetchone()
97
132
  if cached is not None:
98
- result={**json.loads(cached['result_json']),'cache_provenance':{'job_id':cached['job_id'],'run_id':cached['run_id']}}
99
- db.execute('INSERT INTO production_evidence_jobs VALUES(?,?,?,?,?,?,?,?,?)',
100
- (identifier,self.run_id,key,kind,'succeeded',encoded(request),encoded(result),None,utc_now()))
133
+ result = {
134
+ **json.loads(cached["result_json"]),
135
+ "cache_provenance": {"job_id": cached["job_id"], "run_id": cached["run_id"]},
136
+ }
137
+ db.execute(
138
+ "INSERT INTO production_evidence_jobs VALUES(?,?,?,?,?,?,?,?,?)",
139
+ (
140
+ identifier,
141
+ self.run_id,
142
+ key,
143
+ kind,
144
+ "succeeded",
145
+ encoded(request),
146
+ encoded(result),
147
+ None,
148
+ utc_now(),
149
+ ),
150
+ )
101
151
  db.commit()
102
- return ToolResult({'job':self._evidence_job(identifier),'reused':True})
103
- if db.execute("SELECT 1 FROM production_evidence_jobs WHERE run_id=? AND state='running'", (self.run_id,)).fetchone():
104
- raise ProjectError('evidence_busy', '已有本機語音工作執行中,請先讀取或取消。', status_code=409)
105
- db.execute('INSERT INTO production_evidence_jobs VALUES(?,?,?,?,?,?,?,?,?)',
106
- (identifier,self.run_id,key,kind,'running',encoded(request),None,None,utc_now()))
152
+ return ToolResult({"job": self._evidence_job(identifier), "reused": True})
153
+ if db.execute(
154
+ "SELECT 1 FROM production_evidence_jobs WHERE run_id=? AND state='running'", (self.run_id,)
155
+ ).fetchone():
156
+ raise ProjectError("evidence_busy", "已有本機語音工作執行中,請先讀取或取消。", status_code=409)
157
+ db.execute(
158
+ "INSERT INTO production_evidence_jobs VALUES(?,?,?,?,?,?,?,?,?)",
159
+ (identifier, self.run_id, key, kind, "running", encoded(request), None, None, utc_now()),
160
+ )
107
161
  db.commit()
108
162
  cancel = threading.Event()
109
- if not hasattr(self,'_evidence_jobs'):self._evidence_jobs={}
110
- worker = threading.Thread(target=self._run_evidence,args=(identifier,factory,cancel),daemon=True,name='clipen-source-speech')
111
- self._evidence_jobs[identifier]=(cancel,worker)
163
+ if not hasattr(self, "_evidence_jobs"):
164
+ self._evidence_jobs = {}
165
+ worker = threading.Thread(
166
+ target=self._run_evidence, args=(identifier, factory, cancel), daemon=True, name="clipen-source-speech"
167
+ )
168
+ self._evidence_jobs[identifier] = (cancel, worker)
112
169
  worker.start()
113
- return ToolResult({'job':self._evidence_job(identifier),'reused':False})
170
+ return ToolResult({"job": self._evidence_job(identifier), "reused": False})
114
171
 
115
172
  def _run_evidence(self, identifier, factory, cancel):
116
173
  transcriber = None
117
174
  try:
118
175
  from clipen.analysis.audio import PreparedAudio
119
- from clipen.media import MediaPreviewRepository
120
176
  from clipen.finishing.audio import run_process
177
+ from clipen.media import MediaPreviewRepository
178
+
121
179
  from .alignment import REVISION, run_alignment, validate_alignment
180
+
122
181
  job = self._evidence_job(identifier)
123
- if job['kind']=='setup':
182
+ if job["kind"] == "setup":
183
+
124
184
  def progress(value):
125
185
  with self.repository.projects.connect(self.project_id) as db:
126
- db.execute("UPDATE production_evidence_jobs SET result_json=? WHERE job_id=? AND state='running'",(encoded(value),identifier))
127
- if job['request']['target']=='alignment':
186
+ db.execute(
187
+ "UPDATE production_evidence_jobs SET result_json=? WHERE job_id=? AND state='running'",
188
+ (encoded(value), identifier),
189
+ )
190
+
191
+ if job["request"]["target"] == "alignment":
128
192
  from .alignment_setup import install_runtime
129
- result=install_runtime(getattr(self,'local_data_root',None),cancel,progress)
193
+
194
+ result = install_runtime(getattr(self, "local_data_root", None), cancel, progress)
130
195
  else:
131
- setup=getattr(self,'asr_setup_manager',None)
132
- if setup is None:raise ProjectError('asr_unavailable','語音環境尚未設定。',status_code=409)
196
+ setup = getattr(self, "asr_setup_manager", None)
197
+ if setup is None:
198
+ raise ProjectError("asr_unavailable", "語音環境尚未設定。", status_code=409)
133
199
  from clipen.asr_release import NOTICE_VERSION
200
+
134
201
  setup.start_install(NOTICE_VERSION)
135
- while setup.status().state.value=='installing':
136
- if cancel.wait(.5):
202
+ while setup.status().state.value == "installing":
203
+ if cancel.wait(0.5):
137
204
  setup.cancel_install()
138
- raise ProjectError('user_cancelled','已取消本機語音環境準備。',status_code=409)
139
- if setup.status().state.value!='ready':raise ProjectError('asr_setup_failed','本機語音環境準備失敗。',status_code=409)
140
- result={'ready':True,'target':'transcription'}
205
+ raise ProjectError("user_cancelled", "已取消本機語音環境準備。", status_code=409)
206
+ if setup.status().state.value != "ready":
207
+ raise ProjectError("asr_setup_failed", "本機語音環境準備失敗。", status_code=409)
208
+ result = {"ready": True, "target": "transcription"}
141
209
  with self.repository.projects.connect(self.project_id) as db:
142
- db.execute("UPDATE production_evidence_jobs SET state='succeeded',result_json=? WHERE job_id=? AND state='running'",(encoded(result),identifier))
210
+ db.execute(
211
+ "UPDATE production_evidence_jobs SET state='succeeded',result_json=? WHERE job_id=? AND state='running'",
212
+ (encoded(result), identifier),
213
+ )
143
214
  return
144
- request = job['request'];span=request['source']
145
- unit=Fraction(span['time_base']['num'],span['time_base']['den'])
146
- start=float(int(span['start_pts'])*unit);duration=float((int(span['end_pts'])-int(span['start_pts']))*unit)
147
- directory=self._workdir('evidence')/identifier
148
- directory.mkdir(mode=0o700,exist_ok=True)
149
- audio=directory/'source.wav'
150
- media=(getattr(self,'media',None) or MediaPreviewRepository(self.repository.projects)).open(self.project_id,span['version_id'])
215
+ request = job["request"]
216
+ span = request["source"]
217
+ unit = Fraction(span["time_base"]["num"], span["time_base"]["den"])
218
+ start = float(int(span["start_pts"]) * unit)
219
+ duration = float((int(span["end_pts"]) - int(span["start_pts"])) * unit)
220
+ directory = self._workdir("evidence") / identifier
221
+ directory.mkdir(mode=0o700, exist_ok=True)
222
+ audio = directory / "source.wav"
223
+ media = (getattr(self, "media", None) or MediaPreviewRepository(self.repository.projects)).open(
224
+ self.project_id, span["version_id"]
225
+ )
151
226
  try:
152
227
  if not media.audio_stream_indices:
153
- raise ProjectError('source_audio_missing','指定素材沒有音訊。',status_code=422)
154
- stream=span['stream_index'] if span['stream_index'] in media.audio_stream_indices else media.audio_stream_indices[0]
155
- run_process(['ffmpeg','-v','error','-nostdin','-y','-seek_timestamp','1','-ss',str(start),'-i',f'/dev/fd/{media.descriptor}',
156
- '-map',f'0:{stream}','-t',str(duration),'-ac','1','-ar','16000','-c:a','pcm_s16le',str(audio)],
157
- cancel,pass_fds=(media.descriptor,),timeout=90)
158
- finally:media.close()
159
- with wave.open(str(audio),'rb') as wav:
160
- prepared=PreparedAudio(audio,wav.getframerate(),wav.getnchannels(),wav.getsampwidth(),wav.getnframes())
161
- if job['kind']=='transcribe':
162
- transcriber=factory()
163
- transcript_output=directory/'transcript.json'
164
- transcript_output.touch(mode=0o600,exist_ok=False)
165
- result=transcriber.transcribe(prepared,transcript_output,language=request['language'],cancel=cancel)
166
- segments=[{'text':seg.text,'start_seconds':seg.start_sample/16000,
167
- 'end_seconds':seg.end_sample/16000} for seg in result.segments]
228
+ raise ProjectError("source_audio_missing", "指定素材沒有音訊。", status_code=422)
229
+ stream = (
230
+ span["stream_index"]
231
+ if span["stream_index"] in media.audio_stream_indices
232
+ else media.audio_stream_indices[0]
233
+ )
234
+ run_process(
235
+ [
236
+ "ffmpeg",
237
+ "-v",
238
+ "error",
239
+ "-nostdin",
240
+ "-y",
241
+ "-seek_timestamp",
242
+ "1",
243
+ "-ss",
244
+ str(start),
245
+ "-i",
246
+ f"/dev/fd/{media.descriptor}",
247
+ "-map",
248
+ f"0:{stream}",
249
+ "-t",
250
+ str(duration),
251
+ "-ac",
252
+ "1",
253
+ "-ar",
254
+ "16000",
255
+ "-c:a",
256
+ "pcm_s16le",
257
+ str(audio),
258
+ ],
259
+ cancel,
260
+ pass_fds=(media.descriptor,),
261
+ timeout=90,
262
+ )
263
+ finally:
264
+ media.close()
265
+ with wave.open(str(audio), "rb") as wav:
266
+ prepared = PreparedAudio(
267
+ audio, wav.getframerate(), wav.getnchannels(), wav.getsampwidth(), wav.getnframes()
268
+ )
269
+ if job["kind"] == "transcribe":
270
+ transcriber = factory()
271
+ transcript_output = directory / "transcript.json"
272
+ transcript_output.touch(mode=0o600, exist_ok=False)
273
+ result = transcriber.transcribe(
274
+ prepared, transcript_output, language=request["language"], cancel=cancel
275
+ )
276
+ segments = [
277
+ {"text": seg.text, "start_seconds": seg.start_sample / 16000, "end_seconds": seg.end_sample / 16000}
278
+ for seg in result.segments
279
+ ]
168
280
  else:
169
- segments=self._evidence_job(request['transcript_job_id'])['result']['segments']
170
- correction=request.get('correction')
281
+ segments = self._evidence_job(request["transcript_job_id"])["result"]["segments"]
282
+ correction = request.get("correction")
171
283
  if correction:
172
- segment=segments[correction['segment_ordinal']]
173
- segment.update({'source_asr_text':segment.get('source_asr_text',segment['text']),
174
- 'text':correction['text'],'wording_authority':'model_proposed_correction',
175
- 'correction_evidence':correction['evidence']})
176
- segment.pop('words',None)
177
- alignment_error=None
178
- if job['kind']=='align' or request.get('align_words'):
179
- for index,segment in enumerate(segments):
180
- if job['kind']=='align' and request.get('correction') and index!=request['correction']['segment_ordinal']:continue
181
- if not segment['text'].strip():continue
182
- chunk=directory/f'align-{index}.wav'
183
- length=segment['end_seconds']-segment['start_seconds']
184
- run_process(['ffmpeg','-v','error','-nostdin','-y','-ss',str(segment['start_seconds']),'-i',str(audio),'-t',str(length),
185
- '-ac','1','-ar','16000','-c:a','pcm_s16le',str(chunk)],cancel,timeout=30)
284
+ segment = segments[correction["segment_ordinal"]]
285
+ segment.update(
286
+ {
287
+ "source_asr_text": segment.get("source_asr_text", segment["text"]),
288
+ "text": correction["text"],
289
+ "wording_authority": "model_proposed_correction",
290
+ "correction_evidence": correction["evidence"],
291
+ }
292
+ )
293
+ segment.pop("words", None)
294
+ alignment_error = None
295
+ if job["kind"] == "align" or request.get("align_words"):
296
+ for index, segment in enumerate(segments):
297
+ if (
298
+ job["kind"] == "align"
299
+ and request.get("correction")
300
+ and index != request["correction"]["segment_ordinal"]
301
+ ):
302
+ continue
303
+ if not segment["text"].strip():
304
+ continue
305
+ chunk = directory / f"align-{index}.wav"
306
+ length = segment["end_seconds"] - segment["start_seconds"]
307
+ run_process(
308
+ [
309
+ "ffmpeg",
310
+ "-v",
311
+ "error",
312
+ "-nostdin",
313
+ "-y",
314
+ "-ss",
315
+ str(segment["start_seconds"]),
316
+ "-i",
317
+ str(audio),
318
+ "-t",
319
+ str(length),
320
+ "-ac",
321
+ "1",
322
+ "-ar",
323
+ "16000",
324
+ "-c:a",
325
+ "pcm_s16le",
326
+ str(chunk),
327
+ ],
328
+ cancel,
329
+ timeout=30,
330
+ )
186
331
  try:
187
- raw=run_alignment(getattr(self,'local_data_root',None),chunk,segment['text'],request['language'],directory/f'words-{index}.json',cancel)
188
- words=validate_alignment(raw,segment['text'],length)
189
- segment['words']=[{**word,'start_seconds':segment['start_seconds']+word['start_seconds'],
190
- 'end_seconds':segment['start_seconds']+word['end_seconds']} for word in words]
332
+ raw = run_alignment(
333
+ getattr(self, "local_data_root", None),
334
+ chunk,
335
+ segment["text"],
336
+ request["language"],
337
+ directory / f"words-{index}.json",
338
+ cancel,
339
+ )
340
+ words = validate_alignment(raw, segment["text"], length)
341
+ segment["words"] = [
342
+ {
343
+ **word,
344
+ "start_seconds": segment["start_seconds"] + word["start_seconds"],
345
+ "end_seconds": segment["start_seconds"] + word["end_seconds"],
346
+ }
347
+ for word in words
348
+ ]
191
349
  except ProjectError as error:
192
- if job['kind']=='align':raise
193
- alignment_error=error.code
194
- payload={'source':span,'segments':segments,'verification':'asr_draft',
195
- 'timing_basis':'forced_alignment' if segments and all(s.get('words') for s in segments) else 'asr_segment',
196
- 'alignment_revision':REVISION if any(s.get('words') for s in segments) else None,
197
- 'alignment_error':alignment_error,'audio_listened':False,'source_start_seconds':start,
198
- 'coverage_seconds':float(prepared.duration_seconds)}
350
+ if job["kind"] == "align":
351
+ raise
352
+ alignment_error = error.code
353
+ payload = {
354
+ "source": span,
355
+ "segments": segments,
356
+ "verification": "asr_draft",
357
+ "timing_basis": "forced_alignment"
358
+ if segments and all(s.get("words") for s in segments)
359
+ else "asr_segment",
360
+ "alignment_revision": REVISION if any(s.get("words") for s in segments) else None,
361
+ "alignment_error": alignment_error,
362
+ "audio_listened": False,
363
+ "source_start_seconds": start,
364
+ "coverage_seconds": float(prepared.duration_seconds),
365
+ }
199
366
  if cancel.is_set() or self._cancel_event().is_set():
200
- raise ProjectError('user_cancelled','已取消來源證據工作。',status_code=409)
367
+ raise ProjectError("user_cancelled", "已取消來源證據工作。", status_code=409)
201
368
  with self.repository.projects.connect(self.project_id) as db:
202
- db.execute("UPDATE production_evidence_jobs SET state='succeeded',result_json=? WHERE job_id=? AND state='running'", (encoded(payload),identifier))
369
+ db.execute(
370
+ "UPDATE production_evidence_jobs SET state='succeeded',result_json=? WHERE job_id=? AND state='running'",
371
+ (encoded(payload), identifier),
372
+ )
203
373
  except Exception as error:
204
374
  with self.repository.projects.connect(self.project_id) as db:
205
- db.execute('UPDATE production_evidence_jobs SET state=?,error_code=? WHERE job_id=? AND state=\'running\'',
206
- ('cancelled' if cancel.is_set() or self._cancel_event().is_set() else 'failed',getattr(error,'code','source_evidence_failed'),identifier))
375
+ db.execute(
376
+ "UPDATE production_evidence_jobs SET state=?,error_code=? WHERE job_id=? AND state='running'",
377
+ (
378
+ "cancelled" if cancel.is_set() or self._cancel_event().is_set() else "failed",
379
+ getattr(error, "code", "source_evidence_failed"),
380
+ identifier,
381
+ ),
382
+ )
207
383
  finally:
208
- if transcriber is not None:transcriber.close()
384
+ if transcriber is not None:
385
+ transcriber.close()
209
386
 
210
387
  def _production_read_evidence_job(self, args):
211
- deadline=time.monotonic()+args.get('wait_seconds',0)
212
- while (job:=self._evidence_job(args['job_id']))['state']=='running' and time.monotonic()<deadline:
213
- time.sleep(.1)
214
- return ToolResult({'job':job})
388
+ deadline = time.monotonic() + args.get("wait_seconds", 0)
389
+ while (job := self._evidence_job(args["job_id"]))["state"] == "running" and time.monotonic() < deadline:
390
+ time.sleep(0.1)
391
+ return ToolResult({"job": job})
215
392
 
216
393
  def _production_cancel_evidence_job(self, args):
217
- job=self._evidence_job(args['job_id'])
218
- token=getattr(self,'_evidence_jobs',{}).get(args['job_id'])
219
- if token:token[0].set()
394
+ job = self._evidence_job(args["job_id"])
395
+ token = getattr(self, "_evidence_jobs", {}).get(args["job_id"])
396
+ if token:
397
+ token[0].set()
220
398
  with self.repository.projects.connect(self.project_id) as db:
221
- db.execute("UPDATE production_evidence_jobs SET state='cancelled' WHERE job_id=? AND run_id=? AND state='running'",(args['job_id'],self.run_id))
222
- return ToolResult({'job':self._evidence_job(job['job_id'])})
399
+ db.execute(
400
+ "UPDATE production_evidence_jobs SET state='cancelled' WHERE job_id=? AND run_id=? AND state='running'",
401
+ (args["job_id"], self.run_id),
402
+ )
403
+ return ToolResult({"job": self._evidence_job(job["job_id"])})
223
404
 
224
405
 
225
406
  def local_cues(tools, timeline, *, include_drafts):
226
407
  """Map exact source word evidence into the selected cut, not ASR window fractions."""
227
408
  from .production_media import digest
409
+
228
410
  with tools.repository.projects.connect(tools.project_id) as db:
229
- rows=db.execute("SELECT job_id,result_json FROM production_evidence_jobs WHERE run_id=? AND state='succeeded' AND kind IN ('transcribe','align') ORDER BY created_at DESC,rowid DESC",(tools.run_id,)).fetchall()
230
- cues=[];limitations=[];seen=set()
231
- fps=Fraction(timeline.frame_rate.numerator,timeline.frame_rate.denominator)
411
+ rows = db.execute(
412
+ "SELECT job_id,result_json FROM production_evidence_jobs WHERE run_id=? AND state='succeeded' AND kind IN ('transcribe','align') ORDER BY created_at DESC,rowid DESC",
413
+ (tools.run_id,),
414
+ ).fetchall()
415
+ cues = []
416
+ limitations = []
417
+ seen = set()
418
+ fps = Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
232
419
  for track in timeline.tracks:
233
- if track.kind is not TrackKind.VIDEO:continue
420
+ if track.kind is not TrackKind.VIDEO:
421
+ continue
234
422
  for item in track.items:
235
- if any(e.effect_id=='audio.source' and e.parameters['mode']=='mute' for e in item.effects):continue
236
- if any(e.effect_id=='video.speed_ramp' for e in item.effects):
237
- limitations.append({'item_id':item.item_id,'reason':'retimed_speech_mapping_unavailable'})
423
+ if any(e.effect_id == "audio.source" and e.parameters["mode"] == "mute" for e in item.effects):
424
+ continue
425
+ if any(e.effect_id == "video.speed_ramp" for e in item.effects):
426
+ limitations.append({"item_id": item.item_id, "reason": "retimed_speech_mapping_unavailable"})
238
427
  continue
239
- span=item.source.span;unit=Fraction(span.time_base.numerator,span.time_base.denominator)
240
- cut_left=float(int(span.start_pts)*unit);cut_right=float(int(span.end_pts)*unit)
428
+ span = item.source.span
429
+ unit = Fraction(span.time_base.numerator, span.time_base.denominator)
430
+ cut_left = float(int(span.start_pts) * unit)
431
+ cut_right = float(int(span.end_pts) * unit)
241
432
  # A fresh, fully covering transcription supersedes older overlapping
242
433
  # windows. Combining both produces duplicate/conflicting captions.
243
- covering=[]
434
+ covering = []
244
435
  for row in rows:
245
- value=json.loads(row['result_json'])
246
- if value['source']['version_id']!=span.version_id:continue
247
- origin=value['source_start_seconds']
248
- if origin<=cut_left+.5/float(fps) and int(value['source']['end_pts'])*value['source']['time_base']['num']/value['source']['time_base']['den']>=cut_right-.5/float(fps):covering.append(row)
436
+ value = json.loads(row["result_json"])
437
+ if value["source"]["version_id"] != span.version_id:
438
+ continue
439
+ origin = value["source_start_seconds"]
440
+ if origin <= cut_left + 0.5 / float(fps) and int(value["source"]["end_pts"]) * value["source"][
441
+ "time_base"
442
+ ]["num"] / value["source"]["time_base"]["den"] >= cut_right - 0.5 / float(fps):
443
+ covering.append(row)
249
444
  if covering:
250
- first=json.loads(covering[0]['result_json'])
251
- corrected=any('wording_authority' in s for s in first['segments'])
445
+ first = json.loads(covering[0]["result_json"])
446
+ corrected = any("wording_authority" in s for s in first["segments"])
447
+
252
448
  def aligned_for_cut(row):
253
- value=json.loads(row['result_json']);origin=value['source_start_seconds']
254
- return all(s.get('words') for s in value['segments'] if origin+s['start_seconds']<cut_right and cut_left<origin+s['end_seconds'])
255
- chosen=covering[0] if corrected else next((r for r in covering if aligned_for_cut(r)),covering[0])
256
- selected_rows=[chosen]
257
- else:selected_rows=rows
449
+ value = json.loads(row["result_json"])
450
+ origin = value["source_start_seconds"]
451
+ return all(
452
+ s.get("words")
453
+ for s in value["segments"]
454
+ if origin + s["start_seconds"] < cut_right and cut_left < origin + s["end_seconds"]
455
+ )
456
+
457
+ chosen = covering[0] if corrected else next((r for r in covering if aligned_for_cut(r)), covering[0])
458
+ selected_rows = [chosen]
459
+ else:
460
+ selected_rows = rows
258
461
  for row in selected_rows:
259
- result=json.loads(row['result_json'])
260
- if result['source']['version_id']!=span.version_id:continue
261
- origin=result['source_start_seconds']
262
- for n,segment in enumerate(result['segments']):
263
- left=origin+segment['start_seconds'];right=origin+segment['end_seconds']
264
- identity=(item.item_id,round(left,4),round(right,4))
265
- if identity in seen or right<=cut_left or left>=cut_right:continue
266
- partial=left<cut_left-.5/float(fps) or right>cut_right+.5/float(fps)
267
- original_text=segment['text']
462
+ result = json.loads(row["result_json"])
463
+ if result["source"]["version_id"] != span.version_id:
464
+ continue
465
+ origin = result["source_start_seconds"]
466
+ for n, segment in enumerate(result["segments"]):
467
+ left = origin + segment["start_seconds"]
468
+ right = origin + segment["end_seconds"]
469
+ identity = (item.item_id, round(left, 4), round(right, 4))
470
+ if identity in seen or right <= cut_left or left >= cut_right:
471
+ continue
472
+ partial = left < cut_left - 0.5 / float(fps) or right > cut_right + 0.5 / float(fps)
473
+ original_text = segment["text"]
268
474
  if partial:
269
- selected=[w for w in segment.get('words',[]) if origin+w['start_seconds']>=cut_left-.5/float(fps)
270
- and origin+w['end_seconds']<=cut_right+.5/float(fps)]
475
+ selected = [
476
+ w
477
+ for w in segment.get("words", [])
478
+ if origin + w["start_seconds"] >= cut_left - 0.5 / float(fps)
479
+ and origin + w["end_seconds"] <= cut_right + 0.5 / float(fps)
480
+ ]
271
481
  if not selected:
272
- limitations.append({'item_id':item.item_id,'reason':'partial_utterance_requires_alignment','text':segment['text']})
482
+ limitations.append(
483
+ {
484
+ "item_id": item.item_id,
485
+ "reason": "partial_utterance_requires_alignment",
486
+ "text": segment["text"],
487
+ }
488
+ )
273
489
  continue
274
- first,last=selected[0]['char_start'],selected[-1]['char_end']
490
+ first, last = selected[0]["char_start"], selected[-1]["char_end"]
275
491
  # Retain only complete aligned words. Display punctuation
276
492
  # belongs to the source text, never invented speech.
277
493
  from .alignment import significant
278
- while last<len(original_text) and not significant(original_text[last]):last+=1
279
- segment={**segment,'text':original_text[first:last],
280
- 'words':[{**w,'char_start':w['char_start']-first,'char_end':w['char_end']-first} for w in selected]}
281
- left=origin+selected[0]['start_seconds'];right=origin+selected[-1]['end_seconds']
494
+
495
+ while last < len(original_text) and not significant(original_text[last]):
496
+ last += 1
497
+ segment = {
498
+ **segment,
499
+ "text": original_text[first:last],
500
+ "words": [
501
+ {**w, "char_start": w["char_start"] - first, "char_end": w["char_end"] - first}
502
+ for w in selected
503
+ ],
504
+ }
505
+ left = origin + selected[0]["start_seconds"]
506
+ right = origin + selected[-1]["end_seconds"]
282
507
  seen.add(identity)
283
- if not include_drafts:continue
284
- begin=item.start_frame+max(0,math.floor((left-cut_left)*fps))
285
- end=min(item.start_frame+item.duration_frames,item.start_frame+math.ceil((right-cut_left)*fps))
286
- words=[{**w,'start_frame':item.start_frame+max(0,round((origin+w['start_seconds']-cut_left)*fps)),
287
- 'end_frame':min(item.start_frame+item.duration_frames,item.start_frame+round((origin+w['end_seconds']-cut_left)*fps))} for w in segment.get('words',[])]
288
- cues.append({'cue_id':digest([item.item_id,row['job_id'],n])[:24], 'item_id':item.item_id,
289
- 'start_frame':begin,'duration_frames':end-begin,'text':segment['text'],
290
- 'verification':'asr_draft','source_revision_id':row['job_id'],'segment_id':str(n),
291
- 'source_utterance_partial':partial,'source_utterance_text':original_text,
292
- **{key:segment[key] for key in ('wording_authority','source_asr_text','correction_evidence') if key in segment},
293
- 'timing_basis':'forced_alignment' if words else 'asr_segment','words':words,
294
- 'source':{**span.to_storage(),'start_pts':str(round(left/float(unit))),'end_pts':str(round(right/float(unit)))}})
295
- return sorted(cues,key=lambda c:c['start_frame']),limitations
508
+ if not include_drafts:
509
+ continue
510
+ begin = item.start_frame + max(0, math.floor((left - cut_left) * fps))
511
+ end = min(
512
+ item.start_frame + item.duration_frames, item.start_frame + math.ceil((right - cut_left) * fps)
513
+ )
514
+ words = [
515
+ {
516
+ **w,
517
+ "start_frame": item.start_frame
518
+ + max(0, round((origin + w["start_seconds"] - cut_left) * fps)),
519
+ "end_frame": min(
520
+ item.start_frame + item.duration_frames,
521
+ item.start_frame + round((origin + w["end_seconds"] - cut_left) * fps),
522
+ ),
523
+ }
524
+ for w in segment.get("words", [])
525
+ ]
526
+ cues.append(
527
+ {
528
+ "cue_id": digest([item.item_id, row["job_id"], n])[:24],
529
+ "item_id": item.item_id,
530
+ "start_frame": begin,
531
+ "duration_frames": end - begin,
532
+ "text": segment["text"],
533
+ "verification": "asr_draft",
534
+ "source_revision_id": row["job_id"],
535
+ "segment_id": str(n),
536
+ "source_utterance_partial": partial,
537
+ "source_utterance_text": original_text,
538
+ **{
539
+ key: segment[key]
540
+ for key in ("wording_authority", "source_asr_text", "correction_evidence")
541
+ if key in segment
542
+ },
543
+ "timing_basis": "forced_alignment" if words else "asr_segment",
544
+ "words": words,
545
+ "source": {
546
+ **span.to_storage(),
547
+ "start_pts": str(round(left / float(unit))),
548
+ "end_pts": str(round(right / float(unit))),
549
+ },
550
+ }
551
+ )
552
+ return sorted(cues, key=lambda c: c["start_frame"]), limitations