Upload 15 files
Browse files- Stable_diffusion_augmentation/README.md +8 -0
- Stable_diffusion_augmentation/__pycache__/generate_milk10k_sd.cpython-314.pyc +0 -0
- Stable_diffusion_augmentation/__pycache__/generate_milk10k_sd_pairs.cpython-314.pyc +0 -0
- Stable_diffusion_augmentation/generate_milk10k_sd.py +39 -2
- Stable_diffusion_augmentation/generate_milk10k_sd_pairs.py +144 -7
- Stable_diffusion_augmentation/requirements.txt +12 -0
Stable_diffusion_augmentation/README.md
CHANGED
|
@@ -85,6 +85,14 @@ Cài dependency:
|
|
| 85 |
pip install torch diffusers transformers accelerate pillow tqdm
|
| 86 |
```
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
Sinh ảnh clinical cho class `MEL`:
|
| 89 |
|
| 90 |
```bash
|
|
|
|
| 85 |
pip install torch diffusers transformers accelerate pillow tqdm
|
| 86 |
```
|
| 87 |
|
| 88 |
+
Nếu gặp lỗi kiểu `No module named 'flash_attn.flash_attn_interface'`, thường là do `xformers` bị lệch với Python/torch. Với pipeline này `xformers` là optional, cách sửa nhanh là gỡ nó:
|
| 89 |
+
|
| 90 |
+
```bash
|
| 91 |
+
pip uninstall -y xformers flash-attn
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
Trên Python 3.13, nên chạy trước không có `xformers`; script vẫn bật attention slicing trên CUDA.
|
| 95 |
+
|
| 96 |
Sinh ảnh clinical cho class `MEL`:
|
| 97 |
|
| 98 |
```bash
|
Stable_diffusion_augmentation/__pycache__/generate_milk10k_sd.cpython-314.pyc
CHANGED
|
Binary files a/Stable_diffusion_augmentation/__pycache__/generate_milk10k_sd.cpython-314.pyc and b/Stable_diffusion_augmentation/__pycache__/generate_milk10k_sd.cpython-314.pyc differ
|
|
|
Stable_diffusion_augmentation/__pycache__/generate_milk10k_sd_pairs.cpython-314.pyc
CHANGED
|
Binary files a/Stable_diffusion_augmentation/__pycache__/generate_milk10k_sd_pairs.cpython-314.pyc and b/Stable_diffusion_augmentation/__pycache__/generate_milk10k_sd_pairs.cpython-314.pyc differ
|
|
|
Stable_diffusion_augmentation/generate_milk10k_sd.py
CHANGED
|
@@ -120,6 +120,11 @@ def parse_args() -> argparse.Namespace:
|
|
| 120 |
),
|
| 121 |
)
|
| 122 |
parser.add_argument("--fp32", action="store_true", help="Use float32 instead of fp16 on CUDA.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
parser.add_argument(
|
| 124 |
"--disable-safety-checker",
|
| 125 |
action="store_true",
|
|
@@ -179,7 +184,18 @@ def load_class_rows(data_dir: Path, class_name: str, image_type: str) -> list[di
|
|
| 179 |
|
| 180 |
def load_pipeline(args: argparse.Namespace):
|
| 181 |
import torch
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
model_id = resolve_model_id(args)
|
| 185 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
@@ -215,6 +231,14 @@ def prepare_image(path: Path, size: int) -> Image.Image:
|
|
| 215 |
return ImageOps.fit(img, (size, size), method=Image.Resampling.LANCZOS)
|
| 216 |
|
| 217 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
def main() -> None:
|
| 219 |
args = parse_args()
|
| 220 |
import torch
|
|
@@ -228,6 +252,11 @@ def main() -> None:
|
|
| 228 |
output_dir = args.output_dir.expanduser().resolve()
|
| 229 |
image_dir = output_dir / args.class_name / args.image_type
|
| 230 |
image_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
|
| 232 |
rows = load_class_rows(data_dir, args.class_name, args.image_type)
|
| 233 |
if args.shuffle:
|
|
@@ -279,7 +308,15 @@ def main() -> None:
|
|
| 279 |
)
|
| 280 |
out_name = f"{row['lesion_id']}_{row['isic_id']}_sd_{aug_idx:02d}_seed{seed}.jpg"
|
| 281 |
out_path = image_dir / out_name
|
| 282 |
-
result.images[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
|
| 284 |
writer.writerow(
|
| 285 |
{
|
|
|
|
| 120 |
),
|
| 121 |
)
|
| 122 |
parser.add_argument("--fp32", action="store_true", help="Use float32 instead of fp16 on CUDA.")
|
| 123 |
+
parser.add_argument(
|
| 124 |
+
"--allow-black-images",
|
| 125 |
+
action="store_true",
|
| 126 |
+
help="Allow nearly black outputs. By default these fail because they usually mean safety-checker blocking.",
|
| 127 |
+
)
|
| 128 |
parser.add_argument(
|
| 129 |
"--disable-safety-checker",
|
| 130 |
action="store_true",
|
|
|
|
| 184 |
|
| 185 |
def load_pipeline(args: argparse.Namespace):
|
| 186 |
import torch
|
| 187 |
+
try:
|
| 188 |
+
from diffusers import StableDiffusionImg2ImgPipeline
|
| 189 |
+
except RuntimeError as exc:
|
| 190 |
+
message = str(exc)
|
| 191 |
+
if "flash_attn.flash_attn_interface" in message or "xformers" in message:
|
| 192 |
+
raise RuntimeError(
|
| 193 |
+
"Diffusers failed while importing xformers/flash-attn. xformers is optional for this script; "
|
| 194 |
+
"your install appears broken. Fix with:\n\n"
|
| 195 |
+
" pip uninstall -y xformers flash-attn\n\n"
|
| 196 |
+
"Then rerun. The script still enables attention slicing on CUDA."
|
| 197 |
+
) from exc
|
| 198 |
+
raise
|
| 199 |
|
| 200 |
model_id = resolve_model_id(args)
|
| 201 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
| 231 |
return ImageOps.fit(img, (size, size), method=Image.Resampling.LANCZOS)
|
| 232 |
|
| 233 |
|
| 234 |
+
def looks_like_blocked_black_image(image: Image.Image) -> bool:
|
| 235 |
+
stat_image = image.convert("L").resize((32, 32), method=Image.Resampling.BILINEAR)
|
| 236 |
+
pixels = list(stat_image.getdata())
|
| 237 |
+
mean_value = sum(pixels) / max(len(pixels), 1)
|
| 238 |
+
bright_pixels = sum(1 for value in pixels if value > 8)
|
| 239 |
+
return mean_value < 3.0 and bright_pixels / max(len(pixels), 1) < 0.01
|
| 240 |
+
|
| 241 |
+
|
| 242 |
def main() -> None:
|
| 243 |
args = parse_args()
|
| 244 |
import torch
|
|
|
|
| 252 |
output_dir = args.output_dir.expanduser().resolve()
|
| 253 |
image_dir = output_dir / args.class_name / args.image_type
|
| 254 |
image_dir.mkdir(parents=True, exist_ok=True)
|
| 255 |
+
if not args.disable_safety_checker:
|
| 256 |
+
print(
|
| 257 |
+
"Warning: diffusers safety checker is enabled. Clinical/dermoscopic skin images may be falsely "
|
| 258 |
+
"blocked and returned as black images. If that happens, rerun with --disable-safety-checker."
|
| 259 |
+
)
|
| 260 |
|
| 261 |
rows = load_class_rows(data_dir, args.class_name, args.image_type)
|
| 262 |
if args.shuffle:
|
|
|
|
| 308 |
)
|
| 309 |
out_name = f"{row['lesion_id']}_{row['isic_id']}_sd_{aug_idx:02d}_seed{seed}.jpg"
|
| 310 |
out_path = image_dir / out_name
|
| 311 |
+
image = result.images[0]
|
| 312 |
+
if not args.allow_black_images and looks_like_blocked_black_image(image):
|
| 313 |
+
raise RuntimeError(
|
| 314 |
+
"Stable Diffusion returned a nearly black image. This usually means the default safety checker "
|
| 315 |
+
"blocked a clinical skin image as NSFW. Rerun with:\n\n"
|
| 316 |
+
" --disable-safety-checker\n\n"
|
| 317 |
+
f"Blocked output path would have been: {out_path}"
|
| 318 |
+
)
|
| 319 |
+
image.save(out_path, quality=95)
|
| 320 |
|
| 321 |
writer.writerow(
|
| 322 |
{
|
Stable_diffusion_augmentation/generate_milk10k_sd_pairs.py
CHANGED
|
@@ -26,6 +26,7 @@ ImageFile.LOAD_TRUNCATED_IMAGES = True
|
|
| 26 |
|
| 27 |
DEFAULT_MINORITY_CLASSES = ["MAL_OTH", "BEN_OTH", "VASC", "INF", "DF"]
|
| 28 |
MODALITIES = ("clinical_close_up", "dermoscopic")
|
|
|
|
| 29 |
NEUTRAL_METADATA = {
|
| 30 |
"age_approx": "",
|
| 31 |
"sex": "unknown",
|
|
@@ -80,6 +81,12 @@ def parse_args() -> argparse.Namespace:
|
|
| 80 |
parser.add_argument("--clinical-lora-scale", type=float, default=1.0)
|
| 81 |
parser.add_argument("--dermoscopic-lora-scale", type=float, default=1.0)
|
| 82 |
parser.add_argument("--skip-existing", action="store_true", help="Do not regenerate images that already exist.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
parser.add_argument("--fp32", action="store_true", help="Use float32 instead of fp16 on CUDA.")
|
| 84 |
parser.add_argument("--disable-safety-checker", action="store_true")
|
| 85 |
return parser.parse_args()
|
|
@@ -114,10 +121,34 @@ def read_labels(gt_path: Path) -> dict[str, str]:
|
|
| 114 |
return labels
|
| 115 |
|
| 116 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
def load_paired_rows(input_dir: Path, gt_path: Path, meta_path: Path, class_names: list[str]) -> tuple[list[dict[str, str]], list[str]]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
labels = read_labels(gt_path)
|
| 119 |
selected = {lesion_id for lesion_id, label in labels.items() if label in class_names}
|
| 120 |
by_lesion: dict[str, dict[str, dict[str, str]]] = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
with meta_path.open(newline="") as f:
|
| 123 |
reader = csv.DictReader(f)
|
|
@@ -126,12 +157,18 @@ def load_paired_rows(input_dir: Path, gt_path: Path, meta_path: Path, class_name
|
|
| 126 |
lesion_id = row["lesion_id"]
|
| 127 |
if lesion_id not in selected:
|
| 128 |
continue
|
|
|
|
|
|
|
| 129 |
image_type = normalize_image_type(row["image_type"])
|
|
|
|
| 130 |
if image_type not in MODALITIES:
|
| 131 |
continue
|
| 132 |
-
source_path = input_dir
|
| 133 |
-
if
|
|
|
|
|
|
|
| 134 |
continue
|
|
|
|
| 135 |
copied = dict(row)
|
| 136 |
copied["source_path"] = str(source_path)
|
| 137 |
copied["image_type_norm"] = image_type
|
|
@@ -151,9 +188,71 @@ def load_paired_rows(input_dir: Path, gt_path: Path, meta_path: Path, class_name
|
|
| 151 |
}
|
| 152 |
)
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
|
| 159 |
def select_rows(rows: list[dict[str, str]], class_names: list[str], max_source_lesions: int | None, shuffle: bool, seed: int):
|
|
@@ -288,7 +387,20 @@ def log_generation_plan(
|
|
| 288 |
|
| 289 |
def load_pipeline(args: argparse.Namespace, lora_weights: Path | None, lora_scale: float):
|
| 290 |
import torch
|
| 291 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 294 |
dtype = torch.float32 if device == "cpu" or args.fp32 else torch.float16
|
|
@@ -316,6 +428,14 @@ def prepare_image(path: Path, size: int) -> Image.Image:
|
|
| 316 |
return ImageOps.fit(img.convert("RGB"), (size, size), method=Image.Resampling.LANCZOS)
|
| 317 |
|
| 318 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
def modality_prompt(args: argparse.Namespace, class_name: str, modality: str) -> str:
|
| 320 |
if modality == "clinical_close_up" and args.clinical_prompt:
|
| 321 |
return args.clinical_prompt
|
|
@@ -361,7 +481,15 @@ def generate_modality(tasks: list[dict[str, str | int]], args: argparse.Namespac
|
|
| 361 |
num_inference_steps=args.steps,
|
| 362 |
generator=generator,
|
| 363 |
)
|
| 364 |
-
result.images[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
generated += 1
|
| 366 |
|
| 367 |
del pipe
|
|
@@ -480,8 +608,17 @@ def main() -> None:
|
|
| 480 |
raise ValueError("--strength must be in [0, 1]")
|
| 481 |
|
| 482 |
args.output_dir = args.output_dir.expanduser().resolve()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 483 |
|
| 484 |
input_dir, gt_path, meta_path = resolve_data_paths(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
all_rows, metadata_columns = load_paired_rows(input_dir, gt_path, meta_path, args.class_names)
|
| 486 |
rows = select_rows(all_rows, args.class_names, args.max_source_lesions, args.shuffle, args.seed)
|
| 487 |
tasks = build_tasks(rows, args)
|
|
|
|
| 26 |
|
| 27 |
DEFAULT_MINORITY_CLASSES = ["MAL_OTH", "BEN_OTH", "VASC", "INF", "DF"]
|
| 28 |
MODALITIES = ("clinical_close_up", "dermoscopic")
|
| 29 |
+
IMAGE_EXTENSIONS = (".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG")
|
| 30 |
NEUTRAL_METADATA = {
|
| 31 |
"age_approx": "",
|
| 32 |
"sex": "unknown",
|
|
|
|
| 81 |
parser.add_argument("--clinical-lora-scale", type=float, default=1.0)
|
| 82 |
parser.add_argument("--dermoscopic-lora-scale", type=float, default=1.0)
|
| 83 |
parser.add_argument("--skip-existing", action="store_true", help="Do not regenerate images that already exist.")
|
| 84 |
+
parser.add_argument("--diagnose-data", action="store_true", help="Print data matching diagnostics and exit before diffusion.")
|
| 85 |
+
parser.add_argument(
|
| 86 |
+
"--allow-black-images",
|
| 87 |
+
action="store_true",
|
| 88 |
+
help="Allow nearly black outputs. By default these fail because they usually mean the safety checker blocked a medical skin image.",
|
| 89 |
+
)
|
| 90 |
parser.add_argument("--fp32", action="store_true", help="Use float32 instead of fp16 on CUDA.")
|
| 91 |
parser.add_argument("--disable-safety-checker", action="store_true")
|
| 92 |
return parser.parse_args()
|
|
|
|
| 121 |
return labels
|
| 122 |
|
| 123 |
|
| 124 |
+
def resolve_source_image(input_dir: Path, lesion_id: str, isic_id: str) -> Path | None:
|
| 125 |
+
for suffix in IMAGE_EXTENSIONS:
|
| 126 |
+
path = input_dir / lesion_id / f"{isic_id}{suffix}"
|
| 127 |
+
if path.exists():
|
| 128 |
+
return path
|
| 129 |
+
return None
|
| 130 |
+
|
| 131 |
+
|
| 132 |
def load_paired_rows(input_dir: Path, gt_path: Path, meta_path: Path, class_names: list[str]) -> tuple[list[dict[str, str]], list[str]]:
|
| 133 |
+
paired, metadata_columns, diagnostics = load_paired_rows_with_diagnostics(input_dir, gt_path, meta_path, class_names)
|
| 134 |
+
if not paired:
|
| 135 |
+
raise ValueError(format_diagnostics_error(class_names, input_dir, gt_path, meta_path, diagnostics))
|
| 136 |
+
return paired, metadata_columns
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def load_paired_rows_with_diagnostics(
|
| 140 |
+
input_dir: Path,
|
| 141 |
+
gt_path: Path,
|
| 142 |
+
meta_path: Path,
|
| 143 |
+
class_names: list[str],
|
| 144 |
+
) -> tuple[list[dict[str, str]], list[str], dict[str, object]]:
|
| 145 |
labels = read_labels(gt_path)
|
| 146 |
selected = {lesion_id for lesion_id, label in labels.items() if label in class_names}
|
| 147 |
by_lesion: dict[str, dict[str, dict[str, str]]] = {}
|
| 148 |
+
metadata_rows_by_class: Counter[str] = Counter()
|
| 149 |
+
metadata_modality_by_class: Counter[tuple[str, str]] = Counter()
|
| 150 |
+
existing_modality_by_class: Counter[tuple[str, str]] = Counter()
|
| 151 |
+
missing_source_examples: list[str] = []
|
| 152 |
|
| 153 |
with meta_path.open(newline="") as f:
|
| 154 |
reader = csv.DictReader(f)
|
|
|
|
| 157 |
lesion_id = row["lesion_id"]
|
| 158 |
if lesion_id not in selected:
|
| 159 |
continue
|
| 160 |
+
class_name = labels[lesion_id]
|
| 161 |
+
metadata_rows_by_class[class_name] += 1
|
| 162 |
image_type = normalize_image_type(row["image_type"])
|
| 163 |
+
metadata_modality_by_class[(class_name, image_type)] += 1
|
| 164 |
if image_type not in MODALITIES:
|
| 165 |
continue
|
| 166 |
+
source_path = resolve_source_image(input_dir, lesion_id, row["isic_id"])
|
| 167 |
+
if source_path is None:
|
| 168 |
+
if len(missing_source_examples) < 8:
|
| 169 |
+
missing_source_examples.append(str(input_dir / lesion_id / f"{row['isic_id']}.jpg"))
|
| 170 |
continue
|
| 171 |
+
existing_modality_by_class[(class_name, image_type)] += 1
|
| 172 |
copied = dict(row)
|
| 173 |
copied["source_path"] = str(source_path)
|
| 174 |
copied["image_type_norm"] = image_type
|
|
|
|
| 188 |
}
|
| 189 |
)
|
| 190 |
|
| 191 |
+
diagnostics = {
|
| 192 |
+
"labels_by_target_class": dict(sorted(Counter(label for label in labels.values() if label in class_names).items())),
|
| 193 |
+
"selected_lesions": len(selected),
|
| 194 |
+
"metadata_rows_by_class": dict(sorted(metadata_rows_by_class.items())),
|
| 195 |
+
"metadata_modality_by_class": {
|
| 196 |
+
f"{class_name}/{modality}": count
|
| 197 |
+
for (class_name, modality), count in sorted(metadata_modality_by_class.items())
|
| 198 |
+
},
|
| 199 |
+
"existing_modality_by_class": {
|
| 200 |
+
f"{class_name}/{modality}": count
|
| 201 |
+
for (class_name, modality), count in sorted(existing_modality_by_class.items())
|
| 202 |
+
},
|
| 203 |
+
"lesions_with_any_existing_modality": len(by_lesion),
|
| 204 |
+
"paired_lesions_by_class": class_counts(paired),
|
| 205 |
+
"missing_source_examples": missing_source_examples,
|
| 206 |
+
}
|
| 207 |
+
return sorted(paired, key=lambda row: (row["class_name"], row["lesion_id"])), metadata_columns, diagnostics
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def format_diagnostics_error(
|
| 211 |
+
class_names: list[str],
|
| 212 |
+
input_dir: Path,
|
| 213 |
+
gt_path: Path,
|
| 214 |
+
meta_path: Path,
|
| 215 |
+
diagnostics: dict[str, object],
|
| 216 |
+
) -> str:
|
| 217 |
+
lines = [
|
| 218 |
+
f"No paired clinical/dermoscopic lesions found for classes: {', '.join(class_names)}",
|
| 219 |
+
"",
|
| 220 |
+
"Data diagnostics:",
|
| 221 |
+
f" input_dir={input_dir}",
|
| 222 |
+
f" groundtruth_csv={gt_path}",
|
| 223 |
+
f" metadata_csv={meta_path}",
|
| 224 |
+
f" labels_by_target_class={diagnostics['labels_by_target_class']}",
|
| 225 |
+
f" selected_lesions={diagnostics['selected_lesions']}",
|
| 226 |
+
f" metadata_rows_by_class={diagnostics['metadata_rows_by_class']}",
|
| 227 |
+
f" metadata_modality_by_class={diagnostics['metadata_modality_by_class']}",
|
| 228 |
+
f" existing_modality_by_class={diagnostics['existing_modality_by_class']}",
|
| 229 |
+
f" lesions_with_any_existing_modality={diagnostics['lesions_with_any_existing_modality']}",
|
| 230 |
+
f" paired_lesions_by_class={diagnostics['paired_lesions_by_class']}",
|
| 231 |
+
]
|
| 232 |
+
missing = diagnostics.get("missing_source_examples") or []
|
| 233 |
+
if missing:
|
| 234 |
+
lines.append(" missing_source_examples=")
|
| 235 |
+
lines.extend(f" {path}" for path in missing)
|
| 236 |
+
lines.extend(
|
| 237 |
+
[
|
| 238 |
+
"",
|
| 239 |
+
"Most likely fix: pass the real training image root via --input-dir.",
|
| 240 |
+
"Expected image layout: <input-dir>/<lesion_id>/<isic_id>.jpg",
|
| 241 |
+
]
|
| 242 |
+
)
|
| 243 |
+
return "\n".join(lines)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def print_data_diagnostics(input_dir: Path, gt_path: Path, meta_path: Path, class_names: list[str]) -> None:
|
| 247 |
+
rows, metadata_columns, diagnostics = load_paired_rows_with_diagnostics(input_dir, gt_path, meta_path, class_names)
|
| 248 |
+
print("Data diagnostics")
|
| 249 |
+
print(f" input_dir={input_dir}")
|
| 250 |
+
print(f" groundtruth_csv={gt_path}")
|
| 251 |
+
print(f" metadata_csv={meta_path}")
|
| 252 |
+
print(f" metadata_columns={len(metadata_columns)}")
|
| 253 |
+
for key, value in diagnostics.items():
|
| 254 |
+
print(f" {key}={value}")
|
| 255 |
+
print(f" paired_rows={len(rows)}")
|
| 256 |
|
| 257 |
|
| 258 |
def select_rows(rows: list[dict[str, str]], class_names: list[str], max_source_lesions: int | None, shuffle: bool, seed: int):
|
|
|
|
| 387 |
|
| 388 |
def load_pipeline(args: argparse.Namespace, lora_weights: Path | None, lora_scale: float):
|
| 389 |
import torch
|
| 390 |
+
try:
|
| 391 |
+
from diffusers import StableDiffusionImg2ImgPipeline
|
| 392 |
+
except RuntimeError as exc:
|
| 393 |
+
message = str(exc)
|
| 394 |
+
if "flash_attn.flash_attn_interface" in message or "xformers" in message:
|
| 395 |
+
raise RuntimeError(
|
| 396 |
+
"Diffusers failed while importing xformers/flash-attn. Your environment likely has a broken "
|
| 397 |
+
"xformers install. For this SD 1.5 img2img script, xformers is optional; uninstall it and rerun:\n\n"
|
| 398 |
+
" pip uninstall -y xformers flash-attn\n\n"
|
| 399 |
+
"Then keep using attention slicing, which this script enables automatically on CUDA. "
|
| 400 |
+
"If you really need xformers, use a Python 3.10/3.11 CUDA environment with matching torch, "
|
| 401 |
+
"xformers, and flash-attn wheels."
|
| 402 |
+
) from exc
|
| 403 |
+
raise
|
| 404 |
|
| 405 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 406 |
dtype = torch.float32 if device == "cpu" or args.fp32 else torch.float16
|
|
|
|
| 428 |
return ImageOps.fit(img.convert("RGB"), (size, size), method=Image.Resampling.LANCZOS)
|
| 429 |
|
| 430 |
|
| 431 |
+
def looks_like_blocked_black_image(image: Image.Image) -> bool:
|
| 432 |
+
stat_image = image.convert("L").resize((32, 32), method=Image.Resampling.BILINEAR)
|
| 433 |
+
pixels = list(stat_image.getdata())
|
| 434 |
+
mean_value = sum(pixels) / max(len(pixels), 1)
|
| 435 |
+
bright_pixels = sum(1 for value in pixels if value > 8)
|
| 436 |
+
return mean_value < 3.0 and bright_pixels / max(len(pixels), 1) < 0.01
|
| 437 |
+
|
| 438 |
+
|
| 439 |
def modality_prompt(args: argparse.Namespace, class_name: str, modality: str) -> str:
|
| 440 |
if modality == "clinical_close_up" and args.clinical_prompt:
|
| 441 |
return args.clinical_prompt
|
|
|
|
| 481 |
num_inference_steps=args.steps,
|
| 482 |
generator=generator,
|
| 483 |
)
|
| 484 |
+
image = result.images[0]
|
| 485 |
+
if not args.allow_black_images and looks_like_blocked_black_image(image):
|
| 486 |
+
raise RuntimeError(
|
| 487 |
+
"Stable Diffusion returned a nearly black image. This usually means the default safety checker "
|
| 488 |
+
"blocked a clinical skin image as NSFW. Rerun with:\n\n"
|
| 489 |
+
" --disable-safety-checker\n\n"
|
| 490 |
+
f"Blocked output path would have been: {out_path}"
|
| 491 |
+
)
|
| 492 |
+
image.save(out_path, quality=95)
|
| 493 |
generated += 1
|
| 494 |
|
| 495 |
del pipe
|
|
|
|
| 608 |
raise ValueError("--strength must be in [0, 1]")
|
| 609 |
|
| 610 |
args.output_dir = args.output_dir.expanduser().resolve()
|
| 611 |
+
if not args.disable_safety_checker:
|
| 612 |
+
print(
|
| 613 |
+
"Warning: diffusers safety checker is enabled. Clinical/dermoscopic skin images may be falsely "
|
| 614 |
+
"blocked and returned as black images. If that happens, rerun with --disable-safety-checker."
|
| 615 |
+
)
|
| 616 |
|
| 617 |
input_dir, gt_path, meta_path = resolve_data_paths(args)
|
| 618 |
+
if args.diagnose_data:
|
| 619 |
+
print_data_diagnostics(input_dir, gt_path, meta_path, args.class_names)
|
| 620 |
+
return
|
| 621 |
+
|
| 622 |
all_rows, metadata_columns = load_paired_rows(input_dir, gt_path, meta_path, args.class_names)
|
| 623 |
rows = select_rows(all_rows, args.class_names, args.max_source_lesions, args.shuffle, args.seed)
|
| 624 |
tasks = build_tasks(rows, args)
|
Stable_diffusion_augmentation/requirements.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
torchvision
|
| 3 |
+
diffusers
|
| 4 |
+
transformers
|
| 5 |
+
accelerate
|
| 6 |
+
safetensors
|
| 7 |
+
pillow
|
| 8 |
+
tqdm
|
| 9 |
+
pandas
|
| 10 |
+
numpy
|
| 11 |
+
scikit-learn
|
| 12 |
+
timm
|