šØ First Aid Emergency Assistant
Your AI-powered emergency response guide
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("""
Your AI-powered emergency response guide