axis-numeric / axis_numeric /ctc_beam.py
serety95's picture
Update numeric space
f1ba785 verified
Raw History Blame Contribute Delete
1.05 kB
"""CTC prefix beam search with per-timestep character alternatives."""
from .ctc_frames import BeamDecodeResult, CtcFrame, search_ctc_frames, select_candidates
__all__ = ["BeamDecodeResult", "ctc_beam_decode"]
def ctc_beam_decode(
probabilities: list[list[float]],
vocabulary: str,
*,
beam_width: int = 4,
top_k: int = 5,
) -> list[BeamDecodeResult]:
frames = [_frame_from_row(row, vocabulary, top_k) for row in probabilities]
return search_ctc_frames(frames, vocabulary, beam_width)
def _frame_from_row(row: list[float], vocabulary: str, top_k: int) -> CtcFrame:
blank = len(vocabulary)
ranked = sorted(enumerate(row), key=lambda item: item[1], reverse=True)
selected = select_candidates(ranked, top_k, blank)
ordered = sorted(row, reverse=True)
margin = ordered[0] - ordered[1] if len(ordered) > 1 else 1.0
alternatives = tuple((vocabulary[index], float(prob)) for index, prob in selected if index != blank)
return CtcFrame(tuple(selected), alternatives, margin)