# import streamlit as st # import requests # import json # import pandas as pd # import pydeck as pdk # from transformers import pipeline # from datetime import datetime # import os # import time # # Configure page # st.set_page_config( # page_title="DisasterRelief AI Hub", # page_icon="šŸ†˜", # layout="wide", # initial_sidebar_state="expanded" # ) # # Initialize session state # if 'reports' not in st.session_state: # st.session_state.reports = [] # if 'relief_centers' not in st.session_state: # st.session_state.relief_centers = [] # # Load or initialize data files # @st.cache_data # def load_emergency_contacts(): # """Load emergency contacts from JSON file or create default""" # default_contacts = { # "emergency_services": [ # {"name": "Police Emergency", "number": "15", "description": "Police emergency hotline"}, # {"name": "Fire Brigade", "number": "16", "description": "Fire emergency services"}, # {"name": "Medical Emergency", "number": "1122", "description": "Emergency medical services"}, # {"name": "Rescue 1122", "number": "1122", "description": "Emergency rescue services"} # ], # "disaster_helplines": [ # {"name": "NDMA Helpline", "number": "051-9205086", "description": "National Disaster Management Authority"}, # {"name": "PDMA Punjab", "number": "042-99203081", "description": "Provincial Disaster Management Authority"}, # {"name": "Red Crescent", "number": "051-9250404", "description": "Pakistan Red Crescent Society"} # ], # "safety_guidelines": [ # "Keep emergency numbers saved in your phone", # "Have a family emergency plan ready", # "Keep emergency supplies (water, food, flashlight, first aid kit)", # "Stay informed through official channels", # "Follow evacuation orders immediately when issued" # ] # } # return default_contacts # def save_reports(): # """Save reports to session state""" # # In a real deployment, you'd save to a persistent database # pass # def load_reports(): # """Load existing reports""" # return st.session_state.reports # # Initialize AI models # @st.cache_resource # def load_summarizer(): # """Load the summarization model""" # try: # return pipeline("summarization", model="facebook/bart-large-cnn", max_length=150, min_length=30) # except Exception as e: # st.error(f"Error loading summarizer: {e}") # return None # @st.cache_resource # def load_qa_model(): # """Load the Q&A model""" # try: # return pipeline("question-answering", model="deepset/roberta-base-squad2") # except Exception as e: # st.error(f"Error loading Q&A model: {e}") # return None # # Geocoding functions # def geocode_location(location_name): # """Get coordinates for a location using Nominatim API""" # try: # url = f"https://nominatim.openstreetmap.org/search" # params = { # 'q': location_name, # 'format': 'json', # 'limit': 1 # } # headers = {'User-Agent': 'DisasterReliefApp/1.0'} # response = requests.get(url, params=params, headers=headers, timeout=5) # data = response.json() # if data: # return float(data[0]['lat']), float(data[0]['lon']) # return None, None # except Exception as e: # st.error(f"Geocoding error: {e}") # return None, None # def find_nearby_places(lat, lon, place_type="hospital"): # """Find nearby places using Overpass API""" # try: # overpass_url = "http://overpass-api.de/api/interpreter" # # Define search tags based on place type # if place_type == "hospital": # amenity_tag = "hospital" # elif place_type == "shelter": # amenity_tag = "social_facility" # elif place_type == "food_bank": # amenity_tag = "food_bank" # else: # amenity_tag = "hospital" # # Overpass query to find nearby places # overpass_query = f""" # [out:json][timeout:25]; # ( # node["amenity"="{amenity_tag}"](around:5000,{lat},{lon}); # way["amenity"="{amenity_tag}"](around:5000,{lat},{lon}); # relation["amenity"="{amenity_tag}"](around:5000,{lat},{lon}); # ); # out center meta; # """ # response = requests.get(overpass_url, params={'data': overpass_query}, timeout=10) # data = response.json() # places = [] # for element in data.get('elements', [])[:10]: # Limit to 10 results # name = element.get('tags', {}).get('name', f'Unnamed {place_type}') # if element['type'] == 'node': # place_lat, place_lon = element['lat'], element['lon'] # else: # place_lat, place_lon = element.get('center', {}).get('lat'), element.get('center', {}).get('lon') # if place_lat and place_lon: # places.append({ # 'name': name, # 'lat': place_lat, # 'lon': place_lon, # 'type': place_type # }) # return places # except Exception as e: # st.error(f"Error finding nearby places: {e}") # return [] # # Chatbot function # def simple_chatbot(question): # """Simple rule-based chatbot for common queries""" # question_lower = question.lower() # # Common emergency queries # if any(word in question_lower for word in ['emergency', 'help', 'urgent']): # return "🚨 For immediate emergencies, call:\n• Police: 15\n• Medical Emergency: 1122\n• Fire: 16" # elif any(word in question_lower for word in ['hospital', 'medical', 'doctor']): # return "šŸ„ To find nearby hospitals:\n1. Use the 'Relief Centers' tab\n2. Enter your location\n3. Select 'Hospital' from the dropdown\n\nFor medical emergencies, call 1122 immediately." # elif any(word in question_lower for word in ['shelter', 'evacuate', 'safe place']): # return "šŸ  To find emergency shelters:\n1. Go to 'Relief Centers' tab\n2. Enter your location\n3. Select 'Shelter' option\n\nIn case of evacuation orders, follow official instructions immediately." # elif any(word in question_lower for word in ['food', 'hunger', 'supplies']): # return "šŸ½ļø For food assistance:\n1. Check 'Relief Centers' for food banks\n2. Contact local NGOs listed in Emergency Contacts\n3. Call Red Crescent: 051-9250404" # elif any(word in question_lower for word in ['report', 'incident', 'missing']): # return "šŸ“ To report incidents:\n1. Go to 'Report Incident' tab\n2. Fill out the form with details\n3. Submit your report\n\nFor missing persons, also contact local police: 15" # elif any(word in question_lower for word in ['contact', 'number', 'helpline']): # return "šŸ“ž Key emergency contacts:\n• Police: 15\n• Medical: 1122\n• NDMA: 051-9205086\n• Red Crescent: 051-9250404\n\nCheck 'Emergency Contacts' tab for complete list." # else: # return "šŸ¤– I can help you with:\n• Finding nearby relief centers\n• Emergency contact numbers\n• Reporting incidents\n• Safety guidelines\n\nPlease ask specific questions about these topics or call 1122 for emergencies." # # Main app layout # def main(): # # Header # st.title("šŸ†˜ DisasterRelief AI Hub") # st.markdown("### Community-driven disaster assistance platform") # # Sidebar # st.sidebar.title("Navigation") # tab_selection = st.sidebar.selectbox( # "Choose a service:", # ["šŸ„ Relief Centers", "šŸ“ Report Incident", "šŸ“ž Emergency Contacts", "šŸ“„ AI Alert Summarizer", "šŸ¤– AI Assistant"] # ) # # Main content based on tab selection # if tab_selection == "šŸ„ Relief Centers": # relief_centers_tab() # elif tab_selection == "šŸ“ Report Incident": # report_incident_tab() # elif tab_selection == "šŸ“ž Emergency Contacts": # emergency_contacts_tab() # elif tab_selection == "šŸ“„ AI Alert Summarizer": # ai_summarizer_tab() # elif tab_selection == "šŸ¤– AI Assistant": # ai_assistant_tab() # def relief_centers_tab(): # st.header("šŸ„ Find Nearby Relief Centers") # col1, col2 = st.columns([2, 1]) # with col1: # location_input = st.text_input("Enter your location (city, area, or address):", placeholder="e.g., Lahore, Karachi, Islamabad") # with col2: # place_type = st.selectbox("Type of facility:", ["hospital", "shelter", "food_bank"]) # search_button = st.button("šŸ” Search Relief Centers", type="primary") # if search_button and location_input: # with st.spinner("Searching for relief centers..."): # # Geocode the location # lat, lon = geocode_location(location_input) # if lat and lon: # # Find nearby places # places = find_nearby_places(lat, lon, place_type) # if places: # st.success(f"Found {len(places)} {place_type}(s) near {location_input}") # # Create map data # map_data = pd.DataFrame(places) # map_data['lat'] = map_data['lat'].astype(float) # map_data['lon'] = map_data['lon'].astype(float) # # Display map # st.subheader("šŸ“ Map View") # view_state = pdk.ViewState( # latitude=lat, # longitude=lon, # zoom=12, # pitch=0 # ) # layer = pdk.Layer( # 'ScatterplotLayer', # data=map_data, # get_position='[lon, lat]', # get_color='[255, 0, 0, 160]', # get_radius=200, # pickable=True # ) # st.pydeck_chart(pdk.Deck( # map_style='mapbox://styles/mapbox/light-v9', # initial_view_state=view_state, # layers=[layer], # tooltip={"text": "{name}\nType: {type}"} # )) # # Display list # st.subheader("šŸ“‹ Relief Centers List") # for i, place in enumerate(places, 1): # with st.expander(f"{i}. {place['name']}"): # st.write(f"**Type:** {place['type'].replace('_', ' ').title()}") # st.write(f"**Coordinates:** {place['lat']:.6f}, {place['lon']:.6f}") # st.write(f"**Google Maps:** [Open in Maps](https://www.google.com/maps/search/?api=1&query={place['lat']},{place['lon']})") # else: # st.warning(f"No {place_type}s found near {location_input}. Try a different location or facility type.") # else: # st.error("Could not find the specified location. Please check the spelling and try again.") # elif search_button: # st.warning("Please enter a location to search.") # def report_incident_tab(): # st.header("šŸ“ Report Community Incident") # with st.form("incident_report_form"): # col1, col2 = st.columns(2) # with col1: # incident_type = st.selectbox( # "Incident Type:", # ["Road Block", "Missing Person", "Medical Help Needed", "Fire Emergency", "Flood", "Other Emergency"] # ) # location = st.text_input("Location:", placeholder="Specific address or landmark") # with col2: # reporter_name = st.text_input("Your Name (Optional):", placeholder="Anonymous") # contact_info = st.text_input("Contact Info (Optional):", placeholder="Phone number or email") # description = st.text_area("Description:", placeholder="Provide detailed information about the incident...") # submit_button = st.form_submit_button("šŸ“¤ Submit Report", type="primary") # if submit_button: # if incident_type and location and description: # # Create report # report = { # "id": len(st.session_state.reports) + 1, # "type": incident_type, # "location": location, # "description": description, # "reporter": reporter_name if reporter_name else "Anonymous", # "contact": contact_info if contact_info else "Not provided", # "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), # "status": "Reported" # } # st.session_state.reports.insert(0, report) # Add to beginning # save_reports() # st.success("āœ… Report submitted successfully! Thank you for helping the community.") # # Show emergency advice based on incident type # if incident_type == "Medical Help Needed": # st.info("🚨 For immediate medical emergencies, call 1122") # elif incident_type == "Fire Emergency": # st.info("🚨 For fire emergencies, call 16 immediately") # elif incident_type == "Missing Person": # st.info("🚨 Also report to local police: 15") # else: # st.error("Please fill in all required fields.") # # Display recent reports # st.subheader("šŸ“‹ Recent Community Reports") # if st.session_state.reports: # for report in st.session_state.reports[:10]: # Show last 10 reports # with st.expander(f"{report['type']} - {report['location']} ({report['timestamp']})"): # st.write(f"**Description:** {report['description']}") # st.write(f"**Reporter:** {report['reporter']}") # st.write(f"**Status:** {report['status']}") # if report['contact'] != "Not provided": # st.write(f"**Contact:** {report['contact']}") # else: # st.info("No reports submitted yet. Be the first to help your community!") # def emergency_contacts_tab(): # st.header("šŸ“ž Emergency Contacts & Safety Resources") # contacts = load_emergency_contacts() # # Emergency Services # st.subheader("🚨 Emergency Services") # col1, col2 = st.columns(2) # with col1: # for contact in contacts["emergency_services"][:2]: # st.markdown(f""" #
#

{contact['name']}

#

{contact['number']}

#

{contact['description']}

#
# """, unsafe_allow_html=True) # with col2: # for contact in contacts["emergency_services"][2:]: # st.markdown(f""" #
#

{contact['name']}

#

{contact['number']}

#

{contact['description']}

#
# """, unsafe_allow_html=True) # # Disaster Helplines # st.subheader("šŸ¢ Disaster Management Helplines") # for contact in contacts["disaster_helplines"]: # st.markdown(f""" #
#

{contact['name']}: {contact['number']}

#

{contact['description']}

#
# """, unsafe_allow_html=True) # # Safety Guidelines # st.subheader("šŸ›”ļø Safety Guidelines") # for i, guideline in enumerate(contacts["safety_guidelines"], 1): # st.markdown(f"**{i}.** {guideline}") # # Quick Action Section # st.subheader("⚔ Quick Actions") # col1, col2, col3 = st.columns(3) # with col1: # if st.button("šŸ“ž Call Emergency (1122)", type="primary"): # st.info("On mobile devices, this would initiate a call to 1122") # with col2: # if st.button("šŸ“ Share Location"): # st.info("Location sharing feature would be activated") # with col3: # if st.button("🚨 Send Alert"): # st.info("Emergency alert would be sent to registered contacts") # def ai_summarizer_tab(): # st.header("šŸ“„ AI Alert Summarizer") # st.markdown("Paste long official disaster alerts below to get a concise AI-powered summary.") # # Text input # alert_text = st.text_area( # "Official Alert Text:", # placeholder="Paste the long official disaster alert here...", # height=200 # ) # col1, col2 = st.columns([1, 3]) # with col1: # summarize_button = st.button("šŸ¤– Summarize Alert", type="primary", disabled=not alert_text) # if summarize_button and alert_text: # with st.spinner("Analyzing and summarizing the alert..."): # summarizer = load_summarizer() # if summarizer: # try: # # Ensure text is not too long for the model # max_input_length = 1000 # Adjust based on model limits # if len(alert_text) > max_input_length: # alert_text = alert_text[:max_input_length] + "..." # # Generate summary # summary_result = summarizer(alert_text, max_length=150, min_length=30, do_sample=False) # summary = summary_result[0]['summary_text'] # # Display results # st.subheader("šŸ“‹ Summary") # st.success("āœ… Alert summarized successfully!") # # Format as bullet points # sentences = summary.split('. ') # st.markdown("**Key Points:**") # for i, sentence in enumerate(sentences, 1): # if sentence.strip(): # sentence = sentence.strip() # if not sentence.endswith('.'): # sentence += '.' # st.markdown(f"• {sentence}") # # Additional analysis # st.subheader("šŸ“Š Alert Analysis") # col1, col2, col3 = st.columns(3) # with col1: # st.metric("Original Length", f"{len(alert_text)} chars") # with col2: # st.metric("Summary Length", f"{len(summary)} chars") # with col3: # compression_ratio = round((1 - len(summary)/len(alert_text)) * 100, 1) # st.metric("Compression", f"{compression_ratio}%") # # Extract urgency level (simple keyword analysis) # urgency_keywords = { # 'high': ['immediate', 'urgent', 'emergency', 'critical', 'evacuate', 'danger'], # 'medium': ['warning', 'alert', 'caution', 'prepare', 'monitor'], # 'low': ['advisory', 'information', 'update', 'notice'] # } # text_lower = alert_text.lower() # urgency_score = {'high': 0, 'medium': 0, 'low': 0} # for level, keywords in urgency_keywords.items(): # urgency_score[level] = sum(1 for keyword in keywords if keyword in text_lower) # urgency_level = max(urgency_score, key=urgency_score.get) # urgency_colors = {'high': 'šŸ”“', 'medium': '🟔', 'low': '🟢'} # st.markdown(f"**Urgency Level:** {urgency_colors[urgency_level]} {urgency_level.upper()}") # except Exception as e: # st.error(f"Error generating summary: {e}") # st.info("Tip: Try with a shorter text or check your internet connection.") # else: # st.error("AI summarizer is not available. Please try again later.") # # Example alerts # st.subheader("šŸ’” Example Usage") # example_alert = """ # URGENT FLOOD WARNING - DISTRICT LAHORE # The Meteorological Department has issued a severe flood warning for Lahore district effective immediately. Heavy monsoon rains of 150-200mm are expected in the next 24 hours. The Ravi River water level has risen to dangerous levels. Citizens living in low-lying areas including Shahdara, Kot Lakhpat, and areas near Ravi River are advised to evacuate immediately. Emergency shelters have been established at Government Schools in each tehsil. All citizens are advised to avoid unnecessary travel and stay indoors. Emergency services are on high alert. For assistance, contact District Emergency Operations Center at 042-99200100. This is a developing situation and updates will be provided regularly through official channels. # """ # if st.button("Try Example Alert"): # st.text_area("Example Alert:", value=example_alert, height=150, key="example") # def ai_assistant_tab(): # st.header("šŸ¤– AI Assistant") # st.markdown("Ask me questions about emergency services, relief centers, or safety guidelines!") # # Chat interface # if 'chat_history' not in st.session_state: # st.session_state.chat_history = [] # # Display chat history # chat_container = st.container() # with chat_container: # for i, (question, answer) in enumerate(st.session_state.chat_history): # # User message # st.markdown(f""" #
# You: {question} #
# """, unsafe_allow_html=True) # # AI response # st.markdown(f""" #
# AI Assistant:
{answer} #
# """, unsafe_allow_html=True) # # Input form # with st.form("chat_form", clear_on_submit=True): # user_question = st.text_input( # "Ask a question:", # placeholder="e.g., Where is the nearest hospital in Karachi?" # ) # col1, col2 = st.columns([1, 5]) # with col1: # ask_button = st.form_submit_button("Ask", type="primary") # with col2: # if st.form_submit_button("Clear Chat"): # st.session_state.chat_history = [] # st.rerun() # if ask_button and user_question: # with st.spinner("Thinking..."): # # Get AI response # ai_response = simple_chatbot(user_question) # # Add to chat history # st.session_state.chat_history.append((user_question, ai_response)) # # Limit chat history to last 10 exchanges # if len(st.session_state.chat_history) > 10: # st.session_state.chat_history = st.session_state.chat_history[-10:] # st.rerun() # # Quick question buttons # st.subheader("šŸ”— Common Questions") # col1, col2 = st.columns(2) # with col1: # if st.button("šŸ„ Find nearest hospital"): # st.session_state.chat_history.append( # ("Find nearest hospital", simple_chatbot("Find nearest hospital")) # ) # st.rerun() # if st.button("šŸ“ž Emergency numbers"): # st.session_state.chat_history.append( # ("Emergency numbers", simple_chatbot("Emergency numbers")) # ) # st.rerun() # with col2: # if st.button("šŸ  Find shelter"): # st.session_state.chat_history.append( # ("Find shelter", simple_chatbot("Find shelter")) # ) # st.rerun() # if st.button("šŸ“ How to report incident"): # st.session_state.chat_history.append( # ("How to report incident", simple_chatbot("How to report incident")) # ) # st.rerun() # # Footer # def show_footer(): # st.markdown("---") # st.markdown(""" #
#

šŸ†˜ DisasterRelief AI Hub - Helping communities in times of need

#

For immediate emergencies, always call official emergency services: Police (15), Medical (1122), Fire (16)

#

Built with ā¤ļø using Streamlit and Hugging Face AI

#
# """, unsafe_allow_html=True) # if __name__ == "__main__": # main() # show_footer() import streamlit as st import requests import json import pandas as pd import pydeck as pdk from transformers import pipeline from datetime import datetime import os import time # Configure page st.set_page_config( page_title="DisasterRelief AI Hub", page_icon="ļæ½", layout="wide", initial_sidebar_state="expanded" ) # Initialize session state if 'reports' not in st.session_state: st.session_state.reports = [] if 'relief_centers' not in st.session_state: st.session_state.relief_centers = [] # Load or initialize data files @st.cache_data def load_emergency_contacts(): """Load emergency contacts from JSON file or create default""" default_contacts = { "emergency_services": [ {"name": "Police Emergency", "number": "15", "description": "Police emergency hotline"}, {"name": "Fire Brigade", "number": "16", "description": "Fire emergency services"}, {"name": "Medical Emergency", "number": "1122", "description": "Emergency medical services"}, {"name": "Rescue 1122", "number": "1122", "description": "Emergency rescue services"} ], "disaster_helplines": [ {"name": "NDMA Helpline", "number": "051-9205086", "description": "National Disaster Management Authority"}, {"name": "PDMA Punjab", "number": "042-99203081", "description": "Provincial Disaster Management Authority"}, {"name": "Red Crescent", "number": "051-9250404", "description": "Pakistan Red Crescent Society"} ], "safety_guidelines": [ "Keep emergency numbers saved in your phone", "Have a family emergency plan ready", "Keep emergency supplies (water, food, flashlight, first aid kit)", "Stay informed through official channels", "Follow evacuation orders immediately when issued" ] } return default_contacts def save_reports(): """Save reports to session state""" # In a real deployment, you'd save to a persistent database pass def load_reports(): """Load existing reports""" return st.session_state.reports # Initialize AI models @st.cache_resource def load_summarizer(): """Load the summarization model""" try: return pipeline("summarization", model="facebook/bart-large-cnn", max_length=150, min_length=30) except Exception as e: st.error(f"Error loading summarizer: {e}") return None @st.cache_resource def load_qa_model(): """Load the Q&A model""" try: return pipeline("question-answering", model="deepset/roberta-base-squad2") except Exception as e: st.error(f"Error loading Q&A model: {e}") return None # Geocoding functions def geocode_location(location_name): """Get coordinates for a location using Nominatim API""" try: url = f"https://nominatim.openstreetmap.org/search" params = { 'q': location_name, 'format': 'json', 'limit': 1 } headers = {'User-Agent': 'DisasterReliefApp/1.0'} response = requests.get(url, params=params, headers=headers, timeout=5) data = response.json() if data: return float(data[0]['lat']), float(data[0]['lon']) return None, None except Exception as e: st.error(f"Geocoding error: {e}") return None, None def find_nearby_places(lat, lon, place_type="hospital"): """Find nearby places using Overpass API""" try: overpass_url = "http://overpass-api.de/api/interpreter" # Define search tags based on place type if place_type == "hospital": amenity_tag = "hospital" elif place_type == "shelter": # Note: Overpass API typically uses 'social_facility' with 'shelter' tag or similar # For broader search, 'social_facility' might be used, or 'emergency' facility. # Let's keep it simple for now based on the original. amenity_tag = "shelter" # If 'shelter' doesn't yield results, consider 'social_facility' or 'bunker' # Or a more complex query like: # (node["amenity"="social_facility"]["social_facility"="homeless_shelter"](around:5000,{lat},{lon});) elif place_type == "food_bank": amenity_tag = "food_bank" else: amenity_tag = "hospital" # Default to hospital if unknown type # Overpass query to find nearby places overpass_query = f""" [out:json][timeout:30]; /* Increased timeout to 30 seconds */ ( node["amenity"="{amenity_tag}"](around:5000,{lat},{lon}); way["amenity"="{amenity_tag}"](around:5000,{lat},{lon}); relation["amenity"="{amenity_tag}"](around:5000,{lat},{lon}); ); out center meta; """ # Increased timeout to 30 seconds response = requests.get(overpass_url, params={'data': overpass_query}, timeout=30) data = response.json() places = [] for element in data.get('elements', [])[:10]: # Limit to 10 results name = element.get('tags', {}).get('name', f'Unnamed {place_type}') if element['type'] == 'node': place_lat, place_lon = element['lat'], element['lon'] else: place_lat, place_lon = element.get('center', {}).get('lat'), element.get('center', {}).get('lon') if place_lat and place_lon: places.append({ 'name': name, 'lat': place_lat, 'lon': place_lon, 'type': place_type }) return places except Exception as e: st.error(f"Error finding nearby places: {e}") return [] # Chatbot function def simple_chatbot(question): """Simple rule-based chatbot for common queries""" question_lower = question.lower() # Common emergency queries if any(word in question_lower for word in ['emergency', 'help', 'urgent']): return "🚨 For immediate emergencies, call:\n• Police: 15\n• Medical Emergency: 1122\n• Fire: 16" elif any(word in question_lower for word in ['hospital', 'medical', 'doctor']): return "šŸ„ To find nearby hospitals:\n1. Use the 'Relief Centers' tab\n2. Enter your location\n3. Select 'Hospital' from the dropdown\n\nFor medical emergencies, call 1122 immediately." elif any(word in question_lower for word in ['shelter', 'evacuate', 'safe place']): return "šŸ  To find emergency shelters:\n1. Go to 'Relief Centers' tab\n2. Enter your location\n3. Select 'Shelter' option\n\nIn case of evacuation orders, follow official instructions immediately." elif any(word in question_lower for word in ['food', 'hunger', 'supplies']): return "šŸ½ļø For food assistance:\n1. Check 'Relief Centers' for food banks\n2. Contact local NGOs listed in Emergency Contacts\n3. Call Red Crescent: 051-9250404" elif any(word in question_lower for word in ['report', 'incident', 'missing']): return "šŸ“ To report incidents:\n1. Go to 'Report Incident' tab\n2. Fill out the form with details\n3. Submit your report\n\nFor missing persons, also contact local police: 15" elif any(word in question_lower for word in ['contact', 'number', 'helpline']): return "šŸ“ž Key emergency contacts:\n• Police: 15\n• Medical: 1122\n• NDMA: 051-9205086\n• Red Crescent: 051-9250404\n\nCheck 'Emergency Contacts' tab for complete list." else: return "šŸ¤– I can help you with:\n• Finding nearby relief centers\n• Emergency contact numbers\n• Reporting incidents\n• Safety guidelines\n\nPlease ask specific questions about these topics or call 1122 for emergencies." # Main app layout def main(): # Header st.title("šŸ†˜ DisasterRelief AI Hub") st.markdown("### Community-driven disaster assistance platform") # Sidebar st.sidebar.title("Navigation") tab_selection = st.sidebar.selectbox( "Choose a service:", ["šŸ„ Relief Centers", "šŸ“ Report Incident", "šŸ“ž Emergency Contacts", "šŸ“„ AI Alert Summarizer", "šŸ¤– AI Assistant"] ) # Main content based on tab selection if tab_selection == "šŸ„ Relief Centers": relief_centers_tab() elif tab_selection == "šŸ“ Report Incident": report_incident_tab() elif tab_selection == "šŸ“ž Emergency Contacts": emergency_contacts_tab() elif tab_selection == "šŸ“„ AI Alert Summarizer": ai_summarizer_tab() elif tab_selection == "šŸ¤– AI Assistant": ai_assistant_tab() def relief_centers_tab(): st.header("šŸ„ Find Nearby Relief Centers") col1, col2 = st.columns([2, 1]) with col1: location_input = st.text_input("Enter your location (city, area, or address):", placeholder="e.g., Lahore, Karachi, Islamabad") with col2: place_type = st.selectbox("Type of facility:", ["hospital", "shelter", "food_bank"]) search_button = st.button("šŸ” Search Relief Centers", type="primary") if search_button and location_input: with st.spinner("Searching for relief centers..."): # Geocode the location lat, lon = geocode_location(location_input) if lat and lon: # Find nearby places places = find_nearby_places(lat, lon, place_type) if places: st.success(f"Found {len(places)} {place_type}(s) near {location_input}") # Create map data map_data = pd.DataFrame(places) map_data['lat'] = map_data['lat'].astype(float) map_data['lon'] = map_data['lon'].astype(float) # Display map st.subheader("šŸ“ Map View") view_state = pdk.ViewState( latitude=lat, longitude=lon, zoom=12, pitch=0 ) layer = pdk.Layer( 'ScatterplotLayer', data=map_data, get_position='[lon, lat]', get_color='[255, 0, 0, 160]', get_radius=200, pickable=True ) st.pydeck_chart(pdk.Deck( map_style='mapbox://styles/mapbox/light-v9', initial_view_state=view_state, layers=[layer], tooltip={"text": "{name}\nType: {type}"} )) # Display list st.subheader("šŸ“‹ Relief Centers List") for i, place in enumerate(places, 1): with st.expander(f"{i}. {place['name']}"): st.write(f"**Type:** {place['type'].replace('_', ' ').title()}") st.write(f"**Coordinates:** {place['lat']:.6f}, {place['lon']:.6f}") st.write(f"**Google Maps:** [Open in Maps](https://www.google.com/maps/search/?api=1&query={place['lat']},{place['lon']})") else: st.warning(f"No {place_type}s found near {location_input}. Try a different location or facility type.") else: st.error("Could not find the specified location. Please check the spelling and try again.") elif search_button: st.warning("Please enter a location to search.") def report_incident_tab(): st.header("šŸ“ Report Community Incident") with st.form("incident_report_form"): col1, col2 = st.columns(2) with col1: incident_type = st.selectbox( "Incident Type:", ["Road Block", "Missing Person", "Medical Help Needed", "Fire Emergency", "Flood", "Other Emergency"] ) location = st.text_input("Location:", placeholder="Specific address or landmark") with col2: reporter_name = st.text_input("Your Name (Optional):", placeholder="Anonymous") contact_info = st.text_input("Contact Info (Optional):", placeholder="Phone number or email") description = st.text_area("Description:", placeholder="Provide detailed information about the incident...") submit_button = st.form_submit_button("šŸ“¤ Submit Report", type="primary") if submit_button: if incident_type and location and description: # Create report report = { "id": len(st.session_state.reports) + 1, "type": incident_type, "location": location, "description": description, "reporter": reporter_name if reporter_name else "Anonymous", "contact": contact_info if contact_info else "Not provided", "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "status": "Reported" } st.session_state.reports.insert(0, report) # Add to beginning save_reports() st.success("āœ… Report submitted successfully! Thank you for helping the community.") # Show emergency advice based on incident type if incident_type == "Medical Help Needed": st.info("🚨 For immediate medical emergencies, call 1122") elif incident_type == "Fire Emergency": st.info("🚨 For fire emergencies, call 16 immediately") elif incident_type == "Missing Person": st.info("🚨 Also report to local police: 15") else: st.error("Please fill in all required fields.") # Display recent reports st.subheader("šŸ“‹ Recent Community Reports") if st.session_state.reports: for report in st.session_state.reports[:10]: # Show last 10 reports with st.expander(f"{report['type']} - {report['location']} ({report['timestamp']})"): st.write(f"**Description:** {report['description']}") st.write(f"**Reporter:** {report['reporter']}") st.write(f"**Status:** {report['status']}") if report['contact'] != "Not provided": st.write(f"**Contact:** {report['contact']}") else: st.info("No reports submitted yet. Be the first to help your community!") def emergency_contacts_tab(): st.header("šŸ“ž Emergency Contacts & Safety Resources") contacts = load_emergency_contacts() # Emergency Services st.subheader("🚨 Emergency Services") col1, col2 = st.columns(2) with col1: for contact in contacts["emergency_services"][:2]: st.markdown(f"""

{contact['name']}

{contact['number']}

{contact['description']}

""", unsafe_allow_html=True) with col2: for contact in contacts["emergency_services"][2:]: st.markdown(f"""

{contact['name']}

{contact['number']}

{contact['description']}

""", unsafe_allow_html=True) # Disaster Helplines st.subheader("šŸ¢ Disaster Management Helplines") for contact in contacts["disaster_helplines"]: # Explicitly setting color to ensure visibility on light background st.markdown(f"""

{contact['name']}: {contact['number']}

{contact['description']}

""", unsafe_allow_html=True) # Safety Guidelines st.subheader("šŸ›”ļø Safety Guidelines") for i, guideline in enumerate(contacts["safety_guidelines"], 1): st.markdown(f"**{i}.** {guideline}") # Quick Action Section st.subheader("⚔ Quick Actions") col1, col2, col3 = st.columns(3) with col1: if st.button("šŸ“ž Call Emergency (1122)", type="primary"): st.info("On mobile devices, this would initiate a call to 1122") with col2: if st.button("šŸ“ Share Location"): st.info("Location sharing feature would be activated") with col3: if st.button("🚨 Send Alert"): st.info("Emergency alert would be sent to registered contacts") def ai_summarizer_tab(): st.header("šŸ“„ AI Alert Summarizer") st.markdown("Paste long official disaster alerts below to get a concise AI-powered summary.") # Text input alert_text = st.text_area( "Official Alert Text:", placeholder="Paste the long official disaster alert here...", height=200 ) col1, col2 = st.columns([1, 3]) with col1: summarize_button = st.button("šŸ¤– Summarize Alert", type="primary", disabled=not alert_text) if summarize_button and alert_text: with st.spinner("Analyzing and summarizing the alert..."): summarizer = load_summarizer() if summarizer: try: # Ensure text is not too long for the model max_input_length = 1000 # Adjust based on model limits if len(alert_text) > max_input_length: alert_text = alert_text[:max_input_length] + "..." # Generate summary summary_result = summarizer(alert_text, max_length=150, min_length=30, do_sample=False) summary = summary_result[0]['summary_text'] # Display results st.subheader("šŸ“‹ Summary") st.success("āœ… Alert summarized successfully!") # Format as bullet points sentences = summary.split('. ') st.markdown("**Key Points:**") for i, sentence in enumerate(sentences, 1): if sentence.strip(): sentence = sentence.strip() if not sentence.endswith('.'): sentence += '.' st.markdown(f"• {sentence}") # Additional analysis st.subheader("šŸ“Š Alert Analysis") col1, col2, col3 = st.columns(3) with col1: st.metric("Original Length", f"{len(alert_text)} chars") with col2: st.metric("Summary Length", f"{len(summary)} chars") with col3: compression_ratio = round((1 - len(summary)/len(alert_text)) * 100, 1) st.metric("Compression", f"{compression_ratio}%") # Extract urgency level (simple keyword analysis) urgency_keywords = { 'high': ['immediate', 'urgent', 'emergency', 'critical', 'evacuate', 'danger'], 'medium': ['warning', 'alert', 'caution', 'prepare', 'monitor'], 'low': ['advisory', 'information', 'update', 'notice'] } text_lower = alert_text.lower() urgency_score = {'high': 0, 'medium': 0, 'low': 0} for level, keywords in urgency_keywords.items(): urgency_score[level] = sum(1 for keyword in keywords if keyword in text_lower) urgency_level = max(urgency_score, key=urgency_score.get) urgency_colors = {'high': 'šŸ”“', 'medium': '🟔', 'low': '🟢'} st.markdown(f"**Urgency Level:** {urgency_colors[urgency_level]} {urgency_level.upper()}") except Exception as e: st.error(f"Error generating summary: {e}") st.info("Tip: Try with a shorter text or check your internet connection.") else: st.error("AI summarizer is not available. Please try again later.") # Example alerts st.subheader("šŸ’” Example Usage") example_alert = """ URGENT FLOOD WARNING - DISTRICT LAHORE The Meteorological Department has issued a severe flood warning for Lahore district effective immediately. Heavy monsoon rains of 150-200mm are expected in the next 24 hours. The Ravi River water level has risen to dangerous levels. Citizens living in low-lying areas including Shahdara, Kot Lakhpat, and areas near Ravi River are advised to evacuate immediately. Emergency shelters have been established at Government Schools in each tehsil. All citizens are advised to avoid unnecessary travel and stay indoors. Emergency services are on high alert. For assistance, contact District Emergency Operations Center at 042-99200100. This is a developing situation and updates will be provided regularly through official channels. """ if st.button("Try Example Alert"): st.text_area("Example Alert:", value=example_alert, height=150, key="example") def ai_assistant_tab(): st.header("šŸ¤– AI Assistant") st.markdown("Ask me questions about emergency services, relief centers, or safety guidelines!") # Chat interface if 'chat_history' not in st.session_state: st.session_state.chat_history = [] # Display chat history chat_container = st.container() with chat_container: for i, (question, answer) in enumerate(st.session_state.chat_history): # User message st.markdown(f"""
You: {question}
""", unsafe_allow_html=True) # AI response st.markdown(f"""
AI Assistant:
{answer}
""", unsafe_allow_html=True) # Input form with st.form("chat_form", clear_on_submit=True): user_question = st.text_input( "Ask a question:", placeholder="e.g., Where is the nearest hospital in Karachi?" ) col1, col2 = st.columns([1, 5]) with col1: ask_button = st.form_submit_button("Ask", type="primary") with col2: if st.form_submit_button("Clear Chat"): st.session_state.chat_history = [] st.rerun() if ask_button and user_question: with st.spinner("Thinking..."): # Get AI response ai_response = simple_chatbot(user_question) # Add to chat history st.session_state.chat_history.append((user_question, ai_response)) # Limit chat history to last 10 exchanges if len(st.session_state.chat_history) > 10: st.session_state.chat_history = st.session_state.chat_history[-10:] st.rerun() # Quick question buttons st.subheader("šŸ”— Common Questions") col1, col2 = st.columns(2) with col1: if st.button("šŸ„ Find nearest hospital"): st.session_state.chat_history.append( ("Find nearest hospital", simple_chatbot("Find nearest hospital")) ) st.rerun() if st.button("šŸ“ž Emergency numbers"): st.session_state.chat_history.append( ("Emergency numbers", simple_chatbot("Emergency numbers")) ) st.rerun() with col2: if st.button("šŸ  Find shelter"): st.session_state.chat_history.append( ("Find shelter", simple_chatbot("Find shelter")) ) st.rerun() if st.button("šŸ“ How to report incident"): st.session_state.chat_history.append( ("How to report incident", simple_chatbot("How to report incident")) ) st.rerun() # Footer def show_footer(): st.markdown("---") st.markdown("""

šŸ†˜ DisasterRelief AI Hub - Helping communities in times of need

For immediate emergencies, always call official emergency services: Police (15), Medical (1122), Fire (16)

Built with ā¤ļø using Streamlit and Hugging Face AI

""", unsafe_allow_html=True) if __name__ == "__main__": main() show_footer()