Skip to content

Instantly share code, notes, and snippets.

@BharatKalluri
Last active October 20, 2020 19:08
Show Gist options
  • Save BharatKalluri/558d4a32643ccec90579c2e0ed5c979c to your computer and use it in GitHub Desktop.
Save BharatKalluri/558d4a32643ccec90579c2e0ed5c979c to your computer and use it in GitHub Desktop.
OCR documents from local file system using google vision
#!/usr/bin/env python
import argparse
def detect_text(path):
"""Detects text in the file."""
from google.cloud import vision
import io
client = vision.ImageAnnotatorClient()
# [START vision_python_migration_text_detection]
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
response = client.text_detection(image=image)
texts = response.text_annotations
complete_text = texts[0]
print(complete_text.description)
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message))
def run_local(args):
if args.command == 'text':
detect_text(args.path)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
subparsers = parser.add_subparsers(dest='command')
detect_text_parser = subparsers.add_parser(
'text', help=detect_text.__doc__)
detect_text_parser.add_argument('path')
args = parser.parse_args()
run_local(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment