sergetshim27 commited on
Commit
3f0bbf0
·
verified ·
1 Parent(s): b85dfdf

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +19 -8
  2. app.py +116 -0
  3. requirements.txt +6 -0
README.md CHANGED
@@ -1,14 +1,25 @@
1
  ---
2
- title: Smartfile Diarization
3
- emoji: 🏃
4
- colorFrom: yellow
5
- colorTo: pink
6
  sdk: gradio
7
- sdk_version: 6.18.0
8
- python_version: '3.13'
9
  app_file: app.py
10
  pinned: false
11
- short_description: test
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: SmartFile Speaker Diarization
3
+ emoji: 🎙️
4
+ colorFrom: indigo
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 5.9.1
 
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
+ # SmartFile Speaker Diarization
13
+
14
+ Detects **who speaks when** using `pyannote/speaker-diarization-3.1`. SmartFile
15
+ calls this before transcription so each speaker turn can be transcribed and
16
+ labeled (Locuteur 1, Locuteur 2, …).
17
+
18
+ Send base64 audio, get JSON: `{"segments":[{"speaker","start","end"}...], "num_speakers"}`.
19
+
20
+ **Gated models** — you must accept terms for BOTH on the same account as HF_TOKEN:
21
+ - pyannote/speaker-diarization-3.1
22
+ - pyannote/segmentation-3.0
23
+
24
+ Tuned for 2-person interviews/calls (detected, not hard-forced). Heavier than
25
+ the STT Space — use a paid CPU/GPU tier for usable speed.
app.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SmartFile Speaker Diarization — Hugging Face Space
3
+ ==================================================
4
+ Runs pyannote/speaker-diarization-3.1 to detect WHO SPEAKS WHEN in an audio
5
+ clip. SmartFile calls this BEFORE transcription so each speaker turn can be
6
+ transcribed and labeled (Locuteur 1, Locuteur 2, ...).
7
+
8
+ Contract (same simple pattern as the STT Space):
9
+ INPUT : base64-encoded audio (WAV/etc) in a Textbox.
10
+ OUTPUT : a JSON string -> {"segments": [{"speaker": "...", "start": s, "end": s}, ...],
11
+ "num_speakers": N}
12
+ or {"error": "..."} on failure.
13
+
14
+ The pipeline is GATED on Hugging Face and requires accepting terms for BOTH:
15
+ - pyannote/speaker-diarization-3.1
16
+ - pyannote/segmentation-3.0 (dependency)
17
+ and an HF_TOKEN secret on this Space with access to them.
18
+
19
+ Tuning: this client's audio is mostly 2-person interviews/calls, so we hint the
20
+ pipeline toward 2 speakers (min 1, max 4) — detected, not hard-forced, so a
21
+ stray third voice won't break it. Tiny adjacent same-speaker turns are merged.
22
+
23
+ NOTE: pyannote loads several models (segmentation + embedding); it is HEAVIER
24
+ than the STT Space. Use a paid CPU (or GPU) tier for usable speed.
25
+ """
26
+
27
+ import base64
28
+ import io
29
+ import json
30
+ import os
31
+ import gradio as gr
32
+ import torch
33
+ from pyannote.audio import Pipeline
34
+
35
+ HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
36
+ MODEL_ID = "pyannote/speaker-diarization-3.1"
37
+
38
+ # Hint for the typical case (2-person interview/call). Detected, not hard-forced.
39
+ DEFAULT_MIN_SPEAKERS = 1
40
+ DEFAULT_MAX_SPEAKERS = 4
41
+ MERGE_GAP_SEC = 0.5 # merge same-speaker segments separated by < this gap
42
+ MIN_SEG_SEC = 0.3 # drop micro-segments shorter than this (noise/clicks)
43
+
44
+ print(f"[diar] loading {MODEL_ID} ...")
45
+ pipeline = Pipeline.from_pretrained(MODEL_ID, use_auth_token=HF_TOKEN)
46
+ if torch.cuda.is_available():
47
+ pipeline.to(torch.device("cuda"))
48
+ print("[diar] using GPU")
49
+ print("[diar] pipeline ready")
50
+
51
+
52
+ def _merge_segments(segs):
53
+ """Merge adjacent same-speaker segments with tiny gaps; drop micro-segments."""
54
+ if not segs:
55
+ return segs
56
+ segs = sorted(segs, key=lambda s: s["start"])
57
+ merged = [segs[0]]
58
+ for s in segs[1:]:
59
+ last = merged[-1]
60
+ if s["speaker"] == last["speaker"] and s["start"] - last["end"] <= MERGE_GAP_SEC:
61
+ last["end"] = max(last["end"], s["end"])
62
+ else:
63
+ merged.append(s)
64
+ return [s for s in merged if (s["end"] - s["start"]) >= MIN_SEG_SEC]
65
+
66
+
67
+ def diarize_b64(audio_b64):
68
+ if not audio_b64:
69
+ return json.dumps({"error": "empty input"})
70
+ try:
71
+ if audio_b64.strip().startswith("data:") and "," in audio_b64[:64]:
72
+ audio_b64 = audio_b64.split(",", 1)[1]
73
+ raw = base64.b64decode(audio_b64)
74
+ print(f"[diar] decoded {len(raw)} audio bytes")
75
+
76
+ # pyannote reads a file path or a waveform; easiest robust path is to
77
+ # write the bytes to a temp file (it handles WAV/MP3/etc + resampling).
78
+ import tempfile
79
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
80
+ tmp.write(raw)
81
+ tmp_path = tmp.name
82
+
83
+ diarization = pipeline(
84
+ tmp_path,
85
+ min_speakers=DEFAULT_MIN_SPEAKERS,
86
+ max_speakers=DEFAULT_MAX_SPEAKERS,
87
+ )
88
+ os.unlink(tmp_path)
89
+
90
+ segs = []
91
+ for turn, _, speaker in diarization.itertracks(yield_label=True):
92
+ segs.append({
93
+ "speaker": speaker, # e.g. "SPEAKER_00"
94
+ "start": round(float(turn.start), 2),
95
+ "end": round(float(turn.end), 2),
96
+ })
97
+ segs = _merge_segments(segs)
98
+
99
+ speakers = sorted({s["speaker"] for s in segs})
100
+ print(f"[diar] {len(segs)} segments, {len(speakers)} speakers")
101
+ return json.dumps({"segments": segs, "num_speakers": len(speakers)})
102
+ except Exception as e:
103
+ print(f"[diar] error: {e}")
104
+ return json.dumps({"error": str(e)})
105
+
106
+
107
+ demo = gr.Interface(
108
+ fn=diarize_b64,
109
+ inputs=gr.Textbox(label="Base64 audio"),
110
+ outputs=gr.Textbox(label="Diarization JSON"),
111
+ title="SmartFile Speaker Diarization",
112
+ description="Detect who speaks when (pyannote 3.1). Send base64 audio, get speaker segments as JSON.",
113
+ )
114
+
115
+ if __name__ == "__main__":
116
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio==5.9.1
2
+ huggingface_hub>=0.26.0
3
+ pyannote.audio>=3.1.0
4
+ torch>=2.2.0
5
+ torchaudio>=2.2.0
6
+ soundfile>=0.12.1