Spaces:
Sleeping
Sleeping
import streamlit as st | |
import os | |
from datetime import datetime | |
from huggingface_hub import HfApi | |
# Set page config first, before any other Streamlit commands | |
st.set_page_config( | |
page_title="Emergency Response Assistant", | |
page_icon="🚨", | |
layout="wide" | |
) | |
# Language configuration | |
LANGUAGES = { | |
"English": { | |
"code": "en", | |
"chat_placeholder": "Describe the emergency situation", | |
"emergency_types": [ | |
"Medical Emergency", | |
"Natural Disaster", | |
"Fire Emergency", | |
"Security Threat", | |
"Power Outage", | |
"Other" | |
], | |
"priority_levels": ["Low", "Medium", "High", "Critical"], | |
"location_label": "Your Location (optional)" | |
}, | |
"Kiswahili": { | |
"code": "sw", | |
"chat_placeholder": "Elezea hali ya dharura", | |
"emergency_types": [ | |
"Dharura ya Kiafya", | |
"Maafa ya Asili", | |
"Dharura ya Moto", | |
"Tishio la Usalama", | |
"Kukatika kwa Umeme", | |
"Nyingine" | |
], | |
"priority_levels": ["Chini", "Wastani", "Juu", "Muhimu sana"], | |
"location_label": "Eneo lako (hiari)" | |
} | |
} | |
# Initialize session state | |
if "messages" not in st.session_state: | |
st.session_state.messages = [] | |
st.session_state.last_action = None | |
if "language" not in st.session_state: | |
st.session_state.language = "English" | |
# Initialize Groq client with debug logs | |
client = None | |
try: | |
# First, try to import the default way | |
try: | |
st.info("Attempting to import Groq...") | |
from groq import Groq | |
st.success("Successfully imported Groq") | |
except ImportError: | |
# If that fails, try the alternative import (groq_sdk) | |
try: | |
st.info("Attempting to import from groq_sdk...") | |
from groq_sdk import Groq | |
st.success("Successfully imported Groq from groq_sdk") | |
except ImportError: | |
st.error("Failed to import Groq. Make sure 'groq' or 'groq_sdk' is installed.") | |
Groq = None | |
# Now try to get the API key and initialize the client | |
if Groq is not None: | |
try: | |
st.info("Attempting to get API key from environment or Hugging Face...") | |
api_key = os.environ.get('GROQ_API_KEY') | |
if not api_key: | |
st.info("API key not found in environment, trying Hugging Face Space variables...") | |
try: | |
api_key = HfApi().get_space_variables("smainye/Emergency-bot").get('GROQ_API_KEY') | |
if api_key: | |
st.success("Successfully retrieved API key from Hugging Face") | |
else: | |
st.error("API key not found in Hugging Face Space variables") | |
except Exception as e: | |
st.error(f"Error retrieving API key from Hugging Face: {str(e)}") | |
else: | |
st.success("Successfully retrieved API key from environment") | |
if api_key: | |
client = Groq(api_key=api_key) | |
st.success("Successfully initialized Groq client") | |
else: | |
st.error("Failed to get API key") | |
except Exception as e: | |
st.error(f"Error initializing Groq client: {str(e)}") | |
except Exception as e: | |
st.error(f"Unexpected error during Groq setup: {str(e)}") | |
# Language selection in sidebar | |
with st.sidebar: | |
st.session_state.language = st.radio( | |
"Language/Lugha", | |
list(LANGUAGES.keys()), | |
horizontal=True | |
) | |
# Get current language config | |
lang_config = LANGUAGES[st.session_state.language] | |
# Title and description | |
st.title("🚨 Emergency Response Assistant") | |
st.markdown(""" | |
AI-powered emergency assistance / Msaada wa dharura wa AI | |
""") | |
# Sidebar configuration | |
with st.sidebar: | |
st.header("Emergency Configuration / Mipangilio ya Dharura") | |
emergency_type = st.selectbox( | |
"Select Emergency Type / Chagua Aina ya Dharura", | |
lang_config["emergency_types"], | |
key="emerg_type" | |
) | |
priority = st.radio( | |
"Priority Level / Kipaumbele", | |
lang_config["priority_levels"], | |
horizontal=True, | |
key="priority_level" | |
) | |
user_location = st.text_input( | |
lang_config["location_label"], | |
key="user_loc" | |
) | |
# Display chat history | |
for i, message in enumerate(st.session_state.messages): | |
with st.chat_message(message["role"]): | |
st.markdown(message["content"]) | |
# Chat input | |
if prompt := st.chat_input(lang_config["chat_placeholder"], key="chat_input"): | |
if st.session_state.last_action != prompt: | |
st.session_state.messages.append({"role": "user", "content": prompt}) | |
st.session_state.last_action = prompt | |
st.rerun() | |
# Generate response | |
if (st.session_state.messages and | |
st.session_state.messages[-1]["role"] == "user" and | |
(len(st.session_state.messages) % 2 == 1)): | |
with st.chat_message("assistant"): | |
if client is None: | |
error_msg = { | |
"English": "Sorry, the AI service is not available. Please check if the Groq API key is properly configured.", | |
"Kiswahili": "Samahani, huduma ya AI haipatikani. Tafadhali angalia kama ufunguo wa API ya Groq umesanidiwa vizuri." | |
} | |
st.error(error_msg[st.session_state.language]) | |
st.session_state.messages.append({ | |
"role": "assistant", | |
"content": error_msg[st.session_state.language] | |
}) | |
else: | |
with st.spinner("Generating response... / Inatengeneza majibu..."): | |
try: | |
context = f""" | |
EMERGENCY TYPE: {emergency_type} | |
PRIORITY: {priority} | |
LOCATION: {user_location if user_location else 'Unknown'} | |
LANGUAGE: {st.session_state.language} | |
USER REQUEST: {st.session_state.messages[-1]['content']} | |
Provide response in {st.session_state.language}. | |
Include numbered steps, safety advice, and contacts. | |
Be concise and clear. | |
""" | |
response = client.chat.completions.create( | |
messages=[{"role": "user", "content": context}], | |
model="llama3-70b-8192", | |
temperature=0.3, | |
max_tokens=1024 | |
) | |
assistant_response = response.choices[0].message.content | |
st.markdown(assistant_response) | |
st.session_state.messages.append({"role": "assistant", "content": assistant_response}) | |
except Exception as e: | |
error_msg = { | |
"English": "Sorry, I couldn't generate a response. Please try again.", | |
"Kiswahili": "Samahani, sikuweza kutengeneza majibu. Tafadhali jaribu tena." | |
} | |
st.error(f"Error: {str(e)}") | |
st.session_state.messages.append({ | |
"role": "assistant", | |
"content": error_msg[st.session_state.language] | |
}) | |
# Footer | |
st.markdown("---") | |
st.caption(f""" | |
Emergency Response Assistant v3.3 | {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} | |
Msaada wa Dharura wa AI | Toleo 3.3 | |
""") |