tiny-dictation-en / runtime /word_ngram.py
Hansda's picture
Release Tiny Dictation English and complete benchmarks
531b9c5 verified
Raw History Blame Contribute Delete
1.83 kB
'Compress and score a word trigram model within an offline ASR package.'
import math
import struct
import zlib
import numpy as np
SCALE = 12
ENTRY = np.dtype([("delta", "<u4"), ("score", "i1"), ("backoff", "i1")])
START = "<s>"
END = "</s>"
UNKNOWN = -6.5
def key(words):
return zlib.crc32("\x1f".join(words).encode())
class WordLanguage:
def __init__(self, data):
magic, *sizes = struct.unpack_from("<4s3I", data)
if magic != b"WLM1" or len(data) != 16 + sum(sizes) * ENTRY.itemsize:
raise ValueError("Invalid compact trigram payload")
tables = []
offset = 16
for size in sizes:
rows = np.frombuffer(data, dtype=ENTRY, count=size, offset=offset)
keys = rows["delta"].cumsum(dtype=np.uint32).tolist()
tables.append(dict(zip(keys, zip(rows["score"].tolist(), rows["backoff"].tolist()))))
offset += size * ENTRY.itemsize
self.unigrams, self.bigrams, self.trigrams = tables
def score(self, words):
score = 0
first, second = None, START
for word in (*words, END):
trigram = self.trigrams.get(key((first, second, word))) if first is not None else None
if trigram is not None:
score += trigram[0]
else:
if first is not None:
score += self.bigrams.get(key((first, second)), (0, 0))[1]
bigram = self.bigrams.get(key((second, word)))
if bigram is not None:
score += bigram[0]
else:
score += self.unigrams.get(key((second,)), (0, 0))[1]
score += self.unigrams.get(key((word,)), (UNKNOWN * SCALE, 0))[0]
first, second = second, word
return score * (math.log(10) / SCALE)