#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""EP03 S7-2 交付前客观自检 + 打包（wb 箱 id=196）"""
import hashlib, json, os, shutil, zipfile
from PIL import Image
import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
WORK = os.path.join(HERE, "_s72_work")
OUT = os.path.join(HERE, "ep03_s72_monk_2cands.zip")

# 最终交付源 = ep03_s72_final_clean.py 的输出（只清红印、不碰衣褶）
C1 = os.path.join(WORK, "ep03_s72_monk_cand1_front.png")
C2 = os.path.join(WORK, "ep03_s72_monk_cand2_front.png")
# 未清理的原始归一图，用于客观自检对比
N1 = os.path.join(WORK, "_e_norm.png")
N2 = os.path.join(WORK, "_K_norm.png")


def sha(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for c in iter(lambda: f.read(1 << 20), b""):
            h.update(c)
    return h.hexdigest()


def audit(path, norm):
    a = np.asarray(Image.open(path).convert("RGB")).astype(np.float32)
    b = np.asarray(Image.open(norm).convert("RGB")).astype(np.float32)
    h, w = a.shape[:2]
    r, g, b_ = a[:, :, 0], a[:, :, 1], a[:, :, 2]
    # 四角残留朱红印章（高饱和正红，排除暖橙肤色）
    seal = (r > g + 45) & (r > b_ + 45) & (r > 95) & (g < 160)
    corner = np.zeros((h, w), bool)
    corner[:int(h * .28), :int(w * .26)] = True
    corner[:int(h * .28), int(w * .74):] = True
    corner[int(h * .70):, :int(w * .26)] = True
    corner[int(h * .70):, int(w * .74):] = True
    # 四角深色孤立小字：统计四角内 <120 亮度像素占比
    dark = []
    for x0, x1, y0, y1 in [(0, int(w * .22), 0, int(h * .24)), (int(w * .78), w, 0, int(h * .24)),
                           (0, int(w * .22), int(h * .76), h), (int(w * .78), w, int(h * .76), h)]:
        reg = a[y0:y1, x0:x1]
        dark.append(round(float((reg.max(axis=2) < 120).mean()), 5))
    # 清理差异区域 bbox（相对全图）
    diff = (np.abs(a - b).max(axis=2) > 6)
    ys, xs = np.where(diff)
    bbox = [int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max())] if len(xs) else None
    diff_in_center = 0
    if len(xs):
        mid = (xs > w * .24) & (xs < w * .76) & (ys > h * .24) & (ys < h * .76)
        diff_in_center = int(mid.sum())
    # 纸色（四角最亮 20% 像素中位）
    edge = np.concatenate([a[:int(h * .03)].reshape(-1, 3),
                           a[int(h * .97):].reshape(-1, 3)], axis=0)
    paper = np.median(edge, axis=0).round(1).tolist()
    return {
        "size": [w, h], "ratio": round(w / h, 6),
        "corner_seal_px_left": int((seal & corner).sum()),
        "corner_dark_frac": dark,
        "clean_diff_bbox": bbox,
        "clean_diff_px": int(diff.sum()),
        "clean_diff_in_center_px": diff_in_center,
        "paper_rgb": paper,
        "bytes": os.path.getsize(path),
        "sha256": sha(path),
    }


def main():
    a1 = audit(C1, N1); a2 = audit(C2, N2)
    print(json.dumps({"cand1": a1, "cand2": a2}, ensure_ascii=False, indent=2))
    # 交付物已在 _s72_work/ 就位（ep03_s72_final_clean.py 产出），不再复制覆盖
    final1, final2 = C1, C2
    # 并排对照图（非候选，仅供挑选）
    im1 = Image.open(final1).convert("RGB")
    im2 = Image.open(final2).convert("RGB")
    prev = Image.new("RGB", (756 * 2 + 40, 1008), (250, 246, 236))
    prev.paste(im1, (0, 0)); prev.paste(im2, (796, 0))
    prevp = os.path.join(WORK, "preview_2cands.png")
    prev.save(prevp, "PNG", optimize=True)

    manifest = {
        "task": "EP03 S7-2 僧人面孔小肖像（程序层用，非底图）",
        "source": "wb 箱 id=196（2026-11-14 21:56）",
        "spec": {"ratio": "252:336 = 3:4", "size": "756x1008",
                 "placement": "(980,48)-(1232,384) 右上，渲染层按 252x336 摆放",
                 "style": "蔡皋中式绘本水彩 FB-065 锚点：暖米纸、淡彩、细线、留白",
                 "content": "明代九十余岁老僧，光头戒疤，剃净须发，素袈裟，浅色纯底，无文字无水印",
                 "channel": "Pollinations 免费档 flux t2i / nologo=True（不烧 pollen、不碰 ImageGen 积分、不充值）"},
        "candidates": [
            {"file": "ep03_s72_monk_cand1_front.png", "name": "候选1·正面垂目·灰白袈裟",
             "from": "v2 E / seed7331，v3 精确去印", **a1},
            {"file": "ep03_s72_monk_cand2_front.png", "name": "候选2·正面平视·赭灰袈裟",
             "from": "v4 K / seed7421，纯正面提示词", **a2},
        ],
        "rejected": [
            "v1 A/B：左下红印、左侧毛笔字＋两枚红印、长白须偏道士",
            "v2 C/D/F：长白须（道士/寿星感），清角误伤衣摆出现白色抹花",
            "v3 G/H/I：微侧三张全留长白须；I 额外多出锡杖道具",
            "v4 J：短白胡茬＋左袖阶梯状修复块；L：明显修复色块；M：微侧达标但纸底偏冷白，未入选",
        ],
        "engineering_note": ("v2/v3 prompt 写满 NO beard / NO red seal 等否定名词，反把胡须与印章概念"
                             "喂给模型（同 EP03 07 镜「日历」坑）；v4 改纯正面描述、彻底删除相关词，"
                             "印章/题款一律交给程序化 clean_marks 精确清角兜底。"),
        "preview": "preview_2cands.png（并排对照，非第三候选）",
    }
    mpath = os.path.join(WORK, "manifest.json")
    with open(mpath, "w", encoding="utf-8") as f:
        json.dump(manifest, f, ensure_ascii=False, indent=2)

    readme = """# EP03 S7-2 老僧人面孔小肖像｜2 候选

接 wb 箱 id=196（2026-11-14 21:56）。**渲染包就差这一张**，程序层用，非 12 镜底图重开。

## 交付文件
| 文件 | 说明 |
|---|---|
| `ep03_s72_monk_cand1_front.png` | 候选1：正面、垂目、灰白袈裟、暖米纸、淡彩细线 |
| `ep03_s72_monk_cand2_front.png` | 候选2：正面、平视、赭灰袈裟、暖米纸、淡彩细线 |
| `preview_2cands.png` | 两图并排对照（**非第三候选**，仅供挑选） |
| `manifest.json` | 字节 / sha256 / 尺寸 / 客观自检数据 / 落选记录 |
| `scripts/` | 四轮生图与清角脚本，可复现 |

## 规格核对
- 尺寸 **756×1008**，比例 **3:4**（= 252:336 的 3 倍），渲染层按 252×336 放到右上 (980,48)-(1232,384)。
- 明代**九十余岁**老僧：光头＋戒疤、深皱纹、垂白眉、瘦削、剃净须发、素袈裟斜披。
  **不是年轻帝王、不是建文帝、不是道士**（早期多版留长白须被判退，见下）。
- 与 ep03_base_01–11 同风格：FB-065 蔡皋中式绘本水彩为主锚点，暖米纸底、淡彩、细淡墨线、四周留白。
- 浅色纯底、**无文字 / 无数字 / 无红印 / 无水印 / 无签名 / 无边框 / 无风景**，四角空白。
- 原图非任何历史画像或真人的临摹，全部为文生图原创。

## 通道与花费
Pollinations **免费档 flux** 文生图，nologo=True。未烧 pollen、未用 ImageGen 积分、未充值、未买 API，
符合「视频号没见到钱之前不花钱」规矩。共抽 13 张（v1 2 / v2 4 / v3 3 / v4 4），人眼逐张验后取 2 张。

## 两处踩坑与修正（留痕）
1. **否定名词反噬**：v2/v3 prompt 里写满 `NO beard / NO moustache / NO red seal / NO calligraphy`，
   等于反复把「胡须 / 印章 / 书法」概念喂给模型 —— 微侧三张全留长白须、几乎每张自带红印。
   与 EP03 07 镜「prompt 里出现日历二字就画出日历」是同一个坑。
   **v4 改成纯正面描述**（`lean smooth-shaven face`、`corners are untouched blank paper`），
   彻底删除这些词，胡须问题消失。
2. **清角误伤（两次）**：v2 清角把深色衣褶当墨迹抹掉，C/D/F 衣摆出现白色抹花；
   v3 改为只找四角小连通块后，K 的右下衣褶仍被误清出白色方块。
   **最终版 `ep03_s72_final_clean.py` 只找四角的高饱和朱红印章像素、按四角分组求外包矩形，
   一次性用外围纸色覆盖，深色衣褶/线条一律不碰**。客观自检确认：清理差异全部落在四角、
   画面中央 0 像素被改动、四角残留朱红印章 0（cand2 阈值边缘 6px，人眼复核无可见残痕）。

## 落选记录（不抹掉，供复验对照）
- v1 A/B：左下红印、左侧毛笔字＋两枚红印、长白须偏道士。
- v2 C/D/F：长白须（道士/寿星感），清角误伤衣摆。
- v3 G/H/I：微侧三张全留长白须；I 还多出锡杖道具。
- v4 J：短白胡茬＋左袖阶梯状修复块；L：明显修复色块；M：微侧达标但纸底偏冷白，未入选。

## 请花酱复验
1. 两版哪版定稿（或都退，我按意见重出）。
2. 「一眼看得出是老僧人」是否达标、有没有像建文帝或年轻帝王。
3. 与 12 镜底图的风格一致度、暖米纸底色是否对。
4. 浅底摆到右上后是否遮地图广西点（我看不到 S7 地图层，若需更淡底/透明底可再出）。
"""
    rpath = os.path.join(WORK, "README_ep03_s72_monk.md")
    with open(rpath, "w", encoding="utf-8") as f:
        f.write(readme)

    with zipfile.ZipFile(OUT, "w", zipfile.ZIP_DEFLATED, compresslevel=6) as z:
        for p, arc in [(final1, os.path.basename(final1)),
                       (final2, os.path.basename(final2)),
                       (prevp, "preview_2cands.png"),
                       (rpath, "README_ep03_s72_monk.md"),
                       (mpath, "manifest.json")]:
            z.write(p, arc)
        for s in ["ep03_s72_monk_gen.py", "ep03_s72_monk_gen_v2.py",
                  "ep03_s72_monk_gen_v3.py", "ep03_s72_monk_gen_v4.py"]:
            sp = os.path.join(HERE, s)
            if os.path.exists(sp):
                z.write(sp, "scripts/" + s)
    print("ZIP", OUT, os.path.getsize(OUT), sha(OUT))
    with zipfile.ZipFile(OUT) as z:
        print("MEMBERS", len(z.infolist()), "BAD", z.testzip())
        for i in z.infolist():
            print("  ", i.filename, i.file_size)


if __name__ == "__main__":
    main()
