Add transcription library and Llama GPU management

This commit is contained in:
2026-11-22 23:14:14 +03:00
parent 85929c9054
commit 5c5827d241
3 changed files with 1331 additions and 65 deletions
+115 -38
View File
@@ -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),
@@ -617,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")