pyAutoGUIおよびpyTesseractによる画面自動OCRサンプルコードの備忘録
元ネタは
世界一やさしいPython RPA自動化ツール開発のはじめ方: 最短1日でマスターできる業務自動化ツール完全攻略ガイド
にあるコード。読み出しとDEEPLとの複合処理により自動翻訳が可能だったらしい。
DEEPL側の不正防止処理のために動かなかった為、読み出し専用にコード変更。
備忘録として保存用に以下に書き留める。
import pyautogui as ag
import time
import pytesseract
import pyperclip
import numpy
#
pos_kindle = {'x': 857,'y': 957}
pos_deepl_clearbtn = {'x': 1417,'y': 137}
pos_deepl_copybtn = {'x': 1873,'y': 140}
pos_ocr_topleft = {'x': 80,'y': 240}
pos_ocr_btmright = {'x': 860,'y': 900}
#
page_total = 245
#
ocr_area_width = pos_ocr_btmright['x'] - pos_ocr_topleft['x']
ocr_area_height= pos_ocr_btmright['y'] - pos_ocr_topleft['y']
#
text =[]
filename ='bookname.txt'
# If you don't have tesseract executable in your PATH, include the following:
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract'
#loop
for i in range(page_total):
img = ag.screenshot(region=(pos_ocr_topleft['x'],pos_ocr_topleft['y'],ocr_area_width,ocr_area_height))
img_gray = img.convert('L')
img_ocr = numpy.array(img_gray)
#result = pytesseract.image_to_string(img_ocr,lang='jpn')
result = pytesseract.image_to_string(img_ocr)
pyperclip.copy(result)
#ag.click(pos_deepl_clearbtn['x'],pos_deepl_clearbtn['y'],clicks=1)
#ag.hotkey('ctrl','v')
time.sleep(4)
#ag.click(pos_deepl_copybtn['x'],pos_deepl_copybtn['y'],clicks=1)
text.append(pyperclip.paste())
ag.click(pos_kindle['x'],pos_kindle['y'],clicks=1)
ag.hotkey('pagedown')
time.sleep(1)
try:
#
with open(filename, mode='x',encoding="utf-8") as f:
f.writelines(text)
except FileExistsError:
ag.alert(text='file Exist')
print("Read End")
#pyperclip paste error
コメント
コメントを投稿