123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- # coding=utf-8
- import sys
- import json
- import requests
- import base64
- # 保证兼容python2以及python3
- IS_PY3 = sys.version_info.major == 3
- if IS_PY3:
- from urllib.request import urlopen
- from urllib.request import Request
- from urllib.error import URLError
- from urllib.parse import urlencode
- from urllib.parse import quote_plus
- else:
- import urllib2
- from urllib import quote_plus
- from urllib2 import urlopen
- from urllib2 import Request
- from urllib2 import URLError
- from urllib import urlencode
- # 防止https证书校验不正确
- import ssl
- ssl._create_default_https_context = ssl._create_unverified_context
- API_KEY = 'ssfyC49bEbp7QdGnG96GKdt2'
- SECRET_KEY = 'YCQtiQVt1GvldNZzyfOpbVtNugj7S1Uw'
- OCR_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
- """ TOKEN start """
- TOKEN_URL = 'https://aip.baidubce.com/oauth/2.0/token'
- """
- 获取token
- """
- def fetch_token():
- params = {'grant_type': 'client_credentials',
- 'client_id': API_KEY,
- 'client_secret': SECRET_KEY}
- post_data = urlencode(params)
- if (IS_PY3):
- post_data = post_data.encode('utf-8')
- req = Request(TOKEN_URL, post_data)
- try:
- f = urlopen(req, timeout=5)
- result_str = f.read()
- except URLError as err:
- print(err)
- if (IS_PY3):
- result_str = result_str.decode()
- result = json.loads(result_str)
- if ('access_token' in result.keys() and 'scope' in result.keys()):
- if not 'brain_all_scope' in result['scope'].split(' '):
- print ('please ensure has check the ability')
- exit()
- return result['access_token']
- else:
- print ('please overwrite the correct API_KEY and SECRET_KEY')
- exit()
- def ocr():
- '''
- 通用文字识别(高精度版)
- '''
- request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
- # 二进制方式打开图片文件
- f = open('20201111181124.png', 'rb')
- img = base64.b64encode(f.read())
- params = {"image":img}
- access_token = '24.f7a57ed7b887ac523c606fa6b09dac88.2592000.1607681571.282335-22744183'
- request_url = request_url + "?access_token=" + access_token
- headers = {'content-type': 'application/x-www-form-urlencoded'}
- response = requests.post(request_url, data=params, headers=headers)
- if response:
- print (response.json())
- if __name__=="__main__":
- # print(fetch_token())
- ocr()
|