Path: blob/master/Model-3/Project/GCVocr.py
427 views
from __future__ import print_function1from base64 import b64encode2from os import makedirs3from os.path import join, basename4from sys import argv5import json6import requests78class GoogleCloudVisionOCR(object):9def __init__(self, filename):10self.ENDPOINT_URL = "https://vision.googleapis.com/v1/images:annotate"11self.RESULTS_DIR = 'jsons'12self.api_key = "AIzaSyCSMpzBIKlZObk8Uzkx6Iavo967m7vFf0Q"13self.filename = filename1415def make_image_data_list():16"""17image_filename is the filename string18Returns a list of dicts formatted as the Vision API needs them to be19"""20img_requests = []21with open(self.filename, 'rb') as f:22ctxt = b64encode(f.read()).decode()23img_requests.append({'image': {'content': ctxt},'features': [{'type': 'TEXT_DETECTION','maxResults': 1}]})24return img_requests2526def make_image_data():27"""Returns the image data lists as bytes"""28imgdict = make_image_data_list(self.filename)29return json.dumps({"requests": imgdict }).encode()303132def request_ocr():33response = requests.post(ENDPOINT_URL, data=make_image_data(self.filename), params={'key': self.api_key}, headers={'Content-Type': 'application/json'})34return response353637