Skip to content

API Reference parrot_loaders.basevideo

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot_loaders.basevideo

View source

Class BaseVideoLoader

Generating Video transcripts from Videos.

Parameter Type Default Description
source Optional[Union[str, Path, List[Union[str, Path]]]] None
tokenizer Callable[..., Any] None
text_splitter Callable[..., Any] None
source_type str 'video'
language str 'en'
video_path Union[str, Path] None
download_video bool True
diarization bool False
**kwargs {}

Attributes:

Attribute Type Description
extensions List[str]
topics list
summarizer Lazy loading property for the summarizer pipeline. Only loads the model when actually needed, saving ~1.6GB VRAM.

Method BaseVideoLoader.build_default_meta

Return canonical metadata for a video/audio source.

A convenience wrapper around :meth:create_metadata that pre-sets doctype="video_transcript" and source_type="video".

Subclasses can call this instead of assembling raw metadata dicts and pass variant-specific extras as **kwargs (they become top-level metadata keys).

build_default_meta(path: Union[str, 'Path'], *, language: Optional[str] = None, title: Optional[str] = None, **kwargs) -> dict

Parameter Type Default Description
path Union[str, 'Path'] URL or filesystem path to the video/audio source.
language Optional[str] None Document language ISO code. Defaults to self.language when None.
title Optional[str] None Human-readable title. Defaults to :meth:_derive_title when None.
**kwargs {} Loader-specific extras (e.g. origin, vtt_path, start_time, end_time).

Returns: dict — A metadata dict with canonical top-level keys and a closed-shape document_meta sub-dict.

Method BaseVideoLoader.transcript_to_vtt

Convert a transcript to VTT format.

transcript_to_vtt(transcript: str, transcript_path: Path) -> str

Parameter Type Default Description
transcript str
transcript_path Path

Returns: str

Method BaseVideoLoader.audio_to_srt

Build an SRT subtitle string from a call recording using WhisperX-aligned words and Pyannote-based diarization (speaker attribution). Optionally writes the result to disk.

This function consumes a WhisperX-style transcript (with word-level timestamps), performs speaker diarization (optionally constrained to a given speaker count), assigns speakers to words, and groups words into readable subtitle segments with length, gap, and duration constraints.

Parameters

audio_path : pathlib.Path Path to the audio file used for diarization (e.g., preconverted mono 16 kHz WAV). Even if asr is provided, this file is required to run the diarization pipeline. asr : dict, optional WhisperX transcript object containing aligned segments and words. Expected schema: { "text": "...", "language": "en", "chunks": [ { "text": "utterance text", "timestamp": (start: float, end: float), "words": [ {"word": "Hello", "start": 0.50, "end": 0.72}, ... ] }, ... ] } If None or missing chunks, a ValueError is raised. speaker_names : list[str] | tuple[str] | None, optional Friendly labels to apply to speakers in first-appearance order after diarization. For example, ["Bot", "Agent", "Customer"]. If not provided, WhisperX/Pyannote speaker IDs (e.g., "SPEAKER_00") are used as-is. If the number of detected speakers exceeds this list, remaining speakers retain their original IDs. output_srt_path : str | pathlib.Path | None, optional If provided, the generated SRT text is written to this path (UTF-8). If omitted, nothing is written to disk. pyannote_token : str | None, optional Hugging Face access token used by Pyannote diarization models. If not provided, the function attempts to read it from the PYANNOTE_AUDIO_AUTH environment variable. Required for diarization. max_gap_s : float, default=0.5 Maximum allowed silence between consecutive words when aggregating them into a single SRT subtitle line. A larger value yields longer lines; a smaller value creates more, shorter lines. max_chars : int, default=90 Soft limit on the number of characters per SRT subtitle line. When adding the next word would exceed this threshold, a new subtitle block is started. max_duration_s : float, default=8.0 Maximum duration (seconds) permitted for a single subtitle block. If adding the next word would exceed this duration, a new block is started. min_speakers : int, default=1 Lower bound on the number of speakers provided to the diarization pipeline. Useful to avoid the "everything merges into one speaker" failure mode. max_speakers : int, default=2 Upper bound on the number of speakers provided to the diarization pipeline. Set both min_speakers and max_speakers to the exact expected number (e.g., 3) to force a fixed speaker count. speaker_corrections : dict | None, optional Mapping to apply manual, deterministic speaker fixes after diarization and before SRT grouping. The expected shape is flexible, but a common pattern is: { # remap entire diarized IDs "SPEAKER_00": "Bot", # or time-bounded corrections (start_s, end_s): "Customer" } When keys are tuples (start, end), any words whose timestamps fall within that interval are reassigned to the specified label/ID. merge_short_segments : bool, default=True If True, very short adjacent subtitle segments (e.g., created by rapid speaker switches or punctuation) may be merged when safe (same speaker, small gap, within max_chars and max_duration_s), improving readability. min_segment_duration : float, default=0.5 Minimum duration (seconds) target when merging very short segments. Only applies if merge_short_segments=True.

Returns

str A UTF-8 string containing the SRT-formatted transcript with speaker labels, where each subtitle block follows the standard: HH:MM:SS,mmm --> HH:MM:SS,mmm : If output_srt_path is provided, the same content is also written to that file.

Raises

ValueError If asr is None or does not contain a chunks list with valid timestamps. RuntimeError If the diarization pipeline cannot be initialized (e.g., missing pyannote_token) or if internal alignment/speaker assignment fails unexpectedly. FileNotFoundError If audio_path does not exist.

Notes

  • Word-level accuracy: Speaker assignment happens per word (not per sentence), allowing accurate handling of interruptions and fast turn-taking.
  • Speaker mapping: If speaker_names is provided, the first diarized speaker to appear in time is mapped to speaker_names[0], the second to [1], etc.
  • Determinism: Pyannote diarization can be non-deterministic across environments. Pinning dependency versions and disabling/controlling TF32 may help reproducibility.
  • Performance: On low-VRAM systems, consider running diarization on CPU while keeping ASR/alignment on GPU. The function itself is agnostic to device placement as long as the underlying pipeline is configured accordingly.

Examples

Basic usage with forced 3 speakers and file output:

srt = self.audio_to_srt( ... audio_path=Path("call_16k_mono.wav"), ... asr=transcript, # from get_whisper_transcript() / WhisperX ... speaker_names=["Bot", "Agent", "Customer"], ... output_srt_path="call.srt", ... pyannote_token=os.environ["PYANNOTE_AUDIO_AUTH"], ... min_speakers=3, max_speakers=3, ... )

Apply manual speaker correction for the first 8 seconds as "Bot":

srt = self.audio_to_srt( ... audio_path=Path("call.wav"), ... asr=transcript, ... pyannote_token=token, ... speaker_corrections={(0.0, 8.0): "Bot"}, ... )

Tighter line grouping (shorter blocks):

srt = self.audio_to_srt( ... audio_path=Path("call.wav"), ... asr=transcript, ... pyannote_token=token, ... max_gap_s=0.35, max_chars=70, max_duration_s=6.0, ... )

audio_to_srt(audio_path: Path, asr=None, speaker_names=None, output_srt_path=None, pyannote_token: str = None, max_gap_s: float = 0.5, max_chars: int = 90, max_duration_s: float = 8.0, min_speakers: int = 1, max_speakers: int = 2, speaker_corrections: dict = None, merge_short_segments: bool = True, min_segment_duration: float = 0.5)

Parameter Type Default Description
audio_path Path
asr None
speaker_names None
output_srt_path None
pyannote_token str None
max_gap_s float 0.5
max_chars int 90
max_duration_s float 8.0
min_speakers int 1
max_speakers int 2
speaker_corrections dict None
merge_short_segments bool True
min_segment_duration float 0.5

Method BaseVideoLoader.format_timestamp

format_timestamp(seconds)

Parameter Type Default Description
seconds

Method BaseVideoLoader.transcript_to_blocks

Convert a transcript to blocks.

Each block carries both the human-readable SRT timestamps (start_time/end_time) and the raw float seconds (start_seconds/end_seconds) so downstream loaders can build deeplinks and apply numeric range filters in vector stores.

transcript_to_blocks(transcript: str) -> list

Parameter Type Default Description
transcript str

Returns: list

Method BaseVideoLoader.chunk_text

chunk_text(text, chunk_size, tokenizer)

Parameter Type Default Description
text
chunk_size
tokenizer

Method BaseVideoLoader.extract_audio

Extract audio from video. Prefer WAV 16k mono for Whisper.

extract_audio(video_path: Path, audio_path: Path, compress_speed: bool = False, output_path: Optional[Path] = None, speed_factor: float = 1.5)

Parameter Type Default Description
video_path Path
audio_path Path
compress_speed bool False
output_path Optional[Path] None
speed_factor float 1.5

Method BaseVideoLoader.ensure_wav_16k_mono

Ensure src_path is a 16 kHz mono PCM WAV. Returns the WAV path.

  • If src is not a .wav, write .wav
  • If src is already .wav, write .16k.wav to avoid in-place overwrite

ensure_wav_16k_mono(src_path: Path) -> Path

Parameter Type Default Description
src_path Path

Returns: Path

Method BaseVideoLoader.get_whisperx_transcript

WhisperX-based transcription with word-level timestamps. Returns: { "text": "...", "chunks": [ { "text": "...", "timestamp": (start, end), "words": [{"word":"...", "start":..., "end":...}, ...] }, ... ], "language": "en" }

get_whisperx_transcript(audio_path: Path, language: str = 'en', model_name: str = None, batch_size: int = 8, compute_type_gpu: str = 'float16', compute_type_cpu: str = 'int8')

Parameter Type Default Description
audio_path Path
language str 'en'
model_name str None
batch_size int 8
compute_type_gpu str 'float16'
compute_type_cpu str 'int8'

Method BaseVideoLoader.get_whisper_transcript

Enhanced Whisper transcription with manual chunking for GPU memory management.

The key insight: We process smaller audio segments independently on GPU, then merge results with corrected timestamps based on each chunk's offset.

get_whisper_transcript(audio_path: Path, chunk_length: int = 30, word_timestamps: bool = False, manual_chunk: bool = True, max_chunk_duration: int = 60)

Parameter Type Default Description
audio_path Path
chunk_length int 30
word_timestamps bool False
manual_chunk bool True
max_chunk_duration int 60

Method BaseVideoLoader.clear_cuda

Clear CUDA cache and free all GPU memory used by this loader.

This method:

  1. Deletes the summarizer pipeline if loaded
  2. Forces garbage collection
  3. Clears PyTorch CUDA cache

Call this method when done processing to free VRAM for other tasks.

clear_cuda()

Method BaseVideoLoader.load_video

load_video(url: str, video_title: str, transcript: str) -> list

Parameter Type Default Description
url str
video_title str
transcript str

Returns: list

Function extract_video_id

extract_video_id(url)

Parameter Type Default Description
url

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally