Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Aniket025
GitHub Repository: Aniket025/Medical-Prescription-OCR
Path: blob/master/Model-3/cloudvisreq.py
427 views
1
from __future__ import print_function
2
from base64 import b64encode
3
from os import makedirs
4
from os.path import join, basename
5
from sys import argv
6
import json
7
import requests
8
9
10
ENDPOINT_URL = 'https://vision.googleapis.com/v1/images:annotate'
11
RESULTS_DIR = 'jsons'
12
13
def make_image_data_list(image_filenames):
14
"""
15
image_filenames is a list of filename strings
16
Returns a list of dicts formatted as the Vision API
17
needs them to be
18
"""
19
img_requests = []
20
with open(image_filenames, 'rb') as f:
21
ctxt = b64encode(f.read()).decode()
22
img_requests.append({
23
'image': {'content': ctxt},
24
'features': [{
25
'type': 'TEXT_DETECTION',
26
'maxResults': 1
27
}]
28
})
29
return img_requests
30
31
def make_image_data(image_filenames):
32
"""Returns the image data lists as bytes"""
33
imgdict = make_image_data_list(image_filenames)
34
return json.dumps({"requests": imgdict }).encode()
35
36
37
def request_ocr(api_key, image_filenames):
38
response = requests.post(ENDPOINT_URL, data=make_image_data(image_filenames), params={'key': api_key}, headers={'Content-Type': 'application/json'})
39
return response
40
41
42
if __name__ == '__main__':
43
api_key = "AIzaSyCSMpzBIKlZObk8Uzkx6Iavo967m7vFf0Q"
44
image_filenames = "test/1.jpg"
45
if not api_key or not image_filenames:
46
print("""Please supply an api key, then one or more image filenames $ python cloudvisreq.py image1.jpg image2.png""")
47
else:
48
response = request_ocr(api_key, image_filenames)
49
if response.status_code != 200 or response.json().get('error'):
50
print(response.text)
51
else:
52
for idx, resp in enumerate(response.json()['responses']):
53
# save to JSON file
54
imgname = image_filenames[idx]
55
jpath = join(RESULTS_DIR, basename(imgname) + '.json')
56
with open(jpath, 'w') as f:
57
datatxt = json.dumps(resp, indent=2)
58
print("Wrote", len(datatxt), "bytes to", jpath)
59
f.write(datatxt)
60
61
# print the plaintext to screen for convenience
62
print("---------------------------------------------")
63
t = resp['textAnnotations'][0]
64
print(" Bounding Polygon:")
65
print(t['boundingPoly'])
66
print(" Text:")
67
print(t['description'])
68
69