1.目录结构
-script_discerm ------------包
-discerm.py --------------主要逻辑
-__init__.py
-id_care---------------文件夹 存放图片
2.安装模块
pip install urllib3==1.23
pip install requests
pip install base64
3.各文件内容
2.1 discerm.py
import jsonimport requests
import base64
from urllib import parse
import os
#API_KEY SECRET_KEY 是百度云创建应用生成的 -https://console.bce.baidu.com/ai/#/ai/ocr/app/list
API_KEY = "EN3NxxxxxxxIZHueIC"
SECRET_KEY = "kexxxxxxxxxxxxUUotfzB91z"def script_discerns(path): #path 是文件对象url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + get_access_token()#id_card_side=front front是身份证的正面 back是反面payload = 'id_card_side=front&image='+str(get_file_content_as_base64(path, True))headers = {'Content-Type': 'application/x-www-form-urlencoded','Accept': 'application/json'}# print(payload)response = requests.request("POST", url, headers=headers, data=payload)# print(response.text)discern_dict = response.textdiscern_dict = json.loads(discern_dict)return discern_dict #返回的是jsondef get_file_content_as_base64(path, urlencoded=False):"""获取文件base64编码:param path: 文件路径:param urlencoded: 是否对结果进行urlencoded:return: base64编码信息""" #身份证图片存放的路径save_path = os.path.join('youzhu_api/libs/script_discern/id_care',str(path))# print(save_path)f = open(save_path, 'wb+')for chunk in path.chunks():f.write(chunk)f.close()f2 = open(save_path, "rb")content = base64.b64encode(f2.read()).decode("utf8")if urlencoded:content = parse.quote_plus(content)f2.close()return contentdef get_access_token():"""使用 AK,SK 生成鉴权签名(Access Token):return: access_token,或是None(如果错误)"""url = "https://aip.baidubce.com/oauth/2.0/token"params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}return str(requests.post(url, params=params).json().get("access_token"))
2.2__init__.py
from .discern import *
4.调用方式
4.1如果要用我的这一套 注意:
1,要配置 API_KEY ,SECRET_KEY
2.def script_discerns(path) path要传入的是图片对象
3,save_path 图片的地址要正确,才能再打开读取图片
4.2调用
from libs.script_discern import script_discernsfile = request.FILES.get('file') #获取文件对象
discern_dict = script_discerns(file) #调用函数,返回值是jsonwords = discern_dict['words_result']['公民身份号码']['words']addr = discern_dict['words_result']['住址']['words']