Haseeb-001 commited on
Commit
9d63b8a
·
verified ·
1 Parent(s): 45cb7cf

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -185
app.py DELETED
@@ -1,185 +0,0 @@
1
- import os
2
- import streamlit as st
3
- import numpy as np
4
- import faiss
5
- from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification, AutoModel
6
- from groq import Groq
7
-
8
- # Load API Key from Environment
9
- groq_api_key = os.environ.get("GROQ_API_KEY")
10
- if groq_api_key is None:
11
- st.error("GROQ_API_KEY environment variable not set.")
12
- st.stop()
13
-
14
- # Initialize Groq Client
15
- try:
16
- client = Groq(api_key=groq_api_key)
17
- except Exception as e:
18
- st.error(f"Error initializing Groq client: {e}")
19
- st.stop()
20
-
21
- # Load PubMedBERT Model (Try Groq API first, then Hugging Face)
22
- try:
23
- pubmedbert_tokenizer = AutoTokenizer.from_pretrained("NeuML/pubmedbert-base-embeddings")
24
- pubmedbert_model = AutoModel.from_pretrained("NeuML/pubmedbert-base-embeddings")
25
- pubmedbert_pipeline = pipeline('feature-extraction', model=pubmedbert_model, tokenizer=pubmedbert_tokenizer, device=-1)
26
- except Exception:
27
- st.warning("Error loading PubMedBERT from Groq API. Using Hugging Face model.")
28
- pubmedbert_tokenizer = AutoTokenizer.from_pretrained("microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract-fulltext")
29
- pubmedbert_model = AutoModelForSequenceClassification.from_pretrained("microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract-fulltext")
30
- pubmedbert_pipeline = pipeline('feature-extraction', model=pubmedbert_model, tokenizer=pubmedbert_tokenizer, device=-1)
31
-
32
- # Initialize FAISS Index
33
- embedding_dim = 768
34
- index = faiss.IndexFlatL2(embedding_dim)
35
-
36
- # Function to Check Query Category
37
- def preprocess_query(query):
38
- tokens = query.lower().split()
39
- epilepsy_keywords = ["seizure", "epilepsy", "convulsion", "neurology", "brain activity", "headache related to epilepsy"] # Added specific phrase
40
- healthcare_keywords = ["headache", "fever", "blood pressure", "diabetes", "cough", "flu", "nutrition", "mental health", "pain", "legs", "body pain", "health", "medical", "symptoms", "treatment", "disease"] # Extended healthcare keywords
41
-
42
- is_epilepsy_related = any(k in tokens for k in epilepsy_keywords)
43
- is_healthcare_related = any(k in tokens for k in healthcare_keywords) and not is_epilepsy_related # Healthcare but NOT epilepsy
44
- is_general = not is_epilepsy_related and not is_healthcare_related # Truly general queries
45
-
46
- return tokens, is_epilepsy_related, is_healthcare_related, is_general
47
-
48
- # Function to Generate Response with Chat History
49
- def generate_response(user_query, chat_history):
50
- # Grammatical Correction using LLaMA (Hidden from User)
51
- try:
52
- correction_prompt = f"""
53
- Correct the following user query for grammar and spelling errors, but keep the original intent intact.
54
- Do not add or remove any information, just fix the grammar.
55
- User Query: {user_query}
56
- Corrected Query:
57
- """
58
- grammar_completion = client.chat.completions.create(
59
- messages=[{"role": "user", "content": correction_prompt}],
60
- model="llama-3.3-70b-versatile",
61
- stream=False,
62
- )
63
- corrected_query = grammar_completion.choices[0].message.content.strip()
64
- # If correction fails or returns empty, use original query
65
- if not corrected_query:
66
- corrected_query = user_query
67
- except Exception as e:
68
- corrected_query = user_query # Fallback to original query if correction fails
69
- print(f"⚠️ Grammar correction error: {e}") # Optional: Log the error for debugging
70
-
71
- tokens, is_epilepsy_related, is_healthcare_related, is_general = preprocess_query(corrected_query) # Get category flags
72
-
73
- # Greeting Responses
74
- greetings = ["hello", "hi", "hey"]
75
- if any(word in tokens for word in greetings):
76
- return "👋 Hello! How can I assist you today?"
77
-
78
- # If Epilepsy Related - Use Epilepsy Focused Response
79
- if is_epilepsy_related:
80
- # Try Getting Medical Insights from PubMedBERT
81
- try:
82
- pubmedbert_embeddings = pubmedbert_pipeline(corrected_query) # Use corrected query for PubMedBERT
83
- embedding_mean = np.mean(pubmedbert_embeddings[0], axis=0)
84
- index.add(np.array([embedding_mean]))
85
- pubmedbert_insights = "**PubMedBERT Analysis:** ✅ Query is relevant to epilepsy research."
86
- except Exception as e:
87
- pubmedbert_insights = f"⚠️ Error during PubMedBERT analysis: {e}"
88
-
89
- # Use LLaMA for Final Response Generation with Chat History Context (Epilepsy Focus)
90
- try:
91
- prompt_history = ""
92
- if chat_history:
93
- prompt_history += "**Chat History:**\n"
94
- for message in chat_history:
95
- prompt_history += f"{message['role'].capitalize()}: {message['content']}\n"
96
- prompt_history += "\n"
97
-
98
- epilepsy_prompt = f"""
99
- {prompt_history}
100
- **User Query:** {corrected_query} # Use corrected query for final response generation
101
- **Instructions:** Provide a concise, structured, and human-friendly response specifically about epilepsy or seizures, considering the conversation history if available.
102
- """
103
-
104
- chat_completion = client.chat.completions.create(
105
- messages=[{"role": "user", "content": epilepsy_prompt}],
106
- model="llama-3.3-70b-versatile",
107
- stream=False,
108
- )
109
- model_response = chat_completion.choices[0].message.content.strip()
110
- except Exception as e:
111
- model_response = f"⚠️ Error generating response with LLaMA: {e}"
112
-
113
- return f"**NeuroGuard:** ✅ **Analysis:**\n{pubmedbert_insights}\n\n**Response:**\n{model_response}"
114
-
115
- # If Healthcare Related but Not Epilepsy - Provide General Wellness Tips and Basic Remedies
116
- elif is_healthcare_related:
117
- remedy_suggestions = {
118
- "headache": "For headaches, you can try resting in a quiet, dark room, staying hydrated, and applying a cold compress to your forehead. Over-the-counter pain relievers like ibuprofen or acetaminophen may also help.",
119
- "pain": "For general pain, rest, gentle stretching, and applying heat or ice to the affected area can provide relief. Over-the-counter pain relievers might also be beneficial. ",
120
- "legs pain": "For leg pain, try elevating your legs, applying heat or ice, and gentle stretching exercises. Staying hydrated and ensuring good circulation can also help. "
121
- # Add more specific remedies as needed
122
- }
123
- suggested_remedy = "For general wellness:\n" # Default if no specific remedy keyword is found
124
- for keyword, remedy in remedy_suggestions.items():
125
- if keyword in corrected_query: # Check corrected query for keywords
126
- suggested_remedy = remedy + "\n\n" # Use specific remedy if keyword found
127
- break # Use only the first matching remedy for now
128
-
129
- general_health_tips = (
130
- "- 💧 Stay hydrated by drinking plenty of water throughout the day.\n"
131
- "- 🍎 Maintain a balanced diet rich in fruits, vegetables, and whole grains.\n"
132
- "- 🚶‍♀️ Incorporate regular physical activity into your daily routine.\n"
133
- "- 😴 Ensure you get adequate sleep to allow your body to rest and recover.\n"
134
- "- 🧘 Practice stress-reducing activities such as deep breathing or meditation.\n"
135
- "- 🩺 **Important:** These tips are for general wellness and informational purposes only, and are not medical advice. Always consult a healthcare professional for any specific health concerns or before making significant changes to your health regimen."
136
- )
137
-
138
- response_content = f"**NeuroGuard:** 🩺 It seems your question '{user_query}' is about general health. While I focus on epilepsy, here's some information that might help:\n\n" # Use original user_query
139
- response_content += suggested_remedy
140
- response_content += general_health_tips # Always include general tips
141
-
142
- return response_content
143
-
144
-
145
- # If General Query (Not Healthcare or Epilepsy Related) - Provide a different response
146
- elif is_general:
147
- return (
148
- f"**NeuroGuard:** 💡 My expertise is focused on epilepsy and general health. For topics outside of these areas, like '{user_query}', I may not be the best resource. \n\n" # Use original user_query
149
- "**Tip:** For general knowledge questions, you might find better answers using a general search engine or a chatbot trained on a broader range of topics."
150
- )
151
-
152
- # Fallback - should ideally not reach here
153
- else:
154
- return "🤔 I'm not sure how to respond to that."
155
-
156
-
157
- # Streamlit UI Setup
158
- st.set_page_config(page_title="NeuroGuard: Epilepsy & Health Chatbot", layout="wide") # Updated title
159
- st.title("🧠 NeuroGuard: Epilepsy & Health Chatbot") # Updated title
160
- st.write("💬 Ask me anything about epilepsy, seizures, and general health. I remember our conversation!") # Updated description
161
-
162
- # Initialize Chat History in Session State
163
- if "chat_history" not in st.session_state:
164
- st.session_state.chat_history = []
165
-
166
- # Display Chat History
167
- for message in st.session_state.chat_history:
168
- with st.chat_message(message["role"]):
169
- st.markdown(message["content"])
170
-
171
- # User Input
172
- if prompt := st.chat_input("Type your question here..."):
173
- st.session_state.chat_history.append({"role": "user", "content": prompt})
174
- with st.chat_message("user"):
175
- st.markdown(prompt)
176
-
177
- # Generate Bot Response
178
- with st.chat_message("bot"):
179
- with st.spinner("🤖 Thinking..."):
180
- try:
181
- response = generate_response(prompt, st.session_state.chat_history) # Pass chat history here
182
- st.markdown(response)
183
- st.session_state.chat_history.append({"role": "bot", "content": response})
184
- except Exception as e:
185
- st.error(f"⚠️ Error processing query: {e}")