Advertisement
Guest User

Untitled

a guest
Jun 27th, 2016
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.11 KB | None | 0 0
  1. import base64
  2. import os
  3. import re
  4. import sys
  5.  
  6. from googleapiclient import discovery
  7. from googleapiclient import errors
  8. import nltk
  9. from nltk.stem.snowball import EnglishStemmer
  10. from oauth2client.client import GoogleCredentials
  11. import redis
  12.  
  13. DISCOVERY_URL = 'https://{api}.googleapis.com/$discovery/rest?version={apiVersion}' # noqa
  14. BATCH_SIZE = 10
  15.  
  16.  
  17. class VisionApi:
  18. """Construct and use the Google Vision API service."""
  19.  
  20. def __init__(self, api_discovery_file='/home/saadq/Dev/Projects/TM-visual-search/credentials-key.json'):
  21. self.credentials = GoogleCredentials.get_application_default()
  22. print self.credentials.to_json()
  23. self.service = discovery.build(
  24. 'vision', 'v1', credentials=self.credentials,
  25. discoveryServiceUrl=DISCOVERY_URL)
  26. print DISCOVERY_URL
  27.  
  28. def detect_text(self, input_filenames, num_retries=3, max_results=6):
  29. """Uses the Vision API to detect text in the given file.
  30. """
  31. images = {}
  32. for filename in input_filenames:
  33. with open(filename, 'rb') as image_file:
  34. images[filename] = image_file.read()
  35.  
  36. batch_request = []
  37. for filename in images:
  38. batch_request.append({
  39. 'image': {
  40. 'content': base64.b64encode(
  41. images[filename]).decode('UTF-8')
  42. },
  43. 'features': [{
  44. 'type': 'TEXT_DETECTION',
  45. 'maxResults': max_results,
  46. }]
  47. })
  48. request = self.service.images().annotate(
  49. body={'requests': batch_request})
  50.  
  51. try:
  52. responses = request.execute(num_retries=num_retries)
  53. if 'responses' not in responses:
  54. return {}
  55. text_response = {}
  56. for filename, response in zip(images, responses['responses']):
  57. if 'error' in response:
  58. print("API Error for %s: %s" % (
  59. filename,
  60. response['error']['message']
  61. if 'message' in response['error']
  62. else ''))
  63. continue
  64. if 'textAnnotations' in response:
  65. text_response[filename] = response['textAnnotations']
  66. else:
  67. text_response[filename] = []
  68. return text_response
  69. except errors.HttpError as e:
  70. print("Http Error for %s: %s" % (filename, e))
  71. except KeyError as e2:
  72. print("Key error: %s" % e2)
  73.  
  74.  
  75.  
  76. vision = VisionApi()
  77. print vision.detect_text(['test_article.png'])
  78.  
  79. Http Error for test_article.png: <HttpError 403 when requesting https://vision.googleapis.com/v1/images:annotate?alt=json returned "Google Cloud Vision API has not been used in project google.com:cloudsdktool before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/vision.googleapis.com/overview?project=google.com:cloudsdktool then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.">
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement