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 lines202122232425266 unmodified lines333435353637383936373830 unmodified lines69707172737475767778798081828384858687888944 unmodified lines13413513612612712812913013713813914045 unmodified lines18618718818218919019119279 unmodified lines27227327426827527627727873 unmodified lines35235335434834935035135235335435535635735535635735835936036112 unmodified lines37437537637637737837938038138238338438537737837938038138238319 unmodified lines MODEL_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 lines HAS_DRAWABLE_CANVAS,)
try: from streamlit_drawable_canvas import st_canvasexcept (ImportError, AttributeError): pass # HAS_DRAWABLE_CANVAS from ui.components
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 lines return measure_region_dialog if (HAS_DRAWABLE_CANVAS and ST_DIALOG) else None
def _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_mode st.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_name st.session_state["measure_auto_cell_on"] = auto_cell_boundary st.session_state["measure_cell_vals"] = build_cell_vals(heatmap, cell_mask, pixel_sum, force) if auto_cell_boundary else None st.session_state["measure_cell_mask"] = cell_mask if auto_cell_boundary else None
st.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_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 lines
ckp_files = get_ckp_files_for_model(model_type) ckp_folder = ckp_single_cell if model_type == "single_cell" else ckp_spheroid ckp_subfolder_name = "single_cell" if model_type == "single_cell" else "spheroid" ckp_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_spheroid sample_subfolder_name = "single_cell" if model_type == "single_cell" else "spheroid" sample_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, } st.session_state["measure_raw_heatmap"] = heatmap.copy() st.session_state["measure_display_mode"] = display_mode st.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_name cell_mask = estimate_cell_mask(heatmap) st.session_state["measure_auto_cell_on"] = auto_cell_boundary st.session_state["measure_cell_vals"] = build_cell_vals(heatmap, cell_mask, pixel_sum, force) if auto_cell_boundary else None st.session_state["measure_cell_mask"] = cell_mask if auto_cell_boundary else None _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 lines img, 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_mode st.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_name cell_mask = estimate_cell_mask(heatmap) st.session_state["measure_auto_cell_on"] = auto_cell_boundary st.session_state["measure_cell_vals"] = build_cell_vals(heatmap, cell_mask, pixel_sum, force) if auto_cell_boundary else None st.session_state["measure_cell_mask"] = cell_mask if auto_cell_boundary else None _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 lines1415161718192069 unmodified lines909192929394959697939495969713 unmodified lines sys.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 config
69 unmodified lines """ self.model_type = model_type self.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_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 used16 unmodified lines171819202021222378 unmodified lines102103104105106107108109110111112113114115105106107118 unmodified lines22622722824024124222923023123216 unmodified lines TOOL_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.report import heatmap_to_rgb, heatmap_to_rgb_with_contour, heatmap_to_png_bytes, create_pdf_reportfrom utils.segmentation import estimate_cell_mask
try:78 unmodified lines return pts
def 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, 0 combined = 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_heatmap h, w = display_heatmap.shape heatmap_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) heatmap_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 lines21222324252425262728293031323334353637383928 unmodified lines68697065666768697172737420 unmodified lines return heatmap_rgb
def 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."""def 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_rgb
def 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 lines c.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) 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