Download runtime/ctc_fusion.py from Hansda/tiny-dictation-en: direct link, hf CLI and curl.
- Browser
- Download file 2.31 kB
-
https://huggingface.co/Hansda/tiny-dictation-en/resolve/main/runtime/ctc_fusion.py
- Command line
-
hf download hf://Hansda/tiny-dictation-en/runtime/ctc_fusion.py
-
curl -L -o ctc_fusion.py https://huggingface.co/Hansda/tiny-dictation-en/resolve/main/runtime/ctc_fusion.py
2.31 kB
| 'Cross-score a shared set of transcripts with differently tokenized CTC encoders.' | |
| import numpy as np | |
| from multiview_decode import candidate_paths | |
| from multiview_decode import score_paths | |
| from train import normalize | |
| def cross_scores(model, tokenizer, views, paths, texts, blank, normalize_text=normalize): | |
| alternatives = {} | |
| for path, prediction in paths.items(): | |
| text = normalize_text(prediction) | |
| if text in texts: | |
| alternatives[path] = text | |
| original_count = len(alternatives) | |
| represented = set(alternatives.values()) | |
| for text in texts: | |
| if text in represented: | |
| continue | |
| path = tuple(tokenizer.encode(text)) | |
| if normalize_text(model.render_tokens(path)) == text and path not in alternatives: | |
| alternatives[path] = text | |
| scores = score_paths(model, views, alternatives, blank) | |
| indices = np.array([texts[text] for text in alternatives.values()], dtype=np.int64) | |
| result = np.full(len(texts), -np.inf) | |
| np.maximum.at(result, indices, scores) | |
| native = None | |
| choices = scores[:original_count] | |
| if np.isfinite(choices).any(): | |
| native = indices[choices.argmax()] | |
| return result, native | |
| def candidates(models, views, extra=(), normalize_text=normalize): | |
| native = [candidate_paths(model, sample) for (model, _, _), sample in zip(models, views)] | |
| transcripts = dict.fromkeys(normalize_text(text) for row in native for text in row.values()) | |
| transcripts.update(dict.fromkeys(normalize_text(text) for text in extra)) | |
| texts = {text: index for index, text in enumerate(transcripts)} | |
| results = [cross_scores(model, tokens, audio, paths, texts, blank, normalize_text) | |
| for (model, tokens, blank), audio, paths in zip(models, views, native)] | |
| return list(texts), np.stack([row[0] for row in results]), [row[1] for row in results] | |
| def fusion_indices(scores, weights, native): | |
| defaults = [index if index is not None else 0 for index in native] | |
| best = [row.argmax() if np.isfinite(row).any() else i for row, i in zip(scores, defaults)] | |
| finite = np.flatnonzero(np.isfinite(scores).all(axis=0)) | |
| fused = [finite[(weight @ scores[:, finite]).argmax()] if len(finite) else defaults[0] for weight in weights] | |
| return defaults + best + fused, finite | |