pixrick / app.py
Algorick's picture
be231385401e
fc46458 verified
Raw History Blame Contribute Delete
18.2 kB
"""PixRick online: l'interfaccia è nostra, il motore gira su Gradio perché ZeroGPU lo richiede."""
from __future__ import annotations
import base64
import html
import io
import json
import logging
import os
import re
import secrets
import tempfile
import threading
import time
from pathlib import Path
from typing import Any, Iterator
from urllib.parse import urlencode
try:
import spaces
except ImportError: # in locale, senza ZeroGPU
spaces = None
import gradio as gr
import httpx
from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from PIL import Image
from pixrick import config, marking, vector
from pixrick.core import (
Job,
JobRequest,
RequestError,
TemplateBook,
clean_image,
extract_style,
plan,
prompt_for,
source_medium,
)
from pixrick.runner import Runner, models
from pixrick.safety import SafetyError, check_prompt
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s")
log = logging.getLogger("pixrick")
BOOK = TemplateBook.load()
OUT_DIR = Path(tempfile.gettempdir()) / "pixrick"
OUT_DIR.mkdir(parents=True, exist_ok=True)
def gpu(duration: Any):
if spaces is None:
return lambda fn: fn
return spaces.GPU(duration=duration)
if not config.FAKE_ENGINE:
models()
# ---------- motore ----------
def _open(path: str | None) -> Image.Image | None:
if not path:
return None
if os.path.getsize(path) > config.MAX_UPLOAD_BYTES:
raise RequestError("Immagine troppo pesante (massimo 25 MB).")
try:
with Image.open(path) as im:
im.load()
return im.copy()
except Exception as exc: # noqa: BLE001
raise RequestError("Uno dei file non è un'immagine leggibile.") from exc
def _meta(job: Job, model_key: str, image: Image.Image, seed: int, index: int) -> dict[str, Any]:
req = job.request
combo = job.refine and model_key == "z-image" and req.mode != config.REFINE_MODE
return {
"lavoro": job.id,
"modalita": req.mode,
"prompt": req.prompt,
"prompt_finale": prompt_for(job, model_key),
"template": req.templates[0] if req.templates else "libero",
"stili": req.templates,
"campi": req.fields,
"riferimenti": req.refs,
"maschera": req.mask,
"formato": req.aspect,
"larghezza": image.width,
"altezza": image.height,
"qualita": req.quality,
"passi": job.steps[model_key],
"fedelta": req.fidelity if req.mode == "ristila" and model_key == "z-image" and not job.refine else None,
"fedelta_auto": job.fidelity_auto,
"nota": job.note,
"rifinita": job.refine and model_key == "z-image",
"seed": seed,
"modello": model_key,
"modello_nome": "Klein + Z-Image" if combo
else "Rifinita con Z-Image" if req.mode == config.REFINE_MODE
else (config.MODELS.get(model_key) or config.TOOLS[model_key])["nome"],
"trasparente": image.mode == "RGBA",
"vista": config.VIEWS[index % len(config.VIEWS)][0] if req.mode == config.VIEWS_MODE else None,
"creata": time.strftime("%Y-%m-%d %H:%M:%S"),
"generata_con_ai": True,
}
_QUOTA_TEXT = re.compile(r"quota|runs limit", re.I)
_QUOTA_ERRORS = {"ZeroGPUQuotaExceeded", "ZeroGPUIllegalDuration", "ZeroGPUPendingCreditsExceeded"}
def _friendly(exc: BaseException) -> str:
if isinstance(exc, (RequestError, SafetyError)):
return str(exc)
name = type(exc).__name__
if name in _QUOTA_ERRORS or (isinstance(exc, gr.Error) and _QUOTA_TEXT.search(str(exc))):
return str(exc)
if name == "ZeroGPUQueueTimeout":
return "Ci sono troppe persone in coda in questo momento. Riprova tra un minuto."
text = str(exc)
if "out of memory" in text.lower() or "NVML_SUCCESS" in text:
return "La GPU è piena in questo momento. Riprova tra poco o scegli meno immagini."
log.error("Lavoro non riuscito", exc_info=exc)
return "Qualcosa è andato storto durante la generazione. Riprova."
def _estimate(job: Job, *_: Any) -> int:
return job.gpu_seconds()
@gpu(_estimate)
def _work(job: Job, refs: list[Image.Image], mask: Image.Image | None, book: TemplateBook) -> Iterator[tuple[dict, list[str]]]:
runner = Runner(job, refs, mask, book)
outcome: dict[str, Any] = {}
def target() -> None:
try:
outcome["images"] = runner.run()
except BaseException as exc: # noqa: BLE001
outcome["error"] = exc
thread = threading.Thread(target=target, daemon=True)
thread.start()
while thread.is_alive():
thread.join(0.4)
yield job.public(), []
if "error" in outcome:
raise gr.Error(_friendly(outcome["error"]), print_exception=False)
folder = OUT_DIR / job.id
folder.mkdir(parents=True, exist_ok=True)
files: list[str] = []
for index, (model_key, image, seed) in enumerate(outcome["images"]):
meta = _meta(job, model_key, image, seed, index)
path = folder / f"{index:02d}_{model_key}_{seed}.png"
path.write_bytes(marking.to_png(image, meta))
job.results.append(meta)
files.append(str(path))
yield job.public(), files
def genera(richiesta: str, immagini: list[str] | None, maschera: str | None) -> Iterator[tuple[dict, list[str]]]:
"""Valida senza GPU (gli errori non costano quota), poi passa il lavoro alla GPU."""
try:
data = json.loads(richiesta or "{}")
if not isinstance(data, dict):
raise RequestError("Richiesta non valida.")
book = BOOK.with_user(data.get("stili_utente") or [])
req = JobRequest.from_payload(data)
refs = [clean_image(img) for img in (_open(p) for p in (immagini or [])) if img is not None]
mask = _open(maschera)
job = plan(req, refs, mask, book)
Runner(job, refs, mask, book).translate()
except (RequestError, SafetyError, json.JSONDecodeError) as exc:
raise gr.Error(str(exc) if not isinstance(exc, json.JSONDecodeError) else "Richiesta non valida.", print_exception=False)
except Exception as exc: # noqa: BLE001
raise gr.Error(_friendly(exc), print_exception=False)
yield job.public(), []
yield from _work(job, refs, mask, book)
@gpu(20)
def _write_gpu(kind: str, text: str) -> str:
return models().write(kind, text)
def _write(kind: str, text: str) -> str:
if kind in config.TRANSLATOR_REPOS:
return models().write(kind, text)
return _write_gpu(kind, text)
def scrivi(tipo: str, testo: str) -> str:
"""Traduce, migliora o riassume lo stile di un prompt."""
testo = (testo or "")[: config.MAX_PROMPT_CHARS]
if tipo not in ("traduci", "migliora", "migliora_modifica", "in_italiano", "stile"):
raise gr.Error("Operazione non valida.", print_exception=False)
if not testo.strip():
return ""
try:
check_prompt(testo)
except SafetyError as exc:
raise gr.Error(str(exc), print_exception=False)
try:
out = _write(tipo, testo)
if tipo in ("migliora", "migliora_modifica"):
check_prompt(out)
return out
except SafetyError as exc:
raise gr.Error(str(exc), print_exception=False)
except Exception as exc: # noqa: BLE001
raise gr.Error(_friendly(exc), print_exception=False)
@gpu(20)
def _improve_gpu(text: str, kind: str) -> str:
return models().write(kind, text)
def _improve(text: str, kind: str) -> tuple[str, str]:
english = _improve_gpu(text, kind)
return english, models().write("in_italiano", english)
def migliora(testo: str, modalita: str) -> dict[str, str]:
"""Da un'idea a un prompt ricco, con la versione italiana da rileggere."""
testo = (testo or "")[: config.MAX_PROMPT_CHARS]
if not testo.strip():
raise gr.Error("Scrivi prima un'idea da migliorare.", print_exception=False)
try:
check_prompt(testo)
english, italian = _improve(testo, "migliora_modifica" if modalita == "modifica" else "migliora")
check_prompt(english)
except SafetyError as exc:
raise gr.Error(str(exc), print_exception=False)
except Exception as exc: # noqa: BLE001
raise gr.Error(_friendly(exc), print_exception=False)
return {"prompt": english, "italiano": italian}
with gr.Blocks(title="PixRick · motore", analytics_enabled=False, delete_cache=(300, 900)) as motore:
gr.Markdown("Questo è il motore di PixRick. L'app è nella pagina principale.")
with gr.Column(visible=False):
richiesta = gr.Textbox()
immagini = gr.File(file_count="multiple", type="filepath")
maschera = gr.File(type="filepath")
stato = gr.JSON()
risultati = gr.File(file_count="multiple")
tipo = gr.Textbox()
testo = gr.Textbox()
scritto = gr.Textbox()
risposta = gr.JSON()
go = gr.Button()
go.click(genera, [richiesta, immagini, maschera], [stato, risultati], api_name="genera", show_progress="hidden")
gr.Button().click(scrivi, [tipo, testo], scritto, api_name="scrivi", concurrency_limit=4)
gr.Button().click(migliora, [testo, tipo], risposta, api_name="migliora", concurrency_limit=4)
motore.queue(default_concurrency_limit=6, max_size=80)
# ---------- pagina e servizi leggeri (senza GPU) ----------
app = FastAPI(title="PixRick", docs_url=None, redoc_url=None, openapi_url=None)
WEB = config.WEB_DIR
# Ogni avvio ha la sua versione: dopo un aggiornamento il browser non riusa script e stili vecchi.
_VERSION = str(int(time.time()))
_BEACON = os.environ.get("PIXRICK_CF_BEACON", "251a07612a5f420dbdfa174b505faa77").strip()
_INDEX = re.sub(r'((?:src|href)="/web/[\w/.-]+\.(?:js|css))"', rf'\1?v={_VERSION}"', (WEB / "index.html").read_text(encoding="utf-8"))
if re.fullmatch(r"[0-9a-f]{32}", _BEACON):
# Cloudflare Web Analytics: conta le visite senza cookie e senza dati personali.
_INDEX = _INDEX.replace(
"</body>",
f'<script defer src="https://static.cloudflareinsights.com/beacon.min.js" data-cf-beacon=\'{{"token": "{_BEACON}"}}\'></script>\n</body>',
)
@app.middleware("http")
async def _fresh_assets(request: Request, call_next: Any) -> Response:
response = await call_next(request)
path = request.url.path
if path.startswith("/web/") and path.endswith((".js", ".css", ".json")) and "/vendor/" not in path:
response.headers["Cache-Control"] = "no-cache"
return response
@app.get("/", include_in_schema=False)
def home() -> HTMLResponse:
return HTMLResponse(_INDEX, headers={"Cache-Control": "no-cache"})
@app.get("/guida", include_in_schema=False)
@app.get("/guida/", include_in_schema=False)
def guide() -> FileResponse:
return FileResponse(WEB / "guida" / "index.html", headers={"Cache-Control": "no-cache"})
REPORT_URL = "https://huggingface.co/spaces/algorick/pixrick/discussions"
def _legal(name: str) -> HTMLResponse:
owner = html.escape(os.environ.get("PIXRICK_OWNER", "").strip() or "il gestore di PixRick")
mail = os.environ.get("PIXRICK_CONTACT", "").strip()
contact = (
f'<a href="mailto:{html.escape(mail)}">{html.escape(mail)}</a>'
if mail
else f'<a href="{REPORT_URL}" target="_blank" rel="noopener">{REPORT_URL.removeprefix("https://")}</a>'
)
page = (WEB / "legal" / f"{name}.html").read_text(encoding="utf-8")
return HTMLResponse(page.replace("{{titolare}}", owner).replace("{{contatto}}", contact))
@app.get("/privacy", include_in_schema=False)
def privacy() -> HTMLResponse:
return _legal("privacy")
@app.get("/termini", include_in_schema=False)
@app.get("/terms", include_in_schema=False)
def terms() -> HTMLResponse:
return _legal("termini")
@app.get("/guida.pdf", include_in_schema=False)
def guide_pdf() -> FileResponse:
return FileResponse(WEB / "guida" / "PixRick-Guida.pdf", media_type="application/pdf", filename="PixRick-Guida.pdf", content_disposition_type="inline")
@app.get("/sw.js", include_in_schema=False)
def service_worker() -> FileResponse:
return FileResponse(WEB / "sw.js", media_type="text/javascript", headers={"Cache-Control": "no-cache", "Service-Worker-Allowed": "/"})
@app.get("/manifest.webmanifest", include_in_schema=False)
def manifest() -> FileResponse:
return FileResponse(WEB / "manifest.webmanifest", media_type="application/manifest+json")
@app.get("/favicon.ico", include_in_schema=False)
def favicon() -> FileResponse:
return FileResponse(WEB / "icons" / "favicon.ico")
# ---------- accesso facoltativo con Hugging Face ----------
# Il token resta nel browser di chi accede: serve solo a far contare la GPU sulla sua quota personale.
_OAUTH_STATE = "pixrick_oauth_state"
def _oauth() -> dict[str, str] | None:
keys = ("OAUTH_CLIENT_ID", "OAUTH_CLIENT_SECRET", "OPENID_PROVIDER_URL", "SPACE_HOST")
if not all(os.environ.get(k) for k in keys):
return None
return {k: os.environ[k] for k in keys}
def _redirect_uri(conf: dict[str, str]) -> str:
return f"https://{conf['SPACE_HOST'].split(',')[0]}/login/callback"
@app.get("/accedi", include_in_schema=False)
def login() -> Response:
conf = _oauth()
if conf is None:
return RedirectResponse("/#accesso=non-disponibile")
state = secrets.token_urlsafe(24)
query = urlencode({
"client_id": conf["OAUTH_CLIENT_ID"],
"redirect_uri": _redirect_uri(conf),
"scope": os.environ.get("OAUTH_SCOPES", "openid profile"),
"state": state,
"response_type": "code",
})
response = RedirectResponse(f"{conf['OPENID_PROVIDER_URL']}/oauth/authorize?{query}")
response.set_cookie(_OAUTH_STATE, state, max_age=600, httponly=True, secure=True, samesite="lax")
return response
@app.get("/login/callback", include_in_schema=False)
def login_callback(request: Request, code: str = "", state: str = "", error: str = "") -> Response:
conf = _oauth()
expected = request.cookies.get(_OAUTH_STATE)
if conf is None or error or not code or not expected or not secrets.compare_digest(state, expected):
return RedirectResponse("/#accesso=annullato")
try:
with httpx.Client(timeout=15) as client:
token = client.post(
f"{conf['OPENID_PROVIDER_URL']}/oauth/token",
data={"grant_type": "authorization_code", "code": code, "redirect_uri": _redirect_uri(conf), "client_id": conf["OAUTH_CLIENT_ID"]},
auth=(conf["OAUTH_CLIENT_ID"], conf["OAUTH_CLIENT_SECRET"]),
).raise_for_status().json()
user = client.get(
f"{conf['OPENID_PROVIDER_URL']}/oauth/userinfo",
headers={"Authorization": f"Bearer {token['access_token']}"},
).raise_for_status().json()
except Exception: # noqa: BLE001
log.warning("Accesso con Hugging Face non riuscito", exc_info=True)
return RedirectResponse("/#accesso=errore")
session = {
"token": token["access_token"],
"scade": int(time.time() + int(token.get("expires_in") or 28800)) * 1000,
"utente": user.get("preferred_username") or "",
"nome": user.get("name") or user.get("preferred_username") or "",
"foto": user.get("picture") or "",
}
payload = base64.urlsafe_b64encode(json.dumps(session).encode()).decode().rstrip("=")
response = RedirectResponse(f"/#accesso={payload}")
response.delete_cookie(_OAUTH_STATE)
return response
@app.get("/robots.txt", include_in_schema=False)
def robots() -> Response:
return Response("User-agent: *\nAllow: /\nDisallow: /motore/\n", media_type="text/plain")
@app.post("/api/errore", include_in_schema=False)
async def browser_error(request: Request) -> Response:
"""Diagnostica: gli errori del motore visti dal browser finiscono nel log, senza prompt né immagini."""
try:
data = json.loads((await request.body())[:1000] or b"{}")
log.warning("Errore nel browser: %s", str(data.get("m", ""))[:400])
except Exception: # noqa: BLE001
pass
return Response(status_code=204)
@app.get("/api/templates")
def templates() -> JSONResponse:
return JSONResponse({"template": BOOK.all()}, headers={"Cache-Control": "public, max-age=600"})
@app.post("/api/styles/extract")
def styles_extract(data: dict[str, Any]) -> JSONResponse:
text = str(data.get("prompt") or "")[: config.MAX_PROMPT_CHARS]
book = BOOK.with_user(data.get("stili_utente") or [])
ids = [str(i) for i in (data.get("stili") or []) if isinstance(i, str)]
if not text.strip() and not ids:
raise HTTPException(400, "Questa immagine non ha un prompt da cui partire.")
return JSONResponse({"testo": extract_style(text, book.clean_ids(ids), book)})
@app.post("/api/vectorize")
async def vectorize(
file: UploadFile = File(...), stile: str = Form("colori"), trasparente: bool = Form(True)
) -> JSONResponse:
data = await file.read(config.MAX_UPLOAD_BYTES + 1)
if len(data) > config.MAX_UPLOAD_BYTES:
raise HTTPException(413, "Immagine troppo pesante (massimo 25 MB).")
with tempfile.NamedTemporaryFile(suffix=".png", dir=OUT_DIR) as tmp:
try:
with Image.open(io.BytesIO(data)) as im:
im.load()
im.save(tmp.name, "PNG")
medium = source_medium(im)
result = vector.vectorize(Path(tmp.name), stile, trasparente)
except Exception as exc: # noqa: BLE001
log.exception("Vettorizzazione non riuscita")
raise HTTPException(400, "Non sono riuscito a vettorizzare questa immagine.") from exc
result["foto"] = medium == "foto"
return JSONResponse(result)
app.mount("/web", StaticFiles(directory=WEB), name="web")
app = gr.mount_gradio_app(app, motore, path="/motore", ssr_mode=False)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "7860")))