Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add "Name" and "SpatialReference" key-value pair to JSON sidecar, remove check_if_modified #76

Merged
merged 10 commits into from
Feb 14, 2024
73 changes: 33 additions & 40 deletions manual_correction.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,50 +483,44 @@ def get_modification_time(fname):
return datetime.datetime.fromtimestamp(os.path.getmtime(fname))


def check_if_modified(time_one, time_two):
"""
Check if the file was modified by the user. Return True if the file was modified, False otherwise.
:param time_one: modification time of the file before viewing
:param time_two: modification time of the file after viewing
:return:
"""
if time_one != time_two:
print("The label file was modified.")
return True
else:
print("The label file was not modified.")
return False


def update_json(fname_nifti, name_rater, modified):
def update_json(fname_nifti, name_rater):
"""
Create/update JSON sidecar with meta information
:param fname_nifti: str: File name of the nifti image to associate with the JSON sidecar
:param name_rater: str: Name of the expert rater
:param modified: bool: True if the file was modified by the user
:return:
"""
fname_json = fname_nifti.replace('.gz', '').replace('.nii', '.json')
if modified:
if os.path.exists(fname_json):
# Read already existing json file
with open(fname_json, "r") as outfile: # r to read
json_dict = json.load(outfile)

# Special check to fix all of our current json files (Might be deleted later)
if 'GeneratedBy' not in json_dict.keys():
json_dict = {'GeneratedBy': [json_dict]}
else:
# Init new json dict
json_dict = {'GeneratedBy': []}

# Add new author with time and date
json_dict['GeneratedBy'].append({'Author': name_rater, 'Date': time.strftime('%Y-%m-%d %H:%M:%S')})
with open(fname_json, 'w') as outfile: # w to overwrite the file
json.dump(json_dict, outfile, indent=4)
# Add last newline
outfile.write("\n")
print("JSON sidecar was updated: {}".format(fname_json))

# Check if the json file already exists, if so, open it
if os.path.exists(fname_json):
# Read already existing json file
with open(fname_json, "r") as outfile: # r to read
json_dict = json.load(outfile)

# Special checks to fix all of our current json files (Might be deleted later)
if 'GeneratedBy' not in json_dict.keys():
json_dict = {'GeneratedBy': [json_dict]}
if 'SpatialReference' not in json_dict.keys():
json_dict['SpatialReference'] = 'orig'

# If the json file does not exist, initialize a new one
else:
# Init new json dict
json_dict = {'SpatialReference': 'orig',
'GeneratedBy': []}

# If the label was modified or just checked, add "Name": "Manual" to the JSON sidecar
json_dict['GeneratedBy'].append({'Name': 'Manual',
'Author': name_rater,
'Date': time.strftime('%Y-%m-%d %H:%M:%S')})

# Write the data to the JSON file
with open(fname_json, 'w') as outfile: # w to overwrite the file
json.dump(json_dict, outfile, indent=4)
# Add last newline
outfile.write("\n")
print("JSON sidecar was updated: {}".format(fname_json))


def ask_if_modify(fname_out, fname_label, do_labeling_always=False):
Expand Down Expand Up @@ -882,11 +876,10 @@ def main():
if args.add_seg_only:
# We are passing modified=True because we are adding a new segmentation and we want
# to create a JSON file
update_json(fname_out, name_rater, modified=True)
update_json(fname_out, name_rater)
# Generate QC report
else:
modified = check_if_modified(time_one, time_two)
update_json(fname_out, name_rater, modified)
update_json(fname_out, name_rater)
# Generate QC report
generate_qc(fname, fname_out, task, fname_qc, subject, args.config, args.qc_lesion_plane, suffix_dict)

Expand Down
27 changes: 19 additions & 8 deletions tests/test_create_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,21 @@

def test_create_json(tmp_path):
"""
Test that the function update_json() creates a JSON file with the expected metadata if modified=True.
Test that the function update_json() creates a JSON file with the expected metadata
"""
# Create a temporary file for testing
fname_label = "sub-001_ses-01_T1w_seg-manual.nii.gz"
nifti_file = tmp_path / fname_label
nifti_file.touch()

# Call the function with modified=True
update_json(str(nifti_file), "Test Rater", modified=True)
update_json(str(nifti_file), "Test Rater")

# Check that the JSON file was created and contains the expected metadata
expected_metadata = {'GeneratedBy': [{'Author': "Test Rater", 'Date': time.strftime('%Y-%m-%d %H:%M:%S')}]}
expected_metadata = {'SpatialReference': 'orig',
'GeneratedBy': [{'Name': 'Manual',
'Author': "Test Rater",
'Date': time.strftime('%Y-%m-%d %H:%M:%S')}]}
json_file = tmp_path / fname_label.replace(".nii.gz", ".json")
assert json_file.exists()
with open(str(json_file), "r") as f:
Expand All @@ -34,7 +37,7 @@ def test_create_json(tmp_path):

def test_update_json(tmp_path):
"""
Test that the function update_json() updates (appends to) the JSON file with the expected metadata if modified=True.
Test that the function update_json() updates (appends to) the JSON file with the expected metadata.
"""
# Create a temporary file for testing
fname_label = "sub-001_ses-01_T1w_seg-manual.nii.gz"
Expand All @@ -43,14 +46,22 @@ def test_update_json(tmp_path):
# Create JSON file with some metadata
json_file = tmp_path / fname_label.replace(".nii.gz", ".json")
with open(str(json_file), "w") as f:
json.dump({'GeneratedBy': [{'Author': "Test Rater 1", 'Date': "2023-01-01 00:00:00"}]}, f)
json.dump({'SpatialReference': 'orig',
'GeneratedBy': [{'Name': 'Manual',
'Author': "Test Rater 1",
'Date': "2023-01-01 00:00:00"}]}, f)

# Call the function with modified=True
update_json(str(nifti_file), "Test Rater 2", modified=True)
update_json(str(nifti_file), "Test Rater 2")

# Check that the JSON file was created and contains the expected metadata
expected_metadata = {'GeneratedBy': [{'Author': "Test Rater 1", 'Date': "2023-01-01 00:00:00"},
{'Author': "Test Rater 2", 'Date': time.strftime('%Y-%m-%d %H:%M:%S')}]}
expected_metadata = {'SpatialReference': 'orig',
'GeneratedBy': [{'Name': 'Manual',
'Author': "Test Rater 1",
'Date': "2023-01-01 00:00:00"},
{'Name': 'Manual',
'Author': "Test Rater 2",
'Date': time.strftime('%Y-%m-%d %H:%M:%S')}]}
json_file = tmp_path / fname_label.replace(".nii.gz", ".json")
assert json_file.exists()
with open(str(json_file), "r") as f:
Expand Down
Loading