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:
@@ -33,16 +33,17 @@ AI 表格(notable)读写 :class:`aitable.AiTable` 与值归一工具
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
__version__ = "0.1.2"
|
||||
__version__ = "0.1.3"
|
||||
|
||||
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)
|
||||
from .auth import AccessToken, invalidate as invalidate_token, token
|
||||
from .config import RobotAccount, Settings, get_settings, load_env_files
|
||||
from .dws import Dws, push as push_dws
|
||||
from .errors import (ApiError, AuthError, CancelledError, ConfigError, DingTalkError,
|
||||
DwsError, NetworkError)
|
||||
from .errors import (ApiError, AttachmentExpiredError, AuthError, CancelledError,
|
||||
ConfigError, DingTalkError, DwsError, NetworkError)
|
||||
from .media import markdown_image, upload_media
|
||||
from .robot import (DingTalkRobot, Robot, build_sign, build_url, compose_batch_messages,
|
||||
push as push_robot, split_by_chars)
|
||||
@@ -64,6 +65,7 @@ __all__ = [
|
||||
"AccessToken",
|
||||
"AiTable",
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"AuthError",
|
||||
"CancelledError",
|
||||
"ConfigError",
|
||||
@@ -76,6 +78,7 @@ __all__ = [
|
||||
"RobotAccount",
|
||||
"Settings",
|
||||
"aitable",
|
||||
"attachment_items",
|
||||
"auth",
|
||||
"build_sign",
|
||||
"build_url",
|
||||
@@ -94,12 +97,15 @@ __all__ = [
|
||||
"media",
|
||||
"ms_to_str",
|
||||
"norm",
|
||||
"parse_expires",
|
||||
"parse_period",
|
||||
"push_dws",
|
||||
"push_robot",
|
||||
"report",
|
||||
"resolve_base",
|
||||
"robot",
|
||||
"safe_filename",
|
||||
"sniff_kind",
|
||||
"split_by_chars",
|
||||
"to_base_id",
|
||||
"to_ms",
|
||||
|
||||
@@ -225,6 +225,97 @@ def test_aitable() -> None:
|
||||
"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:
|
||||
@@ -264,6 +355,7 @@ def main() -> int:
|
||||
("http", test_http),
|
||||
("dws", test_dws),
|
||||
("aitable", test_aitable),
|
||||
("aitable_attachment", test_aitable_attachment),
|
||||
("media", test_media),
|
||||
("report", test_report),
|
||||
]
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""钉钉 AI 表格(notable)读写。
|
||||
|
||||
能力(与原 ``libs/aitable`` 一致):
|
||||
能力(在原 ``libs/aitable`` 一致基础上补齐附件下载):
|
||||
- 列 sheet / 字段定义;按 ``hasMore`` + ``nextToken`` 分页读全量记录;
|
||||
- 批量新增 / 更新记录(自动按 20 条一批);
|
||||
- 值归一(``norm``)、日期毫秒互转(``ms_to_str`` / ``to_ms``)、
|
||||
按字段类型转换写入值(``coerce_for_fields``)、记录拍平(``flatten``);
|
||||
- 附件(图片/文件)字段解析与下载:``attachment_items`` + ``AiTable.download_attachments``
|
||||
(``attachment`` 字段里带阿里云 OSS 预签名 url,免 token 直连、约 2 小时过期);
|
||||
- base 支持别名 / baseId / alidocs 链接三种写法(``resolve_base``)。
|
||||
|
||||
与旧实现的差异(SDK 契约要求):
|
||||
- 失败抛 ``ConfigError`` / ``ApiError`` / ``NetworkError``,**不再 SystemExit**;
|
||||
- 预签名附件地址过期抛 ``AttachmentExpiredError``(``ConfigError`` 子类),
|
||||
批量下载时单文件失败不中断,结果里 ``ok=False`` 并带原因;
|
||||
- 凭证与操作人可显式传入,缺省读配置(见 :mod:`dingtalk_sdk.config`)。
|
||||
"""
|
||||
|
||||
@@ -17,12 +21,17 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import urllib.parse as urllib_parse
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List, Optional, Tuple
|
||||
|
||||
import requests
|
||||
|
||||
from .auth import KIND_V1, AccessToken
|
||||
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
|
||||
|
||||
TZ_CN = timezone(timedelta(hours=8)) # 表格日期按北京时间落库(毫秒时间戳)
|
||||
@@ -32,6 +41,12 @@ WRITE_BATCH = 20 # 批量写单次上限
|
||||
MAX_PAGES = 500 # 500 × 100 = 5 万条上限
|
||||
_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
|
||||
|
||||
|
||||
# ==================== 附件(图片 / 文件)====================
|
||||
|
||||
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]:
|
||||
"""别名 / baseId / alidocs 链接 → ``(baseId, 链接里带的 sheetId 或空)``。"""
|
||||
mapping = dict(BASE_ALIASES)
|
||||
@@ -263,19 +349,124 @@ class AiTable:
|
||||
return self.update(base, sheet,
|
||||
[{"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__ = [
|
||||
"ATTACH_MIN_REMAIN",
|
||||
"ATTACH_TIMEOUT",
|
||||
"MAX_PAGES",
|
||||
"PAGE_SIZE",
|
||||
"TZ_CN",
|
||||
"WRITE_BATCH",
|
||||
"AiTable",
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"attachment_items",
|
||||
"coerce_for_fields",
|
||||
"flatten",
|
||||
"ms_to_str",
|
||||
"norm",
|
||||
"parse_expires",
|
||||
"resolve_base",
|
||||
"safe_filename",
|
||||
"sniff_kind",
|
||||
"to_base_id",
|
||||
"to_ms",
|
||||
"unique_path",
|
||||
]
|
||||
|
||||
@@ -18,6 +18,10 @@ class ConfigError(DingTalkError):
|
||||
"""配置缺失/非法(缺少 app key、webhook 未配置、dws 未安装等)。"""
|
||||
|
||||
|
||||
class AttachmentExpiredError(ConfigError):
|
||||
"""预签名附件地址已过期或被拒(403):需重新拉记录换新地址,重试同一地址无用。"""
|
||||
|
||||
|
||||
class NetworkError(DingTalkError):
|
||||
"""网络层失败(超时、连接中断、5xx),重试后仍失败才抛出。"""
|
||||
|
||||
@@ -56,6 +60,7 @@ class CancelledError(DingTalkError):
|
||||
|
||||
__all__ = [
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"AuthError",
|
||||
"CancelledError",
|
||||
"ConfigError",
|
||||
|
||||
Reference in New Issue
Block a user