Commit Β·
cd351de
1
Parent(s): b51b5c2
add input standardization
Browse filesFiles changed (2)
- _utils/image_io.pyAdded+358
- app.py+455-113
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358"""Image standardization.
Microscopy TIFFs come in many flavors: 16-bit or float pixels, single ormulti channel, and multi-page Z / time stacks. ``standardize_image`` collapsesany of those variants to a single canonical 8-bit RGB PNG used for BOTH theon-screen preview and the model, so what you see is what gets segmented.
Which axis means what is read from the file's own metadata (``series.axes``from tifffile: 'C'=channel, 'S'=RGB samples, 'Z'/'T'=stack, 'Y'/'X'=spatial)rather than guessed from the array shape -- guessing cannot tell a 3-channel(C, Y, X) image apart from a 3-slice (Z, Y, X) stack. Only when a file namesno axes at all (tifffile reports 'Q' = unknown) do we fall back to the dominantconvention: the first unknown axis of size 2-4 is the channel axis.
Reduction policy:
* multi-page / Z / time stacks -> one frame (default: the first) * more than 3 channels -> first 3 channels (as R, G, B) * intensity -> 0-255 -> 1st-99th percentile auto-contrast for 16-bit/float input (outlier-robust: a hot / saturated pixel would make plain min/max scaling collapse the real signal to black)
Standard 8-bit inputs (PNG/JPG/8-bit TIFF) are passed through unchanged invalue; only channel layout is normalized."""
import osimport tempfilefrom typing import NamedTuple
import numpy as npfrom PIL import Image
try: import tifffileexcept ImportError: # pragma: no cover - tifffile is a project dependency tifffile = None
# Size policy. The model resizes any input to 512x512 (see segmentation.py), so a# larger image costs memory/time and *loses* detail rather than adding any.RECOMMENDED_SIZE = 512 # cropping to about this preserves the most detailWARN_SIZE = 3072 # above this, advise the user to cropMAX_SIZE = 4096 # above this, refuse: reading the pixels risks an OOM# Refuse files whose full array would not comfortably fit in memory. Measured on# the uncompressed array (shape x dtype) rather than the file size on disk, since# compression makes disk size a poor proxy for what we actually allocate.MAX_READ_BYTES = 300 * 1024 ** 2 # 300 MiB
# Axis roles, per tifffile's `series.axes` naming._SPATIAL = ("Y", "X")_CHANNEL = ("C", "S") # C = separate channel planes, S = interleaved RGB samples_UNKNOWN = ("Q", "I") # file named no axis; only these may be *guessed* as channels# Anything else (Z, T, ...) is a stack axis and is indexed by frame.
def _read_array(path): """Load an image file into (array, axes) where axes names each dimension.
axes uses tifffile's convention ('C' channel, 'S' RGB samples, 'Z'/'T' stack, 'Y'/'X' spatial, 'Q' unknown). Indexed / palette images (ImageJ "8-bit Color", palette PNG/GIF) are expanded through their color lookup table so we return true RGB, not bare indices. """ ext = os.path.splitext(path)[1].lower() if ext in (".tif", ".tiff") and tifffile is not None: with tifffile.TiffFile(path) as tif: series = tif.series[0] page = tif.pages[0] arr = np.asarray(series.asarray()) axes = str(series.axes) is_palette = getattr(page, "photometric", None) == tifffile.PHOTOMETRIC.PALETTE if is_palette and page.colormap is not None: colormap = np.asarray(page.colormap) # (3, 2**bits), uint16 rgb = np.moveaxis(colormap[:, arr], 0, -1) # (..., H, W, 3) # TIFF colormaps are 16-bit; scale down to 8-bit (65535/255=257). arr = np.round(rgb / 257.0).astype(np.uint8) axes = axes + "S" # the LUT added an RGB sample axis return arr, axes # Everything else (and if tifffile is unavailable): PIL. Expand palette # images to RGB so the LUT is applied instead of returning bare indices. img = Image.open(path) if img.mode in ("P", "PA"): img = img.convert("RGB") arr = np.asarray(img) return arr, ("YXS" if arr.ndim == 3 else "YX")
def _shape_axes(path): """Return (shape, axes) from metadata only - no pixel decode.""" ext = os.path.splitext(path)[1].lower() if ext in (".tif", ".tiff") and tifffile is not None: try: with tifffile.TiffFile(path) as tif: series = tif.series[0] return tuple(series.shape), str(series.axes) except Exception: # noqa: BLE001 - fall through to PIL pass with Image.open(path) as img: w, h = img.size if img.mode in ("P", "PA", "RGB", "RGBA", "CMYK", "YCbCr", "LAB", "HSV"): return (h, w, len(img.getbands())), "YXS" return (h, w), "YX"
def _plan_axes(shape, axes): """Drop size-1 axes, infer a channel axis when the file names none, and move it last.
Returns (shape, axes, guessed) as lists + a flag saying whether the channel axis had to be inferred rather than read from the file. """ axes = list(axes) shape = list(shape) if len(axes) != len(shape): # be defensive; keep the trailing spatial axes axes = ["Q"] * (len(shape) - 2) + ["Y", "X"]
pairs = [(a, d) for a, d in zip(axes, shape) if d != 1] axes = [a for a, _ in pairs] shape = [d for _, d in pairs]
guessed = False if not any(a in _CHANNEL for a in axes): # Only guess on axes the file left unnamed. An axis the file explicitly # calls Z/T is a stack even when its length happens to be 3. for i, (a, d) in enumerate(zip(axes, shape)): if a in _UNKNOWN and d in (2, 3, 4): axes[i] = "C" guessed = True break
ci = next((i for i, a in enumerate(axes) if a in _CHANNEL), None) if ci is not None: axes.append(axes.pop(ci)) shape.append(shape.pop(ci)) return shape, axes, guessed
def _reduce_to_hwc(arr, axes, frame=0): """Collapse a labelled array to 2D (H, W) or 3D (H, W, C).
The channel axis (named by the file, or inferred by ``_plan_axes`` only when the file names none) is moved last and kept whole. The remaining stack axes (Z / time / page) are indexed: the first by ``frame``, any deeper ones by 0. """ axes = list(axes)
# Drop size-1 axes, keeping arr and axes in sync. for i in range(len(axes) - 1, -1, -1): if arr.shape[i] == 1: arr = arr.reshape(arr.shape[:i] + arr.shape[i + 1:]) axes.pop(i)
_, planned, _ = _plan_axes(arr.shape, axes)
# Apply the plan to the array: infer the channel axis, then move it last. if "C" in planned and not any(a in _CHANNEL for a in axes): for i, (a, d) in enumerate(zip(axes, arr.shape)): if a in _UNKNOWN and d in (2, 3, 4): axes[i] = "C" break ci = next((i for i, a in enumerate(axes) if a in _CHANNEL), None) if ci is not None: arr = np.moveaxis(arr, ci, -1) axes.append(axes.pop(ci))
# Index the leading stack axes: first by `frame`, deeper by 0. target = 3 if ci is not None else 2 first = True while len(axes) > target: idx = int(frame) if first else 0 idx = max(0, min(idx, arr.shape[0] - 1)) arr = arr[idx] axes.pop(0) first = False
return arr
class ImageInfo(NamedTuple): """How a file's dimensions were interpreted (read from metadata only).
frames - length of the first stack (Z/T) axis, 1 if not a stack channels - length of the channel axis, 1 if single-channel axes - the file's own axes string, e.g. 'CZYX' ('Q' = unnamed) guessed - True if the channel axis was inferred rather than read shape - the file's raw shape as stored, e.g. (1, 4, 1, 1024, 1024) width - pixels along the X axis (0 if unknown) height - pixels along the Y axis (0 if unknown) """ frames: int channels: int axes: str guessed: bool shape: tuple width: int height: int
def inspect_image(path): """Describe a file's structure from metadata only (no pixel decode).""" try: shape, axes = _shape_axes(path) planned_shape, planned_axes, guessed = _plan_axes(shape, axes) has_c = bool(planned_axes) and planned_axes[-1] in _CHANNEL channels = int(planned_shape[-1]) if has_c else 1 target = 3 if has_c else 2 frames = int(planned_shape[0]) if len(planned_axes) > target else 1
# Spatial size comes from the named Y/X axes, so it stays correct # whatever order the other axes are in. width = height = 0 for a, d in zip(axes, shape): if a == "Y": height = int(d) elif a == "X": width = int(d) if not (width and height): # no Y/X named; fall back to the header probe width, height = image_size(path)
return ImageInfo(frames, channels, str(axes), guessed, tuple(shape), width, height) except Exception: # noqa: BLE001 return ImageInfo(1, 1, "", False, (), 0, 0)
def count_frames(path): """Return how many frames a file's stack (Z/T) axis has (1 if not a stack).""" return inspect_image(path).frames
def array_nbytes(path): """Bytes that opening this file's full array would allocate.
Computed from shape + dtype in the header - no pixel decode - so it is safe to call on a file that is too large to open. Returns 0 if unknown. """ ext = os.path.splitext(path)[1].lower() if ext in (".tif", ".tiff") and tifffile is not None: try: with tifffile.TiffFile(path) as tif: series = tif.series[0] return int(np.prod(series.shape)) * int(np.dtype(series.dtype).itemsize) except Exception: # noqa: BLE001 - fall through to PIL pass try: with Image.open(path) as img: w, h = img.size return int(w) * int(h) * len(img.getbands()) # 8-bit assumption except Exception: # noqa: BLE001 return 0
def image_size(path): """Return an image's (width, height) by reading only its header.
Never decodes pixel data, so this is safe to call as a size guard on a file that would be too large to load. Returns (0, 0) if the size cannot be determined, so callers treat it as "unknown" and proceed. """ ext = os.path.splitext(path)[1].lower() if ext in (".tif", ".tiff") and tifffile is not None: try: with tifffile.TiffFile(path) as tif: page = tif.pages[0] return int(page.imagewidth), int(page.imagelength) except Exception: # noqa: BLE001 - fall through to PIL pass try: with Image.open(path) as img: # PIL parses the header lazily return int(img.size[0]), int(img.size[1]) except Exception: # noqa: BLE001 return 0, 0
def _to_rgb(arr): """Turn a 2D or (H, W, C) array into exactly 3 channels.""" if arr.ndim == 2: return np.stack([arr] * 3, axis=-1)
channels = arr.shape[2] if channels == 1: return np.repeat(arr, 3, axis=2) if channels == 2: # Pad a zero third channel rather than inventing signal. return np.concatenate([arr, np.zeros_like(arr[:, :, :1])], axis=2) return arr[:, :, :3]
def _load_rgb(path, frame=0): """Read a file and reduce it to an (H, W, 3) array plus its source dtype.""" raw, axes = _read_array(path) arr = _reduce_to_hwc(raw, axes, frame=frame) arr = _to_rgb(arr) return arr, raw.dtype
def _to_uint8(arr, stretch): """Map pixel values to uint8.
When ``stretch`` is True (non-8-bit input) a 1st-99th percentile auto- contrast stretch is applied - outlier-robust, so a hot/saturated pixel does not collapse the visible signal to black. Otherwise values are only clipped, so standard 8-bit images are unchanged. """ arr = arr.astype(np.float32)
if not stretch: return np.clip(arr, 0, 255).astype(np.uint8)
lo, hi = np.percentile(arr, (1, 99)) if hi <= lo: # near-flat image; fall back to full min/max lo, hi = float(arr.min()), float(arr.max()) if hi <= lo: # truly constant image return np.zeros(arr.shape, dtype=np.uint8)
arr = np.clip((arr - lo) / (hi - lo), 0.0, 1.0) return (arr * 255.0).astype(np.uint8)
def _save_png(arr, out_path=None, out_dir=None, base=None, suffix="_std.png"): """Save an (H, W, 3) uint8 array as a PNG and return the path.""" if out_path is None: if out_dir is not None: os.makedirs(out_dir, exist_ok=True) out_path = os.path.join(out_dir, (base or "image") + suffix) else: tmp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix) out_path = tmp.name tmp.close() Image.fromarray(arr, mode="RGB").save(out_path) return out_path
def standardize_image(path, frame=0, out_dir=None, out_path=None): """Standardize any image/TIFF to a canonical 8-bit RGB PNG.
Used for both the preview and the model: one frame, <=3 channels, with a 1st-99th percentile auto-contrast stretch for 16-bit/float input (8-bit is passed through unchanged).
Args: path: path to the input image (TIFF, PNG, JPG, ...). frame: which frame of a stack to use (0-based; ignored for non-stacks). out_dir: optional directory for the output PNG. out_path: optional explicit output file path (overrides out_dir).
Returns: Path to the standardized PNG. On any failure the original ``path`` is returned unchanged so callers degrade gracefully. """ try: arr, dtype = _load_rgb(path, frame=frame) arr = _to_uint8(arr, stretch=(dtype != np.uint8)) base = os.path.splitext(os.path.basename(path))[0] return _save_png(arr, out_path=out_path, out_dir=out_dir, base=base, suffix="_std.png") except Exception as e: # noqa: BLE001 - never let preprocessing crash a run print(f"β οΈ standardize_image failed for {path}: {e}; using original file") return path20 unmodified lines21222324252627282953 unmodified lines83848586878889909192939495969798991001011021031041051061 unmodified line108109110111112113114115116117118174 unmodified lines2932942952962972985 unmodified lines30430530630730830949 unmodified lines359360361362363364365366367368369370371372373374375376377378379633 unmodified lines101310141015101610171018106 unmodified lines11251126112711281129113024 unmodified lines115511561157115811591160116118 unmodified lines118011811182118311841185118611871188118911902 unmodified lines119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121713 unmodified lines12311232123312341235123612371238123912401241124212431244124512465 unmodified lines1252125312541255125612571258125923 unmodified lines1283128412851286128712888 unmodified lines1297129812991300130113021303130413052 unmodified lines130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134433 unmodified lines1378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140315 unmodified lines141914201421142214231424142514261427142814291430143114321433143414351436143714386 unmodified lines1445144614471448144914501451145225 unmodified lines147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015218 unmodified lines15301531153215331534153515361537153833 unmodified lines15721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160413 unmodified lines16181619162016211622162316241625162616271628162916301631163213 unmodified lines1646164716481649165016511652165316541655191 unmodified lines1847184818491850185118521853185418551856185718581859186048 unmodified lines190919101911191220 unmodified linesfrom inference_seg import load_model as load_seg_model, run as run_segfrom inference_count import load_model as load_count_model, run as run_countfrom inference_track import load_model as load_track_model, run as run_trackHF_TOKEN = os.getenv("HF_TOKEN")DATASET_REPO = "phoebe777777/celltool_feedback"print("===== clearing cache =====")53 unmodified linessave_feedback(query_id, feedback_type, feedback_text, img_path, bboxes)returnfeedback_data = {"query_id": query_id,"feedback_type": feedback_type,"feedback_text": feedback_text,"image_path": img_path,"bboxes": str(bboxes), # 转为ε符串"datetime": time.strftime("%Y-%m-%d %H:%M:%S"),"timestamp": time.time()}try:api = HfApi()filename = f"feedback_{query_id}_{int(time.time())}.json"with open(filename, 'w', encoding='utf-8') as f:json.dump(feedback_data, f, indent=2, ensure_ascii=False)api.upload_file(path_or_fileobj=filename,path_in_repo=f"data/{filename}",1 unmodified linerepo_type="dataset",token=HF_TOKEN)os.remove(filename)print(f"β Feedback saved to HF Dataset: {DATASET_REPO}")except Exception as e:print(f"β οΈ Failed to save to HF Dataset: {e}")save_feedback(query_id, feedback_type, feedback_text, img_path, bboxes)174 unmodified linespass@spaces.GPUdef segment_with_choice(use_box_choice, annot_value, overlay_alpha):"""Segmentation handler - supports bounding box, returns colorized overlay and original mask path"""5 unmodified linesbboxes = annot_value[1] if len(annot_value) > 1 else []print(f"πΌοΈ Image path: {img_path}")box_array = Noneif use_box_choice == "Yes" and bboxes:box = parse_bboxes(bboxes)49 unmodified lines"""Counting handler - supports bounding box, returns only density map"""if annot_value is None or len(annot_value) < 1:return None, None, "β οΈ Please provide an image.", {}image_path = annot_value[0]bboxes = annot_value[1] if len(annot_value) > 1 else []print(f"πΌοΈ Image path: {image_path}")box_array = Noneif use_box_choice == "Yes" and bboxes:box = parse_bboxes(bboxes)if box:box_array = boxprint(f"π¦ Using bounding boxes: {box_array}")try:print(f"π’ Counting - Image: {image_path}")device = torch.device("cuda" if torch.cuda.is_available() else "cpu")result = run_count(COUNT_MODEL,633 unmodified lines/* ββ Labels ββββββββββββββββββββββββββββββββββββββββββββ */label { font-weight: 500 !important; color: #374151 !important; }/* ββ Image output ββββββββββββββββββββββββββββββββββββββ */.uniform-height {height: 480px !important;106 unmodified lines.dark label {color: #cbd5e1 !important;}/* ββ Image output area βββββββββββββββββββββββββββββββββ */.dark .uniform-height {24 unmodified linesprimary_hue=gr.themes.colors.sky,secondary_hue=gr.themes.colors.slate,neutral_hue=gr.themes.colors.slate,font=gr.themes.GoogleFont("Inter"),),css=CSS,) as demo:18 unmodified lines)# ε ¨ε±ηΆζcurrent_query_id = gr.State(str(uuid.uuid4()))user_uploaded_examples = gr.State(example_images_seg.copy())seg_vis_state = gr.State({})count_vis_state = gr.State({})track_vis_state = gr.State({})with gr.Tabs():# ===== Tab 1: Segmentation =====2 unmodified linesgr.Markdown("""**Instructions:**1. Upload an image or select an example image (supports various formats: .png, .jpg, .tif)2. (Optional) Specify a target object with a bounding box and select "Yes", or click "Run Segmentation" directly3. Click "Run Segmentation"4. View the segmentation results (you can adjust the overlay opacity by sliding the opacity bar below the visualization), download the original predicted mask (.tif format); if needed, click "Clear Selection" to choose a new imageπ€ Rate and submit feedback to help us improve the model!""")with gr.Row():with gr.Column(scale=1):annotator = BBoxAnnotator(label="πΌοΈ Upload Image (Optional: Provide a Bounding Box)",categories=["cell"],)# Example Images Galleryexample_gallery = gr.Gallery(label="π Example Image Gallery",columns=len(example_images_seg),rows=1,height=120,13 unmodified linesclear_btn = gr.Button("π Clear Selection", variant="secondary")# Upload Example Imageimage_uploader = gr.Image(label="β Upload New Example Image to Gallery",type="filepath")with gr.Column(scale=2):seg_output = gr.Image(type="pil",label="πΈ Segmentation Result",elem_classes="uniform-height")seg_alpha_slider = gr.Slider(5 unmodified lines)# Download Original Predictiondownload_mask_btn = gr.File(label="π₯ Download Original Prediction (.tif format)",visible=True,height=40,)23 unmodified linesvisible=False)# click event for segmentationrun_seg_btn.click(fn=segment_with_choice,8 unmodified lines# click event for clear buttonclear_btn.click(fn=lambda: (None, {}),inputs=None,outputs=[annotator, seg_vis_state])# init Gallery with example images2 unmodified linesoutputs=example_gallery)# click event for image uploaderdef add_to_gallery(img_path, current_imgs):if not img_path:return current_imgstry:if img_path not in current_imgs:current_imgs.append(img_path)return current_imgsexcept:return current_imgsimage_uploader.change(fn=add_to_gallery,inputs=[image_uploader, user_uploaded_examples],outputs=user_uploaded_examples).then(fn=lambda imgs: imgs,inputs=user_uploaded_examples,outputs=example_gallery)# click event for Gallery selectiondef load_from_gallery(evt: gr.SelectData, all_imgs):if evt.index is not None and evt.index < len(all_imgs):return all_imgs[evt.index]return Noneexample_gallery.select(fn=load_from_gallery,inputs=user_uploaded_examples,outputs=annotator)# click event for submitting feedback33 unmodified linesgr.Markdown("""**Usage Instructions:**1. Upload an image or select an example image (supports multiple formats: .png, .jpg, .tif)2. (Optional) Specify a target object with a bounding box and select "Yes", or click "Run Counting" directly3. Click "Run Counting"4. View the density map (you can adjust the density opacity by sliding the opacity bar below the visualization), download the original prediction (.npy format); if needed, click "Clear Selection" to choose a new image to runπ€ Rate and submit feedback to help us improve the model!""")with gr.Row():with gr.Column(scale=1):count_annotator = BBoxAnnotator(label="πΌοΈ Upload Image (Optional: Provide a Bounding Box)",categories=["cell"],)# Example gallery with "add" functionalitywith gr.Row():count_example_gallery = gr.Gallery(label="π Example Image Gallery",columns=len(example_images_cnt),rows=1,object_fit="cover",15 unmodified linesclear_btn = gr.Button("π Clear Selection", variant="secondary")# Add button to upload new exampleswith gr.Row():count_image_uploader = gr.File(label="β Add Example Image to Gallery",file_types=["image"],type="filepath")with gr.Column(scale=2):count_output = gr.Image(label="πΈ Density Map",type="filepath",elem_id="density_map_output")count_alpha_slider = gr.Slider(minimum=0.0,6 unmodified lineslabel="π Statistics",lines=2)download_density_btn = gr.File(label="π₯ Download Original Prediction (.npy format)",visible=True)25 unmodified lines# State for managing gallery imagescount_user_examples = gr.State(example_images_cnt.copy())# Function to add image to gallerydef add_to_count_gallery(new_img_file, current_imgs):"""Add uploaded image to gallery"""if new_img_file is None:return current_imgs, current_imgstry:# Add new image path to listif new_img_file not in current_imgs:current_imgs.append(new_img_file)print(f"β Added image to gallery: {new_img_file}")except Exception as e:print(f"β οΈ Failed to add image: {e}")return current_imgs, current_imgs# When user uploads a new image filecount_image_uploader.upload(fn=add_to_count_gallery,inputs=[count_image_uploader, count_user_examples],outputs=[count_user_examples, count_example_gallery])# When user selects from gallery, load into annotatordef load_from_count_gallery(evt: gr.SelectData, all_imgs):"""Load selected image from gallery into annotator"""if evt.index is not None and evt.index < len(all_imgs):selected_img = all_imgs[evt.index]print(f"πΈ Loading image from gallery: {selected_img}")return selected_imgreturn Nonecount_example_gallery.select(fn=load_from_count_gallery,inputs=count_user_examples,outputs=count_annotator)# Run countingcount_btn.click(fn=count_cells_handler,8 unmodified lines# Clear selectionclear_btn.click(fn=lambda: (None, {}),inputs=None,outputs=[count_annotator, count_vis_state])# Submit feedback33 unmodified linesgr.Markdown("""**Instructions:**1. Upload a ZIP file or select from the example library. The ZIP should contain a sequence of TIF images named in chronological order (e.g., t000.tif, t001.tif...)2. (Optional) Specify a target object with a bounding box on the first frame and select "Yes", or click "Run Tracking" directly3. Click "Run Tracking"4. View the tracking results (you can adjust the overlay opacity by sliding the opacity bar below the visualization), download the CTC format results; if needed, click "Clear Selection" to choose a new ZIP file to runπ€ Rate and submit feedback to help us improve the model!""")with gr.Row():with gr.Column(scale=1):track_zip_upload = gr.File(label="π¦ Upload Image Sequence in ZIP File",file_types=[".zip"])# First frame annotation for bounding boxtrack_first_frame_annotator = BBoxAnnotator(label="πΌοΈ (Optional) First Frame Bounding Box Annotation",categories=["cell"],visible=False, # Hidden initially)# Example ZIP gallerytrack_example_gallery = gr.Gallery(label="π Example Video Gallery (Click to Select)",columns=10,rows=1,height=120,13 unmodified linesclear_btn = gr.Button("π Clear Selection", variant="secondary")# Add to gallery buttontrack_gallery_upload = gr.File(label="β Add ZIP to Example Gallery",file_types=[".zip"],type="filepath")with gr.Column(scale=2):track_first_frame_preview = gr.Image(label="πΈ Tracking Visualization",type="filepath",# height=400,elem_classes="uniform-height",13 unmodified linesinteractive=False)track_download = gr.File(label="π₯ Download Tracking Results (CTC Format)",visible=False)# Satisfaction ratingscore_slider = gr.Slider(191 unmodified linestrack_zip_upload.change(fn=load_first_frame_for_annotation,inputs=track_zip_upload,outputs=[track_first_frame_annotator, track_first_frame_annotator])# Run trackingtrack_btn.click(fn=track_video_handler,inputs=[track_use_box_radio, track_first_frame_annotator, track_zip_upload, track_alpha_slider, track_vis_state],outputs=[track_download, track_output, track_download, track_first_frame_preview, track_vis_state])track_alpha_slider.change(fn=update_tracking_overlay_alpha,48 unmodified linesshare=False,ssr_mode=False,show_error=True,)20 unmodified lines2122232425262728293031323353 unmodified lines878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331 unmodified line135136137138139140141142143144145174 unmodified lines3203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524535 unmodified lines45946046146246346446546646749 unmodified lines517518519520521522523524525526527528529530531532533534535536537538539540633 unmodified lines1174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237106 unmodified lines1344134513461347134813491350135113521353135424 unmodified lines137913801381138213831384138513861387138818 unmodified lines1407140814091410141114121413141414151416141714181419142014211422142314242 unmodified lines1427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147613 unmodified lines1490149114921493149414951496149714981499150015011502150315041505150615071508150915105 unmodified lines15161517151815191520152115221523152423 unmodified lines15481549155015511552155315541555155615571558155915601561156215631564156515668 unmodified lines1575157615771578157915801581158215832 unmodified lines1586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162633 unmodified lines1660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170915 unmodified lines172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617476 unmodified lines17541755175617571758175917601761176225 unmodified lines17881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718488 unmodified lines18571858185918601861186218631864186533 unmodified lines18991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193713 unmodified lines1951195219531954195519561957195819591960196119621963196419651966196713 unmodified lines198119821983198419851986198719881989199019911992191 unmodified lines2184218521862187218821892190219121922193219421952196219748 unmodified lines22462247224822492250225122522253225420 unmodified linesfrom inference_seg import load_model as load_seg_model, run as run_segfrom inference_count import load_model as load_count_model, run as run_countfrom inference_track import load_model as load_track_model, run as run_trackfrom _utils.image_io import (standardize_image, inspect_image, image_size, array_nbytes,RECOMMENDED_SIZE, WARN_SIZE, MAX_SIZE, MAX_READ_BYTES,)HF_TOKEN = os.getenv("HF_TOKEN")DATASET_REPO = "VisionLanguageGroup/feedback"print("===== clearing cache =====")53 unmodified linessave_feedback(query_id, feedback_type, feedback_text, img_path, bboxes)return# One stem for the record and its image so the two pair up. query_id alone is# not enough - a single session can submit feedback more than once.stem = f"feedback_{query_id}_{int(time.time())}"try:api = HfApi()# Upload the standardized PNG: the exact image the model saw (first# frame, <=3 channels, auto-contrasted), not the raw upload.image_in_repo = Noneif img_path and os.path.exists(img_path):try:image_in_repo = f"images/{stem}.png"api.upload_file(path_or_fileobj=img_path,path_in_repo=image_in_repo,repo_id=DATASET_REPO,repo_type="dataset",token=HF_TOKEN)except Exception as e:print(f"β οΈ Failed to upload image: {e}")image_in_repo = None # still record the rest of the feedbackfeedback_data = {"query_id": query_id,"feedback_type": feedback_type,"feedback_text": feedback_text,# Path inside the dataset repo. This used to be the local temp path,# which was meaningless once the session ended."image_path": image_in_repo,"bboxes": str(bboxes), # 转为ε符串"datetime": time.strftime("%Y-%m-%d %H:%M:%S"),"timestamp": time.time()}filename = f"{stem}.json"with open(filename, 'w', encoding='utf-8') as f:json.dump(feedback_data, f, indent=2, ensure_ascii=False)api.upload_file(path_or_fileobj=filename,path_in_repo=f"data/{filename}",1 unmodified linerepo_type="dataset",token=HF_TOKEN)os.remove(filename)print(f"β Feedback saved to HF Dataset: {DATASET_REPO} ({stem})")except Exception as e:print(f"β οΈ Failed to save to HF Dataset: {e}")save_feedback(query_id, feedback_type, feedback_text, img_path, bboxes)174 unmodified linespassdef _annot_path(annot_value):"""Extract the image path from a BBoxAnnotator value (path or (path, boxes))."""if not annot_value:return Noneif isinstance(annot_value, (list, tuple)):return annot_value[0] if len(annot_value) > 0 else Nonereturn annot_valuedef _human_bytes(n):"""Format a byte count as MB or GB, whichever reads better."""gb = n / 1024 ** 3return f"{gb:.1f} GB" if gb >= 1 else f"{n / 1024 ** 2:.0f} MB"def check_image(img_path):"""Check a file from its header only (no pixel decode).Returns a rejection message if the file cannot be used, otherwise None:* unreadable / unsupported format* dimensions over MAX_SIZE* full array over MAX_READ_BYTES (a small time-lapse can still be huge)Also emits an advisory warning over WARN_SIZE, since the model resizes everyinput to RECOMMENDED_SIZE and a larger image only loses detail."""w, h = image_size(img_path)if w <= 0 or h <= 0:# Neither tifffile nor PIL could parse the header, so this is not a# format we can read. Say so instead of failing silently downstream.ext = os.path.splitext(img_path)[1].lower() or "(no extension)"return (f"Could not read {ext} as an image. Supported formats: "f"TIFF / OME-TIFF (8/16/32-bit, stacks, multi-channel), PNG, JPG, and other formats suported by tiffile. "f"please export to TIFF/PNG/JPG (e.g. from ImageJ/Fiji) first.")if w > MAX_SIZE or h > MAX_SIZE:return (f"Image is {w}Γ{h}, larger than the {MAX_SIZE}Γ{MAX_SIZE} limit. "f"Please crop or downsample it before uploading.")nbytes = array_nbytes(img_path)if nbytes > MAX_READ_BYTES:info = inspect_image(img_path)detail = f"{w}Γ{h}"if info.frames > 1:detail += f" Γ {info.frames} frames"if info.channels > 1:detail += f" Γ {info.channels} channels"return (f"This file needs {_human_bytes(nbytes)} of memory to open "f"({detail}), over the {_human_bytes(MAX_READ_BYTES)} limit. "f"Please crop it, or split out the frames you need.")if w > WARN_SIZE or h > WARN_SIZE:gr.Warning(f"Image is {w}Γ{h} and will be resized to "f"{RECOMMENDED_SIZE}Γ{RECOMMENDED_SIZE}, so fine detail could be lost. "f"You can try cropping the image for better results.",# f"For best results, try cropping the image to focus on the region of interest.",duration=None, title="β οΈ Large image")return Nonedef _describe_read(info):"""Plain-language summary of how a file's dimensions were interpreted.Deliberately avoids array jargon ("axis", "size-4"): the reader thinks inchannels / z-slices / timepoints, not numpy axes."""# lines = [f"Detected shape: {info.shape}"]if info.frames >1:lines = [f"Detected {info.channels}-channel {info.frames}-frame image stack of size {info.width}Γ{info.height}."]else:lines = [f"Detected {info.channels}-channel image of size {info.width}Γ{info.height}."]if info.channels >= 3:lines.append(f"Loaded as 3-channel RGB image.")elif info.channels == 2:lines.append(f"Loaded as 2-channel image (red, green).")else:lines.append(f"Loaded as single-channel grayscale image.")if info.frames > 1:lines.append(f"Showing first frame by default (you can use the stack frame slider to pick another).")lines.append("If wrong, please convert your image to a 8-bit RGB/Grayscale image file before uploading (there are available tools such as ImageJ/Fiji).")return "<br>".join(lines)def prepare_uploaded_image(annot_value):"""On annotator upload: standardize frame 0 for preview and configure thestack frame slider.Browsers cannot render 16-bit / float / multi-page TIFFs, so we standardizeto an 8-bit RGB PNG. If the file is a stack, notify the user and reveal aframe slider (default frame 1); otherwise keep it hidden.Returns (annotator_value, raw_path, frame_slider_update)."""img_path = _annot_path(annot_value)if not img_path:return annot_value, None, gr.update(visible=False, value=1)# Guard before any pixels are read. On refusal clear the annotator so the# oversize file cannot be sent to inference.rejected = check_image(img_path)if rejected:gr.Warning(rejected, duration=None, title="β Cannot use this file")return None, None, gr.update(visible=False, value=1)info = inspect_image(img_path)display = standardize_image(img_path, frame=0)# Only speak up when something non-obvious happened: a dimension had to be# guessed, it is a stack, or channels are being dropped. A plain RGB or# grayscale image needs no explanation.if info.guessed or info.frames > 1 or info.channels > 3:gr.Info(_describe_read(info), duration=None, title="π Image Loading Info")slider = (gr.update(visible=True, maximum=info.frames, value=1) if info.frames > 1else gr.update(visible=False, value=1))return display, img_path, sliderdef select_frame(raw_path, frame_num):"""Re-render the annotator preview for the chosen stack frame (1-based)."""if not raw_path:return gr.update()return standardize_image(raw_path, frame=int(frame_num) - 1)@spaces.GPUdef segment_with_choice(use_box_choice, annot_value, overlay_alpha):"""Segmentation handler - supports bounding box, returns colorized overlay and original mask path"""5 unmodified linesbboxes = annot_value[1] if len(annot_value) > 1 else []print(f"πΌοΈ Image path: {img_path}")# One standardized image for both the model and the overlay (WYSIWYG).img_path = standardize_image(img_path)print(f"π§ͺ Standardized image: {img_path}")box_array = Noneif use_box_choice == "Yes" and bboxes:box = parse_bboxes(bboxes)49 unmodified lines"""Counting handler - supports bounding box, returns only density map"""if annot_value is None or len(annot_value) < 1:return None, None, "β οΈ Please provide an image.", {}image_path = annot_value[0]bboxes = annot_value[1] if len(annot_value) > 1 else []print(f"πΌοΈ Image path: {image_path}")# One standardized image for both the model and the overlay (WYSIWYG).image_path = standardize_image(image_path)print(f"π§ͺ Standardized image: {image_path}")box_array = Noneif use_box_choice == "Yes" and bboxes:box = parse_bboxes(bboxes)if box:box_array = boxprint(f"π¦ Using bounding boxes: {box_array}")try:print(f"π’ Counting - Image: {image_path}")device = torch.device("cuda" if torch.cuda.is_available() else "cpu")result = run_count(COUNT_MODEL,633 unmodified lines/* ββ Labels ββββββββββββββββββββββββββββββββββββββββββββ */label { font-weight: 500 !important; color: #374151 !important; }/* File/media title pills use .block-label on a <label>, so the rule aboveforces their text dark. Restore the theme color/weight so they match theother native labels (e.g. "Overlay Opacity"). */.block-label,.block-label span {color: var(--block-label-text-color) !important;font-weight: var(--block-label-text-weight) !important;}/* ββ Collapsible "Image requirements" accordion βββββββββ *//* The label is a <button class="label-wrap"> whose text sits in an inner <span>.Gradio styles that span directly:span.svelte-xxx { font-weight: var(--section-header-text-weight); // = 400font-size: var(--section-header-text-size); }so font-size/weight set on the button is overridden and has no effect - thespan itself must be targeted. Colour is not set on the span, so it inherits. */.req-accordion .label-wrap {color: var(--block-label-text-color) !important;}.req-accordion .label-wrap span:not(.icon) {font-size: 0.9rem !important;font-weight: 700 !important;color: inherit !important;}/* ββ Frame headings (labels above media frames) ββββββββ *//* Neutralize the Gradio block wrapper so it doesn't clip/round the pill */.frame-heading {/* The column has a 16px flex gap; pull the pill back down so it sitsclose to the frame below instead of floating far above it. */margin-bottom: -8px !important;padding: 0 !important;min-width: 0 !important;min-height: 0 !important;background: transparent !important;border: none !important;box-shadow: none !important;border-radius: 0 !important;overflow: visible !important;}/* Match the theme's native field labels (e.g. "Overlay Opacity","Download Original Prediction") exactly: same colors, borderless, fullyrounded β driven by theme variables so it adapts to light/dark mode. */.frame-heading p {display: inline-block !important;width: fit-content !important;background: var(--block-label-background-fill) !important;color: var(--block-label-text-color) !important;border: none !important;border-radius: var(--block-label-radius) !important;font-weight: var(--block-label-text-weight) !important;font-size: var(--block-label-text-size) !important;line-height: 1.3 !important;padding: 5px 12px !important;margin: 0 !important;}/* ββ Image output ββββββββββββββββββββββββββββββββββββββ */.uniform-height {height: 480px !important;106 unmodified lines.dark label {color: #cbd5e1 !important;}.dark .block-label,.dark .block-label span {color: var(--block-label-text-color) !important;font-weight: var(--block-label-text-weight) !important;}/* ββ Image output area βββββββββββββββββββββββββββββββββ */.dark .uniform-height {24 unmodified linesprimary_hue=gr.themes.colors.sky,secondary_hue=gr.themes.colors.slate,neutral_hue=gr.themes.colors.slate,# Weights must be loaded to be usable: GoogleFont defaults to (400, 600),# so any font-weight above 600 silently falls back. Inter tops out at 900;# anything higher is dropped by Google Fonts without an error.font=gr.themes.GoogleFont("Inter", weights=(400, 600, 700, 800)),),css=CSS,) as demo:18 unmodified lines)# ε ¨ε±ηΆζ# Must be a callable: gr.State deepcopies a plain value, so str(uuid4())# would be evaluated once at construction and every session would share the# same id. A callable is re-run on each app load, giving one id per session.current_query_id = gr.State(lambda: str(uuid.uuid4()))user_uploaded_examples = gr.State(example_images_seg.copy())seg_vis_state = gr.State({})count_vis_state = gr.State({})track_vis_state = gr.State({})# Raw uploaded path, kept so a different stack frame can be re-extracted# (the annotator only holds the already-flattened preview PNG).seg_raw_state = gr.State(None)count_raw_state = gr.State(None)with gr.Tabs():# ===== Tab 1: Segmentation =====2 unmodified linesgr.Markdown("""**Instructions:**1. Select an example image from the Example Image Gallery or upload your own image (**Please see the "Image Upload Requirements" section below before uploading**)2. (Optional) Specify a target object with a bounding box and select "Yes", or click "Run Segmentation" directly3. Click "Run Segmentation"4. View the segmentation results (you can adjust the overlay opacity by sliding the opacity bar below the visualization), download the original predicted mask (.tif format); if needed, click "Clear Selection" to choose a new imageπ‘ Want to reuse an image? Upload it under "β Upload New Example Image to Gallery" and click "β Add to Gallery". The uploaded image will appear at the front of the gallery, and can be loaded by clicking its thumbnail. Gallery additions last for the current session only and are cleared when you reload the page.π€ Tell us about your experience by rating and submitting feedback, which would greatly help us improve the framework!""")# Reference material - collapsed by default. Must stay AFTER the# instructions markdown: the CSS styles it via .prose:nth-child(2).with gr.Accordion("π Image Upload Requirements (click to expand or fold)", open=False, elem_classes="req-accordion"):gr.Markdown("""**Please do not upload images or data containing protected health information (PHI) or personally identifiable information (PII).**- **Formats:** Supports TIFF / OME-TIFF (8/16/32-bit, stacks, multi-channel), PNG, JPG, as well as various other microscopy image formats supported by [tifffiles](https://github.com/cgohlke/tifffile)- **Maximum image size:** 4096 Γ 4096 pixels- **Channels:** Accepts RGB (3-channel), Grayscale (single-channel); for images with more than 3 channels, only the first three channels are used as RGB channels.- **For image stacks:** First frame is loaded by default; you can pick another with the stack frame slider that appears after upload**Alternatively, you can use existing tools (e.g., ImageJ/Fiji) to convert your image to a 8-bit RGB/Grayscale PNG/JPG/TIFF file before uploading.**""")with gr.Row():with gr.Column(scale=1):gr.Markdown("πΌοΈ Upload Image (Optional: Provide a Bounding Box)", elem_classes="frame-heading")annotator = BBoxAnnotator(show_label=False,categories=["cell"],)seg_frame_slider = gr.Slider(minimum=1, maximum=1, step=1, value=1,label="π Stack frame (choose frame to use)",visible=False,)# Example Images Gallerygr.Markdown("π Example Image Gallery", elem_classes="frame-heading")example_gallery = gr.Gallery(show_label=True,columns=len(example_images_seg),rows=1,height=120,13 unmodified linesclear_btn = gr.Button("π Clear Selection", variant="secondary")# Upload Example Imagegr.Markdown("β Upload New Example Image to Gallery", elem_classes="frame-heading")image_uploader = gr.File(show_label=False,file_types=["image", ".tif", ".tiff"],type="filepath")add_to_gallery_btn = gr.Button("β Add to Gallery", variant="secondary", size="sm")add_gallery_status = gr.Markdown(visible=False)with gr.Column(scale=2):gr.Markdown("πΈ Segmentation Result", elem_classes="frame-heading")seg_output = gr.Image(type="pil",show_label=False,elem_classes="uniform-height")seg_alpha_slider = gr.Slider(5 unmodified lines)# Download Original Predictiongr.Markdown("π₯ Download Original Prediction (.tif format)", elem_classes="frame-heading")download_mask_btn = gr.File(show_label=False,visible=True,height=40,)23 unmodified linesvisible=False)# standardize on upload (preview) + configure the stack frame sliderannotator.upload(fn=prepare_uploaded_image,inputs=annotator,outputs=[annotator, seg_raw_state, seg_frame_slider])# re-render the preview when the user picks a different stack frameseg_frame_slider.release(fn=select_frame,inputs=[seg_raw_state, seg_frame_slider],outputs=annotator)# click event for segmentationrun_seg_btn.click(fn=segment_with_choice,8 unmodified lines# click event for clear buttonclear_btn.click(fn=lambda: (None, {}, None, gr.update(visible=False, value=1)),inputs=None,outputs=[annotator, seg_vis_state, seg_raw_state, seg_frame_slider])# init Gallery with example images2 unmodified linesoutputs=example_gallery)# Add the uploaded image to the gallery on button click, confirm with# a status message, and clear the uploader so the upload box returns.def add_to_gallery(img_path, current_imgs):if not img_path:return (current_imgs, current_imgs,gr.update(value="β οΈ Please upload an image first.", visible=True), None)rejected = check_image(img_path)if rejected:return (current_imgs, current_imgs,gr.update(value=f"β {rejected}", visible=True), None)# Standardize to an 8-bit PNG so TIFFs render as gallery# thumbnails; prepend so it's immediately visible at the front.std_path = standardize_image(img_path)if std_path not in current_imgs:current_imgs.insert(0, std_path)return (current_imgs, current_imgs,gr.update(value="β Added to the Example Gallery below.", visible=True), None)add_to_gallery_btn.click(fn=add_to_gallery,inputs=[image_uploader, user_uploaded_examples],outputs=[user_uploaded_examples, example_gallery, add_gallery_status, image_uploader])# click event for Gallery selection (gallery entries are single-frame)def load_from_gallery(evt: gr.SelectData, all_imgs):if evt.index is not None and evt.index < len(all_imgs):item = all_imgs[evt.index]return standardize_image(item), item, gr.update(visible=False, value=1)return None, None, gr.update(visible=False, value=1)example_gallery.select(fn=load_from_gallery,inputs=user_uploaded_examples,outputs=[annotator, seg_raw_state, seg_frame_slider])# click event for submitting feedback33 unmodified linesgr.Markdown("""**Usage Instructions:**1. Select an example image from the Example Image Gallery or upload your own image (**Please see the "Image Upload Requirements" section below before uploading**)2. (Optional) Specify a target object with a bounding box and select "Yes", or click "Run Counting" directly3. Click "Run Counting"4. View the density map (you can adjust the density opacity by sliding the opacity bar below the visualization), download the original prediction (.npy format); if needed, click "Clear Selection" to choose a new image to runπ‘ Want to reuse an image? Upload it under "β Upload New Example Image to Gallery" and click "β Add to Gallery". The uploaded image will appear at the front of the gallery, and can be loaded by clicking its thumbnail. Gallery additions last for the current session only and are cleared when you reload the page.π€ Tell us about your experience by rating and submitting feedback, which would greatly help us improve the framework!""")# Reference material - collapsed by default. Must stay AFTER the# instructions markdown: the CSS styles it via .prose:nth-child(2).with gr.Accordion("π Image requirements", open=False, elem_classes="req-accordion"):gr.Markdown("""**Please do not upload images or data containing protected health information (PHI) or personally identifiable information (PII).**- **Formats:** Supports TIFF / OME-TIFF (8/16/32-bit, stacks, multi-channel), PNG, JPG, as well as various other microscopy image formats supported by [tifffiles](https://github.com/cgohlke/tifffile)- **Maximum image size:** 4096 Γ 4096 pixels- **Channels:** Accepts RGB (3-channel), Grayscale (single-channel); for images with more than 3 channels, only the first three channels are used as RGB channels.- **For image stacks:** First frame is loaded by default; you can pick another with the stack frame slider that appears after upload**Alternatively, you can use existing tools (e.g., ImageJ/Fiji) to convert your image to a 8-bit RGB/Grayscale PNG/JPG/TIFF file before uploading.**""")with gr.Row():with gr.Column(scale=1):gr.Markdown("πΌοΈ Upload Image (Optional: Provide a Bounding Box)", elem_classes="frame-heading")count_annotator = BBoxAnnotator(show_label=False,categories=["cell"],)count_frame_slider = gr.Slider(minimum=1, maximum=1, step=1, value=1,label="π Stack frame (choose frame to use)",visible=False,)# Example gallery with "add" functionalitygr.Markdown("π Example Image Gallery", elem_classes="frame-heading")with gr.Row():count_example_gallery = gr.Gallery(show_label=False,columns=len(example_images_cnt),rows=1,object_fit="cover",15 unmodified linesclear_btn = gr.Button("π Clear Selection", variant="secondary")# Add button to upload new examplesgr.Markdown("β Add Example Image to Gallery", elem_classes="frame-heading")count_image_uploader = gr.File(show_label=False,file_types=["image"],type="filepath")add_to_count_gallery_btn = gr.Button("β Add to Gallery", variant="secondary", size="sm")count_add_status = gr.Markdown(visible=False)with gr.Column(scale=2):gr.Markdown("πΈ Density Map", elem_classes="frame-heading")count_output = gr.Image(show_label=False,type="filepath",elem_id="density_map_output")count_alpha_slider = gr.Slider(minimum=0.0,6 unmodified lineslabel="π Statistics",lines=2)gr.Markdown("π₯ Download Original Prediction (.npy format)", elem_classes="frame-heading")download_density_btn = gr.File(show_label=False,visible=True)25 unmodified lines# State for managing gallery imagescount_user_examples = gr.State(example_images_cnt.copy())# Add the uploaded image to the gallery on button click, confirm with# a status message, and clear the uploader afterward.def add_to_count_gallery(new_img_file, current_imgs):"""Add uploaded image to gallery"""if new_img_file is None:return (current_imgs, current_imgs,gr.update(value="β οΈ Please upload an image first.", visible=True), None)rejected = check_image(new_img_file)if rejected:return (current_imgs, current_imgs,gr.update(value=f"β {rejected}", visible=True), None)# Standardize to an 8-bit PNG so TIFFs render as gallery# thumbnails; prepend so it's immediately visible at the front.std_path = standardize_image(new_img_file)if std_path not in current_imgs:current_imgs.insert(0, std_path)print(f"β Added image to gallery: {std_path}")return (current_imgs, current_imgs,gr.update(value="β Added to the Example Gallery above.", visible=True), None)# When user clicks "Add to Gallery"add_to_count_gallery_btn.click(fn=add_to_count_gallery,inputs=[count_image_uploader, count_user_examples],outputs=[count_user_examples, count_example_gallery, count_add_status, count_image_uploader])# standardize on upload (preview) + configure the stack frame slidercount_annotator.upload(fn=prepare_uploaded_image,inputs=count_annotator,outputs=[count_annotator, count_raw_state, count_frame_slider])# re-render the preview when the user picks a different stack framecount_frame_slider.release(fn=select_frame,inputs=[count_raw_state, count_frame_slider],outputs=count_annotator)# When user selects from gallery, load into annotator (single-frame)def load_from_count_gallery(evt: gr.SelectData, all_imgs):"""Load selected image from gallery into annotator"""if evt.index is not None and evt.index < len(all_imgs):selected_img = all_imgs[evt.index]print(f"πΈ Loading image from gallery: {selected_img}")return standardize_image(selected_img), selected_img, gr.update(visible=False, value=1)return None, None, gr.update(visible=False, value=1)count_example_gallery.select(fn=load_from_count_gallery,inputs=count_user_examples,outputs=[count_annotator, count_raw_state, count_frame_slider])# Run countingcount_btn.click(fn=count_cells_handler,8 unmodified lines# Clear selectionclear_btn.click(fn=lambda: (None, {}, None, gr.update(visible=False, value=1)),inputs=None,outputs=[count_annotator, count_vis_state, count_raw_state, count_frame_slider])# Submit feedback33 unmodified linesgr.Markdown("""**Instructions:**1. Select a video from the example library or Upload your own video ZIP file. The ZIP should contain a sequence of TIF images named in chronological order (e.g., t000.tif, t001.tif...)2. (Optional) Specify a target object with a bounding box on the first frame and select "Yes", or click "Run Tracking" directly3. Click "Run Tracking"4. View the tracking results (you can adjust the overlay opacity by sliding the opacity bar below the visualization), download the CTC format results; if needed, click "Clear Selection" to choose a new ZIP file to runπ‘ Want to reuse a video? Upload the ZIP under "β Upload New Example Image to Gallery" and click "β Add to Gallery". The uploaded video will appear at the front of the gallery, and can be loaded by clicking its thumbnail. Gallery additions last for the current session only and are cleared when you reload the page.π€ Tell us about your experience by rating and submitting feedback, which would greatly help us improve the framework!""")with gr.Row():with gr.Column(scale=1):gr.Markdown("π¦ Upload Image Sequence in ZIP File", elem_classes="frame-heading")track_zip_upload = gr.File(show_label=False,file_types=[".zip"])# First frame annotation for bounding box (heading + annotator# share one column so they show/hide together)with gr.Column(visible=False) as track_annot_group:gr.Markdown("πΌοΈ (Optional) First Frame Bounding Box Annotation", elem_classes="frame-heading")track_first_frame_annotator = BBoxAnnotator(show_label=False,categories=["cell"],)# Example ZIP gallerygr.Markdown("π Example Video Gallery (Click to Select)", elem_classes="frame-heading")track_example_gallery = gr.Gallery(show_label=False,columns=10,rows=1,height=120,13 unmodified linesclear_btn = gr.Button("π Clear Selection", variant="secondary")# Add to gallery buttongr.Markdown("β Add ZIP to Example Gallery", elem_classes="frame-heading")track_gallery_upload = gr.File(show_label=False,file_types=[".zip"],type="filepath")with gr.Column(scale=2):gr.Markdown("πΈ Tracking Visualization", elem_classes="frame-heading")track_first_frame_preview = gr.Image(show_label=False,type="filepath",# height=400,elem_classes="uniform-height",13 unmodified linesinteractive=False)# heading + download share one column so they show/hide togetherwith gr.Column(visible=False) as track_dl_group:gr.Markdown("π₯ Download Tracking Results (CTC Format)", elem_classes="frame-heading")track_download = gr.File(show_label=False,)# Satisfaction ratingscore_slider = gr.Slider(191 unmodified linestrack_zip_upload.change(fn=load_first_frame_for_annotation,inputs=track_zip_upload,outputs=[track_first_frame_annotator, track_annot_group])# Run trackingtrack_btn.click(fn=track_video_handler,inputs=[track_use_box_radio, track_first_frame_annotator, track_zip_upload, track_alpha_slider, track_vis_state],outputs=[track_download, track_output, track_dl_group, track_first_frame_preview, track_vis_state])track_alpha_slider.change(fn=update_tracking_overlay_alpha,48 unmodified linesshare=False,ssr_mode=False,show_error=True,# Deliberately no max_file_size: a transport-layer 413 is silent in the# annotator (we never get to run, so we cannot show a message), and file# size is a poor proxy anyway - a 1344x1024 time-lapse can be 256MB while# a 4096x4096 RGB is only 50MB. Size is checked in check_image()# instead, where a real message can be shown.)
_utils/image_io.pyAdded+358
app.py+455-113