Update handler.py
Browse filesUpdate for version mismatch
- handler.py +127 -166
handler.py
CHANGED
|
@@ -1,166 +1,127 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Custom Inference Handler for Pyannote Speaker Diarization
|
| 3 |
-
|
| 4 |
-
This handler is required because Pyannote models don't follow the standard
|
| 5 |
-
HuggingFace Transformers format and need special loading/inference logic.
|
| 6 |
-
|
| 7 |
-
Deployment: Upload this file when creating the HuggingFace Inference Endpoint
|
| 8 |
-
"""
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
import
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
#
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
""
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
segments
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
"type": type(e).__name__
|
| 129 |
-
}
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
# For local testing
|
| 133 |
-
if __name__ == "__main__":
|
| 134 |
-
import sys
|
| 135 |
-
|
| 136 |
-
if len(sys.argv) < 2:
|
| 137 |
-
print("Usage: python handler.py <audio_file.wav>")
|
| 138 |
-
sys.exit(1)
|
| 139 |
-
|
| 140 |
-
# Set token for local testing (get from environment or command line)
|
| 141 |
-
os.environ["HF_TOKEN"] = os.environ.get("HF_TOKEN", "your-token-here")
|
| 142 |
-
|
| 143 |
-
# Initialize handler
|
| 144 |
-
print("Loading diarization pipeline...")
|
| 145 |
-
handler = EndpointHandler()
|
| 146 |
-
|
| 147 |
-
# Test with local file
|
| 148 |
-
audio_path = sys.argv[1]
|
| 149 |
-
print(f"Processing: {audio_path}")
|
| 150 |
-
|
| 151 |
-
with open(audio_path, "rb") as f:
|
| 152 |
-
audio_bytes = f.read()
|
| 153 |
-
|
| 154 |
-
# Run inference
|
| 155 |
-
result = handler({"inputs": audio_bytes})
|
| 156 |
-
|
| 157 |
-
# Print results
|
| 158 |
-
if isinstance(result, dict) and "error" in result:
|
| 159 |
-
print(f"❌ Error: {result['error']}")
|
| 160 |
-
else:
|
| 161 |
-
print(f"✅ Found {len(result)} segments")
|
| 162 |
-
print(f"✅ Speakers: {len(set(s['speaker'] for s in result))}")
|
| 163 |
-
print("\nFirst 5 segments:")
|
| 164 |
-
for segment in result[:5]:
|
| 165 |
-
print(f" {segment['start']:.2f}s - {segment['end']:.2f}s: {segment['speaker']}")
|
| 166 |
-
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Custom Inference Handler for Pyannote Speaker Diarization
|
| 3 |
+
|
| 4 |
+
This handler is required because Pyannote models don't follow the standard
|
| 5 |
+
HuggingFace Transformers format and need special loading/inference logic.
|
| 6 |
+
|
| 7 |
+
Deployment: Upload this file when creating the HuggingFace Inference Endpoint
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
# handler.py
|
| 11 |
+
import os
|
| 12 |
+
os.environ.setdefault("OMP_NUM_THREADS", "1") # silence libgomp warning
|
| 13 |
+
|
| 14 |
+
import io
|
| 15 |
+
import json
|
| 16 |
+
import time
|
| 17 |
+
import uuid
|
| 18 |
+
import tempfile
|
| 19 |
+
import requests
|
| 20 |
+
import torch
|
| 21 |
+
from typing import Any, Dict
|
| 22 |
+
|
| 23 |
+
from pyannote.audio import Pipeline
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class EndpointHandler:
|
| 27 |
+
"""
|
| 28 |
+
Hugging Face Inference Endpoint / Serverless handler
|
| 29 |
+
Expects JSON like:
|
| 30 |
+
{
|
| 31 |
+
"session_id": "sess_123",
|
| 32 |
+
"audio_url": "https://signed-eu-url/file.m4a",
|
| 33 |
+
"min_speakers": 2,
|
| 34 |
+
"max_speakers": 3,
|
| 35 |
+
"offset": 0.0,
|
| 36 |
+
"duration": null,
|
| 37 |
+
"trace_id": "optional-uuid"
|
| 38 |
+
}
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __init__(self, path=""):
|
| 42 |
+
# HF_TOKEN must be provided as a secret / env var in the endpoint
|
| 43 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 44 |
+
if not hf_token:
|
| 45 |
+
raise RuntimeError("HF_TOKEN environment variable is required to download pyannote weights.")
|
| 46 |
+
|
| 47 |
+
# Load the diarization pipeline once
|
| 48 |
+
self.pipeline = Pipeline.from_pretrained(
|
| 49 |
+
"pyannote/speaker-diarization-3.1",
|
| 50 |
+
use_auth_token=hf_token
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
if torch.cuda.is_available():
|
| 54 |
+
self.pipeline.to(torch.device("cuda"))
|
| 55 |
+
|
| 56 |
+
def _download_to_temp(self, url: str) -> str:
|
| 57 |
+
# Minimal URL fetch to a temp file; delete-on-close is False so pyannote can read it
|
| 58 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".bin") as tmp:
|
| 59 |
+
with requests.get(url, stream=True, timeout=60) as r:
|
| 60 |
+
r.raise_for_status()
|
| 61 |
+
for chunk in r.iter_content(1024 * 1024):
|
| 62 |
+
if chunk:
|
| 63 |
+
tmp.write(chunk)
|
| 64 |
+
return tmp.name
|
| 65 |
+
|
| 66 |
+
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
| 67 |
+
t0 = time.time()
|
| 68 |
+
|
| 69 |
+
# Basic payload validation
|
| 70 |
+
if not isinstance(data, dict):
|
| 71 |
+
try:
|
| 72 |
+
data = json.loads(data)
|
| 73 |
+
except Exception:
|
| 74 |
+
raise ValueError("Expected JSON dict or JSON-encoded string.")
|
| 75 |
+
|
| 76 |
+
session_id = data.get("session_id") or "unknown"
|
| 77 |
+
audio_url = data.get("audio_url")
|
| 78 |
+
if not audio_url:
|
| 79 |
+
raise ValueError("Missing required field: 'audio_url'")
|
| 80 |
+
|
| 81 |
+
min_speakers = data.get("min_speakers")
|
| 82 |
+
max_speakers = data.get("max_speakers")
|
| 83 |
+
offset = float(data.get("offset") or 0.0)
|
| 84 |
+
duration = data.get("duration")
|
| 85 |
+
trace_id = data.get("trace_id") or str(uuid.uuid4())
|
| 86 |
+
|
| 87 |
+
# Build kwargs to pass into pyannote pipeline
|
| 88 |
+
kwargs = {}
|
| 89 |
+
if min_speakers is not None:
|
| 90 |
+
kwargs["min_speakers"] = int(min_speakers)
|
| 91 |
+
if max_speakers is not None:
|
| 92 |
+
kwargs["max_speakers"] = int(max_speakers)
|
| 93 |
+
if duration is not None:
|
| 94 |
+
kwargs["duration"] = float(duration)
|
| 95 |
+
if offset:
|
| 96 |
+
kwargs["offset"] = float(offset)
|
| 97 |
+
|
| 98 |
+
# Download, diarize, cleanup
|
| 99 |
+
tmp_path = None
|
| 100 |
+
try:
|
| 101 |
+
tmp_path = self._download_to_temp(audio_url)
|
| 102 |
+
diarization = self.pipeline(tmp_path, **kwargs)
|
| 103 |
+
|
| 104 |
+
segments = []
|
| 105 |
+
for turn, _, speaker in diarization.itertracks(yield_label=True):
|
| 106 |
+
segments.append({
|
| 107 |
+
"start": float(turn.start),
|
| 108 |
+
"end": float(turn.end),
|
| 109 |
+
"speaker": str(speaker)
|
| 110 |
+
})
|
| 111 |
+
|
| 112 |
+
runtime_ms = int((time.time() - t0) * 1000)
|
| 113 |
+
return {
|
| 114 |
+
"session_id": session_id,
|
| 115 |
+
"trace_id": trace_id,
|
| 116 |
+
"segments": segments,
|
| 117 |
+
"model": "pyannote/speaker-diarization-3.1",
|
| 118 |
+
"runtime_ms": runtime_ms
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
finally:
|
| 122 |
+
# Best-effort temp file cleanup
|
| 123 |
+
if tmp_path:
|
| 124 |
+
try:
|
| 125 |
+
os.remove(tmp_path)
|
| 126 |
+
except Exception:
|
| 127 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|