wanhanisah commited on
Commit
35c5863
·
verified ·
1 Parent(s): c4bad48

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +9 -32
app.py CHANGED
@@ -6,7 +6,6 @@ import zipfile
6
  import tempfile
7
  from pathlib import Path
8
  from typing import Optional, List, Dict
9
- import shutil # <-- added for optional local copy
10
 
11
  import numpy as np
12
  import pandas as pd
@@ -26,6 +25,7 @@ from utils.layer_util import ResizeAndConcatenate
26
  # Config / paths
27
  # =========================
28
  os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
 
29
  # os.environ["CUDA_VISIBLE_DEVICES"] = ""
30
 
31
  MODEL_PATH = "./models_final/SEG459.h5"
@@ -434,7 +434,7 @@ def process_nifti_case(nifti_path: str, model, rows_acc: List[Dict], per_frame_r
434
  per_frame_df.insert(0, "Patient_ID", pid)
435
  per_frame_rows_acc.append(per_frame_df)
436
 
437
- # Append summary row BEFORE any UI drawing
438
  rows_acc.append({
439
  'Patient_ID': pid,
440
  'EDV_uL': EDV_uL,
@@ -450,9 +450,10 @@ def process_nifti_case(nifti_path: str, model, rows_acc: List[Dict], per_frame_r
450
  'PixelSpacing_col_mm': spacing['col_mm'],
451
  })
452
 
453
- # GIF: ED vs ES (slices animate)
454
  gif_path = gif_animation_for_patient_pred_only(imgs_4d, preds_4d, pid, ed_idx, es_idx, GIFS_DIR)
455
  try:
 
456
  st.image(gif_path, caption="Generated GIF", use_column_width=True)
457
  except TypeError:
458
  st.image(gif_path, caption="Generated GIF")
@@ -477,20 +478,8 @@ def main():
477
  if uploaded_zip is None:
478
  st.stop()
479
 
480
- # --- Save options UI (filename + optional local copy) ---
481
- st.subheader("Save options")
482
- csv_download_name = st.text_input("CSV file name (for browser download)", "Results.csv")
483
- st.caption("Tip: To choose a folder on download, enable your browser setting “Ask where to save each file before downloading.”")
484
-
485
- save_local_copy = st.checkbox("Also save a copy to a specific path on this machine (advanced)")
486
- local_dir = ""
487
- if save_local_copy:
488
- local_dir = st.text_input("Local directory path (only works on the machine running Streamlit)", os.path.expanduser("~"))
489
-
490
  if st.button("Process Data"):
491
- # Show real uploaded ZIP name in spinner
492
- zip_label = getattr(uploaded_zip, "name", "ZIP file")
493
- with st.spinner(f"Processing {zip_label}..."):
494
  # Save & extract
495
  tmpdir = tempfile.mkdtemp()
496
  zpath = os.path.join(tmpdir, "upload.zip")
@@ -514,7 +503,7 @@ def main():
514
  model = keras.models.load_model(
515
  MODEL_PATH,
516
  custom_objects={
517
- 'focal_tversky_loss': None,
518
  'dice_coef_no_bkg': None,
519
  'ResizeAndConcatenate': ResizeAndConcatenate,
520
  'dice_myo': None,
@@ -534,28 +523,16 @@ def main():
534
  except Exception as e:
535
  st.warning(f"Failed: {Path(fp).name} — {e}")
536
 
537
- # Write merged CSV
538
  csv_path = write_all_in_one_csv(rows, per_frame_rows, CSV_DIR)
539
  st.success(f"Processed {len(rows)} NIfTI file(s).")
540
-
541
- # Browser download (browser decides save location; filename is set)
542
  with open(csv_path, "rb") as f:
543
  st.download_button(
544
  label="Download CSV",
545
  data=f,
546
- file_name=csv_download_name,
547
  mime="text/csv"
548
  )
549
 
550
- # Optional local copy (server filesystem)
551
- if save_local_copy and local_dir.strip():
552
- try:
553
- os.makedirs(local_dir, exist_ok=True)
554
- dest = os.path.join(local_dir, csv_download_name)
555
- shutil.copyfile(csv_path, dest)
556
- st.success(f"Saved CSV to: {dest}")
557
- except Exception as e:
558
- st.error(f"Could not save CSV: {e}")
559
-
560
  if __name__ == "__main__":
561
- main()
 
6
  import tempfile
7
  from pathlib import Path
8
  from typing import Optional, List, Dict
 
9
 
10
  import numpy as np
11
  import pandas as pd
 
25
  # Config / paths
26
  # =========================
27
  os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
28
+ # Uncomment next line to force CPU only
29
  # os.environ["CUDA_VISIBLE_DEVICES"] = ""
30
 
31
  MODEL_PATH = "./models_final/SEG459.h5"
 
434
  per_frame_df.insert(0, "Patient_ID", pid)
435
  per_frame_rows_acc.append(per_frame_df)
436
 
437
+ # -------- Append summary row BEFORE any UI drawing (so UI errors don't drop data)
438
  rows_acc.append({
439
  'Patient_ID': pid,
440
  'EDV_uL': EDV_uL,
 
450
  'PixelSpacing_col_mm': spacing['col_mm'],
451
  })
452
 
453
+ # GIF: ED vs ES (slices animate) — non-fatal display
454
  gif_path = gif_animation_for_patient_pred_only(imgs_4d, preds_4d, pid, ed_idx, es_idx, GIFS_DIR)
455
  try:
456
+ # Streamlit uses 'use_column_width'; keep it, but guard against TypeError on older builds
457
  st.image(gif_path, caption="Generated GIF", use_column_width=True)
458
  except TypeError:
459
  st.image(gif_path, caption="Generated GIF")
 
478
  if uploaded_zip is None:
479
  st.stop()
480
 
 
 
 
 
 
 
 
 
 
 
481
  if st.button("Process Data"):
482
+ with st.spinner("Processing ZIP..."):
 
 
483
  # Save & extract
484
  tmpdir = tempfile.mkdtemp()
485
  zpath = os.path.join(tmpdir, "upload.zip")
 
503
  model = keras.models.load_model(
504
  MODEL_PATH,
505
  custom_objects={
506
+ 'focal_tversky_loss': None, # loss/metrics not needed for inference
507
  'dice_coef_no_bkg': None,
508
  'ResizeAndConcatenate': ResizeAndConcatenate,
509
  'dice_myo': None,
 
523
  except Exception as e:
524
  st.warning(f"Failed: {Path(fp).name} — {e}")
525
 
526
+ # Write merged CSV and show download
527
  csv_path = write_all_in_one_csv(rows, per_frame_rows, CSV_DIR)
528
  st.success(f"Processed {len(rows)} NIfTI file(s).")
 
 
529
  with open(csv_path, "rb") as f:
530
  st.download_button(
531
  label="Download CSV",
532
  data=f,
533
+ file_name="Results.csv",
534
  mime="text/csv"
535
  )
536
 
 
 
 
 
 
 
 
 
 
 
537
  if __name__ == "__main__":
538
+ main()