- Remove dead code: cache.py, context_managers.py, decorators.py, flask-limiter - Replace AudioSource ABC + FakeFile (5 classes) with 4 plain functions - Replace TempFileManager class with create_temp_file/cleanup_temp_files functions - Simplify RequestLogger from 233 to 65 lines, remove file reading side-effect - Convert HistoryLogger and AudioUtils classes to module-level functions - Remove unused speed_up_audio and audio_speed_factor config - Flatten single-file directories: shared/, api/, storage/, validation/, async_tasks/, logging/ - Merge logging config + request_logger into single infrastructure/log.py - Fix request_logging config key (was request_logger) - Trim CLAUDE.md to high-level only Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
92 lines
3.8 KiB
Python
92 lines
3.8 KiB
Python
"""
|
|
Модуль transcription_service.py содержит класс TranscriptionService,
|
|
который отвечает за транскрибацию аудиофайлов.
|
|
"""
|
|
|
|
import os
|
|
import time
|
|
import traceback
|
|
from typing import Dict, Tuple
|
|
import logging
|
|
|
|
from ..audio.utils import get_audio_duration
|
|
from ..history import save_history
|
|
|
|
logger = logging.getLogger('app.transcription_service')
|
|
|
|
|
|
class TranscriptionService:
|
|
"""Сервис для транскрибации аудиофайлов."""
|
|
|
|
def __init__(self, transcriber, config: Dict):
|
|
self.transcriber = transcriber
|
|
self.config = config
|
|
|
|
def transcribe(self, file_path: str, filename: str, params: Dict = None) -> Tuple[Dict, int]:
|
|
"""
|
|
Транскрибирует аудиофайл по пути.
|
|
|
|
Args:
|
|
file_path: Путь к аудиофайлу.
|
|
filename: Имя файла (для логов и истории).
|
|
params: Дополнительные параметры для транскрибации.
|
|
|
|
Returns:
|
|
Кортеж (JSON-ответ, HTTP-код).
|
|
"""
|
|
params = params or {}
|
|
language = params.get('language', self.config.get('language', 'en'))
|
|
temperature = float(params.get('temperature', 0.0))
|
|
prompt = params.get('prompt', '')
|
|
|
|
# Проверяем, запрошены ли временные метки
|
|
return_timestamps = params.get('return_timestamps', self.config.get('return_timestamps', False))
|
|
if isinstance(return_timestamps, str):
|
|
return_timestamps = return_timestamps.lower() in ('true', 't', 'yes', 'y', '1')
|
|
|
|
# Временно изменяем настройку return_timestamps в транскрайбере
|
|
original_return_timestamps = self.transcriber.return_timestamps
|
|
self.transcriber.return_timestamps = return_timestamps
|
|
|
|
try:
|
|
# Определяем длительность аудиофайла
|
|
try:
|
|
duration = get_audio_duration(file_path)
|
|
except Exception as e:
|
|
logger.error(f"Ошибка при определении длительности файла: {e}")
|
|
return {"error": f"Не удалось определить длительность аудиофайла: {e}"}, 500
|
|
|
|
start_time = time.time()
|
|
result = self.transcriber.process_file(file_path)
|
|
processing_time = time.time() - start_time
|
|
|
|
# Формируем ответ
|
|
if return_timestamps:
|
|
response = {
|
|
"segments": result.get("segments", []),
|
|
"text": result.get("text", ""),
|
|
"processing_time": processing_time,
|
|
"response_size_bytes": len(str(result).encode('utf-8')),
|
|
"duration_seconds": duration,
|
|
"model": os.path.basename(self.config["model_path"])
|
|
}
|
|
else:
|
|
response = {
|
|
"text": result,
|
|
"processing_time": processing_time,
|
|
"response_size_bytes": len(str(result).encode('utf-8')),
|
|
"duration_seconds": duration,
|
|
"model": os.path.basename(self.config["model_path"])
|
|
}
|
|
|
|
save_history(response, filename, self.config)
|
|
return response, 200
|
|
|
|
except Exception as e:
|
|
logger.error(f"Ошибка при транскрибации файла '{filename}': {str(e)}")
|
|
logger.error(f"Traceback: {traceback.format_exc()}")
|
|
return {"error": str(e)}, 500
|
|
|
|
finally:
|
|
self.transcriber.return_timestamps = original_return_timestamps
|