@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.
Files changed (232) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +79 -2
  3. package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
  4. package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
  5. package/apps/web/dist/favicon.svg +1 -0
  6. package/apps/web/dist/index.html +16 -0
  7. package/bin/clipen.js +157 -0
  8. package/clipen +18 -0
  9. package/install +25 -0
  10. package/package.json +52 -4
  11. package/pyproject.toml +28 -0
  12. package/requirements/asr-runtime.txt +13 -0
  13. package/requirements/runtime.txt +20 -0
  14. package/src/clipen/__init__.py +3 -0
  15. package/src/clipen/analysis/__init__.py +89 -0
  16. package/src/clipen/analysis/artifacts.py +416 -0
  17. package/src/clipen/analysis/audio.py +392 -0
  18. package/src/clipen/analysis/evidence.py +102 -0
  19. package/src/clipen/analysis/evidence_service.py +751 -0
  20. package/src/clipen/analysis/image_similarity.py +143 -0
  21. package/src/clipen/analysis/keyframes.py +171 -0
  22. package/src/clipen/analysis/models.py +230 -0
  23. package/src/clipen/analysis/qwen_worker.py +629 -0
  24. package/src/clipen/analysis/resources.py +21 -0
  25. package/src/clipen/analysis/runtime.py +64 -0
  26. package/src/clipen/analysis/service.py +626 -0
  27. package/src/clipen/analysis/setup.py +935 -0
  28. package/src/clipen/analysis/setup_cli.py +117 -0
  29. package/src/clipen/analysis/storage.py +2046 -0
  30. package/src/clipen/analysis/transcription.py +948 -0
  31. package/src/clipen/analysis/visual.py +176 -0
  32. package/src/clipen/annotations/__init__.py +10 -0
  33. package/src/clipen/annotations/models.py +22 -0
  34. package/src/clipen/annotations/storage.py +380 -0
  35. package/src/clipen/annotations/suggestions.py +120 -0
  36. package/src/clipen/asr_release.py +139 -0
  37. package/src/clipen/bootstrap.py +967 -0
  38. package/src/clipen/cli.py +84 -0
  39. package/src/clipen/controller/__init__.py +17 -0
  40. package/src/clipen/controller/app.py +1470 -0
  41. package/src/clipen/controller/server.py +543 -0
  42. package/src/clipen/domain/__init__.py +30 -0
  43. package/src/clipen/domain/errors.py +5 -0
  44. package/src/clipen/domain/media_time.py +117 -0
  45. package/src/clipen/domain/timeline.py +584 -0
  46. package/src/clipen/domain/validation.py +15 -0
  47. package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
  48. package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
  49. package/src/clipen/editing/README.md +115 -0
  50. package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
  51. package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
  52. package/src/clipen/editing/__init__.py +15 -0
  53. package/src/clipen/editing/agent.py +13 -0
  54. package/src/clipen/editing/agent_models.py +134 -0
  55. package/src/clipen/editing/agent_repository.py +757 -0
  56. package/src/clipen/editing/agent_tools.py +532 -0
  57. package/src/clipen/editing/alignment.py +110 -0
  58. package/src/clipen/editing/alignment_setup.py +108 -0
  59. package/src/clipen/editing/alignment_worker.py +22 -0
  60. package/src/clipen/editing/change_report.py +71 -0
  61. package/src/clipen/editing/compiler.py +41 -0
  62. package/src/clipen/editing/component_looks.py +107 -0
  63. package/src/clipen/editing/component_review.py +78 -0
  64. package/src/clipen/editing/coordinator.py +374 -0
  65. package/src/clipen/editing/editorial_review.py +187 -0
  66. package/src/clipen/editing/evidence_jobs.py +295 -0
  67. package/src/clipen/editing/history_changes.py +131 -0
  68. package/src/clipen/editing/music_choices.py +15 -0
  69. package/src/clipen/editing/production_catalog.py +192 -0
  70. package/src/clipen/editing/production_limits.py +59 -0
  71. package/src/clipen/editing/production_media.py +226 -0
  72. package/src/clipen/editing/production_preview.py +180 -0
  73. package/src/clipen/editing/production_progress.py +141 -0
  74. package/src/clipen/editing/production_requirements.py +50 -0
  75. package/src/clipen/editing/production_tools.py +596 -0
  76. package/src/clipen/editing/program_audio.py +118 -0
  77. package/src/clipen/editing/program_direction.py +49 -0
  78. package/src/clipen/editing/program_story.py +53 -0
  79. package/src/clipen/editing/program_subtitles.py +134 -0
  80. package/src/clipen/editing/programme_review.py +73 -0
  81. package/src/clipen/editing/prompt_history.py +47 -0
  82. package/src/clipen/editing/recut.py +127 -0
  83. package/src/clipen/editing/refinement_references.py +188 -0
  84. package/src/clipen/editing/resolve_export.py +616 -0
  85. package/src/clipen/editing/resolve_titles.py +234 -0
  86. package/src/clipen/editing/skill_tools.py +575 -0
  87. package/src/clipen/editing/source_dialogue.py +82 -0
  88. package/src/clipen/editing/speech_coverage.py +30 -0
  89. package/src/clipen/editing/speech_quality.py +6 -0
  90. package/src/clipen/editing/tool_receipts.py +52 -0
  91. package/src/clipen/editing/versions.py +161 -0
  92. package/src/clipen/editing/visual_preview.py +93 -0
  93. package/src/clipen/editing/workbench.py +74 -0
  94. package/src/clipen/filesystem.py +25 -0
  95. package/src/clipen/finishing/README.md +103 -0
  96. package/src/clipen/finishing/__init__.py +1 -0
  97. package/src/clipen/finishing/audio.py +149 -0
  98. package/src/clipen/finishing/catalog.py +181 -0
  99. package/src/clipen/finishing/models.py +14 -0
  100. package/src/clipen/finishing/renderer.py +26 -0
  101. package/src/clipen/mcp_editing/__init__.py +5 -0
  102. package/src/clipen/mcp_editing/__main__.py +40 -0
  103. package/src/clipen/mcp_editing/server.py +353 -0
  104. package/src/clipen/media/__init__.py +50 -0
  105. package/src/clipen/media/discovery.py +266 -0
  106. package/src/clipen/media/models.py +360 -0
  107. package/src/clipen/media/preview.py +147 -0
  108. package/src/clipen/media/probe.py +446 -0
  109. package/src/clipen/media/service.py +317 -0
  110. package/src/clipen/media/storage.py +742 -0
  111. package/src/clipen/music_vocabulary.py +5 -0
  112. package/src/clipen/planning/__init__.py +9 -0
  113. package/src/clipen/planning/models.py +240 -0
  114. package/src/clipen/power.py +23 -0
  115. package/src/clipen/projects/__init__.py +26 -0
  116. package/src/clipen/projects/agent_schema.py +94 -0
  117. package/src/clipen/projects/annotation_schema.py +40 -0
  118. package/src/clipen/projects/deletion.py +269 -0
  119. package/src/clipen/projects/evidence_schema.py +52 -0
  120. package/src/clipen/projects/finishing_schema.py +34 -0
  121. package/src/clipen/projects/models.py +192 -0
  122. package/src/clipen/projects/picker.py +256 -0
  123. package/src/clipen/projects/preview_schema.py +29 -0
  124. package/src/clipen/projects/service.py +175 -0
  125. package/src/clipen/projects/storage.py +1478 -0
  126. package/src/clipen/projects/timeline_schema.py +32 -0
  127. package/src/clipen/projects/validation_schema.py +28 -0
  128. package/src/clipen/provider_registry.py +75 -0
  129. package/src/clipen/providers/__init__.py +43 -0
  130. package/src/clipen/providers/account.py +194 -0
  131. package/src/clipen/providers/claude.py +375 -0
  132. package/src/clipen/providers/claude_editing.py +111 -0
  133. package/src/clipen/providers/codex.py +1036 -0
  134. package/src/clipen/providers/codex_editing.py +91 -0
  135. package/src/clipen/providers/editing_agent.py +565 -0
  136. package/src/clipen/providers/errors.py +51 -0
  137. package/src/clipen/providers/recovery.py +270 -0
  138. package/src/clipen/py.typed +1 -0
  139. package/src/clipen/rendering/__init__.py +12 -0
  140. package/src/clipen/rendering/cover.py +126 -0
  141. package/src/clipen/rendering/custom_components.py +240 -0
  142. package/src/clipen/rendering/custom_render.py +197 -0
  143. package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
  144. package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
  145. package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
  146. package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
  147. package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
  148. package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
  149. package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
  150. package/src/clipen/rendering/fonts/manifest.json +145 -0
  151. package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
  152. package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
  153. package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
  154. package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
  155. package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
  156. package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
  157. package/src/clipen/rendering/production_effects.py +64 -0
  158. package/src/clipen/rendering/program_components.py +193 -0
  159. package/src/clipen/rendering/program_creator.py +649 -0
  160. package/src/clipen/rendering/program_identities.py +255 -0
  161. package/src/clipen/rendering/program_motion.py +141 -0
  162. package/src/clipen/rendering/program_studio.py +168 -0
  163. package/src/clipen/rendering/program_styles.py +235 -0
  164. package/src/clipen/rendering/program_subtitles.py +52 -0
  165. package/src/clipen/rendering/renderer.py +708 -0
  166. package/src/clipen/rendering/storage.py +243 -0
  167. package/src/clipen/rendering/titles.py +360 -0
  168. package/src/clipen/skills/__init__.py +4 -0
  169. package/src/clipen/skills/builtin/SKILL.md +72 -0
  170. package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
  171. package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
  172. package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
  173. package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
  174. package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
  175. package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
  176. package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
  177. package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
  178. package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
  179. package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
  180. package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
  181. package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
  182. package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
  183. package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
  184. package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
  185. package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
  186. package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
  187. package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
  188. package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
  189. package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
  190. package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
  191. package/src/clipen/skills/builtin/components.json +133 -0
  192. package/src/clipen/skills/builtin/font_sources.json +20 -0
  193. package/src/clipen/skills/builtin/font_styles.json +329 -0
  194. package/src/clipen/skills/builtin/manifest.json +32 -0
  195. package/src/clipen/skills/builtin/presets.json +8 -0
  196. package/src/clipen/skills/builtin/references/captions.md +14 -0
  197. package/src/clipen/skills/builtin/references/channel-design.md +37 -0
  198. package/src/clipen/skills/builtin/references/editing.md +30 -0
  199. package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
  200. package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
  201. package/src/clipen/skills/builtin/references/graphics.md +59 -0
  202. package/src/clipen/skills/builtin/references/review.md +16 -0
  203. package/src/clipen/skills/builtin/references/sound.md +8 -0
  204. package/src/clipen/skills/builtin/references/story.md +7 -0
  205. package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
  206. package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
  207. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
  208. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
  209. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
  210. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
  211. package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
  212. package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
  213. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
  214. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
  215. package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
  216. package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
  217. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
  218. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
  219. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
  220. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
  221. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
  222. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
  223. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
  224. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
  225. package/src/clipen/skills/builtin/templates.json +284 -0
  226. package/src/clipen/skills/builtin/visual_styles.json +1074 -0
  227. package/src/clipen/skills/catalog.py +218 -0
  228. package/src/clipen/skills/library.py +131 -0
  229. package/src/clipen/skills/package.py +231 -0
  230. package/src/clipen/skills/visual_styles.py +44 -0
  231. package/src/clipen/workspace.py +210 -0
  232. package/uninstall +25 -0
@@ -0,0 +1,374 @@
1
+ """Background orchestration for one-shot provider-driven editing sessions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ import json
7
+ import queue
8
+ import threading
9
+
10
+ from clipen.projects import ProjectError
11
+ from clipen.providers.codex import ProviderCancelled
12
+
13
+ from .agent import AgentRun, EditAgentRepository
14
+ from .production_limits import timeline_stats
15
+
16
+
17
+ class EditAgentCoordinator:
18
+ """Serialize provider jobs while the MCP server owns all timeline mutations."""
19
+
20
+ def __init__(
21
+ self,
22
+ repository: EditAgentRepository,
23
+ attempt_root: Path,
24
+ *,
25
+ adapter_factory=None,
26
+ queue_capacity: int = 4,
27
+ local_runtime: tuple[Path, Path] | None = None,
28
+ provider_id: str = "codex",
29
+ ) -> None:
30
+ root = Path(attempt_root).resolve(strict=True)
31
+ if not root.is_dir() or attempt_root.is_symlink():
32
+ raise ValueError("editing attempt root must be a safe directory")
33
+ if not 1 <= queue_capacity <= 16:
34
+ raise ValueError("editing queue capacity is invalid")
35
+ from clipen.provider_registry import get_provider
36
+
37
+ self.provider = get_provider(provider_id)
38
+ if not self.provider.implemented:
39
+ raise ValueError(f"provider {provider_id} cannot edit yet")
40
+ self.repository = repository
41
+ self.local_runtime = local_runtime
42
+ self.attempt_root = root
43
+ if adapter_factory is None:
44
+ # Import lazily so the provider can import the agent repository
45
+ # without cycling back through clipen.editing.__init__.
46
+ from clipen.provider_registry import editing_agent_factory
47
+
48
+ adapter_factory = editing_agent_factory(provider_id)
49
+ self.adapter_factory = adapter_factory
50
+ self._queue: queue.Queue[tuple[str, str] | None] = queue.Queue(queue_capacity)
51
+ self._cancel: dict[tuple[str, str], threading.Event] = {}
52
+ self._projects: set[str] = set()
53
+ self._worker: threading.Thread | None = None
54
+ self._closed = False
55
+ self._lock = threading.RLock()
56
+ self._user_previews = {}
57
+
58
+ def recover(self) -> int:
59
+ recovered = 0
60
+ for project in self.repository.projects.list_projects():
61
+ recovered += self.repository.interrupt_incomplete(project.project_id)
62
+ with self.repository.projects.connect(project.project_id) as db:
63
+ db.execute("UPDATE production_evidence_jobs SET state='interrupted',error_code='controller_stopped' WHERE state='running'")
64
+ latest = self.repository.latest(project.project_id)
65
+ if (
66
+ latest is not None
67
+ and latest.state == "succeeded"
68
+ and latest.provider_attempt_id is None
69
+ ):
70
+ # finish_edit is durable before the provider process reports its
71
+ # usage. A Controller shutdown in that narrow window must not
72
+ # leave the UI waiting forever for a process that no longer
73
+ # exists. Preserve the successful revision and mark the usage
74
+ # handoff as unavailable.
75
+ self.repository.record_provider_outcome(
76
+ project.project_id,
77
+ latest.run_id,
78
+ "recovered-" + latest.run_id.removeprefix("editrun_"),
79
+ usage=None,
80
+ )
81
+ recovered += 1
82
+ return recovered
83
+
84
+ def status(self, project_id: str) -> dict[str, object]:
85
+ from .production_requirements import production_contents
86
+ latest = self.repository.latest(project_id)
87
+ published = self.repository.latest_successful(project_id)
88
+ result = None
89
+ if published is not None:
90
+ revision = self.repository.final_revision(project_id, published.run_id)
91
+ stats = timeline_stats(revision.timeline)
92
+ with self.repository.projects.connect(project_id) as db:
93
+ rows=db.execute("SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='editorial_review' ORDER BY sequence DESC",(published.run_id,)).fetchall()
94
+ completed_preview=db.execute("SELECT render_id FROM preview_renders WHERE timeline_id=? AND state='succeeded' ORDER BY created_at DESC LIMIT 1",(revision.revision_id,)).fetchone()
95
+ assessment=next((v for v in (json.loads(r['payload_json']) for r in rows) if v['revision_id']==revision.revision_id),None)
96
+ from .program_story import read_episode
97
+ from .program_subtitles import subtitle_status
98
+ from .production_requirements import production_contents
99
+ result = {
100
+ **revision.to_public(include_timeline=True),
101
+ "run_id": published.run_id,
102
+ "editorial_review": assessment,
103
+ "creative_direction": self.repository.creative_direction(project_id,published.run_id),
104
+ "episode": read_episode(self.repository.projects,project_id,published.run_id,revision.timeline),
105
+ "subtitle_review": subtitle_status(self.repository.projects,project_id,revision.timeline),
106
+ "production_contents": production_contents(self.repository.projects,project_id,revision.timeline),
107
+ "export_url": self._export_url(project_id,published.run_id,revision.revision_id),
108
+ "preview_url": f"/api/projects/{project_id}/preview/{completed_preview['render_id']}/media" if completed_preview else None,
109
+ "proof_stats": {
110
+ "duration_seconds": stats.duration_seconds,
111
+ "clip_count": stats.clip_count,
112
+ "longest_clip_seconds": stats.longest_clip_seconds,
113
+ "title_count": stats.title_count,
114
+ "effect_count": stats.effect_count,
115
+ },
116
+ }
117
+ production = None
118
+ if latest is not None:
119
+ session = self.repository.production_session(project_id, latest.run_id)
120
+ if session is not None:
121
+ draft = self.repository.current_revision(project_id, latest.run_id)
122
+ from clipen.rendering import PreviewRenderRepository
123
+ with self.repository.projects.connect(project_id) as db:
124
+ previews = db.execute("SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='production_preview' ORDER BY sequence DESC LIMIT 1", (latest.run_id,)).fetchone()
125
+ successful_preview = db.execute("SELECT e.payload_json FROM edit_agent_events e JOIN preview_renders p ON p.render_id=json_extract(e.payload_json,'$.render_id') AND p.project_id=? WHERE e.run_id=? AND e.event_type='production_preview' AND p.state='succeeded' ORDER BY e.sequence DESC LIMIT 1",(project_id,latest.run_id)).fetchone()
126
+ checks = db.execute("SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='sequence_validation' ORDER BY sequence DESC LIMIT 30",(latest.run_id,)).fetchall()
127
+ jobs = db.execute("SELECT job_id,kind,state,error_code,result_json FROM production_evidence_jobs WHERE run_id=? ORDER BY rowid DESC LIMIT 10",(latest.run_id,)).fetchall()
128
+ from .production_progress import production_activity
129
+ progress = production_activity(db, latest.run_id)
130
+ validation=next((value for row in checks if (value:=json.loads(row['payload_json']))['revision_id']==draft.revision_id),None)
131
+ from .versions import versions
132
+ with self.repository.projects.connect(project_id) as db:
133
+ film_versions=versions(db,latest.run_id,latest.provider)
134
+ succeeded=db.execute("SELECT e.payload_json FROM edit_agent_events e JOIN preview_renders p ON p.render_id=json_extract(e.payload_json,'$.render_id') AND p.project_id=? WHERE e.run_id=? AND e.event_type='production_preview' AND p.state='succeeded' ORDER BY e.sequence DESC LIMIT 200",(project_id,latest.run_id)).fetchall()
135
+ # A finished film is a preview of a version people chose to keep (an AI request that
136
+ # finished, a manual edit or a restore); a newer preview of anything else is a draft.
137
+ complete={v['revision_id']:v for v in film_versions if v['kind']!='ai_partial'}
138
+ finished_row=next((row for row in succeeded if json.loads(row['payload_json'])['revision_id'] in complete),None)
139
+ draft_row=succeeded[0] if succeeded and succeeded[0] is not finished_row else None
140
+ local_jobs=[]
141
+ for row in jobs:
142
+ value=json.loads(row['result_json']) if row['result_json'] else {}
143
+ local_jobs.append({k:row[k] for k in ('job_id','kind','state','error_code')} |
144
+ {k:value[k] for k in ('phase','completed_bytes','total_bytes') if k in value})
145
+ from .production_preview import render_recipe_id
146
+ recipe_id=render_recipe_id()
147
+ def preview_value(row):
148
+ if row is None:return None
149
+ entry=json.loads(row['payload_json'])
150
+ return {**PreviewRenderRepository(self.repository.projects).get(project_id, entry['render_id']),
151
+ 'revision_id': entry['revision_id'], 'stale': entry['revision_id'] != draft.revision_id or entry.get('recipe_id')!=recipe_id,
152
+ 'media_url': f"/api/projects/{project_id}/preview/{entry['render_id']}/media"}
153
+ preview=preview_value(previews)
154
+ last_successful_preview=preview_value(successful_preview)
155
+ finished_preview=preview_value(finished_row)
156
+ draft_preview=preview_value(draft_row)
157
+ by_revision={v['revision_id']:v for v in reversed(film_versions)}
158
+ if finished_preview:finished_preview['version']=by_revision.get(finished_preview['revision_id'])
159
+ if draft_preview:draft_preview['version']=by_revision.get(draft_preview['revision_id'])
160
+ production = {'intent': session['intent'], 'skill': {k: session['skill'][k] for k in ('skill_id','name','version','content_hash','limitations','selected_visual_style_id','selected_font_style_id') if k in session['skill']},
161
+ 'draft': draft.to_public(include_timeline=True), 'preview': preview,'last_successful_preview':last_successful_preview,'finished_preview':finished_preview,'draft_preview':draft_preview,'validation':validation,'local_jobs':local_jobs,
162
+ 'production_contents':production_contents(self.repository.projects,project_id,draft.timeline),
163
+ 'export_url':self._export_url(project_id,latest.run_id,draft.revision_id), 'progress':progress}
164
+ return {
165
+ "latest_run": None if latest is None else latest.to_public(),
166
+ "result": result,
167
+ "production": production,
168
+ }
169
+
170
+ def _export_url(self,project_id,run_id,revision_id):
171
+ try:self.export_path(project_id,run_id,revision_id)
172
+ except ProjectError:return None
173
+ return f'/api/projects/{project_id}/edit-agent/{run_id}/exports/{revision_id}'
174
+
175
+ def export_path(self,project_id,run_id,revision_id):
176
+ from .agent_models import REVISION_ID_PATTERN
177
+ self.repository.get(project_id,run_id)
178
+ if not isinstance(revision_id,str) or REVISION_ID_PATTERN.fullmatch(revision_id) is None:
179
+ raise ProjectError('agent_export_not_found','找不到匯出的剪輯版本。',status_code=404)
180
+ with self.repository.projects.connect(project_id) as db:
181
+ if db.execute('SELECT 1 FROM edit_agent_revisions WHERE revision_id=? AND run_id=?',(revision_id,run_id)).fetchone() is None:
182
+ raise ProjectError('agent_export_not_found','匯出不屬於這次剪輯。',status_code=404)
183
+ root=self.repository.projects.root/project_id/'agent-production'
184
+ path=root/run_id/'exports'/(revision_id+'.json')
185
+ if any(p.is_symlink() for p in (root,root/run_id,root/run_id/'exports',path)) or not path.is_file() or path.stat().st_size>8*1024*1024:
186
+ raise ProjectError('agent_export_not_found','匯出檔案遺失或不安全。',status_code=404)
187
+ return path
188
+
189
+ def start(
190
+ self,
191
+ project_id: str,
192
+ request_id: object,
193
+ consent: object,
194
+ *,
195
+ max_tool_calls: int = 96,
196
+ max_preview_renders: int = 4,
197
+ production: dict,
198
+ ) -> AgentRun:
199
+ if consent is not True:
200
+ raise ProjectError(
201
+ "edit_agent_consent_required",
202
+ f"請先同意使用 {self.provider.display_name} 額度執行這次 AI 剪輯。",
203
+ status_code=422,
204
+ )
205
+ with self._lock:
206
+ if self._closed or self._queue.full():
207
+ raise ProjectError(
208
+ "edit_agent_busy", "AI 剪輯佇列目前已滿。", status_code=409
209
+ )
210
+ run, created = self.repository.create_run(
211
+ project_id,
212
+ request_id,
213
+ provider=self.provider.provider_id,
214
+ max_tool_calls=max_tool_calls,
215
+ max_preview_renders=max_preview_renders,
216
+ production=production,
217
+ )
218
+ if not created:
219
+ return run
220
+ key = (project_id, run.run_id)
221
+ self._projects.add(project_id)
222
+ self._cancel[key] = threading.Event()
223
+ self._queue.put_nowait(key)
224
+ if self._worker is None:
225
+ self._worker = threading.Thread(
226
+ target=self._loop,
227
+ name="clipen-edit-agent",
228
+ daemon=True,
229
+ )
230
+ self._worker.start()
231
+ return run
232
+
233
+ def refine(self, project_id, run_id, request_id, expected_revision_id, instruction, consent, music_asset_id=None, expected_references_version=None):
234
+ if consent is not True:raise ProjectError('edit_agent_consent_required',f'請同意使用 {self.provider.display_name} 額度修改影片。',status_code=422)
235
+ with self._lock:
236
+ key=(project_id,run_id)
237
+ if self._closed or self._queue.full() or key in self._cancel:
238
+ raise ProjectError('edit_agent_busy','AI 製作仍在執行,請稍後再試。',status_code=409)
239
+ run,created=self.repository.request_refinement(project_id,run_id,request_id,expected_revision_id,instruction,music_asset_id,expected_references_version,
240
+ provider=self.provider.provider_id)
241
+ if not created:return run
242
+ self._projects.add(project_id);self._cancel[key]=threading.Event();self._queue.put_nowait(key)
243
+ if self._worker is None:
244
+ self._worker=threading.Thread(target=self._loop,name='clipen-edit-agent',daemon=True);self._worker.start()
245
+ return run
246
+
247
+ def workbench_edit(self, project_id, run_id, tool, arguments, expected_revision_id, mutation_id):
248
+ from .workbench import edit
249
+ with self._lock:
250
+ return edit(self.repository,project_id,run_id,tool,arguments,expected_revision_id,mutation_id)
251
+
252
+ def workbench_render(self, project_id, run_id, expected_revision_id):
253
+ from .workbench import idle, tools_for
254
+ with self._lock:
255
+ run=idle(self.repository,project_id,run_id)
256
+ if run.current_revision_id!=expected_revision_id:raise ProjectError('revision_conflict','影片已更新,請重新讀取。',status_code=409)
257
+ key=(project_id,run_id)
258
+ tools=self._user_previews.get(key)
259
+ if tools is None:
260
+ tools=tools_for(self.repository,project_id,run_id);self._user_previews[key]=tools
261
+ if hasattr(tools,'_session_cache'):del tools._session_cache
262
+ return tools.production_call('render_preview',{}).payload
263
+
264
+ def resume(self, project_id: str, run_id: str, consent: object) -> AgentRun:
265
+ if consent is not True:
266
+ raise ProjectError('edit_agent_consent_required', f'請同意接續使用 {self.provider.display_name} 額度。', status_code=422)
267
+ with self._lock:
268
+ key = (project_id, run_id)
269
+ if self._closed or self._queue.full() or key in self._cancel:
270
+ raise ProjectError('edit_agent_busy', '製作工作仍在結束或佇列已滿,請稍後再試。', status_code=409)
271
+ run = self.repository.resume_stopped(project_id, run_id)
272
+ self._projects.add(project_id)
273
+ self._cancel[key] = threading.Event()
274
+ self._queue.put_nowait(key)
275
+ if self._worker is None:
276
+ self._worker = threading.Thread(target=self._loop, name='clipen-edit-agent', daemon=True)
277
+ self._worker.start()
278
+ return run
279
+
280
+ def cancel(self, project_id: str, run_id: str) -> AgentRun:
281
+ with self._lock:
282
+ run = self.repository.cancel(project_id, run_id)
283
+ token = self._cancel.get((project_id, run_id))
284
+ if token is not None:
285
+ token.set()
286
+ return run
287
+
288
+ def close(self, timeout: float = 15) -> None:
289
+ for tools in self._user_previews.values():tools.close_production()
290
+ with self._lock:
291
+ if self._closed:
292
+ return
293
+ self._closed = True
294
+ active = tuple(self._cancel)
295
+ for token in self._cancel.values():
296
+ token.set()
297
+ while True:
298
+ try:
299
+ queued = self._queue.get_nowait()
300
+ except queue.Empty:
301
+ break
302
+ if queued is not None:
303
+ self._queue.task_done()
304
+ worker = self._worker
305
+ if worker is not None:
306
+ self._queue.put_nowait(None)
307
+ if worker is not None:
308
+ worker.join(max(0, timeout))
309
+ for project_id, run_id in active:
310
+ try:
311
+ self.repository.interrupt_for_shutdown(project_id, run_id)
312
+ except ProjectError:
313
+ pass
314
+ for project_id in self._projects:
315
+ self.repository.interrupt_incomplete(project_id)
316
+
317
+ def _end_attempt_renders(self, key) -> None:
318
+ from clipen.rendering import PreviewRenderRepository
319
+ try:
320
+ PreviewRenderRepository(self.repository.projects).interrupt_attempt_renders(*key)
321
+ except ProjectError:
322
+ pass
323
+
324
+ def _loop(self) -> None:
325
+ while True:
326
+ key = self._queue.get()
327
+ try:
328
+ if key is None:
329
+ return
330
+ with self._lock:
331
+ cancel = self._cancel[key]
332
+ if cancel.is_set():
333
+ continue
334
+ if self.repository.get(*key).provider != self.provider.provider_id:
335
+ # Never spend another provider's quota on a run the user
336
+ # authorised for the provider it was created with.
337
+ self.repository.record_provider_outcome(
338
+ *key, "agent-mismatch-" + key[1].removeprefix("editrun_"),
339
+ usage=None, error_code="provider_mismatch")
340
+ continue
341
+ adapter = self.adapter_factory(
342
+ self.repository.projects.root,
343
+ self.attempt_root,
344
+ self.repository,
345
+ **({'local_runtime':self.local_runtime} if self.local_runtime else {}),
346
+ )
347
+ self._end_attempt_renders(key)
348
+ adapter.execute(*key, cancel=cancel)
349
+ except (ProjectError, ProviderCancelled):
350
+ pass
351
+ except Exception:
352
+ if key is not None:
353
+ try:
354
+ current = self.repository.get(*key)
355
+ if current.state in {"queued", "running"}:
356
+ self.repository.record_provider_outcome(
357
+ *key,
358
+ "agent-launch-" + key[1].removeprefix("editrun_"),
359
+ usage=None,
360
+ error_code="provider_launch_failed",
361
+ )
362
+ except ProjectError:
363
+ pass
364
+ finally:
365
+ if key is not None:
366
+ try:
367
+ with self.repository.projects.connect(key[0]) as db:
368
+ db.execute("UPDATE production_evidence_jobs SET state='interrupted',error_code='provider_ended' WHERE run_id=? AND state='running'",(key[1],))
369
+ except ProjectError:
370
+ pass
371
+ self._end_attempt_renders(key)
372
+ with self._lock:
373
+ self._cancel.pop(key, None)
374
+ self._queue.task_done()
@@ -0,0 +1,187 @@
1
+ """Shot coverage and revision-bound, explicitly model-authored editorial findings.
2
+
3
+ Coverage proves which stills were delivered, never that motion or sound was
4
+ understood. Findings expose the model's decisions rather than inventing a score.
5
+ """
6
+ import hashlib
7
+ import json
8
+ from fractions import Fraction
9
+
10
+ from clipen.domain import EditTimeline, TrackKind
11
+ from clipen.media import MediaPreviewRepository
12
+ from clipen.projects import ProjectError
13
+ from .agent_models import ToolResult
14
+ from .production_media import sample_frames
15
+ from .production_preview import _event, inspect_preview
16
+
17
+
18
+ def shot_offsets(item, fps):
19
+ # First/last real frames, not the following shot at the outgoing boundary.
20
+ return [item.start_frame/fps, (item.start_frame+(item.duration_frames-1)/2)/fps,
21
+ (item.start_frame+item.duration_frames-1)/fps]
22
+
23
+
24
+ def _effects(item):
25
+ return [(e.effect_id, e.version, e._parameters_json) for e in item.effects]
26
+
27
+
28
+ def _fingerprint(value):
29
+ return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True).encode()).hexdigest()
30
+
31
+
32
+ def shot_fingerprints(timeline):
33
+ """What each shot looks like on screen, independent of where it sits in the film.
34
+
35
+ Covers the source range, length, the shot's own effects, the next shot's
36
+ incoming transition and every text or component drawn over it (relative to
37
+ the shot). A shot with the same fingerprint renders the same stills.
38
+ """
39
+ video = [t for t in timeline.tracks if t.kind is TrackKind.VIDEO]
40
+ clips = [item for track in video for item in track.items]
41
+ texts = [item for t in timeline.tracks if t.kind is TrackKind.TITLE for item in t.items]
42
+ result = {}
43
+ for index, clip in enumerate(clips):
44
+ end = clip.start_frame + clip.duration_frames
45
+ following = clips[index + 1] if index + 1 < len(clips) else None
46
+ over = sorted((t.text, t.style_id, t.start_frame - clip.start_frame, t.duration_frames)
47
+ for t in texts if t.start_frame < end and clip.start_frame < t.start_frame + t.duration_frames)
48
+ result[clip.item_id] = _fingerprint({
49
+ 'source': clip.source.span.to_storage(), 'duration': clip.duration_frames, 'effects': _effects(clip),
50
+ 'next_transition': [e for e in _effects(following) if e[0] == 'video.transition'] if following else None,
51
+ 'texts': over, 'canvas': [timeline.width, timeline.height, timeline.frame_rate.numerator, timeline.frame_rate.denominator]})
52
+ return result
53
+
54
+
55
+ def text_fingerprints(timeline):
56
+ """A text matches an earlier review when it and the shot under its midpoint are unchanged."""
57
+ shots = shot_fingerprints(timeline)
58
+ clips = [item for t in timeline.tracks if t.kind is TrackKind.VIDEO for item in t.items]
59
+ result = {}
60
+ for t in timeline.tracks:
61
+ if t.kind is not TrackKind.TITLE:
62
+ continue
63
+ for item in t.items:
64
+ middle = item.start_frame + (item.duration_frames - 1) / 2
65
+ under = next((c for c in clips if c.start_frame <= middle < c.start_frame + c.duration_frames), None)
66
+ result[item.item_id] = _fingerprint({'text': item.text, 'style': item.style_id, 'duration': item.duration_frames,
67
+ 'offset': None if under is None else middle - under.start_frame,
68
+ 'shot': None if under is None else shots[under.item_id]})
69
+ return result
70
+
71
+
72
+ def carried_reviews(tools, revision, recipe_id):
73
+ """Shots and texts already reviewed and accepted in an earlier revision of this run, unchanged since.
74
+
75
+ Only revisions with a recorded editorial review count: that review required
76
+ complete coverage, so an accepted, unchanged shot need not be looked at again.
77
+ """
78
+ with tools.repository.projects.connect(tools.project_id) as db:
79
+ reports = {}
80
+ for row in db.execute("SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type='editorial_review' ORDER BY sequence",
81
+ (tools.run_id,)):
82
+ report = json.loads(row['payload_json'])
83
+ if report.get('recipe_id') == recipe_id and report['revision_id'] != revision.revision_id:
84
+ reports[report['revision_id']] = report
85
+ payloads = {row['revision_id']: row['payload_json'] for row in db.execute(
86
+ f"SELECT revision_id,payload_json FROM edit_agent_revisions WHERE run_id=? AND revision_id IN ({','.join('?' for _ in reports)})",
87
+ (tools.run_id, *reports))} if reports else {}
88
+ accepted_shots, accepted_texts = set(), set()
89
+ for revision_id, report in reports.items():
90
+ if revision_id not in payloads:
91
+ continue
92
+ earlier = EditTimeline.from_payload(json.loads(payloads[revision_id]))
93
+ shots, texts = shot_fingerprints(earlier), text_fingerprints(earlier)
94
+ accepted_shots |= {shots[s['item_id']] for s in report.get('shots', []) if s.get('decision') != 'revise' and s['item_id'] in shots}
95
+ accepted_texts |= {texts[c['item_id']] for c in report.get('text_checks', []) if c.get('matches') and c['item_id'] in texts}
96
+ accepted_shots |= set(report.get('carried_shots', []))
97
+ accepted_texts |= set(report.get('carried_texts', []))
98
+ current_shots, current_texts = shot_fingerprints(revision.timeline), text_fingerprints(revision.timeline)
99
+ return ({item: print_ for item, print_ in current_shots.items() if print_ in accepted_shots},
100
+ {item: print_ for item, print_ in current_texts.items() if print_ in accepted_texts})
101
+
102
+
103
+ def coverage_targets(timeline):
104
+ fps=timeline.frame_rate.numerator/timeline.frame_rate.denominator
105
+ return {item.item_id:shot_offsets(item,fps) for t in timeline.tracks if t.kind is TrackKind.VIDEO for item in t.items}
106
+
107
+
108
+ def text_targets(timeline):
109
+ fps=timeline.frame_rate.numerator/timeline.frame_rate.denominator
110
+ return {item.item_id:(item.start_frame+(item.duration_frames-1)/2)/fps
111
+ for t in timeline.tracks if t.kind is TrackKind.TITLE for item in t.items}
112
+
113
+
114
+ def inspect_cut(tools,args):
115
+ revision=tools.repository.current_revision(tools.project_id,tools.run_id)
116
+ timeline=revision.timeline;targets=coverage_targets(timeline)
117
+ clips={i.item_id:i for i in tools._video().items}
118
+ if any(i not in clips for i in args['item_ids']):
119
+ raise ProjectError('timeline_item_not_found','指定鏡頭不在目前剪輯。',status_code=404)
120
+ fps=Fraction(timeline.frame_rate.numerator,timeline.frame_rate.denominator)
121
+ speech=tools._production_list_transcripts({'include_drafts':True}).payload
122
+ cues,limitations=speech['cues'],speech['limitations']
123
+ images=[];shots=[]
124
+ for identifier in args['item_ids']:
125
+ item=clips[identifier]
126
+ texts=[i for t in timeline.tracks if t.kind is TrackKind.TITLE for i in t.items
127
+ if i.start_frame<item.start_frame+item.duration_frames and item.start_frame<i.start_frame+i.duration_frames]
128
+ if args.get('render_id'):
129
+ offsets=targets[identifier]+[text_targets(timeline)[i.item_id] for i in texts[:1]]
130
+ # Text can span shots; its midpoint must still be inspected, once.
131
+ offsets=sorted(set(offsets))
132
+ for start in range(0,len(offsets),8):
133
+ result=inspect_preview(tools,{'render_id':args['render_id'],'offsets_seconds':offsets[start:start+8]})
134
+ if result.payload['render']['state']!='succeeded' or result.payload['stale']:
135
+ return ToolResult(result.payload)
136
+ images.extend(result.images)
137
+ samples=[{'timeline_seconds':o} for o in offsets]
138
+ else:
139
+ span=item.source.span;unit=Fraction(span.time_base.numerator,span.time_base.denominator)
140
+ duration=span.duration_pts*unit
141
+ last=min(Fraction(item.duration_frames-1,1)/fps,duration-Fraction(1,1)/fps)
142
+ offsets=[0,float(max(0,last)/2),float(max(0,last))]
143
+ media=getattr(tools,'media',None) or MediaPreviewRepository(tools.repository.projects)
144
+ paths,samples=sample_frames(media,tools.project_id,span,offsets,tools._workdir('samples'),tools._cancel_event())
145
+ images.extend(paths)
146
+ shots.append({'item_id':identifier,'source':item.source.span.to_storage(),'samples':samples,
147
+ 'image_count':len(samples),'texts':[{'item_id':i.item_id,'text':i.text,'start_frame':i.start_frame,'duration_frames':i.duration_frames} for i in texts],
148
+ 'dialogue':[c for c in cues if c['item_id']==identifier],
149
+ 'dialogue_problems':[c for c in limitations if c['item_id']==identifier]})
150
+ from .programme_review import pacing
151
+ return ToolResult({'revision_id':revision.revision_id,'shots':shots,'pacing':pacing(timeline),
152
+ 'image_order':'shots in requested order; frames in sample order',
153
+ 'coverage':'start/middle/end stills; continuous motion and audio remain unreviewed',
154
+ 'text_coverage':'At most one additional text midpoint per shot; validate_sequence lists remaining text samples for inspect_preview.',
155
+ 'editorial_questions':['Does this show the event or only preparation/empty wall?',
156
+ 'Does the scene establish a place and then deliver action/reaction?',
157
+ 'Is each location/day assertion supported by this exact shot?',
158
+ 'Does retained speech finish naturally? Repair source spans before captions.']},tuple(images))
159
+
160
+
161
+ def review_cut(tools,args):
162
+ from .production_preview import finish_review_status
163
+ revision=tools.repository.current_revision(tools.project_id,tools.run_id)
164
+ status=finish_review_status(tools)
165
+ if not status['render_coverage_complete']:
166
+ raise ProjectError('agent_preview_review_required','請先檢視每個鏡頭的頭、中、尾及所有文字顯示畫面。',status_code=409)
167
+ every_shot=set(coverage_targets(revision.timeline));every_text=set(text_targets(revision.timeline))
168
+ carried_shots,carried_texts=set(status.get('carried_shots',())),set(status.get('carried_texts',()))
169
+ shots=args['shots'];checks=args['text_checks']
170
+ listed_shots=[s['item_id'] for s in shots];listed_texts=[c['item_id'] for c in checks]
171
+ # Every changed shot and text must be judged; unchanged, already accepted ones may be listed or left out.
172
+ if (len(listed_shots)!=len(set(listed_shots)) or not every_shot-carried_shots<=set(listed_shots)<=every_shot
173
+ or len(listed_texts)!=len(set(listed_texts)) or not every_text-carried_texts<=set(listed_texts)<=every_text):
174
+ raise ProjectError('agent_review_incomplete','審片紀錄必須逐一列出所有改過的鏡頭與文字,不可重複或遺漏;沒改過且已通過的可以省略。',status_code=422)
175
+ if status['unresolved']:
176
+ still_unresolved={s['item_id'] for s in shots if s['decision']=='revise'}|{c['item_id'] for c in checks if not c['matches']}
177
+ if not set(status['unresolved'])<=still_unresolved:
178
+ raise ProjectError('agent_revision_required','這個版本已記錄待修問題;請先實際修改時間軸,再輸出並檢視新版,不能只改評語清除問題。',status_code=409)
179
+ from .production_preview import render_recipe_id
180
+ shot_prints,text_prints=shot_fingerprints(revision.timeline),text_fingerprints(revision.timeline)
181
+ report={'revision_id':revision.revision_id,'recipe_id':render_recipe_id(),'authority':'model_authored',**args,
182
+ # Carried items keep their earlier acceptance for later revisions.
183
+ 'carried_shots':sorted(shot_prints[i] for i in carried_shots-set(listed_shots)),
184
+ 'carried_texts':sorted(text_prints[i] for i in carried_texts-set(listed_texts))}
185
+ _event(tools,'editorial_review',report)
186
+ return ToolResult({'assessment':report,'unresolved':[s['item_id'] for s in shots if s['decision']=='revise']+[c['item_id'] for c in checks if not c['matches']],
187
+ 'human_review':'pending','quality_claim':'This records model findings, not independent approval.'})