Files
37duAutomation/tests/download_xq0084_images.py
T

151 lines
6.5 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 -*-
"""把 XQ0084「银行卡-变更收集表」里的全部照片下载到本地。
输出(每次全量覆盖式复用目录,同名文件自动追加序号,不会删已有文件):
tests/_out/<工号>_<姓名>/银行卡_*.jpg
tests/_out/<工号>_<姓名>/身份证_*.jpg
tests/_out/_manifest.csv 记录 → 本地文件对照表
运行(仓库根目录,本地 .venv):
.venv\\Scripts\\python.exe tests\\download_xq0084_images.py
说明:
- 凭证 / base / sheet / 字段名全部从插件 config 读取,不在此重复写死;
- 钉钉附件是预签名地址(约 2 小时过期),脚本遇到「已过期」会自动重拉记录再试一次。
"""
from __future__ import annotations
import csv
import importlib.util
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
OUT_DIR = ROOT / "tests" / "_out"
CONFIG_FILE = (ROOT / "plugins" / "XQ0001-0100" / "XQ0084 银行卡更新EHR系统"
/ "config" / "__init__.py")
# 插件 SDK 未装进 .venv,这里按仓库目录直接挂上
sys.path.insert(0, str(ROOT / "libs" / "dingtalk"))
from dingtalk_sdk.aitable import AiTable, attachment_items, flatten # noqa: E402
def load_config():
"""把插件 config 当普通模块加载(它不 import 插件内其它模块)。"""
spec = importlib.util.spec_from_file_location("xq0084_config", str(CONFIG_FILE))
if spec is None or spec.loader is None:
raise SystemExit(f"读不到插件配置:{CONFIG_FILE}")
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def pick_folder(cfg, used: dict, item: dict) -> Path:
"""每条记录一个目录:<工号>_<姓名>;同名重复时补记录号后 6 位。"""
base = cfg.safe_name(f"{item['emp_no'] or '无工号'}_{item['holder'] or item['name'] or '无姓名'}")
folder = OUT_DIR / base
if base in used and used[base] != item["record_id"]:
folder = OUT_DIR / f"{base}_{item['record_id'][-6:]}"
used.setdefault(base, item["record_id"])
return folder
def download_batch(cli, cfg, items, used: dict, attempt: int):
"""下载一批记录的两个影像字段,返回需要重试的记录 id 集合(预签名过期)。"""
expired: set[str] = set()
for n, item in enumerate(items, 1):
folder = pick_folder(cfg, used, item)
print(f"[{attempt}-{n}/{len(items)}] {item['emp_no'] or '-'} {item['holder'] or item['name'] or '-'}"
f" → {folder.name}")
for field, prefix in ((cfg.F_CARD_IMG, "银行卡"), (cfg.F_ID_IMG, "身份证")):
value = item["fields"].get(field)
if value and not attachment_items(value):
print(f" ! {field} 无直连地址(可能只有相对 resourceUrl),跳过")
if not attachment_items(value):
continue
try:
got = cli.download_attachments(value, folder, prefix=f"{prefix}_", col=field)
except Exception as exc: # noqa: BLE001 单条失败不影响其它人
item["errors"].append(f"{field}: {exc}")
print(f" ! {field} 失败:{exc}")
continue
for g in got:
if g.get("ok") and g.get("path"):
item["files"].append(g["path"])
else:
msg = g.get("error") or "未知错误"
item["errors"].append(f"{field}/{g.get('filename')}: {msg}")
print(f" ! {g.get('filename')}:{msg}")
if g.get("expired"):
expired.add(item["record_id"])
print(f" 已存 {len(item['files'])} 个文件")
return expired
def main() -> int:
cfg = load_config()
OUT_DIR.mkdir(parents=True, exist_ok=True)
print(f"表:{cfg.AI_BASE} / {cfg.AI_SHEET}({cfg.PENDING_FIELD} 不过滤,全量下载)")
cli = AiTable(app_key=cfg.DINGTALK_APP_KEY, app_secret=cfg.DINGTALK_APP_SECRET,
operator=cfg.AITABLE_OPERATOR_UNIONID, log=lambda m: None)
records = cli.records(cfg.AI_BASE, cfg.AI_SHEET)
print(f"记录数:{len(records)}")
items = []
for rec in records:
fields = rec.get("fields") or {}
row = flatten(rec)
items.append({
"record_id": str(rec.get("id") or rec.get("recordId") or ""),
"fields": fields,
"row": row,
"name": cfg.text(row.get(cfg.F_EMP_NAME)),
"emp_no": cfg.text(row.get(cfg.F_EMP_NO)),
"holder": cfg.text(row.get(cfg.F_HOLDER)),
"card": cfg.text(row.get(cfg.F_CARD)),
"id_no": cfg.text(row.get(cfg.F_ID)),
"files": [],
"errors": [],
})
expired = download_batch(cli, cfg, items, {}, 1)
if expired:
print(f"有 {len(expired)} 条记录的附件地址过期,重新拉取记录后重试…")
fresh = {str(r.get("id") or ""): r for r in cli.records(cfg.AI_BASE, cfg.AI_SHEET)}
retry = []
for item in items:
if item["record_id"] in expired and item["record_id"] in fresh:
item["fields"] = fresh[item["record_id"]].get("fields") or {}
item["errors"] = [e for e in item["errors"] if "过期" not in e]
retry.append(item)
if retry:
download_batch(cli, cfg, retry, {}, 2)
# ---- 对照表(工号/姓名/表格登记卡号 → 本地文件),供后续核对识别准确率
manifest = OUT_DIR / "_manifest.csv"
with open(manifest, "w", newline="", encoding="utf-8-sig") as f:
w = csv.writer(f)
w.writerow(["记录ID", "工号", "姓名", "持卡人", "银行卡号", "身份证号",
"文件数", "错误", "文件"])
for item in items:
w.writerow([item["record_id"], item["emp_no"], item["name"], item["holder"],
item["card"], item["id_no"], len(item["files"]),
" | ".join(item["errors"]), " | ".join(item["files"])])
total = sum(len(i["files"]) for i in items)
bad = sum(1 for i in items if i["errors"])
print(f"\n完成:{total} 个文件,{len(items)} 条记录,{bad} 条有错误")
print(f"目录:{OUT_DIR}")
print(f"对照表:{manifest}")
for item in items:
for e in item["errors"]:
print(f" ! {item['emp_no']} {item['holder'] or item['name']}: {e}")
cli.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())