|
| 1 | +# Copyright 2019 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +# [START translate_hybrid_imports] |
| 17 | +import io |
| 18 | +import os |
| 19 | +import html |
| 20 | + |
| 21 | +# Imports the Google Cloud client libraries |
| 22 | +from google.api_core.exceptions import AlreadyExists |
| 23 | +from google.cloud import translate_v3beta1 as translate |
| 24 | +from google.cloud import vision |
| 25 | +from google.cloud import texttospeech |
| 26 | +# [END translate_hybrid_imports] |
| 27 | + |
| 28 | + |
| 29 | +# [START translate_hybrid_project_id] |
| 30 | +# extract GCP project id |
| 31 | +PROJECT_ID = os.environ['GCLOUD_PROJECT'] |
| 32 | +# [END translate_hybrid_project_id] |
| 33 | + |
| 34 | + |
| 35 | +# [START translate_hybrid_vision] |
| 36 | +def pic_to_text(infile): |
| 37 | + """Detects text in an image file |
| 38 | +
|
| 39 | + ARGS |
| 40 | + infile: path to image file |
| 41 | +
|
| 42 | + RETURNS |
| 43 | + String of text detected in image |
| 44 | + """ |
| 45 | + |
| 46 | + # Instantiates a client |
| 47 | + client = vision.ImageAnnotatorClient() |
| 48 | + |
| 49 | + # Opens the input image file |
| 50 | + with io.open(infile, 'rb') as image_file: |
| 51 | + content = image_file.read() |
| 52 | + |
| 53 | + image = vision.types.Image(content=content) |
| 54 | + |
| 55 | + # For dense text, use document_text_detection |
| 56 | + # For less dense text, use text_detection |
| 57 | + response = client.document_text_detection(image=image) |
| 58 | + text = response.full_text_annotation.text |
| 59 | + |
| 60 | + return text |
| 61 | + # [END translate_hybrid_vision] |
| 62 | + |
| 63 | + |
| 64 | +# [START translate_hybrid_create_glossary] |
| 65 | +def create_glossary(languages, project_id, glossary_name, glossary_uri): |
| 66 | + """Creates a GCP glossary resource |
| 67 | + Assumes you've already manually uploaded a glossary to Cloud Storage |
| 68 | +
|
| 69 | + ARGS |
| 70 | + languages: list of languages in the glossary |
| 71 | + project_id: GCP project id |
| 72 | + glossary_name: name you want to give this glossary resource |
| 73 | + glossary_uri: the uri of the glossary you uploaded to Cloud Storage |
| 74 | +
|
| 75 | + RETURNS |
| 76 | + nothing |
| 77 | + """ |
| 78 | + |
| 79 | + # Instantiates a client |
| 80 | + client = translate.TranslationServiceClient() |
| 81 | + |
| 82 | + # Designates the data center location that you want to use |
| 83 | + location = 'us-central1' |
| 84 | + |
| 85 | + # Set glossary resource name |
| 86 | + name = client.glossary_path( |
| 87 | + project_id, |
| 88 | + location, |
| 89 | + glossary_name) |
| 90 | + |
| 91 | + # Set language codes |
| 92 | + language_codes_set = translate.types.Glossary.LanguageCodesSet( |
| 93 | + language_codes=languages) |
| 94 | + |
| 95 | + gcs_source = translate.types.GcsSource( |
| 96 | + input_uri=glossary_uri) |
| 97 | + |
| 98 | + input_config = translate.types.GlossaryInputConfig( |
| 99 | + gcs_source=gcs_source) |
| 100 | + |
| 101 | + # Set glossary resource information |
| 102 | + glossary = translate.types.Glossary( |
| 103 | + name=name, |
| 104 | + language_codes_set=language_codes_set, |
| 105 | + input_config=input_config) |
| 106 | + |
| 107 | + parent = client.location_path(project_id, location) |
| 108 | + |
| 109 | + # Create glossary resource |
| 110 | + # Handle exception for case in which a glossary |
| 111 | + # with glossary_name already exists |
| 112 | + try: |
| 113 | + operation = client.create_glossary(parent=parent, glossary=glossary) |
| 114 | + operation.result(timeout=90) |
| 115 | + print('Created glossary ' + glossary_name + '.') |
| 116 | + except AlreadyExists: |
| 117 | + print('The glossary ' + glossary_name + |
| 118 | + ' already exists. No new glossary was created.') |
| 119 | + # [END translate_hybrid_create_glossary] |
| 120 | + |
| 121 | + |
| 122 | +# [START translate_hybrid_translate] |
| 123 | +def translate_text(text, source_language_code, target_language_code, |
| 124 | + project_id, glossary_name): |
| 125 | + """Translates text to a given language using a glossary |
| 126 | +
|
| 127 | + ARGS |
| 128 | + text: String of text to translate |
| 129 | + prev_lang: language of input text |
| 130 | + new_lang: language of output text |
| 131 | + project_id: GCP project id |
| 132 | + glossary_name: name you gave your project's glossary |
| 133 | + resource when you created it |
| 134 | +
|
| 135 | + RETURNS |
| 136 | + String of translated text |
| 137 | + """ |
| 138 | + |
| 139 | + # Instantiates a client |
| 140 | + client = translate.TranslationServiceClient() |
| 141 | + |
| 142 | + # Designates the data center location that you want to use |
| 143 | + location = 'us-central1' |
| 144 | + |
| 145 | + glossary = client.glossary_path( |
| 146 | + project_id, |
| 147 | + location, |
| 148 | + glossary_name) |
| 149 | + |
| 150 | + glossary_config = translate.types.TranslateTextGlossaryConfig( |
| 151 | + glossary=glossary) |
| 152 | + |
| 153 | + parent = client.location_path(project_id, location) |
| 154 | + |
| 155 | + result = client.translate_text( |
| 156 | + parent=parent, |
| 157 | + contents=[text], |
| 158 | + mime_type='text/plain', # mime types: text/plain, text/html |
| 159 | + source_language_code=source_language_code, |
| 160 | + target_language_code=target_language_code, |
| 161 | + glossary_config=glossary_config) |
| 162 | + |
| 163 | + # Extract translated text from API response |
| 164 | + return result.glossary_translations[0].translated_text |
| 165 | + # [END translate_hybrid_translate] |
| 166 | + |
| 167 | + |
| 168 | +# [START translate_hybrid_tts] |
| 169 | +def text_to_speech(text, outfile): |
| 170 | + """Converts plaintext to SSML and |
| 171 | + generates synthetic audio from SSML |
| 172 | +
|
| 173 | + ARGS |
| 174 | + text: text to synthesize |
| 175 | + outfile: filename to use to store synthetic audio |
| 176 | +
|
| 177 | + RETURNS |
| 178 | + nothing |
| 179 | + """ |
| 180 | + |
| 181 | + # Replace special characters with HTML Ampersand Character Codes |
| 182 | + # These Codes prevent the API from confusing text with |
| 183 | + # SSML commands |
| 184 | + # For example, '<' --> '<' and '&' --> '&' |
| 185 | + escaped_lines = html.escape(text) |
| 186 | + |
| 187 | + # Convert plaintext to SSML in order to wait two seconds |
| 188 | + # between each line in synthetic speech |
| 189 | + ssml = '<speak>{}</speak>'.format( |
| 190 | + escaped_lines.replace('\n', '\n<break time="2s"/>')) |
| 191 | + |
| 192 | + # Instantiates a client |
| 193 | + client = texttospeech.TextToSpeechClient() |
| 194 | + |
| 195 | + # Sets the text input to be synthesized |
| 196 | + synthesis_input = texttospeech.types.SynthesisInput(ssml=ssml) |
| 197 | + |
| 198 | + # Builds the voice request, selects the language code ("en-US") and |
| 199 | + # the SSML voice gender ("MALE") |
| 200 | + voice = texttospeech.types.VoiceSelectionParams( |
| 201 | + language_code='en-US', |
| 202 | + ssml_gender=texttospeech.enums.SsmlVoiceGender.MALE) |
| 203 | + |
| 204 | + # Selects the type of audio file to return |
| 205 | + audio_config = texttospeech.types.AudioConfig( |
| 206 | + audio_encoding=texttospeech.enums.AudioEncoding.MP3) |
| 207 | + |
| 208 | + # Performs the text-to-speech request on the text input with the selected |
| 209 | + # voice parameters and audio file type |
| 210 | + response = client.synthesize_speech(synthesis_input, voice, audio_config) |
| 211 | + |
| 212 | + # Writes the synthetic audio to the output file. |
| 213 | + with open(outfile, 'wb') as out: |
| 214 | + out.write(response.audio_content) |
| 215 | + print('Audio content written to file ' + outfile) |
| 216 | + # [END translate_hybrid_tts] |
| 217 | + |
| 218 | + |
| 219 | +# [START translate_hybrid_integration] |
| 220 | +def main(): |
| 221 | + |
| 222 | + # Photo from which to extract text |
| 223 | + infile = 'resources/example.png' |
| 224 | + # Name of file that will hold synthetic speech |
| 225 | + outfile = 'resources/example.mp3' |
| 226 | + |
| 227 | + # Defines the languages in the glossary |
| 228 | + # This list must match the languages in the glossary |
| 229 | + # Here, the glossary includes French and English |
| 230 | + glossary_langs = ['fr', 'en'] |
| 231 | + # Name that will be assigned to your project's glossary resource |
| 232 | + glossary_name = 'bistro-glossary' |
| 233 | + # uri of .csv file uploaded to Cloud Storage |
| 234 | + glossary_uri = 'gs://cloud-samples-data/translation/bistro_glossary.csv' |
| 235 | + |
| 236 | + create_glossary(glossary_langs, PROJECT_ID, glossary_name, glossary_uri) |
| 237 | + |
| 238 | + # photo -> detected text |
| 239 | + text_to_translate = pic_to_text(infile) |
| 240 | + # detected text -> translated text |
| 241 | + text_to_speak = translate_text(text_to_translate, 'fr', 'en', |
| 242 | + PROJECT_ID, glossary_name) |
| 243 | + # translated text -> synthetic audio |
| 244 | + text_to_speech(text_to_speak, outfile) |
| 245 | + # [END transalte_hybrid_integration] |
| 246 | + |
| 247 | + |
| 248 | +if __name__ == '__main__': |
| 249 | + main() |
0 commit comments