# app/api/schemas/diarization.py
from pydantic import BaseModel, Field
from typing import Optional
class DiarizationRequest(BaseModel):
language: Optional[str] = Field(None, description="Language code (e.g., 'en', 'fr')")
model_name: str = Field("medium.en", description="Whisper model name")
batch_size: int = Field(8, description="Batch size for processing")
suppress_numerals: bool = Field(False, description="Whether to suppress numerical digits")
no_stem: bool = Field(False, description="Disable source separation")
class DiarizationResponse(BaseModel):
transcript_path: str
srt_path: str
message: str
Создадим сервисный слой:
python
# app/services/diarization.py
import os
from typing import Optional, Tuple
import torch
from faster_whisper import WhisperModel
from ..core.config import settings
from ..utils.helpers import cleanup, create_config
class DiarizationService:
def __init__(self):
self.device = "cuda" if torch.cuda.is_available() else "cpu"
async def process_audio(
self,
file_path: str,
language: Optional[str] = None,
model_name: str = settings.DEFAULT_WHISPER_MODEL,
batch_size: int = settings.DEFAULT_BATCH_SIZE,
suppress_numerals: bool = False,
no_stem: bool = True,
) -> Tuple[str, str]:
try:
# Process audio using existing diarization logic
from diarize import main
args = [
"-a", file_path,
"--whisper-[Redacted Person]", model_name,
"--batch-size", str(batch_size),
"--device", self.device
]
if language:
args.extend(["--language", language])
if suppress_numerals:
args.append("--suppress_numerals")
if no_stem:
args.append("--no-stem")
main(args)
# Get output paths
base_name = os.path.splitext(file_path)[0]
transcript_path = f"{base_name}.txt"
srt_path = f"{base_name}.srt"
return transcript_path, srt_path
except Exception as e:
cleanup(os.path.join(settings.UPLOAD_DIR, "temp_outputs"))
raise Exception(f"Diarization failed: {str(e)}")
Создадим роутеры:
python
# app/api/routes/diarization.py
from typing import Optional
from litestar import post, get
from litestar.datastructures import UploadFile
from litestar.enums import RequestEncodingType
from litestar.status_codes import HTTP_200_OK
import os
import tempfile
from ...core.config import settings
from ...services.diarization import DiarizationService
from ..schemas.diarization import DiarizationRequest, DiarizationResponse
@post("/diarize", status_code=HTTP_200_OK)
async def diarize_audio(
data: Optional[DiarizationRequest] = None,
file: UploadFile = None,
) -> DiarizationResponse:
if not file:
raise ValueError("No audio file provided")
# Create service instance
diarization_service = DiarizationService()
# Create temp directory for processing
with tempfile.TemporaryDirectory() as temp_dir:
# Save uploaded file
file_path = os.path.join(temp_dir, file.filename)
with open(file_path, "wb") as f:
f.write(await file.read())
# Process audio
transcript_path, srt_path = await diarization_service.process_audio(
file_path=file_path,
language=data.language if data else None,
model_name=data.model_name if data else settings.DEFAULT_WHISPER_MODEL,
batch_size=data.batch_size if data else settings.DEFAULT_BATCH_SIZE,
suppress_numerals=data.suppress_numerals if data else False,
no_stem=data.no_stem if data else False,
)
return DiarizationResponse(
transcript_path=transcript_path,
srt_path=srt_path,
message="Diarization completed successfully"
)
Создадим главный файл приложения:
python
# main.py
from litestar import Litestar
from app.api.routes.diarization import diarize_audio
from app.core.config import settings
app = Litestar(
route_handlers=[diarize_audio],
debug=settings.DEBUG
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"main:app",
host="[Redacted IPAddress]",
port=8000,
reload=settings.DEBUG
)
Dockerfile:
dockerfile
FROM nvidia/cuda:12.1.0-runtime-ubuntu22.04
# Set working directory
WORKDIR /app
# Install system dependencies
RUN apt-get update && apt-get install -y \
python3.10 \
python3-pip \
ffmpeg \
&& rm -rf /var/lib/apt/lists/*
# Copy requirements files
COPY requirements.txt constraints.txt ./
# Install Python dependencies
RUN pip3 install --
Продолжаю создание проекта:
Полный Dockerfile:
dockerfile
FROM nvidia/cuda:12.1.0-runtime-ubuntu22.04
# Set working directory
WORKDIR /app
# Install system dependencies
RUN apt-get update && apt-get install -y \
python3.10 \
python3-pip \
ffmpeg \
git \
&& rm -rf /var/lib/apt/lists/*
# Copy requirements files
COPY requirements.txt constraints.txt ./
# Install Python dependencies
RUN pip3 install --no-cache-dir cython
RUN pip3 install --no-cache-dir torch torchaudio --index-url https://download.pytorch.org/whl/cu121
RUN pip3 install --no-cache-dir -c constraints.txt -r requirements.txt
# Install additional dependencies for API
RUN pip3 install --no-cache-dir litestar uvicorn[standard] pydantic-settings python-multipart
# Copy application code
COPY . .
# Create directories for uploads and outputs
RUN mkdir -p uploads outputs
# Expose port
EXPOSE 8000
# Set environment variable for CUDA
ENV CUDA_VISIBLE_DEVICES=0
# Run the API server
CMD ["uvicorn", "main:app", "--host", "[Redacted IPAddress]", "--port", "8000"]
# app/core/logging.py
import logging
from logging.handlers import RotatingFileHandler
import os
def setup_logger(name: str, log_file: str, level=logging.INFO):
"""Function to setup as many loggers as you want"""
formatter = logging.Formatter(
'%(asctime)s %(levelname)s %(module)s - %(funcName)s: %(message)s'
)
handler = RotatingFileHandler(
log_file, maxBytes=[Redacted PhoneNumber], backupCount=5
)
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
return logger
# Create logs directory if it doesn't exist
os.makedirs("logs", exist_ok=True)
# Setup loggers
api_logger = setup_logger('api', 'logs/api.log')
diarization_logger = setup_logger('diarization', 'logs/diarization.log')
Дополним утилиты:
python
# app/utils/helpers.py
import os
import shutil
from typing import List
from ..core.logging import diarization_logger
def save_uploaded_file(upload_file, upload_dir: str) -> str:
"""Save uploaded file and return the path"""
os.makedirs(upload_dir, exist_ok=True)
file_path = os.path.join(upload_dir, upload_file.filename)
with open(file_path, "wb") as buffer:
shutil.copyfileobj(upload_file.file, buffer)
return file_path
def cleanup_files(files: List[str]):
"""Clean up temporary files"""
for file in files:
try:
if os.path.exists(file):
os.remove(file)
except Exception as e:
diarization_logger.error(f"Error cleaning up file {file}: {str(e)}")
def validate_audio_file(filename: str) -> bool:
"""Validate audio file extension"""
valid_extensions = {'.wav', '.mp3', '.ogg', '.opus', '.m4a', '.flac'}
return os.path.splitext(filename)[1].lower() in valid_extensions
Создадим тесты:
python
# tests/test_diarization.py
import pytest
from httpx import AsyncClient
from pathlib import Path
import os
from app.core.config import settings
from main import app
@pytest.mark.asyncio
async def test_diarize_endpoint():
test_file = Path(__file__).parent / "assets" / "test.opus"
async with AsyncClient(app=app, base_url="http://test") as client:
files = {"file": ("test.opus", open(test_file, "rb"))}
data = {
"language": "en",
"model_name": "[Redacted Person]",
"batch_size": 4,
"suppress_numerals": False,
"no_stem": True
}
response = await client.post("/diarize", files=files, data=data)
assert response.status_code == 200
assert "transcript_path" in response.json()
assert "srt_path" in response.json()
@pytest.mark.asyncio
async def test_diarize_no_file():
async with AsyncClient(app=app, base_url="http://test") as client:
response = await client.post("/diarize")
assert response.status_code == 400
Обновим README.md:
markdown
# Whisper Diarization API
REST API for speaker diarization using OpenAI Whisper.
## Features
- Audio file upload and processing
- Speaker diarization with Whisper
- Multiple output formats (TXT, SRT)
- GPU support
- Docker deployment
- Configurable parameters
## Installation
### Using Docker
```bash
# Build and run with docker-compose
docker-compose up --build
# Or build and run manually
docker build -t whisper-diarization-api .
docker run --gpus all -p 8000:8000 whisper-diarization-api
Local Installation
bash
# Create virtual environment
python -m venv venv
source venv/bin/activate # Linux/Mac
venv\Scripts\activate # Windows
# Install dependencies
pip install -r requirements.txt
# Run the application
uvicorn main:app --reload