@clipen/clipen-cli 0.0.0-stage → 1.0.0
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 +79 -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 +52 -4
- package/pyproject.toml +28 -0
- package/requirements/asr-runtime.txt +13 -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 +416 -0
- package/src/clipen/analysis/audio.py +392 -0
- package/src/clipen/analysis/evidence.py +102 -0
- package/src/clipen/analysis/evidence_service.py +751 -0
- package/src/clipen/analysis/image_similarity.py +143 -0
- package/src/clipen/analysis/keyframes.py +171 -0
- package/src/clipen/analysis/models.py +230 -0
- package/src/clipen/analysis/qwen_worker.py +629 -0
- package/src/clipen/analysis/resources.py +21 -0
- package/src/clipen/analysis/runtime.py +64 -0
- package/src/clipen/analysis/service.py +626 -0
- package/src/clipen/analysis/setup.py +935 -0
- package/src/clipen/analysis/setup_cli.py +117 -0
- package/src/clipen/analysis/storage.py +2046 -0
- package/src/clipen/analysis/transcription.py +948 -0
- package/src/clipen/analysis/visual.py +176 -0
- package/src/clipen/annotations/__init__.py +10 -0
- package/src/clipen/annotations/models.py +22 -0
- package/src/clipen/annotations/storage.py +380 -0
- package/src/clipen/annotations/suggestions.py +120 -0
- package/src/clipen/asr_release.py +139 -0
- package/src/clipen/bootstrap.py +967 -0
- package/src/clipen/cli.py +84 -0
- package/src/clipen/controller/__init__.py +17 -0
- package/src/clipen/controller/app.py +1470 -0
- package/src/clipen/controller/server.py +543 -0
- package/src/clipen/domain/__init__.py +30 -0
- package/src/clipen/domain/errors.py +5 -0
- package/src/clipen/domain/media_time.py +117 -0
- package/src/clipen/domain/timeline.py +584 -0
- package/src/clipen/domain/validation.py +15 -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 +134 -0
- package/src/clipen/editing/agent_repository.py +757 -0
- package/src/clipen/editing/agent_tools.py +532 -0
- package/src/clipen/editing/alignment.py +110 -0
- package/src/clipen/editing/alignment_setup.py +108 -0
- package/src/clipen/editing/alignment_worker.py +22 -0
- package/src/clipen/editing/change_report.py +71 -0
- package/src/clipen/editing/compiler.py +41 -0
- package/src/clipen/editing/component_looks.py +107 -0
- package/src/clipen/editing/component_review.py +78 -0
- package/src/clipen/editing/coordinator.py +374 -0
- package/src/clipen/editing/editorial_review.py +187 -0
- package/src/clipen/editing/evidence_jobs.py +295 -0
- package/src/clipen/editing/history_changes.py +131 -0
- package/src/clipen/editing/music_choices.py +15 -0
- package/src/clipen/editing/production_catalog.py +192 -0
- package/src/clipen/editing/production_limits.py +59 -0
- package/src/clipen/editing/production_media.py +226 -0
- package/src/clipen/editing/production_preview.py +180 -0
- package/src/clipen/editing/production_progress.py +141 -0
- package/src/clipen/editing/production_requirements.py +50 -0
- package/src/clipen/editing/production_tools.py +596 -0
- package/src/clipen/editing/program_audio.py +118 -0
- package/src/clipen/editing/program_direction.py +49 -0
- package/src/clipen/editing/program_story.py +53 -0
- package/src/clipen/editing/program_subtitles.py +134 -0
- package/src/clipen/editing/programme_review.py +73 -0
- package/src/clipen/editing/prompt_history.py +47 -0
- package/src/clipen/editing/recut.py +127 -0
- package/src/clipen/editing/refinement_references.py +188 -0
- package/src/clipen/editing/resolve_export.py +616 -0
- package/src/clipen/editing/resolve_titles.py +234 -0
- package/src/clipen/editing/skill_tools.py +575 -0
- package/src/clipen/editing/source_dialogue.py +82 -0
- package/src/clipen/editing/speech_coverage.py +30 -0
- package/src/clipen/editing/speech_quality.py +6 -0
- package/src/clipen/editing/tool_receipts.py +52 -0
- package/src/clipen/editing/versions.py +161 -0
- package/src/clipen/editing/visual_preview.py +93 -0
- package/src/clipen/editing/workbench.py +74 -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 +149 -0
- package/src/clipen/finishing/catalog.py +181 -0
- package/src/clipen/finishing/models.py +14 -0
- package/src/clipen/finishing/renderer.py +26 -0
- package/src/clipen/mcp_editing/__init__.py +5 -0
- package/src/clipen/mcp_editing/__main__.py +40 -0
- package/src/clipen/mcp_editing/server.py +353 -0
- package/src/clipen/media/__init__.py +50 -0
- package/src/clipen/media/discovery.py +266 -0
- package/src/clipen/media/models.py +360 -0
- package/src/clipen/media/preview.py +147 -0
- package/src/clipen/media/probe.py +446 -0
- package/src/clipen/media/service.py +317 -0
- package/src/clipen/media/storage.py +742 -0
- package/src/clipen/music_vocabulary.py +5 -0
- package/src/clipen/planning/__init__.py +9 -0
- package/src/clipen/planning/models.py +240 -0
- package/src/clipen/power.py +23 -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 +269 -0
- package/src/clipen/projects/evidence_schema.py +52 -0
- package/src/clipen/projects/finishing_schema.py +34 -0
- package/src/clipen/projects/models.py +192 -0
- package/src/clipen/projects/picker.py +256 -0
- package/src/clipen/projects/preview_schema.py +29 -0
- package/src/clipen/projects/service.py +175 -0
- package/src/clipen/projects/storage.py +1478 -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 +75 -0
- package/src/clipen/providers/__init__.py +43 -0
- package/src/clipen/providers/account.py +194 -0
- package/src/clipen/providers/claude.py +375 -0
- package/src/clipen/providers/claude_editing.py +111 -0
- package/src/clipen/providers/codex.py +1036 -0
- package/src/clipen/providers/codex_editing.py +91 -0
- package/src/clipen/providers/editing_agent.py +565 -0
- package/src/clipen/providers/errors.py +51 -0
- package/src/clipen/providers/recovery.py +270 -0
- package/src/clipen/py.typed +1 -0
- package/src/clipen/rendering/__init__.py +12 -0
- package/src/clipen/rendering/cover.py +126 -0
- package/src/clipen/rendering/custom_components.py +240 -0
- package/src/clipen/rendering/custom_render.py +197 -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 +64 -0
- package/src/clipen/rendering/program_components.py +193 -0
- package/src/clipen/rendering/program_creator.py +649 -0
- package/src/clipen/rendering/program_identities.py +255 -0
- package/src/clipen/rendering/program_motion.py +141 -0
- package/src/clipen/rendering/program_studio.py +168 -0
- package/src/clipen/rendering/program_styles.py +235 -0
- package/src/clipen/rendering/program_subtitles.py +52 -0
- package/src/clipen/rendering/renderer.py +708 -0
- package/src/clipen/rendering/storage.py +243 -0
- package/src/clipen/rendering/titles.py +360 -0
- package/src/clipen/skills/__init__.py +4 -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 +218 -0
- package/src/clipen/skills/library.py +131 -0
- package/src/clipen/skills/package.py +231 -0
- package/src/clipen/skills/visual_styles.py +44 -0
- package/src/clipen/workspace.py +210 -0
- package/uninstall +25 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Discoverable contracts for the agent's production tools, shared by MCP and dispatch."""
|
|
2
|
+
import json
|
|
3
|
+
from clipen.music_vocabulary import MUSIC_TAGS
|
|
4
|
+
from jsonschema import Draft202012Validator
|
|
5
|
+
from clipen.projects import ProjectError
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def schema(name, description, properties=None, required=None):
|
|
9
|
+
properties = properties or {}
|
|
10
|
+
return {'name': name, 'description': description, 'inputSchema': {
|
|
11
|
+
'type':'object', 'properties':properties, 'required':list(properties if required is None else required),
|
|
12
|
+
'additionalProperties':False}}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
ID={'type':'string','minLength':1,'maxLength':160}
|
|
16
|
+
TEXT={'type':'string','minLength':1,'maxLength':500}
|
|
17
|
+
FRAME={'type':'integer','minimum':0,'maximum':108000}
|
|
18
|
+
LENGTH={'type':'integer','minimum':1,'maximum':108000}
|
|
19
|
+
UNIT={'type':'number','minimum':0,'maximum':1}
|
|
20
|
+
GAIN={'type':'number','minimum':-60,'maximum':12}
|
|
21
|
+
SPAN={'start_frame':FRAME,'duration_frames':LENGTH}
|
|
22
|
+
SUMMARY={'summary':TEXT}
|
|
23
|
+
RECT={**SPAN,'x':UNIT,'y':UNIT,'width':{'type':'number','exclusiveMinimum':0,'maximum':1},
|
|
24
|
+
'height':{'type':'number','exclusiveMinimum':0,'maximum':1},'block_size':{'type':'integer','minimum':4,'maximum':96}}
|
|
25
|
+
EXTRA_TOOLS=(
|
|
26
|
+
schema('list_editing_tools','Discover executable tools, limits and explicitly unsupported capabilities.'),
|
|
27
|
+
schema('search_source_dialogue','Search all current source transcripts before choosing clips. Empty query browses complete utterances. Includes adjacent speech for context; inspect actual footage before inferring events.',
|
|
28
|
+
{'query':{'type':'string','maxLength':120},'version_id':ID,'include_drafts':{'type':'boolean'},
|
|
29
|
+
'offset':{'type':'integer','minimum':0,'maximum':100000},'limit':{'type':'integer','minimum':1,'maximum':30}},[]),
|
|
30
|
+
schema('list_source_media','Page through all currently inventoried source streams, including material absent from earlier candidate selection. Never copies reference footage.',
|
|
31
|
+
{'offset':{'type':'integer','minimum':0,'maximum':100000},'limit':{'type':'integer','minimum':1,'maximum':50}},[]),
|
|
32
|
+
schema('register_source_range','Create an executable candidate anywhere inside an inventoried source stream. Record observations as model-authored evidence, not verified transcript.',
|
|
33
|
+
{'version_id':ID,'stream_index':{'type':'integer','minimum':0,'maximum':4096},'start_offset_seconds':{'type':'number','minimum':0},
|
|
34
|
+
'duration_seconds':{'type':'number','exclusiveMinimum':0,'maximum':3600},'description':TEXT}),
|
|
35
|
+
schema('record_story_plan','Persist the agent-authored story plan and uncertainties against real candidates; this does not pretend the user confirmed the new treatment.',
|
|
36
|
+
{'intent':TEXT,'sections':{'type':'array','minItems':1,'maxItems':30,'items':{'type':'object','properties':{'purpose':TEXT,'candidate_ids':{'type':'array','items':ID,'maxItems':30},'treatment':TEXT},'required':['purpose','candidate_ids','treatment'],'additionalProperties':False}},
|
|
37
|
+
'uncertainties':{'type':'array','items':TEXT,'maxItems':30}}),
|
|
38
|
+
schema('read_story_plan','Read the last model-authored story plan for this run; the confirmed user intent remains separately available.'),
|
|
39
|
+
schema('plan_episode','Plan a dialogue-led programme: audience question, real experience, response/payoff and a purpose for every selected shot. Optional start_frame/duration_frames mark beats within continuous shots without artificial cuts; beats must cover the timeline once in order. Link retained cue IDs when quoting speech. This is an authored treatment, not evidence that the story is entertaining.',
|
|
40
|
+
{'premise':TEXT,'audience_question':TEXT,'payoff':TEXT,'beats':{'type':'array','minItems':1,'maxItems':30,'items':{'type':'object','properties':{
|
|
41
|
+
'beat_id':ID,'role':{'enum':['hook','setup','experience','response','payoff','bridge']},
|
|
42
|
+
**SPAN,
|
|
43
|
+
'item_ids':{'type':'array','items':ID,'minItems':1,'maxItems':30,'uniqueItems':True},
|
|
44
|
+
'dialogue_ids':{'type':'array','items':ID,'maxItems':30,'uniqueItems':True},'source_evidence':TEXT,'audience_takeaway':TEXT},
|
|
45
|
+
'required':['beat_id','role','item_ids','dialogue_ids','source_evidence','audience_takeaway'],'additionalProperties':False}}}),
|
|
46
|
+
schema('set_canvas','Choose a bounded SDR preview canvas before styling. Changes the revision and invalidates previous render review; source media and timing remain intact.',
|
|
47
|
+
{'width':{'enum':[640,1280,1920]},'height':{'enum':[360,720,1080]},**SUMMARY}),
|
|
48
|
+
schema('set_target_duration','Update the production duration only when the latest user revision request changes the desired length (including matching selected music). Cite an exact request_excerpt and derive seconds from the request or measured music. Never lower the target just to pass delivery checks. Saves an audit event without changing shots, graphics, audio or render review.',
|
|
49
|
+
{'target_duration_seconds':{'type':'integer','minimum':30,'maximum':1200},'request_excerpt':TEXT,**SUMMARY}),
|
|
50
|
+
schema('sample_source','Choose exact sample offsets inside a candidate. Returns actual frames with source timestamps; does not infer unseen motion.',
|
|
51
|
+
{'candidate_id':ID,'offsets_seconds':{'type':'array','items':{'type':'number','minimum':0},'minItems':1,'maxItems':8}}),
|
|
52
|
+
schema('inspect_candidates','Audition up to three candidate source ranges before choosing shots. Returns start/middle/end images, transcripts and evidence limitations in one call. Prefer this to repeatedly requesting single cached stills; refine with sample_source when action is missed.',
|
|
53
|
+
{'candidate_ids':{'type':'array','items':ID,'minItems':1,'maxItems':3,'uniqueItems':True}}),
|
|
54
|
+
schema('inspect_cut','Inspect start/middle/end of up to three current shots in one call, with exact source ranges, speech repair spans and overlapping text. Omit render_id to inspect sources before decorating; provide render_id for rendered review. All shots and text must be covered before finish.',
|
|
55
|
+
{'item_ids':{'type':'array','items':ID,'minItems':1,'maxItems':3,'uniqueItems':True},'render_id':ID},['item_ids']),
|
|
56
|
+
schema('inspect_pacing','Inspect actual source continuity across the current timeline. Adjacent pieces of the same take are grouped even when split; use this to find prolonged stretches to review. This does not decide whether a scene is interesting.'),
|
|
57
|
+
schema('review_cut','Save an editorial assessment of the exact current revision after inspecting every changed rendered shot (unchanged shots accepted earlier in this run are carried and may be omitted). Keep specific unresolved problems as revise/matches=false; these block finish. This is a model assessment, not human approval.',
|
|
58
|
+
{'shots':{'type':'array','maxItems':180,'items':{'type':'object','properties':{'item_id':ID,'observation':TEXT,'decision':{'enum':['keep','revise']}},'required':['item_id','observation','decision'],'additionalProperties':False}},
|
|
59
|
+
'text_checks':{'type':'array','maxItems':960,'items':{'type':'object','properties':{'item_id':ID,'evidence':TEXT,'matches':{'type':'boolean'}},'required':['item_id','evidence','matches'],'additionalProperties':False}},
|
|
60
|
+
'story_assessment':TEXT,'audio_limitations':TEXT}),
|
|
61
|
+
schema('replace_clip_source','Replace one shot with an exact inventoried source span, including expansion to a complete utterance returned by list_transcripts. Reflows the timeline and invalidates overlays. Does not restrict selection to earlier candidate windows.',
|
|
62
|
+
{'item_id':ID,'source':{'type':'object','properties':{'version_id':ID,'stream_index':{'type':'integer','minimum':0},'start_pts':{'type':'string','pattern':'^-?[0-9]+$'},'end_pts':{'type':'string','pattern':'^-?[0-9]+$'},'time_base':{'type':'object','properties':{'num':{'type':'integer','minimum':1},'den':{'type':'integer','minimum':1}},'required':['num','den'],'additionalProperties':False}},'required':['version_id','stream_index','start_pts','end_pts','time_base'],'additionalProperties':False},**SUMMARY}),
|
|
63
|
+
schema('list_transcripts','Read complete source utterances remapped to the current cut, or a candidate before cutting. include_drafts explicitly exposes low-confidence ASR as unverified draft cues, not human-approved speech.',{'candidate_id':ID,'include_drafts':{'type':'boolean'}},[]),
|
|
64
|
+
schema('replace_subtitles','Replace the editable subtitle track using returned cue IDs and faithful text; [] removes subtitles. source_excerpt selects an exact character range [start,end) in the source cue, with estimated timing, to omit uncertain ASR without inventing replacement speech. Omit unreliable cues entirely when needed; original audio is preserved.',
|
|
65
|
+
{'captions':{'type':'array','items':{'type':'object','properties':{'cue_id':ID,'text':TEXT,'source_excerpt':{'type':'object','properties':{'start':{'type':'integer','minimum':0,'maximum':500},'end':{'type':'integer','minimum':1,'maximum':500}},'required':['start','end'],'additionalProperties':False},'delivery':{'enum':['dialogue','punchline','quiet']},'emphasis':{'type':'array','items':{'type':'string','minLength':1,'maxLength':16},'maxItems':4,'uniqueItems':True}},'required':['cue_id','text'],'additionalProperties':False},'maxItems':960},'allow_asr_draft':{'type':'boolean'},**SUMMARY},['captions','summary']),
|
|
66
|
+
schema('remove_item','Delete a selected timeline element; video deletion closes the gap and invalidates time-bound overlays.',{'item_id':ID,**SUMMARY}),
|
|
67
|
+
schema('trim_clip','Trim within the current source span, close the gap, and invalidate overlays/audio placements whose timing changed.',
|
|
68
|
+
{'item_id':ID,'start_offset_frames':FRAME,'duration_frames':LENGTH,**SUMMARY}),
|
|
69
|
+
schema('reorder_clips','Reorder all video item IDs exactly once. Clears overlays and audio placements; inspect and reapply them against the new cut.',
|
|
70
|
+
{'item_ids':{'type':'array','items':ID,'minItems':1,'maxItems':180},**SUMMARY}),
|
|
71
|
+
schema('split_clip','Split a video clip at a relative frame. Existing effects/placements on that clip are cleared for explicit reapplication.',
|
|
72
|
+
{'item_id':ID,'offset_frames':LENGTH,**SUMMARY}),
|
|
73
|
+
schema('insert_clip','Insert a precisely trimmed candidate before a video item, or at end when before_item_id is null. Invalidates overlays.',
|
|
74
|
+
{'candidate_id':ID,'start_offset_seconds':{'type':'number','minimum':0},'duration_seconds':{'type':'number','minimum':0.75,'maximum':30},'before_item_id':{'anyOf':[ID,{'type':'null'}]},**SUMMARY}),
|
|
75
|
+
schema('set_source_audio','Choose camera sound treatment and gain for one video clip.',
|
|
76
|
+
{'item_id':ID,'mode':{'enum':['keep','mute','dialogue']},'gain_db':GAIN,**SUMMARY}),
|
|
77
|
+
schema('set_color_grade','Set explicit per-clip exposure/contrast/saturation; neutral values remove the visual grade.',
|
|
78
|
+
{'item_id':ID,'contrast':{'type':'number','minimum':0.5,'maximum':2},'saturation':{'type':'number','minimum':0,'maximum':2},'brightness':{'type':'number','minimum':-0.3,'maximum':0.3},**SUMMARY}),
|
|
79
|
+
schema('set_mosaic','Set static timed rectangular mosaic regions in final canvas coordinates. Multiple intervals permit manual tracking; no automatic tracking claim. [] clears.',
|
|
80
|
+
{'item_id':ID,'regions':{'type':'array','items':{'type':'object','properties':RECT,'required':list(RECT),'additionalProperties':False},'maxItems':32},**SUMMARY}),
|
|
81
|
+
schema('set_transition','Set a dip to black/white at the incoming clip boundary, or none. Duration is in timeline frames.',
|
|
82
|
+
{'item_id':ID,'kind':{'enum':['dip_black','dip_white','none']},'duration_frames':{'type':'integer','minimum':2,'maximum':60},**SUMMARY}),
|
|
83
|
+
schema('set_fade','Fade the beginning/end of THIS shot to black. Use fade_out_frames on the final shot for an actual ending. This is independent of incoming scene transitions. Zero removes that fade.',
|
|
84
|
+
{'item_id':ID,'fade_in_frames':FRAME,'fade_out_frames':FRAME,**SUMMARY}),
|
|
85
|
+
schema('remove_clip_effect','Remove any named semantic effect from a video/audio clip.',{'item_id':ID,'effect_id':ID,**SUMMARY}),
|
|
86
|
+
schema('search_music','Search and acquire up to three public instrumental candidates. Only generic music tags leave the project; preserve source/license evidence.',
|
|
87
|
+
{'tags':{'type':'array','items':{'enum':MUSIC_TAGS},'minItems':1,'maxItems':4}}),
|
|
88
|
+
schema('list_audio_assets','List acquired audio candidates and provenance without filesystem paths.'),
|
|
89
|
+
schema('extract_audio','Prepare a local source range as an audio asset for ambience, dialogue or sound effects. No ownership/license claim is invented.',
|
|
90
|
+
{'candidate_id':ID,'start_offset_seconds':{'type':'number','minimum':0},'duration_seconds':{'type':'number','exclusiveMinimum':0,'maximum':90}}),
|
|
91
|
+
schema('inspect_audio','Read measured loudness, peaks, onsets, BPM and source/license metadata. This is analysis, not listening.',{'asset_id':ID}),
|
|
92
|
+
schema('place_audio','Add/update a named audio layer anchored to a video clip. Supports independent offsets, gain, fades and dialogue ducking.',
|
|
93
|
+
{'item_id':ID,'layer_id':ID,'asset_id':ID,**SPAN,'source_offset_seconds':{'type':'number','minimum':0,'maximum':3600},'gain_db':GAIN,'duck':{'type':'boolean'},'fade_seconds':{'type':'number','minimum':0,'maximum':5},**SUMMARY}),
|
|
94
|
+
schema('remove_audio','Remove one named audio layer from the current timeline.',{'layer_id':ID,**SUMMARY}),
|
|
95
|
+
schema('render_preview','Render the current immutable revision locally for review. Asynchronous: inspect_preview reads the actual result. Reuses a successful exact-revision render.'),
|
|
96
|
+
schema('inspect_preview','Wait at most 30 seconds for a run-owned preview and inspect exact output timestamps. Does not claim audio listening or full-motion review.',
|
|
97
|
+
{'render_id':ID,'offsets_seconds':{'type':'array','items':{'type':'number','minimum':0},'maxItems':8},'wait_seconds':{'type':'number','minimum':0,'maximum':30}},['render_id','offsets_seconds']),
|
|
98
|
+
schema('cancel_preview','Cancel a preview started in this run; preserves the timeline.',{'render_id':ID}),
|
|
99
|
+
schema('validate_sequence','Check executable timing, effects, audio references and render freshness. Returns actionable issues; never aesthetic approval.'),
|
|
100
|
+
schema('get_edit_history','Read this run\'s versions (one per complete edit) and its most recent tool events, newest first. Page back with before_sequence.',
|
|
101
|
+
{'before_sequence':{'type':'integer','minimum':1},'limit':{'type':'integer','minimum':1,'maximum':80}},required=[]),
|
|
102
|
+
schema('restore_revision','Restore a run-owned immutable revision as a new current selection.',{'revision_id':ID,**SUMMARY}),
|
|
103
|
+
schema('export_edit','Save native editable timeline JSON and source/license credits for the current revision. This is not a Resolve project.'),
|
|
104
|
+
)
|
|
105
|
+
CUSTOM_COMPONENT_HELP = (
|
|
106
|
+
"Design an in-picture graphic freely as one self-contained web page: any HTML, CSS, SVG, Canvas or JavaScript, any layout, "
|
|
107
|
+
"typeface, colour, shape or motion. Use it when the built-in components cannot give the look the film needs. "
|
|
108
|
+
"The page is the whole picture (window.clipen.width x window.clipen.height pixels, e.g. 1920x1080); draw only the graphic and leave "
|
|
109
|
+
"the rest transparent, so the footage shows through. Clipen sets the time: CSS animations and the Web Animations API play by "
|
|
110
|
+
"themselves, frame-accurately; for script-driven drawing define window.clipenFrame = (frame, seconds) => {...} (may be async) "
|
|
111
|
+
"and draw that exact frame there. requestAnimationFrame loops, timers and real clocks do not advance. Frame 0 is the first frame "
|
|
112
|
+
"of the graphic; window.clipen also gives fps and durationFrames. The page has no network: inline everything (data: URLs, inline SVG). "
|
|
113
|
+
"Looks: graphics of one kind (chapters, places, reactions...) share a look you define first with set_component_look: its typefaces and "
|
|
114
|
+
"colours. Pass its look_id; Clipen gives the page that look as CSS variables, font-family: var(--look-font-<key>) and colour var(--look-<key>). "
|
|
115
|
+
"Text may only use the look's typefaces (anything else is refused); colours, layout, shapes and motion stay free. To use another typeface, "
|
|
116
|
+
"change the look or make a new one; every graphic using a look follows its changes. Only technical checks apply otherwise: the page must load, run without "
|
|
117
|
+
"errors, draw each frame within 10 seconds, draw something, and stay under 200 KB. The result returns two images: a still of the graphic at rest over the footage, and a sheet of frames from entry to exit (labelled by frame number), so you can judge the motion; look at both and fix what does not read. "
|
|
118
|
+
"Mark what people may change themselves: put each main wording as plain text in an element with data-clipen-text=\"key\" "
|
|
119
|
+
"(optional data-clipen-label=\"主標\"), and declare main colours as :root custom properties named --clipen-<name> (e.g. --clipen-主色) used via var(). "
|
|
120
|
+
"Their changes are applied before your scripts run; split text into letters on DOMContentLoaded or later, from the element's current text."
|
|
121
|
+
)
|
|
122
|
+
CUSTOM_COMPONENT_FIELDS = {
|
|
123
|
+
"element_id": ID, "item_id": {**ID, "description": "The shot the graphic starts in; it follows that footage on a recut and may run on past the cut."},
|
|
124
|
+
"start_offset_frames": FRAME, "duration_frames": LENGTH,
|
|
125
|
+
"name": {"type": "string", "minLength": 1, "maxLength": 40, "description": "Short label people see on the timeline, e.g. 澀谷地標標題."},
|
|
126
|
+
"html": {"type": "string", "minLength": 1, "maxLength": 200000},
|
|
127
|
+
"look_id": {**ID, "description": "The look (typefaces and colours) this graphic uses, from set_component_look. Required when adding."},
|
|
128
|
+
"evidence": TEXT, **SUMMARY,
|
|
129
|
+
}
|
|
130
|
+
LOOK_KEY = {"type": "string", "minLength": 1, "maxLength": 24}
|
|
131
|
+
LOOK_HELP = (
|
|
132
|
+
"Create or change a look: a named set of typefaces and colours that graphics of one kind share (e.g. a chapter look, a place look, "
|
|
133
|
+
"a reaction look). Design each look for its role; looks may differ completely. Pages use the look through CSS variables: "
|
|
134
|
+
"font-family: var(--look-font-<key>) and color var(--look-<key>). Graphics already using this look_id are redrawn with it; a change is "
|
|
135
|
+
"refused if one of them would then need a typeface the look no longer has. Typefaces: list_program_components gives font_choices "
|
|
136
|
+
"(system fonts, plus fonts Clipen carries: Chinese handwriting 'Clipen Chenyu' and brush 'Clipen Iansui', Japanese handwriting "
|
|
137
|
+
"'Yusei Magic', 'Yomogi', 'Zen Kurenaido', 'Hachi Maru Pop', Japanese display 'Dela Gothic One', 'RocknRoll One', 'Zen Maru Gothic', "
|
|
138
|
+
"Latin 'Bebas Neue', 'Anton', 'Caveat', 'Playfair Display'). A character a typeface lacks is drawn by a face of the same feel "
|
|
139
|
+
"(Japanese kana in Clipen Chenyu fall to Yomogi), so mixed Chinese and Japanese keep one style; prefer a Japanese face for mainly "
|
|
140
|
+
"Japanese text. At most 8 looks, 3 typefaces and 6 colours each."
|
|
141
|
+
)
|
|
142
|
+
SKILL_TOOLS = (
|
|
143
|
+
schema("list_production_skills", "List bundled production skills; selecting one never analyzes or uploads footage."),
|
|
144
|
+
schema("read_production_skill", "Read one resource from the skill version frozen for this session. Start with SKILL.md, then load relevant references.",
|
|
145
|
+
{"resource": {"type": "string", "maxLength": 120}}, []),
|
|
146
|
+
schema("list_program_components", "Read executable components, visual presets, exact tool parameters and limitations for the selected skill."),
|
|
147
|
+
schema("remove_program_component", "Remove one programme graphic without changing the cut, captions or music.", {"element_id": ID, **SUMMARY}),
|
|
148
|
+
schema("set_component_look", LOOK_HELP, {
|
|
149
|
+
"look_id": ID, "name": {"type": "string", "minLength": 1, "maxLength": 24, "description": "What people see, e.g. 章節, 地點, 反應字."},
|
|
150
|
+
"fonts": {"type": "array", "minItems": 1, "maxItems": 3, "items": {"type": "object", "properties": {
|
|
151
|
+
"key": LOOK_KEY, "label": LOOK_KEY, "family": {"type": "string", "maxLength": 40}}, "required": ["key", "family"], "additionalProperties": False}},
|
|
152
|
+
"colors": {"type": "array", "maxItems": 6, "items": {"type": "object", "properties": {
|
|
153
|
+
"key": LOOK_KEY, "label": LOOK_KEY, "value": {"type": "string", "pattern": "^#[0-9a-fA-F]{6}$"}}, "required": ["key", "value"], "additionalProperties": False}},
|
|
154
|
+
**SUMMARY}, ["look_id", "name", "fonts", "summary"]),
|
|
155
|
+
schema("add_custom_component", CUSTOM_COMPONENT_HELP, CUSTOM_COMPONENT_FIELDS, ["element_id", "item_id", "start_offset_frames", "duration_frames", "name", "html", "look_id", "summary"]),
|
|
156
|
+
schema("update_custom_component", "Replace any part of a graphic made with add_custom_component (its page, name, shot, timing or look); anything left out stays as it is. An older graphic without a look needs look_id. Preserves its identity and supports exact revision undo.",
|
|
157
|
+
CUSTOM_COMPONENT_FIELDS, ["element_id", "summary"]),
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
EXTRA_TOOLS += SKILL_TOOLS
|
|
161
|
+
EXTRA_TOOLS += (
|
|
162
|
+
schema('transcribe_source_range','Transcribe one registered source range locally, on demand. No old analysis/plan needed. Async job with explicit coverage; does not invent word timing.',
|
|
163
|
+
{'candidate_id':ID,'language':{'enum':['zh','en','ja']},'align_words':{'type':'boolean'}},['candidate_id']),
|
|
164
|
+
schema('align_source_speech','Align the exact ASR text from a successful transcription job to its source audio using an installed offline aligner. Does not verify wording or upload audio.',
|
|
165
|
+
{'transcript_job_id':ID}),
|
|
166
|
+
schema('read_evidence_job','Read a run-owned local evidence job. Wait up to 15 seconds; polling never repeats inference.',
|
|
167
|
+
{'job_id':ID,'wait_seconds':{'type':'number','minimum':0,'maximum':15}},['job_id']),
|
|
168
|
+
schema('cancel_evidence_job','Cancel local source transcription/alignment; preserves completed evidence and edit revisions.',{'job_id':ID}),
|
|
169
|
+
schema('inspect_mix','Read measurements and dialogue-driven duck envelopes from an actual run-owned render. Reports camera/music/final stems separately; numeric evidence is not audio listening.',{'render_id':ID}),
|
|
170
|
+
schema('prepare_local_speech','Prepare the fixed local transcription or word-alignment runtime when unavailable. Requires the session model-download grant. Async and cancellable; never uploads source audio.',{'target':{'enum':['transcription','alignment']}}),
|
|
171
|
+
schema('retry_evidence_job','Explicitly retry a failed/cancelled/interrupted LOCAL evidence job as a new attempt. The old outcome is preserved; reuse request_id to avoid starting the same retry twice.',{'job_id':ID,'request_id':ID}),
|
|
172
|
+
schema('revise_source_speech','Propose a grounded correction to one source utterance and re-align it locally. Preserves original ASR, reason and model-authored authority; never claims human verification.',
|
|
173
|
+
{'transcript_job_id':ID,'segment_ordinal':{'type':'integer','minimum':0,'maximum':99},'text':TEXT,'evidence':TEXT}),
|
|
174
|
+
schema('read_mutation_receipt','Read one run-owned mutation outcome after a lost response. A started receipt means outcome unknown: inspect the current revision before choosing another action.',{'mutation_id':ID}),
|
|
175
|
+
)
|
|
176
|
+
EXTRA_NAMES=tuple(t['name'] for t in EXTRA_TOOLS)
|
|
177
|
+
# Older films keep graphics made with the retired built-in templates; Clipen still draws them, and the
|
|
178
|
+
# AI may remove one, but it designs every new graphic itself (add_custom_component).
|
|
179
|
+
AGENT_TOOLS=EXTRA_TOOLS
|
|
180
|
+
AGENT_NAMES=EXTRA_NAMES
|
|
181
|
+
BY_NAME={t['name']:t for t in EXTRA_TOOLS}
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def validate_arguments(name, arguments):
|
|
185
|
+
errors=list(Draft202012Validator(BY_NAME[name]['inputSchema']).iter_errors(arguments))
|
|
186
|
+
if errors:
|
|
187
|
+
# Report the failing field and constraint, never echo source text/IDs or
|
|
188
|
+
# a potentially huge value. Models otherwise repeat the same invalid call.
|
|
189
|
+
error=errors[0];field='.'.join(str(p) for p in error.absolute_path) or 'arguments'
|
|
190
|
+
constraint=error.validator
|
|
191
|
+
expected=json.dumps(error.validator_value,ensure_ascii=False)[:240]
|
|
192
|
+
raise ProjectError('agent_input_invalid',f'{name}: {field} 不符合 {constraint}={expected};請依工具 schema 修正。',status_code=422)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Session-scoped production bounds and the timeline counts they are checked against."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from fractions import Fraction
|
|
4
|
+
|
|
5
|
+
from clipen.domain import EditTimeline, MediaClip, TrackKind
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True, slots=True)
|
|
9
|
+
class TimelineStats:
|
|
10
|
+
duration_seconds: float
|
|
11
|
+
clip_count: int
|
|
12
|
+
longest_clip_seconds: float
|
|
13
|
+
title_count: int
|
|
14
|
+
effect_count: int
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def timeline_stats(timeline: EditTimeline) -> TimelineStats:
|
|
18
|
+
frame_rate = Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
|
|
19
|
+
video = next((track for track in timeline.tracks if track.kind is TrackKind.VIDEO), None)
|
|
20
|
+
clips = () if video is None else video.items
|
|
21
|
+
clip_seconds = [Fraction(item.duration_frames, 1) / frame_rate for item in clips]
|
|
22
|
+
return TimelineStats(
|
|
23
|
+
float(Fraction(timeline.duration_frames, 1) / frame_rate),
|
|
24
|
+
len(clips),
|
|
25
|
+
float(max(clip_seconds, default=Fraction(0, 1))),
|
|
26
|
+
sum(len(track.items) for track in timeline.tracks if track.kind is TrackKind.TITLE),
|
|
27
|
+
sum(len(item.effects) for track in timeline.tracks for item in track.items if isinstance(item, MediaClip)),
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class ProductionLimits:
|
|
33
|
+
duration_seconds: int = 75
|
|
34
|
+
clips: int = 30
|
|
35
|
+
titles: int = 96
|
|
36
|
+
components: int = 48
|
|
37
|
+
effects: int = 256
|
|
38
|
+
delivery_min_seconds: int = 30
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def limits_for(tools):
|
|
42
|
+
target=tools._session_value()['intent'].get('target_duration_seconds',60)
|
|
43
|
+
return ProductionLimits(max(75,round(target*1.1)),180,960,128,1024,round(target*.9)) if target>75 else ProductionLimits()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def production_limit_issues(tools,timeline,*,complete=False):
|
|
47
|
+
limits=limits_for(tools);stats=timeline_stats(timeline)
|
|
48
|
+
bounds=(('duration_seconds','片長(秒)',stats.duration_seconds,limits.delivery_min_seconds if complete else .75,limits.duration_seconds),
|
|
49
|
+
('clips','鏡頭數',stats.clip_count,1,limits.clips),('longest_clip_seconds','單鏡最長秒數',stats.longest_clip_seconds,0,30),
|
|
50
|
+
('titles','文字數',stats.title_count,0,limits.titles),('effects','效果數',stats.effect_count,0,limits.effects))
|
|
51
|
+
issues=[]
|
|
52
|
+
for field,label,actual,minimum,maximum in bounds:
|
|
53
|
+
if minimum<=actual<=maximum:continue
|
|
54
|
+
below_target=field=='duration_seconds' and complete and actual<minimum
|
|
55
|
+
message=f'{label}為 {actual:g},本次允許範圍為 {minimum:g}–{maximum:g}。'
|
|
56
|
+
if below_target:message+=' 若使用者已更改片長要求,請以 set_target_duration 保存新目標後重新驗證。'
|
|
57
|
+
issues.append({'code':'production_duration_below_target' if below_target else 'production_limits_exceeded',
|
|
58
|
+
'field':field,'actual':actual,'minimum':minimum,'maximum':maximum,'message':message})
|
|
59
|
+
return issues
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Project-owned audio evidence, exact source sampling and local mix execution."""
|
|
2
|
+
from fractions import Fraction
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import secrets
|
|
8
|
+
|
|
9
|
+
from clipen.domain import MediaClip, TrackKind
|
|
10
|
+
from clipen.projects import ProjectError
|
|
11
|
+
from clipen.finishing.audio import open_asset, run_process
|
|
12
|
+
from clipen.finishing.models import digest, encoded
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def atomic_json(path,value):
|
|
16
|
+
if path.is_symlink():raise ProjectError('storage_unsafe','製作檔案不安全。',status_code=409)
|
|
17
|
+
temporary=path.parent/('.write-'+secrets.token_hex(16))
|
|
18
|
+
try:
|
|
19
|
+
fd=os.open(temporary,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
|
|
20
|
+
with os.fdopen(fd,'w') as out:
|
|
21
|
+
out.write(encoded(value));out.flush();os.fsync(out.fileno())
|
|
22
|
+
os.replace(temporary,path)
|
|
23
|
+
finally:temporary.unlink(missing_ok=True)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class AgentAudioStore:
|
|
27
|
+
def __init__(self,projects,project_id):
|
|
28
|
+
self.directory=projects.root/project_id/'agent-audio'
|
|
29
|
+
if self.directory.is_symlink():raise ProjectError('storage_unsafe','音訊目錄不安全。',status_code=409)
|
|
30
|
+
self.directory.mkdir(mode=0o700,exist_ok=True)
|
|
31
|
+
self.manifest=self.directory/'assets.json'
|
|
32
|
+
|
|
33
|
+
def records(self):
|
|
34
|
+
if self.manifest.is_symlink():raise ProjectError('storage_unsafe','音訊索引不安全。',status_code=409)
|
|
35
|
+
if not self.manifest.exists():return []
|
|
36
|
+
if self.manifest.stat().st_size>8*1024*1024:raise ProjectError('storage_corrupt','音訊索引超過上限。',status_code=409)
|
|
37
|
+
return json.loads(self.manifest.read_text())
|
|
38
|
+
|
|
39
|
+
def add(self,assets,reference):
|
|
40
|
+
records=self.records();known={r['asset']['asset_id'] for r in records}
|
|
41
|
+
records.extend({'asset':a,'reference':reference} for a in assets if a['asset_id'] not in known)
|
|
42
|
+
if len(records)>48:raise ProjectError('agent_audio_limit','這個作品已達 48 個音訊候選上限。',status_code=409)
|
|
43
|
+
atomic_json(self.manifest,records)
|
|
44
|
+
|
|
45
|
+
def public_assets(self):
|
|
46
|
+
return [{k:v for k,v in r['asset'].items() if k not in {'relative_path','fingerprint','mtime_ns','size_bytes'}} for r in self.records()]
|
|
47
|
+
|
|
48
|
+
def context(self,asset_id):
|
|
49
|
+
record=next((r for r in self.records() if r['asset']['asset_id']==asset_id),None)
|
|
50
|
+
if record is None:raise ProjectError('agent_audio_missing','找不到這個作品已取得的音訊。',status_code=404)
|
|
51
|
+
asset=record['asset'];reference=record['reference']
|
|
52
|
+
path=Path(reference['canonical_path'])
|
|
53
|
+
if path.parent!=self.directory or path.is_symlink():raise ProjectError('storage_unsafe','音訊來源不在本作品的管理範圍。',status_code=409)
|
|
54
|
+
return {'assets':[asset],'directories':{asset['role']:reference}}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def sample_frames(media,project_id,span,offsets,directory,cancel):
|
|
58
|
+
source=media.open(project_id,span.version_id)
|
|
59
|
+
paths=[];manifest=[]
|
|
60
|
+
try:
|
|
61
|
+
if span.stream_index not in source.video_stream_indices:
|
|
62
|
+
raise ProjectError('agent_video_missing','指定來源沒有這個影像串流。',status_code=409)
|
|
63
|
+
unit=Fraction(span.time_base.numerator,span.time_base.denominator)
|
|
64
|
+
for offset in offsets:
|
|
65
|
+
seconds=int(span.start_pts)*unit+Fraction(str(offset))
|
|
66
|
+
path=directory/('frame-'+secrets.token_hex(12)+'.png')
|
|
67
|
+
run_process(['ffmpeg','-v','error','-nostdin','-seek_timestamp','1','-ss',f'{float(seconds):.9f}',
|
|
68
|
+
'-i',f'/dev/fd/{source.descriptor}','-map',f'0:{span.stream_index}',
|
|
69
|
+
'-frames:v','1','-vf','scale=640:-2','-threads','1',str(path)],cancel,pass_fds=(source.descriptor,),timeout=30)
|
|
70
|
+
if not path.is_file() or not path.stat().st_size:raise ProjectError('agent_sample_missing','取樣時間沒有可解碼畫面。',status_code=409)
|
|
71
|
+
paths.append(path);manifest.append({'offset_seconds':offset,'source_seconds':float(seconds),'version_id':span.version_id})
|
|
72
|
+
finally:source.close()
|
|
73
|
+
return tuple(paths),manifest
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def transcript_cues(projects,project_id,timeline,*,include_drafts=False):
|
|
77
|
+
from .speech_quality import speech_flags
|
|
78
|
+
cues=[];limitations=[];fps=Fraction(timeline.frame_rate.numerator,timeline.frame_rate.denominator)
|
|
79
|
+
with projects.connect(project_id) as db:
|
|
80
|
+
for track in timeline.tracks:
|
|
81
|
+
if track.kind is not TrackKind.VIDEO:continue
|
|
82
|
+
for clip in track.items:
|
|
83
|
+
source_mode=next((e.parameters['mode'] for e in clip.effects if e.effect_id=='audio.source'),'keep')
|
|
84
|
+
if source_mode=='mute':continue
|
|
85
|
+
if any(e.effect_id=='video.speed_ramp' for e in clip.effects):
|
|
86
|
+
limitations.append({'item_id':clip.item_id,'reason':'speed_ramp_requires_new_transcription'});continue
|
|
87
|
+
span=clip.source.span
|
|
88
|
+
rows=db.execute("SELECT tr.*,pi.review_required FROM transcription_revisions tr JOIN preparation_items pi ON pi.transcript_revision_id=tr.revision_id JOIN current_preparation cp ON cp.run_id=pi.run_id WHERE tr.version_id=? AND tr.status IN ('transcribed','needs_review') AND tr.stream_index=(SELECT MIN(stream_index) FROM media_streams WHERE version_id=tr.version_id AND kind='audio') ORDER BY tr.stream_index",(span.version_id,)).fetchall()
|
|
89
|
+
if not rows:continue
|
|
90
|
+
row=rows[0]
|
|
91
|
+
annotation=db.execute('SELECT * FROM transcript_annotations WHERE version_id=? AND stream_index=? AND source_revision_id=?',(span.version_id,row['stream_index'],row['revision_id'])).fetchone()
|
|
92
|
+
if annotation and annotation['discarded']:continue
|
|
93
|
+
needs_review=bool((row['review_required'] or row['status']=='needs_review') and not (annotation and annotation['confirmed']))
|
|
94
|
+
corrections={} if annotation is None else {str(c['ordinal']):c['text'] for c in json.loads(annotation['corrections_json'])}
|
|
95
|
+
src=json.loads(row['source_span_json']);tb=Fraction(src['time_base']['num'],src['time_base']['den'])
|
|
96
|
+
unit=Fraction(span.time_base.numerator,span.time_base.denominator)
|
|
97
|
+
start,end=int(span.start_pts)*unit,int(span.end_pts)*unit
|
|
98
|
+
for seg in db.execute('SELECT * FROM transcript_segments WHERE revision_id=? ORDER BY ordinal',(row['revision_id'],)):
|
|
99
|
+
left,right=int(seg['start_pts'])*tb,int(seg['end_pts'])*tb
|
|
100
|
+
if right<=start or left>=end:continue
|
|
101
|
+
complete_span={'version_id':span.version_id,'stream_index':span.stream_index,
|
|
102
|
+
'start_pts':str(math.floor(left/unit)),'end_pts':str(math.ceil(right/unit)),
|
|
103
|
+
'time_base':span.time_base.to_storage()}
|
|
104
|
+
# Video cuts are quantized to frames while ASR uses audio
|
|
105
|
+
# samples. A trailing AAC/sample remainder below one frame
|
|
106
|
+
# is not a cut-off utterance; clamp displayed timing only.
|
|
107
|
+
tolerance=1/fps
|
|
108
|
+
partial=left<start-tolerance or right>end+tolerance
|
|
109
|
+
if needs_review:
|
|
110
|
+
limitations.append({'item_id':clip.item_id,'reason':'transcript_needs_review',
|
|
111
|
+
'segment_id':seg['segment_id'],'provisional_text':corrections.get(str(seg['ordinal']),seg['text']),
|
|
112
|
+
'source_revision_id':row['revision_id'],
|
|
113
|
+
'source_start_seconds':float(left),'source_end_seconds':float(right),
|
|
114
|
+
'complete_source_span':complete_span,'partial':partial,
|
|
115
|
+
'policy':'Low-confidence ASR. Explicit include_drafts/allow_asr_draft can produce a labelled draft; never claim human confirmation.'})
|
|
116
|
+
if not include_drafts or partial:continue
|
|
117
|
+
if partial:
|
|
118
|
+
limitations.append({'item_id':clip.item_id,'reason':'partial_utterance','segment_id':seg['segment_id'],
|
|
119
|
+
'text':corrections.get(str(seg['ordinal']),seg['text']),
|
|
120
|
+
'complete_source_span':{'version_id':span.version_id,'stream_index':span.stream_index,
|
|
121
|
+
'start_pts':str(math.floor(left/unit)),'end_pts':str(math.ceil(right/unit)),
|
|
122
|
+
'time_base':span.time_base.to_storage()},
|
|
123
|
+
'repair':'Use replace_clip_source with this complete_source_span; inspect the expanded shot, then rebuild subtitles. Alternatively remove/mute this speech for an explicit editorial reason.'});continue
|
|
124
|
+
begin=max(clip.start_frame,clip.start_frame+math.floor((left-start)*fps))
|
|
125
|
+
finish=min(clip.start_frame+clip.duration_frames,clip.start_frame+math.ceil((right-start)*fps))
|
|
126
|
+
cues.append({'cue_id':digest([clip.item_id,row['revision_id'],seg['segment_id']])[:24],
|
|
127
|
+
'item_id':clip.item_id,'start_frame':begin,'duration_frames':finish-begin,
|
|
128
|
+
'text':corrections.get(str(seg['ordinal']),seg['text']),'segment_id':seg['segment_id'],'source_revision_id':row['revision_id'],
|
|
129
|
+
'verification':'asr_draft' if needs_review else 'reviewed_source','confidence':seg['confidence'],
|
|
130
|
+
'quality_flags':speech_flags(corrections.get(str(seg['ordinal']),seg['text'])) if needs_review else [],
|
|
131
|
+
'source':complete_span,'boundary_adjustment_seconds':float(max(start-left,0)+max(right-end,0))})
|
|
132
|
+
return sorted(cues,key=lambda c:c['start_frame']),limitations
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
PRODUCTION_EFFECTS={'video.punch_in','video.slow_push','video.reframe','video.speed_ramp','video.grade','video.mosaic','video.transition','video.fade','audio.source','audio.layers'}
|
|
136
|
+
|
|
137
|
+
def validate_production_timeline(timeline,*,max_texts=96):
|
|
138
|
+
issues=[];cursor=0
|
|
139
|
+
video=next((t for t in timeline.tracks if t.kind is TrackKind.VIDEO),None)
|
|
140
|
+
if video is None:return [{'code':'video_required','message':'至少需要一個畫面軌。'}]
|
|
141
|
+
if not video.items:return [{'code':'video_required','message':'空白草稿尚無可渲染畫面;請先加入來源片段。'}]
|
|
142
|
+
if len([t for t in timeline.tracks if t.kind is TrackKind.VIDEO])!=1:issues.append({'code':'multiple_video_tracks_unsupported'})
|
|
143
|
+
if any(t.items for t in timeline.tracks if t.kind is TrackKind.GRAPHIC):issues.append({'code':'graphics_delivery_unsupported'})
|
|
144
|
+
for i in video.items:
|
|
145
|
+
if i.start_frame!=cursor:issues.append({'code':'video_gap_or_overlap','item_id':i.item_id})
|
|
146
|
+
cursor=i.start_frame+i.duration_frames
|
|
147
|
+
if cursor!=timeline.duration_frames:issues.append({'code':'video_end_mismatch'})
|
|
148
|
+
texts=[]
|
|
149
|
+
for t in timeline.tracks:
|
|
150
|
+
for i in t.items:
|
|
151
|
+
if i.start_frame+i.duration_frames>timeline.duration_frames:issues.append({'code':'item_out_of_bounds','item_id':i.item_id})
|
|
152
|
+
if t.kind is TrackKind.TITLE:texts.append(i)
|
|
153
|
+
if isinstance(i,MediaClip):
|
|
154
|
+
for e in i.effects:
|
|
155
|
+
if e.effect_id not in PRODUCTION_EFFECTS:issues.append({'code':'unsupported_effect','item_id':i.item_id,'effect_id':e.effect_id})
|
|
156
|
+
for n,a in enumerate(texts):
|
|
157
|
+
for b in texts[n+1:]:
|
|
158
|
+
if a.style_id==b.style_id and a.start_frame<b.start_frame+b.duration_frames and b.start_frame<a.start_frame+a.duration_frames:
|
|
159
|
+
issues.append({'code':'text_layout_collision','items':[a.item_id,b.item_id],'message':'相同位置文字同時顯示;請調整時間或樣式。'})
|
|
160
|
+
if len(texts)>max_texts:issues.append({'code':'text_limit_96' if max_texts==96 else 'production_text_limit'})
|
|
161
|
+
return issues
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def mix_audio_layers(media,project_id,timeline,base,output,cancel):
|
|
165
|
+
if timeline.production_session_id is not None:
|
|
166
|
+
from .program_audio import mix_program_audio
|
|
167
|
+
return mix_program_audio(media,project_id,timeline,base,output,cancel)
|
|
168
|
+
store=AgentAudioStore(media.projects,project_id)
|
|
169
|
+
fps=timeline.frame_rate.numerator/timeline.frame_rate.denominator;seconds=timeline.duration_frames/fps
|
|
170
|
+
layers=[(i,l) for t in timeline.tracks for i in t.items if isinstance(i,MediaClip) for e in i.effects if e.effect_id=='audio.layers' for l in e.parameters['layers']]
|
|
171
|
+
if len(layers)>24:raise ProjectError('agent_audio_limit','單次輸出最多 24 個混音片段。',status_code=409)
|
|
172
|
+
command=['ffmpeg','-v','error','-nostdin','-y','-filter_complex_threads','2','-i',str(base)]
|
|
173
|
+
opened=[];filters=['[0:a]anull[original]'];labels=['[original]']
|
|
174
|
+
try:
|
|
175
|
+
for index,(clip,layer) in enumerate(layers,1):
|
|
176
|
+
context=store.context(layer['asset_id']);fd,asset=open_asset(context,layer['asset_id']);opened.append(fd)
|
|
177
|
+
duration=layer['duration_frames']/fps;start=(clip.start_frame+layer['start_frame'])/fps
|
|
178
|
+
if start+duration>seconds or layer['source_offset_seconds']+duration>asset['duration_seconds']:
|
|
179
|
+
raise ProjectError('agent_audio_out_of_bounds','混音片段超出影片或來源長度。',status_code=409)
|
|
180
|
+
command+=['-ss',str(layer['source_offset_seconds']),'-t',str(duration),'-i',f'/dev/fd/{fd}']
|
|
181
|
+
fade=min(layer['fade_seconds'],duration/2)
|
|
182
|
+
chain=f'[{index}:{asset["stream_index"]}]asetpts=PTS-STARTPTS,aresample=48000,aformat=channel_layouts=stereo,volume={layer["gain_db"]:.4f}dB'
|
|
183
|
+
if fade:chain+=f',afade=t=in:d={fade:.6f},afade=t=out:st={duration-fade:.6f}:d={fade:.6f}'
|
|
184
|
+
chain+=f',adelay={round(start*1000)}|{round(start*1000)}[layer{index}]';filters.append(chain)
|
|
185
|
+
if layer['duck']:
|
|
186
|
+
filters.append(f'[0:a]anull[side{index}]')
|
|
187
|
+
filters.append(f'[layer{index}][side{index}]sidechaincompress=threshold=0.025:ratio=8:attack=20:release=350[duck{index}]')
|
|
188
|
+
labels.append(f'[duck{index}]')
|
|
189
|
+
else:labels.append(f'[layer{index}]')
|
|
190
|
+
filters.append(''.join(labels)+f'amix=inputs={len(labels)}:duration=first:normalize=0,alimiter=limit=0.841395:level=0[aout]')
|
|
191
|
+
command+=['-filter_complex',';'.join(filters),'-map','0:v:0','-map','[aout]','-c:v','copy','-c:a','aac','-t',str(seconds),'-movflags','+faststart',str(output)]
|
|
192
|
+
run_process(command,cancel,pass_fds=tuple(opened),timeout=300)
|
|
193
|
+
finally:
|
|
194
|
+
for fd in opened:os.close(fd)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def text_style_path(projects,project_id):
|
|
198
|
+
return projects.root/project_id/'agent-text-styles.json'
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def load_text_styles(projects,project_id):
|
|
202
|
+
if projects is None:return {}
|
|
203
|
+
path=text_style_path(projects,project_id)
|
|
204
|
+
if path.is_symlink():raise ProjectError('storage_unsafe','文字樣式檔案不安全。',status_code=409)
|
|
205
|
+
if not path.exists():return {}
|
|
206
|
+
if path.stat().st_size>16*1024*1024:raise ProjectError('storage_corrupt','文字樣式超出上限。',status_code=409)
|
|
207
|
+
return json.loads(path.read_text())
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def source_rows(projects,project_id):
|
|
211
|
+
"""The live inventory is the authority; prior planning windows are not a source boundary."""
|
|
212
|
+
with projects.connect(project_id) as db:
|
|
213
|
+
rows=db.execute("SELECT i.version_id,i.display_name,s.stream_index,s.kind,s.details_json,v.probe_json FROM current_inventory c JOIN inventory_runs r ON r.run_id=c.run_id JOIN inventory_items i ON i.run_id=r.run_id JOIN assets a ON a.asset_id=i.asset_id JOIN asset_versions v ON v.version_id=i.version_id JOIN media_streams s ON s.version_id=i.version_id WHERE c.slot=1 AND r.state='succeeded' AND a.role='source' AND i.status='usable' AND s.kind IN ('video','audio') ORDER BY i.display_name,i.version_id,s.stream_index LIMIT 10001").fetchall()
|
|
214
|
+
if len(rows)>10000:raise ProjectError('agent_source_limit','素材串流超過上限,請拆分作品。',status_code=409)
|
|
215
|
+
result=[]
|
|
216
|
+
for row in rows:
|
|
217
|
+
details=json.loads(row['details_json']);probe=json.loads(row['probe_json'] or '{}')
|
|
218
|
+
if details.get('attached_pic') or details.get('timed_thumbnails'):continue
|
|
219
|
+
try:
|
|
220
|
+
base=Fraction(details['time_base']);start=int(details.get('start_pts',0))
|
|
221
|
+
duration=int(details['duration_ts']) if 'duration_ts' in details else int(Fraction(str(probe['duration_seconds']))/base)
|
|
222
|
+
if duration<=0 or base<=0:continue
|
|
223
|
+
except (KeyError,ValueError,TypeError,ZeroDivisionError):continue
|
|
224
|
+
result.append({'version_id':row['version_id'],'display_name':row['display_name'],'stream_index':row['stream_index'],'kind':row['kind'],
|
|
225
|
+
'start_pts':str(start),'end_pts':str(start+duration),'time_base':{'num':base.numerator,'den':base.denominator},'duration_seconds':float(duration*base)})
|
|
226
|
+
return result
|