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,20 +1,23 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""aitable · 钉钉 AI 表格(notable)读写库 + 月报/周报数据采集。
|
||||
|
||||
对外只暴露三样:
|
||||
- AiTable 表格客户端(列 sheet/字段、分页读、批量增改)
|
||||
- cli / report 两个命令行入口(python -m aitable / python -m aitable.report)
|
||||
- 值归一工具 norm / to_ms / coerce_for_fields / flatten(写插件回填时常用)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .client import ( # noqa: F401
|
||||
BASE_ALIASES, DEFAULT_OPERATOR, AiTable, coerce_for_fields, flatten,
|
||||
install_dns_fallback, ms_to_str, norm, resolve_base, to_ms,
|
||||
)
|
||||
|
||||
__version__ = "1.0.0"
|
||||
__all__ = [
|
||||
"AiTable", "BASE_ALIASES", "DEFAULT_OPERATOR", "coerce_for_fields", "flatten",
|
||||
"install_dns_fallback", "ms_to_str", "norm", "resolve_base", "to_ms",
|
||||
]
|
||||
# -*- coding: utf-8 -*-
|
||||
"""aitable · 钉钉 AI 表格(notable)读写库 + 月报/周报数据采集。
|
||||
|
||||
对外暴露:
|
||||
- AiTable 表格客户端(列 sheet/字段、分页读、批量增改、附件下载)
|
||||
- cli / report 两个命令行入口(python -m aitable / python -m aitable.report)
|
||||
- 值归一工具 norm / to_ms / coerce_for_fields / flatten(写插件回填时常用)
|
||||
- 附件工具 attachment_items / safe_filename / sniff_kind / parse_expires
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .client import ( # noqa: F401
|
||||
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.1.0"
|
||||
__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",
|
||||
]
|
||||
|
||||
@@ -20,12 +20,12 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
try: # 作为包导入
|
||||
from .client import (AiTable, DEFAULT_OPERATOR, coerce_for_fields, flatten,
|
||||
resolve_base)
|
||||
from .client import (AiTable, DEFAULT_OPERATOR, attachment_items,
|
||||
coerce_for_fields, flatten, norm, resolve_base, safe_filename)
|
||||
except ImportError: # 直接执行文件
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from aitable.client import (AiTable, DEFAULT_OPERATOR, coerce_for_fields, # noqa: F401
|
||||
flatten, resolve_base)
|
||||
from aitable.client import (AiTable, DEFAULT_OPERATOR, attachment_items, # noqa: F401
|
||||
coerce_for_fields, flatten, norm, resolve_base, safe_filename)
|
||||
|
||||
|
||||
# ==================== 过滤 / 输出 ====================
|
||||
@@ -179,6 +179,61 @@ def _cmd_summary(args, cli) -> int:
|
||||
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:
|
||||
if raw and file_path:
|
||||
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.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.add_argument("base")
|
||||
s.add_argument("--sheet", default="")
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""钉钉 AI 表格(notable)客户端:鉴权、分页读取、字段归一、按类型写值。
|
||||
"""钉钉 AI 表格(notable)客户端:鉴权、分页读取、字段归一、按类型写值、附件下载。
|
||||
|
||||
凭证读取顺序(**不读已废弃的 desktop/controlplane/.env**):
|
||||
1. 环境变量 AITABLE_ENV_FILE 指定的 .env
|
||||
@@ -11,8 +11,10 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import time
|
||||
import urllib.parse as urllib_parse
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
@@ -183,6 +185,85 @@ def flatten(rec: dict) -> dict:
|
||||
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:
|
||||
@@ -292,6 +373,77 @@ class AiTable:
|
||||
ok += len(d.get("value") or batch)
|
||||
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:
|
||||
"""别名 / baseId / alidocs 链接 → (baseId, 链接里带的 sheetId 或空)。"""
|
||||
|
||||
Reference in New Issue
Block a user