Update app.py
Browse files1234567891011121314151617181920212223242526275 unmodified lines3334353637381 unmodified line4041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889import streamlit as stimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport osimport requestsfrom dotenv import load_dotenv# Load environment variables from .env fileload_dotenv()# Get the Gemini API key from the environmentGEMINI_API_KEY = os.getenv("GEMINI_API_KEY")# Gemini API URLGEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent"# Load the solar data CSV filedf = pd.read_csv('https://huggingface.co/spaces/MLDeveloper/AI_based_Solar_Project_Estimation_Tool/resolve/main/solar_data_india_2024.csv')# Streamlit UIst.set_page_config(page_title="AI-based Solar Project Estimation Tool", layout="centered")st.title("AI-based Solar Project Estimation Tool")st.write("### Enter Your Details Below:")with st.form("solar_form"):5 unmodified linessubmitted = st.form_submit_button("Get Estimate")if submitted and location and roof_size > 0 and electricity_bill >= 0:state_data = df[df['State'].str.contains(location, case=False)].iloc[0]1 unmodified lineghi = state_data['Avg_GHI (kWh/m²/day)']solar_cost_per_kw = state_data['Solar_Cost_per_kW (₹)']prompt_text = f"""Estimate the solar system for the location '{location}' based on the following details:- Roof size: {roof_size} sq meters- Monthly electricity bill: ₹{electricity_bill}- Average GHI (solar radiation) for {location}: {ghi} kWh/m²/day- Solar system cost per kW in {location}: ₹{solar_cost_per_kw}Provide: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 years"""# Define the headers for the API requestheaders = {"Authorization": f"Bearer {GEMINI_API_KEY}","Content-Type": "application/json"}# Define the request payloadpayload = {"model": "gemini-1.5-flash","messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": prompt_text}],"temperature": 0.7}# Make the API requestresponse = requests.post(GEMINI_API_URL, json=payload, headers=headers)# Check the response from the APIif response.status_code == 200:result = response.json()generated_content = result['choices'][0]['message']['content']# Display the generated content (solar estimates)st.subheader("Solar Project Estimate")st.write(generated_content)else:st.error(f"Error: {response.status_code} - {response.text}")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.")1234567891011121314151617181920212223245 unmodified lines303132333435363738394041424344454647484950515253541 unmodified line5657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101import streamlit as stimport pandas as pdimport google.generativeai as genaiimport osfrom io import StringIO# Initialize Geminigenai.configure(api_key=os.getenv("GEMINI_API_KEY"))model = genai.GenerativeModel("gemini-1.5-flash")# Load solar data@st.cache_datadef 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 dfdf = load_data()# UI - Form for user inputst.set_page_config(page_title="AI-based Solar Project Estimation Tool", layout="centered")st.title("AI-based Solar Project Estimation Tool")st.write("### Enter Your Details Below:")with st.form("solar_form"):5 unmodified linessubmitted = st.form_submit_button("Get Estimate")# Build the prompt for Geminidef build_prompt(location, roof_size, electricity_bill, ghi, solar_cost_per_kw):prompt = f"""Estimate the solar system for the location '{location}' based on the following details:- Roof size: {roof_size} sq meters- Monthly electricity bill: ₹{electricity_bill}- Average GHI (solar radiation) for {location}: {ghi} kWh/m²/day- Solar system cost per kW in {location}: ₹{solar_cost_per_kw}Provide: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 years"""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]1 unmodified lineghi = 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)if prompt_text:with st.spinner("Generating solar estimate with Gemini..."):response = model.generate_content(prompt_text)st.subheader("Solar Project Estimate")st.text_area("Generated Estimate", response.text, height=200)else:st.warning("Please check the inputs again.")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.")# Batch CSV Exportst.markdown("### Export Solar Estimates")batch = st.number_input("How many estimates to generate?", min_value=1, max_value=100, value=5)if st.button("Generate Batch & Download CSV"):if location and roof_size > 0 and electricity_bill >= 0:csv_buffer = StringIO()writer = csv.writer(csv_buffer)writer.writerow(["Sequence_no", "Solar Estimate"])with st.spinner("Generating estimates..."):for i in range(1, batch + 1):state_data = df[df['State'].str.contains(location, case=False)].iloc[0]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)# Generate the estimate using Geminiresponse = model.generate_content(prompt_text)writer.writerow([i, response.text.strip()])st.download_button(label="Download Solar Estimates CSV",data=csv_buffer.getvalue(),file_name="solar_estimates.csv",mime="text/csv")else:st.warning("Please fill out all fields to generate batch estimates.")
app.py+68-56