anonslide 0.1.0b1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- anonslide/__init__.py +23 -0
- anonslide/__main__.py +3 -0
- anonslide/api.py +44 -0
- anonslide/cli.py +77 -0
- anonslide/exceptions.py +21 -0
- anonslide/formats/__init__.py +1 -0
- anonslide/formats/mirax/__init__.py +12 -0
- anonslide/formats/mirax/manager.py +193 -0
- anonslide/formats/mirax/mirax_composite.py +185 -0
- anonslide/formats/mirax/mirax_ini.py +107 -0
- anonslide/formats/mirax/mirax_label_patcher.py +225 -0
- anonslide/formats/mirax/mirax_parser.py +365 -0
- anonslide/formats/mirax/mirax_renamer.py +115 -0
- anonslide/formats/mirax/mirax_slide_model.py +107 -0
- anonslide/formats/mirax/transaction.py +72 -0
- anonslide/labels/__init__.py +3 -0
- anonslide/labels/fonts/JetBrainsMonoNLNerdFontPropo-Regular.ttf +0 -0
- anonslide/labels/fonts/OFL.txt +93 -0
- anonslide/labels/labels.py +202 -0
- anonslide/managers/__init__.py +4 -0
- anonslide/managers/factory.py +63 -0
- anonslide/managers/slide_manager.py +32 -0
- anonslide/models/__init__.py +4 -0
- anonslide/models/result.py +13 -0
- anonslide/models/slide_model.py +40 -0
- anonslide/py.typed +0 -0
- anonslide-0.1.0b1.dist-info/METADATA +177 -0
- anonslide-0.1.0b1.dist-info/RECORD +32 -0
- anonslide-0.1.0b1.dist-info/WHEEL +4 -0
- anonslide-0.1.0b1.dist-info/entry_points.txt +3 -0
- anonslide-0.1.0b1.dist-info/licenses/LICENSE +21 -0
- anonslide-0.1.0b1.dist-info/licenses/src/anonslide/labels/fonts/OFL.txt +93 -0
anonslide/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Pseudonymize whole-slide images without rescanning."""
|
|
2
|
+
|
|
3
|
+
from anonslide.api import anonymize_slide
|
|
4
|
+
from anonslide.exceptions import (
|
|
5
|
+
AnonslideError,
|
|
6
|
+
SlideCollisionError,
|
|
7
|
+
SlideProcessingError,
|
|
8
|
+
SlideValidationError,
|
|
9
|
+
UnsupportedSlideFormatError,
|
|
10
|
+
)
|
|
11
|
+
from anonslide.labels import LabelStyle
|
|
12
|
+
from anonslide.models import AnonymizationResult
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"AnonslideError",
|
|
16
|
+
"AnonymizationResult",
|
|
17
|
+
"LabelStyle",
|
|
18
|
+
"SlideCollisionError",
|
|
19
|
+
"SlideProcessingError",
|
|
20
|
+
"SlideValidationError",
|
|
21
|
+
"UnsupportedSlideFormatError",
|
|
22
|
+
"anonymize_slide",
|
|
23
|
+
]
|
anonslide/__main__.py
ADDED
anonslide/api.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""High-level programmer API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from anonslide.labels import LabelStyle
|
|
8
|
+
from anonslide.managers import SlideManagerFactory
|
|
9
|
+
from anonslide.models import AnonymizationResult
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def anonymize_slide(
|
|
13
|
+
slide_path: str | Path,
|
|
14
|
+
new_slide_name: str,
|
|
15
|
+
label_info: dict[str, str],
|
|
16
|
+
*,
|
|
17
|
+
label_style: LabelStyle | None = None,
|
|
18
|
+
) -> AnonymizationResult:
|
|
19
|
+
"""Pseudonymize a supported slide in place.
|
|
20
|
+
|
|
21
|
+
This operation is destructive. Keep an independent backup of the original
|
|
22
|
+
slide before calling it. MIRAX XML sidecars are removed, while ``SLIDE_ID``
|
|
23
|
+
and ``BARCODE_VALUE`` are retained according to the MIRAX policy.
|
|
24
|
+
"""
|
|
25
|
+
if not isinstance(label_info, dict) or not all(
|
|
26
|
+
isinstance(key, str) and isinstance(value, str)
|
|
27
|
+
for key, value in label_info.items()
|
|
28
|
+
):
|
|
29
|
+
raise TypeError("label_info must be a dictionary of string keys and values")
|
|
30
|
+
if label_style is not None and not isinstance(label_style, LabelStyle):
|
|
31
|
+
raise TypeError("label_style must be a LabelStyle or None")
|
|
32
|
+
|
|
33
|
+
factory = SlideManagerFactory()
|
|
34
|
+
manager = factory.create_manager(Path(slide_path))
|
|
35
|
+
model = manager.anonymize(
|
|
36
|
+
new_slide_name=new_slide_name,
|
|
37
|
+
label_info=label_info,
|
|
38
|
+
label_style=label_style,
|
|
39
|
+
)
|
|
40
|
+
return AnonymizationResult(
|
|
41
|
+
slide_path=model.file_path,
|
|
42
|
+
format=manager.slide_format,
|
|
43
|
+
warnings=tuple(getattr(manager, "warnings", ())),
|
|
44
|
+
)
|
anonslide/cli.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Command-line interface for anonslide."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
9
|
+
|
|
10
|
+
from anonslide.api import anonymize_slide
|
|
11
|
+
from anonslide.exceptions import AnonslideError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _package_version() -> str:
|
|
15
|
+
try:
|
|
16
|
+
return version("anonslide")
|
|
17
|
+
except PackageNotFoundError:
|
|
18
|
+
return "unknown"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
22
|
+
parser = argparse.ArgumentParser(
|
|
23
|
+
prog="anonslide",
|
|
24
|
+
description="Pseudonymize a MIRAX whole-slide image in place.",
|
|
25
|
+
epilog=(
|
|
26
|
+
"WARNING: this modifies the slide destructively and removes its optional "
|
|
27
|
+
"XML sidecar. Keep an independent backup. Repeat --label to add rows."
|
|
28
|
+
),
|
|
29
|
+
)
|
|
30
|
+
parser.add_argument("slide_path", help="path to the .mrxs slide")
|
|
31
|
+
parser.add_argument(
|
|
32
|
+
"--new-name", required=True, help="new filename stem and SLIDE_NAME pseudonym"
|
|
33
|
+
)
|
|
34
|
+
parser.add_argument(
|
|
35
|
+
"--label",
|
|
36
|
+
action="append",
|
|
37
|
+
default=[],
|
|
38
|
+
metavar="KEY=VALUE",
|
|
39
|
+
help="label row; repeat in the desired top-to-bottom order",
|
|
40
|
+
)
|
|
41
|
+
parser.add_argument(
|
|
42
|
+
"--version", action="version", version=f"%(prog)s {_package_version()}"
|
|
43
|
+
)
|
|
44
|
+
return parser
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _parse_labels(items: list[str]) -> dict[str, str]:
|
|
48
|
+
labels: dict[str, str] = {}
|
|
49
|
+
for item in items:
|
|
50
|
+
key, separator, value = item.partition("=")
|
|
51
|
+
if not separator or not key.strip() or not value.strip():
|
|
52
|
+
raise ValueError(f"Invalid --label {item!r}; expected non-empty KEY=VALUE")
|
|
53
|
+
key = key.strip()
|
|
54
|
+
if key in labels:
|
|
55
|
+
raise ValueError(f"Duplicate label key: {key}")
|
|
56
|
+
labels[key] = value.strip()
|
|
57
|
+
return labels
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
61
|
+
parser = build_parser()
|
|
62
|
+
arguments = parser.parse_args(argv)
|
|
63
|
+
try:
|
|
64
|
+
labels = _parse_labels(arguments.label)
|
|
65
|
+
result = anonymize_slide(
|
|
66
|
+
slide_path=arguments.slide_path,
|
|
67
|
+
new_slide_name=arguments.new_name,
|
|
68
|
+
label_info=labels,
|
|
69
|
+
)
|
|
70
|
+
except (AnonslideError, OSError, ValueError) as error:
|
|
71
|
+
print(f"anonslide: error: {error}", file=sys.stderr)
|
|
72
|
+
return 1
|
|
73
|
+
|
|
74
|
+
for warning in result.warnings:
|
|
75
|
+
print(f"anonslide: warning: {warning}", file=sys.stderr)
|
|
76
|
+
print(result.slide_path)
|
|
77
|
+
return 0
|
anonslide/exceptions.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Public exceptions raised by anonslide."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class AnonslideError(Exception):
|
|
5
|
+
"""Base class for anonslide errors."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class UnsupportedSlideFormatError(AnonslideError, ValueError):
|
|
9
|
+
"""Raised when no manager supports the supplied slide."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class SlideValidationError(AnonslideError, ValueError):
|
|
13
|
+
"""Raised when a slide or requested pseudonym is invalid."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class SlideCollisionError(AnonslideError, FileExistsError):
|
|
17
|
+
"""Raised when anonymization would overwrite an existing path."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class SlideProcessingError(AnonslideError, RuntimeError):
|
|
21
|
+
"""Raised when a slide cannot be processed safely."""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Format-specific slide implementations."""
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from .manager import MiraxSlideManager
|
|
2
|
+
from .mirax_label_patcher import MiraxLabelPatcher
|
|
3
|
+
from .mirax_parser import MiraxSlideParser
|
|
4
|
+
from .mirax_slide_model import MiraxAssociatedImage, MiraxSlideModel
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"MiraxAssociatedImage",
|
|
8
|
+
"MiraxLabelPatcher",
|
|
9
|
+
"MiraxSlideManager",
|
|
10
|
+
"MiraxSlideModel",
|
|
11
|
+
"MiraxSlideParser",
|
|
12
|
+
]
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""High-level MIRAX slide pseudonymization workflow."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from io import BytesIO
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from openslide import OpenSlide, OpenSlideError
|
|
9
|
+
from PIL import Image
|
|
10
|
+
from pydantic import ValidationError
|
|
11
|
+
|
|
12
|
+
from anonslide.exceptions import SlideProcessingError, SlideValidationError
|
|
13
|
+
from anonslide.labels import LabelStyle, make_image_with_info
|
|
14
|
+
from anonslide.managers.slide_manager import SlideManager
|
|
15
|
+
|
|
16
|
+
from . import mirax_ini, mirax_renamer
|
|
17
|
+
from .mirax_composite import create_sanitized_composite
|
|
18
|
+
from .mirax_label_patcher import MiraxLabelPatcher
|
|
19
|
+
from .mirax_parser import MiraxSlideParser
|
|
20
|
+
from .mirax_slide_model import MiraxCompositeImage, MiraxSlideModel
|
|
21
|
+
from .transaction import MiraxMutationTransaction
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class MiraxSlideManager(SlideManager):
|
|
25
|
+
"""Destructively pseudonymize a MIRAX bundle with rollback backups."""
|
|
26
|
+
|
|
27
|
+
slide_format = "mrxs"
|
|
28
|
+
aliases = ("mirax",)
|
|
29
|
+
|
|
30
|
+
def __init__(self, path: Path) -> None:
|
|
31
|
+
self.path = Path(path)
|
|
32
|
+
self.warnings: list[str] = []
|
|
33
|
+
if self.path.suffix.lower() != ".mrxs":
|
|
34
|
+
raise SlideValidationError("MIRAX slides must have a .mrxs filename")
|
|
35
|
+
try:
|
|
36
|
+
self.model = MiraxSlideModel(file_path=self.path, vendor="MIRAX")
|
|
37
|
+
if self.model.format != "mirax":
|
|
38
|
+
raise SlideValidationError(
|
|
39
|
+
f"OpenSlide did not detect MIRAX: {self.path}"
|
|
40
|
+
)
|
|
41
|
+
except (ValidationError, ValueError, OSError) as error:
|
|
42
|
+
raise SlideValidationError(
|
|
43
|
+
f"Could not load MIRAX slide: {self.path}"
|
|
44
|
+
) from error
|
|
45
|
+
|
|
46
|
+
def slide_info(self) -> MiraxSlideModel:
|
|
47
|
+
"""Return the current validated model without printing identifiers."""
|
|
48
|
+
return self.model
|
|
49
|
+
|
|
50
|
+
def anonymize(
|
|
51
|
+
self,
|
|
52
|
+
new_slide_name: str,
|
|
53
|
+
label_info: dict[str, str],
|
|
54
|
+
*,
|
|
55
|
+
label_style: LabelStyle | None = None,
|
|
56
|
+
) -> MiraxSlideModel:
|
|
57
|
+
"""Pseudonymize this slide in place and return its renamed model."""
|
|
58
|
+
self.warnings = []
|
|
59
|
+
mirax_renamer.preflight_rename(self.model, new_slide_name)
|
|
60
|
+
if not isinstance(label_info, dict) or not all(
|
|
61
|
+
isinstance(key, str) and isinstance(value, str)
|
|
62
|
+
for key, value in label_info.items()
|
|
63
|
+
):
|
|
64
|
+
raise TypeError("label_info must be a dictionary of string keys and values")
|
|
65
|
+
if label_style is None:
|
|
66
|
+
label_style = LabelStyle()
|
|
67
|
+
elif not isinstance(label_style, LabelStyle):
|
|
68
|
+
raise TypeError("label_style must be a LabelStyle or None")
|
|
69
|
+
|
|
70
|
+
with MiraxMutationTransaction(self.model.parent_dir_path) as transaction:
|
|
71
|
+
with MiraxSlideParser(self.model) as parser:
|
|
72
|
+
candidates, append_required = self._prepare_image_replacements(
|
|
73
|
+
parser, label_info, label_style
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
for kind in candidates:
|
|
77
|
+
transaction.backup_file(parser.get_associated_image(kind).dat_path)
|
|
78
|
+
transaction.backup_file(parser.index_path)
|
|
79
|
+
transaction.backup_file(self.model.slidedat_ini_path)
|
|
80
|
+
xml_path = self.model.xml_file_path
|
|
81
|
+
if xml_path is not None:
|
|
82
|
+
transaction.backup_file(xml_path)
|
|
83
|
+
|
|
84
|
+
for kind, image_bytes in candidates.items():
|
|
85
|
+
patcher = MiraxLabelPatcher(parser, kind)
|
|
86
|
+
if append_required[kind]:
|
|
87
|
+
patcher.patch_append_repoint(image_bytes, wipe_original=True)
|
|
88
|
+
else:
|
|
89
|
+
patcher.patch_inplace(image_bytes)
|
|
90
|
+
|
|
91
|
+
mirax_ini.update_slide_name(self.model.slidedat_ini_path, new_slide_name)
|
|
92
|
+
expected_name = mirax_ini.sanitise(new_slide_name)
|
|
93
|
+
if (
|
|
94
|
+
mirax_ini.get_current_slide_name(self.model.slidedat_ini_path)
|
|
95
|
+
!= expected_name
|
|
96
|
+
):
|
|
97
|
+
raise SlideProcessingError(
|
|
98
|
+
"Could not verify the updated MIRAX SLIDE_NAME"
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
self._verify_patched_images(candidates)
|
|
102
|
+
self._verify_openslide()
|
|
103
|
+
|
|
104
|
+
if xml_path is not None:
|
|
105
|
+
xml_path.unlink()
|
|
106
|
+
self.model = mirax_renamer.rename_mrxs_files(self.model, new_slide_name)
|
|
107
|
+
|
|
108
|
+
return self.model
|
|
109
|
+
|
|
110
|
+
def _prepare_image_replacements(
|
|
111
|
+
self,
|
|
112
|
+
parser: MiraxSlideParser,
|
|
113
|
+
label_info: dict[str, str],
|
|
114
|
+
label_style: LabelStyle,
|
|
115
|
+
) -> tuple[dict[str, bytes], dict[str, bool]]:
|
|
116
|
+
"""Render and validate every candidate before the first slide write."""
|
|
117
|
+
candidates: dict[str, bytes] = {}
|
|
118
|
+
append_required: dict[str, bool] = {}
|
|
119
|
+
|
|
120
|
+
label_record = parser.get_associated_image("label")
|
|
121
|
+
if label_record is not None:
|
|
122
|
+
current_blob = parser.read_image_bytes("label")
|
|
123
|
+
with Image.open(BytesIO(current_blob)) as current_image:
|
|
124
|
+
current_image.load()
|
|
125
|
+
image_format = current_image.format
|
|
126
|
+
width, height = current_image.size
|
|
127
|
+
replacement = make_image_with_info(
|
|
128
|
+
width=width,
|
|
129
|
+
height=height,
|
|
130
|
+
info=label_info,
|
|
131
|
+
style=label_style,
|
|
132
|
+
)
|
|
133
|
+
candidates["label"] = self._encode_image(replacement, image_format)
|
|
134
|
+
else:
|
|
135
|
+
self.warnings.append("No standalone MIRAX label record was present")
|
|
136
|
+
|
|
137
|
+
composite_record = parser.get_associated_image("composite")
|
|
138
|
+
if isinstance(composite_record, MiraxCompositeImage):
|
|
139
|
+
region = composite_record.barcode_region
|
|
140
|
+
replacement = make_image_with_info(
|
|
141
|
+
width=region.width,
|
|
142
|
+
height=region.height,
|
|
143
|
+
info=label_info,
|
|
144
|
+
style=label_style,
|
|
145
|
+
)
|
|
146
|
+
candidates["composite"] = create_sanitized_composite(parser, replacement)
|
|
147
|
+
elif composite_record is not None:
|
|
148
|
+
raise SlideProcessingError("MIRAX composite barcode metadata is incomplete")
|
|
149
|
+
else:
|
|
150
|
+
self.warnings.append("No MIRAX whole-slide composite record was present")
|
|
151
|
+
|
|
152
|
+
for kind, image_bytes in candidates.items():
|
|
153
|
+
patcher = MiraxLabelPatcher(parser, kind)
|
|
154
|
+
append_required[kind] = patcher.validate_replacement(
|
|
155
|
+
image_bytes, allow_append=True
|
|
156
|
+
)
|
|
157
|
+
return candidates, append_required
|
|
158
|
+
|
|
159
|
+
@staticmethod
|
|
160
|
+
def _encode_image(image: Image.Image, image_format: str | None) -> bytes:
|
|
161
|
+
"""Encode a replacement using the source associated-image format."""
|
|
162
|
+
if image_format not in {"JPEG", "PNG"}:
|
|
163
|
+
raise SlideProcessingError(
|
|
164
|
+
f"Unsupported standalone label image format: {image_format!r}"
|
|
165
|
+
)
|
|
166
|
+
output = BytesIO()
|
|
167
|
+
rgb_image = image.convert("RGB")
|
|
168
|
+
if image_format == "JPEG":
|
|
169
|
+
rgb_image.save(output, format="JPEG", quality=85, optimize=True)
|
|
170
|
+
else:
|
|
171
|
+
rgb_image.save(output, format="PNG", optimize=True)
|
|
172
|
+
return output.getvalue()
|
|
173
|
+
|
|
174
|
+
def _verify_patched_images(self, candidates: dict[str, bytes]) -> None:
|
|
175
|
+
"""Re-resolve each record and verify the candidate bytes were written."""
|
|
176
|
+
with MiraxSlideParser(self.model) as parser:
|
|
177
|
+
for kind, expected in candidates.items():
|
|
178
|
+
actual = parser.read_image_bytes(kind)
|
|
179
|
+
if not actual.startswith(expected):
|
|
180
|
+
raise SlideProcessingError(
|
|
181
|
+
f"Could not verify the patched MIRAX {kind} image"
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
def _verify_openslide(self) -> None:
|
|
185
|
+
"""Open the mutated slide and load its associated-image mapping."""
|
|
186
|
+
try:
|
|
187
|
+
with OpenSlide(self.model.file_path) as slide:
|
|
188
|
+
_ = slide.dimensions
|
|
189
|
+
_ = slide.associated_images
|
|
190
|
+
except (OSError, ValueError, OpenSlideError) as error:
|
|
191
|
+
raise SlideProcessingError(
|
|
192
|
+
"The patched MIRAX slide could not be reopened with OpenSlide"
|
|
193
|
+
) from error
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Sanitize the barcode area of a MIRAX whole-slide composite image.
|
|
2
|
+
|
|
3
|
+
This module only reads records and creates new image bytes. It never writes
|
|
4
|
+
to a slide. A caller can persist the returned bytes with
|
|
5
|
+
``MiraxLabelPatcher(parser, "composite")`` after all other validation passes.
|
|
6
|
+
|
|
7
|
+
The supported MIRAX layout stores the composite barcode upside down relative
|
|
8
|
+
to the standalone SlideBarcode image. Its INI rectangle has inclusive right
|
|
9
|
+
and bottom edges. Both conventions were verified by comparing the two image
|
|
10
|
+
records without modifying the source slide.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from io import BytesIO
|
|
14
|
+
|
|
15
|
+
from PIL import Image
|
|
16
|
+
|
|
17
|
+
from anonslide.exceptions import SlideProcessingError
|
|
18
|
+
|
|
19
|
+
from .mirax_parser import MiraxSlideParser
|
|
20
|
+
from .mirax_slide_model import MiraxBarcodeRegion, MiraxCompositeImage
|
|
21
|
+
|
|
22
|
+
_SUPPORTED_FORMATS = {"JPEG", "PNG"}
|
|
23
|
+
_COMPOSITE_BARCODE_ROTATION = 180
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class MiraxCompositeError(SlideProcessingError):
|
|
27
|
+
"""Raised when a whole-slide composite cannot be sanitized safely."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def create_sanitized_composite(
|
|
31
|
+
slide: MiraxSlideParser, replacement_label: Image.Image
|
|
32
|
+
) -> bytes:
|
|
33
|
+
"""Return composite bytes with the declared barcode region replaced.
|
|
34
|
+
|
|
35
|
+
The replacement must have the same dimensions as the declared barcode
|
|
36
|
+
region. It is rotated 180 degrees to match the composite's orientation.
|
|
37
|
+
No slide files are modified.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
slide: An open MIRAX parser.
|
|
41
|
+
replacement_label: The sanitized, upright PIL label image.
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
A complete JPEG or PNG image in the composite's original format.
|
|
45
|
+
|
|
46
|
+
Raises:
|
|
47
|
+
MiraxCompositeError: If the record is absent or its image/metadata are
|
|
48
|
+
inconsistent or unsupported.
|
|
49
|
+
MiraxParseError: If the underlying MIRAX records cannot be read.
|
|
50
|
+
"""
|
|
51
|
+
info = slide.get_associated_image("composite")
|
|
52
|
+
if info is None:
|
|
53
|
+
raise MiraxCompositeError(
|
|
54
|
+
"This slide has no 'composite' associated image to sanitize"
|
|
55
|
+
)
|
|
56
|
+
if not isinstance(info, MiraxCompositeImage):
|
|
57
|
+
raise MiraxCompositeError(
|
|
58
|
+
"The composite record does not contain its required barcode metadata"
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
image_bytes = slide.read_image_bytes("composite")
|
|
62
|
+
return replace_barcode_region(
|
|
63
|
+
image_bytes,
|
|
64
|
+
info.barcode_region,
|
|
65
|
+
replacement_label,
|
|
66
|
+
image_format=info.image_format,
|
|
67
|
+
expected_size=(info.declared_width, info.declared_height),
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def replace_barcode_region(
|
|
72
|
+
image_bytes: bytes,
|
|
73
|
+
barcode_region: MiraxBarcodeRegion,
|
|
74
|
+
replacement_label: Image.Image,
|
|
75
|
+
*,
|
|
76
|
+
image_format: str | None = None,
|
|
77
|
+
expected_size: tuple[int, int] | None = None,
|
|
78
|
+
) -> bytes:
|
|
79
|
+
"""Replace an inclusive barcode rectangle in complete JPEG/PNG bytes.
|
|
80
|
+
|
|
81
|
+
Pixels outside the rectangle are not edited. JPEG output necessarily
|
|
82
|
+
undergoes lossy re-encoding, while PNG output preserves those outside
|
|
83
|
+
pixels exactly. Dimensions and the encoded image format are preserved.
|
|
84
|
+
Metadata is not copied into the new image.
|
|
85
|
+
|
|
86
|
+
The replacement is rotated 180 degrees and must exactly match the region;
|
|
87
|
+
resizing is deliberately not implicit because it can hide metadata or
|
|
88
|
+
geometry errors. The source and replacement PIL images are not modified.
|
|
89
|
+
"""
|
|
90
|
+
if not isinstance(replacement_label, Image.Image):
|
|
91
|
+
raise TypeError("replacement_label must be a PIL Image")
|
|
92
|
+
|
|
93
|
+
declared_format = image_format.upper() if image_format is not None else None
|
|
94
|
+
if declared_format is not None and declared_format not in _SUPPORTED_FORMATS:
|
|
95
|
+
raise MiraxCompositeError(
|
|
96
|
+
f"Unsupported composite image format: {image_format!r}"
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
try:
|
|
100
|
+
source = Image.open(BytesIO(image_bytes))
|
|
101
|
+
source.load()
|
|
102
|
+
except (Image.DecompressionBombError, OSError, SyntaxError, ValueError) as err:
|
|
103
|
+
raise MiraxCompositeError(
|
|
104
|
+
"The composite bytes are not a complete, decodable image"
|
|
105
|
+
) from err
|
|
106
|
+
|
|
107
|
+
with source:
|
|
108
|
+
actual_format = source.format
|
|
109
|
+
if actual_format not in _SUPPORTED_FORMATS:
|
|
110
|
+
raise MiraxCompositeError(
|
|
111
|
+
f"Unsupported decoded composite image format: {actual_format!r}"
|
|
112
|
+
)
|
|
113
|
+
if declared_format is not None and actual_format != declared_format:
|
|
114
|
+
raise MiraxCompositeError(
|
|
115
|
+
"The decoded composite format does not match Slidedat.ini"
|
|
116
|
+
)
|
|
117
|
+
if expected_size is not None and source.size != expected_size:
|
|
118
|
+
raise MiraxCompositeError(
|
|
119
|
+
"The decoded composite dimensions do not match Slidedat.ini: "
|
|
120
|
+
f"expected {expected_size}, got {source.size}"
|
|
121
|
+
)
|
|
122
|
+
_check_region_bounds(barcode_region, source.size)
|
|
123
|
+
|
|
124
|
+
# rotate() returns a new image, leaving the caller's label untouched.
|
|
125
|
+
oriented_label = replacement_label.rotate(
|
|
126
|
+
_COMPOSITE_BARCODE_ROTATION, expand=True
|
|
127
|
+
)
|
|
128
|
+
region_size = (barcode_region.width, barcode_region.height)
|
|
129
|
+
if oriented_label.size != region_size:
|
|
130
|
+
raise MiraxCompositeError(
|
|
131
|
+
"The replacement label dimensions must exactly match the "
|
|
132
|
+
f"barcode region: expected {region_size}, got {oriented_label.size}"
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
# Palette images need conversion before an RGB replacement can be
|
|
136
|
+
# pasted without accidentally reinterpreting palette indices. MIRAX
|
|
137
|
+
# composites are normally RGB, which also permits JPEG 'keep' encoding.
|
|
138
|
+
if source.mode == "P":
|
|
139
|
+
working_image = source.convert(
|
|
140
|
+
"RGBA" if "transparency" in source.info else "RGB"
|
|
141
|
+
)
|
|
142
|
+
else:
|
|
143
|
+
working_image = source
|
|
144
|
+
|
|
145
|
+
converted_label = oriented_label.convert(working_image.mode)
|
|
146
|
+
# No mask: every pixel in the declared region, including alpha where
|
|
147
|
+
# present, comes from the replacement rather than the original image.
|
|
148
|
+
working_image.paste(converted_label, (barcode_region.left, barcode_region.top))
|
|
149
|
+
|
|
150
|
+
save_options: dict[str, object] = {}
|
|
151
|
+
if actual_format == "JPEG":
|
|
152
|
+
if working_image is source:
|
|
153
|
+
# Retain the source quantization tables and chroma subsampling.
|
|
154
|
+
# The scan still needs full lossy re-encoding after pixel edits.
|
|
155
|
+
save_options = {"quality": "keep", "subsampling": "keep"}
|
|
156
|
+
else:
|
|
157
|
+
save_options = {"quality": 95}
|
|
158
|
+
|
|
159
|
+
output = BytesIO()
|
|
160
|
+
try:
|
|
161
|
+
working_image.save(output, format=actual_format, **save_options)
|
|
162
|
+
except (OSError, ValueError) as err:
|
|
163
|
+
raise MiraxCompositeError(
|
|
164
|
+
f"Could not encode the sanitized composite as {actual_format}"
|
|
165
|
+
) from err
|
|
166
|
+
|
|
167
|
+
return output.getvalue()
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _check_region_bounds(
|
|
171
|
+
region: MiraxBarcodeRegion, image_size: tuple[int, int]
|
|
172
|
+
) -> None:
|
|
173
|
+
width, height = image_size
|
|
174
|
+
if region.right >= width or region.bottom >= height:
|
|
175
|
+
raise MiraxCompositeError(
|
|
176
|
+
"The declared barcode region extends beyond the composite image: "
|
|
177
|
+
f"region {region.as_pil_box()}, image size {image_size}"
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
__all__ = [
|
|
182
|
+
"MiraxCompositeError",
|
|
183
|
+
"create_sanitized_composite",
|
|
184
|
+
"replace_barcode_region",
|
|
185
|
+
]
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Read and update the MIRAX ``SLIDE_NAME`` without rewriting the INI file."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import codecs
|
|
6
|
+
import configparser
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import stat
|
|
10
|
+
import tempfile
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from anonslide.exceptions import SlideProcessingError, SlideValidationError
|
|
14
|
+
|
|
15
|
+
_SECTION_RE = re.compile(r"^[ \t]*\[([^]]+)\][ \t]*(?:\r\n|\n|\r)?$")
|
|
16
|
+
_SLIDE_NAME_RE = re.compile(
|
|
17
|
+
r"^([ \t]*SLIDE_NAME[ \t]*[=:][ \t]*)[^\r\n]*(\r\n|\n|\r)?$",
|
|
18
|
+
re.IGNORECASE,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _read_ini(path: Path) -> tuple[str, bool]:
|
|
23
|
+
raw = path.read_bytes()
|
|
24
|
+
has_bom = raw.startswith(codecs.BOM_UTF8)
|
|
25
|
+
try:
|
|
26
|
+
return raw.decode("utf-8-sig"), has_bom
|
|
27
|
+
except UnicodeDecodeError as error:
|
|
28
|
+
raise SlideProcessingError(
|
|
29
|
+
f"Could not decode MIRAX INI file: {path}"
|
|
30
|
+
) from error
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _parse_ini(text: str, path: Path) -> configparser.RawConfigParser:
|
|
34
|
+
parser = configparser.RawConfigParser()
|
|
35
|
+
parser.optionxform = str
|
|
36
|
+
try:
|
|
37
|
+
parser.read_string(text)
|
|
38
|
+
except configparser.Error as error:
|
|
39
|
+
raise SlideProcessingError(f"Could not parse MIRAX INI file: {path}") from error
|
|
40
|
+
return parser
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def get_current_slide_name(path: Path) -> str:
|
|
44
|
+
"""Return ``GENERAL.SLIDE_NAME`` without interpolating percent signs."""
|
|
45
|
+
text, _ = _read_ini(path)
|
|
46
|
+
parser = _parse_ini(text, path)
|
|
47
|
+
try:
|
|
48
|
+
return parser["GENERAL"]["SLIDE_NAME"]
|
|
49
|
+
except KeyError as error:
|
|
50
|
+
raise SlideProcessingError(
|
|
51
|
+
f"MIRAX INI has no GENERAL.SLIDE_NAME: {path}"
|
|
52
|
+
) from error
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def sanitise(name: str) -> str:
|
|
56
|
+
"""Return the scanner-compatible representation used for ``SLIDE_NAME``."""
|
|
57
|
+
return name.strip().replace(" ", "_").upper()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def update_slide_name(path: Path, new_name: str) -> None:
|
|
61
|
+
"""Atomically replace only the ``SLIDE_NAME`` line, preserving other bytes."""
|
|
62
|
+
new_value = sanitise(new_name)
|
|
63
|
+
if not new_value:
|
|
64
|
+
raise SlideValidationError("The new slide name cannot be empty")
|
|
65
|
+
|
|
66
|
+
text, has_bom = _read_ini(path)
|
|
67
|
+
_parse_ini(text, path)
|
|
68
|
+
|
|
69
|
+
replaced = False
|
|
70
|
+
section = ""
|
|
71
|
+
output_lines: list[str] = []
|
|
72
|
+
for line in text.splitlines(keepends=True):
|
|
73
|
+
section_match = _SECTION_RE.match(line)
|
|
74
|
+
if section_match:
|
|
75
|
+
section = section_match.group(1)
|
|
76
|
+
|
|
77
|
+
name_match = _SLIDE_NAME_RE.match(line)
|
|
78
|
+
if section.upper() == "GENERAL" and name_match and not replaced:
|
|
79
|
+
line = f"{name_match.group(1)}{new_value}{name_match.group(2) or ''}"
|
|
80
|
+
replaced = True
|
|
81
|
+
output_lines.append(line)
|
|
82
|
+
|
|
83
|
+
if not replaced:
|
|
84
|
+
raise SlideProcessingError(f"MIRAX INI has no GENERAL.SLIDE_NAME: {path}")
|
|
85
|
+
|
|
86
|
+
output = "".join(output_lines).encode("utf-8")
|
|
87
|
+
if has_bom:
|
|
88
|
+
output = codecs.BOM_UTF8 + output
|
|
89
|
+
|
|
90
|
+
temporary_path: Path | None = None
|
|
91
|
+
try:
|
|
92
|
+
with tempfile.NamedTemporaryFile(
|
|
93
|
+
mode="wb",
|
|
94
|
+
dir=path.parent,
|
|
95
|
+
prefix=f".{path.name}.",
|
|
96
|
+
suffix=".tmp",
|
|
97
|
+
delete=False,
|
|
98
|
+
) as temporary_file:
|
|
99
|
+
temporary_path = Path(temporary_file.name)
|
|
100
|
+
temporary_file.write(output)
|
|
101
|
+
temporary_file.flush()
|
|
102
|
+
os.fsync(temporary_file.fileno())
|
|
103
|
+
os.chmod(temporary_path, stat.S_IMODE(path.stat().st_mode))
|
|
104
|
+
os.replace(temporary_path, path)
|
|
105
|
+
finally:
|
|
106
|
+
if temporary_path is not None and temporary_path.exists():
|
|
107
|
+
temporary_path.unlink()
|