#!/usr/bin/env python3
"""把「多個動作並排在同一張圖」的講師動作表切開、去背、對齊,做成影片用的動作圖與轉場圖。
用法:python3 -I tools/avatar-sheet.py <動作表圖> <輸出資料夾> [人物高度px,預設 400] [動作數,預設 6]
輸出:
  <輸出資料夾>/pose0.png … pose{N-1}.png   尺寸相同、透明背景、以頭頂與身體中線對齊(頭和身體不會跳動)
  <輸出資料夾>/blend_{a}_{b}_{k}.png         由動作 a 轉到動作 b 的第 k 張過場(k = 1..BF),用來做淡入淡出,避免硬切
動作表要求:每個動作都是同一個人的全身,橫向由左到右排列,白色背景。
切割方式:在每個預期邊界附近找「不透明像素最少」的那一條垂直線切開(相鄰動作的指尖可能剛好靠在一起)。
"""
import sys
import numpy as np
from PIL import Image, ImageDraw, ImageFilter

BF = 4  # 兩個動作之間的過場張數
sheet, outdir = sys.argv[1], sys.argv[2]
H = int(sys.argv[3]) if len(sys.argv) > 3 else 400
N = int(sys.argv[4]) if len(sys.argv) > 4 else 6

im = Image.open(sheet).convert('RGB')
w, h = im.size
# 1) 去背:從四邊填滿接近白色的背景
rgb = im.copy()
mark = (255, 0, 255)
seeds = [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)] + [(int(w * k / 24), 0) for k in range(1, 24)] + [(int(w * k / 24), h - 1) for k in range(1, 24)]
for xy in seeds:
    px = rgb.getpixel(xy)
    if min(px) >= 235 and px != mark:
        ImageDraw.floodfill(rgb, xy, mark, thresh=30)
m = np.asarray(rgb)
bg = (m[:, :, 0] == 255) & (m[:, :, 1] == 0) & (m[:, :, 2] == 255)
alpha = Image.fromarray(np.where(bg, 0, 255).astype(np.uint8)).filter(ImageFilter.MinFilter(3)).filter(ImageFilter.GaussianBlur(1.2))
cut = im.convert('RGBA')
cut.putalpha(alpha)
al = np.asarray(alpha) > 40

# 2) 分配每個像素屬於哪個動作:相鄰動作的手可能伸進鄰居的位置(指尖甚至互相碰到),
#    所以不用直線切,而是從每個人的身體(軀幹)出發,沿著不透明區域「同時向外擴張」,
#    先到達的那一個就是它的手臂/手指(最短路徑歸屬)。
from collections import deque

ys_all, xs_all = np.where(al)
y_top, y_bot = ys_all.min(), ys_all.max()
FH = y_bot - y_top
# 2a) 用腿的位置找出 N 個身體中線(腿部區域不會被別人的手蓋到)
# 第 5 個參數可指定找腿的高度區間(預設 0.72-0.85);穿寬裙的人物相鄰裙襬太近,要改看小腿,例如 0.88-0.95
LEG_LO, LEG_HI = (float(v) for v in (sys.argv[5] if len(sys.argv) > 5 else '0.72-0.85').split('-'))
leg = al[y_top + int(FH * LEG_LO): y_top + int(FH * LEG_HI)].any(axis=0)
runs, st = [], None
for x, v in enumerate(leg):
    if v and st is None:
        st = x
    if not v and st is not None:
        runs.append([st, x - 1]); st = None
if st is not None:
    runs.append([st, len(leg) - 1])
merged = []
for r in runs:  # 同一個人的兩條腿之間的小縫要合併
    if merged and r[0] - merged[-1][1] < 70:
        merged[-1][1] = r[1]
    else:
        merged.append(r)
if len(merged) != N:
    sys.exit(f'找不到 {N} 個身體(偵測到 {len(merged)} 個),請檢查動作表是否為白底、N 是否正確')
axes = [(r[0] + r[1]) / 2 for r in merged]
# 2b) 多源廣度優先擴張(半解析度以加快速度)
F = 2
sm = al[::F, ::F]
hh, ww = sm.shape
lab = np.zeros((hh, ww), np.int16)
q = deque()
for k, ax in enumerate(axes):
    for y in range((y_top + int(FH * 0.30)) // F, (y_top + int(FH * 0.55)) // F):
        for x in range(max(0, int(ax - 60) // F), min(ww, int(ax + 60) // F)):
            if sm[y, x] and not lab[y, x]:
                lab[y, x] = k + 1
                q.append((y, x))
while q:
    cy, cx = q.popleft()
    k = lab[cy, cx]
    for dy in (-1, 0, 1):
        for dx in (-1, 0, 1):
            ny, nx = cy + dy, cx + dx
            if 0 <= ny < hh and 0 <= nx < ww and sm[ny, nx] and not lab[ny, nx]:
                lab[ny, nx] = k
                q.append((ny, nx))
full = np.kron(lab, np.ones((F, F), np.int16))[:h, :w]
if full.shape != (h, w):
    full = np.pad(full, ((0, h - full.shape[0]), (0, w - full.shape[1])))
alpha_np = np.asarray(alpha)

# 3) 逐個動作:依歸屬取出該人物(稍微外擴以保留邊緣),量頭頂/腳底/身體中線
figs = []
for i in range(N):
    mk = Image.fromarray(((full == i + 1) * 255).astype(np.uint8)).filter(ImageFilter.MaxFilter(5))
    pa = np.minimum(alpha_np, np.asarray(mk))
    # 外擴的 2px 可能吃到鄰居的邊,只保留「沒有明確屬於別人」的像素
    other = (full != 0) & (full != i + 1)
    pa = np.where(other, 0, pa).astype(np.uint8)
    a = pa > 40
    ys, xs = np.where(a)
    top, bottom, left, right = ys.min(), ys.max(), xs.min(), xs.max()
    hf = bottom - top

    def cxrows(r0, r1):
        rr = a[top + int(hf * r0): top + int(hf * r1)]
        _, xx = np.where(rr)
        return xx.mean()

    axis = (cxrows(0.0, 0.10) + cxrows(0.55, 0.70)) / 2  # 頭與髖的中線,代表身體位置
    part = cut.crop((left, 0, right + 1, h)).copy()
    part.putalpha(Image.fromarray(pa[:, left:right + 1]))
    figs.append(dict(img=part, top=top, bottom=bottom, left=0, right=right - left, fcx=axis - left))

# 4) 縮放到相同的「頭頂到腳底」高度,再以身體中線與頭頂對齊
scaled = []
for f in figs:
    s = H / (f['bottom'] - f['top'])
    im2 = f['img'].crop((0, f['top'], f['img'].width, f['bottom'] + 1)).resize((max(1, round(f['img'].width * s)), H + 1), Image.LANCZOS)
    scaled.append(dict(img=im2, fcx=f['fcx'] * s, left=f['left'] * s, right=f['right'] * s))
pad = 10
maxL = max(f['fcx'] - f['left'] for f in scaled) + pad
maxR = max(f['right'] - f['fcx'] for f in scaled) + pad
CW, CH = int(maxL + maxR), H + 1 + pad
poses = []
for i, f in enumerate(scaled):
    canvas = Image.new('RGBA', (CW, CH), (0, 0, 0, 0))
    canvas.paste(f['img'], (int(round(maxL - f['fcx'])), 0), f['img'])
    canvas.save(f'{outdir}/pose{i}.png')
    poses.append(canvas)

# 5) 轉場:在預乘 alpha 空間線性混合,邊緣才不會出現黑邊
def premult(img):
    a = np.asarray(img).astype(np.float32)
    a[:, :, :3] *= a[:, :, 3:4] / 255.0
    return a

pm = [premult(p) for p in poses]
for a in range(N):
    for b in range(N):
        if a == b:
            continue
        for k in range(1, BF + 1):
            t = k / (BF + 1)
            mix = pm[a] * (1 - t) + pm[b] * t
            al_ = mix[:, :, 3:4]
            out = np.zeros_like(mix)
            out[:, :, :3] = np.where(al_ > 0.5, mix[:, :, :3] * 255.0 / np.maximum(al_, 1e-3), 0)
            out[:, :, 3:4] = al_
            Image.fromarray(np.clip(out, 0, 255).astype(np.uint8), 'RGBA').save(f'{outdir}/blend_{a}_{b}_{k}.png')
print(f'{CW}x{CH} poses={N} blend={BF}')
