Spaces:
Sleeping
Sleeping
File size: 12,281 Bytes
2ab01da 24da0c6 2ab01da 24da0c6 2ab01da 24da0c6 2ab01da 24da0c6 2ab01da 24da0c6 2ab01da 24da0c6 2ab01da 24da0c6 2ab01da | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | """Validate immutable, precomputed example results without loading a model."""
from __future__ import annotations
import copy
import hashlib
import json
import math
import secrets
import pydicom
from pathlib import Path
from .storage import InputError, Projection, automatic_assignment
DATASET_REPOSITORY = 'MesserMMP/coronary-angiography-syntax'
SERVICE_DIRECTORY = Path(__file__).resolve().parent
MODEL_MANIFEST = SERVICE_DIRECTORY.parent / 'engine' / 'manifest.json'
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open('rb') as source:
for chunk in iter(lambda: source.read(1024 * 1024), b''):
digest.update(chunk)
return digest.hexdigest()
def _same_number(actual, expected):
return (type(actual) in (int, float) and math.isfinite(actual)
and math.isclose(actual, expected, rel_tol=1e-7, abs_tol=1e-6))
def _require(condition, message):
if not condition:
raise InputError('The precomputed example result could not be verified: ' + message)
def classifier_provenance(outputs: list[dict], manifest=None):
manifest = manifest or json.loads(MODEL_MANIFEST.read_text())
return {'repo_id': manifest['repo_id'], 'revision': manifest['revision'],
'weight': {key: manifest['classifier'][key] for key in ('path', 'sha256')},
'preprocessing': manifest['preprocessing']['classifier'],
'thresholds': {'left_max': .1, 'right_min': .9}, 'outputs': outputs}
def verify_classification(classification, example, files, manifest):
_require(isinstance(classification, dict), 'classifier provenance is required.')
outputs = classification.get('outputs')
_require(isinstance(outputs, list) and len(outputs) == len(files), 'classifier output count mismatch.')
_require(classification == classifier_provenance(outputs, manifest), 'classifier identity or preprocessing mismatch.')
for output, source, entry in zip(outputs, files, example['files']):
_require(set(output) == {'sop_uid', 'frames', 'artery', 'probability_right', 'reason'}, 'unexpected classifier output metadata.')
_require(output['sop_uid'] == source['sop_uid'] and type(output['frames']) is int and output['frames'] > 0,
'classifier source identity mismatch.')
artery, probability, reason = automatic_assignment(output['frames'], output['probability_right'])
_require(output['artery'] == artery == source['artery'] and output['reason'] == reason,
'classifier assignment or exclusion reason mismatch.')
if entry.get('preview'):
_require(entry['preview']['frames'] == output['frames'], 'classifier frame count mismatch.')
for key in ('probability_right', 'reason'):
if key in entry:
_require(entry[key] == output[key], 'classifier manifest metadata mismatch.')
return copy.deepcopy(classification)
def read_cache(example: dict, *, base: Path = SERVICE_DIRECTORY, model_manifest: Path = MODEL_MANIFEST):
"""Absent optional cache is allowed. A configured but invalid cache fails closed."""
filename = example.get('cache_file')
if not filename:
return None
try:
relative = Path(filename)
root = (base / 'example_results').resolve()
path = (base / relative).resolve()
_require(not relative.is_absolute() and path.is_relative_to(root) and path.suffix == '.json', 'invalid cache path.')
_require(path.stat().st_size < 1024 * 1024, 'cache file is too large.')
payload = json.loads(path.read_text())
manifest = json.loads(model_manifest.read_text())
_require(payload.get('schema_version') == 1 and payload.get('example_id') == example['id'], 'example identity mismatch.')
dataset = {'repo_id': example.get('repository', DATASET_REPOSITORY),
'revision': example.get('revision', example.get('dataset_revision'))}
_require(payload.get('dataset') == dataset, 'dataset revision mismatch.')
files = payload['files']
_require(len(files) == len(example['files']), 'file count mismatch.')
for recorded, expected in zip(files, example['files']):
_require(all(recorded.get(key) == expected.get(key) for key in ('path', 'sop_uid', 'artery')), 'ordered file manifest mismatch.')
digest = recorded.get('sha256', '')
_require(isinstance(digest, str) and len(digest) == 64 and all(c in '0123456789abcdef' for c in digest), 'invalid DICOM checksum.')
if expected.get('sha256'):
_require(digest == expected['sha256'], 'DICOM manifest checksum mismatch.')
classification = verify_classification(payload.get('classification'), example, files, manifest)
result = payload['result']
_require(result.get('complete') is True and result.get('study_uid') == example['study_uid'], 'study identity or completeness mismatch.')
provenance = result['provenance']
_require(provenance.get('repo_id') == manifest['repo_id'] and provenance.get('revision') == manifest['revision'], 'model revision mismatch.')
expected_weights = [{'path': item['path'], 'sha256': item['sha256']} for item in manifest['score_weights']]
_require(provenance.get('weights') == expected_weights, 'model weight checksum mismatch.')
calibration = {key: manifest['calibration'][key] for key in ('path', 'sha256', 'folds')}
_require(provenance.get('calibration_source') == calibration, 'calibration checksum or coefficients mismatch.')
for side in ('left', 'right'):
expected_sops = [item['sop_uid'] for item in files if item['artery'] == side]
ordered = provenance['ordered_inputs'][side]
_require(expected_sops and [item['sop_uid'] for item in ordered] == expected_sops, 'ordered projection identifiers mismatch.')
_require(set(result[side]) == {'raw', 'per_fold', 'projections'}, 'unexpected artery result metadata.')
values = result[side]['per_fold']
_require(len(values) == 5 and all(type(v) in (int, float) and math.isfinite(v) for v in values), 'invalid per-fold artery scores.')
_require(_same_number(result[side]['raw'], sum(values) / 5), 'artery mean mismatch.')
_require(result[side]['projections'] == len(expected_sops), 'artery projection count mismatch.')
folds = result['per_fold']
_require(len(folds) == 5, 'the full five-fold ensemble is required.')
for index, (fold, coefficient) in enumerate(zip(folds, calibration['folds'])):
left, right = result['left']['per_fold'][index], result['right']['per_fold'][index]
_require(set(fold) == {'fold', 'left', 'right', 'raw', 'calibrated', 'a', 'b'}, 'unexpected fold metadata.')
expected = {'left': left, 'right': right, 'raw': left + right,
'calibrated': coefficient['a'] * (left + right) + coefficient['b'], **coefficient}
_require(fold.get('fold') == index and all(_same_number(fold.get(key), value) for key, value in expected.items()), 'fold arithmetic mismatch.')
_require(_same_number(result['raw'], max(0., sum(fold['raw'] for fold in folds) / 5)), 'raw ensemble mismatch.')
_require(_same_number(result['calibrated'], max(0., sum(fold['calibrated'] for fold in folds) / 5)), 'calibrated ensemble mismatch.')
_require(result['projection_count'] == sum(item['artery'] in ('left', 'right') for item in files), 'input projection count mismatch.')
# The exported cache only carries engine results and public identifier provenance.
allowed_result = {'raw', 'calibrated', 'complete', 'study_uid', 'left', 'right', 'per_fold',
'projection_count', 'provenance', 'message'}
allowed_provenance = {'repo_id', 'revision', 'architecture', 'precision', 'preprocessing',
'projection_order', 'calibration', 'calibration_source', 'ordered_inputs', 'weights', 'device'}
_require(set(result) <= allowed_result and set(provenance) <= allowed_provenance, 'unexpected result metadata.')
for records in provenance['ordered_inputs'].values():
_require(all(set(record) <= {'sop_uid', 'series_uid', 'frames'} for record in records), 'unexpected input metadata.')
return {'result': copy.deepcopy(result), 'files': files, 'cache_sha256': sha256_file(path), 'dataset': dataset, 'classification': classification}
except InputError:
raise
except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
raise InputError('The precomputed example result is unavailable or invalid. No cached score was used.') from exc
def verify_download(cache, index: int, path: Path, projection):
record = cache['files'][index]
_require(cache['classification']['outputs'][index]['frames'] == projection.frames, 'classifier source frame count mismatch.')
_require(sha256_file(path) == record['sha256'], 'downloaded DICOM checksum mismatch.')
if record['artery'] in ('left', 'right'):
expected = next(x for x in cache['result']['provenance']['ordered_inputs'][record['artery']]
if x['sop_uid'] == projection.sop_uid)
_require(expected['frames'] == projection.frames, 'DICOM frame count mismatch.')
series = str(pydicom.dcmread(path, stop_before_pixels=True, specific_tags=['SeriesInstanceUID']).get('SeriesInstanceUID', ''))
_require(expected['series_uid'] == series, 'DICOM series identifier mismatch.')
_require(record['artery'] == projection.artery, 'DICOM eligibility or artery assignment mismatch.')
def virtual_projections(example, cache, static_root: Path):
"""Packaged media creates a usable study without fetching source DICOM."""
if not cache or not any(item.get('preview') for item in example['files']):
return None
projections = []
for item, record, classified in zip(example['files'], cache['files'], cache['classification']['outputs']):
preview = item.get('preview')
_require(isinstance(preview, dict), 'preview metadata is incomplete.')
urls = {}
for kind, suffix in (('video', '.mp4'), ('poster', '.png')):
relative = Path(preview.get(kind, ''))
path = (static_root / relative).resolve()
_require(not relative.is_absolute() and path.is_relative_to((static_root / 'examples').resolve())
and path.suffix == suffix, 'invalid packaged preview path.')
_require(path.is_file() and sha256_file(path) == preview.get(kind + '_sha256'), 'packaged preview checksum mismatch.')
urls[kind] = '/static/' + relative.as_posix()
frames, rows, columns = (preview.get(key) for key in ('frames', 'rows', 'columns'))
_require(all(type(value) is int and value > 0 for value in (frames, rows, columns)), 'invalid preview dimensions.')
_require(item['artery'] in ('left', 'right', 'exclude'), 'invalid preview artery assignment.')
_require(isinstance(preview.get('series_uid'), str) and bool(preview['series_uid']), 'missing preview series identifier.')
if item['artery'] in ('left', 'right'):
expected = next(x for x in cache['result']['provenance']['ordered_inputs'][item['artery']]
if x['sop_uid'] == item['sop_uid'])
_require(expected['frames'] == frames and expected['series_uid'] == preview.get('series_uid'),
'packaged preview source metadata mismatch.')
_require(frames >= 10 or item['artery'] == 'exclude', 'short cine must remain excluded.')
source = {**cache['dataset'], 'path': item['path'], 'sha256': record['sha256'],
'series_uid': preview.get('series_uid')}
projections.append(Projection(secrets.token_urlsafe(24), Path(), Path(item['path']).name,
frames, rows, columns, item['sop_uid'], artery=classified['artery'],
probability=classified['probability_right'], reason=classified['reason'],
source=source, static_preview=urls))
return projections
|