cleaned app.py
Browse filesFiles changed (7)
- S2FApp/config/__init__.pyAdded+1
- S2FApp/config/constants.pyAdded+30
- S2FApp/ui/__init__.pyAdded+1
- S2FApp/ui/components.pyAdded+521
- S2FApp/utils/display.pyAdded+34
- S2FApp/utils/metrics.py+2-2
- S2FApp/utils/report.pyAdded+106
1# Config package123456789101112131415161718192021222324252627282930"""Centralized constants for S2F App."""import cv2
# Model & pathsMODEL_INPUT_SIZE = 1024
# UICANVAS_SIZE = 320COLORMAP_N_SAMPLES = 64
# Model type labelsMODEL_TYPE_LABELS = {"single_cell": "Single cell", "spheroid": "Spheroid LS174T"}
# Drawing toolsDRAW_TOOLS = ["polygon", "rect", "circle"]TOOL_LABELS = {"polygon": "Polygon", "rect": "Rectangle", "circle": "Circle"}
# File extensionsSAMPLE_EXTENSIONS = (".tif", ".tiff", ".png", ".jpg", ".jpeg")
# Colormaps (OpenCV)COLORMAPS = { "Jet": cv2.COLORMAP_JET, "Viridis": cv2.COLORMAP_VIRIDIS, "Plasma": cv2.COLORMAP_PLASMA, "Inferno": cv2.COLORMAP_INFERNO, "Magma": cv2.COLORMAP_MAGMA,}1# UI components package123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521"""UI components for S2F App."""import csvimport ioimport os
import cv2import numpy as npimport streamlit as stfrom PIL import Imageimport plotly.graph_objects as gofrom plotly.subplots import make_subplots
from config.constants import ( CANVAS_SIZE, COLORMAPS, DRAW_TOOLS, 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.segmentation import estimate_cell_mask
try: from streamlit_drawable_canvas import st_canvas HAS_DRAWABLE_CANVAS = Trueexcept (ImportError, AttributeError): HAS_DRAWABLE_CANVAS = False
# Resolve st.dialog early to fix ordering bug (used in _render_result_display)ST_DIALOG = getattr(st, "dialog", None) or getattr(st, "experimental_dialog", None)
def make_annotated_heatmap(heatmap_rgb, mask, fill_alpha=0.3, stroke_color=(255, 102, 0), stroke_width=2): """Composite heatmap with drawn region overlay.""" annotated = heatmap_rgb.copy() contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) overlay = annotated.copy() cv2.fillPoly(overlay, contours, stroke_color) mask_3d = np.stack([mask] * 3, axis=-1).astype(bool) annotated[mask_3d] = ( (1 - fill_alpha) * annotated[mask_3d].astype(np.float32) + fill_alpha * overlay[mask_3d].astype(np.float32) ).astype(np.uint8) cv2.drawContours(annotated, contours, -1, stroke_color, stroke_width) return annotated
def _obj_to_pts(obj, scale_x, scale_y, heatmap_w, heatmap_h): """Convert a single canvas object to polygon points in heatmap coords. Returns None if invalid.""" obj_type = obj.get("type", "") pts = [] if obj_type == "rect": left = obj.get("left", 0) top = obj.get("top", 0) w = obj.get("width", 0) h = obj.get("height", 0) pts = np.array([ [left, top], [left + w, top], [left + w, top + h], [left, top + h] ], dtype=np.float32) elif obj_type == "circle" or obj_type == "ellipse": left = obj.get("left", 0) top = obj.get("top", 0) width = obj.get("width", 0) height = obj.get("height", 0) radius = obj.get("radius", 0) angle_deg = obj.get("angle", 0) if radius > 0: rx = ry = radius angle_rad = np.deg2rad(angle_deg) cx = left + radius * np.cos(angle_rad) cy = top + radius * np.sin(angle_rad) else: rx = width / 2 if width > 0 else 0 ry = height / 2 if height > 0 else 0 if rx <= 0 or ry <= 0: return None cx = left + rx cy = top + ry if rx <= 0 or ry <= 0: return None n = 32 angles = np.linspace(0, 2 * np.pi, n, endpoint=False) pts = np.column_stack([cx + rx * np.cos(angles), cy + ry * np.sin(angles)]).astype(np.float32) elif obj_type == "path": path = obj.get("path", []) for cmd in path: if isinstance(cmd, (list, tuple)) and len(cmd) >= 3: if cmd[0] in ("M", "L"): pts.append([float(cmd[1]), float(cmd[2])]) elif cmd[0] == "Q" and len(cmd) >= 5: pts.append([float(cmd[3]), float(cmd[4])]) elif cmd[0] == "C" and len(cmd) >= 7: pts.append([float(cmd[5]), float(cmd[6])]) if len(pts) < 3: return None pts = np.array(pts, dtype=np.float32) else: return None pts[:, 0] *= scale_x pts[:, 1] *= scale_y pts = np.clip(pts, 0, [heatmap_w - 1, heatmap_h - 1]).astype(np.int32) 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"]: return [], 0 scale_x = heatmap_w / canvas_w scale_y = heatmap_h / canvas_h masks = [] for obj in json_data["objects"]: pts = _obj_to_pts(obj, scale_x, scale_y, heatmap_w, heatmap_h) if pts is None: continue mask = np.zeros((heatmap_h, heatmap_w), dtype=np.uint8) cv2.fillPoly(mask, [pts], 1) masks.append(mask) return masks, len(masks)
def build_original_vals(raw_heatmap, pixel_sum, force): """Build original_vals dict for measure tool (full map).""" return { "pixel_sum": pixel_sum, "force": force, "max": float(np.max(raw_heatmap)), "mean": float(np.mean(raw_heatmap)), }
def build_cell_vals(raw_heatmap, cell_mask, pixel_sum, force): """Build cell_vals dict for measure tool (estimated cell area). Returns None if invalid.""" cell_pixel_sum, cell_force, cell_mean = _compute_cell_metrics(raw_heatmap, cell_mask, pixel_sum, force) if cell_pixel_sum is None: return None region_values = raw_heatmap * cell_mask region_nonzero = region_values[cell_mask > 0] cell_max = float(np.max(region_nonzero)) if len(region_nonzero) > 0 else 0 return { "pixel_sum": cell_pixel_sum, "force": cell_force, "max": cell_max, "mean": cell_mean, }
def compute_region_metrics(raw_heatmap, mask, original_vals=None): """Compute region metrics from mask.""" area_px = int(np.sum(mask)) region_values = raw_heatmap * mask region_nonzero = region_values[mask > 0] force_sum = float(np.sum(region_values)) density = force_sum / area_px if area_px > 0 else 0 region_max = float(np.max(region_nonzero)) if len(region_nonzero) > 0 else 0 region_mean = float(np.mean(region_nonzero)) if len(region_nonzero) > 0 else 0 region_force_scaled = ( force_sum * (original_vals["force"] / original_vals["pixel_sum"]) if original_vals and original_vals.get("pixel_sum", 0) > 0 else force_sum ) return { "area_px": area_px, "force_sum": force_sum, "density": density, "max": region_max, "mean": region_mean, "force_scaled": region_force_scaled, }
def render_region_metrics_and_downloads(metrics_list, heatmap_rgb, combined_mask, input_filename, key_suffix, has_original_vals, first_region_label=None): """Render per-shape metrics table and download buttons. first_region_label: custom label for first row (e.g. 'Auto boundary').""" base_name = os.path.splitext(input_filename or "image")[0] st.markdown("**Regions (each selection = one row)**") if has_original_vals: headers = ["Region", "Area", "F.sum", "Force", "Max", "Mean"] csv_rows = [["image", "region"] + headers[1:]] else: headers = ["Region", "Area (px²)", "Force sum", "Mean"] csv_rows = [["image", "region", "Area", "Force sum", "Mean"]] table_rows = [headers] for i, metrics in enumerate(metrics_list, 1): region_label = first_region_label if (i == 1 and first_region_label) else f"Region {i - (1 if first_region_label else 0)}" if has_original_vals: row = [region_label, str(metrics["area_px"]), f"{metrics['force_sum']:.3f}", f"{metrics['force_scaled']:.1f}", f"{metrics['max']:.3f}", f"{metrics['mean']:.4f}"] csv_rows.append([base_name, region_label, metrics["area_px"], f"{metrics['force_sum']:.3f}", f"{metrics['force_scaled']:.1f}", f"{metrics['max']:.3f}", f"{metrics['mean']:.4f}"]) else: row = [region_label, str(metrics["area_px"]), f"{metrics['force_sum']:.4f}", f"{metrics['mean']:.6f}"] csv_rows.append([base_name, region_label, metrics["area_px"], f"{metrics['force_sum']:.4f}", f"{metrics['mean']:.6f}"]) table_rows.append(row) st.table(table_rows) buf_csv = io.StringIO() csv.writer(buf_csv).writerows(csv_rows) buf_img = io.BytesIO() Image.fromarray(make_annotated_heatmap(heatmap_rgb, combined_mask)).save(buf_img, format="PNG") buf_img.seek(0) dl_col1, dl_col2 = st.columns(2) with dl_col1: st.download_button("Download all regions", data=buf_csv.getvalue(), file_name=f"{base_name}_all_regions.csv", mime="text/csv", key=f"download_all_regions_{key_suffix}", icon=":material/download:") with dl_col2: st.download_button("Download annotated heatmap", data=buf_img.getvalue(), file_name=f"{base_name}_annotated_heatmap.png", mime="image/png", key=f"download_annotated_{key_suffix}", icon=":material/image:")
def _draw_contour_on_image(img_rgb, mask, stroke_color=(255, 0, 0), stroke_width=2): """Draw contour from mask on RGB image. Resizes mask to match img if needed.""" h, w = img_rgb.shape[:2] if mask.shape[:2] != (h, w): mask = cv2.resize(mask.astype(np.uint8), (w, h), interpolation=cv2.INTER_NEAREST) contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if contours: cv2.drawContours(img_rgb, contours, -1, stroke_color, stroke_width) return img_rgb
def render_region_canvas(display_heatmap, raw_heatmap=None, bf_img=None, original_vals=None, cell_vals=None, cell_mask=None, key_suffix="", input_filename=None, colormap_name="Jet"): """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) pil_bg = Image.fromarray(heatmap_rgb).resize((CANVAS_SIZE, CANVAS_SIZE), Image.Resampling.LANCZOS)
st.markdown(""" <style> [data-testid="stDialog"] [data-testid="stSelectbox"], [data-testid="stExpander"] [data-testid="stSelectbox"], [data-testid="stDialog"] [data-testid="stSelectbox"] > div, [data-testid="stExpander"] [data-testid="stSelectbox"] > div { width: 100% !important; max-width: 100% !important; } [data-testid="stDialog"] [data-testid="stMetric"] label, [data-testid="stDialog"] [data-testid="stMetric"] [data-testid="stMetricValue"], [data-testid="stExpander"] [data-testid="stMetric"] label, [data-testid="stExpander"] [data-testid="stMetric"] [data-testid="stMetricValue"] { font-size: 0.95rem !important; } [data-testid="stDialog"] img, [data-testid="stExpander"] img { border-radius: 0 !important; } </style> """, unsafe_allow_html=True)
if bf_img is not None: bf_resized = cv2.resize(bf_img, (CANVAS_SIZE, CANVAS_SIZE)) bf_rgb = cv2.cvtColor(bf_resized, cv2.COLOR_GRAY2RGB) if bf_img.ndim == 2 else cv2.cvtColor(bf_resized, cv2.COLOR_BGR2RGB) left_col, right_col = st.columns(2, gap=None) with left_col: draw_mode = st.selectbox("Tool", DRAW_TOOLS, format_func=lambda x: TOOL_LABELS[x], key=f"draw_mode_region_{key_suffix}") st.caption("Left-click add, right-click close. \nForce map (draw region)") canvas_result = st_canvas( fill_color="rgba(255, 165, 0, 0.3)", stroke_width=2, stroke_color="#ff6600", background_image=pil_bg, drawing_mode=draw_mode, update_streamlit=True, height=CANVAS_SIZE, width=CANVAS_SIZE, display_toolbar=True, key=f"region_measure_canvas_{key_suffix}", ) with right_col: vals = cell_vals if cell_vals else original_vals if vals: label = "Cell area" if cell_vals else "Full map" st.markdown(f'<p style="font-weight: 400; color: #334155; font-size: 0.95rem; margin: 0 20px 4px 4px;">{label}</p>', unsafe_allow_html=True) st.markdown(f""" <div style="width: 100%; box-sizing: border-box; border: 1px solid #e2e8f0; border-radius: 10px; padding: 10px 12px; margin: 0 10px 20px 10px; background: linear-gradient(145deg, #f8fafc 0%, #f1f5f9 100%); box-shadow: 0 1px 3px rgba(0,0,0,0.06);"> <div style="display: flex; flex-wrap: wrap; gap: 5px; font-size: 0.9rem;"> <span><strong>Sum:</strong> {vals['pixel_sum']:.1f}</span> <span><strong>Force:</strong> {vals['force']:.1f}</span> <span><strong>Max:</strong> {vals['max']:.3f}</span> <span><strong>Mean:</strong> {vals['mean']:.3f}</span> </div> </div> """, unsafe_allow_html=True) st.caption("Bright-field") bf_display = bf_rgb.copy() if cell_mask is not None and np.any(cell_mask > 0): bf_display = _draw_contour_on_image(bf_display, cell_mask, stroke_color=(255, 0, 0), stroke_width=2) st.image(bf_display, width=CANVAS_SIZE) else: st.markdown("**Draw a region** on the heatmap.") draw_mode = st.selectbox("Drawing tool", DRAW_TOOLS, format_func=lambda x: "Polygon (free shape)" if x == "polygon" else TOOL_LABELS[x], key=f"draw_mode_region_{key_suffix}") st.caption("Polygon: left-click to add points, right-click to close.") canvas_result = st_canvas( fill_color="rgba(255, 165, 0, 0.3)", stroke_width=2, stroke_color="#ff6600", background_image=pil_bg, drawing_mode=draw_mode, update_streamlit=True, height=CANVAS_SIZE, width=CANVAS_SIZE, display_toolbar=True, key=f"region_measure_canvas_{key_suffix}", )
if canvas_result.json_data: masks, n = parse_canvas_shapes_to_masks(canvas_result.json_data, CANVAS_SIZE, CANVAS_SIZE, h, w) if masks and n > 0: metrics_list = [compute_region_metrics(raw_heatmap, m, original_vals) for m in masks] if cell_mask is not None and np.any(cell_mask > 0): cell_metrics = compute_region_metrics(raw_heatmap, cell_mask, original_vals) metrics_list = [cell_metrics] + metrics_list combined_mask = masks[0].copy() for m in masks[1:]: combined_mask = np.maximum(combined_mask, m) render_region_metrics_and_downloads( metrics_list, heatmap_rgb, combined_mask, input_filename, key_suffix, original_vals is not None, first_region_label="Auto boundary" if (cell_mask is not None and np.any(cell_mask > 0)) else None, )
def _compute_cell_metrics(raw_heatmap, cell_mask, pixel_sum, force): """Compute metrics over estimated cell area only.""" area_px = int(np.sum(cell_mask)) if area_px == 0: return None, None, None region_values = raw_heatmap * cell_mask cell_pixel_sum = float(np.sum(region_values)) cell_force = cell_pixel_sum * (force / pixel_sum) if pixel_sum > 0 else cell_pixel_sum cell_mean = cell_pixel_sum / area_px return cell_pixel_sum, cell_force, cell_mean
def _add_cell_contour_to_fig(fig_pl, cell_mask, row=1, col=2): """Add red contour overlay to Plotly heatmap subplot.""" if cell_mask is None or not np.any(cell_mask > 0): return contours, _ = cv2.findContours(cell_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if not contours: return # Use largest contour cnt = max(contours, key=cv2.contourArea) pts = cnt.squeeze() if pts.ndim == 1: pts = pts.reshape(1, 2) x, y = pts[:, 0].tolist(), pts[:, 1].tolist() if x[0] != x[-1] or y[0] != y[-1]: x.append(x[0]) y.append(y[0]) fig_pl.add_trace( go.Scatter(x=x, y=y, mode="lines", line=dict(color="red", width=2), showlegend=False), row=row, col=col )
def render_result_display(img, raw_heatmap, display_heatmap, pixel_sum, force, key_img, download_key_suffix="", colormap_name="Jet", display_mode="Auto", measure_region_dialog=None, auto_cell_boundary=True): """ Render prediction result: plot, metrics, expander, and download/measure buttons. measure_region_dialog: callable to open measure dialog (when ST_DIALOG available). auto_cell_boundary: when True, use estimated cell area for metrics; when False, use entire map. """ cell_mask = estimate_cell_mask(raw_heatmap) if auto_cell_boundary else None cell_pixel_sum, cell_force, cell_mean = _compute_cell_metrics(raw_heatmap, cell_mask, pixel_sum, force) if cell_mask is not None else (None, None, None) use_cell_metrics = auto_cell_boundary and cell_pixel_sum is not None and cell_force is not None and cell_mean is not None
base_name = os.path.splitext(key_img or "image")[0] if use_cell_metrics: main_csv_rows = [ ["image", "Cell sum", "Cell force (scaled)", "Heatmap max", "Cell mean"], [base_name, f"{cell_pixel_sum:.2f}", f"{cell_force:.2f}", f"{np.max(raw_heatmap):.4f}", f"{cell_mean:.4f}"], ] else: main_csv_rows = [ ["image", "Sum of all pixels", "Cell force (scaled)", "Heatmap max", "Heatmap mean"], [base_name, f"{pixel_sum:.2f}", f"{force:.2f}", f"{np.max(raw_heatmap):.4f}", f"{np.mean(raw_heatmap):.4f}"], ] buf_main_csv = io.StringIO() csv.writer(buf_main_csv).writerows(main_csv_rows)
buf_hm = heatmap_to_png_bytes(display_heatmap, colormap_name, cell_mask=cell_mask)
tit1, tit2 = st.columns(2) with tit1: st.markdown('<p style="font-size: 1.1rem; color: black; font-weight: 600;">Input: Bright-field image</p>', unsafe_allow_html=True) with tit2: st.markdown('<p style="font-size: 1.1rem; color: black; font-weight: 600;">Output: Predicted traction force map</p>', unsafe_allow_html=True) fig_pl = make_subplots(rows=1, cols=2) fig_pl.add_trace(go.Heatmap(z=img, colorscale="gray", showscale=False), row=1, col=1) plotly_colorscale = cv_colormap_to_plotly_colorscale(colormap_name) zmin, zmax = 0.0, 1.0 fig_pl.add_trace(go.Heatmap(z=display_heatmap, colorscale=plotly_colorscale, zmin=zmin, zmax=zmax, showscale=True, colorbar=dict(len=0.4, thickness=12)), row=1, col=2) _add_cell_contour_to_fig(fig_pl, cell_mask, row=1, col=2) fig_pl.update_layout( height=400, margin=dict(l=10, r=10, t=10, b=10), xaxis=dict(scaleanchor="y", scaleratio=1), xaxis2=dict(scaleanchor="y2", scaleratio=1), ) fig_pl.update_xaxes(showticklabels=False) fig_pl.update_yaxes(showticklabels=False, autorange="reversed") st.plotly_chart(fig_pl, use_container_width=True, config={"displayModeBar": True, "responsive": True})
col1, col2, col3, col4 = st.columns(4) if use_cell_metrics: with col1: st.metric("Cell sum", f"{cell_pixel_sum:.2f}", help="Sum over estimated cell area (background excluded)") with col2: st.metric("Cell force (scaled)", f"{cell_force:.2f}", help="Total traction force in physical units") with col3: st.metric("Heatmap max", f"{np.max(raw_heatmap):.4f}", help="Peak force intensity in the map") with col4: st.metric("Cell mean", f"{cell_mean:.4f}", help="Mean force over estimated cell area") else: with col1: st.metric("Sum of all pixels", f"{pixel_sum:.2f}", help="Raw sum of all pixel values in the force map") with col2: st.metric("Cell force (scaled)", f"{force:.2f}", help="Total traction force in physical units") with col3: st.metric("Heatmap max", f"{np.max(raw_heatmap):.4f}", help="Peak force intensity in the map") with col4: st.metric("Heatmap mean", f"{np.mean(raw_heatmap):.4f}", help="Average force intensity (full FOV)")
with st.expander("How to read the results"): if use_cell_metrics: st.markdown("""**Input (left):** Bright-field microscopy image of a cell or spheroid on a substrate. This is the raw image you provided—it shows cell shape but not forces.
**Output (right):** Predicted traction force map. - **Color** indicates force magnitude: blue = low, red = high - **Brighter/warmer colors** = stronger forces exerted by the cell on the substrate - **Red border = estimated cell area** (background excluded from metrics)- Values are normalized to [0, 1] for visualization
**Metrics (auto cell boundary on):**- **Cell sum:** Sum over estimated cell area (background excluded)- **Cell force (scaled):** Total traction force in physical units- **Heatmap max:** Peak force intensity in the map- **Cell mean:** Mean force over the estimated cell area """) else: st.markdown("""**Input (left):** Bright-field microscopy image of a cell or spheroid on a substrate. This is the raw image you provided—it shows cell shape but not forces.
**Output (right):** Predicted traction force map. - **Color** indicates force magnitude: blue = low, red = high - **Brighter/warmer colors** = stronger forces exerted by the cell on the substrate - Values are normalized to [0, 1] for visualization
**Metrics (auto cell boundary off):**- **Sum of all pixels:** Raw sum over entire map- **Cell force (scaled):** Total traction force in physical units- **Heatmap max/mean:** Peak and average force intensity (full field of view) """)
original_vals = build_original_vals(raw_heatmap, pixel_sum, force)
pdf_bytes = create_pdf_report( img, display_heatmap, raw_heatmap, pixel_sum, force, base_name, colormap_name, cell_mask=cell_mask, cell_pixel_sum=cell_pixel_sum, cell_force=cell_force, cell_mean=cell_mean )
btn_col1, btn_col2, btn_col3, btn_col4 = st.columns(4) with btn_col1: if HAS_DRAWABLE_CANVAS and measure_region_dialog is not None: if st.button("Measure tool", key="open_measure", icon=":material/straighten:"): st.session_state["open_measure_dialog"] = True st.rerun() elif HAS_DRAWABLE_CANVAS: with st.expander("Measure tool"): expander_cell_vals = build_cell_vals(raw_heatmap, cell_mask, pixel_sum, force) if (auto_cell_boundary and cell_mask is not None) else None expander_cell_mask = cell_mask if auto_cell_boundary else None render_region_canvas( display_heatmap, raw_heatmap=raw_heatmap, bf_img=img, original_vals=original_vals, cell_vals=expander_cell_vals, cell_mask=expander_cell_mask, key_suffix="expander", input_filename=key_img, colormap_name=colormap_name, ) else: st.caption("Install `streamlit-drawable-canvas-fix` for region measurement: `pip install streamlit-drawable-canvas-fix`") with btn_col2: st.download_button( "Download heatmap", width="stretch", data=buf_hm.getvalue(), file_name="s2f_heatmap.png", mime="image/png", key=f"download_heatmap{download_key_suffix}", icon=":material/download:", ) with btn_col3: st.download_button( "Download values", width="stretch", data=buf_main_csv.getvalue(), file_name=f"{base_name}_main_values.csv", mime="text/csv", key=f"download_main_values{download_key_suffix}", icon=":material/download:", ) with btn_col4: st.download_button( "Download report", width="stretch", data=pdf_bytes, file_name=f"{base_name}_report.pdf", mime="application/pdf", key=f"download_pdf{download_key_suffix}", icon=":material/picture_as_pdf:", )12345678910111213141516171819202122232425262728293031323334"""Display utilities for heatmaps and colormaps."""import numpy as npimport cv2
from config.constants import COLORMAPS, COLORMAP_N_SAMPLES
def cv_colormap_to_plotly_colorscale(colormap_name, n_samples=None): """Build a Plotly colorscale from OpenCV colormap so UI matches download/PDF exactly.""" n = n_samples or COLORMAP_N_SAMPLES cv2_cmap = COLORMAPS.get(colormap_name, cv2.COLORMAP_JET) gradient = np.linspace(0, 255, n, dtype=np.uint8).reshape(1, -1) rgb = cv2.applyColorMap(gradient, cv2_cmap) rgb = cv2.cvtColor(rgb, cv2.COLOR_BGR2RGB) scale = [] for i in range(n): r, g, b = rgb[0, i] scale.append([i / (n - 1), f"rgb({r},{g},{b})"]) return scale
def apply_display_scale(heatmap, mode): """ Apply display scaling (Fiji-style). Display only—does not change underlying values. - Auto: map data min..max to 0..1 (full color range) - Fixed: use 0-1 range as-is """ if mode == "Fixed": return np.clip(heatmap, 0, 1).astype(np.float32) hmin, hmax = float(np.min(heatmap)), float(np.max(heatmap)) if hmax > hmin: out = (heatmap.astype(np.float32) - hmin) / (hmax - hmin) return np.clip(out, 0, 1).astype(np.float32) return np.clip(heatmap, 0, 1).astype(np.float32)236 unmodified lines237238239240241242243176 unmodified lines420421422423424425426236 unmodified linesif use_settings and normalization_params is not None:from models.s2f_model import create_settings_channelsmeta = metadata if has_metadata else {'substrate': [substrate_override or 'fibroblasts_PDMS'] * images.size(0)}settings_ch = create_settings_channels(meta, normalization_params, device, images.shape, config_path=config_path)images = torch.cat([images, settings_ch], dim=1)176 unmodified linesbf_batch = torch.stack(bf_list[:n]).to(device, dtype=torch.float32)if use_settings and normalization_params:from models.s2f_model import create_settings_channelssub = substrate_override or 'fibroblasts_PDMS'meta_dict = {'substrate': [sub] * n}settings_ch = create_settings_channels(meta_dict, normalization_params, device, bf_batch.shape, config_path=config_path)bf_batch = torch.cat([bf_batch, settings_ch], dim=1)236 unmodified lines237238239240241242243176 unmodified lines420421422423424425426236 unmodified linesif use_settings and normalization_params is not None:from models.s2f_model import create_settings_channelsmeta = metadata if has_metadata else {'substrate': [substrate_override or 'Fibroblasts_Fibronectin_6KPa'] * images.size(0)}settings_ch = create_settings_channels(meta, normalization_params, device, images.shape, config_path=config_path)images = torch.cat([images, settings_ch], dim=1)176 unmodified linesbf_batch = torch.stack(bf_list[:n]).to(device, dtype=torch.float32)if use_settings and normalization_params:from models.s2f_model import create_settings_channelssub = substrate_override or 'Fibroblasts_Fibronectin_6KPa'meta_dict = {'substrate': [sub] * n}settings_ch = create_settings_channels(meta_dict, normalization_params, device, bf_batch.shape, config_path=config_path)bf_batch = torch.cat([bf_batch, settings_ch], dim=1)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106"""Report and heatmap export utilities."""import iofrom datetime import datetime
import cv2import numpy as npfrom PIL import Imagefrom reportlab.lib.pagesizes import A4from reportlab.lib.units import inchfrom reportlab.lib.utils import ImageReaderfrom reportlab.pdfgen import canvas
from config.constants import COLORMAPS
def heatmap_to_rgb(scaled_heatmap, colormap_name="Jet"): """Convert scaled heatmap (float 0-1) to RGB array using the given colormap.""" heatmap_uint8 = (np.clip(scaled_heatmap, 0, 1) * 255).astype(np.uint8) cv2_colormap = COLORMAPS.get(colormap_name, cv2.COLORMAP_JET) heatmap_rgb = cv2.cvtColor(cv2.applyColorMap(heatmap_uint8, cv2_colormap), cv2.COLOR_BGR2RGB) 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(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) return buf
def create_pdf_report(img, display_heatmap, raw_heatmap, pixel_sum, force, base_name, colormap_name="Jet", cell_mask=None, cell_pixel_sum=None, cell_force=None, cell_mean=None): """Create a PDF report with input image, heatmap, and metrics.""" buf = io.BytesIO() c = canvas.Canvas(buf, pagesize=A4) c.setTitle("Shape2Force") c.setAuthor("Angione-Lab") h = A4[1] img_w, img_h = 2.5 * inch, 2.5 * inch
footer_y = 40 c.setFont("Helvetica", 8) c.setFillColorRGB(0.4, 0.4, 0.4) gen_date = datetime.now().strftime("%Y-%m-%d %H:%M") c.drawString(72, footer_y, f"Generated by Shape2Force (S2F) on {gen_date}") c.drawString(72, footer_y - 12, "Model: https://huggingface.co/Angione-Lab/Shape2Force") c.drawString(72, footer_y - 24, "Web app: https://huggingface.co/spaces/Angione-Lab/Shape2force") c.setFillColorRGB(0, 0, 0)
img_top = h - 70 img_pil = Image.fromarray(img) if img.ndim == 2 else Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) img_buf = io.BytesIO() img_pil.save(img_buf, format="PNG") img_buf.seek(0) c.drawImage(ImageReader(img_buf), 72, img_top - img_h, width=img_w, height=img_h, preserveAspectRatio=True) 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) hm_buf = io.BytesIO() Image.fromarray(heatmap_rgb).save(hm_buf, format="PNG") hm_buf.seek(0) c.drawImage(ImageReader(hm_buf), 72 + img_w + 20, img_top - img_h, width=img_w, height=img_h, preserveAspectRatio=True) c.drawString(72 + img_w + 20, img_top - img_h - 12, "Output: Force map (red = estimated cell)")
c.setFont("Helvetica-Bold", 16) c.drawString(72, img_top + 25, "Shape2Force (S2F) - Prediction Report") c.setFont("Helvetica", 10) c.drawString(72, img_top + 8, f"Image: {base_name}")
y = img_top - img_h - 45 c.setFont("Helvetica-Bold", 10) c.drawString(72, y, "Metrics") c.setFont("Helvetica", 9) y -= 18 if cell_pixel_sum is not None and cell_force is not None and cell_mean is not None: metrics = [ ("Cell sum (estimated cell area)", f"{cell_pixel_sum:.2f}"), ("Cell force (scaled)", f"{cell_force:.2f}"), ("Heatmap max", f"{np.max(raw_heatmap):.4f}"), ("Cell mean (estimated cell area)", f"{cell_mean:.4f}"), ] else: metrics = [ ("Sum of all pixels", f"{pixel_sum:.2f}"), ("Cell force (scaled)", f"{force:.2f}"), ("Heatmap max", f"{np.max(raw_heatmap):.4f}"), ("Heatmap mean", f"{np.mean(raw_heatmap):.4f}"), ] for label, val in metrics: c.drawString(72, y, f"{label}: {val}") y -= 16
c.save() buf.seek(0) return buf.getvalue()S2FApp/config/__init__.pyAdded+1
S2FApp/config/constants.pyAdded+30
S2FApp/ui/__init__.pyAdded+1
S2FApp/ui/components.pyAdded+521
S2FApp/utils/display.pyAdded+34
S2FApp/utils/metrics.py+2-2
S2FApp/utils/report.pyAdded+106