File size: 5,824 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
"""Normalization engine: turn any validated original into a standard RGB JPEG.

Order matters and follows the plan:

  1. EXIF transpose first (phone photos would otherwise end up rotated).
  2. Colour handling to RGB:
       - RGBA / LA / PA / palette-with-transparency -> composited on WHITE
         (a naive convert("RGB") turns transparent pixels black)
       - CMYK -> sRGB through the embedded ICC profile when there is one
       - RGB with a non-sRGB ICC profile -> converted to sRGB when possible
       - grayscale / 1-bit / 16-bit -> RGB
  3. Downscale (never upscale) if the long side exceeds ``max_long_side`` (LANCZOS).
  4. Encode as JPEG q95, 4:4:4 chroma (subsampling=0), optimized, metadata stripped.

Originals are never modified; this only ever writes a derived copy.
"""
from __future__ import annotations

import hashlib
import io
import logging
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from pathlib import Path

import numpy as np
from PIL import Image, ImageCms, ImageOps
from tqdm import tqdm

from .manifest import Manifest
from .validator import register_heif

log = logging.getLogger(__name__)
register_heif()

Image.MAX_IMAGE_PIXELS = None  # size is already policed by the validator


@dataclass
class NormalizeResult:
    width: int
    height: int
    pixel_sha256: str


def _icc_to_srgb(img: Image.Image) -> Image.Image:
    """Convert to sRGB via the embedded ICC profile; fall back to a plain convert."""
    icc = img.info.get("icc_profile")
    if not icc:
        return img.convert("RGB")
    try:
        src = ImageCms.ImageCmsProfile(io.BytesIO(icc))
        if img.mode == "RGB" and "srgb" in ImageCms.getProfileDescription(src).lower():
            return img
        dst = ImageCms.createProfile("sRGB")
        return ImageCms.profileToProfile(img, src, dst, outputMode="RGB")
    except Exception:
        return img.convert("RGB")


def _wide_mode_to_rgb(img: Image.Image) -> Image.Image:
    """16-bit / int / float single-channel images -> 8-bit RGB with min/max scaling."""
    arr = np.asarray(img, dtype=np.float64)
    lo, hi = float(arr.min()), float(arr.max())
    scaled = np.zeros_like(arr) if hi <= lo else (arr - lo) / (hi - lo) * 255.0
    return Image.fromarray(scaled.astype(np.uint8), mode="L").convert("RGB")


def to_rgb(img: Image.Image) -> Image.Image:
    mode = img.mode
    if mode in ("RGBA", "LA", "PA", "RGBa", "La") or (mode == "P" and "transparency" in img.info):
        rgba = img.convert("RGBA")
        background = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
        return Image.alpha_composite(background, rgba).convert("RGB")
    if mode == "CMYK":
        return _icc_to_srgb(img)
    if mode in ("I", "I;16", "I;16L", "I;16B", "F"):
        return _wide_mode_to_rgb(img)
    if mode == "RGB":
        return _icc_to_srgb(img) if img.info.get("icc_profile") else img
    return img.convert("RGB")  # L, 1, P (opaque), YCbCr, LAB, HSV, ...


def normalize_image(src: str | Path, dst: str | Path, pcfg: dict) -> NormalizeResult:
    src, dst = Path(src), Path(dst)
    with Image.open(src) as opened:
        opened.seek(0)  # first frame of animated files
        img = ImageOps.exif_transpose(opened)
        img.load()
        img = to_rgb(img)

    max_long = int(pcfg.get("max_long_side", 2560))
    long_side = max(img.size)
    if max_long and long_side > max_long:
        scale = max_long / long_side
        new_size = (max(1, round(img.width * scale)), max(1, round(img.height * scale)))
        img = img.resize(new_size, Image.Resampling.LANCZOS)

    digest = hashlib.sha256(f"{img.width}x{img.height}".encode() + img.tobytes()).hexdigest()

    dst.parent.mkdir(parents=True, exist_ok=True)
    tmp = dst.with_name(dst.name + f".{os.getpid()}.tmp")
    try:
        img.save(tmp, format="JPEG", quality=int(pcfg.get("jpeg_quality", 95)),
                 subsampling=int(pcfg.get("jpeg_subsampling", 0)), optimize=True)
        os.replace(tmp, dst)  # atomic: a crash never leaves a half-written JPEG
    finally:
        if tmp.exists():
            tmp.unlink()
    return NormalizeResult(img.width, img.height, digest)


def run(manifest: Manifest, cfg: dict, data_dir: Path, images_dir: Path) -> dict[str, int]:
    """Normalize every image in status 'validated'."""
    pcfg = cfg["process"]
    todo = manifest.images(statuses=["validated"])
    stats = {"normalized": 0, "normalize_failed": 0}
    if not todo:
        log.info("process: nothing to do")
        return stats

    def work(img: dict):
        dst = images_dir / f"{img['image_id']}.jpg"
        try:
            return img, normalize_image(data_dir / img["orig_path"], dst, pcfg), dst, None
        except Exception as exc:  # noqa: BLE001 - any decode/encode failure discards the image
            return img, None, dst, exc

    with ThreadPoolExecutor(max_workers=int(pcfg.get("workers", 4))) 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="process", unit="img"):
                img, res, dst, err = fut.result()
                if err is None and res is not None:
                    manifest.update_image(
                        img["image_id"], status="normalized", norm_path=str(dst.relative_to(data_dir)),
                        norm_width=res.width, norm_height=res.height, pixel_sha256=res.pixel_sha256)
                    stats["normalized"] += 1
                else:
                    log.warning("normalize failed for %s: %s", img["image_id"], err)
                    manifest.discard(img["image_id"], "normalize_failed")
                    stats["normalize_failed"] += 1
    log.info("process: %s", stats)
    return stats