#!/usr/bin/env python3
"""Check and use a transparent cutout PNG. Needs Python 3 with Pillow and NumPy.

  python3 cutout_tools.py check  cutout.png [--box X,Y,W,H] [--prefix NAME]
  python3 cutout_tools.py lift   photo.jpg lifted.jpg [--gamma 0.45]
  python3 cutout_tools.py reapply original.jpg cutout_of_lifted.png result.png
  python3 cutout_tools.py thumb  cutout.png thumb.png [--size 1280x720] [--color 1F3A93]

check  prints corner alpha, how much is transparent, solid or soft, and saves NAME-on-black.png and NAME-on-white.png.
lift   brightens a copy (draft setting 0.45, not a rule) so a cutout tool can see dark hair.
reapply puts the mask of the cutout made from the lifted copy onto the original pixels (the output must be a .png).
All commands turn a phone photo upright using its rotation tag before they work. The output name must differ from the input name: a command stops with exit 2 instead of overwriting.
thumb  scales the cutout to the frame height, puts it at the right on a flat colour.
"""
import argparse
import os
import sys

try:
    import numpy as np
    from PIL import Image, ImageOps, UnidentifiedImageError
except ImportError:
    sys.exit("Needs Pillow and NumPy: python3 -m pip install pillow numpy")


def fail(msg):
    print("error: " + msg, file=sys.stderr)
    sys.exit(2)


def check_out(path, inputs, exts):
    for i in inputs:
        if os.path.exists(path) and os.path.samefile(path, i):
            fail("the output is the same file as the input (" + path + "): use a new name")
    if os.path.splitext(path)[1].lower() not in exts:
        fail("the output name must end in " + " or ".join(exts) + ": " + path)
    folder = os.path.dirname(path) or "."
    if not os.path.isdir(folder):
        fail("folder does not exist: " + folder)


def load(path, want_alpha=False):
    if not os.path.isfile(path):
        fail("file not found: " + path)
    if os.path.getsize(path) == 0:
        fail("file is empty: " + path)
    try:
        im = Image.open(path)
        im.load()
        im = ImageOps.exif_transpose(im)
    except (UnidentifiedImageError, OSError):
        fail("not an image Pillow can read: " + path)
    if want_alpha and im.mode == "P" and "transparency" in im.info:
        im = im.convert("RGBA")
    if want_alpha and "A" not in im.getbands():
        fail("no transparency in " + path + " (a JPG has none: use the PNG the tool gives you)")
    return im


def cmd_check(a):
    im = load(a.cutout, True).convert("RGBA")
    check_out(a.prefix + "-on-black.png", [a.cutout], (".png",))
    arr = np.array(im)
    al = arr[..., 3]
    h, w = al.shape
    total = h * w
    edge = (al > 0) & (al < 255)
    print("size: %d x %d" % (w, h))
    print("corner alpha (top-left, top-right, bottom-left, bottom-right): %d %d %d %d"
          % (al[0, 0], al[0, -1], al[-1, 0], al[-1, -1]))
    print("transparent (alpha 0): %.1f%%" % (100.0 * (al == 0).sum() / total))
    print("solid (alpha 255): %.1f%%" % (100.0 * (al == 255).sum() / total))
    print("soft (alpha 1-254): %.1f%% = %d pixels" % (100.0 * edge.sum() / total, edge.sum()))
    if a.box:
        try:
            x, y, bw, bh = [int(v) for v in a.box.split(",")]
        except ValueError:
            fail("--box needs four whole numbers: X,Y,W,H")
        if x < 0 or y < 0 or bw < 1 or bh < 1 or x + bw > w or y + bh > h:
            fail("--box leaves the picture (%d x %d px)" % (w, h))
        sub = al[y:y + bh, x:x + bw]
        print("box %s: %.1f%% of its pixels have alpha 128 or more" % (a.box, 100.0 * (sub >= 128).sum() / sub.size))
    for name, bg in (("black", (0, 0, 0, 255)), ("white", (255, 255, 255, 255))):
        out = Image.alpha_composite(Image.new("RGBA", im.size, bg), im).convert("RGB")
        out.save("%s-on-%s.png" % (a.prefix, name))
    print("saved %s-on-black.png and %s-on-white.png: open both at 100%% zoom and look at hair and shoulders" % (a.prefix, a.prefix))


def cmd_lift(a):
    if a.gamma <= 0 or a.gamma > 1:
        fail("--gamma must be above 0 and at most 1 (below 1 brightens)")
    check_out(a.out, [a.photo], (".jpg", ".jpeg", ".png"))
    im = load(a.photo).convert("RGB")
    arr = (np.array(im).astype(float) / 255.0) ** a.gamma
    Image.fromarray((arr * 255).round().astype("uint8")).save(a.out, quality=95)
    print("saved %s (gamma %.2f)" % (a.out, a.gamma))


def cmd_reapply(a):
    check_out(a.out, [a.original, a.cutout], (".png",))
    orig = load(a.original).convert("RGB")
    cut = load(a.cutout, True)
    if cut.size != orig.size:
        fail("sizes differ: original %dx%d, cutout %dx%d" % (orig.size + cut.size))
    out = orig.convert("RGBA")
    out.putalpha(cut.getchannel("A"))
    out.save(a.out)
    print("saved %s (original pixels, mask from %s)" % (a.out, a.cutout))


def cmd_thumb(a):
    try:
        tw, th = [int(v) for v in a.size.lower().split("x")]
        col = a.color.lstrip("#")
        rgb = tuple(int(col[i:i + 2], 16) for i in (0, 2, 4))
    except (ValueError, IndexError):
        fail("--size looks like 1280x720 and --color like 1F3A93")
    if tw < 1 or th < 1 or len(col) != 6:
        fail("--size looks like 1280x720 and --color like 1F3A93")
    if tw > 8192 or th > 8192:
        fail("--size is limited to 8192 pixels on each side")
    check_out(a.out, [a.cutout], (".png", ".jpg", ".jpeg"))
    im = load(a.cutout, True).convert("RGBA")
    box = im.getchannel("A").point(lambda v: 255 if v >= 128 else 0).getbbox()
    if box is None:
        fail("the cutout has no solid pixels")
    im = im.crop(box)
    scale = th / im.height
    im = im.resize((max(1, round(im.width * scale)), th), Image.LANCZOS)
    frame = Image.new("RGBA", (tw, th), rgb + (255,))
    if im.width <= tw:
        frame.alpha_composite(im, (tw - im.width, 0))
    else:
        print("note: the cutout is wider than the frame at full height: its left %d px are cut off" % (im.width - tw))
        frame.alpha_composite(im.crop((im.width - tw, 0, im.width, th)), (0, 0))
    frame.convert("RGB").save(a.out)
    print("saved %s at %dx%d" % (a.out, tw, th))


p = argparse.ArgumentParser(description="Check and use a transparent cutout PNG")
s = p.add_subparsers(dest="cmd", required=True)
c = s.add_parser("check"); c.add_argument("cutout"); c.add_argument("--box"); c.add_argument("--prefix", default="check"); c.set_defaults(f=cmd_check)
c = s.add_parser("lift"); c.add_argument("photo"); c.add_argument("out"); c.add_argument("--gamma", type=float, default=0.45); c.set_defaults(f=cmd_lift)
c = s.add_parser("reapply"); c.add_argument("original"); c.add_argument("cutout"); c.add_argument("out"); c.set_defaults(f=cmd_reapply)
c = s.add_parser("thumb"); c.add_argument("cutout"); c.add_argument("out"); c.add_argument("--size", default="1280x720"); c.add_argument("--color", default="1F3A93"); c.set_defaults(f=cmd_thumb)
args = p.parse_args()
args.f(args)
