Source code for mllm_shap.backends.transformers.audio
"""Audio parts for a Hugging Face processor: waveforms, rates and template parts.
@domain backends
@see [[knowledge/architecture/backends]]
@tested-by [[tests/backends/test_transformers_audio.py]]
"""
import base64
from typing import Any
import numpy as np
from numpy.typing import NDArray
from ...alignment.io import decode_audio, encode_wav
from ...domain.conversation import AudioPart
[docs]
def audio_template_part(
samples: NDArray[np.float32], rate: int, processor: Any
) -> dict[str, Any]:
"""Return a chat-template audio part; mistral-common takes base64 WAV."""
if is_mistral_common(processor):
encoded = base64.b64encode(encode_wav(samples, rate)).decode()
return {"type": "audio", "base64": encoded}
return {"type": "audio", "audio": samples}
[docs]
def sampling_rate(processor: Any) -> int:
"""Return the sample rate of the processor's audio component."""
# Processors name their audio component differently (Granite: audio_processor).
extractor: Any = getattr(processor, "feature_extractor", None) or getattr(
processor, "audio_processor", None
)
return int(extractor.sampling_rate)
[docs]
def is_mistral_common(processor: Any) -> bool:
"""Return whether the tokenizer is mistral-common's (Voxtral)."""
return "mistral_common" in type(processor.tokenizer).__module__
[docs]
def template_has_audio(processor: Any) -> bool:
"""Return whether the processor's chat template takes audio parts."""
return is_mistral_common(processor) or template_mentions(processor, "audio")
[docs]
def template_mentions(processor: Any, word: str) -> bool:
"""Return whether the processor's or tokenizer's chat template contains ``word``."""
templates = (
getattr(processor, "chat_template", None),
getattr(processor.tokenizer, "chat_template", None),
)
return any(isinstance(t, str) and word in t for t in templates)