Spaces:
Sleeping

maxambrox commited on
Commit
2fecd56
·
verified ·
1 Parent(s): 4734e8e

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -449
app.py DELETED
@@ -1,449 +0,0 @@
1
- # app.py — AI Festival: Prompt Battle
2
- # Deploy su HF Spaces (Gradio SDK)
3
- # Secrets richiesti: GEMINI_API_KEY (gratis da ai.google.dev)
4
-
5
- import gradio as gr
6
- from google import genai
7
- from google.genai import types
8
- import os
9
- import time
10
- import json
11
- from pathlib import Path
12
- from datetime import datetime
13
-
14
- client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
15
-
16
- # --- Cartella immagini ---
17
- IMAGES_DIR = Path("/tmp/festival_images")
18
- IMAGES_DIR.mkdir(parents=True, exist_ok=True)
19
-
20
- STATE_FILE = Path("/tmp/festival_state.json")
21
-
22
- # --- Stato di gioco persistente su file (condiviso tra utenti) ---
23
-
24
- def default_state():
25
- return {
26
- "theme": "Nessun tema impostato",
27
- "round": 0,
28
- "timer_start": 0,
29
- "timer_duration": 1200,
30
- "active": False,
31
- "submissions": {},
32
- }
33
-
34
-
35
- def load_state():
36
- if STATE_FILE.exists():
37
- try:
38
- return json.loads(STATE_FILE.read_text())
39
- except Exception:
40
- pass
41
- return default_state()
42
-
43
-
44
- def save_state(state):
45
- STATE_FILE.write_text(json.dumps(state, ensure_ascii=False))
46
-
47
-
48
- def reset_full_state():
49
- state = default_state()
50
- save_state(state)
51
- return state
52
-
53
-
54
- # Inizializza
55
- if not STATE_FILE.exists():
56
- save_state(default_state())
57
-
58
-
59
- # =============================================
60
- # ADMIN
61
- # =============================================
62
-
63
- ADMIN_PIN = os.environ.get("ADMIN_PIN", "festival2026")
64
-
65
-
66
- def admin_login(pin):
67
- if pin == ADMIN_PIN:
68
- return (
69
- gr.update(visible=False),
70
- gr.update(visible=True),
71
- "",
72
- )
73
- return (
74
- gr.update(visible=True),
75
- gr.update(visible=False),
76
- "⛔ PIN errato",
77
- )
78
-
79
-
80
- def admin_start_round(theme, round_num, minutes):
81
- state = load_state()
82
- state["theme"] = theme
83
- state["round"] = round_num
84
- state["timer_start"] = time.time()
85
- state["timer_duration"] = int(minutes) * 60
86
- state["active"] = True
87
- save_state(state)
88
-
89
- r = "UN'IMMAGINE" if round_num == 1 else "UNA STORIA in 5 IMMAGINI"
90
- return f"✅ Round {round_num} avviato!\nTema: {theme}\nObiettivo: {r}\nTempo: {minutes} minuti"
91
-
92
-
93
- def admin_stop():
94
- state = load_state()
95
- state["active"] = False
96
- state["round"] = 0
97
- save_state(state)
98
- return "⏹️ Round fermato."
99
-
100
-
101
- def admin_reset():
102
- reset_full_state()
103
- # Pulisci immagini
104
- for f in IMAGES_DIR.glob("*"):
105
- f.unlink()
106
- return "🗑️ Tutto resettato."
107
-
108
-
109
- def admin_gallery_info():
110
- state = load_state()
111
- subs = state.get("submissions", {})
112
- lines = []
113
- for player, rounds in subs.items():
114
- for rnd, data in rounds.items():
115
- n_imgs = len(data.get("images", []))
116
- lines.append(f"• {player} — {rnd}: {n_imgs} immagine/i")
117
- if not lines:
118
- return "Nessuna submission ancora."
119
- return "\n".join(lines)
120
-
121
-
122
- # =============================================
123
- # PLAYER
124
- # =============================================
125
-
126
-
127
- def get_round_info():
128
- state = load_state()
129
- if not state["active"]:
130
- return (
131
- "⏳ In attesa che l'admin avvii il round...",
132
- "",
133
- "",
134
- False,
135
- )
136
-
137
- elapsed = time.time() - state["timer_start"]
138
- remaining = max(0, state["timer_duration"] - elapsed)
139
- mins = int(remaining // 60)
140
- secs = int(remaining % 60)
141
-
142
- if remaining <= 0:
143
- time_str = "⏰ TEMPO SCADUTO!"
144
- can_play = False
145
- else:
146
- time_str = f"⏱️ Tempo rimasto: {mins:02d}:{secs:02d}"
147
- can_play = True
148
-
149
- rnd = state["round"]
150
- if rnd == 1:
151
- obiettivo = "Crea il prompt perfetto per generare UN'IMMAGINE sul tema dato."
152
- else:
153
- obiettivo = "Crea il prompt per raccontare UNA STORIA in 5 IMMAGINI sul tema dato."
154
-
155
- theme_text = f"## 🎨 Round {rnd}\n### Tema: {state['theme']}\n\n{obiettivo}"
156
-
157
- return theme_text, time_str, "", can_play
158
-
159
-
160
- def generate_image(player_name, prompt, image_num):
161
- """Genera una singola immagine con Gemini Imagen 3."""
162
- if not player_name.strip():
163
- return None, "❌ Inserisci il tuo nome prima di generare!"
164
- if not prompt.strip():
165
- return None, "❌ Scrivi un prompt!"
166
-
167
- state = load_state()
168
- if not state["active"]:
169
- return None, "❌ Nessun round attivo."
170
-
171
- elapsed = time.time() - state["timer_start"]
172
- remaining = state["timer_duration"] - elapsed
173
- if remaining <= 0:
174
- return None, "⏰ Tempo scaduto! Non puoi più generare."
175
-
176
- try:
177
- response = client.models.generate_images(
178
- model="imagen-3.0-generate-002",
179
- prompt=prompt,
180
- config=types.GenerateImagesConfig(
181
- number_of_images=1,
182
- output_mime_type="image/png",
183
- ),
184
- )
185
-
186
- # Salva l'immagine
187
- rnd = state["round"]
188
- safe_name = "".join(c if c.isalnum() else "_" for c in player_name)
189
- filename = f"R{rnd}_{safe_name}_img{image_num}_{int(time.time())}.png"
190
- filepath = IMAGES_DIR / filename
191
- response.generated_images[0].image.save(str(filepath))
192
-
193
- # Salva nella submission
194
- player_key = player_name.strip()
195
- round_key = f"round{rnd}"
196
- if player_key not in state["submissions"]:
197
- state["submissions"][player_key] = {}
198
- if round_key not in state["submissions"][player_key]:
199
- state["submissions"][player_key][round_key] = {
200
- "prompt": prompt,
201
- "images": [],
202
- }
203
- state["submissions"][player_key][round_key]["prompt"] = prompt
204
- state["submissions"][player_key][round_key]["images"].append(str(filepath))
205
- save_state(state)
206
-
207
- msg = f"✅ Immagine {image_num} generata!"
208
- return str(filepath), msg
209
-
210
- except Exception as e:
211
- return None, f"❌ Errore: {str(e)}"
212
-
213
-
214
- def generate_round1(player_name, prompt):
215
- img, msg = generate_image(player_name, prompt, 1)
216
- return img, msg
217
-
218
-
219
- def generate_round2(player_name, prompt, slot):
220
- slot_num = int(slot.split(" ")[1]) # "Scena 1" -> 1
221
- img, msg = generate_image(player_name, prompt, slot_num)
222
- return img, msg
223
-
224
-
225
- # =============================================
226
- # GALLERIA
227
- # =============================================
228
-
229
-
230
- def load_gallery():
231
- state = load_state()
232
- subs = state.get("submissions", {})
233
- images = []
234
- for player, rounds in subs.items():
235
- for rnd_key, data in sorted(rounds.items()):
236
- for img_path in data.get("images", []):
237
- if os.path.exists(img_path):
238
- rnd_num = rnd_key.replace("round", "")
239
- caption = f"{player} — Round {rnd_num}"
240
- images.append((img_path, caption))
241
- if not images:
242
- return []
243
- return images
244
-
245
-
246
- # =============================================
247
- # INTERFACCIA GRADIO
248
- # =============================================
249
-
250
- CUSTOM_CSS = """
251
- @import url('https://fonts.googleapis.com/css2?family=Righteous&family=Source+Sans+3:wght@400;600&display=swap');
252
- .gradio-container { max-width: 1000px !important; margin: 0 auto !important; }
253
- .main-header {
254
- font-family: 'Righteous', cursive !important;
255
- text-align: center !important;
256
- font-size: 2.6em !important;
257
- margin-bottom: 0 !important;
258
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
259
- -webkit-background-clip: text;
260
- -webkit-text-fill-color: transparent;
261
- }
262
- .sub-header {
263
- text-align: center !important;
264
- color: #666 !important;
265
- font-size: 1.1em !important;
266
- margin-top: 0 !important;
267
- }
268
- .timer-display {
269
- font-family: 'Righteous', cursive !important;
270
- font-size: 2em !important;
271
- text-align: center !important;
272
- padding: 15px !important;
273
- border-radius: 12px !important;
274
- }
275
- footer { display: none !important; }
276
- """
277
-
278
- with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Soft(), title="AI Festival") as demo:
279
-
280
- gr.HTML(
281
- '<h1 class="main-header">🎨 AI Festival — Prompt Battle</h1>'
282
- '<p class="sub-header">Crea il prompt perfetto. Genera l\'immagine vincente.</p>'
283
- )
284
-
285
- with gr.Tabs() as tabs:
286
-
287
- # ===================
288
- # TAB: GIOCA
289
- # ===================
290
- with gr.Tab("🎮 Gioca", id="play"):
291
-
292
- player_name = gr.Textbox(
293
- label="Il tuo nome",
294
- placeholder="Come ti chiami?",
295
- max_lines=1,
296
- )
297
-
298
- round_info = gr.Markdown("⏳ In attesa che l'admin avvii il round...")
299
- timer_display = gr.Markdown("", elem_classes=["timer-display"])
300
- refresh_btn = gr.Button("🔄 Aggiorna stato", size="sm")
301
-
302
- # --- Round 1: una immagine ---
303
- with gr.Group(visible=True) as round1_group:
304
- gr.Markdown("### ✏️ Scrivi il tuo prompt")
305
- prompt_r1 = gr.Textbox(
306
- label="Prompt",
307
- lines=4,
308
- placeholder="Descrivi l'immagine che vuoi creare in modo dettagliato...",
309
- )
310
- gen_btn_r1 = gr.Button(
311
- "🎨 Genera Immagine",
312
- variant="primary",
313
- size="lg",
314
- )
315
- with gr.Row():
316
- result_img_r1 = gr.Image(
317
- label="La tua immagine", type="filepath", height=400
318
- )
319
- status_r1 = gr.Markdown("")
320
-
321
- # --- Round 2: 5 immagini storia ---
322
- with gr.Group(visible=True) as round2_group:
323
- gr.Markdown("### ✏️ Racconta una storia in 5 immagini")
324
- gr.Markdown(
325
- "Genera le 5 scene della tua storia una alla volta. "
326
- "Seleziona la scena, scrivi il prompt, genera."
327
- )
328
- with gr.Row():
329
- scene_selector = gr.Radio(
330
- ["Scena 1", "Scena 2", "Scena 3", "Scena 4", "Scena 5"],
331
- value="Scena 1",
332
- label="Quale scena stai generando?",
333
- )
334
- prompt_r2 = gr.Textbox(
335
- label="Prompt per questa scena",
336
- lines=3,
337
- placeholder="Descrivi questa scena della storia...",
338
- )
339
- gen_btn_r2 = gr.Button(
340
- "🎨 Genera Scena",
341
- variant="primary",
342
- size="lg",
343
- )
344
- with gr.Row():
345
- result_img_r2 = gr.Image(
346
- label="Scena generata", type="filepath", height=350
347
- )
348
- status_r2 = gr.Markdown("")
349
-
350
- # --- Azioni ---
351
- def refresh_ui():
352
- info, timer, _, can_play = get_round_info()
353
- return info, timer
354
-
355
- refresh_btn.click(refresh_ui, outputs=[round_info, timer_display])
356
-
357
- gen_btn_r1.click(
358
- generate_round1,
359
- inputs=[player_name, prompt_r1],
360
- outputs=[result_img_r1, status_r1],
361
- )
362
-
363
- gen_btn_r2.click(
364
- generate_round2,
365
- inputs=[player_name, prompt_r2, scene_selector],
366
- outputs=[result_img_r2, status_r2],
367
- )
368
-
369
- # ===================
370
- # TAB: GALLERIA
371
- # ===================
372
- with gr.Tab("🖼️ Galleria", id="gallery"):
373
- gallery_btn = gr.Button("🔄 Carica galleria", size="sm")
374
- gallery = gr.Gallery(
375
- label="Tutte le immagini generate",
376
- columns=3,
377
- height=600,
378
- object_fit="contain",
379
- )
380
- gallery_btn.click(load_gallery, outputs=gallery)
381
-
382
- # ===================
383
- # TAB: ADMIN
384
- # ===================
385
- with gr.Tab("⚙️ Admin", id="admin"):
386
-
387
- # Login
388
- with gr.Group() as admin_login_group:
389
- gr.Markdown("### 🔐 Accesso Admin")
390
- pin_input = gr.Textbox(
391
- label="PIN Admin",
392
- type="password",
393
- placeholder="Inserisci il PIN...",
394
- )
395
- login_btn = gr.Button("Accedi", variant="primary")
396
- login_msg = gr.Markdown("")
397
-
398
- # Pannello admin (nascosto finché non fai login)
399
- with gr.Group(visible=False) as admin_panel:
400
- gr.Markdown("### 🎛️ Pannello di controllo")
401
-
402
- theme_input = gr.Textbox(
403
- label="Tema del round",
404
- placeholder='Es: "Il futuro delle città nel 2100"',
405
- lines=2,
406
- )
407
-
408
- with gr.Row():
409
- round_select = gr.Radio(
410
- [1, 2],
411
- value=1,
412
- label="Round",
413
- info="Round 1 = 1 immagine, Round 2 = storia in 5 immagini",
414
- )
415
- minutes_input = gr.Number(
416
- value=20,
417
- label="Minuti",
418
- minimum=1,
419
- maximum=60,
420
- )
421
-
422
- with gr.Row():
423
- start_btn = gr.Button("▶️ Avvia Round", variant="primary")
424
- stop_btn = gr.Button("⏹️ Ferma Round", variant="stop")
425
- reset_btn = gr.Button("🗑️ Reset totale")
426
-
427
- admin_status = gr.Markdown("")
428
-
429
- gr.Markdown("### 📊 Submissions")
430
- submissions_btn = gr.Button("Aggiorna elenco", size="sm")
431
- submissions_info = gr.Markdown("")
432
-
433
- # Admin events
434
- login_btn.click(
435
- admin_login,
436
- inputs=pin_input,
437
- outputs=[admin_login_group, admin_panel, login_msg],
438
- )
439
- start_btn.click(
440
- admin_start_round,
441
- inputs=[theme_input, round_select, minutes_input],
442
- outputs=admin_status,
443
- )
444
- stop_btn.click(admin_stop, outputs=admin_status)
445
- reset_btn.click(admin_reset, outputs=admin_status)
446
- submissions_btn.click(admin_gallery_info, outputs=submissions_info)
447
-
448
-
449
- demo.launch()