551 lines
18 KiB
Python
551 lines
18 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import logging
|
|
import sqlite3
|
|
import uuid
|
|
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
import httpx
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class TranscriptionQueue:
|
|
def __init__(
|
|
self,
|
|
data_dir: Path,
|
|
speaches_url: str,
|
|
llama_url: str,
|
|
model: str,
|
|
max_upload_bytes: int,
|
|
allowed_extensions: set[str],
|
|
):
|
|
self.data_dir = Path(data_dir)
|
|
self.upload_dir = self.data_dir / "uploads"
|
|
self.db_path = self.data_dir / "queue.sqlite3"
|
|
|
|
self.speaches_url = speaches_url.rstrip("/")
|
|
self.llama_url = llama_url.rstrip("/")
|
|
self.model = model
|
|
self.max_upload_bytes = max_upload_bytes
|
|
self.allowed_extensions = allowed_extensions
|
|
|
|
self.queue: asyncio.Queue[str] = asyncio.Queue()
|
|
self.worker_task: asyncio.Task | None = None
|
|
self.running = False
|
|
|
|
def _connect(self):
|
|
connection = sqlite3.connect(self.db_path, timeout=30)
|
|
connection.row_factory = sqlite3.Row
|
|
return connection
|
|
|
|
@staticmethod
|
|
def _now():
|
|
return datetime.now(timezone.utc).isoformat()
|
|
|
|
def initialize(self):
|
|
self.upload_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
with self._connect() as db:
|
|
db.execute("""
|
|
CREATE TABLE IF NOT EXISTS transcription_jobs (
|
|
id TEXT PRIMARY KEY,
|
|
filename TEXT NOT NULL,
|
|
language TEXT NOT NULL,
|
|
status TEXT NOT NULL,
|
|
created_at TEXT NOT NULL,
|
|
started_at TEXT,
|
|
finished_at TEXT,
|
|
error TEXT,
|
|
result_json TEXT
|
|
)
|
|
""")
|
|
|
|
# Миграция существующей таблицы без потери записей.
|
|
columns = {
|
|
row["name"]
|
|
for row in db.execute("PRAGMA table_info(transcription_jobs)")
|
|
}
|
|
|
|
migrations = {
|
|
"title": "ALTER TABLE transcription_jobs ADD COLUMN title TEXT",
|
|
"description": "ALTER TABLE transcription_jobs ADD COLUMN description TEXT NOT NULL DEFAULT ''",
|
|
"tags_json": "ALTER TABLE transcription_jobs ADD COLUMN tags_json TEXT NOT NULL DEFAULT '[]'",
|
|
"duration": "ALTER TABLE transcription_jobs ADD COLUMN duration REAL",
|
|
"detected_language": "ALTER TABLE transcription_jobs ADD COLUMN detected_language TEXT",
|
|
}
|
|
|
|
for name, sql in migrations.items():
|
|
if name not in columns:
|
|
db.execute(sql)
|
|
|
|
db.execute("""
|
|
UPDATE transcription_jobs
|
|
SET title = filename
|
|
WHERE title IS NULL OR title = ''
|
|
""")
|
|
|
|
db.execute("""
|
|
CREATE INDEX IF NOT EXISTS idx_transcription_status_created
|
|
ON transcription_jobs(status, created_at)
|
|
""")
|
|
|
|
# Незавершённые задания возвращаем в очередь.
|
|
db.execute("""
|
|
UPDATE transcription_jobs
|
|
SET status = 'queued', started_at = NULL
|
|
WHERE status = 'processing'
|
|
""")
|
|
|
|
db.commit()
|
|
|
|
async def start(self):
|
|
if self.running:
|
|
return
|
|
|
|
self.initialize()
|
|
self.running = True
|
|
|
|
with self._connect() as db:
|
|
rows = db.execute("""
|
|
SELECT id FROM transcription_jobs
|
|
WHERE status = 'queued'
|
|
ORDER BY created_at
|
|
""").fetchall()
|
|
|
|
for row in rows:
|
|
self.queue.put_nowait(row["id"])
|
|
|
|
self.worker_task = asyncio.create_task(
|
|
self._worker(),
|
|
name="transcription-queue-worker",
|
|
)
|
|
|
|
logger.info("Transcription queue started: %s pending jobs", len(rows))
|
|
|
|
async def stop(self):
|
|
self.running = False
|
|
|
|
if self.worker_task:
|
|
self.worker_task.cancel()
|
|
try:
|
|
await self.worker_task
|
|
except asyncio.CancelledError:
|
|
pass
|
|
self.worker_task = None
|
|
|
|
logger.info("Transcription queue stopped")
|
|
|
|
async def submit(self, filename: str, content: bytes, language: str):
|
|
suffix = Path(filename).suffix.lower()
|
|
|
|
if suffix not in self.allowed_extensions:
|
|
raise ValueError("Неподдерживаемый формат аудио")
|
|
|
|
if not content:
|
|
raise ValueError("Файл пуст")
|
|
|
|
if len(content) > self.max_upload_bytes:
|
|
raise ValueError("Максимальный размер файла — 500 МБ")
|
|
|
|
job_id = uuid.uuid4().hex
|
|
stored_file = self.upload_dir / f"{job_id}{suffix}"
|
|
|
|
await asyncio.to_thread(stored_file.write_bytes, content)
|
|
|
|
try:
|
|
with self._connect() as db:
|
|
db.execute("""
|
|
INSERT INTO transcription_jobs
|
|
(id, filename, title, language, status, created_at)
|
|
VALUES (?, ?, ?, ?, 'queued', ?)
|
|
""", (
|
|
job_id,
|
|
Path(filename).name,
|
|
Path(filename).name,
|
|
language or "auto",
|
|
self._now(),
|
|
))
|
|
db.commit()
|
|
except Exception:
|
|
stored_file.unlink(missing_ok=True)
|
|
raise
|
|
|
|
self.queue.put_nowait(job_id)
|
|
return job_id
|
|
|
|
def list_jobs(self, page=1, per_page=20, status=None, query=None):
|
|
page = max(1, int(page))
|
|
per_page = min(100, max(1, int(per_page)))
|
|
query = (query or "").strip()
|
|
|
|
conditions = []
|
|
params = []
|
|
|
|
if status in {"queued", "processing", "completed", "failed"}:
|
|
conditions.append("status = ?")
|
|
params.append(status)
|
|
elif status == "queue":
|
|
conditions.append("status IN ('queued', 'processing')")
|
|
elif status == "history":
|
|
conditions.append("status IN ('completed', 'failed')")
|
|
|
|
if query:
|
|
pattern = f"%{query}%"
|
|
conditions.append("""
|
|
(title LIKE ? COLLATE NOCASE
|
|
OR filename LIKE ? COLLATE NOCASE
|
|
OR description LIKE ? COLLATE NOCASE
|
|
OR tags_json LIKE ? COLLATE NOCASE)
|
|
""")
|
|
params.extend([pattern] * 4)
|
|
|
|
where = " WHERE " + " AND ".join(conditions) if conditions else ""
|
|
|
|
with self._connect() as db:
|
|
total = db.execute(
|
|
f"SELECT COUNT(*) FROM transcription_jobs{where}", params
|
|
).fetchone()[0]
|
|
|
|
rows = db.execute(f"""
|
|
SELECT id, filename, title, description, tags_json,
|
|
language, detected_language, duration, status,
|
|
created_at, started_at, finished_at, error
|
|
FROM transcription_jobs
|
|
{where}
|
|
ORDER BY
|
|
CASE status
|
|
WHEN 'processing' THEN 0
|
|
WHEN 'queued' THEN 1
|
|
ELSE 2
|
|
END,
|
|
created_at DESC
|
|
LIMIT ? OFFSET ?
|
|
""", [*params, per_page, (page - 1) * per_page]).fetchall()
|
|
|
|
jobs = []
|
|
for row in rows:
|
|
item = dict(row)
|
|
item["tags"] = json.loads(item.pop("tags_json") or "[]")
|
|
jobs.append(item)
|
|
|
|
return {
|
|
"jobs": jobs,
|
|
"page": page,
|
|
"per_page": per_page,
|
|
"total": total,
|
|
"pages": (total + per_page - 1) // per_page,
|
|
}
|
|
|
|
def get_job(self, job_id: str):
|
|
with self._connect() as db:
|
|
row = db.execute("""
|
|
SELECT id, filename, title, description, tags_json,
|
|
language, detected_language, duration, status,
|
|
created_at, started_at, finished_at, error, result_json
|
|
FROM transcription_jobs
|
|
WHERE id = ?
|
|
""", (job_id,)).fetchone()
|
|
|
|
if not row:
|
|
return None
|
|
|
|
result = dict(row)
|
|
result["tags"] = json.loads(result.pop("tags_json") or "[]")
|
|
|
|
if result["result_json"]:
|
|
result["result"] = json.loads(result.pop("result_json"))
|
|
else:
|
|
result.pop("result_json")
|
|
|
|
return result
|
|
|
|
def update_metadata(self, job_id, title, description="", tags=None):
|
|
title = str(title or "").strip()
|
|
description = str(description or "").strip()
|
|
|
|
if not title:
|
|
raise ValueError("Название не может быть пустым")
|
|
if len(title) > 200:
|
|
raise ValueError("Название: не более 200 символов")
|
|
if len(description) > 2000:
|
|
raise ValueError("Описание: не более 2000 символов")
|
|
|
|
if isinstance(tags, str):
|
|
tags = tags.split(",")
|
|
|
|
normalized_tags = []
|
|
seen = set()
|
|
|
|
for tag in tags or []:
|
|
tag = str(tag).strip()
|
|
key = tag.casefold()
|
|
if not tag or key in seen:
|
|
continue
|
|
if len(tag) > 40:
|
|
raise ValueError("Длина тега — не более 40 символов")
|
|
seen.add(key)
|
|
normalized_tags.append(tag)
|
|
|
|
if len(normalized_tags) > 20:
|
|
raise ValueError("Можно добавить не более 20 тегов")
|
|
|
|
with self._connect() as db:
|
|
cursor = db.execute("""
|
|
UPDATE transcription_jobs
|
|
SET title = ?, description = ?, tags_json = ?
|
|
WHERE id = ?
|
|
""", (
|
|
title,
|
|
description,
|
|
json.dumps(normalized_tags, ensure_ascii=False),
|
|
job_id,
|
|
))
|
|
db.commit()
|
|
|
|
return cursor.rowcount > 0
|
|
|
|
def delete_job(self, job_id: str):
|
|
with self._connect() as db:
|
|
row = db.execute("""
|
|
SELECT status FROM transcription_jobs WHERE id = ?
|
|
""", (job_id,)).fetchone()
|
|
|
|
if not row:
|
|
return "not_found"
|
|
|
|
if row["status"] == "processing":
|
|
return "processing"
|
|
|
|
db.execute("DELETE FROM transcription_jobs WHERE id = ?", (job_id,))
|
|
db.commit()
|
|
|
|
for file_path in self.upload_dir.glob(f"{job_id}.*"):
|
|
file_path.unlink(missing_ok=True)
|
|
|
|
return "deleted"
|
|
|
|
def delete_jobs(self, job_ids):
|
|
ids = list(dict.fromkeys(str(item) for item in job_ids if item))
|
|
deleted = 0
|
|
skipped = 0
|
|
not_found = 0
|
|
|
|
for job_id in ids:
|
|
result = self.delete_job(job_id)
|
|
if result == "deleted":
|
|
deleted += 1
|
|
elif result == "processing":
|
|
skipped += 1
|
|
else:
|
|
not_found += 1
|
|
|
|
return {
|
|
"deleted": deleted,
|
|
"skipped_processing": skipped,
|
|
"not_found": not_found,
|
|
}
|
|
|
|
async def _worker(self):
|
|
while self.running:
|
|
job_id = await self.queue.get()
|
|
|
|
try:
|
|
await self._process_job(job_id)
|
|
except asyncio.CancelledError:
|
|
raise
|
|
except Exception:
|
|
logger.exception("Unexpected queue worker error for %s", job_id)
|
|
finally:
|
|
self.queue.task_done()
|
|
|
|
async def _unload_llama_models(self):
|
|
"""Выгружает все загруженные модели из Llama Router."""
|
|
async with httpx.AsyncClient(timeout=30.0) as client:
|
|
response = await client.get(f"{self.llama_url}/v1/models")
|
|
response.raise_for_status()
|
|
models = response.json().get("data")
|
|
|
|
if not isinstance(models, list):
|
|
raise RuntimeError("Llama Router вернул некорректный список моделей")
|
|
|
|
loaded = [
|
|
model for model in models
|
|
if (model.get("status") or {}).get("value") == "loaded"
|
|
]
|
|
|
|
for model in loaded:
|
|
model_id = model.get("id")
|
|
if not model_id:
|
|
raise RuntimeError("У загруженной модели отсутствует ID")
|
|
|
|
response = await client.post(
|
|
f"{self.llama_url}/models/unload",
|
|
json={"model": model_id},
|
|
)
|
|
response.raise_for_status()
|
|
|
|
result = response.json()
|
|
if result.get("success") is not True:
|
|
raise RuntimeError(
|
|
f"Router не подтвердил выгрузку модели {model_id}: {result}"
|
|
)
|
|
|
|
logger.info("Llama model unload requested: %s", model_id)
|
|
|
|
# Проверяем фактическое состояние всех моделей.
|
|
for attempt in range(30):
|
|
response = await client.get(f"{self.llama_url}/v1/models")
|
|
response.raise_for_status()
|
|
models = response.json().get("data")
|
|
|
|
if not isinstance(models, list):
|
|
raise RuntimeError("Llama Router вернул некорректный список моделей")
|
|
|
|
remaining = [
|
|
model.get("id", "unknown")
|
|
for model in models
|
|
if (model.get("status") or {}).get("value") != "unloaded"
|
|
]
|
|
|
|
if not remaining:
|
|
logger.info("All Llama models are unloaded")
|
|
return
|
|
|
|
if attempt < 29:
|
|
await asyncio.sleep(1)
|
|
|
|
raise RuntimeError(
|
|
"Не удалось подтвердить выгрузку моделей Llama: "
|
|
+ ", ".join(remaining)
|
|
)
|
|
|
|
async def _process_job(self, job_id: str):
|
|
with self._connect() as db:
|
|
row = db.execute("""
|
|
SELECT filename, language
|
|
FROM transcription_jobs
|
|
WHERE id = ? AND status = 'queued'
|
|
""", (job_id,)).fetchone()
|
|
|
|
if not row:
|
|
return
|
|
|
|
db.execute("""
|
|
UPDATE transcription_jobs
|
|
SET status = 'processing', started_at = ?, error = NULL
|
|
WHERE id = ?
|
|
""", (self._now(), job_id))
|
|
db.commit()
|
|
|
|
filename = row["filename"]
|
|
language = row["language"]
|
|
|
|
files = list(self.upload_dir.glob(f"{job_id}.*"))
|
|
if not files:
|
|
self._set_failed(job_id, "Аудиофайл задания не найден")
|
|
return
|
|
|
|
audio_path = files[0]
|
|
|
|
try:
|
|
await self._unload_llama_models()
|
|
|
|
data = {
|
|
"model": self.model,
|
|
"response_format": "verbose_json",
|
|
}
|
|
|
|
if language and language != "auto":
|
|
data["language"] = language
|
|
|
|
def read_audio():
|
|
return audio_path.read_bytes()
|
|
|
|
content = await asyncio.to_thread(read_audio)
|
|
|
|
async with httpx.AsyncClient(
|
|
timeout=httpx.Timeout(3600.0, connect=15.0)
|
|
) as client:
|
|
response = await client.post(
|
|
f"{self.speaches_url}/v1/audio/transcriptions",
|
|
data=data,
|
|
files={
|
|
"file": (
|
|
filename,
|
|
content,
|
|
"application/octet-stream",
|
|
)
|
|
},
|
|
)
|
|
|
|
response.raise_for_status()
|
|
result = response.json()
|
|
|
|
result = {
|
|
"text": result.get("text", ""),
|
|
"language": result.get("language"),
|
|
"duration": result.get("duration"),
|
|
"segments": result.get("segments", []),
|
|
}
|
|
|
|
with self._connect() as db:
|
|
db.execute("""
|
|
UPDATE transcription_jobs
|
|
SET status = 'completed',
|
|
finished_at = ?,
|
|
result_json = ?,
|
|
duration = ?,
|
|
detected_language = ?,
|
|
error = NULL
|
|
WHERE id = ?
|
|
""", (
|
|
self._now(),
|
|
json.dumps(result, ensure_ascii=False),
|
|
result.get("duration"),
|
|
result.get("language"),
|
|
job_id,
|
|
))
|
|
db.commit()
|
|
|
|
logger.info("Transcription job completed: %s", job_id)
|
|
audio_path.unlink(missing_ok=True)
|
|
|
|
except asyncio.CancelledError:
|
|
# При остановке Portal файл сохраняется.
|
|
# При следующем запуске задание вернётся в очередь.
|
|
raise
|
|
except httpx.HTTPStatusError as exc:
|
|
detail = exc.response.text[:1200]
|
|
self._set_failed(
|
|
job_id,
|
|
f"Speaches вернул HTTP {exc.response.status_code}: {detail}",
|
|
)
|
|
audio_path.unlink(missing_ok=True)
|
|
except httpx.HTTPError as exc:
|
|
self._set_failed(job_id, f"Ошибка соединения со Speaches: {exc}")
|
|
audio_path.unlink(missing_ok=True)
|
|
except (ValueError, OSError) as exc:
|
|
self._set_failed(job_id, str(exc))
|
|
audio_path.unlink(missing_ok=True)
|
|
except Exception as exc:
|
|
logger.exception("Transcription failed: %s", job_id)
|
|
self._set_failed(job_id, str(exc))
|
|
audio_path.unlink(missing_ok=True)
|
|
|
|
def _set_failed(self, job_id: str, error: str):
|
|
with self._connect() as db:
|
|
db.execute("""
|
|
UPDATE transcription_jobs
|
|
SET status = 'failed', finished_at = ?, error = ?
|
|
WHERE id = ?
|
|
""", (self._now(), error[:2000], job_id))
|
|
db.commit()
|
|
|
|
logger.error("Transcription job failed: %s: %s", job_id, error)
|