import streamlit as st import PyPDF2 import requests import json from sentence_transformers import SentenceTransformer import numpy as np from sklearn.metrics.pairwise import cosine_similarity import os from datetime import datetime # Page configuration st.set_page_config( page_title="🚨 First Aid Emergency Assistant", page_icon="🚨", layout="wide", initial_sidebar_state="collapsed" ) # Custom CSS for ChatGPT-like interface st.markdown(""" """, unsafe_allow_html=True) # Initialize GROQ API @st.cache_resource def setup_groq(): os.getenv("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") if not groq_api_key: st.error("āš ļø GROQ API key not found! Please add it to your Hugging Face secrets.") st.stop() return groq_api_key # Load and process PDF @st.cache_resource def load_pdf(): try: with open("First-Aid.pdf", "rb") as file: pdf_reader = PyPDF2.PdfReader(file) text = "" for page in pdf_reader.pages: text += page.extract_text() + "\n" return text except FileNotFoundError: st.error("šŸ“„ First-Aid.pdf not found! Please upload the PDF file to your space.") st.stop() except Exception as e: st.error(f"āŒ Error loading PDF: {str(e)}") st.stop() # Setup embeddings and knowledge base @st.cache_resource def setup_knowledge_base(): # Load PDF content pdf_text = load_pdf() # Split text into chunks chunks = [] sentences = pdf_text.split('\n') current_chunk = "" for sentence in sentences: if len(current_chunk + sentence) < 1000: current_chunk += sentence + "\n" else: if current_chunk.strip(): chunks.append(current_chunk.strip()) current_chunk = sentence + "\n" if current_chunk.strip(): chunks.append(current_chunk.strip()) # Load sentence transformer model model = SentenceTransformer('all-MiniLM-L6-v2') # Create embeddings for chunks chunk_embeddings = model.encode(chunks) return chunks, chunk_embeddings, model def find_relevant_context(query, chunks, chunk_embeddings, model, top_k=3): """Find most relevant chunks for the query""" query_embedding = model.encode([query]) similarities = cosine_similarity(query_embedding, chunk_embeddings)[0] top_indices = np.argsort(similarities)[-top_k:][::-1] relevant_chunks = [chunks[i] for i in top_indices] return "\n\n".join(relevant_chunks) def query_groq(prompt, api_key): """Query GROQ API""" url = "https://api.groq.com/openai/v1/chat/completions" headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } data = { "model": "mixtral-8x7b-32768", "messages": [ { "role": "system", "content": """You are a First Aid Emergency Assistant. You provide clear, step-by-step first aid guidance based on the provided medical manual context. IMPORTANT RULES: 1. Only answer questions related to first aid, medical emergencies, and health safety 2. If asked about non-medical topics, politely redirect to first aid topics 3. For serious emergencies, always remind users to call emergency services first 4. Provide clear, numbered steps when giving instructions 5. Keep responses focused and practical If the question is not related to first aid or medical emergencies, respond with: "🚨 I'm specialized in First Aid emergencies only! Please ask me about medical emergencies, CPR, wounds, burns, fractures, or other first aid topics." """ }, { "role": "user", "content": prompt } ], "temperature": 0.3, "max_tokens": 1000 } try: response = requests.post(url, headers=headers, json=data, timeout=30) response.raise_for_status() return response.json()["choices"][0]["message"]["content"] except requests.exceptions.RequestException as e: return f"āŒ Error connecting to GROQ API: {str(e)}" except Exception as e: return f"āŒ Error processing response: {str(e)}" # Initialize session state if "messages" not in st.session_state: st.session_state.messages = [ { "role": "assistant", "content": "🚨 **Hello! I'm your First Aid Emergency Assistant.**\n\nI can help you with:\n• CPR procedures\n• Bleeding control\n• Burns treatment\n• Choking response\n• Fracture management\n• Poisoning emergencies\n• And much more!\n\nšŸ’” **Ask me anything about first aid emergencies!**" } ] if "knowledge_base" not in st.session_state: with st.spinner("šŸ”„ Loading First Aid knowledge base..."): chunks, embeddings, model = setup_knowledge_base() st.session_state.knowledge_base = { "chunks": chunks, "embeddings": embeddings, "model": model } if "groq_api_key" not in st.session_state: st.session_state.groq_api_key = setup_groq() # Header st.markdown("""

🚨 First Aid Emergency Assistant

Your AI-powered emergency response guide

""", unsafe_allow_html=True) # Warning disclaimer st.markdown("""
āš ļø IMPORTANT MEDICAL DISCLAIMER:
This chatbot provides general first aid guidance only. In real emergencies, always call emergency services immediately. This tool is not a substitute for professional medical advice, diagnosis, or treatment.
""", unsafe_allow_html=True) # Chat container chat_container = st.container() with chat_container: st.markdown('
', unsafe_allow_html=True) # Display chat messages for message in st.session_state.messages: if message["role"] == "user": st.markdown(f"""
You: {message["content"]}
""", unsafe_allow_html=True) else: st.markdown(f"""
šŸ¤– First Aid Assistant:
{message["content"]}
""", unsafe_allow_html=True) st.markdown('
', unsafe_allow_html=True) # Input section st.markdown('
', unsafe_allow_html=True) col1, col2 = st.columns([4, 1]) with col1: user_input = st.text_input( "", placeholder="Ask me about first aid emergencies... (e.g., 'How to treat burns?')", key="user_input", label_visibility="collapsed" ) with col2: send_button = st.button("Send šŸš€", key="send_button") st.markdown('
', unsafe_allow_html=True) # Process user input if send_button and user_input.strip(): # Add user message to chat st.session_state.messages.append({"role": "user", "content": user_input}) # Get bot response with st.spinner("šŸ¤” Thinking..."): try: # Find relevant context from PDF kb = st.session_state.knowledge_base context = find_relevant_context( user_input, kb["chunks"], kb["embeddings"], kb["model"] ) # Create enhanced prompt with context enhanced_prompt = f""" Based on the following first aid manual content, answer this question: {user_input} Context from First Aid Manual: {context} Please provide a clear, helpful response based on this information. If this is a serious emergency, remind the user to call emergency services first. """ # Query GROQ API response = query_groq(enhanced_prompt, st.session_state.groq_api_key) # Enhance response with emergency reminder for serious cases serious_keywords = ['heart attack', 'stroke', 'unconscious', 'not breathing', 'severe bleeding', 'poisoning', 'choking'] if any(keyword in user_input.lower() for keyword in serious_keywords): response = f"🚨 **CALL EMERGENCY SERVICES IMMEDIATELY!**\n\n{response}" except Exception as e: response = f"āŒ Sorry, I encountered an error: {str(e)}. Please try asking your question differently." # Add bot response to chat st.session_state.messages.append({"role": "assistant", "content": response}) # Rerun to show new message st.rerun() # Sidebar with helpful information with st.sidebar: st.markdown("## šŸ“‹ Quick Emergency Numbers") st.markdown(""" """, unsafe_allow_html=True) st.markdown("## šŸŽÆ What I Can Help With") st.markdown(""" """, unsafe_allow_html=True) st.markdown("## ā„¹ļø How to Use") st.markdown(""" """, unsafe_allow_html=True) # Footer st.markdown("---") st.markdown("""
šŸ¤– First Aid Emergency Assistant | Powered by GROQ AI | Always consult medical professionals for serious emergencies
""", unsafe_allow_html=True)