farrell236's picture
Deploy native Gradio OCT inference app
8fca640 verified
Raw History Blame Contribute Delete
3.59 kB
"""Label-free structural OCT I/O; no segmentation dependency."""
from pathlib import Path
import json,re
import numpy as np
import pydicom
from pydicom.pixels import pixel_array,iter_pixels
from PIL import Image
def load_manifest(path):
rows=[json.loads(s) for s in Path(path).read_text().splitlines() if s.strip()]
seen=set()
for row in rows:
name=row['case_id']
if not isinstance(name,str) or not re.fullmatch(r'[A-Za-z0-9_-]{1,64}',name):raise ValueError('Unsafe case identifier')
if name in seen:raise ValueError('Duplicate case')
seen.add(name)
return rows
def safe_path(root,relative):
p=Path(relative)
if p.is_absolute() or '..' in p.parts:raise ValueError('Input path must be dataset-relative')
return Path(root)/p
def volume_headers(root,oct_paths,with_spacing=False):
tags=['SOPClassUID','Rows','Columns','NumberOfFrames','ConcatenationFrameOffsetNumber']
if with_spacing:tags+=['SharedFunctionalGroupsSequence','PerFrameFunctionalGroupsSequence']
# Inference asks for geometry, never participant identifiers or clinical tags.
headers=[(safe_path(root,p),pydicom.dcmread(safe_path(root,p),stop_before_pixels=True,specific_tags=tags)) for p in oct_paths]
headers.sort(key=lambda v:int(v[1].get('ConcatenationFrameOffsetNumber',0)))
offsets=[int(d.get('ConcatenationFrameOffsetNumber',0)) for p,d in headers]
n=0;h=int(headers[0][1].Rows);w=int(headers[0][1].Columns)
for off,(p,d) in zip(offsets,headers):
if off!=n:raise ValueError('Missing or overlapping concatenation frames')
if (int(d.Rows),int(d.Columns))!=(h,w):raise ValueError('Inconsistent structural geometry')
if str(d.SOPClassUID)!='1.2.840.10008.5.1.4.1.1.77.1.5.4':raise ValueError('Input is not structural OCT')
n+=int(d.get('NumberOfFrames',1))
return headers,(n,h,w)
def read_frame(headers,index):
for path,ds in headers:
off=int(ds.get('ConcatenationFrameOffsetNumber',0));n=int(ds.get('NumberOfFrames',1))
if off<=index<off+n:
plugin='pylibjpeg' if ds.file_meta.TransferSyntaxUID.is_compressed else ''
return pixel_array(path,index=index-off,decoding_plugin=plugin)
raise IndexError('Frame outside volume')
def read_frames(headers,indices):
"""Decode selected original frames with one file/decoder pass per source part."""
requested=[int(i) for i in indices];result={}
for path,ds in headers:
off=int(ds.get('ConcatenationFrameOffsetNumber',0));n=int(ds.get('NumberOfFrames',1))
local=[i-off for i in requested if off<=i<off+n]
if not local:continue
plugin='pylibjpeg' if ds.file_meta.TransferSyntaxUID.is_compressed else ''
for i,frame in zip(local,iter_pixels(path,indices=local,decoding_plugin=plugin)):
result[off+i]=frame
if set(result)!=set(requested):raise ValueError('Selected structural frame coverage is incomplete')
return result
def iter_volume_frames(headers):
for path,ds in headers:
plugin='pylibjpeg' if ds.file_meta.TransferSyntaxUID.is_compressed else ''
yield from iter_pixels(path,decoding_plugin=plugin)
def normalize_frame(image,shape):
"""Deterministic within-image percentiles; no cohort fitting or metadata features."""
image=np.asarray(image,dtype=np.float32)
finite=np.isfinite(image)
if not finite.any():return np.zeros(shape,dtype=np.float32)
lo,hi=np.quantile(image[finite],[.01,.995])
image=np.nan_to_num(image,nan=float(lo),posinf=float(hi),neginf=float(lo))
image=np.clip((image-lo)/max(float(hi-lo),1e-6),0,1)
# PIL float bilinear matches center-based coordinate conversion.
return np.asarray(Image.fromarray(image).resize((shape[1],shape[0]),Image.Resampling.BILINEAR),dtype=np.float32).copy()