Hasnain-Ali commited on
Commit
0f0392e
·
verified ·
1 Parent(s): c7599f0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -42
app.py CHANGED
@@ -4,10 +4,13 @@ from fpdf import FPDF
4
  import os
5
  from groq import Groq
6
  from deep_translator import GoogleTranslator
 
7
 
8
  # Load API Key
9
  groq_api_key = os.getenv("groq_api_key")
10
  groq_client = Groq(api_key=groq_api_key)
 
 
11
 
12
  # Load Zero-Shot Classification Model
13
  classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
@@ -53,7 +56,6 @@ def translate_text(text, target_lang="en"):
53
  # Function to generate expert analysis
54
  def generate_expert_analysis(condition, symptoms):
55
  specialist_title = specialist_mapping.get(condition, ("General Physician", "General Medicine"))[0]
56
-
57
  prompt = f"""As a {specialist_title.lower()}, explain {condition} to a patient experiencing these symptoms: "{symptoms}".
58
 
59
  Structure the response into:
@@ -64,14 +66,12 @@ def generate_expert_analysis(condition, symptoms):
64
  5. **Diet Plan**
65
  Use professional yet simple language. **No AI disclaimers or generic advice**.
66
  """
67
-
68
  response = groq_client.chat.completions.create(
69
  messages=[{"role": "user", "content": prompt}],
70
  model="mixtral-8x7b-32768",
71
  temperature=0.5,
72
  max_tokens=1024
73
  )
74
-
75
  return response.choices[0].message.content
76
 
77
  # Function to create a medical report
@@ -80,9 +80,7 @@ def create_medical_report(symptoms):
80
  result = classifier(translated_symptoms, conditions, multi_label=False)
81
  diagnosis = result['labels'][0]
82
  specialist, system = specialist_mapping.get(diagnosis, ("General Physician", "General Medicine"))
83
-
84
  expert_analysis = generate_expert_analysis(diagnosis, translated_symptoms)
85
-
86
  full_report = (
87
  f"**Medical Report**\n\n"
88
  f"**Patient Symptoms:** {translated_symptoms}\n"
@@ -96,50 +94,42 @@ def create_medical_report(symptoms):
96
  "3. What lifestyle changes help manage this condition?\n"
97
  "4. What warning signs require immediate attention?\n"
98
  )
99
-
100
  pdf = FPDF()
101
  pdf.add_page()
102
  pdf.set_font("Arial", size=12)
103
  pdf.multi_cell(0, 10, full_report)
104
  pdf_path = "medical_report.pdf"
105
  pdf.output(pdf_path)
106
-
107
  return full_report, pdf_path
108
 
109
- # Gradio UI Setup
110
- def show_section(selected):
111
- return (
112
- gr.update(visible=selected == "Home"),
113
- gr.update(visible=selected == "Diagnosis")
114
- )
115
-
116
- with gr.Blocks() as interface:
117
- with gr.Row():
118
- with gr.Column(scale=1):
119
- gr.Markdown("## 🏥 MedExpert")
120
- gr.Markdown("AI-powered medical diagnosis system.")
121
- nav_buttons = gr.Radio(["Home", "Diagnosis"], value="Home")
122
-
123
- with gr.Column(scale=4):
124
- with gr.Group(visible=True) as home_section:
125
- gr.Markdown("## 🌟 Welcome to MedExpert")
126
- gr.Markdown("### Your Intelligent Health Companion")
127
- gr.Markdown("""
128
- - Symptom Analysis & Diagnosis
129
- - Mental Health Support
130
- - Medical Report Generation
131
- """)
132
-
133
- with gr.Group(visible=False) as diagnostic_section:
134
- gr.Markdown("## 🩺 Symptom Analyzer")
135
- symptoms_input = gr.Textbox(label="Describe your symptoms", placeholder="e.g., headache, fever, nausea...")
136
- analyze_btn = gr.Button("Analyze Symptoms", variant="primary")
137
- report_output = gr.Textbox(label="Medical Report", interactive=False)
138
- pdf_output = gr.File(label="Download Full Report", file_count="single")
139
-
140
- # Actions
141
- analyze_btn.click(create_medical_report, inputs=symptoms_input, outputs=[report_output, pdf_output])
142
- nav_buttons.change(show_section, inputs=[nav_buttons], outputs=[home_section, diagnostic_section])
143
 
144
  # Run Interface
145
- interface.launch()
 
4
  import os
5
  from groq import Groq
6
  from deep_translator import GoogleTranslator
7
+ import requests
8
 
9
  # Load API Key
10
  groq_api_key = os.getenv("groq_api_key")
11
  groq_client = Groq(api_key=groq_api_key)
12
+ GROQ_API_KEY = os.getenv("groq_api_key")
13
+ API_URL = "https://api.groq.com/v1/chat/completions"
14
 
15
  # Load Zero-Shot Classification Model
16
  classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
 
56
  # Function to generate expert analysis
57
  def generate_expert_analysis(condition, symptoms):
58
  specialist_title = specialist_mapping.get(condition, ("General Physician", "General Medicine"))[0]
 
59
  prompt = f"""As a {specialist_title.lower()}, explain {condition} to a patient experiencing these symptoms: "{symptoms}".
60
 
61
  Structure the response into:
 
66
  5. **Diet Plan**
67
  Use professional yet simple language. **No AI disclaimers or generic advice**.
68
  """
 
69
  response = groq_client.chat.completions.create(
70
  messages=[{"role": "user", "content": prompt}],
71
  model="mixtral-8x7b-32768",
72
  temperature=0.5,
73
  max_tokens=1024
74
  )
 
75
  return response.choices[0].message.content
76
 
77
  # Function to create a medical report
 
80
  result = classifier(translated_symptoms, conditions, multi_label=False)
81
  diagnosis = result['labels'][0]
82
  specialist, system = specialist_mapping.get(diagnosis, ("General Physician", "General Medicine"))
 
83
  expert_analysis = generate_expert_analysis(diagnosis, translated_symptoms)
 
84
  full_report = (
85
  f"**Medical Report**\n\n"
86
  f"**Patient Symptoms:** {translated_symptoms}\n"
 
94
  "3. What lifestyle changes help manage this condition?\n"
95
  "4. What warning signs require immediate attention?\n"
96
  )
 
97
  pdf = FPDF()
98
  pdf.add_page()
99
  pdf.set_font("Arial", size=12)
100
  pdf.multi_cell(0, 10, full_report)
101
  pdf_path = "medical_report.pdf"
102
  pdf.output(pdf_path)
 
103
  return full_report, pdf_path
104
 
105
+ # Chatbot Integration
106
+ def chat_with_groq(prompt, model="llama3-8b-8192", temperature=0.7, max_tokens=150):
107
+ headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
108
+ data = {"model": model, "messages": [{"role": "user", "content": prompt}], "temperature": temperature, "max_tokens": max_tokens}
109
+ response = requests.post(API_URL, headers=headers, json=data)
110
+ if response.status_code == 200:
111
+ return response.json()["choices"][0]["message"]["content"].strip()
112
+ else:
113
+ return f"Error: {response.status_code}, {response.text}"
114
+
115
+ def respond(message, history, system_message, max_tokens, temperature, top_p):
116
+ response = chat_with_groq(prompt=message, model="llama3-8b-8192", temperature=temperature, max_tokens=max_tokens)
117
+ yield response
118
+
119
+ system_message = (
120
+ "You are a compassionate medical assistant and mental health guide. "
121
+ "Provide supportive responses but avoid direct diagnoses or prescriptions."
122
+ )
123
+
124
+ demo = gr.ChatInterface(
125
+ respond,
126
+ additional_inputs=[
127
+ gr.Textbox(value=system_message, label="System message"),
128
+ gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
129
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
130
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p"),
131
+ ],
132
+ )
 
 
 
 
 
 
133
 
134
  # Run Interface
135
+ demo.launch()