@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,74 @@
|
|
|
1
|
+
"""Content checks that keep programme graphics tied to a moment, not a template."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import unicodedata
|
|
5
|
+
from collections import Counter
|
|
6
|
+
|
|
7
|
+
# Short reactions land on one beat; a long hold reads as a static label.
|
|
8
|
+
RESTATE_RATIO = 0.5
|
|
9
|
+
SAME_POSITION_DISTANCE = 0.03
|
|
10
|
+
SAME_POSITION_RUN = 3
|
|
11
|
+
UNIFORM_DURATION_SHARE = 0.5
|
|
12
|
+
UNIFORM_DURATION_MINIMUM = 4
|
|
13
|
+
_PARALLEL = re.compile(r"^[^,,・]{2,8}[,,][^,,・]{2,8}$")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def significant(text):
|
|
17
|
+
return "".join(c for c in unicodedata.normalize("NFKC", text) if unicodedata.category(c)[0] not in "PZCS")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _bigrams(text):
|
|
21
|
+
text = significant(text)
|
|
22
|
+
return [text[n : n + 2] for n in range(len(text) - 1)]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def restated_ratio(text, subtitles):
|
|
26
|
+
"""Share of the graphic's character pairs copied from concurrent subtitles."""
|
|
27
|
+
pairs = _bigrams(text)
|
|
28
|
+
spoken = significant("".join(subtitles))
|
|
29
|
+
return sum(pair in spoken for pair in pairs) / len(pairs) if pairs else 0.0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def concurrent_subtitles(timeline, start, duration):
|
|
33
|
+
end = start + duration
|
|
34
|
+
return [
|
|
35
|
+
i.text
|
|
36
|
+
for t in timeline.tracks
|
|
37
|
+
if t.track_id == "agent-subtitles"
|
|
38
|
+
for i in t.items
|
|
39
|
+
if i.start_frame < end and start < i.start_frame + i.duration_frames
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def design_notes(timeline, elements, styles):
|
|
44
|
+
"""Advisory findings; heuristics never block delivery on their own."""
|
|
45
|
+
fps = timeline.frame_rate.numerator / timeline.frame_rate.denominator
|
|
46
|
+
ordered = sorted(elements, key=lambda i: (i.start_frame, i.item_id))
|
|
47
|
+
notes = []
|
|
48
|
+
run = []
|
|
49
|
+
for element in ordered:
|
|
50
|
+
profile = styles.get(element.style_id, {})
|
|
51
|
+
point = (profile.get("x"), profile.get("y"))
|
|
52
|
+
if run and None not in point and all(abs(a - b) <= SAME_POSITION_DISTANCE for a, b in zip(point, run[-1][1])):
|
|
53
|
+
run.append((element.item_id, point))
|
|
54
|
+
else:
|
|
55
|
+
if len(run) >= SAME_POSITION_RUN:
|
|
56
|
+
notes.append({"code": "component_position_repeated", "item_ids": [i for i, _ in run]})
|
|
57
|
+
run = [(element.item_id, point)] if None not in point else []
|
|
58
|
+
if len(run) >= SAME_POSITION_RUN:
|
|
59
|
+
notes.append({"code": "component_position_repeated", "item_ids": [i for i, _ in run]})
|
|
60
|
+
if len(ordered) >= UNIFORM_DURATION_MINIMUM:
|
|
61
|
+
duration, count = Counter(round(i.duration_frames / fps * 2) / 2 for i in ordered).most_common(1)[0]
|
|
62
|
+
if count / len(ordered) > UNIFORM_DURATION_SHARE:
|
|
63
|
+
notes.append({"code": "component_duration_uniform", "seconds": duration, "count": count})
|
|
64
|
+
for element in ordered:
|
|
65
|
+
kind = styles.get(element.style_id, {}).get("component_id")
|
|
66
|
+
primary = element.text.partition("\n")[0]
|
|
67
|
+
if kind not in {"program_title"} and _PARALLEL.match(primary):
|
|
68
|
+
notes.append({"code": "component_parallel_phrasing", "item_id": element.item_id, "text": primary})
|
|
69
|
+
messages = {
|
|
70
|
+
"component_position_repeated": "連續多個元件擺在同一位置。請依每個畫面的人物、物件與空白處重新決定位置。",
|
|
71
|
+
"component_duration_uniform": "多數元件的顯示時長相同,節奏像固定節拍。請依每個瞬間的閱讀需要調整。",
|
|
72
|
+
"component_parallel_phrasing": "「A,B」對句常只是描述畫面。請改成畫面看不出的資訊或觀點,或移除這個元件。",
|
|
73
|
+
}
|
|
74
|
+
return [{**note, "message": messages[note["code"]]} for note in notes]
|
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
"""Background orchestration for one-shot provider-driven editing sessions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import queue
|
|
7
|
+
import threading
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from clipen.projects import ProjectError
|
|
11
|
+
from clipen.providers.codex import ProviderCancelled
|
|
12
|
+
|
|
13
|
+
from .agent import AgentRun, EditAgentRepository
|
|
14
|
+
from .production_limits import timeline_stats
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class EditAgentCoordinator:
|
|
18
|
+
"""Serialize provider jobs while the MCP server owns all timeline mutations."""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
repository: EditAgentRepository,
|
|
23
|
+
attempt_root: Path,
|
|
24
|
+
*,
|
|
25
|
+
adapter_factory=None,
|
|
26
|
+
queue_capacity: int = 4,
|
|
27
|
+
local_runtime: tuple[Path, Path] | None = None,
|
|
28
|
+
provider_id: str = "codex",
|
|
29
|
+
) -> None:
|
|
30
|
+
root = Path(attempt_root).resolve(strict=True)
|
|
31
|
+
if not root.is_dir() or attempt_root.is_symlink():
|
|
32
|
+
raise ValueError("editing attempt root must be a safe directory")
|
|
33
|
+
if not 1 <= queue_capacity <= 16:
|
|
34
|
+
raise ValueError("editing queue capacity is invalid")
|
|
35
|
+
from clipen.provider_registry import get_provider
|
|
36
|
+
|
|
37
|
+
self.provider = get_provider(provider_id)
|
|
38
|
+
if not self.provider.implemented:
|
|
39
|
+
raise ValueError(f"provider {provider_id} cannot edit yet")
|
|
40
|
+
self.repository = repository
|
|
41
|
+
self.local_runtime = local_runtime
|
|
42
|
+
self.attempt_root = root
|
|
43
|
+
if adapter_factory is None:
|
|
44
|
+
# Import lazily so the provider can import the agent repository
|
|
45
|
+
# without cycling back through clipen.editing.__init__.
|
|
46
|
+
from clipen.provider_registry import editing_agent_factory
|
|
47
|
+
|
|
48
|
+
adapter_factory = editing_agent_factory(provider_id)
|
|
49
|
+
self.adapter_factory = adapter_factory
|
|
50
|
+
self._queue: queue.Queue[tuple[str, str] | None] = queue.Queue(queue_capacity)
|
|
51
|
+
self._cancel: dict[tuple[str, str], threading.Event] = {}
|
|
52
|
+
self._projects: set[str] = set()
|
|
53
|
+
self._worker: threading.Thread | None = None
|
|
54
|
+
self._closed = False
|
|
55
|
+
self._lock = threading.RLock()
|
|
56
|
+
self._user_previews = {}
|
|
57
|
+
|
|
58
|
+
def recover(self) -> int:
|
|
59
|
+
recovered = 0
|
|
60
|
+
for project in self.repository.projects.list_projects():
|
|
61
|
+
recovered += self.repository.interrupt_incomplete(project.project_id)
|
|
62
|
+
with self.repository.projects.connect(project.project_id) as db:
|
|
63
|
+
db.execute(
|
|
64
|
+
"UPDATE production_evidence_jobs SET state='interrupted',error_code='controller_stopped' WHERE state='running'"
|
|
65
|
+
)
|
|
66
|
+
latest = self.repository.latest(project.project_id)
|
|
67
|
+
if latest is not None and latest.state == "succeeded" and latest.provider_attempt_id is None:
|
|
68
|
+
# finish_edit is durable before the provider process reports its
|
|
69
|
+
# usage. A Controller shutdown in that narrow window must not
|
|
70
|
+
# leave the UI waiting forever for a process that no longer
|
|
71
|
+
# exists. Preserve the successful revision and mark the usage
|
|
72
|
+
# handoff as unavailable.
|
|
73
|
+
self.repository.record_provider_outcome(
|
|
74
|
+
project.project_id,
|
|
75
|
+
latest.run_id,
|
|
76
|
+
"recovered-" + latest.run_id.removeprefix("editrun_"),
|
|
77
|
+
usage=None,
|
|
78
|
+
)
|
|
79
|
+
recovered += 1
|
|
80
|
+
return recovered
|
|
81
|
+
|
|
82
|
+
def status(self, project_id: str) -> dict[str, object]:
|
|
83
|
+
from .production_requirements import production_contents
|
|
84
|
+
|
|
85
|
+
latest = self.repository.latest(project_id)
|
|
86
|
+
published = self.repository.latest_successful(project_id)
|
|
87
|
+
result = None
|
|
88
|
+
if published is not None:
|
|
89
|
+
revision = self.repository.final_revision(project_id, published.run_id)
|
|
90
|
+
stats = timeline_stats(revision.timeline)
|
|
91
|
+
with self.repository.projects.connect(project_id) as db:
|
|
92
|
+
rows = db.execute(
|
|
93
|
+
"SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='editorial_review' ORDER BY sequence DESC",
|
|
94
|
+
(published.run_id,),
|
|
95
|
+
).fetchall()
|
|
96
|
+
completed_preview = db.execute(
|
|
97
|
+
"SELECT render_id FROM preview_renders WHERE timeline_id=? AND state='succeeded' ORDER BY created_at DESC LIMIT 1",
|
|
98
|
+
(revision.revision_id,),
|
|
99
|
+
).fetchone()
|
|
100
|
+
assessment = next(
|
|
101
|
+
(v for v in (json.loads(r["payload_json"]) for r in rows) if v["revision_id"] == revision.revision_id),
|
|
102
|
+
None,
|
|
103
|
+
)
|
|
104
|
+
from .production_requirements import production_contents
|
|
105
|
+
from .program_story import read_episode
|
|
106
|
+
from .program_subtitles import subtitle_status
|
|
107
|
+
|
|
108
|
+
result = {
|
|
109
|
+
**revision.to_public(include_timeline=True),
|
|
110
|
+
"run_id": published.run_id,
|
|
111
|
+
"editorial_review": assessment,
|
|
112
|
+
"creative_direction": self.repository.creative_direction(project_id, published.run_id),
|
|
113
|
+
"episode": read_episode(self.repository.projects, project_id, published.run_id, revision.timeline),
|
|
114
|
+
"subtitle_review": subtitle_status(self.repository.projects, project_id, revision.timeline),
|
|
115
|
+
"production_contents": production_contents(self.repository.projects, project_id, revision.timeline),
|
|
116
|
+
"export_url": self._export_url(project_id, published.run_id, revision.revision_id),
|
|
117
|
+
"preview_url": f"/api/projects/{project_id}/preview/{completed_preview['render_id']}/media"
|
|
118
|
+
if completed_preview
|
|
119
|
+
else None,
|
|
120
|
+
"proof_stats": {
|
|
121
|
+
"duration_seconds": stats.duration_seconds,
|
|
122
|
+
"clip_count": stats.clip_count,
|
|
123
|
+
"longest_clip_seconds": stats.longest_clip_seconds,
|
|
124
|
+
"title_count": stats.title_count,
|
|
125
|
+
"effect_count": stats.effect_count,
|
|
126
|
+
},
|
|
127
|
+
}
|
|
128
|
+
production = None
|
|
129
|
+
if latest is not None:
|
|
130
|
+
session = self.repository.production_session(project_id, latest.run_id)
|
|
131
|
+
if session is not None:
|
|
132
|
+
draft = self.repository.current_revision(project_id, latest.run_id)
|
|
133
|
+
from clipen.rendering import PreviewRenderRepository
|
|
134
|
+
|
|
135
|
+
with self.repository.projects.connect(project_id) as db:
|
|
136
|
+
previews = db.execute(
|
|
137
|
+
"SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='production_preview' ORDER BY sequence DESC LIMIT 1",
|
|
138
|
+
(latest.run_id,),
|
|
139
|
+
).fetchone()
|
|
140
|
+
successful_preview = db.execute(
|
|
141
|
+
"SELECT e.payload_json FROM edit_agent_events e JOIN preview_renders p ON p.render_id=json_extract(e.payload_json,'$.render_id') AND p.project_id=? WHERE e.run_id=? AND e.event_type='production_preview' AND p.state='succeeded' ORDER BY e.sequence DESC LIMIT 1",
|
|
142
|
+
(project_id, latest.run_id),
|
|
143
|
+
).fetchone()
|
|
144
|
+
checks = db.execute(
|
|
145
|
+
"SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='sequence_validation' ORDER BY sequence DESC LIMIT 30",
|
|
146
|
+
(latest.run_id,),
|
|
147
|
+
).fetchall()
|
|
148
|
+
jobs = db.execute(
|
|
149
|
+
"SELECT job_id,kind,state,error_code,result_json FROM production_evidence_jobs WHERE run_id=? ORDER BY rowid DESC LIMIT 10",
|
|
150
|
+
(latest.run_id,),
|
|
151
|
+
).fetchall()
|
|
152
|
+
from .production_progress import production_activity
|
|
153
|
+
|
|
154
|
+
progress = production_activity(db, latest.run_id)
|
|
155
|
+
validation = next(
|
|
156
|
+
(
|
|
157
|
+
value
|
|
158
|
+
for row in checks
|
|
159
|
+
if (value := json.loads(row["payload_json"]))["revision_id"] == draft.revision_id
|
|
160
|
+
),
|
|
161
|
+
None,
|
|
162
|
+
)
|
|
163
|
+
from .versions import versions
|
|
164
|
+
|
|
165
|
+
with self.repository.projects.connect(project_id) as db:
|
|
166
|
+
film_versions = versions(db, latest.run_id, latest.provider)
|
|
167
|
+
succeeded = db.execute(
|
|
168
|
+
"SELECT e.payload_json FROM edit_agent_events e JOIN preview_renders p ON p.render_id=json_extract(e.payload_json,'$.render_id') AND p.project_id=? WHERE e.run_id=? AND e.event_type='production_preview' AND p.state='succeeded' ORDER BY e.sequence DESC LIMIT 200",
|
|
169
|
+
(project_id, latest.run_id),
|
|
170
|
+
).fetchall()
|
|
171
|
+
# A finished film is a preview of a version people chose to keep (an AI request that
|
|
172
|
+
# finished, a manual edit or a restore); a newer preview of anything else is a draft.
|
|
173
|
+
complete = {v["revision_id"]: v for v in film_versions if v["kind"] != "ai_partial"}
|
|
174
|
+
finished_row = next(
|
|
175
|
+
(row for row in succeeded if json.loads(row["payload_json"])["revision_id"] in complete), None
|
|
176
|
+
)
|
|
177
|
+
draft_row = succeeded[0] if succeeded and succeeded[0] is not finished_row else None
|
|
178
|
+
local_jobs = []
|
|
179
|
+
for row in jobs:
|
|
180
|
+
value = json.loads(row["result_json"]) if row["result_json"] else {}
|
|
181
|
+
local_jobs.append(
|
|
182
|
+
{k: row[k] for k in ("job_id", "kind", "state", "error_code")}
|
|
183
|
+
| {k: value[k] for k in ("phase", "completed_bytes", "total_bytes") if k in value}
|
|
184
|
+
)
|
|
185
|
+
from .production_preview import render_recipe_id
|
|
186
|
+
|
|
187
|
+
recipe_id = render_recipe_id()
|
|
188
|
+
|
|
189
|
+
def preview_value(row):
|
|
190
|
+
if row is None:
|
|
191
|
+
return None
|
|
192
|
+
entry = json.loads(row["payload_json"])
|
|
193
|
+
return {
|
|
194
|
+
**PreviewRenderRepository(self.repository.projects).get(project_id, entry["render_id"]),
|
|
195
|
+
"revision_id": entry["revision_id"],
|
|
196
|
+
"stale": entry["revision_id"] != draft.revision_id or entry.get("recipe_id") != recipe_id,
|
|
197
|
+
"media_url": f"/api/projects/{project_id}/preview/{entry['render_id']}/media",
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
preview = preview_value(previews)
|
|
201
|
+
last_successful_preview = preview_value(successful_preview)
|
|
202
|
+
finished_preview = preview_value(finished_row)
|
|
203
|
+
draft_preview = preview_value(draft_row)
|
|
204
|
+
by_revision = {v["revision_id"]: v for v in reversed(film_versions)}
|
|
205
|
+
if finished_preview:
|
|
206
|
+
finished_preview["version"] = by_revision.get(finished_preview["revision_id"])
|
|
207
|
+
if draft_preview:
|
|
208
|
+
draft_preview["version"] = by_revision.get(draft_preview["revision_id"])
|
|
209
|
+
production = {
|
|
210
|
+
"intent": session["intent"],
|
|
211
|
+
"skill": {
|
|
212
|
+
k: session["skill"][k]
|
|
213
|
+
for k in (
|
|
214
|
+
"skill_id",
|
|
215
|
+
"name",
|
|
216
|
+
"version",
|
|
217
|
+
"content_hash",
|
|
218
|
+
"limitations",
|
|
219
|
+
"selected_visual_style_id",
|
|
220
|
+
"selected_font_style_id",
|
|
221
|
+
)
|
|
222
|
+
if k in session["skill"]
|
|
223
|
+
},
|
|
224
|
+
"draft": draft.to_public(include_timeline=True),
|
|
225
|
+
"preview": preview,
|
|
226
|
+
"last_successful_preview": last_successful_preview,
|
|
227
|
+
"finished_preview": finished_preview,
|
|
228
|
+
"draft_preview": draft_preview,
|
|
229
|
+
"validation": validation,
|
|
230
|
+
"local_jobs": local_jobs,
|
|
231
|
+
"production_contents": production_contents(self.repository.projects, project_id, draft.timeline),
|
|
232
|
+
"export_url": self._export_url(project_id, latest.run_id, draft.revision_id),
|
|
233
|
+
"progress": progress,
|
|
234
|
+
}
|
|
235
|
+
return {
|
|
236
|
+
"latest_run": None if latest is None else latest.to_public(),
|
|
237
|
+
"result": result,
|
|
238
|
+
"production": production,
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
def _export_url(self, project_id, run_id, revision_id):
|
|
242
|
+
try:
|
|
243
|
+
self.export_path(project_id, run_id, revision_id)
|
|
244
|
+
except ProjectError:
|
|
245
|
+
return None
|
|
246
|
+
return f"/api/projects/{project_id}/edit-agent/{run_id}/exports/{revision_id}"
|
|
247
|
+
|
|
248
|
+
def export_path(self, project_id, run_id, revision_id):
|
|
249
|
+
from .agent_models import REVISION_ID_PATTERN
|
|
250
|
+
|
|
251
|
+
self.repository.get(project_id, run_id)
|
|
252
|
+
if not isinstance(revision_id, str) or REVISION_ID_PATTERN.fullmatch(revision_id) is None:
|
|
253
|
+
raise ProjectError("agent_export_not_found", "找不到匯出的剪輯版本。", status_code=404)
|
|
254
|
+
with self.repository.projects.connect(project_id) as db:
|
|
255
|
+
if (
|
|
256
|
+
db.execute(
|
|
257
|
+
"SELECT 1 FROM edit_agent_revisions WHERE revision_id=? AND run_id=?", (revision_id, run_id)
|
|
258
|
+
).fetchone()
|
|
259
|
+
is None
|
|
260
|
+
):
|
|
261
|
+
raise ProjectError("agent_export_not_found", "匯出不屬於這次剪輯。", status_code=404)
|
|
262
|
+
root = self.repository.projects.root / project_id / "agent-production"
|
|
263
|
+
path = root / run_id / "exports" / (revision_id + ".json")
|
|
264
|
+
if (
|
|
265
|
+
any(p.is_symlink() for p in (root, root / run_id, root / run_id / "exports", path))
|
|
266
|
+
or not path.is_file()
|
|
267
|
+
or path.stat().st_size > 8 * 1024 * 1024
|
|
268
|
+
):
|
|
269
|
+
raise ProjectError("agent_export_not_found", "匯出檔案遺失或不安全。", status_code=404)
|
|
270
|
+
return path
|
|
271
|
+
|
|
272
|
+
def start(
|
|
273
|
+
self,
|
|
274
|
+
project_id: str,
|
|
275
|
+
request_id: object,
|
|
276
|
+
consent: object,
|
|
277
|
+
*,
|
|
278
|
+
max_tool_calls: int = 96,
|
|
279
|
+
max_preview_renders: int = 4,
|
|
280
|
+
production: dict,
|
|
281
|
+
) -> AgentRun:
|
|
282
|
+
if consent is not True:
|
|
283
|
+
raise ProjectError(
|
|
284
|
+
"edit_agent_consent_required",
|
|
285
|
+
f"請先同意使用 {self.provider.display_name} 額度執行這次 AI 剪輯。",
|
|
286
|
+
status_code=422,
|
|
287
|
+
)
|
|
288
|
+
with self._lock:
|
|
289
|
+
if self._closed or self._queue.full():
|
|
290
|
+
raise ProjectError("edit_agent_busy", "AI 剪輯佇列目前已滿。", status_code=409)
|
|
291
|
+
run, created = self.repository.create_run(
|
|
292
|
+
project_id,
|
|
293
|
+
request_id,
|
|
294
|
+
provider=self.provider.provider_id,
|
|
295
|
+
max_tool_calls=max_tool_calls,
|
|
296
|
+
max_preview_renders=max_preview_renders,
|
|
297
|
+
production=production,
|
|
298
|
+
)
|
|
299
|
+
if not created:
|
|
300
|
+
return run
|
|
301
|
+
key = (project_id, run.run_id)
|
|
302
|
+
self._projects.add(project_id)
|
|
303
|
+
self._cancel[key] = threading.Event()
|
|
304
|
+
self._queue.put_nowait(key)
|
|
305
|
+
if self._worker is None:
|
|
306
|
+
self._worker = threading.Thread(
|
|
307
|
+
target=self._loop,
|
|
308
|
+
name="clipen-edit-agent",
|
|
309
|
+
daemon=True,
|
|
310
|
+
)
|
|
311
|
+
self._worker.start()
|
|
312
|
+
return run
|
|
313
|
+
|
|
314
|
+
def refine(
|
|
315
|
+
self,
|
|
316
|
+
project_id,
|
|
317
|
+
run_id,
|
|
318
|
+
request_id,
|
|
319
|
+
expected_revision_id,
|
|
320
|
+
instruction,
|
|
321
|
+
consent,
|
|
322
|
+
music_asset_id=None,
|
|
323
|
+
expected_references_version=None,
|
|
324
|
+
):
|
|
325
|
+
if consent is not True:
|
|
326
|
+
raise ProjectError(
|
|
327
|
+
"edit_agent_consent_required",
|
|
328
|
+
f"請同意使用 {self.provider.display_name} 額度修改影片。",
|
|
329
|
+
status_code=422,
|
|
330
|
+
)
|
|
331
|
+
with self._lock:
|
|
332
|
+
key = (project_id, run_id)
|
|
333
|
+
if self._closed or self._queue.full() or key in self._cancel:
|
|
334
|
+
raise ProjectError("edit_agent_busy", "AI 製作仍在執行,請稍後再試。", status_code=409)
|
|
335
|
+
run, created = self.repository.request_refinement(
|
|
336
|
+
project_id,
|
|
337
|
+
run_id,
|
|
338
|
+
request_id,
|
|
339
|
+
expected_revision_id,
|
|
340
|
+
instruction,
|
|
341
|
+
music_asset_id,
|
|
342
|
+
expected_references_version,
|
|
343
|
+
provider=self.provider.provider_id,
|
|
344
|
+
)
|
|
345
|
+
if not created:
|
|
346
|
+
return run
|
|
347
|
+
self._projects.add(project_id)
|
|
348
|
+
self._cancel[key] = threading.Event()
|
|
349
|
+
self._queue.put_nowait(key)
|
|
350
|
+
if self._worker is None:
|
|
351
|
+
self._worker = threading.Thread(target=self._loop, name="clipen-edit-agent", daemon=True)
|
|
352
|
+
self._worker.start()
|
|
353
|
+
return run
|
|
354
|
+
|
|
355
|
+
def workbench_edit(self, project_id, run_id, tool, arguments, expected_revision_id, mutation_id):
|
|
356
|
+
from .workbench import edit
|
|
357
|
+
|
|
358
|
+
with self._lock:
|
|
359
|
+
return edit(self.repository, project_id, run_id, tool, arguments, expected_revision_id, mutation_id)
|
|
360
|
+
|
|
361
|
+
def workbench_render(self, project_id, run_id, expected_revision_id):
|
|
362
|
+
from .workbench import idle, tools_for
|
|
363
|
+
|
|
364
|
+
with self._lock:
|
|
365
|
+
run = idle(self.repository, project_id, run_id)
|
|
366
|
+
if run.current_revision_id != expected_revision_id:
|
|
367
|
+
raise ProjectError("revision_conflict", "影片已更新,請重新讀取。", status_code=409)
|
|
368
|
+
key = (project_id, run_id)
|
|
369
|
+
tools = self._user_previews.get(key)
|
|
370
|
+
if tools is None:
|
|
371
|
+
tools = tools_for(self.repository, project_id, run_id)
|
|
372
|
+
self._user_previews[key] = tools
|
|
373
|
+
if hasattr(tools, "_session_cache"):
|
|
374
|
+
del tools._session_cache
|
|
375
|
+
return tools.production_call("render_preview", {}).payload
|
|
376
|
+
|
|
377
|
+
def resume(self, project_id: str, run_id: str, consent: object) -> AgentRun:
|
|
378
|
+
if consent is not True:
|
|
379
|
+
raise ProjectError(
|
|
380
|
+
"edit_agent_consent_required", f"請同意接續使用 {self.provider.display_name} 額度。", status_code=422
|
|
381
|
+
)
|
|
382
|
+
with self._lock:
|
|
383
|
+
key = (project_id, run_id)
|
|
384
|
+
if self._closed or self._queue.full() or key in self._cancel:
|
|
385
|
+
raise ProjectError("edit_agent_busy", "製作工作仍在結束或佇列已滿,請稍後再試。", status_code=409)
|
|
386
|
+
run = self.repository.resume_stopped(project_id, run_id)
|
|
387
|
+
self._projects.add(project_id)
|
|
388
|
+
self._cancel[key] = threading.Event()
|
|
389
|
+
self._queue.put_nowait(key)
|
|
390
|
+
if self._worker is None:
|
|
391
|
+
self._worker = threading.Thread(target=self._loop, name="clipen-edit-agent", daemon=True)
|
|
392
|
+
self._worker.start()
|
|
393
|
+
return run
|
|
394
|
+
|
|
395
|
+
def cancel(self, project_id: str, run_id: str) -> AgentRun:
|
|
396
|
+
with self._lock:
|
|
397
|
+
run = self.repository.cancel(project_id, run_id)
|
|
398
|
+
token = self._cancel.get((project_id, run_id))
|
|
399
|
+
if token is not None:
|
|
400
|
+
token.set()
|
|
401
|
+
return run
|
|
402
|
+
|
|
403
|
+
def close(self, timeout: float = 15) -> None:
|
|
404
|
+
for tools in self._user_previews.values():
|
|
405
|
+
tools.close_production()
|
|
406
|
+
with self._lock:
|
|
407
|
+
if self._closed:
|
|
408
|
+
return
|
|
409
|
+
self._closed = True
|
|
410
|
+
active = tuple(self._cancel)
|
|
411
|
+
for token in self._cancel.values():
|
|
412
|
+
token.set()
|
|
413
|
+
while True:
|
|
414
|
+
try:
|
|
415
|
+
queued = self._queue.get_nowait()
|
|
416
|
+
except queue.Empty:
|
|
417
|
+
break
|
|
418
|
+
if queued is not None:
|
|
419
|
+
self._queue.task_done()
|
|
420
|
+
worker = self._worker
|
|
421
|
+
if worker is not None:
|
|
422
|
+
self._queue.put_nowait(None)
|
|
423
|
+
if worker is not None:
|
|
424
|
+
worker.join(max(0, timeout))
|
|
425
|
+
for project_id, run_id in active:
|
|
426
|
+
try:
|
|
427
|
+
self.repository.interrupt_for_shutdown(project_id, run_id)
|
|
428
|
+
except ProjectError:
|
|
429
|
+
pass
|
|
430
|
+
for project_id in self._projects:
|
|
431
|
+
self.repository.interrupt_incomplete(project_id)
|
|
432
|
+
|
|
433
|
+
def _end_attempt_renders(self, key) -> None:
|
|
434
|
+
from clipen.rendering import PreviewRenderRepository
|
|
435
|
+
|
|
436
|
+
try:
|
|
437
|
+
PreviewRenderRepository(self.repository.projects).interrupt_attempt_renders(*key)
|
|
438
|
+
except ProjectError:
|
|
439
|
+
pass
|
|
440
|
+
|
|
441
|
+
def _loop(self) -> None:
|
|
442
|
+
while True:
|
|
443
|
+
key = self._queue.get()
|
|
444
|
+
try:
|
|
445
|
+
if key is None:
|
|
446
|
+
return
|
|
447
|
+
with self._lock:
|
|
448
|
+
cancel = self._cancel[key]
|
|
449
|
+
if cancel.is_set():
|
|
450
|
+
continue
|
|
451
|
+
if self.repository.get(*key).provider != self.provider.provider_id:
|
|
452
|
+
# Never spend another provider's quota on a run the user
|
|
453
|
+
# authorised for the provider it was created with.
|
|
454
|
+
self.repository.record_provider_outcome(
|
|
455
|
+
*key,
|
|
456
|
+
"agent-mismatch-" + key[1].removeprefix("editrun_"),
|
|
457
|
+
usage=None,
|
|
458
|
+
error_code="provider_mismatch",
|
|
459
|
+
)
|
|
460
|
+
continue
|
|
461
|
+
adapter = self.adapter_factory(
|
|
462
|
+
self.repository.projects.root,
|
|
463
|
+
self.attempt_root,
|
|
464
|
+
self.repository,
|
|
465
|
+
**({"local_runtime": self.local_runtime} if self.local_runtime else {}),
|
|
466
|
+
)
|
|
467
|
+
self._end_attempt_renders(key)
|
|
468
|
+
adapter.execute(*key, cancel=cancel)
|
|
469
|
+
except (ProjectError, ProviderCancelled):
|
|
470
|
+
pass
|
|
471
|
+
except Exception:
|
|
472
|
+
if key is not None:
|
|
473
|
+
try:
|
|
474
|
+
current = self.repository.get(*key)
|
|
475
|
+
if current.state in {"queued", "running"}:
|
|
476
|
+
self.repository.record_provider_outcome(
|
|
477
|
+
*key,
|
|
478
|
+
"agent-launch-" + key[1].removeprefix("editrun_"),
|
|
479
|
+
usage=None,
|
|
480
|
+
error_code="provider_launch_failed",
|
|
481
|
+
)
|
|
482
|
+
except ProjectError:
|
|
483
|
+
pass
|
|
484
|
+
finally:
|
|
485
|
+
if key is not None:
|
|
486
|
+
try:
|
|
487
|
+
with self.repository.projects.connect(key[0]) as db:
|
|
488
|
+
db.execute(
|
|
489
|
+
"UPDATE production_evidence_jobs SET state='interrupted',error_code='provider_ended' WHERE run_id=? AND state='running'",
|
|
490
|
+
(key[1],),
|
|
491
|
+
)
|
|
492
|
+
except ProjectError:
|
|
493
|
+
pass
|
|
494
|
+
self._end_attempt_renders(key)
|
|
495
|
+
with self._lock:
|
|
496
|
+
self._cancel.pop(key, None)
|
|
497
|
+
self._queue.task_done()
|