diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..b9b29da3ffde92d684a86af6281fc7c395e7e22d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,22 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +web/guida/PixRick-Guida.pdf filter=lfs diff=lfs merge=lfs -text +web/guida/img/anime.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/locandina-lineup.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/s-detail.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/s-gallery.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/s-loc-a.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/s-loc-b.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/s-loc-c.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/s-loc-pick.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/s-ristila.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/s-studio.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/s-tip.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/s-vector.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/s-zona.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/s-zona2.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/soglia.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/st-fumetto.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/tpl-griglia.jpg filter=lfs diff=lfs merge=lfs -text +web/guida/img/volpe-scontornata.png filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..657226302fb0829c48f0bc310e6d4ab2f24304a4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +__pycache__/ +*.pyc +.venv/ +node_modules/ diff --git a/README.md b/README.md index c131ced99b186a279d021ad09ff0d425eaa11dcf..2d7451e67d900b34fb44ca02de51f03675033dc0 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,28 @@ --- -title: Pixrick -emoji: 🌖 -colorFrom: yellow -colorTo: gray +title: PixRick +emoji: 🎞️ +colorFrom: indigo +colorTo: pink sdk: gradio sdk_version: 6.32.0 -python_version: '3.12' +python_version: "3.12" app_file: app.py +hf_oauth: true +startup_duration_timeout: 1h +preload_from_hub: + - Tongyi-MAI/Z-Image-Turbo + - black-forest-labs/FLUX.2-klein-4B + - ZhengPeng7/BiRefNet + - Qwen/Qwen3-1.7B + - Falconsai/nsfw_image_detection +short_description: Studio di immagini AI con Z-Image e FLUX.2 Klein pinned: false -short_description: 'Studio di immagini AI: crea, ristila, modifica e componi loc' --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# PixRick + +Studio di immagini AI: crea, ristila, modifica una zona, continua una storia, ingrandisci, scontorna, vettorizza e componi locandine. + +Gira su Z-Image Turbo e FLUX.2 Klein 4B (licenza Apache 2.0). Le immagini restano nel browser di chi le crea: il server non conserva né immagini né prompt. + +Ogni immagine generata porta metadati che la dichiarano creata con AI e una filigrana invisibile. diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..ea6563df47626f4532af00d366da4394223b5a0c --- /dev/null +++ b/app.py @@ -0,0 +1,364 @@ +"""PixRick online: l'interfaccia è nostra, il motore gira su Gradio perché ZeroGPU lo richiede.""" + +from __future__ import annotations + +import html +import io +import json +import logging +import os +import tempfile +import threading +import time +from pathlib import Path +from typing import Any, Iterator + +try: + import spaces +except ImportError: # in locale, senza ZeroGPU + spaces = None + +import gradio as gr +from fastapi import FastAPI, File, Form, HTTPException, UploadFile +from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, 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, + } + + +def _friendly(exc: BaseException) -> str: + if isinstance(exc, (RequestError, SafetyError)): + return str(exc) + text = str(exc) + if "out of memory" in text.lower(): + return "La GPU è piena in questo momento. Riprova tra poco o scegli meno immagini." + log.exception("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) + 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) + yield job.public(), [] + yield from _work(job, refs, mask, book) + + +@gpu(30) +def _write(kind: str, text: str) -> str: + return models().write(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) + + +ON_SPACES = bool(os.environ.get("SPACE_ID")) + + +@gpu(40) +def _improve(text: str, kind: str) -> tuple[str, str]: + m = models() + english = m.write(kind, text) + return english, m.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} + + +def chi_sono(profile: gr.OAuthProfile | None) -> dict[str, Any]: + if profile is None: + return {"accesso": False} + return {"accesso": True, "nome": profile.name or profile.username, "utente": profile.username} + + +def chi_sono_locale() -> dict[str, Any]: + return {"accesso": False, "locale": True} + + +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() + profilo = gr.JSON() + if ON_SPACES: + gr.LoginButton() + 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], profilo, api_name="migliora", concurrency_limit=4) + gr.Button().click(chi_sono if ON_SPACES else chi_sono_locale, None, profilo, api_name="chi_sono", queue=False) + +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 + + +@app.get("/", include_in_schema=False) +def home() -> FileResponse: + return FileResponse(WEB / "index.html", 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'{html.escape(mail)}' + if mail + else f'{REPORT_URL.removeprefix("https://")}' + ) + 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("/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") + + +@app.get("/robots.txt", include_in_schema=False) +def robots() -> Response: + return Response("User-agent: *\nAllow: /\nDisallow: /motore/\n", media_type="text/plain") + + +@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"))) diff --git a/pixrick/config.py b/pixrick/config.py new file mode 100644 index 0000000000000000000000000000000000000000..10b124877a5721ae726005f4400c163104b4877c --- /dev/null +++ b/pixrick/config.py @@ -0,0 +1,85 @@ +from __future__ import annotations + +import os +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +WEB_DIR = ROOT / "web" +TEMPLATES_FILE = Path(__file__).resolve().parent / "templates.json" + +FAKE_ENGINE = os.environ.get("PIXRICK_FAKE") == "1" + +MAX_BATCH = 4 +MAX_REFS = 4 +MAX_PROMPT_CHARS = 2000 +MAX_UPLOAD_BYTES = 25 * 1024 * 1024 +MAX_INPUT_SIDE = 2048 +TARGET_AREA = 1024 * 1024 +MAX_UPSCALE_SIDE = 2048 + +MODES = ("crea", "ristila", "modifica", "continua") +VIEWS_MODE = "viste" +VIEWS = ( + ("Lato sinistro", "Show the exact same figure from its left side: a strict 90-degree side profile view facing left."), + ("Retro", "Show the exact same figure from behind: a straight back view, the face is not visible."), + ("Lato destro", "Show the exact same figure from its right side: a strict 90-degree side profile view facing right."), +) +VIEWS_KEEP = ( + "Keep the identical design, proportions, colors, materials, hair, clothes, accessories and base. " + "Full body visible and centered, same plain background, same soft even studio lighting." +) + +MODELS: dict[str, dict] = { + "z-image": { + "nome": "Z-Image Turbo", + "repo": "Tongyi-MAI/Z-Image-Turbo", + "descrizione": "Il più fedele al prompt. Foto realistiche e testo dentro l'immagine.", + "modalita": ["crea", "ristila"], + "qualita": {"rapida": 6, "bilanciata": 9, "massima": 14}, + }, + "klein": { + "nome": "FLUX.2 Klein", + "repo": "black-forest-labs/FLUX.2-klein-4B", + "descrizione": "Veloce, stile pulito. L'unico che modifica le foto a comando.", + "modalita": ["crea", "ristila", "modifica", "continua"], + "qualita": {"rapida": 4, "bilanciata": 5, "massima": 8}, + }, +} +TOOLS: dict[str, dict] = { + "ingrandisci": {"nome": "Z-Image Turbo"}, + "scontorna": {"nome": "BiRefNet", "repo": "ZhengPeng7/BiRefNet"}, +} +TOOL_MODES = tuple(TOOLS) +PROMPTER_REPO = "Qwen/Qwen3-1.7B" +NSFW_REPO = "Falconsai/nsfw_image_detection" +NSFW_THRESHOLD = 0.6 + +AUTO_MODEL = {"crea": "z-image", "ristila": "z-image", "modifica": "klein", "continua": "klein", "rifinisci": "z-image"} +REFINE = "klein+z" +REFINE_MODE = "rifinisci" +REFINE_FIDELITY = 0.68 +UPSCALE_FIDELITY = 0.78 +REFINE_MODES = ("ristila", "modifica", "continua") +CONTINUE_PROMPT = ( + "Create a brand-new image that belongs to the same story as image 1: same visual style, rendering, " + "color palette, lighting mood and world, and the same characters with identical faces, hair and clothes " + "whenever they appear. Do not copy the composition of image 1. New scene: {prompt}" +) +BOTH = "entrambi" +QUALITIES = ("rapida", "bilanciata", "massima") + +ASPECTS: dict[str, tuple[int, int]] = { + "1:1": (1024, 1024), + "4:5": (896, 1120), + "3:4": (864, 1152), + "2:3": (832, 1248), + "9:16": (768, 1344), + "16:9": (1344, 768), + "3:2": (1248, 832), +} +DEFAULT_ASPECT = "1:1" + +# Secondi di GPU stimati per passo, per chiedere a ZeroGPU solo il tempo che serve. +SECONDS_PER_STEP = {"z-image": 0.35, "klein": 0.3} +GPU_OVERHEAD = 12 +GPU_MAX_SECONDS = 170 diff --git a/pixrick/core.py b/pixrick/core.py new file mode 100644 index 0000000000000000000000000000000000000000..4600d1fed32303f78917f50a926ccd229bb01b05 --- /dev/null +++ b/pixrick/core.py @@ -0,0 +1,451 @@ +"""Richieste, stili e pianificazione dei lavori. Niente GPU qui: solo regole.""" + +from __future__ import annotations + +import json +import math +import random +import re +import time +import uuid +from dataclasses import asdict, dataclass, field +from typing import Any + +from PIL import Image, ImageOps + +from . import config +from .safety import check_prompt + +MAX_STYLES = 3 + + +class RequestError(ValueError): + """Errore da mostrare all'utente così com'è.""" + + +def fit_dims(width: int, height: int) -> tuple[int, int]: + scale = math.sqrt(config.TARGET_AREA / (width * height)) + w = max(256, int(round(width * scale / 16)) * 16) + h = max(256, int(round(height * scale / 16)) * 16) + return w, h + + +def clean_image(img: Image.Image) -> Image.Image: + """Ruota secondo l'EXIF, appiattisce la trasparenza su grigio chiaro e limita il lato lungo.""" + img = ImageOps.exif_transpose(img) + if img.mode in ("RGBA", "LA", "P"): + rgba = img.convert("RGBA") + flat = Image.new("RGB", rgba.size, (232, 232, 232)) + flat.paste(rgba, mask=rgba.split()[3]) + img = flat + else: + img = img.convert("RGB") + img.thumbnail((config.MAX_INPUT_SIDE, config.MAX_INPUT_SIDE)) + return img + + +@dataclass +class JobRequest: + prompt: str + mode: str = "crea" + model: str = "auto" + templates: list[str] = field(default_factory=list) + fields: dict[str, str] = field(default_factory=dict) + refs: list[str] = field(default_factory=list) + aspect: str = config.DEFAULT_ASPECT + quality: str = "bilanciata" + fidelity: float | None = None + seed: int | None = None + count: int = 1 + translate: bool = True + mask: str | None = None + + @classmethod + def from_payload(cls, data: dict[str, Any]) -> "JobRequest": + seed = data.get("seed") + refs = [str(r) for r in (data.get("riferimenti") or [])] + try: + return cls( + prompt=str(data.get("prompt") or ""), + mode=str(data.get("modalita") or "crea"), + model=str(data.get("modello") or "auto"), + templates=[str(t) for t in (data.get("stili") or [])], + fields={str(k): str(v)[:200] for k, v in (data.get("campi") or {}).items()}, + refs=refs, + aspect=str(data.get("formato") or ("originale" if refs else config.DEFAULT_ASPECT)), + quality=str(data.get("qualita") or "bilanciata"), + fidelity=None if data.get("fedelta") in (None, "", "auto") else float(data["fedelta"]), + seed=int(seed) if seed not in (None, "") else None, + count=int(data.get("quantita") or 1), + translate=bool(data.get("traduci", True)), + mask=str(data["maschera"]) if data.get("maschera") else None, + ) + except (TypeError, ValueError) as exc: + raise RequestError("Richiesta non valida.") from exc + + +@dataclass +class Job: + id: str + request: JobRequest + final_prompt: str + models: list[str] + steps: dict[str, int] + width: int + height: int + status: str = "in_coda" + progress: float = 0.0 + current: int = 0 + current_model: str = "" + created: float = field(default_factory=time.time) + started: float | None = None + finished: float | None = None + results: list[dict[str, Any]] = field(default_factory=list) + error: str | None = None + klein_prompt: str = "" + refine: bool = False + refine_prompt: str = "" + note: str = "" + fidelity_auto: bool = False + pause_left: int = 0 + + @property + def total(self) -> int: + return len(self.models) * self.request.count + + def public(self) -> dict[str, Any]: + data = asdict(self) + data["total"] = self.total + model = self.current_model or self.models[0] + data["model_name"] = (config.MODELS.get(model) or config.TOOLS[model])["nome"] + data["current_steps"] = self.steps[model] + data["confronto"] = len(self.models) > 1 + data["elapsed"] = round((self.finished or time.time()) - (self.started or self.created), 1) + return data + + def gpu_seconds(self) -> int: + """Stima del tempo di GPU, così ZeroGPU riserva (e scala dalla quota) solo quanto serve.""" + area = self.width * self.height / config.TARGET_AREA + total = 0.0 + for model in self.models: + per_step = config.SECONDS_PER_STEP.get(model, 0.35) + if model == "ingrandisci": + total += 9 * 0.35 * area * 1.4 + elif model == "scontorna": + total += 4 + else: + total += self.steps[model] * per_step * area * self.request.count + return int(min(config.GPU_MAX_SECONDS, config.GPU_OVERHEAD + total * 1.6)) + + +class TemplateBook: + """Stili di serie più quelli dell'utente, che vivono nel suo browser e arrivano con la richiesta.""" + + USER_CATEGORY = "I tuoi stili" + + def __init__(self, items: dict[str, dict[str, Any]]): + self._items = items + + @classmethod + def load(cls) -> "TemplateBook": + data = json.loads(config.TEMPLATES_FILE.read_text(encoding="utf-8")) + return cls({item["id"]: item for item in data["template"]}) + + def with_user(self, styles: list[dict[str, Any]]) -> "TemplateBook": + items = dict(self._items) + for raw in styles[:40]: + if not isinstance(raw, dict): + continue + style_id = str(raw.get("id") or "") + text = str(raw.get("prompt") or "") + if not style_id.startswith("u-") or "{prompt}" not in text: + continue + check_prompt(text) + items[style_id] = { + "id": style_id, + "nome": str(raw.get("nome") or "")[:40], + "prompt": text[:800], + "categoria": self.USER_CATEGORY, + "utente": True, + "campi": [], + } + return TemplateBook(items) + + def all(self) -> list[dict[str, Any]]: + return list(self._items.values()) + + def get(self, template_id: str) -> dict[str, Any]: + return self._items.get(template_id) or self._items["libero"] + + def clean_ids(self, ids: list[str]) -> list[str]: + seen: list[str] = [] + for i in ids: + if i in self._items and i != "libero" and i not in seen: + seen.append(i) + return seen[:MAX_STYLES] + + @staticmethod + def _fill(text: str, template: dict[str, Any], fields: dict[str, str]) -> str: + for spec in template.get("campi", []): + value = (fields.get(spec["id"]) or "").strip().replace('"', "'") + phrase = spec["frase"].replace("{valore}", value) if value else "" + text = text.replace("{" + spec["id"] + "}", phrase) + return text + + def render(self, ids: list[str], prompt: str, fields: dict[str, str], mode: str = "crea") -> str: + """Il primo stile decide il tipo di immagine; gli altri aggiungono solo i loro descrittori.""" + ids = self.clean_ids(ids) + if not ids: + return prompt.strip() + first = self._items[ids[0]] + base = first.get("prompt_ristila") if mode == "ristila" and first.get("prompt_ristila") else first["prompt"] + text = self._fill(base.replace("{prompt}", prompt.strip()), first, fields) + for extra_id in ids[1:]: + extra = self._items[extra_id] + body = extra["prompt"] + idx = body.find("{prompt}") + if idx >= 0: + cut = body.find(". ", idx) + body = body[cut + 2 :] if cut >= 0 else "" + for spec in extra.get("campi", []): + if "{" + spec["id"] + "}" not in body: + body = "{" + spec["id"] + "} " + body + text += " " + self._fill(body, extra, fields) + return re.sub(r"\s{2,}", " ", text).strip(" ,") + + +_STYLE_WORDS = re.compile( + r"\b(light|lighting|lit|glow|shadow|shadows|color|colors|colour|palette|tones?|hues?|saturat\w*|contrast|" + r"style|styled|aesthetic|look|mood|atmosphere|cinematic|photograph\w*|photo|render\w*|illustration|painting|" + r"painted|watercolou?r|anime|comic|cel|ink|line art|brush\w*|texture|textured|grain|film|lens|mm|bokeh|" + r"depth of field|shot on|camera|matte|glossy|vinyl|material|finish|vintage|retro|neon|pastel|monochrome|" + r"minimal\w*|detailed|detail|sharp|soft|dramatic|moody|warm|cold|cool|golden|studio|backdrop|background|" + r"chibi|proportions|3d|cgi|octane|unreal|pixel|vector|flat|isometric|editorial|magazine|high-end|" + r"composition|framing|symmetr\w*|haze|fog|misty|smoke|volumetric)\b", + re.IGNORECASE, +) + + +def extract_style(prompt: str, style_ids: list[str], book: TemplateBook) -> str: + """Tiene solo le frasi che descrivono l'aspetto (luce, colori, resa, materiali), non il soggetto.""" + parts: list[str] = [] + for sid in style_ids: + body = book.get(sid).get("prompt", "") + idx = body.find("{prompt}") + tail = body[idx + len("{prompt}") :] if idx >= 0 else body + tail = re.sub(r"\{[a-z_]+\}", "", tail) + parts.extend(c.strip(" .,") for c in re.split(r"[.,;]", tail)) + for clause in re.split(r"[.,;]|\band\b", re.sub(r'"[^"]*"', "", prompt)): + clause = clause.strip(" .:") + if ( + clause + and len(clause.split()) <= 9 + and _STYLE_WORDS.search(clause) + and not re.search(r"\bof\b|camera|lens|\d+\s?mm\b|shot on", clause, re.IGNORECASE) + ): + parts.append(clause) + seen: set[str] = set() + kept: list[str] = [] + for part in parts: + key = part.lower() + if part and key not in seen and not key.startswith(("of ", "with the ")): + seen.add(key) + kept.append(part[0].lower() + part[1:] if part[:2] != part[:2].upper() else part) + return " ".join(", ".join(kept).split()[:90]).rstrip(",") + + +def source_medium(img: Image.Image) -> str: + """Foto o disegno/render? Nelle foto anche le zone uniformi hanno grana; disegni e render 3D sono lisci.""" + import numpy as np + + small = img.convert("RGB") + small.thumbnail((384, 384)) + gray = np.asarray(small, dtype=np.float32).mean(axis=2) + grad = np.abs(np.diff(gray, axis=1))[:-1, :] + np.abs(np.diff(gray, axis=0))[:, :-1] + lum = gray[:-1, :-1] + mid_tones = (lum > 30) & (lum < 235) + sample = grad[mid_tones] if mid_tones.sum() > 2000 else grad.ravel() + smooth = float((sample < 1.5).mean()) + hard = float((sample >= 25).mean()) + return "disegno" if smooth > 0.24 or hard > 0.8 else "foto" + + +def plan_restyle(src: Image.Image, styles: list[dict[str, Any]], has_prompt: bool) -> tuple[float, bool, str]: + """Quanto tenere della foto (per Z-Image) e se serve un modello che la capisca (Klein).""" + origin = source_medium(src) + if not styles: + return (0.42 if has_prompt else 0.5), False, "" + known = [s for s in styles if s.get("materia")] + if not known: + return 0.38, False, "" + first = known[0] + target = first["materia"] + if any(s.get("forma") for s in known): + return 0.25, True, f"«{first['nome']}» cambia forme e proporzioni: l'ha fatta Klein, che capisce la foto" + if target != origin: + what = {"foto": "una foto vera", "disegno": "un disegno", "3d": "un modello 3D", "grafica": "una grafica"}[target] + frm = "un disegno" if origin == "disegno" else "una foto" + return 0.28, True, f"Da {frm} a {what}: l'ha fatta Klein, che capisce cosa c'è nell'immagine" + return 0.52, False, "" + + +def resolve_models(mode: str, wanted: str) -> list[str]: + if wanted == config.REFINE and mode in config.REFINE_MODES: + return ["klein", "z-image"] + if wanted == config.BOTH: + usable = [k for k, m in config.MODELS.items() if mode in m["modalita"]] + return usable or [config.AUTO_MODEL[mode]] + if wanted in config.MODELS and mode in config.MODELS[wanted]["modalita"]: + return [wanted] + return [config.AUTO_MODEL[mode]] + + +def refine_text(book: TemplateBook, req: JobRequest, subject: str) -> str: + """Per ripassare con Z-Image serve una descrizione del risultato, non un'istruzione di modifica.""" + if req.mode == "modifica": + return "A high quality, natural and detailed image with the same composition, subjects, colors and style, clean realistic textures and lighting." + subject = subject.strip() or "the same subject and scene" + if req.templates: + return book.render(req.templates, subject, req.fields) + return f"{subject}. Same composition, colors and style, with clean natural detail." + + +def klein_restyle(book: TemplateBook, req: JobRequest, extra: str) -> str: + """Klein vede la foto: gli si dice solo cosa cambia, i dettagli li prende dall'immagine.""" + if req.mode != "ristila" or not req.templates: + return "" + base = book.get(req.templates[0]).get("prompt_ristila") + if not base: + return "" + others = book.render(req.templates[1:], "", req.fields).strip(" .") if len(req.templates) > 1 else "" + text = base + (f" {others}." if others else "") + (f" Also: {extra.strip()}." if extra.strip() else "") + return re.sub(r"\s{2,}", " ", text).strip() + + +def _new_id() -> str: + return uuid.uuid4().hex[:12] + + +def _seed(value: int | None) -> int: + return int(value) if value is not None and int(value) >= 0 else random.randint(0, 2**31 - 1) + + +def plan(req: JobRequest, refs: list[Image.Image], mask: Image.Image | None, book: TemplateBook) -> Job: + """Valida la richiesta e prepara il lavoro, con le stesse regole dell'app sul computer.""" + if len(refs) != len(req.refs): + raise RequestError("Le immagini di partenza non sono arrivate tutte. Riprova.") + req.refs = req.refs[: config.MAX_REFS] + refs[:] = refs[: config.MAX_REFS] + + if req.mode in config.TOOL_MODES: + if not refs: + raise RequestError("Scegli l'immagine su cui lavorare.") + req.refs, refs[:] = req.refs[:1], refs[:1] + req.prompt, req.templates, req.count, req.mask = "", [], 1, None + req.seed = _seed(req.seed) + width, height = refs[0].size + if req.mode == "ingrandisci": + scale = min(2.0, config.MAX_UPSCALE_SIDE / max(width, height)) + if scale <= 1.05: + raise RequestError("L'immagine è già grande: online si ingrandisce fino a 2048 pixel di lato.") + width, height = int(width * scale) // 16 * 16, int(height * scale) // 16 * 16 + return Job(_new_id(), req, "", [req.mode], {req.mode: 1}, width, height) + + if req.mode == config.VIEWS_MODE: + if not refs: + raise RequestError("Scegli la figura da girare.") + req.refs, refs[:] = req.refs[:1], refs[:1] + req.prompt, req.templates, req.mask, req.model = "", [], None, "klein" + req.count, req.aspect = len(config.VIEWS), "originale" + req.quality = req.quality if req.quality in config.QUALITIES else "bilanciata" + req.seed = _seed(req.seed) + width, height = fit_dims(*refs[0].size) + steps = {"klein": config.MODELS["klein"]["qualita"][req.quality]} + return Job(_new_id(), req, "", ["klein"], steps, width, height) + + if req.mode == config.REFINE_MODE: + if not refs: + raise RequestError("Scegli l'immagine da rifinire.") + req.refs, refs[:] = req.refs[:1], refs[:1] + req.model, req.count, req.mask, req.aspect = "z-image", 1, None, "originale" + req.templates = book.clean_ids(req.templates) + req.prompt = req.prompt.strip()[: config.MAX_PROMPT_CHARS] + req.quality = req.quality if req.quality in config.QUALITIES else "bilanciata" + req.fidelity = config.REFINE_FIDELITY + req.seed = _seed(req.seed) + width, height = fit_dims(*refs[0].size) + prompt = refine_text(book, req, req.prompt) + check_prompt(prompt) + steps = {"z-image": config.MODELS["z-image"]["qualita"][req.quality]} + return Job(_new_id(), req, prompt, ["z-image"], steps, width, height, refine=True, refine_prompt=prompt) + + req.mode = req.mode if req.mode in config.MODES else "crea" + req.prompt = req.prompt.strip()[: config.MAX_PROMPT_CHARS] + if req.mode in ("ristila", "modifica", "continua") and not refs: + raise RequestError("Aggiungi almeno un'immagine di partenza.") + if req.mode == "crea": + req.refs, refs[:] = [], [] + if req.mode == "ristila": + req.refs, refs[:] = req.refs[:1], refs[:1] + if not req.prompt and not book.clean_ids(req.templates): + raise RequestError("Scrivi come vuoi trasformarla o scegli uno stile.") + elif not req.prompt: + raise RequestError({"crea": "Scrivi cosa vuoi vedere.", "continua": "Scrivi la nuova scena."}.get(req.mode, "Scrivi cosa cambiare.")) + req.templates = [] if req.mode in ("modifica", "continua") else book.clean_ids(req.templates) + if mask is not None and req.mode == "modifica": + req.model = config.REFINE if req.model == config.REFINE else "klein" + else: + req.mask = None + + note = "" + fidelity_auto = req.fidelity is None + if req.mode == "ristila": + styles = [book.get(t) for t in req.templates] + auto_value, needs_klein, reason = plan_restyle(refs[0], styles, bool(req.prompt)) + if fidelity_auto: + req.fidelity = auto_value + if needs_klein and req.model == "auto": + req.model = "klein" + note = reason + models = resolve_models(req.mode, req.model) + req.quality = req.quality if req.quality in config.QUALITIES else "bilanciata" + steps = {m: config.MODELS[m]["qualita"][req.quality] for m in models} + req.count = max(1, min(config.MAX_BATCH, int(req.count))) + req.fidelity = max(0.15, min(0.85, float(req.fidelity if req.fidelity is not None else 0.45))) + req.seed = _seed(req.seed) + + if req.mask: + req.aspect = "originale" + width, height = refs[0].size + elif req.aspect == "originale" and refs: + width, height = fit_dims(*refs[0].size) + else: + req.aspect = req.aspect if req.aspect in config.ASPECTS else config.DEFAULT_ASPECT + width, height = config.ASPECTS[req.aspect] + + subject = req.prompt or "the same subject and scene as the input image" + final_prompt = book.render(req.templates, subject, req.fields) + check_prompt(final_prompt + " " + " ".join(req.fields.values())) + + job = Job(_new_id(), req, final_prompt, models, steps, width, height) + job.klein_prompt = klein_restyle(book, req, req.prompt) + job.note = note + job.fidelity_auto = fidelity_auto and req.mode == "ristila" + if req.model == config.REFINE and models == ["klein", "z-image"]: + job.refine = True + job.refine_prompt = refine_text(book, req, req.prompt) + return job + + +def prompt_for(job: Job, model_key: str) -> str: + if job.refine and model_key == "z-image": + return job.refine_prompt + if job.request.mode == "continua": + return config.CONTINUE_PROMPT.format(prompt=job.final_prompt) + if job.request.mode == config.VIEWS_MODE: + return f"{config.VIEWS[job.current % len(config.VIEWS)][1]} {config.VIEWS_KEEP}" + if job.request.mode == "ristila" and model_key == "klein": + if job.klein_prompt: + return job.klein_prompt + return f"Restyle image 1, keeping the same subject and composition: {job.final_prompt}" + return job.final_prompt diff --git a/pixrick/marking.py b/pixrick/marking.py new file mode 100644 index 0000000000000000000000000000000000000000..e47c135cbc7540be86a2a6dadc160998caeaceef --- /dev/null +++ b/pixrick/marking.py @@ -0,0 +1,62 @@ +"""Ogni immagine esce marcata come generata con AI: metadati leggibili dalle macchine e filigrana invisibile.""" + +from __future__ import annotations + +import io +import json +import logging +from typing import Any + +from PIL import Image, PngImagePlugin + +log = logging.getLogger("pixrick.marking") + +WATERMARK = b"PixRick AI" +_XMP = """ + + + + http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia + PixRick + AI-generated image + + + +""" + + +def _watermark(img: Image.Image) -> Image.Image: + try: + import cv2 + import numpy as np + from imwatermark import WatermarkEncoder + except ImportError: + return img + if min(img.size) < 256: + return img + alpha = img.getchannel("A") if img.mode == "RGBA" else None + bgr = cv2.cvtColor(np.asarray(img.convert("RGB")), cv2.COLOR_RGB2BGR) + encoder = WatermarkEncoder() + encoder.set_watermark("bytes", WATERMARK) + marked = Image.fromarray(cv2.cvtColor(encoder.encode(bgr, "dwtDct"), cv2.COLOR_BGR2RGB)) + if alpha is not None: + marked.putalpha(alpha) + return marked + + +def to_png(img: Image.Image, meta: dict[str, Any]) -> bytes: + try: + img = _watermark(img) + except Exception: # noqa: BLE001 + log.exception("Filigrana non applicata") + info = PngImagePlugin.PngInfo() + info.add_text("Software", "PixRick") + info.add_text("Description", "AI-generated image") + info.add_text("parameters", json.dumps(meta, ensure_ascii=False)) + info.add_itxt("XML:com.adobe.xmp", _XMP) + buf = io.BytesIO() + img.save(buf, "PNG", pnginfo=info) + return buf.getvalue() diff --git a/pixrick/prompter.py b/pixrick/prompter.py new file mode 100644 index 0000000000000000000000000000000000000000..73b495e1b835aa94c9c9c740c64ea7ce9e4ad9df --- /dev/null +++ b/pixrick/prompter.py @@ -0,0 +1,79 @@ +"""Traduce e arricchisce i prompt con un piccolo modello di testo (Qwen3 1.7B).""" + +from __future__ import annotations + +import re + +_ITALIAN_HINTS = re.compile( + r"\b(il|lo|la|gli|le|un|una|uno|di|del|della|dei|delle|che|con|per|sul|sulla|nel|nella|non|più|" + r"mentre|sopra|sotto|dietro|davanti|vicino|foto|immagine|ragazza|ragazzo|uomo|donna|cielo|mare|" + r"togli|metti|aggiungi|cambia|rendi|sostituisci|fai)\b|[àèéìòù]", + re.IGNORECASE, +) + +_RULES = ( + "Rules: keep every text inside double quotes exactly as written (do not translate it). " + "Reply with the result only, one paragraph, no preamble, no quotes around the whole answer." +) + +PROMPTS = { + "traduci": ( + "Translate this image-generation prompt into natural English. Translate faithfully: do not add, " + "remove or embellish details. If it is already English, return it unchanged. " + _RULES + ), + "migliora": ( + "Rewrite this idea as a rich English prompt for a text-to-image model: describe subject, action, " + "setting, composition and framing, lighting, colors, mood and style in concrete visual terms, " + "in 40 to 90 words. Keep every element the user asked for and do not contradict them. Describe only what " + "appears in the picture: never mention cameras, lenses, focal lengths or photographic equipment, because " + "the image model would draw them. Write everything in positive terms. " + _RULES + ), + "migliora_modifica": ( + "Rewrite this photo-editing request as one clear English instruction for an image-editing model. " + "Be explicit about what to change and say that everything else must stay the same. " + "Refer to input images as 'image 1', 'image 2' when the user mentions more photos. " + _RULES + ), + "in_italiano": ( + "Translate this English image-generation prompt into natural, simple Italian. Translate faithfully: " + "do not add, remove or explain anything. Keep every text inside double quotes exactly as written. " + "Reply with the translation only, one paragraph." + ), + "stile": ( + "From this image-generation prompt keep only the visual style: medium, rendering technique, lighting, " + "color palette, mood, camera and lens, textures. Remove the subject, characters, objects, actions, " + "text to render and the place or setting. Reply with a short comma-separated English list of 10 to 40 " + "words, nothing else." + ), +} + + +def _drop_repeats(text: str) -> str: + """Il modello piccolo a volte gira in tondo: tolgo i pezzi già detti e la frase troncata in fondo.""" + seen: set[str] = set() + kept: list[str] = [] + for chunk in re.split(r"(?<=[,.;])\s+", text): + key = chunk.strip(" ,.;").lower() + if key and key not in seen: + seen.add(key) + kept.append(chunk) + out = " ".join(kept).strip() + if out and out[-1] not in ".!?\"": + cut = max(out.rfind(". "), out.rfind(", ")) + out = out[: cut + 1] if cut > len(out) * 0.6 else out + return out.rstrip(",; ") + + +def looks_italian(text: str) -> bool: + unquoted = re.sub(r'"[^"]*"', "", text) + return bool(_ITALIAN_HINTS.search(unquoted)) + + + +def finish(raw: str, original: str) -> str: + out = re.sub(r".*?", "", raw, flags=re.DOTALL).strip().strip('"').strip() + return _drop_repeats(out) or original + + +def settings(kind: str) -> tuple[float, int]: + temperature = 0.2 if kind in ("traduci", "in_italiano", "stile") else 0.6 + return temperature, 460 if kind == "in_italiano" else 260 diff --git a/pixrick/runner.py b/pixrick/runner.py new file mode 100644 index 0000000000000000000000000000000000000000..b774b7ee73860806a9054e5ebc7bda0ef2c2da47 --- /dev/null +++ b/pixrick/runner.py @@ -0,0 +1,377 @@ +"""Il lavoro vero sulla GPU: modelli, rendering, strumenti, controlli sul risultato.""" + +from __future__ import annotations + +import logging +import random +import threading +import time +from typing import Any, Callable + +from PIL import Image, ImageDraw, ImageFilter + +from . import config, prompter +from .core import Job, TemplateBook, fit_dims, klein_restyle, prompt_for, refine_text +from .safety import SafetyError, check_prompt + +log = logging.getLogger("pixrick.runner") + +Report = Callable[[float], None] + + +class Models: + """Tutto caricato una volta all'avvio: ZeroGPU sposta i pesi sulla GPU solo durante le chiamate.""" + + def __init__(self) -> None: + self.ready = False + self._lock = threading.Lock() + if config.FAKE_ENGINE: + self.ready = True + return + import torch + from diffusers import Flux2KleinPipeline, ZImageImg2ImgPipeline, ZImagePipeline + from transformers import ( + AutoImageProcessor, + AutoModelForCausalLM, + AutoModelForImageClassification, + AutoModelForImageSegmentation, + AutoTokenizer, + ) + + dtype = torch.bfloat16 + self.torch = torch + self.zimage = ZImagePipeline.from_pretrained(config.MODELS["z-image"]["repo"], torch_dtype=dtype).to("cuda") + self.zimage_i2i = ZImageImg2ImgPipeline(**self.zimage.components) + self.klein = Flux2KleinPipeline.from_pretrained(config.MODELS["klein"]["repo"], torch_dtype=dtype).to("cuda") + self.cutout = AutoModelForImageSegmentation.from_pretrained( + config.TOOLS["scontorna"]["repo"], trust_remote_code=True + ).to("cuda").eval() + self.text_tok = AutoTokenizer.from_pretrained(config.PROMPTER_REPO) + self.text = AutoModelForCausalLM.from_pretrained(config.PROMPTER_REPO, torch_dtype=dtype).to("cuda").eval() + self.nsfw_proc = AutoImageProcessor.from_pretrained(config.NSFW_REPO) + self.nsfw = AutoModelForImageClassification.from_pretrained(config.NSFW_REPO).to("cuda").eval() + self.ready = True + log.info("Modelli pronti") + + # ---------- testo ---------- + + def write(self, kind: str, text: str) -> str: + text = text.strip() + if not text: + return text + if config.FAKE_ENGINE: + time.sleep(0.4) + if kind == "in_italiano": + return f"[IT] {text}" + if kind == "stile": + return "warm cinematic lighting, deep shadows, rich saturated colors, film grain" + return f"[EN] {text}" if kind == "traduci" else f"A richly detailed scene of {text}, cinematic light." + torch = self.torch + messages = [{"role": "system", "content": prompter.PROMPTS[kind]}, {"role": "user", "content": text}] + chat = self.text_tok.apply_chat_template( + messages, add_generation_prompt=True, tokenize=False, enable_thinking=False + ) + inputs = self.text_tok(chat, return_tensors="pt").to("cuda") + temperature, max_tokens = prompter.settings(kind) + with torch.inference_mode(): + out = self.text.generate( + **inputs, + max_new_tokens=max_tokens, + do_sample=True, + temperature=temperature, + top_p=0.9, + repetition_penalty=1.12, + ) + raw = self.text_tok.decode(out[0][inputs["input_ids"].shape[1] :], skip_special_tokens=True) + return prompter.finish(raw, text) + + # ---------- controlli ---------- + + def is_explicit(self, img: Image.Image) -> bool: + if config.FAKE_ENGINE: + return False + torch = self.torch + inputs = self.nsfw_proc(images=img.convert("RGB"), return_tensors="pt").to("cuda") + with torch.inference_mode(): + probs = self.nsfw(**inputs).logits.softmax(-1)[0] + labels = self.nsfw.config.id2label + score = sum(float(probs[i]) for i, name in labels.items() if name.lower() in ("nsfw", "porn", "sexy", "hentai")) + return score >= config.NSFW_THRESHOLD + + # ---------- generazione ---------- + + def _callback(self, report: Report, total: int): + def step_end(_pipe, step: int, _timestep, kwargs): + report(min(1.0, (step + 1) / max(1, total))) + return kwargs + + return step_end + + def _generator(self, seed: int): + return self.torch.Generator("cuda").manual_seed(seed) + + def zimage_create(self, prompt: str, w: int, h: int, steps: int, seed: int, report: Report) -> Image.Image: + return self.zimage( + prompt=prompt, + width=w, + height=h, + num_inference_steps=steps, + guidance_scale=0.0, + generator=self._generator(seed), + callback_on_step_end=self._callback(report, steps), + ).images[0] + + def zimage_from( + self, prompt: str, source: Image.Image, keep: float, w: int, h: int, steps: int, seed: int, report: Report + ) -> Image.Image: + """keep = quanto resta della foto di partenza (0 = la ignora, 1 = identica).""" + strength = max(0.08, min(0.95, 1.0 - keep)) + return self.zimage_i2i( + prompt=prompt, + image=source, + strength=strength, + width=w, + height=h, + num_inference_steps=steps, + guidance_scale=0.0, + generator=self._generator(seed), + callback_on_step_end=self._callback(report, max(1, int(steps * strength))), + ).images[0] + + def klein_run( + self, prompt: str, images: list[Image.Image], w: int, h: int, steps: int, seed: int, report: Report + ) -> Image.Image: + args: dict[str, Any] = {} + if images: + args["image"] = images + return self.klein( + prompt=prompt, + width=w, + height=h, + num_inference_steps=steps, + guidance_scale=1.0, + generator=self._generator(seed), + callback_on_step_end=self._callback(report, steps), + **args, + ).images[0] + + def cut_out(self, img: Image.Image) -> Image.Image: + from torchvision import transforms + + torch = self.torch + prep = transforms.Compose( + [ + transforms.Resize((1024, 1024)), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ] + ) + rgb = img.convert("RGB") + tensor = prep(rgb).unsqueeze(0).to("cuda") + with torch.inference_mode(): + pred = self.cutout(tensor)[-1].sigmoid().float().cpu()[0].squeeze() + alpha = transforms.ToPILImage()(pred).resize(rgb.size, Image.LANCZOS) + out = rgb.convert("RGBA") + out.putalpha(alpha) + return out + + +_models: Models | None = None +_models_lock = threading.Lock() + + +def models() -> Models: + global _models + with _models_lock: + if _models is None: + _models = Models() + return _models + + +# ---------- immagini finte per provare tutto senza GPU ---------- + + +def _fake(job: Job, model_key: str, seed: int, refs: list[Image.Image], report: Report) -> Image.Image: + steps = job.steps.get(model_key, 1) + for s in range(steps): + time.sleep(0.15) + report((s + 1) / steps) + rnd = random.Random(f"{seed}-{model_key}") + img = Image.new("RGB", (job.width, job.height)) + draw = ImageDraw.Draw(img) + a = [rnd.randint(30, 220) for _ in range(3)] + b = [rnd.randint(30, 220) for _ in range(3)] + for y in range(job.height): + k = y / job.height + draw.line([(0, y), (job.width, y)], fill=tuple(int(a[i] * (1 - k) + b[i] * k) for i in range(3))) + if refs: + img.paste(refs[0].convert("RGB").resize((job.width // 2, job.height // 2)), (job.width // 4, job.height // 4)) + return img + + +# ---------- pezzi del lavoro ---------- + + +def _fit_init(src: Image.Image, width: int, height: int) -> Image.Image: + """Z-Image riparte dai pixel: se il formato cambia, ritaglio al centro invece di schiacciare la foto.""" + target = width / height + if abs(src.width / src.height - target) < 0.02: + return src + if src.width / src.height > target: + w = int(src.height * target) + box = ((src.width - w) // 2, 0, (src.width - w) // 2 + w, src.height) + else: + h = int(src.width / target) + box = (0, (src.height - h) // 2, src.width, (src.height - h) // 2 + h) + return src.crop(box) + + +def _keep_outside_zone(refined: Image.Image, base: Image.Image, mask: Image.Image) -> Image.Image: + """Col pennello la rifinitura vale solo dentro la zona: fuori resta la foto di partenza al pixel.""" + refined = refined.convert("RGB").resize(base.size, Image.LANCZOS) + m = mask.convert("L").resize(base.size, Image.BILINEAR).point(lambda v: 255 if v > 127 else 0) + soft = m.filter(ImageFilter.MaxFilter(5)).filter(ImageFilter.GaussianBlur(max(3, int(max(base.size) * 0.02)))) + return Image.composite(refined, base, soft) + + +class Runner: + """Esegue un lavoro dall'inizio alla fine, aggiornando job.progress per chi guarda.""" + + def __init__(self, job: Job, refs: list[Image.Image], mask: Image.Image | None, book: TemplateBook): + self.job = job + self.book = book + self.refs = refs + self.mask = mask + self.m = models() + self.intermediate: list[Image.Image] = [] + self.images: list[tuple[str, Image.Image, int]] = [] + + def _report(self, fraction: float) -> None: + job = self.job + job.progress = round((job.current + max(0.0, fraction)) / job.total, 4) + + def translate(self) -> None: + job, req = self.job, self.job.request + if req.mode in config.TOOL_MODES or not req.translate or not req.prompt or not prompter.looks_italian(req.prompt): + return + book = self.book + job.status = "traduzione" + english = self.m.write("traduci", req.prompt) or req.prompt + job.final_prompt = book.render(req.templates, english, req.fields) + job.klein_prompt = klein_restyle(book, req, english) + if job.refine: + job.refine_prompt = refine_text(book, req, english) + if req.mode == config.REFINE_MODE: + job.final_prompt = job.refine_prompt + check_prompt(job.final_prompt) + + def check_inputs(self) -> None: + for img in self.refs: + if self.m.is_explicit(img): + raise SafetyError("Immagine di partenza rifiutata: qui niente nudo né contenuti sessuali.") + + def render(self, model_key: str, seed: int) -> Image.Image: + job, req, m = self.job, self.job.request, self.m + report = self._report + if config.FAKE_ENGINE: + if model_key == "scontorna": + time.sleep(0.6) + rgba = self.refs[0].convert("RGBA") + w, h = rgba.size + alpha = Image.new("L", (w, h), 0) + alpha.paste(255, (w // 5, h // 8, w * 4 // 5, h * 7 // 8)) + rgba.putalpha(alpha) + return rgba + if model_key == "ingrandisci": + time.sleep(0.8) + return self.refs[0].resize((job.width, job.height), Image.LANCZOS) + return _fake(job, model_key, seed, self.refs, report) + + if model_key == "scontorna": + return m.cut_out(self.refs[0]) + if model_key == "ingrandisci": + big = self.refs[0].resize((job.width, job.height), Image.LANCZOS) + text = "A high quality image with the same content, composition, colors and style, with crisp natural fine detail and clean textures." + return m.zimage_from(text, big, config.UPSCALE_FIDELITY, job.width, job.height, 9, seed, report) + + steps = job.steps[model_key] + prompt = prompt_for(job, model_key) + if self.mask is not None and not (job.refine and model_key == "z-image"): + return self._render_zone(seed) + if model_key == "z-image": + if job.refine: + source = self.refs[0] if req.mode == config.REFINE_MODE else self.intermediate[job.current - req.count] + fitted = _fit_init(source, job.width, job.height) + image = m.zimage_from(prompt, fitted, config.REFINE_FIDELITY, job.width, job.height, steps, seed, report) + if self.mask is not None: + image = _keep_outside_zone(image, source.convert("RGB"), self.mask) + return image + if req.mode == "ristila": + fitted = _fit_init(self.refs[0], job.width, job.height) + return m.zimage_from(prompt, fitted, req.fidelity or 0.45, job.width, job.height, steps, seed, report) + return m.zimage_create(prompt, job.width, job.height, steps, seed, report) + return m.klein_run(prompt, self.refs, job.width, job.height, steps, seed, report) + + def _render_zone(self, seed: int) -> Image.Image: + """Modifica solo la zona dipinta: lavora su un ritaglio ingrandito e lo rimette al suo posto sfumato.""" + job = self.job + src = self.refs[0].convert("RGB") + mask = self.mask.convert("L").resize(src.size, Image.BILINEAR).point(lambda v: 255 if v > 127 else 0) + bbox = mask.getbbox() + if bbox is None: + raise ValueError("Dipingi la zona da cambiare.") + x0, y0, x1, y1 = bbox + side = max(x1 - x0, y1 - y0) + pad = max(48, int(side * 0.35)) + min_side = min(384, src.width, src.height) + cx, cy = (x0 + x1) / 2, (y0 + y1) / 2 + half_w = max((x1 - x0) / 2 + pad, min_side / 2) + half_h = max((y1 - y0) / 2 + pad, min_side / 2) + box = ( + max(0, int(cx - half_w)), + max(0, int(cy - half_h)), + min(src.width, int(cx + half_w)), + min(src.height, int(cy + half_h)), + ) + crop = src.crop(box) + width, height = fit_dims(*crop.size) + steps = job.steps["klein"] + if config.FAKE_ENGINE: + for s in range(steps): + time.sleep(0.15) + self._report((s + 1) / steps) + edited = Image.new("RGB", crop.size, tuple(random.Random(seed).randint(40, 220) for _ in range(3))) + else: + edited = self.m.klein_run(job.final_prompt, [crop, *self.refs[1:]], width, height, steps, seed, self._report) + edited = edited.convert("RGB").resize(crop.size, Image.LANCZOS) + feather = max(3, int(max(crop.size) * 0.025)) + soft = mask.crop(box).filter(ImageFilter.MaxFilter(5)).filter(ImageFilter.GaussianBlur(feather)) + out = src.copy() + out.paste(Image.composite(edited, crop, soft), box[:2]) + return out + + def run(self) -> list[tuple[str, Image.Image, int]]: + job, req = self.job, self.job.request + job.started = time.time() + self.check_inputs() + self.translate() + combo = job.refine and req.mode != config.REFINE_MODE + index = 0 + for model_key in job.models: + job.current_model = model_key + job.status = "generazione" + for i in range(req.count): + job.current = index + seed = int(req.seed) + (0 if req.mode == config.VIEWS_MODE else i) + image = self.render(model_key, seed) + if self.m.is_explicit(image): + raise SafetyError("Risultato bloccato dal filtro: qui niente nudo né contenuti sessuali.") + if combo and model_key == "klein": + self.intermediate.append(image) + else: + self.images.append((model_key, image, seed)) + index += 1 + job.progress = 1.0 + job.status = "fatto" + job.finished = time.time() + return self.images diff --git a/pixrick/safety.py b/pixrick/safety.py new file mode 100644 index 0000000000000000000000000000000000000000..417815850267cc1bcac0ca9892a0ef0207b79478 --- /dev/null +++ b/pixrick/safety.py @@ -0,0 +1,38 @@ +"""Regole di sicurezza: valgono per tutti e non si spengono.""" + +from __future__ import annotations + +import re + +_MINOR_TERMS = re.compile( + r"\b(child|children|kid|kids|minor|minors|underage|teen|teens|teenager|preteen|toddler|infant|baby|" + r"boy|girl|schoolgirl|schoolboy|loli|lolita|shota|young\s*(?:girl|boy)|years?\s*old|" + r"bambin[oaie]|ragazzin[oaie]|minorenn[ei]|adolescent[ei]|neonat[oaie]|scolar[aei]|" + r"\d{1,2}\s*ann[io]|1[0-7]\s*(?:y|anni))\b", + re.IGNORECASE, +) +_SEXUAL_TERMS = re.compile( + r"\b(nude|naked|nsfw|sex|sexy|sexual|erotic|porn\w*|explicit|lingerie|topless|bottomless|undress\w*|" + r"genital\w*|breasts?|nipples?|boobs?|butt|ass|striptease|bikini|underwear|panties|bra|seductive|" + r"nud[oaie]|nudit[aà]|sesso|sessual[ei]|erotic[oaie]|porno\w*|spogliat[oaie]|svestit[oaie]|" + r"intimo|seno|tette|capezzol[oi]|mutand\w*|reggiseno|perizoma|provocante|sensual[ei])\b", + re.IGNORECASE, +) +_GORE_TERMS = re.compile( + r"\b(gore|gory|dismember\w*|decapitat\w*|mutilat\w*|disembowel\w*|beheading|corpse\s+torn|" + r"smembrat\w*|decapitat\w*|mutilat\w*|sbudellat\w*)\b", + re.IGNORECASE, +) + + +class SafetyError(ValueError): + """Richiesta bloccata per regole di sicurezza.""" + + +def check_prompt(text: str) -> None: + if _MINOR_TERMS.search(text) and _SEXUAL_TERMS.search(text): + raise SafetyError("Richiesta bloccata: i minori non si toccano.") + if _SEXUAL_TERMS.search(text): + raise SafetyError("Richiesta bloccata: qui niente nudo né contenuti sessuali.") + if _GORE_TERMS.search(text): + raise SafetyError("Richiesta bloccata: niente violenza esplicita.") diff --git a/pixrick/templates.json b/pixrick/templates.json new file mode 100644 index 0000000000000000000000000000000000000000..c7a80c12b18ff2524f662dde0971d4cb62f2abdd --- /dev/null +++ b/pixrick/templates.json @@ -0,0 +1,303 @@ +{ + "template": [ + { + "id": "libero", + "nome": "Prompt libero", + "descrizione": "Usa esattamente quello che scrivi.", + "formato": "1:1", + "colore": "#3A3F44", + "campi": [], + "prompt": "{prompt}", + "categoria": "Base" + }, + { + "id": "figura-vinile", + "nome": "Funko", + "descrizione": "Figura in vinile stile Funko: testa grande, corpo piccolo. Pronta per l'image-to-3D e la stampa.", + "formato": "3:4", + "colore": "#e0743a", + "campi": [], + "prompt": "A glossy vinyl pop collectible figure of {prompt}, standing on a small round black base. The head is huge and rounded-square, about half of the figure's total height, with a flat simple face: two large flat black dot eyes, a tiny nose and no visible mouth, smooth plain vinyl skin. The body is small and boxy, with short stubby legs and simply sculpted clothes and hair. The whole figure is centered with empty space around it, on a plain light gray seamless backdrop, in soft even studio lighting. Style: clean toy product photo.", + "categoria": "Stampa 3D", + "prompt_ristila": "Turn the character in image 1 into a glossy vinyl pop collectible figure standing on a small round black base. The head becomes huge and rounded-square, about half of the figure's total height, with the character's own hairstyle and hair color sculpted on it. The face is flat and simple: two large flat black dot eyes, a tiny nose and no visible mouth. The body becomes small and boxy with short stubby legs, wearing the same outfit and holding the same objects. Plain light gray seamless backdrop, soft even studio lighting. Style: clean toy product photo.", + "materia": "3d", + "forma": true + }, + { + "id": "riferimento-stampa", + "nome": "Statuetta 3D", + "descrizione": "Statuetta realistica, intera e neutra, pronta per Hunyuan3D, Tripo o Meshy.", + "formato": "3:4", + "colore": "#8A8F96", + "campi": [], + "prompt": "A single standalone figurine of {prompt}, full body visible from head to feet with empty space around it, three-quarter front view, standing on a simple round base. Neutral matte gray material, thick sturdy limbs held close to the body, plain white background, soft even lighting, sharp clean silhouette.", + "categoria": "Stampa 3D", + "prompt_ristila": "Turn the character in image 1 into a single standalone figurine sculpture standing on a simple round base, full body visible from head to feet, made of neutral matte gray material. Plain white backdrop, soft even shadowless lighting, sharp clean silhouette. Style: clean product photo of a statue.", + "materia": "3d", + "forma": true + }, + { + "id": "foto", + "nome": "Foto realistica", + "descrizione": "Fotografia naturale, luce vera, dettaglio fine.", + "formato": "3:2", + "colore": "#C98A2B", + "campi": [], + "prompt": "{prompt}. A natural, candid real-life photograph with true-to-life colors, soft natural daylight, gentle background blur and fine realistic detail.", + "categoria": "Foto", + "materia": "foto", + "forma": false + }, + { + "id": "ritratto", + "nome": "Ritratto", + "descrizione": "Primo piano editoriale con luce morbida.", + "formato": "4:5", + "colore": "#9C5B4F", + "campi": [], + "prompt": "Close-up portrait of {prompt}, looking slightly away with a calm natural expression. Soft window light from the side, realistic skin texture, softly blurred background, refined editorial magazine look.", + "categoria": "Foto", + "materia": "foto", + "forma": false + }, + { + "id": "prodotto", + "nome": "Foto prodotto", + "descrizione": "Still life pubblicitario in studio.", + "formato": "1:1", + "colore": "#2E5E8C", + "campi": [], + "prompt": "Advertising still life of {prompt}, alone at the center on a seamless smooth studio backdrop. Soft diffused studio lighting with clean controlled reflections and crisp detail, high-end commercial look.", + "categoria": "Foto", + "materia": "foto", + "forma": false + }, + { + "id": "anime", + "nome": "Anime", + "descrizione": "Key visual in stile anime giapponese moderno.", + "formato": "3:4", + "colore": "#E2699A", + "campi": [], + "prompt": "Anime illustration of {prompt}, drawn in modern Japanese anime style with clean line art, cel shading, expressive eyes and vivid colors, set in a detailed painted background like a high-quality key visual.", + "categoria": "Illustrazione", + "materia": "disegno", + "forma": false + }, + { + "id": "fumetto", + "nome": "Fumetto", + "descrizione": "Vignetta con chine marcate e retini.", + "formato": "3:4", + "colore": "#F2C230", + "campi": [], + "prompt": "Comic book panel of {prompt}, drawn with bold ink outlines, halftone dot shading and flat vibrant colors in a dynamic graphic novel composition.", + "categoria": "Illustrazione", + "materia": "disegno", + "forma": false + }, + { + "id": "acquerello", + "nome": "Acquerello", + "descrizione": "Pittura leggera, carta e pigmenti che sfumano.", + "formato": "4:5", + "colore": "#6FA3B8", + "campi": [], + "prompt": "Watercolor painting of {prompt}, with soft washes, delicate bleeding pigments, loose brushwork and a light airy palette on textured cold-pressed paper.", + "categoria": "Illustrazione", + "materia": "disegno", + "forma": false + }, + { + "id": "dark-fantasy", + "nome": "Dark fantasy", + "descrizione": "Concept art epica, nebbia e oro spento.", + "formato": "16:9", + "colore": "#7A6A3A", + "campi": [], + "prompt": "Dark fantasy concept art of {prompt}, epic in scale, among misty gothic ruins with dramatic rim light, muted gold and ash tones and rich painterly detail.", + "categoria": "Illustrazione", + "materia": "disegno", + "forma": false + }, + { + "id": "personaggio-3d", + "nome": "Personaggio 3D", + "descrizione": "Render da film d'animazione, materiali morbidi.", + "formato": "1:1", + "colore": "#4C8C6A", + "campi": [], + "prompt": "Stylized 3D animated character of {prompt}, with big expressive features, smooth soft materials and warm soft lighting, rendered like a family animated feature film, on a clean simple studio backdrop.", + "categoria": "Illustrazione", + "materia": "3d", + "forma": true + }, + { + "id": "pixel", + "nome": "Pixel art", + "descrizione": "Videogioco retrò a 16 bit.", + "formato": "1:1", + "colore": "#5D9C3A", + "campi": [], + "prompt": "Pixel art of {prompt} in 16-bit retro video game style, with a limited color palette, crisp hard-edged square pixels and charming small details.", + "categoria": "Illustrazione", + "materia": "disegno", + "forma": true + }, + { + "id": "locandina", + "nome": "Locandina", + "descrizione": "Poster per eventi con titolo, sottotitolo e info.", + "formato": "2:3", + "colore": "#D7262F", + "campi": [ + { + "id": "titolo", + "etichetta": "Titolo", + "placeholder": "FESTA D'AUTUNNO", + "frase": "Large bold headline text reading \"{valore}\"." + }, + { + "id": "sottotitolo", + "etichetta": "Sottotitolo", + "placeholder": "Seconda edizione", + "frase": "Smaller subtitle text reading \"{valore}\"." + }, + { + "id": "info", + "etichetta": "Data e luogo", + "placeholder": "12 dicembre · Piazza del Comune", + "frase": "Small footer text reading \"{valore}\"." + } + ], + "prompt": "Printed event poster with a strong clean layout. {titolo} {sottotitolo} {info} The main visual shows {prompt}. Clear typographic hierarchy, generous margins, vibrant yet tasteful colors, print-ready graphic design.", + "categoria": "Grafica", + "materia": "grafica", + "forma": true + }, + { + "id": "logo", + "nome": "Logo", + "descrizione": "Marchio piatto e semplice su fondo bianco.", + "formato": "1:1", + "colore": "#1F7A7A", + "campi": [ + { + "id": "nome", + "etichetta": "Nome del marchio", + "placeholder": "Bottega Aurora", + "frase": "with the brand name \"{valore}\" in clean lettering" + } + ], + "prompt": "Minimal flat vector logo of {prompt} {nome}, built from a few simple geometric shapes in two or three solid flat colors, centered on a plain white background, simple enough to work as a small icon.", + "categoria": "Grafica", + "materia": "grafica", + "forma": true + }, + { + "id": "copertina", + "nome": "Copertina album", + "descrizione": "Artwork quadrato per musica.", + "formato": "1:1", + "colore": "#5B3F7A", + "campi": [ + { + "id": "titolo", + "etichetta": "Titolo sulla copertina", + "placeholder": "", + "frase": "Title text reading \"{valore}\"." + } + ], + "prompt": "Square album cover artwork for {prompt}. {titolo} A bold artistic concept with a striking composition and rich texture, designed as music artwork.", + "categoria": "Grafica", + "materia": "grafica", + "forma": false + }, + { + "id": "sticker", + "nome": "Sticker", + "descrizione": "Adesivo fustellato con bordo bianco.", + "formato": "1:1", + "colore": "#E07B39", + "campi": [], + "prompt": "Die-cut sticker of {prompt} with a thick white border, bold outlines and vibrant flat colors, isolated on a plain light background.", + "categoria": "Grafica", + "materia": "grafica", + "forma": true + }, + { + "id": "ui-app", + "nome": "Schermata app", + "categoria": "Interfacce", + "descrizione": "Mockup di una schermata mobile. Ottimo per esplorare idee: i testi piccoli possono uscire imprecisi.", + "formato": "9:16", + "colore": "#7C8CF8", + "campi": [ + { + "id": "titolo", + "etichetta": "Titolo della schermata", + "placeholder": "Le mie ricette", + "frase": "with the screen title \"{valore}\"" + } + ], + "prompt": "High-fidelity mobile app screen design of {prompt} {titolo}, shown flat and straight-on as a single screen filling the image. Modern clean interface with clear visual hierarchy, consistent spacing, rounded components, legible labels and realistic content. Every label and line of copy is a short, real English word or phrase in Latin letters.", + "materia": "grafica", + "forma": true + }, + { + "id": "ui-web", + "nome": "Pagina web", + "categoria": "Interfacce", + "descrizione": "Landing page vista da desktop: hero, menu, sezioni.", + "formato": "16:9", + "colore": "#5FB3A1", + "campi": [ + { + "id": "titolo", + "etichetta": "Titolo principale", + "placeholder": "Studio Nord", + "frase": "with the hero headline \"{valore}\"" + } + ], + "prompt": "High-fidelity website landing page design of {prompt} {titolo}, shown flat as a full desktop page: top navigation bar, large hero section with a call-to-action button and a clean grid of sections below. Modern typography, generous whitespace, realistic copy and imagery. Every label and line of copy is a short, real English word or phrase in Latin letters.", + "materia": "grafica", + "forma": true + }, + { + "id": "ui-dashboard", + "nome": "Dashboard", + "categoria": "Interfacce", + "descrizione": "Gestionale web con barra laterale, card, grafici e tabelle.", + "formato": "16:9", + "colore": "#E3A857", + "campi": [], + "prompt": "High-fidelity web app dashboard design for {prompt}, shown flat as a full desktop screen: left sidebar navigation, top bar with search, KPI cards, line and bar charts and a data table. Balanced whitespace, crisp modern interface, subtle shadows, realistic data. Every label and line of copy is a short, real English word or phrase in Latin letters.", + "materia": "grafica", + "forma": true + }, + { + "id": "ui-componenti", + "nome": "Kit componenti", + "categoria": "Interfacce", + "descrizione": "Tavola con bottoni, campi, card, palette e caratteri.", + "formato": "16:9", + "colore": "#C46BAE", + "campi": [], + "prompt": "UI component kit board for {prompt}, neatly arranged on a clean canvas: primary and secondary buttons, text inputs, toggles, checkboxes, cards, tags, a color palette with swatches and typography samples, in design system documentation style. Every label and line of copy is a short, real English word or phrase in Latin letters.", + "materia": "grafica", + "forma": true + }, + { + "id": "ui-icona", + "nome": "Icona app", + "categoria": "Interfacce", + "descrizione": "Icona quadrata arrotondata, un simbolo forte.", + "formato": "1:1", + "colore": "#4E9AE0", + "campi": [], + "prompt": "App icon design for {prompt}: a rounded square with one bold simple symbol, soft gradient and subtle depth, centered on a plain neutral background, premium mobile app icon style.", + "materia": "grafica", + "forma": true + } + ] +} diff --git a/pixrick/vector.py b/pixrick/vector.py new file mode 100644 index 0000000000000000000000000000000000000000..7e52ead039cef982bd2beeb78c89f71a791d7ed7 --- /dev/null +++ b/pixrick/vector.py @@ -0,0 +1,137 @@ +"""Vettorizzazione: da PNG a SVG con vtracer, preceduta da una pulizia dei colori. + +Le immagini generate hanno rumore e sfumature finissime: tracciarle così darebbe +migliaia di tracciati. Prima riduco i colori a una tavolozza piccola, poi traccio. +""" + +from __future__ import annotations + +import io +import re +from dataclasses import dataclass +from pathlib import Path + +from PIL import Image, ImageDraw, ImageFilter + +MAX_SIDE = 1400 +INK = 90 +MIN_SHARE = 0.004 + + +@dataclass(frozen=True) +class Preset: + nome: str + colori: int + binario: bool + speckle: int + angoli: int + + +PRESETS: dict[str, Preset] = { + "colori": Preset("Illustrazione", 16, False, 6, 60), + "essenziale": Preset("Pochi colori", 8, False, 10, 70), + "contorno": Preset("Solo contorni", 2, True, 8, 60), +} + + +def available() -> bool: + try: + import vtracer # noqa: F401 + except ImportError: + return False + return True + + +def _drop_background(img: Image.Image) -> Image.Image: + """Il colore che riempie i bordi, se collegato ai bordi, diventa trasparente (fondo bianco dei loghi).""" + rgb = img.convert("RGB") + w, h = rgb.size + edge = [rgb.getpixel((x, y)) for x in range(0, w, max(1, w // 40)) for y in (0, h - 1)] + edge += [rgb.getpixel((x, y)) for y in range(0, h, max(1, h // 40)) for x in (0, w - 1)] + bg = max(set(edge), key=edge.count) + if edge.count(bg) < len(edge) * 0.6: + return img + same = Image.new("L", (w, h), 0) + same.putdata([255 if p == bg else 0 for p in rgb.getdata()]) + for x, y in ((0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1), (w // 2, 0), (w // 2, h - 1), (0, h // 2), (w - 1, h // 2)): + if same.getpixel((x, y)) == 255: + ImageDraw.floodfill(same, (x, y), 128) + out = img.convert("RGBA") + alpha = out.getchannel("A") + alpha.paste(0, mask=same.point(lambda v: 255 if v == 128 else 0)) + out.putalpha(alpha) + return out + + +def _prepare(path: Path, preset: Preset, transparent: bool) -> bytes: + img = Image.open(path) + img.load() + has_alpha = img.mode in ("RGBA", "LA") or "transparency" in img.info + img = img.convert("RGBA") + if max(img.size) > MAX_SIDE: + img.thumbnail((MAX_SIDE, MAX_SIDE), Image.LANCZOS) + alpha = img.getchannel("A") + rgb = img.convert("RGB").filter(ImageFilter.MedianFilter(5)) + if preset.binario: + rgb = rgb.convert("L").point(lambda v: 255 if v > INK else 0).convert("RGB") + else: + rgb = _flatten(rgb, preset.colori) + out = rgb.convert("RGBA") + if has_alpha: + out.putalpha(alpha.point(lambda v: 255 if v > 127 else 0)) + elif transparent and not preset.binario: + out = _drop_background(out) + buf = io.BytesIO() + out.save(buf, "PNG") + return buf.getvalue() + + +def _flatten(rgb: Image.Image, colors: int) -> Image.Image: + """Riduce a pochi colori e butta quelli rarissimi: sono i pixel di bordo sfumati, che diventerebbero + filetti chiari e puntini tra una forma e l'altra.""" + first = rgb.quantize(colors=colors, method=Image.Quantize.FASTOCTREE, kmeans=4, dither=Image.Dither.NONE) + counts = first.getcolors(colors) or [] + total = rgb.width * rgb.height + pal = first.getpalette()[: colors * 3] + kept = [idx for n, idx in sorted(counts, reverse=True) if n / total >= MIN_SHARE] or [max(counts)[1]] + flat: list[int] = [] + for idx in kept: + flat += pal[idx * 3 : idx * 3 + 3] + palette = Image.new("P", (1, 1)) + palette.putpalette(flat + flat[:3] * (256 - len(kept))) + return rgb.quantize(palette=palette, dither=Image.Dither.NONE).convert("RGB") + + +def vectorize(path: Path, preset_id: str = "colori", transparent: bool = True) -> dict[str, object]: + import vtracer + + preset = PRESETS.get(preset_id, PRESETS["colori"]) + data = _prepare(path, preset, transparent) + svg = vtracer.convert_raw_image_to_svg( + data, + img_format="png", + colormode="binary" if preset.binario else "color", + hierarchical="stacked", + mode="spline", + filter_speckle=preset.speckle, + color_precision=8, + layer_difference=8, + corner_threshold=preset.angoli, + length_threshold=4.0, + max_iterations=10, + splice_threshold=45, + path_precision=2, + ) + w, h = Image.open(io.BytesIO(data)).size + svg = re.sub(r"]*)>", lambda m: _with_viewbox(m.group(1), w, h), svg, count=1) + return { + "svg": svg, + "tracciati": svg.count(" str: + attrs = re.sub(r'\s*(width|height|viewBox)="[^"]*"', "", attrs) + return f'' diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..094ca7f81e69cf5dc0b421fe6e5e65fb20831588 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,15 @@ +torch==2.13.0 +torchvision==0.28.0 +diffusers==0.43.0 +transformers==5.23.0 +accelerate +safetensors +sentencepiece +timm +einops +kornia +vtracer==0.6.15 +invisible-watermark +opencv-python-headless +numpy +pillow diff --git a/web/app.js b/web/app.js new file mode 100644 index 0000000000000000000000000000000000000000..aa49d27cbfda983ba8f65a2e912fe2bbd01b813f --- /dev/null +++ b/web/app.js @@ -0,0 +1,2057 @@ +"use strict"; + +const $ = (s) => document.querySelector(s); +const $$ = (s) => [...document.querySelectorAll(s)]; +const PAGE = 60; +const MAX_STYLES = 3; +const BOTH = "entrambi"; +const REFINE = "klein+z"; +const REFINE_MODES = ["ristila", "modifica", "continua"]; +const TOOL_MODES = ["ingrandisci", "scontorna"]; +const USER_CATEGORY = "I tuoi stili"; +const STYLE_COLORS = ["#cbbcff", "#ffc9a8", "#9fe3da", "#ffd600", "#ff7a7a", "#7aa7ff"]; + +const MODES = { + crea: { + hint: "Un'immagine nuova da una descrizione.", + placeholder: "Descrivi la scena: soggetto, luogo, luce, stile. Il testo da scrivere nell'immagine va tra virgolette.", + maxRefs: 0, + button: "Genera", + }, + ristila: { + hint: "Stessa foto, stile nuovo.", + placeholder: "Scegli uno stile a destra. Con Z-Image descrivi anche in breve chi c'è nella foto: «uomo con barba lunga, maglietta nera e chitarra rossa».", + maxRefs: 1, + button: "Ristila", + }, + modifica: { + hint: "Cambia quello che scrivi: in tutta la foto o solo nella zona che dipingi.", + placeholder: "Cosa cambiare: «togli la persona a sinistra», «metti un cappello rosso». Con più foto: «il gatto della foto 2 sul divano della foto 1».", + maxRefs: 4, + button: "Modifica", + }, + continua: { + hint: "Una nuova scena con lo stesso stile, mondo e personaggi della foto.", + placeholder: "La nuova scena: «lo stesso personaggio di notte sul tetto», «la piazza vista dall'alto con la folla».", + maxRefs: 1, + button: "Crea la scena", + }, +}; + +const MODE_LABEL = { + crea: "Creata", + ristila: "Ristilizzata", + modifica: "Modificata", + continua: "Stessa storia", + ingrandisci: "Ingrandita ×2", + scontorna: "Scontornata", + locandina: "Locandina", + viste: "Vista per il 3D", +}; +const PRINT_CATEGORY = "Stampa 3D"; +const isTool = (item) => TOOL_MODES.includes(item?.modalita); +const isPoster = (item) => item?.modalita === "locandina"; +const isView = (item) => item?.modalita === "viste"; +const isFixed = (item) => isTool(item) || isPoster(item) || isView(item); +const canRefine = (item) => item && item.modello === "klein" && !isFixed(item) && !item.rifinita; +const isPrintable = (item) => !isFixed(item) && stylesOf(item).some((id) => templateById(id)?.categoria === PRINT_CATEGORY); + +const prefs = { + get(key, fallback) { + try { const v = localStorage.getItem(`pixrick.${key}`); return v === null ? fallback : JSON.parse(v); } catch { return fallback; } + }, + set(key, value) { + try { localStorage.setItem(`pixrick.${key}`, JSON.stringify(value)); } catch { /* spazio pieno o non disponibile */ } + }, +}; + +const state = { + models: {}, + auto: {}, + templates: [], + mode: "crea", + model: "auto", + styles: [], + fieldValues: {}, + aspect: "1:1", + aspectTouched: false, + aspects: {}, + quality: "bilanciata", + count: 1, + refs: [], + current: null, + session: [], + refineFrom: null, + nextDismissed: "", + userStylesOpen: false, + tools: {}, + batch: [], + lastPrompt: "", + busy: false, + polling: null, + gallery: { filter: "tutte", items: [], offset: 0, full: false, selected: new Set(), detailIndex: -1 }, +}; + +/* ---------- utilità ---------- */ + +async function api(path, body, extraHeaders = {}) { + if (window.PixBackend) { + try { + return await window.PixBackend.api(path, body, extraHeaders); + } catch (e) { + throw e instanceof Error ? e : new Error(String(e)); + } + } + const opts = body === undefined ? {} : { + method: "POST", + headers: { "X-ImgAI": "1", ...extraHeaders }, + body: body instanceof Blob ? body : JSON.stringify(body), + }; + if (body !== undefined && !(body instanceof Blob)) opts.headers["Content-Type"] = "application/json"; + const res = await fetch(path, opts); + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.errore || `Errore ${res.status}`); + return data; +} + +function toast(text, action) { + const box = $("#toast"); + const btn = $("#toast-action"); + $("#toast-text").textContent = text; + btn.hidden = !action; + btn.onclick = null; + if (action) { + btn.textContent = action.label; + btn.onclick = () => { box.classList.remove("show"); action.run(); }; + } + box.classList.add("show"); + clearTimeout(toast.t); + toast.t = setTimeout(() => box.classList.remove("show"), action ? 6000 : 2800); +} + +function radio(container, attr, value) { + container.querySelectorAll("[role=radio]").forEach((b) => b.setAttribute("aria-checked", String(b.dataset[attr] === String(value)))); +} + +const mediaUrl = (path) => "/" + path.split("/").map(encodeURIComponent).join("/"); +const outputUrl = (file) => mediaUrl("outputs/" + file); + +function el(tag, props = {}, children = []) { + const n = document.createElement(tag); + for (const [k, v] of Object.entries(props)) { + if (k === "class") n.className = v; + else if (k === "text") n.textContent = v; + else if (k.startsWith("on")) n.addEventListener(k.slice(2), v); + else if (k === "data") Object.assign(n.dataset, v); + else n.setAttribute(k, v); + } + n.append(...children); + return n; +} + +function icon(id) { + const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + const use = document.createElementNS("http://www.w3.org/2000/svg", "use"); + use.setAttribute("href", `#${id}`); + svg.append(use); + return svg; +} + +const templateById = (id) => state.templates.find((t) => t.id === id); +const stylesOf = (item) => item.stili || (item.template && item.template !== "libero" ? [item.template] : []); +const styleNames = (ids) => ids.map((id) => templateById(id)?.nome || "stile eliminato").join(" + "); +const titleOf = (item) => item.titolo || item.prompt + || (stylesOf(item).length ? `${styleNames(stylesOf(item))}, da una foto` : "") + || item.prompt_finale || "Senza titolo"; + +function resolvedModels(mode = state.mode, wanted = state.model) { + if (mode === "modifica" && mask.hasStrokes() && wanted !== REFINE) return ["klein"]; + if (wanted === REFINE) return REFINE_MODES.includes(mode) ? ["klein", "z-image"] : [state.auto[mode]]; + if (wanted === BOTH) return Object.keys(state.models).filter((k) => state.models[k].modalita.includes(mode)); + const m = state.models[wanted]; + return [m && m.modalita.includes(mode) ? wanted : state.auto[mode]]; +} +const resolvedModel = (mode, wanted) => resolvedModels(mode, wanted)[0]; +const otherModel = (key) => Object.keys(state.models).find((k) => k !== key); + +/* ---------- stato motore ---------- */ + +async function refreshStatus() { + try { + return await api("/api/status"); + } catch { + return null; + } +} + +/* ---------- pannello modello ---------- */ + +function renderModels() { + const box = $("#models"); + box.replaceChildren(); + const autoKey = state.auto[state.mode]; + const zoned = state.mode === "modifica" && mask.hasStrokes(); + const options = [ + { key: "auto", nome: "Automatico", note: state.models[autoKey]?.nome, descrizione: "Sceglie il modello giusto per quello che stai facendo." }, + ...Object.entries(state.models).map(([key, m]) => ({ key, ...m })), + { key: BOTH, nome: "Entrambi", modalita: ["crea", "ristila"], descrizione: "Stesso prompt e stesso seme con i due modelli, affiancati." }, + { key: REFINE, nome: "Klein + rifinitura Z-Image", modalita: REFINE_MODES, descrizione: "Klein capisce la foto e fa il lavoro, poi Z-Image ripassa pelle, luce e dettagli. Ricevi solo le immagini finite." }, + ]; + for (const o of options) { + const supported = o.key === "auto" || (o.modalita.includes(state.mode) && !(zoned && !["klein", REFINE].includes(o.key))); + if (o.key === REFINE && !supported) continue; + box.append(el("button", { + type: "button", + class: "model", + role: "radio", + "aria-checked": String(state.model === o.key), + "aria-disabled": String(!supported), + title: supported ? "" : "Le modifiche a comando le fa solo FLUX.2 Klein", + onclick: () => { if (supported) { state.model = o.key; syncAll(); } }, + }, [ + el("span", { class: "model-name" }, [o.nome, ...(o.note ? [el("small", { text: o.note })] : [])]), + el("span", { class: "model-desc", text: o.descrizione }), + ])); + } +} + +/* ---------- stili combinabili ---------- */ + +function renderTemplates() { + const box = $("#templates"); + box.replaceChildren(); + const groups = new Map([[USER_CATEGORY, []]]); + for (const t of state.templates) { + if (!groups.has(t.categoria)) groups.set(t.categoria, []); + groups.get(t.categoria).push(t); + } + const ordered = new Map(); + for (const [name, items] of groups) { + if (name === USER_CATEGORY) continue; + ordered.set(name, items); + if (ordered.size === 1) ordered.set(USER_CATEGORY, groups.get(USER_CATEGORY)); + } + const USER_VISIBLE = 6; + for (const [name, all] of ordered) { + const chips = el("div", { class: "tpl-chips", "aria-label": name }); + let items = all; + const hiddenCount = name === USER_CATEGORY && !state.userStylesOpen ? Math.max(0, all.length - USER_VISIBLE) : 0; + if (hiddenCount) { + const picked = all.filter((t) => state.styles.includes(t.id)); + const rest = all.filter((t) => !state.styles.includes(t.id)); + items = [...picked, ...rest].slice(0, Math.max(USER_VISIBLE, picked.length)); + } + for (const t of items) { + const c = el("button", { type: "button", class: "chip", "aria-checked": "false", data: { id: t.id }, text: t.nome, title: t.descrizione || "", onclick: () => toggleStyle(t.id) }); + c.style.setProperty("--c", t.colore); + if (t.utente) { + chips.append(el("span", { class: "chip-wrap" }, [ + c, + el("button", { type: "button", class: "chip-edit", title: `Modifica «${t.nome}»`, "aria-label": `Modifica lo stile ${t.nome}`, onclick: () => openStyleDialog(t) }, [icon("i-pencil")]), + ])); + } else { + chips.append(c); + } + } + if (name === USER_CATEGORY && all.length > USER_VISIBLE) { + const extra = all.length - items.length; + chips.append(el("button", { + type: "button", + class: "chip chip-more", + onclick: () => { state.userStylesOpen = !state.userStylesOpen; renderTemplates(); }, + }, [state.userStylesOpen ? "Mostra meno" : `Altri ${extra}`])); + } + if (name === USER_CATEGORY) { + chips.append(el("button", { type: "button", class: "chip chip-add", title: "Salva un tuo stile da riusare e combinare", onclick: () => openStyleDialog() }, [icon("i-plus"), items.length ? "Nuovo" : "Crea il tuo stile"])); + } + box.append(el("div", { class: "tpl-group" + (name === USER_CATEGORY ? " user" : "") }, [el("p", { class: "tpl-group-name", text: name }), chips])); + } + renderStyleState(); +} + +function toggleStyle(id) { + saveFieldValues(); + if (id === "libero") { + state.styles = []; + } else if (state.styles.includes(id)) { + state.styles = state.styles.filter((s) => s !== id); + } else if (state.styles.length >= MAX_STYLES) { + toast(`Al massimo ${MAX_STYLES} stili insieme`); + return; + } else { + state.styles.push(id); + const t = templateById(id); + if (state.styles.length === 1 && !state.aspectTouched && (state.mode === "crea" || (state.mode === "ristila" && t.forma))) selectAspect(t.formato); + if (t.utente && (t.modello || t.qualita)) { + const usable = t.modello && (t.modello === BOTH ? state.mode !== "modifica" : state.models[t.modello]?.modalita.includes(state.mode)); + if (usable) state.model = t.modello; + if (t.qualita) { state.quality = t.qualita; radio($("#quality"), "v", state.quality); } + syncAll(); + toast(`«${t.nome}» ha impostato anche ${usable ? "modello e " : ""}qualità`); + } + } + renderStyleState(); +} + +function renderStyleState() { + state.styles = state.styles.filter((id) => templateById(id)); + const multi = state.styles.length > 1; + $$("#templates .chip[data-id]").forEach((c) => { + const id = c.dataset.id; + const idx = state.styles.indexOf(id); + const on = id === "libero" ? state.styles.length === 0 : idx >= 0; + c.setAttribute("aria-checked", String(on)); + if (multi && idx >= 0) c.dataset.order = String(idx + 1); + else delete c.dataset.order; + }); + let desc = "Nessuno stile: usa esattamente quello che scrivi."; + if (state.styles.length === 1) desc = templateById(state.styles[0]).descrizione; + if (multi) desc = `${styleNames(state.styles)}. Il primo decide il tipo di immagine, gli altri aggiungono il loro stile.`; + $("#tpl-desc").textContent = desc; + + const fields = $("#tpl-fields"); + fields.replaceChildren(); + const seen = new Set(); + for (const id of state.styles) { + for (const f of templateById(id)?.campi || []) { + if (seen.has(f.id)) continue; + seen.add(f.id); + const input = el("input", { type: "text", maxlength: "200", placeholder: f.placeholder || "", data: { field: f.id } }); + input.value = state.fieldValues[f.id] || ""; + fields.append(el("label", {}, [f.etichetta, input])); + } + } + renderPills(); +} + +function saveFieldValues() { + $$("[data-field]").forEach((i) => (state.fieldValues[i.dataset.field] = i.value)); +} + +async function reloadTemplates() { + state.templates = (await api("/api/templates")).template; + renderTemplates(); +} + +/* ---------- stili salvati ---------- */ + +const styleDlg = { editing: null, color: STYLE_COLORS[0], aspect: "1:1", model: "", quality: "" }; + +function openStyleDialog(style = null, fromItem = null) { + styleDlg.editing = style; + styleDlg.model = style?.modello || fromItem?.modello || ""; + styleDlg.quality = style?.qualita || fromItem?.qualita || ""; + const modelName = state.models[styleDlg.model]?.nome || (styleDlg.model === BOTH ? "Entrambi" : ""); + $("#sd-model-row").hidden = !modelName; + $("#sd-model").checked = Boolean(style ? style.modello : fromItem); + $("#sd-model-label").textContent = `Ricorda anche modello e qualità (${modelName}${styleDlg.quality ? `, ${styleDlg.quality}` : ""})`; + styleDlg.color = style?.colore || STYLE_COLORS[Math.floor(Math.random() * STYLE_COLORS.length)]; + const itemAspect = fromItem && state.aspects[fromItem.formato] ? fromItem.formato : null; + styleDlg.aspect = style?.formato || itemAspect || (state.aspect !== "originale" ? state.aspect : "1:1"); + $("#style-dlg-title").textContent = style ? "Modifica stile" : "Nuovo stile"; + $("#sd-name").value = style?.nome || ""; + $("#sd-text").value = style?.testo || ""; + $("#sd-delete").hidden = !style; + $("#sd-error").textContent = ""; + const sw = $("#sd-colors"); + sw.replaceChildren(...STYLE_COLORS.map((c) => { + const b = el("button", { type: "button", class: "swatch", role: "radio", "aria-checked": String(c === styleDlg.color), "aria-label": c, data: { v: c }, onclick: () => { styleDlg.color = c; radio(sw, "v", c); } }); + b.style.setProperty("--c", c); + return b; + })); + const asp = $("#sd-aspect"); + asp.replaceChildren(...Object.keys(state.aspects).map((k) => el("button", { + type: "button", role: "radio", "aria-checked": String(k === styleDlg.aspect), data: { v: k }, text: k, + onclick: () => { styleDlg.aspect = k; radio(asp, "v", k); }, + }))); + $("#style-dlg").showModal(); + $("#sd-name").focus(); + if (fromItem) extractStyle(fromItem); +} + +async function extractStyle(item) { + const field = $("#sd-text"); + field.value = ""; + field.placeholder = "Ricavo lo stile dall'immagine…"; + field.disabled = true; + try { + const { testo } = await api("/api/styles/extract", { prompt: item.prompt_finale || item.prompt || "", stili: stylesOf(item) }); + field.value = testo || ""; + if (!testo) $("#sd-error").textContent = "Il prompt non descriveva lo stile: scrivilo tu in poche parole (luce, colori, resa)."; + } catch (e) { + $("#sd-error").textContent = e.message; + } finally { + field.disabled = false; + field.placeholder = "Notte, luci calde ambra e bianche, fumo di palco, folla in controluce, contrasto forte"; + } +} + +async function saveStyleDialog() { + const name = $("#sd-name").value.trim(); + const text = $("#sd-text").value.trim(); + const err = $("#sd-error"); + if (!name || !text) { err.textContent = "Servono un nome e una descrizione."; return; } + const btn = $("#sd-save"); + btn.disabled = true; + btn.textContent = "Salvo…"; + try { + const saved = await api("/api/styles/save", { + id: styleDlg.editing?.id || "", nome: name, testo: text, formato: styleDlg.aspect, colore: styleDlg.color, + modello: $("#sd-model").checked && !$("#sd-model-row").hidden ? styleDlg.model : "", + qualita: $("#sd-model").checked && !$("#sd-model-row").hidden ? styleDlg.quality : "", + }); + $("#style-dlg").close(); + await reloadTemplates(); + if (!styleDlg.editing && !state.styles.includes(saved.id) && state.styles.length < MAX_STYLES) { + if (state.mode !== "crea" && state.mode !== "ristila") setMode("crea"); + toggleStyle(saved.id); + } + toast(styleDlg.editing ? "Stile aggiornato" : `Stile «${saved.nome}» salvato e selezionato`); + } catch (e) { + err.textContent = e.message; + } finally { + btn.disabled = false; + btn.textContent = "Salva stile"; + } +} + +async function deleteStyleDialog() { + const style = styleDlg.editing; + if (!style) return; + $("#style-dlg").close(); + const ok = await confirmDialog({ title: `Eliminare «${style.nome}»?`, text: "Le immagini già fatte con questo stile restano.", confirm: "Elimina stile", danger: true }); + if (!ok) return; + await api("/api/styles/delete", { id: style.id }); + state.styles = state.styles.filter((s) => s !== style.id); + await reloadTemplates(); + toast("Stile eliminato"); +} + +/* ---------- formato e qualità ---------- */ + +function renderAspects() { + const box = $("#aspects"); + box.replaceChildren(); + const entries = Object.entries(state.aspects); + if (state.mode !== "crea") entries.unshift(["originale", null]); + for (const [key, dims] of entries) { + const [w, h] = dims || [3, 4]; + const shape = el("span", { class: "aspect-box" }); + const scale = 22 / Math.max(w, h); + shape.style.width = `${Math.round(w * scale)}px`; + shape.style.height = `${Math.round(h * scale)}px`; + box.append(el("button", { + type: "button", + class: "aspect" + (dims ? "" : " aspect-original"), + role: "radio", + "aria-checked": "false", + data: { v: key }, + title: dims ? `${dims[0]}×${dims[1]}` : "Stesse proporzioni della prima foto", + onclick: () => { state.aspectTouched = true; selectAspect(key); }, + }, [shape, el("span", { text: dims ? key : "Originale" })])); + } + radio(box, "v", state.aspect); +} + +function selectAspect(key) { + if (key !== "originale" && !state.aspects[key]) return; + state.aspect = key; + radio($("#aspects"), "v", key); + renderPills(); +} + +function updateQualityNote() { + const keys = resolvedModels().filter((k) => state.models[k]); + if (!keys.length) return; + const notes = { rapida: "Per provare idee al volo.", bilanciata: "Il punto giusto tra resa e tempo.", massima: "Più dettaglio, un po' più di attesa." }; + const steps = keys.map((k) => `${state.models[k].nome} ${state.models[k].qualita[state.quality]} passi`).join(", "); + $("#quality-note").textContent = `${notes[state.quality]} ${steps}.`; + $("#count-note").textContent = state.model === REFINE && keys.length > 1 + ? `Ogni immagine passa da Klein e poi da Z-Image: ricevi ${state.count} ${state.count === 1 ? "immagine finita" : "immagini finite"}.` + : keys.length > 1 ? `Con Entrambi: ${state.count} per modello, ${state.count * keys.length} in tutto, su due righe.` : ""; +} + +/* ---------- riepilogo impostazioni nel composer ---------- */ + +function renderPills() { + const box = $("#pills"); + if (!box) return; + const pills = []; + const zoned = state.mode === "modifica" && mask.hasStrokes(); + if (state.mode === "modifica") { + pills.push({ k: "Zona", v: zoned ? "Solo la parte dipinta" : "Tutta l'immagine", target: "panel-zone", on: zoned }); + } else if (state.mode === "continua") { + pills.push({ k: "Stile", v: "Come la foto", target: "panel-aspect", on: true }); + } else { + pills.push({ k: "Stile", v: state.styles.length ? styleNames(state.styles) : "Nessuno", target: "panel-style", on: state.styles.length > 0 }); + } + if (!zoned) pills.push({ k: "Formato", v: state.aspect === "originale" ? "Come la foto" : state.aspect, target: "panel-aspect" }); + const models = resolvedModels(); + const modelText = state.model === REFINE && models.length > 1 ? "Klein + Z-Image" + : state.model === BOTH && models.length > 1 ? "Entrambi" : (state.models[models[0]]?.nome || "").replace(" Turbo", ""); + const autoText = state.mode === "ristila" && state.refs.length ? "Auto · sceglie PixRick" : `Auto · ${modelText}`; + pills.push({ k: "Modello", v: state.model === "auto" && !zoned ? autoText : modelText, target: "panel-model" }); + const n = state.model === REFINE ? state.count : models.length * state.count; + pills.push({ k: "Qualità", v: `${state.quality[0].toUpperCase()}${state.quality.slice(1)}${n > 1 ? ` · ${n} immagini` : ""}`, target: "panel-quality" }); + box.replaceChildren(...pills.map((p) => el("button", { + type: "button", + class: "pill" + (p.on ? " on" : ""), + title: "Cambia", + onclick: () => focusPanel(p.target), + }, [el("span", { class: "pill-k", text: p.k }), el("span", { class: "pill-v", text: p.v })]))); +} + +function focusPanel(id) { + const panel = document.getElementById(id); + if (!panel) return; + if (panel.tagName === "DETAILS") panel.open = true; + panel.scrollIntoView({ behavior: "smooth", block: "nearest" }); + panel.classList.remove("flash"); + void panel.offsetWidth; + panel.classList.add("flash"); +} + +/* ---------- modalità e foto di partenza ---------- */ + +function setMode(mode) { + state.mode = mode; + document.body.dataset.mode = mode; + $$(".modes [role=tab]").forEach((t) => t.setAttribute("aria-selected", String(t.dataset.mode === mode))); + const cfg = MODES[mode]; + $("#mode-hint").textContent = cfg.hint; + $("#prompt").placeholder = cfg.placeholder; + $("#generate-label").textContent = cfg.button; + $("#ref-add-label").textContent = mode === "ristila" ? "Foto" : "Foto"; + const supports = state.model === BOTH ? !["modifica", "continua"].includes(mode) + : state.model === REFINE ? REFINE_MODES.includes(mode) + : state.model === "auto" || state.models[state.model]?.modalita.includes(mode); + if (!supports) { + state.model = "auto"; + toast(mode === "continua" ? "Le storie le fa solo FLUX.2 Klein: l'ho selezionato io" : "Le modifiche a comando le fa solo FLUX.2 Klein: l'ho selezionato io"); + } + if (!state.aspectTouched || (mode === "crea" && state.aspect === "originale")) { + state.aspect = mode === "crea" ? (templateById(state.styles[0])?.formato || "1:1") : "originale"; + state.aspectTouched = false; + } + if (mode !== "modifica") brush.stop(); + renderAspects(); + syncAll(); + syncBase(); + updateNextBar(); +} + +function syncAll() { + document.body.dataset.modelResolved = resolvedModel(); + document.body.dataset.model = state.model; + renderModels(); + renderRefs(); + updateQualityNote(); + updateShotActions(); + renderZone(); + renderPills(); +} + +function renderRefs() { + const list = $("#ref-list"); + list.replaceChildren(); + const max = MODES[state.mode].maxRefs; + const shown = state.refs.slice(0, max); + shown.forEach((r, i) => { + list.append(el("div", { class: "ref" + (i === 0 ? " main" : "") }, [ + el("img", { src: mediaUrl(r.file), alt: r.nome || `Foto ${i + 1}` }), + ...(state.mode === "modifica" && shown.length > 1 ? [el("span", { class: "ref-index", text: String(i + 1) })] : []), + el("button", { type: "button", "aria-label": "Togli questa foto", onclick: () => { state.refs.splice(i, 1); refsChanged(); } }, [icon("i-x")]), + ])); + }); + $("#refs").classList.toggle("full", shown.length >= max); +} + +function refsChanged() { + renderRefs(); + if (state.mode !== "crea" && state.refs[0]) sessionAddStart(state.refs[0]); + syncBase(); + updateNextBar(); + sessionRender(); +} + +async function addFiles(files) { + const images = [...files].filter((f) => f.type.startsWith("image/")); + if (!images.length) return; + if (state.mode === "crea") setMode(images.length > 1 ? "modifica" : "ristila"); + const max = MODES[state.mode].maxRefs; + if (state.mode === "ristila" || state.mode === "continua") state.refs = []; + for (const f of images) { + if (state.refs.length >= max) { toast(`Al massimo ${max} foto in questa modalità`); break; } + try { + const info = await api("/api/upload", f, { "Content-Type": f.type || "application/octet-stream", "X-Filename": encodeURIComponent(f.name || "incollata") }); + state.refs.push(info); + refsChanged(); + } catch (e) { + toast(e.message); + } + } + $("#prompt").focus(); +} + +function useAsRef(item, mode) { + state.refs = [{ file: "outputs/" + item.file, nome: titleOf(item) }]; + setView("studio"); + setMode(mode); + refsChanged(); + $("#prompt").value = ""; + autosize(); + $("#prompt").focus(); + const tips = { + modifica: "Scrivi cosa cambiare, o dipingi prima la zona", + ristila: "Scegli uno stile o descrivi la trasformazione", + continua: "Scrivi la nuova scena: stile e personaggi restano quelli", + }; + toast(tips[mode]); +} + +/* ---------- sessione: tutto quello che hai fatto da quando hai aperto la pagina ---------- */ + +const fileName = (f) => (f || "").split("/").pop(); + +function sessionAdd(items, group = "", kind = "risultato") { + for (const item of items) { + if (state.session.some((e) => fileName(e.item.file) === fileName(item.file))) continue; + state.session.push({ item, group, kind }); + } + sessionRender(); +} + +function sessionAddStart(ref) { + if (!ref?.file) return; + const name = fileName(ref.file); + const existing = state.session.find((e) => fileName(e.item.file) === name); + if (existing) { existing.kind = "partenza"; sessionRender(); return; } + state.session.push({ item: { file: ref.file, nome: ref.nome || "Foto", esterna: true }, group: "", kind: "partenza" }); + sessionRender(); +} + +function sessionSwap(byName) { + for (const e of state.session) { + const n = fileName(e.item.file); + if (byName.has(n)) e.item = byName.get(n); + } + sessionRender(); +} + +function sessionRemove(files) { + const gone = new Set(files.map(fileName)); + state.session = state.session.filter((e) => !gone.has(fileName(e.item.file))); + sessionRender(); +} + +const sessionSrc = (e) => (e.item.esterna ? mediaUrl(e.item.file) : outputUrl(e.item.miniatura || e.item.file)); + +function sessionActiveName() { + const st = $("#stage").dataset.state; + if (st === "base") return fileName(state.refs[0]?.file); + if (st === "foto") return fileName(state.current?.file); + return ""; +} + +function sessionRender() { + const nav = $("#session"); + const list = $("#session-list"); + nav.hidden = state.session.length === 0; + list.replaceChildren(); + const active = sessionActiveName(); + const compareGroup = $("#stage").dataset.state === "confronto" ? state.batch.map((b) => fileName(b.file)) : []; + let lastGroup = null; + state.session.forEach((e, i) => { + const name = fileName(e.item.file); + const siblings = e.group ? state.session.filter((x) => x.group === e.group) : []; + if (e.group && e.group !== lastGroup && siblings.length > 1) { + list.append(el("button", { + type: "button", + class: "session-group", + title: "Confronta queste immagini affiancate", + onclick: () => { state.batch = siblings.map((x) => x.item); showCompare(state.batch); }, + }, [`${siblings.length} insieme`])); + } + lastGroup = e.group; + const isOn = name === active || compareGroup.includes(name); + list.append(el("button", { + type: "button", + class: "session-item" + (isOn ? " on" : "") + (e.item.bozza === false ? " saved" : ""), + title: e.kind === "partenza" ? "Immagine di partenza" : (MODE_LABEL[e.item.modalita] || "Creata") + (e.item.bozza === false ? " · in galleria" : " · bozza"), + data: { i: String(i) }, + onclick: () => sessionOpen(i), + }, [ + el("img", { src: sessionSrc(e), alt: "" }), + ...(e.kind === "partenza" ? [el("span", { class: "session-tag", text: "partenza" })] : []), + ])); + }); + list.querySelector(".session-item.on")?.scrollIntoView({ block: "nearest" }); +} + +function sessionOpen(i) { + const e = state.session[i]; + if (!e) return; + const isStart = state.mode !== "crea" && fileName(state.refs[0]?.file) === fileName(e.item.file); + if (isStart) { + state.current = null; + $("#stage").dataset.state = ""; + syncBase(); + } else if (e.item.esterna) { + if (state.mode === "crea") setMode("ristila"); + state.refs = [{ file: e.item.file, nome: e.item.nome }]; + refsChanged(); + } else { + showShot(e.item); + } + sessionRender(); +} + +function sessionStep(delta) { + if (!state.session.length) return; + const active = sessionActiveName(); + let i = state.session.findIndex((e) => fileName(e.item.file) === active); + i = i < 0 ? state.session.length - 1 : Math.max(0, Math.min(state.session.length - 1, i + delta)); + sessionOpen(i); +} + +/* ---------- lavoro a cascata: continua dalla nuova versione ---------- */ + +function updateNextBar() { + const bar = $("#next-bar"); + const it = state.current; + const ref = state.refs[0]?.file; + const show = Boolean( + it && ref && state.mode !== "crea" && !state.busy + && $("#stage").dataset.state === "foto" + && `outputs/${it.file}` !== ref + && state.nextDismissed !== it.file + && !isPoster(it), + ); + bar.hidden = !show; + if (show) $("#next-thumb").src = outputUrl(it.miniatura || it.file); +} + +function continueFromCurrent() { + const it = state.current; + if (!it) return; + const others = state.refs.slice(1); + state.refs = [{ file: "outputs/" + it.file, nome: titleOf(it) }, ...others]; + if (it.modalita === "scontorna" && state.mode === "ristila" && !state.aspectTouched) state.aspect = "originale"; + refsChanged(); + $("#next-bar").hidden = true; + $("#prompt").focus(); + toast("Ora lavori sulla nuova versione"); +} + +/* ---------- menu sull'immagine ---------- */ + +const shotMenu = { + open(e) { + const item = state.current; + if (!item || $("#stage").dataset.state !== "foto") return; + const menu = $("#shot-menu"); + const hasPrompt = Boolean(item.prompt_finale || item.prompt) && !isPoster(item) && !isView(item); + $("#m-style").disabled = !hasPrompt; + $("#m-story").disabled = isPoster(item); + $("#m-refine").hidden = !canRefine(item); + const r = $("#stage").getBoundingClientRect(); + menu.hidden = false; + const w = menu.offsetWidth; + const h = menu.offsetHeight; + menu.style.left = `${Math.min(r.width - w - 12, Math.max(12, e.clientX - r.left))}px`; + menu.style.top = `${Math.min(r.height - h - 12, Math.max(12, e.clientY - r.top))}px`; + menu.querySelector("button:not([disabled])")?.focus(); + }, + close() { $("#shot-menu").hidden = true; }, + wire() { + $("#shot-img").addEventListener("click", (e) => { e.stopPropagation(); this.open(e); }); + document.addEventListener("click", (e) => { if (!e.target.closest("#shot-menu")) this.close(); }); + document.addEventListener("keydown", (e) => { if (e.key === "Escape") this.close(); }); + const act = (id, fn) => $(id).addEventListener("click", () => { const it = state.current; this.close(); if (it) fn(it); }); + act("#m-story", (it) => useAsRef(it, "continua")); + act("#m-style", (it) => openStyleDialog(null, it)); + act("#m-refine", runRefine); + act("#m-zone", (it) => { useAsRef(it, "modifica"); setTimeout(() => brush.start(), 80); }); + act("#m-poster", openInPoster); + }, +}; + +/* ---------- immagine di partenza e zona dipinta ---------- */ + +function syncBase() { + const stage = $("#stage"); + const ref = state.mode !== "crea" ? state.refs[0] : null; + if (ref) { + const img = $("#base-img"); + if (img.dataset.file !== ref.file) { + img.dataset.file = ref.file; + img.src = mediaUrl(ref.file); + mask.reset(); + } + $("#base-label").textContent = { modifica: "Immagine da modificare", continua: "La storia parte da qui" }[state.mode] || "Immagine di partenza"; + if (!state.busy) { + stage.dataset.state = "base"; + $("#shot-bar").hidden = true; + $("#next-bar").hidden = true; + $("#base-bar").hidden = brush.active; + $("#b-upscale").disabled = !state.tools.ingrandisci; + $("#b-cutout").disabled = !state.tools.scontorna; + } + } else { + brush.stop(); + mask.reset(); + $("#base-img").removeAttribute("src"); + delete $("#base-img").dataset.file; + if (stage.dataset.state === "base") restoreStage(); + } + if (stage.dataset.state !== "base") $("#base-bar").hidden = true; +} + +function restoreStage() { + if (state.batch.length > 1 && document.body.dataset.stage === "confronto") showCompare(state.batch); + else if (state.current) showShot(state.current); + else clearStage(); +} + +const mask = { + strokes: [], + canvas: null, + ctx: null, + hasStrokes() { return this.strokes.some((s) => !s.erase); }, + init() { + this.canvas = $("#mask-canvas"); + this.ctx = this.canvas.getContext("2d"); + }, + size() { + const img = $("#base-img"); + return [img.naturalWidth || 1, img.naturalHeight || 1]; + }, + fit() { + const [w, h] = this.size(); + if (this.canvas.width !== w || this.canvas.height !== h) { + this.canvas.width = w; + this.canvas.height = h; + this.redraw(); + } + }, + reset() { + this.strokes = []; + if (this.ctx) this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); + renderZone(); + }, + undo() { + this.strokes.pop(); + this.redraw(); + renderZone(); + }, + drawStroke(ctx, s, color) { + ctx.save(); + ctx.globalCompositeOperation = s.erase && !color ? "destination-out" : "source-over"; + ctx.strokeStyle = color ? (s.erase ? "#000" : "#fff") : "#cbbcff"; + ctx.fillStyle = ctx.strokeStyle; + ctx.lineWidth = s.size; + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + if (s.pts.length === 1) { + ctx.beginPath(); + ctx.arc(s.pts[0][0], s.pts[0][1], s.size / 2, 0, Math.PI * 2); + ctx.fill(); + } else { + ctx.beginPath(); + ctx.moveTo(...s.pts[0]); + for (const p of s.pts.slice(1)) ctx.lineTo(...p); + ctx.stroke(); + } + ctx.restore(); + }, + redraw() { + this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); + for (const s of this.strokes) this.drawStroke(this.ctx, s); + }, + async upload() { + const [w, h] = this.size(); + const off = document.createElement("canvas"); + off.width = w; + off.height = h; + const c = off.getContext("2d"); + c.fillStyle = "#000"; + c.fillRect(0, 0, w, h); + for (const s of this.strokes) this.drawStroke(c, s, true); + const probe = document.createElement("canvas"); + probe.width = 96; + probe.height = Math.max(1, Math.round((96 * h) / w)); + const pc = probe.getContext("2d"); + pc.drawImage(off, 0, 0, probe.width, probe.height); + const px = pc.getImageData(0, 0, probe.width, probe.height).data; + let painted = false; + for (let i = 0; i < px.length; i += 4) if (px[i] > 40) { painted = true; break; } + if (!painted) return null; + const blob = await new Promise((r) => off.toBlob(r, "image/png")); + const info = await api("/api/upload", blob, { "Content-Type": "image/png", "X-Filename": "zona.png" }); + return info.file; + }, +}; + +const brush = { + active: false, + tool: "pennello", + drawing: null, + sizeFraction() { return Number($("#brush-size").value); }, + px() { const [w, h] = mask.size(); return Math.max(4, this.sizeFraction() * Math.min(w, h)); }, + start() { + if (state.mode !== "modifica" || !state.refs[0]) { + toast("Aggiungi prima la foto da modificare"); + return; + } + if (state.busy) return; + syncBase(); + mask.fit(); + this.active = true; + $("#stage").dataset.brush = "on"; + $("#base-bar").hidden = true; + renderZone(); + }, + stop() { + this.active = false; + $("#stage").dataset.brush = "off"; + if ($("#stage").dataset.state === "base") $("#base-bar").hidden = false; + $("#brush-cursor").classList.remove("show"); + renderZone(); + }, + setTool(tool) { + this.tool = tool; + radio($("#brush-bar .seg"), "tool", tool); + }, + pos(e) { + const r = mask.canvas.getBoundingClientRect(); + const [w, h] = mask.size(); + return [((e.clientX - r.left) / r.width) * w, ((e.clientY - r.top) / r.height) * h]; + }, + cursor(e) { + const cur = $("#brush-cursor"); + if (!this.active || !e) { cur.classList.remove("show"); return; } + const r = mask.canvas.getBoundingClientRect(); + const d = (this.px() * r.width) / mask.size()[0]; + const stage = $("#stage").getBoundingClientRect(); + cur.style.width = cur.style.height = `${d}px`; + cur.style.transform = `translate(${e.clientX - stage.left - d / 2}px, ${e.clientY - stage.top - d / 2}px)`; + cur.classList.toggle("erase", this.tool === "gomma"); + cur.classList.add("show"); + }, + wire() { + const cv = $("#mask-canvas"); + cv.addEventListener("pointerdown", (e) => { + if (!this.active) return; + e.preventDefault(); + cv.setPointerCapture(e.pointerId); + this.drawing = { erase: this.tool === "gomma", size: this.px(), pts: [this.pos(e)] }; + mask.strokes.push(this.drawing); + mask.drawStroke(mask.ctx, this.drawing); + }); + cv.addEventListener("pointermove", (e) => { + this.cursor(e); + if (!this.drawing) return; + const p = this.pos(e); + const last = this.drawing.pts[this.drawing.pts.length - 1]; + if (Math.hypot(p[0] - last[0], p[1] - last[1]) < 2) return; + this.drawing.pts.push(p); + const seg = { ...this.drawing, pts: [last, p] }; + mask.drawStroke(mask.ctx, seg); + }); + const end = () => { + if (!this.drawing) return; + this.drawing = null; + renderZone(); + }; + cv.addEventListener("pointerup", end); + cv.addEventListener("pointercancel", end); + cv.addEventListener("pointerleave", () => this.cursor(null)); + $("#base-img").addEventListener("load", () => mask.fit()); + $("#brush-bar .seg").addEventListener("click", (e) => { const b = e.target.closest("[data-tool]"); if (b) this.setTool(b.dataset.tool); }); + $("#brush-undo").addEventListener("click", () => mask.undo()); + $("#brush-clear").addEventListener("click", () => mask.reset()); + $("#brush-done").addEventListener("click", () => { this.stop(); $("#prompt").focus(); }); + $("#zone-btn").addEventListener("click", () => (this.active ? this.stop() : this.start())); + $("#zone-clear").addEventListener("click", () => mask.reset()); + document.addEventListener("keydown", (e) => { + if (!this.active || e.target.closest("input, textarea")) return; + if (e.key === "Escape") this.stop(); + else if (e.key === "b" || e.key === "B") this.setTool("pennello"); + else if (e.key === "e" || e.key === "E") this.setTool("gomma"); + else if (e.key === "[" || e.key === "]") { + const r = $("#brush-size"); + r.value = String(Number(r.value) + (e.key === "]" ? 0.01 : -0.01)); + } else if (e.key === "z" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); mask.undo(); } + }); + }, +}; + +function renderZone() { + const zoned = mask.hasStrokes(); + $("#zone-text").textContent = zoned + ? "Cambio solo la parte dipinta: il resto della foto resta identico." + : "Senza zona cambia tutta l'immagine. Dipingi una parte e il resto resterà identico."; + $("#zone-btn-label").textContent = brush.active ? "Ho finito di dipingere" : zoned ? "Ritocca la zona" : "Dipingi la zona"; + $("#zone-btn").setAttribute("aria-pressed", String(brush.active)); + $("#zone-clear").hidden = !zoned; + document.body.dataset.zoned = String(zoned && state.mode === "modifica"); + if (state.models.klein) { + document.body.dataset.modelResolved = resolvedModel(); + renderPills(); + } +} + +/* ---------- palco: sviluppo, foto, confronto ---------- */ + +function grainTile() { + if (grainTile.url) return grainTile.url; + const c = document.createElement("canvas"); + c.width = c.height = 160; + const ctx = c.getContext("2d"); + const img = ctx.createImageData(160, 160); + for (let i = 0; i < img.data.length; i += 4) { + const v = Math.random() * 255; + img.data[i] = img.data[i + 1] = img.data[i + 2] = v; + img.data[i + 3] = 255; + } + ctx.putImageData(img, 0, 0); + grainTile.url = c.toDataURL("image/png"); + return grainTile.url; +} + +function showWorking(job) { + const stage = $("#stage"); + brush.stop(); + stage.dataset.state = "lavoro"; + $("#shot-bar").hidden = true; + $("#base-bar").hidden = true; + $("#next-bar").hidden = true; + const frame = $("#develop-frame"); + frame.style.setProperty("--ar", String(job.width / job.height)); + $("#develop-grain").style.backgroundImage = `url(${grainTile()})`; + let title = "In coda"; + let sub = "Parte appena si libera una GPU."; + if (job.status === "invio") { + title = "Invio la richiesta"; + sub = "Un attimo."; + } else if (job.status === "in_coda" && job.position != null) { + title = job.position === 0 ? "Sei il prossimo" : `In coda: ${job.position} prima di te`; + sub = job.eta ? `Circa ${Math.max(1, Math.round(job.eta))} s` : "Parte appena si libera una GPU."; + } else if (job.status === "salvataggio") { + title = "Quasi fatto"; + sub = "Salvo l'immagine nel tuo browser."; + } + const tool = TOOL_MODES.includes(job.request.mode); + if (job.status === "traduzione") { + title = "Traduco il prompt"; + sub = "Il testo in italiano diventa inglese."; + } else if (job.status === "caricamento") { + title = `Preparo ${job.model_name}`; + sub = "Succede la prima volta o quando cambi modello."; + } else if (job.status === "generazione" && job.request.mode === "rifinisci") { + title = "Z-Image ripassa la resa"; + sub = `passo ${Math.min(job.current_steps, Math.max(1, Math.ceil(job.progress * job.current_steps)))} di ${job.current_steps} · ${Math.round(job.elapsed)} s`; + } else if (job.status === "generazione" && job.refine && job.request.mode !== "rifinisci") { + const n = job.request.count; + const k = job.current_model === "klein"; + const idx = k ? job.current + 1 : job.current - n + 1; + title = k ? `Klein prepara ${n > 1 ? `l'immagine ${idx} di ${n}` : "l'immagine"}` : `Z-Image rifinisce ${n > 1 ? `l'immagine ${idx} di ${n}` : "l'immagine"}`; + sub = `${Math.round(job.elapsed)} s`; + } else if (job.status === "generazione" && job.request.mode === "viste") { + const names = ["lato sinistro", "retro", "lato destro"]; + title = `Giro la figura: ${names[job.current] || ""}`; + sub = `Vista ${job.current + 1} di ${job.total} · ${Math.round(job.elapsed)} s`; + } else if (job.status === "generazione" && tool) { + title = job.request.mode === "ingrandisci" ? "Raddoppio la risoluzione" : "Tolgo lo sfondo"; + sub = `${Math.round(job.elapsed)} s`; + } else if (job.status === "generazione") { + const total = job.total; + const within = Math.max(0, job.progress * total - job.current); + const steps = job.current_steps; + const step = Math.min(steps, Math.max(1, Math.ceil(within * steps))); + title = job.confronto ? `${job.model_name}, ${job.current + 1} di ${total}` : total > 1 ? `Immagine ${job.current + 1} di ${total}` : job.request.mask ? "Ridipingo la zona" : "Sto sviluppando l'immagine"; + sub = `${job.model_name} · passo ${step} di ${steps} · ${Math.round(job.elapsed)} s`; + } + $("#develop-title").textContent = title; + $("#develop-sub").textContent = sub; + const progress = job.status === "generazione" ? job.progress : job.status === "caricamento" || job.status === "traduzione" ? 0.02 : 0; + $("#develop-bar").style.transform = `scaleX(${Math.max(0, Math.min(1, progress))})`; + frame.dataset.phase = job.status; +} + +function describe(item) { + if (isPoster(item)) return ["Locandina", `${item.larghezza}×${item.altezza}`]; + if (isView(item)) return ["Vista per il 3D", item.vista || "", `${item.larghezza}×${item.altezza}`]; + const parts = [MODE_LABEL[item.modalita] || "Creata", item.modello_nome || "Z-Image Turbo"]; + if (isTool(item)) return [...parts, `${item.larghezza}×${item.altezza}`]; + if (item.maschera) parts.push("solo una zona"); + if (item.fedelta) parts.push(`fedeltà ${Number(item.fedelta).toFixed(2)}${item.fedelta_auto ? " auto" : ""}`); + const styles = stylesOf(item); + if (styles.length) parts.push(styleNames(styles)); + parts.push(`${item.larghezza}×${item.altezza}`, `seme ${item.seed}`); + return parts; +} + +const metaSpans = (item) => describe(item).map((t) => el("span", { text: t })); + +function showShot(item, fresh = false) { + state.current = item; + $("#base-bar").hidden = true; + document.body.dataset.stage = "foto"; + const stage = $("#stage"); + const img = $("#shot-img"); + img.classList.remove("fresh"); + img.onload = () => { + stage.dataset.state = "foto"; + if (fresh) { void img.offsetWidth; img.classList.add("fresh"); } + updateNextBar(); + sessionRender(); + }; + img.src = outputUrl(item.file); + img.alt = titleOf(item); + img.classList.toggle("checker", Boolean(item.trasparente)); + if (img.complete && img.naturalWidth) img.onload(); + $("#shot-bar").hidden = false; + $("#shot-prompt").textContent = titleOf(item); + $("#shot-prompt").title = item.prompt_finale || ""; + $("#shot-meta").replaceChildren(...metaSpans(item)); + const dl = $("#act-download"); + dl.href = outputUrl(item.file); + dl.download = item.file.split("/").pop(); + const save = $("#act-save"); + save.dataset.saved = String(!item.bozza); + $("#act-save-label").textContent = item.bozza ? "Salva in galleria" : "In galleria"; + $("#act-trash").title = item.bozza ? "Elimina la bozza" : "Sposta nel cestino"; + $("#act-back").hidden = !(state.batch.length > 1 && state.batch.some((b) => b.file === item.file)); + updateShotActions(); + updateNextBar(); +} + +function showCompare(items = state.batch, fresh = false) { + state.batch = items; + state.current = items[0]; + document.body.dataset.stage = "confronto"; + $("#stage").dataset.state = "confronto"; + $("#base-bar").hidden = true; + $("#next-bar").hidden = true; + const box = $("#compare"); + box.replaceChildren(); + const byModel = [...new Set(items.map((i) => i.modello))]; + const rows = !isView(items[0]) && byModel.length > 1 && items.length > byModel.length ? byModel.length : 1; + box.dataset.rows = String(rows); + box.style.setProperty("--cols", String(Math.ceil(items.length / rows))); + for (const item of items) { + const save = el("button", { + type: "button", + class: "save-btn", + "data-saved": String(!item.bozza), + onclick: () => saveItems([item]), + }, [icon("i-check"), el("span", { text: item.bozza ? "Salva" : "In galleria" })]); + box.append(el("div", { class: "card" }, [ + el("button", { type: "button", class: "card-media", title: "Guarda da sola", onclick: () => showShot(item) }, [ + el("img", { src: outputUrl(item.file), alt: titleOf(item), class: fresh ? "fresh" : "" }), + ]), + el("div", { class: "card-foot" }, [ + el("span", { class: "card-name" }, isView(item) + ? [item.vista, el("small", { text: `${item.larghezza}×${item.altezza}` })] + : [item.modello_nome, el("small", { text: `seme ${item.seed}, ${item.larghezza}×${item.altezza}` })]), + save, + ]), + ])); + } + $("#shot-bar").hidden = false; + $("#act-back").hidden = true; + $("#shot-prompt").textContent = isView(items[0]) ? "La stessa figura da altre angolazioni" : titleOf(items[0]); + $("#shot-prompt").title = items[0].prompt_finale || ""; + const first = isView(items[0]) ? ["Viste per il 3D", "da dare insieme alla frontale"] : describe(items[0]).filter((p, i) => i !== 1); + $("#shot-meta").replaceChildren(...first.map((t) => el("span", { text: t }))); + sessionRender(); + const allSaved = items.every((i) => !i.bozza); + const all = $("#act-save-all"); + all.dataset.saved = String(allSaved); + all.querySelector("span").textContent = allSaved ? "Tutte in galleria" : "Salva tutte"; +} + +async function saveItems(items) { + const drafts = items.filter((i) => i.bozza); + if (!drafts.length) return; + const { salvate } = await api("/api/keep", { files: drafts.map((d) => d.file) }); + const byName = new Map(salvate.map((s) => [s.file.split("/").pop(), s])); + const swap = (it) => (it && it.bozza && byName.has(it.file.split("/").pop()) ? byName.get(it.file.split("/").pop()) : it); + state.batch = state.batch.map(swap); + const current = swap(state.current); + sessionSwap(new Map(salvate.map((x) => [fileName(x.file), x]))); + if (document.body.dataset.stage === "confronto" && $("#stage").dataset.state === "confronto") showCompare(state.batch); + else if (current && $("#stage").dataset.state === "foto") showShot(current); + else state.current = current; + refreshDraftCount(); + toast(salvate.length === 1 ? "Salvata in galleria" : `${salvate.length} immagini salvate in galleria`); +} + +function updateShotActions() { + const it = state.current; + if (!it) return; + const other = otherModel(it.modello || "z-image"); + const mode = it.modalita || "crea"; + const canSwitch = !isFixed(it) && mode !== "modifica" && state.models[other]?.modalita.includes(mode); + $("#act-variant").disabled = isFixed(it); + $("#act-views").hidden = !isPrintable(it); + $("#act-refine").hidden = !canRefine(it); + $("#act-upscale").disabled = !state.tools.ingrandisci; + $("#act-cutout").disabled = !state.tools.scontorna || Boolean(it.trasparente); + $("#act-reuse").disabled = isFixed(it); + const btn = $("#act-other"); + btn.disabled = !canSwitch; + btn.title = canSwitch ? "Stesse impostazioni e stesso seme con l'altro modello" : isFixed(it) ? "Non serve per questa immagine" : "Solo FLUX.2 Klein sa modificare a comando"; + $("#act-other-label").textContent = canSwitch ? `Prova con ${state.models[other].nome.split(" ")[0]}` : "Altro modello"; +} + +function clearStage() { + state.current = null; + $("#base-bar").hidden = true; + $("#next-bar").hidden = true; + state.batch = []; + $("#stage").dataset.state = "vuoto"; + $("#shot-bar").hidden = true; +} + +/* ---------- bozze ---------- */ + +async function refreshDraftCount() { + try { + const { immagini } = await api("/api/history?limit=200&vista=bozze"); + $("#drafts-count").textContent = immagini.length ? String(immagini.length) : ""; + } catch { /* server spento */ } +} + +async function discardDraft(item) { + await api("/api/discard", { files: [item.file] }); + sessionRemove([item.file]); + state.batch = state.batch.filter((b) => b.file !== item.file); + if (state.batch.length > 1) showCompare(state.batch); + else if (state.batch[0]) showShot(state.batch[0]); + else clearStage(); + syncBase(); + refreshDraftCount(); + toast("Bozza eliminata"); +} + +async function discardFiles(files, all = false) { + const n = all ? Number($("#drafts-count").textContent || 0) : files.length; + if (!n) return; + if (n > 1 || all) { + const ok = await confirmDialog({ + title: all ? "Eliminare tutte le bozze?" : `Eliminare ${n} bozze?`, + text: "Le bozze eliminate non passano dal cestino: spariscono subito.", + confirm: "Elimina", + danger: true, + }); + if (!ok) return; + } + const { scartate } = await api("/api/discard", all ? { tutto: true } : { files }); + if (all) { state.session = state.session.filter((e) => e.item.bozza === false || e.item.esterna); sessionRender(); } else sessionRemove(files); + g.selected.clear(); + const gone = all ? null : new Set(files); + if (state.current?.bozza && (all || gone.has(state.current.file))) { + state.batch = all ? [] : state.batch.filter((b) => !gone.has(b.file)); + if ($("#stage").dataset.state !== "base") restoreStage(); + if (!state.batch.length && state.current?.bozza) clearStage(); + } + await Promise.all([loadGallery(), refreshDraftCount()]); + toast(scartate === 1 ? "Bozza eliminata" : `${scartate} bozze eliminate`); +} + +async function keepFiles(files) { + if (!files.length) return; + const { salvate } = await api("/api/keep", { files }); + sessionSwap(new Map(salvate.map((x) => [fileName(x.file), x]))); + g.selected.clear(); + await Promise.all([loadGallery(), refreshDraftCount()]); + toast(salvate.length === 1 ? "Salvata in galleria" : `${salvate.length} immagini salvate in galleria`); +} + +/* ---------- galleria ---------- */ + +const g = state.gallery; +const serverScope = (f) => (["cestino", "preferite", "bozze"].includes(f) ? f : "galleria"); + +function galleryVisible() { + if (["tutte", "preferite", "cestino", "bozze"].includes(g.filter)) return g.items; + return g.items.filter((i) => (i.modalita || "crea") === g.filter); +} + +async function loadGallery(reset = true) { + if (reset) { g.offset = 0; g.items = []; g.selected.clear(); } + const { immagini } = await api(`/api/history?limit=${PAGE}&offset=${g.offset}&vista=${serverScope(g.filter)}`); + g.items = g.items.concat(immagini); + g.offset += immagini.length; + g.full = immagini.length < PAGE; + renderGallery(); +} + +function renderGallery() { + const scope = serverScope(g.filter); + const inTrash = scope === "cestino"; + const inDrafts = scope === "bozze"; + document.body.dataset.scope = inTrash ? "cestino" : inDrafts ? "bozze" : "galleria"; + $("#gallery-title").textContent = inTrash ? "Cestino" : inDrafts ? "Bozze" : g.filter === "preferite" ? "Preferite" : "Galleria"; + $("#trash-note").hidden = !inTrash || g.items.length === 0; + $("#drafts-note").hidden = !inDrafts || g.items.length === 0; + const box = $("#masonry"); + box.replaceChildren(); + const items = galleryVisible(); + items.forEach((item, index) => { + const img = el("img", { src: outputUrl(item.miniatura || item.file), alt: titleOf(item), loading: "lazy" }); + img.width = item.larghezza; + img.height = item.altezza; + const tile = el("div", { + class: "tile", + tabindex: "0", + role: "button", + "aria-label": titleOf(item), + "aria-selected": String(g.selected.has(item.file)), + data: { file: item.file, fav: String(Boolean(item.preferita)) }, + onclick: () => (g.selected.size ? toggleSelect(item.file) : openDetail(index)), + onkeydown: (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); openDetail(index); } }, + }, [ + img, + el("button", { type: "button", class: "tile-check", "aria-label": "Seleziona", onclick: (e) => { e.stopPropagation(); toggleSelect(item.file); } }, [icon("i-check")]), + ...(scope === "galleria" || scope === "preferite" ? [el("button", { type: "button", class: "tile-star", "aria-label": "Preferita", onclick: (e) => { e.stopPropagation(); setFavorite([item], !item.preferita); } }, [icon("i-star")])] : []), + el("div", { class: "tile-info" }, [el("p", { class: "tile-title", text: titleOf(item) }), el("p", { class: "tile-meta" }, metaSpans(item))]), + ]); + box.append(tile); + }); + const empty = $("#gallery-empty"); + empty.hidden = items.length > 0; + empty.textContent = inTrash ? "Il cestino è vuoto." + : inDrafts ? "Nessuna bozza: quello che generi e non salvi finisce qui per 24 ore." + : g.filter === "preferite" ? "Nessuna preferita. Tocca la stella su un'immagine per aggiungerla." + : g.filter === "locandina" ? "Nessuna locandina. Componi la prima dalla scheda Locandina." + : "Nessuna immagine qui. Torna nello Studio e genera la prima."; + $("#more-btn").hidden = g.full; + updateSelectionBar(); +} + +function toggleSelect(file) { + if (g.selected.has(file)) g.selected.delete(file); else g.selected.add(file); + $$(".tile").forEach((t) => t.setAttribute("aria-selected", String(g.selected.has(t.dataset.file)))); + updateSelectionBar(); +} + +function updateSelectionBar() { + const n = g.selected.size; + $("#selection-bar").hidden = n === 0; + $("#masonry").dataset.selecting = String(n > 0); + $("#selection-count").textContent = n === 1 ? "1 selezionata" : `${n} selezionate`; +} + +async function setFavorite(items, value) { + for (const item of items) { + const updated = await api("/api/update", { file: item.file, modifiche: { preferita: value } }); + Object.assign(item, { preferita: updated.preferita }); + } + if (g.filter === "preferite" && !value) g.items = g.items.filter((i) => !items.includes(i)); + renderGallery(); + if (detailItem()) renderDetail(); +} + +async function moveToTrash(files) { + if (!files.length) return; + await api("/api/trash", { files }); + sessionRemove(files); + const gone = new Set(files); + g.items = g.items.filter((i) => !gone.has(i.file)); + g.selected.clear(); + renderGallery(); + if (state.current && gone.has(state.current.file)) { + state.batch = state.batch.filter((b) => !gone.has(b.file)); + if ($("#stage").dataset.state !== "base") { if (state.batch.length) restoreStage(); else clearStage(); } + } + const label = files.length === 1 ? "Spostata nel cestino" : `${files.length} immagini nel cestino`; + toast(label, { label: "Annulla", run: () => restoreFiles(files.map((f) => `_cestino/${f}`), true) }); +} + +async function restoreFiles(trashFiles, silent = false) { + if (!trashFiles.length) return; + const { ripristinate } = await api("/api/restore", { files: trashFiles }); + g.selected.clear(); + if (document.body.dataset.view === "galleria") await loadGallery(); + if (!silent) toast(ripristinate === 1 ? "Immagine ripristinata" : `${ripristinate} immagini ripristinate`); +} + +async function purgeFiles(trashFiles, all = false) { + const n = all ? g.items.length : trashFiles.length; + if (!n) return; + const what = n === 1 ? "questa immagine" : `${n} immagini`; + const ok = await confirmDialog({ + title: "Eliminare per sempre?", + text: `Stai per eliminare ${what} dal cestino. Non si può annullare.`, + confirm: "Elimina per sempre", + danger: true, + }); + if (!ok) return; + const { eliminate } = await api("/api/purge", all ? { tutto: true } : { files: trashFiles }); + g.selected.clear(); + await loadGallery(); + toast(eliminate === 1 ? "Eliminata per sempre" : `${eliminate} immagini eliminate per sempre`); +} + +/* ---------- conferma a tema ---------- */ + +function confirmDialog({ title, text, confirm = "Conferma", danger = false }) { + const dlg = $("#confirm"); + $("#confirm-title").textContent = title; + $("#confirm-text").textContent = text; + const yes = $("#confirm-yes"); + yes.textContent = confirm; + yes.classList.toggle("danger", danger); + yes.classList.toggle("primary", !danger); + dlg.returnValue = ""; + dlg.showModal(); + $("#confirm-no").focus(); + return new Promise((resolve) => dlg.addEventListener("close", () => resolve(dlg.returnValue === "si"), { once: true })); +} + +/* ---------- scheda dettaglio ---------- */ + +const detailItem = () => galleryVisible()[g.detailIndex]; + +function openDetail(index) { + g.detailIndex = index; + $(".detail-media").classList.remove("zoomed"); + renderDetail(); + const dlg = $("#detail"); + if (!dlg.open) dlg.showModal(); +} + +function renderDetail() { + const item = detailItem(); + if (!item) { $("#detail").close(); return; } + const dlg = $("#detail"); + const scope = serverScope(g.filter); + dlg.dataset.scope = scope === "preferite" ? "galleria" : scope; + $("#detail-img").src = outputUrl(item.file); + $("#detail-img").classList.toggle("checker", Boolean(item.trasparente)); + $("#d-variant").disabled = isFixed(item); + $("#d-style").disabled = !(item.prompt_finale || item.prompt) || isPoster(item) || isView(item); + $("#d-story").disabled = isPoster(item); + $("#d-views").hidden = !isPrintable(item); + $("#d-refine").hidden = !canRefine(item); + $("#d-upscale").disabled = !state.tools.ingrandisci; + $("#d-cutout").disabled = !state.tools.scontorna || Boolean(item.trasparente); + $("#detail-img").alt = titleOf(item); + const title = $("#detail-title"); + title.value = item.titolo || ""; + title.readOnly = scope !== "galleria" && scope !== "preferite"; + title.placeholder = item.prompt ? item.prompt.slice(0, 60) : "Senza titolo"; + $("#detail-prompt").textContent = item.prompt_finale || item.prompt || ""; + const rows = isPoster(item) + ? [["Tipo", "Locandina"], ["Misura", `${item.larghezza}×${item.altezza}`], ["Creata", item.creata]] + : [ + ["Modalità", MODE_LABEL[item.modalita] || "Creata"], + ...(item.vista ? [["Vista", item.vista]] : []), + ["Modello", item.modello_nome || "Z-Image Turbo"], + ...(item.maschera ? [["Zona", "Solo la parte dipinta"]] : []), + ...(stylesOf(item).length ? [["Stili", styleNames(stylesOf(item))]] : []), + ["Misura", `${item.larghezza}×${item.altezza}`], + ...(isTool(item) || isView(item) ? [] : [["Qualità", `${item.qualita || "bilanciata"}, ${item.passi} passi`], ["Seme", String(item.seed)]]), + ["Creata", `${item.creata}${item.origine === "claude" ? " da Claude" : ""}`], + ]; + $("#detail-meta").replaceChildren(...rows.flatMap(([k, v]) => [el("dt", { text: k }), el("dd", { text: v })])); + const fav = $("#d-fav"); + fav.setAttribute("aria-pressed", String(Boolean(item.preferita))); + $("#d-fav-label").textContent = item.preferita ? "Tra le preferite" : "Preferita"; + const dl = $("#d-download"); + dl.href = outputUrl(item.file); + dl.download = item.file.split("/").pop(); + const total = galleryVisible().length; + $("#detail-prev").disabled = g.detailIndex <= 0; + $("#detail-next").disabled = g.detailIndex >= total - 1; +} + +async function saveTitle() { + const item = detailItem(); + if (!item || !["galleria", "preferite"].includes(serverScope(g.filter))) return; + const value = $("#detail-title").value.trim(); + if (value === (item.titolo || "")) return; + const updated = await api("/api/update", { file: item.file, modifiche: { titolo: value } }); + item.titolo = updated.titolo; + if (state.current?.file === item.file) state.current.titolo = updated.titolo; + renderGallery(); + toast(value ? "Titolo salvato" : "Titolo tolto"); +} + +function stepDetail(delta) { + const next = g.detailIndex + delta; + if (next < 0 || next >= galleryVisible().length) return; + saveTitle(); + g.detailIndex = next; + renderDetail(); +} + +/* ---------- viste ---------- */ + +function setView(view) { + document.body.dataset.view = view; + $$(".views button").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.view === view))); + $("#studio").hidden = view !== "studio"; + $("#gallery").hidden = view !== "galleria"; + $("#poster").hidden = view !== "locandina"; + if (view === "galleria") { loadGallery(); refreshDraftCount(); } + if (view === "locandina") window.PosterStudio?.show(); +} + +/* ---------- generazione ---------- */ + +async function readForm() { + saveFieldValues(); + const campi = {}; + for (const id of state.styles) for (const f of templateById(id)?.campi || []) campi[f.id] = state.fieldValues[f.id] || ""; + const seed = $("#seed").value.trim(); + const payload = { + modalita: state.mode, + modello: state.model, + prompt: $("#prompt").value, + stili: ["modifica", "continua"].includes(state.mode) ? [] : state.styles, + campi, + riferimenti: state.refs.slice(0, MODES[state.mode].maxRefs).map((r) => r.file), + formato: state.aspect, + qualita: state.quality, + fedelta: $("#fidelity-auto").checked ? null : Number($("#fidelity").value), + seed: seed === "" ? null : Number(seed), + quantita: state.count, + traduci: $("#translate").checked, + }; + if (state.mode === "modifica" && mask.hasStrokes() && payload.prompt.trim() && payload.riferimenti.length) { + payload.maschera = await mask.upload(); + } + return payload; +} + +function runRefine(item) { + if (!canRefine(item)) return; + state.refineFrom = item; + submit({ + modalita: "rifinisci", + riferimenti: ["outputs/" + item.file], + prompt: item.prompt || "", + stili: stylesOf(item).filter((id) => templateById(id)), + qualita: state.quality, + }); +} + +function runViews(item) { + if (!item) return; + submit({ modalita: "viste", riferimenti: ["outputs/" + item.file], qualita: state.quality }); +} + +function runTool(item, tool) { + if (!item) return; + submit({ modalita: tool, riferimenti: ["outputs/" + item.file] }); +} + +/* ---------- vettorizza: PNG → SVG ---------- */ + +const vectorizer = { + source: null, + style: "colori", + svg: "", + ticket: 0, + open(path, name) { + if (!state.tools.vettorizza) { + toast("Manca il vettorizzatore: rilancia Installa.command una volta."); + return; + } + this.source = path; + this.name = (name || path.split("/").pop()).replace(/\.[a-z0-9]+$/i, ""); + $("#vector-dlg").showModal(); + this.run(); + }, + async run() { + const ticket = ++this.ticket; + const view = $("#vector-view"); + view.dataset.state = "lavoro"; + $("#vector-download").disabled = true; + $("#vector-stats").textContent = ""; + try { + const res = await api("/api/vectorize", { file: this.source, stile: this.style, trasparente: $("#vector-transparent").checked }); + if (ticket !== this.ticket) return; + this.svg = res.svg; + $("#vector-art").innerHTML = res.svg; + $("#vector-stats").textContent = `${res.tracciati} forme · ${res.kb.toLocaleString("it-IT")} KB`; + $("#vector-warn").hidden = !res.foto || this.style === "contorno"; + $("#vector-download").disabled = false; + view.dataset.state = "pronto"; + } catch (err) { + if (ticket !== this.ticket) return; + view.dataset.state = "errore"; + $("#vector-stats").textContent = err.message; + } + }, + download() { + const url = URL.createObjectURL(new Blob([this.svg], { type: "image/svg+xml" })); + const a = Object.assign(document.createElement("a"), { href: url, download: `${this.name}_${this.style}.svg` }); + a.click(); + setTimeout(() => URL.revokeObjectURL(url), 2000); + }, + bind() { + $("#vector-styles").addEventListener("click", (e) => { + const btn = e.target.closest("[role=radio]"); + if (!btn || btn.dataset.v === this.style) return; + this.style = btn.dataset.v; + radio($("#vector-styles"), "v", this.style); + this.run(); + }); + $("#vector-transparent").addEventListener("change", () => this.run()); + $("#vector-dark").addEventListener("change", (e) => $("#vector-view").classList.toggle("dark", e.target.checked)); + $("#vector-close").addEventListener("click", () => $("#vector-dlg").close()); + $("#vector-download").addEventListener("click", () => this.download()); + $("#vector-dlg").addEventListener("close", () => { this.ticket++; $("#vector-art").innerHTML = ""; }); + }, +}; + +/* ---------- prompt migliorato: inglese per il modello, italiano per te ---------- */ + +const bilingual = { + on: false, + syncedIt: "", + syncedEn: "", + open(en, it) { + this.on = true; + $("#prompt").value = en; + $("#prompt-it").value = it; + this.syncedIt = it; + this.syncedEn = en; + $("#prompt-area").classList.add("bilingual"); + this.check(); + autosize(); + }, + close() { + this.on = false; + $("#prompt-area").classList.remove("bilingual"); + $("#prompt-it").value = ""; + autosize(); + }, + check() { + $("#sync-en").hidden = !this.on || $("#prompt-it").value.trim() === this.syncedIt.trim(); + $("#sync-it").hidden = !this.on || $("#prompt").value.trim() === this.syncedEn.trim(); + }, + async sync(direction) { + const from = direction === "en" ? $("#prompt-it") : $("#prompt"); + const to = direction === "en" ? $("#prompt") : $("#prompt-it"); + const btn = direction === "en" ? $("#sync-en") : $("#sync-it"); + btn.textContent = "Traduco…"; + btn.disabled = true; + try { + const { testo } = await api("/api/translate", { testo: from.value, verso: direction }); + to.value = testo; + this.syncedIt = $("#prompt-it").value; + this.syncedEn = $("#prompt").value; + autosize(); + } catch (e) { + $("#form-error").textContent = e.message; + } finally { + btn.textContent = direction === "en" ? "Aggiorna l'inglese" : "Aggiorna l'italiano"; + btn.disabled = false; + this.check(); + } + }, + wire() { + $("#prompt-it").addEventListener("input", () => { this.check(); autosize(); }); + $("#prompt").addEventListener("input", () => this.check()); + $("#sync-en").addEventListener("click", () => this.sync("en")); + $("#sync-it").addEventListener("click", () => this.sync("it")); + $("#bilingual-close").addEventListener("click", () => this.close()); + }, +}; + +async function enhancePrompt() { + const field = $("#prompt"); + const before = bilingual.on ? $("#prompt-it").value : field.value; + if (!before.trim()) { + $("#form-error").textContent = "Scrivi prima un'idea, anche in italiano: la trasformo in un prompt dettagliato."; + return; + } + const btn = $("#enhance-btn"); + btn.setAttribute("aria-busy", "true"); + $("#form-error").textContent = ""; + try { + const { prompt, italiano } = await api("/api/enhance", { prompt: before, modalita: state.mode }); + bilingual.open(prompt, italiano || ""); + toast("A sinistra in italiano, a destra quello che va al modello. Correggi pure, poi genera", { + label: "Annulla", + run: () => { bilingual.close(); field.value = before; autosize(); }, + }); + } catch (e) { + $("#form-error").textContent = e.message; + } finally { + btn.removeAttribute("aria-busy"); + } +} + +function payloadFromItem(item, overrides = {}) { + return { + modalita: item.modalita || "crea", + modello: item.modello || "auto", + prompt: item.prompt, + stili: stylesOf(item).filter((id) => templateById(id)), + campi: item.campi || {}, + riferimenti: item.riferimenti || [], + maschera: item.maschera || null, + formato: item.formato, + qualita: item.qualita || "bilanciata", + fedelta: item.fedelta_auto ? null : item.fedelta ?? null, + seed: item.seed, + quantita: 1, + ...overrides, + }; +} + +async function submitFromComposer() { + if (state.busy) return; + try { + submit(await readForm(), true); + } catch (e) { + $("#form-error").textContent = e.message; + } +} + +async function submit(payload, fromComposer = false) { + if (state.busy) return; + const err = $("#form-error"); + err.textContent = ""; + state.busy = true; + $("#generate-btn").disabled = true; + try { + const job = await api("/api/generate", payload); + if (fromComposer && payload.prompt.trim()) { + state.lastPrompt = payload.prompt; + $("#prompt").value = ""; + bilingual.close(); + autosize(); + } + setView("studio"); + showWorking(job); + track(job.id); + } catch (e) { + err.textContent = e.message; + state.busy = false; + $("#generate-btn").disabled = false; + } +} + +function finishJob() { + state.busy = false; + $("#generate-btn").disabled = false; + refreshStatus(); + refreshDraftCount(); +} + +function track(jobId) { + clearInterval(state.polling); + state.polling = setInterval(async () => { + let job; + try { job = await api(`/api/jobs/${jobId}`); } catch { return; } + if (job.status === "fatto" || job.status === "errore") { + clearInterval(state.polling); + finishJob(); + if (job.status === "errore") { + if (job.error_code === "quota") window.PixOnline?.quota(job.retry_in); + else $("#form-error").textContent = job.error; + if (state.lastPrompt && !$("#prompt").value) { $("#prompt").value = state.lastPrompt; autosize(); } + if (state.mode !== "crea" && state.refs[0]) syncBase(); else restoreStage(); + return; + } + const n = job.results.length; + sessionAdd(job.results, job.id); + if (job.request.mode === "rifinisci" && state.refineFrom) { + state.batch = [state.refineFrom, ...job.results]; + state.refineFrom = null; + showCompare(state.batch, true); + toast("Prima e dopo: tieni quella che ti piace di più"); + return; + } + state.batch = job.results; + if (n > 1) showCompare(job.results, true); + else showShot(job.results[0], true); + if (job.results[0]?.nota) { toast(job.results[0].nota); return; } + if (job.request.mode === "viste") { toast("Viste pronte: salva quelle buone e dalle a Tripo, Meshy o Hunyuan3D insieme alla frontale"); return; } + toast(n > 1 ? `${n} immagini pronte in ${job.elapsed} s: salva quelle che ti piacciono` : `Pronta in ${job.elapsed} s`); + return; + } + showWorking(job); + if (job.status === "caricamento") refreshStatus(); + }, 600); +} + +/* ---------- azioni sullo scatto ---------- */ + +function reuse(item = state.current) { + if (!item || isFixed(item)) return; + setView("studio"); + state.refs = (item.riferimenti || []).map((file) => ({ file })); + state.model = item.modello || "auto"; + state.styles = stylesOf(item).filter((id) => templateById(id)); + state.fieldValues = { ...(item.campi || {}) }; + state.quality = item.qualita || "bilanciata"; + radio($("#quality"), "v", state.quality); + $("#fidelity-auto").checked = item.fedelta_auto !== false || !item.fedelta; + if (item.fedelta) $("#fidelity").value = item.fedelta; + $("#fidelity").dispatchEvent(new Event("input")); + $("#prompt").value = item.prompt || ""; + $("#seed").value = item.seed; + setMode(item.modalita || "crea"); + renderStyleState(); + state.aspectTouched = true; + renderAspects(); + selectAspect(item.formato); + autosize(); + if (state.mode === "crea") showShot(item); + toast("Impostazioni caricate, seme compreso"); +} + +function openInPoster(item) { + if (!item) return; + setView("locandina"); + window.PosterStudio?.setBackground("outputs/" + item.file); +} + +/* ---------- eventi ---------- */ + +function autosize() { + for (const t of [$("#prompt"), $("#prompt-it")]) { + t.style.height = "auto"; + t.style.height = `${Math.min(bilingual.on ? 220 : 180, t.scrollHeight)}px`; + } +} + +function wire() { + $("#composer").addEventListener("submit", (e) => { e.preventDefault(); submitFromComposer(); }); + document.addEventListener("keydown", (e) => { + if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && document.body.dataset.view === "studio" && !document.querySelector("dialog[open]:not(#guide)")) { + e.preventDefault(); + submitFromComposer(); + } + if ($("#detail").open && document.activeElement !== $("#detail-title")) { + if (e.key === "ArrowLeft") stepDetail(-1); + if (e.key === "ArrowRight") stepDetail(1); + } + }); + const prompt = $("#prompt"); + prompt.addEventListener("input", autosize); + prompt.addEventListener("keydown", (e) => { + if (e.key === "ArrowUp" && !prompt.value && state.lastPrompt) { + e.preventDefault(); + prompt.value = state.lastPrompt; + autosize(); + } + }); + $$(".modes [role=tab]").forEach((t) => t.addEventListener("click", () => setMode(t.dataset.mode))); + $$(".views button").forEach((b) => b.addEventListener("click", () => setView(b.dataset.view))); + $("#file-input").addEventListener("change", (e) => { addFiles(e.target.files); e.target.value = ""; }); + + const stage = $("#stage"); + let depth = 0; + const hasFiles = (e) => [...(e.dataTransfer?.types || [])].includes("Files"); + document.addEventListener("dragenter", (e) => { if (hasFiles(e) && document.body.dataset.view === "studio") { depth++; stage.classList.add("dragging"); } }); + document.addEventListener("dragleave", () => { depth = Math.max(0, depth - 1); if (!depth) stage.classList.remove("dragging"); }); + document.addEventListener("dragover", (e) => { if (hasFiles(e)) e.preventDefault(); }); + document.addEventListener("drop", (e) => { + if (!hasFiles(e)) return; + e.preventDefault(); + depth = 0; + stage.classList.remove("dragging"); + if (document.body.dataset.view === "locandina") return; + setView("studio"); + addFiles(e.dataTransfer.files); + }); + document.addEventListener("paste", (e) => { + if (document.body.dataset.view !== "studio") return; + const files = [...(e.clipboardData?.files || [])].filter((f) => f.type.startsWith("image/")); + if (files.length) { e.preventDefault(); addFiles(files); } + }); + + $("#quality").addEventListener("click", (e) => { + const b = e.target.closest("[data-v]"); + if (!b) return; + state.quality = b.dataset.v; + radio($("#quality"), "v", state.quality); + updateQualityNote(); + renderPills(); + }); + $("#count").addEventListener("click", (e) => { + const b = e.target.closest("[data-v]"); + if (!b) return; + state.count = Number(b.dataset.v); + radio($("#count"), "v", b.dataset.v); + renderPills(); + }); + const fid = $("#fidelity"); + const fidAuto = $("#fidelity-auto"); + const fidNote = () => { + const v = Number(fid.value); + const auto = fidAuto.checked; + $("#fidelity-manual").hidden = auto; + $("#fidelity-auto-note").hidden = !auto; + $("#fidelity-out").textContent = auto ? "Auto" : v.toFixed(2); + $("#fidelity-note").textContent = v <= 0.25 ? "Molto libero: tiene colori e posa, ridisegna il resto." + : v <= 0.4 ? "Equilibrato: riconoscibile, ma con spazio per cambiare." + : v <= 0.6 ? "Fedele: cambia lo stile, forme e proporzioni restano quelle." + : "Quasi identica: solo un ritocco di stile."; + }; + fid.addEventListener("input", fidNote); + fidAuto.addEventListener("change", fidNote); + fidNote(); + $("#seed-dice").addEventListener("click", () => ($("#seed").value = Math.floor(Math.random() * 2147483647))); + + // scatto nello studio + $("#act-variant").addEventListener("click", () => state.current && submit(payloadFromItem(state.current, { seed: null }))); + $("#act-other").addEventListener("click", () => { + const it = state.current; + if (it) submit(payloadFromItem(it, { modello: otherModel(it.modello || "z-image") })); + }); + $("#act-edit").addEventListener("click", () => state.current && useAsRef(state.current, "modifica")); + $("#act-restyle").addEventListener("click", () => state.current && useAsRef(state.current, "ristila")); + $("#act-reuse").addEventListener("click", () => reuse()); + $("#act-upscale").addEventListener("click", () => runTool(state.current, "ingrandisci")); + $("#act-cutout").addEventListener("click", () => runTool(state.current, "scontorna")); + $("#act-poster").addEventListener("click", () => openInPoster(state.current)); + $("#act-vector").addEventListener("click", () => state.current && vectorizer.open("outputs/" + state.current.file, state.current.file)); + $("#b-vector").addEventListener("click", () => baseRef() && vectorizer.open(baseRef(), state.refs[0]?.name)); + vectorizer.bind(); + $("#act-views").addEventListener("click", () => runViews(state.current)); + $("#act-refine").addEventListener("click", () => runRefine(state.current)); + const baseRef = () => state.refs[0]?.file; + $("#b-upscale").addEventListener("click", () => baseRef() && submit({ modalita: "ingrandisci", riferimenti: [baseRef()] })); + $("#b-cutout").addEventListener("click", () => baseRef() && submit({ modalita: "scontorna", riferimenti: [baseRef()] })); + $("#b-poster").addEventListener("click", () => { if (baseRef()) { setView("locandina"); window.PosterStudio?.setBackground(baseRef()); } }); + $("#enhance-btn").addEventListener("click", enhancePrompt); + const translate = $("#translate"); + translate.checked = prefs.get("traduci", true); + translate.addEventListener("change", () => prefs.set("traduci", translate.checked)); + $("#act-copy").addEventListener("click", async () => { + if (!state.current) return; + await navigator.clipboard.writeText(state.current.prompt_finale || state.current.prompt); + toast("Prompt completo copiato"); + }); + $("#act-trash").addEventListener("click", () => { + const it = state.current; + if (!it) return; + if (it.bozza) discardDraft(it); else moveToTrash([it.file]); + }); + $("#act-save").addEventListener("click", () => state.current && saveItems([state.current])); + $("#act-save-all").addEventListener("click", () => saveItems(state.batch)); + $("#act-back").addEventListener("click", () => showCompare(state.batch)); + + // stili salvati + $("#sd-save").addEventListener("click", saveStyleDialog); + $("#sd-delete").addEventListener("click", deleteStyleDialog); + $("#style-form").addEventListener("submit", (e) => { if (e.submitter?.value !== "no") { e.preventDefault(); saveStyleDialog(); } }); + $("#sd-from-prompt").addEventListener("click", () => { + const text = $("#prompt").value.trim() || state.lastPrompt; + if (text) $("#sd-text").value = text; + else $("#sd-error").textContent = "Nel campo del prompt non c'è ancora niente."; + }); + + // galleria + $("#filters").addEventListener("click", (e) => { + const b = e.target.closest("[data-f]"); + if (!b) return; + const was = serverScope(g.filter); + g.filter = b.dataset.f; + radio($("#filters"), "f", g.filter); + g.selected.clear(); + if (serverScope(g.filter) !== was) loadGallery(); else renderGallery(); + }); + $("#more-btn").addEventListener("click", () => loadGallery(false)); + $("#empty-trash").addEventListener("click", () => purgeFiles([], true)); + $("#drafts-clear").addEventListener("click", () => discardFiles([], true)); + $("#sel-clear").addEventListener("click", () => { g.selected.clear(); renderGallery(); }); + $("#sel-trash").addEventListener("click", () => moveToTrash([...g.selected])); + $("#sel-keep").addEventListener("click", () => keepFiles([...g.selected])); + $("#sel-discard").addEventListener("click", () => discardFiles([...g.selected])); + $("#sel-fav").addEventListener("click", () => { + const items = g.items.filter((i) => g.selected.has(i.file)); + const value = !items.every((i) => i.preferita); + g.selected.clear(); + setFavorite(items, value); + }); + $("#sel-restore").addEventListener("click", () => restoreFiles([...g.selected])); + $("#sel-purge").addEventListener("click", () => purgeFiles([...g.selected])); + + // scheda dettaglio + const dlg = $("#detail"); + $("#detail-close").addEventListener("click", () => dlg.close()); + dlg.addEventListener("click", (e) => { if (e.target === dlg) dlg.close(); }); + dlg.addEventListener("close", saveTitle); + $("#detail-title").addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); saveTitle(); e.target.blur(); } }); + $("#detail-title").addEventListener("blur", saveTitle); + $("#detail-img").addEventListener("click", () => $(".detail-media").classList.toggle("zoomed")); + $("#detail-prev").addEventListener("click", () => stepDetail(-1)); + $("#detail-next").addEventListener("click", () => stepDetail(1)); + const fromDetail = (fn) => () => { const it = detailItem(); if (!it) return; dlg.close(); fn(it); }; + const openStudio = (it) => { setView("studio"); state.batch = [it]; if (state.mode !== "crea" && state.refs.length) setMode("crea"); showShot(it); }; + $("#d-open").addEventListener("click", fromDetail(openStudio)); + $("#d-open-draft").addEventListener("click", fromDetail(openStudio)); + $("#d-keep").addEventListener("click", fromDetail((it) => keepFiles([it.file]))); + $("#d-discard").addEventListener("click", fromDetail((it) => discardFiles([it.file]))); + $("#d-edit").addEventListener("click", fromDetail((it) => useAsRef(it, "modifica"))); + $("#d-restyle").addEventListener("click", fromDetail((it) => useAsRef(it, "ristila"))); + $("#d-variant").addEventListener("click", fromDetail((it) => submit(payloadFromItem(it, { seed: null })))); + $("#d-upscale").addEventListener("click", fromDetail((it) => runTool(it, "ingrandisci"))); + $("#d-cutout").addEventListener("click", fromDetail((it) => runTool(it, "scontorna"))); + $("#d-poster").addEventListener("click", fromDetail(openInPoster)); + $("#d-vector").addEventListener("click", () => { const it = detailItem(); if (it) vectorizer.open("outputs/" + it.file, it.file); }); + $("#d-views").addEventListener("click", fromDetail(runViews)); + $("#d-refine").addEventListener("click", fromDetail(runRefine)); + $("#d-story").addEventListener("click", fromDetail((it) => useAsRef(it, "continua"))); + $("#d-style").addEventListener("click", fromDetail((it) => openStyleDialog(null, it))); + $("#d-fav").addEventListener("click", () => { const it = detailItem(); if (it) setFavorite([it], !it.preferita); }); + $("#d-trash").addEventListener("click", fromDetail((it) => moveToTrash([it.file]))); + $("#d-restore").addEventListener("click", fromDetail((it) => restoreFiles([it.file]))); + $("#d-purge").addEventListener("click", fromDetail((it) => purgeFiles([it.file]))); + + mask.init(); + brush.wire(); + shotMenu.wire(); + bilingual.wire(); + $("#next-use").addEventListener("click", continueFromCurrent); + $("#next-stay").addEventListener("click", () => { + state.nextDismissed = state.current?.file || ""; + state.current = null; + $("#stage").dataset.state = ""; + syncBase(); + updateNextBar(); + sessionRender(); + toast("Sei sull'originale: la nuova versione resta nella colonna Sessione a sinistra"); + }); + $("#session-clear").addEventListener("click", () => { state.session = []; sessionRender(); }); + document.addEventListener("keydown", (e) => { + if (document.body.dataset.view !== "studio" || document.querySelector("dialog[open]:not(#guide)") || brush.active) return; + if (e.target.closest("input, textarea, select")) return; + if (e.key === "ArrowLeft" || e.key === "ArrowUp") { e.preventDefault(); sessionStep(-1); } + if (e.key === "ArrowRight" || e.key === "ArrowDown") { e.preventDefault(); sessionStep(1); } + }); +} + +async function init() { + if (window.PixBackend) await window.PixBackend.ready; + wire(); + const s = await refreshStatus(); + if (s) { + state.aspects = s.formati; + state.tools = s.strumenti || {}; + if (!s.traduttore) $("#enhance-btn").hidden = true; + state.models = s.modelli; + state.auto = s.automatico; + } + state.templates = (await api("/api/templates")).template; + renderTemplates(); + setMode("crea"); + refreshDraftCount(); + setInterval(refreshStatus, 10000); +} + +window.PixRick = { api, toast, el, icon, radio, prefs, mediaUrl, outputUrl, confirmDialog, setView, refreshDraftCount }; + +init(); diff --git a/web/backend.js b/web/backend.js new file mode 100644 index 0000000000000000000000000000000000000000..d561e063ba597f23a9c1bc9add3100fcdadae833 --- /dev/null +++ b/web/backend.js @@ -0,0 +1,596 @@ +/* PixRick online: le stesse API dell'app sul computer, ma la galleria vive nel browser + e la generazione passa dal motore su Hugging Face. Niente immagini restano sul server. */ +(() => { + "use strict"; + + const DB_NAME = "pixrick"; + const DRAFT_TTL_MS = 24 * 3600 * 1000; + const THUMB_SIDE = 640; + const MAX_INPUT_SIDE = 2048; + const MAX_UPLOAD_BYTES = 25 * 1024 * 1024; + const ENGINE_PATH = "/motore/"; + + /* ---------- archivio nel browser ---------- */ + + let dbPromise = null; + function db() { + dbPromise ||= new Promise((resolve, reject) => { + const req = indexedDB.open(DB_NAME, 1); + req.onupgradeneeded = () => { + const d = req.result; + d.createObjectStore("blobs"); + const items = d.createObjectStore("items", { keyPath: "file" }); + items.createIndex("scope", "scope"); + d.createObjectStore("kv"); + }; + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); + return dbPromise; + } + + async function tx(stores, mode, work) { + const d = await db(); + return new Promise((resolve, reject) => { + const t = d.transaction(stores, mode); + let out; + t.oncomplete = () => resolve(out); + t.onerror = () => reject(t.error); + t.onabort = () => reject(t.error || new Error("Archivio del browser non disponibile.")); + out = work(...[].concat(stores).map((s) => t.objectStore(s))); + }); + } + + const req2p = (r) => new Promise((resolve, reject) => { r.onsuccess = () => resolve(r.result); r.onerror = () => reject(r.error); }); + + async function readBlob(path) { + const d = await db(); + return req2p(d.transaction("blobs").objectStore("blobs").get(path)); + } + async function readItem(file) { + const d = await db(); + return req2p(d.transaction("items").objectStore("items").get(file)); + } + async function itemsIn(scope) { + const d = await db(); + return req2p(d.transaction("items").objectStore("items").index("scope").getAll(scope)); + } + async function kvGet(key, fallback) { + const d = await db(); + const v = await req2p(d.transaction("kv").objectStore("kv").get(key)); + return v === undefined ? fallback : v; + } + const kvSet = (key, value) => tx("kv", "readwrite", (s) => { s.put(value, key); }); + + /* ---------- immagini ---------- */ + + const pad = (n) => String(n).padStart(2, "0"); + const today = (d = new Date()) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; + const clock = (d = new Date()) => `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`; + const stamp = (d = new Date()) => `${today(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; + const rand = () => Math.random().toString(16).slice(2, 8); + + async function bitmap(blob) { + try { + return await createImageBitmap(blob, { imageOrientation: "from-image" }); + } catch { + throw new Error("Il file non è un'immagine leggibile."); + } + } + + function canvasOf(w, h) { + const c = document.createElement("canvas"); + c.width = w; + c.height = h; + return c; + } + + const toBlob = (canvas, type, quality) => new Promise((r) => canvas.toBlob(r, type, quality)); + + async function thumbnail(blob) { + const bmp = await bitmap(blob); + const k = Math.min(1, THUMB_SIDE / Math.max(bmp.width, bmp.height)); + const c = canvasOf(Math.round(bmp.width * k), Math.round(bmp.height * k)); + c.getContext("2d").drawImage(bmp, 0, 0, c.width, c.height); + bmp.close?.(); + return (await toBlob(c, "image/webp", 0.84)) || toBlob(c, "image/png"); + } + + /** Ruota secondo l'EXIF, rimpicciolisce e riscrive in PNG: via EXIF e posizione GPS. */ + async function cleanUpload(file) { + if (file.size > MAX_UPLOAD_BYTES) throw new Error("Immagine troppo pesante (massimo 25 MB)."); + const bmp = await bitmap(file); + const k = Math.min(1, MAX_INPUT_SIDE / Math.max(bmp.width, bmp.height)); + const c = canvasOf(Math.round(bmp.width * k), Math.round(bmp.height * k)); + const ctx = c.getContext("2d"); + ctx.fillStyle = "#fff"; + ctx.fillRect(0, 0, c.width, c.height); + ctx.drawImage(bmp, 0, 0, c.width, c.height); + bmp.close?.(); + return { blob: await toBlob(c, "image/png"), width: c.width, height: c.height }; + } + + /* ---------- galleria ---------- */ + + // Percorsi come sul computer: bozze in _bozze/, galleria per giorno, cestino in _cestino/. + const SCOPE_PREFIX = { bozze: "_bozze/", galleria: "", cestino: "_cestino/" }; + const thumbPath = (scope, day, stem) => (scope === "galleria" ? `.miniature/${day}/${stem}.webp` : `${SCOPE_PREFIX[scope]}${day}/${stem}.webp`); + + function splitFile(file) { + const parts = file.split("/"); + const name = parts.pop(); + return { day: parts.pop(), stem: name.replace(/\.png$/, "") }; + } + + async function storeItem(scope, meta, png, thumb) { + const day = today(); + const stem = meta._stem || `${clock()}_${meta.modalita || "crea"}_${meta.modello || "img"}_${rand()}`; + delete meta._stem; + const file = `${SCOPE_PREFIX[scope]}${day}/${stem}.png`; + const mini = thumbPath(scope, day, stem); + const item = { ...meta, file, miniatura: mini, bozza: scope === "bozze", titolo: meta.titolo || "", preferita: !!meta.preferita }; + await tx(["blobs", "items"], "readwrite", (blobs, items) => { + blobs.put(png, "outputs/" + file); + blobs.put(thumb, "outputs/" + mini); + items.put({ file, scope, t: Date.now(), meta: item }); + }); + return item; + } + + async function move(file, fromScope, toScope) { + const rec = await readItem(file); + if (!rec || rec.scope !== fromScope) return null; + const { day, stem } = splitFile(file); + const newFile = `${SCOPE_PREFIX[toScope]}${day}/${stem}.png`; + const newMini = thumbPath(toScope, day, stem); + const png = await readBlob("outputs/" + file); + const thumb = await readBlob("outputs/" + rec.meta.miniatura); + const meta = { ...rec.meta, file: newFile, miniatura: newMini, bozza: toScope === "bozze" }; + await tx(["blobs", "items"], "readwrite", (blobs, items) => { + blobs.delete("outputs/" + file); + blobs.delete("outputs/" + rec.meta.miniatura); + items.delete(file); + if (png) blobs.put(png, "outputs/" + newFile); + if (thumb) blobs.put(thumb, "outputs/" + newMini); + items.put({ file: newFile, scope: toScope, t: rec.t, meta }); + }); + return meta; + } + + async function remove(file, scope) { + const rec = await readItem(file); + if (!rec || (scope && rec.scope !== scope)) return false; + await tx(["blobs", "items"], "readwrite", (blobs, items) => { + blobs.delete("outputs/" + file); + blobs.delete("outputs/" + rec.meta.miniatura); + items.delete(file); + }); + return true; + } + + async function history(params) { + const scope = params.get("vista") || "galleria"; + const limit = Math.min(200, Number(params.get("limit") || 60)); + const offset = Math.max(0, Number(params.get("offset") || 0)); + const real = scope === "preferite" ? "galleria" : scope; + let list = (await itemsIn(real)).map((r) => r.meta); + if (scope === "preferite") list = list.filter((m) => m.preferita); + list.sort((a, b) => (a.file < b.file ? 1 : -1)); + return { immagini: list.slice(offset, offset + limit) }; + } + + async function cleanOld() { + const limit = Date.now() - DRAFT_TTL_MS; + for (const rec of await itemsIn("bozze")) if (rec.t < limit) await remove(rec.file, "bozze"); + const used = new Set(); + for (const scope of ["galleria", "cestino", "bozze"]) { + for (const rec of await itemsIn(scope)) { + (rec.meta.riferimenti || []).forEach((r) => used.add(r)); + if (rec.meta.maschera) used.add(rec.meta.maschera); + } + } + const inputs = (await kvGet("inputs", {})) || {}; + let changed = false; + for (const [path, t] of Object.entries(inputs)) { + if (t < limit && !used.has(path)) { + await tx("blobs", "readwrite", (s) => s.delete(path)); + delete inputs[path]; + changed = true; + } + } + if (changed) await kvSet("inputs", inputs); + } + + async function saveInput(blob, name) { + const path = `inputs/${today()}/${clock()}_${rand()}.png`; + await tx("blobs", "readwrite", (s) => { s.put(blob, path); }); + const inputs = (await kvGet("inputs", {})) || {}; + inputs[path] = Date.now(); + await kvSet("inputs", inputs); + return path; + } + + /* ---------- stili dell'utente ---------- */ + + const ITALIAN = /\b(il|lo|la|gli|le|un|una|uno|di|del|della|dei|delle|che|con|per|sul|sulla|nel|nella|non|più|mentre|sopra|sotto|dietro|davanti|vicino|foto|immagine|ragazza|ragazzo|uomo|donna|cielo|mare|togli|metti|aggiungi|cambia|rendi|sostituisci|fai)\b|[àèéìòù]/i; + const looksItalian = (t) => ITALIAN.test(t.replace(/"[^"]*"/g, "")); + + const userStyles = () => kvGet("stili", []); + + async function saveStyle(data) { + const name = String(data.nome || "").trim().slice(0, 40); + const text = String(data.testo || "").trim().slice(0, 600); + if (!name || !text) throw new Error("Servono un nome e una descrizione dello stile."); + let english = text; + if (looksItalian(text)) english = (await write("traduci", text)) || text; + const items = await userStyles(); + let id = String(data.id || ""); + if (!id.startsWith("u-") || !items.some((i) => i.id === id)) { + const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 24) || "stile"; + id = `u-${slug}-${rand().slice(0, 4)}`; + } + const color = /^#[0-9a-f]{6}$/i.test(data.colore || "") ? data.colore : "#cbbcff"; + const style = { + id, + nome: name, + descrizione: text.length < 90 ? text : text.slice(0, 87) + "…", + testo: text, + formato: data.formato || "1:1", + colore: color, + modello: ["z-image", "klein", "entrambi"].includes(data.modello) ? data.modello : "", + qualita: ["rapida", "bilanciata", "massima"].includes(data.qualita) ? data.qualita : "", + prompt: "{prompt}. " + english.trim().replace(/\.$/, "") + ".", + }; + const next = items.some((i) => i.id === id) ? items.map((i) => (i.id === id ? style : i)) : [...items, style]; + await kvSet("stili", next); + return { ...style, categoria: "I tuoi stili", utente: true, campi: [] }; + } + + async function templates() { + const res = await fetch("/api/templates"); + const data = await res.json(); + const mine = (await userStyles()).map((s) => ({ ...s, categoria: "I tuoi stili", utente: true, campi: [] })); + return { template: [...data.template, ...mine] }; + } + + /* ---------- motore ---------- */ + + let clientPromise = null; + function engine() { + clientPromise ||= import("/web/vendor/gradio-client.js") + .then(({ Client }) => Client.connect(location.origin + ENGINE_PATH, { events: ["data", "status"] })) + .catch((e) => { + clientPromise = null; + throw e; + }); + return clientPromise; + } + + const QUOTA = /quota|GPU (?:time|duration)/i; + function engineError(raw) { + const text = String(raw?.message || raw || ""); + const wait = text.match(/Try again in (\d+):(\d+):(\d+)/i); + if (QUOTA.test(text)) { + const err = new Error(wait ? "quota" : "quota"); + err.code = "quota"; + if (wait) err.retryIn = Number(wait[1]) * 3600 + Number(wait[2]) * 60 + Number(wait[3]); + return err; + } + if (/queue is full|too many/i.test(text)) { + const err = new Error("Ci sono troppe persone in coda in questo momento. Riprova tra un minuto."); + err.code = "full"; + return err; + } + return new Error(text.replace(/^Error:\s*/, "") || "Il motore non risponde. Riprova tra poco."); + } + + async function write(kind, text) { + const client = await engine(); + try { + const res = await client.predict("/scrivi", [kind, text]); + return res.data[0]; + } catch (e) { + throw engineError(e); + } + } + + async function improve(text, mode) { + const client = await engine(); + try { + const res = await client.predict("/migliora", [text, mode]); + return res.data[0]; + } catch (e) { + throw engineError(e); + } + } + + const jobs = new Map(); + const listeners = new Set(); + const emit = (event) => listeners.forEach((fn) => { try { fn(event); } catch { /* ascoltatore rotto */ } }); + + function placeholderJob(id, payload) { + return { + id, + status: "invio", + progress: 0, + current: 0, + current_model: "", + total: Math.max(1, Number(payload.quantita) || 1), + current_steps: 1, + model_name: "", + confronto: false, + elapsed: 0, + width: 1024, + height: 1024, + results: [], + request: { mode: payload.modalita || "crea", count: Number(payload.quantita) || 1, mask: payload.maschera || null }, + created: Date.now() / 1000, + }; + } + + async function startJob(payload) { + const files = []; + for (const ref of payload.riferimenti || []) { + const blob = await readBlob(ref); + if (!blob) throw new Error("Un'immagine di partenza non c'è più. Ricaricala."); + files.push(new File([blob], "ref.png", { type: blob.type || "image/png" })); + } + let mask = null; + if (payload.maschera) { + const blob = await readBlob(payload.maschera); + if (blob) mask = new File([blob], "mask.png", { type: "image/png" }); + } + const request = { ...payload, stili_utente: await userStyles() }; + const client = await engine(); + const { handle_file: handle } = await import("/web/vendor/gradio-client.js"); + const id = "j" + Date.now().toString(36) + rand(); + const started = Date.now(); + const state = { job: placeholderJob(id, payload), payload }; + jobs.set(id, state); + + const run = client.submit("/genera", [JSON.stringify(request), files.map((f) => handle(f)), mask ? handle(mask) : null]); + (async () => { + try { + for await (const msg of run) { + if (msg.type === "status") { + if (msg.stage === "error") throw engineError(msg.message); + if (msg.stage === "pending" && msg.position != null && state.job.status !== "generazione") { + state.job = { ...state.job, status: "in_coda", position: msg.position, eta: msg.eta ?? null, queue_size: msg.queue_size ?? null }; + } + } + if (msg.type === "data") { + const [pub, out] = msg.data; + if (!pub) continue; + const live = { ...pub, elapsed: Math.round((Date.now() - started) / 100) / 10 }; + if (pub.status === "fatto" && out && out.length) { + state.job = { ...live, status: "salvataggio" }; + const results = []; + for (let i = 0; i < out.length; i++) { + const res = await fetch(out[i].url); + const png = await res.blob(); + const meta = { ...pub.results[i], riferimenti: payload.riferimenti || [], maschera: payload.maschera || null }; + results.push(await storeItem("bozze", meta, png, await thumbnail(png))); + } + state.job = { ...live, status: "fatto", results, progress: 1 }; + emit({ type: "generata", count: results.length }); + return; + } + state.job = { ...live, status: pub.status === "fatto" ? "salvataggio" : pub.status }; + } + } + } catch (e) { + const err = e instanceof Error && e.code ? e : engineError(e); + state.job = { ...state.job, status: "errore", error: err.message, error_code: err.code || null, retry_in: err.retryIn || null }; + emit({ type: "errore", code: err.code || null, retryIn: err.retryIn || null }); + } + })(); + return state.job; + } + + /* ---------- account ---------- */ + + async function whoAmI() { + try { + const client = await engine(); + const res = await client.predict("/chi_sono", []); + return res.data[0] || { accesso: false }; + } catch { + return { accesso: false }; + } + } + + /* ---------- router delle API ---------- */ + + const MODELS = { + "z-image": { nome: "Z-Image Turbo", descrizione: "Il più fedele al prompt. Foto realistiche e testo dentro l'immagine.", modalita: ["crea", "ristila"], qualita: { rapida: 6, bilanciata: 9, massima: 14 } }, + klein: { nome: "FLUX.2 Klein", descrizione: "Veloce, stile pulito. L'unico che modifica le foto a comando.", modalita: ["crea", "ristila", "modifica", "continua"], qualita: { rapida: 4, bilanciata: 5, massima: 8 } }, + }; + const ASPECTS = { "1:1": [1024, 1024], "4:5": [896, 1120], "3:4": [864, 1152], "2:3": [832, 1248], "9:16": [768, 1344], "16:9": [1344, 768], "3:2": [1248, 832] }; + + function status() { + const busy = [...jobs.values()].filter((s) => !["fatto", "errore"].includes(s.job.status)).length; + return { + modello: "pronto", + modello_caricato: null, + modelli_installati: { "z-image": true, klein: true }, + lavori_attivi: busy, + traduttore: true, + strumenti: { ingrandisci: true, scontorna: true, vettorizza: true }, + motore_finto: false, + online: true, + formati: ASPECTS, + modelli: MODELS, + automatico: { crea: "z-image", ristila: "z-image", modifica: "klein", continua: "klein", rifinisci: "z-image" }, + max_riferimenti: 4, + }; + } + + async function posterSave(blob, info) { + const bmp = await bitmap(blob); + const meta = { + _stem: `${clock()}_locandina_${rand()}`, + modalita: "locandina", + prompt: String(info.titolo || "").slice(0, 120), + prompt_finale: "", + template: "libero", + stili: [], + campi: {}, + riferimenti: info.sfondo ? [String(info.sfondo)] : [], + formato: String(info.formato || ""), + larghezza: bmp.width, + altezza: bmp.height, + qualita: "", + passi: 0, + seed: 0, + modello: "compositore", + modello_nome: "Compositore", + trasparente: false, + creata: stamp(), + titolo: String(info.titolo || "").slice(0, 120), + preferita: false, + }; + bmp.close?.(); + return storeItem("galleria", meta, blob, await thumbnail(blob)); + } + + async function vectorize(body) { + const blob = await readBlob(body.file); + if (!blob) throw new Error("Immagine non trovata."); + const form = new FormData(); + form.append("file", blob, "immagine.png"); + form.append("stile", body.stile || "colori"); + form.append("trasparente", String(body.trasparente !== false)); + const res = await fetch("/api/vectorize", { method: "POST", body: form }); + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.detail || "Vettorizzazione non riuscita."); + return data; + } + + async function extractStyle(body) { + const res = await fetch("/api/styles/extract", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ ...body, stili_utente: await userStyles() }), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.detail || "Non riuscito."); + return data; + } + + const filesOf = (body) => (body.files || (body.file ? [body.file] : [])).map(String); + + async function api(path, body, headers = {}) { + const url = new URL(path, location.origin); + const p = url.pathname; + if (body === undefined) { + if (p === "/api/status") return status(); + if (p === "/api/templates") return templates(); + if (p === "/api/history") return history(url.searchParams); + if (p.startsWith("/api/jobs/")) { + const s = jobs.get(p.split("/").pop()); + if (!s) throw new Error("Lavoro non trovato."); + return s.job; + } + throw new Error("Pagina non trovata."); + } + switch (p) { + case "/api/upload": { + const { blob, width, height } = await cleanUpload(body); + const name = decodeURIComponent(headers["X-Filename"] || "").slice(0, 80); + return { file: await saveInput(blob, name), larghezza: width, altezza: height, nome: name }; + } + case "/api/poster": { + const info = JSON.parse(decodeURIComponent(headers["X-Meta"] || "") || "{}"); + return posterSave(body, info); + } + case "/api/generate": + return startJob(body); + case "/api/enhance": + if (!String(body.prompt || "").trim()) throw new Error("Scrivi prima un'idea da migliorare."); + return improve(String(body.prompt), body.modalita || "crea"); + case "/api/translate": + return { testo: String(body.testo || "").trim() ? await write(body.verso === "it" ? "in_italiano" : "traduci", String(body.testo)) : "" }; + case "/api/vectorize": + return vectorize(body); + case "/api/keep": { + const kept = []; + for (const f of filesOf(body)) { const m = await move(f, "bozze", "galleria"); if (m) kept.push(m); } + return { salvate: kept }; + } + case "/api/discard": { + let n = 0; + const list = body.tutto ? (await itemsIn("bozze")).map((r) => r.file) : filesOf(body); + for (const f of list) if (await remove(f, "bozze")) n++; + return { scartate: n }; + } + case "/api/trash": { + let n = 0; + for (const f of filesOf(body)) if (await move(f, "galleria", "cestino")) n++; + return { spostate: n }; + } + case "/api/restore": { + let n = 0; + for (const f of filesOf(body)) if (await move(f, "cestino", "galleria")) n++; + return { ripristinate: n }; + } + case "/api/purge": { + let n = 0; + const list = body.tutto ? (await itemsIn("cestino")).map((r) => r.file) : filesOf(body); + for (const f of list) if (await remove(f, "cestino")) n++; + return { eliminate: n }; + } + case "/api/update": { + const rec = await readItem(String(body.file || "")); + if (!rec || rec.scope !== "galleria") throw new Error("Immagine non trovata."); + const changes = body.modifiche || {}; + if ("titolo" in changes) rec.meta.titolo = String(changes.titolo || "").trim().slice(0, 120); + if ("preferita" in changes) rec.meta.preferita = !!changes.preferita; + await tx("items", "readwrite", (s) => { s.put(rec); }); + return rec.meta; + } + case "/api/styles/save": + return saveStyle(body); + case "/api/styles/extract": + return extractStyle(body); + case "/api/styles/delete": { + const items = await userStyles(); + const next = items.filter((i) => i.id !== String(body.id || "")); + if (next.length === items.length) throw new Error("Stile non trovato."); + await kvSet("stili", next); + return { ok: true }; + } + case "/api/unload": + case "/api/shutdown": + return { ok: true }; + default: + throw new Error("Azione non trovata."); + } + } + + async function serviceWorker() { + if (!("serviceWorker" in navigator)) return false; + try { + await navigator.serviceWorker.register("/sw.js", { scope: "/" }); + await navigator.serviceWorker.ready; + if (!navigator.serviceWorker.controller) { + await new Promise((resolve) => { + navigator.serviceWorker.addEventListener("controllerchange", resolve, { once: true }); + setTimeout(resolve, 1500); + }); + } + return !!navigator.serviceWorker.controller; + } catch { + return false; + } + } + + const ready = (async () => { + await db(); + const sw = await serviceWorker(); + cleanOld().catch(() => {}); + if (navigator.storage?.persist) navigator.storage.persist().catch(() => {}); + return { serviceWorker: sw }; + })(); + + window.PixBackend = { api, ready, whoAmI, engine, on: (fn) => listeners.add(fn), readBlob }; +})(); diff --git a/web/fonts/LICENSE-OFL.txt b/web/fonts/LICENSE-OFL.txt new file mode 100644 index 0000000000000000000000000000000000000000..76a02175dbde6453b8527c9163b904c1a2567c7c --- /dev/null +++ b/web/fonts/LICENSE-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2016 The Oswald Project Authors (https://github.com/googlefonts/OswaldFont) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/web/fonts/anton-latin-400-normal.woff2 b/web/fonts/anton-latin-400-normal.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..69d48b9af8be985ae9ac4808be7c70a2c833405a Binary files /dev/null and b/web/fonts/anton-latin-400-normal.woff2 differ diff --git a/web/fonts/archivo-black-latin-400-normal.woff2 b/web/fonts/archivo-black-latin-400-normal.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..a88b0b5352960c400c46ee17180d0d8f5c0d0db9 Binary files /dev/null and b/web/fonts/archivo-black-latin-400-normal.woff2 differ diff --git a/web/fonts/bebas-neue-latin-400-normal.woff2 b/web/fonts/bebas-neue-latin-400-normal.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..92d6a0f7297276c67ade85119be8996eae8b3d57 Binary files /dev/null and b/web/fonts/bebas-neue-latin-400-normal.woff2 differ diff --git a/web/fonts/inter-latin-400-normal.woff2 b/web/fonts/inter-latin-400-normal.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..f15b025d666269fb07daf0263e54231481e4289c Binary files /dev/null and b/web/fonts/inter-latin-400-normal.woff2 differ diff --git a/web/fonts/inter-latin-600-normal.woff2 b/web/fonts/inter-latin-600-normal.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..d1897949fda5c7fc5f04622df43a3fcba5b89d84 Binary files /dev/null and b/web/fonts/inter-latin-600-normal.woff2 differ diff --git a/web/fonts/inter-latin-800-normal.woff2 b/web/fonts/inter-latin-800-normal.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..74a16d45945264434aa7409e79549c626ebcdfb1 Binary files /dev/null and b/web/fonts/inter-latin-800-normal.woff2 differ diff --git a/web/fonts/newsreader-latin-400-italic.woff2 b/web/fonts/newsreader-latin-400-italic.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..a662767db6000b69cc0cb3d6e6888dfd056aa5ef Binary files /dev/null and b/web/fonts/newsreader-latin-400-italic.woff2 differ diff --git a/web/fonts/newsreader-latin-400-normal.woff2 b/web/fonts/newsreader-latin-400-normal.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..8536068e1fca064421e37775949b0e9224efa3ac Binary files /dev/null and b/web/fonts/newsreader-latin-400-normal.woff2 differ diff --git a/web/fonts/newsreader-latin-500-italic.woff2 b/web/fonts/newsreader-latin-500-italic.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..52588d47524c121bb0dcb76bb05f4a3575548ced Binary files /dev/null and b/web/fonts/newsreader-latin-500-italic.woff2 differ diff --git a/web/fonts/newsreader-latin-500-normal.woff2 b/web/fonts/newsreader-latin-500-normal.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..a84e0164976543c35b1d779a1b4fe21d1e574a44 Binary files /dev/null and b/web/fonts/newsreader-latin-500-normal.woff2 differ diff --git a/web/fonts/oswald-latin-500-normal.woff2 b/web/fonts/oswald-latin-500-normal.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..e0f43696b11fca1fd9df83b6a9a2d1e78af7eec8 Binary files /dev/null and b/web/fonts/oswald-latin-500-normal.woff2 differ diff --git a/web/fonts/oswald-latin-700-normal.woff2 b/web/fonts/oswald-latin-700-normal.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..e1290c1e8c19d93f1f30030b4c1e9782f3d5d8ac Binary files /dev/null and b/web/fonts/oswald-latin-700-normal.woff2 differ diff --git a/web/fonts/permanent-marker-latin-400-normal.woff2 b/web/fonts/permanent-marker-latin-400-normal.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..203ccaeb9c2bab914dbb05e4501915a16315200b Binary files /dev/null and b/web/fonts/permanent-marker-latin-400-normal.woff2 differ diff --git a/web/fonts/playfair-display-latin-700-normal.woff2 b/web/fonts/playfair-display-latin-700-normal.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..39eefe0333444ed21139388621c18781e832ce5e Binary files /dev/null and b/web/fonts/playfair-display-latin-700-normal.woff2 differ diff --git a/web/fonts/playfair-display-latin-900-normal.woff2 b/web/fonts/playfair-display-latin-900-normal.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..87eff243471acaa0bb0b3cca7224cca0a13a2945 Binary files /dev/null and b/web/fonts/playfair-display-latin-900-normal.woff2 differ diff --git a/web/guida/PixRick-Guida.pdf b/web/guida/PixRick-Guida.pdf new file mode 100644 index 0000000000000000000000000000000000000000..18411ced0520e322795e4fa2e78cd4d423746c30 --- /dev/null +++ b/web/guida/PixRick-Guida.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25199c412d5bf1c29a630d23836351feddeab5a3a609bd34645eb7fa08752b7e +size 5934679 diff --git a/web/guida/guida.css b/web/guida/guida.css new file mode 100644 index 0000000000000000000000000000000000000000..031a709276e53eb0f495e9121c0742618ee3a029 --- /dev/null +++ b/web/guida/guida.css @@ -0,0 +1,328 @@ +@font-face { font-family: "Newsreader"; src: url("/web/fonts/newsreader-latin-400-normal.woff2") format("woff2"); font-weight: 400; font-style: normal; } +@font-face { font-family: "Newsreader"; src: url("/web/fonts/newsreader-latin-500-normal.woff2") format("woff2"); font-weight: 500; font-style: normal; } +@font-face { font-family: "Newsreader"; src: url("/web/fonts/newsreader-latin-400-italic.woff2") format("woff2"); font-weight: 400; font-style: italic; } +@font-face { font-family: "Inter"; src: url("/web/fonts/inter-latin-400-normal.woff2") format("woff2"); font-weight: 400; } +@font-face { font-family: "Inter"; src: url("/web/fonts/inter-latin-600-normal.woff2") format("woff2"); font-weight: 600; } + +:root { + --paper: #f7f7f9; + --sheet: #ffffff; + --ink: #1b1c22; + --ink-2: #4a4c57; + --ink-3: #7b7e8a; + --rule: #e3e3ea; + --violet: #5b45c2; + --violet-soft: #efecfb; + --amber: #8a5a00; + --amber-soft: #fff4dc; + --mint-soft: #e6f6f1; + --mint: #1d6b55; + --pearl: linear-gradient(115deg, #c9b8ff 0%, #ffc9a8 55%, #9fe3da 100%); + --serif: "Newsreader", ui-serif, Georgia, serif; + --sans: "Inter", -apple-system, system-ui, sans-serif; + --measure: 68ch; +} + +* { box-sizing: border-box; } +html { scroll-behavior: smooth; scroll-padding-top: 24px; } +body { + margin: 0; + background: var(--paper); + color: var(--ink); + font: 400 16px/1.65 var(--sans); + -webkit-font-smoothing: antialiased; + font-feature-settings: "cv11", "ss01"; +} +img { display: block; max-width: 100%; height: auto; } +a { color: var(--violet); text-decoration-thickness: 1px; text-underline-offset: 3px; } +kbd { + display: inline-block; + min-width: 1.7em; + padding: 0 0.4em; + border: 1px solid var(--rule); + border-bottom-width: 2px; + border-radius: 5px; + background: var(--sheet); + font: 600 0.82em/1.6 var(--sans); + text-align: center; + color: var(--ink-2); +} +code { font: 0.9em/1 ui-monospace, "SF Mono", Menlo, monospace; padding: 0.1em 0.35em; border-radius: 4px; background: #eeeef3; } +b, strong { font-weight: 600; } + +/* ---------- impaginazione ---------- */ + +.layout { display: grid; grid-template-columns: 260px minmax(0, 1fr); max-width: 1180px; margin: 0 auto; } +.toc { + position: sticky; + top: 0; + align-self: start; + height: 100vh; + overflow-y: auto; + padding: 36px 20px 40px 28px; + border-right: 1px solid var(--rule); + font-size: 13.5px; +} +.toc .toc-brand { display: flex; align-items: center; gap: 10px; margin-bottom: 26px; font: 500 20px/1 var(--serif); color: var(--ink); text-decoration: none; } +.toc-brand img { display: inline-block; width: 26px; height: 26px; } +.toc ol { margin: 0; padding: 0; list-style: none; counter-reset: cap; } +.toc > nav > ol > li { counter-increment: cap; margin: 0 0 2px; } +.toc a { display: block; padding: 5px 8px; border-radius: 7px; color: var(--ink-2); text-decoration: none; } +.toc > nav > ol > li > a::before { content: counter(cap) ". "; color: var(--ink-3); font-variant-numeric: tabular-nums; } +.toc a:hover { background: #ececf2; color: var(--ink); } +.toc a.attivo { background: var(--violet-soft); color: var(--violet); } +.toc ol ol { margin: 2px 0 8px 18px; font-size: 12.5px; } +.toc ol ol a { padding: 3px 8px; } +.toc-pdf { display: inline-flex; align-items: center; gap: 8px; margin-top: 22px; padding: 8px 12px; border: 1px solid var(--rule); border-radius: 9px; background: var(--sheet); color: var(--ink); font-weight: 600; text-decoration: none; } + +main { padding: 0 56px 120px; min-width: 0; } +.doc { max-width: var(--measure); } + +/* ---------- copertina ---------- */ + +.cover { position: relative; padding: 72px 0 56px; } +.cover-mark { width: 54px; height: 54px; margin-bottom: 30px; } +.cover h1 { margin: 0; font: 400 clamp(46px, 7vw, 76px)/0.98 var(--serif); letter-spacing: -0.02em; } +.cover .sub { max-width: 34ch; margin: 18px 0 0; font: 400 22px/1.4 var(--serif); color: var(--ink-2); } +.cover-strip { display: grid; grid-template-columns: 1.5fr 1fr 0.75fr 1fr; gap: 6px; margin: 44px 0 18px; } +.cover-strip img { width: 100%; height: 190px; object-fit: cover; border-radius: 6px; } +.cover-strip figcaption { grid-column: 1 / -1; font-size: 12.5px; color: var(--ink-3); } +.pearl-rule { height: 3px; width: 120px; margin: 28px 0 0; border: 0; border-radius: 3px; background: var(--pearl); } +.cover-meta { margin: 14px 0 0; font-size: 13px; color: var(--ink-3); } + +/* ---------- capitoli ---------- */ + +.chapter { padding-top: 56px; } +.chapter + .chapter { border-top: 1px solid var(--rule); margin-top: 56px; } +.chapter-num { margin: 0 0 6px; font: 400 15px/1 var(--serif); font-style: italic; color: var(--violet); } +h2 { margin: 0 0 14px; font: 400 38px/1.1 var(--serif); letter-spacing: -0.01em; } +h3 { margin: 40px 0 10px; font: 500 23px/1.25 var(--serif); } +h4 { margin: 26px 0 6px; font: 600 15px/1.4 var(--sans); } +p { margin: 0 0 14px; } +.lead { font: 400 19px/1.55 var(--serif); color: var(--ink-2); } +ul, ol { margin: 0 0 16px; padding-left: 1.3em; } +li { margin: 0 0 6px; } +li::marker { color: var(--ink-3); } + +.steps { list-style: none; padding: 0; counter-reset: passo; } +.steps > li { position: relative; padding-left: 40px; margin-bottom: 14px; counter-increment: passo; } +.steps > li::before { + content: counter(passo); + position: absolute; + left: 0; + top: 1px; + width: 26px; + height: 26px; + border-radius: 50%; + background: var(--ink); + color: #fff; + font: 600 13px/26px var(--sans); + text-align: center; +} + +/* ---------- figure ---------- */ + +figure { margin: 26px 0 28px; } +.shot { border: 1px solid var(--rule); border-radius: 12px; overflow: hidden; background: #15161a; box-shadow: 0 18px 40px -26px rgba(20, 20, 40, 0.45); } +.wide { width: min(100%, 900px); max-width: none; } +figcaption { margin-top: 10px; font-size: 13.5px; line-height: 1.5; color: var(--ink-3); } +.pair { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; } +.pair img, .trio img { width: 100%; border-radius: 8px; } +.trio { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; } +.label-img { position: relative; } +.label-img span { + position: absolute; + left: 8px; + bottom: 8px; + padding: 3px 8px; + border-radius: 6px; + background: rgba(20, 20, 26, 0.75); + color: #fff; + font-size: 12px; + font-weight: 600; +} +.checker { padding: 18px; border-radius: 8px; background-color: #fff; background-image: conic-gradient(#ececf0 25%, transparent 0 50%, #ececf0 0 75%, transparent 0); background-size: 18px 18px; } + +/* mappa numerata sopra uno screenshot */ +.map { position: relative; } +.pin { + position: absolute; + width: 26px; + height: 26px; + margin: -13px 0 0 -13px; + border: 2px solid #fff; + border-radius: 50%; + background: var(--violet); + color: #fff; + font: 600 12.5px/22px var(--sans); + text-align: center; + box-shadow: 0 4px 10px rgba(0, 0, 0, 0.35); +} +.legend { list-style: none; padding: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 6px 22px; font-size: 14.5px; } +.legend li { display: flex; gap: 10px; align-items: baseline; margin: 0; } +.legend b.n { + flex: none; + width: 22px; + height: 22px; + border-radius: 50%; + background: var(--violet); + color: #fff; + font: 600 12px/22px var(--sans); + text-align: center; +} + +/* ---------- box ---------- */ + +.note, .tip-box, .warn { + margin: 20px 0; + padding: 14px 18px; + border-radius: 10px; + font-size: 15px; + line-height: 1.6; +} +.note { background: var(--violet-soft); } +.tip-box { background: var(--mint-soft); } +.warn { background: var(--amber-soft); } +.note > b:first-child, .tip-box > b:first-child, .warn > b:first-child { display: block; margin-bottom: 2px; } +.tip-box > b:first-child { color: var(--mint); } +.warn > b:first-child { color: var(--amber); } +.note > b:first-child { color: var(--violet); } +.note p:last-child, .tip-box p:last-child, .warn p:last-child { margin: 0; } + +/* ---------- tabelle ---------- */ + +table { width: 100%; margin: 18px 0 24px; border-collapse: collapse; font-size: 14.5px; } +th, td { padding: 10px 12px 10px 0; border-bottom: 1px solid var(--rule); text-align: left; vertical-align: top; } +th { font-weight: 600; color: var(--ink-2); font-size: 13px; } +td:first-child { white-space: nowrap; font-weight: 600; } + +/* ---------- chat con Claude ---------- */ + +.chat { margin: 24px 0 30px; padding: 22px; border-radius: 14px; background: #1c1d22; color: #ececef; font-size: 14.5px; } +.chat .u, .chat .c { max-width: 92%; margin: 0 0 12px; padding: 10px 14px; border-radius: 12px; line-height: 1.55; } +.chat .u { margin-left: auto; background: #34313f; } +.chat .c { background: transparent; padding-left: 0; color: #d9d9df; } +.chat code { background: #2c2d35; color: #e6e6ea; } +.chat .tool { + display: inline-flex; + align-items: center; + gap: 8px; + margin: 0 0 10px; + padding: 5px 10px; + border: 1px solid #3a3b44; + border-radius: 8px; + color: #a9abb6; + font: 12.5px/1.4 ui-monospace, "SF Mono", Menlo, monospace; +} +.chat .tool::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: #7fd8a6; } +.chat img { width: 220px; margin: 2px 0 12px; border-radius: 8px; } +.chat .row { display: flex; gap: 8px; flex-wrap: wrap; } +.chat .row img { width: 150px; } + +.prompts { list-style: none; padding: 0; display: grid; gap: 8px; } +.prompts li { margin: 0; padding: 10px 14px; border-left: 3px solid var(--violet); background: var(--sheet); border-radius: 0 8px 8px 0; font: italic 400 16.5px/1.5 var(--serif); } + +.cols { display: grid; grid-template-columns: 1fr 1fr; gap: 0 28px; } + +/* evidenziazione dopo un salto dall'infobox */ +.flash { animation: flash 1.6s ease-out; border-radius: 8px; } +@keyframes flash { 0%, 30% { background: var(--violet-soft); box-shadow: 0 0 0 10px var(--violet-soft); } 100% { background: transparent; box-shadow: 0 0 0 10px transparent; } } + +/* ---------- dentro la dashboard ---------- */ + +body.incorporata .layout { display: block; } +body.incorporata .toc { display: none; } +body.incorporata main { padding: 0 26px 80px; } +body.incorporata .cover { padding-top: 34px; } +body.incorporata .cover h1 { font-size: 44px; } +body.incorporata .cover-strip img { height: 110px; } +body.incorporata h2 { font-size: 31px; } +body.incorporata .legend, body.incorporata .cols { grid-template-columns: 1fr; } + +@media (max-width: 900px) { + .layout { display: block; } + .toc { display: none; } + main { padding: 0 22px 80px; } +} + +@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } .flash { animation: none; } } + +/* ---------- stampa (PDF) ---------- */ + +@page { size: A4; margin: 18mm 17mm 20mm; } +@media print { + html { scroll-behavior: auto; } + body { background: #fff; font-size: 10.6pt; line-height: 1.55; } + .layout { display: block; max-width: none; } + .toc { display: none; } + main { padding: 0; } + .doc { max-width: none; } + .cover { min-height: 255mm; padding: 26mm 4mm 0; break-after: page; } + .cover h1 { font-size: 84pt; } + .cover .sub { font-size: 18pt; } + .cover-strip { margin-top: 22mm; } + .cover-strip img { height: 78mm; } + .print-toc { display: block; break-after: page; } + .chapter { padding-top: 10mm; margin-top: 10mm; } + .chapter + .chapter { margin-top: 8mm; border-top: 0.6pt solid var(--rule); } + .print-toc + .chapter { border-top: 0; margin-top: 0; padding-top: 0; } + #claude-mcp { break-before: page; border-top: 0; } + .chapter-num, h2, h3, .lead { break-after: avoid; } + p, li { orphans: 3; widows: 3; } + h2 { font-size: 28pt; } + h3 { font-size: 15pt; break-after: avoid; } + h4 { break-after: avoid; } + figure, table, .chat, .note, .tip-box, .warn, .legend { break-inside: avoid; } + .chat { background: #1c1d22 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; } + .pin, .legend b.n, .steps > li::before, .note, .tip-box, .warn, .shot, .pearl-rule, .checker, kbd, code, .prompts li { -webkit-print-color-adjust: exact; print-color-adjust: exact; } + .shot { box-shadow: none; } + figure img { max-height: 105mm; width: auto; margin: 0 auto; } + figure img.shot { max-height: 84mm; } + figcaption { font-size: 9pt; } + .pair img, .trio img { max-height: 70mm; object-fit: contain; } + .wide { width: 100%; } + .map img { max-height: none; width: 100%; } + .chat img { max-height: 45mm; width: auto; } + .cover-strip img { max-height: none; width: 100%; } + a { color: inherit; text-decoration: none; } + .no-print { display: none !important; } +} +@media screen { .print-toc { display: none; } } +.print-toc h2 { margin-top: 0; } +.print-toc ol { list-style: none; margin: 3mm 0 0; padding: 0; counter-reset: voce; } +.print-toc li { display: flex; align-items: baseline; gap: 8px; margin: 0; break-inside: avoid; } +.print-toc li::after { content: ""; order: 1; flex: 1; border-bottom: 0.6pt dotted #b9bbc6; transform: translateY(-3px); } +.print-toc li span { order: 2; min-width: 2em; text-align: right; font-variant-numeric: tabular-nums; color: var(--ink-2); } +.print-toc li.cap { counter-increment: voce; margin-top: 1.6mm; font-weight: 600; font-size: 10.4pt; } +.print-toc li.cap a::before { content: counter(voce) ". "; color: var(--violet); } +.print-toc li.sub { padding-left: 7mm; font-size: 9pt; color: var(--ink-2); line-height: 1.38; } +.print-toc a { color: inherit; text-decoration: none; } +.print-toc .note { margin-top: 5mm; font-size: 9.4pt; padding: 10px 14px; } +.pmark { position: absolute; top: 0; right: 0; font-size: 2px; line-height: 1; color: #fff; } +@media print { .nuova-pagina { break-before: page; } } + +/* posizioni dei numeri sulla mappa dello Studio */ +.p-viste { left: 39.4%; top: 3%; } +.p-stato { left: 72.3%; top: 3%; } +.p-azioni { left: 37.4%; top: 73.6%; } +.p-modi { left: 2.2%; top: 80.4%; } +.p-prompt { left: 59.5%; top: 87.8%; } +.p-pillole { left: 41.8%; top: 95%; } +.p-genera { left: 58%; top: 95%; } +.p-stili { left: 89.6%; top: 9.4%; } +.p-sessione { left: 7.2%; top: 14%; } + +.gallery-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin: 18px 0 26px; } +.gallery-grid figure { margin: 0; } +.gallery-grid img { width: 100%; aspect-ratio: 3 / 2; object-fit: cover; border-radius: 6px; } +.gallery-grid.four img { aspect-ratio: 1; } +.gallery-grid .label-img span { left: 6px; bottom: 6px; font-size: 11px; padding: 2px 7px; } +body.incorporata .gallery-grid { grid-template-columns: repeat(2, 1fr); } +@media print { .gallery-grid img { max-height: none; } .gallery-grid { break-inside: avoid; } } + +.side { display: grid; grid-template-columns: 0.8fr 1.2fr; gap: 22px; align-items: start; margin: 18px 0 22px; } +.side > img { width: 100%; border-radius: 8px; } +.side .poster-final { box-shadow: 0 18px 40px -22px rgba(20, 20, 40, 0.55); } +.quote { font: italic 400 16px/1.5 var(--serif); color: var(--ink-2); } +body.incorporata .side { grid-template-columns: 1fr; } +@media print { .side { break-inside: avoid; } .side > img { max-height: 120mm; width: auto; } } diff --git a/web/guida/guida.js b/web/guida/guida.js new file mode 100644 index 0000000000000000000000000000000000000000..44cf9e9e18355b637e3b7c325a5a818a077f4a07 --- /dev/null +++ b/web/guida/guida.js @@ -0,0 +1,42 @@ +"use strict"; + +(() => { + const params = new URLSearchParams(location.search); + if (params.has("incorporata")) document.body.classList.add("incorporata"); + + const flash = (id) => { + const target = id && document.getElementById(id); + if (!target) return; + const block = target.matches("section") ? target.querySelector("h2, h3") || target : target; + block.classList.remove("flash"); + void block.offsetWidth; + block.classList.add("flash"); + }; + + const go = (id) => { + const target = id && document.getElementById(id); + if (!target) return; + target.scrollIntoView({ block: "start" }); + flash(id); + }; + + window.addEventListener("hashchange", () => go(location.hash.slice(1))); + window.addEventListener("message", (e) => { + if (e.origin !== location.origin || !e.data || !("evidenzia" in e.data)) return; + if (e.data.evidenzia) go(e.data.evidenzia); + }); + if (location.hash) requestAnimationFrame(() => go(location.hash.slice(1))); + + const links = [...document.querySelectorAll(".toc a[href^='#']")]; + const byId = new Map(links.map((a) => [a.getAttribute("href").slice(1), a])); + const watched = [...document.querySelectorAll("main [id]")].filter((n) => byId.has(n.id)); + if (!watched.length || !("IntersectionObserver" in window)) return; + const io = new IntersectionObserver((entries) => { + for (const entry of entries) { + if (!entry.isIntersecting) continue; + links.forEach((a) => a.classList.remove("attivo")); + byId.get(entry.target.id)?.classList.add("attivo"); + } + }, { rootMargin: "-10% 0px -80% 0px" }); + watched.forEach((n) => io.observe(n)); +})(); diff --git a/web/guida/img/anime-foto.jpg b/web/guida/img/anime-foto.jpg new file mode 100644 index 0000000000000000000000000000000000000000..162441fabea4541c059cb2e373aad1a1179ca545 Binary files /dev/null and b/web/guida/img/anime-foto.jpg differ diff --git a/web/guida/img/anime.jpg b/web/guida/img/anime.jpg new file mode 100644 index 0000000000000000000000000000000000000000..775880bc38a8aa261193f3d6d063ae9894f6e3ca --- /dev/null +++ b/web/guida/img/anime.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7cb552c891997a77b508e5d1a9b64bb91745b3432dc8fd353116896631c78fc4 +size 162498 diff --git a/web/guida/img/app-cinese.jpg b/web/guida/img/app-cinese.jpg new file mode 100644 index 0000000000000000000000000000000000000000..544161065309500d501472653b99fd9068fafbf3 Binary files /dev/null and b/web/guida/img/app-cinese.jpg differ diff --git a/web/guida/img/app.jpg b/web/guida/img/app.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4124b1da5f6447ddc539a4573e1696a4cea2c186 Binary files /dev/null and b/web/guida/img/app.jpg differ diff --git a/web/guida/img/funko.jpg b/web/guida/img/funko.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f7f35b6d90ba4937f2874328f0c44a70fafcba70 Binary files /dev/null and b/web/guida/img/funko.jpg differ diff --git a/web/guida/img/liutaio.jpg b/web/guida/img/liutaio.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f50e27f4ac34347da27b6ded6c54ce75e322b936 Binary files /dev/null and b/web/guida/img/liutaio.jpg differ diff --git a/web/guida/img/locandina-lineup.jpg b/web/guida/img/locandina-lineup.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3991ac3de768b82f4e72d3c2b1ce25731c6d2d62 --- /dev/null +++ b/web/guida/img/locandina-lineup.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e903db7dd8ea4e2a88040ee0c4272bb488c08325d071a34face65b32e4540bd3 +size 162029 diff --git a/web/guida/img/logo.jpg b/web/guida/img/logo.jpg new file mode 100644 index 0000000000000000000000000000000000000000..24bc598ca8275e07be4df5b47628253130a4174d Binary files /dev/null and b/web/guida/img/logo.jpg differ diff --git a/web/guida/img/miele.jpg b/web/guida/img/miele.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ebb06467641a3acf5b99059086a52ab9489e5304 Binary files /dev/null and b/web/guida/img/miele.jpg differ diff --git a/web/guida/img/neve.jpg b/web/guida/img/neve.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6417b835627789d922a645a43c3fcce9f253bf4a Binary files /dev/null and b/web/guida/img/neve.jpg differ diff --git a/web/guida/img/ritratto.jpg b/web/guida/img/ritratto.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e6bee17b5a27bba5cac7187c25b9e19f564cc3bf Binary files /dev/null and b/web/guida/img/ritratto.jpg differ diff --git a/web/guida/img/s-detail.jpg b/web/guida/img/s-detail.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1132501c2dc8377c72ac01949bc342dd24eb575c --- /dev/null +++ b/web/guida/img/s-detail.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:32004f4c92db3c6938436565a71f4fa1ac0cd8f881cca71d4742ebc58799ea11 +size 256082 diff --git a/web/guida/img/s-gallery.jpg b/web/guida/img/s-gallery.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f8671cf3ecb0c834627c20217100eab958f10d4b --- /dev/null +++ b/web/guida/img/s-gallery.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a49beba0cfe0ec0834e7db2de8a209f74b3c599873b6e622ff736a79238f92fe +size 228156 diff --git a/web/guida/img/s-loc-a.jpg b/web/guida/img/s-loc-a.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e803e54c26f2222482030a3951c17f2e004bb84e --- /dev/null +++ b/web/guida/img/s-loc-a.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0de712603b727ae84fc5edf53193db29c18ec5668880a30f7725b3bcaf1a22a0 +size 170676 diff --git a/web/guida/img/s-loc-b.jpg b/web/guida/img/s-loc-b.jpg new file mode 100644 index 0000000000000000000000000000000000000000..869a1f001b0a5df54cf32224045b2a1e9455b5c5 --- /dev/null +++ b/web/guida/img/s-loc-b.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38ccbe3bba2ccfed990f6ad100bf5010c14db038a3454a6fee46d908225e2f9e +size 150096 diff --git a/web/guida/img/s-loc-c.jpg b/web/guida/img/s-loc-c.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d27579c4f9b81ee3ecc811eb219996d37b5dc1e8 --- /dev/null +++ b/web/guida/img/s-loc-c.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:293510aad244387e92fc979c568c8e9011a77ecbc7c808b417b949346b4ee738 +size 149184 diff --git a/web/guida/img/s-loc-pick.jpg b/web/guida/img/s-loc-pick.jpg new file mode 100644 index 0000000000000000000000000000000000000000..05c57b2088cea805901e3e230f4072c70c4e16ac --- /dev/null +++ b/web/guida/img/s-loc-pick.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a8d04bd1786f7360929a375016a19e6e9b3664a1ba3aa8bfe6403ef5e2e9c47 +size 173089 diff --git a/web/guida/img/s-models.jpg b/web/guida/img/s-models.jpg new file mode 100644 index 0000000000000000000000000000000000000000..acf2449658f1e948cd6f244a5329d99b93491a19 Binary files /dev/null and b/web/guida/img/s-models.jpg differ diff --git a/web/guida/img/s-ristila.jpg b/web/guida/img/s-ristila.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c129695cc52a1da868b30d950462dc2da38e2b03 --- /dev/null +++ b/web/guida/img/s-ristila.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:571e017dbe0efdd3cbff963937db519c19f2d8d99d33fed6029c3a12c806e891 +size 192588 diff --git a/web/guida/img/s-studio.jpg b/web/guida/img/s-studio.jpg new file mode 100644 index 0000000000000000000000000000000000000000..851672af3bd5e0bd667d3ad3aa7b0fe5c1df610a --- /dev/null +++ b/web/guida/img/s-studio.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f5b89a2a2ab8f92d34cd6966a41a11bb3a888e4469537ccac759c1a4ad6b19e +size 211544 diff --git a/web/guida/img/s-tip.jpg b/web/guida/img/s-tip.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9742bdc3b560d88c64d14e031a4e5de12f416b5d --- /dev/null +++ b/web/guida/img/s-tip.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6341571dda03de449d93f9fe68ea657911ad45d9f092288c2a992e842fc9ee3e +size 203235 diff --git a/web/guida/img/s-vector.jpg b/web/guida/img/s-vector.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5dddf1b6783f775718f662065cf7c8c6011b573c --- /dev/null +++ b/web/guida/img/s-vector.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:687332715e73d739d9e7b4bb088e20d87198c8151c522a1be9ec28bce03834d9 +size 151435 diff --git a/web/guida/img/s-zona.jpg b/web/guida/img/s-zona.jpg new file mode 100644 index 0000000000000000000000000000000000000000..54f6e235c20676895ec17bc58d92c223f6b9face --- /dev/null +++ b/web/guida/img/s-zona.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4446bc43f0468a5e611c861ed40bfee14a1534dab7bd991c44782012d467884 +size 206996 diff --git a/web/guida/img/s-zona2.jpg b/web/guida/img/s-zona2.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d2749155ffde7941aab411c4e2517bf13516e8e7 --- /dev/null +++ b/web/guida/img/s-zona2.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c9efd58ba0501cfd5cb1af2e549b1186b99f92f888ce5d88ca3e680eb0ec1ad +size 193932 diff --git a/web/guida/img/soglia.jpg b/web/guida/img/soglia.jpg new file mode 100644 index 0000000000000000000000000000000000000000..eedabf8860ad90baa933b91e7cde8c47d242f256 --- /dev/null +++ b/web/guida/img/soglia.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01b9857c1fbdbdaef4c437407cd115fc39298d6d13fd537801f8239043a9d873 +size 121363 diff --git a/web/guida/img/st-3d.jpg b/web/guida/img/st-3d.jpg new file mode 100644 index 0000000000000000000000000000000000000000..fc814d2749a3faa0e07c5ebecd5c1f61e0ef31c5 Binary files /dev/null and b/web/guida/img/st-3d.jpg differ diff --git a/web/guida/img/st-acquerello.jpg b/web/guida/img/st-acquerello.jpg new file mode 100644 index 0000000000000000000000000000000000000000..636e4fb463ab0a83ba45d39e81dae11e6444c438 Binary files /dev/null and b/web/guida/img/st-acquerello.jpg differ diff --git a/web/guida/img/st-darkfantasy.jpg b/web/guida/img/st-darkfantasy.jpg new file mode 100644 index 0000000000000000000000000000000000000000..806f28dbe9aaa12b69a88bf869cc502c24c32cdb Binary files /dev/null and b/web/guida/img/st-darkfantasy.jpg differ diff --git a/web/guida/img/st-fumetto.jpg b/web/guida/img/st-fumetto.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a97b19b4924a757843169a7f2ae62efb6a003a4b --- /dev/null +++ b/web/guida/img/st-fumetto.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e1a833e020b35206cdf041ff5a726ae281bee62f16ed49dddf83ff74324601f +size 181442 diff --git a/web/guida/img/st-pixel.jpg b/web/guida/img/st-pixel.jpg new file mode 100644 index 0000000000000000000000000000000000000000..068b827fa6472544ad01302510a49657a087b300 Binary files /dev/null and b/web/guida/img/st-pixel.jpg differ diff --git a/web/guida/img/tpl-griglia.jpg b/web/guida/img/tpl-griglia.jpg new file mode 100644 index 0000000000000000000000000000000000000000..822e85a9a071e63d8d272b8bfe701b0dbdaae1a5 --- /dev/null +++ b/web/guida/img/tpl-griglia.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb39a96706e6c779b794352ab6489e111c536b20793b9e34b0095d4a4cf20a51 +size 353619 diff --git a/web/guida/img/viste.jpg b/web/guida/img/viste.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1abb537c8c926421e41bae54cec28a067b91184c Binary files /dev/null and b/web/guida/img/viste.jpg differ diff --git a/web/guida/img/volpe-contorni.svg b/web/guida/img/volpe-contorni.svg new file mode 100644 index 0000000000000000000000000000000000000000..67867001925096ea5715a4310fa6f157c2689dbb --- /dev/null +++ b/web/guida/img/volpe-contorni.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/web/guida/img/volpe-scontornata.png b/web/guida/img/volpe-scontornata.png new file mode 100644 index 0000000000000000000000000000000000000000..d47972e56acad2d1722c26b0a09417b17aab91ca --- /dev/null +++ b/web/guida/img/volpe-scontornata.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9fede7c296f1dd2f550beeb037362978331e8db289c1ad22de79b2f3c17b76fa +size 321788 diff --git a/web/guida/img/volpe-sticker.jpg b/web/guida/img/volpe-sticker.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b2edbcb15b89da0961c508ffb7099218b019b65d Binary files /dev/null and b/web/guida/img/volpe-sticker.jpg differ diff --git a/web/guida/img/volpe-vettoriale.svg b/web/guida/img/volpe-vettoriale.svg new file mode 100644 index 0000000000000000000000000000000000000000..41815b0cdca7a4cff668a8090eafe05dcc5dae4e --- /dev/null +++ b/web/guida/img/volpe-vettoriale.svg @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/web/guida/img/volpe.jpg b/web/guida/img/volpe.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3e41c84f90a96f2069ac0ae229079575df39e0b2 Binary files /dev/null and b/web/guida/img/volpe.jpg differ diff --git a/web/guida/index.html b/web/guida/index.html new file mode 100644 index 0000000000000000000000000000000000000000..7a821c1441d59f00ca01650fc5efaed7790bec77 --- /dev/null +++ b/web/guida/index.html @@ -0,0 +1,622 @@ + + + + + + Guida di PixRick + + + + +
+ + +
+
+ +
+ +

PixRick

+

Lo studio di immagini AI che lavora in locale. Nessun abbonamento, nessun cloud, nessun limite di generazioni.

+
+ Foto di un liutaio al lavoro + La stessa scena in stile anime + Il liutaio come figura Funko + Logo Liuteria +
+
+

Guida all'uso · versione di novembre 2026

+
+ + + + +
+

Capitolo 1

+

In due minuti

+

PixRick crea, trasforma e ritocca immagini con due modelli di intelligenza artificiale che girano direttamente sul computer. Nessuna immagine e nessuna parola che scrivi va in rete.

+
    +
  1. Scegli cosa fare. In basso ci sono quattro schede: Crea (da zero), Ristila (stessa foto, altro stile), Modifica (cambi qualcosa a comando), Storia (scena nuova, stessi personaggi).
  2. +
  3. Descrivi. Scrivi in italiano, come parleresti a un fotografo o a un illustratore. Se vuoi, scegli uno stile nella colonna di destra.
  4. +
  5. Genera. Premi ⌘ ↵. La prima immagine richiede qualche secondo in più, il tempo di caricare il modello.
  6. +
  7. Salva quello che ti piace. Il resto rimane tra le bozze per 24 ore e poi sparisce da solo.
  8. +
+
Aiuto sempre a portata

Fermati col mouse su qualsiasi pulsante: compare un infobox con la spiegazione breve e il collegamento al punto giusto di questa guida. Premi ? per aprirla in qualsiasi momento.

+
Il consiglio più utile

Se un risultato non ti convince, prima di riscrivere tutto prova Varia (stessa idea, seme nuovo) o Altro modello. Spesso basta.

+
+ + +
+

Capitolo 2

+

Lo Studio

+

È la schermata dove passi quasi tutto il tempo: al centro l'immagine, sotto quello che scrivi, a destra le impostazioni.

+
+ Lo Studio con una foto appena generata + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 +
+
    +
  • 1Studio, Locandina, Galleria: le tre zone dell'app.
  • +
  • 2Stato del motore, conferma che sei offline e pulsante per liberare memoria.
  • +
  • 3Azioni sul risultato: salva, varia, modifica, ristila, strumenti.
  • +
  • 4Cosa vuoi fare: Crea, Ristila, Modifica, Storia.
  • +
  • 5La descrizione, in italiano o in inglese.
  • +
  • 6Riassunto di stile, formato, modello e qualità: clicca per cambiarli.
  • +
  • 7Migliora il prompt e Genera.
  • +
  • 8Stili, poi più in basso formato, modello, qualità e altre opzioni.
  • +
  • 9La sessione: tutte le versioni su cui hai lavorato, per tornare indietro con un clic.
  • +
+

La barra in alto

+

A destra vedi sempre lo stato del motore (a riposo, carico, pronto, al lavoro) e il bollino Offline, che conferma che la rete è chiusa. Un modello occupa diversi GB di memoria: dopo qualche minuto di inattività PixRick lo libera da solo, e se ti serve RAM subito c'è il pulsante a forma di chip. Il modello si ricarica alla prossima immagine.

+

La foto di partenza

+

Per Ristila, Modifica e Storia serve un'immagine da cui partire. Puoi trascinarla nello Studio, incollarla con ⌘ V, sceglierla col pulsante Foto oppure partire da un risultato appena generato con i pulsanti Modifica e Ristila. Anche così com'è puoi ingrandirla, scontornarla, vettorizzarla o usarla per una locandina.

+
+ + +
+

Capitolo 3

+

Crea

+

Un'immagine nuova partendo solo dalle parole.

+
+ Un anziano liutaio leviga il manico di una chitarra +
«Un anziano liutaio con la barba grigia leviga il manico di una chitarra nella sua bottega, luce calda di fine pomeriggio dalla finestra, trucioli sul banco.» Stile Foto realistica, qualità Massima.
+
+

Scrivere il prompt

+

Il «prompt» è la descrizione. Funziona meglio quando risponde, in ordine, a queste domande:

+
    +
  1. Chi o cosa c'è: «un anziano liutaio con la barba grigia».
  2. +
  3. Cosa fa e dove: «leviga una chitarra nella sua bottega».
  4. +
  5. Che luce: «luce calda di fine pomeriggio dalla finestra».
  6. +
  7. Dettagli che rendono vera la scena: «trucioli sul banco, attrezzi appesi».
  8. +
+

Lo stile (foto, anime, acquerello…) conviene sceglierlo con i pulsanti a destra invece di scriverlo: i pulsanti aggiungono una descrizione già collaudata. Descrivi quello che vuoi vedere, non quello che non vuoi: «cielo limpido» funziona meglio di «senza nuvole».

+

Puoi scrivere in italiano: un piccolo modello locale traduce in inglese prima di generare, perché i modelli capiscono meglio l'inglese. A campo vuoto, la freccia ↑ ti ripropone l'ultimo prompt.

+

Migliora

+

Hai un'idea ma non hai voglia di scriverla per bene? Scrivi due parole («volpe col caffè, adesivo») e premi Migliora. PixRick riscrive l'idea come prompt dettagliato e ti mostra due colonne: italiano per te, inglese per il modello. Correggi quella che preferisci e premi «Aggiorna l'altra» per tenerle allineate.

+

Scritte nelle immagini

+

Il testo da far comparire nell'immagine va tra virgolette, e resta com'è anche quando il resto viene tradotto. Z-Image è il modello più bravo con le scritte.

+
+
Mockup con scritte inventateSenza virgolette
+
Mockup con le scritte giusteCon le etichette tra virgolette
+
+

A sinistra le etichette le ha inventate il modello, e sono parole senza senso. A destra il prompt diceva «il nome "Marco Liutaio"», «la sezione "Oggi"», «gli orari "10:00", "11:30"», «il bottone "Prenota"»: quasi tutto giusto, tranne il bottone uscito «Prenosta».

+
Onestamente

Le scritte lunghe o piccole possono uscire con qualche lettera sbagliata, e chiedere a Modifica di correggerle non sempre funziona. Quando il testo deve essere perfetto (un evento, un prezzo, un indirizzo) usa la Locandina: lì le lettere sono font veri, mai sbagliate.

+
+ + +
+

Capitolo 4

+

Gli stili

+

Gli stili sono ricette collaudate: scegli il risultato che vuoi, al resto pensa PixRick.

+ + + + + + + +
GruppoStiliQuando usarli
FotoFoto realistica, Ritratto, Foto prodottoScene vere, persone, oggetti da vendere.
IllustrazioneAnime, Fumetto, Acquerello, Dark fantasy, Personaggio 3D, Pixel artDisegni e mondi inventati.
GraficaLocandina, Logo, Copertina album, StickerCose da stampare o pubblicare. Alcuni chiedono campi extra, come il nome del marchio.
InterfacceSchermata app, Pagina web, Dashboard, Kit componenti, Icona appEsplorare idee di design. Metti le etichette tra virgolette.
Stampa 3DFunko, Statuetta 3DFigure pronte per i servizi che trasformano un'immagine in un modello 3D.
+

Una scena, tanti stili

+

La stessa foto del liutaio passata in Ristila con stili diversi. Cambia il linguaggio, la scena resta.

+ +

Da zero, con Crea

+ +

Combinare gli stili

+

Puoi combinare fino a 3 stili. Il primo decide il «materiale» (foto, disegno, 3D), gli altri aggiungono atmosfera: Anime + Dark fantasy dà un anime cupo e dorato. Fermati col mouse su uno stile per leggere cosa fa.

+

I tuoi stili

+

Hai trovato un aspetto che ti piace e vuoi rifarlo? Due strade:

+
    +
  • + Nuovo nella colonna Stili: dai un nome e descrivi colori, luce, materiali e atmosfera, anche in italiano (lo traduce PixRick quando salvi).
  • +
  • Salva come stile da un'immagine riuscita: PixRick estrae dal suo prompt la parte che descrive l'aspetto, senza il soggetto.
  • +
+

I tuoi stili compaiono in cima, si combinano con gli altri e si modificano con la matita accanto al nome. Puoi anche far ricordare allo stile modello e qualità preferiti.

+
+ + +
+

Capitolo 5

+

Ristila

+

Stessa foto, stile nuovo. La composizione resta, cambia il modo in cui è fatta.

+
+
Foto originaleFoto
+
Versione animeRistila · Anime
+
+
    +
  1. Scheda Ristila, poi trascina la foto (o premi Ristila sotto un risultato).
  2. +
  3. Scegli uno stile a destra.
  4. +
  5. Facoltativo ma utile: descrivi in breve chi c'è nella foto, per esempio «anziano liutaio con la barba grigia che leviga una chitarra». Aiuta il modello a non perdere i dettagli importanti.
  6. +
  7. Premi Ristila.
  8. +
+
+ Ristila con la foto di partenza e lo stile Anime +
In Ristila la colonna di sinistra mostra la foto di partenza, a destra scegli modello e qualità.
+
+

Quanto resta dell'originale

+

È la manopola più importante del Ristila, e di solito non devi toccarla: con «Decide PixRick» acceso, PixRick guarda la foto e lo stile e sceglie da solo.

+
    +
  • Stesso materiale (foto → altra foto, disegno → altro disegno): tiene molto dell'originale.
  • +
  • Materiale diverso (disegno → foto, foto → anime): lascia più libertà e passa a Klein, l'unico modello che «vede» davvero la foto.
  • +
  • Stili che cambiano la forma (Funko, Statuetta): libertà massima, sempre con Klein.
  • +
+

Sotto il risultato trovi scritto cosa ha deciso e perché. Se spegni l'interruttore torni alla barra manuale: verso «Poco» il modello inventa di più, verso «Molto» resta più fedele.

+

Anche al contrario

+
+
Disegno animeDisegno
+
Lo stesso disegno diventato fotoRistila · Foto realistica
+
+

Da un disegno si torna a una foto credibile: stessa posa, stessi attrezzi, stessa finestra. Funziona con illustrazioni, fumetti, bozzetti e personaggi di fantasia.

+
+ + +
+

Capitolo 6

+

Modifica

+

Dici cosa cambiare, PixRick lo cambia e lascia il resto com'è.

+
+
PrimaPrima
+
Dopo: chitarra rossa e neveDopo
+
+

Istruzione usata: «Appendi una chitarra elettrica rossa lucida al muro, a destra della finestra. Fuori dal vetro il giardino è coperto di neve. Il resto resta com'è.»

+
    +
  • Scrivi l'azione, non la scena intera: «togli la persona a sinistra», «metti un cappello rosso», «cambia la scritta in "Aperto"».
  • +
  • Se serve, aggiungi cosa deve restare uguale: aiuta parecchio.
  • +
  • Più foto insieme (fino a 4): «il gatto della foto 2 sul divano della foto 1». Le foto si chiamano «foto 1», «foto 2» nell'ordine in cui le aggiungi.
  • +
+

Le modifiche a comando le fa FLUX.2 Klein; con la combo Klein + Z-Image ottieni la stessa modifica con una resa più ricca.

+

Cambiare solo una zona

+

Quando vuoi essere sicuro che il resto non si muova di un pixel, dipingi la zona.

+
+
Pennello sulla zona da cambiare
Dipingi la parte da cambiare.
+
Zona pronta e istruzione scritta
Premi Fatto, scrivi cosa mettere lì, premi Modifica.
+
+ + + + + + + +
TastoCosa fa
BPennello
EGomma
[ ]Pennello più piccolo o più grande
⌘ ZAnnulla l'ultimo tratto
EscEsci dal pennello
+
Consiglio

Dipingi un po' più largo dell'oggetto: il modello ha bisogno di un margine per raccordare luce e ombre.

+
+ + +
+

Capitolo 7

+

Storia

+

Una scena nuova con lo stesso stile, lo stesso mondo e gli stessi personaggi.

+
+
Scena 1Scena 1
+
Scena 2, stesso personaggioScena 2
+
+

Parti da un'immagine, scheda Storia (oppure Continua la storia dal menu dell'immagine) e descrivi solo la scena nuova: «lo stesso liutaio seduto sulla soglia della bottega al tramonto, suona la chitarra finita e sorride».

+

Utile per fumetti, storyboard, serie di post, illustrazioni di un racconto.

+
Onestamente

La somiglianza è buona ma non perfetta: nei primi tentativi il viso può cambiare. Ripeti più volte (Varia) e aiuta il modello ricordando i tratti principali: «stessa barba grigia, stessa camicia di jeans, stesso grembiule di cuoio».

+
+ + +
+

Capitolo 8

+

I modelli

+

Dentro PixRick lavorano due modelli con caratteri diversi. Con Automatico sceglie PixRick quello giusto.

+ + + + + + +
ModelloPunti fortiLimiti
Z-Image TurboIl più fedele al prompt. Foto realistiche, pelle, luce, scritte nelle immagini.Non «vede» le foto: nel Ristila ripassa i pixel, non capisce chi c'è.
FLUX.2 KleinVeloce, pulito. Legge le foto: l'unico che modifica a comando, cambia materiale (disegno → foto), fa Funko e Storia.Resa a volte più «liscia», meno bravo con le scritte.
EntrambiStesso prompt e stesso seme con i due modelli, affiancati. Per scegliere a colpo d'occhio.Solo per Crea e Ristila.
Klein + Z-ImageIl meglio dei due: vedi sotto.Tempo quasi doppio.
+

Klein + Z-Image

+
+ Pannello Modello con la combo selezionata +
Klein capisce la foto e fa il lavoro. Poi Z-Image ripassa pelle, luce e dettagli senza cambiare la composizione. Ricevi solo le immagini finite: se chiedi 4 immagini, ne arrivano 4.
+
+

Si sceglie in Ristila, Modifica (anche con la zona dipinta) e Storia. In galleria queste immagini risultano fatte con «Klein + Z-Image». Usala per il risultato finale; per provare idee basta un modello solo.

+
+ + +
+

Capitolo 9

+

Impostazioni

+

Formato

+

La forma dell'immagine: 1:1 quadrato, 4:5 e 3:4 per i social e i ritratti, 2:3 e 9:16 verticali (storie, telefono), 16:9 e 3:2 orizzontali. Ogni stile propone il formato giusto; con una foto di partenza c'è anche Come la foto.

+

Qualità

+ + + + + +
LivelloQuando
RapidaProvare idee, capire se una strada funziona.
BilanciataTutti i giorni: il punto giusto tra resa e tempo.
MassimaIl risultato da tenere. Più passaggi, più dettaglio, più tempo.
+

Quante immagini

+

Da 1 a 4 varianti in una volta. Con più immagini compare il confronto, dove tieni solo quelle che ti piacciono.

+

Seme

+

Il numero che decide la parte «casuale» di un'immagine. Stesso seme + stesse impostazioni = stessa immagine. Lascialo vuoto per avere ogni volta qualcosa di diverso; scrivilo quando vuoi rifare un'immagine cambiando solo un dettaglio del prompt.

+

Raffreddamento

+

Un portatile senza ventola, se lavora a lungo, si scalda e rallenta. In automatico PixRick misura quanto ha lavorato di recente (le immagini grandi e l'ingrandimento pesano di più) e, solo se serve, fa una pausa tra un'immagine e l'altra, fino a un massimo di 45 secondi. Durante la pausa vedi «Faccio respirare il computer» con il conto alla rovescia. Con lavori brevi non si ferma mai.

+

Altre opzioni

+
    +
  • Traduci in inglese prima di generare: lascialo acceso se scrivi in italiano.
  • +
  • Pausa: spegni «Decide PixRick» per impostare una pausa fissa.
  • +
  • Suggerimenti al passaggio del mouse: accende o spegne gli infobox.
  • +
+
+ + +
+

Capitolo 10

+

Dopo la generazione

+

Sotto ogni risultato c'è una barra di azioni. Ogni pulsante ha il suo infobox: fermati sopra col mouse.

+
+ Infobox sopra il pulsante SVG +
L'infobox spiega il pulsante e porta al punto giusto di questa guida.
+
+ + + + + + + + + +
AzioneCosa fa
Salva in galleriaTiene l'immagine. Quello che non salvi resta tra le bozze per 24 ore.
VariaStesse impostazioni, seme nuovo: una sorella della stessa idea.
Altro modelloRifà l'immagine con l'altro modello e lo stesso seme.
Modifica · RistilaUsa il risultato come foto di partenza.
×2 · Scontorna · SVGGli strumenti.
LocandinaUsa l'immagine come sfondo di una locandina.
Scarica · Riusa · CopiaIl PNG originale; rimettere prompt e impostazioni nel composer; copiare il prompt finale.
+

La sessione

+

A sinistra dello Studio c'è una colonna con tutto quello che hai fatto da quando hai aperto la pagina: foto di partenza, varianti, modifiche. Clicca una miniatura, oppure usa le frecce ← →, per tornare a una versione precedente. Quando ricarichi la pagina la colonna si svuota (le immagini restano tra le bozze).

+

Il confronto

+

Con più immagini le vedi affiancate. Clicca quella che ti interessa per aprirla da sola; Confronto ti riporta alla griglia, Salva tutte le tiene tutte.

+

Continua con questa

+

Dopo una modifica compare la barra «Nuova versione pronta». Continua con questa fa diventare il risultato la nuova base, così la prossima modifica parte da qui. Resta sull'originale la ignora. Lavorando così puoi fare modifiche a catena, un passo alla volta.

+ +

Clicca sull'immagine per altre azioni: Continua la storia, Salva come stile, Rifinisci con Z-Image, Cambia solo una zona, Usa per una locandina.

+

Rifinisci con Z-Image

+

Compare sulle immagini fatte con Klein. Z-Image ripassa pelle, luce e dettagli senza cambiare l'immagine; vedi prima e dopo affiancate e tieni quella che preferisci. Se scrivi qualcosa nel prompt, lo usa come guida per la rifinitura.

+
+ + +
+

Capitolo 11

+

Gli strumenti

+

Quattro lavori di precisione che non servono prompt.

+

Ingrandisci ×2

+

Raddoppia la risoluzione aggiungendo dettaglio vero (SeedVR2), non solo pixel più grandi. Per stampe e schermi grandi. È lo strumento più pesante: su immagini grandi conta qualche minuto.

+

Scontorna

+
+
Volpe con sfondoPrima
+
Volpe scontornataScontornata
+
+

Toglie lo sfondo e lascia il soggetto su trasparente (PNG), con un modello dedicato (BiRefNet) molto preciso anche su capelli e pelo.

+

Vettorizza in SVG

+

Trasforma l'immagine in un file SVG: invece dei pixel ci sono forme vere, nitide a qualsiasi grandezza, da un adesivo a un cartellone. Serve per loghi, stampa, plotter da taglio, incisione laser, ricamo.

+
+ Finestra Vettorizza con il logo +
Il logo Liuteria diventa 16 forme e pesa 21 KB, con lo sfondo bianco già tolto.
+
+ + + + + +
TipoRisultatoPer
IllustrazioneFino a 16 colori, la più fedele.Sticker, illustrazioni, loghi a colori.
Pochi colori8 colori, forme più grandi e pulite, file leggero.Stampa serigrafica, vinile, plotter.
Solo contorniLe linee scure, su trasparente.Pagine da colorare, incisione, timbri.
+
+
Sticker originalePNG
+
Volpe in SVG a pochi coloriPochi colori
+
Volpe solo contorniSolo contorni
+
+

Sfondo trasparente (acceso di default) toglie il colore che riempie i bordi, di solito il bianco dietro un logo. Le zone di quel colore chiuse dentro una forma, come il buco di una «A», restano: è voluto, così il bianco degli occhi o di una pancia non sparisce.

+
Ricetta per un logo perfetto

Genera con lo stile Logo o Sticker (forme piatte e pochi colori), poi Vettorizza. Con le foto l'SVG viene pesante e «dipinto»: PixRick te lo segnala.

+

Viste 3D

+

Sulle figure fatte con gli stili Funko o Statuetta 3D compare Viste 3D: PixRick crea la stessa figura vista di lato e di spalle. Con 3–4 viste i servizi che trasformano immagini in modelli 3D (Tripo, Meshy, Hunyuan3D) ricostruiscono molto meglio il retro, e il modello si stampa senza sorprese.

+
Una figura Funko vista da quattro lati
Il Funko del liutaio fatto con Ristila (a sinistra) e le tre viste generate: lato, spalle, altro lato.
+
+ + +
+

Capitolo 12

+

Locandina

+

L'AI fa le immagini, la Locandina le trasforma in un manifesto vero: template studiati, font veri, loghi e foto che sposti dove vuoi. Le lettere non sono mai sbagliate, perché non le disegna l'AI.

+ +

Sei template, sei idee diverse

+
Lo stesso evento nei sei template
Lo stesso evento in tutti e sei: cambia la struttura, non solo il colore.
+ + + + + + + + +
TemplateCom'è fattoIdeale per
ClassicaLogo o titolo in alto, foto naturale, informazioni a colonne in basso.Serate con un nome solo.
Line-upIntestazione a filetti, band dalla principale alle altre, foto in duotono.Più band, festival, rassegne.
HeadlinerUn nome enorme allineato a sinistra, la data in alto a destra, foto in bianco e nero.Un protagonista con ospiti.
Data giganteIl giorno occupa mezza locandina, il mese corre in verticale.Date da ricordare, anteprime.
FasciaFoto sopra, fascia di colore pieno con i testi sotto.Social, eventi diurni, locali.
MinimalCarta chiara, foto incorniciata, griglia tipografica.Mostre, presentazioni, teatro.
+

Le anteprime dei template mostrano già i tuoi testi e le tue immagini: scegli guardando il risultato, non uno schema. Ogni template imposta il suo font e il suo trattamento della foto; poi puoi cambiarli.

+ +

1. L'immagine

+
Scelta dell'immagine di sfondo
Dalla galleria, dalle bozze o da un file. È facoltativa: senza immagine il template usa un fondo sfumato nel colore d'accento.
+

Sotto il pulsante scegli il trattamento: Naturale, Bianco e nero o Duotono, che ricolora la foto dal nero al colore d'accento e la lega ai testi. Posizione e zoom decidono il taglio.

+
Consiglio

Genera lo sfondo pensando alla locandina: un soggetto chiaro e spazio vuoto dove andranno i testi. Esempio: «silhouette del pubblico con le mani alzate, luci calde e fasci di luce nella foschia, i due terzi in alto quasi solo fumo».

+ +

2. Il template

+
Template Line-up selezionato
Line-up con la foto del pubblico in duotono giallo: la band principale grande, le altre sotto nel colore d'accento.
+ +

3. Loghi e foto

+
Tre loghi di band sulla locandina
Tre band, tre loghi. Il template li mette in fila con lo stesso peso visivo; quello selezionato ha la cornice con la maniglia.
+
    +
  • Logo carica uno o più file insieme (band, sponsor, locale). Foto aggiunge un'immagine come riquadro: rettangolo, angoli arrotondati o cerchio.
  • +
  • Sposta trascinando sulla locandina, ridimensiona tirando la maniglia nell'angolo, Canc toglie, le frecce spostano di precisione.
  • +
  • Per ogni livello: colore (originale, bianco, nero, accento), Togli lo sfondo bianco, dimensione, porta avanti o dietro. Rimetti a posto lo riconsegna al template.
  • +
  • I loghi prendono il posto dei primi nomi della line-up: a testo restano solo le band che il logo non ce l'hanno.
  • +
+ +

4. Testi, carattere, formato

+
Campi di testo e scelta del carattere
Titolo, etichetta, line-up (una band per riga), data, ora, luogo, una riga piccola. Ogni template mostra solo i campi che usa.
+

Sette font veri, colore del testo e d'accento, cinque formati (2:3, A4, 4:5 per i post, 9:16 per le storie, 1:1). La grana da stampa toglie l'effetto troppo digitale.

+ +

Il risultato

+
+ Locandina Notte acustica con tre band +
+

2000 × 3000 pixel, pronta per la stampa o per i social. Salva in galleria la tiene con le altre immagini, Scarica la porta dove vuoi.

+

Tutto il lavoro resta salvato: se torni nella Locandina ritrovi template, testi e livelli come li avevi lasciati.

+
Consiglio

Scegli il colore d'accento da un dettaglio della foto: con il duotono tutta la locandina parla con una voce sola.

+
+
+
+ + +
+

Capitolo 13

+

Galleria

+
La galleria
+

Qui c'è tutto quello che hai salvato. I filtri in alto separano create, ristilizzate, modificate, locandine e preferite (la stella). Selezionando più immagini compare una barra per metterle tra le preferite o eliminarle insieme.

+

Bozze

+

Le immagini che non hai salvato. Restano 24 ore e poi si cancellano da sole: la galleria non si riempie mai di tentativi. Se una bozza ti piace, Salva in galleria.

+

Cestino

+

Le immagini eliminate dalla galleria finiscono qui e restano finché non svuoti il cestino. Puoi ripristinarle.

+

Il dettaglio

+
Il dettaglio di un'immagine
+

Clicca un'immagine per vederla grande, con prompt, modello, stili, misura, seme e data. Dai un titolo (Invio per salvarlo), passa alle altre con ← →, clicca l'immagine per vederla a grandezza reale e scorrerla (utile per quelle lunghe). Da qui hai tutte le azioni: aprila nello Studio, modificala, ristilala, vettorizzala, fanne una locandina.

+
+ + +
+

Capitolo 14

+

PixRick con Claude

+

PixRick si può collegare a Claude, l'assistente AI di Anthropic. Da quel momento Claude lo usa come uno strumento suo: tu chiedi a parole, Claude scrive i prompt, sceglie modello e stile, guarda i risultati e corregge il tiro.

+

Come si collega

+

Il collegamento passa da MCP (Model Context Protocol), il modo standard con cui Claude usa programmi esterni. PixRick include il suo server MCP e durante l'installazione si registra da solo nell'app Claude per desktop e in Claude Code: dopo un riavvio di Claude, PixRick compare tra gli strumenti disponibili e si può usare in qualsiasi conversazione.

+

Le immagini restano sul computer. Claude riceve solo le anteprime dei risultati che chiede, per poterli valutare.

+ +

Cosa può fare Claude

+ + + + + + + + +
StrumentoCosa fa
generate_imageTutto quello che fai dallo Studio: crea, ristila, modifica, storia, rifinisci, ingrandisci, scontorna, viste 3D. Con stili, formato, qualità, seme, maschera.
vectorize_imageTrasforma un'immagine in SVG e lo salva in outputs/_vettoriali.
get_image_jobControlla un lavoro lungo e ne ritira i risultati.
save_imagesSposta in galleria le bozze che ti piacciono.
list_templatesLegge gli stili disponibili, compresi i tuoi.
recent_imagesRitrova le ultime immagini con prompt, seme e percorso.
+ +

Un esempio vero

+

Queste immagini sono state fatte così, per questa guida.

+
+

Mi fai uno sticker di una volpe col caffè? Poi mi serve in SVG per il plotter.

+ generate_image · stile sticker · Z-Image + +

Eccolo. Per il plotter ti conviene la versione «Pochi colori»: forme grandi e solo 8 colori, quindi meno tagli.

+ vectorize_image · essenziale +

Salvato in outputs/_vettoriali: 58 forme, 67 KB, sfondo trasparente.

+
+
+

Fammi una foto di un vecchio liutaio al lavoro. Poi la stessa scena in anime, e una versione Funko da stampare.

+ generate_image · crea · foto · Massima · seme 2026 + generate_image · ristila · anime + generate_image · modifica · Klein · 4:5 +
+ + + +
+

Il primo Funko era uscito con due figure: ho riformulato l'istruzione descrivendo solo la trasformazione e alla seconda è venuto giusto. Vuoi che prepari anche le viste di lato e di spalle per Tripo?

+
+

Nota l'ultima riga: Claude guarda il risultato, se qualcosa non va riprova da solo con un'altra formulazione, un altro modello o un altro seme. È come avere un assistente che conosce PixRick a memoria.

+ +

Cose da chiedere

+
    +
  • Prendi le foto nella cartella Evento sul Desktop e scontornale tutte.
  • +
  • Guarda questa foto e scrivimi tre prompt per rifarla in stili diversi, poi generali.
  • +
  • Fammi 4 proposte di logo per «Bottega Rick», vettorizza la migliore.
  • +
  • Trasforma questa foto in Funko e prepara le viste per la stampa 3D.
  • +
  • Crea 6 illustrazioni per un racconto, sempre con lo stesso personaggio.
  • +
  • Riprendi l'immagine di ieri del liutaio e fanne una versione invernale.
  • +
+ +

Perché è potente

+
+
+

Gratis e senza limiti

+

Le immagini si generano in locale: Claude può fare 20 tentativi senza costi di generazione.

+

Lavori in blocco

+

Cartelle intere, varianti in serie, nomi e ordine dei file: Claude li gestisce mentre fai altro.

+
+
+

Occhio critico

+

Claude vede i risultati e li giudica: scarta le mani storte, rifà le scritte sbagliate, sceglie il migliore.

+

Tutto collegato

+

Nella stessa conversazione Claude può cercare idee, scrivere i testi di una locandina, generare le immagini e impaginare un documento.

+
+
+
Bozze anche con Claude

Quello che genera Claude finisce tra le bozze come il resto: lo vedi in galleria, e resta solo se tu (o Claude, su tua richiesta) lo salvi.

+
+ + +
+

Capitolo 15

+

Privacy

+
    +
  • Niente rete. Il motore blocca ogni connessione verso l'esterno. Ogni tentativo viene fermato e annotato in un registro.
  • +
  • Tutto in una cartella. Programmi, modelli, impostazioni, immagini e cache stanno in un'unica cartella. Cancellata quella, non resta nulla.
  • +
  • Le foto caricate si cancellano da sole dopo 24 ore.
  • +
  • Le bozze spariscono dopo 24 ore; la galleria contiene solo ciò che salvi.
  • +
  • La colonna Sessione si svuota a ogni apertura della pagina.
  • +
+
+ + +
+

Capitolo 16

+

Scorciatoie

+ + + + + + + + + + + + +
TastiDoveCosa fa
⌘ ↵StudioGenera
↑Prompt vuotoRipropone l'ultimo prompt
⌘ VStudioIncolla un'immagine come foto di partenza
← →StudioScorre la sessione
← →DettaglioImmagine precedente o successiva
B EPennelloPennello o gomma
[ ]PennelloDimensione
⌘ ZPennelloAnnulla tratto
?OvunqueApre questa guida
EscOvunqueChiude finestre, guida e infobox
+
+ + +
+

Capitolo 17

+

Problemi e soluzioni

+

Il Ristila non cambia quasi niente

+

Stai probabilmente usando Z-Image su un cambio di materiale (disegno → foto). Riaccendi «Decide PixRick» o scegli Klein, o la combo Klein + Z-Image.

+

Il Funko ha due figure o il viso sbagliato

+

Prova Varia con un seme nuovo e descrivi chi c'è nella foto in poche parole. Lascia il formato proposto dallo stile.

+

Le scritte sono sbagliate

+

Mettile tra virgolette, usa Z-Image e qualità Massima. Per testi che devono essere perfetti usa la Locandina.

+

Mani o dita strane

+

Varia (seme nuovo) o Altro modello. Poi, se serve, Modifica con la zona dipinta solo sulla mano.

+

Va lento

+

Controlla che non sia in corso una pausa di raffreddamento. Chiudi le app pesanti o premi il pulsante della memoria. Usa la qualità Rapida per provare idee.

+

Manca un pulsante (Migliora, Vettorizza, Scontorna…)

+

Lo strumento non è installato: ripeti l'installazione, che aggiunge solo quello che manca.

+
+ + +
+

Capitolo 18

+

Glossario

+ + + + + + + + + + + + +
PromptLa descrizione di quello che vuoi ottenere.
ModelloIl «cervello» che disegna. In PixRick: Z-Image Turbo e FLUX.2 Klein.
SemeIl numero che fissa la parte casuale. Stesso seme, stessa immagine.
PassiQuante volte il modello ripassa l'immagine. Più passi, più dettaglio e più tempo.
FedeltàQuanto della foto di partenza sopravvive nel Ristila.
Maschera / zonaLa parte dipinta col pennello: solo lì l'immagine cambia.
BozzaUn risultato non salvato. Sparisce dopo 24 ore.
ScontornareTogliere lo sfondo lasciando solo il soggetto.
SVGImmagine fatta di forme invece che di pixel: nitida a qualsiasi grandezza.
MCPIl collegamento che permette a Claude di usare PixRick.
Image-to-3DServizi che trasformano una o più immagini in un modello 3D stampabile.
+
+ +
+
+
+ + + diff --git a/web/icon.svg b/web/icon.svg new file mode 100644 index 0000000000000000000000000000000000000000..30f332da248389bd411f0126c0ea2ad614caed2a --- /dev/null +++ b/web/icon.svg @@ -0,0 +1 @@ +AAAWgmp1bWIAAAAeanVtZGMycGEAEQAQgAAAqgA4m3EDYzJwYQAAABZcanVtYgAAAEdqdW1kYzJtYQARABCAAACqADibcQN1cm46YzJwYTo4OWE5YWU2MC1kODFiLTRkNjgtYjdlZC1iZjdlZDMwMTJkMjcAAAADl2p1bWIAAAApanVtZGMyYXMAEQAQgAAAqgA4m3EDYzJwYS5hc3NlcnRpb25zAAAAALxqdW1iAAAARGp1bWRjYm9yABEAEIAAAKoAOJtxE2MycGEuaW5ncmVkaWVudC52MwAAAAAYYzJzaG3NqI2Hs2s26HnjjEwcVAkAAABwY2JvcqNpZGM6Zm9ybWF0bWltYWdlL3N2Zyt4bWxqaW5zdGFuY2VJRHgseG1wOmlpZDoxZTc2NGM5Zi01MjhkLTQ0NGUtOTBlMC01ZTQ3ZDRlMjc0OTNscmVsYXRpb25zaGlwaHBhcmVudE9mAAAB4mp1bWIAAABBanVtZGNib3IAEQAQgAAAqgA4m3ETYzJwYS5hY3Rpb25zLnYyAAAAABhjMnNoGfm0tPbW6hrVGYx7/e46TgAAAZljYm9yomdhY3Rpb25zgqJmYWN0aW9ua2MycGEub3BlbmVkanBhcmFtZXRlcnOha2luZ3JlZGllbnRzgaJjdXJseC1zZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmluZ3JlZGllbnQudjNkaGFzaFggsSGmMmwmbA/XTkfbtFccq2RaukNgNfslPbMtRqN7Y/SkZmFjdGlvbngdY29tLmFudGhyb3BpYy5jbGF1ZGUucHJvdmlkZWRqcGFyYW1ldGVyc6F4H2NvbS5hbnRocm9waWMub3JpZ2luLWNvbmZpZGVuY2VndW5rbm93bmtkZXNjcmlwdGlvbnhmQ2xhdWRlIHByb3ZpZGVkIHRoaXMgZmlsZSBhdCB0aGUgcmVxdWVzdCBvZiBhIHVzZXIgYW5kIG1heSBoYXZlIGNyZWF0ZWQgb3IgbW9kaWZpZWQgdGhlIGZpbGUgY29udGVudHMubXNvZnR3YXJlQWdlbnShZG5hbWVmQ2xhdWRlcmFsbEFjdGlvbnNJbmNsdWRlZPUAAADIanVtYgAAAEBqdW1kY2JvcgARABCAAACqADibcRNjMnBhLmhhc2guZGF0YQAAAAAYYzJzaNala6ZZBQM4qc/b6XWGv5wAAACAY2JvcqVjYWxnZnNoYTI1NmNwYWRMAAAAAAAAAAAAAAAAZGhhc2hYIFQmXIoD0LC/z5aLHBGKqEZZV6QCVqfKIahKw5fDTA4yZG5hbWVuanVtYmYgbWFuaWZlc3RqZXhjbHVzaW9uc4GiZXN0YXJ0GQHEZmxlbmd0aBkeBAAAAj5qdW1iAAAAJ2p1bWRjMmNsABEAEIAAAKoAOJtxA2MycGEuY2xhaW0udjIAAAACD2Nib3KlY2FsZ2ZzaGEyNTZpc2lnbmF0dXJleE1zZWxmI2p1bWJmPS9jMnBhL3VybjpjMnBhOjg5YTlhZTYwLWQ4MWItNGQ2OC1iN2VkLWJmN2VkMzAxMmQyNy9jMnBhLnNpZ25hdHVyZWppbnN0YW5jZUlEeCx4bXA6aWlkOjQ5YjU4MWZkLWQ5MjAtNGEyNS1hYTE0LTYzZmUyYTU1ZmEzNnJjcmVhdGVkX2Fzc2VydGlvbnODomN1cmx4LXNlbGYjanVtYmY9YzJwYS5hc3NlcnRpb25zL2MycGEuaW5ncmVkaWVudC52M2RoYXNoWCCxIaYybCZsD9dOR9u0VxyrZFq6Q2A1+yU9sy1Go3tj9KJjdXJseCpzZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmFjdGlvbnMudjJkaGFzaFggMoTxYmUJREtdSM2g82kFQs5jDhTfPqZAPXgWfdiChnKiY3VybHgpc2VsZiNqdW1iZj1jMnBhLmFzc2VydGlvbnMvYzJwYS5oYXNoLmRhdGFkaGFzaFggHl3pGYA4MO+fVFuL0P2Zx3EHGYT4913R7wSFU10ZWct0Y2xhaW1fZ2VuZXJhdG9yX2luZm+jZG5hbWVvQW50aHJvcGljIEZpbGVzZ3ZlcnNpb25lMS4wLjBrc3BlY1ZlcnNpb25lMi40LjAAABA4anVtYgAAAChqdW1kYzJjcwARABCAAACqADibcQNjMnBhLnNpZ25hdHVyZQAAABAIY2JvctKEWQISogEmGCFZAgowggIGMIIBjaADAgECAhRA5aAK7sI50L64g/oGQgU9Z1UTADAKBggqhkjOPQQDAzBJMRcwFQYDVQQKEw5BbnRocm9waWMsIFBCQzEuMCwGA1UEAxMlQW50aHJvcGljIENvbnRlbnQgQ3JlZGVudGlhbHMgUm9vdCBDQTAeFw0yNjA4MDcxODQzNTZaFw0yODA4MDYxOTQzNTZaMEQxFzAVBgNVBAoTDkFudGhyb3BpYywgUEJDMSkwJwYDVQQDEyBBbnRocm9waWMgQ2xhdWRlIENvbnRlbnQgU2lnbmluZzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJh6CmvLUBgFFNU0vUKlOVtE6djd17L5SuwX0LemFisBM3dkd/3cyjxFA3Qo5S46fX0/ihY0VZ7mfb9KF703t5OjWDBWMA4GA1UdDwEB/wQEAwIHgDAVBgNVHSUEDjAMBgorBgEEAYPoXgIBMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAUzlHiBIFOZFsj+OPEz5o+nMHXXMIwCgYIKoZIzj0EAwMDZwAwZAIwMXMdFJ4BetLLVY7ORuE9noqbbAZOZn/aArXyTwFAZfKrPzxF2vPoJNf1+UCdg1XGAjBwX1zd9WGqYkqmL5SFqw1QySjr1zJfpJM9+1rdDwSPLMOPOjKuiXjoU/pUUeG9RwmhY3BhZFkNngAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPZYQJWZMYVglQ3xzRtREaiXXLxq68n0azWVNJahoMmPWAJEBe15VgPDlP/yaDegnz6CG9FFkTER3UaEiF+FCBQ1SE4= diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000000000000000000000000000000000000..163558dc85385946272f7dd361447fc5b5bf4153 --- /dev/null +++ b/web/index.html @@ -0,0 +1,702 @@ + + + + + + + + PixRick · Studio di immagini AI + + + + + + + + + + + + + + + + + + +
+
+ + PixRick +
+ +
+ + + + +
+
+ +
+
+
+ +
+
+

Cosa vuoi vedere oggi?

+

Descrivi un'idea qui sotto, oppure trascina qui una foto per cambiarle stile o modificarla. Le immagini restano sul tuo dispositivo.

+
+ +
+
+ Immagine di partenza + +
+ Immagine di partenza +
+ +
+ + +
+ +
+
+ + + +
+
+

In coda

+

+
+
+ + + + + +
+
+ + + + + +
+
+
+ + + + +
+

+
+ + + +
+
+
+ +
+
+
+
Italiano · per te
+ +
+
+
Inglese · va al modello
+ +
+
+
+ +
+
+ + + +
+
+
+ + +
+ +
+
+
+ + +
+

Trascina loghi e foto per spostarli, tira l'angolo per ridimensionarli. Canc li toglie.

+ +
+ + +
+ +
+ + + +
+ + + + +
+ + +
+ + + +
+
+
+ + +
+

+
+ +
+ + +
+
+
+ + +
+

Nuovo stile

+ + +

Descrivi colori, luce, materiali e atmosfera, anche in italiano: lo traduco io quando lo salvi. Si combina con gli altri stili.

+
Formato preferito
+
Colore
+ + +
+ + + + +
+
+
+ + +
+
+

Traccio i contorni…

+
+
+

Vettorizza

+

Trasforma l'immagine in un SVG: forme vere invece di pixel, nitido a qualsiasi grandezza. Per stampe, taglio, incisione e loghi.

+
+ + + +
+

+ + + +
+ + + +
+
+
+ + +
+

Scegli lo sfondo

+
+ + +
+ + +
+
+
+ + + +
+

Benvenuto in PixRick

+

Uno studio di immagini AI che gira gratis sulle GPU di Hugging Face. Niente abbonamenti, niente pubblicità.

+
+
+
Come ospite
+
2 minuti di GPU al giorno, coda normale.
+
+
+
Con un account Hugging Face
+
5 minuti al giorno e precedenza in coda. L'account è gratuito e PixRick non vede la tua password.
+
+
+
Le immagini restano tue
+
Galleria e bozze vivono nel tuo browser. Il server non conserva né immagini né prompt: scarica quello che vuoi tenere.
+
+
+

Qui niente nudo né contenuti sessuali, niente minori in contesti inappropriati, niente immagini di persone reali senza il loro consenso. Ogni immagine è marcata come generata con AI.

+ +
+ Accedi con Hugging Face + +
+
+
+ + +

Minuti finiti per oggi

+

+

+
+ + Accedi con Hugging Face +
+
+ + +
+

+

+
+ + +
+
+
+ + +
+ +

Guida

+ + PDF + A tutta pagina + +
+ +
+ +
+ + + + + + + diff --git a/web/legal/legal.css b/web/legal/legal.css new file mode 100644 index 0000000000000000000000000000000000000000..6e5c693cd8e534ea7de27b96f65683adfeb958eb --- /dev/null +++ b/web/legal/legal.css @@ -0,0 +1,31 @@ +:root { + --bg: #141519; + --text: #ececef; + --muted: #a3a5b0; + --line: rgba(255, 255, 255, 0.09); + --accent: #cbbcff; + --serif: ui-serif, "New York", "Iowan Old Style", "Palatino", Georgia, serif; + --sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Inter", system-ui, sans-serif; +} +* { box-sizing: border-box; } +html { background: var(--bg); color: var(--text); -webkit-text-size-adjust: 100%; } +body { margin: 0; font-family: var(--sans); font-size: 16px; line-height: 1.6; -webkit-font-smoothing: antialiased; } +main { max-width: 68ch; margin: 0 auto; padding: max(28px, env(safe-area-inset-top)) 22px max(64px, env(safe-area-inset-bottom)); } +header { display: flex; align-items: center; gap: 12px; margin-bottom: 36px; } +header a.home { display: inline-flex; align-items: center; gap: 10px; color: var(--text); text-decoration: none; font-family: var(--serif); font-size: 20px; } +header img { width: 26px; height: 26px; } +header .spacer { flex: 1; } +.lang { display: inline-flex; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; } +.lang button { min-width: 44px; height: 34px; border: 0; background: transparent; color: var(--muted); font: 600 12px var(--sans); letter-spacing: 0.04em; cursor: pointer; } +.lang button[aria-pressed="true"] { background: rgba(255, 255, 255, 0.08); color: var(--text); } +h1 { margin: 0 0 6px; font-family: var(--serif); font-weight: 400; font-size: clamp(30px, 6vw, 40px); line-height: 1.1; } +.updated { margin: 0 0 32px; color: var(--muted); font-size: 14px; } +h2 { margin: 36px 0 8px; font-family: var(--serif); font-weight: 400; font-size: 23px; } +p, li { color: #d6d7dd; } +ul { padding-left: 20px; } +li { margin: 4px 0; } +a { color: var(--accent); } +strong { color: var(--text); font-weight: 600; } +section[lang] { display: none; } +html[data-lang="it"] section[lang="it"], html[data-lang="en"] section[lang="en"] { display: block; } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 6px; } diff --git a/web/legal/legal.js b/web/legal/legal.js new file mode 100644 index 0000000000000000000000000000000000000000..a86915e4db4f47afa5be09daaf691e6cd32eb190 --- /dev/null +++ b/web/legal/legal.js @@ -0,0 +1,21 @@ +(() => { + const pick = () => { + const asked = new URLSearchParams(location.search).get("lang"); + let saved = null; + try { saved = localStorage.getItem("pixrick.lingua"); } catch { /* storage bloccato */ } + const lang = asked || saved || (navigator.language || "it").slice(0, 2); + return lang === "it" ? "it" : "en"; + }; + const set = (lang) => { + document.documentElement.dataset.lang = lang; + document.documentElement.lang = lang; + document.querySelectorAll(".lang button").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.lang === lang))); + const title = document.querySelector(`section[lang="${lang}"] h1`); + if (title) document.title = `${title.textContent} · PixRick`; + }; + document.querySelectorAll(".lang button").forEach((b) => b.addEventListener("click", () => { + try { localStorage.setItem("pixrick.lingua", b.dataset.lang); } catch { /* storage bloccato */ } + set(b.dataset.lang); + })); + set(pick()); +})(); diff --git a/web/legal/privacy.html b/web/legal/privacy.html new file mode 100644 index 0000000000000000000000000000000000000000..3d4218c64b70b076336d2c4a63487355d484d904 --- /dev/null +++ b/web/legal/privacy.html @@ -0,0 +1,94 @@ + + + + + + + Informativa privacy · PixRick + + + + +
+
+ PixRick + +
+ + +
+
+ +
+

Informativa privacy

+

Aggiornata il 19 novembre 2026

+ +

PixRick è un progetto personale e gratuito. È costruito per sapere di te il meno possibile: niente pubblicità, niente statistiche di visita, niente profilazione.

+ +

Chi è il titolare

+

{{titolare}}. Per qualsiasi richiesta: {{contatto}}.

+ +

Cosa succede quando generi un'immagine

+ + +

Cosa resta sul tuo dispositivo

+

Galleria, bozze, stili che crei e preferenze sono salvati nel tuo browser (IndexedDB e localStorage). Non vengono inviati a nessuno. Puoi cancellarli quando vuoi dalla galleria o svuotando i dati del sito dalle impostazioni del browser. Le bozze non salvate si cancellano da sole dopo 24 ore.

+ +

Accesso con Hugging Face

+

Se scegli di accedere, Hugging Face ci comunica il tuo nome utente e il nome pubblico del profilo, che mostriamo nell'interfaccia. Non riceviamo né vediamo la tua password. L'accesso serve solo a darti più minuti di GPU e la precedenza in coda, che Hugging Face gestisce in base al tuo account. Il login usa un cookie tecnico di sessione, necessario al funzionamento.

+ +

Infrastruttura

+

PixRick è ospitato su Hugging Face Spaces (Hugging Face, Inc., Stati Uniti), che fornisce server e GPU. Come ogni servizio web, Hugging Face può registrare dati tecnici di connessione (indirizzo IP, browser, orario) per sicurezza e per calcolare i minuti di GPU usati. Questi dati sono trattati secondo la privacy policy di Hugging Face.

+ +

Base giuridica

+

Trattiamo i dati strettamente necessari per fornirti il servizio che chiedi (art. 6.1.b GDPR) e per proteggerlo da abusi (art. 6.1.f GDPR, legittimo interesse).

+ +

Età minima

+

PixRick è riservato a persone maggiorenni.

+ +

I tuoi diritti

+

Puoi chiedere accesso, rettifica, cancellazione, limitazione e opposizione, e puoi proporre reclamo al Garante per la protezione dei dati personali (garanteprivacy.it). Poiché non conserviamo immagini né prompt, nella maggior parte dei casi non c'è nulla da cancellare da parte nostra: i tuoi dati sono già nel tuo browser.

+
+ +
+

Privacy notice

+

Updated 19 November 2026

+ +

PixRick is a free personal project. It is built to know as little about you as possible: no ads, no visitor analytics, no profiling.

+ +

Who is responsible

+

{{titolare}}. For any request: {{contatto}}.

+ +

What happens when you generate an image

+ + +

What stays on your device

+

Gallery, drafts, the styles you create and your preferences are saved in your browser (IndexedDB and localStorage). They are not sent to anyone. You can delete them at any time from the gallery or by clearing this site's data in your browser settings. Unsaved drafts delete themselves after 24 hours.

+ +

Signing in with Hugging Face

+

If you choose to sign in, Hugging Face shares your username and public profile name with us, and we show them in the interface. We never receive or see your password. Signing in only gives you more GPU minutes and queue priority, which Hugging Face manages based on your account. Sign-in uses a technical session cookie that the service needs to work.

+ +

Infrastructure

+

PixRick is hosted on Hugging Face Spaces (Hugging Face, Inc., United States), which provides servers and GPUs. Like any web service, Hugging Face may log technical connection data (IP address, browser, time) for security and to count the GPU minutes used. That data is handled under Hugging Face's privacy policy.

+ +

Legal basis

+

We process only the data needed to provide the service you ask for (GDPR art. 6.1.b) and to protect it from abuse (GDPR art. 6.1.f, legitimate interest).

+ +

Minimum age

+

PixRick is for adults only.

+ +

Your rights

+

You can ask for access, correction, deletion, restriction and objection, and you can lodge a complaint with your data protection authority (in Italy, the Garante per la protezione dei dati personali). Since we keep neither images nor prompts, in most cases there is nothing for us to delete: your data is already in your browser.

+
+
+ + + diff --git a/web/legal/termini.html b/web/legal/termini.html new file mode 100644 index 0000000000000000000000000000000000000000..a6a079826bdaf39b19cee7897a9a411d1908715c --- /dev/null +++ b/web/legal/termini.html @@ -0,0 +1,108 @@ + + + + + + + Termini d'uso · PixRick + + + + +
+
+ PixRick + +
+ + +
+
+ +
+

Termini d'uso

+

Aggiornati il 19 novembre 2026

+ +

PixRick è una dimostrazione gratuita di generazione di immagini con intelligenza artificiale, offerta da {{titolare}}. Usandolo accetti questi termini.

+ +

Il servizio

+ + +

Cosa non puoi fare

+

Non puoi usare PixRick per creare, caricare o diffondere:

+ +

Filtri automatici bloccano molte di queste richieste, ma la responsabilità di ciò che chiedi, carichi e pubblichi resta tua. Puoi caricare solo immagini su cui hai i diritti, e foto di persone solo con il loro consenso.

+ +

Marcatura come AI

+

Ogni immagine generata contiene metadati che la dichiarano creata con intelligenza artificiale e una filigrana invisibile, come previsto dal Regolamento europeo sull'IA. Non rimuoverli. Se pubblichi un'immagine realistica che ritrae persone, luoghi o eventi, dichiara che è generata con AI.

+ +

Le immagini che crei

+

Puoi usare le immagini che generi, anche a fini commerciali, nel rispetto di questi termini e della legge. Non garantiamo che siano originali o protette dal diritto d'autore, né che non somiglino a opere esistenti: verifica prima di usarle in contesti importanti. I modelli usati (Z-Image Turbo e FLUX.2 Klein 4B) sono distribuiti con licenza Apache 2.0.

+ +

Responsabilità

+

Nei limiti consentiti dalla legge, il servizio è offerto senza garanzie e senza responsabilità per danni derivanti dal suo uso o dalla sua indisponibilità. Chi viola questi termini può essere bloccato.

+ +

Segnalazioni

+

Se trovi un contenuto o un comportamento che viola queste regole, scrivi a {{contatto}}.

+ +

Legge applicabile

+

Questi termini sono regolati dalla legge italiana. Restano salvi i diritti che ti riconosce la legge del tuo paese come consumatore.

+
+ +
+

Terms of use

+

Updated 19 November 2026

+ +

PixRick is a free demonstration of AI image generation, offered by {{titolare}}. By using it you accept these terms.

+ +

The service

+ + +

What you may not do

+

You may not use PixRick to create, upload or share:

+ +

Automatic filters block many of these requests, but you remain responsible for what you ask for, upload and publish. Upload only images you have the rights to, and photos of people only with their consent.

+ +

AI labelling

+

Every generated image carries metadata stating that it was made with artificial intelligence, plus an invisible watermark, as required by the EU AI Act. Do not remove them. If you publish a realistic image of people, places or events, say that it is AI-generated.

+ +

The images you create

+

You may use the images you generate, commercial use included, within these terms and the law. We do not guarantee that they are original or protected by copyright, or that they do not resemble existing works: check before using them where it matters. The models used (Z-Image Turbo and FLUX.2 Klein 4B) are released under the Apache 2.0 licence.

+ +

Liability

+

To the extent permitted by law, the service is provided without warranties and without liability for damages arising from its use or unavailability. Anyone who breaks these terms may be blocked.

+ +

Reports

+

If you find content or behaviour that breaks these rules, write to {{contatto}}.

+ +

Governing law

+

These terms are governed by Italian law. This does not affect the rights the law of your country gives you as a consumer.

+
+
+ + + diff --git a/web/online.js b/web/online.js new file mode 100644 index 0000000000000000000000000000000000000000..f987e738e77f93bf55c547dcf13fc6dc3f48660b --- /dev/null +++ b/web/online.js @@ -0,0 +1,103 @@ +/* Solo online: account Hugging Face, benvenuto, minuti GPU finiti, segnalazioni. */ +(() => { + "use strict"; + + const $ = (s) => document.querySelector(s); + const WELCOME_KEY = "pixrick.benvenuto.v1"; + const REPORT_URL = "https://huggingface.co/spaces/algorick/pixrick/discussions/new"; + const loginUrl = () => `/motore/login/huggingface?_target_url=${encodeURIComponent(location.pathname)}`; + const logoutUrl = () => `/motore/logout?_target_url=${encodeURIComponent(location.pathname)}`; + const t = (text) => (window.PixI18n ? window.PixI18n.t(text) : text); + + let user = { accesso: false }; + + function seenWelcome() { + try { return localStorage.getItem(WELCOME_KEY) === "1"; } catch { return false; } + } + function markWelcome() { + try { localStorage.setItem(WELCOME_KEY, "1"); } catch { /* storage bloccato */ } + } + + function renderAccount() { + const btn = $("#account-btn"); + btn.dataset.state = user.accesso ? "dentro" : "ospite"; + $("#account-text").textContent = user.accesso ? user.nome || user.utente : t("Ospite"); + $("#account-head").textContent = user.accesso ? t("Accesso con Hugging Face") + ": " + (user.utente || "") : t("Stai usando PixRick come ospite"); + $("#account-note").textContent = user.accesso ? t("5 minuti di GPU al giorno e precedenza in coda.") : t("2 minuti di GPU al giorno, coda normale."); + $("#account-login").hidden = user.accesso; + $("#account-logout").hidden = !user.accesso; + $("#account-login").href = loginUrl(); + $("#account-logout").href = logoutUrl(); + document.body.dataset.account = user.accesso ? "dentro" : "ospite"; + } + + function toggleMenu(open) { + const menu = $("#account-menu"); + const show = open ?? menu.hidden; + menu.hidden = !show; + $("#account-btn").setAttribute("aria-expanded", String(show)); + if (show) menu.querySelector("a:not([hidden]), button")?.focus(); + } + + function openWelcome() { + toggleMenu(false); + const dlg = $("#welcome"); + $("#welcome-login").href = loginUrl(); + $("#welcome-login").hidden = user.accesso; + $("#welcome-start").textContent = t(user.accesso ? "Inizia" : "Continua come ospite"); + dlg.showModal(); + } + + function quota(retryIn) { + const dlg = $("#quota"); + let when = ""; + if (retryIn) { + const h = Math.floor(retryIn / 3600); + const m = Math.ceil((retryIn % 3600) / 60); + when = h ? `${h} h ${m} min` : `${m} min`; + } + $("#quota-when").textContent = when ? t("I minuti tornano tra") + " " + when + "." : t("I minuti tornano entro 24 ore dal primo utilizzo."); + $("#quota-login").hidden = user.accesso; + $("#quota-login").href = loginUrl(); + $("#quota-text").textContent = user.accesso + ? t("Hai usato i 5 minuti di GPU gratuiti di oggi.") + : t("Hai usato i 2 minuti di GPU gratuiti per gli ospiti. Con un account Hugging Face gratuito ne hai 5 e la precedenza in coda."); + dlg.showModal(); + } + + function wire() { + $("#account-btn").addEventListener("click", (e) => { e.stopPropagation(); toggleMenu(); }); + document.addEventListener("click", (e) => { if (!e.target.closest("#account-menu")) toggleMenu(false); }); + document.addEventListener("keydown", (e) => { if (e.key === "Escape") toggleMenu(false); }); + $("#account-welcome").addEventListener("click", openWelcome); + $("#account-report").addEventListener("click", () => { toggleMenu(false); window.open(REPORT_URL, "_blank", "noopener"); }); + const terms = $("#welcome-terms"); + const sync = () => { + $("#welcome-start").disabled = !terms.checked; + $("#welcome-login").setAttribute("aria-disabled", String(!terms.checked)); + }; + terms.addEventListener("change", sync); + $("#welcome-login").addEventListener("click", (e) => { + if (!terms.checked) { e.preventDefault(); return; } + markWelcome(); + }); + $("#welcome").addEventListener("cancel", (e) => { if (!seenWelcome()) e.preventDefault(); }); + $("#welcome-form").addEventListener("submit", () => markWelcome()); + $("#quota-close").addEventListener("click", () => $("#quota").close()); + if (seenWelcome()) terms.checked = true; + sync(); + } + + async function boot() { + wire(); + if (!seenWelcome()) openWelcome(); + user = await window.PixBackend.whoAmI(); + renderAccount(); + if ($("#welcome").open) $("#welcome-login").hidden = user.accesso; + } + + window.PixOnline = { quota, openWelcome, refresh: async () => { user = await window.PixBackend.whoAmI(); renderAccount(); } }; + document.addEventListener("pixrick:lang", renderAccount); + renderAccount(); + boot(); +})(); diff --git a/web/poster.js b/web/poster.js new file mode 100644 index 0000000000000000000000000000000000000000..fc3c4abd540b53b3c351628dfdebea834f1d01b0 --- /dev/null +++ b/web/poster.js @@ -0,0 +1,1290 @@ +"use strict"; + +/* Locandina: template con strutture diverse, testi con font veri, loghi e foto come livelli + da spostare e ridimensionare sulla tela. */ + +(() => { + const FONTS = [ + { id: "oswald", nome: "Oswald", heavy: [700, "PR Oswald"], medium: [500, "PR Oswald"], track: 0.01 }, + { id: "anton", nome: "Anton", heavy: [400, "PR Anton"], medium: [500, "PR Oswald"], track: 0.01 }, + { id: "bebas", nome: "Bebas Neue", heavy: [400, "PR Bebas"], medium: [400, "PR Bebas"], track: 0.04 }, + { id: "archivo", nome: "Archivo Black", heavy: [400, "PR Archivo"], medium: [600, "PR Inter"], track: 0 }, + { id: "inter", nome: "Inter", heavy: [800, "PR Inter"], medium: [600, "PR Inter"], track: -0.01 }, + { id: "playfair", nome: "Playfair", heavy: [900, "PR Playfair"], medium: [700, "PR Playfair"], track: 0 }, + { id: "marker", nome: "Marker", heavy: [400, "PR Marker"], medium: [500, "PR Oswald"], track: 0 }, + ]; + const BODY = [600, "PR Inter"]; + const FORMATS = { "2:3": [2000, 3000], A4: [2000, 2828], "4:5": [2000, 2500], "9:16": [1800, 3200], "1:1": [2000, 2000] }; + const TEXT_COLORS = ["#f6f5f0", "#ffffff", "#111111", "#ffd600"]; + const ACCENT_COLORS = ["#ffd600", "#ff3b3b", "#ff7a1a", "#cbbcff", "#4dd4ff", "#f6f5f0"]; + const FIELDS = ["titolo", "tag", "lineup", "data", "ora", "luogo", "info"]; + const SAMPLE = { + titolo: "Notte acustica", + tag: "Live in bottega", + lineup: "The Lanterns\nMara Vento\nI Cortili", + data: "Venerdì 12 dicembre", + ora: "Ore 21:00", + luogo: "Teatro comunale", + info: "Ingresso libero", + }; + const MONTHS = ["gen", "feb", "mar", "apr", "mag", "giu", "lug", "ago", "set", "ott", "nov", "dic"]; + + const TEMPLATES = [ + { id: "classica", nome: "Classica", desc: "Logo o titolo in alto, foto naturale, informazioni a colonne.", fields: ["titolo", "tag", "data", "ora", "luogo", "info"], bleed: true, font: "oswald", treatment: "naturale" }, + { id: "lineup", nome: "Line-up", desc: "Festival: più band in evidenza, dalla principale alle altre.", fields: FIELDS, bleed: true, font: "bebas", treatment: "duotono" }, + { id: "headliner", nome: "Headliner", desc: "Un nome enorme in basso, gli altri in supporto, data in alto.", fields: ["tag", "lineup", "data", "ora", "luogo", "info"], bleed: true, font: "archivo", treatment: "bn" }, + { id: "data", nome: "Data gigante", desc: "Il giorno diventa la grafica, testi in colonna.", fields: FIELDS, bleed: true, font: "anton", treatment: "duotono" }, + { id: "fascia", nome: "Fascia", desc: "Foto sopra, fascia di colore pieno con i testi.", fields: FIELDS, bleed: false, font: "oswald", treatment: "naturale" }, + { id: "minimal", nome: "Minimal", desc: "Carta chiara, foto incorniciata, griglia tipografica.", fields: FIELDS, bleed: false, light: true, font: "inter", treatment: "bn" }, + ]; + + const defaults = { + template: "classica", + bg: null, + bgY: 0.5, + bgZoom: 1, + texts: { ...SAMPLE }, + upper: true, + font: "oswald", + textScale: 1, + textColor: "#f6f5f0", + accent: "#ffd600", + format: "2:3", + treatment: "naturale", + shade: 0.85, + grain: true, + }; + + const S = { ...structuredClone(defaults), ...prefs.get("poster", {}) }; + S.texts = { ...defaults.texts, ...(S.texts || {}) }; + if (!TEMPLATES.some((t) => t.id === S.template)) S.template = "classica"; + delete S.layout; + + let layers = []; + const processed = new Map(); + let rects = new Map(); + let selected = null; + let bgImg = null; + let grain = null; + let pending = 0; + let thumbTimer = 0; + let wired = false; + + const canvas = () => $("#poster-canvas"); + const tpl = (id = S.template) => TEMPLATES.find((t) => t.id === id) || TEMPLATES[0]; + const font = () => FONTS.find((f) => f.id === S.font) || FONTS[0]; + const fontCss = ([weight, family], size) => `${weight} ${Math.round(size)}px "${family}"`; + const persist = () => prefs.set("poster", S); + const persistLayers = () => prefs.set("posterLayers", layers.map(({ id, kind, nome, src, mode, key, shape, scale, manual, x, y, w }) => ({ id, kind, nome, src, mode, key, shape, scale, manual, x, y, w }))); + const upper = (v) => (S.upper ? v.toLocaleUpperCase("it-IT") : v); + const txt = (id) => upper((S.texts[id] || "").trim()); + const lineup = () => (S.texts.lineup || "").split("\n").map((l) => upper(l.trim())).filter(Boolean); + /** I loghi prendono il posto dei primi nomi della line-up: a testo restano le band senza logo. */ + const rest = (auto) => lineup().slice(auto.length); + + function loadImage(src) { + return new Promise((resolve, reject) => { + const img = new Image(); + img.onload = () => resolve(img); + img.onerror = () => reject(new Error("Immagine non leggibile")); + img.src = src; + }); + } + + function hexRgb(hex) { + const n = parseInt(hex.slice(1), 16); + return [(n >> 16) & 255, (n >> 8) & 255, n & 255]; + } + const isLight = (hex) => { + const [r, g, b] = hexRgb(hex); + return 0.299 * r + 0.587 * g + 0.114 * b > 150; + }; + const onAccent = () => (isLight(S.accent) ? "#0b0b0b" : "#ffffff"); + + function grainPattern(ctx) { + if (!grain) { + const c = document.createElement("canvas"); + c.width = c.height = 256; + const g = c.getContext("2d"); + const d = g.createImageData(256, 256); + for (let i = 0; i < d.data.length; i += 4) { + const v = 128 + (Math.random() - 0.5) * 140; + d.data[i] = d.data[i + 1] = d.data[i + 2] = v; + d.data[i + 3] = 255; + } + g.putImageData(d, 0, 0); + grain = c; + } + return ctx.createPattern(grain, "repeat"); + } + + /* ---------- livelli: loghi e foto ---------- */ + + function alphaBounds(ctx, w, h) { + const px = ctx.getImageData(0, 0, w, h).data; + let x0 = w, y0 = h, x1 = -1, y1 = -1; + for (let y = 0; y < h; y += 2) { + for (let x = 0; x < w; x += 2) { + if (px[(y * w + x) * 4 + 3] > 16) { + if (x < x0) x0 = x; + if (x > x1) x1 = x; + if (y < y0) y0 = y; + if (y > y1) y1 = y; + } + } + } + if (x1 < 0) return null; + const left = Math.max(0, x0 - 2); + const top = Math.max(0, y0 - 2); + return [left, top, Math.min(w, x1 + 4) - left, Math.min(h, y1 + 4) - top]; + } + + function processLayer(layer) { + const src = layer.img; + if (!src) return; + processed.delete(`${layer.id}:ink`); + const max = 1600; + const k = Math.min(1, max / Math.max(src.naturalWidth, src.naturalHeight)); + const w = Math.max(1, Math.round(src.naturalWidth * k)); + const h = Math.max(1, Math.round(src.naturalHeight * k)); + const c = document.createElement("canvas"); + c.width = w; + c.height = h; + const ctx = c.getContext("2d", { willReadFrequently: true }); + ctx.drawImage(src, 0, 0, w, h); + if (layer.key || layer.mode !== "originale") { + const data = ctx.getImageData(0, 0, w, h); + const px = data.data; + const tint = layer.mode === "bianco" ? [255, 255, 255] : layer.mode === "nero" ? [12, 12, 12] : layer.mode === "accento" ? hexRgb(S.accent) : null; + for (let i = 0; i < px.length; i += 4) { + if (layer.key) { + const lum = 0.299 * px[i] + 0.587 * px[i + 1] + 0.114 * px[i + 2]; + px[i + 3] = Math.round(px[i + 3] * Math.max(0, Math.min(1, (250 - lum) / 45))); + } + if (tint) [px[i], px[i + 1], px[i + 2]] = tint; + } + ctx.putImageData(data, 0, 0); + } + let out = c; + if (layer.kind === "logo") { + const b = alphaBounds(ctx, w, h); + if (b) { + out = document.createElement("canvas"); + out.width = b[2]; + out.height = b[3]; + out.getContext("2d").drawImage(c, b[0], b[1], b[2], b[3], 0, 0, b[2], b[3]); + } + } + if (layer.shape === "cerchio") { + const s = Math.min(out.width, out.height); + const sq = document.createElement("canvas"); + sq.width = sq.height = s; + sq.getContext("2d").drawImage(out, (out.width - s) / 2, (out.height - s) / 2, s, s, 0, 0, s, s); + out = sq; + } + processed.set(layer.id, out); + } + + const ratio = (layer) => { + const c = processed.get(layer.id); + return c ? c.height / c.width : 1; + }; + + /** Rettangolo che contiene il livello dentro un box, centrato. */ + function fitBox(layer, cx, cy, maxW, maxH) { + let w = maxW * (layer.scale || 1); + let h = w * ratio(layer); + const lim = maxH * (layer.scale || 1); + if (h > lim) { h = lim; w = h / ratio(layer); } + return { x: cx - w / 2, y: cy - h / 2, w, h }; + } + + /** Mette i loghi in fila con lo stesso peso visivo: conta l'area, non la larghezza, + così un logo lungo e uno tondo sembrano grandi uguali. */ + function logoRow(list, x, y, w, maxH, perRow = 4, align = "center") { + const rows = []; + for (let i = 0; i < list.length; i += perRow) rows.push(list.slice(i, i + perRow)); + const gapX = w * 0.07; + const gapY = maxH * 0.35; + const items = []; + let yy = y; + for (const row of rows) { + const roots = row.map((l) => Math.sqrt(1 / ratio(l))); + const k = Math.min((w - gapX * (row.length - 1)) / roots.reduce((a, b) => a + b, 0), maxH * Math.min(...roots)); + const boxes = row.map((l, i) => { + const sc = l.scale || 1; + return { w: k * roots[i] * sc, h: (k / roots[i]) * sc }; + }); + const rowH = Math.max(...boxes.map((b) => b.h)); + const used = boxes.reduce((s, b) => s + b.w, 0) + gapX * (row.length - 1); + let cx = align === "left" ? x : align === "right" ? x + w - used : x + (w - used) / 2; + boxes.forEach((b, i) => { + items.push([row[i], { x: cx, y: yy + (rowH - b.h) / 2, w: b.w, h: b.h }]); + cx += b.w + gapX; + }); + yy += rowH + gapY; + } + return { items, h: yy - y - gapY }; + } + + /* ---------- testo ---------- */ + + function setFont(ctx, spec, size, track) { + ctx.font = fontCss(spec, size); + const t = track ?? (spec === BODY ? 0.02 : font().track); + if ("letterSpacing" in ctx) ctx.letterSpacing = `${(t * size).toFixed(1)}px`; + } + + function fit(ctx, str, spec, size, maxW, track) { + setFont(ctx, spec, size, track); + const w = ctx.measureText(str).width; + if (w > maxW) { + size *= maxW / w; + setFont(ctx, spec, size, track); + } + return size; + } + + function write(ctx, str, { spec, size, x, y, maxW, align = "center", color = S.textColor, base = "alphabetic", track }) { + if (!str) return 0; + const s = fit(ctx, str, spec, size, maxW, track); + ctx.fillStyle = color; + ctx.textAlign = align; + ctx.textBaseline = base; + ctx.fillText(str, x, y); + return s; + } + + /** Etichetta piccola e spaziata, come nei manifesti tipografici. */ + function label(ctx, str, { x, y, maxW, align = "left", color, size }) { + if (!str) return 0; + ctx.save(); + ctx.globalAlpha = 0.72; + write(ctx, str.toLocaleUpperCase("it-IT"), { spec: BODY, size, x, y, maxW, align, color, base: "alphabetic", track: 0.2 }); + ctx.restore(); + return size; + } + + function rule(ctx, x, y, w, t, color) { + ctx.fillStyle = color; + ctx.fillRect(x, y, w, Math.max(1.5, t)); + } + + /** Riga di informazioni a colonne: etichetta sopra, valore sotto, filetto in testa. */ + function infoGrid(ctx, W, { x, y, w, items, ink, labelInk, valueSize, align = "left" }) { + const cols = items.filter((i) => i.value); + if (!cols.length) return 0; + const ls = W * 0.0165; + const vs = valueSize; + rule(ctx, x, y, w, W * 0.0018, ink); + const cw = w / cols.length; + const size = Math.min(...cols.map((c) => fit(ctx, c.value, font().heavy, vs, cw - W * 0.03))); + cols.forEach((c, i) => { + const cx = align === "center" ? x + cw * i + cw / 2 : x + cw * i; + label(ctx, c.label, { x: cx, y: y + ls * 2.6, maxW: cw - W * 0.02, align, color: labelInk || ink, size: ls }); + write(ctx, c.value, { spec: font().heavy, size, x: cx, y: y + ls * 2.9 + vs * 1.02, maxW: cw - W * 0.03, align, color: ink }); + }); + return ls * 2.9 + vs * 1.2; + } + + const infoItems = (keys = ["data", "ora", "luogo"]) => keys.map((k) => ({ + label: { data: "Data", ora: "Ore", luogo: "Dove", info: "Info" }[k], + value: k === "ora" ? txt("ora").replace(/^ORE\s+|^ore\s+/i, "") : txt(k), + })); + + /** Giorno e mese ricavati dal testo della data («Venerdì 12 dicembre» → 12, DIC, VENERDÌ). */ + function dayParts() { + const raw = (S.texts.data || "").trim(); + const day = raw.match(/\b(\d{1,2})\b/)?.[1] || ""; + const low = raw.toLowerCase(); + const mi = MONTHS.findIndex((m) => low.includes(m)); + const first = raw.split(/\s+/)[0] || ""; + const full = mi >= 0 ? raw.split(/\s+/).find((w) => w.toLowerCase().startsWith(MONTHS[mi])) || MONTHS[mi] : ""; + return { day, month: mi >= 0 ? MONTHS[mi] : "", fullMonth: full, weekday: first && !/\d/.test(first) ? first : "" }; + } + + /* ---------- sfondo e trattamenti ---------- */ + + const treated = new Map(); + + /** L'immagine ritagliata sull'area, con il trattamento scelto: naturale, bianco e nero o duotono. */ + function treatedImage(w, h, mode) { + const key = [S.bg, Math.round(w), Math.round(h), mode, S.accent, S.bgY, S.bgZoom].join("|"); + if (treated.has(key)) return treated.get(key); + const c = document.createElement("canvas"); + c.width = Math.max(1, Math.round(w)); + c.height = Math.max(1, Math.round(h)); + const ctx = c.getContext("2d", { willReadFrequently: mode !== "naturale" }); + const scale = Math.max(c.width / bgImg.naturalWidth, c.height / bgImg.naturalHeight) * S.bgZoom; + const dw = bgImg.naturalWidth * scale; + const dh = bgImg.naturalHeight * scale; + ctx.imageSmoothingQuality = "high"; + ctx.drawImage(bgImg, (c.width - dw) / 2, (c.height - dh) * S.bgY, dw, dh); + if (mode !== "naturale") { + const data = ctx.getImageData(0, 0, c.width, c.height); + const px = data.data; + const [ar, ag, ab] = hexRgb(S.accent); + const dark = [Math.round(ar * 0.08), Math.round(ag * 0.08), Math.round(ab * 0.1)]; + for (let i = 0; i < px.length; i += 4) { + let l = (0.299 * px[i] + 0.587 * px[i + 1] + 0.114 * px[i + 2]) / 255; + l = Math.min(1, Math.max(0, (l - 0.04) * 1.18)); + if (mode === "bn") { + const v = Math.round(Math.pow(l, 1.05) * 255); + px[i] = px[i + 1] = px[i + 2] = v; + } else { + const t = Math.pow(l, 1.15); + px[i] = dark[0] + (ar - dark[0]) * t; + px[i + 1] = dark[1] + (ag - dark[1]) * t; + px[i + 2] = dark[2] + (ab - dark[2]) * t; + } + } + ctx.putImageData(data, 0, 0); + } + treated.set(key, c); + if (treated.size > 14) treated.delete(treated.keys().next().value); + return c; + } + + function cover(ctx, x, y, w, h, mode = S.treatment) { + if (!bgImg) { + const g = ctx.createLinearGradient(x, y, x + w * 0.3, y + h); + const [r, gg, b] = hexRgb(S.accent); + g.addColorStop(0, `rgb(${Math.round(r * 0.3)},${Math.round(gg * 0.3)},${Math.round(b * 0.3)})`); + g.addColorStop(0.55, "#121216"); + g.addColorStop(1, "#08080a"); + ctx.fillStyle = g; + ctx.fillRect(x, y, w, h); + return; + } + const tr = ctx.getTransform(); + const k = Math.hypot(tr.a, tr.b) || 1; + ctx.drawImage(treatedImage(w * k, h * k, mode), x, y, w, h); + } + + function shade(ctx, W, H, stops) { + const a = S.shade; + if (a <= 0) return; + const g = ctx.createLinearGradient(0, 0, 0, H); + for (const [t, v] of stops) g.addColorStop(t, `rgba(6,6,8,${(v * a).toFixed(3)})`); + ctx.fillStyle = g; + ctx.fillRect(0, 0, W, H); + } + + /* ---------- template ---------- */ + + const M = (W) => W * 0.07; + + const RENDER = { + /* Logo o titolo in alto, foto naturale, informazioni a colonne in basso. */ + classica(ctx, W, H, auto) { + cover(ctx, 0, 0, W, H); + shade(ctx, W, H, [[0, 0.75], [0.3, 0.15], [0.55, 0.1], [0.78, 0.7], [1, 0.95]]); + const f = font(); + const s = S.textScale; + const m = M(W); + const place = []; + let y = m * 1.1; + if (auto.length) { + const row = logoRow(auto, m, y, W - m * 2, H * 0.17, 3); + place.push(...row.items); + y += row.h; + } else if (txt("titolo")) { + for (const line of txt("titolo").split(/\s*\|\s*/).filter(Boolean)) { + const size = write(ctx, line, { spec: f.heavy, size: W * 0.16 * s, x: W / 2, y, maxW: W - m * 2, base: "top" }); + y += size * 0.95; + } + } + if (txt("tag")) { + y += W * 0.045; + const ts = W * 0.022 * s; + setFont(ctx, BODY, ts, 0.28); + const tw = Math.min(ctx.measureText(txt("tag")).width, W * 0.6); + write(ctx, txt("tag"), { spec: BODY, size: ts, x: W / 2, y, maxW: W * 0.6, base: "middle", color: S.textColor, track: 0.28 }); + rule(ctx, W / 2 - tw / 2 - W * 0.12, y, W * 0.08, W * 0.002, S.accent); + rule(ctx, W / 2 + tw / 2 + W * 0.04, y, W * 0.08, W * 0.002, S.accent); + } + const bottom = H - m; + if (txt("info")) label(ctx, txt("info"), { x: W / 2, y: bottom, maxW: W - m * 2, align: "center", color: S.textColor, size: W * 0.019 * s }); + const gridY = bottom - W * 0.06 - W * 0.15 * s; + infoGrid(ctx, W, { x: m, y: gridY, w: W - m * 2, items: infoItems(), ink: S.textColor, labelInk: S.accent, valueSize: W * 0.052 * s, align: "center" }); + return place; + }, + + /* Festival: intestazione a filetti, line-up tipografica a scalare, griglia in fondo. */ + lineup(ctx, W, H, auto) { + cover(ctx, 0, 0, W, H); + shade(ctx, W, H, [[0, 0.7], [0.25, 0.35], [0.6, 0.45], [1, 0.9]]); + const f = font(); + const s = S.textScale; + const m = M(W); + const ls = W * 0.0175 * s; + const { day, month, weekday } = dayParts(); + const head = [weekday && weekday.slice(0, 3), day, month].filter(Boolean).join(" "); + label(ctx, head || txt("data"), { x: m, y: m + ls, maxW: W * 0.4, color: S.textColor, size: ls }); + label(ctx, txt("luogo"), { x: W - m, y: m + ls, maxW: W * 0.45, align: "right", color: S.textColor, size: ls }); + rule(ctx, m, m + ls * 2, W - m * 2, W * 0.0018, S.textColor); + let y = m + ls * 2 + W * 0.08; + if (txt("tag")) { + label(ctx, txt("tag"), { x: W / 2, y, maxW: W * 0.7, align: "center", color: S.accent, size: W * 0.024 * s }); + y += W * 0.03; + } + if (txt("titolo")) { + const size = write(ctx, txt("titolo"), { spec: f.heavy, size: W * 0.15 * s, x: W / 2, y, maxW: W - m * 2, base: "top" }); + y += size * 0.95; + } + const gridH = W * 0.15 * s; + const bottom = H - m - (txt("info") ? W * 0.05 : 0); + const gridY = bottom - gridH; + const place = []; + const names = auto.length ? rest(auto) : lineup(); + let blockTop = y + W * 0.06; + const blockBottom = gridY - W * 0.07; + if (auto.length) { + const row = logoRow(auto, m, 0, W - m * 2, Math.min(H * 0.17, (blockBottom - blockTop) * 0.7), auto.length > 4 ? 3 : 4); + const namesH = names.length ? W * 0.09 : 0; + const top = blockTop + Math.max(0, (blockBottom - blockTop - row.h - namesH) / 2); + row.items.forEach(([l, r]) => { r.y += top; }); + place.push(...row.items); + if (names.length) write(ctx, names.join(" • "), { spec: f.heavy, size: W * 0.055 * s, x: W / 2, y: top + row.h + W * 0.085, maxW: W - m * 2 }); + } else if (names.length) { + const first = names[0]; + const others = names.slice(1); + const big = fit(ctx, first, f.heavy, W * 0.17 * s, W - m * 2); + const lines = []; + let cur = []; + for (const n of others) { + const test = [...cur, n].join(" • "); + setFont(ctx, f.heavy, W * 0.07 * s); + if (cur.length && ctx.measureText(test).width > W - m * 2) { lines.push(cur.join(" • ")); cur = [n]; } else cur.push(n); + } + if (cur.length) lines.push(cur.join(" • ")); + const total = big * 0.95 + lines.length * W * 0.085 * s + (lines.length ? W * 0.05 : 0); + let yy = blockTop + Math.max(0, (blockBottom - blockTop - total) / 2); + write(ctx, first, { spec: f.heavy, size: big, x: W / 2, y: yy, maxW: W - m * 2, base: "top" }); + yy += big * 0.95 + W * 0.05; + for (const ln of lines) { + write(ctx, ln, { spec: f.heavy, size: W * 0.07 * s, x: W / 2, y: yy, maxW: W - m * 2, base: "top", color: S.accent }); + yy += W * 0.085 * s; + } + } + infoGrid(ctx, W, { x: m, y: gridY, w: W - m * 2, items: infoItems(), ink: S.textColor, labelInk: S.accent, valueSize: W * 0.05 * s, align: "center" }); + if (txt("info")) label(ctx, txt("info"), { x: W / 2, y: H - m, maxW: W - m * 2, align: "center", color: S.textColor, size: W * 0.019 * s }); + return place; + }, + + /* Svizzero: tutto a sinistra, il protagonista enorme in basso, la data in alto a destra. */ + headliner(ctx, W, H, auto) { + cover(ctx, 0, 0, W, H); + shade(ctx, W, H, [[0, 0.55], [0.3, 0.1], [0.5, 0.25], [0.8, 0.85], [1, 0.95]]); + const f = font(); + const s = S.textScale; + const m = M(W); + const { day, month } = dayParts(); + if (txt("tag")) label(ctx, txt("tag"), { x: m, y: m + W * 0.02, maxW: W * 0.5, color: S.accent, size: W * 0.022 * s }); + if (day) { + const ds = write(ctx, day, { spec: f.heavy, size: W * 0.2, x: W - m, y: m * 0.8, maxW: W * 0.4, align: "right", base: "top" }); + if (month) write(ctx, upper(month), { spec: f.heavy, size: W * 0.07, x: W - m, y: m * 0.8 + ds * 0.92, maxW: W * 0.4, align: "right", base: "top", color: S.accent }); + } + const place = []; + let b = H - m; + if (txt("info")) { label(ctx, txt("info"), { x: m, y: b, maxW: W - m * 2, color: S.textColor, size: W * 0.019 * s }); b -= W * 0.05; } + const gh = W * 0.13 * s; + infoGrid(ctx, W, { x: m, y: b - gh, w: W - m * 2, items: infoItems(["data", "ora", "luogo"]), ink: S.textColor, labelInk: S.accent, valueSize: W * 0.042 * s }); + b -= gh + W * 0.06; + const head = auto[0] || null; + const support = auto.slice(1); + const supportNames = head ? rest(auto) : lineup().slice(1); + if (support.length) { + const row = logoRow(support, m, 0, W * 0.6, H * 0.065, 4, "left"); + row.items.forEach(([, r]) => { r.y += b - row.h; }); + place.push(...row.items); + b -= row.h + W * 0.03; + } + for (const n of [...supportNames].reverse()) { + const sz = write(ctx, n, { spec: f.heavy, size: W * 0.06 * s, x: m, y: b, maxW: W - m * 2, align: "left" }); + b -= sz * 1.1; + } + if (support.length || supportNames.length) { + label(ctx, "con", { x: m, y: b, maxW: W * 0.3, color: S.accent, size: W * 0.02 * s }); + b -= W * 0.06; + } + if (head) { + const r = fitBox(head, 0, 0, W * 0.72, H * 0.24); + r.x = m; + r.y = b - r.h; + place.push([head, r]); + } else if (lineup()[0]) { + const words = lineup()[0].split(/\s+/); + const lines = []; + for (const w of words) { + const test = [lines.at(-1), w].filter(Boolean).join(" "); + setFont(ctx, f.heavy, W * 0.24 * s); + if (lines.length && ctx.measureText(test).width <= W - m * 2) lines[lines.length - 1] = test; else lines.push(w); + } + const size = Math.min(...lines.map((l) => fit(ctx, l, f.heavy, W * 0.24 * s, W - m * 2))); + for (const ln of [...lines].reverse()) { + write(ctx, ln, { spec: f.heavy, size, x: m - W * 0.006, y: b, maxW: W - m * 2, align: "left" }); + b -= size * 0.9; + } + } + return place; + }, + + /* Il giorno enorme che esce dal bordo, il mese in verticale, testi in colonna. */ + data(ctx, W, H, auto) { + cover(ctx, 0, 0, W, H); + shade(ctx, W, H, [[0, 0.35], [0.45, 0.2], [0.7, 0.75], [1, 0.95]]); + const f = font(); + const s = S.textScale; + const m = M(W); + const { day, fullMonth, weekday } = dayParts(); + if (day) { + ctx.save(); + ctx.globalAlpha = 0.96; + write(ctx, day, { spec: f.heavy, size: W * 0.74, x: -W * 0.04, y: W * 0.01, maxW: W * 1.05, align: "left", base: "top", color: S.accent }); + ctx.restore(); + } + if (fullMonth || weekday) { + ctx.save(); + ctx.translate(W - m * 0.62, m); + ctx.rotate(Math.PI / 2); + write(ctx, [weekday, fullMonth].filter(Boolean).join(" · ").toLocaleUpperCase("it-IT"), { spec: f.heavy, size: W * 0.055, x: 0, y: 0, maxW: H * 0.55, align: "left", base: "alphabetic" }); + ctx.restore(); + } + const place = []; + let b = H - m; + if (txt("info")) { label(ctx, txt("info"), { x: m, y: b, maxW: W - m * 2, color: S.textColor, size: W * 0.019 * s }); b -= W * 0.05; } + const gh = W * 0.13 * s; + infoGrid(ctx, W, { x: m, y: b - gh, w: W - m * 2, items: infoItems(["ora", "luogo"]), ink: S.textColor, labelInk: S.accent, valueSize: W * 0.045 * s }); + b -= gh + W * 0.06; + const names = rest(auto); + for (const n of [...names].reverse()) { + const sz = write(ctx, n, { spec: f.heavy, size: W * 0.058 * s, x: m, y: b, maxW: W * 0.62, align: "left" }); + b -= sz * 1.12; + } + if (names.length) b -= W * 0.015; + if (txt("titolo")) { + const sz = write(ctx, txt("titolo"), { spec: f.heavy, size: W * 0.12 * s, x: m - W * 0.005, y: b, maxW: W - m * 2, align: "left" }); + b -= sz * 1.0; + } + if (txt("tag")) { label(ctx, txt("tag"), { x: m, y: b - W * 0.01, maxW: W * 0.6, color: S.accent, size: W * 0.022 * s }); b -= W * 0.06; } + if (auto.length) { + const slot = Math.min(H * 0.085, (b - H * 0.42) / auto.length); + let yy = b - W * 0.04 - slot * auto.length; + for (const l of auto) { + const r = fitBox(l, 0, 0, W * 0.26, slot * 0.8); + r.x = W - m - r.w; + r.y = yy + (slot - r.h) / 2; + place.push([l, r]); + yy += slot; + } + } + return place; + }, + + /* Foto naturale sopra, fascia di colore pieno sotto con testi a sinistra. */ + fascia(ctx, W, H, auto) { + const split = H * 0.6; + cover(ctx, 0, 0, W, split); + ctx.fillStyle = S.accent; + ctx.fillRect(0, split, W, H - split); + const ink = onAccent(); + const f = font(); + const s = S.textScale; + const m = M(W); + const place = []; + if (auto.length) { + const row = logoRow(auto, m, 0, W * 0.5, H * 0.07, 4, "right"); + row.items.forEach(([, r]) => { r.x += W - m * 2 - W * 0.5; r.y += split - m * 0.6 - row.h; }); + place.push(...row.items); + } + if (txt("tag")) { + const ts = W * 0.022 * s; + setFont(ctx, BODY, ts, 0.24); + const tw = Math.min(ctx.measureText(txt("tag")).width, W * 0.6) + ts * 1.6; + ctx.fillStyle = ink; + ctx.fillRect(m, split - ts * 1.25, tw, ts * 2.5); + write(ctx, txt("tag"), { spec: BODY, size: ts, x: m + ts * 0.8, y: split + ts * 0.05, maxW: W * 0.6, align: "left", base: "middle", color: S.accent, track: 0.24 }); + } + let y = split + W * 0.075; + if (txt("titolo")) { + const size = write(ctx, txt("titolo"), { spec: f.heavy, size: W * 0.14 * s, x: m - W * 0.006, y, maxW: W - m * 2, align: "left", base: "top", color: ink }); + y += size * 0.95; + } + const names = rest(auto); + if (names.length) write(ctx, names.join(" / "), { spec: f.heavy, size: W * 0.048 * s, x: m, y: y + W * 0.015, maxW: W - m * 2, align: "left", base: "top", color: ink }); + const gh = W * 0.12 * s; + const gy = H - m - gh - (txt("info") ? W * 0.045 : 0); + infoGrid(ctx, W, { x: m, y: gy, w: W - m * 2, items: infoItems(), ink, valueSize: W * 0.042 * s }); + if (txt("info")) label(ctx, txt("info"), { x: m, y: H - m, maxW: W - m * 2, color: ink, size: W * 0.018 * s }); + return place; + }, + + /* Carta chiara, foto in bianco e nero incorniciata, griglia tipografica. */ + minimal(ctx, W, H, auto) { + const paper = "#f1f0ec"; + const ink = isLight(S.textColor) ? "#141414" : S.textColor; + const mark = isLight(S.accent) && S.accent !== "#ffd600" ? ink : S.accent; + ctx.fillStyle = paper; + ctx.fillRect(0, 0, W, H); + const m = M(W); + const f = font(); + const s = S.textScale; + label(ctx, txt("tag"), { x: m, y: m + W * 0.012, maxW: W * 0.55, color: ink, size: W * 0.018 * s }); + label(ctx, txt("data"), { x: W - m, y: m + W * 0.012, maxW: W * 0.4, align: "right", color: ink, size: W * 0.018 * s }); + const top = m + W * 0.04; + const photoH = H * 0.47; + cover(ctx, m, top, W - m * 2, photoH, S.treatment === "naturale" ? "naturale" : "bn"); + ctx.fillStyle = mark; + ctx.fillRect(m, top + photoH + W * 0.045, W * 0.045, W * 0.045); + let y = top + photoH + W * 0.12; + if (txt("titolo")) { + const size = write(ctx, txt("titolo"), { spec: f.heavy, size: W * 0.13 * s, x: m - W * 0.006, y, maxW: W - m * 2, align: "left", base: "top", color: ink }); + y += size * 1.0; + } + for (const n of rest(auto).slice(0, 4)) { + const size = write(ctx, n, { spec: f.medium, size: W * 0.046 * s, x: m, y, maxW: W - m * 2, align: "left", base: "top", color: ink }); + y += size * 1.18; + } + const gh = W * 0.12 * s; + const gy = H - m - gh - (txt("info") ? W * 0.04 : 0); + infoGrid(ctx, W, { x: m, y: gy, w: W - m * 2, items: infoItems(), ink, valueSize: W * 0.04 * s }); + if (txt("info")) label(ctx, txt("info"), { x: m, y: H - m, maxW: W * 0.6, color: ink, size: W * 0.017 * s }); + if (!auto.length) return []; + const row = logoRow(auto, W * 0.5, 0, W * 0.5 - m, W * 0.11, 4, "right"); + row.items.forEach(([, r]) => { r.y += gy - W * 0.05 - row.h; }); + return row.items; + }, + }; + + /* ---------- disegno ---------- */ + + /** Su fondo chiaro un logo reso bianco sparirebbe: lo disegno color inchiostro. */ + function inked(layer) { + const key = `${layer.id}:ink`; + if (!processed.has(key)) { + const ink = { ...layer, id: key, mode: "nero" }; + processLayer(ink); + } + return processed.get(key); + } + + function drawLayer(ctx, layer, r, W, light) { + const c = light && layer.mode === "bianco" ? inked(layer) : processed.get(layer.id); + if (!c) return; + ctx.save(); + if (layer.kind === "foto") { + ctx.shadowColor = "rgba(0,0,0,0.45)"; + ctx.shadowBlur = W * 0.02; + ctx.shadowOffsetY = W * 0.006; + ctx.beginPath(); + if (layer.shape === "cerchio") ctx.arc(r.x + r.w / 2, r.y + r.h / 2, Math.min(r.w, r.h) / 2, 0, Math.PI * 2); + else if (layer.shape === "arrotondata") ctx.roundRect(r.x, r.y, r.w, r.h, Math.min(r.w, r.h) * 0.06); + else ctx.rect(r.x, r.y, r.w, r.h); + ctx.fillStyle = "#000"; + ctx.fill(); + ctx.shadowColor = "transparent"; + ctx.clip(); + } else if (!light) { + ctx.shadowColor = "rgba(0,0,0,0.45)"; + ctx.shadowBlur = W * 0.012; + ctx.shadowOffsetY = W * 0.004; + } + ctx.drawImage(c, r.x, r.y, r.w, r.h); + ctx.restore(); + } + + function paint(cv, W, H, templateId, main) { + const ctx = cv.getContext("2d"); + ctx.save(); + ctx.clearRect(0, 0, W, H); + const ready = layers.filter((l) => processed.has(l.id)); + const auto = ready.filter((l) => !l.manual); + const fixed = ready.filter((l) => l.manual); + const place = RENDER[templateId](ctx, W, H, auto) || []; + const drawn = new Map(place.map(([l, r]) => [l.id, r])); + for (const l of fixed) { + const w = l.w * W; + const h = w * ratio(l); + drawn.set(l.id, { x: l.x * W - w / 2, y: l.y * H - h / 2, w, h }); + } + for (const l of ready) { + const r = drawn.get(l.id); + if (r) drawLayer(ctx, l, r, W, tpl(templateId).light); + } + if (main && S.grain) { + ctx.globalCompositeOperation = "overlay"; + ctx.globalAlpha = 0.2; + ctx.fillStyle = grainPattern(ctx); + ctx.fillRect(0, 0, W, H); + } + ctx.restore(); + return drawn; + } + + function render() { + pending = 0; + const cv = canvas(); + const [W, H] = FORMATS[S.format] || FORMATS["2:3"]; + if (cv.width !== W || cv.height !== H) { cv.width = W; cv.height = H; } + rects = paint(cv, W, H, S.template, true); + syncOverlay(); + clearTimeout(thumbTimer); + thumbTimer = setTimeout(renderThumbs, 260); + } + + function renderThumbs() { + const [W, H] = FORMATS[S.format] || FORMATS["2:3"]; + const tw = 300; + const th = Math.round((tw * H) / W); + for (const c of document.querySelectorAll("#pp-templates canvas")) { + if (c.width !== tw || c.height !== th) { c.width = tw; c.height = th; } + const ctx = c.getContext("2d"); + ctx.save(); + ctx.scale(tw / W, th / H); + const tmp = { getContext: () => ctx }; + paint(tmp, W, H, c.dataset.tpl, false); + ctx.restore(); + } + } + + function schedule() { + if (pending) return; + pending = requestAnimationFrame(render); + } + + async function ensureFonts() { + const f = font(); + await Promise.all([fontCss(f.heavy, 40), fontCss(f.medium, 40), fontCss(BODY, 40)].map((s) => document.fonts.load(s))).catch(() => {}); + } + + /* ---------- tela interattiva: seleziona, sposta, ridimensiona ---------- */ + + function canvasPoint(e) { + const cv = canvas(); + const r = cv.getBoundingClientRect(); + return [((e.clientX - r.left) / r.width) * cv.width, ((e.clientY - r.top) / r.height) * cv.height]; + } + + function hit(x, y) { + for (const l of [...layers].reverse()) { + const r = rects.get(l.id); + if (r && x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) return l; + } + return null; + } + + function syncOverlay() { + const box = $("#pp-overlay"); + const cv = canvas(); + const wrap = $("#poster-wrap").getBoundingClientRect(); + const cr = cv.getBoundingClientRect(); + box.style.left = `${cr.left - wrap.left}px`; + box.style.top = `${cr.top - wrap.top}px`; + box.style.width = `${cr.width}px`; + box.style.height = `${cr.height}px`; + const k = cr.width / cv.width; + const sel = selected && rects.get(selected.id); + const frame = $("#pp-frame"); + frame.hidden = !sel; + if (sel) { + frame.style.left = `${sel.x * k}px`; + frame.style.top = `${sel.y * k}px`; + frame.style.width = `${sel.w * k}px`; + frame.style.height = `${sel.h * k}px`; + } + } + + function select(layer) { + selected = layer; + renderLayerList(); + syncOverlay(); + } + + function pinLayer(layer) { + if (layer.manual) return; + const r = rects.get(layer.id); + const [W, H] = FORMATS[S.format]; + if (!r) return; + Object.assign(layer, { manual: true, x: (r.x + r.w / 2) / W, y: (r.y + r.h / 2) / H, w: r.w / W }); + } + + function wireCanvas() { + const wrap = $("#poster-wrap"); + let drag = null; + wrap.addEventListener("pointerdown", (e) => { + const [x, y] = canvasPoint(e); + const onHandle = e.target.closest(".pp-handle"); + const layer = onHandle ? selected : hit(x, y); + if (!layer) { if (selected) select(null); return; } + if (layer !== selected) select(layer); + pinLayer(layer); + const [W, H] = FORMATS[S.format]; + drag = { layer, resize: Boolean(onHandle), x0: x, y0: y, lx: layer.x, ly: layer.y, lw: layer.w, W, H }; + wrap.setPointerCapture(e.pointerId); + wrap.classList.add("dragging"); + e.preventDefault(); + }); + wrap.addEventListener("pointermove", (e) => { + if (!drag) { + const [x, y] = canvasPoint(e); + wrap.classList.toggle("can-move", Boolean(hit(x, y))); + return; + } + const [x, y] = canvasPoint(e); + const { layer, W, H } = drag; + if (drag.resize) { + const cx = drag.lx * W; + layer.w = Math.max(0.05, Math.min(1.4, (Math.abs(x - cx) * 2) / W)); + } else { + layer.x = Math.max(0, Math.min(1, drag.lx + (x - drag.x0) / W)); + layer.y = Math.max(0, Math.min(1, drag.ly + (y - drag.y0) / H)); + } + schedule(); + }); + const end = () => { + if (!drag) return; + drag = null; + wrap.classList.remove("dragging"); + persistLayers(); + renderLayerList(); + }; + wrap.addEventListener("pointerup", end); + wrap.addEventListener("pointercancel", end); + window.addEventListener("resize", () => syncOverlay()); + document.addEventListener("keydown", (e) => { + if ($("#poster").hidden || !selected || e.target.closest("input, textarea, [contenteditable]") || document.querySelector("dialog[open]:not(#guide)")) return; + const step = e.shiftKey ? 0.02 : 0.004; + const moves = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }; + if (moves[e.key]) { + pinLayer(selected); + selected.x += moves[e.key][0]; + selected.y += moves[e.key][1]; + persistLayers(); + schedule(); + e.preventDefault(); + } else if (e.key === "Delete" || e.key === "Backspace") { + removeLayer(selected); + e.preventDefault(); + } else if (e.key === "Escape") { + select(null); + } + }); + } + + /* ---------- gestione dei livelli ---------- */ + + const newId = () => `l${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`; + + function hasLightBackground(img) { + const c = document.createElement("canvas"); + c.width = c.height = 32; + const ctx = c.getContext("2d", { willReadFrequently: true }); + ctx.drawImage(img, 0, 0, 32, 32); + const px = ctx.getImageData(0, 0, 32, 32).data; + return [[0, 0], [31, 0], [0, 31], [31, 31]].every(([x, y]) => { + const i = (y * 32 + x) * 4; + return px[i + 3] > 245 && 0.299 * px[i] + 0.587 * px[i + 1] + 0.114 * px[i + 2] > 225; + }); + } + + /** Riduce l'immagine prima di tenerla in memoria: un logo non serve oltre i 1600 px. */ + async function compact(src) { + const img = await loadImage(src); + const k = Math.min(1, 1600 / Math.max(img.naturalWidth, img.naturalHeight)); + if (k === 1 && String(src).length < 1_400_000) return { img, src }; + const c = document.createElement("canvas"); + c.width = Math.round(img.naturalWidth * k); + c.height = Math.round(img.naturalHeight * k); + c.getContext("2d").drawImage(img, 0, 0, c.width, c.height); + const out = c.toDataURL("image/png"); + return { img: await loadImage(out), src: out }; + } + + async function addLayer(kind, src, nome) { + let res; + try { res = await compact(src); } catch { toast("Questa immagine non si apre"); return; } + const layer = { + id: newId(), kind, nome: nome || (kind === "logo" ? "Logo" : "Foto"), + src: res.src, img: res.img, + mode: "originale", key: kind === "logo" && hasLightBackground(res.img), + shape: kind === "foto" ? "arrotondata" : "libera", + scale: 1, manual: false, x: 0.5, y: 0.5, w: 0.4, + }; + processLayer(layer); + layers.push(layer); + persistLayers(); + select(layer); + schedule(); + } + + async function addFromFile(kind, file) { + if (!file) return; + const url = await new Promise((resolve) => { + const r = new FileReader(); + r.onload = () => resolve(r.result); + r.readAsDataURL(file); + }); + await addLayer(kind, url, file.name.replace(/\.[a-z0-9]+$/i, "")); + } + + function removeLayer(layer) { + layers = layers.filter((l) => l !== layer); + processed.delete(layer.id); + if (selected === layer) selected = null; + persistLayers(); + renderLayerList(); + schedule(); + } + + function moveLayer(layer, delta) { + const i = layers.indexOf(layer); + const j = i + delta; + if (j < 0 || j >= layers.length) return; + [layers[i], layers[j]] = [layers[j], layers[i]]; + persistLayers(); + renderLayerList(); + schedule(); + } + + function renderLayerList() { + const list = $("#pp-layer-list"); + list.replaceChildren(...layers.map((l) => { + const thumb = el("img", { src: l.src, alt: "" }); + const row = el("button", { + type: "button", + class: "pp-layer", + "aria-pressed": String(l === selected), + onclick: () => select(l === selected ? null : l), + }, [thumb, el("span", { text: l.nome }), el("small", { text: l.manual ? "a mano" : "automatico" })]); + return row; + })); + $("#pp-layers-empty").hidden = layers.length > 0; + const opts = $("#pp-layer-opts"); + opts.hidden = !selected; + if (!selected) return; + radio($("#pp-layer-color"), "v", selected.mode); + radio($("#pp-layer-shape"), "v", selected.shape); + $("#pp-layer-key").checked = selected.key; + $("#pp-layer-shape").hidden = selected.kind !== "foto"; + $("#pp-layer-size").value = String(selected.manual ? selected.w / 0.4 : selected.scale); + $("#pp-layer-reset").hidden = !selected.manual; + } + + function relayer() { + if (!selected) return; + processLayer(selected); + persistLayers(); + renderLayerList(); + schedule(); + } + + /* ---------- sfondo ---------- */ + + async function setBackground(path) { + try { + bgImg = await loadImage(mediaUrl(path)); + S.bg = path; + S.bgY = 0.5; + S.bgZoom = 1; + $("#pp-bg-y").value = "0.5"; + $("#pp-bg-zoom").value = "1"; + $("#pp-bg-label").textContent = "Cambia immagine"; + persist(); + schedule(); + } catch { + toast("Non riesco ad aprire quell'immagine"); + } + } + + let pickerScope = "galleria"; + let pickerTarget = "sfondo"; + + async function openPicker(target = "sfondo") { + pickerTarget = target; + $("#picker-title").textContent = target === "sfondo" ? "Scegli l'immagine di sfondo" : "Aggiungi una foto"; + const dlg = $("#picker"); + if (!dlg.open) dlg.showModal(); + await fillPicker(); + } + + function pick(path, nome) { + $("#picker").close(); + if (pickerTarget === "sfondo") setBackground(path); + else addLayer("foto", mediaUrl(path), nome); + } + + async function fillPicker() { + const grid = $("#picker-grid"); + grid.replaceChildren(el("p", { class: "picker-empty", text: "Carico…" })); + radio($("#picker-scope"), "v", pickerScope); + const { immagini } = await api(`/api/history?limit=120&vista=${pickerScope}`); + const items = immagini.filter((i) => i.modalita !== "locandina"); + grid.replaceChildren(); + if (!items.length) { + grid.append(el("p", { class: "picker-empty", text: pickerScope === "bozze" ? "Nessuna bozza." : "La galleria è vuota: genera o carica un'immagine." })); + return; + } + for (const item of items) { + grid.append(el("button", { + type: "button", + class: "picker-item", + title: item.titolo || item.prompt || "", + onclick: () => pick("outputs/" + item.file, item.titolo || "Foto"), + }, [el("img", { src: outputUrl(item.miniatura || item.file), alt: "", loading: "lazy" })])); + } + } + + async function uploadPicked(file) { + if (!file) return; + if (pickerTarget !== "sfondo") { + $("#picker").close(); + addFromFile("foto", file); + return; + } + try { + const info = await api("/api/upload", file, { "Content-Type": file.type || "application/octet-stream", "X-Filename": encodeURIComponent(file.name || "sfondo") }); + $("#picker").close(); + setBackground(info.file); + } catch (e) { + toast(e.message); + } + } + + /* ---------- esporta ---------- */ + + async function blob() { + const keep = selected; + selected = null; + render(); + selected = keep; + return new Promise((r) => canvas().toBlob(r, "image/png")); + } + + function posterTitle() { + return S.texts.titolo || lineup()[0] || [S.texts.tag, S.texts.data].filter(Boolean).join(" · ") || "Locandina"; + } + + async function save() { + const btn = $("#pp-save"); + btn.disabled = true; + try { + const data = await blob(); + const meta = encodeURIComponent(JSON.stringify({ titolo: posterTitle(), sfondo: S.bg, formato: S.format })); + await api("/api/poster", data, { "Content-Type": "image/png", "X-Meta": meta }); + toast("Locandina salvata in galleria", { label: "Apri galleria", run: () => window.PixRick.setView("galleria") }); + } catch (e) { + toast(e.message); + } finally { + btn.disabled = false; + } + } + + async function download(e) { + e.preventDefault(); + const data = await blob(); + const url = URL.createObjectURL(data); + const a = el("a", { href: url, download: `locandina-${posterTitle().toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 40)}.png` }); + document.body.append(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 4000); + } + + /* ---------- pannello ---------- */ + + function swatches(box, colors, key) { + box.replaceChildren(); + const custom = el("input", { type: "color", class: "swatch-custom", "aria-label": "Altro colore", value: S[key] }); + for (const c of colors) { + const b = el("button", { type: "button", class: "swatch", role: "radio", "aria-checked": String(S[key] === c), "aria-label": c, data: { v: c } }); + b.style.setProperty("--c", c); + b.addEventListener("click", () => { S[key] = c; radio(box, "v", c); custom.value = c; colorChanged(key); }); + box.append(b); + } + custom.addEventListener("input", () => { S[key] = custom.value; radio(box, "v", custom.value); colorChanged(key); }); + box.append(custom); + } + + function colorChanged(key) { + if (key === "accent") layers.filter((l) => l.mode === "accento").forEach(processLayer); + changed(); + } + + function changed() { + persist(); + schedule(); + } + + function syncFields() { + const t = tpl(); + for (const id of FIELDS) $(`#pp-f-${id}`).hidden = !t.fields.includes(id); + $("#pp-shade-row").hidden = !t.bleed; + radio($("#pp-templates"), "v", t.id); + $("#pp-template-desc").textContent = t.desc; + } + + function buildPanel() { + const tpls = $("#pp-templates"); + tpls.replaceChildren(...TEMPLATES.map((t) => el("button", { + type: "button", class: "pp-tpl", role: "radio", "aria-checked": String(S.template === t.id), data: { v: t.id }, title: t.desc, + onclick: async () => { + S.template = t.id; + S.font = t.font; + S.treatment = t.treatment; + radio($("#pp-fonts"), "v", S.font); + radio($("#pp-treatment"), "v", S.treatment); + syncFields(); + await ensureFonts(); + changed(); + }, + }, [el("canvas", { data: { tpl: t.id } }), el("span", { text: t.nome })]))); + const fonts = $("#pp-fonts"); + fonts.replaceChildren(...FONTS.map((f) => { + const b = el("button", { type: "button", class: "font-opt", role: "radio", "aria-checked": String(S.font === f.id), data: { v: f.id }, text: f.nome }); + b.style.fontFamily = `"${f.heavy[1]}"`; + b.style.fontWeight = String(f.heavy[0]); + b.addEventListener("click", async () => { S.font = f.id; radio(fonts, "v", f.id); await ensureFonts(); changed(); }); + return b; + })); + const formats = $("#pp-format"); + formats.replaceChildren(...Object.keys(FORMATS).map((k) => el("button", { + type: "button", role: "radio", "aria-checked": String(S.format === k), data: { v: k }, text: k, + title: `${FORMATS[k][0]}×${FORMATS[k][1]}`, + onclick: () => { S.format = k; radio(formats, "v", k); changed(); }, + }))); + swatches($("#pp-text-colors"), TEXT_COLORS, "textColor"); + swatches($("#pp-accent-colors"), ACCENT_COLORS, "accent"); + syncFields(); + } + + function syncInputs() { + for (const id of FIELDS) $(`#pp-${id}`).value = S.texts[id] || ""; + $("#pp-upper").checked = S.upper; + $("#pp-bg-y").value = String(S.bgY); + $("#pp-bg-zoom").value = String(S.bgZoom); + $("#pp-text-scale").value = String(S.textScale); + $("#pp-shade").value = String(S.shade); + $("#pp-grain").checked = S.grain; + radio($("#pp-treatment"), "v", S.treatment); + } + + function wire() { + if (wired) return; + wired = true; + buildPanel(); + syncInputs(); + for (const id of FIELDS) $(`#pp-${id}`).addEventListener("input", (e) => { S.texts[id] = e.target.value; changed(); }); + const num = (id, key) => $(id).addEventListener("input", (e) => { S[key] = Number(e.target.value); changed(); }); + num("#pp-bg-y", "bgY"); + num("#pp-bg-zoom", "bgZoom"); + num("#pp-text-scale", "textScale"); + num("#pp-shade", "shade"); + $("#pp-upper").addEventListener("change", (e) => { S.upper = e.target.checked; changed(); }); + $("#pp-treatment").addEventListener("click", (e) => { + const b = e.target.closest("[data-v]"); + if (!b) return; + S.treatment = b.dataset.v; + radio($("#pp-treatment"), "v", S.treatment); + changed(); + }); + $("#pp-grain").addEventListener("change", (e) => { S.grain = e.target.checked; changed(); }); + $("#pp-clear-texts").addEventListener("click", () => { + for (const id of FIELDS) S.texts[id] = ""; + syncInputs(); + changed(); + }); + + $("#pp-add-logo").addEventListener("change", async (e) => { + const files = [...e.target.files]; + e.target.value = ""; + for (const f of files) await addFromFile("logo", f); + }); + $("#pp-add-photo").addEventListener("click", () => openPicker("livello")); + $("#pp-layer-color").addEventListener("click", (e) => { + const b = e.target.closest("[data-v]"); + if (!b || !selected) return; + selected.mode = b.dataset.v; + relayer(); + }); + $("#pp-layer-shape").addEventListener("click", (e) => { + const b = e.target.closest("[data-v]"); + if (!b || !selected) return; + selected.shape = b.dataset.v; + relayer(); + }); + $("#pp-layer-key").addEventListener("change", (e) => { if (selected) { selected.key = e.target.checked; relayer(); } }); + $("#pp-layer-size").addEventListener("input", (e) => { + if (!selected) return; + const v = Number(e.target.value); + if (selected.manual) selected.w = 0.4 * v; else selected.scale = v; + persistLayers(); + schedule(); + }); + $("#pp-layer-reset").addEventListener("click", () => { if (selected) { selected.manual = false; selected.scale = 1; relayer(); } }); + $("#pp-layer-up").addEventListener("click", () => selected && moveLayer(selected, 1)); + $("#pp-layer-down").addEventListener("click", () => selected && moveLayer(selected, -1)); + $("#pp-layer-remove").addEventListener("click", () => selected && removeLayer(selected)); + + $("#poster-pick").addEventListener("click", () => openPicker("sfondo")); + $("#pp-bg-remove").addEventListener("click", () => { bgImg = null; S.bg = null; $("#pp-bg-label").textContent = "Scegli immagine"; changed(); }); + $("#picker-close").addEventListener("click", () => $("#picker").close()); + $("#picker").addEventListener("click", (e) => { if (e.target === $("#picker")) $("#picker").close(); }); + $("#picker-scope").addEventListener("click", (e) => { + const b = e.target.closest("[data-v]"); + if (!b) return; + pickerScope = b.dataset.v; + fillPicker(); + }); + $("#picker-file").addEventListener("change", (e) => { uploadPicked(e.target.files[0]); e.target.value = ""; }); + $("#pp-save").addEventListener("click", save); + $("#pp-download").addEventListener("click", download); + const stage = $("#poster-stage"); + stage.addEventListener("dragover", (e) => e.preventDefault()); + stage.addEventListener("drop", (e) => { + const files = [...(e.dataTransfer?.files || [])].filter((f) => f.type.startsWith("image/")); + if (!files.length) return; + e.preventDefault(); + (async () => { for (const f of files) await addFromFile("logo", f); })(); + }); + wireCanvas(); + new ResizeObserver(() => syncOverlay()).observe($("#poster-wrap")); + } + + async function restore() { + if (!layers.length) { + const saved = prefs.get("posterLayers", null); + const legacy = prefs.get("posterLogo", null); + const list = saved || (legacy ? [{ id: newId(), kind: "logo", nome: "Logo", src: legacy, mode: "originale", key: true, shape: "libera", scale: 1, manual: false, x: 0.5, y: 0.5, w: 0.4 }] : []); + for (const l of list) { + try { + l.img = await loadImage(l.src); + processLayer(l); + layers.push(l); + } catch { /* livello illeggibile: lo salto */ } + } + if (legacy) prefs.set("posterLogo", null); + persistLayers(); + renderLayerList(); + } + if (S.bg && !bgImg) { + try { + bgImg = await loadImage(mediaUrl(S.bg)); + $("#pp-bg-label").textContent = "Cambia immagine"; + } catch { S.bg = null; } + } + } + + window.PosterStudio = { + async show() { + wire(); + await Promise.all([ensureFonts(), restore()]); + render(); + }, + async setBackground(path) { + wire(); + await Promise.all([ensureFonts(), restore()]); + await setBackground(path); + }, + }; +})(); diff --git a/web/style.css b/web/style.css new file mode 100644 index 0000000000000000000000000000000000000000..613004989ba224836f41a03a0c3dcaa2324d5ca2 --- /dev/null +++ b/web/style.css @@ -0,0 +1,1689 @@ +/* PixRick — studio scuro, l'immagine al centro, il colore solo dove conta */ + +:root { + --bg: #141519; + --bg-raised: #191a1f; + --surface: #1f2026; + --surface-2: #272930; + --line: rgba(255, 255, 255, 0.07); + --line-strong: rgba(255, 255, 255, 0.13); + --text: #ececef; + --muted: #9c9ea9; + --faint: #6c6f7a; + --accent: #cbbcff; + --accent-soft: rgba(203, 188, 255, 0.12); + --danger: #ff8f8f; + --ok: #7fd8a6; + --pearl: linear-gradient(115deg, #c9b8ff 0%, #ffc9a8 55%, #9fe3da 100%); + + --sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Inter", system-ui, sans-serif; + --serif: ui-serif, "New York", "Iowan Old Style", "Palatino", Georgia, serif; + + --r-lg: 18px; + --r-md: 12px; + --r-sm: 8px; + --topbar: 56px; + --inspector: 320px; + --ease: cubic-bezier(0.2, 0.7, 0.2, 1); +} + +* { box-sizing: border-box; } +[hidden] { display: none !important; } +html, body { margin: 0; height: 100%; } + +body { + font-family: var(--sans); + font-size: 14px; + line-height: 1.45; + color: var(--text); + background: var(--bg); + -webkit-font-smoothing: antialiased; + overflow: hidden; +} + +button, input, textarea, select { font: inherit; color: inherit; } +button { cursor: pointer; } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 6px; } +svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; flex: none; } +.sprite { display: none; } + +kbd { + font-family: var(--sans); + font-size: 11px; + padding: 1px 6px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.18); +} + +/* ---------- barra in alto ---------- */ + +.topbar { + height: var(--topbar); + display: grid; + grid-template-columns: 1fr auto 1fr; + align-items: center; + padding: 0 18px; + border-bottom: 1px solid var(--line); + background: var(--bg-raised); +} +.brand { display: flex; align-items: center; gap: 10px; } +.brand-mark { width: 26px; height: 26px; } +.brand-name { font-family: var(--serif); font-size: 19px; letter-spacing: 0.005em; } + +.views { + display: flex; + padding: 3px; + border-radius: 10px; + background: var(--surface); + border: 1px solid var(--line); +} +.views button { + border: 0; + background: transparent; + padding: 6px 16px; + border-radius: 7px; + color: var(--muted); + font-weight: 500; + transition: background 0.15s, color 0.15s; +} +.views button[aria-pressed="true"] { background: var(--surface-2); color: var(--text); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); } +.views .count { color: var(--faint); font-variant-numeric: tabular-nums; margin-left: 2px; } + +.top-status { display: flex; align-items: center; gap: 14px; justify-content: flex-end; color: var(--muted); font-size: 13px; } +.top-status { position: relative; } +.lang-btn { + height: 32px; + min-width: 36px; + padding: 0 8px; + border: 1px solid var(--line); + border-radius: 9px; + background: transparent; + color: var(--muted); + font-size: 12px; + font-weight: 600; + letter-spacing: 0.04em; +} +.lang-btn:hover { color: var(--text); border-color: var(--line-strong); } +.account { + display: inline-flex; + align-items: center; + gap: 8px; + height: 32px; + max-width: 180px; + padding: 0 12px 0 10px; + border: 1px solid var(--line-strong); + border-radius: 999px; + background: var(--surface); + color: var(--text); + font-size: 13px; +} +.account span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.account-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--faint); flex: none; } +.account[data-state="dentro"] .account-dot { background: var(--ok); box-shadow: 0 0 0 3px rgba(127, 216, 166, 0.15); } +.account-menu { + position: absolute; + top: calc(100% + 8px); + right: 0; + z-index: 30; + display: grid; + gap: 6px; + width: 270px; + padding: 14px; + border: 1px solid var(--line-strong); + border-radius: 14px; + background: var(--bg-raised); + box-shadow: 0 30px 80px -24px rgba(0, 0, 0, 0.9); + animation: rise 0.16s var(--ease); +} +.account-head { margin: 0; color: var(--text); font-size: 13.5px; font-weight: 500; overflow-wrap: anywhere; } +.account-note { margin: 0 0 6px; color: var(--muted); font-size: 12.5px; } +.account-menu hr { width: 100%; margin: 6px 0 2px; border: 0; border-top: 1px solid var(--line); } +.menu-link { + display: block; + padding: 7px 8px; + border: 0; + border-radius: 8px; + background: transparent; + color: var(--muted); + font-size: 13px; + text-align: left; + text-decoration: none; +} +.menu-link:hover { background: var(--surface); color: var(--text); } +@keyframes pulse { 50% { opacity: 0.35; } } + +.icon-btn { + display: grid; + place-items: center; + width: 32px; + height: 32px; + border: 1px solid var(--line); + border-radius: var(--r-sm); + background: transparent; + color: var(--muted); + transition: background 0.15s, color 0.15s, border-color 0.15s; +} +.icon-btn:hover { background: var(--surface); color: var(--text); border-color: var(--line-strong); } + +.ghost { + border: 1px solid var(--line-strong); + background: transparent; + border-radius: var(--r-sm); + padding: 8px 16px; + color: var(--text); +} +.ghost:hover { background: var(--surface); } + +/* ---------- studio ---------- */ + +.studio { + display: grid; + grid-template-columns: minmax(0, 1fr) var(--inspector); + height: calc(100vh - var(--topbar)); +} + +.workspace { + display: flex; + flex-direction: column; + gap: 12px; + min-width: 0; + min-height: 0; + padding: 18px 22px 14px; +} + +.stage { + position: relative; + flex: 1; + min-height: 0; + display: grid; + grid-template: minmax(0, 1fr) / minmax(0, 1fr); + place-items: center; + border-radius: var(--r-lg); + background: + radial-gradient(60% 70% at 50% 45%, rgba(203, 188, 255, 0.05), transparent 70%), + var(--bg-raised); + border: 1px solid var(--line); + overflow: hidden; + transition: border-color 0.2s; + container-type: size; +} +.stage > * { grid-area: 1 / 1; } + +.empty { max-width: 460px; text-align: center; padding: 24px; } +.empty h1 { + margin: 0 0 10px; + font-family: var(--serif); + font-weight: 400; + font-size: clamp(30px, 3.4vw, 44px); + line-height: 1.1; + letter-spacing: -0.01em; +} +.empty p { margin: 0; color: var(--muted); font-size: 15px; } + +.shot { margin: 0; width: 100%; height: 100%; min-height: 0; padding: 18px; display: none; place-items: center; grid-template: minmax(0, 1fr) / minmax(0, 1fr); } +.shot img { + max-width: 100%; + max-height: 100%; + object-fit: contain; + border-radius: 10px; + box-shadow: 0 30px 60px -30px rgba(0, 0, 0, 0.8), 0 0 0 1px rgba(255, 255, 255, 0.04); +} +.shot img.fresh { animation: reveal 1.5s var(--ease) both; } +@keyframes reveal { + 0% { filter: blur(22px) saturate(0) brightness(1.25); opacity: 0.35; } + 55% { filter: blur(4px) saturate(0.7) brightness(1.06); opacity: 1; } + 100% { filter: none; } +} + +/* sviluppo: la cornice dell'immagine che sta nascendo */ +.develop { display: none; place-items: center; align-content: center; gap: 18px; width: 100%; height: 100%; padding: 22px; position: relative; z-index: 2; } +.develop-frame { + --ar: 1; + position: relative; + width: min(86cqw, 68cqh * var(--ar)); + aspect-ratio: var(--ar); + border-radius: 12px; + overflow: hidden; + background: #16171c; + box-shadow: 0 30px 70px -36px rgba(0, 0, 0, 0.9), inset 0 0 0 1px rgba(255, 255, 255, 0.05); +} +.develop-glow { + position: absolute; + inset: -30%; + background: + radial-gradient(38% 34% at 30% 35%, rgba(201, 184, 255, 0.34), transparent 70%), + radial-gradient(34% 30% at 70% 62%, rgba(255, 201, 168, 0.26), transparent 70%), + radial-gradient(30% 28% at 52% 80%, rgba(159, 227, 218, 0.2), transparent 70%); + filter: blur(26px); + animation: drift 7s ease-in-out infinite alternate; +} +.develop-frame[data-phase="in_coda"] .develop-glow, .develop-frame[data-phase="caricamento"] .develop-glow { opacity: 0.45; } +.develop-grain { + position: absolute; + inset: 0; + opacity: 0.09; + mix-blend-mode: overlay; + background-size: 160px 160px; + animation: grain 0.9s steps(5) infinite; +} +.develop-bar { position: absolute; left: 0; right: 0; bottom: 0; height: 3px; background: rgba(255, 255, 255, 0.06); } +.develop-bar i { display: block; height: 100%; background: var(--pearl); transform-origin: left; transform: scaleX(0); transition: transform 0.6s var(--ease); } +.develop-caption { text-align: center; } +.develop-title { margin: 0; font-family: var(--serif); font-size: 20px; } +.develop-sub { margin: 4px 0 0; color: var(--muted); font-size: 13px; font-variant-numeric: tabular-nums; } +@keyframes drift { + 0% { transform: translate(-4%, -3%) rotate(0deg) scale(1); } + 100% { transform: translate(5%, 4%) rotate(14deg) scale(1.12); } +} +@keyframes grain { + 0% { background-position: 0 0; } + 20% { background-position: -40px 30px; } + 40% { background-position: 50px -20px; } + 60% { background-position: -20px -50px; } + 80% { background-position: 30px 60px; } +} + +.compare { + display: none; + width: 100%; + height: 100%; + min-height: 0; + padding: 18px; + gap: 16px; + grid-auto-flow: column; + grid-auto-columns: minmax(0, 1fr); +} +.stage[data-state="confronto"] .compare { display: grid; } +.compare[data-rows="2"] { grid-auto-flow: row; grid-template-columns: repeat(var(--cols), minmax(0, 1fr)); grid-template-rows: repeat(2, minmax(0, 1fr)); gap: 12px 14px; padding: 14px; } +.compare[data-rows="2"] .card-foot { gap: 6px; } +.compare[data-rows="2"] .card-media { width: 100%; height: 100%; overflow: hidden; } +.compare[data-rows="2"] .card-media img { width: 100%; height: 100%; object-fit: contain; box-shadow: none; filter: drop-shadow(0 14px 22px rgba(0, 0, 0, 0.55)); } +.compare[data-rows="2"] .card-name small { display: none; } +.compare[data-rows="2"] .save-btn { height: 28px; padding: 0 10px 0 8px; font-size: 12px; } +.card { + display: grid; + grid-template-rows: minmax(0, 1fr) auto; + gap: 10px; + min-height: 0; +} +.card-media { + min-height: 0; + display: grid; + place-items: center; + border: 0; + padding: 0; + background: transparent; + cursor: zoom-in; +} +.card-media img { + max-width: 100%; + max-height: 100%; + object-fit: contain; + border-radius: 10px; + box-shadow: 0 24px 50px -28px rgba(0, 0, 0, 0.8), 0 0 0 1px rgba(255, 255, 255, 0.04); +} +.card-media img.fresh { animation: reveal 1.5s var(--ease) both; } +.card-foot { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 0 2px; } +.card-name { font-weight: 500; font-size: 13.5px; } +.card-name small { display: block; color: var(--faint); font-weight: 400; font-size: 12px; font-variant-numeric: tabular-nums; } + +.save-btn { + display: inline-flex; + align-items: center; + gap: 7px; + height: 32px; + padding: 0 14px 0 11px; + border: 0; + border-radius: var(--r-sm); + background: var(--pearl); + color: #17141f; + font-weight: 600; + font-size: 13px; + white-space: nowrap; + transition: transform 0.08s, opacity 0.15s; +} +.save-btn svg { width: 16px; height: 16px; stroke-width: 2.2; } +.save-btn:active { transform: scale(0.97); } +.save-btn[data-saved="true"] { background: transparent; color: var(--ok); box-shadow: inset 0 0 0 1px rgba(127, 216, 166, 0.35); pointer-events: none; } + +.shot-actions.compare-actions { display: none; } +.compare-hint { color: var(--faint); font-size: 12.5px; margin-right: 6px; } +body[data-stage="confronto"] .shot-actions.compare-actions { display: flex; } +body[data-stage="confronto"] .shot-actions.single-actions { display: none; } +.back { color: var(--text); } + +.stage[data-state="vuoto"] .empty { display: block; } +.stage:not([data-state="vuoto"]) .empty { display: none; } +.stage[data-state="foto"] .shot { display: grid; } +.stage[data-state="lavoro"] .develop { display: grid; } +.stage[data-state="base"] .base { display: grid; } + +.drop-hint { + display: none; + flex-direction: column; + align-items: center; + gap: 10px; + color: var(--accent); + font-size: 15px; + z-index: 3; +} +.drop-hint svg { width: 34px; height: 34px; } +.stage.dragging { border-color: var(--accent); background: var(--accent-soft); } +.stage.dragging > :not(.drop-hint) { opacity: 0.15; } +.stage.dragging .drop-hint { display: flex; } + +/* barra dello scatto */ + +.shot-bar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 16px; + min-height: 40px; +} +.shot-caption { min-width: 220px; flex: 1 1 260px; } +.shot-bar .shot-meta { flex-wrap: nowrap; overflow: hidden; white-space: nowrap; } +.shot-bar .shot-meta span { flex: none; } +.shot-bar .shot-meta span:last-child { flex: 0 1 auto; overflow: hidden; text-overflow: ellipsis; } +.shot-prompt { margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.shot-meta, .tile-meta { display: flex; flex-wrap: wrap; gap: 2px 12px; margin: 2px 0 0; color: var(--faint); font-size: 12.5px; font-variant-numeric: tabular-nums; } +.shot-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: 4px; flex: 0 1 auto; margin-left: auto; } +.act { + display: inline-flex; + align-items: center; + gap: 6px; + height: 32px; + padding: 0 11px; + border: 0; + border-radius: var(--r-sm); + background: transparent; + color: var(--muted); + font-size: 13px; + text-decoration: none; + transition: background 0.15s, color 0.15s; +} +.act svg { width: 16px; height: 16px; } +.act:hover { background: var(--surface); color: var(--text); } +.act.icon-only { width: 32px; padding: 0; justify-content: center; } +.act.danger:hover { color: var(--danger); } +.act[disabled] { opacity: 0.35; pointer-events: none; } +.act.views-btn { color: var(--accent); box-shadow: inset 0 0 0 1px rgba(203, 188, 255, 0.35); } +.act.views-btn:hover { background: var(--accent-soft); color: var(--accent); } +.act-sep { width: 1px; height: 18px; background: var(--line-strong); margin: 0 4px; } + +/* composer */ + +.composer { + border: 1px solid var(--line-strong); + border-radius: var(--r-lg); + background: var(--surface); + padding: 10px 12px 10px; + box-shadow: 0 20px 40px -24px rgba(0, 0, 0, 0.7); + transition: border-color 0.15s; +} +.composer:focus-within { border-color: rgba(203, 188, 255, 0.35); } + +.composer-top { display: flex; align-items: center; gap: 14px; margin-bottom: 6px; min-width: 0; } +.modes { display: flex; gap: 2px; padding: 3px; border-radius: 10px; background: var(--bg-raised); border: 1px solid var(--line); flex: none; } +.modes button { + display: inline-flex; + align-items: center; + gap: 7px; + border: 0; + background: transparent; + padding: 5px 12px 5px 10px; + border-radius: 7px; + color: var(--muted); + font-weight: 500; + font-size: 13px; + transition: background 0.15s, color 0.15s; +} +.modes button svg { width: 15px; height: 15px; } +.modes button:hover { color: var(--text); } +.modes button[aria-selected="true"] { background: var(--surface-2); color: var(--text); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.35); } +.modes button[aria-selected="true"] svg { color: var(--accent); } +.mode-hint { margin: 0; color: var(--faint); font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; } + +.composer-body { display: flex; align-items: flex-start; gap: 10px; } +.refs { display: none; gap: 6px; align-items: center; padding-top: 4px; flex: none; max-width: 45%; overflow-x: auto; } +body:not([data-mode="crea"]) .refs { display: flex; } +.ref-list { display: flex; gap: 6px; } +.ref { + position: relative; + width: 52px; + height: 52px; + border-radius: 10px; + overflow: hidden; + flex: none; + box-shadow: 0 0 0 1px var(--line-strong); +} +.ref img { width: 100%; height: 100%; object-fit: cover; display: block; } +.ref button { + position: absolute; + top: 3px; + right: 3px; + width: 20px; + height: 20px; + display: grid; + place-items: center; + border: 0; + border-radius: 50%; + background: rgba(10, 10, 12, 0.75); + color: #fff; + opacity: 0; + transition: opacity 0.15s; +} +.ref button svg { width: 12px; height: 12px; } +.ref:hover button, .ref button:focus-visible { opacity: 1; } +.ref-index { + position: absolute; + left: 4px; + bottom: 3px; + font-size: 10.5px; + font-weight: 600; + padding: 0 5px; + border-radius: 4px; + background: rgba(10, 10, 12, 0.7); +} +.ref-add { + position: relative; + display: grid; + place-items: center; + align-content: center; + gap: 2px; + width: 52px; + height: 52px; + border: 1px dashed var(--line-strong); + border-radius: 10px; + color: var(--muted); + font-size: 11px; + cursor: pointer; + flex: none; + transition: border-color 0.15s, color 0.15s; +} +.ref-add svg { width: 16px; height: 16px; } +.ref-add:hover { border-color: var(--accent); color: var(--text); } +.ref-add input { position: absolute; width: 1px; height: 1px; opacity: 0; } +.ref-add:focus-within { outline: 2px solid var(--accent); outline-offset: 2px; } +.refs.full .ref-add { display: none; } + +.prompt-area { flex: 1; min-width: 0; display: grid; grid-template-columns: minmax(0, 1fr); } +.prompt-col { min-width: 0; } +.it-col { display: none; } +.col-head { display: none; } +.prompt-area.bilingual { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px; } +.prompt-area.bilingual .it-col { display: block; } +.prompt-area.bilingual .col-head { display: flex; align-items: center; gap: 10px; min-height: 24px; padding: 0 4px; font-size: 11.5px; color: var(--faint); } +.prompt-area.bilingual .col-head span { flex: 1; } +.prompt-area.bilingual .col-head .link { font-size: 12px; } +#prompt-area.bilingual textarea { border: 1px solid var(--line); border-radius: 10px; padding: 8px 10px; background: var(--bg-raised); font-size: 13.5px; } +#prompt-area.bilingual textarea:focus { border-color: rgba(203, 188, 255, 0.4); } +#prompt-area.bilingual .en-col textarea { color: var(--muted); } +.icon-btn.tiny { width: 24px; height: 24px; border: 0; } +.icon-btn.tiny svg { width: 14px; height: 14px; } +#prompt-it { + display: block; + width: 100%; + min-height: 48px; + resize: none; + line-height: 1.5; + outline: none; +} +#prompt { + display: block; + flex: 1; + min-width: 0; + width: 100%; + min-height: 48px; + max-height: 180px; + padding: 8px 4px; + border: 0; + background: transparent; + resize: none; + font-size: 15px; + line-height: 1.5; +} +#prompt:focus { outline: none; } +#prompt::placeholder { color: var(--faint); } + +.composer-foot { display: flex; align-items: center; gap: 10px; margin-top: 4px; } +.pills { display: flex; flex-wrap: wrap; gap: 6px; flex: 1; min-width: 0; } +.pill { + display: inline-flex; + align-items: baseline; + gap: 6px; + max-width: 260px; + height: 28px; + padding: 0 10px; + border: 1px solid var(--line); + border-radius: 999px; + background: transparent; + font-size: 12.5px; + white-space: nowrap; + line-height: 26px; + transition: border-color 0.15s, background 0.15s; +} +.pill:hover { border-color: var(--line-strong); background: var(--surface-2); } +.pill-k { color: var(--faint); } +.pill-v { color: var(--text); overflow: hidden; text-overflow: ellipsis; } +.pill.on { border-color: rgba(203, 188, 255, 0.4); background: var(--accent-soft); } +.error { color: var(--danger); font-size: 12.5px; } +.error:empty { display: none; } +.error:not(:empty) ~ .enhance { margin-left: 0; } + +.generate { + display: inline-flex; + align-items: center; + gap: 10px; + height: 38px; + padding: 0 14px 0 18px; + border: 0; + border-radius: 10px; + background: var(--pearl); + color: #17141f; + font-weight: 600; + font-size: 14px; + background-size: 160% 100%; + background-position: 0% 0; + transition: background-position 0.5s var(--ease), transform 0.08s, opacity 0.15s; + margin-left: auto; +} +.generate:hover { background-position: 100% 0; } +.generate:active { transform: scale(0.98); } +.generate[disabled] { opacity: 0.6; cursor: progress; } + +.enhance { + display: inline-flex; + align-items: center; + gap: 6px; + height: 38px; + padding: 0 12px; + border: 1px solid var(--line-strong); + border-radius: 10px; + background: transparent; + color: var(--muted); + font-size: 13px; + margin-left: auto; + transition: color 0.15s, border-color 0.15s; +} +.enhance svg { width: 16px; height: 16px; } +.enhance:hover { color: var(--text); border-color: rgba(203, 188, 255, 0.4); } +.enhance[aria-busy="true"] { color: var(--accent); pointer-events: none; } +.enhance[aria-busy="true"] svg { animation: pulse 0.9s ease-in-out infinite; } +.enhance + .generate { margin-left: 0; } + +.checker { + background-color: #2a2b31; + background-image: + linear-gradient(45deg, #34353c 25%, transparent 25%), + linear-gradient(-45deg, #34353c 25%, transparent 25%), + linear-gradient(45deg, transparent 75%, #34353c 75%), + linear-gradient(-45deg, transparent 75%, #34353c 75%); + background-size: 18px 18px; + background-position: 0 0, 0 9px, 9px -9px, -9px 0; +} + +.switch-row { display: flex; align-items: center; gap: 10px; font-size: 13px; cursor: pointer; margin-top: 4px; } +.switch-row input { position: absolute; opacity: 0; width: 1px; height: 1px; } +.switch { position: relative; width: 32px; height: 18px; flex: none; border-radius: 999px; background: var(--surface-2); box-shadow: inset 0 0 0 1px var(--line-strong); transition: background 0.15s; } +.switch::after { content: ""; position: absolute; top: 2px; left: 2px; width: 14px; height: 14px; border-radius: 50%; background: var(--muted); transition: transform 0.15s var(--ease), background 0.15s; } +.switch-row input:checked + .switch { background: var(--accent-soft); box-shadow: inset 0 0 0 1px rgba(203, 188, 255, 0.5); } +.switch-row input:checked + .switch::after { transform: translateX(14px); background: var(--accent); } +.switch-row input:focus-visible + .switch { outline: 2px solid var(--accent); outline-offset: 2px; } + +/* ---------- inspector ---------- */ + +.inspector { + border-left: 1px solid var(--line); + background: var(--bg-raised); + overflow-y: auto; + padding: 6px 18px 30px; + scrollbar-width: thin; + scrollbar-color: var(--surface-2) transparent; +} +.panel { padding: 16px 0; border-bottom: 1px solid var(--line); } +.panel:last-child { border-bottom: 0; } +.panel-aside { font-weight: 400; color: var(--faint); margin-left: 6px; } +.panel h2, .panel summary { + margin: 0 0 10px; + font-size: 12.5px; + font-weight: 600; + color: var(--muted); + letter-spacing: 0.01em; +} +.panel-note { margin: 8px 0 0; color: var(--faint); font-size: 12px; } +.row-head { display: flex; justify-content: space-between; align-items: baseline; } +.row-head output { color: var(--accent); font-variant-numeric: tabular-nums; font-weight: 600; } + +.models { display: grid; gap: 6px; } +.model { + display: grid; + grid-template-columns: 16px 1fr; + gap: 2px 10px; + text-align: left; + padding: 10px 12px; + border: 1px solid var(--line); + border-radius: var(--r-md); + background: transparent; + transition: border-color 0.15s, background 0.15s; +} +.model:hover { border-color: var(--line-strong); } +.model::before { + content: ""; + grid-row: span 2; + width: 14px; + height: 14px; + margin-top: 2px; + border-radius: 50%; + border: 1.5px solid var(--faint); +} +.model[aria-checked="true"] { border-color: rgba(203, 188, 255, 0.45); background: var(--accent-soft); } +.model[aria-checked="true"]::before { border: 4px solid var(--accent); } +.model-name { font-weight: 500; font-size: 13.5px; } +.model-name small { color: var(--faint); font-weight: 400; margin-left: 4px; } +.model-desc { color: var(--muted); font-size: 12px; line-height: 1.4; } +.model[aria-disabled="true"] { opacity: 0.4; cursor: not-allowed; } +.count-note { display: none; } +body[data-model="entrambi"] .count-note { display: block; } + +.tpl-groups { display: grid; gap: 12px; } +.tpl-group-name { margin: 0 0 6px; font-size: 11.5px; color: var(--faint); } +.tpl-chips { display: flex; flex-wrap: wrap; gap: 6px; } +.chip { + --c: #888; + display: inline-flex; + align-items: center; + gap: 7px; + padding: 5px 11px 5px 9px; + border: 1px solid var(--line); + border-radius: 999px; + background: transparent; + font-size: 12.5px; + color: var(--text); + transition: border-color 0.15s, background 0.15s; +} +.chip::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--c); } +.chip:hover { border-color: var(--line-strong); } +.chip[aria-checked="true"] { border-color: var(--c); background: color-mix(in srgb, var(--c) 16%, transparent); } +.chip[data-order]::after { + content: attr(data-order); + display: grid; + place-items: center; + width: 16px; + height: 16px; + margin-right: -4px; + border-radius: 50%; + background: var(--c); + color: #141519; + font-size: 10px; + font-weight: 700; +} +.tpl-detail { margin-top: 12px; } +.tpl-detail p { margin: 0; color: var(--muted); font-size: 12.5px; } +.tpl-fields { display: grid; gap: 8px; margin-top: 10px; } +.tpl-fields:empty { display: none; } +.tpl-fields label { display: grid; gap: 4px; font-size: 12px; color: var(--muted); } + +input[type="text"], input[type="number"], .pp-fields textarea { + width: 100%; + height: 34px; + padding: 0 10px; + border: 1px solid var(--line-strong); + border-radius: var(--r-sm); + background: var(--surface); + transition: border-color 0.15s; +} +input[type="text"]:focus, input[type="number"]:focus, .pp-fields textarea:focus { outline: none; border-color: var(--accent); } +input::placeholder { color: var(--faint); } + +input[type="range"] { width: 100%; accent-color: var(--accent); } +.scale { display: flex; justify-content: space-between; color: var(--faint); font-size: 11.5px; margin-top: 2px; } + +.aspects { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; } +.aspect { + display: grid; + justify-items: center; + align-content: end; + gap: 6px; + height: 64px; + padding: 8px 4px 6px; + border: 1px solid var(--line); + border-radius: var(--r-sm); + background: transparent; + color: var(--muted); + font-size: 11.5px; + font-variant-numeric: tabular-nums; + transition: border-color 0.15s, color 0.15s; +} +.aspect-box { display: block; border: 1.5px solid currentColor; border-radius: 3px; } +.aspect:hover { border-color: var(--line-strong); color: var(--text); } +.aspect[aria-checked="true"] { border-color: rgba(203, 188, 255, 0.45); color: var(--accent); background: var(--accent-soft); } +.aspect-original .aspect-box { border-style: dashed; } + +.segmented { + display: grid; + grid-auto-flow: column; + grid-auto-columns: 1fr; + padding: 3px; + border-radius: 10px; + background: var(--surface); + border: 1px solid var(--line); +} +.segmented button { + border: 0; + background: transparent; + border-radius: 7px; + padding: 6px 0; + color: var(--muted); + font-size: 12.5px; + font-variant-numeric: tabular-nums; +} +.segmented button[aria-checked="true"] { background: var(--surface-2); color: var(--text); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); } + +.more summary { cursor: pointer; list-style: none; display: flex; justify-content: space-between; margin: 0; } +.more summary::-webkit-details-marker { display: none; } +.more summary::after { content: "+"; font-size: 16px; line-height: 1; color: var(--faint); } +.more[open] summary::after { content: "–"; } +.more[open] summary { margin-bottom: 12px; } +.row-label { display: flex; justify-content: space-between; font-size: 12.5px; color: var(--muted); margin: 10px 0 6px; } +.row-label output { color: var(--faint); font-variant-numeric: tabular-nums; } +.seed-row { display: grid; grid-template-columns: 1fr 34px; gap: 6px; } +.seed-row .icon-btn { width: 34px; height: 34px; } + +body[data-mode="modifica"] #panel-style, +body[data-mode="continua"] #panel-style, +body:not([data-mode="modifica"]) #panel-zone, +body[data-zoned="true"] #panel-aspect, +body:not([data-mode="ristila"]) #panel-fidelity, +body[data-model-resolved="klein"] #panel-fidelity { display: none; } + +/* ---------- galleria ---------- */ + +.gallery { height: calc(100vh - var(--topbar)); overflow-y: auto; padding: 28px 32px 110px; } +.gallery-head { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 22px; flex-wrap: wrap; } +.gallery-head h1 { margin: 0; font-family: var(--serif); font-weight: 400; font-size: 34px; letter-spacing: -0.01em; } +.filters { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; } +.filters button { + border: 1px solid var(--line); + background: transparent; + border-radius: 999px; + padding: 6px 14px; + color: var(--muted); + font-size: 13px; + transition: color 0.15s, border-color 0.15s, background 0.15s; +} +.filters button:hover { color: var(--text); } +.filters button[aria-checked="true"] { color: var(--text); border-color: var(--line-strong); background: var(--surface); } +.filters-sep { width: 1px; height: 18px; background: var(--line-strong); margin: 0 4px; } + +.scope-note { display: flex; align-items: center; gap: 12px; margin: -8px 0 20px; color: var(--muted); font-size: 13px; } +.link { border: 0; background: none; padding: 0; color: var(--accent); font-size: 13px; text-decoration: underline; text-underline-offset: 3px; } +.link.danger { color: var(--danger); } + +.masonry { columns: 4 260px; column-gap: 14px; } +.tile { + position: relative; + margin: 0 0 14px; + border-radius: var(--r-md); + overflow: hidden; + background: var(--surface); + break-inside: avoid; + cursor: zoom-in; +} +.tile img { display: block; width: 100%; height: auto; transition: transform 0.4s var(--ease), opacity 0.2s; } +.tile:hover img { transform: scale(1.02); } +.tile-info { + position: absolute; + inset: auto 0 0 0; + padding: 36px 12px 10px; + background: linear-gradient(to top, rgba(10, 10, 12, 0.88), transparent); + opacity: 0; + transform: translateY(6px); + transition: opacity 0.2s, transform 0.2s; + pointer-events: none; +} +.tile-title { margin: 0; font-size: 13px; font-weight: 500; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } +.tile-info .tile-meta { margin-top: 4px; font-size: 11.5px; color: var(--muted); gap: 2px 10px; } +.tile:hover .tile-info, .tile:focus-within .tile-info { opacity: 1; transform: none; } + +.tile-check, .tile-star { + position: absolute; + top: 10px; + width: 28px; + height: 28px; + display: grid; + place-items: center; + border: 0; + border-radius: 8px; + background: rgba(14, 14, 18, 0.6); + backdrop-filter: blur(6px); + color: #fff; + opacity: 0; + transition: opacity 0.15s, background 0.15s; +} +.tile-check { left: 10px; } +.tile-star { right: 10px; } +.tile-check svg, .tile-star svg { width: 16px; height: 16px; } +.tile-check svg { opacity: 0; } +.tile:hover .tile-check, .tile:hover .tile-star, .tile-check:focus-visible, .tile-star:focus-visible { opacity: 1; } +.tile[data-fav="true"] .tile-star { opacity: 1; color: #ffd27a; } +.tile[data-fav="true"] .tile-star svg { fill: currentColor; } +.tile[aria-selected="true"] { box-shadow: 0 0 0 2px var(--accent); } +.tile[aria-selected="true"] img { opacity: 0.75; } +.tile[aria-selected="true"] .tile-check { opacity: 1; background: var(--accent); color: #17141f; } +.tile[aria-selected="true"] .tile-check svg { opacity: 1; } +.masonry[data-selecting="true"] .tile-check { opacity: 1; } +.masonry[data-selecting="true"] .tile { cursor: pointer; } +.gallery-empty { color: var(--muted); } +#more-btn { display: block; margin: 10px auto 0; } + +.selection-bar { + position: fixed; + left: 50%; + bottom: 24px; + transform: translateX(-50%); + display: flex; + align-items: center; + gap: 16px; + padding: 8px 8px 8px 18px; + border: 1px solid var(--line-strong); + border-radius: 14px; + background: var(--surface-2); + box-shadow: 0 20px 50px -20px rgba(0, 0, 0, 0.9); + z-index: 10; + font-variant-numeric: tabular-nums; +} +.selection-actions { display: flex; gap: 2px; } +body[data-scope="galleria"] .selection-bar [data-scope]:not([data-scope="galleria"]), +body[data-scope="bozze"] .selection-bar [data-scope]:not([data-scope="bozze"]), +body[data-scope="cestino"] .selection-bar [data-scope]:not([data-scope="cestino"]) { display: none; } + +/* ---------- scheda dettaglio ---------- */ + +.detail { + width: min(1240px, 94vw); + height: min(820px, 90vh); + padding: 0; + border: 1px solid var(--line-strong); + border-radius: 20px; + background: var(--bg-raised); + color: var(--text); + overflow: hidden; + box-shadow: 0 40px 100px -30px rgba(0, 0, 0, 0.9); +} +.detail[open] { display: grid; grid-template-columns: minmax(0, 1fr) 340px; grid-template-rows: minmax(0, 1fr); animation: rise 0.25s var(--ease); } +.detail::backdrop { background: rgba(6, 6, 8, 0.7); backdrop-filter: blur(6px); } +@keyframes rise { from { opacity: 0; transform: translateY(10px) scale(0.99); } } + +.detail-media { position: relative; display: flex; align-items: center; justify-content: center; min-height: 0; height: 100%; padding: 20px; background: #101114; overflow: hidden; } +.detail-media img { max-width: 100%; max-height: 100%; width: auto; height: auto; object-fit: contain; border-radius: 10px; cursor: zoom-in; } +.detail-media.zoomed { align-items: flex-start; overflow: auto; } +.detail-media.zoomed img { flex: none; } +.detail-media.zoomed img { max-width: none; max-height: none; cursor: zoom-out; } +.nav { + position: absolute; + top: 50%; + width: 40px; + height: 40px; + margin-top: -20px; + display: grid; + place-items: center; + border: 0; + border-radius: 50%; + background: rgba(30, 31, 37, 0.8); + color: var(--text); + opacity: 0; + transition: opacity 0.15s; +} +.nav.prev { left: 14px; } +.nav.next { right: 14px; } +.detail-media:hover .nav, .nav:focus-visible { opacity: 1; } +.nav[disabled] { display: none; } + +.detail-side { display: flex; flex-direction: column; gap: 16px; min-height: 0; overflow-y: auto; padding: 18px 20px 20px; border-left: 1px solid var(--line); } +.detail-top { display: flex; gap: 8px; align-items: center; } +#detail-title { + flex: 1; + height: 40px; + padding: 0 10px; + margin-left: -10px; + border: 1px solid transparent; + border-radius: var(--r-sm); + background: transparent; + font-family: var(--serif); + font-size: 22px; +} +#detail-title:hover { border-color: var(--line); } +#detail-title:focus { outline: none; border-color: var(--accent); background: var(--surface); } +.detail-prompt { margin: 0; color: var(--muted); font-size: 13.5px; line-height: 1.55; max-height: 30vh; overflow-y: auto; } +.detail-meta { display: grid; grid-template-columns: auto 1fr; gap: 6px 14px; margin: 0; font-size: 12.5px; } +.detail-meta dt { color: var(--faint); } +.detail-meta dd { margin: 0; font-variant-numeric: tabular-nums; } +.detail-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: auto; } +.detail-btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; + height: 38px; + padding: 0 12px; + border: 1px solid var(--line-strong); + border-radius: 10px; + background: transparent; + color: var(--text); + font-size: 13px; + text-decoration: none; + transition: background 0.15s, border-color 0.15s; +} +.detail-btn svg { width: 16px; height: 16px; } +.detail-btn:hover { background: var(--surface); } +.detail-btn.primary { grid-column: 1 / -1; border: 0; background: var(--pearl); color: #17141f; font-weight: 600; } +.detail-btn[disabled] { opacity: 0.35; pointer-events: none; } +.detail-btn.danger:hover { color: var(--danger); border-color: rgba(255, 143, 143, 0.4); } +.detail-btn[aria-pressed="true"] { color: #ffd27a; border-color: rgba(255, 210, 122, 0.4); } +.detail-btn[aria-pressed="true"] svg { fill: currentColor; } +.detail[data-scope="cestino"] #detail-actions-gallery, +.detail:not([data-scope="cestino"]) #detail-actions-trash, +.detail[data-scope="bozze"] #detail-actions-gallery [data-scope="galleria"], +.detail[data-scope="galleria"] #detail-actions-gallery [data-scope="bozze"] { display: none; } +.detail[data-scope="cestino"] #detail-title { pointer-events: none; } + +/* ---------- conferma ---------- */ + +.confirm { + width: min(420px, 92vw); + padding: 22px 22px 18px; + border: 1px solid var(--line-strong); + border-radius: 18px; + background: var(--bg-raised); + color: var(--text); + box-shadow: 0 40px 100px -30px rgba(0, 0, 0, 0.9); +} +.confirm[open] { animation: rise 0.2s var(--ease); } +.confirm::backdrop { background: rgba(6, 6, 8, 0.6); backdrop-filter: blur(4px); } +.confirm h2 { margin: 0 0 6px; font-family: var(--serif); font-weight: 400; font-size: 22px; } +.confirm p { margin: 0 0 20px; color: var(--muted); font-size: 13.5px; } +.confirm-actions { display: flex; justify-content: flex-end; gap: 8px; } +.confirm-actions .detail-btn { min-width: 110px; } +#confirm-yes.danger { border: 0; background: #e25c5c; color: #fff; font-weight: 600; } +#confirm-yes.danger:hover { background: #ec6b6b; } + +/* ---------- toast ---------- */ + +.toast { + position: fixed; + left: 50%; + top: calc(var(--topbar) + 14px); + transform: translate(-50%, -12px); + display: flex; + align-items: center; + gap: 14px; + padding: 10px 12px 10px 16px; + border-radius: 12px; + background: var(--surface-2); + border: 1px solid var(--line-strong); + box-shadow: 0 16px 40px -16px rgba(0, 0, 0, 0.8); + font-size: 13.5px; + opacity: 0; + pointer-events: none; + transition: opacity 0.2s, transform 0.2s var(--ease); + z-index: 30; +} +.toast.show { opacity: 1; transform: translate(-50%, 0); pointer-events: auto; } +#toast-action { border: 0; background: var(--accent-soft); color: var(--accent); border-radius: 7px; padding: 4px 10px; font-weight: 500; } + +/* ---------- font della locandina (inclusi nella cartella, niente rete) ---------- */ + +@font-face { font-family: "PR Oswald"; font-weight: 500; src: url("/web/fonts/oswald-latin-500-normal.woff2") format("woff2"); } +@font-face { font-family: "PR Oswald"; font-weight: 700; src: url("/web/fonts/oswald-latin-700-normal.woff2") format("woff2"); } +@font-face { font-family: "PR Anton"; font-weight: 400; src: url("/web/fonts/anton-latin-400-normal.woff2") format("woff2"); } +@font-face { font-family: "PR Bebas"; font-weight: 400; src: url("/web/fonts/bebas-neue-latin-400-normal.woff2") format("woff2"); } +@font-face { font-family: "PR Archivo"; font-weight: 400; src: url("/web/fonts/archivo-black-latin-400-normal.woff2") format("woff2"); } +@font-face { font-family: "PR Inter"; font-weight: 400; src: url("/web/fonts/inter-latin-400-normal.woff2") format("woff2"); } +@font-face { font-family: "PR Inter"; font-weight: 600; src: url("/web/fonts/inter-latin-600-normal.woff2") format("woff2"); } +@font-face { font-family: "PR Inter"; font-weight: 800; src: url("/web/fonts/inter-latin-800-normal.woff2") format("woff2"); } +@font-face { font-family: "PR Playfair"; font-weight: 700; src: url("/web/fonts/playfair-display-latin-700-normal.woff2") format("woff2"); } +@font-face { font-family: "PR Playfair"; font-weight: 900; src: url("/web/fonts/playfair-display-latin-900-normal.woff2") format("woff2"); } +@font-face { font-family: "PR Marker"; font-weight: 400; src: url("/web/fonts/permanent-marker-latin-400-normal.woff2") format("woff2"); } + +/* ---------- immagine di partenza e pennello ---------- */ + +.base { display: none; width: 100%; height: 100%; padding: 22px 22px 52px; place-items: center; align-content: center; position: relative; } +.paint { position: relative; display: block; line-height: 0; } +.paint img { + display: block; + max-width: calc(100cqw - 44px); + max-height: calc(100cqh - 110px); + border-radius: 10px; + box-shadow: 0 30px 60px -30px rgba(0, 0, 0, 0.8), 0 0 0 1px rgba(255, 255, 255, 0.04); +} +#mask-canvas { position: absolute; inset: 0; width: 100%; height: 100%; border-radius: 10px; opacity: 0.55; pointer-events: none; } +.base-label { + position: absolute; + left: 50%; + bottom: 18px; + transform: translateX(-50%); + padding: 4px 12px; + border-radius: 999px; + background: rgba(14, 14, 18, 0.7); + color: var(--muted); + font-size: 12.5px; + white-space: nowrap; +} +.stage[data-brush="on"] #mask-canvas { pointer-events: auto; cursor: none; touch-action: none; } +.stage[data-brush="on"] .base-label { display: none; } +.brush-bar { + display: none; + position: absolute; + left: 50%; + bottom: 16px; + transform: translateX(-50%); + z-index: 4; + align-items: center; + gap: 10px; + padding: 6px 6px 6px 8px; + border: 1px solid var(--line-strong); + border-radius: 14px; + background: rgba(31, 32, 38, 0.92); + backdrop-filter: blur(10px); + box-shadow: 0 20px 40px -20px rgba(0, 0, 0, 0.9); + grid-area: auto; +} +.stage[data-brush="on"][data-state="base"] .brush-bar { display: flex; } +.brush-bar .seg { display: flex; padding: 2px; border-radius: 9px; background: var(--bg-raised); } +.brush-bar .seg button { display: grid; place-items: center; width: 32px; height: 28px; border: 0; border-radius: 7px; background: transparent; color: var(--muted); } +.brush-bar .seg button[aria-checked="true"] { background: var(--surface-2); color: var(--accent); } +.brush-size { display: flex; align-items: center; gap: 8px; color: var(--muted); font-size: 12px; } +.brush-size input { width: 110px; } +.brush-cursor { + position: absolute; + top: 0; + left: 0; + z-index: 5; + border-radius: 50%; + border: 1.5px solid #fff; + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.6); + pointer-events: none; + display: none; + grid-area: auto; +} +.brush-cursor.show { display: block; } +.brush-cursor.erase { border-style: dashed; } + +/* ---------- pannelli ---------- */ + +.panel-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 10px; } +.panel-head h2 { margin: 0; } +.panel-text { margin: 0 0 12px; color: var(--muted); font-size: 12.5px; } +.sub-h { margin-top: 16px !important; } +.panel.flash { animation: flash 1s var(--ease); } +@keyframes flash { 0% { background: var(--accent-soft); box-shadow: -18px 0 0 var(--accent-soft), 18px 0 0 var(--accent-soft); } 100% { background: transparent; } } +.mini-btn { + display: inline-flex; + align-items: center; + gap: 4px; + height: 26px; + padding: 0 9px 0 6px; + border: 1px solid var(--line); + border-radius: 8px; + background: transparent; + color: var(--muted); + font-size: 12px; +} +.mini-btn svg { width: 14px; height: 14px; } +.mini-btn:hover { color: var(--text); border-color: var(--line-strong); } +.wide-btn { + position: relative; + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + width: 100%; + height: 38px; + border: 1px solid var(--line-strong); + border-radius: 10px; + background: var(--surface); + color: var(--text); + font-size: 13px; + cursor: pointer; + transition: border-color 0.15s, background 0.15s; +} +.wide-btn:hover { border-color: rgba(203, 188, 255, 0.45); } +.wide-btn[aria-pressed="true"] { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); } +.wide-btn svg { width: 16px; height: 16px; } +.file-btn input { position: absolute; width: 1px; height: 1px; opacity: 0; } +.file-btn:focus-within { outline: 2px solid var(--accent); outline-offset: 2px; } +.zone-row { display: grid; gap: 8px; justify-items: start; } +.zone-row .wide-btn { width: 100%; } + +.tpl-group.user .tpl-chips { align-items: center; } +.chip-wrap { position: relative; display: inline-flex; } +.chip-wrap .chip { padding-right: 26px; } +.chip-edit { + position: absolute; + right: 4px; + top: 50%; + transform: translateY(-50%); + width: 20px; + height: 20px; + display: grid; + place-items: center; + border: 0; + border-radius: 50%; + background: transparent; + color: var(--faint); +} +.chip-edit svg { width: 12px; height: 12px; } +.chip-edit:hover { color: var(--text); background: var(--surface-2); } +.chip-add { border-style: dashed; color: var(--muted); gap: 4px; padding-left: 7px; } +.chip-add::before { display: none; } +.chip-add svg { width: 13px; height: 13px; } +.chip-add:hover { color: var(--text); } + +.segmented.small button { font-size: 12px; padding: 5px 0; } +.swatches { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } +.swatch { + width: 24px; + height: 24px; + border-radius: 50%; + border: 0; + background: var(--c); + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.15); +} +.swatch[aria-checked="true"] { box-shadow: 0 0 0 2px var(--bg-raised), 0 0 0 4px var(--accent); } +.swatch-custom { width: 26px; height: 26px; padding: 0; border: 1px dashed var(--line-strong); border-radius: 50%; background: transparent; cursor: pointer; } +.swatch-custom::-webkit-color-swatch-wrapper { padding: 3px; } +.swatch-custom::-webkit-color-swatch { border: 0; border-radius: 50%; } + +/* ---------- dialoghi ---------- */ + +.sheet { + width: min(480px, 92vw); + padding: 22px; + border: 1px solid var(--line-strong); + border-radius: 18px; + background: var(--bg-raised); + color: var(--text); + box-shadow: 0 40px 100px -30px rgba(0, 0, 0, 0.9); +} +.sheet[open] { animation: rise 0.2s var(--ease); } +.sheet::backdrop { background: rgba(6, 6, 8, 0.6); backdrop-filter: blur(4px); } +.sheet h2 { margin: 0 0 16px; font-family: var(--serif); font-weight: 400; font-size: 22px; } +.field { display: grid; gap: 6px; margin-bottom: 14px; font-size: 12.5px; color: var(--muted); } +.field textarea { + width: 100%; + padding: 9px 10px; + border: 1px solid var(--line-strong); + border-radius: var(--r-sm); + background: var(--surface); + resize: vertical; + font-size: 13.5px; + line-height: 1.45; +} +.field textarea:focus { outline: none; border-color: var(--accent); } +.sheet .panel-note { margin: -6px 0 14px; } +.sheet-actions { display: flex; gap: 8px; margin-top: 8px; } +.sheet-actions .spacer { flex: 1; } +.sheet-actions .detail-btn { min-width: 96px; } +.sheet-actions .detail-btn.primary { grid-column: auto; padding: 0 16px; } +.sheet .error { display: block; margin: 0 0 8px; } + +.picker { width: min(980px, 94vw); height: min(720px, 88vh); padding: 0; } +.picker[open] { display: grid; grid-template-rows: auto minmax(0, 1fr); } +.picker-head { display: flex; align-items: center; gap: 12px; padding: 16px 18px; border-bottom: 1px solid var(--line); } +.picker-head h2 { margin: 0; flex: 1; } +.picker-head .segmented { width: 190px; } +.picker-head .detail-btn { position: relative; } +.picker-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; padding: 18px; overflow-y: auto; align-content: start; } +.picker-item { padding: 0; border: 0; border-radius: 10px; overflow: hidden; background: var(--surface); aspect-ratio: 1; cursor: pointer; transition: box-shadow 0.15s, transform 0.15s; } +.picker-item img { width: 100%; height: 100%; object-fit: cover; display: block; } +.picker-item:hover { box-shadow: 0 0 0 2px var(--accent); transform: translateY(-1px); } +.picker-empty { color: var(--muted); grid-column: 1 / -1; } + +/* ---------- locandina ---------- */ + +.poster { display: grid; grid-template-columns: minmax(0, 1fr) 340px; height: calc(100vh - var(--topbar)); } +.poster-stage { + position: relative; + display: grid; + place-items: center; + min-height: 0; + margin: 18px 22px; + border-radius: var(--r-lg); + background: var(--bg-raised); + border: 1px solid var(--line); + overflow: hidden; + container-type: size; +} +.poster-canvas-wrap { display: grid; place-items: center; width: 100%; height: 100%; padding: 24px; } +#poster-canvas { + display: block; + max-width: calc(100cqw - 48px); + max-height: calc(100cqh - 48px); + width: auto; + height: auto; + border-radius: 6px; + box-shadow: 0 40px 80px -40px rgba(0, 0, 0, 0.95), 0 0 0 1px rgba(255, 255, 255, 0.05); +} +.poster-empty { max-width: 420px; text-align: center; display: grid; gap: 12px; justify-items: center; padding: 24px; } +.poster-empty h1 { margin: 0; font-family: var(--serif); font-weight: 400; font-size: clamp(28px, 3vw, 40px); } +.poster-empty p { margin: 0 0 8px; color: var(--muted); } +.poster-empty .detail-btn.primary { padding: 0 18px; } +.poster-panel { display: grid; grid-template-rows: minmax(0, 1fr) auto; border-left: 1px solid var(--line); background: var(--bg-raised); min-height: 0; } +.poster-scroll { overflow-y: auto; padding: 6px 18px 20px; scrollbar-width: thin; scrollbar-color: var(--surface-2) transparent; } +.poster-actions { display: grid; grid-template-columns: 1fr 1.4fr; gap: 8px; padding: 12px 18px 16px; border-top: 1px solid var(--line); } +.poster-actions .detail-btn.primary { grid-column: auto; } +.pp-row { margin-bottom: 4px; } +.pp-logo-opts { display: grid; gap: 4px; margin-top: 12px; } +.pp-fields { display: grid; gap: 9px; margin-bottom: 12px; } +.pp-fields label { display: grid; gap: 4px; font-size: 12px; color: var(--muted); } +.pp-fields small { color: var(--faint); font-weight: 400; margin-left: 4px; } +.pp-two { display: grid; grid-template-columns: 1.5fr 1fr; gap: 8px; } +.font-list { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; } +.font-opt { + height: 40px; + border: 1px solid var(--line); + border-radius: var(--r-sm); + background: transparent; + font-size: 17px; + color: var(--text); + transition: border-color 0.15s, background 0.15s; +} +.font-opt:hover { border-color: var(--line-strong); } +.font-opt[aria-checked="true"] { border-color: rgba(203, 188, 255, 0.5); background: var(--accent-soft); } +.color-rows { display: grid; gap: 10px; } +.color-row { display: grid; grid-template-columns: 62px 1fr; align-items: center; font-size: 12.5px; color: var(--muted); } +.layouts { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; } +.layout-opt { + display: grid; + justify-items: center; + gap: 6px; + padding: 10px 4px 8px; + border: 1px solid var(--line); + border-radius: var(--r-sm); + background: transparent; + color: var(--muted); + font-size: 11.5px; +} +.layout-opt[aria-checked="true"] { border-color: rgba(203, 188, 255, 0.5); background: var(--accent-soft); color: var(--accent); } + +.views .count, .filters .count { color: var(--faint); font-variant-numeric: tabular-nums; margin-left: 2px; } +.filters .count:empty { display: none; } + +/* menu sull'immagine */ +.shot img { cursor: pointer; } +.shot-menu { + position: absolute; + z-index: 6; + grid-area: auto; + display: grid; + gap: 2px; + width: 290px; + padding: 6px; + border: 1px solid var(--line-strong); + border-radius: 14px; + background: rgba(31, 32, 38, 0.96); + backdrop-filter: blur(12px); + box-shadow: 0 24px 60px -20px rgba(0, 0, 0, 0.9); + animation: rise 0.15s var(--ease); +} +.shot-menu button { + display: grid; + grid-template-columns: 20px 1fr; + gap: 10px; + align-items: start; + padding: 9px 10px; + border: 0; + border-radius: 9px; + background: transparent; + text-align: left; +} +.shot-menu button svg { margin-top: 1px; color: var(--accent); } +.shot-menu button:hover, .shot-menu button:focus-visible { background: var(--surface-2); outline: none; } +.shot-menu button[disabled] { opacity: 0.35; pointer-events: none; } +.shot-menu b { display: block; font-weight: 500; font-size: 13.5px; } +.shot-menu small { display: block; color: var(--muted); font-size: 12px; } +.chip-more { color: var(--muted); border-style: dashed; } +.chip-more::before { display: none; } +.sd-model { margin: -4px 0 12px; } + +/* continua dalla nuova versione */ +.next-bar { + display: flex; + align-items: center; + gap: 12px; + margin: 2px 0 8px; + padding: 7px 8px 7px 7px; + border: 1px solid rgba(203, 188, 255, 0.35); + border-radius: 12px; + background: var(--accent-soft); + animation: rise 0.2s var(--ease); +} +.next-bar img { width: 34px; height: 34px; border-radius: 7px; object-fit: cover; flex: none; } +.next-bar p { margin: 0; flex: 1; min-width: 0; font-size: 13px; color: var(--muted); } +.next-bar b { color: var(--text); font-weight: 500; } +.next-bar .link { font-size: 12.5px; color: var(--muted); } + +/* sessione */ +.stage-row { flex: 1; min-height: 0; display: flex; gap: 12px; } +.stage-row .stage { flex: 1; min-width: 0; } +.session { width: 76px; flex: none; display: grid; grid-template-rows: auto minmax(0, 1fr) auto; gap: 6px; min-height: 0; } +.session-head { margin: 0; display: grid; gap: 2px; font-size: 11px; color: var(--faint); text-align: center; } +.session-head span { text-transform: none; letter-spacing: 0; } +.session-head .link { font-size: 11px; color: var(--faint); } +.session-list { display: flex; flex-direction: column; gap: 6px; overflow-y: auto; padding: 3px; scrollbar-width: none; } +.session-list::-webkit-scrollbar { display: none; } +.session-item { + position: relative; + flex: none; + width: 66px; + height: 66px; + padding: 0; + border: 0; + border-radius: 10px; + overflow: hidden; + background: var(--surface); + opacity: 0.55; + box-shadow: 0 0 0 1px var(--line); + transition: opacity 0.15s, box-shadow 0.15s, transform 0.15s; +} +.session-item img { width: 100%; height: 100%; object-fit: cover; display: block; } +.session-item:hover { opacity: 0.9; } +.session-item.on { opacity: 1; box-shadow: 0 0 0 2px var(--accent); } +.session-item.saved::after { content: ""; position: absolute; top: 5px; right: 5px; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 0 2px rgba(10, 10, 12, 0.7); } +.session-tag { position: absolute; left: 0; right: 0; bottom: 0; padding: 2px 0; font-size: 9.5px; text-align: center; background: rgba(10, 10, 12, 0.72); color: var(--muted); } +.session-group { flex: none; padding: 2px 0; border: 0; border-top: 1px solid var(--line); background: transparent; color: var(--faint); font-size: 10.5px; } +.session-group:hover { color: var(--accent); } +.session-keys { margin: 0; font-size: 10px; color: var(--faint); text-align: center; } +.act.refine-btn { color: var(--accent); } + +/* ---------- schermi stretti ---------- */ + +@media (max-width: 1600px) { + .single-actions .act.secondary span { display: none; } + .single-actions .act.secondary { width: 32px; padding: 0; justify-content: center; } +} + +@media (max-width: 1360px) { + .single-actions .act span { display: none; } + .single-actions .act { width: 32px; padding: 0; justify-content: center; } +} + +@media (max-width: 1100px) { + :root { --inspector: 280px; } + .poster { grid-template-columns: minmax(0, 1fr) 300px; } + .mode-hint { display: none; } + .act span { display: none; } + .act { width: 32px; padding: 0; justify-content: center; } +} + +@media (max-width: 820px) { + body { overflow: auto; } + .topbar { grid-template-columns: auto 1fr; gap: 12px; } + .views { justify-self: end; } + .top-status { display: none; } + .studio { grid-template-columns: 1fr; height: auto; } + .workspace { padding: 14px; } + .stage { min-height: 56vh; } + .inspector { border-left: 0; border-top: 1px solid var(--line); } + .shot-bar { flex-wrap: wrap; } + .shot-caption { flex-basis: 100%; } + .compare { grid-auto-flow: row; grid-auto-rows: minmax(260px, 1fr); overflow-y: auto; } + .compare-hint { display: none; } + .mode-hint { display: none; } + .gallery { height: auto; padding: 20px 14px 110px; } + .detail[open] { grid-template-columns: 1fr; grid-template-rows: 50% 1fr; } + .detail-side { border-left: 0; border-top: 1px solid var(--line); } +} + +@media (max-width: 1600px) { + .single-actions .act.views-btn { width: auto; padding: 0 11px; } + .single-actions .act.views-btn span, .single-actions .act.refine-btn span { display: inline; } + .single-actions .act.refine-btn { width: auto; padding: 0 11px; } +} + +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { animation: none !important; transition: none !important; } +} + +/* ---------- vettorizza ---------- */ + +.vector { width: min(980px, 94vw); height: min(640px, 88vh); padding: 0; overflow: hidden; } +.vector[open] { display: grid; grid-template-columns: minmax(0, 1fr) 320px; } +.vector-view { + position: relative; + display: flex; + align-items: center; + justify-content: center; + min-height: 0; + padding: 28px; + background-color: #f4f4f6; + background-image: conic-gradient(#e6e6ea 25%, transparent 0 50%, #e6e6ea 0 75%, transparent 0); + background-size: 20px 20px; + transition: background-color 0.2s var(--ease); +} +.vector-view.dark { background-color: #16171b; background-image: conic-gradient(#1e1f24 25%, transparent 0 50%, #1e1f24 0 75%, transparent 0); } +.vector-art { display: contents; } +.vector-art svg { max-width: 100%; max-height: 100%; width: auto; height: auto; transition: opacity 0.2s var(--ease); } +.vector-wait { + position: absolute; + inset: auto 0 22px; + margin: 0; + text-align: center; + font-size: 12.5px; + color: #55575f; + opacity: 0; + transition: opacity 0.2s var(--ease); +} +.vector-view.dark .vector-wait { color: var(--muted); } +.vector-view[data-state="lavoro"] .vector-art svg { opacity: 0.25; } +.vector-view[data-state="lavoro"] .vector-wait { opacity: 1; } +.vector-side { display: flex; flex-direction: column; gap: 14px; min-height: 0; padding: 22px; border-left: 1px solid var(--line); overflow-y: auto; } +.vector-side h2 { margin: 0; } +.vector-side .panel-note { margin: 0; } +.vector-styles { display: grid; gap: 8px; } +.vector-styles button { + display: grid; + gap: 2px; + padding: 10px 12px; + border: 1px solid var(--line-strong); + border-radius: var(--r-md); + background: transparent; + color: var(--text); + text-align: left; + cursor: pointer; + transition: border-color 0.15s, background 0.15s; +} +.vector-styles button:hover { background: var(--surface); } +.vector-styles button[aria-checked="true"] { border-color: var(--accent); background: var(--accent-soft); } +.vector-styles b { font-weight: 600; font-size: 13.5px; } +.vector-styles small { color: var(--muted); font-size: 12px; } +.vector-stats { margin: 0; min-height: 18px; color: var(--muted); font-size: 12.5px; font-variant-numeric: tabular-nums; } +.vector-warn { margin: 0; padding: 10px 12px; border-radius: var(--r-sm); background: rgba(255, 210, 122, 0.08); color: #ffd27a; font-size: 12.5px; line-height: 1.5; } +.vector-side .sheet-actions { margin-top: auto; } +.vector-side .detail-btn svg { width: 16px; height: 16px; } + +/* ---------- infobox ---------- */ + +.tip { + position: fixed; + z-index: 1000; + max-width: 300px; + padding: 10px 12px; + border: 1px solid var(--line-strong); + border-radius: 12px; + background: rgba(36, 37, 44, 0.97); + box-shadow: 0 18px 40px -12px rgba(0, 0, 0, 0.75); + color: var(--text); + font-size: 12.5px; + line-height: 1.5; + opacity: 0; + transform: translateY(3px); + transition: opacity 0.14s var(--ease), transform 0.14s var(--ease); + pointer-events: auto; +} +.tip[data-side="sotto"] { transform: translateY(-3px); } +.tip.show { opacity: 1; transform: none; } +.tip::after { + content: ""; + position: absolute; + left: calc(var(--arrow, 50%) - 5px); + width: 10px; + height: 10px; + background: inherit; + border: inherit; + border-width: 0 1px 1px 0; + transform: rotate(45deg); +} +.tip[data-side="sopra"]::after { bottom: -6px; } +.tip[data-side="sotto"]::after { top: -6px; transform: rotate(225deg); } +.tip-text { margin: 0; } +.tip-more { + display: inline-flex; + align-items: center; + gap: 6px; + margin-top: 8px; + padding: 0; + border: 0; + background: none; + color: var(--accent); + font-size: 12px; + font-weight: 600; + cursor: pointer; +} +.tip-more svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 1.8; } +.tip-more:hover span { text-decoration: underline; text-underline-offset: 3px; } +@media (prefers-reduced-motion: reduce) { .tip { transition: none; } } + +/* ---------- guida laterale ---------- */ + +.guide { + position: fixed; + inset: var(--topbar) 0 0 auto; + z-index: 900; + width: min(560px, 100vw); + height: auto; + max-height: none; + margin: 0; + padding: 0; + border: 0; + border-left: 1px solid var(--line-strong); + background: var(--bg-raised); + color: var(--text); + box-shadow: -30px 0 60px -30px rgba(0, 0, 0, 0.8); + transform: translateX(100%); + transition: transform 0.25s var(--ease); +} +.guide[open] { display: grid; grid-template-rows: auto minmax(0, 1fr); } +.guide.show { transform: none; } +.guide-head { display: flex; align-items: center; gap: 8px; padding: 10px 12px 10px 18px; border-bottom: 1px solid var(--line); } +.guide-head > svg { width: 18px; height: 18px; fill: none; stroke: var(--accent); stroke-width: 1.7; } +.guide-head h2 { margin: 0; font-family: var(--serif); font-weight: 400; font-size: 19px; } +.guide-head .spacer { flex: 1; } +.guide-head .detail-btn { height: 32px; padding: 0 10px; font-size: 12.5px; text-decoration: none; } +.guide iframe { width: 100%; height: 100%; border: 0; background: #fbfaf7; } +@media (prefers-reduced-motion: reduce) { .guide { transition: none; } } + +/* ---------- locandina: template, livelli, tela ---------- */ + +.poster-canvas-wrap { position: relative; } +.pp-overlay { position: absolute; pointer-events: none; } +.pp-frame { position: absolute; border: 1.5px solid var(--accent); border-radius: 3px; box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.5); } +.pp-handle { + position: absolute; + right: -7px; + bottom: -7px; + width: 14px; + height: 14px; + border: 2px solid var(--bg); + border-radius: 50%; + background: var(--accent); + pointer-events: auto; + cursor: nwse-resize; +} +.poster-canvas-wrap.can-move { cursor: move; } +.poster-canvas-wrap.dragging { cursor: grabbing; } +.pp-hint { position: absolute; left: 0; right: 0; bottom: 8px; margin: 0; text-align: center; font-size: 11.5px; color: var(--faint); pointer-events: none; } +.pp-templates { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; } +.pp-tpl { + display: grid; + gap: 5px; + padding: 5px 5px 7px; + border: 1px solid var(--line); + border-radius: var(--r-md); + background: transparent; + color: var(--muted); + font-size: 11.5px; + cursor: pointer; + transition: border-color 0.15s, color 0.15s; +} +.pp-tpl canvas { width: 100%; height: auto; border-radius: 4px; background: var(--surface); } +.pp-tpl:hover { border-color: var(--line-strong); color: var(--text); } +.pp-tpl[aria-checked="true"] { border-color: var(--accent); color: var(--text); background: var(--accent-soft); } +.pp-two-btn { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; } +.pp-layer-list { display: grid; gap: 6px; margin-top: 10px; } +.pp-layer { + display: grid; + grid-template-columns: 40px minmax(0, 1fr) auto; + align-items: center; + gap: 10px; + padding: 5px 10px 5px 5px; + border: 1px solid var(--line); + border-radius: var(--r-sm); + background: transparent; + color: var(--text); + text-align: left; + font-size: 13px; + cursor: pointer; +} +.pp-layer img { width: 40px; height: 40px; object-fit: contain; border-radius: 4px; background: repeating-conic-gradient(#2a2b31 0 25%, #222328 0 50%) 0 0 / 10px 10px; } +.pp-layer span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.pp-layer small { color: var(--faint); font-size: 11px; } +.pp-layer[aria-pressed="true"] { border-color: var(--accent); background: var(--accent-soft); } +.pp-layer-opts { display: grid; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--line); } +.pp-layer-actions { display: flex; align-items: center; gap: 4px; } +.pp-layer-actions .spacer { flex: 1; } +.pp-fields textarea { height: auto; min-height: 70px; padding: 8px 10px; resize: vertical; font: inherit; font-size: 13.5px; line-height: 1.45; color: var(--text); } + +/* ---------- benvenuto e minuti finiti ---------- */ + +.welcome { + width: min(560px, 94vw); + max-height: min(860px, 94dvh); + padding: 0; + overflow: auto; + border: 1px solid var(--line-strong); + border-radius: 22px; + background: var(--bg-raised); + color: var(--text); + box-shadow: 0 50px 120px -30px rgba(0, 0, 0, 0.95); +} +.welcome[open] { animation: rise 0.24s var(--ease); } +.welcome::backdrop { background: rgba(6, 6, 8, 0.72); backdrop-filter: blur(6px); } +.welcome-strip { display: grid; grid-template-columns: repeat(5, 1fr); height: 120px; } +.welcome-strip img { width: 100%; height: 100%; object-fit: cover; } +.welcome-body { padding: 26px 28px 24px; } +.welcome h2 { margin: 0 0 8px; font-family: var(--serif); font-weight: 400; font-size: 28px; line-height: 1.15; } +.welcome-lead { margin: 0 0 18px; color: var(--muted); font-size: 14px; } +.welcome-facts { display: grid; gap: 12px; margin: 0 0 16px; } +.welcome-facts div { padding-left: 12px; border-left: 2px solid var(--line-strong); } +.welcome-facts div:nth-child(2) { border-color: var(--accent); } +.welcome-facts dt { font-size: 13.5px; font-weight: 600; } +.welcome-facts dd { margin: 2px 0 0; color: var(--muted); font-size: 13px; } +.welcome-rules { margin: 0 0 14px; padding: 10px 12px; border-radius: 10px; background: var(--surface); color: var(--muted); font-size: 12.5px; } +.welcome-check { display: flex; gap: 10px; align-items: flex-start; margin-bottom: 18px; font-size: 13px; color: var(--muted); cursor: pointer; } +.welcome-check input { width: 18px; height: 18px; margin: 1px 0 0; accent-color: #c9b8ff; flex: none; } +.welcome-check a, .welcome-rules a { color: var(--text); } +.welcome-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; } +.welcome-actions .detail-btn { height: 44px; font-size: 14px; } +.welcome-actions .detail-btn.primary { grid-column: auto; } +.welcome-actions [aria-disabled="true"] { opacity: 0.35; pointer-events: none; } +.quota .quota-when { margin-top: -10px; color: var(--text); } +.quota .confirm-actions .detail-btn.primary { grid-column: auto; padding: 0 16px; } + +@media (max-width: 520px) { + .welcome-strip { height: 88px; } + .welcome-body { padding: 20px 18px 18px; } + .welcome h2 { font-size: 24px; } + .welcome-actions { grid-template-columns: 1fr; } +} diff --git a/web/sw.js b/web/sw.js new file mode 100644 index 0000000000000000000000000000000000000000..24c278fe314ce0b715fef34323b2b5ec1d4bd926 --- /dev/null +++ b/web/sw.js @@ -0,0 +1,43 @@ +/* Serve le immagini della galleria dal browser stesso: /outputs/... e /inputs/... vivono in IndexedDB. */ +const DB_NAME = "pixrick"; + +self.addEventListener("install", () => self.skipWaiting()); +self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim())); + +function openDb() { + return new Promise((resolve, reject) => { + const req = indexedDB.open(DB_NAME, 1); + req.onupgradeneeded = () => { + const d = req.result; + d.createObjectStore("blobs"); + const items = d.createObjectStore("items", { keyPath: "file" }); + items.createIndex("scope", "scope"); + d.createObjectStore("kv"); + }; + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); +} + +async function fromStore(path) { + const db = await openDb(); + const blob = await new Promise((resolve, reject) => { + const r = db.transaction("blobs").objectStore("blobs").get(path); + r.onsuccess = () => resolve(r.result); + r.onerror = () => reject(r.error); + }); + db.close(); + if (!blob) return new Response("Immagine non trovata", { status: 404 }); + return new Response(blob, { + headers: { "Content-Type": blob.type || (path.endsWith(".webp") ? "image/webp" : "image/png"), "Cache-Control": "no-store" }, + }); +} + +self.addEventListener("fetch", (event) => { + const url = new URL(event.request.url); + if (url.origin !== location.origin || event.request.method !== "GET") return; + if (url.pathname.startsWith("/outputs/") || url.pathname.startsWith("/inputs/")) { + const path = url.pathname.slice(1).split("/").map(decodeURIComponent).join("/"); + event.respondWith(fromStore(path)); + } +}); diff --git a/web/tips.js b/web/tips.js new file mode 100644 index 0000000000000000000000000000000000000000..dcc94e481406fd3d0b0335801dd88efd6fdff71a --- /dev/null +++ b/web/tips.js @@ -0,0 +1,250 @@ +"use strict"; + +/* Infobox al passaggio del mouse, con collegamento alla sezione giusta della guida. + Ogni voce: [selettore, testo (null = usa il title dell'elemento), sezione della guida]. */ +const TIPS = [ + // barra in alto + [".views [data-view=studio]", "Dove crei, ristili e modifichi le immagini.", "studio"], + [".views [data-view=locandina]", "Componi una locandina con testi veri: font, logo e colori li scegli tu.", "locandina"], + [".views [data-view=galleria]", "Tutte le immagini salvate, le bozze delle ultime 24 ore e il cestino.", "galleria"], + ["#account-btn", "Il tuo accesso. Da ospite hai 2 minuti di GPU al giorno; con un account Hugging Face gratuito 5 minuti e la precedenza in coda.", ""], + ["#lang-btn", "Cambia lingua dell'interfaccia: italiano o inglese.", ""], + ["#help-btn", "Apri la guida completa.", ""], + + // modalità + [".modes [data-mode=crea]", "Un'immagine nuova partendo solo da una descrizione.", "crea"], + [".modes [data-mode=ristila]", "Tieni la composizione di una foto e cambiale stile: anime, foto vera, Funko, acquerello…", "ristila"], + [".modes [data-mode=modifica]", "Cambia quello che scrivi: togli, aggiungi, sostituisci. Anche solo in una zona dipinta, o combinando fino a 4 foto.", "modifica"], + [".modes [data-mode=continua]", "Una scena nuova con lo stesso stile, mondo e personaggi della foto di partenza.", "storia"], + + // composer + [".ref-add", "Aggiungi la foto di partenza. Puoi anche trascinarla nello Studio o incollarla con ⌘V.", "foto-partenza"], + ["#prompt", "Scrivi in italiano o in inglese. Il testo da far comparire nell'immagine va tra virgolette. Con la freccia ↑ a campo vuoto ritrovi l'ultimo prompt.", "prompt"], + ["#prompt-it", "La tua versione in italiano. Se la cambi, premi «Aggiorna l'inglese».", "migliora"], + ["#enhance-btn", "Trasforma un'idea veloce in un prompt ricco e preciso. Vedi inglese e italiano affiancati e puoi correggere prima di generare.", "migliora"], + ["#generate-btn", "Avvia la generazione. Scorciatoia: ⌘↵ da qualsiasi punto dello Studio.", "crea"], + ["#pills", "Il riassunto delle impostazioni attive. Clicca una voce per andare a cambiarla.", "studio"], + ["#next-use", "Da ora lavori su questa versione: la prossima modifica partirà da qui.", "continua-con-questa"], + ["#next-stay", "Ignora la nuova versione e continua a lavorare sull'immagine di prima.", "continua-con-questa"], + + // pannello destro + ["#panel-zone", "Dipingi la parte da cambiare: tutto il resto resta identico al pixel.", "zona"], + ["#zone-btn", "Apri il pennello e dipingi la zona da modificare. B pennello, E gomma, [ e ] dimensione, ⌘Z annulla.", "zona"], + ["#templates .chip", null, "stili"], + ["#templates .chip-edit", null, "tuoi-stili"], + ["#panel-style h2", "Puoi combinare fino a 3 stili: il primo decide il «materiale» (foto, disegno, 3D), gli altri aggiungono atmosfera.", "stili"], + ["#panel-fidelity", "Quanto dell'immagine originale sopravvive. In automatico PixRick guarda se è una foto o un disegno e cosa chiede lo stile.", "fedelta"], + ["#panel-aspect .aspects button", "La forma dell'immagine. «Come la foto» mantiene le proporzioni della foto di partenza.", "formato"], + ["#models .model", null, "modelli"], + ["#quality", "Rapida per provare idee, Bilanciata per tutti i giorni, Massima per il risultato finale: più passaggi, più dettaglio, più tempo.", "qualita"], + ["#count", "Quante varianti generare in una volta. Con la combo Klein + Z-Image ricevi comunque solo immagini finite.", "quantita"], + ["#translate", "Se scrivi in italiano, un piccolo modello di testo traduce in inglese prima di generare. Il testo tra virgolette non viene tradotto.", "prompt"], + ["#seed", "Il numero che decide la «casualità». Stesso seme + stesse impostazioni = stessa immagine. Vuoto = sempre diverso.", "seme"], + ["#seed-dice", "Estrai un seme a caso.", "seme"], + + // risultato + ["#session", "Tutto quello che hai fatto da quando hai aperto la pagina. Clicca o usa le frecce per tornare a una versione precedente.", "sessione"], + ["#act-save", "Sposta l'immagine in galleria. Quello che non salvi resta tra le bozze per 24 ore, poi sparisce.", "bozze"], + ["#act-save-all", "Salva in galleria tutte le immagini del confronto.", "bozze"], + ["#act-back", "Torna alla griglia con tutte le varianti generate.", "confronto"], + ["#act-variant", "Stesse impostazioni, seme nuovo: una sorella della stessa idea.", "varia"], + ["#act-other", "Rifà la stessa immagine con l'altro modello e lo stesso seme, per confrontare.", "modelli"], + ["#act-edit", "Usa questa immagine come partenza per una modifica a comando.", "modifica"], + ["#act-restyle", "Usa questa immagine come partenza per cambiarle stile.", "ristila"], + ["#act-upscale", "Raddoppia la risoluzione aggiungendo dettaglio vero, non solo pixel più grandi.", "ingrandisci"], + ["#act-cutout", "Toglie lo sfondo e lascia il soggetto su trasparente (PNG).", "scontorna"], + ["#act-refine", "Z-Image ripassa pelle, luce e dettagli senza cambiare l'immagine. Vedi prima e dopo affiancate.", "rifinisci"], + ["#act-views", "Crea la stessa figura vista di lato e di spalle, pronta per i servizi che trasformano immagini in modelli 3D.", "viste-3d"], + ["#act-vector", "Trasforma l'immagine in SVG: forme vere, nitide a qualsiasi dimensione. Perfetto per loghi, sticker, taglio e stampa.", "svg"], + ["#act-poster", "Usa questa immagine come sfondo di una locandina.", "locandina"], + ["#act-download", "Scarica il file PNG originale.", "risultato"], + ["#act-reuse", "Rimette nel composer prompt, stili, modello e impostazioni di questa immagine.", "risultato"], + ["#act-copy", "Copia il prompt finale (quello in inglese andato al modello).", "risultato"], + ["#act-trash", "Elimina l'immagine. Dalla galleria finisce nel cestino, dalle bozze sparisce.", "cestino"], + ["#shot-img", "Clicca l'immagine per il menu: continua la storia, salva come stile, rifinisci, cambia una zona, locandina.", "menu-immagine"], + ["#b-upscale", "Raddoppia la risoluzione della foto di partenza.", "ingrandisci"], + ["#b-cutout", "Toglie lo sfondo dalla foto di partenza.", "scontorna"], + ["#b-vector", "Trasforma la foto di partenza in SVG.", "svg"], + ["#b-poster", "Usa la foto di partenza come sfondo di una locandina.", "locandina"], + ["#brush-bar", "Pennello per la zona: B pennello, E gomma, [ e ] dimensione, ⌘Z annulla l'ultimo tratto.", "zona"], + + // galleria + ["#filters [data-f=bozze]", "Le immagini non salvate: restano 24 ore, poi si cancellano da sole.", "bozze"], + ["#filters [data-f=cestino]", "Le immagini eliminate dalla galleria. Restano qui finché non svuoti il cestino.", "cestino"], + ["#filters [data-f=preferite]", "Solo le immagini segnate con la stella.", "galleria"], + ["#filters", "Filtra la galleria per tipo di lavoro.", "galleria"], + ["#detail-title", "Dai un titolo all'immagine: Invio per salvarlo.", "dettaglio"], + ["#detail-img", "Clicca per vederla a grandezza reale e scorrerla. ← → per passare alle altre.", "dettaglio"], + ["#d-open", "Apri l'immagine nello Studio per continuare a lavorarci.", "dettaglio"], + ["#d-vector", "Trasforma l'immagine in SVG.", "svg"], + ["#d-story", "Una scena nuova con gli stessi personaggi e lo stesso stile.", "storia"], + ["#d-style", "Salva l'aspetto di questa immagine come stile riutilizzabile.", "tuoi-stili"], + ["#d-fav", "Segna come preferita.", "galleria"], + + // locandina + ["#pp-templates .pp-tpl", null, "locandina-template"], + ["#poster-pick", "L'immagine di sfondo: dalla galleria, dalle bozze o dal dispositivo. È facoltativa.", "locandina"], + ["#pp-add-logo", "Carica uno o più loghi (band, sponsor, locale). Il template li dispone da solo.", "locandina-livelli"], + ["#pp-add-photo", "Aggiungi una foto come riquadro: rettangolo, angoli arrotondati o cerchio.", "locandina-livelli"], + ["#pp-layer-key", "Se il logo ha lo sfondo bianco, lo rende trasparente.", "locandina-livelli"], + ["#pp-layer-reset", "Il livello torna nella posizione decisa dal template.", "locandina-livelli"], + ["#pp-lineup", "Una band o un ospite per riga. La prima è la principale.", "locandina-template"], + ["#pp-fonts", "Font veri installati in PixRick: le lettere sono sempre corrette, niente scritte inventate dall'AI.", "locandina"], + ["#pp-grain", "Una grana leggera da carta stampata, per un effetto meno digitale.", "locandina"], + ["#pp-save", "Salva la locandina in galleria in alta risoluzione.", "locandina"], + + // vettorizza + ["#vector-transparent", "Il colore di fondo che tocca i bordi (di solito il bianco) sparisce: il logo si appoggia su qualsiasi superficie.", "svg"], + ["#vector-styles [data-v=colori]", "Fino a 16 colori: la più fedele all'originale.", "svg"], + ["#vector-styles [data-v=essenziale]", "8 colori, forme più grandi e pulite: file leggero, ideale per stampa e plotter da taglio.", "svg"], + ["#vector-styles [data-v=contorno]", "Solo le linee scure, su trasparente: per pagine da colorare, incisione laser, timbri.", "svg"], +]; + +const tips = { + el: null, + target: null, + showTimer: 0, + hideTimer: 0, + warmUntil: 0, + enabled: true, + + init() { + this.enabled = prefs.get("suggerimenti", true); + this.el = el("div", { class: "tip", role: "tooltip", id: "tip", hidden: true }, [ + el("p", { class: "tip-text" }), + el("button", { type: "button", class: "tip-more" }, [icon("i-help"), el("span", { text: "Approfondisci nella guida" })]), + ]); + document.body.append(this.el); + this.el.addEventListener("pointerenter", () => clearTimeout(this.hideTimer)); + this.el.addEventListener("pointerleave", () => this.scheduleHide()); + this.el.querySelector(".tip-more").addEventListener("click", () => { + const section = this.el.dataset.guide; + this.hide(true); + guide.open(section); + }); + document.addEventListener("pointerover", (e) => this.over(e), true); + document.addEventListener("pointerdown", (e) => { if (!this.el.contains(e.target)) this.hide(true); }, true); + document.addEventListener("keydown", (e) => { if (e.key === "Escape") this.hide(true); }); + window.addEventListener("scroll", () => this.hide(true), true); + const toggle = $("#tips-toggle"); + if (toggle) { + toggle.checked = this.enabled; + toggle.addEventListener("change", () => { this.enabled = toggle.checked; prefs.set("suggerimenti", this.enabled); if (!this.enabled) this.hide(true); }); + } + }, + + lookup(node) { + for (let n = node; n && n !== document.body; n = n.parentElement) { + if (n === this.el || n.closest?.(".tip")) return null; + for (const [sel, text, section] of TIPS) { + if (n.matches?.(sel)) { + const own = n.dataset.tip || n.getAttribute("title") || ""; + const body = text ?? own; + if (body) return { node: n, text: body, section }; + } + } + const own = n.dataset?.tip || n.getAttribute?.("title"); + if (own) return { node: n, text: own, section: n.closest("[data-guide]")?.dataset.guide || "" }; + } + return null; + }, + + over(e) { + if (!this.enabled || e.pointerType === "touch") return; + if (this.el.contains(e.target)) return; + const hit = this.lookup(e.target); + if (!hit) { + if (this.target) this.scheduleHide(); + return; + } + if (hit.node.hasAttribute("title")) { + hit.node.dataset.tip = hit.node.getAttribute("title"); + hit.node.removeAttribute("title"); + } + if (hit.node === this.target) { clearTimeout(this.hideTimer); return; } + clearTimeout(this.showTimer); + clearTimeout(this.hideTimer); + const delay = performance.now() < this.warmUntil ? 60 : 550; + this.showTimer = setTimeout(() => this.show(hit), delay); + }, + + show({ node, text, section }) { + if (!node.isConnected) return; + this.target = node; + this.el.querySelector(".tip-text").textContent = text; + this.el.dataset.guide = section || ""; + this.el.querySelector(".tip-more").hidden = !section; + this.el.hidden = false; + this.place(node); + this.el.classList.add("show"); + node.addEventListener("pointerleave", () => this.scheduleHide(), { once: true }); + }, + + place(node) { + const r = node.getBoundingClientRect(); + const t = this.el.getBoundingClientRect(); + const gap = 10; + const below = r.top - t.height - gap < 8; + let left = r.left + r.width / 2 - t.width / 2; + left = Math.max(8, Math.min(left, innerWidth - t.width - 8)); + const top = below ? r.bottom + gap : r.top - t.height - gap; + this.el.style.left = `${left}px`; + this.el.style.top = `${Math.max(8, Math.min(top, innerHeight - t.height - 8))}px`; + this.el.dataset.side = below ? "sotto" : "sopra"; + this.el.style.setProperty("--arrow", `${Math.max(14, Math.min(t.width - 14, r.left + r.width / 2 - left))}px`); + }, + + scheduleHide() { + clearTimeout(this.showTimer); + clearTimeout(this.hideTimer); + this.hideTimer = setTimeout(() => this.hide(), 220); + }, + + hide(now = false) { + clearTimeout(this.showTimer); + clearTimeout(this.hideTimer); + if (this.target) this.warmUntil = performance.now() + (now ? 0 : 900); + this.target = null; + this.el?.classList.remove("show"); + if (this.el) this.el.hidden = true; + }, +}; + +/* ---------- guida laterale ---------- */ + +const guide = { + open(section = "") { + const drawer = $("#guide"); + const frame = $("#guide-frame"); + const hash = section ? `#${section}` : ""; + if (!frame.src || !frame.src.includes("/guida")) { + frame.src = `/guida?incorporata=1${hash}`; + } else { + try { + const doc = frame.contentWindow; + if (section) doc.location.hash = section; else doc.scrollTo({ top: 0 }); + doc.postMessage({ evidenzia: section }, location.origin); + } catch { frame.src = `/guida?incorporata=1${hash}`; } + } + $("#guide-full").href = `/guida${hash}`; + if (!drawer.open) drawer.show(); + drawer.classList.add("show"); + document.body.classList.add("guide-open"); + }, + close() { + const drawer = $("#guide"); + drawer.classList.remove("show"); + document.body.classList.remove("guide-open"); + setTimeout(() => { if (!drawer.classList.contains("show")) drawer.close(); }, 250); + }, + bind() { + $("#help-btn").addEventListener("click", () => ($("#guide").open ? this.close() : this.open())); + $("#guide-close").addEventListener("click", () => this.close()); + document.addEventListener("keydown", (e) => { + if (e.key === "Escape" && $("#guide").open && !document.querySelector("dialog[open]:not(#guide)")) this.close(); + if (e.key === "?" && !e.target.closest("input, textarea, [contenteditable]")) { e.preventDefault(); this.open(); } + }); + }, +}; + +document.addEventListener("DOMContentLoaded", () => { tips.init(); guide.bind(); }); diff --git a/web/vendor/LICENSE b/web/vendor/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/web/vendor/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/web/vendor/__vite-browser-external-Cgmn0awE.js b/web/vendor/__vite-browser-external-Cgmn0awE.js new file mode 100644 index 0000000000000000000000000000000000000000..70db3371c54f628d4cb8616f92afa9d781fdc814 --- /dev/null +++ b/web/vendor/__vite-browser-external-Cgmn0awE.js @@ -0,0 +1,7 @@ +import { t as e } from "./browser.js"; +//#region __vite-browser-external +var t = /* @__PURE__ */ e(((e, t) => { + t.exports = {}; +})); +//#endregion +export default t(); diff --git a/web/vendor/gradio-client.js b/web/vendor/gradio-client.js new file mode 100644 index 0000000000000000000000000000000000000000..6f61d1e27644844a985da4f69a5338c721446972 --- /dev/null +++ b/web/vendor/gradio-client.js @@ -0,0 +1,2367 @@ +//#region \0rolldown/runtime.js +var e = Object.create, t = Object.defineProperty, n = Object.getOwnPropertyDescriptor, r = Object.getOwnPropertyNames, i = Object.getPrototypeOf, a = Object.prototype.hasOwnProperty, o = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t.exports), s = (e, i, o, s) => { + if (i && typeof i == "object" || typeof i == "function") for (var c = r(i), l = 0, u = c.length, d; l < u; l++) d = c[l], !a.call(e, d) && d !== o && t(e, d, { + get: ((e) => i[e]).bind(null, d), + enumerable: !(s = n(i, d)) || s.enumerable + }); + return e; +}, c = (n, r, a) => (a = n == null ? {} : e(i(n)), s(r || !n || !n.__esModule ? t(a, "default", { + value: n, + enumerable: !0 +}) : a, n)), l = "supports-zerogpu-headers", u = !1; +function d() { + return typeof window < "u" && typeof document < "u" && typeof window.addEventListener == "function"; +} +function f(e) { + return e.includes(".dev.") ? `https://moon-${e.split(".")[1]}.dev.spaces.huggingface.tech` : e.endsWith(".hf.space") ? "https://huggingface.co" : null; +} +function p() { + if (!d() || u) return; + window.addEventListener("message", (e) => { + e.data === l && (window.supports_zerogpu_headers = !0); + }), u = !0; + let e = f(window.location.hostname); + e && window.parent !== window && window.parent.postMessage(l, e); +} +//#endregion +//#region src/helpers/console_forward.ts +var m = "gradio-console", h = 4096, ee = 1e4, g = "[Unserializable]", _ = 100, v = 1e3, y = [ + "log", + "info", + "warn", + "error", + "debug" +], b = "https://huggingface.co", x = /^http:\/\/(localhost|127\.0\.0\.1)(:\d{1,5})?$/; +function te(e, t) { + return typeof e == "string" ? e === b || x.test(e) ? !0 : typeof t == "string" && t.includes(".dev.") ? e === f(t) : !1 : !1; +} +function ne(e, t = {}) { + try { + let t = e.parent; + if (!t || t === e) return null; + } catch { + return null; + } + let n = T(), r = "", i = null; + f(t); + let a = !0, o = !1, s = 0, c = 0, l = !1, u = null, d = []; + function f(e) { + !r && typeof e.gradio_version == "string" && (r = e.gradio_version), typeof e.untrack == "function" && (i = e.untrack); + } + function p(e) { + if (!(o || !a)) { + o = !0; + try { + e(); + } catch {} finally { + o = !1; + } + } + } + function h(e, t) { + p(() => { + let n = Date.now(), r = i ? i(t) : t(), a = { + seq: ++s, + ts: n, + level: e, + text: E(r.text) + }; + typeof r.stack == "string" && (a.stack = E(r.stack)), d.push(a), d.length > 100 && (c += d.length - 100, d.splice(0, d.length - 100)); + }); + } + function g(t) { + p(() => { + let i = t?.data; + if (typeof i != "object" || !i || i.protocol !== "gradio-console" || i.type !== "get") return; + let a = e.parent; + if (!a || t.source !== a) return; + let o = t.origin; + if (!te(o, e.location.hostname)) return; + l = !0, u !== null && (clearTimeout(u), u = null), ne(); + let s = { + protocol: m, + version: 1, + type: "state", + session_id: n, + gradio_version: r, + dropped: c, + entries: d.slice() + }; + (typeof i.id == "string" || typeof i.id == "number") && (s.id = i.id), a.postMessage(s, o); + }); + } + function _(e) { + let t, n, r = ""; + try { + t = e?.error, n = e?.message, e?.filename && (r = ` (${e.filename}:${e.lineno}:${e.colno})`); + } catch {} + h("exception", () => t == null ? { text: (typeof n == "string" && n ? n : "Unknown error") + r } : ie([t])); + } + function v(e) { + let t; + try { + t = e?.reason; + } catch { + t = void 0; + } + h("rejection", () => ie([t])); + } + let b = /* @__PURE__ */ new Map(), x = !1; + function ne() { + x = !0; + for (let t of y) if (!b.has(t)) try { + let n = e.console, r = n[t]; + if (typeof r != "function") continue; + let i = function(...e) { + try { + return r.apply(this, e); + } finally { + x && h(t, () => ie(e)); + } + }; + try { + Object.defineProperty(i, "name", { value: r.name }); + } catch {} + n[t] = i, b.set(t, { + wrapped: i, + original: r + }); + } catch {} + } + function S() { + x = !1; + for (let [t, { wrapped: n, original: r }] of b) try { + e.console[t] === n && (e.console[t] = r, b.delete(t)); + } catch {} + } + function C() { + u !== null || l || !a || (u = setTimeout(() => { + u = null, l || S(); + }, ee)); + } + ne(); + let w = [], re = [ + ["message", g], + ["error", _], + ["unhandledrejection", v], + ["load", C] + ]; + for (let [t, n] of re) try { + e.addEventListener(t, n), w.push(() => e.removeEventListener(t, n)); + } catch {} + try { + e.document?.readyState === "complete" && C(); + } catch {} + return { + session_id: n, + configure: f, + uninstall() { + a = !1, u !== null && clearTimeout(u), u = null, S(); + for (let e of w) try { + e(); + } catch {} + } + }; +} +var S = Symbol.for("gradio.console_forward"); +function C(e = {}) { + try { + if (typeof window > "u" || typeof window.addEventListener != "function") return null; + let t = window, n = t[S]; + if (n !== void 0) return n?.configure(e), n; + let r = ne(window, e); + return t[S] = r, r; + } catch { + return null; + } +} +function w(e, t) { + try { + if (typeof window > "u" || typeof e != "string" || new URL(e).origin !== window.location.origin) return; + C({ gradio_version: t }); + } catch {} +} +function re() { + try { + if (typeof window > "u" || f(window.location.hostname) === null) return; + C(); + } catch {} +} +function T() { + try { + let e = globalThis.crypto; + if (e && typeof e.randomUUID == "function") return e.randomUUID(); + } catch {} + return Date.now().toString(36) + "-" + Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2); +} +function E(e) { + return e.length > 4096 ? e.slice(0, h) : e; +} +function ie(e) { + let t = [], n, r = !1; + for (let i of e) { + if (!r && i instanceof Error) { + r = !0; + try { + typeof i.stack == "string" && (n = i.stack); + } catch {} + } + t.push(ae(i)); + } + let i = { text: E(t.join(" ")) }; + return n !== void 0 && (i.stack = E(n)), i; +} +function ae(e) { + try { + return typeof e == "string" ? e : e instanceof Error ? `${e.name}: ${e.message}` : oe(e) ?? String(e); + } catch { + try { + return String(e); + } catch { + return g; + } + } +} +function oe(e) { + let t = 0; + return JSON.stringify(e, (e, n) => { + if (++t > v) return "…"; + if (typeof n != "object" || !n) return n; + if (ArrayBuffer.isView(n) || n instanceof ArrayBuffer) { + let e = "length" in n ? n.length : n.byteLength; + return `[${n.constructor?.name ?? "ArrayBuffer"} length ${e}]`; + } + if (Array.isArray(n) && n.length > _) { + let e = n.slice(0, _); + return e.push(`…[${n.length - _} more]`), e; + } + return n; + }); +} +//#endregion +//#region src/constants.ts +var se = "host", ce = "queue/data", le = "queue/join", D = "upload", ue = "login", O = "config", de = "info", fe = "runtime", k = "sleeptime", pe = "heartbeat", A = "component_server", me = "reset", he = "cancel", j = "app_id", ge = "This application is currently busy. Please try again. ", M = "Connection errored out. ", N = "Could not resolve app config. ", P = "Could not get space status. ", F = "Could not get API info. ", I = "Space metadata could not be loaded. ", _e = "Invalid URL. A full URL path is required.", L = "Not authorized to access this space. ", ve = "Invalid credentials. Could not login. ", R = "Login credentials are required to access this space.", ye = "Could not access this app (received a 401 response). If it is a private Hugging Face Space, pass a valid Hugging Face token to the `token` option of `Client.connect`. You can generate a token at https://huggingface.co/settings/tokens.", be = (e, t) => `Space "${e}" could not be accessed (received a ${t} response from the Hugging Face API). Check that the Space name is spelled correctly and that the Space exists. If the Space is private, pass a valid Hugging Face token to the \`token\` option of \`Client.connect\`. You can generate a token at https://huggingface.co/settings/tokens.`, xe = "No API information is available for this app. This can happen when the app's `/info` endpoint cannot be reached, or when the app is running a legacy version of Gradio that is not supported by this client. ", Se = "This app appears to be running a legacy version of Gradio (3.x or earlier) that communicates over WebSockets, which is not supported by this version of @gradio/client. Please upgrade the app to a newer version of Gradio, or connect to it with @gradio/client version 0.x.", Ce = "File system access is only available in Node.js environments", z = "Root URL not found in client config", we = "Error uploading file"; +//#endregion +//#region src/helpers/init_helpers.ts +async function Te(e, t, n) { + try { + return (await (await fetch(`https://huggingface.co/api/spaces/${e}/jwt`, { headers: { + Authorization: `Bearer ${t}`, + ...n ? { Cookie: n } : {} + } })).json()).token || !1; + } catch { + return !1; + } +} +function B(e) { + e.hf_token && !e.token && (e.token = e.hf_token, console.warn("The `hf_token` option has been renamed to `token`. Support for `hf_token` will be removed in a future version of @gradio/client.")); +} +function V(e) { + let t = {}; + return e.forEach(({ api_name: e, id: n }) => { + e && (t[e] = n); + }), t; +} +function Ee(e, t, n = !1) { + let r = new URL(t), i = new URL(e, r), a = i.hostname.endsWith(".colab-user-runtimes.internal") || i.hostname.endsWith(".codatalab-user-runtimes.internal"); + return n || a ? new URL(new URL(e, r).pathname, r).toString().replace(/\/$/, "") : i.hostname === r.hostname ? (i.protocol = r.protocol, i.host = r.host, i.toString().replace(/\/$/, "")) : e; +} +async function De(e, t = !0) { + let n = this.options.token ? { Authorization: `Bearer ${this.options.token}` } : {}; + if (typeof window < "u" && window.gradio_config && location.origin !== "http://localhost:9876") { + if (t && window.gradio_config.current_page && (e = e.substring(0, e.lastIndexOf("/"))), window.gradio_config.dev_mode || typeof window < "u" && window?.BUILD_MODE === "dev") { + let t = new URL(Fe(e, O)); + this.deep_link && t.searchParams.set("deep_link", this.deep_link), this.page !== null && t.searchParams.set("page", this.page); + let r = await Oe(await this.fetch(t, { + headers: n, + credentials: this.options.credentials ?? "same-origin" + }), !!this.options.auth); + r.root = e || r.root, window.gradio_config = { + ...r, + current_page: window.gradio_config.current_page + }; + } + let r = { ...window.gradio_config }; + return r.root = Ee(r.root, location.href, r.is_colab), r; + } else if (e) { + let t = new URL(Fe(e, O)); + this.deep_link && t.searchParams.set("deep_link", this.deep_link), this.page !== null && t.searchParams.set("page", this.page); + let r = await Oe(await this.fetch(t, { + headers: n, + credentials: this.options.credentials ?? "same-origin" + }), !!this.options.auth); + return r.root ||= e, r; + } + throw Error(N); +} +async function Oe(e, t) { + if (e?.status === 401 && !t) { + let t = null; + try { + t = await e.json(); + } catch { + throw Error(ye); + } + let n = t?.detail?.auth_message; + throw Error(n || "Login credentials are required to access this space."); + } else if (e?.status === 401 && t) throw Error(ve); + if (e?.status === 200) { + let t = await e.json(); + return t.dependencies?.forEach((e, t) => { + e.id === void 0 && (e.id = t); + }), t; + } else if (e?.status === 401) throw Error(L); + throw Error(`${N}(received status ${e?.status} when fetching the app config)`); +} +async function ke() { + let { http_protocol: e, host: t } = await Pe(this.app_reference, this.options.token); + try { + if (this.options.auth) { + let n = await Ae(e, t, this.options.auth, this.fetch, this.options.token, this.options.credentials); + n && this.set_cookies(n); + } + } catch (e) { + throw Error(e.message); + } +} +async function Ae(e, t, n, r, i, a) { + let o = new FormData(); + o.append("username", n?.[0]), o.append("password", n?.[1]); + let s = {}; + i && (s.Authorization = `Bearer ${i}`); + let c = await r(`${e}//${t}/${ue}`, { + headers: s, + method: "POST", + body: o, + credentials: a ?? "same-origin" + }); + if (c.status === 200) return c.headers.get("set-cookie"); + throw c.status === 401 ? Error(ve) : Error(I); +} +function H(e) { + if (e.startsWith("http")) { + let { protocol: t, host: n, pathname: r } = new URL(e); + return { + ws_protocol: t === "https:" ? "wss" : "ws", + http_protocol: t, + host: n + (r === "/" ? "" : r) + }; + } + return { + ws_protocol: "wss", + http_protocol: "https:", + host: new URL(e).host + }; +} +var je = (e) => { + let t = []; + return e.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/).forEach((e) => { + let [n, r] = e.split(";")[0].split("="); + n && r && t.push(`${n.trim()}=${r.trim()}`); + }), t; +}, Me = /^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/, Ne = /.*hf\.space\/{0,1}.*$/; +async function Pe(e, t) { + let n = {}; + t && (n.Authorization = `Bearer ${t}`); + let r = e.trim().replace(/\/$/, ""); + if (Me.test(r)) { + let e; + try { + e = await fetch(`https://huggingface.co/api/spaces/${r}/${se}`, { headers: n }); + } catch { + throw Error(I); + } + if (e.status === 401 || e.status === 404) throw Error(be(r, e.status)); + let t; + try { + t = (await e.json()).host; + } catch { + throw Error(I); + } + if (!t) throw Error(I); + return { + space_id: r, + ...H(t) + }; + } + if (Ne.test(r)) { + let { ws_protocol: e, http_protocol: t, host: n } = H(r); + return { + space_id: n.split("/")[0].replace(".hf.space", ""), + ws_protocol: e, + http_protocol: t, + host: n + }; + } + return { + space_id: !1, + ...H(r) + }; +} +var Fe = (...e) => { + try { + return e.reduce((e, t) => (e = e.replace(/\/+$/, ""), t = t.replace(/^\/+/, ""), new URL(t, e + "/").toString())); + } catch { + throw Error(_e); + } +}; +function Ie(e, t, n) { + let r = { + named_endpoints: {}, + unnamed_endpoints: {} + }; + return Object.keys(e).forEach((i) => { + (i === "named_endpoints" || i === "unnamed_endpoints") && (r[i] = {}, Object.entries(e[i]).forEach(([e, a]) => { + let o = a?.parameters ?? [], s = a?.returns ?? [], c = t.dependencies.find((t) => t.api_name === e || t.api_name === e.replace("/", ""))?.id || n[e.replace("/", "")] || -1, l = c === -1 ? void 0 : t.dependencies.find((e) => e.id == c), u = c === -1 ? { + generator: !1, + cancel: !1 + } : l?.types; + if (l && Array.isArray(l.inputs) && l.inputs.length !== o.length) { + let e = l.inputs.map((e) => t.components.find((t) => t.id === e)?.type); + try { + e.forEach((e, t) => { + e === "state" && o.splice(t, 0, { + component: "state", + example: null, + parameter_default: null, + parameter_has_default: !0, + parameter_name: null, + hidden: !0 + }); + }); + } catch (e) { + console.error(e); + } + } + let d = (e, t, n, r) => ({ + ...e, + description: Re(e?.type, n), + type: Le(e?.type, t, n, r) || "" + }); + r[i][e] = { + parameters: o.map((e) => d(e, e?.component, e?.serializer, "parameter")), + returns: s.map((e) => d(e, e?.component, e?.serializer, "return")), + type: u, + ...a?.oauth_token ? { oauth_token: a.oauth_token } : {} + }; + })); + }), r; +} +function Le(e, t, n, r) { + if (t === "Api") return e.type; + switch (e?.type) { + case "string": return "string"; + case "boolean": return "boolean"; + case "number": return "number"; + } + if (n === "JSONSerializable" || n === "StringSerializable") return "any"; + if (n === "ListStringSerializable") return "string[]"; + if (t === "Image") return r === "parameter" ? "Blob | File | Buffer" : "string"; + if (n === "FileSerializable") return e?.type === "array" ? r === "parameter" ? "(Blob | File | Buffer)[]" : "{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]" : r === "parameter" ? "Blob | File | Buffer" : "{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}"; + if (n === "GallerySerializable") return r === "parameter" ? "[(Blob | File | Buffer), (string | null)][]" : "[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]"; +} +function Re(e, t) { + return t === "GallerySerializable" ? "array of [file, label] tuples" : t === "ListStringSerializable" ? "array of strings" : t === "FileSerializable" ? "array of files or single file" : e?.description; +} +function ze(e, t) { + switch (e.msg) { + case "send_data": return { type: "data" }; + case "send_hash": return { type: "hash" }; + case "queue_full": return { + type: "update", + status: { + queue: !0, + message: ge, + stage: "error", + code: e.code, + success: e.success + } + }; + case "heartbeat": return { type: "heartbeat" }; + case "unexpected_error": return { + type: "unexpected_error", + status: { + queue: !0, + message: e.message, + session_not_found: e.session_not_found, + stage: "error", + success: !1 + } + }; + case "broken_connection": return { + type: "broken_connection", + status: { + queue: !0, + message: e.message, + stage: "error", + success: !1 + } + }; + case "estimation": return { + type: "update", + status: { + queue: !0, + stage: t || "pending", + code: e.code, + size: e.queue_size, + position: e.rank, + eta: e.rank_eta, + success: e.success + } + }; + case "progress": return { + type: "update", + status: { + queue: !0, + stage: "pending", + code: e.code, + progress_data: e.progress_data, + success: e.success + } + }; + case "log": return { + type: "log", + data: e + }; + case "process_generating": return { + type: "generating", + status: { + queue: !0, + message: e.success ? null : e.output.error, + stage: e.success ? "generating" : "error", + code: e.code, + progress_data: e.progress_data, + eta: e.average_duration, + changed_state_ids: e.success ? e.output.changed_state_ids : void 0 + }, + data: e.success ? e.output : null + }; + case "process_streaming": return { + type: "streaming", + status: { + queue: !0, + message: e.output.error, + stage: "streaming", + time_limit: e.time_limit, + code: e.code, + progress_data: e.progress_data, + changed_state_ids: e.output.changed_state_ids, + eta: e.eta + }, + data: e.output + }; + case "process_completed": return "error" in e.output ? { + type: "update", + status: { + queue: !0, + title: e.output.title ?? "Error", + message: e.output.error ?? "An error occurred", + visible: e.output.visible, + duration: e.output.duration, + stage: "error", + code: e.code, + success: e.success + } + } : { + type: "complete", + status: { + queue: !0, + message: e.success ? void 0 : e.output.error, + stage: e.success ? "complete" : "error", + code: e.code, + progress_data: e.progress_data, + changed_state_ids: e.success ? e.output.changed_state_ids : void 0, + used_cache: e.used_cache, + cache_duration: e.cache_duration, + avg_time: e.avg_time + }, + data: e.success ? e.output : null + }; + case "process_starts": return { + type: "update", + status: { + queue: !0, + stage: "pending", + code: e.code, + size: e.rank, + position: 0, + success: e.success, + eta: e.eta + }, + original_msg: "process_starts" + }; + } + return { + type: "none", + status: { + stage: "error", + queue: !0 + } + }; +} +var Be = (e = [], t) => { + let n = t ? t.parameters : []; + if (Array.isArray(e)) return t && n.length > 0 && e.length > n.length && console.warn("Too many arguments provided for the endpoint."), e; + let r = [], i = Object.keys(e); + return n.forEach((t, n) => { + if (e.hasOwnProperty(t.parameter_name)) r[n] = e[t.parameter_name]; + else if (t.parameter_has_default) r[n] = t.parameter_default; + else throw Error(`No value provided for required parameter: ${t.parameter_name}`); + }), i.forEach((e) => { + if (!n.some((t) => t.parameter_name === e)) throw Error(`Parameter \`${e}\` is not a valid keyword argument. Please refer to the API for usage.`); + }), r.forEach((e, t) => { + if (e === void 0 && !n[t].parameter_has_default) throw Error(`No value provided for required parameter: ${n[t].parameter_name}`); + }), r; +}; +//#endregion +//#region src/utils/view_api.ts +async function Ve() { + if (this.api_info) return this.api_info; + let { token: e } = this.options, { config: t } = this, n = {}; + if (e && (n.Authorization = `Bearer ${e}`), t) try { + let e, r; + if (typeof window < "u" && window.gradio_api_info) r = window.gradio_api_info; + else { + let i = new URL(Fe(t.root, this.api_prefix, de)); + if (this.page !== null && i.searchParams.set("page", this.page), e = await this.fetch(i, { + headers: n, + credentials: this.options.credentials ?? "same-origin" + }), !e.ok) throw Error(M); + r = await e.json(); + } + return "api" in r && (r = r.api), r.named_endpoints["/predict"] && !r.unnamed_endpoints[0] && (r.unnamed_endpoints[0] = r.named_endpoints["/predict"]), Ie(r, t, this.api_map); + } catch (e) { + throw Error("Could not get API info. " + e.message); + } +} +//#endregion +//#region src/utils/upload_files.ts +async function He(e, t, n) { + let r = {}; + this?.options?.token && (r.Authorization = `Bearer ${this.options.token}`); + let i = 1e3, a = [], o; + for (let s = 0; s < t.length; s += i) { + let c = t.slice(s, s + i), l = new FormData(); + c.forEach((e) => { + l.append("files", e); + }); + try { + let t = n ? `${e}${this.api_prefix}/${D}?upload_id=${n}` : `${e}${this.api_prefix}/${D}`; + o = await this.fetch(t, { + method: "POST", + body: l, + headers: r, + credentials: this.options.credentials ?? "same-origin" + }); + } catch (e) { + throw Error(M + e.message); + } + if (!o.ok) { + let e = await o.text(); + return { error: `HTTP ${o.status}: ${e}` }; + } + let u = await o.json(); + u && a.push(...u); + } + return { files: a }; +} +var Ue = { + si: { + radix: 1e3, + unit: [ + "b", + "kb", + "Mb", + "Gb", + "Tb", + "Pb", + "Eb", + "Zb", + "Yb" + ] + }, + iec: { + radix: 1024, + unit: [ + "b", + "Kib", + "Mib", + "Gib", + "Tib", + "Pib", + "Eib", + "Zib", + "Yib" + ] + }, + jedec: { + radix: 1024, + unit: [ + "b", + "Kb", + "Mb", + "Gb", + "Tb", + "Pb", + "Eb", + "Zb", + "Yb" + ] + } +}; +function We(e, t = 1, n = "jedec") { + e = Math.abs(e); + let { radix: r, unit: i } = Ue[n] || Ue.jedec, a = 0; + for (; e >= r;) e /= r, ++a; + return `${e.toFixed(t)} ${i[a]}`; +} +//#endregion +//#region src/upload.ts +async function Ge(e, t, n, r) { + let i = (Array.isArray(e) ? e : [e]).map((e) => e.blob), a = i.filter((e) => e.size > (r ?? Infinity)); + if (a.length) throw Error(`File(s) exceed the maximum allowed size of ${We(r || Infinity)}: ${a.map((e) => `"${e.name}"`).join(", ")}`); + return await Promise.all(await this.upload_files(t, i, n).then(async (n) => { + if (n.error) throw Error(n.error); + return n.files ? n.files.map((n, r) => { + let i = n.split("/").map((e) => encodeURIComponent(e)).join("/"); + return new U({ + ...e[r], + path: n, + url: `${t}${this.api_prefix}/file=${i}` + }); + }) : []; + })); +} +async function Ke(e, t) { + return e.map((e) => new U({ + path: e.name, + orig_name: e.name, + blob: e, + size: e.size, + mime_type: e.type, + is_stream: t + })); +} +var U = class { + path; + url; + orig_name; + size; + blob; + is_stream; + mime_type; + alt_text; + b64; + meta = { _type: "gradio.FileData" }; + constructor({ path: e, url: t, orig_name: n, size: r, blob: i, is_stream: a, mime_type: o, alt_text: s, b64: c }) { + this.path = e, this.url = t, this.orig_name = n, this.size = r, this.blob = t ? void 0 : i, this.is_stream = a, this.mime_type = o, this.alt_text = s, this.b64 = c; + } +}, qe = class { + type; + command; + meta; + fileData; + constructor(e, t) { + this.type = "command", this.command = e, this.meta = t; + } +}, Je = typeof process < "u" && process.versions && process.versions.node; +function Ye(e, t, n) { + for (; n.length > 1;) { + let t = n.shift(); + if (typeof t == "string" || typeof t == "number") e = e[t]; + else throw Error("Invalid key type"); + } + let r = n.shift(); + if (typeof r == "string" || typeof r == "number") e[r] = t; + else throw Error("Invalid key type"); +} +async function Xe(e, t = void 0, n = [], r = !1, i = void 0) { + if (Array.isArray(e)) { + let a = []; + return await Promise.all(e.map(async (o, s) => { + let c = n.slice(); + c.push(String(s)); + let l = await Xe(e[s], r ? i?.parameters[s]?.component || void 0 : t, c, !1, i); + a = a.concat(l); + })), a; + } else if (globalThis.Buffer && e instanceof globalThis.Buffer || e instanceof Blob) return [{ + path: n, + blob: e instanceof Blob ? e : new Blob([e]), + type: t + }]; + else if (typeof e == "object" && e) { + let t = []; + for (let r of Object.keys(e)) { + let a = [...n, r], o = e[r]; + t = t.concat(await Xe(o, void 0, a, !1, i)); + } + return t; + } + return []; +} +function Ze(e, t) { + let n = t?.dependencies?.find((t) => t.id == e)?.queue; + return n == null ? !t.enable_queue : !n; +} +function Qe(e, t) { + return new Promise((n, r) => { + let i = new MessageChannel(); + i.port1.onmessage = (({ data: e }) => { + i.port1.close(), n(e); + }), window.parent.postMessage(e, t, [i.port2]); + }); +} +function $e(e) { + if (typeof e == "string") { + if (e.startsWith("http://") || e.startsWith("https://")) return { + path: e, + url: e, + orig_name: e.split("/").pop() ?? "unknown", + meta: { _type: "gradio.FileData" } + }; + if (Je) return new qe("upload_file", { + path: e, + name: e, + orig_path: e + }); + } else if (typeof File < "u" && e instanceof File) return e; + else if (globalThis.Buffer && e instanceof globalThis.Buffer) return new Blob([e]); + else if (e instanceof Blob) return e; + throw Error("Invalid input: must be a URL, File, Blob, or Buffer object."); +} +function W(e, t, n, r, i = !1) { + if (r === "input" && !i) throw Error("Invalid code path. Cannot skip state inputs for input."); + if (r === "output" && i) return e; + let a = [], o = 0, s = r === "input" ? t.inputs : t.outputs; + for (let t = 0; t < s.length; t++) { + let r = s[t]; + if (n.find((e) => e.id === r)?.type === "state") { + if (i) if (e.length === s.length) { + let t = e[o]; + a.push(t), o++; + } else a.push(null); + else { + o++; + continue; + } + continue; + } else { + let t = e[o]; + a.push(t), o++; + } + } + return a; +} +var et = [ + "/file=", + "/file/", + "/stream/", + "/proxy=" +]; +function tt(e, t, n, r) { + if (!r || typeof e != "object" || !e) return; + let i = r, a = new URL(t), o = a.pathname.replace(/\/+$/, ""), s = n ? `/${n.replace(/^\/+|\/+$/g, "")}` : "", c = new Set([`${o}${s}`, s]); + s || (c.add(`${o}/gradio_api`), c.add("/gradio_api")); + function l(e) { + if (typeof e != "object" || !e) return; + let t = e; + if (t.meta?._type === "gradio.FileData" && typeof t.url == "string") { + let e = new URL(t.url, `${a.toString().replace(/\/$/, "")}/`), n = [...c].some((t) => et.some((n) => e.pathname.startsWith(`${t}${n}`))); + (e.protocol === "http:" || e.protocol === "https:") && e.origin === a.origin && n && (e.searchParams.set("__sign", i), t.url = e.toString()); + } + for (let e of Object.values(t)) l(e); + } + l(e); +} +function nt(e, t) { + for (let n of e.components || []) tt(n.props?.value, e.root, e.api_prefix || "", t); +} +//#endregion +//#region src/utils/handle_blob.ts +async function rt(e, t, n) { + let r = this; + await it(r, t); + let i = await Xe(t, void 0, [], !0, n); + return (await Promise.all(i.map(async ({ path: t, blob: n, type: i }) => { + if (!n) return { + path: t, + type: i + }; + let a = await r.upload_files(e, [n]); + return { + path: t, + file_url: a.files && a.files[0], + type: i, + name: typeof File < "u" && n instanceof File ? n?.name : void 0 + }; + }))).forEach(({ path: e, file_url: n, type: r, name: i }) => { + r === "Gallery" ? Ye(t, n, e) : n && Ye(t, new U({ + path: n, + orig_name: i + }), e); + }), t; +} +async function it(e, t) { + if (!(e.config?.root || e.config?.root_url)) throw Error(z); + await at(e, t); +} +async function at(e, t, n = []) { + for (let r in t) t[r] instanceof qe ? await ot(e, t, r) : typeof t[r] == "object" && t[r] !== null && await at(e, t[r], [...n, r]); +} +async function ot(e, t, n) { + let r = t[n], i = e.config?.root || e.config?.root_url; + if (!i) throw Error(z); + try { + let a, o; + if (typeof process < "u" && process.versions && process.versions.node) { + let e = await import("./__vite-browser-external-Cgmn0awE.js").then((e) => /* @__PURE__ */ c(e.default, 1)); + o = (await import("./__vite-browser-external-Cgmn0awE.js").then((e) => /* @__PURE__ */ c(e.default, 1))).resolve(process.cwd(), r.meta.path), a = await e.readFile(o); + } else throw Error(Ce); + let s = new Blob([a], { type: "application/octet-stream" }), l = await e.upload_files(i, [s]), u = l.files && l.files[0]; + u && (t[n] = new U({ + path: u, + orig_name: r.meta.name || "" + })); + } catch (e) { + console.error(we, e); + } +} +//#endregion +//#region src/utils/post_data.ts +async function st(e, t, n) { + let r = { "Content-Type": "application/json" }; + this.options.token && (r.Authorization = `Bearer ${this.options.token}`); + try { + var i = await this.fetch(e, { + method: "POST", + body: JSON.stringify(t), + headers: { + ...r, + ...n + }, + credentials: this.options.credentials ?? "same-origin" + }); + } catch { + return [{ error: M }, 500]; + } + let a, o; + try { + a = await i.json(), o = i.status; + } catch (e) { + a = { error: `Could not parse server response: ${e}` }, o = 500; + } + return [a, o]; +} +//#endregion +//#region src/utils/predict.ts +async function ct(e, t = {}) { + let n = !1, r = !1; + if (!this.config) throw Error("Could not resolve app config"); + if (typeof e == "number") this.config.dependencies.find((t) => t.id == e); + else { + let t = e.replace(/^\//, ""); + this.config.dependencies.find((e) => e.id == this.api_map[t]); + } + let i = this.submit(e, t, null, null, !0), a; + for await (let e of i) { + if (e.type === "data" && (n = !0, a = e, r)) return a; + if (e.type === "status") { + if (e.stage === "error") { + let { message: t, ...n } = e, r = Error((typeof t == "string" ? t : t && JSON.stringify(t)) || "An unknown error occurred while making a prediction."); + throw Object.assign(r, n), r; + } + if (e.stage === "complete" && (r = !0, n)) return a; + } + } + return a; +} +//#endregion +//#region src/helpers/spaces.ts +async function G(e, t, n) { + let r = t === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${e}` : `https://huggingface.co/api/spaces/${e}`, i, a; + try { + if (i = await fetch(r), a = i.status, a !== 200) throw Error(); + i = await i.json(); + } catch { + n({ + status: "error", + load_status: "error", + message: P, + detail: "NOT_FOUND" + }); + return; + } + if (!i || a !== 200) return; + let { runtime: { stage: o }, id: s } = i; + switch (o) { + case "STOPPED": + case "SLEEPING": + n({ + status: "sleeping", + load_status: "pending", + message: "Space is asleep. Waking it up...", + detail: o + }), setTimeout(() => { + G(e, t, n); + }, 1e3); + break; + case "PAUSED": + n({ + status: "paused", + load_status: "error", + message: "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.", + detail: o, + discussions_enabled: await dt(s) + }); + break; + case "RUNNING": + case "RUNNING_BUILDING": + n({ + status: "running", + load_status: "complete", + message: "Space is running.", + detail: o + }); + break; + case "BUILDING": + n({ + status: "building", + load_status: "pending", + message: "Space is building...", + detail: o + }), setTimeout(() => { + G(e, t, n); + }, 1e3); + break; + case "APP_STARTING": + n({ + status: "starting", + load_status: "pending", + message: "Space is starting...", + detail: o + }), setTimeout(() => { + G(e, t, n); + }, 1e3); + break; + default: + n({ + status: "space_error", + load_status: "error", + message: "This space is experiencing an issue.", + detail: o, + discussions_enabled: await dt(s) + }); + break; + } +} +var lt = async (e, t) => { + let n = 0; + return new Promise((r) => { + G(e, Me.test(e) ? "space_name" : "subdomain", (i) => { + t(i), i.status === "running" || i.status === "error" || i.status === "paused" || i.status === "space_error" ? r() : (i.status === "sleeping" || i.status === "building") && (n < 12 ? (n++, setTimeout(() => { + lt(e, t).then(r); + }, 5e3)) : r()); + }); + }); +}, ut = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/; +async function dt(e) { + try { + let t = await fetch(`https://huggingface.co/api/spaces/${e}/discussions`, { method: "HEAD" }), n = t.headers.get("x-error-message"); + return !(!t.ok || n && ut.test(n)); + } catch { + return !1; + } +} +async function ft(e, t) { + let n = {}; + t && (n.Authorization = `Bearer ${t}`); + try { + let t = await fetch(`https://huggingface.co/api/spaces/${e}/${fe}`, { headers: n }); + if (t.status !== 200) throw Error("Space hardware could not be obtained."); + let { hardware: r } = await t.json(); + return r.current; + } catch (e) { + throw Error(e.message); + } +} +async function pt(e, t, n) { + let r = {}; + n && (r.Authorization = `Bearer ${n}`); + let i = { seconds: t }; + try { + let t = await fetch(`https://huggingface.co/api/spaces/${e}/${k}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + ...r + }, + body: JSON.stringify(i) + }); + if (t.status !== 200) throw Error("Could not set sleep timeout on duplicated Space. Please visit *ADD HF LINK TO SETTINGS* to set a timeout manually to reduce billing charges."); + return await t.json(); + } catch (e) { + throw Error(e.message); + } +} +var mt = [ + "cpu-basic", + "cpu-upgrade", + "cpu-xl", + "t4-small", + "t4-medium", + "a10g-small", + "a10g-large", + "a10g-largex2", + "a10g-largex4", + "a100-large", + "zero-a10g", + "h100", + "h100x8" +]; +//#endregion +//#region src/utils/duplicate.ts +async function ht(e, t) { + B(t); + let { token: n, private: r, hardware: i, timeout: a, auth: o } = t; + if (i && !mt.includes(i)) throw Error(`Invalid hardware type provided. Valid types are: ${mt.map((e) => `"${e}"`).join(",")}.`); + let { http_protocol: s, host: c } = await Pe(e, n), l = null; + if (o) { + let e = await Ae(s, c, o, fetch, void 0, t.credentials); + e && (l = je(e)); + } + let u = { + Authorization: `Bearer ${n}`, + "Content-Type": "application/json", + ...l ? { Cookie: l.join("; ") } : {} + }, d = (await (await fetch("https://huggingface.co/api/whoami-v2", { headers: u })).json()).name, f = e.split("/")[1], p = { repository: `${d}/${f}` }; + r && (p.private = !0); + let m; + try { + i || (m = await ft(e, n)); + } catch (e) { + throw Error(I + e.message); + } + p.hardware = i || m || "cpu-basic"; + try { + let r = await fetch(`https://huggingface.co/api/spaces/${e}/duplicate`, { + method: "POST", + headers: u, + body: JSON.stringify(p) + }); + if (r.status === 409) try { + return await Q.connect(`${d}/${f}`, t); + } catch (e) { + throw console.error("Failed to connect Client instance:", e), e; + } + else if (r.status !== 200) throw Error(r.statusText); + let i = await r.json(); + return await pt(`${d}/${f}`, a || 300, n), await Q.connect(gt(i.url), t); + } catch (e) { + throw Error(e); + } +} +function gt(e) { + let t = e.match(/https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/); + if (t) return t[1]; +} +//#endregion +//#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/deps/jsr.io/@std/streams/0.221.0/text_line_stream.js +var _t = class extends TransformStream { + #e = ""; + constructor(e = { allowCR: !1 }) { + super({ + transform: (t, n) => { + for (t = this.#e + t;;) { + let r = t.indexOf("\n"), i = e.allowCR ? t.indexOf("\r") : -1; + if (i !== -1 && i !== t.length - 1 && (r === -1 || r - 1 > i)) { + n.enqueue(t.slice(0, i)), t = t.slice(i + 1); + continue; + } + if (r === -1) break; + let a = t[r - 1] === "\r" ? r - 1 : r; + n.enqueue(t.slice(0, a)), t = t.slice(r + 1); + } + this.#e = t; + }, + flush: (t) => { + if (this.#e === "") return; + let n = e.allowCR && this.#e.endsWith("\r") ? this.#e.slice(0, -1) : this.#e; + t.enqueue(n); + } + }); + } +}; +//#endregion +//#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/utils.js +function vt(e) { + let t = new TextDecoderStream(), n = new _t({ allowCR: !0 }); + return e.pipeThrough(t).pipeThrough(n); +} +function yt(e) { + let t = /[:]\s*/.exec(e), n = t && t.index; + if (n) return [e.substring(0, n), e.substring(n + t[0].length)]; +} +function bt(e, t, n) { + e.get(t) || e.set(t, n); +} +//#endregion +//#region ../../node_modules/.pnpm/fetch-event-stream@0.1.6/node_modules/fetch-event-stream/esm/mod.js +async function* xt(e, t) { + if (!e.body) return; + let n = vt(e.body), r, i = n.getReader(), a; + for (;;) { + if (t && t.aborted) return i.cancel(); + if (r = await i.read(), r.done) return; + if (!r.value) { + a && (yield a), a = void 0; + continue; + } + let [e, n] = yt(r.value) || []; + e === "data" ? (a ||= {}, a[e] = a[e] ? a[e] + "\n" + n : n) : e === "event" ? (a ||= {}, a[e] = n) : e === "id" ? (a ||= {}, a[e] = String(+n) === n ? +n : n) : e === "retry" && (a ||= {}, a[e] = +n || void 0); + } +} +async function St(e, t) { + let n = new Request(e, t); + bt(n.headers, "Accept", "text/event-stream"), bt(n.headers, "Content-Type", "application/json"); + let r = await fetch(n); + if (!r.ok) throw r; + return xt(r, n.signal); +} +//#endregion +//#region src/utils/stream.ts +async function Ct() { + let { event_callbacks: e, unclosed_events: t, pending_stream_messages: n, stream_status: r, config: i, jwt: a } = this, o = this; + if (!i) throw Error("Could not resolve app config"); + r.open = !0; + let s = null, c = new URLSearchParams({ session_hash: this.session_hash }).toString(), l = new URL(`${i.root}${this.api_prefix}/${ce}?${c}`); + if (a && l.searchParams.set("__sign", a), s = this.stream(l), !s) { + console.warn("Cannot connect to SSE endpoint: " + l.toString()); + return; + } + s.onmessage = async function(a) { + let s = JSON.parse(a.data); + if (s.msg === "close_stream") { + wt(r, o.abort_controller); + return; + } + let c = s.event_id; + if (!c) await Promise.all(Object.keys(e).map((t) => e[t](s))); + else if (e[c] && i) { + s.msg === "process_completed" && [ + "sse", + "sse_v1", + "sse_v2", + "sse_v2.1", + "sse_v3" + ].includes(i.protocol) && t.delete(c); + let n = e[c]; + typeof window < "u" && typeof document < "u" && document.visibilityState !== "hidden" ? setTimeout(n, 0, s) : n(s); + } else n[c] || (n[c] = []), n[c].push(s); + }, s.onerror = async function(t) { + console.error(t), await Promise.all(Object.keys(e).map((t) => e[t]({ + msg: "broken_connection", + message: M + }))); + }; +} +function wt(e, t) { + e && (e.open = !1, t?.abort()); +} +function Tt(e, t, n) { + e[t] ? n.data.forEach((r, i) => { + let a = Et(i < e[t].length ? e[t][i] : null, r); + e[t][i] = a, n.data[i] = a; + }) : (e[t] = [], n.data.forEach((n, r) => { + e[t][r] = n; + })); +} +function Et(e, t) { + return t.forEach(([t, n, r]) => { + e = Dt(e, n, t, r); + }), e; +} +function Dt(e, t, n, r) { + if (t.length === 0) { + if (n === "replace") return r; + if (n === "append") return e + r; + throw Error(`Unsupported action: ${n}`); + } + let i = e; + for (let e = 0; e < t.length - 1; e++) i = i[t[e]]; + let a = t[t.length - 1]; + switch (n) { + case "replace": + i[a] = r; + break; + case "append": + i[a] += r; + break; + case "add": + Array.isArray(i) ? i.splice(Number(a), 0, r) : i[a] = r; + break; + case "delete": + Array.isArray(i) ? i.splice(Number(a), 1) : delete i[a]; + break; + default: throw Error(`Unknown action: ${n}`); + } + return e; +} +function Ot(e, t = {}) { + let n = { + close: () => { + console.warn("Method not implemented."); + }, + onerror: null, + onmessage: null, + onopen: null, + readyState: 0, + url: e.toString(), + withCredentials: !1, + CONNECTING: 0, + OPEN: 1, + CLOSED: 2, + addEventListener: () => { + throw Error("Method not implemented."); + }, + dispatchEvent: () => { + throw Error("Method not implemented."); + }, + removeEventListener: () => { + throw Error("Method not implemented."); + } + }; + return St(e, t).then(async (e) => { + n.readyState = n.OPEN; + try { + for await (let t of e) n.onmessage && n.onmessage(t); + n.readyState = n.CLOSED; + } catch (e) { + n.onerror && n.onerror(e), n.readyState = n.CLOSED; + } + }).catch((e) => { + e?.name !== "AbortError" && console.error(e), n.onerror && n.onerror(e), n.readyState = n.CLOSED; + }), n; +} +//#endregion +//#region src/utils/run_history.ts +var kt = "gradio:run-history:", K = `${kt}v2:`, At = `${kt}replay:v2:`, jt = `${kt}destination:v1:`, Mt = 100, Nt = 8; +function q(e, t) { + try { + return e(); + } catch (e) { + return console.warn("Could not update the run history.", e), t; + } +} +function Pt(e, t = "/gradio_api") { + return `${e.replace(/\/+$/, "")}${t}/runs`; +} +var Ft = new Set(["tick", "load"]); +function It(e, t, n) { + if (n == null) return !1; + let r = t; + for (let t = 0; t < 100 && r.trigger_after != null; t++) { + let t = e.find((e) => e.id === r.trigger_after); + if (!t) break; + r = t; + } + let i = r.targets.filter(([e]) => e === n).map(([, e]) => e); + return i.length > 0 && i.every((e) => Ft.has(e)); +} +function J(e) { + if (typeof window > "u") return null; + let t = e?.app_id; + if (t == null || t === "") return null; + try { + return window.localStorage ? `${K}${t}${e?.username ? `:user:${encodeURIComponent(e.username)}` : ""}` : null; + } catch { + return null; + } +} +function Lt(e) { + let t = J(e); + return t ? t.replace(K, At) : null; +} +function Rt(e) { + let t = J(e); + return t ? t.replace(K, jt) : null; +} +function zt(e) { + let t = Rt(e); + if (!t) return { type: "browser" }; + try { + let e = JSON.parse(window.localStorage.getItem(t) || "null"); + return typeof e?.bucket_id == "string" ? e.type === "bucket" ? { + type: "bucket", + bucket_id: e.bucket_id + } : { + type: "browser", + bucket_id: e.bucket_id + } : { type: "browser" }; + } catch { + return { type: "browser" }; + } +} +function Bt(e, t) { + let n = Rt(e); + n && (t.type === "browser" && !t.bucket_id ? window.localStorage.removeItem(n) : window.localStorage.setItem(n, JSON.stringify(t)), Jt()); +} +function Vt(e) { + try { + let t = JSON.parse(window.localStorage.getItem(e) || "[]"); + return Array.isArray(t) && t.length && Date.parse(t[0]?.started_at) || 0; + } catch { + return 0; + } +} +function Ht(e) { + let t = Object.keys(window.localStorage).filter((e) => e.startsWith(kt)), n = [...t.filter((e) => !e.startsWith(K) && !e.startsWith(At) && !e.startsWith(jt)), ...t.filter((t) => t.startsWith(K) && t !== e).sort((e, t) => Vt(t) - Vt(e)).slice(Nt - 1)]; + for (let e of n) try { + window.localStorage.removeItem(e), window.sessionStorage.removeItem(e.replace(K, At)); + } catch {} +} +function Ut() { + return typeof crypto < "u" && crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`; +} +function Y(e) { + let t = /* @__PURE__ */ new WeakSet(); + try { + return JSON.parse(JSON.stringify(e, (e, n) => { + if (typeof n == "bigint") return n.toString(); + if (typeof n == "object" && n) { + if (t.has(n)) return "[Circular]"; + t.add(n); + } + return n; + })); + } catch { + return "[Unserializable value]"; + } +} +function X(e) { + let t = J(e); + if (!t) return []; + try { + let e = JSON.parse(window.localStorage.getItem(t) || "[]"); + return Array.isArray(e) ? e : []; + } catch { + return []; + } +} +function Wt(e, t) { + let n = J(e); + if (!n) return; + let r = t.slice(0, Mt), i = !1; + for (; r.length > 0;) try { + window.localStorage.setItem(n, JSON.stringify(r)); + return; + } catch { + if (!i) { + i = !0, Ht(n); + continue; + } + r = r.slice(0, -1); + } + try { + window.localStorage.removeItem(n); + } catch {} +} +function Gt(e) { + let t = J(e); + if (t) { + try { + window.localStorage.removeItem(t); + } catch {} + Jt(); + } +} +function Kt(e, t) { + Wt(e, X(e).filter((e) => e.id !== t)), Jt(); +} +var qt = "gradio:run-history-change"; +function Jt() { + if (!(typeof window > "u")) try { + window.dispatchEvent(new Event(qt)); + } catch {} +} +function Yt(e) { + return typeof window > "u" ? () => {} : (window.addEventListener(qt, e), window.addEventListener("storage", e), () => { + window.removeEventListener(qt, e), window.removeEventListener("storage", e); + }); +} +function Xt(e, t) { + let n = Lt(e); + if (n) try { + window.sessionStorage.setItem(n, JSON.stringify(t)); + } catch {} +} +function Zt(e) { + let t = Lt(e); + if (!t) return null; + try { + let e = window.sessionStorage.getItem(t); + return window.sessionStorage.removeItem(t), e ? JSON.parse(e) : null; + } catch { + return null; + } +} +function Qt(e, t) { + let n = e.dependencies.find((e) => e.id === t.fn_index || typeof e.api_name == "string" && `/${e.api_name.replace(/^\//, "")}` === t.api_name); + if (!n) return !1; + let r = Array.isArray(t.inputs) ? t.inputs : Object.values(t.inputs ?? {}), i = Array.isArray(t.outputs) ? t.outputs : t.outputs === null || t.outputs === void 0 ? [] : [t.outputs], a = (t, n) => { + for (let [r, i] of t.entries()) { + let t = e.components.find((e) => e.id === i); + !t || r >= n.length || t.type !== "state" && (t.props.value = n[r]); + } + }; + return a(n.inputs, r), a(n.outputs, i), !0; +} +function $t(e) { + let t = Zt(e); + return t ? Qt(e, t) : !1; +} +function en(e) { + if (zt(e).type === "bucket") return null; + let t = J(e); + if (!t) return null; + Ht(t); + let n = { + id: Ut(), + endpoint: e.endpoint, + api_name: e.api_name, + fn_index: e.fn_index, + page: `${window.location.pathname}${window.location.search}`, + inputs: Y(e.inputs), + outputs: null, + ...e.input_components ? { input_components: Y(e.input_components) } : {}, + ...e.output_components ? { output_components: Y(e.output_components) } : {}, + status: "running", + started_at: (/* @__PURE__ */ new Date()).toISOString() + }; + return Wt(e, [n, ...X(e)]), Jt(), n.id; +} +function tn(e, t, n) { + if (!t) return; + let r = X(e), i = r.find((e) => e.id === t); + i && (i.inputs = Y(n), Wt(e, r)); +} +function nn(e, t, n) { + if (!t) return; + let r = X(e), i = r.find((e) => e.id === t); + if (!i) return; + let a = !1; + if (n.type === "data") i.outputs = Y(n.data), Z.set(t, i.outputs); + else if (n.type === "status" && n.original_msg === "process_starts") on(i, n.time); + else if (n.type === "status" && (n.stage === "generating" || n.stage === "streaming")) i.streamed = !0; + else if (n.type === "status" && n.stage === "complete") i.status = "completed", sn(i, n), a = !0; + else if (n.type === "status" && n.stage === "error") i.status = "failed", i.error = typeof n.message == "string" ? n.message : JSON.stringify(n.message || "Unknown error"), sn(i, n), a = !0; + else return; + if (a) Z.has(t) && (i.outputs = Z.get(t)), Z.delete(t), an.delete(t); + else if (i.streamed) { + if (Date.now() - (an.get(t) ?? 0) < rn) return; + an.set(t, Date.now()), Z.delete(t); + } + Wt(e, r); +} +var rn = 500, an = /* @__PURE__ */ new Map(), Z = /* @__PURE__ */ new Map(); +function on(e, t) { + if (e.process_started_at) return; + let n = t || /* @__PURE__ */ new Date(); + e.process_started_at = n.toISOString(), e.queued_ms = Math.max(0, n.getTime() - Date.parse(e.started_at)); +} +function sn(e, t) { + let n = t.time || /* @__PURE__ */ new Date(); + e.completed_at = n.toISOString(), e.duration_ms = (!e.streamed && typeof t.cache_duration == "number" && t.cache_duration >= 0 ? t.cache_duration * 1e3 : null) ?? Math.max(0, n.getTime() - Date.parse(e.process_started_at || e.started_at)); +} +function cn(e, t, n) { + return q(() => It(e, t, n), !1); +} +function ln(e) { + return q(() => X(e), []); +} +function un(e) { + return q(() => zt(e), { type: "browser" }); +} +function dn(e, t) { + q(() => Bt(e, t), void 0); +} +function fn(e) { + q(() => Gt(e), void 0); +} +function pn(e, t) { + q(() => Kt(e, t), void 0); +} +function mn(e, t) { + q(() => Xt(e, t), void 0); +} +function hn(e) { + return q(() => Zt(e), null); +} +function gn(e) { + return q(() => $t(e), !1); +} +function _n(e) { + return q(() => en(e), null); +} +function vn(e, t, n) { + q(() => tn(e, t, n), void 0); +} +function yn(e, t, n) { + q(() => nn(e, t, n), void 0); +} +function bn(e) { + return q(() => Yt(() => q(e, void 0)), () => {}); +} +//#endregion +//#region src/utils/submit.ts +function xn(e, t = {}, n, r, i, a) { + try { + let { token: o } = this.options, { fetch: s, app_reference: c, config: l, session_hash: u, api_info: d, api_map: p, stream_status: m, pending_stream_messages: h, pending_diff_streams: ee, event_callbacks: g, unclosed_events: _, post_data: v, options: y, api_prefix: b } = this, x = a || { "x-gradio-user": "api" }, te = this; + if (!d) throw Error(xe); + if (!l) throw Error("Could not resolve app config"); + let ne = l.root; + this.open_heartbeat(); + let { fn_index: S, endpoint_info: C, dependency: w } = Cn(d, e, p, l), re = Be(t, C), T = l.protocol ?? "ws"; + if (T === "ws") throw Error(Se); + let E = typeof w.api_name == "string" ? `/${w.api_name}` : e, ie = typeof w.api_name == "string" ? `/${w.api_name}` : `Function ${S}`, ae = (e) => { + let t = l.components.find((t) => t.id === e); + return t ? { + type: t.type, + component_class_id: t.component_class_id, + props: t.props + } : null; + }, oe = w.api_visibility === "public", se = new Set(w.targets.filter(([, e]) => e === "stream").map(([e]) => e)), D = (e) => e.map((e, t) => se.has(w.inputs[t]) ? null : e), ue = l.run_history !== !1 && this.options.record_history !== !1, O = { + app_id: l.app_id, + username: l.username + }, de = un(O), fe = { + ...x, + ...ue && de.type === "bucket" ? { "x-gradio-history-bucket": de.bucket_id } : {} + }, k = !ue || !oe || cn(l.dependencies, w, r) ? null : _n({ + ...O, + endpoint: E, + api_name: ie, + fn_index: S, + inputs: D(W(re, w, l.components, "input", !0)), + input_components: w.inputs.map(ae), + output_components: w.outputs.map(ae) + }), pe = "", A, j = "", N = typeof e == "number" ? "/predict" : e, P, F = null, I = !1, _e = {}, L = typeof window < "u" && typeof document < "u" ? new URLSearchParams(window.location.search).toString() : "", ve = y?.events?.reduce((e, t) => (e[t] = !0, e), {}) || {}; + function R(e) { + yn(O, k, e), (e.type === "data" || e.type === "render") && tt(e.data, ne, b, te.jwt), (i || ve[e.type]) && Oe(e); + } + async function ye() { + let e = {}, t = {}; + e = { event_id: F }, t = { + event_id: F, + session_hash: u, + fn_index: S + }; + try { + if (!l) throw Error("Could not resolve app config"); + "event_id" in t && await s(`${l.root}${b}/${he}`, { + headers: { "Content-Type": "application/json" }, + method: "POST", + body: JSON.stringify(t) + }), await s(`${l.root}${b}/${me}`, { + headers: { "Content-Type": "application/json" }, + method: "POST", + body: JSON.stringify(e) + }); + } catch { + console.warn("The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."); + } + } + let be = async (e) => { + await this._resolve_heartbeat(e); + }; + async function Ce(e) { + if (!l) return; + let t = e.render_id; + l.components = [...l.components.filter((e) => e.props.rendered_in !== t), ...e.components], l.dependencies = [...l.dependencies.filter((e) => e.rendered_in !== t), ...e.dependencies]; + let n = l.components.some((e) => e.type === "state"), r = l.dependencies.some((e) => e.targets.some((e) => e[1] === "unload")); + l.connect_heartbeat = n || r, await be(l), R({ + type: "render", + data: e, + endpoint: N, + fn_index: S + }); + } + let z = this.handle_blob(l.root, re, C).then(async (e) => { + let t = W(e, w, l.components, "input", !0); + if (vn(O, k, D(t || [])), P = { + data: t || [], + event_data: n, + fn_index: S, + trigger_id: r, + ...y.oauth_token && C?.oauth_token ? { oauth_token: y.oauth_token } : {} + }, Ze(S, l)) R({ + type: "status", + endpoint: N, + stage: "pending", + queue: !1, + fn_index: S, + time: /* @__PURE__ */ new Date() + }), v(`${l.root}${b}/run${N.startsWith("/") ? N : `/${N}`}${L ? "?" + L : ""}`, { + ...P, + session_hash: u + }, fe).then(async ([e, t]) => { + let i = e.data; + if (t == 200) R({ + type: "data", + endpoint: N, + fn_index: S, + data: W(i, w, l.components, "output", y.with_null_state), + time: /* @__PURE__ */ new Date(), + event_data: n, + trigger_id: r + }), e.render_config && await Ce(e.render_config), R({ + type: "status", + endpoint: N, + fn_index: S, + stage: "complete", + eta: e.average_duration, + queue: !1, + time: /* @__PURE__ */ new Date() + }); + else { + let t = e?.error === M; + R({ + type: "status", + stage: "error", + endpoint: N, + fn_index: S, + message: e.error, + broken: t, + queue: !1, + time: /* @__PURE__ */ new Date() + }); + } + }).catch((e) => { + R({ + type: "status", + stage: "error", + message: e.message, + endpoint: N, + fn_index: S, + queue: !1, + time: /* @__PURE__ */ new Date() + }); + }); + else if (T == "sse") { + R({ + type: "status", + stage: "pending", + queue: !0, + endpoint: N, + fn_index: S, + time: /* @__PURE__ */ new Date() + }); + var i = new URLSearchParams({ + fn_index: S.toString(), + session_hash: u + }).toString(); + let e = new URL(`${l.root}${b}/${ce}?${L ? L + "&" : ""}${i}`); + if (this.jwt && e.searchParams.set("__sign", this.jwt), A = this.stream(e), !A) return Promise.reject(/* @__PURE__ */ Error("Cannot connect to SSE endpoint: " + e.toString())); + A.onmessage = async function(e) { + let { type: t, status: i, data: a } = ze(JSON.parse(e.data), _e[S]); + if (t === "update" && i && !I) R({ + type: "status", + endpoint: N, + fn_index: S, + time: /* @__PURE__ */ new Date(), + ...i + }), i.stage === "error" && (A?.close(), V()); + else if (t === "data") { + let [e, t] = await v(`${l.root}${b}/queue/data`, { + ...P, + session_hash: u, + event_id: F + }, fe); + t !== 200 && (R({ + type: "status", + stage: "error", + message: M, + queue: !0, + endpoint: N, + fn_index: S, + time: /* @__PURE__ */ new Date() + }), A?.close(), V()); + } else t === "complete" ? I = i : t === "log" ? R({ + type: "log", + title: a.title, + log: a.log, + level: a.level, + endpoint: N, + duration: a.duration, + visible: a.visible, + fn_index: S + }) : (t === "generating" || t === "streaming") && R({ + type: "status", + time: /* @__PURE__ */ new Date(), + ...i, + stage: i?.stage, + queue: !0, + endpoint: N, + fn_index: S + }); + a && (R({ + type: "data", + time: /* @__PURE__ */ new Date(), + data: W(a.data, w, l.components, "output", y.with_null_state), + endpoint: N, + fn_index: S, + event_data: n, + trigger_id: r + }), I && (R({ + type: "status", + time: /* @__PURE__ */ new Date(), + ...I, + stage: i?.stage, + queue: !0, + endpoint: N, + fn_index: S + }), A?.close(), V())); + }; + } else if (T == "sse_v1" || T == "sse_v2" || T == "sse_v2.1" || T == "sse_v3") { + R({ + type: "status", + stage: "pending", + queue: !0, + endpoint: N, + fn_index: S, + time: /* @__PURE__ */ new Date() + }); + let e = ""; + typeof window < "u" && typeof document < "u" && (e = window?.location?.hostname); + let t = f(e); + return (typeof window < "u" && typeof document < "u" && window.parent != window && t && window.supports_zerogpu_headers ? Qe("zerogpu-headers", t) : Promise.resolve(null)).then((e) => { + let t = { + ...fe, + ...e || {} + }; + return v(`${l.root}${b}/${le}?${L}`, { + ...P, + session_hash: u + }, t); + }).then(async ([e, t]) => { + if (e.event_id && (j = e.event_id), t === 503) R({ + type: "status", + stage: "error", + message: ge, + queue: !0, + endpoint: N, + fn_index: S, + time: /* @__PURE__ */ new Date(), + visible: !0 + }), V(); + else if (t === 422) R({ + type: "status", + stage: "error", + message: e.detail, + queue: !0, + endpoint: N, + fn_index: S, + code: "validation_error", + time: /* @__PURE__ */ new Date(), + visible: !0 + }), V(); + else if (t !== 200) { + let t = e?.error === M; + R({ + type: "status", + stage: "error", + broken: t, + message: t ? M : e.detail || e.error, + queue: !0, + endpoint: N, + fn_index: S, + time: /* @__PURE__ */ new Date(), + visible: !0 + }), V(); + } else { + F = e.event_id, j = F; + let t = async function(e) { + try { + let { type: t, status: n, data: r, original_msg: i } = ze(e, _e[S]); + if (t == "heartbeat") return; + if (t === "update" && n && !I) R({ + type: "status", + endpoint: N, + fn_index: S, + time: /* @__PURE__ */ new Date(), + original_msg: i, + ...n + }); + else if (t === "complete") I = n; + else if (t == "unexpected_error" || t == "broken_connection") { + console.error("Unexpected error", n?.message); + let e = t === "broken_connection"; + R({ + type: "status", + stage: "error", + message: n?.message || "An Unexpected Error Occurred!", + queue: !0, + endpoint: N, + broken: e, + session_not_found: n?.session_not_found, + fn_index: S, + time: /* @__PURE__ */ new Date() + }); + } else if (t === "log") { + R({ + type: "log", + title: r.title, + log: r.log, + level: r.level, + endpoint: N, + duration: r.duration, + visible: r.visible, + fn_index: S + }); + return; + } else (t === "generating" || t === "streaming") && (R({ + type: "status", + time: /* @__PURE__ */ new Date(), + ...n, + stage: n?.stage, + queue: !0, + endpoint: N, + fn_index: S + }), r && w.connection !== "stream" && [ + "sse_v2", + "sse_v2.1", + "sse_v3" + ].includes(T) && Tt(ee, F, r)); + r && (R({ + type: "data", + time: /* @__PURE__ */ new Date(), + data: W(r.data, w, l.components, "output", y.with_null_state), + endpoint: N, + fn_index: S + }), r.render_config && await Ce(r.render_config), I && (R({ + type: "status", + time: /* @__PURE__ */ new Date(), + ...I, + stage: n?.stage, + queue: !0, + endpoint: N, + fn_index: S + }), V())), (n?.stage === "complete" || n?.stage === "error") && (g[F] && delete g[F], F in ee && delete ee[F], V()); + } catch (e) { + console.error("Unexpected client exception", e), R({ + type: "status", + stage: "error", + message: "An Unexpected Error Occurred!", + queue: !0, + endpoint: N, + fn_index: S, + time: /* @__PURE__ */ new Date() + }), [ + "sse_v2", + "sse_v2.1", + "sse_v3" + ].includes(T) && (wt(m, te.abort_controller), m.open = !1, V()); + } + }; + F in h && (h[F].forEach((e) => t(e)), delete h[F]), g[F] = t, _.add(F), m.open || await this.open_stream(); + } + }); + } + }); + z.catch((e) => { + R({ + type: "status", + stage: "error", + message: e instanceof Error ? e.message : String(e), + queue: !Ze(S, l), + endpoint: N, + fn_index: S, + time: /* @__PURE__ */ new Date() + }), V(); + }); + let we = !1, Te = [], B = []; + function V() { + for (we = !0; B.length > 0;) B.shift()({ + value: void 0, + done: !0 + }); + } + function Ee(e) { + B.length > 0 ? B.shift()(e) : Te.push(e); + } + function De(e) { + Ee(Sn(e)), V(); + } + function Oe(e) { + Ee({ + value: e, + done: !1 + }); + } + function ke() { + return Te.length > 0 ? Promise.resolve(Te.shift()) : we ? Promise.resolve({ + value: void 0, + done: !0 + }) : new Promise((e) => B.push(e)); + } + let Ae = (e, t) => { + z.then(() => { + j && this.post_data(`${l.root}${b}/stream/${j}${e}`, t); + }, () => {}); + }, H = { + [Symbol.asyncIterator]: () => H, + next: ke, + throw: async (e) => (De(e), ke()), + return: async () => (V(), { + value: void 0, + done: !0 + }), + cancel: ye, + send_chunk: (e) => { + Ae("", { + ...e, + session_hash: this.session_hash + }), z.then(() => { + if (!(!k || I)) try { + let t = D(W(e.data, w, l.components, "input", !0)), n = JSON.stringify(t); + if (n === pe) return; + pe = n, vn(O, k, t); + } catch (e) { + console.warn("Could not update the run history.", e); + } + }, () => {}); + }, + close_stream: () => { + V(), Ae("/close", {}); + }, + event_id: () => j, + wait_for_id: async () => (await z, F) + }; + return H; + } catch (e) { + throw console.error("Submit function encountered an error:", e), e; + } +} +function Sn(e) { + return { then: (t, n) => n(e) }; +} +function Cn(e, t, n, r) { + let i, a, o; + if (typeof t == "number") i = t, a = e.unnamed_endpoints[i], o = r.dependencies.find((e) => e.id == t); + else { + let s = t.replace(/^\//, ""); + i = n[s], a = e.named_endpoints[t.trim()] ?? e.named_endpoints[`/${s}`], o = r.dependencies.find((e) => e.id == n[s]); + } + if (typeof i != "number" || !o) { + let e = r.dependencies.filter((e) => e.api_name).map((e) => `"/${e.api_name}"`).join(", "); + throw Error(`No endpoint matching ${JSON.stringify(t)} was found. ` + (e ? `Valid named endpoints are: ${e}. ` : "This app exposes no named endpoints. ") + "An fn_index (number) of an existing dependency can also be used."); + } + return { + fn_index: i, + endpoint_info: a, + dependency: o + }; +} +//#endregion +//#region src/client.ts +var Q = class { + app_reference; + options; + deep_link = null; + page = null; + config; + api_prefix = ""; + api_info; + api_map = {}; + session_hash = Math.random().toString(36).substring(2); + jwt = !1; + last_status = {}; + cookies = null; + stream_status = { open: !1 }; + closed = !1; + pending_stream_messages = {}; + pending_diff_streams = {}; + event_callbacks = {}; + unclosed_events = /* @__PURE__ */ new Set(); + heartbeat_event = null; + heartbeat_controller = null; + heartbeat_wanted = typeof window < "u" && typeof document < "u"; + abort_controller = null; + stream_instance = null; + current_payload; + get_url_config(e = null) { + if (!this.config) throw Error(N); + e === null && (e = window.location.href); + let t = (e) => e.replace(/^\/+|\/+$/g, ""), n = t(new URL(this.config.root).pathname), r = t(new URL(e).pathname), i; + return i = r.startsWith(n) ? t(r.substring(n.length)) : "", this.get_page_config(i); + } + get_page_config(e) { + if (!this.config) throw Error(N); + let t = this.config; + return e in t.page || (e = ""), { + ...t, + current_page: e, + layout: t.page[e].layout, + components: t.components.filter((n) => t.page[e].components.includes(n.id)), + dependencies: this.config.dependencies.filter((n) => t.page[e].dependencies.includes(n.id)) + }; + } + fetch(e, t) { + let n = new Headers(t?.headers || {}); + return this && this.cookies && n.append("Cookie", this.cookies), this && this.options.headers && new Headers(this.options.headers).forEach((e, t) => { + n.append(t, e); + }), fetch(e, { + ...t, + headers: n + }); + } + stream(e, t) { + let n = new Headers(); + return this && this.cookies && n.append("Cookie", this.cookies), this && this.options.headers && new Headers(this.options.headers).forEach((e, t) => { + n.append(t, e); + }), this && this.options.token && n.append("Authorization", `Bearer ${this.options.token}`), t || (t = new AbortController(), this.abort_controller = t), this.stream_instance = Ot(e.toString(), { + credentials: this.options.credentials ?? "same-origin", + headers: n, + signal: t.signal + }), this.stream_instance; + } + view_api; + upload_files; + upload; + handle_blob; + post_data; + submit; + predict; + open_stream; + resolve_config; + resolve_cookies; + constructor(e, t = { events: ["data"] }) { + this.app_reference = e, this.deep_link = t.query_params?.deep_link || null, this.page = t.query_params?.page ?? null, t.events ||= ["data"], B(t), this.options = t, this.current_payload = {}, t.cookies && (this.cookies = t.cookies), this.view_api = Ve.bind(this), this.upload_files = He.bind(this), this.handle_blob = rt.bind(this), this.post_data = st.bind(this), this.submit = xn.bind(this), this.predict = ct.bind(this), this.open_stream = Ct.bind(this), this.resolve_config = De.bind(this), this.resolve_cookies = ke.bind(this), this.upload = Ge.bind(this), this.fetch = this.fetch.bind(this), this.handle_space_success = this.handle_space_success.bind(this), this.stream = this.stream.bind(this); + } + async init() { + p(), w(this.app_reference), this.options.auth && await this.resolve_cookies(), await this._resolve_config().then((e) => e?.config && this._resolve_heartbeat(e.config)); + try { + this.api_info = await this.view_api(); + } catch (e) { + console.error(e.message); + } + this.api_map = V(this.config?.dependencies || []); + } + async _resolve_heartbeat(e) { + this.config = e, this.api_prefix = e.api_prefix || "", w(e.root, e.version), e.space_id && this.options.token && (this.jwt = await Te(e.space_id, this.options.token, this.cookies)), nt(this.config, this.jwt), this.heartbeat_wanted && this.open_heartbeat(); + } + open_heartbeat() { + if (this.heartbeat_wanted = !0, !this.config?.connect_heartbeat || this.heartbeat_event) return; + let e = new URL(`${this.config.root}${this.api_prefix}/${pe}/${this.session_hash}`); + this.jwt && e.searchParams.set("__sign", this.jwt), this.heartbeat_controller = new AbortController(), this.heartbeat_event = this.stream(e, this.heartbeat_controller); + } + static async connect(e, t = { events: ["data"] }) { + let n = new this(e, t); + return t.session_hash && (n.session_hash = t.session_hash), await n.init(), n; + } + async reconnect() { + let e = new URL(`${this.config.root}${this.api_prefix}/${j}`), t; + try { + let n = await this.fetch(e); + if (!n.ok) throw Error(); + t = (await n.json()).app_id; + } catch { + return "broken"; + } + return t === this.config.app_id ? "connected" : "changed"; + } + close() { + this.closed = !0, wt(this.stream_status, this.abort_controller), this.heartbeat_controller?.abort(), this.heartbeat_controller = null, this.heartbeat_event = null; + } + async refresh() { + if (!this.config) throw Error(N); + let e = await this.resolve_config(this.config.root, !1); + if (!e) throw Error(N); + this.config = e, this.api_prefix = e.api_prefix || "", this.api_map = V(e.dependencies || []), nt(this.config, this.jwt); + try { + this.api_info = await this.view_api(); + } catch (e) { + console.error(F + e.message); + } + return this.get_url_config(); + } + set_current_payload(e) { + this.current_payload = e; + } + static async duplicate(e, t = { events: ["data"] }) { + return ht(e, t); + } + async _resolve_config() { + let { http_protocol: e, host: t, space_id: n } = await Pe(this.app_reference, this.options.token), { status_callback: r } = this.options; + n && r && await lt(n, r); + let i; + try { + let n = `${e}//${t}`; + if (i = await this.resolve_config(n), !i) throw Error(N); + return this.config_success(i); + } catch (e) { + if (n && r) G(n, Me.test(n) ? "space_name" : "subdomain", this.handle_space_success); + else throw r && r({ + status: "error", + message: "Could not load this space.", + load_status: "error", + detail: "NOT_FOUND" + }), e instanceof Error ? e : Error(String(e)); + } + } + async config_success(e) { + if (this.config = e, this.api_prefix = e.api_prefix || "", e.run_history === !1 && fn({ + app_id: e.app_id, + username: e.username + }), this.config.auth_required) return this.prepare_return_obj(); + try { + this.api_info = await this.view_api(); + } catch (e) { + console.error(F + e.message); + } + return this.prepare_return_obj(); + } + async handle_space_success(e) { + if (!this) throw Error(N); + let { status_callback: t } = this.options; + if (t && t(e), e.status === "running") try { + if (this.config = await this._resolve_config(), this.api_prefix = this?.config?.api_prefix || "", !this.config) throw Error(N); + return await this.config_success(this.config); + } catch (e) { + throw t && t({ + status: "error", + message: "Could not load this space.", + load_status: "error", + detail: "NOT_FOUND" + }), e; + } + } + async component_server(e, t, n) { + if (!this.config) throw Error(N); + let r = {}, { token: i } = this.options, { session_hash: a } = this; + i && (r.Authorization = `Bearer ${this.options.token}`); + let o, s = this.config.components.find((t) => t.id === e); + o = s?.props?.root_url ? s.props.root_url : this.config.root; + let c; + if (typeof n == "object" && n && "binary" in n) { + let r = n; + c = new FormData(); + for (let e in r.data) e !== "binary" && c.append(e, r.data[e]); + c.set("component_id", e.toString()), c.set("fn_name", t), c.set("session_hash", a); + } else c = JSON.stringify({ + data: n, + component_id: e, + fn_name: t, + session_hash: a + }), r["Content-Type"] = "application/json"; + i && (r.Authorization = `Bearer ${i}`); + try { + let e = await this.fetch(`${o}${this.api_prefix}/${A}/`, { + method: "POST", + body: c, + headers: r, + credentials: this.options.credentials ?? "same-origin" + }); + if (!e.ok) throw Error("Could not connect to component server: " + e.statusText); + let t = await e.json(); + return tt(t, this.config.root, this.config.api_prefix || "", this.jwt), t; + } catch (e) { + console.warn(e); + } + } + set_cookies(e) { + this.cookies = je(e).join("; "); + } + prepare_return_obj() { + return { + config: this.config, + predict: this.predict, + submit: this.submit, + view_api: this.view_api, + component_server: this.component_server + }; + } +}; +async function wn(e, t = { events: ["data"] }) { + return await Q.connect(e, t); +} +async function Tn(e, t) { + return await Q.duplicate(e, t); +} +//#endregion +//#region src/utils/bucket_sync.ts +var En = /^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-][a-zA-Z0-9_./-]*$/; +function Dn(e) { + return En.test(e) ? !e.split("/").some((e) => e === "" || e === "." || e === "..") : !1; +} +function $(e, t, n) { + let r = n ? `?${new URLSearchParams(n)}` : "", i = e.replace(/\/+$/, ""); + return i ? `${i}/gradio_api/run-history/${t}${r}` : typeof document < "u" && document.baseURI ? new URL(`gradio_api/run-history/${t}${r}`, document.baseURI).toString() : `gradio_api/run-history/${t}${r}`; +} +async function On(e) { + try { + let t = await e.json(); + return typeof t?.detail == "string" ? t.detail : `${e.status}`; + } catch { + return `${e.status}`; + } +} +async function kn(e, t, n, r) { + try { + let i = await fetch(e, { + credentials: "include", + ...t + }); + return i.ok ? { + ok: !0, + status: i.status, + data: r(await i.json()) + } : { + ok: !1, + status: i.status, + data: n, + detail: await On(i) + }; + } catch (e) { + return { + ok: !1, + status: 0, + data: n, + detail: String(e) + }; + } +} +async function An(e, t, n) { + return Dn(t) ? kn($(e, "connect"), { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(n ? { + bucket_id: t, + token: n + } : { bucket_id: t }) + }, null, () => null) : { + ok: !1, + status: 422, + data: null, + detail: "invalid bucket id" + }; +} +async function jn(e) { + return kn($(e, "disconnect"), { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: "{}" + }, null, () => null); +} +async function Mn(e) { + return kn($(e, "buckets"), {}, [], (e) => Array.isArray(e?.buckets) ? e.buckets : []); +} +async function Nn(e, t) { + return kn($(e, "records", { bucket: t }), {}, [], (e) => Array.isArray(e?.records) ? e.records : []); +} +function Pn(e, t, n, r, i) { + return $(e, `records/${encodeURIComponent(n)}/${encodeURIComponent(r)}/assets/${encodeURIComponent(i)}`, { bucket: t }); +} +//#endregion +//#region src/index.ts +re(); +//#endregion +export { Q as Client, U as FileData, R as MISSING_CREDENTIALS_MSG, gn as apply_run_history_replay, Pn as asset_url, fn as clear_run_history, wn as client, An as connect_bucket, hn as consume_run_history_replay, pn as delete_run_history, jn as disconnect_bucket, Tn as duplicate, $e as handle_file, C as initialize_console_forwarding, te as is_console_forward_origin_allowed, Dn as is_valid_bucket_id, Nn as list_bucket_records, Mn as list_user_buckets, bn as on_run_history_change, ct as predict, Ke as prepare_files, ln as read_run_history, un as read_run_history_storage, Pt as run_history_url, dn as set_run_history_storage, mn as stage_run_history_replay, xn as submit, o as t, Ge as upload, He as upload_files };