Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -6,6 +6,7 @@ import requests
|
|
6 |
from bs4 import BeautifulSoup
|
7 |
import re
|
8 |
from urllib.parse import quote_plus
|
|
|
9 |
|
10 |
# Groq API setup
|
11 |
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
|
@@ -33,249 +34,76 @@ def google_search(query):
|
|
33 |
'link': link,
|
34 |
'snippet': snippet.text
|
35 |
})
|
36 |
-
return results[:3]
|
37 |
except Exception as e:
|
38 |
-
st.error(f"
|
39 |
return []
|
40 |
|
41 |
-
#
|
42 |
-
def
|
43 |
-
patterns = [
|
44 |
-
r'(\d+[\s-]*\d*\s*(بار|قطرے|گولیاں|خوارج)\s*(فی دن|روزانہ))',
|
45 |
-
r'(دن میں \d+\s*بار)',
|
46 |
-
r'(\d+-\d+\s*گھنٹے کے وقفے سے)'
|
47 |
-
]
|
48 |
-
|
49 |
-
for pattern in patterns:
|
50 |
-
match = re.search(pattern, text)
|
51 |
-
if match:
|
52 |
-
return match.group()
|
53 |
-
return "دن میں 3 بار (ڈیفالٹ)"
|
54 |
-
|
55 |
-
# Chatbot logic
|
56 |
-
def homeo_chatbot_urdu(user_input):
|
57 |
-
# Step 1: Symptom extraction in Urdu
|
58 |
-
symptom_prompt = f"""صارف کی تفصیل: {user_input}
|
59 |
-
ہومیوپیتھک علامات کو انگلش میں کاما سے علیحدہ فہرست میں نکالیں۔
|
60 |
-
مثال: headache, dry cough, fever with chills"""
|
61 |
-
|
62 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
symptom_response = client.chat.completions.create(
|
64 |
messages=[{"role": "user", "content": symptom_prompt}],
|
65 |
model="llama3-70b-8192",
|
66 |
temperature=0.2
|
67 |
)
|
68 |
symptoms = symptom_response.choices[0].message.content.split(", ")
|
69 |
-
except Exception as e:
|
70 |
-
return f"ایرر: {str(e)}"
|
71 |
-
|
72 |
-
# Step 2: Web search for remedies
|
73 |
-
search_query = f"homeopathic remedies for {' '.join(symptoms)} site:.edu OR site:.gov"
|
74 |
-
search_results = google_search(search_query)
|
75 |
-
|
76 |
-
remedies = []
|
77 |
-
for result in search_results:
|
78 |
-
remedies.append({
|
79 |
-
'title': result['title'],
|
80 |
-
'link': result['link'],
|
81 |
-
'content': result['snippet']
|
82 |
-
})
|
83 |
-
|
84 |
-
# Step 3: Prepare response in Urdu
|
85 |
-
final_response = "🌿 **تجویز کردہ ہومیوپیتھک علاج:**\n\n"
|
86 |
-
for idx, remedy in enumerate(remedies, 1):
|
87 |
-
dosage = extract_dosage_info(remedy['content'])
|
88 |
-
final_response += f"""\
|
89 |
-
**آپشن {idx}:**
|
90 |
-
- **دوا:** {remedy['content'].split(' ')[0]}
|
91 |
-
- **علامات:** {', '.join(symptoms[:3])}
|
92 |
-
- **خوارک:** {dosage}
|
93 |
-
- **طریقہ استعمال:** {"5 قطرے پانی میں" if 'قطرے' in dosage else "2 گولیاں"}
|
94 |
-
- **دورانیہ:** {"3 دن" if 'حاد' in user_input else "1 ہفتہ"}
|
95 |
-
- **ماخذ:** [{remedy['title']}]({remedy['link']})
|
96 |
-
|
97 |
-
"""
|
98 |
-
|
99 |
-
return final_response
|
100 |
-
|
101 |
-
# Streamlit UI in Urdu
|
102 |
-
st.set_page_config(page_title="ہومیوپیتھک ڈاکٹر", page_icon="🌿")
|
103 |
-
|
104 |
-
# Urdu interface
|
105 |
-
st.title("🌐 لائیو ہومیوپیتھک مشیر")
|
106 |
-
st.markdown("""
|
107 |
-
<style>
|
108 |
-
[data-testid="stMarkdownContainer"] ul {
|
109 |
-
padding-right: 40px;
|
110 |
-
}
|
111 |
-
</style>
|
112 |
-
""", unsafe_allow_html=True)
|
113 |
-
|
114 |
-
# Chat history
|
115 |
-
if "messages" not in st.session_state:
|
116 |
-
st.session_state.messages = [
|
117 |
-
{"role": "assistant", "content": "السلام علیکم! آپ کی کیا علامات ہیں؟ مثالوں:\n- سر درد اور چکر آنا\n- کھانسی کے ساتھ بخار\n- پیٹ درد اور بھوک نہ لگنا"}
|
118 |
-
]
|
119 |
-
|
120 |
-
for message in st.session_state.messages:
|
121 |
-
with st.chat_message(message["role"]):
|
122 |
-
st.markdown(message["content"])
|
123 |
-
|
124 |
-
if prompt := st.chat_input("اپنی علامات یہاں درج کریں..."):
|
125 |
-
st.session_state.messages.append({"role": "user", "content": prompt})
|
126 |
-
with st.chat_message("user"):
|
127 |
-
st.markdown(prompt)
|
128 |
-
|
129 |
-
with st.chat_message("assistant"):
|
130 |
-
with st.spinner("تجویز تیار کی جا رہی ہے..."):
|
131 |
-
full_response = homeo_chatbot_urdu(prompt)
|
132 |
-
st.markdown(full_response)
|
133 |
-
st.session_state.messages.append({"role": "assistant", "content": full_response})
|
134 |
-
|
135 |
-
# Disclaimer
|
136 |
-
st.markdown("""
|
137 |
-
---
|
138 |
-
**⚠️ نوٹس:**
|
139 |
-
یہ طبی مشورہ نہیں ہے۔ ہمیشہ کوالیفائیڈ ڈاکٹر سے رجوع کریں۔
|
140 |
-
This is not medical advice. Always consult a qualified practitioner.
|
141 |
-
""")# app.py
|
142 |
-
import streamlit as st
|
143 |
-
from groq import Groq
|
144 |
-
import os
|
145 |
-
import requests
|
146 |
-
from bs4 import BeautifulSoup
|
147 |
-
import re
|
148 |
-
from urllib.parse import quote_plus
|
149 |
-
|
150 |
-
# Groq API setup
|
151 |
-
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
|
152 |
-
|
153 |
-
# Web scraping functions
|
154 |
-
def google_search(query):
|
155 |
-
headers = {
|
156 |
-
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
|
157 |
-
}
|
158 |
-
encoded_query = quote_plus(query)
|
159 |
-
url = f"https://www.google.com/search?q={encoded_query}&gl=us&hl=en"
|
160 |
-
|
161 |
-
try:
|
162 |
-
response = requests.get(url, headers=headers)
|
163 |
-
soup = BeautifulSoup(response.text, 'html.parser')
|
164 |
-
results = []
|
165 |
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
st.error(f"سرچ ایرر: {str(e)}")
|
179 |
-
return []
|
180 |
-
|
181 |
-
# Homeopathic dosage extraction (Urdu supported)
|
182 |
-
def extract_dosage_info(text):
|
183 |
-
patterns = [
|
184 |
-
r'(\d+[\s-]*\d*\s*(بار|قطرے|گولیاں|خوارج)\s*(فی دن|روزانہ))',
|
185 |
-
r'(دن میں \d+\s*بار)',
|
186 |
-
r'(\d+-\d+\s*گھنٹے کے وقفے سے)'
|
187 |
-
]
|
188 |
-
|
189 |
-
for pattern in patterns:
|
190 |
-
match = re.search(pattern, text)
|
191 |
-
if match:
|
192 |
-
return match.group()
|
193 |
-
return "دن میں 3 بار (ڈیفالٹ)"
|
194 |
-
|
195 |
-
# Chatbot logic
|
196 |
-
def homeo_chatbot_urdu(user_input):
|
197 |
-
# Step 1: Symptom extraction in Urdu
|
198 |
-
symptom_prompt = f"""صارف کی تفصیل: {user_input}
|
199 |
-
ہومیوپیتھک علامات کو انگلش میں کاما سے علیحدہ فہرست میں نکالیں۔
|
200 |
-
مثال: headache, dry cough, fever with chills"""
|
201 |
-
|
202 |
-
try:
|
203 |
-
symptom_response = client.chat.completions.create(
|
204 |
-
messages=[{"role": "user", "content": symptom_prompt}],
|
205 |
model="llama3-70b-8192",
|
206 |
-
temperature=0.
|
207 |
)
|
208 |
-
|
|
|
|
|
209 |
except Exception as e:
|
210 |
-
return f"
|
211 |
-
|
212 |
-
# Step 2: Web search for remedies
|
213 |
-
search_query = f"homeopathic remedies for {' '.join(symptoms)} site:.edu OR site:.gov"
|
214 |
-
search_results = google_search(search_query)
|
215 |
-
|
216 |
-
remedies = []
|
217 |
-
for result in search_results:
|
218 |
-
remedies.append({
|
219 |
-
'title': result['title'],
|
220 |
-
'link': result['link'],
|
221 |
-
'content': result['snippet']
|
222 |
-
})
|
223 |
-
|
224 |
-
# Step 3: Prepare response in Urdu
|
225 |
-
final_response = "🌿 **تجویز کردہ ہومیوپیتھک علاج:**\n\n"
|
226 |
-
for idx, remedy in enumerate(remedies, 1):
|
227 |
-
dosage = extract_dosage_info(remedy['content'])
|
228 |
-
final_response += f"""\
|
229 |
-
**آپشن {idx}:**
|
230 |
-
- **دوا:** {remedy['content'].split(' ')[0]}
|
231 |
-
- **علامات:** {', '.join(symptoms[:3])}
|
232 |
-
- **خوارک:** {dosage}
|
233 |
-
- **طریقہ استعمال:** {"5 قطرے پانی میں" if 'قطرے' in dosage else "2 گولیاں"}
|
234 |
-
- **دورانیہ:** {"3 دن" if 'حاد' in user_input else "1 ہفتہ"}
|
235 |
-
- **ماخذ:** [{remedy['title']}]({remedy['link']})
|
236 |
-
|
237 |
-
"""
|
238 |
-
|
239 |
-
return final_response
|
240 |
-
|
241 |
-
# Streamlit UI in Urdu
|
242 |
-
st.set_page_config(page_title="ہومیوپیتھک ڈاکٹر", page_icon="🌿")
|
243 |
|
244 |
-
#
|
245 |
-
st.
|
246 |
-
st.
|
247 |
-
<style>
|
248 |
-
[data-testid="stMarkdownContainer"] ul {
|
249 |
-
padding-right: 40px;
|
250 |
-
}
|
251 |
-
</style>
|
252 |
-
""", unsafe_allow_html=True)
|
253 |
|
254 |
-
#
|
255 |
if "messages" not in st.session_state:
|
256 |
-
st.session_state.messages = [
|
257 |
-
{"role": "assistant", "content": "السلام علیکم! آپ کی کیا علامات ہیں؟ مثالوں:\n- سر درد اور چکر آنا\n- کھانسی کے ساتھ بخار\n- پیٹ درد اور بھوک نہ لگنا"}
|
258 |
-
]
|
259 |
|
|
|
260 |
for message in st.session_state.messages:
|
261 |
with st.chat_message(message["role"]):
|
262 |
st.markdown(message["content"])
|
263 |
|
264 |
-
|
|
|
265 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
266 |
-
|
267 |
-
st.markdown(prompt)
|
268 |
-
|
269 |
with st.chat_message("assistant"):
|
270 |
-
with st.spinner("
|
271 |
-
|
272 |
-
st.markdown(
|
273 |
-
st.session_state.messages.append({"role": "assistant", "content":
|
274 |
|
275 |
# Disclaimer
|
276 |
st.markdown("""
|
277 |
---
|
278 |
-
**⚠️
|
279 |
-
یہ طبی مشورہ نہیں ہے۔ ہمیشہ کوالیفائیڈ ڈاکٹر سے رجوع کریں۔
|
280 |
This is not medical advice. Always consult a qualified practitioner.
|
281 |
""")
|
|
|
6 |
from bs4 import BeautifulSoup
|
7 |
import re
|
8 |
from urllib.parse import quote_plus
|
9 |
+
from langdetect import detect
|
10 |
|
11 |
# Groq API setup
|
12 |
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
|
|
|
34 |
'link': link,
|
35 |
'snippet': snippet.text
|
36 |
})
|
37 |
+
return results[:3]
|
38 |
except Exception as e:
|
39 |
+
st.error(f"Search Error: {str(e)}")
|
40 |
return []
|
41 |
|
42 |
+
# Chatbot processing
|
43 |
+
def multilingual_chatbot(user_input):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
try:
|
45 |
+
# Detect input language
|
46 |
+
lang = detect(user_input)
|
47 |
+
|
48 |
+
# Step 1: Symptom extraction (English for searching)
|
49 |
+
symptom_prompt = f"""Extract medical symptoms from this text in English comma-separated format:
|
50 |
+
{user_input}
|
51 |
+
Example Output: headache, dry cough, fever"""
|
52 |
+
|
53 |
symptom_response = client.chat.completions.create(
|
54 |
messages=[{"role": "user", "content": symptom_prompt}],
|
55 |
model="llama3-70b-8192",
|
56 |
temperature=0.2
|
57 |
)
|
58 |
symptoms = symptom_response.choices[0].message.content.split(", ")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
|
60 |
+
# Step 2: Web search
|
61 |
+
search_query = f"homeopathic remedies for {' '.join(symptoms)} site:.edu OR site:.gov"
|
62 |
+
results = google_search(search_query)
|
63 |
+
|
64 |
+
# Step 3: Generate multilingual response
|
65 |
+
response_prompt = f"""Translate this medical advice to {lang} while keeping medicine names in English:
|
66 |
+
Suggested remedies for {', '.join(symptoms)}:
|
67 |
+
{[r['snippet'] for r in results]}
|
68 |
+
Include dosage instructions and administration method."""
|
69 |
+
|
70 |
+
final_response = client.chat.completions.create(
|
71 |
+
messages=[{"role": "user", "content": response_prompt}],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
model="llama3-70b-8192",
|
73 |
+
temperature=0.3
|
74 |
)
|
75 |
+
|
76 |
+
return final_response.choices[0].message.content
|
77 |
+
|
78 |
except Exception as e:
|
79 |
+
return f"Error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
|
81 |
+
# Streamlit UI
|
82 |
+
st.set_page_config(page_title="Homeo Assistant", page_icon="🌿")
|
83 |
+
st.title("🌐 Multilingual Homeopathy Advisor")
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
|
85 |
+
# Initialize chat history
|
86 |
if "messages" not in st.session_state:
|
87 |
+
st.session_state.messages = [{"role": "assistant", "content": "Describe your symptoms in any language"}]
|
|
|
|
|
88 |
|
89 |
+
# Display chat messages
|
90 |
for message in st.session_state.messages:
|
91 |
with st.chat_message(message["role"]):
|
92 |
st.markdown(message["content"])
|
93 |
|
94 |
+
# Chat input
|
95 |
+
if prompt := st.chat_input("Type your symptoms..."):
|
96 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
97 |
+
|
|
|
|
|
98 |
with st.chat_message("assistant"):
|
99 |
+
with st.spinner("Analyzing symptoms..."):
|
100 |
+
response = multilingual_chatbot(prompt)
|
101 |
+
st.markdown(response)
|
102 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
103 |
|
104 |
# Disclaimer
|
105 |
st.markdown("""
|
106 |
---
|
107 |
+
**⚠️ Disclaimer:**
|
|
|
108 |
This is not medical advice. Always consult a qualified practitioner.
|
109 |
""")
|