File size: 18,197 Bytes
8af7605
 
 
 
b48b1fc
8af7605
 
 
 
 
814ee46
b48b1fc
8af7605
 
 
 
 
b48b1fc
8af7605
 
 
 
 
 
 
b48b1fc
 
 
8af7605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
814ee46
 
 
 
8af7605
 
 
814ee46
 
 
 
 
8af7605
ca86176
8af7605
dd09568
2714d18
8af7605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b48b1fc
8af7605
 
b48b1fc
 
8af7605
 
 
 
b48b1fc
 
8af7605
 
 
b48b1fc
 
 
 
 
 
8af7605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b48b1fc
 
 
 
 
8af7605
b48b1fc
 
8af7605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2714d18
8af7605
 
 
2714d18
8af7605
 
 
 
 
 
 
 
 
 
c1bd0d2
 
c50a3d9
c1bd0d2
 
 
4803fd1
 
 
 
 
 
 
 
c1bd0d2
 
 
 
 
 
 
 
 
8af7605
c1bd0d2
 
8af7605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2714d18
 
 
6d1f4c8
 
8af7605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b48b1fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8af7605
 
 
 
 
fc46458
 
 
 
 
 
 
 
 
 
 
8af7605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
"""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")))