"""Shared decoding: greedy CTC, CTC prefix beam search with a character n-gram language model, and the language model class itself.""" import math from collections import defaultdict import numpy as np class CharLM: """Witten-Bell interpolated character n-gram model. Probabilities are cached per (context, char).""" def __init__(s, lines, order): s.o = order; s.c = defaultdict(int); s.t = defaultdict(int); s.u = defaultdict(int); V = set() for l in lines: l = "\x02" * (order - 1) + l + "\x03"; V.update(l) for i in range(order - 1, len(l)): for k in range(order): h = l[i - k:i]; g = h + l[i] if g not in s.c: s.u[h] += 1 s.c[g] += 1; s.t[h] += 1 s.V = len(V); s.cache = {} def p(s, h, ch): h = h[-(s.o - 1):] if s.o > 1 else ""; key = (h, ch) if key in s.cache: return s.cache[key] pr = 1.0 / s.V for k in range(0, len(h) + 1): hh = h[len(h) - k:]; t = s.t.get(hh, 0) if t == 0: break uu = s.u[hh]; pr = (s.c.get(hh + ch, 0) + uu * pr) / (t + uu) lp = math.log(pr) if len(s.cache) > 2_000_000: s.cache.clear() s.cache[key] = lp; return lp def load_lm(path): """Language models were pickled from a script, so the class is looked up on __main__.""" if str(path).endswith(".npz"): # compact release format (compact_lm.py) from compact_lm import CompactLM; return CompactLM(path) import pickle, __main__ __main__.CharLM = CharLM; lm = pickle.load(open(path, "rb")); lm.cache = {}; return lm def greedy(lp, chars): """lp: [T, classes] log-probabilities. Returns (text, confidence = mean peak probability of emitted characters).""" ids = lp.argmax(1); pm = np.exp(lp.max(1)); keep = (ids != 0) & np.concatenate([[True], ids[1:] != ids[:-1]]) return "".join(chars[i - 1] for i in ids[keep]), float(pm[keep].mean()) if keep.any() else 0.0 def _lse(a, b): if a == -math.inf: return b if b == -math.inf: return a m = max(a, b); return m + math.log1p(math.exp(-abs(a - b))) def beam(lp, chars, lm, alpha, beta, B=8, prune=-7.0): """CTC prefix beam search; LM log-probability (times alpha) is added per appended character, beta rewards length.""" beams = {"": (0.0, -math.inf, 0.0)} for t in range(lp.shape[0]): row = lp[t]; cand = np.nonzero(row > prune)[0] if row[0] > -0.05 and len(cand) == 1: beams = {k: (_lse(pb, pnb) + row[0], -math.inf, ls) for k, (pb, pnb, ls) in beams.items()}; continue nb = defaultdict(lambda: [-math.inf, -math.inf, 0.0]) for pre, (pb, pnb, ls) in beams.items(): tot = _lse(pb, pnb) for v in cand.tolist(): p = float(row[v]) if v == 0: e = nb[pre]; e[0] = _lse(e[0], tot + p); e[2] = ls; continue ch = chars[v - 1]; last = pre[-1] if pre else None if ch == last: e = nb[pre]; e[1] = _lse(e[1], pnb + p); e[2] = ls ext = pre + ch; e2 = nb[ext]; e2[1] = _lse(e2[1], pb + p); e2[2] = ls + alpha * lm.p(pre, ch) else: ext = pre + ch; e2 = nb[ext]; e2[1] = _lse(e2[1], tot + p); e2[2] = ls + alpha * lm.p(pre, ch) beams = dict(sorted(((k, tuple(v)) for k, v in nb.items()), key=lambda kv: -(_lse(kv[1][0], kv[1][1]) + kv[1][2] + beta * len(kv[0])))[:B]) return max(beams.items(), key=lambda kv: _lse(kv[1][0], kv[1][1]) + kv[1][2] + alpha * lm.p(kv[0], "\x03") + beta * len(kv[0]))[0]