|
| 1 | +# Copyright 2018, Google, LLC. |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# |
| 6 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +# |
| 8 | +# Unless required by applicable law or agreed to in writing, software |
| 9 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +# See the License for the specific language governing permissions and |
| 12 | +# limitations under the License. |
| 13 | + |
| 14 | +# [START functions_ocr_setup] |
| 15 | +import base64 |
| 16 | +import json |
| 17 | +import os |
| 18 | + |
| 19 | +from google.cloud import pubsub_v1 |
| 20 | +from google.cloud import storage |
| 21 | +from google.cloud import translate |
| 22 | +from google.cloud import vision |
| 23 | + |
| 24 | +vision_client = vision.ImageAnnotatorClient() |
| 25 | +translate_client = translate.Client() |
| 26 | +publisher = pubsub_v1.PublisherClient() |
| 27 | +storage_client = storage.Client() |
| 28 | + |
| 29 | +project_id = os.environ['GCLOUD_PROJECT'] |
| 30 | + |
| 31 | +with open('config.json') as f: |
| 32 | + data = f.read() |
| 33 | +config = json.loads(data) |
| 34 | +# [END functions_ocr_setup] |
| 35 | + |
| 36 | + |
| 37 | +# [START functions_ocr_detect] |
| 38 | +def detect_text(bucket, filename): |
| 39 | + print('Looking for text in image {}'.format(filename)) |
| 40 | + |
| 41 | + futures = [] |
| 42 | + |
| 43 | + text_detection_response = vision_client.text_detection({ |
| 44 | + 'source': {'image_uri': 'gs://{}/{}'.format(bucket, filename)} |
| 45 | + }) |
| 46 | + annotations = text_detection_response.text_annotations |
| 47 | + if len(annotations) > 0: |
| 48 | + text = annotations[0].description |
| 49 | + else: |
| 50 | + text = '' |
| 51 | + print('Extracted text {} from image ({} chars).'.format(text, len(text))) |
| 52 | + |
| 53 | + detect_language_response = translate_client.detect_language(text) |
| 54 | + src_lang = detect_language_response['language'] |
| 55 | + print('Detected language {} for text {}.'.format(src_lang, text)) |
| 56 | + |
| 57 | + # Submit a message to the bus for each target language |
| 58 | + for target_lang in config.get('TO_LANG', []): |
| 59 | + topic_name = config['TRANSLATE_TOPIC'] |
| 60 | + if src_lang == target_lang: |
| 61 | + topic_name = config['RESULT_TOPIC'] |
| 62 | + message = { |
| 63 | + 'text': text, |
| 64 | + 'filename': filename, |
| 65 | + 'target_lang': target_lang, |
| 66 | + 'src_lang': src_lang |
| 67 | + } |
| 68 | + message_data = json.dumps(message).encode('utf-8') |
| 69 | + topic_path = publisher.topic_path(project_id, topic_name) |
| 70 | + future = publisher.publish(topic_path, data=message_data) |
| 71 | + futures.append(future) |
| 72 | + for future in futures: |
| 73 | + future.result() |
| 74 | +# [END functions_ocr_detect] |
| 75 | + |
| 76 | + |
| 77 | +# [START message_validatation_helper] |
| 78 | +def validate_message(message, param): |
| 79 | + var = message.get(param) |
| 80 | + if not var: |
| 81 | + raise ValueError('{} is not provided. Make sure you have \ |
| 82 | + property {} in the request'.format(param, param)) |
| 83 | + return var |
| 84 | +# [END message_validatation_helper] |
| 85 | + |
| 86 | + |
| 87 | +# [START functions_ocr_process] |
| 88 | +def process_image(file, context): |
| 89 | + """Cloud Function triggered by Cloud Storage when a file is changed. |
| 90 | + Args: |
| 91 | + file (dict): Metadata of the changed file, provided by the triggering |
| 92 | + Cloud Storage event. |
| 93 | + context (google.cloud.functions.Context): Metadata of triggering event. |
| 94 | + Returns: |
| 95 | + None; the output is written to stdout and Stackdriver Logging |
| 96 | + """ |
| 97 | + bucket = validate_message(file, 'bucket') |
| 98 | + name = validate_message(file, 'name') |
| 99 | + |
| 100 | + detect_text(bucket, name) |
| 101 | + |
| 102 | + print('File {} processed.'.format(file['name'])) |
| 103 | +# [END functions_ocr_process] |
| 104 | + |
| 105 | + |
| 106 | +# [START functions_ocr_translate] |
| 107 | +def translate_text(event, context): |
| 108 | + if event.get('data'): |
| 109 | + message_data = base64.b64decode(event['data']).decode('utf-8') |
| 110 | + message = json.loads(message_data) |
| 111 | + else: |
| 112 | + raise ValueError('Data sector is missing in the Pub/Sub message.') |
| 113 | + |
| 114 | + text = validate_message(message, 'text') |
| 115 | + filename = validate_message(message, 'filename') |
| 116 | + target_lang = validate_message(message, 'target_lang') |
| 117 | + src_lang = validate_message(message, 'src_lang') |
| 118 | + |
| 119 | + print('Translating text into {}.'.format(target_lang)) |
| 120 | + translated_text = translate_client.translate(text, |
| 121 | + target_language=target_lang, |
| 122 | + source_language=src_lang) |
| 123 | + topic_name = config['RESULT_TOPIC'] |
| 124 | + message = { |
| 125 | + 'text': translated_text['translatedText'], |
| 126 | + 'filename': filename, |
| 127 | + 'lang': target_lang, |
| 128 | + } |
| 129 | + message_data = json.dumps(message).encode('utf-8') |
| 130 | + topic_path = publisher.topic_path(project_id, topic_name) |
| 131 | + future = publisher.publish(topic_path, data=message_data) |
| 132 | + future.result() |
| 133 | +# [END functions_ocr_translate] |
| 134 | + |
| 135 | + |
| 136 | +# [START functions_ocr_save] |
| 137 | +def save_result(event, context): |
| 138 | + if event.get('data'): |
| 139 | + message_data = base64.b64decode(event['data']).decode('utf-8') |
| 140 | + message = json.loads(message_data) |
| 141 | + else: |
| 142 | + raise ValueError('Data sector is missing in the Pub/Sub message.') |
| 143 | + |
| 144 | + text = validate_message(message, 'text') |
| 145 | + filename = validate_message(message, 'filename') |
| 146 | + lang = validate_message(message, 'lang') |
| 147 | + |
| 148 | + print('Received request to save file {}.'.format(filename)) |
| 149 | + |
| 150 | + bucket_name = config['RESULT_BUCKET'] |
| 151 | + result_filename = '{}_{}.txt'.format(filename, lang) |
| 152 | + bucket = storage_client.get_bucket(bucket_name) |
| 153 | + blob = bucket.blob(result_filename) |
| 154 | + |
| 155 | + print('Saving result to {} in bucket {}.'.format(result_filename, |
| 156 | + bucket_name)) |
| 157 | + |
| 158 | + blob.upload_from_string(text) |
| 159 | + |
| 160 | + print('File saved.') |
| 161 | +# [END functions_ocr_save] |
0 commit comments