Writes a JSON file that logs the mapping between input image paths and their corresponding output paths. This class uses FileLock to ensure safe writing to the JSON file in a multiprocess environment. Args: mapping_file_path (Path or str): Path to the JSON file where the mappin
| 525 | |
| 526 | |
| 527 | class WriteFileMapping(Transform): |
| 528 | """ |
| 529 | Writes a JSON file that logs the mapping between input image paths and their corresponding output paths. |
| 530 | This class uses FileLock to ensure safe writing to the JSON file in a multiprocess environment. |
| 531 | |
| 532 | Args: |
| 533 | mapping_file_path (Path or str): Path to the JSON file where the mappings will be saved. |
| 534 | """ |
| 535 | |
| 536 | def __init__(self, mapping_file_path: Path | str = "mapping.json"): |
| 537 | self.mapping_file_path = Path(mapping_file_path) |
| 538 | |
| 539 | def __call__(self, img: NdarrayOrTensor): |
| 540 | """ |
| 541 | Args: |
| 542 | img: The input image with metadata. |
| 543 | """ |
| 544 | if isinstance(img, MetaTensor): |
| 545 | meta_data = img.meta |
| 546 | |
| 547 | if MetaKeys.SAVED_TO not in meta_data: |
| 548 | raise KeyError( |
| 549 | "Missing 'saved_to' key in metadata. Check SaveImage argument 'savepath_in_metadict' is True." |
| 550 | ) |
| 551 | |
| 552 | input_path = meta_data[ImageMetaKey.FILENAME_OR_OBJ] |
| 553 | output_path = meta_data[MetaKeys.SAVED_TO] |
| 554 | log_data = {"input": input_path, "output": output_path} |
| 555 | |
| 556 | if has_filelock: |
| 557 | with FileLock(str(self.mapping_file_path) + ".lock"): |
| 558 | self._write_to_file(log_data) |
| 559 | else: |
| 560 | self._write_to_file(log_data) |
| 561 | return img |
| 562 | |
| 563 | def _write_to_file(self, log_data): |
| 564 | try: |
| 565 | with self.mapping_file_path.open("r") as f: |
| 566 | existing_log_data = json.load(f) |
| 567 | except (FileNotFoundError, json.JSONDecodeError): |
| 568 | existing_log_data = [] |
| 569 | existing_log_data.append(log_data) |
| 570 | with self.mapping_file_path.open("w") as f: |
| 571 | json.dump(existing_log_data, f, indent=4) |
no outgoing calls
searching dependent graphs…