Update app.py
Browse files1 unmodified line23456789101112131415161718192021222324252627282930313233341 unmodified line3637383940414243444546474849505152535455562 unmodified lines596061626364656667686970717273747576777879808182838485868788891 unmodified lineimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport openaiimport streamlit as stimport pandas as pdimport requests# 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')# Set up the Gemini API key (replace with your actual Gemini API key)GEMINI_API_KEY = 'AIzaSyAGGP8I7c0YmA8xKZsEdAF9AF3ElaPoEn4'# Set the API endpoint for GeminiGEMINI_API_URL = "https://gemini.googleapis.com/v1/completions" # Example URL, please check the actual URL# Streamlit UIst.set_page_config(page_title="AI-based Solar Project Estimation Tool", layout="centered")st.title("AI-based Solar Project Estimation Tool")# Center all input widgetsst.write("### Enter Your Details Below:")with st.form("solar_form"):# Get the list of unique states from the datasetstate_options = df['State'].dropna().unique()# Input widgetslocation = 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)1 unmodified linesubmitted = st.form_submit_button("Get Estimate")if submitted and location and roof_size > 0 and electricity_bill >= 0:# Fetch state data from the datasetstate_data = df[df['State'].str.contains(location, case=False)].iloc[0] # Get the first matchif state_data is not None:ghi = state_data['Avg_GHI (kWh/m²/day)']solar_cost_per_kw = state_data['Solar_Cost_per_kW (₹)']# Use Gemini API to generate solar project estimate (cost, savings, payback period)prompt = f"""Estimate the solar system for the location '{location}' based on the following details:Roof size: {roof_size} sq metersMonthly electricity bill: ₹{electricity_bill}Average GHI (solar radiation) for {location}: {ghi} kWh/m²/daySolar system cost per kW in {location}: ₹{solar_cost_per_kw}Provide:1. Estimated solar system size in kW2. Estimated daily solar output in kWh2 unmodified lines5. Payback period in years"""# Request to Gemini API (Adjust headers and body according to Gemini API documentation)response = requests.post(GEMINI_API_URL,headers={"Authorization": f"Bearer {GEMINI_API_KEY}","Content-Type": "application/json"},json={"model": "gemini-model-xyz", # Use the actual Gemini model name"prompt": prompt,"max_tokens": 250,"temperature": 0.7,"top_p": 1.0,"n": 1})# Check for successful responseif response.status_code == 200:result = response.json().get("choices", [])[0].get("text", "").strip()# Display the response from the Gemini modelst.subheader("Estimated Solar System Details:")st.write(result)else:st.error(f"Error: {response.status_code}. Unable to get response from Gemini API.")else:st.error("Sorry, the location entered does not match any available data.")1 unmodified line2345678910111213141516171819202122232425262728293031321 unmodified line343536373839404142434445464748495051522 unmodified lines5556575859606162636465666768697071727374757677787980818283848586871 unmodified lineimport 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"):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)1 unmodified linesubmitted = 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]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 = 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 kWh2 unmodified lines5. 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.")
app.py+43-45