vighnesh-shetty-vs commited on
Commit
fe378f2
Β·
1 Parent(s): 4e510ce

Add updated files

Browse files
Files changed (1) hide show
  1. app.py +116 -172
app.py CHANGED
@@ -4,10 +4,6 @@ import random
4
  from gtts import gTTS
5
  import os
6
 
7
- from game_data import calculate_impact, MODELS
8
- from dialogues import get_dialogue
9
- from alternatives import ALTERNATIVES
10
-
11
  print("Loading classification model...", flush=True)
12
  classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
13
 
@@ -85,7 +81,6 @@ ALTERNATIVES = {
85
  def calculate_impact(category, confidence_score, query_text, model_name):
86
  model_cost = MODELS.get(model_name, MODELS["Mistral Large 3"])
87
  cat_mult = CATEGORY_MULTIPLIERS.get(category, 0.05)
88
-
89
  conf_mult = 1.0 if confidence_score > 0.8 else (1.2 if confidence_score > 0.5 else 1.5)
90
  word_count = len(query_text.split())
91
  len_factor = max(0.5, 1.0 + ((word_count - 15) * 0.015))
@@ -95,15 +90,11 @@ def calculate_impact(category, confidence_score, query_text, model_name):
95
  co2_g = model_cost["co2_g"] * cat_mult * conf_mult * len_factor
96
 
97
  return {
98
- "water_l": water_ml / 1000.0,
99
- "energy_kwh": energy_wh / 1000.0,
100
- "water_ml": round(water_ml, 1),
101
- "energy_wh": round(energy_wh, 2),
102
- "co2_g": round(co2_g, 2)
103
  }
104
 
105
  def get_dialogue(water_level, category):
106
- # Adjusted dialogue thresholds for 1L max
107
  state = "energetic" if water_level > 0.7 else ("tired" if water_level >= 0.3 else "raspy")
108
  return DIALOGUES[state].get(category, "I have no words left for this.")
109
 
@@ -113,7 +104,7 @@ def generate_audio(text):
113
  tts.save(filepath)
114
  return filepath
115
 
116
- # --- 2. UI GENERATORS ---
117
 
118
  def get_relatable_translations(impact):
119
  bottles = impact['water_ml'] / 500.0
@@ -125,32 +116,17 @@ def get_relatable_translations(impact):
125
  return w_ex, e_ex, c_ex
126
 
127
  def get_stats_html(water, energy, co2, points):
128
- # Updated progress bar logic for a 1.0L maximum
129
  water_percent = max(0, min(100, (water / 1.0) * 100))
130
  return f"""
131
  <div class="stats-container">
132
- <div class="stat-card water-card">
133
- <div class="stat-label">WATER TANK (1L MAX)</div>
134
- <div class="stat-value">{water:.3f}L</div>
135
- <div class="progress-bar-bg"><div class="progress-bar-fill" style="width: {water_percent}%;"></div></div>
136
- </div>
137
- <div class="stat-card energy-card">
138
- <div class="stat-label">ENERGY WASTED</div>
139
- <div class="stat-value">{energy:.4f} <span style="font-size: 0.5em;">kWh</span></div>
140
- </div>
141
- <div class="stat-card co2-card">
142
- <div class="stat-label">CARBON (COβ‚‚e)</div>
143
- <div class="stat-value">{co2:.2f}g</div>
144
- </div>
145
- <div class="stat-card points-card">
146
- <div class="stat-label">SCORE</div>
147
- <div class="stat-value">{points}</div>
148
- </div>
149
  </div>
150
  """
151
 
152
  def get_drip_visuals(water_level):
153
- # Adjusted visual state thresholds for 1.0L maximum
154
  if water_level > 0.7:
155
  g_start, g_end = "#7dd3fc", "#0369a1"
156
  mouth_d = "M43 112 Q60 122 77 112"
@@ -176,11 +152,7 @@ def get_drip_visuals(water_level):
176
  <div class="drip-panel" style="animation: {anim}; display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%;">
177
  <div class="drip-lbl" style="font-weight: 800; color: #94a3b8; letter-spacing: 3px; font-size: 14px; margin-bottom: 5px;">DRIP</div>
178
  <svg id="drip-svg" viewBox="0 0 120 148" style="width: 140px; height: 160px; overflow: visible;" xmlns="http://www.w3.org/2000/svg">
179
- <defs>
180
- <radialGradient id="dg" cx="38%" cy="32%">
181
- <stop id="dg1" offset="0%" stop-color="{g_start}"></stop><stop id="dg2" offset="100%" stop-color="{g_end}"></stop>
182
- </radialGradient>
183
- </defs>
184
  <path id="dbody" d="M60 8 C60 8,102 66,102 90 C102 118,83 137,60 137 C37 137,18 118,18 90 C18 66,60 8,60 8Z" fill="url(#dg)" stroke="rgba(34,211,238,0.35)" stroke-width="1.5" opacity="1"></path>
185
  <ellipse cx="42" cy="70" rx="9" ry="13" fill="rgba(255,255,255,0.22)" transform="rotate(-18,42,70)"></ellipse>
186
  <circle cx="44" cy="90" r="10" fill="white"></circle><circle cx="76" cy="90" r="10" fill="white"></circle>
@@ -188,17 +160,13 @@ def get_drip_visuals(water_level):
188
  <circle cx="47" cy="88" r="2.5" fill="white"></circle><circle cx="79" cy="88" r="2.5" fill="white"></circle>
189
  <path id="dm" d="{mouth_d}" stroke="#0f172a" stroke-width="2.5" stroke-linecap="round" fill="none"></path>
190
  <g id="cracks" opacity="{cracks_op}" style="transition: opacity 0.5s;">
191
- <path d="M80 46 L86 58 L79 65 L85 77" stroke="#bae6fd" stroke-width="1.3" stroke-linecap="round" fill="none" opacity=".7"></path>
192
- <path d="M37 82 L31 93 L39 99" stroke="#bae6fd" stroke-width="1.3" stroke-linecap="round" fill="none" opacity=".7"></path>
193
  </g>
194
  <path id="sweat" d="M108 76 C110 70,116 70,116 78 C116 84,110 88,108 82Z" fill="#7dd3fc" opacity="{sweat_op}" style="transition: opacity 0.5s;"></path>
195
  <path id="tear" d="M38 104 C37 108,33 108,33 112 C33 115,36 117,38 114 C40 117,43 115,43 112 C43 108,39 108,38 104Z" fill="#93c5fd" opacity="{tear_op}" style="transition: opacity 0.5s;"></path>
196
  </svg>
197
  <div class="drip-mood" id="drip-mood" style="color: {mood_color}; font-weight: 500; font-size: 1.1rem; margin-top: 15px;">{mood}</div>
198
- <div style="text-align:center; margin-top:10px;">
199
- <div style="font-size:10px; color:#94a3b8; text-transform:uppercase; letter-spacing:1px;">Water Left</div>
200
- <div style="font-size:26px; font-weight:700; color:{mood_color};" id="d-water">{water_level:.3f}L</div>
201
- </div>
202
  </div>
203
  """
204
 
@@ -232,131 +200,108 @@ def format_alt_button(text, impact):
232
  return f"{icon} {text}\n\nπŸ† Score: +10 Pts\nπŸ’§ Save: {impact['water_ml']} mL\n⚑ Save: {impact['energy_wh']} Wh\n☁️ Save: {impact['co2_g']} g"
233
 
234
  def generate_victory_dashboard(state):
235
- try:
236
- total_w_saved, total_e_saved, total_c_saved = 0.0, 0.0, 0.0
237
- rows = ""
238
- for item in state.get("history", []):
239
- alt_name = item.get('alt_name', 'None')
240
- saved_w = item.get('water_ml', 0.0)
241
- saved_e = max(0.0, item.get('energy_wh', 0.0) - 0.001)
242
- saved_c = max(0.0, item.get('co2_g', 0.0) - 0.01)
243
-
244
- total_w_saved += saved_w
245
- total_e_saved += saved_e
246
- total_c_saved += saved_c
247
- alt_display = f"<span style='color: #34d399; font-weight: bold;'>{alt_name}</span>"
248
-
249
- rows += f"""
250
- <tr style="border-bottom: 1px solid rgba(255,255,255,0.1); background: rgba(0,0,0,0.2);">
251
- <td style="padding: 15px; font-style: italic;">"{item.get('query', '')}"</td>
252
- <td style="padding: 15px; color: #fca5a5; line-height: 1.5;">πŸ’§ {item.get('water_ml', 0):.1f} mL<br>⚑ {item.get('energy_wh', 0):.2f} Wh<br>☁️ {item.get('co2_g', 0):.2f} g</td>
253
- <td style="padding: 15px;">{alt_display}</td>
254
- <td style="padding: 15px; color: #60a5fa; font-weight: bold; line-height: 1.5;">πŸ’§ {saved_w:.1f} mL<br>⚑ {saved_e:.2f} Wh<br>☁️ {saved_c:.2f} g</td>
255
- </tr>
256
- """
257
- confetti_elements = "".join([f'<div class="confetti-piece" style="left: {random.randint(0, 100)}%; background-color: hsl({random.randint(0, 360)}, 100%, 60%); animation-duration: {random.uniform(2.5, 5)}s; animation-delay: {random.uniform(0, 2)}s;"></div>' for _ in range(60)])
258
 
259
- # Updated "Total Wasted" formula from 10.0 to 1.0 to reflect the 1L tank
260
- return f"""
261
- <div class="victory-wrapper">
262
- {confetti_elements}
263
- <div class="victory-dashboard">
264
- <h1 class="victory-title">πŸŽ‰ PLANET SAVED! πŸŽ‰</h1>
265
- <p style="text-align: center; font-size: 1.3em; color: #a7f3d0; margin-bottom: 30px;">Congratulations! You reached {state.get('points', 0)} points!</p>
266
- <div class="victory-stats-row">
267
- <div class="v-stat-box" style="border-top: 4px solid #34d399;">
268
- <h4 style="color: #34d399;">Planetary Savings</h4>
269
- <p style="color: #34d399; font-size: 1.3em; font-weight: bold; margin: 8px 0;">πŸ’§ {total_w_saved:.1f} mL Saved</p>
270
- <p style="color: #facc15; font-size: 1.3em; font-weight: bold; margin: 8px 0;">⚑ {total_e_saved:.2f} Wh Saved</p>
271
- <p style="color: #a8a29e; font-size: 1.3em; font-weight: bold; margin: 8px 0;">☁️ {total_c_saved:.2f} g Saved</p>
272
- </div>
273
- <div class="v-stat-box" style="border-top: 4px solid #fca5a5;">
274
- <h4 style="color: #fca5a5;">Total Wasted</h4>
275
- <p style="color: #fca5a5; font-size: 1.1em; margin: 8px 0;">πŸ’§ {1.0 - state.get('water', 1.0):.3f} L</p>
276
- <p style="color: #fca5a5; font-size: 1.1em; margin: 8px 0;">⚑ {state.get('energy', 0):.4f} kWh</p>
277
- <p style="color: #fca5a5; font-size: 1.1em; margin: 8px 0;">☁️ {state.get('co2', 0):.2f} g</p>
278
- </div>
 
 
279
  </div>
280
- <h3 style="margin-top: 40px; color: #38bdf8; font-size: 1.8em; text-align: center;">πŸ“Š AI Usage Audit Log</h3>
281
- <div style="max-height: 500px; overflow-y: auto; background: rgba(15, 23, 42, 0.9); border-radius: 12px; border: 1px solid rgba(255,255,255,0.1); padding: 10px;">
282
- <table style="width: 100%; text-align: left; border-collapse: collapse; font-size: 1.05em;">
283
- <tr style="background: rgba(56, 189, 248, 0.1); border-bottom: 2px solid #38bdf8;">
284
- <th style="padding: 15px; color: #e2e8f0;">User Query</th><th style="padding: 15px; color: #fca5a5;">LLM Cost</th><th style="padding: 15px; color: #34d399;">Alternative</th><th style="padding: 15px; color: #60a5fa;">Resources Saved</th>
285
- </tr>
286
- {rows}
287
- </table>
288
  </div>
289
  </div>
 
 
 
 
 
 
 
 
 
290
  </div>
291
- """
292
- except Exception as e:
293
- return f"<div style='color:red;'>Error generating dashboard: {str(e)}</div>"
294
 
295
  def generate_defeat_dashboard(state):
296
- """Generates a dark, Game Over report when Drip evaporates."""
297
- try:
298
- rows = ""
299
- for item in state.get("history", []):
300
- rows += f"""
301
- <tr style="border-bottom: 1px solid rgba(255,255,255,0.1); background: rgba(0,0,0,0.2);">
302
- <td style="padding: 15px; font-style: italic; color: #e2e8f0;">"{item.get('query', '')}"</td>
303
- <td style="padding: 15px; color: #fca5a5; font-weight: bold; line-height: 1.5;">
304
- πŸ’§ {item.get('water_ml', 0):.1f} mL<br>
305
- ⚑ {item.get('energy_wh', 0):.2f} Wh<br>
306
- ☁️ {item.get('co2_g', 0):.2f} g
307
- </td>
308
- </tr>
309
- """
310
-
311
- # Dynamically generate rising "ash/steam" particles
312
- ash_elements = "".join([f'<div class="ash-piece" style="left: {random.randint(0, 100)}%; animation-duration: {random.uniform(3, 6)}s; animation-delay: {random.uniform(0, 2)}s;"></div>' for _ in range(60)])
313
-
314
- return f"""
315
- <div class="victory-wrapper">
316
- {ash_elements}
317
- <div class="defeat-dashboard">
318
- <h1 class="defeat-title">πŸ’€ DRIP EVAPORATED! πŸ’€</h1>
319
- <p style="text-align: center; font-size: 1.3em; color: #fca5a5; margin-bottom: 30px;">
320
- You ran out of water before reaching 500 points. The planet's resources have been drained!
321
- </p>
322
-
323
- <div class="victory-stats-row">
324
- <div class="v-stat-box" style="border-top: 4px solid #ef4444; background: rgba(239, 68, 68, 0.1);">
325
- <h4 style="color: #ef4444;">Total Resources Wasted</h4>
326
- <p style="color: #fca5a5; font-size: 1.3em; font-weight: bold; margin: 8px 0;">πŸ’§ 1.0 L (Tank Empty)</p>
327
- <p style="color: #fca5a5; font-size: 1.3em; font-weight: bold; margin: 8px 0;">⚑ {state.get('energy', 0):.4f} kWh</p>
328
- <p style="color: #fca5a5; font-size: 1.3em; font-weight: bold; margin: 8px 0;">☁️ {state.get('co2', 0):.2f} g</p>
329
- </div>
330
- <div class="v-stat-box" style="border-top: 4px solid #94a3b8;">
331
- <h4 style="color: #94a3b8;">Final Score</h4>
332
- <p style="color: white; font-size: 3.5em; font-weight: bold; margin: 10px 0;">{state.get('points', 0)}</p>
333
- </div>
334
  </div>
335
-
336
- <h3 style="margin-top: 40px; color: #fca5a5; font-size: 1.8em; text-align: center;">πŸ”₯ Wasted Resources Log</h3>
337
- <p style="opacity: 0.9; margin-bottom: 20px; text-align: center; color: #e2e8f0;">See exactly where your massive LLM compute drained Drip's tank.</p>
338
-
339
- <div style="max-height: 400px; overflow-y: auto; background: rgba(15, 23, 42, 0.9); border-radius: 12px; border: 1px solid rgba(239, 68, 68, 0.3); padding: 10px;">
340
- <table style="width: 100%; text-align: left; border-collapse: collapse; font-size: 1.05em;">
341
- <tr style="background: rgba(239, 68, 68, 0.15); border-bottom: 2px solid #ef4444;">
342
- <th style="padding: 15px; color: #fca5a5;">User Query</th>
343
- <th style="padding: 15px; color: #fca5a5;">Resources Drained</th>
344
- </tr>
345
- {rows}
346
- </table>
347
  </div>
348
  </div>
 
 
 
 
 
 
 
 
 
349
  </div>
350
- """
351
- except Exception as e:
352
- return f"<div style='color:red;'>Error generating dashboard: {str(e)}</div>"
353
-
354
 
355
  # --- 3. EVENT HANDLERS ---
356
 
357
  def process_query(user_input, selected_model, state):
 
358
  if state["game_over"] or not user_input.strip():
359
- return [state, gr.update()] + [gr.update()]*10 + [gr.update(visible=True), gr.update(visible=False), gr.update()]
360
 
361
  result = classifier(user_input, CATEGORIES)
362
  category = result['labels'][0]
@@ -396,27 +341,29 @@ def process_query(user_input, selected_model, state):
396
  audio_path = generate_audio(dialogue)
397
  feedback_text = f"<div class='feedback-box'>🧠 <strong>{category.upper()}</strong> Detected!<br><br><em>\"{dialogue}\"</em></div>"
398
 
399
- # Check for WIN condition
400
  if state["points"] >= 500:
401
  state["game_over"] = True
402
  return (state, stats_ui, drip_ui, audio_path, impact_ui, gr.update(), gr.update(visible=False),
403
  gr.update(), gr.update(), gr.update(), gr.update(), gr.update(value=""),
404
  gr.update(visible=False), gr.update(visible=True), gr.update(value=generate_victory_dashboard(state)))
405
 
406
- # Check for LOSS condition
407
- elif state["water"] <= 0:
408
  state["game_over"] = True
409
  return (state, stats_ui, drip_ui, audio_path, impact_ui, gr.update(), gr.update(visible=False),
410
  gr.update(), gr.update(), gr.update(), gr.update(), gr.update(value=""),
411
  gr.update(visible=False), gr.update(visible=True), gr.update(value=generate_defeat_dashboard(state)))
412
 
 
413
  return (state, stats_ui, drip_ui, audio_path, impact_ui, gr.update(value=feedback_text), gr.update(visible=True),
414
  gr.update(value=alt_choices[0], visible=True), gr.update(value=alt_choices[1], visible=True), gr.update(value=alt_choices[2], visible=True), gr.update(value=""), gr.update(value=""),
415
  gr.update(visible=True), gr.update(visible=False), gr.update())
416
 
417
  def select_alternative(choice_text, state):
 
418
  if state["game_over"] or not state.get("current_best_alt"):
419
- return state, gr.update(), gr.update(), gr.update(), gr.update(visible=True), gr.update(visible=False), gr.update()
420
 
421
  first_line = choice_text.split("\n")[0]
422
  clean_choice = first_line.split(" ", 1)[1].strip() if " " in first_line else first_line
@@ -432,6 +379,7 @@ def select_alternative(choice_text, state):
432
 
433
  stats_ui = get_stats_html(state["water"], state["energy"], state["co2"], state["points"])
434
 
 
435
  if state["points"] >= 500:
436
  state["game_over"] = True
437
  return state, stats_ui, gr.update(), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), gr.update(value=generate_victory_dashboard(state))
@@ -482,35 +430,26 @@ h1 { text-align: center; color: #38bdf8; text-shadow: 0 0 15px rgba(56, 189, 248
482
  .alt-card:hover { background: linear-gradient(145deg, #064e3b, #065f46) !important; transform: translateY(-8px) !important; box-shadow: 0 12px 30px rgba(16, 185, 129, 0.3) !important; color: white !important; border-color: #34d399 !important;}
483
  .custom-dropdown { background: rgba(30, 41, 59, 0.8) !important; border: 1px solid #38bdf8 !important; border-radius: 12px !important; }
484
 
485
- /* Victory Dashboard & Celebration */
486
- @keyframes pulseGlow { 0% { box-shadow: 0 0 20px rgba(52, 211, 153, 0.4); } 50% { box-shadow: 0 0 50px rgba(52, 211, 153, 0.8); } 100% { box-shadow: 0 0 20px rgba(52, 211, 153, 0.4); } }
487
- .victory-wrapper { position: relative; width: 100%; min-height: 600px; overflow: hidden; border-radius: 24px; padding-top: 10px; }
488
  .victory-dashboard { background: linear-gradient(135deg, #0f172a, #1e293b); padding: 40px; border-radius: 24px; border: 2px solid #34d399; animation: pulseGlow 2s infinite; color: white; position: relative; z-index: 5; margin-top: 20px;}
489
  .victory-title { text-align: center; color: #34d399; font-size: 3.5em !important; text-shadow: 0 0 20px rgba(52, 211, 153, 0.6); margin-bottom: 5px; }
490
  .victory-stats-row { display: flex; gap: 20px; margin-top: 30px; }
491
  .v-stat-box { flex: 1; background: rgba(0,0,0,0.4); padding: 25px; border-radius: 16px; text-align: center; border: 1px solid rgba(52, 211, 153, 0.3); }
492
  .v-stat-box h4 { color: #94a3b8; font-size: 0.9em; text-transform: uppercase; letter-spacing: 1px; margin: 0 0 10px 0; }
493
 
 
494
  .confetti-piece { position: absolute; width: 10px; height: 15px; top: -20px; opacity: 0; animation: fall linear forwards infinite; z-index: 10; border-radius: 2px;}
495
- @keyframes fall {
496
- 0% { transform: translateY(-20px) rotate(0deg); opacity: 1; }
497
- 100% { transform: translateY(1000px) rotate(720deg); opacity: 1; }
498
- }
499
 
500
- /* Defeat Dashboard & Animations */
501
- @keyframes pulseRed { 0% { box-shadow: 0 0 20px rgba(239, 68, 68, 0.4); } 50% { box-shadow: 0 0 60px rgba(239, 68, 68, 0.8); } 100% { box-shadow: 0 0 20px rgba(239, 68, 68, 0.4); } }
502
  .defeat-dashboard { background: linear-gradient(135deg, #2b1010, #450a0a); padding: 40px; border-radius: 24px; border: 2px solid #ef4444; animation: pulseRed 2s infinite; color: white; position: relative; z-index: 5; margin-top: 20px; }
503
  .defeat-title { text-align: center; color: #ef4444; font-size: 3.5em !important; text-shadow: 0 0 20px rgba(239, 68, 68, 0.8); margin-bottom: 5px; }
 
504
  .ash-piece { position: absolute; width: 8px; height: 8px; background-color: rgba(156, 163, 175, 0.6); border-radius: 50%; opacity: 0; animation: floatAsh linear forwards infinite; z-index: 10; filter: blur(1px); }
505
- @keyframes floatAsh {
506
- 0% { transform: translateY(600px) scale(1); opacity: 0; }
507
- 20% { opacity: 0.8; }
508
- 100% { transform: translateY(-100px) scale(2); opacity: 0; }
509
- }
510
  """
511
 
512
  with gr.Blocks(css=custom_css, title="EcoQueryQuest") as demo:
513
- # UPDATED to start with 1.0 Liters
514
  game_state = gr.State({
515
  "water": 1.0, "energy": 0.0, "co2": 0.0, "points": 0, "queries": 0,
516
  "history": [], "game_over": False, "current_best_alt": None, "current_shuffled_alts": []
@@ -519,13 +458,11 @@ with gr.Blocks(css=custom_css, title="EcoQueryQuest") as demo:
519
  gr.Markdown("<h1>🌍 EcoQueryQuest</h1>")
520
  gr.Markdown("<div class='subtitle'>Select a model, type a query, and watch Drip react. Reach 500 points to win!</div>")
521
 
522
- # UPDATED to start UI with 1.0 Liters
523
  stats_html = gr.HTML(get_stats_html(1.0, 0.0, 0.0, 0))
524
 
525
  with gr.Column(visible=True) as main_game_ui:
526
  with gr.Row():
527
  with gr.Column(scale=1, elem_classes=["drip-pod"]):
528
- # UPDATED to start Drip visual with 1.0 Liters
529
  drip_html = gr.HTML(get_drip_visuals(1.0))
530
  drip_audio = gr.Audio(label="Drip's Voice", autoplay=True, interactive=False, elem_classes=["hidden-audio"])
531
  drip_feedback = gr.HTML("<div class='feedback-box'>Waiting for your first query...</div>")
@@ -548,6 +485,13 @@ with gr.Blocks(css=custom_css, title="EcoQueryQuest") as demo:
548
  with gr.Column(visible=False) as victory_ui:
549
  victory_display = gr.HTML()
550
 
 
 
 
 
 
 
 
551
  submit_btn.click(
552
  fn=process_query,
553
  inputs=[user_input, model_selector, game_state],
 
4
  from gtts import gTTS
5
  import os
6
 
 
 
 
 
7
  print("Loading classification model...", flush=True)
8
  classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
9
 
 
81
  def calculate_impact(category, confidence_score, query_text, model_name):
82
  model_cost = MODELS.get(model_name, MODELS["Mistral Large 3"])
83
  cat_mult = CATEGORY_MULTIPLIERS.get(category, 0.05)
 
84
  conf_mult = 1.0 if confidence_score > 0.8 else (1.2 if confidence_score > 0.5 else 1.5)
85
  word_count = len(query_text.split())
86
  len_factor = max(0.5, 1.0 + ((word_count - 15) * 0.015))
 
90
  co2_g = model_cost["co2_g"] * cat_mult * conf_mult * len_factor
91
 
92
  return {
93
+ "water_l": water_ml / 1000.0, "energy_kwh": energy_wh / 1000.0,
94
+ "water_ml": round(water_ml, 1), "energy_wh": round(energy_wh, 2), "co2_g": round(co2_g, 2)
 
 
 
95
  }
96
 
97
  def get_dialogue(water_level, category):
 
98
  state = "energetic" if water_level > 0.7 else ("tired" if water_level >= 0.3 else "raspy")
99
  return DIALOGUES[state].get(category, "I have no words left for this.")
100
 
 
104
  tts.save(filepath)
105
  return filepath
106
 
107
+ # --- 2. UI GENERATORS & DASHBOARDS ---
108
 
109
  def get_relatable_translations(impact):
110
  bottles = impact['water_ml'] / 500.0
 
116
  return w_ex, e_ex, c_ex
117
 
118
  def get_stats_html(water, energy, co2, points):
 
119
  water_percent = max(0, min(100, (water / 1.0) * 100))
120
  return f"""
121
  <div class="stats-container">
122
+ <div class="stat-card water-card"><div class="stat-label">WATER TANK (1L MAX)</div><div class="stat-value">{water:.3f}L</div><div class="progress-bar-bg"><div class="progress-bar-fill" style="width: {water_percent}%;"></div></div></div>
123
+ <div class="stat-card energy-card"><div class="stat-label">ENERGY WASTED</div><div class="stat-value">{energy:.4f} <span style="font-size: 0.5em;">kWh</span></div></div>
124
+ <div class="stat-card co2-card"><div class="stat-label">CARBON (COβ‚‚e)</div><div class="stat-value">{co2:.2f}g</div></div>
125
+ <div class="stat-card points-card"><div class="stat-label">SCORE</div><div class="stat-value">{points}</div></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  </div>
127
  """
128
 
129
  def get_drip_visuals(water_level):
 
130
  if water_level > 0.7:
131
  g_start, g_end = "#7dd3fc", "#0369a1"
132
  mouth_d = "M43 112 Q60 122 77 112"
 
152
  <div class="drip-panel" style="animation: {anim}; display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%;">
153
  <div class="drip-lbl" style="font-weight: 800; color: #94a3b8; letter-spacing: 3px; font-size: 14px; margin-bottom: 5px;">DRIP</div>
154
  <svg id="drip-svg" viewBox="0 0 120 148" style="width: 140px; height: 160px; overflow: visible;" xmlns="http://www.w3.org/2000/svg">
155
+ <defs><radialGradient id="dg" cx="38%" cy="32%"><stop id="dg1" offset="0%" stop-color="{g_start}"></stop><stop id="dg2" offset="100%" stop-color="{g_end}"></stop></radialGradient></defs>
 
 
 
 
156
  <path id="dbody" d="M60 8 C60 8,102 66,102 90 C102 118,83 137,60 137 C37 137,18 118,18 90 C18 66,60 8,60 8Z" fill="url(#dg)" stroke="rgba(34,211,238,0.35)" stroke-width="1.5" opacity="1"></path>
157
  <ellipse cx="42" cy="70" rx="9" ry="13" fill="rgba(255,255,255,0.22)" transform="rotate(-18,42,70)"></ellipse>
158
  <circle cx="44" cy="90" r="10" fill="white"></circle><circle cx="76" cy="90" r="10" fill="white"></circle>
 
160
  <circle cx="47" cy="88" r="2.5" fill="white"></circle><circle cx="79" cy="88" r="2.5" fill="white"></circle>
161
  <path id="dm" d="{mouth_d}" stroke="#0f172a" stroke-width="2.5" stroke-linecap="round" fill="none"></path>
162
  <g id="cracks" opacity="{cracks_op}" style="transition: opacity 0.5s;">
163
+ <path d="M80 46 L86 58 L79 65 L85 77" stroke="#bae6fd" stroke-width="1.3" stroke-linecap="round" fill="none" opacity=".7"></path><path d="M37 82 L31 93 L39 99" stroke="#bae6fd" stroke-width="1.3" stroke-linecap="round" fill="none" opacity=".7"></path>
 
164
  </g>
165
  <path id="sweat" d="M108 76 C110 70,116 70,116 78 C116 84,110 88,108 82Z" fill="#7dd3fc" opacity="{sweat_op}" style="transition: opacity 0.5s;"></path>
166
  <path id="tear" d="M38 104 C37 108,33 108,33 112 C33 115,36 117,38 114 C40 117,43 115,43 112 C43 108,39 108,38 104Z" fill="#93c5fd" opacity="{tear_op}" style="transition: opacity 0.5s;"></path>
167
  </svg>
168
  <div class="drip-mood" id="drip-mood" style="color: {mood_color}; font-weight: 500; font-size: 1.1rem; margin-top: 15px;">{mood}</div>
169
+ <div style="text-align:center; margin-top:10px;"><div style="font-size:10px; color:#94a3b8; text-transform:uppercase; letter-spacing:1px;">Water Left</div><div style="font-size:26px; font-weight:700; color:{mood_color};" id="d-water">{water_level:.3f}L</div></div>
 
 
 
170
  </div>
171
  """
172
 
 
200
  return f"{icon} {text}\n\nπŸ† Score: +10 Pts\nπŸ’§ Save: {impact['water_ml']} mL\n⚑ Save: {impact['energy_wh']} Wh\n☁️ Save: {impact['co2_g']} g"
201
 
202
  def generate_victory_dashboard(state):
203
+ total_w_saved, total_e_saved, total_c_saved = 0.0, 0.0, 0.0
204
+ rows = ""
205
+ for item in state.get("history", []):
206
+ alt_name = item.get('alt_name', 'None')
207
+ saved_w = item.get('water_ml', 0.0)
208
+ saved_e = max(0.0, item.get('energy_wh', 0.0) - 0.001)
209
+ saved_c = max(0.0, item.get('co2_g', 0.0) - 0.01)
210
+ total_w_saved += saved_w
211
+ total_e_saved += saved_e
212
+ total_c_saved += saved_c
 
 
 
 
 
 
 
 
 
 
 
 
 
213
 
214
+ rows += f"""
215
+ <tr style="border-bottom: 1px solid rgba(255,255,255,0.1); background: rgba(0,0,0,0.2);">
216
+ <td style="padding: 15px; font-style: italic;">"{item.get('query', '')}"</td>
217
+ <td style="padding: 15px; color: #fca5a5; line-height: 1.5;">πŸ’§ {item.get('water_ml', 0):.1f} mL<br>⚑ {item.get('energy_wh', 0):.2f} Wh<br>☁️ {item.get('co2_g', 0):.2f} g</td>
218
+ <td style="padding: 15px;"><span style='color: #34d399; font-weight: bold;'>{alt_name}</span></td>
219
+ <td style="padding: 15px; color: #60a5fa; font-weight: bold; line-height: 1.5;">πŸ’§ {saved_w:.1f} mL<br>⚑ {saved_e:.2f} Wh<br>☁️ {saved_c:.2f} g</td>
220
+ </tr>
221
+ """
222
+ confetti_elements = "".join([f'<div class="confetti-piece" style="left: {random.randint(0, 100)}%; background-color: hsl({random.randint(0, 360)}, 100%, 60%); animation-duration: {random.uniform(2.5, 5)}s; animation-delay: {random.uniform(0, 2)}s;"></div>' for _ in range(60)])
223
+
224
+ return f"""
225
+ <div class="endgame-wrapper">
226
+ {confetti_elements}
227
+ <div class="victory-dashboard">
228
+ <h1 class="victory-title">πŸŽ‰ PLANET SAVED! πŸŽ‰</h1>
229
+ <p style="text-align: center; font-size: 1.3em; color: #a7f3d0; margin-bottom: 30px;">Congratulations! You reached {state.get('points', 0)} points!</p>
230
+ <div class="victory-stats-row">
231
+ <div class="v-stat-box" style="border-top: 4px solid #34d399;">
232
+ <h4 style="color: #34d399;">Planetary Savings</h4>
233
+ <p style="color: #34d399; font-size: 1.3em; font-weight: bold; margin: 8px 0;">πŸ’§ {total_w_saved:.1f} mL Saved</p>
234
+ <p style="color: #facc15; font-size: 1.3em; font-weight: bold; margin: 8px 0;">⚑ {total_e_saved:.2f} Wh Saved</p>
235
+ <p style="color: #a8a29e; font-size: 1.3em; font-weight: bold; margin: 8px 0;">☁️ {total_c_saved:.2f} g Saved</p>
236
  </div>
237
+ <div class="v-stat-box" style="border-top: 4px solid #fca5a5;">
238
+ <h4 style="color: #fca5a5;">Total Wasted</h4>
239
+ <p style="color: #fca5a5; font-size: 1.1em; margin: 8px 0;">πŸ’§ {1.0 - state.get('water', 1.0):.3f} L</p>
240
+ <p style="color: #fca5a5; font-size: 1.1em; margin: 8px 0;">⚑ {state.get('energy', 0):.4f} kWh</p>
241
+ <p style="color: #fca5a5; font-size: 1.1em; margin: 8px 0;">☁️ {state.get('co2', 0):.2f} g</p>
 
 
 
242
  </div>
243
  </div>
244
+ <h3 style="margin-top: 40px; color: #38bdf8; font-size: 1.8em; text-align: center;">πŸ“Š AI Usage Audit Log</h3>
245
+ <div style="max-height: 500px; overflow-y: auto; background: rgba(15, 23, 42, 0.9); border-radius: 12px; border: 1px solid rgba(255,255,255,0.1); padding: 10px;">
246
+ <table style="width: 100%; text-align: left; border-collapse: collapse; font-size: 1.05em;">
247
+ <tr style="background: rgba(56, 189, 248, 0.1); border-bottom: 2px solid #38bdf8;">
248
+ <th style="padding: 15px; color: #e2e8f0;">User Query</th><th style="padding: 15px; color: #fca5a5;">LLM Cost</th><th style="padding: 15px; color: #34d399;">Alternative Selected</th><th style="padding: 15px; color: #60a5fa;">Resources Saved</th>
249
+ </tr>
250
+ {rows}
251
+ </table>
252
+ </div>
253
  </div>
254
+ </div>
255
+ """
 
256
 
257
  def generate_defeat_dashboard(state):
258
+ rows = ""
259
+ for item in state.get("history", []):
260
+ rows += f"""
261
+ <tr style="border-bottom: 1px solid rgba(255,255,255,0.1); background: rgba(0,0,0,0.2);">
262
+ <td style="padding: 15px; font-style: italic;">"{item.get('query', '')}"</td>
263
+ <td style="padding: 15px; color: #fca5a5; line-height: 1.5;">πŸ’§ {item.get('water_ml', 0):.1f} mL<br>⚑ {item.get('energy_wh', 0):.2f} Wh<br>☁️ {item.get('co2_g', 0):.2f} g</td>
264
+ </tr>
265
+ """
266
+ ash_elements = "".join([f'<div class="ash-piece" style="left: {random.randint(0, 100)}%; animation-duration: {random.uniform(3, 6)}s; animation-delay: {random.uniform(0, 2)}s;"></div>' for _ in range(60)])
267
+
268
+ return f"""
269
+ <div class="endgame-wrapper">
270
+ {ash_elements}
271
+ <div class="defeat-dashboard">
272
+ <h1 class="defeat-title">πŸ’€ DRIP EVAPORATED! πŸ’€</h1>
273
+ <p style="text-align: center; font-size: 1.3em; color: #fca5a5; margin-bottom: 30px;">You ran out of water before reaching 500 points.</p>
274
+ <div class="victory-stats-row">
275
+ <div class="v-stat-box" style="border-top: 4px solid #ef4444; background: rgba(239, 68, 68, 0.1);">
276
+ <h4 style="color: #ef4444;">Total Resources Wasted</h4>
277
+ <p style="color: #fca5a5; font-size: 1.3em; font-weight: bold; margin: 8px 0;">πŸ’§ 1.0 L (Tank Empty)</p>
278
+ <p style="color: #fca5a5; font-size: 1.3em; font-weight: bold; margin: 8px 0;">⚑ {state.get('energy', 0):.4f} kWh</p>
279
+ <p style="color: #fca5a5; font-size: 1.3em; font-weight: bold; margin: 8px 0;">☁️ {state.get('co2', 0):.2f} g</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
  </div>
281
+ <div class="v-stat-box" style="border-top: 4px solid #94a3b8;">
282
+ <h4 style="color: #94a3b8;">Final Score</h4>
283
+ <p style="color: white; font-size: 3.5em; font-weight: bold; margin: 10px 0;">{state.get('points', 0)}</p>
 
 
 
 
 
 
 
 
 
284
  </div>
285
  </div>
286
+ <h3 style="margin-top: 40px; color: #fca5a5; font-size: 1.8em; text-align: center;">πŸ”₯ Wasted Resources Log</h3>
287
+ <div style="max-height: 400px; overflow-y: auto; background: rgba(15, 23, 42, 0.9); border-radius: 12px; border: 1px solid rgba(239, 68, 68, 0.3); padding: 10px;">
288
+ <table style="width: 100%; text-align: left; border-collapse: collapse; font-size: 1.05em;">
289
+ <tr style="background: rgba(239, 68, 68, 0.15); border-bottom: 2px solid #ef4444;">
290
+ <th style="padding: 15px; color: #fca5a5;">User Query</th><th style="padding: 15px; color: #fca5a5;">Resources Drained</th>
291
+ </tr>
292
+ {rows}
293
+ </table>
294
+ </div>
295
  </div>
296
+ </div>
297
+ """
 
 
298
 
299
  # --- 3. EVENT HANDLERS ---
300
 
301
  def process_query(user_input, selected_model, state):
302
+ # CRITICAL FIX: If game is already over, return empty gr.updates so we don't accidentally hide the endgame screen
303
  if state["game_over"] or not user_input.strip():
304
+ return [state] + [gr.update()]*14
305
 
306
  result = classifier(user_input, CATEGORIES)
307
  category = result['labels'][0]
 
341
  audio_path = generate_audio(dialogue)
342
  feedback_text = f"<div class='feedback-box'>🧠 <strong>{category.upper()}</strong> Detected!<br><br><em>\"{dialogue}\"</em></div>"
343
 
344
+ # WIN CONDITION
345
  if state["points"] >= 500:
346
  state["game_over"] = True
347
  return (state, stats_ui, drip_ui, audio_path, impact_ui, gr.update(), gr.update(visible=False),
348
  gr.update(), gr.update(), gr.update(), gr.update(), gr.update(value=""),
349
  gr.update(visible=False), gr.update(visible=True), gr.update(value=generate_victory_dashboard(state)))
350
 
351
+ # LOSS CONDITION
352
+ elif state["water"] <= 0.001: # Using 0.001 to prevent floating point math errors
353
  state["game_over"] = True
354
  return (state, stats_ui, drip_ui, audio_path, impact_ui, gr.update(), gr.update(visible=False),
355
  gr.update(), gr.update(), gr.update(), gr.update(), gr.update(value=""),
356
  gr.update(visible=False), gr.update(visible=True), gr.update(value=generate_defeat_dashboard(state)))
357
 
358
+ # REGULAR GAMEPLAY RETURN
359
  return (state, stats_ui, drip_ui, audio_path, impact_ui, gr.update(value=feedback_text), gr.update(visible=True),
360
  gr.update(value=alt_choices[0], visible=True), gr.update(value=alt_choices[1], visible=True), gr.update(value=alt_choices[2], visible=True), gr.update(value=""), gr.update(value=""),
361
  gr.update(visible=True), gr.update(visible=False), gr.update())
362
 
363
  def select_alternative(choice_text, state):
364
+ # CRITICAL FIX: Empty gr.updates to prevent UI reset if accidentally clicked after game over
365
  if state["game_over"] or not state.get("current_best_alt"):
366
+ return [state] + [gr.update()]*6
367
 
368
  first_line = choice_text.split("\n")[0]
369
  clean_choice = first_line.split(" ", 1)[1].strip() if " " in first_line else first_line
 
379
 
380
  stats_ui = get_stats_html(state["water"], state["energy"], state["co2"], state["points"])
381
 
382
+ # WIN CONDITION FROM ALTERNATIVE CLICK
383
  if state["points"] >= 500:
384
  state["game_over"] = True
385
  return state, stats_ui, gr.update(), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), gr.update(value=generate_victory_dashboard(state))
 
430
  .alt-card:hover { background: linear-gradient(145deg, #064e3b, #065f46) !important; transform: translateY(-8px) !important; box-shadow: 0 12px 30px rgba(16, 185, 129, 0.3) !important; color: white !important; border-color: #34d399 !important;}
431
  .custom-dropdown { background: rgba(30, 41, 59, 0.8) !important; border: 1px solid #38bdf8 !important; border-radius: 12px !important; }
432
 
433
+ /* End Game Dashboards & Animations */
434
+ .endgame-wrapper { position: relative; width: 100%; min-height: 600px; overflow: hidden; border-radius: 24px; padding-top: 10px; }
 
435
  .victory-dashboard { background: linear-gradient(135deg, #0f172a, #1e293b); padding: 40px; border-radius: 24px; border: 2px solid #34d399; animation: pulseGlow 2s infinite; color: white; position: relative; z-index: 5; margin-top: 20px;}
436
  .victory-title { text-align: center; color: #34d399; font-size: 3.5em !important; text-shadow: 0 0 20px rgba(52, 211, 153, 0.6); margin-bottom: 5px; }
437
  .victory-stats-row { display: flex; gap: 20px; margin-top: 30px; }
438
  .v-stat-box { flex: 1; background: rgba(0,0,0,0.4); padding: 25px; border-radius: 16px; text-align: center; border: 1px solid rgba(52, 211, 153, 0.3); }
439
  .v-stat-box h4 { color: #94a3b8; font-size: 0.9em; text-transform: uppercase; letter-spacing: 1px; margin: 0 0 10px 0; }
440
 
441
+ @keyframes pulseGlow { 0% { box-shadow: 0 0 20px rgba(52, 211, 153, 0.4); } 50% { box-shadow: 0 0 50px rgba(52, 211, 153, 0.8); } 100% { box-shadow: 0 0 20px rgba(52, 211, 153, 0.4); } }
442
  .confetti-piece { position: absolute; width: 10px; height: 15px; top: -20px; opacity: 0; animation: fall linear forwards infinite; z-index: 10; border-radius: 2px;}
443
+ @keyframes fall { 0% { transform: translateY(-20px) rotate(0deg); opacity: 1; } 100% { transform: translateY(1000px) rotate(720deg); opacity: 1; } }
 
 
 
444
 
 
 
445
  .defeat-dashboard { background: linear-gradient(135deg, #2b1010, #450a0a); padding: 40px; border-radius: 24px; border: 2px solid #ef4444; animation: pulseRed 2s infinite; color: white; position: relative; z-index: 5; margin-top: 20px; }
446
  .defeat-title { text-align: center; color: #ef4444; font-size: 3.5em !important; text-shadow: 0 0 20px rgba(239, 68, 68, 0.8); margin-bottom: 5px; }
447
+ @keyframes pulseRed { 0% { box-shadow: 0 0 20px rgba(239, 68, 68, 0.4); } 50% { box-shadow: 0 0 60px rgba(239, 68, 68, 0.8); } 100% { box-shadow: 0 0 20px rgba(239, 68, 68, 0.4); } }
448
  .ash-piece { position: absolute; width: 8px; height: 8px; background-color: rgba(156, 163, 175, 0.6); border-radius: 50%; opacity: 0; animation: floatAsh linear forwards infinite; z-index: 10; filter: blur(1px); }
449
+ @keyframes floatAsh { 0% { transform: translateY(600px) scale(1); opacity: 0; } 20% { opacity: 0.8; } 100% { transform: translateY(-100px) scale(2); opacity: 0; } }
 
 
 
 
450
  """
451
 
452
  with gr.Blocks(css=custom_css, title="EcoQueryQuest") as demo:
 
453
  game_state = gr.State({
454
  "water": 1.0, "energy": 0.0, "co2": 0.0, "points": 0, "queries": 0,
455
  "history": [], "game_over": False, "current_best_alt": None, "current_shuffled_alts": []
 
458
  gr.Markdown("<h1>🌍 EcoQueryQuest</h1>")
459
  gr.Markdown("<div class='subtitle'>Select a model, type a query, and watch Drip react. Reach 500 points to win!</div>")
460
 
 
461
  stats_html = gr.HTML(get_stats_html(1.0, 0.0, 0.0, 0))
462
 
463
  with gr.Column(visible=True) as main_game_ui:
464
  with gr.Row():
465
  with gr.Column(scale=1, elem_classes=["drip-pod"]):
 
466
  drip_html = gr.HTML(get_drip_visuals(1.0))
467
  drip_audio = gr.Audio(label="Drip's Voice", autoplay=True, interactive=False, elem_classes=["hidden-audio"])
468
  drip_feedback = gr.HTML("<div class='feedback-box'>Waiting for your first query...</div>")
 
485
  with gr.Column(visible=False) as victory_ui:
486
  victory_display = gr.HTML()
487
 
488
+ # Pressing Enter in the Textbox triggers the same function
489
+ user_input.submit(
490
+ fn=process_query,
491
+ inputs=[user_input, model_selector, game_state],
492
+ outputs=[game_state, stats_html, drip_html, drip_audio, impact_display, drip_feedback, alternatives_group, alt_btn_1, alt_btn_2, alt_btn_3, alt_feedback, user_input, main_game_ui, victory_ui, victory_display]
493
+ )
494
+
495
  submit_btn.click(
496
  fn=process_query,
497
  inputs=[user_input, model_selector, game_state],