File size: 6,751 Bytes
11a414e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | """Validation engine.
Checks run cheapest-first so most bad files fail early:
1. file size < min_file_bytes -> discard too_small_file
2. integrity open -> verify() -> reopen -> load() -> discard corrupt
3. animated multi-frame GIF/WEBP/APNG -> flag animated (first frame used)
4. resolution short/long side below minimum -> discard low_resolution
5. aspect (hard) > hard_aspect : 1 -> discard extreme_aspect_hard
6. aspect (soft) > flag_aspect : 1 -> flag extreme_aspect (goes to review)
`verify()` alone does not detect truncated JPEGs, so the file is reopened and fully decoded
with `load()` (verify() invalidates the image object, hence the reopen).
The soft aspect limit is a *flag*, not a discard: RAM modules and edge-finger strips are
naturally ~4.5-5:1 and must survive.
"""
from __future__ import annotations
import logging
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from pathlib import Path
from PIL import Image, ImageFile
from tqdm import tqdm
from .manifest import Manifest
log = logging.getLogger(__name__)
ImageFile.LOAD_TRUNCATED_IMAGES = False # never silently accept truncated files
# Pillow's own bomb check works through process-global warnings (not thread-safe), so it is
# disabled and replaced by an explicit header-size check in validate_image().
Image.MAX_IMAGE_PIXELS = None
ALLOWED_FORMATS = {"JPEG", "MPO", "PNG", "WEBP", "GIF", "BMP", "TIFF"}
def register_heif() -> bool:
"""Enable iPhone HEIC/HEIF photos if the optional `pillow-heif` package is installed."""
try:
import pillow_heif # type: ignore
pillow_heif.register_heif_opener()
ALLOWED_FORMATS.add("HEIF")
return True
except Exception: # pragma: no cover - optional dependency
return False
register_heif()
@dataclass
class ValidationResult:
ok: bool
reason: str | None = None
flags: list[str] = field(default_factory=list)
width: int | None = None
height: int | None = None
fmt: str | None = None
aspect: float | None = None
DEFAULT_AI_KEYWORDS = {
"midjourney", "stable diffusion", "dall-e", "dalle", "comfyui",
"novelai", "c2pa", "firefly", "bing image creator", "flux.1",
"fooocus", "automatic1111", "ai_generated", "generated by"
}
def check_ai_metadata(img: Image.Image, custom_keywords: list[str] | set[str] | None = None) -> bool:
"""Return True if image metadata contains AI generator signatures."""
keywords = set(custom_keywords) if custom_keywords else DEFAULT_AI_KEYWORDS
info = getattr(img, "info", {})
if not isinstance(info, dict):
return False
raw_str = " ".join(f"{k} {v}" for k, v in info.items()).lower()
return any(kw.lower() in raw_str for kw in keywords)
def validate_image(path: str | Path, vcfg: dict) -> ValidationResult:
path = Path(path)
try:
size = path.stat().st_size
except OSError:
return ValidationResult(False, "missing_file")
if size < int(vcfg["min_file_bytes"]):
return ValidationResult(False, "too_small_file")
max_pixels = int(vcfg.get("max_pixels", 120_000_000))
flags: list[str] = []
try:
with Image.open(path) as img: # lazy: reads the header only
if img.width * img.height > max_pixels:
return ValidationResult(False, "decompression_bomb", width=img.width, height=img.height)
img.verify()
with Image.open(path) as img: # reopen: verify() leaves the object unusable
fmt = img.format
if fmt not in ALLOWED_FORMATS:
return ValidationResult(False, "unsupported_format", fmt=fmt)
animated = bool(getattr(img, "is_animated", False))
img.load() # full decode -> catches truncation that verify() misses
width, height = img.size
if check_ai_metadata(img, vcfg.get("ai_keywords")):
return ValidationResult(False, "ai_generated_metadata", width=width, height=height, fmt=fmt)
except Exception: # OSError, SyntaxError, ValueError, struct errors, ...
return ValidationResult(False, "corrupt")
if animated:
flags.append("animated")
short, long_ = min(width, height), max(width, height)
if short < int(vcfg["min_short_side"]) or long_ < int(vcfg["min_long_side"]):
return ValidationResult(False, "low_resolution", flags, width, height, fmt)
aspect = long_ / short if short else float("inf")
if aspect > float(vcfg["hard_aspect"]):
return ValidationResult(False, "extreme_aspect_hard", flags, width, height, fmt, aspect)
if aspect > float(vcfg["flag_aspect"]):
flags.append("extreme_aspect")
return ValidationResult(True, None, flags, width, height, fmt, round(aspect, 4))
def run(manifest: Manifest, cfg: dict, data_dir: Path, force: bool = False) -> dict[str, int]:
"""Validate images. If force=True, re-checks previously validated/normalized images for AI metadata."""
vcfg = cfg["validate"]
statuses = ["downloaded", "validated", "normalized", "kept"] if force else ["downloaded"]
todo = manifest.images(statuses=statuses)
stats: dict[str, int] = {"validated": 0}
if not todo:
log.info("validate: nothing to do")
return stats
def work(img: dict) -> tuple[dict, ValidationResult]:
return img, validate_image(data_dir / img["orig_path"], vcfg)
workers = int(vcfg.get("workers", 4))
with ThreadPoolExecutor(max_workers=workers) as ex:
futures = [ex.submit(work, img) for img in todo]
with manifest.transaction():
for fut in tqdm(as_completed(futures), total=len(futures), desc="validate", unit="img"):
img, res = fut.result()
if res.ok:
flags = sorted(set(img["flags"]) | set(res.flags))
manifest.update_image(
img["image_id"], status="validated", width=res.width, height=res.height,
aspect_ratio=res.aspect, orig_format=(res.fmt or "").lower(), flags=flags)
stats["validated"] += 1
else:
manifest.update_image(
img["image_id"], status="discarded", discard_reason=res.reason,
width=res.width, height=res.height, aspect_ratio=res.aspect,
flags=sorted(set(img["flags"]) | set(res.flags)))
stats[res.reason or "discarded"] = stats.get(res.reason or "discarded", 0) + 1
log.info("validate: %s", stats)
return stats
|