Haseeb-001 commited on
Commit
96fd1a1
Β·
verified Β·
1 Parent(s): 3769d1e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -37
app.py CHANGED
@@ -33,14 +33,17 @@ except Exception:
33
  embedding_dim = 768
34
  index = faiss.IndexFlatL2(embedding_dim)
35
 
36
- # Function to Check if Query is Related to Epilepsy
37
  def preprocess_query(query):
38
  tokens = query.lower().split()
39
  epilepsy_keywords = ["seizure", "epilepsy", "convulsion", "neurology", "brain activity"]
 
40
 
41
  is_epilepsy_related = any(k in tokens for k in epilepsy_keywords)
 
 
42
 
43
- return tokens, is_epilepsy_related
44
 
45
  # Function to Generate Response with Chat History
46
  def generate_response(user_query, chat_history):
@@ -65,7 +68,7 @@ def generate_response(user_query, chat_history):
65
  corrected_query = user_query # Fallback to original query if correction fails
66
  print(f"⚠️ Grammar correction error: {e}") # Optional: Log the error for debugging
67
 
68
- tokens, is_epilepsy_related = preprocess_query(corrected_query) # Use corrected query for processing
69
 
70
  # Greeting Responses
71
  greetings = ["hello", "hi", "hey"]
@@ -109,43 +112,33 @@ def generate_response(user_query, chat_history):
109
 
110
  return f"**NeuroGuard:** βœ… **Analysis:**\n{pubmedbert_insights}\n\n**Response:**\n{model_response}"
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
- # If Not Epilepsy Related - Try to Answer as General Health Query
114
- else:
115
- # Try Getting Medical Insights from PubMedBERT (even for general health)
116
- try:
117
- pubmedbert_embeddings = pubmedbert_pipeline(corrected_query)
118
- embedding_mean = np.mean(pubmedbert_embeddings[0], axis=0)
119
- index.add(np.array([embedding_mean]))
120
- pubmedbert_insights = "**PubMedBERT Analysis:** PubMed analysis performed for health-related context." # General analysis message
121
- except Exception as e:
122
- pubmedbert_insights = f"⚠️ Error during PubMedBERT analysis: {e}"
123
-
124
- # Use LLaMA for General Health Response Generation with Chat History Context
125
- try:
126
- prompt_history = ""
127
- if chat_history:
128
- prompt_history += "**Chat History:**\n"
129
- for message in chat_history:
130
- prompt_history += f"{message['role'].capitalize()}: {message['content']}\n"
131
- prompt_history += "\n"
132
-
133
- general_health_prompt = f"""
134
- {prompt_history}
135
- **User Query:** {corrected_query}
136
- **Instructions:** Provide a concise, structured, and human-friendly response to the general health query, considering the conversation history if available. If the query is clearly not health-related, respond generally.
137
- """
138
 
139
- chat_completion = client.chat.completions.create(
140
- messages=[{"role": "user", "content": general_health_prompt}],
141
- model="llama-3.3-70b-versatile",
142
- stream=False,
143
- )
144
- model_response = chat_completion.choices[0].message.content.strip()
145
- except Exception as e:
146
- model_response = f"⚠️ Error generating response with LLaMA: {e}"
147
 
148
- return f"**NeuroGuard:** βœ… **Analysis:**\n{pubmedbert_insights}\n\n**Response:**\n{model_response}"
 
 
149
 
150
 
151
  # Streamlit UI Setup
 
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"]
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):
 
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"]
 
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
116
+ elif is_healthcare_related:
117
+ general_health_tips = (
118
+ "For general health and well-being:\n"
119
+ "- πŸ’§ Stay hydrated by drinking plenty of water throughout the day.\n"
120
+ "- 🍎 Maintain a balanced diet rich in fruits, vegetables, and whole grains.\n"
121
+ "- πŸšΆβ€β™€οΈ Incorporate regular physical activity into your daily routine.\n"
122
+ "- 😴 Ensure you get adequate sleep to allow your body to rest and recover.\n"
123
+ "- 🧘 Practice stress-reducing activities such as deep breathing or meditation.\n"
124
+ "- 🩺 **Important:** These tips are for general wellness. Always consult a healthcare professional for any specific health concerns or before making significant changes to your health regimen."
125
+ )
126
+ return (
127
+ f"**NeuroGuard:** 🩺 It sounds like your question '{user_query}' is about general health. While I specialize in epilepsy, here are some general wellness tips that might be helpful:\n\n" # Use original user_query in response
128
+ f"{general_health_tips}"
129
+ )
130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
+ # If General Query (Not Healthcare or Epilepsy Related) - Provide a different response
133
+ elif is_general:
134
+ return (
135
+ 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"
136
+ "**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."
137
+ )
 
 
138
 
139
+ # Fallback - should ideally not reach here
140
+ else:
141
+ return "πŸ€” I'm not sure how to respond to that."
142
 
143
 
144
  # Streamlit UI Setup