cleaned code
Browse filesFiles changed (5)
- S2FApp/app.py+27-32
- S2FApp/predictor.py+3-6
- S2FApp/ui/components.py+2-15
- S2FApp/utils/paths.pyAdded+17
- S2FApp/utils/report.py+9-7
19 unmodified lines2021222324256 unmodified lines323334353637383940414230 unmodified lines73747576777844 unmodified lines12312412512612712812913013113213345 unmodified lines17918018118218318418579 unmodified lines26526626726826927027173 unmodified lines34534634734834935035135235335435535635735835936012 unmodified lines37337437537637737837938038138238338438538638738819 unmodified linesMODEL_TYPE_LABELS,SAMPLE_EXTENSIONS,)from utils.segmentation import estimate_cell_maskfrom utils.substrate_settings import list_substratesfrom utils.display import apply_display_scale6 unmodified linesHAS_DRAWABLE_CANVAS,)try:from streamlit_drawable_canvas import st_canvasexcept (ImportError, AttributeError):pass # HAS_DRAWABLE_CANVAS from ui.componentsCITATION = ("Lautaro Baro, Kaveh Shahhosseini, Amparo Andrés-Bordería, Claudio Angione, and Maria Angeles Juanes. ""**\"Shape-to-force (S2F): Predicting Cell Traction Forces from LabelFree Imaging\"**, 2026."30 unmodified linesreturn measure_region_dialog if (HAS_DRAWABLE_CANVAS and ST_DIALOG) else Nonest.set_page_config(page_title="Shape2Force (S2F)", page_icon="🦠", layout="centered")# Theme CSS (inject based on sidebar selection)44 unmodified linesst.caption("Predict traction force maps from bright-field microscopy images of cells or spheroids")# Foldersckp_base = os.path.join(S2F_ROOT, "ckp")if not os.path.isdir(ckp_base):project_root = os.path.dirname(S2F_ROOT)if os.path.isdir(os.path.join(project_root, "ckp")):ckp_base = os.path.join(project_root, "ckp")ckp_single_cell = os.path.join(ckp_base, "single_cell")ckp_spheroid = os.path.join(ckp_base, "spheroid")sample_base = os.path.join(S2F_ROOT, "samples")45 unmodified linesckp_files = get_ckp_files_for_model(model_type)ckp_folder = ckp_single_cell if model_type == "single_cell" else ckp_spheroidckp_subfolder_name = "single_cell" if model_type == "single_cell" else "spheroid"if ckp_files:checkpoint = st.selectbox(79 unmodified lineselse:sample_files = get_sample_files_for_model(model_type)sample_folder = sample_single_cell if model_type == "single_cell" else sample_spheroidsample_subfolder_name = "single_cell" if model_type == "single_cell" else "spheroid"if sample_files:selected_sample = st.selectbox(f"Select example image (from `samples/{sample_subfolder_name}/`)",73 unmodified lines"pixel_sum": pixel_sum,"cache_key": cache_key,}st.session_state["measure_raw_heatmap"] = heatmap.copy()st.session_state["measure_display_mode"] = display_modest.session_state["measure_bf_img"] = img.copy()st.session_state["measure_input_filename"] = key_img or "image"st.session_state["measure_original_vals"] = build_original_vals(heatmap, pixel_sum, force)st.session_state["measure_colormap"] = colormap_namecell_mask = estimate_cell_mask(heatmap)st.session_state["measure_auto_cell_on"] = auto_cell_boundaryst.session_state["measure_cell_vals"] = build_cell_vals(heatmap, cell_mask, pixel_sum, force) if auto_cell_boundary else Nonest.session_state["measure_cell_mask"] = cell_mask if auto_cell_boundary else Nonerender_result_display(img, heatmap, display_heatmap, pixel_sum, force, key_img,12 unmodified linesimg, heatmap, force, pixel_sum = r["img"], r["heatmap"], r["force"], r["pixel_sum"]display_heatmap = apply_display_scale(heatmap, display_mode)st.session_state["measure_raw_heatmap"] = heatmap.copy()st.session_state["measure_display_mode"] = display_modest.session_state["measure_bf_img"] = img.copy()st.session_state["measure_input_filename"] = key_img or "image"st.session_state["measure_original_vals"] = build_original_vals(heatmap, pixel_sum, force)st.session_state["measure_colormap"] = colormap_namecell_mask = estimate_cell_mask(heatmap)st.session_state["measure_auto_cell_on"] = auto_cell_boundaryst.session_state["measure_cell_vals"] = build_cell_vals(heatmap, cell_mask, pixel_sum, force) if auto_cell_boundary else Nonest.session_state["measure_cell_mask"] = cell_mask if auto_cell_boundary else Noneif st.session_state.pop("open_measure_dialog", False):measure_region_dialog()19 unmodified lines202122232425266 unmodified lines33343536373830 unmodified lines69707172737475767778798081828384858687888944 unmodified lines13413513613713813914045 unmodified lines18618718818919019119279 unmodified lines27227327427527627727873 unmodified lines35235335435535635735835936036112 unmodified lines37437537637737837938038138238319 unmodified linesMODEL_TYPE_LABELS,SAMPLE_EXTENSIONS,)from utils.paths import get_ckp_base, model_subfolderfrom utils.segmentation import estimate_cell_maskfrom utils.substrate_settings import list_substratesfrom utils.display import apply_display_scale6 unmodified linesHAS_DRAWABLE_CANVAS,)CITATION = ("Lautaro Baro, Kaveh Shahhosseini, Amparo Andrés-Bordería, Claudio Angione, and Maria Angeles Juanes. ""**\"Shape-to-force (S2F): Predicting Cell Traction Forces from LabelFree Imaging\"**, 2026."30 unmodified linesreturn measure_region_dialog if (HAS_DRAWABLE_CANVAS and ST_DIALOG) else Nonedef _populate_measure_session_state(heatmap, img, pixel_sum, force, key_img, colormap_name,display_mode, auto_cell_boundary):"""Populate session state for the measure tool."""cell_mask = estimate_cell_mask(heatmap)st.session_state["measure_raw_heatmap"] = heatmap.copy()st.session_state["measure_display_mode"] = display_modest.session_state["measure_bf_img"] = img.copy()st.session_state["measure_input_filename"] = key_img or "image"st.session_state["measure_original_vals"] = build_original_vals(heatmap, pixel_sum, force)st.session_state["measure_colormap"] = colormap_namest.session_state["measure_auto_cell_on"] = auto_cell_boundaryst.session_state["measure_cell_vals"] = build_cell_vals(heatmap, cell_mask, pixel_sum, force) if auto_cell_boundary else Nonest.session_state["measure_cell_mask"] = cell_mask if auto_cell_boundary else Nonest.set_page_config(page_title="Shape2Force (S2F)", page_icon="🦠", layout="centered")# Theme CSS (inject based on sidebar selection)44 unmodified linesst.caption("Predict traction force maps from bright-field microscopy images of cells or spheroids")# Foldersckp_base = get_ckp_base(S2F_ROOT)ckp_single_cell = os.path.join(ckp_base, "single_cell")ckp_spheroid = os.path.join(ckp_base, "spheroid")sample_base = os.path.join(S2F_ROOT, "samples")45 unmodified linesckp_files = get_ckp_files_for_model(model_type)ckp_folder = ckp_single_cell if model_type == "single_cell" else ckp_spheroidckp_subfolder_name = model_subfolder(model_type)if ckp_files:checkpoint = st.selectbox(79 unmodified lineselse:sample_files = get_sample_files_for_model(model_type)sample_folder = sample_single_cell if model_type == "single_cell" else sample_spheroidsample_subfolder_name = model_subfolder(model_type)if sample_files:selected_sample = st.selectbox(f"Select example image (from `samples/{sample_subfolder_name}/`)",73 unmodified lines"pixel_sum": pixel_sum,"cache_key": cache_key,}_populate_measure_session_state(heatmap, img, pixel_sum, force, key_img, colormap_name,display_mode, auto_cell_boundary,)render_result_display(img, heatmap, display_heatmap, pixel_sum, force, key_img,12 unmodified linesimg, heatmap, force, pixel_sum = r["img"], r["heatmap"], r["force"], r["pixel_sum"]display_heatmap = apply_display_scale(heatmap, display_mode)_populate_measure_session_state(heatmap, img, pixel_sum, force, key_img, colormap_name,display_mode, auto_cell_boundary,)if st.session_state.pop("open_measure_dialog", False):measure_region_dialog()
13 unmodified lines14151617181969 unmodified lines899091929394959697989910013 unmodified linessys.path.insert(0, S2F_ROOT)from models.s2f_model import create_s2f_modelfrom utils.substrate_settings import get_settings_of_category, compute_settings_normalizationfrom utils import config69 unmodified lines"""self.model_type = model_typeself.device = device or ("cuda" if torch.cuda.is_available() else "cpu")ckp_base = os.path.join(S2F_ROOT, "ckp")if not os.path.isdir(ckp_base):project_root = os.path.dirname(S2F_ROOT)if os.path.isdir(os.path.join(project_root, "ckp")):ckp_base = os.path.join(project_root, "ckp")subfolder = "single_cell" if model_type == "single_cell" else "spheroid"ckp_dir = ckp_folder if ckp_folder else os.path.join(ckp_base, subfolder)if not os.path.isdir(ckp_dir):ckp_dir = ckp_base # fallback if subfolders not used13 unmodified lines1415161718192069 unmodified lines909192939495969713 unmodified linessys.path.insert(0, S2F_ROOT)from models.s2f_model import create_s2f_modelfrom utils.paths import get_ckp_base, model_subfolderfrom utils.substrate_settings import get_settings_of_category, compute_settings_normalizationfrom utils import config69 unmodified lines"""self.model_type = model_typeself.device = device or ("cuda" if torch.cuda.is_available() else "cpu")ckp_base = get_ckp_base(S2F_ROOT)subfolder = model_subfolder(model_type)ckp_dir = ckp_folder if ckp_folder else os.path.join(ckp_base, subfolder)if not os.path.isdir(ckp_dir):ckp_dir = ckp_base # fallback if subfolders not used
16 unmodified lines1718192021222378 unmodified lines102103104105106107108109110111112113114115116117118118 unmodified lines23723823924024124224324424516 unmodified linesTOOL_LABELS,)from utils.display import apply_display_scale, cv_colormap_to_plotly_colorscalefrom utils.report import heatmap_to_rgb, heatmap_to_png_bytes, create_pdf_reportfrom utils.segmentation import estimate_cell_masktry:78 unmodified linesreturn ptsdef parse_canvas_shapes_to_mask(json_data, canvas_h, canvas_w, heatmap_h, heatmap_w):"""Parse drawn shapes from streamlit-drawable-canvas json_data and create binary mask (combined)."""masks, _ = parse_canvas_shapes_to_masks(json_data, canvas_h, canvas_w, heatmap_h, heatmap_w)if not masks:return None, 0combined = np.zeros((heatmap_h, heatmap_w), dtype=np.uint8)for m in masks:combined = np.maximum(combined, m)return combined, len(masks)def parse_canvas_shapes_to_masks(json_data, canvas_h, canvas_w, heatmap_h, heatmap_w):"""Parse drawn shapes and return a list of individual masks (one per shape)."""if not json_data or "objects" not in json_data or not json_data["objects"]:118 unmodified lines"""Render drawable canvas and region metrics. When cell_vals: show cell area (replaces Full map). Else: show Full map."""raw_heatmap = raw_heatmap if raw_heatmap is not None else display_heatmaph, w = display_heatmap.shapeheatmap_rgb = heatmap_to_rgb(display_heatmap, colormap_name)if cell_mask is not None and np.any(cell_mask > 0):heatmap_rgb = _draw_contour_on_image(heatmap_rgb.copy(), cell_mask, stroke_color=(255, 0, 0), stroke_width=2)pil_bg = Image.fromarray(heatmap_rgb).resize((CANVAS_SIZE, CANVAS_SIZE), Image.Resampling.LANCZOS)st.markdown("""16 unmodified lines1718192021222378 unmodified lines102103104105106107118 unmodified lines22622722822923023123216 unmodified linesTOOL_LABELS,)from utils.display import apply_display_scale, cv_colormap_to_plotly_colorscalefrom utils.report import heatmap_to_rgb, heatmap_to_rgb_with_contour, heatmap_to_png_bytes, create_pdf_reportfrom utils.segmentation import estimate_cell_masktry:78 unmodified linesreturn ptsdef parse_canvas_shapes_to_masks(json_data, canvas_h, canvas_w, heatmap_h, heatmap_w):"""Parse drawn shapes and return a list of individual masks (one per shape)."""if not json_data or "objects" not in json_data or not json_data["objects"]:118 unmodified lines"""Render drawable canvas and region metrics. When cell_vals: show cell area (replaces Full map). Else: show Full map."""raw_heatmap = raw_heatmap if raw_heatmap is not None else display_heatmaph, w = display_heatmap.shapeheatmap_rgb = heatmap_to_rgb_with_contour(display_heatmap, colormap_name, cell_mask)pil_bg = Image.fromarray(heatmap_rgb).resize((CANVAS_SIZE, CANVAS_SIZE), Image.Resampling.LANCZOS)st.markdown("""
1234567891011121314151617"""Path resolution utilities for S2F App."""import os
def get_ckp_base(root): """Resolve checkpoint base directory (S2FApp/ckp or project/ckp).""" ckp_base = os.path.join(root, "ckp") if not os.path.isdir(ckp_base): project_root = os.path.dirname(root) if os.path.isdir(os.path.join(project_root, "ckp")): ckp_base = os.path.join(project_root, "ckp") return ckp_base
def model_subfolder(model_type): """Return subfolder name for model type: 'single_cell' or 'spheroid'.""" return "single_cell" if model_type == "single_cell" else "spheroid"20 unmodified lines2122232425262728293031323328 unmodified lines626364656667686970717220 unmodified linesreturn heatmap_rgbdef heatmap_to_png_bytes(scaled_heatmap, colormap_name="Jet", cell_mask=None):"""Convert scaled heatmap (float 0-1) to PNG bytes buffer. Optionally draw red cell contour."""heatmap_rgb = heatmap_to_rgb(scaled_heatmap, colormap_name)if cell_mask is not None and np.any(cell_mask > 0):contours, _ = cv2.findContours(cell_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)if contours:cv2.drawContours(heatmap_rgb, contours, -1, (255, 0, 0), 2)buf = io.BytesIO()Image.fromarray(heatmap_rgb).save(buf, format="PNG")buf.seek(0)28 unmodified linesc.setFont("Helvetica", 9)c.drawString(72, img_top - img_h - 12, "Input: Bright-field")heatmap_rgb = heatmap_to_rgb(display_heatmap, colormap_name)if cell_mask is not None and np.any(cell_mask > 0):contours, _ = cv2.findContours(cell_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)if contours:cv2.drawContours(heatmap_rgb, contours, -1, (255, 0, 0), 2)hm_buf = io.BytesIO()Image.fromarray(heatmap_rgb).save(hm_buf, format="PNG")hm_buf.seek(0)20 unmodified lines2122232425262728293031323334353637383928 unmodified lines6869707172737420 unmodified linesreturn heatmap_rgbdef heatmap_to_rgb_with_contour(scaled_heatmap, colormap_name="Jet", cell_mask=None):"""Convert heatmap to RGB, optionally drawing red cell contour. Mask must match heatmap shape."""heatmap_rgb = heatmap_to_rgb(scaled_heatmap, colormap_name)if cell_mask is not None and np.any(cell_mask > 0):contours, _ = cv2.findContours(cell_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)if contours:cv2.drawContours(heatmap_rgb, contours, -1, (255, 0, 0), 2)return heatmap_rgbdef heatmap_to_png_bytes(scaled_heatmap, colormap_name="Jet", cell_mask=None):"""Convert scaled heatmap (float 0-1) to PNG bytes buffer. Optionally draw red cell contour."""heatmap_rgb = heatmap_to_rgb_with_contour(scaled_heatmap, colormap_name, cell_mask)buf = io.BytesIO()Image.fromarray(heatmap_rgb).save(buf, format="PNG")buf.seek(0)28 unmodified linesc.setFont("Helvetica", 9)c.drawString(72, img_top - img_h - 12, "Input: Bright-field")heatmap_rgb = heatmap_to_rgb_with_contour(display_heatmap, colormap_name, cell_mask)hm_buf = io.BytesIO()Image.fromarray(heatmap_rgb).save(hm_buf, format="PNG")hm_buf.seek(0)
S2FApp/app.py+27-32
S2FApp/predictor.py+3-6
S2FApp/ui/components.py+2-15
S2FApp/utils/paths.pyAdded+17
S2FApp/utils/report.py+9-7