Spaces:
Configuration error

File size: 1,361 Bytes
f1ba785
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"""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())