mattrguerra/transcription-pipelinemainPrivate on GitHub, published here in full

align.py

Language Python1.2 KB34 lines

transcription_pipeline/align.py

  1. """Word timestamps: WhisperX's wav2vec2 forced alignment.
  2. Runs on either engine's segments. Neither Whisper model returns reliable word
  3. timing on its own (DeepInfra returns none), and speaker assignment needs it.
  4. When no alignment model exists for the language, the result passes through
  5. untouched and shape.py interpolates sentence times across each segment.
  6. """
  7. from __future__ import annotations
  8. from functools import lru_cache
  9. from pathlib import Path
  10. from .audio import load_wav16k
  11. @lru_cache(maxsize=4)
  12. def _align_model(language: str, device: str):
  13. import whisperx
  14. return whisperx.load_align_model(language_code=language, device=device)
  15. def align(result: dict, wav: Path, device: str = "cpu", log=print) -> dict:
  16. import whisperx
  17. language = result.get("language") or "en"
  18. try:
  19. model, metadata = _align_model(language, device)
  20. except ValueError as e: # no default alignment model for this language
  21. log(f" align: skipped ({e}); timestamps will be interpolated.")
  22. return result
  23. audio = load_wav16k(wav)
  24. aligned = whisperx.align(result["segments"], model, metadata, audio, device,
  25. return_char_alignments=False)
  26. return {**result, "segments": aligned["segments"], "aligned": True}