Hasnain-Ali commited on
Commit
b6fb84d
Β·
verified Β·
1 Parent(s): 2c41456

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -118
app.py CHANGED
@@ -1,26 +1,25 @@
1
- import streamlit as st
2
  from transformers import pipeline
3
  from fpdf import FPDF
4
  import os
5
  from groq import Groq
6
  from deep_translator import GoogleTranslator
7
- import time
8
 
9
- # Load API Key
10
- groq_api_key = os.getenv("groq_api_key")
11
  groq_client = Groq(api_key=groq_api_key)
12
 
13
- # Load Model
14
- classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
15
-
16
- # Translation Function
17
  def translate_text(text, target_lang="en"):
18
  try:
19
  return GoogleTranslator(source="auto", target=target_lang).translate(text)
20
  except Exception as e:
21
  return f"Translation Error: {str(e)}"
22
 
23
- # Medical Conditions
 
 
 
24
  conditions = [
25
  "Asthma", "COPD", "Pneumonia", "Tuberculosis", "COVID-19", "Bronchitis",
26
  "Heart Failure", "Hypertension", "Diabetes Type 1", "Diabetes Type 2",
@@ -28,7 +27,7 @@ conditions = [
28
  "Chronic Kidney Disease", "UTI", "Osteoporosis", "Psoriasis", "Epilepsy"
29
  ]
30
 
31
- # Specialist Mapping
32
  specialist_mapping = {
33
  "Asthma": ("Pulmonologist", "Respiratory System"),
34
  "COPD": ("Pulmonologist", "Respiratory System"),
@@ -51,11 +50,11 @@ specialist_mapping = {
51
  "Epilepsy": ("Neurologist", "Nervous System")
52
  }
53
 
54
- # Function to generate expert analysis
55
  def generate_expert_analysis(condition, symptoms):
 
56
  specialist_title = specialist_mapping.get(condition, ("General Physician", "General Medicine"))[0]
57
 
58
- prompt = f"""As a {specialist_title.lower()}, explain {condition} to a patient experiencing these symptoms: "{symptoms}".
59
 
60
  Structure the response into:
61
  1. **Biological Process**
@@ -63,7 +62,8 @@ def generate_expert_analysis(condition, symptoms):
63
  3. **Long-term Care**
64
  4. **Emergency Signs**
65
  5. **Diet Plan**
66
- Use professional yet simple language.
 
67
  """
68
 
69
  response = groq_client.chat.completions.create(
@@ -75,10 +75,11 @@ def generate_expert_analysis(condition, symptoms):
75
 
76
  return response.choices[0].message.content
77
 
78
- # Function to generate medical report
79
  def create_medical_report(symptoms):
 
80
  try:
81
  translated_symptoms = translate_text(symptoms, "en")
 
82
  result = classifier(translated_symptoms, conditions, multi_label=False)
83
  diagnosis = result['labels'][0]
84
  specialist, system = specialist_mapping.get(diagnosis, ("General Physician", "General Medicine"))
@@ -92,120 +93,53 @@ def create_medical_report(symptoms):
92
  f"**Affected System:** {system}\n"
93
  f"**Consult:** {specialist}\n\n"
94
  f"**Expert Analysis:**\n{expert_analysis}\n\n"
 
 
 
 
 
95
  )
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
 
104
- return full_report, pdf_path
105
 
106
  except Exception as e:
107
  return f"Error generating report: {str(e)}", None
108
 
109
- # Streamlit UI Enhancements
110
- st.set_page_config(page_title="MedExpert AI", layout="wide")
111
-
112
- # Apply Tailwind CSS & Custom Styles
113
- st.markdown("""
114
- <style>
115
- /* Background Gradient */
116
- body {
117
- background: linear-gradient(to right, #ff7e5f, #feb47b);
118
- color: white;
119
- }
120
-
121
- /* Sidebar Design */
122
- [data-testid="stSidebar"] {
123
- background-color: #2C3E50 !important;
124
- color: white !important;
125
- }
126
-
127
- [data-testid="stSidebar"] a {
128
- color: white !important;
129
- font-size: 18px !important;
130
- }
131
-
132
- /* Custom Buttons */
133
- .stButton>button {
134
- background-color: #16A085;
135
- color: white;
136
- padding: 10px 20px;
137
- border-radius: 8px;
138
- font-size: 16px;
139
- }
140
-
141
- .stButton>button:hover {
142
- background-color: #1ABC9C;
143
- }
144
-
145
- /* Custom Input Box */
146
- .stTextInput>div>div>input {
147
- background-color: white !important;
148
- border-radius: 10px !important;
149
- border: 2px solid #16A085 !important;
150
- padding: 8px !important;
151
- }
152
-
153
- /* Title Styling */
154
- .stApp h1 {
155
- text-align: center;
156
- font-size: 36px;
157
- color: #2C3E50;
158
- }
159
-
160
- </style>
161
- """, unsafe_allow_html=True)
162
-
163
-
164
- # Sidebar UI
165
- with st.sidebar:
166
- st.markdown("## πŸ” **Navigation**", unsafe_allow_html=True)
167
- page = st.radio("", ["🏠 Home", "πŸ“„ Diagnosis", "πŸ“’ About"])
168
- st.markdown("---")
169
- st.markdown("### πŸ“Œ **Built with AI & Healthcare Experts**")
170
-
171
-
172
- # Main Page
173
- st.title("🩺 MedExpert: AI-Powered Clinical Analysis System")
174
- st.markdown("πŸ’‘ *Get AI-powered medical analysis & professional reports instantly!*")
175
-
176
- # Home Page
177
- if page == "🏠 Home":
178
- st.image("https://source.unsplash.com/800x400/?healthcare,hospital", use_container_width=True)
179
- st.write("### Welcome to MedExpert!")
180
- st.write("πŸ”Ή AI-based clinical diagnosis system for analyzing symptoms.")
181
- st.write("πŸ”Ή Generates professional **medical reports** instantly.")
182
- st.write("πŸ”Ή Provides **expert doctor recommendations**.")
183
- st.write("πŸ”Ή Supports **multiple languages** (Urdu, English, Arabic, etc.).")
184
-
185
- # Diagnosis Page
186
- elif page == "πŸ“„ Diagnosis":
187
- st.subheader("πŸ“ Describe Your Symptoms")
188
- symptoms = st.text_area("Enter symptoms in any language", placeholder="e.g., Mujhay sar main dard hai")
189
-
190
- if st.button("πŸ§‘β€βš•οΈ Get Diagnosis"):
191
- if symptoms.strip():
192
- with st.spinner("πŸ” **Analyzing Symptoms... Please wait...**"):
193
- time.sleep(2) # Simulate processing
194
- report_text, pdf_file = create_medical_report(symptoms)
195
-
196
 
197
- if pdf_file:
198
- st.subheader("πŸ“‹ Medical Report")
199
- st.write(report_text)
200
- with open(pdf_file, "rb") as file:
201
- st.download_button(label="πŸ“₯ Download Report", data=file, file_name="medical_report.pdf", mime="application/pdf")
202
- elif:
203
- st.error("❌ Report generation failed.")
204
- elif:
205
- st.error("⚠ Please enter symptoms before proceeding.")
206
-
207
- # About Page
208
- elif page == "πŸ“’ About":
209
- st.write("### ℹ️ About MedExpert")
210
- st.write("This AI-powered medical system helps users get professional diagnosis and expert medical recommendations.")
211
 
 
 
 
1
+ import gradio as gr
2
  from transformers import pipeline
3
  from fpdf import FPDF
4
  import os
5
  from groq import Groq
6
  from deep_translator import GoogleTranslator
 
7
 
8
+ # βœ… Load Groq API key
9
+ groq_api_key = os.getenv("groq_api_key")
10
  groq_client = Groq(api_key=groq_api_key)
11
 
12
+ # βœ… Use Google Translate for auto-detection & translation
 
 
 
13
  def translate_text(text, target_lang="en"):
14
  try:
15
  return GoogleTranslator(source="auto", target=target_lang).translate(text)
16
  except Exception as e:
17
  return f"Translation Error: {str(e)}"
18
 
19
+ # βœ… Load Models
20
+ classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
21
+
22
+ # βœ… Medical Conditions List
23
  conditions = [
24
  "Asthma", "COPD", "Pneumonia", "Tuberculosis", "COVID-19", "Bronchitis",
25
  "Heart Failure", "Hypertension", "Diabetes Type 1", "Diabetes Type 2",
 
27
  "Chronic Kidney Disease", "UTI", "Osteoporosis", "Psoriasis", "Epilepsy"
28
  ]
29
 
30
+ # βœ… Specialist Mapping
31
  specialist_mapping = {
32
  "Asthma": ("Pulmonologist", "Respiratory System"),
33
  "COPD": ("Pulmonologist", "Respiratory System"),
 
50
  "Epilepsy": ("Neurologist", "Nervous System")
51
  }
52
 
 
53
  def generate_expert_analysis(condition, symptoms):
54
+ """Generates expert medical analysis using Groq API"""
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:
60
  1. **Biological Process**
 
62
  3. **Long-term Care**
63
  4. **Emergency Signs**
64
  5. **Diet Plan**
65
+
66
+ Use professional yet simple language. **No AI disclaimers or generic advice**.
67
  """
68
 
69
  response = groq_client.chat.completions.create(
 
75
 
76
  return response.choices[0].message.content
77
 
 
78
  def create_medical_report(symptoms):
79
+ """Generates a complete medical report"""
80
  try:
81
  translated_symptoms = translate_text(symptoms, "en")
82
+
83
  result = classifier(translated_symptoms, conditions, multi_label=False)
84
  diagnosis = result['labels'][0]
85
  specialist, system = specialist_mapping.get(diagnosis, ("General Physician", "General Medicine"))
 
93
  f"**Affected System:** {system}\n"
94
  f"**Consult:** {specialist}\n\n"
95
  f"**Expert Analysis:**\n{expert_analysis}\n\n"
96
+ "**Key Questions for Your Doctor:**\n"
97
+ "1. Is this condition acute or chronic?\n"
98
+ "2. What medication options are suitable?\n"
99
+ "3. What lifestyle changes help manage this condition?\n"
100
+ "4. What warning signs require immediate attention?\n"
101
  )
102
 
103
  pdf = FPDF()
104
  pdf.add_page()
105
  pdf.set_font("Arial", size=12)
106
  pdf.multi_cell(0, 10, full_report)
107
+ pdf.output("report.pdf")
 
108
 
109
+ return full_report, "report.pdf"
110
 
111
  except Exception as e:
112
  return f"Error generating report: {str(e)}", None
113
 
114
+ # βœ… Create Sidebar with Navigation
115
+ with gr.Blocks(css="body { background-color: #f5f7fa; }") as app:
116
+ with gr.Row():
117
+ gr.Markdown("<h1 style='text-align: center; color: #4A90E2;'>MedExpert AI</h1>")
118
+
119
+ with gr.Tabs():
120
+ with gr.TabItem("🏠 Home"):
121
+ gr.Markdown("""
122
+ <h2 style="color: #4A90E2;">Welcome to MedExpert</h2>
123
+ <p style="font-size:18px;">An AI-powered medical assistant that provides expert analysis based on your symptoms.</p>
124
+ <p style="font-size:18px;">Simply describe your symptoms, and let AI generate a detailed report!</p>
125
+ """)
126
+
127
+ with gr.TabItem("πŸ“„ Medical Diagnosis"):
128
+ with gr.Row():
129
+ symptoms_input = gr.Textbox(label="Describe Your Symptoms", placeholder="e.g., Mujhay sar main dard hai", interactive=True)
130
+ report_btn = gr.Button("πŸ” Generate Report", elem_id="generate-btn")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
+ with gr.Row():
133
+ report_output = gr.Textbox(label="Complete Medical Report", interactive=False)
134
+ pdf_output = gr.File(label="Download PDF Report")
135
+
136
+ report_btn.click(create_medical_report, inputs=[symptoms_input], outputs=[report_output, pdf_output])
137
+
138
+ with gr.TabItem("ℹ️ About"):
139
+ gr.Markdown("""
140
+ <h2 style="color: #4A90E2;">About This App</h2>
141
+ <p style="font-size:18px;">MedExpert AI is an intelligent health assistant designed to provide expert insights into medical conditions.</p>
142
+ """)
 
 
 
143
 
144
+ # βœ… Launch App
145
+ app.launch()