Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140import streamlit as stimport requestsfrom datetime import datetimefrom deep_translator import GoogleTranslatorfrom streamlit_js_eval import get_geolocationfrom geopy.geocoders import Nominatimfrom timezonefinder import TimezoneFinderimport pytz
# API key for GroqGROQ_API_KEY = "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"
# Emergency contactsrescue_contacts = { "Pakistan": { "Ambulance": "115", "Fire Brigade": "16", "Rescue Service": "1122", "Police": "15" }, "India": { "Ambulance": "102", "Fire Brigade": "101", "Disaster Helpline": "108", "Police": "100" }, "USA": {"Emergency Services": "911"}, "United Kingdom": {"Emergency Services": "999"}}
if "history" not in st.session_state: st.session_state.history = []
st.set_page_config(page_title="AI Disaster Assistant", layout="wide")
# π Titlest.markdown("""<h1 style='text-align: center; background-color: #008080; color: white; padding: 1rem; border-radius: 12px;'>π AI Disaster Response Assistant</h1>""", unsafe_allow_html=True)
# π Language selectorlanguage_options = { "English": "en", "Urdu": "ur", "Hindi": "hi", "Japanese": "ja", "Turkish": "tr", "Italian": "it"}preferred_language = st.selectbox("π Select your preferred language:", list(language_options.keys()))target_lang_code = language_options[preferred_language]
# π Location Detectionlocation_data = get_geolocation()user_location = "Unknown"city = ""country = ""timezone_str = ""local_time = datetime.now()
if location_data: lat = location_data['coords']['latitude'] lon = location_data['coords']['longitude'] st.success(f"π GPS Location: {lat:.4f}, {lon:.4f}") try: geolocator = Nominatim(user_agent="geoapiExercises") location = geolocator.reverse((lat, lon), language='en') city = location.raw['address'].get('city', '') or location.raw['address'].get('town', '') country = location.raw['address'].get('country', '') user_location = f"{city}, {country}" st.markdown(f"π You are in *{user_location}*")
tf = TimezoneFinder() timezone_str = tf.timezone_at(lat=lat, lng=lon) if timezone_str: tz = pytz.timezone(timezone_str) local_time = datetime.now(tz) except Exception: st.warning("β οΈ Could not detect full location or time zone.")
# π¨ Emergency numbersif country in rescue_contacts: st.markdown("### π¨ Local Emergency Numbers") for service, number in rescue_contacts[country].items(): st.markdown(f"π **{service}**: {number}")
# π§ Ask user promptcol1, col2 = st.columns([2, 1])with col1: st.markdown("### Ask Your Disaster Question:") user_input = st.text_area(" ", placeholder="e.g., What to do in a flood?", height=120)
if st.button("π Get Help"): if user_input.strip() != "": try: translated_input = GoogleTranslator(source='auto', target='en').translate(user_input) prompt = f"The user is currently in {user_location}. Please provide disaster-specific advice and safety tips for this question: {translated_input}"
headers = { "Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json" } data = { "model": "llama3-70b-8192", "messages": [{"role": "user", "content": prompt}] }
response = requests.post("https://api.groq.com/openai/v1/chat/completions", headers=headers, json=data)
if response.status_code == 200: answer_en = response.json()['choices'][0]['message']['content'] translated_answer = GoogleTranslator(source='en', target=target_lang_code).translate(answer_en)
timestamp = local_time.strftime("%I:%M %p") st.session_state.history.append({"time": timestamp, "question": user_input})
st.markdown(f"<div style='background:#d6f5f5;padding:1rem;border-radius:10px;color:#000'>{translated_answer}</div>", unsafe_allow_html=True) else: st.error("β API error: " + response.text) except Exception as e: st.error(f"β οΈ Error: {e}")
# π Chat historywith col2: st.markdown("### π Chat History") if st.session_state.history: for entry in reversed(st.session_state.history): st.markdown(f""" <div style='background:#f0f0f0;padding:0.5rem;border-radius:10px;color:#000;margin-bottom:0.5rem'> π {entry['time']}<br><b>{entry['question']}</b> </div> """, unsafe_allow_html=True) else: st.info("No previous questions.")
if st.button("π§Ή Clear History"): st.session_state.history = [] st.success("Chat history cleared.")app.pyAdded+140