add description

This commit is contained in:
Serge Zaigraeff
2025-03-02 12:35:37 +03:00
parent 5af6225c51
commit eed8dd2813
2 changed files with 259 additions and 50 deletions
+76
View File
@@ -0,0 +1,76 @@
# Структура проекта Whisper API Service
Проект представляет собой локальный API-сервис для распознавания речи, построенный на основе модели Whisper. Сервис разработан как OpenAI-совместимый API, что позволяет использовать его в качестве локальной альтернативы облачным сервисам распознавания речи.
## Основные файлы
### Корневые файлы
- **server.py** - точка входа в приложение, инициализирует и запускает сервис
- **server.sh** - bash-скрипт для запуска сервера с опциональным обновлением conda-окружения
- **config.json** - конфигурационный файл с настройками сервиса
- **requirements.txt** - зависимости проекта для conda/pip
### Модуль `app`
#### app/\_\_init\_\_.py
Содержит основной класс `WhisperServiceAPI`, который инициализирует приложение, загружает конфигурацию и запускает сервер на указанном порту.
#### app/logger.py
Настройка логирования для всех компонентов приложения.
#### app/transcriber.py
Содержит класс `WhisperTranscriber`, который загружает модель Whisper и выполняет распознавание речи. Класс определяет оптимальное устройство для вычислений (CPU, CUDA, MPS) и поддерживает ускорение с помощью Flash Attention 2.
#### app/audio_processor.py
Содержит класс `AudioProcessor` для предобработки аудиофайлов перед их транскрибацией. Включает методы для:
- Конвертации в WAV с частотой 16 кГц
- Нормализации уровня громкости
- Добавления тишины в начало записи
- Очистки временных файлов
#### app/audio_sources.py
Содержит абстрактный класс `AudioSource` и его конкретные реализации для различных источников аудио:
- `UploadedFileSource` - для файлов, загруженных через HTTP-запрос
- `URLSource` - для файлов, доступных по URL
- `Base64Source` - для аудио, закодированного в base64
- `LocalFileSource` - для локальных файлов на сервере
- `FakeFile` - вспомогательный класс для унификации обработки из разных источников
#### app/routes.py
Содержит классы:
- `TranscriptionService` - сервис для обработки и транскрибации аудиофайлов
- `Routes` - регистрирует все эндпоинты API, включая OpenAI-совместимые маршруты
## Основные классы и их описание
### WhisperServiceAPI
Основной класс приложения, инициализирует сервис, загружает конфигурацию и запускает сервер с использованием Waitress.
### WhisperTranscriber
Класс для распознавания речи с использованием модели Whisper. Определяет оптимальное устройство для вычислений, загружает модель с учетом доступного оборудования и выполняет транскрибацию аудиофайлов.
### AudioProcessor
Класс для предобработки аудиофайлов. Выполняет конвертацию, нормализацию и добавление тишины в начало записи для улучшения качества распознавания.
### AudioSource (и наследники)
Абстрактный класс и его реализации для работы с различными источниками аудиофайлов. Обеспечивает унифицированный интерфейс для получения аудиофайлов из разных источников.
### TranscriptionService
Сервис, объединяющий логику обработки запросов и транскрибации аудио. Принимает источник аудио, обрабатывает его и возвращает результат транскрибации.
### Routes
Класс, регистрирующий все маршруты API сервиса, включая совместимые с OpenAI эндпоинты для интеграции с существующими клиентами.
## API Endpoints
Сервис предоставляет несколько эндпоинтов, включая:
- `/health` - проверка статуса сервиса
- `/config` - получение текущей конфигурации
- `/local/transcriptions` - транскрибация локального файла на сервере
- `/v1/models` - получение списка доступных моделей (OpenAI-совместимый)
- `/v1/audio/transcriptions` - транскрибация загруженного файла (OpenAI-совместимый)
- `/v1/audio/transcriptions/url` - транскрибация по URL
- `/v1/audio/transcriptions/base64` - транскрибация из base64
- `/v1/audio/transcriptions/multipart` - транскрибация файла из multipart-формы
Сервис разработан таким образом, чтобы обеспечить максимальную гибкость в использовании и интеграцию с существующими системами, поддерживающими API OpenAI Whisper.
+183 -50
View File
@@ -1,62 +1,195 @@
# Whisper Speech-to-Text API Service
# Whisper API Service
## Overview
This project is a lightweight, OpenAI-compatible API server for transcribing audio to text using the Whisper model. It's designed to run locally, making it easy to set up and use for speech-to-text tasks.
A local, OpenAI-compatible speech recognition API service using the Whisper model. This service provides a straightforward way to transcribe audio files in various formats with high accuracy and is designed to be compatible with the OpenAI Whisper API.
## Features
- **OpenAI API Compatibility**: Fully compatible with OpenAI's `/v1/audio/transcriptions` and `/v1/models` endpoints.
- **Local File Support**: Transcribe audio files stored locally on your machine.
- **Multiple Input Methods**: Supports:
- Local file paths
- Files accessible via URL
- Base64-encoded audio
- Multipart form uploads
- **Easy Setup**: Designed to run as a local service with minimal configuration.
- **Hardware Optimization**: Utilizes GPU (CUDA, MPS) or CPU for efficient processing.
- **Health Check**: Includes a `/health` endpoint for service monitoring.
- 🔊 High-quality speech recognition using Whisper model
- 🌐 OpenAI-compatible API endpoints
- 🚀 Hardware acceleration support (CUDA, MPS)
- ⚡ Flash Attention 2 for faster transcription on compatible GPUs
- 🎛️ Audio preprocessing for better transcription results
- 🔄 Multiple input formats (file upload, URL, base64, local files)
- 🚪 Easy deployment with Docker or conda environment
## Recommended Model
## Requirements
For Russian language transcription, we recommend using the [**whisper-large-v3-russian**](https://huggingface.co/antony66/whisper-large-v3-russian) model from Hugging Face. This model is fine-tuned specifically for Russian speech recognition and delivers high accuracy. For faster transcription with slightly lower accuracy, consider the [**whisper-large-v3-turbo-russian**](https://huggingface.co/dvislobokov/whisper-large-v3-turbo-russian) model, which is optimized for speed.
- Python 3.10+ (3.11 recommended)
- CUDA-compatible GPU (optional, for faster processing)
- FFmpeg and SoX for audio processing
Perfect for local development or offline use cases where OpenAI's API isn't accessible.
## Installation
## Quick Start
### Using conda (recommended)
1. **Edit the Configuration File (`config.json`)**:
- Set the path to your Whisper model (`model_path`).
- Configure other parameters like language (`language`), chunk size (`chunk_length_s`), batch size (`batch_size`), and audio normalization settings.
```json
{
"service_port": 5042,
"model_path": "/path/to/your/whisper-model",
"language": "english",
"chunk_length_s": 30,
"batch_size": 16,
"max_new_tokens": 256,
"return_timestamps": false,
"norm_level": "-0.5",
"compand_params": "0.3,1 -90,-90,-70,-70,-60,-20,0,0 -5 0 0.2"
}
```
1. Clone the repository:
```bash
git clone https://github.com/yourusername/whisper-api-service.git
cd whisper-api-service
```
2. **Run the Server**:
- Simply execute the `server.sh` script:
```bash
./server.sh
```
- If you need to update the environment, use:
```bash
./server.sh --update
```
2. Run the server script with the update flag to create and set up the conda environment:
```bash
chmod +x server.sh
./server.sh --update
```
3. **Use the API**:
- Once the server is running, you can send transcription requests.
- Example request (curl):
```bash
curl -X POST -F file=@audio.mp3 http://localhost:5042/v1/audio/transcriptions | jq -r '.text'
```
This will:
- Create a conda environment named "transcribe" with Python 3.11
- Install all required dependencies
- Start the service
Enjoy seamless audio-to-text transcription with your local Whisper API server!
### Manual Installation
1. Create and activate a conda environment:
```bash
conda create -n transcribe python=3.11
conda activate transcribe
```
2. Install the required dependencies:
```bash
pip install -r requirements.txt
```
3. Start the service:
```bash
python server.py
```
## Configuration
The service is configured through the `config.json` file:
```json
{
"service_port": 5042,
"model_path": "/mnt/cloud/llm/whisper/whisper-large-v3-russian",
"language": "russian",
"chunk_length_s": 30,
"batch_size": 16,
"max_new_tokens": 256,
"return_timestamps": false,
"norm_level": "-0.5",
"compand_params": "0.3,1 -90,-90,-70,-70,-60,-20,0,0 -5 0 0.2"
}
```
### Configuration Parameters
| Parameter | Description |
|-----------|-------------|
| `service_port` | Port on which the service will run |
| `model_path` | Path to the Whisper model directory |
| `language` | Language for transcription (e.g., "russian", "english") |
| `chunk_length_s` | Length of audio chunks for processing (in seconds) |
| `batch_size` | Batch size for processing |
| `max_new_tokens` | Maximum new tokens for the model output |
| `return_timestamps` | Whether to return timestamps in the transcription |
| `norm_level` | Normalization level for audio preprocessing |
| `compand_params` | Parameters for audio compression/expansion |
## API Usage
### Health Check
```bash
curl http://localhost:5042/health
```
### Get Configuration
```bash
curl http://localhost:5042/config
```
### Transcribe an Audio File (OpenAI-compatible)
```bash
curl -X POST http://localhost:5042/v1/audio/transcriptions \
-F file=@audio.mp3
```
### Transcribe from URL
```bash
curl -X POST http://localhost:5042/v1/audio/transcriptions/url \
-H "Content-Type: application/json" \
-d '{"url":"https://example.com/audio.mp3"}'
```
### Transcribe from Base64
```bash
curl -X POST http://localhost:5042/v1/audio/transcriptions/base64 \
-H "Content-Type: application/json" \
-d '{"file":"base64_encoded_audio_data"}'
```
### Transcribe a Local File on the Server
```bash
curl -X POST http://localhost:5042/local/transcriptions \
-H "Content-Type: application/json" \
-d '{"file_path":"/path/to/audio.mp3"}'
```
## Project Structure
The project consists of the following components:
- `server.py`: Entry point that initializes and starts the service
- `server.sh`: Bash script for launching the server with optional conda environment update
- `config.json`: Service configuration file
- `requirements.txt`: Project dependencies for conda/pip
- `app/`: Main application module
- `__init__.py`: Contains the `WhisperServiceAPI` class for service initialization
- `logger.py`: Logging configuration
- `transcriber.py`: Contains the `WhisperTranscriber` class for speech recognition
- `audio_processor.py`: Contains the `AudioProcessor` class for audio preprocessing
- `audio_sources.py`: Contains the `AudioSource` abstract class and implementations
- `routes.py`: Contains the API route definitions
## Advanced Usage
### Using with Different Models
You can use any Whisper model by changing the `model_path` in the configuration:
1. Download a model from Hugging Face (e.g., `openai/whisper-large-v3`)
2. Update the `model_path` in `config.json`
3. Restart the service
### Hardware Acceleration
The service automatically selects the best available compute device:
- CUDA GPU (index 1 if available, otherwise index 0)
- Apple Silicon MPS (for Mac with M1/M2/M3 chips)
- CPU (fallback)
For best performance on NVIDIA GPUs, Flash Attention 2 is used when available.
## Troubleshooting
### Audio Processing Issues
If you encounter audio processing errors:
- Ensure that FFmpeg and SoX are installed on your system
- Check that the audio file is not corrupted
- Try different audio preprocessing parameters in the configuration
### Performance Issues
For slow transcription:
- Use a GPU if available
- Adjust `chunk_length_s` and `batch_size` parameters
- Consider using a smaller Whisper model
## License
[MIT License](LICENSE)
## Acknowledgements
- OpenAI for the Whisper model
- Hugging Face for model distribution and transformers library