abdullah890 commited on
Commit
7fa798b
Β·
verified Β·
1 Parent(s): 08116b6
Files changed (1) hide show
  1. app.py +348 -0
app.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import json
5
+ from datetime import datetime
6
+
7
+ class EmergencyCore:
8
+ """
9
+ Advanced disaster response system with comprehensive emergency management capabilities.
10
+ """
11
+
12
+ def __init__(self, api_key):
13
+ """
14
+ Initialize the EmergencyCore with API credentials.
15
+
16
+ Args:
17
+ api_key (str): API key for external service authentication
18
+ """
19
+ self.xai_api_key = api_key
20
+
21
+ def analyze_report(self, report_text, urgency):
22
+ """
23
+ Enhanced emergency report analysis using Grok API.
24
+
25
+ Args:
26
+ report_text (str): Detailed emergency situation description
27
+ urgency (str): Urgency level of the report
28
+
29
+ Returns:
30
+ str: Formatted emergency analysis report
31
+ """
32
+ if not report_text:
33
+ return "🚨 Error: Please provide a detailed emergency description."
34
+
35
+ try:
36
+ headers = {
37
+ "Authorization": f"Bearer {self.xai_api_key}",
38
+ "Content-Type": "application/json"
39
+ }
40
+
41
+ # Enhanced prompt with more context and specific instructions
42
+ enhanced_prompt = f"""
43
+ Advanced Disaster Analysis Protocol:
44
+
45
+ Emergency Report: '{report_text}'
46
+ Urgency Level: {urgency}
47
+
48
+ Comprehensive Analysis Requirements:
49
+ 1. Identify precise disaster type
50
+ 2. Provide detailed severity assessment
51
+ 3. Outline immediate safety recommendations
52
+ 4. Develop comprehensive emergency response strategy
53
+ 5. Suggest resource allocation and prioritization
54
+
55
+ Analyze with scientific precision and humanitarian insight.
56
+ """
57
+
58
+ payload = {
59
+ "model": "grok-beta",
60
+ "max_tokens": 500,
61
+ "system": "You are an advanced AI disaster response coordinator with expertise in emergency management, risk assessment, and humanitarian aid.",
62
+ "messages": [
63
+ {
64
+ "role": "user",
65
+ "content": enhanced_prompt
66
+ }
67
+ ]
68
+ }
69
+
70
+ response = requests.post(
71
+ "https://api.x.ai/v1/chat/completions",
72
+ headers=headers,
73
+ data=json.dumps(payload)
74
+ )
75
+
76
+ if response.status_code == 200:
77
+ result = response.json()
78
+ analysis = result['choices'][0]['message']['content']
79
+
80
+ # Urgency color coding
81
+ urgency_prefix = {
82
+ "Low": "🟒",
83
+ "Medium": "🟠",
84
+ "High": "πŸ”΄"
85
+ }
86
+
87
+ # Format the analysis
88
+ formatted_analysis = (
89
+ f"{urgency_prefix.get(urgency, '🚨')} {urgency.upper()} THREAT LEVEL\n\n"
90
+ f"{self._format_emergency_analysis(analysis)}"
91
+ )
92
+
93
+ return formatted_analysis
94
+ else:
95
+ return f"🚨 API Error: {response.status_code} - {response.text}"
96
+
97
+ except requests.RequestException as e:
98
+ return f"🚨 Network Error: {str(e)}"
99
+ except Exception as e:
100
+ return f"🚨 Critical Error: {str(e)}"
101
+
102
+ def _format_emergency_analysis(self, analysis_text):
103
+ """
104
+ Advanced formatting of emergency analysis report.
105
+
106
+ Args:
107
+ analysis_text (str): Raw analysis text from API
108
+
109
+ Returns:
110
+ str: Formatted analysis report
111
+ """
112
+ def create_section(title, content):
113
+ """
114
+ Create a formatted section for the analysis.
115
+
116
+ Args:
117
+ title (str): Section title
118
+ content (str): Section content
119
+
120
+ Returns:
121
+ str: Formatted section
122
+ """
123
+ formatted_lines = [
124
+ f"πŸ” {title.upper()}",
125
+ "-" * 50
126
+ ]
127
+
128
+ # Process content lines
129
+ for line in content.split('\n'):
130
+ line = line.strip()
131
+ if line.startswith('-'):
132
+ formatted_lines.append(f" β€’ {line[1:].strip()}")
133
+ elif line:
134
+ formatted_lines.append(f" {line}")
135
+
136
+ return '\n'.join(formatted_lines)
137
+
138
+ # Sections to extract and format
139
+ sections = [
140
+ "Potential Disaster Type Classification",
141
+ "Severity Assessment",
142
+ "Recommended Emergency Response",
143
+ "Resource Allocation Suggestions"
144
+ ]
145
+
146
+ # Build formatted report
147
+ formatted_report = [
148
+ "🚨 EMERGENCY RESPONSE ANALYSIS ���",
149
+ "=" * 40
150
+ ]
151
+
152
+ # Extract and format each section
153
+ for section in sections:
154
+ if section.lower() in analysis_text.lower():
155
+ # Find the section content
156
+ start = analysis_text.lower().find(section.lower())
157
+ end = analysis_text.find('####', start + 1) if analysis_text.find('####', start + 1) != -1 else len(analysis_text)
158
+ section_content = analysis_text[start:end].split('\n', 1)[1].strip()
159
+
160
+ formatted_report.append('\n' + create_section(section, section_content))
161
+
162
+ # Add timestamp and urgency note
163
+ formatted_report.extend([
164
+ "\nπŸ•’ Analysis Timestamp: " + datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
165
+ "⚠️ URGENT ACTION REQUIRED ⚠️"
166
+ ])
167
+
168
+ return '\n'.join(formatted_report)
169
+
170
+ def weather_prediction(self, location):
171
+ """
172
+ Enhanced weather prediction with detailed information.
173
+
174
+ Args:
175
+ location (str): Location for weather prediction
176
+
177
+ Returns:
178
+ str: Formatted weather prediction report
179
+ """
180
+ if not location:
181
+ return "🌍 Error: Please enter a valid location."
182
+
183
+ try:
184
+ # Simulate more comprehensive weather prediction
185
+ weather_risks = {
186
+ "Low": "Minor weather concerns, standard precautions advised.",
187
+ "Moderate": "Potential for severe weather. Prepare emergency kit and stay informed.",
188
+ "High": "Extreme weather warning. Immediate protective actions recommended."
189
+ }
190
+
191
+ # Mock risk assessment (in real implementation, use a weather API)
192
+ risk_level = "Moderate"
193
+
194
+ return f"""🌦️ Weather Prediction for {location.title()}
195
+ Risk Level: {risk_level}
196
+ {weather_risks[risk_level]}
197
+
198
+ πŸ•’ Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
199
+ ⚠️ Always cross-check with local meteorological services"""
200
+
201
+ except Exception as e:
202
+ return f"🚨 Weather Prediction Error: {str(e)}"
203
+
204
+ def upload_damage_image(self, image):
205
+ """
206
+ Enhanced image upload and processing.
207
+
208
+ Args:
209
+ image (PIL.Image): Uploaded image for damage assessment
210
+
211
+ Returns:
212
+ str: Image analysis report
213
+ """
214
+ if image is None:
215
+ return "πŸ–ΌοΈ No image uploaded. Please provide a damage assessment image."
216
+
217
+ try:
218
+ # Basic image metadata extraction
219
+ height, width = image.size
220
+
221
+ return f"""πŸ–ΌοΈ Damage Assessment Image Analysis
222
+ Image Uploaded Successfully
223
+ πŸ“ Dimensions: {width} x {height} pixels
224
+ πŸ“Š Processing Status: Preliminary assessment in progress
225
+ πŸ” Recommendation: Detailed expert evaluation required
226
+
227
+ ⚠️ Note: This is an automated initial assessment.
228
+ Full analysis requires professional on-site inspection."""
229
+ except Exception as e:
230
+ return f"🚨 Image Processing Error: {str(e)}"
231
+
232
+ def create_interface(self):
233
+ """
234
+ Create an enhanced Gradio interface with improved visuals and interactivity.
235
+
236
+ Returns:
237
+ gr.Blocks: Configured Gradio interface
238
+ """
239
+ css = """
240
+ .gradio-container {
241
+ background-color: #f8fafc;
242
+ font-family: 'Verdana', sans-serif;
243
+ color: #333;
244
+ }
245
+ .analysis-output {
246
+ background-color: #f0f9ff;
247
+ border: 2px solid #007BFF;
248
+ border-radius: 10px;
249
+ padding: 15px;
250
+ line-height: 1.6;
251
+ }
252
+ .gr-title {
253
+ font-size: 24px;
254
+ font-weight: bold;
255
+ text-align: center;
256
+ margin: 15px 0;
257
+ }
258
+ """
259
+
260
+ with gr.Blocks(css=css) as demo:
261
+ gr.Markdown("# 🚨 EmergencyCore: Advanced Disaster Response System")
262
+
263
+ with gr.Tab("Emergency Reporting"):
264
+ gr.Markdown("### πŸ“ Submit an Emergency Report")
265
+ with gr.Row():
266
+ with gr.Column():
267
+ report_text = gr.Textbox(
268
+ label="Describe Emergency Situation",
269
+ lines=6,
270
+ placeholder="Provide detailed information about the emergency (e.g., location, risks)..."
271
+ )
272
+ urgency = gr.Dropdown(
273
+ ["High", "Medium", "Low"],
274
+ label="Urgency Level",
275
+ value="Medium"
276
+ )
277
+ submit_btn = gr.Button("Analyze Emergency 🚨", variant="primary")
278
+
279
+ with gr.Column():
280
+ analysis_output = gr.Textbox(
281
+ label="Emergency Analysis",
282
+ lines=15,
283
+ interactive=False,
284
+ elem_classes=["analysis-output"]
285
+ )
286
+
287
+ submit_btn.click(
288
+ fn=self.analyze_report,
289
+ inputs=[report_text, urgency],
290
+ outputs=analysis_output
291
+ )
292
+
293
+ with gr.Tab("Weather Monitoring"):
294
+ gr.Markdown("### 🌀️ Get Weather Predictions for Your Area")
295
+ location_input = gr.Textbox(label="Enter Location")
296
+ weather_btn = gr.Button("Get Weather Prediction 🌦️")
297
+ weather_output = gr.Textbox(label="Weather Analysis", lines=8)
298
+
299
+ weather_btn.click(
300
+ fn=self.weather_prediction,
301
+ inputs=location_input,
302
+ outputs=weather_output
303
+ )
304
+
305
+ with gr.Tab("Damage Assessment"):
306
+ gr.Markdown("### πŸ–ΌοΈ Upload an Image for Damage Assessment")
307
+ image_upload = gr.Image(
308
+ type="pil",
309
+ label="Upload Damage Image",
310
+ height=300
311
+ )
312
+ image_output = gr.Textbox(
313
+ label="Image Analysis",
314
+ lines=8,
315
+ interactive=False
316
+ )
317
+
318
+ process_btn = gr.Button("Process Damage Image πŸ”")
319
+ process_btn.click(
320
+ fn=self.upload_damage_image,
321
+ inputs=image_upload,
322
+ outputs=image_output
323
+ )
324
+
325
+ gr.Markdown(
326
+ "#### πŸ”— Learn More\n"
327
+ "For help, visit our [FAQ page](https://example.com)."
328
+ )
329
+
330
+ return demo
331
+
332
+
333
+ def main():
334
+ """
335
+ Main function to initialize and launch EmergencyCore application.
336
+ """
337
+ # Replace with your actual Grok API key
338
+ XAI_API_KEY = "xai-rBOk1AWqTKhnoSYs2N3icYx8aXu6wNDOK5qTapSJaNZz8QWP1zEEU0JflB9RuFuKRLEve2BG8g1kBs3P"
339
+
340
+ # Create EmergencyCore instance
341
+ emergency_core = EmergencyCore(XAI_API_KEY)
342
+
343
+ # Create and launch the interface
344
+ demo = emergency_core.create_interface()
345
+ demo.launch(debug=True, share=True)
346
+
347
+ if __name__ == "__main__":
348
+ main()