Aryagm commited on
Commit
478276e
·
verified ·
1 Parent(s): 3fc327c

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +22 -10
app.py CHANGED
@@ -66,17 +66,29 @@ def load_model():
66
  print(f"Output shape: {model.output_shape}")
67
  return model
68
 
69
- def parse_nifti(file_bytes: bytes):
70
  """Parse NIfTI file from bytes"""
71
- # Check if gzipped
72
- if file_bytes[:2] == b'\x1f\x8b':
73
- file_bytes = gzip.decompress(file_bytes)
74
 
75
- # Use nibabel with BytesIO
76
- fh = nib.FileHolder(fileobj=io.BytesIO(file_bytes))
77
- img = nib.Nifti1Image.from_file_map({'header': fh, 'image': fh})
78
 
79
- return img.get_fdata(), img.header
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  def min_max_normalize(data):
82
  """Normalize data to 0-1 range"""
@@ -159,7 +171,7 @@ async def segment(file: UploadFile = File(...)):
159
 
160
  # Parse NIfTI
161
  parse_start = time.time()
162
- data, header = parse_nifti(file_bytes)
163
  parse_time = time.time() - parse_start
164
  print(f"Volume shape: {data.shape}, Parse time: {parse_time:.2f}s")
165
 
@@ -217,7 +229,7 @@ async def segment_compact(file: UploadFile = File(...)):
217
  raise HTTPException(400, "File must be a NIfTI file (.nii or .nii.gz)")
218
 
219
  file_bytes = await file.read()
220
- data, header = parse_nifti(file_bytes)
221
  processed = preprocess_volume(data)
222
  segmentation = run_inference(processed)
223
 
 
66
  print(f"Output shape: {model.output_shape}")
67
  return model
68
 
69
+ def parse_nifti(file_bytes: bytes, filename: str = "temp.nii"):
70
  """Parse NIfTI file from bytes"""
71
+ import tempfile
 
 
72
 
73
+ # Determine file extension for nibabel
74
+ is_gzipped = file_bytes[:2] == b'\x1f\x8b' or filename.endswith('.gz')
75
+ suffix = '.nii.gz' if is_gzipped else '.nii'
76
 
77
+ # Write to temp file and load with nibabel
78
+ with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
79
+ tmp.write(file_bytes)
80
+ tmp_path = tmp.name
81
+
82
+ try:
83
+ img = nib.load(tmp_path)
84
+ data = img.get_fdata()
85
+ header = img.header
86
+ finally:
87
+ # Clean up temp file
88
+ import os
89
+ os.unlink(tmp_path)
90
+
91
+ return data, header
92
 
93
  def min_max_normalize(data):
94
  """Normalize data to 0-1 range"""
 
171
 
172
  # Parse NIfTI
173
  parse_start = time.time()
174
+ data, header = parse_nifti(file_bytes, file.filename)
175
  parse_time = time.time() - parse_start
176
  print(f"Volume shape: {data.shape}, Parse time: {parse_time:.2f}s")
177
 
 
229
  raise HTTPException(400, "File must be a NIfTI file (.nii or .nii.gz)")
230
 
231
  file_bytes = await file.read()
232
+ data, header = parse_nifti(file_bytes, file.filename)
233
  processed = preprocess_volume(data)
234
  segmentation = run_inference(processed)
235