rename.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """
  2. - add task entity to the filename
  3. - add TaskName to the json file
  4. - change acquisition entity to use uppercase for pmc
  5. - remove run entity as it was a place holder for the task
  6. """
  7. import json
  8. import os
  9. from pathlib import Path
  10. from bids import BIDSLayout
  11. from rich import print
  12. dry_run = False
  13. data_pth = Path(__file__).parent.parent
  14. pybids_config = Path(__file__).parent.joinpath("pybids_config.json")
  15. layout = BIDSLayout(Path(__file__).parent.parent, config=pybids_config)
  16. print(data_pth)
  17. print(layout)
  18. bf = layout.get(datatype="anat", extension="nii|json", regex_search=True)
  19. run_task_map = {"01": "still", "02": "nodding", "03": "shaking"}
  20. for file in bf:
  21. entities = file.entities.copy()
  22. input_file = layout.build_path(entities, strict=False, validate=False)
  23. task_label = run_task_map[str(entities["run"])]
  24. entities["task"] = task_label
  25. entities["acquisition"] = entities["acquisition"].replace("pmc", "PMC")
  26. entities.pop("run")
  27. # need to skip validation as the the new task entity is not yet in the validator
  28. output_file = layout.build_path(entities, strict=False, validate=False)
  29. print()
  30. print(input_file)
  31. # print(entities)
  32. print(output_file)
  33. if not dry_run:
  34. os.rename(input_file, output_file)
  35. if file.entities["extension"] == ".json":
  36. with open(output_file, "r") as f:
  37. json_data = json.load(f)
  38. json_data["TaskName"] = task_label
  39. with open(output_file, "w") as f:
  40. json.dump(json_data, f, indent=4)