CodeNine commited on
Commit
ccc9eb4
Β·
verified Β·
1 Parent(s): 209c26d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -49
app.py CHANGED
@@ -4,26 +4,35 @@ import requests
4
  import json
5
  from datetime import datetime
6
 
7
- # Configuration - Use Hugging Face Secrets
8
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
9
  MODEL = "llama3-70b-8192"
10
  API_URL = "https://api.groq.com/openai/v1/chat/completions"
11
 
 
 
 
 
 
 
 
 
 
12
  def analyze_flood(location, water_level, rainfall, historical_data):
13
- """Enhanced flood analysis with error handling"""
14
  prompt = f"""
15
- As FloodAI Expert, analyze:
16
- - Location: {location}
17
- - Water Level: {water_level}m
18
- - Rainfall: {rainfall}mm
19
- - Historical Data: {'Available' if historical_data else 'Unavailable'}
20
 
21
- Respond in JSON with:
22
  - risk_level (HIGH/MEDIUM/LOW)
23
- - confidence (0-100)
24
- - alert_message
25
- - actions (3 bullet points)
26
- - emergency (boolean)
27
  """
28
 
29
  try:
@@ -38,7 +47,7 @@ def analyze_flood(location, water_level, rainfall, historical_data):
38
  "messages": [
39
  {
40
  "role": "system",
41
- "content": "You are FloodAI. Respond in valid JSON only."
42
  },
43
  {
44
  "role": "user",
@@ -52,57 +61,74 @@ def analyze_flood(location, water_level, rainfall, historical_data):
52
  response.raise_for_status()
53
  result = json.loads(response.json()["choices"][0]["message"]["content"])
54
 
55
- # Format for Gradio output
56
- return {
57
- "Risk Level": result.get("risk_level", "UNKNOWN"),
58
- "Confidence": f"{result.get('confidence', 0)}%",
59
- "Alert": result.get("alert_message", "No alert generated"),
60
- "Recommended Actions": "\n".join([f"β€’ {action}" for action in result.get("actions", [])]),
61
- "Emergency": "🚨 EVACUATE" if result.get("emergency") else "⚠️ Monitor"
62
- }
63
 
64
  except Exception as e:
65
- return {"Error": f"API Failure: {str(e)}"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
- # Hugging Face Optimized Interface
68
- with gr.Blocks(theme=gr.themes.Soft(), title="FloodAI Pro") as app:
69
- # Header Section
70
  gr.Markdown("""
71
  <div style='text-align: center'>
72
- <h1>🌊 FloodAI Pro</h1>
73
- <p>Real-time Flood Risk Assessment powered by Groq AI</p>
74
  </div>
75
  """)
76
 
77
  # Input Section
78
  with gr.Row():
79
  with gr.Column():
80
- gr.Markdown("### πŸ“ Location Data")
81
- location = gr.Textbox(label="City/Region", placeholder="e.g. Karachi, Pakistan")
82
  water_level = gr.Slider(0, 15, step=0.1, label="Water Level (meters)")
83
  rainfall = gr.Slider(0, 500, step=5, label="24h Rainfall (mm)")
84
  historical = gr.Checkbox(label="Include historical flood data")
85
  submit_btn = gr.Button("Analyze Risk", variant="primary")
86
 
87
- # Output Section
 
88
  with gr.Column():
89
- gr.Markdown("### πŸ“Š Risk Assessment")
90
- risk_output = gr.JSON(label="Analysis Results")
 
91
 
92
- with gr.Accordion("πŸ›‘οΈ Safety Recommendations", open=False):
93
- gr.Markdown("""
94
- - Move to higher ground if risk is HIGH
95
- - Prepare emergency supplies
96
- - Monitor local authorities' instructions
97
- """)
 
98
 
99
- # Examples Section
100
- gr.Markdown("### πŸ§ͺ Try Example Scenarios")
101
  gr.Examples(
102
  examples=[
103
- ["Dhaka, Bangladesh", 4.5, 200, True],
104
- ["Lahore, Pakistan", 2.1, 80, False],
105
- ["Mumbai, India", 3.8, 300, True]
106
  ],
107
  inputs=[location, water_level, rainfall, historical],
108
  label="Click any example to load"
@@ -110,9 +136,8 @@ with gr.Blocks(theme=gr.themes.Soft(), title="FloodAI Pro") as app:
110
 
111
  # Footer
112
  gr.Markdown(f"""
113
- <div style='text-align: center; color: #666'>
114
- <p>Last Updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
115
- <p>Powered by Groq LPU β€’ Model: {MODEL}</p>
116
  </div>
117
  """)
118
 
@@ -120,8 +145,13 @@ with gr.Blocks(theme=gr.themes.Soft(), title="FloodAI Pro") as app:
120
  submit_btn.click(
121
  fn=analyze_flood,
122
  inputs=[location, water_level, rainfall, historical],
123
- outputs=risk_output
 
 
 
 
 
 
124
  )
125
 
126
- # Required for Hugging Face Spaces
127
- app.launch(debug=True)
 
4
  import json
5
  from datetime import datetime
6
 
7
+ # Configuration
8
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
9
  MODEL = "llama3-70b-8192"
10
  API_URL = "https://api.groq.com/openai/v1/chat/completions"
11
 
12
+ def get_risk_color(risk_level):
13
+ """Return color based on risk level"""
14
+ colors = {
15
+ "HIGH": "#ff4d4d", # Red
16
+ "MEDIUM": "#ffa64d", # Orange
17
+ "LOW": "#4dff4d", # Green
18
+ }
19
+ return colors.get(risk_level.upper(), "#666666")
20
+
21
  def analyze_flood(location, water_level, rainfall, historical_data):
22
+ """Enhanced flood analysis with structured output"""
23
  prompt = f"""
24
+ As a hydrology expert, analyze flood risk for:
25
+ Location: {location}
26
+ Water Level: {water_level}m
27
+ Rainfall: {rainfall}mm
28
+ Historical Data: {'Available' if historical_data else 'Not available'}
29
 
30
+ Respond in JSON format with:
31
  - risk_level (HIGH/MEDIUM/LOW)
32
+ - summary (1 sentence)
33
+ - detailed_analysis (3-5 bullet points)
34
+ - recommended_actions (3 bullet points)
35
+ - confidence (percentage)
36
  """
37
 
38
  try:
 
47
  "messages": [
48
  {
49
  "role": "system",
50
+ "content": "You are a flood risk analysis AI. Respond in valid JSON format."
51
  },
52
  {
53
  "role": "user",
 
61
  response.raise_for_status()
62
  result = json.loads(response.json()["choices"][0]["message"]["content"])
63
 
64
+ return format_output(result)
 
 
 
 
 
 
 
65
 
66
  except Exception as e:
67
+ return format_output({"error": str(e)})
68
+
69
+ def format_output(data):
70
+ """Format the API response for Gradio display"""
71
+ if "error" in data:
72
+ return {
73
+ "Risk Level": "ERROR",
74
+ "Summary": data["error"],
75
+ "Details": "Failed to get analysis",
76
+ "Actions": "Please try again later"
77
+ }
78
+
79
+ risk_level = data.get("risk_level", "UNKNOWN")
80
+ color = get_risk_color(risk_level)
81
+
82
+ return {
83
+ "Risk Level": f"<span style='color: {color}; font-weight: bold'>{risk_level}</span>",
84
+ "Summary": data.get("summary", "No summary available"),
85
+ "Detailed Analysis": "\n".join([f"β€’ {point}" for point in data.get("detailed_analysis", [])]),
86
+ "Recommended Actions": "\n".join([f"β€’ {action}" for action in data.get("recommended_actions", [])]),
87
+ "Confidence": f"{data.get('confidence', 'N/A')}%"
88
+ }
89
 
90
+ # Gradio Interface
91
+ with gr.Blocks(theme=gr.themes.Soft(), title="Flood Risk Analyzer") as app:
92
+ # Header
93
  gr.Markdown("""
94
  <div style='text-align: center'>
95
+ <h1>🌊 Flood Risk Assessment</h1>
96
+ <p>Instant flood risk analysis powered by Groq AI</p>
97
  </div>
98
  """)
99
 
100
  # Input Section
101
  with gr.Row():
102
  with gr.Column():
103
+ gr.Markdown("### πŸ“ Enter Location Details")
104
+ location = gr.Textbox(label="City/Region")
105
  water_level = gr.Slider(0, 15, step=0.1, label="Water Level (meters)")
106
  rainfall = gr.Slider(0, 500, step=5, label="24h Rainfall (mm)")
107
  historical = gr.Checkbox(label="Include historical flood data")
108
  submit_btn = gr.Button("Analyze Risk", variant="primary")
109
 
110
+ # Output Section
111
+ with gr.Row():
112
  with gr.Column():
113
+ gr.Markdown("### 🚨 Risk Overview")
114
+ risk_level = gr.HTML(label="Risk Level")
115
+ summary = gr.Textbox(label="Summary", interactive=False)
116
 
117
+ with gr.Accordion("πŸ“Š Detailed Analysis", open=False):
118
+ details = gr.Markdown()
119
+
120
+ with gr.Accordion("πŸ›‘οΈ Recommended Actions", open=False):
121
+ actions = gr.Markdown()
122
+
123
+ confidence = gr.Textbox(label="Confidence Level", interactive=False)
124
 
125
+ # Examples
126
+ gr.Markdown("### πŸ§ͺ Example Scenarios")
127
  gr.Examples(
128
  examples=[
129
+ ["Karachi, Pakistan", 4.2, 180, True],
130
+ ["Delhi, India", 2.5, 90, False],
131
+ ["Dhaka, Bangladesh", 5.1, 250, True]
132
  ],
133
  inputs=[location, water_level, rainfall, historical],
134
  label="Click any example to load"
 
136
 
137
  # Footer
138
  gr.Markdown(f"""
139
+ <div style='text-align: center; color: #666; margin-top: 20px'>
140
+ <p>Last update: {datetime.now().strftime('%Y-%m-%d %H:%M')} | Model: {MODEL}</p>
 
141
  </div>
142
  """)
143
 
 
145
  submit_btn.click(
146
  fn=analyze_flood,
147
  inputs=[location, water_level, rainfall, historical],
148
+ outputs={
149
+ "Risk Level": risk_level,
150
+ "Summary": summary,
151
+ "Detailed Analysis": details,
152
+ "Recommended Actions": actions,
153
+ "Confidence": confidence
154
+ }
155
  )
156
 
157
+ app.launch()