Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,9 +1,6 @@
|
|
| 1 |
-
# app.py (Definitive Final Version with Syntax Fix)
|
| 2 |
-
|
| 3 |
import gradio as gr
|
| 4 |
from pathlib import Path
|
| 5 |
import asyncio
|
| 6 |
-
from PIL import Image
|
| 7 |
|
| 8 |
# Import backend components
|
| 9 |
from app.prediction import PredictionPipeline
|
|
@@ -14,45 +11,26 @@ prediction_pipeline = PredictionPipeline()
|
|
| 14 |
SAMPLE_IMAGE_DIR = Path("sample_images")
|
| 15 |
try:
|
| 16 |
if SAMPLE_IMAGE_DIR.is_dir():
|
| 17 |
-
|
|
|
|
| 18 |
else: raise FileNotFoundError
|
| 19 |
except FileNotFoundError:
|
| 20 |
-
print("Warning: 'sample_images' directory not found.");
|
| 21 |
|
| 22 |
# --- Core Logic Functions (Unchanged) ---
|
| 23 |
-
async def process_analysis(patient_name, patient_age, image_list
|
| 24 |
-
if not
|
| 25 |
-
|
| 26 |
-
if not image_list:
|
| 27 |
-
raise gr.Error("At least one image is required.")
|
| 28 |
-
|
| 29 |
result = prediction_pipeline.predict(image_list)
|
| 30 |
-
if "error" in result:
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
final_pred =
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
if not is_sample:
|
| 37 |
-
await add_patient_record(str(patient_name), int(patient_age), final_pred, final_conf)
|
| 38 |
-
|
| 39 |
-
confidences = {"NORMAL": 0.0, "PNEUMONIA": 0.0}
|
| 40 |
-
confidences[final_pred] = final_conf
|
| 41 |
-
confidences["NORMAL" if final_pred == "PNEUMONIA" else "PNEUMONIA"] = 1 - final_conf
|
| 42 |
-
|
| 43 |
-
return [
|
| 44 |
-
gr.update(visible=False),
|
| 45 |
-
gr.update(visible=True),
|
| 46 |
-
gr.update(value=result["watermarked_images"]),
|
| 47 |
-
gr.update(value=confidences)
|
| 48 |
-
]
|
| 49 |
-
|
| 50 |
async def refresh_history_table():
|
| 51 |
records = await get_all_records()
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
data_for_df = [[r.get('name'), r.get('age'), r.get('prediction_result'), f"{r.get('confidence_score', 0):.2%}", r.get('timestamp').strftime('%Y-%m-%d %H:%M')] for r in records]
|
| 55 |
-
return gr.update(value=data_for_df)
|
| 56 |
|
| 57 |
# --- Gradio UI Definition ---
|
| 58 |
css = """
|
|
@@ -66,10 +44,10 @@ css = """
|
|
| 66 |
#main_container { gap: 2rem; max-width: 900px; margin: 0 auto; }
|
| 67 |
#results_gallery .gallery-item { padding: 0.25rem !important; background-color: #374151; border: 1px solid #374151 !important; }
|
| 68 |
#bottom_controls { max-width: 500px; margin: 2.5rem auto 1rem auto; }
|
|
|
|
| 69 |
"""
|
| 70 |
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="blue"), css=css, title="Pneumonia Detection AI") as demo:
|
| 71 |
|
| 72 |
-
# --- UI Layout (Unchanged) ---
|
| 73 |
with gr.Column() as main_app:
|
| 74 |
with gr.Column(elem_id="app_header"):
|
| 75 |
gr.Markdown("# 🩺 Pneumonia Detection AI", elem_id="app_title")
|
|
@@ -90,9 +68,24 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="blue")
|
|
| 90 |
with gr.Row():
|
| 91 |
submit_analysis_btn = gr.Button("Analyze Images", variant="primary")
|
| 92 |
cancel_btn = gr.Button("Cancel", variant="stop")
|
|
|
|
|
|
|
| 93 |
with gr.Column(elem_id="bottom_controls"):
|
| 94 |
with gr.Accordion("About this Tool", open=False):
|
| 95 |
-
gr.Markdown(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
with gr.Row():
|
| 97 |
samples_btn = gr.Button("Try Sample Images")
|
| 98 |
history_btn = gr.Button("View Patient History")
|
|
@@ -106,14 +99,21 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="blue")
|
|
| 106 |
|
| 107 |
with gr.Column(visible=False) as samples_page:
|
| 108 |
gr.Markdown("# 🖼️ Sample Image Library", elem_classes="app_title")
|
| 109 |
-
gr.Markdown("
|
| 110 |
-
sample_gallery = gr.Gallery(value=SAMPLE_IMAGES, label="Sample Images", columns=5, height=400, allow_preview=True, elem_id="sample_gallery")
|
| 111 |
-
hidden_sample_analyze_btn = gr.Button("Analyze Sample", visible=False)
|
| 112 |
back_to_main_btn_samp = gr.Button("⬅️ Back to Main App")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
-
# --- Event Handling Logic ---
|
| 115 |
-
|
| 116 |
-
# ... (upload, modal, start over handlers are correct)
|
| 117 |
def show_patient_info(files): return gr.update(visible=True) if files else gr.update(visible=False)
|
| 118 |
image_input.upload(fn=show_patient_info, inputs=image_input, outputs=patient_info_modal)
|
| 119 |
async def submit_and_hide_modal(name, age, files):
|
|
@@ -121,30 +121,7 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="blue")
|
|
| 121 |
submit_analysis_btn.click(fn=submit_and_hide_modal, inputs=[patient_name_modal, patient_age_modal, image_input], outputs=[uploader_column, results_column, result_images, result_label, patient_info_modal])
|
| 122 |
cancel_btn.click(lambda: (gr.update(visible=False), None), None, [patient_info_modal, image_input])
|
| 123 |
start_over_btn.click(fn=None, js="() => { window.location.reload(); }")
|
| 124 |
-
|
| 125 |
-
# --- SAMPLE PAGE LOGIC (THE DEFINITIVE FIX) ---
|
| 126 |
-
def on_sample_select(evt: gr.SelectData):
|
| 127 |
-
return evt.value
|
| 128 |
-
|
| 129 |
-
sample_gallery.select(
|
| 130 |
-
fn=on_sample_select,
|
| 131 |
-
inputs=None, # The event data is passed automatically
|
| 132 |
-
outputs=[hidden_sample_analyze_btn]
|
| 133 |
-
)
|
| 134 |
-
|
| 135 |
-
async def handle_sample_analysis(selected_image_path: str):
|
| 136 |
-
if not selected_image_path:
|
| 137 |
-
raise gr.Error("Sample image path is missing.")
|
| 138 |
-
analysis_results = await process_analysis("Sample User", 0, [selected_image_path], is_sample=True)
|
| 139 |
-
return [gr.update(visible=True), gr.update(visible=False), *analysis_results]
|
| 140 |
-
|
| 141 |
-
hidden_sample_analyze_btn.click(
|
| 142 |
-
fn=handle_sample_analysis,
|
| 143 |
-
inputs=[hidden_sample_analyze_btn],
|
| 144 |
-
outputs=[main_app, samples_page, uploader_column, results_column, result_images, result_label]
|
| 145 |
-
)
|
| 146 |
|
| 147 |
-
# --- Page Navigation ---
|
| 148 |
all_pages = [main_app, history_page, samples_page]
|
| 149 |
async def show_history_page_and_refresh(): records_update = await refresh_history_table(); return [gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), records_update]
|
| 150 |
def show_samples_page(): return [gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)]
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from pathlib import Path
|
| 3 |
import asyncio
|
|
|
|
| 4 |
|
| 5 |
# Import backend components
|
| 6 |
from app.prediction import PredictionPipeline
|
|
|
|
| 11 |
SAMPLE_IMAGE_DIR = Path("sample_images")
|
| 12 |
try:
|
| 13 |
if SAMPLE_IMAGE_DIR.is_dir():
|
| 14 |
+
NORMAL_SAMPLES = [str(p) for p in sorted(list((SAMPLE_IMAGE_DIR / 'NORMAL').glob('*.jpeg')))]
|
| 15 |
+
PNEUMONIA_SAMPLES = [str(p) for p in sorted(list((SAMPLE_IMAGE_DIR / 'PNEUMONIA').glob('*.jpeg')))]
|
| 16 |
else: raise FileNotFoundError
|
| 17 |
except FileNotFoundError:
|
| 18 |
+
print("Warning: 'sample_images' directory not found."); NORMAL_SAMPLES, PNEUMONIA_SAMPLES = [], []
|
| 19 |
|
| 20 |
# --- Core Logic Functions (Unchanged) ---
|
| 21 |
+
async def process_analysis(patient_name, patient_age, image_list):
|
| 22 |
+
if not patient_name or patient_age is None: raise gr.Error("Patient Name and Age are required.")
|
| 23 |
+
if not image_list: raise gr.Error("At least one image is required.")
|
|
|
|
|
|
|
|
|
|
| 24 |
result = prediction_pipeline.predict(image_list)
|
| 25 |
+
if "error" in result: raise gr.Error(result.get("details", result["error"]))
|
| 26 |
+
final_pred, final_conf = result["final_prediction"], result["final_confidence"]
|
| 27 |
+
await add_patient_record(str(patient_name), int(patient_age), final_pred, final_conf)
|
| 28 |
+
confidences = {"NORMAL": 0.0, "PNEUMONIA": 0.0}; confidences[final_pred] = final_conf; confidences["NORMAL" if final_pred == "PNEUMONIA" else "PNEUMONIA"] = 1 - final_conf
|
| 29 |
+
return [gr.update(visible=False), gr.update(visible=True), gr.update(value=result["watermarked_images"]), gr.update(value=confidences)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
async def refresh_history_table():
|
| 31 |
records = await get_all_records()
|
| 32 |
+
data = [[r.get('name'), r.get('age'), r.get('prediction_result'), f"{r.get('confidence_score', 0):.2%}", r.get('timestamp').strftime('%Y-%m-%d %H:%M')] for r in records] if records else []
|
| 33 |
+
return gr.update(value=data)
|
|
|
|
|
|
|
| 34 |
|
| 35 |
# --- Gradio UI Definition ---
|
| 36 |
css = """
|
|
|
|
| 44 |
#main_container { gap: 2rem; max-width: 900px; margin: 0 auto; }
|
| 45 |
#results_gallery .gallery-item { padding: 0.25rem !important; background-color: #374151; border: 1px solid #374151 !important; }
|
| 46 |
#bottom_controls { max-width: 500px; margin: 2.5rem auto 1rem auto; }
|
| 47 |
+
#bottom_controls .gr-accordion > .gr-block-label { text-align: center !important; display: block !important; }
|
| 48 |
"""
|
| 49 |
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="blue"), css=css, title="Pneumonia Detection AI") as demo:
|
| 50 |
|
|
|
|
| 51 |
with gr.Column() as main_app:
|
| 52 |
with gr.Column(elem_id="app_header"):
|
| 53 |
gr.Markdown("# 🩺 Pneumonia Detection AI", elem_id="app_title")
|
|
|
|
| 68 |
with gr.Row():
|
| 69 |
submit_analysis_btn = gr.Button("Analyze Images", variant="primary")
|
| 70 |
cancel_btn = gr.Button("Cancel", variant="stop")
|
| 71 |
+
|
| 72 |
+
# --- "About" Section (RESTORED) ---
|
| 73 |
with gr.Column(elem_id="bottom_controls"):
|
| 74 |
with gr.Accordion("About this Tool", open=False):
|
| 75 |
+
gr.Markdown(
|
| 76 |
+
"""
|
| 77 |
+
### MLOps-Powered Pneumonia Detection
|
| 78 |
+
This application demonstrates a complete, end-to-end MLOps pipeline for medical image classification. It leverages a state-of-the-art **Vision Transformer (ViT)** model, fine-tuned on a public dataset of chest X-ray images to distinguish between Normal and Pneumonia cases.
|
| 79 |
+
|
| 80 |
+
**Disclaimer:** This tool is for demonstration and educational purposes only and is **not a substitute for professional medical advice.**
|
| 81 |
+
|
| 82 |
+
---
|
| 83 |
+
|
| 84 |
+
**Project Team:**
|
| 85 |
+
* **Alyyan Ahmed** - ML Engineer & Developer
|
| 86 |
+
* **Munim Akbar** - ML Engineer & Developer
|
| 87 |
+
"""
|
| 88 |
+
)
|
| 89 |
with gr.Row():
|
| 90 |
samples_btn = gr.Button("Try Sample Images")
|
| 91 |
history_btn = gr.Button("View Patient History")
|
|
|
|
| 99 |
|
| 100 |
with gr.Column(visible=False) as samples_page:
|
| 101 |
gr.Markdown("# 🖼️ Sample Image Library", elem_classes="app_title")
|
| 102 |
+
gr.Markdown("You can download these sample images to test the tool on the main page.")
|
|
|
|
|
|
|
| 103 |
back_to_main_btn_samp = gr.Button("⬅️ Back to Main App")
|
| 104 |
+
|
| 105 |
+
with gr.Row():
|
| 106 |
+
with gr.Column():
|
| 107 |
+
gr.Markdown("### Normal Cases")
|
| 108 |
+
for img_path in NORMAL_SAMPLES:
|
| 109 |
+
gr.File(value=img_path, label=Path(img_path).name, interactive=False)
|
| 110 |
+
|
| 111 |
+
with gr.Column():
|
| 112 |
+
gr.Markdown("### Pneumonia Cases")
|
| 113 |
+
for img_path in PNEUMONIA_SAMPLES:
|
| 114 |
+
gr.File(value=img_path, label=Path(img_path).name, interactive=False)
|
| 115 |
|
| 116 |
+
# --- Event Handling Logic (Unchanged and Correct) ---
|
|
|
|
|
|
|
| 117 |
def show_patient_info(files): return gr.update(visible=True) if files else gr.update(visible=False)
|
| 118 |
image_input.upload(fn=show_patient_info, inputs=image_input, outputs=patient_info_modal)
|
| 119 |
async def submit_and_hide_modal(name, age, files):
|
|
|
|
| 121 |
submit_analysis_btn.click(fn=submit_and_hide_modal, inputs=[patient_name_modal, patient_age_modal, image_input], outputs=[uploader_column, results_column, result_images, result_label, patient_info_modal])
|
| 122 |
cancel_btn.click(lambda: (gr.update(visible=False), None), None, [patient_info_modal, image_input])
|
| 123 |
start_over_btn.click(fn=None, js="() => { window.location.reload(); }")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
|
|
|
| 125 |
all_pages = [main_app, history_page, samples_page]
|
| 126 |
async def show_history_page_and_refresh(): records_update = await refresh_history_table(); return [gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), records_update]
|
| 127 |
def show_samples_page(): return [gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)]
|