ahmed-7124 commited on
Commit
3858fe6
Β·
verified Β·
1 Parent(s): a10473c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +179 -37
app.py CHANGED
@@ -1,9 +1,10 @@
1
- # Import necessary libraries
2
  import gradio as gr
3
  import tensorflow as tf
4
  import pdfplumber
5
- from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
6
  import timm
 
 
7
 
8
  # Load pre-trained zero-shot model for text classification
9
  classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
@@ -15,6 +16,10 @@ image_model.eval()
15
  # Load saved TensorFlow eye disease detection model
16
  eye_model = tf.keras.models.load_model('model.h5')
17
 
 
 
 
 
18
  # Patient database
19
  patients_db = []
20
 
@@ -26,57 +31,194 @@ disease_details = {
26
  "diabetes": {"medication": "Metformin or insulin", "precaution": "Monitor sugar levels", "doctor": "Endocrinologist"},
27
  }
28
 
29
- # Doctor consultant models
30
- neura_tokenizer = AutoTokenizer.from_pretrained("ahmed-7124/NeuraMedAW")
31
- neura_model = AutoModelForCausalLM.from_pretrained("ahmed-7124/NeuraMedAW")
32
- lynx_tokenizer = AutoTokenizer.from_pretrained("ahmed-7124/LynxMedAW")
33
- lynx_model = AutoModelForCausalLM.from_pretrained("ahmed-7124/LynxMedAW")
34
-
35
  # Passwords
36
  doctor_password = "doctor123"
37
 
38
- # Helper Functions
39
- def generate_consultation_response(prompt):
40
- neura_input = neura_tokenizer(prompt, return_tensors="pt")
41
- neura_response = neura_model.generate(**neura_input, max_length=200, num_return_sequences=1)
42
- neura_output = neura_tokenizer.decode(neura_response[0], skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
- lynx_input = lynx_tokenizer(prompt, return_tensors="pt")
45
- lynx_response = lynx_model.generate(**lynx_input, max_length=200, num_return_sequences=1)
46
- lynx_output = lynx_tokenizer.decode(lynx_response[0], skip_special_tokens=True)
 
 
 
 
 
 
47
 
48
- return f"**NeuraMedAW Response:**\n{neura_output}\n\n**LynxMedAW Response:**\n{lynx_output}"
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
- # Remaining helper functions are unchanged...
51
- # Register patient, analyze reports, extract PDF, predict eye disease, doctor space, pharmacist space, and dashboards.
 
 
 
 
52
 
53
  # Gradio Interfaces
54
  registration_interface = gr.Interface(
55
  fn=register_patient,
56
- inputs=[gr.Textbox(label="Patient Name"), gr.Number(label="Age"), gr.Radio(label="Gender", choices=["Male", "Female", "Other"]), gr.Textbox(label="Set Password", type="password")],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  outputs="text",
58
  )
59
 
60
- pdf_extraction_interface = gr.Interface(fn=extract_pdf_report, inputs=gr.File(label="Upload PDF Report"), outputs="text")
61
- report_analysis_interface = gr.Interface(fn=analyze_report, inputs=[gr.Number(label="Patient ID"), gr.Textbox(label="Report Text")], outputs="text")
62
- eye_disease_interface = gr.Interface(fn=predict_eye_disease, inputs=gr.Image(label="Upload Eye Image", type="numpy"), outputs="text")
63
- doctor_space_interface = gr.Interface(fn=doctor_space, inputs=gr.Number(label="Patient ID"), outputs="text")
64
- pharmacist_space_interface = gr.Interface(fn=pharmacist_space, inputs=gr.Number(label="Patient ID"), outputs="text")
65
- patient_dashboard_interface = gr.Interface(fn=patient_dashboard, inputs=[gr.Number(label="Patient ID"), gr.Textbox(label="Password", type="password")], outputs="text")
66
- doctor_dashboard_interface = gr.Interface(fn=doctor_dashboard, inputs=gr.Textbox(label="Doctor Password", type="password"), outputs="text")
67
- doctor_consultant_interface = gr.Interface(fn=generate_consultation_response, inputs=gr.Textbox(label="Enter Symptoms or Query"), outputs="text")
68
 
69
  # Gradio App Layout
70
  with gr.Blocks() as app:
71
  gr.Markdown("# Medico GPT")
72
- with gr.Tab("Patient Registration"): registration_interface.render()
73
- with gr.Tab("Analyze Medical Report"): report_analysis_interface.render()
74
- with gr.Tab("Extract PDF Report"): pdf_extraction_interface.render()
75
- with gr.Tab("Ophthalmologist Space"): eye_disease_interface.render()
76
- with gr.Tab("Doctor Space"): doctor_space_interface.render()
77
- with gr.Tab("Pharmacist Space"): pharmacist_space_interface.render()
78
- with gr.Tab("Patient Dashboard"): patient_dashboard_interface.render()
79
- with gr.Tab("Doctor Dashboard"): doctor_dashboard_interface.render()
80
- with gr.Tab("Doctor Consultant"): doctor_consultant_interface.render()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
  app.launch(share=True)
 
 
1
  import gradio as gr
2
  import tensorflow as tf
3
  import pdfplumber
4
+ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
5
  import timm
6
+ import torch
7
+ import pandas as pd
8
 
9
  # Load pre-trained zero-shot model for text classification
10
  classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
 
16
  # Load saved TensorFlow eye disease detection model
17
  eye_model = tf.keras.models.load_model('model.h5')
18
 
19
+ # Load NeuraMedAW model and tokenizer
20
+ tokenizer = AutoTokenizer.from_pretrained("ahmed-7124/NeuraMedAW")
21
+ model = AutoModelForCausalLM.from_pretrained("ahmed-7124/NeuraMedAW")
22
+
23
  # Patient database
24
  patients_db = []
25
 
 
31
  "diabetes": {"medication": "Metformin or insulin", "precaution": "Monitor sugar levels", "doctor": "Endocrinologist"},
32
  }
33
 
 
 
 
 
 
 
34
  # Passwords
35
  doctor_password = "doctor123"
36
 
37
+ # Functions
38
+ def register_patient(name, age, gender, password):
39
+ patient_id = len(patients_db) + 1
40
+ patients_db.append({
41
+ "ID": patient_id,
42
+ "Name": name,
43
+ "Age": age,
44
+ "Gender": gender,
45
+ "Password": password,
46
+ "Diagnosis": "",
47
+ "Medications": "",
48
+ "Precautions": "",
49
+ "Doctor": ""
50
+ })
51
+ return f"βœ… Patient {name} registered successfully. Patient ID: {patient_id}"
52
+
53
+ def analyze_report(patient_id, report_text):
54
+ candidate_labels = list(disease_details.keys())
55
+ result = classifier(report_text, candidate_labels)
56
+ diagnosis = result['labels'][0]
57
+
58
+ # Update patient's record
59
+ medication = disease_details[diagnosis]['medication']
60
+ precaution = disease_details[diagnosis]['precaution']
61
+ doctor = disease_details[diagnosis]['doctor']
62
+ for patient in patients_db:
63
+ if patient['ID'] == patient_id:
64
+ patient.update(Diagnosis=diagnosis, Medications=medication, Precautions=precaution, Doctor=doctor)
65
+ return f"πŸ” Diagnosis: {diagnosis}"
66
+
67
+ def extract_pdf_report(pdf):
68
+ text = ""
69
+ with pdfplumber.open(pdf.name) as pdf_file:
70
+ for page in pdf_file.pages:
71
+ text += page.extract_text()
72
+ return text
73
+
74
+ def predict_eye_disease(input_image):
75
+ input_image = tf.image.resize(input_image, [224, 224]) / 255.0
76
+ input_image = tf.expand_dims(input_image, 0)
77
+ predictions = eye_model.predict(input_image)
78
+ labels = ['Cataract', 'Conjunctivitis', 'Glaucoma', 'Normal']
79
+ confidence_scores = {labels[i]: round(predictions[0][i] * 100, 2) for i in range(len(labels))}
80
+ if confidence_scores['Normal'] > 50:
81
+ return f"Congrats! No disease detected. Confidence: {confidence_scores['Normal']}%"
82
+ return "\n".join([f"{label}: {confidence}%" for label, confidence in confidence_scores.items()])
83
+
84
+ def doctor_space(patient_id):
85
+ for patient in patients_db:
86
+ if patient["ID"] == patient_id:
87
+ return f"⚠️ Precautions: {patient['Precautions']}\nπŸ‘©β€βš•οΈ Recommended Doctor: {patient['Doctor']}"
88
+ return "❌ Patient not found. Please check the ID."
89
+
90
+ def pharmacist_space(patient_id):
91
+ for patient in patients_db:
92
+ if patient["ID"] == patient_id:
93
+ return f"πŸ’Š Medications: {patient['Medications']}"
94
+ return "❌ Patient not found. Please check the ID."
95
 
96
+ def patient_dashboard(patient_id, password):
97
+ for patient in patients_db:
98
+ if patient["ID"] == patient_id and patient["Password"] == password:
99
+ return (f"🩺 Name: {patient['Name']}\n"
100
+ f"πŸ“‹ Diagnosis: {patient['Diagnosis']}\n"
101
+ f"πŸ’Š Medications: {patient['Medications']}\n"
102
+ f"⚠️ Precautions: {patient['Precautions']}\n"
103
+ f"πŸ‘©β€βš•οΈ Recommended Doctor: {patient['Doctor']}")
104
+ return "❌ Access Denied: Invalid ID or Password."
105
 
106
+ def doctor_dashboard(password):
107
+ if password != doctor_password:
108
+ return "❌ Access Denied: Incorrect Password"
109
+ if not patients_db:
110
+ return "No patient records available."
111
+ details = []
112
+ for patient in patients_db:
113
+ details.append(f"🩺 Name: {patient['Name']}\n"
114
+ f"πŸ“‹ Diagnosis: {patient['Diagnosis']}\n"
115
+ f"πŸ’Š Medications: {patient['Medications']}\n"
116
+ f"⚠️ Precautions: {patient['Precautions']}\n"
117
+ f"πŸ‘©β€βš•οΈ Recommended Doctor: {patient['Doctor']}")
118
+ return "\n\n".join(details)
119
 
120
+ def doctor_consultant(patient_query):
121
+ # Combine both models for a more comprehensive answer
122
+ inputs = tokenizer(patient_query, return_tensors="pt")
123
+ output = model.generate(**inputs, max_length=500)
124
+ response = tokenizer.decode(output[0], skip_special_tokens=True)
125
+ return response
126
 
127
  # Gradio Interfaces
128
  registration_interface = gr.Interface(
129
  fn=register_patient,
130
+ inputs=[
131
+ gr.Textbox(label="Patient Name"),
132
+ gr.Number(label="Age"),
133
+ gr.Radio(label="Gender", choices=["Male", "Female", "Other"]),
134
+ gr.Textbox(label="Set Password", type="password"),
135
+ ],
136
+ outputs="text",
137
+ )
138
+
139
+ pdf_extraction_interface = gr.Interface(
140
+ fn=extract_pdf_report,
141
+ inputs=gr.File(label="Upload PDF Report"),
142
+ outputs="text",
143
+ )
144
+
145
+ report_analysis_interface = gr.Interface(
146
+ fn=analyze_report,
147
+ inputs=[
148
+ gr.Number(label="Patient ID"),
149
+ gr.Textbox(label="Report Text"),
150
+ ],
151
+ outputs="text",
152
+ )
153
+
154
+ eye_disease_interface = gr.Interface(
155
+ fn=predict_eye_disease,
156
+ inputs=gr.Image(label="Upload an Eye Image", type="numpy"),
157
+ outputs="text",
158
+ )
159
+
160
+ doctor_space_interface = gr.Interface(
161
+ fn=doctor_space,
162
+ inputs=gr.Number(label="Patient ID"),
163
+ outputs="text",
164
+ )
165
+
166
+ pharmacist_space_interface = gr.Interface(
167
+ fn=pharmacist_space,
168
+ inputs=gr.Number(label="Patient ID"),
169
+ outputs="text",
170
+ )
171
+
172
+ patient_dashboard_interface = gr.Interface(
173
+ fn=patient_dashboard,
174
+ inputs=[
175
+ gr.Number(label="Patient ID"),
176
+ gr.Textbox(label="Password", type="password"),
177
+ ],
178
+ outputs="text",
179
+ )
180
+
181
+ doctor_dashboard_interface = gr.Interface(
182
+ fn=doctor_dashboard,
183
+ inputs=gr.Textbox(label="Doctor Password", type="password"),
184
  outputs="text",
185
  )
186
 
187
+ doctor_consultant_interface = gr.Interface(
188
+ fn=doctor_consultant,
189
+ inputs=gr.Textbox(label="Ask the Doctor a Question"),
190
+ outputs="text",
191
+ )
 
 
 
192
 
193
  # Gradio App Layout
194
  with gr.Blocks() as app:
195
  gr.Markdown("# Medico GPT")
196
+
197
+ with gr.Tab("Patient Registration"):
198
+ registration_interface.render()
199
+
200
+ with gr.Tab("Analyze Medical Report"):
201
+ report_analysis_interface.render()
202
+
203
+ with gr.Tab("Extract PDF Report"):
204
+ pdf_extraction_interface.render()
205
+
206
+ with gr.Tab("Ophthalmologist Space"):
207
+ eye_disease_interface.render()
208
+
209
+ with gr.Tab("Doctor Space"):
210
+ doctor_space_interface.render()
211
+
212
+ with gr.Tab("Pharmacist Space"):
213
+ pharmacist_space_interface.render()
214
+
215
+ with gr.Tab("Patient Dashboard"):
216
+ patient_dashboard_interface.render()
217
+
218
+ with gr.Tab("Doctor Dashboard"):
219
+ doctor_dashboard_interface.render()
220
+
221
+ with gr.Tab("Doctor Consultant"):
222
+ doctor_consultant_interface.render()
223
 
224
  app.launch(share=True)