aminahmed78 commited on
Commit
3fdc359
·
verified ·
1 Parent(s): 0392a70

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +140 -0
app.py CHANGED
@@ -111,6 +111,146 @@ st.markdown("""
111
  </style>
112
  """, unsafe_allow_html=True)
113
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  # Chat history
115
  if "messages" not in st.session_state:
116
  st.session_state.messages = [
 
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
+ for g in soup.find_all('div', class_='tF2Cxc'):
167
+ link = g.find('a')['href']
168
+ title = g.find('h3').text
169
+ snippet = g.find('div', class_='VwiC3b')
170
+ if snippet:
171
+ results.append({
172
+ 'title': title,
173
+ 'link': link,
174
+ 'snippet': snippet.text
175
+ })
176
+ return results[:3] # Return top 3 results
177
+ except Exception as e:
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.2
207
+ )
208
+ symptoms = symptom_response.choices[0].message.content.split(", ")
209
+ except Exception as e:
210
+ return f"ایرر: {str(e)}"
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
+ # Urdu interface
245
+ st.title("🌐 لائیو ہومیوپیتھک مشیر")
246
+ st.markdown("""
247
+ <style>
248
+ [data-testid="stMarkdownContainer"] ul {
249
+ padding-right: 40px;
250
+ }
251
+ </style>
252
+ """, unsafe_allow_html=True)
253
+
254
  # Chat history
255
  if "messages" not in st.session_state:
256
  st.session_state.messages = [