duyle2408 commited on
Commit
5265d5f
·
verified ·
1 Parent(s): ab93c59

Upload 14 files

Browse files
Stable_diffusion_augmentation/README.md CHANGED
@@ -5,6 +5,31 @@ Thư mục này có 3 script:
5
  - `prepare_milk10k_sd_training_set.py`: tách data MILK10k thành folder train Stable Diffusion/LoRA cho **1 class** và **1 loại ảnh**.
6
  - `generate_milk10k_sd.py`: dùng Stable Diffusion `img2img` để tạo ảnh augmentation cho **1 class** và **1 loại ảnh**.
7
  - `plot_generated_images.py`: gom ảnh trong 1 folder thành grid/contact sheet để kiểm tra nhanh.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  ## Điểm quan trọng của MILK10k
10
 
 
5
  - `prepare_milk10k_sd_training_set.py`: tách data MILK10k thành folder train Stable Diffusion/LoRA cho **1 class** và **1 loại ảnh**.
6
  - `generate_milk10k_sd.py`: dùng Stable Diffusion `img2img` để tạo ảnh augmentation cho **1 class** và **1 loại ảnh**.
7
  - `plot_generated_images.py`: gom ảnh trong 1 folder thành grid/contact sheet để kiểm tra nhanh.
8
+ - `plan_and_materialize_balanced_milk10k.py`: audit phân phối real/synthetic, cap BCC, lập quota SD/QC và tùy chọn tạo dataset paired cân bằng riêng.
9
+
10
+ ## Audit và lập balance plan
11
+
12
+ Chạy audit trên các CSV hiện có mà chưa materialize:
13
+
14
+ ```bash
15
+ python Stable_diffusion_augmentation/plan_and_materialize_balanced_milk10k.py \
16
+ --base-data-dir data_related \
17
+ --report-dir data_related/augmented_info/balance_audit
18
+ ```
19
+
20
+ Khi đã có ảnh synthetic và QC summary, tạo dataset riêng bằng hardlink:
21
+
22
+ ```bash
23
+ python Stable_diffusion_augmentation/plan_and_materialize_balanced_milk10k.py \
24
+ --base-data-dir data_related \
25
+ --synthetic-input-dir /path/to/synthetic_prediction_input \
26
+ --qc-summary /path/to/effb2_qc_summary.csv \
27
+ --report-dir /path/to/balance_report \
28
+ --materialize-dir /path/to/milk10k_balanced \
29
+ --require-target-pred
30
+ ```
31
+
32
+ Script chỉ materialize synthetic có đủ clinical + dermoscopic và pass QC. Dataset output cần train với `--synthetic-train-only` để synthetic không vào validation.
33
 
34
  ## Điểm quan trọng của MILK10k
35
 
Stable_diffusion_augmentation/materialize_augmented_milk10k_dataset.py CHANGED
@@ -43,6 +43,12 @@ def parse_args() -> argparse.Namespace:
43
  action="store_true",
44
  help="Symlink images instead of copying. Default is copy, which is easier to move/use later.",
45
  )
 
 
 
 
 
 
46
  parser.add_argument("--overwrite", action="store_true", help="Overwrite output CSV files and existing image links.")
47
  return parser.parse_args()
48
 
@@ -103,6 +109,28 @@ def synthetic_metadata_row(
103
  return row
104
 
105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  def synthetic_groundtruth_row(lesion_id: str, class_name: str, columns: list[str]) -> dict[str, str]:
107
  row = {column: "0.0" for column in columns}
108
  row["lesion_id"] = lesion_id
@@ -123,6 +151,8 @@ def materialize_synthetic_rows(
123
  manifest_rows: list[dict[str, str]],
124
  metadata_columns: list[str],
125
  groundtruth_columns: list[str],
 
 
126
  output_input_dir: Path,
127
  copy_file: bool,
128
  overwrite: bool,
@@ -141,8 +171,31 @@ def materialize_synthetic_rows(
141
  link_or_copy(Path(row["clinical_generated_path"]), clinical_dst, copy_file, overwrite)
142
  link_or_copy(Path(row["dermoscopic_generated_path"]), dermoscopic_dst, copy_file, overwrite)
143
 
144
- metadata_rows.append(synthetic_metadata_row(metadata_columns, lesion_id, "clinical: close-up", clinical_isic_id))
145
- metadata_rows.append(synthetic_metadata_row(metadata_columns, lesion_id, "dermoscopic", dermoscopic_isic_id))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  if lesion_id not in seen_lesions:
147
  groundtruth_rows.append(synthetic_groundtruth_row(lesion_id, row["class_name"], groundtruth_columns))
148
  seen_lesions.add(lesion_id)
@@ -167,6 +220,7 @@ def main() -> None:
167
 
168
  metadata_columns = list(metadata_rows[0].keys())
169
  groundtruth_columns = list(groundtruth_rows[0].keys())
 
170
 
171
  copy_file = not args.symlink
172
  materialize_original_images(input_dir, output_input_dir, metadata_rows, copy_file, args.overwrite)
@@ -174,6 +228,8 @@ def main() -> None:
174
  manifest_rows,
175
  metadata_columns,
176
  groundtruth_columns,
 
 
177
  output_input_dir,
178
  copy_file,
179
  args.overwrite,
@@ -191,6 +247,7 @@ def main() -> None:
191
  print(f" original groundtruth rows: {len(groundtruth_rows)}")
192
  print(f" synthetic groundtruth rows: {len(synthetic_groundtruth_rows)}")
193
  print(f" image mode: {'symlink' if args.symlink else 'copy'}")
 
194
  print("")
195
  print("Use this for training:")
196
  print(f" --data-dir {output_dir}")
 
43
  action="store_true",
44
  help="Symlink images instead of copying. Default is copy, which is easier to move/use later.",
45
  )
46
+ parser.add_argument(
47
+ "--synthetic-metadata",
48
+ choices=["source", "neutral"],
49
+ default="source",
50
+ help="Metadata for synthetic rows. source copies source lesion metadata; neutral writes unknown/0 values.",
51
+ )
52
  parser.add_argument("--overwrite", action="store_true", help="Overwrite output CSV files and existing image links.")
53
  return parser.parse_args()
54
 
 
109
  return row
110
 
111
 
112
+ def source_metadata_row(
113
+ source_row: dict[str, str] | None,
114
+ columns: list[str],
115
+ lesion_id: str,
116
+ image_type: str,
117
+ isic_id: str,
118
+ ) -> dict[str, str]:
119
+ if source_row is None:
120
+ return synthetic_metadata_row(columns, lesion_id, image_type, isic_id)
121
+ row = {column: source_row.get(column, "") for column in columns}
122
+ row["lesion_id"] = lesion_id
123
+ row["image_type"] = image_type
124
+ row["isic_id"] = isic_id
125
+ if "attribution" in row:
126
+ row["attribution"] = "Stable Diffusion synthetic augmentation"
127
+ if "copyright_license" in row:
128
+ row["copyright_license"] = "synthetic"
129
+ if "image_manipulation" in row:
130
+ row["image_manipulation"] = "synthetic_from_source"
131
+ return row
132
+
133
+
134
  def synthetic_groundtruth_row(lesion_id: str, class_name: str, columns: list[str]) -> dict[str, str]:
135
  row = {column: "0.0" for column in columns}
136
  row["lesion_id"] = lesion_id
 
151
  manifest_rows: list[dict[str, str]],
152
  metadata_columns: list[str],
153
  groundtruth_columns: list[str],
154
+ source_metadata_by_key: dict[tuple[str, str], dict[str, str]],
155
+ synthetic_metadata_mode: str,
156
  output_input_dir: Path,
157
  copy_file: bool,
158
  overwrite: bool,
 
171
  link_or_copy(Path(row["clinical_generated_path"]), clinical_dst, copy_file, overwrite)
172
  link_or_copy(Path(row["dermoscopic_generated_path"]), dermoscopic_dst, copy_file, overwrite)
173
 
174
+ if synthetic_metadata_mode == "source":
175
+ source_lesion_id = row.get("source_lesion_id", "")
176
+ clinical_source_isic_id = row.get("clinical_source_isic_id", "")
177
+ dermoscopic_source_isic_id = row.get("dermoscopic_source_isic_id", "")
178
+ metadata_rows.append(
179
+ source_metadata_row(
180
+ source_metadata_by_key.get((source_lesion_id, clinical_source_isic_id)),
181
+ metadata_columns,
182
+ lesion_id,
183
+ "clinical: close-up",
184
+ clinical_isic_id,
185
+ )
186
+ )
187
+ metadata_rows.append(
188
+ source_metadata_row(
189
+ source_metadata_by_key.get((source_lesion_id, dermoscopic_source_isic_id)),
190
+ metadata_columns,
191
+ lesion_id,
192
+ "dermoscopic",
193
+ dermoscopic_isic_id,
194
+ )
195
+ )
196
+ else:
197
+ metadata_rows.append(synthetic_metadata_row(metadata_columns, lesion_id, "clinical: close-up", clinical_isic_id))
198
+ metadata_rows.append(synthetic_metadata_row(metadata_columns, lesion_id, "dermoscopic", dermoscopic_isic_id))
199
  if lesion_id not in seen_lesions:
200
  groundtruth_rows.append(synthetic_groundtruth_row(lesion_id, row["class_name"], groundtruth_columns))
201
  seen_lesions.add(lesion_id)
 
220
 
221
  metadata_columns = list(metadata_rows[0].keys())
222
  groundtruth_columns = list(groundtruth_rows[0].keys())
223
+ source_metadata_by_key = {(row["lesion_id"], row["isic_id"]): row for row in metadata_rows}
224
 
225
  copy_file = not args.symlink
226
  materialize_original_images(input_dir, output_input_dir, metadata_rows, copy_file, args.overwrite)
 
228
  manifest_rows,
229
  metadata_columns,
230
  groundtruth_columns,
231
+ source_metadata_by_key,
232
+ args.synthetic_metadata,
233
  output_input_dir,
234
  copy_file,
235
  args.overwrite,
 
247
  print(f" original groundtruth rows: {len(groundtruth_rows)}")
248
  print(f" synthetic groundtruth rows: {len(synthetic_groundtruth_rows)}")
249
  print(f" image mode: {'symlink' if args.symlink else 'copy'}")
250
+ print(f" synthetic metadata: {args.synthetic_metadata}")
251
  print("")
252
  print("Use this for training:")
253
  print(f" --data-dir {output_dir}")
Stable_diffusion_augmentation/plan_and_materialize_balanced_milk10k.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Audit MILK10k imbalance, plan paired SD augmentation, and optionally materialize a capped dataset."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import math
9
+ import os
10
+ import shutil
11
+ from pathlib import Path
12
+
13
+ os.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib-cache")
14
+ import matplotlib.pyplot as plt
15
+ import numpy as np
16
+ import pandas as pd
17
+ try:
18
+ import seaborn as sns
19
+ except ModuleNotFoundError: # Matplotlib fallback keeps audit usable in minimal environments.
20
+ sns = None
21
+
22
+ LABEL_COLUMNS = ["AKIEC", "BCC", "BEN_OTH", "BKL", "DF", "INF", "MAL_OTH", "MEL", "NV", "SCCKA", "VASC"]
23
+ MODALITIES = {"clinical: close-up", "dermoscopic"}
24
+
25
+
26
+ def parse_args(argv=None):
27
+ p = argparse.ArgumentParser(description="Audit and materialize a safely balanced paired MILK10k dataset.")
28
+ p.add_argument("--base-data-dir", type=Path, required=True)
29
+ p.add_argument("--base-input-dir", type=Path, default=None)
30
+ p.add_argument("--augmented-groundtruth", type=Path, default=None)
31
+ p.add_argument("--augmented-metadata", type=Path, default=None)
32
+ p.add_argument("--synthetic-input-dir", type=Path, default=None)
33
+ p.add_argument("--qc-summary", type=Path, default=None)
34
+ p.add_argument("--report-dir", type=Path, required=True)
35
+ p.add_argument("--materialize-dir", type=Path, default=None)
36
+ p.add_argument("--bcc-cap-ratio", type=float, default=1.5)
37
+ p.add_argument("--tail-floor", type=int, default=150)
38
+ p.add_argument("--max-synthetic-real-ratio", type=float, default=2.0)
39
+ p.add_argument("--max-synthetic-per-source", type=int, default=3)
40
+ p.add_argument("--min-target-prob", type=float, default=0.4)
41
+ p.add_argument("--require-target-pred", action="store_true")
42
+ p.add_argument("--seed", type=int, default=42)
43
+ p.add_argument("--num-variants", type=int, default=1)
44
+ p.add_argument("--link-mode", choices=["hardlink", "copy", "symlink"], default="hardlink")
45
+ p.add_argument("--overwrite", action="store_true")
46
+ return p.parse_args(argv)
47
+
48
+
49
+ def resolve_paths(args):
50
+ base = args.base_data_dir.expanduser().resolve()
51
+ gt = base / "MILK10k_Training_GroundTruth.csv"
52
+ meta = base / "MILK10k_Training_Metadata.csv"
53
+ input_dir = (args.base_input_dir or base / "MILK10k_Training_Input").expanduser().resolve()
54
+ if not input_dir.exists() and args.base_input_dir is None:
55
+ input_dir = (base.parent / "MILK10k_Training_Input").resolve()
56
+ info = base / "augmented_info"
57
+ aug_gt = args.augmented_groundtruth or info / "MILK10k_Training_GroundTruth(2).csv"
58
+ aug_meta = args.augmented_metadata or info / "MILK10k_Training_Metadata(3).csv"
59
+ required = [gt, meta, input_dir, aug_gt, aug_meta]
60
+ missing = [str(path) for path in required if not path.exists()]
61
+ if missing: raise FileNotFoundError("Missing inputs: " + ", ".join(missing))
62
+ return gt, meta, input_dir, aug_gt.expanduser().resolve(), aug_meta.expanduser().resolve()
63
+
64
+
65
+ def attach_labels(gt):
66
+ missing = set(LABEL_COLUMNS) - set(gt.columns)
67
+ if missing: raise ValueError(f"Ground truth missing labels: {sorted(missing)}")
68
+ result = gt.copy(); result["label"] = result[LABEL_COLUMNS].idxmax(axis=1)
69
+ if result.lesion_id.duplicated().any(): raise ValueError("Duplicate lesion_id in ground truth.")
70
+ return result
71
+
72
+
73
+ def source_id(lesion_id): return str(lesion_id).split("__sdpair_", 1)[0]
74
+
75
+
76
+ def load_inventory(args):
77
+ gt_path, meta_path, input_dir, aug_gt_path, aug_meta_path = resolve_paths(args)
78
+ base_gt_raw = pd.read_csv(gt_path); base_meta = pd.read_csv(meta_path); aug_gt_raw = pd.read_csv(aug_gt_path); aug_meta = pd.read_csv(aug_meta_path)
79
+ base_gt = attach_labels(base_gt_raw); aug_gt = attach_labels(aug_gt_raw)
80
+ base_ids = set(base_gt.lesion_id.astype(str)); synth_gt = aug_gt[~aug_gt.lesion_id.astype(str).isin(base_ids)].copy()
81
+ synth_meta = aug_meta[aug_meta.lesion_id.astype(str).isin(set(synth_gt.lesion_id.astype(str)))].copy()
82
+ if set(base_gt.lesion_id.astype(str)) - set(aug_gt.lesion_id.astype(str)): raise ValueError("Augmented ground truth omits base lesions.")
83
+ if synth_gt.lesion_id.duplicated().any(): raise ValueError("Duplicate synthetic lesion IDs.")
84
+ synth_gt["source_lesion_id"] = synth_gt.lesion_id.map(source_id)
85
+ modality_counts = synth_meta.groupby("lesion_id").image_type.agg(lambda values: set(map(str, values)))
86
+ synth_gt["pair_metadata_complete"] = synth_gt.lesion_id.map(lambda x: modality_counts.get(x, set()) == MODALITIES)
87
+ return base_gt_raw, base_gt, base_meta, synth_gt, synth_meta, input_dir
88
+
89
+
90
+ def add_file_and_qc_status(args, synth, synth_meta):
91
+ result = synth.copy(); qc = None
92
+ if args.qc_summary:
93
+ qc = pd.read_csv(args.qc_summary.expanduser().resolve()).drop_duplicates("synthetic_lesion_id").set_index("synthetic_lesion_id")
94
+ if args.synthetic_input_dir:
95
+ image_root = args.synthetic_input_dir.expanduser().resolve()
96
+ paths = synth_meta.assign(path=synth_meta.apply(lambda row: image_root / str(row.lesion_id) / f"{row.isic_id}.jpg", axis=1))
97
+ file_counts = paths.groupby("lesion_id").path.agg(lambda values: sum(Path(x).exists() for x in values))
98
+ result["existing_image_files"] = result.lesion_id.map(lambda x: int(file_counts.get(x, 0)))
99
+ result["pair_files_complete"] = result.lesion_id.map(lambda x: file_counts.get(x, 0) == 2)
100
+ else:
101
+ result["existing_image_files"] = 0
102
+ result["pair_files_complete"] = False
103
+ result["qc_available"] = result.lesion_id.isin(set(qc.index)) if qc is not None else False
104
+ result["target_probability"] = result.lesion_id.map(qc.target_class_probability) if qc is not None and "target_class_probability" in qc else np.nan
105
+ result["is_target_predicted"] = result.lesion_id.map(qc.is_target_predicted).astype(str).eq("True") if qc is not None and "is_target_predicted" in qc else False
106
+ result["qc_pass"] = result.qc_available & (pd.to_numeric(result.target_probability, errors="coerce").fillna(0) >= args.min_target_prob)
107
+ if args.require_target_pred: result["qc_pass"] &= result.is_target_predicted
108
+ result["usable"] = result.pair_metadata_complete & result.pair_files_complete & result.qc_pass
109
+ return result
110
+
111
+
112
+ def capped_synthetic(synth, real_counts, args, usable_only):
113
+ candidates = synth[synth.usable].copy() if usable_only else synth.copy()
114
+ candidates = candidates.sort_values(["label", "is_target_predicted", "target_probability", "lesion_id"], ascending=[True, False, False, True])
115
+ candidates["source_rank"] = candidates.groupby(["label", "source_lesion_id"]).cumcount() + 1
116
+ candidates = candidates[candidates.source_rank <= args.max_synthetic_per_source]
117
+ selected = []
118
+ for label, group in candidates.groupby("label", sort=True):
119
+ cap = int(math.floor(real_counts.get(label, 0) * args.max_synthetic_real_ratio))
120
+ selected.append(group.head(cap))
121
+ return pd.concat(selected, ignore_index=True) if selected else candidates.iloc[:0]
122
+
123
+
124
+ def plan_counts(base, synth, inventory_selected, usable_selected, args):
125
+ real = base.label.value_counts().reindex(LABEL_COLUMNS, fill_value=0).astype(int)
126
+ raw = synth.label.value_counts().reindex(LABEL_COLUMNS, fill_value=0).astype(int)
127
+ inventory = inventory_selected.label.value_counts().reindex(LABEL_COLUMNS, fill_value=0).astype(int)
128
+ usable = usable_selected.label.value_counts().reindex(LABEL_COLUMNS, fill_value=0).astype(int)
129
+ second = int(real.drop("BCC").max()); bcc_cap = min(int(real.BCC), int(math.floor(second * args.bcc_cap_ratio)))
130
+ rows = []
131
+ for label in LABEL_COLUMNS:
132
+ target = int(real[label])
133
+ if label in {"BEN_OTH", "DF", "INF", "MAL_OTH", "VASC"}:
134
+ target = min(args.tail_floor, int(math.floor(real[label] * (1 + args.max_synthetic_real_ratio))))
135
+ kept_real = bcc_cap if label == "BCC" else int(real[label])
136
+ rows.append({"class": label, "real_count": int(real[label]), "raw_synthetic_inventory": int(raw[label]),
137
+ "capped_inventory": int(inventory[label]), "verified_usable": int(usable[label]), "target_total": target,
138
+ "kept_real": kept_real, "final_inventory_total": kept_real + int(inventory[label]),
139
+ "final_verified_total": kept_real + int(usable[label]),
140
+ "additional_needed_inventory": max(0, target - int(real[label]) - int(inventory[label])),
141
+ "additional_needed_verified": max(0, target - int(real[label]) - int(usable[label]))})
142
+ return pd.DataFrame(rows), bcc_cap
143
+
144
+
145
+ def bcc_strata(base_meta, base, cap, seed):
146
+ bcc = base[base.label.eq("BCC")][["lesion_id"]].merge(base_meta.drop_duplicates("lesion_id"), on="lesion_id", how="left")
147
+ age = pd.to_numeric(bcc.age_approx, errors="coerce"); bcc["age_bin"] = pd.cut(age, [-np.inf,29,49,69,np.inf], labels=["<30","30-49","50-69","70+"]).astype(str)
148
+ for column in ("sex", "site", "skin_tone_class", "age_bin"): bcc[column] = bcc[column].fillna("unknown").astype(str)
149
+ bcc["stratum"] = bcc[["sex","site","skin_tone_class","age_bin"]].agg("|".join, axis=1)
150
+ counts = bcc.stratum.value_counts().sort_index(); exact = counts / len(bcc) * cap; quota = np.floor(exact).astype(int)
151
+ for key in (exact-quota).sort_values(ascending=False).index:
152
+ if quota.sum() >= cap: break
153
+ if quota[key] < counts[key]: quota[key] += 1
154
+ chosen=[]; rng=np.random.default_rng(seed)
155
+ for key in counts.index:
156
+ ids=bcc.loc[bcc.stratum.eq(key),"lesion_id"].to_numpy();rng.shuffle(ids);chosen.extend(ids[:quota[key]])
157
+ if len(chosen)<cap:
158
+ remaining=np.array(sorted(set(bcc.lesion_id)-set(chosen)));rng.shuffle(remaining);chosen.extend(remaining[:cap-len(chosen)])
159
+ return set(map(str, chosen[:cap])), bcc
160
+
161
+
162
+ def drift_table(bcc, selected_ids):
163
+ rows=[]
164
+ for column in ("sex","site","skin_tone_class","age_bin"):
165
+ full=bcc[column].value_counts(normalize=True); kept=bcc[bcc.lesion_id.astype(str).isin(selected_ids)][column].value_counts(normalize=True)
166
+ for value in sorted(set(full.index)|set(kept.index)): rows.append({"field":column,"value":value,"full_ratio":float(full.get(value,0)),"kept_ratio":float(kept.get(value,0)),"absolute_drift":abs(float(full.get(value,0)-kept.get(value,0)))})
167
+ return pd.DataFrame(rows)
168
+
169
+
170
+ def selection_manifest(synth, inventory_ids, usable_ids):
171
+ result=synth.copy();result["selected_inventory"]=result.lesion_id.isin(inventory_ids);result["selected_usable"]=result.lesion_id.isin(usable_ids)
172
+ def reason(row):
173
+ if not row.pair_metadata_complete:return "incomplete_metadata_pair"
174
+ if not row.pair_files_complete:return "missing_image_pair"
175
+ if not row.qc_available:return "qc_missing"
176
+ if not row.qc_pass:return "qc_failed"
177
+ if not row.selected_usable:return "class_or_source_cap"
178
+ return "selected"
179
+ result["selection_reason"]=result.apply(reason,axis=1)
180
+ return result
181
+
182
+
183
+ def source_diversity(synth, selected):
184
+ rows=[]
185
+ for label in LABEL_COLUMNS:
186
+ group=synth[synth.label.eq(label)]; kept=selected[selected.label.eq(label)]
187
+ rows.append({"class":label,"inventory":len(group),"inventory_sources":group.source_lesion_id.nunique(),
188
+ "selected":len(kept),"selected_sources":kept.source_lesion_id.nunique(),
189
+ "max_selected_per_source":int(kept.groupby("source_lesion_id").size().max()) if len(kept) else 0})
190
+ return pd.DataFrame(rows)
191
+
192
+
193
+ def plot_reports(report_dir, distribution, sources):
194
+ if sns is not None:sns.set_theme(style="whitegrid")
195
+ def grouped(frame,x,y,hue,path,log=False):
196
+ plt.figure(figsize=(14,6))
197
+ if sns is not None:sns.barplot(data=frame,x=x,y=y,hue=hue)
198
+ else:
199
+ pivot=frame.pivot(index=x,columns=hue,values=y);pivot.plot(kind="bar",ax=plt.gca())
200
+ if log:plt.yscale("log")
201
+ plt.xticks(rotation=35);plt.tight_layout();plt.savefig(path,dpi=170);plt.close()
202
+ long=distribution.melt(id_vars="class",value_vars=["real_count","raw_synthetic_inventory","capped_inventory","verified_usable"],var_name="series",value_name="count")
203
+ grouped(long,"class","count","series",report_dir/"class_distribution.png")
204
+ final=distribution.melt(id_vars="class",value_vars=["real_count","final_inventory_total","final_verified_total","target_total"],var_name="series",value_name="count")
205
+ grouped(final,"class","count","series",report_dir/"balance_before_after.png",True)
206
+ ratio=distribution.assign(synthetic_real_ratio=lambda d:d.capped_inventory/d.real_count.clip(lower=1))
207
+ plt.figure(figsize=(12,5));
208
+ if sns is not None:sns.barplot(data=ratio,x="class",y="synthetic_real_ratio")
209
+ else:plt.bar(ratio["class"],ratio.synthetic_real_ratio)
210
+ plt.axhline(2,color="red",linestyle="--");plt.xticks(rotation=35);plt.tight_layout();plt.savefig(report_dir/"synthetic_real_ratio.png",dpi=170);plt.close()
211
+ plt.figure(figsize=(12,5));
212
+ if sns is not None:sns.barplot(data=sources,x="class",y="selected_sources")
213
+ else:plt.bar(sources["class"],sources.selected_sources)
214
+ plt.xticks(rotation=35);plt.tight_layout();plt.savefig(report_dir/"source_diversity.png",dpi=170);plt.close()
215
+
216
+
217
+ def transfer(src, dst, mode, overwrite):
218
+ if not src.exists(): raise FileNotFoundError(src)
219
+ dst.parent.mkdir(parents=True, exist_ok=True)
220
+ if dst.exists() or dst.is_symlink():
221
+ if not overwrite:return
222
+ dst.unlink()
223
+ if mode=="copy":shutil.copy2(src,dst)
224
+ elif mode=="symlink":dst.symlink_to(src.resolve())
225
+ else:
226
+ try:os.link(src,dst)
227
+ except OSError:shutil.copy2(src,dst)
228
+
229
+
230
+ def materialize_variant(destination, base_gt_raw, base_meta, selected_base_ids, synth_gt, synth_meta, selected_synth_ids, base_input, synth_input, args):
231
+ if synth_input is None: raise ValueError("--synthetic-input-dir is required for materialization.")
232
+ if destination.exists() and not args.overwrite and any(destination.iterdir()):raise FileExistsError(f"Output is not empty: {destination}")
233
+ destination.mkdir(parents=True,exist_ok=True);output_images=destination/"MILK10k_Training_Input"
234
+ kept_gt=base_gt_raw[base_gt_raw.lesion_id.astype(str).isin(selected_base_ids)].copy()
235
+ kept_meta=base_meta[base_meta.lesion_id.astype(str).isin(selected_base_ids)].copy()
236
+ add_gt=synth_gt[synth_gt.lesion_id.astype(str).isin(selected_synth_ids)][["lesion_id",*LABEL_COLUMNS]].copy()
237
+ add_meta=synth_meta[synth_meta.lesion_id.astype(str).isin(selected_synth_ids)].copy()
238
+ counts=add_meta.groupby("lesion_id").image_type.agg(lambda x:set(map(str,x)))
239
+ bad=[x for x in selected_synth_ids if counts.get(x,set())!=MODALITIES]
240
+ if bad:raise ValueError(f"Incomplete synthetic pairs: {bad[:5]}")
241
+ combined_meta=pd.concat([kept_meta.assign(source_root=str(base_input)),add_meta.assign(source_root=str(synth_input))])
242
+ for _,row in combined_meta.iterrows():
243
+ src=Path(row.source_root)/str(row.lesion_id)/f"{row.isic_id}.jpg";dst=output_images/str(row.lesion_id)/f"{row.isic_id}.jpg";transfer(src,dst,args.link_mode,args.overwrite)
244
+ pd.concat([kept_gt,add_gt],ignore_index=True).to_csv(destination/"MILK10k_Training_GroundTruth.csv",index=False)
245
+ pd.concat([kept_meta,add_meta],ignore_index=True).to_csv(destination/"MILK10k_Training_Metadata.csv",index=False)
246
+
247
+
248
+ def command_script(args, plan, report_dir):
249
+ needed_rows=plan[(plan.additional_needed_verified>0)&~plan["class"].eq("MAL_OTH")]
250
+ classes=" ".join(needed_rows["class"].astype(str));per_source=args.max_synthetic_per_source
251
+ max_sources=max([math.ceil(int(value)/per_source) for value in needed_rows.additional_needed_verified] or [1])
252
+ base_data=args.base_data_dir.expanduser().resolve();base_input=(args.base_input_dir.expanduser().resolve() if args.base_input_dir else base_data/"MILK10k_Training_Input")
253
+ if not base_input.exists():base_input=base_data.parent/"MILK10k_Training_Input"
254
+ header=["#!/usr/bin/env bash","set -euo pipefail","","# Generated commands. Review paths before running.",
255
+ f'BASE_DATA="{base_data}"',f'BASE_INPUT="{base_input}"',f'REPORT_DIR="{report_dir}"','CHECKPOINT_DIR="/path/to/convnext_5fold_run"',
256
+ 'GEN_DIR="$REPORT_DIR/generated_balance_pairs"','CANDIDATE_DIR="$REPORT_DIR/candidate_augmented"','FINAL_DIR="/path/to/milk10k_balanced"',""]
257
+ generate=[]
258
+ if classes:
259
+ generate += [f"# Planned classes: {classes}; planner applies exact caps after QC.",
260
+ f"python Stable_diffusion_augmentation/generate_milk10k_sd_pairs.py --data-dir \"$BASE_DATA\" --input-dir \"$BASE_INPUT\" --output-dir \"$GEN_DIR\" --class-names {classes} --num-per-lesion {per_source} --max-source-lesions {max_sources} --shuffle --skip-existing",""]
261
+ qc_materialize=["# QC outputs: $GEN_DIR/effb2_qc_predictions.csv and effb2_qc_summary.csv.",
262
+ "python Stable_diffusion_augmentation/run_effb2_qc.py --checkpoint-dir \"$CHECKPOINT_DIR\" --output-dir \"$GEN_DIR\"", "",
263
+ "python Stable_diffusion_augmentation/filter_paired_augmentation_by_qc.py --manifest \"$GEN_DIR/paired_augmentation_manifest.csv\" --qc-summary \"$GEN_DIR/effb2_qc_summary.csv\" --output \"$GEN_DIR/filtered_manifest.csv\" --min-target-prob 0.4 --require-target-pred", "",
264
+ "# Build a temporary complete MILK10k dataset from QC-passed pairs.",
265
+ "python Stable_diffusion_augmentation/materialize_augmented_milk10k_dataset.py --input-dir \"$BASE_INPUT\" --metadata-csv \"$BASE_DATA/MILK10k_Training_Metadata.csv\" --groundtruth-csv \"$BASE_DATA/MILK10k_Training_GroundTruth.csv\" --augmentation-manifest \"$GEN_DIR/filtered_manifest.csv\" --output-dir \"$CANDIDATE_DIR\" --symlink --synthetic-metadata neutral --overwrite", "",
266
+ "# Apply BCC stratified cap and final source/class caps into a separate dataset.",
267
+ "python Stable_diffusion_augmentation/plan_and_materialize_balanced_milk10k.py --base-data-dir \"$BASE_DATA\" --augmented-groundtruth \"$CANDIDATE_DIR/MILK10k_Training_GroundTruth.csv\" --augmented-metadata \"$CANDIDATE_DIR/MILK10k_Training_Metadata.csv\" --synthetic-input-dir \"$CANDIDATE_DIR/MILK10k_Training_Input\" --qc-summary \"$GEN_DIR/effb2_qc_summary.csv\" --report-dir \"$REPORT_DIR/final_audit\" --materialize-dir \"$FINAL_DIR\" --require-target-pred --overwrite", "",
268
+ "# Train safely: synthetic IDs stay train-only.",
269
+ "# python milk10k_effb2_dermoscopic_metadata/train_milk10k_effb2_dermoscopic_metadata.py --data-dir \"$FINAL_DIR\" --output-dir /path/to/run --split-manifest /path/to/run/split_v2.json --synthetic-train-only --metadata-mode none --loss ldam", ""]
270
+ scripts={"01_generate_pairs.sh":header+generate,"02_qc_and_materialize.sh":header+qc_materialize,
271
+ "run_balance_pipeline.sh":header+generate+qc_materialize}
272
+ for name,lines in scripts.items():
273
+ path=report_dir/name;path.write_text("\n".join(lines),encoding="utf-8");path.chmod(0o755)
274
+
275
+
276
+ def report_markdown(args, plan, sources, manifest, bcc_cap, usable_count, missing_pairs, missing_image_files):
277
+ warnings=[]
278
+ if args.qc_summary is None:warnings.append("QC summary was not provided; no synthetic row is considered verified usable.")
279
+ if args.synthetic_input_dir is None:warnings.append("Synthetic image root was not provided; materialization is disabled.")
280
+ if missing_pairs:warnings.append(f"Synthetic images missing: {missing_image_files} files across {missing_pairs} incomplete inventory pairs.")
281
+ warnings.append("MAL_OTH should use external/manual-reviewed data; do not scale SD from only a few source lesions.")
282
+ lines=["# MILK10k Balance Report","",f"- BCC static cap: {bcc_cap}",f"- verified usable synthetic lesions: {usable_count}",f"- source cap: {args.max_synthetic_per_source}",f"- synthetic/real cap: {args.max_synthetic_real_ratio}x","","## Warnings",""]+[f"- {x}" for x in warnings]
283
+ lines += ["","## Augmentation plan","","```",plan.to_string(index=False),"```","","## Source diversity","","```",sources.to_string(index=False),"```","","## Selection reasons","",manifest.selection_reason.value_counts().to_string(),""]
284
+ return "\n".join(lines)
285
+
286
+
287
+ def run(args):
288
+ if args.num_variants<1 or args.max_synthetic_per_source<1:raise ValueError("num variants and source cap must be positive.")
289
+ report_dir=args.report_dir.expanduser().resolve();report_dir.mkdir(parents=True,exist_ok=True)
290
+ base_gt_raw,base,base_meta,synth_gt,synth_meta,base_input=load_inventory(args)
291
+ synth=add_file_and_qc_status(args,synth_gt,synth_meta);real_counts=base.label.value_counts().to_dict()
292
+ inventory_selected=capped_synthetic(synth,real_counts,args,False);usable_selected=capped_synthetic(synth,real_counts,args,True)
293
+ plan,bcc_cap=plan_counts(base,synth,inventory_selected,usable_selected,args)
294
+ manifest=selection_manifest(synth,set(inventory_selected.lesion_id),set(usable_selected.lesion_id));sources=source_diversity(synth,inventory_selected)
295
+ variants=[];drifts=[]
296
+ materialize_error = None
297
+ if args.materialize_dir and len(inventory_selected) and not len(usable_selected):
298
+ materialize_error = ValueError(
299
+ "Materialization refused: synthetic inventory exists but no pair passed image/QC validation. "
300
+ "Check --synthetic-input-dir and --qc-summary; audit reports are still written."
301
+ )
302
+ for index in range(args.num_variants):
303
+ ids,bcc=bcc_strata(base_meta,base,bcc_cap,args.seed+index);selected_base=set(base.loc[~base.label.eq("BCC"),"lesion_id"].astype(str))|ids
304
+ variants.append(selected_base);drift=drift_table(bcc,ids);drift["variant"]=index;drifts.append(drift)
305
+ base[["lesion_id","label"]].assign(selected=lambda frame:frame.lesion_id.astype(str).isin(selected_base),variant=index).to_csv(report_dir/f"selected_base_manifest_variant_{index:02d}.csv",index=False)
306
+ if args.materialize_dir and materialize_error is None:
307
+ root=args.materialize_dir.expanduser().resolve();destination=root if args.num_variants==1 else root/f"variant_{index:02d}"
308
+ materialize_variant(destination,base_gt_raw,base_meta,selected_base,synth_gt,synth_meta,set(usable_selected.lesion_id),base_input,args.synthetic_input_dir.expanduser().resolve() if args.synthetic_input_dir else None,args)
309
+ plan.to_csv(report_dir/"augmentation_plan.csv",index=False);sources.to_csv(report_dir/"source_diversity.csv",index=False);manifest.to_csv(report_dir/"selected_synthetic_manifest.csv",index=False)
310
+ pd.concat(drifts,ignore_index=True).to_csv(report_dir/"bcc_distribution_drift.csv",index=False)
311
+ distribution=plan.copy();distribution.to_csv(report_dir/"class_distribution.csv",index=False);plot_reports(report_dir,distribution,sources)
312
+ missing_pairs=int((~synth.pair_files_complete).sum());missing_image_files=int((2-synth.existing_image_files.clip(upper=2)).sum())
313
+ payload={"policy":vars(args),"bcc_cap":bcc_cap,"inventory_lesions":len(synth),"usable_synthetic_lesions":len(usable_selected),"missing_image_pairs":missing_pairs,"missing_image_files":missing_image_files,"plan":plan.to_dict("records")}
314
+ payload["policy"]={k:str(v) if isinstance(v,Path) else v for k,v in payload["policy"].items()};(report_dir/"balance_plan.json").write_text(json.dumps(payload,indent=2),encoding="utf-8")
315
+ (report_dir/"balance_report.md").write_text(report_markdown(args,plan,sources,manifest,bcc_cap,len(usable_selected),missing_pairs,missing_image_files),encoding="utf-8")
316
+ command_script(args,plan,report_dir)
317
+ print(f"Base lesions: {len(base)}; synthetic inventory: {len(synth)}; verified usable: {len(usable_selected)}")
318
+ print(f"BCC cap: {bcc_cap}; reports: {report_dir}")
319
+ if materialize_error is not None:raise materialize_error
320
+ if args.materialize_dir:print(f"Materialized dataset: {args.materialize_dir.expanduser().resolve()}")
321
+ return {"plan":plan,"manifest":manifest,"bcc_cap":bcc_cap,"usable":usable_selected}
322
+
323
+
324
+ def main():run(parse_args())
325
+ if __name__=="__main__":main()
Stable_diffusion_augmentation/requirements.txt CHANGED
@@ -10,3 +10,5 @@ pandas
10
  numpy
11
  scikit-learn
12
  timm
 
 
 
10
  numpy
11
  scikit-learn
12
  timm
13
+ matplotlib
14
+ seaborn
Stable_diffusion_augmentation/run_effb2_qc.py CHANGED
@@ -13,7 +13,13 @@ from pathlib import Path
13
 
14
  def parse_args() -> argparse.Namespace:
15
  parser = argparse.ArgumentParser(description="Run EffB2 QC prediction and print confidence summary.")
16
- parser.add_argument("--checkpoint", type=Path, required=True, help="Path to EffB2 best.pt checkpoint.")
 
 
 
 
 
 
17
  parser.add_argument("--output-dir", type=Path, default=Path("Stable_diffusion_augmentation/out_minority_pairs"))
18
  parser.add_argument("--batch-size", type=int, default=16)
19
  parser.add_argument("--image-size", type=int, default=384)
@@ -129,7 +135,8 @@ def print_confidence_summary(summary_path: Path, print_misses: int) -> None:
129
  def main() -> None:
130
  args = parse_args()
131
  output_dir = args.output_dir.expanduser().resolve()
132
- checkpoint = args.checkpoint.expanduser().resolve()
 
133
  manifest = output_dir / "paired_augmentation_manifest.csv"
134
  metadata_csv = output_dir / "metadata_for_prediction.csv"
135
  groundtruth_csv = output_dir / "groundtruth_for_prediction.csv"
@@ -144,16 +151,19 @@ def main() -> None:
144
  "Summary script",
145
  )
146
 
147
- for path in (checkpoint, manifest, metadata_csv, groundtruth_csv, input_dir):
148
  if not path.exists():
149
  raise FileNotFoundError(f"Required QC input not found: {path}")
150
 
151
- run_command(
152
- [
153
  args.python,
154
  str(predict_script),
155
- "--checkpoint",
156
- str(checkpoint),
 
 
 
 
157
  "--input-dir",
158
  str(input_dir),
159
  "--metadata-csv",
@@ -169,8 +179,8 @@ def main() -> None:
169
  str(args.image_size),
170
  "--num-workers",
171
  str(args.num_workers),
172
- ]
173
- )
174
  run_command(
175
  [
176
  args.python,
 
13
 
14
  def parse_args() -> argparse.Namespace:
15
  parser = argparse.ArgumentParser(description="Run EffB2 QC prediction and print confidence summary.")
16
+ checkpoint_group = parser.add_mutually_exclusive_group(required=True)
17
+ checkpoint_group.add_argument("--checkpoint", type=Path, help="Path to one classifier best.pt checkpoint.")
18
+ checkpoint_group.add_argument(
19
+ "--checkpoint-dir",
20
+ type=Path,
21
+ help="Run directory containing fold_*/best.pt; all folds are ensembled for QC.",
22
+ )
23
  parser.add_argument("--output-dir", type=Path, default=Path("Stable_diffusion_augmentation/out_minority_pairs"))
24
  parser.add_argument("--batch-size", type=int, default=16)
25
  parser.add_argument("--image-size", type=int, default=384)
 
135
  def main() -> None:
136
  args = parse_args()
137
  output_dir = args.output_dir.expanduser().resolve()
138
+ checkpoint = args.checkpoint.expanduser().resolve() if args.checkpoint else None
139
+ checkpoint_dir = args.checkpoint_dir.expanduser().resolve() if args.checkpoint_dir else None
140
  manifest = output_dir / "paired_augmentation_manifest.csv"
141
  metadata_csv = output_dir / "metadata_for_prediction.csv"
142
  groundtruth_csv = output_dir / "groundtruth_for_prediction.csv"
 
151
  "Summary script",
152
  )
153
 
154
+ for path in (checkpoint or checkpoint_dir, manifest, metadata_csv, groundtruth_csv, input_dir):
155
  if not path.exists():
156
  raise FileNotFoundError(f"Required QC input not found: {path}")
157
 
158
+ predict_command = [
 
159
  args.python,
160
  str(predict_script),
161
+ ]
162
+ if checkpoint is not None:
163
+ predict_command.extend(["--checkpoint", str(checkpoint)])
164
+ else:
165
+ predict_command.extend(["--checkpoint-dir", str(checkpoint_dir)])
166
+ predict_command.extend([
167
  "--input-dir",
168
  str(input_dir),
169
  "--metadata-csv",
 
179
  str(args.image_size),
180
  "--num-workers",
181
  str(args.num_workers),
182
+ ])
183
+ run_command(predict_command)
184
  run_command(
185
  [
186
  args.python,
Stable_diffusion_augmentation/tests/test_balance_planner.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import sys,tempfile,unittest
3
+ from pathlib import Path
4
+ import numpy as np,pandas as pd
5
+ from PIL import Image
6
+
7
+ sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
8
+ from plan_and_materialize_balanced_milk10k import LABEL_COLUMNS,parse_args,run
9
+
10
+
11
+ def gt_row(lesion,label):
12
+ return {"lesion_id":lesion,**{name:float(name==label) for name in LABEL_COLUMNS}}
13
+
14
+
15
+ def image(path,value):
16
+ path.parent.mkdir(parents=True,exist_ok=True);Image.fromarray(np.full((8,8,3),value,dtype=np.uint8)).save(path)
17
+
18
+
19
+ def fixture(root,missing_synthetic=False):
20
+ base=root/"base";images=base/"MILK10k_Training_Input";base.mkdir()
21
+ labels=["BCC"]*10+["NV"]*4+["BEN_OTH"]*2
22
+ gt=[];meta=[]
23
+ for i,label in enumerate(labels):
24
+ lesion=f"L{i}";gt.append(gt_row(lesion,label))
25
+ for modality,suffix in (("clinical: close-up","c"),("dermoscopic","d")):
26
+ isic=f"{lesion}_{suffix}";meta.append({"lesion_id":lesion,"image_type":modality,"isic_id":isic,"age_approx":40+i,"sex":"x","skin_tone_class":2,"site":"arm"});image(images/lesion/f"{isic}.jpg",80+i)
27
+ pd.DataFrame(gt).to_csv(base/"MILK10k_Training_GroundTruth.csv",index=False);pd.DataFrame(meta).to_csv(base/"MILK10k_Training_Metadata.csv",index=False)
28
+ synth_root=root/"synthetic";aug_gt=list(gt);aug_meta=list(meta);qc=[]
29
+ for i in range(4):
30
+ lesion=f"L{10+i%2}__sdpair_{i:03d}";aug_gt.append(gt_row(lesion,"BEN_OTH"))
31
+ for modality,suffix in (("clinical: close-up","clinical"),("dermoscopic","dermoscopic")):
32
+ isic=f"{lesion}__{suffix}";aug_meta.append({"lesion_id":lesion,"image_type":modality,"isic_id":isic,"age_approx":"","sex":"unknown","skin_tone_class":"","site":"unknown"})
33
+ if not missing_synthetic:image(synth_root/lesion/f"{isic}.jpg",120+i)
34
+ qc.append({"synthetic_lesion_id":lesion,"target_class_probability":.9-i*.1,"is_target_predicted":"True"})
35
+ info=base/"augmented_info";info.mkdir();pd.DataFrame(aug_gt).to_csv(info/"MILK10k_Training_GroundTruth(2).csv",index=False);pd.DataFrame(aug_meta).to_csv(info/"MILK10k_Training_Metadata(3).csv",index=False)
36
+ qc_path=root/"qc.csv";pd.DataFrame(qc).to_csv(qc_path,index=False)
37
+ return base,synth_root,qc_path
38
+
39
+
40
+ class BalancePlannerTests(unittest.TestCase):
41
+ def test_caps_qc_reproducibility_and_hardlink_materialization(self):
42
+ with tempfile.TemporaryDirectory() as tmp:
43
+ root=Path(tmp);base,synth,qc=fixture(root)
44
+ outputs=[]
45
+ for index in range(2):
46
+ report=root/f"report{index}";materialized=root/f"out{index}"
47
+ args=parse_args(["--base-data-dir",str(base),"--synthetic-input-dir",str(synth),"--qc-summary",str(qc),"--report-dir",str(report),"--materialize-dir",str(materialized),"--max-synthetic-per-source","1","--seed","7"])
48
+ result=run(args);outputs.append(pd.read_csv(materialized/"MILK10k_Training_GroundTruth.csv"))
49
+ self.assertEqual(result["bcc_cap"],6);self.assertLessEqual(len(result["usable"]),2)
50
+ self.assertTrue((report/"class_distribution.png").exists());self.assertTrue((report/"run_balance_pipeline.sh").exists())
51
+ first=materialized/"MILK10k_Training_Input/L0/L0_c.jpg";self.assertEqual(first.stat().st_ino,(base/"MILK10k_Training_Input/L0/L0_c.jpg").stat().st_ino)
52
+ self.assertEqual(set(outputs[0].lesion_id),set(outputs[1].lesion_id))
53
+
54
+ def test_materialization_refuses_missing_synthetic_pairs(self):
55
+ with tempfile.TemporaryDirectory() as tmp:
56
+ root=Path(tmp);base,synth,qc=fixture(root,True)
57
+ args=parse_args(["--base-data-dir",str(base),"--synthetic-input-dir",str(synth),"--qc-summary",str(qc),"--report-dir",str(root/"report"),"--materialize-dir",str(root/"out")])
58
+ with self.assertRaises((ValueError,FileNotFoundError)):run(args)
59
+
60
+ def test_audit_without_images_reports_inventory_but_no_usable(self):
61
+ with tempfile.TemporaryDirectory() as tmp:
62
+ root=Path(tmp);base,_,_=fixture(root)
63
+ result=run(parse_args(["--base-data-dir",str(base),"--report-dir",str(root/"report")]))
64
+ self.assertEqual(len(result["manifest"]),4);self.assertEqual(len(result["usable"]),0)
65
+
66
+
67
+ if __name__=="__main__":unittest.main()