Spaces:
Configuration error
Configuration error
Download axis_numeric/ctc_topk.py from serety95/axis-numeric: direct link, hf CLI and curl.
- Browser
- Download file 1.36 kB
-
https://huggingface.co/spaces/serety95/axis-numeric/resolve/main/axis_numeric/ctc_topk.py
- Command line
-
hf download hf://spaces/serety95/axis-numeric/axis_numeric/ctc_topk.py
-
curl -L -o ctc_topk.py https://huggingface.co/spaces/serety95/axis-numeric/resolve/main/axis_numeric/ctc_topk.py
1.36 kB
| """Top-k CTC frames from a logit matrix. Full softmax stays in numpy.""" | |
| from __future__ import annotations | |
| import numpy as np | |
| from .ctc_frames import CtcFrame, select_candidates | |
| def frames_from_logits(logits: np.ndarray, vocabulary: str, top_k: int = 5) -> list[CtcFrame]: | |
| blank = len(vocabulary) | |
| shifted = logits - logits.max(axis=1, keepdims=True) | |
| exp = np.exp(shifted) | |
| probs = exp / exp.sum(axis=1, keepdims=True) | |
| width = probs.shape[1] | |
| take = min(width, top_k + 2) | |
| frames: list[CtcFrame] = [] | |
| for row in probs: | |
| ranked = _ranked(row, take) | |
| selected = select_candidates(ranked, top_k, blank) | |
| margin = _margin(row) | |
| alternatives = tuple((vocabulary[index], prob) for index, prob in selected if index != blank) | |
| frames.append(CtcFrame(tuple(selected), alternatives, margin)) | |
| return frames | |
| def _ranked(row: np.ndarray, take: int) -> list[tuple[int, float]]: | |
| if row.shape[0] == 1: | |
| return [(0, float(row[0]))] | |
| part = np.argpartition(row, -take)[-take:] | |
| return sorted(((int(index), float(row[index])) for index in part), key=lambda item: (-item[1], item[0])) | |
| def _margin(row: np.ndarray) -> float: | |
| if row.shape[0] <= 1: | |
| return 1.0 | |
| top2 = np.partition(row, -2)[-2:] | |
| return float(top2.max() - top2.min()) | |