garridojuan commited on
Commit
469daaf
·
verified ·
1 Parent(s): 05b4bce

Delete formatting_models.py

Browse files
Files changed (1) hide show
  1. formatting_models.py +0 -350
formatting_models.py DELETED
@@ -1,350 +0,0 @@
1
- from pathlib import Path
2
- import json
3
- import shutil
4
- import torch
5
- import re
6
-
7
- SOURCE_ROOT = Path(r"\\NAS3_Z\all\Juan\Documents\MATLAB\AutoAGM\AutoAGM_files\pythonfiles\folders\nnunet_results")
8
- DEST_ROOT = Path(r"\\NAS3_Z\all\Juan\EVARAI\HuggingFace_models")
9
-
10
- DATASETS = {
11
- "Dataset370_PreInterventionV3": "Dataset100_SegmentationPreEVAR",
12
- "Dataset380_LandmarksPreInterventionV2": "Dataset101_LandmarksPreEVAR",
13
- "Dataset371_PostInterventionV3": "Dataset200_SegmentationPostEVAR",
14
- "Dataset381_LandmarksPostInterventionV2": "Dataset201_LandmarksPostEVAR",
15
- }
16
-
17
-
18
-
19
- OVERWRITE = True
20
-
21
-
22
- def get_dataset_id(name):
23
- match = re.match(r"Dataset(\d{3})_", name)
24
- if not match:
25
- raise ValueError(f"Nombre de dataset no válido: {name}")
26
- return int(match.group(1))
27
-
28
-
29
- def normalize_key(key):
30
- return str(key).lower().replace("-", "_").replace(" ", "_")
31
-
32
-
33
- def is_dataset_id_key(key):
34
- key = normalize_key(key)
35
- return key in {"dataset_id", "datasetid", "dataset_name_or_id"} or key.endswith("_dataset_id")
36
-
37
-
38
- def is_dataset_name_key(key):
39
- key = normalize_key(key)
40
- return key == "dataset_name" or key.endswith("_dataset_name")
41
-
42
-
43
- def load_checkpoint(path):
44
- try:
45
- return torch.load(path, map_location="cpu", weights_only=False)
46
- except TypeError:
47
- return torch.load(path, map_location="cpu")
48
-
49
-
50
- def find_dataset_references(obj, old_name, old_id, path="root", parent_key=None):
51
- """Busca referencias al nombre/ID antiguo sin modificar nada."""
52
- found = []
53
-
54
- if isinstance(obj, dict):
55
- for key, value in obj.items():
56
- current_path = f"{path}.{key}"
57
-
58
- if isinstance(key, str) and (old_name in key or f"Dataset{old_id:03d}" in key):
59
- found.append((current_path + " [KEY]", key))
60
-
61
- # No tiene sentido recorrer millones de parámetros
62
- if key == "network_weights":
63
- continue
64
-
65
- found.extend(find_dataset_references(value, old_name, old_id, current_path, key))
66
-
67
- elif isinstance(obj, (list, tuple)):
68
- for i, value in enumerate(obj):
69
- found.extend(find_dataset_references(value, old_name, old_id, f"{path}[{i}]", parent_key))
70
-
71
- elif isinstance(obj, str):
72
- if old_name in obj or f"Dataset{old_id:03d}" in obj:
73
- found.append((path, obj))
74
- elif parent_key is not None and is_dataset_id_key(parent_key) and obj == str(old_id):
75
- found.append((path, obj))
76
-
77
- elif isinstance(obj, int) and not isinstance(obj, bool):
78
- if parent_key is not None and is_dataset_id_key(parent_key) and obj == old_id:
79
- found.append((path, obj))
80
-
81
- return found
82
-
83
-
84
- def rewrite_metadata(obj, old_name, new_name, old_id, new_id, parent_key=None):
85
- """
86
- Cambia únicamente referencias identificables del dataset.
87
- No hace un reemplazo global old_id -> new_id.
88
- """
89
- if isinstance(obj, dict):
90
- result = {}
91
-
92
- for key, value in obj.items():
93
- new_key = key
94
-
95
- if isinstance(key, str):
96
- new_key = key.replace(old_name, new_name)
97
-
98
- if new_key == "network_weights":
99
- result[new_key] = value
100
- continue
101
-
102
- result[new_key] = rewrite_metadata(value, old_name, new_name, old_id, new_id, new_key)
103
-
104
- return result
105
-
106
- if isinstance(obj, list):
107
- return [rewrite_metadata(v, old_name, new_name, old_id, new_id, parent_key) for v in obj]
108
-
109
- if isinstance(obj, tuple):
110
- return tuple(rewrite_metadata(v, old_name, new_name, old_id, new_id, parent_key) for v in obj)
111
-
112
- if isinstance(obj, str):
113
- value = obj.replace(old_name, new_name)
114
-
115
- if parent_key is not None and is_dataset_name_key(parent_key):
116
- if value.startswith(f"Dataset{old_id:03d}_") or value == f"Dataset{old_id:03d}":
117
- value = new_name
118
-
119
- if parent_key is not None and is_dataset_id_key(parent_key) and value == str(old_id):
120
- value = str(new_id)
121
-
122
- return value
123
-
124
- if isinstance(obj, int) and not isinstance(obj, bool):
125
- if parent_key is not None and is_dataset_id_key(parent_key) and obj == old_id:
126
- return new_id
127
-
128
- return obj
129
-
130
-
131
- def verify_weights_identical(original, modified):
132
- """Comprueba que network_weights no ha cambiado."""
133
- if "network_weights" not in original or "network_weights" not in modified:
134
- raise RuntimeError("El checkpoint no contiene 'network_weights'.")
135
-
136
- weights_a = original["network_weights"]
137
- weights_b = modified["network_weights"]
138
-
139
- if weights_a.keys() != weights_b.keys():
140
- raise RuntimeError("Las claves de network_weights han cambiado.")
141
-
142
- for key in weights_a:
143
- a, b = weights_a[key], weights_b[key]
144
-
145
- if torch.is_tensor(a) and torch.is_tensor(b):
146
- if not torch.equal(a, b):
147
- raise RuntimeError(f"Los pesos han cambiado en: {key}")
148
- elif a != b:
149
- raise RuntimeError(f"Ha cambiado un elemento de network_weights: {key}")
150
-
151
-
152
- def audit_json(path, old_name, old_id):
153
- with open(path, "r", encoding="utf-8") as f:
154
- data = json.load(f)
155
-
156
- return find_dataset_references(data, old_name, old_id, path.name)
157
-
158
-
159
- def audit_checkpoint(path, old_name, old_id):
160
- checkpoint = load_checkpoint(path)
161
- return find_dataset_references(checkpoint, old_name, old_id, path.name)
162
-
163
-
164
- def save_modified_json(src, dst, old_name, new_name, old_id, new_id):
165
- with open(src, "r", encoding="utf-8") as f:
166
- data = json.load(f)
167
-
168
- data = rewrite_metadata(data, old_name, new_name, old_id, new_id)
169
-
170
- dst.parent.mkdir(parents=True, exist_ok=True)
171
-
172
- with open(dst, "w", encoding="utf-8") as f:
173
- json.dump(data, f, indent=4, ensure_ascii=False)
174
-
175
-
176
- def save_modified_checkpoint(src, dst, old_name, new_name, old_id, new_id):
177
- checkpoint = load_checkpoint(src)
178
-
179
- # Guardamos una referencia a los pesos originales.
180
- original_weights = checkpoint["network_weights"]
181
-
182
- # Modificamos todos los metadatos excepto network_weights.
183
- modified = rewrite_metadata(checkpoint, old_name, new_name, old_id, new_id)
184
-
185
- # Comprobación antes de guardar.
186
- verify_weights_identical({"network_weights": original_weights}, modified)
187
-
188
- dst.parent.mkdir(parents=True, exist_ok=True)
189
- torch.save(modified, dst)
190
-
191
- # Volvemos a cargar el archivo generado y comprobamos de nuevo.
192
- reloaded = load_checkpoint(dst)
193
- verify_weights_identical({"network_weights": original_weights}, reloaded)
194
-
195
-
196
- def find_trainer_dirs(dataset_dir):
197
- trainers = []
198
-
199
- for plans_file in dataset_dir.rglob("plans.json"):
200
- trainer_dir = plans_file.parent
201
-
202
- if (trainer_dir / "dataset.json").exists() and any(trainer_dir.glob("fold_*")):
203
- trainers.append(trainer_dir)
204
-
205
- return sorted(set(trainers))
206
-
207
-
208
- def print_references(refs, indent=" "):
209
- if not refs:
210
- print(f"{indent}No se encontraron referencias.")
211
- return
212
-
213
- for path, value in refs:
214
- value = str(value)
215
- if len(value) > 150:
216
- value = value[:147] + "..."
217
- print(f"{indent}{path}: {value}")
218
-
219
-
220
- def export_dataset(old_name, new_name):
221
- old_id = get_dataset_id(old_name)
222
- new_id = get_dataset_id(new_name)
223
-
224
- src_dataset = SOURCE_ROOT / old_name
225
- dst_dataset = DEST_ROOT / new_name
226
-
227
- print("\n" + "=" * 80)
228
- print(f"{old_name} -> {new_name}")
229
- print(f"ID: {old_id} -> {new_id}")
230
-
231
- if not src_dataset.exists():
232
- raise FileNotFoundError(f"No existe: {src_dataset}")
233
-
234
- if dst_dataset.exists() and not OVERWRITE:
235
- raise FileExistsError(
236
- f"Ya existe {dst_dataset}. Bórralo o cambia OVERWRITE = True."
237
- )
238
-
239
- if dst_dataset.exists() and OVERWRITE:
240
- shutil.rmtree(dst_dataset)
241
-
242
- trainer_dirs = find_trainer_dirs(src_dataset)
243
-
244
- if not trainer_dirs:
245
- raise RuntimeError(f"No se encontraron trainers dentro de {src_dataset}")
246
-
247
- for trainer_dir in trainer_dirs:
248
- relative = trainer_dir.relative_to(src_dataset)
249
- dst_trainer = dst_dataset / relative
250
-
251
- print(f"\n Trainer: {relative}")
252
-
253
- # ------------------------------------------------------------------
254
- # AUDITORÍA ORIGINAL
255
- # ------------------------------------------------------------------
256
-
257
- for filename in ("dataset.json", "plans.json"):
258
- src = trainer_dir / filename
259
-
260
- print(f"\n Auditoría {filename}:")
261
- refs = audit_json(src, old_name, old_id)
262
- print_references(refs)
263
-
264
- save_modified_json(
265
- src, dst_trainer / filename,
266
- old_name, new_name, old_id, new_id
267
- )
268
-
269
- # ------------------------------------------------------------------
270
- # FOLDS
271
- # ------------------------------------------------------------------
272
-
273
- fold_dirs = sorted(
274
- [p for p in trainer_dir.glob("fold_*") if p.is_dir()],
275
- key=lambda p: p.name
276
- )
277
-
278
- for fold_dir in fold_dirs:
279
- checkpoint = fold_dir / "checkpoint_best.pth"
280
-
281
- if not checkpoint.exists():
282
- print(f"\n [WARNING] {fold_dir.name}: no existe checkpoint_best.pth")
283
- continue
284
-
285
- print(f"\n Auditoría {fold_dir.name}/checkpoint_best.pth:")
286
-
287
- refs = audit_checkpoint(checkpoint, old_name, old_id)
288
- print_references(refs)
289
-
290
- dst_checkpoint = dst_trainer / fold_dir.name / "checkpoint_best.pth"
291
-
292
- save_modified_checkpoint(
293
- checkpoint, dst_checkpoint,
294
- old_name, new_name, old_id, new_id
295
- )
296
-
297
- print(" ✓ checkpoint copiado")
298
- print(" ✓ metadatos actualizados")
299
- print(" ✓ network_weights idénticos")
300
-
301
- # ------------------------------------------------------------------
302
- # AUDITORÍA FINAL
303
- # ------------------------------------------------------------------
304
-
305
- print("\n Comprobación final...")
306
-
307
- residual_refs = []
308
-
309
- for filename in ("dataset.json", "plans.json"):
310
- residual_refs.extend(
311
- audit_json(dst_trainer / filename, old_name, old_id)
312
- )
313
-
314
- for checkpoint in dst_trainer.glob("fold_*/checkpoint_best.pth"):
315
- residual_refs.extend(
316
- audit_checkpoint(checkpoint, old_name, old_id)
317
- )
318
-
319
- if residual_refs:
320
- print("\n [ERROR] Quedan referencias al dataset antiguo:")
321
- print_references(residual_refs)
322
- raise RuntimeError(
323
- f"La exportación de {old_name} contiene referencias antiguas."
324
- )
325
-
326
- print(" ✓ No quedan referencias al nombre/ID antiguo.")
327
-
328
-
329
- def main():
330
- if not SOURCE_ROOT.exists():
331
- raise FileNotFoundError(f"No existe SOURCE_ROOT: {SOURCE_ROOT}")
332
-
333
- DEST_ROOT.mkdir(parents=True, exist_ok=True)
334
-
335
- print("SOURCE:", SOURCE_ROOT)
336
- print("DEST: ", DEST_ROOT)
337
-
338
- for old_name, new_name in DATASETS.items():
339
- export_dataset(old_name, new_name)
340
-
341
- print("\n" + "=" * 80)
342
- print("EXPORTACIÓN COMPLETADA")
343
- print("=" * 80)
344
-
345
- for new_name in DATASETS.values():
346
- print(f" {DEST_ROOT / new_name}")
347
-
348
-
349
- if __name__ == "__main__":
350
- main()