Spaces:
Sleeping
Sleeping
ahmed-7124
commited on
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import gradio as gr
|
3 |
+
import tensorflow as tf
|
4 |
+
import numpy as np
|
5 |
+
import pandas as pd
|
6 |
+
from transformers import pipeline
|
7 |
+
import pdfplumber
|
8 |
+
from PIL import Image
|
9 |
+
import timm
|
10 |
+
import torch
|
11 |
+
|
12 |
+
# Load pre-trained zero-shot model for text classification
|
13 |
+
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
|
14 |
+
|
15 |
+
# Pre-trained model for X-ray analysis
|
16 |
+
image_model = timm.create_model('resnet50', pretrained=True)
|
17 |
+
image_model.eval()
|
18 |
+
|
19 |
+
# Load saved TensorFlow eye disease detection model
|
20 |
+
eye_model = tf.keras.models.load_model('model.h5')
|
21 |
+
|
22 |
+
# Patient database
|
23 |
+
patients_db = []
|
24 |
+
|
25 |
+
# Disease details for medical report analyzer
|
26 |
+
disease_details = {
|
27 |
+
"anemia": {
|
28 |
+
"medication": "Iron supplements (e.g., Ferrous sulfate 325mg)",
|
29 |
+
"precaution": "Increase intake of iron-rich foods like spinach, red meat, and beans.",
|
30 |
+
"doctor": "Hematologist"
|
31 |
+
},
|
32 |
+
"viral infection": {
|
33 |
+
"medication": "Antiviral drugs (e.g., Oseltamivir 75mg for flu)",
|
34 |
+
"precaution": "Rest, stay hydrated, avoid close contact with others, and wash hands frequently.",
|
35 |
+
"doctor": "Infectious Disease Specialist"
|
36 |
+
},
|
37 |
+
"liver disease": {
|
38 |
+
"medication": "Hepatoprotective drugs (e.g., Ursodeoxycholic acid 300mg)",
|
39 |
+
"precaution": "Avoid alcohol and maintain a balanced diet, avoid fatty foods.",
|
40 |
+
"doctor": "Hepatologist"
|
41 |
+
},
|
42 |
+
"kidney disease": {
|
43 |
+
"medication": "Angiotensin-converting enzyme inhibitors (e.g., Lisinopril 10mg)",
|
44 |
+
"precaution": "Monitor salt intake, stay hydrated, and avoid NSAIDs.",
|
45 |
+
"doctor": "Nephrologist"
|
46 |
+
},
|
47 |
+
"diabetes": {
|
48 |
+
"medication": "Metformin (e.g., 500mg) or insulin therapy",
|
49 |
+
"precaution": "Follow a low-sugar diet, monitor blood sugar levels, and exercise regularly.",
|
50 |
+
"doctor": "Endocrinologist"
|
51 |
+
},
|
52 |
+
"hypertension": {
|
53 |
+
"medication": "Antihypertensive drugs (e.g., Amlodipine 5mg)",
|
54 |
+
"precaution": "Reduce salt intake, manage stress, and avoid smoking.",
|
55 |
+
"doctor": "Cardiologist"
|
56 |
+
},
|
57 |
+
"COVID-19": {
|
58 |
+
"medication": "Supportive care, antiviral drugs (e.g., Remdesivir 200mg in severe cases)",
|
59 |
+
"precaution": "Follow isolation protocols, wear a mask, stay hydrated, and rest.",
|
60 |
+
"doctor": "Infectious Disease Specialist"
|
61 |
+
},
|
62 |
+
"pneumonia": {
|
63 |
+
"medication": "Antibiotics (e.g., Amoxicillin 500mg or Azithromycin 250mg)",
|
64 |
+
"precaution": "Rest, avoid smoking, stay hydrated, and get proper ventilation.",
|
65 |
+
"doctor": "Pulmonologist"
|
66 |
+
}
|
67 |
+
}
|
68 |
+
|
69 |
+
# Functions
|
70 |
+
def register_patient(name, age, gender):
|
71 |
+
patient_id = len(patients_db) + 1
|
72 |
+
patients_db.append({
|
73 |
+
"ID": patient_id,
|
74 |
+
"Name": name,
|
75 |
+
"Age": age,
|
76 |
+
"Gender": gender,
|
77 |
+
"Diagnosis": "",
|
78 |
+
"Medications": "",
|
79 |
+
"Precautions": ""
|
80 |
+
})
|
81 |
+
return f"β
Patient {name} registered successfully. Patient ID: {patient_id}"
|
82 |
+
|
83 |
+
def analyze_report(patient_id, report_text):
|
84 |
+
candidate_labels = list(disease_details.keys())
|
85 |
+
result = classifier(report_text, candidate_labels)
|
86 |
+
diagnosis = result['labels'][0]
|
87 |
+
|
88 |
+
# Update patient's record
|
89 |
+
medication = disease_details[diagnosis]['medication']
|
90 |
+
precaution = disease_details[diagnosis]['precaution']
|
91 |
+
for patient in patients_db:
|
92 |
+
if patient['ID'] == patient_id:
|
93 |
+
patient.update(Diagnosis=diagnosis, Medications=medication, Precautions=precaution)
|
94 |
+
return f"π Diagnosis: {diagnosis}"
|
95 |
+
|
96 |
+
def extract_pdf_report(pdf):
|
97 |
+
text = ""
|
98 |
+
with pdfplumber.open(pdf.name) as pdf_file:
|
99 |
+
for page in pdf_file.pages:
|
100 |
+
text += page.extract_text()
|
101 |
+
return text
|
102 |
+
|
103 |
+
def predict_eye_disease(input_image):
|
104 |
+
input_image = tf.image.resize(input_image, [224, 224]) / 255.0
|
105 |
+
input_image = tf.expand_dims(input_image, 0)
|
106 |
+
predictions = eye_model.predict(input_image)
|
107 |
+
labels = ['Cataract', 'Conjunctivitis', 'Glaucoma', 'Normal']
|
108 |
+
confidence_scores = {labels[i]: round(predictions[0][i] * 100, 2) for i in range(len(labels))}
|
109 |
+
if confidence_scores['Normal'] > 50:
|
110 |
+
return f"Congrats! No disease detected. Confidence: {confidence_scores['Normal']}%"
|
111 |
+
return "\n".join([f"{label}: {confidence}%" for label, confidence in confidence_scores.items()])
|
112 |
+
|
113 |
+
def doctor_space(patient_id):
|
114 |
+
for patient in patients_db:
|
115 |
+
if patient["ID"] == patient_id:
|
116 |
+
diagnosis = patient["Diagnosis"]
|
117 |
+
medication = patient["Medications"]
|
118 |
+
precaution = patient["Precautions"]
|
119 |
+
doctor = disease_details.get(diagnosis, {}).get("doctor", "No doctor available")
|
120 |
+
return (f"π©Ί Patient Name: {patient['Name']}\n"
|
121 |
+
f"π Diagnosis: {diagnosis}\n"
|
122 |
+
f"π Medications: {medication}\n"
|
123 |
+
f"β οΈ Precautions: {precaution}\n"
|
124 |
+
f"π©ββοΈ Recommended Doctor: {doctor}")
|
125 |
+
return "Patient not found. Please check the ID."
|
126 |
+
|
127 |
+
def pharmacist_space(patient_id):
|
128 |
+
for patient in patients_db:
|
129 |
+
if patient["ID"] == patient_id:
|
130 |
+
diagnosis = patient["Diagnosis"]
|
131 |
+
medication = patient["Medications"]
|
132 |
+
return f"π Patient Name: {patient['Name']}\nπ Prescribed Medications: {medication}"
|
133 |
+
return "Patient not found. Please check the ID."
|
134 |
+
|
135 |
+
# Gradio Interfaces
|
136 |
+
registration_interface = gr.Interface(fn=register_patient, inputs=[gr.Textbox(label="Patient Name"), gr.Number(label="Age"), gr.Radio(label="Gender", choices=["Male", "Female", "Other"])], outputs="text")
|
137 |
+
report_analysis_interface = gr.Interface(fn=analyze_report, inputs=[gr.Number(label="Patient ID"), gr.Textbox(label="Report Text")], outputs="text")
|
138 |
+
pdf_report_extraction_interface = gr.Interface(fn=extract_pdf_report, inputs=gr.File(label="Upload PDF Report"), outputs="text")
|
139 |
+
eye_disease_interface = gr.Interface(fn=predict_eye_disease, inputs=gr.Image(label="Upload an Eye Image", type="numpy"), outputs="text")
|
140 |
+
dashboard_interface = gr.Interface(fn=lambda: pd.DataFrame(patients_db), inputs=None, outputs="dataframe")
|
141 |
+
doctor_interface = gr.Interface(fn=doctor_space, inputs=gr.Number(label="Patient ID"), outputs="text")
|
142 |
+
pharmacist_interface = gr.Interface(fn=pharmacist_space, inputs=gr.Number(label="Patient ID"), outputs="text")
|
143 |
+
|
144 |
+
# Gradio App Layout
|
145 |
+
with gr.Blocks() as app:
|
146 |
+
gr.Markdown("# Medical Analyzer and Eye Disease Detection")
|
147 |
+
with gr.Tab("Patient Registration"):
|
148 |
+
registration_interface.render()
|
149 |
+
with gr.Tab("Analyze Medical Report"):
|
150 |
+
report_analysis_interface.render()
|
151 |
+
with gr.Tab("Extract PDF Report"):
|
152 |
+
pdf_report_extraction_interface.render()
|
153 |
+
with gr.Tab("Detect Eye Disease"):
|
154 |
+
eye_disease_interface.render()
|
155 |
+
with gr.Tab("Doctor Space"):
|
156 |
+
doctor_interface.render()
|
157 |
+
with gr.Tab("Pharmacist Space"):
|
158 |
+
pharmacist_interface.render()
|
159 |
+
with gr.Tab("Patient Dashboard"):
|
160 |
+
dashboard_interface.render()
|
161 |
+
|
162 |
+
app.launch(share=True)
|