feat(sdk): desktopauto 0.5.3 银行卡/证件 OCR 增强、dingtalk 1.1.0、aitable 0.1.3

- desktopauto:cardocr 引擎/流水线/校验与 ocr 调整,sdk.json/pyproject/版本三处一致
- dingtalk:AI 表格读写与错误封装扩充
- aitable:client/cli/自测与打包配置更新
This commit is contained in:
2026-11-18 18:56:09 +08:00
parent 50fb138e1b
commit 39b768d0b7
26 changed files with 1043 additions and 93 deletions
+28
View File
@@ -38,11 +38,37 @@ $cli = "libs\aitable\aitable\cli.py"
& $py $cli list workplan --sheet hERWDMS --month 上线日期=2026-10 --json & $py $cli list workplan --sheet hERWDMS --month 上线日期=2026-10 --json
& $py $cli summary workplan --sheet hERWDMS --by 状态 & $py $cli summary workplan --sheet hERWDMS --by 状态
& $py $cli update workplan --sheet hERWDMS --record <id> --data '{\"状态\":\"上线\"}' --dry-run & $py $cli update workplan --sheet hERWDMS --record <id> --data '{\"状态\":\"上线\"}' --dry-run
& $py $cli download hr --sheet uavChPe --field 银行卡卡号面照片,持卡人身份证照片 --limit 10 --name-field 持卡人姓名 --prefix
``` ```
base 支持三种写法:别名(`workplan` / `hr`)、baseId、`https://alidocs.dingtalk.com/i/nodes/<baseId>?sheetId=xxx`。 base 支持三种写法:别名(`workplan` / `hr`)、baseId、`https://alidocs.dingtalk.com/i/nodes/<baseId>?sheetId=xxx`。
新增常用表在 `aitable/client.py` 的 `BASE_ALIASES` 里登记。 新增常用表在 `aitable/client.py` 的 `BASE_ALIASES` 里登记。
## 附件(图片 / 文件)下载
`attachment` 字段的元数据里带阿里云 OSS **预签名地址**(`url`,免 token 直连、约 2 小时过期),
库里已封装解析 + 下载(`resourceUrl` 是相对路径,不能直连):
```python
from aitable import AiTable, attachment_items
cli = AiTable()
rows = cli.records("hr", "uavChPe") # 银行卡-变更收集表
for r in rows:
v = r["fields"].get("银行卡卡号面照片")
print(attachment_items(v)) # [{resourceId, filename, size, type, url}]
for res in cli.download_attachments(v, r"D:\资料\银行卡照片\<姓名>"):
print(res["ok"], res["path"], res["kind"], res["size_match"])
```
返回字段:`ok / path / bytes / status / kind / content_type / size_match / expires_in / expired / error`。
要点:
- `expired=True`(预签名地址剩余 <60s 或下载 403)→ **重新拉记录换新 url**,不要重试同一地址;
- 落盘按 `prefix + 原文件名`,同名自动加 `-2`,非法字符换 `_`,文件名限长 120;
- `kind` 按文件头魔数判断真实类型,`size_match` 与表格里声明的 `size` 比对,防止存成错误页/半截文件;
- 单文件失败自动重试 3 次,仍失败在 `error` 里给原因;隐私图片勿入库(见根 `.gitignore`)。
## 月报 / 周报数据采集 ## 月报 / 周报数据采集
```powershell ```powershell
@@ -68,3 +94,5 @@ base 支持三种写法:别名(`workplan` / `hr`)、baseId、`https://alid
3. 日期是**毫秒时间戳 + 北京时间**(UTC 16:00 = 次日 00:00),自行换算易整体差一天。 3. 日期是**毫秒时间戳 + 北京时间**(UTC 16:00 = 次日 00:00),自行换算易整体差一天。
4. 写入:`singleSelect` 传选项名、`multipleSelect` 传数组、`date` 传毫秒、`user` 传 unionId 数组、`autoNumber` 只读。 4. 写入:`singleSelect` 传选项名、`multipleSelect` 传数组、`date` 传毫秒、`user` 传 unionId 数组、`autoNumber` 只读。
5. 部分 Windows 机器 `api.dingtalk.com` 的 A 记录解析失败(11001),库内置 DoH 兜底,可用 `AITABLE_DNS_IP` 覆盖。 5. 部分 Windows 机器 `api.dingtalk.com` 的 A 记录解析失败(11001),库内置 DoH 兜底,可用 `AITABLE_DNS_IP` 覆盖。
6. 附件 `url` 是预签名地址(含 `Expires`),**约 2 小时过期**:拉记录后要立刻下载,不能存 url 隔夜用;过期后只能重新 `records()` 换新地址。
7. 读接口拿不到附件二进制,只能按 `resourceId/filename/size/type/url` 走 `download_attachments()`;`resourceUrl` 是相对路径,直连会 404。
+99
View File
@@ -10,6 +10,7 @@ from __future__ import annotations
import os import os
import sys import sys
from datetime import date, datetime, timedelta, timezone from datetime import date, datetime, timedelta, timezone
from pathlib import Path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
@@ -109,6 +110,102 @@ def test_filters() -> None:
ok(len(cli.apply_filters(rows, [], ["上线日期=2026-10"])) == 1, "仅月份过滤") ok(len(cli.apply_filters(rows, [], ["上线日期=2026-10"])) == 1, "仅月份过滤")
def test_attachment_helpers() -> None:
from aitable.client import (attachment_items, parse_expires, safe_filename,
sniff_kind, unique_path)
val = [{"resourceId": "r1", "filename": "a.jpg", "size": 10, "type": "image",
"url": "https://x.oss-cn/y.jpg?Expires=1794886717&Signature=abc"},
{"resourceId": "r2", "filename": "b.png", "size": 5, "type": "image",
"resourceUrl": "/core/api/resources/img/zz"}]
its = attachment_items(val)
ok(len(its) == 2, "attachment 字段值拆出 2 个附件")
ok(its[0]["url"].startswith("https://") and its[0]["size"] == 10, "直连 url 与声明大小保留")
ok(its[1]["url"] == "", "相对 resourceUrl 不当作可直连地址")
ok(attachment_items(None) == [] and attachment_items({"filename": "c"})[0]["url"] == "",
"空值/单个 dict 兼容")
ok(parse_expires(its[0]["url"]) == 1794886717, "解析预签名 Expires")
ok(parse_expires("https://x/y.jpg") == 0, "无 Expires 返回 0")
ok(safe_filename('a/b:c*?"<>|.jpg') == "a_b_c_.jpg", "非法字符换下划线")
ok(safe_filename("", "") == "file" and safe_filename(" .. ") == "file", "空名兜底")
ok(len(safe_filename("x" * 200)) == 120, "文件名限长 120")
import tempfile
with tempfile.TemporaryDirectory() as d:
png, jpg, txt = (Path(d) / n for n in ("a.png", "b.jpg", "c.txt"))
png.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\0" * 8)
jpg.write_bytes(b"\xff\xd8\xff\xe0" + b"\0" * 8)
txt.write_text("hello", encoding="utf-8")
ok(sniff_kind(png) == "png" and sniff_kind(jpg) == "jpg", "按魔数识别 png/jpg")
ok(sniff_kind(txt) == "unknown", "非图片判为 unknown")
ok(sniff_kind(Path(d) / "nope.png") == "missing", "不存在的文件判为 missing")
ok(unique_path(png) == Path(d) / "a-2.png", "同名文件改名 -2")
(Path(d) / "a-2.png").write_bytes(b"x")
ok(unique_path(png) == Path(d) / "a-3.png", "再同名改名 -3")
def test_attachment_download() -> None:
"""本地 HTTP 服务模拟 OSS:验证下载、魔数/大小校验、同名不覆盖、403/过期判定。"""
import http.server
import socketserver
import tempfile
import threading
from aitable.client import AiTable, ATTACH_MIN_REMAIN # noqa: F401
png = b"\x89PNG\r\n\x1a\n" + b"\0" * 24
class _H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path.startswith("/ok"):
self.send_response(200)
self.send_header("content-type", "image/png")
self.send_header("content-length", str(len(png)))
self.end_headers()
self.wfile.write(png)
else:
self.send_response(403)
self.end_headers()
def log_message(self, *a):
pass
with socketserver.TCPServer(("127.0.0.1", 0), _H) as srv:
threading.Thread(target=srv.serve_forever, daemon=True).start()
port = srv.server_address[1]
base = f"http://127.0.0.1:{port}"
try:
cli_ = AiTable.__new__(AiTable) # 只测下载,不走鉴权初始化
with tempfile.TemporaryDirectory() as d:
r1 = cli_.download_attachment({"url": f"{base}/ok.png", "size": len(png)},
Path(d) / "x.png")
ok(r1["ok"] and r1["kind"] == "png" and r1["size_match"] is True
and r1["bytes"] == len(png), "下载成功 + 魔数/大小校验通过")
r2 = cli_.download_attachment({"url": f"{base}/ok.png", "size": len(png)},
Path(d) / "x.png")
ok(Path(r2["path"]).name == "x-2.png", "同名附件不覆盖,自动加 -2")
r3 = cli_.download_attachment({"url": f"{base}/deny.png"}, Path(d) / "y.png")
ok(r3["expired"] is True and r3["ok"] is False, "403 判定预签名 url 过期")
r4 = cli_.download_attachment({"url": f"{base}/ok.png?Expires=1000"},
Path(d) / "z.png")
ok(r4["expired"] is True and not (Path(d) / "z.png").exists(),
"Expires 已过期 → 不发请求、直接报过期")
multi = cli_.download_attachments(
[{"url": f"{base}/ok.png", "filename": "卡号面.jpg", "size": len(png)},
{"url": f"{base}/ok.png", "filename": "身份证.png", "size": len(png)}],
Path(d) / "sub", prefix="银行卡-", col="银行卡卡号面照片")
names = sorted(Path(x["path"]).name for x in multi)
ok(len(multi) == 2 and all(x["ok"] for x in multi), "多附件字段批量下载")
ok(names == ["银行卡-卡号面.jpg", "银行卡-身份证.png"], "prefix + 原文件名")
ok(multi[0]["col"] == "银行卡卡号面照片" and multi[1]["index"] == 2,
"结果带字段名与序号")
finally:
srv.shutdown()
def test_online() -> None: def test_online() -> None:
from aitable import AiTable from aitable import AiTable
cli_ = AiTable() cli_ = AiTable()
@@ -131,6 +228,8 @@ def main() -> int:
test_resolve_base() test_resolve_base()
test_period() test_period()
test_filters() test_filters()
test_attachment_helpers()
test_attachment_download()
if "--online" in sys.argv: if "--online" in sys.argv:
test_online() test_online()
print(f"\n全部通过:{_passed} 项") print(f"\n全部通过:{_passed} 项")
+23 -20
View File
@@ -1,20 +1,23 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""aitable · 钉钉 AI 表格(notable)读写库 + 月报/周报数据采集。 """aitable · 钉钉 AI 表格(notable)读写库 + 月报/周报数据采集。
对外只暴露三样: 对外暴露:
- AiTable 表格客户端(列 sheet/字段、分页读、批量增改) - AiTable 表格客户端(列 sheet/字段、分页读、批量增改、附件下载)
- cli / report 两个命令行入口(python -m aitable / python -m aitable.report) - cli / report 两个命令行入口(python -m aitable / python -m aitable.report)
- 值归一工具 norm / to_ms / coerce_for_fields / flatten(写插件回填时常用) - 值归一工具 norm / to_ms / coerce_for_fields / flatten(写插件回填时常用)
""" - 附件工具 attachment_items / safe_filename / sniff_kind / parse_expires
from __future__ import annotations """
from __future__ import annotations
from .client import ( # noqa: F401
BASE_ALIASES, DEFAULT_OPERATOR, AiTable, coerce_for_fields, flatten, from .client import ( # noqa: F401
install_dns_fallback, ms_to_str, norm, resolve_base, to_ms, BASE_ALIASES, DEFAULT_OPERATOR, AiTable, attachment_items, coerce_for_fields,
) flatten, install_dns_fallback, ms_to_str, norm, parse_expires, resolve_base,
safe_filename, sniff_kind, to_ms,
__version__ = "1.0.0" )
__all__ = [
"AiTable", "BASE_ALIASES", "DEFAULT_OPERATOR", "coerce_for_fields", "flatten", __version__ = "1.1.0"
"install_dns_fallback", "ms_to_str", "norm", "resolve_base", "to_ms", __all__ = [
] "AiTable", "BASE_ALIASES", "DEFAULT_OPERATOR", "attachment_items",
"coerce_for_fields", "flatten", "install_dns_fallback", "ms_to_str", "norm",
"parse_expires", "resolve_base", "safe_filename", "sniff_kind", "to_ms",
]
+73 -4
View File
@@ -20,12 +20,12 @@ from pathlib import Path
from typing import Any from typing import Any
try: # 作为包导入 try: # 作为包导入
from .client import (AiTable, DEFAULT_OPERATOR, coerce_for_fields, flatten, from .client import (AiTable, DEFAULT_OPERATOR, attachment_items,
resolve_base) coerce_for_fields, flatten, norm, resolve_base, safe_filename)
except ImportError: # 直接执行文件 except ImportError: # 直接执行文件
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from aitable.client import (AiTable, DEFAULT_OPERATOR, coerce_for_fields, # noqa: F401 from aitable.client import (AiTable, DEFAULT_OPERATOR, attachment_items, # noqa: F401
flatten, resolve_base) coerce_for_fields, flatten, norm, resolve_base, safe_filename)
# ==================== 过滤 / 输出 ==================== # ==================== 过滤 / 输出 ====================
@@ -179,6 +179,61 @@ def _cmd_summary(args, cli) -> int:
return 0 return 0
def _cmd_download(args, cli) -> int:
"""把 attachment 字段(图片/文件)下载到本地:每记录一个子目录,按字段分组落盘。"""
base, link_sheet = resolve_base(args.base)
sheet = _sheet_arg(args, cli, base, link_sheet)
cols = [c.strip() for c in args.field.split(",") if c.strip()]
if not cols:
raise SystemExit("[x] --field 至少给一个字段名")
recs = cli.records(base, sheet)
if args.where:
keep = {r["_id"] for r in apply_filters([flatten(x) for x in recs], args.where, [])}
recs = [x for x in recs if x.get("id") in keep]
out_root = Path(args.out or f"aitable_downloads/{sheet}")
results, people, total = [], 0, 0
for rec in recs:
f = rec.get("fields") or {}
got = {c: attachment_items(f.get(c)) for c in cols}
if not any(got.values()): # 该记录这些字段都没有附件,跳过
continue
if args.limit and people >= args.limit:
break
people += 1
label = str(norm(f.get(args.name_field))) if args.name_field else ""
folder = out_root / safe_filename(label or rec.get("id", ""), rec.get("id", "rec"))
for c in cols:
prefix = f"{safe_filename(c)}-" if args.prefix else ""
for r in cli.download_attachments(got[c], folder, prefix=prefix, col=c):
total += 1
results.append({"记录id": rec.get("id", ""), "姓名": label,
"字段": c, "文件": r.get("filename", ""),
"ok": r.get("ok"), "path": r.get("path", ""),
"bytes": r.get("bytes", 0), "kind": r.get("kind", ""),
"size_match": r.get("size_match"),
"expired": r.get("expired"), "error": r.get("error", "")})
okn = sum(1 for r in results if r["ok"])
bad = [r for r in results if not r["ok"]]
expired = [r for r in results if r.get("expired")]
summary = {"sheet": sheet, "fields": cols, "out": str(out_root),
"records": people, "attachments": total, "downloaded": okn,
"failed": len(bad), "expired": len(expired),
"bytes": sum(r["bytes"] or 0 for r in results)}
if args.json:
emit_json({"summary": summary, "items": results})
else:
print(f"{people} 条记录 / {total} 个附件 → 成功 {okn},失败 {len(bad)}"
f"(过期 {len(expired)}),共 {summary['bytes'] / 1024:.0f} KB")
print(f"落盘:{out_root}")
for r in bad:
print(f"[x] {r['记录id']} {r['姓名']} {r['字段']} {r['文件']}:"
f"{r['error'] or '下载失败'}")
return 0 if not bad else 1
def _load_data(raw: str, file_path: str) -> dict: def _load_data(raw: str, file_path: str) -> dict:
if raw and file_path: if raw and file_path:
raise SystemExit("[x] --data 与 --data-file 只能二选一") raise SystemExit("[x] --data 与 --data-file 只能二选一")
@@ -262,6 +317,20 @@ def build_parser() -> argparse.ArgumentParser:
s.add_argument("--month", action="append", default=[], metavar="日期字段=YYYY-MM") s.add_argument("--month", action="append", default=[], metavar="日期字段=YYYY-MM")
s.set_defaults(func=_cmd_summary) s.set_defaults(func=_cmd_summary)
s = sub.add_parser("download", help="下载 attachment(图片/文件)字段到本地目录",
parents=[common])
s.add_argument("base")
s.add_argument("--sheet", default="")
s.add_argument("--field", required=True, metavar="字段名[,字段名]",
help="要下载的附件字段,逗号分隔")
s.add_argument("--out", default="", help="落盘根目录(默认 aitable_downloads/<sheetId>)")
s.add_argument("--limit", type=int, default=0, help="最多处理多少条记录,0=全部")
s.add_argument("--name-field", default="", help="用该字段值作子目录名,默认记录 id")
s.add_argument("--prefix", action="store_true", help="文件名前加字段名,便于区分多列")
s.add_argument("--where", action="append", default=[], metavar="字段=值",
help="等值过滤,可重复(AND)")
s.set_defaults(func=_cmd_download)
s = sub.add_parser("add", help="新增记录", parents=[common]) s = sub.add_parser("add", help="新增记录", parents=[common])
s.add_argument("base") s.add_argument("base")
s.add_argument("--sheet", default="") s.add_argument("--sheet", default="")
+153 -1
View File
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""钉钉 AI 表格(notable)客户端:鉴权、分页读取、字段归一、按类型写值。 """钉钉 AI 表格(notable)客户端:鉴权、分页读取、字段归一、按类型写值、附件下载。
凭证读取顺序(**不读已废弃的 desktop/controlplane/.env**): 凭证读取顺序(**不读已废弃的 desktop/controlplane/.env**):
1. 环境变量 AITABLE_ENV_FILE 指定的 .env 1. 环境变量 AITABLE_ENV_FILE 指定的 .env
@@ -11,8 +11,10 @@ from __future__ import annotations
import json import json
import os import os
import re
import socket import socket
import time import time
import urllib.parse as urllib_parse
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from pathlib import Path from pathlib import Path
from typing import Any, Optional from typing import Any, Optional
@@ -183,6 +185,85 @@ def flatten(rec: dict) -> dict:
return row return row
# ==================== 附件(图片 / 文件)====================
ATTACH_RETRY = 3 # 单文件下载重试次数
ATTACH_TIMEOUT = 30
ATTACH_MIN_REMAIN = 60 # 预签名 url 剩余有效期低于该秒数即视为不可用
_BAD_NAME = re.compile(r'[\\/:*?"<>|\r\n\t]+')
_MAGIC = ((b"\xff\xd8\xff", "jpg"), (b"\x89PNG\r\n\x1a\n", "png"),
(b"GIF87a", "gif"), (b"GIF89a", "gif"), (b"BM", "bmp"), (b"%PDF", "pdf"))
def attachment_items(value: Any) -> list:
"""attachment 字段值 → [{resourceId, filename, size, type, url}]。
notable 返回的附件元数据里 `url` 是阿里云 OSS **预签名地址**(免 token 直连,
约 2 小时过期);`resourceUrl` 是相对路径,不能直连,故只保留绝对 url。
"""
if not value:
return []
if isinstance(value, dict):
value = [value]
out = []
for it in value:
if not isinstance(it, dict):
continue
url = str(it.get("url") or "")
if not url.startswith(("http://", "https://")):
url = ""
out.append({"resourceId": it.get("resourceId") or "",
"filename": it.get("filename") or "",
"size": int(it.get("size") or 0),
"type": it.get("type") or "",
"url": url})
return out
def parse_expires(url: str) -> int:
"""预签名 url 的 `Expires` 秒级时间戳;取不到返回 0(不限时的地址)。"""
try:
q = urllib_parse.parse_qs(urllib_parse.urlparse(url).query)
return int((q.get("Expires") or ["0"])[0] or 0)
except (TypeError, ValueError):
return 0
def safe_filename(name: Any, fallback: str = "file") -> str:
"""文件名净化:Windows 非法字符换 `_`、去首尾点空格、限长 120。"""
s = _BAD_NAME.sub("_", str(name or "")).strip(" .")
if not s:
s = _BAD_NAME.sub("_", str(fallback or "file")).strip(" .") or "file"
return s[:120]
def sniff_kind(path: Any) -> str:
"""按文件头魔数判断真实类型(防止把错误页/占位图当图片)。"""
try:
head = Path(path).read_bytes()[:16]
except OSError:
return "missing"
if head[:4] == b"RIFF" and b"WEBP" in head[:16]:
return "webp"
for sig, kind in _MAGIC:
if head.startswith(sig):
return kind
return "unknown"
def unique_path(dest: Path) -> Path:
"""目标已存在时追加 `-2`、`-3`…,避免同名附件互相覆盖。"""
dest = Path(dest)
if not dest.exists():
return dest
n = 2
while True:
cand = dest.with_name(f"{dest.stem}-{n}{dest.suffix}")
if not cand.exists():
return cand
n += 1
# ==================== 客户端 ==================== # ==================== 客户端 ====================
class AiTable: class AiTable:
@@ -292,6 +373,77 @@ class AiTable:
ok += len(d.get("value") or batch) ok += len(d.get("value") or batch)
return ok return ok
# ---- 附件(图片 / 文件)下载 ----
def download_attachment(self, item: dict, dest: Any, retries: int = ATTACH_RETRY,
overwrite: bool = False) -> dict:
"""下载单个附件到 dest。
返回 dict:ok / path / bytes / status / kind / content_type / size_match /
expires_in / expired / error。`expired=True` 表示预签名 url 已过期或 403,
需重新拉记录换新 url(不要重试同一个地址)。
"""
dest = Path(dest)
info: dict = {"ok": False, "path": str(dest), "bytes": 0, "status": 0,
"kind": "", "content_type": "", "size_match": None,
"expires_in": None, "expired": False, "error": ""}
item = item or {}
url = str(item.get("url") or "")
if not url:
info["error"] = "附件没有可直连的 url(只有相对 resourceUrl)"
return info
exp = parse_expires(url)
if exp:
info["expires_in"] = int(exp - time.time())
if info["expires_in"] <= ATTACH_MIN_REMAIN:
info["expired"] = True
info["error"] = f"预签名 url 已过期/即将过期(剩 {info['expires_in']}s),请重新拉记录"
return info
target = dest if overwrite else unique_path(dest)
info["path"] = str(target)
last: Any = None
for attempt in range(1, retries + 1):
try:
r = requests.get(url, timeout=ATTACH_TIMEOUT)
if r.status_code == 403: # OSS 签名过期/无权限:重试同一地址无意义
info.update(status=403, expired=True,
error="下载被拒(403,url 可能已过期),请重新拉记录")
return info
r.raise_for_status()
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(r.content)
declared = int(item.get("size") or 0)
info.update(ok=True, status=r.status_code, bytes=len(r.content),
content_type=r.headers.get("content-type", ""),
kind=sniff_kind(target),
size_match=(None if not declared else
len(r.content) == declared))
return info
except Exception as exc: # 网络抖动 / 限流 / 5xx
last = exc
if attempt < retries:
time.sleep(RETRY_DELAY_BASE * attempt)
info["error"] = repr(last)
return info
def download_attachments(self, value: Any, save_dir: Any, prefix: str = "",
col: str = "", retries: int = ATTACH_RETRY,
overwrite: bool = False) -> list:
"""下载一个 attachment 字段的全部附件到 save_dir/(`prefix + 原文件名` 命名)。
返回每个附件的 download_attachment 结果列表(额外带 col/index/filename/
resourceId/declared_size)。多图字段按 index 顺序落盘,重名自动加 `-2`。
"""
out = []
for i, it in enumerate(attachment_items(value), 1):
name = safe_filename(it["filename"], it["resourceId"] or f"{col or 'file'}{i}")
dest = Path(save_dir) / safe_filename(f"{prefix}{name}" if prefix else name)
r = self.download_attachment(it, dest, retries=retries, overwrite=overwrite)
r.update(col=col or "", index=i, filename=it["filename"],
resourceId=it["resourceId"], declared_size=it["size"])
out.append(r)
return out
def resolve_base(raw: str) -> tuple: def resolve_base(raw: str) -> tuple:
"""别名 / baseId / alidocs 链接 → (baseId, 链接里带的 sheetId 或空)。""" """别名 / baseId / alidocs 链接 → (baseId, 链接里带的 sheetId 或空)。"""
+2 -2
View File
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "aitable" name = "aitable"
version = "1.0.0" version = "1.1.0"
description = "钉钉 AI 表格(notable)读写库:列 sheet/字段、分页读取、过滤统计、按类型写值,附月报/周报数据采集" description = "钉钉 AI 表格(notable)读写库:列 sheet/字段、分页读取、过滤统计、按类型写值、附件图片下载,附月报/周报数据采集"
readme = "README.md" readme = "README.md"
requires-python = ">=3.9" requires-python = ">=3.9"
dependencies = [ dependencies = [
+7 -1
View File
@@ -1,7 +1,7 @@
{ {
"schema_version": 1, "schema_version": 1,
"sdk_id": "desktopauto", "sdk_id": "desktopauto",
"version": "0.5.0", "version": "0.5.3",
"modules": { "modules": {
"desktopauto": { "desktopauto": {
"exports": [ "exports": [
@@ -501,8 +501,10 @@
"cv2", "cv2",
"dataclass", "dataclass",
"expand_pts", "expand_pts",
"find_card_color",
"find_cards", "find_cards",
"four_point_warp", "four_point_warp",
"locate_bank_card",
"np", "np",
"order_points", "order_points",
"quad_area", "quad_area",
@@ -518,8 +520,10 @@
"Tuple": "(*args, **kwargs)", "Tuple": "(*args, **kwargs)",
"dataclass": "(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)", "dataclass": "(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)",
"expand_pts": "(pts: 'np.ndarray', ratio: 'float', shape: 'Tuple[int, int]') -> 'np.ndarray'", "expand_pts": "(pts: 'np.ndarray', ratio: 'float', shape: 'Tuple[int, int]') -> 'np.ndarray'",
"find_card_color": "(img: 'np.ndarray', warp_width: 'int' = 1712) -> 'Optional[CardRegion]'",
"find_cards": "(img: 'np.ndarray', max_cards: 'int' = 3, warp_width: 'int' = 0) -> 'List[CardRegion]'", "find_cards": "(img: 'np.ndarray', max_cards: 'int' = 3, warp_width: 'int' = 0) -> 'List[CardRegion]'",
"four_point_warp": "(img: 'np.ndarray', pts: 'Sequence[Sequence[float]]', width: 'int' = 0, height: 'int' = 0) -> 'Tuple[np.ndarray, np.ndarray]'", "four_point_warp": "(img: 'np.ndarray', pts: 'Sequence[Sequence[float]]', width: 'int' = 0, height: 'int' = 0) -> 'Tuple[np.ndarray, np.ndarray]'",
"locate_bank_card": "(img: 'np.ndarray', warp_width: 'int' = 1712) -> 'Optional[np.ndarray]'",
"order_points": "(pts: 'Sequence[Sequence[float]]') -> 'np.ndarray'", "order_points": "(pts: 'Sequence[Sequence[float]]') -> 'np.ndarray'",
"quad_area": "(pts: 'np.ndarray') -> 'float'", "quad_area": "(pts: 'np.ndarray') -> 'float'",
"sqrt_": "(x: 'float') -> 'float'", "sqrt_": "(x: 'float') -> 'float'",
@@ -808,6 +812,7 @@
"idline", "idline",
"imread", "imread",
"join_text", "join_text",
"locate_bank_card",
"logger", "logger",
"logging", "logging",
"normalize_text", "normalize_text",
@@ -850,6 +855,7 @@
"idline": "(views: 'Sequence[View]', kind: 'str') -> 'List[Line]'", "idline": "(views: 'Sequence[View]', kind: 'str') -> 'List[Line]'",
"imread": "(path: 'str') -> 'np.ndarray'", "imread": "(path: 'str') -> 'np.ndarray'",
"join_text": "(items: 'List[Line]') -> 'str'", "join_text": "(items: 'List[Line]') -> 'str'",
"locate_bank_card": "(img: 'np.ndarray', warp_width: 'int' = 1712) -> 'Optional[np.ndarray]'",
"normalize_text": "(text: 'str') -> 'str'", "normalize_text": "(text: 'str') -> 'str'",
"number_runs": "(text: 'str', min_len: 'int' = 6) -> 'List[str]'", "number_runs": "(text: 'str', min_len: 'int' = 6) -> 'List[str]'",
"ocr_lines": "(img: 'np.ndarray', min_score: 'float' = 0.0) -> 'List[Line]'", "ocr_lines": "(img: 'np.ndarray', min_score: 'float' = 0.0) -> 'List[Line]'",
+1 -1
View File
@@ -104,4 +104,4 @@ __all__ = [
"mark", "summarize", "mark", "summarize",
] ]
__version__ = "0.5.0" __version__ = "0.5.3"
+1 -1
View File
@@ -10,7 +10,7 @@ import numpy as np
from . import matcher from . import matcher
EXPECTED_VERSION = "0.5.0" EXPECTED_VERSION = "0.5.3"
#: 插件实际用到的门面 API,缺失即视为破坏性变更 #: 插件实际用到的门面 API,缺失即视为破坏性变更
REQUIRED_EXPORTS = ( REQUIRED_EXPORTS = (
@@ -14,9 +14,10 @@ BANK_KEYWORDS = ("银行", "银联", "UnionPay", "UNIONPAY", "Debit", "Credit",
"信用卡", "储蓄卡", "一卡通", "招商", "农业", "工商", "建设", "民生", "信用卡", "储蓄卡", "一卡通", "招商", "农业", "工商", "建设", "民生",
"兴业", "浦发", "交通", "邮政", "中信", "光大", "华夏", "广发", "平安") "兴业", "浦发", "交通", "邮政", "中信", "光大", "华夏", "广发", "平安")
BANK_NAMES = ("中国工商银行", "中国农业银行", "中国建设银行", "中国银行", "招商银行", BANK_NAMES = ("重庆农村商业银行", "重庆三峡银行", "中国工商银行", "中国农业银行",
"中国民生银行", "兴业银行", "浦发银行", "交通银行", "中国邮政储蓄银行", "中国建设银行", "中国银行", "招商银行", "中国民生银行", "兴业银行",
"中信银行", "中国光大银行", "华夏银行", "广发银行", "平安银行") "浦发银行", "交通银行", "中国邮政储蓄银行", "中信银行", "中国光大银行",
"华夏银行", "广发银行", "平安银行")
_VALID_BANK_LEN = (16, 18, 19) _VALID_BANK_LEN = (16, 18, 19)
@@ -64,7 +65,9 @@ def _bank_from_face(text: str) -> str:
"招商": "招商银行", "民生": "中国民生银行", "兴业": "兴业银行", "招商": "招商银行", "民生": "中国民生银行", "兴业": "兴业银行",
"浦发": "浦发银行", "交通": "交通银行", "邮政": "中国邮政储蓄银行", "浦发": "浦发银行", "交通": "交通银行", "邮政": "中国邮政储蓄银行",
"中信": "中信银行", "光大": "中国光大银行", "华夏": "华夏银行", "中信": "中信银行", "光大": "中国光大银行", "华夏": "华夏银行",
"广发": "广发银行", "平安": "平安银行"} "广发": "广发银行", "平安": "平安银行",
"重庆农商": "重庆农村商业银行", "重庆农村商业": "重庆农村商业银行",
"三峡": "重庆三峡银行"}
for k, v in short.items(): for k, v in short.items():
if k + "银行" in text or k in text: if k + "银行" in text or k in text:
return v return v
@@ -141,3 +141,126 @@ def expand_pts(pts: np.ndarray, ratio: float, shape: Tuple[int, int]) -> np.ndar
"""把四边形向外扩一点(卡片边缘会把字裁掉时用)。""" """把四边形向外扩一点(卡片边缘会把字裁掉时用)。"""
c = pts.mean(axis=0) c = pts.mean(axis=0)
return (pts - c) * (1.0 + ratio) + c return (pts - c) * (1.0 + ratio) + c
# ---------------------------------------------------------------- 色块兜底定位
# Canny 找四边形要求卡边基本连续,反光/压边/桌面同色时常直接失败(实测有的卡图
# 一张都找不到)。卡面通常是一整块同色区域,所以再补两条更宽松的路子:
# 1) 量化主色相 → 色块掩膜 → 最大轮廓 → 最小外接矩形;
# 2) Canny 边缘闭运算桥接反光断口 → 最大几个轮廓 → 最小外接矩形。
def _mask_card_rects(small: np.ndarray) -> List[Tuple]:
hsv = cv2.cvtColor(small, cv2.COLOR_BGR2HSV)
h, w = small.shape[:2]
sel = (hsv[..., 1] > 60) & (hsv[..., 2] > 25)
if int(sel.sum()) < h * w * 0.02:
return []
hue = hsv[..., 0][sel].astype(np.int32)
hist = np.bincount(hue // 15, minlength=12)[:12]
out: List[Tuple] = []
for t in np.argsort(hist)[::-1][:2]:
if hist[t] < h * w * 0.01:
continue
lo = int(t * 15)
m = cv2.inRange(hsv, (lo, 60, 25), (lo + 14, 255, 255))
m = cv2.morphologyEx(m, cv2.MORPH_CLOSE, np.ones((41, 41), np.uint8))
m = cv2.morphologyEx(m, cv2.MORPH_OPEN, np.ones((11, 11), np.uint8))
cnts, _ = cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if not cnts:
continue
c = max(cnts, key=cv2.contourArea)
if cv2.contourArea(c) < h * w * 0.05:
continue
out.append(cv2.minAreaRect(c))
return out
def _edge_card_rects(small: np.ndarray) -> List[Tuple]:
h, w = small.shape[:2]
edges = cv2.Canny(cv2.GaussianBlur(to_gray(small), (5, 5), 0), 40, 120)
# 大核闭运算把反光造成的断口接上,否则轮廓不闭合
edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, np.ones((15, 15), np.uint8))
cnts, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
out: List[Tuple] = []
for c in sorted(cnts, key=cv2.contourArea, reverse=True)[:5]:
if cv2.contourArea(c) < h * w * 0.05:
continue
out.append(cv2.minAreaRect(c))
return out
def _warp_card(img: np.ndarray, rect: Tuple, width: int) -> np.ndarray:
"""按最小外接矩形矫正,并保证「卡长边 → 图宽」(否则会横拉成瘦长条)。"""
(cx, cy), (rw, rh), ang = rect
box = cv2.boxPoints(((cx, cy), (rw, rh), ang)).astype(np.float32)
pts = order_points(box)
e_w = float(np.linalg.norm(pts[1] - pts[0])) # 将映射到「宽」的那条边
e_h = float(np.linalg.norm(pts[3] - pts[0])) # 将映射到「高」的那条边
if e_w < e_h: # 横边是短边 → 卡长边在竖直方向
pts = np.roll(pts, -1, axis=0)
w = int(width)
h = int(round(width / CARD_ASPECT))
m = cv2.getPerspectiveTransform(
pts, np.float32([[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]]))
return cv2.warpPerspective(img, m, (w, h), flags=cv2.INTER_CUBIC)
def find_card_color(img: np.ndarray, warp_width: int = 1712) -> Optional[CardRegion]:
"""色块/边缘兜底找卡(find_cards 失败时用),返回已矫正的卡图。
比例按 85.6:54 还原,长边对应图宽;方向(上下/左右)不在这里判,由调用方
根据 OCR 结果决定,避免再引入一次不可靠的方向猜测。
"""
h, w = img.shape[:2]
scale = 1000.0 / max(h, w)
if scale < 1.0:
small = cv2.resize(img, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
inv = 1.0 / scale
else:
small, inv = img, 1.0
rects = _mask_card_rects(small) + _edge_card_rects(small)
best, best_score = None, 0.0
for rect in rects:
(cx, cy), (rw, rh), ang = rect
if min(rw, rh) <= 0:
continue
# 只按长宽比评分,不奖励面积:边缘法经常把「卡+桌面」框成一个同样比例的大矩形,
# 按面积优选就会选中那个,矫正后的卡反而变小、卡号更难认。
score = _aspect_score(max(rw, rh) / min(rw, rh))
if score > best_score:
best, best_score = rect, score
if best is None:
return None
(cx, cy), (rw, rh), ang = best
rect_full = ((cx * inv, cy * inv), (rw * inv, rh * inv), ang)
pts = order_points(cv2.boxPoints(rect_full).astype(np.float32))
region = CardRegion(pts=pts, area=rw * rh * inv * inv,
aspect=max(rw, rh) / min(rw, rh), score=best_score,
source="color")
region.warped = _warp_card(img, rect_full, warp_width)
return region
def _digit_score(lines) -> int:
n = sum(1 for x in lines for ch in x.text if ch.isdigit())
rows = sum(1 for x in lines if sum(ch.isdigit() for ch in x.text) >= 4)
return n + 5 * rows
def locate_bank_card(img: np.ndarray, warp_width: int = 1712) -> Optional[np.ndarray]:
"""色块兜底找卡 + 用 OCR 结果判方向,返回「摆正的卡图」;找不到返回 None。"""
region = find_card_color(img, warp_width=warp_width)
if region is None or region.warped is None or region.warped.size == 0:
return None
from .engine import lines as ocr_lines # noqa: PLC0415 避免循环引用
card = region.warped
scored = [(_digit_score(ocr_lines(np.ascontiguousarray(np.rot90(card, k)))), k)
for k in (0, 2)]
scored.sort(reverse=True)
if scored[0][0] <= 0: # 0/180 都读不到数字,说明卡是横躺的
scored = [(_digit_score(ocr_lines(np.ascontiguousarray(np.rot90(card, k)))), k)
for k in (1, 3)]
scored.sort(reverse=True)
k = scored[0][1]
return np.ascontiguousarray(np.rot90(card, k))
+14 -2
View File
@@ -57,6 +57,18 @@ def engine_available() -> bool:
return False return False
def _silence_rapidocr() -> None:
"""把 RapidOCR 自带的控制台日志压到 ERROR。
RapidOCR 在 import 时给 "RapidOCR" logger 挂了 stderr handler,识别不到文字等
WARNING 会直接写 stderr,被执行机当成 ERROR 刷进运行日志(`[ERROR] [WARNING] ...`)。
这里只压掉 WARNING 及以下的噪音,ERROR 仍然保留。
"""
lg = logging.getLogger("RapidOCR")
lg.setLevel(logging.ERROR)
lg.propagate = False
def _get_engine(): def _get_engine():
global _ENGINE global _ENGINE
if _ENGINE is not None: if _ENGINE is not None:
@@ -68,7 +80,7 @@ def _get_engine():
# 固定线程数:默认会按核数开线程,在共享办公机上反而抖动严重(同一张图 2s~13s) # 固定线程数:默认会按核数开线程,在共享办公机上反而抖动严重(同一张图 2s~13s)
params = { params = {
"Global.log_level": "WARNING", "Global.log_level": "ERROR",
"EngineConfig.onnxruntime.intra_op_num_threads": 4, "EngineConfig.onnxruntime.intra_op_num_threads": 4,
"EngineConfig.onnxruntime.inter_op_num_threads": 1, "EngineConfig.onnxruntime.inter_op_num_threads": 1,
} }
@@ -76,7 +88,7 @@ def _get_engine():
_ENGINE = RapidOCR(params=params) _ENGINE = RapidOCR(params=params)
except Exception: # noqa: BLE001 旧版本不支持 params except Exception: # noqa: BLE001 旧版本不支持 params
_ENGINE = RapidOCR() _ENGINE = RapidOCR()
logging.getLogger("RapidOCR").setLevel(logging.WARNING) _silence_rapidocr()
return _ENGINE return _ENGINE
@@ -166,7 +166,8 @@ def find_number_bands(gray: np.ndarray, limit: int = _MAX_BANDS
) -> List[Tuple[int, int, int, int]]: ) -> List[Tuple[int, int, int, int]]:
"""定位卡号带的若干候选(按可能性排序),返回 [(x1, y1, x2, y2), ...]。 """定位卡号带的若干候选(按可能性排序),返回 [(x1, y1, x2, y2), ...]。
只做「纵向定位」:横向跨度交给 _SPAN_RATIOS 先验,避免被花纹干扰。 返回的 x 跨度是 MSER 行自己的实际范围(不再写死整图 3%~97%),
这样卡片没占满画面、或者只是裁出来的卡图,分组窗口都能对得上。
""" """
if gray is None or gray.size == 0: if gray is None or gray.size == 0:
return [] return []
@@ -189,13 +190,14 @@ def find_number_bands(gray: np.ndarray, limit: int = _MAX_BANDS
continue continue
med_h = float(np.median([b[3] for b in row])) med_h = float(np.median([b[3] for b in row]))
score = 2.0 * span + min(len(row), 12) / 12.0 + 12.0 * (med_h / small.shape[0]) score = 2.0 * span + min(len(row), 12) / 12.0 + 12.0 * (med_h / small.shape[0])
scraped.append((score, float(np.median([b[1] + b[3] / 2.0 for b in row])), med_h, row)) scraped.append((score, float(np.median([b[1] + b[3] / 2.0 for b in row])), med_h,
float(x1), float(x2)))
scraped.sort(key=lambda x: -x[0]) scraped.sort(key=lambda x: -x[0])
inv = 1.0 / scale if scale < 1.0 else 1.0 inv = 1.0 / scale if scale < 1.0 else 1.0
out: List[Tuple[int, int, int, int]] = [] out: List[Tuple[int, int, int, int]] = []
centers: List[float] = [] centers: List[float] = []
for _score, yc_s, med_h_s, _row in scraped: for _score, yc_s, med_h_s, x1_s, x2_s in scraped:
yc, med_h = yc_s * inv, med_h_s * inv yc, med_h = yc_s * inv, med_h_s * inv
if any(abs(yc - c) < max(med_h * 0.6, 8) for c in centers): if any(abs(yc - c) < max(med_h * 0.6, 8) for c in centers):
continue continue
@@ -204,7 +206,10 @@ def find_number_bands(gray: np.ndarray, limit: int = _MAX_BANDS
half = max(half, h * 0.030) half = max(half, h * 0.030)
y1 = max(0, int(yc - half)) y1 = max(0, int(yc - half))
y2 = min(h, int(yc + half)) y2 = min(h, int(yc + half))
out.append((int(w * 0.03), y1, int(w * 0.97), y2)) # x 跨度用 MSER 行自己的实际范围(原来写死 3%~97%,卡片没占满画面时分组窗口会整体错位)
x1, x2 = int(x1_s * inv), int(x2_s * inv)
pad = max(4, int((x2 - x1) * 0.04))
out.append((max(0, x1 - pad), y1, min(w, x2 + pad), y2))
centers.append(yc) centers.append(yc)
if len(out) >= limit: if len(out) >= limit:
break break
@@ -378,11 +383,47 @@ def _bank_from_text(text: str) -> str:
# ---------------------------------------------------------------- 对外接口 # ---------------------------------------------------------------- 对外接口
def _warp_fallback(bgr: np.ndarray) -> Optional[np.ndarray]:
"""整图找不到卡号带时的兜底:按色块/边缘找卡并摆正,失败返回 None。"""
try:
from .cards import locate_bank_card # noqa: PLC0415 避免循环引用
return locate_bank_card(bgr)
except Exception: # noqa: BLE001 兜底链路不允许把主流程带崩
logger.debug("找卡兜底失败", exc_info=True)
return None
def _text_bands(bgr: np.ndarray) -> List[Tuple[int, int, int, int]]:
"""MSER 找不到卡号带时的兜底:用 OCR 检出的数字行定 y、卡宽定 x。
浮雕卡片的数字是「同色凸起」,MSER 经常整行都检测不到;而 OCR 检测网络对
这类卡面仍能框出部分数字(哪怕只读到 4 位),用它定纵向位置更稳。
"""
try:
from .engine import lines as ocr_lines # noqa: PLC0415 避免循环引用
ls = ocr_lines(bgr)
except Exception: # noqa: BLE001
return []
h, w = bgr.shape[:2]
rows = [ln for ln in ls if sum(1 for ch in ln.text if ch.isdigit()) >= 2]
rows.sort(key=lambda ln: -ln.width)
out: List[Tuple[int, int, int, int]] = []
for ln in rows[:2]:
cy = (ln.top + ln.bottom) / 2.0
half = max(24, int(ln.height * 0.75))
out.append((int(w * _SPAN_RATIOS[0][0]), max(0, int(cy - half)),
int(w * _SPAN_RATIOS[0][1]), min(h, int(cy + half))))
return out
def _band_probe(gray: np.ndarray, band: Tuple[int, int, int, int]) -> int: def _band_probe(gray: np.ndarray, band: Tuple[int, int, int, int]) -> int:
"""便宜地试读一条带子:只跑 morph 一路,数「正好 4 位」的分组个数。""" """便宜地试读一条带子:只跑 morph 一路,数「正好 4 位」的分组个数。"""
_, y1, _, y2 = band xa, y1, xb, y2 = band
h, w = gray.shape[:2] h, w = gray.shape[:2]
xa, xb = int(w * _SPAN_RATIOS[0][0]), int(w * _SPAN_RATIOS[0][1]) if xb - xa < w * 0.6: # 带子比整图窄:按带子自己的跨度切
xa, xb = max(0, xa), min(w, xb)
else:
xa, xb = int(w * _SPAN_RATIOS[0][0]), int(w * _SPAN_RATIOS[0][1])
gw = (xb - xa) / 4.0 gw = (xb - xa) / 4.0
good = 0 good = 0
for i in range(4): for i in range(4):
@@ -415,9 +456,20 @@ def read_bank_card_number(image, face_text: str = "") -> NumberReading:
candidate/failed,不硬猜。 candidate/failed,不硬猜。
""" """
t0 = time.time() t0 = time.time()
gray = to_gray(image) if isinstance(image, np.ndarray) else to_gray(imread(str(image))) src = image if isinstance(image, np.ndarray) else imread(str(image))
if src is None or getattr(src, "size", 0) == 0:
return NumberReading(elapsed_s=time.time() - t0)
gray = to_gray(src)
res = NumberReading() res = NumberReading()
bands = find_number_bands(gray) bands = find_number_bands(gray)
if not bands and getattr(src, "ndim", 0) == 3:
# 整图定位不到卡号带(卡没占满画面、拍歪、反光打断):先自动找卡摆正再试
warped = _warp_fallback(src)
if warped is not None:
gray = to_gray(warped)
bands = find_number_bands(gray) or _text_bands(warped)
if not bands and getattr(src, "ndim", 0) == 3:
bands = _text_bands(src)
if not bands: if not bands:
res.elapsed_s = time.time() - t0 res.elapsed_s = time.time() - t0
return res return res
@@ -431,10 +483,16 @@ def read_bank_card_number(image, face_text: str = "") -> NumberReading:
best: Optional[NumberReading] = None best: Optional[NumberReading] = None
best_key = (-1, -1, -1, -1) best_key = (-1, -1, -1, -1)
for band in ordered[:2]: for band in ordered[:2]:
_, y1, _, y2 = band bx1, y1, bx2, y2 = band
pad = max(4, int((y2 - y1) * 0.06)) pad = max(4, int((y2 - y1) * 0.06))
y1, y2 = max(0, y1 - pad), min(h, y2 + pad) y1, y2 = max(0, y1 - pad), min(h, y2 + pad)
for (ra, rb) in _SPAN_RATIOS: spans = []
if 0 < bx2 - bx1 < w * 0.85:
# 带子明显比整图窄:优先用它自己的实际跨度(卡没占满画面时固定百分比会错位)
pw = max(4, int((bx2 - bx1) * 0.04))
spans.append((max(0, bx1 - pw) / float(w), min(w, bx2 + pw) / float(w)))
spans.extend(_SPAN_RATIOS)
for (ra, rb) in spans:
xa, xb = int(w * ra), int(w * rb) xa, xb = int(w * ra), int(w * rb)
gw = (xb - xa) / 4.0 gw = (xb - xa) / 4.0
groups = [_pick_group(gray, int(round(xa + gw * i)), groups = [_pick_group(gray, int(round(xa + gw * i)),
@@ -20,7 +20,7 @@ import cv2
import numpy as np import numpy as np
from . import bankcard, idcard from . import bankcard, idcard
from .cards import find_cards from .cards import find_cards, locate_bank_card
from .engine import Line, join_text, lines as ocr_lines, row_texts, text_line from .engine import Line, join_text, lines as ocr_lines, row_texts, text_line
from .img import apply_exif, gray_variants, imread, resize_side, rotate90, to_gray from .img import apply_exif, gray_variants, imread, resize_side, rotate90, to_gray
from .validators import (_CONFUSABLE, PRIMARY, card_candidates, id_candidates, from .validators import (_CONFUSABLE, PRIMARY, card_candidates, id_candidates,
@@ -353,9 +353,21 @@ def analyze_image(path: str, expected_name: str = "",
if bank_res.found and bank_res.luhn_ok: if bank_res.found and bank_res.luhn_ok:
break break
# ---- 6) 兜底:整图几乎没识别到文字时,试一次卡片四边形矫正 # ---- 6) 兜底:卡号/身份证没读出来时,试一次卡片矫正
if not fast and len([ln for v in views for ln in v.lines]) < 3: # 注意条件不能只看「几乎没文字」:手机拍卡常能认出「招商银行/银联」几行,
for i, r in enumerate(find_cards(img_work, max_cards=2, warp_width=1712)): # 文字够多但卡号一个都没检出,这时同样需要矫正后再认一遍。
if not fast and (len([ln for v in views for ln in v.lines]) < 3
or (not (bank_res.found and bank_res.luhn_ok)
and bankcard.looks_like_bank_card(
" ".join(v.text for v in views)))):
quads = list(find_cards(img_work, max_cards=2, warp_width=1712))
if not quads:
# Canny 四边形找不到(反光打断卡边)时,退到色块/边缘兜底
flat = locate_bank_card(img_work, warp_width=1712)
if flat is not None:
add_view(View(name="quad1", image=flat, source="quad",
rect=(0, 0, flat.shape[1], flat.shape[0])))
for i, r in enumerate(quads):
if r.warped is not None and r.warped.size: if r.warped is not None and r.warped.size:
add_view(View(name=f"quad{i + 1}", image=r.warped, source="quad", add_view(View(name=f"quad{i + 1}", image=r.warped, source="quad",
rect=cv2.boundingRect(np.asarray(r.pts, dtype=np.int32)))) rect=cv2.boundingRect(np.asarray(r.pts, dtype=np.int32))))
@@ -231,51 +231,62 @@ class CardCandidate:
score: float = 0.0 score: float = 0.0
# 常见储蓄卡 BIN(6 位)→ 银行;只收录能确认的,其余留给卡面文字判断 # 常见储蓄卡 BIN(6 位)→ 银行;只收录能确认的,其余留给卡面文字判断。
# 与插件 XQ0005「银行卡检查」的已核验工资卡 BIN 对齐(重庆农商/三峡等本地卡种),
# 同一 BIN 只能对应一家银行,勿重复登记(Python dict 重复键会静默覆盖)。
BIN_BANK: Dict[str, str] = { BIN_BANK: Dict[str, str] = {
# 工商银行 # 工商银行
"622202": "中国工商银行", "622203": "中国工商银行", "622200": "中国工商银行", "622200": "中国工商银行", "622202": "中国工商银行", "622203": "中国工商银行",
"622208": "中国工商银行", "621226": "中国工商银行", "955880": "中国工商银行", "622208": "中国工商银行", "621225": "中国工商银行", "621226": "中国工商银行",
"955882": "中国工商银行", "621225": "中国工商银行", "955880": "中国工商银行", "955882": "中国工商银行",
# 农业银行 # 农业银行
"622848": "中国农业银行", "622845": "中国农业银行", "622846": "中国农业银行", "621336": "中国农业银行", "622841": "中国农业银行", "622845": "中国农业银行",
"622849": "中国农业银行", "621336": "中国农业银行", "622841": "中国农业银行", "622846": "中国农业银行", "622848": "中国农业银行", "622849": "中国农业银行",
# 建设银行 # 建设银行
"621700": "中国建设银行", "622700": "中国建设银行", "436742": "中国建设银行", "621081": "中国建设银行", "621499": "中国建设银行", "621700": "中国建设银行",
"622280": "中国建设银行", "621081": "中国建设银行", "622280": "中国建设银行", "622700": "中国建设银行", "436742": "中国建设银行",
# 中国银行 # 中国银行
"621661": "中国银行", "621660": "中国银行", "621662": "中国银行", "456351": "中国银行", "601382": "中国银行", "621660": "中国银行",
"621663": "中国银行", "621665": "中国银行", "601382": "中国银行", "621661": "中国银行", "621662": "中国银行", "621663": "中国银行",
"456351": "中国银行", "621785": "中国银行", "621786": "中国银行", "621665": "中国银行", "621785": "中国银行", "621786": "中国银行",
"621787": "中国银行", "621788": "中国银行", "621789": "中国银行", "621787": "中国银行", "621788": "中国银行", "621789": "中国银行",
# 招商银行 # 招商银行
"621483": "招商银行", "622588": "招商银行", "621286": "招商银行", "621286": "招商银行", "621483": "招商银行", "621485": "招商银行",
"622575": "招商银行", "622576": "招商银行", "622577": "招商银行", "621486": "招商银行", "622575": "招商银行", "622576": "招商银行",
"622578": "招商银行", "622579": "招商银行", "622577": "招商银行", "622578": "招商银行", "622579": "招商银行",
"622588": "招商银行", "622609": "招商银行",
# 民生银行 # 民生银行
"622622": "中国民生银行", "622600": "中国民生银行", "622601": "中国民生银行", "421393": "中国民生银行", "621691": "中国民生银行", "622600": "中国民生银行",
"622602": "中国民生银行", "622603": "中国民生银行", "622615": "中国民生银行", "622601": "中国民生银行", "622602": "中国民生银行", "622603": "中国民生银行",
"622617": "中国民生银行", "622619": "中国民生银行", "622621": "中国民生银行", "622615": "中国民生银行", "622617": "中国民生银行", "622619": "中国民生银行",
"622623": "中国民生银行", "421393": "中国民生银行", "622620": "中国民生银行", "622621": "中国民生银行", "622622": "中国民生银行",
"622623": "中国民生银行",
# 兴业银行 # 兴业银行
"622908": "兴业银行", "622909": "兴业银行", "621084": "兴业银行", "621084": "兴业银行", "622908": "兴业银行", "622909": "兴业银行",
# 浦发银行 # 浦发银行
"622521": "浦发银行", "622522": "浦发银行", "622523": "浦发银行", "621792": "浦发银行", "621793": "浦发银行", "622516": "浦发银行",
"622516": "浦发银行", "622517": "浦发银行", "622518": "浦发银行", "622517": "浦发银行", "622518": "浦发银行", "622521": "浦发银行",
"622525": "浦发银行", "622526": "浦发银行", "622522": "浦发银行", "622523": "浦发银行", "622525": "浦发银行",
"622526": "浦发银行",
# 交通银行 # 交通银行
"622260": "交通银行", "622262": "交通银行", "622250": "交通银行", "622250": "交通银行", "622251": "交通银行", "622252": "交通银行",
"622251": "交通银行", "622252": "交通银行", "622253": "交通银行", "622253": "交通银行", "622254": "交通银行", "622255": "交通银行",
"622254": "交通银行", "622255": "交通银行", "622260": "交通银行", "622262": "交通银行",
# 邮储银行 # 邮储银行
"620062": "中国邮政储蓄银行", "621095": "中国邮政储蓄银行",
"622188": "中国邮政储蓄银行", "622199": "中国邮政储蓄银行", "622188": "中国邮政储蓄银行", "622199": "中国邮政储蓄银行",
"621095": "中国邮政储蓄银行", "620062": "中国邮政储蓄银行", "955100": "中国邮政储蓄银行", "955100": "中国邮政储蓄银行",
# 中信 / 光大 / 华夏 / 广发 / 平安 # 中信 / 光大 / 华夏 / 广发 / 平安
"622690": "中信银行", "622691": "中信银行", "622692": "中信银行", "622690": "中信银行", "622691": "中信银行", "622692": "中信银行",
"622660": "中国光大银行", "622661": "中国光大银行", "622662": "中国光大银行", "622660": "中国光大银行", "622661": "中国光大银行", "622662": "中国光大银行",
"622630": "华夏银行", "622631": "华夏银行", "622632": "华夏银行", "622630": "华夏银行", "622631": "华夏银行", "622632": "华夏银行",
"622568": "广发银行", "622576": "广发银行", "623020": "华夏银行",
"622568": "广发银行",
"622155": "平安银行", "622156": "平安银行", "622157": "平安银行", "622155": "平安银行", "622156": "平安银行", "622157": "平安银行",
# 重庆本地(工资卡主力卡种,XQ0005 实际数据核验)
"621258": "重庆农村商业银行", "621465": "重庆农村商业银行",
"621528": "重庆农村商业银行", "622867": "重庆农村商业银行",
"621755": "重庆三峡银行",
} }
+14 -2
View File
@@ -72,6 +72,18 @@ class TextItem:
# ==================== 引擎 ==================== # ==================== 引擎 ====================
def _silence_rapidocr() -> None:
"""把 RapidOCR 自带的控制台日志压到 ERROR。
RapidOCR 在 import 时给 "RapidOCR" logger 挂了 stderr handler,识别不到文字等
WARNING 会直接写 stderr,被执行机当成 ERROR 刷进运行日志(`[ERROR] [WARNING] ...`)。
这里只压掉 WARNING 及以下的噪音,ERROR 仍然保留。
"""
lg = logging.getLogger("RapidOCR")
lg.setLevel(logging.ERROR)
lg.propagate = False
def _get_engine(): def _get_engine():
"""懒加载 RapidOCR 单例(模型随包,离线可用)。""" """懒加载 RapidOCR 单例(模型随包,离线可用)。"""
global _ENGINE global _ENGINE
@@ -88,10 +100,10 @@ def _get_engine():
"(模型随包内置,无需联网下载;识别失败时可删除 rapidocr/models 重新解压)" "(模型随包内置,无需联网下载;识别失败时可删除 rapidocr/models 重新解压)"
) from e ) from e
try: try:
_ENGINE = RapidOCR(params={"Global.log_level": "WARNING"}) _ENGINE = RapidOCR(params={"Global.log_level": "ERROR"})
except Exception: # noqa: BLE001 老版本不支持 params except Exception: # noqa: BLE001 老版本不支持 params
_ENGINE = RapidOCR() _ENGINE = RapidOCR()
logging.getLogger("RapidOCR").setLevel(logging.WARNING) _silence_rapidocr()
logger.debug("RapidOCR 引擎已初始化") logger.debug("RapidOCR 引擎已初始化")
return _ENGINE return _ENGINE
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "desktopauto" name = "desktopauto"
version = "0.5.0" version = "0.5.3"
description = "桌面自动化库:识图点击、图像存在判断、OCR 文字坐标、身份证/银行卡照片识别、键鼠输入、窗口与进程管理" description = "桌面自动化库:识图点击、图像存在判断、OCR 文字坐标、身份证/银行卡照片识别、键鼠输入、窗口与进程管理"
readme = "README.md" readme = "README.md"
requires-python = ">=3.9" requires-python = ">=3.9"
+1 -1
View File
@@ -2,7 +2,7 @@
"schema_version": 1, "schema_version": 1,
"id": "desktopauto", "id": "desktopauto",
"name": "桌面自动化 SDK", "name": "桌面自动化 SDK",
"version": "0.5.0", "version": "0.5.3",
"description": "屏幕识图点击、图像存在判断、OCR 文字坐标、身份证/银行卡照片识别(号码纠错/命中分析)、键鼠输入、窗口与进程管理(面向拿不到元素树的桌面程序)", "description": "屏幕识图点击、图像存在判断、OCR 文字坐标、身份证/银行卡照片识别(号码纠错/命中分析)、键鼠输入、窗口与进程管理(面向拿不到元素树的桌面程序)",
"provides": [ "provides": [
"desktopauto" "desktopauto"
+30 -1
View File
@@ -22,6 +22,7 @@
| 群聊推送(文本/文件、标题、@所有人、@成员) | `dws.Dws`、`dws.push` | 同上 | | 群聊推送(文本/文件、标题、@所有人、@成员) | `dws.Dws`、`dws.push` | 同上 |
| 防封控限流 + 推送记录 CSV | `Dws(rate_limit=...)`、`Dws(record_dir=...)` | 同上 | | 防封控限流 + 推送记录 CSV | `Dws(rate_limit=...)`、`Dws(record_dir=...)` | 同上 |
| AI 表格读写(sheet/字段/分页读/批量增改、值归一与类型转换) | `aitable.AiTable` | `libs/aitable/aitable/client.py` | | AI 表格读写(sheet/字段/分页读/批量增改、值归一与类型转换) | `aitable.AiTable` | `libs/aitable/aitable/client.py` |
| AI 表格附件下载(图片/文件字段、预签名过期检测、重试/命名/魔数校验) | `aitable.AiTable.download_attachments`、`aitable.attachment_items` | 新增(`libs/aitable` 1.1.0 同步实现) |
| 月报/周报数据采集(Git + 需求表) | `report.collect`、`python -m dingtalk_sdk.report` | `libs/aitable/aitable/report.py` | | 月报/周报数据采集(Git + 需求表) | `report.collect`、`python -m dingtalk_sdk.report` | `libs/aitable/aitable/report.py` |
不在范围内:`workflows/share/dingtalk_sender.py`(已废弃的 OCR + 模拟点击单聊推送, 不在范围内:`workflows/share/dingtalk_sender.py`(已废弃的 OCR + 模拟点击单聊推送,
@@ -96,6 +97,32 @@ with AiTable() as table: # 操作人取配置 AITABLE_OPERATOR_UN
`base` 参数支持别名(`workplan` / `hr`)、baseId、alidocs 链接三种写法,方法内部自动转换 `base` 参数支持别名(`workplan` / `hr`)、baseId、alidocs 链接三种写法,方法内部自动转换
(旧 `libs/aitable` 需要先调 `resolve_base`,SDK 里可省略)。 (旧 `libs/aitable` 需要先调 `resolve_base`,SDK 里可省略)。
附件(图片/文件)字段的下载:
```python
from dingtalk_sdk import AiTable, attachment_items
with AiTable() as table:
rows = table.records("hr", "uavChPe") # 银行卡-变更收集表
for record in rows:
fields = record.get("fields") or {}
photos = attachment_items(fields.get("银行卡卡号面照片")) # 元数据(含预签名 url)
for res in table.download_attachments(fields.get("银行卡卡号面照片"),
rf"D:\资料\银行卡照片\{fields.get('持卡人姓名', '')}",
prefix="银行卡-"):
print(res["ok"], res["path"], res["kind"], res["size_match"])
```
要点:
- `attachment` 字段的 `url` 是阿里云 OSS **预签名地址**(免 token 直连,约 **2 小时过期**):
拉完记录要立刻下载,过期只能重拉记录换新地址(抛 `AttachmentExpiredError`,重试同一地址无用);
- `download_attachment()` 单文件失败抛异常;`download_attachments()` 批量时单文件失败**不中断**,
结果里 `ok=False` + `error` + `expired`;
- 落盘文件名为 `prefix + 原文件名`,同名自动加 `-2`,非法字符换 `_`,限长 120;
- `kind` 按文件头魔数判断真实类型、`size_match` 与表格声明大小比对,防止把错误页/半截文件当图片;
- `resourceUrl` 是相对路径,不能直连(`attachment_items` 会丢掉它)。
### 5. 月报 / 周报 ### 5. 月报 / 周报
```python ```python
@@ -135,6 +162,7 @@ dws 可执行文件解析顺序:`Dws(bin=...)` > `DINGTALK_DWS_BIN` > `~/.loca
| 项 | 旧实现 | SDK | | 项 | 旧实现 | SDK |
|---|---|---| |---|---|---|
| 错误 | `SystemExit` / 返回 dict 混用 | 统一异常(`ConfigError`/`ApiError`/`NetworkError`/`DwsError`);兼容入口 `robot.push` / `dws.push` 仍返回 dict | | 错误 | `SystemExit` / 返回 dict 混用 | 统一异常(`ConfigError`/`ApiError`/`NetworkError`/`DwsError`);兼容入口 `robot.push` / `dws.push` 仍返回 dict |
| 附件下载 | 无(只有 `attachment` 元数据) | `download_attachment(s)`;预签名过期抛 `AttachmentExpiredError`,批量失败项不中断 |
| 输出 | 直接 `print` | 通过 `log=` 回调(默认静默),不污染插件日志 | | 输出 | 直接 `print` | 通过 `log=` 回调(默认静默),不污染插件日志 |
| 环境定位 | 按 `__file__` 推仓库根 | 按 cwd 向上 + 环境变量 | | 环境定位 | 按 `__file__` 推仓库根 | 按 cwd 向上 + 环境变量 |
| 影刀全局变量 | 写 `glv['push_record_path']` | 仍 best-effort 写;同时 `push()` 返回 `record_path` | | 影刀全局变量 | 写 `glv['push_record_path']` | 仍 best-effort 写;同时 `push()` 返回 `record_path` |
@@ -173,7 +201,7 @@ cd libs\dingtalk; ..\..\.venv\Scripts\python.exe -m dingtalk_sdk._selftest; cd .
# 直发正式(SDK 无独立入口、无法单测,不走测试通道;要小范围看就发消费插件的测试版) # 直发正式(SDK 无独立入口、无法单测,不走测试通道;要小范围看就发消费插件的测试版)
.venv\Scripts\python.exe tools\agent_cli.py --admin puddy --password 123456 ` .venv\Scripts\python.exe tools\agent_cli.py --admin puddy --password 123456 `
--base http://172.30.30.243:8800 ` --base http://172.30.30.243:8800 `
sdk-publish dist-sdk\dingtalk_sdk_v0.1.2.zip --baseline-sdk <上一版 zip> --prod sdk-publish dist-sdk\dingtalk_sdk_v0.1.3.zip --baseline-sdk <上一版 zip> --prod
``` ```
完整发版 SOP 见技能 `.skills/37du-SDK-Deploy/SKILL.md`;`^0.x` 是标准 caret 语义, 完整发版 SOP 见技能 `.skills/37du-SDK-Deploy/SKILL.md`;`^0.x` 是标准 caret 语义,
@@ -190,3 +218,4 @@ cd libs\dingtalk; ..\..\.venv\Scripts\python.exe -m dingtalk_sdk._selftest; cd .
5. **AI 表格必须带 `operatorId`**:操作人须是目标表协作者,个人空间文档默认不对应用开放。 5. **AI 表格必须带 `operatorId`**:操作人须是目标表协作者,个人空间文档默认不对应用开放。
6. **日期是毫秒时间戳 + 北京时间**:`norm` / `to_ms` 已处理,自己拼时间戳容易整体差一天。 6. **日期是毫秒时间戳 + 北京时间**:`norm` / `to_ms` 已处理,自己拼时间戳容易整体差一天。
7. **dws 限流**:默认 50 条/分钟,批量推送会阻塞等待(不丢消息),长批次请预留时间。 7. **dws 限流**:默认 50 条/分钟,批量推送会阻塞等待(不丢消息),长批次请预留时间。
8. **表格附件 url 约 2 小时过期**:`attachment` 字段里的 `url` 是预签名地址,必须“拉记录 → 立刻下载”,不能存 url 隔夜用;翻页拉 5000 条再回头下载前面的是常见翻车点。
+43 -4
View File
@@ -1,13 +1,14 @@
{ {
"schema_version": 1, "schema_version": 1,
"sdk_id": "dingtalk_sdk", "sdk_id": "dingtalk_sdk",
"version": "0.1.2", "version": "0.1.3",
"modules": { "modules": {
"dingtalk_sdk": { "dingtalk_sdk": {
"exports": [ "exports": [
"AccessToken", "AccessToken",
"AiTable", "AiTable",
"ApiError", "ApiError",
"AttachmentExpiredError",
"AuthError", "AuthError",
"CancelledError", "CancelledError",
"ConfigError", "ConfigError",
@@ -20,6 +21,7 @@
"RobotAccount", "RobotAccount",
"Settings", "Settings",
"aitable", "aitable",
"attachment_items",
"auth", "auth",
"build_sign", "build_sign",
"build_url", "build_url",
@@ -38,12 +40,15 @@
"media", "media",
"ms_to_str", "ms_to_str",
"norm", "norm",
"parse_expires",
"parse_period", "parse_period",
"push_dws", "push_dws",
"push_robot", "push_robot",
"report", "report",
"resolve_base", "resolve_base",
"robot", "robot",
"safe_filename",
"sniff_kind",
"split_by_chars", "split_by_chars",
"to_base_id", "to_base_id",
"to_ms", "to_ms",
@@ -55,6 +60,7 @@
"AccessToken", "AccessToken",
"AiTable", "AiTable",
"ApiError", "ApiError",
"AttachmentExpiredError",
"AuthError", "AuthError",
"CancelledError", "CancelledError",
"ConfigError", "ConfigError",
@@ -67,6 +73,7 @@
"RobotAccount", "RobotAccount",
"Settings", "Settings",
"aitable", "aitable",
"attachment_items",
"auth", "auth",
"build_sign", "build_sign",
"build_url", "build_url",
@@ -85,12 +92,15 @@
"media", "media",
"ms_to_str", "ms_to_str",
"norm", "norm",
"parse_expires",
"parse_period", "parse_period",
"push_dws", "push_dws",
"push_robot", "push_robot",
"report", "report",
"resolve_base", "resolve_base",
"robot", "robot",
"safe_filename",
"sniff_kind",
"split_by_chars", "split_by_chars",
"to_base_id", "to_base_id",
"to_ms", "to_ms",
@@ -108,6 +118,7 @@
"Robot": "(webhook: 'str' = '', secret: 'str' = '', server_name: 'str' = '', env: 'str' = 'prod', timeout: 'Optional[float]' = None, retries: 'Optional[int]' = None, log: 'Optional[Callable[[str], None]]' = None) -> 'None'", "Robot": "(webhook: 'str' = '', secret: 'str' = '', server_name: 'str' = '', env: 'str' = 'prod', timeout: 'Optional[float]' = None, retries: 'Optional[int]' = None, log: 'Optional[Callable[[str], None]]' = None) -> 'None'",
"RobotAccount": "(webhook: 'str' = '', secret: 'str' = '', server_name: 'str' = '37du 任务调度平台') -> None", "RobotAccount": "(webhook: 'str' = '', secret: 'str' = '', server_name: 'str' = '37du 任务调度平台') -> None",
"Settings": "(app_key: 'str' = '', app_secret: 'str' = '', operator: 'str' = '', dws_bin: 'str' = '', timeout: 'float' = 30.0, retries: 'int' = 3, rate_limit: 'int' = 50, rate_window: 'float' = 60.0, default_env: 'str' = 'prod', robots: 'Dict[str, RobotAccount]' = <factory>, base_aliases: 'Dict[str, str]' = <factory>) -> None", "Settings": "(app_key: 'str' = '', app_secret: 'str' = '', operator: 'str' = '', dws_bin: 'str' = '', timeout: 'float' = 30.0, retries: 'int' = 3, rate_limit: 'int' = 50, rate_window: 'float' = 60.0, default_env: 'str' = 'prod', robots: 'Dict[str, RobotAccount]' = <factory>, base_aliases: 'Dict[str, str]' = <factory>) -> None",
"attachment_items": "(value: 'Any') -> 'List[Dict[str, Any]]'",
"build_sign": "(secret: 'str', timestamp_ms: 'Union[int, str]') -> 'str'", "build_sign": "(secret: 'str', timestamp_ms: 'Union[int, str]') -> 'str'",
"build_url": "(webhook: 'str', secret: 'str' = '') -> 'str'", "build_url": "(webhook: 'str', secret: 'str' = '') -> 'str'",
"coerce_for_fields": "(meta: 'dict', data: 'dict') -> 'dict'", "coerce_for_fields": "(meta: 'dict', data: 'dict') -> 'dict'",
@@ -120,10 +131,13 @@
"markdown_image": "(media_id: 'str', alt: 'str' = '图片') -> 'str'", "markdown_image": "(media_id: 'str', alt: 'str' = '图片') -> 'str'",
"ms_to_str": "(ms: 'Any', with_time: 'bool' = False) -> 'str'", "ms_to_str": "(ms: 'Any', with_time: 'bool' = False) -> 'str'",
"norm": "(value: 'Any') -> 'Any'", "norm": "(value: 'Any') -> 'Any'",
"parse_expires": "(url: 'str') -> 'int'",
"parse_period": "(month: 'str' = '', week: 'Optional[str]' = None) -> 'dict'", "parse_period": "(month: 'str' = '', week: 'Optional[str]' = None) -> 'dict'",
"push_dws": "(messages: 'Iterable', record_dir: 'str' = '', chat_type: 'str' = '') -> 'dict'", "push_dws": "(messages: 'Iterable', record_dir: 'str' = '', chat_type: 'str' = '') -> 'dict'",
"push_robot": "(text, title: 'str' = '消息通知', status: 'str' = 'info', webhook: 'str' = '', secret: 'str' = '', server_name: 'str' = '', env: 'str' = 'prod', batch: 'bool' = False, max_chars: 'int' = 15000, log: 'Optional[Callable[[str], None]]' = None) -> 'dict'", "push_robot": "(text, title: 'str' = '消息通知', status: 'str' = 'info', webhook: 'str' = '', secret: 'str' = '', server_name: 'str' = '', env: 'str' = 'prod', batch: 'bool' = False, max_chars: 'int' = 15000, log: 'Optional[Callable[[str], None]]' = None) -> 'dict'",
"resolve_base": "(raw: 'str', aliases: 'Optional[Dict[str, str]]' = None) -> 'Tuple[str, str]'", "resolve_base": "(raw: 'str', aliases: 'Optional[Dict[str, str]]' = None) -> 'Tuple[str, str]'",
"safe_filename": "(name: 'Any', fallback: 'str' = 'file') -> 'str'",
"sniff_kind": "(path: 'Any') -> 'str'",
"split_by_chars": "(content: 'str', max_chars: 'int' = 15000) -> 'List[str]'", "split_by_chars": "(content: 'str', max_chars: 'int' = 15000) -> 'List[str]'",
"to_base_id": "(base: 'str', aliases: 'Optional[Dict[str, str]]' = None) -> 'str'", "to_base_id": "(base: 'str', aliases: 'Optional[Dict[str, str]]' = None) -> 'str'",
"to_ms": "(value: 'Any') -> 'Optional[int]'", "to_ms": "(value: 'Any') -> 'Optional[int]'",
@@ -148,6 +162,7 @@
"report", "report",
"robot", "robot",
"test_aitable", "test_aitable",
"test_aitable_attachment",
"test_config", "test_config",
"test_dws", "test_dws",
"test_http", "test_http",
@@ -160,6 +175,7 @@
"signatures": { "signatures": {
"main": "() -> 'int'", "main": "() -> 'int'",
"test_aitable": "() -> 'None'", "test_aitable": "() -> 'None'",
"test_aitable_attachment": "() -> 'None'",
"test_config": "() -> 'None'", "test_config": "() -> 'None'",
"test_dws": "() -> 'None'", "test_dws": "() -> 'None'",
"test_http": "() -> 'None'", "test_http": "() -> 'None'",
@@ -170,45 +186,66 @@
}, },
"dingtalk_sdk.aitable": { "dingtalk_sdk.aitable": {
"exports": [ "exports": [
"ATTACH_MIN_REMAIN",
"ATTACH_TIMEOUT",
"MAX_PAGES", "MAX_PAGES",
"PAGE_SIZE", "PAGE_SIZE",
"TZ_CN", "TZ_CN",
"WRITE_BATCH", "WRITE_BATCH",
"AiTable", "AiTable",
"ApiError", "ApiError",
"AttachmentExpiredError",
"attachment_items",
"coerce_for_fields", "coerce_for_fields",
"flatten", "flatten",
"ms_to_str", "ms_to_str",
"norm", "norm",
"parse_expires",
"resolve_base", "resolve_base",
"safe_filename",
"sniff_kind",
"to_base_id", "to_base_id",
"to_ms" "to_ms",
"unique_path"
], ],
"all": [ "all": [
"ATTACH_MIN_REMAIN",
"ATTACH_TIMEOUT",
"MAX_PAGES", "MAX_PAGES",
"PAGE_SIZE", "PAGE_SIZE",
"TZ_CN", "TZ_CN",
"WRITE_BATCH", "WRITE_BATCH",
"AiTable", "AiTable",
"ApiError", "ApiError",
"AttachmentExpiredError",
"attachment_items",
"coerce_for_fields", "coerce_for_fields",
"flatten", "flatten",
"ms_to_str", "ms_to_str",
"norm", "norm",
"parse_expires",
"resolve_base", "resolve_base",
"safe_filename",
"sniff_kind",
"to_base_id", "to_base_id",
"to_ms" "to_ms",
"unique_path"
], ],
"signatures": { "signatures": {
"AiTable": "(operator: 'str' = '', app_key: 'str' = '', app_secret: 'str' = '', timeout: 'Optional[float]' = None, retries: 'Optional[int]' = None, log: 'Optional[Callable[[str], None]]' = None) -> 'None'", "AiTable": "(operator: 'str' = '', app_key: 'str' = '', app_secret: 'str' = '', timeout: 'Optional[float]' = None, retries: 'Optional[int]' = None, log: 'Optional[Callable[[str], None]]' = None) -> 'None'",
"ApiError": "(message: 'str', code: 'str' = '', errmsg: 'str' = '', payload=None)", "ApiError": "(message: 'str', code: 'str' = '', errmsg: 'str' = '', payload=None)",
"attachment_items": "(value: 'Any') -> 'List[Dict[str, Any]]'",
"coerce_for_fields": "(meta: 'dict', data: 'dict') -> 'dict'", "coerce_for_fields": "(meta: 'dict', data: 'dict') -> 'dict'",
"flatten": "(record: 'dict') -> 'dict'", "flatten": "(record: 'dict') -> 'dict'",
"ms_to_str": "(ms: 'Any', with_time: 'bool' = False) -> 'str'", "ms_to_str": "(ms: 'Any', with_time: 'bool' = False) -> 'str'",
"norm": "(value: 'Any') -> 'Any'", "norm": "(value: 'Any') -> 'Any'",
"parse_expires": "(url: 'str') -> 'int'",
"resolve_base": "(raw: 'str', aliases: 'Optional[Dict[str, str]]' = None) -> 'Tuple[str, str]'", "resolve_base": "(raw: 'str', aliases: 'Optional[Dict[str, str]]' = None) -> 'Tuple[str, str]'",
"safe_filename": "(name: 'Any', fallback: 'str' = 'file') -> 'str'",
"sniff_kind": "(path: 'Any') -> 'str'",
"to_base_id": "(base: 'str', aliases: 'Optional[Dict[str, str]]' = None) -> 'str'", "to_base_id": "(base: 'str', aliases: 'Optional[Dict[str, str]]' = None) -> 'str'",
"to_ms": "(value: 'Any') -> 'Optional[int]'" "to_ms": "(value: 'Any') -> 'Optional[int]'",
"unique_path": "(dest: 'Path') -> 'Path'"
} }
}, },
"dingtalk_sdk.auth": { "dingtalk_sdk.auth": {
@@ -336,6 +373,7 @@
"dingtalk_sdk.errors": { "dingtalk_sdk.errors": {
"exports": [ "exports": [
"ApiError", "ApiError",
"AttachmentExpiredError",
"AuthError", "AuthError",
"CancelledError", "CancelledError",
"ConfigError", "ConfigError",
@@ -345,6 +383,7 @@
], ],
"all": [ "all": [
"ApiError", "ApiError",
"AttachmentExpiredError",
"AuthError", "AuthError",
"CancelledError", "CancelledError",
"ConfigError", "ConfigError",
+10 -4
View File
@@ -33,16 +33,17 @@ AI 表格(notable)读写 :class:`aitable.AiTable` 与值归一工具
from __future__ import annotations from __future__ import annotations
__version__ = "0.1.2" __version__ = "0.1.3"
from . import aitable, auth, config, dws, errors, http, media, robot from . import aitable, auth, config, dws, errors, http, media, robot
from .aitable import (AiTable, coerce_for_fields, flatten, ms_to_str, norm, resolve_base, from .aitable import (AiTable, attachment_items, coerce_for_fields, flatten, ms_to_str,
norm, parse_expires, resolve_base, safe_filename, sniff_kind,
to_base_id, to_ms) to_base_id, to_ms)
from .auth import AccessToken, invalidate as invalidate_token, token from .auth import AccessToken, invalidate as invalidate_token, token
from .config import RobotAccount, Settings, get_settings, load_env_files from .config import RobotAccount, Settings, get_settings, load_env_files
from .dws import Dws, push as push_dws from .dws import Dws, push as push_dws
from .errors import (ApiError, AuthError, CancelledError, ConfigError, DingTalkError, from .errors import (ApiError, AttachmentExpiredError, AuthError, CancelledError,
DwsError, NetworkError) ConfigError, DingTalkError, DwsError, NetworkError)
from .media import markdown_image, upload_media from .media import markdown_image, upload_media
from .robot import (DingTalkRobot, Robot, build_sign, build_url, compose_batch_messages, from .robot import (DingTalkRobot, Robot, build_sign, build_url, compose_batch_messages,
push as push_robot, split_by_chars) push as push_robot, split_by_chars)
@@ -64,6 +65,7 @@ __all__ = [
"AccessToken", "AccessToken",
"AiTable", "AiTable",
"ApiError", "ApiError",
"AttachmentExpiredError",
"AuthError", "AuthError",
"CancelledError", "CancelledError",
"ConfigError", "ConfigError",
@@ -76,6 +78,7 @@ __all__ = [
"RobotAccount", "RobotAccount",
"Settings", "Settings",
"aitable", "aitable",
"attachment_items",
"auth", "auth",
"build_sign", "build_sign",
"build_url", "build_url",
@@ -94,12 +97,15 @@ __all__ = [
"media", "media",
"ms_to_str", "ms_to_str",
"norm", "norm",
"parse_expires",
"parse_period", "parse_period",
"push_dws", "push_dws",
"push_robot", "push_robot",
"report", "report",
"resolve_base", "resolve_base",
"robot", "robot",
"safe_filename",
"sniff_kind",
"split_by_chars", "split_by_chars",
"to_base_id", "to_base_id",
"to_ms", "to_ms",
+92
View File
@@ -225,6 +225,97 @@ def test_aitable() -> None:
"baseId 幂等") "baseId 幂等")
# ==================== AI 表格:附件下载 ====================
def test_aitable_attachment() -> None:
import socketserver
import http.server as httpserver
import tempfile
import threading
value = [{"resourceId": "r1", "filename": "卡号面.jpg", "size": 12, "type": "image",
"url": "https://x.oss-cn/y.jpg?Expires=1794886717&Signature=abc"},
{"resourceId": "r2", "filename": "身份证.png", "size": 8, "type": "image",
"resourceUrl": "/core/api/resources/img/zz"}]
items = aitable.attachment_items(value)
_eq(len(items), 2, "attachment 字段值拆出 2 个附件")
_eq(items[0]["size"], 12, "声明大小保留")
_eq(items[1]["url"], "", "相对 resourceUrl 不当作可直连地址")
_eq(aitable.attachment_items(None), [], "空附件返回空列表")
_eq(aitable.attachment_items({"filename": "x"})[0]["url"], "", "单个 dict 兼容")
_eq(aitable.parse_expires(items[0]["url"]), 1794886717, "解析预签名 Expires")
_eq(aitable.parse_expires("https://x/y.jpg"), 0, "无 Expires 返回 0")
_eq(aitable.safe_filename('a/b:c*?"<>|.jpg'), "a_b_c_.jpg", "非法字符换下划线")
_eq(aitable.safe_filename("", ""), "file", "空名兜底")
_eq(len(aitable.safe_filename("x" * 200)), 120, "文件名限长 120")
# 本地 HTTP 服务模拟 OSS;不联网、不读生产凭证
png = b"\x89PNG\r\n\x1a\n" + b"\0" * 24
class _Handler(httpserver.BaseHTTPRequestHandler):
def do_GET(self):
if self.path.startswith("/ok"):
self.send_response(200)
self.send_header("content-type", "image/png")
self.send_header("content-length", str(len(png)))
self.end_headers()
self.wfile.write(png)
else:
self.send_response(403)
self.end_headers()
def log_message(self, *args):
pass
table = object.__new__(aitable.AiTable) # 只测下载,不初始化鉴权
table._http = http.HttpClient(retries=2, timeout=5, log=lambda m: None)
with socketserver.TCPServer(("127.0.0.1", 0), _Handler) as srv:
threading.Thread(target=srv.serve_forever, daemon=True).start()
base = f"http://127.0.0.1:{srv.server_address[1]}"
try:
with tempfile.TemporaryDirectory() as tmp:
res = table.download_attachment({"url": f"{base}/ok.png", "size": len(png)},
os.path.join(tmp, "a.png"))
_ok(res["ok"] and res["kind"] == "png" and res["size_match"] is True,
"下载成功 + 魔数/声明大小校验")
dup = table.download_attachment({"url": f"{base}/ok.png"},
os.path.join(tmp, "a.png"))
_eq(os.path.basename(dup["path"]), "a-2.png", "同名附件不覆盖")
_raises(aitable.AttachmentExpiredError,
lambda: table.download_attachment({"url": f"{base}/deny.png"},
os.path.join(tmp, "b.png")),
"403 抛 AttachmentExpiredError")
_raises(aitable.AttachmentExpiredError,
lambda: table.download_attachment(
{"url": f"{base}/ok.png?Expires=1000"},
os.path.join(tmp, "c.png")),
"Expires 已过期 → 不发请求直接报过期")
_raises(config.ConfigError,
lambda: table.download_attachment({"resourceUrl": "/x"},
os.path.join(tmp, "d.png")),
"无可直连 url 抛 ConfigError")
# 批量:单文件失败不中断,过期项打 expired,prefix 命名生效
batch = table.download_attachments(
[{"url": f"{base}/ok.png", "filename": "卡号面.jpg", "size": len(png)},
{"url": f"{base}/deny.png", "filename": "身份证.png"}],
os.path.join(tmp, "sub"), prefix="银行卡-", col="银行卡卡号面照片")
_eq(len(batch), 2, "批量下载 2 个附件")
_ok(batch[0]["ok"] and os.path.basename(batch[0]["path"]) == "银行卡-卡号面.jpg",
"批量成功项落盘且带 prefix")
_ok(batch[1]["ok"] is False and batch[1]["expired"] is True
and "403" in batch[1]["error"], "批量失败项标 expired 并带原因")
_eq(batch[1]["col"], "银行卡卡号面照片", "结果带字段名")
_eq(batch[0]["index"], 1, "结果带序号")
finally:
srv.shutdown()
srv.server_close()
# ==================== 媒体 ==================== # ==================== 媒体 ====================
def test_media() -> None: def test_media() -> None:
@@ -264,6 +355,7 @@ def main() -> int:
("http", test_http), ("http", test_http),
("dws", test_dws), ("dws", test_dws),
("aitable", test_aitable), ("aitable", test_aitable),
("aitable_attachment", test_aitable_attachment),
("media", test_media), ("media", test_media),
("report", test_report), ("report", test_report),
] ]
+193 -2
View File
@@ -1,15 +1,19 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""钉钉 AI 表格(notable)读写。 """钉钉 AI 表格(notable)读写。
能力(与原 ``libs/aitable`` 一致): 能力(在原 ``libs/aitable`` 一致基础上补齐附件下载):
- 列 sheet / 字段定义;按 ``hasMore`` + ``nextToken`` 分页读全量记录; - 列 sheet / 字段定义;按 ``hasMore`` + ``nextToken`` 分页读全量记录;
- 批量新增 / 更新记录(自动按 20 条一批); - 批量新增 / 更新记录(自动按 20 条一批);
- 值归一(``norm``)、日期毫秒互转(``ms_to_str`` / ``to_ms``)、 - 值归一(``norm``)、日期毫秒互转(``ms_to_str`` / ``to_ms``)、
按字段类型转换写入值(``coerce_for_fields``)、记录拍平(``flatten``); 按字段类型转换写入值(``coerce_for_fields``)、记录拍平(``flatten``);
- 附件(图片/文件)字段解析与下载:``attachment_items`` + ``AiTable.download_attachments``
(``attachment`` 字段里带阿里云 OSS 预签名 url,免 token 直连、约 2 小时过期);
- base 支持别名 / baseId / alidocs 链接三种写法(``resolve_base``)。 - base 支持别名 / baseId / alidocs 链接三种写法(``resolve_base``)。
与旧实现的差异(SDK 契约要求): 与旧实现的差异(SDK 契约要求):
- 失败抛 ``ConfigError`` / ``ApiError`` / ``NetworkError``,**不再 SystemExit**; - 失败抛 ``ConfigError`` / ``ApiError`` / ``NetworkError``,**不再 SystemExit**;
- 预签名附件地址过期抛 ``AttachmentExpiredError``(``ConfigError`` 子类),
批量下载时单文件失败不中断,结果里 ``ok=False`` 并带原因;
- 凭证与操作人可显式传入,缺省读配置(见 :mod:`dingtalk_sdk.config`)。 - 凭证与操作人可显式传入,缺省读配置(见 :mod:`dingtalk_sdk.config`)。
""" """
@@ -17,12 +21,17 @@ from __future__ import annotations
import json import json
import re import re
import time
import urllib.parse as urllib_parse
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple from typing import Any, Callable, Dict, List, Optional, Tuple
import requests
from .auth import KIND_V1, AccessToken from .auth import KIND_V1, AccessToken
from .config import BASE_ALIASES, get_settings from .config import BASE_ALIASES, get_settings
from .errors import ApiError, ConfigError from .errors import ApiError, AttachmentExpiredError, ConfigError, NetworkError
from .http import API_BASE, HttpClient, install_dns_fallback from .http import API_BASE, HttpClient, install_dns_fallback
TZ_CN = timezone(timedelta(hours=8)) # 表格日期按北京时间落库(毫秒时间戳) TZ_CN = timezone(timedelta(hours=8)) # 表格日期按北京时间落库(毫秒时间戳)
@@ -32,6 +41,12 @@ WRITE_BATCH = 20 # 批量写单次上限
MAX_PAGES = 500 # 500 × 100 = 5 万条上限 MAX_PAGES = 500 # 500 × 100 = 5 万条上限
_TS_FLOOR = 1_000_000_000_000 # 毫秒时间戳判定下限 _TS_FLOOR = 1_000_000_000_000 # 毫秒时间戳判定下限
ATTACH_MIN_REMAIN = 60 # 预签名 url 剩余有效期低于该秒数即视为不可用
ATTACH_TIMEOUT = 30.0 # 附件下载单次超时(秒)
_BAD_NAME = re.compile(r'[\\/:*?"<>|\r\n\t]+')
_MAGIC = ((b"\xff\xd8\xff", "jpg"), (b"\x89PNG\r\n\x1a\n", "png"),
(b"GIF87a", "gif"), (b"GIF89a", "gif"), (b"BM", "bmp"), (b"%PDF", "pdf"))
# ==================== 值归一 / 类型转换 ==================== # ==================== 值归一 / 类型转换 ====================
@@ -106,6 +121,77 @@ def flatten(record: dict) -> dict:
return row return row
# ==================== 附件(图片 / 文件)====================
def attachment_items(value: Any) -> List[Dict[str, Any]]:
"""``attachment`` 字段值 → ``[{resourceId, filename, size, type, url}]``。
notable 返回的附件元数据里 ``url`` 是阿里云 OSS **预签名地址**(免 token 直连、
约 2 小时过期);``resourceUrl`` 是相对路径不能直连,故只保留绝对 url。
"""
if not value:
return []
if isinstance(value, dict):
value = [value]
out: List[Dict[str, Any]] = []
for item in value:
if not isinstance(item, dict):
continue
url = str(item.get("url") or "")
if not url.startswith(("http://", "https://")):
url = ""
out.append({"resourceId": item.get("resourceId") or "",
"filename": item.get("filename") or "",
"size": int(item.get("size") or 0),
"type": item.get("type") or "",
"url": url})
return out
def parse_expires(url: str) -> int:
"""预签名 url 的 ``Expires`` 秒级时间戳;取不到返回 0(不限时的地址)。"""
try:
query = urllib_parse.parse_qs(urllib_parse.urlparse(url).query)
return int((query.get("Expires") or ["0"])[0] or 0)
except (TypeError, ValueError):
return 0
def safe_filename(name: Any, fallback: str = "file") -> str:
"""文件名净化:Windows 非法字符换 ``_``、去首尾点空格、限长 120。"""
text = _BAD_NAME.sub("_", str(name or "")).strip(" .")
if not text:
text = _BAD_NAME.sub("_", str(fallback or "file")).strip(" .") or "file"
return text[:120]
def sniff_kind(path: Any) -> str:
"""按文件头魔数判断真实类型(避免把错误页/半截文件当图片存下来)。"""
try:
head = Path(path).read_bytes()[:16]
except OSError:
return "missing"
if head[:4] == b"RIFF" and b"WEBP" in head[:16]:
return "webp"
for sig, kind in _MAGIC:
if head.startswith(sig):
return kind
return "unknown"
def unique_path(dest: Path) -> Path:
"""目标已存在时追加 ``-2``、``-3``…,避免同名附件互相覆盖。"""
dest = Path(dest)
if not dest.exists():
return dest
index = 2
while True:
candidate = dest.with_name(f"{dest.stem}-{index}{dest.suffix}")
if not candidate.exists():
return candidate
index += 1
def resolve_base(raw: str, aliases: Optional[Dict[str, str]] = None) -> Tuple[str, str]: def resolve_base(raw: str, aliases: Optional[Dict[str, str]] = None) -> Tuple[str, str]:
"""别名 / baseId / alidocs 链接 → ``(baseId, 链接里带的 sheetId 或空)``。""" """别名 / baseId / alidocs 链接 → ``(baseId, 链接里带的 sheetId 或空)``。"""
mapping = dict(BASE_ALIASES) mapping = dict(BASE_ALIASES)
@@ -263,19 +349,124 @@ class AiTable:
return self.update(base, sheet, return self.update(base, sheet,
[{"id": record_id, "fields": coerce_for_fields(meta, fields)}]) [{"id": record_id, "fields": coerce_for_fields(meta, fields)}])
# ---- 附件(图片 / 文件)下载 ----
def download_attachment(self, item: Dict[str, Any], dest: Any,
overwrite: bool = False,
timeout: Optional[float] = None) -> Dict[str, Any]:
"""下载单个附件到 ``dest``,返回结果 dict(``ok`` 恒为 True)。
返回字段:``path`` / ``bytes`` / ``kind`` / ``content_type`` / ``size_match``
(与表格声明大小比对)/ ``expires_in``(预签名剩余秒数)。
Raises:
AttachmentExpiredError: 预签名地址已过期/即将过期,或下载被拒(403)——
重新 ``records()`` 拉记录换新地址,重试同一地址无用
ConfigError: 附件没有可直连 url(只有相对 ``resourceUrl``)
ApiError: OSS 返回其它非 2xx
NetworkError: 重试耗尽仍未下载成功
"""
target = Path(dest)
item = item or {}
url = str(item.get("url") or "")
if not url:
raise ConfigError("附件没有可直连的 url(只有相对 resourceUrl)")
expires_in: Optional[int] = None
expires = parse_expires(url)
if expires:
expires_in = int(expires - time.time())
if expires_in <= ATTACH_MIN_REMAIN:
raise AttachmentExpiredError(
f"预签名 url 已过期/即将过期(剩 {expires_in}s),请重新拉记录换新地址")
target = target if overwrite else unique_path(target)
tmo = float(timeout if timeout is not None else ATTACH_TIMEOUT)
last: Optional[BaseException] = None
for attempt in range(1, self._http.retries + 1):
try:
resp = self._http.session.get(url, timeout=tmo)
except requests.RequestException as exc: # 网络抖动
last = NetworkError(f"附件下载失败({attempt}/{self._http.retries}):{exc}")
else:
if resp.status_code == 403:
raise AttachmentExpiredError(
"附件下载被拒(403,预签名 url 已过期或无权限),请重新拉记录")
if resp.status_code >= 400:
last = ApiError(f"附件下载失败:HTTP {resp.status_code}",
code=str(resp.status_code))
else:
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(resp.content)
declared = int(item.get("size") or 0)
return {"ok": True, "path": str(target), "bytes": len(resp.content),
"kind": sniff_kind(target),
"content_type": resp.headers.get("content-type", ""),
"size_match": (None if not declared
else len(resp.content) == declared),
"expires_in": expires_in}
if attempt < self._http.retries:
time.sleep(1.0 * attempt)
assert last is not None
if isinstance(last, (ApiError, NetworkError)):
raise last
raise NetworkError(f"附件下载失败:{last}")
def download_attachments(self, value: Any, save_dir: Any, prefix: str = "",
col: str = "", overwrite: bool = False) -> List[Dict[str, Any]]:
"""下载一个 ``attachment`` 字段的全部附件到 ``save_dir/``(``prefix + 原文件名``)。
单个附件失败不中断,结果里 ``ok=False`` 并带 ``error``/``expired``;成功项带
``path``/``bytes``/``kind``/``size_match``。结果额外含 ``col``/``index``/
``filename``/``resourceId``/``declared_size``,便于按字段归类落盘。
Example::
rows = table.records("hr", "uavChPe") # 银行卡-变更收集表
for record in rows:
fields = record.get("fields") or {}
table.download_attachments(fields.get("银行卡卡号面照片"),
rf"D:\\资料\\银行卡照片\\{fields.get('持卡人姓名','')}",
prefix="银行卡-")
"""
results: List[Dict[str, Any]] = []
for index, item in enumerate(attachment_items(value), 1):
name = safe_filename(item["filename"],
item["resourceId"] or f"{col or 'file'}{index}")
target = Path(save_dir) / safe_filename(f"{prefix}{name}" if prefix else name)
row: Dict[str, Any] = {
"col": col or "", "index": index, "filename": item["filename"],
"resourceId": item["resourceId"], "declared_size": item["size"],
"ok": False, "path": "", "bytes": 0, "kind": "", "content_type": "",
"size_match": None, "expires_in": None, "expired": False, "error": "",
}
try:
row.update(self.download_attachment(item, target, overwrite=overwrite))
except AttachmentExpiredError as exc:
row.update(expired=True, error=str(exc))
except (ConfigError, ApiError, NetworkError) as exc:
row["error"] = str(exc)
results.append(row)
return results
__all__ = [ __all__ = [
"ATTACH_MIN_REMAIN",
"ATTACH_TIMEOUT",
"MAX_PAGES", "MAX_PAGES",
"PAGE_SIZE", "PAGE_SIZE",
"TZ_CN", "TZ_CN",
"WRITE_BATCH", "WRITE_BATCH",
"AiTable", "AiTable",
"ApiError", "ApiError",
"AttachmentExpiredError",
"attachment_items",
"coerce_for_fields", "coerce_for_fields",
"flatten", "flatten",
"ms_to_str", "ms_to_str",
"norm", "norm",
"parse_expires",
"resolve_base", "resolve_base",
"safe_filename",
"sniff_kind",
"to_base_id", "to_base_id",
"to_ms", "to_ms",
"unique_path",
] ]
+5
View File
@@ -18,6 +18,10 @@ class ConfigError(DingTalkError):
"""配置缺失/非法(缺少 app key、webhook 未配置、dws 未安装等)。""" """配置缺失/非法(缺少 app key、webhook 未配置、dws 未安装等)。"""
class AttachmentExpiredError(ConfigError):
"""预签名附件地址已过期或被拒(403):需重新拉记录换新地址,重试同一地址无用。"""
class NetworkError(DingTalkError): class NetworkError(DingTalkError):
"""网络层失败(超时、连接中断、5xx),重试后仍失败才抛出。""" """网络层失败(超时、连接中断、5xx),重试后仍失败才抛出。"""
@@ -56,6 +60,7 @@ class CancelledError(DingTalkError):
__all__ = [ __all__ = [
"ApiError", "ApiError",
"AttachmentExpiredError",
"AuthError", "AuthError",
"CancelledError", "CancelledError",
"ConfigError", "ConfigError",
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "dingtalk_sdk" name = "dingtalk_sdk"
version = "0.1.2" version = "0.1.3"
description = "钉钉能力 SDK:群机器人推送 / 应用鉴权 / 媒体上传 / 单聊群聊推送(dws)/ AI 表格读写与月报周报采集" description = "钉钉能力 SDK:群机器人推送 / 应用鉴权 / 媒体上传 / 单聊群聊推送(dws)/ AI 表格读写与月报周报采集"
readme = "README.md" readme = "README.md"
requires-python = ">=3.9" requires-python = ">=3.9"
+1 -1
View File
@@ -2,7 +2,7 @@
"schema_version": 1, "schema_version": 1,
"id": "dingtalk_sdk", "id": "dingtalk_sdk",
"name": "钉钉 SDK", "name": "钉钉 SDK",
"version": "0.1.2", "version": "0.1.3",
"description": "钉钉能力集合:群机器人推送(加签/Markdown/状态色/分批/块格式/多环境)、企业内部应用鉴权(v1 + oapi)、媒体库上传、dws 单聊/群聊推送(文本/文件/@/限流/推送记录)、AI 表格读写与月报周报采集", "description": "钉钉能力集合:群机器人推送(加签/Markdown/状态色/分批/块格式/多环境)、企业内部应用鉴权(v1 + oapi)、媒体库上传、dws 单聊/群聊推送(文本/文件/@/限流/推送记录)、AI 表格读写与月报周报采集",
"provides": [ "provides": [
"dingtalk_sdk" "dingtalk_sdk"