Datasets:
Formats:
parquet
Languages:
English
Size:
1K - 10K
Tags:
microscopy
microalgae
conditional-generation
pseudo-instance-segmentation
population-phenotype
License:
Download code/build_dataset_release.py from SiuSeven/cmfi-17-1024: direct link, hf CLI and curl.
- Browser
- Download file 31.9 kB
-
https://huggingface.co/datasets/SiuSeven/cmfi-17-1024/resolve/main/code/build_dataset_release.py
- Command line
-
hf download hf://datasets/SiuSeven/cmfi-17-1024/code/build_dataset_release.py
-
curl -L -o build_dataset_release.py https://huggingface.co/datasets/SiuSeven/cmfi-17-1024/resolve/main/code/build_dataset_release.py
31.9 kB
| #!/usr/bin/env python3 | |
| """Build an isolated, lossless native-1024 CMFI release without GPU work. | |
| Only NumPy, Pillow and PyArrow are required. Source assets and legacy splits | |
| are immutable. This script never authenticates, uploads, trains or segments. | |
| The masks are crops of the pinned release's existing pseudo annotations; | |
| their original Cellpose model revision is not recorded. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import hashlib | |
| import io | |
| import json | |
| import re | |
| import time | |
| from collections import Counter, defaultdict | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| from PIL import Image | |
| SOURCE_REPO = "SiuSeven/cmfi-17-v1-0" | |
| SOURCE_REVISION = "6faa7d9f83fffa689eb4e3a7a1962f101ceefe58" | |
| SOURCE_MANIFEST_SHA256 = "2f99601a3b59afaf6192d41ccdd8fa06e8b520d22daeb5738b8f5950177c32c8" | |
| REPO_ID = "SiuSeven/cmfi-17-1024" | |
| SIZE = 1024 | |
| SOURCE_SIZE = (1360, 1024) | |
| CROP_BOX = (168, 0, 1192, 1024) | |
| SPLITS = ("train", "validation", "test") | |
| ANNOTATION_SOURCE = "source_release_pseudo_mask_crop" | |
| SCHEMA_VERSION = "cmfi-native-1024-v1" | |
| SOURCE_COLUMNS = ( | |
| "observation_id", "content_group_id", "time_h", "regime", | |
| "condition_key", "split", "image_path", "mask_path", | |
| "release_image_sha256", "mask_sha256", "acquisition_group_id", | |
| "capture_epoch_seconds", | |
| ) | |
| OPTIONAL_SOURCE_COLUMNS = ("content_group_id_v01_legacy",) | |
| def sha256_bytes(data: bytes) -> str: | |
| return hashlib.sha256(data).hexdigest() | |
| def sha256_file(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def pixel_sha256(array: np.ndarray) -> str: | |
| """Hash C-order pixels; mask pixels use explicitly little-endian uint16.""" | |
| if array.ndim == 2: | |
| array = array.astype("<u2", copy=False) | |
| return sha256_bytes(np.ascontiguousarray(array).tobytes()) | |
| def write_json(path: Path, value: Any) -> None: | |
| path.write_text(json.dumps(value, indent=2, sort_keys=True, allow_nan=False) + "\n", encoding="utf-8") | |
| def safe_source_path(source_root: Path, relative: str) -> Path: | |
| candidate = Path(relative) | |
| if candidate.is_absolute() or ".." in candidate.parts: | |
| raise ValueError(f"Unsafe source path: {relative}") | |
| # prepare_data.py flattens the upstream data/ prefix into source_root. | |
| if candidate.parts and candidate.parts[0] == "data": | |
| candidate = Path(*candidate.parts[1:]) | |
| resolved = (source_root / candidate).resolve() | |
| if not resolved.is_relative_to(source_root.resolve()) or not resolved.is_file(): | |
| raise ValueError(f"Source asset missing or outside source root: {relative}") | |
| return resolved | |
| def validate_output_root(source_root: Path, output_root: Path) -> Path: | |
| """Require a new destination disjoint from the complete source tree.""" | |
| source = source_root.resolve() | |
| output = output_root.resolve() | |
| if output == source or output.is_relative_to(source) or source.is_relative_to(output): | |
| raise ValueError("Output and source roots must be disjoint") | |
| if output_root.is_symlink() or output.exists(): | |
| raise ValueError("Output root must be fresh and must not already exist") | |
| if not source.is_dir(): | |
| raise ValueError("Source root must be an existing directory") | |
| return output | |
| def load_source_rows(source_root: Path) -> list[dict[str, Any]]: | |
| path = source_root / "canonical/fov_manifest.parquet" | |
| available = set(pq.read_schema(path).names) | |
| missing = set(SOURCE_COLUMNS) - available | |
| if missing: | |
| raise ValueError(f"Source manifest missing columns: {sorted(missing)}") | |
| columns = [*SOURCE_COLUMNS, *(name for name in OPTIONAL_SOURCE_COLUMNS if name in available)] | |
| rows = pq.read_table(path, columns=columns).to_pylist() | |
| if not rows: | |
| raise ValueError("Empty source manifest") | |
| seen: set[str] = set() | |
| for row in rows: | |
| observation = row["observation_id"] | |
| if not isinstance(observation, str) or not re.fullmatch(r"[A-Za-z0-9_.-]+", observation): | |
| raise ValueError("Unsafe observation ID") | |
| if observation in seen: | |
| raise ValueError(f"Duplicate observation ID: {observation}") | |
| seen.add(observation) | |
| if row["split"] not in SPLITS: | |
| raise ValueError(f"Unknown legacy split: {row['split']}") | |
| if row["capture_epoch_seconds"] is None or not row["acquisition_group_id"]: | |
| raise ValueError("Session diagnostic requires acquisition group and capture time") | |
| for key in ("release_image_sha256", "mask_sha256"): | |
| if not isinstance(row[key], str) or not re.fullmatch(r"[0-9a-f]{64}", row[key]): | |
| raise ValueError(f"Missing or invalid source digest: {key}") | |
| if int(row["time_h"]) == 0: | |
| valid_condition = row["condition_key"] == "0h_shared" | |
| else: | |
| valid_condition = row["regime"] in ("light", "dark") and row["condition_key"] == f"{int(row['time_h'])}h_{row['regime']}" | |
| if not valid_condition: | |
| raise ValueError(f"Invalid condition metadata: {observation}") | |
| return sorted(rows, key=lambda row: row["observation_id"]) | |
| def measure_mask(mask: np.ndarray) -> tuple[dict[str, Any], np.ndarray, np.ndarray, np.ndarray]: | |
| """Count source labels, excluding every label touching any crop edge.""" | |
| if mask.shape != (SIZE, SIZE) or not np.issubdtype(mask.dtype, np.integer): | |
| raise ValueError("Mask must be a native-1024 integer instance map") | |
| if np.any(mask < 0) or int(mask.max()) > 65535: | |
| raise ValueError("Mask labels must fit uint16") | |
| present = np.unique(mask) | |
| present = present[present != 0] | |
| border = np.unique(np.concatenate((mask[0], mask[-1], mask[:, 0], mask[:, -1]))) | |
| border = border[border != 0] | |
| valid = np.setdiff1d(present, border, assume_unique=True) | |
| yy, xx = np.nonzero(mask) | |
| ids = mask[yy, xx].astype(np.int64, copy=False) | |
| limit = int(mask.max()) + 1 | |
| areas = np.bincount(ids, minlength=limit)[valid].astype(np.int64) | |
| if len(valid): | |
| cy = np.bincount(ids, weights=yy, minlength=limit)[valid] / areas | |
| cx = np.bincount(ids, weights=xx, minlength=limit)[valid] / areas | |
| cells = np.column_stack((cy / SIZE, cx / SIZE, np.log(areas / float(SIZE * SIZE)))) | |
| centers = np.column_stack((cy, cx)) | |
| else: | |
| cells = np.empty((0, 3), dtype=np.float64) | |
| centers = np.empty((0, 2), dtype=np.float64) | |
| nn_mean = None | |
| if len(valid) > 1: | |
| distance = np.linalg.norm(centers[:, None, :] - centers[None, :, :], axis=2) | |
| np.fill_diagonal(distance, np.inf) | |
| nn_mean = float(distance.min(axis=1).mean()) | |
| stats = { | |
| "n_instances_in_crop": int(len(present)), | |
| "n_instances_border_excluded": int(len(border)), | |
| "n_valid_instances": int(len(valid)), | |
| "mask_max_label": int(mask.max()), | |
| "foreground_coverage_all": float(len(ids) / (SIZE * SIZE)), | |
| "valid_foreground_coverage": float(areas.sum() / (SIZE * SIZE)), | |
| "valid_foreground_area_px": int(areas.sum()), | |
| "area_px_mean": float(areas.mean()) if len(areas) else None, | |
| "area_px_std": float(areas.std()) if len(areas) else None, | |
| "log_cell_area_mean": float(np.log(areas).mean()) if len(areas) else None, | |
| "nn_distance_mean_px": nn_mean, | |
| } | |
| return stats, cells, areas, valid.astype(np.uint16) | |
| class FieldResult: | |
| row: dict[str, Any] | |
| cells: np.ndarray | |
| areas: np.ndarray | |
| labels: np.ndarray | |
| rgb_sum: np.ndarray | |
| rgb_squared_sum: np.ndarray | |
| def process_field(row: dict[str, Any], source_root: Path, output_root: Path) -> FieldResult: | |
| image_bytes = safe_source_path(source_root, row["image_path"]).read_bytes() | |
| mask_bytes = safe_source_path(source_root, row["mask_path"]).read_bytes() | |
| if sha256_bytes(image_bytes) != row["release_image_sha256"]: | |
| raise ValueError(f"Source image checksum mismatch: {row['observation_id']}") | |
| if sha256_bytes(mask_bytes) != row["mask_sha256"]: | |
| raise ValueError(f"Source mask checksum mismatch: {row['observation_id']}") | |
| with Image.open(io.BytesIO(image_bytes)) as source: | |
| if source.mode != "RGB" or source.size != SOURCE_SIZE: | |
| raise ValueError(f"Unexpected source image format: {row['observation_id']}") | |
| image = np.asarray(source.crop(CROP_BOX)).copy() | |
| with Image.open(io.BytesIO(mask_bytes)) as source: | |
| if source.size != SOURCE_SIZE or source.mode not in ("I;16", "I;16B", "I;16L", "I"): | |
| raise ValueError(f"Unexpected source mask format: {row['observation_id']}") | |
| mask = np.asarray(source.crop(CROP_BOX)).copy() | |
| stats, cells, areas, labels = measure_mask(mask) | |
| mask = mask.astype(np.uint16) | |
| image_relative = f"images/{row['observation_id']}.png" | |
| mask_relative = f"masks/{row['observation_id']}.png" | |
| image_path, mask_path = output_root / image_relative, output_root / mask_relative | |
| Image.fromarray(image).save(image_path, format="PNG", compress_level=3) | |
| Image.fromarray(mask).save(mask_path, format="PNG", compress_level=3) | |
| with Image.open(image_path) as emitted: | |
| image_equal = emitted.mode == "RGB" and np.array_equal(np.asarray(emitted), image) | |
| with Image.open(mask_path) as emitted: | |
| mask_equal = np.array_equal(np.asarray(emitted), mask) | |
| if not image_equal or not mask_equal: | |
| raise ValueError(f"Lossless crop validation failed: {row['observation_id']}") | |
| result = { | |
| "observation_id": row["observation_id"], | |
| "condition_key": row["condition_key"], | |
| "time_h": int(row["time_h"]), | |
| "regime": "shared" if int(row["time_h"]) == 0 else row["regime"], | |
| "split": row["split"], | |
| "legacy_split": row["split"], | |
| "legacy_content_group_id": row["content_group_id"], | |
| "legacy_content_group_id_v01": row.get("content_group_id_v01_legacy"), | |
| "acquisition_group_id": row["acquisition_group_id"], | |
| "capture_epoch_seconds": int(row["capture_epoch_seconds"]), | |
| "image_path": image_relative, "mask_path": mask_relative, | |
| "image_sha256": sha256_file(image_path), "mask_sha256": sha256_file(mask_path), | |
| "pixel_sha256": pixel_sha256(image), "mask_pixel_sha256": pixel_sha256(mask), | |
| "source_release_image_sha256": row["release_image_sha256"], | |
| "source_mask_sha256": row["mask_sha256"], | |
| "source_image_release_path": row["image_path"], | |
| "source_mask_release_path": row["mask_path"], | |
| "content_group_id": "sha256:" + pixel_sha256(image), | |
| "width": SIZE, "height": SIZE, "channels": 3, | |
| "image_mode": "RGB", "image_dtype": "uint8", "image_codec": "png", | |
| "mask_dtype": "uint16", "mask_background_id": 0, | |
| "mask_instance_id_policy": "sparse_source_ids_preserved", | |
| "annotation_source": ANNOTATION_SOURCE, | |
| "mask_annotation_type": "pseudo_instance", | |
| "mask_generator": "cellpose_source_model_revision_unknown", | |
| "crop_x0": CROP_BOX[0], "crop_y0": CROP_BOX[1], "crop_size": SIZE, | |
| "schema_version": SCHEMA_VERSION, | |
| **stats, | |
| } | |
| return FieldResult( | |
| result, cells, areas, labels, | |
| image.sum(axis=(0, 1), dtype=np.uint64), | |
| np.square(image.astype(np.uint32)).sum(axis=(0, 1), dtype=np.uint64), | |
| ) | |
| def check_pixel_leakage(rows: list[dict[str, Any]]) -> dict[str, int]: | |
| by_pixel: dict[str, list[dict[str, Any]]] = defaultdict(list) | |
| for row in rows: | |
| by_pixel[row["pixel_sha256"]].append(row) | |
| leaking = [group for group in by_pixel.values() if len({row["split"] for row in group}) > 1] | |
| if leaking: | |
| example = [row["observation_id"] for row in leaking[0]] | |
| raise ValueError(f"Cropped-pixel duplicate crosses legacy splits: {example}") | |
| return { | |
| "unique_cropped_pixel_groups": len(by_pixel), | |
| "within_split_duplicate_groups": sum(len(group) > 1 for group in by_pixel.values()), | |
| "cross_split_cropped_pixel_duplicate_groups": 0, | |
| } | |
| def session_holdout(rows: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, Any]]: | |
| """Last whole acquisition session per condition; diagnostic, never blind.""" | |
| groups: dict[str, dict[str, list[dict[str, Any]]]] = defaultdict(lambda: defaultdict(list)) | |
| group_conditions: dict[str, set[str]] = defaultdict(set) | |
| for row in rows: | |
| if row.get("capture_epoch_seconds") is None or not row.get("acquisition_group_id"): | |
| raise ValueError("Session diagnostic requires acquisition group and capture time") | |
| groups[row["condition_key"]][row["acquisition_group_id"]].append(row) | |
| group_conditions[row["acquisition_group_id"]].add(row["condition_key"]) | |
| if any(len(conditions) > 1 for conditions in group_conditions.values()): | |
| raise ValueError("Acquisition group spans conditions; cannot select independently") | |
| selection: dict[str, str] = {} | |
| for condition, sessions in sorted(groups.items()): | |
| if len(sessions) < 2: | |
| raise ValueError(f"Condition has fewer than two acquisition sessions: {condition}") | |
| selection[condition] = max( | |
| sessions, | |
| key=lambda group: (max(int(row["capture_epoch_seconds"]) for row in sessions[group]), group), | |
| ) | |
| mapping = [ | |
| { | |
| "observation_id": row["observation_id"], "condition_key": row["condition_key"], | |
| "acquisition_group_id": row["acquisition_group_id"], | |
| "legacy_split": row["split"], | |
| "session_diagnostic_split": "diagnostic_holdout" if row["acquisition_group_id"] == selection[row["condition_key"]] else "development", | |
| } | |
| for row in rows | |
| ] | |
| pixel_partitions: dict[str, set[str]] = defaultdict(set) | |
| for row, assignment in zip(rows, mapping, strict=True): | |
| if "pixel_sha256" in row: | |
| pixel_partitions[row["pixel_sha256"]].add(assignment["session_diagnostic_split"]) | |
| if any(len(partitions) > 1 for partitions in pixel_partitions.values()): | |
| raise ValueError("Cropped-pixel duplicate crosses session diagnostic partitions") | |
| report = { | |
| "policy": "chronological-last-session-per-condition-diagnostic", | |
| "ordering": "maximum capture_epoch_seconds per session; lexicographically largest group ID breaks ties", | |
| "selected_sessions": selection, | |
| "field_counts": dict(sorted(Counter(row["session_diagnostic_split"] for row in mapping).items())), | |
| "is_blind_test": False, | |
| "legacy_baseline_comparable": False, | |
| "biological_replicate_holdout": False, | |
| "cross_partition_cropped_pixel_duplicate_groups": 0 if pixel_partitions else None, | |
| "refit_required": "Any future session-diagnostic experiment must fit models, normalization and thresholds only on development, with an internal selection split; legacy checkpoints/statistics are not eligible.", | |
| "limitations": "Previously exposed observations; acquisition sessions are not proven independent cultures; no three-way session split is defined.", | |
| } | |
| return mapping, report | |
| def train_normalization(results: list[FieldResult]) -> dict[str, Any]: | |
| train = [result for result in results if result.row["split"] == "train"] | |
| if not train: | |
| raise ValueError("Training split is empty") | |
| pixels = len(train) * SIZE * SIZE | |
| sums = sum((result.rgb_sum.astype(np.float64) for result in train), np.zeros(3)) | |
| squares = sum((result.rgb_squared_sum.astype(np.float64) for result in train), np.zeros(3)) | |
| mean = sums / pixels / 255.0 | |
| std = np.sqrt(np.maximum(squares / pixels / (255.0**2) - mean**2, 0)) | |
| fields = np.asarray([[result.row["n_valid_instances"], result.row["valid_foreground_coverage"]] for result in train], dtype=np.float64) | |
| areas = np.concatenate([result.areas for result in train]) | |
| return { | |
| "fit_source_split": "train", "train_fields": len(train), "train_pixels": pixels, | |
| "rgb_input_scale": "uint8 / 255", "rgb_mean": mean.tolist(), "rgb_std": std.tolist(), | |
| "field_features": ["n_valid_instances", "valid_foreground_coverage"], | |
| "field_mean": fields.mean(axis=0).tolist(), "field_std_population": fields.std(axis=0).tolist(), | |
| "valid_cells": int(len(areas)), "log_cell_area_definition": "natural log of valid instance area in pixels", | |
| "log_cell_area_mean": float(np.log(areas).mean()) if len(areas) else None, | |
| "log_cell_area_std_population": float(np.log(areas).std()) if len(areas) else None, | |
| "readout_source": ANNOTATION_SOURCE, | |
| "automatic_normalization_applied_to_images": False, | |
| } | |
| def write_plans(path: Path, results: list[FieldResult]) -> None: | |
| offsets = np.concatenate(([0], np.cumsum([len(result.cells) for result in results]))).astype(np.int64) | |
| cells = np.concatenate([result.cells for result in results], axis=0) if results else np.empty((0, 3)) | |
| areas = np.concatenate([result.areas for result in results]) if results else np.empty(0, dtype=np.int64) | |
| labels = np.concatenate([result.labels for result in results]) if results else np.empty(0, dtype=np.uint16) | |
| np.savez_compressed( | |
| path, | |
| schema_version=np.asarray([SCHEMA_VERSION]), annotation_source=np.asarray([ANNOTATION_SOURCE]), | |
| sample_ids=np.asarray([result.row["observation_id"] for result in results], dtype=str), | |
| condition_keys=np.asarray([result.row["condition_key"] for result in results], dtype=str), | |
| time_h=np.asarray([result.row["time_h"] for result in results], dtype=np.float32), | |
| regime=np.asarray([0 if result.row["regime"] == "shared" else (1 if result.row["regime"] == "light" else -1) for result in results], dtype=np.int8), | |
| offsets=offsets, cells_yx_log_area=cells.astype(np.float32), | |
| area_px=areas, log_area_px=np.log(areas), instance_ids=labels, | |
| valid_count=np.asarray([len(result.cells) for result in results], dtype=np.int32), | |
| valid_coverage=np.asarray([result.row["valid_foreground_coverage"] for result in results]), | |
| all_count=np.asarray([result.row["n_instances_in_crop"] for result in results], dtype=np.int32), | |
| all_coverage=np.asarray([result.row["foreground_coverage_all"] for result in results]), | |
| border_excluded_count=np.asarray([result.row["n_instances_border_excluded"] for result in results], dtype=np.int32), | |
| ) | |
| with np.load(path, allow_pickle=False) as archive: | |
| if not np.array_equal(archive["cells_yx_log_area"], cells.astype(np.float32)) or not np.array_equal(archive["area_px"], areas): | |
| raise ValueError("Plan archive round trip failed") | |
| if not np.array_equal(np.diff(archive["offsets"]), archive["valid_count"]): | |
| raise ValueError("Plan offsets disagree with valid counts") | |
| HF_VALUE_TYPES = { | |
| "observation_id": "string", "condition_key": "string", "time_h": "int64", "regime": "string", | |
| "split": "string", "legacy_split": "string", "acquisition_group_id": "string", | |
| "n_instances_in_crop": "int64", "n_instances_border_excluded": "int64", "n_valid_instances": "int64", | |
| "foreground_coverage_all": "float64", "valid_foreground_coverage": "float64", | |
| "image_sha256": "string", "mask_sha256": "string", "pixel_sha256": "string", "mask_pixel_sha256": "string", | |
| "annotation_source": "string", | |
| } | |
| def hf_schema() -> pa.Schema: | |
| binary_image = pa.struct([pa.field("bytes", pa.binary()), pa.field("path", pa.string())]) | |
| fields = [pa.field("image", binary_image), pa.field("mask", binary_image)] | |
| features: dict[str, Any] = { | |
| "image": {"_type": "Image", "mode": "RGB"}, | |
| "mask": {"_type": "Image", "mode": "I;16"}, | |
| } | |
| types = {"string": pa.string(), "int64": pa.int64(), "float64": pa.float64()} | |
| for name, dtype in HF_VALUE_TYPES.items(): | |
| fields.append(pa.field(name, types[dtype])) | |
| features[name] = {"_type": "Value", "dtype": dtype} | |
| return pa.schema(fields, metadata={b"huggingface": json.dumps({"info": {"features": features}}).encode()}) | |
| def write_hf_shards(output_root: Path, rows: list[dict[str, Any]], shard_size: int) -> dict[str, Any]: | |
| reports: dict[str, Any] = {} | |
| schema = hf_schema() | |
| for split in SPLITS: | |
| subset = [row for row in rows if row["split"] == split] | |
| shards = [] | |
| for start in range(0, len(subset), shard_size): | |
| chunk = subset[start : start + shard_size] | |
| values = [] | |
| for row in chunk: | |
| values.append({ | |
| **{name: row[name] for name in HF_VALUE_TYPES}, | |
| "image": {"bytes": (output_root / row["image_path"]).read_bytes(), "path": row["image_path"]}, | |
| "mask": {"bytes": (output_root / row["mask_path"]).read_bytes(), "path": row["mask_path"]}, | |
| }) | |
| relative = f"data/{split}-{start // shard_size:05d}.parquet" | |
| pq.write_table(pa.Table.from_pylist(values, schema=schema), output_root / relative, compression="zstd") | |
| # Check the bytes used by HF as well as their decoded pixels. | |
| decoded = pq.read_table(output_root / relative).to_pylist() | |
| for expected, actual in zip(chunk, decoded, strict=True): | |
| for name in HF_VALUE_TYPES: | |
| if actual[name] != expected[name]: | |
| raise ValueError(f"HF shard metadata mismatch: {name}") | |
| for name in ("image", "mask"): | |
| payload = actual[name]["bytes"] | |
| if sha256_bytes(payload) != expected[f"{name}_sha256"]: | |
| raise ValueError(f"HF shard embedded byte mismatch: {expected['observation_id']}") | |
| with Image.open(io.BytesIO(payload)) as image: | |
| array = np.asarray(image) | |
| digest_key = "pixel_sha256" if name == "image" else "mask_pixel_sha256" | |
| if pixel_sha256(array) != expected[digest_key]: | |
| raise ValueError("HF shard embedded pixel mismatch") | |
| shards.append({"path": relative, "rows": len(chunk), "sha256": sha256_file(output_root / relative)}) | |
| print(f"shards {split}: {start + len(chunk)}/{len(subset)} fields", flush=True) | |
| reports[split] = {"fields": len(subset), "shards": shards} | |
| return reports | |
| def counts_by_condition(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: | |
| totals: dict[tuple[str, str], dict[str, Any]] = {} | |
| for row in rows: | |
| key = (row["split"], row["condition_key"]) | |
| total = totals.setdefault(key, {"split": key[0], "condition_key": key[1], "fields": 0, "all_instances": 0, "valid_instances": 0, "border_excluded_instances": 0}) | |
| total["fields"] += 1 | |
| total["all_instances"] += row["n_instances_in_crop"] | |
| total["valid_instances"] += row["n_valid_instances"] | |
| total["border_excluded_instances"] += row["n_instances_border_excluded"] | |
| return [totals[key] for key in sorted(totals)] | |
| def build_release( | |
| source_root: Path, output_root: Path, *, workers: int = 4, | |
| shard_size: int = 128, repo_id: str = REPO_ID, | |
| source_repo: str = SOURCE_REPO, source_revision: str = SOURCE_REVISION, | |
| ) -> dict[str, Any]: | |
| if workers < 1 or shard_size < 1: | |
| raise ValueError("Workers and shard size must be positive") | |
| if source_repo != SOURCE_REPO or source_revision != SOURCE_REVISION: | |
| raise ValueError("Source repository and revision must match the pinned CMFI release") | |
| source_root = source_root.resolve() | |
| output_root = validate_output_root(source_root, output_root) | |
| source_manifest = source_root / "canonical/fov_manifest.parquet" | |
| source_manifest_sha256 = sha256_file(source_manifest) | |
| if source_manifest_sha256 != SOURCE_MANIFEST_SHA256: | |
| raise ValueError("Source manifest does not match the audited pinned release receipt") | |
| source_rows = load_source_rows(source_root) | |
| # Reject impossible session protocols before writing any output. | |
| session_holdout(source_rows) | |
| output_root.mkdir(parents=True, exist_ok=False) | |
| for folder in ("images", "masks", "canonical", "metadata", "derived", "data"): | |
| (output_root / folder).mkdir() | |
| started = time.monotonic() | |
| results = [] | |
| with ThreadPoolExecutor(max_workers=workers) as pool: | |
| futures = [pool.submit(process_field, row, source_root, output_root) for row in source_rows] | |
| for index, future in enumerate(as_completed(futures), 1): | |
| results.append(future.result()) | |
| if index == 1 or index % 100 == 0 or index == len(source_rows): | |
| print(f"cropped/verified {index}/{len(source_rows)} fields; elapsed={time.monotonic() - started:.1f}s", flush=True) | |
| results.sort(key=lambda result: result.row["observation_id"]) | |
| rows = [result.row for result in results] | |
| leakage = check_pixel_leakage(rows) | |
| if sha256_file(source_manifest) != source_manifest_sha256: | |
| raise ValueError("Source manifest changed during build") | |
| for row in source_rows: | |
| for path_key, digest_key in (("image_path", "release_image_sha256"), ("mask_path", "mask_sha256")): | |
| if sha256_file(safe_source_path(source_root, row[path_key])) != row[digest_key]: | |
| raise ValueError(f"Source asset changed during build: {row['observation_id']}") | |
| canonical = pa.Table.from_pylist(rows) | |
| pq.write_table(canonical, output_root / "canonical/fov_manifest.parquet", compression="zstd") | |
| if pq.read_table(output_root / "canonical/fov_manifest.parquet").to_pylist() != rows: | |
| raise ValueError("Canonical manifest round trip failed") | |
| with (output_root / "metadata/field_counts.csv").open("w", newline="", encoding="utf-8") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=list(rows[0])) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| mapping, diagnostic = session_holdout(rows) | |
| pq.write_table(pa.Table.from_pylist(mapping), output_root / "metadata/session_holdout.parquet", compression="zstd") | |
| write_json(output_root / "metadata/train_normalization.json", train_normalization(results)) | |
| for split in SPLITS: | |
| write_plans(output_root / f"derived/{split}_plans.npz", [result for result in results if result.row["split"] == split]) | |
| protocol = { | |
| "schema_version": SCHEMA_VERSION, "repo_id": repo_id, | |
| "source_repo": source_repo, "source_revision": source_revision, | |
| "source_manifest_sha256": source_manifest_sha256, | |
| "image_processing": {"decoded_source_mode": "RGB", "source_size_wh": list(SOURCE_SIZE), "crop_box_xyxy": list(CROP_BOX), "output_size_wh": [SIZE, SIZE], "resize": False, "codec": "lossless PNG", "pixel_hash": "SHA256 of C-order RGB uint8 bytes"}, | |
| "mask_processing": {"annotation_source": ANNOTATION_SOURCE, "source_annotation_type": "Cellpose pseudo instances", "source_model_revision": None, "source_model_weights_sha256": None, "segmentation_reexecuted": False, "crop_box_xyxy": list(CROP_BOX), "resize": False, "labels": "source uint16 IDs preserved, including border-touching instances", "valid_rule": "nonzero source labels not touching any of the four output image edges", "coverage": "foreground union area divided by 1024*1024", "pixel_hash": "SHA256 of C-order little-endian uint16 bytes"}, | |
| "plans": {"annotation_source": ANNOTATION_SOURCE, "cell_columns": ["centroid_y / 1024", "centroid_x / 1024", "ln(area_px / (1024*1024))"], "coordinate_convention": "zero-based pixel-index centroid, no half-pixel shift", "area_rule": "all pixels of each valid source ID; no area filtering", "offsets": "field i occupies cells[offsets[i]:offsets[i+1]]", "instance_ids": "source labels aligned with packed cell arrays", "scientific_limit": "Pseudo-mask-derived reference plans; not independently verified cell truth or CPSAM re-segmentation"}, | |
| "legacy_split_policy": "Preserved source split assignments; identifiers and old content-group IDs retained", | |
| "test_exposure": "Existing observations and historical test use; republication does not create a blind test", | |
| "session_diagnostic": diagnostic, | |
| "normalization": "Statistics fitted only on legacy train; stored without modifying image pixels", | |
| "claims_blocked": ["biological replicate generalization", "continuous dynamics", "physiological accuracy", "metabolite or biomass prediction"], | |
| } | |
| write_json(output_root / "metadata/readout_protocol.json", protocol) | |
| split_report = { | |
| "legacy_field_counts": dict(sorted(Counter(row["split"] for row in rows).items())), | |
| "condition_counts": counts_by_condition(rows), "cropped_pixel_leakage": leakage, | |
| "session_diagnostic": diagnostic, | |
| "acquisition_groups_crossing_legacy_splits": sum(len({row["split"] for row in rows if row["acquisition_group_id"] == group}) > 1 for group in {row["acquisition_group_id"] for row in rows}), | |
| "biological_rep_labels_exported": False, | |
| } | |
| write_json(output_root / "metadata/split_report.json", split_report) | |
| shards = write_hf_shards(output_root, rows, shard_size) | |
| report = { | |
| "all_passed": True, "fields": len(rows), | |
| "source_image_sha256_verified": len(rows), "source_mask_sha256_verified": len(rows), | |
| "image_crop_pixel_equal": len(rows), "mask_crop_label_equal": len(rows), | |
| "mask_statistics_recomputed": len(rows), "hf_embedded_image_bytes_verified": len(rows), | |
| "hf_embedded_mask_bytes_verified": len(rows), "hf_embedded_image_pixels_verified": len(rows), | |
| "hf_embedded_mask_labels_verified": len(rows), | |
| "canonical_manifest_round_trip": True, "plan_archives_round_trip": True, | |
| "source_manifest_unchanged": True, "legacy_ids_and_splits_preserved": True, | |
| "source_assets_unchanged_at_final_check": True, | |
| "cross_split_cropped_pixel_duplicate_groups": 0, | |
| "source_manifest_sha256": source_manifest_sha256, | |
| "condition_counts": split_report["condition_counts"], "hf_shards": shards, | |
| "elapsed_seconds": time.monotonic() - started, | |
| "segmentation_reexecuted": False, "annotation_source": ANNOTATION_SOURCE, | |
| } | |
| try: | |
| write_json(output_root / "metadata/validation_report.json", report) | |
| files = sorted(path for path in output_root.rglob("*") if path.is_file()) | |
| checksum_path = output_root / "metadata/checksums.sha256" | |
| checksum_path.write_text("".join(f"{sha256_file(path)} {path.relative_to(output_root).as_posix()}\n" for path in files), encoding="utf-8") | |
| for line in checksum_path.read_text().splitlines(): | |
| digest, relative = line.split(maxsplit=1) | |
| if sha256_file(output_root / relative) != digest: | |
| raise ValueError(f"Final checksum verification failed: {relative}") | |
| except Exception: | |
| report["all_passed"] = False | |
| write_json(output_root / "metadata/validation_report.json", report) | |
| raise | |
| print(f"release validated: {len(rows)} fields at {output_root}", flush=True) | |
| return report | |
| def arguments() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--source-root", type=Path, required=True) | |
| parser.add_argument("--output-root", type=Path, required=True) | |
| parser.add_argument("--workers", type=int, default=4) | |
| parser.add_argument("--shard-size", type=int, default=128) | |
| parser.add_argument("--repo-id", default=REPO_ID) | |
| parser.add_argument("--source-repo", default=SOURCE_REPO) | |
| parser.add_argument("--source-revision", default=SOURCE_REVISION) | |
| return parser.parse_args() | |
| def main() -> None: | |
| args = arguments() | |
| build_release(**vars(args)) | |
| if __name__ == "__main__": | |
| main() | |