Files
37duAutomation/tests/aitable_probe/probe_bankcard_images.py
T

112 lines
4.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""探针:用 aitable SDK 的下载能力,把「银行卡-变更收集表」两列照片取到本地。
表格:37°人资领域相关工作台账 / hr base(YndMj49yWjPmvXXDFb1OBGAoJ3pmz5aA)
sheet:银行卡-变更收集表(uavChPe)
目标列:银行卡卡号面照片、持卡人身份证照片(attachment,预签名 OSS url 约 2h 过期)
统计全量覆盖情况,并按 --limit 条记录落盘样本(默认 10 人);落盘目录已被 .gitignore 忽略。
用法(仓库根):
.venv\\Scripts\\python.exe tests\\aitable_probe\\probe_bankcard_images.py # 全量统计 + 10 人落盘
.venv\\Scripts\\python.exe tests\\aitable_probe\\probe_bankcard_images.py --limit 0 # 全量落盘
"""
from __future__ import annotations
import argparse
import json
import sys
import time
from pathlib import Path
HERE = Path(__file__).resolve().parent
REPO_ROOT = HERE.parents[1]
sys.path.insert(0, str(REPO_ROOT / "libs" / "aitable"))
from aitable.client import AiTable, attachment_items, resolve_base # noqa: E402
BASE = "hr"
SHEET = "uavChPe" # 银行卡-变更收集表
FIELDS = {"银行卡卡号面照片": "银行卡-", "持卡人身份证照片": "身份证-"} # 字段 → 文件名前缀
NAME_FIELD = "持卡人姓名"
def main() -> int:
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
ap = argparse.ArgumentParser()
ap.add_argument("--limit", type=int, default=10, help="落盘记录数(人),0=全量")
ap.add_argument("--out", default=str(HERE / "_out"), help="落盘目录")
args = ap.parse_args()
out_dir = Path(args.out)
cli = AiTable()
base, _ = resolve_base(BASE)
sheet = cli.resolve_sheet(base, SHEET)
print(f"base={base} sheet={sheet}({SHEET}) 拉记录…")
recs = cli.records(base, sheet)
stat = {"records": len(recs), "people_with_card": 0, "people_with_id": 0,
"people_with_both": 0, "card_images": 0, "id_images": 0,
"people_downloaded": 0, "downloaded": 0, "failed": 0,
"expired": 0, "size_mismatch": 0, "unknown_kind": 0, "bytes": 0}
details, seen = [], 0
for rec in recs:
f = rec.get("fields") or {}
card = attachment_items(f.get("银行卡卡号面照片"))
idc = attachment_items(f.get("持卡人身份证照片"))
stat["card_images"] += len(card)
stat["id_images"] += len(idc)
stat["people_with_card"] += bool(card)
stat["people_with_id"] += bool(idc)
stat["people_with_both"] += bool(card and idc)
if not (card or idc) or (args.limit and seen >= args.limit):
continue
seen += 1
stat["people_downloaded"] += 1
name = str(f.get(NAME_FIELD) or rec.get("id", ""))
folder = out_dir / name
row = {"记录id": rec.get("id", ""), "姓名": name, "files": []}
for field, prefix in FIELDS.items():
for r in cli.download_attachments(f.get(field), folder, prefix=prefix, col=field):
row["files"].append({k: r.get(k) for k in
("col", "filename", "ok", "bytes", "kind",
"size_match", "expired", "error")} |
{"path": Path(r["path"]).relative_to(out_dir).as_posix()})
if r["ok"]:
stat["downloaded"] += 1
stat["bytes"] += r.get("bytes") or 0
stat["size_mismatch"] += r.get("size_match") is False
stat["unknown_kind"] += r.get("kind") == "unknown"
elif r.get("expired"):
stat["expired"] += 1
else:
stat["failed"] += 1
details.append(row)
summary = {"base": base, "sheet": SHEET, "sheet_id": sheet,
"fields": list(FIELDS), "stats": stat,
"generated_at": time.strftime("%Y-%m-%d %H:%M:%S")}
out_dir.mkdir(parents=True, exist_ok=True)
(out_dir / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=1),
encoding="utf-8")
(out_dir / "details.json").write_text(json.dumps(details, ensure_ascii=False, indent=1),
encoding="utf-8")
print("\n===== 汇总 =====")
for k, v in stat.items():
print(f" {k:22s} {v}")
print(f"\n落盘:{stat['downloaded']} 个文件 / {stat['bytes'] / 1024:.0f} KB → {out_dir}")
bad = [x for d in details for x in d["files"] if not x.get("ok")]
for x in bad[:5]:
print(f"[x] {x.get('col')} {x.get('filename')}:{x.get('error')}")
return 0 if not bad else 1
if __name__ == "__main__":
raise SystemExit(main())