Spaces:
Sleeping
Sleeping
Download engine/dicom.py from MesserMMP/syntax-video-infer: direct link, hf CLI and curl.
- Browser
- Download file 4.05 kB
-
https://huggingface.co/spaces/MesserMMP/syntax-video-infer/resolve/main/engine/dicom.py
- Command line
-
hf download hf://spaces/MesserMMP/syntax-video-infer/engine/dicom.py
-
curl -L -o dicom.py https://huggingface.co/spaces/MesserMMP/syntax-video-infer/resolve/main/engine/dicom.py
4.05 kB
| """DICOM input checks; no source files or patient metadata are modified.""" | |
| from pathlib import Path | |
| MIN_FRAMES = 10 | |
| MAX_FRAMES = 1024 | |
| MAX_DECODED_BYTES = 512 * 1024 * 1024 | |
| class InferenceError(RuntimeError): | |
| """An actionable validation or inference failure, never a numeric fallback.""" | |
| def inspect(path): | |
| import pydicom | |
| tags = ["StudyInstanceUID", "SeriesInstanceUID", "SOPInstanceUID", "NumberOfFrames", | |
| "Rows", "Columns", "SamplesPerPixel", "BitsAllocated", "PixelRepresentation", | |
| "PhotometricInterpretation"] | |
| try: | |
| ds = pydicom.dcmread(str(path), stop_before_pixels=True, specific_tags=tags) | |
| result = { | |
| "path": str(path), | |
| "study_uid": str(ds.get("StudyInstanceUID", "")), | |
| "series_uid": str(ds.get("SeriesInstanceUID", "")), | |
| "sop_uid": str(ds.get("SOPInstanceUID", "")), | |
| "frames": int(ds.get("NumberOfFrames", 1)), | |
| "rows": int(ds.get("Rows", 0)), | |
| "columns": int(ds.get("Columns", 0)), | |
| "samples_per_pixel": int(ds.get("SamplesPerPixel", 1)), | |
| "bits_allocated": int(ds.get("BitsAllocated", 0)), | |
| "pixel_representation": int(ds.get("PixelRepresentation", 0)), | |
| "photometric_interpretation": str(ds.get("PhotometricInterpretation", "")), | |
| } | |
| except Exception as exc: | |
| raise InferenceError(f"Cannot read DICOM header: {Path(path).name}.") from exc | |
| result["eligible"] = ( | |
| MIN_FRAMES <= result["frames"] <= MAX_FRAMES | |
| and result["rows"] > 0 and result["columns"] > 0 | |
| and result["samples_per_pixel"] == 1 | |
| and result["bits_allocated"] in (8, 16) | |
| and result["pixel_representation"] == 0 | |
| and result["photometric_interpretation"] in ("MONOCHROME1", "MONOCHROME2") | |
| ) | |
| return result | |
| def read_video(path): | |
| """Return raw unsigned grayscale frames; preserve the reference pixel convention.""" | |
| import numpy as np | |
| import pydicom | |
| meta = inspect(path) | |
| if not meta["eligible"]: | |
| raise InferenceError( | |
| f"{Path(path).name}: use an unsigned 8/16-bit grayscale DICOM cine " | |
| f"with {MIN_FRAMES}–{MAX_FRAMES} frames." | |
| ) | |
| if meta["frames"] * meta["rows"] * meta["columns"] * (meta["bits_allocated"] // 8) > MAX_DECODED_BYTES: | |
| raise InferenceError(f"{Path(path).name}: the decoded video exceeds the memory limit.") | |
| try: | |
| video = pydicom.dcmread(str(path)).pixel_array | |
| except Exception as exc: | |
| raise InferenceError(f"Cannot decode DICOM pixels: {Path(path).name}.") from exc | |
| if video.ndim != 3 or tuple(video.shape) != (meta["frames"], meta["rows"], meta["columns"]): | |
| raise InferenceError(f"{Path(path).name}: pixel dimensions do not match its DICOM header.") | |
| if video.dtype.kind != "u" or video.dtype.itemsize not in (1, 2): | |
| raise InferenceError(f"{Path(path).name}: unsupported pixel data type.") | |
| # Rescale/windowing and MONOCHROME1 inversion are deliberately not applied: | |
| # the published model reads pixel_array directly using these conventions. | |
| return np.asarray(video) | |
| def validate_study(paths): | |
| """Reject mixed studies and duplicate acquisitions without reordering paths.""" | |
| records = [inspect(path) for path in paths] | |
| if not records: | |
| raise InferenceError("Select at least one angiography projection.") | |
| if any(not record["study_uid"] or not record["sop_uid"] for record in records): | |
| raise InferenceError("Each DICOM must retain StudyInstanceUID and SOPInstanceUID.") | |
| if len({r["study_uid"] for r in records}) != 1: | |
| raise InferenceError("The selected projections belong to different studies.") | |
| if len({r["sop_uid"] for r in records}) != len(records): | |
| raise InferenceError("A projection is included more than once (duplicate SOPInstanceUID).") | |
| if any(not r["eligible"] for r in records): | |
| raise InferenceError("Remove unsupported or fewer-than-10-frame projections before inference.") | |
| return records | |