Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import os | |
| import requests | |
| import json | |
| from datetime import datetime | |
| # Configuration - Use Hugging Face Secrets | |
| GROQ_API_KEY = os.getenv("GROQ_API_KEY") | |
| MODEL = "llama3-70b-8192" | |
| API_URL = "https://api.groq.com/openai/v1/chat/completions" | |
| def analyze_flood(location, water_level, rainfall, historical_data): | |
| """Enhanced flood analysis with error handling""" | |
| prompt = f""" | |
| As FloodAI Expert, analyze: | |
| - Location: {location} | |
| - Water Level: {water_level}m | |
| - Rainfall: {rainfall}mm | |
| - Historical Data: {'Available' if historical_data else 'Unavailable'} | |
| Respond in JSON with: | |
| - risk_level (HIGH/MEDIUM/LOW) | |
| - confidence (0-100) | |
| - alert_message | |
| - actions (3 bullet points) | |
| - emergency (boolean) | |
| """ | |
| 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 FloodAI. Respond in valid JSON only." | |
| }, | |
| { | |
| "role": "user", | |
| "content": prompt | |
| } | |
| ], | |
| "response_format": {"type": "json_object"} | |
| }, | |
| timeout=10 | |
| ) | |
| response.raise_for_status() | |
| result = json.loads(response.json()["choices"][0]["message"]["content"]) | |
| # Format for Gradio output | |
| return { | |
| "Risk Level": result.get("risk_level", "UNKNOWN"), | |
| "Confidence": f"{result.get('confidence', 0)}%", | |
| "Alert": result.get("alert_message", "No alert generated"), | |
| "Recommended Actions": "\n".join([f"β’ {action}" for action in result.get("actions", [])]), | |
| "Emergency": "π¨ EVACUATE" if result.get("emergency") else "β οΈ Monitor" | |
| } | |
| except Exception as e: | |
| return {"Error": f"API Failure: {str(e)}"} | |
| # Hugging Face Optimized Interface | |
| with gr.Blocks(theme=gr.themes.Soft(), title="FloodAI Pro") as app: | |
| # Header Section | |
| gr.Markdown(""" | |
| <div style='text-align: center'> | |
| <h1>π FloodAI Pro</h1> | |
| <p>Real-time Flood Risk Assessment powered by Groq AI</p> | |
| </div> | |
| """) | |
| # Input Section | |
| with gr.Row(): | |
| with gr.Column(): | |
| gr.Markdown("### π Location Data") | |
| location = gr.Textbox(label="City/Region", placeholder="e.g. Karachi, Pakistan") | |
| 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.Column(): | |
| gr.Markdown("### π Risk Assessment") | |
| risk_output = gr.JSON(label="Analysis Results") | |
| with gr.Accordion("π‘οΈ Safety Recommendations", open=False): | |
| gr.Markdown(""" | |
| - Move to higher ground if risk is HIGH | |
| - Prepare emergency supplies | |
| - Monitor local authorities' instructions | |
| """) | |
| # Examples Section | |
| gr.Markdown("### π§ͺ Try Example Scenarios") | |
| gr.Examples( | |
| examples=[ | |
| ["Dhaka, Bangladesh", 4.5, 200, True], | |
| ["Lahore, Pakistan", 2.1, 80, False], | |
| ["Mumbai, India", 3.8, 300, True] | |
| ], | |
| inputs=[location, water_level, rainfall, historical], | |
| label="Click any example to load" | |
| ) | |
| # Footer | |
| gr.Markdown(f""" | |
| <div style='text-align: center; color: #666'> | |
| <p>Last Updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p> | |
| <p>Powered by Groq LPU β’ Model: {MODEL}</p> | |
| </div> | |
| """) | |
| # Event Handling | |
| submit_btn.click( | |
| fn=analyze_flood, | |
| inputs=[location, water_level, rainfall, historical], | |
| outputs=risk_output | |
| ) | |
| # Required for Hugging Face Spaces | |
| app.launch(debug=True) |