ALYYAN commited on
Commit
a658c43
·
unverified ·
1 Parent(s): aef7d82

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -24
app.py CHANGED
@@ -1,27 +1,30 @@
1
- # app.py (Final Version with Checkbox Samples and Watermark Fix)
2
 
3
  import gradio as gr
4
  from pathlib import Path
5
- from huggingface_hub import snapshot_download
6
  import asyncio
 
7
 
8
  from app.prediction import PredictionPipeline
9
  from app.database import add_patient_record, get_all_records
10
 
11
  # --- Initialization ---
12
  prediction_pipeline = PredictionPipeline()
13
- HF_DATASET_REPO = "ALYYAN/chest-xray-pneumonia-samples"
 
14
  try:
15
- SAMPLE_IMAGE_DIR = Path(snapshot_download(repo_id=HF_DATASET_REPO, repo_type="dataset"))
16
- SAMPLE_IMAGES = [str(p) for p in list(SAMPLE_IMAGE_DIR.glob('*/*.jpeg'))]
17
- except Exception as e:
18
- print(f"Could not download sample images: {e}")
 
19
  SAMPLE_IMAGES = []
20
 
21
- # --- Core Logic (Async Functions - Unchanged) ---
 
22
  async def process_analysis(patient_name, patient_age, image_list, is_sample=False):
23
  # ... (code is the same)
24
- if not is_sample and (not patient_name or patient_age is None or str(patient_age).strip() == ""): raise gr.Error("Patient Name and Age are required.")
25
  if not image_list: raise gr.Error("At least one image is required.")
26
  result = prediction_pipeline.predict(image_list)
27
  if "error" in result: raise gr.Error(result["error"])
@@ -29,6 +32,7 @@ async def process_analysis(patient_name, patient_age, image_list, is_sample=Fals
29
  if not is_sample: await add_patient_record(str(patient_name), int(patient_age), final_pred, final_conf)
30
  confidences = {"NORMAL": 0.0, "PNEUMONIA": 0.0}; confidences[final_pred] = final_conf; confidences["NORMAL" if final_pred == "PNEUMONIA" else "PNEUMONIA"] = 1 - final_conf
31
  return [gr.update(visible=False), gr.update(visible=True), gr.update(value=result["watermarked_images"]), gr.update(value=confidences)]
 
32
  async def refresh_history_table():
33
  # ... (code is the same)
34
  records = await get_all_records()
@@ -90,16 +94,18 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="blue")
90
  refresh_history_btn = gr.Button("Refresh History")
91
  history_df = gr.DataFrame(headers=["Name", "Age", "Prediction", "Confidence", "Date"], row_count=10, interactive=False)
92
 
93
- # --- SAMPLES PAGE (THE FIX) ---
94
  with gr.Column(visible=False) as samples_page:
95
  gr.Markdown("# 🖼️ Sample Image Library", elem_classes="app_title")
96
- gr.Markdown("Select up to 3 images, then click 'Analyze Selected Samples'.")
97
 
98
- # Use a CheckboxGroup with images as choices
99
  sample_checkboxes = gr.CheckboxGroup(
100
  label="Sample Images",
101
- choices=[(Image.open(p), p) for p in SAMPLE_IMAGES], # Tuple of (PIL Image for display, path for value)
102
- type="value"
 
 
103
  )
104
 
105
  with gr.Row():
@@ -108,7 +114,7 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="blue")
108
 
109
  # --- Event Handling Logic ---
110
 
111
- # ... (upload, modal, start_over handlers are correct)
112
  def show_patient_info(files): return gr.update(visible=True) if files else gr.update(visible=False)
113
  image_input.upload(fn=show_patient_info, inputs=image_input, outputs=patient_info_modal)
114
  async def submit_and_hide_modal(name, age, files):
@@ -126,15 +132,12 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="blue")
126
 
127
  analysis_results = await process_analysis("Sample User", 0, selected_images, is_sample=True)
128
 
129
- return {
130
- main_app: gr.update(visible=True),
131
- samples_page: gr.update(visible=False),
132
- # Unpack dictionary updates for specific components
133
- uploader_column: analysis_results[0],
134
- results_column: analysis_results[1],
135
- result_images: analysis_results[2],
136
- result_label: analysis_results[3],
137
- }
138
  analyze_samples_btn.click(fn=handle_sample_analysis, inputs=[sample_checkboxes], outputs=[main_app, samples_page, uploader_column, results_column, result_images, result_label])
139
 
140
  # ... (Page Navigation is correct)
 
1
+ # app.py (Final Version with Local Samples, Checkbox Selector, and UI Fixes)
2
 
3
  import gradio as gr
4
  from pathlib import Path
 
5
  import asyncio
6
+ from PIL import Image
7
 
8
  from app.prediction import PredictionPipeline
9
  from app.database import add_patient_record, get_all_records
10
 
11
  # --- Initialization ---
12
  prediction_pipeline = PredictionPipeline()
13
+ # --- FIX: Point to the locally cloned sample images directory from setup.sh ---
14
+ SAMPLE_IMAGE_DIR = Path("sample_images")
15
  try:
16
+ SAMPLE_IMAGES = [str(p) for p in sorted(list(SAMPLE_IMAGE_DIR.glob('*/*.jpeg')))]
17
+ if not SAMPLE_IMAGES:
18
+ raise FileNotFoundError
19
+ except FileNotFoundError:
20
+ print("Warning: 'sample_images' directory not found or is empty. Samples will be unavailable.")
21
  SAMPLE_IMAGES = []
22
 
23
+
24
+ # --- Core Logic Functions (Unchanged and Correct) ---
25
  async def process_analysis(patient_name, patient_age, image_list, is_sample=False):
26
  # ... (code is the same)
27
+ if not is_sample and (not patient_name or patient_age is None): raise gr.Error("Patient Name and Age are required.")
28
  if not image_list: raise gr.Error("At least one image is required.")
29
  result = prediction_pipeline.predict(image_list)
30
  if "error" in result: raise gr.Error(result["error"])
 
32
  if not is_sample: await add_patient_record(str(patient_name), int(patient_age), final_pred, final_conf)
33
  confidences = {"NORMAL": 0.0, "PNEUMONIA": 0.0}; confidences[final_pred] = final_conf; confidences["NORMAL" if final_pred == "PNEUMONIA" else "PNEUMONIA"] = 1 - final_conf
34
  return [gr.update(visible=False), gr.update(visible=True), gr.update(value=result["watermarked_images"]), gr.update(value=confidences)]
35
+
36
  async def refresh_history_table():
37
  # ... (code is the same)
38
  records = await get_all_records()
 
94
  refresh_history_btn = gr.Button("Refresh History")
95
  history_df = gr.DataFrame(headers=["Name", "Age", "Prediction", "Confidence", "Date"], row_count=10, interactive=False)
96
 
97
+ # --- SAMPLES PAGE (THE DEFINITIVE FIX) ---
98
  with gr.Column(visible=False) as samples_page:
99
  gr.Markdown("# 🖼️ Sample Image Library", elem_classes="app_title")
100
+ gr.Markdown("Select up to 3 images, then click 'Analyze'.")
101
 
102
+ # Use a CheckboxGroup with images for selection
103
  sample_checkboxes = gr.CheckboxGroup(
104
  label="Sample Images",
105
+ # A choice is a tuple: (Image for display, file path for value)
106
+ choices=[(Image.open(p), p) for p in SAMPLE_IMAGES],
107
+ type="value",
108
+ elem_id="sample_gallery" # Use the gallery CSS
109
  )
110
 
111
  with gr.Row():
 
114
 
115
  # --- Event Handling Logic ---
116
 
117
+ # ... (upload, modal, start over handlers are correct)
118
  def show_patient_info(files): return gr.update(visible=True) if files else gr.update(visible=False)
119
  image_input.upload(fn=show_patient_info, inputs=image_input, outputs=patient_info_modal)
120
  async def submit_and_hide_modal(name, age, files):
 
132
 
133
  analysis_results = await process_analysis("Sample User", 0, selected_images, is_sample=True)
134
 
135
+ # Return updates to show the results on the main page and hide this page
136
+ return [
137
+ gr.update(visible=True), # main_app
138
+ gr.update(visible=False), # samples_page
139
+ *analysis_results
140
+ ]
 
 
 
141
  analyze_samples_btn.click(fn=handle_sample_analysis, inputs=[sample_checkboxes], outputs=[main_app, samples_page, uploader_column, results_column, result_images, result_label])
142
 
143
  # ... (Page Navigation is correct)