@clipen/clipen-cli 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +60 -50
  2. package/package.json +7 -4
  3. package/pyproject.toml +18 -2
  4. package/requirements/dev.txt +2 -0
  5. package/src/clipen/__init__.py +1 -1
  6. package/src/clipen/analysis/__init__.py +7 -7
  7. package/src/clipen/analysis/artifacts.py +4 -10
  8. package/src/clipen/analysis/audio.py +10 -8
  9. package/src/clipen/analysis/evidence_service.py +345 -167
  10. package/src/clipen/analysis/image_similarity.py +5 -14
  11. package/src/clipen/analysis/keyframes.py +5 -17
  12. package/src/clipen/analysis/models.py +5 -7
  13. package/src/clipen/analysis/qwen_worker.py +19 -54
  14. package/src/clipen/analysis/resources.py +2 -1
  15. package/src/clipen/analysis/runtime.py +1 -3
  16. package/src/clipen/analysis/service.py +16 -48
  17. package/src/clipen/analysis/setup.py +11 -25
  18. package/src/clipen/analysis/setup_cli.py +5 -15
  19. package/src/clipen/analysis/storage.py +96 -278
  20. package/src/clipen/analysis/transcription.py +40 -82
  21. package/src/clipen/analysis/visual.py +109 -48
  22. package/src/clipen/annotations/__init__.py +5 -2
  23. package/src/clipen/annotations/models.py +1 -1
  24. package/src/clipen/annotations/storage.py +132 -84
  25. package/src/clipen/annotations/suggestions.py +3 -8
  26. package/src/clipen/asr_release.py +4 -11
  27. package/src/clipen/bootstrap.py +65 -54
  28. package/src/clipen/{planning/models.py → candidates.py} +29 -47
  29. package/src/clipen/cli.py +2 -2
  30. package/src/clipen/controller/app.py +401 -214
  31. package/src/clipen/controller/server.py +28 -38
  32. package/src/clipen/domain/__init__.py +1 -1
  33. package/src/clipen/domain/media_time.py +3 -10
  34. package/src/clipen/domain/timeline.py +45 -47
  35. package/src/clipen/domain/validation.py +0 -1
  36. package/src/clipen/editing/__init__.py +1 -1
  37. package/src/clipen/editing/agent_models.py +4 -11
  38. package/src/clipen/editing/agent_repository.py +391 -170
  39. package/src/clipen/editing/agent_tools.py +180 -99
  40. package/src/clipen/editing/alignment.py +92 -52
  41. package/src/clipen/editing/alignment_setup.py +118 -70
  42. package/src/clipen/editing/alignment_worker.py +11 -9
  43. package/src/clipen/editing/change_report.py +95 -38
  44. package/src/clipen/editing/compiler.py +0 -1
  45. package/src/clipen/editing/component_looks.py +58 -34
  46. package/src/clipen/editing/component_review.py +34 -38
  47. package/src/clipen/editing/coordinator.py +213 -90
  48. package/src/clipen/editing/editorial_review.py +217 -95
  49. package/src/clipen/editing/evidence_jobs.py +457 -200
  50. package/src/clipen/editing/history_changes.py +129 -68
  51. package/src/clipen/editing/music_choices.py +8 -5
  52. package/src/clipen/editing/production_catalog.py +573 -136
  53. package/src/clipen/editing/production_limits.py +43 -17
  54. package/src/clipen/editing/production_media.py +376 -167
  55. package/src/clipen/editing/production_preview.py +322 -129
  56. package/src/clipen/editing/production_progress.py +164 -69
  57. package/src/clipen/editing/production_requirements.py +106 -39
  58. package/src/clipen/editing/production_tools.py +1064 -462
  59. package/src/clipen/editing/program_audio.py +211 -81
  60. package/src/clipen/editing/program_direction.py +59 -25
  61. package/src/clipen/editing/program_story.py +83 -45
  62. package/src/clipen/editing/program_subtitles.py +194 -96
  63. package/src/clipen/editing/programme_review.py +98 -50
  64. package/src/clipen/editing/prompt_history.py +64 -27
  65. package/src/clipen/editing/recut.py +65 -25
  66. package/src/clipen/editing/refinement_references.py +176 -86
  67. package/src/clipen/editing/resolve_export.py +449 -218
  68. package/src/clipen/editing/resolve_titles.py +162 -105
  69. package/src/clipen/editing/skill_tools.py +530 -154
  70. package/src/clipen/editing/source_dialogue.py +177 -67
  71. package/src/clipen/editing/speech_coverage.py +42 -22
  72. package/src/clipen/editing/speech_quality.py +6 -1
  73. package/src/clipen/editing/tool_receipts.py +78 -32
  74. package/src/clipen/editing/versions.py +122 -64
  75. package/src/clipen/editing/visual_preview.py +157 -61
  76. package/src/clipen/editing/workbench.py +104 -42
  77. package/src/clipen/finishing/audio.py +69 -30
  78. package/src/clipen/finishing/catalog.py +176 -93
  79. package/src/clipen/finishing/models.py +1 -1
  80. package/src/clipen/finishing/renderer.py +33 -14
  81. package/src/clipen/mcp_editing/__main__.py +3 -1
  82. package/src/clipen/mcp_editing/server.py +77 -34
  83. package/src/clipen/media/__init__.py +3 -3
  84. package/src/clipen/media/discovery.py +7 -20
  85. package/src/clipen/media/models.py +7 -18
  86. package/src/clipen/media/preview.py +14 -24
  87. package/src/clipen/media/probe.py +16 -44
  88. package/src/clipen/media/service.py +6 -19
  89. package/src/clipen/media/storage.py +33 -81
  90. package/src/clipen/music_vocabulary.py +33 -4
  91. package/src/clipen/power.py +8 -3
  92. package/src/clipen/projects/__init__.py +1 -1
  93. package/src/clipen/projects/deletion.py +19 -32
  94. package/src/clipen/projects/finishing_schema.py +3 -1
  95. package/src/clipen/projects/models.py +2 -5
  96. package/src/clipen/projects/picker.py +13 -37
  97. package/src/clipen/projects/service.py +8 -24
  98. package/src/clipen/projects/storage.py +226 -246
  99. package/src/clipen/provider_registry.py +4 -2
  100. package/src/clipen/providers/account.py +86 -35
  101. package/src/clipen/providers/claude.py +59 -25
  102. package/src/clipen/providers/claude_editing.py +14 -7
  103. package/src/clipen/providers/codex.py +73 -118
  104. package/src/clipen/providers/codex_editing.py +2 -2
  105. package/src/clipen/providers/editing_agent.py +19 -17
  106. package/src/clipen/providers/recovery.py +7 -8
  107. package/src/clipen/rendering/cover.py +18 -5
  108. package/src/clipen/rendering/custom_components.py +167 -79
  109. package/src/clipen/rendering/custom_render.py +62 -41
  110. package/src/clipen/rendering/production_effects.py +77 -45
  111. package/src/clipen/rendering/program_components.py +134 -73
  112. package/src/clipen/rendering/program_creator.py +432 -277
  113. package/src/clipen/rendering/program_identities.py +277 -182
  114. package/src/clipen/rendering/program_motion.py +140 -95
  115. package/src/clipen/rendering/program_studio.py +175 -116
  116. package/src/clipen/rendering/program_styles.py +231 -145
  117. package/src/clipen/rendering/program_subtitles.py +71 -34
  118. package/src/clipen/rendering/renderer.py +150 -121
  119. package/src/clipen/rendering/storage.py +9 -22
  120. package/src/clipen/rendering/titles.py +193 -86
  121. package/src/clipen/skills/__init__.py +1 -0
  122. package/src/clipen/skills/catalog.py +151 -55
  123. package/src/clipen/skills/library.py +13 -7
  124. package/src/clipen/skills/package.py +46 -23
  125. package/src/clipen/skills/visual_styles.py +29 -18
  126. package/src/clipen/workspace.py +15 -44
  127. package/src/clipen/planning/__init__.py +0 -9
@@ -1,47 +1,84 @@
1
1
  """Durable user prompts, including older production and refinement requests."""
2
- import json
2
+
3
3
  import hashlib
4
+ import json
5
+
4
6
  from clipen.projects import ProjectError
5
7
  from clipen.projects.models import validate_request_id
6
8
  from clipen.projects.storage import utc_now
9
+
7
10
  from .agent_models import bounded_text, encoded
8
11
 
9
12
 
10
13
  def save(repository, project_id, request_id, kind, text):
11
14
  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'}
15
+ request_id = validate_request_id(request_id)
16
+ if kind not in {"production", "refinement"}:
17
+ raise ProjectError("prompt_invalid", "需求類型無效。", status_code=422)
18
+ text = bounded_text(text, "Prompt", 8000)
19
+ identifier = "prompt_" + hashlib.sha256(request_id.encode()).hexdigest()[:32]
20
+ value = {"prompt_id": identifier, "kind": kind, "text": text, "source": "saved"}
17
21
  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()
22
+ db.execute("BEGIN IMMEDIATE")
23
+ prior = db.execute(
24
+ "SELECT payload_json,created_at FROM operation_events WHERE event_id=?", (identifier,)
25
+ ).fetchone()
20
26
  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))
27
+ if json.loads(prior["payload_json"]) != value:
28
+ raise ProjectError("request_reused", "儲存識別已用於其他需求。", status_code=409)
29
+ return {**value, "created_at": prior["created_at"]}
30
+ now = utc_now()
31
+ db.execute(
32
+ "INSERT INTO operation_events(event_id,project_id,operation_id,event_type,payload_json,created_at) VALUES(?,?,?,?,?,?)",
33
+ (identifier, project_id, request_id, "production_prompt_saved", encoded(value), now),
34
+ )
25
35
  db.commit()
26
- return {**value,'created_at':now}
36
+ return {**value, "created_at": now}
27
37
 
28
38
 
29
39
  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=[]
40
+ if project_id:
41
+ projects = [repository.projects.get_project(project_id)]
42
+ else:
43
+ projects = repository.projects.list_projects()
44
+ entries = []
33
45
  for project in projects:
34
46
  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']})
47
+ for row in db.execute("SELECT run_id,intent_json,created_at FROM production_sessions"):
48
+ intent = json.loads(row["intent_json"])
49
+ entries.append(
50
+ {
51
+ "prompt_id": "initial-" + row["run_id"],
52
+ "kind": "production",
53
+ "text": intent["brief"],
54
+ "created_at": row["created_at"],
55
+ "source": "submitted",
56
+ "run_id": row["run_id"],
57
+ "target_duration_seconds": intent.get("target_duration_seconds"),
58
+ }
59
+ )
60
+ for row in db.execute(
61
+ "SELECT run_id,sequence,payload_json,created_at FROM edit_agent_events WHERE event_type='refinement_requested'"
62
+ ):
63
+ value = json.loads(row["payload_json"])
64
+ entries.append(
65
+ {
66
+ "prompt_id": "revision-" + row["run_id"] + "-" + str(row["sequence"]),
67
+ "kind": "refinement",
68
+ "text": value["instruction"],
69
+ "references": value.get("references", {"version": 0, "items": []}),
70
+ "created_at": row["created_at"],
71
+ "source": "submitted",
72
+ "run_id": row["run_id"],
73
+ }
74
+ )
75
+ for row in db.execute(
76
+ "SELECT payload_json,created_at FROM operation_events WHERE event_type='production_prompt_saved'"
77
+ ):
78
+ entries.append({**json.loads(row["payload_json"]), "created_at": row["created_at"]})
43
79
  # Enrich only entries from this project, never expose filesystem paths.
44
80
  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}
81
+ if "project_id" not in entry:
82
+ entry.update(project_id=project.project_id, project_name=project.name)
83
+ entries.sort(key=lambda e: (e["created_at"], e["prompt_id"]), reverse=True)
84
+ return {"prompts": entries[offset : offset + limit], "total": len(entries), "offset": offset, "limit": limit}
@@ -1,4 +1,5 @@
1
1
  """Map existing post-production through local cuts instead of clearing it all."""
2
+
2
3
  from dataclasses import replace
3
4
  from fractions import Fraction
4
5
 
@@ -6,8 +7,10 @@ from clipen.domain import EffectRequest, TextClip
6
7
 
7
8
 
8
9
  def remap_cut(tools, items):
9
- from .production_media import load_text_styles, atomic_json, text_style_path
10
10
  from clipen.finishing.models import digest
11
+
12
+ from .production_media import atomic_json, load_text_styles, text_style_path
13
+
11
14
  timeline = tools._timeline()
12
15
  old = list(tools._video().items)
13
16
  old_by_id = {item.item_id: item for item in old}
@@ -21,12 +24,15 @@ def remap_cut(tools, items):
21
24
  # Clip-local masks and transitions require explicit review if the
22
25
  # visible source changes. Preserve source treatment and music.
23
26
  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]
27
+ invalidated += [
28
+ {"item_id": item.item_id, "effect_id": e.effect_id, "reason": "changed_source_requires_review"}
29
+ for e in effects
30
+ if e.effect_id in unsafe
31
+ ]
26
32
  effects = [e for e in effects if e.effect_id not in unsafe]
27
33
  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
34
+ before_old = old[old.index(previous) - 1].item_id if old.index(previous) else None
35
+ before_new = items[index - 1].item_id if index else None
30
36
  if before_old != before_new:
31
37
  effects = [e for e in effects if e.effect_id != "video.transition"]
32
38
  invalidated.append({"item_id": item.item_id, "effect_id": "video.transition", "reason": "cut_changed"})
@@ -40,7 +46,7 @@ def remap_cut(tools, items):
40
46
  continue
41
47
  layers = []
42
48
  for layer in effect.parameters["layers"]:
43
- remaining = cursor-clip.start_frame-layer["start_frame"]
49
+ remaining = cursor - clip.start_frame - layer["start_frame"]
44
50
  if remaining <= 0:
45
51
  invalidated.append({"layer_id": layer["layer_id"], "reason": "anchor_beyond_end"})
46
52
  else:
@@ -63,8 +69,15 @@ def remap_cut(tools, items):
63
69
  profile = styles.get(element.style_id, {})
64
70
  anchor = next((i for i in old if i.item_id == profile.get("anchor_item_id")), None)
65
71
  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)
72
+ anchor = next(
73
+ (
74
+ i
75
+ for i in old
76
+ if i.start_frame <= element.start_frame
77
+ and element.start_frame + element.duration_frames <= i.start_frame + i.duration_frames
78
+ ),
79
+ None,
80
+ )
68
81
  if anchor is None:
69
82
  invalidated.append({"item_id": element.item_id, "reason": "no_source_anchor"})
70
83
  continue
@@ -72,29 +85,43 @@ def remap_cut(tools, items):
72
85
  graphic = profile.get("kind") == "program_component"
73
86
  span = anchor.source.span
74
87
  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
88
+ left = int(span.start_pts) * unit + Fraction(element.start_frame - anchor.start_frame, 1) / fps
89
+ right = left + Fraction(element.duration_frames, 1) / fps
77
90
  # Prefer stable clip identity; split children can carry an element
78
91
  # wholly contained in their source interval. Never duplicate it.
79
92
  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)
93
+ target = next(
94
+ (
95
+ i
96
+ for i in candidates
97
+ if i.source.span.version_id == span.version_id
98
+ and i.source.span.stream_index == span.stream_index
99
+ and (i.item_id == anchor.item_id or i.item_id not in old_by_id)
100
+ and int(i.source.span.start_pts) * unit <= left
101
+ and (
102
+ left < int(i.source.span.end_pts) * unit
103
+ if graphic
104
+ else right <= int(i.source.span.end_pts) * unit
105
+ )
106
+ ),
107
+ None,
108
+ )
85
109
  if target is None:
86
110
  invalidated.append({"item_id": element.item_id, "reason": "source_removed_or_trimmed"})
87
111
  continue
88
- offset = round((left-int(target.source.span.start_pts)*unit)*fps)
112
+ offset = round((left - int(target.source.span.start_pts) * unit) * fps)
89
113
  style_id = element.style_id
90
- if profile.get("kind") in {"program_component","program_subtitle"}:
114
+ if profile.get("kind") in {"program_component", "program_subtitle"}:
91
115
  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]
116
+ if profile["kind"] == "program_component":
117
+ updated["start_offset_frames"] = offset
118
+ style_id = ("agent.component." if profile["kind"] == "program_component" else "agent.text.") + digest(
119
+ updated
120
+ )[:24]
94
121
  styles[style_id] = updated
95
122
  styles_changed = True
96
- start = target.start_frame+offset
97
- length = min(element.duration_frames, cursor-start) if graphic else element.duration_frames
123
+ start = target.start_frame + offset
124
+ length = min(element.duration_frames, cursor - start) if graphic else element.duration_frames
98
125
  if length < 6:
99
126
  invalidated.append({"item_id": element.item_id, "reason": "source_removed_or_trimmed"})
100
127
  continue
@@ -105,14 +132,21 @@ def remap_cut(tools, items):
105
132
  retained_tracks.append(replace(track, items=tuple(mapped)))
106
133
  if styles_changed:
107
134
  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
135
+ return replace(
136
+ timeline, duration_frames=cursor, tracks=tuple(retained_tracks) + relane(lanes), markers=()
137
+ ), invalidated
109
138
 
110
139
 
111
140
  def relane(lanes):
112
141
  """Component lanes from lists of graphics. Graphics that run past a cut may meet others after a recut:
113
142
  each keeps its lane while it fits, otherwise it moves to the first lane that is free at that time."""
114
143
  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)
144
+
145
+ fits = lambda lane, item: all(
146
+ i.start_frame + i.duration_frames <= item.start_frame
147
+ or item.start_frame + item.duration_frames <= i.start_frame
148
+ for i in lane
149
+ )
116
150
  placed, moved = [[] for _ in lanes], []
117
151
  for n, items in enumerate(lanes):
118
152
  for item in sorted(items, key=lambda i: i.start_frame):
@@ -123,5 +157,11 @@ def relane(lanes):
123
157
  target = []
124
158
  placed.append(target)
125
159
  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]))
160
+ return tuple(
161
+ Track(
162
+ "program-components" if n == 0 else f"program-components-{n + 1}",
163
+ TrackKind.TITLE,
164
+ tuple(sorted(lane, key=lambda i: i.start_frame)),
165
+ )
166
+ for n, lane in enumerate([l for l in placed if l])
167
+ )
@@ -5,25 +5,27 @@ the range it covers inside one shot, and optionally the caption or programme
5
5
  component they pointed at. Location facts stay for later rounds; every other
6
6
  note belongs to the round it was sent with.
7
7
  """
8
+
8
9
  import hashlib
9
10
  import json
10
11
  import math
11
12
  from fractions import Fraction
13
+
12
14
  from clipen.domain import TrackKind
13
15
  from clipen.projects import ProjectError
14
16
  from clipen.projects.models import validate_request_id
15
17
  from clipen.projects.storage import command_digest, utc_now
16
18
  from clipen.rendering.renderer import FfmpegPreviewRenderer
17
- from .agent_models import bounded_text, encoded
18
19
 
20
+ from .agent_models import bounded_text, encoded
19
21
 
20
- KINDS = {'change','remove','keep','highlight','location','audio','note'}
21
- LASTING = {'location'}
22
- _OPTIONAL = {'source_gain_db','fill_music','audio_layer_id','at_offset_frames','explicit_range','element_id'}
22
+ KINDS = {"change", "remove", "keep", "highlight", "location", "audio", "note"}
23
+ LASTING = {"location"}
24
+ _OPTIONAL = {"source_gain_db", "fill_music", "audio_layer_id", "at_offset_frames", "explicit_range", "element_id"}
23
25
 
24
26
 
25
27
  def references(intent):
26
- return intent.get('user_references', {'version': 0, 'items': []})
28
+ return intent.get("user_references", {"version": 0, "items": []})
27
29
 
28
30
 
29
31
  def source_pts(clip, fps, offset):
@@ -52,137 +54,225 @@ def locate(reference, timeline):
52
54
  if track.kind is not TrackKind.VIDEO:
53
55
  continue
54
56
  for clip in track.items:
55
- if clip.item_id == reference['item_id'] and clip.source.to_payload() == reference['clip_source'] and clip.duration_frames == reference['clip_duration_frames'] and timeline.frame_rate.to_storage() == reference['frame_rate'] and list(FfmpegPreviewRenderer._speed_profile(clip) or ()) == reference['speed_profile']:
56
- layer = reference.get('audio_layer_id')
57
- if layer and not any(l['layer_id'] == layer for effect in clip.effects if effect.effect_id == 'audio.layers' for l in effect.parameters['layers']):
57
+ if (
58
+ clip.item_id == reference["item_id"]
59
+ and clip.source.to_payload() == reference["clip_source"]
60
+ and clip.duration_frames == reference["clip_duration_frames"]
61
+ and timeline.frame_rate.to_storage() == reference["frame_rate"]
62
+ and list(FfmpegPreviewRenderer._speed_profile(clip) or ()) == reference["speed_profile"]
63
+ ):
64
+ layer = reference.get("audio_layer_id")
65
+ if layer and not any(
66
+ l["layer_id"] == layer
67
+ for effect in clip.effects
68
+ if effect.effect_id == "audio.layers"
69
+ for l in effect.parameters["layers"]
70
+ ):
58
71
  return None
59
- located = {'item_id': clip.item_id, 'start_frame': clip.start_frame + reference['start_offset_frames'], 'duration_frames': reference['duration_frames'],
60
- 'at_frame': clip.start_frame + reference.get('at_offset_frames', reference['start_offset_frames'])}
61
- element = reference.get('element_id')
72
+ located = {
73
+ "item_id": clip.item_id,
74
+ "start_frame": clip.start_frame + reference["start_offset_frames"],
75
+ "duration_frames": reference["duration_frames"],
76
+ "at_frame": clip.start_frame + reference.get("at_offset_frames", reference["start_offset_frames"]),
77
+ }
78
+ element = reference.get("element_id")
62
79
  if element:
63
- located['element_present'] = any(item.item_id == element for t in timeline.tracks for item in t.items)
80
+ located["element_present"] = any(
81
+ item.item_id == element for t in timeline.tracks for item in t.items
82
+ )
64
83
  return located
65
84
  return None
66
85
 
67
86
 
68
87
  def sent(intent):
69
88
  """What the last revision request handed to the AI, for review."""
70
- request = intent.get('latest_revision_request')
89
+ request = intent.get("latest_revision_request")
71
90
  if not request:
72
91
  return None
73
- return {'instruction': request.get('instruction'), 'created_at': request.get('created_at'), 'items': request.get('references', {}).get('items', [])}
92
+ return {
93
+ "instruction": request.get("instruction"),
94
+ "created_at": request.get("created_at"),
95
+ "items": request.get("references", {}).get("items", []),
96
+ }
74
97
 
75
98
 
76
99
  def hand_over(intent):
77
100
  """Close the round: only lasting facts stay for the next one."""
78
101
  state = references(intent)
79
- kept = [item for item in state['items'] if item['kind'] in LASTING]
80
- if len(kept) != len(state['items']):
81
- intent['user_references'] = {'version': state['version'] + 1, 'items': kept}
102
+ kept = [item for item in state["items"] if item["kind"] in LASTING]
103
+ if len(kept) != len(state["items"]):
104
+ intent["user_references"] = {"version": state["version"] + 1, "items": kept}
82
105
 
83
106
 
84
107
  def public_state(intent, timeline):
85
108
  state = references(intent)
86
- return {**state, 'items': [{**item, 'current_range': locate(item, timeline)} for item in state['items']]}
109
+ return {**state, "items": [{**item, "current_range": locate(item, timeline)} for item in state["items"]]}
87
110
 
88
111
 
89
- def update(repository, project_id, run_id, expected_revision_id, expected_version, mutation_id, reference=None, delete_id=None):
112
+ def update(
113
+ repository, project_id, run_id, expected_revision_id, expected_version, mutation_id, reference=None, delete_id=None
114
+ ):
90
115
  run_id = repository._validate_run_id(run_id)
91
116
  mutation_id = validate_request_id(mutation_id)
92
117
  if isinstance(expected_version, bool) or not isinstance(expected_version, int) or expected_version < 0:
93
- raise ProjectError('reference_invalid', '參考註記版本無效。', status_code=422)
118
+ raise ProjectError("reference_invalid", "參考註記版本無效。", status_code=422)
94
119
  if (reference is None) == (delete_id is None):
95
- raise ProjectError('reference_invalid', '請指定一筆要儲存或刪除的註記。', status_code=422)
96
- request_hash = command_digest({'run_id':run_id,'revision':expected_revision_id,'version':expected_version,'reference':reference,'delete_id':delete_id})
97
- event_id = 'reference_' + hashlib.sha256(mutation_id.encode()).hexdigest()[:32]
120
+ raise ProjectError("reference_invalid", "請指定一筆要儲存或刪除的註記。", status_code=422)
121
+ request_hash = command_digest(
122
+ {
123
+ "run_id": run_id,
124
+ "revision": expected_revision_id,
125
+ "version": expected_version,
126
+ "reference": reference,
127
+ "delete_id": delete_id,
128
+ }
129
+ )
130
+ event_id = "reference_" + hashlib.sha256(mutation_id.encode()).hexdigest()[:32]
98
131
  with repository.projects.connect(project_id) as db:
99
- db.execute('BEGIN IMMEDIATE')
100
- prior = db.execute('SELECT payload_json FROM operation_events WHERE event_id=?', (event_id,)).fetchone()
132
+ db.execute("BEGIN IMMEDIATE")
133
+ prior = db.execute("SELECT payload_json FROM operation_events WHERE event_id=?", (event_id,)).fetchone()
101
134
  if prior:
102
- payload = json.loads(prior['payload_json'])
103
- if payload['request_hash'] != request_hash:
104
- raise ProjectError('request_reused', '操作識別已用於其他註記。', status_code=409)
105
- return payload['result']
135
+ payload = json.loads(prior["payload_json"])
136
+ if payload["request_hash"] != request_hash:
137
+ raise ProjectError("request_reused", "操作識別已用於其他註記。", status_code=409)
138
+ return payload["result"]
106
139
  run = repository._read_run(db, run_id)
107
- latest = db.execute('SELECT run_id FROM edit_agent_runs ORDER BY created_at DESC,rowid DESC LIMIT 1').fetchone()
108
- if latest['run_id'] != run_id or db.execute("SELECT 1 FROM edit_agent_runs WHERE state IN ('queued','running')").fetchone():
109
- raise ProjectError('edit_agent_busy', '請先停止 AI 製作,再修改參考註記。', status_code=409)
140
+ latest = db.execute("SELECT run_id FROM edit_agent_runs ORDER BY created_at DESC,rowid DESC LIMIT 1").fetchone()
141
+ if (
142
+ latest["run_id"] != run_id
143
+ or db.execute("SELECT 1 FROM edit_agent_runs WHERE state IN ('queued','running')").fetchone()
144
+ ):
145
+ raise ProjectError("edit_agent_busy", "請先停止 AI 製作,再修改參考註記。", status_code=409)
110
146
  if run.current_revision_id != expected_revision_id:
111
- raise ProjectError('revision_conflict', '影片已更新,請重新讀取後標記。', status_code=409)
112
- row = db.execute('SELECT intent_json FROM production_sessions WHERE run_id=?', (run_id,)).fetchone()
147
+ raise ProjectError("revision_conflict", "影片已更新,請重新讀取後標記。", status_code=409)
148
+ row = db.execute("SELECT intent_json FROM production_sessions WHERE run_id=?", (run_id,)).fetchone()
113
149
  if row is None:
114
- raise ProjectError('production_required', '這個版本不支援參考註記。', status_code=422)
115
- intent = json.loads(row['intent_json']); state = references(intent)
116
- if state['version'] != expected_version:
117
- raise ProjectError('reference_conflict', '註記已在其他視窗更新,請重新讀取後再修改。', status_code=409)
150
+ raise ProjectError("production_required", "這個版本不支援參考註記。", status_code=422)
151
+ intent = json.loads(row["intent_json"])
152
+ state = references(intent)
153
+ if state["version"] != expected_version:
154
+ raise ProjectError("reference_conflict", "註記已在其他視窗更新,請重新讀取後再修改。", status_code=409)
118
155
  revision = repository._read_revision(db, run.current_revision_id)
119
- items = list(state['items'])
156
+ items = list(state["items"])
120
157
  if delete_id is not None:
121
- if not isinstance(delete_id, str) or not any(item['reference_id'] == delete_id for item in items):
122
- raise ProjectError('reference_not_found', '找不到這筆註記。', status_code=404)
123
- items = [item for item in items if item['reference_id'] != delete_id]
158
+ if not isinstance(delete_id, str) or not any(item["reference_id"] == delete_id for item in items):
159
+ raise ProjectError("reference_not_found", "找不到這筆註記。", status_code=404)
160
+ items = [item for item in items if item["reference_id"] != delete_id]
124
161
  else:
125
162
  item = normalize(reference, revision)
126
- old = next((r for r in items if r['reference_id'] == item['reference_id']), None)
163
+ old = next((r for r in items if r["reference_id"] == item["reference_id"]), None)
127
164
  if old:
128
- items = [item if r['reference_id'] == item['reference_id'] else r for r in items]
165
+ items = [item if r["reference_id"] == item["reference_id"] else r for r in items]
129
166
  else:
130
167
  if len(items) >= 100:
131
- raise ProjectError('reference_limit', '每支影片最多保留 100 筆參考註記。', status_code=422)
168
+ raise ProjectError("reference_limit", "每支影片最多保留 100 筆參考註記。", status_code=422)
132
169
  items.append(item)
133
- intent['user_references'] = {'version':state['version'] + 1, 'items':items}
134
- db.execute('UPDATE production_sessions SET intent_json=? WHERE run_id=?', (encoded(intent),run_id))
170
+ intent["user_references"] = {"version": state["version"] + 1, "items": items}
171
+ db.execute("UPDATE production_sessions SET intent_json=? WHERE run_id=?", (encoded(intent), run_id))
135
172
  result = public_state(intent, revision.timeline)
136
- payload = {'authority':'user','run_id':run_id,'request_hash':request_hash,'result':result}
137
- db.execute('INSERT INTO operation_events(event_id,project_id,operation_id,event_type,payload_json,created_at) VALUES(?,?,?,?,?,?)', (event_id,project_id,mutation_id,'production_reference_changed',encoded(payload),utc_now()))
173
+ payload = {"authority": "user", "run_id": run_id, "request_hash": request_hash, "result": result}
174
+ db.execute(
175
+ "INSERT INTO operation_events(event_id,project_id,operation_id,event_type,payload_json,created_at) VALUES(?,?,?,?,?,?)",
176
+ (event_id, project_id, mutation_id, "production_reference_changed", encoded(payload), utc_now()),
177
+ )
138
178
  db.commit()
139
179
  return result
140
180
 
141
181
 
142
182
  def normalize(value, revision):
143
- required = {'reference_id','kind','item_id','start_offset_frames','duration_frames','note'}
183
+ required = {"reference_id", "kind", "item_id", "start_offset_frames", "duration_frames", "note"}
144
184
  if not isinstance(value, dict) or not required <= value.keys() or value.keys() - required - _OPTIONAL:
145
- raise ProjectError('reference_invalid', '參考註記欄位無效。', status_code=422)
146
- identifier = validate_request_id(value['reference_id'])
147
- kind = value['kind']
185
+ raise ProjectError("reference_invalid", "參考註記欄位無效。", status_code=422)
186
+ identifier = validate_request_id(value["reference_id"])
187
+ kind = value["kind"]
148
188
  if not isinstance(kind, str) or kind not in KINDS:
149
- raise ProjectError('reference_invalid', '請選擇註記類型。', status_code=422)
189
+ raise ProjectError("reference_invalid", "請選擇註記類型。", status_code=422)
150
190
  # "Remove this" and "this is fine" say enough on their own.
151
- note = bounded_text(value['note'], '參考說明', 2000, empty=kind in {'remove','keep'})
152
- clip = next((item for track in revision.timeline.tracks if track.kind is TrackKind.VIDEO for item in track.items if item.item_id == value['item_id']), None)
191
+ note = bounded_text(value["note"], "參考說明", 2000, empty=kind in {"remove", "keep"})
192
+ clip = next(
193
+ (
194
+ item
195
+ for track in revision.timeline.tracks
196
+ if track.kind is TrackKind.VIDEO
197
+ for item in track.items
198
+ if item.item_id == value["item_id"]
199
+ ),
200
+ None,
201
+ )
153
202
  if clip is None:
154
- raise ProjectError('reference_invalid', '請選擇這支影片中的畫面片段。', status_code=422)
155
- start, length = value['start_offset_frames'], value['duration_frames']
156
- if any(isinstance(v,bool) or not isinstance(v,int) for v in (start,length)) or start < 0 or length < 1 or start + length > clip.duration_frames:
157
- raise ProjectError('reference_invalid', '標記範圍必須在選定片段內。', status_code=422)
158
- at = value.get('at_offset_frames', start)
159
- if isinstance(at,bool) or not isinstance(at,int) or not start <= at < start + length:
160
- raise ProjectError('reference_invalid', '標記的時間點必須在範圍內。', status_code=422)
161
- if not isinstance(value.get('explicit_range', False), bool):
162
- raise ProjectError('reference_invalid', '參考註記欄位無效。', status_code=422)
163
- item = {k:value[k] for k in required}
164
- item.update(at_offset_frames=at, explicit_range=value.get('explicit_range', False))
165
- if value.get('element_id') is not None:
166
- element_id = value['element_id']
167
- found = next(((t,i) for t in revision.timeline.tracks for i in t.items if i.item_id == element_id), None) if isinstance(element_id,str) else None
203
+ raise ProjectError("reference_invalid", "請選擇這支影片中的畫面片段。", status_code=422)
204
+ start, length = value["start_offset_frames"], value["duration_frames"]
205
+ if (
206
+ any(isinstance(v, bool) or not isinstance(v, int) for v in (start, length))
207
+ or start < 0
208
+ or length < 1
209
+ or start + length > clip.duration_frames
210
+ ):
211
+ raise ProjectError("reference_invalid", "標記範圍必須在選定片段內。", status_code=422)
212
+ at = value.get("at_offset_frames", start)
213
+ if isinstance(at, bool) or not isinstance(at, int) or not start <= at < start + length:
214
+ raise ProjectError("reference_invalid", "標記的時間點必須在範圍內。", status_code=422)
215
+ if not isinstance(value.get("explicit_range", False), bool):
216
+ raise ProjectError("reference_invalid", "參考註記欄位無效。", status_code=422)
217
+ item = {k: value[k] for k in required}
218
+ item.update(at_offset_frames=at, explicit_range=value.get("explicit_range", False))
219
+ if value.get("element_id") is not None:
220
+ element_id = value["element_id"]
221
+ found = (
222
+ next(((t, i) for t in revision.timeline.tracks for i in t.items if i.item_id == element_id), None)
223
+ if isinstance(element_id, str)
224
+ else None
225
+ )
168
226
  begin = clip.start_frame + start
169
- if found is None or found[1].start_frame >= begin + length or found[1].start_frame + found[1].duration_frames <= begin:
170
- raise ProjectError('reference_invalid', '指定的字幕或元件不在這段時間。', status_code=422)
227
+ if (
228
+ found is None
229
+ or found[1].start_frame >= begin + length
230
+ or found[1].start_frame + found[1].duration_frames <= begin
231
+ ):
232
+ raise ProjectError("reference_invalid", "指定的字幕或元件不在這段時間。", status_code=422)
171
233
  track, element = found
172
- item.update(element_id=element_id, element_track=track.track_id, element_text=(getattr(element,'text',None) or '')[:120] or None)
173
- item.update(reference_id=identifier,note=note,authority='user',base_revision_id=revision.revision_id,clip_source=clip.source.to_payload(),clip_duration_frames=clip.duration_frames,frame_rate=revision.timeline.frame_rate.to_storage(),speed_profile=list(FfmpegPreviewRenderer._speed_profile(clip) or ()))
234
+ item.update(
235
+ element_id=element_id,
236
+ element_track=track.track_id,
237
+ element_text=(getattr(element, "text", None) or "")[:120] or None,
238
+ )
239
+ item.update(
240
+ reference_id=identifier,
241
+ note=note,
242
+ authority="user",
243
+ base_revision_id=revision.revision_id,
244
+ clip_source=clip.source.to_payload(),
245
+ clip_duration_frames=clip.duration_frames,
246
+ frame_rate=revision.timeline.frame_rate.to_storage(),
247
+ speed_profile=list(FfmpegPreviewRenderer._speed_profile(clip) or ()),
248
+ )
174
249
  fps = Fraction(revision.timeline.frame_rate.numerator, revision.timeline.frame_rate.denominator)
175
- item['source_range'] = {**clip.source.span.to_storage(), 'start_pts':str(math.floor(source_pts(clip,fps,start))), 'end_pts':str(math.ceil(source_pts(clip,fps,start+length)))}
176
- if kind == 'audio':
177
- gain = value.get('source_gain_db', -12)
178
- if isinstance(gain,bool) or not isinstance(gain,(int,float)) or not math.isfinite(gain) or not -60 <= gain <= 0 or not isinstance(value.get('fill_music',True),bool):
179
- raise ProjectError('reference_invalid', '原音音量需介於 -60 至 0 dB。', status_code=422)
180
- item.update(source_gain_db=gain,fill_music=value.get('fill_music',True))
181
- layer = value.get('audio_layer_id')
250
+ item["source_range"] = {
251
+ **clip.source.span.to_storage(),
252
+ "start_pts": str(math.floor(source_pts(clip, fps, start))),
253
+ "end_pts": str(math.ceil(source_pts(clip, fps, start + length))),
254
+ }
255
+ if kind == "audio":
256
+ gain = value.get("source_gain_db", -12)
257
+ if (
258
+ isinstance(gain, bool)
259
+ or not isinstance(gain, (int, float))
260
+ or not math.isfinite(gain)
261
+ or not -60 <= gain <= 0
262
+ or not isinstance(value.get("fill_music", True), bool)
263
+ ):
264
+ raise ProjectError("reference_invalid", "原音音量需介於 -60 至 0 dB。", status_code=422)
265
+ item.update(source_gain_db=gain, fill_music=value.get("fill_music", True))
266
+ layer = value.get("audio_layer_id")
182
267
  if layer:
183
- if not isinstance(layer,str) or not any(l['layer_id']==layer for e in clip.effects if e.effect_id=='audio.layers' for l in e.parameters['layers']):
184
- raise ProjectError('reference_invalid', '找不到選定片段的音軌。', status_code=422)
185
- item['audio_layer_id'] = layer
186
- elif any(key in value for key in ('source_gain_db','fill_music','audio_layer_id')):
187
- raise ProjectError('reference_invalid', '只有聲音註記可以指定混音設定。', status_code=422)
268
+ if not isinstance(layer, str) or not any(
269
+ l["layer_id"] == layer
270
+ for e in clip.effects
271
+ if e.effect_id == "audio.layers"
272
+ for l in e.parameters["layers"]
273
+ ):
274
+ raise ProjectError("reference_invalid", "找不到選定片段的音軌。", status_code=422)
275
+ item["audio_layer_id"] = layer
276
+ elif any(key in value for key in ("source_gain_db", "fill_music", "audio_layer_id")):
277
+ raise ProjectError("reference_invalid", "只有聲音註記可以指定混音設定。", status_code=422)
188
278
  return item