Spaces:
Running on Zero
Running on Zero
AutoPipeline 0.1.8: run Reader V3 (384 px patches); keep the Connect your tool panel
Browse files- CONNECT.md +6 -6
- README.md +14 -14
- app.py +78 -25
- connect.html +6 -6
- connect.json +6 -6
- inkspace.py +20 -15
- kit/auc.py +59 -24
- kit/fetch.py +29 -4
- kit/layers.py +16 -9
- kit/s3retry.py +10 -7
- kit/vc3d_audit.py +7 -5
- kit/vc3d_io.py +75 -10
- kit/vc3d_region.py +54 -6
- kit/verify.py +148 -17
- samples.json +49 -17
- scripts/vc3d/ink.py +372 -14
CONNECT.md
CHANGED
|
@@ -2,13 +2,13 @@
|
|
| 2 |
|
| 3 |
The segments this page analyzes and the model it runs are public, and both read straight from these URLs in your own tool.
|
| 4 |
|
| 5 |
-
Checked 2026-10-
|
| 6 |
|
| 7 |
## Call the analysis from code
|
| 8 |
|
| 9 |
`https://huggingface.co/spaces/SharpMeow/autopipeline-ink`
|
| 10 |
|
| 11 |
-
License: Code Apache 2.0; Reader
|
| 12 |
|
| 13 |
### Python /on_sample (tested 2026-10-24)
|
| 14 |
|
|
@@ -64,14 +64,14 @@ curl -s https://vesuvius-challenge-open-data.s3.us-east-1.amazonaws.com/PHerc084
|
|
| 64 |
curl -s https://vesuvius-challenge-open-data.s3.us-east-1.amazonaws.com/PHerc0841/segments/20260220213127-w00/surface-volumes/9.366um-1.2m-113keV-volume-20250821151531.zarr/0/.zarray # one level: shape, chunks, dtype, codec
|
| 65 |
```
|
| 66 |
|
| 67 |
-
## The model: Reader
|
| 68 |
|
| 69 |
-
`https://huggingface.co/domenicor046/reader-
|
| 70 |
|
| 71 |
-
License: MIT. sha256
|
| 72 |
|
| 73 |
### curl (tested 2026-10-24)
|
| 74 |
|
| 75 |
```bash
|
| 76 |
-
curl -L -O https://huggingface.co/domenicor046/reader-
|
| 77 |
```
|
|
|
|
| 2 |
|
| 3 |
The segments this page analyzes and the model it runs are public, and both read straight from these URLs in your own tool.
|
| 4 |
|
| 5 |
+
Checked 2026-10-25. Generated from `connect.json` by `kit spaceconnect` in [ChaseHendrick/Scrolls](https://github.com/ChaseHendrick/Scrolls).
|
| 6 |
|
| 7 |
## Call the analysis from code
|
| 8 |
|
| 9 |
`https://huggingface.co/spaces/SharpMeow/autopipeline-ink`
|
| 10 |
|
| 11 |
+
License: Code Apache 2.0; Reader V3 MIT; scans CC BY-NC 4.0. The Space has no MCP server; use gradio_client or curl. Each call spends the caller's ZeroGPU quota, which is small when logged out: pass hf_token= to Client (or an Authorization header to curl) for your own.
|
| 12 |
|
| 13 |
### Python /on_sample (tested 2026-10-24)
|
| 14 |
|
|
|
|
| 64 |
curl -s https://vesuvius-challenge-open-data.s3.us-east-1.amazonaws.com/PHerc0841/segments/20260220213127-w00/surface-volumes/9.366um-1.2m-113keV-volume-20250821151531.zarr/0/.zarray # one level: shape, chunks, dtype, codec
|
| 65 |
```
|
| 66 |
|
| 67 |
+
## The model: Reader V3 (Domenico Russo)
|
| 68 |
|
| 69 |
+
`https://huggingface.co/domenicor046/reader-v3/resolve/main/reader-v3.pth`
|
| 70 |
|
| 71 |
+
License: MIT. sha256 ea405417450abd8ace1b8ff79ebce3adb646c5e48ab95da46844d77efe984d8a; an ink_9um-format checkpoint for villa's ink detection, with 384 px patches in its config.
|
| 72 |
|
| 73 |
### curl (tested 2026-10-24)
|
| 74 |
|
| 75 |
```bash
|
| 76 |
+
curl -L -O https://huggingface.co/domenicor046/reader-v3/resolve/main/reader-v3.pth
|
| 77 |
```
|
README.md
CHANGED
|
@@ -9,14 +9,14 @@ app_file: app.py
|
|
| 9 |
suggested_hardware: zero-a10g
|
| 10 |
license: apache-2.0
|
| 11 |
models:
|
| 12 |
-
- domenicor046/reader-
|
| 13 |
-
short_description: Reader
|
| 14 |
pinned: false
|
| 15 |
---
|
| 16 |
|
| 17 |
# AutoPipeline ink step
|
| 18 |
|
| 19 |
-
Pick a crop of a released segment, or upload a small surface volume. The Space runs Reader
|
| 20 |
|
| 21 |
AutoPipeline runs villa's pipeline from a released scan to a scored ink map, with checks that can fail at every step. This Space is its last step only.
|
| 22 |
|
|
@@ -24,33 +24,33 @@ An ink map is model output, not a reading.
|
|
| 24 |
|
| 25 |
## What runs
|
| 26 |
|
| 27 |
-
- Model: [Reader
|
| 28 |
-
- Inference: villa's flat ink inference (`vesuvius.ink_detection.inference.infer`) at commit `e0bbb8b40a2db58b1d71864f286eb85717e59e64`, called in the Space's own process on an array in memory. Its settings are villa's defaults:
|
| 29 |
- Data: read anonymously from the [open-data bucket](https://vesuvius-challenge-open-data.s3.us-east-1.amazonaws.com) when you press Run analysis. Nothing is bundled.
|
| 30 |
- Checks: a map that is constant, has non-finite pixels, or equals its control is refused, not shown. The forward map is never shown without its control.
|
| 31 |
-
- Score: pixel AUC, the chance that a labelled ink pixel scores above a labelled background pixel, inside the labelled area. A 64 px edge is left out, where a crop sees less context than the whole segment.
|
| 32 |
|
| 33 |
## The samples
|
| 34 |
|
| 35 |
Each is a 640 px crop where the labels mark a lot of ink. I picked these windows with the labels, so none of them is a blind test.
|
| 36 |
|
| 37 |
-
| Sample | What it is to Reader
|
| 38 |
| --- | --- |
|
| 39 |
-
| PHerc0841 w00 | Development segment.
|
| 40 |
| PHerc0841 auto-grown 896 | Development segment, as above. |
|
| 41 |
-
| PHerc0139 w035 | Training data
|
| 42 |
-
| PHerc0139 w045 | Not held out: Reader
|
| 43 |
|
| 44 |
## Uploads
|
| 45 |
|
| 46 |
-
A surface volume as `.npy` or a multi-page `.tif`, layers first (layers x height x width), uint8 or uint16,
|
| 47 |
|
| 48 |
## GPU time
|
| 49 |
|
| 50 |
-
Each run is one GPU call with both directions in it. The call asks for 10 s plus
|
| 51 |
|
| 52 |
## Code
|
| 53 |
|
| 54 |
-
`app.py` is the page and the call into villa. `inkspace.py` holds the rest: the sample list and the segments the Space may read, crop sizing, the bucket reads, the checks and the scoring. They use AutoPipeline's `kit/` (the anonymous bucket reader and `kit/auc.py`) and `scripts/vc3d/ink.py` (the map checks). Code: Apache License 2.0. The model and the data keep their own licenses.
|
| 55 |
|
| 56 |
-
AutoPipeline's full source,
|
|
|
|
| 9 |
suggested_hardware: zero-a10g
|
| 10 |
license: apache-2.0
|
| 11 |
models:
|
| 12 |
+
- domenicor046/reader-v3
|
| 13 |
+
short_description: Reader V3 ink maps with a reversed-layer control
|
| 14 |
pinned: false
|
| 15 |
---
|
| 16 |
|
| 17 |
# AutoPipeline ink step
|
| 18 |
|
| 19 |
+
Pick a crop of a released segment, or upload a small surface volume. The Space runs Reader V3, Domenico Russo's community ink model, on it twice: once with the layers in their stored order, and once with the layers reversed. The reversed map is the control. A model that reads ink in depth order should do worse on it. Where the crop has published ink labels, both maps get a pixel AUC.
|
| 20 |
|
| 21 |
AutoPipeline runs villa's pipeline from a released scan to a scored ink map, with checks that can fail at every step. This Space is its last step only.
|
| 22 |
|
|
|
|
| 24 |
|
| 25 |
## What runs
|
| 26 |
|
| 27 |
+
- Model: [Reader V3](https://huggingface.co/domenicor046/reader-v3), file `reader-v3.pth` (MIT), by Domenico Russo. It continues Reader v2, itself a fine-tune of the released `ink_9um`, on 384 px tiles; it keeps `ink_9um`'s checkpoint format, so villa's ink detection loads it unchanged. It is AutoPipeline's default reader since version 0.1.8. Its author reports fewer false ink marks on blank papyrus than Reader v2 (Community report). This Space makes no claim that it reads ink better than Reader v2. The Space downloads it when it starts and refuses it unless its SHA-256 is `ea405417450abd8ace1b8ff79ebce3adb646c5e48ab95da46844d77efe984d8a`.
|
| 28 |
+
- Inference: villa's flat ink inference (`vesuvius.ink_detection.inference.infer`) at commit `e0bbb8b40a2db58b1d71864f286eb85717e59e64`, called in the Space's own process on an array in memory. Its settings are the checkpoint's own and villa's defaults: 384 px patches (from Reader V3's config), overlap 0.5, Hann blending, the middle 17 layers. These are the calls villa's command line makes for a zarr of the same crop (`--direction both`). On the GPU, villa runs this checkpoint in fp16, so the maps differ a little from a CPU run.
|
| 29 |
- Data: read anonymously from the [open-data bucket](https://vesuvius-challenge-open-data.s3.us-east-1.amazonaws.com) when you press Run analysis. Nothing is bundled.
|
| 30 |
- Checks: a map that is constant, has non-finite pixels, or equals its control is refused, not shown. The forward map is never shown without its control.
|
| 31 |
+
- Score: pixel AUC, the chance that a labelled ink pixel scores above a labelled background pixel, inside the labelled area. A 64 px edge is left out, where a crop sees less context than the whole segment. With 384 px patches a crop's map still differs from the whole segment's map further in, so a crop's AUC is a crop number, not the segment's.
|
| 32 |
|
| 33 |
## The samples
|
| 34 |
|
| 35 |
Each is a 640 px crop where the labels mark a lot of ink. I picked these windows with the labels, so none of them is a blind test.
|
| 36 |
|
| 37 |
+
| Sample | What it is to Reader V3 |
|
| 38 |
| --- | --- |
|
| 39 |
+
| PHerc0841 w00 | Development segment. Reader V3 was not trained on PHerc0841, and neither were Reader v2 and `ink_9um`, the models it continues. Reader V3's author benchmarked PHerc0841 while choosing its recipe, so it may have been selected on these segments. |
|
| 40 |
| PHerc0841 auto-grown 896 | Development segment, as above. |
|
| 41 |
+
| PHerc0139 w035 | Training data: `ink_9um` was trained on it, and Reader v2 and Reader V3 continue from `ink_9um`. A high AUC here only shows the pipeline runs. |
|
| 42 |
+
| PHerc0139 w045 | Not held out: Reader V3 was trained on this segment and on its 2.4 µm render, as Reader v2 was before it. A check on training data. |
|
| 43 |
|
| 44 |
## Uploads
|
| 45 |
|
| 46 |
+
A surface volume as `.npy` or a multi-page `.tif`, layers first (layers x height x width), uint8 or uint16, 384 to 768 px a side, 17 to 65 layers, at most 64 MB. Its shape and type are checked from the file's header before its data are read. When you press Analyze upload it is read into memory and its upload file is deleted; a file you upload but do not run is deleted within 11 minutes. The images of it (its middle layer and the two maps) are sent inside the page and never written to the Space's disk. Uploads get maps but no AUC, since there are no labels for them.
|
| 47 |
|
| 48 |
## GPU time
|
| 49 |
|
| 50 |
+
Each run is one GPU call with both directions in it. The call asks for 10 s plus 1 s per 384 px patch, at least 20 s: any crop the Space takes is at most 3 x 3 patches, so 28 s for a 640 px sample and for a 768 px upload. A crop that would need more than 60 s is refused. On Hugging Face the time counts against the daily GPU quota of whoever presses Run.
|
| 51 |
|
| 52 |
## Code
|
| 53 |
|
| 54 |
+
`app.py` is the page and the call into villa. `inkspace.py` holds the rest: the sample list and the segments the Space may read, crop sizing, the bucket reads, the checks and the scoring. They use AutoPipeline's `kit/` (the anonymous bucket reader and `kit/auc.py`) and `scripts/vc3d/ink.py` (the map checks). The Connect your tool panel (`connect.json`, `connect.html`, `CONNECT.md`) lists the data's URLs and ready snippets for other tools. Code: Apache License 2.0. The model and the data keep their own licenses.
|
| 55 |
|
| 56 |
+
AutoPipeline's full source, with these files, its tests and its guide: [ChaseHendrick/Scrolls, branch submission/progress-2026-10-fix8](https://github.com/ChaseHendrick/Scrolls/tree/submission/progress-2026-10-fix8/submissions/progress-2026-10-fix8/autopipeline).
|
app.py
CHANGED
|
@@ -1,9 +1,9 @@
|
|
| 1 |
"""AutoPipeline's ink step as a Hugging Face Space (Gradio).
|
| 2 |
|
| 3 |
A visitor picks a public sample crop of a released segment, or uploads a small surface volume, and gets two ink
|
| 4 |
-
maps from Reader
|
| 5 |
-
the same layers reversed (the control). Where the crop has published ink labels,
|
| 6 |
-
map is model output, not a reading.
|
| 7 |
|
| 8 |
The inference is villa's own flat ink inference (vesuvius.ink_detection.inference.infer, at the commit pinned in
|
| 9 |
samples.json), called in this process: villa's configure_model loads the checkpoint, and villa's
|
|
@@ -15,21 +15,25 @@ only to the decorated function `infer_pair`. Everything else runs on the CPU.
|
|
| 15 |
|
| 16 |
Locally: `python3 app.py` serves the page; `python3 app.py --sample 0841-w00 --size 256` runs one crop on this
|
| 17 |
machine and prints the receipt. VILLA_SRC names a local villa vesuvius/src instead of the pinned download;
|
| 18 |
-
INK_CACHE is where downloads are kept
|
| 19 |
-
|
|
|
|
|
|
|
| 20 |
"""
|
| 21 |
|
| 22 |
from __future__ import annotations
|
| 23 |
|
| 24 |
import argparse
|
|
|
|
|
|
|
| 25 |
import json
|
| 26 |
import os
|
| 27 |
import platform
|
| 28 |
import shutil
|
|
|
|
| 29 |
import subprocess
|
| 30 |
import sys
|
| 31 |
import tarfile
|
| 32 |
-
import tempfile
|
| 33 |
import time
|
| 34 |
import urllib.request
|
| 35 |
from pathlib import Path
|
|
@@ -50,7 +54,8 @@ CHECKPOINT = CATALOG["checkpoint"]
|
|
| 50 |
VILLA_COMMIT = CATALOG["villa_commit"]
|
| 51 |
VILLA_REPO = "https://github.com/ScrollPrize/villa.git"
|
| 52 |
VILLA_TARBALL = "https://codeload.github.com/ScrollPrize/villa/tar.gz/{commit}"
|
| 53 |
-
CACHE = Path(os.environ.get("INK_CACHE") or Path(
|
|
|
|
| 54 |
BATCH = 4
|
| 55 |
ENGINE = None
|
| 56 |
# Gradio refuses a bigger upload while it streams in, before the whole file is on disk.
|
|
@@ -63,6 +68,24 @@ def log(message):
|
|
| 63 |
|
| 64 |
# ---------------------------------------------------------------- villa and the checkpoint
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
def _git_commit(path):
|
| 67 |
try:
|
| 68 |
return subprocess.run(["git", "-C", str(path), "rev-parse", "HEAD"], capture_output=True, text=True,
|
|
@@ -126,7 +149,7 @@ def ensure_villa(cache=CACHE):
|
|
| 126 |
src, how = Path(os.environ["VILLA_SRC"]).expanduser().resolve(), "VILLA_SRC"
|
| 127 |
commit = _git_commit(src)
|
| 128 |
else:
|
| 129 |
-
dest =
|
| 130 |
if not (dest / "COMMIT").is_file():
|
| 131 |
log(f"fetching villa {VILLA_COMMIT[:12]}")
|
| 132 |
_fetch_villa(dest)
|
|
@@ -136,20 +159,21 @@ def ensure_villa(cache=CACHE):
|
|
| 136 |
if commit != VILLA_COMMIT:
|
| 137 |
log(f"warning: villa at {src} is {commit}, not the pinned {VILLA_COMMIT}")
|
| 138 |
if str(src) not in sys.path:
|
| 139 |
-
sys.path.
|
| 140 |
-
return {"source": how, "commit": commit, "pinned": VILLA_COMMIT}
|
| 141 |
|
| 142 |
|
| 143 |
def ensure_checkpoint(cache=CACHE):
|
| 144 |
-
"""The checkpoint samples.json names
|
| 145 |
-
samples.json (and, where the repository's readers.tsv is present, that file
|
|
|
|
| 146 |
row = inkspace.readers_row(CHECKPOINT["name"], ROOT)
|
| 147 |
if row is not None and (row["sha256"], row["url"]) != (CHECKPOINT["sha256"], CHECKPOINT["url"]):
|
| 148 |
raise RuntimeError(f"samples.json and readers.tsv disagree about {CHECKPOINT['name']}")
|
| 149 |
if os.environ.get("INK_CHECKPOINT"):
|
| 150 |
path = Path(os.environ["INK_CHECKPOINT"]).expanduser()
|
| 151 |
else:
|
| 152 |
-
path =
|
| 153 |
if not path.is_file():
|
| 154 |
log(f"downloading {CHECKPOINT['url']}")
|
| 155 |
path.parent.mkdir(parents=True, exist_ok=True)
|
|
@@ -158,10 +182,31 @@ def ensure_checkpoint(cache=CACHE):
|
|
| 158 |
with urllib.request.urlopen(req, timeout=600) as resp, open(part, "wb") as out:
|
| 159 |
shutil.copyfileobj(resp, out, 1 << 20)
|
| 160 |
os.replace(part, path)
|
| 161 |
-
|
|
|
|
| 162 |
if digest != CHECKPOINT["sha256"]:
|
| 163 |
raise RuntimeError(f"{path} has SHA-256 {digest}, expected {CHECKPOINT['sha256']}; refusing it")
|
| 164 |
-
return path, digest
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
|
| 166 |
|
| 167 |
class Engine:
|
|
@@ -170,11 +215,17 @@ class Engine:
|
|
| 170 |
def __init__(self, cache=CACHE):
|
| 171 |
t0 = time.time()
|
| 172 |
self.villa = ensure_villa(cache)
|
| 173 |
-
self.checkpoint, self.sha256 = ensure_checkpoint(cache)
|
| 174 |
import torch
|
| 175 |
from vesuvius.ink_detection.inference import infer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
self.torch, self.infer = torch, infer
|
| 177 |
self.cm = infer.configure_model(argparse.Namespace(checkpoint=self.checkpoint, amp_dtype="auto"))
|
|
|
|
| 178 |
got = (int(self.cm.patch_size), int(self.cm.input_depth))
|
| 179 |
if got != (inkspace.PATCH, inkspace.INPUT_DEPTH):
|
| 180 |
raise RuntimeError(f"checkpoint has patch and depth {got}, the Space is sized for "
|
|
@@ -434,11 +485,12 @@ def build_demo():
|
|
| 434 |
brief_notes = {}
|
| 435 |
for sample in CATALOG["samples"]:
|
| 436 |
if sample["role"] == "development":
|
| 437 |
-
brief = ("Development crop. The model was not trained on PHerc0841
|
| 438 |
-
"
|
|
|
|
| 439 |
elif sample["id"] == "0139-w045":
|
| 440 |
-
brief = ("Training segment. Reader
|
| 441 |
-
"
|
| 442 |
else:
|
| 443 |
brief = ("Training segment. The model was trained on this segment. A high AUC checks that the "
|
| 444 |
"pipeline runs; it is not an independent test.")
|
|
@@ -467,7 +519,7 @@ def build_demo():
|
|
| 467 |
<svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" stroke-width="1.5">
|
| 468 |
<path d="M4 6h14M4 11h14M4 16h14M7 3v16M15 3v16"/></svg></span>
|
| 469 |
<div><strong>AutoPipeline</strong><small>Vesuvius research tools</small></div></div>
|
| 470 |
-
<div class="ap-header-note"><strong>Reader
|
| 471 |
<div class="ap-page-heading"><div><h1>Ink analysis</h1>
|
| 472 |
<p>Inspect a surface volume alongside its ink map and reversed-layer control.</p></div>
|
| 473 |
<span class="ap-step">Surface volume → Ink inference → Comparison</span></div>''')
|
|
@@ -491,7 +543,7 @@ def build_demo():
|
|
| 491 |
gr.Markdown(inkspace.UPLOAD_TEXT)
|
| 492 |
run_up = gr.Button("Analyze upload", variant="primary", elem_id="ap-upload-run")
|
| 493 |
gr.HTML('''<section class="ap-source-meta" aria-label="Inference settings"><h3>Run settings</h3>
|
| 494 |
-
<dl><dt>Model</dt><dd>Reader
|
| 495 |
<dt>Directions</dt><dd>Stored + reversed</dd><dt>Sample crop</dt><dd>640 × 640 px</dd></dl>
|
| 496 |
<p>Sample data loads when you run. Both directions use the same model and settings.
|
| 497 |
GPU time counts against your Space quota.</p></section>''')
|
|
@@ -505,13 +557,14 @@ def build_demo():
|
|
| 505 |
receipt = gr.JSON(label="Model, inputs, settings and timings")
|
| 506 |
gr.Markdown("**Model output, not a reading.** Compare the ink map with its reversed-layer control. "
|
| 507 |
"Brightness alone does not establish legible ink.", elem_id="ap-footnote")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 508 |
with gr.Accordion("About this workflow", open=False, elem_id="ap-about"):
|
| 509 |
gr.Markdown(inkspace.INTRO)
|
| 510 |
gr.Markdown("### Selected sample")
|
| 511 |
sample_detail = gr.Markdown(notes[titles[0]])
|
| 512 |
-
with gr.Accordion("Connect your tool", open=False, elem_id="ap-connect"):
|
| 513 |
-
# The data's URLs and ready snippets, made by python -m kit spaceconnect in ChaseHendrick/Scrolls
|
| 514 |
-
gr.HTML((HERE / "connect.html").read_text() if (HERE / "connect.html").exists() else "")
|
| 515 |
gr.HTML('<footer class="ap-credit">Built by Chase Hendrick</footer>')
|
| 516 |
outputs = [images, text, receipt]
|
| 517 |
pick.change(lambda t: (brief_notes.get(t, ""), notes.get(t, "")), pick, [note, sample_detail])
|
|
|
|
| 1 |
"""AutoPipeline's ink step as a Hugging Face Space (Gradio).
|
| 2 |
|
| 3 |
A visitor picks a public sample crop of a released segment, or uploads a small surface volume, and gets two ink
|
| 4 |
+
maps from Reader V3 (Domenico Russo's community ink model, an ink_9um-format checkpoint named in samples.json): the
|
| 5 |
+
layers in their stored order, and the same layers reversed (the control). Where the crop has published ink labels,
|
| 6 |
+
both maps get a pixel AUC. An ink map is model output, not a reading.
|
| 7 |
|
| 8 |
The inference is villa's own flat ink inference (vesuvius.ink_detection.inference.infer, at the commit pinned in
|
| 9 |
samples.json), called in this process: villa's configure_model loads the checkpoint, and villa's
|
|
|
|
| 15 |
|
| 16 |
Locally: `python3 app.py` serves the page; `python3 app.py --sample 0841-w00 --size 256` runs one crop on this
|
| 17 |
machine and prints the receipt. VILLA_SRC names a local villa vesuvius/src instead of the pinned download;
|
| 18 |
+
INK_CACHE is where downloads are kept (default ~/.cache/autopipeline-ink, or under XDG_CACHE_HOME; it must belong to
|
| 19 |
+
you and be writable by no one else, since villa's code is imported from it); INK_CHECKPOINT names a local copy of
|
| 20 |
+
the checkpoint (its SHA-256 is still checked). The checkpoint is read once, its SHA-256 checked on those bytes, and
|
| 21 |
+
the same bytes loaded with torch's weights-only unpickler (villa's own loader would run any pickle code in a file).
|
| 22 |
"""
|
| 23 |
|
| 24 |
from __future__ import annotations
|
| 25 |
|
| 26 |
import argparse
|
| 27 |
+
import hashlib
|
| 28 |
+
import io
|
| 29 |
import json
|
| 30 |
import os
|
| 31 |
import platform
|
| 32 |
import shutil
|
| 33 |
+
import stat
|
| 34 |
import subprocess
|
| 35 |
import sys
|
| 36 |
import tarfile
|
|
|
|
| 37 |
import time
|
| 38 |
import urllib.request
|
| 39 |
from pathlib import Path
|
|
|
|
| 54 |
VILLA_COMMIT = CATALOG["villa_commit"]
|
| 55 |
VILLA_REPO = "https://github.com/ScrollPrize/villa.git"
|
| 56 |
VILLA_TARBALL = "https://codeload.github.com/ScrollPrize/villa/tar.gz/{commit}"
|
| 57 |
+
CACHE = Path(os.environ.get("INK_CACHE") or Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache")
|
| 58 |
+
/ "autopipeline-ink")
|
| 59 |
BATCH = 4
|
| 60 |
ENGINE = None
|
| 61 |
# Gradio refuses a bigger upload while it streams in, before the whole file is on disk.
|
|
|
|
| 68 |
|
| 69 |
# ---------------------------------------------------------------- villa and the checkpoint
|
| 70 |
|
| 71 |
+
def private_cache(cache=CACHE):
|
| 72 |
+
"""The cache folder, created 0700 when missing, and refused unless it is a real folder of this user that no one
|
| 73 |
+
else can write: villa's code is imported from it and the checkpoint read from it, so another local user who
|
| 74 |
+
could write there (a shared /tmp, say) could run code as you."""
|
| 75 |
+
cache = Path(cache)
|
| 76 |
+
cache.mkdir(mode=0o700, parents=True, exist_ok=True)
|
| 77 |
+
st = os.lstat(cache)
|
| 78 |
+
if not stat.S_ISDIR(st.st_mode):
|
| 79 |
+
raise RuntimeError(f"the ink cache {cache} is not a folder (a link?); set INK_CACHE to a folder of yours")
|
| 80 |
+
if hasattr(os, "getuid") and st.st_uid != os.getuid():
|
| 81 |
+
raise RuntimeError(f"the ink cache {cache} belongs to uid {st.st_uid}, not you ({os.getuid()}); "
|
| 82 |
+
"set INK_CACHE to a folder of yours")
|
| 83 |
+
if st.st_mode & 0o022:
|
| 84 |
+
raise RuntimeError(f"the ink cache {cache} is writable by others (mode {stat.S_IMODE(st.st_mode):o}); "
|
| 85 |
+
f"run chmod go-w on it or set INK_CACHE to a private folder")
|
| 86 |
+
return cache
|
| 87 |
+
|
| 88 |
+
|
| 89 |
def _git_commit(path):
|
| 90 |
try:
|
| 91 |
return subprocess.run(["git", "-C", str(path), "rev-parse", "HEAD"], capture_output=True, text=True,
|
|
|
|
| 149 |
src, how = Path(os.environ["VILLA_SRC"]).expanduser().resolve(), "VILLA_SRC"
|
| 150 |
commit = _git_commit(src)
|
| 151 |
else:
|
| 152 |
+
dest = private_cache(cache) / f"villa-{VILLA_COMMIT[:12]}"
|
| 153 |
if not (dest / "COMMIT").is_file():
|
| 154 |
log(f"fetching villa {VILLA_COMMIT[:12]}")
|
| 155 |
_fetch_villa(dest)
|
|
|
|
| 159 |
if commit != VILLA_COMMIT:
|
| 160 |
log(f"warning: villa at {src} is {commit}, not the pinned {VILLA_COMMIT}")
|
| 161 |
if str(src) not in sys.path:
|
| 162 |
+
sys.path.append(str(src)) # last: villa's folder must not shadow torch or another installed package
|
| 163 |
+
return {"source": how, "commit": commit, "pinned": VILLA_COMMIT, "src": str(src)}
|
| 164 |
|
| 165 |
|
| 166 |
def ensure_checkpoint(cache=CACHE):
|
| 167 |
+
"""The checkpoint's path (samples.json names it), its SHA-256 and its bytes: downloaded once, read once, and refused unless the
|
| 168 |
+
SHA-256 of the bytes read matches samples.json (and, where the repository's readers.tsv is present, that file
|
| 169 |
+
too). The caller loads these bytes, never the file again, so the file cannot change between check and load."""
|
| 170 |
row = inkspace.readers_row(CHECKPOINT["name"], ROOT)
|
| 171 |
if row is not None and (row["sha256"], row["url"]) != (CHECKPOINT["sha256"], CHECKPOINT["url"]):
|
| 172 |
raise RuntimeError(f"samples.json and readers.tsv disagree about {CHECKPOINT['name']}")
|
| 173 |
if os.environ.get("INK_CHECKPOINT"):
|
| 174 |
path = Path(os.environ["INK_CHECKPOINT"]).expanduser()
|
| 175 |
else:
|
| 176 |
+
path = private_cache(cache) / CHECKPOINT["name"] / CHECKPOINT["file"]
|
| 177 |
if not path.is_file():
|
| 178 |
log(f"downloading {CHECKPOINT['url']}")
|
| 179 |
path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 182 |
with urllib.request.urlopen(req, timeout=600) as resp, open(part, "wb") as out:
|
| 183 |
shutil.copyfileobj(resp, out, 1 << 20)
|
| 184 |
os.replace(part, path)
|
| 185 |
+
data = path.read_bytes()
|
| 186 |
+
digest = hashlib.sha256(data).hexdigest()
|
| 187 |
if digest != CHECKPOINT["sha256"]:
|
| 188 |
raise RuntimeError(f"{path} has SHA-256 {digest}, expected {CHECKPOINT['sha256']}; refusing it")
|
| 189 |
+
return path, digest, data
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def checked_loader(torch, path, data):
|
| 193 |
+
"""A stand-in for villa's load_checkpoint that returns the checked bytes, unpickled weights-only, for the
|
| 194 |
+
checkpoint and refuses to load any other file."""
|
| 195 |
+
def load_checkpoint(asked, *args, **kwargs):
|
| 196 |
+
if Path(str(asked)).expanduser().resolve() != Path(path).expanduser().resolve():
|
| 197 |
+
raise RuntimeError(f"villa asked to load {asked}, not the checked checkpoint {path}")
|
| 198 |
+
return torch.load(io.BytesIO(data), map_location="cpu", weights_only=True)
|
| 199 |
+
return load_checkpoint
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def use_checked_loader(loader):
|
| 203 |
+
"""Put loader in place of villa's load_checkpoint in every villa module that holds it."""
|
| 204 |
+
from vesuvius.ink_detection.models import checkpoint
|
| 205 |
+
unsafe = checkpoint.load_checkpoint
|
| 206 |
+
for name, mod in list(sys.modules.items()):
|
| 207 |
+
if name.split(".")[0] == "vesuvius" and getattr(mod, "load_checkpoint", None) is unsafe:
|
| 208 |
+
mod.load_checkpoint = loader
|
| 209 |
+
checkpoint.load_checkpoint = loader
|
| 210 |
|
| 211 |
|
| 212 |
class Engine:
|
|
|
|
| 215 |
def __init__(self, cache=CACHE):
|
| 216 |
t0 = time.time()
|
| 217 |
self.villa = ensure_villa(cache)
|
| 218 |
+
self.checkpoint, self.sha256, data = ensure_checkpoint(cache)
|
| 219 |
import torch
|
| 220 |
from vesuvius.ink_detection.inference import infer
|
| 221 |
+
src = Path(self.villa.pop("src")).resolve()
|
| 222 |
+
if src not in Path(infer.__file__).resolve().parents:
|
| 223 |
+
raise RuntimeError(f"vesuvius was imported from {infer.__file__}, not from villa at {src}: another "
|
| 224 |
+
"vesuvius is installed in this Python; uninstall it or set VILLA_SRC to it")
|
| 225 |
+
use_checked_loader(checked_loader(torch, self.checkpoint, data))
|
| 226 |
self.torch, self.infer = torch, infer
|
| 227 |
self.cm = infer.configure_model(argparse.Namespace(checkpoint=self.checkpoint, amp_dtype="auto"))
|
| 228 |
+
del data
|
| 229 |
got = (int(self.cm.patch_size), int(self.cm.input_depth))
|
| 230 |
if got != (inkspace.PATCH, inkspace.INPUT_DEPTH):
|
| 231 |
raise RuntimeError(f"checkpoint has patch and depth {got}, the Space is sized for "
|
|
|
|
| 485 |
brief_notes = {}
|
| 486 |
for sample in CATALOG["samples"]:
|
| 487 |
if sample["role"] == "development":
|
| 488 |
+
brief = ("Development crop. The model was not trained on PHerc0841, but its author benchmarked "
|
| 489 |
+
"PHerc0841 while choosing its recipe. This crop was selected using published labels; its "
|
| 490 |
+
"AUC is not a blind test.")
|
| 491 |
elif sample["id"] == "0139-w045":
|
| 492 |
+
brief = ("Training segment. Reader V3 was trained on this segment and on a 2.4 µm render of it. "
|
| 493 |
+
"This check is not held out.")
|
| 494 |
else:
|
| 495 |
brief = ("Training segment. The model was trained on this segment. A high AUC checks that the "
|
| 496 |
"pipeline runs; it is not an independent test.")
|
|
|
|
| 519 |
<svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" stroke-width="1.5">
|
| 520 |
<path d="M4 6h14M4 11h14M4 16h14M7 3v16M15 3v16"/></svg></span>
|
| 521 |
<div><strong>AutoPipeline</strong><small>Vesuvius research tools</small></div></div>
|
| 522 |
+
<div class="ap-header-note"><strong>Reader V3</strong>Community model · Paired control</div></header>
|
| 523 |
<div class="ap-page-heading"><div><h1>Ink analysis</h1>
|
| 524 |
<p>Inspect a surface volume alongside its ink map and reversed-layer control.</p></div>
|
| 525 |
<span class="ap-step">Surface volume → Ink inference → Comparison</span></div>''')
|
|
|
|
| 543 |
gr.Markdown(inkspace.UPLOAD_TEXT)
|
| 544 |
run_up = gr.Button("Analyze upload", variant="primary", elem_id="ap-upload-run")
|
| 545 |
gr.HTML('''<section class="ap-source-meta" aria-label="Inference settings"><h3>Run settings</h3>
|
| 546 |
+
<dl><dt>Model</dt><dd>Reader V3</dd><dt>Depth</dt><dd>Middle 17 layers</dd>
|
| 547 |
<dt>Directions</dt><dd>Stored + reversed</dd><dt>Sample crop</dt><dd>640 × 640 px</dd></dl>
|
| 548 |
<p>Sample data loads when you run. Both directions use the same model and settings.
|
| 549 |
GPU time counts against your Space quota.</p></section>''')
|
|
|
|
| 557 |
receipt = gr.JSON(label="Model, inputs, settings and timings")
|
| 558 |
gr.Markdown("**Model output, not a reading.** Compare the ink map with its reversed-layer control. "
|
| 559 |
"Brightness alone does not establish legible ink.", elem_id="ap-footnote")
|
| 560 |
+
with gr.Accordion("Connect your tool", open=False, elem_id="ap-connect"):
|
| 561 |
+
# The data's URLs and ready snippets, rendered by public Scrolls' spaceconnect tool and uploaded
|
| 562 |
+
# beside the Space's files; empty when they are not there
|
| 563 |
+
gr.HTML((HERE / "connect.html").read_text() if (HERE / "connect.html").exists() else "")
|
| 564 |
with gr.Accordion("About this workflow", open=False, elem_id="ap-about"):
|
| 565 |
gr.Markdown(inkspace.INTRO)
|
| 566 |
gr.Markdown("### Selected sample")
|
| 567 |
sample_detail = gr.Markdown(notes[titles[0]])
|
|
|
|
|
|
|
|
|
|
| 568 |
gr.HTML('<footer class="ap-credit">Built by Chase Hendrick</footer>')
|
| 569 |
outputs = [images, text, receipt]
|
| 570 |
pick.change(lambda t: (brief_notes.get(t, ""), notes.get(t, "")), pick, [note, sample_detail])
|
connect.html
CHANGED
|
@@ -18,7 +18,7 @@
|
|
| 18 |
<h2>Connect your tool</h2>
|
| 19 |
<p>The segments this page analyzes and the model it runs are public, and both read straight from these URLs in your own tool.</p>
|
| 20 |
<div class="scc-src" id="connect-api"><h3>Call the analysis from code</h3>
|
| 21 |
-
<p class="scc-meta">Code Apache 2.0; Reader
|
| 22 |
<div class="scc-url"><button type="button" class="scc-copy" data-testid="connect-copy" onclick="navigator.clipboard&&navigator.clipboard.writeText(this.parentNode.querySelector('code').innerText).then(()=>{this.textContent='Copied';setTimeout(()=>this.textContent='Copy',1200)})">Copy</button><pre><code>https://huggingface.co/spaces/SharpMeow/autopipeline-ink</code></pre></div>
|
| 23 |
<details><summary>Python /on_sample<span class="scc-b ok">tested 2026-10-24</span></summary>
|
| 24 |
<div class="scc-code"><button type="button" class="scc-copy" data-testid="connect-copy" onclick="navigator.clipboard&&navigator.clipboard.writeText(this.parentNode.querySelector('code').innerText).then(()=>{this.textContent='Copied';setTimeout(()=>this.textContent='Copy',1200)})">Copy</button><pre><code># pip install gradio_client
|
|
@@ -53,10 +53,10 @@ block = v[0:64, 2800:2864, 2900:2964]</code></pre></div></details>
|
|
| 53 |
<div class="scc-code"><button type="button" class="scc-copy" data-testid="connect-copy" onclick="navigator.clipboard&&navigator.clipboard.writeText(this.parentNode.querySelector('code').innerText).then(()=>{this.textContent='Copied';setTimeout(()=>this.textContent='Copy',1200)})">Copy</button><pre><code>curl -s https://vesuvius-challenge-open-data.s3.us-east-1.amazonaws.com/PHerc0841/segments/20260220213127-w00/surface-volumes/9.366um-1.2m-113keV-volume-20250821151531.zarr/.zattrs # OME multiscales metadata
|
| 54 |
curl -s https://vesuvius-challenge-open-data.s3.us-east-1.amazonaws.com/PHerc0841/segments/20260220213127-w00/surface-volumes/9.366um-1.2m-113keV-volume-20250821151531.zarr/0/.zarray # one level: shape, chunks, dtype, codec</code></pre></div></details>
|
| 55 |
</div>
|
| 56 |
-
<div class="scc-src" id="connect-model"><h3>The model: Reader
|
| 57 |
-
<p class="scc-meta">MIT · sha256
|
| 58 |
-
<div class="scc-url"><button type="button" class="scc-copy" data-testid="connect-copy" onclick="navigator.clipboard&&navigator.clipboard.writeText(this.parentNode.querySelector('code').innerText).then(()=>{this.textContent='Copied';setTimeout(()=>this.textContent='Copy',1200)})">Copy</button><pre><code>https://huggingface.co/domenicor046/reader-
|
| 59 |
<details><summary>curl<span class="scc-b ok">tested 2026-10-24</span></summary>
|
| 60 |
-
<div class="scc-code"><button type="button" class="scc-copy" data-testid="connect-copy" onclick="navigator.clipboard&&navigator.clipboard.writeText(this.parentNode.querySelector('code').innerText).then(()=>{this.textContent='Copied';setTimeout(()=>this.textContent='Copy',1200)})">Copy</button><pre><code>curl -L -O https://huggingface.co/domenicor046/reader-
|
| 61 |
</div>
|
| 62 |
-
<footer>Machine-readable: <a href="https://huggingface.co/spaces/SharpMeow/autopipeline-ink/blob/main/connect.json" target="_blank" rel="noopener">connect.json</a> and <a href="https://huggingface.co/spaces/SharpMeow/autopipeline-ink/blob/main/CONNECT.md" target="_blank" rel="noopener">CONNECT.md</a>. Checked 2026-10-
|
|
|
|
| 18 |
<h2>Connect your tool</h2>
|
| 19 |
<p>The segments this page analyzes and the model it runs are public, and both read straight from these URLs in your own tool.</p>
|
| 20 |
<div class="scc-src" id="connect-api"><h3>Call the analysis from code</h3>
|
| 21 |
+
<p class="scc-meta">Code Apache 2.0; Reader V3 MIT; scans CC BY-NC 4.0 · The Space has no MCP server; use gradio_client or curl. Each call spends the caller's ZeroGPU quota, which is small when logged out: pass hf_token= to Client (or an Authorization header to curl) for your own.</p>
|
| 22 |
<div class="scc-url"><button type="button" class="scc-copy" data-testid="connect-copy" onclick="navigator.clipboard&&navigator.clipboard.writeText(this.parentNode.querySelector('code').innerText).then(()=>{this.textContent='Copied';setTimeout(()=>this.textContent='Copy',1200)})">Copy</button><pre><code>https://huggingface.co/spaces/SharpMeow/autopipeline-ink</code></pre></div>
|
| 23 |
<details><summary>Python /on_sample<span class="scc-b ok">tested 2026-10-24</span></summary>
|
| 24 |
<div class="scc-code"><button type="button" class="scc-copy" data-testid="connect-copy" onclick="navigator.clipboard&&navigator.clipboard.writeText(this.parentNode.querySelector('code').innerText).then(()=>{this.textContent='Copied';setTimeout(()=>this.textContent='Copy',1200)})">Copy</button><pre><code># pip install gradio_client
|
|
|
|
| 53 |
<div class="scc-code"><button type="button" class="scc-copy" data-testid="connect-copy" onclick="navigator.clipboard&&navigator.clipboard.writeText(this.parentNode.querySelector('code').innerText).then(()=>{this.textContent='Copied';setTimeout(()=>this.textContent='Copy',1200)})">Copy</button><pre><code>curl -s https://vesuvius-challenge-open-data.s3.us-east-1.amazonaws.com/PHerc0841/segments/20260220213127-w00/surface-volumes/9.366um-1.2m-113keV-volume-20250821151531.zarr/.zattrs # OME multiscales metadata
|
| 54 |
curl -s https://vesuvius-challenge-open-data.s3.us-east-1.amazonaws.com/PHerc0841/segments/20260220213127-w00/surface-volumes/9.366um-1.2m-113keV-volume-20250821151531.zarr/0/.zarray # one level: shape, chunks, dtype, codec</code></pre></div></details>
|
| 55 |
</div>
|
| 56 |
+
<div class="scc-src" id="connect-model"><h3>The model: Reader V3 (Domenico Russo)</h3>
|
| 57 |
+
<p class="scc-meta">MIT · sha256 ea405417450abd8ace1b8ff79ebce3adb646c5e48ab95da46844d77efe984d8a; an ink_9um-format checkpoint for villa's ink detection, with 384 px patches in its config.</p>
|
| 58 |
+
<div class="scc-url"><button type="button" class="scc-copy" data-testid="connect-copy" onclick="navigator.clipboard&&navigator.clipboard.writeText(this.parentNode.querySelector('code').innerText).then(()=>{this.textContent='Copied';setTimeout(()=>this.textContent='Copy',1200)})">Copy</button><pre><code>https://huggingface.co/domenicor046/reader-v3/resolve/main/reader-v3.pth</code></pre></div>
|
| 59 |
<details><summary>curl<span class="scc-b ok">tested 2026-10-24</span></summary>
|
| 60 |
+
<div class="scc-code"><button type="button" class="scc-copy" data-testid="connect-copy" onclick="navigator.clipboard&&navigator.clipboard.writeText(this.parentNode.querySelector('code').innerText).then(()=>{this.textContent='Copied';setTimeout(()=>this.textContent='Copy',1200)})">Copy</button><pre><code>curl -L -O https://huggingface.co/domenicor046/reader-v3/resolve/main/reader-v3.pth</code></pre></div></details>
|
| 61 |
</div>
|
| 62 |
+
<footer>Machine-readable: <a href="https://huggingface.co/spaces/SharpMeow/autopipeline-ink/blob/main/connect.json" target="_blank" rel="noopener">connect.json</a> and <a href="https://huggingface.co/spaces/SharpMeow/autopipeline-ink/blob/main/CONNECT.md" target="_blank" rel="noopener">CONNECT.md</a>. Checked 2026-10-25. "Tested" means the snippet ran against this public data on that date. Scan data keeps its own license (the Vesuvius Challenge open data is CC BY-NC 4.0).</footer></section>
|
connect.json
CHANGED
|
@@ -2,23 +2,23 @@
|
|
| 2 |
"schema": "space-connect/1",
|
| 3 |
"space": "SharpMeow/autopipeline-ink",
|
| 4 |
"title": "AutoPipeline ink",
|
| 5 |
-
"checked": "2026-10-
|
| 6 |
"intro": "The segments this page analyzes and the model it runs are public, and both read straight from these URLs in your own tool.",
|
| 7 |
"sources": [
|
| 8 |
{"id": "api", "title": "Call the analysis from code", "kind": "gradio-api",
|
| 9 |
"url": "https://huggingface.co/spaces/SharpMeow/autopipeline-ink", "space": "SharpMeow/autopipeline-ink",
|
| 10 |
"host": "https://sharpmeow-autopipeline-ink.hf.space", "status": "running", "tools": ["python", "curl"],
|
| 11 |
"endpoints": [{"api": "/on_sample", "args": {"title": "PHerc0841 w00 (development segment)"}}],
|
| 12 |
-
"license": "Code Apache 2.0; Reader
|
| 13 |
-
"note": "The Space has no MCP server; use gradio_client or curl."},
|
| 14 |
{"id": "layers", "title": "The layers it reads, example PHerc0841 w00 (9.366 um surface volume)", "kind": "ome-zarr",
|
| 15 |
"url": "https://vesuvius-challenge-open-data.s3.us-east-1.amazonaws.com/PHerc0841/segments/20260220213127-w00/surface-volumes/9.366um-1.2m-113keV-volume-20250821151531.zarr",
|
| 16 |
"zarr_format": 2, "example": {"level": "0", "start": [0, 2800, 2900]}, "tools": ["zarr", "vesuvius", "curl"],
|
| 17 |
"license": "CC BY-NC 4.0 (Vesuvius Challenge open data)",
|
| 18 |
"browse": "https://scrollprize.org/data_browser/PHerc0841"},
|
| 19 |
-
{"id": "model", "title": "The model: Reader
|
| 20 |
-
"url": "https://huggingface.co/domenicor046/reader-
|
| 21 |
"tools": ["curl"], "license": "MIT",
|
| 22 |
-
"note": "sha256
|
| 23 |
]
|
| 24 |
}
|
|
|
|
| 2 |
"schema": "space-connect/1",
|
| 3 |
"space": "SharpMeow/autopipeline-ink",
|
| 4 |
"title": "AutoPipeline ink",
|
| 5 |
+
"checked": "2026-10-25",
|
| 6 |
"intro": "The segments this page analyzes and the model it runs are public, and both read straight from these URLs in your own tool.",
|
| 7 |
"sources": [
|
| 8 |
{"id": "api", "title": "Call the analysis from code", "kind": "gradio-api",
|
| 9 |
"url": "https://huggingface.co/spaces/SharpMeow/autopipeline-ink", "space": "SharpMeow/autopipeline-ink",
|
| 10 |
"host": "https://sharpmeow-autopipeline-ink.hf.space", "status": "running", "tools": ["python", "curl"],
|
| 11 |
"endpoints": [{"api": "/on_sample", "args": {"title": "PHerc0841 w00 (development segment)"}}],
|
| 12 |
+
"license": "Code Apache 2.0; Reader V3 MIT; scans CC BY-NC 4.0",
|
| 13 |
+
"note": "The Space has no MCP server; use gradio_client or curl. Each call spends the caller's ZeroGPU quota, which is small when logged out: pass hf_token= to Client (or an Authorization header to curl) for your own."},
|
| 14 |
{"id": "layers", "title": "The layers it reads, example PHerc0841 w00 (9.366 um surface volume)", "kind": "ome-zarr",
|
| 15 |
"url": "https://vesuvius-challenge-open-data.s3.us-east-1.amazonaws.com/PHerc0841/segments/20260220213127-w00/surface-volumes/9.366um-1.2m-113keV-volume-20250821151531.zarr",
|
| 16 |
"zarr_format": 2, "example": {"level": "0", "start": [0, 2800, 2900]}, "tools": ["zarr", "vesuvius", "curl"],
|
| 17 |
"license": "CC BY-NC 4.0 (Vesuvius Challenge open data)",
|
| 18 |
"browse": "https://scrollprize.org/data_browser/PHerc0841"},
|
| 19 |
+
{"id": "model", "title": "The model: Reader V3 (Domenico Russo)", "kind": "file",
|
| 20 |
+
"url": "https://huggingface.co/domenicor046/reader-v3/resolve/main/reader-v3.pth", "format": "bytes",
|
| 21 |
"tools": ["curl"], "license": "MIT",
|
| 22 |
+
"note": "sha256 ea405417450abd8ace1b8ff79ebce3adb646c5e48ab95da46844d77efe984d8a; an ink_9um-format checkpoint for villa's ink detection, with 384 px patches in its config."}
|
| 23 |
]
|
| 24 |
}
|
inkspace.py
CHANGED
|
@@ -28,9 +28,9 @@ HERE = Path(__file__).resolve().parent
|
|
| 28 |
SAMPLES_FILE = HERE / "samples.json"
|
| 29 |
BUCKET = "https://vesuvius-challenge-open-data.s3.us-east-1.amazonaws.com"
|
| 30 |
|
| 31 |
-
# The only segments the Space reads, with what each one is to its model (Reader
|
| 32 |
-
#
|
| 33 |
-
# the Space at other data.
|
| 34 |
ALLOWED = {
|
| 35 |
("PHerc0841", "20260220213127-w00"): "development",
|
| 36 |
("PHerc0841", "20260220214732-auto_grown_20260220144552896"): "development",
|
|
@@ -38,10 +38,10 @@ ALLOWED = {
|
|
| 38 |
("PHerc0139", "20260126000000-w045_2026012619"): "training",
|
| 39 |
}
|
| 40 |
|
| 41 |
-
# villa's flat inference for
|
| 42 |
-
# 0.5 (stride
|
| 43 |
-
PATCH =
|
| 44 |
-
STRIDE =
|
| 45 |
INPUT_DEPTH = 17
|
| 46 |
INNER = 64 # edge left out of the AUC: a crop sees less context there than the whole segment does
|
| 47 |
LABEL_LEVEL = "2" # the 2.4 um labels' level 2 is the 9 um surface grid up to a uniform scale (kit/auc.py)
|
|
@@ -59,13 +59,18 @@ DTYPES = ("uint8", "uint16")
|
|
| 59 |
CACHE_SWEEP_S, UPLOAD_MAX_AGE_S = 60, 600
|
| 60 |
UNRUN_UPLOAD_MINUTES = (CACHE_SWEEP_S + UPLOAD_MAX_AGE_S) // 60
|
| 61 |
|
| 62 |
-
# One GPU call per run, both directions. Seconds per
|
| 63 |
-
# which runs in the call too (
|
| 64 |
-
#
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
| 66 |
OVERHEAD_S = 10.0
|
| 67 |
MIN_GPU_S, MAX_GPU_S = 20, 60
|
| 68 |
|
|
|
|
|
|
|
| 69 |
SPACE_FILES = ("README.md", "app.py", "inkspace.py", "samples.json", "requirements.txt")
|
| 70 |
KIT_MODULES = ("__init__", "auc", "fetch", "keepalive", "layers", "s3retry", "vc3d_audit", "vc3d_io", "vc3d_region",
|
| 71 |
"verify")
|
|
@@ -73,10 +78,10 @@ EXTRA_FILES = ("scripts/vc3d/ink.py", "LICENSE")
|
|
| 73 |
|
| 74 |
INTRO = """# AutoPipeline ink step
|
| 75 |
|
| 76 |
-
Pick a crop of a released segment, or upload a small surface volume. The Space runs Reader
|
| 77 |
-
|
| 78 |
-
with the layers reversed. The reversed map is the control. A model that reads ink in
|
| 79 |
-
it. Where the crop has published ink labels, both maps get a pixel AUC.
|
| 80 |
|
| 81 |
AutoPipeline runs villa's pipeline from a released scan to a scored ink map, with checks that can fail at every
|
| 82 |
step. This is its last step only.
|
|
|
|
| 28 |
SAMPLES_FILE = HERE / "samples.json"
|
| 29 |
BUCKET = "https://vesuvius-challenge-open-data.s3.us-east-1.amazonaws.com"
|
| 30 |
|
| 31 |
+
# The only segments the Space reads, with what each one is to its model (Reader V3, and Reader v2 and ink_9um, the
|
| 32 |
+
# models it continues). Anything else is refused before a byte is fetched, so a sample file edited by mistake
|
| 33 |
+
# cannot point the Space at other data.
|
| 34 |
ALLOWED = {
|
| 35 |
("PHerc0841", "20260220213127-w00"): "development",
|
| 36 |
("PHerc0841", "20260220214732-auto_grown_20260220144552896"): "development",
|
|
|
|
| 38 |
("PHerc0139", "20260126000000-w045_2026012619"): "training",
|
| 39 |
}
|
| 40 |
|
| 41 |
+
# villa's flat inference for Reader V3, whose config asks for 17 x 384 x 384 patches (Reader v2 and ink_9um: 128 px):
|
| 42 |
+
# villa's default overlap 0.5 (stride 192), Hann blending.
|
| 43 |
+
PATCH = 384
|
| 44 |
+
STRIDE = 192
|
| 45 |
INPUT_DEPTH = 17
|
| 46 |
INNER = 64 # edge left out of the AUC: a crop sees less context there than the whole segment does
|
| 47 |
LABEL_LEVEL = "2" # the 2.4 um labels' level 2 is the 9 um surface grid up to a uniform scale (kit/auc.py)
|
|
|
|
| 59 |
CACHE_SWEEP_S, UPLOAD_MAX_AGE_S = 60, 600
|
| 60 |
UNRUN_UPLOAD_MINUTES = (CACHE_SWEEP_S + UPLOAD_MAX_AGE_S) // 60
|
| 61 |
|
| 62 |
+
# One GPU call per run, both directions. Seconds per 384 px patch inside the call: villa's per-patch normalisation,
|
| 63 |
+
# which runs on the CPU in the call too (about 0.03 s per 128 px patch on a 4-core CPU, 13 Oct 2026, so about nine
|
| 64 |
+
# times that here), and the model's forward pass. The whole call took 2.1 s a patch on a 4-core CPU with no GPU
|
| 65 |
+
# (PHerc0841 w00 crop, 25 Oct 2026); on the GPU the forward pass is a small part of that, so 1 s leaves room. The
|
| 66 |
+
# overhead covers moving the model and starting CUDA. Any crop the Space takes is 3 x 3 patches at most, so a call
|
| 67 |
+
# asks for 28 s.
|
| 68 |
+
SEC_PER_PATCH = 1.0
|
| 69 |
OVERHEAD_S = 10.0
|
| 70 |
MIN_GPU_S, MAX_GPU_S = 20, 60
|
| 71 |
|
| 72 |
+
# The Connect your tool panel (CONNECT.md, connect.html, connect.json) is not among them: public Scrolls renders it
|
| 73 |
+
# with its spaceconnect tool and it is uploaded beside these; app.py shows connect.html when it is there
|
| 74 |
SPACE_FILES = ("README.md", "app.py", "inkspace.py", "samples.json", "requirements.txt")
|
| 75 |
KIT_MODULES = ("__init__", "auc", "fetch", "keepalive", "layers", "s3retry", "vc3d_audit", "vc3d_io", "vc3d_region",
|
| 76 |
"verify")
|
|
|
|
| 78 |
|
| 79 |
INTRO = """# AutoPipeline ink step
|
| 80 |
|
| 81 |
+
Pick a crop of a released segment, or upload a small surface volume. The Space runs Reader V3, Domenico Russo's
|
| 82 |
+
community ink model continued from Reader v2 and the released `ink_9um`, on it twice: once with the layers in
|
| 83 |
+
their stored order, and once with the layers reversed. The reversed map is the control. A model that reads ink in
|
| 84 |
+
depth order should do worse on it. Where the crop has published ink labels, both maps get a pixel AUC.
|
| 85 |
|
| 86 |
AutoPipeline runs villa's pipeline from a released scan to a scored ink map, with checks that can fail at every
|
| 87 |
step. This is its last step only.
|
kit/auc.py
CHANGED
|
@@ -1,16 +1,16 @@
|
|
| 1 |
"""Pixel AUC of an ink map against a segment's published ink labels.
|
| 2 |
|
| 3 |
-
On a
|
| 4 |
-
w045 for v8in only, since ink_9um trained on its 2.4 um
|
| 5 |
-
number: the chance that a
|
| 6 |
-
|
| 7 |
-
|
| 8 |
reports, not checked here): `ink_9um` on PHerc0841 team surfaces, 0.74 to 0.81 (Bullo27);
|
| 9 |
on the PHerc0139 title, 0.81 to 0.95 depending on the checkpoint (Nieuwlaar).
|
| 10 |
|
| 11 |
The labels sit on the 2.4 um scan's grid. Its pyramid level 2 is the 9 um surface grid up
|
| 12 |
to a uniform scale (w045: 5,820 x 8,020 labels for 5,980 x 8,240 surface pixels), so labels
|
| 13 |
-
are mapped onto the map by nearest
|
| 14 |
refused. A map that covers only a window of the surface gives that window with `crop` and
|
| 15 |
the full surface shape with `surface_shape`.
|
| 16 |
|
|
@@ -22,7 +22,7 @@ Pixels where the map is exactly 0 are left out by default: villa and v8in write
|
|
| 22 |
they made no prediction (outside the surface). The count is reported.
|
| 23 |
|
| 24 |
Sampling noise: a segment's labels cover about 1 cm2 (PHerc0841: 0.9 to 1.4 cm2 each), and
|
| 25 |
-
|
| 26 |
suggests. `bootstrap` resamples square blocks (default 107 px, 1 mm at 9.366 um) with
|
| 27 |
replacement and reports a 95 % interval; `compare` scores a second map on the same pixels
|
| 28 |
with the same draws and reports the difference, its interval, and the share of draws in
|
|
@@ -35,10 +35,9 @@ Two options change which labels count, the same way for the map, its control and
|
|
| 35 |
exclude boxes (y0 y1 x0 x1 on the surface grid, the same frame as `crop`), each grown by `exclude_margin`
|
| 36 |
pixels on every side and clipped to the surface, are removed from the supervision mask: a region
|
| 37 |
that was looked at before (a window chosen with labels) is left out of a later score. The pixels and
|
| 38 |
-
the
|
| 39 |
offset the labels are moved by (dy, dx) surface pixels after they are mapped onto the map's grid:
|
| 40 |
-
label[y, x] = stretched[y - dy, x - dx] (TAUIL-Abd-Elilah's label-equivalent convention,
|
| 41 |
-
kit.transplant.shift2d), so (-6, -7) takes each pixel's label from 6 rows down and 7 columns right.
|
| 42 |
Pixels whose source falls outside the surface (the vacated edge) leave the mask. The offset is applied
|
| 43 |
on the whole surface, so a cropped map and the same window cut from a whole map get the same labels.
|
| 44 |
"""
|
|
@@ -60,6 +59,14 @@ def _load(path):
|
|
| 60 |
return load_map(path)
|
| 61 |
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
def _levels(path, level):
|
| 64 |
try:
|
| 65 |
s3retry.refuse_remote(path, "kit auc")
|
|
@@ -77,15 +84,35 @@ def _levels(path, level):
|
|
| 77 |
return node
|
| 78 |
|
| 79 |
|
|
|
|
|
|
|
|
|
|
| 80 |
def _quantize(np, values):
|
| 81 |
-
"""Integer scores for exact histogram AUC: uint8 and uint16 as is, floats to 0..65535.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
if values.dtype in (np.uint8, np.uint16):
|
| 83 |
return values.astype(np.int64), 65536
|
| 84 |
v = values.astype(np.float64)
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
|
| 91 |
def auc_scores(ink_scores, background_scores):
|
|
@@ -118,7 +145,7 @@ def _axis_index(start, stop, n_surface, n_labels, scale, shift=0):
|
|
| 118 |
|
| 119 |
|
| 120 |
def label_index(labels_shape, surface_shape, crop, map_shape, offset=(0, 0)):
|
| 121 |
-
"""Row and column indices into the labels for every map pixel (nearest
|
| 122 |
offset (dy, dx) surface pixels, and per row and column whether the label's source is on the surface."""
|
| 123 |
sy = labels_shape[0] / surface_shape[0]
|
| 124 |
sx = labels_shape[1] / surface_shape[1]
|
|
@@ -140,7 +167,7 @@ def label_index(labels_shape, surface_shape, crop, map_shape, offset=(0, 0)):
|
|
| 140 |
|
| 141 |
|
| 142 |
def label_grid(labels_shape, surface_shape, crop, map_shape):
|
| 143 |
-
"""Row and column indices into the labels for every map pixel (nearest
|
| 144 |
rows, cols, _, _ = label_index(labels_shape, surface_shape, crop, map_shape)
|
| 145 |
return rows, cols
|
| 146 |
|
|
@@ -255,7 +282,11 @@ def block_bootstrap(prediction, ink, mask, draws=300, block_px=BLOCK_PX, seed=0,
|
|
| 255 |
if len(ys) == 0:
|
| 256 |
raise VerifyError("no supervised pixels to resample")
|
| 257 |
keys = (ys // block_px) * (prediction.shape[1] // block_px + 1) + xs // block_px
|
| 258 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
lab = ink[ys, xs]
|
| 260 |
if lab.all() or not lab.any():
|
| 261 |
raise VerifyError("the mask holds only one class; no AUC to resample")
|
|
@@ -264,9 +295,9 @@ def block_bootstrap(prediction, ink, mask, draws=300, block_px=BLOCK_PX, seed=0,
|
|
| 264 |
q, _ = _quantize(np, m)
|
| 265 |
top = 255 if m.dtype == np.uint8 else 65535 # _quantize keeps uint8 as 0..255
|
| 266 |
qb = q[ys, xs] * (BOOT_BINS - 1) // top
|
| 267 |
-
|
| 268 |
-
np.
|
| 269 |
-
np.
|
| 270 |
hists.append((hi, hb))
|
| 271 |
rng = np.random.default_rng(seed)
|
| 272 |
w = np.stack([np.bincount(rng.integers(0, len(blocks), len(blocks)), minlength=len(blocks))
|
|
@@ -278,7 +309,7 @@ def block_bootstrap(prediction, ink, mask, draws=300, block_px=BLOCK_PX, seed=0,
|
|
| 278 |
if other is not None:
|
| 279 |
full = [float(_auc_hist(np, hi.sum(0), hb.sum(0))) for hi, hb in hists]
|
| 280 |
exact = []
|
| 281 |
-
for m in maps: # every
|
| 282 |
q, _ = _quantize(np, m)
|
| 283 |
v = q[ys, xs]
|
| 284 |
exact.append(auc_scores(v[lab], v[~lab]))
|
|
@@ -327,6 +358,10 @@ def score_files(prediction, labels, mask, control=None, level=DEFAULT_LEVEL, cro
|
|
| 327 |
ctrl = np.squeeze(_load(control))
|
| 328 |
if ctrl.shape != pred.shape:
|
| 329 |
raise VerifyError(f"control shape {ctrl.shape} differs from the map's {pred.shape}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
result["control"] = score_array(ctrl, ink, supervised, keep_zero, inner)
|
| 331 |
if bootstrap or compare is not None:
|
| 332 |
other = None
|
|
@@ -357,7 +392,7 @@ def format_result(result):
|
|
| 357 |
"left out of the mask")
|
| 358 |
ex = result.get("excluded")
|
| 359 |
if ex:
|
| 360 |
-
kept = "" if ex["ink_share_kept"] is None else f", {ex['ink_share_kept']:.1%} of the
|
| 361 |
rows.append(f"excluded {len(ex['grown'])} box(es) grown by {ex['margin']} px: {ex['grown']}; "
|
| 362 |
f"{ex['supervised_px_removed']} supervised px removed ({ex['ink_px_removed']} ink){kept}")
|
| 363 |
rows.append(line("map ", result["forward"]))
|
|
@@ -375,6 +410,6 @@ def format_result(result):
|
|
| 375 |
verdict = ("ahead beyond sampling noise" if c["ci95"][0] > 0 else
|
| 376 |
"behind beyond sampling noise" if c["ci95"][1] < 0 else "not distinguishable from noise")
|
| 377 |
rows.append(f"map minus compared map: {c['difference']:+.4f} ({c['difference_exact']:+.4f} at every "
|
| 378 |
-
f"
|
| 379 |
f"shared px: {verdict}")
|
| 380 |
return "\n".join(rows)
|
|
|
|
| 1 |
"""Pixel AUC of an ink map against a segment's published ink labels.
|
| 2 |
|
| 3 |
+
On a labeled segment no model was trained on (PHerc0841 for the released readers but not for Hecate,
|
| 4 |
+
see `held_out` in docs/results.json; PHerc0139 w045 for v8in only, since ink_9um trained on its 2.4 um
|
| 5 |
+
render), this is the generalization number: the chance that a labeled ink pixel scores above a
|
| 6 |
+
labeled non-ink pixel. Only pixels inside the supervision mask count, because the
|
| 7 |
+
labelers marked ink and non-ink there and nowhere else. Reference values (Community
|
| 8 |
reports, not checked here): `ink_9um` on PHerc0841 team surfaces, 0.74 to 0.81 (Bullo27);
|
| 9 |
on the PHerc0139 title, 0.81 to 0.95 depending on the checkpoint (Nieuwlaar).
|
| 10 |
|
| 11 |
The labels sit on the 2.4 um scan's grid. Its pyramid level 2 is the 9 um surface grid up
|
| 12 |
to a uniform scale (w045: 5,820 x 8,020 labels for 5,980 x 8,240 surface pixels), so labels
|
| 13 |
+
are mapped onto the map by nearest neighbor, and a scale that differs between the axes is
|
| 14 |
refused. A map that covers only a window of the surface gives that window with `crop` and
|
| 15 |
the full surface shape with `surface_shape`.
|
| 16 |
|
|
|
|
| 22 |
they made no prediction (outside the surface). The count is reported.
|
| 23 |
|
| 24 |
Sampling noise: a segment's labels cover about 1 cm2 (PHerc0841: 0.9 to 1.4 cm2 each), and
|
| 25 |
+
neighboring pixels are not independent, so an AUC carries more noise than its pixel count
|
| 26 |
suggests. `bootstrap` resamples square blocks (default 107 px, 1 mm at 9.366 um) with
|
| 27 |
replacement and reports a 95 % interval; `compare` scores a second map on the same pixels
|
| 28 |
with the same draws and reports the difference, its interval, and the share of draws in
|
|
|
|
| 35 |
exclude boxes (y0 y1 x0 x1 on the surface grid, the same frame as `crop`), each grown by `exclude_margin`
|
| 36 |
pixels on every side and clipped to the surface, are removed from the supervision mask: a region
|
| 37 |
that was looked at before (a window chosen with labels) is left out of a later score. The pixels and
|
| 38 |
+
the labeled ink removed are reported.
|
| 39 |
offset the labels are moved by (dy, dx) surface pixels after they are mapped onto the map's grid:
|
| 40 |
+
label[y, x] = stretched[y - dy, x - dx] (TAUIL-Abd-Elilah's label-equivalent convention), so (-6, -7) takes each pixel's label from 6 rows down and 7 columns right.
|
|
|
|
| 41 |
Pixels whose source falls outside the surface (the vacated edge) leave the mask. The offset is applied
|
| 42 |
on the whole surface, so a cropped map and the same window cut from a whole map get the same labels.
|
| 43 |
"""
|
|
|
|
| 59 |
return load_map(path)
|
| 60 |
|
| 61 |
|
| 62 |
+
def _same_file(a, b):
|
| 63 |
+
import os
|
| 64 |
+
try:
|
| 65 |
+
return os.path.samefile(a, b)
|
| 66 |
+
except OSError:
|
| 67 |
+
return False
|
| 68 |
+
|
| 69 |
+
|
| 70 |
def _levels(path, level):
|
| 71 |
try:
|
| 72 |
s3retry.refuse_remote(path, "kit auc")
|
|
|
|
| 84 |
return node
|
| 85 |
|
| 86 |
|
| 87 |
+
MIN_FLOAT_LEVELS = 256 # a float map spanning fewer of the 65,536 levels is rescaled min..max
|
| 88 |
+
|
| 89 |
+
|
| 90 |
def _quantize(np, values):
|
| 91 |
+
"""Integer scores for exact histogram AUC: uint8 and uint16 as is, floats to 0..65535.
|
| 92 |
+
|
| 93 |
+
A float map is read as 0..1 (or 0..255, or 0..65535 when its largest value says so), as
|
| 94 |
+
before. A float map that does not fit that reading, with a value below 0 or above 65535
|
| 95 |
+
(logits, signed integers) or a range so narrow it falls on fewer than MIN_FLOAT_LEVELS
|
| 96 |
+
levels, is instead stretched from its own minimum to its maximum, which keeps every pixel's
|
| 97 |
+
rank. NaN and infinite values are refused: they have no rank."""
|
| 98 |
if values.dtype in (np.uint8, np.uint16):
|
| 99 |
return values.astype(np.int64), 65536
|
| 100 |
v = values.astype(np.float64)
|
| 101 |
+
if not np.isfinite(v).all():
|
| 102 |
+
bad = int((~np.isfinite(v)).sum())
|
| 103 |
+
raise VerifyError(f"the map holds {bad} NaN or infinite values; replace them (with 0 for no "
|
| 104 |
+
"prediction) before scoring")
|
| 105 |
+
if not v.size:
|
| 106 |
+
return v.astype(np.int64), 65536
|
| 107 |
+
low, top = float(v.min()), float(v.max())
|
| 108 |
+
if low >= 0 and top <= 65535:
|
| 109 |
+
s = v / (255.0 if top <= 255 else 65535.0) if top > 1.0 else v
|
| 110 |
+
q = np.clip(np.round(s * 65535), 0, 65535).astype(np.int64)
|
| 111 |
+
if top == low or int(q.max()) - int(q.min()) >= MIN_FLOAT_LEVELS:
|
| 112 |
+
return q, 65536
|
| 113 |
+
if top == low: # a constant map outside 0..65535, such as a blank sham written as logits: every pixel ties
|
| 114 |
+
return np.zeros(v.shape, dtype=np.int64), 65536
|
| 115 |
+
return np.round((v - low) / (top - low) * 65535).astype(np.int64), 65536
|
| 116 |
|
| 117 |
|
| 118 |
def auc_scores(ink_scores, background_scores):
|
|
|
|
| 145 |
|
| 146 |
|
| 147 |
def label_index(labels_shape, surface_shape, crop, map_shape, offset=(0, 0)):
|
| 148 |
+
"""Row and column indices into the labels for every map pixel (nearest neighbor), the labels moved by
|
| 149 |
offset (dy, dx) surface pixels, and per row and column whether the label's source is on the surface."""
|
| 150 |
sy = labels_shape[0] / surface_shape[0]
|
| 151 |
sx = labels_shape[1] / surface_shape[1]
|
|
|
|
| 167 |
|
| 168 |
|
| 169 |
def label_grid(labels_shape, surface_shape, crop, map_shape):
|
| 170 |
+
"""Row and column indices into the labels for every map pixel (nearest neighbor)."""
|
| 171 |
rows, cols, _, _ = label_index(labels_shape, surface_shape, crop, map_shape)
|
| 172 |
return rows, cols
|
| 173 |
|
|
|
|
| 282 |
if len(ys) == 0:
|
| 283 |
raise VerifyError("no supervised pixels to resample")
|
| 284 |
keys = (ys // block_px) * (prediction.shape[1] // block_px + 1) + xs // block_px
|
| 285 |
+
# dense relabel of the (small, bounded) block keys: same sorted blocks and inverse as np.unique, without the sort
|
| 286 |
+
present = np.zeros(int(keys.max()) + 1, bool)
|
| 287 |
+
present[keys] = True
|
| 288 |
+
blocks = np.flatnonzero(present)
|
| 289 |
+
inv = (np.cumsum(present) - 1)[keys]
|
| 290 |
lab = ink[ys, xs]
|
| 291 |
if lab.all() or not lab.any():
|
| 292 |
raise VerifyError("the mask holds only one class; no AUC to resample")
|
|
|
|
| 295 |
q, _ = _quantize(np, m)
|
| 296 |
top = 255 if m.dtype == np.uint8 else 65535 # _quantize keeps uint8 as 0..255
|
| 297 |
qb = q[ys, xs] * (BOOT_BINS - 1) // top
|
| 298 |
+
flat = inv * BOOT_BINS + qb # per-(block, bin) counts via one bincount per class, not np.add.at
|
| 299 |
+
hi = np.bincount(flat[lab], minlength=len(blocks) * BOOT_BINS).reshape(len(blocks), BOOT_BINS).astype(np.float64)
|
| 300 |
+
hb = np.bincount(flat[~lab], minlength=len(blocks) * BOOT_BINS).reshape(len(blocks), BOOT_BINS).astype(np.float64)
|
| 301 |
hists.append((hi, hb))
|
| 302 |
rng = np.random.default_rng(seed)
|
| 303 |
w = np.stack([np.bincount(rng.integers(0, len(blocks), len(blocks)), minlength=len(blocks))
|
|
|
|
| 309 |
if other is not None:
|
| 310 |
full = [float(_auc_hist(np, hi.sum(0), hb.sum(0))) for hi, hb in hists]
|
| 311 |
exact = []
|
| 312 |
+
for m in maps: # every gray level, as score_array counts them, on the shared pixels
|
| 313 |
q, _ = _quantize(np, m)
|
| 314 |
v = q[ys, xs]
|
| 315 |
exact.append(auc_scores(v[lab], v[~lab]))
|
|
|
|
| 358 |
ctrl = np.squeeze(_load(control))
|
| 359 |
if ctrl.shape != pred.shape:
|
| 360 |
raise VerifyError(f"control shape {ctrl.shape} differs from the map's {pred.shape}")
|
| 361 |
+
# the same file is refused; an identical copy still scores, and its zero gap fails the control honestly
|
| 362 |
+
# (a constant known-bad map, such as a blank sham, equals its own reverse)
|
| 363 |
+
if _same_file(control, prediction):
|
| 364 |
+
raise VerifyError(f"control {control} is the map itself; give the reverse-depth map as the control")
|
| 365 |
result["control"] = score_array(ctrl, ink, supervised, keep_zero, inner)
|
| 366 |
if bootstrap or compare is not None:
|
| 367 |
other = None
|
|
|
|
| 392 |
"left out of the mask")
|
| 393 |
ex = result.get("excluded")
|
| 394 |
if ex:
|
| 395 |
+
kept = "" if ex["ink_share_kept"] is None else f", {ex['ink_share_kept']:.1%} of the labeled ink kept"
|
| 396 |
rows.append(f"excluded {len(ex['grown'])} box(es) grown by {ex['margin']} px: {ex['grown']}; "
|
| 397 |
f"{ex['supervised_px_removed']} supervised px removed ({ex['ink_px_removed']} ink){kept}")
|
| 398 |
rows.append(line("map ", result["forward"]))
|
|
|
|
| 410 |
verdict = ("ahead beyond sampling noise" if c["ci95"][0] > 0 else
|
| 411 |
"behind beyond sampling noise" if c["ci95"][1] < 0 else "not distinguishable from noise")
|
| 412 |
rows.append(f"map minus compared map: {c['difference']:+.4f} ({c['difference_exact']:+.4f} at every "
|
| 413 |
+
f"gray level), 95 % interval {c['ci95'][0]:+.4f} to {c['ci95'][1]:+.4f} on {c['pixels']} "
|
| 414 |
f"shared px: {verdict}")
|
| 415 |
return "\n".join(rows)
|
kit/fetch.py
CHANGED
|
@@ -4,11 +4,9 @@ The same files ``aws s3 sync --no-sign-request`` would fetch, without the AWS CL
|
|
| 4 |
Existing files of the right size are skipped, so an interrupted fetch resumes.
|
| 5 |
"""
|
| 6 |
|
| 7 |
-
import concurrent.futures
|
| 8 |
import os
|
| 9 |
import re
|
| 10 |
import urllib.parse
|
| 11 |
-
import urllib.request
|
| 12 |
from pathlib import Path
|
| 13 |
|
| 14 |
from . import s3retry
|
|
@@ -39,7 +37,8 @@ def parse_listing(xml):
|
|
| 39 |
return entries, token.group(1) if token else None
|
| 40 |
|
| 41 |
|
| 42 |
-
def list_prefix(prefix, opener=
|
|
|
|
| 43 |
prefix = prefix.strip("/") + "/"
|
| 44 |
entries, token, seen = [], None, set()
|
| 45 |
while True:
|
|
@@ -55,6 +54,31 @@ def list_prefix(prefix, opener=urllib.request.urlopen, base=BUCKET_URL):
|
|
| 55 |
seen.add(token)
|
| 56 |
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
def local_path(dest, prefix, key):
|
| 59 |
relative = key[len(prefix):]
|
| 60 |
if not relative or relative.startswith("/") or ".." in Path(relative).parts:
|
|
@@ -62,7 +86,8 @@ def local_path(dest, prefix, key):
|
|
| 62 |
return Path(dest) / relative
|
| 63 |
|
| 64 |
|
| 65 |
-
def fetch_prefix(prefix, dest, workers=16, opener=
|
|
|
|
| 66 |
prefix, entries = list_prefix(prefix, opener, base)
|
| 67 |
if not entries:
|
| 68 |
raise FetchError(f"nothing under s3://vesuvius-challenge-open-data/{prefix}")
|
|
|
|
| 4 |
Existing files of the right size are skipped, so an interrupted fetch resumes.
|
| 5 |
"""
|
| 6 |
|
|
|
|
| 7 |
import os
|
| 8 |
import re
|
| 9 |
import urllib.parse
|
|
|
|
| 10 |
from pathlib import Path
|
| 11 |
|
| 12 |
from . import s3retry
|
|
|
|
| 37 |
return entries, token.group(1) if token else None
|
| 38 |
|
| 39 |
|
| 40 |
+
def list_prefix(prefix, opener=None, base=BUCKET_URL):
|
| 41 |
+
# opener None: urllib.request.urlopen (s3retry.open_url), imported only when a fetch runs
|
| 42 |
prefix = prefix.strip("/") + "/"
|
| 43 |
entries, token, seen = [], None, set()
|
| 44 |
while True:
|
|
|
|
| 54 |
seen.add(token)
|
| 55 |
|
| 56 |
|
| 57 |
+
def parse_dir_listing(xml):
|
| 58 |
+
"""Return (["dir/", ...], next_token or None) from one ListObjectsV2 delimiter page."""
|
| 59 |
+
dirs = re.findall(r"<Prefix>([^<]+)</Prefix>", xml)
|
| 60 |
+
token = re.search(r"<NextContinuationToken>([^<]+)</NextContinuationToken>", xml)
|
| 61 |
+
return dirs, token.group(1) if token else None
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def list_prefix_dirs(prefix, opener=None, base=BUCKET_URL):
|
| 65 |
+
"""The directories directly under `prefix`, via one delimiter listing: no walk of the keys
|
| 66 |
+
inside them (list_prefix descends into zarr chunk trees and is the wrong tool for pools)."""
|
| 67 |
+
prefix = prefix.strip("/") + "/"
|
| 68 |
+
dirs, token, seen = [], None, set()
|
| 69 |
+
while True:
|
| 70 |
+
url = f"{base}/?list-type=2&max-keys=1000&delimiter=/&prefix={urllib.parse.quote(prefix)}"
|
| 71 |
+
if token:
|
| 72 |
+
url += "&continuation-token=" + urllib.parse.quote(token, safe="")
|
| 73 |
+
page, token = parse_dir_listing(s3retry.open_url(url, opener, 60).read().decode())
|
| 74 |
+
dirs += page
|
| 75 |
+
if not token:
|
| 76 |
+
return prefix, dirs
|
| 77 |
+
if token in seen:
|
| 78 |
+
raise FetchError("bucket listing repeated a continuation token")
|
| 79 |
+
seen.add(token)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
def local_path(dest, prefix, key):
|
| 83 |
relative = key[len(prefix):]
|
| 84 |
if not relative or relative.startswith("/") or ".." in Path(relative).parts:
|
|
|
|
| 86 |
return Path(dest) / relative
|
| 87 |
|
| 88 |
|
| 89 |
+
def fetch_prefix(prefix, dest, workers=16, opener=None, base=BUCKET_URL):
|
| 90 |
+
import concurrent.futures
|
| 91 |
prefix, entries = list_prefix(prefix, opener, base)
|
| 92 |
if not entries:
|
| 93 |
raise FetchError(f"nothing under s3://vesuvius-challenge-open-data/{prefix}")
|
kit/layers.py
CHANGED
|
@@ -12,12 +12,13 @@ than layer by layer), and falls back to one layer at a time otherwise. Depth ord
|
|
| 12 |
stored; reverse it at inference time (v8in `--reverse`), not here, so one export serves both
|
| 13 |
directions. Needs numpy, tifffile and zarr (all in villa's environment).
|
| 14 |
|
| 15 |
-
The depth-shuffle control (after aviad12g's vesuvius-depth-order-control) is the exception:
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
| 21 |
"""
|
| 22 |
|
| 23 |
from pathlib import Path
|
|
@@ -73,7 +74,8 @@ BAND_ROWS = 1024
|
|
| 73 |
|
| 74 |
def export_layers(volume, out_dir, start=0, count=None, compression="zlib", crop=None,
|
| 75 |
max_bytes=DEFAULT_MAX_BYTES, order=None):
|
| 76 |
-
"""Write layers start .. start+count-1 of volume as 00.tif, 01.tif, ... in out_dir
|
|
|
|
| 77 |
|
| 78 |
crop is (y0, y1, x0, x1) in full-resolution pixels, or None for the whole layer. order, a
|
| 79 |
permutation of range(count), writes layer start+order[i] as file i (the shuffle control)."""
|
|
@@ -94,6 +96,10 @@ def export_layers(volume, out_dir, start=0, count=None, compression="zlib", crop
|
|
| 94 |
region = (slice(y0, y1), slice(x0, x1))
|
| 95 |
if volume.dtype != np.uint8:
|
| 96 |
raise VerifyError(f"the volume is {volume.dtype}; v8in expects uint8 layers")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
stack = None
|
| 98 |
if count * (y1 - y0) * (x1 - x0) <= max_bytes:
|
| 99 |
stack = np.empty((count, y1 - y0, x1 - x0), dtype=np.uint8)
|
|
@@ -104,7 +110,6 @@ def export_layers(volume, out_dir, start=0, count=None, compression="zlib", crop
|
|
| 104 |
order = list(range(count))
|
| 105 |
elif sorted(order) != list(range(count)):
|
| 106 |
raise VerifyError(f"order must be a permutation of 0..{count - 1}")
|
| 107 |
-
out = Path(out_dir)
|
| 108 |
out.mkdir(parents=True, exist_ok=True)
|
| 109 |
width = max(2, len(str(count - 1)))
|
| 110 |
written = []
|
|
@@ -130,6 +135,8 @@ def shuffle_file(src, dst, seed, level="0", crop=None):
|
|
| 130 |
"""Write src's layers in a fixed random order to a new zarr (array "0"), for villa's reader."""
|
| 131 |
np = _numpy()
|
| 132 |
zarr = _zarr()
|
|
|
|
|
|
|
| 133 |
volume = open_volume(src, level)
|
| 134 |
n, h, w = volume.shape
|
| 135 |
y0, y1, x0, x1 = crop if crop is not None else (0, h, 0, w)
|
|
@@ -140,7 +147,7 @@ def shuffle_file(src, dst, seed, level="0", crop=None):
|
|
| 140 |
for band in range(y0, y1, BAND_ROWS):
|
| 141 |
end = min(band + BAND_ROWS, y1)
|
| 142 |
data[:, band - y0:end - y0] = volume[:, band:end, x0:x1][order]
|
| 143 |
-
group = zarr.open_group(str(dst), mode="w")
|
| 144 |
group.create_array("0", data=data, chunks=(n, min(128, y1 - y0), min(128, x1 - x0)))
|
| 145 |
group.attrs["depth_shuffle"] = {"source": str(src), "seed": seed, "order": order, "crop": crop}
|
| 146 |
return {"source": str(src), "out": str(dst), "shape": list(data.shape), "seed": seed, "order": order}
|
|
|
|
| 12 |
stored; reverse it at inference time (v8in `--reverse`), not here, so one export serves both
|
| 13 |
directions. Needs numpy, tifffile and zarr (all in villa's environment).
|
| 14 |
|
| 15 |
+
The depth-shuffle control (after aviad12g's vesuvius-depth-order-control) is the exception: `shuffle` writes the
|
| 16 |
+
layers in a fixed random order, never the stored or the reversed one. A model that reads ink loses it there; on
|
| 17 |
+
PHerc0841 the released readers we tried read at or below their reversed AUC on shuffled layers (seed 20261007),
|
| 18 |
+
mostly near 0.5 but up to 0.607 on one segment, often a cleaner null than the reversed volume, which keeps a depth
|
| 19 |
+
structure. Not always: with another shuffle seed a released reader can score higher on shuffled than on reversed
|
| 20 |
+
layers, so report the seed.
|
| 21 |
+
`kit shuffle` writes a zarr (villa's input); `kit layers --shuffle` writes v8in's layer folder in the same order.
|
| 22 |
"""
|
| 23 |
|
| 24 |
from pathlib import Path
|
|
|
|
| 74 |
|
| 75 |
def export_layers(volume, out_dir, start=0, count=None, compression="zlib", crop=None,
|
| 76 |
max_bytes=DEFAULT_MAX_BYTES, order=None):
|
| 77 |
+
"""Write layers start .. start+count-1 of volume as 00.tif, 01.tif, ... in out_dir, which must
|
| 78 |
+
not already hold numbered layer TIFFs.
|
| 79 |
|
| 80 |
crop is (y0, y1, x0, x1) in full-resolution pixels, or None for the whole layer. order, a
|
| 81 |
permutation of range(count), writes layer start+order[i] as file i (the shuffle control)."""
|
|
|
|
| 96 |
region = (slice(y0, y1), slice(x0, x1))
|
| 97 |
if volume.dtype != np.uint8:
|
| 98 |
raise VerifyError(f"the volume is {volume.dtype}; v8in expects uint8 layers")
|
| 99 |
+
out = Path(out_dir)
|
| 100 |
+
if out.is_dir() and any(p.suffix == ".tif" and p.stem.isdigit() for p in out.iterdir()):
|
| 101 |
+
raise VerifyError(f"{out} already holds layer TIFFs from an earlier export, which v8in would read too; "
|
| 102 |
+
"remove them or give an empty folder")
|
| 103 |
stack = None
|
| 104 |
if count * (y1 - y0) * (x1 - x0) <= max_bytes:
|
| 105 |
stack = np.empty((count, y1 - y0, x1 - x0), dtype=np.uint8)
|
|
|
|
| 110 |
order = list(range(count))
|
| 111 |
elif sorted(order) != list(range(count)):
|
| 112 |
raise VerifyError(f"order must be a permutation of 0..{count - 1}")
|
|
|
|
| 113 |
out.mkdir(parents=True, exist_ok=True)
|
| 114 |
width = max(2, len(str(count - 1)))
|
| 115 |
written = []
|
|
|
|
| 135 |
"""Write src's layers in a fixed random order to a new zarr (array "0"), for villa's reader."""
|
| 136 |
np = _numpy()
|
| 137 |
zarr = _zarr()
|
| 138 |
+
if Path(dst).exists():
|
| 139 |
+
raise VerifyError(f"{dst} already exists; remove it or give a new path for the shuffled zarr")
|
| 140 |
volume = open_volume(src, level)
|
| 141 |
n, h, w = volume.shape
|
| 142 |
y0, y1, x0, x1 = crop if crop is not None else (0, h, 0, w)
|
|
|
|
| 147 |
for band in range(y0, y1, BAND_ROWS):
|
| 148 |
end = min(band + BAND_ROWS, y1)
|
| 149 |
data[:, band - y0:end - y0] = volume[:, band:end, x0:x1][order]
|
| 150 |
+
group = zarr.open_group(str(dst), mode="w-")
|
| 151 |
group.create_array("0", data=data, chunks=(n, min(128, y1 - y0), min(128, x1 - x0)))
|
| 152 |
group.attrs["depth_shuffle"] = {"source": str(src), "seed": seed, "order": order, "crop": crop}
|
| 153 |
return {"source": str(src), "out": str(dst), "shape": list(data.shape), "seed": seed, "order": order}
|
kit/s3retry.py
CHANGED
|
@@ -13,12 +13,10 @@ NoSuchKey, or when it carries no S3 error code at all (a server that is not S3).
|
|
| 13 |
new connection, and a key that keeps getting it is reported as unknown, never as missing.
|
| 14 |
"""
|
| 15 |
|
| 16 |
-
import http.client
|
| 17 |
import io
|
| 18 |
import re
|
| 19 |
import time
|
| 20 |
-
import urllib.error
|
| 21 |
-
import urllib.request
|
| 22 |
|
| 23 |
MISSING_CODE = "NoSuchKey"
|
| 24 |
TRIES = 10 # attempts in all: 0.32 ** 10 is about 1e-5 at the worst rate measured
|
|
@@ -48,8 +46,11 @@ def _backoff(attempt):
|
|
| 48 |
def open_url(req, opener=None, timeout=60, tries=TRIES, sleep=time.sleep, counter=None):
|
| 49 |
"""opener(req, timeout=timeout) with a false 404 retried, up to `tries` attempts in all. Any other answer is
|
| 50 |
returned or raised as the opener gives it; a key that answers a false 404 every time raises that HTTPError
|
| 51 |
-
with a reason that says so. counter: a dict whose "false_404" entry counts the false answers.
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
| 53 |
for attempt in range(tries):
|
| 54 |
try:
|
| 55 |
return opener(req, timeout=timeout)
|
|
@@ -73,7 +74,9 @@ def key_state(url, opener=None, timeout=30, tries=TRIES, sleep=time.sleep, count
|
|
| 73 |
"""(present | missing | unknown, detail) for one object, from a one-byte ranged GET with false 404s retried:
|
| 74 |
present on 200 or 206; missing on a 404 that names NoSuchKey or names no code; unknown otherwise (403,
|
| 75 |
which S3 also gives for missing keys in buckets it will not list, failures, a false 404 every time)."""
|
| 76 |
-
|
|
|
|
|
|
|
| 77 |
try:
|
| 78 |
with open_url(req, opener, timeout, tries, sleep, counter) as resp:
|
| 79 |
resp.read()
|
|
@@ -84,7 +87,7 @@ def key_state(url, opener=None, timeout=30, tries=TRIES, sleep=time.sleep, count
|
|
| 84 |
if not false_404(404, body):
|
| 85 |
return MISSING, f"HTTP 404 {error_code(body) or '(no S3 code)'}"
|
| 86 |
return UNKNOWN, f"HTTP {exc.code} {exc.reason}"
|
| 87 |
-
except (urllib.error.URLError, OSError,
|
| 88 |
return UNKNOWN, str(getattr(exc, "reason", exc))
|
| 89 |
|
| 90 |
|
|
|
|
| 13 |
new connection, and a key that keeps getting it is reported as unknown, never as missing.
|
| 14 |
"""
|
| 15 |
|
|
|
|
| 16 |
import io
|
| 17 |
import re
|
| 18 |
import time
|
| 19 |
+
import urllib.error # urllib.request and http.client are imported where used: `python -m kit` imports this module
|
|
|
|
| 20 |
|
| 21 |
MISSING_CODE = "NoSuchKey"
|
| 22 |
TRIES = 10 # attempts in all: 0.32 ** 10 is about 1e-5 at the worst rate measured
|
|
|
|
| 46 |
def open_url(req, opener=None, timeout=60, tries=TRIES, sleep=time.sleep, counter=None):
|
| 47 |
"""opener(req, timeout=timeout) with a false 404 retried, up to `tries` attempts in all. Any other answer is
|
| 48 |
returned or raised as the opener gives it; a key that answers a false 404 every time raises that HTTPError
|
| 49 |
+
with a reason that says so. counter: a dict whose "false_404" entry counts the false answers. Fewer than one
|
| 50 |
+
try is taken as one."""
|
| 51 |
+
if opener is None:
|
| 52 |
+
from urllib.request import urlopen as opener
|
| 53 |
+
tries = max(1, tries)
|
| 54 |
for attempt in range(tries):
|
| 55 |
try:
|
| 56 |
return opener(req, timeout=timeout)
|
|
|
|
| 74 |
"""(present | missing | unknown, detail) for one object, from a one-byte ranged GET with false 404s retried:
|
| 75 |
present on 200 or 206; missing on a 404 that names NoSuchKey or names no code; unknown otherwise (403,
|
| 76 |
which S3 also gives for missing keys in buckets it will not list, failures, a false 404 every time)."""
|
| 77 |
+
from http.client import HTTPException
|
| 78 |
+
from urllib.request import Request
|
| 79 |
+
req = Request(url, headers={"Range": "bytes=0-0", "User-Agent": "kit-s3retry"})
|
| 80 |
try:
|
| 81 |
with open_url(req, opener, timeout, tries, sleep, counter) as resp:
|
| 82 |
resp.read()
|
|
|
|
| 87 |
if not false_404(404, body):
|
| 88 |
return MISSING, f"HTTP 404 {error_code(body) or '(no S3 code)'}"
|
| 89 |
return UNKNOWN, f"HTTP {exc.code} {exc.reason}"
|
| 90 |
+
except (urllib.error.URLError, OSError, HTTPException) as exc:
|
| 91 |
return UNKNOWN, str(getattr(exc, "reason", exc))
|
| 92 |
|
| 93 |
|
kit/vc3d_audit.py
CHANGED
|
@@ -478,6 +478,8 @@ def _v3_bytes_codecs(codecs, raw):
|
|
| 478 |
spec["shuffle"] = {"noshuffle": 0, "shuffle": 1, "bitshuffle": 2}.get(conf.get("shuffle"), 1)
|
| 479 |
spec.pop("typesize", None)
|
| 480 |
raw = bytes(vc3d_io._numcodecs(spec).decode(raw))
|
|
|
|
|
|
|
| 481 |
else:
|
| 482 |
raise vc3d_io.IOFormatError(f"codec {name} not decoded here")
|
| 483 |
return raw
|
|
@@ -528,7 +530,7 @@ def surface_samples(surface, scale_segmentation=1.0, max_points=DEFAULT_MAX_POIN
|
|
| 528 |
about max_points, in the volume's level-0 voxels.
|
| 529 |
|
| 530 |
Returns (samples [(x, y, z, row, col)], spacing, info): spacing is the 95th percentile distance between
|
| 531 |
-
|
| 532 |
p = Path(surface)
|
| 533 |
gx, gy, gz = (vc3d_io.read_tiff(p / f"{a}.tif") for a in "xyz")
|
| 534 |
if not (gx.h == gy.h == gz.h and gx.w == gy.w == gz.w):
|
|
@@ -572,7 +574,7 @@ def footprint(samples, spacing, shape, chunks, factor, margin=DEFAULT_MARGIN):
|
|
| 572 |
"""Chunk indices a render along the surface reads in one array.
|
| 573 |
|
| 574 |
factor: voxels of this array per level-0 voxel along (z, y, x). core: chunks within half the sample
|
| 575 |
-
spacing plus one voxel (the trilinear
|
| 576 |
each; halo: chunks only within `margin` voxels further (the layers either side of the surface).
|
| 577 |
Returns (core {idx: [r0, r1, c0, c1]}, halo set, samples outside the array)."""
|
| 578 |
counts = [-(-s // c) for s, c in zip(shape, chunks)]
|
|
@@ -687,7 +689,7 @@ def populated(store, meta, limit=3):
|
|
| 687 |
|
| 688 |
|
| 689 |
def probe(store, meta, budget):
|
| 690 |
-
"""Presence of the chunks at the
|
| 691 |
scroll's papyrus is), for stores that cannot list. Returns ({key: state}, requests)."""
|
| 692 |
counts = grid_counts(meta)
|
| 693 |
picks = []
|
|
@@ -708,7 +710,7 @@ def render_zeros(path):
|
|
| 708 |
|
| 709 |
VC3D writes 0 where the surface is invalid, so a pixel 0 in every layer is off the surface; inside the
|
| 710 |
footprint (nonzero in some layer) a 0 is a sample of fill_value: a missing chunk, the mask of a masked
|
| 711 |
-
volume, or the volume's edge. Zeros on the
|
| 712 |
explain. A hole as deep as the whole stack looks like off-surface here; the footprint check covers it."""
|
| 713 |
p = Path(path)
|
| 714 |
if vc3d_io.is_zarr(p):
|
|
@@ -838,7 +840,7 @@ def audit(location, surface=None, check_levels=None, scale_segmentation=1.0, mar
|
|
| 838 |
report["render"] = rz
|
| 839 |
if rz.get("centre_zero_fraction"):
|
| 840 |
report["warnings"].append(
|
| 841 |
-
f"render: {rz['centre_zero_fraction']:.2%} of the footprint is 0 on the
|
| 842 |
f"columns {rz['centre_zero_box_rows_cols']}): missing chunks, the mask or the volume's edge")
|
| 843 |
unknown = any(r.get("unknown") for r in (report.get("footprint") or {}).get("levels", []))
|
| 844 |
report["verdict"] = "defects" if report["defects"] else "incomplete" if unknown else "clean"
|
|
|
|
| 478 |
spec["shuffle"] = {"noshuffle": 0, "shuffle": 1, "bitshuffle": 2}.get(conf.get("shuffle"), 1)
|
| 479 |
spec.pop("typesize", None)
|
| 480 |
raw = bytes(vc3d_io._numcodecs(spec).decode(raw))
|
| 481 |
+
elif name == "volcomp":
|
| 482 |
+
raw = vc3d_io.volcomp_decode(raw) # opt in: needs KIT_VOLCOMP_LIB (kit/vc3d_io.py)
|
| 483 |
else:
|
| 484 |
raise vc3d_io.IOFormatError(f"codec {name} not decoded here")
|
| 485 |
return raw
|
|
|
|
| 530 |
about max_points, in the volume's level-0 voxels.
|
| 531 |
|
| 532 |
Returns (samples [(x, y, z, row, col)], spacing, info): spacing is the 95th percentile distance between
|
| 533 |
+
neighboring samples in a row, so a box of that size around each sample covers the surface between them."""
|
| 534 |
p = Path(surface)
|
| 535 |
gx, gy, gz = (vc3d_io.read_tiff(p / f"{a}.tif") for a in "xyz")
|
| 536 |
if not (gx.h == gy.h == gz.h and gx.w == gy.w == gz.w):
|
|
|
|
| 574 |
"""Chunk indices a render along the surface reads in one array.
|
| 575 |
|
| 576 |
factor: voxels of this array per level-0 voxel along (z, y, x). core: chunks within half the sample
|
| 577 |
+
spacing plus one voxel (the trilinear neighbor) of a sample, with the grid rows and columns that reach
|
| 578 |
each; halo: chunks only within `margin` voxels further (the layers either side of the surface).
|
| 579 |
Returns (core {idx: [r0, r1, c0, c1]}, halo set, samples outside the array)."""
|
| 580 |
counts = [-(-s // c) for s, c in zip(shape, chunks)]
|
|
|
|
| 689 |
|
| 690 |
|
| 691 |
def probe(store, meta, budget):
|
| 692 |
+
"""Presence of the chunks at the centers of a 3 x 3 x 3 lattice over the middle of the grid (where a
|
| 693 |
scroll's papyrus is), for stores that cannot list. Returns ({key: state}, requests)."""
|
| 694 |
counts = grid_counts(meta)
|
| 695 |
picks = []
|
|
|
|
| 710 |
|
| 711 |
VC3D writes 0 where the surface is invalid, so a pixel 0 in every layer is off the surface; inside the
|
| 712 |
footprint (nonzero in some layer) a 0 is a sample of fill_value: a missing chunk, the mask of a masked
|
| 713 |
+
volume, or the volume's edge. Zeros on the center layer, which lies on the papyrus, are the ones to
|
| 714 |
explain. A hole as deep as the whole stack looks like off-surface here; the footprint check covers it."""
|
| 715 |
p = Path(path)
|
| 716 |
if vc3d_io.is_zarr(p):
|
|
|
|
| 840 |
report["render"] = rz
|
| 841 |
if rz.get("centre_zero_fraction"):
|
| 842 |
report["warnings"].append(
|
| 843 |
+
f"render: {rz['centre_zero_fraction']:.2%} of the footprint is 0 on the center layer (rows and "
|
| 844 |
f"columns {rz['centre_zero_box_rows_cols']}): missing chunks, the mask or the volume's edge")
|
| 845 |
unknown = any(r.get("unknown") for r in (report.get("footprint") or {}).get("levels", []))
|
| 846 |
report["verdict"] = "defects" if report["defects"] else "incomplete" if unknown else "clean"
|
kit/vc3d_io.py
CHANGED
|
@@ -8,7 +8,8 @@ The agent tools (`kit/vc3d_agent.py`) have to run in any Python, so nothing here
|
|
| 8 |
vc_render_tifxyz layers, tifxyz x/y/z grids (the catalog's BigTIFF ones too) and villa's ink maps.
|
| 9 |
read_npy 2-D or 3-D .npy (torchscript_infer.py and v8in write their maps this way)
|
| 10 |
open_zarr v2 and unsharded v3 arrays and OME-Zarr groups, uncompressed, zlib or gzip; blosc,
|
| 11 |
-
zstd and lz4 through numcodecs when it is installed
|
|
|
|
| 12 |
png_bytes 8-bit grey or RGB PNG, for previews
|
| 13 |
|
| 14 |
Pure-Python decoding is slow (LZW runs at a few MB/s), so the agent's `preview` reads the least it
|
|
@@ -337,6 +338,14 @@ def read_npy(path, index=None):
|
|
| 337 |
|
| 338 |
# ---------------------------------------------------------------- zarr
|
| 339 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
class ZArray:
|
| 341 |
"""A local zarr v2 or (unsharded) v3 array; `read` returns the samples of a box."""
|
| 342 |
|
|
@@ -356,7 +365,7 @@ class ZArray:
|
|
| 356 |
self.sep = meta.get("dimension_separator", ".")
|
| 357 |
self.prefix = ""
|
| 358 |
self.compressor = meta.get("compressor")
|
| 359 |
-
self.fill = meta.get("fill_value")
|
| 360 |
elif (self.path / "zarr.json").is_file():
|
| 361 |
meta = json.loads((self.path / "zarr.json").read_text())
|
| 362 |
if meta.get("node_type") != "array":
|
|
@@ -386,9 +395,14 @@ class ZArray:
|
|
| 386 |
spec["shuffle"] = {"noshuffle": 0, "shuffle": 1, "bitshuffle": 2}.get(conf.get("shuffle"), 1)
|
| 387 |
spec.pop("typesize", None)
|
| 388 |
self.compressor = spec
|
| 389 |
-
elif name
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 390 |
raise IOFormatError(f"{path}: codec {name} not supported")
|
| 391 |
-
self.fill = meta.get("fill_value")
|
| 392 |
else:
|
| 393 |
raise IOFormatError(f"{path}: no .zarray or zarr.json")
|
| 394 |
self.size = KINDS[self.kind][1]
|
|
@@ -557,6 +571,49 @@ def volcomp_source(path):
|
|
| 557 |
return None
|
| 558 |
|
| 559 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 560 |
def layer_files(path):
|
| 561 |
"""Numbered layer images of a directory (00.tif, 01.tif, ...), in numeric order."""
|
| 562 |
files = [f for f in Path(path).iterdir() if f.suffix.lower() in (".tif", ".tiff") and f.stem.isdigit()]
|
|
@@ -585,9 +642,15 @@ def png_bytes(h, w, data, channels=1):
|
|
| 585 |
|
| 586 |
|
| 587 |
def read_png_gray(blob):
|
| 588 |
-
"""Decode an 8-bit grey or RGB, non-interlaced PNG (enough to test png_bytes and read previews).
|
|
|
|
| 589 |
if blob[:8] != b"\x89PNG\r\n\x1a\n":
|
| 590 |
raise IOFormatError("not a PNG")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 591 |
pos, idat, w, h, channels = 8, b"", 0, 0, 1
|
| 592 |
while pos < len(blob):
|
| 593 |
n = struct.unpack(">I", blob[pos:pos + 4])[0]
|
|
@@ -664,24 +727,26 @@ def prob_threshold(kind):
|
|
| 664 |
|
| 665 |
|
| 666 |
def downsample(raster, factor, how="mean"):
|
| 667 |
-
"""Block reduce by an integer factor (mean, max or nearest), returning float32 samples.
|
|
|
|
| 668 |
if factor <= 1:
|
| 669 |
return Raster(raster.h, raster.w, "f32", as_floats(raster.data))
|
| 670 |
h, w = raster.h // factor, raster.w // factor
|
| 671 |
h, w = max(1, h), max(1, w)
|
| 672 |
data, W = raster.data, raster.w
|
|
|
|
| 673 |
out = array.array("f", bytes(4 * h * w))
|
| 674 |
if how == "nearest":
|
| 675 |
-
c0 =
|
| 676 |
for r in range(h):
|
| 677 |
-
base = (r * factor + factor // 2) * W
|
| 678 |
out[r * w:(r + 1) * w] = as_floats(data[base + c0:base + c0 + w * factor:factor][:w])
|
| 679 |
return Raster(h, w, "f32", out)
|
| 680 |
reduce_max = how == "max"
|
| 681 |
for r in range(h):
|
| 682 |
acc = [0.0] * w if not reduce_max else [-math.inf] * w
|
| 683 |
for rr in range(r * factor, min(raster.h, (r + 1) * factor)):
|
| 684 |
-
row = data[rr * W:rr * W + w * factor]
|
| 685 |
for c in range(w):
|
| 686 |
block = row[c * factor:(c + 1) * factor]
|
| 687 |
if reduce_max:
|
|
@@ -691,7 +756,7 @@ def downsample(raster, factor, how="mean"):
|
|
| 691 |
else:
|
| 692 |
acc[c] += sum(block)
|
| 693 |
if not reduce_max:
|
| 694 |
-
area =
|
| 695 |
acc = [a / area for a in acc]
|
| 696 |
out[r * w:(r + 1) * w] = array.array("f", acc)
|
| 697 |
return Raster(h, w, "f32", out)
|
|
|
|
| 8 |
vc_render_tifxyz layers, tifxyz x/y/z grids (the catalog's BigTIFF ones too) and villa's ink maps.
|
| 9 |
read_npy 2-D or 3-D .npy (torchscript_infer.py and v8in write their maps this way)
|
| 10 |
open_zarr v2 and unsharded v3 arrays and OME-Zarr groups, uncompressed, zlib or gzip; blosc,
|
| 11 |
+
zstd and lz4 through numcodecs when it is installed; a v3 transpose codec only when it
|
| 12 |
+
keeps the axis order
|
| 13 |
png_bytes 8-bit grey or RGB PNG, for previews
|
| 14 |
|
| 15 |
Pure-Python decoding is slow (LZW runs at a few MB/s), so the agent's `preview` reads the least it
|
|
|
|
| 338 |
|
| 339 |
# ---------------------------------------------------------------- zarr
|
| 340 |
|
| 341 |
+
FILL_NAMES = {"NaN": math.nan, "Infinity": math.inf, "-Infinity": -math.inf}
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def _fill_value(value):
|
| 345 |
+
"""A zarr fill value as a number: both formats write NaN and the infinities as strings, and None means 0."""
|
| 346 |
+
return FILL_NAMES.get(value, value) if isinstance(value, str) else value or 0
|
| 347 |
+
|
| 348 |
+
|
| 349 |
class ZArray:
|
| 350 |
"""A local zarr v2 or (unsharded) v3 array; `read` returns the samples of a box."""
|
| 351 |
|
|
|
|
| 365 |
self.sep = meta.get("dimension_separator", ".")
|
| 366 |
self.prefix = ""
|
| 367 |
self.compressor = meta.get("compressor")
|
| 368 |
+
self.fill = _fill_value(meta.get("fill_value"))
|
| 369 |
elif (self.path / "zarr.json").is_file():
|
| 370 |
meta = json.loads((self.path / "zarr.json").read_text())
|
| 371 |
if meta.get("node_type") != "array":
|
|
|
|
| 395 |
spec["shuffle"] = {"noshuffle": 0, "shuffle": 1, "bitshuffle": 2}.get(conf.get("shuffle"), 1)
|
| 396 |
spec.pop("typesize", None)
|
| 397 |
self.compressor = spec
|
| 398 |
+
elif name == "transpose":
|
| 399 |
+
order = conf.get("order")
|
| 400 |
+
if order != "C" and order != list(range(len(self.shape))):
|
| 401 |
+
raise IOFormatError(f"{path}: the transpose codec (order {order}) is not supported; "
|
| 402 |
+
"rewrite the array without it, in C order")
|
| 403 |
+
else:
|
| 404 |
raise IOFormatError(f"{path}: codec {name} not supported")
|
| 405 |
+
self.fill = _fill_value(meta.get("fill_value"))
|
| 406 |
else:
|
| 407 |
raise IOFormatError(f"{path}: no .zarray or zarr.json")
|
| 408 |
self.size = KINDS[self.kind][1]
|
|
|
|
| 571 |
return None
|
| 572 |
|
| 573 |
|
| 574 |
+
# Decoding volcomp chunks, opt in. kit has no decoder of its own: KIT_VOLCOMP_LIB names a shared library built from
|
| 575 |
+
# villa's vendored copy (volume-cartographer/libs/volcomp: volcomp.h is MIT licensed, volcomp_lib.c exports
|
| 576 |
+
# volcomp_lib_decode), for example `cc -O2 -std=c11 -fPIC -shared -o libvolcomp.so volcomp_lib.c -lm`. Every chunk
|
| 577 |
+
# is 128^3 uint8 in z-major order (volcomp_lib.h). What comes back is the lossy copy, never the scan: the render
|
| 578 |
+
# guard above still applies to anything that renders ink from it.
|
| 579 |
+
VOLCOMP_LIB_ENV = "KIT_VOLCOMP_LIB"
|
| 580 |
+
VOLCOMP_CHUNK_BYTES = 128 ** 3
|
| 581 |
+
_VOLCOMP_LIBS = {}
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
def volcomp_lib():
|
| 585 |
+
"""The ctypes handle of the library KIT_VOLCOMP_LIB names, loaded once; IOFormatError when it is unset."""
|
| 586 |
+
import os
|
| 587 |
+
path = os.environ.get(VOLCOMP_LIB_ENV)
|
| 588 |
+
if not path:
|
| 589 |
+
raise IOFormatError(f"codec volcomp not decoded here: set {VOLCOMP_LIB_ENV} to a libvolcomp.so built from "
|
| 590 |
+
"villa's volume-cartographer/libs/volcomp (cc -O2 -std=c11 -fPIC -shared -o libvolcomp.so "
|
| 591 |
+
"volcomp_lib.c -lm)")
|
| 592 |
+
lib = _VOLCOMP_LIBS.get(path)
|
| 593 |
+
if lib is None:
|
| 594 |
+
import ctypes
|
| 595 |
+
try:
|
| 596 |
+
lib = ctypes.CDLL(path)
|
| 597 |
+
except OSError as exc:
|
| 598 |
+
raise IOFormatError(f"{VOLCOMP_LIB_ENV}={path} does not load: {exc}") from exc
|
| 599 |
+
lib.volcomp_lib_decode.argtypes = [ctypes.c_char_p, ctypes.c_size_t, ctypes.c_void_p, ctypes.c_size_t]
|
| 600 |
+
lib.volcomp_lib_decode.restype = ctypes.c_int
|
| 601 |
+
_VOLCOMP_LIBS[path] = lib
|
| 602 |
+
return lib
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
def volcomp_decode(raw, lib=None):
|
| 606 |
+
"""One volcomp chunk decoded to its 128^3 uint8 voxels (bytes, z-major), by villa's codec (volcomp_lib)."""
|
| 607 |
+
import ctypes
|
| 608 |
+
lib = lib if lib is not None else volcomp_lib()
|
| 609 |
+
raw = bytes(raw)
|
| 610 |
+
dst = ctypes.create_string_buffer(VOLCOMP_CHUNK_BYTES)
|
| 611 |
+
status = lib.volcomp_lib_decode(raw, len(raw), dst, VOLCOMP_CHUNK_BYTES)
|
| 612 |
+
if status != 0:
|
| 613 |
+
raise IOFormatError(f"volcomp chunk of {len(raw)} bytes does not decode (status {status})")
|
| 614 |
+
return dst.raw
|
| 615 |
+
|
| 616 |
+
|
| 617 |
def layer_files(path):
|
| 618 |
"""Numbered layer images of a directory (00.tif, 01.tif, ...), in numeric order."""
|
| 619 |
files = [f for f in Path(path).iterdir() if f.suffix.lower() in (".tif", ".tiff") and f.stem.isdigit()]
|
|
|
|
| 642 |
|
| 643 |
|
| 644 |
def read_png_gray(blob):
|
| 645 |
+
"""Decode an 8-bit grey or RGB, non-interlaced PNG (enough to test png_bytes and read previews). A file sealed
|
| 646 |
+
until a recorded opening (kit.verify, "sealed files") is refused."""
|
| 647 |
if blob[:8] != b"\x89PNG\r\n\x1a\n":
|
| 648 |
raise IOFormatError("not a PNG")
|
| 649 |
+
from .verify import SealedError, sealed_refuse
|
| 650 |
+
try:
|
| 651 |
+
sealed_refuse(blob, "PNG")
|
| 652 |
+
except SealedError as exc:
|
| 653 |
+
raise IOFormatError(str(exc)) from None
|
| 654 |
pos, idat, w, h, channels = 8, b"", 0, 0, 1
|
| 655 |
while pos < len(blob):
|
| 656 |
n = struct.unpack(">I", blob[pos:pos + 4])[0]
|
|
|
|
| 727 |
|
| 728 |
|
| 729 |
def downsample(raster, factor, how="mean"):
|
| 730 |
+
"""Block reduce by an integer factor (mean, max or nearest), returning float32 samples. A factor wider (or
|
| 731 |
+
taller) than the image makes one block across it, of the pixels there are."""
|
| 732 |
if factor <= 1:
|
| 733 |
return Raster(raster.h, raster.w, "f32", as_floats(raster.data))
|
| 734 |
h, w = raster.h // factor, raster.w // factor
|
| 735 |
h, w = max(1, h), max(1, w)
|
| 736 |
data, W = raster.data, raster.w
|
| 737 |
+
bw = min(factor, W) # block width: never past the end of a row into the next one
|
| 738 |
out = array.array("f", bytes(4 * h * w))
|
| 739 |
if how == "nearest":
|
| 740 |
+
c0 = bw // 2
|
| 741 |
for r in range(h):
|
| 742 |
+
base = (r * factor + min(factor, raster.h) // 2) * W
|
| 743 |
out[r * w:(r + 1) * w] = as_floats(data[base + c0:base + c0 + w * factor:factor][:w])
|
| 744 |
return Raster(h, w, "f32", out)
|
| 745 |
reduce_max = how == "max"
|
| 746 |
for r in range(h):
|
| 747 |
acc = [0.0] * w if not reduce_max else [-math.inf] * w
|
| 748 |
for rr in range(r * factor, min(raster.h, (r + 1) * factor)):
|
| 749 |
+
row = data[rr * W:rr * W + min(W, w * factor)]
|
| 750 |
for c in range(w):
|
| 751 |
block = row[c * factor:(c + 1) * factor]
|
| 752 |
if reduce_max:
|
|
|
|
| 756 |
else:
|
| 757 |
acc[c] += sum(block)
|
| 758 |
if not reduce_max:
|
| 759 |
+
area = bw * min(factor, raster.h - r * factor)
|
| 760 |
acc = [a / area for a in acc]
|
| 761 |
out[r * w:(r + 1) * w] = array.array("f", acc)
|
| 762 |
return Raster(h, w, "f32", out)
|
kit/vc3d_region.py
CHANGED
|
@@ -6,14 +6,14 @@ For checks that need voxels rather than chunk presence, such as the image check
|
|
| 6 |
prediction 1.76 times slower on a direct connection), and a 404 counts as a missing chunk only when S3 says
|
| 7 |
NoSuchKey. A missing chunk reads as the array's fill value and is counted; a chunk that could not be fetched raises,
|
| 8 |
so a failed request never passes as blank data. Pyramid levels are related by their scale transforms with voxel
|
| 9 |
-
|
| 10 |
2x). Arrays are (z, y, x); points are given as (x, y, z) where the docstring says so. Needs numpy.
|
| 11 |
|
| 12 |
Sharded zarr v3 arrays are read inner chunk by inner chunk through each shard's index (its CRC32C checked when the
|
| 13 |
-
index has one). Over HTTP the inner chunks a box needs from one shard are fetched in merged range reads:
|
| 14 |
in the shard's bytes are joined while the gap between them is at most MERGE_GAP and the whole read at most
|
| 15 |
MERGE_SPAN, so a box costs far fewer requests than chunks. The bounds are those SuperOptimizer/ufsm reports for its
|
| 16 |
-
grouped reads (64 KiB gaps, 2 MiB spans; DESIGN.md at commit 75e063b, 14 October 2026); ufsm has no
|
| 17 |
own code, so this is our own implementation and nothing is copied. `coalesce=False` reads one range per inner chunk,
|
| 18 |
the control. A short or failed range read raises; an absent inner chunk reads as fill.
|
| 19 |
"""
|
|
@@ -62,7 +62,7 @@ def crc32c(data):
|
|
| 62 |
|
| 63 |
def merge_ranges(items, gap=MERGE_GAP, span=MERGE_SPAN):
|
| 64 |
"""Group (offset, nbytes, tag) items of one shard into range reads: [(start, nbytes, [(offset, nbytes, tag)])],
|
| 65 |
-
joining
|
| 66 |
than `span` is read alone; gap < 0 joins nothing."""
|
| 67 |
groups = []
|
| 68 |
for off, n, tag in sorted(items, key=lambda it: it[0]):
|
|
@@ -84,6 +84,17 @@ def _dtype(meta):
|
|
| 84 |
return np.dtype(meta["dtype"]).newbyteorder(">" if big else "<")
|
| 85 |
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
def _inner_dtype(meta):
|
| 88 |
"""The data type of a sharded array's inner chunks (their own bytes codec gives the byte order)."""
|
| 89 |
big = any(c.get("name") == "bytes" and (c.get("configuration") or {}).get("endian") == "big"
|
|
@@ -91,6 +102,40 @@ def _inner_dtype(meta):
|
|
| 91 |
return np.dtype(meta["dtype"]).newbyteorder(">" if big else "<")
|
| 92 |
|
| 93 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
class Volume:
|
| 95 |
"""One OME-Zarr volume (or bare array) for reading boxes and sampling points; decoded chunks are kept in a
|
| 96 |
small cache. `voxel_um` is level 0's voxel size, when known."""
|
|
@@ -305,6 +350,9 @@ class Volume:
|
|
| 305 |
def read(self, level, box):
|
| 306 |
"""The box [[z0, z1], [y0, y1], [x0, x1]] of a level (integers; parts outside the array read as fill)."""
|
| 307 |
meta = self.levels[level]["meta"]
|
|
|
|
|
|
|
|
|
|
| 308 |
box = [[int(a), int(b)] for a, b in box]
|
| 309 |
size = [max(0, b - a) for a, b in box]
|
| 310 |
fill = meta.get("fill_value")
|
|
@@ -335,7 +383,7 @@ class Volume:
|
|
| 335 |
|
| 336 |
def sample(self, level, xyz, pad=1):
|
| 337 |
"""Trilinear values at points (N, 3) given as (x, y, z) in a level's voxels; points outside the array
|
| 338 |
-
read the fill value at their
|
| 339 |
pts = np.asarray(xyz, dtype=float).reshape(-1, 3)
|
| 340 |
zyx = pts[:, ::-1]
|
| 341 |
lo = np.floor(zyx.min(axis=0)).astype(int) - pad
|
|
@@ -394,7 +442,7 @@ def ncc_map(template, image):
|
|
| 394 |
|
| 395 |
def peak(ncc, exclude=4.0):
|
| 396 |
"""(peak value, peak position, best value farther than `exclude` voxels from the peak) of an NCC map. The
|
| 397 |
-
position is refined below a voxel by a parabola through the peak and its
|
| 398 |
k = np.unravel_index(int(np.argmax(ncc)), ncc.shape)
|
| 399 |
grid = np.indices(ncc.shape).reshape(3, -1).T
|
| 400 |
far = np.sqrt(((grid - np.array(k)) ** 2).sum(axis=1)) > exclude
|
|
|
|
| 6 |
prediction 1.76 times slower on a direct connection), and a 404 counts as a missing chunk only when S3 says
|
| 7 |
NoSuchKey. A missing chunk reads as the array's fill value and is counted; a chunk that could not be fetched raises,
|
| 8 |
so a failed request never passes as blank data. Pyramid levels are related by their scale transforms with voxel
|
| 9 |
+
centers aligned: level-0 coordinate p is (p + 0.5) * f - 0.5 at a level f times as fine (f = 0.5 for a level binned
|
| 10 |
2x). Arrays are (z, y, x); points are given as (x, y, z) where the docstring says so. Needs numpy.
|
| 11 |
|
| 12 |
Sharded zarr v3 arrays are read inner chunk by inner chunk through each shard's index (its CRC32C checked when the
|
| 13 |
+
index has one). Over HTTP the inner chunks a box needs from one shard are fetched in merged range reads: neighbors
|
| 14 |
in the shard's bytes are joined while the gap between them is at most MERGE_GAP and the whole read at most
|
| 15 |
MERGE_SPAN, so a box costs far fewer requests than chunks. The bounds are those SuperOptimizer/ufsm reports for its
|
| 16 |
+
grouped reads (64 KiB gaps, 2 MiB spans; DESIGN.md at commit 75e063b, 14 October 2026); ufsm has no license for its
|
| 17 |
own code, so this is our own implementation and nothing is copied. `coalesce=False` reads one range per inner chunk,
|
| 18 |
the control. A short or failed range read raises; an absent inner chunk reads as fill.
|
| 19 |
"""
|
|
|
|
| 62 |
|
| 63 |
def merge_ranges(items, gap=MERGE_GAP, span=MERGE_SPAN):
|
| 64 |
"""Group (offset, nbytes, tag) items of one shard into range reads: [(start, nbytes, [(offset, nbytes, tag)])],
|
| 65 |
+
joining neighbors in offset order while the gap is at most `gap` and the read at most `span`. An item longer
|
| 66 |
than `span` is read alone; gap < 0 joins nothing."""
|
| 67 |
groups = []
|
| 68 |
for off, n, tag in sorted(items, key=lambda it: it[0]):
|
|
|
|
| 84 |
return np.dtype(meta["dtype"]).newbyteorder(">" if big else "<")
|
| 85 |
|
| 86 |
|
| 87 |
+
def _permutes(codecs):
|
| 88 |
+
"""Whether a zarr v3 codec list holds a transpose codec that changes the axis order (read in C order, its chunks
|
| 89 |
+
would come back with their axes swapped)."""
|
| 90 |
+
for c in codecs or []:
|
| 91 |
+
if c.get("name") == "transpose":
|
| 92 |
+
order = (c.get("configuration") or {}).get("order")
|
| 93 |
+
if order != "C" and not (isinstance(order, list) and order == list(range(len(order)))):
|
| 94 |
+
return True
|
| 95 |
+
return False
|
| 96 |
+
|
| 97 |
+
|
| 98 |
def _inner_dtype(meta):
|
| 99 |
"""The data type of a sharded array's inner chunks (their own bytes codec gives the byte order)."""
|
| 100 |
big = any(c.get("name") == "bytes" and (c.get("configuration") or {}).get("endian") == "big"
|
|
|
|
| 102 |
return np.dtype(meta["dtype"]).newbyteorder(">" if big else "<")
|
| 103 |
|
| 104 |
|
| 105 |
+
def chunk_groups(c):
|
| 106 |
+
"""Group the rows of an (N, d) integer array, such as each point's chunk index. Returns (keys, order, bounds):
|
| 107 |
+
keys are the distinct rows in lexicographic order, as np.unique(c, axis=0) returns them, and
|
| 108 |
+
order[bounds[k]:bounds[k + 1]] are the numbers of the rows equal to keys[k], ascending, as
|
| 109 |
+
np.flatnonzero(inverse == k) gives them. One stable argsort of a flat mixed-radix key replaces unique(axis=0)
|
| 110 |
+
and a scan of every row for every group, which is about ten times faster on millions of points."""
|
| 111 |
+
c = np.asarray(c)
|
| 112 |
+
n = len(c)
|
| 113 |
+
if not n:
|
| 114 |
+
return c[:0], np.zeros(0, np.intp), np.zeros(1, np.intp)
|
| 115 |
+
lo = c.min(axis=0)
|
| 116 |
+
ext = [int(h) - int(l) + 1 for h, l in zip(c.max(axis=0).tolist(), lo.tolist())]
|
| 117 |
+
size = 1
|
| 118 |
+
for e in ext:
|
| 119 |
+
size *= e
|
| 120 |
+
if not np.issubdtype(c.dtype, np.integer) or size >= 2 ** 62:
|
| 121 |
+
# the flat key would not fit in int64: group by unique(axis=0) itself
|
| 122 |
+
keys, inv = np.unique(c, axis=0, return_inverse=True)
|
| 123 |
+
inv = np.asarray(inv).reshape(-1)
|
| 124 |
+
order = np.argsort(inv, kind="stable")
|
| 125 |
+
bounds = np.concatenate(([0], np.cumsum(np.bincount(inv, minlength=len(keys))))).astype(np.intp)
|
| 126 |
+
return keys, order, bounds
|
| 127 |
+
d = c.astype(np.int64) - lo.astype(np.int64) # exact: wraparound cancels and each difference is below 2 ** 62
|
| 128 |
+
flat = d[:, 0].copy()
|
| 129 |
+
for j in range(1, len(ext)):
|
| 130 |
+
flat *= ext[j]
|
| 131 |
+
flat += d[:, j]
|
| 132 |
+
order = np.argsort(flat, kind="stable")
|
| 133 |
+
fs = flat[order]
|
| 134 |
+
cut = np.flatnonzero(fs[1:] != fs[:-1]) + 1
|
| 135 |
+
bounds = np.concatenate(([0], cut, [n])).astype(np.intp)
|
| 136 |
+
return c[order[bounds[:-1]]], order, bounds
|
| 137 |
+
|
| 138 |
+
|
| 139 |
class Volume:
|
| 140 |
"""One OME-Zarr volume (or bare array) for reading boxes and sampling points; decoded chunks are kept in a
|
| 141 |
small cache. `voxel_um` is level 0's voxel size, when known."""
|
|
|
|
| 350 |
def read(self, level, box):
|
| 351 |
"""The box [[z0, z1], [y0, y1], [x0, x1]] of a level (integers; parts outside the array read as fill)."""
|
| 352 |
meta = self.levels[level]["meta"]
|
| 353 |
+
if _permutes(meta.get("codecs")):
|
| 354 |
+
raise RegionError(f"{self.store} level {level}: the transpose codec changes the axis order and is not "
|
| 355 |
+
"read here; rewrite the array without it, in C order")
|
| 356 |
box = [[int(a), int(b)] for a, b in box]
|
| 357 |
size = [max(0, b - a) for a, b in box]
|
| 358 |
fill = meta.get("fill_value")
|
|
|
|
| 383 |
|
| 384 |
def sample(self, level, xyz, pad=1):
|
| 385 |
"""Trilinear values at points (N, 3) given as (x, y, z) in a level's voxels; points outside the array
|
| 386 |
+
read the fill value at their neighbors."""
|
| 387 |
pts = np.asarray(xyz, dtype=float).reshape(-1, 3)
|
| 388 |
zyx = pts[:, ::-1]
|
| 389 |
lo = np.floor(zyx.min(axis=0)).astype(int) - pad
|
|
|
|
| 442 |
|
| 443 |
def peak(ncc, exclude=4.0):
|
| 444 |
"""(peak value, peak position, best value farther than `exclude` voxels from the peak) of an NCC map. The
|
| 445 |
+
position is refined below a voxel by a parabola through the peak and its neighbors on each axis."""
|
| 446 |
k = np.unravel_index(int(np.argmax(ncc)), ncc.shape)
|
| 447 |
grid = np.indices(ncc.shape).reshape(3, -1).T
|
| 448 |
far = np.sqrt(((grid - np.array(k)) ** 2).sum(axis=1)) > exclude
|
kit/verify.py
CHANGED
|
@@ -6,13 +6,13 @@ agreement under a stated tolerance counts only if a deliberately wrong input, th
|
|
| 6 |
control, is caught by the same comparison. Without a control the verdict says so.
|
| 7 |
|
| 8 |
Default tolerance: villa PR #1865 reported CPU and MPS maps differing by at most 1 of
|
| 9 |
-
255
|
| 10 |
beyond that) leave margin above that report without accepting a different map.
|
| 11 |
|
| 12 |
The maps are villa's uint8 TIFFs. Reading them needs numpy and tifffile (and
|
| 13 |
imagecodecs for LZW); villa's environment has all three. `load_map` also reads 8-bit and
|
| 14 |
-
16-bit
|
| 15 |
-
a
|
| 16 |
ignored); palette, sub-byte and interlaced PNG are refused. Maps keep their own grid; a
|
| 17 |
map on another grid is refused by the comparison, never resized here.
|
| 18 |
"""
|
|
@@ -23,6 +23,7 @@ import zlib
|
|
| 23 |
from pathlib import Path
|
| 24 |
|
| 25 |
DEFAULT_TOLERANCE = 2
|
|
|
|
| 26 |
DEFAULT_MAX_FRACTION = 1e-4
|
| 27 |
ROWS_PER_BLOCK = 1024
|
| 28 |
|
|
@@ -48,14 +49,93 @@ def _numpy():
|
|
| 48 |
|
| 49 |
|
| 50 |
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
| 51 |
-
PNG_CHANNELS = {0: 1, 2: 3, 4: 2, 6: 4} #
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
|
| 54 |
def _png_unfilter(np, rows, filters, bpp):
|
| 55 |
"""Undo PNG's per-row filters. rows: (h, stride) uint8 as stored, filters: (h,) filter types.
|
| 56 |
|
| 57 |
Rows filtered with None, Sub or Up are undone one row at a time. Average and Paeth depend on
|
| 58 |
-
the reconstructed left
|
| 59 |
anti-diagonals: every pixel of one diagonal depends only on the two diagonals before it."""
|
| 60 |
h, stride = rows.shape
|
| 61 |
if filters.size and int(filters.max()) > 4:
|
|
@@ -90,12 +170,14 @@ def _png_unfilter(np, rows, filters, bpp):
|
|
| 90 |
return pad.reshape(h + 1, w1, bpp)[1:, 1:].reshape(h, stride).astype(np.uint8)
|
| 91 |
|
| 92 |
|
| 93 |
-
def read_png(path):
|
| 94 |
-
"""A
|
|
|
|
| 95 |
np = _numpy()
|
| 96 |
blob = Path(path).read_bytes()
|
| 97 |
if blob[:8] != PNG_SIGNATURE:
|
| 98 |
raise VerifyError(f"{path}: not a PNG")
|
|
|
|
| 99 |
pos, idat, header = 8, [], None
|
| 100 |
while pos + 8 <= len(blob):
|
| 101 |
n = struct.unpack(">I", blob[pos:pos + 4])[0]
|
|
@@ -115,8 +197,8 @@ def read_png(path):
|
|
| 115 |
if not (w and h):
|
| 116 |
raise VerifyError(f"{path}: empty PNG ({w} x {h})")
|
| 117 |
if color not in PNG_CHANNELS or depth not in (8, 16) or interlace:
|
| 118 |
-
raise VerifyError(f"{path}: only 8 or 16-bit
|
| 119 |
-
f"(bit depth {depth},
|
| 120 |
channels = PNG_CHANNELS[color]
|
| 121 |
bpp = channels * depth // 8
|
| 122 |
stride = w * bpp
|
|
@@ -133,7 +215,7 @@ def read_png(path):
|
|
| 133 |
data = data.reshape(h, w, channels)
|
| 134 |
colours = data[..., :3] if channels >= 3 else data[..., :1]
|
| 135 |
if colours.shape[-1] > 1 and not (colours == colours[..., :1]).all():
|
| 136 |
-
raise VerifyError(f"{path}: a
|
| 137 |
return np.ascontiguousarray(data[..., 0])
|
| 138 |
|
| 139 |
|
|
@@ -160,8 +242,9 @@ def load_map(path):
|
|
| 160 |
return array
|
| 161 |
|
| 162 |
|
| 163 |
-
def compare(reference, candidate, tolerance=DEFAULT_TOLERANCE):
|
| 164 |
-
"""Statistics of candidate minus reference, computed in row blocks to bound memory
|
|
|
|
| 165 |
np = _numpy()
|
| 166 |
if reference.shape != candidate.shape:
|
| 167 |
return {"shape_match": False, "reference_shape": list(reference.shape),
|
|
@@ -172,12 +255,20 @@ def compare(reference, candidate, tolerance=DEFAULT_TOLERANCE):
|
|
| 172 |
over = 0
|
| 173 |
sx = sy = sxx = syy = sxy = 0.0
|
| 174 |
for start in range(0, reference.shape[0], ROWS_PER_BLOCK):
|
| 175 |
-
a = reference[start:start + ROWS_PER_BLOCK].astype(np.float64)
|
| 176 |
-
b = candidate[start:start + ROWS_PER_BLOCK].astype(np.float64)
|
| 177 |
d = np.abs(b - a)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
max_abs = max(max_abs, float(d.max()))
|
| 179 |
sum_abs += float(d.sum())
|
| 180 |
-
over += int(
|
| 181 |
sx += float(a.sum())
|
| 182 |
sy += float(b.sum())
|
| 183 |
sxx += float((a * a).sum())
|
|
@@ -214,13 +305,53 @@ def verdict(candidate_agrees, control_agrees=None):
|
|
| 214 |
return PASS
|
| 215 |
|
| 216 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
def verify_arrays(reference, candidate, control=None, tolerance=DEFAULT_TOLERANCE,
|
| 218 |
max_fraction=DEFAULT_MAX_FRACTION):
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
result["candidate_agrees"] = agrees(result["candidate"], max_fraction)
|
| 221 |
control_agrees = None
|
| 222 |
if control is not None:
|
| 223 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
control_agrees = agrees(result["control"], max_fraction)
|
| 225 |
result["control_agrees"] = control_agrees
|
| 226 |
result["verdict"] = verdict(result["candidate_agrees"], control_agrees)
|
|
|
|
| 6 |
control, is caught by the same comparison. Without a control the verdict says so.
|
| 7 |
|
| 8 |
Default tolerance: villa PR #1865 reported CPU and MPS maps differing by at most 1 of
|
| 9 |
+
255 gray levels on 0.002% of pixels. The defaults (2 levels, at most 0.01% of pixels
|
| 10 |
beyond that) leave margin above that report without accepting a different map.
|
| 11 |
|
| 12 |
The maps are villa's uint8 TIFFs. Reading them needs numpy and tifffile (and
|
| 13 |
imagecodecs for LZW); villa's environment has all three. `load_map` also reads 8-bit and
|
| 14 |
+
16-bit gray PNG (Hecate writes its maps as PNG, round(255 p)) with zlib and numpy alone:
|
| 15 |
+
a color PNG is accepted only when its color channels agree (the first is kept, alpha is
|
| 16 |
ignored); palette, sub-byte and interlaced PNG are refused. Maps keep their own grid; a
|
| 17 |
map on another grid is refused by the comparison, never resized here.
|
| 18 |
"""
|
|
|
|
| 23 |
from pathlib import Path
|
| 24 |
|
| 25 |
DEFAULT_TOLERANCE = 2
|
| 26 |
+
UNIT_SLACK = 1e-3 # kit.mapscale.UNIT_SLACK: a float map up to 1.001 still counts as 0 to 1
|
| 27 |
DEFAULT_MAX_FRACTION = 1e-4
|
| 28 |
ROWS_PER_BLOCK = 1024
|
| 29 |
|
|
|
|
| 49 |
|
| 50 |
|
| 51 |
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
| 52 |
+
PNG_CHANNELS = {0: 1, 2: 3, 4: 2, 6: 4} # color type: samples per pixel (3, palette, is refused)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# ---------------------------------------------------------------- sealed files
|
| 56 |
+
# A preregistration can seal published files (labels, or maps made with them) until its one-time opening, so that no
|
| 57 |
+
# choice made before the opening can use them. A registry, a JSON file under a folder of the source repository, lists each sealed file
|
| 58 |
+
# by sha256 with its group (the unit that opens together) and whether it may be decoded after the opening at all, and
|
| 59 |
+
# names the marker file, relative to the source folder, whose "openings" list records the opened groups:
|
| 60 |
+
# {"marker": "docs/.../openings.json",
|
| 61 |
+
# "files": {"<sha256>": {"file": "<name>", "group": "<group>", "after_opening": true}}}
|
| 62 |
+
# read_png here and kit.vc3d_io.read_png_gray call sealed_refuse before decoding, so every kit command that reads a
|
| 63 |
+
# PNG through them (kit auc, the agent tools) refuses a sealed file. Readers outside
|
| 64 |
+
# kit (PIL, tifffile, cv2 in a script) are not covered. With no registry nothing is hashed.
|
| 65 |
+
SOURCE = Path(__file__).resolve().parents[1]
|
| 66 |
+
SEALED_DIR = SOURCE / "kit" / "data" / "sealed"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class SealedError(VerifyError):
|
| 70 |
+
"""A sealed file would be decoded before its opening is recorded, or at all when it never opens."""
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def sealed_registries():
|
| 74 |
+
"""Every registry under SEALED_DIR, as dicts; an unreadable registry is an error, not a free pass."""
|
| 75 |
+
if not SEALED_DIR.is_dir():
|
| 76 |
+
return []
|
| 77 |
+
import json
|
| 78 |
+
out = []
|
| 79 |
+
for path in sorted(SEALED_DIR.glob("*.json")):
|
| 80 |
+
try:
|
| 81 |
+
reg = json.loads(path.read_text(encoding="utf-8"))
|
| 82 |
+
except (OSError, ValueError) as exc:
|
| 83 |
+
raise SealedError(f"cannot read the sealed-file registry {path}: {exc}") from None
|
| 84 |
+
reg.setdefault("source", str(path))
|
| 85 |
+
out.append(reg)
|
| 86 |
+
return out
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def opened_groups(marker, source=None):
|
| 90 |
+
"""Groups that the marker file (relative to the source folder) records as opened; none when it is absent."""
|
| 91 |
+
if not marker:
|
| 92 |
+
return set()
|
| 93 |
+
path = Path(source or SOURCE) / marker
|
| 94 |
+
if not path.is_file():
|
| 95 |
+
return set()
|
| 96 |
+
import json
|
| 97 |
+
try:
|
| 98 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 99 |
+
except (OSError, ValueError) as exc:
|
| 100 |
+
raise SealedError(f"cannot read the opening marker {path}: {exc}") from None
|
| 101 |
+
return {str(g) for entry in data.get("openings", []) for g in entry.get("windings", entry.get("groups", []))}
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def sealed_check(blob, what="file", registries=None):
|
| 105 |
+
"""None when the bytes may be decoded now, else why not."""
|
| 106 |
+
regs = sealed_registries() if registries is None else registries
|
| 107 |
+
if not regs:
|
| 108 |
+
return None
|
| 109 |
+
import hashlib
|
| 110 |
+
digest = hashlib.sha256(bytes(blob)).hexdigest()
|
| 111 |
+
for reg in regs:
|
| 112 |
+
entry = (reg.get("files") or {}).get(digest)
|
| 113 |
+
if entry is None:
|
| 114 |
+
continue
|
| 115 |
+
name = entry.get("file", digest[:12])
|
| 116 |
+
if not entry.get("after_opening", False):
|
| 117 |
+
return f"{what} is {name}, sealed by {reg['source']}: it is never decoded, before or after the opening"
|
| 118 |
+
if str(entry.get("group")) not in opened_groups(reg.get("marker")):
|
| 119 |
+
return (f"{what} is {name}, sealed by {reg['source']} until the opening of {entry.get('group')} is "
|
| 120 |
+
f"recorded in {reg.get('marker')}")
|
| 121 |
+
return None
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def sealed_refuse(blob, what="file", allow=False):
|
| 125 |
+
"""SealedError when `blob` is a sealed file that may not be decoded now; allow=True is for the one tool that
|
| 126 |
+
performs the opening, which records it first."""
|
| 127 |
+
if allow:
|
| 128 |
+
return
|
| 129 |
+
why = sealed_check(blob, what)
|
| 130 |
+
if why:
|
| 131 |
+
raise SealedError(why)
|
| 132 |
|
| 133 |
|
| 134 |
def _png_unfilter(np, rows, filters, bpp):
|
| 135 |
"""Undo PNG's per-row filters. rows: (h, stride) uint8 as stored, filters: (h,) filter types.
|
| 136 |
|
| 137 |
Rows filtered with None, Sub or Up are undone one row at a time. Average and Paeth depend on
|
| 138 |
+
the reconstructed left neighbor, so when any row uses them the whole image is undone along
|
| 139 |
anti-diagonals: every pixel of one diagonal depends only on the two diagonals before it."""
|
| 140 |
h, stride = rows.shape
|
| 141 |
if filters.size and int(filters.max()) > 4:
|
|
|
|
| 170 |
return pad.reshape(h + 1, w1, bpp)[1:, 1:].reshape(h, stride).astype(np.uint8)
|
| 171 |
|
| 172 |
|
| 173 |
+
def read_png(path, allow_sealed=False):
|
| 174 |
+
"""A gray PNG (8 or 16 bit) as a 2D uint8 or uint16 array, decoded with zlib and numpy. A sealed file (above)
|
| 175 |
+
is refused unless allow_sealed."""
|
| 176 |
np = _numpy()
|
| 177 |
blob = Path(path).read_bytes()
|
| 178 |
if blob[:8] != PNG_SIGNATURE:
|
| 179 |
raise VerifyError(f"{path}: not a PNG")
|
| 180 |
+
sealed_refuse(blob, str(path), allow_sealed)
|
| 181 |
pos, idat, header = 8, [], None
|
| 182 |
while pos + 8 <= len(blob):
|
| 183 |
n = struct.unpack(">I", blob[pos:pos + 4])[0]
|
|
|
|
| 197 |
if not (w and h):
|
| 198 |
raise VerifyError(f"{path}: empty PNG ({w} x {h})")
|
| 199 |
if color not in PNG_CHANNELS or depth not in (8, 16) or interlace:
|
| 200 |
+
raise VerifyError(f"{path}: only 8 or 16-bit gray (or gray-valued color), non-interlaced PNG is read "
|
| 201 |
+
f"(bit depth {depth}, color type {color}, interlace {interlace})")
|
| 202 |
channels = PNG_CHANNELS[color]
|
| 203 |
bpp = channels * depth // 8
|
| 204 |
stride = w * bpp
|
|
|
|
| 215 |
data = data.reshape(h, w, channels)
|
| 216 |
colours = data[..., :3] if channels >= 3 else data[..., :1]
|
| 217 |
if colours.shape[-1] > 1 and not (colours == colours[..., :1]).all():
|
| 218 |
+
raise VerifyError(f"{path}: a color PNG whose channels differ is not an ink map")
|
| 219 |
return np.ascontiguousarray(data[..., 0])
|
| 220 |
|
| 221 |
|
|
|
|
| 242 |
return array
|
| 243 |
|
| 244 |
|
| 245 |
+
def compare(reference, candidate, tolerance=DEFAULT_TOLERANCE, factor=1.0):
|
| 246 |
+
"""Statistics of candidate minus reference, computed in row blocks to bound memory; both are multiplied by
|
| 247 |
+
factor first (255 puts two 0 to 1 maps on the gray levels the tolerance counts)."""
|
| 248 |
np = _numpy()
|
| 249 |
if reference.shape != candidate.shape:
|
| 250 |
return {"shape_match": False, "reference_shape": list(reference.shape),
|
|
|
|
| 255 |
over = 0
|
| 256 |
sx = sy = sxx = syy = sxy = 0.0
|
| 257 |
for start in range(0, reference.shape[0], ROWS_PER_BLOCK):
|
| 258 |
+
a = reference[start:start + ROWS_PER_BLOCK].astype(np.float64) * factor
|
| 259 |
+
b = candidate[start:start + ROWS_PER_BLOCK].astype(np.float64) * factor
|
| 260 |
d = np.abs(b - a)
|
| 261 |
+
# NaN or inf in one map and not the other is a disagreement: d is then NaN or inf, and
|
| 262 |
+
# max() and "d > tolerance" would both pass a NaN by. Equal values (inf and inf) or NaN in
|
| 263 |
+
# both maps at the same pixel agree.
|
| 264 |
+
same = (a == b) | (np.isnan(a) & np.isnan(b))
|
| 265 |
+
bad = ~(d <= tolerance) & ~same
|
| 266 |
+
d = np.where(same, 0.0, d)
|
| 267 |
+
if bad.any() and not np.isfinite(d[bad]).all():
|
| 268 |
+
max_abs = math.inf
|
| 269 |
max_abs = max(max_abs, float(d.max()))
|
| 270 |
sum_abs += float(d.sum())
|
| 271 |
+
over += int(bad.sum())
|
| 272 |
sx += float(a.sum())
|
| 273 |
sy += float(b.sum())
|
| 274 |
sxx += float((a * a).sum())
|
|
|
|
| 305 |
return PASS
|
| 306 |
|
| 307 |
|
| 308 |
+
def _gray_factor(np, reference, candidate, control=None):
|
| 309 |
+
"""255 when the maps are float maps in 0 to 1, so the tolerance counts gray levels as it does on villa's uint8
|
| 310 |
+
maps (on 0 to 1 a tolerance of 2 let any candidate agree; audit, 22 Oct 2026); else 1. A 0 to 1 map beside a
|
| 311 |
+
uint8 or uint16 map, or a uint8 beside a uint16 map, is refused: they differ by up to 255 everywhere. A float
|
| 312 |
+
map holding gray levels (0 to 255) may still be compared with a uint8 one, and a blank map with any."""
|
| 313 |
+
# kit.mapscale's rule, inlined: the AutoPipeline Space stages verify.py without mapscale.py
|
| 314 |
+
maps = [reference, candidate] + ([control] if control is not None else [])
|
| 315 |
+
|
| 316 |
+
def scale(m):
|
| 317 |
+
d = np.asarray(m).dtype
|
| 318 |
+
if d.kind == "u" and d.itemsize in (1, 2):
|
| 319 |
+
return "u8" if d.itemsize == 1 else "u16"
|
| 320 |
+
if d.kind != "f":
|
| 321 |
+
return None
|
| 322 |
+
v = np.asarray(m)
|
| 323 |
+
lo, hi = (float(np.fmin.reduce(v, axis=None)), float(np.fmax.reduce(v, axis=None))) if v.size else (0.0, 0.0)
|
| 324 |
+
if lo != lo or hi == 0:
|
| 325 |
+
return None # all NaN or all zero: fits any scale
|
| 326 |
+
return "unit" if lo >= 0 and hi <= 1 + UNIT_SLACK else "float"
|
| 327 |
+
found = {scale(m) for m in maps} - {None}
|
| 328 |
+
if ("unit" in found and found & {"u8", "u16"}) or {"u8", "u16"} <= found:
|
| 329 |
+
raise VerifyError(f"the maps are on different scales ({', '.join(sorted(found))}); compare maps of one scale "
|
| 330 |
+
"(kit.mapscale.to_u8 puts a 0 to 1 map on villa's uint8 grid)")
|
| 331 |
+
floats = all(np.asarray(m).dtype.kind == "f" for m in maps)
|
| 332 |
+
return 255.0 if floats and found == {"unit"} else 1.0
|
| 333 |
+
|
| 334 |
+
|
| 335 |
def verify_arrays(reference, candidate, control=None, tolerance=DEFAULT_TOLERANCE,
|
| 336 |
max_fraction=DEFAULT_MAX_FRACTION):
|
| 337 |
+
np = _numpy()
|
| 338 |
+
if reference.dtype.kind == "f" and reference.size and not np.isfinite(reference).any():
|
| 339 |
+
# NaN at the same pixel counts as agreement, so an all-NaN candidate (both devices overflowing,
|
| 340 |
+
# say) would agree with an all-NaN reference and any finite control would look caught
|
| 341 |
+
raise VerifyError("the reference map has no finite values; a broken reference cannot show agreement")
|
| 342 |
+
factor = _gray_factor(np, reference, candidate, control)
|
| 343 |
+
result = {"candidate": compare(reference, candidate, tolerance, factor), "max_fraction": max_fraction}
|
| 344 |
+
if factor != 1.0:
|
| 345 |
+
result["scaled_from_0_1"] = True
|
| 346 |
result["candidate_agrees"] = agrees(result["candidate"], max_fraction)
|
| 347 |
control_agrees = None
|
| 348 |
if control is not None:
|
| 349 |
+
if control.shape != reference.shape:
|
| 350 |
+
# A control of another shape would "disagree" by shape alone and turn any candidate
|
| 351 |
+
# into a pass; it shows nothing about whether the comparison can fail.
|
| 352 |
+
raise VerifyError(f"control shape {tuple(control.shape)} differs from the reference's "
|
| 353 |
+
f"{tuple(reference.shape)}; the control must be the same map made wrongly")
|
| 354 |
+
result["control"] = compare(reference, control, tolerance, factor)
|
| 355 |
control_agrees = agrees(result["control"], max_fraction)
|
| 356 |
result["control_agrees"] = control_agrees
|
| 357 |
result["verdict"] = verdict(result["candidate_agrees"], control_agrees)
|
samples.json
CHANGED
|
@@ -2,11 +2,11 @@
|
|
| 2 |
"note": "Public crops of released segments. The Space reads them anonymously from the open-data bucket when someone runs one; nothing is bundled. Crops are (y0, y1, x0, x1) on the segment's 9 um surface volume.",
|
| 3 |
"bucket": "https://vesuvius-challenge-open-data.s3.us-east-1.amazonaws.com",
|
| 4 |
"checkpoint": {
|
| 5 |
-
"name": "
|
| 6 |
-
"repo": "domenicor046/reader-
|
| 7 |
-
"file": "reader-
|
| 8 |
-
"url": "https://huggingface.co/domenicor046/reader-
|
| 9 |
-
"sha256": "
|
| 10 |
"license": "MIT"
|
| 11 |
},
|
| 12 |
"villa_commit": "e0bbb8b40a2db58b1d71864f286eb85717e59e64",
|
|
@@ -18,10 +18,18 @@
|
|
| 18 |
"segment": "20260220213127-w00",
|
| 19 |
"surface_volume": "surface-volumes/9.366um-1.2m-113keV-volume-20250821151531.zarr",
|
| 20 |
"labels": "ink-labels/2.403um-volume-20260319124803/20260918",
|
| 21 |
-
"surface_shape": [
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
"role": "development",
|
| 24 |
-
"note": "Reader
|
| 25 |
},
|
| 26 |
{
|
| 27 |
"id": "0841-ag896",
|
|
@@ -30,10 +38,18 @@
|
|
| 30 |
"segment": "20260220214732-auto_grown_20260220144552896",
|
| 31 |
"surface_volume": "surface-volumes/9.366um-1.2m-113keV-volume-20250821151531.zarr",
|
| 32 |
"labels": "ink-labels/2.403um-volume-20260319124803/20260918",
|
| 33 |
-
"surface_shape": [
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
"role": "development",
|
| 36 |
-
"note": "Reader
|
| 37 |
},
|
| 38 |
{
|
| 39 |
"id": "0139-w035",
|
|
@@ -42,10 +58,18 @@
|
|
| 42 |
"segment": "20260317000000-w035_2026031718",
|
| 43 |
"surface_volume": "surface-volumes/9.362um-1.2m-113keV-volume-20250728140407.zarr",
|
| 44 |
"labels": "ink-labels/2.399um-volume-20260102150214/20260918",
|
| 45 |
-
"surface_shape": [
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
"role": "training",
|
| 48 |
-
"note": "Training data:
|
| 49 |
},
|
| 50 |
{
|
| 51 |
"id": "0139-w045",
|
|
@@ -54,10 +78,18 @@
|
|
| 54 |
"segment": "20260126000000-w045_2026012619",
|
| 55 |
"surface_volume": "surface-volumes/9.362um-1.2m-113keV-volume-20250728140407.zarr",
|
| 56 |
"labels": "ink-labels/2.399um-volume-20260102150214/20260918",
|
| 57 |
-
"surface_shape": [
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
"role": "training",
|
| 60 |
-
"note": "Not held out: Reader
|
| 61 |
}
|
| 62 |
]
|
| 63 |
}
|
|
|
|
| 2 |
"note": "Public crops of released segments. The Space reads them anonymously from the open-data bucket when someone runs one; nothing is bundled. Crops are (y0, y1, x0, x1) on the segment's 9 um surface volume.",
|
| 3 |
"bucket": "https://vesuvius-challenge-open-data.s3.us-east-1.amazonaws.com",
|
| 4 |
"checkpoint": {
|
| 5 |
+
"name": "readerv3",
|
| 6 |
+
"repo": "domenicor046/reader-v3",
|
| 7 |
+
"file": "reader-v3.pth",
|
| 8 |
+
"url": "https://huggingface.co/domenicor046/reader-v3/resolve/main/reader-v3.pth",
|
| 9 |
+
"sha256": "ea405417450abd8ace1b8ff79ebce3adb646c5e48ab95da46844d77efe984d8a",
|
| 10 |
"license": "MIT"
|
| 11 |
},
|
| 12 |
"villa_commit": "e0bbb8b40a2db58b1d71864f286eb85717e59e64",
|
|
|
|
| 18 |
"segment": "20260220213127-w00",
|
| 19 |
"surface_volume": "surface-volumes/9.366um-1.2m-113keV-volume-20250821151531.zarr",
|
| 20 |
"labels": "ink-labels/2.403um-volume-20260319124803/20260918",
|
| 21 |
+
"surface_shape": [
|
| 22 |
+
4220,
|
| 23 |
+
4760
|
| 24 |
+
],
|
| 25 |
+
"crop": [
|
| 26 |
+
2624,
|
| 27 |
+
3264,
|
| 28 |
+
2688,
|
| 29 |
+
3328
|
| 30 |
+
],
|
| 31 |
"role": "development",
|
| 32 |
+
"note": "Reader V3 was not trained on PHerc0841, and neither were Reader v2 and ink_9um, the models it continues. Its author did benchmark PHerc0841 while choosing its recipe, so it may have been selected on these segments. This 640 px window was picked with the labels, where they mark a lot of ink, so its AUC is a development number, not a blind test."
|
| 33 |
},
|
| 34 |
{
|
| 35 |
"id": "0841-ag896",
|
|
|
|
| 38 |
"segment": "20260220214732-auto_grown_20260220144552896",
|
| 39 |
"surface_volume": "surface-volumes/9.366um-1.2m-113keV-volume-20250821151531.zarr",
|
| 40 |
"labels": "ink-labels/2.403um-volume-20260319124803/20260918",
|
| 41 |
+
"surface_shape": [
|
| 42 |
+
4640,
|
| 43 |
+
4720
|
| 44 |
+
],
|
| 45 |
+
"crop": [
|
| 46 |
+
2496,
|
| 47 |
+
3136,
|
| 48 |
+
1600,
|
| 49 |
+
2240
|
| 50 |
+
],
|
| 51 |
"role": "development",
|
| 52 |
+
"note": "Reader V3 was not trained on PHerc0841, and neither were Reader v2 and ink_9um, the models it continues. Its author did benchmark PHerc0841 while choosing its recipe, so it may have been selected on these segments. This 640 px window was picked with the labels, where they mark a lot of ink, so its AUC is a development number, not a blind test."
|
| 53 |
},
|
| 54 |
{
|
| 55 |
"id": "0139-w035",
|
|
|
|
| 58 |
"segment": "20260317000000-w035_2026031718",
|
| 59 |
"surface_volume": "surface-volumes/9.362um-1.2m-113keV-volume-20250728140407.zarr",
|
| 60 |
"labels": "ink-labels/2.399um-volume-20260102150214/20260918",
|
| 61 |
+
"surface_shape": [
|
| 62 |
+
5820,
|
| 63 |
+
5240
|
| 64 |
+
],
|
| 65 |
+
"crop": [
|
| 66 |
+
1920,
|
| 67 |
+
2560,
|
| 68 |
+
2304,
|
| 69 |
+
2944
|
| 70 |
+
],
|
| 71 |
"role": "training",
|
| 72 |
+
"note": "Training data: ink_9um was trained on this segment, and Reader v2 and Reader V3 continue from it, so a high AUC here only shows the pipeline runs. It is not a test."
|
| 73 |
},
|
| 74 |
{
|
| 75 |
"id": "0139-w045",
|
|
|
|
| 78 |
"segment": "20260126000000-w045_2026012619",
|
| 79 |
"surface_volume": "surface-volumes/9.362um-1.2m-113keV-volume-20250728140407.zarr",
|
| 80 |
"labels": "ink-labels/2.399um-volume-20260102150214/20260918",
|
| 81 |
+
"surface_shape": [
|
| 82 |
+
5980,
|
| 83 |
+
8240
|
| 84 |
+
],
|
| 85 |
+
"crop": [
|
| 86 |
+
3840,
|
| 87 |
+
4480,
|
| 88 |
+
2560,
|
| 89 |
+
3200
|
| 90 |
+
],
|
| 91 |
"role": "training",
|
| 92 |
+
"note": "Not held out: Reader V3 was trained on this segment and on its 2.4 um render (w029), as Reader v2 was before it, and ink_9um on that 2.4 um render. This 9 um render is a check on training data, not a test."
|
| 93 |
}
|
| 94 |
]
|
| 95 |
}
|
scripts/vc3d/ink.py
CHANGED
|
@@ -15,11 +15,15 @@ Each engine gets the layout it reads; copies go under DIR/work and are removed a
|
|
| 15 |
|
| 16 |
Engines
|
| 17 |
villa villa's flat inference, `python -m vesuvius.ink_detection.inference.infer`, on a .pth
|
| 18 |
-
checkpoint: ink_9um and its drop-in fine-tunes (Reader v2, d9v2)
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
layers to the model depth, Hann blending of 128 px patches. CPU, CUDA or MPS.
|
| 24 |
v8in a snapshot of Youssef Nader's v8in through scripts/v8in_run.py (reads a layer folder;
|
| 25 |
uses the central 24 layers).
|
|
@@ -31,7 +35,29 @@ Variants (--variants)
|
|
| 31 |
f forward: the layer order as rendered (the team's order when kit rendered it)
|
| 32 |
r depth reversed: the control a reader of real ink must lose (AGENTS.md rule 4)
|
| 33 |
s depth shuffled: a fixed permutation (kit.layers.depth_permutation, --seed) that is neither the
|
| 34 |
-
stored nor the reversed order;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
Writes DIR/ink_<variant>.tif or .npy and DIR/ink.json: each map's statistics as a probability,
|
| 37 |
inside the rendered surface (where the input's middle layer is nonzero), the forward map
|
|
@@ -54,6 +80,8 @@ from __future__ import annotations
|
|
| 54 |
|
| 55 |
import argparse
|
| 56 |
import array
|
|
|
|
|
|
|
| 57 |
import importlib.util
|
| 58 |
import json
|
| 59 |
import os
|
|
@@ -63,6 +91,7 @@ import subprocess
|
|
| 63 |
import sys
|
| 64 |
import tempfile
|
| 65 |
import time
|
|
|
|
| 66 |
from pathlib import Path
|
| 67 |
|
| 68 |
import numpy as np
|
|
@@ -80,6 +109,23 @@ def log(message):
|
|
| 80 |
print(f"[ink {time.strftime('%H:%M:%S')}] {message}", flush=True)
|
| 81 |
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
class InkError(Exception):
|
| 84 |
pass
|
| 85 |
|
|
@@ -130,7 +176,8 @@ class LayerStack:
|
|
| 130 |
|
| 131 |
|
| 132 |
def read_image(path):
|
| 133 |
-
"""A 2-D map or layer as numpy: TIFF (tifffile when installed, else kit.vc3d_io
|
|
|
|
| 134 |
p = Path(path)
|
| 135 |
if p.suffix.lower() == ".npy":
|
| 136 |
return np.load(p)
|
|
@@ -139,8 +186,18 @@ def read_image(path):
|
|
| 139 |
return np.asarray(Image.open(p))
|
| 140 |
try:
|
| 141 |
import tifffile
|
| 142 |
-
return np.squeeze(tifffile.imread(str(p)))
|
| 143 |
except ImportError:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
r = vc3d_io.read_tiff(p)
|
| 145 |
dtype = {"u8": np.uint8, "i8": np.int8, "u16": np.uint16, "i16": np.int16, "u32": np.uint32,
|
| 146 |
"i32": np.int32, "f32": np.float32, "f64": np.float64}[r.kind]
|
|
@@ -319,7 +376,11 @@ class Villa(Engine):
|
|
| 319 |
want = set(variants)
|
| 320 |
direction = "both" if want == {"f", "r"} else "forward" if want == {"f"} else "reverse"
|
| 321 |
target = out / "ink_f.tif" if "f" in want else out / "ink_r.tif"
|
| 322 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 323 |
"--direction", direction, "--batch-size", self.args.batch or 4, "--no-compile",
|
| 324 |
"--num-workers", min(4, self.args.threads)]
|
| 325 |
if self.args.stride:
|
|
@@ -345,18 +406,22 @@ class TorchScript(Engine):
|
|
| 345 |
self.mod = importlib.util.module_from_spec(spec)
|
| 346 |
spec.loader.exec_module(self.mod)
|
| 347 |
self.checkpoint = Path(args.checkpoint)
|
|
|
|
| 348 |
|
| 349 |
def run(self, path, variants, out):
|
| 350 |
out = Path(out)
|
| 351 |
out.mkdir(parents=True, exist_ok=True)
|
| 352 |
arr = open_stack(path)
|
| 353 |
n, h, w = arr.shape
|
|
|
|
|
|
|
|
|
|
| 354 |
maps = {}
|
| 355 |
for v in variants:
|
| 356 |
dest = out / f"ink_{v}.npy"
|
| 357 |
self.mod.run(str(path), str(self.checkpoint), str(dest), (0, h, 0, w), (0, n), v,
|
| 358 |
stride=self.args.stride or 96, batch=self.args.batch or 16, device=self.device,
|
| 359 |
-
threads=self.args.threads, seed=self.args.seed, log_every=0)
|
| 360 |
maps[v] = dest
|
| 361 |
return maps
|
| 362 |
|
|
@@ -450,7 +515,8 @@ def prepare(engine, src, a, b, box, work, shuffle_seed=None):
|
|
| 450 |
if engine.layout == "layers" and not is_layer_dir(src):
|
| 451 |
from kit.layers import export_layers # zarr to layer TIFFs in row bands, as kit layers does
|
| 452 |
dest = Path(work) / name
|
| 453 |
-
|
|
|
|
| 454 |
return dest, info
|
| 455 |
data = read_window(stack, a, b, box)
|
| 456 |
if order is not None:
|
|
@@ -554,6 +620,7 @@ def constant(prob, where=""):
|
|
| 554 |
|
| 555 |
|
| 556 |
IDENTICAL = "forward map is identical to the "
|
|
|
|
| 557 |
|
| 558 |
|
| 559 |
def unreadable(probs, mask=None):
|
|
@@ -589,16 +656,239 @@ def advice(failures):
|
|
| 589 |
writes; a forward map identical to a control means the control's input never reached the engine, and another
|
| 590 |
device will not change that."""
|
| 591 |
tips = []
|
| 592 |
-
|
|
|
|
| 593 |
tips.append("A broken GPU run can write such maps and exit 0; this is not a null result, so rerun on another "
|
| 594 |
"device or precision before reading anything.")
|
| 595 |
-
if any(r.startswith(IDENTICAL) for r in
|
| 596 |
tips.append("A forward map identical to a control means the engine did not read the control's input (check "
|
| 597 |
"{reverse}, the layer window and the shuffled copy); this is not a null result, so fix that "
|
| 598 |
"before reading anything.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 599 |
return " ".join(tips)
|
| 600 |
|
| 601 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 602 |
# ---------------------------------------------------------------- main
|
| 603 |
|
| 604 |
def run(args):
|
|
@@ -614,6 +904,7 @@ def run(args):
|
|
| 614 |
stack = open_stack(args.input)
|
| 615 |
box = tuple(int(v) for v in args.box.split(",")) if args.box else None
|
| 616 |
a, b, box = window(stack.shape, args.layer_start, args.layer_end, box)
|
|
|
|
| 617 |
log(f"input {args.input}: {list(stack.shape)} layers x rows x cols; window layers [{a}, {b}), box {list(box)}; "
|
| 618 |
f"engine {engine.name} on {engine.device}")
|
| 619 |
maps, notes = {}, {}
|
|
@@ -634,8 +925,12 @@ def run(args):
|
|
| 634 |
if not args.keep_work and work.exists():
|
| 635 |
shutil.rmtree(work, ignore_errors=True)
|
| 636 |
mask = surface_mask(args.input, a, b, box)
|
| 637 |
-
|
|
|
|
| 638 |
failures = unreadable(probs, mask)
|
|
|
|
|
|
|
|
|
|
| 639 |
summary = {"engine": engine.describe(), "input": str(args.input), "window": {"layers": [a, b], "box": list(box)},
|
| 640 |
"variants": variants, "seed": args.seed, "prepared": notes,
|
| 641 |
"status": "failed" if failures else "ok", "failures": failures,
|
|
@@ -645,15 +940,68 @@ def run(args):
|
|
| 645 |
"seconds": round(time.time() - started, 1),
|
| 646 |
"note": "model output, not a reading; a forward map that keeps its blobs under the controls is "
|
| 647 |
"not responding to ink in depth order"}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 648 |
(out / "ink.json").write_text(json.dumps(summary, indent=1))
|
| 649 |
log(f"done in {summary['seconds']} s: " + ", ".join(
|
| 650 |
f"{v} above 0.5: {summary['maps'][v]['stats'].get('above_threshold')}" for v in maps))
|
| 651 |
if failures:
|
| 652 |
raise UnreadableMaps("the maps cannot be read (status failed in ink.json): " + "; ".join(failures) + ". " +
|
| 653 |
advice(failures), summary)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 654 |
return summary
|
| 655 |
|
| 656 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 657 |
def parse_args(argv=None):
|
| 658 |
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 659 |
p.add_argument("--input", required=True, help="surface volume: zarr or layer folder")
|
|
@@ -661,6 +1009,8 @@ def parse_args(argv=None):
|
|
| 661 |
p.add_argument("--variants", default="f,r", help="comma list of f, r, s (default f,r)")
|
| 662 |
p.add_argument("--engine", required=True, choices=sorted(ENGINES))
|
| 663 |
p.add_argument("--checkpoint", help="villa .pth or TorchScript .pt")
|
|
|
|
|
|
|
| 664 |
p.add_argument("--model-dir", help="v8in snapshot")
|
| 665 |
p.add_argument("--command-json", help="command engine: JSON argv with {input} or {layers}, {output}, "
|
| 666 |
"{reverse} and {device}")
|
|
@@ -673,6 +1023,14 @@ def parse_args(argv=None):
|
|
| 673 |
p.add_argument("--stride", type=int)
|
| 674 |
p.add_argument("--seed", type=int, default=SEED, help="depth-shuffle seed")
|
| 675 |
p.add_argument("--keep-work", action="store_true", help="keep the converted inputs under OUT/work")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 676 |
return p.parse_args(argv)
|
| 677 |
|
| 678 |
|
|
|
|
| 15 |
|
| 16 |
Engines
|
| 17 |
villa villa's flat inference, `python -m vesuvius.ink_detection.inference.infer`, on a .pth
|
| 18 |
+
checkpoint: ink_9um and its drop-in fine-tunes (Reader v2, d9v2), run through
|
| 19 |
+
scripts/vc3d/villa_infer.py, which loads the checkpoint weights-only (villa's own loader
|
| 20 |
+
would run any pickle code in it) and, with --checkpoint-sha256, checks the bytes it loads
|
| 21 |
+
against that hash. Forward and reverse come from one run (--direction both). CUDA when
|
| 22 |
+
available, else CPU; villa's flat inference has no MPS path, so on a Mac use the
|
| 23 |
+
torchscript engine.
|
| 24 |
+
torchscript a TorchScript export of an ink checkpoint (load only exports from a source you trust:
|
| 25 |
+
TorchScript is code; --checkpoint-sha256 is checked before the load), run here by
|
| 26 |
+
scripts/vc3d/torchscript_infer.py: villa's robust normalization, center crop of the
|
| 27 |
layers to the model depth, Hann blending of 128 px patches. CPU, CUDA or MPS.
|
| 28 |
v8in a snapshot of Youssef Nader's v8in through scripts/v8in_run.py (reads a layer folder;
|
| 29 |
uses the central 24 layers).
|
|
|
|
| 35 |
f forward: the layer order as rendered (the team's order when kit rendered it)
|
| 36 |
r depth reversed: the control a reader of real ink must lose (AGENTS.md rule 4)
|
| 37 |
s depth shuffled: a fixed permutation (kit.layers.depth_permutation, --seed) that is neither the
|
| 38 |
+
stored nor the reversed order; often, not always, a cleaner null than r (report the seed; docs/tricks.md)
|
| 39 |
+
|
| 40 |
+
Villa's names (--villa-names SEGDIR)
|
| 41 |
+
The forward map and the reversed control go into SEGDIR/preds/ under the names villa's folder inference gives its
|
| 42 |
+
own predictions, <seg>_<model>_forward_<ddmmyy>.tif and <seg>_<model>_reverse_<ddmmyy>.tif, as uint8 0 to 255,
|
| 43 |
+
tiled, LZW, Big TIFF (villa main 8aa507c12, vesuvius/src/vesuvius/ink_detection/inference/infer.py:791-834 and
|
| 44 |
+
1211-1213, 1223-1247), so villa's merge_predictions takes each by its direction and villa's folder inference counts
|
| 45 |
+
the segment as done for that model. <model> is the checkpoint's stem, as villa names it (--villa-model to choose
|
| 46 |
+
another; required for the command engine). The villa engine's own file is moved in byte for byte; a map in any other
|
| 47 |
+
form (v8in's float32 .npy, TorchScript's .npy, a command's TIFF) goes through kit.villafmt's `preds export`, which
|
| 48 |
+
encodes it as villa's inference does (clipped to 0 to 1, times 255, truncated). The forward map is then registered
|
| 49 |
+
in SEGDIR/ink-detections.json, the record VC3D's Ink Detection overlay lists (apps/VC3D/OpenDataSegmentCache.cpp:
|
| 50 |
+
651-694, 2022-2063), when SEGDIR is a tifxyz segment. That overlay opens a map with cv::imread, which cannot read a
|
| 51 |
+
.npy, and shows a uint8 map as stored but stretches any other depth from its own minimum to maximum
|
| 52 |
+
(overlays/InkDetectionOverlayController.cpp:106-137, 518). The controls are never registered, and the shuffled map
|
| 53 |
+
stays in DIR: villa has no name for it. ink.json keeps every variant under its key (f, r, s) with the path of the
|
| 54 |
+
file written, so a reader of ink.json["maps"] finds villa's files. Statistics and the unreadable-map test then read
|
| 55 |
+
the uint8 maps, and a map that holds nothing once encoded is refused like any unreadable map. Refused before the
|
| 56 |
+
model runs: a --box crop (villa and VC3D take one image per segment), a render whose size does not fit SEGDIR (the
|
| 57 |
+
tifxyz canvas's aspect within 2 percent, the exact size of a surface zarr there, and the size of the predictions of
|
| 58 |
+
the same direction already in preds/, since villa's merge stops on a shape mismatch), a name villa's merge would
|
| 59 |
+
read as the other direction, and a prediction already at the name (--villa-overwrite replaces it). Unreadable maps
|
| 60 |
+
are never written to preds/.
|
| 61 |
|
| 62 |
Writes DIR/ink_<variant>.tif or .npy and DIR/ink.json: each map's statistics as a probability,
|
| 63 |
inside the rendered surface (where the input's middle layer is nonzero), the forward map
|
|
|
|
| 80 |
|
| 81 |
import argparse
|
| 82 |
import array
|
| 83 |
+
import fnmatch
|
| 84 |
+
import hashlib
|
| 85 |
import importlib.util
|
| 86 |
import json
|
| 87 |
import os
|
|
|
|
| 91 |
import sys
|
| 92 |
import tempfile
|
| 93 |
import time
|
| 94 |
+
from datetime import datetime
|
| 95 |
from pathlib import Path
|
| 96 |
|
| 97 |
import numpy as np
|
|
|
|
| 109 |
print(f"[ink {time.strftime('%H:%M:%S')}] {message}", flush=True)
|
| 110 |
|
| 111 |
|
| 112 |
+
def check_checkpoint(path, want):
|
| 113 |
+
"""Refuse a checkpoint whose sha256 is not want (when want is given)."""
|
| 114 |
+
if not want:
|
| 115 |
+
return
|
| 116 |
+
got = _sha256(path)
|
| 117 |
+
if got != want.strip().lower():
|
| 118 |
+
raise InkError(f"{path}: sha256 {got}, expected {want}; refusing to load it")
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _sha256(path, chunk=1 << 22):
|
| 122 |
+
h = hashlib.sha256()
|
| 123 |
+
with open(path, "rb") as f:
|
| 124 |
+
for block in iter(lambda: f.read(chunk), b""):
|
| 125 |
+
h.update(block)
|
| 126 |
+
return h.hexdigest()
|
| 127 |
+
|
| 128 |
+
|
| 129 |
class InkError(Exception):
|
| 130 |
pass
|
| 131 |
|
|
|
|
| 176 |
|
| 177 |
|
| 178 |
def read_image(path):
|
| 179 |
+
"""A 2-D map or layer as numpy: TIFF (tifffile when installed, else kit.vc3d_io; an LZW TIFF such as villa's
|
| 180 |
+
predictions through kit.villafmt's decoder when tifffile has no imagecodecs), .npy or PNG."""
|
| 181 |
p = Path(path)
|
| 182 |
if p.suffix.lower() == ".npy":
|
| 183 |
return np.load(p)
|
|
|
|
| 186 |
return np.asarray(Image.open(p))
|
| 187 |
try:
|
| 188 |
import tifffile
|
|
|
|
| 189 |
except ImportError:
|
| 190 |
+
tifffile = None
|
| 191 |
+
if tifffile is not None:
|
| 192 |
+
try:
|
| 193 |
+
return np.squeeze(tifffile.imread(str(p)))
|
| 194 |
+
except ValueError: # an LZW TIFF, villa's prediction encoding, when tifffile has no imagecodecs
|
| 195 |
+
vf = _villafmt()
|
| 196 |
+
info = vf.tiff_info(p)
|
| 197 |
+
if info["compression"] != 5:
|
| 198 |
+
raise
|
| 199 |
+
return vf.read_lzw_pixels(p, info)
|
| 200 |
+
else:
|
| 201 |
r = vc3d_io.read_tiff(p)
|
| 202 |
dtype = {"u8": np.uint8, "i8": np.int8, "u16": np.uint16, "i16": np.int16, "u32": np.uint32,
|
| 203 |
"i32": np.int32, "f32": np.float32, "f64": np.float64}[r.kind]
|
|
|
|
| 376 |
want = set(variants)
|
| 377 |
direction = "both" if want == {"f", "r"} else "forward" if want == {"f"} else "reverse"
|
| 378 |
target = out / "ink_f.tif" if "f" in want else out / "ink_r.tif"
|
| 379 |
+
safe = [ROOT / "scripts" / "vc3d" / "villa_infer.py"] # villa's infer, with a weights-only load
|
| 380 |
+
pin = getattr(self.args, "checkpoint_sha256", None)
|
| 381 |
+
if pin:
|
| 382 |
+
safe += ["--sha256", pin]
|
| 383 |
+
argv = [sys.executable, *safe, path, self.checkpoint, target,
|
| 384 |
"--direction", direction, "--batch-size", self.args.batch or 4, "--no-compile",
|
| 385 |
"--num-workers", min(4, self.args.threads)]
|
| 386 |
if self.args.stride:
|
|
|
|
| 406 |
self.mod = importlib.util.module_from_spec(spec)
|
| 407 |
spec.loader.exec_module(self.mod)
|
| 408 |
self.checkpoint = Path(args.checkpoint)
|
| 409 |
+
self.loaded = None # the model is loaded once, then kept for every variant and stack
|
| 410 |
|
| 411 |
def run(self, path, variants, out):
|
| 412 |
out = Path(out)
|
| 413 |
out.mkdir(parents=True, exist_ok=True)
|
| 414 |
arr = open_stack(path)
|
| 415 |
n, h, w = arr.shape
|
| 416 |
+
if self.loaded is None:
|
| 417 |
+
check_checkpoint(self.checkpoint, getattr(self.args, "checkpoint_sha256", None))
|
| 418 |
+
self.loaded = self.mod.load_model(str(self.checkpoint))
|
| 419 |
maps = {}
|
| 420 |
for v in variants:
|
| 421 |
dest = out / f"ink_{v}.npy"
|
| 422 |
self.mod.run(str(path), str(self.checkpoint), str(dest), (0, h, 0, w), (0, n), v,
|
| 423 |
stride=self.args.stride or 96, batch=self.args.batch or 16, device=self.device,
|
| 424 |
+
threads=self.args.threads, seed=self.args.seed, log_every=0, loaded=self.loaded)
|
| 425 |
maps[v] = dest
|
| 426 |
return maps
|
| 427 |
|
|
|
|
| 515 |
if engine.layout == "layers" and not is_layer_dir(src):
|
| 516 |
from kit.layers import export_layers # zarr to layer TIFFs in row bands, as kit layers does
|
| 517 |
dest = Path(work) / name
|
| 518 |
+
shutil.rmtree(dest, ignore_errors=True) # this run's own copy from an earlier --keep-work run; kit layers
|
| 519 |
+
export_layers(stack, dest, start=a, count=b - a, crop=box, order=order) # refuses to write over one
|
| 520 |
return dest, info
|
| 521 |
data = read_window(stack, a, b, box)
|
| 522 |
if order is not None:
|
|
|
|
| 620 |
|
| 621 |
|
| 622 |
IDENTICAL = "forward map is identical to the "
|
| 623 |
+
ENCODED = " once encoded as villa's uint8 prediction" # --villa-names: a map that holds nothing in 0 to 255
|
| 624 |
|
| 625 |
|
| 626 |
def unreadable(probs, mask=None):
|
|
|
|
| 656 |
writes; a forward map identical to a control means the control's input never reached the engine, and another
|
| 657 |
device will not change that."""
|
| 658 |
tips = []
|
| 659 |
+
rest = [r for r in failures if not r.endswith(ENCODED)]
|
| 660 |
+
if any(not r.startswith(IDENTICAL) for r in rest):
|
| 661 |
tips.append("A broken GPU run can write such maps and exit 0; this is not a null result, so rerun on another "
|
| 662 |
"device or precision before reading anything.")
|
| 663 |
+
if any(r.startswith(IDENTICAL) for r in rest):
|
| 664 |
tips.append("A forward map identical to a control means the engine did not read the control's input (check "
|
| 665 |
"{reverse}, the layer window and the shuffled copy); this is not a null result, so fix that "
|
| 666 |
"before reading anything.")
|
| 667 |
+
if len(rest) < len(failures):
|
| 668 |
+
tips.append("villa's uint8 encoding (clipped to 0 to 1, times 255, truncated) leaves the map with nothing to "
|
| 669 |
+
"read, so nothing was written to preds/; the engine's own map is still in the output folder. "
|
| 670 |
+
"Check the model's output scale before reading anything.")
|
| 671 |
return " ".join(tips)
|
| 672 |
|
| 673 |
|
| 674 |
+
# ---------------------------------------------------------------- villa's names (--villa-names SEGDIR)
|
| 675 |
+
|
| 676 |
+
VILLA_DIRECTIONS = {"f": "forward", "r": "reverse"} # the variants villa has a name for; s stays in OUT
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
def _villafmt():
|
| 680 |
+
from kit import villafmt # this spelling lets the release cut find the module
|
| 681 |
+
return villafmt
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def villa_model(args):
|
| 685 |
+
"""The model name in villa's file names: --villa-model, else the checkpoint's stem as villa's folder inference
|
| 686 |
+
takes it (infer.py:1211), else the v8in snapshot folder's name."""
|
| 687 |
+
if args.villa_model:
|
| 688 |
+
return args.villa_model
|
| 689 |
+
if args.engine in ("villa", "torchscript"):
|
| 690 |
+
return Path(args.checkpoint).stem # villa: Path(checkpoint).stem, any suffix
|
| 691 |
+
if args.engine == "v8in":
|
| 692 |
+
return Path(os.path.abspath(args.model_dir)).name
|
| 693 |
+
raise InkError("--villa-names with the command engine needs --villa-model NAME: the model's name in villa's "
|
| 694 |
+
"prediction file names")
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
def villa_plan(args, shape, variants, box):
|
| 698 |
+
"""Everything --villa-names will write, checked before the model runs (InkError on a refusal): the folder, the
|
| 699 |
+
names and their directions, a crop, the render's size against SEGDIR's tifxyz canvas, its surface zarr and the
|
| 700 |
+
predictions already in preds/."""
|
| 701 |
+
vf = _villafmt()
|
| 702 |
+
segdir = Path(args.villa_names)
|
| 703 |
+
if not segdir.is_dir():
|
| 704 |
+
raise InkError(f"--villa-names {segdir}: not a folder (the segment folder that gets preds/ and "
|
| 705 |
+
"ink-detections.json)")
|
| 706 |
+
if "f" not in variants:
|
| 707 |
+
raise InkError("--villa-names writes the forward map under villa's name and registers it for VC3D; include f "
|
| 708 |
+
"in --variants")
|
| 709 |
+
n, h, w = shape
|
| 710 |
+
if tuple(box) != (0, h, 0, w):
|
| 711 |
+
raise InkError(f"--villa-names needs the whole {h} x {w} surface, not the box {list(box)}: villa's predictions "
|
| 712 |
+
"and VC3D's overlay are one image per segment, and a crop would be stretched over all of it")
|
| 713 |
+
try:
|
| 714 |
+
model = vf.model_stem(villa_model(args))
|
| 715 |
+
except vf.FormatError as exc:
|
| 716 |
+
raise InkError(f"--villa-model: {exc}") from None
|
| 717 |
+
date = args.villa_date or datetime.now().strftime(vf.PRED_DATE)
|
| 718 |
+
try:
|
| 719 |
+
ok_date = len(date) == 6 and date.isdigit() and bool(datetime.strptime(date, vf.PRED_DATE))
|
| 720 |
+
except ValueError:
|
| 721 |
+
ok_date = False
|
| 722 |
+
if not ok_date:
|
| 723 |
+
raise InkError(f"--villa-date {date!r} is not DDMMYY, the date villa's folder inference writes (infer.py:1212)")
|
| 724 |
+
seg = Path(os.path.abspath(segdir)).name
|
| 725 |
+
paths = {}
|
| 726 |
+
for v in (v for v in ("f", "r") if v in variants):
|
| 727 |
+
direction = VILLA_DIRECTIONS[v]
|
| 728 |
+
name = vf.pred_name(seg, model, direction, date)
|
| 729 |
+
parsed = vf.pred_direction(name)
|
| 730 |
+
if parsed != direction:
|
| 731 |
+
raise InkError(f"villa's merge_predictions would read {name} as {parsed!r}, not {direction!r} "
|
| 732 |
+
"(merge_predictions.py:112-118: _forward_ anywhere in the name counts first); the segment "
|
| 733 |
+
"folder or the model name holds _forward_ or _reverse_, so pass another --villa-model")
|
| 734 |
+
if name.lower().startswith(vf.PRED_MERGED):
|
| 735 |
+
raise InkError(f"{name} starts with {vf.PRED_MERGED}, which villa's merge_predictions takes for its own "
|
| 736 |
+
"output and never merges")
|
| 737 |
+
dest = segdir / "preds" / name
|
| 738 |
+
if dest.exists() and not args.villa_overwrite:
|
| 739 |
+
raise InkError(f"{dest} exists; pass --villa-overwrite to replace it")
|
| 740 |
+
paths[v] = dest
|
| 741 |
+
plan = {"segment": str(segdir), "segment_name": seg, "model": model, "date": date, "size": [w, h],
|
| 742 |
+
"paths": {v: str(p) for v, p in paths.items()}, "overwrite": bool(args.villa_overwrite),
|
| 743 |
+
"villa": vf.VILLA_PIN, "warnings": []}
|
| 744 |
+
surf = vf.villa_surface(segdir)
|
| 745 |
+
if surf["height"] is not None and (surf["height"], surf["width"]) != (h, w):
|
| 746 |
+
raise InkError(f"the render is {w} x {h} but villa would predict {surf['width']} x {surf['height']} from "
|
| 747 |
+
f"{surf['path']} (infer.py:940-952); villa's merge expects one size per segment")
|
| 748 |
+
plan["surface_zarr"] = surf["path"]
|
| 749 |
+
seg_check = vf.check_tifxyz(segdir, pixels=False) if (segdir / "meta.json").is_file() else None
|
| 750 |
+
if seg_check is not None and seg_check["ok"]:
|
| 751 |
+
meta, rows, cols, expected = vf.canvas_aspect(segdir)
|
| 752 |
+
got = w / h
|
| 753 |
+
if abs(got / expected - 1) > vf.ASPECT_TOL:
|
| 754 |
+
raise InkError(f"the render is {w} x {h} (aspect {got:.4f}) but {seg}'s {cols} x {rows} grid needs aspect "
|
| 755 |
+
f"{expected:.4f}: VC3D stretches an ink map over the whole grid "
|
| 756 |
+
"(InkDetectionOverlayController.cpp:399-437), so this render is not of this segment")
|
| 757 |
+
plan["tifxyz"] = {"grid": [rows, cols], "key": vf.segment_key(segdir, meta)}
|
| 758 |
+
else:
|
| 759 |
+
why = ("no meta.json" if seg_check is None else
|
| 760 |
+
"; ".join(e["message"] for e in seg_check["errors"]))
|
| 761 |
+
plan["tifxyz"] = None
|
| 762 |
+
plan["no_record"] = (f"{segdir} is not a loadable tifxyz segment ({why}), so no ink-detections.json record "
|
| 763 |
+
"is written: VC3D's overlay lists the records of the segment it shows")
|
| 764 |
+
plan["warnings"].append(plan["no_record"])
|
| 765 |
+
preds = segdir / "preds"
|
| 766 |
+
for p in (sorted(preds.iterdir()) if preds.is_dir() else []):
|
| 767 |
+
if not p.is_file() or p.suffix.lower() not in vf.PRED_SUFFIXES or p.stem.lower().startswith(vf.PRED_MERGED):
|
| 768 |
+
continue
|
| 769 |
+
d = vf.pred_direction(p.name)
|
| 770 |
+
mine = [v for v, q in paths.items() if VILLA_DIRECTIONS[v] == d]
|
| 771 |
+
if not mine or p == paths[mine[0]]:
|
| 772 |
+
continue
|
| 773 |
+
try:
|
| 774 |
+
pw, ph, _ = vf.image_size(p)
|
| 775 |
+
except vf.FormatError:
|
| 776 |
+
plan["warnings"].append(f"cannot read the size of {p.name} in preds/")
|
| 777 |
+
continue
|
| 778 |
+
if (pw, ph) != (w, h):
|
| 779 |
+
raise InkError(f"preds/ already holds {p.name}, a {d} prediction of {pw} x {ph}, and this map is {w} x {h}: "
|
| 780 |
+
"villa's merge_predictions stops on a shape mismatch (merge_predictions.py:330-340)")
|
| 781 |
+
if fnmatch.fnmatchcase(p.name, f"{seg}_{model}_{d}_*.tif"): # villa's skip test (infer.py:1224-1236)
|
| 782 |
+
plan["warnings"].append(f"preds/ already holds {p.name} for this model and direction: villa's folder "
|
| 783 |
+
"inference skips on either file, and merge_predictions averages all of them")
|
| 784 |
+
return plan
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
def villa_encode(raw, shape):
|
| 788 |
+
"""(uint8 map as villa's inference encodes it, None) or (None, why it cannot be). uint8 stays as it is; a float
|
| 789 |
+
map must hold probabilities (0 to 1, as villafmt's prob scale takes them) and is clipped, times 255, truncated
|
| 790 |
+
(infer.py:791-812); NaN and infinite values (off the surface: on it the run has failed already) become 0."""
|
| 791 |
+
vf = _villafmt()
|
| 792 |
+
a = np.asarray(raw)
|
| 793 |
+
if a.ndim == 3 and a.shape[0] == 1:
|
| 794 |
+
a = a[0]
|
| 795 |
+
if a.shape != tuple(shape):
|
| 796 |
+
return None, f"the map has shape {list(a.shape)} but the input surface is {list(shape)} (rows, columns)"
|
| 797 |
+
if a.dtype == np.uint8:
|
| 798 |
+
return a, None
|
| 799 |
+
if a.dtype.kind == "f":
|
| 800 |
+
finite = a[np.isfinite(a)]
|
| 801 |
+
if finite.size and (float(finite.min()) < -vf.PROB_TOL or float(finite.max()) > 1 + vf.PROB_TOL):
|
| 802 |
+
return None, (f"its values run from {float(finite.min()):g} to {float(finite.max()):g}, outside 0 to 1, so "
|
| 803 |
+
"they are not probabilities villa's encoding can keep")
|
| 804 |
+
p = probability(a)
|
| 805 |
+
p = np.nan_to_num(p.astype(np.float32), nan=0.0, posinf=0.0, neginf=0.0)
|
| 806 |
+
np.clip(p, 0, 1, out=p)
|
| 807 |
+
p *= 255
|
| 808 |
+
return p.astype(np.uint8), None
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
def is_villa_tiff(path):
|
| 812 |
+
"""True for a uint8 single-sample tiled LZW Big TIFF, the file villa's inference writes (infer.py:815-834)."""
|
| 813 |
+
vf = _villafmt()
|
| 814 |
+
try:
|
| 815 |
+
info = vf.tiff_info(path)
|
| 816 |
+
except vf.FormatError:
|
| 817 |
+
return False
|
| 818 |
+
return (info["dtype"] == "uint8" and info["samples"] == 1 and info["compression"] == 5 and info["tiled"]
|
| 819 |
+
and info["bigtiff"])
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
def _move_into(src, dest):
|
| 823 |
+
"""Move src to dest whole: through a hidden .part name no villa tool picks up (merge_predictions.py:30 takes .png,
|
| 824 |
+
.tif and .tiff), then one rename, so a stopped run leaves no half file under villa's name."""
|
| 825 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 826 |
+
part = dest.with_name(f".{dest.name}.part")
|
| 827 |
+
try:
|
| 828 |
+
os.replace(src, part)
|
| 829 |
+
except OSError: # another file system
|
| 830 |
+
shutil.copyfile(src, part)
|
| 831 |
+
os.unlink(src)
|
| 832 |
+
os.replace(part, dest)
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
def publish_villa(plan, maps, raws, enc, tmp, engine_name, files):
|
| 836 |
+
"""Write the encoded maps under villa's names (the reversed control first, so a stop between the two never leaves
|
| 837 |
+
a forward map without its control) and register the forward map in SEGDIR/ink-detections.json. Each file written
|
| 838 |
+
goes into files (the caller's dict, so a later refusal still shows what was written). Returns the registration;
|
| 839 |
+
InkError when villafmt refuses a file."""
|
| 840 |
+
vf = _villafmt()
|
| 841 |
+
segdir = Path(plan["segment"])
|
| 842 |
+
for v in (v for v in ("r", "f") if v in enc):
|
| 843 |
+
dest = Path(plan["paths"][v])
|
| 844 |
+
src = Path(maps[v])
|
| 845 |
+
rec = {"path": str(dest), "name": dest.name, "direction": VILLA_DIRECTIONS[v]}
|
| 846 |
+
if is_villa_tiff(src):
|
| 847 |
+
_move_into(src, dest)
|
| 848 |
+
rec["how"] = "villa's own file, moved in byte for byte"
|
| 849 |
+
else:
|
| 850 |
+
# villafmt reads the map as ink.py read it (a .npy as it is, anything else saved here as a .npy first)
|
| 851 |
+
raw = np.squeeze(np.asarray(raws[v]))
|
| 852 |
+
as_is = raw.dtype == np.uint8 or (raw.dtype.kind == "f" and bool(np.isfinite(raw).all()))
|
| 853 |
+
scale = "u8" if raw.dtype == np.uint8 or not as_is else "prob"
|
| 854 |
+
if as_is and src.suffix.lower() == ".npy":
|
| 855 |
+
source = src
|
| 856 |
+
else:
|
| 857 |
+
tmp.mkdir(parents=True, exist_ok=True)
|
| 858 |
+
source = tmp / f"ink_{v}.npy"
|
| 859 |
+
np.save(source, raw if as_is else enc[v])
|
| 860 |
+
if not as_is:
|
| 861 |
+
rec["encoded_here"] = ("the map was encoded here first (NaN or infinite values off the surface set to "
|
| 862 |
+
f"0, or a {raw.dtype} map taken as a probability)")
|
| 863 |
+
try:
|
| 864 |
+
rep = vf.export_pred(source, segdir, plan["model"], VILLA_DIRECTIONS[v], scale=scale, date=plan["date"],
|
| 865 |
+
overwrite=plan["overwrite"])
|
| 866 |
+
except vf.FormatError as exc:
|
| 867 |
+
raise InkError(f"villafmt preds export refused the {NAMES[v]}: {exc}") from None
|
| 868 |
+
if not rep["ok"] or Path(rep["file"]) != dest:
|
| 869 |
+
why = "; ".join(e["message"] for e in rep["errors"]) or f"it wrote {rep['file']}, not {dest}"
|
| 870 |
+
raise InkError(f"villafmt preds export refused the {NAMES[v]}: {why}")
|
| 871 |
+
rec.update(how=f"villafmt preds export, scale {scale}", engine_file=str(src),
|
| 872 |
+
encoding=rep["encoding"], scale=rep["scale"],
|
| 873 |
+
warnings=[e["message"] for e in rep["warnings"]])
|
| 874 |
+
files[v] = rec
|
| 875 |
+
registered = None
|
| 876 |
+
if "f" in files and plan["tifxyz"] is not None:
|
| 877 |
+
try:
|
| 878 |
+
rep = vf.add_inkmap(segdir, files["f"]["path"], extra={
|
| 879 |
+
"producer": "scripts/vc3d/ink.py --villa-names", "engine": engine_name, "variant": "f",
|
| 880 |
+
"reverse_control": files.get("r", {}).get("name")})
|
| 881 |
+
except vf.FormatError as exc:
|
| 882 |
+
raise InkError(f"registering the forward map in ink-detections.json: {exc}") from None
|
| 883 |
+
if not rep["ok"]:
|
| 884 |
+
raise InkError("registering the forward map in ink-detections.json: " +
|
| 885 |
+
"; ".join(e["message"] for e in rep["errors"]))
|
| 886 |
+
registered = {"file": rep["file"], "records": rep["records"], "record": rep["record"]}
|
| 887 |
+
elif "f" in files:
|
| 888 |
+
registered = {"skipped": plan["no_record"]}
|
| 889 |
+
return registered
|
| 890 |
+
|
| 891 |
+
|
| 892 |
# ---------------------------------------------------------------- main
|
| 893 |
|
| 894 |
def run(args):
|
|
|
|
| 904 |
stack = open_stack(args.input)
|
| 905 |
box = tuple(int(v) for v in args.box.split(",")) if args.box else None
|
| 906 |
a, b, box = window(stack.shape, args.layer_start, args.layer_end, box)
|
| 907 |
+
plan = villa_plan(args, stack.shape, variants, box) if args.villa_names else None # refusals before the model
|
| 908 |
log(f"input {args.input}: {list(stack.shape)} layers x rows x cols; window layers [{a}, {b}), box {list(box)}; "
|
| 909 |
f"engine {engine.name} on {engine.device}")
|
| 910 |
maps, notes = {}, {}
|
|
|
|
| 925 |
if not args.keep_work and work.exists():
|
| 926 |
shutil.rmtree(work, ignore_errors=True)
|
| 927 |
mask = surface_mask(args.input, a, b, box)
|
| 928 |
+
raws = {v: read_image(p) for v, p in maps.items()}
|
| 929 |
+
probs = {v: probability(r) for v, r in raws.items()}
|
| 930 |
failures = unreadable(probs, mask)
|
| 931 |
+
villa = None
|
| 932 |
+
if plan is not None:
|
| 933 |
+
villa, failures = villa_step(plan, maps, raws, probs, mask, failures, out, engine.name)
|
| 934 |
summary = {"engine": engine.describe(), "input": str(args.input), "window": {"layers": [a, b], "box": list(box)},
|
| 935 |
"variants": variants, "seed": args.seed, "prepared": notes,
|
| 936 |
"status": "failed" if failures else "ok", "failures": failures,
|
|
|
|
| 940 |
"seconds": round(time.time() - started, 1),
|
| 941 |
"note": "model output, not a reading; a forward map that keeps its blobs under the controls is "
|
| 942 |
"not responding to ink in depth order"}
|
| 943 |
+
if villa is not None:
|
| 944 |
+
summary["villa_names"] = villa
|
| 945 |
+
for v, rec in (villa.get("files") or {}).items():
|
| 946 |
+
summary["maps"][v].update(villa_name=rec["name"], engine_file=rec.get("engine_file"))
|
| 947 |
(out / "ink.json").write_text(json.dumps(summary, indent=1))
|
| 948 |
log(f"done in {summary['seconds']} s: " + ", ".join(
|
| 949 |
f"{v} above 0.5: {summary['maps'][v]['stats'].get('above_threshold')}" for v in maps))
|
| 950 |
if failures:
|
| 951 |
raise UnreadableMaps("the maps cannot be read (status failed in ink.json): " + "; ".join(failures) + ". " +
|
| 952 |
advice(failures), summary)
|
| 953 |
+
if villa is not None and villa["errors"]:
|
| 954 |
+
raise InkError("--villa-names: " + "; ".join(villa["errors"]) + f" ({villa.get('why_not', '')})")
|
| 955 |
+
if villa is not None:
|
| 956 |
+
reg = villa["registered"] or {}
|
| 957 |
+
log(f"villa's names: {', '.join(rec['name'] for rec in villa['files'].values())} in {plan['segment']}/preds; "
|
| 958 |
+
+ (f"forward map registered in {reg['file']}" if reg.get("file") else f"not registered: {reg.get('skipped')}"))
|
| 959 |
return summary
|
| 960 |
|
| 961 |
|
| 962 |
+
def villa_step(plan, maps, raws, probs, mask, failures, out, engine_name):
|
| 963 |
+
"""--villa-names once the maps are made: encode the forward map and the reversed control as villa's uint8, test
|
| 964 |
+
the encoded maps as any map is tested, then publish and register them. Updates maps and probs to the files
|
| 965 |
+
written. Returns (the record for ink.json, the run's failures). Nothing reaches preds/ from a run whose maps
|
| 966 |
+
cannot be read, before or after the encoding."""
|
| 967 |
+
villa = {k: plan[k] for k in ("segment", "segment_name", "model", "date", "paths", "surface_zarr", "tifxyz",
|
| 968 |
+
"warnings", "villa")}
|
| 969 |
+
villa.update(published=False, errors=[], files={}, registered=None)
|
| 970 |
+
if failures:
|
| 971 |
+
villa["why_not"] = "the maps cannot be read (status failed); nothing was written to preds/"
|
| 972 |
+
return villa, failures
|
| 973 |
+
w, h = plan["size"]
|
| 974 |
+
enc = {}
|
| 975 |
+
for v in (v for v in VILLA_DIRECTIONS if v in raws):
|
| 976 |
+
e, why = villa_encode(raws[v], (h, w))
|
| 977 |
+
if why:
|
| 978 |
+
villa["errors"].append(f"the {NAMES[v]}: {why}")
|
| 979 |
+
else:
|
| 980 |
+
enc[v] = e
|
| 981 |
+
if villa["errors"]:
|
| 982 |
+
villa["why_not"] = "a map cannot be written as villa's prediction; nothing was written to preds/"
|
| 983 |
+
return villa, failures
|
| 984 |
+
encoded = {v: e.astype(np.float32) / 255.0 for v, e in enc.items()}
|
| 985 |
+
lost = unreadable({**probs, **encoded}, mask)
|
| 986 |
+
if lost:
|
| 987 |
+
villa["why_not"] = "a map holds nothing once encoded as villa's uint8; nothing was written to preds/"
|
| 988 |
+
return villa, [r + ENCODED for r in lost]
|
| 989 |
+
tmp = Path(tempfile.mkdtemp(prefix=".kit-ink-villa-", dir=out))
|
| 990 |
+
try:
|
| 991 |
+
villa["registered"] = publish_villa(plan, maps, raws, enc, tmp, engine_name, villa["files"])
|
| 992 |
+
except InkError as exc:
|
| 993 |
+
villa["errors"].append(str(exc))
|
| 994 |
+
villa["why_not"] = ("villa's names were not all written: files lists those that were" if villa["files"] else
|
| 995 |
+
"nothing was written to preds/")
|
| 996 |
+
finally:
|
| 997 |
+
shutil.rmtree(tmp, ignore_errors=True)
|
| 998 |
+
maps.update({v: Path(rec["path"]) for v, rec in villa["files"].items()}) # where each map now is
|
| 999 |
+
if not villa["errors"]:
|
| 1000 |
+
villa["published"] = True
|
| 1001 |
+
probs.update(encoded)
|
| 1002 |
+
return villa, failures
|
| 1003 |
+
|
| 1004 |
+
|
| 1005 |
def parse_args(argv=None):
|
| 1006 |
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 1007 |
p.add_argument("--input", required=True, help="surface volume: zarr or layer folder")
|
|
|
|
| 1009 |
p.add_argument("--variants", default="f,r", help="comma list of f, r, s (default f,r)")
|
| 1010 |
p.add_argument("--engine", required=True, choices=sorted(ENGINES))
|
| 1011 |
p.add_argument("--checkpoint", help="villa .pth or TorchScript .pt")
|
| 1012 |
+
p.add_argument("--checkpoint-sha256", help="refuse a checkpoint whose sha256 is not this (checked right before "
|
| 1013 |
+
"the load, on the bytes loaded for villa)")
|
| 1014 |
p.add_argument("--model-dir", help="v8in snapshot")
|
| 1015 |
p.add_argument("--command-json", help="command engine: JSON argv with {input} or {layers}, {output}, "
|
| 1016 |
"{reverse} and {device}")
|
|
|
|
| 1023 |
p.add_argument("--stride", type=int)
|
| 1024 |
p.add_argument("--seed", type=int, default=SEED, help="depth-shuffle seed")
|
| 1025 |
p.add_argument("--keep-work", action="store_true", help="keep the converted inputs under OUT/work")
|
| 1026 |
+
p.add_argument("--villa-names", metavar="SEGDIR", help="write the forward map and the reversed control into "
|
| 1027 |
+
"SEGDIR/preds/ under villa's prediction names as uint8 0 to 255, and register the forward map in "
|
| 1028 |
+
"SEGDIR/ink-detections.json for VC3D's Ink Detection overlay")
|
| 1029 |
+
p.add_argument("--villa-model", metavar="NAME", help="the model name in villa's file names (default: the "
|
| 1030 |
+
"checkpoint's stem, or the v8in snapshot folder's name; required for the command engine)")
|
| 1031 |
+
p.add_argument("--villa-date", metavar="DDMMYY", help="the date in villa's file names (default: today, as villa "
|
| 1032 |
+
"writes it)")
|
| 1033 |
+
p.add_argument("--villa-overwrite", action="store_true", help="replace a prediction already at villa's name")
|
| 1034 |
return p.parse_args(argv)
|
| 1035 |
|
| 1036 |
|