DAM_ANALYSIS / app.py
rajkhanke's picture
Upload 4 files
643b9da verified
import os
import json
import pandas as pd
import requests
from flask import Flask, render_template, request, jsonify
from dotenv import load_dotenv
import google.generativeai as genai
load_dotenv()
app = Flask(__name__)
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
CSV_PATH = "dam.csv"
# Initialize Gemini API
genai.configure(api_key=GOOGLE_API_KEY)
gemini_model = genai.GenerativeModel('gemini-1.5-flash')
# Load dams CSV with latitude, longitude, dam_name columns
dams_df = pd.read_csv(CSV_PATH)
dams_df['latitude'] = pd.to_numeric(dams_df['latitude'], errors='coerce')
dams_df['longitude'] = pd.to_numeric(dams_df['longitude'], errors='coerce')
dams_df.dropna(subset=['latitude', 'longitude', 'dam_name'], inplace=True)
@app.route('/')
def index():
dams = dams_df.to_dict(orient='records')
return render_template('index.html', dams=dams)
@app.route('/dam_details', methods=['POST'])
def dam_details():
data = request.json
dam_name = data.get('dam_name')
lat = data.get('latitude')
lon = data.get('longitude')
current_level = data.get('current_water_level')
# Gemini: Get dam info
prompt = f"""
Provide the following information for the dam "{dam_name}" in JSON format:
{{
"capacity_mcm": "N/A if unknown",
"number_of_spillway_gates": "N/A if unknown",
"gate_type": "N/A if unknown",
"dam_height_meters": "N/A if unknown",
"purpose": "N/A if unknown",
"river_name": "N/A if unknown",
"country": "N/A if unknown"
}}
"""
try:
response = gemini_model.generate_content(prompt)
text = response.text.strip()
# Extract JSON from response text
json_start = text.find('{')
json_end = text.rfind('}') + 1
dam_info = json.loads(text[json_start:json_end])
except Exception as e:
return jsonify({"error": f"Gemini API error: {e}"})
# Fetch rainfall forecast
try:
forecast_url = "https://api.open-meteo.com/v1/forecast"
params = {
"latitude": lat,
"longitude": lon,
"daily": "precipitation_sum",
"forecast_days": 10,
"timezone": "auto"
}
r = requests.get(forecast_url, params=params, timeout=10)
r.raise_for_status()
forecast_data = r.json()
dates = forecast_data['daily']['time']
rain = forecast_data['daily']['precipitation_sum']
rainfall_list = [{"date": d, "rainfall_mm": v} for d, v in zip(dates, rain)]
except Exception as e:
return jsonify({"error": f"Rainfall API error: {e}"})
# Prepare prompt for operational advice
rain_summary = "\n".join([f"{r['date']}: {r['rainfall_mm']} mm" for r in rainfall_list])
advice_prompt = f"""
You are an expert dam operations advisor. For the dam "{dam_name}", here is the info:
Capacity (MCM): {dam_info.get('capacity_mcm', 'N/A')}
Spillway gates: {dam_info.get('number_of_spillway_gates', 'N/A')} ({dam_info.get('gate_type', 'N/A')})
Height: {dam_info.get('dam_height_meters', 'N/A')} meters
Purpose: {dam_info.get('purpose', 'N/A')}
River: {dam_info.get('river_name', 'N/A')}
Country: {dam_info.get('country', 'N/A')}
Current water level: {current_level} % of capacity.
Rainfall forecast for next 10 days:
{rain_summary}
Based on this data, provide operational recommendations with key performance indicators (KPIs).
Format your response with:
KEY RECOMMENDATIONS:
- Overall Status: [NORMAL, WATCH, WARNING, EMERGENCY]
- Action Required: [MAINTAIN CURRENT, OPEN GATES, CLOSE GATES, MONITOR CLOSELY]
- Urgency and timing if opening gates
- Suggested % of gate opening
- Other notes
"""
try:
advice_resp = gemini_model.generate_content(advice_prompt)
advice_text = advice_resp.text.strip()
except Exception as e:
advice_text = f"Error generating advice: {e}"
return jsonify({
"dam_info": dam_info,
"rainfall_forecast": rainfall_list,
"operational_advice": advice_text
})
if __name__ == "__main__":
app.run(debug=True)