Files
2026-10-18 07:40:42 +08:00

53 lines
1.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""调用示例:上传本地图片,拿回结构化 JSON。
三种鉴权方式按需选一种(与服务端 .env 对应):
1. 静态 token(推荐):TOKEN = "你的 token",走 Authorization: Bearer
2. 短期 token:填 CLIENT_SECRET,脚本自动换 token(适合前端后端代理场景)
3. 不配置:TOKEN 和 CLIENT_SECRET 都留空,服务端也必须未配鉴权
"""
import json
import sys
import requests
BASE = "http://10.1.1.163:8000" # 换成你的服务地址
TOKEN = "" # 静态 token(API_TOKENS 里那把)
CLIENT_ID = "default"
CLIENT_SECRET = "" # 填了就走短期 token 流程
def get_token() -> str:
"""用 client_secret 换一个短期 token。"""
r = requests.post(
f"{BASE}/api/v1/auth/token",
json={"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET},
timeout=10,
)
r.raise_for_status()
data = r.json()
print(f"[token] 有效期 {data['expires_in']}s", file=sys.stderr)
return data["token"]
def recognize(path: str, side: str = "auto", mask: bool = False) -> dict:
token = TOKEN or (get_token() if CLIENT_SECRET else "")
headers = {"Authorization": f"Bearer {token}"} if token else {}
with open(path, "rb") as f:
r = requests.post(
f"{BASE}/api/v1/idcard/recognize",
files={"file": (path, f, "image/jpeg")},
data={"side": side, "mask": str(mask).lower()},
headers=headers,
timeout=120, # 低端 NAS 第一次要加载模型,给足时间
)
if r.status_code == 401:
raise SystemExit("鉴权失败:token 无效或已过期(检查 .env 里的 API_TOKENS / CLIENT_SECRET)")
r.raise_for_status()
return r.json()
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else "idcard.jpg"
print(json.dumps(recognize(path), ensure_ascii=False, indent=2))