Algorick commited on
Commit
8af7605
·
verified ·
1 Parent(s): afa3b5c

e889ffbdc138

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +19 -0
  2. .gitignore +4 -0
  3. README.md +21 -7
  4. app.py +364 -0
  5. pixrick/config.py +85 -0
  6. pixrick/core.py +451 -0
  7. pixrick/marking.py +62 -0
  8. pixrick/prompter.py +79 -0
  9. pixrick/runner.py +377 -0
  10. pixrick/safety.py +38 -0
  11. pixrick/templates.json +303 -0
  12. pixrick/vector.py +137 -0
  13. requirements.txt +15 -0
  14. web/app.js +2057 -0
  15. web/backend.js +596 -0
  16. web/fonts/LICENSE-OFL.txt +93 -0
  17. web/fonts/anton-latin-400-normal.woff2 +0 -0
  18. web/fonts/archivo-black-latin-400-normal.woff2 +0 -0
  19. web/fonts/bebas-neue-latin-400-normal.woff2 +0 -0
  20. web/fonts/inter-latin-400-normal.woff2 +0 -0
  21. web/fonts/inter-latin-600-normal.woff2 +0 -0
  22. web/fonts/inter-latin-800-normal.woff2 +0 -0
  23. web/fonts/newsreader-latin-400-italic.woff2 +0 -0
  24. web/fonts/newsreader-latin-400-normal.woff2 +0 -0
  25. web/fonts/newsreader-latin-500-italic.woff2 +0 -0
  26. web/fonts/newsreader-latin-500-normal.woff2 +0 -0
  27. web/fonts/oswald-latin-500-normal.woff2 +0 -0
  28. web/fonts/oswald-latin-700-normal.woff2 +0 -0
  29. web/fonts/permanent-marker-latin-400-normal.woff2 +0 -0
  30. web/fonts/playfair-display-latin-700-normal.woff2 +0 -0
  31. web/fonts/playfair-display-latin-900-normal.woff2 +0 -0
  32. web/guida/PixRick-Guida.pdf +3 -0
  33. web/guida/guida.css +328 -0
  34. web/guida/guida.js +42 -0
  35. web/guida/img/anime-foto.jpg +0 -0
  36. web/guida/img/anime.jpg +3 -0
  37. web/guida/img/app-cinese.jpg +0 -0
  38. web/guida/img/app.jpg +0 -0
  39. web/guida/img/funko.jpg +0 -0
  40. web/guida/img/liutaio.jpg +0 -0
  41. web/guida/img/locandina-lineup.jpg +3 -0
  42. web/guida/img/logo.jpg +0 -0
  43. web/guida/img/miele.jpg +0 -0
  44. web/guida/img/neve.jpg +0 -0
  45. web/guida/img/ritratto.jpg +0 -0
  46. web/guida/img/s-detail.jpg +3 -0
  47. web/guida/img/s-gallery.jpg +3 -0
  48. web/guida/img/s-loc-a.jpg +3 -0
  49. web/guida/img/s-loc-b.jpg +3 -0
  50. web/guida/img/s-loc-c.jpg +3 -0
.gitattributes CHANGED
@@ -33,3 +33,22 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ web/guida/PixRick-Guida.pdf filter=lfs diff=lfs merge=lfs -text
37
+ web/guida/img/anime.jpg filter=lfs diff=lfs merge=lfs -text
38
+ web/guida/img/locandina-lineup.jpg filter=lfs diff=lfs merge=lfs -text
39
+ web/guida/img/s-detail.jpg filter=lfs diff=lfs merge=lfs -text
40
+ web/guida/img/s-gallery.jpg filter=lfs diff=lfs merge=lfs -text
41
+ web/guida/img/s-loc-a.jpg filter=lfs diff=lfs merge=lfs -text
42
+ web/guida/img/s-loc-b.jpg filter=lfs diff=lfs merge=lfs -text
43
+ web/guida/img/s-loc-c.jpg filter=lfs diff=lfs merge=lfs -text
44
+ web/guida/img/s-loc-pick.jpg filter=lfs diff=lfs merge=lfs -text
45
+ web/guida/img/s-ristila.jpg filter=lfs diff=lfs merge=lfs -text
46
+ web/guida/img/s-studio.jpg filter=lfs diff=lfs merge=lfs -text
47
+ web/guida/img/s-tip.jpg filter=lfs diff=lfs merge=lfs -text
48
+ web/guida/img/s-vector.jpg filter=lfs diff=lfs merge=lfs -text
49
+ web/guida/img/s-zona.jpg filter=lfs diff=lfs merge=lfs -text
50
+ web/guida/img/s-zona2.jpg filter=lfs diff=lfs merge=lfs -text
51
+ web/guida/img/soglia.jpg filter=lfs diff=lfs merge=lfs -text
52
+ web/guida/img/st-fumetto.jpg filter=lfs diff=lfs merge=lfs -text
53
+ web/guida/img/tpl-griglia.jpg filter=lfs diff=lfs merge=lfs -text
54
+ web/guida/img/volpe-scontornata.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ node_modules/
README.md CHANGED
@@ -1,14 +1,28 @@
1
  ---
2
- title: Pixrick
3
- emoji: 🌖
4
- colorFrom: yellow
5
- colorTo: gray
6
  sdk: gradio
7
  sdk_version: 6.32.0
8
- python_version: '3.12'
9
  app_file: app.py
 
 
 
 
 
 
 
 
 
10
  pinned: false
11
- short_description: 'Studio di immagini AI: crea, ristila, modifica e componi loc'
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
1
  ---
2
+ title: PixRick
3
+ emoji: 🎞️
4
+ colorFrom: indigo
5
+ colorTo: pink
6
  sdk: gradio
7
  sdk_version: 6.32.0
8
+ python_version: "3.12"
9
  app_file: app.py
10
+ hf_oauth: true
11
+ startup_duration_timeout: 1h
12
+ preload_from_hub:
13
+ - Tongyi-MAI/Z-Image-Turbo
14
+ - black-forest-labs/FLUX.2-klein-4B
15
+ - ZhengPeng7/BiRefNet
16
+ - Qwen/Qwen3-1.7B
17
+ - Falconsai/nsfw_image_detection
18
+ short_description: Studio di immagini AI con Z-Image e FLUX.2 Klein
19
  pinned: false
 
20
  ---
21
 
22
+ # PixRick
23
+
24
+ Studio di immagini AI: crea, ristila, modifica una zona, continua una storia, ingrandisci, scontorna, vettorizza e componi locandine.
25
+
26
+ 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.
27
+
28
+ Ogni immagine generata porta metadati che la dichiarano creata con AI e una filigrana invisibile.
app.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PixRick online: l'interfaccia è nostra, il motore gira su Gradio perché ZeroGPU lo richiede."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ import io
7
+ import json
8
+ import logging
9
+ import os
10
+ import tempfile
11
+ import threading
12
+ import time
13
+ from pathlib import Path
14
+ from typing import Any, Iterator
15
+
16
+ try:
17
+ import spaces
18
+ except ImportError: # in locale, senza ZeroGPU
19
+ spaces = None
20
+
21
+ import gradio as gr
22
+ from fastapi import FastAPI, File, Form, HTTPException, UploadFile
23
+ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
24
+ from fastapi.staticfiles import StaticFiles
25
+ from PIL import Image
26
+
27
+ from pixrick import config, marking, vector
28
+ from pixrick.core import (
29
+ Job,
30
+ JobRequest,
31
+ RequestError,
32
+ TemplateBook,
33
+ clean_image,
34
+ extract_style,
35
+ plan,
36
+ prompt_for,
37
+ source_medium,
38
+ )
39
+ from pixrick.runner import Runner, models
40
+ from pixrick.safety import SafetyError, check_prompt
41
+
42
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s")
43
+ log = logging.getLogger("pixrick")
44
+
45
+ BOOK = TemplateBook.load()
46
+ OUT_DIR = Path(tempfile.gettempdir()) / "pixrick"
47
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
48
+
49
+
50
+ def gpu(duration: Any):
51
+ if spaces is None:
52
+ return lambda fn: fn
53
+ return spaces.GPU(duration=duration)
54
+
55
+
56
+ if not config.FAKE_ENGINE:
57
+ models()
58
+
59
+
60
+ # ---------- motore ----------
61
+
62
+
63
+ def _open(path: str | None) -> Image.Image | None:
64
+ if not path:
65
+ return None
66
+ if os.path.getsize(path) > config.MAX_UPLOAD_BYTES:
67
+ raise RequestError("Immagine troppo pesante (massimo 25 MB).")
68
+ try:
69
+ with Image.open(path) as im:
70
+ im.load()
71
+ return im.copy()
72
+ except Exception as exc: # noqa: BLE001
73
+ raise RequestError("Uno dei file non è un'immagine leggibile.") from exc
74
+
75
+
76
+ def _meta(job: Job, model_key: str, image: Image.Image, seed: int, index: int) -> dict[str, Any]:
77
+ req = job.request
78
+ combo = job.refine and model_key == "z-image" and req.mode != config.REFINE_MODE
79
+ return {
80
+ "lavoro": job.id,
81
+ "modalita": req.mode,
82
+ "prompt": req.prompt,
83
+ "prompt_finale": prompt_for(job, model_key),
84
+ "template": req.templates[0] if req.templates else "libero",
85
+ "stili": req.templates,
86
+ "campi": req.fields,
87
+ "riferimenti": req.refs,
88
+ "maschera": req.mask,
89
+ "formato": req.aspect,
90
+ "larghezza": image.width,
91
+ "altezza": image.height,
92
+ "qualita": req.quality,
93
+ "passi": job.steps[model_key],
94
+ "fedelta": req.fidelity if req.mode == "ristila" and model_key == "z-image" and not job.refine else None,
95
+ "fedelta_auto": job.fidelity_auto,
96
+ "nota": job.note,
97
+ "rifinita": job.refine and model_key == "z-image",
98
+ "seed": seed,
99
+ "modello": model_key,
100
+ "modello_nome": "Klein + Z-Image" if combo
101
+ else "Rifinita con Z-Image" if req.mode == config.REFINE_MODE
102
+ else (config.MODELS.get(model_key) or config.TOOLS[model_key])["nome"],
103
+ "trasparente": image.mode == "RGBA",
104
+ "vista": config.VIEWS[index % len(config.VIEWS)][0] if req.mode == config.VIEWS_MODE else None,
105
+ "creata": time.strftime("%Y-%m-%d %H:%M:%S"),
106
+ "generata_con_ai": True,
107
+ }
108
+
109
+
110
+ def _friendly(exc: BaseException) -> str:
111
+ if isinstance(exc, (RequestError, SafetyError)):
112
+ return str(exc)
113
+ text = str(exc)
114
+ if "out of memory" in text.lower():
115
+ return "La GPU è piena in questo momento. Riprova tra poco o scegli meno immagini."
116
+ log.exception("Lavoro non riuscito", exc_info=exc)
117
+ return "Qualcosa è andato storto durante la generazione. Riprova."
118
+
119
+
120
+ def _estimate(job: Job, *_: Any) -> int:
121
+ return job.gpu_seconds()
122
+
123
+
124
+ @gpu(_estimate)
125
+ def _work(job: Job, refs: list[Image.Image], mask: Image.Image | None, book: TemplateBook) -> Iterator[tuple[dict, list[str]]]:
126
+ runner = Runner(job, refs, mask, book)
127
+ outcome: dict[str, Any] = {}
128
+
129
+ def target() -> None:
130
+ try:
131
+ outcome["images"] = runner.run()
132
+ except BaseException as exc: # noqa: BLE001
133
+ outcome["error"] = exc
134
+
135
+ thread = threading.Thread(target=target, daemon=True)
136
+ thread.start()
137
+ while thread.is_alive():
138
+ thread.join(0.4)
139
+ yield job.public(), []
140
+ if "error" in outcome:
141
+ raise gr.Error(_friendly(outcome["error"]), print_exception=False)
142
+
143
+ folder = OUT_DIR / job.id
144
+ folder.mkdir(parents=True, exist_ok=True)
145
+ files: list[str] = []
146
+ for index, (model_key, image, seed) in enumerate(outcome["images"]):
147
+ meta = _meta(job, model_key, image, seed, index)
148
+ path = folder / f"{index:02d}_{model_key}_{seed}.png"
149
+ path.write_bytes(marking.to_png(image, meta))
150
+ job.results.append(meta)
151
+ files.append(str(path))
152
+ yield job.public(), files
153
+
154
+
155
+ def genera(richiesta: str, immagini: list[str] | None, maschera: str | None) -> Iterator[tuple[dict, list[str]]]:
156
+ """Valida senza GPU (gli errori non costano quota), poi passa il lavoro alla GPU."""
157
+ try:
158
+ data = json.loads(richiesta or "{}")
159
+ if not isinstance(data, dict):
160
+ raise RequestError("Richiesta non valida.")
161
+ book = BOOK.with_user(data.get("stili_utente") or [])
162
+ req = JobRequest.from_payload(data)
163
+ refs = [clean_image(img) for img in (_open(p) for p in (immagini or [])) if img is not None]
164
+ mask = _open(maschera)
165
+ job = plan(req, refs, mask, book)
166
+ except (RequestError, SafetyError, json.JSONDecodeError) as exc:
167
+ raise gr.Error(str(exc) if not isinstance(exc, json.JSONDecodeError) else "Richiesta non valida.", print_exception=False)
168
+ yield job.public(), []
169
+ yield from _work(job, refs, mask, book)
170
+
171
+
172
+ @gpu(30)
173
+ def _write(kind: str, text: str) -> str:
174
+ return models().write(kind, text)
175
+
176
+
177
+ def scrivi(tipo: str, testo: str) -> str:
178
+ """Traduce, migliora o riassume lo stile di un prompt."""
179
+ testo = (testo or "")[: config.MAX_PROMPT_CHARS]
180
+ if tipo not in ("traduci", "migliora", "migliora_modifica", "in_italiano", "stile"):
181
+ raise gr.Error("Operazione non valida.", print_exception=False)
182
+ if not testo.strip():
183
+ return ""
184
+ try:
185
+ check_prompt(testo)
186
+ except SafetyError as exc:
187
+ raise gr.Error(str(exc), print_exception=False)
188
+ try:
189
+ out = _write(tipo, testo)
190
+ if tipo in ("migliora", "migliora_modifica"):
191
+ check_prompt(out)
192
+ return out
193
+ except SafetyError as exc:
194
+ raise gr.Error(str(exc), print_exception=False)
195
+ except Exception as exc: # noqa: BLE001
196
+ raise gr.Error(_friendly(exc), print_exception=False)
197
+
198
+
199
+ ON_SPACES = bool(os.environ.get("SPACE_ID"))
200
+
201
+
202
+ @gpu(40)
203
+ def _improve(text: str, kind: str) -> tuple[str, str]:
204
+ m = models()
205
+ english = m.write(kind, text)
206
+ return english, m.write("in_italiano", english)
207
+
208
+
209
+ def migliora(testo: str, modalita: str) -> dict[str, str]:
210
+ """Da un'idea a un prompt ricco, con la versione italiana da rileggere."""
211
+ testo = (testo or "")[: config.MAX_PROMPT_CHARS]
212
+ if not testo.strip():
213
+ raise gr.Error("Scrivi prima un'idea da migliorare.", print_exception=False)
214
+ try:
215
+ check_prompt(testo)
216
+ english, italian = _improve(testo, "migliora_modifica" if modalita == "modifica" else "migliora")
217
+ check_prompt(english)
218
+ except SafetyError as exc:
219
+ raise gr.Error(str(exc), print_exception=False)
220
+ except Exception as exc: # noqa: BLE001
221
+ raise gr.Error(_friendly(exc), print_exception=False)
222
+ return {"prompt": english, "italiano": italian}
223
+
224
+
225
+ def chi_sono(profile: gr.OAuthProfile | None) -> dict[str, Any]:
226
+ if profile is None:
227
+ return {"accesso": False}
228
+ return {"accesso": True, "nome": profile.name or profile.username, "utente": profile.username}
229
+
230
+
231
+ def chi_sono_locale() -> dict[str, Any]:
232
+ return {"accesso": False, "locale": True}
233
+
234
+
235
+ with gr.Blocks(title="PixRick · motore", analytics_enabled=False, delete_cache=(300, 900)) as motore:
236
+ gr.Markdown("Questo è il motore di PixRick. L'app è nella pagina principale.")
237
+ with gr.Column(visible=False):
238
+ richiesta = gr.Textbox()
239
+ immagini = gr.File(file_count="multiple", type="filepath")
240
+ maschera = gr.File(type="filepath")
241
+ stato = gr.JSON()
242
+ risultati = gr.File(file_count="multiple")
243
+ tipo = gr.Textbox()
244
+ testo = gr.Textbox()
245
+ scritto = gr.Textbox()
246
+ profilo = gr.JSON()
247
+ if ON_SPACES:
248
+ gr.LoginButton()
249
+ go = gr.Button()
250
+ go.click(genera, [richiesta, immagini, maschera], [stato, risultati], api_name="genera", show_progress="hidden")
251
+ gr.Button().click(scrivi, [tipo, testo], scritto, api_name="scrivi", concurrency_limit=4)
252
+ gr.Button().click(migliora, [testo, tipo], profilo, api_name="migliora", concurrency_limit=4)
253
+ gr.Button().click(chi_sono if ON_SPACES else chi_sono_locale, None, profilo, api_name="chi_sono", queue=False)
254
+
255
+ motore.queue(default_concurrency_limit=6, max_size=80)
256
+
257
+
258
+ # ---------- pagina e servizi leggeri (senza GPU) ----------
259
+
260
+ app = FastAPI(title="PixRick", docs_url=None, redoc_url=None, openapi_url=None)
261
+ WEB = config.WEB_DIR
262
+
263
+
264
+ @app.get("/", include_in_schema=False)
265
+ def home() -> FileResponse:
266
+ return FileResponse(WEB / "index.html", headers={"Cache-Control": "no-cache"})
267
+
268
+
269
+ @app.get("/guida", include_in_schema=False)
270
+ @app.get("/guida/", include_in_schema=False)
271
+ def guide() -> FileResponse:
272
+ return FileResponse(WEB / "guida" / "index.html", headers={"Cache-Control": "no-cache"})
273
+
274
+
275
+ REPORT_URL = "https://huggingface.co/spaces/algorick/pixrick/discussions"
276
+
277
+
278
+ def _legal(name: str) -> HTMLResponse:
279
+ owner = html.escape(os.environ.get("PIXRICK_OWNER", "").strip() or "il gestore di PixRick")
280
+ mail = os.environ.get("PIXRICK_CONTACT", "").strip()
281
+ contact = (
282
+ f'<a href="mailto:{html.escape(mail)}">{html.escape(mail)}</a>'
283
+ if mail
284
+ else f'<a href="{REPORT_URL}" target="_blank" rel="noopener">{REPORT_URL.removeprefix("https://")}</a>'
285
+ )
286
+ page = (WEB / "legal" / f"{name}.html").read_text(encoding="utf-8")
287
+ return HTMLResponse(page.replace("{{titolare}}", owner).replace("{{contatto}}", contact))
288
+
289
+
290
+ @app.get("/privacy", include_in_schema=False)
291
+ def privacy() -> HTMLResponse:
292
+ return _legal("privacy")
293
+
294
+
295
+ @app.get("/termini", include_in_schema=False)
296
+ @app.get("/terms", include_in_schema=False)
297
+ def terms() -> HTMLResponse:
298
+ return _legal("termini")
299
+
300
+
301
+ @app.get("/sw.js", include_in_schema=False)
302
+ def service_worker() -> FileResponse:
303
+ return FileResponse(WEB / "sw.js", media_type="text/javascript", headers={"Cache-Control": "no-cache", "Service-Worker-Allowed": "/"})
304
+
305
+
306
+ @app.get("/manifest.webmanifest", include_in_schema=False)
307
+ def manifest() -> FileResponse:
308
+ return FileResponse(WEB / "manifest.webmanifest", media_type="application/manifest+json")
309
+
310
+
311
+ @app.get("/favicon.ico", include_in_schema=False)
312
+ def favicon() -> FileResponse:
313
+ return FileResponse(WEB / "icons" / "favicon.ico")
314
+
315
+
316
+ @app.get("/robots.txt", include_in_schema=False)
317
+ def robots() -> Response:
318
+ return Response("User-agent: *\nAllow: /\nDisallow: /motore/\n", media_type="text/plain")
319
+
320
+
321
+ @app.get("/api/templates")
322
+ def templates() -> JSONResponse:
323
+ return JSONResponse({"template": BOOK.all()}, headers={"Cache-Control": "public, max-age=600"})
324
+
325
+
326
+ @app.post("/api/styles/extract")
327
+ def styles_extract(data: dict[str, Any]) -> JSONResponse:
328
+ text = str(data.get("prompt") or "")[: config.MAX_PROMPT_CHARS]
329
+ book = BOOK.with_user(data.get("stili_utente") or [])
330
+ ids = [str(i) for i in (data.get("stili") or []) if isinstance(i, str)]
331
+ if not text.strip() and not ids:
332
+ raise HTTPException(400, "Questa immagine non ha un prompt da cui partire.")
333
+ return JSONResponse({"testo": extract_style(text, book.clean_ids(ids), book)})
334
+
335
+
336
+ @app.post("/api/vectorize")
337
+ async def vectorize(
338
+ file: UploadFile = File(...), stile: str = Form("colori"), trasparente: bool = Form(True)
339
+ ) -> JSONResponse:
340
+ data = await file.read(config.MAX_UPLOAD_BYTES + 1)
341
+ if len(data) > config.MAX_UPLOAD_BYTES:
342
+ raise HTTPException(413, "Immagine troppo pesante (massimo 25 MB).")
343
+ with tempfile.NamedTemporaryFile(suffix=".png", dir=OUT_DIR) as tmp:
344
+ try:
345
+ with Image.open(io.BytesIO(data)) as im:
346
+ im.load()
347
+ im.save(tmp.name, "PNG")
348
+ medium = source_medium(im)
349
+ result = vector.vectorize(Path(tmp.name), stile, trasparente)
350
+ except Exception as exc: # noqa: BLE001
351
+ log.exception("Vettorizzazione non riuscita")
352
+ raise HTTPException(400, "Non sono riuscito a vettorizzare questa immagine.") from exc
353
+ result["foto"] = medium == "foto"
354
+ return JSONResponse(result)
355
+
356
+
357
+ app.mount("/web", StaticFiles(directory=WEB), name="web")
358
+ app = gr.mount_gradio_app(app, motore, path="/motore", ssr_mode=False)
359
+
360
+
361
+ if __name__ == "__main__":
362
+ import uvicorn
363
+
364
+ uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "7860")))
pixrick/config.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+ ROOT = Path(__file__).resolve().parent.parent
7
+ WEB_DIR = ROOT / "web"
8
+ TEMPLATES_FILE = Path(__file__).resolve().parent / "templates.json"
9
+
10
+ FAKE_ENGINE = os.environ.get("PIXRICK_FAKE") == "1"
11
+
12
+ MAX_BATCH = 4
13
+ MAX_REFS = 4
14
+ MAX_PROMPT_CHARS = 2000
15
+ MAX_UPLOAD_BYTES = 25 * 1024 * 1024
16
+ MAX_INPUT_SIDE = 2048
17
+ TARGET_AREA = 1024 * 1024
18
+ MAX_UPSCALE_SIDE = 2048
19
+
20
+ MODES = ("crea", "ristila", "modifica", "continua")
21
+ VIEWS_MODE = "viste"
22
+ VIEWS = (
23
+ ("Lato sinistro", "Show the exact same figure from its left side: a strict 90-degree side profile view facing left."),
24
+ ("Retro", "Show the exact same figure from behind: a straight back view, the face is not visible."),
25
+ ("Lato destro", "Show the exact same figure from its right side: a strict 90-degree side profile view facing right."),
26
+ )
27
+ VIEWS_KEEP = (
28
+ "Keep the identical design, proportions, colors, materials, hair, clothes, accessories and base. "
29
+ "Full body visible and centered, same plain background, same soft even studio lighting."
30
+ )
31
+
32
+ MODELS: dict[str, dict] = {
33
+ "z-image": {
34
+ "nome": "Z-Image Turbo",
35
+ "repo": "Tongyi-MAI/Z-Image-Turbo",
36
+ "descrizione": "Il più fedele al prompt. Foto realistiche e testo dentro l'immagine.",
37
+ "modalita": ["crea", "ristila"],
38
+ "qualita": {"rapida": 6, "bilanciata": 9, "massima": 14},
39
+ },
40
+ "klein": {
41
+ "nome": "FLUX.2 Klein",
42
+ "repo": "black-forest-labs/FLUX.2-klein-4B",
43
+ "descrizione": "Veloce, stile pulito. L'unico che modifica le foto a comando.",
44
+ "modalita": ["crea", "ristila", "modifica", "continua"],
45
+ "qualita": {"rapida": 4, "bilanciata": 5, "massima": 8},
46
+ },
47
+ }
48
+ TOOLS: dict[str, dict] = {
49
+ "ingrandisci": {"nome": "Z-Image Turbo"},
50
+ "scontorna": {"nome": "BiRefNet", "repo": "ZhengPeng7/BiRefNet"},
51
+ }
52
+ TOOL_MODES = tuple(TOOLS)
53
+ PROMPTER_REPO = "Qwen/Qwen3-1.7B"
54
+ NSFW_REPO = "Falconsai/nsfw_image_detection"
55
+ NSFW_THRESHOLD = 0.6
56
+
57
+ AUTO_MODEL = {"crea": "z-image", "ristila": "z-image", "modifica": "klein", "continua": "klein", "rifinisci": "z-image"}
58
+ REFINE = "klein+z"
59
+ REFINE_MODE = "rifinisci"
60
+ REFINE_FIDELITY = 0.68
61
+ UPSCALE_FIDELITY = 0.78
62
+ REFINE_MODES = ("ristila", "modifica", "continua")
63
+ CONTINUE_PROMPT = (
64
+ "Create a brand-new image that belongs to the same story as image 1: same visual style, rendering, "
65
+ "color palette, lighting mood and world, and the same characters with identical faces, hair and clothes "
66
+ "whenever they appear. Do not copy the composition of image 1. New scene: {prompt}"
67
+ )
68
+ BOTH = "entrambi"
69
+ QUALITIES = ("rapida", "bilanciata", "massima")
70
+
71
+ ASPECTS: dict[str, tuple[int, int]] = {
72
+ "1:1": (1024, 1024),
73
+ "4:5": (896, 1120),
74
+ "3:4": (864, 1152),
75
+ "2:3": (832, 1248),
76
+ "9:16": (768, 1344),
77
+ "16:9": (1344, 768),
78
+ "3:2": (1248, 832),
79
+ }
80
+ DEFAULT_ASPECT = "1:1"
81
+
82
+ # Secondi di GPU stimati per passo, per chiedere a ZeroGPU solo il tempo che serve.
83
+ SECONDS_PER_STEP = {"z-image": 0.35, "klein": 0.3}
84
+ GPU_OVERHEAD = 12
85
+ GPU_MAX_SECONDS = 170
pixrick/core.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Richieste, stili e pianificazione dei lavori. Niente GPU qui: solo regole."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import random
8
+ import re
9
+ import time
10
+ import uuid
11
+ from dataclasses import asdict, dataclass, field
12
+ from typing import Any
13
+
14
+ from PIL import Image, ImageOps
15
+
16
+ from . import config
17
+ from .safety import check_prompt
18
+
19
+ MAX_STYLES = 3
20
+
21
+
22
+ class RequestError(ValueError):
23
+ """Errore da mostrare all'utente così com'è."""
24
+
25
+
26
+ def fit_dims(width: int, height: int) -> tuple[int, int]:
27
+ scale = math.sqrt(config.TARGET_AREA / (width * height))
28
+ w = max(256, int(round(width * scale / 16)) * 16)
29
+ h = max(256, int(round(height * scale / 16)) * 16)
30
+ return w, h
31
+
32
+
33
+ def clean_image(img: Image.Image) -> Image.Image:
34
+ """Ruota secondo l'EXIF, appiattisce la trasparenza su grigio chiaro e limita il lato lungo."""
35
+ img = ImageOps.exif_transpose(img)
36
+ if img.mode in ("RGBA", "LA", "P"):
37
+ rgba = img.convert("RGBA")
38
+ flat = Image.new("RGB", rgba.size, (232, 232, 232))
39
+ flat.paste(rgba, mask=rgba.split()[3])
40
+ img = flat
41
+ else:
42
+ img = img.convert("RGB")
43
+ img.thumbnail((config.MAX_INPUT_SIDE, config.MAX_INPUT_SIDE))
44
+ return img
45
+
46
+
47
+ @dataclass
48
+ class JobRequest:
49
+ prompt: str
50
+ mode: str = "crea"
51
+ model: str = "auto"
52
+ templates: list[str] = field(default_factory=list)
53
+ fields: dict[str, str] = field(default_factory=dict)
54
+ refs: list[str] = field(default_factory=list)
55
+ aspect: str = config.DEFAULT_ASPECT
56
+ quality: str = "bilanciata"
57
+ fidelity: float | None = None
58
+ seed: int | None = None
59
+ count: int = 1
60
+ translate: bool = True
61
+ mask: str | None = None
62
+
63
+ @classmethod
64
+ def from_payload(cls, data: dict[str, Any]) -> "JobRequest":
65
+ seed = data.get("seed")
66
+ refs = [str(r) for r in (data.get("riferimenti") or [])]
67
+ try:
68
+ return cls(
69
+ prompt=str(data.get("prompt") or ""),
70
+ mode=str(data.get("modalita") or "crea"),
71
+ model=str(data.get("modello") or "auto"),
72
+ templates=[str(t) for t in (data.get("stili") or [])],
73
+ fields={str(k): str(v)[:200] for k, v in (data.get("campi") or {}).items()},
74
+ refs=refs,
75
+ aspect=str(data.get("formato") or ("originale" if refs else config.DEFAULT_ASPECT)),
76
+ quality=str(data.get("qualita") or "bilanciata"),
77
+ fidelity=None if data.get("fedelta") in (None, "", "auto") else float(data["fedelta"]),
78
+ seed=int(seed) if seed not in (None, "") else None,
79
+ count=int(data.get("quantita") or 1),
80
+ translate=bool(data.get("traduci", True)),
81
+ mask=str(data["maschera"]) if data.get("maschera") else None,
82
+ )
83
+ except (TypeError, ValueError) as exc:
84
+ raise RequestError("Richiesta non valida.") from exc
85
+
86
+
87
+ @dataclass
88
+ class Job:
89
+ id: str
90
+ request: JobRequest
91
+ final_prompt: str
92
+ models: list[str]
93
+ steps: dict[str, int]
94
+ width: int
95
+ height: int
96
+ status: str = "in_coda"
97
+ progress: float = 0.0
98
+ current: int = 0
99
+ current_model: str = ""
100
+ created: float = field(default_factory=time.time)
101
+ started: float | None = None
102
+ finished: float | None = None
103
+ results: list[dict[str, Any]] = field(default_factory=list)
104
+ error: str | None = None
105
+ klein_prompt: str = ""
106
+ refine: bool = False
107
+ refine_prompt: str = ""
108
+ note: str = ""
109
+ fidelity_auto: bool = False
110
+ pause_left: int = 0
111
+
112
+ @property
113
+ def total(self) -> int:
114
+ return len(self.models) * self.request.count
115
+
116
+ def public(self) -> dict[str, Any]:
117
+ data = asdict(self)
118
+ data["total"] = self.total
119
+ model = self.current_model or self.models[0]
120
+ data["model_name"] = (config.MODELS.get(model) or config.TOOLS[model])["nome"]
121
+ data["current_steps"] = self.steps[model]
122
+ data["confronto"] = len(self.models) > 1
123
+ data["elapsed"] = round((self.finished or time.time()) - (self.started or self.created), 1)
124
+ return data
125
+
126
+ def gpu_seconds(self) -> int:
127
+ """Stima del tempo di GPU, così ZeroGPU riserva (e scala dalla quota) solo quanto serve."""
128
+ area = self.width * self.height / config.TARGET_AREA
129
+ total = 0.0
130
+ for model in self.models:
131
+ per_step = config.SECONDS_PER_STEP.get(model, 0.35)
132
+ if model == "ingrandisci":
133
+ total += 9 * 0.35 * area * 1.4
134
+ elif model == "scontorna":
135
+ total += 4
136
+ else:
137
+ total += self.steps[model] * per_step * area * self.request.count
138
+ return int(min(config.GPU_MAX_SECONDS, config.GPU_OVERHEAD + total * 1.6))
139
+
140
+
141
+ class TemplateBook:
142
+ """Stili di serie più quelli dell'utente, che vivono nel suo browser e arrivano con la richiesta."""
143
+
144
+ USER_CATEGORY = "I tuoi stili"
145
+
146
+ def __init__(self, items: dict[str, dict[str, Any]]):
147
+ self._items = items
148
+
149
+ @classmethod
150
+ def load(cls) -> "TemplateBook":
151
+ data = json.loads(config.TEMPLATES_FILE.read_text(encoding="utf-8"))
152
+ return cls({item["id"]: item for item in data["template"]})
153
+
154
+ def with_user(self, styles: list[dict[str, Any]]) -> "TemplateBook":
155
+ items = dict(self._items)
156
+ for raw in styles[:40]:
157
+ if not isinstance(raw, dict):
158
+ continue
159
+ style_id = str(raw.get("id") or "")
160
+ text = str(raw.get("prompt") or "")
161
+ if not style_id.startswith("u-") or "{prompt}" not in text:
162
+ continue
163
+ check_prompt(text)
164
+ items[style_id] = {
165
+ "id": style_id,
166
+ "nome": str(raw.get("nome") or "")[:40],
167
+ "prompt": text[:800],
168
+ "categoria": self.USER_CATEGORY,
169
+ "utente": True,
170
+ "campi": [],
171
+ }
172
+ return TemplateBook(items)
173
+
174
+ def all(self) -> list[dict[str, Any]]:
175
+ return list(self._items.values())
176
+
177
+ def get(self, template_id: str) -> dict[str, Any]:
178
+ return self._items.get(template_id) or self._items["libero"]
179
+
180
+ def clean_ids(self, ids: list[str]) -> list[str]:
181
+ seen: list[str] = []
182
+ for i in ids:
183
+ if i in self._items and i != "libero" and i not in seen:
184
+ seen.append(i)
185
+ return seen[:MAX_STYLES]
186
+
187
+ @staticmethod
188
+ def _fill(text: str, template: dict[str, Any], fields: dict[str, str]) -> str:
189
+ for spec in template.get("campi", []):
190
+ value = (fields.get(spec["id"]) or "").strip().replace('"', "'")
191
+ phrase = spec["frase"].replace("{valore}", value) if value else ""
192
+ text = text.replace("{" + spec["id"] + "}", phrase)
193
+ return text
194
+
195
+ def render(self, ids: list[str], prompt: str, fields: dict[str, str], mode: str = "crea") -> str:
196
+ """Il primo stile decide il tipo di immagine; gli altri aggiungono solo i loro descrittori."""
197
+ ids = self.clean_ids(ids)
198
+ if not ids:
199
+ return prompt.strip()
200
+ first = self._items[ids[0]]
201
+ base = first.get("prompt_ristila") if mode == "ristila" and first.get("prompt_ristila") else first["prompt"]
202
+ text = self._fill(base.replace("{prompt}", prompt.strip()), first, fields)
203
+ for extra_id in ids[1:]:
204
+ extra = self._items[extra_id]
205
+ body = extra["prompt"]
206
+ idx = body.find("{prompt}")
207
+ if idx >= 0:
208
+ cut = body.find(". ", idx)
209
+ body = body[cut + 2 :] if cut >= 0 else ""
210
+ for spec in extra.get("campi", []):
211
+ if "{" + spec["id"] + "}" not in body:
212
+ body = "{" + spec["id"] + "} " + body
213
+ text += " " + self._fill(body, extra, fields)
214
+ return re.sub(r"\s{2,}", " ", text).strip(" ,")
215
+
216
+
217
+ _STYLE_WORDS = re.compile(
218
+ r"\b(light|lighting|lit|glow|shadow|shadows|color|colors|colour|palette|tones?|hues?|saturat\w*|contrast|"
219
+ r"style|styled|aesthetic|look|mood|atmosphere|cinematic|photograph\w*|photo|render\w*|illustration|painting|"
220
+ r"painted|watercolou?r|anime|comic|cel|ink|line art|brush\w*|texture|textured|grain|film|lens|mm|bokeh|"
221
+ r"depth of field|shot on|camera|matte|glossy|vinyl|material|finish|vintage|retro|neon|pastel|monochrome|"
222
+ r"minimal\w*|detailed|detail|sharp|soft|dramatic|moody|warm|cold|cool|golden|studio|backdrop|background|"
223
+ r"chibi|proportions|3d|cgi|octane|unreal|pixel|vector|flat|isometric|editorial|magazine|high-end|"
224
+ r"composition|framing|symmetr\w*|haze|fog|misty|smoke|volumetric)\b",
225
+ re.IGNORECASE,
226
+ )
227
+
228
+
229
+ def extract_style(prompt: str, style_ids: list[str], book: TemplateBook) -> str:
230
+ """Tiene solo le frasi che descrivono l'aspetto (luce, colori, resa, materiali), non il soggetto."""
231
+ parts: list[str] = []
232
+ for sid in style_ids:
233
+ body = book.get(sid).get("prompt", "")
234
+ idx = body.find("{prompt}")
235
+ tail = body[idx + len("{prompt}") :] if idx >= 0 else body
236
+ tail = re.sub(r"\{[a-z_]+\}", "", tail)
237
+ parts.extend(c.strip(" .,") for c in re.split(r"[.,;]", tail))
238
+ for clause in re.split(r"[.,;]|\band\b", re.sub(r'"[^"]*"', "", prompt)):
239
+ clause = clause.strip(" .:")
240
+ if (
241
+ clause
242
+ and len(clause.split()) <= 9
243
+ and _STYLE_WORDS.search(clause)
244
+ and not re.search(r"\bof\b|camera|lens|\d+\s?mm\b|shot on", clause, re.IGNORECASE)
245
+ ):
246
+ parts.append(clause)
247
+ seen: set[str] = set()
248
+ kept: list[str] = []
249
+ for part in parts:
250
+ key = part.lower()
251
+ if part and key not in seen and not key.startswith(("of ", "with the ")):
252
+ seen.add(key)
253
+ kept.append(part[0].lower() + part[1:] if part[:2] != part[:2].upper() else part)
254
+ return " ".join(", ".join(kept).split()[:90]).rstrip(",")
255
+
256
+
257
+ def source_medium(img: Image.Image) -> str:
258
+ """Foto o disegno/render? Nelle foto anche le zone uniformi hanno grana; disegni e render 3D sono lisci."""
259
+ import numpy as np
260
+
261
+ small = img.convert("RGB")
262
+ small.thumbnail((384, 384))
263
+ gray = np.asarray(small, dtype=np.float32).mean(axis=2)
264
+ grad = np.abs(np.diff(gray, axis=1))[:-1, :] + np.abs(np.diff(gray, axis=0))[:, :-1]
265
+ lum = gray[:-1, :-1]
266
+ mid_tones = (lum > 30) & (lum < 235)
267
+ sample = grad[mid_tones] if mid_tones.sum() > 2000 else grad.ravel()
268
+ smooth = float((sample < 1.5).mean())
269
+ hard = float((sample >= 25).mean())
270
+ return "disegno" if smooth > 0.24 or hard > 0.8 else "foto"
271
+
272
+
273
+ def plan_restyle(src: Image.Image, styles: list[dict[str, Any]], has_prompt: bool) -> tuple[float, bool, str]:
274
+ """Quanto tenere della foto (per Z-Image) e se serve un modello che la capisca (Klein)."""
275
+ origin = source_medium(src)
276
+ if not styles:
277
+ return (0.42 if has_prompt else 0.5), False, ""
278
+ known = [s for s in styles if s.get("materia")]
279
+ if not known:
280
+ return 0.38, False, ""
281
+ first = known[0]
282
+ target = first["materia"]
283
+ if any(s.get("forma") for s in known):
284
+ return 0.25, True, f"«{first['nome']}» cambia forme e proporzioni: l'ha fatta Klein, che capisce la foto"
285
+ if target != origin:
286
+ what = {"foto": "una foto vera", "disegno": "un disegno", "3d": "un modello 3D", "grafica": "una grafica"}[target]
287
+ frm = "un disegno" if origin == "disegno" else "una foto"
288
+ return 0.28, True, f"Da {frm} a {what}: l'ha fatta Klein, che capisce cosa c'è nell'immagine"
289
+ return 0.52, False, ""
290
+
291
+
292
+ def resolve_models(mode: str, wanted: str) -> list[str]:
293
+ if wanted == config.REFINE and mode in config.REFINE_MODES:
294
+ return ["klein", "z-image"]
295
+ if wanted == config.BOTH:
296
+ usable = [k for k, m in config.MODELS.items() if mode in m["modalita"]]
297
+ return usable or [config.AUTO_MODEL[mode]]
298
+ if wanted in config.MODELS and mode in config.MODELS[wanted]["modalita"]:
299
+ return [wanted]
300
+ return [config.AUTO_MODEL[mode]]
301
+
302
+
303
+ def refine_text(book: TemplateBook, req: JobRequest, subject: str) -> str:
304
+ """Per ripassare con Z-Image serve una descrizione del risultato, non un'istruzione di modifica."""
305
+ if req.mode == "modifica":
306
+ return "A high quality, natural and detailed image with the same composition, subjects, colors and style, clean realistic textures and lighting."
307
+ subject = subject.strip() or "the same subject and scene"
308
+ if req.templates:
309
+ return book.render(req.templates, subject, req.fields)
310
+ return f"{subject}. Same composition, colors and style, with clean natural detail."
311
+
312
+
313
+ def klein_restyle(book: TemplateBook, req: JobRequest, extra: str) -> str:
314
+ """Klein vede la foto: gli si dice solo cosa cambia, i dettagli li prende dall'immagine."""
315
+ if req.mode != "ristila" or not req.templates:
316
+ return ""
317
+ base = book.get(req.templates[0]).get("prompt_ristila")
318
+ if not base:
319
+ return ""
320
+ others = book.render(req.templates[1:], "", req.fields).strip(" .") if len(req.templates) > 1 else ""
321
+ text = base + (f" {others}." if others else "") + (f" Also: {extra.strip()}." if extra.strip() else "")
322
+ return re.sub(r"\s{2,}", " ", text).strip()
323
+
324
+
325
+ def _new_id() -> str:
326
+ return uuid.uuid4().hex[:12]
327
+
328
+
329
+ def _seed(value: int | None) -> int:
330
+ return int(value) if value is not None and int(value) >= 0 else random.randint(0, 2**31 - 1)
331
+
332
+
333
+ def plan(req: JobRequest, refs: list[Image.Image], mask: Image.Image | None, book: TemplateBook) -> Job:
334
+ """Valida la richiesta e prepara il lavoro, con le stesse regole dell'app sul computer."""
335
+ if len(refs) != len(req.refs):
336
+ raise RequestError("Le immagini di partenza non sono arrivate tutte. Riprova.")
337
+ req.refs = req.refs[: config.MAX_REFS]
338
+ refs[:] = refs[: config.MAX_REFS]
339
+
340
+ if req.mode in config.TOOL_MODES:
341
+ if not refs:
342
+ raise RequestError("Scegli l'immagine su cui lavorare.")
343
+ req.refs, refs[:] = req.refs[:1], refs[:1]
344
+ req.prompt, req.templates, req.count, req.mask = "", [], 1, None
345
+ req.seed = _seed(req.seed)
346
+ width, height = refs[0].size
347
+ if req.mode == "ingrandisci":
348
+ scale = min(2.0, config.MAX_UPSCALE_SIDE / max(width, height))
349
+ if scale <= 1.05:
350
+ raise RequestError("L'immagine è già grande: online si ingrandisce fino a 2048 pixel di lato.")
351
+ width, height = int(width * scale) // 16 * 16, int(height * scale) // 16 * 16
352
+ return Job(_new_id(), req, "", [req.mode], {req.mode: 1}, width, height)
353
+
354
+ if req.mode == config.VIEWS_MODE:
355
+ if not refs:
356
+ raise RequestError("Scegli la figura da girare.")
357
+ req.refs, refs[:] = req.refs[:1], refs[:1]
358
+ req.prompt, req.templates, req.mask, req.model = "", [], None, "klein"
359
+ req.count, req.aspect = len(config.VIEWS), "originale"
360
+ req.quality = req.quality if req.quality in config.QUALITIES else "bilanciata"
361
+ req.seed = _seed(req.seed)
362
+ width, height = fit_dims(*refs[0].size)
363
+ steps = {"klein": config.MODELS["klein"]["qualita"][req.quality]}
364
+ return Job(_new_id(), req, "", ["klein"], steps, width, height)
365
+
366
+ if req.mode == config.REFINE_MODE:
367
+ if not refs:
368
+ raise RequestError("Scegli l'immagine da rifinire.")
369
+ req.refs, refs[:] = req.refs[:1], refs[:1]
370
+ req.model, req.count, req.mask, req.aspect = "z-image", 1, None, "originale"
371
+ req.templates = book.clean_ids(req.templates)
372
+ req.prompt = req.prompt.strip()[: config.MAX_PROMPT_CHARS]
373
+ req.quality = req.quality if req.quality in config.QUALITIES else "bilanciata"
374
+ req.fidelity = config.REFINE_FIDELITY
375
+ req.seed = _seed(req.seed)
376
+ width, height = fit_dims(*refs[0].size)
377
+ prompt = refine_text(book, req, req.prompt)
378
+ check_prompt(prompt)
379
+ steps = {"z-image": config.MODELS["z-image"]["qualita"][req.quality]}
380
+ return Job(_new_id(), req, prompt, ["z-image"], steps, width, height, refine=True, refine_prompt=prompt)
381
+
382
+ req.mode = req.mode if req.mode in config.MODES else "crea"
383
+ req.prompt = req.prompt.strip()[: config.MAX_PROMPT_CHARS]
384
+ if req.mode in ("ristila", "modifica", "continua") and not refs:
385
+ raise RequestError("Aggiungi almeno un'immagine di partenza.")
386
+ if req.mode == "crea":
387
+ req.refs, refs[:] = [], []
388
+ if req.mode == "ristila":
389
+ req.refs, refs[:] = req.refs[:1], refs[:1]
390
+ if not req.prompt and not book.clean_ids(req.templates):
391
+ raise RequestError("Scrivi come vuoi trasformarla o scegli uno stile.")
392
+ elif not req.prompt:
393
+ raise RequestError({"crea": "Scrivi cosa vuoi vedere.", "continua": "Scrivi la nuova scena."}.get(req.mode, "Scrivi cosa cambiare."))
394
+ req.templates = [] if req.mode in ("modifica", "continua") else book.clean_ids(req.templates)
395
+ if mask is not None and req.mode == "modifica":
396
+ req.model = config.REFINE if req.model == config.REFINE else "klein"
397
+ else:
398
+ req.mask = None
399
+
400
+ note = ""
401
+ fidelity_auto = req.fidelity is None
402
+ if req.mode == "ristila":
403
+ styles = [book.get(t) for t in req.templates]
404
+ auto_value, needs_klein, reason = plan_restyle(refs[0], styles, bool(req.prompt))
405
+ if fidelity_auto:
406
+ req.fidelity = auto_value
407
+ if needs_klein and req.model == "auto":
408
+ req.model = "klein"
409
+ note = reason
410
+ models = resolve_models(req.mode, req.model)
411
+ req.quality = req.quality if req.quality in config.QUALITIES else "bilanciata"
412
+ steps = {m: config.MODELS[m]["qualita"][req.quality] for m in models}
413
+ req.count = max(1, min(config.MAX_BATCH, int(req.count)))
414
+ req.fidelity = max(0.15, min(0.85, float(req.fidelity if req.fidelity is not None else 0.45)))
415
+ req.seed = _seed(req.seed)
416
+
417
+ if req.mask:
418
+ req.aspect = "originale"
419
+ width, height = refs[0].size
420
+ elif req.aspect == "originale" and refs:
421
+ width, height = fit_dims(*refs[0].size)
422
+ else:
423
+ req.aspect = req.aspect if req.aspect in config.ASPECTS else config.DEFAULT_ASPECT
424
+ width, height = config.ASPECTS[req.aspect]
425
+
426
+ subject = req.prompt or "the same subject and scene as the input image"
427
+ final_prompt = book.render(req.templates, subject, req.fields)
428
+ check_prompt(final_prompt + " " + " ".join(req.fields.values()))
429
+
430
+ job = Job(_new_id(), req, final_prompt, models, steps, width, height)
431
+ job.klein_prompt = klein_restyle(book, req, req.prompt)
432
+ job.note = note
433
+ job.fidelity_auto = fidelity_auto and req.mode == "ristila"
434
+ if req.model == config.REFINE and models == ["klein", "z-image"]:
435
+ job.refine = True
436
+ job.refine_prompt = refine_text(book, req, req.prompt)
437
+ return job
438
+
439
+
440
+ def prompt_for(job: Job, model_key: str) -> str:
441
+ if job.refine and model_key == "z-image":
442
+ return job.refine_prompt
443
+ if job.request.mode == "continua":
444
+ return config.CONTINUE_PROMPT.format(prompt=job.final_prompt)
445
+ if job.request.mode == config.VIEWS_MODE:
446
+ return f"{config.VIEWS[job.current % len(config.VIEWS)][1]} {config.VIEWS_KEEP}"
447
+ if job.request.mode == "ristila" and model_key == "klein":
448
+ if job.klein_prompt:
449
+ return job.klein_prompt
450
+ return f"Restyle image 1, keeping the same subject and composition: {job.final_prompt}"
451
+ return job.final_prompt
pixrick/marking.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ogni immagine esce marcata come generata con AI: metadati leggibili dalle macchine e filigrana invisibile."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import json
7
+ import logging
8
+ from typing import Any
9
+
10
+ from PIL import Image, PngImagePlugin
11
+
12
+ log = logging.getLogger("pixrick.marking")
13
+
14
+ WATERMARK = b"PixRick AI"
15
+ _XMP = """<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
16
+ <x:xmpmeta xmlns:x="adobe:ns:meta/">
17
+ <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
18
+ <rdf:Description rdf:about=""
19
+ xmlns:Iptc4xmpExt="http://iptc.org/std/Iptc4xmpExt/2008-02-29/"
20
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
21
+ xmlns:xmp="http://ns.adobe.com/xap/1.0/">
22
+ <Iptc4xmpExt:DigitalSourceType>http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia</Iptc4xmpExt:DigitalSourceType>
23
+ <xmp:CreatorTool>PixRick</xmp:CreatorTool>
24
+ <dc:description><rdf:Alt><rdf:li xml:lang="x-default">AI-generated image</rdf:li></rdf:Alt></dc:description>
25
+ </rdf:Description>
26
+ </rdf:RDF>
27
+ </x:xmpmeta>
28
+ <?xpacket end="w"?>"""
29
+
30
+
31
+ def _watermark(img: Image.Image) -> Image.Image:
32
+ try:
33
+ import cv2
34
+ import numpy as np
35
+ from imwatermark import WatermarkEncoder
36
+ except ImportError:
37
+ return img
38
+ if min(img.size) < 256:
39
+ return img
40
+ alpha = img.getchannel("A") if img.mode == "RGBA" else None
41
+ bgr = cv2.cvtColor(np.asarray(img.convert("RGB")), cv2.COLOR_RGB2BGR)
42
+ encoder = WatermarkEncoder()
43
+ encoder.set_watermark("bytes", WATERMARK)
44
+ marked = Image.fromarray(cv2.cvtColor(encoder.encode(bgr, "dwtDct"), cv2.COLOR_BGR2RGB))
45
+ if alpha is not None:
46
+ marked.putalpha(alpha)
47
+ return marked
48
+
49
+
50
+ def to_png(img: Image.Image, meta: dict[str, Any]) -> bytes:
51
+ try:
52
+ img = _watermark(img)
53
+ except Exception: # noqa: BLE001
54
+ log.exception("Filigrana non applicata")
55
+ info = PngImagePlugin.PngInfo()
56
+ info.add_text("Software", "PixRick")
57
+ info.add_text("Description", "AI-generated image")
58
+ info.add_text("parameters", json.dumps(meta, ensure_ascii=False))
59
+ info.add_itxt("XML:com.adobe.xmp", _XMP)
60
+ buf = io.BytesIO()
61
+ img.save(buf, "PNG", pnginfo=info)
62
+ return buf.getvalue()
pixrick/prompter.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Traduce e arricchisce i prompt con un piccolo modello di testo (Qwen3 1.7B)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ _ITALIAN_HINTS = re.compile(
8
+ r"\b(il|lo|la|gli|le|un|una|uno|di|del|della|dei|delle|che|con|per|sul|sulla|nel|nella|non|più|"
9
+ r"mentre|sopra|sotto|dietro|davanti|vicino|foto|immagine|ragazza|ragazzo|uomo|donna|cielo|mare|"
10
+ r"togli|metti|aggiungi|cambia|rendi|sostituisci|fai)\b|[àèéìòù]",
11
+ re.IGNORECASE,
12
+ )
13
+
14
+ _RULES = (
15
+ "Rules: keep every text inside double quotes exactly as written (do not translate it). "
16
+ "Reply with the result only, one paragraph, no preamble, no quotes around the whole answer."
17
+ )
18
+
19
+ PROMPTS = {
20
+ "traduci": (
21
+ "Translate this image-generation prompt into natural English. Translate faithfully: do not add, "
22
+ "remove or embellish details. If it is already English, return it unchanged. " + _RULES
23
+ ),
24
+ "migliora": (
25
+ "Rewrite this idea as a rich English prompt for a text-to-image model: describe subject, action, "
26
+ "setting, composition and framing, lighting, colors, mood and style in concrete visual terms, "
27
+ "in 40 to 90 words. Keep every element the user asked for and do not contradict them. Describe only what "
28
+ "appears in the picture: never mention cameras, lenses, focal lengths or photographic equipment, because "
29
+ "the image model would draw them. Write everything in positive terms. " + _RULES
30
+ ),
31
+ "migliora_modifica": (
32
+ "Rewrite this photo-editing request as one clear English instruction for an image-editing model. "
33
+ "Be explicit about what to change and say that everything else must stay the same. "
34
+ "Refer to input images as 'image 1', 'image 2' when the user mentions more photos. " + _RULES
35
+ ),
36
+ "in_italiano": (
37
+ "Translate this English image-generation prompt into natural, simple Italian. Translate faithfully: "
38
+ "do not add, remove or explain anything. Keep every text inside double quotes exactly as written. "
39
+ "Reply with the translation only, one paragraph."
40
+ ),
41
+ "stile": (
42
+ "From this image-generation prompt keep only the visual style: medium, rendering technique, lighting, "
43
+ "color palette, mood, camera and lens, textures. Remove the subject, characters, objects, actions, "
44
+ "text to render and the place or setting. Reply with a short comma-separated English list of 10 to 40 "
45
+ "words, nothing else."
46
+ ),
47
+ }
48
+
49
+
50
+ def _drop_repeats(text: str) -> str:
51
+ """Il modello piccolo a volte gira in tondo: tolgo i pezzi già detti e la frase troncata in fondo."""
52
+ seen: set[str] = set()
53
+ kept: list[str] = []
54
+ for chunk in re.split(r"(?<=[,.;])\s+", text):
55
+ key = chunk.strip(" ,.;").lower()
56
+ if key and key not in seen:
57
+ seen.add(key)
58
+ kept.append(chunk)
59
+ out = " ".join(kept).strip()
60
+ if out and out[-1] not in ".!?\"":
61
+ cut = max(out.rfind(". "), out.rfind(", "))
62
+ out = out[: cut + 1] if cut > len(out) * 0.6 else out
63
+ return out.rstrip(",; ")
64
+
65
+
66
+ def looks_italian(text: str) -> bool:
67
+ unquoted = re.sub(r'"[^"]*"', "", text)
68
+ return bool(_ITALIAN_HINTS.search(unquoted))
69
+
70
+
71
+
72
+ def finish(raw: str, original: str) -> str:
73
+ out = re.sub(r"<think>.*?</think>", "", raw, flags=re.DOTALL).strip().strip('"').strip()
74
+ return _drop_repeats(out) or original
75
+
76
+
77
+ def settings(kind: str) -> tuple[float, int]:
78
+ temperature = 0.2 if kind in ("traduci", "in_italiano", "stile") else 0.6
79
+ return temperature, 460 if kind == "in_italiano" else 260
pixrick/runner.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Il lavoro vero sulla GPU: modelli, rendering, strumenti, controlli sul risultato."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import random
7
+ import threading
8
+ import time
9
+ from typing import Any, Callable
10
+
11
+ from PIL import Image, ImageDraw, ImageFilter
12
+
13
+ from . import config, prompter
14
+ from .core import Job, TemplateBook, fit_dims, klein_restyle, prompt_for, refine_text
15
+ from .safety import SafetyError, check_prompt
16
+
17
+ log = logging.getLogger("pixrick.runner")
18
+
19
+ Report = Callable[[float], None]
20
+
21
+
22
+ class Models:
23
+ """Tutto caricato una volta all'avvio: ZeroGPU sposta i pesi sulla GPU solo durante le chiamate."""
24
+
25
+ def __init__(self) -> None:
26
+ self.ready = False
27
+ self._lock = threading.Lock()
28
+ if config.FAKE_ENGINE:
29
+ self.ready = True
30
+ return
31
+ import torch
32
+ from diffusers import Flux2KleinPipeline, ZImageImg2ImgPipeline, ZImagePipeline
33
+ from transformers import (
34
+ AutoImageProcessor,
35
+ AutoModelForCausalLM,
36
+ AutoModelForImageClassification,
37
+ AutoModelForImageSegmentation,
38
+ AutoTokenizer,
39
+ )
40
+
41
+ dtype = torch.bfloat16
42
+ self.torch = torch
43
+ self.zimage = ZImagePipeline.from_pretrained(config.MODELS["z-image"]["repo"], torch_dtype=dtype).to("cuda")
44
+ self.zimage_i2i = ZImageImg2ImgPipeline(**self.zimage.components)
45
+ self.klein = Flux2KleinPipeline.from_pretrained(config.MODELS["klein"]["repo"], torch_dtype=dtype).to("cuda")
46
+ self.cutout = AutoModelForImageSegmentation.from_pretrained(
47
+ config.TOOLS["scontorna"]["repo"], trust_remote_code=True
48
+ ).to("cuda").eval()
49
+ self.text_tok = AutoTokenizer.from_pretrained(config.PROMPTER_REPO)
50
+ self.text = AutoModelForCausalLM.from_pretrained(config.PROMPTER_REPO, torch_dtype=dtype).to("cuda").eval()
51
+ self.nsfw_proc = AutoImageProcessor.from_pretrained(config.NSFW_REPO)
52
+ self.nsfw = AutoModelForImageClassification.from_pretrained(config.NSFW_REPO).to("cuda").eval()
53
+ self.ready = True
54
+ log.info("Modelli pronti")
55
+
56
+ # ---------- testo ----------
57
+
58
+ def write(self, kind: str, text: str) -> str:
59
+ text = text.strip()
60
+ if not text:
61
+ return text
62
+ if config.FAKE_ENGINE:
63
+ time.sleep(0.4)
64
+ if kind == "in_italiano":
65
+ return f"[IT] {text}"
66
+ if kind == "stile":
67
+ return "warm cinematic lighting, deep shadows, rich saturated colors, film grain"
68
+ return f"[EN] {text}" if kind == "traduci" else f"A richly detailed scene of {text}, cinematic light."
69
+ torch = self.torch
70
+ messages = [{"role": "system", "content": prompter.PROMPTS[kind]}, {"role": "user", "content": text}]
71
+ chat = self.text_tok.apply_chat_template(
72
+ messages, add_generation_prompt=True, tokenize=False, enable_thinking=False
73
+ )
74
+ inputs = self.text_tok(chat, return_tensors="pt").to("cuda")
75
+ temperature, max_tokens = prompter.settings(kind)
76
+ with torch.inference_mode():
77
+ out = self.text.generate(
78
+ **inputs,
79
+ max_new_tokens=max_tokens,
80
+ do_sample=True,
81
+ temperature=temperature,
82
+ top_p=0.9,
83
+ repetition_penalty=1.12,
84
+ )
85
+ raw = self.text_tok.decode(out[0][inputs["input_ids"].shape[1] :], skip_special_tokens=True)
86
+ return prompter.finish(raw, text)
87
+
88
+ # ---------- controlli ----------
89
+
90
+ def is_explicit(self, img: Image.Image) -> bool:
91
+ if config.FAKE_ENGINE:
92
+ return False
93
+ torch = self.torch
94
+ inputs = self.nsfw_proc(images=img.convert("RGB"), return_tensors="pt").to("cuda")
95
+ with torch.inference_mode():
96
+ probs = self.nsfw(**inputs).logits.softmax(-1)[0]
97
+ labels = self.nsfw.config.id2label
98
+ score = sum(float(probs[i]) for i, name in labels.items() if name.lower() in ("nsfw", "porn", "sexy", "hentai"))
99
+ return score >= config.NSFW_THRESHOLD
100
+
101
+ # ---------- generazione ----------
102
+
103
+ def _callback(self, report: Report, total: int):
104
+ def step_end(_pipe, step: int, _timestep, kwargs):
105
+ report(min(1.0, (step + 1) / max(1, total)))
106
+ return kwargs
107
+
108
+ return step_end
109
+
110
+ def _generator(self, seed: int):
111
+ return self.torch.Generator("cuda").manual_seed(seed)
112
+
113
+ def zimage_create(self, prompt: str, w: int, h: int, steps: int, seed: int, report: Report) -> Image.Image:
114
+ return self.zimage(
115
+ prompt=prompt,
116
+ width=w,
117
+ height=h,
118
+ num_inference_steps=steps,
119
+ guidance_scale=0.0,
120
+ generator=self._generator(seed),
121
+ callback_on_step_end=self._callback(report, steps),
122
+ ).images[0]
123
+
124
+ def zimage_from(
125
+ self, prompt: str, source: Image.Image, keep: float, w: int, h: int, steps: int, seed: int, report: Report
126
+ ) -> Image.Image:
127
+ """keep = quanto resta della foto di partenza (0 = la ignora, 1 = identica)."""
128
+ strength = max(0.08, min(0.95, 1.0 - keep))
129
+ return self.zimage_i2i(
130
+ prompt=prompt,
131
+ image=source,
132
+ strength=strength,
133
+ width=w,
134
+ height=h,
135
+ num_inference_steps=steps,
136
+ guidance_scale=0.0,
137
+ generator=self._generator(seed),
138
+ callback_on_step_end=self._callback(report, max(1, int(steps * strength))),
139
+ ).images[0]
140
+
141
+ def klein_run(
142
+ self, prompt: str, images: list[Image.Image], w: int, h: int, steps: int, seed: int, report: Report
143
+ ) -> Image.Image:
144
+ args: dict[str, Any] = {}
145
+ if images:
146
+ args["image"] = images
147
+ return self.klein(
148
+ prompt=prompt,
149
+ width=w,
150
+ height=h,
151
+ num_inference_steps=steps,
152
+ guidance_scale=1.0,
153
+ generator=self._generator(seed),
154
+ callback_on_step_end=self._callback(report, steps),
155
+ **args,
156
+ ).images[0]
157
+
158
+ def cut_out(self, img: Image.Image) -> Image.Image:
159
+ from torchvision import transforms
160
+
161
+ torch = self.torch
162
+ prep = transforms.Compose(
163
+ [
164
+ transforms.Resize((1024, 1024)),
165
+ transforms.ToTensor(),
166
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
167
+ ]
168
+ )
169
+ rgb = img.convert("RGB")
170
+ tensor = prep(rgb).unsqueeze(0).to("cuda")
171
+ with torch.inference_mode():
172
+ pred = self.cutout(tensor)[-1].sigmoid().float().cpu()[0].squeeze()
173
+ alpha = transforms.ToPILImage()(pred).resize(rgb.size, Image.LANCZOS)
174
+ out = rgb.convert("RGBA")
175
+ out.putalpha(alpha)
176
+ return out
177
+
178
+
179
+ _models: Models | None = None
180
+ _models_lock = threading.Lock()
181
+
182
+
183
+ def models() -> Models:
184
+ global _models
185
+ with _models_lock:
186
+ if _models is None:
187
+ _models = Models()
188
+ return _models
189
+
190
+
191
+ # ---------- immagini finte per provare tutto senza GPU ----------
192
+
193
+
194
+ def _fake(job: Job, model_key: str, seed: int, refs: list[Image.Image], report: Report) -> Image.Image:
195
+ steps = job.steps.get(model_key, 1)
196
+ for s in range(steps):
197
+ time.sleep(0.15)
198
+ report((s + 1) / steps)
199
+ rnd = random.Random(f"{seed}-{model_key}")
200
+ img = Image.new("RGB", (job.width, job.height))
201
+ draw = ImageDraw.Draw(img)
202
+ a = [rnd.randint(30, 220) for _ in range(3)]
203
+ b = [rnd.randint(30, 220) for _ in range(3)]
204
+ for y in range(job.height):
205
+ k = y / job.height
206
+ draw.line([(0, y), (job.width, y)], fill=tuple(int(a[i] * (1 - k) + b[i] * k) for i in range(3)))
207
+ if refs:
208
+ img.paste(refs[0].convert("RGB").resize((job.width // 2, job.height // 2)), (job.width // 4, job.height // 4))
209
+ return img
210
+
211
+
212
+ # ---------- pezzi del lavoro ----------
213
+
214
+
215
+ def _fit_init(src: Image.Image, width: int, height: int) -> Image.Image:
216
+ """Z-Image riparte dai pixel: se il formato cambia, ritaglio al centro invece di schiacciare la foto."""
217
+ target = width / height
218
+ if abs(src.width / src.height - target) < 0.02:
219
+ return src
220
+ if src.width / src.height > target:
221
+ w = int(src.height * target)
222
+ box = ((src.width - w) // 2, 0, (src.width - w) // 2 + w, src.height)
223
+ else:
224
+ h = int(src.width / target)
225
+ box = (0, (src.height - h) // 2, src.width, (src.height - h) // 2 + h)
226
+ return src.crop(box)
227
+
228
+
229
+ def _keep_outside_zone(refined: Image.Image, base: Image.Image, mask: Image.Image) -> Image.Image:
230
+ """Col pennello la rifinitura vale solo dentro la zona: fuori resta la foto di partenza al pixel."""
231
+ refined = refined.convert("RGB").resize(base.size, Image.LANCZOS)
232
+ m = mask.convert("L").resize(base.size, Image.BILINEAR).point(lambda v: 255 if v > 127 else 0)
233
+ soft = m.filter(ImageFilter.MaxFilter(5)).filter(ImageFilter.GaussianBlur(max(3, int(max(base.size) * 0.02))))
234
+ return Image.composite(refined, base, soft)
235
+
236
+
237
+ class Runner:
238
+ """Esegue un lavoro dall'inizio alla fine, aggiornando job.progress per chi guarda."""
239
+
240
+ def __init__(self, job: Job, refs: list[Image.Image], mask: Image.Image | None, book: TemplateBook):
241
+ self.job = job
242
+ self.book = book
243
+ self.refs = refs
244
+ self.mask = mask
245
+ self.m = models()
246
+ self.intermediate: list[Image.Image] = []
247
+ self.images: list[tuple[str, Image.Image, int]] = []
248
+
249
+ def _report(self, fraction: float) -> None:
250
+ job = self.job
251
+ job.progress = round((job.current + max(0.0, fraction)) / job.total, 4)
252
+
253
+ def translate(self) -> None:
254
+ job, req = self.job, self.job.request
255
+ if req.mode in config.TOOL_MODES or not req.translate or not req.prompt or not prompter.looks_italian(req.prompt):
256
+ return
257
+ book = self.book
258
+ job.status = "traduzione"
259
+ english = self.m.write("traduci", req.prompt) or req.prompt
260
+ job.final_prompt = book.render(req.templates, english, req.fields)
261
+ job.klein_prompt = klein_restyle(book, req, english)
262
+ if job.refine:
263
+ job.refine_prompt = refine_text(book, req, english)
264
+ if req.mode == config.REFINE_MODE:
265
+ job.final_prompt = job.refine_prompt
266
+ check_prompt(job.final_prompt)
267
+
268
+ def check_inputs(self) -> None:
269
+ for img in self.refs:
270
+ if self.m.is_explicit(img):
271
+ raise SafetyError("Immagine di partenza rifiutata: qui niente nudo né contenuti sessuali.")
272
+
273
+ def render(self, model_key: str, seed: int) -> Image.Image:
274
+ job, req, m = self.job, self.job.request, self.m
275
+ report = self._report
276
+ if config.FAKE_ENGINE:
277
+ if model_key == "scontorna":
278
+ time.sleep(0.6)
279
+ rgba = self.refs[0].convert("RGBA")
280
+ w, h = rgba.size
281
+ alpha = Image.new("L", (w, h), 0)
282
+ alpha.paste(255, (w // 5, h // 8, w * 4 // 5, h * 7 // 8))
283
+ rgba.putalpha(alpha)
284
+ return rgba
285
+ if model_key == "ingrandisci":
286
+ time.sleep(0.8)
287
+ return self.refs[0].resize((job.width, job.height), Image.LANCZOS)
288
+ return _fake(job, model_key, seed, self.refs, report)
289
+
290
+ if model_key == "scontorna":
291
+ return m.cut_out(self.refs[0])
292
+ if model_key == "ingrandisci":
293
+ big = self.refs[0].resize((job.width, job.height), Image.LANCZOS)
294
+ text = "A high quality image with the same content, composition, colors and style, with crisp natural fine detail and clean textures."
295
+ return m.zimage_from(text, big, config.UPSCALE_FIDELITY, job.width, job.height, 9, seed, report)
296
+
297
+ steps = job.steps[model_key]
298
+ prompt = prompt_for(job, model_key)
299
+ if self.mask is not None and not (job.refine and model_key == "z-image"):
300
+ return self._render_zone(seed)
301
+ if model_key == "z-image":
302
+ if job.refine:
303
+ source = self.refs[0] if req.mode == config.REFINE_MODE else self.intermediate[job.current - req.count]
304
+ fitted = _fit_init(source, job.width, job.height)
305
+ image = m.zimage_from(prompt, fitted, config.REFINE_FIDELITY, job.width, job.height, steps, seed, report)
306
+ if self.mask is not None:
307
+ image = _keep_outside_zone(image, source.convert("RGB"), self.mask)
308
+ return image
309
+ if req.mode == "ristila":
310
+ fitted = _fit_init(self.refs[0], job.width, job.height)
311
+ return m.zimage_from(prompt, fitted, req.fidelity or 0.45, job.width, job.height, steps, seed, report)
312
+ return m.zimage_create(prompt, job.width, job.height, steps, seed, report)
313
+ return m.klein_run(prompt, self.refs, job.width, job.height, steps, seed, report)
314
+
315
+ def _render_zone(self, seed: int) -> Image.Image:
316
+ """Modifica solo la zona dipinta: lavora su un ritaglio ingrandito e lo rimette al suo posto sfumato."""
317
+ job = self.job
318
+ src = self.refs[0].convert("RGB")
319
+ mask = self.mask.convert("L").resize(src.size, Image.BILINEAR).point(lambda v: 255 if v > 127 else 0)
320
+ bbox = mask.getbbox()
321
+ if bbox is None:
322
+ raise ValueError("Dipingi la zona da cambiare.")
323
+ x0, y0, x1, y1 = bbox
324
+ side = max(x1 - x0, y1 - y0)
325
+ pad = max(48, int(side * 0.35))
326
+ min_side = min(384, src.width, src.height)
327
+ cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
328
+ half_w = max((x1 - x0) / 2 + pad, min_side / 2)
329
+ half_h = max((y1 - y0) / 2 + pad, min_side / 2)
330
+ box = (
331
+ max(0, int(cx - half_w)),
332
+ max(0, int(cy - half_h)),
333
+ min(src.width, int(cx + half_w)),
334
+ min(src.height, int(cy + half_h)),
335
+ )
336
+ crop = src.crop(box)
337
+ width, height = fit_dims(*crop.size)
338
+ steps = job.steps["klein"]
339
+ if config.FAKE_ENGINE:
340
+ for s in range(steps):
341
+ time.sleep(0.15)
342
+ self._report((s + 1) / steps)
343
+ edited = Image.new("RGB", crop.size, tuple(random.Random(seed).randint(40, 220) for _ in range(3)))
344
+ else:
345
+ edited = self.m.klein_run(job.final_prompt, [crop, *self.refs[1:]], width, height, steps, seed, self._report)
346
+ edited = edited.convert("RGB").resize(crop.size, Image.LANCZOS)
347
+ feather = max(3, int(max(crop.size) * 0.025))
348
+ soft = mask.crop(box).filter(ImageFilter.MaxFilter(5)).filter(ImageFilter.GaussianBlur(feather))
349
+ out = src.copy()
350
+ out.paste(Image.composite(edited, crop, soft), box[:2])
351
+ return out
352
+
353
+ def run(self) -> list[tuple[str, Image.Image, int]]:
354
+ job, req = self.job, self.job.request
355
+ job.started = time.time()
356
+ self.check_inputs()
357
+ self.translate()
358
+ combo = job.refine and req.mode != config.REFINE_MODE
359
+ index = 0
360
+ for model_key in job.models:
361
+ job.current_model = model_key
362
+ job.status = "generazione"
363
+ for i in range(req.count):
364
+ job.current = index
365
+ seed = int(req.seed) + (0 if req.mode == config.VIEWS_MODE else i)
366
+ image = self.render(model_key, seed)
367
+ if self.m.is_explicit(image):
368
+ raise SafetyError("Risultato bloccato dal filtro: qui niente nudo né contenuti sessuali.")
369
+ if combo and model_key == "klein":
370
+ self.intermediate.append(image)
371
+ else:
372
+ self.images.append((model_key, image, seed))
373
+ index += 1
374
+ job.progress = 1.0
375
+ job.status = "fatto"
376
+ job.finished = time.time()
377
+ return self.images
pixrick/safety.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regole di sicurezza: valgono per tutti e non si spengono."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ _MINOR_TERMS = re.compile(
8
+ r"\b(child|children|kid|kids|minor|minors|underage|teen|teens|teenager|preteen|toddler|infant|baby|"
9
+ r"boy|girl|schoolgirl|schoolboy|loli|lolita|shota|young\s*(?:girl|boy)|years?\s*old|"
10
+ r"bambin[oaie]|ragazzin[oaie]|minorenn[ei]|adolescent[ei]|neonat[oaie]|scolar[aei]|"
11
+ r"\d{1,2}\s*ann[io]|1[0-7]\s*(?:y|anni))\b",
12
+ re.IGNORECASE,
13
+ )
14
+ _SEXUAL_TERMS = re.compile(
15
+ r"\b(nude|naked|nsfw|sex|sexy|sexual|erotic|porn\w*|explicit|lingerie|topless|bottomless|undress\w*|"
16
+ r"genital\w*|breasts?|nipples?|boobs?|butt|ass|striptease|bikini|underwear|panties|bra|seductive|"
17
+ r"nud[oaie]|nudit[aà]|sesso|sessual[ei]|erotic[oaie]|porno\w*|spogliat[oaie]|svestit[oaie]|"
18
+ r"intimo|seno|tette|capezzol[oi]|mutand\w*|reggiseno|perizoma|provocante|sensual[ei])\b",
19
+ re.IGNORECASE,
20
+ )
21
+ _GORE_TERMS = re.compile(
22
+ r"\b(gore|gory|dismember\w*|decapitat\w*|mutilat\w*|disembowel\w*|beheading|corpse\s+torn|"
23
+ r"smembrat\w*|decapitat\w*|mutilat\w*|sbudellat\w*)\b",
24
+ re.IGNORECASE,
25
+ )
26
+
27
+
28
+ class SafetyError(ValueError):
29
+ """Richiesta bloccata per regole di sicurezza."""
30
+
31
+
32
+ def check_prompt(text: str) -> None:
33
+ if _MINOR_TERMS.search(text) and _SEXUAL_TERMS.search(text):
34
+ raise SafetyError("Richiesta bloccata: i minori non si toccano.")
35
+ if _SEXUAL_TERMS.search(text):
36
+ raise SafetyError("Richiesta bloccata: qui niente nudo né contenuti sessuali.")
37
+ if _GORE_TERMS.search(text):
38
+ raise SafetyError("Richiesta bloccata: niente violenza esplicita.")
pixrick/templates.json ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "template": [
3
+ {
4
+ "id": "libero",
5
+ "nome": "Prompt libero",
6
+ "descrizione": "Usa esattamente quello che scrivi.",
7
+ "formato": "1:1",
8
+ "colore": "#3A3F44",
9
+ "campi": [],
10
+ "prompt": "{prompt}",
11
+ "categoria": "Base"
12
+ },
13
+ {
14
+ "id": "figura-vinile",
15
+ "nome": "Funko",
16
+ "descrizione": "Figura in vinile stile Funko: testa grande, corpo piccolo. Pronta per l'image-to-3D e la stampa.",
17
+ "formato": "3:4",
18
+ "colore": "#e0743a",
19
+ "campi": [],
20
+ "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.",
21
+ "categoria": "Stampa 3D",
22
+ "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.",
23
+ "materia": "3d",
24
+ "forma": true
25
+ },
26
+ {
27
+ "id": "riferimento-stampa",
28
+ "nome": "Statuetta 3D",
29
+ "descrizione": "Statuetta realistica, intera e neutra, pronta per Hunyuan3D, Tripo o Meshy.",
30
+ "formato": "3:4",
31
+ "colore": "#8A8F96",
32
+ "campi": [],
33
+ "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.",
34
+ "categoria": "Stampa 3D",
35
+ "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.",
36
+ "materia": "3d",
37
+ "forma": true
38
+ },
39
+ {
40
+ "id": "foto",
41
+ "nome": "Foto realistica",
42
+ "descrizione": "Fotografia naturale, luce vera, dettaglio fine.",
43
+ "formato": "3:2",
44
+ "colore": "#C98A2B",
45
+ "campi": [],
46
+ "prompt": "{prompt}. A natural, candid real-life photograph with true-to-life colors, soft natural daylight, gentle background blur and fine realistic detail.",
47
+ "categoria": "Foto",
48
+ "materia": "foto",
49
+ "forma": false
50
+ },
51
+ {
52
+ "id": "ritratto",
53
+ "nome": "Ritratto",
54
+ "descrizione": "Primo piano editoriale con luce morbida.",
55
+ "formato": "4:5",
56
+ "colore": "#9C5B4F",
57
+ "campi": [],
58
+ "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.",
59
+ "categoria": "Foto",
60
+ "materia": "foto",
61
+ "forma": false
62
+ },
63
+ {
64
+ "id": "prodotto",
65
+ "nome": "Foto prodotto",
66
+ "descrizione": "Still life pubblicitario in studio.",
67
+ "formato": "1:1",
68
+ "colore": "#2E5E8C",
69
+ "campi": [],
70
+ "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.",
71
+ "categoria": "Foto",
72
+ "materia": "foto",
73
+ "forma": false
74
+ },
75
+ {
76
+ "id": "anime",
77
+ "nome": "Anime",
78
+ "descrizione": "Key visual in stile anime giapponese moderno.",
79
+ "formato": "3:4",
80
+ "colore": "#E2699A",
81
+ "campi": [],
82
+ "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.",
83
+ "categoria": "Illustrazione",
84
+ "materia": "disegno",
85
+ "forma": false
86
+ },
87
+ {
88
+ "id": "fumetto",
89
+ "nome": "Fumetto",
90
+ "descrizione": "Vignetta con chine marcate e retini.",
91
+ "formato": "3:4",
92
+ "colore": "#F2C230",
93
+ "campi": [],
94
+ "prompt": "Comic book panel of {prompt}, drawn with bold ink outlines, halftone dot shading and flat vibrant colors in a dynamic graphic novel composition.",
95
+ "categoria": "Illustrazione",
96
+ "materia": "disegno",
97
+ "forma": false
98
+ },
99
+ {
100
+ "id": "acquerello",
101
+ "nome": "Acquerello",
102
+ "descrizione": "Pittura leggera, carta e pigmenti che sfumano.",
103
+ "formato": "4:5",
104
+ "colore": "#6FA3B8",
105
+ "campi": [],
106
+ "prompt": "Watercolor painting of {prompt}, with soft washes, delicate bleeding pigments, loose brushwork and a light airy palette on textured cold-pressed paper.",
107
+ "categoria": "Illustrazione",
108
+ "materia": "disegno",
109
+ "forma": false
110
+ },
111
+ {
112
+ "id": "dark-fantasy",
113
+ "nome": "Dark fantasy",
114
+ "descrizione": "Concept art epica, nebbia e oro spento.",
115
+ "formato": "16:9",
116
+ "colore": "#7A6A3A",
117
+ "campi": [],
118
+ "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.",
119
+ "categoria": "Illustrazione",
120
+ "materia": "disegno",
121
+ "forma": false
122
+ },
123
+ {
124
+ "id": "personaggio-3d",
125
+ "nome": "Personaggio 3D",
126
+ "descrizione": "Render da film d'animazione, materiali morbidi.",
127
+ "formato": "1:1",
128
+ "colore": "#4C8C6A",
129
+ "campi": [],
130
+ "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.",
131
+ "categoria": "Illustrazione",
132
+ "materia": "3d",
133
+ "forma": true
134
+ },
135
+ {
136
+ "id": "pixel",
137
+ "nome": "Pixel art",
138
+ "descrizione": "Videogioco retrò a 16 bit.",
139
+ "formato": "1:1",
140
+ "colore": "#5D9C3A",
141
+ "campi": [],
142
+ "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.",
143
+ "categoria": "Illustrazione",
144
+ "materia": "disegno",
145
+ "forma": true
146
+ },
147
+ {
148
+ "id": "locandina",
149
+ "nome": "Locandina",
150
+ "descrizione": "Poster per eventi con titolo, sottotitolo e info.",
151
+ "formato": "2:3",
152
+ "colore": "#D7262F",
153
+ "campi": [
154
+ {
155
+ "id": "titolo",
156
+ "etichetta": "Titolo",
157
+ "placeholder": "FESTA D'AUTUNNO",
158
+ "frase": "Large bold headline text reading \"{valore}\"."
159
+ },
160
+ {
161
+ "id": "sottotitolo",
162
+ "etichetta": "Sottotitolo",
163
+ "placeholder": "Seconda edizione",
164
+ "frase": "Smaller subtitle text reading \"{valore}\"."
165
+ },
166
+ {
167
+ "id": "info",
168
+ "etichetta": "Data e luogo",
169
+ "placeholder": "12 dicembre · Piazza del Comune",
170
+ "frase": "Small footer text reading \"{valore}\"."
171
+ }
172
+ ],
173
+ "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.",
174
+ "categoria": "Grafica",
175
+ "materia": "grafica",
176
+ "forma": true
177
+ },
178
+ {
179
+ "id": "logo",
180
+ "nome": "Logo",
181
+ "descrizione": "Marchio piatto e semplice su fondo bianco.",
182
+ "formato": "1:1",
183
+ "colore": "#1F7A7A",
184
+ "campi": [
185
+ {
186
+ "id": "nome",
187
+ "etichetta": "Nome del marchio",
188
+ "placeholder": "Bottega Aurora",
189
+ "frase": "with the brand name \"{valore}\" in clean lettering"
190
+ }
191
+ ],
192
+ "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.",
193
+ "categoria": "Grafica",
194
+ "materia": "grafica",
195
+ "forma": true
196
+ },
197
+ {
198
+ "id": "copertina",
199
+ "nome": "Copertina album",
200
+ "descrizione": "Artwork quadrato per musica.",
201
+ "formato": "1:1",
202
+ "colore": "#5B3F7A",
203
+ "campi": [
204
+ {
205
+ "id": "titolo",
206
+ "etichetta": "Titolo sulla copertina",
207
+ "placeholder": "",
208
+ "frase": "Title text reading \"{valore}\"."
209
+ }
210
+ ],
211
+ "prompt": "Square album cover artwork for {prompt}. {titolo} A bold artistic concept with a striking composition and rich texture, designed as music artwork.",
212
+ "categoria": "Grafica",
213
+ "materia": "grafica",
214
+ "forma": false
215
+ },
216
+ {
217
+ "id": "sticker",
218
+ "nome": "Sticker",
219
+ "descrizione": "Adesivo fustellato con bordo bianco.",
220
+ "formato": "1:1",
221
+ "colore": "#E07B39",
222
+ "campi": [],
223
+ "prompt": "Die-cut sticker of {prompt} with a thick white border, bold outlines and vibrant flat colors, isolated on a plain light background.",
224
+ "categoria": "Grafica",
225
+ "materia": "grafica",
226
+ "forma": true
227
+ },
228
+ {
229
+ "id": "ui-app",
230
+ "nome": "Schermata app",
231
+ "categoria": "Interfacce",
232
+ "descrizione": "Mockup di una schermata mobile. Ottimo per esplorare idee: i testi piccoli possono uscire imprecisi.",
233
+ "formato": "9:16",
234
+ "colore": "#7C8CF8",
235
+ "campi": [
236
+ {
237
+ "id": "titolo",
238
+ "etichetta": "Titolo della schermata",
239
+ "placeholder": "Le mie ricette",
240
+ "frase": "with the screen title \"{valore}\""
241
+ }
242
+ ],
243
+ "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.",
244
+ "materia": "grafica",
245
+ "forma": true
246
+ },
247
+ {
248
+ "id": "ui-web",
249
+ "nome": "Pagina web",
250
+ "categoria": "Interfacce",
251
+ "descrizione": "Landing page vista da desktop: hero, menu, sezioni.",
252
+ "formato": "16:9",
253
+ "colore": "#5FB3A1",
254
+ "campi": [
255
+ {
256
+ "id": "titolo",
257
+ "etichetta": "Titolo principale",
258
+ "placeholder": "Studio Nord",
259
+ "frase": "with the hero headline \"{valore}\""
260
+ }
261
+ ],
262
+ "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.",
263
+ "materia": "grafica",
264
+ "forma": true
265
+ },
266
+ {
267
+ "id": "ui-dashboard",
268
+ "nome": "Dashboard",
269
+ "categoria": "Interfacce",
270
+ "descrizione": "Gestionale web con barra laterale, card, grafici e tabelle.",
271
+ "formato": "16:9",
272
+ "colore": "#E3A857",
273
+ "campi": [],
274
+ "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.",
275
+ "materia": "grafica",
276
+ "forma": true
277
+ },
278
+ {
279
+ "id": "ui-componenti",
280
+ "nome": "Kit componenti",
281
+ "categoria": "Interfacce",
282
+ "descrizione": "Tavola con bottoni, campi, card, palette e caratteri.",
283
+ "formato": "16:9",
284
+ "colore": "#C46BAE",
285
+ "campi": [],
286
+ "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.",
287
+ "materia": "grafica",
288
+ "forma": true
289
+ },
290
+ {
291
+ "id": "ui-icona",
292
+ "nome": "Icona app",
293
+ "categoria": "Interfacce",
294
+ "descrizione": "Icona quadrata arrotondata, un simbolo forte.",
295
+ "formato": "1:1",
296
+ "colore": "#4E9AE0",
297
+ "campi": [],
298
+ "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.",
299
+ "materia": "grafica",
300
+ "forma": true
301
+ }
302
+ ]
303
+ }
pixrick/vector.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vettorizzazione: da PNG a SVG con vtracer, preceduta da una pulizia dei colori.
2
+
3
+ Le immagini generate hanno rumore e sfumature finissime: tracciarle così darebbe
4
+ migliaia di tracciati. Prima riduco i colori a una tavolozza piccola, poi traccio.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import io
10
+ import re
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+
14
+ from PIL import Image, ImageDraw, ImageFilter
15
+
16
+ MAX_SIDE = 1400
17
+ INK = 90
18
+ MIN_SHARE = 0.004
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Preset:
23
+ nome: str
24
+ colori: int
25
+ binario: bool
26
+ speckle: int
27
+ angoli: int
28
+
29
+
30
+ PRESETS: dict[str, Preset] = {
31
+ "colori": Preset("Illustrazione", 16, False, 6, 60),
32
+ "essenziale": Preset("Pochi colori", 8, False, 10, 70),
33
+ "contorno": Preset("Solo contorni", 2, True, 8, 60),
34
+ }
35
+
36
+
37
+ def available() -> bool:
38
+ try:
39
+ import vtracer # noqa: F401
40
+ except ImportError:
41
+ return False
42
+ return True
43
+
44
+
45
+ def _drop_background(img: Image.Image) -> Image.Image:
46
+ """Il colore che riempie i bordi, se collegato ai bordi, diventa trasparente (fondo bianco dei loghi)."""
47
+ rgb = img.convert("RGB")
48
+ w, h = rgb.size
49
+ edge = [rgb.getpixel((x, y)) for x in range(0, w, max(1, w // 40)) for y in (0, h - 1)]
50
+ edge += [rgb.getpixel((x, y)) for y in range(0, h, max(1, h // 40)) for x in (0, w - 1)]
51
+ bg = max(set(edge), key=edge.count)
52
+ if edge.count(bg) < len(edge) * 0.6:
53
+ return img
54
+ same = Image.new("L", (w, h), 0)
55
+ same.putdata([255 if p == bg else 0 for p in rgb.getdata()])
56
+ 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)):
57
+ if same.getpixel((x, y)) == 255:
58
+ ImageDraw.floodfill(same, (x, y), 128)
59
+ out = img.convert("RGBA")
60
+ alpha = out.getchannel("A")
61
+ alpha.paste(0, mask=same.point(lambda v: 255 if v == 128 else 0))
62
+ out.putalpha(alpha)
63
+ return out
64
+
65
+
66
+ def _prepare(path: Path, preset: Preset, transparent: bool) -> bytes:
67
+ img = Image.open(path)
68
+ img.load()
69
+ has_alpha = img.mode in ("RGBA", "LA") or "transparency" in img.info
70
+ img = img.convert("RGBA")
71
+ if max(img.size) > MAX_SIDE:
72
+ img.thumbnail((MAX_SIDE, MAX_SIDE), Image.LANCZOS)
73
+ alpha = img.getchannel("A")
74
+ rgb = img.convert("RGB").filter(ImageFilter.MedianFilter(5))
75
+ if preset.binario:
76
+ rgb = rgb.convert("L").point(lambda v: 255 if v > INK else 0).convert("RGB")
77
+ else:
78
+ rgb = _flatten(rgb, preset.colori)
79
+ out = rgb.convert("RGBA")
80
+ if has_alpha:
81
+ out.putalpha(alpha.point(lambda v: 255 if v > 127 else 0))
82
+ elif transparent and not preset.binario:
83
+ out = _drop_background(out)
84
+ buf = io.BytesIO()
85
+ out.save(buf, "PNG")
86
+ return buf.getvalue()
87
+
88
+
89
+ def _flatten(rgb: Image.Image, colors: int) -> Image.Image:
90
+ """Riduce a pochi colori e butta quelli rarissimi: sono i pixel di bordo sfumati, che diventerebbero
91
+ filetti chiari e puntini tra una forma e l'altra."""
92
+ first = rgb.quantize(colors=colors, method=Image.Quantize.FASTOCTREE, kmeans=4, dither=Image.Dither.NONE)
93
+ counts = first.getcolors(colors) or []
94
+ total = rgb.width * rgb.height
95
+ pal = first.getpalette()[: colors * 3]
96
+ kept = [idx for n, idx in sorted(counts, reverse=True) if n / total >= MIN_SHARE] or [max(counts)[1]]
97
+ flat: list[int] = []
98
+ for idx in kept:
99
+ flat += pal[idx * 3 : idx * 3 + 3]
100
+ palette = Image.new("P", (1, 1))
101
+ palette.putpalette(flat + flat[:3] * (256 - len(kept)))
102
+ return rgb.quantize(palette=palette, dither=Image.Dither.NONE).convert("RGB")
103
+
104
+
105
+ def vectorize(path: Path, preset_id: str = "colori", transparent: bool = True) -> dict[str, object]:
106
+ import vtracer
107
+
108
+ preset = PRESETS.get(preset_id, PRESETS["colori"])
109
+ data = _prepare(path, preset, transparent)
110
+ svg = vtracer.convert_raw_image_to_svg(
111
+ data,
112
+ img_format="png",
113
+ colormode="binary" if preset.binario else "color",
114
+ hierarchical="stacked",
115
+ mode="spline",
116
+ filter_speckle=preset.speckle,
117
+ color_precision=8,
118
+ layer_difference=8,
119
+ corner_threshold=preset.angoli,
120
+ length_threshold=4.0,
121
+ max_iterations=10,
122
+ splice_threshold=45,
123
+ path_precision=2,
124
+ )
125
+ w, h = Image.open(io.BytesIO(data)).size
126
+ svg = re.sub(r"<svg ([^>]*)>", lambda m: _with_viewbox(m.group(1), w, h), svg, count=1)
127
+ return {
128
+ "svg": svg,
129
+ "tracciati": svg.count("<path"),
130
+ "kb": round(len(svg.encode()) / 1024, 1),
131
+ "preset": preset_id if preset_id in PRESETS else "colori",
132
+ }
133
+
134
+
135
+ def _with_viewbox(attrs: str, w: int, h: int) -> str:
136
+ attrs = re.sub(r'\s*(width|height|viewBox)="[^"]*"', "", attrs)
137
+ return f'<svg {attrs.strip()} width="{w}" height="{h}" viewBox="0 0 {w} {h}">'
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch==2.13.0
2
+ torchvision==0.28.0
3
+ diffusers==0.43.0
4
+ transformers==5.23.0
5
+ accelerate
6
+ safetensors
7
+ sentencepiece
8
+ timm
9
+ einops
10
+ kornia
11
+ vtracer==0.6.15
12
+ invisible-watermark
13
+ opencv-python-headless
14
+ numpy
15
+ pillow
web/app.js ADDED
@@ -0,0 +1,2057 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use strict";
2
+
3
+ const $ = (s) => document.querySelector(s);
4
+ const $$ = (s) => [...document.querySelectorAll(s)];
5
+ const PAGE = 60;
6
+ const MAX_STYLES = 3;
7
+ const BOTH = "entrambi";
8
+ const REFINE = "klein+z";
9
+ const REFINE_MODES = ["ristila", "modifica", "continua"];
10
+ const TOOL_MODES = ["ingrandisci", "scontorna"];
11
+ const USER_CATEGORY = "I tuoi stili";
12
+ const STYLE_COLORS = ["#cbbcff", "#ffc9a8", "#9fe3da", "#ffd600", "#ff7a7a", "#7aa7ff"];
13
+
14
+ const MODES = {
15
+ crea: {
16
+ hint: "Un'immagine nuova da una descrizione.",
17
+ placeholder: "Descrivi la scena: soggetto, luogo, luce, stile. Il testo da scrivere nell'immagine va tra virgolette.",
18
+ maxRefs: 0,
19
+ button: "Genera",
20
+ },
21
+ ristila: {
22
+ hint: "Stessa foto, stile nuovo.",
23
+ 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».",
24
+ maxRefs: 1,
25
+ button: "Ristila",
26
+ },
27
+ modifica: {
28
+ hint: "Cambia quello che scrivi: in tutta la foto o solo nella zona che dipingi.",
29
+ 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».",
30
+ maxRefs: 4,
31
+ button: "Modifica",
32
+ },
33
+ continua: {
34
+ hint: "Una nuova scena con lo stesso stile, mondo e personaggi della foto.",
35
+ placeholder: "La nuova scena: «lo stesso personaggio di notte sul tetto», «la piazza vista dall'alto con la folla».",
36
+ maxRefs: 1,
37
+ button: "Crea la scena",
38
+ },
39
+ };
40
+
41
+ const MODE_LABEL = {
42
+ crea: "Creata",
43
+ ristila: "Ristilizzata",
44
+ modifica: "Modificata",
45
+ continua: "Stessa storia",
46
+ ingrandisci: "Ingrandita ×2",
47
+ scontorna: "Scontornata",
48
+ locandina: "Locandina",
49
+ viste: "Vista per il 3D",
50
+ };
51
+ const PRINT_CATEGORY = "Stampa 3D";
52
+ const isTool = (item) => TOOL_MODES.includes(item?.modalita);
53
+ const isPoster = (item) => item?.modalita === "locandina";
54
+ const isView = (item) => item?.modalita === "viste";
55
+ const isFixed = (item) => isTool(item) || isPoster(item) || isView(item);
56
+ const canRefine = (item) => item && item.modello === "klein" && !isFixed(item) && !item.rifinita;
57
+ const isPrintable = (item) => !isFixed(item) && stylesOf(item).some((id) => templateById(id)?.categoria === PRINT_CATEGORY);
58
+
59
+ const prefs = {
60
+ get(key, fallback) {
61
+ try { const v = localStorage.getItem(`pixrick.${key}`); return v === null ? fallback : JSON.parse(v); } catch { return fallback; }
62
+ },
63
+ set(key, value) {
64
+ try { localStorage.setItem(`pixrick.${key}`, JSON.stringify(value)); } catch { /* spazio pieno o non disponibile */ }
65
+ },
66
+ };
67
+
68
+ const state = {
69
+ models: {},
70
+ auto: {},
71
+ templates: [],
72
+ mode: "crea",
73
+ model: "auto",
74
+ styles: [],
75
+ fieldValues: {},
76
+ aspect: "1:1",
77
+ aspectTouched: false,
78
+ aspects: {},
79
+ quality: "bilanciata",
80
+ count: 1,
81
+ refs: [],
82
+ current: null,
83
+ session: [],
84
+ refineFrom: null,
85
+ nextDismissed: "",
86
+ userStylesOpen: false,
87
+ tools: {},
88
+ batch: [],
89
+ lastPrompt: "",
90
+ busy: false,
91
+ polling: null,
92
+ gallery: { filter: "tutte", items: [], offset: 0, full: false, selected: new Set(), detailIndex: -1 },
93
+ };
94
+
95
+ /* ---------- utilità ---------- */
96
+
97
+ async function api(path, body, extraHeaders = {}) {
98
+ if (window.PixBackend) {
99
+ try {
100
+ return await window.PixBackend.api(path, body, extraHeaders);
101
+ } catch (e) {
102
+ throw e instanceof Error ? e : new Error(String(e));
103
+ }
104
+ }
105
+ const opts = body === undefined ? {} : {
106
+ method: "POST",
107
+ headers: { "X-ImgAI": "1", ...extraHeaders },
108
+ body: body instanceof Blob ? body : JSON.stringify(body),
109
+ };
110
+ if (body !== undefined && !(body instanceof Blob)) opts.headers["Content-Type"] = "application/json";
111
+ const res = await fetch(path, opts);
112
+ const data = await res.json().catch(() => ({}));
113
+ if (!res.ok) throw new Error(data.errore || `Errore ${res.status}`);
114
+ return data;
115
+ }
116
+
117
+ function toast(text, action) {
118
+ const box = $("#toast");
119
+ const btn = $("#toast-action");
120
+ $("#toast-text").textContent = text;
121
+ btn.hidden = !action;
122
+ btn.onclick = null;
123
+ if (action) {
124
+ btn.textContent = action.label;
125
+ btn.onclick = () => { box.classList.remove("show"); action.run(); };
126
+ }
127
+ box.classList.add("show");
128
+ clearTimeout(toast.t);
129
+ toast.t = setTimeout(() => box.classList.remove("show"), action ? 6000 : 2800);
130
+ }
131
+
132
+ function radio(container, attr, value) {
133
+ container.querySelectorAll("[role=radio]").forEach((b) => b.setAttribute("aria-checked", String(b.dataset[attr] === String(value))));
134
+ }
135
+
136
+ const mediaUrl = (path) => "/" + path.split("/").map(encodeURIComponent).join("/");
137
+ const outputUrl = (file) => mediaUrl("outputs/" + file);
138
+
139
+ function el(tag, props = {}, children = []) {
140
+ const n = document.createElement(tag);
141
+ for (const [k, v] of Object.entries(props)) {
142
+ if (k === "class") n.className = v;
143
+ else if (k === "text") n.textContent = v;
144
+ else if (k.startsWith("on")) n.addEventListener(k.slice(2), v);
145
+ else if (k === "data") Object.assign(n.dataset, v);
146
+ else n.setAttribute(k, v);
147
+ }
148
+ n.append(...children);
149
+ return n;
150
+ }
151
+
152
+ function icon(id) {
153
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
154
+ const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
155
+ use.setAttribute("href", `#${id}`);
156
+ svg.append(use);
157
+ return svg;
158
+ }
159
+
160
+ const templateById = (id) => state.templates.find((t) => t.id === id);
161
+ const stylesOf = (item) => item.stili || (item.template && item.template !== "libero" ? [item.template] : []);
162
+ const styleNames = (ids) => ids.map((id) => templateById(id)?.nome || "stile eliminato").join(" + ");
163
+ const titleOf = (item) => item.titolo || item.prompt
164
+ || (stylesOf(item).length ? `${styleNames(stylesOf(item))}, da una foto` : "")
165
+ || item.prompt_finale || "Senza titolo";
166
+
167
+ function resolvedModels(mode = state.mode, wanted = state.model) {
168
+ if (mode === "modifica" && mask.hasStrokes() && wanted !== REFINE) return ["klein"];
169
+ if (wanted === REFINE) return REFINE_MODES.includes(mode) ? ["klein", "z-image"] : [state.auto[mode]];
170
+ if (wanted === BOTH) return Object.keys(state.models).filter((k) => state.models[k].modalita.includes(mode));
171
+ const m = state.models[wanted];
172
+ return [m && m.modalita.includes(mode) ? wanted : state.auto[mode]];
173
+ }
174
+ const resolvedModel = (mode, wanted) => resolvedModels(mode, wanted)[0];
175
+ const otherModel = (key) => Object.keys(state.models).find((k) => k !== key);
176
+
177
+ /* ---------- stato motore ---------- */
178
+
179
+ async function refreshStatus() {
180
+ try {
181
+ return await api("/api/status");
182
+ } catch {
183
+ return null;
184
+ }
185
+ }
186
+
187
+ /* ---------- pannello modello ---------- */
188
+
189
+ function renderModels() {
190
+ const box = $("#models");
191
+ box.replaceChildren();
192
+ const autoKey = state.auto[state.mode];
193
+ const zoned = state.mode === "modifica" && mask.hasStrokes();
194
+ const options = [
195
+ { key: "auto", nome: "Automatico", note: state.models[autoKey]?.nome, descrizione: "Sceglie il modello giusto per quello che stai facendo." },
196
+ ...Object.entries(state.models).map(([key, m]) => ({ key, ...m })),
197
+ { key: BOTH, nome: "Entrambi", modalita: ["crea", "ristila"], descrizione: "Stesso prompt e stesso seme con i due modelli, affiancati." },
198
+ { 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." },
199
+ ];
200
+ for (const o of options) {
201
+ const supported = o.key === "auto" || (o.modalita.includes(state.mode) && !(zoned && !["klein", REFINE].includes(o.key)));
202
+ if (o.key === REFINE && !supported) continue;
203
+ box.append(el("button", {
204
+ type: "button",
205
+ class: "model",
206
+ role: "radio",
207
+ "aria-checked": String(state.model === o.key),
208
+ "aria-disabled": String(!supported),
209
+ title: supported ? "" : "Le modifiche a comando le fa solo FLUX.2 Klein",
210
+ onclick: () => { if (supported) { state.model = o.key; syncAll(); } },
211
+ }, [
212
+ el("span", { class: "model-name" }, [o.nome, ...(o.note ? [el("small", { text: o.note })] : [])]),
213
+ el("span", { class: "model-desc", text: o.descrizione }),
214
+ ]));
215
+ }
216
+ }
217
+
218
+ /* ---------- stili combinabili ---------- */
219
+
220
+ function renderTemplates() {
221
+ const box = $("#templates");
222
+ box.replaceChildren();
223
+ const groups = new Map([[USER_CATEGORY, []]]);
224
+ for (const t of state.templates) {
225
+ if (!groups.has(t.categoria)) groups.set(t.categoria, []);
226
+ groups.get(t.categoria).push(t);
227
+ }
228
+ const ordered = new Map();
229
+ for (const [name, items] of groups) {
230
+ if (name === USER_CATEGORY) continue;
231
+ ordered.set(name, items);
232
+ if (ordered.size === 1) ordered.set(USER_CATEGORY, groups.get(USER_CATEGORY));
233
+ }
234
+ const USER_VISIBLE = 6;
235
+ for (const [name, all] of ordered) {
236
+ const chips = el("div", { class: "tpl-chips", "aria-label": name });
237
+ let items = all;
238
+ const hiddenCount = name === USER_CATEGORY && !state.userStylesOpen ? Math.max(0, all.length - USER_VISIBLE) : 0;
239
+ if (hiddenCount) {
240
+ const picked = all.filter((t) => state.styles.includes(t.id));
241
+ const rest = all.filter((t) => !state.styles.includes(t.id));
242
+ items = [...picked, ...rest].slice(0, Math.max(USER_VISIBLE, picked.length));
243
+ }
244
+ for (const t of items) {
245
+ 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) });
246
+ c.style.setProperty("--c", t.colore);
247
+ if (t.utente) {
248
+ chips.append(el("span", { class: "chip-wrap" }, [
249
+ c,
250
+ el("button", { type: "button", class: "chip-edit", title: `Modifica «${t.nome}»`, "aria-label": `Modifica lo stile ${t.nome}`, onclick: () => openStyleDialog(t) }, [icon("i-pencil")]),
251
+ ]));
252
+ } else {
253
+ chips.append(c);
254
+ }
255
+ }
256
+ if (name === USER_CATEGORY && all.length > USER_VISIBLE) {
257
+ const extra = all.length - items.length;
258
+ chips.append(el("button", {
259
+ type: "button",
260
+ class: "chip chip-more",
261
+ onclick: () => { state.userStylesOpen = !state.userStylesOpen; renderTemplates(); },
262
+ }, [state.userStylesOpen ? "Mostra meno" : `Altri ${extra}`]));
263
+ }
264
+ if (name === USER_CATEGORY) {
265
+ 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"]));
266
+ }
267
+ box.append(el("div", { class: "tpl-group" + (name === USER_CATEGORY ? " user" : "") }, [el("p", { class: "tpl-group-name", text: name }), chips]));
268
+ }
269
+ renderStyleState();
270
+ }
271
+
272
+ function toggleStyle(id) {
273
+ saveFieldValues();
274
+ if (id === "libero") {
275
+ state.styles = [];
276
+ } else if (state.styles.includes(id)) {
277
+ state.styles = state.styles.filter((s) => s !== id);
278
+ } else if (state.styles.length >= MAX_STYLES) {
279
+ toast(`Al massimo ${MAX_STYLES} stili insieme`);
280
+ return;
281
+ } else {
282
+ state.styles.push(id);
283
+ const t = templateById(id);
284
+ if (state.styles.length === 1 && !state.aspectTouched && (state.mode === "crea" || (state.mode === "ristila" && t.forma))) selectAspect(t.formato);
285
+ if (t.utente && (t.modello || t.qualita)) {
286
+ const usable = t.modello && (t.modello === BOTH ? state.mode !== "modifica" : state.models[t.modello]?.modalita.includes(state.mode));
287
+ if (usable) state.model = t.modello;
288
+ if (t.qualita) { state.quality = t.qualita; radio($("#quality"), "v", state.quality); }
289
+ syncAll();
290
+ toast(`«${t.nome}» ha impostato anche ${usable ? "modello e " : ""}qualità`);
291
+ }
292
+ }
293
+ renderStyleState();
294
+ }
295
+
296
+ function renderStyleState() {
297
+ state.styles = state.styles.filter((id) => templateById(id));
298
+ const multi = state.styles.length > 1;
299
+ $$("#templates .chip[data-id]").forEach((c) => {
300
+ const id = c.dataset.id;
301
+ const idx = state.styles.indexOf(id);
302
+ const on = id === "libero" ? state.styles.length === 0 : idx >= 0;
303
+ c.setAttribute("aria-checked", String(on));
304
+ if (multi && idx >= 0) c.dataset.order = String(idx + 1);
305
+ else delete c.dataset.order;
306
+ });
307
+ let desc = "Nessuno stile: usa esattamente quello che scrivi.";
308
+ if (state.styles.length === 1) desc = templateById(state.styles[0]).descrizione;
309
+ if (multi) desc = `${styleNames(state.styles)}. Il primo decide il tipo di immagine, gli altri aggiungono il loro stile.`;
310
+ $("#tpl-desc").textContent = desc;
311
+
312
+ const fields = $("#tpl-fields");
313
+ fields.replaceChildren();
314
+ const seen = new Set();
315
+ for (const id of state.styles) {
316
+ for (const f of templateById(id)?.campi || []) {
317
+ if (seen.has(f.id)) continue;
318
+ seen.add(f.id);
319
+ const input = el("input", { type: "text", maxlength: "200", placeholder: f.placeholder || "", data: { field: f.id } });
320
+ input.value = state.fieldValues[f.id] || "";
321
+ fields.append(el("label", {}, [f.etichetta, input]));
322
+ }
323
+ }
324
+ renderPills();
325
+ }
326
+
327
+ function saveFieldValues() {
328
+ $$("[data-field]").forEach((i) => (state.fieldValues[i.dataset.field] = i.value));
329
+ }
330
+
331
+ async function reloadTemplates() {
332
+ state.templates = (await api("/api/templates")).template;
333
+ renderTemplates();
334
+ }
335
+
336
+ /* ---------- stili salvati ---------- */
337
+
338
+ const styleDlg = { editing: null, color: STYLE_COLORS[0], aspect: "1:1", model: "", quality: "" };
339
+
340
+ function openStyleDialog(style = null, fromItem = null) {
341
+ styleDlg.editing = style;
342
+ styleDlg.model = style?.modello || fromItem?.modello || "";
343
+ styleDlg.quality = style?.qualita || fromItem?.qualita || "";
344
+ const modelName = state.models[styleDlg.model]?.nome || (styleDlg.model === BOTH ? "Entrambi" : "");
345
+ $("#sd-model-row").hidden = !modelName;
346
+ $("#sd-model").checked = Boolean(style ? style.modello : fromItem);
347
+ $("#sd-model-label").textContent = `Ricorda anche modello e qualità (${modelName}${styleDlg.quality ? `, ${styleDlg.quality}` : ""})`;
348
+ styleDlg.color = style?.colore || STYLE_COLORS[Math.floor(Math.random() * STYLE_COLORS.length)];
349
+ const itemAspect = fromItem && state.aspects[fromItem.formato] ? fromItem.formato : null;
350
+ styleDlg.aspect = style?.formato || itemAspect || (state.aspect !== "originale" ? state.aspect : "1:1");
351
+ $("#style-dlg-title").textContent = style ? "Modifica stile" : "Nuovo stile";
352
+ $("#sd-name").value = style?.nome || "";
353
+ $("#sd-text").value = style?.testo || "";
354
+ $("#sd-delete").hidden = !style;
355
+ $("#sd-error").textContent = "";
356
+ const sw = $("#sd-colors");
357
+ sw.replaceChildren(...STYLE_COLORS.map((c) => {
358
+ 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); } });
359
+ b.style.setProperty("--c", c);
360
+ return b;
361
+ }));
362
+ const asp = $("#sd-aspect");
363
+ asp.replaceChildren(...Object.keys(state.aspects).map((k) => el("button", {
364
+ type: "button", role: "radio", "aria-checked": String(k === styleDlg.aspect), data: { v: k }, text: k,
365
+ onclick: () => { styleDlg.aspect = k; radio(asp, "v", k); },
366
+ })));
367
+ $("#style-dlg").showModal();
368
+ $("#sd-name").focus();
369
+ if (fromItem) extractStyle(fromItem);
370
+ }
371
+
372
+ async function extractStyle(item) {
373
+ const field = $("#sd-text");
374
+ field.value = "";
375
+ field.placeholder = "Ricavo lo stile dall'immagine…";
376
+ field.disabled = true;
377
+ try {
378
+ const { testo } = await api("/api/styles/extract", { prompt: item.prompt_finale || item.prompt || "", stili: stylesOf(item) });
379
+ field.value = testo || "";
380
+ if (!testo) $("#sd-error").textContent = "Il prompt non descriveva lo stile: scrivilo tu in poche parole (luce, colori, resa).";
381
+ } catch (e) {
382
+ $("#sd-error").textContent = e.message;
383
+ } finally {
384
+ field.disabled = false;
385
+ field.placeholder = "Notte, luci calde ambra e bianche, fumo di palco, folla in controluce, contrasto forte";
386
+ }
387
+ }
388
+
389
+ async function saveStyleDialog() {
390
+ const name = $("#sd-name").value.trim();
391
+ const text = $("#sd-text").value.trim();
392
+ const err = $("#sd-error");
393
+ if (!name || !text) { err.textContent = "Servono un nome e una descrizione."; return; }
394
+ const btn = $("#sd-save");
395
+ btn.disabled = true;
396
+ btn.textContent = "Salvo…";
397
+ try {
398
+ const saved = await api("/api/styles/save", {
399
+ id: styleDlg.editing?.id || "", nome: name, testo: text, formato: styleDlg.aspect, colore: styleDlg.color,
400
+ modello: $("#sd-model").checked && !$("#sd-model-row").hidden ? styleDlg.model : "",
401
+ qualita: $("#sd-model").checked && !$("#sd-model-row").hidden ? styleDlg.quality : "",
402
+ });
403
+ $("#style-dlg").close();
404
+ await reloadTemplates();
405
+ if (!styleDlg.editing && !state.styles.includes(saved.id) && state.styles.length < MAX_STYLES) {
406
+ if (state.mode !== "crea" && state.mode !== "ristila") setMode("crea");
407
+ toggleStyle(saved.id);
408
+ }
409
+ toast(styleDlg.editing ? "Stile aggiornato" : `Stile «${saved.nome}» salvato e selezionato`);
410
+ } catch (e) {
411
+ err.textContent = e.message;
412
+ } finally {
413
+ btn.disabled = false;
414
+ btn.textContent = "Salva stile";
415
+ }
416
+ }
417
+
418
+ async function deleteStyleDialog() {
419
+ const style = styleDlg.editing;
420
+ if (!style) return;
421
+ $("#style-dlg").close();
422
+ const ok = await confirmDialog({ title: `Eliminare «${style.nome}»?`, text: "Le immagini già fatte con questo stile restano.", confirm: "Elimina stile", danger: true });
423
+ if (!ok) return;
424
+ await api("/api/styles/delete", { id: style.id });
425
+ state.styles = state.styles.filter((s) => s !== style.id);
426
+ await reloadTemplates();
427
+ toast("Stile eliminato");
428
+ }
429
+
430
+ /* ---------- formato e qualità ---------- */
431
+
432
+ function renderAspects() {
433
+ const box = $("#aspects");
434
+ box.replaceChildren();
435
+ const entries = Object.entries(state.aspects);
436
+ if (state.mode !== "crea") entries.unshift(["originale", null]);
437
+ for (const [key, dims] of entries) {
438
+ const [w, h] = dims || [3, 4];
439
+ const shape = el("span", { class: "aspect-box" });
440
+ const scale = 22 / Math.max(w, h);
441
+ shape.style.width = `${Math.round(w * scale)}px`;
442
+ shape.style.height = `${Math.round(h * scale)}px`;
443
+ box.append(el("button", {
444
+ type: "button",
445
+ class: "aspect" + (dims ? "" : " aspect-original"),
446
+ role: "radio",
447
+ "aria-checked": "false",
448
+ data: { v: key },
449
+ title: dims ? `${dims[0]}×${dims[1]}` : "Stesse proporzioni della prima foto",
450
+ onclick: () => { state.aspectTouched = true; selectAspect(key); },
451
+ }, [shape, el("span", { text: dims ? key : "Originale" })]));
452
+ }
453
+ radio(box, "v", state.aspect);
454
+ }
455
+
456
+ function selectAspect(key) {
457
+ if (key !== "originale" && !state.aspects[key]) return;
458
+ state.aspect = key;
459
+ radio($("#aspects"), "v", key);
460
+ renderPills();
461
+ }
462
+
463
+ function updateQualityNote() {
464
+ const keys = resolvedModels().filter((k) => state.models[k]);
465
+ if (!keys.length) return;
466
+ const notes = { rapida: "Per provare idee al volo.", bilanciata: "Il punto giusto tra resa e tempo.", massima: "Più dettaglio, un po' più di attesa." };
467
+ const steps = keys.map((k) => `${state.models[k].nome} ${state.models[k].qualita[state.quality]} passi`).join(", ");
468
+ $("#quality-note").textContent = `${notes[state.quality]} ${steps}.`;
469
+ $("#count-note").textContent = state.model === REFINE && keys.length > 1
470
+ ? `Ogni immagine passa da Klein e poi da Z-Image: ricevi ${state.count} ${state.count === 1 ? "immagine finita" : "immagini finite"}.`
471
+ : keys.length > 1 ? `Con Entrambi: ${state.count} per modello, ${state.count * keys.length} in tutto, su due righe.` : "";
472
+ }
473
+
474
+ /* ---------- riepilogo impostazioni nel composer ---------- */
475
+
476
+ function renderPills() {
477
+ const box = $("#pills");
478
+ if (!box) return;
479
+ const pills = [];
480
+ const zoned = state.mode === "modifica" && mask.hasStrokes();
481
+ if (state.mode === "modifica") {
482
+ pills.push({ k: "Zona", v: zoned ? "Solo la parte dipinta" : "Tutta l'immagine", target: "panel-zone", on: zoned });
483
+ } else if (state.mode === "continua") {
484
+ pills.push({ k: "Stile", v: "Come la foto", target: "panel-aspect", on: true });
485
+ } else {
486
+ pills.push({ k: "Stile", v: state.styles.length ? styleNames(state.styles) : "Nessuno", target: "panel-style", on: state.styles.length > 0 });
487
+ }
488
+ if (!zoned) pills.push({ k: "Formato", v: state.aspect === "originale" ? "Come la foto" : state.aspect, target: "panel-aspect" });
489
+ const models = resolvedModels();
490
+ const modelText = state.model === REFINE && models.length > 1 ? "Klein + Z-Image"
491
+ : state.model === BOTH && models.length > 1 ? "Entrambi" : (state.models[models[0]]?.nome || "").replace(" Turbo", "");
492
+ const autoText = state.mode === "ristila" && state.refs.length ? "Auto · sceglie PixRick" : `Auto · ${modelText}`;
493
+ pills.push({ k: "Modello", v: state.model === "auto" && !zoned ? autoText : modelText, target: "panel-model" });
494
+ const n = state.model === REFINE ? state.count : models.length * state.count;
495
+ pills.push({ k: "Qualità", v: `${state.quality[0].toUpperCase()}${state.quality.slice(1)}${n > 1 ? ` · ${n} immagini` : ""}`, target: "panel-quality" });
496
+ box.replaceChildren(...pills.map((p) => el("button", {
497
+ type: "button",
498
+ class: "pill" + (p.on ? " on" : ""),
499
+ title: "Cambia",
500
+ onclick: () => focusPanel(p.target),
501
+ }, [el("span", { class: "pill-k", text: p.k }), el("span", { class: "pill-v", text: p.v })])));
502
+ }
503
+
504
+ function focusPanel(id) {
505
+ const panel = document.getElementById(id);
506
+ if (!panel) return;
507
+ if (panel.tagName === "DETAILS") panel.open = true;
508
+ panel.scrollIntoView({ behavior: "smooth", block: "nearest" });
509
+ panel.classList.remove("flash");
510
+ void panel.offsetWidth;
511
+ panel.classList.add("flash");
512
+ }
513
+
514
+ /* ---------- modalità e foto di partenza ---------- */
515
+
516
+ function setMode(mode) {
517
+ state.mode = mode;
518
+ document.body.dataset.mode = mode;
519
+ $$(".modes [role=tab]").forEach((t) => t.setAttribute("aria-selected", String(t.dataset.mode === mode)));
520
+ const cfg = MODES[mode];
521
+ $("#mode-hint").textContent = cfg.hint;
522
+ $("#prompt").placeholder = cfg.placeholder;
523
+ $("#generate-label").textContent = cfg.button;
524
+ $("#ref-add-label").textContent = mode === "ristila" ? "Foto" : "Foto";
525
+ const supports = state.model === BOTH ? !["modifica", "continua"].includes(mode)
526
+ : state.model === REFINE ? REFINE_MODES.includes(mode)
527
+ : state.model === "auto" || state.models[state.model]?.modalita.includes(mode);
528
+ if (!supports) {
529
+ state.model = "auto";
530
+ 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");
531
+ }
532
+ if (!state.aspectTouched || (mode === "crea" && state.aspect === "originale")) {
533
+ state.aspect = mode === "crea" ? (templateById(state.styles[0])?.formato || "1:1") : "originale";
534
+ state.aspectTouched = false;
535
+ }
536
+ if (mode !== "modifica") brush.stop();
537
+ renderAspects();
538
+ syncAll();
539
+ syncBase();
540
+ updateNextBar();
541
+ }
542
+
543
+ function syncAll() {
544
+ document.body.dataset.modelResolved = resolvedModel();
545
+ document.body.dataset.model = state.model;
546
+ renderModels();
547
+ renderRefs();
548
+ updateQualityNote();
549
+ updateShotActions();
550
+ renderZone();
551
+ renderPills();
552
+ }
553
+
554
+ function renderRefs() {
555
+ const list = $("#ref-list");
556
+ list.replaceChildren();
557
+ const max = MODES[state.mode].maxRefs;
558
+ const shown = state.refs.slice(0, max);
559
+ shown.forEach((r, i) => {
560
+ list.append(el("div", { class: "ref" + (i === 0 ? " main" : "") }, [
561
+ el("img", { src: mediaUrl(r.file), alt: r.nome || `Foto ${i + 1}` }),
562
+ ...(state.mode === "modifica" && shown.length > 1 ? [el("span", { class: "ref-index", text: String(i + 1) })] : []),
563
+ el("button", { type: "button", "aria-label": "Togli questa foto", onclick: () => { state.refs.splice(i, 1); refsChanged(); } }, [icon("i-x")]),
564
+ ]));
565
+ });
566
+ $("#refs").classList.toggle("full", shown.length >= max);
567
+ }
568
+
569
+ function refsChanged() {
570
+ renderRefs();
571
+ if (state.mode !== "crea" && state.refs[0]) sessionAddStart(state.refs[0]);
572
+ syncBase();
573
+ updateNextBar();
574
+ sessionRender();
575
+ }
576
+
577
+ async function addFiles(files) {
578
+ const images = [...files].filter((f) => f.type.startsWith("image/"));
579
+ if (!images.length) return;
580
+ if (state.mode === "crea") setMode(images.length > 1 ? "modifica" : "ristila");
581
+ const max = MODES[state.mode].maxRefs;
582
+ if (state.mode === "ristila" || state.mode === "continua") state.refs = [];
583
+ for (const f of images) {
584
+ if (state.refs.length >= max) { toast(`Al massimo ${max} foto in questa modalità`); break; }
585
+ try {
586
+ const info = await api("/api/upload", f, { "Content-Type": f.type || "application/octet-stream", "X-Filename": encodeURIComponent(f.name || "incollata") });
587
+ state.refs.push(info);
588
+ refsChanged();
589
+ } catch (e) {
590
+ toast(e.message);
591
+ }
592
+ }
593
+ $("#prompt").focus();
594
+ }
595
+
596
+ function useAsRef(item, mode) {
597
+ state.refs = [{ file: "outputs/" + item.file, nome: titleOf(item) }];
598
+ setView("studio");
599
+ setMode(mode);
600
+ refsChanged();
601
+ $("#prompt").value = "";
602
+ autosize();
603
+ $("#prompt").focus();
604
+ const tips = {
605
+ modifica: "Scrivi cosa cambiare, o dipingi prima la zona",
606
+ ristila: "Scegli uno stile o descrivi la trasformazione",
607
+ continua: "Scrivi la nuova scena: stile e personaggi restano quelli",
608
+ };
609
+ toast(tips[mode]);
610
+ }
611
+
612
+ /* ---------- sessione: tutto quello che hai fatto da quando hai aperto la pagina ---------- */
613
+
614
+ const fileName = (f) => (f || "").split("/").pop();
615
+
616
+ function sessionAdd(items, group = "", kind = "risultato") {
617
+ for (const item of items) {
618
+ if (state.session.some((e) => fileName(e.item.file) === fileName(item.file))) continue;
619
+ state.session.push({ item, group, kind });
620
+ }
621
+ sessionRender();
622
+ }
623
+
624
+ function sessionAddStart(ref) {
625
+ if (!ref?.file) return;
626
+ const name = fileName(ref.file);
627
+ const existing = state.session.find((e) => fileName(e.item.file) === name);
628
+ if (existing) { existing.kind = "partenza"; sessionRender(); return; }
629
+ state.session.push({ item: { file: ref.file, nome: ref.nome || "Foto", esterna: true }, group: "", kind: "partenza" });
630
+ sessionRender();
631
+ }
632
+
633
+ function sessionSwap(byName) {
634
+ for (const e of state.session) {
635
+ const n = fileName(e.item.file);
636
+ if (byName.has(n)) e.item = byName.get(n);
637
+ }
638
+ sessionRender();
639
+ }
640
+
641
+ function sessionRemove(files) {
642
+ const gone = new Set(files.map(fileName));
643
+ state.session = state.session.filter((e) => !gone.has(fileName(e.item.file)));
644
+ sessionRender();
645
+ }
646
+
647
+ const sessionSrc = (e) => (e.item.esterna ? mediaUrl(e.item.file) : outputUrl(e.item.miniatura || e.item.file));
648
+
649
+ function sessionActiveName() {
650
+ const st = $("#stage").dataset.state;
651
+ if (st === "base") return fileName(state.refs[0]?.file);
652
+ if (st === "foto") return fileName(state.current?.file);
653
+ return "";
654
+ }
655
+
656
+ function sessionRender() {
657
+ const nav = $("#session");
658
+ const list = $("#session-list");
659
+ nav.hidden = state.session.length === 0;
660
+ list.replaceChildren();
661
+ const active = sessionActiveName();
662
+ const compareGroup = $("#stage").dataset.state === "confronto" ? state.batch.map((b) => fileName(b.file)) : [];
663
+ let lastGroup = null;
664
+ state.session.forEach((e, i) => {
665
+ const name = fileName(e.item.file);
666
+ const siblings = e.group ? state.session.filter((x) => x.group === e.group) : [];
667
+ if (e.group && e.group !== lastGroup && siblings.length > 1) {
668
+ list.append(el("button", {
669
+ type: "button",
670
+ class: "session-group",
671
+ title: "Confronta queste immagini affiancate",
672
+ onclick: () => { state.batch = siblings.map((x) => x.item); showCompare(state.batch); },
673
+ }, [`${siblings.length} insieme`]));
674
+ }
675
+ lastGroup = e.group;
676
+ const isOn = name === active || compareGroup.includes(name);
677
+ list.append(el("button", {
678
+ type: "button",
679
+ class: "session-item" + (isOn ? " on" : "") + (e.item.bozza === false ? " saved" : ""),
680
+ title: e.kind === "partenza" ? "Immagine di partenza" : (MODE_LABEL[e.item.modalita] || "Creata") + (e.item.bozza === false ? " · in galleria" : " · bozza"),
681
+ data: { i: String(i) },
682
+ onclick: () => sessionOpen(i),
683
+ }, [
684
+ el("img", { src: sessionSrc(e), alt: "" }),
685
+ ...(e.kind === "partenza" ? [el("span", { class: "session-tag", text: "partenza" })] : []),
686
+ ]));
687
+ });
688
+ list.querySelector(".session-item.on")?.scrollIntoView({ block: "nearest" });
689
+ }
690
+
691
+ function sessionOpen(i) {
692
+ const e = state.session[i];
693
+ if (!e) return;
694
+ const isStart = state.mode !== "crea" && fileName(state.refs[0]?.file) === fileName(e.item.file);
695
+ if (isStart) {
696
+ state.current = null;
697
+ $("#stage").dataset.state = "";
698
+ syncBase();
699
+ } else if (e.item.esterna) {
700
+ if (state.mode === "crea") setMode("ristila");
701
+ state.refs = [{ file: e.item.file, nome: e.item.nome }];
702
+ refsChanged();
703
+ } else {
704
+ showShot(e.item);
705
+ }
706
+ sessionRender();
707
+ }
708
+
709
+ function sessionStep(delta) {
710
+ if (!state.session.length) return;
711
+ const active = sessionActiveName();
712
+ let i = state.session.findIndex((e) => fileName(e.item.file) === active);
713
+ i = i < 0 ? state.session.length - 1 : Math.max(0, Math.min(state.session.length - 1, i + delta));
714
+ sessionOpen(i);
715
+ }
716
+
717
+ /* ---------- lavoro a cascata: continua dalla nuova versione ---------- */
718
+
719
+ function updateNextBar() {
720
+ const bar = $("#next-bar");
721
+ const it = state.current;
722
+ const ref = state.refs[0]?.file;
723
+ const show = Boolean(
724
+ it && ref && state.mode !== "crea" && !state.busy
725
+ && $("#stage").dataset.state === "foto"
726
+ && `outputs/${it.file}` !== ref
727
+ && state.nextDismissed !== it.file
728
+ && !isPoster(it),
729
+ );
730
+ bar.hidden = !show;
731
+ if (show) $("#next-thumb").src = outputUrl(it.miniatura || it.file);
732
+ }
733
+
734
+ function continueFromCurrent() {
735
+ const it = state.current;
736
+ if (!it) return;
737
+ const others = state.refs.slice(1);
738
+ state.refs = [{ file: "outputs/" + it.file, nome: titleOf(it) }, ...others];
739
+ if (it.modalita === "scontorna" && state.mode === "ristila" && !state.aspectTouched) state.aspect = "originale";
740
+ refsChanged();
741
+ $("#next-bar").hidden = true;
742
+ $("#prompt").focus();
743
+ toast("Ora lavori sulla nuova versione");
744
+ }
745
+
746
+ /* ---------- menu sull'immagine ---------- */
747
+
748
+ const shotMenu = {
749
+ open(e) {
750
+ const item = state.current;
751
+ if (!item || $("#stage").dataset.state !== "foto") return;
752
+ const menu = $("#shot-menu");
753
+ const hasPrompt = Boolean(item.prompt_finale || item.prompt) && !isPoster(item) && !isView(item);
754
+ $("#m-style").disabled = !hasPrompt;
755
+ $("#m-story").disabled = isPoster(item);
756
+ $("#m-refine").hidden = !canRefine(item);
757
+ const r = $("#stage").getBoundingClientRect();
758
+ menu.hidden = false;
759
+ const w = menu.offsetWidth;
760
+ const h = menu.offsetHeight;
761
+ menu.style.left = `${Math.min(r.width - w - 12, Math.max(12, e.clientX - r.left))}px`;
762
+ menu.style.top = `${Math.min(r.height - h - 12, Math.max(12, e.clientY - r.top))}px`;
763
+ menu.querySelector("button:not([disabled])")?.focus();
764
+ },
765
+ close() { $("#shot-menu").hidden = true; },
766
+ wire() {
767
+ $("#shot-img").addEventListener("click", (e) => { e.stopPropagation(); this.open(e); });
768
+ document.addEventListener("click", (e) => { if (!e.target.closest("#shot-menu")) this.close(); });
769
+ document.addEventListener("keydown", (e) => { if (e.key === "Escape") this.close(); });
770
+ const act = (id, fn) => $(id).addEventListener("click", () => { const it = state.current; this.close(); if (it) fn(it); });
771
+ act("#m-story", (it) => useAsRef(it, "continua"));
772
+ act("#m-style", (it) => openStyleDialog(null, it));
773
+ act("#m-refine", runRefine);
774
+ act("#m-zone", (it) => { useAsRef(it, "modifica"); setTimeout(() => brush.start(), 80); });
775
+ act("#m-poster", openInPoster);
776
+ },
777
+ };
778
+
779
+ /* ---------- immagine di partenza e zona dipinta ---------- */
780
+
781
+ function syncBase() {
782
+ const stage = $("#stage");
783
+ const ref = state.mode !== "crea" ? state.refs[0] : null;
784
+ if (ref) {
785
+ const img = $("#base-img");
786
+ if (img.dataset.file !== ref.file) {
787
+ img.dataset.file = ref.file;
788
+ img.src = mediaUrl(ref.file);
789
+ mask.reset();
790
+ }
791
+ $("#base-label").textContent = { modifica: "Immagine da modificare", continua: "La storia parte da qui" }[state.mode] || "Immagine di partenza";
792
+ if (!state.busy) {
793
+ stage.dataset.state = "base";
794
+ $("#shot-bar").hidden = true;
795
+ $("#next-bar").hidden = true;
796
+ $("#base-bar").hidden = brush.active;
797
+ $("#b-upscale").disabled = !state.tools.ingrandisci;
798
+ $("#b-cutout").disabled = !state.tools.scontorna;
799
+ }
800
+ } else {
801
+ brush.stop();
802
+ mask.reset();
803
+ $("#base-img").removeAttribute("src");
804
+ delete $("#base-img").dataset.file;
805
+ if (stage.dataset.state === "base") restoreStage();
806
+ }
807
+ if (stage.dataset.state !== "base") $("#base-bar").hidden = true;
808
+ }
809
+
810
+ function restoreStage() {
811
+ if (state.batch.length > 1 && document.body.dataset.stage === "confronto") showCompare(state.batch);
812
+ else if (state.current) showShot(state.current);
813
+ else clearStage();
814
+ }
815
+
816
+ const mask = {
817
+ strokes: [],
818
+ canvas: null,
819
+ ctx: null,
820
+ hasStrokes() { return this.strokes.some((s) => !s.erase); },
821
+ init() {
822
+ this.canvas = $("#mask-canvas");
823
+ this.ctx = this.canvas.getContext("2d");
824
+ },
825
+ size() {
826
+ const img = $("#base-img");
827
+ return [img.naturalWidth || 1, img.naturalHeight || 1];
828
+ },
829
+ fit() {
830
+ const [w, h] = this.size();
831
+ if (this.canvas.width !== w || this.canvas.height !== h) {
832
+ this.canvas.width = w;
833
+ this.canvas.height = h;
834
+ this.redraw();
835
+ }
836
+ },
837
+ reset() {
838
+ this.strokes = [];
839
+ if (this.ctx) this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
840
+ renderZone();
841
+ },
842
+ undo() {
843
+ this.strokes.pop();
844
+ this.redraw();
845
+ renderZone();
846
+ },
847
+ drawStroke(ctx, s, color) {
848
+ ctx.save();
849
+ ctx.globalCompositeOperation = s.erase && !color ? "destination-out" : "source-over";
850
+ ctx.strokeStyle = color ? (s.erase ? "#000" : "#fff") : "#cbbcff";
851
+ ctx.fillStyle = ctx.strokeStyle;
852
+ ctx.lineWidth = s.size;
853
+ ctx.lineCap = "round";
854
+ ctx.lineJoin = "round";
855
+ if (s.pts.length === 1) {
856
+ ctx.beginPath();
857
+ ctx.arc(s.pts[0][0], s.pts[0][1], s.size / 2, 0, Math.PI * 2);
858
+ ctx.fill();
859
+ } else {
860
+ ctx.beginPath();
861
+ ctx.moveTo(...s.pts[0]);
862
+ for (const p of s.pts.slice(1)) ctx.lineTo(...p);
863
+ ctx.stroke();
864
+ }
865
+ ctx.restore();
866
+ },
867
+ redraw() {
868
+ this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
869
+ for (const s of this.strokes) this.drawStroke(this.ctx, s);
870
+ },
871
+ async upload() {
872
+ const [w, h] = this.size();
873
+ const off = document.createElement("canvas");
874
+ off.width = w;
875
+ off.height = h;
876
+ const c = off.getContext("2d");
877
+ c.fillStyle = "#000";
878
+ c.fillRect(0, 0, w, h);
879
+ for (const s of this.strokes) this.drawStroke(c, s, true);
880
+ const probe = document.createElement("canvas");
881
+ probe.width = 96;
882
+ probe.height = Math.max(1, Math.round((96 * h) / w));
883
+ const pc = probe.getContext("2d");
884
+ pc.drawImage(off, 0, 0, probe.width, probe.height);
885
+ const px = pc.getImageData(0, 0, probe.width, probe.height).data;
886
+ let painted = false;
887
+ for (let i = 0; i < px.length; i += 4) if (px[i] > 40) { painted = true; break; }
888
+ if (!painted) return null;
889
+ const blob = await new Promise((r) => off.toBlob(r, "image/png"));
890
+ const info = await api("/api/upload", blob, { "Content-Type": "image/png", "X-Filename": "zona.png" });
891
+ return info.file;
892
+ },
893
+ };
894
+
895
+ const brush = {
896
+ active: false,
897
+ tool: "pennello",
898
+ drawing: null,
899
+ sizeFraction() { return Number($("#brush-size").value); },
900
+ px() { const [w, h] = mask.size(); return Math.max(4, this.sizeFraction() * Math.min(w, h)); },
901
+ start() {
902
+ if (state.mode !== "modifica" || !state.refs[0]) {
903
+ toast("Aggiungi prima la foto da modificare");
904
+ return;
905
+ }
906
+ if (state.busy) return;
907
+ syncBase();
908
+ mask.fit();
909
+ this.active = true;
910
+ $("#stage").dataset.brush = "on";
911
+ $("#base-bar").hidden = true;
912
+ renderZone();
913
+ },
914
+ stop() {
915
+ this.active = false;
916
+ $("#stage").dataset.brush = "off";
917
+ if ($("#stage").dataset.state === "base") $("#base-bar").hidden = false;
918
+ $("#brush-cursor").classList.remove("show");
919
+ renderZone();
920
+ },
921
+ setTool(tool) {
922
+ this.tool = tool;
923
+ radio($("#brush-bar .seg"), "tool", tool);
924
+ },
925
+ pos(e) {
926
+ const r = mask.canvas.getBoundingClientRect();
927
+ const [w, h] = mask.size();
928
+ return [((e.clientX - r.left) / r.width) * w, ((e.clientY - r.top) / r.height) * h];
929
+ },
930
+ cursor(e) {
931
+ const cur = $("#brush-cursor");
932
+ if (!this.active || !e) { cur.classList.remove("show"); return; }
933
+ const r = mask.canvas.getBoundingClientRect();
934
+ const d = (this.px() * r.width) / mask.size()[0];
935
+ const stage = $("#stage").getBoundingClientRect();
936
+ cur.style.width = cur.style.height = `${d}px`;
937
+ cur.style.transform = `translate(${e.clientX - stage.left - d / 2}px, ${e.clientY - stage.top - d / 2}px)`;
938
+ cur.classList.toggle("erase", this.tool === "gomma");
939
+ cur.classList.add("show");
940
+ },
941
+ wire() {
942
+ const cv = $("#mask-canvas");
943
+ cv.addEventListener("pointerdown", (e) => {
944
+ if (!this.active) return;
945
+ e.preventDefault();
946
+ cv.setPointerCapture(e.pointerId);
947
+ this.drawing = { erase: this.tool === "gomma", size: this.px(), pts: [this.pos(e)] };
948
+ mask.strokes.push(this.drawing);
949
+ mask.drawStroke(mask.ctx, this.drawing);
950
+ });
951
+ cv.addEventListener("pointermove", (e) => {
952
+ this.cursor(e);
953
+ if (!this.drawing) return;
954
+ const p = this.pos(e);
955
+ const last = this.drawing.pts[this.drawing.pts.length - 1];
956
+ if (Math.hypot(p[0] - last[0], p[1] - last[1]) < 2) return;
957
+ this.drawing.pts.push(p);
958
+ const seg = { ...this.drawing, pts: [last, p] };
959
+ mask.drawStroke(mask.ctx, seg);
960
+ });
961
+ const end = () => {
962
+ if (!this.drawing) return;
963
+ this.drawing = null;
964
+ renderZone();
965
+ };
966
+ cv.addEventListener("pointerup", end);
967
+ cv.addEventListener("pointercancel", end);
968
+ cv.addEventListener("pointerleave", () => this.cursor(null));
969
+ $("#base-img").addEventListener("load", () => mask.fit());
970
+ $("#brush-bar .seg").addEventListener("click", (e) => { const b = e.target.closest("[data-tool]"); if (b) this.setTool(b.dataset.tool); });
971
+ $("#brush-undo").addEventListener("click", () => mask.undo());
972
+ $("#brush-clear").addEventListener("click", () => mask.reset());
973
+ $("#brush-done").addEventListener("click", () => { this.stop(); $("#prompt").focus(); });
974
+ $("#zone-btn").addEventListener("click", () => (this.active ? this.stop() : this.start()));
975
+ $("#zone-clear").addEventListener("click", () => mask.reset());
976
+ document.addEventListener("keydown", (e) => {
977
+ if (!this.active || e.target.closest("input, textarea")) return;
978
+ if (e.key === "Escape") this.stop();
979
+ else if (e.key === "b" || e.key === "B") this.setTool("pennello");
980
+ else if (e.key === "e" || e.key === "E") this.setTool("gomma");
981
+ else if (e.key === "[" || e.key === "]") {
982
+ const r = $("#brush-size");
983
+ r.value = String(Number(r.value) + (e.key === "]" ? 0.01 : -0.01));
984
+ } else if (e.key === "z" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); mask.undo(); }
985
+ });
986
+ },
987
+ };
988
+
989
+ function renderZone() {
990
+ const zoned = mask.hasStrokes();
991
+ $("#zone-text").textContent = zoned
992
+ ? "Cambio solo la parte dipinta: il resto della foto resta identico."
993
+ : "Senza zona cambia tutta l'immagine. Dipingi una parte e il resto resterà identico.";
994
+ $("#zone-btn-label").textContent = brush.active ? "Ho finito di dipingere" : zoned ? "Ritocca la zona" : "Dipingi la zona";
995
+ $("#zone-btn").setAttribute("aria-pressed", String(brush.active));
996
+ $("#zone-clear").hidden = !zoned;
997
+ document.body.dataset.zoned = String(zoned && state.mode === "modifica");
998
+ if (state.models.klein) {
999
+ document.body.dataset.modelResolved = resolvedModel();
1000
+ renderPills();
1001
+ }
1002
+ }
1003
+
1004
+ /* ---------- palco: sviluppo, foto, confronto ---------- */
1005
+
1006
+ function grainTile() {
1007
+ if (grainTile.url) return grainTile.url;
1008
+ const c = document.createElement("canvas");
1009
+ c.width = c.height = 160;
1010
+ const ctx = c.getContext("2d");
1011
+ const img = ctx.createImageData(160, 160);
1012
+ for (let i = 0; i < img.data.length; i += 4) {
1013
+ const v = Math.random() * 255;
1014
+ img.data[i] = img.data[i + 1] = img.data[i + 2] = v;
1015
+ img.data[i + 3] = 255;
1016
+ }
1017
+ ctx.putImageData(img, 0, 0);
1018
+ grainTile.url = c.toDataURL("image/png");
1019
+ return grainTile.url;
1020
+ }
1021
+
1022
+ function showWorking(job) {
1023
+ const stage = $("#stage");
1024
+ brush.stop();
1025
+ stage.dataset.state = "lavoro";
1026
+ $("#shot-bar").hidden = true;
1027
+ $("#base-bar").hidden = true;
1028
+ $("#next-bar").hidden = true;
1029
+ const frame = $("#develop-frame");
1030
+ frame.style.setProperty("--ar", String(job.width / job.height));
1031
+ $("#develop-grain").style.backgroundImage = `url(${grainTile()})`;
1032
+ let title = "In coda";
1033
+ let sub = "Parte appena si libera una GPU.";
1034
+ if (job.status === "invio") {
1035
+ title = "Invio la richiesta";
1036
+ sub = "Un attimo.";
1037
+ } else if (job.status === "in_coda" && job.position != null) {
1038
+ title = job.position === 0 ? "Sei il prossimo" : `In coda: ${job.position} prima di te`;
1039
+ sub = job.eta ? `Circa ${Math.max(1, Math.round(job.eta))} s` : "Parte appena si libera una GPU.";
1040
+ } else if (job.status === "salvataggio") {
1041
+ title = "Quasi fatto";
1042
+ sub = "Salvo l'immagine nel tuo browser.";
1043
+ }
1044
+ const tool = TOOL_MODES.includes(job.request.mode);
1045
+ if (job.status === "traduzione") {
1046
+ title = "Traduco il prompt";
1047
+ sub = "Il testo in italiano diventa inglese.";
1048
+ } else if (job.status === "caricamento") {
1049
+ title = `Preparo ${job.model_name}`;
1050
+ sub = "Succede la prima volta o quando cambi modello.";
1051
+ } else if (job.status === "generazione" && job.request.mode === "rifinisci") {
1052
+ title = "Z-Image ripassa la resa";
1053
+ 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`;
1054
+ } else if (job.status === "generazione" && job.refine && job.request.mode !== "rifinisci") {
1055
+ const n = job.request.count;
1056
+ const k = job.current_model === "klein";
1057
+ const idx = k ? job.current + 1 : job.current - n + 1;
1058
+ 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"}`;
1059
+ sub = `${Math.round(job.elapsed)} s`;
1060
+ } else if (job.status === "generazione" && job.request.mode === "viste") {
1061
+ const names = ["lato sinistro", "retro", "lato destro"];
1062
+ title = `Giro la figura: ${names[job.current] || ""}`;
1063
+ sub = `Vista ${job.current + 1} di ${job.total} · ${Math.round(job.elapsed)} s`;
1064
+ } else if (job.status === "generazione" && tool) {
1065
+ title = job.request.mode === "ingrandisci" ? "Raddoppio la risoluzione" : "Tolgo lo sfondo";
1066
+ sub = `${Math.round(job.elapsed)} s`;
1067
+ } else if (job.status === "generazione") {
1068
+ const total = job.total;
1069
+ const within = Math.max(0, job.progress * total - job.current);
1070
+ const steps = job.current_steps;
1071
+ const step = Math.min(steps, Math.max(1, Math.ceil(within * steps)));
1072
+ 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";
1073
+ sub = `${job.model_name} · passo ${step} di ${steps} · ${Math.round(job.elapsed)} s`;
1074
+ }
1075
+ $("#develop-title").textContent = title;
1076
+ $("#develop-sub").textContent = sub;
1077
+ const progress = job.status === "generazione" ? job.progress : job.status === "caricamento" || job.status === "traduzione" ? 0.02 : 0;
1078
+ $("#develop-bar").style.transform = `scaleX(${Math.max(0, Math.min(1, progress))})`;
1079
+ frame.dataset.phase = job.status;
1080
+ }
1081
+
1082
+ function describe(item) {
1083
+ if (isPoster(item)) return ["Locandina", `${item.larghezza}×${item.altezza}`];
1084
+ if (isView(item)) return ["Vista per il 3D", item.vista || "", `${item.larghezza}×${item.altezza}`];
1085
+ const parts = [MODE_LABEL[item.modalita] || "Creata", item.modello_nome || "Z-Image Turbo"];
1086
+ if (isTool(item)) return [...parts, `${item.larghezza}×${item.altezza}`];
1087
+ if (item.maschera) parts.push("solo una zona");
1088
+ if (item.fedelta) parts.push(`fedeltà ${Number(item.fedelta).toFixed(2)}${item.fedelta_auto ? " auto" : ""}`);
1089
+ const styles = stylesOf(item);
1090
+ if (styles.length) parts.push(styleNames(styles));
1091
+ parts.push(`${item.larghezza}×${item.altezza}`, `seme ${item.seed}`);
1092
+ return parts;
1093
+ }
1094
+
1095
+ const metaSpans = (item) => describe(item).map((t) => el("span", { text: t }));
1096
+
1097
+ function showShot(item, fresh = false) {
1098
+ state.current = item;
1099
+ $("#base-bar").hidden = true;
1100
+ document.body.dataset.stage = "foto";
1101
+ const stage = $("#stage");
1102
+ const img = $("#shot-img");
1103
+ img.classList.remove("fresh");
1104
+ img.onload = () => {
1105
+ stage.dataset.state = "foto";
1106
+ if (fresh) { void img.offsetWidth; img.classList.add("fresh"); }
1107
+ updateNextBar();
1108
+ sessionRender();
1109
+ };
1110
+ img.src = outputUrl(item.file);
1111
+ img.alt = titleOf(item);
1112
+ img.classList.toggle("checker", Boolean(item.trasparente));
1113
+ if (img.complete && img.naturalWidth) img.onload();
1114
+ $("#shot-bar").hidden = false;
1115
+ $("#shot-prompt").textContent = titleOf(item);
1116
+ $("#shot-prompt").title = item.prompt_finale || "";
1117
+ $("#shot-meta").replaceChildren(...metaSpans(item));
1118
+ const dl = $("#act-download");
1119
+ dl.href = outputUrl(item.file);
1120
+ dl.download = item.file.split("/").pop();
1121
+ const save = $("#act-save");
1122
+ save.dataset.saved = String(!item.bozza);
1123
+ $("#act-save-label").textContent = item.bozza ? "Salva in galleria" : "In galleria";
1124
+ $("#act-trash").title = item.bozza ? "Elimina la bozza" : "Sposta nel cestino";
1125
+ $("#act-back").hidden = !(state.batch.length > 1 && state.batch.some((b) => b.file === item.file));
1126
+ updateShotActions();
1127
+ updateNextBar();
1128
+ }
1129
+
1130
+ function showCompare(items = state.batch, fresh = false) {
1131
+ state.batch = items;
1132
+ state.current = items[0];
1133
+ document.body.dataset.stage = "confronto";
1134
+ $("#stage").dataset.state = "confronto";
1135
+ $("#base-bar").hidden = true;
1136
+ $("#next-bar").hidden = true;
1137
+ const box = $("#compare");
1138
+ box.replaceChildren();
1139
+ const byModel = [...new Set(items.map((i) => i.modello))];
1140
+ const rows = !isView(items[0]) && byModel.length > 1 && items.length > byModel.length ? byModel.length : 1;
1141
+ box.dataset.rows = String(rows);
1142
+ box.style.setProperty("--cols", String(Math.ceil(items.length / rows)));
1143
+ for (const item of items) {
1144
+ const save = el("button", {
1145
+ type: "button",
1146
+ class: "save-btn",
1147
+ "data-saved": String(!item.bozza),
1148
+ onclick: () => saveItems([item]),
1149
+ }, [icon("i-check"), el("span", { text: item.bozza ? "Salva" : "In galleria" })]);
1150
+ box.append(el("div", { class: "card" }, [
1151
+ el("button", { type: "button", class: "card-media", title: "Guarda da sola", onclick: () => showShot(item) }, [
1152
+ el("img", { src: outputUrl(item.file), alt: titleOf(item), class: fresh ? "fresh" : "" }),
1153
+ ]),
1154
+ el("div", { class: "card-foot" }, [
1155
+ el("span", { class: "card-name" }, isView(item)
1156
+ ? [item.vista, el("small", { text: `${item.larghezza}×${item.altezza}` })]
1157
+ : [item.modello_nome, el("small", { text: `seme ${item.seed}, ${item.larghezza}×${item.altezza}` })]),
1158
+ save,
1159
+ ]),
1160
+ ]));
1161
+ }
1162
+ $("#shot-bar").hidden = false;
1163
+ $("#act-back").hidden = true;
1164
+ $("#shot-prompt").textContent = isView(items[0]) ? "La stessa figura da altre angolazioni" : titleOf(items[0]);
1165
+ $("#shot-prompt").title = items[0].prompt_finale || "";
1166
+ const first = isView(items[0]) ? ["Viste per il 3D", "da dare insieme alla frontale"] : describe(items[0]).filter((p, i) => i !== 1);
1167
+ $("#shot-meta").replaceChildren(...first.map((t) => el("span", { text: t })));
1168
+ sessionRender();
1169
+ const allSaved = items.every((i) => !i.bozza);
1170
+ const all = $("#act-save-all");
1171
+ all.dataset.saved = String(allSaved);
1172
+ all.querySelector("span").textContent = allSaved ? "Tutte in galleria" : "Salva tutte";
1173
+ }
1174
+
1175
+ async function saveItems(items) {
1176
+ const drafts = items.filter((i) => i.bozza);
1177
+ if (!drafts.length) return;
1178
+ const { salvate } = await api("/api/keep", { files: drafts.map((d) => d.file) });
1179
+ const byName = new Map(salvate.map((s) => [s.file.split("/").pop(), s]));
1180
+ const swap = (it) => (it && it.bozza && byName.has(it.file.split("/").pop()) ? byName.get(it.file.split("/").pop()) : it);
1181
+ state.batch = state.batch.map(swap);
1182
+ const current = swap(state.current);
1183
+ sessionSwap(new Map(salvate.map((x) => [fileName(x.file), x])));
1184
+ if (document.body.dataset.stage === "confronto" && $("#stage").dataset.state === "confronto") showCompare(state.batch);
1185
+ else if (current && $("#stage").dataset.state === "foto") showShot(current);
1186
+ else state.current = current;
1187
+ refreshDraftCount();
1188
+ toast(salvate.length === 1 ? "Salvata in galleria" : `${salvate.length} immagini salvate in galleria`);
1189
+ }
1190
+
1191
+ function updateShotActions() {
1192
+ const it = state.current;
1193
+ if (!it) return;
1194
+ const other = otherModel(it.modello || "z-image");
1195
+ const mode = it.modalita || "crea";
1196
+ const canSwitch = !isFixed(it) && mode !== "modifica" && state.models[other]?.modalita.includes(mode);
1197
+ $("#act-variant").disabled = isFixed(it);
1198
+ $("#act-views").hidden = !isPrintable(it);
1199
+ $("#act-refine").hidden = !canRefine(it);
1200
+ $("#act-upscale").disabled = !state.tools.ingrandisci;
1201
+ $("#act-cutout").disabled = !state.tools.scontorna || Boolean(it.trasparente);
1202
+ $("#act-reuse").disabled = isFixed(it);
1203
+ const btn = $("#act-other");
1204
+ btn.disabled = !canSwitch;
1205
+ 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";
1206
+ $("#act-other-label").textContent = canSwitch ? `Prova con ${state.models[other].nome.split(" ")[0]}` : "Altro modello";
1207
+ }
1208
+
1209
+ function clearStage() {
1210
+ state.current = null;
1211
+ $("#base-bar").hidden = true;
1212
+ $("#next-bar").hidden = true;
1213
+ state.batch = [];
1214
+ $("#stage").dataset.state = "vuoto";
1215
+ $("#shot-bar").hidden = true;
1216
+ }
1217
+
1218
+ /* ---------- bozze ---------- */
1219
+
1220
+ async function refreshDraftCount() {
1221
+ try {
1222
+ const { immagini } = await api("/api/history?limit=200&vista=bozze");
1223
+ $("#drafts-count").textContent = immagini.length ? String(immagini.length) : "";
1224
+ } catch { /* server spento */ }
1225
+ }
1226
+
1227
+ async function discardDraft(item) {
1228
+ await api("/api/discard", { files: [item.file] });
1229
+ sessionRemove([item.file]);
1230
+ state.batch = state.batch.filter((b) => b.file !== item.file);
1231
+ if (state.batch.length > 1) showCompare(state.batch);
1232
+ else if (state.batch[0]) showShot(state.batch[0]);
1233
+ else clearStage();
1234
+ syncBase();
1235
+ refreshDraftCount();
1236
+ toast("Bozza eliminata");
1237
+ }
1238
+
1239
+ async function discardFiles(files, all = false) {
1240
+ const n = all ? Number($("#drafts-count").textContent || 0) : files.length;
1241
+ if (!n) return;
1242
+ if (n > 1 || all) {
1243
+ const ok = await confirmDialog({
1244
+ title: all ? "Eliminare tutte le bozze?" : `Eliminare ${n} bozze?`,
1245
+ text: "Le bozze eliminate non passano dal cestino: spariscono subito.",
1246
+ confirm: "Elimina",
1247
+ danger: true,
1248
+ });
1249
+ if (!ok) return;
1250
+ }
1251
+ const { scartate } = await api("/api/discard", all ? { tutto: true } : { files });
1252
+ if (all) { state.session = state.session.filter((e) => e.item.bozza === false || e.item.esterna); sessionRender(); } else sessionRemove(files);
1253
+ g.selected.clear();
1254
+ const gone = all ? null : new Set(files);
1255
+ if (state.current?.bozza && (all || gone.has(state.current.file))) {
1256
+ state.batch = all ? [] : state.batch.filter((b) => !gone.has(b.file));
1257
+ if ($("#stage").dataset.state !== "base") restoreStage();
1258
+ if (!state.batch.length && state.current?.bozza) clearStage();
1259
+ }
1260
+ await Promise.all([loadGallery(), refreshDraftCount()]);
1261
+ toast(scartate === 1 ? "Bozza eliminata" : `${scartate} bozze eliminate`);
1262
+ }
1263
+
1264
+ async function keepFiles(files) {
1265
+ if (!files.length) return;
1266
+ const { salvate } = await api("/api/keep", { files });
1267
+ sessionSwap(new Map(salvate.map((x) => [fileName(x.file), x])));
1268
+ g.selected.clear();
1269
+ await Promise.all([loadGallery(), refreshDraftCount()]);
1270
+ toast(salvate.length === 1 ? "Salvata in galleria" : `${salvate.length} immagini salvate in galleria`);
1271
+ }
1272
+
1273
+ /* ---------- galleria ---------- */
1274
+
1275
+ const g = state.gallery;
1276
+ const serverScope = (f) => (["cestino", "preferite", "bozze"].includes(f) ? f : "galleria");
1277
+
1278
+ function galleryVisible() {
1279
+ if (["tutte", "preferite", "cestino", "bozze"].includes(g.filter)) return g.items;
1280
+ return g.items.filter((i) => (i.modalita || "crea") === g.filter);
1281
+ }
1282
+
1283
+ async function loadGallery(reset = true) {
1284
+ if (reset) { g.offset = 0; g.items = []; g.selected.clear(); }
1285
+ const { immagini } = await api(`/api/history?limit=${PAGE}&offset=${g.offset}&vista=${serverScope(g.filter)}`);
1286
+ g.items = g.items.concat(immagini);
1287
+ g.offset += immagini.length;
1288
+ g.full = immagini.length < PAGE;
1289
+ renderGallery();
1290
+ }
1291
+
1292
+ function renderGallery() {
1293
+ const scope = serverScope(g.filter);
1294
+ const inTrash = scope === "cestino";
1295
+ const inDrafts = scope === "bozze";
1296
+ document.body.dataset.scope = inTrash ? "cestino" : inDrafts ? "bozze" : "galleria";
1297
+ $("#gallery-title").textContent = inTrash ? "Cestino" : inDrafts ? "Bozze" : g.filter === "preferite" ? "Preferite" : "Galleria";
1298
+ $("#trash-note").hidden = !inTrash || g.items.length === 0;
1299
+ $("#drafts-note").hidden = !inDrafts || g.items.length === 0;
1300
+ const box = $("#masonry");
1301
+ box.replaceChildren();
1302
+ const items = galleryVisible();
1303
+ items.forEach((item, index) => {
1304
+ const img = el("img", { src: outputUrl(item.miniatura || item.file), alt: titleOf(item), loading: "lazy" });
1305
+ img.width = item.larghezza;
1306
+ img.height = item.altezza;
1307
+ const tile = el("div", {
1308
+ class: "tile",
1309
+ tabindex: "0",
1310
+ role: "button",
1311
+ "aria-label": titleOf(item),
1312
+ "aria-selected": String(g.selected.has(item.file)),
1313
+ data: { file: item.file, fav: String(Boolean(item.preferita)) },
1314
+ onclick: () => (g.selected.size ? toggleSelect(item.file) : openDetail(index)),
1315
+ onkeydown: (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); openDetail(index); } },
1316
+ }, [
1317
+ img,
1318
+ el("button", { type: "button", class: "tile-check", "aria-label": "Seleziona", onclick: (e) => { e.stopPropagation(); toggleSelect(item.file); } }, [icon("i-check")]),
1319
+ ...(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")])] : []),
1320
+ el("div", { class: "tile-info" }, [el("p", { class: "tile-title", text: titleOf(item) }), el("p", { class: "tile-meta" }, metaSpans(item))]),
1321
+ ]);
1322
+ box.append(tile);
1323
+ });
1324
+ const empty = $("#gallery-empty");
1325
+ empty.hidden = items.length > 0;
1326
+ empty.textContent = inTrash ? "Il cestino è vuoto."
1327
+ : inDrafts ? "Nessuna bozza: quello che generi e non salvi finisce qui per 24 ore."
1328
+ : g.filter === "preferite" ? "Nessuna preferita. Tocca la stella su un'immagine per aggiungerla."
1329
+ : g.filter === "locandina" ? "Nessuna locandina. Componi la prima dalla scheda Locandina."
1330
+ : "Nessuna immagine qui. Torna nello Studio e genera la prima.";
1331
+ $("#more-btn").hidden = g.full;
1332
+ updateSelectionBar();
1333
+ }
1334
+
1335
+ function toggleSelect(file) {
1336
+ if (g.selected.has(file)) g.selected.delete(file); else g.selected.add(file);
1337
+ $$(".tile").forEach((t) => t.setAttribute("aria-selected", String(g.selected.has(t.dataset.file))));
1338
+ updateSelectionBar();
1339
+ }
1340
+
1341
+ function updateSelectionBar() {
1342
+ const n = g.selected.size;
1343
+ $("#selection-bar").hidden = n === 0;
1344
+ $("#masonry").dataset.selecting = String(n > 0);
1345
+ $("#selection-count").textContent = n === 1 ? "1 selezionata" : `${n} selezionate`;
1346
+ }
1347
+
1348
+ async function setFavorite(items, value) {
1349
+ for (const item of items) {
1350
+ const updated = await api("/api/update", { file: item.file, modifiche: { preferita: value } });
1351
+ Object.assign(item, { preferita: updated.preferita });
1352
+ }
1353
+ if (g.filter === "preferite" && !value) g.items = g.items.filter((i) => !items.includes(i));
1354
+ renderGallery();
1355
+ if (detailItem()) renderDetail();
1356
+ }
1357
+
1358
+ async function moveToTrash(files) {
1359
+ if (!files.length) return;
1360
+ await api("/api/trash", { files });
1361
+ sessionRemove(files);
1362
+ const gone = new Set(files);
1363
+ g.items = g.items.filter((i) => !gone.has(i.file));
1364
+ g.selected.clear();
1365
+ renderGallery();
1366
+ if (state.current && gone.has(state.current.file)) {
1367
+ state.batch = state.batch.filter((b) => !gone.has(b.file));
1368
+ if ($("#stage").dataset.state !== "base") { if (state.batch.length) restoreStage(); else clearStage(); }
1369
+ }
1370
+ const label = files.length === 1 ? "Spostata nel cestino" : `${files.length} immagini nel cestino`;
1371
+ toast(label, { label: "Annulla", run: () => restoreFiles(files.map((f) => `_cestino/${f}`), true) });
1372
+ }
1373
+
1374
+ async function restoreFiles(trashFiles, silent = false) {
1375
+ if (!trashFiles.length) return;
1376
+ const { ripristinate } = await api("/api/restore", { files: trashFiles });
1377
+ g.selected.clear();
1378
+ if (document.body.dataset.view === "galleria") await loadGallery();
1379
+ if (!silent) toast(ripristinate === 1 ? "Immagine ripristinata" : `${ripristinate} immagini ripristinate`);
1380
+ }
1381
+
1382
+ async function purgeFiles(trashFiles, all = false) {
1383
+ const n = all ? g.items.length : trashFiles.length;
1384
+ if (!n) return;
1385
+ const what = n === 1 ? "questa immagine" : `${n} immagini`;
1386
+ const ok = await confirmDialog({
1387
+ title: "Eliminare per sempre?",
1388
+ text: `Stai per eliminare ${what} dal cestino. Non si può annullare.`,
1389
+ confirm: "Elimina per sempre",
1390
+ danger: true,
1391
+ });
1392
+ if (!ok) return;
1393
+ const { eliminate } = await api("/api/purge", all ? { tutto: true } : { files: trashFiles });
1394
+ g.selected.clear();
1395
+ await loadGallery();
1396
+ toast(eliminate === 1 ? "Eliminata per sempre" : `${eliminate} immagini eliminate per sempre`);
1397
+ }
1398
+
1399
+ /* ---------- conferma a tema ---------- */
1400
+
1401
+ function confirmDialog({ title, text, confirm = "Conferma", danger = false }) {
1402
+ const dlg = $("#confirm");
1403
+ $("#confirm-title").textContent = title;
1404
+ $("#confirm-text").textContent = text;
1405
+ const yes = $("#confirm-yes");
1406
+ yes.textContent = confirm;
1407
+ yes.classList.toggle("danger", danger);
1408
+ yes.classList.toggle("primary", !danger);
1409
+ dlg.returnValue = "";
1410
+ dlg.showModal();
1411
+ $("#confirm-no").focus();
1412
+ return new Promise((resolve) => dlg.addEventListener("close", () => resolve(dlg.returnValue === "si"), { once: true }));
1413
+ }
1414
+
1415
+ /* ---------- scheda dettaglio ---------- */
1416
+
1417
+ const detailItem = () => galleryVisible()[g.detailIndex];
1418
+
1419
+ function openDetail(index) {
1420
+ g.detailIndex = index;
1421
+ $(".detail-media").classList.remove("zoomed");
1422
+ renderDetail();
1423
+ const dlg = $("#detail");
1424
+ if (!dlg.open) dlg.showModal();
1425
+ }
1426
+
1427
+ function renderDetail() {
1428
+ const item = detailItem();
1429
+ if (!item) { $("#detail").close(); return; }
1430
+ const dlg = $("#detail");
1431
+ const scope = serverScope(g.filter);
1432
+ dlg.dataset.scope = scope === "preferite" ? "galleria" : scope;
1433
+ $("#detail-img").src = outputUrl(item.file);
1434
+ $("#detail-img").classList.toggle("checker", Boolean(item.trasparente));
1435
+ $("#d-variant").disabled = isFixed(item);
1436
+ $("#d-style").disabled = !(item.prompt_finale || item.prompt) || isPoster(item) || isView(item);
1437
+ $("#d-story").disabled = isPoster(item);
1438
+ $("#d-views").hidden = !isPrintable(item);
1439
+ $("#d-refine").hidden = !canRefine(item);
1440
+ $("#d-upscale").disabled = !state.tools.ingrandisci;
1441
+ $("#d-cutout").disabled = !state.tools.scontorna || Boolean(item.trasparente);
1442
+ $("#detail-img").alt = titleOf(item);
1443
+ const title = $("#detail-title");
1444
+ title.value = item.titolo || "";
1445
+ title.readOnly = scope !== "galleria" && scope !== "preferite";
1446
+ title.placeholder = item.prompt ? item.prompt.slice(0, 60) : "Senza titolo";
1447
+ $("#detail-prompt").textContent = item.prompt_finale || item.prompt || "";
1448
+ const rows = isPoster(item)
1449
+ ? [["Tipo", "Locandina"], ["Misura", `${item.larghezza}×${item.altezza}`], ["Creata", item.creata]]
1450
+ : [
1451
+ ["Modalità", MODE_LABEL[item.modalita] || "Creata"],
1452
+ ...(item.vista ? [["Vista", item.vista]] : []),
1453
+ ["Modello", item.modello_nome || "Z-Image Turbo"],
1454
+ ...(item.maschera ? [["Zona", "Solo la parte dipinta"]] : []),
1455
+ ...(stylesOf(item).length ? [["Stili", styleNames(stylesOf(item))]] : []),
1456
+ ["Misura", `${item.larghezza}×${item.altezza}`],
1457
+ ...(isTool(item) || isView(item) ? [] : [["Qualità", `${item.qualita || "bilanciata"}, ${item.passi} passi`], ["Seme", String(item.seed)]]),
1458
+ ["Creata", `${item.creata}${item.origine === "claude" ? " da Claude" : ""}`],
1459
+ ];
1460
+ $("#detail-meta").replaceChildren(...rows.flatMap(([k, v]) => [el("dt", { text: k }), el("dd", { text: v })]));
1461
+ const fav = $("#d-fav");
1462
+ fav.setAttribute("aria-pressed", String(Boolean(item.preferita)));
1463
+ $("#d-fav-label").textContent = item.preferita ? "Tra le preferite" : "Preferita";
1464
+ const dl = $("#d-download");
1465
+ dl.href = outputUrl(item.file);
1466
+ dl.download = item.file.split("/").pop();
1467
+ const total = galleryVisible().length;
1468
+ $("#detail-prev").disabled = g.detailIndex <= 0;
1469
+ $("#detail-next").disabled = g.detailIndex >= total - 1;
1470
+ }
1471
+
1472
+ async function saveTitle() {
1473
+ const item = detailItem();
1474
+ if (!item || !["galleria", "preferite"].includes(serverScope(g.filter))) return;
1475
+ const value = $("#detail-title").value.trim();
1476
+ if (value === (item.titolo || "")) return;
1477
+ const updated = await api("/api/update", { file: item.file, modifiche: { titolo: value } });
1478
+ item.titolo = updated.titolo;
1479
+ if (state.current?.file === item.file) state.current.titolo = updated.titolo;
1480
+ renderGallery();
1481
+ toast(value ? "Titolo salvato" : "Titolo tolto");
1482
+ }
1483
+
1484
+ function stepDetail(delta) {
1485
+ const next = g.detailIndex + delta;
1486
+ if (next < 0 || next >= galleryVisible().length) return;
1487
+ saveTitle();
1488
+ g.detailIndex = next;
1489
+ renderDetail();
1490
+ }
1491
+
1492
+ /* ---------- viste ---------- */
1493
+
1494
+ function setView(view) {
1495
+ document.body.dataset.view = view;
1496
+ $$(".views button").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.view === view)));
1497
+ $("#studio").hidden = view !== "studio";
1498
+ $("#gallery").hidden = view !== "galleria";
1499
+ $("#poster").hidden = view !== "locandina";
1500
+ if (view === "galleria") { loadGallery(); refreshDraftCount(); }
1501
+ if (view === "locandina") window.PosterStudio?.show();
1502
+ }
1503
+
1504
+ /* ---------- generazione ---------- */
1505
+
1506
+ async function readForm() {
1507
+ saveFieldValues();
1508
+ const campi = {};
1509
+ for (const id of state.styles) for (const f of templateById(id)?.campi || []) campi[f.id] = state.fieldValues[f.id] || "";
1510
+ const seed = $("#seed").value.trim();
1511
+ const payload = {
1512
+ modalita: state.mode,
1513
+ modello: state.model,
1514
+ prompt: $("#prompt").value,
1515
+ stili: ["modifica", "continua"].includes(state.mode) ? [] : state.styles,
1516
+ campi,
1517
+ riferimenti: state.refs.slice(0, MODES[state.mode].maxRefs).map((r) => r.file),
1518
+ formato: state.aspect,
1519
+ qualita: state.quality,
1520
+ fedelta: $("#fidelity-auto").checked ? null : Number($("#fidelity").value),
1521
+ seed: seed === "" ? null : Number(seed),
1522
+ quantita: state.count,
1523
+ traduci: $("#translate").checked,
1524
+ };
1525
+ if (state.mode === "modifica" && mask.hasStrokes() && payload.prompt.trim() && payload.riferimenti.length) {
1526
+ payload.maschera = await mask.upload();
1527
+ }
1528
+ return payload;
1529
+ }
1530
+
1531
+ function runRefine(item) {
1532
+ if (!canRefine(item)) return;
1533
+ state.refineFrom = item;
1534
+ submit({
1535
+ modalita: "rifinisci",
1536
+ riferimenti: ["outputs/" + item.file],
1537
+ prompt: item.prompt || "",
1538
+ stili: stylesOf(item).filter((id) => templateById(id)),
1539
+ qualita: state.quality,
1540
+ });
1541
+ }
1542
+
1543
+ function runViews(item) {
1544
+ if (!item) return;
1545
+ submit({ modalita: "viste", riferimenti: ["outputs/" + item.file], qualita: state.quality });
1546
+ }
1547
+
1548
+ function runTool(item, tool) {
1549
+ if (!item) return;
1550
+ submit({ modalita: tool, riferimenti: ["outputs/" + item.file] });
1551
+ }
1552
+
1553
+ /* ---------- vettorizza: PNG → SVG ---------- */
1554
+
1555
+ const vectorizer = {
1556
+ source: null,
1557
+ style: "colori",
1558
+ svg: "",
1559
+ ticket: 0,
1560
+ open(path, name) {
1561
+ if (!state.tools.vettorizza) {
1562
+ toast("Manca il vettorizzatore: rilancia Installa.command una volta.");
1563
+ return;
1564
+ }
1565
+ this.source = path;
1566
+ this.name = (name || path.split("/").pop()).replace(/\.[a-z0-9]+$/i, "");
1567
+ $("#vector-dlg").showModal();
1568
+ this.run();
1569
+ },
1570
+ async run() {
1571
+ const ticket = ++this.ticket;
1572
+ const view = $("#vector-view");
1573
+ view.dataset.state = "lavoro";
1574
+ $("#vector-download").disabled = true;
1575
+ $("#vector-stats").textContent = "";
1576
+ try {
1577
+ const res = await api("/api/vectorize", { file: this.source, stile: this.style, trasparente: $("#vector-transparent").checked });
1578
+ if (ticket !== this.ticket) return;
1579
+ this.svg = res.svg;
1580
+ $("#vector-art").innerHTML = res.svg;
1581
+ $("#vector-stats").textContent = `${res.tracciati} forme · ${res.kb.toLocaleString("it-IT")} KB`;
1582
+ $("#vector-warn").hidden = !res.foto || this.style === "contorno";
1583
+ $("#vector-download").disabled = false;
1584
+ view.dataset.state = "pronto";
1585
+ } catch (err) {
1586
+ if (ticket !== this.ticket) return;
1587
+ view.dataset.state = "errore";
1588
+ $("#vector-stats").textContent = err.message;
1589
+ }
1590
+ },
1591
+ download() {
1592
+ const url = URL.createObjectURL(new Blob([this.svg], { type: "image/svg+xml" }));
1593
+ const a = Object.assign(document.createElement("a"), { href: url, download: `${this.name}_${this.style}.svg` });
1594
+ a.click();
1595
+ setTimeout(() => URL.revokeObjectURL(url), 2000);
1596
+ },
1597
+ bind() {
1598
+ $("#vector-styles").addEventListener("click", (e) => {
1599
+ const btn = e.target.closest("[role=radio]");
1600
+ if (!btn || btn.dataset.v === this.style) return;
1601
+ this.style = btn.dataset.v;
1602
+ radio($("#vector-styles"), "v", this.style);
1603
+ this.run();
1604
+ });
1605
+ $("#vector-transparent").addEventListener("change", () => this.run());
1606
+ $("#vector-dark").addEventListener("change", (e) => $("#vector-view").classList.toggle("dark", e.target.checked));
1607
+ $("#vector-close").addEventListener("click", () => $("#vector-dlg").close());
1608
+ $("#vector-download").addEventListener("click", () => this.download());
1609
+ $("#vector-dlg").addEventListener("close", () => { this.ticket++; $("#vector-art").innerHTML = ""; });
1610
+ },
1611
+ };
1612
+
1613
+ /* ---------- prompt migliorato: inglese per il modello, italiano per te ---------- */
1614
+
1615
+ const bilingual = {
1616
+ on: false,
1617
+ syncedIt: "",
1618
+ syncedEn: "",
1619
+ open(en, it) {
1620
+ this.on = true;
1621
+ $("#prompt").value = en;
1622
+ $("#prompt-it").value = it;
1623
+ this.syncedIt = it;
1624
+ this.syncedEn = en;
1625
+ $("#prompt-area").classList.add("bilingual");
1626
+ this.check();
1627
+ autosize();
1628
+ },
1629
+ close() {
1630
+ this.on = false;
1631
+ $("#prompt-area").classList.remove("bilingual");
1632
+ $("#prompt-it").value = "";
1633
+ autosize();
1634
+ },
1635
+ check() {
1636
+ $("#sync-en").hidden = !this.on || $("#prompt-it").value.trim() === this.syncedIt.trim();
1637
+ $("#sync-it").hidden = !this.on || $("#prompt").value.trim() === this.syncedEn.trim();
1638
+ },
1639
+ async sync(direction) {
1640
+ const from = direction === "en" ? $("#prompt-it") : $("#prompt");
1641
+ const to = direction === "en" ? $("#prompt") : $("#prompt-it");
1642
+ const btn = direction === "en" ? $("#sync-en") : $("#sync-it");
1643
+ btn.textContent = "Traduco…";
1644
+ btn.disabled = true;
1645
+ try {
1646
+ const { testo } = await api("/api/translate", { testo: from.value, verso: direction });
1647
+ to.value = testo;
1648
+ this.syncedIt = $("#prompt-it").value;
1649
+ this.syncedEn = $("#prompt").value;
1650
+ autosize();
1651
+ } catch (e) {
1652
+ $("#form-error").textContent = e.message;
1653
+ } finally {
1654
+ btn.textContent = direction === "en" ? "Aggiorna l'inglese" : "Aggiorna l'italiano";
1655
+ btn.disabled = false;
1656
+ this.check();
1657
+ }
1658
+ },
1659
+ wire() {
1660
+ $("#prompt-it").addEventListener("input", () => { this.check(); autosize(); });
1661
+ $("#prompt").addEventListener("input", () => this.check());
1662
+ $("#sync-en").addEventListener("click", () => this.sync("en"));
1663
+ $("#sync-it").addEventListener("click", () => this.sync("it"));
1664
+ $("#bilingual-close").addEventListener("click", () => this.close());
1665
+ },
1666
+ };
1667
+
1668
+ async function enhancePrompt() {
1669
+ const field = $("#prompt");
1670
+ const before = bilingual.on ? $("#prompt-it").value : field.value;
1671
+ if (!before.trim()) {
1672
+ $("#form-error").textContent = "Scrivi prima un'idea, anche in italiano: la trasformo in un prompt dettagliato.";
1673
+ return;
1674
+ }
1675
+ const btn = $("#enhance-btn");
1676
+ btn.setAttribute("aria-busy", "true");
1677
+ $("#form-error").textContent = "";
1678
+ try {
1679
+ const { prompt, italiano } = await api("/api/enhance", { prompt: before, modalita: state.mode });
1680
+ bilingual.open(prompt, italiano || "");
1681
+ toast("A sinistra in italiano, a destra quello che va al modello. Correggi pure, poi genera", {
1682
+ label: "Annulla",
1683
+ run: () => { bilingual.close(); field.value = before; autosize(); },
1684
+ });
1685
+ } catch (e) {
1686
+ $("#form-error").textContent = e.message;
1687
+ } finally {
1688
+ btn.removeAttribute("aria-busy");
1689
+ }
1690
+ }
1691
+
1692
+ function payloadFromItem(item, overrides = {}) {
1693
+ return {
1694
+ modalita: item.modalita || "crea",
1695
+ modello: item.modello || "auto",
1696
+ prompt: item.prompt,
1697
+ stili: stylesOf(item).filter((id) => templateById(id)),
1698
+ campi: item.campi || {},
1699
+ riferimenti: item.riferimenti || [],
1700
+ maschera: item.maschera || null,
1701
+ formato: item.formato,
1702
+ qualita: item.qualita || "bilanciata",
1703
+ fedelta: item.fedelta_auto ? null : item.fedelta ?? null,
1704
+ seed: item.seed,
1705
+ quantita: 1,
1706
+ ...overrides,
1707
+ };
1708
+ }
1709
+
1710
+ async function submitFromComposer() {
1711
+ if (state.busy) return;
1712
+ try {
1713
+ submit(await readForm(), true);
1714
+ } catch (e) {
1715
+ $("#form-error").textContent = e.message;
1716
+ }
1717
+ }
1718
+
1719
+ async function submit(payload, fromComposer = false) {
1720
+ if (state.busy) return;
1721
+ const err = $("#form-error");
1722
+ err.textContent = "";
1723
+ state.busy = true;
1724
+ $("#generate-btn").disabled = true;
1725
+ try {
1726
+ const job = await api("/api/generate", payload);
1727
+ if (fromComposer && payload.prompt.trim()) {
1728
+ state.lastPrompt = payload.prompt;
1729
+ $("#prompt").value = "";
1730
+ bilingual.close();
1731
+ autosize();
1732
+ }
1733
+ setView("studio");
1734
+ showWorking(job);
1735
+ track(job.id);
1736
+ } catch (e) {
1737
+ err.textContent = e.message;
1738
+ state.busy = false;
1739
+ $("#generate-btn").disabled = false;
1740
+ }
1741
+ }
1742
+
1743
+ function finishJob() {
1744
+ state.busy = false;
1745
+ $("#generate-btn").disabled = false;
1746
+ refreshStatus();
1747
+ refreshDraftCount();
1748
+ }
1749
+
1750
+ function track(jobId) {
1751
+ clearInterval(state.polling);
1752
+ state.polling = setInterval(async () => {
1753
+ let job;
1754
+ try { job = await api(`/api/jobs/${jobId}`); } catch { return; }
1755
+ if (job.status === "fatto" || job.status === "errore") {
1756
+ clearInterval(state.polling);
1757
+ finishJob();
1758
+ if (job.status === "errore") {
1759
+ if (job.error_code === "quota") window.PixOnline?.quota(job.retry_in);
1760
+ else $("#form-error").textContent = job.error;
1761
+ if (state.lastPrompt && !$("#prompt").value) { $("#prompt").value = state.lastPrompt; autosize(); }
1762
+ if (state.mode !== "crea" && state.refs[0]) syncBase(); else restoreStage();
1763
+ return;
1764
+ }
1765
+ const n = job.results.length;
1766
+ sessionAdd(job.results, job.id);
1767
+ if (job.request.mode === "rifinisci" && state.refineFrom) {
1768
+ state.batch = [state.refineFrom, ...job.results];
1769
+ state.refineFrom = null;
1770
+ showCompare(state.batch, true);
1771
+ toast("Prima e dopo: tieni quella che ti piace di più");
1772
+ return;
1773
+ }
1774
+ state.batch = job.results;
1775
+ if (n > 1) showCompare(job.results, true);
1776
+ else showShot(job.results[0], true);
1777
+ if (job.results[0]?.nota) { toast(job.results[0].nota); return; }
1778
+ if (job.request.mode === "viste") { toast("Viste pronte: salva quelle buone e dalle a Tripo, Meshy o Hunyuan3D insieme alla frontale"); return; }
1779
+ toast(n > 1 ? `${n} immagini pronte in ${job.elapsed} s: salva quelle che ti piacciono` : `Pronta in ${job.elapsed} s`);
1780
+ return;
1781
+ }
1782
+ showWorking(job);
1783
+ if (job.status === "caricamento") refreshStatus();
1784
+ }, 600);
1785
+ }
1786
+
1787
+ /* ---------- azioni sullo scatto ---------- */
1788
+
1789
+ function reuse(item = state.current) {
1790
+ if (!item || isFixed(item)) return;
1791
+ setView("studio");
1792
+ state.refs = (item.riferimenti || []).map((file) => ({ file }));
1793
+ state.model = item.modello || "auto";
1794
+ state.styles = stylesOf(item).filter((id) => templateById(id));
1795
+ state.fieldValues = { ...(item.campi || {}) };
1796
+ state.quality = item.qualita || "bilanciata";
1797
+ radio($("#quality"), "v", state.quality);
1798
+ $("#fidelity-auto").checked = item.fedelta_auto !== false || !item.fedelta;
1799
+ if (item.fedelta) $("#fidelity").value = item.fedelta;
1800
+ $("#fidelity").dispatchEvent(new Event("input"));
1801
+ $("#prompt").value = item.prompt || "";
1802
+ $("#seed").value = item.seed;
1803
+ setMode(item.modalita || "crea");
1804
+ renderStyleState();
1805
+ state.aspectTouched = true;
1806
+ renderAspects();
1807
+ selectAspect(item.formato);
1808
+ autosize();
1809
+ if (state.mode === "crea") showShot(item);
1810
+ toast("Impostazioni caricate, seme compreso");
1811
+ }
1812
+
1813
+ function openInPoster(item) {
1814
+ if (!item) return;
1815
+ setView("locandina");
1816
+ window.PosterStudio?.setBackground("outputs/" + item.file);
1817
+ }
1818
+
1819
+ /* ---------- eventi ---------- */
1820
+
1821
+ function autosize() {
1822
+ for (const t of [$("#prompt"), $("#prompt-it")]) {
1823
+ t.style.height = "auto";
1824
+ t.style.height = `${Math.min(bilingual.on ? 220 : 180, t.scrollHeight)}px`;
1825
+ }
1826
+ }
1827
+
1828
+ function wire() {
1829
+ $("#composer").addEventListener("submit", (e) => { e.preventDefault(); submitFromComposer(); });
1830
+ document.addEventListener("keydown", (e) => {
1831
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && document.body.dataset.view === "studio" && !document.querySelector("dialog[open]:not(#guide)")) {
1832
+ e.preventDefault();
1833
+ submitFromComposer();
1834
+ }
1835
+ if ($("#detail").open && document.activeElement !== $("#detail-title")) {
1836
+ if (e.key === "ArrowLeft") stepDetail(-1);
1837
+ if (e.key === "ArrowRight") stepDetail(1);
1838
+ }
1839
+ });
1840
+ const prompt = $("#prompt");
1841
+ prompt.addEventListener("input", autosize);
1842
+ prompt.addEventListener("keydown", (e) => {
1843
+ if (e.key === "ArrowUp" && !prompt.value && state.lastPrompt) {
1844
+ e.preventDefault();
1845
+ prompt.value = state.lastPrompt;
1846
+ autosize();
1847
+ }
1848
+ });
1849
+ $$(".modes [role=tab]").forEach((t) => t.addEventListener("click", () => setMode(t.dataset.mode)));
1850
+ $$(".views button").forEach((b) => b.addEventListener("click", () => setView(b.dataset.view)));
1851
+ $("#file-input").addEventListener("change", (e) => { addFiles(e.target.files); e.target.value = ""; });
1852
+
1853
+ const stage = $("#stage");
1854
+ let depth = 0;
1855
+ const hasFiles = (e) => [...(e.dataTransfer?.types || [])].includes("Files");
1856
+ document.addEventListener("dragenter", (e) => { if (hasFiles(e) && document.body.dataset.view === "studio") { depth++; stage.classList.add("dragging"); } });
1857
+ document.addEventListener("dragleave", () => { depth = Math.max(0, depth - 1); if (!depth) stage.classList.remove("dragging"); });
1858
+ document.addEventListener("dragover", (e) => { if (hasFiles(e)) e.preventDefault(); });
1859
+ document.addEventListener("drop", (e) => {
1860
+ if (!hasFiles(e)) return;
1861
+ e.preventDefault();
1862
+ depth = 0;
1863
+ stage.classList.remove("dragging");
1864
+ if (document.body.dataset.view === "locandina") return;
1865
+ setView("studio");
1866
+ addFiles(e.dataTransfer.files);
1867
+ });
1868
+ document.addEventListener("paste", (e) => {
1869
+ if (document.body.dataset.view !== "studio") return;
1870
+ const files = [...(e.clipboardData?.files || [])].filter((f) => f.type.startsWith("image/"));
1871
+ if (files.length) { e.preventDefault(); addFiles(files); }
1872
+ });
1873
+
1874
+ $("#quality").addEventListener("click", (e) => {
1875
+ const b = e.target.closest("[data-v]");
1876
+ if (!b) return;
1877
+ state.quality = b.dataset.v;
1878
+ radio($("#quality"), "v", state.quality);
1879
+ updateQualityNote();
1880
+ renderPills();
1881
+ });
1882
+ $("#count").addEventListener("click", (e) => {
1883
+ const b = e.target.closest("[data-v]");
1884
+ if (!b) return;
1885
+ state.count = Number(b.dataset.v);
1886
+ radio($("#count"), "v", b.dataset.v);
1887
+ renderPills();
1888
+ });
1889
+ const fid = $("#fidelity");
1890
+ const fidAuto = $("#fidelity-auto");
1891
+ const fidNote = () => {
1892
+ const v = Number(fid.value);
1893
+ const auto = fidAuto.checked;
1894
+ $("#fidelity-manual").hidden = auto;
1895
+ $("#fidelity-auto-note").hidden = !auto;
1896
+ $("#fidelity-out").textContent = auto ? "Auto" : v.toFixed(2);
1897
+ $("#fidelity-note").textContent = v <= 0.25 ? "Molto libero: tiene colori e posa, ridisegna il resto."
1898
+ : v <= 0.4 ? "Equilibrato: riconoscibile, ma con spazio per cambiare."
1899
+ : v <= 0.6 ? "Fedele: cambia lo stile, forme e proporzioni restano quelle."
1900
+ : "Quasi identica: solo un ritocco di stile.";
1901
+ };
1902
+ fid.addEventListener("input", fidNote);
1903
+ fidAuto.addEventListener("change", fidNote);
1904
+ fidNote();
1905
+ $("#seed-dice").addEventListener("click", () => ($("#seed").value = Math.floor(Math.random() * 2147483647)));
1906
+
1907
+ // scatto nello studio
1908
+ $("#act-variant").addEventListener("click", () => state.current && submit(payloadFromItem(state.current, { seed: null })));
1909
+ $("#act-other").addEventListener("click", () => {
1910
+ const it = state.current;
1911
+ if (it) submit(payloadFromItem(it, { modello: otherModel(it.modello || "z-image") }));
1912
+ });
1913
+ $("#act-edit").addEventListener("click", () => state.current && useAsRef(state.current, "modifica"));
1914
+ $("#act-restyle").addEventListener("click", () => state.current && useAsRef(state.current, "ristila"));
1915
+ $("#act-reuse").addEventListener("click", () => reuse());
1916
+ $("#act-upscale").addEventListener("click", () => runTool(state.current, "ingrandisci"));
1917
+ $("#act-cutout").addEventListener("click", () => runTool(state.current, "scontorna"));
1918
+ $("#act-poster").addEventListener("click", () => openInPoster(state.current));
1919
+ $("#act-vector").addEventListener("click", () => state.current && vectorizer.open("outputs/" + state.current.file, state.current.file));
1920
+ $("#b-vector").addEventListener("click", () => baseRef() && vectorizer.open(baseRef(), state.refs[0]?.name));
1921
+ vectorizer.bind();
1922
+ $("#act-views").addEventListener("click", () => runViews(state.current));
1923
+ $("#act-refine").addEventListener("click", () => runRefine(state.current));
1924
+ const baseRef = () => state.refs[0]?.file;
1925
+ $("#b-upscale").addEventListener("click", () => baseRef() && submit({ modalita: "ingrandisci", riferimenti: [baseRef()] }));
1926
+ $("#b-cutout").addEventListener("click", () => baseRef() && submit({ modalita: "scontorna", riferimenti: [baseRef()] }));
1927
+ $("#b-poster").addEventListener("click", () => { if (baseRef()) { setView("locandina"); window.PosterStudio?.setBackground(baseRef()); } });
1928
+ $("#enhance-btn").addEventListener("click", enhancePrompt);
1929
+ const translate = $("#translate");
1930
+ translate.checked = prefs.get("traduci", true);
1931
+ translate.addEventListener("change", () => prefs.set("traduci", translate.checked));
1932
+ $("#act-copy").addEventListener("click", async () => {
1933
+ if (!state.current) return;
1934
+ await navigator.clipboard.writeText(state.current.prompt_finale || state.current.prompt);
1935
+ toast("Prompt completo copiato");
1936
+ });
1937
+ $("#act-trash").addEventListener("click", () => {
1938
+ const it = state.current;
1939
+ if (!it) return;
1940
+ if (it.bozza) discardDraft(it); else moveToTrash([it.file]);
1941
+ });
1942
+ $("#act-save").addEventListener("click", () => state.current && saveItems([state.current]));
1943
+ $("#act-save-all").addEventListener("click", () => saveItems(state.batch));
1944
+ $("#act-back").addEventListener("click", () => showCompare(state.batch));
1945
+
1946
+ // stili salvati
1947
+ $("#sd-save").addEventListener("click", saveStyleDialog);
1948
+ $("#sd-delete").addEventListener("click", deleteStyleDialog);
1949
+ $("#style-form").addEventListener("submit", (e) => { if (e.submitter?.value !== "no") { e.preventDefault(); saveStyleDialog(); } });
1950
+ $("#sd-from-prompt").addEventListener("click", () => {
1951
+ const text = $("#prompt").value.trim() || state.lastPrompt;
1952
+ if (text) $("#sd-text").value = text;
1953
+ else $("#sd-error").textContent = "Nel campo del prompt non c'è ancora niente.";
1954
+ });
1955
+
1956
+ // galleria
1957
+ $("#filters").addEventListener("click", (e) => {
1958
+ const b = e.target.closest("[data-f]");
1959
+ if (!b) return;
1960
+ const was = serverScope(g.filter);
1961
+ g.filter = b.dataset.f;
1962
+ radio($("#filters"), "f", g.filter);
1963
+ g.selected.clear();
1964
+ if (serverScope(g.filter) !== was) loadGallery(); else renderGallery();
1965
+ });
1966
+ $("#more-btn").addEventListener("click", () => loadGallery(false));
1967
+ $("#empty-trash").addEventListener("click", () => purgeFiles([], true));
1968
+ $("#drafts-clear").addEventListener("click", () => discardFiles([], true));
1969
+ $("#sel-clear").addEventListener("click", () => { g.selected.clear(); renderGallery(); });
1970
+ $("#sel-trash").addEventListener("click", () => moveToTrash([...g.selected]));
1971
+ $("#sel-keep").addEventListener("click", () => keepFiles([...g.selected]));
1972
+ $("#sel-discard").addEventListener("click", () => discardFiles([...g.selected]));
1973
+ $("#sel-fav").addEventListener("click", () => {
1974
+ const items = g.items.filter((i) => g.selected.has(i.file));
1975
+ const value = !items.every((i) => i.preferita);
1976
+ g.selected.clear();
1977
+ setFavorite(items, value);
1978
+ });
1979
+ $("#sel-restore").addEventListener("click", () => restoreFiles([...g.selected]));
1980
+ $("#sel-purge").addEventListener("click", () => purgeFiles([...g.selected]));
1981
+
1982
+ // scheda dettaglio
1983
+ const dlg = $("#detail");
1984
+ $("#detail-close").addEventListener("click", () => dlg.close());
1985
+ dlg.addEventListener("click", (e) => { if (e.target === dlg) dlg.close(); });
1986
+ dlg.addEventListener("close", saveTitle);
1987
+ $("#detail-title").addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); saveTitle(); e.target.blur(); } });
1988
+ $("#detail-title").addEventListener("blur", saveTitle);
1989
+ $("#detail-img").addEventListener("click", () => $(".detail-media").classList.toggle("zoomed"));
1990
+ $("#detail-prev").addEventListener("click", () => stepDetail(-1));
1991
+ $("#detail-next").addEventListener("click", () => stepDetail(1));
1992
+ const fromDetail = (fn) => () => { const it = detailItem(); if (!it) return; dlg.close(); fn(it); };
1993
+ const openStudio = (it) => { setView("studio"); state.batch = [it]; if (state.mode !== "crea" && state.refs.length) setMode("crea"); showShot(it); };
1994
+ $("#d-open").addEventListener("click", fromDetail(openStudio));
1995
+ $("#d-open-draft").addEventListener("click", fromDetail(openStudio));
1996
+ $("#d-keep").addEventListener("click", fromDetail((it) => keepFiles([it.file])));
1997
+ $("#d-discard").addEventListener("click", fromDetail((it) => discardFiles([it.file])));
1998
+ $("#d-edit").addEventListener("click", fromDetail((it) => useAsRef(it, "modifica")));
1999
+ $("#d-restyle").addEventListener("click", fromDetail((it) => useAsRef(it, "ristila")));
2000
+ $("#d-variant").addEventListener("click", fromDetail((it) => submit(payloadFromItem(it, { seed: null }))));
2001
+ $("#d-upscale").addEventListener("click", fromDetail((it) => runTool(it, "ingrandisci")));
2002
+ $("#d-cutout").addEventListener("click", fromDetail((it) => runTool(it, "scontorna")));
2003
+ $("#d-poster").addEventListener("click", fromDetail(openInPoster));
2004
+ $("#d-vector").addEventListener("click", () => { const it = detailItem(); if (it) vectorizer.open("outputs/" + it.file, it.file); });
2005
+ $("#d-views").addEventListener("click", fromDetail(runViews));
2006
+ $("#d-refine").addEventListener("click", fromDetail(runRefine));
2007
+ $("#d-story").addEventListener("click", fromDetail((it) => useAsRef(it, "continua")));
2008
+ $("#d-style").addEventListener("click", fromDetail((it) => openStyleDialog(null, it)));
2009
+ $("#d-fav").addEventListener("click", () => { const it = detailItem(); if (it) setFavorite([it], !it.preferita); });
2010
+ $("#d-trash").addEventListener("click", fromDetail((it) => moveToTrash([it.file])));
2011
+ $("#d-restore").addEventListener("click", fromDetail((it) => restoreFiles([it.file])));
2012
+ $("#d-purge").addEventListener("click", fromDetail((it) => purgeFiles([it.file])));
2013
+
2014
+ mask.init();
2015
+ brush.wire();
2016
+ shotMenu.wire();
2017
+ bilingual.wire();
2018
+ $("#next-use").addEventListener("click", continueFromCurrent);
2019
+ $("#next-stay").addEventListener("click", () => {
2020
+ state.nextDismissed = state.current?.file || "";
2021
+ state.current = null;
2022
+ $("#stage").dataset.state = "";
2023
+ syncBase();
2024
+ updateNextBar();
2025
+ sessionRender();
2026
+ toast("Sei sull'originale: la nuova versione resta nella colonna Sessione a sinistra");
2027
+ });
2028
+ $("#session-clear").addEventListener("click", () => { state.session = []; sessionRender(); });
2029
+ document.addEventListener("keydown", (e) => {
2030
+ if (document.body.dataset.view !== "studio" || document.querySelector("dialog[open]:not(#guide)") || brush.active) return;
2031
+ if (e.target.closest("input, textarea, select")) return;
2032
+ if (e.key === "ArrowLeft" || e.key === "ArrowUp") { e.preventDefault(); sessionStep(-1); }
2033
+ if (e.key === "ArrowRight" || e.key === "ArrowDown") { e.preventDefault(); sessionStep(1); }
2034
+ });
2035
+ }
2036
+
2037
+ async function init() {
2038
+ if (window.PixBackend) await window.PixBackend.ready;
2039
+ wire();
2040
+ const s = await refreshStatus();
2041
+ if (s) {
2042
+ state.aspects = s.formati;
2043
+ state.tools = s.strumenti || {};
2044
+ if (!s.traduttore) $("#enhance-btn").hidden = true;
2045
+ state.models = s.modelli;
2046
+ state.auto = s.automatico;
2047
+ }
2048
+ state.templates = (await api("/api/templates")).template;
2049
+ renderTemplates();
2050
+ setMode("crea");
2051
+ refreshDraftCount();
2052
+ setInterval(refreshStatus, 10000);
2053
+ }
2054
+
2055
+ window.PixRick = { api, toast, el, icon, radio, prefs, mediaUrl, outputUrl, confirmDialog, setView, refreshDraftCount };
2056
+
2057
+ init();
web/backend.js ADDED
@@ -0,0 +1,596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* PixRick online: le stesse API dell'app sul computer, ma la galleria vive nel browser
2
+ e la generazione passa dal motore su Hugging Face. Niente immagini restano sul server. */
3
+ (() => {
4
+ "use strict";
5
+
6
+ const DB_NAME = "pixrick";
7
+ const DRAFT_TTL_MS = 24 * 3600 * 1000;
8
+ const THUMB_SIDE = 640;
9
+ const MAX_INPUT_SIDE = 2048;
10
+ const MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
11
+ const ENGINE_PATH = "/motore/";
12
+
13
+ /* ---------- archivio nel browser ---------- */
14
+
15
+ let dbPromise = null;
16
+ function db() {
17
+ dbPromise ||= new Promise((resolve, reject) => {
18
+ const req = indexedDB.open(DB_NAME, 1);
19
+ req.onupgradeneeded = () => {
20
+ const d = req.result;
21
+ d.createObjectStore("blobs");
22
+ const items = d.createObjectStore("items", { keyPath: "file" });
23
+ items.createIndex("scope", "scope");
24
+ d.createObjectStore("kv");
25
+ };
26
+ req.onsuccess = () => resolve(req.result);
27
+ req.onerror = () => reject(req.error);
28
+ });
29
+ return dbPromise;
30
+ }
31
+
32
+ async function tx(stores, mode, work) {
33
+ const d = await db();
34
+ return new Promise((resolve, reject) => {
35
+ const t = d.transaction(stores, mode);
36
+ let out;
37
+ t.oncomplete = () => resolve(out);
38
+ t.onerror = () => reject(t.error);
39
+ t.onabort = () => reject(t.error || new Error("Archivio del browser non disponibile."));
40
+ out = work(...[].concat(stores).map((s) => t.objectStore(s)));
41
+ });
42
+ }
43
+
44
+ const req2p = (r) => new Promise((resolve, reject) => { r.onsuccess = () => resolve(r.result); r.onerror = () => reject(r.error); });
45
+
46
+ async function readBlob(path) {
47
+ const d = await db();
48
+ return req2p(d.transaction("blobs").objectStore("blobs").get(path));
49
+ }
50
+ async function readItem(file) {
51
+ const d = await db();
52
+ return req2p(d.transaction("items").objectStore("items").get(file));
53
+ }
54
+ async function itemsIn(scope) {
55
+ const d = await db();
56
+ return req2p(d.transaction("items").objectStore("items").index("scope").getAll(scope));
57
+ }
58
+ async function kvGet(key, fallback) {
59
+ const d = await db();
60
+ const v = await req2p(d.transaction("kv").objectStore("kv").get(key));
61
+ return v === undefined ? fallback : v;
62
+ }
63
+ const kvSet = (key, value) => tx("kv", "readwrite", (s) => { s.put(value, key); });
64
+
65
+ /* ---------- immagini ---------- */
66
+
67
+ const pad = (n) => String(n).padStart(2, "0");
68
+ const today = (d = new Date()) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
69
+ const clock = (d = new Date()) => `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
70
+ const stamp = (d = new Date()) => `${today(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
71
+ const rand = () => Math.random().toString(16).slice(2, 8);
72
+
73
+ async function bitmap(blob) {
74
+ try {
75
+ return await createImageBitmap(blob, { imageOrientation: "from-image" });
76
+ } catch {
77
+ throw new Error("Il file non è un'immagine leggibile.");
78
+ }
79
+ }
80
+
81
+ function canvasOf(w, h) {
82
+ const c = document.createElement("canvas");
83
+ c.width = w;
84
+ c.height = h;
85
+ return c;
86
+ }
87
+
88
+ const toBlob = (canvas, type, quality) => new Promise((r) => canvas.toBlob(r, type, quality));
89
+
90
+ async function thumbnail(blob) {
91
+ const bmp = await bitmap(blob);
92
+ const k = Math.min(1, THUMB_SIDE / Math.max(bmp.width, bmp.height));
93
+ const c = canvasOf(Math.round(bmp.width * k), Math.round(bmp.height * k));
94
+ c.getContext("2d").drawImage(bmp, 0, 0, c.width, c.height);
95
+ bmp.close?.();
96
+ return (await toBlob(c, "image/webp", 0.84)) || toBlob(c, "image/png");
97
+ }
98
+
99
+ /** Ruota secondo l'EXIF, rimpicciolisce e riscrive in PNG: via EXIF e posizione GPS. */
100
+ async function cleanUpload(file) {
101
+ if (file.size > MAX_UPLOAD_BYTES) throw new Error("Immagine troppo pesante (massimo 25 MB).");
102
+ const bmp = await bitmap(file);
103
+ const k = Math.min(1, MAX_INPUT_SIDE / Math.max(bmp.width, bmp.height));
104
+ const c = canvasOf(Math.round(bmp.width * k), Math.round(bmp.height * k));
105
+ const ctx = c.getContext("2d");
106
+ ctx.fillStyle = "#fff";
107
+ ctx.fillRect(0, 0, c.width, c.height);
108
+ ctx.drawImage(bmp, 0, 0, c.width, c.height);
109
+ bmp.close?.();
110
+ return { blob: await toBlob(c, "image/png"), width: c.width, height: c.height };
111
+ }
112
+
113
+ /* ---------- galleria ---------- */
114
+
115
+ // Percorsi come sul computer: bozze in _bozze/, galleria per giorno, cestino in _cestino/.
116
+ const SCOPE_PREFIX = { bozze: "_bozze/", galleria: "", cestino: "_cestino/" };
117
+ const thumbPath = (scope, day, stem) => (scope === "galleria" ? `.miniature/${day}/${stem}.webp` : `${SCOPE_PREFIX[scope]}${day}/${stem}.webp`);
118
+
119
+ function splitFile(file) {
120
+ const parts = file.split("/");
121
+ const name = parts.pop();
122
+ return { day: parts.pop(), stem: name.replace(/\.png$/, "") };
123
+ }
124
+
125
+ async function storeItem(scope, meta, png, thumb) {
126
+ const day = today();
127
+ const stem = meta._stem || `${clock()}_${meta.modalita || "crea"}_${meta.modello || "img"}_${rand()}`;
128
+ delete meta._stem;
129
+ const file = `${SCOPE_PREFIX[scope]}${day}/${stem}.png`;
130
+ const mini = thumbPath(scope, day, stem);
131
+ const item = { ...meta, file, miniatura: mini, bozza: scope === "bozze", titolo: meta.titolo || "", preferita: !!meta.preferita };
132
+ await tx(["blobs", "items"], "readwrite", (blobs, items) => {
133
+ blobs.put(png, "outputs/" + file);
134
+ blobs.put(thumb, "outputs/" + mini);
135
+ items.put({ file, scope, t: Date.now(), meta: item });
136
+ });
137
+ return item;
138
+ }
139
+
140
+ async function move(file, fromScope, toScope) {
141
+ const rec = await readItem(file);
142
+ if (!rec || rec.scope !== fromScope) return null;
143
+ const { day, stem } = splitFile(file);
144
+ const newFile = `${SCOPE_PREFIX[toScope]}${day}/${stem}.png`;
145
+ const newMini = thumbPath(toScope, day, stem);
146
+ const png = await readBlob("outputs/" + file);
147
+ const thumb = await readBlob("outputs/" + rec.meta.miniatura);
148
+ const meta = { ...rec.meta, file: newFile, miniatura: newMini, bozza: toScope === "bozze" };
149
+ await tx(["blobs", "items"], "readwrite", (blobs, items) => {
150
+ blobs.delete("outputs/" + file);
151
+ blobs.delete("outputs/" + rec.meta.miniatura);
152
+ items.delete(file);
153
+ if (png) blobs.put(png, "outputs/" + newFile);
154
+ if (thumb) blobs.put(thumb, "outputs/" + newMini);
155
+ items.put({ file: newFile, scope: toScope, t: rec.t, meta });
156
+ });
157
+ return meta;
158
+ }
159
+
160
+ async function remove(file, scope) {
161
+ const rec = await readItem(file);
162
+ if (!rec || (scope && rec.scope !== scope)) return false;
163
+ await tx(["blobs", "items"], "readwrite", (blobs, items) => {
164
+ blobs.delete("outputs/" + file);
165
+ blobs.delete("outputs/" + rec.meta.miniatura);
166
+ items.delete(file);
167
+ });
168
+ return true;
169
+ }
170
+
171
+ async function history(params) {
172
+ const scope = params.get("vista") || "galleria";
173
+ const limit = Math.min(200, Number(params.get("limit") || 60));
174
+ const offset = Math.max(0, Number(params.get("offset") || 0));
175
+ const real = scope === "preferite" ? "galleria" : scope;
176
+ let list = (await itemsIn(real)).map((r) => r.meta);
177
+ if (scope === "preferite") list = list.filter((m) => m.preferita);
178
+ list.sort((a, b) => (a.file < b.file ? 1 : -1));
179
+ return { immagini: list.slice(offset, offset + limit) };
180
+ }
181
+
182
+ async function cleanOld() {
183
+ const limit = Date.now() - DRAFT_TTL_MS;
184
+ for (const rec of await itemsIn("bozze")) if (rec.t < limit) await remove(rec.file, "bozze");
185
+ const used = new Set();
186
+ for (const scope of ["galleria", "cestino", "bozze"]) {
187
+ for (const rec of await itemsIn(scope)) {
188
+ (rec.meta.riferimenti || []).forEach((r) => used.add(r));
189
+ if (rec.meta.maschera) used.add(rec.meta.maschera);
190
+ }
191
+ }
192
+ const inputs = (await kvGet("inputs", {})) || {};
193
+ let changed = false;
194
+ for (const [path, t] of Object.entries(inputs)) {
195
+ if (t < limit && !used.has(path)) {
196
+ await tx("blobs", "readwrite", (s) => s.delete(path));
197
+ delete inputs[path];
198
+ changed = true;
199
+ }
200
+ }
201
+ if (changed) await kvSet("inputs", inputs);
202
+ }
203
+
204
+ async function saveInput(blob, name) {
205
+ const path = `inputs/${today()}/${clock()}_${rand()}.png`;
206
+ await tx("blobs", "readwrite", (s) => { s.put(blob, path); });
207
+ const inputs = (await kvGet("inputs", {})) || {};
208
+ inputs[path] = Date.now();
209
+ await kvSet("inputs", inputs);
210
+ return path;
211
+ }
212
+
213
+ /* ---------- stili dell'utente ---------- */
214
+
215
+ 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;
216
+ const looksItalian = (t) => ITALIAN.test(t.replace(/"[^"]*"/g, ""));
217
+
218
+ const userStyles = () => kvGet("stili", []);
219
+
220
+ async function saveStyle(data) {
221
+ const name = String(data.nome || "").trim().slice(0, 40);
222
+ const text = String(data.testo || "").trim().slice(0, 600);
223
+ if (!name || !text) throw new Error("Servono un nome e una descrizione dello stile.");
224
+ let english = text;
225
+ if (looksItalian(text)) english = (await write("traduci", text)) || text;
226
+ const items = await userStyles();
227
+ let id = String(data.id || "");
228
+ if (!id.startsWith("u-") || !items.some((i) => i.id === id)) {
229
+ const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 24) || "stile";
230
+ id = `u-${slug}-${rand().slice(0, 4)}`;
231
+ }
232
+ const color = /^#[0-9a-f]{6}$/i.test(data.colore || "") ? data.colore : "#cbbcff";
233
+ const style = {
234
+ id,
235
+ nome: name,
236
+ descrizione: text.length < 90 ? text : text.slice(0, 87) + "…",
237
+ testo: text,
238
+ formato: data.formato || "1:1",
239
+ colore: color,
240
+ modello: ["z-image", "klein", "entrambi"].includes(data.modello) ? data.modello : "",
241
+ qualita: ["rapida", "bilanciata", "massima"].includes(data.qualita) ? data.qualita : "",
242
+ prompt: "{prompt}. " + english.trim().replace(/\.$/, "") + ".",
243
+ };
244
+ const next = items.some((i) => i.id === id) ? items.map((i) => (i.id === id ? style : i)) : [...items, style];
245
+ await kvSet("stili", next);
246
+ return { ...style, categoria: "I tuoi stili", utente: true, campi: [] };
247
+ }
248
+
249
+ async function templates() {
250
+ const res = await fetch("/api/templates");
251
+ const data = await res.json();
252
+ const mine = (await userStyles()).map((s) => ({ ...s, categoria: "I tuoi stili", utente: true, campi: [] }));
253
+ return { template: [...data.template, ...mine] };
254
+ }
255
+
256
+ /* ---------- motore ---------- */
257
+
258
+ let clientPromise = null;
259
+ function engine() {
260
+ clientPromise ||= import("/web/vendor/gradio-client.js")
261
+ .then(({ Client }) => Client.connect(location.origin + ENGINE_PATH, { events: ["data", "status"] }))
262
+ .catch((e) => {
263
+ clientPromise = null;
264
+ throw e;
265
+ });
266
+ return clientPromise;
267
+ }
268
+
269
+ const QUOTA = /quota|GPU (?:time|duration)/i;
270
+ function engineError(raw) {
271
+ const text = String(raw?.message || raw || "");
272
+ const wait = text.match(/Try again in (\d+):(\d+):(\d+)/i);
273
+ if (QUOTA.test(text)) {
274
+ const err = new Error(wait ? "quota" : "quota");
275
+ err.code = "quota";
276
+ if (wait) err.retryIn = Number(wait[1]) * 3600 + Number(wait[2]) * 60 + Number(wait[3]);
277
+ return err;
278
+ }
279
+ if (/queue is full|too many/i.test(text)) {
280
+ const err = new Error("Ci sono troppe persone in coda in questo momento. Riprova tra un minuto.");
281
+ err.code = "full";
282
+ return err;
283
+ }
284
+ return new Error(text.replace(/^Error:\s*/, "") || "Il motore non risponde. Riprova tra poco.");
285
+ }
286
+
287
+ async function write(kind, text) {
288
+ const client = await engine();
289
+ try {
290
+ const res = await client.predict("/scrivi", [kind, text]);
291
+ return res.data[0];
292
+ } catch (e) {
293
+ throw engineError(e);
294
+ }
295
+ }
296
+
297
+ async function improve(text, mode) {
298
+ const client = await engine();
299
+ try {
300
+ const res = await client.predict("/migliora", [text, mode]);
301
+ return res.data[0];
302
+ } catch (e) {
303
+ throw engineError(e);
304
+ }
305
+ }
306
+
307
+ const jobs = new Map();
308
+ const listeners = new Set();
309
+ const emit = (event) => listeners.forEach((fn) => { try { fn(event); } catch { /* ascoltatore rotto */ } });
310
+
311
+ function placeholderJob(id, payload) {
312
+ return {
313
+ id,
314
+ status: "invio",
315
+ progress: 0,
316
+ current: 0,
317
+ current_model: "",
318
+ total: Math.max(1, Number(payload.quantita) || 1),
319
+ current_steps: 1,
320
+ model_name: "",
321
+ confronto: false,
322
+ elapsed: 0,
323
+ width: 1024,
324
+ height: 1024,
325
+ results: [],
326
+ request: { mode: payload.modalita || "crea", count: Number(payload.quantita) || 1, mask: payload.maschera || null },
327
+ created: Date.now() / 1000,
328
+ };
329
+ }
330
+
331
+ async function startJob(payload) {
332
+ const files = [];
333
+ for (const ref of payload.riferimenti || []) {
334
+ const blob = await readBlob(ref);
335
+ if (!blob) throw new Error("Un'immagine di partenza non c'è più. Ricaricala.");
336
+ files.push(new File([blob], "ref.png", { type: blob.type || "image/png" }));
337
+ }
338
+ let mask = null;
339
+ if (payload.maschera) {
340
+ const blob = await readBlob(payload.maschera);
341
+ if (blob) mask = new File([blob], "mask.png", { type: "image/png" });
342
+ }
343
+ const request = { ...payload, stili_utente: await userStyles() };
344
+ const client = await engine();
345
+ const { handle_file: handle } = await import("/web/vendor/gradio-client.js");
346
+ const id = "j" + Date.now().toString(36) + rand();
347
+ const started = Date.now();
348
+ const state = { job: placeholderJob(id, payload), payload };
349
+ jobs.set(id, state);
350
+
351
+ const run = client.submit("/genera", [JSON.stringify(request), files.map((f) => handle(f)), mask ? handle(mask) : null]);
352
+ (async () => {
353
+ try {
354
+ for await (const msg of run) {
355
+ if (msg.type === "status") {
356
+ if (msg.stage === "error") throw engineError(msg.message);
357
+ if (msg.stage === "pending" && msg.position != null && state.job.status !== "generazione") {
358
+ state.job = { ...state.job, status: "in_coda", position: msg.position, eta: msg.eta ?? null, queue_size: msg.queue_size ?? null };
359
+ }
360
+ }
361
+ if (msg.type === "data") {
362
+ const [pub, out] = msg.data;
363
+ if (!pub) continue;
364
+ const live = { ...pub, elapsed: Math.round((Date.now() - started) / 100) / 10 };
365
+ if (pub.status === "fatto" && out && out.length) {
366
+ state.job = { ...live, status: "salvataggio" };
367
+ const results = [];
368
+ for (let i = 0; i < out.length; i++) {
369
+ const res = await fetch(out[i].url);
370
+ const png = await res.blob();
371
+ const meta = { ...pub.results[i], riferimenti: payload.riferimenti || [], maschera: payload.maschera || null };
372
+ results.push(await storeItem("bozze", meta, png, await thumbnail(png)));
373
+ }
374
+ state.job = { ...live, status: "fatto", results, progress: 1 };
375
+ emit({ type: "generata", count: results.length });
376
+ return;
377
+ }
378
+ state.job = { ...live, status: pub.status === "fatto" ? "salvataggio" : pub.status };
379
+ }
380
+ }
381
+ } catch (e) {
382
+ const err = e instanceof Error && e.code ? e : engineError(e);
383
+ state.job = { ...state.job, status: "errore", error: err.message, error_code: err.code || null, retry_in: err.retryIn || null };
384
+ emit({ type: "errore", code: err.code || null, retryIn: err.retryIn || null });
385
+ }
386
+ })();
387
+ return state.job;
388
+ }
389
+
390
+ /* ---------- account ---------- */
391
+
392
+ async function whoAmI() {
393
+ try {
394
+ const client = await engine();
395
+ const res = await client.predict("/chi_sono", []);
396
+ return res.data[0] || { accesso: false };
397
+ } catch {
398
+ return { accesso: false };
399
+ }
400
+ }
401
+
402
+ /* ---------- router delle API ---------- */
403
+
404
+ const MODELS = {
405
+ "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 } },
406
+ 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 } },
407
+ };
408
+ 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] };
409
+
410
+ function status() {
411
+ const busy = [...jobs.values()].filter((s) => !["fatto", "errore"].includes(s.job.status)).length;
412
+ return {
413
+ modello: "pronto",
414
+ modello_caricato: null,
415
+ modelli_installati: { "z-image": true, klein: true },
416
+ lavori_attivi: busy,
417
+ traduttore: true,
418
+ strumenti: { ingrandisci: true, scontorna: true, vettorizza: true },
419
+ motore_finto: false,
420
+ online: true,
421
+ formati: ASPECTS,
422
+ modelli: MODELS,
423
+ automatico: { crea: "z-image", ristila: "z-image", modifica: "klein", continua: "klein", rifinisci: "z-image" },
424
+ max_riferimenti: 4,
425
+ };
426
+ }
427
+
428
+ async function posterSave(blob, info) {
429
+ const bmp = await bitmap(blob);
430
+ const meta = {
431
+ _stem: `${clock()}_locandina_${rand()}`,
432
+ modalita: "locandina",
433
+ prompt: String(info.titolo || "").slice(0, 120),
434
+ prompt_finale: "",
435
+ template: "libero",
436
+ stili: [],
437
+ campi: {},
438
+ riferimenti: info.sfondo ? [String(info.sfondo)] : [],
439
+ formato: String(info.formato || ""),
440
+ larghezza: bmp.width,
441
+ altezza: bmp.height,
442
+ qualita: "",
443
+ passi: 0,
444
+ seed: 0,
445
+ modello: "compositore",
446
+ modello_nome: "Compositore",
447
+ trasparente: false,
448
+ creata: stamp(),
449
+ titolo: String(info.titolo || "").slice(0, 120),
450
+ preferita: false,
451
+ };
452
+ bmp.close?.();
453
+ return storeItem("galleria", meta, blob, await thumbnail(blob));
454
+ }
455
+
456
+ async function vectorize(body) {
457
+ const blob = await readBlob(body.file);
458
+ if (!blob) throw new Error("Immagine non trovata.");
459
+ const form = new FormData();
460
+ form.append("file", blob, "immagine.png");
461
+ form.append("stile", body.stile || "colori");
462
+ form.append("trasparente", String(body.trasparente !== false));
463
+ const res = await fetch("/api/vectorize", { method: "POST", body: form });
464
+ const data = await res.json().catch(() => ({}));
465
+ if (!res.ok) throw new Error(data.detail || "Vettorizzazione non riuscita.");
466
+ return data;
467
+ }
468
+
469
+ async function extractStyle(body) {
470
+ const res = await fetch("/api/styles/extract", {
471
+ method: "POST",
472
+ headers: { "Content-Type": "application/json" },
473
+ body: JSON.stringify({ ...body, stili_utente: await userStyles() }),
474
+ });
475
+ const data = await res.json().catch(() => ({}));
476
+ if (!res.ok) throw new Error(data.detail || "Non riuscito.");
477
+ return data;
478
+ }
479
+
480
+ const filesOf = (body) => (body.files || (body.file ? [body.file] : [])).map(String);
481
+
482
+ async function api(path, body, headers = {}) {
483
+ const url = new URL(path, location.origin);
484
+ const p = url.pathname;
485
+ if (body === undefined) {
486
+ if (p === "/api/status") return status();
487
+ if (p === "/api/templates") return templates();
488
+ if (p === "/api/history") return history(url.searchParams);
489
+ if (p.startsWith("/api/jobs/")) {
490
+ const s = jobs.get(p.split("/").pop());
491
+ if (!s) throw new Error("Lavoro non trovato.");
492
+ return s.job;
493
+ }
494
+ throw new Error("Pagina non trovata.");
495
+ }
496
+ switch (p) {
497
+ case "/api/upload": {
498
+ const { blob, width, height } = await cleanUpload(body);
499
+ const name = decodeURIComponent(headers["X-Filename"] || "").slice(0, 80);
500
+ return { file: await saveInput(blob, name), larghezza: width, altezza: height, nome: name };
501
+ }
502
+ case "/api/poster": {
503
+ const info = JSON.parse(decodeURIComponent(headers["X-Meta"] || "") || "{}");
504
+ return posterSave(body, info);
505
+ }
506
+ case "/api/generate":
507
+ return startJob(body);
508
+ case "/api/enhance":
509
+ if (!String(body.prompt || "").trim()) throw new Error("Scrivi prima un'idea da migliorare.");
510
+ return improve(String(body.prompt), body.modalita || "crea");
511
+ case "/api/translate":
512
+ return { testo: String(body.testo || "").trim() ? await write(body.verso === "it" ? "in_italiano" : "traduci", String(body.testo)) : "" };
513
+ case "/api/vectorize":
514
+ return vectorize(body);
515
+ case "/api/keep": {
516
+ const kept = [];
517
+ for (const f of filesOf(body)) { const m = await move(f, "bozze", "galleria"); if (m) kept.push(m); }
518
+ return { salvate: kept };
519
+ }
520
+ case "/api/discard": {
521
+ let n = 0;
522
+ const list = body.tutto ? (await itemsIn("bozze")).map((r) => r.file) : filesOf(body);
523
+ for (const f of list) if (await remove(f, "bozze")) n++;
524
+ return { scartate: n };
525
+ }
526
+ case "/api/trash": {
527
+ let n = 0;
528
+ for (const f of filesOf(body)) if (await move(f, "galleria", "cestino")) n++;
529
+ return { spostate: n };
530
+ }
531
+ case "/api/restore": {
532
+ let n = 0;
533
+ for (const f of filesOf(body)) if (await move(f, "cestino", "galleria")) n++;
534
+ return { ripristinate: n };
535
+ }
536
+ case "/api/purge": {
537
+ let n = 0;
538
+ const list = body.tutto ? (await itemsIn("cestino")).map((r) => r.file) : filesOf(body);
539
+ for (const f of list) if (await remove(f, "cestino")) n++;
540
+ return { eliminate: n };
541
+ }
542
+ case "/api/update": {
543
+ const rec = await readItem(String(body.file || ""));
544
+ if (!rec || rec.scope !== "galleria") throw new Error("Immagine non trovata.");
545
+ const changes = body.modifiche || {};
546
+ if ("titolo" in changes) rec.meta.titolo = String(changes.titolo || "").trim().slice(0, 120);
547
+ if ("preferita" in changes) rec.meta.preferita = !!changes.preferita;
548
+ await tx("items", "readwrite", (s) => { s.put(rec); });
549
+ return rec.meta;
550
+ }
551
+ case "/api/styles/save":
552
+ return saveStyle(body);
553
+ case "/api/styles/extract":
554
+ return extractStyle(body);
555
+ case "/api/styles/delete": {
556
+ const items = await userStyles();
557
+ const next = items.filter((i) => i.id !== String(body.id || ""));
558
+ if (next.length === items.length) throw new Error("Stile non trovato.");
559
+ await kvSet("stili", next);
560
+ return { ok: true };
561
+ }
562
+ case "/api/unload":
563
+ case "/api/shutdown":
564
+ return { ok: true };
565
+ default:
566
+ throw new Error("Azione non trovata.");
567
+ }
568
+ }
569
+
570
+ async function serviceWorker() {
571
+ if (!("serviceWorker" in navigator)) return false;
572
+ try {
573
+ await navigator.serviceWorker.register("/sw.js", { scope: "/" });
574
+ await navigator.serviceWorker.ready;
575
+ if (!navigator.serviceWorker.controller) {
576
+ await new Promise((resolve) => {
577
+ navigator.serviceWorker.addEventListener("controllerchange", resolve, { once: true });
578
+ setTimeout(resolve, 1500);
579
+ });
580
+ }
581
+ return !!navigator.serviceWorker.controller;
582
+ } catch {
583
+ return false;
584
+ }
585
+ }
586
+
587
+ const ready = (async () => {
588
+ await db();
589
+ const sw = await serviceWorker();
590
+ cleanOld().catch(() => {});
591
+ if (navigator.storage?.persist) navigator.storage.persist().catch(() => {});
592
+ return { serviceWorker: sw };
593
+ })();
594
+
595
+ window.PixBackend = { api, ready, whoAmI, engine, on: (fn) => listeners.add(fn), readBlob };
596
+ })();
web/fonts/LICENSE-OFL.txt ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2016 The Oswald Project Authors (https://github.com/googlefonts/OswaldFont)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
web/fonts/anton-latin-400-normal.woff2 ADDED
Binary file (18.6 kB). View file
 
web/fonts/archivo-black-latin-400-normal.woff2 ADDED
Binary file (18.6 kB). View file
 
web/fonts/bebas-neue-latin-400-normal.woff2 ADDED
Binary file (13.8 kB). View file
 
web/fonts/inter-latin-400-normal.woff2 ADDED
Binary file (23.7 kB). View file
 
web/fonts/inter-latin-600-normal.woff2 ADDED
Binary file (24.5 kB). View file
 
web/fonts/inter-latin-800-normal.woff2 ADDED
Binary file (24.4 kB). View file
 
web/fonts/newsreader-latin-400-italic.woff2 ADDED
Binary file (24.3 kB). View file
 
web/fonts/newsreader-latin-400-normal.woff2 ADDED
Binary file (22.5 kB). View file
 
web/fonts/newsreader-latin-500-italic.woff2 ADDED
Binary file (25.6 kB). View file
 
web/fonts/newsreader-latin-500-normal.woff2 ADDED
Binary file (23.6 kB). View file
 
web/fonts/oswald-latin-500-normal.woff2 ADDED
Binary file (12.7 kB). View file
 
web/fonts/oswald-latin-700-normal.woff2 ADDED
Binary file (12.7 kB). View file
 
web/fonts/permanent-marker-latin-400-normal.woff2 ADDED
Binary file (29.6 kB). View file
 
web/fonts/playfair-display-latin-700-normal.woff2 ADDED
Binary file (23.2 kB). View file
 
web/fonts/playfair-display-latin-900-normal.woff2 ADDED
Binary file (22.4 kB). View file
 
web/guida/PixRick-Guida.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25199c412d5bf1c29a630d23836351feddeab5a3a609bd34645eb7fa08752b7e
3
+ size 5934679
web/guida/guida.css ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @font-face { font-family: "Newsreader"; src: url("/web/fonts/newsreader-latin-400-normal.woff2") format("woff2"); font-weight: 400; font-style: normal; }
2
+ @font-face { font-family: "Newsreader"; src: url("/web/fonts/newsreader-latin-500-normal.woff2") format("woff2"); font-weight: 500; font-style: normal; }
3
+ @font-face { font-family: "Newsreader"; src: url("/web/fonts/newsreader-latin-400-italic.woff2") format("woff2"); font-weight: 400; font-style: italic; }
4
+ @font-face { font-family: "Inter"; src: url("/web/fonts/inter-latin-400-normal.woff2") format("woff2"); font-weight: 400; }
5
+ @font-face { font-family: "Inter"; src: url("/web/fonts/inter-latin-600-normal.woff2") format("woff2"); font-weight: 600; }
6
+
7
+ :root {
8
+ --paper: #f7f7f9;
9
+ --sheet: #ffffff;
10
+ --ink: #1b1c22;
11
+ --ink-2: #4a4c57;
12
+ --ink-3: #7b7e8a;
13
+ --rule: #e3e3ea;
14
+ --violet: #5b45c2;
15
+ --violet-soft: #efecfb;
16
+ --amber: #8a5a00;
17
+ --amber-soft: #fff4dc;
18
+ --mint-soft: #e6f6f1;
19
+ --mint: #1d6b55;
20
+ --pearl: linear-gradient(115deg, #c9b8ff 0%, #ffc9a8 55%, #9fe3da 100%);
21
+ --serif: "Newsreader", ui-serif, Georgia, serif;
22
+ --sans: "Inter", -apple-system, system-ui, sans-serif;
23
+ --measure: 68ch;
24
+ }
25
+
26
+ * { box-sizing: border-box; }
27
+ html { scroll-behavior: smooth; scroll-padding-top: 24px; }
28
+ body {
29
+ margin: 0;
30
+ background: var(--paper);
31
+ color: var(--ink);
32
+ font: 400 16px/1.65 var(--sans);
33
+ -webkit-font-smoothing: antialiased;
34
+ font-feature-settings: "cv11", "ss01";
35
+ }
36
+ img { display: block; max-width: 100%; height: auto; }
37
+ a { color: var(--violet); text-decoration-thickness: 1px; text-underline-offset: 3px; }
38
+ kbd {
39
+ display: inline-block;
40
+ min-width: 1.7em;
41
+ padding: 0 0.4em;
42
+ border: 1px solid var(--rule);
43
+ border-bottom-width: 2px;
44
+ border-radius: 5px;
45
+ background: var(--sheet);
46
+ font: 600 0.82em/1.6 var(--sans);
47
+ text-align: center;
48
+ color: var(--ink-2);
49
+ }
50
+ code { font: 0.9em/1 ui-monospace, "SF Mono", Menlo, monospace; padding: 0.1em 0.35em; border-radius: 4px; background: #eeeef3; }
51
+ b, strong { font-weight: 600; }
52
+
53
+ /* ---------- impaginazione ---------- */
54
+
55
+ .layout { display: grid; grid-template-columns: 260px minmax(0, 1fr); max-width: 1180px; margin: 0 auto; }
56
+ .toc {
57
+ position: sticky;
58
+ top: 0;
59
+ align-self: start;
60
+ height: 100vh;
61
+ overflow-y: auto;
62
+ padding: 36px 20px 40px 28px;
63
+ border-right: 1px solid var(--rule);
64
+ font-size: 13.5px;
65
+ }
66
+ .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; }
67
+ .toc-brand img { display: inline-block; width: 26px; height: 26px; }
68
+ .toc ol { margin: 0; padding: 0; list-style: none; counter-reset: cap; }
69
+ .toc > nav > ol > li { counter-increment: cap; margin: 0 0 2px; }
70
+ .toc a { display: block; padding: 5px 8px; border-radius: 7px; color: var(--ink-2); text-decoration: none; }
71
+ .toc > nav > ol > li > a::before { content: counter(cap) ". "; color: var(--ink-3); font-variant-numeric: tabular-nums; }
72
+ .toc a:hover { background: #ececf2; color: var(--ink); }
73
+ .toc a.attivo { background: var(--violet-soft); color: var(--violet); }
74
+ .toc ol ol { margin: 2px 0 8px 18px; font-size: 12.5px; }
75
+ .toc ol ol a { padding: 3px 8px; }
76
+ .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; }
77
+
78
+ main { padding: 0 56px 120px; min-width: 0; }
79
+ .doc { max-width: var(--measure); }
80
+
81
+ /* ---------- copertina ---------- */
82
+
83
+ .cover { position: relative; padding: 72px 0 56px; }
84
+ .cover-mark { width: 54px; height: 54px; margin-bottom: 30px; }
85
+ .cover h1 { margin: 0; font: 400 clamp(46px, 7vw, 76px)/0.98 var(--serif); letter-spacing: -0.02em; }
86
+ .cover .sub { max-width: 34ch; margin: 18px 0 0; font: 400 22px/1.4 var(--serif); color: var(--ink-2); }
87
+ .cover-strip { display: grid; grid-template-columns: 1.5fr 1fr 0.75fr 1fr; gap: 6px; margin: 44px 0 18px; }
88
+ .cover-strip img { width: 100%; height: 190px; object-fit: cover; border-radius: 6px; }
89
+ .cover-strip figcaption { grid-column: 1 / -1; font-size: 12.5px; color: var(--ink-3); }
90
+ .pearl-rule { height: 3px; width: 120px; margin: 28px 0 0; border: 0; border-radius: 3px; background: var(--pearl); }
91
+ .cover-meta { margin: 14px 0 0; font-size: 13px; color: var(--ink-3); }
92
+
93
+ /* ---------- capitoli ---------- */
94
+
95
+ .chapter { padding-top: 56px; }
96
+ .chapter + .chapter { border-top: 1px solid var(--rule); margin-top: 56px; }
97
+ .chapter-num { margin: 0 0 6px; font: 400 15px/1 var(--serif); font-style: italic; color: var(--violet); }
98
+ h2 { margin: 0 0 14px; font: 400 38px/1.1 var(--serif); letter-spacing: -0.01em; }
99
+ h3 { margin: 40px 0 10px; font: 500 23px/1.25 var(--serif); }
100
+ h4 { margin: 26px 0 6px; font: 600 15px/1.4 var(--sans); }
101
+ p { margin: 0 0 14px; }
102
+ .lead { font: 400 19px/1.55 var(--serif); color: var(--ink-2); }
103
+ ul, ol { margin: 0 0 16px; padding-left: 1.3em; }
104
+ li { margin: 0 0 6px; }
105
+ li::marker { color: var(--ink-3); }
106
+
107
+ .steps { list-style: none; padding: 0; counter-reset: passo; }
108
+ .steps > li { position: relative; padding-left: 40px; margin-bottom: 14px; counter-increment: passo; }
109
+ .steps > li::before {
110
+ content: counter(passo);
111
+ position: absolute;
112
+ left: 0;
113
+ top: 1px;
114
+ width: 26px;
115
+ height: 26px;
116
+ border-radius: 50%;
117
+ background: var(--ink);
118
+ color: #fff;
119
+ font: 600 13px/26px var(--sans);
120
+ text-align: center;
121
+ }
122
+
123
+ /* ---------- figure ---------- */
124
+
125
+ figure { margin: 26px 0 28px; }
126
+ .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); }
127
+ .wide { width: min(100%, 900px); max-width: none; }
128
+ figcaption { margin-top: 10px; font-size: 13.5px; line-height: 1.5; color: var(--ink-3); }
129
+ .pair { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
130
+ .pair img, .trio img { width: 100%; border-radius: 8px; }
131
+ .trio { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
132
+ .label-img { position: relative; }
133
+ .label-img span {
134
+ position: absolute;
135
+ left: 8px;
136
+ bottom: 8px;
137
+ padding: 3px 8px;
138
+ border-radius: 6px;
139
+ background: rgba(20, 20, 26, 0.75);
140
+ color: #fff;
141
+ font-size: 12px;
142
+ font-weight: 600;
143
+ }
144
+ .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; }
145
+
146
+ /* mappa numerata sopra uno screenshot */
147
+ .map { position: relative; }
148
+ .pin {
149
+ position: absolute;
150
+ width: 26px;
151
+ height: 26px;
152
+ margin: -13px 0 0 -13px;
153
+ border: 2px solid #fff;
154
+ border-radius: 50%;
155
+ background: var(--violet);
156
+ color: #fff;
157
+ font: 600 12.5px/22px var(--sans);
158
+ text-align: center;
159
+ box-shadow: 0 4px 10px rgba(0, 0, 0, 0.35);
160
+ }
161
+ .legend { list-style: none; padding: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 6px 22px; font-size: 14.5px; }
162
+ .legend li { display: flex; gap: 10px; align-items: baseline; margin: 0; }
163
+ .legend b.n {
164
+ flex: none;
165
+ width: 22px;
166
+ height: 22px;
167
+ border-radius: 50%;
168
+ background: var(--violet);
169
+ color: #fff;
170
+ font: 600 12px/22px var(--sans);
171
+ text-align: center;
172
+ }
173
+
174
+ /* ---------- box ---------- */
175
+
176
+ .note, .tip-box, .warn {
177
+ margin: 20px 0;
178
+ padding: 14px 18px;
179
+ border-radius: 10px;
180
+ font-size: 15px;
181
+ line-height: 1.6;
182
+ }
183
+ .note { background: var(--violet-soft); }
184
+ .tip-box { background: var(--mint-soft); }
185
+ .warn { background: var(--amber-soft); }
186
+ .note > b:first-child, .tip-box > b:first-child, .warn > b:first-child { display: block; margin-bottom: 2px; }
187
+ .tip-box > b:first-child { color: var(--mint); }
188
+ .warn > b:first-child { color: var(--amber); }
189
+ .note > b:first-child { color: var(--violet); }
190
+ .note p:last-child, .tip-box p:last-child, .warn p:last-child { margin: 0; }
191
+
192
+ /* ---------- tabelle ---------- */
193
+
194
+ table { width: 100%; margin: 18px 0 24px; border-collapse: collapse; font-size: 14.5px; }
195
+ th, td { padding: 10px 12px 10px 0; border-bottom: 1px solid var(--rule); text-align: left; vertical-align: top; }
196
+ th { font-weight: 600; color: var(--ink-2); font-size: 13px; }
197
+ td:first-child { white-space: nowrap; font-weight: 600; }
198
+
199
+ /* ---------- chat con Claude ---------- */
200
+
201
+ .chat { margin: 24px 0 30px; padding: 22px; border-radius: 14px; background: #1c1d22; color: #ececef; font-size: 14.5px; }
202
+ .chat .u, .chat .c { max-width: 92%; margin: 0 0 12px; padding: 10px 14px; border-radius: 12px; line-height: 1.55; }
203
+ .chat .u { margin-left: auto; background: #34313f; }
204
+ .chat .c { background: transparent; padding-left: 0; color: #d9d9df; }
205
+ .chat code { background: #2c2d35; color: #e6e6ea; }
206
+ .chat .tool {
207
+ display: inline-flex;
208
+ align-items: center;
209
+ gap: 8px;
210
+ margin: 0 0 10px;
211
+ padding: 5px 10px;
212
+ border: 1px solid #3a3b44;
213
+ border-radius: 8px;
214
+ color: #a9abb6;
215
+ font: 12.5px/1.4 ui-monospace, "SF Mono", Menlo, monospace;
216
+ }
217
+ .chat .tool::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: #7fd8a6; }
218
+ .chat img { width: 220px; margin: 2px 0 12px; border-radius: 8px; }
219
+ .chat .row { display: flex; gap: 8px; flex-wrap: wrap; }
220
+ .chat .row img { width: 150px; }
221
+
222
+ .prompts { list-style: none; padding: 0; display: grid; gap: 8px; }
223
+ .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); }
224
+
225
+ .cols { display: grid; grid-template-columns: 1fr 1fr; gap: 0 28px; }
226
+
227
+ /* evidenziazione dopo un salto dall'infobox */
228
+ .flash { animation: flash 1.6s ease-out; border-radius: 8px; }
229
+ @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; } }
230
+
231
+ /* ---------- dentro la dashboard ---------- */
232
+
233
+ body.incorporata .layout { display: block; }
234
+ body.incorporata .toc { display: none; }
235
+ body.incorporata main { padding: 0 26px 80px; }
236
+ body.incorporata .cover { padding-top: 34px; }
237
+ body.incorporata .cover h1 { font-size: 44px; }
238
+ body.incorporata .cover-strip img { height: 110px; }
239
+ body.incorporata h2 { font-size: 31px; }
240
+ body.incorporata .legend, body.incorporata .cols { grid-template-columns: 1fr; }
241
+
242
+ @media (max-width: 900px) {
243
+ .layout { display: block; }
244
+ .toc { display: none; }
245
+ main { padding: 0 22px 80px; }
246
+ }
247
+
248
+ @media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } .flash { animation: none; } }
249
+
250
+ /* ---------- stampa (PDF) ---------- */
251
+
252
+ @page { size: A4; margin: 18mm 17mm 20mm; }
253
+ @media print {
254
+ html { scroll-behavior: auto; }
255
+ body { background: #fff; font-size: 10.6pt; line-height: 1.55; }
256
+ .layout { display: block; max-width: none; }
257
+ .toc { display: none; }
258
+ main { padding: 0; }
259
+ .doc { max-width: none; }
260
+ .cover { min-height: 255mm; padding: 26mm 4mm 0; break-after: page; }
261
+ .cover h1 { font-size: 84pt; }
262
+ .cover .sub { font-size: 18pt; }
263
+ .cover-strip { margin-top: 22mm; }
264
+ .cover-strip img { height: 78mm; }
265
+ .print-toc { display: block; break-after: page; }
266
+ .chapter { padding-top: 10mm; margin-top: 10mm; }
267
+ .chapter + .chapter { margin-top: 8mm; border-top: 0.6pt solid var(--rule); }
268
+ .print-toc + .chapter { border-top: 0; margin-top: 0; padding-top: 0; }
269
+ #claude-mcp { break-before: page; border-top: 0; }
270
+ .chapter-num, h2, h3, .lead { break-after: avoid; }
271
+ p, li { orphans: 3; widows: 3; }
272
+ h2 { font-size: 28pt; }
273
+ h3 { font-size: 15pt; break-after: avoid; }
274
+ h4 { break-after: avoid; }
275
+ figure, table, .chat, .note, .tip-box, .warn, .legend { break-inside: avoid; }
276
+ .chat { background: #1c1d22 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
277
+ .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; }
278
+ .shot { box-shadow: none; }
279
+ figure img { max-height: 105mm; width: auto; margin: 0 auto; }
280
+ figure img.shot { max-height: 84mm; }
281
+ figcaption { font-size: 9pt; }
282
+ .pair img, .trio img { max-height: 70mm; object-fit: contain; }
283
+ .wide { width: 100%; }
284
+ .map img { max-height: none; width: 100%; }
285
+ .chat img { max-height: 45mm; width: auto; }
286
+ .cover-strip img { max-height: none; width: 100%; }
287
+ a { color: inherit; text-decoration: none; }
288
+ .no-print { display: none !important; }
289
+ }
290
+ @media screen { .print-toc { display: none; } }
291
+ .print-toc h2 { margin-top: 0; }
292
+ .print-toc ol { list-style: none; margin: 3mm 0 0; padding: 0; counter-reset: voce; }
293
+ .print-toc li { display: flex; align-items: baseline; gap: 8px; margin: 0; break-inside: avoid; }
294
+ .print-toc li::after { content: ""; order: 1; flex: 1; border-bottom: 0.6pt dotted #b9bbc6; transform: translateY(-3px); }
295
+ .print-toc li span { order: 2; min-width: 2em; text-align: right; font-variant-numeric: tabular-nums; color: var(--ink-2); }
296
+ .print-toc li.cap { counter-increment: voce; margin-top: 1.6mm; font-weight: 600; font-size: 10.4pt; }
297
+ .print-toc li.cap a::before { content: counter(voce) ". "; color: var(--violet); }
298
+ .print-toc li.sub { padding-left: 7mm; font-size: 9pt; color: var(--ink-2); line-height: 1.38; }
299
+ .print-toc a { color: inherit; text-decoration: none; }
300
+ .print-toc .note { margin-top: 5mm; font-size: 9.4pt; padding: 10px 14px; }
301
+ .pmark { position: absolute; top: 0; right: 0; font-size: 2px; line-height: 1; color: #fff; }
302
+ @media print { .nuova-pagina { break-before: page; } }
303
+
304
+ /* posizioni dei numeri sulla mappa dello Studio */
305
+ .p-viste { left: 39.4%; top: 3%; }
306
+ .p-stato { left: 72.3%; top: 3%; }
307
+ .p-azioni { left: 37.4%; top: 73.6%; }
308
+ .p-modi { left: 2.2%; top: 80.4%; }
309
+ .p-prompt { left: 59.5%; top: 87.8%; }
310
+ .p-pillole { left: 41.8%; top: 95%; }
311
+ .p-genera { left: 58%; top: 95%; }
312
+ .p-stili { left: 89.6%; top: 9.4%; }
313
+ .p-sessione { left: 7.2%; top: 14%; }
314
+
315
+ .gallery-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin: 18px 0 26px; }
316
+ .gallery-grid figure { margin: 0; }
317
+ .gallery-grid img { width: 100%; aspect-ratio: 3 / 2; object-fit: cover; border-radius: 6px; }
318
+ .gallery-grid.four img { aspect-ratio: 1; }
319
+ .gallery-grid .label-img span { left: 6px; bottom: 6px; font-size: 11px; padding: 2px 7px; }
320
+ body.incorporata .gallery-grid { grid-template-columns: repeat(2, 1fr); }
321
+ @media print { .gallery-grid img { max-height: none; } .gallery-grid { break-inside: avoid; } }
322
+
323
+ .side { display: grid; grid-template-columns: 0.8fr 1.2fr; gap: 22px; align-items: start; margin: 18px 0 22px; }
324
+ .side > img { width: 100%; border-radius: 8px; }
325
+ .side .poster-final { box-shadow: 0 18px 40px -22px rgba(20, 20, 40, 0.55); }
326
+ .quote { font: italic 400 16px/1.5 var(--serif); color: var(--ink-2); }
327
+ body.incorporata .side { grid-template-columns: 1fr; }
328
+ @media print { .side { break-inside: avoid; } .side > img { max-height: 120mm; width: auto; } }
web/guida/guida.js ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use strict";
2
+
3
+ (() => {
4
+ const params = new URLSearchParams(location.search);
5
+ if (params.has("incorporata")) document.body.classList.add("incorporata");
6
+
7
+ const flash = (id) => {
8
+ const target = id && document.getElementById(id);
9
+ if (!target) return;
10
+ const block = target.matches("section") ? target.querySelector("h2, h3") || target : target;
11
+ block.classList.remove("flash");
12
+ void block.offsetWidth;
13
+ block.classList.add("flash");
14
+ };
15
+
16
+ const go = (id) => {
17
+ const target = id && document.getElementById(id);
18
+ if (!target) return;
19
+ target.scrollIntoView({ block: "start" });
20
+ flash(id);
21
+ };
22
+
23
+ window.addEventListener("hashchange", () => go(location.hash.slice(1)));
24
+ window.addEventListener("message", (e) => {
25
+ if (e.origin !== location.origin || !e.data || !("evidenzia" in e.data)) return;
26
+ if (e.data.evidenzia) go(e.data.evidenzia);
27
+ });
28
+ if (location.hash) requestAnimationFrame(() => go(location.hash.slice(1)));
29
+
30
+ const links = [...document.querySelectorAll(".toc a[href^='#']")];
31
+ const byId = new Map(links.map((a) => [a.getAttribute("href").slice(1), a]));
32
+ const watched = [...document.querySelectorAll("main [id]")].filter((n) => byId.has(n.id));
33
+ if (!watched.length || !("IntersectionObserver" in window)) return;
34
+ const io = new IntersectionObserver((entries) => {
35
+ for (const entry of entries) {
36
+ if (!entry.isIntersecting) continue;
37
+ links.forEach((a) => a.classList.remove("attivo"));
38
+ byId.get(entry.target.id)?.classList.add("attivo");
39
+ }
40
+ }, { rootMargin: "-10% 0px -80% 0px" });
41
+ watched.forEach((n) => io.observe(n));
42
+ })();
web/guida/img/anime-foto.jpg ADDED
web/guida/img/anime.jpg ADDED

Git LFS Details

  • SHA256: 7cb552c891997a77b508e5d1a9b64bb91745b3432dc8fd353116896631c78fc4
  • Pointer size: 131 Bytes
  • Size of remote file: 162 kB
web/guida/img/app-cinese.jpg ADDED
web/guida/img/app.jpg ADDED
web/guida/img/funko.jpg ADDED
web/guida/img/liutaio.jpg ADDED
web/guida/img/locandina-lineup.jpg ADDED

Git LFS Details

  • SHA256: e903db7dd8ea4e2a88040ee0c4272bb488c08325d071a34face65b32e4540bd3
  • Pointer size: 131 Bytes
  • Size of remote file: 162 kB
web/guida/img/logo.jpg ADDED
web/guida/img/miele.jpg ADDED
web/guida/img/neve.jpg ADDED
web/guida/img/ritratto.jpg ADDED
web/guida/img/s-detail.jpg ADDED

Git LFS Details

  • SHA256: 32004f4c92db3c6938436565a71f4fa1ac0cd8f881cca71d4742ebc58799ea11
  • Pointer size: 131 Bytes
  • Size of remote file: 256 kB
web/guida/img/s-gallery.jpg ADDED

Git LFS Details

  • SHA256: a49beba0cfe0ec0834e7db2de8a209f74b3c599873b6e622ff736a79238f92fe
  • Pointer size: 131 Bytes
  • Size of remote file: 228 kB
web/guida/img/s-loc-a.jpg ADDED

Git LFS Details

  • SHA256: 0de712603b727ae84fc5edf53193db29c18ec5668880a30f7725b3bcaf1a22a0
  • Pointer size: 131 Bytes
  • Size of remote file: 171 kB
web/guida/img/s-loc-b.jpg ADDED

Git LFS Details

  • SHA256: 38ccbe3bba2ccfed990f6ad100bf5010c14db038a3454a6fee46d908225e2f9e
  • Pointer size: 131 Bytes
  • Size of remote file: 150 kB
web/guida/img/s-loc-c.jpg ADDED

Git LFS Details

  • SHA256: 293510aad244387e92fc979c568c8e9011a77ecbc7c808b417b949346b4ee738
  • Pointer size: 131 Bytes
  • Size of remote file: 149 kB