Spaces:
Sleeping
Sleeping
| # updated_app.py | |
| 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 (unchanged for brevity, keep original styling from your code) | |
| # ... [unchanged CSS block here] ... | |
| # Initialize GROQ API Key from secrets | |
| def setup_groq(): | |
| api_key = st.secrets.get("GROQ_API_KEY") | |
| if not api_key: | |
| st.error("⚠️ GROQ API key not found in secrets! Please add it to .streamlit/secrets.toml") | |
| st.stop() | |
| return api_key | |
| # Load and process PDF | |
| 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.") | |
| st.stop() | |
| except Exception as e: | |
| st.error(f"❌ Error loading PDF: {str(e)}") | |
| st.stop() | |
| # Setup embeddings and knowledge base | |
| def setup_knowledge_base(): | |
| pdf_text = load_pdf() | |
| 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()) | |
| model = SentenceTransformer('all-MiniLM-L6-v2') | |
| chunk_embeddings = model.encode(chunks) | |
| return chunks, chunk_embeddings, model | |
| def find_relevant_context(query, chunks, chunk_embeddings, model, top_k=3): | |
| query_embedding = model.encode([query]) | |
| similarities = cosine_similarity(query_embedding, chunk_embeddings)[0] | |
| top_indices = np.argsort(similarities)[-top_k:][::-1] | |
| return "\n\n".join([chunks[i] for i in top_indices]) | |
| def query_groq(prompt, api_key): | |
| 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. \nIMPORTANT RULES:\n1. Only answer questions related to first aid, medical emergencies, and health safety\n2. If asked about non-medical topics, politely redirect to first aid topics\n3. For serious emergencies, always remind users to call emergency services first\n4. Provide clear, numbered steps when giving instructions\n5. Keep responses focused and practical\nIf 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.\""".strip() | |
| }, | |
| { | |
| "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 UI, Sidebar, and Input box (unchanged from original) | |
| # ... [keep the rest of your UI and chat input logic unchanged] ... | |
| # Add "Clear Chat" button | |
| if st.sidebar.button("🧹 Clear Chat"): | |
| st.session_state.messages = [st.session_state.messages[0]] | |
| st.rerun() | |
| # Handle user input and response (unchanged) | |
| # ... [same as original block with improved exception handling if desired] ... |