欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python3版阿里云身份证识别

程序员文章站 2022-07-15 14:59:48
...

购买了阿里云的身份证识别OCR:https://market.aliyun.com/products/57124001/cmapi028587.html#sku=yuncode2258700001

示例用的是python2,花了点时间给它转成了python3版,并采用了requests库(需要pip install requests)

#!/usr/bin/env python3
import requests
import sys
from base64 import b64encode
from pathlib import Path

HOST = "https://cardiddecode.market.alicloudapi.com"
PATH = "/api/decode_cardid_aliyun"


def verify(url, appcode, fname):
    data = {"imgbase64": b64encode(Path(fname).read_bytes()).decode()}
    headers = {
        "Authorization": f"APPCODE {appcode}",
        "Content-Type": "application/json; charset=UTF-8",
    }
    requests.packages.urllib3.disable_warnings()
    r = requests.post(url, json=data, headers=headers, verify=False)
    r.raise_for_status()
    return r.json()


def main():
    url = HOST + PATH
    appcode = load_appcode()  # appcode = 'xxx'
    fname = image_name()  # fname = 'xxx.jpg'
    result = verify(url, appcode, fname)
    print(f"Response from ``{url}`` for ``{fname}``:\n{result}")


def load_appcode():
    for fname in ("appcode", "appcode.txt"):
        p = Path(fname)
        if p.exists():
            appcode = p.read_text().strip()
            break
    else:
        appcode = input("appcode: ").strip()
    return appcode


def image_name():
    if sys.argv[1:]:
        fname = sys.argv[1]
    else:
        fname = None
    if not fname or not Path(fname).exists():
        for suffix in (".jpg", ".png"):
            imgs = list(Path().glob(f"*{suffix}"))
            if imgs:
                fname = imgs[0]
                break
        else:
            fname = input("Image file name: ").strip()
    return fname


if __name__ == "__main__":
    main()

 

相关标签: a'