from os.path import relpath from pathlib import Path import shutil import h5py def make_abspath_to_relpath(ilp_filename: str, my_root: Path, their_root: Path): pa_ilp_old = my_root / ilp_filename assert pa_ilp_old.exists() pa_ilp_new = pa_ilp_old.parent / f'relpath_{pa_ilp_old.name}' with h5py.File(shutil.copy(pa_ilp_old, pa_ilp_new), 'r+') as h5: infos = h5['Input Data/infos'] for lane in infos.keys(): for role in infos[lane].keys(): if len(infos[lane][role]) == 0: continue pa_img_abs = Path(infos[lane][role]['filePath'][()].decode()) my_ilp_dir = (my_root / ilp_filename).parent their_ilp_dir = (their_root / ilp_filename).parent pa_img_rel = Path(relpath(pa_img_abs, their_ilp_dir)) if pa_img_rel.parts[-2].upper().endswith('.H5'): assert (my_ilp_dir / Path(*pa_img_rel.parts[0:-1])).exists() else: assert (my_ilp_dir / pa_img_rel).exists() del infos[lane][role]['filePath'] infos[lane][role]['filePath'] = str(pa_img_rel) return pa_ilp_new if __name__ == '__main__': files = [ '01_ilastik_files/240301_LSM900_DNA_PC.ilp', '01_ilastik_files/240320_LSM900_DNA_OC_new.ilp', '01_ilastik_files/240301_LSM900_TM_PC.ilp', '01_ilastik_files/240320_LSM900_TM_OC_new.ilp' ] for f in files: new_ilp = make_abspath_to_relpath( f, Path('w:/03_analysis/Trial3_LSM900'), Path('/g/cuylen/01_Share/Filemaker/01_Experiments/Experiments_1100/1156/03_analysis/Trial3_LSM900') ) print(f'Finished converting {new_ilp}')