|
import gradio as gr |
|
import pandas as pd |
|
import random |
|
from transformers import AutoTokenizer, AutoModelForCausalLM |
|
import plotly.graph_objects as go |
|
|
|
|
|
tokenizer = AutoTokenizer.from_pretrained("gpt2") |
|
model = AutoModelForCausalLM.from_pretrained("gpt2") |
|
|
|
|
|
def analyze_energy_data(energy_data, location, language): |
|
appliances = {} |
|
total_kwh = 0 |
|
peak_hours_rate = 20 |
|
off_peak_hours_rate = 12 |
|
benchmarks = {"AC": 400, "Refrigerator": 200, "Lighting": 150, "Fan": 100} |
|
alerts = [] |
|
|
|
try: |
|
for line in energy_data.strip().split("\n"): |
|
appliance, kwh = line.split(":") |
|
kwh_value = float(kwh.strip().split(" ")[0]) |
|
appliances[appliance.strip()] = kwh_value |
|
total_kwh += kwh_value |
|
|
|
if appliance.strip() in benchmarks and kwh_value > benchmarks[appliance.strip()]: |
|
alert_message = ( |
|
f"Your {appliance.strip()} usage exceeds the limit by " |
|
f"{kwh_value - benchmarks[appliance.strip()]:.2f} kWh." |
|
) |
|
alerts.append(alert_message) |
|
|
|
except Exception: |
|
return ( |
|
"Error: Enter data in the correct format (e.g., AC: 500 kWh).", |
|
"", |
|
"", |
|
"", |
|
"", |
|
"", |
|
"", |
|
0.0 |
|
) |
|
|
|
total_bill = total_kwh * peak_hours_rate |
|
optimized_bill = sum( |
|
appliances[app] * (off_peak_hours_rate if app in ["AC", "Refrigerator"] else peak_hours_rate) |
|
for app in appliances |
|
) |
|
savings = total_bill - optimized_bill |
|
carbon_emissions = total_kwh * 0.707 |
|
weather_tips = ( |
|
f"Considering high temperatures in {location}, keep windows closed during peak heat hours to optimize cooling." |
|
if "Lahore" in location |
|
else "Check local weather to optimize energy usage." |
|
) |
|
|
|
return ( |
|
f"Your current bill is PKR {total_bill:.2f}, potentially saving PKR {savings:.2f}.", |
|
"\n".join([f"{appliance}: {random.choice(['Use during off-peak hours.', 'Turn off when not in use.'])}" for appliance in appliances]), |
|
weather_tips, |
|
"\n".join(alerts), |
|
f"Your carbon footprint: {carbon_emissions:.2f} kg of CO2. Consider using renewable energy.", |
|
f"AI Recommendation: Optimize usage of AC and lighting based on peak hours to reduce costs and emissions.", |
|
savings |
|
) |
|
|
|
|
|
leaderboard = {"User1": 30, "User2": 25, "User3": 20} |
|
|
|
def update_leaderboard(user_name, reduction_percentage): |
|
leaderboard[user_name] = leaderboard.get(user_name, 0) + reduction_percentage |
|
sorted_leaderboard = sorted(leaderboard.items(), key=lambda x: x[1], reverse=True) |
|
leaderboard_text = "\n".join([f"{i+1}. {user}: {points} points" for i, (user, points) in enumerate(sorted_leaderboard)]) |
|
badge = "Gold" if reduction_percentage > 30 else "Silver" if reduction_percentage > 20 else "Bronze" |
|
return leaderboard_text, f"Badge earned: {badge}" |
|
|
|
|
|
def fetch_smart_device_data(): |
|
data = { |
|
"AC": random.randint(350, 500), |
|
"Lighting": random.randint(100, 200), |
|
"Refrigerator": random.randint(180, 250), |
|
} |
|
return "\n".join([f"{k}: {v} kWh" for k, v in data.items()]) |
|
|
|
|
|
def visualize_energy_data(appliances): |
|
df = pd.DataFrame(appliances.items(), columns=["Appliance", "Energy (kWh)"]) |
|
fig = go.Figure(data=[go.Bar( |
|
x=df["Appliance"], |
|
y=df["Energy (kWh)"], |
|
marker=dict(color=['#FF6347' if x > 300 else '#32CD32' for x in df["Energy (kWh)"]]) |
|
)]) |
|
fig.update_layout( |
|
title="Appliance-wise Energy Usage", |
|
xaxis_title="Appliance", |
|
yaxis_title="Energy (kWh)", |
|
hovermode='x unified', |
|
) |
|
return fig |
|
|
|
|
|
def calculate_roi(initial_investment, savings): |
|
try: |
|
roi = (savings / initial_investment) * 100 |
|
except ZeroDivisionError: |
|
roi = 0.0 |
|
return f"Your ROI is {roi:.2f}% based on an initial investment of {initial_investment} PKR and savings of {savings:.2f} PKR." |
|
|
|
|
|
def chatbot_interface(home_size, location, energy_data, language, user_name, reduction_percentage, initial_investment): |
|
energy_analysis, tips, weather_tips, alerts, carbon_output, ai_recommendation, savings = analyze_energy_data(energy_data, location, language) |
|
appliances = { |
|
appliance: float(kwh.strip(" kWh")) |
|
for appliance, kwh in [line.split(":") for line in energy_data.strip().split("\n")] |
|
} |
|
energy_chart = visualize_energy_data(appliances) |
|
leaderboard_text, badge = update_leaderboard(user_name, reduction_percentage) |
|
roi_output = calculate_roi(initial_investment, savings) |
|
return energy_analysis, tips, weather_tips, alerts, carbon_output, ai_recommendation, energy_chart, leaderboard_text, badge, roi_output |
|
|
|
|
|
def build_ui(): |
|
with gr.Blocks() as demo: |
|
with gr.Row(): |
|
home_size = gr.Slider(minimum=500, maximum=5000, step=100, label="Home Size (sq ft)", value=1200) |
|
location = gr.Textbox(label="Location (City)", placeholder="Enter your city...", info="Specify the city to get weather-based tips.") |
|
energy_data = gr.Textbox( |
|
label="Energy Data (Appliance: kWh)", |
|
placeholder="e.g., AC: 500 kWh\nLighting: 120 kWh\nRefrigerator: 150 kWh", |
|
lines=5, |
|
info="Enter your appliances and their energy usage." |
|
) |
|
language = gr.Radio(choices=["English", "Urdu"], label="Language") |
|
|
|
with gr.Row(): |
|
user_name = gr.Textbox(label="Your Name", placeholder="Enter your name...", info="Provide your name to track performance.") |
|
reduction_percentage = gr.Slider(minimum=0, maximum=50, step=1, label="Energy Reduction (%)", value=10) |
|
initial_investment = gr.Number(label="Initial Investment (PKR)", value=10000) |
|
|
|
fetch_data_button = gr.Button("Fetch Smart Device Data") |
|
fetch_data_output = gr.Textbox(label="Smart Device Data", interactive=False) |
|
|
|
fetch_data_button.click(fetch_smart_device_data, inputs=[], outputs=fetch_data_output) |
|
|
|
submit_button = gr.Button("Analyze", variant="primary", elem_id="submit-button") |
|
|
|
with gr.Row(): |
|
energy_output = gr.Textbox(label="Energy Consumption Analysis", interactive=False) |
|
tips_output = gr.Textbox(label="Optimization Tips", interactive=False) |
|
weather_output = gr.Textbox(label="Weather-specific Tips", interactive=False) |
|
alerts_output = gr.Textbox(label="Alerts", interactive=False) |
|
ai_recommendations = gr.Textbox(label="AI Recommendations", interactive=False) |
|
|
|
with gr.Row(): |
|
carbon_output = gr.Textbox(label="Carbon Footprint", interactive=False) |
|
energy_chart = gr.Plot(label="Energy Visualization") |
|
|
|
with gr.Row(): |
|
leaderboard_output = gr.Textbox(label="Leaderboard", interactive=False) |
|
badge_output = gr.Textbox(label="Your Badge", interactive=False) |
|
|
|
with gr.Row(): |
|
roi_output = gr.Textbox(label="Return on Investment (ROI)", interactive=False) |
|
|
|
submit_button.click( |
|
chatbot_interface, |
|
inputs=[home_size, location, energy_data, language, user_name, reduction_percentage, initial_investment], |
|
outputs=[energy_output, tips_output, weather_output, alerts_output, carbon_output, ai_recommendations, energy_chart, leaderboard_output, badge_output, roi_output] |
|
) |
|
|
|
return demo |
|
|
|
demo = build_ui() |
|
demo.launch() |
|
|