File size: 24,458 Bytes
621ad1f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 |
import gradio as gr
import random, math
from transformers import pipeline
from PyPDF2 import PdfReader
##############################
# Helper Functions
##############################
def sigmoid(x):
return 1 / (1 + math.exp(-x))
def extract_pdf_text(pdf_file):
"""Extract text from an uploaded PDF file using PyPDF2."""
try:
reader = PdfReader(pdf_file.name) # pdf_file.name gives the filename in Colab
text = ""
for page in reader.pages:
text += page.extract_text()
return text
except Exception as e:
return f"Error extracting PDF text: {e}"
##############################
# Callback to update visibility of "Other" fields
##############################
def update_visibility(choice):
if choice == "Other":
return gr.update(visible=True)
else:
return gr.update(visible=False)
##############################
# Prediction function for non-MRI data (with PDF extraction)
##############################
def predict_without_mri(
# Section A: Patient Demographics
age, gender, ethnicity, education, pincode, mobile,
# Section B: Medical History
family_history, family_relationship, conditions, medications,
# Section C: Basic Cognitive Assessment
basic_memory_changes, basic_memory_desc, basic_difficulty_recent,
basic_trouble_words, basic_problem_solving, basic_trouble_appointments,
basic_changes_reaction, basic_driving_concern,
# Section IV: Lifestyle Factors
smoking_status, alcohol_consumption, physical_activity,
# Section E: Physical & Neurological Exam (using "Other" options)
reflexes_choice, reflexes_other,
muscle_tone_choice, muscle_tone_other,
coordination_choice, coordination_other,
balance_choice, balance_other,
sight_hearing_choice, sight_hearing_other,
# Section V: Detailed Cognitive & Functional Assessment
# A. Memory
mem_diff_recent, mem_forget_appointments, mem_repeat, mem_learning,
# B. Language
lang_find_words, lang_understand, lang_follow,
# C. Executive Function
exec_plan, exec_decide, exec_finance,
# D. Visuospatial Skills
visuospatial_judge, visuospatial_navigate, visuospatial_recognize,
# E. Attention and Concentration
attention_focus, attention_distracted, attention_instructions,
# F. Functional Abilities
func_ADL, func_medications, func_transport,
# Section VI: Behavioral and Emotional Changes
behavior_mood_change, behavior_mood_change_desc, behavior_anxiety, behavior_irritability, behavior_loss_interest,
# Section VII: Additional Comments
additional_comments,
# Section G: Blood-Based Biomarkers
p_tau217, abeta42, abeta40, miRNAs,
# Section H: Basic Cognitive & Functional Assessment Scores
mmse, adas_cog, faq, ravlt,
# PDF Report Upload (new)
pdf_report
):
# Convert numeric strings to floats
try:
mmse = float(mmse)
except:
mmse = 0.0
try:
adas = float(adas_cog)
except:
adas = 0.0
try:
p_tau217 = float(p_tau217)
except:
p_tau217 = 0.0
try:
abeta42 = float(abeta42)
except:
abeta42 = 0.0
try:
abeta40 = float(abeta40)
except:
abeta40 = 1.0 # avoid division by zero
try:
abeta_ratio = abeta42 / abeta40
except:
abeta_ratio = 0.0
# Dummy calculative model with illustrative coefficients
w_age = 0.05
w_education = -0.1
w_mmse = -0.05
w_adas = 0.05
w_ptau = 0.02
w_abeta_ratio = 0.5
bias = -5.0
risk_value = (w_age * age + w_education * education + w_mmse * mmse +
w_adas * adas + w_ptau * p_tau217 + w_abeta_ratio * abeta_ratio + bias)
risk_probability = sigmoid(risk_value)
if risk_probability < 0.33:
risk_category = "Low Risk"
elif risk_probability < 0.66:
risk_category = "Moderate Risk"
else:
risk_category = "High Risk"
# Extract text from PDF if provided
if pdf_report is not None:
pdf_text = extract_pdf_text(pdf_report)
else:
pdf_text = "No PDF report provided."
result = f"""### Prediction Result: {risk_category}
Calculated Risk Probability: {risk_probability*100:.2f}%
**Section A: Patient Demographics**
- Age: {age}
- Gender: {gender}
- Ethnicity: {ethnicity}
- Years of Education: {education}
- Pincode: {pincode}
- Mobile Number: {mobile}
**Section B: Medical History**
- Family history of Alzheimer's/dementia: {family_history}
- Relationship: {family_relationship if family_history == "Yes" else "N/A"}
- Conditions: {', '.join(conditions) if conditions else 'None'}
- Current Medications: {medications}
**Section C: Basic Cognitive Assessment**
- Recent changes in memory: {basic_memory_changes}
- Description: {basic_memory_desc}
- Difficulty remembering recent events: {basic_difficulty_recent}
- Trouble finding the right words: {basic_trouble_words}
- Difficulty with problem-solving: {basic_problem_solving}
- Trouble with appointments/medications: {basic_trouble_appointments}
- Changes in reactions: {basic_changes_reaction}
- Concerns about driving: {basic_driving_concern}
**Section IV: Lifestyle Factors**
- Smoking status: {smoking_status}
- Alcohol consumption: {alcohol_consumption}
- Physical activity level: {physical_activity}
**Section E: Physical & Neurological Exam**
- Reflexes: {reflexes_choice if reflexes_choice != "Other" else reflexes_other}
- Muscle tone and strength: {muscle_tone_choice if muscle_tone_choice != "Other" else muscle_tone_other}
- Coordination: {coordination_choice if coordination_choice != "Other" else coordination_other}
- Balance: {balance_choice if balance_choice != "Other" else balance_other}
- Sense of sight and hearing: {sight_hearing_choice if sight_hearing_choice != "Other" else sight_hearing_other}
**Section V: Detailed Cognitive & Functional Assessment**
*A. Memory*
- Difficulty remembering recent events: {mem_diff_recent}
- Forget appointments or important dates: {mem_forget_appointments}
- Repeat questions or statements: {mem_repeat}
- Trouble learning new information: {mem_learning}
*B. Language*
- Trouble finding the right words: {lang_find_words}
- Difficulty understanding what people say: {lang_understand}
- Trouble following conversations: {lang_follow}
*C. Executive Function*
- Difficulty planning/organizing tasks: {exec_plan}
- Trouble making decisions/solving problems: {exec_decide}
- Hard to manage finances: {exec_finance}
*D. Visuospatial Skills*
- Difficulty judging distances: {visuospatial_judge}
- Trouble finding your way around familiar places: {visuospatial_navigate}
- Difficulty recognizing faces: {visuospatial_recognize}
*E. Attention and Concentration*
- Difficulty focusing: {attention_focus}
- Easily distracted: {attention_distracted}
- Trouble following instructions: {attention_instructions}
*F. Functional Abilities*
- Need assistance with ADLs: {func_ADL}
- Difficulty managing medications: {func_medications}
- Difficulty driving/using public transport: {func_transport}
**Section VI: Behavioral and Emotional Changes**
- Changes in mood or personality: {behavior_mood_change}
- Description of mood changes: {behavior_mood_change_desc if behavior_mood_change == "Yes" else "N/A"}
- More anxious or depressed: {behavior_anxiety}
- More irritable or agitated: {behavior_irritability}
- Lost interest in activities: {behavior_loss_interest}
**Section VII: Additional Comments**
{additional_comments}
**Section G: Blood-Based Biomarkers**
- p-tau217: {p_tau217}
- Aβ42: {abeta42}
- Aβ40: {abeta40}
- miRNAs: {miRNAs}
**Section H: Basic Cognitive & Functional Assessment Scores**
- MMSE: {mmse}
- ADAS-Cog: {adas_cog}
- FAQ: {faq}
- RAVLT: {ravlt}
**Uploaded PDF Report Details:**
{pdf_text}
"""
return result
##############################
# Prediction function for MRI using a Hugging Face pipeline
##############################
pipe = pipeline("image-classification", model="evanrsl/resnet-Alzheimer")
#pipe = pipeline("image-classification", model="evanrsl/resnet-Alzheimer")
#def predict_with_mri(image):
def predict_alzheimer(image, age, gender, ethnicity):
"""
Predict Alzheimer’s status from an uploaded image using the pretrained pipeline,
and include demographic information (age, gender, ethnicity) in the output.
"""
# Run the pipeline on the input image
results = pipe(image)
# Assume the pipeline returns a list of dictionaries; we'll take the top result.
print(results)
label = results[0]['label']
confidence = results[0]['score'] * 100 # convert to percentage
# Create output text combining prediction and demographic info
output_text = (f"**Prediction:** {label}\n"
f"**Confidence:** {confidence:.2f}%\n\n"
f"**Demographics:**\n"
f"- Age: {age}\n"
f"- Gender: {gender}\n"
f"- Ethnicity: {ethnicity}\n"
f"Note: Prediction may be Non-Demented to High-Demented\n Confidence suggests that how the model is sure of this prediction")
return output_text
##############################
# Gradio App Interface Configuration
##############################
with gr.Blocks() as demo:
gr.Markdown("# ADAP System : Alzheimer Detection, Assessment & Prediction System")
with gr.Tabs():
###########################
# Tab: Without MRI Data #
###########################
with gr.Tab("Without MRI Data"):
gr.Markdown("### Please fill out the following form:")
# Section A: Patient Demographics
with gr.Column():
gr.Markdown("#### Section A: Patient Demographics")
age = gr.Number(label="Age (years)", value=60)
gender = gr.Radio(label="Gender", choices=["Male", "Female", "Other"])
ethnicity = gr.Textbox(label="Ethnicity", placeholder="Enter ethnicity")
education = gr.Number(label="Years of Education", value=12)
pincode = gr.Textbox(label="Pincode", placeholder="Enter your pincode")
mobile = gr.Textbox(label="Mobile Number", placeholder="Enter your mobile number")
# Section B: Medical History
with gr.Column():
gr.Markdown("#### Section B: Medical History")
family_history = gr.Radio(label="Do you have a family history of Alzheimer's disease or dementia?", choices=["Yes", "No"])
family_relationship = gr.Textbox(label="If yes, please specify the relationship", placeholder="e.g., Mother, Father, Grandparent")
conditions = gr.CheckboxGroup(label="Do you have any of the following conditions?", choices=["High blood pressure", "Heart disease", "Stroke", "Diabetes", "High cholesterol", "Head injuries"])
medications = gr.Textbox(label="List any current medications", lines=3, placeholder="Enter current medications")
# Section C: Basic Cognitive Assessment
with gr.Column():
gr.Markdown("#### Section C: Basic Cognitive Assessment")
basic_memory_changes = gr.Radio(label="Have you noticed any recent changes in your memory?", choices=["Yes", "No"])
basic_memory_desc = gr.Textbox(label="If yes, please describe", lines=3, placeholder="Describe any changes")
basic_difficulty_recent = gr.Radio(label="Do you have difficulty remembering recent events?", choices=["Not at all", "Mild", "Moderate", "Severe"])
basic_trouble_words = gr.Radio(label="Do you have trouble finding the right words?", choices=["Not at all", "Mild", "Moderate", "Severe"])
basic_problem_solving = gr.Radio(label="Do you have difficulty with problem-solving or decision-making?", choices=["Not at all", "Mild", "Moderate", "Severe"])
basic_trouble_appointments = gr.Radio(label="Are you having trouble remembering healthcare appointments or when to take your medicines?", choices=["Yes", "No"])
basic_changes_reaction = gr.Radio(label="Have you noticed any changes in the way you tend to react to people or events?", choices=["Yes", "No"])
basic_driving_concern = gr.Radio(label="Does anyone express unusual concern about your driving?", choices=["Yes", "No"])
# Section IV: Lifestyle Factors
with gr.Column():
gr.Markdown("#### Section IV: Lifestyle Factors")
smoking_status = gr.Radio(label="Smoking status", choices=["Yes", "No"])
alcohol_consumption = gr.Dropdown(label="Alcohol consumption", choices=["None", "Occasional", "Regular", "Heavy"])
physical_activity = gr.Dropdown(label="Physical activity level", choices=["Sedentary", "Moderate", "Active"])
# Section E: Physical & Neurological Exam with "Other" options
with gr.Column():
gr.Markdown("#### Section E: Physical & Neurological Exam")
reflexes_choice = gr.Radio(label="Reflexes", choices=["Normal", "Diminished", "Hyperactive", "Other"], value="Normal")
reflexes_other = gr.Textbox(label="If Other, please describe", placeholder="Describe reflexes", visible=False)
reflexes_choice.change(fn=update_visibility, inputs=reflexes_choice, outputs=reflexes_other)
muscle_tone_choice = gr.Radio(label="Muscle tone and strength", choices=["Normal", "Reduced", "Increased", "Other"], value="Normal")
muscle_tone_other = gr.Textbox(label="If Other, please describe", placeholder="Describe muscle tone and strength", visible=False)
muscle_tone_choice.change(fn=update_visibility, inputs=muscle_tone_choice, outputs=muscle_tone_other)
coordination_choice = gr.Radio(label="Coordination", choices=["Normal", "Impaired", "Other"], value="Normal")
coordination_other = gr.Textbox(label="If Other, please describe", placeholder="Describe coordination", visible=False)
coordination_choice.change(fn=update_visibility, inputs=coordination_choice, outputs=coordination_other)
balance_choice = gr.Radio(label="Balance", choices=["Stable", "Impaired", "Other"], value="Stable")
balance_other = gr.Textbox(label="If Other, please describe", placeholder="Describe balance", visible=False)
balance_choice.change(fn=update_visibility, inputs=balance_choice, outputs=balance_other)
sight_hearing_choice = gr.Radio(label="Sense of sight and hearing", choices=["Normal", "Impaired", "Other"], value="Normal")
sight_hearing_other = gr.Textbox(label="If Other, please describe", placeholder="Describe any issues", visible=False)
sight_hearing_choice.change(fn=update_visibility, inputs=sight_hearing_choice, outputs=sight_hearing_other)
# Section V: Detailed Cognitive & Functional Assessment
with gr.Column():
gr.Markdown("#### Section V: Detailed Cognitive & Functional Assessment")
gr.Markdown("**A. Memory**")
mem_diff_recent = gr.Radio(label="Do you have difficulty remembering recent events?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
mem_forget_appointments = gr.Radio(label="Do you forget appointments or important dates more often than before?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
mem_repeat = gr.Radio(label="Do you repeat questions or statements during a conversation?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
mem_learning = gr.Radio(label="Do you have trouble learning new information?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
gr.Markdown("**B. Language**")
lang_find_words = gr.Radio(label="Do you have trouble finding the right words to express yourself?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
lang_understand = gr.Radio(label="Do you have difficulty understanding what people are saying?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
lang_follow = gr.Radio(label="Do you have trouble following conversations?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
gr.Markdown("**C. Executive Function**")
exec_plan = gr.Radio(label="Do you have difficulty planning and organizing tasks?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
exec_decide = gr.Radio(label="Do you have trouble making decisions or solving problems?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
exec_finance = gr.Radio(label="Do you find it hard to manage your finances?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
gr.Markdown("**D. Visuospatial Skills**")
visuospatial_judge = gr.Radio(label="Do you have difficulty judging distances?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
visuospatial_navigate = gr.Radio(label="Do you have trouble finding your way around familiar places?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
visuospatial_recognize = gr.Radio(label="Do you have trouble recognizing faces?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
gr.Markdown("**E. Attention and Concentration**")
attention_focus = gr.Radio(label="Do you have difficulty focusing your attention?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
attention_distracted = gr.Radio(label="Are you easily distracted?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
attention_instructions = gr.Radio(label="Do you have trouble following instructions?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
gr.Markdown("**F. Functional Abilities**")
func_ADL = gr.Radio(label="Do you need assistance with activities of daily living (bathing, dressing, eating)?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
func_medications = gr.Radio(label="Do you have difficulty managing your medications?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
func_transport = gr.Radio(label="Do you have difficulty driving or using public transportation?", choices=["Not at all", "Mildly", "Moderately", "Severely"])
# Section VI: Behavioral and Emotional Changes
with gr.Column():
gr.Markdown("#### Section VI: Behavioral and Emotional Changes")
behavior_mood_change = gr.Radio(label="Have you noticed any changes in your mood or personality?", choices=["Yes", "No"])
behavior_mood_change_desc = gr.Textbox(label="If Yes, please describe", lines=3, placeholder="Describe changes")
behavior_anxiety = gr.Radio(label="Do you feel more anxious or depressed than usual?", choices=["Yes", "No"])
behavior_irritability = gr.Radio(label="Are you more irritable or agitated than usual?", choices=["Yes", "No"])
behavior_loss_interest = gr.Radio(label="Have you lost interest in activities you used to enjoy?", choices=["Yes", "No"])
# Section VII: Additional Comments
with gr.Column():
gr.Markdown("#### Section VII: Additional Comments")
additional_comments = gr.Textbox(label="Please provide any additional comments", lines=3, placeholder="Enter additional comments here")
# Section G: Blood-Based Biomarkers
with gr.Column():
gr.Markdown("#### Section G: Blood-Based Biomarkers")
p_tau217 = gr.Textbox(label="p-tau217 (pg/mL)", placeholder="Enter value")
abeta42 = gr.Textbox(label="Aβ42 (pg/mL)", placeholder="Enter value")
abeta40 = gr.Textbox(label="Aβ40 (pg/mL)", placeholder="Enter value")
miRNAs = gr.Textbox(label="miRNAs (List with values)", lines=2, placeholder="e.g., miR-1: 2.5, miR-2: 3.0")
# Section H: Basic Cognitive & Functional Assessment Scores
with gr.Column():
gr.Markdown("#### Section H: Basic Cognitive & Functional Assessment Scores")
mmse = gr.Textbox(label="MMSE Score", placeholder="Enter MMSE score")
adas_cog = gr.Textbox(label="ADAS-Cog Score", placeholder="Enter ADAS-Cog score")
faq = gr.Textbox(label="FAQ Score", placeholder="Enter FAQ score")
ravlt = gr.Textbox(label="RAVLT Score", placeholder="Enter RAVLT score")
# Section: Upload PDF Report for additional details
with gr.Column():
gr.Markdown("#### Additional Document (Optional)")
pdf_report = gr.File(label="Upload PDF Report (optional)", file_types=['.pdf'])
predict_btn_no_mri = gr.Button("Predict Alzheimer's Risk")
output_no_mri = gr.Textbox(label="Prediction Result", lines=35)
predict_btn_no_mri.click(
fn=predict_without_mri,
inputs=[
age, gender, ethnicity, education, pincode, mobile,
family_history, family_relationship, conditions, medications,
basic_memory_changes, basic_memory_desc, basic_difficulty_recent,
basic_trouble_words, basic_problem_solving, basic_trouble_appointments,
basic_changes_reaction, basic_driving_concern,
smoking_status, alcohol_consumption, physical_activity,
reflexes_choice, reflexes_other,
muscle_tone_choice, muscle_tone_other,
coordination_choice, coordination_other,
balance_choice, balance_other,
sight_hearing_choice, sight_hearing_other,
mem_diff_recent, mem_forget_appointments, mem_repeat, mem_learning,
lang_find_words, lang_understand, lang_follow,
exec_plan, exec_decide, exec_finance,
visuospatial_judge, visuospatial_navigate, visuospatial_recognize,
attention_focus, attention_distracted, attention_instructions,
func_ADL, func_medications, func_transport,
behavior_mood_change, behavior_mood_change_desc, behavior_anxiety, behavior_irritability, behavior_loss_interest,
additional_comments,
p_tau217, abeta42, abeta40, miRNAs,
mmse, adas_cog, faq, ravlt,
pdf_report
],
outputs=output_no_mri
)
###########################
# Tab: With MRI Image #
###########################
with gr.Tab("With MRI Image"):
gr.Markdown("# ADAP System : Alzheimer Detection, Assessment & Prediction System")
gr.Markdown("### With MRI Data: Upload an MRI scan and provide your demographic details")
with gr.Row():
image_input = gr.Image(label="Upload MRI Scan", type="pil")
age_input = gr.Number(label="Age (years)", value=65)
gender_input = gr.Radio(label="Gender", choices=["Male", "Female", "Other"], value="Male")
ethnicity_input = gr.Textbox(label="Ethnicity", placeholder="Enter your ethnicity")
predict_button = gr.Button("Predict Alzheimer's")
output_box = gr.Textbox(label="Prediction Result", lines=8)
predict_button.click(fn=predict_alzheimer, inputs=[image_input, age_input, gender_input, ethnicity_input], outputs=output_box)
# Launch the Gradio app
demo.launch()
|