Add model auto-download and English logging

This commit is contained in:
Dymas
2026-06-06 12:47:59 +02:00
parent d8b92d5025
commit 0c7f93d067
17 changed files with 204 additions and 77 deletions
+3 -3
View File
@@ -93,14 +93,14 @@ class AsyncTaskManager:
self.tasks[task_id]["result"] = result
self.tasks[task_id]["completed_at"] = time.time()
logger.info("Задача %s завершена успешно", task_id)
logger.info("Task %s completed successfully", task_id)
except Exception as e:
with self._lock:
self.tasks[task_id]["status"] = "failed"
self.tasks[task_id]["error"] = str(e)
self.tasks[task_id]["completed_at"] = time.time()
logger.error("Задача %s завершилась с ошибкой: %s", task_id, e)
logger.error("Task %s failed: %s", task_id, e)
def get_task_status(self, task_id: str) -> Optional[Dict[str, Any]]:
"""
@@ -147,4 +147,4 @@ def transcribe_audio_async(file_path: str, transcription_service, params: Dict =
params = params or {}
def _transcribe():
return transcription_service.transcribe(file_path, "async_task", params)
return task_manager.run_task(_transcribe)
return task_manager.run_task(_transcribe)
+2 -2
View File
@@ -91,7 +91,7 @@ class RequestLogger:
return
g.start_time = time.time()
self.logger.info(
"%s %s от %s",
"%s %s from %s",
request.method, request.path, self._get_client_ip(),
extra={"type": "request"}
)
@@ -101,7 +101,7 @@ class RequestLogger:
return response
processing_time = time.time() - getattr(g, 'start_time', time.time())
self.logger.info(
"%s за %.3f сек",
"%s in %.3f sec",
response.status_code, processing_time,
extra={"type": "response"}
)
+3 -3
View File
@@ -21,7 +21,7 @@ def create_temp_file(suffix: str = ".wav") -> str:
"""
fd, temp_path = tempfile.mkstemp(suffix=suffix)
os.close(fd)
logger.debug("Создан временный файл: %s", temp_path)
logger.debug("Created temporary file: %s", temp_path)
return temp_path
@@ -36,6 +36,6 @@ def cleanup_temp_files(file_paths: list) -> None:
try:
if os.path.exists(path):
os.remove(path)
logger.debug("Удалён временный файл: %s", path)
logger.debug("Removed temporary file: %s", path)
except Exception as e:
logger.warning("Не удалось очистить временный файл %s: %s", path, e)
logger.warning("Failed to clean up temporary file %s: %s", path, e)
+9 -9
View File
@@ -51,11 +51,11 @@ class FileValidator:
if not any(filename.lower().endswith(ext.lower()) for ext in self.allowed_extensions):
# Логирование попытки загрузки файла с неразрешенным расширением
file_extension = os.path.splitext(filename)[1]
logger.warning("Попытка загрузки файла с неразрешенным расширением '%s'. "
"Имя файла: %s. Разрешенные расширения: %s", file_extension, filename, ", ".join(self.allowed_extensions))
logger.warning("Attempt to upload a file with disallowed extension '%s'. "
"Filename: %s. Allowed extensions: %s", file_extension, filename, ", ".join(self.allowed_extensions))
raise ValidationError(f"Расширение файла не разрешено. "
f"Разрешенные расширения: {', '.join(self.allowed_extensions)}")
raise ValidationError(f"File extension is not allowed. "
f"Allowed extensions: {', '.join(self.allowed_extensions)}")
def validate_file_by_path(self, file_path: str, filename: str) -> bool:
"""
@@ -78,18 +78,18 @@ class FileValidator:
file_size = os.path.getsize(file_path)
max_size_bytes = self.max_file_size_mb * 1024 * 1024
if file_size > max_size_bytes:
raise ValidationError(f"Размер файла ({file_size / (1024*1024):.2f} МБ) "
f"превышает максимально допустимый ({self.max_file_size_mb} МБ)")
raise ValidationError(f"File size ({file_size / (1024*1024):.2f} MB) "
f"exceeds the maximum allowed size ({self.max_file_size_mb} MB)")
# Проверка MIME-типа
try:
mime_type = magic.from_file(file_path, mime=True)
if mime_type not in self.allowed_mime_types:
raise ValidationError(f"MIME-тип файла ({mime_type}) не разрешен. "
f"Разрешенные MIME-типы: {', '.join(self.allowed_mime_types)}")
raise ValidationError(f"File MIME type ({mime_type}) is not allowed. "
f"Allowed MIME types: {', '.join(self.allowed_mime_types)}")
except ValidationError:
raise
except Exception as e:
logger.warning("Не удалось определить MIME-тип файла: %s", e)
logger.warning("Failed to determine file MIME type: %s", e)
return True