Path: blob/master/Model-4/cloudvisreq.py
427 views
from __future__ import print_function1from base64 import b64encode2from os import makedirs, remove3from os.path import join, basename4from sys import argv5import json6import requests7import glob8910ENDPOINT_URL = 'https://vision.googleapis.com/v1/images:annotate'11RESULTS_DIR = 'jsons'1213def make_image_data_list(image_filenames):14"""15image_filenames is a list of filename strings16Returns a list of dicts formatted as the Vision API17needs them to be18"""19img_requests = []20with open(image_filenames, 'rb') as f:21ctxt = b64encode(f.read()).decode()22img_requests.append({23'image': {'content': ctxt},24'features': [{25'type': 'TEXT_DETECTION',26'maxResults': 127}]28})29return img_requests3031def make_image_data(image_filenames):32"""Returns the image data lists as bytes"""33imgdict = make_image_data_list(image_filenames)34return json.dumps({"requests": imgdict }).encode()353637def request_ocr(api_key, image_filenames):38response = requests.post(ENDPOINT_URL, data=make_image_data(image_filenames), params={'key': api_key}, headers={'Content-Type': 'application/json'})39return response404142if __name__ == '__main__':43api_key = "AIzaSyCSMpzBIKlZObk8Uzkx6Iavo967m7vFf0Q"44file = open("output/words/normal/detection.txt","w")45list = glob.glob("/Users/Piyush_Jena/Documents/Opensoft/spell_correction/test_software/output/words/normal/*.jpg")46for i in range(0,len(list)):47image_filenames = list[i]48if not api_key or not image_filenames:49print("""Please supply an api key, then one or more image filenames $ python cloudvisreq.py image1.jpg image2.png""")50else:51response = request_ocr(api_key, image_filenames)52if response.status_code != 200 or response.json().get('error'):53print(response.text)54else:55for idx, resp in enumerate(response.json()['responses']):56# save to JSON file57imgname = image_filenames[idx]58jpath = join(RESULTS_DIR, basename(imgname) + '.json')59with open(jpath, 'w') as f:60datatxt = json.dumps(resp, indent=2)61print("Wrote", len(datatxt), "bytes to", jpath)62f.write(datatxt)6364# print the plaintext to screen for convenience65print("---------------------------------------------")66t = resp['textAnnotations'][0]67print(" Bounding Polygon:")68print(t['boundingPoly'])69print(" Text:")70print(t['description'])7172file.write(t['description'])73#print("---------------------------------------------")7475#print(" Bounding Polygon:")76#print(t['boundingPoly'])77#print(" Text:")78#print(t['description'])79for file in list:80remove(file)818283