Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 115fb5acb9 | |||
| 5c5827d241 | |||
| 85929c9054 |
@@ -321,9 +321,63 @@ def password_change(username):
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
def system_power(action):
|
||||
commands = {
|
||||
'reboot': '/usr/bin/systemctl',
|
||||
'poweroff': '/usr/bin/systemctl',
|
||||
}
|
||||
if action not in commands:
|
||||
return 2
|
||||
|
||||
subprocess.run(
|
||||
[commands[action], '--no-block', action],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
)
|
||||
return 0
|
||||
|
||||
def speaches_control(action):
|
||||
"""Manage only the dedicated Speaches container."""
|
||||
if action not in {"start", "stop"}:
|
||||
return 2
|
||||
|
||||
docker = "/usr/bin/docker"
|
||||
container = "speaches"
|
||||
|
||||
state = run(
|
||||
docker,
|
||||
"inspect",
|
||||
"--format",
|
||||
"{{.State.Running}}",
|
||||
container,
|
||||
timeout=10,
|
||||
).stdout.strip().lower()
|
||||
|
||||
if state not in {"true", "false"}:
|
||||
raise RuntimeError(f"Unexpected Speaches container state: {state}")
|
||||
|
||||
if action == "start":
|
||||
if state == "true":
|
||||
return 0
|
||||
run(docker, "start", container, timeout=60)
|
||||
return 0
|
||||
|
||||
if state == "false":
|
||||
return 0
|
||||
|
||||
run(docker, "stop", "--time", "10", container, timeout=30)
|
||||
return 0
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 3: return 2
|
||||
action, value = sys.argv[1:]
|
||||
|
||||
if action == "speaches-control":
|
||||
return speaches_control(value)
|
||||
if action == 'hostname':
|
||||
if len(value) > 63 or not re.fullmatch(r'[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?', value): return 2
|
||||
run('/usr/bin/hostnamectl', 'set-hostname', value); return 0
|
||||
@@ -334,6 +388,7 @@ def main():
|
||||
if value not in {'yes', 'no'}: return 2
|
||||
run('/usr/bin/timedatectl', 'set-ntp', 'true' if value == 'yes' else 'false'); return 0
|
||||
if action == 'password-change': return password_change(value)
|
||||
if action == 'system-power': return system_power(value)
|
||||
if action == 'network-read': return network_read(value)
|
||||
if action == 'network-status': return network_status()
|
||||
if action == 'network-apply': return network_apply(value)
|
||||
|
||||
@@ -16,6 +16,7 @@ import time
|
||||
import ipaddress
|
||||
import logging
|
||||
import hmac
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timezone
|
||||
from zoneinfo import available_timezones
|
||||
from pathlib import Path
|
||||
@@ -30,16 +31,43 @@ from fastapi.staticfiles import StaticFiles
|
||||
from starlette.middleware.sessions import SessionMiddleware
|
||||
import pam
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from transcription_queue import TranscriptionQueue
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
SERVICES_FILE = BASE_DIR / "services.json"
|
||||
|
||||
SPEACHES_URL = "http://192.168.1.26:8000"
|
||||
WHISPER_MODEL = "Systran/faster-whisper-small"
|
||||
LLAMA_ROUTER_URL = "http://192.168.1.26:8080"
|
||||
WHISPER_MODEL = "Systran/faster-whisper-large-v3"
|
||||
MAX_UPLOAD_BYTES = 500 * 1024 * 1024
|
||||
ALLOWED_EXTENSIONS = {".wav", ".mp3", ".m4a", ".mp4", ".mpeg", ".mpga", ".webm", ".ogg", ".oga", ".flac"}
|
||||
ALLOWED_EXTENSIONS = {".wav", ".mp3", ".m4a", ".aac", ".mp4", ".mpeg", ".mpga", ".webm", ".ogg", ".oga", ".flac", ".opus"}
|
||||
|
||||
app = FastAPI(title="AI Station Portal", version="0.8.2")
|
||||
TRANSCRIPTION_DATA_DIR = Path("/var/lib/ai-station-portal/transcription")
|
||||
|
||||
transcription_queue = TranscriptionQueue(
|
||||
data_dir=TRANSCRIPTION_DATA_DIR,
|
||||
speaches_url=SPEACHES_URL,
|
||||
llama_url=LLAMA_ROUTER_URL,
|
||||
model=WHISPER_MODEL,
|
||||
max_upload_bytes=MAX_UPLOAD_BYTES,
|
||||
allowed_extensions=ALLOWED_EXTENSIONS,
|
||||
)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
await transcription_queue.start()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await transcription_queue.stop()
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="AI Station Portal",
|
||||
version="0.8.2",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
app.add_middleware(
|
||||
SessionMiddleware,
|
||||
secret_key=os.getenv("AI_STATION_SESSION_SECRET") or secrets.token_urlsafe(48),
|
||||
@@ -373,6 +401,39 @@ async def update_admin_password(
|
||||
return RedirectResponse("/admin/login?result=password-changed", status_code=303)
|
||||
|
||||
|
||||
|
||||
@app.post("/admin/system/reboot")
|
||||
async def admin_reboot(request: Request, csrf_token: str = Form(...)):
|
||||
if not admin_session_valid(request):
|
||||
return RedirectResponse("/admin/login", status_code=303)
|
||||
|
||||
session_token = request.session.get("password_csrf", "")
|
||||
if not session_token or not hmac.compare_digest(csrf_token, session_token):
|
||||
return RedirectResponse("/admin?error=system-csrf", status_code=303)
|
||||
|
||||
ok, _ = run_helper("system-power", "reboot")
|
||||
if not ok:
|
||||
return RedirectResponse("/admin?error=system-power", status_code=303)
|
||||
|
||||
return RedirectResponse("/admin", status_code=303)
|
||||
|
||||
|
||||
@app.post("/admin/system/poweroff")
|
||||
async def admin_poweroff(request: Request, csrf_token: str = Form(...)):
|
||||
if not admin_session_valid(request):
|
||||
return RedirectResponse("/admin/login", status_code=303)
|
||||
|
||||
session_token = request.session.get("password_csrf", "")
|
||||
if not session_token or not hmac.compare_digest(csrf_token, session_token):
|
||||
return RedirectResponse("/admin?error=system-csrf", status_code=303)
|
||||
|
||||
ok, _ = run_helper("system-power", "poweroff")
|
||||
if not ok:
|
||||
return RedirectResponse("/admin?error=system-power", status_code=303)
|
||||
|
||||
return RedirectResponse("/admin", status_code=303)
|
||||
|
||||
|
||||
@app.post("/admin/settings/network")
|
||||
async def update_network(
|
||||
request: Request,
|
||||
@@ -584,50 +645,99 @@ async def admin_logout(request: Request):
|
||||
|
||||
@app.post("/api/transcribe")
|
||||
async def transcribe(
|
||||
request: Request,
|
||||
file: UploadFile = File(...),
|
||||
language: str = Form("auto"),
|
||||
):
|
||||
filename = file.filename or "audio"
|
||||
suffix = Path(filename).suffix.lower()
|
||||
if suffix not in ALLOWED_EXTENSIONS:
|
||||
raise HTTPException(status_code=400, detail="Неподдерживаемый формат аудио")
|
||||
|
||||
content = await file.read(MAX_UPLOAD_BYTES + 1)
|
||||
if not content:
|
||||
raise HTTPException(status_code=400, detail="Файл пуст")
|
||||
if len(content) > MAX_UPLOAD_BYTES:
|
||||
raise HTTPException(status_code=413, detail="Максимальный размер файла — 500 МБ")
|
||||
|
||||
data = {"model": WHISPER_MODEL, "response_format": "verbose_json"}
|
||||
if language and language != "auto":
|
||||
data["language"] = language
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=httpx.Timeout(3600.0, connect=15.0)) as client:
|
||||
response = await client.post(
|
||||
f"http://{request.url.hostname}:8000/v1/audio/transcriptions",
|
||||
data=data,
|
||||
files={"file": (filename, content, file.content_type or "application/octet-stream")},
|
||||
)
|
||||
response.raise_for_status()
|
||||
except httpx.HTTPStatusError as exc:
|
||||
detail = exc.response.text[:1200] or f"Speaches вернул HTTP {exc.response.status_code}"
|
||||
raise HTTPException(status_code=502, detail=f"Ошибка Speaches: {detail}") from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(status_code=502, detail=f"Не удалось связаться со Speaches: {exc}") from exc
|
||||
|
||||
try:
|
||||
result = response.json()
|
||||
job_id = await transcription_queue.submit(
|
||||
filename=filename,
|
||||
content=content,
|
||||
language=language,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=502, detail="Speaches вернул некорректный ответ") from exc
|
||||
status_code = 413 if "500 МБ" in str(exc) else 400
|
||||
raise HTTPException(status_code=status_code, detail=str(exc)) from exc
|
||||
|
||||
return JSONResponse({
|
||||
"text": result.get("text", ""),
|
||||
"language": result.get("language"),
|
||||
"duration": result.get("duration"),
|
||||
"segments": result.get("segments", []),
|
||||
})
|
||||
return JSONResponse(
|
||||
{"job_id": job_id, "status": "queued"},
|
||||
status_code=202,
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/transcriptions")
|
||||
async def list_transcriptions(
|
||||
page: int = 1,
|
||||
per_page: int = 20,
|
||||
status: str | None = None,
|
||||
q: str | None = None,
|
||||
):
|
||||
return transcription_queue.list_jobs(
|
||||
page=page,
|
||||
per_page=per_page,
|
||||
status=status,
|
||||
query=q,
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/transcriptions/{job_id}")
|
||||
async def get_transcription(job_id: str):
|
||||
job = transcription_queue.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Задание не найдено")
|
||||
return job
|
||||
|
||||
|
||||
@app.patch("/api/transcriptions/{job_id}")
|
||||
async def update_transcription(job_id: str, request: Request):
|
||||
payload = await request.json()
|
||||
|
||||
try:
|
||||
updated = transcription_queue.update_metadata(
|
||||
job_id=job_id,
|
||||
title=payload.get("title", ""),
|
||||
description=payload.get("description", ""),
|
||||
tags=payload.get("tags", []),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
if not updated:
|
||||
raise HTTPException(status_code=404, detail="Задание не найдено")
|
||||
|
||||
return transcription_queue.get_job(job_id)
|
||||
|
||||
|
||||
@app.delete("/api/transcriptions/bulk")
|
||||
async def bulk_delete_transcriptions(request: Request):
|
||||
payload = await request.json()
|
||||
ids = payload.get("ids", [])
|
||||
|
||||
if not isinstance(ids, list):
|
||||
raise HTTPException(status_code=400, detail="ids должен быть списком")
|
||||
|
||||
if len(ids) > 500:
|
||||
raise HTTPException(status_code=400, detail="За один раз можно удалить не более 500 записей")
|
||||
|
||||
return transcription_queue.delete_jobs(ids)
|
||||
|
||||
|
||||
@app.delete("/api/transcriptions/{job_id}")
|
||||
async def delete_transcription(job_id: str):
|
||||
result = transcription_queue.delete_job(job_id)
|
||||
|
||||
if result == "not_found":
|
||||
raise HTTPException(status_code=404, detail="Задание не найдено")
|
||||
|
||||
if result == "processing":
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Нельзя удалить задание во время обработки",
|
||||
)
|
||||
|
||||
return {"status": "deleted", "job_id": job_id}
|
||||
|
||||
|
||||
@app.post("/api/export/docx")
|
||||
|
||||
@@ -275,6 +275,30 @@
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="card bg-dark border-secondary mb-4">
|
||||
<summary class="card-header bg-transparent text-light fw-semibold">
|
||||
<h2 class="h5 mb-0"><i class="bi bi-power text-warning me-2"></i>Управление станцией</h2></summary>
|
||||
<div class="card-body p-4">
|
||||
<p class="text-secondary small">Перезагрузка или полное выключение сервера.</p>
|
||||
<div class="d-flex flex-wrap gap-2">
|
||||
<form method="post" action="/admin/system/reboot"
|
||||
onsubmit="return confirm('Перезагрузить станцию? Все активные задачи будут прерваны.')">
|
||||
<input type="hidden" name="csrf_token" value="{{ password_csrf }}">
|
||||
<button class="btn btn-outline-warning" type="submit">
|
||||
<i class="bi bi-arrow-clockwise me-1"></i>Перезагрузить
|
||||
</button>
|
||||
</form>
|
||||
<form method="post" action="/admin/system/poweroff"
|
||||
onsubmit="return confirm('Выключить станцию? Для повторного запуска потребуется физически включить сервер.')">
|
||||
<input type="hidden" name="csrf_token" value="{{ password_csrf }}">
|
||||
<button class="btn btn-outline-danger" type="submit">
|
||||
<i class="bi bi-power me-1"></i>Выключить
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="card bg-dark border-secondary mb-4">
|
||||
<summary class="card-header bg-transparent text-light fw-semibold">
|
||||
<h2 class="h5 mb-0"><i class="bi bi-ethernet text-info me-2"></i>Сеть</h2></summary>
|
||||
|
||||
+666
-27
@@ -25,10 +25,10 @@
|
||||
<label for="audio-file" class="upload-area d-flex flex-column align-items-center justify-content-center text-center p-5 mb-3">
|
||||
<i class="bi bi-cloud-arrow-up display-4 text-info mb-3"></i>
|
||||
<span class="fw-semibold">Выберите аудиофайл или перетащите его сюда</span>
|
||||
<span class="text-secondary small mt-2">WAV, MP3, M4A, OGG, FLAC, WEBM · до 500 МБ</span>
|
||||
<span class="text-secondary small mt-2">WAV, MP3, M4A, AAC, OGG, OPUS, FLAC, WEBM · до 500 МБ</span>
|
||||
<span id="file-name" class="small text-info mt-3">Файл не выбран</span>
|
||||
</label>
|
||||
<input class="visually-hidden" type="file" id="audio-file" name="file" accept="audio/*,.mp4,.mpeg,.mpga,.webm" required>
|
||||
<input class="visually-hidden" type="file" id="audio-file" name="file" accept="audio/*,.aac,.mp4,.mpeg,.mpga,.webm,.opus" multiple required>
|
||||
<div class="row g-3 align-items-end">
|
||||
<div class="col-12 col-md-5">
|
||||
<label for="language" class="form-label">Язык записи</label>
|
||||
@@ -51,6 +51,82 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
<section class="card border-secondary-subtle bg-dark-subtle mb-4">
|
||||
<div class="card-body p-4">
|
||||
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
|
||||
<h2 class="h5 mb-0"><i class="bi bi-collection me-2"></i>Библиотека расшифровок</h2>
|
||||
<span class="badge text-bg-secondary" id="queue-count">0</span>
|
||||
</div>
|
||||
|
||||
<div class="btn-group mb-3" role="group" aria-label="Фильтр записей">
|
||||
<button class="btn btn-outline-light active" data-filter="all">Все</button>
|
||||
<button class="btn btn-outline-light" data-filter="queue">Очередь</button>
|
||||
<button class="btn btn-outline-light" data-filter="history">История</button>
|
||||
</div>
|
||||
|
||||
<div class="row g-2 mb-3">
|
||||
<div class="col">
|
||||
<input type="search" class="form-control" id="library-search"
|
||||
placeholder="Поиск по названию, файлу, описанию и тегам">
|
||||
</div>
|
||||
<div class="col-auto">
|
||||
<button class="btn btn-outline-light" id="search-button">
|
||||
<i class="bi bi-search"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-2">
|
||||
<div class="small text-secondary" id="library-info">Загрузка...</div>
|
||||
<button class="btn btn-outline-danger btn-sm d-none" id="bulk-delete-button">
|
||||
<i class="bi bi-trash me-1"></i>Удалить выбранные
|
||||
(<span id="selected-count">0</span>)
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="queue-list">
|
||||
<div class="text-secondary small">Загрузка записей...</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex justify-content-between align-items-center mt-3">
|
||||
<button class="btn btn-outline-light btn-sm" id="page-prev" disabled>
|
||||
<i class="bi bi-chevron-left me-1"></i>Назад
|
||||
</button>
|
||||
<span class="small text-secondary" id="page-info">Страница 1</span>
|
||||
<button class="btn btn-outline-light btn-sm" id="page-next" disabled>
|
||||
Далее<i class="bi bi-chevron-right ms-1"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<dialog id="metadata-dialog" class="bg-dark text-light border border-secondary rounded-3 p-0"
|
||||
style="width:min(560px, calc(100% - 24px));">
|
||||
<div class="p-4">
|
||||
<h2 class="h5 mb-3">Свойства записи</h2>
|
||||
<input type="hidden" id="metadata-job-id">
|
||||
<div class="mb-3">
|
||||
<label for="metadata-title" class="form-label">Название</label>
|
||||
<input type="text" class="form-control" id="metadata-title" maxlength="200" required>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="metadata-description" class="form-label">Описание</label>
|
||||
<textarea class="form-control" id="metadata-description" rows="3" maxlength="2000"></textarea>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="metadata-tags" class="form-label">Теги</label>
|
||||
<input type="text" class="form-control" id="metadata-tags"
|
||||
placeholder="Например: совещание, клиент, проект">
|
||||
<div class="form-text">Разделяйте теги запятыми. Не более 20 тегов.</div>
|
||||
</div>
|
||||
<div class="d-flex justify-content-end gap-2">
|
||||
<button class="btn btn-outline-light" id="metadata-cancel">Отмена</button>
|
||||
<button class="btn btn-primary" id="metadata-save">Сохранить</button>
|
||||
</div>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<section id="result-section" class="card border-secondary-subtle bg-dark-subtle d-none">
|
||||
<div class="card-body p-4">
|
||||
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
|
||||
@@ -82,41 +158,604 @@ const resultSection = document.getElementById('result-section');
|
||||
const transcript = document.getElementById('transcript');
|
||||
let lastSegments = [];
|
||||
|
||||
fileInput.addEventListener('change', () => { fileName.textContent = fileInput.files[0]?.name || 'Файл не выбран'; });
|
||||
function updateFileName() {
|
||||
const files = Array.from(fileInput.files || []);
|
||||
if (!files.length) {
|
||||
fileName.textContent = 'Файл не выбран';
|
||||
} else if (files.length === 1) {
|
||||
fileName.textContent = files[0].name;
|
||||
} else {
|
||||
fileName.textContent = `Выбрано файлов: ${files.length}`;
|
||||
}
|
||||
}
|
||||
|
||||
fileInput.addEventListener('change', updateFileName);
|
||||
const uploadArea = document.querySelector('.upload-area');
|
||||
uploadArea.addEventListener('dragover', e => { e.preventDefault(); uploadArea.classList.add('drag-over'); });
|
||||
uploadArea.addEventListener('dragleave', () => uploadArea.classList.remove('drag-over'));
|
||||
uploadArea.addEventListener('drop', e => { e.preventDefault(); uploadArea.classList.remove('drag-over'); if (e.dataTransfer.files.length) { fileInput.files = e.dataTransfer.files; fileName.textContent = fileInput.files[0].name; } });
|
||||
uploadArea.addEventListener('drop', e => {
|
||||
e.preventDefault();
|
||||
uploadArea.classList.remove('drag-over');
|
||||
if (e.dataTransfer.files.length) {
|
||||
fileInput.files = e.dataTransfer.files;
|
||||
updateFileName();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
let activeJobId = null;
|
||||
let loadedJobId = null;
|
||||
let currentPage = 1;
|
||||
let currentFilter = 'all';
|
||||
let currentQuery = '';
|
||||
let totalPages = 1;
|
||||
let selectedIds = new Set();
|
||||
|
||||
const statusLabels = {
|
||||
queued: 'В очереди',
|
||||
processing: 'Распознаётся',
|
||||
completed: 'Готово',
|
||||
failed: 'Ошибка'
|
||||
};
|
||||
|
||||
const list = document.getElementById('queue-list');
|
||||
const count = document.getElementById('queue-count');
|
||||
const searchInput = document.getElementById('library-search');
|
||||
const dialog = document.getElementById('metadata-dialog');
|
||||
|
||||
function updateSelectionUI() {
|
||||
const button = document.getElementById('bulk-delete-button');
|
||||
document.getElementById('selected-count').textContent = selectedIds.size;
|
||||
button.classList.toggle('d-none', selectedIds.size === 0);
|
||||
}
|
||||
|
||||
function renderQueue(jobs) {
|
||||
list.replaceChildren();
|
||||
count.textContent = document.getElementById('library-info').dataset.total || '0';
|
||||
|
||||
if (!jobs.length) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'text-secondary small py-3';
|
||||
empty.textContent = 'Записей не найдено';
|
||||
list.append(empty);
|
||||
updateSelectionUI();
|
||||
return;
|
||||
}
|
||||
|
||||
jobs.forEach(job => {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'd-flex flex-wrap align-items-center gap-3 py-3 border-bottom border-secondary-subtle';
|
||||
|
||||
if (job.status !== 'processing') {
|
||||
const checkbox = document.createElement('input');
|
||||
checkbox.type = 'checkbox';
|
||||
checkbox.className = 'form-check-input mt-0';
|
||||
checkbox.checked = selectedIds.has(job.id);
|
||||
checkbox.addEventListener('change', () => {
|
||||
if (checkbox.checked) selectedIds.add(job.id);
|
||||
else selectedIds.delete(job.id);
|
||||
updateSelectionUI();
|
||||
});
|
||||
item.append(checkbox);
|
||||
} else {
|
||||
const spacer = document.createElement('span');
|
||||
spacer.style.width = '16px';
|
||||
item.append(spacer);
|
||||
}
|
||||
|
||||
const info = document.createElement('div');
|
||||
info.className = 'me-auto';
|
||||
info.style.minWidth = '180px';
|
||||
|
||||
const name = document.createElement('div');
|
||||
name.className = 'fw-semibold';
|
||||
name.textContent = job.title || job.filename;
|
||||
|
||||
const details = document.createElement('div');
|
||||
details.className = 'small text-secondary';
|
||||
const date = new Date(job.created_at).toLocaleString();
|
||||
const detailsParts = [
|
||||
statusLabels[job.status] || job.status,
|
||||
date,
|
||||
job.filename
|
||||
];
|
||||
if (Number.isFinite(job.duration)) {
|
||||
detailsParts.push(`${Math.round(job.duration)} сек.`);
|
||||
}
|
||||
if (job.detected_language) {
|
||||
detailsParts.push(job.detected_language);
|
||||
}
|
||||
details.textContent = detailsParts.join(' · ');
|
||||
|
||||
info.append(name, details);
|
||||
|
||||
if (job.description) {
|
||||
const description = document.createElement('div');
|
||||
description.className = 'small text-secondary mt-1';
|
||||
description.textContent = job.description;
|
||||
info.append(description);
|
||||
}
|
||||
|
||||
if (job.tags?.length) {
|
||||
const tags = document.createElement('div');
|
||||
tags.className = 'd-flex flex-wrap gap-1 mt-2';
|
||||
job.tags.forEach(tag => {
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'badge text-bg-secondary';
|
||||
badge.textContent = tag;
|
||||
tags.append(badge);
|
||||
});
|
||||
info.append(tags);
|
||||
}
|
||||
|
||||
if (job.error) {
|
||||
const error = document.createElement('div');
|
||||
error.className = 'small text-danger mt-1';
|
||||
error.textContent = job.error;
|
||||
info.append(error);
|
||||
}
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'd-flex flex-wrap gap-2';
|
||||
|
||||
if (job.status === 'completed') {
|
||||
const openButton = document.createElement('button');
|
||||
openButton.className = 'btn btn-outline-info btn-sm';
|
||||
openButton.textContent = 'Открыть';
|
||||
openButton.addEventListener('click', () => openJob(job.id));
|
||||
actions.append(openButton);
|
||||
}
|
||||
|
||||
if (job.status !== 'processing') {
|
||||
const editButton = document.createElement('button');
|
||||
editButton.className = 'btn btn-outline-light btn-sm';
|
||||
editButton.textContent = 'Изменить';
|
||||
editButton.addEventListener('click', () => editMetadata(job));
|
||||
actions.append(editButton);
|
||||
|
||||
const deleteButton = document.createElement('button');
|
||||
deleteButton.className = 'btn btn-outline-danger btn-sm';
|
||||
deleteButton.textContent = 'Удалить';
|
||||
deleteButton.addEventListener('click', () => deleteJob(job.id));
|
||||
actions.append(deleteButton);
|
||||
}
|
||||
|
||||
item.append(info, actions);
|
||||
list.append(item);
|
||||
});
|
||||
|
||||
updateSelectionUI();
|
||||
}
|
||||
|
||||
async function refreshQueue() {
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
page: String(currentPage),
|
||||
per_page: '20'
|
||||
});
|
||||
|
||||
if (currentFilter !== 'all') params.set('status', currentFilter);
|
||||
if (currentQuery) params.set('q', currentQuery);
|
||||
|
||||
const response = await fetch(`/api/transcriptions?${params}`);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
totalPages = Math.max(1, data.pages || 1);
|
||||
if (currentPage > totalPages) {
|
||||
currentPage = totalPages;
|
||||
return refreshQueue();
|
||||
}
|
||||
|
||||
document.getElementById('library-info').textContent =
|
||||
`Найдено записей: ${data.total}`;
|
||||
document.getElementById('library-info').dataset.total = data.total;
|
||||
count.textContent = data.total;
|
||||
|
||||
document.getElementById('page-info').textContent =
|
||||
`Страница ${data.page} из ${totalPages}`;
|
||||
document.getElementById('page-prev').disabled = currentPage <= 1;
|
||||
document.getElementById('page-next').disabled = currentPage >= totalPages;
|
||||
|
||||
renderQueue(data.jobs || []);
|
||||
|
||||
if (activeJobId) {
|
||||
const active = data.jobs?.find(job => job.id === activeJobId);
|
||||
|
||||
if (active?.status === 'processing') {
|
||||
document.getElementById('progress-label').textContent = 'Идёт распознавание...';
|
||||
progress.classList.remove('d-none');
|
||||
} else if (active?.status === 'queued') {
|
||||
document.getElementById('progress-label').textContent = 'Задание ожидает своей очереди...';
|
||||
progress.classList.remove('d-none');
|
||||
} else if (active?.status === 'completed' && loadedJobId !== activeJobId) {
|
||||
loadedJobId = activeJobId;
|
||||
const completedId = activeJobId;
|
||||
activeJobId = null;
|
||||
progress.classList.add('d-none');
|
||||
await openJob(completedId);
|
||||
} else if (active?.status === 'failed') {
|
||||
showError(active.error || 'Ошибка распознавания');
|
||||
activeJobId = null;
|
||||
progress.classList.add('d-none');
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Не удалось обновить библиотеку:', err);
|
||||
}
|
||||
}
|
||||
|
||||
async function openJob(jobId) {
|
||||
try {
|
||||
const response = await fetch(`/api/transcriptions/${encodeURIComponent(jobId)}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.detail || `Ошибка HTTP ${response.status}`);
|
||||
}
|
||||
if (data.status !== 'completed' || !data.result) {
|
||||
throw new Error('Результат задания пока недоступен');
|
||||
}
|
||||
|
||||
const result = data.result;
|
||||
transcript.value = result.text || '';
|
||||
lastSegments = result.segments || [];
|
||||
|
||||
const meta = [];
|
||||
if (result.language) meta.push(`Язык: ${result.language}`);
|
||||
if (Number.isFinite(result.duration)) {
|
||||
meta.push(`Длительность: ${Math.round(result.duration)} сек.`);
|
||||
}
|
||||
meta.push(`Название: ${data.title || data.filename}`);
|
||||
meta.push(`Файл: ${data.filename}`);
|
||||
|
||||
document.getElementById('result-meta').textContent = meta.join(' · ');
|
||||
resultSection.classList.remove('d-none');
|
||||
resultSection.scrollIntoView({behavior: 'smooth', block: 'start'});
|
||||
errorBox.classList.add('d-none');
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
function editMetadata(job) {
|
||||
document.getElementById('metadata-job-id').value = job.id;
|
||||
document.getElementById('metadata-title').value = job.title || job.filename;
|
||||
document.getElementById('metadata-description').value = job.description || '';
|
||||
document.getElementById('metadata-tags').value = (job.tags || []).join(', ');
|
||||
dialog.showModal();
|
||||
}
|
||||
|
||||
document.getElementById('metadata-cancel').addEventListener('click', () => dialog.close());
|
||||
|
||||
document.getElementById('metadata-save').addEventListener('click', async () => {
|
||||
const id = document.getElementById('metadata-job-id').value;
|
||||
const button = document.getElementById('metadata-save');
|
||||
button.disabled = true;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/transcriptions/${encodeURIComponent(id)}`, {
|
||||
method: 'PATCH',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({
|
||||
title: document.getElementById('metadata-title').value,
|
||||
description: document.getElementById('metadata-description').value,
|
||||
tags: document.getElementById('metadata-tags').value
|
||||
.split(',').map(tag => tag.trim()).filter(Boolean)
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.detail || `HTTP ${response.status}`);
|
||||
|
||||
dialog.close();
|
||||
selectedIds.delete(id);
|
||||
await refreshQueue();
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
async function deleteJob(jobId) {
|
||||
if (!confirm('Удалить запись и связанные с ней файлы?')) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/transcriptions/${encodeURIComponent(jobId)}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.detail || `HTTP ${response.status}`);
|
||||
|
||||
selectedIds.delete(jobId);
|
||||
await refreshQueue();
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('bulk-delete-button').addEventListener('click', async () => {
|
||||
if (!selectedIds.size) return;
|
||||
if (!confirm(`Удалить выбранные записи (${selectedIds.size}) и связанные файлы?`)) return;
|
||||
|
||||
const button = document.getElementById('bulk-delete-button');
|
||||
button.disabled = true;
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/transcriptions/bulk', {
|
||||
method: 'DELETE',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({ids: Array.from(selectedIds)})
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.detail || `HTTP ${response.status}`);
|
||||
|
||||
selectedIds.clear();
|
||||
await refreshQueue();
|
||||
|
||||
if (data.skipped_processing) {
|
||||
showError(`Удалено: ${data.deleted}. Пропущено (идёт обработка): ${data.skipped_processing}.`);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelectorAll('[data-filter]').forEach(button => {
|
||||
button.addEventListener('click', () => {
|
||||
currentFilter = button.dataset.filter;
|
||||
currentPage = 1;
|
||||
selectedIds.clear();
|
||||
|
||||
document.querySelectorAll('[data-filter]').forEach(item =>
|
||||
item.classList.toggle('active', item === button)
|
||||
);
|
||||
|
||||
refreshQueue();
|
||||
});
|
||||
});
|
||||
|
||||
function applySearch() {
|
||||
currentQuery = searchInput.value.trim();
|
||||
currentPage = 1;
|
||||
selectedIds.clear();
|
||||
refreshQueue();
|
||||
}
|
||||
|
||||
document.getElementById('search-button').addEventListener('click', applySearch);
|
||||
searchInput.addEventListener('keydown', event => {
|
||||
if (event.key === 'Enter') applySearch();
|
||||
});
|
||||
|
||||
document.getElementById('page-prev').addEventListener('click', () => {
|
||||
if (currentPage > 1) {
|
||||
currentPage--;
|
||||
refreshQueue();
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('page-next').addEventListener('click', () => {
|
||||
if (currentPage < totalPages) {
|
||||
currentPage++;
|
||||
refreshQueue();
|
||||
}
|
||||
});
|
||||
|
||||
form.addEventListener('submit', async e => {
|
||||
e.preventDefault();
|
||||
if (!fileInput.files.length) return;
|
||||
errorBox.classList.add('d-none'); resultSection.classList.add('d-none'); progress.classList.remove('d-none');
|
||||
|
||||
const files = Array.from(fileInput.files || []);
|
||||
if (!files.length || submitButton.disabled) return;
|
||||
|
||||
const confirmed = confirm(
|
||||
'Для транскрибации Portal выгрузит все загруженные модели Llama.cpp с GPU.\n\n' +
|
||||
'Активные LLM-сессии могут быть прерваны. После транскрибации модели ' +
|
||||
'автоматически не восстановятся.\n\nПродолжить?'
|
||||
);
|
||||
|
||||
if (!confirmed) return;
|
||||
|
||||
errorBox.classList.add('d-none');
|
||||
submitButton.disabled = true;
|
||||
document.getElementById('progress-label').textContent = 'Файл отправлен. Выполняется распознавание...';
|
||||
const body = new FormData(); body.append('file', fileInput.files[0]); body.append('language', document.getElementById('language').value);
|
||||
progress.classList.remove('d-none');
|
||||
|
||||
const language = document.getElementById('language').value;
|
||||
let submitted = 0;
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/transcribe', {method:'POST', body});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.detail || `Ошибка HTTP ${response.status}`);
|
||||
transcript.value = data.text || '';
|
||||
lastSegments = data.segments || [];
|
||||
const meta = [];
|
||||
if (data.language) meta.push(`Язык: ${data.language}`);
|
||||
if (Number.isFinite(data.duration)) meta.push(`Длительность: ${Math.round(data.duration)} сек.`);
|
||||
document.getElementById('result-meta').textContent = meta.join(' · ');
|
||||
resultSection.classList.remove('d-none');
|
||||
resultSection.scrollIntoView({behavior:'smooth', block:'start'});
|
||||
} catch (err) { errorBox.textContent = err.message; errorBox.classList.remove('d-none'); }
|
||||
finally { progress.classList.add('d-none'); submitButton.disabled = false; }
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
document.getElementById('progress-label').textContent =
|
||||
`Загружаем файл ${i + 1} из ${files.length}: ${files[i].name}`;
|
||||
|
||||
const body = new FormData();
|
||||
body.append('file', files[i]);
|
||||
body.append('language', language);
|
||||
|
||||
const response = await fetch('/api/transcribe', {
|
||||
method: 'POST',
|
||||
body
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`${files[i].name}: ${data.detail || `Ошибка HTTP ${response.status}`}`
|
||||
);
|
||||
}
|
||||
|
||||
activeJobId = data.job_id;
|
||||
loadedJobId = null;
|
||||
currentFilter = 'all';
|
||||
currentQuery = '';
|
||||
currentPage = 1;
|
||||
searchInput.value = '';
|
||||
document.querySelectorAll('[data-filter]').forEach(item =>
|
||||
item.classList.toggle('active', item.dataset.filter === 'all')
|
||||
);
|
||||
submitted++;
|
||||
}
|
||||
|
||||
fileInput.value = '';
|
||||
updateFileName();
|
||||
|
||||
document.getElementById('progress-label').textContent =
|
||||
`В очередь добавлено файлов: ${submitted}`;
|
||||
|
||||
await refreshQueue();
|
||||
|
||||
} catch (err) {
|
||||
const prefix = submitted
|
||||
? `Успешно добавлено ${submitted} из ${files.length}. `
|
||||
: '';
|
||||
showError(prefix + err.message);
|
||||
|
||||
if (submitted) {
|
||||
await refreshQueue();
|
||||
} else {
|
||||
progress.classList.add('d-none');
|
||||
}
|
||||
} finally {
|
||||
submitButton.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
async function pollQueue() {
|
||||
await refreshQueue();
|
||||
setTimeout(pollQueue, 2500);
|
||||
}
|
||||
|
||||
pollQueue();
|
||||
|
||||
function showError(message) {
|
||||
errorBox.textContent = message;
|
||||
errorBox.classList.remove('d-none');
|
||||
}
|
||||
|
||||
function requireText() {
|
||||
if (!transcript.value.trim()) {
|
||||
showError('Сначала выполните распознавание или введите текст.');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async function copyText(text) {
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return;
|
||||
}
|
||||
|
||||
const area = document.createElement('textarea');
|
||||
area.value = text;
|
||||
area.style.position = 'fixed';
|
||||
area.style.opacity = '0';
|
||||
document.body.appendChild(area);
|
||||
area.select();
|
||||
|
||||
const copied = document.execCommand('copy');
|
||||
area.remove();
|
||||
|
||||
if (!copied) throw new Error('Браузер не разрешил копирование.');
|
||||
}
|
||||
|
||||
document.getElementById('copy-button').addEventListener('click', async () => {
|
||||
if (!requireText()) return;
|
||||
try {
|
||||
await copyText(transcript.value);
|
||||
errorBox.textContent = 'Текст скопирован.';
|
||||
errorBox.classList.remove('d-none');
|
||||
} catch (err) {
|
||||
showError(`Не удалось скопировать текст: ${err.message}`);
|
||||
}
|
||||
});
|
||||
|
||||
function download(name, content, type) {
|
||||
if (!content) {
|
||||
showError('Нет данных для экспорта.');
|
||||
return;
|
||||
}
|
||||
|
||||
const blob = new Blob([content], {type});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = name;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
document.getElementById('txt-button').addEventListener('click', () => {
|
||||
if (requireText()) download('transcript.txt', transcript.value, 'text/plain;charset=utf-8');
|
||||
});
|
||||
|
||||
function stamp(seconds) {
|
||||
const ms = Math.round(seconds * 1000);
|
||||
const h = String(Math.floor(ms / 3600000)).padStart(2, '0');
|
||||
const m = String(Math.floor(ms % 3600000 / 60000)).padStart(2, '0');
|
||||
const sec = String(Math.floor(ms % 60000 / 1000)).padStart(2, '0');
|
||||
const milli = String(ms % 1000).padStart(3, '0');
|
||||
return `${h}:${m}:${sec},${milli}`;
|
||||
}
|
||||
|
||||
document.getElementById('srt-button').addEventListener('click', () => {
|
||||
if (!requireText()) return;
|
||||
|
||||
const srt = lastSegments.map((x, i) =>
|
||||
`${i + 1}\n${stamp(x.start || 0)} --> ${stamp(x.end || x.start || 0)}\n${x.text || ''}`
|
||||
).join('\n\n');
|
||||
|
||||
if (!srt) {
|
||||
showError('Speaches не вернул сегменты с таймкодами. Доступен экспорт TXT и DOCX.');
|
||||
return;
|
||||
}
|
||||
|
||||
download('transcript.srt', srt, 'text/plain;charset=utf-8');
|
||||
});
|
||||
|
||||
document.getElementById('docx-button').addEventListener('click', async () => {
|
||||
if (!requireText()) return;
|
||||
|
||||
const button = document.getElementById('docx-button');
|
||||
button.disabled = true;
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/export/docx', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({text: transcript.value})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let message = 'Ошибка экспорта DOCX';
|
||||
try {
|
||||
const data = await response.json();
|
||||
message = data.detail || message;
|
||||
} catch {}
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'transcript.docx';
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('copy-button').addEventListener('click', async () => { await navigator.clipboard.writeText(transcript.value); });
|
||||
function download(name, content, type) { const blob = new Blob([content], {type}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download=name; a.click(); URL.revokeObjectURL(url); }
|
||||
document.getElementById('txt-button').addEventListener('click', () => download('transcript.txt', transcript.value, 'text/plain;charset=utf-8'));
|
||||
function stamp(seconds) { const ms=Math.round(seconds*1000); const h=String(Math.floor(ms/3600000)).padStart(2,'0'); const m=String(Math.floor(ms%3600000/60000)).padStart(2,'0'); const s=String(Math.floor(ms%60000/1000)).padStart(2,'0'); const milli=String(ms%1000).padStart(3,'0'); return `${h}:${m}:${s},${milli}`; }
|
||||
document.getElementById('srt-button').addEventListener('click', () => { const srt=lastSegments.map((x,i)=>`${i+1}\n${stamp(x.start||0)} --> ${stamp(x.end||x.start||0)}\n${x.text||''}`).join('\n\n'); if (!srt) { errorBox.textContent='Speaches не вернул сегменты с таймкодами. Доступен экспорт TXT и DOCX.'; errorBox.classList.remove('d-none'); return; } download('transcript.srt', srt, 'text/plain;charset=utf-8'); });
|
||||
document.getElementById('docx-button').addEventListener('click', async () => { try { const response = await fetch('/api/export/docx', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({text:transcript.value})}); if (!response.ok) { const data=await response.json(); throw new Error(data.detail || 'Ошибка экспорта DOCX'); } const blob=await response.blob(); const url=URL.createObjectURL(blob); const a=document.createElement('a'); a.href=url; a.download='transcript.docx'; a.click(); URL.revokeObjectURL(url); } catch(err) { errorBox.textContent=err.message; errorBox.classList.remove('d-none'); } });
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,640 @@
|
||||
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.helper_path = "/opt/ai-station-portal/ai-station-portal-admin"
|
||||
|
||||
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
|
||||
|
||||
try:
|
||||
await self._speaches_control("stop")
|
||||
except Exception:
|
||||
logger.exception("Failed to stop Speaches during queue shutdown")
|
||||
|
||||
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 _speaches_control(self, action: str):
|
||||
if action not in {"start", "stop"}:
|
||||
raise ValueError("Unsupported Speaches action")
|
||||
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
"sudo",
|
||||
"-n",
|
||||
self.helper_path,
|
||||
"speaches-control",
|
||||
action,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
|
||||
try:
|
||||
stdout, stderr = await asyncio.wait_for(
|
||||
process.communicate(),
|
||||
timeout=45,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
if process.returncode is None:
|
||||
process.kill()
|
||||
await process.communicate()
|
||||
raise RuntimeError(f"Speaches {action} helper timed out")
|
||||
except asyncio.CancelledError:
|
||||
if process.returncode is None:
|
||||
process.kill()
|
||||
await process.communicate()
|
||||
raise
|
||||
|
||||
if process.returncode != 0:
|
||||
detail = stderr.decode(errors="replace").strip()
|
||||
if not detail:
|
||||
detail = stdout.decode(errors="replace").strip()
|
||||
raise RuntimeError(
|
||||
f"Speaches {action} failed: {detail or process.returncode}"
|
||||
)
|
||||
|
||||
logger.info("Speaches container action completed: %s", action)
|
||||
|
||||
async def _ensure_speaches_running(self):
|
||||
await self._speaches_control("start")
|
||||
|
||||
deadline = asyncio.get_running_loop().time() + 90
|
||||
last_error = "health endpoint did not respond"
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
timeout=httpx.Timeout(5.0, connect=2.0)
|
||||
) as client:
|
||||
while asyncio.get_running_loop().time() < deadline:
|
||||
try:
|
||||
response = await client.get(
|
||||
f"{self.speaches_url}/health"
|
||||
)
|
||||
response.raise_for_status()
|
||||
logger.info("Speaches API is ready")
|
||||
return
|
||||
except httpx.HTTPError as exc:
|
||||
last_error = str(exc)
|
||||
|
||||
await asyncio.sleep(2)
|
||||
|
||||
raise RuntimeError(
|
||||
f"Speaches did not become ready within 90 seconds: {last_error}"
|
||||
)
|
||||
|
||||
async def _worker(self):
|
||||
while self.running:
|
||||
# No pending jobs: release the GPU before waiting for new work.
|
||||
if self.queue.empty():
|
||||
try:
|
||||
await self._speaches_control("stop")
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Failed to stop idle Speaches container"
|
||||
)
|
||||
|
||||
try:
|
||||
job_id = await self.queue.get()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
|
||||
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:
|
||||
# Free LLM VRAM first, then start the transcription service.
|
||||
await self._unload_llama_models()
|
||||
await self._ensure_speaches_running()
|
||||
|
||||
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)
|
||||
Reference in New Issue
Block a user