Python-使用百度文字识别API实现的文字识别工具

 1 import requests
 2 import base64
 3 import keyboard
 4 import mouse
 5 import time
 6 import os
 7 from PIL import ImageGrab
 8 
 9 TEMP_FILE_PATH = r'shortcut/temp.txt'
10 if not os.path.exists('shortcut'):
11     os.mkdir('shortcut')
12 if keyboard.wait(hotkey='ctrl+1') == None:
13     if mouse.wait(button='left', target_types=('double')) == None:
14         time.sleep(0.1)
15         im = ImageGrab.grabclipboard()
16         im.save('shortcut/temp.png')
17 
18 
19 # If the access_token is expired, the following code need to be implemented.
20 # --------------------------------------------------------------------------
21 # at_url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s'
22 # ak = 'api_key'
23 # sk = 'secret_key'
24 # result = requests.get(at_url%(ak, sk))
25 # at = result.json()['access_token']
26 # --------------------------------------------------------------------------
27 
28 
29 with open(r'shortcut/temp.png', 'rb') as f:
30     imgcontent = f.read()
31 post_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=%s"
32 at = "your access_token"
33 headers = {'Content-Type': 'application/x-www-form-urlencoded'}
34 data = {
35     'image': base64.b64encode(imgcontent),
36     # 'paragraph': 'true',
37 }
38 result =requests.post(post_url%at, headers=headers, data=data)
39 result_dict = result.json()
40 content = "\n".join([i['words'].strip() for i in result_dict['words_result']])
41 with open(TEMP_FILE_PATH, 'w') as f:
42     f.write(content)
43 import subprocess
44 os.popen("notepad %s" % os.path.abspath(TEMP_FILE_PATH))
45 print("S.U.C.C.E.S.S")

使用的截图工具为360软件小助手自带的截图功能,开始截图快捷键设置为 ctrl+1 ,双击鼠标左键完成截图

键盘鼠标事件捕获实现的参考地址:https://www.sohu.com/a/274979945_216476

posted on 2020-05-31 12:06  Colliventy  阅读(423)  评论(0编辑  收藏  举报