patchkori 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,666 @@
1
+ from __future__ import annotations
2
+ from pathlib import Path
3
+ from typing import Any
4
+ import gradio as gr
5
+ import numpy as np
6
+ from PIL import Image, ImageDraw
7
+
8
+ from patchkori.config import AppConfig
9
+ from patchkori.core.models import (
10
+ CropRequest,
11
+ PyramidMetadata,
12
+ translate_box_between_levels,
13
+ )
14
+ from patchkori.core.pyramidal_cropper.adapter import PyramidalCropperAdapter
15
+ from patchkori.core.sample_generator import generate_sample_pyramidal_ome_tiff
16
+ from patchkori.ui.icons import (
17
+ ICON_CHANNELS,
18
+ ICON_CROP,
19
+ ICON_CUT,
20
+ ICON_DRAW,
21
+ ICON_LAYERS,
22
+ ICON_MAXIMIZE,
23
+ ICON_MICROSCOPE,
24
+ ICON_PLAY,
25
+ )
26
+ from patchkori.ui.registry import BaseBioTool, ToolRegistry
27
+
28
+
29
+ def make_editor_dict(img: np.ndarray | None) -> dict[str, Any] | None:
30
+ """Helper to return a valid Gradio 5.x ImageEditor value dictionary."""
31
+ if img is None:
32
+ return None
33
+ return {"background": img, "layers": [], "composite": img}
34
+
35
+
36
+ def draw_roi_overlay(
37
+ rgb_thumb: np.ndarray | None,
38
+ meta: PyramidMetadata | None,
39
+ target_level_idx: int,
40
+ x: int,
41
+ y: int,
42
+ w: int,
43
+ h: int,
44
+ mode: str = "single_roi",
45
+ tile_size: int = 256,
46
+ tile_overlap: int = 0,
47
+ ) -> np.ndarray | None:
48
+ """Renders the active ROI bounding box (and optional tile grid lines) onto the thumbnail."""
49
+ if rgb_thumb is None or meta is None:
50
+ return rgb_thumb
51
+
52
+ lvl = meta.get_level(target_level_idx)
53
+ scale_x = meta.thumb_width / max(lvl.width, 1)
54
+ scale_y = meta.thumb_height / max(lvl.height, 1)
55
+
56
+ tx0 = max(0, min(int(round(x * scale_x)), meta.thumb_width - 1))
57
+ ty0 = max(0, min(int(round(y * scale_y)), meta.thumb_height - 1))
58
+ tx1 = max(tx0 + 1, min(int(round((x + w) * scale_x)), meta.thumb_width))
59
+ ty1 = max(ty0 + 1, min(int(round((y + h) * scale_y)), meta.thumb_height))
60
+
61
+ pil_img = Image.fromarray(rgb_thumb.copy())
62
+ draw = ImageDraw.Draw(pil_img)
63
+
64
+ # Optional subtle tile grid overlay
65
+ if mode == "tile_grid" and tile_size > 0:
66
+ step = max(1, tile_size - max(0, tile_overlap))
67
+ for gx in range(int(x), int(x + w), step):
68
+ px = int(round(gx * scale_x))
69
+ draw.line([(px, ty0), (px, ty1)], fill=(0, 220, 255), width=1)
70
+ for gy in range(int(y), int(y + h), step):
71
+ py = int(round(gy * scale_y))
72
+ draw.line([(tx0, py), (tx1, py)], fill=(0, 220, 255), width=1)
73
+
74
+ # Outer bounding box
75
+ draw.rectangle([tx0, ty0, tx1, ty1], outline=(0, 255, 160), width=3)
76
+ return np.asarray(pil_img, dtype=np.uint8)
77
+
78
+
79
+ def extract_box_from_editor_layers(
80
+ editor_data: dict[str, Any] | None,
81
+ meta: PyramidMetadata | None,
82
+ target_level_idx: int,
83
+ ) -> tuple[int, int, int, int] | None:
84
+ """
85
+ Extracts drawn bounding box from Gradio ImageEditor layers (hand-drawn box/mask)
86
+ and maps it back to pixel coordinates at target_level.
87
+ """
88
+ if not editor_data or not isinstance(editor_data, dict) or meta is None:
89
+ return None
90
+
91
+ layers = editor_data.get("layers", [])
92
+ if not layers:
93
+ return None
94
+
95
+ lvl = meta.get_level(target_level_idx)
96
+ all_alphas = []
97
+ for layer in layers:
98
+ layer_arr = np.asarray(layer)
99
+ if layer_arr.ndim == 3 and layer_arr.shape[2] == 4:
100
+ all_alphas.append(layer_arr[:, :, 3])
101
+ elif layer_arr.ndim == 2:
102
+ all_alphas.append(layer_arr)
103
+
104
+ if not all_alphas:
105
+ return None
106
+
107
+ combined_mask = np.maximum.reduce(all_alphas)
108
+ nonzeros = np.argwhere(combined_mask > 20)
109
+ if nonzeros.size == 0:
110
+ return None
111
+
112
+ y_min, x_min = nonzeros.min(axis=0)
113
+ y_max, x_max = nonzeros.max(axis=0)
114
+
115
+ thumb_h, thumb_w = combined_mask.shape[:2]
116
+ x_lvl, y_lvl, w_lvl, h_lvl = translate_box_between_levels(
117
+ x_src=int(x_min),
118
+ y_src=int(y_min),
119
+ w_src=int(max(1, x_max - x_min)),
120
+ h_src=int(max(1, y_max - y_min)),
121
+ src_width=thumb_w,
122
+ src_height=thumb_h,
123
+ dst_level=lvl,
124
+ )
125
+ return x_lvl, y_lvl, w_lvl, h_lvl
126
+
127
+
128
+ def format_metadata_html(meta: PyramidMetadata) -> str:
129
+ """
130
+ Renders PyramidMetadata as clean, non-breaking HTML:
131
+ 1. Table of Pyramid Levels (L0, L1, ...) with white-space: nowrap (no awkward text breaks).
132
+ 2. Dataset Details key-value row (File, Format, Storage Axes, Total Channels).
133
+ 3. Channel tags grid.
134
+ Zero unparsed markdown asterisks (**).
135
+ """
136
+ rows = []
137
+ for lvl in meta.levels:
138
+ tile_str = f"{lvl.tile_width}×{lvl.tile_height}" if lvl.is_tiled else "Striped"
139
+ rows.append(
140
+ f"""<tr>
141
+ <td><span class="pk-lvl-badge">L{lvl.level_index}</span></td>
142
+ <td><span class="pk-code-pill">{lvl.width} × {lvl.height} px</span></td>
143
+ <td>{lvl.channels}</td>
144
+ <td><span class="pk-code-pill">{lvl.dtype}</span></td>
145
+ <td>{lvl.downsample_factor:.1f}×</td>
146
+ <td>{tile_str}</td>
147
+ <td>~{lvl.estimated_ram_mb:.1f} MB</td>
148
+ </tr>"""
149
+ )
150
+
151
+ table_rows = "\n".join(rows)
152
+ channel_tags = "".join(f'<span class="pk-channel-tag">{ch}</span>' for ch in meta.channel_names)
153
+
154
+ return f"""
155
+ <div class="pk-section-header">{ICON_LAYERS} Pyramid Levels Overview</div>
156
+ <div class="pk-table-wrap">
157
+ <table class="pk-meta-table">
158
+ <thead>
159
+ <tr>
160
+ <th>Level</th>
161
+ <th>Dimensions (W × H)</th>
162
+ <th>Channels</th>
163
+ <th>Dtype</th>
164
+ <th>Downsample</th>
165
+ <th>Tiled</th>
166
+ <th>Est. RAM</th>
167
+ </tr>
168
+ </thead>
169
+ <tbody>
170
+ {table_rows}
171
+ </tbody>
172
+ </table>
173
+ </div>
174
+
175
+ <div class="pk-section-header" style="margin-top:14px;">{ICON_CHANNELS} Dataset Details & Channel Listing</div>
176
+ <div class="pk-details-grid">
177
+ <div class="pk-detail-item"><strong>File:</strong> <span class="pk-code-pill">{meta.file_path.name}</span></div>
178
+ <div class="pk-detail-item"><strong>Format:</strong> <span class="pk-code-pill">{meta.format_name}</span></div>
179
+ <div class="pk-detail-item"><strong>Storage Axes:</strong> <span class="pk-code-pill">{meta.axes}</span></div>
180
+ <div class="pk-detail-item"><strong>Total Channels:</strong> {len(meta.channel_names)}</div>
181
+ </div>
182
+
183
+ <div style="font-size:0.83rem; font-weight:600; color:var(--pk-text-primary); margin-bottom:4px;">Available Channels / Markers:</div>
184
+ <div class="pk-channel-cloud">
185
+ {channel_tags}
186
+ </div>
187
+ """
188
+
189
+
190
+ @ToolRegistry.register
191
+ class PyramidalCropperTool(BaseBioTool):
192
+ tool_id = "pyramidal-cropper"
193
+ title = "Pyramidal Cropper"
194
+ icon = ICON_MICROSCOPE
195
+ description = (
196
+ "Out-of-core patch & tile extraction kit for gigapixel biological image datasets "
197
+ "(OME-TIFF, QPTIFF, Pyramidal TIFF)."
198
+ )
199
+ order = 10
200
+
201
+ def __init__(self) -> None:
202
+ self.adapter = PyramidalCropperAdapter()
203
+ self.cfg = AppConfig.from_env()
204
+
205
+ def _ensure_sample_file(self) -> Path:
206
+ sample_path = self.cfg.sample_data_dir / "sample_tonsil_pyramidal.ome.tif"
207
+ if not sample_path.exists():
208
+ generate_sample_pyramidal_ome_tiff(sample_path)
209
+ return sample_path
210
+
211
+ def build_ui(self, is_demo_mode: bool = False) -> None:
212
+ meta_state = gr.State(None)
213
+ raw_thumb_state = gr.State(None)
214
+
215
+ with gr.Row():
216
+ # LEFT COLUMN: Ingestion, Crop & Tiling Parameters, then Levels & Channels
217
+ with gr.Column(scale=4):
218
+ gr.HTML(f"""<div class="pk-section-header">{ICON_MICROSCOPE} 1. Image & Marker Configuration</div>""")
219
+ local_path_input = gr.Textbox(
220
+ label="Local File Path (OME-TIFF / QPTIFF / Pyramidal TIFF)",
221
+ placeholder="/path/to/whole_slide.ome.tif",
222
+ interactive=not is_demo_mode,
223
+ info=(
224
+ "Disabled in Cloud Demo Mode (use Sample or Upload below)."
225
+ if is_demo_mode
226
+ else "Zero-copy local path reading — no browser upload required."
227
+ ),
228
+ )
229
+
230
+ markerlist_input = gr.Textbox(
231
+ label="Optional: markerlist.txt Path (Channel Names)",
232
+ placeholder="/path/to/markerlist.txt (one marker per line)",
233
+ interactive=not is_demo_mode,
234
+ info="If provided, replaces default indices with your actual marker names.",
235
+ )
236
+
237
+ with gr.Row():
238
+ load_sample_btn = gr.Button("🧪 Load Sample Dataset", size="sm")
239
+ inspect_btn = gr.Button("🔍 Inspect Pyramid", variant="primary", size="sm")
240
+
241
+ with gr.Accordion("Optional: Upload Image or markerlist.txt", open=is_demo_mode):
242
+ upload_image = gr.File(
243
+ label="Upload Pyramidal TIFF / OME-TIFF (<200 MB)",
244
+ file_types=[".tif", ".tiff", ".qptiff"],
245
+ type="filepath",
246
+ )
247
+ upload_markerlist = gr.File(
248
+ label="Upload markerlist.txt / .csv",
249
+ file_types=[".txt", ".csv", ".tsv"],
250
+ type="filepath",
251
+ )
252
+
253
+ # 2. Crop & Tiling Parameters (Placed ABOVE Target Level & Channels)
254
+ gr.HTML(f"""<div class="pk-section-header">{ICON_CROP} 2. Crop & Tiling Parameters</div>""")
255
+ mode_radio = gr.Radio(
256
+ label="Extraction Mode",
257
+ choices=[
258
+ ("Single Bounding-Box ROI", "single_roi"),
259
+ ("Sliding-Window Tile Grid", "tile_grid"),
260
+ ],
261
+ value="single_roi",
262
+ )
263
+ with gr.Row():
264
+ x_input = gr.Number(label="X (px at Target Level)", value=0, precision=0)
265
+ y_input = gr.Number(label="Y (px at Target Level)", value=0, precision=0)
266
+ with gr.Row():
267
+ w_input = gr.Number(label="Width (px)", value=256, precision=0)
268
+ h_input = gr.Number(label="Height (px)", value=256, precision=0)
269
+
270
+ with gr.Row(visible=False) as tile_grid_row:
271
+ tile_size_input = gr.Number(label="Tile Size (px)", value=256, precision=0)
272
+ tile_overlap_input = gr.Number(label="Tile Overlap (px)", value=0, precision=0)
273
+
274
+ # 3. Target Level & Channels (Placed BELOW Crop & Tiling Parameters)
275
+ gr.HTML(f"""<div class="pk-section-header">{ICON_LAYERS} 3. Target Level & Channels</div>""")
276
+ level_dropdown = gr.Dropdown(
277
+ label="Target Extraction Pyramid Level",
278
+ choices=[],
279
+ interactive=True,
280
+ )
281
+
282
+ channels_dropdown = gr.Dropdown(
283
+ label="Channels to Extract (Multi-Select Dropdown)",
284
+ choices=[],
285
+ multiselect=True,
286
+ interactive=True,
287
+ info="Pick any subset of channels. If empty, all channels are extracted.",
288
+ )
289
+
290
+ # CENTER COLUMN: Interactive Preview & Metadata Table
291
+ with gr.Column(scale=5):
292
+ gr.HTML(
293
+ f"""
294
+ <div class="pk-section-header">{ICON_DRAW} Interactive Canvas & ROI Selection</div>
295
+ <div class="pk-canvas-instructions">
296
+ <strong>How to crop:</strong> Draw a box/mask with the green brush tool on the canvas below and click <strong>Apply Hand-Drawn Box</strong>, or click <strong>Full Level ROI</strong>.
297
+ </div>
298
+ """
299
+ )
300
+
301
+ # Action buttons placed directly ABOVE the image box with clean spacing
302
+ with gr.Row(elem_classes=["pk-action-row"]):
303
+ full_level_btn = gr.Button("📐 Full Level ROI", size="sm")
304
+ apply_drawn_roi_btn = gr.Button("✏️ Apply Hand-Drawn Box", size="sm", variant="secondary")
305
+
306
+ # show_label=False prevents Gradio from placing a label under the floating toolbar
307
+ with gr.Group(elem_classes=["pk-image-editor-wrap"]):
308
+ editor_preview = gr.ImageEditor(
309
+ show_label=False,
310
+ type="numpy",
311
+ interactive=True,
312
+ height=440,
313
+ brush=gr.Brush(colors=["#00FFA0"], default_size=12),
314
+ )
315
+
316
+ # Metadata table and channel list placed below the image box
317
+ with gr.Group(elem_classes=["pk-metadata-card"]):
318
+ metadata_md = gr.HTML(
319
+ """<div style="font-size:0.86rem; color:var(--pk-text-secondary); text-align:center; padding:12px 0;">
320
+ Click <strong>Load Sample Dataset</strong> or enter a file path and click <strong>Inspect Pyramid</strong> to view pyramid levels and channels.
321
+ </div>"""
322
+ )
323
+
324
+ # RIGHT COLUMN: Output Settings, Execution & Gallery
325
+ with gr.Column(scale=4):
326
+ gr.HTML(f"""<div class="pk-section-header">{ICON_CUT} 4. Extraction & Execution</div>""")
327
+ output_dir_input = gr.Textbox(
328
+ label="Local Output Directory",
329
+ value=str(self.cfg.default_output_dir),
330
+ interactive=not is_demo_mode,
331
+ )
332
+ with gr.Row():
333
+ output_format_dropdown = gr.Dropdown(
334
+ label="Output Format",
335
+ choices=["ome.tif", "tif", "png", "zarr"],
336
+ value="ome.tif",
337
+ )
338
+ prefix_input = gr.Textbox(label="Filename Prefix", value="crop")
339
+
340
+ zip_checkbox = gr.Checkbox(
341
+ label="Create downloadable .zip archive",
342
+ value=is_demo_mode,
343
+ )
344
+ run_crop_btn = gr.Button("✂️ Run Out-of-Core Crop", variant="primary")
345
+ status_md = gr.Markdown("")
346
+ gallery_output = gr.Gallery(
347
+ label="Extracted Patch Quick Previews",
348
+ columns=2,
349
+ height=320,
350
+ preview=True,
351
+ )
352
+ zip_download = gr.File(
353
+ label="Download Cropped Bundle (.zip)",
354
+ visible=True,
355
+ )
356
+
357
+ # --- Callbacks ---
358
+ def on_load_sample() -> str:
359
+ sample = self._ensure_sample_file()
360
+ return str(sample)
361
+
362
+ def on_inspect(
363
+ local_path: str,
364
+ uploaded_image: str | None,
365
+ local_markerlist: str,
366
+ uploaded_markerlist: str | None,
367
+ ) -> tuple[Any, ...]:
368
+ target_path_str = (uploaded_image or "").strip() or (local_path or "").strip()
369
+ if not target_path_str:
370
+ sample = self._ensure_sample_file()
371
+ target_path_str = str(sample)
372
+
373
+ marker_path_str = (uploaded_markerlist or "").strip() or (local_markerlist or "").strip() or None
374
+
375
+ meta, rgb_thumb = self.adapter.inspect(
376
+ target_path_str,
377
+ max_thumb_edge=self.cfg.max_thumb_edge,
378
+ markerlist_path=marker_path_str,
379
+ )
380
+ level_choices = [(lvl.label, lvl.level_index) for lvl in meta.levels]
381
+ base_lvl = meta.levels[0]
382
+
383
+ default_x = int(base_lvl.width * 0.25)
384
+ default_y = int(base_lvl.height * 0.25)
385
+ default_w = max(64, int(base_lvl.width * 0.5))
386
+ default_h = max(64, int(base_lvl.height * 0.5))
387
+
388
+ overlay = draw_roi_overlay(
389
+ rgb_thumb, meta, 0, default_x, default_y, default_w, default_h
390
+ )
391
+ md_table = format_metadata_html(meta)
392
+ editor_val = make_editor_dict(overlay)
393
+
394
+ return (
395
+ meta,
396
+ rgb_thumb,
397
+ target_path_str,
398
+ gr.update(choices=level_choices, value=0),
399
+ gr.update(choices=meta.channel_names, value=meta.channel_names),
400
+ default_x,
401
+ default_y,
402
+ default_w,
403
+ default_h,
404
+ editor_val,
405
+ md_table,
406
+ )
407
+
408
+ def on_update_overlay(
409
+ meta: PyramidMetadata | None,
410
+ rgb_thumb: np.ndarray | None,
411
+ level_idx: int | None,
412
+ x: float,
413
+ y: float,
414
+ w: float,
415
+ h: float,
416
+ mode: str,
417
+ tile_size: float,
418
+ tile_overlap: float,
419
+ ) -> dict[str, Any] | None:
420
+ if meta is None or rgb_thumb is None or level_idx is None:
421
+ return make_editor_dict(rgb_thumb)
422
+ overlay = draw_roi_overlay(
423
+ rgb_thumb,
424
+ meta,
425
+ int(level_idx),
426
+ int(x),
427
+ int(y),
428
+ int(w),
429
+ int(h),
430
+ mode=mode,
431
+ tile_size=int(tile_size),
432
+ tile_overlap=int(tile_overlap),
433
+ )
434
+ return make_editor_dict(overlay)
435
+
436
+ def on_apply_drawn_roi(
437
+ editor_data: dict[str, Any] | None,
438
+ meta: PyramidMetadata | None,
439
+ rgb_thumb: np.ndarray | None,
440
+ level_idx: int | None,
441
+ mode: str,
442
+ tile_size: float,
443
+ tile_overlap: float,
444
+ ) -> tuple[int, int, int, int, dict[str, Any] | None]:
445
+ if meta is None or level_idx is None:
446
+ return 0, 0, 256, 256, make_editor_dict(rgb_thumb)
447
+
448
+ extracted = extract_box_from_editor_layers(editor_data, meta, int(level_idx))
449
+ if extracted is None:
450
+ lvl = meta.get_level(int(level_idx))
451
+ return 0, 0, lvl.width, lvl.height, make_editor_dict(rgb_thumb)
452
+
453
+ x_box, y_box, w_box, h_box = extracted
454
+ overlay = draw_roi_overlay(
455
+ rgb_thumb,
456
+ meta,
457
+ int(level_idx),
458
+ x_box,
459
+ y_box,
460
+ w_box,
461
+ h_box,
462
+ mode=mode,
463
+ tile_size=int(tile_size),
464
+ tile_overlap=int(tile_overlap),
465
+ )
466
+ return x_box, y_box, w_box, h_box, make_editor_dict(overlay)
467
+
468
+ def on_full_level(
469
+ meta: PyramidMetadata | None,
470
+ rgb_thumb: np.ndarray | None,
471
+ level_idx: int | None,
472
+ mode: str,
473
+ tile_size: float,
474
+ tile_overlap: float,
475
+ ) -> tuple[int, int, int, int, dict[str, Any] | None]:
476
+ if meta is None or level_idx is None:
477
+ return 0, 0, 256, 256, make_editor_dict(rgb_thumb)
478
+ lvl = meta.get_level(int(level_idx))
479
+ overlay = draw_roi_overlay(
480
+ rgb_thumb,
481
+ meta,
482
+ int(level_idx),
483
+ 0,
484
+ 0,
485
+ lvl.width,
486
+ lvl.height,
487
+ mode=mode,
488
+ tile_size=int(tile_size),
489
+ tile_overlap=int(tile_overlap),
490
+ )
491
+ return 0, 0, lvl.width, lvl.height, make_editor_dict(overlay)
492
+
493
+ def on_mode_change(mode: str) -> dict[str, Any]:
494
+ return gr.update(visible=(mode == "tile_grid"))
495
+
496
+ def on_run_crop(
497
+ meta: PyramidMetadata | None,
498
+ level_idx: int | None,
499
+ selected_channels: list[str] | None,
500
+ mode: str,
501
+ x: float,
502
+ y: float,
503
+ w: float,
504
+ h: float,
505
+ tile_size: float,
506
+ tile_overlap: float,
507
+ output_dir: str,
508
+ output_format: str,
509
+ prefix: str,
510
+ create_zip: bool,
511
+ progress: gr.Progress = gr.Progress(),
512
+ ) -> tuple[str, list[str], str | None]:
513
+ if meta is None:
514
+ raise gr.Error("Please inspect a pyramidal image first.")
515
+
516
+ lvl_idx = int(level_idx or 0)
517
+ if selected_channels:
518
+ channel_indices = [
519
+ meta.channel_names.index(ch)
520
+ for ch in selected_channels
521
+ if ch in meta.channel_names
522
+ ]
523
+ else:
524
+ channel_indices = list(range(len(meta.channel_names)))
525
+
526
+ if not channel_indices:
527
+ channel_indices = list(range(len(meta.channel_names)))
528
+
529
+ req = CropRequest(
530
+ input_path=meta.file_path,
531
+ output_dir=Path(output_dir),
532
+ target_level=lvl_idx,
533
+ x=int(x),
534
+ y=int(y),
535
+ width=int(w),
536
+ height=int(h),
537
+ channel_indices=channel_indices,
538
+ mode="tile_grid" if mode == "tile_grid" else "single_roi",
539
+ tile_size=int(tile_size),
540
+ tile_overlap=int(tile_overlap),
541
+ output_format=output_format, # type: ignore[arg-type]
542
+ prefix=(prefix or "crop").strip(),
543
+ create_zip=bool(create_zip),
544
+ )
545
+
546
+ def _prog(frac: float, desc: str) -> None:
547
+ progress(frac, desc=desc)
548
+
549
+ result = self.adapter.execute_crop(req, progress_callback=_prog)
550
+ gallery_paths = [str(p) for p in result.preview_images]
551
+ zip_str = str(result.zip_path) if result.zip_path else None
552
+ return f"✅ {result.summary_message}", gallery_paths, zip_str
553
+
554
+ # Wire events
555
+ load_sample_btn.click(fn=on_load_sample, outputs=[local_path_input]).then(
556
+ fn=on_inspect,
557
+ inputs=[local_path_input, upload_image, markerlist_input, upload_markerlist],
558
+ outputs=[
559
+ meta_state,
560
+ raw_thumb_state,
561
+ local_path_input,
562
+ level_dropdown,
563
+ channels_dropdown,
564
+ x_input,
565
+ y_input,
566
+ w_input,
567
+ h_input,
568
+ editor_preview,
569
+ metadata_md,
570
+ ],
571
+ )
572
+
573
+ inspect_btn.click(
574
+ fn=on_inspect,
575
+ inputs=[local_path_input, upload_image, markerlist_input, upload_markerlist],
576
+ outputs=[
577
+ meta_state,
578
+ raw_thumb_state,
579
+ local_path_input,
580
+ level_dropdown,
581
+ channels_dropdown,
582
+ x_input,
583
+ y_input,
584
+ w_input,
585
+ h_input,
586
+ editor_preview,
587
+ metadata_md,
588
+ ],
589
+ )
590
+
591
+ mode_radio.change(fn=on_mode_change, inputs=[mode_radio], outputs=[tile_grid_row])
592
+
593
+ for ctrl in (
594
+ level_dropdown,
595
+ x_input,
596
+ y_input,
597
+ w_input,
598
+ h_input,
599
+ mode_radio,
600
+ tile_size_input,
601
+ tile_overlap_input,
602
+ ):
603
+ ctrl.change(
604
+ fn=on_update_overlay,
605
+ inputs=[
606
+ meta_state,
607
+ raw_thumb_state,
608
+ level_dropdown,
609
+ x_input,
610
+ y_input,
611
+ w_input,
612
+ h_input,
613
+ mode_radio,
614
+ tile_size_input,
615
+ tile_overlap_input,
616
+ ],
617
+ outputs=[editor_preview],
618
+ )
619
+
620
+ apply_drawn_roi_btn.click(
621
+ fn=on_apply_drawn_roi,
622
+ inputs=[
623
+ editor_preview,
624
+ meta_state,
625
+ raw_thumb_state,
626
+ level_dropdown,
627
+ mode_radio,
628
+ tile_size_input,
629
+ tile_overlap_input,
630
+ ],
631
+ outputs=[x_input, y_input, w_input, h_input, editor_preview],
632
+ )
633
+
634
+ full_level_btn.click(
635
+ fn=on_full_level,
636
+ inputs=[
637
+ meta_state,
638
+ raw_thumb_state,
639
+ level_dropdown,
640
+ mode_radio,
641
+ tile_size_input,
642
+ tile_overlap_input,
643
+ ],
644
+ outputs=[x_input, y_input, w_input, h_input, editor_preview],
645
+ )
646
+
647
+ run_crop_btn.click(
648
+ fn=on_run_crop,
649
+ inputs=[
650
+ meta_state,
651
+ level_dropdown,
652
+ channels_dropdown,
653
+ mode_radio,
654
+ x_input,
655
+ y_input,
656
+ w_input,
657
+ h_input,
658
+ tile_size_input,
659
+ tile_overlap_input,
660
+ output_dir_input,
661
+ output_format_dropdown,
662
+ prefix_input,
663
+ zip_checkbox,
664
+ ],
665
+ outputs=[status_md, gallery_output, zip_download],
666
+ )