{"repo": "centyuan/pydemo", "files": {"PyExample/OcrGather/clients/xfyun_ocr.py": {"b8aa48d1868c924389f65310169c2cae4fbce2ff": {"t": 1785674330.869733, "n": 4327, "h": "16bf86525886f24f", "c": "from datetime import datetime\nfrom wsgiref.handlers import format_date_time\nfrom time import mktime\nimport hashlib\nimport base64\nimport hmac\nfrom urllib.parse import urlencode\nimport json\nimport requests\n\n\nclass AssembleHeaderException(Exception):\n def __init__(self, msg):\n self.message = msg\n\n\ndef sha256base64(data):\n sha256 = hashlib.sha256()\n sha256.update(data)\n digest = base64.b64encode(sha256.digest()).decode(encoding='utf-8')\n return digest\n\n\ndef parse_url(requset_url):\n \"\"\"\n 解析url\n :param requset_url:\n :return:\n \"\"\"\n stidx = requset_url.index(\"://\")\n host = requset_url[stidx + 3:]\n schema = requset_url[:stidx + 3]\n edidx = host.index(\"/\")\n if edidx <= 0:\n raise AssembleHeaderException(\"invalid request url:\" + requset_url)\n path = host[edidx:]\n host = host[:edidx]\n return host, path, schema\n\n\ndef assemble_ws_auth_url(requset_url, method=\"POST\", api_key=\"\", api_secret=\"\"):\n \"\"\"\n 鉴权 并返回request url\n :param requset_url:\n :param method:\n :param api_key:\n :param api_secret:\n :return:\n \"\"\"\n host, path, schema = parse_url(requset_url)\n date = format_date_time(mktime(datetime.now().timetuple()))\n # date = \"Thu, 12 Dec 2019 01:57:27 GMT\"\n signature_origin = \"host: {}\\ndate: {}\\n{} {} HTTP/1.1\".format(host, date, method, path)\n \"\"\"\n signature原始字段(signature_origin)则为:\n host: api.xf-yun.com\n date: Wed, 11 Aug 2021 06:55:18 GMT\n POST /v1/private/sf8e6aca1 HTTP/1.1\n \"\"\"\n # 生成摘要\n signature_sha = hmac.new(api_secret.encode('utf-8'), signature_origin.encode('utf-8'),\n digestmod=hashlib.sha256).digest()\n # 对摘要编码\n signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')\n authorization_origin = \"api_key=\\\"%s\\\", algorithm=\\\"%s\\\", headers=\\\"%s\\\", signature=\\\"%s\\\"\" % (\n api_key, \"hmac-sha256\", \"host date request-line\", signature_sha)\n authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')\n values = {\n \"host\": host,\n \"date\": date,\n \"authorization\": authorization\n }\n return requset_url + \"?\" + urlencode(values)\n\n\ndef XFyunApi(app_id, api_key, secret_key, file_path=None, file_data=None):\n \"\"\"\n :param app_id:\n :param api_key:\n :param secret_key:\n :param file_path:\n :param file_data:\n :return:\n \"\"\"\n APPId = app_id # 控制台获取\n APISecret = secret_key # 控制台获取\n APIKey = api_key # 控制台获取\n imageBytes = None\n if file_path:\n with open(file_path, \"rb\") as f:\n imageBytes = f.read()\n if imageBytes:\n url = 'https://api.xf-yun.com/v1/private/sf8e6aca1'\n body = {\n \"header\": {\n \"app_id\": APPId,\n \"status\": 3\n },\n \"parameter\": {\n \"sf8e6aca1\": {\n \"category\": \"ch_en_public_cloud\",\n \"result\": {\n \"encoding\": \"utf8\",\n \"compress\": \"raw\",\n \"format\": \"json\"\n }\n }\n },\n \"payload\": {\n \"sf8e6aca1_data_1\": {\n \"encoding\": \"jpg\",\n \"image\": str(base64.b64encode(imageBytes), 'UTF-8'),\n \"status\": 3\n }\n }\n }\n request_url = assemble_ws_auth_url(url, \"POST\", APIKey, APISecret)\n\n headers = {'content-type': \"application/json\", 'host': 'api.xf-yun.com', 'app_id': APPId}\n response = requests.post(request_url, data=json.dumps(body), headers=headers)\n tempResult = json.loads(response.content.decode())\n\n finalResult = base64.b64decode(tempResult['payload']['result']['text']).decode()\n finalResult = finalResult.replace(\" \", \"\").replace(\"\\n\", \"\").replace(\"\\t\", \"\").strip()\n text = ''\n for item in eval(finalResult)['pages'][0]['lines'][0]['words']:\n text += item['content']\n return text\n\n\nif __name__ == '__main__':\n app_id = \"eb78ba1a\" # 控制台获取\n secret_key = \"ZmM3Mjc4NjcyNjcyYmJiNGZmNmU5NmNh\" # 控制台获取\n api_key = \"618642319dd26346780f676e9f9dfad9\" # 控制台获取\n text = XFyunApi(app_id, api_key, secret_key, file_path='../resource/ocr_test.png')\n print(text)\n"}}}}