#!/usr/bin/env python3
"""Check a product cutout and make a white listing image. Needs Python 3 with Pillow and NumPy.

  python3 listing_tools.py check   cutout.png [--box X,Y,W,H] [--prefix NAME]
  python3 listing_tools.py lift    photo.jpg lifted.jpg [--gamma 0.45]
  python3 listing_tools.py reapply original.jpg cutout_of_lifted.png result.png
  python3 listing_tools.py listing cutout.png out.png [--size 1000] [--margin 8] [--shadow none|floor|drop]
  python3 listing_tools.py corners image.jpg

check    prints corner alpha and the transparent, solid and soft shares, 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 a pale or shiny edge.
reapply  puts the mask of the cutout made from the lifted copy onto the original pixels (output must be .png).
listing  centres the product on a square pure white canvas (--size pixels per side, --margin percent of the side kept
         empty on each side, draft setting 8). --shadow floor or drop adds a soft grey shadow (draft settings, our taste).
         Output .png or .jpg (JPG quality 95).
corners  prints the four corner pixels and how many pixels along the border are exactly 255,255,255.
All commands turn a phone photo upright using its rotation tag. The output name must differ from the input name:
a command stops with exit 2 instead of overwriting.
"""
import argparse
import os
import sys

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

Image.MAX_IMAGE_PIXELS = 100_000_000


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, Image.DecompressionBombError):
        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",))
    al = np.array(im)[..., 3]
    h, w = al.shape
    total = h * w
    soft = (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 * soft.sum() / total, soft.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, %.1f%% have any opacity"
              % (a.box, 100.0 * (sub >= 128).sum() / sub.size, 100.0 * (sub > 0).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 the outline" % (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_listing(a):
    if a.size < 100 or a.size > 5000:
        fail("--size must be between 100 and 5000 pixels")
    if a.margin < 0 or a.margin > 40:
        fail("--margin must be between 0 and 40 (percent of the 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 >= 16 else 0).getbbox()
    if box is None:
        fail("the cutout has no visible pixels")
    im = im.crop(box)
    s = a.size
    room = round(s * 0.06) if a.shadow == "floor" else 0
    free_w = s * (1 - 2 * a.margin / 100.0)
    free_h = s * (1 - 2 * a.margin / 100.0) - room
    k = min(free_w / im.width, free_h / im.height)
    im = im.resize((max(1, round(im.width * k)), max(1, round(im.height * k))), Image.LANCZOS)
    x = (s - im.width) // 2
    y = (s - room - im.height) // 2
    canvas = Image.new("RGBA", (s, s), (255, 255, 255, 255))
    if a.shadow != "none":
        al = im.getchannel("A")
        if a.shadow == "floor":
            band = np.array(al)[int(im.height * 0.95):, :] >= 128
            cols = np.where(band.any(axis=0))[0]
            bw = int(cols.max() - cols.min() + 1) if len(cols) else im.width
            cx = int((cols.max() + cols.min()) // 2) if len(cols) else im.width // 2
            ew, eh = max(2, round(bw * 0.9)), max(2, round(bw * 0.09))
            sh = Image.new("L", (ew, eh), 0)
            ImageDraw.Draw(sh).ellipse((0, 0, ew - 1, eh - 1), fill=255)
            pos = (x + cx - ew // 2, y + im.height - eh // 2)
        else:
            sh = al
            pos = (x + round(s * 0.012), y + round(s * 0.015))
        mask = Image.new("L", (s, s), 0)
        mask.paste(sh, pos)
        mask = mask.filter(ImageFilter.GaussianBlur(max(1, round(s * 0.012)))).point(lambda v: round(v * 0.45))
        layer = Image.new("RGBA", (s, s), (60, 60, 60, 0))
        layer.putalpha(mask)
        canvas = Image.alpha_composite(canvas, layer)
    canvas.alpha_composite(im, (x, y))
    rgb = canvas.convert("RGB")
    if os.path.splitext(a.out)[1].lower() == ".png":
        rgb.save(a.out)
    else:
        rgb.save(a.out, quality=95)
    print("saved %s at %d x %d, product %d x %d px, shadow %s" % (a.out, s, s, im.width, im.height, a.shadow))
    cmd_corners(argparse.Namespace(image=a.out))


def cmd_corners(a):
    im = load(a.image).convert("RGB")
    arr = np.array(im)
    h, w, _ = arr.shape
    print("corner pixels (top-left, top-right, bottom-left, bottom-right): %s %s %s %s"
          % tuple(tuple(int(c) for c in arr[y, x]) for y, x in ((0, 0), (0, w - 1), (h - 1, 0), (h - 1, w - 1))))
    border = np.concatenate([arr[0], arr[-1], arr[:, 0], arr[:, -1]])
    pure = int((border == 255).all(axis=1).sum())
    print("border pixels exactly 255,255,255: %d of %d (%.1f%%); lowest channel value on the border: %d"
          % (pure, len(border), 100.0 * pure / len(border), int(border.min())))


p = argparse.ArgumentParser(description="Check a product cutout and make a white listing image")
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("listing"); c.add_argument("cutout"); c.add_argument("out"); c.add_argument("--size", type=int, default=1000); c.add_argument("--margin", type=float, default=8); c.add_argument("--shadow", choices=("none", "floor", "drop"), default="none"); c.set_defaults(f=cmd_listing)
c = s.add_parser("corners"); c.add_argument("image"); c.set_defaults(f=cmd_corners)
args = p.parse_args()
args.f(args)
