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,476 @@
1
+ from __future__ import annotations
2
+ import time
3
+ import xml.etree.ElementTree as ET
4
+ import zipfile
5
+ from pathlib import Path
6
+ from typing import Any, Callable
7
+ import numpy as np
8
+ from PIL import Image
9
+ import tifffile
10
+ import zarr
11
+
12
+ from patchkori.core.models import (
13
+ CropRequest,
14
+ CropResult,
15
+ LevelInfo,
16
+ PyramidMetadata,
17
+ )
18
+
19
+
20
+ class PyramidalCropperAdapter:
21
+ """
22
+ Out-of-core pyramidal image inspector and patch/tile cropper.
23
+ Designed as a clean adapter interface that can either run its built-in
24
+ tifffile+zarr chunk streaming engine or delegate to an external
25
+ `pyramidal_cropper` callable if registered.
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ external_crop_fn: Callable[[CropRequest], list[Path]] | None = None,
31
+ ) -> None:
32
+ self._external_crop_fn = external_crop_fn
33
+
34
+ def inspect(
35
+ self,
36
+ image_path: str | Path,
37
+ max_thumb_edge: int = 1024,
38
+ markerlist_path: str | Path | None = None,
39
+ ) -> tuple[PyramidMetadata, np.ndarray]:
40
+ """
41
+ Lazily inspects pyramidal image headers (without loading full-resolution
42
+ planes into RAM) and renders an 8-bit RGB preview thumbnail from the
43
+ optimal low-resolution pyramid level.
44
+
45
+ If `markerlist_path` is provided, channel names will be parsed from this file
46
+ (one marker name per line, tab-separated, or comma-separated). Otherwise, names
47
+ are extracted from OME-XML/QPTIFF tags, falling back to indices 0, 1, 2, ...
48
+ """
49
+ path = Path(image_path).expanduser().resolve()
50
+ if not path.exists():
51
+ raise FileNotFoundError(f"Pyramidal image file not found: {path}")
52
+
53
+ with tifffile.TiffFile(path) as tif:
54
+ if not tif.series:
55
+ raise ValueError(f"No image series found in TIFF file: {path}")
56
+
57
+ series = tif.series[0]
58
+ axes = series.axes.upper()
59
+ levels_info: list[LevelInfo] = []
60
+
61
+ base_parsed = self._parse_shape(series.levels[0].shape, axes)
62
+ base_w, base_h, num_c = base_parsed["W"], base_parsed["H"], base_parsed["C"]
63
+
64
+ for idx, lvl in enumerate(series.levels):
65
+ parsed = self._parse_shape(lvl.shape, axes)
66
+ page0 = lvl.pages[0]
67
+ is_tiled = bool(getattr(page0, "is_tiled", False))
68
+ levels_info.append(
69
+ LevelInfo(
70
+ level_index=idx,
71
+ width=parsed["W"],
72
+ height=parsed["H"],
73
+ channels=parsed["C"],
74
+ dtype=str(lvl.dtype),
75
+ downsample_factor=round(base_w / max(parsed["W"], 1), 2),
76
+ is_tiled=is_tiled,
77
+ tile_width=int(page0.tilewidth) if is_tiled else None,
78
+ tile_height=int(page0.tilelength) if is_tiled else None,
79
+ )
80
+ )
81
+
82
+ # Pick the smallest pyramid level whose longest edge >= max_thumb_edge (or lowest level)
83
+ thumb_idx = len(series.levels) - 1
84
+ for lvl_info in reversed(levels_info):
85
+ if max(lvl_info.width, lvl_info.height) >= max_thumb_edge:
86
+ thumb_idx = lvl_info.level_index
87
+ break
88
+
89
+ raw_thumb = series.levels[thumb_idx].asarray()
90
+ rgb_thumb = self.array_to_uint8_rgb(raw_thumb, axes, max_edge=max_thumb_edge)
91
+
92
+ # Resolve channel names: markerlist > OME-XML > index numbers
93
+ channel_names = self._resolve_channel_names(
94
+ tif=tif,
95
+ num_c=num_c,
96
+ markerlist_path=markerlist_path,
97
+ )
98
+ fmt_name = (
99
+ "OME-TIFF"
100
+ if tif.is_ome
101
+ else ("QPTIFF" if getattr(tif, "is_qpi", False) else "Pyramidal TIFF")
102
+ )
103
+
104
+ metadata = PyramidMetadata(
105
+ file_path=path,
106
+ format_name=fmt_name,
107
+ axes=axes,
108
+ levels=levels_info,
109
+ channel_names=channel_names,
110
+ thumb_level_index=thumb_idx,
111
+ thumb_width=int(rgb_thumb.shape[1]),
112
+ thumb_height=int(rgb_thumb.shape[0]),
113
+ )
114
+ return metadata, rgb_thumb
115
+
116
+ def execute_crop(
117
+ self,
118
+ request: CropRequest,
119
+ progress_callback: Callable[[float, str], None] | None = None,
120
+ ) -> CropResult:
121
+ """
122
+ Streams only the compressed tiles overlapping the requested bounding box
123
+ or tile grid at `request.target_level` directly to disk.
124
+ """
125
+ t0 = time.perf_counter()
126
+ input_path = Path(request.input_path).expanduser().resolve()
127
+ output_dir = Path(request.output_dir).expanduser().resolve()
128
+ output_dir.mkdir(parents=True, exist_ok=True)
129
+ preview_dir = output_dir / "_previews"
130
+ preview_dir.mkdir(parents=True, exist_ok=True)
131
+
132
+ if self._external_crop_fn is not None:
133
+ output_files = self._external_crop_fn(request)
134
+ elapsed = time.perf_counter() - t0
135
+ return CropResult(
136
+ output_files=output_files,
137
+ preview_images=[],
138
+ zip_path=None,
139
+ target_level=request.target_level,
140
+ extracted_shape=(0,),
141
+ elapsed_seconds=round(elapsed, 3),
142
+ summary_message=f"External cropper wrote {len(output_files)} file(s).",
143
+ )
144
+
145
+ output_files: list[Path] = []
146
+ preview_images: list[Path] = []
147
+ last_shape: tuple[int, ...] = (0,)
148
+
149
+ with tifffile.TiffFile(input_path) as tif:
150
+ series = tif.series[0]
151
+ axes = series.axes.upper()
152
+ if not (0 <= request.target_level < len(series.levels)):
153
+ raise IndexError(
154
+ f"Target level {request.target_level} out of range (0..{len(series.levels) - 1})"
155
+ )
156
+
157
+ target_lvl = series.levels[request.target_level]
158
+ lvl_parsed = self._parse_shape(target_lvl.shape, axes)
159
+ lvl_w, lvl_h, lvl_c = lvl_parsed["W"], lvl_parsed["H"], lvl_parsed["C"]
160
+
161
+ channel_indices = (
162
+ [c for c in request.channel_indices if 0 <= c < lvl_c]
163
+ if request.channel_indices
164
+ else list(range(lvl_c))
165
+ )
166
+ if not channel_indices:
167
+ channel_indices = [0]
168
+
169
+ boxes = self._compute_boxes(request, lvl_w, lvl_h)
170
+ total_boxes = len(boxes)
171
+
172
+ store = series.aszarr()
173
+ z_root = zarr.open(store, mode="r")
174
+ if isinstance(z_root, zarr.Group):
175
+ z_arr = z_root[str(request.target_level)]
176
+ else:
177
+ z_arr = z_root
178
+
179
+ for i, (x0, y0, x1, y1) in enumerate(boxes):
180
+ if progress_callback:
181
+ progress_callback(
182
+ i / max(total_boxes, 1),
183
+ f"Streaming crop {i + 1}/{total_boxes} at Level {request.target_level}...",
184
+ )
185
+
186
+ patch, patch_axes = self._slice_zarr(
187
+ z_arr, axes, x0, y0, x1, y1, channel_indices
188
+ )
189
+ last_shape = tuple(int(s) for s in patch.shape)
190
+
191
+ stem = (
192
+ f"{request.prefix}_L{request.target_level}"
193
+ f"_x{x0}_y{y0}_w{x1 - x0}_h{y1 - y0}"
194
+ )
195
+ out_path = output_dir / f"{stem}.{request.output_format}"
196
+ self._save_patch(patch, patch_axes, out_path, request.output_format)
197
+ output_files.append(out_path)
198
+
199
+ # Always save a lightweight 8-bit PNG preview for the Gradio Gallery (optimized fast downsample)
200
+ if len(preview_images) < 24:
201
+ rgb_prev = self.array_to_uint8_rgb(patch, patch_axes, max_edge=256, fast=True)
202
+ prev_path = preview_dir / f"{stem}_prev.png"
203
+ Image.fromarray(rgb_prev).save(prev_path, format="PNG", optimize=False)
204
+ preview_images.append(prev_path)
205
+
206
+ if progress_callback:
207
+ progress_callback(1.0, f"Completed {len(output_files)} crop(s).")
208
+
209
+ zip_path: Path | None = None
210
+ if request.create_zip and output_files:
211
+ zip_path = output_dir / f"{request.prefix}_L{request.target_level}_bundle.zip"
212
+ with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
213
+ for fpath in output_files:
214
+ if fpath.is_file():
215
+ zf.write(fpath, arcname=fpath.name)
216
+
217
+ elapsed = time.perf_counter() - t0
218
+ summary = (
219
+ f"Extracted {len(output_files)} patch(es) at Level {request.target_level} "
220
+ f"(last shape: {last_shape}) to `{output_dir}` in {elapsed:.2f}s."
221
+ )
222
+ return CropResult(
223
+ output_files=output_files,
224
+ preview_images=preview_images,
225
+ zip_path=zip_path,
226
+ target_level=request.target_level,
227
+ extracted_shape=last_shape,
228
+ elapsed_seconds=round(elapsed, 3),
229
+ summary_message=summary,
230
+ )
231
+
232
+ @staticmethod
233
+ def _parse_shape(shape: tuple[int, ...], axes: str) -> dict[str, int]:
234
+ axes = axes.upper()
235
+ w = shape[axes.index("X")] if "X" in axes else shape[-1]
236
+ h = shape[axes.index("Y")] if "Y" in axes else shape[-2]
237
+ if "C" in axes:
238
+ c = shape[axes.index("C")]
239
+ elif "S" in axes:
240
+ c = shape[axes.index("S")]
241
+ else:
242
+ c = 1
243
+ return {"W": int(w), "H": int(h), "C": int(c)}
244
+
245
+ @classmethod
246
+ def _resolve_channel_names(
247
+ cls,
248
+ tif: tifffile.TiffFile,
249
+ num_c: int,
250
+ markerlist_path: str | Path | None = None,
251
+ ) -> list[str]:
252
+ # 1. Try markerlist file if provided
253
+ if markerlist_path:
254
+ m_path = Path(markerlist_path).expanduser().resolve()
255
+ if m_path.exists() and m_path.is_file():
256
+ try:
257
+ lines = m_path.read_text(encoding="utf-8", errors="replace").splitlines()
258
+ parsed_markers: list[str] = []
259
+ for line in lines:
260
+ clean = line.strip()
261
+ if not clean or clean.startswith("#"):
262
+ continue
263
+ # If comma or tab-separated, take tokens or primary column
264
+ tokens = [t.strip() for t in clean.replace("\t", ",").split(",") if t.strip()]
265
+ if tokens:
266
+ parsed_markers.append(tokens[0])
267
+ if parsed_markers:
268
+ # Pad or slice to num_c
269
+ if len(parsed_markers) >= num_c:
270
+ return [f"[{i}] {name}" for i, name in enumerate(parsed_markers[:num_c])]
271
+ padded = [f"[{i}] {name}" for i, name in enumerate(parsed_markers)]
272
+ for i in range(len(parsed_markers), num_c):
273
+ padded.append(f"[{i}] Channel_{i}")
274
+ return padded
275
+ except Exception:
276
+ pass
277
+
278
+ # 2. Try OME-XML metadata tags
279
+ extracted_ome = cls._extract_channel_names(tif, num_c)
280
+ if any(not name.startswith("Channel_") for name in extracted_ome):
281
+ return [f"[{i}] {name}" for i, name in enumerate(extracted_ome)]
282
+
283
+ # 3. Fallback strictly to index numbers: [0] Channel 0, [1] Channel 1, ...
284
+ return [f"[{i}] Channel {i}" for i in range(num_c)]
285
+
286
+ @staticmethod
287
+ def _extract_channel_names(tif: tifffile.TiffFile, num_c: int) -> list[str]:
288
+ if tif.is_ome and tif.ome_metadata:
289
+ try:
290
+ root = ET.fromstring(tif.ome_metadata)
291
+ names = [
292
+ elem.attrib.get("Name", "").strip()
293
+ for elem in root.iter()
294
+ if elem.tag.endswith("Channel")
295
+ ]
296
+ names = [n for n in names if n]
297
+ if len(names) >= num_c:
298
+ return names[:num_c]
299
+ except ET.ParseError:
300
+ pass
301
+ return [f"Channel_{i}" for i in range(num_c)]
302
+
303
+ @staticmethod
304
+ def _compute_boxes(
305
+ request: CropRequest, lvl_w: int, lvl_h: int
306
+ ) -> list[tuple[int, int, int, int]]:
307
+ x0 = max(0, min(int(request.x), lvl_w - 1))
308
+ y0 = max(0, min(int(request.y), lvl_h - 1))
309
+ w = max(1, min(int(request.width), lvl_w - x0))
310
+ h = max(1, min(int(request.height), lvl_h - y0))
311
+ roi_x1 = x0 + w
312
+ roi_y1 = y0 + h
313
+
314
+ if request.mode == "single_roi":
315
+ return [(x0, y0, roi_x1, roi_y1)]
316
+
317
+ tile_sz = max(16, int(request.tile_size))
318
+ overlap = max(0, min(int(request.tile_overlap), tile_sz - 1))
319
+ step = max(1, tile_sz - overlap)
320
+
321
+ boxes: list[tuple[int, int, int, int]] = []
322
+ for ty in range(y0, roi_y1, step):
323
+ for tx in range(x0, roi_x1, step):
324
+ bx1 = min(tx + tile_sz, roi_x1)
325
+ by1 = min(ty + tile_sz, roi_y1)
326
+ if (bx1 - tx) > 0 and (by1 - ty) > 0:
327
+ boxes.append((tx, ty, bx1, by1))
328
+ return boxes or [(x0, y0, roi_x1, roi_y1)]
329
+
330
+ @staticmethod
331
+ def _slice_zarr(
332
+ z_arr: Any,
333
+ axes: str,
334
+ x0: int,
335
+ y0: int,
336
+ x1: int,
337
+ y1: int,
338
+ channel_indices: list[int],
339
+ ) -> tuple[np.ndarray, str]:
340
+ """
341
+ Slices only the required chunk range and selected channels from the
342
+ Zarr-backed pyramid level (compatible with both Zarr v2 and Zarr v3).
343
+ """
344
+ axes = axes.upper()
345
+ if "C" in axes or "S" in axes:
346
+ c_axis_char = "C" if "C" in axes else "S"
347
+ planes: list[np.ndarray] = []
348
+ for c_idx in channel_indices:
349
+ slicers: list[Any] = []
350
+ for ax in axes:
351
+ if ax == "Y":
352
+ slicers.append(slice(y0, y1))
353
+ elif ax == "X":
354
+ slicers.append(slice(x0, x1))
355
+ elif ax == c_axis_char:
356
+ slicers.append(int(c_idx))
357
+ else:
358
+ slicers.append(0)
359
+ planes.append(np.asarray(z_arr[tuple(slicers)]))
360
+ patch = np.stack(planes, axis=0)
361
+ return patch, "CYX"
362
+
363
+ # Single-channel 2D (YX)
364
+ slicers_2d: list[Any] = []
365
+ for ax in axes:
366
+ if ax == "Y":
367
+ slicers_2d.append(slice(y0, y1))
368
+ elif ax == "X":
369
+ slicers_2d.append(slice(x0, x1))
370
+ else:
371
+ slicers_2d.append(0)
372
+ patch_2d = np.asarray(z_arr[tuple(slicers_2d)])
373
+ if patch_2d.ndim == 2:
374
+ patch_2d = patch_2d[np.newaxis, :, :]
375
+ return patch_2d, "CYX"
376
+
377
+ @classmethod
378
+ def array_to_uint8_rgb(
379
+ cls,
380
+ arr: np.ndarray,
381
+ axes: str,
382
+ max_edge: int = 1024,
383
+ fast: bool = False,
384
+ ) -> np.ndarray:
385
+ """
386
+ Converts an arbitrary biological array (CYX, YXS, YX; uint8/uint16/float)
387
+ into a contrast-normalized 8-bit RGB image for fast browser preview.
388
+ When fast=True, uses fast strided subsampling instead of heavy interpolation.
389
+ """
390
+ data = np.asarray(arr)
391
+ axes = axes.upper()
392
+
393
+ if data.ndim == 2:
394
+ cyx = data[np.newaxis, :, :]
395
+ elif axes.startswith("CYX"):
396
+ cyx = data
397
+ elif axes.endswith("C") or axes.endswith("S"):
398
+ cyx = np.moveaxis(data, -1, 0)
399
+ else:
400
+ cyx = data.reshape((-1, data.shape[-2], data.shape[-1]))
401
+
402
+ c, h, w = cyx.shape
403
+
404
+ # Fast subsampling if array is large
405
+ longest = max(h, w)
406
+ if fast and longest > max_edge and max_edge > 0:
407
+ step = int(np.ceil(longest / max_edge))
408
+ cyx = cyx[:, ::step, ::step]
409
+ c, h, w = cyx.shape
410
+
411
+ rgb = np.zeros((h, w, 3), dtype=np.uint8)
412
+
413
+ for i in range(min(c, 3)):
414
+ plane = cyx[i]
415
+ # Fast min/max approximation for snappy previews
416
+ if fast or plane.dtype == np.uint8:
417
+ p_low = float(plane.min())
418
+ p_high = float(plane.max())
419
+ else:
420
+ # Subsample 5% for fast percentile estimation
421
+ sample_pts = plane[::4, ::4].astype(np.float32)
422
+ p_low, p_high = np.percentile(sample_pts, (1.0, 99.5))
423
+
424
+ if p_high <= p_low:
425
+ p_low, p_high = float(plane.min()), float(plane.max())
426
+
427
+ if p_high > p_low:
428
+ norm = np.clip((plane.astype(np.float32) - p_low) / (p_high - p_low), 0.0, 1.0)
429
+ rgb[:, :, i] = (norm * 255.0).astype(np.uint8)
430
+ else:
431
+ rgb[:, :, i] = 0
432
+
433
+ if c == 1:
434
+ rgb[:, :, 1] = rgb[:, :, 0]
435
+ rgb[:, :, 2] = rgb[:, :, 0]
436
+
437
+ if not fast and longest > max_edge and max_edge > 0:
438
+ scale = max_edge / longest
439
+ new_w = max(1, int(round(w * scale)))
440
+ new_h = max(1, int(round(h * scale)))
441
+ pil_img = Image.fromarray(rgb).resize((new_w, new_h), Image.Resampling.BILINEAR)
442
+ return np.asarray(pil_img, dtype=np.uint8)
443
+
444
+ return rgb
445
+
446
+ @classmethod
447
+ def _save_patch(
448
+ cls,
449
+ patch: np.ndarray,
450
+ patch_axes: str,
451
+ out_path: Path,
452
+ output_format: str,
453
+ ) -> None:
454
+ if output_format == "ome.tif":
455
+ tifffile.imwrite(
456
+ out_path,
457
+ patch,
458
+ ome=True,
459
+ photometric="minisblack",
460
+ compression="deflate",
461
+ metadata={"axes": patch_axes},
462
+ )
463
+ elif output_format == "tif":
464
+ tifffile.imwrite(
465
+ out_path,
466
+ patch,
467
+ photometric="minisblack",
468
+ compression="deflate",
469
+ )
470
+ elif output_format == "png":
471
+ rgb = cls.array_to_uint8_rgb(patch, patch_axes, max_edge=4096)
472
+ Image.fromarray(rgb).save(out_path)
473
+ elif output_format == "zarr":
474
+ zarr.save(str(out_path), patch)
475
+ else:
476
+ raise ValueError(f"Unsupported output format: {output_format}")
@@ -0,0 +1,77 @@
1
+ from __future__ import annotations
2
+ from pathlib import Path
3
+ import numpy as np
4
+ import tifffile
5
+
6
+
7
+ def generate_sample_pyramidal_ome_tiff(
8
+ output_path: str | Path,
9
+ base_width: int = 1024,
10
+ base_height: int = 1024,
11
+ num_levels: int = 4,
12
+ tile_size: int = 128,
13
+ channel_names: list[str] | None = None,
14
+ ) -> Path:
15
+ """
16
+ Generates a synthetic multi-channel, multi-resolution tiled pyramidal OME-TIFF
17
+ with realistic synthetic tissue/cell structures for tests and cloud demo mode.
18
+ """
19
+ out = Path(output_path).expanduser().resolve()
20
+ out.parent.mkdir(parents=True, exist_ok=True)
21
+ channels = channel_names or ["DAPI_Nuclei", "CD3_TCells", "PanCK_Tumor"]
22
+ num_c = len(channels)
23
+
24
+ rng = np.random.default_rng(seed=42)
25
+ yy, xx = np.mgrid[0:base_height, 0:base_width]
26
+
27
+ # Build synthetic multiplexed fluorescence tissue plane (C, Y, X) uint16
28
+ base_data = np.zeros((num_c, base_height, base_width), dtype=np.uint16)
29
+
30
+ for c_idx in range(num_c):
31
+ # Smooth tissue macro-regions + cellular hotspots
32
+ cx = base_width * (0.3 + 0.2 * c_idx)
33
+ cy = base_height * (0.35 + 0.15 * c_idx)
34
+ radius = min(base_width, base_height) * 0.28
35
+ dist_sq = (xx - cx) ** 2 + (yy - cy) ** 2
36
+ macro = np.exp(-dist_sq / (2.0 * (radius ** 2))) * 35000.0
37
+
38
+ # Add cellular grid pattern so crops at different coordinates are visually distinct
39
+ grid_pattern = (
40
+ (np.sin(xx / (12.0 + c_idx * 4)) * np.cos(yy / (12.0 + c_idx * 4)) + 1.0)
41
+ * 12000.0
42
+ )
43
+ noise = rng.integers(0, 3000, size=(base_height, base_width), dtype=np.uint16)
44
+ plane = np.clip(macro + grid_pattern + noise, 0, 65535).astype(np.uint16)
45
+ base_data[c_idx] = plane
46
+
47
+ subresolutions = max(0, num_levels - 1)
48
+ metadata = {
49
+ "axes": "CYX",
50
+ "Channel": {"Name": channels},
51
+ "PhysicalSizeX": 0.25,
52
+ "PhysicalSizeXUnit": "µm",
53
+ "PhysicalSizeY": 0.25,
54
+ "PhysicalSizeYUnit": "µm",
55
+ }
56
+
57
+ with tifffile.TiffWriter(out, bigtiff=True, ome=True) as tif:
58
+ tif.write(
59
+ base_data,
60
+ subifds=subresolutions,
61
+ tile=(tile_size, tile_size),
62
+ compression="deflate",
63
+ photometric="minisblack",
64
+ metadata=metadata,
65
+ )
66
+ current = base_data
67
+ for _ in range(subresolutions):
68
+ current = current[:, ::2, ::2]
69
+ tif.write(
70
+ current,
71
+ subfiletype=1,
72
+ tile=(tile_size, tile_size),
73
+ compression="deflate",
74
+ photometric="minisblack",
75
+ )
76
+
77
+ return out
@@ -0,0 +1,5 @@
1
+ """Gradio UI package and extensible plugin registry for PatchKori."""
2
+
3
+ from patchkori.ui.registry import BaseBioTool, ToolRegistry
4
+
5
+ __all__ = ["BaseBioTool", "ToolRegistry"]
patchkori/ui/app.py ADDED
@@ -0,0 +1,42 @@
1
+ from __future__ import annotations
2
+ import gradio as gr
3
+ from patchkori.config import AppConfig
4
+ from patchkori.ui.icons import LOGO_HEADER_HTML
5
+ from patchkori.ui.registry import ToolRegistry
6
+ from patchkori.ui.theme import CUSTOM_CSS, build_app_theme
7
+ import patchkori.ui.tools # noqa: F401 - triggers @ToolRegistry.register for all tools
8
+
9
+
10
+ def create_app(config: AppConfig | None = None) -> gr.Blocks:
11
+ """Constructs the unified PatchKori Bioinformatics Patch Kits Hub."""
12
+ cfg = config or AppConfig.from_env()
13
+ tools = ToolRegistry.get_tools()
14
+
15
+ mode_badge_text = (
16
+ "☁️ Cloud Demo Mode — Testing on sample dataset (<200 MB)"
17
+ if cfg.is_demo_mode
18
+ else "💻 Local Workstation Mode — Zero-copy streaming on gigapixel biological datasets"
19
+ )
20
+
21
+ theme = build_app_theme()
22
+
23
+ with gr.Blocks(title=cfg.app_name, theme=theme, css=CUSTOM_CSS) as demo:
24
+ gr.HTML(LOGO_HEADER_HTML)
25
+ gr.HTML(
26
+ f"""
27
+ <div class="pk-top-bar">
28
+ <div class="pk-mode-badge">{mode_badge_text}</div>
29
+ <div class="pk-api-badge">⚡ Use via API (In Development)</div>
30
+ </div>
31
+ """
32
+ )
33
+
34
+ with gr.Tabs():
35
+ for tool in tools:
36
+ with gr.Tab(tool.title, id=tool.tool_id):
37
+ if tool.description:
38
+ gr.Markdown(f"*{tool.description}*")
39
+ tool.build_ui(is_demo_mode=cfg.is_demo_mode)
40
+
41
+ demo.queue(default_concurrency_limit=cfg.max_workers)
42
+ return demo
patchkori/ui/icons.py ADDED
@@ -0,0 +1,38 @@
1
+ """
2
+ Custom Vector Logos and Colorblind-Safe Icons for PatchKori.
3
+ Eye-soothing palette based on Okabe-Ito guidelines:
4
+ Deep Marine Blue, Bio-Teal, Warm Amber, and Steel Slate (Zero violet/purple).
5
+ """
6
+
7
+ LOGO_PATCHKORI_SVG = """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="44" height="44" fill="none" style="display:inline-block; vertical-align:middle; flex-shrink:0;"><defs><linearGradient id="pk_tile_navy" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="#1E3A8A" /><stop offset="100%" stop-color="#2563EB" /></linearGradient><linearGradient id="pk_tile_teal" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="#0F766E" /><stop offset="100%" stop-color="#14B8A6" /></linearGradient><linearGradient id="pk_tile_slate" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="#334155" /><stop offset="100%" stop-color="#475569" /></linearGradient><linearGradient id="pk_tile_amber" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="#B45309" /><stop offset="100%" stop-color="#F59E0B" /></linearGradient></defs><rect x="14" y="14" width="32" height="32" rx="6" fill="url(#pk_tile_navy)" /><rect x="54" y="14" width="32" height="32" rx="6" fill="url(#pk_tile_teal)" /><rect x="14" y="54" width="32" height="32" rx="6" fill="url(#pk_tile_slate)" /><rect x="54" y="54" width="14" height="14" rx="3" fill="#0284C7" /><rect x="72" y="54" width="14" height="14" rx="3" fill="#0D9488" /><rect x="54" y="72" width="14" height="14" rx="3" fill="#475569" /><rect x="72" y="72" width="14" height="14" rx="3" fill="url(#pk_tile_amber)" /><circle cx="50" cy="50" r="14" stroke="#FFFFFF" stroke-width="2" stroke-dasharray="3 3" opacity="0.9" /><circle cx="50" cy="50" r="4.5" fill="#FFFFFF" /><circle cx="50" cy="50" r="2" fill="#0F766E" /><path d="M 8 22 L 8 8 L 22 8" stroke="#0284C7" stroke-width="2.5" stroke-linecap="round" /><path d="M 78 8 L 92 8 L 92 22" stroke="#14B8A6" stroke-width="2.5" stroke-linecap="round" /><path d="M 8 78 L 8 92 L 22 92" stroke="#64748B" stroke-width="2.5" stroke-linecap="round" /><path d="M 78 92 L 92 92 L 92 78" stroke="#D97706" stroke-width="2.5" stroke-linecap="round" /></svg>"""
8
+
9
+ LOGO_HEADER_HTML = f"""
10
+ <div class="pk-brand-container">
11
+ {LOGO_PATCHKORI_SVG}
12
+ <div class="pk-brand-text">
13
+ <div class="pk-brand-title">
14
+ <span class="pk-logo-accent">Patch</span><span class="pk-logo-main">Kori</span>
15
+ </div>
16
+ <div class="pk-brand-tagline">Bioinformatics Patch Kits Hub</div>
17
+ </div>
18
+ </div>
19
+ """
20
+
21
+ # Colorblind-safe vector icons (One-line compact SVGs, safe for HTML & Markdown embedding):
22
+ ICON_MICROSCOPE = """<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="pk-icon-teal" style="display:inline-block; vertical-align:middle; margin-right:4px;"><path d="M6 18h8"/><path d="M3 22h18"/><path d="M14 22a7 7 0 1 0 0-14h-1"/><path d="M9 14h2"/><path d="M9 12a2 2 0 0 1-2-2V6h6v4a2 2 0 0 1-2 2Z"/><path d="M12 6V3a1 1 0 0 0-1-1H9a1 1 0 0 0-1 1v3"/></svg>"""
23
+
24
+ ICON_LAYERS = """<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="pk-icon-blue" style="display:inline-block; vertical-align:middle; margin-right:4px;"><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg>"""
25
+
26
+ ICON_CROP = """<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="pk-icon-teal" style="display:inline-block; vertical-align:middle; margin-right:4px;"><path d="M6 2v14a2 2 0 0 0 2 2h14"/><path d="M18 22V8a2 2 0 0 0-2-2H2"/></svg>"""
27
+
28
+ # New Premium Scissors / Patch Extractor icon from React-Icons (LuScissors / TbCut)
29
+ ICON_CUT = """<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="pk-icon-teal" style="display:inline-block; vertical-align:middle; margin-right:4px;"><circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><line x1="20" y1="4" x2="8.12" y2="15.88"/><line x1="14.47" y1="14.48" x2="20" y2="20"/><line x1="8.12" y1="8.12" x2="12" y2="12"/></svg>"""
30
+
31
+ # New Fast Action / Play Processor icon from React-Icons (TbPlayerPlay / LuPlay)
32
+ ICON_PLAY = """<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="currentColor" stroke="none" class="pk-icon-teal" style="display:inline-block; vertical-align:middle; margin-right:5px;"><polygon points="6 4 20 12 6 20 6 4"/></svg>"""
33
+
34
+ ICON_DRAW = """<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="pk-icon-blue" style="display:inline-block; vertical-align:middle; margin-right:4px;"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg>"""
35
+
36
+ ICON_MAXIMIZE = """<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="pk-icon-slate" style="display:inline-block; vertical-align:middle; margin-right:4px;"><path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M21 8V5a2 2 0 0 0-2-2h-3"/><path d="M3 16v3a2 2 0 0 0 2 2h3"/><path d="M16 21h3a2 2 0 0 0 2-2v-3"/></svg>"""
37
+
38
+ ICON_CHANNELS = """<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="pk-icon-blue" style="display:inline-block; vertical-align:middle; margin-right:4px;"><circle cx="12" cy="12" r="10"/><path d="m4.93 4.93 4.24 4.24"/><path d="m14.83 9.17 4.24-4.24"/><path d="m14.83 14.83 4.24 4.24"/><path d="m9.17 14.83-4.24 4.24"/></svg>"""