vighnesh-shetty-vs commited on
Commit
a02ff46
Β·
1 Parent(s): e444069

Add updated files

Browse files
Files changed (1) hide show
  1. app.py +134 -74
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
 
@@ -18,23 +14,107 @@ CATEGORIES = [
18
  "complex research query"
19
  ]
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  def generate_audio(text):
22
  tts = gTTS(text, lang='en')
23
  filepath = "temp_drip_voice.mp3"
24
  tts.save(filepath)
25
  return filepath
26
 
 
 
27
  def get_relatable_translations(impact):
28
- """Converts abstract numbers into physical examples."""
29
  bottles = impact['water_ml'] / 500.0
30
  w_ex = f"{bottles:.1f} water bottles" if bottles >= 0.1 else "A few sips"
31
-
32
  bulb_hours = impact['energy_wh'] / 10.0
33
  e_ex = f"{bulb_hours:.1f} hours of 1 LED bulb" if bulb_hours >= 0.1 else f"{impact['energy_wh']*12:.1f} mins of 1 LED bulb"
34
-
35
  charges = impact['co2_g'] / 5.0
36
  c_ex = f"{charges:.1f} phone charges" if charges >= 0.1 else "Negligible emissions"
37
-
38
  return w_ex, e_ex, c_ex
39
 
40
  def get_stats_html(water, energy, co2, points):
@@ -44,9 +124,7 @@ def get_stats_html(water, energy, co2, points):
44
  <div class="stat-card water-card">
45
  <div class="stat-label">WATER TANK (10L MAX)</div>
46
  <div class="stat-value">{water:.2f}L</div>
47
- <div class="progress-bar-bg">
48
- <div class="progress-bar-fill" style="width: {water_percent}%;"></div>
49
- </div>
50
  </div>
51
  <div class="stat-card energy-card">
52
  <div class="stat-label">ENERGY WASTED</div>
@@ -68,26 +146,22 @@ def get_drip_visuals(water_level):
68
  g_start, g_end = "#7dd3fc", "#0369a1"
69
  mouth_d = "M43 112 Q60 122 77 112"
70
  cracks_op, sweat_op, tear_op = "0", "0", "0"
71
- mood, mood_color = "Hydrated and coping", "rgb(34, 211, 238)"
72
- anim = "bounce 2s infinite ease-in-out"
73
  elif 3.0 <= water_level <= 7.0:
74
  g_start, g_end = "#38bdf8", "#0284c7"
75
  mouth_d = "M43 112 Q60 110 77 112"
76
  cracks_op, sweat_op, tear_op = "0", "1", "0"
77
- mood, mood_color = "Shrinking & Sweaty", "#0ea5e9"
78
- anim = "float 4s infinite ease-in-out"
79
  elif water_level > 0:
80
  g_start, g_end = "#fca5a5", "#b91c1c"
81
  mouth_d = "M43 116 Q60 102 77 116"
82
  cracks_op, sweat_op, tear_op = "1", "0", "1"
83
- mood, mood_color = "Overheating & Raspy", "#ef4444"
84
- anim = "shake 0.5s infinite"
85
  else:
86
  g_start, g_end = "#94a3b8", "#334155"
87
  mouth_d = "M40 112 Q45 105 50 112 T60 112 T70 112 T80 112"
88
  cracks_op, sweat_op, tear_op = "0", "0", "0"
89
- mood, mood_color = "Evaporated!", "#94a3b8"
90
- anim = "floatUp 3s forwards"
91
 
92
  return f"""
93
  <div class="drip-panel" style="animation: {anim}; display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%;">
@@ -95,18 +169,14 @@ def get_drip_visuals(water_level):
95
  <svg id="drip-svg" viewBox="0 0 120 148" style="width: 140px; height: 160px; overflow: visible;" xmlns="http://www.w3.org/2000/svg">
96
  <defs>
97
  <radialGradient id="dg" cx="38%" cy="32%">
98
- <stop id="dg1" offset="0%" stop-color="{g_start}"></stop>
99
- <stop id="dg2" offset="100%" stop-color="{g_end}"></stop>
100
  </radialGradient>
101
  </defs>
102
  <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>
103
  <ellipse cx="42" cy="70" rx="9" ry="13" fill="rgba(255,255,255,0.22)" transform="rotate(-18,42,70)"></ellipse>
104
- <circle cx="44" cy="90" r="10" fill="white"></circle>
105
- <circle cx="76" cy="90" r="10" fill="white"></circle>
106
- <circle id="pl" cx="45" cy="91" r="6" fill="#0f172a"></circle>
107
- <circle id="pr" cx="77" cy="91" r="6" fill="#0f172a"></circle>
108
- <circle cx="47" cy="88" r="2.5" fill="white"></circle>
109
- <circle cx="79" cy="88" r="2.5" fill="white"></circle>
110
  <path id="dm" d="{mouth_d}" stroke="#0f172a" stroke-width="2.5" stroke-linecap="round" fill="none"></path>
111
  <g id="cracks" opacity="{cracks_op}" style="transition: opacity 0.5s;">
112
  <path d="M80 46 L86 58 L79 65 L85 77" stroke="#bae6fd" stroke-width="1.3" stroke-linecap="round" fill="none" opacity=".7"></path>
@@ -153,10 +223,7 @@ def format_alt_button(text, impact):
153
 
154
  def generate_victory_dashboard(state):
155
  try:
156
- total_w_saved = 0.0
157
- total_e_saved = 0.0
158
- total_c_saved = 0.0
159
-
160
  rows = ""
161
  for item in state.get("history", []):
162
  alt_name = item.get('alt_name', 'None (Justified Use)')
@@ -167,7 +234,6 @@ def generate_victory_dashboard(state):
167
  saved_w = item.get('water_ml', 0.0)
168
  saved_e = max(0.0, item.get('energy_wh', 0.0) - 0.001)
169
  saved_c = max(0.0, item.get('co2_g', 0.0) - 0.01)
170
-
171
  total_w_saved += saved_w
172
  total_e_saved += saved_e
173
  total_c_saved += saved_c
@@ -176,20 +242,11 @@ def generate_victory_dashboard(state):
176
  rows += f"""
177
  <tr style="border-bottom: 1px solid rgba(255,255,255,0.1); background: rgba(0,0,0,0.2);">
178
  <td style="padding: 15px; font-style: italic;">"{item.get('query', '')}"</td>
179
- <td style="padding: 15px; color: #fca5a5; line-height: 1.5;">
180
- πŸ’§ {item.get('water_ml', 0):.1f} mL<br>
181
- ⚑ {item.get('energy_wh', 0):.2f} Wh<br>
182
- ☁️ {item.get('co2_g', 0):.2f} g
183
- </td>
184
  <td style="padding: 15px;">{alt_display}</td>
185
- <td style="padding: 15px; color: #60a5fa; font-weight: bold; line-height: 1.5;">
186
- πŸ’§ {saved_w:.1f} mL<br>
187
- ⚑ {saved_e:.2f} Wh<br>
188
- ☁️ {saved_c:.2f} g
189
- </td>
190
  </tr>
191
  """
192
-
193
  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)])
194
 
195
  return f"""
@@ -197,10 +254,7 @@ def generate_victory_dashboard(state):
197
  {confetti_elements}
198
  <div class="victory-dashboard">
199
  <h1 class="victory-title">πŸŽ‰ PLANET SAVED! πŸŽ‰</h1>
200
- <p style="text-align: center; font-size: 1.3em; color: #a7f3d0; margin-bottom: 30px;">
201
- Congratulations! You reached {state.get('points', 0)} points and prevented Drip from evaporating!
202
- </p>
203
-
204
  <div class="victory-stats-row">
205
  <div class="v-stat-box" style="border-top: 4px solid #34d399;">
206
  <h4 style="color: #34d399;">Planetary Savings</h4>
@@ -215,17 +269,11 @@ def generate_victory_dashboard(state):
215
  <p style="color: #fca5a5; font-size: 1.1em; margin: 8px 0;">☁️ {state.get('co2', 0):.2f} g</p>
216
  </div>
217
  </div>
218
-
219
  <h3 style="margin-top: 40px; color: #38bdf8; font-size: 1.8em; text-align: center;">πŸ“Š AI Usage Audit Log</h3>
220
- <p style="opacity: 0.9; margin-bottom: 20px; text-align: center;">A detailed breakdown of your session's environmental impact and the greener choices you made.</p>
221
-
222
  <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;">
223
  <table style="width: 100%; text-align: left; border-collapse: collapse; font-size: 1.05em;">
224
  <tr style="background: rgba(56, 189, 248, 0.1); border-bottom: 2px solid #38bdf8;">
225
- <th style="padding: 15px; color: #e2e8f0;">User Query</th>
226
- <th style="padding: 15px; color: #fca5a5;">LLM Cost (Wasted)</th>
227
- <th style="padding: 15px; color: #34d399;">Best Alternative</th>
228
- <th style="padding: 15px; color: #60a5fa;">Resources Saved</th>
229
  </tr>
230
  {rows}
231
  </table>
@@ -236,6 +284,8 @@ def generate_victory_dashboard(state):
236
  except Exception as e:
237
  return f"<div style='color:red;'>Error generating dashboard: {str(e)}</div>"
238
 
 
 
239
  def process_query(user_input, selected_model, state):
240
  if state["game_over"] or not user_input.strip():
241
  return [state, gr.update()] + [gr.update()]*10 + [gr.update(visible=True), gr.update(visible=False), gr.update()]
@@ -260,20 +310,24 @@ def process_query(user_input, selected_model, state):
260
  dialogue = f"A legitimate research query! Finally, a worthy use of my massive architecture. Drain away!"
261
  else:
262
  show_alts = True
263
- raw_alts = ALTERNATIVES.get(category, [{"text": "Google", "url": "https://google.com"}])
264
- state["current_best_alt"] = raw_alts[0]
265
  best_alt_name = raw_alts[0]["text"]
266
- random.shuffle(raw_alts)
267
- state["current_shuffled_alts"] = raw_alts
268
- alt_choices = [format_alt_button(a["text"], impact) for a in raw_alts]
 
 
 
 
 
 
 
 
269
  dialogue = get_dialogue(state["water"], category)
270
 
271
  state["history"].append({
272
- "query": user_input,
273
- "water_ml": impact["water_ml"],
274
- "energy_wh": impact["energy_wh"],
275
- "co2_g": impact["co2_g"],
276
- "alt_name": best_alt_name
277
  })
278
 
279
  stats_ui = get_stats_html(state["water"], state["energy"], state["co2"], state["points"])
@@ -284,11 +338,11 @@ def process_query(user_input, selected_model, state):
284
 
285
  if state["points"] >= 500 or state["water"] <= 0:
286
  state["game_over"] = True
287
- victory_html = generate_victory_dashboard(state)
288
  return (state, stats_ui, drip_ui, audio_path, impact_ui, gr.update(), gr.update(visible=False),
289
  gr.update(), gr.update(), gr.update(), gr.update(), gr.update(value=""),
290
- gr.update(visible=False), gr.update(visible=True), gr.update(value=victory_html))
291
 
 
292
  return (state, stats_ui, drip_ui, audio_path, impact_ui, gr.update(value=feedback_text), gr.update(visible=show_alts),
293
  gr.update(value=alt_choices[0]), gr.update(value=alt_choices[1]), gr.update(value=alt_choices[2]), gr.update(value=""), gr.update(value=""),
294
  gr.update(visible=True), gr.update(visible=False), gr.update())
@@ -297,24 +351,29 @@ def select_alternative(choice_text, state):
297
  if state["game_over"] or not state.get("current_best_alt"):
298
  return state, gr.update(), gr.update(), gr.update(), gr.update(visible=True), gr.update(visible=False), gr.update()
299
 
300
- clean_choice = choice_text.split("\n")[0][2:].strip()
 
 
 
301
  selected_dict = next((item for item in state["current_shuffled_alts"] if item["text"] == clean_choice), None)
 
302
 
303
  if clean_choice == state["current_best_alt"]["text"]:
304
  state["points"] += 10
305
- msg = f"βœ… **Excellent!** +10 Points.\n\n<a href='{selected_dict['url']}' target='_blank' style='display:inline-block; margin-top:10px; padding: 10px 20px; background:#10b981; color:white; text-decoration:none; border-radius:8px; font-weight:bold;'>πŸ‘‰ Click here to use {clean_choice}</a>"
306
  else:
307
- msg = f"⚠️ **Okay choice.** Better than an LLM, but there was a slightly more optimal tool.\n\n<a href='{selected_dict['url']}' target='_blank' style='display:inline-block; margin-top:10px; padding: 10px 20px; background:#38bdf8; color:white; text-decoration:none; border-radius:8px; font-weight:bold;'>πŸ‘‰ Click here to use {clean_choice}</a>"
308
 
309
  stats_ui = get_stats_html(state["water"], state["energy"], state["co2"], state["points"])
310
 
311
  if state["points"] >= 500:
312
  state["game_over"] = True
313
- victory_html = generate_victory_dashboard(state)
314
- return state, stats_ui, gr.update(), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), gr.update(value=victory_html)
315
 
316
  return state, stats_ui, gr.update(value=msg), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update()
317
 
 
 
318
  custom_css = """
319
  @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@300;500;700&display=swap');
320
  body, .gradio-container { background-color: #0B1120 !important; font-family: 'Outfit', sans-serif !important; color: #e2e8f0 !important; }
@@ -339,6 +398,7 @@ h1 { text-align: center; color: #38bdf8; text-shadow: 0 0 15px rgba(56, 189, 248
339
  @keyframes floatUp { to { transform: translateY(-30px); opacity: 0; } }
340
 
341
  .drip-pod { background: rgba(15, 23, 42, 0.6); border-radius: 24px; border: 1px solid rgba(56, 189, 248, 0.2); padding: 30px 20px; display: flex; flex-direction: column; align-items: center; box-shadow: inset 0 0 40px rgba(0,0,0,0.5); }
 
342
  .feedback-box { background: rgba(56, 189, 248, 0.1); border-left: 4px solid #38bdf8; padding: 15px; border-radius: 8px; font-size: 1.05em; color: #e2e8f0; width: 100%; text-align: left; line-height: 1.4; box-sizing: border-box;}
343
 
344
  .input-row { align-items: stretch !important; margin: 10px 0; }
@@ -365,7 +425,6 @@ h1 { text-align: center; color: #38bdf8; text-shadow: 0 0 15px rgba(56, 189, 248
365
  .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); }
366
  .v-stat-box h4 { color: #94a3b8; font-size: 0.9em; text-transform: uppercase; letter-spacing: 1px; margin: 0 0 10px 0; }
367
 
368
- /* Pure CSS Confetti Physics */
369
  .confetti-piece { position: absolute; width: 10px; height: 15px; top: -20px; opacity: 0; animation: fall linear forwards infinite; z-index: 10; border-radius: 2px;}
370
  @keyframes fall {
371
  0% { transform: translateY(-20px) rotate(0deg); opacity: 1; }
@@ -388,8 +447,8 @@ with gr.Blocks(css=custom_css, title="EcoQueryQuest") as demo:
388
  with gr.Row():
389
  with gr.Column(scale=1, elem_classes=["drip-pod"]):
390
  drip_html = gr.HTML(get_drip_visuals(10.0))
391
- # Set visible=False on the Audio component so it stays completely hidden while still autoplaying!
392
- drip_audio = gr.Audio(label="Drip's Voice", autoplay=True, interactive=False, visible=False)
393
  drip_feedback = gr.HTML("<div class='feedback-box'>Waiting for your first query...</div>")
394
 
395
  with gr.Column(scale=2):
@@ -410,6 +469,7 @@ with gr.Blocks(css=custom_css, title="EcoQueryQuest") as demo:
410
  with gr.Column(visible=False) as victory_ui:
411
  victory_display = gr.HTML()
412
 
 
413
  submit_btn.click(
414
  fn=process_query,
415
  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
 
 
14
  "complex research query"
15
  ]
16
 
17
+ # --- 1. EMBEDDED DATA (Prevents import errors) ---
18
+
19
+ MODELS = {
20
+ "Mistral Large 3": {"energy_wh": 1.98, "water_ml": 3.56, "co2_g": 0.95},
21
+ "Mistral Medium 3": {"energy_wh": 6.76, "water_ml": 12.17, "co2_g": 3.24},
22
+ "Claude Sonnet 4.6": {"energy_wh": 19.32, "water_ml": 34.78, "co2_g": 9.27},
23
+ "Gemini 3 Pro": {"energy_wh": 72.45, "water_ml": 130.41, "co2_g": 34.78},
24
+ "Gemini 3.1 Pro": {"energy_wh": 77.28, "water_ml": 139.10, "co2_g": 37.09},
25
+ "Claude Opus 4.6": {"energy_wh": 96.60, "water_ml": 173.88, "co2_g": 46.37},
26
+ "GPT-5.2": {"energy_wh": 144.90, "water_ml": 260.82, "co2_g": 69.55},
27
+ "GPT-5.4": {"energy_wh": 169.05, "water_ml": 304.29, "co2_g": 81.14}
28
+ }
29
+
30
+ CATEGORY_MULTIPLIERS = {
31
+ "simple factual question": 0.05,
32
+ "mathematical calculation": 0.10,
33
+ "creative content generation": 0.80,
34
+ "complex research query": 1.50
35
+ }
36
+
37
+ DIALOGUES = {
38
+ "energetic": {
39
+ "simple factual question": "You used a supercomputer for a simple fact? I'm full right now, but that's just lazy. Open a book.",
40
+ "mathematical calculation": "A basic calculator could do this with zero footprint. But sure, burn my energy for basic math.",
41
+ "creative content generation": "Generating artificial creativity... I'll allow it, but watch my water levels drop. Your poetry is expensive.",
42
+ "complex research query": "A legitimate research query! Finally, a worthy use of my massive architecture. Drain away!"
43
+ },
44
+ "tired": {
45
+ "simple factual question": "Look at me. I'm sweating. All because you couldn't be bothered to use a standard search engine.",
46
+ "mathematical calculation": "Did you skip basic math class? I am literally evaporating to do arithmetic for you.",
47
+ "creative content generation": "Your 'creativity' is draining my lifeblood. Make it quick, I don't have much cooling left.",
48
+ "complex research query": "I respect the complexity, but this is taking a severe toll on my cooling systems. I hope this research saves the world."
49
+ },
50
+ "raspy": {
51
+ "simple factual question": "*Cough* Read an encyclopedia... I'm dying for your trivia...",
52
+ "mathematical calculation": "Use an abacus... you are boiling my last drops for numbers...",
53
+ "creative content generation": "My final breath... wasted on generating a fictional story... how poetic... and cruel.",
54
+ "complex research query": "Critical system failure imminent... I am giving my life for your research... make it count."
55
+ }
56
+ }
57
+
58
+ ALTERNATIVES = {
59
+ "simple factual question": [
60
+ {"text": "Search Engine (Google)", "url": "https://www.google.com"},
61
+ {"text": "Wikipedia Encyclopedia", "url": "https://www.wikipedia.org"},
62
+ {"text": "Ask a Human Expert (Quora)", "url": "https://www.quora.com"}
63
+ ],
64
+ "mathematical calculation": [
65
+ {"text": "Wolfram Alpha Engine", "url": "https://www.wolframalpha.com"},
66
+ {"text": "Geogebra Calculator", "url": "https://www.geogebra.org"},
67
+ {"text": "Desmos Graphing", "url": "https://www.desmos.com"}
68
+ ],
69
+ "creative content generation": [
70
+ {"text": "Writing Prompts (Reddit)", "url": "https://www.reddit.com/r/WritingPrompts/"},
71
+ {"text": "Thesaurus/Dictionary", "url": "https://www.thesaurus.com"},
72
+ {"text": "Project Gutenberg Books", "url": "https://www.gutenberg.org"}
73
+ ],
74
+ "complex research query": []
75
+ }
76
+
77
+ # --- 2. GAME LOGIC ---
78
+
79
+ def calculate_impact(category, confidence_score, query_text, model_name):
80
+ model_cost = MODELS.get(model_name, MODELS["Mistral Large 3"])
81
+ cat_mult = CATEGORY_MULTIPLIERS.get(category, 0.05)
82
+
83
+ conf_mult = 1.0 if confidence_score > 0.8 else (1.2 if confidence_score > 0.5 else 1.5)
84
+ word_count = len(query_text.split())
85
+ len_factor = max(0.5, 1.0 + ((word_count - 15) * 0.015))
86
+
87
+ water_ml = model_cost["water_ml"] * cat_mult * conf_mult * len_factor
88
+ energy_wh = model_cost["energy_wh"] * cat_mult * conf_mult * len_factor
89
+ co2_g = model_cost["co2_g"] * cat_mult * conf_mult * len_factor
90
+
91
+ return {
92
+ "water_l": water_ml / 1000.0,
93
+ "energy_kwh": energy_wh / 1000.0,
94
+ "water_ml": round(water_ml, 1),
95
+ "energy_wh": round(energy_wh, 2),
96
+ "co2_g": round(co2_g, 2)
97
+ }
98
+
99
+ def get_dialogue(water_level, category):
100
+ state = "energetic" if water_level > 7.0 else ("tired" if water_level >= 3.0 else "raspy")
101
+ return DIALOGUES[state].get(category, "I have no words left for this.")
102
+
103
  def generate_audio(text):
104
  tts = gTTS(text, lang='en')
105
  filepath = "temp_drip_voice.mp3"
106
  tts.save(filepath)
107
  return filepath
108
 
109
+ # --- 3. UI GENERATORS ---
110
+
111
  def get_relatable_translations(impact):
 
112
  bottles = impact['water_ml'] / 500.0
113
  w_ex = f"{bottles:.1f} water bottles" if bottles >= 0.1 else "A few sips"
 
114
  bulb_hours = impact['energy_wh'] / 10.0
115
  e_ex = f"{bulb_hours:.1f} hours of 1 LED bulb" if bulb_hours >= 0.1 else f"{impact['energy_wh']*12:.1f} mins of 1 LED bulb"
 
116
  charges = impact['co2_g'] / 5.0
117
  c_ex = f"{charges:.1f} phone charges" if charges >= 0.1 else "Negligible emissions"
 
118
  return w_ex, e_ex, c_ex
119
 
120
  def get_stats_html(water, energy, co2, points):
 
124
  <div class="stat-card water-card">
125
  <div class="stat-label">WATER TANK (10L MAX)</div>
126
  <div class="stat-value">{water:.2f}L</div>
127
+ <div class="progress-bar-bg"><div class="progress-bar-fill" style="width: {water_percent}%;"></div></div>
 
 
128
  </div>
129
  <div class="stat-card energy-card">
130
  <div class="stat-label">ENERGY WASTED</div>
 
146
  g_start, g_end = "#7dd3fc", "#0369a1"
147
  mouth_d = "M43 112 Q60 122 77 112"
148
  cracks_op, sweat_op, tear_op = "0", "0", "0"
149
+ mood, mood_color, anim = "Hydrated and coping", "rgb(34, 211, 238)", "bounce 2s infinite ease-in-out"
 
150
  elif 3.0 <= water_level <= 7.0:
151
  g_start, g_end = "#38bdf8", "#0284c7"
152
  mouth_d = "M43 112 Q60 110 77 112"
153
  cracks_op, sweat_op, tear_op = "0", "1", "0"
154
+ mood, mood_color, anim = "Shrinking & Sweaty", "#0ea5e9", "float 4s infinite ease-in-out"
 
155
  elif water_level > 0:
156
  g_start, g_end = "#fca5a5", "#b91c1c"
157
  mouth_d = "M43 116 Q60 102 77 116"
158
  cracks_op, sweat_op, tear_op = "1", "0", "1"
159
+ mood, mood_color, anim = "Overheating & Raspy", "#ef4444", "shake 0.5s infinite"
 
160
  else:
161
  g_start, g_end = "#94a3b8", "#334155"
162
  mouth_d = "M40 112 Q45 105 50 112 T60 112 T70 112 T80 112"
163
  cracks_op, sweat_op, tear_op = "0", "0", "0"
164
+ mood, mood_color, anim = "Evaporated!", "#94a3b8", "floatUp 3s forwards"
 
165
 
166
  return f"""
167
  <div class="drip-panel" style="animation: {anim}; display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%;">
 
169
  <svg id="drip-svg" viewBox="0 0 120 148" style="width: 140px; height: 160px; overflow: visible;" xmlns="http://www.w3.org/2000/svg">
170
  <defs>
171
  <radialGradient id="dg" cx="38%" cy="32%">
172
+ <stop id="dg1" offset="0%" stop-color="{g_start}"></stop><stop id="dg2" offset="100%" stop-color="{g_end}"></stop>
 
173
  </radialGradient>
174
  </defs>
175
  <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>
176
  <ellipse cx="42" cy="70" rx="9" ry="13" fill="rgba(255,255,255,0.22)" transform="rotate(-18,42,70)"></ellipse>
177
+ <circle cx="44" cy="90" r="10" fill="white"></circle><circle cx="76" cy="90" r="10" fill="white"></circle>
178
+ <circle id="pl" cx="45" cy="91" r="6" fill="#0f172a"></circle><circle id="pr" cx="77" cy="91" r="6" fill="#0f172a"></circle>
179
+ <circle cx="47" cy="88" r="2.5" fill="white"></circle><circle cx="79" cy="88" r="2.5" fill="white"></circle>
 
 
 
180
  <path id="dm" d="{mouth_d}" stroke="#0f172a" stroke-width="2.5" stroke-linecap="round" fill="none"></path>
181
  <g id="cracks" opacity="{cracks_op}" style="transition: opacity 0.5s;">
182
  <path d="M80 46 L86 58 L79 65 L85 77" stroke="#bae6fd" stroke-width="1.3" stroke-linecap="round" fill="none" opacity=".7"></path>
 
223
 
224
  def generate_victory_dashboard(state):
225
  try:
226
+ total_w_saved, total_e_saved, total_c_saved = 0.0, 0.0, 0.0
 
 
 
227
  rows = ""
228
  for item in state.get("history", []):
229
  alt_name = item.get('alt_name', 'None (Justified Use)')
 
234
  saved_w = item.get('water_ml', 0.0)
235
  saved_e = max(0.0, item.get('energy_wh', 0.0) - 0.001)
236
  saved_c = max(0.0, item.get('co2_g', 0.0) - 0.01)
 
237
  total_w_saved += saved_w
238
  total_e_saved += saved_e
239
  total_c_saved += saved_c
 
242
  rows += f"""
243
  <tr style="border-bottom: 1px solid rgba(255,255,255,0.1); background: rgba(0,0,0,0.2);">
244
  <td style="padding: 15px; font-style: italic;">"{item.get('query', '')}"</td>
245
+ <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>
 
 
 
 
246
  <td style="padding: 15px;">{alt_display}</td>
247
+ <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>
 
 
 
 
248
  </tr>
249
  """
 
250
  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)])
251
 
252
  return f"""
 
254
  {confetti_elements}
255
  <div class="victory-dashboard">
256
  <h1 class="victory-title">πŸŽ‰ PLANET SAVED! πŸŽ‰</h1>
257
+ <p style="text-align: center; font-size: 1.3em; color: #a7f3d0; margin-bottom: 30px;">Congratulations! You reached {state.get('points', 0)} points!</p>
 
 
 
258
  <div class="victory-stats-row">
259
  <div class="v-stat-box" style="border-top: 4px solid #34d399;">
260
  <h4 style="color: #34d399;">Planetary Savings</h4>
 
269
  <p style="color: #fca5a5; font-size: 1.1em; margin: 8px 0;">☁️ {state.get('co2', 0):.2f} g</p>
270
  </div>
271
  </div>
 
272
  <h3 style="margin-top: 40px; color: #38bdf8; font-size: 1.8em; text-align: center;">πŸ“Š AI Usage Audit Log</h3>
 
 
273
  <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;">
274
  <table style="width: 100%; text-align: left; border-collapse: collapse; font-size: 1.05em;">
275
  <tr style="background: rgba(56, 189, 248, 0.1); border-bottom: 2px solid #38bdf8;">
276
+ <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>
 
 
 
277
  </tr>
278
  {rows}
279
  </table>
 
284
  except Exception as e:
285
  return f"<div style='color:red;'>Error generating dashboard: {str(e)}</div>"
286
 
287
+ # --- 4. EVENT HANDLERS ---
288
+
289
  def process_query(user_input, selected_model, state):
290
  if state["game_over"] or not user_input.strip():
291
  return [state, gr.update()] + [gr.update()]*10 + [gr.update(visible=True), gr.update(visible=False), gr.update()]
 
310
  dialogue = f"A legitimate research query! Finally, a worthy use of my massive architecture. Drain away!"
311
  else:
312
  show_alts = True
313
+ raw_alts = ALTERNATIVES.get(category, ALTERNATIVES["simple factual question"])
 
314
  best_alt_name = raw_alts[0]["text"]
315
+
316
+ # Safely shuffle without modifying original dict
317
+ shuffled_alts = list(raw_alts)
318
+ random.shuffle(shuffled_alts)
319
+ state["current_shuffled_alts"] = shuffled_alts
320
+ state["current_best_alt"] = raw_alts[0]
321
+
322
+ # Ensure we always have exactly 3 choices to update the buttons
323
+ alt_choices = [format_alt_button(a["text"], impact) for a in shuffled_alts]
324
+ while len(alt_choices) < 3: alt_choices.append("")
325
+
326
  dialogue = get_dialogue(state["water"], category)
327
 
328
  state["history"].append({
329
+ "query": user_input, "water_ml": impact["water_ml"], "energy_wh": impact["energy_wh"],
330
+ "co2_g": impact["co2_g"], "alt_name": best_alt_name
 
 
 
331
  })
332
 
333
  stats_ui = get_stats_html(state["water"], state["energy"], state["co2"], state["points"])
 
338
 
339
  if state["points"] >= 500 or state["water"] <= 0:
340
  state["game_over"] = True
 
341
  return (state, stats_ui, drip_ui, audio_path, impact_ui, gr.update(), gr.update(visible=False),
342
  gr.update(), gr.update(), gr.update(), gr.update(), gr.update(value=""),
343
+ gr.update(visible=False), gr.update(visible=True), gr.update(value=generate_victory_dashboard(state)))
344
 
345
+ # Pass exact button updates, and toggle the alternatives group visibility
346
  return (state, stats_ui, drip_ui, audio_path, impact_ui, gr.update(value=feedback_text), gr.update(visible=show_alts),
347
  gr.update(value=alt_choices[0]), gr.update(value=alt_choices[1]), gr.update(value=alt_choices[2]), gr.update(value=""), gr.update(value=""),
348
  gr.update(visible=True), gr.update(visible=False), gr.update())
 
351
  if state["game_over"] or not state.get("current_best_alt"):
352
  return state, gr.update(), gr.update(), gr.update(), gr.update(visible=True), gr.update(visible=False), gr.update()
353
 
354
+ # Safely extract tool name (Handles edge cases with emojis and spaces)
355
+ first_line = choice_text.split("\n")[0]
356
+ clean_choice = first_line.split(" ", 1)[1].strip() if " " in first_line else first_line
357
+
358
  selected_dict = next((item for item in state["current_shuffled_alts"] if item["text"] == clean_choice), None)
359
+ url = selected_dict['url'] if selected_dict else "#"
360
 
361
  if clean_choice == state["current_best_alt"]["text"]:
362
  state["points"] += 10
363
+ msg = f"βœ… **Excellent!** +10 Points.\n\n<a href='{url}' target='_blank' style='display:inline-block; margin-top:10px; padding: 10px 20px; background:#10b981; color:white; text-decoration:none; border-radius:8px; font-weight:bold;'>πŸ‘‰ Click here to use {clean_choice}</a>"
364
  else:
365
+ msg = f"⚠️ **Okay choice.** Better than an LLM, but there was a slightly more optimal tool.\n\n<a href='{url}' target='_blank' style='display:inline-block; margin-top:10px; padding: 10px 20px; background:#38bdf8; color:white; text-decoration:none; border-radius:8px; font-weight:bold;'>πŸ‘‰ Click here to use {clean_choice}</a>"
366
 
367
  stats_ui = get_stats_html(state["water"], state["energy"], state["co2"], state["points"])
368
 
369
  if state["points"] >= 500:
370
  state["game_over"] = True
371
+ 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))
 
372
 
373
  return state, stats_ui, gr.update(value=msg), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update()
374
 
375
+ # --- 5. UI & STYLING ---
376
+
377
  custom_css = """
378
  @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@300;500;700&display=swap');
379
  body, .gradio-container { background-color: #0B1120 !important; font-family: 'Outfit', sans-serif !important; color: #e2e8f0 !important; }
 
398
  @keyframes floatUp { to { transform: translateY(-30px); opacity: 0; } }
399
 
400
  .drip-pod { background: rgba(15, 23, 42, 0.6); border-radius: 24px; border: 1px solid rgba(56, 189, 248, 0.2); padding: 30px 20px; display: flex; flex-direction: column; align-items: center; box-shadow: inset 0 0 40px rgba(0,0,0,0.5); }
401
+ .hidden-audio { display: none !important; height: 0 !important; width: 0 !important; overflow: hidden !important; }
402
  .feedback-box { background: rgba(56, 189, 248, 0.1); border-left: 4px solid #38bdf8; padding: 15px; border-radius: 8px; font-size: 1.05em; color: #e2e8f0; width: 100%; text-align: left; line-height: 1.4; box-sizing: border-box;}
403
 
404
  .input-row { align-items: stretch !important; margin: 10px 0; }
 
425
  .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); }
426
  .v-stat-box h4 { color: #94a3b8; font-size: 0.9em; text-transform: uppercase; letter-spacing: 1px; margin: 0 0 10px 0; }
427
 
 
428
  .confetti-piece { position: absolute; width: 10px; height: 15px; top: -20px; opacity: 0; animation: fall linear forwards infinite; z-index: 10; border-radius: 2px;}
429
  @keyframes fall {
430
  0% { transform: translateY(-20px) rotate(0deg); opacity: 1; }
 
447
  with gr.Row():
448
  with gr.Column(scale=1, elem_classes=["drip-pod"]):
449
  drip_html = gr.HTML(get_drip_visuals(10.0))
450
+ # The audio component is visible=True but hidden via CSS so browser autoplay isn't blocked!
451
+ drip_audio = gr.Audio(label="Drip's Voice", autoplay=True, interactive=False, elem_classes=["hidden-audio"])
452
  drip_feedback = gr.HTML("<div class='feedback-box'>Waiting for your first query...</div>")
453
 
454
  with gr.Column(scale=2):
 
469
  with gr.Column(visible=False) as victory_ui:
470
  victory_display = gr.HTML()
471
 
472
+ # The 15 inputs and outputs are securely wired here
473
  submit_btn.click(
474
  fn=process_query,
475
  inputs=[user_input, model_selector, game_state],