@clipen/clipen-cli 1.0.0 → 1.0.2

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 (132) hide show
  1. package/README.md +56 -48
  2. package/apps/web/dist/assets/{index-D5D2HiB1.js → index-DPHwA954.js} +1 -1
  3. package/apps/web/dist/index.html +1 -1
  4. package/bin/clipen.js +1 -1
  5. package/package.json +7 -6
  6. package/pyproject.toml +18 -2
  7. package/requirements/dev.txt +2 -0
  8. package/src/clipen/__init__.py +1 -1
  9. package/src/clipen/analysis/__init__.py +7 -7
  10. package/src/clipen/analysis/artifacts.py +4 -10
  11. package/src/clipen/analysis/audio.py +10 -8
  12. package/src/clipen/analysis/evidence_service.py +345 -167
  13. package/src/clipen/analysis/image_similarity.py +5 -14
  14. package/src/clipen/analysis/keyframes.py +5 -17
  15. package/src/clipen/analysis/models.py +5 -7
  16. package/src/clipen/analysis/qwen_worker.py +19 -54
  17. package/src/clipen/analysis/resources.py +2 -1
  18. package/src/clipen/analysis/runtime.py +1 -3
  19. package/src/clipen/analysis/service.py +16 -48
  20. package/src/clipen/analysis/setup.py +11 -25
  21. package/src/clipen/analysis/setup_cli.py +5 -15
  22. package/src/clipen/analysis/storage.py +96 -278
  23. package/src/clipen/analysis/transcription.py +40 -82
  24. package/src/clipen/analysis/visual.py +109 -48
  25. package/src/clipen/annotations/__init__.py +5 -2
  26. package/src/clipen/annotations/models.py +1 -1
  27. package/src/clipen/annotations/storage.py +132 -84
  28. package/src/clipen/annotations/suggestions.py +3 -8
  29. package/src/clipen/asr_release.py +4 -11
  30. package/src/clipen/bootstrap.py +71 -61
  31. package/src/clipen/{planning/models.py → candidates.py} +29 -47
  32. package/src/clipen/cli.py +4 -9
  33. package/src/clipen/controller/app.py +401 -214
  34. package/src/clipen/controller/server.py +28 -38
  35. package/src/clipen/domain/__init__.py +1 -1
  36. package/src/clipen/domain/media_time.py +3 -10
  37. package/src/clipen/domain/timeline.py +45 -47
  38. package/src/clipen/domain/validation.py +0 -1
  39. package/src/clipen/editing/__init__.py +1 -1
  40. package/src/clipen/editing/agent_models.py +4 -11
  41. package/src/clipen/editing/agent_repository.py +393 -172
  42. package/src/clipen/editing/agent_tools.py +180 -99
  43. package/src/clipen/editing/alignment.py +92 -52
  44. package/src/clipen/editing/alignment_setup.py +118 -70
  45. package/src/clipen/editing/alignment_worker.py +11 -9
  46. package/src/clipen/editing/change_report.py +95 -38
  47. package/src/clipen/editing/compiler.py +0 -1
  48. package/src/clipen/editing/component_looks.py +58 -34
  49. package/src/clipen/editing/component_review.py +34 -38
  50. package/src/clipen/editing/coordinator.py +213 -92
  51. package/src/clipen/editing/editorial_review.py +217 -95
  52. package/src/clipen/editing/evidence_jobs.py +457 -200
  53. package/src/clipen/editing/history_changes.py +129 -68
  54. package/src/clipen/editing/music_choices.py +8 -5
  55. package/src/clipen/editing/production_catalog.py +573 -136
  56. package/src/clipen/editing/production_limits.py +43 -17
  57. package/src/clipen/editing/production_media.py +376 -167
  58. package/src/clipen/editing/production_preview.py +322 -129
  59. package/src/clipen/editing/production_progress.py +164 -69
  60. package/src/clipen/editing/production_requirements.py +106 -39
  61. package/src/clipen/editing/production_tools.py +1064 -462
  62. package/src/clipen/editing/program_audio.py +211 -81
  63. package/src/clipen/editing/program_direction.py +59 -25
  64. package/src/clipen/editing/program_story.py +83 -45
  65. package/src/clipen/editing/program_subtitles.py +194 -96
  66. package/src/clipen/editing/programme_review.py +98 -50
  67. package/src/clipen/editing/prompt_history.py +64 -27
  68. package/src/clipen/editing/recut.py +65 -25
  69. package/src/clipen/editing/refinement_references.py +176 -86
  70. package/src/clipen/editing/resolve_export.py +449 -218
  71. package/src/clipen/editing/resolve_titles.py +162 -105
  72. package/src/clipen/editing/skill_tools.py +530 -154
  73. package/src/clipen/editing/source_dialogue.py +177 -67
  74. package/src/clipen/editing/speech_coverage.py +42 -22
  75. package/src/clipen/editing/speech_quality.py +6 -1
  76. package/src/clipen/editing/tool_receipts.py +78 -32
  77. package/src/clipen/editing/versions.py +122 -64
  78. package/src/clipen/editing/visual_preview.py +157 -61
  79. package/src/clipen/editing/workbench.py +104 -42
  80. package/src/clipen/finishing/audio.py +69 -30
  81. package/src/clipen/finishing/catalog.py +176 -93
  82. package/src/clipen/finishing/models.py +1 -1
  83. package/src/clipen/finishing/renderer.py +33 -14
  84. package/src/clipen/mcp_editing/__main__.py +3 -1
  85. package/src/clipen/mcp_editing/server.py +77 -34
  86. package/src/clipen/media/__init__.py +3 -3
  87. package/src/clipen/media/discovery.py +7 -20
  88. package/src/clipen/media/models.py +7 -18
  89. package/src/clipen/media/preview.py +14 -24
  90. package/src/clipen/media/probe.py +16 -44
  91. package/src/clipen/media/service.py +6 -19
  92. package/src/clipen/media/storage.py +33 -81
  93. package/src/clipen/music_vocabulary.py +33 -4
  94. package/src/clipen/power.py +8 -3
  95. package/src/clipen/projects/__init__.py +1 -1
  96. package/src/clipen/projects/deletion.py +19 -32
  97. package/src/clipen/projects/finishing_schema.py +3 -1
  98. package/src/clipen/projects/models.py +2 -5
  99. package/src/clipen/projects/picker.py +13 -37
  100. package/src/clipen/projects/service.py +8 -24
  101. package/src/clipen/projects/storage.py +226 -246
  102. package/src/clipen/provider_registry.py +9 -20
  103. package/src/clipen/providers/account.py +86 -35
  104. package/src/clipen/providers/claude.py +59 -25
  105. package/src/clipen/providers/claude_editing.py +14 -7
  106. package/src/clipen/providers/codex.py +73 -118
  107. package/src/clipen/providers/codex_editing.py +2 -2
  108. package/src/clipen/providers/editing_agent.py +19 -17
  109. package/src/clipen/providers/recovery.py +7 -8
  110. package/src/clipen/rendering/cover.py +18 -5
  111. package/src/clipen/rendering/custom_components.py +167 -79
  112. package/src/clipen/rendering/custom_render.py +62 -41
  113. package/src/clipen/rendering/production_effects.py +77 -45
  114. package/src/clipen/rendering/program_components.py +134 -73
  115. package/src/clipen/rendering/program_creator.py +432 -277
  116. package/src/clipen/rendering/program_identities.py +277 -182
  117. package/src/clipen/rendering/program_motion.py +140 -95
  118. package/src/clipen/rendering/program_studio.py +175 -116
  119. package/src/clipen/rendering/program_styles.py +231 -145
  120. package/src/clipen/rendering/program_subtitles.py +71 -34
  121. package/src/clipen/rendering/renderer.py +150 -121
  122. package/src/clipen/rendering/storage.py +9 -22
  123. package/src/clipen/rendering/titles.py +193 -86
  124. package/src/clipen/skills/__init__.py +1 -0
  125. package/src/clipen/skills/catalog.py +151 -55
  126. package/src/clipen/skills/library.py +13 -7
  127. package/src/clipen/skills/package.py +46 -23
  128. package/src/clipen/skills/visual_styles.py +29 -18
  129. package/src/clipen/workspace.py +15 -44
  130. package/install +0 -25
  131. package/src/clipen/planning/__init__.py +0 -9
  132. package/uninstall +0 -25
@@ -1,82 +1,192 @@
1
1
  """Search current source speech before picking a cut; no synthetic event labels."""
2
- from fractions import Fraction
2
+
3
3
  import json
4
4
  import math
5
- from .production_media import source_rows
5
+ from fractions import Fraction
6
+
6
7
  from .agent_models import ToolResult
8
+ from .production_media import source_rows
7
9
 
8
10
 
9
- def search_dialogue(tools,args):
11
+ def search_dialogue(tools, args):
10
12
  from .speech_quality import speech_flags
11
- sources={}
12
- for source in (tools._source_rows() if hasattr(tools,'_source_rows') else source_rows(tools.repository.projects,tools.project_id)):
13
- if source['kind']=='video':sources.setdefault(source['version_id'],source)
14
- query=args.get('query','').strip().casefold();version=args.get('version_id');drafts=args.get('include_drafts',False)
15
- results=[];unreviewed=0;incomplete=0
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
16
28
  with tools.repository.projects.connect(tools.project_id) as db:
17
- rows=db.execute("SELECT tr.*,pi.review_required FROM current_preparation cp JOIN preparation_items pi ON pi.run_id=cp.run_id JOIN transcription_revisions tr ON tr.revision_id=pi.transcript_revision_id WHERE tr.status IN ('transcribed','needs_review') AND tr.stream_index=(SELECT MIN(stream_index) FROM media_streams WHERE version_id=tr.version_id AND kind='audio') ORDER BY tr.version_id,tr.revision_id").fetchall()
18
- seen=set()
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()
19
33
  for row in rows:
20
- vid=row['version_id']
21
- if vid not in sources or vid in seen or (version and version!=vid):continue
22
- seen.add(vid);source=sources[vid]
23
- annotation=db.execute('SELECT * FROM transcript_annotations WHERE version_id=? AND stream_index=? AND source_revision_id=?',(vid,row['stream_index'],row['revision_id'])).fetchone()
24
- if annotation and annotation['discarded']:continue
25
- pending=bool((row['review_required'] or row['status']=='needs_review') and not (annotation and annotation['confirmed']))
26
- corrections={} if annotation is None else {str(c['ordinal']):c['text'] for c in json.loads(annotation['corrections_json'])}
27
- segments=db.execute('SELECT * FROM transcript_segments WHERE revision_id=? ORDER BY ordinal',(row['revision_id'],)).fetchall()
28
- tb=json.loads(row['source_span_json'])['time_base'];unit=Fraction(source['time_base']['num'],source['time_base']['den']);asr_unit=Fraction(tb['num'],tb['den'])
29
- for n,seg in enumerate(segments):
30
- text=corrections.get(str(seg['ordinal']),seg['text'])
31
- if query and query not in text.casefold():continue
32
- if pending and not drafts:unreviewed+=1;continue
33
- left=int(seg['start_pts'])*asr_unit;right=int(seg['end_pts'])*asr_unit
34
- if left<int(source['start_pts'])*unit-Fraction(1,30) or right>int(source['end_pts'])*unit+Fraction(1,30):
35
- incomplete+=1;continue
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
36
74
  # Audio sample tails may exceed the last video frame. Return
37
75
  # an executable video span, plus the unchanged ASR timing.
38
- start=max(int(source['start_pts']),math.floor(left/unit));end=min(int(source['end_pts']),math.ceil(right/unit))
39
- if start>=end:continue
40
- results.append({'version_id':vid,'display_name':source['display_name'],'source_revision_id':row['revision_id'],
41
- 'segment_id':seg['segment_id'],'text':text,'confidence':seg['confidence'],
42
- 'verification':'asr_draft' if pending else 'reviewed_source',
43
- 'quality_flags':speech_flags(text) if pending else [],
44
- 'start_offset_seconds':float((start-int(source['start_pts']))*unit),'duration_seconds':float((end-start)*unit),
45
- 'source':{'version_id':vid,'stream_index':source['stream_index'],'start_pts':str(start),'end_pts':str(end),'time_base':source['time_base']},
46
- 'asr_start_seconds':float(left),'asr_end_seconds':float(right),
47
- 'context':[{'segment_id':c['segment_id'],'text':corrections.get(str(c['ordinal']),c['text'])} for c in segments[max(0,n-1):n+2]]})
48
- local_ranges=[]
49
- jobs=[]
50
- if hasattr(tools.repository,'production_session'):
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"):
51
110
  with tools.repository.projects.connect(tools.project_id) as db:
52
- jobs=db.execute("SELECT job_id,result_json FROM production_evidence_jobs WHERE run_id=? AND state='succeeded' AND kind IN ('transcribe','align') ORDER BY created_at DESC,rowid DESC",(tools.run_id,)).fetchall()
53
- local_seen=set()
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()
54
116
  for job in jobs:
55
- value=json.loads(job['result_json']);span=value['source'];vid=span['version_id']
56
- if vid not in sources or (version and vid!=version):continue
57
- source=sources[vid];unit=Fraction(source['time_base']['num'],source['time_base']['den'])
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"])
58
124
  local_ranges.append(span)
59
- for n,segment in enumerate(value['segments']):
60
- text=segment['text'];left=value['source_start_seconds']+segment['start_seconds'];right=value['source_start_seconds']+segment['end_seconds']
61
- identity=(vid,round(left,4),round(right,4))
62
- if identity in local_seen:continue
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
63
132
  local_seen.add(identity)
64
- results=[r for r in results if not (r['version_id']==vid and abs(r['asr_start_seconds']-left)<.05 and abs(r['asr_end_seconds']-right)<.05)]
65
- if query and query not in text.casefold():continue
66
- if not drafts:unreviewed+=1;continue
67
- results.append({'version_id':vid,'display_name':source['display_name'],'source_revision_id':job['job_id'],
68
- 'segment_id':str(n),'text':text,'confidence':None,'verification':'asr_draft','quality_flags':speech_flags(text),
69
- 'start_offset_seconds':left-float(int(source['start_pts'])*unit),'duration_seconds':right-left,
70
- 'source':{**span,'start_pts':str(round(left/float(unit))),'end_pts':str(round(right/float(unit)))},
71
- 'asr_start_seconds':left,'asr_end_seconds':right,
72
- 'context':[{'segment_id':str(i),'text':s['text']} for i,s in enumerate(value['segments'][max(0,n-1):n+2],max(0,n-1))]})
73
- results.sort(key=lambda r:(r['display_name'],r['version_id'],r['start_offset_seconds']))
74
- offset=args.get('offset',0);limit=args.get('limit',12)
75
- return ToolResult({'utterances':results[offset:offset+limit],'total':len(results),'next_offset':offset+limit if offset+limit<len(results) else None,
76
- 'unreviewed_omitted':unreviewed,'incomplete_omitted':incomplete,
77
- 'coverage': {'video_sources': len(sources), 'sources_with_transcripts': len(seen|{r['version_id'] for r in local_ranges}),
78
- 'untranscribed_version_ids': sorted(set(sources)-seen-{r['version_id'] for r in local_ranges}),
79
- 'local_transcribed_ranges':local_ranges,
80
- 'limitations':'A source with transcripts may still have uncovered intervals; local ranges cover only their recorded source span.'},
81
- 'scope':'Inventoried authorized sources; only existing transcripts searched. Unknown footage is not evidence of absence. Text matches are not proof of event continuity.',
82
- 'next_step':'Choose a promising event, register_source_range around complete speech and nearby context, then inspect_candidates/sample_source.'})
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
+ )
@@ -1,30 +1,50 @@
1
1
  """Explicit analyzed ranges for retained speech; no transcript match is not absence."""
2
- from fractions import Fraction
2
+
3
3
  import json
4
+ from fractions import Fraction
4
5
 
5
6
 
6
7
  def speech_coverage(tools):
7
- audio_versions={row['version_id'] for row in tools._source_rows() if row['kind']=='audio'}
8
- ranges={}
8
+ audio_versions = {row["version_id"] for row in tools._source_rows() if row["kind"] == "audio"}
9
+ ranges = {}
9
10
  with tools.repository.projects.connect(tools.project_id) as db:
10
- local=db.execute("SELECT result_json FROM production_evidence_jobs WHERE run_id=? AND state='succeeded' AND kind IN ('transcribe','align')",(tools.run_id,)).fetchall()
11
- legacy=db.execute("SELECT tr.source_span_json FROM current_preparation cp JOIN preparation_items pi ON pi.run_id=cp.run_id JOIN transcription_revisions tr ON tr.revision_id=pi.transcript_revision_id WHERE pi.status IN ('transcribed','no_speech') AND tr.status IN ('transcribed','needs_review','no_speech_detected')").fetchall()
12
- spans=[json.loads(row['result_json'])['source'] for row in local]+[json.loads(row['source_span_json']) for row in legacy]
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
+ ]
13
21
  for span in spans:
14
- unit=Fraction(span['time_base']['num'],span['time_base']['den'])
15
- ranges.setdefault(span['version_id'],[]).append((int(span['start_pts'])*unit,int(span['end_pts'])*unit))
16
- unknown=[]
17
- fps=Fraction(tools._timeline().frame_rate.numerator,tools._timeline().frame_rate.denominator)
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)
18
26
  for clip in tools._video().items:
19
- if clip.source.span.version_id not in audio_versions:continue
20
- if any(e.effect_id=='audio.source' and e.parameters['mode']=='mute' for e in clip.effects):continue
21
- span=clip.source.span;unit=Fraction(span.time_base.numerator,span.time_base.denominator)
22
- left=int(span.start_pts)*unit;right=int(span.end_pts)*unit;cursor=left
23
- for start,end in sorted(ranges.get(span.version_id,[])):
24
- if end<=cursor:continue
25
- if start>cursor+1/fps:break
26
- cursor=max(cursor,end)
27
- if cursor<right-1/fps:
28
- unknown.append({'item_id':clip.item_id,'source':span.to_storage(),'unknown_from_seconds':float(cursor)})
29
- return {'unknown_ranges':unknown,'complete':not unknown,
30
- 'scope':'Local transcription coverage only; ASR correctness, hearing and semantics are separate.'}
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
+ }
@@ -1,6 +1,11 @@
1
1
  """Conservative ASR warning signals, not a claim that spoken repetition is wrong."""
2
+
2
3
  import re
3
4
 
4
5
 
5
6
  def speech_flags(text):
6
- return ['repeated_asr_token_needs_listening'] if re.search(r'\b([a-z]{3,})(?:[\s,.!?,。!?]+\1){2,}\b',text,re.I) else []
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
+ )
@@ -1,52 +1,98 @@
1
1
  """Durable mutation receipts; uncertain interrupted calls are never silently replayed."""
2
+
2
3
  import hashlib
3
4
  import json
4
5
 
5
6
  from clipen.projects import ProjectError
6
7
  from clipen.projects.storage import utc_now
8
+
7
9
  from .agent_models import ToolResult, bounded_text, encoded
8
10
 
9
- TIMELINE_MUTATIONS = frozenset({
10
- 'replace_sequence','set_clip_effect','undo_revision','finish_edit',
11
- 'set_canvas','set_target_duration','replace_clip_source','replace_subtitles',
12
- 'remove_item','trim_clip','reorder_clips','split_clip','insert_clip',
13
- 'set_source_audio','set_color_grade','set_mosaic','set_transition','set_fade',
14
- 'remove_clip_effect','place_audio','remove_audio','restore_revision',
15
- 'remove_program_component','add_custom_component','update_custom_component',
16
- 'set_component_text','edit_component','set_component_look','edit_component_look',
17
- })
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
+ )
18
44
 
19
45
 
20
46
  def begin_receipt(tools, name, arguments, expected_revision_id, mutation_id):
21
- mutation_id=bounded_text(mutation_id,'操作識別',160)
22
- argument_hash=hashlib.sha256(encoded({'arguments':arguments,'expected_revision_id':expected_revision_id}).encode()).hexdigest()
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()
23
51
  with tools.repository.projects.connect(tools.project_id) as db:
24
- db.execute('BEGIN IMMEDIATE')
25
- row=db.execute('SELECT * FROM production_tool_receipts WHERE run_id=? AND mutation_id=?',(tools.run_id,mutation_id)).fetchone()
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()
26
56
  if row:
27
- if row['tool_name']!=name or row['arguments_hash']!=argument_hash:
28
- raise ProjectError('request_reused','這個操作識別已用於其他參數。',status_code=409)
29
- if row['state']=='started':
30
- raise ProjectError('tool_outcome_unknown','先前操作在回報前中斷;請讀取目前版本與紀錄確認結果,不要直接重送。',status_code=409)
31
- payload=json.loads(row['result_json'])
32
- if row['state']=='failed':
33
- raise ProjectError(payload['error'],payload['message'],status_code=409)
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)
34
68
  db.rollback()
35
- return ToolResult({**payload,'replayed':True})
36
- current=tools.repository._read_run(db,tools.run_id)
37
- if expected_revision_id is not None and expected_revision_id!=current.current_revision_id:
38
- raise ProjectError('revision_conflict','作品版本已更新,請重新讀取後修改。',status_code=409)
39
- if current.state!='running' and not (getattr(tools,'_user_edit',False) and current.state not in {'queued','running'}):
40
- raise ProjectError('edit_agent_not_running','AI 製作目前未在執行。',status_code=409)
41
- db.execute('INSERT INTO production_tool_receipts VALUES(?,?,?,?,?,?,?)',
42
- (tools.run_id,mutation_id,name,argument_hash,'started',None,utc_now()))
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
+ )
43
81
  db.commit()
44
82
  return None
45
83
 
46
84
 
47
85
  def finish_receipt(tools, mutation_id, *, result=None, error=None):
48
- payload=dict(result.payload) if error is None else {'error':getattr(error,'code','tool_failed'),
49
- 'message':getattr(error,'message','這次操作未完成,請查看作品版本與紀錄。')}
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
+ )
50
94
  with tools.repository.projects.connect(tools.project_id) as db:
51
- db.execute("UPDATE production_tool_receipts SET state=?,result_json=? WHERE run_id=? AND mutation_id=? AND state='started'",
52
- ('completed' if error is None else 'failed',encoded(payload),tools.run_id,mutation_id))
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
+ )