Flood_Detection / app.py
CodeNine's picture
Update app.py
ccc9eb4 verified
raw
history blame
5.25 kB
import gradio as gr
import os
import requests
import json
from datetime import datetime
# Configuration
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
MODEL = "llama3-70b-8192"
API_URL = "https://api.groq.com/openai/v1/chat/completions"
def get_risk_color(risk_level):
"""Return color based on risk level"""
colors = {
"HIGH": "#ff4d4d", # Red
"MEDIUM": "#ffa64d", # Orange
"LOW": "#4dff4d", # Green
}
return colors.get(risk_level.upper(), "#666666")
def analyze_flood(location, water_level, rainfall, historical_data):
"""Enhanced flood analysis with structured output"""
prompt = f"""
As a hydrology expert, analyze flood risk for:
Location: {location}
Water Level: {water_level}m
Rainfall: {rainfall}mm
Historical Data: {'Available' if historical_data else 'Not available'}
Respond in JSON format with:
- risk_level (HIGH/MEDIUM/LOW)
- summary (1 sentence)
- detailed_analysis (3-5 bullet points)
- recommended_actions (3 bullet points)
- confidence (percentage)
"""
try:
response = requests.post(
API_URL,
headers={
"Authorization": f"Bearer {GROQ_API_KEY}",
"Content-Type": "application/json"
},
json={
"model": MODEL,
"messages": [
{
"role": "system",
"content": "You are a flood risk analysis AI. Respond in valid JSON format."
},
{
"role": "user",
"content": prompt
}
],
"response_format": {"type": "json_object"}
},
timeout=10
)
response.raise_for_status()
result = json.loads(response.json()["choices"][0]["message"]["content"])
return format_output(result)
except Exception as e:
return format_output({"error": str(e)})
def format_output(data):
"""Format the API response for Gradio display"""
if "error" in data:
return {
"Risk Level": "ERROR",
"Summary": data["error"],
"Details": "Failed to get analysis",
"Actions": "Please try again later"
}
risk_level = data.get("risk_level", "UNKNOWN")
color = get_risk_color(risk_level)
return {
"Risk Level": f"<span style='color: {color}; font-weight: bold'>{risk_level}</span>",
"Summary": data.get("summary", "No summary available"),
"Detailed Analysis": "\n".join([f"β€’ {point}" for point in data.get("detailed_analysis", [])]),
"Recommended Actions": "\n".join([f"β€’ {action}" for action in data.get("recommended_actions", [])]),
"Confidence": f"{data.get('confidence', 'N/A')}%"
}
# Gradio Interface
with gr.Blocks(theme=gr.themes.Soft(), title="Flood Risk Analyzer") as app:
# Header
gr.Markdown("""
<div style='text-align: center'>
<h1>🌊 Flood Risk Assessment</h1>
<p>Instant flood risk analysis powered by Groq AI</p>
</div>
""")
# Input Section
with gr.Row():
with gr.Column():
gr.Markdown("### πŸ“ Enter Location Details")
location = gr.Textbox(label="City/Region")
water_level = gr.Slider(0, 15, step=0.1, label="Water Level (meters)")
rainfall = gr.Slider(0, 500, step=5, label="24h Rainfall (mm)")
historical = gr.Checkbox(label="Include historical flood data")
submit_btn = gr.Button("Analyze Risk", variant="primary")
# Output Section
with gr.Row():
with gr.Column():
gr.Markdown("### 🚨 Risk Overview")
risk_level = gr.HTML(label="Risk Level")
summary = gr.Textbox(label="Summary", interactive=False)
with gr.Accordion("πŸ“Š Detailed Analysis", open=False):
details = gr.Markdown()
with gr.Accordion("πŸ›‘οΈ Recommended Actions", open=False):
actions = gr.Markdown()
confidence = gr.Textbox(label="Confidence Level", interactive=False)
# Examples
gr.Markdown("### πŸ§ͺ Example Scenarios")
gr.Examples(
examples=[
["Karachi, Pakistan", 4.2, 180, True],
["Delhi, India", 2.5, 90, False],
["Dhaka, Bangladesh", 5.1, 250, True]
],
inputs=[location, water_level, rainfall, historical],
label="Click any example to load"
)
# Footer
gr.Markdown(f"""
<div style='text-align: center; color: #666; margin-top: 20px'>
<p>Last update: {datetime.now().strftime('%Y-%m-%d %H:%M')} | Model: {MODEL}</p>
</div>
""")
# Event Handling
submit_btn.click(
fn=analyze_flood,
inputs=[location, water_level, rainfall, historical],
outputs={
"Risk Level": risk_level,
"Summary": summary,
"Detailed Analysis": details,
"Recommended Actions": actions,
"Confidence": confidence
}
)
app.launch()