aminahmed78 commited on
Commit
2bfa4a7
·
verified ·
1 Parent(s): b5ce2d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -70
app.py CHANGED
@@ -1,121 +1,113 @@
1
  import streamlit as st
2
  import os
3
- from transformers import pipeline
4
- from langdetect import detect, DetectorFactory
5
  from groq import Groq
 
 
6
 
7
  # Ensure consistent language detection
8
  DetectorFactory.seed = 0
9
 
10
- # Load Hugging Face token from environment
11
- HF_TOKEN = os.environ.get("homeo_doc")
12
- if not HF_TOKEN:
13
- st.error("❌ Missing Hugging Face API token. Set 'homeo_doc' in environment variables.")
14
-
15
- # Initialize translation pipeline
16
- try:
17
- translator = pipeline("translation", model="facebook/nllb-200-distilled-600M", token=HF_TOKEN)
18
- except Exception as e:
19
- st.error(f"❌ Error initializing translation model: {e}")
20
-
21
- # Initialize Groq client for AI-based homeopathic advice
22
  GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
23
  if not GROQ_API_KEY:
24
  st.error("❌ Missing GROQ API Key. Set 'GROQ_API_KEY' in environment variables.")
25
 
 
26
  groq_client = Groq(api_key=GROQ_API_KEY)
27
 
28
- # Language code mapping for NLLB-200
29
- LANG_CODE_MAP = {
30
- 'en': 'eng_Latn', # English
31
- 'ur': 'urd_Arab', # Urdu
32
- 'ar': 'arb_Arab', # Arabic
33
- 'es': 'spa_Latn', # Spanish
34
- 'hi': 'hin_Deva', # Hindi
35
- 'fr': 'fra_Latn' # French
36
- }
37
-
38
- def translate_text(text, target_lang='eng_Latn'):
39
- """Translate text using NLLB-200 model."""
40
  try:
41
- source_lang = detect(text)
42
- source_code = LANG_CODE_MAP.get(source_lang, 'eng_Latn') # Default to English if unknown
43
-
44
- st.write(f"🔄 Detected source: {source_code}, Target: {target_lang}") # Debugging log
45
 
46
- translation = translator(
47
- text,
48
- src_lang=source_code, # Pass source language
49
- tgt_lang=target_lang # Pass target language
 
 
 
 
 
 
50
  )
51
-
52
- return translation[0]['translation_text']
53
-
54
  except Exception as e:
55
- st.error(f"⚠️ Translation error: {str(e)}")
56
- return text # Return original text if translation fails
57
 
58
- def get_homeopathic_advice(symptoms):
59
- """Get medical advice using Groq AI API."""
60
  try:
61
  response = groq_client.chat.completions.create(
62
  model="llama3-70b-8192",
63
- messages=[{
64
- "role": "user",
65
- "content": f"Act as a homeopathic expert. Suggest remedies for: {symptoms}"
66
- }],
67
- temperature=0.3
68
  )
69
  return response.choices[0].message.content
70
  except Exception as e:
71
- return f" Error fetching homeopathic advice: {str(e)}"
72
 
73
  # 🎨 Streamlit UI
74
- st.set_page_config(page_title="Homeo Advisor", page_icon="🌿")
75
- st.title("🌍 Multilingual Homeopathic Advisor")
76
 
77
- # Chat interface (Persistent session)
78
  if "messages" not in st.session_state:
79
  st.session_state.messages = []
80
 
81
- # Display previous 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 box
87
- if prompt := st.chat_input("Describe symptoms in any language..."):
88
  st.session_state.messages.append({"role": "user", "content": prompt})
89
 
90
- with st.spinner("🔍 Analyzing..."):
91
- # Translate user input to English
92
- english_input = translate_text(prompt, "eng_Latn")
93
 
94
- # Get homeopathic advice in English
95
- english_advice = get_homeopathic_advice(english_input)
96
 
97
- # Detect original language
98
- source_lang = detect(prompt)
99
- source_code = LANG_CODE_MAP.get(source_lang, 'eng_Latn')
 
 
100
 
101
- # Translate advice back to original language
102
- translated_advice = translate_text(english_advice, source_code)
103
-
104
- # Format response
105
  final_response = f"""
106
- **💡 English Recommendation:**
107
- {english_advice}
108
 
109
- **🌍 Translated Recommendation ({source_lang.upper()}):**
110
  {translated_advice}
111
  """
112
 
113
  # Display response
114
  with st.chat_message("assistant"):
115
  st.markdown(final_response)
116
-
117
- # Save response in session history
118
  st.session_state.messages.append({"role": "assistant", "content": final_response})
119
 
120
  # Disclaimer
121
- st.caption("⚠️ This is not medical advice. Consult a professional.")
 
1
  import streamlit as st
2
  import os
 
 
3
  from groq import Groq
4
+ from langdetect import detect, DetectorFactory
5
+ import json
6
 
7
  # Ensure consistent language detection
8
  DetectorFactory.seed = 0
9
 
10
+ # Load API key from environment
 
 
 
 
 
 
 
 
 
 
 
11
  GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
12
  if not GROQ_API_KEY:
13
  st.error("❌ Missing GROQ API Key. Set 'GROQ_API_KEY' in environment variables.")
14
 
15
+ # Initialize Groq client
16
  groq_client = Groq(api_key=GROQ_API_KEY)
17
 
18
+ # Define chatbot role as a specialized homeopathic doctor
19
+ CHATBOT_ROLE = """You are a highly skilled homeopathic doctor specializing in natural remedies.
20
+ You analyze symptoms provided by users and suggest effective homeopathic treatments based on research-backed sources.
21
+ Your response must include:
22
+ - Best possible remedy
23
+ - Proper dosage and administration
24
+ - Scientific or historical sources for reference
25
+ - Store/availability of the medicine
26
+ Ensure accuracy in medical details and maintain professionalism."""
27
+
28
+ def detect_language(text):
29
+ """Detect the language of the input text."""
30
  try:
31
+ lang = detect(text)
32
+ return lang
33
+ except:
34
+ return "en" # Default to English if detection fails
35
 
36
+ def get_homeopathic_advice(symptoms, lang="en"):
37
+ """Search the web for remedies and generate a professional homeopathic response."""
38
+ try:
39
+ response = groq_client.chat.completions.create(
40
+ model="llama3-70b-8192",
41
+ messages=[
42
+ {"role": "system", "content": CHATBOT_ROLE},
43
+ {"role": "user", "content": f"Find the best homeopathic remedy for: {symptoms}. Provide remedy details, usage, dose, sources, and availability."}
44
+ ],
45
+ temperature=0.3
46
  )
47
+ return response.choices[0].message.content
 
 
48
  except Exception as e:
49
+ return f" Error fetching homeopathic advice: {str(e)}"
 
50
 
51
+ def translate_text(text, target_lang):
52
+ """Translate text using Groq's LLaMA model."""
53
  try:
54
  response = groq_client.chat.completions.create(
55
  model="llama3-70b-8192",
56
+ messages=[
57
+ {"role": "system", "content": "You are a multilingual AI that accurately translates medical advice while preserving technical accuracy."},
58
+ {"role": "user", "content": f"Translate this medical advice into {target_lang}: {text}"}
59
+ ],
60
+ temperature=0.2
61
  )
62
  return response.choices[0].message.content
63
  except Exception as e:
64
+ return f"⚠️ Translation error: {str(e)}"
65
 
66
  # 🎨 Streamlit UI
67
+ st.set_page_config(page_title="Homeo Doctor AI", page_icon="🌿")
68
+ st.title("🌍 AI-Powered Homeopathic Doctor")
69
 
70
+ # Chat interface
71
  if "messages" not in st.session_state:
72
  st.session_state.messages = []
73
 
74
+ # Display chat history
75
  for message in st.session_state.messages:
76
  with st.chat_message(message["role"]):
77
  st.markdown(message["content"])
78
 
79
  # User input box
80
+ if prompt := st.chat_input("Describe your symptoms..."):
81
  st.session_state.messages.append({"role": "user", "content": prompt})
82
 
83
+ with st.spinner("🔍 Analyzing symptoms..."):
84
+ # Detect user language
85
+ detected_lang = detect_language(prompt)
86
 
87
+ # Get homeopathic remedy
88
+ homeo_advice = get_homeopathic_advice(prompt, detected_lang)
89
 
90
+ # Translate advice if needed
91
+ if detected_lang != "en":
92
+ translated_advice = translate_text(homeo_advice, detected_lang)
93
+ else:
94
+ translated_advice = homeo_advice
95
 
96
+ # Format final response
 
 
 
97
  final_response = f"""
98
+ **💡 Expert Homeopathic Advice (English):**
99
+ {homeo_advice}
100
 
101
+ **🌍 Translated Advice ({detected_lang.upper()}):**
102
  {translated_advice}
103
  """
104
 
105
  # Display response
106
  with st.chat_message("assistant"):
107
  st.markdown(final_response)
108
+
109
+ # Save chat history
110
  st.session_state.messages.append({"role": "assistant", "content": final_response})
111
 
112
  # Disclaimer
113
+ st.caption("⚠️ This AI does not replace professional medical consultation.")