#!/usr/bin/env python3
"""Uji potong 1000x567 beberapa nilai ybias untuk foto terpilih artikel 14."""
import urllib.request
from PIL import Image

OUT = "/home/mantapman/.hermes/profiles/atun/workspace/tslaw_listikel"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}
PID = "7504780"

u = f"https://images.pexels.com/photos/{PID}/pexels-photo-{PID}.jpeg?auto=compress&cs=tinysrgb&w=1600"
data = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=120).read()
open(f"{OUT}/_uji14_raw.jpg", "wb").write(data)
im0 = Image.open(f"{OUT}/_uji14_raw.jpg").convert("RGB")
print("ukuran asli:", im0.size)

tw, th = 1000, 567
r = tw / th
sheet = []
for yb in (0.55, 0.70, 0.85, 1.0):
    im = im0.copy()
    w, h = im.size
    if w / h > r:
        cw = int(h * r); x0 = (w - cw) // 2
        im = im.crop((x0, 0, x0 + cw, h))
    else:
        ch = int(w / r); y0 = int((h - ch) * yb)
        im = im.crop((0, y0, w, y0 + ch))
    f = f"{OUT}/_uji14_{int(yb*100)}.webp"
    im.resize((tw, th), Image.LANCZOS).save(f, "WEBP", quality=80, method=6)
    print(f"  ybias {yb}: {f}")
    sheet.append((int(yb * 100), f))

from PIL import ImageDraw, ImageFont
F = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 44)
cw, ch = 1000, 567
sh = Image.new("RGB", (cw, ch * len(sheet)), "white")
d = ImageDraw.Draw(sh)
for i, (yb, f) in enumerate(sheet):
    sh.paste(Image.open(f), (0, i * ch))
    d.rectangle([6, i * ch + 6, 250, i * ch + 66], fill="black")
    d.text((16, i * ch + 10), f"ybias {yb}", font=F, fill="white")
sh.save(f"{OUT}/_uji14_sheet.jpg", quality=86)
print("sheet:", f"{OUT}/_uji14_sheet.jpg")
