@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,121 @@
|
|
|
1
|
+
"""Observable editorial structure and caption omissions, without aesthetic scores."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import unicodedata
|
|
5
|
+
from fractions import Fraction
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def pacing(timeline):
|
|
9
|
+
from clipen.domain import TrackKind
|
|
10
|
+
|
|
11
|
+
fps = Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
|
|
12
|
+
runs = []
|
|
13
|
+
for track in timeline.tracks:
|
|
14
|
+
if track.kind is not TrackKind.VIDEO:
|
|
15
|
+
continue
|
|
16
|
+
previous = None
|
|
17
|
+
for item in track.items:
|
|
18
|
+
span = item.source.span
|
|
19
|
+
unit = Fraction(span.time_base.numerator, span.time_base.denominator)
|
|
20
|
+
left, right = int(span.start_pts) * unit, int(span.end_pts) * unit
|
|
21
|
+
contiguous = (
|
|
22
|
+
previous is not None
|
|
23
|
+
and previous["version_id"] == span.version_id
|
|
24
|
+
and previous["stream_index"] == span.stream_index
|
|
25
|
+
and abs(previous["source_end"] - left) <= 1 / fps
|
|
26
|
+
and previous["end_frame"] == item.start_frame
|
|
27
|
+
)
|
|
28
|
+
if contiguous:
|
|
29
|
+
previous["item_ids"].append(item.item_id)
|
|
30
|
+
previous["end_frame"] = item.start_frame + item.duration_frames
|
|
31
|
+
previous["source_end"] = right
|
|
32
|
+
else:
|
|
33
|
+
previous = {
|
|
34
|
+
"version_id": span.version_id,
|
|
35
|
+
"stream_index": span.stream_index,
|
|
36
|
+
"item_ids": [item.item_id],
|
|
37
|
+
"start_frame": item.start_frame,
|
|
38
|
+
"end_frame": item.start_frame + item.duration_frames,
|
|
39
|
+
"source_end": right,
|
|
40
|
+
}
|
|
41
|
+
runs.append(previous)
|
|
42
|
+
return {
|
|
43
|
+
"duration_seconds": float(timeline.duration_frames / fps),
|
|
44
|
+
"source_runs": [
|
|
45
|
+
{k: v for k, v in r.items() if k != "source_end"}
|
|
46
|
+
| {"duration_seconds": float((r["end_frame"] - r["start_frame"]) / fps)}
|
|
47
|
+
for r in runs
|
|
48
|
+
],
|
|
49
|
+
"scope": "Adjacent spans from the same source are grouped even when split into clips. This is source continuity, not visual scene detection or an aesthetic verdict.",
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def caption_coverage(tools, speech):
|
|
54
|
+
from .production_media import load_text_styles
|
|
55
|
+
|
|
56
|
+
timeline = tools._timeline()
|
|
57
|
+
styles = load_text_styles(tools.repository.projects, tools.project_id)
|
|
58
|
+
|
|
59
|
+
def words(text):
|
|
60
|
+
return "".join(
|
|
61
|
+
c.casefold() for c in unicodedata.normalize("NFKC", text) if unicodedata.category(c)[0] not in "PZC"
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
rendered = {}
|
|
65
|
+
for track in timeline.tracks:
|
|
66
|
+
if track.track_id != "agent-subtitles":
|
|
67
|
+
continue
|
|
68
|
+
for item in track.items:
|
|
69
|
+
profile = styles.get(item.style_id, {})
|
|
70
|
+
key = (profile.get("anchor_item_id"), profile.get("cue_id"))
|
|
71
|
+
rendered.setdefault(key, []).append(item)
|
|
72
|
+
missing = []
|
|
73
|
+
for cue in speech["cues"]:
|
|
74
|
+
expected = words(cue["text"])
|
|
75
|
+
if not expected:
|
|
76
|
+
continue
|
|
77
|
+
pages = sorted(rendered.get((cue["item_id"], cue["cue_id"]), []), key=lambda i: i.start_frame)
|
|
78
|
+
actual = words("".join(i.text for i in pages))
|
|
79
|
+
if actual != expected:
|
|
80
|
+
missing.append(
|
|
81
|
+
{
|
|
82
|
+
"item_id": cue["item_id"],
|
|
83
|
+
"cue_id": cue["cue_id"],
|
|
84
|
+
"start_frame": cue["start_frame"],
|
|
85
|
+
"duration_frames": cue["duration_frames"],
|
|
86
|
+
}
|
|
87
|
+
)
|
|
88
|
+
# A partially selected legacy ASR segment can disappear from cues entirely.
|
|
89
|
+
# It still needs repair unless a newer successful local job covered that cut.
|
|
90
|
+
with tools.repository.projects.connect(tools.project_id) as db:
|
|
91
|
+
local = [
|
|
92
|
+
json.loads(r["result_json"])["source"]
|
|
93
|
+
for r in db.execute(
|
|
94
|
+
"SELECT result_json FROM production_evidence_jobs WHERE run_id=? AND state='succeeded' AND kind IN ('transcribe','align')",
|
|
95
|
+
(tools.run_id,),
|
|
96
|
+
)
|
|
97
|
+
]
|
|
98
|
+
fps = Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
|
|
99
|
+
|
|
100
|
+
def locally_analyzed(item):
|
|
101
|
+
span = item.source.span
|
|
102
|
+
unit = Fraction(span.time_base.numerator, span.time_base.denominator)
|
|
103
|
+
left, right = int(span.start_pts) * unit, int(span.end_pts) * unit
|
|
104
|
+
return any(
|
|
105
|
+
s["version_id"] == span.version_id
|
|
106
|
+
and int(s["start_pts"]) * Fraction(s["time_base"]["num"], s["time_base"]["den"]) <= left + 1 / fps
|
|
107
|
+
and int(s["end_pts"]) * Fraction(s["time_base"]["num"], s["time_base"]["den"]) >= right - 1 / fps
|
|
108
|
+
for s in local
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
shots = {i.item_id: i for i in tools._video().items}
|
|
112
|
+
unresolved = sorted(
|
|
113
|
+
{
|
|
114
|
+
v["item_id"]
|
|
115
|
+
for v in speech["limitations"]
|
|
116
|
+
if (v.get("reason") in {"partial_utterance", "partial_utterance_requires_alignment"} or v.get("partial"))
|
|
117
|
+
and v["item_id"] in shots
|
|
118
|
+
and (v.get("reason") == "partial_utterance_requires_alignment" or not locally_analyzed(shots[v["item_id"]]))
|
|
119
|
+
}
|
|
120
|
+
)
|
|
121
|
+
return {"complete": not missing and not unresolved, "missing_cues": missing, "unresolved_item_ids": unresolved}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Durable user prompts, including older production and refinement requests."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
from clipen.projects import ProjectError
|
|
7
|
+
from clipen.projects.models import validate_request_id
|
|
8
|
+
from clipen.projects.storage import utc_now
|
|
9
|
+
|
|
10
|
+
from .agent_models import bounded_text, encoded
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def save(repository, project_id, request_id, kind, text):
|
|
14
|
+
repository.projects.get_project(project_id)
|
|
15
|
+
request_id = validate_request_id(request_id)
|
|
16
|
+
if kind not in {"production", "refinement"}:
|
|
17
|
+
raise ProjectError("prompt_invalid", "需求類型無效。", status_code=422)
|
|
18
|
+
text = bounded_text(text, "Prompt", 8000)
|
|
19
|
+
identifier = "prompt_" + hashlib.sha256(request_id.encode()).hexdigest()[:32]
|
|
20
|
+
value = {"prompt_id": identifier, "kind": kind, "text": text, "source": "saved"}
|
|
21
|
+
with repository.projects.connect(project_id) as db:
|
|
22
|
+
db.execute("BEGIN IMMEDIATE")
|
|
23
|
+
prior = db.execute(
|
|
24
|
+
"SELECT payload_json,created_at FROM operation_events WHERE event_id=?", (identifier,)
|
|
25
|
+
).fetchone()
|
|
26
|
+
if prior:
|
|
27
|
+
if json.loads(prior["payload_json"]) != value:
|
|
28
|
+
raise ProjectError("request_reused", "儲存識別已用於其他需求。", status_code=409)
|
|
29
|
+
return {**value, "created_at": prior["created_at"]}
|
|
30
|
+
now = utc_now()
|
|
31
|
+
db.execute(
|
|
32
|
+
"INSERT INTO operation_events(event_id,project_id,operation_id,event_type,payload_json,created_at) VALUES(?,?,?,?,?,?)",
|
|
33
|
+
(identifier, project_id, request_id, "production_prompt_saved", encoded(value), now),
|
|
34
|
+
)
|
|
35
|
+
db.commit()
|
|
36
|
+
return {**value, "created_at": now}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def history(repository, project_id=None, offset=0, limit=30):
|
|
40
|
+
if project_id:
|
|
41
|
+
projects = [repository.projects.get_project(project_id)]
|
|
42
|
+
else:
|
|
43
|
+
projects = repository.projects.list_projects()
|
|
44
|
+
entries = []
|
|
45
|
+
for project in projects:
|
|
46
|
+
with repository.projects.connect(project.project_id) as db:
|
|
47
|
+
for row in db.execute("SELECT run_id,intent_json,created_at FROM production_sessions"):
|
|
48
|
+
intent = json.loads(row["intent_json"])
|
|
49
|
+
entries.append(
|
|
50
|
+
{
|
|
51
|
+
"prompt_id": "initial-" + row["run_id"],
|
|
52
|
+
"kind": "production",
|
|
53
|
+
"text": intent["brief"],
|
|
54
|
+
"created_at": row["created_at"],
|
|
55
|
+
"source": "submitted",
|
|
56
|
+
"run_id": row["run_id"],
|
|
57
|
+
"target_duration_seconds": intent.get("target_duration_seconds"),
|
|
58
|
+
}
|
|
59
|
+
)
|
|
60
|
+
for row in db.execute(
|
|
61
|
+
"SELECT run_id,sequence,payload_json,created_at FROM edit_agent_events WHERE event_type='refinement_requested'"
|
|
62
|
+
):
|
|
63
|
+
value = json.loads(row["payload_json"])
|
|
64
|
+
entries.append(
|
|
65
|
+
{
|
|
66
|
+
"prompt_id": "revision-" + row["run_id"] + "-" + str(row["sequence"]),
|
|
67
|
+
"kind": "refinement",
|
|
68
|
+
"text": value["instruction"],
|
|
69
|
+
"references": value.get("references", {"version": 0, "items": []}),
|
|
70
|
+
"created_at": row["created_at"],
|
|
71
|
+
"source": "submitted",
|
|
72
|
+
"run_id": row["run_id"],
|
|
73
|
+
}
|
|
74
|
+
)
|
|
75
|
+
for row in db.execute(
|
|
76
|
+
"SELECT payload_json,created_at FROM operation_events WHERE event_type='production_prompt_saved'"
|
|
77
|
+
):
|
|
78
|
+
entries.append({**json.loads(row["payload_json"]), "created_at": row["created_at"]})
|
|
79
|
+
# Enrich only entries from this project, never expose filesystem paths.
|
|
80
|
+
for entry in entries:
|
|
81
|
+
if "project_id" not in entry:
|
|
82
|
+
entry.update(project_id=project.project_id, project_name=project.name)
|
|
83
|
+
entries.sort(key=lambda e: (e["created_at"], e["prompt_id"]), reverse=True)
|
|
84
|
+
return {"prompts": entries[offset : offset + limit], "total": len(entries), "offset": offset, "limit": limit}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Map existing post-production through local cuts instead of clearing it all."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import replace
|
|
4
|
+
from fractions import Fraction
|
|
5
|
+
|
|
6
|
+
from clipen.domain import EffectRequest, TextClip
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def remap_cut(tools, items):
|
|
10
|
+
from clipen.finishing.models import digest
|
|
11
|
+
|
|
12
|
+
from .production_media import atomic_json, load_text_styles, text_style_path
|
|
13
|
+
|
|
14
|
+
timeline = tools._timeline()
|
|
15
|
+
old = list(tools._video().items)
|
|
16
|
+
old_by_id = {item.item_id: item for item in old}
|
|
17
|
+
fps = Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
|
|
18
|
+
cursor, clips, invalidated = 0, [], []
|
|
19
|
+
for index, item in enumerate(items):
|
|
20
|
+
previous = old_by_id.get(item.item_id)
|
|
21
|
+
effects = list(previous.effects if previous else item.effects)
|
|
22
|
+
changed = previous is not None and previous.source != item.source
|
|
23
|
+
if changed:
|
|
24
|
+
# Clip-local masks and transitions require explicit review if the
|
|
25
|
+
# visible source changes. Preserve source treatment and music.
|
|
26
|
+
unsafe = {"video.mosaic", "video.transition", "video.fade", "video.speed_ramp"}
|
|
27
|
+
invalidated += [
|
|
28
|
+
{"item_id": item.item_id, "effect_id": e.effect_id, "reason": "changed_source_requires_review"}
|
|
29
|
+
for e in effects
|
|
30
|
+
if e.effect_id in unsafe
|
|
31
|
+
]
|
|
32
|
+
effects = [e for e in effects if e.effect_id not in unsafe]
|
|
33
|
+
if previous and any(e.effect_id == "video.transition" for e in effects):
|
|
34
|
+
before_old = old[old.index(previous) - 1].item_id if old.index(previous) else None
|
|
35
|
+
before_new = items[index - 1].item_id if index else None
|
|
36
|
+
if before_old != before_new:
|
|
37
|
+
effects = [e for e in effects if e.effect_id != "video.transition"]
|
|
38
|
+
invalidated.append({"item_id": item.item_id, "effect_id": "video.transition", "reason": "cut_changed"})
|
|
39
|
+
clips.append(replace(item, start_frame=cursor, effects=tuple(effects)))
|
|
40
|
+
cursor += item.duration_frames
|
|
41
|
+
for n, clip in enumerate(clips):
|
|
42
|
+
effects = []
|
|
43
|
+
for effect in clip.effects:
|
|
44
|
+
if effect.effect_id != "audio.layers":
|
|
45
|
+
effects.append(effect)
|
|
46
|
+
continue
|
|
47
|
+
layers = []
|
|
48
|
+
for layer in effect.parameters["layers"]:
|
|
49
|
+
remaining = cursor - clip.start_frame - layer["start_frame"]
|
|
50
|
+
if remaining <= 0:
|
|
51
|
+
invalidated.append({"layer_id": layer["layer_id"], "reason": "anchor_beyond_end"})
|
|
52
|
+
else:
|
|
53
|
+
layers.append({**layer, "duration_frames": min(layer["duration_frames"], remaining)})
|
|
54
|
+
if layers:
|
|
55
|
+
effects.append(EffectRequest("audio.layers", {"layers": layers}))
|
|
56
|
+
clips[n] = replace(clip, effects=tuple(effects))
|
|
57
|
+
styles = load_text_styles(tools.repository.projects, tools.project_id)
|
|
58
|
+
styles_changed = False
|
|
59
|
+
retained_tracks = [replace(tools._video(), items=tuple(clips))]
|
|
60
|
+
lanes = []
|
|
61
|
+
for track in timeline.tracks:
|
|
62
|
+
if track is tools._video() or track.track_id == tools._video().track_id:
|
|
63
|
+
continue
|
|
64
|
+
mapped = []
|
|
65
|
+
for element in track.items:
|
|
66
|
+
if not isinstance(element, TextClip):
|
|
67
|
+
invalidated.append({"item_id": element.item_id, "reason": "independent_track_needs_remapping"})
|
|
68
|
+
continue
|
|
69
|
+
profile = styles.get(element.style_id, {})
|
|
70
|
+
anchor = next((i for i in old if i.item_id == profile.get("anchor_item_id")), None)
|
|
71
|
+
if anchor is None:
|
|
72
|
+
anchor = next(
|
|
73
|
+
(
|
|
74
|
+
i
|
|
75
|
+
for i in old
|
|
76
|
+
if i.start_frame <= element.start_frame
|
|
77
|
+
and element.start_frame + element.duration_frames <= i.start_frame + i.duration_frames
|
|
78
|
+
),
|
|
79
|
+
None,
|
|
80
|
+
)
|
|
81
|
+
if anchor is None:
|
|
82
|
+
invalidated.append({"item_id": element.item_id, "reason": "no_source_anchor"})
|
|
83
|
+
continue
|
|
84
|
+
# A graphic only needs its first frame on the footage; it may run on past the cut.
|
|
85
|
+
graphic = profile.get("kind") == "program_component"
|
|
86
|
+
span = anchor.source.span
|
|
87
|
+
unit = Fraction(span.time_base.numerator, span.time_base.denominator)
|
|
88
|
+
left = int(span.start_pts) * unit + Fraction(element.start_frame - anchor.start_frame, 1) / fps
|
|
89
|
+
right = left + Fraction(element.duration_frames, 1) / fps
|
|
90
|
+
# Prefer stable clip identity; split children can carry an element
|
|
91
|
+
# wholly contained in their source interval. Never duplicate it.
|
|
92
|
+
candidates = sorted(clips, key=lambda i: i.item_id != anchor.item_id)
|
|
93
|
+
target = next(
|
|
94
|
+
(
|
|
95
|
+
i
|
|
96
|
+
for i in candidates
|
|
97
|
+
if i.source.span.version_id == span.version_id
|
|
98
|
+
and i.source.span.stream_index == span.stream_index
|
|
99
|
+
and (i.item_id == anchor.item_id or i.item_id not in old_by_id)
|
|
100
|
+
and int(i.source.span.start_pts) * unit <= left
|
|
101
|
+
and (
|
|
102
|
+
left < int(i.source.span.end_pts) * unit
|
|
103
|
+
if graphic
|
|
104
|
+
else right <= int(i.source.span.end_pts) * unit
|
|
105
|
+
)
|
|
106
|
+
),
|
|
107
|
+
None,
|
|
108
|
+
)
|
|
109
|
+
if target is None:
|
|
110
|
+
invalidated.append({"item_id": element.item_id, "reason": "source_removed_or_trimmed"})
|
|
111
|
+
continue
|
|
112
|
+
offset = round((left - int(target.source.span.start_pts) * unit) * fps)
|
|
113
|
+
style_id = element.style_id
|
|
114
|
+
if profile.get("kind") in {"program_component", "program_subtitle"}:
|
|
115
|
+
updated = {**profile, "anchor_item_id": target.item_id}
|
|
116
|
+
if profile["kind"] == "program_component":
|
|
117
|
+
updated["start_offset_frames"] = offset
|
|
118
|
+
style_id = ("agent.component." if profile["kind"] == "program_component" else "agent.text.") + digest(
|
|
119
|
+
updated
|
|
120
|
+
)[:24]
|
|
121
|
+
styles[style_id] = updated
|
|
122
|
+
styles_changed = True
|
|
123
|
+
start = target.start_frame + offset
|
|
124
|
+
length = min(element.duration_frames, cursor - start) if graphic else element.duration_frames
|
|
125
|
+
if length < 6:
|
|
126
|
+
invalidated.append({"item_id": element.item_id, "reason": "source_removed_or_trimmed"})
|
|
127
|
+
continue
|
|
128
|
+
mapped.append(replace(element, start_frame=start, duration_frames=length, style_id=style_id))
|
|
129
|
+
if track.track_id == "program-components" or track.track_id.startswith("program-components-"):
|
|
130
|
+
lanes.append(mapped)
|
|
131
|
+
elif mapped:
|
|
132
|
+
retained_tracks.append(replace(track, items=tuple(mapped)))
|
|
133
|
+
if styles_changed:
|
|
134
|
+
atomic_json(text_style_path(tools.repository.projects, tools.project_id), styles)
|
|
135
|
+
return replace(
|
|
136
|
+
timeline, duration_frames=cursor, tracks=tuple(retained_tracks) + relane(lanes), markers=()
|
|
137
|
+
), invalidated
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def relane(lanes):
|
|
141
|
+
"""Component lanes from lists of graphics. Graphics that run past a cut may meet others after a recut:
|
|
142
|
+
each keeps its lane while it fits, otherwise it moves to the first lane that is free at that time."""
|
|
143
|
+
from clipen.domain import Track, TrackKind
|
|
144
|
+
|
|
145
|
+
fits = lambda lane, item: all(
|
|
146
|
+
i.start_frame + i.duration_frames <= item.start_frame
|
|
147
|
+
or item.start_frame + item.duration_frames <= i.start_frame
|
|
148
|
+
for i in lane
|
|
149
|
+
)
|
|
150
|
+
placed, moved = [[] for _ in lanes], []
|
|
151
|
+
for n, items in enumerate(lanes):
|
|
152
|
+
for item in sorted(items, key=lambda i: i.start_frame):
|
|
153
|
+
(placed[n] if fits(placed[n], item) else moved).append(item)
|
|
154
|
+
for item in moved:
|
|
155
|
+
target = next((lane for lane in placed if fits(lane, item)), None)
|
|
156
|
+
if target is None:
|
|
157
|
+
target = []
|
|
158
|
+
placed.append(target)
|
|
159
|
+
target.append(item)
|
|
160
|
+
return tuple(
|
|
161
|
+
Track(
|
|
162
|
+
"program-components" if n == 0 else f"program-components-{n + 1}",
|
|
163
|
+
TrackKind.TITLE,
|
|
164
|
+
tuple(sorted(lane, key=lambda i: i.start_frame)),
|
|
165
|
+
)
|
|
166
|
+
for n, lane in enumerate([l for l in placed if l])
|
|
167
|
+
)
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"""User-owned, source-anchored review notes for incremental AI revisions.
|
|
2
|
+
|
|
3
|
+
A note marks a moment the person paused at while watching (at_offset_frames),
|
|
4
|
+
the range it covers inside one shot, and optionally the caption or programme
|
|
5
|
+
component they pointed at. Location facts stay for later rounds; every other
|
|
6
|
+
note belongs to the round it was sent with.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import math
|
|
12
|
+
from fractions import Fraction
|
|
13
|
+
|
|
14
|
+
from clipen.domain import TrackKind
|
|
15
|
+
from clipen.projects import ProjectError
|
|
16
|
+
from clipen.projects.models import validate_request_id
|
|
17
|
+
from clipen.projects.storage import command_digest, utc_now
|
|
18
|
+
from clipen.rendering.renderer import FfmpegPreviewRenderer
|
|
19
|
+
|
|
20
|
+
from .agent_models import bounded_text, encoded
|
|
21
|
+
|
|
22
|
+
KINDS = {"change", "remove", "keep", "highlight", "location", "audio", "note"}
|
|
23
|
+
LASTING = {"location"}
|
|
24
|
+
_OPTIONAL = {"source_gain_db", "fill_music", "audio_layer_id", "at_offset_frames", "explicit_range", "element_id"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def references(intent):
|
|
28
|
+
return intent.get("user_references", {"version": 0, "items": []})
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def source_pts(clip, fps, offset):
|
|
32
|
+
"""Map a cut-relative frame boundary through the native speed ramp."""
|
|
33
|
+
span = clip.source.span
|
|
34
|
+
unit = Fraction(span.time_base.numerator, span.time_base.denominator)
|
|
35
|
+
duration = span.duration_pts * unit
|
|
36
|
+
elapsed = Fraction(offset, 1) / fps
|
|
37
|
+
speed = FfmpegPreviewRenderer._speed_profile(clip)
|
|
38
|
+
if speed:
|
|
39
|
+
outside, center = map(lambda rate: Fraction(str(rate)), speed)
|
|
40
|
+
first = duration * Fraction(2, 5) / outside
|
|
41
|
+
middle = duration * Fraction(1, 5) / center
|
|
42
|
+
if elapsed < first:
|
|
43
|
+
elapsed *= outside
|
|
44
|
+
elif elapsed < first + middle:
|
|
45
|
+
elapsed = duration * Fraction(2, 5) + (elapsed - first) * center
|
|
46
|
+
else:
|
|
47
|
+
elapsed = duration * Fraction(3, 5) + (elapsed - first - middle) * outside
|
|
48
|
+
return Fraction(int(span.start_pts)) + min(duration, max(Fraction(0), elapsed)) / unit
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def locate(reference, timeline):
|
|
52
|
+
"""Only claim a current position when the anchored source cut still matches."""
|
|
53
|
+
for track in timeline.tracks:
|
|
54
|
+
if track.kind is not TrackKind.VIDEO:
|
|
55
|
+
continue
|
|
56
|
+
for clip in track.items:
|
|
57
|
+
if (
|
|
58
|
+
clip.item_id == reference["item_id"]
|
|
59
|
+
and clip.source.to_payload() == reference["clip_source"]
|
|
60
|
+
and clip.duration_frames == reference["clip_duration_frames"]
|
|
61
|
+
and timeline.frame_rate.to_storage() == reference["frame_rate"]
|
|
62
|
+
and list(FfmpegPreviewRenderer._speed_profile(clip) or ()) == reference["speed_profile"]
|
|
63
|
+
):
|
|
64
|
+
layer = reference.get("audio_layer_id")
|
|
65
|
+
if layer and not any(
|
|
66
|
+
l["layer_id"] == layer
|
|
67
|
+
for effect in clip.effects
|
|
68
|
+
if effect.effect_id == "audio.layers"
|
|
69
|
+
for l in effect.parameters["layers"]
|
|
70
|
+
):
|
|
71
|
+
return None
|
|
72
|
+
located = {
|
|
73
|
+
"item_id": clip.item_id,
|
|
74
|
+
"start_frame": clip.start_frame + reference["start_offset_frames"],
|
|
75
|
+
"duration_frames": reference["duration_frames"],
|
|
76
|
+
"at_frame": clip.start_frame + reference.get("at_offset_frames", reference["start_offset_frames"]),
|
|
77
|
+
}
|
|
78
|
+
element = reference.get("element_id")
|
|
79
|
+
if element:
|
|
80
|
+
located["element_present"] = any(
|
|
81
|
+
item.item_id == element for t in timeline.tracks for item in t.items
|
|
82
|
+
)
|
|
83
|
+
return located
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def sent(intent):
|
|
88
|
+
"""What the last revision request handed to the AI, for review."""
|
|
89
|
+
request = intent.get("latest_revision_request")
|
|
90
|
+
if not request:
|
|
91
|
+
return None
|
|
92
|
+
return {
|
|
93
|
+
"instruction": request.get("instruction"),
|
|
94
|
+
"created_at": request.get("created_at"),
|
|
95
|
+
"items": request.get("references", {}).get("items", []),
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def hand_over(intent):
|
|
100
|
+
"""Close the round: only lasting facts stay for the next one."""
|
|
101
|
+
state = references(intent)
|
|
102
|
+
kept = [item for item in state["items"] if item["kind"] in LASTING]
|
|
103
|
+
if len(kept) != len(state["items"]):
|
|
104
|
+
intent["user_references"] = {"version": state["version"] + 1, "items": kept}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def public_state(intent, timeline):
|
|
108
|
+
state = references(intent)
|
|
109
|
+
return {**state, "items": [{**item, "current_range": locate(item, timeline)} for item in state["items"]]}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def update(
|
|
113
|
+
repository, project_id, run_id, expected_revision_id, expected_version, mutation_id, reference=None, delete_id=None
|
|
114
|
+
):
|
|
115
|
+
run_id = repository._validate_run_id(run_id)
|
|
116
|
+
mutation_id = validate_request_id(mutation_id)
|
|
117
|
+
if isinstance(expected_version, bool) or not isinstance(expected_version, int) or expected_version < 0:
|
|
118
|
+
raise ProjectError("reference_invalid", "參考註記版本無效。", status_code=422)
|
|
119
|
+
if (reference is None) == (delete_id is None):
|
|
120
|
+
raise ProjectError("reference_invalid", "請指定一筆要儲存或刪除的註記。", status_code=422)
|
|
121
|
+
request_hash = command_digest(
|
|
122
|
+
{
|
|
123
|
+
"run_id": run_id,
|
|
124
|
+
"revision": expected_revision_id,
|
|
125
|
+
"version": expected_version,
|
|
126
|
+
"reference": reference,
|
|
127
|
+
"delete_id": delete_id,
|
|
128
|
+
}
|
|
129
|
+
)
|
|
130
|
+
event_id = "reference_" + hashlib.sha256(mutation_id.encode()).hexdigest()[:32]
|
|
131
|
+
with repository.projects.connect(project_id) as db:
|
|
132
|
+
db.execute("BEGIN IMMEDIATE")
|
|
133
|
+
prior = db.execute("SELECT payload_json FROM operation_events WHERE event_id=?", (event_id,)).fetchone()
|
|
134
|
+
if prior:
|
|
135
|
+
payload = json.loads(prior["payload_json"])
|
|
136
|
+
if payload["request_hash"] != request_hash:
|
|
137
|
+
raise ProjectError("request_reused", "操作識別已用於其他註記。", status_code=409)
|
|
138
|
+
return payload["result"]
|
|
139
|
+
run = repository._read_run(db, run_id)
|
|
140
|
+
latest = db.execute("SELECT run_id FROM edit_agent_runs ORDER BY created_at DESC,rowid DESC LIMIT 1").fetchone()
|
|
141
|
+
if (
|
|
142
|
+
latest["run_id"] != run_id
|
|
143
|
+
or db.execute("SELECT 1 FROM edit_agent_runs WHERE state IN ('queued','running')").fetchone()
|
|
144
|
+
):
|
|
145
|
+
raise ProjectError("edit_agent_busy", "請先停止 AI 製作,再修改參考註記。", status_code=409)
|
|
146
|
+
if run.current_revision_id != expected_revision_id:
|
|
147
|
+
raise ProjectError("revision_conflict", "影片已更新,請重新讀取後標記。", status_code=409)
|
|
148
|
+
row = db.execute("SELECT intent_json FROM production_sessions WHERE run_id=?", (run_id,)).fetchone()
|
|
149
|
+
if row is None:
|
|
150
|
+
raise ProjectError("production_required", "這個版本不支援參考註記。", status_code=422)
|
|
151
|
+
intent = json.loads(row["intent_json"])
|
|
152
|
+
state = references(intent)
|
|
153
|
+
if state["version"] != expected_version:
|
|
154
|
+
raise ProjectError("reference_conflict", "註記已在其他視窗更新,請重新讀取後再修改。", status_code=409)
|
|
155
|
+
revision = repository._read_revision(db, run.current_revision_id)
|
|
156
|
+
items = list(state["items"])
|
|
157
|
+
if delete_id is not None:
|
|
158
|
+
if not isinstance(delete_id, str) or not any(item["reference_id"] == delete_id for item in items):
|
|
159
|
+
raise ProjectError("reference_not_found", "找不到這筆註記。", status_code=404)
|
|
160
|
+
items = [item for item in items if item["reference_id"] != delete_id]
|
|
161
|
+
else:
|
|
162
|
+
item = normalize(reference, revision)
|
|
163
|
+
old = next((r for r in items if r["reference_id"] == item["reference_id"]), None)
|
|
164
|
+
if old:
|
|
165
|
+
items = [item if r["reference_id"] == item["reference_id"] else r for r in items]
|
|
166
|
+
else:
|
|
167
|
+
if len(items) >= 100:
|
|
168
|
+
raise ProjectError("reference_limit", "每支影片最多保留 100 筆參考註記。", status_code=422)
|
|
169
|
+
items.append(item)
|
|
170
|
+
intent["user_references"] = {"version": state["version"] + 1, "items": items}
|
|
171
|
+
db.execute("UPDATE production_sessions SET intent_json=? WHERE run_id=?", (encoded(intent), run_id))
|
|
172
|
+
result = public_state(intent, revision.timeline)
|
|
173
|
+
payload = {"authority": "user", "run_id": run_id, "request_hash": request_hash, "result": result}
|
|
174
|
+
db.execute(
|
|
175
|
+
"INSERT INTO operation_events(event_id,project_id,operation_id,event_type,payload_json,created_at) VALUES(?,?,?,?,?,?)",
|
|
176
|
+
(event_id, project_id, mutation_id, "production_reference_changed", encoded(payload), utc_now()),
|
|
177
|
+
)
|
|
178
|
+
db.commit()
|
|
179
|
+
return result
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def normalize(value, revision):
|
|
183
|
+
required = {"reference_id", "kind", "item_id", "start_offset_frames", "duration_frames", "note"}
|
|
184
|
+
if not isinstance(value, dict) or not required <= value.keys() or value.keys() - required - _OPTIONAL:
|
|
185
|
+
raise ProjectError("reference_invalid", "參考註記欄位無效。", status_code=422)
|
|
186
|
+
identifier = validate_request_id(value["reference_id"])
|
|
187
|
+
kind = value["kind"]
|
|
188
|
+
if not isinstance(kind, str) or kind not in KINDS:
|
|
189
|
+
raise ProjectError("reference_invalid", "請選擇註記類型。", status_code=422)
|
|
190
|
+
# "Remove this" and "this is fine" say enough on their own.
|
|
191
|
+
note = bounded_text(value["note"], "參考說明", 2000, empty=kind in {"remove", "keep"})
|
|
192
|
+
clip = next(
|
|
193
|
+
(
|
|
194
|
+
item
|
|
195
|
+
for track in revision.timeline.tracks
|
|
196
|
+
if track.kind is TrackKind.VIDEO
|
|
197
|
+
for item in track.items
|
|
198
|
+
if item.item_id == value["item_id"]
|
|
199
|
+
),
|
|
200
|
+
None,
|
|
201
|
+
)
|
|
202
|
+
if clip is None:
|
|
203
|
+
raise ProjectError("reference_invalid", "請選擇這支影片中的畫面片段。", status_code=422)
|
|
204
|
+
start, length = value["start_offset_frames"], value["duration_frames"]
|
|
205
|
+
if (
|
|
206
|
+
any(isinstance(v, bool) or not isinstance(v, int) for v in (start, length))
|
|
207
|
+
or start < 0
|
|
208
|
+
or length < 1
|
|
209
|
+
or start + length > clip.duration_frames
|
|
210
|
+
):
|
|
211
|
+
raise ProjectError("reference_invalid", "標記範圍必須在選定片段內。", status_code=422)
|
|
212
|
+
at = value.get("at_offset_frames", start)
|
|
213
|
+
if isinstance(at, bool) or not isinstance(at, int) or not start <= at < start + length:
|
|
214
|
+
raise ProjectError("reference_invalid", "標記的時間點必須在範圍內。", status_code=422)
|
|
215
|
+
if not isinstance(value.get("explicit_range", False), bool):
|
|
216
|
+
raise ProjectError("reference_invalid", "參考註記欄位無效。", status_code=422)
|
|
217
|
+
item = {k: value[k] for k in required}
|
|
218
|
+
item.update(at_offset_frames=at, explicit_range=value.get("explicit_range", False))
|
|
219
|
+
if value.get("element_id") is not None:
|
|
220
|
+
element_id = value["element_id"]
|
|
221
|
+
found = (
|
|
222
|
+
next(((t, i) for t in revision.timeline.tracks for i in t.items if i.item_id == element_id), None)
|
|
223
|
+
if isinstance(element_id, str)
|
|
224
|
+
else None
|
|
225
|
+
)
|
|
226
|
+
begin = clip.start_frame + start
|
|
227
|
+
if (
|
|
228
|
+
found is None
|
|
229
|
+
or found[1].start_frame >= begin + length
|
|
230
|
+
or found[1].start_frame + found[1].duration_frames <= begin
|
|
231
|
+
):
|
|
232
|
+
raise ProjectError("reference_invalid", "指定的字幕或元件不在這段時間。", status_code=422)
|
|
233
|
+
track, element = found
|
|
234
|
+
item.update(
|
|
235
|
+
element_id=element_id,
|
|
236
|
+
element_track=track.track_id,
|
|
237
|
+
element_text=(getattr(element, "text", None) or "")[:120] or None,
|
|
238
|
+
)
|
|
239
|
+
item.update(
|
|
240
|
+
reference_id=identifier,
|
|
241
|
+
note=note,
|
|
242
|
+
authority="user",
|
|
243
|
+
base_revision_id=revision.revision_id,
|
|
244
|
+
clip_source=clip.source.to_payload(),
|
|
245
|
+
clip_duration_frames=clip.duration_frames,
|
|
246
|
+
frame_rate=revision.timeline.frame_rate.to_storage(),
|
|
247
|
+
speed_profile=list(FfmpegPreviewRenderer._speed_profile(clip) or ()),
|
|
248
|
+
)
|
|
249
|
+
fps = Fraction(revision.timeline.frame_rate.numerator, revision.timeline.frame_rate.denominator)
|
|
250
|
+
item["source_range"] = {
|
|
251
|
+
**clip.source.span.to_storage(),
|
|
252
|
+
"start_pts": str(math.floor(source_pts(clip, fps, start))),
|
|
253
|
+
"end_pts": str(math.ceil(source_pts(clip, fps, start + length))),
|
|
254
|
+
}
|
|
255
|
+
if kind == "audio":
|
|
256
|
+
gain = value.get("source_gain_db", -12)
|
|
257
|
+
if (
|
|
258
|
+
isinstance(gain, bool)
|
|
259
|
+
or not isinstance(gain, (int, float))
|
|
260
|
+
or not math.isfinite(gain)
|
|
261
|
+
or not -60 <= gain <= 0
|
|
262
|
+
or not isinstance(value.get("fill_music", True), bool)
|
|
263
|
+
):
|
|
264
|
+
raise ProjectError("reference_invalid", "原音音量需介於 -60 至 0 dB。", status_code=422)
|
|
265
|
+
item.update(source_gain_db=gain, fill_music=value.get("fill_music", True))
|
|
266
|
+
layer = value.get("audio_layer_id")
|
|
267
|
+
if layer:
|
|
268
|
+
if not isinstance(layer, str) or not any(
|
|
269
|
+
l["layer_id"] == layer
|
|
270
|
+
for e in clip.effects
|
|
271
|
+
if e.effect_id == "audio.layers"
|
|
272
|
+
for l in e.parameters["layers"]
|
|
273
|
+
):
|
|
274
|
+
raise ProjectError("reference_invalid", "找不到選定片段的音軌。", status_code=422)
|
|
275
|
+
item["audio_layer_id"] = layer
|
|
276
|
+
elif any(key in value for key in ("source_gain_db", "fill_music", "audio_layer_id")):
|
|
277
|
+
raise ProjectError("reference_invalid", "只有聲音註記可以指定混音設定。", status_code=422)
|
|
278
|
+
return item
|