Upload 21 files
Browse files- Stable_diffusion_augmentation/__pycache__/materialize_augmented_milk10k_dataset.cpython-314.pyc +0 -0
- Stable_diffusion_augmentation/__pycache__/merge_paired_augmentation_manifests.cpython-314.pyc +0 -0
- Stable_diffusion_augmentation/materialize_augmented_milk10k_dataset.py +200 -0
- Stable_diffusion_augmentation/merge_paired_augmentation_manifests.py +87 -0
Stable_diffusion_augmentation/__pycache__/materialize_augmented_milk10k_dataset.cpython-314.pyc
ADDED
|
Binary file (12 kB). View file
|
|
|
Stable_diffusion_augmentation/__pycache__/merge_paired_augmentation_manifests.cpython-314.pyc
ADDED
|
Binary file (6.48 kB). View file
|
|
|
Stable_diffusion_augmentation/materialize_augmented_milk10k_dataset.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Create a MILK10k-style dataset folder with original + synthetic paired augmentations."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import csv
|
| 8 |
+
import shutil
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
LABEL_COLUMNS = [
|
| 13 |
+
"AKIEC",
|
| 14 |
+
"BCC",
|
| 15 |
+
"BEN_OTH",
|
| 16 |
+
"BKL",
|
| 17 |
+
"DF",
|
| 18 |
+
"INF",
|
| 19 |
+
"MAL_OTH",
|
| 20 |
+
"MEL",
|
| 21 |
+
"NV",
|
| 22 |
+
"SCCKA",
|
| 23 |
+
"VASC",
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
NEUTRAL_METADATA = {
|
| 27 |
+
"age_approx": "",
|
| 28 |
+
"sex": "unknown",
|
| 29 |
+
"skin_tone_class": "",
|
| 30 |
+
"site": "unknown",
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def parse_args() -> argparse.Namespace:
|
| 35 |
+
parser = argparse.ArgumentParser(description="Materialize original + synthetic data as a MILK10k-style dataset.")
|
| 36 |
+
parser.add_argument("--input-dir", type=Path, required=True, help="Original MILK10k_Training_Input folder.")
|
| 37 |
+
parser.add_argument("--metadata-csv", type=Path, required=True, help="Original MILK10k_Training_Metadata.csv.")
|
| 38 |
+
parser.add_argument("--groundtruth-csv", type=Path, required=True, help="Original MILK10k_Training_GroundTruth.csv.")
|
| 39 |
+
parser.add_argument("--augmentation-manifest", type=Path, required=True, help="Paired augmentation manifest to add.")
|
| 40 |
+
parser.add_argument("--output-dir", type=Path, required=True, help="Output MILK10k-style dataset folder.")
|
| 41 |
+
parser.add_argument(
|
| 42 |
+
"--symlink",
|
| 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 |
+
|
| 49 |
+
|
| 50 |
+
def read_rows(path: Path) -> list[dict[str, str]]:
|
| 51 |
+
with path.open(newline="") as f:
|
| 52 |
+
return list(csv.DictReader(f))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def write_rows(path: Path, rows: list[dict[str, str]], fieldnames: list[str]) -> None:
|
| 56 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 57 |
+
with path.open("w", newline="") as f:
|
| 58 |
+
writer = csv.DictWriter(f, fieldnames=fieldnames)
|
| 59 |
+
writer.writeheader()
|
| 60 |
+
writer.writerows(rows)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def link_or_copy(src: Path, dst: Path, copy_file: bool, overwrite: bool) -> None:
|
| 64 |
+
if not src.exists():
|
| 65 |
+
raise FileNotFoundError(f"Source image not found: {src}")
|
| 66 |
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
| 67 |
+
if dst.exists() or dst.is_symlink():
|
| 68 |
+
if not overwrite:
|
| 69 |
+
return
|
| 70 |
+
dst.unlink()
|
| 71 |
+
if copy_file:
|
| 72 |
+
shutil.copy2(src, dst)
|
| 73 |
+
else:
|
| 74 |
+
dst.symlink_to(src.resolve())
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def original_image_path(input_dir: Path, row: dict[str, str]) -> Path:
|
| 78 |
+
return input_dir / row["lesion_id"] / f"{row['isic_id']}.jpg"
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def synthetic_metadata_row(
|
| 82 |
+
columns: list[str],
|
| 83 |
+
lesion_id: str,
|
| 84 |
+
image_type: str,
|
| 85 |
+
isic_id: str,
|
| 86 |
+
) -> dict[str, str]:
|
| 87 |
+
row = {column: "" for column in columns}
|
| 88 |
+
row["lesion_id"] = lesion_id
|
| 89 |
+
row["image_type"] = image_type
|
| 90 |
+
row["isic_id"] = isic_id
|
| 91 |
+
if "attribution" in row:
|
| 92 |
+
row["attribution"] = "Stable Diffusion synthetic augmentation"
|
| 93 |
+
if "copyright_license" in row:
|
| 94 |
+
row["copyright_license"] = "synthetic"
|
| 95 |
+
if "image_manipulation" in row:
|
| 96 |
+
row["image_manipulation"] = "synthetic"
|
| 97 |
+
for key, value in NEUTRAL_METADATA.items():
|
| 98 |
+
if key in row:
|
| 99 |
+
row[key] = value
|
| 100 |
+
for column in columns:
|
| 101 |
+
if column.startswith("MONET_"):
|
| 102 |
+
row[column] = "0"
|
| 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
|
| 109 |
+
for class_column in LABEL_COLUMNS:
|
| 110 |
+
if class_column in row:
|
| 111 |
+
row[class_column] = "1.0" if class_column == class_name else "0.0"
|
| 112 |
+
return row
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def materialize_original_images(input_dir: Path, output_input_dir: Path, metadata_rows: list[dict[str, str]], copy_file: bool, overwrite: bool) -> None:
|
| 116 |
+
for row in metadata_rows:
|
| 117 |
+
src = original_image_path(input_dir, row)
|
| 118 |
+
dst = output_input_dir / row["lesion_id"] / f"{row['isic_id']}.jpg"
|
| 119 |
+
link_or_copy(src, dst, copy_file, overwrite)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
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,
|
| 129 |
+
) -> tuple[list[dict[str, str]], list[dict[str, str]]]:
|
| 130 |
+
metadata_rows = []
|
| 131 |
+
groundtruth_rows = []
|
| 132 |
+
seen_lesions = set()
|
| 133 |
+
|
| 134 |
+
for row in manifest_rows:
|
| 135 |
+
lesion_id = row["synthetic_lesion_id"]
|
| 136 |
+
clinical_isic_id = row.get("clinical_synthetic_isic_id") or f"{lesion_id}__clinical"
|
| 137 |
+
dermoscopic_isic_id = row.get("dermoscopic_synthetic_isic_id") or f"{lesion_id}__dermoscopic"
|
| 138 |
+
|
| 139 |
+
clinical_dst = output_input_dir / lesion_id / f"{clinical_isic_id}.jpg"
|
| 140 |
+
dermoscopic_dst = output_input_dir / lesion_id / f"{dermoscopic_isic_id}.jpg"
|
| 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)
|
| 149 |
+
|
| 150 |
+
return metadata_rows, groundtruth_rows
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def main() -> None:
|
| 154 |
+
args = parse_args()
|
| 155 |
+
input_dir = args.input_dir.expanduser().resolve()
|
| 156 |
+
metadata_csv = args.metadata_csv.expanduser().resolve()
|
| 157 |
+
groundtruth_csv = args.groundtruth_csv.expanduser().resolve()
|
| 158 |
+
augmentation_manifest = args.augmentation_manifest.expanduser().resolve()
|
| 159 |
+
output_dir = args.output_dir.expanduser().resolve()
|
| 160 |
+
output_input_dir = output_dir / "MILK10k_Training_Input"
|
| 161 |
+
|
| 162 |
+
metadata_rows = read_rows(metadata_csv)
|
| 163 |
+
groundtruth_rows = read_rows(groundtruth_csv)
|
| 164 |
+
manifest_rows = read_rows(augmentation_manifest)
|
| 165 |
+
if not manifest_rows:
|
| 166 |
+
raise ValueError(f"No augmentation rows found: {augmentation_manifest}")
|
| 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)
|
| 173 |
+
synthetic_metadata_rows, synthetic_groundtruth_rows = materialize_synthetic_rows(
|
| 174 |
+
manifest_rows,
|
| 175 |
+
metadata_columns,
|
| 176 |
+
groundtruth_columns,
|
| 177 |
+
output_input_dir,
|
| 178 |
+
copy_file,
|
| 179 |
+
args.overwrite,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
all_metadata_rows = metadata_rows + synthetic_metadata_rows
|
| 183 |
+
all_groundtruth_rows = groundtruth_rows + synthetic_groundtruth_rows
|
| 184 |
+
write_rows(output_dir / "MILK10k_Training_Metadata.csv", all_metadata_rows, metadata_columns)
|
| 185 |
+
write_rows(output_dir / "MILK10k_Training_GroundTruth.csv", all_groundtruth_rows, groundtruth_columns)
|
| 186 |
+
|
| 187 |
+
print("Materialized augmented MILK10k dataset")
|
| 188 |
+
print(f" output_dir: {output_dir}")
|
| 189 |
+
print(f" original metadata rows: {len(metadata_rows)}")
|
| 190 |
+
print(f" synthetic metadata rows: {len(synthetic_metadata_rows)}")
|
| 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}")
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
if __name__ == "__main__":
|
| 200 |
+
main()
|
Stable_diffusion_augmentation/merge_paired_augmentation_manifests.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Merge paired augmentation manifests for training."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import csv
|
| 8 |
+
from collections import Counter
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def parse_args() -> argparse.Namespace:
|
| 13 |
+
parser = argparse.ArgumentParser(description="Merge paired augmentation manifests into one training manifest.")
|
| 14 |
+
parser.add_argument("--manifest", type=Path, action="append", required=True, help="Input manifest. Pass multiple times.")
|
| 15 |
+
parser.add_argument("--output", type=Path, required=True, help="Merged output manifest.")
|
| 16 |
+
parser.add_argument(
|
| 17 |
+
"--replace-class",
|
| 18 |
+
action="append",
|
| 19 |
+
default=[],
|
| 20 |
+
help="For this class, keep rows only from the last input manifest containing that class. Can be repeated.",
|
| 21 |
+
)
|
| 22 |
+
parser.add_argument("--dedupe", action="store_true", help="Drop duplicate synthetic_lesion_id rows, keeping later inputs.")
|
| 23 |
+
return parser.parse_args()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def read_manifest(path: Path, input_index: int) -> list[dict[str, str]]:
|
| 27 |
+
with path.open(newline="") as f:
|
| 28 |
+
rows = list(csv.DictReader(f))
|
| 29 |
+
for row in rows:
|
| 30 |
+
row["_input_index"] = str(input_index)
|
| 31 |
+
row["_input_manifest"] = str(path)
|
| 32 |
+
return rows
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def class_counts(rows: list[dict[str, str]]) -> dict[str, int]:
|
| 36 |
+
return dict(sorted(Counter(row["class_name"] for row in rows).items()))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def main() -> None:
|
| 40 |
+
args = parse_args()
|
| 41 |
+
manifests = [path.expanduser().resolve() for path in args.manifest]
|
| 42 |
+
for path in manifests:
|
| 43 |
+
if not path.exists():
|
| 44 |
+
raise FileNotFoundError(f"Manifest not found: {path}")
|
| 45 |
+
|
| 46 |
+
rows_by_input = [read_manifest(path, idx) for idx, path in enumerate(manifests)]
|
| 47 |
+
rows = [row for group in rows_by_input for row in group]
|
| 48 |
+
if not rows:
|
| 49 |
+
raise ValueError("No rows found in input manifests.")
|
| 50 |
+
|
| 51 |
+
replace_classes = set(args.replace_class)
|
| 52 |
+
if replace_classes:
|
| 53 |
+
last_input_for_class: dict[str, int] = {}
|
| 54 |
+
for row in rows:
|
| 55 |
+
class_name = row["class_name"]
|
| 56 |
+
if class_name in replace_classes:
|
| 57 |
+
last_input_for_class[class_name] = int(row["_input_index"])
|
| 58 |
+
rows = [
|
| 59 |
+
row
|
| 60 |
+
for row in rows
|
| 61 |
+
if row["class_name"] not in replace_classes
|
| 62 |
+
or int(row["_input_index"]) == last_input_for_class.get(row["class_name"])
|
| 63 |
+
]
|
| 64 |
+
|
| 65 |
+
if args.dedupe:
|
| 66 |
+
by_id = {row["synthetic_lesion_id"]: row for row in rows}
|
| 67 |
+
rows = list(by_id.values())
|
| 68 |
+
|
| 69 |
+
output = args.output.expanduser().resolve()
|
| 70 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 71 |
+
fieldnames = [key for key in rows[0].keys() if not key.startswith("_")]
|
| 72 |
+
with output.open("w", newline="") as f:
|
| 73 |
+
writer = csv.DictWriter(f, fieldnames=fieldnames)
|
| 74 |
+
writer.writeheader()
|
| 75 |
+
for row in rows:
|
| 76 |
+
writer.writerow({key: row.get(key, "") for key in fieldnames})
|
| 77 |
+
|
| 78 |
+
print("Merged paired augmentation manifests")
|
| 79 |
+
for path, group in zip(manifests, rows_by_input):
|
| 80 |
+
print(f" input: {path}")
|
| 81 |
+
print(f" rows={len(group)}, classes={class_counts(group)}")
|
| 82 |
+
print(f" output: {output}")
|
| 83 |
+
print(f" rows={len(rows)}, classes={class_counts(rows)}")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
if __name__ == "__main__":
|
| 87 |
+
main()
|