From 1a2e27ae5a56ff591e8a045a13c904d11f2faf3c Mon Sep 17 00:00:00 2001 From: kim Date: Sat, 17 Oct 2026 21:57:15 +0900 Subject: [PATCH] =?UTF-8?q?scripts/stt-bench.py:=20faster-whisper=20?= =?UTF-8?q?=EB=AA=A8=EB=8D=B8=20=EB=B9=84=EA=B5=90(TTS=20=ED=95=A9?= =?UTF-8?q?=EC=84=B1=20=EC=9D=8C=EC=84=B1+=EC=9E=A1=EC=9D=8C=20=EB=B3=80?= =?UTF-8?q?=ED=98=95,=20CER=C2=B7=EC=9A=A9=EC=96=B4=20=EC=A0=81=EC=A4=91?= =?UTF-8?q?=C2=B7=EC=86=8D=EB=8F=84)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- scripts/stt-bench.py | 211 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 211 insertions(+) create mode 100644 scripts/stt-bench.py diff --git a/scripts/stt-bench.py b/scripts/stt-bench.py new file mode 100644 index 0000000..34ea556 --- /dev/null +++ b/scripts/stt-bench.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 +""" +음성 인식(STT) 모델 비교: faster-whisper 모델 여러 개를 같은 음성으로 돌려 한국어 정확도와 속도를 잰다. + +음성은 홈클로 TTS(/api/voice/tts, 복제 음성)로 정답 문장을 합성해 만들고, 깨끗한 음성 외에 잡음(SNR 10dB)· +작은 소리 변형을 더해 어려운 조건도 본다. 합성 음성은 실제 사람 목소리보다 깨끗하므로 절대 수치보다 +"모델 간 상대 비교"로 읽을 것. + +사용 (voice-venv의 python으로): + HC_PASSWORD=... voice-venv/bin/python scripts/stt-bench.py --models medium,large-v3-turbo --device-index 1 --out r.json + +채점: 공백·문장부호를 뺀 글자 단위 오류율(CER). 인식문의 아라비아 숫자는 한글 수사로 바꿔 비교한다(정답은 한글 수사로 썼다). +고유어(용어) 적중률은 "정답 용어가 인식문에 그대로 들어 있는지"로 본다. +""" +import argparse, json, os, re, struct, sys, time, wave, urllib.request, hashlib +import numpy as np + +BASE = "http://localhost:18789" +OUTDIR = os.environ.get("STT_BENCH_DIR", "/tmp/stt-bench") + +# (정답 문장, 포함돼야 할 고유어/핵심어) +SENTENCES = [ + ("클로서버 상태 알려줘", ["클로서버"]), + ("지서버 깨워줘", ["지서버"]), + ("옥토서버에서 프린터 확인해", ["옥토서버"]), + ("트루나스 용량이 얼마나 남았어", ["트루나스"]), + ("홈클로 재시작해도 될까", ["홈클로"]), + ("시어엔진으로 검색해줘", ["시어엔진"]), + ("라즈베리 파이에 카메라 연결하는 방법 알려줘", ["라즈베리 파이"]), + ("홈어시스턴트에서 에어컨 이십사 도로 맞춰줘", ["홈어시스턴트"]), + ("탐정앱에서 사건 메모를 정리해줘", ["탐정앱"]), + ("기상청에서 미세먼지 농도 확인해줘", ["기상청", "미세먼지"]), + ("오늘 구미 날씨 어때", ["구미", "날씨"]), + ("내일 오후에 비 오는지 알려줘", ["내일", "오후"]), + ("설탕 오십 그램이랑 밀가루 이백 그램 넣어", ["오십", "이백"]), + ("전압이 오 볼트인데 전류는 이 암페어야", ["볼트", "암페어"]), + ("지금 혈당이 백십 밀리그램 퍼 데시리터야", ["혈당", "백십"]), + ("노즐 온도를 이백십 도로 올려줘", ["이백십"]), + ("그래픽카드 메모리는 십이 기가바이트야", ["기가바이트"]), + ("엔트로피와 해밀토니안은 어떤 관계야", ["엔트로피", "해밀토니안"]), + ("최근 한 달 동안 전기 사용량을 표로 보여줘", ["전기", "사용량"]), + ("마당 카메라 지금 화면 보여줘", ["마당", "카메라"]), + ("작업실 프로젝트 진행 상황을 요약해줘", ["작업실", "프로젝트"]), + ("강릉 원주 대학교에서 접속한 기록이 있어", ["강릉", "접속"]), + ("서른 평 아파트의 소비 전력은 얼마나 돼", ["소비 전력"]), + ("일 번 이 번 삼 번 순서대로 읽어줘", ["순서대로"]), +] + +SINO = ['영', '일', '이', '삼', '사', '오', '육', '칠', '팔', '구'] + + +def sino_int(n): + if n == 0: + return '영' + out, units = '', ['', '십', '백', '천'] + groups = [] + while n > 0: + groups.append(n % 10000); n //= 10000 + big = ['', '만', '억', '조'] + parts = [] + for gi in range(len(groups) - 1, -1, -1): + g = groups[gi] + if g == 0: + continue + s = '' + for i, ch in enumerate(f"{g:04d}"): + d = int(ch); u = units[3 - i] + if d == 0: + continue + s += (u if (d == 1 and u) else SINO[d] + u) + parts.append((s if not (gi > 0 and g == 1) else '') + big[gi]) + return ''.join(parts) + + +def digits_to_korean(text): + def rep(m): + s = m.group(0).replace(',', '') + if '.' in s: + a, b = s.split('.') + return sino_int(int(a)) + '점' + ''.join(SINO[int(c)] for c in b) + return sino_int(int(s)) + t = re.sub(r'\d[\d,]*(?:\.\d+)?', rep, text) + for sym, word in (('g', '그램'), ('V', '볼트'), ('A', '암페어'), ('℃', '도'), ('°C', '도')): + t = t.replace(sym, word) + return t + + +def norm(text): + return re.sub(r'[\s\.,!?\-~:;\'"()\[\]·…]', '', digits_to_korean(text or '')).lower() + + +def cer(ref, hyp): + r, h = list(norm(ref)), list(norm(hyp)) + if not r: + return 0.0 + dp = list(range(len(h) + 1)) + for i in range(1, len(r) + 1): + prev, dp[0] = dp[0], i + for j in range(1, len(h) + 1): + cur = dp[j] + dp[j] = min(dp[j] + 1, dp[j - 1] + 1, prev + (r[i - 1] != h[j - 1])) + prev = cur + return dp[len(h)] / len(r) + + +def login(): + pw = os.environ.get("HC_PASSWORD") + if not pw: + txt = open("/home/kim/.claude/projects/-srv-homeclaw/memory/project_papa_credentials.md", encoding="utf-8").read() + pw = re.search(r"password\s*=\s*(\S+)", txt).group(1).strip("`'\"*,;") + req = urllib.request.Request(BASE + "/api/auth/login", json.dumps({"username": "papa", "password": pw}).encode(), + {"Content-Type": "application/json"}) + return json.loads(urllib.request.urlopen(req, timeout=20).read())["token"] + + +def synth(token, text, path): + if os.path.exists(path): + return + req = urllib.request.Request(BASE + "/api/voice/tts", json.dumps({"text": text}).encode(), + {"Content-Type": "application/json", "Authorization": "Bearer " + token}) + data = urllib.request.urlopen(req, timeout=120).read() + open(path, "wb").write(data) + + +def read_wav(path): + with wave.open(path, "rb") as w: + sr, ch, sw = w.getframerate(), w.getnchannels(), w.getsampwidth() + raw = w.readframes(w.getnframes()) + a = np.frombuffer(raw, dtype=np.int16 if sw == 2 else np.int32).astype(np.float32) + a = a.reshape(-1, ch).mean(axis=1) / (32768.0 if sw == 2 else 2147483648.0) + return a, sr + + +def write_wav16k(path, a, sr): + if sr != 16000: # 선형보간 리샘플(시험용으로 충분) + n = int(len(a) * 16000 / sr) + a = np.interp(np.linspace(0, len(a) - 1, n), np.arange(len(a)), a) + pcm = (np.clip(a, -1, 1) * 32767).astype(np.int16) + with wave.open(path, "wb") as w: + w.setnchannels(1); w.setsampwidth(2); w.setframerate(16000); w.writeframes(pcm.tobytes()) + + +def variants(a, seed): + rng = np.random.default_rng(seed) + rms = float(np.sqrt(np.mean(a ** 2))) + 1e-9 + out = {"clean": a} + noise = rng.standard_normal(len(a)).astype(np.float32) + out["noise10dB"] = a + noise * (rms / (10 ** (10 / 20))) # SNR 10dB 백색잡음 + out["quiet+noise"] = a * 0.25 + noise * (rms * 0.25 / (10 ** (15 / 20))) # 멀리서 작게 + SNR 15dB + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--models", default="medium,large-v3-turbo") + ap.add_argument("--device-index", type=int, default=1) + ap.add_argument("--beam", type=int, default=5) + ap.add_argument("--out", default="") + a = ap.parse_args() + os.makedirs(OUTDIR, exist_ok=True) + + token = login() + items = [] + for i, (text, terms) in enumerate(SENTENCES): + wav = os.path.join(OUTDIR, f"s{i:02d}.wav") + synth(token, text, wav) + sig, sr = read_wav(wav) + for vname, v in variants(sig, i).items(): + p = os.path.join(OUTDIR, f"s{i:02d}_{vname}.wav") + write_wav16k(p, v, sr) + items.append({"i": i, "text": text, "terms": terms, "cond": vname, "path": p}) + print(f"{len(items)} clips ({len(SENTENCES)} sentences x 3 conditions)", flush=True) + + from faster_whisper import WhisperModel + results = {} + for mname in [m for m in a.models.split(",") if m]: + t0 = time.time() + model = WhisperModel(mname, device="cuda", device_index=a.device_index, compute_type="float16") + load_s = time.time() - t0 + rows, secs = [], 0.0 + # 첫 호출은 워밍업이라 시간 측정에서 뺀다 + list(model.transcribe(items[0]["path"], language="ko", beam_size=a.beam, vad_filter=True)[0]) + for it in items: + t1 = time.time() + segs, _ = model.transcribe(it["path"], language="ko", beam_size=a.beam, vad_filter=True, + condition_on_previous_text=False, hallucination_silence_threshold=2.0) + hyp = "".join(s.text for s in segs if s.no_speech_prob < 0.6).strip() + dt = time.time() - t1; secs += dt + hits = sum(1 for t in it["terms"] if re.sub(r'\s', '', t) in re.sub(r'\s', '', digits_to_korean(hyp))) + rows.append({**{k: it[k] for k in ("i", "cond", "text")}, "hyp": hyp, "cer": cer(it["text"], hyp), + "terms_hit": hits, "terms_total": len(it["terms"]), "sec": dt}) + results[mname] = {"load_s": round(load_s, 1), "rows": rows, "avg_sec": secs / len(items)} + print(f"[{mname}] loaded {load_s:.1f}s, avg {secs / len(items):.2f}s/clip", flush=True) + del model + import gc; gc.collect() + + print("\n=== 요약 (CER 낮을수록 좋음 / 용어 적중 높을수록 좋음) ===") + print(f"{'모델':<18}{'조건':<13}{'CER':>7}{'용어적중':>10}{'평균초':>8}") + for mname, r in results.items(): + for cond in ("clean", "noise10dB", "quiet+noise", "ALL"): + rs = [x for x in r["rows"] if cond == "ALL" or x["cond"] == cond] + c = sum(x["cer"] for x in rs) / len(rs) + th = sum(x["terms_hit"] for x in rs); tt = sum(x["terms_total"] for x in rs) + s = sum(x["sec"] for x in rs) / len(rs) + print(f"{mname:<18}{cond:<13}{c * 100:>6.1f}%{th:>5}/{tt:<4}{s:>8.2f}") + if a.out: + json.dump(results, open(a.out, "w"), ensure_ascii=False, indent=1) + + +if __name__ == "__main__": + main()