@clipen/clipen-cli 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +89 -2
- package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
- package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
- package/apps/web/dist/favicon.svg +1 -0
- package/apps/web/dist/index.html +16 -0
- package/bin/clipen.js +157 -0
- package/clipen +18 -0
- package/install +25 -0
- package/package.json +55 -4
- package/pyproject.toml +44 -0
- package/requirements/asr-runtime.txt +13 -0
- package/requirements/dev.txt +2 -0
- package/requirements/runtime.txt +20 -0
- package/src/clipen/__init__.py +3 -0
- package/src/clipen/analysis/__init__.py +89 -0
- package/src/clipen/analysis/artifacts.py +410 -0
- package/src/clipen/analysis/audio.py +394 -0
- package/src/clipen/analysis/evidence.py +102 -0
- package/src/clipen/analysis/evidence_service.py +929 -0
- package/src/clipen/analysis/image_similarity.py +134 -0
- package/src/clipen/analysis/keyframes.py +159 -0
- package/src/clipen/analysis/models.py +228 -0
- package/src/clipen/analysis/qwen_worker.py +594 -0
- package/src/clipen/analysis/resources.py +22 -0
- package/src/clipen/analysis/runtime.py +62 -0
- package/src/clipen/analysis/service.py +594 -0
- package/src/clipen/analysis/setup.py +921 -0
- package/src/clipen/analysis/setup_cli.py +107 -0
- package/src/clipen/analysis/storage.py +1864 -0
- package/src/clipen/analysis/transcription.py +906 -0
- package/src/clipen/analysis/visual.py +237 -0
- package/src/clipen/annotations/__init__.py +13 -0
- package/src/clipen/annotations/models.py +22 -0
- package/src/clipen/annotations/storage.py +428 -0
- package/src/clipen/annotations/suggestions.py +115 -0
- package/src/clipen/asr_release.py +132 -0
- package/src/clipen/bootstrap.py +978 -0
- package/src/clipen/candidates.py +222 -0
- package/src/clipen/cli.py +84 -0
- package/src/clipen/controller/__init__.py +17 -0
- package/src/clipen/controller/app.py +1657 -0
- package/src/clipen/controller/server.py +533 -0
- package/src/clipen/domain/__init__.py +30 -0
- package/src/clipen/domain/errors.py +5 -0
- package/src/clipen/domain/media_time.py +110 -0
- package/src/clipen/domain/timeline.py +582 -0
- package/src/clipen/domain/validation.py +14 -0
- package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
- package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
- package/src/clipen/editing/README.md +115 -0
- package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
- package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
- package/src/clipen/editing/__init__.py +15 -0
- package/src/clipen/editing/agent.py +13 -0
- package/src/clipen/editing/agent_models.py +127 -0
- package/src/clipen/editing/agent_repository.py +978 -0
- package/src/clipen/editing/agent_tools.py +613 -0
- package/src/clipen/editing/alignment.py +150 -0
- package/src/clipen/editing/alignment_setup.py +156 -0
- package/src/clipen/editing/alignment_worker.py +24 -0
- package/src/clipen/editing/change_report.py +128 -0
- package/src/clipen/editing/compiler.py +40 -0
- package/src/clipen/editing/component_looks.py +131 -0
- package/src/clipen/editing/component_review.py +74 -0
- package/src/clipen/editing/coordinator.py +497 -0
- package/src/clipen/editing/editorial_review.py +309 -0
- package/src/clipen/editing/evidence_jobs.py +552 -0
- package/src/clipen/editing/history_changes.py +192 -0
- package/src/clipen/editing/music_choices.py +18 -0
- package/src/clipen/editing/production_catalog.py +629 -0
- package/src/clipen/editing/production_limits.py +85 -0
- package/src/clipen/editing/production_media.py +435 -0
- package/src/clipen/editing/production_preview.py +373 -0
- package/src/clipen/editing/production_progress.py +236 -0
- package/src/clipen/editing/production_requirements.py +117 -0
- package/src/clipen/editing/production_tools.py +1198 -0
- package/src/clipen/editing/program_audio.py +248 -0
- package/src/clipen/editing/program_direction.py +83 -0
- package/src/clipen/editing/program_story.py +91 -0
- package/src/clipen/editing/program_subtitles.py +232 -0
- package/src/clipen/editing/programme_review.py +121 -0
- package/src/clipen/editing/prompt_history.py +84 -0
- package/src/clipen/editing/recut.py +167 -0
- package/src/clipen/editing/refinement_references.py +278 -0
- package/src/clipen/editing/resolve_export.py +847 -0
- package/src/clipen/editing/resolve_titles.py +291 -0
- package/src/clipen/editing/skill_tools.py +951 -0
- package/src/clipen/editing/source_dialogue.py +192 -0
- package/src/clipen/editing/speech_coverage.py +50 -0
- package/src/clipen/editing/speech_quality.py +11 -0
- package/src/clipen/editing/tool_receipts.py +98 -0
- package/src/clipen/editing/versions.py +219 -0
- package/src/clipen/editing/visual_preview.py +189 -0
- package/src/clipen/editing/workbench.py +136 -0
- package/src/clipen/filesystem.py +25 -0
- package/src/clipen/finishing/README.md +103 -0
- package/src/clipen/finishing/__init__.py +1 -0
- package/src/clipen/finishing/audio.py +188 -0
- package/src/clipen/finishing/catalog.py +264 -0
- package/src/clipen/finishing/models.py +14 -0
- package/src/clipen/finishing/renderer.py +45 -0
- package/src/clipen/mcp_editing/__init__.py +5 -0
- package/src/clipen/mcp_editing/__main__.py +42 -0
- package/src/clipen/mcp_editing/server.py +396 -0
- package/src/clipen/media/__init__.py +50 -0
- package/src/clipen/media/discovery.py +253 -0
- package/src/clipen/media/models.py +349 -0
- package/src/clipen/media/preview.py +137 -0
- package/src/clipen/media/probe.py +418 -0
- package/src/clipen/media/service.py +304 -0
- package/src/clipen/media/storage.py +694 -0
- package/src/clipen/music_vocabulary.py +34 -0
- package/src/clipen/power.py +28 -0
- package/src/clipen/projects/__init__.py +26 -0
- package/src/clipen/projects/agent_schema.py +94 -0
- package/src/clipen/projects/annotation_schema.py +40 -0
- package/src/clipen/projects/deletion.py +256 -0
- package/src/clipen/projects/evidence_schema.py +52 -0
- package/src/clipen/projects/finishing_schema.py +36 -0
- package/src/clipen/projects/models.py +189 -0
- package/src/clipen/projects/picker.py +232 -0
- package/src/clipen/projects/preview_schema.py +29 -0
- package/src/clipen/projects/service.py +159 -0
- package/src/clipen/projects/storage.py +1458 -0
- package/src/clipen/projects/timeline_schema.py +32 -0
- package/src/clipen/projects/validation_schema.py +28 -0
- package/src/clipen/provider_registry.py +77 -0
- package/src/clipen/providers/__init__.py +43 -0
- package/src/clipen/providers/account.py +245 -0
- package/src/clipen/providers/claude.py +409 -0
- package/src/clipen/providers/claude_editing.py +118 -0
- package/src/clipen/providers/codex.py +991 -0
- package/src/clipen/providers/codex_editing.py +91 -0
- package/src/clipen/providers/editing_agent.py +567 -0
- package/src/clipen/providers/errors.py +51 -0
- package/src/clipen/providers/recovery.py +269 -0
- package/src/clipen/py.typed +1 -0
- package/src/clipen/rendering/__init__.py +12 -0
- package/src/clipen/rendering/cover.py +139 -0
- package/src/clipen/rendering/custom_components.py +328 -0
- package/src/clipen/rendering/custom_render.py +218 -0
- package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/manifest.json +145 -0
- package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
- package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
- package/src/clipen/rendering/production_effects.py +96 -0
- package/src/clipen/rendering/program_components.py +254 -0
- package/src/clipen/rendering/program_creator.py +804 -0
- package/src/clipen/rendering/program_identities.py +350 -0
- package/src/clipen/rendering/program_motion.py +186 -0
- package/src/clipen/rendering/program_studio.py +227 -0
- package/src/clipen/rendering/program_styles.py +321 -0
- package/src/clipen/rendering/program_subtitles.py +89 -0
- package/src/clipen/rendering/renderer.py +737 -0
- package/src/clipen/rendering/storage.py +230 -0
- package/src/clipen/rendering/titles.py +467 -0
- package/src/clipen/skills/__init__.py +5 -0
- package/src/clipen/skills/builtin/SKILL.md +72 -0
- package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
- package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
- package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
- package/src/clipen/skills/builtin/components.json +133 -0
- package/src/clipen/skills/builtin/font_sources.json +20 -0
- package/src/clipen/skills/builtin/font_styles.json +329 -0
- package/src/clipen/skills/builtin/manifest.json +32 -0
- package/src/clipen/skills/builtin/presets.json +8 -0
- package/src/clipen/skills/builtin/references/captions.md +14 -0
- package/src/clipen/skills/builtin/references/channel-design.md +37 -0
- package/src/clipen/skills/builtin/references/editing.md +30 -0
- package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
- package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
- package/src/clipen/skills/builtin/references/graphics.md +59 -0
- package/src/clipen/skills/builtin/references/review.md +16 -0
- package/src/clipen/skills/builtin/references/sound.md +8 -0
- package/src/clipen/skills/builtin/references/story.md +7 -0
- package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
- package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
- package/src/clipen/skills/builtin/templates.json +284 -0
- package/src/clipen/skills/builtin/visual_styles.json +1074 -0
- package/src/clipen/skills/catalog.py +314 -0
- package/src/clipen/skills/library.py +137 -0
- package/src/clipen/skills/package.py +254 -0
- package/src/clipen/skills/visual_styles.py +55 -0
- package/src/clipen/workspace.py +181 -0
- package/uninstall +25 -0
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
"""On-demand local source speech jobs, independent of the legacy preparation stage."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
import wave
|
|
9
|
+
from fractions import Fraction
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from clipen.domain import TrackKind
|
|
13
|
+
from clipen.projects import ProjectError
|
|
14
|
+
from clipen.projects.storage import utc_now
|
|
15
|
+
|
|
16
|
+
from .agent_models import ToolResult, encoded, make_id
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class EvidenceTools:
|
|
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)
|
|
25
|
+
|
|
26
|
+
def _production_transcribe_source_range(self, args):
|
|
27
|
+
candidate = self._candidate(args["candidate_id"])
|
|
28
|
+
span = candidate.source
|
|
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"]:
|
|
44
|
+
from .alignment import REVISION
|
|
45
|
+
|
|
46
|
+
request["alignment_revision"] = REVISION
|
|
47
|
+
return self._start_evidence("transcribe", request, runtime[0])
|
|
48
|
+
|
|
49
|
+
def _production_align_source_speech(self, args):
|
|
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)
|
|
53
|
+
from .alignment import REVISION
|
|
54
|
+
|
|
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)
|
|
72
|
+
|
|
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)
|
|
80
|
+
from .alignment import REVISION
|
|
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)
|
|
89
|
+
|
|
90
|
+
def _evidence_job(self, job_id):
|
|
91
|
+
with self.repository.projects.connect(self.project_id) as db:
|
|
92
|
+
row = db.execute(
|
|
93
|
+
"SELECT * FROM production_evidence_jobs WHERE job_id=? AND run_id=?", (job_id, self.run_id)
|
|
94
|
+
).fetchone()
|
|
95
|
+
if row is None:
|
|
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
|
+
}
|
|
105
|
+
|
|
106
|
+
def _start_evidence(self, kind, request, factory):
|
|
107
|
+
from clipen.analysis import transcription
|
|
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
|
+
):
|
|
117
|
+
recipe.update(path.read_bytes())
|
|
118
|
+
key = make_id("evidence_", [kind, request, recipe.hexdigest()])
|
|
119
|
+
identifier = make_id("speech_", [self.run_id, key])
|
|
120
|
+
with self.repository.projects.connect(self.project_id) as db:
|
|
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()
|
|
125
|
+
if existing:
|
|
126
|
+
db.rollback()
|
|
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()
|
|
132
|
+
if cached is not None:
|
|
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
|
+
)
|
|
151
|
+
db.commit()
|
|
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
|
+
)
|
|
161
|
+
db.commit()
|
|
162
|
+
cancel = threading.Event()
|
|
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)
|
|
169
|
+
worker.start()
|
|
170
|
+
return ToolResult({"job": self._evidence_job(identifier), "reused": False})
|
|
171
|
+
|
|
172
|
+
def _run_evidence(self, identifier, factory, cancel):
|
|
173
|
+
transcriber = None
|
|
174
|
+
try:
|
|
175
|
+
from clipen.analysis.audio import PreparedAudio
|
|
176
|
+
from clipen.finishing.audio import run_process
|
|
177
|
+
from clipen.media import MediaPreviewRepository
|
|
178
|
+
|
|
179
|
+
from .alignment import REVISION, run_alignment, validate_alignment
|
|
180
|
+
|
|
181
|
+
job = self._evidence_job(identifier)
|
|
182
|
+
if job["kind"] == "setup":
|
|
183
|
+
|
|
184
|
+
def progress(value):
|
|
185
|
+
with self.repository.projects.connect(self.project_id) as db:
|
|
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":
|
|
192
|
+
from .alignment_setup import install_runtime
|
|
193
|
+
|
|
194
|
+
result = install_runtime(getattr(self, "local_data_root", None), cancel, progress)
|
|
195
|
+
else:
|
|
196
|
+
setup = getattr(self, "asr_setup_manager", None)
|
|
197
|
+
if setup is None:
|
|
198
|
+
raise ProjectError("asr_unavailable", "語音環境尚未設定。", status_code=409)
|
|
199
|
+
from clipen.asr_release import NOTICE_VERSION
|
|
200
|
+
|
|
201
|
+
setup.start_install(NOTICE_VERSION)
|
|
202
|
+
while setup.status().state.value == "installing":
|
|
203
|
+
if cancel.wait(0.5):
|
|
204
|
+
setup.cancel_install()
|
|
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"}
|
|
209
|
+
with self.repository.projects.connect(self.project_id) as db:
|
|
210
|
+
db.execute(
|
|
211
|
+
"UPDATE production_evidence_jobs SET state='succeeded',result_json=? WHERE job_id=? AND state='running'",
|
|
212
|
+
(encoded(result), identifier),
|
|
213
|
+
)
|
|
214
|
+
return
|
|
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
|
+
)
|
|
226
|
+
try:
|
|
227
|
+
if not media.audio_stream_indices:
|
|
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
|
+
]
|
|
280
|
+
else:
|
|
281
|
+
segments = self._evidence_job(request["transcript_job_id"])["result"]["segments"]
|
|
282
|
+
correction = request.get("correction")
|
|
283
|
+
if correction:
|
|
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
|
+
)
|
|
331
|
+
try:
|
|
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
|
+
]
|
|
349
|
+
except ProjectError as error:
|
|
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
|
+
}
|
|
366
|
+
if cancel.is_set() or self._cancel_event().is_set():
|
|
367
|
+
raise ProjectError("user_cancelled", "已取消來源證據工作。", status_code=409)
|
|
368
|
+
with self.repository.projects.connect(self.project_id) as db:
|
|
369
|
+
db.execute(
|
|
370
|
+
"UPDATE production_evidence_jobs SET state='succeeded',result_json=? WHERE job_id=? AND state='running'",
|
|
371
|
+
(encoded(payload), identifier),
|
|
372
|
+
)
|
|
373
|
+
except Exception as error:
|
|
374
|
+
with self.repository.projects.connect(self.project_id) as db:
|
|
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
|
+
)
|
|
383
|
+
finally:
|
|
384
|
+
if transcriber is not None:
|
|
385
|
+
transcriber.close()
|
|
386
|
+
|
|
387
|
+
def _production_read_evidence_job(self, args):
|
|
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})
|
|
392
|
+
|
|
393
|
+
def _production_cancel_evidence_job(self, args):
|
|
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()
|
|
398
|
+
with self.repository.projects.connect(self.project_id) as db:
|
|
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"])})
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def local_cues(tools, timeline, *, include_drafts):
|
|
407
|
+
"""Map exact source word evidence into the selected cut, not ASR window fractions."""
|
|
408
|
+
from .production_media import digest
|
|
409
|
+
|
|
410
|
+
with tools.repository.projects.connect(tools.project_id) as db:
|
|
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)
|
|
419
|
+
for track in timeline.tracks:
|
|
420
|
+
if track.kind is not TrackKind.VIDEO:
|
|
421
|
+
continue
|
|
422
|
+
for item in track.items:
|
|
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"})
|
|
427
|
+
continue
|
|
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)
|
|
432
|
+
# A fresh, fully covering transcription supersedes older overlapping
|
|
433
|
+
# windows. Combining both produces duplicate/conflicting captions.
|
|
434
|
+
covering = []
|
|
435
|
+
for row in rows:
|
|
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)
|
|
444
|
+
if covering:
|
|
445
|
+
first = json.loads(covering[0]["result_json"])
|
|
446
|
+
corrected = any("wording_authority" in s for s in first["segments"])
|
|
447
|
+
|
|
448
|
+
def aligned_for_cut(row):
|
|
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
|
|
461
|
+
for row in selected_rows:
|
|
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"]
|
|
474
|
+
if partial:
|
|
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
|
+
]
|
|
481
|
+
if not selected:
|
|
482
|
+
limitations.append(
|
|
483
|
+
{
|
|
484
|
+
"item_id": item.item_id,
|
|
485
|
+
"reason": "partial_utterance_requires_alignment",
|
|
486
|
+
"text": segment["text"],
|
|
487
|
+
}
|
|
488
|
+
)
|
|
489
|
+
continue
|
|
490
|
+
first, last = selected[0]["char_start"], selected[-1]["char_end"]
|
|
491
|
+
# Retain only complete aligned words. Display punctuation
|
|
492
|
+
# belongs to the source text, never invented speech.
|
|
493
|
+
from .alignment import significant
|
|
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"]
|
|
507
|
+
seen.add(identity)
|
|
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
|