Skip to content

Commit dd79922

Browse files
committed
Add Whisper speaker diarization
1 parent faf5729 commit dd79922

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
from typing import Any, Dict, List, Tuple
2+
3+
import torch
4+
from speechbox import ASRDiarizationPipeline
5+
6+
7+
## From https://huggingface.co/spaces/speechbox/whisper-speaker-diarization
8+
## Uses the pre-trained checkpoint Whisper Tiny for the ASR transcriptions and pyannote.audio to label the speakers.
9+
class SpeakerDiarization:
10+
def __init__(self, model_name="openai/whisper-tiny"):
11+
self.device = 0 if torch.cuda.is_available() else "cpu"
12+
self.pipe = ASRDiarizationPipeline.from_pretrained(
13+
asr_model=model_name,
14+
device=self.device,
15+
)
16+
17+
def transcribe(self, file_upload) -> List[Dict[str, Any]]:
18+
"""Transcribe audio file using speaker diarization
19+
20+
Args:
21+
file_upload (_type_): Input audio file
22+
23+
Returns:
24+
str: Transcription of audio file
25+
"""
26+
segments = self.pipe(file_upload)
27+
return segments
28+
29+
def tuple_to_string(self, start_end_tuple: Tuple[float, float], ndigits: int = 1) -> str:
30+
"""Turn a tuple of floats into a string
31+
32+
Args:
33+
start_end_tuple (Tuple[float, float]): Start and end times
34+
ndigits (int, optional): Number of digits . Defaults to 1.
35+
36+
Returns:
37+
str: String representation of tuple
38+
"""
39+
return str((round(start_end_tuple[0], ndigits), round(start_end_tuple[1], ndigits)))
40+
41+
42+
def format_as_transcription(self, raw_segments: List[Dict[str, Any]], with_timestamps: bool=False) -> str:
43+
"""Format raw speaker diarization output as a human readable transcription
44+
45+
Args:
46+
raw_segments (_type_): Raw speaker diarization output
47+
with_timestamps (bool): Whether to include timestamps in the transcription
48+
49+
Returns:
50+
str: Transcription of audio file
51+
"""
52+
if with_timestamps:
53+
return "\n\n".join([chunk["speaker"] + " " + self.tuple_to_string(chunk["timestamp"]) + chunk["text"] for chunk in raw_segments])
54+
else:
55+
return "\n\n".join([chunk["speaker"] + chunk["text"] for chunk in raw_segments])
56+
57+
58+

0 commit comments

Comments
 (0)