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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -182
app.py CHANGED
@@ -1,40 +1,27 @@
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")
 
11
 
12
- # Pre-trained ResNet50 model for X-ray or image analysis
13
- image_model = timm.create_model('resnet50', pretrained=True)
14
- image_model.eval()
15
-
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
 
26
- # Disease details for medical report analyzer
27
- disease_details = {
28
- "anemia": {"medication": "Iron supplements", "precaution": "Eat iron-rich foods", "doctor": "Hematologist"},
29
- "viral infection": {"medication": "Antiviral drugs", "precaution": "Stay hydrated", "doctor": "Infectious Disease Specialist"},
30
- "liver disease": {"medication": "Hepatoprotective drugs", "precaution": "Avoid alcohol", "doctor": "Hepatologist"},
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({
@@ -50,81 +37,16 @@ def register_patient(name, age, gender, password):
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=[
@@ -136,60 +58,6 @@ registration_interface = gr.Interface(
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")
@@ -197,28 +65,7 @@ with gr.Blocks() as app:
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)
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
 
 
 
 
 
3
 
4
+ # Load the PastelMed model and tokenizer
5
+ tokenizer = AutoTokenizer.from_pretrained("harishussain12/PastelMed")
6
+ model = AutoModelForCausalLM.from_pretrained("harishussain12/PastelMed")
7
 
8
+ # Patient database (example, can be expanded)
 
 
 
 
 
 
 
 
 
 
 
9
  patients_db = []
10
 
11
+ # Doctor's assistant function
12
+ def doctor_assistant(question):
13
+ # Encode the input question
14
+ inputs = tokenizer(question, return_tensors="pt")
15
+
16
+ # Generate a response from the model
17
+ outputs = model.generate(inputs["input_ids"], max_length=200, num_return_sequences=1)
18
+
19
+ # Decode the generated response
20
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
21
+
22
+ return response
23
 
24
+ # Function to register a patient (simplified version)
25
  def register_patient(name, age, gender, password):
26
  patient_id = len(patients_db) + 1
27
  patients_db.append({
 
37
  })
38
  return f"βœ… Patient {name} registered successfully. Patient ID: {patient_id}"
39
 
40
+ # Gradio Interface for Doctor Assistance
41
+ doctor_assistant_interface = gr.Interface(
42
+ fn=doctor_assistant,
43
+ inputs=gr.Textbox(label="Ask a Question to the Doctor Assistant"),
44
+ outputs="text",
45
+ title="Doctor Assistant",
46
+ description="Ask the assistant for medical advice and it will generate a response based on the PastelMed model."
47
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
+ # Gradio Interface for Patient Registration (for testing)
50
  registration_interface = gr.Interface(
51
  fn=register_patient,
52
  inputs=[
 
58
  outputs="text",
59
  )
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  # Gradio App Layout
62
  with gr.Blocks() as app:
63
  gr.Markdown("# Medico GPT")
 
65
  with gr.Tab("Patient Registration"):
66
  registration_interface.render()
67
 
68
+ with gr.Tab("Doctor Assistant"):
69
+ doctor_assistant_interface.render()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
  app.launch(share=True)