Kamaljeyaram07 commited on
Commit
b6ad76c
·
verified ·
1 Parent(s): 2891ff4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -12
app.py CHANGED
@@ -3,20 +3,21 @@ import os
3
  import re
4
  from groq import Groq
5
  from tavily import TavilyClient
6
- # Import your custom logic
7
  from language import detect_language, translate_text
8
 
9
  # 1. Clients
10
  groq_client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
11
  tavily_client = TavilyClient(api_key=os.environ.get("TAVILY_API_KEY"))
12
 
13
- # 2. Medical Prompt
14
  SYSTEM_PROMPT = """
15
  You are a Medical Information Specialist.
16
  - Use the context to explain health concepts simply.
17
  - STICK TO NON-DRUG ADVICE (Rest, hydration, hygiene).
18
  - NO MEDICATIONS, NO DOSAGES, NO BRAND NAMES.
19
  - Always include a section on 'When to see a doctor'.
 
20
  """
21
 
22
  def medical_chat(message, history):
@@ -24,18 +25,34 @@ def medical_chat(message, history):
24
  # A. Language Detection
25
  user_lang = detect_language(message)
26
 
27
- # B. Translation to English for the best search results
 
 
 
 
 
 
 
28
  eng_query = translate_text(message, "en") if user_lang != "en" else message
29
 
30
- # C. Search Trusted Official Sources
31
- search = tavily_client.search(
32
  query=f"medical guidance for {eng_query}",
33
  include_domains=["who.int", "mohfw.gov.in", "mayoclinic.org", "nhs.uk"],
34
  max_results=3
35
  )
36
- context = "\n".join([f"Source: {r['content']}" for r in search['results']])
 
 
 
 
 
 
 
 
 
37
 
38
- # D. Groq Reasoning (English)
39
  response = groq_client.chat.completions.create(
40
  model="llama-3.3-70b-versatile",
41
  messages=[
@@ -45,14 +62,15 @@ def medical_chat(message, history):
45
  )
46
  eng_response = response.choices[0].message.content
47
 
48
- # E. Final Translation back to User's Language
49
  final_output = translate_text(eng_response, user_lang) if user_lang != "en" else eng_response
50
 
51
- # F. Safety Check
52
  if re.search(r'\d+\s?(mg|ml|tablet|pill)', final_output.lower()):
53
- return "I cannot provide specific dosages. / मैं खुराक की जानकारी नहीं दे सकता।"
54
 
55
- return final_output
 
56
 
57
  except Exception as e:
58
  return f"⚠️ Error: {str(e)}"
@@ -60,7 +78,12 @@ def medical_chat(message, history):
60
  # 3. Launch UI (Gradio 6.0 compatible)
61
  with gr.Blocks() as demo:
62
  gr.Markdown("# ⚡ Official Indic-Medical AI")
63
- gr.ChatInterface(fn=medical_chat)
 
 
 
 
 
64
 
65
  if __name__ == "__main__":
66
  demo.launch(ssr_mode=False, theme="soft")
 
3
  import re
4
  from groq import Groq
5
  from tavily import TavilyClient
6
+ # Import your custom logic from language.py
7
  from language import detect_language, translate_text
8
 
9
  # 1. Clients
10
  groq_client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
11
  tavily_client = TavilyClient(api_key=os.environ.get("TAVILY_API_KEY"))
12
 
13
+ # 2. Optimized Medical Prompt
14
  SYSTEM_PROMPT = """
15
  You are a Medical Information Specialist.
16
  - Use the context to explain health concepts simply.
17
  - STICK TO NON-DRUG ADVICE (Rest, hydration, hygiene).
18
  - NO MEDICATIONS, NO DOSAGES, NO BRAND NAMES.
19
  - Always include a section on 'When to see a doctor'.
20
+ - If the user just says hi/hello, respond with a friendly medical greeting and ask how you can help with their health queries.
21
  """
22
 
23
  def medical_chat(message, history):
 
25
  # A. Language Detection
26
  user_lang = detect_language(message)
27
 
28
+ # B. Handle Small Talk / Greetings
29
+ # If message is very short, don't waste search credits
30
+ small_talk_patterns = r"^(hi|hello|hey|namaste|vanakkam|hi there|hello there)[!?.]?$"
31
+ if re.match(small_talk_patterns, message.strip().lower()):
32
+ greeting = "Hello! I am your Indic-Medical Assistant. How can I help you with your health or medical questions today?"
33
+ return translate_text(greeting, user_lang) if user_lang != "en" else greeting
34
+
35
+ # C. Translation to English for the best search results
36
  eng_query = translate_text(message, "en") if user_lang != "en" else message
37
 
38
+ # D. Search Trusted Official Sources
39
+ search_result = tavily_client.search(
40
  query=f"medical guidance for {eng_query}",
41
  include_domains=["who.int", "mohfw.gov.in", "mayoclinic.org", "nhs.uk"],
42
  max_results=3
43
  )
44
+
45
+ # Extract context and build a source list
46
+ context_parts = []
47
+ sources = []
48
+ for i, r in enumerate(search_result['results']):
49
+ context_parts.append(f"Source [{i+1}]: {r['content']}")
50
+ sources.append(f"- [{r.get('title', 'Official Source')}]({r['url']})")
51
+
52
+ context = "\n".join(context_parts)
53
+ source_markdown = "\n\n**Sources / स्रोत:**\n" + "\n".join(sources)
54
 
55
+ # E. Groq Reasoning (English)
56
  response = groq_client.chat.completions.create(
57
  model="llama-3.3-70b-versatile",
58
  messages=[
 
62
  )
63
  eng_response = response.choices[0].message.content
64
 
65
+ # F. Final Translation back to User's Language
66
  final_output = translate_text(eng_response, user_lang) if user_lang != "en" else eng_response
67
 
68
+ # G. Safety Check (Regex for dosages)
69
  if re.search(r'\d+\s?(mg|ml|tablet|pill)', final_output.lower()):
70
+ final_output = "I cannot provide specific dosages. Please consult a doctor. / मैं खुराक की जानकारी नहीं दे सकता। कृपया डॉक्टर से सलाह लें।"
71
 
72
+ # Combine output with sources
73
+ return f"{final_output}\n\n---\n{source_markdown}"
74
 
75
  except Exception as e:
76
  return f"⚠️ Error: {str(e)}"
 
78
  # 3. Launch UI (Gradio 6.0 compatible)
79
  with gr.Blocks() as demo:
80
  gr.Markdown("# ⚡ Official Indic-Medical AI")
81
+ gr.Markdown("Conversational medical guidance in Indian languages with official citations.")
82
+
83
+ gr.ChatInterface(
84
+ fn=medical_chat,
85
+ examples=["बुखार के लक्षण क्या हैं?", "Signs of heart attack", "Explain diabetes in Tamil"],
86
+ )
87
 
88
  if __name__ == "__main__":
89
  demo.launch(ssr_mode=False, theme="soft")