aminahmed78 commited on
Commit
2ccd913
·
verified ·
1 Parent(s): 256d4fe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -84
app.py CHANGED
@@ -1,71 +1,45 @@
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
- from langdetect import detect
10
-
11
- # Groq API setup
12
- client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
13
-
14
- # Web scraping functions
15
- def google_search(query):
16
- headers = {
17
- "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"
18
- }
19
- encoded_query = quote_plus(query)
20
- url = f"https://www.google.com/search?q={encoded_query}&gl=us&hl=en"
21
-
22
- try:
23
- response = requests.get(url, headers=headers)
24
- soup = BeautifulSoup(response.text, 'html.parser')
25
- results = []
26
-
27
- for g in soup.find_all('div', class_='tF2Cxc'):
28
- link = g.find('a')['href']
29
- title = g.find('h3').text
30
- snippet = g.find('div', class_='VwiC3b')
31
- if snippet:
32
- results.append({
33
- 'title': title,
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}],
@@ -76,34 +50,4 @@ def multilingual_chatbot(user_input):
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
- """)
 
1
+ # app.py (Updated Version)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  def multilingual_chatbot(user_input):
3
  try:
4
  # Detect input language
5
  lang = detect(user_input)
6
 
7
+ # Step 1: Symptom extraction with homeopathy focus
8
+ symptom_prompt = f"""Extract ONLY homeopathic-relevant symptoms from this text as English comma-separated list:
9
  {user_input}
10
+ Example Output: stinging pain, anxiety worse evenings, thirstlessness"""
11
 
12
  symptom_response = client.chat.completions.create(
13
  messages=[{"role": "user", "content": symptom_prompt}],
14
  model="llama3-70b-8192",
15
+ temperature=0.1
16
  )
17
  symptoms = symptom_response.choices[0].message.content.split(", ")
18
 
19
+ # Step 2: Focused homeopathic web search
20
+ search_query = (
21
+ f"homeopathic remedy for {' '.join(symptoms)} "
22
+ f"(site:.edu OR site:.gov) "
23
+ f"-allopathic -conventional -pharmaceutical"
24
+ )
25
  results = google_search(search_query)
26
 
27
+ # Filter homeopathic-specific results
28
+ homeo_keywords = ['homeopath', 'remedy', 'potency', 'materia medica']
29
+ filtered_results = [
30
+ r for r in results
31
+ if any(kw in r['snippet'].lower() for kw in homeo_keywords)
32
+ ]
33
+
34
+ # Step 3: Generate strict homeopathic response
35
+ response_prompt = f"""You are a homeopathic doctor. Recommend ONLY homeopathic medicines in {lang} for these symptoms: {', '.join(symptoms)}.
36
+ Use this research data: {[r['snippet'] for r in filtered_results]}
37
+ Include:
38
+ - Medicine name in English
39
+ - Potency (like 30C, 200CK)
40
+ - Administration method
41
+ - Key symptoms it addresses
42
+ - Source reference"""
43
 
44
  final_response = client.chat.completions.create(
45
  messages=[{"role": "user", "content": response_prompt}],
 
50
  return final_response.choices[0].message.content
51
 
52
  except Exception as e:
53
+ return f"Error: {str(e)}"