Notesoop-STT-Ko-v2 / transcribe.py
yclee12345's picture
fix: remove legacy checkpoint fallbacks, strictly enforce NoteSoop_stt_v2_best.pt
2f6061f verified
Raw History Blame Contribute Delete
22.6 kB
#!/usr/bin/env python3
"""
transcribe.py
Notesoop-STT-Ko-v2: Standalone Portable Korean STT Inference Engine
===================================================================
- Google EmbeddingGemma-2 Frozen 300M Audio Tower (MRL 256-dim acoustic feature extraction)
- 10-Layer Conformer Reader (34.3M params; 34.8M total w/ CTC Head) on NVIDIA CUDA / Apple Silicon MPS / Multi-core CPU
- 2,048 BPE SentencePiece Vocabulary with Cosine Similarity Matching
- Ultra-Fast Native C++ Rolling-Hash CTC Beam Search (< 1ms per utterance)
- Asynchronous KenLM 5-Gram Language Model Rescoring (80.2MB Trie)
- Multi-OS Native Acceleration (Linux .so, macOS .dylib, Windows .dll)
"""
from __future__ import annotations
import argparse
import difflib
import gc
import os
import re
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor, Future
from pathlib import Path
from typing import Optional, List, Tuple, Callable
# Add local src to import path
_ROOT = Path(__file__).resolve().parent
_SRC = _ROOT / "src"
if str(_SRC) not in sys.path:
sys.path.insert(0, str(_SRC))
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
import numpy as np
import torch
import torch.nn.functional as F
try:
import sentencepiece as spm
except ImportError:
spm = None
from model import EmbeddingGemmaCTCReader
from step2_extract_features import GenuineAudioFeatureExtractor
from dataset import normalize_text
def auto_detect_device() -> str:
"""
Intelligently selects the best compute device:
1. NVIDIA CUDA GPU (Highest throughput & Tensor Cores)
2. Apple Silicon MPS (Metal Performance Shaders)
3. Multi-core CPU fallback
"""
if torch.cuda.is_available():
return "cuda"
if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
return "mps"
return "cpu"
def sync_device(device: torch.device) -> None:
"""Synchronizes device queues for precise latency benchmarking."""
if device.type == "cuda":
torch.cuda.synchronize()
elif device.type == "mps" and hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
torch.mps.synchronize()
def empty_device_cache(device: torch.device) -> None:
"""Safely frees cached device VRAM across backends."""
if device.type == "cuda":
torch.cuda.empty_cache()
elif device.type == "mps" and hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
torch.mps.empty_cache()
class SentencePieceCTCTokenizer:
"""SentencePiece BPE Tokenizer for Notesoop-STT-Ko-v2 (2,048 vocab)."""
def __init__(self, model_path: Optional[str] = None, model_bytes: Optional[bytes] = None):
if spm is None:
raise ImportError("sentencepiece package is required. Run 'pip install sentencepiece'.")
self.sp = spm.SentencePieceProcessor()
if model_bytes is not None:
self.sp.load_from_serialized_proto(model_bytes)
elif model_path is not None:
self.sp.load(str(model_path))
else:
raise ValueError("Either model_path or model_bytes must be provided")
self.blank_id = 0
self.blank_token = "<blank>"
self.unk_id = 1
self.unk_token = "<unk>"
self.vocab_size = self.sp.get_piece_size()
def encode(self, text: str) -> List[int]:
clean = normalize_text(text)
return self.sp.encode_as_ids(clean) if clean else []
def decode(self, token_ids: List[int], remove_blank: bool = True, collapse_repeats: bool = True) -> str:
if collapse_repeats:
collapsed = []
prev = None
for tid in token_ids:
if tid != prev:
collapsed.append(tid)
prev = tid
token_ids = collapsed
filtered = [tid for tid in token_ids if not (remove_blank and tid == self.blank_id) and tid != self.unk_id]
if not filtered:
return ""
return self.sp.decode_ids(filtered).strip()
def id_to_piece(self, tid: int) -> str:
return self.sp.id_to_piece(tid)
def load_audio(
file_path: str,
target_sr: int = 16000,
start_sec: float = 0.0,
duration_limit: float = 0.0
) -> Tuple[torch.Tensor, float]:
"""
Loads any audio container (.wav, .m4a, .mp3, .flac) into 16kHz float32 mono tensor.
Leverages FFmpeg streaming decode with native subsecond seeking.
"""
p = Path(file_path)
if not p.exists():
raise FileNotFoundError(f"Audio file not found: {file_path}")
cmd = ["ffmpeg", "-nostdin", "-threads", "0"]
if start_sec > 0:
cmd.extend(["-ss", str(start_sec)])
if duration_limit > 0:
cmd.extend(["-t", str(duration_limit)])
cmd.extend([
"-i", str(p),
"-f", "f32le", "-ac", "1", "-ar", str(target_sr), "-"
])
try:
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
out, _ = proc.communicate()
if proc.returncode != 0 or len(out) == 0:
raise RuntimeError("FFmpeg decode returned empty data")
arr = np.frombuffer(out, dtype=np.float32).copy()
except Exception:
# Fallback to soundfile / torchaudio
import soundfile as sf
arr, sr = sf.read(str(p), dtype="float32")
if arr.ndim > 1:
arr = arr.mean(axis=1)
if start_sec > 0:
arr = arr[int(start_sec * sr):]
if duration_limit > 0:
arr = arr[:int(duration_limit * sr)]
if sr != target_sr:
import math
gcd = math.gcd(sr, target_sr)
up = target_sr // gcd
down = sr // gcd
import scipy.signal as sps
arr = sps.resample_poly(arr, up, down).astype(np.float32)
wav = torch.from_numpy(arr).unsqueeze(0)
duration_sec = wav.size(-1) / float(target_sr)
return wav, duration_sec
def merge_chunk_transcripts(transcripts: List[str]) -> str:
"""
Intelligently merges transcripts from overlapping sliding audio windows:
- Multi-word exact match (k=8 down to 1)
- Fuzzy character-level longest common substring matching (difflib)
- Consecutive repeated phrase / word stuttering filter
"""
if not transcripts:
return ""
if len(transcripts) == 1:
return transcripts[0].strip()
merged = transcripts[0].strip()
for next_text in transcripts[1:]:
next_text = next_text.strip()
if not next_text:
continue
if not merged:
merged = next_text
continue
mw = merged.split()
nw = next_text.split()
max_k = min(8, len(mw), len(nw))
best_k = 0
for k in range(max_k, 0, -1):
if mw[-k:] == nw[:k]:
best_k = k
break
if best_k > 0:
merged = " ".join(mw + nw[best_k:])
continue
# 2. Fuzzy Substring / Suffix-Prefix Overlap (Character-level)
tail = merged[-60:]
head = next_text[:60]
matcher = difflib.SequenceMatcher(None, tail, head)
match = matcher.find_longest_match(0, len(tail), 0, len(head))
tail_dist_from_end = len(tail) - (match.a + match.size)
head_dist_from_start = match.b
if match.size >= 3 and tail_dist_from_end <= 10 and head_dist_from_start <= 10:
cut_idx = len(merged) - len(tail) + match.a + match.size
rem_head = next_text[match.b + match.size:].lstrip()
merged = merged[:cut_idx] + " " + rem_head
merged = re.sub(r"\s+", " ", merged).strip()
continue
# 3. Last word / first word partial match fallback
last_word = mw[-1]
first_word = nw[0]
if last_word == first_word:
merged = " ".join(mw + nw[1:])
elif len(last_word) >= 2 and first_word.startswith(last_word):
mw[-1] = first_word
merged = " ".join(mw + nw[1:])
elif len(first_word) >= 2 and last_word.endswith(first_word):
merged = " ".join(mw + nw[1:])
elif len(first_word) >= 2 and first_word in last_word:
merged = " ".join(mw + nw[1:])
elif len(last_word) >= 2 and last_word in first_word:
mw[-1] = first_word
merged = " ".join(mw + nw[1:])
else:
merged = " ".join(mw + nw)
# 4. Immediate phrase repetition deduplication (stuttering filter)
words = merged.split()
cleaned: List[str] = []
i = 0
while i < len(words):
if i + 3 < len(words) and words[i:i+2] == words[i+2:i+4]:
cleaned.extend(words[i:i+2])
i += 4
continue
if i + 1 < len(words) and words[i] == words[i+1]:
cleaned.append(words[i])
i += 2
continue
cleaned.append(words[i])
i += 1
return re.sub(r"\s+", " ", " ".join(cleaned)).strip()
class EmbeddingGemmaSTTV2:
"""
High-Performance, Standalone Korean STT Engine for Notesoop-STT-Ko-v2.
Fully accelerated on NVIDIA CUDA, Apple Silicon MPS, and Multi-core CPU.
"""
def __init__(
self,
checkpoint_path: Optional[str] = None,
lm_path: Optional[str] = None,
device: str = "auto",
use_kenlm: bool = True,
alpha: float = 0.18,
beta: float = 0.35,
beam_size: int = 16,
):
self.root = _ROOT
self.dev_str = auto_detect_device() if device == "auto" else device
self.device = torch.device(self.dev_str)
self.use_kenlm = use_kenlm
self.alpha = alpha
self.beta = beta
self.beam_size = beam_size
# 1. Resolve Checkpoint
if checkpoint_path:
ckpt_p = Path(checkpoint_path)
if not ckpt_p.is_absolute():
ckpt_p = self.root / ckpt_p
else:
ckpt_p = self.root / "checkpoints/NoteSoop_stt_v2_best.pt"
if not ckpt_p.exists():
raise FileNotFoundError(f"Checkpoint not found: {ckpt_p}")
print(f"📦 [Notesoop V2 Engine] Initializing on {self.device.type.upper()} ({self.dev_str})...")
ckpt = torch.load(ckpt_p, map_location="cpu", weights_only=False)
state_dict = ckpt.get("model_state_dict", ckpt)
# 2. Tokenizer (2,048 BPE)
if "tokenizer_bpe_bytes" in ckpt:
self.tokenizer = SentencePieceCTCTokenizer(model_bytes=ckpt["tokenizer_bpe_bytes"])
elif "tokenizer_model" in ckpt:
self.tokenizer = SentencePieceCTCTokenizer(model_bytes=ckpt["tokenizer_model"])
else:
sp_p = self.root / "tokenizer/ko_bpe_2048.model"
if not sp_p.exists():
raise FileNotFoundError(f"Tokenizer model not found at {sp_p}")
self.tokenizer = SentencePieceCTCTokenizer(model_path=str(sp_p))
# 3. Conformer Reader Model
vb_model = state_dict.get("ctc_head.vector_bank")
if vb_model is None:
raise ValueError("Checkpoint is missing vector_bank in ctc_head!")
d_model = state_dict["reader.input_proj.weight"].shape[0] if "reader.input_proj.weight" in state_dict else 384
input_dim = state_dict["reader.input_proj.weight"].shape[1] if "reader.input_proj.weight" in state_dict else 256
detected_layers = len([k for k in state_dict.keys() if k.startswith("reader.layers.") and k.endswith(".final_norm.weight")])
num_layers = detected_layers if detected_layers > 0 else 10
dim_feedforward = state_dict["reader.layers.0.ffn1.0.weight"].shape[0] if "reader.layers.0.ffn1.0.weight" in state_dict else 1536
nhead = d_model // 64
output_dim = vb_model.shape[1] if hasattr(vb_model, "shape") else 256
self.reader = EmbeddingGemmaCTCReader(
input_dim=input_dim,
output_dim=output_dim,
d_model=d_model,
nhead=nhead,
num_layers=num_layers,
dim_feedforward=dim_feedforward,
dropout=0.0,
init_temperature=0.05,
vector_bank=vb_model,
use_spec_augment=False,
trainable_vector_bank=False
).to(self.device)
self.reader.load_state_dict(state_dict, strict=False)
self.reader.eval()
# Apply device-optimal fastpath (bfloat16 precision for CUDA & MPS)
if hasattr(self.reader, "enable_fastpath"):
self.reader.enable_fastpath(self.device)
elif self.device.type == "mps" and hasattr(self.reader, "enable_mps_bfloat16_fastpath"):
self.reader.enable_mps_bfloat16_fastpath()
elif self.device.type == "cuda":
self.reader = self.reader.to(dtype=torch.bfloat16)
# 4. Audio Feature Extractor (Google EmbeddingGemma-2 300M Audio Tower)
print(f"🎵 [Audio Tower] Loading Google EmbeddingGemma-2 on {self.device} (bfloat16)...")
self.extractor = GenuineAudioFeatureExtractor(device=self.device, model_name="google/embeddinggemma-2")
# 5. Native C++ KenLM Beam Search Decoder
self.decoder_kenlm = None
if self.use_kenlm:
from decoder import KenLMBeamSearchDecoder
resolved_lm = lm_path or str(self.root / "lm/ko_bpe_2048_lm.bin")
try:
self.decoder_kenlm = KenLMBeamSearchDecoder(
tokenizer=self.tokenizer,
lm_path=resolved_lm,
beam_size=self.beam_size,
alpha=self.alpha,
beta=self.beta
)
except Exception as e:
print(f"⚠️ [KenLM Warning] Could not load KenLM: {e}. Falling back to greedy decoding.")
@torch.no_grad()
def transcribe(
self,
audio_path: str,
chunk_sec: float = 15.0,
overlap_sec: float = 1.0,
start_sec: float = 0.0,
duration_limit: float = 0.0,
batch_size: int = 4,
on_chunk: Optional[Callable[[str, float, float], None]] = None
) -> Tuple[str, float]:
"""
Transcribes audio of arbitrary length into accurate Korean text.
Features Batched GPU Forward Passes + Asynchronous KenLM C++ Rescoring:
- CPU Mel-spectrogram Preprocessing
- GPU Batched 300M Audio Tower Forward (CUDA / MPS)
- GPU Batched 10-Layer Conformer Forward (bfloat16)
- Asynchronous C++ CTC Rolling-Hash Beam Search & KenLM 5-Gram Rescoring
"""
wav, eval_dur = load_audio(
audio_path,
target_sr=16000,
start_sec=start_sec,
duration_limit=duration_limit
)
sr = 16000
step_sec = max(chunk_sec - overlap_sec, 0.5) if overlap_sec > 0 else chunk_sec
step_samples = int(step_sec * sr)
chunk_samples = int(chunk_sec * sr)
total_samples = wav.size(-1)
chunk_ranges: List[Tuple[int, int]] = []
c_start = 0
while c_start < total_samples:
c_end = min(c_start + chunk_samples, total_samples)
if (c_end - c_start) / sr >= 0.5:
chunk_ranges.append((c_start, c_end))
if c_end == total_samples:
break
c_start += step_samples
if not chunk_ranges:
return "", 0.0
sync_device(self.device)
t0 = time.time()
# 1. Preprocess Mel-spectrogram on CPU
preprocessed_chunks = []
for cs, ce in chunk_ranges:
c_wav = wav[:, cs:ce]
if c_wav.size(-1) < chunk_samples:
c_wav = F.pad(c_wav, (0, chunk_samples - c_wav.size(-1)))
preprocessed_chunks.append((self.extractor.preprocess_audio_cpu(c_wav), cs, ce))
chunk_texts: List[str] = []
kenlm_futures: List[Tuple[Future, float, float]] = []
use_kenlm_async = (self.decoder_kenlm is not None)
# 2. Pipelined Batched GPU Inference with Asynchronous CPU Decoding
with ThreadPoolExecutor(max_workers=max(2, os.cpu_count() or 2)) as executor:
for b_idx in range(0, len(preprocessed_chunks), batch_size):
b_slice = preprocessed_chunks[b_idx : b_idx + batch_size]
b_items = [item[0] for item in b_slice]
# Step A: GPU Audio Tower Features
if len(b_items) > 1 and len(set(it[3] for it in b_items)) == 1:
feats = self.extractor.extract_batch_same_bucket(b_items)
else:
feats = [self.extractor.extract_from_preprocessed(*it) for it in b_items]
# Step B: Conformer Reader Forward
model_dtype = self.reader.reader.input_proj.weight.dtype
if len(feats) > 1 and len(set(f.size(0) for f in feats)) == 1:
feats_batch = torch.stack(feats, dim=0).to(device=self.device, dtype=model_dtype)
logits_batch = self.reader(feats_batch)
else:
logits_batch = [
self.reader(f.unsqueeze(0).to(device=self.device, dtype=model_dtype)).squeeze(0)
for f in feats
]
# Step C: Dispatch Decoding (KenLM C++ Async or Argmax Greedy)
for b in range(len(feats)):
logits = logits_batch[b]
cs, ce = b_slice[b][1], b_slice[b][2]
if use_kenlm_async:
lprobs = F.log_softmax(logits.float(), dim=-1)
topk_lprobs, topk_ids = torch.topk(lprobs, k=32, dim=-1)
blank_lprobs = lprobs[:, 0]
fut = executor.submit(
self.decoder_kenlm.decode_topk,
topk_ids.detach().cpu().to(torch.int32).numpy(),
topk_lprobs.detach().cpu().float().numpy(),
blank_lprobs.detach().cpu().float().numpy(),
beam_size=self.beam_size,
alpha=self.alpha,
beta=self.beta
)
kenlm_futures.append((fut, cs / sr, ce / sr))
else:
pred_ids = torch.argmax(logits, dim=-1).cpu().tolist()
txt = self.tokenizer.decode(pred_ids, remove_blank=True, collapse_repeats=True)
chunk_texts.append(txt)
if on_chunk:
on_chunk(txt, cs / sr, ce / sr)
if use_kenlm_async:
for fut, cs_sec, ce_sec in kenlm_futures:
txt = fut.result()
chunk_texts.append(txt)
if on_chunk:
on_chunk(txt, cs_sec, ce_sec)
sync_device(self.device)
t_elapsed = time.time() - t0
rtf = t_elapsed / max(eval_dur, 0.001)
valid_texts = [t.strip() for t in chunk_texts if t.strip()]
if overlap_sec > 0:
full_text = merge_chunk_transcripts(valid_texts)
else:
full_text = " ".join(valid_texts)
return full_text, rtf
def main():
parser = argparse.ArgumentParser(description="Notesoop-STT-Ko-v2 Standalone Portable Inference CLI")
parser.add_argument("--audio", type=str, default="sample_audio.wav", help="Path to audio file (.wav, .mp3, .m4a, etc.)")
parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint (.pt)")
parser.add_argument("--device", type=str, default="auto", choices=["auto", "cuda", "mps", "cpu"], help="Inference compute device")
parser.add_argument("--batch_size", type=int, default=4, help="GPU batch size for audio chunks (default: 4; set 8~16 on CUDA)")
parser.add_argument("--kenlm", action="store_true", default=True, help="Enable KenLM 5-gram language model rescoring")
parser.add_argument("--no_kenlm", dest="kenlm", action="store_false", help="Disable KenLM (Greedy decoding)")
parser.add_argument("--lm", type=str, default=None, help="Path to KenLM binary model")
parser.add_argument("--alpha", type=float, default=0.18, help="KenLM language model weight (default: 0.18)")
parser.add_argument("--beta", type=float, default=0.35, help="Token insertion bonus weight (default: 0.35)")
parser.add_argument("--beam_size", type=int, default=16, help="CTC Beam search size (default: 16)")
parser.add_argument("--chunk_sec", type=float, default=15.0, help="Chunk size in seconds (default: 15.0)")
parser.add_argument("--overlap_sec", type=float, default=1.0, help="Overlap between chunks in seconds (default: 1.0)")
parser.add_argument("--duration", type=float, default=0.0, help="Duration limit in seconds (0 for full audio)")
parser.add_argument("--output", type=str, default=None, help="Optional text file to save transcript")
args = parser.parse_args()
engine = EmbeddingGemmaSTTV2(
checkpoint_path=args.checkpoint,
lm_path=args.lm,
device=args.device,
use_kenlm=args.kenlm,
alpha=args.alpha,
beta=args.beta,
beam_size=args.beam_size,
)
print("\n" + "=" * 75)
print("🚀 [Notesoop-STT-Ko-v2] Starting Audio Transcription...")
print(f" • Audio File : {args.audio}")
print(f" • Device : {engine.device.type.upper()}")
print(f" • Batch Size : {args.batch_size}")
print(f" • KenLM Mode : {'Enabled (Native C++ Rolling-Hash)' if args.kenlm and engine.decoder_kenlm else 'Greedy'}")
print("=" * 75 + "\n")
def _chunk_callback(txt: str, start: float, end: float):
if txt.strip():
print(f" [{int(start):02d}s ~ {int(end):02d}s] {txt}")
text, rtf = engine.transcribe(
audio_path=args.audio,
chunk_sec=args.chunk_sec,
overlap_sec=args.overlap_sec,
duration_limit=args.duration,
batch_size=args.batch_size,
on_chunk=_chunk_callback
)
print("\n" + "=" * 75)
print("📝 [최종 전사 결과]:")
print(text)
print("-" * 75)
speedup = 1.0 / max(rtf, 1e-5)
print(f"⚡ 체감 속도 : {speedup:.1f}x Real-time (RTF: {rtf:.4f})")
print("=" * 75)
if args.output:
out_p = Path(args.output)
out_p.parent.mkdir(parents=True, exist_ok=True)
out_p.write_text(text, encoding="utf-8")
print(f"💾 Transcript saved to: {out_p.resolve()}")
if __name__ == "__main__":
main()