Python3调用京东AI,进行文字识别

匿名 (未验证) 提交于 2019-12-02 22:11:45
 #!/usr/bin/python # -*- coding: utf-8 -*- import os import time import requests import hashlib from dataclasses import dataclass   def get_file_content(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:         return fp.read()  def get_param_sign_str(sign_str):     """根据规则拼接字符串,并对其进行MD5运算,得到sign"""     md5 = hashlib.md5()     md5.update(sign_str.encode())     return md5.hexdigest()  @dataclass class JDAPIMsg(object):     appkey     : str     secretkey  : str     apiurl     : str     image_file : str      def __post_init__(self):         self.image     = get_file_content(self.image_file)         self.timestamp = str(int(time.time()*1000))         self.sign      = get_param_sign_str(self.secretkey + self.timestamp)         self.params    = {             'appkey':    self.appkey,             'timestamp': self.timestamp,             'sign':      self.sign, }      def get_ocr_result(self):         response    = requests.post(self.apiurl,data = self.image,params = self.params)         try:             data    = response.json()             texts   = data['result']['resultData']             words   = [text['text'] for text in texts]             return '\n'.join(words)         except:             print ('获取结果失败,请检查各参数是否配置正确。')             return ''  if __name__ == '__main__':     appkey     = 'c******************************3'     #需要自己申请     secretkey  = 'e******************************0'     #需要自己申请     apiurl     = 'https://aiapi.jd.com/jdai/ocr_universal'     image_file = 'F:\\20180829193608871.jpg'          Jd = JDAPIMsg(appkey, secretkey, apiurl, image_file)     result = Jd.get_ocr_result()     print(result) 

文章来源: https://blog.csdn.net/qq523176585/article/details/88876235
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!