@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,82 @@
|
|
|
1
|
+
"""Search current source speech before picking a cut; no synthetic event labels."""
|
|
2
|
+
from fractions import Fraction
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
from .production_media import source_rows
|
|
6
|
+
from .agent_models import ToolResult
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def search_dialogue(tools,args):
|
|
10
|
+
from .speech_quality import speech_flags
|
|
11
|
+
sources={}
|
|
12
|
+
for source in (tools._source_rows() if hasattr(tools,'_source_rows') else source_rows(tools.repository.projects,tools.project_id)):
|
|
13
|
+
if source['kind']=='video':sources.setdefault(source['version_id'],source)
|
|
14
|
+
query=args.get('query','').strip().casefold();version=args.get('version_id');drafts=args.get('include_drafts',False)
|
|
15
|
+
results=[];unreviewed=0;incomplete=0
|
|
16
|
+
with tools.repository.projects.connect(tools.project_id) as db:
|
|
17
|
+
rows=db.execute("SELECT tr.*,pi.review_required FROM current_preparation cp JOIN preparation_items pi ON pi.run_id=cp.run_id JOIN transcription_revisions tr ON tr.revision_id=pi.transcript_revision_id WHERE 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.version_id,tr.revision_id").fetchall()
|
|
18
|
+
seen=set()
|
|
19
|
+
for row in rows:
|
|
20
|
+
vid=row['version_id']
|
|
21
|
+
if vid not in sources or vid in seen or (version and version!=vid):continue
|
|
22
|
+
seen.add(vid);source=sources[vid]
|
|
23
|
+
annotation=db.execute('SELECT * FROM transcript_annotations WHERE version_id=? AND stream_index=? AND source_revision_id=?',(vid,row['stream_index'],row['revision_id'])).fetchone()
|
|
24
|
+
if annotation and annotation['discarded']:continue
|
|
25
|
+
pending=bool((row['review_required'] or row['status']=='needs_review') and not (annotation and annotation['confirmed']))
|
|
26
|
+
corrections={} if annotation is None else {str(c['ordinal']):c['text'] for c in json.loads(annotation['corrections_json'])}
|
|
27
|
+
segments=db.execute('SELECT * FROM transcript_segments WHERE revision_id=? ORDER BY ordinal',(row['revision_id'],)).fetchall()
|
|
28
|
+
tb=json.loads(row['source_span_json'])['time_base'];unit=Fraction(source['time_base']['num'],source['time_base']['den']);asr_unit=Fraction(tb['num'],tb['den'])
|
|
29
|
+
for n,seg in enumerate(segments):
|
|
30
|
+
text=corrections.get(str(seg['ordinal']),seg['text'])
|
|
31
|
+
if query and query not in text.casefold():continue
|
|
32
|
+
if pending and not drafts:unreviewed+=1;continue
|
|
33
|
+
left=int(seg['start_pts'])*asr_unit;right=int(seg['end_pts'])*asr_unit
|
|
34
|
+
if left<int(source['start_pts'])*unit-Fraction(1,30) or right>int(source['end_pts'])*unit+Fraction(1,30):
|
|
35
|
+
incomplete+=1;continue
|
|
36
|
+
# Audio sample tails may exceed the last video frame. Return
|
|
37
|
+
# an executable video span, plus the unchanged ASR timing.
|
|
38
|
+
start=max(int(source['start_pts']),math.floor(left/unit));end=min(int(source['end_pts']),math.ceil(right/unit))
|
|
39
|
+
if start>=end:continue
|
|
40
|
+
results.append({'version_id':vid,'display_name':source['display_name'],'source_revision_id':row['revision_id'],
|
|
41
|
+
'segment_id':seg['segment_id'],'text':text,'confidence':seg['confidence'],
|
|
42
|
+
'verification':'asr_draft' if pending else 'reviewed_source',
|
|
43
|
+
'quality_flags':speech_flags(text) if pending else [],
|
|
44
|
+
'start_offset_seconds':float((start-int(source['start_pts']))*unit),'duration_seconds':float((end-start)*unit),
|
|
45
|
+
'source':{'version_id':vid,'stream_index':source['stream_index'],'start_pts':str(start),'end_pts':str(end),'time_base':source['time_base']},
|
|
46
|
+
'asr_start_seconds':float(left),'asr_end_seconds':float(right),
|
|
47
|
+
'context':[{'segment_id':c['segment_id'],'text':corrections.get(str(c['ordinal']),c['text'])} for c in segments[max(0,n-1):n+2]]})
|
|
48
|
+
local_ranges=[]
|
|
49
|
+
jobs=[]
|
|
50
|
+
if hasattr(tools.repository,'production_session'):
|
|
51
|
+
with tools.repository.projects.connect(tools.project_id) as db:
|
|
52
|
+
jobs=db.execute("SELECT job_id,result_json FROM production_evidence_jobs WHERE run_id=? AND state='succeeded' AND kind IN ('transcribe','align') ORDER BY created_at DESC,rowid DESC",(tools.run_id,)).fetchall()
|
|
53
|
+
local_seen=set()
|
|
54
|
+
for job in jobs:
|
|
55
|
+
value=json.loads(job['result_json']);span=value['source'];vid=span['version_id']
|
|
56
|
+
if vid not in sources or (version and vid!=version):continue
|
|
57
|
+
source=sources[vid];unit=Fraction(source['time_base']['num'],source['time_base']['den'])
|
|
58
|
+
local_ranges.append(span)
|
|
59
|
+
for n,segment in enumerate(value['segments']):
|
|
60
|
+
text=segment['text'];left=value['source_start_seconds']+segment['start_seconds'];right=value['source_start_seconds']+segment['end_seconds']
|
|
61
|
+
identity=(vid,round(left,4),round(right,4))
|
|
62
|
+
if identity in local_seen:continue
|
|
63
|
+
local_seen.add(identity)
|
|
64
|
+
results=[r for r in results if not (r['version_id']==vid and abs(r['asr_start_seconds']-left)<.05 and abs(r['asr_end_seconds']-right)<.05)]
|
|
65
|
+
if query and query not in text.casefold():continue
|
|
66
|
+
if not drafts:unreviewed+=1;continue
|
|
67
|
+
results.append({'version_id':vid,'display_name':source['display_name'],'source_revision_id':job['job_id'],
|
|
68
|
+
'segment_id':str(n),'text':text,'confidence':None,'verification':'asr_draft','quality_flags':speech_flags(text),
|
|
69
|
+
'start_offset_seconds':left-float(int(source['start_pts'])*unit),'duration_seconds':right-left,
|
|
70
|
+
'source':{**span,'start_pts':str(round(left/float(unit))),'end_pts':str(round(right/float(unit)))},
|
|
71
|
+
'asr_start_seconds':left,'asr_end_seconds':right,
|
|
72
|
+
'context':[{'segment_id':str(i),'text':s['text']} for i,s in enumerate(value['segments'][max(0,n-1):n+2],max(0,n-1))]})
|
|
73
|
+
results.sort(key=lambda r:(r['display_name'],r['version_id'],r['start_offset_seconds']))
|
|
74
|
+
offset=args.get('offset',0);limit=args.get('limit',12)
|
|
75
|
+
return ToolResult({'utterances':results[offset:offset+limit],'total':len(results),'next_offset':offset+limit if offset+limit<len(results) else None,
|
|
76
|
+
'unreviewed_omitted':unreviewed,'incomplete_omitted':incomplete,
|
|
77
|
+
'coverage': {'video_sources': len(sources), 'sources_with_transcripts': len(seen|{r['version_id'] for r in local_ranges}),
|
|
78
|
+
'untranscribed_version_ids': sorted(set(sources)-seen-{r['version_id'] for r in local_ranges}),
|
|
79
|
+
'local_transcribed_ranges':local_ranges,
|
|
80
|
+
'limitations':'A source with transcripts may still have uncovered intervals; local ranges cover only their recorded source span.'},
|
|
81
|
+
'scope':'Inventoried authorized sources; only existing transcripts searched. Unknown footage is not evidence of absence. Text matches are not proof of event continuity.',
|
|
82
|
+
'next_step':'Choose a promising event, register_source_range around complete speech and nearby context, then inspect_candidates/sample_source.'})
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Explicit analyzed ranges for retained speech; no transcript match is not absence."""
|
|
2
|
+
from fractions import Fraction
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def speech_coverage(tools):
|
|
7
|
+
audio_versions={row['version_id'] for row in tools._source_rows() if row['kind']=='audio'}
|
|
8
|
+
ranges={}
|
|
9
|
+
with tools.repository.projects.connect(tools.project_id) as db:
|
|
10
|
+
local=db.execute("SELECT result_json FROM production_evidence_jobs WHERE run_id=? AND state='succeeded' AND kind IN ('transcribe','align')",(tools.run_id,)).fetchall()
|
|
11
|
+
legacy=db.execute("SELECT tr.source_span_json FROM current_preparation cp JOIN preparation_items pi ON pi.run_id=cp.run_id JOIN transcription_revisions tr ON tr.revision_id=pi.transcript_revision_id WHERE pi.status IN ('transcribed','no_speech') AND tr.status IN ('transcribed','needs_review','no_speech_detected')").fetchall()
|
|
12
|
+
spans=[json.loads(row['result_json'])['source'] for row in local]+[json.loads(row['source_span_json']) for row in legacy]
|
|
13
|
+
for span in spans:
|
|
14
|
+
unit=Fraction(span['time_base']['num'],span['time_base']['den'])
|
|
15
|
+
ranges.setdefault(span['version_id'],[]).append((int(span['start_pts'])*unit,int(span['end_pts'])*unit))
|
|
16
|
+
unknown=[]
|
|
17
|
+
fps=Fraction(tools._timeline().frame_rate.numerator,tools._timeline().frame_rate.denominator)
|
|
18
|
+
for clip in tools._video().items:
|
|
19
|
+
if clip.source.span.version_id not in audio_versions:continue
|
|
20
|
+
if any(e.effect_id=='audio.source' and e.parameters['mode']=='mute' for e in clip.effects):continue
|
|
21
|
+
span=clip.source.span;unit=Fraction(span.time_base.numerator,span.time_base.denominator)
|
|
22
|
+
left=int(span.start_pts)*unit;right=int(span.end_pts)*unit;cursor=left
|
|
23
|
+
for start,end in sorted(ranges.get(span.version_id,[])):
|
|
24
|
+
if end<=cursor:continue
|
|
25
|
+
if start>cursor+1/fps:break
|
|
26
|
+
cursor=max(cursor,end)
|
|
27
|
+
if cursor<right-1/fps:
|
|
28
|
+
unknown.append({'item_id':clip.item_id,'source':span.to_storage(),'unknown_from_seconds':float(cursor)})
|
|
29
|
+
return {'unknown_ranges':unknown,'complete':not unknown,
|
|
30
|
+
'scope':'Local transcription coverage only; ASR correctness, hearing and semantics are separate.'}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Durable mutation receipts; uncertain interrupted calls are never silently replayed."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
from clipen.projects import ProjectError
|
|
6
|
+
from clipen.projects.storage import utc_now
|
|
7
|
+
from .agent_models import ToolResult, bounded_text, encoded
|
|
8
|
+
|
|
9
|
+
TIMELINE_MUTATIONS = frozenset({
|
|
10
|
+
'replace_sequence','set_clip_effect','undo_revision','finish_edit',
|
|
11
|
+
'set_canvas','set_target_duration','replace_clip_source','replace_subtitles',
|
|
12
|
+
'remove_item','trim_clip','reorder_clips','split_clip','insert_clip',
|
|
13
|
+
'set_source_audio','set_color_grade','set_mosaic','set_transition','set_fade',
|
|
14
|
+
'remove_clip_effect','place_audio','remove_audio','restore_revision',
|
|
15
|
+
'remove_program_component','add_custom_component','update_custom_component',
|
|
16
|
+
'set_component_text','edit_component','set_component_look','edit_component_look',
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def begin_receipt(tools, name, arguments, expected_revision_id, mutation_id):
|
|
21
|
+
mutation_id=bounded_text(mutation_id,'操作識別',160)
|
|
22
|
+
argument_hash=hashlib.sha256(encoded({'arguments':arguments,'expected_revision_id':expected_revision_id}).encode()).hexdigest()
|
|
23
|
+
with tools.repository.projects.connect(tools.project_id) as db:
|
|
24
|
+
db.execute('BEGIN IMMEDIATE')
|
|
25
|
+
row=db.execute('SELECT * FROM production_tool_receipts WHERE run_id=? AND mutation_id=?',(tools.run_id,mutation_id)).fetchone()
|
|
26
|
+
if row:
|
|
27
|
+
if row['tool_name']!=name or row['arguments_hash']!=argument_hash:
|
|
28
|
+
raise ProjectError('request_reused','這個操作識別已用於其他參數。',status_code=409)
|
|
29
|
+
if row['state']=='started':
|
|
30
|
+
raise ProjectError('tool_outcome_unknown','先前操作在回報前中斷;請讀取目前版本與紀錄確認結果,不要直接重送。',status_code=409)
|
|
31
|
+
payload=json.loads(row['result_json'])
|
|
32
|
+
if row['state']=='failed':
|
|
33
|
+
raise ProjectError(payload['error'],payload['message'],status_code=409)
|
|
34
|
+
db.rollback()
|
|
35
|
+
return ToolResult({**payload,'replayed':True})
|
|
36
|
+
current=tools.repository._read_run(db,tools.run_id)
|
|
37
|
+
if expected_revision_id is not None and expected_revision_id!=current.current_revision_id:
|
|
38
|
+
raise ProjectError('revision_conflict','作品版本已更新,請重新讀取後修改。',status_code=409)
|
|
39
|
+
if current.state!='running' and not (getattr(tools,'_user_edit',False) and current.state not in {'queued','running'}):
|
|
40
|
+
raise ProjectError('edit_agent_not_running','AI 製作目前未在執行。',status_code=409)
|
|
41
|
+
db.execute('INSERT INTO production_tool_receipts VALUES(?,?,?,?,?,?,?)',
|
|
42
|
+
(tools.run_id,mutation_id,name,argument_hash,'started',None,utc_now()))
|
|
43
|
+
db.commit()
|
|
44
|
+
return None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def finish_receipt(tools, mutation_id, *, result=None, error=None):
|
|
48
|
+
payload=dict(result.payload) if error is None else {'error':getattr(error,'code','tool_failed'),
|
|
49
|
+
'message':getattr(error,'message','這次操作未完成,請查看作品版本與紀錄。')}
|
|
50
|
+
with tools.repository.projects.connect(tools.project_id) as db:
|
|
51
|
+
db.execute("UPDATE production_tool_receipts SET state=?,result_json=? WHERE run_id=? AND mutation_id=? AND state='started'",
|
|
52
|
+
('completed' if error is None else 'failed',encoded(payload),tools.run_id,mutation_id))
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Versions a person can return to: one per complete edit, not one per AI tool call.
|
|
2
|
+
|
|
3
|
+
The AI saves a revision after every small step (one caption, one label), and
|
|
4
|
+
those stay available for repair tools. People see a version when an AI request
|
|
5
|
+
ends (finished, or stopped part way with changes) and after each restore.
|
|
6
|
+
Projects from before review notes may also hold manual edits, still labelled below.
|
|
7
|
+
"""
|
|
8
|
+
import json
|
|
9
|
+
import sqlite3
|
|
10
|
+
|
|
11
|
+
from clipen.provider_registry import get_provider
|
|
12
|
+
|
|
13
|
+
_STOPS = {'provider_failed', 'run_cancelled', 'run_interrupted', 'budget_exhausted'}
|
|
14
|
+
_STOP_REASONS = {
|
|
15
|
+
'provider_usage_limit': '額度不足時停下', 'provider_timed_out': '超過時間上限時停下',
|
|
16
|
+
'provider_authentication_required': '登入過期時停下', 'provider_stopped_early': 'AI 提早結束',
|
|
17
|
+
'delivery_blocked': '交付檢查未通過', 'provider_network_error': '連線中斷時停下',
|
|
18
|
+
}
|
|
19
|
+
# Labels for manual edits: rewording a graphic now, and the edits earlier Clipen versions allowed.
|
|
20
|
+
_MANUAL = {'edit_text': '文字與時間', 'configure_text_style': '文字外觀', 'remove_item': '刪除元素', 'trim_clip': '裁切片段',
|
|
21
|
+
'reorder_clips': '重排片段', 'split_clip': '分割片段', 'replace_clip_source': '替換來源', 'insert_clip': '插入片段',
|
|
22
|
+
'set_source_audio': '原音', 'set_color_grade': '調色', 'set_mosaic': '馬賽克', 'set_transition': '轉場',
|
|
23
|
+
'set_fade': '淡入淡出', 'remove_clip_effect': '移除效果', 'place_audio': '音樂與音效', 'remove_audio': '移除聲音',
|
|
24
|
+
'remove_program_component': '移除節目元件',
|
|
25
|
+
'add_custom_component': '新增自由設計元件', 'update_custom_component': '修改自由設計元件',
|
|
26
|
+
'set_component_text': '元件文字', 'edit_component': '修改元件', 'edit_component_look': '元件外觀'}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _name(provider_id):
|
|
30
|
+
try:
|
|
31
|
+
return get_provider(provider_id).display_name
|
|
32
|
+
except ValueError:
|
|
33
|
+
return 'AI'
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def versions(database, run_id, provider, styles=None, current=None):
|
|
37
|
+
"""Versions of one film, newest first, each saying what changed. `provider` is the run's current AI;
|
|
38
|
+
`current` the revision the film is at now, which is always the newest entry."""
|
|
39
|
+
rows = database.execute(
|
|
40
|
+
"SELECT sequence,event_type,payload_json,created_at FROM edit_agent_events WHERE run_id=? AND event_type IN "
|
|
41
|
+
"('run_created','refinement_requested','revision_created','revision_selected','run_finished','provider_failed','run_cancelled',"
|
|
42
|
+
"'run_interrupted','budget_exhausted','tool_completed','provider_switched','provider_finished') ORDER BY sequence", (run_id,)).fetchall()
|
|
43
|
+
switches = [json.loads(r['payload_json']) for r in rows if r['event_type'] == 'provider_switched']
|
|
44
|
+
current_ai = switches[0]['from'] if switches else provider
|
|
45
|
+
latest = start = None
|
|
46
|
+
request = None
|
|
47
|
+
sent = {}
|
|
48
|
+
result = []
|
|
49
|
+
|
|
50
|
+
skipped = []
|
|
51
|
+
# Tokens an AI attempt used, waiting for the version that attempt produced.
|
|
52
|
+
pending, last_ai, span = None, None, 0
|
|
53
|
+
|
|
54
|
+
def add(kind, label, created_at, detail=None):
|
|
55
|
+
nonlocal pending, last_ai
|
|
56
|
+
if latest is None or (result and result[-1]['revision_id'] == latest):
|
|
57
|
+
if latest is not None:
|
|
58
|
+
skipped.append((kind, label, created_at))
|
|
59
|
+
return
|
|
60
|
+
entry = {'revision_id': latest, 'kind': kind, 'label': label, 'detail': detail, 'created_at': created_at}
|
|
61
|
+
if kind.startswith('ai_'):
|
|
62
|
+
entry['usage'], pending, last_ai = pending, None, (entry, span)
|
|
63
|
+
result.append(entry)
|
|
64
|
+
|
|
65
|
+
for row in rows:
|
|
66
|
+
kind, payload = row['event_type'], json.loads(row['payload_json'])
|
|
67
|
+
usage = payload.get('usage') if kind in ('provider_finished', 'provider_failed') else None
|
|
68
|
+
if isinstance(usage, dict):
|
|
69
|
+
# A finished attempt reports after its version is listed; a stopped one before.
|
|
70
|
+
if kind == 'provider_finished' and last_ai is not None and last_ai[1] == span:
|
|
71
|
+
last_ai[0]['usage'] = add_usage(last_ai[0]['usage'], usage)
|
|
72
|
+
else:
|
|
73
|
+
pending = add_usage(pending, usage)
|
|
74
|
+
if kind in ('run_created', 'refinement_requested'):
|
|
75
|
+
# An attempt that changed nothing has no version to show it; it still counts in the film's total.
|
|
76
|
+
span, pending = span + 1, None
|
|
77
|
+
if kind in ('revision_created', 'revision_selected'):
|
|
78
|
+
latest = payload.get('revision_id', latest)
|
|
79
|
+
if start is None:
|
|
80
|
+
start = latest
|
|
81
|
+
elif kind == 'run_created':
|
|
82
|
+
request, start, sent = None, latest, {}
|
|
83
|
+
elif kind == 'refinement_requested':
|
|
84
|
+
request, start = payload.get('instruction'), payload.get('base_revision_id', latest)
|
|
85
|
+
sent = {item.get('reference_id'): item for item in (payload.get('references') or {}).get('items', []) if isinstance(item, dict)}
|
|
86
|
+
elif kind == 'provider_switched':
|
|
87
|
+
current_ai = payload.get('to', current_ai)
|
|
88
|
+
elif kind == 'run_finished':
|
|
89
|
+
add('ai_complete', f'{_name(current_ai)} {"打磨" if request else "製作"}完成', row['created_at'], request)
|
|
90
|
+
if result and result[-1]['revision_id'] == latest:
|
|
91
|
+
result[-1]['report'] = _report(payload, sent)
|
|
92
|
+
start = latest
|
|
93
|
+
elif kind in _STOPS:
|
|
94
|
+
# A stop that changed nothing is not a version.
|
|
95
|
+
if latest != start:
|
|
96
|
+
reason = _STOP_REASONS.get(payload.get('error_code'), '製作中斷')
|
|
97
|
+
add('ai_partial', f'{_name(current_ai)} 未完成({reason})', row['created_at'], request)
|
|
98
|
+
start = latest
|
|
99
|
+
elif kind == 'tool_completed' and payload.get('authority') == 'user':
|
|
100
|
+
tool = payload.get('tool')
|
|
101
|
+
add('restore' if tool == 'restore_revision' else 'manual',
|
|
102
|
+
'還原版本' if tool == 'restore_revision' else f'手動修改:{_MANUAL.get(tool, "編輯")}', row['created_at'])
|
|
103
|
+
start = latest
|
|
104
|
+
# Older projects did not record a step that went back to an earlier picture; show where the film is now.
|
|
105
|
+
if current and result and result[-1]['revision_id'] != current and skipped:
|
|
106
|
+
kind, label, created_at = skipped[-1]
|
|
107
|
+
result.append({'revision_id': current, 'kind': kind, 'label': label, 'detail': None, 'created_at': created_at})
|
|
108
|
+
_describe(database, run_id, result, styles or {})
|
|
109
|
+
for number, entry in enumerate(result, 1):
|
|
110
|
+
entry['number'] = number
|
|
111
|
+
return list(reversed(result))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _report(payload, sent):
|
|
115
|
+
"""What the AI said it changed, with each answer placed next to the note it answers."""
|
|
116
|
+
from .change_report import OUTCOMES
|
|
117
|
+
report = payload.get('report') or {}
|
|
118
|
+
notes = [{**note, 'outcome_label': OUTCOMES.get(note.get('outcome'), ''), 'kind': (sent.get(note.get('reference_id')) or {}).get('kind'),
|
|
119
|
+
'note': (sent.get(note.get('reference_id')) or {}).get('note', '')} for note in report.get('notes', [])]
|
|
120
|
+
from .change_report import REASONS
|
|
121
|
+
# Reports written before reasons were required hold plain lines.
|
|
122
|
+
left = [{'what': item, 'reason': None, 'reason_label': '', 'detail': ''} if isinstance(item, str)
|
|
123
|
+
else {**item, 'reason_label': REASONS.get(item.get('reason'), '')} for item in report.get('not_done', [])]
|
|
124
|
+
for note in notes:
|
|
125
|
+
note['reason_label'] = REASONS.get(note.get('reason'), '')
|
|
126
|
+
return {'summary': payload.get('summary') or '', 'changes': report.get('changes', []), 'notes': notes, 'not_done': left}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def add_usage(total, usage):
|
|
130
|
+
keys = ('input_tokens', 'cached_input_tokens', 'output_tokens')
|
|
131
|
+
if not isinstance(usage, dict) or not all(isinstance(usage.get(k), int) for k in keys):
|
|
132
|
+
return total
|
|
133
|
+
return {k: (total or {}).get(k, 0) + usage[k] for k in keys}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def film_usage(database, run_id):
|
|
137
|
+
"""Every token the AI used on this film, including attempts that changed nothing."""
|
|
138
|
+
total = None
|
|
139
|
+
for row in database.execute("SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type IN ('provider_finished','provider_failed')", (run_id,)):
|
|
140
|
+
total = add_usage(total, json.loads(row['payload_json']).get('usage'))
|
|
141
|
+
return total
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _describe(database, run_id, result, styles):
|
|
145
|
+
"""What each version changed from the one before it, and which moment a restore went back to."""
|
|
146
|
+
from .history_changes import describe, summary
|
|
147
|
+
ids = sorted({entry['revision_id'] for entry in result})
|
|
148
|
+
payloads = {}
|
|
149
|
+
try:
|
|
150
|
+
for start in range(0, len(ids), 400):
|
|
151
|
+
chunk = ids[start:start+400]
|
|
152
|
+
for row in database.execute(f"SELECT revision_id,payload_json FROM edit_agent_revisions WHERE run_id=? AND revision_id IN ({','.join('?'*len(chunk))})", (run_id, *chunk)):
|
|
153
|
+
payloads[row['revision_id']] = json.loads(row['payload_json'])
|
|
154
|
+
except sqlite3.OperationalError:
|
|
155
|
+
pass # Without stored pictures the history still lists every step, only without what changed.
|
|
156
|
+
for index, entry in enumerate(result):
|
|
157
|
+
earlier = next((e for e in reversed(result[:index]) if e['revision_id'] == entry['revision_id']), None)
|
|
158
|
+
if entry['kind'] == 'restore' and earlier is not None:
|
|
159
|
+
entry['restored_from'] = earlier['created_at']
|
|
160
|
+
before, after = (payloads.get(result[index-1]['revision_id']) if index else None), payloads.get(entry['revision_id'])
|
|
161
|
+
entry['changes'] = summary(describe(before, after, styles)) if before and after else None
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""One-frame editing canvas using real source pixels and native text renderers.
|
|
2
|
+
|
|
3
|
+
This is a static editing view, not approval of transitions, motion or sound.
|
|
4
|
+
"""
|
|
5
|
+
import base64
|
|
6
|
+
from dataclasses import replace
|
|
7
|
+
from fractions import Fraction
|
|
8
|
+
from io import BytesIO
|
|
9
|
+
import math
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import tempfile
|
|
12
|
+
import threading
|
|
13
|
+
from PIL import Image, ImageDraw, ImageFont
|
|
14
|
+
from clipen.domain import TrackKind, EffectRequest
|
|
15
|
+
from clipen.media import MediaPreviewRepository
|
|
16
|
+
from clipen.projects import ProjectError
|
|
17
|
+
from clipen.finishing.audio import run_process
|
|
18
|
+
from clipen.rendering.renderer import FfmpegPreviewRenderer
|
|
19
|
+
from clipen.rendering.production_effects import grade_filters
|
|
20
|
+
from clipen.rendering.titles import TitleCardRenderer, TitleRenderError
|
|
21
|
+
from .production_media import load_text_styles
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def frame(repository, project_id, run_id, expected_revision_id, frame_number, component=None):
|
|
25
|
+
"""One still of the current version.
|
|
26
|
+
|
|
27
|
+
component ({element_id, ...unsaved settings}) draws that graphic as the person's changes would
|
|
28
|
+
leave it, and the result says where it sits so the page can let them drag it."""
|
|
29
|
+
revision=repository.current_revision(project_id,run_id);timeline=revision.timeline
|
|
30
|
+
if revision.revision_id!=expected_revision_id:raise ProjectError('revision_conflict','影片已更新,正在重新讀取編輯畫面。',status_code=409)
|
|
31
|
+
if isinstance(frame_number,bool) or not isinstance(frame_number,int) or not 0<=frame_number<timeline.duration_frames:
|
|
32
|
+
raise ProjectError('frame_invalid','預覽時間不在影片內。',status_code=422)
|
|
33
|
+
items=[i for t in timeline.tracks if t.kind is TrackKind.TITLE for i in t.items]
|
|
34
|
+
styles=load_text_styles(repository.projects,project_id)
|
|
35
|
+
draft=profile=None
|
|
36
|
+
if component is not None:
|
|
37
|
+
from .workbench import tools_for
|
|
38
|
+
draft,profile,_=tools_for(repository,project_id,run_id)._component_draft(component)
|
|
39
|
+
styles={**styles,draft.style_id:profile}
|
|
40
|
+
items=[draft if i.item_id==draft.item_id else i for i in items]
|
|
41
|
+
clip=next((i for t in timeline.tracks if t.kind is TrackKind.VIDEO for i in t.items if i.start_frame<=frame_number<i.start_frame+i.duration_frames),None)
|
|
42
|
+
if clip is None:raise ProjectError('frame_invalid','這個時間沒有畫面片段。',status_code=422)
|
|
43
|
+
fps=Fraction(timeline.frame_rate.numerator,timeline.frame_rate.denominator)
|
|
44
|
+
relative=frame_number-clip.start_frame
|
|
45
|
+
span=clip.source.span;unit=Fraction(span.time_base.numerator,span.time_base.denominator)
|
|
46
|
+
duration=span.duration_pts*unit
|
|
47
|
+
elapsed=Fraction(relative,1)/fps
|
|
48
|
+
speed=FfmpegPreviewRenderer._speed_profile(clip)
|
|
49
|
+
if speed:
|
|
50
|
+
outside,center=speed;first=float(duration)*.4/outside;middle=float(duration)*.2/center;t=float(elapsed)
|
|
51
|
+
elapsed=Fraction(str(t*outside if t<first else float(duration)*.4+(t-first)*center if t<first+middle else float(duration)*.6+(t-first-middle)*outside))
|
|
52
|
+
seconds=int(span.start_pts)*unit+min(max(Fraction(0),elapsed),max(Fraction(0),duration-Fraction(1,1)/fps))
|
|
53
|
+
media=MediaPreviewRepository(repository.projects);source=media.open(project_id,span.version_id)
|
|
54
|
+
try:
|
|
55
|
+
if span.stream_index not in source.video_stream_indices:raise ProjectError('frame_invalid','來源沒有指定的影像串流。',status_code=422)
|
|
56
|
+
effects=[]
|
|
57
|
+
for effect in clip.effects:
|
|
58
|
+
if effect.effect_id=='video.slow_push':
|
|
59
|
+
p=effect.parameters;scale=p.get('scale_from',1)+(p.get('scale_to',1.08)-p.get('scale_from',1))*relative/max(1,clip.duration_frames-1)
|
|
60
|
+
effects.append(EffectRequest('video.punch_in',{'scale':scale,'center_x':.5,'center_y':.5}))
|
|
61
|
+
else:effects.append(effect)
|
|
62
|
+
still_clip=replace(clip,effects=tuple(effects))
|
|
63
|
+
filters=f'scale={timeline.width}:{timeline.height}:force_original_aspect_ratio=decrease,pad={timeline.width}:{timeline.height}:(ow-iw)/2:(oh-ih)/2'
|
|
64
|
+
filters+=FfmpegPreviewRenderer._video_effect_filters(still_clip,timeline)+grade_filters(clip)
|
|
65
|
+
with tempfile.TemporaryDirectory(prefix='clipen-edit-frame-') as temporary:
|
|
66
|
+
output=Path(temporary)/'source.png'
|
|
67
|
+
run_process(['ffmpeg','-v','error','-nostdin','-seek_timestamp','1','-ss',f'{float(seconds):.9f}','-i',f'/dev/fd/{source.descriptor}','-map',f'0:{span.stream_index}','-frames:v','1','-vf',filters,'-threads','1',str(output)],threading.Event(),pass_fds=(source.descriptor,),timeout=30)
|
|
68
|
+
with Image.open(output) as pixels:image=pixels.convert('RGBA')
|
|
69
|
+
finally:source.close()
|
|
70
|
+
# Match the native mosaic geometry for this exact instant.
|
|
71
|
+
for effect in clip.effects:
|
|
72
|
+
if effect.effect_id!='video.mosaic':continue
|
|
73
|
+
for region in effect.parameters['regions']:
|
|
74
|
+
if not region['start_frame']<=relative<region['start_frame']+region['duration_frames']:continue
|
|
75
|
+
width=max(2,min(timeline.width,round(timeline.width*region['width'])//2*2));height=max(2,min(timeline.height,round(timeline.height*region['height'])//2*2))
|
|
76
|
+
x=min(timeline.width-width,round(timeline.width*region['x'])//2*2);y=min(timeline.height-height,round(timeline.height*region['y'])//2*2)
|
|
77
|
+
pixels=image.crop((x,y,x+width,y+height));pixels=pixels.resize((max(1,math.ceil(width/region['block_size'])),max(1,math.ceil(height/region['block_size']))),Image.Resampling.BOX).resize((width,height),Image.Resampling.NEAREST);image.paste(pixels,(x,y))
|
|
78
|
+
font=TitleCardRenderer._font_path()
|
|
79
|
+
if font is None:raise ProjectError('preview_title_font_missing','找不到預覽字型。',status_code=422)
|
|
80
|
+
overlay=Image.new('RGBA',image.size,(0,0,0,0));draw=ImageDraw.Draw(overlay);renderer=TitleCardRenderer(styles)
|
|
81
|
+
try:
|
|
82
|
+
for item in items:
|
|
83
|
+
if item.start_frame<=frame_number<item.start_frame+item.duration_frames:
|
|
84
|
+
renderer._draw_card(draw,ImageFont,font,timeline,item,frame_number-item.start_frame)
|
|
85
|
+
except TitleRenderError as error:raise ProjectError(error.code,'文字超出版面或無法顯示,請縮短文字或調整位置。',status_code=422) from error
|
|
86
|
+
box=None
|
|
87
|
+
if draft is not None and draft.start_frame<=frame_number<draft.start_frame+draft.duration_frames:
|
|
88
|
+
from clipen.rendering.program_components import component_bounds
|
|
89
|
+
left,top,right,bottom=component_bounds(draw,font,timeline,draft,profile)[0]
|
|
90
|
+
box={'x':left/timeline.width,'y':top/timeline.height,'width':(right-left)/timeline.width,'height':(bottom-top)/timeline.height}
|
|
91
|
+
image=Image.alpha_composite(image,overlay).convert('RGB');image.thumbnail((960,960))
|
|
92
|
+
encoded=BytesIO();image.save(encoded,format='JPEG',quality=88)
|
|
93
|
+
return {'revision_id':revision.revision_id,'frame':frame_number,'source_item_id':clip.item_id,'image_data_url':'data:image/jpeg;base64,'+base64.b64encode(encoded.getvalue()).decode(),'scope':'editing_still','component_box':box}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""The review workbench: read the current film, restore a version, reword graphics, render and export it."""
|
|
2
|
+
import threading
|
|
3
|
+
import json
|
|
4
|
+
from clipen.projects import ProjectError, DirectoryReference, DirectoryRole
|
|
5
|
+
from clipen.projects.storage import utc_now
|
|
6
|
+
from .agent_tools import EditAgentTools
|
|
7
|
+
from .production_media import AgentAudioStore
|
|
8
|
+
from .refinement_references import public_state, sent
|
|
9
|
+
|
|
10
|
+
# Changes go through review notes to the AI; the user picks which version is current and edits graphics directly.
|
|
11
|
+
USER_TOOLS = frozenset({'restore_revision','set_component_text','edit_component','edit_component_look','remove_program_component'})
|
|
12
|
+
|
|
13
|
+
def idle(repository, project_id, run_id):
|
|
14
|
+
run=repository.get(project_id,run_id)
|
|
15
|
+
latest=repository.latest(project_id)
|
|
16
|
+
if latest is None or latest.run_id!=run_id or run.state in {'queued','running'}:
|
|
17
|
+
raise ProjectError('edit_agent_busy','請先停止 AI 製作,再還原或輸出目前版本。',status_code=409)
|
|
18
|
+
if repository.production_session(project_id,run_id) is None:
|
|
19
|
+
raise ProjectError('production_required','這個版本不是可編輯的影片製作。',status_code=409)
|
|
20
|
+
return run
|
|
21
|
+
|
|
22
|
+
def tools_for(repository, project_id, run_id):
|
|
23
|
+
tools=EditAgentTools(repository,project_id,run_id)
|
|
24
|
+
tools._user_edit=True
|
|
25
|
+
return tools
|
|
26
|
+
|
|
27
|
+
def state(repository, project_id, run_id):
|
|
28
|
+
revision=repository.current_revision(project_id,run_id)
|
|
29
|
+
from .versions import film_usage, versions
|
|
30
|
+
with repository.projects.connect(project_id) as db:
|
|
31
|
+
# One entry per complete edit; the AI's per-step revisions stay internal.
|
|
32
|
+
from .production_media import load_text_styles
|
|
33
|
+
history=versions(db,run_id,repository.get(project_id,run_id).provider,load_text_styles(repository.projects,project_id),revision.revision_id)
|
|
34
|
+
usage=film_usage(db,run_id)
|
|
35
|
+
for version in history:
|
|
36
|
+
row=db.execute('SELECT payload_json FROM edit_agent_revisions WHERE revision_id=? AND run_id=?',(version['revision_id'],run_id)).fetchone()
|
|
37
|
+
if row:
|
|
38
|
+
value=json.loads(row['payload_json']);rate=value['frame_rate']
|
|
39
|
+
version['duration_seconds']=value['duration_frames']*rate['den']/rate['num']
|
|
40
|
+
preview=db.execute("SELECT render_id FROM preview_renders WHERE timeline_id=? AND state='succeeded' ORDER BY created_at DESC LIMIT 1",(version['revision_id'],)).fetchone()
|
|
41
|
+
version['preview_url']=f"/api/projects/{project_id}/preview/{preview['render_id']}/media" if preview else None
|
|
42
|
+
intent=(repository.production_session(project_id,run_id) or {}).get('intent',{})
|
|
43
|
+
try:editing=tools_for(repository,project_id,run_id)._component_editing()
|
|
44
|
+
except (ProjectError,KeyError,StopIteration):editing={'components':{},'visual_styles':[],'font_styles':[]}
|
|
45
|
+
return {'revision':revision.to_public(include_timeline=True),'component_editing':editing,'history':history,'ai_usage':usage,'references':public_state(intent,revision.timeline),'sent_notes':sent(intent),'audio_assets':AgentAudioStore(repository.projects,project_id).public_assets()}
|
|
46
|
+
|
|
47
|
+
def edit(repository, project_id, run_id, name, arguments, expected, mutation_id):
|
|
48
|
+
idle(repository,project_id,run_id)
|
|
49
|
+
if name not in USER_TOOLS:
|
|
50
|
+
raise ProjectError('tool_not_allowed','請用審片注記交給 AI 修改;這裡只能還原版本或編輯元件。',status_code=422)
|
|
51
|
+
tools=tools_for(repository,project_id,run_id)
|
|
52
|
+
try:
|
|
53
|
+
result=tools.call(name,{**arguments,'expected_revision_id':expected,'mutation_id':mutation_id})
|
|
54
|
+
return result.payload
|
|
55
|
+
finally:tools.close_production()
|
|
56
|
+
|
|
57
|
+
def import_music(repository, project_id, path, display_name):
|
|
58
|
+
from clipen.finishing.audio import inspect_library
|
|
59
|
+
store=AgentAudioStore(repository.projects,project_id)
|
|
60
|
+
directory=path.parent;info=directory.stat()
|
|
61
|
+
reference=DirectoryReference(DirectoryRole.SOURCE,str(directory),directory.name,'使用者指定配樂',info.st_dev,info.st_ino,utc_now()).to_storage()
|
|
62
|
+
assets,issues=inspect_library('music',reference,threading.Event(),lambda _:None)
|
|
63
|
+
if len(assets)!=1:
|
|
64
|
+
raise ProjectError('music_invalid','音樂檔無法解碼或沒有可用聲音。',status_code=422)
|
|
65
|
+
asset=assets[0];asset['name']=display_name
|
|
66
|
+
asset['provenance']={'source':'user_upload','title':display_name,'license':'user_supplied','rights_verified':False,'attribution':'使用者提供;系統未驗證授權。','changes':'將依剪輯需要截取、調整音量及淡入淡出。'}
|
|
67
|
+
store.add(assets,reference)
|
|
68
|
+
return next(a for a in store.public_assets() if a['asset_id']==asset['asset_id'])
|
|
69
|
+
|
|
70
|
+
def music_choice(repository, project_id, asset_id):
|
|
71
|
+
if asset_id is None:return None
|
|
72
|
+
asset=next((a for a in AgentAudioStore(repository.projects,project_id).public_assets() if a['asset_id']==asset_id and a['role']=='music'),None)
|
|
73
|
+
if asset is None:raise ProjectError('music_missing','指定的配樂不在本作品,請重新選擇。',status_code=422)
|
|
74
|
+
return {'mode':'user','asset_id':asset_id,'name':asset['name']}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Filesystem helpers that also work on user-selected non-POSIX volumes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def restrict_permissions(path: Path, mode: int) -> None:
|
|
10
|
+
"""Apply POSIX privacy bits, or verify access when the volume lacks them."""
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
os.chmod(path, mode)
|
|
14
|
+
return
|
|
15
|
+
except OSError:
|
|
16
|
+
pass
|
|
17
|
+
if path.is_symlink() or not path.exists():
|
|
18
|
+
raise OSError(f"unsafe managed path: {path}")
|
|
19
|
+
required = os.R_OK
|
|
20
|
+
if mode & 0o200:
|
|
21
|
+
required |= os.W_OK
|
|
22
|
+
if path.is_dir():
|
|
23
|
+
required |= os.X_OK
|
|
24
|
+
if not os.access(path, required):
|
|
25
|
+
raise OSError(f"managed path permissions unavailable: {path}")
|