@chrono-meta/fh-gate 3.24.0 → 3.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/.claude/rules/fh_4axis_gate.md +14 -1
  2. package/.claude-plugin/marketplace.json +4 -4
  3. package/CLAUDE.md +5 -4
  4. package/README.md +8 -6
  5. package/knowledge/shared/harness-core/claude_md_gate_details.md +34 -0
  6. package/knowledge/shared/harness-core/fh_integration_contract.md +0 -1
  7. package/knowledge/shared/harness-core/fh_opencode_governance_wrapper.md +0 -1
  8. package/knowledge/shared/harness-core/fh_three_layer_canon.md +110 -2
  9. package/knowledge/shared/harness-core/field_verdict_crossfamily_gate.md +22 -0
  10. package/knowledge/shared/harness-core/governance_engineering_definition.md +16 -0
  11. package/knowledge/shared/harness-core/harness_verification_core_extended.md +26 -0
  12. package/knowledge/shared/harness-core/ship_readiness_gate.md +3 -0
  13. package/knowledge/shared/harness-core/sonnet_floor_doctrine.md +19 -0
  14. package/package.json +10 -2
  15. package/plugins/fh-commons/.claude-plugin/plugin.json +1 -1
  16. package/plugins/fh-meta/.claude-plugin/plugin.json +1 -1
  17. package/plugins/fh-meta/CHANGELOG.md +9 -0
  18. package/plugins/fh-meta/skills/install-wizard/SKILL_detail.md +17 -3
  19. package/plugins/fh-meta/skills/verify-bidirectional/SKILL.md +1 -1
  20. package/plugins/fh-preprep/.claude-plugin/plugin.json +2 -2
  21. package/plugins/fh-preprep/README.md +11 -0
  22. package/plugins/fh-preprep/skills/preprep/SKILL.md +47 -1
  23. package/plugins/fh-preprep/skills/preprep/lane_speech_coach.py +1080 -0
  24. package/plugins/fh-preprep/skills/preprep/test_lane_speech_coach.py +705 -0
  25. package/plugins/fh-qp/.claude-plugin/plugin.json +1 -1
  26. package/scripts/cluster_capability_scan.sh +17 -0
  27. package/scripts/compaction_probe.sh +102 -23
  28. package/scripts/count_check.sh +37 -10
  29. package/scripts/field_canon_preload.sh +84 -2
  30. package/scripts/marker_diff_sha.sh +13 -0
  31. package/scripts/mutation_probe.py +1541 -0
  32. package/scripts/revert_probe.sh +5 -6
  33. package/scripts/selfcheck.sh +48 -0
  34. package/scripts/test_axis23_skip_reason_lanes.sh +109 -0
  35. package/scripts/test_count_check_all_plugins_lanes.sh +130 -0
  36. package/scripts/test_field_canon_lanes.sh +33 -0
  37. package/scripts/test_hook_templates_copilot_compat_lanes.sh +250 -0
  38. package/scripts/test_marker_diff_sha_lanes.sh +129 -0
  39. package/scripts/test_mutation_probe_lanes.sh +786 -0
  40. package/scripts/test_preprep_speech_coach_lanes.sh +62 -0
  41. package/scripts/test_skill_canon_preload_lanes.sh +148 -0
  42. package/scripts/universal_guard_check.sh +2 -0
  43. package/templates/.git-hooks/pre-commit +109 -5
  44. package/templates/goal-quench-hook-setup.md +3 -3
  45. package/templates/goal-quench-settings-merged.json +0 -1
  46. package/templates/settings.Compaction.snippet.json +0 -2
  47. package/templates/settings.FieldCanon.snippet.json +0 -1
  48. package/templates/settings.SessionStart.snippet.json +0 -2
  49. package/templates/settings.SubagentStop.snippet.json +0 -1
  50. package/templates/subagent-tally-hook.json +0 -1
@@ -0,0 +1,1080 @@
1
+ #!/usr/bin/env python3
2
+ """lane_speech_coach.py — L16 speech-coach: 리허설 녹화를 듣고 코칭 6항 표를 낸다. (advisory)
3
+
4
+ 다른 레인은 «표면 사이»(덱 ↔ 원고 ↔ 노트)를 본다. 이 레인은 그 원고를 **소리 내 읽은 결과**를
5
+ 본다 — 발표 준비의 마지막 표면이다. 입력이 `surfaces.yaml` 의 문서가 아니라 녹화라서
6
+ `preprep.py` 에 배선하지 않고 독립 CLI 로 부른다.
7
+
8
+ python3 lane_speech_coach.py <녹화.mp4|.wav> [--script 덱.pptx|원고.txt] [--audio-only]
9
+ [--skip 1,2] [--json 결과.json]
10
+
11
+ 코칭 6항(아나운서 코칭 한 회분을 known-positive 로 삼아 나눈 축):
12
+ ① 소리 내 읽기·발음 — 받아쓰기 × 원고 대조. 어긋난 자리는 «발음 후보»일 뿐이다
13
+ ② 쉼표 여유 · 접속사 끌기 — 쉼으로 자른 덩어리 × 받아쓰기. 접속사 앞뒤 쉼과 늘임
14
+ ③ 어미 밀당 — 문장 끝 300ms 피치 모양(하강 · 올림 · 올렸다 내림)
15
+ ④ 첫 인사·끝인사 강조 — 첫·끝 덩어리의 크기를 녹화 자기 분포에 대고 잰다
16
+ ⑤ 시선 — 오디오 계기 범위 밖(설계상)
17
+ ⑥ 스피치보다 내용 — 계기 대상이 아니다. 이 스킬의 다른 레인(L1~L15)이 맡는다
18
+
19
+ 의존성 — 전부 로컬, 녹화는 기계 밖으로 나가지 않는다:
20
+ ffmpeg 필수. 없으면 «전부 측정불가» · exit 2. 경로 지정: PREPREP_FFMPEG
21
+ whisper-cli 선택. 없으면 ①② 측정불가, ③④ 는 오디오만으로 돈다.
22
+ 경로 지정: PREPREP_WHISPER_CLI · 모델: PREPREP_WHISPER_MODEL(기본값 없음 — 지정 필수)
23
+ 언어: PREPREP_WHISPER_LANG(기본 ko)
24
+ python-pptx `--script *.pptx` 를 줄 때만(발표자 노트를 원고로 읽는다)
25
+
26
+ 종료코드 — 🟥 **1 은 쓰지 않는다.**
27
+ 0 범위 안의 항목이 전부 측정됐다. 🟥 «좋은 발표」가 아니라 «다 들었다」다
28
+ 2 하나라도 측정 못 했다(ffmpeg 없음 · 디코드 실패 · 발화 0 · whisper/모델/원고 없음).
29
+ 범위에서 빼려면 `--audio-only`(①② 제외) 또는 `--skip` 으로 «선언»한다 — 선언한 것은
30
+ «범위에서 뺌(선언)」으로 출력된다. 조용히 사라지지 않는다.
31
+ 이 레인의 숫자는 묘사다. 문턱(끌기 · 밀당 · 덩어리 경계)은 녹화 1건 · TTS 대조군에서 고른
32
+ 값이라 전부 `UNCALIBRATED` 로 출력된다. 숫자를 «발견」으로 바꿔 종료코드에 태우면 그건
33
+ 보정 안 된 계기가 판정을 내리는 것이다 — L8·R*·P* 와 같은 advisory 관례.
34
+
35
+ 알려진 한계(인용 전에 읽어라):
36
+ · 받아쓰기 낱말 시각은 실측 최대 ~0.8초 어긋났다. 그래서 낱말 시각으로 쉼을 재지 않는다 —
37
+ 쉼으로 자른 덩어리를 하나씩 받아쓰게 하고, 경계는 음향(덩어리)에서 가져온다.
38
+ 덩어리 안 낱말의 길이는 토큰 시각이라 `UNCALIBRATED` 로 표기한다.
39
+ · 덩어리 단독 받아쓰기는 0.35초 미만 잡음에 «감사합니다」를 지어낸다(실측 16/550). 걸러내고
40
+ 그 수를 출력한다. 다른 형태의 환각은 못 거른다.
41
+ · ① 의 어긋남은 받아쓰기 오류와 실제 발음을 이 계기만으로 못 가른다 — 사람 귀 확인 전에는
42
+ «후보」다.
43
+ · ③ 은 기준선이 없다. 한국어 평서문은 원래 내려가므로 «하강 비율이 높다」는 결함 판정이 아니다.
44
+ · 피치는 자기상관 근사다(순음·합성 톱니 known-pair 통과, 실화자 프레임 단위 손검증 없음).
45
+ """
46
+ import argparse
47
+ import array
48
+ import difflib
49
+ import json
50
+ import math
51
+ import operator
52
+ import os
53
+ import re
54
+ import shutil
55
+ import subprocess
56
+ import sys
57
+ import tempfile
58
+ import wave
59
+
60
+ SR = 16000
61
+ HOP = 160 # 10ms
62
+ LANE = 'L16 speech-coach'
63
+
64
+ # 🟥 보정 상수 — 전부 UNCALIBRATED. 녹화 1건(화자 1명) · TTS 대조군에서 고른 값이다.
65
+ # 출력에 그대로 싣는다. 이 값을 근거로 «빠르다/단조롭다/끌지 않았다」를 판정하지 마라.
66
+ CAL = {
67
+ 'rel_db': (12.0, '발화 문턱 = 지역 하위 10% + 이 값(dB)'),
68
+ 'thr_win_s': (60, '지역 문턱 창(초) — 잡음 바닥이 구간마다 다르다(실측 ~10dB 차)'),
69
+ 'thr_step_s': (10, '지역 문턱 갱신 간격(초)'),
70
+ 'min_sil_s': (0.15, '이보다 짧은 무음은 덩어리 경계로 안 본다'),
71
+ 'min_speech_s': (0.08, '이보다 짧은 «발화」는 무음으로 흡수'),
72
+ 'pad_s': (0.12, '덩어리를 받아쓰기에 넘길 때 앞뒤 여유'),
73
+ 'hallu_max_s': (0.35, '이보다 짧은 덩어리의 상투 인사 받아쓰기는 환각으로 버린다(유성이면 누락으로도 센다)'),
74
+ 'voiced_min': (0.25, '빈 받아쓰기 덩어리의 유성 비율이 이 이상이면 «말소리를 놓쳤다」(누락)로 센다'),
75
+ 'drag_stretch': (1.30, '접속사 «끌기」 후보 문턱(TTS 보통 1.11 · 끈 것 1.44 사이)'),
76
+ 'phrase_end_gap_s': (0.60, '받아쓰기 없을 때 «구 끝」 대리: 뒤 쉼이 이 이상'),
77
+ 'tail_s': (0.30, '문장 끝 창(초)'),
78
+ 'body_s': (1.20, '문장 끝 직전 본문 창(초)'),
79
+ 'peak_st': (1.0, '밀당 = 끝 창 봉우리가 본문 대비 이 반음 이상 올랐다가 그만큼 내려옴'),
80
+ 'decode_short_frac': (0.02, '디코드된 길이가 녹화 길이(ffprobe)보다 이 비율 이상 짧으면 «부분 디코드」'),
81
+ 'octave_up_st': (6.0, '끝 봉우리가 본문 대비 이 반음 넘게 오르면 옥타브 오류 의심 — 예시·밀당에서 뺀다'),
82
+ 'octave_down_st': (12.0, '끝 평균이 본문 대비 이 반음 넘게 내리면 옥타브 오류 의심(한국어 평서 하강은 보통 이 안쪽)'),
83
+ }
84
+
85
+
86
+ def C(k):
87
+ return CAL[k][0]
88
+
89
+
90
+ CONJ = ['그런데', '그리고', '그래서', '그러나', '그러면', '하지만', '그래도', '그러니까', '따라서', '반면', '또한', '즉']
91
+ STOCK_HALLU = re.compile(r'^(감사합니다|고맙습니다|시청해주셔서감사합니다)[.!]?$')
92
+ PRONOUN_TOPIC = ('저', '우리', '이', '그', '이것', '그것', '나', '너')
93
+
94
+ ST_MEASURED, ST_PARTIAL, ST_NONE = '잡음', '부분', '측정불가'
95
+ CAUSE_DEP, CAUSE_DESIGN, CAUSE_DECLARED = 'unmeasured', 'by_design', 'declared'
96
+ CAUSE_INCOMPLETE = 'incomplete' # 측정은 됐지만 일부 덩어리를 못 들었다 — rc 에 센다
97
+
98
+
99
+ # ── 오디오 기초 ───────────────────────────────────────────────────────────────────────────────
100
+ def fmt_t(s):
101
+ if s is None:
102
+ return '—'
103
+ m = int(s // 60)
104
+ return '%d:%04.1f' % (m, s - 60 * m)
105
+
106
+
107
+ def pct(v, p):
108
+ s = sorted(v)
109
+ if not s:
110
+ return float('nan')
111
+ return s[min(len(s) - 1, int(p / 100 * len(s)))]
112
+
113
+
114
+ def frame_db(x):
115
+ """10ms 프레임 RMS dBFS."""
116
+ mul = operator.mul
117
+ out = []
118
+ for i in range(0, len(x) - HOP + 1, HOP):
119
+ w = x[i:i + HOP]
120
+ out.append(20 * math.log10(math.sqrt(sum(map(mul, w, w)) / HOP) + 1e-9) - 90.309)
121
+ return out
122
+
123
+
124
+ def thr_series(db, win_s=None, step_s=None, rel=None):
125
+ """지역 적응 문턱: step 마다 ±win/2 창의 하위 10% + rel dB.
126
+
127
+ 전역 문턱 하나로는 잡음 바닥이 올라간 구간의 쉼이 «발화」로 읽혀 덩어리가 수십 초로 붙는다
128
+ (실측 21초짜리 덩어리). 되돌림 프로브가 이 함수를 전역 문턱으로 바꿔 그 병합을 재현한다.
129
+ """
130
+ win_s = C('thr_win_s') if win_s is None else win_s
131
+ step_s = C('thr_step_s') if step_s is None else step_s
132
+ rel = C('rel_db') if rel is None else rel
133
+ n = len(db)
134
+ out = [0.0] * n
135
+ step = int(step_s * 100)
136
+ half = int(win_s * 50)
137
+ for c in range(0, n, step):
138
+ w = db[max(0, c + step // 2 - half): c + step // 2 + half]
139
+ t = pct(w, 10) + rel
140
+ for i in range(c, min(n, c + step)):
141
+ out[i] = t
142
+ return out
143
+
144
+
145
+ def runs(db, thr, min_sil=None):
146
+ """(발화?, 시작초, 끝초) 런. min_sil 미만 무음은 앞 발화에 흡수."""
147
+ min_sil = C('min_sil_s') if min_sil is None else min_sil
148
+ if not db:
149
+ return []
150
+ v = [d > t for d, t in zip(db, thr)]
151
+ rr, cur, st = [], v[0], 0
152
+ for i in range(1, len(v)):
153
+ if v[i] != cur:
154
+ rr.append([cur, st, i])
155
+ cur, st = v[i], i
156
+ rr.append([cur, st, len(v)])
157
+ m = []
158
+ for r in rr:
159
+ if not r[0] and (r[2] - r[1]) * 0.01 < min_sil and m:
160
+ m[-1][2] = r[2]
161
+ continue
162
+ if m and m[-1][0] == r[0]:
163
+ m[-1][2] = r[2]
164
+ else:
165
+ m.append(r)
166
+ return [(bool(r[0]), r[1] * 0.01, r[2] * 0.01) for r in m]
167
+
168
+
169
+ def clean_runs(R, min_speech=None):
170
+ min_speech = C('min_speech_s') if min_speech is None else min_speech
171
+ out = []
172
+ for v, a, b in R:
173
+ if v and b - a < min_speech:
174
+ v = False
175
+ if out and out[-1][0] == v:
176
+ out[-1] = (v, out[-1][1], b)
177
+ else:
178
+ out.append((v, a, b))
179
+ return out
180
+
181
+
182
+ def segment(db):
183
+ """발화 덩어리 [(a,b)] · 문턱 시계열. 쉼으로 갈린 덩어리가 이 레인의 시간 정본이다."""
184
+ thr = thr_series(db)
185
+ R = clean_runs(runs(db, thr))
186
+ return [(a, b) for v, a, b in R if v], thr
187
+
188
+
189
+ def smooth(v, k=5):
190
+ h = k // 2
191
+ out = []
192
+ for i in range(len(v)):
193
+ w = v[max(0, i - h): i + h + 1]
194
+ out.append(sum(w) / len(w))
195
+ return out
196
+
197
+
198
+ def peaks_in(db, thr_v, f0, f1):
199
+ """f0..f1 프레임 구간의 음절 핵(평활 에너지 봉우리, 돌출 3dB · 간격 80ms)."""
200
+ lo_ = max(0, f0 - 20)
201
+ seg = smooth(db[lo_:f1 + 20], 5)
202
+ out, last = [], -999
203
+ for i in range(1, len(seg) - 1):
204
+ g = lo_ + i
205
+ if g < f0 or g >= f1:
206
+ continue
207
+ if seg[i] > thr_v and seg[i] >= seg[i - 1] and seg[i] > seg[i + 1]:
208
+ lo = min(seg[max(0, i - 15):i] or [seg[i]])
209
+ ro = min(seg[i + 1:i + 16] or [seg[i]])
210
+ if seg[i] - max(lo, ro) >= 3.0 and g - last >= 8:
211
+ out.append(g)
212
+ last = g
213
+ return out
214
+
215
+
216
+ def f0_at(x, center_s):
217
+ """40ms 창 · 4kHz 자기상관 피치(50~400Hz). 서브하모닉 회피: 최댓값 0.85 이상인 첫 국소 최대."""
218
+ c = int(center_s * SR)
219
+ raw = x[c:c + (160 + 80) * 4]
220
+ if len(raw) < (160 + 80) * 4:
221
+ return None
222
+ d = [(raw[i] + raw[i + 1] + raw[i + 2] + raw[i + 3]) / 4.0 for i in range(0, len(raw) - 3, 4)]
223
+ W = 160
224
+ m = sum(d[:W]) / W
225
+ d = [v - m for v in d]
226
+ a = d[:W]
227
+ mul = operator.mul
228
+ e0 = sum(map(mul, a, a)) + 1e-9
229
+ rs = [0.0] * 81
230
+ for lag in range(10, 81):
231
+ b = d[lag:lag + W]
232
+ rs[lag] = sum(map(mul, a, b)) / math.sqrt(e0 * (sum(map(mul, b, b)) + 1e-9))
233
+ best = max(rs[10:81])
234
+ bl = None
235
+ for lag in range(11, 80):
236
+ if rs[lag] >= 0.85 * best and rs[lag] >= rs[lag - 1] and rs[lag] >= rs[lag + 1]:
237
+ bl = lag
238
+ break
239
+ return 4000.0 / bl if (bl and best > 0.55) else None
240
+
241
+
242
+ def contour(x, db, thr, t0, t1, step=0.02):
243
+ pts = []
244
+ t = t0
245
+ while t < t1:
246
+ fi = int(t * 100)
247
+ if 0 <= fi < len(db) and db[fi] > thr[fi] + 3:
248
+ pts.append((round(t, 2), f0_at(x, t)))
249
+ else:
250
+ pts.append((round(t, 2), None))
251
+ t += step
252
+ idx = [i for i, (_, v) in enumerate(pts) if v]
253
+ clean = list(pts)
254
+ for k, i in enumerate(idx): # 옥타브 오류: 이웃 7개 중앙값 ×1.6 / ×0.62 밖은 버린다
255
+ nb = sorted(pts[j][1] for j in idx[max(0, k - 3):k + 4])
256
+ med = nb[len(nb) // 2]
257
+ if pts[i][1] > med * 1.6 or pts[i][1] < med * 0.62:
258
+ clean[i] = (pts[i][0], None)
259
+ return clean
260
+
261
+
262
+ def st(a, ref):
263
+ return 12 * math.log2(a / ref)
264
+
265
+
266
+ def end_metrics(x, db, thr, ra, rb):
267
+ """문장(구) 끝 rb 직전: 끝 창 평균 피치(본문 중앙값 대비 반음) · 봉우리 · 마지막 0.1초 · 에너지 낙차."""
268
+ tail_s, body_s = C('tail_s'), C('body_s')
269
+ t0 = max(ra, rb - body_s)
270
+ v = [(t, f) for t, f in contour(x, db, thr, t0, rb) if f]
271
+ tail = [f for t, f in v if t >= rb - tail_s]
272
+ body = [f for t, f in v if t < rb - tail_s]
273
+ rec = {'end': round(rb, 2), 'n_voiced': len(v)}
274
+ if len(tail) >= 3 and len(body) >= 3:
275
+ ref = sorted(body)[len(body) // 2]
276
+ rec['tail_st'] = round(st(sum(tail) / len(tail), ref), 1)
277
+ rec['tail_peak_st'] = round(st(max(tail), ref), 1)
278
+ last = [f for t, f in v if t >= rb - 0.1]
279
+ if last:
280
+ rec['tail_last_st'] = round(st(sum(last) / len(last), ref), 1)
281
+ e_tail = db[int((rb - tail_s) * 100):int(rb * 100)]
282
+ e_body = db[int(t0 * 100):int((rb - tail_s) * 100)]
283
+ if e_tail and e_body:
284
+ rec['tail_energy_drop_db'] = round(pct(e_tail, 50) - pct(e_body, 50), 1)
285
+ return rec
286
+
287
+
288
+ def is_push_pull(rec):
289
+ """밀당 = 끝 창에서 한 번 올렸다(≥peak_st) 내려옴(봉우리 대비 ≥peak_st)."""
290
+ p, l = rec.get('tail_peak_st'), rec.get('tail_last_st')
291
+ return (p is not None and l is not None and p >= C('peak_st') and p - l >= C('peak_st')
292
+ and not octave_suspect(rec))
293
+
294
+
295
+ def octave_suspect(rec):
296
+ """봉우리가 +octave_up_st 넘게 오르거나 끝 평균이 −octave_down_st 넘게 내림.
297
+
298
+ 🟥 위아래가 비대칭인 이유(첫 실사용에서 드러남): 처음엔 ±6 하나로 걸었는데, 한국어 평서문 끝은
299
+ 중앙 −7.5반음으로 «정상적으로» 깊게 내려가서 실녹화 214개 중 164개가 «의심」으로 빠졌다.
300
+ 위로 6반음 넘는 봉우리(실측 +13.2)는 드물고 옥타브 오류일 가능성이 크지만, 아래로는 한 옥타브
301
+ 가까이 가야 의심할 만하다.
302
+ """
303
+ return ((rec.get('tail_peak_st') or 0) > C('octave_up_st')
304
+ or (rec.get('tail_st') or 0) < -C('octave_down_st'))
305
+
306
+
307
+ # ── 외부 도구 (로컬) ──────────────────────────────────────────────────────────────────────────
308
+ def _exc(e):
309
+ return '%s: %s' % (type(e).__name__, str(e)[:120])
310
+
311
+
312
+ # ── 외부 입력 경계 ───────────────────────────────────────────────────────────────────────────
313
+ # 🟥 «외부 입력 하나가 전체를 죽인다」가 세 번 나왔다(codex R2 B-json · R4 거대 정수 · R5 노트 자리표시자).
314
+ # 사례별로 막지 않고 경계를 전수로 세운다. 각 경계는 «그 경계 전용 예외 → 그 항목 UNMEASURED(사유) ·
315
+ # exit 2」로 떨어진다. 경계 밖(우리 분석 코드)은 넓게 잡지 않는다 — 우리 버그를 «못 들음」으로 숨기지 않게.
316
+ # E1 환경변수 경로(도구 찾기) find_tool → ffmpeg: ①~④ / whisper: ①②
317
+ # E2 모델 경로 check_model → ①②
318
+ # E3 녹화 디코드(ffmpeg 출력) coach: decode 호출 → ①~④ (rc 0 + stderr 오류 = «부분」 강등, codex R6)
319
+ # E3b 녹화 길이(ffprobe 출력) coach: probe 호출 → 대조 못 하면 ①~④ «부분」
320
+ # E4 원고 로드(pptx/txt/md) coach: read_script → ①
321
+ # E5 whisper 실행 run_whisper → ①②
322
+ # E6 덩어리 파일 준비 transcribe: 쓰기 → ①②
323
+ # E7 whisper 출력(덩어리별) transcribe: 파싱 → 그 덩어리 누락 → ①② 부분 · exit 2
324
+ def find_tool(env, envvar, name):
325
+ """명시 경로가 있으면 그것만 쓴다(없으면 «없음」 — PATH 로 몰래 갈아타지 않는다). [경계 E1]"""
326
+ try:
327
+ p = env.get(envvar)
328
+ if p:
329
+ return (p, None) if (os.path.isfile(p) and os.access(p, os.X_OK)) else \
330
+ (None, '%s=%s 가 실행 파일이 아니다' % (envvar, p))
331
+ w = shutil.which(name, path=env.get('PATH', ''))
332
+ return (w, None) if w else (None, '%s 가 PATH 에 없다(%s 로 지정 가능)' % (name, envvar))
333
+ except Exception as e: # noqa: BLE001 — 경계 E1
334
+ return None, '%s 경로 확인 실패(%s)' % (name, _exc(e))
335
+
336
+
337
+ def check_model(path):
338
+ """[경계 E2] 모델 파일이 있나. 없으면 사유 문자열, 있으면 None."""
339
+ return None if os.path.isfile(path) else 'PREPREP_WHISPER_MODEL 이 가리키는 파일이 없다'
340
+
341
+
342
+ def run_whisper(cmd, env):
343
+ """[경계 E5] whisper-cli 한 번 실행."""
344
+ subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)
345
+
346
+
347
+ def decode(path, ffmpeg, env=None):
348
+ """반환 (샘플, stderr 오류 줄들).
349
+
350
+ 🟥 rc 0 은 «다 디코드했다」가 아니다(codex R6, 진짜 ffmpeg 로 재현): 손상 패킷을 만나면 ffmpeg 는
351
+ `-v error` 로 «Invalid data found…」를 찍고 그 구간을 버린 채 rc 0 으로 끝난다. 그래서 stderr 를
352
+ 버리지 않고 돌려준다 — 호출자가 «부분 디코드」로 강등한다.
353
+ """
354
+ p = subprocess.run([ffmpeg, '-nostdin', '-v', 'error', '-i', path, '-vn', '-ac', '1',
355
+ '-ar', str(SR), '-f', 's16le', '-'],
356
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
357
+ if p.returncode != 0:
358
+ raise RuntimeError('ffmpeg rc=%d: %s' % (p.returncode, p.stderr.decode('utf-8', 'replace')[-300:]))
359
+ raw = p.stdout[:len(p.stdout) - len(p.stdout) % 2]
360
+ a = array.array('h')
361
+ a.frombytes(raw)
362
+ if sys.byteorder == 'big':
363
+ a.byteswap()
364
+ errs = [l.strip() for l in p.stderr.decode('utf-8', 'replace').splitlines() if l.strip()]
365
+ return a, errs
366
+
367
+
368
+ def probe_duration(path, ffprobe, env=None):
369
+ """[경계 E3b] 녹화의 오디오 길이(초) — 오디오 스트림 길이, 없으면 컨테이너 길이."""
370
+ p = subprocess.run([ffprobe, '-v', 'error', '-select_streams', 'a:0', '-show_entries',
371
+ 'stream=duration:format=duration', '-of', 'default=nw=1', path],
372
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
373
+ if p.returncode != 0:
374
+ raise RuntimeError('ffprobe rc=%d' % p.returncode)
375
+ for l in p.stdout.decode('utf-8', 'replace').splitlines():
376
+ v = l.split('=', 1)[-1].strip()
377
+ try:
378
+ d = float(v)
379
+ except ValueError:
380
+ continue # N/A
381
+ if math.isfinite(d) and d > 0:
382
+ return d
383
+ raise ValueError('길이를 못 읽었다')
384
+
385
+
386
+ def write_wav(path, samples):
387
+ with wave.open(path, 'wb') as w:
388
+ w.setnchannels(1)
389
+ w.setsampwidth(2)
390
+ w.setframerate(SR)
391
+ s = array.array('h', samples)
392
+ if sys.byteorder == 'big':
393
+ s.byteswap()
394
+ w.writeframes(s.tobytes())
395
+
396
+
397
+ def words_from_whisper(tj, offset):
398
+ """whisper-cli -ojf JSON → 낱말 [{w,t0,t1,p}]. 시각은 덩어리 파일 기준 + offset."""
399
+ if not isinstance(tj, dict) or not isinstance(tj.get('transcription'), list):
400
+ raise ValueError('받아쓰기 JSON 모양이 아니다')
401
+ W = []
402
+ for s in tj['transcription']:
403
+ if not isinstance(s, dict) or not isinstance(s.get('tokens', []), list):
404
+ raise ValueError('받아쓰기 구간 모양이 아니다')
405
+ cur = None
406
+ for tk in s.get('tokens', []):
407
+ t = tk.get('text', '')
408
+ if t.startswith('[_') or t.startswith('<|'):
409
+ continue
410
+ fr, to = tk['offsets']['from'], tk['offsets']['to']
411
+ # 값 검증 — 모양만 맞고 값이 터무니없는 것(거대 정수 · NaN · 음수 · 뒤집힘)도 «못 읽음」이다
412
+ for v in (fr, to):
413
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or v < 0:
414
+ raise ValueError('토큰 오프셋 값이 이상하다: %r' % (v,))
415
+ if to < fr:
416
+ raise ValueError('토큰 오프셋이 뒤집혔다: %r > %r' % (fr, to))
417
+ a = fr / 1000 + offset
418
+ b = to / 1000 + offset
419
+ if t.startswith(' ') or cur is None:
420
+ if cur:
421
+ W.append(cur)
422
+ cur = {'w': t.strip(), 't0': round(a, 2), 't1': round(b, 2), 'p': tk.get('p', 1.0)}
423
+ else:
424
+ cur['w'] += t
425
+ cur['t1'] = round(b, 2)
426
+ cur['p'] = min(cur['p'], tk.get('p', 1.0))
427
+ if cur:
428
+ W.append(cur)
429
+ return [w for w in W if w['w']]
430
+
431
+
432
+ def voiced_fraction(x, a, b, step=0.02):
433
+ """덩어리 a..b 의 유성 비율(자기상관 피치가 잡힌 20ms 점의 몫). 무성 잡음(숨·마찰·클릭)은 낮다."""
434
+ ts = []
435
+ t = a
436
+ while t < b:
437
+ ts.append(t)
438
+ t += step
439
+ if not ts:
440
+ return 0.0
441
+ return sum(1 for t in ts if f0_at(x, t)) / len(ts)
442
+
443
+
444
+ class WhisperFailed(Exception):
445
+ pass
446
+
447
+
448
+ def transcribe(x, chunks, whisper, model, lang, tmp, batch=100, env=None):
449
+ """덩어리마다 따로 받아쓰기. 반환 (낱말들, 버린 환각 덩어리, 누락 덩어리 번호들, 무성이라 뺀 빈 덩어리,
450
+ 누락 사유 {덩어리: 사유}).
451
+
452
+ 누락 = JSON 이 없음 · 못 읽음 · 모양이 이상함 · **유효한데 낱말 0 인 말소리 덩어리**.
453
+ 🟥 마지막 것을 안 세면 «소리는 있는데 받아쓰기가 비었다」가 커버리지 구멍으로 조용히 빠진다
454
+ (codex 교차 리뷰 A2). 🟥 «말소리」 판정은 **길이가 아니라 유성 비율**이다(codex R2) — 처음엔
455
+ 0.35초 미만을 잡음으로 단정했는데, 0.3초 «즉」·«네」 같은 실제 발화의 빈 받아쓰기가 누락에도
456
+ 환각에도 안 잡혀 exit 0 이 났다. 유성 비율이 voiced_min 미만인 무성 잡음만 누락에서 뺀다.
457
+ whisper 를 아예 실행하지 못하면(ENOEXEC · 권한 …) WhisperFailed — ①② 측정불가로 올린다.
458
+ """
459
+ pad = C('pad_s')
460
+ files = []
461
+ try: # 경계 E6 — 덩어리 파일 준비
462
+ for j, (a, b) in enumerate(chunks):
463
+ s0 = max(0, int((a - pad) * SR))
464
+ s1 = min(len(x), int((b + pad) * SR))
465
+ p = os.path.join(tmp, 'c%04d.wav' % j)
466
+ write_wav(p, x[s0:s1])
467
+ files.append((p, s0 / SR))
468
+ except Exception as e: # noqa: BLE001 — 경계 E6
469
+ raise WhisperFailed('덩어리 파일 준비 실패(%s)' % _exc(e))
470
+ for i in range(0, len(files), batch):
471
+ try: # 경계 E5 — isfile·X_OK 를 통과해도 실행이 안 될 수 있다(ENOEXEC 등)
472
+ run_whisper([whisper, '-m', model, '-l', lang, '-ojf', '-np'] + [f for f, _ in files[i:i + batch]], env)
473
+ except Exception as e: # noqa: BLE001 — 경계 E5
474
+ raise WhisperFailed('whisper-cli 실행 불가(%s)' % (
475
+ e.strerror if isinstance(e, OSError) and e.strerror else _exc(e)))
476
+ words, dropped, missing, quiet_empty, why = [], [], [], [], {}
477
+ for j, (p, off) in enumerate(files):
478
+ jp = p + '.json'
479
+ if not os.path.exists(jp):
480
+ missing.append(j)
481
+ why[j] = 'JSON 없음'
482
+ continue
483
+ # 🟥 [경계 E7] 덩어리 «하나」를 파싱하는 경계 — 여기서는 어떤 예외든 그 덩어리의 누락이다(사유 보존).
484
+ # 예외 종류를 나열해 막으면 다음 종류가 또 전체를 죽인다(codex R2 B-json → R4 OverflowError,
485
+ # 같은 부류 두 번). 경계는 «읽기 + 파싱」 두 줄뿐이다 — 그 밖(전체 흐름)은 넓게 잡지 않는다.
486
+ try:
487
+ with open(jp, encoding='utf-8') as fh:
488
+ ws = words_from_whisper(json.load(fh), off)
489
+ except Exception as e: # noqa: BLE001 — 의도된 부류 경계
490
+ missing.append(j)
491
+ why[j] = '%s: %s' % (type(e).__name__, str(e)[:120])
492
+ continue
493
+ a, b = chunks[j]
494
+ if not ws:
495
+ if voiced_fraction(x, a, b) >= C('voiced_min'):
496
+ missing.append(j) # 말소리가 있는데 받아쓰기가 비었다
497
+ why[j] = '유성 덩어리의 빈 받아쓰기'
498
+ else:
499
+ quiet_empty.append(j)
500
+ continue
501
+ joined = re.sub(r'\s+', '', ''.join(w['w'] for w in ws))
502
+ if b - a < C('hallu_max_s') and STOCK_HALLU.match(joined):
503
+ dropped.append(j)
504
+ # 🟥 버린 덩어리도 유성이면 «말은 했는데 못 알아들었다」 = 누락이다(codex R3). 이 줄이 없으면
505
+ # 환각 필터가 위의 빈-받아쓰기 커버리지 검사를 우회한다 — 같은 오디오가 빈 받아쓰기면
506
+ # exit 2, «감사합니다」로 지어내면 exit 0 이 됐다. 무성이면 잡음으로 보고 누락에 안 센다.
507
+ if voiced_fraction(x, a, b) >= C('voiced_min'):
508
+ missing.append(j)
509
+ why[j] = '유성 덩어리의 상투 문구 환각(못 알아들음)'
510
+ continue
511
+ for w in ws:
512
+ w['chunk'] = j
513
+ words.append(w)
514
+ return words, dropped, missing, quiet_empty, why
515
+
516
+
517
+ # ── 원고 ─────────────────────────────────────────────────────────────────────────────────────
518
+ class ScriptUnreadable(Exception):
519
+ pass
520
+
521
+
522
+ def read_script(path):
523
+ """[(단위, 줄)]. 단위 = pptx 의 장 번호 또는 텍스트의 줄 번호. 무대 지시([간지]/[진행])는 뺀다."""
524
+ if not os.path.isfile(path):
525
+ raise ScriptUnreadable('원고 파일이 없다')
526
+ ext = os.path.splitext(path)[1].lower()
527
+ units = []
528
+ if ext == '.pptx':
529
+ try:
530
+ from pptx import Presentation
531
+ except ImportError:
532
+ raise ScriptUnreadable('python-pptx 없음 — pptx 노트를 못 읽는다')
533
+ try:
534
+ prs = Presentation(path)
535
+ except Exception as e: # noqa: BLE001 — 깨진 파일은 «못 읽음」으로 계상한다
536
+ raise ScriptUnreadable('pptx 를 못 연다: %s' % type(e).__name__)
537
+ for i, s in enumerate(prs.slides, 1):
538
+ if s.has_notes_slide:
539
+ tf = s.notes_slide.notes_text_frame # 노트 본문 자리표시자가 없으면 None(codex R5)
540
+ if tf is not None:
541
+ units.append((i, tf.text))
542
+ elif ext in ('.txt', '.md'):
543
+ # 🟥 한국어 원고는 CP949 로 저장된 것이 흔하다. UTF-8(BOM 허용) → CP949 순으로 시도하고, 둘 다
544
+ # 실패하거나 파일을 못 열면 트레이스백(exit 1 = «발견」으로 오독)이 아니라 «못 읽음」이다
545
+ # (codex 교차 리뷰 B1).
546
+ try:
547
+ with open(path, 'rb') as fh:
548
+ raw = fh.read()
549
+ except OSError as e:
550
+ raise ScriptUnreadable('원고 파일을 못 연다: %s' % type(e).__name__)
551
+ text = None
552
+ for enc in ('utf-8-sig', 'cp949'):
553
+ try:
554
+ text = raw.decode(enc)
555
+ break
556
+ except UnicodeDecodeError:
557
+ continue
558
+ if text is None:
559
+ raise ScriptUnreadable('원고 인코딩을 못 읽는다(UTF-8 · CP949 둘 다 실패)')
560
+ units = [(i, l) for i, l in enumerate(text.splitlines(), 1)]
561
+ else:
562
+ raise ScriptUnreadable('원고 형식을 모른다(%s) — .pptx(노트) · .txt · .md' % ext)
563
+ out = []
564
+ for u, text in units:
565
+ for l in text.splitlines():
566
+ l = l.strip()
567
+ if not l or re.match(r'^\[(간지|진행)\]', l):
568
+ continue
569
+ out.append((u, re.sub(r'^\(이어서\)\s*', '', l)))
570
+ if not out:
571
+ raise ScriptUnreadable('낭독 줄 0 — 노트가 비었다')
572
+ return out
573
+
574
+
575
+ def norm_chars(s):
576
+ return [c for c in s if re.match(r'[가-힣A-Za-z0-9]', c)]
577
+
578
+
579
+ def nsyl(w):
580
+ h = len(re.findall(r'[가-힣]', w))
581
+ up = len(re.findall(r'[A-Z]', w))
582
+ lo = len(re.findall(r'[a-z]+', w))
583
+ dg = len(re.findall(r'[0-9]', w))
584
+ return max(1, h + round(up * 1.5) + lo * 2 + round(dg * 1.5))
585
+
586
+
587
+ def jong(ch):
588
+ return (ord(ch) - 0xAC00) % 28 if '가' <= ch <= '힣' else -1
589
+
590
+
591
+ # ── 항목별 계기 ───────────────────────────────────────────────────────────────────────────────
592
+ def row_pron(script, words, chunks):
593
+ """① 원고 ↔ 받아쓰기 글자 대조. 1~2글자 치환 · 관형형 «-는」 탈락을 «후보」로 낸다."""
594
+ sc, s_unit = [], []
595
+ sw = []
596
+ for u, l in script:
597
+ for w in l.split():
598
+ sw.append((u, w))
599
+ for c in norm_chars(w):
600
+ sc.append(c)
601
+ s_unit.append(u)
602
+ tc, t_chunk = [], []
603
+ for w in words:
604
+ for c in norm_chars(w['w']):
605
+ tc.append(c)
606
+ t_chunk.append(w['chunk'])
607
+ if not sc or not tc:
608
+ return None
609
+ sm = difflib.SequenceMatcher(None, sc, tc, autojunk=False)
610
+ ops = sm.get_opcodes()
611
+ eq = set()
612
+ s2t = {}
613
+ for tag, i1, i2, j1, j2 in ops:
614
+ if tag == 'equal':
615
+ eq.update(range(i1, i2))
616
+ for k in range(i2 - i1):
617
+ s2t[i1 + k] = j1 + k
618
+ else:
619
+ for k in range(i1, i2):
620
+ s2t[k] = min(j1, len(tc) - 1)
621
+
622
+ def t_at(tj):
623
+ return chunks[t_chunk[min(tj, len(t_chunk) - 1)]][0]
624
+
625
+ subs = []
626
+ for tag, i1, i2, j1, j2 in ops:
627
+ a, b = ''.join(sc[i1:i2]), ''.join(tc[j1:j2])
628
+ if tag == 'replace' and len(a) <= 2 and len(b) <= 2 and not re.search(r'[0-9A-Za-z]', a + b):
629
+ subs.append({'t': t_at(j1), 'unit': s_unit[i1], 'script': a, 'heard': b,
630
+ 'ctx': ''.join(sc[max(0, i1 - 4):i1]) + '[' + a + '→' + b + ']' + ''.join(sc[i2:i2 + 4])})
631
+ neun = {'verb': [0, []], 'pron': [0, []]}
632
+ pos = 0
633
+ for u, w in sw:
634
+ chars = norm_chars(w)
635
+ core = re.sub(r'[^가-힣]', '', w)
636
+ if len(core) >= 2 and core.endswith('는') and jong(core[-2]) == 0:
637
+ kind = 'pron' if core[:-1] in PRONOUN_TOPIC else 'verb'
638
+ ni = pos + max(i for i, c in enumerate(chars) if c == '는') # 원고 글자열에서 그 «는」의 자리
639
+ neun[kind][0] += 1
640
+ if ni not in eq:
641
+ neun[kind][1].append({'t': t_at(s2t.get(ni, 0)), 'unit': u, 'word': w})
642
+ pos += len(chars)
643
+ return {'ratio': round(sm.ratio(), 3), 'subs': subs, 'neun': neun}
644
+
645
+
646
+ def row_conj(words, chunks):
647
+ """② 접속사: 덩어리 첫 낱말인가 · 홀로 섰나 · 앞뒤 쉼 · 늘임(1.0 = 지역 말속도 그대로)."""
648
+ by = {}
649
+ for i, w in enumerate(words):
650
+ by.setdefault(w['chunk'], []).append(i)
651
+
652
+ def gap_before(j):
653
+ return round(chunks[j][0] - chunks[j - 1][1], 2) if j > 0 else None
654
+
655
+ def gap_after(j):
656
+ return round(chunks[j + 1][0] - chunks[j][1], 2) if j + 1 < len(chunks) else None
657
+
658
+ def local_rate(j):
659
+ js = [q for q in range(max(0, j - 3), min(len(chunks), j + 4)) if q in by]
660
+ s = sum(nsyl(words[i]['w']) for q in js for i in by[q])
661
+ d = sum(chunks[q][1] - chunks[q][0] for q in js)
662
+ return s / d if d else None
663
+
664
+ conj = []
665
+ for i, w in enumerate(words):
666
+ base = re.sub(r'[.,!?~"\']', '', w['w'])
667
+ hit = next((c for c in CONJ if base == c), None)
668
+ if not hit:
669
+ continue
670
+ j = w['chunk']
671
+ ids = by[j]
672
+ alone = len(ids) == 1
673
+ first = ids[0] == i
674
+ a, b = chunks[j]
675
+ lr = local_rate(j)
676
+ rec = {'conj': hit, 't': a if first else w['t0'], 'alone': alone, 'first_in_chunk': first,
677
+ 'pause_before': gap_before(j) if first else 0.0,
678
+ 'pause_after': gap_after(j) if (alone or ids[-1] == i) else 0.0}
679
+ if alone:
680
+ rec['dur'], rec['dur_src'] = round(b - a, 2), '음향 경계'
681
+ else:
682
+ rec['dur'], rec['dur_src'] = round(w['t1'] - w['t0'], 2), '토큰 시각(UNCALIBRATED)'
683
+ # 1음절(«즉」)은 늘임을 안 낸다 — 음절 하나의 길이는 앞뒤 자음에 휘둘린다(프로토타입도 뺐다)
684
+ rec['stretch'] = round((rec['dur'] / len(hit)) * lr, 2) if (lr and rec['dur'] > 0 and len(hit) >= 2) \
685
+ else None
686
+ conj.append(rec)
687
+ commas, ends = [], []
688
+ for i, w in enumerate(words):
689
+ last_in_chunk = by[w['chunk']][-1] == i
690
+ g = gap_after(w['chunk']) if last_in_chunk else 0.0
691
+ if w['w'].endswith(','):
692
+ commas.append(g)
693
+ elif re.search(r'[.?!]["\']?$', w['w']) and g is not None:
694
+ ends.append(g)
695
+ return {'conj': conj, 'commas': commas, 'ends': ends}
696
+
697
+
698
+ def sentence_ends(chunks, words):
699
+ """③ 측정 대상 끝: 받아쓰기가 있으면 문장부호로 끝나는 덩어리, 없으면 뒤 쉼이 긴 덩어리."""
700
+ if words is not None:
701
+ last = {}
702
+ for w in words:
703
+ last[w['chunk']] = w['w']
704
+ return [j for j in sorted(last) if re.search(r'[.?!]["\']?$', last[j])], '받아쓰기 문장부호'
705
+ out = []
706
+ for j, (a, b) in enumerate(chunks):
707
+ gap = chunks[j + 1][0] - b if j + 1 < len(chunks) else 99
708
+ if gap >= C('phrase_end_gap_s') and b - a >= 0.5:
709
+ out.append(j)
710
+ return out, '뒤 쉼 ≥ %.2f초(UNCALIBRATED 대리)' % C('phrase_end_gap_s')
711
+
712
+
713
+ def chunk_level(db, a, b):
714
+ seg = db[int(a * 100):int(b * 100)]
715
+ return pct(seg, 90) if seg else None
716
+
717
+
718
+ def row_greet(db, chunks, words):
719
+ """④ 첫·끝 덩어리 크기를 녹화 자기 분포(중앙 · 하위 10%)에 대고 잰다. 끝 덩어리는 끝 꺼짐까지."""
720
+ lv = [chunk_level(db, a, b) for a, b in chunks]
721
+ med, p10 = pct(lv, 50), pct(lv, 10)
722
+ first, last = 0, len(chunks) - 1
723
+ if words is not None: # 받아쓰기가 있으면 인사 덩어리를 낱말로 찾는다(없으면 처음·끝 덩어리)
724
+ text = {}
725
+ for w in words:
726
+ text[w['chunk']] = text.get(w['chunk'], '') + w['w']
727
+ f = [j for j in sorted(text)[:5] if '안녕' in text[j]]
728
+ l = [j for j in sorted(text)[-5:] if re.search('감사|고맙', text[j])]
729
+ first, last = (f[0] if f else first), (l[-1] if l else last)
730
+ out = {'median': med, 'p10': p10}
731
+ for k, j in (('first', first), ('last', last)):
732
+ a, b = chunks[j]
733
+ e = {'chunk': j, 't': a, 'level': lv[j], 'vs_median': lv[j] - med, 'below_p10': lv[j] < p10,
734
+ 'rank_quiet': 1 + sum(1 for v in lv if v < lv[j]), 'n': len(lv)}
735
+ if k == 'last':
736
+ tw = min(C('tail_s'), (b - a) / 2)
737
+ et = db[int((b - tw) * 100):int(b * 100)]
738
+ eb = db[int(a * 100):int((b - tw) * 100)]
739
+ if et and eb:
740
+ e['tail_win_s'], e['tail_drop_db'] = tw, pct(et, 50) - pct(eb, 50)
741
+ out[k] = e
742
+ return out
743
+
744
+
745
+ # ── 코칭 본체 ─────────────────────────────────────────────────────────────────────────────────
746
+ def _row(n, name, status, cause=None, why='', obs=None, ev=None):
747
+ return {'n': n, 'name': name, 'status': status, 'cause': cause, 'why': why,
748
+ 'obs': obs or [], 'evidence': ev or []}
749
+
750
+
751
+ NAMES = {1: '소리 내 읽기·발음', 2: '쉼표 여유 · 접속사 끌기', 3: '어미 밀당(문장 끝 억양)',
752
+ 4: '첫 인사·끝인사 강조', 5: '시선', 6: '스피치보다 내용'}
753
+
754
+
755
+ def coach(recording, script_path=None, skip=(), env=None):
756
+ env = dict(os.environ if env is None else env)
757
+ skip = set(skip)
758
+ rep = {'lane': LANE, 'recording': recording, 'deps': {}, 'notes': [],
759
+ 'cal': {k: {'value': v, 'meaning': m, 'status': 'UNCALIBRATED'} for k, (v, m) in CAL.items()}}
760
+ rows = {}
761
+ for n in (5, 6):
762
+ rows[n] = _row(n, NAMES[n], ST_NONE, CAUSE_DESIGN,
763
+ '오디오 계기 범위 밖 — 영상(시선 추정)이 필요하다' if n == 5 else
764
+ '계기 대상이 아니다 — 내용 정합은 이 스킬의 다른 레인(L1~L15)이 본다')
765
+ for n in (1, 2, 3, 4):
766
+ if n in skip:
767
+ rows[n] = _row(n, NAMES[n], ST_NONE, CAUSE_DECLARED, '범위에서 뺌(선언 — --skip/--audio-only)')
768
+
769
+ def finish(whole_reason=None):
770
+ for n in (1, 2, 3, 4):
771
+ if n not in rows:
772
+ rows[n] = _row(n, NAMES[n], ST_NONE, CAUSE_DEP, whole_reason or '계기 미실행')
773
+ if rep.get('decode_issue'): # 들린 부분의 표는 내되 «다 들음」이라 하지 않는다
774
+ for n in (1, 2, 3, 4):
775
+ r_ = rows[n]
776
+ if r_['cause'] in (None, CAUSE_INCOMPLETE):
777
+ r_['status'], r_['cause'] = ST_PARTIAL, CAUSE_INCOMPLETE
778
+ r_['why'] = '디코드 불완전: %s · %s' % (rep['decode_issue'], r_['why'])
779
+ rep['rows'] = [rows[n] for n in range(1, 7)]
780
+ unmeasured = [r['n'] for r in rep['rows'] if r['cause'] in (CAUSE_DEP, CAUSE_INCOMPLETE)]
781
+ rep['rc'] = 2 if unmeasured else 0
782
+ rep['unmeasured_rows'] = unmeasured
783
+ return rep
784
+
785
+ ffmpeg, why = find_tool(env, 'PREPREP_FFMPEG', 'ffmpeg')
786
+ rep['deps']['ffmpeg'] = 'found' if ffmpeg else 'absent — ' + why
787
+ if not ffmpeg:
788
+ return finish('ffmpeg 없음 — 녹화를 못 연다(%s)' % why)
789
+ try: # 경계 E3 — 녹화 디코드(ffmpeg 출력 포함)
790
+ if not os.path.isfile(recording):
791
+ return finish('녹화 파일이 없다')
792
+ x, dec_errs = decode(recording, ffmpeg, env)
793
+ except Exception as e: # noqa: BLE001 — 경계 E3
794
+ return finish('디코드 실패(%s)' % _exc(e))
795
+ # 부분 디코드 판정 — 오류 줄 · 길이 부족 · 길이 대조 불가, 셋 중 하나라도면 ①~④ 를 «부분」으로 강등
796
+ issues = []
797
+ if dec_errs:
798
+ issues.append('디코드 오류 %d줄 — 첫 줄: %s' % (len(dec_errs), dec_errs[0][:100]))
799
+ ffprobe, pwhy = find_tool(env, 'PREPREP_FFPROBE', 'ffprobe')
800
+ if not ffprobe and not env.get('PREPREP_FFPROBE'):
801
+ sib = os.path.join(os.path.dirname(ffmpeg), 'ffprobe') # ffmpeg 옆에 같이 깔리는 게 보통이다
802
+ if os.path.isfile(sib) and os.access(sib, os.X_OK):
803
+ ffprobe, pwhy = sib, None
804
+ decoded_s = len(x) / SR
805
+ if not ffprobe:
806
+ issues.append('녹화 길이 대조 못 함(%s) — 잘린 디코드를 못 가린다' % pwhy)
807
+ else:
808
+ try: # 경계 E3b — ffprobe 출력
809
+ dur = probe_duration(recording, ffprobe, env)
810
+ rep['recording_s'] = round(dur, 2)
811
+ if dur - decoded_s >= C('decode_short_frac') * dur:
812
+ issues.append('디코드 길이 %.1f초 < 녹화 %.1f초 (%.1f%% 짧음)' % (decoded_s, dur,
813
+ 100 * (dur - decoded_s) / dur))
814
+ except Exception as e: # noqa: BLE001 — 경계 E3b
815
+ issues.append('녹화 길이 대조 못 함(%s)' % _exc(e))
816
+ rep['decode_issue'] = ' · '.join(issues) if issues else None
817
+ db = frame_db(x)
818
+ chunks, thr = segment(db)
819
+ rep['duration_s'] = round(len(x) / SR, 2)
820
+ rep['n_chunks'] = len(chunks)
821
+ if not chunks:
822
+ return finish('발화 덩어리 0 — 무음이거나 계기가 못 들었다(«발견 0」 아님)')
823
+ rep['speech_s'] = round(sum(b - a for a, b in chunks), 2)
824
+
825
+ # 받아쓰기(선택 의존성)
826
+ words = None
827
+ asr_gap = None
828
+ need_asr = bool({1, 2} - skip)
829
+ if need_asr:
830
+ whisper, wwhy = find_tool(env, 'PREPREP_WHISPER_CLI', 'whisper-cli')
831
+ model = env.get('PREPREP_WHISPER_MODEL')
832
+ if not whisper:
833
+ asr_why = 'whisper-cli 없음 (%s)' % wwhy
834
+ elif not model:
835
+ asr_why = 'PREPREP_WHISPER_MODEL 미지정 — 모델 경로 기본값은 일부러 없다'
836
+ else:
837
+ try:
838
+ asr_why = check_model(model)
839
+ except Exception as e: # noqa: BLE001 — 경계 E2
840
+ asr_why = '모델 경로 확인 실패(%s)' % _exc(e)
841
+ rep['deps']['whisper'] = 'found' if not asr_why else 'absent — ' + asr_why
842
+ if asr_why is None:
843
+ tmp = None
844
+ try:
845
+ tmp = tempfile.mkdtemp(prefix='preprep_coach_')
846
+ words, dropped, missing, quiet, miss_why = transcribe(x, chunks, whisper, model,
847
+ env.get('PREPREP_WHISPER_LANG', 'ko'), tmp, env=env)
848
+ except WhisperFailed as e:
849
+ words, asr_why = None, str(e)
850
+ rep['deps']['whisper'] = 'found but failed — ' + asr_why
851
+ except OSError as e: # 임시 폴더를 못 만든다
852
+ words, asr_why = None, '받아쓰기 임시 폴더 실패(%s)' % _exc(e)
853
+ rep['deps']['whisper'] = 'found but failed — ' + asr_why
854
+ finally:
855
+ if tmp:
856
+ shutil.rmtree(tmp, ignore_errors=True)
857
+ if asr_why is None:
858
+ rep['asr'] = {'chunks': len(chunks), 'missing': len(missing),
859
+ 'missing_at': [fmt_t(chunks[j][0]) for j in missing],
860
+ 'missing_why': {fmt_t(chunks[j][0]): miss_why.get(j, '') for j in missing},
861
+ 'hallucination_dropped': len(dropped),
862
+ 'hallucination_dropped_at': [fmt_t(chunks[j][0]) for j in dropped[:10]],
863
+ 'unvoiced_empty': len(quiet)}
864
+ if len(missing) == len(chunks):
865
+ asr_why, words = '받아쓰기 출력 0 — whisper 가 한 덩어리도 못 냈다', None
866
+ elif not words:
867
+ # 🟥 파일은 나왔는데 낱말이 0 — 빈 받아쓰기를 «접속사 0개 · 발음 어긋남 0」으로 렌더하면
868
+ # «못 들었다」가 «깨끗하다」로 접힌다. 측정불가로 올린다.
869
+ asr_why, words = '받아쓰기 낱말 0 — 빈 받아쓰기(또는 전부 환각으로 걸러짐)', None
870
+ elif missing:
871
+ # 🟥 노트만 달면 ② 가 «잡음」· exit 0 으로 나간다(codex 교차 리뷰 A1). 아래에서 ①② 를
872
+ # «부분 · 일부 못 들음」으로 묶고 rc 를 2 로 만든다 — 누락 비율과 위치를 같이 낸다.
873
+ asr_gap = '받아쓰기 누락 덩어리 %d/%d (%.0f%%) — 위치 %s%s — 그 몫은 안 들었다' % (
874
+ len(missing), len(chunks), 100.0 * len(missing) / len(chunks),
875
+ ', '.join(rep['asr']['missing_at'][:10]), ' …' if len(missing) > 10 else '')
876
+ rep['notes'].append(asr_gap)
877
+ if asr_why:
878
+ for n in (1, 2):
879
+ if n not in rows:
880
+ rows[n] = _row(n, NAMES[n], ST_NONE, CAUSE_DEP, asr_why +
881
+ ' — ③④ 는 오디오만으로 돈다. 범위에서 빼려면 --audio-only')
882
+
883
+ # ① 발음
884
+ if 1 not in rows:
885
+ if not script_path:
886
+ rows[1] = _row(1, NAMES[1], ST_NONE, CAUSE_DEP,
887
+ '원고 없음 — --script 로 원고(pptx 노트 · txt · md)를 주거나 --skip 1')
888
+ else:
889
+ r = None
890
+ try: # 경계 E4 — 원고 로드(pptx/txt/md)
891
+ script = read_script(script_path)
892
+ except ScriptUnreadable as e:
893
+ rows[1] = _row(1, NAMES[1], ST_NONE, CAUSE_DEP, '원고를 못 읽는다: %s' % e)
894
+ except Exception as e: # noqa: BLE001 — 경계 E4
895
+ rows[1] = _row(1, NAMES[1], ST_NONE, CAUSE_DEP, '원고를 못 읽는다(%s)' % _exc(e))
896
+ if 1 not in rows:
897
+ r = row_pron(script, words, chunks) # 우리 분석 코드 — 경계 밖
898
+ if 1 not in rows:
899
+ if r is None:
900
+ rows[1] = _row(1, NAMES[1], ST_NONE, CAUSE_DEP, '대조할 글자가 0 — 원고나 받아쓰기가 비었다')
901
+ else:
902
+ vlost, plost = r['neun']['verb'][1], r['neun']['pron'][1]
903
+ obs = ['원고 ↔ 받아쓰기 글자 일치율 %.3f' % r['ratio'],
904
+ '1~2글자 치환 %d곳(발음 «후보」)' % len(r['subs']),
905
+ '관형형 «-는」(열린 음절 + 는) 받아쓰기에서 사라짐: %d/%d · 대명사 주제 «-는」 %d/%d'
906
+ % (len(vlost), r['neun']['verb'][0], len(plost), r['neun']['pron'][0])]
907
+ ev = [(e['t'], '«%s」 → «-는」 탈락 후보 (원고 단위 %s)' % (e['word'], e['unit'])) for e in vlost[:3]]
908
+ ev += [(s['t'], '%s (원고 단위 %s)' % (s['ctx'], s['unit'])) for s in r['subs'][:3 - len(ev)]]
909
+ rows[1] = _row(1, NAMES[1], ST_PARTIAL, None,
910
+ '후보다 — 받아쓰기 오류와 실제 발음을 이 계기는 못 가른다. 사람 귀로 확인 전엔 판정 아님',
911
+ obs, ev)
912
+ rep['pron_candidates'] = {'subs': r['subs'], 'neun_lost': vlost, 'neun_pron_lost': plost}
913
+
914
+ # ② 접속사 · 쉼표
915
+ if 2 not in rows:
916
+ r = row_conj(words, chunks)
917
+ cj = r['conj']
918
+ alone = [c for c in cj if c['alone'] and c['stretch'] is not None]
919
+ drag = [c for c in alone if c['stretch'] >= C('drag_stretch')]
920
+ obs = ['접속사 %d개 · 홀로 선 것 %d · 앞에 쉼 있는 것 %d'
921
+ % (len(cj), sum(1 for c in cj if c['alone']), sum(1 for c in cj if (c['pause_before'] or 0) > 0))]
922
+ if alone:
923
+ s = sorted(c['stretch'] for c in alone)
924
+ obs.append('홀로 선 접속사 늘임 %.2f~%.2f (중앙 %.2f) · 끌기 후보(≥%.2f, UNCALIBRATED) %d개'
925
+ % (s[0], s[-1], s[len(s) // 2], C('drag_stretch'), len(drag)))
926
+ if r['commas']:
927
+ rz = [g for g in r['commas'] if g and g > 0]
928
+ obs.append('쉼표 %d곳 중 쉼으로 실현 %d · 쉼 중앙 %.2f초'
929
+ % (len(r['commas']), len(rz), pct(rz, 50) if rz else 0.0))
930
+ if r['ends']:
931
+ obs.append('문장 끝 뒤 쉼 중앙 %.2f초 (n=%d)' % (pct(r['ends'], 50), len(r['ends'])))
932
+ pick = sorted(alone, key=lambda c: -c['stretch'])[:3] if alone else cj[:3]
933
+ ev = [(c['t'], '«%s」 앞 쉼 %s초 · 뒤 쉼 %s초 · 늘임 %s (%s)'
934
+ % (c['conj'], c['pause_before'], c['pause_after'], c['stretch'], c['dur_src'])) for c in pick]
935
+ rows[2] = _row(2, NAMES[2], ST_MEASURED if cj else ST_PARTIAL, None,
936
+ '위치와 쉼은 음향 경계에서 잰다 · «끌기」 문턱은 UNCALIBRATED' if cj else
937
+ '접속사 0개 — 끌기는 못 봤다(0 은 «안 끌었다」가 아니다). 쉼표·문장 끝 쉼만',
938
+ obs, ev)
939
+ rep['conjunctions'] = cj
940
+
941
+ # 받아쓰기 일부 누락 → ①② 는 «부분」을 넘지 못하고 rc 를 0 으로 두지 않는다
942
+ if asr_gap:
943
+ for n in (1, 2):
944
+ r_ = rows.get(n)
945
+ if r_ is not None and r_['cause'] is None:
946
+ r_['status'], r_['cause'] = ST_PARTIAL, CAUSE_INCOMPLETE
947
+ r_['why'] = asr_gap + ' · ' + r_['why']
948
+
949
+ # ③ 문장 끝
950
+ if 3 not in rows:
951
+ idx, src = sentence_ends(chunks, words)
952
+ recs = []
953
+ for j in idx:
954
+ m = end_metrics(x, db, thr, chunks[j][0], chunks[j][1])
955
+ if m.get('tail_st') is not None:
956
+ recs.append(m)
957
+ if len(recs) < 3:
958
+ rows[3] = _row(3, NAMES[3], ST_NONE, CAUSE_DEP,
959
+ '피치를 잴 수 있는 문장 끝이 %d개(<3) — 유성 구간이 짧거나 피치를 못 잡았다' % len(recs))
960
+ else:
961
+ v = sorted(m['tail_st'] for m in recs)
962
+ n = len(v)
963
+ mean = sum(v) / n
964
+ sd = math.sqrt(sum((z - mean) ** 2 for z in v) / n)
965
+ pp = [m for m in recs if is_push_pull(m)]
966
+ sus = [m for m in recs if octave_suspect(m)]
967
+ obs = ['측정한 끝 %d개 (대상 고르기: %s)' % (n, src),
968
+ '끝 300ms 평균 피치(본문 대비) 중앙 %+.1f반음 · sd %.1f' % (v[n // 2], sd),
969
+ '하강(<-1) %d%% · 올림(>+1) %d%% · 올렸다 내림(밀당) %d%%'
970
+ % (round(100 * sum(1 for z in v if z < -1) / n), round(100 * sum(1 for z in v if z > 1) / n),
971
+ round(100 * len(pp) / n)),
972
+ '옥타브 오류 의심 %d개 — 분포에는 남기고 근거 예시·밀당 셈에서는 뺐다' % len(sus)]
973
+ med = v[n // 2]
974
+ rep_ = sorted([m for m in recs if not octave_suspect(m)], key=lambda m: abs(m['tail_st'] - med))
975
+ ev = [(m['end'], '대표 끝(중앙 근처) %+.1f반음' % m['tail_st']) for m in rep_[:2]]
976
+ ev += [(m['end'], '밀당 — 봉우리 %+.1f → 마지막 %+.1f' % (m['tail_peak_st'], m['tail_last_st']))
977
+ for m in pp[:1]]
978
+ rows[3] = _row(3, NAMES[3], ST_PARTIAL, None,
979
+ '기준선 없음 — 한국어 평서문은 원래 내려간다. 모양의 묘사이지 결함 판정이 아니다', obs, ev)
980
+ rep['sentence_ends'] = recs
981
+
982
+ # ④ 첫·끝 인사
983
+ if 4 not in rows:
984
+ g = row_greet(db, chunks, words)
985
+ obs = ['덩어리 크기(p90 dBFS) 중앙 %.1f · 하위 10%% %.1f%s' % (
986
+ g['median'], g['p10'], ' — 덩어리 10개 미만이라 하위 10%는 곧 최솟값이다' if len(chunks) < 10 else '')]
987
+ ev = []
988
+ for tag, k in (('첫', 'first'), ('끝', 'last')):
989
+ e = g[k]
990
+ line = '%s 덩어리 %.1f dB (중앙 대비 %+.1f · 조용한 쪽부터 %d/%d)%s' % (
991
+ tag, e['level'], e['vs_median'], e['rank_quiet'], e['n'],
992
+ ' · 하위 10% 아래' if e['below_p10'] else '')
993
+ if e.get('tail_drop_db') is not None:
994
+ line += ' · 끝 %.2f초가 %+.1f dB' % (e['tail_win_s'], e['tail_drop_db'])
995
+ obs.append(line)
996
+ ev.append((e['t'], line))
997
+ rows[4] = _row(4, NAMES[4], ST_MEASURED, None,
998
+ '녹화 자기 분포에 대고 잰 순위다 — 크다/작다의 절대 문턱은 없다', obs, ev)
999
+ return finish()
1000
+
1001
+
1002
+ # ── 출력 ─────────────────────────────────────────────────────────────────────────────────────
1003
+ def render(rep):
1004
+ out = ['── 발표 코칭 (%s · advisory) ──' % rep['lane'],
1005
+ ' 녹화: %s · 길이 %s · 발화 덩어리 %s'
1006
+ % (rep['recording'], fmt_t(rep.get('duration_s')), rep.get('n_chunks', '—')),
1007
+ ' 의존성: ' + ' · '.join('%s %s' % kv for kv in rep['deps'].items())]
1008
+ if rep.get('decode_issue'):
1009
+ out.append(' ⚠️ 디코드 불완전 — %s' % rep['decode_issue'])
1010
+ if 'asr' in rep:
1011
+ a = rep['asr']
1012
+ out.append(' 받아쓰기: 덩어리 %d · 누락 %d · 환각으로 버림 %d %s'
1013
+ % (a['chunks'], a['missing'], a['hallucination_dropped'],
1014
+ ('(' + ', '.join(a['hallucination_dropped_at']) + ')') if a['hallucination_dropped_at'] else ''))
1015
+ for t_, w_ in list(a.get('missing_why', {}).items())[:10]:
1016
+ out.append(' 못 들음 %s — %s' % (t_, w_))
1017
+ out.append(' 🟥 이 표는 판정이 아니다 — 숫자는 묘사이고 문턱은 전부 UNCALIBRATED 다.')
1018
+ out.append('')
1019
+ for r in rep['rows']:
1020
+ tag = r['status']
1021
+ if r['cause'] == CAUSE_DESIGN:
1022
+ tag += '(범위 밖 — 설계)'
1023
+ elif r['cause'] == CAUSE_DECLARED:
1024
+ tag += '(범위에서 뺌 — 선언)'
1025
+ elif r['cause'] == CAUSE_DEP:
1026
+ tag += '(UNMEASURED — 통과 아님)'
1027
+ elif r['cause'] == CAUSE_INCOMPLETE:
1028
+ tag += '(일부 못 들음 — 통과 아님)'
1029
+ out.append(' %s %s — %s' % ('①②③④⑤⑥'[r['n'] - 1], r['name'], tag))
1030
+ if r['why']:
1031
+ out.append(' ' + r['why'])
1032
+ for o in r['obs']:
1033
+ out.append(' · ' + o)
1034
+ for t, d in r['evidence']:
1035
+ out.append(' ▸ %s %s' % (fmt_t(t), d))
1036
+ for n in rep['notes']:
1037
+ out.append(' ⚠️ ' + n)
1038
+ out.append('')
1039
+ out.append(' 보정 상수 (전부 UNCALIBRATED — 녹화 1건 · TTS 대조군에서 고른 값):')
1040
+ for k, c in rep['cal'].items():
1041
+ out.append(' %-17s %-6s %s' % (k, c['value'], c['meaning']))
1042
+ if rep['rc'] == 2:
1043
+ out.append('\n exit 2 — 측정 못 한 항목: %s. «발견 0」 이 아니라 «못 들었다」다(통과 아님).'
1044
+ % ', '.join('①②③④⑤⑥'[n - 1] for n in rep['unmeasured_rows']))
1045
+ else:
1046
+ out.append('\n exit 0 — 범위 안 항목을 전부 들었다. «좋은 발표」라는 뜻이 아니다.')
1047
+ return '\n'.join(out)
1048
+
1049
+
1050
+ def main(argv=None):
1051
+ ap = argparse.ArgumentParser(description='preprep L16 speech-coach — 리허설 녹화 코칭 6항 (advisory)')
1052
+ ap.add_argument('recording')
1053
+ ap.add_argument('--script', help='원고: 발표자 노트가 든 .pptx 또는 .txt/.md')
1054
+ ap.add_argument('--audio-only', action='store_true', help='①② 를 범위에서 뺀다(선언) — 받아쓰기 없이')
1055
+ ap.add_argument('--skip', default='', help='범위에서 뺄 항목 번호, 쉼표로(예: 1 또는 1,2)')
1056
+ ap.add_argument('--json', dest='json_out', help='전체 결과를 JSON 으로 쓴다')
1057
+ a = ap.parse_args(argv)
1058
+ # 🟥 isdigit() 는 «²» 같은 유니코드 숫자도 참이라 int() 에서 죽는다 — 허용 낱말을 정확히 대조한다.
1059
+ # 모르는 낱말은 argparse 오류(exit 2)로 — «측정 못 함」 과 같은 쪽, exit 1 크래시가 아니다.
1060
+ toks = [s.strip() for s in a.skip.split(',') if s.strip()]
1061
+ bad = [s for s in toks if s not in ('1', '2', '3', '4')]
1062
+ if bad:
1063
+ ap.error('--skip 은 1~4 만 받는다: %s' % ', '.join(repr(s) for s in bad))
1064
+ skip = {int(s) for s in toks}
1065
+ if a.audio_only:
1066
+ skip |= {1, 2}
1067
+ rep = coach(a.recording, a.script, skip)
1068
+ print(render(rep))
1069
+ if a.json_out:
1070
+ with open(a.json_out, 'w', encoding='utf-8') as fh:
1071
+ json.dump(rep, fh, ensure_ascii=False, indent=1)
1072
+ return rep['rc']
1073
+
1074
+
1075
+ if __name__ == '__main__':
1076
+ try:
1077
+ from usage_ledger import observe as _observe
1078
+ except Exception: # noqa: BLE001 — 원장은 옵트인이고 없어도 판정은 같다
1079
+ _observe = None
1080
+ sys.exit(_observe('preprep', 'speech-coach', main) if _observe else main())