File size: 4,335 Bytes
4a9ac34
 
 
 
 
 
2e8e0c0
1ad33b7
2e8e0c0
 
 
 
 
 
1ad33b7
 
2e8e0c0
 
 
4a9ac34
2e8e0c0
4a9ac34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299f487
4a9ac34
 
2e8e0c0
4a9ac34
 
299f487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a9ac34
 
 
299f487
4a9ac34
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import gradio as gr
import pandas as pd
import random
from transformers import AutoTokenizer, AutoModelForCausalLM
import plotly.graph_objects as go

# Attempt to import PyTorch
try:
    import torch
except ImportError:
    torch = None

# Load GPT-2 model if PyTorch is available
if torch:
    tokenizer = AutoTokenizer.from_pretrained("gpt2")
    model = AutoModelForCausalLM.from_pretrained("gpt2")
else:
    tokenizer, model = None, None
    print("PyTorch not available. GPT-2 model will not be loaded.")

# Analyze energy data and provide consumption details, recommendations, and weather tips
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  # Approx kg of CO2 per kWh
    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
    )

# Build the Gradio UI
def build_ui():
    with gr.Blocks() as demo:
        gr.Markdown("## Energy Consumption Analyzer")
        
        with gr.Row():
            energy_data = gr.Textbox(
                label="Enter Energy Data",
                placeholder="e.g., AC: 500 kWh\nRefrigerator: 300 kWh",
                lines=5
            )
            location = gr.Textbox(label="Enter Location", placeholder="e.g., Lahore")
            language = gr.Dropdown(
                label="Select Language",
                choices=["English", "Urdu"],
                value="English"
            )

        with gr.Row():
            analyze_button = gr.Button("Analyze")

        with gr.Row():
            output_bill = gr.Text(label="Estimated Bill")
            output_recommendations = gr.Text(label="Recommendations")

        with gr.Row():
            output_weather_tips = gr.Text(label="Weather Tips")
            output_alerts = gr.Text(label="Alerts")
            output_carbon_footprint = gr.Text(label="Carbon Footprint")
            output_ai_recommendation = gr.Text(label="AI Recommendations")

        analyze_button.click(
            analyze_energy_data,
            inputs=[energy_data, location, language],
            outputs=[
                output_bill,
                output_recommendations,
                output_weather_tips,
                output_alerts,
                output_carbon_footprint,
                output_ai_recommendation
            ]
        )

    return demo

# Launch the Gradio app
demo = build_ui()
demo.launch()