- desktopauto:cardocr 引擎/流水线/校验与 ocr 调整,sdk.json/pyproject/版本三处一致 - dingtalk:AI 表格读写与错误封装扩充 - aitable:client/cli/自测与打包配置更新
365 lines
16 KiB
Python
365 lines
16 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""钉钉 AI 表格命令行(agent 用):列 sheet/字段、拉记录、过滤、统计、增改、导出。
|
||
|
||
运行(仓库根):
|
||
.venv\\Scripts\\python.exe libs\\aitable\\aitable\\cli.py sheets workplan
|
||
.venv\\Scripts\\python.exe libs\\aitable\\aitable\\cli.py list workplan --sheet hERWDMS --month 上线日期=2026-10
|
||
.venv\\Scripts\\python.exe libs\\aitable\\aitable\\cli.py summary workplan --sheet hERWDMS --by 状态
|
||
|
||
也支持 `python -m aitable`(需 PYTHONPATH 指向 libs/aitable 或 pip install -e)。
|
||
base 支持别名(workplan / hr)、baseId、alidocs 文档链接;凭证见 client.py。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import csv
|
||
import json
|
||
import sys
|
||
import unicodedata
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
try: # 作为包导入
|
||
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, attachment_items, # noqa: F401
|
||
coerce_for_fields, flatten, norm, resolve_base, safe_filename)
|
||
|
||
|
||
# ==================== 过滤 / 输出 ====================
|
||
|
||
def apply_filters(rows: list, wheres: list, months: list) -> list:
|
||
"""--where 字段=值(精确,AND);--month 字段=YYYY-MM(任一命中,OR)。"""
|
||
for w in wheres or []:
|
||
if "=" not in w:
|
||
raise SystemExit(f"[x] --where 需为 字段=值:{w}")
|
||
k, v = w.split("=", 1)
|
||
rows = [r for r in rows if str(r.get(k.strip(), "")).strip() == v.strip()]
|
||
if months:
|
||
pairs = []
|
||
for m in months:
|
||
if "=" not in m:
|
||
raise SystemExit(f"[x] --month 需为 字段=YYYY-MM:{m}")
|
||
k, v = m.split("=", 1)
|
||
pairs.append((k.strip(), v.strip()))
|
||
rows = [r for r in rows
|
||
if any(str(r.get(k, "")).startswith(v) for k, v in pairs)]
|
||
return rows
|
||
|
||
|
||
def _disp_width(s: str) -> int:
|
||
return sum(2 if unicodedata.east_asian_width(ch) in "WF" else 1 for ch in s)
|
||
|
||
|
||
def _pad(s: str, width: int) -> str:
|
||
return s + " " * max(0, width - _disp_width(s))
|
||
|
||
|
||
def print_table(rows: list, columns: list) -> None:
|
||
if not rows:
|
||
print("(无记录)")
|
||
return
|
||
|
||
def _cell(v: Any) -> str:
|
||
return str(v if v is not None else "").replace("\r", " ").replace("\n", " ").strip()
|
||
|
||
cells = [[_cell(r.get(c)) for c in columns] for r in rows]
|
||
widths = [max(_disp_width(c), *(_disp_width(row[i]) for row in cells)) for i, c in enumerate(columns)]
|
||
print(" ".join(_pad(c, w) for c, w in zip(columns, widths)))
|
||
print(" ".join("-" * w for w in widths))
|
||
for row in cells:
|
||
print(" ".join(_pad(v, w) for v, w in zip(row, widths)))
|
||
|
||
|
||
def emit_json(obj: Any) -> None:
|
||
print(json.dumps(obj, ensure_ascii=False, indent=1))
|
||
|
||
|
||
def write_out(path: str, rows: list, columns: list) -> None:
|
||
p = Path(path)
|
||
p.parent.mkdir(parents=True, exist_ok=True)
|
||
if p.suffix.lower() == ".json":
|
||
p.write_text(json.dumps(rows, ensure_ascii=False, indent=1), encoding="utf-8")
|
||
else:
|
||
with p.open("w", encoding="utf-8-sig", newline="") as f: # utf-8-sig:Excel 打开不乱码
|
||
w = csv.DictWriter(f, fieldnames=columns, extrasaction="ignore")
|
||
w.writeheader()
|
||
w.writerows([{k: r.get(k, "") for k in columns} for r in rows])
|
||
print(f"[+] 已导出 {len(rows)} 条 → {p}")
|
||
|
||
|
||
def pick_columns(rows: list, spec: str) -> list:
|
||
if spec:
|
||
return [c.strip() for c in spec.split(",") if c.strip()]
|
||
cols = []
|
||
for r in rows:
|
||
for k in r:
|
||
if k not in cols:
|
||
cols.append(k)
|
||
cols.sort(key=lambda c: c != "_id")
|
||
return cols
|
||
|
||
|
||
def _sheet_arg(args: argparse.Namespace, cli: AiTable, base: str, link_sheet: str) -> str:
|
||
raw = getattr(args, "sheet", "") or link_sheet
|
||
if not raw:
|
||
raise SystemExit("[x] 缺少 --sheet(可先跑 sheets 子命令查看 id/名称)")
|
||
return cli.resolve_sheet(base, raw)
|
||
|
||
|
||
# ==================== 子命令 ====================
|
||
|
||
def _cmd_sheets(args, cli) -> int:
|
||
base, _ = resolve_base(args.base)
|
||
items = cli.sheets(base)
|
||
if args.json:
|
||
emit_json({"base": base, "sheets": items})
|
||
else:
|
||
print(f"base {base} 共 {len(items)} 张 sheet:")
|
||
print_table([{"名称": s.get("name"), "id": s.get("id")} for s in items], ["名称", "id"])
|
||
return 0
|
||
|
||
|
||
def _cmd_fields(args, cli) -> int:
|
||
base, link_sheet = resolve_base(args.base)
|
||
sheet = _sheet_arg(args, cli, base, link_sheet)
|
||
meta = cli.fields(base, sheet)
|
||
if args.json:
|
||
emit_json({"base": base, "sheet": sheet, "fields": meta.get("value", [])})
|
||
return 0
|
||
rows = []
|
||
for f in meta.get("value", []):
|
||
choices = [c.get("name") for c in (f.get("property") or {}).get("choices") or []]
|
||
rows.append({"字段": f.get("name"), "类型": f.get("type"),
|
||
"选项": "/".join(map(str, choices))[:60]})
|
||
print(f"sheet {sheet} 共 {len(rows)} 个字段:")
|
||
print_table(rows, ["字段", "类型", "选项"])
|
||
return 0
|
||
|
||
|
||
def _cmd_list(args, cli) -> int:
|
||
base, link_sheet = resolve_base(args.base)
|
||
sheet = _sheet_arg(args, cli, base, link_sheet)
|
||
rows = [flatten(r) for r in cli.records(base, sheet)]
|
||
rows = apply_filters(rows, args.where, args.month)
|
||
if args.limit:
|
||
rows = rows[: args.limit]
|
||
cols = pick_columns(rows, args.columns)
|
||
if args.out:
|
||
write_out(args.out, rows, cols)
|
||
if args.json:
|
||
emit_json({"base": base, "sheet": sheet, "count": len(rows), "records": rows})
|
||
else:
|
||
print(f"共 {len(rows)} 条:")
|
||
print_table(rows, cols)
|
||
return 0
|
||
|
||
|
||
def _cmd_summary(args, cli) -> int:
|
||
base, link_sheet = resolve_base(args.base)
|
||
sheet = _sheet_arg(args, cli, base, link_sheet)
|
||
rows = apply_filters([flatten(r) for r in cli.records(base, sheet)], args.where, args.month)
|
||
bys = [b.strip() for b in args.by.split(",") if b.strip()]
|
||
result: dict = {}
|
||
for b in bys:
|
||
counter: dict = {}
|
||
for r in rows:
|
||
key = str(r.get(b) if r.get(b) not in (None, "") else "(空)")
|
||
counter[key] = counter.get(key, 0) + 1
|
||
result[b] = dict(sorted(counter.items(), key=lambda kv: -kv[1]))
|
||
if args.json:
|
||
emit_json({"base": base, "sheet": sheet, "total": len(rows), "summary": result})
|
||
return 0
|
||
print(f"共 {len(rows)} 条记录:")
|
||
for b, counter in result.items():
|
||
print(f"\n[{b}]")
|
||
print_table([{b: k, "数量": v} for k, v in counter.items()], [b, "数量"])
|
||
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 只能二选一")
|
||
text = Path(file_path).read_text(encoding="utf-8") if file_path else (raw or "")
|
||
if not text.strip():
|
||
raise SystemExit("[x] 缺少 --data '{...}' 或 --data-file <json>")
|
||
try:
|
||
data = json.loads(text)
|
||
except json.JSONDecodeError as exc:
|
||
raise SystemExit(f"[x] 数据不是合法 JSON:{exc}")
|
||
if not isinstance(data, dict):
|
||
raise SystemExit("[x] 数据必须是 JSON 对象(字段名 → 值)")
|
||
return data
|
||
|
||
|
||
def _cmd_add(args, cli) -> int:
|
||
base, link_sheet = resolve_base(args.base)
|
||
sheet = _sheet_arg(args, cli, base, link_sheet)
|
||
payload = coerce_for_fields(cli.fields(base, sheet), _load_data(args.data, args.data_file))
|
||
if args.dry_run:
|
||
print("[~] 试算,未写入:")
|
||
emit_json(payload)
|
||
return 0
|
||
n = cli.add(base, sheet, [payload])
|
||
print(f"[+] 新增 {n} 条 → sheet {sheet}")
|
||
return 0
|
||
|
||
|
||
def _cmd_update(args, cli) -> int:
|
||
base, link_sheet = resolve_base(args.base)
|
||
sheet = _sheet_arg(args, cli, base, link_sheet)
|
||
if not args.record:
|
||
raise SystemExit("[x] 缺少 --record(记录 id,可用 list --json 查看 _id)")
|
||
payload = coerce_for_fields(cli.fields(base, sheet), _load_data(args.data, args.data_file))
|
||
if args.dry_run:
|
||
print("[~] 试算,未写入:")
|
||
emit_json({"id": args.record, "fields": payload})
|
||
return 0
|
||
n = cli.update(base, sheet, [{"id": args.record, "fields": payload}])
|
||
print(f"[+] 更新 {n} 条 → sheet {sheet} / record {args.record}")
|
||
return 0
|
||
|
||
|
||
def build_parser() -> argparse.ArgumentParser:
|
||
p = argparse.ArgumentParser(
|
||
prog="aitable",
|
||
description="钉钉 AI 表格读写 CLI(notable);base 支持别名 / baseId / alidocs 链接")
|
||
sub = p.add_subparsers(dest="cmd", required=True)
|
||
|
||
common = argparse.ArgumentParser(add_help=False)
|
||
common.add_argument("--operator", default=DEFAULT_OPERATOR,
|
||
help="操作人 unionId(须是目标表格协作者;默认人资专用号)")
|
||
common.add_argument("--json", action="store_true", help="以 JSON 输出(agent 解析用)")
|
||
|
||
s = sub.add_parser("sheets", help="列出 base 下全部 sheet", parents=[common])
|
||
s.add_argument("base", help="别名 / baseId / 文档链接")
|
||
s.set_defaults(func=_cmd_sheets)
|
||
|
||
s = sub.add_parser("fields", help="查看 sheet 字段名/类型/单选选项", parents=[common])
|
||
s.add_argument("base")
|
||
s.add_argument("--sheet", default="", help="sheet id 或名称")
|
||
s.set_defaults(func=_cmd_fields)
|
||
|
||
s = sub.add_parser("list", help="拉取记录(可过滤/导出)", parents=[common])
|
||
s.add_argument("base")
|
||
s.add_argument("--sheet", default="")
|
||
s.add_argument("--where", action="append", default=[], metavar="字段=值",
|
||
help="等值过滤,可重复(AND)")
|
||
s.add_argument("--month", action="append", default=[], metavar="日期字段=YYYY-MM",
|
||
help="按月份过滤(北京时间),可重复(OR)")
|
||
s.add_argument("--columns", default="", help="输出列,逗号分隔")
|
||
s.add_argument("--limit", type=int, default=0, help="最多输出条数")
|
||
s.add_argument("--out", default="", help="导出 .csv / .json")
|
||
s.set_defaults(func=_cmd_list)
|
||
|
||
s = sub.add_parser("summary", help="分组统计(状态分布 / 月度完成情况)", parents=[common])
|
||
s.add_argument("base")
|
||
s.add_argument("--sheet", default="")
|
||
s.add_argument("--by", required=True, help="分组字段,逗号分隔,如 状态,需求部门")
|
||
s.add_argument("--where", action="append", default=[], metavar="字段=值")
|
||
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="")
|
||
s.add_argument("--data", default="", help='JSON 对象,如 \'{"需求编号":"XQ0100"}\'')
|
||
s.add_argument("--data-file", default="", help="从 JSON 文件读取字段")
|
||
s.add_argument("--dry-run", action="store_true", help="只打印转换后的字段,不写入")
|
||
s.set_defaults(func=_cmd_add)
|
||
|
||
s = sub.add_parser("update", help="更新记录", parents=[common])
|
||
s.add_argument("base")
|
||
s.add_argument("--sheet", default="")
|
||
s.add_argument("--record", default="", help="记录 id")
|
||
s.add_argument("--data", default="")
|
||
s.add_argument("--data-file", default="")
|
||
s.add_argument("--dry-run", action="store_true")
|
||
s.set_defaults(func=_cmd_update)
|
||
return p
|
||
|
||
|
||
def main(argv: list = None) -> None:
|
||
try:
|
||
sys.stdout.reconfigure(encoding="utf-8")
|
||
except Exception:
|
||
pass
|
||
args = build_parser().parse_args(argv)
|
||
cli = AiTable(args.operator)
|
||
sys.exit(args.func(args, cli))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|