Add optional pyannote diarization alongside the pooled Whisper instances, gated by a diarize parameter and DIARIZATION_MODEL env var
Browse filesFiles changed (3)
- diarization_utils.pyAdded+141
- handler.py+53-8
- requirements.txt+1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141import torchimport numpy as npfrom torchaudio import functional as Ffrom transformers.pipelines.audio_utils import ffmpeg_readfrom starlette.exceptions import HTTPExceptionimport sys
# Code from insanely-fast-whisper:# https://github.com/Vaibhavs10/insanely-fast-whisper
import logginglogger = logging.getLogger(__name__)
def preprocess_inputs(inputs, sampling_rate): inputs = ffmpeg_read(inputs, sampling_rate)
if sampling_rate != 16000: inputs = F.resample( torch.from_numpy(inputs), sampling_rate, 16000 ).numpy()
if len(inputs.shape) != 1: logger.error(f"Diarization pipeline expecs single channel audio, received {inputs.shape}") raise HTTPException( status_code=400, detail=f"Diarization pipeline expecs single channel audio, received {inputs.shape}" )
# diarization model expects float32 torch tensor of shape `(channels, seq_len)` diarizer_inputs = torch.from_numpy(inputs).float() diarizer_inputs = diarizer_inputs.unsqueeze(0)
return inputs, diarizer_inputs
def diarize_audio(diarizer_inputs, diarization_pipeline, parameters): diarization = diarization_pipeline( {"waveform": diarizer_inputs, "sample_rate": parameters.sampling_rate}, num_speakers=parameters.num_speakers, min_speakers=parameters.min_speakers, max_speakers=parameters.max_speakers, )
segments = [] for segment, track, label in diarization.itertracks(yield_label=True): segments.append( { "segment": {"start": segment.start, "end": segment.end}, "track": track, "label": label, } )
# diarizer output may contain consecutive segments from the same speaker (e.g. {(0 -> 1, speaker_1), (1 -> 1.5, speaker_1), ...}) # we combine these segments to give overall timestamps for each speaker's turn (e.g. {(0 -> 1.5, speaker_1), ...}) new_segments = [] prev_segment = cur_segment = segments[0]
for i in range(1, len(segments)): cur_segment = segments[i]
# check if we have changed speaker ("label") if cur_segment["label"] != prev_segment["label"] and i < len(segments): # add the start/end times for the super-segment to the new list new_segments.append( { "segment": { "start": prev_segment["segment"]["start"], "end": cur_segment["segment"]["start"], }, "speaker": prev_segment["label"], } ) prev_segment = segments[i]
# add the last segment(s) if there was no speaker change new_segments.append( { "segment": { "start": prev_segment["segment"]["start"], "end": cur_segment["segment"]["end"], }, "speaker": prev_segment["label"], } )
return new_segments
def post_process_segments_and_transcripts(new_segments, transcript, group_by_speaker) -> list: # get the end timestamps for each chunk from the ASR output end_timestamps = np.array( [chunk["timestamp"][-1] if chunk["timestamp"][-1] is not None else sys.float_info.max for chunk in transcript]) segmented_preds = []
# align the diarizer timestamps and the ASR timestamps for segment in new_segments: # get the diarizer end timestamp end_time = segment["segment"]["end"] # find the ASR end timestamp that is closest to the diarizer's end timestamp and cut the transcript to here upto_idx = np.argmin(np.abs(end_timestamps - end_time))
if group_by_speaker: segmented_preds.append( { "speaker": segment["speaker"], "text": "".join( [chunk["text"] for chunk in transcript[: upto_idx + 1]] ), "timestamp": ( transcript[0]["timestamp"][0], transcript[upto_idx]["timestamp"][1], ), } ) else: for i in range(upto_idx + 1): segmented_preds.append({"speaker": segment["speaker"], **transcript[i]})
# crop the transcripts and timestamp lists according to the latest timestamp (for faster argmin) transcript = transcript[upto_idx + 1:] end_timestamps = end_timestamps[upto_idx + 1:]
if len(end_timestamps) == 0: break
return segmented_preds
def diarize(diarization_pipeline, file, parameters, asr_outputs): _, diarizer_inputs = preprocess_inputs(file, parameters.sampling_rate)
segments = diarize_audio( diarizer_inputs, diarization_pipeline, parameters )
return post_process_segments_and_transcripts( segments, asr_outputs["chunks"], group_by_speaker=False )1 unmodified line234567891011121314157 unmodified lines2324252627282930313233343536373839404142431 unmodified lineimport loggingimport osimport queueimport torchfrom transformers import pipelinelogger = logging.getLogger(__name__)ASR_MODEL = os.environ.get("ASR_MODEL", "openai/whisper-large-v3")NUM_INSTANCES = int(os.environ.get("NUM_INSTANCES", "3"))class EndpointHandler:7 unmodified linesfor _ in range(NUM_INSTANCES)]# Each pipeline instance has internal state (KV cache buffers etc.) that isn't# safe to share across concurrent calls, so requests check an instance out of# this pool and return it when done rather than all hitting self.pipelines[0].self.pool: queue.Queue = queue.Queue()for i in range(NUM_INSTANCES):self.pool.put(i)def __call__(self, data: dict) -> dict:inputs = data.pop("inputs")if isinstance(inputs, str):inputs = base64.b64decode(inputs)parameters = data.pop("parameters", None) or {}index = self.pool.get() # blocks here if all instances are busytry:return self.pipelines[index](inputs, **parameters)finally:self.pool.put(index)1 unmodified line234567891011121314151617181920217 unmodified lines2930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687881 unmodified lineimport loggingimport osimport queueimport typesimport torchfrom huggingface_hub import HfApifrom transformers import pipelinefrom diarization_utils import diarizelogger = logging.getLogger(__name__)ASR_MODEL = os.environ.get("ASR_MODEL", "openai/whisper-large-v3")NUM_INSTANCES = int(os.environ.get("NUM_INSTANCES", "5"))DIARIZATION_MODEL = os.environ.get("DIARIZATION_MODEL") # unset = diarization disabledHF_TOKEN = os.environ.get("HF_TOKEN")class EndpointHandler:7 unmodified linesfor _ in range(NUM_INSTANCES)]# Each pipeline instance has internal state that isn't safe to share across# concurrent calls, so requests check an instance out of this pool and return# it when done rather than all hitting self.pipelines[0].self.pool: queue.Queue = queue.Queue()for i in range(NUM_INSTANCES):self.pool.put(i)self.diarization_pipeline = Noneif DIARIZATION_MODEL:from pyannote.audio import Pipeline as DiarizationPipeline# Raises if the token can't access the (gated) diarization model.HfApi().whoami(HF_TOKEN)logger.info(f"Loading diarization model {DIARIZATION_MODEL}")self.diarization_pipeline = DiarizationPipeline.from_pretrained(checkpoint_path=DIARIZATION_MODEL, use_auth_token=HF_TOKEN)self.diarization_pipeline.to(device)def __call__(self, data: dict) -> dict:inputs = data.pop("inputs")raw_bytes = base64.b64decode(inputs) if isinstance(inputs, str) else inputsparameters = dict(data.pop("parameters", None) or {})want_diarization = parameters.pop("diarize", False)num_speakers = parameters.pop("num_speakers", None)min_speakers = parameters.pop("min_speakers", None)max_speakers = parameters.pop("max_speakers", None)sampling_rate = parameters.pop("sampling_rate", 16000)# Diarization's speaker/transcript alignment needs chunk timestamps to merge# against, even if the caller didn't explicitly ask for them.if want_diarization and "return_timestamps" not in parameters:parameters["return_timestamps"] = Trueindex = self.pool.get() # blocks here if all instances are busytry:asr_outputs = self.pipelines[index](raw_bytes, **parameters)finally:self.pool.put(index)if not want_diarization:return asr_outputsif self.diarization_pipeline is None:return {**asr_outputs, "speakers": [], "error": "DIARIZATION_MODEL is not configured on this endpoint"}diar_params = types.SimpleNamespace(sampling_rate=sampling_rate,num_speakers=num_speakers,min_speakers=min_speakers,max_speakers=max_speakers,)chunks = asr_outputs.get("chunks") or [{"timestamp": [0, None], "text": asr_outputs.get("text", "")}]speakers = diarize(self.diarization_pipeline, raw_bytes, diar_params, {"chunks": chunks})return {**asr_outputs, "speakers": speakers}
3 unmodified lines4563 unmodified linestorchaudio==2.4.0transformers==4.44.2numpy==1.26.43 unmodified lines45673 unmodified linestorchaudio==2.4.0transformers==4.44.2numpy==1.26.4pyannote-audio==3.1.1
diarization_utils.pyAdded+141
handler.py+53-8
requirements.txt+1