import gradio as gr
from transformers import pipeline
import random
from gtts import gTTS
import os
print("Loading classification model...", flush=True)
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
CATEGORIES = [
"simple factual question",
"mathematical calculation",
"creative content generation",
"complex research query"
]
# --- 1. EMBEDDED DATA & LOGIC ---
MODELS = {
"Mistral Large 3": {"energy_wh": 1.98, "water_ml": 3.56, "co2_g": 0.95},
"Mistral Medium 3": {"energy_wh": 6.76, "water_ml": 12.17, "co2_g": 3.24},
"Claude Sonnet 4.6": {"energy_wh": 19.32, "water_ml": 34.78, "co2_g": 9.27},
"Gemini 3 Pro": {"energy_wh": 72.45, "water_ml": 130.41, "co2_g": 34.78},
"Gemini 3.1 Pro": {"energy_wh": 77.28, "water_ml": 139.10, "co2_g": 37.09},
"Claude Opus 4.6": {"energy_wh": 96.60, "water_ml": 173.88, "co2_g": 46.37},
"GPT-5.2": {"energy_wh": 144.90, "water_ml": 260.82, "co2_g": 69.55},
"GPT-5.4": {"energy_wh": 169.05, "water_ml": 304.29, "co2_g": 81.14}
}
CATEGORY_MULTIPLIERS = {
"simple factual question": 0.05,
"mathematical calculation": 0.10,
"creative content generation": 0.80,
"complex research query": 1.50
}
DIALOGUES = {
"energetic": {
"simple factual question": "You used a supercomputer for a simple fact? I'm full right now, but that's just lazy. Open a book.",
"mathematical calculation": "A basic calculator could do this with zero footprint. But sure, burn my energy for basic math.",
"creative content generation": "Generating artificial creativity... I'll allow it, but watch my water levels drop. Your poetry is expensive.",
"complex research query": "A legitimate research query! Finally, a worthy use of my massive architecture. Drain away!"
},
"tired": {
"simple factual question": "Look at me. I'm sweating. All because you couldn't be bothered to use a standard search engine.",
"mathematical calculation": "Did you skip basic math class? I am literally evaporating to do arithmetic for you.",
"creative content generation": "Your 'creativity' is draining my lifeblood. Make it quick, I don't have much cooling left.",
"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."
},
"raspy": {
"simple factual question": "*Cough* Read an encyclopedia... I'm dying for your trivia...",
"mathematical calculation": "Use an abacus... you are boiling my last drops for numbers...",
"creative content generation": "My final breath... wasted on generating a fictional story... how poetic... and cruel.",
"complex research query": "Critical system failure imminent... I am giving my life for your research... make it count."
}
}
ALTERNATIVES = {
"simple factual question": [
{"text": "Search Engine (Google)", "url": "https://www.google.com"},
{"text": "Wikipedia Encyclopedia", "url": "https://www.wikipedia.org"},
{"text": "Ask a Human Expert (Quora)", "url": "https://www.quora.com"}
],
"mathematical calculation": [
{"text": "Wolfram Alpha Engine", "url": "https://www.wolframalpha.com"},
{"text": "Geogebra Calculator", "url": "https://www.geogebra.org"},
{"text": "Desmos Graphing", "url": "https://www.desmos.com"}
],
"creative content generation": [
{"text": "Writing Prompts (Reddit)", "url": "https://www.reddit.com/r/WritingPrompts/"},
{"text": "Thesaurus/Dictionary", "url": "https://www.thesaurus.com"},
{"text": "Project Gutenberg Books", "url": "https://www.gutenberg.org"}
],
"complex research query": [
{"text": "Google Scholar Search", "url": "https://scholar.google.com"},
{"text": "University Library Database", "url": "https://www.worldcat.org/"},
{"text": "Open Access Journals (DOAJ)", "url": "https://doaj.org/"}
]
}
def calculate_impact(category, confidence_score, query_text, model_name):
model_cost = MODELS.get(model_name, MODELS["Mistral Large 3"])
cat_mult = CATEGORY_MULTIPLIERS.get(category, 0.05)
conf_mult = 1.0 if confidence_score > 0.8 else (1.2 if confidence_score > 0.5 else 1.5)
word_count = len(query_text.split())
len_factor = max(0.5, 1.0 + ((word_count - 15) * 0.015))
water_ml = model_cost["water_ml"] * cat_mult * conf_mult * len_factor
energy_wh = model_cost["energy_wh"] * cat_mult * conf_mult * len_factor
co2_g = model_cost["co2_g"] * cat_mult * conf_mult * len_factor
return {
"water_l": water_ml / 1000.0, "energy_kwh": energy_wh / 1000.0,
"water_ml": round(water_ml, 1), "energy_wh": round(energy_wh, 2), "co2_g": round(co2_g, 2)
}
def get_dialogue(water_level, category):
# Adjusted dialogue thresholds back to 10L max (7.0 and 3.0)
state = "energetic" if water_level > 7.0 else ("tired" if water_level >= 3.0 else "raspy")
return DIALOGUES[state].get(category, "I have no words left for this.")
def generate_audio(text):
tts = gTTS(text, lang='en')
filepath = "temp_drip_voice.mp3"
tts.save(filepath)
return filepath
# --- 2. UI GENERATORS & DASHBOARDS ---
def get_relatable_translations(impact):
bottles = impact['water_ml'] / 500.0
w_ex = f"{bottles:.1f} water bottles" if bottles >= 0.1 else "A few sips"
bulb_hours = impact['energy_wh'] / 10.0
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"
charges = impact['co2_g'] / 5.0
c_ex = f"{charges:.1f} phone charges" if charges >= 0.1 else "Negligible emissions"
return w_ex, e_ex, c_ex
def get_stats_html(water, energy, co2, points):
# Updated progress bar logic for a 10.0L maximum
water_percent = max(0, min(100, (water / 10.0) * 100))
return f"""
"""
def format_alt_button(text, impact):
icon = "💡"
if "Search" in text or "Google" in text: icon = "🔍"
elif "Wikipedia" in text or "Encyclopedia" in text: icon = "📚"
elif "Expert" in text or "Quora" in text: icon = "👤"
elif "Wolfram" in text or "Geogebra" in text or "Desmos" in text: icon = "🧮"
elif "Reddit" in text or "Gutenberg" in text or "Thesaurus" in text: icon = "📝"
elif "Scholar" in text or "Database" in text or "Journals" in text: icon = "🎓"
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"
def generate_victory_dashboard(state):
try:
total_w_saved, total_e_saved, total_c_saved = 0.0, 0.0, 0.0
rows = ""
for item in state.get("history", []):
alt_name = item.get('alt_name', 'None')
saved_w = item.get('water_ml', 0.0)
saved_e = max(0.0, item.get('energy_wh', 0.0) - 0.001)
saved_c = max(0.0, item.get('co2_g', 0.0) - 0.01)
total_w_saved += saved_w
total_e_saved += saved_e
total_c_saved += saved_c
rows += f"""
"{item.get('query', '')}"
💧 {item.get('water_ml', 0):.1f} mL ⚡ {item.get('energy_wh', 0):.2f} Wh ☁️ {item.get('co2_g', 0):.2f} g
{alt_name}
💧 {saved_w:.1f} mL ⚡ {saved_e:.2f} Wh ☁️ {saved_c:.2f} g
"""
confetti_elements = "".join([f'' for _ in range(60)])
# Updated "Total Wasted" formula to 10.0 to reflect the 10L tank
return f"""
{confetti_elements}
🎉 PLANET SAVED! 🎉
Congratulations! You reached {state.get('points', 0)} points!
Planetary Savings
💧 {total_w_saved:.1f} mL Saved
⚡ {total_e_saved:.2f} Wh Saved
☁️ {total_c_saved:.2f} g Saved
Total Wasted
💧 {10.0 - state.get('water', 10.0):.2f} L
⚡ {state.get('energy', 0):.4f} kWh
☁️ {state.get('co2', 0):.2f} g
📊 AI Usage Audit Log
User Query
LLM Cost
Alternative Selected
Resources Saved
{rows}
"""
except Exception as e:
return f"
Error generating dashboard: {str(e)}
"
def generate_defeat_dashboard(state):
try:
rows = ""
for item in state.get("history", []):
rows += f"""
"{item.get('query', '')}"
💧 {item.get('water_ml', 0):.1f} mL ⚡ {item.get('energy_wh', 0):.2f} Wh ☁️ {item.get('co2_g', 0):.2f} g
"""
ash_elements = "".join([f'' for _ in range(60)])
# Updated "Total Wasted" to reflect the empty 10L tank
return f"""