Hasnain-Ali commited on
Commit
bb247b8
Β·
verified Β·
1 Parent(s): d5012fd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -86
app.py CHANGED
@@ -4,11 +4,15 @@ 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
  # Translation Function
13
  def translate_text(text, target_lang="en"):
14
  try:
@@ -16,43 +20,49 @@ def translate_text(text, target_lang="en"):
16
  except Exception as e:
17
  return f"Translation Error: {str(e)}"
18
 
19
- # Load Model
20
- classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
21
-
22
- # Medical Conditions & Specialist Mapping
23
- conditions = {
24
- "Asthma": "Pulmonologist",
25
- "COPD": "Pulmonologist",
26
- "Pneumonia": "Pulmonologist",
27
- "Tuberculosis": "Infectious Disease Specialist",
28
- "COVID-19": "Infectious Disease Specialist",
29
- "Heart Failure": "Cardiologist",
30
- "Hypertension": "Cardiologist",
31
- "Diabetes Type 1": "Endocrinologist",
32
- "Diabetes Type 2": "Endocrinologist",
33
- "Migraine": "Neurologist",
34
- "Gastroenteritis": "Gastroenterologist",
35
- "Anemia": "Hematologist",
36
- "Depression": "Psychiatrist",
37
- "Anxiety Disorder": "Psychiatrist",
38
- "Chronic Kidney Disease": "Nephrologist",
39
- "UTI": "Urologist",
40
- "Osteoporosis": "Orthopedic Specialist",
41
- "Psoriasis": "Dermatologist",
42
- "Epilepsy": "Neurologist"
 
 
 
 
 
43
  }
44
 
45
  # Function to generate expert analysis
46
  def generate_expert_analysis(condition, symptoms):
47
- specialist = conditions.get(condition, "General Physician")
48
 
49
- prompt = f"""As a {specialist.lower()}, explain {condition} to a patient experiencing these symptoms: "{symptoms}".
 
50
  Structure the response into:
51
- 1. **Biological Process**
52
- 2. **Immediate Treatment**
53
- 3. **Long-term Care**
54
- 4. **Emergency Signs**
55
- 5. **Diet Plan**
56
  Use professional yet simple language.
57
  """
58
 
@@ -69,95 +79,94 @@ def generate_expert_analysis(condition, symptoms):
69
  def create_medical_report(symptoms):
70
  try:
71
  translated_symptoms = translate_text(symptoms, "en")
72
- result = classifier(translated_symptoms, list(conditions.keys()), multi_label=False)
73
  diagnosis = result['labels'][0]
74
- specialist = conditions.get(diagnosis, "General Physician")
75
 
76
  expert_analysis = generate_expert_analysis(diagnosis, translated_symptoms)
77
 
78
- full_report = f"""
79
- ### πŸ“‹ Medical Report
80
- **πŸ“ Patient Symptoms:** {translated_symptoms}
81
- **πŸ” Primary Diagnosis:** {diagnosis}
82
- **πŸ«€ Consult:** {specialist}
83
-
84
- **πŸ§‘β€βš•οΈ Expert Analysis:**
85
- {expert_analysis}
86
-
87
- **🩺 Key Questions for Doctor:**
88
- 1️⃣ Is this condition acute or chronic?
89
- 2️⃣ What medication options are suitable?
90
- 3️⃣ What lifestyle changes help manage this condition?
91
- 4️⃣ What warning signs require immediate attention?
92
- """
93
 
94
  pdf = FPDF()
95
  pdf.add_page()
96
  pdf.set_font("Arial", size=12)
97
  pdf.multi_cell(0, 10, full_report)
98
- pdf.output("medical_report.pdf")
 
99
 
100
- return full_report, "medical_report.pdf"
101
 
102
  except Exception as e:
103
  return f"Error generating report: {str(e)}", None
104
 
105
- # Streamlit UI
106
  st.set_page_config(page_title="MedExpert AI", layout="wide")
107
 
108
- # Custom CSS for Tailwind Styling
109
- st.markdown("""
 
110
  <style>
111
- body { background: linear-gradient(135deg, #1d3557, #457b9d); color: white; }
112
- .sidebar .sidebar-content { background: #1d3557 !important; color: white; }
113
- .stButton>button { background: #e63946; color: white; font-weight: bold; padding: 12px 20px; border-radius: 5px; }
114
- .stButton>button:hover { background: #a02938; }
115
- .report-box { background: white; color: black; padding: 20px; border-radius: 10px; }
116
- .loader { animation: spin 1s linear infinite; border: 4px solid #ccc; border-top: 4px solid #e63946; border-radius: 50%; width: 50px; height: 50px; }
117
- @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
118
  </style>
119
- """, unsafe_allow_html=True)
 
 
120
 
121
- # Sidebar
122
- st.sidebar.markdown("## πŸ” Navigation")
123
- page = st.sidebar.radio("", ["🏠 Home", "πŸ“„ Diagnosis", "πŸ“’ About"])
 
 
 
124
 
125
  # Main Page
126
- st.markdown("<h1 style='text-align: center;'>🩺 MedExpert AI</h1>", unsafe_allow_html=True)
127
- st.markdown("<p style='text-align: center; font-size: 18px;'>πŸ’‘ AI-powered medical diagnosis & reports</p>", unsafe_allow_html=True)
128
 
 
129
  if page == "🏠 Home":
130
- st.image("https://source.unsplash.com/800x400/?healthcare,medical", use_column_width=True)
131
- st.markdown("""
132
- - πŸ”Ή AI-based clinical **symptom analysis**
133
- - πŸ”Ή Generates **professional medical reports**
134
- - πŸ”Ή Provides **expert doctor recommendations**
135
- - πŸ”Ή Supports **multiple languages**
136
- """)
137
-
138
  elif page == "πŸ“„ Diagnosis":
139
- st.markdown("<h2>πŸ“ Describe Your Symptoms</h2>", unsafe_allow_html=True)
140
  symptoms = st.text_area("Enter symptoms in any language", placeholder="e.g., Mujhay sar main dard hai")
141
 
142
  if st.button("πŸ§‘β€βš•οΈ Get Diagnosis"):
143
  if symptoms.strip():
144
- with st.spinner("πŸ” AI is analyzing..."):
 
145
  report_text, pdf_file = create_medical_report(symptoms)
146
 
147
- if report_text:
148
- st.markdown('<div class="report-box">', unsafe_allow_html=True)
149
- st.markdown(report_text, unsafe_allow_html=True)
150
- st.markdown('</div>', unsafe_allow_html=True)
151
- st.success("βœ… Report Generated Successfully!")
152
-
153
  with open(pdf_file, "rb") as file:
154
  st.download_button(label="πŸ“₯ Download Report", data=file, file_name="medical_report.pdf", mime="application/pdf")
 
 
155
  else:
156
  st.error("⚠ Please enter symptoms before proceeding.")
157
 
 
158
  elif page == "πŸ“’ About":
159
- st.markdown("### ℹ️ About MedExpert")
160
- st.markdown("AI-powered **medical diagnosis system** to provide expert guidance.")
161
 
162
- st.markdown("---")
163
- st.markdown("<p style='text-align: center;'>πŸ‘¨β€βš•οΈ Built with ❀️ by AI & Healthcare Experts</p>", unsafe_allow_html=True)
 
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:
 
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",
27
+ "Migraine", "Gastroenteritis", "Anemia", "Depression", "Anxiety Disorder",
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"),
35
+ "Pneumonia": ("Pulmonologist", "Respiratory System"),
36
+ "Tuberculosis": ("Infectious Disease Specialist", "Respiratory System"),
37
+ "COVID-19": ("Infectious Disease Specialist", "Immune System"),
38
+ "Heart Failure": ("Cardiologist", "Cardiovascular System"),
39
+ "Hypertension": ("Cardiologist", "Cardiovascular System"),
40
+ "Diabetes Type 1": ("Endocrinologist", "Endocrine System"),
41
+ "Diabetes Type 2": ("Endocrinologist", "Endocrine System"),
42
+ "Migraine": ("Neurologist", "Nervous System"),
43
+ "Gastroenteritis": ("Gastroenterologist", "Digestive System"),
44
+ "Anemia": ("Hematologist", "Blood Disorders"),
45
+ "Depression": ("Psychiatrist", "Mental Health"),
46
+ "Anxiety Disorder": ("Psychiatrist", "Mental Health"),
47
+ "Chronic Kidney Disease": ("Nephrologist", "Urinary System"),
48
+ "UTI": ("Urologist", "Urinary System"),
49
+ "Osteoporosis": ("Orthopedic Specialist", "Musculoskeletal System"),
50
+ "Psoriasis": ("Dermatologist", "Skin Disorders"),
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**
62
+ 2. **Immediate Treatment**
63
+ 3. **Long-term Care**
64
+ 4. **Emergency Signs**
65
+ 5. **Diet Plan**
66
  Use professional yet simple language.
67
  """
68
 
 
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"))
85
 
86
  expert_analysis = generate_expert_analysis(diagnosis, translated_symptoms)
87
 
88
+ full_report = (
89
+ f"**Medical Report**\n\n"
90
+ f"**Patient Symptoms:** {translated_symptoms}\n"
91
+ f"**Primary Diagnosis:** {diagnosis}\n"
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
+ """
115
  <style>
116
+ body {background: linear-gradient(to right, #ff7e5f, #feb47b);}
117
+ .sidebar .sidebar-content {background: #2C3E50;}
118
+ .sidebar .sidebar-content a {color: #ffffff !important; font-size: 18px;}
119
+ .stButton>button {background-color: #16A085; color: white; padding: 10px 20px; border-radius: 8px;}
120
+ .stButton>button:hover {background-color: #1ABC9C;}
121
+ .stMarkdown {font-size: 18px; color: #2C3E50;}
 
122
  </style>
123
+ """,
124
+ unsafe_allow_html=True
125
+ )
126
 
127
+ # Sidebar UI
128
+ with st.sidebar:
129
+ st.markdown("## πŸ” Navigation")
130
+ page = st.radio("", ["🏠 Home", "πŸ“„ Diagnosis", "πŸ“’ About"])
131
+ st.markdown("---")
132
+ st.markdown("**πŸ“Œ Built by AI & Healthcare Experts**")
133
 
134
  # Main Page
135
+ st.title("🩺 MedExpert: AI-Powered Clinical Analysis System")
136
+ st.markdown("πŸ’‘ *Get AI-powered medical analysis & professional reports instantly!*")
137
 
138
+ # Home Page
139
  if page == "🏠 Home":
140
+ st.image("https://source.unsplash.com/800x400/?healthcare,hospital", use_container_width=True)
141
+ st.write("### Welcome to MedExpert!")
142
+ st.write("πŸ”Ή AI-based clinical diagnosis system for analyzing symptoms.")
143
+ st.write("πŸ”Ή Generates professional **medical reports** instantly.")
144
+ st.write("πŸ”Ή Provides **expert doctor recommendations**.")
145
+ st.write("πŸ”Ή Supports **multiple languages** (Urdu, English, Arabic, etc.).")
146
+
147
+ # Diagnosis Page
148
  elif page == "πŸ“„ Diagnosis":
149
+ st.subheader("πŸ“ Describe Your Symptoms")
150
  symptoms = st.text_area("Enter symptoms in any language", placeholder="e.g., Mujhay sar main dard hai")
151
 
152
  if st.button("πŸ§‘β€βš•οΈ Get Diagnosis"):
153
  if symptoms.strip():
154
+ with st.spinner("πŸ” Analyzing Symptoms..."):
155
+ time.sleep(2) # Simulate processing
156
  report_text, pdf_file = create_medical_report(symptoms)
157
 
158
+ if pdf_file:
159
+ st.subheader("πŸ“‹ Medical Report")
160
+ st.write(report_text)
 
 
 
161
  with open(pdf_file, "rb") as file:
162
  st.download_button(label="πŸ“₯ Download Report", data=file, file_name="medical_report.pdf", mime="application/pdf")
163
+ else:
164
+ st.error("❌ Report generation failed.")
165
  else:
166
  st.error("⚠ Please enter symptoms before proceeding.")
167
 
168
+ # About Page
169
  elif page == "πŸ“’ About":
170
+ st.write("### ℹ️ About MedExpert")
171
+ st.write("This AI-powered medical system helps users get professional diagnosis and expert medical recommendations.")
172