A mistmatch can occur, when a `.nii` file is actually something other than a NIfTI1 file. That could be, for example, a git-annex pointer file (no content present).
46 lines
1.1 KiB
Python
46 lines
1.1 KiB
Python
import sys
|
|
from nibabel.nifti1 import Nifti1Header
|
|
import numpy
|
|
import gzip
|
|
|
|
|
|
def fmt_row(key, val) -> str:
|
|
return f'<tr><td>{fmt_val(key)}</td><td>{fmt_val(val)}</td></tr>'
|
|
|
|
|
|
def fmt_val(val) -> str:
|
|
if isinstance(val, numpy.ndarray):
|
|
if not len(val.shape):
|
|
val = val.item()
|
|
if isinstance(val, bytes):
|
|
if not val:
|
|
return ''
|
|
return f'<code>{str(val)[2:-1]}</code>'
|
|
|
|
return str(val)
|
|
|
|
|
|
# we read from STDIN to avoid having to set IS_INPUT_FILE
|
|
in_fp = sys.stdin.buffer
|
|
|
|
# GZIP starts with a header magic of `1f 8b`, whereas a NIfTI1 header starts
|
|
# with 348, we can easily tell them apart
|
|
if in_fp.peek(2)[:2] == b'\x1f\x8b':
|
|
# gzip compressed
|
|
fp = gzip.GzipFile(fileobj=in_fp, mode='rb')
|
|
else:
|
|
fp = in_fp
|
|
|
|
try:
|
|
hdr = Nifti1Header.from_fileobj(fp)
|
|
except Exception as e:
|
|
# if we cannot handle it, render error, but do not fail
|
|
print(f'<pre>{e}</pre>')
|
|
sys.exit(0)
|
|
|
|
print('<table>')
|
|
print('<tr><th>Header</th><th>Value</th></tr>')
|
|
for k, v in hdr.items():
|
|
print(fmt_row(k, v))
|
|
|
|
print('</table>')
|