Update app.py
Browse files3 unmodified lines45678910111213141516171819202122233 unmodified lines272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101113 unmodified linesimport osfrom dotenv import load_dotenv# Load environment variablesload_dotenv()# Set page configurationst.set_page_config(page_title="AI-based Solar Project Estimation Tool", layout="centered")# Initialize Geminiapi_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.")model = genai.GenerativeModel("gemini-1.5-flash")# Load solar data@st.cache_data3 unmodified linesdf = load_data()# Solar Calculation Function (not relying on Gemini for calculation)def calculate_solar_estimate(roof_size, monthly_bill, electricity_price, ghi, cost_per_kw):daily_consumption_inr = monthly_bill / 30daily_consumption_kwh = daily_consumption_inr / electricity_price# Assume system size based on consumptionestimated_system_size_kw = 3 # Fixed for now as realistic estimatepeak_sun_hours = ghi # Use GHI as sun hours (approximation)daily_solar_output_kwh = estimated_system_size_kw * peak_sun_hours * 0.75 # considering derating factortotal_system_cost = estimated_system_size_kw * cost_per_kwmonthly_generation_kwh = daily_solar_output_kwh * 30monthly_savings_inr = monthly_generation_kwh * electricity_priceannual_savings_inr = monthly_savings_inr * 12payback_period_years = total_system_cost / annual_savings_inrreturn {"Estimated solar system size in kW": round(estimated_system_size_kw, 2),"Estimated daily solar output in kWh": round(daily_solar_output_kwh, 2),"Total system cost in ₹": int(total_system_cost),"Monthly savings in ₹": int(monthly_savings_inr),"Payback period in years": round(payback_period_years, 2)}# UI - Formst.title("AI-based Solar Project Estimation Tool")st.write("### Enter Your Details:")with st.form("solar_form"):state_options = df['State'].dropna().unique()location = st.selectbox("Select your State", options=sorted(state_options))roof_size = st.number_input("Enter your roof size (in sq meters)", min_value=1)monthly_bill = st.number_input("Enter your monthly electricity bill (₹)", min_value=0)submitted = st.form_submit_button("Get Estimate")if submitted and location and roof_size > 0 and monthly_bill >= 0: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 (₹)']electricity_price = 8 # Assume ₹8/kWh# Calculate estimatesestimates = calculate_solar_estimate(roof_size, monthly_bill, electricity_price, ghi, solar_cost_per_kw)# Build clean prompt for Gemini to verify the calculationprompt = f"""ONLY output these 5 points based on inputs:1. Estimated solar system size in kW2. Estimated daily solar output in kWh3. Total system cost in ₹4. Monthly savings in ₹5. Payback period in yearsRoof size = {roof_size} sq metersMonthly bill = ₹{monthly_bill}GHI = {ghi} kWh/m²/daySolar system cost per kW = ₹{solar_cost_per_kw}Use no description. Only numeric values clearly."""# Call Gemini API (just to double-check/validate if you want)with st.spinner("Generating final estimate..."):gemini_response = model.generate_content(prompt)final_response = gemini_response.text.strip()# Display calculated values directly (without trusting Gemini text output)st.subheader("Solar Project Estimate")for key, value in estimates.items():st.write(f"{key}: {value}")else:st.error("Location data not found. Please select a valid state.")else:st.warning("Please fill all the fields.")3 unmodified lines4567891011121314151617181920212223243 unmodified lines282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990913 unmodified linesimport osfrom dotenv import load_dotenv# Load environment variables from .env fileload_dotenv()# Set page configuration firstst.set_page_config(page_title="AI-based Solar Project Estimation Tool", layout="centered")# Initialize Gemini with the API key loaded from the .env fileapi_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 better model: gemini-1.5-promodel = genai.GenerativeModel("gemini-1.5-pro")# Load solar data@st.cache_data3 unmodified linesdf = load_data()# UI - Form for user inputst.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))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)submitted = st.form_submit_button("Get Estimate")# Build the clean prompt for Geminidef build_prompt(location, roof_size, electricity_bill, ghi, solar_cost_per_kw):prompt = f"""You are a solar project estimator tool. Based on the following details, calculate and return only the values without any extra description:Location: {location}Roof size: {roof_size} sq metersMonthly electricity bill: ₹{electricity_bill}Average GHI: {ghi} kWh/m²/daySolar system cost per kW: ₹{solar_cost_per_kw}Respond strictly in this format (do not add anything extra):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>"""return prompt# Generate the solar project estimate via Geminiif submitted and location and roof_size > 0 and electricity_bill >= 0: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 (₹)']prompt_text = build_prompt(location, roof_size, electricity_bill, ghi, solar_cost_per_kw)# Call Gemini APIwith st.spinner("Generating solar estimate with Gemini..."):response = model.generate_content(prompt_text)# Display clean structured outputst.subheader("Solar Project Estimate")estimated_data = response.text.strip().split("\n")for point in estimated_data:if ":" in point:key, value = point.split(":", 1)st.write(f"**{key.strip()}**: {value.strip()}")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.")
app.py+45-65