# -*- coding: utf-8 -*-
"""教材照片预处理工具（第 4 章及后续章节通用）
功能：
  1) **自动判方向**：对 0/90/180/270 四种朝向打分（正文横排时"行方向"亮度方差最大）
  2) 自动定位书页区域（亮度剖面）
  3) **自动识别双页展开**并按装订线（gutter）切左右页
  4) 每页切「上/下」两块并缩放到 1500px 宽，输出到输出目录 + manifest.json
用法（实测口径）：
  ~/Downloads/.tools/pyvenv/bin/python _prep_photos.py <照片|目录> [--out 输出目录]
输出：*-work.jpg（选定朝向的工作图）、*-preview.jpg（整页预览）、*-grid.jpg（**带 10% 坐标网格**，
      用于精确选裁剪框）、*-alt-preview.jpg（另一朝向备选，若默认反了改用它）、manifest.json
说明：① **判向**已用两张已知照片对拍验证（第 3 章那批需逆时针 90°、第 4 章这批无需旋转，均判对）；
      ② **不自动切页**——书页/装订线位置每次都不同，自动裁剪有切到正文的风险，
      改为"看网格预览 → 人工确认裁剪框"，再按下方命令切片：
        ffmpeg -y -i <work>.jpg -vf "crop=W:H:X:Y,scale=1500:-1" out.jpg
依赖：ffmpeg（必须）、Pillow（网格预览，系统已装）
"""
import os, sys, json, glob, subprocess, statistics, argparse

FONT_W = 300          # 灰度取样网格
FONT_H = 135


def gray_sample(path, sw=FONT_W, sh=FONT_H):
    r = subprocess.run(['ffmpeg', '-v', 'error', '-i', path, '-vf',
                        f'scale={sw}:{sh},format=gray', '-f', 'rawvideo', '-'],
                       capture_output=True)
    d = r.stdout
    if len(d) < sw * sh:
        return None
    return d, sw, sh


def gray_sample_aspect(path, long_side=200):
    """按长边归一到 long_side 取样（保持长宽比，避免压扁）。"""
    w, h = probe(path)
    if w >= h:
        sw, sh = long_side, max(4, round(long_side * h / w))
    else:
        sw, sh = max(4, round(long_side * w / h)), long_side
    r = subprocess.run(['ffmpeg', '-v', 'error', '-i', path, '-vf',
                        f'scale={sw}:{sh},format=gray', '-f', 'rawvideo', '-'],
                       capture_output=True)
    d = r.stdout
    return (d, sw, sh) if len(d) >= sw * sh else None


def profiles(d, sw, sh):
    rows = [sum(d[y * sw:(y + 1) * sw]) / sw for y in range(sh)]
    cols = [sum(d[y * sw + x] for y in range(sh)) / sh for x in range(sw)]
    return rows, cols


def variance(v):
    return statistics.pvariance(v) if len(v) > 1 else 0.0


def _energy(v):
    return sum((v[i + 1] - v[i]) ** 2 for i in range(len(v) - 1))


def _ratio(path, vf):
    """返回 行能量/列能量；正文横排时该比值偏小（行方向跨过一行才有跳变）。"""
    tmp = '/tmp/_orient_score.jpg'
    pre = [x for x in [vf, 'scale=320:160', 'format=gray'] if x]
    subprocess.run(['ffmpeg', '-v', 'error', '-y', '-i', path, '-vf', ','.join(pre), '-q:v', '3', tmp], check=True)
    smp = gray_sample(tmp, 320, 160)
    if not smp:
        return None
    rows, cols = profiles(*smp)
    return _energy(rows) / (_energy(cols) + 1e-9)


def orientation_scores(path):
    """返回 {'none'/'cw'/'ccw'/'180': ratio}。实测口径（用两张已知照片对拍确认）：
    比值**最低**的那一对朝向＝正文横排（即正确朝向所在轴）。"""
    out = {}
    for rot, vf in [('none', None), ('cw', 'transpose=1'), ('ccw', 'transpose=2'),
                    ('180', 'transpose=1,transpose=1')]:
        r = _ratio(path, vf)
        if r is not None:
            out[rot] = round(r, 3)
    return out


def page_region(path, ow, oh, ratio=0.62, min_frac=0.18):
    """在给定图像上按行/列亮度找书页矩形，返回 (x0,x1,y0,y1)。"""
    smp = gray_sample_aspect(path)
    if not smp:
        return None
    rows, cols = profiles(*smp)
    sh, sw = len(rows), len(cols)

    def longest(vals):
        mx, mn = max(vals), min(vals)
        thr = mn + (mx - mn) * ratio
        idx = [i for i, v in enumerate(vals) if v >= thr]
        if not idx:
            return None
        runs, cur = [], [idx[0]]
        for i in idx[1:]:
            if i - cur[-1] <= 3:
                cur.append(i)
            else:
                runs.append(cur); cur = [i]
        runs.append(cur)
        run = max(runs, key=len)
        return None if len(run) < len(vals) * min_frac else (run[0], run[-1])
    ry, rx = longest(rows), longest(cols)
    if not ry or not rx:
        return None
    y0 = max(0, int(ry[0] / sh * oh) - 60); y1 = min(oh, int(ry[1] / sh * oh) + 60)
    x0 = max(0, int(rx[0] / sw * ow) - 60); x1 = min(ow, int(rx[1] / sw * ow) + 60)
    return x0, x1, y0, y1


def find_gutter(path, x0, x1, y0, y1):
    """在页区中间 30% 宽度内找最暗的竖直带（装订线），返回其 x 中心；找不到返回 None。"""
    w = x1 - x0
    crop = f'crop={w}:{y1-y0}:{x0}:{y0},scale=120:60,format=gray'
    r = subprocess.run(['ffmpeg', '-v', 'error', '-i', path, '-vf', crop, '-f', 'rawvideo', '-'],
                       capture_output=True)
    d = r.stdout
    if len(d) < 120 * 60:
        return None
    cols = [sum(d[y * 120 + x] for y in range(60)) / 60 for x in range(120)]
    lo, hi = int(120 * 0.38), int(120 * 0.62)      # 只在中间 24% 找装订线
    seg = cols[lo:hi]
    if not seg or (max(cols) - min(seg)) < 10:      # 中间没有明显暗带 → 非双页
        return None
    xm = lo + seg.index(min(seg))
    gx = x0 + int(xm / 120 * w)
    if not (x0 + (x1 - x0) * 0.2 < gx < x1 - (x1 - x0) * 0.2):   # 太靠边视为噪声
        return None
    return gx


def grid_preview(work, out, step=0.1):
    """在整页预览上画 10% 网格并标注原始像素坐标，便于精确选取裁剪框。"""
    try:
        from PIL import Image, ImageDraw, ImageFont
    except Exception as e:
        print('（未装 Pillow，跳过网格预览）', e); return None
    im = Image.open(work).convert('RGB')
    W, H = im.size
    scale = 1400 / max(W, H)
    im = im.resize((int(W * scale), int(H * scale)))
    w, h = im.size
    d = ImageDraw.Draw(im)
    for i in range(1, 10):
        x = int(w * i / 10); y = int(h * i / 10)
        d.line([(x, 0), (x, h)], fill=(255, 0, 0), width=1)
        d.line([(0, y), (w, y)], fill=(255, 0, 0), width=1)
        d.text((x + 3, 4), f'x{int(W * i / 10)}', fill=(200, 0, 0))
        d.text((4, y + 3), f'y{int(H * i / 10)}', fill=(200, 0, 0))
    d.rectangle([0, 0, w - 1, h - 1], outline=(0, 0, 0))
    im.save(out, quality=88)
    return out


def prep(path, outdir):
    os.makedirs(outdir, exist_ok=True)
    base = os.path.splitext(os.path.basename(path))[0]
    info = {'src': path, 'name': base}
    sc = orientation_scores(path)
    info['orientation_scores'] = sc
    hv = (sc.get('none', 9) + sc.get('180', 9)) / 2
    vv = (sc.get('cw', 9) + sc.get('ccw', 9)) / 2
    if hv <= vv:
        cands = ['none', '180']; info['axis'] = '正文横排（0°/180°）'
    else:
        cands = ['ccw', 'cw']; info['axis'] = '正文竖排（需 90° 旋转）'
    info.update(candidates=cands, chosen=cands[0])
    vfmap = {'none': None, 'cw': 'transpose=1', 'ccw': 'transpose=2', '180': 'transpose=1,transpose=1'}

    def render(rot, suffix=''):
        work = os.path.join(outdir, f'{base}-work{suffix}.jpg')
        cmd = ['ffmpeg', '-v', 'error', '-y', '-i', path]
        if vfmap[rot]:
            cmd += ['-vf', vfmap[rot]]
        cmd += ['-map_metadata', '0', '-q:v', '2', work]
        subprocess.run(cmd, check=True)
        return work

    work = render(cands[0])
    info['work'] = os.path.basename(work)
    info['work_size'] = list(probe(work))
    prev = os.path.join(outdir, f'{base}-preview.jpg')
    subprocess.run(['ffmpeg', '-v', 'error', '-y', '-i', work, '-vf', 'scale=1400:-1', prev], check=True)
    info['preview'] = os.path.basename(prev)
    gp = grid_preview(work, os.path.join(outdir, f'{base}-grid.jpg'))
    info['grid_preview'] = os.path.basename(gp) if gp else None
    alt = render(cands[1], '-alt')
    altp = os.path.join(outdir, f'{base}-alt-preview.jpg')
    subprocess.run(['ffmpeg', '-v', 'error', '-y', '-i', alt, '-vf', 'scale=1400:-1', altp], check=True)
    info['alt_preview'] = os.path.basename(altp)
    return info


def probe(p):
    r = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'v:0',
                        '-show_entries', 'stream=width,height', '-of', 'csv=p=0', p],
                       capture_output=True, text=True)
    w, h = r.stdout.strip().split(',')
    return int(w), int(h)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('target')
    ap.add_argument('--out', default='/tmp/ch-prep')
    a = ap.parse_args()
    files = []
    if os.path.isdir(a.target):
        for ext in ('*.jpg', '*.jpeg', '*.png', '*.JPG'):
            files += sorted(glob.glob(os.path.join(a.target, ext)))
    else:
        files = [a.target]
    # 排除工作图/切片
    files = [f for f in files if '-work' not in f and not any(f.endswith(f'-{t}.jpg') for t in ('top', 'bot'))]
    manifest = []
    for f in files:
        info = prep(f, a.out)
        manifest.append(info)
        print(f"📷 {info['name']}: 判向={info['axis']} ｜ 候选={info['candidates']} 默认={info['chosen']} ｜ "
              f"比值={info['orientation_scores']} ｜ 工作图={info['work_size']}")
        print(f"     预览={info['preview']} ｜ 网格预览={info['grid_preview']} ｜ 备选预览={info['alt_preview']}")
    with open(os.path.join(a.out, 'manifest.json'), 'w', encoding='utf-8') as fp:
        json.dump(manifest, fp, ensure_ascii=False, indent=2)
    print('✅ manifest →', os.path.join(a.out, 'manifest.json'))


if __name__ == '__main__':
    main()
