Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download backends/diarization.py from treble-technologies/ffasr: direct link, hf CLI and curl.
- Browser
- Download file 5.32 kB
-
https://huggingface.co/spaces/treble-technologies/ffasr/resolve/main/backends/diarization.py
- Command line
-
hf download hf://spaces/treble-technologies/ffasr/backends/diarization.py
-
curl -L -o diarization.py https://huggingface.co/spaces/treble-technologies/ffasr/resolve/main/backends/diarization.py
5.32 kB
| """ | |
| Speaker diarization backends: ``diarize(audio_np, sampling_rate) -> [(start_s, end_s, speaker)]``. | |
| Families: | |
| * ``pyannote`` — ``pyannote.audio.Pipeline`` checkpoints (e.g. ``pyannote/speaker-diarization-3.1``). | |
| * ``nemo_sortformer`` — NeMo Sortformer end-to-end diarizers (e.g. ``nvidia/diar_sortformer_4spk-v1``). | |
| * custom script — submitter module defining ``diarize(file: Path)`` (``evaluate`` is accepted | |
| as an alias); the return value may be any format ``benchmark.diarization.normalize_segments`` | |
| understands (tuples, dicts, RTTM text, pyannote ``Annotation``). | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import shutil | |
| import tempfile | |
| from collections.abc import Callable | |
| from pathlib import Path | |
| from ._model_utils import count_params | |
| DIARIZATION_FAMILY_LABELS: dict[str, str] = { | |
| "pyannote": "pyannote.audio pipeline", | |
| "nemo_sortformer": "NeMo Sortformer", | |
| "custom": "Custom diarize()", | |
| } | |
| def resolve_diarization_family(model_id: str, family_id: str | None = None) -> str: | |
| fid = (family_id or "auto").strip().lower() | |
| if fid in DIARIZATION_FAMILY_LABELS and fid != "custom": | |
| return fid | |
| m = (model_id or "").lower() | |
| if "sortformer" in m or m.startswith("nvidia/diar"): | |
| return "nemo_sortformer" | |
| return "pyannote" | |
| def _hf_token() -> str | None: | |
| return (os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN") or "").strip() or None | |
| def _temp_wav_writer(prefix: str): | |
| import soundfile as sf | |
| wav_dir = tempfile.mkdtemp(prefix=prefix) | |
| counter = {"i": 0} | |
| def write(audio_np, sampling_rate: int) -> Path: | |
| counter["i"] += 1 | |
| path = Path(wav_dir) / f"sample_{counter['i']:08d}.wav" | |
| sf.write(str(path), audio_np, int(sampling_rate), subtype="PCM_16") | |
| return path | |
| return write, wav_dir | |
| def _build_pyannote(model_id: str, device_str: str): | |
| import torch | |
| from pyannote.audio import Pipeline | |
| token = _hf_token() | |
| try: | |
| pipeline = Pipeline.from_pretrained(model_id, token=token) | |
| except TypeError: | |
| pipeline = Pipeline.from_pretrained(model_id, use_auth_token=token) | |
| if pipeline is None: | |
| raise RuntimeError( | |
| f"pyannote could not load {model_id!r} (gated repo? accept its conditions for HF_TOKEN)." | |
| ) | |
| pipeline.to(torch.device(device_str)) | |
| def diarize(audio_np, sampling_rate: int): | |
| waveform = torch.from_numpy(audio_np).float().reshape(1, -1) | |
| return pipeline({"waveform": waveform, "sample_rate": int(sampling_rate)}) | |
| n = 0 | |
| for attr in ("_segmentation", "_embedding", "segmentation_model", "embedding_model"): | |
| sub = getattr(pipeline, attr, None) | |
| n += count_params(getattr(sub, "model", None) or sub) | |
| diarize._num_params = n # type: ignore[attr-defined] | |
| return diarize, (lambda: None) | |
| def _build_nemo_sortformer(model_id: str, device_str: str): | |
| from nemo.collections.asr.models import SortformerEncLabelModel | |
| model = SortformerEncLabelModel.from_pretrained(model_id, map_location=device_str) | |
| model.eval() | |
| write_wav, wav_dir = _temp_wav_writer("ffasr_diar_wav_") | |
| def diarize(audio_np, sampling_rate: int): | |
| path = write_wav(audio_np, sampling_rate) | |
| try: | |
| out = model.diarize(audio=[str(path)], batch_size=1) | |
| finally: | |
| path.unlink(missing_ok=True) | |
| return out[0] if isinstance(out, (list, tuple)) and out else out | |
| diarize._num_params = count_params(model) # type: ignore[attr-defined] | |
| return diarize, (lambda: shutil.rmtree(wav_dir, ignore_errors=True)) | |
| def _build_custom(script_text: str): | |
| from .custom_eval import discover_num_params, load_custom_module | |
| mod, script_path = load_custom_module(script_text) | |
| fn = getattr(mod, "diarize", None) or getattr(mod, "evaluate", None) | |
| if not callable(fn): | |
| os.unlink(script_path) | |
| raise RuntimeError( | |
| "Custom diarization script must define " | |
| "`diarize(file: pathlib.Path) -> list[tuple[float, float, str]]`." | |
| ) | |
| write_wav, wav_dir = _temp_wav_writer("ffasr_custom_diar_wav_") | |
| def diarize(audio_np, sampling_rate: int): | |
| path = write_wav(audio_np, sampling_rate) | |
| try: | |
| return fn(path) | |
| finally: | |
| path.unlink(missing_ok=True) | |
| try: | |
| diarize._num_params = discover_num_params(mod) # type: ignore[attr-defined] | |
| except Exception: | |
| diarize._num_params = 0 # type: ignore[attr-defined] | |
| def cleanup() -> None: | |
| shutil.rmtree(wav_dir, ignore_errors=True) | |
| Path(script_path).unlink(missing_ok=True) | |
| return diarize, cleanup | |
| def build_diarizer( | |
| model_id: str, | |
| family_id: str, | |
| device_str: str, | |
| custom_script: str = "", | |
| ) -> tuple[Callable, Callable[[], None], str]: | |
| """Return ``(diarize, cleanup, family_label)``.""" | |
| if (custom_script or "").strip(): | |
| fn, cleanup = _build_custom(custom_script) | |
| return fn, cleanup, DIARIZATION_FAMILY_LABELS["custom"] | |
| fid = resolve_diarization_family(model_id, family_id) | |
| if fid == "nemo_sortformer": | |
| fn, cleanup = _build_nemo_sortformer(model_id, device_str) | |
| else: | |
| fn, cleanup = _build_pyannote(model_id, device_str) | |
| return fn, cleanup, DIARIZATION_FAMILY_LABELS[fid] | |