@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.
- package/README.md +56 -48
- package/apps/web/dist/assets/{index-D5D2HiB1.js → index-DPHwA954.js} +1 -1
- package/apps/web/dist/index.html +1 -1
- package/bin/clipen.js +1 -1
- package/package.json +7 -6
- package/pyproject.toml +18 -2
- package/requirements/dev.txt +2 -0
- package/src/clipen/__init__.py +1 -1
- package/src/clipen/analysis/__init__.py +7 -7
- package/src/clipen/analysis/artifacts.py +4 -10
- package/src/clipen/analysis/audio.py +10 -8
- package/src/clipen/analysis/evidence_service.py +345 -167
- package/src/clipen/analysis/image_similarity.py +5 -14
- package/src/clipen/analysis/keyframes.py +5 -17
- package/src/clipen/analysis/models.py +5 -7
- package/src/clipen/analysis/qwen_worker.py +19 -54
- package/src/clipen/analysis/resources.py +2 -1
- package/src/clipen/analysis/runtime.py +1 -3
- package/src/clipen/analysis/service.py +16 -48
- package/src/clipen/analysis/setup.py +11 -25
- package/src/clipen/analysis/setup_cli.py +5 -15
- package/src/clipen/analysis/storage.py +96 -278
- package/src/clipen/analysis/transcription.py +40 -82
- package/src/clipen/analysis/visual.py +109 -48
- package/src/clipen/annotations/__init__.py +5 -2
- package/src/clipen/annotations/models.py +1 -1
- package/src/clipen/annotations/storage.py +132 -84
- package/src/clipen/annotations/suggestions.py +3 -8
- package/src/clipen/asr_release.py +4 -11
- package/src/clipen/bootstrap.py +71 -61
- package/src/clipen/{planning/models.py → candidates.py} +29 -47
- package/src/clipen/cli.py +4 -9
- package/src/clipen/controller/app.py +401 -214
- package/src/clipen/controller/server.py +28 -38
- package/src/clipen/domain/__init__.py +1 -1
- package/src/clipen/domain/media_time.py +3 -10
- package/src/clipen/domain/timeline.py +45 -47
- package/src/clipen/domain/validation.py +0 -1
- package/src/clipen/editing/__init__.py +1 -1
- package/src/clipen/editing/agent_models.py +4 -11
- package/src/clipen/editing/agent_repository.py +393 -172
- package/src/clipen/editing/agent_tools.py +180 -99
- package/src/clipen/editing/alignment.py +92 -52
- package/src/clipen/editing/alignment_setup.py +118 -70
- package/src/clipen/editing/alignment_worker.py +11 -9
- package/src/clipen/editing/change_report.py +95 -38
- package/src/clipen/editing/compiler.py +0 -1
- package/src/clipen/editing/component_looks.py +58 -34
- package/src/clipen/editing/component_review.py +34 -38
- package/src/clipen/editing/coordinator.py +213 -92
- package/src/clipen/editing/editorial_review.py +217 -95
- package/src/clipen/editing/evidence_jobs.py +457 -200
- package/src/clipen/editing/history_changes.py +129 -68
- package/src/clipen/editing/music_choices.py +8 -5
- package/src/clipen/editing/production_catalog.py +573 -136
- package/src/clipen/editing/production_limits.py +43 -17
- package/src/clipen/editing/production_media.py +376 -167
- package/src/clipen/editing/production_preview.py +322 -129
- package/src/clipen/editing/production_progress.py +164 -69
- package/src/clipen/editing/production_requirements.py +106 -39
- package/src/clipen/editing/production_tools.py +1064 -462
- package/src/clipen/editing/program_audio.py +211 -81
- package/src/clipen/editing/program_direction.py +59 -25
- package/src/clipen/editing/program_story.py +83 -45
- package/src/clipen/editing/program_subtitles.py +194 -96
- package/src/clipen/editing/programme_review.py +98 -50
- package/src/clipen/editing/prompt_history.py +64 -27
- package/src/clipen/editing/recut.py +65 -25
- package/src/clipen/editing/refinement_references.py +176 -86
- package/src/clipen/editing/resolve_export.py +449 -218
- package/src/clipen/editing/resolve_titles.py +162 -105
- package/src/clipen/editing/skill_tools.py +530 -154
- package/src/clipen/editing/source_dialogue.py +177 -67
- package/src/clipen/editing/speech_coverage.py +42 -22
- package/src/clipen/editing/speech_quality.py +6 -1
- package/src/clipen/editing/tool_receipts.py +78 -32
- package/src/clipen/editing/versions.py +122 -64
- package/src/clipen/editing/visual_preview.py +157 -61
- package/src/clipen/editing/workbench.py +104 -42
- package/src/clipen/finishing/audio.py +69 -30
- package/src/clipen/finishing/catalog.py +176 -93
- package/src/clipen/finishing/models.py +1 -1
- package/src/clipen/finishing/renderer.py +33 -14
- package/src/clipen/mcp_editing/__main__.py +3 -1
- package/src/clipen/mcp_editing/server.py +77 -34
- package/src/clipen/media/__init__.py +3 -3
- package/src/clipen/media/discovery.py +7 -20
- package/src/clipen/media/models.py +7 -18
- package/src/clipen/media/preview.py +14 -24
- package/src/clipen/media/probe.py +16 -44
- package/src/clipen/media/service.py +6 -19
- package/src/clipen/media/storage.py +33 -81
- package/src/clipen/music_vocabulary.py +33 -4
- package/src/clipen/power.py +8 -3
- package/src/clipen/projects/__init__.py +1 -1
- package/src/clipen/projects/deletion.py +19 -32
- package/src/clipen/projects/finishing_schema.py +3 -1
- package/src/clipen/projects/models.py +2 -5
- package/src/clipen/projects/picker.py +13 -37
- package/src/clipen/projects/service.py +8 -24
- package/src/clipen/projects/storage.py +226 -246
- package/src/clipen/provider_registry.py +9 -20
- package/src/clipen/providers/account.py +86 -35
- package/src/clipen/providers/claude.py +59 -25
- package/src/clipen/providers/claude_editing.py +14 -7
- package/src/clipen/providers/codex.py +73 -118
- package/src/clipen/providers/codex_editing.py +2 -2
- package/src/clipen/providers/editing_agent.py +19 -17
- package/src/clipen/providers/recovery.py +7 -8
- package/src/clipen/rendering/cover.py +18 -5
- package/src/clipen/rendering/custom_components.py +167 -79
- package/src/clipen/rendering/custom_render.py +62 -41
- package/src/clipen/rendering/production_effects.py +77 -45
- package/src/clipen/rendering/program_components.py +134 -73
- package/src/clipen/rendering/program_creator.py +432 -277
- package/src/clipen/rendering/program_identities.py +277 -182
- package/src/clipen/rendering/program_motion.py +140 -95
- package/src/clipen/rendering/program_studio.py +175 -116
- package/src/clipen/rendering/program_styles.py +231 -145
- package/src/clipen/rendering/program_subtitles.py +71 -34
- package/src/clipen/rendering/renderer.py +150 -121
- package/src/clipen/rendering/storage.py +9 -22
- package/src/clipen/rendering/titles.py +193 -86
- package/src/clipen/skills/__init__.py +1 -0
- package/src/clipen/skills/catalog.py +151 -55
- package/src/clipen/skills/library.py +13 -7
- package/src/clipen/skills/package.py +46 -23
- package/src/clipen/skills/visual_styles.py +29 -18
- package/src/clipen/workspace.py +15 -44
- package/install +0 -25
- package/src/clipen/planning/__init__.py +0 -9
- package/uninstall +0 -25
|
@@ -1,295 +1,552 @@
|
|
|
1
1
|
"""On-demand local source speech jobs, independent of the legacy preparation stage."""
|
|
2
|
-
|
|
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[
|
|
21
|
-
raise ProjectError(
|
|
22
|
-
return self._start_evidence(
|
|
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[
|
|
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(
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
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
|
-
|
|
38
|
-
|
|
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[
|
|
42
|
-
if job[
|
|
43
|
-
raise ProjectError(
|
|
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
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
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[
|
|
63
|
-
if job[
|
|
64
|
-
raise ProjectError(
|
|
65
|
-
index=args[
|
|
66
|
-
if index>=len(job[
|
|
67
|
-
raise ProjectError(
|
|
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
|
-
|
|
70
|
-
|
|
71
|
-
|
|
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(
|
|
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(
|
|
78
|
-
return {
|
|
79
|
-
|
|
80
|
-
|
|
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
|
-
|
|
85
|
-
|
|
86
|
-
|
|
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(
|
|
89
|
-
identifier = make_id(
|
|
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(
|
|
92
|
-
existing = db.execute(
|
|
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({
|
|
96
|
-
cached=db.execute(
|
|
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={
|
|
99
|
-
|
|
100
|
-
|
|
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({
|
|
103
|
-
if db.execute(
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
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,
|
|
110
|
-
|
|
111
|
-
|
|
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({
|
|
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[
|
|
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(
|
|
127
|
-
|
|
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
|
-
|
|
193
|
+
|
|
194
|
+
result = install_runtime(getattr(self, "local_data_root", None), cancel, progress)
|
|
130
195
|
else:
|
|
131
|
-
setup=getattr(self,
|
|
132
|
-
if setup is None:
|
|
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==
|
|
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(
|
|
139
|
-
if setup.status().state.value!=
|
|
140
|
-
|
|
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(
|
|
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[
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
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(
|
|
154
|
-
stream=
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
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[
|
|
170
|
-
correction=request.get(
|
|
281
|
+
segments = self._evidence_job(request["transcript_job_id"])["result"]["segments"]
|
|
282
|
+
correction = request.get("correction")
|
|
171
283
|
if correction:
|
|
172
|
-
segment=segments[correction[
|
|
173
|
-
segment.update(
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
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(
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
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[
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
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(
|
|
367
|
+
raise ProjectError("user_cancelled", "已取消來源證據工作。", status_code=409)
|
|
201
368
|
with self.repository.projects.connect(self.project_id) as db:
|
|
202
|
-
db.execute(
|
|
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(
|
|
206
|
-
|
|
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:
|
|
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(
|
|
212
|
-
while (job:=self._evidence_job(args[
|
|
213
|
-
time.sleep(.1)
|
|
214
|
-
return ToolResult({
|
|
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[
|
|
218
|
-
token=getattr(self,
|
|
219
|
-
if token:
|
|
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(
|
|
222
|
-
|
|
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(
|
|
230
|
-
|
|
231
|
-
|
|
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:
|
|
420
|
+
if track.kind is not TrackKind.VIDEO:
|
|
421
|
+
continue
|
|
234
422
|
for item in track.items:
|
|
235
|
-
if any(e.effect_id==
|
|
236
|
-
|
|
237
|
-
|
|
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
|
|
240
|
-
|
|
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[
|
|
246
|
-
if value[
|
|
247
|
-
|
|
248
|
-
|
|
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][
|
|
251
|
-
corrected=any(
|
|
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[
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
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[
|
|
260
|
-
if result[
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
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=
|
|
270
|
-
|
|
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(
|
|
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][
|
|
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
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
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:
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
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
|