@clipen/clipen-cli 0.0.0-stage → 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 (232) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -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 +55 -4
  11. package/pyproject.toml +44 -0
  12. package/requirements/asr-runtime.txt +13 -0
  13. package/requirements/dev.txt +2 -0
  14. package/requirements/runtime.txt +20 -0
  15. package/src/clipen/__init__.py +3 -0
  16. package/src/clipen/analysis/__init__.py +89 -0
  17. package/src/clipen/analysis/artifacts.py +410 -0
  18. package/src/clipen/analysis/audio.py +394 -0
  19. package/src/clipen/analysis/evidence.py +102 -0
  20. package/src/clipen/analysis/evidence_service.py +929 -0
  21. package/src/clipen/analysis/image_similarity.py +134 -0
  22. package/src/clipen/analysis/keyframes.py +159 -0
  23. package/src/clipen/analysis/models.py +228 -0
  24. package/src/clipen/analysis/qwen_worker.py +594 -0
  25. package/src/clipen/analysis/resources.py +22 -0
  26. package/src/clipen/analysis/runtime.py +62 -0
  27. package/src/clipen/analysis/service.py +594 -0
  28. package/src/clipen/analysis/setup.py +921 -0
  29. package/src/clipen/analysis/setup_cli.py +107 -0
  30. package/src/clipen/analysis/storage.py +1864 -0
  31. package/src/clipen/analysis/transcription.py +906 -0
  32. package/src/clipen/analysis/visual.py +237 -0
  33. package/src/clipen/annotations/__init__.py +13 -0
  34. package/src/clipen/annotations/models.py +22 -0
  35. package/src/clipen/annotations/storage.py +428 -0
  36. package/src/clipen/annotations/suggestions.py +115 -0
  37. package/src/clipen/asr_release.py +132 -0
  38. package/src/clipen/bootstrap.py +978 -0
  39. package/src/clipen/candidates.py +222 -0
  40. package/src/clipen/cli.py +84 -0
  41. package/src/clipen/controller/__init__.py +17 -0
  42. package/src/clipen/controller/app.py +1657 -0
  43. package/src/clipen/controller/server.py +533 -0
  44. package/src/clipen/domain/__init__.py +30 -0
  45. package/src/clipen/domain/errors.py +5 -0
  46. package/src/clipen/domain/media_time.py +110 -0
  47. package/src/clipen/domain/timeline.py +582 -0
  48. package/src/clipen/domain/validation.py +14 -0
  49. package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
  50. package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
  51. package/src/clipen/editing/README.md +115 -0
  52. package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
  53. package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
  54. package/src/clipen/editing/__init__.py +15 -0
  55. package/src/clipen/editing/agent.py +13 -0
  56. package/src/clipen/editing/agent_models.py +127 -0
  57. package/src/clipen/editing/agent_repository.py +978 -0
  58. package/src/clipen/editing/agent_tools.py +613 -0
  59. package/src/clipen/editing/alignment.py +150 -0
  60. package/src/clipen/editing/alignment_setup.py +156 -0
  61. package/src/clipen/editing/alignment_worker.py +24 -0
  62. package/src/clipen/editing/change_report.py +128 -0
  63. package/src/clipen/editing/compiler.py +40 -0
  64. package/src/clipen/editing/component_looks.py +131 -0
  65. package/src/clipen/editing/component_review.py +74 -0
  66. package/src/clipen/editing/coordinator.py +497 -0
  67. package/src/clipen/editing/editorial_review.py +309 -0
  68. package/src/clipen/editing/evidence_jobs.py +552 -0
  69. package/src/clipen/editing/history_changes.py +192 -0
  70. package/src/clipen/editing/music_choices.py +18 -0
  71. package/src/clipen/editing/production_catalog.py +629 -0
  72. package/src/clipen/editing/production_limits.py +85 -0
  73. package/src/clipen/editing/production_media.py +435 -0
  74. package/src/clipen/editing/production_preview.py +373 -0
  75. package/src/clipen/editing/production_progress.py +236 -0
  76. package/src/clipen/editing/production_requirements.py +117 -0
  77. package/src/clipen/editing/production_tools.py +1198 -0
  78. package/src/clipen/editing/program_audio.py +248 -0
  79. package/src/clipen/editing/program_direction.py +83 -0
  80. package/src/clipen/editing/program_story.py +91 -0
  81. package/src/clipen/editing/program_subtitles.py +232 -0
  82. package/src/clipen/editing/programme_review.py +121 -0
  83. package/src/clipen/editing/prompt_history.py +84 -0
  84. package/src/clipen/editing/recut.py +167 -0
  85. package/src/clipen/editing/refinement_references.py +278 -0
  86. package/src/clipen/editing/resolve_export.py +847 -0
  87. package/src/clipen/editing/resolve_titles.py +291 -0
  88. package/src/clipen/editing/skill_tools.py +951 -0
  89. package/src/clipen/editing/source_dialogue.py +192 -0
  90. package/src/clipen/editing/speech_coverage.py +50 -0
  91. package/src/clipen/editing/speech_quality.py +11 -0
  92. package/src/clipen/editing/tool_receipts.py +98 -0
  93. package/src/clipen/editing/versions.py +219 -0
  94. package/src/clipen/editing/visual_preview.py +189 -0
  95. package/src/clipen/editing/workbench.py +136 -0
  96. package/src/clipen/filesystem.py +25 -0
  97. package/src/clipen/finishing/README.md +103 -0
  98. package/src/clipen/finishing/__init__.py +1 -0
  99. package/src/clipen/finishing/audio.py +188 -0
  100. package/src/clipen/finishing/catalog.py +264 -0
  101. package/src/clipen/finishing/models.py +14 -0
  102. package/src/clipen/finishing/renderer.py +45 -0
  103. package/src/clipen/mcp_editing/__init__.py +5 -0
  104. package/src/clipen/mcp_editing/__main__.py +42 -0
  105. package/src/clipen/mcp_editing/server.py +396 -0
  106. package/src/clipen/media/__init__.py +50 -0
  107. package/src/clipen/media/discovery.py +253 -0
  108. package/src/clipen/media/models.py +349 -0
  109. package/src/clipen/media/preview.py +137 -0
  110. package/src/clipen/media/probe.py +418 -0
  111. package/src/clipen/media/service.py +304 -0
  112. package/src/clipen/media/storage.py +694 -0
  113. package/src/clipen/music_vocabulary.py +34 -0
  114. package/src/clipen/power.py +28 -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 +256 -0
  119. package/src/clipen/projects/evidence_schema.py +52 -0
  120. package/src/clipen/projects/finishing_schema.py +36 -0
  121. package/src/clipen/projects/models.py +189 -0
  122. package/src/clipen/projects/picker.py +232 -0
  123. package/src/clipen/projects/preview_schema.py +29 -0
  124. package/src/clipen/projects/service.py +159 -0
  125. package/src/clipen/projects/storage.py +1458 -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 +77 -0
  129. package/src/clipen/providers/__init__.py +43 -0
  130. package/src/clipen/providers/account.py +245 -0
  131. package/src/clipen/providers/claude.py +409 -0
  132. package/src/clipen/providers/claude_editing.py +118 -0
  133. package/src/clipen/providers/codex.py +991 -0
  134. package/src/clipen/providers/codex_editing.py +91 -0
  135. package/src/clipen/providers/editing_agent.py +567 -0
  136. package/src/clipen/providers/errors.py +51 -0
  137. package/src/clipen/providers/recovery.py +269 -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 +139 -0
  141. package/src/clipen/rendering/custom_components.py +328 -0
  142. package/src/clipen/rendering/custom_render.py +218 -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 +96 -0
  158. package/src/clipen/rendering/program_components.py +254 -0
  159. package/src/clipen/rendering/program_creator.py +804 -0
  160. package/src/clipen/rendering/program_identities.py +350 -0
  161. package/src/clipen/rendering/program_motion.py +186 -0
  162. package/src/clipen/rendering/program_studio.py +227 -0
  163. package/src/clipen/rendering/program_styles.py +321 -0
  164. package/src/clipen/rendering/program_subtitles.py +89 -0
  165. package/src/clipen/rendering/renderer.py +737 -0
  166. package/src/clipen/rendering/storage.py +230 -0
  167. package/src/clipen/rendering/titles.py +467 -0
  168. package/src/clipen/skills/__init__.py +5 -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 +314 -0
  228. package/src/clipen/skills/library.py +137 -0
  229. package/src/clipen/skills/package.py +254 -0
  230. package/src/clipen/skills/visual_styles.py +55 -0
  231. package/src/clipen/workspace.py +181 -0
  232. package/uninstall +25 -0
@@ -0,0 +1,192 @@
1
+ """Search current source speech before picking a cut; no synthetic event labels."""
2
+
3
+ import json
4
+ import math
5
+ from fractions import Fraction
6
+
7
+ from .agent_models import ToolResult
8
+ from .production_media import source_rows
9
+
10
+
11
+ def search_dialogue(tools, args):
12
+ from .speech_quality import speech_flags
13
+
14
+ sources = {}
15
+ for source in (
16
+ tools._source_rows()
17
+ if hasattr(tools, "_source_rows")
18
+ else source_rows(tools.repository.projects, tools.project_id)
19
+ ):
20
+ if source["kind"] == "video":
21
+ sources.setdefault(source["version_id"], source)
22
+ query = args.get("query", "").strip().casefold()
23
+ version = args.get("version_id")
24
+ drafts = args.get("include_drafts", False)
25
+ results = []
26
+ unreviewed = 0
27
+ incomplete = 0
28
+ with tools.repository.projects.connect(tools.project_id) as db:
29
+ rows = db.execute(
30
+ "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"
31
+ ).fetchall()
32
+ seen = set()
33
+ for row in rows:
34
+ vid = row["version_id"]
35
+ if vid not in sources or vid in seen or (version and version != vid):
36
+ continue
37
+ seen.add(vid)
38
+ source = sources[vid]
39
+ annotation = db.execute(
40
+ "SELECT * FROM transcript_annotations WHERE version_id=? AND stream_index=? AND source_revision_id=?",
41
+ (vid, row["stream_index"], row["revision_id"]),
42
+ ).fetchone()
43
+ if annotation and annotation["discarded"]:
44
+ continue
45
+ pending = bool(
46
+ (row["review_required"] or row["status"] == "needs_review")
47
+ and not (annotation and annotation["confirmed"])
48
+ )
49
+ corrections = (
50
+ {}
51
+ if annotation is None
52
+ else {str(c["ordinal"]): c["text"] for c in json.loads(annotation["corrections_json"])}
53
+ )
54
+ segments = db.execute(
55
+ "SELECT * FROM transcript_segments WHERE revision_id=? ORDER BY ordinal", (row["revision_id"],)
56
+ ).fetchall()
57
+ tb = json.loads(row["source_span_json"])["time_base"]
58
+ unit = Fraction(source["time_base"]["num"], source["time_base"]["den"])
59
+ asr_unit = Fraction(tb["num"], tb["den"])
60
+ for n, seg in enumerate(segments):
61
+ text = corrections.get(str(seg["ordinal"]), seg["text"])
62
+ if query and query not in text.casefold():
63
+ continue
64
+ if pending and not drafts:
65
+ unreviewed += 1
66
+ continue
67
+ left = int(seg["start_pts"]) * asr_unit
68
+ right = int(seg["end_pts"]) * asr_unit
69
+ if left < int(source["start_pts"]) * unit - Fraction(1, 30) or right > int(
70
+ source["end_pts"]
71
+ ) * unit + Fraction(1, 30):
72
+ incomplete += 1
73
+ continue
74
+ # Audio sample tails may exceed the last video frame. Return
75
+ # an executable video span, plus the unchanged ASR timing.
76
+ start = max(int(source["start_pts"]), math.floor(left / unit))
77
+ end = min(int(source["end_pts"]), math.ceil(right / unit))
78
+ if start >= end:
79
+ continue
80
+ results.append(
81
+ {
82
+ "version_id": vid,
83
+ "display_name": source["display_name"],
84
+ "source_revision_id": row["revision_id"],
85
+ "segment_id": seg["segment_id"],
86
+ "text": text,
87
+ "confidence": seg["confidence"],
88
+ "verification": "asr_draft" if pending else "reviewed_source",
89
+ "quality_flags": speech_flags(text) if pending else [],
90
+ "start_offset_seconds": float((start - int(source["start_pts"])) * unit),
91
+ "duration_seconds": float((end - start) * unit),
92
+ "source": {
93
+ "version_id": vid,
94
+ "stream_index": source["stream_index"],
95
+ "start_pts": str(start),
96
+ "end_pts": str(end),
97
+ "time_base": source["time_base"],
98
+ },
99
+ "asr_start_seconds": float(left),
100
+ "asr_end_seconds": float(right),
101
+ "context": [
102
+ {"segment_id": c["segment_id"], "text": corrections.get(str(c["ordinal"]), c["text"])}
103
+ for c in segments[max(0, n - 1) : n + 2]
104
+ ],
105
+ }
106
+ )
107
+ local_ranges = []
108
+ jobs = []
109
+ if hasattr(tools.repository, "production_session"):
110
+ with tools.repository.projects.connect(tools.project_id) as db:
111
+ jobs = db.execute(
112
+ "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",
113
+ (tools.run_id,),
114
+ ).fetchall()
115
+ local_seen = set()
116
+ for job in jobs:
117
+ value = json.loads(job["result_json"])
118
+ span = value["source"]
119
+ vid = span["version_id"]
120
+ if vid not in sources or (version and vid != version):
121
+ continue
122
+ source = sources[vid]
123
+ unit = Fraction(source["time_base"]["num"], source["time_base"]["den"])
124
+ local_ranges.append(span)
125
+ for n, segment in enumerate(value["segments"]):
126
+ text = segment["text"]
127
+ left = value["source_start_seconds"] + segment["start_seconds"]
128
+ right = value["source_start_seconds"] + segment["end_seconds"]
129
+ identity = (vid, round(left, 4), round(right, 4))
130
+ if identity in local_seen:
131
+ continue
132
+ local_seen.add(identity)
133
+ results = [
134
+ r
135
+ for r in results
136
+ if not (
137
+ r["version_id"] == vid
138
+ and abs(r["asr_start_seconds"] - left) < 0.05
139
+ and abs(r["asr_end_seconds"] - right) < 0.05
140
+ )
141
+ ]
142
+ if query and query not in text.casefold():
143
+ continue
144
+ if not drafts:
145
+ unreviewed += 1
146
+ continue
147
+ results.append(
148
+ {
149
+ "version_id": vid,
150
+ "display_name": source["display_name"],
151
+ "source_revision_id": job["job_id"],
152
+ "segment_id": str(n),
153
+ "text": text,
154
+ "confidence": None,
155
+ "verification": "asr_draft",
156
+ "quality_flags": speech_flags(text),
157
+ "start_offset_seconds": left - float(int(source["start_pts"]) * unit),
158
+ "duration_seconds": right - left,
159
+ "source": {
160
+ **span,
161
+ "start_pts": str(round(left / float(unit))),
162
+ "end_pts": str(round(right / float(unit))),
163
+ },
164
+ "asr_start_seconds": left,
165
+ "asr_end_seconds": right,
166
+ "context": [
167
+ {"segment_id": str(i), "text": s["text"]}
168
+ for i, s in enumerate(value["segments"][max(0, n - 1) : n + 2], max(0, n - 1))
169
+ ],
170
+ }
171
+ )
172
+ results.sort(key=lambda r: (r["display_name"], r["version_id"], r["start_offset_seconds"]))
173
+ offset = args.get("offset", 0)
174
+ limit = args.get("limit", 12)
175
+ return ToolResult(
176
+ {
177
+ "utterances": results[offset : offset + limit],
178
+ "total": len(results),
179
+ "next_offset": offset + limit if offset + limit < len(results) else None,
180
+ "unreviewed_omitted": unreviewed,
181
+ "incomplete_omitted": incomplete,
182
+ "coverage": {
183
+ "video_sources": len(sources),
184
+ "sources_with_transcripts": len(seen | {r["version_id"] for r in local_ranges}),
185
+ "untranscribed_version_ids": sorted(set(sources) - seen - {r["version_id"] for r in local_ranges}),
186
+ "local_transcribed_ranges": local_ranges,
187
+ "limitations": "A source with transcripts may still have uncovered intervals; local ranges cover only their recorded source span.",
188
+ },
189
+ "scope": "Inventoried authorized sources; only existing transcripts searched. Unknown footage is not evidence of absence. Text matches are not proof of event continuity.",
190
+ "next_step": "Choose a promising event, register_source_range around complete speech and nearby context, then inspect_candidates/sample_source.",
191
+ }
192
+ )
@@ -0,0 +1,50 @@
1
+ """Explicit analyzed ranges for retained speech; no transcript match is not absence."""
2
+
3
+ import json
4
+ from fractions import Fraction
5
+
6
+
7
+ def speech_coverage(tools):
8
+ audio_versions = {row["version_id"] for row in tools._source_rows() if row["kind"] == "audio"}
9
+ ranges = {}
10
+ with tools.repository.projects.connect(tools.project_id) as db:
11
+ local = db.execute(
12
+ "SELECT result_json FROM production_evidence_jobs WHERE run_id=? AND state='succeeded' AND kind IN ('transcribe','align')",
13
+ (tools.run_id,),
14
+ ).fetchall()
15
+ legacy = db.execute(
16
+ "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')"
17
+ ).fetchall()
18
+ spans = [json.loads(row["result_json"])["source"] for row in local] + [
19
+ json.loads(row["source_span_json"]) for row in legacy
20
+ ]
21
+ for span in spans:
22
+ unit = Fraction(span["time_base"]["num"], span["time_base"]["den"])
23
+ ranges.setdefault(span["version_id"], []).append((int(span["start_pts"]) * unit, int(span["end_pts"]) * unit))
24
+ unknown = []
25
+ fps = Fraction(tools._timeline().frame_rate.numerator, tools._timeline().frame_rate.denominator)
26
+ for clip in tools._video().items:
27
+ if clip.source.span.version_id not in audio_versions:
28
+ continue
29
+ if any(e.effect_id == "audio.source" and e.parameters["mode"] == "mute" for e in clip.effects):
30
+ continue
31
+ span = clip.source.span
32
+ unit = Fraction(span.time_base.numerator, span.time_base.denominator)
33
+ left = int(span.start_pts) * unit
34
+ right = int(span.end_pts) * unit
35
+ cursor = left
36
+ for start, end in sorted(ranges.get(span.version_id, [])):
37
+ if end <= cursor:
38
+ continue
39
+ if start > cursor + 1 / fps:
40
+ break
41
+ cursor = max(cursor, end)
42
+ if cursor < right - 1 / fps:
43
+ unknown.append(
44
+ {"item_id": clip.item_id, "source": span.to_storage(), "unknown_from_seconds": float(cursor)}
45
+ )
46
+ return {
47
+ "unknown_ranges": unknown,
48
+ "complete": not unknown,
49
+ "scope": "Local transcription coverage only; ASR correctness, hearing and semantics are separate.",
50
+ }
@@ -0,0 +1,11 @@
1
+ """Conservative ASR warning signals, not a claim that spoken repetition is wrong."""
2
+
3
+ import re
4
+
5
+
6
+ def speech_flags(text):
7
+ return (
8
+ ["repeated_asr_token_needs_listening"]
9
+ if re.search(r"\b([a-z]{3,})(?:[\s,.!?,。!?]+\1){2,}\b", text, re.I)
10
+ else []
11
+ )
@@ -0,0 +1,98 @@
1
+ """Durable mutation receipts; uncertain interrupted calls are never silently replayed."""
2
+
3
+ import hashlib
4
+ import json
5
+
6
+ from clipen.projects import ProjectError
7
+ from clipen.projects.storage import utc_now
8
+
9
+ from .agent_models import ToolResult, bounded_text, encoded
10
+
11
+ TIMELINE_MUTATIONS = frozenset(
12
+ {
13
+ "replace_sequence",
14
+ "set_clip_effect",
15
+ "undo_revision",
16
+ "finish_edit",
17
+ "set_canvas",
18
+ "set_target_duration",
19
+ "replace_clip_source",
20
+ "replace_subtitles",
21
+ "remove_item",
22
+ "trim_clip",
23
+ "reorder_clips",
24
+ "split_clip",
25
+ "insert_clip",
26
+ "set_source_audio",
27
+ "set_color_grade",
28
+ "set_mosaic",
29
+ "set_transition",
30
+ "set_fade",
31
+ "remove_clip_effect",
32
+ "place_audio",
33
+ "remove_audio",
34
+ "restore_revision",
35
+ "remove_program_component",
36
+ "add_custom_component",
37
+ "update_custom_component",
38
+ "set_component_text",
39
+ "edit_component",
40
+ "set_component_look",
41
+ "edit_component_look",
42
+ }
43
+ )
44
+
45
+
46
+ def begin_receipt(tools, name, arguments, expected_revision_id, mutation_id):
47
+ mutation_id = bounded_text(mutation_id, "操作識別", 160)
48
+ argument_hash = hashlib.sha256(
49
+ encoded({"arguments": arguments, "expected_revision_id": expected_revision_id}).encode()
50
+ ).hexdigest()
51
+ with tools.repository.projects.connect(tools.project_id) as db:
52
+ db.execute("BEGIN IMMEDIATE")
53
+ row = db.execute(
54
+ "SELECT * FROM production_tool_receipts WHERE run_id=? AND mutation_id=?", (tools.run_id, mutation_id)
55
+ ).fetchone()
56
+ if row:
57
+ if row["tool_name"] != name or row["arguments_hash"] != argument_hash:
58
+ raise ProjectError("request_reused", "這個操作識別已用於其他參數。", status_code=409)
59
+ if row["state"] == "started":
60
+ raise ProjectError(
61
+ "tool_outcome_unknown",
62
+ "先前操作在回報前中斷;請讀取目前版本與紀錄確認結果,不要直接重送。",
63
+ status_code=409,
64
+ )
65
+ payload = json.loads(row["result_json"])
66
+ if row["state"] == "failed":
67
+ raise ProjectError(payload["error"], payload["message"], status_code=409)
68
+ db.rollback()
69
+ return ToolResult({**payload, "replayed": True})
70
+ current = tools.repository._read_run(db, tools.run_id)
71
+ if expected_revision_id is not None and expected_revision_id != current.current_revision_id:
72
+ raise ProjectError("revision_conflict", "作品版本已更新,請重新讀取後修改。", status_code=409)
73
+ if current.state != "running" and not (
74
+ getattr(tools, "_user_edit", False) and current.state not in {"queued", "running"}
75
+ ):
76
+ raise ProjectError("edit_agent_not_running", "AI 製作目前未在執行。", status_code=409)
77
+ db.execute(
78
+ "INSERT INTO production_tool_receipts VALUES(?,?,?,?,?,?,?)",
79
+ (tools.run_id, mutation_id, name, argument_hash, "started", None, utc_now()),
80
+ )
81
+ db.commit()
82
+ return None
83
+
84
+
85
+ def finish_receipt(tools, mutation_id, *, result=None, error=None):
86
+ payload = (
87
+ dict(result.payload)
88
+ if error is None
89
+ else {
90
+ "error": getattr(error, "code", "tool_failed"),
91
+ "message": getattr(error, "message", "這次操作未完成,請查看作品版本與紀錄。"),
92
+ }
93
+ )
94
+ with tools.repository.projects.connect(tools.project_id) as db:
95
+ db.execute(
96
+ "UPDATE production_tool_receipts SET state=?,result_json=? WHERE run_id=? AND mutation_id=? AND state='started'",
97
+ ("completed" if error is None else "failed", encoded(payload), tools.run_id, mutation_id),
98
+ )
@@ -0,0 +1,219 @@
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
+
9
+ import json
10
+ import sqlite3
11
+
12
+ from clipen.provider_registry import get_provider
13
+
14
+ _STOPS = {"provider_failed", "run_cancelled", "run_interrupted", "budget_exhausted"}
15
+ _STOP_REASONS = {
16
+ "provider_usage_limit": "額度不足時停下",
17
+ "provider_timed_out": "超過時間上限時停下",
18
+ "provider_authentication_required": "登入過期時停下",
19
+ "provider_stopped_early": "AI 提早結束",
20
+ "delivery_blocked": "交付檢查未通過",
21
+ "provider_network_error": "連線中斷時停下",
22
+ }
23
+ # Labels for manual edits: rewording a graphic now, and the edits earlier Clipen versions allowed.
24
+ _MANUAL = {
25
+ "edit_text": "文字與時間",
26
+ "configure_text_style": "文字外觀",
27
+ "remove_item": "刪除元素",
28
+ "trim_clip": "裁切片段",
29
+ "reorder_clips": "重排片段",
30
+ "split_clip": "分割片段",
31
+ "replace_clip_source": "替換來源",
32
+ "insert_clip": "插入片段",
33
+ "set_source_audio": "原音",
34
+ "set_color_grade": "調色",
35
+ "set_mosaic": "馬賽克",
36
+ "set_transition": "轉場",
37
+ "set_fade": "淡入淡出",
38
+ "remove_clip_effect": "移除效果",
39
+ "place_audio": "音樂與音效",
40
+ "remove_audio": "移除聲音",
41
+ "remove_program_component": "移除節目元件",
42
+ "add_custom_component": "新增自由設計元件",
43
+ "update_custom_component": "修改自由設計元件",
44
+ "set_component_text": "元件文字",
45
+ "edit_component": "修改元件",
46
+ "edit_component_look": "元件外觀",
47
+ }
48
+
49
+
50
+ def _name(provider_id):
51
+ try:
52
+ return get_provider(provider_id).display_name
53
+ except ValueError:
54
+ return "AI"
55
+
56
+
57
+ def versions(database, run_id, provider, styles=None, current=None):
58
+ """Versions of one film, newest first, each saying what changed. `provider` is the run's current AI;
59
+ `current` the revision the film is at now, which is always the newest entry."""
60
+ rows = database.execute(
61
+ "SELECT sequence,event_type,payload_json,created_at FROM edit_agent_events WHERE run_id=? AND event_type IN "
62
+ "('run_created','refinement_requested','revision_created','revision_selected','run_finished','provider_failed','run_cancelled',"
63
+ "'run_interrupted','budget_exhausted','tool_completed','provider_switched','provider_finished') ORDER BY sequence",
64
+ (run_id,),
65
+ ).fetchall()
66
+ switches = [json.loads(r["payload_json"]) for r in rows if r["event_type"] == "provider_switched"]
67
+ current_ai = switches[0]["from"] if switches else provider
68
+ latest = start = None
69
+ request = None
70
+ sent = {}
71
+ result = []
72
+
73
+ skipped = []
74
+ # Tokens an AI attempt used, waiting for the version that attempt produced.
75
+ pending, last_ai, span = None, None, 0
76
+
77
+ def add(kind, label, created_at, detail=None):
78
+ nonlocal pending, last_ai
79
+ if latest is None or (result and result[-1]["revision_id"] == latest):
80
+ if latest is not None:
81
+ skipped.append((kind, label, created_at))
82
+ return
83
+ entry = {"revision_id": latest, "kind": kind, "label": label, "detail": detail, "created_at": created_at}
84
+ if kind.startswith("ai_"):
85
+ entry["usage"], pending, last_ai = pending, None, (entry, span)
86
+ result.append(entry)
87
+
88
+ for row in rows:
89
+ kind, payload = row["event_type"], json.loads(row["payload_json"])
90
+ usage = payload.get("usage") if kind in ("provider_finished", "provider_failed") else None
91
+ if isinstance(usage, dict):
92
+ # A finished attempt reports after its version is listed; a stopped one before.
93
+ if kind == "provider_finished" and last_ai is not None and last_ai[1] == span:
94
+ last_ai[0]["usage"] = add_usage(last_ai[0]["usage"], usage)
95
+ else:
96
+ pending = add_usage(pending, usage)
97
+ if kind in ("run_created", "refinement_requested"):
98
+ # An attempt that changed nothing has no version to show it; it still counts in the film's total.
99
+ span, pending = span + 1, None
100
+ if kind in ("revision_created", "revision_selected"):
101
+ latest = payload.get("revision_id", latest)
102
+ if start is None:
103
+ start = latest
104
+ elif kind == "run_created":
105
+ request, start, sent = None, latest, {}
106
+ elif kind == "refinement_requested":
107
+ request, start = payload.get("instruction"), payload.get("base_revision_id", latest)
108
+ sent = {
109
+ item.get("reference_id"): item
110
+ for item in (payload.get("references") or {}).get("items", [])
111
+ if isinstance(item, dict)
112
+ }
113
+ elif kind == "provider_switched":
114
+ current_ai = payload.get("to", current_ai)
115
+ elif kind == "run_finished":
116
+ add("ai_complete", f"{_name(current_ai)} {'打磨' if request else '製作'}完成", row["created_at"], request)
117
+ if result and result[-1]["revision_id"] == latest:
118
+ result[-1]["report"] = _report(payload, sent)
119
+ start = latest
120
+ elif kind in _STOPS:
121
+ # A stop that changed nothing is not a version.
122
+ if latest != start:
123
+ reason = _STOP_REASONS.get(payload.get("error_code"), "製作中斷")
124
+ add("ai_partial", f"{_name(current_ai)} 未完成({reason})", row["created_at"], request)
125
+ start = latest
126
+ elif kind == "tool_completed" and payload.get("authority") == "user":
127
+ tool = payload.get("tool")
128
+ add(
129
+ "restore" if tool == "restore_revision" else "manual",
130
+ "還原版本" if tool == "restore_revision" else f"手動修改:{_MANUAL.get(tool, '編輯')}",
131
+ row["created_at"],
132
+ )
133
+ start = latest
134
+ # Older projects did not record a step that went back to an earlier picture; show where the film is now.
135
+ if current and result and result[-1]["revision_id"] != current and skipped:
136
+ kind, label, created_at = skipped[-1]
137
+ result.append({"revision_id": current, "kind": kind, "label": label, "detail": None, "created_at": created_at})
138
+ _describe(database, run_id, result, styles or {})
139
+ for number, entry in enumerate(result, 1):
140
+ entry["number"] = number
141
+ return list(reversed(result))
142
+
143
+
144
+ def _report(payload, sent):
145
+ """What the AI said it changed, with each answer placed next to the note it answers."""
146
+ from .change_report import OUTCOMES
147
+
148
+ report = payload.get("report") or {}
149
+ notes = [
150
+ {
151
+ **note,
152
+ "outcome_label": OUTCOMES.get(note.get("outcome"), ""),
153
+ "kind": (sent.get(note.get("reference_id")) or {}).get("kind"),
154
+ "note": (sent.get(note.get("reference_id")) or {}).get("note", ""),
155
+ }
156
+ for note in report.get("notes", [])
157
+ ]
158
+ from .change_report import REASONS
159
+
160
+ # Reports written before reasons were required hold plain lines.
161
+ left = [
162
+ {"what": item, "reason": None, "reason_label": "", "detail": ""}
163
+ if isinstance(item, str)
164
+ else {**item, "reason_label": REASONS.get(item.get("reason"), "")}
165
+ for item in report.get("not_done", [])
166
+ ]
167
+ for note in notes:
168
+ note["reason_label"] = REASONS.get(note.get("reason"), "")
169
+ return {
170
+ "summary": payload.get("summary") or "",
171
+ "changes": report.get("changes", []),
172
+ "notes": notes,
173
+ "not_done": left,
174
+ }
175
+
176
+
177
+ def add_usage(total, usage):
178
+ keys = ("input_tokens", "cached_input_tokens", "output_tokens")
179
+ if not isinstance(usage, dict) or not all(isinstance(usage.get(k), int) for k in keys):
180
+ return total
181
+ return {k: (total or {}).get(k, 0) + usage[k] for k in keys}
182
+
183
+
184
+ def film_usage(database, run_id):
185
+ """Every token the AI used on this film, including attempts that changed nothing."""
186
+ total = None
187
+ for row in database.execute(
188
+ "SELECT payload_json FROM edit_agent_events WHERE run_id=? AND event_type IN ('provider_finished','provider_failed')",
189
+ (run_id,),
190
+ ):
191
+ total = add_usage(total, json.loads(row["payload_json"]).get("usage"))
192
+ return total
193
+
194
+
195
+ def _describe(database, run_id, result, styles):
196
+ """What each version changed from the one before it, and which moment a restore went back to."""
197
+ from .history_changes import describe, summary
198
+
199
+ ids = sorted({entry["revision_id"] for entry in result})
200
+ payloads = {}
201
+ try:
202
+ for start in range(0, len(ids), 400):
203
+ chunk = ids[start : start + 400]
204
+ for row in database.execute(
205
+ f"SELECT revision_id,payload_json FROM edit_agent_revisions WHERE run_id=? AND revision_id IN ({','.join('?' * len(chunk))})",
206
+ (run_id, *chunk),
207
+ ):
208
+ payloads[row["revision_id"]] = json.loads(row["payload_json"])
209
+ except sqlite3.OperationalError:
210
+ pass # Without stored pictures the history still lists every step, only without what changed.
211
+ for index, entry in enumerate(result):
212
+ earlier = next((e for e in reversed(result[:index]) if e["revision_id"] == entry["revision_id"]), None)
213
+ if entry["kind"] == "restore" and earlier is not None:
214
+ entry["restored_from"] = earlier["created_at"]
215
+ before, after = (
216
+ (payloads.get(result[index - 1]["revision_id"]) if index else None),
217
+ payloads.get(entry["revision_id"]),
218
+ )
219
+ entry["changes"] = summary(describe(before, after, styles)) if before and after else None