-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
beta_snippets.py
412 lines (326 loc) · 15.1 KB
/
beta_snippets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
#!/usr/bin/env python
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Google Cloud Vision API Python Beta Snippets
Example Usage:
python beta_snippets.py -h
python beta_snippets.py object-localization INPUT_IMAGE
python beta_snippets.py object-localization-uri gs://...
python beta_snippets.py handwritten-ocr INPUT_IMAGE
python beta_snippets.py handwritten-ocr-uri gs://...
python beta_snippets.py batch-annotate-files INPUT_PDF
python beta_snippets.py batch-annotate-files-uri gs://...
python beta_snippets.py batch-annotate-images-uri gs://... gs://...
For more information, the documentation at
https://cloud.google.com/vision/docs.
"""
import argparse
import io
# [START vision_localize_objects_beta]
def localize_objects(path):
"""Localize objects in the local image.
Args:
path: The path to the local file.
"""
from google.cloud import vision_v1p3beta1 as vision
client = vision.ImageAnnotatorClient()
with open(path, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
objects = client.object_localization(
image=image).localized_object_annotations
print('Number of objects found: {}'.format(len(objects)))
for object_ in objects:
print('\n{} (confidence: {})'.format(object_.name, object_.score))
print('Normalized bounding polygon vertices: ')
for vertex in object_.bounding_poly.normalized_vertices:
print(' - ({}, {})'.format(vertex.x, vertex.y))
# [END vision_localize_objects_beta]
# [START vision_localize_objects_gcs_beta]
def localize_objects_uri(uri):
"""Localize objects in the image on Google Cloud Storage
Args:
uri: The path to the file in Google Cloud Storage (gs://...)
"""
from google.cloud import vision_v1p3beta1 as vision
client = vision.ImageAnnotatorClient()
image = vision.Image()
image.source.image_uri = uri
objects = client.object_localization(
image=image).localized_object_annotations
print('Number of objects found: {}'.format(len(objects)))
for object_ in objects:
print('\n{} (confidence: {})'.format(object_.name, object_.score))
print('Normalized bounding polygon vertices: ')
for vertex in object_.bounding_poly.normalized_vertices:
print(' - ({}, {})'.format(vertex.x, vertex.y))
# [END vision_localize_objects_gcs_beta]
# [START vision_handwritten_ocr_beta]
def detect_handwritten_ocr(path):
"""Detects handwritten characters in a local image.
Args:
path: The path to the local file.
"""
from google.cloud import vision_v1p3beta1 as vision
client = vision.ImageAnnotatorClient()
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
# Language hint codes for handwritten OCR:
# en-t-i0-handwrit, mul-Latn-t-i0-handwrit
# Note: Use only one language hint code per request for handwritten OCR.
image_context = vision.ImageContext(
language_hints=['en-t-i0-handwrit'])
response = client.document_text_detection(image=image,
image_context=image_context)
print('Full Text: {}'.format(response.full_text_annotation.text))
for page in response.full_text_annotation.pages:
for block in page.blocks:
print('\nBlock confidence: {}\n'.format(block.confidence))
for paragraph in block.paragraphs:
print('Paragraph confidence: {}'.format(
paragraph.confidence))
for word in paragraph.words:
word_text = ''.join([
symbol.text for symbol in word.symbols
])
print('Word text: {} (confidence: {})'.format(
word_text, word.confidence))
for symbol in word.symbols:
print('\tSymbol: {} (confidence: {})'.format(
symbol.text, symbol.confidence))
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message))
# [END vision_handwritten_ocr_beta]
# [START vision_handwritten_ocr_gcs_beta]
def detect_handwritten_ocr_uri(uri):
"""Detects handwritten characters in the file located in Google Cloud
Storage.
Args:
uri: The path to the file in Google Cloud Storage (gs://...)
"""
from google.cloud import vision_v1p3beta1 as vision
client = vision.ImageAnnotatorClient()
image = vision.Image()
image.source.image_uri = uri
# Language hint codes for handwritten OCR:
# en-t-i0-handwrit, mul-Latn-t-i0-handwrit
# Note: Use only one language hint code per request for handwritten OCR.
image_context = vision.ImageContext(
language_hints=['en-t-i0-handwrit'])
response = client.document_text_detection(image=image,
image_context=image_context)
print('Full Text: {}'.format(response.full_text_annotation.text))
for page in response.full_text_annotation.pages:
for block in page.blocks:
print('\nBlock confidence: {}\n'.format(block.confidence))
for paragraph in block.paragraphs:
print('Paragraph confidence: {}'.format(
paragraph.confidence))
for word in paragraph.words:
word_text = ''.join([
symbol.text for symbol in word.symbols
])
print('Word text: {} (confidence: {})'.format(
word_text, word.confidence))
for symbol in word.symbols:
print('\tSymbol: {} (confidence: {})'.format(
symbol.text, symbol.confidence))
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message))
# [END vision_handwritten_ocr_gcs_beta]
# [START vision_batch_annotate_files_beta]
def detect_batch_annotate_files(path):
"""Detects document features in a PDF/TIFF/GIF file.
While your PDF file may have several pages,
this API can process up to 5 pages only.
Args:
path: The path to the local file.
"""
from google.cloud import vision_v1p4beta1 as vision
client = vision.ImageAnnotatorClient()
with open(path, 'rb') as pdf_file:
content = pdf_file.read()
# Other supported mime_types: image/tiff' or 'image/gif'
mime_type = 'application/pdf'
input_config = vision.InputConfig(
content=content, mime_type=mime_type)
feature = vision.Feature(
type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION)
# Annotate the first two pages and the last one (max 5 pages)
# First page starts at 1, and not 0. Last page is -1.
pages = [1, 2, -1]
request = vision.AnnotateFileRequest(
input_config=input_config,
features=[feature],
pages=pages)
response = client.batch_annotate_files(requests=[request])
for image_response in response.responses[0].responses:
for page in image_response.full_text_annotation.pages:
for block in page.blocks:
print(u'\nBlock confidence: {}\n'.format(block.confidence))
for par in block.paragraphs:
print(u'\tParagraph confidence: {}'.format(par.confidence))
for word in par.words:
symbol_texts = [symbol.text for symbol in word.symbols]
word_text = ''.join(symbol_texts)
print(u'\t\tWord text: {} (confidence: {})'.format(
word_text, word.confidence))
for symbol in word.symbols:
print(u'\t\t\tSymbol: {} (confidence: {})'.format(
symbol.text, symbol.confidence))
# [END vision_batch_annotate_files_beta]
# [START vision_batch_annotate_files_gcs_beta]
def detect_batch_annotate_files_uri(gcs_uri):
"""Detects document features in a PDF/TIFF/GIF file.
While your PDF file may have several pages,
this API can process up to 5 pages only.
Args:
uri: The path to the file in Google Cloud Storage (gs://...)
"""
from google.cloud import vision_v1p4beta1 as vision
client = vision.ImageAnnotatorClient()
# Other supported mime_types: image/tiff' or 'image/gif'
mime_type = 'application/pdf'
input_config = vision.InputConfig(
gcs_source=vision.GcsSource(uri=gcs_uri), mime_type=mime_type)
feature = vision.Feature(
type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION)
# Annotate the first two pages and the last one (max 5 pages)
# First page starts at 1, and not 0. Last page is -1.
pages = [1, 2, -1]
request = vision.AnnotateFileRequest(
input_config=input_config,
features=[feature],
pages=pages)
response = client.batch_annotate_files(requests=[request])
for image_response in response.responses[0].responses:
for page in image_response.full_text_annotation.pages:
for block in page.blocks:
print(u'\nBlock confidence: {}\n'.format(block.confidence))
for par in block.paragraphs:
print(u'\tParagraph confidence: {}'.format(par.confidence))
for word in par.words:
symbol_texts = [symbol.text for symbol in word.symbols]
word_text = ''.join(symbol_texts)
print(u'\t\tWord text: {} (confidence: {})'.format(
word_text, word.confidence))
for symbol in word.symbols:
print(u'\t\t\tSymbol: {} (confidence: {})'.format(
symbol.text, symbol.confidence))
# [END vision_batch_annotate_files_gcs_beta]
# [START vision_async_batch_annotate_images_beta]
def async_batch_annotate_images_uri(input_image_uri, output_uri):
"""Batch annotation of images on Google Cloud Storage asynchronously.
Args:
input_image_uri: The path to the image in Google Cloud Storage (gs://...)
output_uri: The path to the output path in Google Cloud Storage (gs://...)
"""
import re
from google.cloud import storage
from google.cloud import vision_v1p4beta1 as vision
client = vision.ImageAnnotatorClient()
# Construct the request for the image(s) to be annotated:
image_source = vision.ImageSource(image_uri=input_image_uri)
image = vision.Image(source=image_source)
features = [
vision.Feature(type_=vision.Feature.Type.LABEL_DETECTION),
vision.Feature(type_=vision.Feature.Type.TEXT_DETECTION),
vision.Feature(type_=vision.Feature.Type.IMAGE_PROPERTIES),
]
requests = [
vision.AnnotateImageRequest(image=image, features=features),
]
gcs_destination = vision.GcsDestination(uri=output_uri)
output_config = vision.OutputConfig(
gcs_destination=gcs_destination, batch_size=2)
operation = client.async_batch_annotate_images(
requests=requests, output_config=output_config)
print('Waiting for the operation to finish.')
operation.result(timeout=10000)
# Once the request has completed and the output has been
# written to Google Cloud Storage, we can list all the output files.
storage_client = storage.Client()
match = re.match(r'gs://([^/]+)/(.+)', output_uri)
bucket_name = match.group(1)
prefix = match.group(2)
bucket = storage_client.get_bucket(bucket_name)
# Lists objects with the given prefix.
blob_list = list(bucket.list_blobs(prefix=prefix))
print('Output files:')
for blob in blob_list:
print(blob.name)
# Processes the first output file from Google Cloud Storage.
# Since we specified batch_size=2, the first response contains
# annotations for the first two annotate image requests.
output = blob_list[0]
json_string = output.download_as_string()
response = vision.BatchAnnotateImagesResponse.from_json(json_string)
# Prints the actual response for the first annotate image request.
print(u'The annotation response for the first request: {}'.format(
response.responses[0]))
# [END vision_async_batch_annotate_images_beta]
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
subparsers = parser.add_subparsers(dest='command')
object_parser = subparsers.add_parser(
'object-localization', help=localize_objects.__doc__)
object_parser.add_argument('path')
object_uri_parser = subparsers.add_parser(
'object-localization-uri', help=localize_objects_uri.__doc__)
object_uri_parser.add_argument('uri')
handwritten_parser = subparsers.add_parser(
'handwritten-ocr', help=detect_handwritten_ocr.__doc__)
handwritten_parser.add_argument('path')
handwritten_uri_parser = subparsers.add_parser(
'handwritten-ocr-uri', help=detect_handwritten_ocr_uri.__doc__)
handwritten_uri_parser.add_argument('uri')
batch_annotate_parser = subparsers.add_parser(
'batch-annotate-files', help=detect_batch_annotate_files.__doc__)
batch_annotate_parser.add_argument('path')
batch_annotate_uri_parser = subparsers.add_parser(
'batch-annotate-files-uri',
help=detect_batch_annotate_files_uri.__doc__)
batch_annotate_uri_parser.add_argument('uri')
batch_annotate__image_uri_parser = subparsers.add_parser(
'batch-annotate-images-uri',
help=async_batch_annotate_images_uri.__doc__)
batch_annotate__image_uri_parser.add_argument('uri')
batch_annotate__image_uri_parser.add_argument('output')
args = parser.parse_args()
if 'uri' in args.command:
if 'object-localization-uri' in args.command:
localize_objects_uri(args.uri)
elif 'handwritten-ocr-uri' in args.command:
detect_handwritten_ocr_uri(args.uri)
elif 'batch-annotate-files-uri' in args.command:
detect_batch_annotate_files_uri(args.uri)
elif 'batch-annotate-images-uri' in args.command:
async_batch_annotate_images_uri(args.uri, args.output)
else:
if 'object-localization' in args.command:
localize_objects(args.path)
elif 'handwritten-ocr' in args.command:
detect_handwritten_ocr(args.path)
elif 'batch-annotate-files' in args.command:
detect_batch_annotate_files(args.path)