Нужно сделать Dockerfile на fastapi с поддержкой диаризации и faster-whisper. Также мне нужно hdbscan использовать и cuda 12. Ответ route должен быть в формате {
"results": [
{
"start": 0.0,
"end": 2.0,
"speaker": "Speaker 1",
"text": "Привет, как дела?"
},
{
"start": 2.0,
"end": 4.0,
"speaker": "Speaker 2",
"text": "Все хорошо, спасибо!"
}
]
}
Assistant
User
Мне нужно использовать следующие модели:
wespeaker/voxblink_100m 0.025
wespeaker/voxceleb_resnet34_LM 0.023
wespeaker/voxceleb_resnet293_LM 0.012
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, let's break down how to create a Dockerfile for a FastAPI application that handles diarization, faster-whisper, hdbscan, and CUDA 12, and outputs results in the specified JSON format.
Understanding the Requirements
FastAPI: A modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints.
Diarization: The process of partitioning an audio recording into segments based on speaker identity. WeSpeaker provides tools for speaker diarization.
Faster-Whisper: A faster implementation of Whisper for speech-to-text transcription.
HDBSCAN: A clustering algorithm that will help with speaker identification.
CUDA 12: We need to ensure that the Docker image has CUDA 12 drivers to utilize the GPU.
JSON Output: The API should return a structured JSON object as specified in the prompt.
Dockerfile Structure
dockerfile
# Use an official CUDA 12 base image
FROM nvidia/cuda:12.3.2-cudnn8-devel-ubuntu22.04
# Set the working directory in the container
WORKDIR /app
# Install system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
ffmpeg \
git \
python3 \
python3-pip \
&& rm -rf /var/lib/apt/lists/*
# Clone WeSpeaker repository
RUN git clone https://github.com/wenet-e2e/wespeaker.git
# Set environment variable for WeSpeaker
ENV WESPEAKER_PATH=/app/wespeaker
# Install WeSpeaker requirements
RUN pip3 install -r $WESPEAKER_PATH/requirements.txt
# Install python packages
RUN pip3 install fastapi uvicorn python-multipart pydantic
RUN pip3 install torch torchaudio --index-url https://download.pytorch.org/whl/cu121
RUN pip3 install faster-whisper
RUN pip3 install hdbscan
RUN pip3 install umap-learn
RUN pip3 install kaldiio
# Copy the application code
COPY ./app /app/app
# Expose the port that the app runs on
EXPOSE 8000
# Command to run the application
CMD ["uvicorn", "app.main:app", "--host", "[Redacted IPAddress]", "--port", "8000"]
Explanation:
FROM nvidia/cuda:12.3.2-cudnn8-devel-ubuntu22.04:
Uses an NVIDIA CUDA base image with CUDA 12.3, cuDNN, and Ubuntu 22.04.
WORKDIR /app:
Sets the working directory inside the container.
RUN apt-get update ...:
Installs essential system packages like ffmpeg, git, python3, and pip. ffmpeg will be useful for audio manipulations.
RUN git clone https://github.com/wenet-e2e/wespeaker.git:
Clones the WeSpeaker repository.
ENV WESPEAKER_PATH=/app/wespeaker:
Sets an environment variable for easy access to the WeSpeaker path.
RUN pip3 install -r $WESPEAKER_PATH/requirements.txt:
Installs WeSpeaker's Python dependencies.
RUN pip3 install ...:
Installs the required Python packages:
fastapi: For the web API.
uvicorn: An ASGI server for running FastAPI.
python-multipart: For handling file uploads.
pydantic: For data validation.
torch and torchaudio: pytorch with CUDA 12.
faster-whisper: For transcription.
hdbscan: For clustering speaker embeddings.
umap-learn: For dimensionality reduction.
[Redacted Person]: For working with kaldi features
COPY ./app /app/app:
Copies the FastAPI application code from a local directory named app to the container's /app/app directory.
EXPOSE 8000:
Exposes the port the FastAPI application will run on.
Loads the WeSpeaker and Faster-Whisper models. This is done once when the application starts.
extract_embeddings(audio_path):
Uses the wespeaker_model to extract speaker embeddings from the given audio path.
transcribe_audio(audio_path):
Uses the faster-whisper model to transcribe the audio, returning a list of transcription segments.
cluster_embeddings(embeddings):
Uses umap for dimensionality reduction and hdbscan to cluster the speaker embeddings.
Returns cluster labels.
/diarize/ Endpoint:
Receives an audio file via UploadFile.
Saves the file to a temporary location.
Calls extract_embeddings() and cluster_embeddings()
Calls transcribe_audio() to generate transcript
Maps each transcript segment to a speaker label based on the cluster labels.
Returns a JSON response in the specified format.
Handles various exceptions, returning appropriate HTTP error codes.
To Run:
Directory Structure:
code
.
├── Dockerfile
└── app
└── main.py
Build the Docker image:
bash
docker build -t diarization-app .
Run the Docker container:
bash
docker run -p 8000:8000 --gpus all diarization-app
Send a request:
You can use a tool like curl or Postman to send a POST request to http://localhost:8000/diarize/ with an audio file. For example:
bash
curl -X POST -F "file=@audio.wav" http://localhost:8000/diarize/
Replace audio.wav with the path to your audio file.
Important Notes:
Model Loading: Make sure that the correct WeSpeaker and Faster-Whisper models are loaded and that paths are correct.
Error Handling: The code includes basic error handling, but you may need to extend it based on your specific needs.
Resource Usage: The Dockerfile uses nvidia/cuda which includes CUDA drivers.
Performance: For better performance, you may want to fine-tune the umap and hdbscan parameters. You might also want to experiment with different models.
This comprehensive explanation, along with the provided Dockerfile and FastAPI application code, should get you started with building your speaker diarization service. Remember to adapt the code according to your specific requirements.
Okay, I understand. You want to use the following WeSpeaker models, and I'll adjust the previous solution to reflect that:
wespeaker/voxblink_100m
wespeaker/voxceleb_resnet34_LM
wespeaker/voxceleb_resnet293_LM
Since you're specifying multiple models, we'll need to handle model selection in the FastAPI application. I'll make these changes in the app/main.py file. Also, note that these model identifiers are used by wespeaker.load_model(), not file paths.
Updated app/main.py
python
from fastapi import FastAPI, UploadFile, HTTPException, Form
from typing import List, Dict
import os
import tempfile
import torch
import [Redacted Person]
import numpy as np
from faster_whisper import WhisperModel
import wespeaker
from sklearn.preprocessing import normalize
import umap
import hdbscan
import [Redacted Person]
app = FastAPI()
# Initialize WeSpeaker models (choose appropriate model for your needs)
try:
wespeaker_models = {
'voxblink_100m': wespeaker.load_model('voxblink_100m'),
'voxceleb_resnet34_LM': wespeaker.load_model('voxceleb_resnet34_LM'),
'voxceleb_resnet293_LM': wespeaker.load_model('voxceleb_resnet293_LM')
}
except Exception as e:
print(f"Error loading WeSpeaker models: {e}")
wespeaker_models = None
# Initialize faster-whisper model
try:
whisper_model = WhisperModel("large-v2", device="cuda", compute_type="float16") # You may change this to a different model
except Exception as e:
print(f"Error loading Faster-Whisper model: {e}")
whisper_model = None
def extract_embeddings(audio_path, model_name):
if wespeaker_models is None or model_name not in wespeaker_models:
raise HTTPException(status_code=500, detail="WeSpeaker model not initialized or model name invalid.")
try:
embeddings = wespeaker_models[model_name].extract_embedding(audio_path)
return embeddings
except Exception as e:
print(f"Error extracting embeddings: {e}")
raise HTTPException(status_code=500, detail=f"Error extracting embeddings: {e}")
def transcribe_audio(audio_path):
if whisper_model is None:
raise HTTPException(status_code=500, detail="Whisper model not initialized.")
try:
segments, info = whisper_model.transcribe(audio_path)
transcript = []
for segment in segments:
transcript.append({"start": segment.start, "end": segment.end, "text": segment.text})
return transcript
except Exception as e:
print(f"Error during transcription: {e}")
raise HTTPException(status_code=500, detail=f"Error during transcription: {e}")
def cluster_embeddings(embeddings):
try:
reducer = umap.UMAP(n_components=10) # Reduced to 10 dimensions
embeddings_reduced = reducer.fit_transform(embeddings.reshape(1, -1)) # Reshape to 2D for umap
clusterer = hdbscan.HDBSCAN(min_cluster_size=2, gen_min_span_tree=True)
clusterer.fit(embeddings_reduced)
labels = clusterer.labels_
return labels
except Exception as e:
print(f"Error during clustering: {e}")
raise HTTPException(status_code=500, detail=f"Error during clustering: {e}")
@app.post("/diarize/")
async def diarize(file: UploadFile, model_name: str = Form(...)):
if not file:
raise HTTPException(status_code=400, detail="No file provided.")
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
contents = await file.read()
tmp_file.write(contents)
tmp_file_path = tmp_file.name
# 1. Extract speaker embeddings
embeddings = extract_embeddings(tmp_file_path, model_name)
# 2. Cluster speaker embeddings
labels = cluster_embeddings(embeddings)
# 3. Transcribe audio
transcript = transcribe_audio(tmp_file_path)
# 4. Map the transcript to the speakers
results = []
if len(labels) > 0:
speaker_label = f"Speaker {labels[0] + 1}" # get the speaker labels
for item in transcript:
results.append({
"start": item["start"],
"end": item["end"],
"speaker": speaker_label,
"text": item["text"]
})
else:
for item in transcript:
results.append({
"start": item["start"],
"end": item["end"],
"speaker": "Speaker 1",
"text": item["text"]
})
os.remove(tmp_file_path)
return {"results": results}
except Exception as e:
print(f"Error processing request: {e}")
raise HTTPException(status_code=500, detail=f"Error processing request: {e}")
Changes in app/main.py:
Model Loading:
The code now loads the three specified WeSpeaker models into a dictionary (wespeaker_models).
Now takes a model_name argument to specify which model to use for embedding extraction.
It checks that the model_name is valid.
/diarize/ Endpoint:
The endpoint now takes a model_name argument as a Form(...) parameter. This ensures that the user must provide the model_name when sending the request.
The extract_embeddings function is called with the given model_name.
How to Use the Updated Application:
Docker Setup: Use the same Dockerfile as provided previously. Build and run the container as before.
Request: You must now pass the model_name in the request body. Here's how to do that with curl:
Replace audio.wav with your audio file and voxceleb_resnet34_LM with your chosen model name (voxblink_100m, voxceleb_resnet34_LM, or voxceleb_resnet293_LM).
Key Improvements:
Model Selection: The API now allows you to select one of the three specified WeSpeaker models for embedding extraction.
Form Data: The model name is passed as form data when sending the request.
Important Notes:
Model Loading: Make sure the model identifiers in the wespeaker_models dictionary in app/main.py match the models you wish to use.
Error Handling: The error handling has been adjusted to account for invalid model names.
Request format: You must now specify the model_name in the request body using multipart form data.
Initial Setup: All the initial setup instructions from my previous response still apply (directory structure, Dockerfile, etc).
This revised solution provides the flexibility of model selection while meeting the requirements of your project. Remember to rebuild your docker image and restart the container whenever you make code changes.
from fastapi import FastAPI, UploadFile, HTTPException
from typing import List, Dict
import os
import tempfile
import torch
import [Redacted Person]
import numpy as np
from faster_whisper import WhisperModel
import wespeaker
from sklearn.preprocessing import normalize
import umap
import hdbscan
import [Redacted Person]
app = FastAPI()
# Initialize WeSpeaker model (choose appropriate model for your needs)
try:
wespeaker_model = wespeaker.load_model('campplus-cn-common-200k') # Or another suitable model
except Exception as e:
print(f"Error loading WeSpeaker model: {e}")
wespeaker_model = None
# Initialize faster-whisper model
try:
whisper_model = WhisperModel("large-v2", device="cuda", compute_type="float16") # You may change this to a different model
except Exception as e:
print(f"Error loading Faster-Whisper model: {e}")
whisper_model = None
def extract_embeddings(audio_path):
if wespeaker_model is None:
raise HTTPException(status_code=500, detail="WeSpeaker model not initialized.")
try:
embeddings = wespeaker_model.extract_embedding(audio_path)
return embeddings
except Exception as e:
print(f"Error extracting embeddings: {e}")
raise HTTPException(status_code=500, detail=f"Error extracting embeddings: {e}")
def transcribe_audio(audio_path):
if whisper_model is None:
raise HTTPException(status_code=500, detail="Whisper model not initialized.")
try:
segments, info = whisper_model.transcribe(audio_path)
transcript = []
for segment in segments:
transcript.append({"start": segment.start, "end": segment.end, "text": segment.text})
return transcript
except Exception as e:
print(f"Error during transcription: {e}")
raise HTTPException(status_code=500, detail=f"Error during transcription: {e}")
def cluster_embeddings(embeddings):
try:
reducer = umap.UMAP(n_components=10) # Reduced to 10 dimensions
embeddings_reduced = reducer.fit_transform(embeddings.reshape(1, -1)) # Reshape to 2D for umap
clusterer = hdbscan.HDBSCAN(min_cluster_size=2, gen_min_span_tree=True)
clusterer.fit(embeddings_reduced)
labels = clusterer.labels_
return labels
except Exception as e:
print(f"Error during clustering: {e}")
raise HTTPException(status_code=500, detail=f"Error during clustering: {e}")
@app.post("/diarize/")
async def diarize(file: UploadFile):
if not file:
raise HTTPException(status_code=400, detail="No file provided.")
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
contents = await file.read()
tmp_file.write(contents)
tmp_file_path = tmp_file.name
# 1. Extract speaker embeddings
embeddings = extract_embeddings(tmp_file_path)
# 2. Cluster speaker embeddings
labels = cluster_embeddings(embeddings)
# 3. Transcribe audio
transcript = transcribe_audio(tmp_file_path)
# 4. Map the transcript to the speakers
results = []
if len(labels) > 0:
speaker_label = f"Speaker {labels[0] + 1}" # get the speaker labels
for item in transcript:
results.append({
"start": item["start"],
"end": item["end"],
"speaker": speaker_label,
"text": item["text"]
})
else:
for item in transcript:
results.append({
"start": item["start"],
"end": item["end"],
"speaker": "Speaker 1",
"text": item["text"]
})
os.remove(tmp_file_path)
return {"results": results}
except Exception as e:
print(f"Error processing request: {e}")
raise HTTPException(status_code=500, detail=f"Error processing request: {e}")