Fix code review issues: security, race conditions, resource leaks

- Fix race condition: pass return_timestamps as parameter instead of mutating shared state
- Remove /local/transcriptions endpoint (path traversal vulnerability)
- Add timeout=30 and URL scheme validation to prevent SSRF
- Add temp file cleanup via try/finally in all route handlers
- AsyncTaskManager: add threading.Lock and TTL cleanup for completed tasks
- Change audio_rate to 16000 (matches Whisper's expected sample rate)
- Extract filename from URL via Content-Disposition/path
- Detect base64 audio format via python-magic
- Fix response_size_bytes to use json.dumps instead of str()
- Move scipy import to module level
- Clamp temperature to [0.0, 1.0]
- Deduplicate _load_model() code
- Fix docstrings, README structure, typo, log level

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Serge Zaigraeff
2026-03-30 00:54:50 +03:00
co-authored by Claude Opus 4.6
parent ff4bd2ba3d
commit 2138651474
12 changed files with 153 additions and 189 deletions
+5 -11
View File
@@ -3,6 +3,7 @@
который отвечает за транскрибацию аудиофайлов.
"""
import json
import os
import time
import traceback
@@ -36,7 +37,7 @@ class TranscriptionService:
"""
params = params or {}
language = params.get('language', self.config.get('language', 'en'))
temperature = float(params.get('temperature', 0.0))
temperature = max(0.0, min(1.0, float(params.get('temperature', 0.0))))
prompt = params.get('prompt', '')
# Проверяем, запрошены ли временные метки
@@ -44,10 +45,6 @@ class TranscriptionService:
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:
@@ -57,7 +54,7 @@ class TranscriptionService:
return {"error": f"Не удалось определить длительность аудиофайла: {e}"}, 500
start_time = time.time()
result = self.transcriber.process_file(file_path)
result = self.transcriber.process_file(file_path, return_timestamps=return_timestamps)
processing_time = time.time() - start_time
# Формируем ответ
@@ -66,7 +63,7 @@ class TranscriptionService:
"segments": result.get("segments", []),
"text": result.get("text", ""),
"processing_time": processing_time,
"response_size_bytes": len(str(result).encode('utf-8')),
"response_size_bytes": len(json.dumps(result, ensure_ascii=False).encode('utf-8')),
"duration_seconds": duration,
"model": os.path.basename(self.config["model_path"])
}
@@ -74,7 +71,7 @@ class TranscriptionService:
response = {
"text": result,
"processing_time": processing_time,
"response_size_bytes": len(str(result).encode('utf-8')),
"response_size_bytes": len(json.dumps(result, ensure_ascii=False).encode('utf-8')),
"duration_seconds": duration,
"model": os.path.basename(self.config["model_path"])
}
@@ -86,6 +83,3 @@ class TranscriptionService:
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