Spaces:
Sleeping
Sleeping
Download wsi_loader.py from LOP3Zs/BreastCancer: direct link, hf CLI and curl.
- Browser
- Download file 8.52 kB
-
https://huggingface.co/spaces/LOP3Zs/BreastCancer/resolve/main/wsi_loader.py
- Command line
-
hf download hf://spaces/LOP3Zs/BreastCancer/wsi_loader.py
-
curl -L -o wsi_loader.py https://huggingface.co/spaces/LOP3Zs/BreastCancer/resolve/main/wsi_loader.py
8.52 kB
| import io | |
| import math | |
| import os | |
| from pathlib import Path | |
| from typing import List, Tuple, Dict, Any, Optional | |
| import numpy as np | |
| from PIL import Image, ImageOps, PngImagePlugin | |
| # Allow opening large whole-slide PNG thumbnails with substantial iCCP metadata | |
| PngImagePlugin.MAX_TEXT_CHUNK = 100 * (1024 * 1024) | |
| MAX_SVS_SIZE_MB = 200 | |
| MAX_IMAGE_SIDE = 1700 | |
| DEFAULT_TILE_SIZE = 224 | |
| MAX_CPU_TILES = 800 | |
| WHITE_THRESHOLD = 240 | |
| MIN_TISSUE_FRACTION = 0.02 | |
| def is_tissue_tile(tile: Image.Image, white_threshold: int = WHITE_THRESHOLD, min_fraction: float = MIN_TISSUE_FRACTION) -> bool: | |
| """Filter out acellular / glass / white background patches.""" | |
| arr = np.asarray(tile.convert("RGB")) | |
| non_white = np.any(arr < white_threshold, axis=2) | |
| return float(np.mean(non_white)) >= min_fraction | |
| def process_standard_image( | |
| image: Image.Image, | |
| target_tiles: int = 500, | |
| max_side: int = MAX_IMAGE_SIDE, | |
| max_tiles: int = MAX_CPU_TILES, | |
| ) -> Tuple[Image.Image, List[Image.Image], List[Tuple[int, int, int, int]], Dict[str, Any]]: | |
| """ | |
| Process regular histology image (PNG, JPG, TIFF): | |
| - Automatically resizes if exceeding max_side while preserving aspect ratio. | |
| - Generates a dense, publication-grade tile grid (typically 300-800 tiles) | |
| so the attention map is finely resolved and smooth rather than coarse blocks. | |
| - Each tile is cropped and formatted to 224x224 for Phikon-v2 feature extraction. | |
| - Filters acellular glass/background using white thresholding (matching figure.ipynb). | |
| """ | |
| image = ImageOps.exif_transpose(image).convert("RGB") | |
| orig_w, orig_h = image.size | |
| # Ensure thumbnail / canvas max side matches figure.ipynb (1700px) | |
| if max(orig_w, orig_h) > max_side: | |
| scale = max_side / max(orig_w, orig_h) | |
| new_size = (max(1, round(orig_w * scale)), max(1, round(orig_h * scale))) | |
| image = image.resize(new_size, Image.Resampling.LANCZOS) | |
| elif max(orig_w, orig_h) < 1200: | |
| # Scale up small ROI patches to standard 1400-1700 canvas to ensure fine-grained attention resolution | |
| scale = min(1700 / max(orig_w, orig_h), 2.5) | |
| new_size = (max(1, round(orig_w * scale)), max(1, round(orig_h * scale))) | |
| image = image.resize(new_size, Image.Resampling.LANCZOS) | |
| width, height = image.size | |
| # Calculate optimal tile span on this canvas to achieve dense, publication-quality coverage (~300-600 tiles) | |
| # Area per tile = (width * height) / target_tiles | |
| target_patch_side = int(round(math.sqrt((width * height) / max(50, target_tiles)))) | |
| # Clamp tile size between 48px (very fine) and 160px (coarse) | |
| tile_span = max(48, min(160, target_patch_side)) | |
| stride = tile_span # contiguous non-overlapping coverage | |
| candidate_tiles = [] | |
| candidate_coords = [] | |
| # Dense step coordinates covering 100% of the image including right & bottom edges | |
| x_steps = list(range(0, max(1, width - tile_span + 1), stride)) | |
| if x_steps[-1] + tile_span < width: | |
| x_steps.append(width - tile_span) | |
| y_steps = list(range(0, max(1, height - tile_span + 1), stride)) | |
| if y_steps[-1] + tile_span < height: | |
| y_steps.append(height - tile_span) | |
| for y in y_steps: | |
| for x in x_steps: | |
| crop_box = (x, y, x + tile_span, y + tile_span) | |
| patch = image.crop(crop_box) | |
| if is_tissue_tile(patch): | |
| # Standardize tile to 224x224 for Phikon-v2 foundation model | |
| phikon_tile = patch.resize((224, 224), Image.Resampling.BILINEAR) if tile_span != 224 else patch | |
| candidate_tiles.append(phikon_tile) | |
| candidate_coords.append((x, y, tile_span, tile_span)) | |
| # If entire image is very light or tissue filter dropped too many, fallback to all tiles | |
| if len(candidate_tiles) < 10: | |
| candidate_tiles.clear() | |
| candidate_coords.clear() | |
| for y in y_steps: | |
| for x in x_steps: | |
| patch = image.crop((x, y, x + tile_span, y + tile_span)) | |
| phikon_tile = patch.resize((224, 224), Image.Resampling.BILINEAR) if tile_span != 224 else patch | |
| candidate_tiles.append(phikon_tile) | |
| candidate_coords.append((x, y, tile_span, tile_span)) | |
| meta = { | |
| "original_width": orig_w, | |
| "original_height": orig_h, | |
| "canvas_width": width, | |
| "canvas_height": height, | |
| "tile_span": tile_span, | |
| "tile_size": tile_span, | |
| "total_tissue_tiles_found": len(candidate_tiles), | |
| "tiles_processed": len(candidate_tiles), | |
| "source_type": "standard_image" | |
| } | |
| return image, candidate_tiles, candidate_coords, meta | |
| def process_svs_slide( | |
| svs_path: str, | |
| tile_size: int = DEFAULT_TILE_SIZE, | |
| max_tiles: int = MAX_CPU_TILES, | |
| ) -> Tuple[Image.Image, List[Image.Image], List[Tuple[int, int, int, int]], Dict[str, Any]]: | |
| """ | |
| Process Whole Slide Image (.svs) using OpenSlide: | |
| - Checks file size constraint | |
| - Generates high-resolution thumbnail (1800px max side) | |
| - Extracts dense tissue tiles and aligns coordinates with thumbnail | |
| """ | |
| import openslide | |
| file_size_mb = os.path.getsize(svs_path) / (1024 * 1024) | |
| if file_size_mb > MAX_SVS_SIZE_MB: | |
| raise ValueError( | |
| f"Whole Slide Image is {file_size_mb:.1f} MB, which exceeds the current limit ({MAX_SVS_SIZE_MB} MB). " | |
| "Please crop the region of interest or upload a standard PNG/TIFF format." | |
| ) | |
| slide = openslide.OpenSlide(svs_path) | |
| try: | |
| w0, h0 = slide.level_dimensions[0] | |
| thumb_max_side = 1700 | |
| scale = thumb_max_side / max(w0, h0) | |
| thumb_w = max(1, round(w0 * scale)) | |
| thumb_h = max(1, round(h0 * scale)) | |
| thumbnail = slide.get_thumbnail((thumb_w, thumb_h)).convert("RGB") | |
| target_level = 0 | |
| if len(slide.level_dimensions) > 1 and max(w0, h0) > 25000: | |
| target_level = min(1, len(slide.level_dimensions) - 1) | |
| lw, lh = slide.level_dimensions[target_level] | |
| ds = slide.level_downsamples[target_level] | |
| candidate_tiles = [] | |
| candidate_coords_thumb = [] | |
| stride = tile_size if (lw * lh / (tile_size * tile_size)) <= max_tiles * 3 else tile_size * 2 | |
| xs = list(range(0, lw - tile_size + 1, stride)) | |
| ys = list(range(0, lh - tile_size + 1, stride)) | |
| for y in ys: | |
| for x in xs: | |
| xy0 = (int(round(x * ds)), int(round(y * ds))) | |
| tile = slide.read_region(xy0, target_level, (tile_size, tile_size)).convert("RGB") | |
| if is_tissue_tile(tile): | |
| tx = int(round(xy0[0] * scale)) | |
| ty = int(round(xy0[1] * scale)) | |
| tw = max(2, int(round(tile_size * ds * scale))) | |
| th = max(2, int(round(tile_size * ds * scale))) | |
| candidate_tiles.append(tile) | |
| candidate_coords_thumb.append((tx, ty, tw, th)) | |
| if len(candidate_tiles) >= max_tiles: | |
| break | |
| if len(candidate_tiles) >= max_tiles: | |
| break | |
| if not candidate_tiles: | |
| cx0, cy0 = w0 // 2, h0 // 2 | |
| tile = slide.read_region((cx0, cy0), 0, (tile_size, tile_size)).convert("RGB") | |
| candidate_tiles.append(tile) | |
| candidate_coords_thumb.append((thumb_w // 2, thumb_h // 2, 20, 20)) | |
| meta = { | |
| "original_width": w0, | |
| "original_height": h0, | |
| "canvas_width": thumbnail.width, | |
| "canvas_height": thumbnail.height, | |
| "tile_size": tile_size, | |
| "tiles_processed": len(candidate_tiles), | |
| "source_type": "svs_wsi" | |
| } | |
| return thumbnail, candidate_tiles, candidate_coords_thumb, meta | |
| finally: | |
| slide.close() | |
| def load_image_or_slide_from_path( | |
| file_path: str, | |
| tile_size: int = DEFAULT_TILE_SIZE, | |
| max_tiles: int = MAX_CPU_TILES | |
| ) -> Tuple[Image.Image, List[Image.Image], List[Tuple[int, int, int, int]], Dict[str, Any]]: | |
| """Dispatcher for file path.""" | |
| suffix = Path(file_path).suffix.lower() | |
| if suffix in (".svs", ".ndpi", ".vms", ".vmu", ".scn", ".mrxs"): | |
| return process_svs_slide(file_path, tile_size=tile_size, max_tiles=max_tiles) | |
| else: | |
| image = Image.open(file_path) | |
| return process_standard_image(image, target_tiles=500, max_tiles=max_tiles) | |
| # Alias for backward compatibility | |
| load_image_or_slide = load_image_or_slide_from_path | |