Files

236 lines
7.9 KiB
Python

# -*- coding: utf-8 -*-
"""采一批真实的小学试卷图片,用于评测「拍题 → 切题 → 解析」。
只做一件事:按关键词搜图,下载、校验(尺寸 / 纸面特征 / 感知去重)、落盘。
不登录、不绕验证码、不抓需要付费的内容;每张图记录来源 URL,便于审计与回溯。
用途限定:**内部准确率评测**。图片不二次分发、不进公开仓库(`data/bench/` 已 gitignore)。
用法:
python bench/fetch.py --limit 24 # 小样本,先看产出率
python bench/fetch.py --limit 300 # 正式采(1 张 = 1 次切题调用)
python bench/fetch.py --queries 三年级数学期末试卷 --limit 10
"""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import random
import re
import sys
import time
import urllib.parse
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / "data" / "bench"
RAW = OUT / "raw"
META = OUT / "meta.jsonl"
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/124.0 Safari/537.36")
GRADES = ["一", "二", "三", "四", "五", "六"]
SUBJECTS = ["数学", "语文"]
PATTERNS = ["{g}年级{s}期末试卷", "{g}年级{s}上册期末试题", "{g}年级{s}错题"]
MURL = re.compile(r'murl(?:"|")\s*:\s*(?:"|")([^"&]+)')
def _get(url: str, referer: str = "https://www.bing.com/", timeout: int = 20) -> bytes:
req = urllib.request.Request(url, headers={
"User-Agent": UA,
"Referer": referer,
"Accept": "*/*",
"Accept-Language": "zh-CN,zh;q=0.9",
})
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.read()
def search(q: str, offset: int = 0, count: int = 35) -> list[dict]:
"""360 图片搜索(JSON),返回 [{url,title,w,h,link}]。
Bing 的 /images/search 对我们这个 UA 会返回不相关结果(问数学卷子给酸奶、绵羊),
360 的 j 接口稳定且带 width/height,可以在下载前就筛掉小图。
"""
qe = urllib.parse.quote(q)
url = ("https://image.so.com/j?q=%s&src=srp&correct=%s&sn=%d&pn=%d"
% (qe, qe, offset, count))
try:
raw = _get(url, referer="https://image.so.com/")
data = json.loads(raw.decode("utf-8", "ignore"))
except Exception as e: # noqa: BLE001
print(f" ! 搜索失败 {q}: {type(e).__name__}")
return []
out = []
for it in (data.get("list") or []):
u = it.get("img") or it.get("thumb") or ""
if not u.startswith("http"):
continue
try:
w, h = int(it.get("width") or 0), int(it.get("height") or 0)
except (TypeError, ValueError):
w = h = 0
out.append({"url": u, "title": it.get("title") or "",
"w": w, "h": h, "link": it.get("link") or it.get("purl") or ""})
return out
def _pil():
try:
from PIL import Image
return Image
except ImportError: # pragma: no cover
return None
def dhash(im) -> int:
"""8x8 差分哈希:同一张卷子的不同压缩版本会得到相同/相近的值。"""
g = im.convert("L").resize((9, 8))
px = list(g.getdata())
bits = 0
for row in range(8):
for col in range(8):
bits = (bits << 1) | (1 if px[row * 9 + col] > px[row * 9 + col + 1] else 0)
return bits
def paper_score(im) -> tuple[bool, str]:
"""像不像一张卷子:浅底、有字、不是商品图。"""
g = im.convert("L").resize((120, 160))
px = list(g.getdata())
n = len(px)
mean = sum(px) / n
dark = sum(1 for v in px if v < 110) / n
if mean < 150:
return False, f"dark(mean={mean:.0f})"
if not (0.004 <= dark <= 0.30):
return False, f"ink({dark:.3f})"
return True, f"mean={mean:.0f},ink={dark:.3f}"
def probe(data: bytes):
"""返回 (ok, why, w, h, dhash, image)。"""
Image = _pil()
if Image is None:
return False, "no-pil", 0, 0, 0, None
try:
im = Image.open(io.BytesIO(data))
im.load()
im = im.convert("RGB")
w, h = im.size
except Exception as e: # noqa: BLE001
return False, f"bad-image({type(e).__name__})", 0, 0, 0, None
if min(w, h) < 500:
return False, f"small({w}x{h})", w, h, 0, im
if max(w, h) > 8000:
return False, f"big({w}x{h})", w, h, 0, im
ratio = w / h if h else 0
if not (0.4 <= ratio <= 2.4):
return False, f"ratio({ratio:.2f})", w, h, 0, im
ok, why = paper_score(im)
if not ok:
return False, why, w, h, 0, im
return True, why, w, h, dhash(im), im
def save(im, q: str, url: str, w: int, h: int, why: str,
title: str = "", page: str = "") -> str:
KEEP = 12
buf = io.BytesIO()
im.save(buf, "JPEG", quality=92)
data = buf.getvalue()
sha = hashlib.sha1(data).hexdigest()[:16]
dst = RAW / f"{sha}.jpg"
if dst.exists():
return ""
dst.write_bytes(data)
with META.open("a", encoding="utf-8") as f:
f.write(json.dumps({"id": sha, "q": q, "url": url, "page": page, "title": title,
"w": w, "h": h, "bytes": len(data), "look": why,
"ts": int(time.time())},
ensure_ascii=False) + "\n")
return sha
def load_seen() -> list[int]:
"""已采过的图算一遍 dhash,后续新图跟它们比。"""
Image = _pil()
out = []
if Image is None or not RAW.exists():
return out
for f in RAW.glob("*.jpg"):
try:
out.append(dhash(Image.open(f)))
except Exception: # noqa: BLE001
continue
return out
def near_dup(h: int, seen: list[int], tol: int = 6) -> bool:
return any(bin(h ^ s).count("1") <= tol for s in seen)
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description="采小学试卷图片做评测")
ap.add_argument("--limit", type=int, default=60, help="最多保存多少张")
ap.add_argument("--per-query", type=int, default=35, help="每个关键词取多少候选")
ap.add_argument("--queries", nargs="*", default=None,
help="自定义关键词(默认 1–6 年级 × 数学/语文 × 3 种说法)")
args = ap.parse_args(argv)
RAW.mkdir(parents=True, exist_ok=True)
META.parent.mkdir(parents=True, exist_ok=True)
queries = args.queries or [p.format(g=g, s=s)
for g in GRADES for s in SUBJECTS for p in PATTERNS]
seen = load_seen()
saved = dup = bad = 0
for q in queries:
if saved >= args.limit:
break
cands = search(q, count=args.per_query)
print(f"[{q}] 候选 {len(cands)}")
for c in cands:
if saved >= args.limit:
break
u = c["url"]
# 下载前先按搜索给的尺寸筛:小学卷子竖版,短边太小的直接跳过
if c["w"] and c["h"] and min(c["w"], c["h"]) < 600:
bad += 1
continue
try:
data = _get(u, referer="https://image.so.com/")
except Exception: # noqa: BLE001
bad += 1
continue
if len(data) < 12_000:
bad += 1
continue
ok, why, w, h, hsh, im = probe(data)
if not ok:
bad += 1
continue
if near_dup(hsh, seen):
dup += 1
continue
if save(im, q, u, w, h, why, title=c["title"], page=c["link"]):
seen.append(hsh)
saved += 1
print(f" + {saved:3d} {w}x{h} {why}")
else:
dup += 1
time.sleep(random.uniform(0.5, 1.0))
time.sleep(random.uniform(0.8, 1.4))
print(f"\n完成:保存 {saved} / 重复 {dup} / 丢弃 {bad};目录 {RAW}")
return 0 if saved else 1
if __name__ == "__main__":
sys.exit(main())