#coding=utf-8 import os import json import time import random import base64 import string import hashlib import requests from dataclasses import dataclass def get_img_base64str(image_file): """生成原始图片的base64编码数据,得到image参数""" if not isinstance(image_file, str): return None if not os.path.isfile(image_file): print('图片文件有误,请传入正确的文件路径') return None with open(image_file, 'rb') as fp: imgbase64 = base64.b64encode(fp.read()) return imgbase64.decode() @dataclass class YouDaoAPIMsg(object): app_Key: str secret_Key: str api_url: str image_file: str def __post_init__(self): self.image = get_img_base64str(self.image_file) self.salt = str(random.randint(10000, 99999)) def gen_sign_md5(self, req_dict): sign = req_dict['appKey'] + req_dict['img'] + \ req_dict['salt'] + self.secret_Key md5 = hashlib.md5() md5.update(sign.encode()) return md5.hexdigest().upper() def set_req_dict(self): """生成字典,得到请求参数,严格按照此代码顺序,避免排序""" req_dict = { 'appKey': self.app_Key, 'img': self.image, 'detectType': '10012', 'imageType': '1', 'langType': "zh-en", 'salt': self.salt, } req_dict['sign'] = self.gen_sign_md5(req_dict) return req_dict def get_ocr_result(self): data = self.set_req_dict() text = requests.post(self.api_url, data=data) try: data = text.json() text = data['Result']['regions'][0]['lines'] res = [word['text'] for word in text] return ''.join(res) except: print('获取结果失败,请检查各参数是否配置正确。') return '' if __name__ == "__main__": app_Key = '2**************2' #需要自己申请 secret_Key = 'b******************************b' #需要自己申请 api_url = "http://openapi.youdao.com/ocrapi" image_file = 'F:\\20180829193608871.jpg' Youdao = YouDaoAPIMsg(app_Key, secret_Key, api_url, image_file) text = Youdao.get_ocr_result() print(text)
文章来源: https://blog.csdn.net/qq523176585/article/details/88876595