#!/usr/bin/env python3
"""Koldflux: controls and the JPEG-to-lossless trap, run after measure.py."""
import os, subprocess, re
from PIL import Image
def run(c): return subprocess.run(c, check=True, capture_output=True, text=True)
def ssim(a, b):
    r = subprocess.run(["ffmpeg", "-hide_banner", "-i", a, "-i", b, "-lavfi", "[0:v]format=gbrp[x];[1:v]format=gbrp[y];[x][y]ssim", "-f", "null", "-"], capture_output=True, text=True)
    return float(re.search(r"All:([0-9.]+)", r.stderr).group(1))
print("=== controls")
for n in ("photo", "graphic"): print(f"{n}: reference against itself, SSIM {ssim(n + '-ref.png', n + '-ref.png'):.6f}")
print("\n=== an existing JPEG converted to WebP (photo, the q85 JPEG from measure.py stands in for a camera or CMS JPEG)")
j = "enc/photo-q85.jpg"; run(["djpeg", "-outfile", "enc/j85.ppm", j])
run(["cwebp", "-quiet", "-lossless", "-z", "9", "enc/j85.ppm", "-o", "enc/j85-lossless.webp"])
Image.open("enc/j85.ppm").save("enc/j85.png", optimize=True)
print(f"source JPEG q85: {os.path.getsize(j):,} bytes")
print(f"lossless WebP of the decoded JPEG: {os.path.getsize('enc/j85-lossless.webp'):,} bytes")
print(f"PNG of the decoded JPEG: {os.path.getsize('enc/j85.png'):,} bytes")
for q in (75, 85):
    o = f"enc/j85-webp-q{q}.webp"; run(["cwebp", "-quiet", "-q", str(q), "-m", "6", "enc/j85.ppm", "-o", o]); run(["dwebp", "-quiet", o, "-ppm", "-o", o + ".ppm"])
    print(f"lossy WebP q{q} of the decoded JPEG: {os.path.getsize(o):,} bytes, SSIM against the original reference {ssim(o + '.ppm', 'photo-ref.png'):.4f} (the JPEG itself: {ssim('enc/j85.ppm', 'photo-ref.png'):.4f})")
