Triển khai chuyển đổi giọng nói thành văn bản với Whisper và FastAPI

Whisper là mô hình nhận dạng giọng nói đa năng được huấn luyện trên tập dữ liệu âm thanh đa dạng. Mô hình transformer sequence-to-sequence này xử lý nhiều tác vụ bao gồm:

  • Nhận dạng giọng nói đa ngôn ngữ
  • Dịch giọng nói
  • Nhận diện ngôn ngữ
  • Phát hiện hoạt động giọng nói

Cài đặt phụ thuộc

fastapi==0.112.1
uvicorn==0.30.6
git+https://github.com/openai/whisper.git@v20231117
setuptools-rust==1.9.0
numpy==1.26.4
opencc-python-reimplemented==1.1.9
torch==2.4.0

Cài đặt FFmpeg

# Ubuntu/Debian
sudo apt install ffmpeg -y

# Arch Linux
sudo pacman -S ffmpeg

# macOS (Homebrew)
brew install ffmpeg

# Windows (Chocolatey)
choco install ffmpeg

# Windows (Scoop)
scoop install ffmpeg

Triển khai dịch vụ API

import socket
import uvicorn
import whisper
import torch
import logging
import os
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse
from tempfile import TemporaryDirectory
from opencc import OpenCC
from typing import List

# Cấu hình logging
logging.basicConfig(level=logging.INFO, 
                    format='%(asctime)s - %(levelname)s - %(message)s')

# Thiết lập thiết bị
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
asr_model = whisper.load_model("base", device=DEVICE)
text_converter = OpenCC("t2s")

app = FastAPI()

def fetch_local_ip():
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
            s.connect(("8.8.8.8", 80))
            return s.getsockname()[0]
    except Exception as e:
        logging.error(f"Lỗi xác định IP: {e}")
        return "127.0.0.1"

@app.post("/transcribe/")
async def transcribe_audio(files: List[UploadFile] = File(...)):
    if not files:
        raise HTTPException(status_code=400, detail="Thiếu tệp đầu vào")
    
    transcriptions = []
    
    with TemporaryDirectory() as tmpdir:
        for audio_file in files:
            file_path = os.path.join(tmpdir, audio_file.filename)
            
            with open(file_path, "wb") as f:
                f.write(await audio_file.read())
            
            result = asr_model.transcribe(file_path)
            simplified_text = text_converter.convert(result["text"])
            
            transcriptions.append({
                "filename": audio_file.filename,
                "text": simplified_text
            })
    
    return JSONResponse(content={"transcriptions": transcriptions})

if __name__ == "__main__":
    host_ip = fetch_local_ip()
    uvicorn.run(app, host=host_ip, port=8080)

Tính năng chính

  • Xử lý đồng thời nhiều tệp âm thanh
  • Tự động chuyển đổi phồn thể sang giản thể
  • Hỗ trợ GPU để tăng tốc xử lý
  • Truy cập tài liệu API qua /docs

Ghi chú mô hình

Các mô hình .en (tiny.en, base.en) cho kết quả tối ưu với tiếng Anh. Phiên bản turbo cải thiện tốc độ xử lý với độ chính xác gần tương đương large-v3.

Thẻ: whisper FastAPI Speech-Recognition opencc python-api

Đăng vào ngày 29 tháng 5 lúc 22:30