@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,118 @@
|
|
|
1
|
+
"""Bounded dialogue-driven envelopes and inspectable stems for skill productions."""
|
|
2
|
+
from array import array
|
|
3
|
+
import math
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from types import SimpleNamespace
|
|
7
|
+
import wave
|
|
8
|
+
|
|
9
|
+
from clipen.domain import MediaClip
|
|
10
|
+
from clipen.projects import ProjectError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def dialogue_regions(projects, project_id, timeline):
|
|
14
|
+
from .evidence_jobs import local_cues
|
|
15
|
+
from .production_media import transcript_cues
|
|
16
|
+
tools=SimpleNamespace(repository=SimpleNamespace(projects=projects),project_id=project_id,run_id=timeline.production_session_id)
|
|
17
|
+
local,_=local_cues(tools,timeline,include_drafts=True)
|
|
18
|
+
legacy,_=transcript_cues(projects,project_id,timeline,include_drafts=True)
|
|
19
|
+
fps=timeline.frame_rate.numerator/timeline.frame_rate.denominator
|
|
20
|
+
intervals=[]
|
|
21
|
+
for cue in local+legacy:
|
|
22
|
+
intervals.extend((w['start_frame']/fps,w['end_frame']/fps) for w in cue.get('words',[]))
|
|
23
|
+
# Legacy long ASR windows are deliberately not treated as speech activity.
|
|
24
|
+
# Missing activity leaves music at its chosen gain instead of permanently
|
|
25
|
+
# compressing it under noise. Report that limitation in the mix evidence.
|
|
26
|
+
merged=[]
|
|
27
|
+
for start,end in sorted(intervals):
|
|
28
|
+
if merged and start<=merged[-1][1]+.18:
|
|
29
|
+
merged[-1]=(merged[-1][0],max(end,merged[-1][1]))
|
|
30
|
+
elif end>start:merged.append((start,end))
|
|
31
|
+
return merged
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def duck_expression(regions, *, attenuation_db=7, attack=.12, release=.4):
|
|
35
|
+
if not regions:return '1'
|
|
36
|
+
pieces=[f"min(1,max(0,(t-{start-attack:.6f})/{attack}))*min(1,max(0,({end+release:.6f}-t)/{release}))" for start,end in regions]
|
|
37
|
+
return f"pow(10,-{attenuation_db}*min(1,({'+'.join(pieces)}))/20)"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def measure_stem(path):
|
|
41
|
+
windows=[];total=0;count=0;peak=0
|
|
42
|
+
with wave.open(str(path),'rb') as source:
|
|
43
|
+
if source.getsampwidth()!=2:raise ValueError('stem requires PCM16')
|
|
44
|
+
block=max(1,source.getframerate()//2)
|
|
45
|
+
while chunk:=source.readframes(block):
|
|
46
|
+
samples=array('h');samples.frombytes(chunk)
|
|
47
|
+
if sys.byteorder!='little':samples.byteswap()
|
|
48
|
+
power=sum(v*v for v in samples)
|
|
49
|
+
rms=math.sqrt(power/max(1,len(samples)))/32768
|
|
50
|
+
windows.append(round(20*math.log10(rms),2) if rms else None)
|
|
51
|
+
total+=power;count+=len(samples);peak=max(peak,max((abs(v) for v in samples),default=0))
|
|
52
|
+
rms=math.sqrt(total/max(1,count))/32768
|
|
53
|
+
return {'rms_dbfs':round(20*math.log10(rms),2) if rms else None,
|
|
54
|
+
'peak_dbfs':round(20*math.log10(peak/32768),2) if peak else None,
|
|
55
|
+
'window_seconds':.5,'window_rms_dbfs':windows}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def render_music_stem(media, project_id, timeline, music, cancel):
|
|
59
|
+
"""Write the music and effects under dialogue as one PCM stem; returns its settings and speech regions."""
|
|
60
|
+
from clipen.finishing.audio import open_asset, run_process
|
|
61
|
+
from .production_media import AgentAudioStore
|
|
62
|
+
fps=timeline.frame_rate.numerator/timeline.frame_rate.denominator
|
|
63
|
+
seconds=timeline.duration_frames/fps
|
|
64
|
+
layers=[(i,l) for t in timeline.tracks for i in t.items if isinstance(i,MediaClip)
|
|
65
|
+
for e in i.effects if e.effect_id=='audio.layers' for l in e.parameters['layers']]
|
|
66
|
+
if len(layers)>24:raise ProjectError('agent_audio_limit','單次最多 24 個混音片段。',status_code=422)
|
|
67
|
+
regions=dialogue_regions(media.projects,project_id,timeline)
|
|
68
|
+
if len(regions)>(1024 if seconds>75 else 256):raise ProjectError('audio_envelope_limit','語音包絡過多,請縮小預覽區間。',status_code=422)
|
|
69
|
+
store=AgentAudioStore(media.projects,project_id)
|
|
70
|
+
command=['ffmpeg','-v','error','-nostdin','-y','-filter_complex_threads','2','-f','lavfi','-i',f'anullsrc=r=48000:cl=stereo:d={seconds}']
|
|
71
|
+
filters=[];labels=['[0:a]'];duck_labels=[];opened=[];settings=[]
|
|
72
|
+
try:
|
|
73
|
+
for index,(clip,layer) in enumerate(layers,1):
|
|
74
|
+
context=store.context(layer['asset_id']);fd,asset=open_asset(context,layer['asset_id']);opened.append(fd)
|
|
75
|
+
duration=layer['duration_frames']/fps;start=(clip.start_frame+layer['start_frame'])/fps
|
|
76
|
+
if start+duration>seconds+.0001 or layer['source_offset_seconds']+duration>asset['duration_seconds']+.0001:
|
|
77
|
+
raise ProjectError('agent_audio_out_of_bounds','混音範圍超出來源或影片。',status_code=422)
|
|
78
|
+
command+=['-ss',str(layer['source_offset_seconds']),'-t',str(duration),'-i',f'/dev/fd/{fd}']
|
|
79
|
+
normalization=max(-18,min(18,-18-asset['rms_db']))
|
|
80
|
+
chain=f'[{index}:{asset["stream_index"]}]asetpts=PTS-STARTPTS,aresample=48000,aformat=channel_layouts=stereo,volume={normalization+layer["gain_db"]:.4f}dB'
|
|
81
|
+
fade=min(layer['fade_seconds'],duration/2)
|
|
82
|
+
if fade:chain+=f',afade=t=in:d={fade:.6f},afade=t=out:st={duration-fade:.6f}:d={fade:.6f}'
|
|
83
|
+
chain+=f',adelay={round(start*1000)}|{round(start*1000)}'
|
|
84
|
+
chain+=f'[layer{index}]';filters.append(chain)
|
|
85
|
+
(duck_labels if layer['duck'] else labels).append(f'[layer{index}]')
|
|
86
|
+
settings.append({'layer_id':layer['layer_id'],'start_seconds':start,'duration_seconds':duration,
|
|
87
|
+
'gain_db':layer['gain_db'],'normalization_db':normalization,'duck':layer['duck'],
|
|
88
|
+
'duck_attenuation_db':7 if layer['duck'] and regions else 0})
|
|
89
|
+
if duck_labels:
|
|
90
|
+
prefix=''.join(duck_labels)
|
|
91
|
+
if len(duck_labels)>1:prefix+=f'amix=inputs={len(duck_labels)}:duration=longest:normalize=0,'
|
|
92
|
+
filters.append(prefix+f"volume='{duck_expression(regions)}':eval=frame[ducked]")
|
|
93
|
+
labels.append('[ducked]')
|
|
94
|
+
filters.append(''.join(labels)+f'amix=inputs={len(labels)}:duration=first:normalize=0[music]')
|
|
95
|
+
run_process(command+['-filter_complex',';'.join(filters),'-map','[music]','-c:a','pcm_s16le',str(music)],cancel,pass_fds=tuple(opened),timeout=300)
|
|
96
|
+
finally:
|
|
97
|
+
for fd in opened:os.close(fd)
|
|
98
|
+
return settings,regions
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def mix_program_audio(media, project_id, timeline, base, output, cancel):
|
|
102
|
+
from clipen.finishing.audio import run_process
|
|
103
|
+
from .production_media import atomic_json
|
|
104
|
+
seconds=timeline.duration_frames/(timeline.frame_rate.numerator/timeline.frame_rate.denominator)
|
|
105
|
+
music=output.with_suffix('.music.wav');camera=output.with_suffix('.camera.wav');final=output.with_suffix('.mix.wav')
|
|
106
|
+
settings,regions=render_music_stem(media,project_id,timeline,music,cancel)
|
|
107
|
+
run_process(['ffmpeg','-v','error','-nostdin','-y','-i',str(base),'-i',str(music),
|
|
108
|
+
'-filter_complex','[0:a][1:a]amix=inputs=2:duration=first:normalize=0,alimiter=limit=0.750:level=0[a]',
|
|
109
|
+
'-map','0:v','-map','[a]','-c:v','copy','-c:a','aac','-t',str(seconds),'-movflags','+faststart',str(output)],cancel,timeout=300)
|
|
110
|
+
for source,destination in ((base,camera),(output,final)):
|
|
111
|
+
run_process(['ffmpeg','-v','error','-nostdin','-y','-i',str(source),'-vn','-ac','2','-ar','48000','-c:a','pcm_s16le',str(destination)],cancel,timeout=120)
|
|
112
|
+
measured={name:measure_stem(path) for name,path in (('camera',camera),('music',music),('mix',final))}
|
|
113
|
+
issues=[]
|
|
114
|
+
if measured['music']['peak_dbfs'] is None or measured['music']['peak_dbfs'] < -50:
|
|
115
|
+
issues.append({'code':'music_effectively_silent','message':'渲染後的配樂 stem 幾乎無聲,請調整來源與音量。'})
|
|
116
|
+
atomic_json(output.with_suffix('.mix.json'), {'measurements':measured,'layers':settings,
|
|
117
|
+
'dialogue_regions_seconds':regions,'duck_basis':'aligned_source_words' if regions else 'unavailable_no_attenuation',
|
|
118
|
+
'issues':issues,'audio_listened':False,'scope':'Rendered stems and numeric levels; audibility and musical taste still require listening.'})
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""User-selected programme direction, separate from model-authored treatments."""
|
|
2
|
+
from clipen.projects import ProjectError
|
|
3
|
+
|
|
4
|
+
PROGRAM_DIRECTION = {
|
|
5
|
+
'format': 'travel_program',
|
|
6
|
+
'title_cards': False,
|
|
7
|
+
'subtitle_style': 'program',
|
|
8
|
+
'direction': '以人物對話、期待、實際體驗與回應串起故事;不用獨立字卡交代行程。',
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
FULL_PRODUCTION_REQUIREMENTS = {'music': True, 'editing': True, 'transitions': True}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def validate_direction(value):
|
|
15
|
+
if value is None:
|
|
16
|
+
return None
|
|
17
|
+
if (not isinstance(value, dict) or set(value) not in (set(PROGRAM_DIRECTION),set(PROGRAM_DIRECTION)|{'production_requirements'})
|
|
18
|
+
or value['format'] != 'travel_program' or value['title_cards'] is not False
|
|
19
|
+
or value['subtitle_style'] != 'program' or not isinstance(value['direction'], str)
|
|
20
|
+
or not 1 <= len(value['direction'].strip()) <= 1000):
|
|
21
|
+
raise ProjectError('editing_direction_invalid', '節目方向需要明確的格式、字幕樣式與不使用字卡設定。', status_code=422)
|
|
22
|
+
requirements=value.get('production_requirements')
|
|
23
|
+
if 'production_requirements' in value and (not isinstance(requirements,dict) or set(requirements)!=set(FULL_PRODUCTION_REQUIREMENTS) or any(type(v) is not bool for v in requirements.values())):
|
|
24
|
+
raise ProjectError('editing_direction_invalid','後製需求需明確指定 music、editing、transitions。',status_code=422)
|
|
25
|
+
return dict(value)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def direction_for(tools):
|
|
29
|
+
return tools.repository.creative_direction(tools.project_id, tools.run_id)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def direction_issues(tools):
|
|
33
|
+
if direction_for(tools).get('title_cards') is not False:
|
|
34
|
+
return []
|
|
35
|
+
from clipen.domain import TrackKind
|
|
36
|
+
issues=[{'code':'title_cards_disabled', 'item_id':i.item_id}
|
|
37
|
+
for t in tools._timeline().tracks if t.kind is TrackKind.TITLE and t.track_id not in {'agent-subtitles','program-components'} and not t.track_id.startswith('program-components-') for i in t.items]
|
|
38
|
+
from .production_media import load_text_styles
|
|
39
|
+
styles=load_text_styles(tools.repository.projects,tools.project_id)
|
|
40
|
+
issues += [{'code':'program_subtitle_style_required','item_id':i.item_id}
|
|
41
|
+
for t in tools._timeline().tracks if t.track_id=='agent-subtitles' for i in t.items
|
|
42
|
+
if styles.get(i.style_id,{}).get('kind')!='program_subtitle']
|
|
43
|
+
from .speech_quality import speech_flags
|
|
44
|
+
issues += [{'code':'subtitle_draft_unreliable','item_id':i.item_id,
|
|
45
|
+
'message':'ASR 有可疑重複詞。請以 source_excerpt 選擇可用字串,或移除這段字幕並保留原音。'}
|
|
46
|
+
for t in tools._timeline().tracks if t.track_id=='agent-subtitles' for i in t.items
|
|
47
|
+
if (p:=styles.get(i.style_id,{})).get('verification')=='asr_draft'
|
|
48
|
+
and speech_flags(i.text if p.get('source_excerpt') else p.get('source_text',i.text))]
|
|
49
|
+
return issues
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""A source-bound episode treatment; never a synthetic aesthetic score."""
|
|
2
|
+
import json
|
|
3
|
+
from clipen.domain import TrackKind
|
|
4
|
+
from clipen.projects import ProjectError
|
|
5
|
+
from clipen.finishing.models import digest
|
|
6
|
+
from .production_media import atomic_json
|
|
7
|
+
from .agent_models import ToolResult
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def cut_signature(timeline):
|
|
11
|
+
return digest([{'item_id':i.item_id,'start_frame':i.start_frame,'duration_frames':i.duration_frames,
|
|
12
|
+
'source':i.source.span.to_storage(),
|
|
13
|
+
'source_audio_muted':any(e.effect_id=='audio.source' and e.parameters['mode']=='mute' for e in i.effects)}
|
|
14
|
+
for t in timeline.tracks if t.kind is TrackKind.VIDEO for i in t.items])
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def read_episode(projects,project_id,run_id,timeline):
|
|
18
|
+
base=projects.root/project_id/'agent-production'
|
|
19
|
+
path=base/run_id/'analysis'/'episode.json'
|
|
20
|
+
if any(p.is_symlink() for p in (base,base/run_id,base/run_id/'analysis',path)):
|
|
21
|
+
raise ProjectError('storage_unsafe','節目規劃路徑不安全。',status_code=409)
|
|
22
|
+
if not path.is_file():return None
|
|
23
|
+
if path.stat().st_size>128000:raise ProjectError('storage_corrupt','節目規劃超過上限。',status_code=409)
|
|
24
|
+
value=json.loads(path.read_text())
|
|
25
|
+
return value if value['cut_signature']==cut_signature(timeline) else None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def plan_episode(tools,args):
|
|
29
|
+
clips={i.item_id:i for i in tools._video().items}
|
|
30
|
+
cursor=0;beat_ids=[]
|
|
31
|
+
cues={c['cue_id']:c for c in tools._production_list_transcripts({'include_drafts':True}).payload['cues']}
|
|
32
|
+
for beat in args['beats']:
|
|
33
|
+
if beat['beat_id'] in beat_ids:raise ProjectError('episode_invalid','節目段落 ID 不可重複。',status_code=422)
|
|
34
|
+
beat_ids.append(beat['beat_id'])
|
|
35
|
+
if any(i not in clips for i in beat['item_ids']):raise ProjectError('episode_invalid','節目段落引用了不在目前剪輯的鏡頭。',status_code=422)
|
|
36
|
+
selected=[clips[i] for i in beat['item_ids']]
|
|
37
|
+
explicit='start_frame' in beat or 'duration_frames' in beat
|
|
38
|
+
if explicit and not {'start_frame','duration_frames'}<=set(beat):
|
|
39
|
+
raise ProjectError('episode_invalid','段內敘事時間需要同時提供起點與時長。',status_code=422)
|
|
40
|
+
left=beat['start_frame'] if explicit else selected[0].start_frame
|
|
41
|
+
right=left+beat['duration_frames'] if explicit else selected[-1].start_frame+selected[-1].duration_frames
|
|
42
|
+
overlapping=[i.item_id for i in clips.values() if i.start_frame<right and left<i.start_frame+i.duration_frames]
|
|
43
|
+
if left!=cursor or right>tools._timeline().duration_frames or overlapping!=beat['item_ids']:
|
|
44
|
+
raise ProjectError('episode_invalid','段落需依序覆蓋時間軸,並引用該範圍內的所有鏡頭;同一連續鏡頭可用明確時間分成不同敘事段落。',status_code=422)
|
|
45
|
+
for cue_id in beat['dialogue_ids']:
|
|
46
|
+
if cue_id not in cues or cues[cue_id]['item_id'] not in beat['item_ids'] or not (cues[cue_id]['start_frame']<right and left<cues[cue_id]['start_frame']+cues[cue_id]['duration_frames']):
|
|
47
|
+
raise ProjectError('episode_invalid','對話證據必須來自這個段落實際保留的完整口語。',status_code=422)
|
|
48
|
+
cursor=right
|
|
49
|
+
if cursor!=tools._timeline().duration_frames:
|
|
50
|
+
raise ProjectError('episode_invalid','每個鏡頭都需要明確的節目用途,不可遺漏或重複歸類。',status_code=422)
|
|
51
|
+
value={'authority':'model_authored','cut_signature':cut_signature(tools._timeline()),**args}
|
|
52
|
+
atomic_json(tools._workdir('analysis')/'episode.json',value)
|
|
53
|
+
return ToolResult({'episode':value,'review_scope':'Source links and treatment only; semantic causality and entertainment value still need review.'})
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Source-linked programme captions; draft ASR never becomes human approval."""
|
|
2
|
+
import unicodedata
|
|
3
|
+
import re
|
|
4
|
+
import math
|
|
5
|
+
from clipen.domain import TextClip
|
|
6
|
+
from clipen.finishing.models import digest
|
|
7
|
+
from clipen.projects import ProjectError
|
|
8
|
+
from .production_media import load_text_styles, atomic_json, text_style_path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def make_subtitle_items(tools,cue,row):
|
|
12
|
+
text=row['text'].strip()
|
|
13
|
+
if not text:raise ProjectError('agent_input_invalid','字幕不可空白。',status_code=422)
|
|
14
|
+
def spoken_content(value):
|
|
15
|
+
return ''.join(c.casefold() for c in unicodedata.normalize('NFKC',value) if unicodedata.category(c)[0] not in 'PZC')
|
|
16
|
+
original=cue;excerpt=row.get('source_excerpt');source_text=cue['text']
|
|
17
|
+
if excerpt:
|
|
18
|
+
left,right=excerpt['start'],excerpt['end']
|
|
19
|
+
if not 0<=left<right<=len(source_text):raise ProjectError('subtitle_source_mismatch','字幕引用字元範圍超出來源句。',status_code=422)
|
|
20
|
+
begin=cue['duration_frames']*left//len(source_text);end=cue['duration_frames']*right//len(source_text)
|
|
21
|
+
cue={**cue,'text':source_text[left:right],'start_frame':cue['start_frame']+begin,'duration_frames':end-begin}
|
|
22
|
+
if (excerpt or cue.get('verification')=='asr_draft') and spoken_content(text)!=spoken_content(cue['text']):
|
|
23
|
+
raise ProjectError('subtitle_source_mismatch','未核對字幕草稿可以調整標點與分句,不能改寫原話內容或加入新事實;請先核對來源逐字稿。',status_code=422)
|
|
24
|
+
from .speech_quality import speech_flags
|
|
25
|
+
if cue.get('verification')=='asr_draft' and speech_flags(text):
|
|
26
|
+
raise ProjectError('subtitle_draft_unreliable','這段 ASR 有可疑的連續重複詞,不能直接作為字幕。請用 source_excerpt 引用原句中可用的部分,或略過這段字幕並保留原音;不可編造替代台詞。',status_code=422)
|
|
27
|
+
# Page boundaries are an explicit estimate inside the original ASR segment,
|
|
28
|
+
# not invented word-level alignment. The original audio remains untouched.
|
|
29
|
+
spans=[];cursor=0
|
|
30
|
+
for match in re.finditer(r'[^,,。!?!?;;]+[,,。!?!?;;]*',text):
|
|
31
|
+
end=match.end();phrase=text[cursor:end];count=max(1,math.ceil(len(phrase)/18))
|
|
32
|
+
spans.extend((cursor+len(phrase)*n//count,cursor+len(phrase)*(n+1)//count) for n in range(count));cursor=end
|
|
33
|
+
if cursor<len(text):spans.append((cursor,len(text)))
|
|
34
|
+
pages=[]
|
|
35
|
+
for left,right in spans:
|
|
36
|
+
if pages and pages[-1][1]-pages[-1][0]<6 and right-pages[-1][0]<=18:
|
|
37
|
+
pages[-1]=(pages[-1][0],right)
|
|
38
|
+
else:pages.append((left,right))
|
|
39
|
+
if cue['duration_frames']<len(pages):raise ProjectError('subtitle_too_short','口語時間不足以顯示分句字幕。',status_code=422)
|
|
40
|
+
aligned = None
|
|
41
|
+
if original.get('words'):
|
|
42
|
+
frame_rate=tools._timeline().frame_rate
|
|
43
|
+
aligned = aligned_pages(original, text, excerpt, pages, frame_rate.numerator/frame_rate.denominator)
|
|
44
|
+
pages = [(left,right) for left,right,_,_ in aligned]
|
|
45
|
+
styles=load_text_styles(tools.repository.projects,tools.project_id);items=[]
|
|
46
|
+
for n,(left,right) in enumerate(pages):
|
|
47
|
+
start=cue['start_frame']+cue['duration_frames']*left//len(text)
|
|
48
|
+
end=cue['start_frame']+cue['duration_frames']*right//len(text)
|
|
49
|
+
if aligned:
|
|
50
|
+
start,end = aligned[n][2:]
|
|
51
|
+
delivery=row.get('delivery','dialogue')
|
|
52
|
+
profile={'kind':'program_subtitle','font_size_ratio':.075 if delivery=='punchline' else .05 if delivery=='quiet' else .06,
|
|
53
|
+
'delivery':delivery,'emphasis':[s for s in row.get('emphasis',[]) if s in text[left:right]],
|
|
54
|
+
'verification':cue.get('verification','reviewed_source'),'source_revision_id':cue.get('source_revision_id'),
|
|
55
|
+
'segment_id':cue.get('segment_id'),'source':cue.get('source'),'source_text':source_text,
|
|
56
|
+
'source_excerpt':excerpt,'cue_id':cue['cue_id'],'anchor_item_id':original.get('item_id'),
|
|
57
|
+
'timing_basis':'forced_alignment' if aligned else 'character_proportional_within_asr_segment' if excerpt or len(pages)>1 else 'asr_segment',
|
|
58
|
+
'caption_text_edited':text!=original['text'],'motion':'none' if delivery=='quiet' else 'pop'}
|
|
59
|
+
profile.update({key:original[key] for key in ('wording_authority','source_asr_text','correction_evidence') if key in original})
|
|
60
|
+
skill=tools._skill_value();preset=skill['presets']['subtitle']
|
|
61
|
+
profile.update({'font_size_ratio':preset['font_size_ratio']*(1.25 if delivery=='punchline' else .9 if delivery=='quiet' else 1),
|
|
62
|
+
'emphasis_color':preset['emphasis_color'],'outline_color':preset['outline_color'],
|
|
63
|
+
'skill_hash':skill['content_hash']})
|
|
64
|
+
identifier='agent.text.'+digest(profile)[:24];styles[identifier]=profile
|
|
65
|
+
items.append(TextClip('subtitle-'+cue['cue_id']+'-'+str(n),start,end-start,text[left:right],identifier))
|
|
66
|
+
from .production_limits import limits_for
|
|
67
|
+
if len(styles)>max(256,limits_for(tools).titles*2):raise ProjectError('agent_input_invalid','自訂字幕樣式索引超過上限。',status_code=422)
|
|
68
|
+
atomic_json(text_style_path(tools.repository.projects,tools.project_id),styles)
|
|
69
|
+
return items
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def aligned_pages(cue, text, excerpt, pages, fps=30):
|
|
73
|
+
"""Snap display page boundaries to actual words; pauses get no invented duration."""
|
|
74
|
+
from .alignment import significant
|
|
75
|
+
original = cue['text']
|
|
76
|
+
left,right = (excerpt['start'],excerpt['end']) if excerpt else (0,len(original))
|
|
77
|
+
if significant(text) != significant(original[left:right]):
|
|
78
|
+
raise ProjectError('subtitle_alignment_text_changed','文字已改變,請重新對齊後再建立字幕。',status_code=422)
|
|
79
|
+
words=[w for w in cue['words'] if w['char_end']>left and w['char_start']<right]
|
|
80
|
+
if not words or words[0]['char_start']<left or words[-1]['char_end']>right:
|
|
81
|
+
raise ProjectError('subtitle_word_boundary_required','摘錄需包含完整對齊字詞,不能在詞內估算時間。',status_code=422)
|
|
82
|
+
display_positions=[n for n,c in enumerate(text) if significant(c)]
|
|
83
|
+
start_count=len(significant(original[:left]))
|
|
84
|
+
counts=[(len(significant(original[:w['char_start']]))-start_count,
|
|
85
|
+
len(significant(original[:w['char_end']]))-start_count,w) for w in words]
|
|
86
|
+
endings=set()
|
|
87
|
+
for previous, following in zip(counts, counts[1:]):
|
|
88
|
+
if following[2]['start_frame']-previous[2]['end_frame'] > .6*fps:
|
|
89
|
+
endings.add(previous[1])
|
|
90
|
+
for _,end in pages:
|
|
91
|
+
desired=len(significant(text[:end]))
|
|
92
|
+
ending=next((b for a,b,_ in counts if b>=desired),len(display_positions))
|
|
93
|
+
endings.add(ending)
|
|
94
|
+
endings.add(len(display_positions))
|
|
95
|
+
result=[];previous=0;previous_count=0
|
|
96
|
+
for count in sorted(endings):
|
|
97
|
+
if count<=previous_count:continue
|
|
98
|
+
end=display_positions[count] if count<len(display_positions) else len(text)
|
|
99
|
+
included=[word for a,b,word in counts if a>=previous_count and b<=count]
|
|
100
|
+
if not included:
|
|
101
|
+
raise ProjectError('subtitle_alignment_incomplete','分頁沒有完整對齊字詞。',status_code=422)
|
|
102
|
+
first,last=included[0]['start_frame'],included[-1]['end_frame']
|
|
103
|
+
if last<=first:
|
|
104
|
+
raise ProjectError('subtitle_too_short','對齊字詞不足一格,請調整分句。',status_code=422)
|
|
105
|
+
result.append((previous,end,first,last));previous=end;previous_count=count
|
|
106
|
+
# Word evidence can put pauses inside a short phrase (我 / 們, 伴手 / 禮).
|
|
107
|
+
# Join tiny pages using the existing first/last word boundaries; no word
|
|
108
|
+
# timestamps are stretched or estimated, and long pauses remain separate.
|
|
109
|
+
merged=[]
|
|
110
|
+
for current in result:
|
|
111
|
+
if merged:
|
|
112
|
+
before=merged[-1]
|
|
113
|
+
short=min(len(significant(text[before[0]:before[1]])),len(significant(text[current[0]:current[1]])))<=5
|
|
114
|
+
sentence_end=text[before[0]:before[1]].rstrip().endswith(('。','!','?','!','?','.'))
|
|
115
|
+
tiny_reply=len(significant(text[current[0]:current[1]]))<=1
|
|
116
|
+
if short and (not sentence_end or tiny_reply) and current[2]-before[3]<1.5*fps and len(significant(text[before[0]:current[1]]))<=18:
|
|
117
|
+
merged[-1]=(before[0],current[1],before[2],current[3]);continue
|
|
118
|
+
merged.append(current)
|
|
119
|
+
return merged
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def subtitle_status(projects,project_id,timeline):
|
|
123
|
+
from clipen.domain import TrackKind
|
|
124
|
+
styles=load_text_styles(projects,project_id)
|
|
125
|
+
items=[i for t in timeline.tracks if t.kind is TrackKind.TITLE and t.track_id=='agent-subtitles' for i in t.items]
|
|
126
|
+
drafts=[i.item_id for i in items if styles.get(i.style_id,{}).get('verification')=='asr_draft']
|
|
127
|
+
aligned=[i.item_id for i in items if styles.get(i.style_id,{}).get('timing_basis')=='forced_alignment']
|
|
128
|
+
manual=[i.item_id for i in items if styles.get(i.style_id,{}).get('timing_basis')=='user_adjusted']
|
|
129
|
+
timed=set(aligned+manual)
|
|
130
|
+
unaligned=[i.item_id for i in items if i.item_id not in timed]
|
|
131
|
+
return {'count':len(items),'draft_count':len(drafts),'draft_item_ids':drafts,
|
|
132
|
+
'unaligned_item_ids':unaligned,'aligned_count':len(aligned),
|
|
133
|
+
'manual_timing_item_ids':manual,'manual_timing_count':len(manual),
|
|
134
|
+
'audio_listened':False,'review_scope':'Source-linked draft captions are not human-verified transcription.'}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Observable editorial structure and caption omissions, without aesthetic scores."""
|
|
2
|
+
from fractions import Fraction
|
|
3
|
+
import json
|
|
4
|
+
import unicodedata
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def pacing(timeline):
|
|
8
|
+
from clipen.domain import TrackKind
|
|
9
|
+
fps=Fraction(timeline.frame_rate.numerator,timeline.frame_rate.denominator)
|
|
10
|
+
runs=[]
|
|
11
|
+
for track in timeline.tracks:
|
|
12
|
+
if track.kind is not TrackKind.VIDEO:continue
|
|
13
|
+
previous=None
|
|
14
|
+
for item in track.items:
|
|
15
|
+
span=item.source.span
|
|
16
|
+
unit=Fraction(span.time_base.numerator,span.time_base.denominator)
|
|
17
|
+
left,right=int(span.start_pts)*unit,int(span.end_pts)*unit
|
|
18
|
+
contiguous=(previous is not None and previous['version_id']==span.version_id
|
|
19
|
+
and previous['stream_index']==span.stream_index
|
|
20
|
+
and abs(previous['source_end']-left)<=1/fps
|
|
21
|
+
and previous['end_frame']==item.start_frame)
|
|
22
|
+
if contiguous:
|
|
23
|
+
previous['item_ids'].append(item.item_id)
|
|
24
|
+
previous['end_frame']=item.start_frame+item.duration_frames
|
|
25
|
+
previous['source_end']=right
|
|
26
|
+
else:
|
|
27
|
+
previous={'version_id':span.version_id,'stream_index':span.stream_index,'item_ids':[item.item_id],
|
|
28
|
+
'start_frame':item.start_frame,'end_frame':item.start_frame+item.duration_frames,'source_end':right}
|
|
29
|
+
runs.append(previous)
|
|
30
|
+
return {'duration_seconds':float(timeline.duration_frames/fps),
|
|
31
|
+
'source_runs':[{k:v for k,v in r.items() if k!='source_end'} |
|
|
32
|
+
{'duration_seconds':float((r['end_frame']-r['start_frame'])/fps)} for r in runs],
|
|
33
|
+
'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.'}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def caption_coverage(tools, speech):
|
|
37
|
+
from .production_media import load_text_styles
|
|
38
|
+
timeline=tools._timeline();styles=load_text_styles(tools.repository.projects,tools.project_id)
|
|
39
|
+
def words(text):
|
|
40
|
+
return ''.join(c.casefold() for c in unicodedata.normalize('NFKC',text) if unicodedata.category(c)[0] not in 'PZC')
|
|
41
|
+
rendered={}
|
|
42
|
+
for track in timeline.tracks:
|
|
43
|
+
if track.track_id!='agent-subtitles':continue
|
|
44
|
+
for item in track.items:
|
|
45
|
+
profile=styles.get(item.style_id,{})
|
|
46
|
+
key=(profile.get('anchor_item_id'),profile.get('cue_id'))
|
|
47
|
+
rendered.setdefault(key,[]).append(item)
|
|
48
|
+
missing=[]
|
|
49
|
+
for cue in speech['cues']:
|
|
50
|
+
expected=words(cue['text'])
|
|
51
|
+
if not expected:continue
|
|
52
|
+
pages=sorted(rendered.get((cue['item_id'],cue['cue_id']),[]),key=lambda i:i.start_frame)
|
|
53
|
+
actual=words(''.join(i.text for i in pages))
|
|
54
|
+
if actual!=expected:
|
|
55
|
+
missing.append({'item_id':cue['item_id'],'cue_id':cue['cue_id'],
|
|
56
|
+
'start_frame':cue['start_frame'],'duration_frames':cue['duration_frames']})
|
|
57
|
+
# A partially selected legacy ASR segment can disappear from cues entirely.
|
|
58
|
+
# It still needs repair unless a newer successful local job covered that cut.
|
|
59
|
+
with tools.repository.projects.connect(tools.project_id) as db:
|
|
60
|
+
local=[json.loads(r['result_json'])['source'] for r in db.execute(
|
|
61
|
+
"SELECT result_json FROM production_evidence_jobs WHERE run_id=? AND state='succeeded' AND kind IN ('transcribe','align')",(tools.run_id,))]
|
|
62
|
+
fps=Fraction(timeline.frame_rate.numerator,timeline.frame_rate.denominator)
|
|
63
|
+
def locally_analyzed(item):
|
|
64
|
+
span=item.source.span;unit=Fraction(span.time_base.numerator,span.time_base.denominator)
|
|
65
|
+
left,right=int(span.start_pts)*unit,int(span.end_pts)*unit
|
|
66
|
+
return any(s['version_id']==span.version_id and
|
|
67
|
+
int(s['start_pts'])*Fraction(s['time_base']['num'],s['time_base']['den'])<=left+1/fps and
|
|
68
|
+
int(s['end_pts'])*Fraction(s['time_base']['num'],s['time_base']['den'])>=right-1/fps for s in local)
|
|
69
|
+
shots={i.item_id:i for i in tools._video().items}
|
|
70
|
+
unresolved=sorted({v['item_id'] for v in speech['limitations'] if
|
|
71
|
+
(v.get('reason') in {'partial_utterance','partial_utterance_requires_alignment'} or v.get('partial'))
|
|
72
|
+
and v['item_id'] in shots and (v.get('reason')=='partial_utterance_requires_alignment' or not locally_analyzed(shots[v['item_id']]))})
|
|
73
|
+
return {'complete':not missing and not unresolved,'missing_cues':missing,'unresolved_item_ids':unresolved}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Durable user prompts, including older production and refinement requests."""
|
|
2
|
+
import json
|
|
3
|
+
import hashlib
|
|
4
|
+
from clipen.projects import ProjectError
|
|
5
|
+
from clipen.projects.models import validate_request_id
|
|
6
|
+
from clipen.projects.storage import utc_now
|
|
7
|
+
from .agent_models import bounded_text, encoded
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def save(repository, project_id, request_id, kind, text):
|
|
11
|
+
repository.projects.get_project(project_id)
|
|
12
|
+
request_id=validate_request_id(request_id)
|
|
13
|
+
if kind not in {'production','refinement'}:raise ProjectError('prompt_invalid','需求類型無效。',status_code=422)
|
|
14
|
+
text=bounded_text(text,'Prompt',8000)
|
|
15
|
+
identifier='prompt_'+hashlib.sha256(request_id.encode()).hexdigest()[:32]
|
|
16
|
+
value={'prompt_id':identifier,'kind':kind,'text':text,'source':'saved'}
|
|
17
|
+
with repository.projects.connect(project_id) as db:
|
|
18
|
+
db.execute('BEGIN IMMEDIATE')
|
|
19
|
+
prior=db.execute('SELECT payload_json,created_at FROM operation_events WHERE event_id=?',(identifier,)).fetchone()
|
|
20
|
+
if prior:
|
|
21
|
+
if json.loads(prior['payload_json'])!=value:raise ProjectError('request_reused','儲存識別已用於其他需求。',status_code=409)
|
|
22
|
+
return {**value,'created_at':prior['created_at']}
|
|
23
|
+
now=utc_now()
|
|
24
|
+
db.execute('INSERT INTO operation_events(event_id,project_id,operation_id,event_type,payload_json,created_at) VALUES(?,?,?,?,?,?)',(identifier,project_id,request_id,'production_prompt_saved',encoded(value),now))
|
|
25
|
+
db.commit()
|
|
26
|
+
return {**value,'created_at':now}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def history(repository, project_id=None, offset=0, limit=30):
|
|
30
|
+
if project_id:projects=[repository.projects.get_project(project_id)]
|
|
31
|
+
else:projects=repository.projects.list_projects()
|
|
32
|
+
entries=[]
|
|
33
|
+
for project in projects:
|
|
34
|
+
with repository.projects.connect(project.project_id) as db:
|
|
35
|
+
for row in db.execute('SELECT run_id,intent_json,created_at FROM production_sessions'):
|
|
36
|
+
intent=json.loads(row['intent_json'])
|
|
37
|
+
entries.append({'prompt_id':'initial-'+row['run_id'],'kind':'production','text':intent['brief'],'created_at':row['created_at'],'source':'submitted','run_id':row['run_id'],'target_duration_seconds':intent.get('target_duration_seconds')})
|
|
38
|
+
for row in db.execute("SELECT run_id,sequence,payload_json,created_at FROM edit_agent_events WHERE event_type='refinement_requested'"):
|
|
39
|
+
value=json.loads(row['payload_json'])
|
|
40
|
+
entries.append({'prompt_id':'revision-'+row['run_id']+'-'+str(row['sequence']),'kind':'refinement','text':value['instruction'],'references':value.get('references',{'version':0,'items':[]}),'created_at':row['created_at'],'source':'submitted','run_id':row['run_id']})
|
|
41
|
+
for row in db.execute("SELECT payload_json,created_at FROM operation_events WHERE event_type='production_prompt_saved'"):
|
|
42
|
+
entries.append({**json.loads(row['payload_json']),'created_at':row['created_at']})
|
|
43
|
+
# Enrich only entries from this project, never expose filesystem paths.
|
|
44
|
+
for entry in entries:
|
|
45
|
+
if 'project_id' not in entry:entry.update(project_id=project.project_id,project_name=project.name)
|
|
46
|
+
entries.sort(key=lambda e:(e['created_at'],e['prompt_id']),reverse=True)
|
|
47
|
+
return {'prompts':entries[offset:offset+limit],'total':len(entries),'offset':offset,'limit':limit}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Map existing post-production through local cuts instead of clearing it all."""
|
|
2
|
+
from dataclasses import replace
|
|
3
|
+
from fractions import Fraction
|
|
4
|
+
|
|
5
|
+
from clipen.domain import EffectRequest, TextClip
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def remap_cut(tools, items):
|
|
9
|
+
from .production_media import load_text_styles, atomic_json, text_style_path
|
|
10
|
+
from clipen.finishing.models import digest
|
|
11
|
+
timeline = tools._timeline()
|
|
12
|
+
old = list(tools._video().items)
|
|
13
|
+
old_by_id = {item.item_id: item for item in old}
|
|
14
|
+
fps = Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
|
|
15
|
+
cursor, clips, invalidated = 0, [], []
|
|
16
|
+
for index, item in enumerate(items):
|
|
17
|
+
previous = old_by_id.get(item.item_id)
|
|
18
|
+
effects = list(previous.effects if previous else item.effects)
|
|
19
|
+
changed = previous is not None and previous.source != item.source
|
|
20
|
+
if changed:
|
|
21
|
+
# Clip-local masks and transitions require explicit review if the
|
|
22
|
+
# visible source changes. Preserve source treatment and music.
|
|
23
|
+
unsafe = {"video.mosaic", "video.transition", "video.fade", "video.speed_ramp"}
|
|
24
|
+
invalidated += [{"item_id": item.item_id, "effect_id": e.effect_id,
|
|
25
|
+
"reason": "changed_source_requires_review"} for e in effects if e.effect_id in unsafe]
|
|
26
|
+
effects = [e for e in effects if e.effect_id not in unsafe]
|
|
27
|
+
if previous and any(e.effect_id == "video.transition" for e in effects):
|
|
28
|
+
before_old = old[old.index(previous)-1].item_id if old.index(previous) else None
|
|
29
|
+
before_new = items[index-1].item_id if index else None
|
|
30
|
+
if before_old != before_new:
|
|
31
|
+
effects = [e for e in effects if e.effect_id != "video.transition"]
|
|
32
|
+
invalidated.append({"item_id": item.item_id, "effect_id": "video.transition", "reason": "cut_changed"})
|
|
33
|
+
clips.append(replace(item, start_frame=cursor, effects=tuple(effects)))
|
|
34
|
+
cursor += item.duration_frames
|
|
35
|
+
for n, clip in enumerate(clips):
|
|
36
|
+
effects = []
|
|
37
|
+
for effect in clip.effects:
|
|
38
|
+
if effect.effect_id != "audio.layers":
|
|
39
|
+
effects.append(effect)
|
|
40
|
+
continue
|
|
41
|
+
layers = []
|
|
42
|
+
for layer in effect.parameters["layers"]:
|
|
43
|
+
remaining = cursor-clip.start_frame-layer["start_frame"]
|
|
44
|
+
if remaining <= 0:
|
|
45
|
+
invalidated.append({"layer_id": layer["layer_id"], "reason": "anchor_beyond_end"})
|
|
46
|
+
else:
|
|
47
|
+
layers.append({**layer, "duration_frames": min(layer["duration_frames"], remaining)})
|
|
48
|
+
if layers:
|
|
49
|
+
effects.append(EffectRequest("audio.layers", {"layers": layers}))
|
|
50
|
+
clips[n] = replace(clip, effects=tuple(effects))
|
|
51
|
+
styles = load_text_styles(tools.repository.projects, tools.project_id)
|
|
52
|
+
styles_changed = False
|
|
53
|
+
retained_tracks = [replace(tools._video(), items=tuple(clips))]
|
|
54
|
+
lanes = []
|
|
55
|
+
for track in timeline.tracks:
|
|
56
|
+
if track is tools._video() or track.track_id == tools._video().track_id:
|
|
57
|
+
continue
|
|
58
|
+
mapped = []
|
|
59
|
+
for element in track.items:
|
|
60
|
+
if not isinstance(element, TextClip):
|
|
61
|
+
invalidated.append({"item_id": element.item_id, "reason": "independent_track_needs_remapping"})
|
|
62
|
+
continue
|
|
63
|
+
profile = styles.get(element.style_id, {})
|
|
64
|
+
anchor = next((i for i in old if i.item_id == profile.get("anchor_item_id")), None)
|
|
65
|
+
if anchor is None:
|
|
66
|
+
anchor = next((i for i in old if i.start_frame <= element.start_frame
|
|
67
|
+
and element.start_frame+element.duration_frames <= i.start_frame+i.duration_frames), None)
|
|
68
|
+
if anchor is None:
|
|
69
|
+
invalidated.append({"item_id": element.item_id, "reason": "no_source_anchor"})
|
|
70
|
+
continue
|
|
71
|
+
# A graphic only needs its first frame on the footage; it may run on past the cut.
|
|
72
|
+
graphic = profile.get("kind") == "program_component"
|
|
73
|
+
span = anchor.source.span
|
|
74
|
+
unit = Fraction(span.time_base.numerator, span.time_base.denominator)
|
|
75
|
+
left = int(span.start_pts)*unit+Fraction(element.start_frame-anchor.start_frame, 1)/fps
|
|
76
|
+
right = left+Fraction(element.duration_frames, 1)/fps
|
|
77
|
+
# Prefer stable clip identity; split children can carry an element
|
|
78
|
+
# wholly contained in their source interval. Never duplicate it.
|
|
79
|
+
candidates = sorted(clips, key=lambda i: i.item_id != anchor.item_id)
|
|
80
|
+
target = next((i for i in candidates if i.source.span.version_id == span.version_id
|
|
81
|
+
and i.source.span.stream_index == span.stream_index
|
|
82
|
+
and (i.item_id == anchor.item_id or i.item_id not in old_by_id)
|
|
83
|
+
and int(i.source.span.start_pts)*unit <= left
|
|
84
|
+
and (left < int(i.source.span.end_pts)*unit if graphic else right <= int(i.source.span.end_pts)*unit)), None)
|
|
85
|
+
if target is None:
|
|
86
|
+
invalidated.append({"item_id": element.item_id, "reason": "source_removed_or_trimmed"})
|
|
87
|
+
continue
|
|
88
|
+
offset = round((left-int(target.source.span.start_pts)*unit)*fps)
|
|
89
|
+
style_id = element.style_id
|
|
90
|
+
if profile.get("kind") in {"program_component","program_subtitle"}:
|
|
91
|
+
updated = {**profile, "anchor_item_id": target.item_id}
|
|
92
|
+
if profile['kind']=='program_component':updated['start_offset_frames']=offset
|
|
93
|
+
style_id = ("agent.component." if profile['kind']=='program_component' else 'agent.text.')+digest(updated)[:24]
|
|
94
|
+
styles[style_id] = updated
|
|
95
|
+
styles_changed = True
|
|
96
|
+
start = target.start_frame+offset
|
|
97
|
+
length = min(element.duration_frames, cursor-start) if graphic else element.duration_frames
|
|
98
|
+
if length < 6:
|
|
99
|
+
invalidated.append({"item_id": element.item_id, "reason": "source_removed_or_trimmed"})
|
|
100
|
+
continue
|
|
101
|
+
mapped.append(replace(element, start_frame=start, duration_frames=length, style_id=style_id))
|
|
102
|
+
if track.track_id == "program-components" or track.track_id.startswith("program-components-"):
|
|
103
|
+
lanes.append(mapped)
|
|
104
|
+
elif mapped:
|
|
105
|
+
retained_tracks.append(replace(track, items=tuple(mapped)))
|
|
106
|
+
if styles_changed:
|
|
107
|
+
atomic_json(text_style_path(tools.repository.projects, tools.project_id), styles)
|
|
108
|
+
return replace(timeline, duration_frames=cursor, tracks=tuple(retained_tracks)+relane(lanes), markers=()), invalidated
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def relane(lanes):
|
|
112
|
+
"""Component lanes from lists of graphics. Graphics that run past a cut may meet others after a recut:
|
|
113
|
+
each keeps its lane while it fits, otherwise it moves to the first lane that is free at that time."""
|
|
114
|
+
from clipen.domain import Track, TrackKind
|
|
115
|
+
fits = lambda lane, item: all(i.start_frame+i.duration_frames <= item.start_frame or item.start_frame+item.duration_frames <= i.start_frame for i in lane)
|
|
116
|
+
placed, moved = [[] for _ in lanes], []
|
|
117
|
+
for n, items in enumerate(lanes):
|
|
118
|
+
for item in sorted(items, key=lambda i: i.start_frame):
|
|
119
|
+
(placed[n] if fits(placed[n], item) else moved).append(item)
|
|
120
|
+
for item in moved:
|
|
121
|
+
target = next((lane for lane in placed if fits(lane, item)), None)
|
|
122
|
+
if target is None:
|
|
123
|
+
target = []
|
|
124
|
+
placed.append(target)
|
|
125
|
+
target.append(item)
|
|
126
|
+
return tuple(Track("program-components" if n == 0 else f"program-components-{n+1}", TrackKind.TITLE,
|
|
127
|
+
tuple(sorted(lane, key=lambda i: i.start_frame))) for n, lane in enumerate([l for l in placed if l]))
|