From cde5b53167dca738c7ae0a4340e4969a579bf3a3 Mon Sep 17 00:00:00 2001
From: Christopher Rhodes <christopher.rhodes@embl.de>
Date: Fri, 26 Apr 2024 11:02:03 +0200
Subject: [PATCH] Script converts absolute paths to relative ones in ilastik
 project files

---
 .../scripts/correct_ilastik_abspath.py        | 44 +++++++++++++++++++
 1 file changed, 44 insertions(+)
 create mode 100644 model_server/scripts/correct_ilastik_abspath.py

diff --git a/model_server/scripts/correct_ilastik_abspath.py b/model_server/scripts/correct_ilastik_abspath.py
new file mode 100644
index 00000000..234031d2
--- /dev/null
+++ b/model_server/scripts/correct_ilastik_abspath.py
@@ -0,0 +1,44 @@
+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}')
+
-- 
GitLab