"""Measure the actual exported PNGs. Run with Python 3, Pillow and NumPy.

No inference is performed here. Input and output images must be downloaded
separately. Percentages describe alpha pixels, never segmentation accuracy.
"""
from pathlib import Path
import hashlib
import json
import numpy as np
from PIL import Image

ROOT = Path(__file__).resolve().parent
CASES = [("coffee", "coffee.png"), ("chelsea", "chelsea.png"), ("rocket", "rocket.jpg")]


def describe(path):
    with Image.open(path) as image:
        result = {"file": path.name, "bytes": path.stat().st_size,
                  "width": image.width, "height": image.height,
                  "mode": image.mode,
                  "sha256": hashlib.sha256(path.read_bytes()).hexdigest()}
        if "A" in image.getbands():
            alpha = np.asarray(image.getchannel("A"))
            total = alpha.size
            result["alpha"] = {
                "pixels": total,
                "transparentPixels": int(np.count_nonzero(alpha == 0)),
                "partialPixels": int(np.count_nonzero((alpha > 0) & (alpha < 255))),
                "opaquePixels": int(np.count_nonzero(alpha == 255)),
                "transparentPercent": round(100 * float(np.mean(alpha == 0)), 2),
                "partialPercent": round(100 * float(np.mean((alpha > 0) & (alpha < 255))), 2),
                "opaquePercent": round(100 * float(np.mean(alpha == 255)), 2),
            }
        return result


if __name__ == "__main__":
    records = []
    for case, source in CASES:
        output = ROOT / f"{case}-output.png"
        if not output.is_file():
            raise FileNotFoundError(f"Real browser output required: {output.name}")
        with Image.open(output) as image:
            if "A" not in image.getbands():
                raise ValueError(f"Export has no alpha channel: {output.name}")
        records.append({"id": case, "input": describe(ROOT / source), "output": describe(output)})
    text = json.dumps({"method": "Count pixels at alpha=0, alpha=255 and 0<alpha<255 in the unedited browser PNG. No ground-truth mask or accuracy score.", "cases": records}, indent=2)
    (ROOT / "measurements.json").write_text(text + "\n")
    print(text)
