aminahmed78 commited on
Commit
2d81770
·
verified ·
1 Parent(s): 8ffe65a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -39
app.py CHANGED
@@ -1,53 +1,97 @@
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}],
46
- model="llama3-70b-8192",
47
- temperature=0.3
48
- )
49
-
50
- return final_response.choices[0].message.content
51
 
52
  except Exception as e:
53
- return f"Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from langdetect import detect
8
+ from urllib.parse import quote_plus
9
+
10
+ # Initialize Groq client
11
+ try:
12
+ client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
13
+ except Exception as e:
14
+ st.error(f"Groq initialization failed: {str(e)}")
15
+
16
+ # Web scraping with error handling
17
+ def google_search(query):
18
  try:
19
+ headers = {"User-Agent": "Mozilla/5.0"}
20
+ encoded_query = quote_plus(query)
21
+ url = f"https://www.google.com/search?q={encoded_query}&gl=us&hl=en"
22
+ response = requests.get(url, headers=headers)
23
+ response.raise_for_status()
24
+
25
+ soup = BeautifulSoup(response.text, 'html.parser')
26
+ return [
27
+ {
28
+ 'title': result.find('h3').text,
29
+ 'link': result.find('a')['href'],
30
+ 'snippet': result.find('div', class_='VwiC3b').text
31
+ }
32
+ for result in soup.find_all('div', class_='tF2Cxc')[:3]
33
+ ]
34
+ except Exception as e:
35
+ st.error(f"Google search failed: {str(e)}")
36
+ return []
37
+
38
+ # Main chatbot function
39
+ def get_homeopathic_advice(user_input):
40
+ try:
41
+ # Language detection
42
  lang = detect(user_input)
43
 
44
+ # Step 1: Symptom extraction
45
+ symptom_prompt = f"""Extract homeopathic symptoms from this text as comma-separated list:
46
  {user_input}
47
+ Example: headache, dry cough, anxiety"""
48
 
49
+ symptoms = client.chat.completions.create(
50
  messages=[{"role": "user", "content": symptom_prompt}],
51
+ model="llama3-70b-8192"
52
+ ).choices[0].message.content.split(", ")
 
 
53
 
54
+ # Step 2: Homeopathic-specific search
55
+ search_results = google_search(
56
  f"homeopathic remedy for {' '.join(symptoms)} "
57
+ f"site:.edu OR site:.gov -allopathic"
 
58
  )
 
59
 
60
+ # Step 3: Generate response
61
+ response_prompt = f"""You're a homeopathic expert. Suggest remedies in {lang} for: {', '.join(symptoms)}
62
+ Use only this data: {[r['snippet'] for r in search_results]}
63
+ Include medicine name (English), potency, dosage and source."""
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
+ return client.chat.completions.create(
66
  messages=[{"role": "user", "content": response_prompt}],
67
+ model="llama3-70b-8192"
68
+ ).choices[0].message.content
 
 
 
69
 
70
  except Exception as e:
71
+ return f"Error: {str(e)}"
72
+
73
+ # Streamlit UI Setup
74
+ st.set_page_config(page_title="Homeo Advisor", page_icon="🌿")
75
+ st.title("🌿 Homeopathic Chat Advisor")
76
+
77
+ # Initialize chat history
78
+ if "messages" not in st.session_state:
79
+ st.session_state.messages = [{"role": "assistant", "content": "Describe your symptoms in any language"}]
80
+
81
+ # Display chat messages
82
+ for message in st.session_state.messages:
83
+ with st.chat_message(message["role"]):
84
+ st.markdown(message["content"])
85
+
86
+ # User input handling
87
+ if prompt := st.chat_input("Enter symptoms..."):
88
+ st.session_state.messages.append({"role": "user", "content": prompt})
89
+
90
+ with st.chat_message("assistant"):
91
+ with st.spinner("Analyzing..."):
92
+ response = get_homeopathic_advice(prompt)
93
+ st.markdown(response)
94
+ st.session_state.messages.append({"role": "assistant", "content": response})
95
+
96
+ # Disclaimer
97
+ st.caption("⚠️ This is not medical advice. Consult a professional.")