File size: 9,398 Bytes
b555fe1
 
a851214
372b3f3
0cdc019
7a4002e
23fc541
46545a4
0cdc019
618f85b
eaee169
70d18af
27cc353
eaee169
0cdc019
 
 
618f85b
0cdc019
 
eaee169
46545a4
372b3f3
a851214
 
 
 
 
b555fe1
a851214
27cc353
51f1284
eaee169
 
 
 
9d998f3
 
51f1284
9d998f3
 
 
 
 
 
 
 
 
 
 
 
 
46545a4
 
 
 
 
eaee169
9d998f3
eaee169
9d998f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eaee169
 
 
 
 
46545a4
 
 
9d998f3
51f1284
eaee169
586cb7a
eaee169
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46545a4
eaee169
2d29e28
5aee751
54c70ee
b555fe1
822b684
eaee169
2c7e9af
 
 
 
 
 
 
 
eaee169
d36a0d6
46545a4
 
 
e799f84
eaee169
 
46545a4
 
 
1854cda
 
 
233f1db
c148187
1f53c6b
46545a4
 
1854cda
 
 
 
 
 
 
eaee169
1854cda
 
 
 
 
233f1db
 
1854cda
 
eaee169
1854cda
1f53c6b
 
 
 
c148187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f53c6b
70d18af
1854cda
70d18af
1f53c6b
70d18af
 
 
1f53c6b
70d18af
 
 
 
 
 
 
 
 
 
233f1db
70d18af
 
 
 
233f1db
70d18af
1854cda
b555fe1
46545a4
b555fe1
70d18af
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import streamlit as st
import pandas as pd
import google.generativeai as genai
import os
from dotenv import load_dotenv
import plotly.graph_objects as go

# Load environment variables from .env file
load_dotenv()

# Set page configuration
st.set_page_config(page_title="☀️AI-Based Solar Project Estimation Tool", layout="centered")

# Initialize Gemini with the API key
api_key = os.getenv("GOOGLE_API_KEY")
if api_key:
    genai.configure(api_key=api_key)
else:
    st.error("API key is missing. Please set the GOOGLE_API_KEY environment variable.")

# Use Gemini-1.5-Pro model
model = genai.GenerativeModel("gemini-1.5-pro")

# Load solar data
@st.cache_data
def load_data():
    df = pd.read_csv('https://huggingface.co/spaces/MLDeveloper/AI_based_Solar_Project_Estimation_Tool/resolve/main/solar_data_india_2024.csv')
    return df

df = load_data()

# Build prompt for Gemini
# Build prompt for Gemini
def build_prompt(location, project_type, roof_size=None, desired_kwh=None, electricity_bill=None, ghi=None, solar_cost_per_kw=None):
    if project_type == "Rooftop Solar":
        prompt = f"""
You are an AI-based solar project estimator.
Use the following calculation methods:
- Estimated system size (kW) = Roof size (sq meters) × 0.10
- Estimated daily solar output (kWh) = System size (kW) × Average GHI (kWh/m²/day)
- Total system cost (₹) = System size (kW) × Solar system cost per kW
- Assume tariff rate = ₹7/kWh
- Monthly savings (₹) = Estimated daily output × 30 × 7
- Payback period (years) = Total system cost ÷ (Monthly savings × 12)
Inputs:
- Project Type: Rooftop Solar
- Location: {location}
- Roof Size: {roof_size} sq meters
- Monthly Electricity Bill: ₹{electricity_bill}
- Average GHI: {ghi} kWh/m²/day
- Solar System Cost per kW: ₹{solar_cost_per_kw}
Now, calculate and return strictly in this format:
Estimated solar system size in kW: <value>
Estimated daily solar output in kWh: <value>
Total system cost in ₹: <value>
Monthly savings in ₹: <value>
Payback period in years: <value>
"""
    else:
        prompt = f"""
You are an AI-based solar project estimator.
Use the following calculation methods:
- Required system size (kW) = Desired monthly solar production ÷ (30 × Average GHI)
- Estimated daily solar output (kWh) = System size (kW) × Average GHI (kWh/m²/day)
- Total system cost (₹) = System size (kW) × Solar system cost per kW
- Assume tariff rate = ₹7/kWh
- Monthly savings (₹) = Estimated daily output × 30 × 7
- Payback period (years) = Total system cost ÷ (Monthly savings × 12)
Inputs:
- Project Type: Ground Mount Solar
- Location: {location}
- Desired Monthly Solar Production: {desired_kwh} kWh
- Monthly Electricity Bill: ₹{electricity_bill}
- Average GHI: {ghi} kWh/m²/day
- Solar System Cost per kW: ₹{solar_cost_per_kw}
Now, calculate and return strictly in this format:
Required solar system size in kW: <value>
Estimated daily solar output in kWh: <value>
Total system cost in ₹: <value>
Monthly savings in ₹: <value>
Payback period in years: <value>
"""
    return prompt



# UI - Form for user input
st.title("☀️AI-Based Solar Project Estimation Tool")
st.write("### Enter Your Details Below:")

with st.form("solar_form"):
    state_options = df['State'].dropna().unique()
    
    location = st.selectbox("Select your State", options=sorted(state_options))
    
    project_type = st.radio(
        "Select Solar Project Type",
        options=["Rooftop Solar", "Ground Mount Solar"]
    )

    if project_type == "Rooftop Solar":
        roof_size = st.number_input("Enter your roof size (in sq meters)", min_value=1)
        electricity_bill = st.number_input("Enter your monthly electricity bill (₹)", min_value=0)
        desired_kwh = None
    else:
        desired_kwh = st.number_input("Enter desired monthly solar electricity production (kWh)", min_value=1)
        electricity_bill = st.number_input("Enter your monthly electricity bill (₹)", min_value=0)
        roof_size = None

    submitted = st.form_submit_button("Get Estimate")

# Generate the solar project estimate via Gemini
if submitted and location:
    state_data = df[df['State'].str.contains(location, case=False)].iloc[0]
    
    if state_data is not None:
        ghi = state_data['Avg_GHI (kWh/m²/day)']
        solar_cost_per_kw = state_data['Solar_Cost_per_kW (₹)']

        # Check roof size limit for rooftop solar
        if project_type == "Rooftop Solar" and roof_size:
            max_allowed_kw = roof_size * 0.15
            if max_allowed_kw > 5:  # Maximum 5 kW limit
                st.warning(f"Roof size exceeds the maximum allowed capacity of 5 kW. The system size will be limited to 5 kW.")
                max_allowed_kw = 5
            roof_size = max_allowed_kw / 0.15  # Adjust roof size to fit within the limit

        prompt_text = build_prompt(location, project_type, roof_size=roof_size, desired_kwh=desired_kwh, electricity_bill=electricity_bill, ghi=ghi, solar_cost_per_kw=solar_cost_per_kw)
        
        # Call Gemini API
        with st.spinner("Generating solar estimate with Gemini..."):
            response = model.generate_content(prompt_text)
        
        # Display structured output
        st.subheader("🔹 Solar Project Estimate")
        
        estimated_data = response.text.strip().split("\n")
        
        system_size_kw = None
        monthly_savings_rs = None
        total_system_cost = None
        payback_period_years = None
        daily_output_kwh = None

        for point in estimated_data:
            if ":" in point:
                try:
                    key, value = point.split(":", 1)
                    key = key.strip()
                    value = value.strip()
                    
                    st.write(f"**{key}**: {value}")

                    if "Estimated solar system size" in key or "Required solar system size" in key:
                        system_size_kw = float(value.split()[0])
                    if "Monthly savings" in key:
                        monthly_savings_rs = float(value.split()[0])
                    if "Total system cost" in key:
                        total_system_cost = float(value.split()[0])
                    if "Payback period" in key:
                        payback_period_years = float(value.split()[0])

                except ValueError:
                    st.warning("There was an issue processing the response. Please try again.")

        # Calculate Daily Output in kWh
        if system_size_kw is not None and ghi is not None:
            daily_output_kwh = system_size_kw * ghi  # Estimate daily output in kWh
        
        # Show the formulas
        st.subheader("🧮 Formulas Used:")

        if project_type == "Rooftop Solar":
            st.markdown(f"""
            **For Rooftop Solar:**
            - Estimated Solar System Size (kW) = Roof Size (m²) × 0.15
            - Estimated Daily Solar Output (kWh) = System Size (kW) × Average GHI (kWh/m²/day)
            - Total System Cost (₹) = System Size (kW) × Solar Cost per kW (₹)
            - Monthly Savings (₹) = (Estimated Daily Output × 30 × Tariff Rate per kWh) [Approximate]
            - Payback Period (years) = Total System Cost ÷ (Monthly Savings × 12)
            """)
        else:
            st.markdown(f"""
            **For Ground Mount Solar:**
            - Required Solar System Size (kW) = Desired Monthly Solar Production ÷ (30 × Average GHI)
            - Estimated Daily Solar Output (kWh) = System Size (kW) × Average GHI (kWh/m²/day)
            - Total System Cost (₹) = System Size (kW) × Solar Cost per kW (₹)
            - Monthly Savings (₹) = (Estimated Daily Output × 30 × Tariff Rate per kWh) [Approximate]
            - Payback Period (years) = Total System Cost ÷ (Monthly Savings × 12)
            """)
        
        st.info("Note: Tariff rate is assumed based on your state electricity average or ₹7/kWh (default).")

        # Visual Summary - Grouped Bar Chart
        if system_size_kw is not None and total_system_cost is not None:
            st.subheader("📊 Visual Summary")
            
            fig = go.Figure(data=[ 
                go.Bar(
                    name="System Size (kW)",
                    x=["Solar System Size", "Daily Output", "Total Cost", "Monthly Savings", "Payback Period"],
                    y=[system_size_kw, daily_output_kwh , total_system_cost, monthly_savings_rs, payback_period_years],
                    marker_color='#636EFA'
                ),
                go.Bar(
                    name="Financials",
                    x=["Solar System Size", "Daily Output", "Total Cost", "Monthly Savings", "Payback Period"],
                    y=[0, 0, total_system_cost, monthly_savings_rs, payback_period_years],
                    marker_color='#00CC96'
                )
            ])
            
            fig.update_layout(
                barmode='group',
                title="Comparison of Solar System Parameters",
                yaxis_title="Values",
                xaxis_title="Parameters"
            )
            st.plotly_chart(fig, use_container_width=True)

    else:
        st.error("Sorry, the location entered does not match any available data.")
else:
    st.warning("Please fill out all fields to see your solar project estimate.")