@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,134 +1,232 @@
1
1
  """Source-linked programme captions; draft ASR never becomes human approval."""
2
- import unicodedata
3
- import re
2
+
4
3
  import math
4
+ import re
5
+ import unicodedata
6
+
5
7
  from clipen.domain import TextClip
6
8
  from clipen.finishing.models import digest
7
9
  from clipen.projects import ProjectError
8
- from .production_media import load_text_styles, atomic_json, text_style_path
10
+
11
+ from .production_media import atomic_json, load_text_styles, text_style_path
9
12
 
10
13
 
11
- def make_subtitle_items(tools,cue,row):
12
- text=row['text'].strip()
13
- if not text:raise ProjectError('agent_input_invalid','字幕不可空白。',status_code=422)
14
+ def make_subtitle_items(tools, cue, row):
15
+ text = row["text"].strip()
16
+ if not text:
17
+ raise ProjectError("agent_input_invalid", "字幕不可空白。", status_code=422)
18
+
14
19
  def spoken_content(value):
15
- return ''.join(c.casefold() for c in unicodedata.normalize('NFKC',value) if unicodedata.category(c)[0] not in 'PZC')
16
- original=cue;excerpt=row.get('source_excerpt');source_text=cue['text']
20
+ return "".join(
21
+ c.casefold() for c in unicodedata.normalize("NFKC", value) if unicodedata.category(c)[0] not in "PZC"
22
+ )
23
+
24
+ original = cue
25
+ excerpt = row.get("source_excerpt")
26
+ source_text = cue["text"]
17
27
  if excerpt:
18
- left,right=excerpt['start'],excerpt['end']
19
- if not 0<=left<right<=len(source_text):raise ProjectError('subtitle_source_mismatch','字幕引用字元範圍超出來源句。',status_code=422)
20
- begin=cue['duration_frames']*left//len(source_text);end=cue['duration_frames']*right//len(source_text)
21
- cue={**cue,'text':source_text[left:right],'start_frame':cue['start_frame']+begin,'duration_frames':end-begin}
22
- if (excerpt or cue.get('verification')=='asr_draft') and spoken_content(text)!=spoken_content(cue['text']):
23
- raise ProjectError('subtitle_source_mismatch','未核對字幕草稿可以調整標點與分句,不能改寫原話內容或加入新事實;請先核對來源逐字稿。',status_code=422)
28
+ left, right = excerpt["start"], excerpt["end"]
29
+ if not 0 <= left < right <= len(source_text):
30
+ raise ProjectError("subtitle_source_mismatch", "字幕引用字元範圍超出來源句。", status_code=422)
31
+ begin = cue["duration_frames"] * left // len(source_text)
32
+ end = cue["duration_frames"] * right // len(source_text)
33
+ cue = {
34
+ **cue,
35
+ "text": source_text[left:right],
36
+ "start_frame": cue["start_frame"] + begin,
37
+ "duration_frames": end - begin,
38
+ }
39
+ if (excerpt or cue.get("verification") == "asr_draft") and spoken_content(text) != spoken_content(cue["text"]):
40
+ raise ProjectError(
41
+ "subtitle_source_mismatch",
42
+ "未核對字幕草稿可以調整標點與分句,不能改寫原話內容或加入新事實;請先核對來源逐字稿。",
43
+ status_code=422,
44
+ )
24
45
  from .speech_quality import speech_flags
25
- if cue.get('verification')=='asr_draft' and speech_flags(text):
26
- raise ProjectError('subtitle_draft_unreliable','這段 ASR 有可疑的連續重複詞,不能直接作為字幕。請用 source_excerpt 引用原句中可用的部分,或略過這段字幕並保留原音;不可編造替代台詞。',status_code=422)
46
+
47
+ if cue.get("verification") == "asr_draft" and speech_flags(text):
48
+ raise ProjectError(
49
+ "subtitle_draft_unreliable",
50
+ "這段 ASR 有可疑的連續重複詞,不能直接作為字幕。請用 source_excerpt 引用原句中可用的部分,或略過這段字幕並保留原音;不可編造替代台詞。",
51
+ status_code=422,
52
+ )
27
53
  # Page boundaries are an explicit estimate inside the original ASR segment,
28
54
  # not invented word-level alignment. The original audio remains untouched.
29
- spans=[];cursor=0
30
- for match in re.finditer(r'[^,,。!?!?;;]+[,,。!?!?;;]*',text):
31
- end=match.end();phrase=text[cursor:end];count=max(1,math.ceil(len(phrase)/18))
32
- spans.extend((cursor+len(phrase)*n//count,cursor+len(phrase)*(n+1)//count) for n in range(count));cursor=end
33
- if cursor<len(text):spans.append((cursor,len(text)))
34
- pages=[]
35
- for left,right in spans:
36
- if pages and pages[-1][1]-pages[-1][0]<6 and right-pages[-1][0]<=18:
37
- pages[-1]=(pages[-1][0],right)
38
- else:pages.append((left,right))
39
- if cue['duration_frames']<len(pages):raise ProjectError('subtitle_too_short','口語時間不足以顯示分句字幕。',status_code=422)
55
+ spans = []
56
+ cursor = 0
57
+ for match in re.finditer(r"[^,,。!?!?;;]+[,,。!?!?;;]*", text):
58
+ end = match.end()
59
+ phrase = text[cursor:end]
60
+ count = max(1, math.ceil(len(phrase) / 18))
61
+ spans.extend((cursor + len(phrase) * n // count, cursor + len(phrase) * (n + 1) // count) for n in range(count))
62
+ cursor = end
63
+ if cursor < len(text):
64
+ spans.append((cursor, len(text)))
65
+ pages = []
66
+ for left, right in spans:
67
+ if pages and pages[-1][1] - pages[-1][0] < 6 and right - pages[-1][0] <= 18:
68
+ pages[-1] = (pages[-1][0], right)
69
+ else:
70
+ pages.append((left, right))
71
+ if cue["duration_frames"] < len(pages):
72
+ raise ProjectError("subtitle_too_short", "口語時間不足以顯示分句字幕。", status_code=422)
40
73
  aligned = None
41
- if original.get('words'):
42
- frame_rate=tools._timeline().frame_rate
43
- aligned = aligned_pages(original, text, excerpt, pages, frame_rate.numerator/frame_rate.denominator)
44
- pages = [(left,right) for left,right,_,_ in aligned]
45
- styles=load_text_styles(tools.repository.projects,tools.project_id);items=[]
46
- for n,(left,right) in enumerate(pages):
47
- start=cue['start_frame']+cue['duration_frames']*left//len(text)
48
- end=cue['start_frame']+cue['duration_frames']*right//len(text)
74
+ if original.get("words"):
75
+ frame_rate = tools._timeline().frame_rate
76
+ aligned = aligned_pages(original, text, excerpt, pages, frame_rate.numerator / frame_rate.denominator)
77
+ pages = [(left, right) for left, right, _, _ in aligned]
78
+ styles = load_text_styles(tools.repository.projects, tools.project_id)
79
+ items = []
80
+ for n, (left, right) in enumerate(pages):
81
+ start = cue["start_frame"] + cue["duration_frames"] * left // len(text)
82
+ end = cue["start_frame"] + cue["duration_frames"] * right // len(text)
49
83
  if aligned:
50
- start,end = aligned[n][2:]
51
- delivery=row.get('delivery','dialogue')
52
- profile={'kind':'program_subtitle','font_size_ratio':.075 if delivery=='punchline' else .05 if delivery=='quiet' else .06,
53
- 'delivery':delivery,'emphasis':[s for s in row.get('emphasis',[]) if s in text[left:right]],
54
- 'verification':cue.get('verification','reviewed_source'),'source_revision_id':cue.get('source_revision_id'),
55
- 'segment_id':cue.get('segment_id'),'source':cue.get('source'),'source_text':source_text,
56
- 'source_excerpt':excerpt,'cue_id':cue['cue_id'],'anchor_item_id':original.get('item_id'),
57
- 'timing_basis':'forced_alignment' if aligned else 'character_proportional_within_asr_segment' if excerpt or len(pages)>1 else 'asr_segment',
58
- 'caption_text_edited':text!=original['text'],'motion':'none' if delivery=='quiet' else 'pop'}
59
- profile.update({key:original[key] for key in ('wording_authority','source_asr_text','correction_evidence') if key in original})
60
- skill=tools._skill_value();preset=skill['presets']['subtitle']
61
- profile.update({'font_size_ratio':preset['font_size_ratio']*(1.25 if delivery=='punchline' else .9 if delivery=='quiet' else 1),
62
- 'emphasis_color':preset['emphasis_color'],'outline_color':preset['outline_color'],
63
- 'skill_hash':skill['content_hash']})
64
- identifier='agent.text.'+digest(profile)[:24];styles[identifier]=profile
65
- items.append(TextClip('subtitle-'+cue['cue_id']+'-'+str(n),start,end-start,text[left:right],identifier))
84
+ start, end = aligned[n][2:]
85
+ delivery = row.get("delivery", "dialogue")
86
+ profile = {
87
+ "kind": "program_subtitle",
88
+ "font_size_ratio": 0.075 if delivery == "punchline" else 0.05 if delivery == "quiet" else 0.06,
89
+ "delivery": delivery,
90
+ "emphasis": [s for s in row.get("emphasis", []) if s in text[left:right]],
91
+ "verification": cue.get("verification", "reviewed_source"),
92
+ "source_revision_id": cue.get("source_revision_id"),
93
+ "segment_id": cue.get("segment_id"),
94
+ "source": cue.get("source"),
95
+ "source_text": source_text,
96
+ "source_excerpt": excerpt,
97
+ "cue_id": cue["cue_id"],
98
+ "anchor_item_id": original.get("item_id"),
99
+ "timing_basis": "forced_alignment"
100
+ if aligned
101
+ else "character_proportional_within_asr_segment"
102
+ if excerpt or len(pages) > 1
103
+ else "asr_segment",
104
+ "caption_text_edited": text != original["text"],
105
+ "motion": "none" if delivery == "quiet" else "pop",
106
+ }
107
+ profile.update(
108
+ {
109
+ key: original[key]
110
+ for key in ("wording_authority", "source_asr_text", "correction_evidence")
111
+ if key in original
112
+ }
113
+ )
114
+ skill = tools._skill_value()
115
+ preset = skill["presets"]["subtitle"]
116
+ profile.update(
117
+ {
118
+ "font_size_ratio": preset["font_size_ratio"]
119
+ * (1.25 if delivery == "punchline" else 0.9 if delivery == "quiet" else 1),
120
+ "emphasis_color": preset["emphasis_color"],
121
+ "outline_color": preset["outline_color"],
122
+ "skill_hash": skill["content_hash"],
123
+ }
124
+ )
125
+ identifier = "agent.text." + digest(profile)[:24]
126
+ styles[identifier] = profile
127
+ items.append(
128
+ TextClip("subtitle-" + cue["cue_id"] + "-" + str(n), start, end - start, text[left:right], identifier)
129
+ )
66
130
  from .production_limits import limits_for
67
- if len(styles)>max(256,limits_for(tools).titles*2):raise ProjectError('agent_input_invalid','自訂字幕樣式索引超過上限。',status_code=422)
68
- atomic_json(text_style_path(tools.repository.projects,tools.project_id),styles)
131
+
132
+ if len(styles) > max(256, limits_for(tools).titles * 2):
133
+ raise ProjectError("agent_input_invalid", "自訂字幕樣式索引超過上限。", status_code=422)
134
+ atomic_json(text_style_path(tools.repository.projects, tools.project_id), styles)
69
135
  return items
70
136
 
71
137
 
72
138
  def aligned_pages(cue, text, excerpt, pages, fps=30):
73
139
  """Snap display page boundaries to actual words; pauses get no invented duration."""
74
140
  from .alignment import significant
75
- original = cue['text']
76
- left,right = (excerpt['start'],excerpt['end']) if excerpt else (0,len(original))
141
+
142
+ original = cue["text"]
143
+ left, right = (excerpt["start"], excerpt["end"]) if excerpt else (0, len(original))
77
144
  if significant(text) != significant(original[left:right]):
78
- raise ProjectError('subtitle_alignment_text_changed','文字已改變,請重新對齊後再建立字幕。',status_code=422)
79
- words=[w for w in cue['words'] if w['char_end']>left and w['char_start']<right]
80
- if not words or words[0]['char_start']<left or words[-1]['char_end']>right:
81
- raise ProjectError('subtitle_word_boundary_required','摘錄需包含完整對齊字詞,不能在詞內估算時間。',status_code=422)
82
- display_positions=[n for n,c in enumerate(text) if significant(c)]
83
- start_count=len(significant(original[:left]))
84
- counts=[(len(significant(original[:w['char_start']]))-start_count,
85
- len(significant(original[:w['char_end']]))-start_count,w) for w in words]
86
- endings=set()
145
+ raise ProjectError("subtitle_alignment_text_changed", "文字已改變,請重新對齊後再建立字幕。", status_code=422)
146
+ words = [w for w in cue["words"] if w["char_end"] > left and w["char_start"] < right]
147
+ if not words or words[0]["char_start"] < left or words[-1]["char_end"] > right:
148
+ raise ProjectError(
149
+ "subtitle_word_boundary_required", "摘錄需包含完整對齊字詞,不能在詞內估算時間。", status_code=422
150
+ )
151
+ display_positions = [n for n, c in enumerate(text) if significant(c)]
152
+ start_count = len(significant(original[:left]))
153
+ counts = [
154
+ (
155
+ len(significant(original[: w["char_start"]])) - start_count,
156
+ len(significant(original[: w["char_end"]])) - start_count,
157
+ w,
158
+ )
159
+ for w in words
160
+ ]
161
+ endings = set()
87
162
  for previous, following in zip(counts, counts[1:]):
88
- if following[2]['start_frame']-previous[2]['end_frame'] > .6*fps:
163
+ if following[2]["start_frame"] - previous[2]["end_frame"] > 0.6 * fps:
89
164
  endings.add(previous[1])
90
- for _,end in pages:
91
- desired=len(significant(text[:end]))
92
- ending=next((b for a,b,_ in counts if b>=desired),len(display_positions))
165
+ for _, end in pages:
166
+ desired = len(significant(text[:end]))
167
+ ending = next((b for a, b, _ in counts if b >= desired), len(display_positions))
93
168
  endings.add(ending)
94
169
  endings.add(len(display_positions))
95
- result=[];previous=0;previous_count=0
170
+ result = []
171
+ previous = 0
172
+ previous_count = 0
96
173
  for count in sorted(endings):
97
- if count<=previous_count:continue
98
- end=display_positions[count] if count<len(display_positions) else len(text)
99
- included=[word for a,b,word in counts if a>=previous_count and b<=count]
174
+ if count <= previous_count:
175
+ continue
176
+ end = display_positions[count] if count < len(display_positions) else len(text)
177
+ included = [word for a, b, word in counts if a >= previous_count and b <= count]
100
178
  if not included:
101
- raise ProjectError('subtitle_alignment_incomplete','分頁沒有完整對齊字詞。',status_code=422)
102
- first,last=included[0]['start_frame'],included[-1]['end_frame']
103
- if last<=first:
104
- raise ProjectError('subtitle_too_short','對齊字詞不足一格,請調整分句。',status_code=422)
105
- result.append((previous,end,first,last));previous=end;previous_count=count
179
+ raise ProjectError("subtitle_alignment_incomplete", "分頁沒有完整對齊字詞。", status_code=422)
180
+ first, last = included[0]["start_frame"], included[-1]["end_frame"]
181
+ if last <= first:
182
+ raise ProjectError("subtitle_too_short", "對齊字詞不足一格,請調整分句。", status_code=422)
183
+ result.append((previous, end, first, last))
184
+ previous = end
185
+ previous_count = count
106
186
  # Word evidence can put pauses inside a short phrase (我 / 們, 伴手 / 禮).
107
187
  # Join tiny pages using the existing first/last word boundaries; no word
108
188
  # timestamps are stretched or estimated, and long pauses remain separate.
109
- merged=[]
189
+ merged = []
110
190
  for current in result:
111
191
  if merged:
112
- before=merged[-1]
113
- short=min(len(significant(text[before[0]:before[1]])),len(significant(text[current[0]:current[1]])))<=5
114
- sentence_end=text[before[0]:before[1]].rstrip().endswith(('。','!','?','!','?','.'))
115
- tiny_reply=len(significant(text[current[0]:current[1]]))<=1
116
- if short and (not sentence_end or tiny_reply) and current[2]-before[3]<1.5*fps and len(significant(text[before[0]:current[1]]))<=18:
117
- merged[-1]=(before[0],current[1],before[2],current[3]);continue
192
+ before = merged[-1]
193
+ short = (
194
+ min(len(significant(text[before[0] : before[1]])), len(significant(text[current[0] : current[1]]))) <= 5
195
+ )
196
+ sentence_end = text[before[0] : before[1]].rstrip().endswith(("。", "!", "?", "!", "?", "."))
197
+ tiny_reply = len(significant(text[current[0] : current[1]])) <= 1
198
+ if (
199
+ short
200
+ and (not sentence_end or tiny_reply)
201
+ and current[2] - before[3] < 1.5 * fps
202
+ and len(significant(text[before[0] : current[1]])) <= 18
203
+ ):
204
+ merged[-1] = (before[0], current[1], before[2], current[3])
205
+ continue
118
206
  merged.append(current)
119
207
  return merged
120
208
 
121
209
 
122
- def subtitle_status(projects,project_id,timeline):
210
+ def subtitle_status(projects, project_id, timeline):
123
211
  from clipen.domain import TrackKind
124
- styles=load_text_styles(projects,project_id)
125
- items=[i for t in timeline.tracks if t.kind is TrackKind.TITLE and t.track_id=='agent-subtitles' for i in t.items]
126
- drafts=[i.item_id for i in items if styles.get(i.style_id,{}).get('verification')=='asr_draft']
127
- aligned=[i.item_id for i in items if styles.get(i.style_id,{}).get('timing_basis')=='forced_alignment']
128
- manual=[i.item_id for i in items if styles.get(i.style_id,{}).get('timing_basis')=='user_adjusted']
129
- timed=set(aligned+manual)
130
- unaligned=[i.item_id for i in items if i.item_id not in timed]
131
- return {'count':len(items),'draft_count':len(drafts),'draft_item_ids':drafts,
132
- 'unaligned_item_ids':unaligned,'aligned_count':len(aligned),
133
- 'manual_timing_item_ids':manual,'manual_timing_count':len(manual),
134
- 'audio_listened':False,'review_scope':'Source-linked draft captions are not human-verified transcription.'}
212
+
213
+ styles = load_text_styles(projects, project_id)
214
+ items = [
215
+ i for t in timeline.tracks if t.kind is TrackKind.TITLE and t.track_id == "agent-subtitles" for i in t.items
216
+ ]
217
+ drafts = [i.item_id for i in items if styles.get(i.style_id, {}).get("verification") == "asr_draft"]
218
+ aligned = [i.item_id for i in items if styles.get(i.style_id, {}).get("timing_basis") == "forced_alignment"]
219
+ manual = [i.item_id for i in items if styles.get(i.style_id, {}).get("timing_basis") == "user_adjusted"]
220
+ timed = set(aligned + manual)
221
+ unaligned = [i.item_id for i in items if i.item_id not in timed]
222
+ return {
223
+ "count": len(items),
224
+ "draft_count": len(drafts),
225
+ "draft_item_ids": drafts,
226
+ "unaligned_item_ids": unaligned,
227
+ "aligned_count": len(aligned),
228
+ "manual_timing_item_ids": manual,
229
+ "manual_timing_count": len(manual),
230
+ "audio_listened": False,
231
+ "review_scope": "Source-linked draft captions are not human-verified transcription.",
232
+ }
@@ -1,73 +1,121 @@
1
1
  """Observable editorial structure and caption omissions, without aesthetic scores."""
2
- from fractions import Fraction
2
+
3
3
  import json
4
4
  import unicodedata
5
+ from fractions import Fraction
5
6
 
6
7
 
7
8
  def pacing(timeline):
8
9
  from clipen.domain import TrackKind
9
- fps=Fraction(timeline.frame_rate.numerator,timeline.frame_rate.denominator)
10
- runs=[]
10
+
11
+ fps = Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
12
+ runs = []
11
13
  for track in timeline.tracks:
12
- if track.kind is not TrackKind.VIDEO:continue
13
- previous=None
14
+ if track.kind is not TrackKind.VIDEO:
15
+ continue
16
+ previous = None
14
17
  for item in track.items:
15
- span=item.source.span
16
- unit=Fraction(span.time_base.numerator,span.time_base.denominator)
17
- left,right=int(span.start_pts)*unit,int(span.end_pts)*unit
18
- contiguous=(previous is not None and previous['version_id']==span.version_id
19
- and previous['stream_index']==span.stream_index
20
- and abs(previous['source_end']-left)<=1/fps
21
- and previous['end_frame']==item.start_frame)
18
+ span = item.source.span
19
+ unit = Fraction(span.time_base.numerator, span.time_base.denominator)
20
+ left, right = int(span.start_pts) * unit, int(span.end_pts) * unit
21
+ contiguous = (
22
+ previous is not None
23
+ and previous["version_id"] == span.version_id
24
+ and previous["stream_index"] == span.stream_index
25
+ and abs(previous["source_end"] - left) <= 1 / fps
26
+ and previous["end_frame"] == item.start_frame
27
+ )
22
28
  if contiguous:
23
- previous['item_ids'].append(item.item_id)
24
- previous['end_frame']=item.start_frame+item.duration_frames
25
- previous['source_end']=right
29
+ previous["item_ids"].append(item.item_id)
30
+ previous["end_frame"] = item.start_frame + item.duration_frames
31
+ previous["source_end"] = right
26
32
  else:
27
- previous={'version_id':span.version_id,'stream_index':span.stream_index,'item_ids':[item.item_id],
28
- 'start_frame':item.start_frame,'end_frame':item.start_frame+item.duration_frames,'source_end':right}
33
+ previous = {
34
+ "version_id": span.version_id,
35
+ "stream_index": span.stream_index,
36
+ "item_ids": [item.item_id],
37
+ "start_frame": item.start_frame,
38
+ "end_frame": item.start_frame + item.duration_frames,
39
+ "source_end": right,
40
+ }
29
41
  runs.append(previous)
30
- return {'duration_seconds':float(timeline.duration_frames/fps),
31
- 'source_runs':[{k:v for k,v in r.items() if k!='source_end'} |
32
- {'duration_seconds':float((r['end_frame']-r['start_frame'])/fps)} for r in runs],
33
- 'scope':'Adjacent spans from the same source are grouped even when split into clips. This is source continuity, not visual scene detection or an aesthetic verdict.'}
42
+ return {
43
+ "duration_seconds": float(timeline.duration_frames / fps),
44
+ "source_runs": [
45
+ {k: v for k, v in r.items() if k != "source_end"}
46
+ | {"duration_seconds": float((r["end_frame"] - r["start_frame"]) / fps)}
47
+ for r in runs
48
+ ],
49
+ "scope": "Adjacent spans from the same source are grouped even when split into clips. This is source continuity, not visual scene detection or an aesthetic verdict.",
50
+ }
34
51
 
35
52
 
36
53
  def caption_coverage(tools, speech):
37
54
  from .production_media import load_text_styles
38
- timeline=tools._timeline();styles=load_text_styles(tools.repository.projects,tools.project_id)
55
+
56
+ timeline = tools._timeline()
57
+ styles = load_text_styles(tools.repository.projects, tools.project_id)
58
+
39
59
  def words(text):
40
- return ''.join(c.casefold() for c in unicodedata.normalize('NFKC',text) if unicodedata.category(c)[0] not in 'PZC')
41
- rendered={}
60
+ return "".join(
61
+ c.casefold() for c in unicodedata.normalize("NFKC", text) if unicodedata.category(c)[0] not in "PZC"
62
+ )
63
+
64
+ rendered = {}
42
65
  for track in timeline.tracks:
43
- if track.track_id!='agent-subtitles':continue
66
+ if track.track_id != "agent-subtitles":
67
+ continue
44
68
  for item in track.items:
45
- profile=styles.get(item.style_id,{})
46
- key=(profile.get('anchor_item_id'),profile.get('cue_id'))
47
- rendered.setdefault(key,[]).append(item)
48
- missing=[]
49
- for cue in speech['cues']:
50
- expected=words(cue['text'])
51
- if not expected:continue
52
- pages=sorted(rendered.get((cue['item_id'],cue['cue_id']),[]),key=lambda i:i.start_frame)
53
- actual=words(''.join(i.text for i in pages))
54
- if actual!=expected:
55
- missing.append({'item_id':cue['item_id'],'cue_id':cue['cue_id'],
56
- 'start_frame':cue['start_frame'],'duration_frames':cue['duration_frames']})
69
+ profile = styles.get(item.style_id, {})
70
+ key = (profile.get("anchor_item_id"), profile.get("cue_id"))
71
+ rendered.setdefault(key, []).append(item)
72
+ missing = []
73
+ for cue in speech["cues"]:
74
+ expected = words(cue["text"])
75
+ if not expected:
76
+ continue
77
+ pages = sorted(rendered.get((cue["item_id"], cue["cue_id"]), []), key=lambda i: i.start_frame)
78
+ actual = words("".join(i.text for i in pages))
79
+ if actual != expected:
80
+ missing.append(
81
+ {
82
+ "item_id": cue["item_id"],
83
+ "cue_id": cue["cue_id"],
84
+ "start_frame": cue["start_frame"],
85
+ "duration_frames": cue["duration_frames"],
86
+ }
87
+ )
57
88
  # A partially selected legacy ASR segment can disappear from cues entirely.
58
89
  # It still needs repair unless a newer successful local job covered that cut.
59
90
  with tools.repository.projects.connect(tools.project_id) as db:
60
- local=[json.loads(r['result_json'])['source'] for r in db.execute(
61
- "SELECT result_json FROM production_evidence_jobs WHERE run_id=? AND state='succeeded' AND kind IN ('transcribe','align')",(tools.run_id,))]
62
- fps=Fraction(timeline.frame_rate.numerator,timeline.frame_rate.denominator)
91
+ local = [
92
+ json.loads(r["result_json"])["source"]
93
+ for r in db.execute(
94
+ "SELECT result_json FROM production_evidence_jobs WHERE run_id=? AND state='succeeded' AND kind IN ('transcribe','align')",
95
+ (tools.run_id,),
96
+ )
97
+ ]
98
+ fps = Fraction(timeline.frame_rate.numerator, timeline.frame_rate.denominator)
99
+
63
100
  def locally_analyzed(item):
64
- span=item.source.span;unit=Fraction(span.time_base.numerator,span.time_base.denominator)
65
- left,right=int(span.start_pts)*unit,int(span.end_pts)*unit
66
- return any(s['version_id']==span.version_id and
67
- int(s['start_pts'])*Fraction(s['time_base']['num'],s['time_base']['den'])<=left+1/fps and
68
- int(s['end_pts'])*Fraction(s['time_base']['num'],s['time_base']['den'])>=right-1/fps for s in local)
69
- shots={i.item_id:i for i in tools._video().items}
70
- unresolved=sorted({v['item_id'] for v in speech['limitations'] if
71
- (v.get('reason') in {'partial_utterance','partial_utterance_requires_alignment'} or v.get('partial'))
72
- and v['item_id'] in shots and (v.get('reason')=='partial_utterance_requires_alignment' or not locally_analyzed(shots[v['item_id']]))})
73
- return {'complete':not missing and not unresolved,'missing_cues':missing,'unresolved_item_ids':unresolved}
101
+ span = item.source.span
102
+ unit = Fraction(span.time_base.numerator, span.time_base.denominator)
103
+ left, right = int(span.start_pts) * unit, int(span.end_pts) * unit
104
+ return any(
105
+ s["version_id"] == span.version_id
106
+ and int(s["start_pts"]) * Fraction(s["time_base"]["num"], s["time_base"]["den"]) <= left + 1 / fps
107
+ and int(s["end_pts"]) * Fraction(s["time_base"]["num"], s["time_base"]["den"]) >= right - 1 / fps
108
+ for s in local
109
+ )
110
+
111
+ shots = {i.item_id: i for i in tools._video().items}
112
+ unresolved = sorted(
113
+ {
114
+ v["item_id"]
115
+ for v in speech["limitations"]
116
+ if (v.get("reason") in {"partial_utterance", "partial_utterance_requires_alignment"} or v.get("partial"))
117
+ and v["item_id"] in shots
118
+ and (v.get("reason") == "partial_utterance_requires_alignment" or not locally_analyzed(shots[v["item_id"]]))
119
+ }
120
+ )
121
+ return {"complete": not missing and not unresolved, "missing_cues": missing, "unresolved_item_ids": unresolved}