aminahmed78 commited on
Commit
f0144dd
·
verified ·
1 Parent(s): 0c03116

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -125
app.py CHANGED
@@ -1,151 +1,141 @@
 
1
  import streamlit as st
2
- import pandas as pd
3
  from groq import Groq
4
  import os
 
 
 
 
5
 
6
- # --------------------------
7
- # 1. Dataset Setup (Updated with Urdu)
8
- # --------------------------
9
- data = {
10
- "symptoms_en": ["headache", "fever", "insomnia", "anxiety", "cough"],
11
- "symptoms_es": ["dolor de cabeza", "fiebre", "insomnio", "ansiedad", "tos"],
12
- "symptoms_hi": ["सिरदर्द", "बुखार", "अनिद्रा", "चिंता", "खांसी"],
13
- "symptoms_ur": ["سر درد", "بخار", "بے خوابی", "اضطراب", "کھانسی"],
14
- "remedy": ["Belladonna", "Aconitum", "Coffea", "Argentum nitricum", "Drosera"],
15
- "potency": ["30C"]*5,
16
- "usage": ["3 times daily"]*5
17
- }
18
-
19
- df = pd.DataFrame(data)
20
-
21
- # --------------------------
22
- # 2. Groq Setup (Multilingual Processing)
23
- # --------------------------
24
  client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
25
 
26
- def analyze_symptoms(text, language):
27
- """Use Groq's Llama 3 for symptom analysis"""
28
- lang_map = {
29
- 'en': 'English',
30
- 'es': 'Spanish',
31
- 'hi': 'Hindi',
32
- 'ur': 'Urdu'
33
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- prompt = f"""Task: Extract medical symptoms from this {lang_map[language]} text.
36
- Text: {text}
37
- Output format: Comma-separated symptoms in {lang_map[language]}.
38
- Example: headache, muscle pain, dry cough"""
 
 
 
 
 
 
 
 
39
 
40
  try:
41
- chat_completion = client.chat.completions.create(
42
- messages=[{"role": "user", "content": prompt}],
43
  model="llama3-70b-8192",
44
- temperature=0.1
45
  )
46
- return [s.strip() for s in chat_completion.choices[0].message.content.split(",")]
47
  except Exception as e:
48
- st.error(f"Error in Groq API: {str(e)}")
49
- return []
 
 
 
 
 
 
 
 
 
 
 
50
 
51
- # --------------------------
52
- # 3. Streamlit UI (Multilingual Interface)
53
- # --------------------------
54
- st.set_page_config(page_title="Homeo Doctor", page_icon="🌿")
 
 
 
 
 
 
 
 
55
 
56
- # Language selection
57
- language = st.sidebar.selectbox("भाषा चुनें/Select Language",
58
- ['English', 'Español', 'हिन्दी', 'اردو'],
59
- format_func=lambda x: x)
60
 
61
- lang_code = {
62
- 'English': 'en',
63
- 'Español': 'es',
64
- 'हिन्दी': 'hi',
65
- 'اردو': 'ur'
66
- }[language]
67
 
68
- # Header with dynamic language
69
- headers = {
70
- 'en': "🌿 Homeopathic Doctor",
71
- 'es': "🌿 Doctor Homeopático",
72
- 'hi': "🌿 होम्योपैथिक डॉक्टर",
73
- 'ur': "🌿 ہومیوپیتھک ڈاکٹر"
74
  }
75
- st.header(headers[lang_code])
 
76
 
77
- # MCQ Symptoms
78
- symptom_col = f"symptoms_{lang_code}"
79
- symptoms = df[symptom_col].tolist()
80
- selected = st.multiselect(
81
- label={
82
- 'en': "Select your symptoms:",
83
- 'es': "Seleccione sus síntomas:",
84
- 'hi': "अपने लक्षण चुनें:",
85
- 'ur': "اپنی علامات منتخب کریں:"
86
- }[lang_code],
87
- options=symptoms
88
- )
89
 
90
- # Chat Input
91
- chat_input = st.text_input(
92
- label={
93
- 'en': "Describe other symptoms:",
94
- 'es': "Describa otros síntomas:",
95
- 'hi': "अन्य लक्षण बताएं:",
96
- 'ur': "دیگر علامات بیان کریں:"
97
- }[lang_code],
98
- placeholder={
99
- 'en': "Type symptoms not listed above...",
100
- 'ur': "اوپر درج نہ کی گئی علامات ٹائپ کریں..."
101
- }[lang_code] if lang_code == 'ur' else ""
102
- )
103
 
104
- # Diagnosis Logic
105
- if st.button({
106
- 'en': "Get Recommendation",
107
- 'es': "Obtener Recomendación",
108
- 'hi': "सिफारिश प्राप्त करें",
109
- 'ur': "تجویز حاصل کریں"
110
- }[lang_code]):
111
- # Process chat input
112
- if chat_input:
113
- analyzed_symptoms = analyze_symptoms(chat_input, lang_code)
114
- selected += [s for s in analyzed_symptoms if s in symptoms]
115
-
116
- # Find best remedy
117
- if not selected:
118
- st.warning({
119
- 'en': "Please select or describe symptoms!",
120
- 'ur': "براہ کرم علامات منتخب کریں یا بیان کریں!"
121
- }[lang_code] if lang_code == 'ur' else "")
122
- else:
123
- matches = df[df[symptom_col].isin(selected)]
124
- if not matches.empty:
125
- remedy = matches.iloc[0]
126
- st.success(f"""
127
- **{remedy['remedy']}**
128
- {{
129
- 'en': "Potency: {remedy['potency']}",
130
- 'ur': "طاقت: {remedy['potency']}"
131
- }}[lang_code]
132
- {{
133
- 'en': "Usage: {remedy['usage']}",
134
- 'ur': "استعمال: {remedy['usage']}"
135
- }}[lang_code]
136
- """)
137
- else:
138
- st.error({
139
- 'en': "No matching remedy found. Consult a professional.",
140
- 'ur': "کوئی مماثل دوا نہیں ملی۔ پیشہ ور سے مشورہ کریں۔"
141
- }[lang_code])
142
 
143
  # Disclaimer
144
  st.markdown("""
145
  ---
146
- **⚠️ Notice/نوٹس:**
147
- This is not medical advice. Always consult a qualified homeopath.
148
- यह चिकित्सीय सलाह नहीं है। हमेशा योग्य होम्योपैथ से सलाह लें۔
149
- Esto no es un consejo médico. Siempre consulte a un homeópata calificado.
150
- یہ طبی مشورہ نہیں ہے۔ ہمیشہ کوالیفائڈ ہومیوپیتھک ڈاکٹر سے مشورہ کریں۔
151
  """)
 
1
+ # app.py
2
  import streamlit as st
 
3
  from groq import Groq
4
  import os
5
+ 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"))
12
 
13
+ # Web scraping functions
14
+ def google_search(query):
15
+ headers = {
16
+ "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"
 
 
 
17
  }
18
+ encoded_query = quote_plus(query)
19
+ url = f"https://www.google.com/search?q={encoded_query}&gl=us&hl=en"
20
+
21
+ try:
22
+ response = requests.get(url, headers=headers)
23
+ soup = BeautifulSoup(response.text, 'html.parser')
24
+ results = []
25
+
26
+ for g in soup.find_all('div', class_='tF2Cxc'):
27
+ link = g.find('a')['href']
28
+ title = g.find('h3').text
29
+ snippet = g.find('div', class_='VwiC3b')
30
+ if snippet:
31
+ results.append({
32
+ 'title': title,
33
+ 'link': link,
34
+ 'snippet': snippet.text
35
+ })
36
+ return results[:3] # Return top 3 results
37
+ except Exception as e:
38
+ st.error(f"سرچ ایرر: {str(e)}")
39
+ return []
40
+
41
+ # Homeopathic dosage extraction (Urdu supported)
42
+ def extract_dosage_info(text):
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
  """)