How to use ocrEngine method in fMBT

Best Python code snippet using fMBT_python

ocr.py

Source:ocr.py Github

copy

Full Screen

1import requests2from io import BytesIO3import base644import hashlib5import time6import json7from .errors import *8class OCREngine(object):9 def ocr(self, img):10 pass11class OCRBox(object):12 def __init__(self, x, y, w, h):13 self.__x = x14 self.__y = y15 self.__w = w16 self.__h = h17 @property18 def left(self):19 return self.__x20 @property21 def right(self):22 return self.__x + self.__w23 @property24 def top(self):25 return self.__y26 @property27 def bottom(self):28 return self.__y + self.__h29 @property30 def width(self):31 return self.__w32 @property33 def height(self):34 return self.__h35 def __repr__(self):36 return 'OCRBox(%d,%d,%d,%d)' % (self.__x, self.__y, self.__w, self.__h)37class OCRWord(OCRBox):38 def __init__(self, location, word, chars):39 self.__word = word40 self.__chars = chars41 super().__init__(location.left, location.top, location.width, location.height)42 @property43 def word(self):44 return self.__word45 @property46 def chars(self):47 return self.__chars48 def __len__(self):49 return len(self.word)50 def __getitem__(self, key):51 boxes = self.chars[key]52 left = min([it.left for it in boxes])53 right = max([it.right for it in boxes])54 top = min([it.top for it in boxes])55 bottom = max([it.bottom for it in boxes])56 return OCRWord(OCRBox(left, top, right - left, bottom - top), self.word[key], boxes)57 def __repr__(self):58 return 'OCRWord(%s,%s,%s)' % (super().__repr__(), self.__word.__repr__(), self.chars.__repr__())59class BaiduOCREngine(OCREngine):60 def __init__(self, token, accurate=False):61 self.__token = token62 self.__url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/' + ('accurate' if accurate else 'general')63 self.__headers = {'Content-Type': 'application/x-www-form-urlencoded'}64 self.__params = {'access_token': token}65 self.__body = {'recognize_granularity': 'small'}66 @staticmethod67 def __loc2box(loc):68 return OCRBox(loc['left'], loc['top'], loc['width'], loc['height'])69 def ocr(self, img):70 byte = BytesIO()71 img.save(byte, format='png')72 encoded = base64.b64encode(byte.getvalue()).decode()73 self.__body['image'] = encoded74 response = requests.post(url=self.__url, params=self.__params, headers=self.__headers, data=self.__body).json()75 if 'code' in response:76 raise BaiduOCRError(code=response['code'], message=response['message'])77 results = response['words_result']78 words = [79 OCRWord(80 self.__loc2box(word['location']),81 ''.join([c['char'] for c in word['chars']]),82 [self.__loc2box(c['location']) for c in word['chars']]83 ) for word in results84 ]85 return words86class SogouOCREngine(OCREngine):87 def __init__(self, pid, key):88 self.__pid = pid89 self.__key = key90 self.__service = 'basicOpenOcr'91 self.__url = 'http://deepi.sogou.com/api/sogouService'92 self.__headers = {'content-type': "application/x-www-form-urlencoded", 'accept': "application/json"}93 self.__params = {'pid': pid, 'key': key, 'service': self.__service}94 self.__body = {}95 @staticmethod96 def __frame2box(frame):97 x0, y0 = map(int, frame[0].split(','))98 x1, y1 = map(int, frame[1].split(','))99 x2, y2 = map(int, frame[2].split(','))100 x3, y3 = map(int, frame[3].split(','))101 left = min(x0, x1, x2, x3)102 right = max(x0, x1, x2, x3)103 top = min(y0, y1, y2, y3)104 bottom = max(y0, y1, y2, y3)105 return OCRBox(left, top, right - left, bottom - top)106 @staticmethod107 def __split(box, n):108 det = box.width / n109 return [OCRBox(round(box.left + det * c), box.top, round(det), box.height) for c in range(n)]110 def ocr(self, img):111 byte = BytesIO()112 img.save(byte, format='png')113 encoded = base64.b64encode(byte.getvalue()).decode()114 self.__body['image'] = encoded115 salt = str(time.time_ns())116 sign = self.__md5(self.__pid + self.__service + salt + encoded[:1024] + self.__key)117 self.__params['salt'] = salt118 self.__params['sign'] = sign119 response = requests.post(url=self.__url, params=self.__params, headers=self.__headers, data=self.__body).json()120 if 'code' in response:121 raise SogouOCRError(code=response['code'], message=response['message'])122 if 'err_code' in response:123 raise SogouOCRError(code=response['err_code'], message=response['err_msg'])124 results = response['result']125 words = [126 OCRWord(127 self.__frame2box(word['frame']),128 word['content'].strip(),129 self.__split(self.__frame2box(word['frame']), len(word['content'].strip()))130 ) for word in results131 ]132 return words133 @staticmethod134 def __md5(s):135 return hashlib.md5(s.encode('utf8')).hexdigest()136class AliOCREngine(OCREngine):137 def __init__(self, appcode):138 self.__appcode = appcode139 self.__url = 'https://ocrapi-advanced.taobao.com/ocrservice/advanced'140 self.__headers = {'content-type': 'application/json', 'Authorization': 'APPCODE ' + appcode}141 self.__body = {'charInfo': True}142 @staticmethod143 def __pos2box(pos):144 left = pos[0]['x']145 top = pos[0]['y']146 right = pos[2]['x']147 bottom = pos[2]['y']148 return OCRBox(left, top, right - left, bottom - top)149 @staticmethod150 def __char2box(char):151 return OCRBox(char['x'], char['y'], char['w'], char['h'])152 def ocr(self, img):153 byte = BytesIO()154 img.save(byte, format='png')155 encoded = base64.b64encode(byte.getvalue()).decode()156 self.__body['img'] = encoded157 response = requests.post(url=self.__url, headers=self.__headers, data=json.dumps(self.__body)).json()158 if 'error_code' in response:159 raise AliOCRError(code=response['error_code'], message=response['error_msg'])160 results = response['prism_wordsInfo']161 words = [162 OCRWord(163 self.__pos2box(word['pos']),164 ''.join([c['word'] for c in word['charInfo']]),165 [self.__char2box(c) for c in word['charInfo']]166 ) for word in results167 ]...

Full Screen

Full Screen

ocrdiffer.py

Source:ocrdiffer.py Github

copy

Full Screen

1from .ocr import *2from .match import match_box3from .diff import diff_words4from .draw import highlight5from .split import split_word6from io import BytesIO7from PIL import Image8import base649class OCRDiffer(object):10 def __init__(self, engine='baidu', *args, **kwargs):11 if engine == 'baidu':12 self.__engine = BaiduOCREngine(*args, **kwargs)13 elif engine == 'sogou':14 self.__engine = SogouOCREngine(*args, **kwargs)15 elif engine == 'ali':16 self.__engine = AliOCREngine(*args, **kwargs)17 else:18 raise OCREngineUnknownError()19 def work(self, img1, img2):20 img2.resize(img1.size)21 ocr1 = self.__engine.ocr(img1)22 ocr2 = self.__engine.ocr(img2)23 ocr1 = split_word(ocr1)24 ocr2 = split_word(ocr2)25 mat, unmat1, unmat2 = match_box(ocr1, ocr2)26 diff1, diff2 = diff_words(mat)27 out = highlight(img1, img2, ocr1, ocr2, diff1 + unmat1, diff2 + unmat2)28 return out29 def work_http(self, img1, img2):30 dec1 = base64.b64decode(img1)31 dec2 = base64.b64decode(img2)32 img1 = Image.open(BytesIO(dec1))33 img2 = Image.open(BytesIO(dec2))...

Full Screen

Full Screen

letssee.py

Source:letssee.py Github

copy

Full Screen

1from asprise_ocr_api import *2Ocr.set_up()3ocrEngine=Ocr()4ocrEngine.start_engine("eng")5s=ocrEngine.recognize("XAO.png",-1,-1,-1,-1,-1,OCR_RECOGNIZE_TYPE_ALL,OCR_OUTPUT_FORMAT_PLAINTEXT)6print("Result ->"+s)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fMBT automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful