CodeNine commited on
Commit
110d33a
·
verified ·
1 Parent(s): 81d1cfc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -92
app.py CHANGED
@@ -2,58 +2,42 @@ import gradio as gr
2
  import os
3
  import requests
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": "red",
16
- "MEDIUM": "orange",
17
- "LOW": "green",
18
- "ERROR": "gray"
19
- }
20
- return colors.get(risk_level.upper(), "gray")
21
-
22
- def analyze_flood(location, water_level, rainfall, historical_data):
23
- """Enhanced flood analysis with structured output"""
24
  prompt = f"""
25
- As a hydrology expert, analyze flood risk for:
26
- Location: {location}
27
- Water Level: {water_level}m
28
- Rainfall: {rainfall}mm
29
- Historical Data: {'Available' if historical_data else 'Not available'}
 
30
 
31
  Respond in JSON format with:
32
- - risk_level (HIGH/MEDIUM/LOW)
33
- - summary (1 sentence)
34
- - detailed_analysis (3-5 bullet points)
35
- - recommended_actions (3 bullet points)
36
- - confidence (percentage)
37
  """
38
 
39
  try:
40
  response = requests.post(
41
  API_URL,
42
- headers={
43
- "Authorization": f"Bearer {GROQ_API_KEY}",
44
- "Content-Type": "application/json"
45
- },
46
  json={
47
  "model": MODEL,
48
  "messages": [
49
  {
50
  "role": "system",
51
- "content": "You are a flood risk analysis AI. Respond in valid JSON format."
52
  },
53
- {
54
- "role": "user",
55
- "content": prompt
56
- }
57
  ],
58
  "response_format": {"type": "json_object"}
59
  },
@@ -62,86 +46,67 @@ def analyze_flood(location, water_level, rainfall, historical_data):
62
  response.raise_for_status()
63
  result = json.loads(response.json()["choices"][0]["message"]["content"])
64
 
65
- # Format results
66
- risk_level = result.get("risk_level", "UNKNOWN")
67
- color = get_risk_color(risk_level)
68
 
69
- return (
70
- f"<span style='color: {color}; font-weight: bold'>{risk_level}</span>",
71
- result.get("summary", "No summary available"),
72
- "\n".join([f"• {point}" for point in result.get("detailed_analysis", [])]),
73
- "\n".join([f"• {action}" for action in result.get("recommended_actions", [])]),
74
- f"{result.get('confidence', 'N/A')}%"
75
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
  except Exception as e:
78
- return (
79
- "<span style='color: gray; font-weight: bold'>ERROR</span>",
80
- f"Analysis failed: {str(e)}",
81
- "Please try again later",
82
- "Check your API key and connection",
83
- "0%"
84
- )
85
 
86
  # Gradio Interface
87
  with gr.Blocks(theme=gr.themes.Soft(), title="Flood Risk Analyzer") as app:
88
- # Header
89
- gr.Markdown("""
90
- <div style='text-align: center'>
91
- <h1>🌊 Flood Risk Assessment</h1>
92
- <p>Instant flood risk analysis powered by Groq AI</p>
93
- </div>
94
- """)
95
 
96
- # Input Section
97
  with gr.Row():
98
  with gr.Column():
99
- gr.Markdown("### 📍 Enter Location Details")
100
- location = gr.Textbox(label="City/Region")
101
- water_level = gr.Slider(0, 15, step=0.1, label="Water Level (meters)")
102
- rainfall = gr.Slider(0, 500, step=5, label="24h Rainfall (mm)")
103
- historical = gr.Checkbox(label="Include historical flood data")
104
  submit_btn = gr.Button("Analyze Risk", variant="primary")
105
 
106
- # Output Section
107
- with gr.Row():
108
  with gr.Column():
109
- gr.Markdown("### 🚨 Risk Overview")
110
- risk_level = gr.HTML(label="Risk Level")
111
- summary = gr.Textbox(label="Summary", interactive=False)
112
-
113
- with gr.Accordion("📊 Detailed Analysis", open=False):
114
- details = gr.Markdown()
115
-
116
- with gr.Accordion("🛡️ Recommended Actions", open=False):
117
- actions = gr.Markdown()
118
-
119
- confidence = gr.Textbox(label="Confidence Level", interactive=False)
120
 
121
  # Examples
122
- gr.Markdown("### 🧪 Example Scenarios")
123
  gr.Examples(
124
  examples=[
125
- ["Karachi, Pakistan", 4.2, 180, True],
126
- ["Delhi, India", 2.5, 90, False],
127
- ["Dhaka, Bangladesh", 5.1, 250, True]
128
  ],
129
- inputs=[location, water_level, rainfall, historical],
130
- label="Click any example to load"
131
  )
132
 
133
- # Footer
134
- gr.Markdown(f"""
135
- <div style='text-align: center; color: #666; margin-top: 20px'>
136
- <p>Last update: {datetime.now().strftime('%Y-%m-%d %H:%M')} | Model: {MODEL}</p>
137
- </div>
138
- """)
139
-
140
- # Event Handling - Now returning a tuple instead of dict
141
  submit_btn.click(
142
- fn=analyze_flood,
143
- inputs=[location, water_level, rainfall, historical],
144
- outputs=[risk_level, summary, details, actions, confidence]
145
  )
146
 
147
  app.launch()
 
2
  import os
3
  import requests
4
  import json
 
5
 
6
  # Configuration
7
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
8
  MODEL = "llama3-70b-8192"
9
  API_URL = "https://api.groq.com/openai/v1/chat/completions"
10
 
11
+ def analyze_flood_risk(country, city, area, water_level, rainfall):
12
+ """Detailed flood analysis based on location"""
 
 
 
 
 
 
 
 
 
 
13
  prompt = f"""
14
+ As a flood risk expert, analyze:
15
+ - Country: {country}
16
+ - City: {city}
17
+ - Area: {area}
18
+ - Water Level: {water_level} meters
19
+ - 24h Rainfall: {rainfall} mm
20
 
21
  Respond in JSON format with:
22
+ - risk_level: <HIGH/MEDIUM/LOW>
23
+ - summary: <1 sentence>
24
+ - affected_areas: <list>
25
+ - precautions: <3 bullet points>
26
+ - emergency_contacts: <local authorities>
27
  """
28
 
29
  try:
30
  response = requests.post(
31
  API_URL,
32
+ headers={"Authorization": f"Bearer {GROQ_API_KEY}"},
 
 
 
33
  json={
34
  "model": MODEL,
35
  "messages": [
36
  {
37
  "role": "system",
38
+ "content": "You are a local flood analysis expert. Consider regional geography."
39
  },
40
+ {"role": "user", "content": prompt}
 
 
 
41
  ],
42
  "response_format": {"type": "json_object"}
43
  },
 
46
  response.raise_for_status()
47
  result = json.loads(response.json()["choices"][0]["message"]["content"])
48
 
49
+ # Determine color based on risk
50
+ color = "#ff0000" if result["risk_level"] == "HIGH" else "#ff9900" if result["risk_level"] == "MEDIUM" else "#00aa00"
 
51
 
52
+ # Format HTML output
53
+ return f"""
54
+ <div style='border-left: 5px solid {color}; padding-left: 10px'>
55
+ <h3>{area}, {city}, {country}</h3>
56
+ <p><b>Risk Level:</b> <span style='color:{color}'>{result['risk_level']}</span></p>
57
+ <p><b>Summary:</b> {result['summary']}</p>
58
+
59
+ <h4>Affected Areas:</h4>
60
+ <ul>
61
+ {"".join([f"<li>{area}</li>" for area in result['affected_areas']])}
62
+ </ul>
63
+
64
+ <h4>Precautions:</h4>
65
+ <ol>
66
+ {"".join([f"<li>{action}</li>" for action in result['precautions']])}
67
+ </ol>
68
+
69
+ <h4>Emergency Contacts:</h4>
70
+ <ul>
71
+ {"".join([f"<li>{contact}</li>" for contact in result['emergency_contacts']])}
72
+ </ul>
73
+ </div>
74
+ """
75
 
76
  except Exception as e:
77
+ return f"<div style='color:red'>Error: {str(e)}</div>"
 
 
 
 
 
 
78
 
79
  # Gradio Interface
80
  with gr.Blocks(theme=gr.themes.Soft(), title="Flood Risk Analyzer") as app:
81
+ gr.Markdown("# 🌊 Flood Risk Assessment")
82
+ gr.Markdown("Enter location details to analyze flood risk")
 
 
 
 
 
83
 
 
84
  with gr.Row():
85
  with gr.Column():
86
+ country = gr.Textbox(label="Country", placeholder="e.g. Pakistan")
87
+ city = gr.Textbox(label="City", placeholder="e.g. Karachi")
88
+ area = gr.Textbox(label="Area/Neighborhood", placeholder="e.g. Clifton")
89
+ water_level = gr.Slider(0, 10, step=0.1, label="Water Level (meters)")
90
+ rainfall = gr.Slider(0, 500, label="24h Rainfall (mm)")
91
  submit_btn = gr.Button("Analyze Risk", variant="primary")
92
 
 
 
93
  with gr.Column():
94
+ output_html = gr.HTML(label="Analysis Results")
 
 
 
 
 
 
 
 
 
 
95
 
96
  # Examples
 
97
  gr.Examples(
98
  examples=[
99
+ ["Pakistan", "Karachi", "Clifton", 3.5, 200],
100
+ ["Pakistan", "Lahore", "Iqbal Town", 2.0, 80],
101
+ ["India", "Mumbai", "Nariman Point", 4.0, 300]
102
  ],
103
+ inputs=[country, city, area, water_level, rainfall]
 
104
  )
105
 
 
 
 
 
 
 
 
 
106
  submit_btn.click(
107
+ fn=analyze_flood_risk,
108
+ inputs=[country, city, area, water_level, rainfall],
109
+ outputs=output_html
110
  )
111
 
112
  app.launch()