{ } "Version":"2012-10-17", "Statement":[ { "Effect":"Allow", "Action":[ "polly:synthesizespeech", "dynamodb:query", "dynamodb:scan", "dynamodb:putitem", "dynamodb:updateitem", "sns:publish", "s3:putobject", "s3:putobjectacl", "s3:getbucketlocation", "logs:createloggroup", "logs:createlogstream", "logs:putlogevents", "lambda:invokefunction" ], "Resource":[ "*" ] } ]
import boto3 import os import json import uuid import datetime def lambda_handler(event, context): recordid = str(uuid.uuid4()) voice = event["voice"] origintext = event["text"] hanja = event["hanja"] updatedate = datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S") print('generating new DynamoDB record, with ID: ' + recordid) print('input Text: ' + origintext) print('selected voice: ' + voice) # Hanja to Korean if hanja: lambda_client = boto3.client('lambda') invoke_response = lambda_client.invoke( FunctionName = "HanjaToKorean", InvocationType = 'RequestResponse',
Payload = json.dumps({"inputtext": origintext}) ) data = invoke_response['payload'].read() resulttext = json.loads(data) replacetext = resulttext['outputtext'] print('hanja to Korean Text: ' + replacetext) else: replacetext = origintext # Creating new record in DynamoDB table dynamodb = boto3.resource('dynamodb') table = dynamodb.table(os.environ['db_table_name']) table.put_item( Item={ 'id' : recordid, 'voice' : voice, 'text': origintext, 'replacetext': replacetext, 'status' : "PROCESSING", 'updatedate': updatedate } ) # Sending notification about new post to SNS client = boto3.client('sns') client.publish( TopicArn = os.environ['sns_topic'], Message = recordid ) return recordid
{ } "voice": "Seoyeon", "text": ",. Polly.", "hanja": false
sudo apt-get install maven brew install maven mvn package
{ } "inputtext": " "
{ } "voice": "Seoyeon", "text": ".", "hanja": true
import boto3 import os from contextlib import closing from boto3.dynamodb.conditions import Key, Attr def lambda_handler(event, context): postid = event["records"][0]["sns"]["message"] print "Text to Speech function. Post ID in DynamoDB: " + postid #Retrieving information about the post from DynamoDB table dynamodb = boto3.resource('dynamodb') table = dynamodb.table(os.environ['db_table_name']) postitem = table.query( KeyConditionExpression=Key('id').eq(postId) ) text = postitem["items"][0]["replacetext"] voice = postitem["items"][0]["voice"] rest = text #Because single invocation of the polly synthesize_speech api can # transform text with about 1,500 characters, we are dividing the # post into blocks of approximately 1,000 characters. textblocks = [] while (len(rest) > 1100): begin = 0 end = rest.find(".", 1000) if (end == -1): end = rest.find(" ", 1000) textblock = rest[begin:end] rest = rest[end:] textblocks.append(textblock) textblocks.append(rest) #For each block, invoke Polly API, which will transform text into audio polly = boto3.client('polly') for textblock in textblocks: response = polly.synthesize_speech( OutputFormat='mp3', Text = textblock, VoiceId = voice ) #Save the audio stream returned by Amazon Polly on Lambda's temp # directory. If there are multiple text blocks, the audio stream # will be combined into a single file. if "AudioStream" in response: with closing(response["audiostream"]) as stream: output = os.path.join("/tmp/", postid) with open(output, "a") as file: file.write(stream.read()) s3 = boto3.client('s3') s3.upload_file('/tmp/' + postid, os.environ['bucket_name'],
postid + ".mp3") s3.put_object_acl(acl='public-read', Bucket=os.environ['BUCKET_NAME'], Key= postid + ".mp3") location = s3.get_bucket_location(bucket=os.environ['bucket_name']) region = location['locationconstraint'] if region is None: url_begining = "https://s3.amazonaws.com/" else: url_begining = "https://s3-" + str(region) + ".amazonaws.com/" \ url = url_begining \ + str(os.environ['bucket_name']) \ + "/" \ + str(postid) \ + ".mp3" #Updating the item in DynamoDB response = table.update_item( Key={'id':postId}, UpdateExpression= "SET #statusatt = :statusvalue, #urlatt = :urlvalue", ExpressionAttributeValues= {':statusvalue': 'UPDATED', ':urlvalue': url}, ExpressionAttributeNames= {'#statusatt': 'status', '#urlatt': 'mp3url'}, ) return
import boto3 import os from boto3.dynamodb.conditions import Key, Attr def lambda_handler(event, context): postid = event["postid"] dynamodb = boto3.resource('dynamodb') table = dynamodb.table(os.environ['db_table_name']) if postid == "*": items = table.scan() else: items = table.query(keyconditionexpression=key('id').eq(postid)) return items["items"] { } "postid": "*"
{ } "postid": "$input.params('postid')"
{ } "Version":"2012-10-17", "Statement":[ { "Sid":"PublicReadGetObject", "Effect":"Allow", "Principal":"*", "Action":[ "s3:getobject" ], "Resource":[ "arn:aws:s3:::bucket_name/*" ] } ]