#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""montage.py — 把某目录下的图片拼成带中文标签的复核联系表（用于人工/模型逐格核对）。

用法: python3 montage.py <目录> [每行张数,默认3] [输出文件]
输出: 默认 <目录>/_联系表.jpg
"""
import os, sys
from PIL import Image, ImageDraw, ImageFont

DIR = sys.argv[1]
COLS = int(sys.argv[2]) if len(sys.argv) > 2 else 3
OUT = sys.argv[3] if len(sys.argv) > 3 else os.path.join(DIR, "_联系表.jpg")
START = int(sys.argv[4]) if len(sys.argv) > 4 else 1     # 从第几张开始（1 起）
COUNT = int(sys.argv[5]) if len(sys.argv) > 5 else 10 ** 6
CELL_W, CELL_H, BAR = 560, 420, 34
FONT = "/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc"

files = sorted(f for f in os.listdir(DIR) if f.lower().endswith((".png", ".jpg", ".jpeg")) and not f.startswith("_"))
files = files[START - 1: START - 1 + COUNT]
if not files:
    print("没有图片"); sys.exit(1)

font = ImageFont.truetype(FONT, 20)
rows = (len(files) + COLS - 1) // COLS
W, H = COLS * CELL_W, rows * (CELL_H + BAR)
sheet = Image.new("RGB", (W, H), (245, 243, 236))
d = ImageDraw.Draw(sheet)

for i, fn in enumerate(files):
    r, c = divmod(i, COLS)
    x, y = c * CELL_W, r * (CELL_H + BAR)
    try:
        im = Image.open(os.path.join(DIR, fn)).convert("RGB")
    except Exception as e:
        print("跳过", fn, e); continue
    im.thumbnail((CELL_W - 8, CELL_H - 8))
    sheet.paste(im, (x + (CELL_W - im.width) // 2, y + BAR + (CELL_H - im.height) // 2))
    label = f"{i+1:02d}  {os.path.splitext(fn)[0]}"
    d.text((x + 6, y + 6), label, fill=(20, 20, 20), font=font)

sheet.save(OUT, quality=88)
print(OUT, sheet.size, len(files))
