#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""二维码可扫尺寸扫描：把三个码缩到不同像素，逐个尝试解码（Vision），找出各自的最小可扫尺寸"""
import os
import subprocess
from PIL import Image

QRDIR = '/Users/liuxinyuan/Desktop/Hermes输出-工作类/科研2026秋季促销/华南农大海报_20260920/qr'
SWIFT = '/Users/liuxinyuan/Desktop/Hermes输出-工作类/脚本/decode_qr.swift'
OUT = '/tmp/qr_sweep'
os.makedirs(OUT, exist_ok=True)

SIZES = [140, 160, 176, 190, 210, 240]
names = ['公众号.png', '小红书.png', '视频号.png']

print('尺寸扫描（纯码区，不含白边）:')
tests = []
for n in names:
    src = Image.open(os.path.join(QRDIR, n)).convert('L')
    for s in SIZES:
        p = os.path.join(OUT, '%s_%d.png' % (n[:-4], s))
        im = src.resize((s, s), Image.LANCZOS).point(lambda v: 0 if v < 150 else 255).convert('RGB')
        im.save(p)
        tests.append((n[:-4], s, p))

res = subprocess.run(['swift', SWIFT] + [t[2] for t in tests],
                     capture_output=True, text=True)
ok = {}
for line in res.stdout.splitlines():
    parts = line.split('\t')
    if len(parts) < 3:
        continue
    f = os.path.basename(parts[0])
    key = '_'.join(f[:-4].split('_')[:-1])
    size = int(f[:-4].split('_')[-1])
    if 'ERR' not in parts[1]:
        ok.setdefault(key, []).append(size)

print('\n结果:')
for n in [x[:-4] for x in names]:
    good = sorted(ok.get(n, []))
    print('  %-6s 可扫尺寸: %s  → 最小 %s px' % (n, good if good else '全部失败 ✗',
                                            (str(good[0]) + '') if good else '—'))
print('\n（脚本耗时 %.0fs）' % 0)
