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:
@@ -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",
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user