Skip to content

Instantly share code, notes, and snippets.

@kntmr
Created June 7, 2020 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kntmr/c1fcb243859d7f979c8ec41439e8b792 to your computer and use it in GitHub Desktop.
Save kntmr/c1fcb243859d7f979c8ec41439e8b792 to your computer and use it in GitHub Desktop.
import json
import urllib.parse
import boto3
import datetime
print('Loading function')
s3 = boto3.client('s3')
def read_input_text(bucket_name, input_key):
obj = s3.get_object(Bucket = bucket_name, Key = input_key)
body = obj['Body'].read().decode('utf-8')
return json.loads(body)['results']['transcripts'][0]['transcript']
def translate_text(text):
translate = boto3.client('translate')
response = translate.translate_text(
Text = text,
SourceLanguageCode = 'en',
TargetLanguageCode = 'ja'
)
return response['TranslatedText']
def upload_json(bucket_name, output_key, json_text):
resource_s3 = boto3.resource('s3')
obj = resource_s3.Object(bucket_name, output_key)
obj.put(Key = output_key, Body = json_text)
def lambda_handler(event, context):
bucket = event['Records'][0]['s3']['bucket']['name']
input_key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
try:
input_text = read_input_text(bucket, input_key)
translated_text = translate_text(input_text)
output_key = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + '_translated.json'
json_text = json.dumps({
'input_text': input_text,
'translated_text': translated_text
}, ensure_ascii = False)
upload_json(bucket, output_key, json_text)
except Exception as e:
print(e)
raise e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment