vighnesh-shetty-vs commited on
Commit
4a9d6cb
·
1 Parent(s): 526fab1

Add updated files

Browse files
Files changed (2) hide show
  1. app.py +65 -340
  2. game_data.py +7 -21
app.py CHANGED
@@ -8,202 +8,76 @@ from game_data import calculate_impact, MODELS
8
  from dialogues import get_dialogue
9
  from alternatives import ALTERNATIVES
10
 
11
- print("Loading classification model...")
12
  classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
13
 
14
- CATEGORIES = [
15
- "simple factual question",
16
- "mathematical calculation",
17
- "creative content generation",
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_stats_html(water, energy, co2, points):
28
- water_percent = max(0, min(100, (water / 10.0) * 100))
29
- return f"""
30
- <div class="stats-container">
31
- <div class="stat-card water-card">
32
- <div class="stat-label">WATER TANK (10L MAX)</div>
33
- <div class="stat-value">{water:.2f}L</div>
34
- <div class="progress-bar-bg">
35
- <div class="progress-bar-fill" style="width: {water_percent}%;"></div>
36
- </div>
37
- </div>
38
- <div class="stat-card energy-card">
39
- <div class="stat-label">ENERGY WASTED</div>
40
- <div class="stat-value">{energy:.4f} <span style="font-size: 0.5em;">kWh</span></div>
41
- </div>
42
- <div class="stat-card co2-card">
43
- <div class="stat-label">CARBON (CO₂e)</div>
44
- <div class="stat-value">{co2:.2f}g</div>
45
- </div>
46
- <div class="stat-card points-card">
47
- <div class="stat-label">SCORE</div>
48
- <div class="stat-value">{points}</div>
49
- </div>
50
- </div>
51
- """
52
-
53
- def get_drip_visuals(water_level):
54
- if water_level > 7.0:
55
- g_start, g_end = "#7dd3fc", "#0369a1"
56
- mouth_d = "M43 112 Q60 122 77 112"
57
- cracks_op, sweat_op, tear_op = "0", "0", "0"
58
- mood, mood_color = "Hydrated and coping", "rgb(34, 211, 238)"
59
- anim = "bounce 2s infinite ease-in-out"
60
- elif 3.0 <= water_level <= 7.0:
61
- g_start, g_end = "#38bdf8", "#0284c7"
62
- mouth_d = "M43 112 Q60 110 77 112"
63
- cracks_op, sweat_op, tear_op = "0", "1", "0"
64
- mood, mood_color = "Shrinking & Sweaty", "#0ea5e9"
65
- anim = "float 4s infinite ease-in-out"
66
- elif water_level > 0:
67
- g_start, g_end = "#fca5a5", "#b91c1c"
68
- mouth_d = "M43 116 Q60 102 77 116"
69
- cracks_op, sweat_op, tear_op = "1", "0", "1"
70
- mood, mood_color = "Overheating & Raspy", "#ef4444"
71
- anim = "shake 0.5s infinite"
72
- else:
73
- g_start, g_end = "#94a3b8", "#334155"
74
- mouth_d = "M40 112 Q45 105 50 112 T60 112 T70 112 T80 112"
75
- cracks_op, sweat_op, tear_op = "0", "0", "0"
76
- mood, mood_color = "Evaporated!", "#94a3b8"
77
- anim = "floatUp 3s forwards"
78
-
79
- return f"""
80
- <div class="drip-panel" style="animation: {anim}; display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%;">
81
- <div class="drip-lbl" style="font-weight: 800; color: #94a3b8; letter-spacing: 3px; font-size: 14px; margin-bottom: 5px;">DRIP</div>
82
- <svg id="drip-svg" viewBox="0 0 120 148" style="width: 140px; height: 160px; overflow: visible;" xmlns="http://www.w3.org/2000/svg">
83
- <defs>
84
- <radialGradient id="dg" cx="38%" cy="32%">
85
- <stop id="dg1" offset="0%" stop-color="{g_start}"></stop>
86
- <stop id="dg2" offset="100%" stop-color="{g_end}"></stop>
87
- </radialGradient>
88
- </defs>
89
- <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>
90
- <ellipse cx="42" cy="70" rx="9" ry="13" fill="rgba(255,255,255,0.22)" transform="rotate(-18,42,70)"></ellipse>
91
- <circle cx="44" cy="90" r="10" fill="white"></circle>
92
- <circle cx="76" cy="90" r="10" fill="white"></circle>
93
- <circle id="pl" cx="45" cy="91" r="6" fill="#0f172a"></circle>
94
- <circle id="pr" cx="77" cy="91" r="6" fill="#0f172a"></circle>
95
- <circle cx="47" cy="88" r="2.5" fill="white"></circle>
96
- <circle cx="79" cy="88" r="2.5" fill="white"></circle>
97
- <path id="dm" d="{mouth_d}" stroke="#0f172a" stroke-width="2.5" stroke-linecap="round" fill="none"></path>
98
- <g id="cracks" opacity="{cracks_op}" style="transition: opacity 0.5s;">
99
- <path d="M80 46 L86 58 L79 65 L85 77" stroke="#bae6fd" stroke-width="1.3" stroke-linecap="round" fill="none" opacity=".7"></path>
100
- <path d="M37 82 L31 93 L39 99" stroke="#bae6fd" stroke-width="1.3" stroke-linecap="round" fill="none" opacity=".7"></path>
101
- </g>
102
- <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>
103
- <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>
104
- </svg>
105
- <div class="drip-mood" id="drip-mood" style="color: {mood_color}; font-weight: 500; font-size: 1.1rem; margin-top: 15px;">{mood}</div>
106
- <div style="text-align:center; margin-top:10px;">
107
- <div style="font-size:10px; color:#94a3b8; text-transform:uppercase; letter-spacing:1px;">Water Left</div>
108
- <div style="font-size:26px; font-weight:700; color:{mood_color};" id="d-water">{water_level:.2f}L</div>
109
- </div>
110
- </div>
111
- """
112
 
113
  def get_impact_cards(impact, category):
 
114
  return f"""
115
  <div class="impact-container">
116
  <div class="impact-card bad-impact">
117
  <h3 style="margin: 0 0 10px 0; color: #fca5a5;">🔥 LLM Impact</h3>
118
- <p style="margin:4px 0; font-size:1.1em;"><strong>{impact['water_ml']} mL</strong> Water</p>
119
- <p style="margin:4px 0; font-size:1.1em;"><strong>{impact['energy_wh']} Wh</strong> Energy</p>
120
- <p style="margin:4px 0; font-size:1.1em;"><strong>{impact['co2_g']} g</strong> CO₂e</p>
121
- <p style="margin:0; font-size:0.85em; opacity: 0.8;">Deducted from global reserves.</p>
122
  </div>
123
  <div class="impact-card good-impact">
124
  <h3 style="margin: 0 0 10px 0; color: #86efac;">🌿 Eco-Alternative</h3>
125
- <p style="margin:4px 0; font-size:1.1em;"><strong>~0.0 mL</strong> Water</p>
126
- <p style="margin:4px 0; font-size:1.1em;"><strong>~0.001 Wh</strong> Energy</p>
127
- <p style="margin:4px 0; font-size:1.1em;"><strong>~0.01 g</strong> CO₂e</p>
128
- <p style="margin:0; font-size:0.85em; opacity: 0.8;">Near-zero footprint.</p>
129
  </div>
130
  </div>
131
  """
132
 
133
- def format_alt_button(text, impact):
134
- icon = "💡"
135
- if "Search" in text or "Google" in text: icon = "🔍"
136
- elif "Wikipedia" in text or "Encyclopedia" in text: icon = "📚"
137
- elif "Expert" in text or "Quora" in text: icon = "👤"
138
- elif "Wolfram" in text or "Geogebra" in text or "Desmos" in text: icon = "🧮"
139
- elif "Reddit" in text or "Gutenberg" in text or "Thesaurus" in text: icon = "📝"
140
- 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"
141
-
142
  def generate_victory_dashboard(state):
143
- """Generates a celebratory end-game report with detailed query analytics[cite: 14, 41]."""
144
- total_w_saved = 0
145
- total_e_saved = 0
146
- total_c_saved = 0
147
 
148
  rows = ""
149
  for item in state["history"]:
150
- if item['alt_name'] == "None (Justified Use)":
151
- saved_w, saved_e, saved_c = 0.0, 0.0, 0.0
152
- alt_display = "<span style='color: #94a3b8;'>Justified Use (No Alternative)</span>"
153
- else:
154
- saved_w = item['water_ml']
155
- saved_e = max(0, item['energy_wh'] - 0.001)
156
- saved_c = max(0, item['co2_g'] - 0.01)
157
-
158
- total_w_saved += saved_w
159
- total_e_saved += saved_e
160
- total_c_saved += saved_c
161
- alt_display = f"<span style='color: #34d399;'>{item['alt_name']}</span>"
162
-
163
  rows += f"""
164
- <tr style="border-bottom: 1px solid rgba(255,255,255,0.1); background: rgba(0,0,0,0.2);">
165
- <td style="padding: 15px; font-style: italic;">"{item['query']}"</td>
166
- <td style="padding: 15px; color: #fca5a5;">{item['water_ml']:.1f}mL / {item['energy_wh']:.2f}Wh / {item['co2_g']:.2f}g</td>
167
- <td style="padding: 15px;">{alt_display}</td>
168
- <td style="padding: 15px; color: #60a5fa; font-weight: bold;">{saved_w:.1f}mL / {saved_e:.2f}Wh / {saved_c:.2f}g</td>
169
  </tr>
170
  """
171
 
172
  return f"""
173
- <div class="victory-dashboard">
174
- <div class="confetti"></div>
175
- <h1 class="victory-title">🏆 PLANET SAVED! 🏆</h1>
176
- <p style="text-align: center; font-size: 1.3em; color: #a7f3d0; margin-bottom: 30px;">You reached {state['points']} points and kept Drip alive!</p>
177
 
178
- <div class="victory-stats-row">
179
- <div class="v-stat-box">
180
- <h4>Final Water</h4>
181
- <h2>{state['water']:.2f} L</h2>
182
- </div>
183
- <div class="v-stat-box" style="border-color: #34d399;">
184
- <h4 style="color: #34d399;">Planetary Savings</h4>
185
- <p style="color: #34d399; margin: 5px 0;">💧 {total_w_saved:.1f} mL Saved</p>
186
- <p style="color: #facc15; margin: 5px 0;">⚡ {total_e_saved:.2f} Wh Saved</p>
187
- <p style="color: #a8a29e; margin: 5px 0;">☁️ {total_c_saved:.2f} g Saved</p>
188
- </div>
189
- <div class="v-stat-box" style="border-color: #fca5a5;">
190
- <h4 style="color: #fca5a5;">Total Usage</h4>
191
- <p style="color: #fca5a5; margin: 5px 0;">💧 {10.0 - state['water']:.2f} L</p>
192
- <p style="color: #fca5a5; margin: 5px 0;">⚡ {state['energy']:.4f} kWh</p>
193
- <p style="color: #fca5a5; margin: 5px 0;">☁️ {state['co2']:.2f} g</p>
194
- </div>
195
  </div>
196
 
197
- <h3 style="margin-top: 40px; color: #38bdf8; font-size: 1.8em;">📊 AI Usage Audit Log</h3>
198
- <p style="opacity: 0.9; margin-bottom: 20px;">Detailed breakdown of your session's environmental impact[cite: 14].</p>
199
-
200
- <div style="max-height: 400px; overflow-y: auto; background: rgba(15, 23, 42, 0.9); border-radius: 12px; border: 1px solid rgba(255,255,255,0.1);">
201
- <table style="width: 100%; text-align: left; border-collapse: collapse; font-size: 1em;">
202
- <tr style="background: rgba(56, 189, 248, 0.1); border-bottom: 2px solid #38bdf8;">
203
- <th style="padding: 15px;">User Query</th>
204
- <th style="padding: 15px;">LLM Cost (Wasted)</th>
205
- <th style="padding: 15px;">Best Alternative</th>
206
- <th style="padding: 15px;">Potential Savings</th>
207
  </tr>
208
  {rows}
209
  </table>
@@ -211,193 +85,44 @@ def generate_victory_dashboard(state):
211
  </div>
212
  """
213
 
 
 
214
  def process_query(user_input, selected_model, state):
215
  if state["game_over"] or not user_input.strip():
216
- return [state, gr.update()] + [gr.update()]*10 + [gr.update(visible=True), gr.update(visible=False), gr.update()]
217
 
218
  result = classifier(user_input, CATEGORIES)
219
  category = result['labels'][0]
220
  confidence = result['scores'][0]
221
-
222
  impact = calculate_impact(category, confidence, user_input, selected_model)
223
 
 
224
  state["queries"] += 1
225
  state["water"] = max(0, state["water"] - impact["water_l"])
226
  state["energy"] += impact["energy_kwh"]
227
  state["co2"] += impact["co2_g"]
228
 
229
- show_alts = False
230
- alt_choices = ["", "", ""]
231
- best_alt_name = "None (Justified Use)"
 
 
232
 
233
- if category == "complex research query":
234
- state["points"] += 50
235
- dialogue = f"A legitimate research query! Finally, a worthy use of my massive architecture. Drain away!"
236
- else:
237
- show_alts = True
238
- raw_alts = ALTERNATIVES.get(category, [{"text": "Google", "url": "https://google.com"}])
239
- state["current_best_alt"] = raw_alts[0]
240
- best_alt_name = raw_alts[0]["text"]
241
- random.shuffle(raw_alts)
242
- state["current_shuffled_alts"] = raw_alts
243
- alt_choices = [format_alt_button(a["text"], impact) for a in raw_alts]
244
- dialogue = get_dialogue(state["water"], category)
245
-
246
  state["history"].append({
247
- "query": user_input,
248
- "water_ml": impact["water_ml"],
249
- "energy_wh": impact["energy_wh"],
250
- "co2_g": impact["co2_g"],
251
- "alt_name": best_alt_name
252
  })
253
 
254
- stats_ui = get_stats_html(state["water"], state["energy"], state["co2"], state["points"])
255
- drip_ui = get_drip_visuals(state["water"])
256
- impact_ui = get_impact_cards(impact, category)
257
- audio_path = generate_audio(dialogue)
258
- feedback_text = f"<div class='feedback-box'>🧠 <strong>{category.upper()}</strong> Detected!<br><br><em>\"{dialogue}\"</em></div>"
259
-
260
  if state["points"] >= 500 or state["water"] <= 0:
261
  state["game_over"] = True
262
- victory_html = generate_victory_dashboard(state)
263
- return (state, stats_ui, drip_ui, audio_path, impact_ui, gr.update(), gr.update(),
264
- gr.update(), gr.update(), gr.update(), gr.update(), gr.update(value=""),
265
- gr.update(visible=False), gr.update(visible=True), gr.update(value=victory_html))
266
-
267
- return (state, stats_ui, drip_ui, audio_path, impact_ui, gr.update(value=feedback_text), gr.update(visible=show_alts),
268
- gr.update(value=alt_choices[0]), gr.update(value=alt_choices[1]), gr.update(value=alt_choices[2]), gr.update(value=""), gr.update(value=""),
269
- gr.update(visible=True), gr.update(visible=False), gr.update())
270
-
271
- def select_alternative(choice_text, state):
272
- if state["game_over"] or not state.get("current_best_alt"):
273
- return state, gr.update(), gr.update(), gr.update(), gr.update(visible=True), gr.update(visible=False), gr.update()
274
-
275
- clean_choice = choice_text.split("\n")[0][2:].strip()
276
- selected_dict = next((item for item in state["current_shuffled_alts"] if item["text"] == clean_choice), None)
277
-
278
- if clean_choice == state["current_best_alt"]["text"]:
279
- state["points"] += 10
280
- 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>"
281
- else:
282
- 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>"
283
-
284
- stats_ui = get_stats_html(state["water"], state["energy"], state["co2"], state["points"])
285
-
286
- if state["points"] >= 500:
287
- state["game_over"] = True
288
- victory_html = generate_victory_dashboard(state)
289
- return state, stats_ui, gr.update(), gr.update(), gr.update(visible=False), gr.update(visible=True), gr.update(value=victory_html)
290
-
291
- return state, stats_ui, gr.update(value=msg), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update()
292
-
293
- custom_css = """
294
- @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@300;500;700&display=swap');
295
- body, .gradio-container { background-color: #0B1120 !important; font-family: 'Outfit', sans-serif !important; color: #e2e8f0 !important; }
296
- .gradio-container { max-width: 950px !important; margin: auto; padding-top: 20px; }
297
- h1 { text-align: center; color: #38bdf8; text-shadow: 0 0 15px rgba(56, 189, 248, 0.5); font-size: 2.5em !important; margin-bottom: 5px !important;}
298
- .subtitle { text-align: center; color: #94a3b8; margin-bottom: 30px; font-weight: 300; }
299
-
300
- .stats-container { display: flex; gap: 10px; justify-content: space-between; margin-bottom: 20px; }
301
- .stat-card { flex: 1; padding: 15px 10px; border-radius: 12px; text-align: center; background: rgba(30, 41, 59, 0.6); border: 1px solid rgba(255,255,255,0.1); }
302
- .water-card { box-shadow: 0 4px 20px rgba(56, 189, 248, 0.15); border-top: 2px solid #38bdf8; }
303
- .energy-card { box-shadow: 0 4px 20px rgba(250, 204, 21, 0.15); border-top: 2px solid #facc15; }
304
- .co2-card { box-shadow: 0 4px 20px rgba(168, 162, 158, 0.15); border-top: 2px solid #a8a29e; }
305
- .points-card { box-shadow: 0 4px 20px rgba(52, 211, 153, 0.15); border-top: 2px solid #34d399; }
306
- .stat-label { font-size: 0.75em; letter-spacing: 1px; opacity: 0.8; margin-bottom: 5px; }
307
- .stat-value { font-size: 1.8em; font-weight: 700; color: white; }
308
- .progress-bar-bg { background: #1e293b; height: 8px; border-radius: 4px; margin-top: 10px; overflow: hidden; }
309
- .progress-bar-fill { background: linear-gradient(90deg, #0284c7, #38bdf8); height: 100%; transition: width 0.5s ease; }
310
-
311
- @keyframes bounce { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-15px); } }
312
- @keyframes float { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-5px); } }
313
- @keyframes shake { 0%, 100% { transform: translateX(0); } 25% { transform: translateX(-3px); } 75% { transform: translateX(3px); } }
314
- @keyframes floatUp { to { transform: translateY(-30px); opacity: 0; } }
315
-
316
- .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); }
317
- .drip-audio { background: transparent !important; border: none !important; box-shadow: none !important; width: 100%; max-width: 300px; filter: invert(1) hue-rotate(180deg) brightness(1.5); margin-bottom: 15px;}
318
- .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;}
319
-
320
- .input-row { align-items: stretch !important; margin: 10px 0; }
321
- .custom-textbox textarea { background: rgba(30, 41, 59, 0.8) !important; border: 1px solid #38bdf8 !important; color: white !important; font-size: 1.1em !important; border-radius: 12px !important; box-shadow: inset 0 2px 10px rgba(0,0,0,0.3) !important; padding: 15px !important; resize: none !important; }
322
- .custom-btn { background: linear-gradient(135deg, #0284c7, #0ea5e9) !important; border: none !important; color: white !important; font-weight: bold !important; font-size: 1.1em !important; border-radius: 12px !important; transition: all 0.3s !important; height: 100%; min-height: 85px; }
323
- .custom-btn:hover { box-shadow: 0 0 20px rgba(56, 189, 248, 0.6) !important; transform: scale(1.02); }
324
-
325
- .impact-container { display: flex; gap: 20px; width: 100%; }
326
- .impact-card { flex: 1; padding: 20px; border-radius: 16px; border: 1px solid rgba(255,255,255,0.1); }
327
- .bad-impact { background: linear-gradient(180deg, rgba(127, 29, 29, 0.3), rgba(69, 10, 10, 0.5)); border-top: 3px solid #ef4444; }
328
- .good-impact { background: linear-gradient(180deg, rgba(20, 83, 45, 0.3), rgba(6, 78, 59, 0.5)); border-top: 3px solid #10b981; }
329
-
330
- .alt-group { padding: 25px; background: linear-gradient(145deg, rgba(16, 185, 129, 0.05), rgba(6, 95, 70, 0.1)); border-radius: 20px; border: 1px solid rgba(16, 185, 129, 0.3); margin-top: 25px; box-shadow: 0 10px 30px rgba(0,0,0,0.2);}
331
- .alt-card { background: linear-gradient(145deg, #1e293b, #0f172a) !important; border: 1px solid #10b981 !important; color: #a7f3d0 !important; height: auto !important; min-height: 180px !important; border-radius: 16px !important; font-size: 1.05em !important; font-weight: 500 !important; white-space: pre-wrap !important; line-height: 1.5 !important; padding: 15px !important; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important; cursor: pointer; box-shadow: 0 4px 15px rgba(0,0,0,0.4) !important;}
332
- .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;}
333
- .custom-dropdown { background: rgba(30, 41, 59, 0.8) !important; border: 1px solid #38bdf8 !important; border-radius: 12px !important; }
334
-
335
- /* Victory Dashboard & Celebration */
336
- @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); } }
337
- .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; overflow: hidden; }
338
- .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; }
339
- .victory-stats-row { display: flex; gap: 20px; margin-top: 30px; }
340
- .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); }
341
- .v-stat-box h4 { color: #94a3b8; font-size: 0.9em; text-transform: uppercase; letter-spacing: 1px; margin: 0 0 10px 0; }
342
- .v-stat-box h2 { color: #38bdf8; font-size: 2.5em; margin: 0; }
343
-
344
- /* Confetti Blast Animation */
345
- .confetti { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 10; }
346
- .confetti::before { content: '🎉'; position: absolute; font-size: 2rem; animation: scatter 3s infinite linear; }
347
- @keyframes scatter {
348
- 0% { transform: translate(50vw, 50vh) rotate(0deg); opacity: 1; }
349
- 100% { transform: translate(calc(100vw * var(--x)), calc(100vh * var(--y))) rotate(360deg); opacity: 0; }
350
- }
351
- """
352
-
353
- with gr.Blocks(title="EcoQueryQuest") as demo:
354
- game_state = gr.State({
355
- "water": 10.0, "energy": 0.0, "co2": 0.0, "points": 0, "queries": 0,
356
- "history": [], "game_over": False, "current_best_alt": None, "current_shuffled_alts": []
357
- })
358
-
359
- gr.Markdown("<h1>🌍 EcoQueryQuest</h1>")
360
- gr.Markdown("<div class='subtitle'>Select a model, type a query, and watch Drip react. Reach 500 points to win!</div>")
361
-
362
- stats_html = gr.HTML(get_stats_html(10.0, 0.0, 0.0, 0))
363
-
364
- with gr.Column(visible=True) as main_game_ui:
365
- with gr.Row():
366
- with gr.Column(scale=1, elem_classes=["drip-pod"]):
367
- drip_html = gr.HTML(get_drip_visuals(10.0))
368
- drip_audio = gr.Audio(label="Drip's Voice", autoplay=True, interactive=False, elem_classes=["drip-audio"])
369
- drip_feedback = gr.HTML("<div class='feedback-box'>Waiting for your first query...</div>")
370
-
371
- with gr.Column(scale=2):
372
- model_selector = gr.Dropdown(choices=list(MODELS.keys()), value="GPT-5.4", label="Select Target LLM Backend", elem_classes=["custom-dropdown"])
373
- with gr.Row(elem_classes=["input-row"]):
374
- user_input = gr.Textbox(show_label=False, placeholder="Type your query here...", elem_classes=["custom-textbox"], scale=4, lines=3)
375
- submit_btn = gr.Button("Send Query", elem_classes=["custom-btn"], scale=1)
376
- impact_display = gr.HTML()
377
-
378
- with gr.Group(visible=False, elem_classes=["alt-group"]) as alternatives_group:
379
- gr.Markdown("<h3 style='text-align:center; color:#34d399; margin-bottom: 20px;'>🌱 Drip says: 'Quick! Pick a greener tool to earn points!'</h3>")
380
- with gr.Row():
381
- alt_btn_1 = gr.Button("", elem_classes=["alt-card"])
382
- alt_btn_2 = gr.Button("", elem_classes=["alt-card"])
383
- alt_btn_3 = gr.Button("", elem_classes=["alt-card"])
384
- alt_feedback = gr.Markdown()
385
-
386
- with gr.Column(visible=False) as victory_ui:
387
- victory_display = gr.HTML()
388
-
389
- submit_btn.click(
390
- fn=process_query,
391
- inputs=[user_input, model_selector, game_state],
392
- 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]
393
- )
394
-
395
- for btn in [alt_btn_1, alt_btn_2, alt_btn_3]:
396
- btn.click(
397
- fn=select_alternative,
398
- inputs=[btn, game_state],
399
- outputs=[game_state, stats_html, alt_feedback, alternatives_group, main_game_ui, victory_ui, victory_display]
400
- )
401
-
402
- if __name__ == "__main__":
403
- demo.launch(css=custom_css)
 
8
  from dialogues import get_dialogue
9
  from alternatives import ALTERNATIVES
10
 
 
11
  classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
12
 
13
+ def get_relatable_translations(impact):
14
+ """Converts abstract numbers into physical examples."""
15
+ # Water: 1 bottle = 500mL
16
+ bottles = impact['water_ml'] / 500.0
17
+ w_ex = f"{bottles:.1f} water bottles" if bottles >= 0.1 else "A few sips"
18
+
19
+ # Energy: 10 LED bulbs (10W each) for 1 hour = 100Wh
20
+ # Let's use 1 LED bulb for X hours
21
+ bulb_hours = impact['energy_wh'] / 10.0
22
+ 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"
23
+
24
+ # CO2: 1 phone charge = ~5g
25
+ charges = impact['co2_g'] / 5.0
26
+ c_ex = f"{charges:.1f} phone charges" if charges >= 0.1 else "Negligible emissions"
27
+
28
+ return w_ex, e_ex, c_ex
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  def get_impact_cards(impact, category):
31
+ w_ex, e_ex, c_ex = get_relatable_translations(impact)
32
  return f"""
33
  <div class="impact-container">
34
  <div class="impact-card bad-impact">
35
  <h3 style="margin: 0 0 10px 0; color: #fca5a5;">🔥 LLM Impact</h3>
36
+ <p>💧 <strong>{impact['water_ml']} mL</strong> ({w_ex})</p>
37
+ <p><strong>{impact['energy_wh']} Wh</strong> ({e_ex})</p>
38
+ <p>☁️ <strong>{impact['co2_g']} g</strong> ({c_ex})</p>
 
39
  </div>
40
  <div class="impact-card good-impact">
41
  <h3 style="margin: 0 0 10px 0; color: #86efac;">🌿 Eco-Alternative</h3>
42
+ <p><strong>~0.0 mL</strong> Water | <strong>~0.001 Wh</strong> Energy</p>
43
+ <p style="font-size:0.85em; opacity: 0.8;">Zero bottles wasted. Planet saved.</p>
 
 
44
  </div>
45
  </div>
46
  """
47
 
 
 
 
 
 
 
 
 
 
48
  def generate_victory_dashboard(state):
49
+ """Victory screen with celebrations and detailed audit[cite: 14, 41]."""
50
+ total_w_saved = sum(item['water_ml'] for item in state["history"] if item['alt_name'] != "None")
51
+ total_e_saved = sum(item['energy_wh'] for item in state["history"] if item['alt_name'] != "None")
 
52
 
53
  rows = ""
54
  for item in state["history"]:
55
+ savings = f"{item['water_ml']:.1f}mL saved" if item['alt_name'] != "None" else "Justified"
 
 
 
 
 
 
 
 
 
 
 
 
56
  rows += f"""
57
+ <tr style="border-bottom: 1px solid rgba(255,255,255,0.1);">
58
+ <td style="padding: 10px;">{item['query']}</td>
59
+ <td style="padding: 10px; color: #fca5a5;">{item['water_ml']}mL / {item['co2_g']}g</td>
60
+ <td style="padding: 10px; color: #34d399;">{item['alt_name']}</td>
61
+ <td style="padding: 10px; color: #60a5fa;">{savings}</td>
62
  </tr>
63
  """
64
 
65
  return f"""
66
+ <div class="victory-screen">
67
+ <div class="pyro"><div class="before"></div><div class="after"></div></div>
68
+ <h1 style="color: #34d399; text-align: center; font-size: 3em;">🏆 MISSION ACCOMPLISHED!</h1>
69
+ <p style="text-align: center; font-size: 1.2em;">You reached {state['points']} points and protected the environment!</p>
70
 
71
+ <div class="final-stats">
72
+ <div class="v-box"><h4>Total Water Saved</h4><h2>{total_w_saved:.1f} mL</h2><p>({total_w_saved/500:.1f} bottles)</p></div>
73
+ <div class="v-box"><h4>Total Energy Saved</h4><h2>{total_e_saved:.2f} Wh</h2><p>({total_e_saved/10:.1f} bulb hours)</p></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  </div>
75
 
76
+ <h3 style="margin-top: 30px; color: #38bdf8;">📊 Your Eco-Audit Log</h3>
77
+ <div style="overflow-x:auto;">
78
+ <table style="width: 100%; border-collapse: collapse; background: rgba(0,0,0,0.3); border-radius: 10px;">
79
+ <tr style="background: rgba(255,255,255,0.1); text-align: left;">
80
+ <th style="padding: 10px;">Query</th><th style="padding: 10px;">LLM Cost</th><th style="padding: 10px;">Greener Tool</th><th style="padding: 10px;">Savings</th>
 
 
 
 
 
81
  </tr>
82
  {rows}
83
  </table>
 
85
  </div>
86
  """
87
 
88
+ # ... [The custom_css should include .pyro animations for the 'blast' effect] ...
89
+
90
  def process_query(user_input, selected_model, state):
91
  if state["game_over"] or not user_input.strip():
92
+ return [state] + [gr.update()]*13 + [gr.update(visible=True), gr.update(visible=False), gr.update()]
93
 
94
  result = classifier(user_input, CATEGORIES)
95
  category = result['labels'][0]
96
  confidence = result['scores'][0]
 
97
  impact = calculate_impact(category, confidence, user_input, selected_model)
98
 
99
+ # Update State [cite: 12, 37]
100
  state["queries"] += 1
101
  state["water"] = max(0, state["water"] - impact["water_l"])
102
  state["energy"] += impact["energy_kwh"]
103
  state["co2"] += impact["co2_g"]
104
 
105
+ # Handle Dialogue and Alternatives [cite: 6, 16]
106
+ show_alts = category != "complex research query"
107
+ if not show_alts: state["points"] += 50
108
+
109
+ dialogue = get_dialogue(state["water"], category)
110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  state["history"].append({
112
+ "query": user_input, "water_ml": impact["water_ml"], "energy_wh": impact["energy_wh"],
113
+ "co2_g": impact["co2_g"], "alt_name": ALTERNATIVES[category][0]['text'] if show_alts else "None"
 
 
 
114
  })
115
 
116
+ # Return elements and clear user_input [cite: 40]
 
 
 
 
 
117
  if state["points"] >= 500 or state["water"] <= 0:
118
  state["game_over"] = True
119
+ return (state, gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
120
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(value=""),
121
+ gr.update(visible=False), gr.update(visible=True), generate_victory_dashboard(state))
122
+
123
+ # General return with input field reset
124
+ return (state, get_stats_html(state["water"], state["energy"], state["co2"], state["points"]),
125
+ get_drip_visuals(state["water"]), generate_audio(dialogue), get_impact_cards(impact, category),
126
+ f"### {category.upper()}\n{dialogue}", gr.update(visible=show_alts),
127
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(value=""),
128
+ gr.update(visible=True), gr.update(visible=False), gr.update())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
game_data.py CHANGED
@@ -1,4 +1,4 @@
1
- # Model Baselines (per 1000 tokens)
2
  MODELS = {
3
  "Mistral Large 3": {"energy_wh": 1.98, "water_ml": 3.56, "co2_g": 0.95},
4
  "Mistral Medium 3": {"energy_wh": 6.76, "water_ml": 12.17, "co2_g": 3.24},
@@ -10,7 +10,6 @@ MODELS = {
10
  "GPT-5.4": {"energy_wh": 169.05, "water_ml": 304.29, "co2_g": 81.14}
11
  }
12
 
13
- # Category Token Multipliers
14
  CATEGORY_MULTIPLIERS = {
15
  "simple factual question": 0.05,
16
  "mathematical calculation": 0.10,
@@ -22,31 +21,18 @@ def calculate_impact(category, confidence_score, query_text, model_name):
22
  model_cost = MODELS.get(model_name, MODELS["Mistral Large 3"])
23
  cat_mult = CATEGORY_MULTIPLIERS.get(category, 0.05)
24
 
25
- if confidence_score > 0.8:
26
- conf_mult = 1.0
27
- elif 0.5 <= confidence_score <= 0.8:
28
- conf_mult = 1.2
29
- else:
30
- conf_mult = 1.5
31
-
32
  word_count = len(query_text.split())
33
- if word_count < 20:
34
- len_factor = 1.0
35
- elif 20 <= word_count <= 50:
36
- len_factor = 1.3
37
- else:
38
- len_factor = 1.5
39
-
40
  water_ml = model_cost["water_ml"] * cat_mult * conf_mult * len_factor
41
  energy_wh = model_cost["energy_wh"] * cat_mult * conf_mult * len_factor
42
  co2_g = model_cost["co2_g"] * cat_mult * conf_mult * len_factor
43
 
44
- water_l = water_ml / 1000.0
45
- energy_kwh = energy_wh / 1000.0
46
-
47
  return {
48
- "water_l": round(water_l, 4),
49
- "energy_kwh": round(energy_kwh, 5),
50
  "water_ml": round(water_ml, 1),
51
  "energy_wh": round(energy_wh, 2),
52
  "co2_g": round(co2_g, 2)
 
1
+ # Model Baselines (per 1000 tokens) based on scaling laws [cite: 26, 27]
2
  MODELS = {
3
  "Mistral Large 3": {"energy_wh": 1.98, "water_ml": 3.56, "co2_g": 0.95},
4
  "Mistral Medium 3": {"energy_wh": 6.76, "water_ml": 12.17, "co2_g": 3.24},
 
10
  "GPT-5.4": {"energy_wh": 169.05, "water_ml": 304.29, "co2_g": 81.14}
11
  }
12
 
 
13
  CATEGORY_MULTIPLIERS = {
14
  "simple factual question": 0.05,
15
  "mathematical calculation": 0.10,
 
21
  model_cost = MODELS.get(model_name, MODELS["Mistral Large 3"])
22
  cat_mult = CATEGORY_MULTIPLIERS.get(category, 0.05)
23
 
24
+ # Logic for buffers and length factors [cite: 25, 29]
25
+ conf_mult = 1.0 if confidence_score > 0.8 else (1.2 if confidence_score > 0.5 else 1.5)
 
 
 
 
 
26
  word_count = len(query_text.split())
27
+ len_factor = 1.0 if word_count < 20 else (1.3 if word_count <= 50 else 1.5)
28
+
 
 
 
 
 
29
  water_ml = model_cost["water_ml"] * cat_mult * conf_mult * len_factor
30
  energy_wh = model_cost["energy_wh"] * cat_mult * conf_mult * len_factor
31
  co2_g = model_cost["co2_g"] * cat_mult * conf_mult * len_factor
32
 
 
 
 
33
  return {
34
+ "water_l": water_ml / 1000.0,
35
+ "energy_kwh": energy_wh / 1000.0,
36
  "water_ml": round(water_ml, 1),
37
  "energy_wh": round(energy_wh, 2),
38
  "co2_g": round(co2_g, 2)