Spaces:
Runtime error

ollama_api / app.py
riki74's picture
Update app.py
b55b3df verified
Raw History Blame Contribute Delete
24.2 kB
"""
FastAPI server per orchestrare job OCR verso Ollama persistendo lo stato
nel database Postgres (Neon). Pensato per l'esecuzione su Hugging Face
Spaces: tutte le credenziali del DB vengono lette da variabili
ambiente (JOB_DB_* oppure DB_* come fallback) e la tabella `jobs` viene
inizializzata all'avvio se non esiste.
Questa versione non invia webhook: il client legge direttamente lo stato
dei job dal database.
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import time
import uuid
from collections import defaultdict
from datetime import datetime, timezone
from logging.handlers import RotatingFileHandler
from typing import Any, Dict, Tuple
import aiohttp
import psycopg2
from psycopg2 import errors
from fastapi import FastAPI, HTTPException
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - [Job %(job_id)s] - %(message)s",
handlers=[
RotatingFileHandler("server.log", maxBytes=10 * 1024 * 1024, backupCount=5),
logging.StreamHandler(),
],
)
class _JobIdFilter(logging.Filter):
"""Assicura che ogni log abbia un campo job_id per evitare KeyError."""
def filter(self, record: logging.LogRecord) -> bool: # pragma: no cover - filtraggio logging
if not hasattr(record, "job_id"):
record.job_id = "N/A"
return True
logger = logging.getLogger(__name__)
logger.addFilter(_JobIdFilter())
app = FastAPI(title="OCR Job Orchestrator (HF + Neon)")
OLLAMA_URL = os.getenv("OLLAMA_URL", "http://localhost:11434/api/generate")
OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "llama3.2-vision:11b-instruct-q4_K_M")
JOB_QUEUE: asyncio.Queue[Tuple[str, Dict[str, Any]]] = asyncio.Queue()
JOBS_STATE: defaultdict[str, Dict[str, Any]] = defaultdict(dict)
class ImageRequest(BaseModel):
prompt: str
images: list[str]
job_id: str | None = None
user_id: int | None = None
format_type: str | None = None
tag: str | None = None
roi_type: str | None = None
class Config:
extra = "allow"
def _utcnow() -> datetime:
return datetime.now(timezone.utc)
def truncate_images(payload: dict) -> dict:
"""Tronca il campo 'images' a 30 caratteri per il logging."""
truncated_payload = payload.copy()
if "images" in truncated_payload:
truncated_payload["images"] = [
img[:30] + "..." if len(img) > 30 else img for img in truncated_payload["images"]
]
return truncated_payload
def _get_env_config() -> dict:
"""Raccoglie le impostazioni del DB leggendo JOB_DB_* o i fallback DB_*."""
def _first(*keys: str, default: str | None = None):
for key in keys:
val = os.getenv(key)
if val:
return val
return default
host = _first("JOB_DB_HOST", "DB_HOST")
port_raw = _first("JOB_DB_PORT", "DB_PORT")
database = _first("JOB_DB_DATABASE", "DB_NAME", default="neondb")
user = _first("JOB_DB_USER", "DB_USER")
password = _first("JOB_DB_PASSWORD", "DB_PASSWORD")
sslmode = _first("JOB_DB_SSLMODE", "DB_SSLMODE", default="require")
try:
port = int(port_raw) if port_raw else 5432
except (TypeError, ValueError):
port = 5432
return {
"host": host,
"port": port,
"database": database,
"user": user,
"password": password,
"sslmode": sslmode,
}
def _normalize_roi_type(raw: str | None) -> str:
"""Restituisce una ROI normalizzata alle sole etichette attese."""
if not raw:
return "testo"
value = raw.strip().lower()
if value in {"tag", "tags"}:
return "tags"
if value in {"testo", "text", "markdown", "plain"}:
return "testo"
if value in {"data", "date"}:
return "data"
# Fallback per evitare valori "unknown" o personalizzati: consideriamo
# qualunque etichetta non riconosciuta come testo.
return "testo"
def _extract_roi_hint(request: ImageRequest) -> tuple[str | None, str]:
"""Estrae l'hint ROI più affidabile e la sua origine dal payload grezzo."""
# Considera prima i campi ufficiali supportati dal modello Pydantic
if request.roi_type:
return request.roi_type, "roi_type"
if request.tag:
return request.tag, "tag"
# Permettiamo anche campi extra (es. `roi`, `roi_hint`) che il client
# potrebbe inviare ma che altrimenti verrebbero ignorati. Diamo
# priorità a questi campi perché spesso contengono la ROI "data" che
# altrimenti verrebbe sovrascritta da un generico format_type="text".
raw_dict = request.__dict__
for alt_field in ("roi", "roi_hint", "roi_label"):
if alt_field in raw_dict and raw_dict.get(alt_field):
return raw_dict.get(alt_field), alt_field
if request.format_type:
return request.format_type, "format_type"
return None, "<default>"
def _connect_job_db(max_retries: int = 5, delay: int = 3):
"""Crea una connessione Postgres con retry basato sulle variabili ambiente."""
db_conf = _get_env_config()
for attempt in range(max_retries):
try:
conn = psycopg2.connect(
host=db_conf.get("host"),
port=db_conf.get("port"),
dbname=db_conf.get("database"),
user=db_conf.get("user"),
password=db_conf.get("password"),
sslmode=db_conf.get("sslmode"),
connect_timeout=10,
)
logger.info("Connessione al Job DB stabilita")
return conn
except Exception as exc: # pragma: no cover - retry per resilienza
logger.error("Tentativo di connessione %d fallito: %s", attempt + 1, exc)
if attempt < max_retries - 1:
time.sleep(delay)
else:
raise RuntimeError(
"Connessione al Job DB non riuscita. Verifica JOB_DB_HOST/JOB_DB_DATABASE/JOB_DB_USER."
) from exc
def _init_jobs_table_sync():
connection = None
try:
connection = _connect_job_db()
cursor = connection.cursor()
create_table_sql = """
CREATE TABLE IF NOT EXISTS jobs (
id SERIAL PRIMARY KEY,
job_id VARCHAR(255) UNIQUE,
prompt TEXT,
callback_url VARCHAR(1024),
request_payload JSONB,
status VARCHAR(50),
roi_type VARCHAR(50),
submitted_at TIMESTAMPTZ DEFAULT now(),
acknowledged_at TIMESTAMPTZ NULL,
started_at TIMESTAMPTZ NULL,
completed_at TIMESTAMPTZ NULL,
execution_time DOUBLE PRECISION NULL,
result_payload JSONB NULL,
error_message TEXT NULL
);
CREATE INDEX IF NOT EXISTS idx_jobs_status ON jobs(status);
CREATE INDEX IF NOT EXISTS idx_jobs_roi_type ON jobs(roi_type);
CREATE INDEX IF NOT EXISTS idx_jobs_completed_at ON jobs(completed_at);
ALTER TABLE jobs ADD COLUMN IF NOT EXISTS roi_type VARCHAR(50);
ALTER TABLE jobs ADD COLUMN IF NOT EXISTS acknowledged_at TIMESTAMPTZ NULL;
ALTER TABLE jobs ADD COLUMN IF NOT EXISTS started_at TIMESTAMPTZ NULL;
ALTER TABLE jobs ADD COLUMN IF NOT EXISTS completed_at TIMESTAMPTZ NULL;
ALTER TABLE jobs ADD COLUMN IF NOT EXISTS execution_time DOUBLE PRECISION NULL;
"""
cursor.execute(create_table_sql)
connection.commit()
logger.info("Tabella jobs inizializzata/aggiornata")
finally:
if connection:
connection.close()
def _insert_job_sync(
job_id: str,
prompt: str,
callback_url: str | None,
request_payload: dict,
roi_type: str | None,
acknowledged_at: datetime,
):
connection = None
try:
connection = _connect_job_db()
cursor = connection.cursor()
insert_sql = (
"""
INSERT INTO jobs (job_id, prompt, callback_url, request_payload, status, roi_type, acknowledged_at)
VALUES (%s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (job_id) DO UPDATE
SET prompt = EXCLUDED.prompt,
callback_url = EXCLUDED.callback_url,
request_payload = EXCLUDED.request_payload,
status = 'queued',
roi_type = EXCLUDED.roi_type,
acknowledged_at = COALESCE(EXCLUDED.acknowledged_at, jobs.acknowledged_at),
error_message = NULL,
result_payload = NULL,
started_at = NULL,
completed_at = NULL,
execution_time = NULL,
submitted_at = COALESCE(jobs.submitted_at, now())
"""
)
params = (
job_id,
prompt,
callback_url,
json.dumps(request_payload),
"pending",
roi_type,
acknowledged_at,
)
cursor.execute(insert_sql, params)
connection.commit()
logger.info("Job %s inserito/aggiornato su DB", job_id)
finally:
if connection:
connection.close()
def _update_job_sync(
*,
job_id: str,
status: str,
result_payload: dict | None = None,
error_message: str | None = None,
acknowledged_at: datetime | None = None,
started_at: datetime | None = None,
completed_at: datetime | None = None,
execution_time: float | None = None,
):
connection = None
try:
connection = _connect_job_db()
cursor = connection.cursor()
update_sql = """
UPDATE jobs
SET status = %s,
result_payload = %s,
error_message = %s,
acknowledged_at = COALESCE(%s, acknowledged_at),
started_at = COALESCE(%s, started_at),
completed_at = COALESCE(%s, completed_at),
execution_time = COALESCE(%s, execution_time)
WHERE job_id = %s
"""
params = (
status,
json.dumps(result_payload) if result_payload is not None else None,
error_message,
acknowledged_at,
started_at,
completed_at,
execution_time,
job_id,
)
cursor.execute(update_sql, params)
connection.commit()
finally:
if connection:
connection.close()
def _get_job_sync(job_id: str):
connection = None
try:
connection = _connect_job_db()
cursor = connection.cursor()
select_sql = """
SELECT job_id, prompt, callback_url, request_payload, status, roi_type, submitted_at, acknowledged_at,
started_at, completed_at, execution_time, result_payload, error_message
FROM jobs
WHERE job_id = %s
"""
cursor.execute(select_sql, (job_id,))
row = cursor.fetchone()
columns = [col[0] for col in cursor.description] if cursor.description else []
return dict(zip(columns, row)) if row else None
finally:
if connection:
connection.close()
def _log_db_target():
db_conf = _get_env_config()
logger.info(
"Job DB target resolved as host=%s port=%s database=%s sslmode=%s",
db_conf.get("host") or "<unset>",
db_conf.get("port") or "<unset>",
db_conf.get("database") or "<unset>",
db_conf.get("sslmode") or "default",
extra={"job_id": "N/A"},
)
def _update_ocr_results_sync(job_id: str, result_text: str) -> None:
"""Aggiorna le tabelle pages/ocr_results/keywords dopo completamento OCR.
Args:
job_id: ID del job OCR completato
result_text: Testo estratto dall'OCR
"""
connection = None
try:
connection = _connect_job_db()
cursor = connection.cursor()
# Trova il page_id associato a questo job_id
cursor.execute(
"""
SELECT page_id
FROM ocr_results
WHERE ocr_data->'ocr_jobs'->>'data' = %s
OR ocr_data->'ocr_jobs'->>'tags' = %s
OR ocr_data->'ocr_jobs'->>'testo' = %s
""",
(job_id, job_id, job_id)
)
row = cursor.fetchone()
if not row:
logger.warning("Nessun page_id trovato per job_id %s in ocr_results", job_id, extra={"job_id": job_id})
return
page_id = row[0]
# Recupera i dati OCR esistenti
cursor.execute("SELECT ocr_data FROM ocr_results WHERE page_id = %s", (page_id,))
ocr_row = cursor.fetchone()
if not ocr_row:
logger.error("Page_id %s non trovato in ocr_results", page_id, extra={"job_id": job_id})
return
ocr_data = json.loads(ocr_row[0]) if isinstance(ocr_row[0], str) else ocr_row[0]
ocr_jobs = ocr_data.get("ocr_jobs", {})
# Mappa job_id al campo corretto (date/tags/text)
field_mapping = {}
if "data" in ocr_jobs:
field_mapping[ocr_jobs["data"]] = "date"
if "tags" in ocr_jobs:
field_mapping[ocr_jobs["tags"]] = "tags"
if "testo" in ocr_jobs:
field_mapping[ocr_jobs["testo"]] = "text"
field = field_mapping.get(job_id)
if not field:
logger.warning(
"Job_id %s non mappato a nessun campo (ocr_jobs: %s)",
job_id,
list(ocr_jobs.keys()),
extra={"job_id": job_id}
)
return
# Aggiorna ocr_data in ocr_results
ocr_data[field] = result_text
cursor.execute(
"UPDATE ocr_results SET ocr_data = %s WHERE page_id = %s",
(json.dumps(ocr_data), page_id)
)
# Aggiorna il campo corrispondente nella tabella pages
cursor.execute(
f"UPDATE pages SET {field} = %s WHERE image_path = (SELECT archived_image FROM ocr_results WHERE page_id = %s)",
(result_text, page_id)
)
# Se è tags o text, aggiorna anche la tabella keywords
if field in ["tags", "text"]:
cursor.execute(
"SELECT id FROM pages WHERE image_path = (SELECT archived_image FROM ocr_results WHERE page_id = %s)",
(page_id,)
)
page_db_row = cursor.fetchone()
if page_db_row:
page_db_id = page_db_row[0]
# Estrai keywords dal testo
keywords = set(result_text.split(", ") if field == "tags" else result_text.split())
for keyword in keywords:
keyword = keyword.strip()
if keyword:
cursor.execute(
"INSERT INTO keywords (page_id, keyword) VALUES (%s, %s)",
(page_db_id, keyword)
)
connection.commit()
logger.info("Dati OCR aggiornati per page_id %s, job_id %s, campo %s", page_id, job_id, field, extra={"job_id": job_id})
except Exception as exc:
logger.error("Errore aggiornamento dati OCR: %s", exc, exc_info=True, extra={"job_id": job_id})
if connection:
connection.rollback()
finally:
if connection:
connection.close()
async def _init_jobs_table():
await asyncio.to_thread(_init_jobs_table_sync)
async def _insert_job(
job_id: str, prompt: str, callback_url: str | None, request_payload: dict, roi_type: str | None
):
await asyncio.to_thread(
_insert_job_sync, job_id, prompt, callback_url, request_payload, roi_type, _utcnow()
)
async def _update_job(**kwargs):
await asyncio.to_thread(_update_job_sync, **kwargs)
async def _get_job(job_id: str):
return await asyncio.to_thread(_get_job_sync, job_id)
async def _update_ocr_results(job_id: str, result_text: str):
"""Versione async di _update_ocr_results_sync."""
await asyncio.to_thread(_update_ocr_results_sync, job_id, result_text)
async def process_job(job_id: str, payload: dict):
start_time = _utcnow()
JOBS_STATE[job_id]["processing_start_time"] = start_time
JOBS_STATE[job_id]["status"] = "processing"
logger.info("Inizio elaborazione job dalla coda", extra={"job_id": job_id})
await _update_job(
job_id=job_id,
status="processing",
acknowledged_at=JOBS_STATE[job_id].get("acknowledged_at"),
started_at=start_time,
)
async with aiohttp.ClientSession() as session:
try:
timeout = aiohttp.ClientTimeout(total=21600)
async with session.post(OLLAMA_URL, json=payload, timeout=timeout) as response:
response.raise_for_status()
content_type = response.headers.get("Content-Type", "")
logger.debug("Content-Type ricevuto: %s", content_type, extra={"job_id": job_id})
logger.debug("Intestazioni ricevute: %s", dict(response.headers), extra={"job_id": job_id})
if "application/x-ndjson" in content_type:
text = await response.text()
logger.debug("Risposta NDJSON grezza: %s", text, extra={"job_id": job_id})
result_lines = [
json.loads(line).get("response", "") for line in text.splitlines() if line.strip()
]
result = "".join(result_lines)
else:
result = await response.json()
logger.debug(
"Risposta JSON grezza: %s", json.dumps(result, indent=4), extra={"job_id": job_id}
)
end_time = _utcnow()
JOBS_STATE[job_id]["processing_end_time"] = end_time
JOBS_STATE[job_id]["status"] = "completed"
JOBS_STATE[job_id]["result"] = result if isinstance(result, str) else result.get("response", "")
execution_time = (end_time - start_time).total_seconds()
await _update_job(
job_id=job_id,
status="completed",
result_payload={"response": JOBS_STATE[job_id]["result"]},
error_message=None,
acknowledged_at=JOBS_STATE[job_id].get("acknowledged_at"),
started_at=start_time,
completed_at=end_time,
execution_time=execution_time,
)
# ✅ FIX: Aggiorna tabelle pages/ocr_results/keywords con i risultati OCR
try:
await _update_ocr_results(job_id, JOBS_STATE[job_id]["result"])
except Exception as exc:
logger.error(
"Errore aggiornamento tabelle OCR per job %s: %s",
job_id,
exc,
extra={"job_id": job_id}
)
result_preview = str(JOBS_STATE[job_id]["result"])
if len(result_preview) > 200:
result_preview = result_preview[:200] + "..."
logger.info(
"Job completato con risposta: %s",
result_preview,
extra={"job_id": job_id},
)
except asyncio.TimeoutError:
JOBS_STATE[job_id]["status"] = "timeout"
JOBS_STATE[job_id]["error"] = "Processing timed out"
logger.error("Timeout elaborazione job", extra={"job_id": job_id})
await _update_job(
job_id=job_id,
status="timeout",
error_message="Processing timed out",
acknowledged_at=JOBS_STATE[job_id].get("acknowledged_at"),
started_at=start_time,
completed_at=_utcnow(),
)
except Exception as exc: # pragma: no cover - protezione difensiva
JOBS_STATE[job_id]["status"] = "failed"
JOBS_STATE[job_id]["error"] = str(exc)
logger.error("Errore in process_job: %s", exc, exc_info=True, extra={"job_id": job_id})
await _update_job(
job_id=job_id,
status="failed",
error_message=str(exc),
acknowledged_at=JOBS_STATE[job_id].get("acknowledged_at"),
started_at=start_time,
completed_at=_utcnow(),
)
async def process_jobs_from_queue():
while True:
job_id, payload = await JOB_QUEUE.get()
await process_job(job_id, payload)
JOB_QUEUE.task_done()
logger.debug("Job %s completato, task rimosso dalla coda", job_id, extra={"job_id": job_id})
@app.post("/api/submit")
async def submit_job_endpoint(request: ImageRequest):
logger.info("Payload ricevuto: %s", request.dict(), extra={"job_id": "N/A"})
job_id = request.job_id or str(uuid.uuid4())
acknowledged_at = _utcnow()
roi_hint_raw, roi_hint_source = _extract_roi_hint(request)
roi_type = _normalize_roi_type(roi_hint_raw)
# Manteniamo sia il format_type richiesto dal client sia il valore
# normalizzato da usare verso Ollama/DB per evitare di perdere ROI
# come "data" quando il client imposta format_type generici.
requested_format_type = request.format_type
format_type = roi_type if roi_type else requested_format_type
logger.info(
"ROI hint=%s (source=%s) normalizzato a=%s", roi_hint_raw, roi_hint_source, roi_type, extra={"job_id": job_id}
)
payload = {
"model": OLLAMA_MODEL,
"prompt": request.prompt,
"images": [img.split(",")[1] if img.startswith("data:image") else img for img in request.images],
"format_type": format_type,
"user_id": request.user_id,
}
if requested_format_type and requested_format_type != format_type:
payload["format_type_requested"] = requested_format_type
if roi_type:
payload["roi_type"] = roi_type
if roi_hint_raw:
payload["roi_hint_raw"] = roi_hint_raw
payload["roi_hint_source"] = roi_hint_source
JOBS_STATE[job_id] = {
"status": "queued",
"result": None,
"error": None,
"start_time": time.time(),
"user_id": request.user_id,
"acknowledged_at": acknowledged_at,
}
try:
await _insert_job(job_id, request.prompt, None, payload, roi_type)
await _update_job(job_id=job_id, status="queued", acknowledged_at=acknowledged_at)
except errors.UniqueViolation:
# Non dovrebbe capitare grazie all'UPSERT, ma gestiamo comunque la violazione.
logger.warning(
"Job %s già presente, proseguo aggiornando lo stato queued", job_id, extra={"job_id": job_id}
)
await _update_job(job_id=job_id, status="queued", acknowledged_at=acknowledged_at)
except Exception as exc:
logger.error("Impossibile salvare il job su DB: %s", exc, extra={"job_id": job_id})
raise HTTPException(status_code=500, detail="Errore nella persistenza del job")
await JOB_QUEUE.put((job_id, payload))
logger.info(
"Job queued con payload: %s", json.dumps(truncate_images(payload), indent=4), extra={"job_id": job_id}
)
return {"job_id": job_id, "status": "queued", "acknowledged_at": acknowledged_at.isoformat()}
@app.get("/api/result/{job_id}")
async def get_result(job_id: str):
job_info = await _get_job(job_id)
if not job_info:
logger.warning("Job non trovato", extra={"job_id": job_id})
raise HTTPException(status_code=404, detail="Job not found")
logger.debug("Richiesta risultato: %s", json.dumps(job_info, default=str, indent=4), extra={"job_id": job_id})
return jsonable_encoder(job_info)
@app.get("/health")
async def healthcheck():
"""Endpoint di health-check per ambienti come Hugging Face Spaces."""
return {"status": "ok"}
@app.on_event("startup")
async def startup_event():
_log_db_target()
await _init_jobs_table()
asyncio.create_task(process_jobs_from_queue())
if __name__ == "__main__":
import uvicorn
logger.info("Avvio del server OCR su porta 7860", extra={"job_id": "N/A"})
uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", "7860")))