Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions apigw-lambda-sfn-transcribe-translate-polly-sam/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ API Gateway handles incoming traffic and sends it to the lambda which in turn in

Follow the steps to test the pattern:

1. Copy the audio to the input bucket (available from the output of the cloudformation stack).
1. Copy the audio to the input bucket (available from the output of the CloudFormation stack).
```bash
aws s3 cp audio.ogg s3://{input-bucket-name}
```
Expand All @@ -70,7 +70,7 @@ Follow the steps to test the pattern:
```
1. Run websocket client to invoke the API Gateway. Get the API ID from the output of the deployment step
```bash
wscat -c wss://<API-ID>.execute-api.<Region>.amazonaws.com/dev?proto=https
wscat -c wss://<API-ID>.execute-api.<Region>.amazonaws.com/dev?proto=https
```
1. On the next prompt, add the input parameters. Replace the input bucket name. It can be tested with other language codes as well.
```bash
Expand All @@ -90,4 +90,4 @@ Follow the steps to test the pattern:
----
Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
SPDX-License-Identifier: MIT-0
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
const AWS = require('aws-sdk');
const stepfunctions = new AWS.StepFunctions();
const apig = new AWS.ApiGatewayManagementApi({
endpoint: process.env.APIG_ENDPOINT,
const { SFNClient, StartSyncExecutionCommand } = require('@aws-sdk/client-sfn');
const { ApiGatewayManagementApiClient, PostToConnectionCommand } = require('@aws-sdk/client-apigatewaymanagementapi');
const stepfunctions = new SFNClient({});
const apig = new ApiGatewayManagementApiClient({
endpoint: `https://${process.env.APIG_ENDPOINT}`,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: Some error occurs. Because we need use connections url with https.

< {"message": "Internal server error", "connectionId":"R-c1lc6StjMCFug=", "requestId":"R-d65GZntjMECaQ="}

});

module.exports.handler = async (event, context) => {
Expand All @@ -25,12 +26,11 @@ module.exports.handler = async (event, context) => {
stateMachineArn: process.env.statemachine_arn,
input: body
}
let response = await stepfunctions.startSyncExecution(params).promise();
await apig
.postToConnection({
let response = await stepfunctions.send(new StartSyncExecutionCommand(params));
await apig.send(new PostToConnectionCommand({
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: Some error occurs. Because in Node.js 18 and later runtimes, AWS SDK v3 is bundled, so I rewrote it to v3. See articles below.

ConnectionId: connectionId,
Data: response?JSON.stringify( {"url" : JSON.parse(response.output).url} ):"No data"
}).promise();
}));
if ( response && response.output)
response = {"url" : JSON.parse(response.output).url}
return {
Expand Down
30 changes: 20 additions & 10 deletions apigw-lambda-sfn-transcribe-translate-polly-sam/src/speech.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const polly = new AWS.Polly();
const uuidv1 = require('uuidv1');
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: Some error occurs.

{
  "errorType": "Runtime.ImportModuleError",
  "errorMessage": "Error: Cannot find module 'uuidv1'\nRequire stack:\n- /var/task/src/speech.js\n- /var/runtime/index.mjs",
  "trace": [
    "Runtime.ImportModuleError: Error: Cannot find module 'uuidv1'",
    "Require stack:",
    "- /var/task/src/speech.js",
    "- /var/runtime/index.mjs",
    "    at _loadUserApp (file:///var/runtime/index.mjs:1192:17)",
    "    at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1235:21)",
    "    at async start (file:///var/runtime/index.mjs:1454:23)",
    "    at async file:///var/runtime/index.mjs:1464:1"
  ]
}

const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const { PollyClient, SynthesizeSpeechCommand } = require('@aws-sdk/client-polly');
const { getSignedUrl } = require('@aws-sdk/s3-request-presigner');
const { GetObjectCommand } = require('@aws-sdk/client-s3');
const { randomUUID } = require('crypto');
const s3 = new S3Client({});
const polly = new PollyClient({});


module.exports.handler = async (event, context) => {
Expand Down Expand Up @@ -62,21 +65,28 @@ module.exports.handler = async (event, context) => {

console.log(speechParams)

const response = await polly.synthesizeSpeech(speechParams).promise();
const response = await polly.send(new SynthesizeSpeechCommand(speechParams));
let audioStream = response.AudioStream;
let key = uuidv1();

const chunks = [];
for await (const chunk of audioStream) {
chunks.push(chunk);
}
const audioBuffer = Buffer.concat(chunks);

let key = randomUUID();
let params = {
Bucket: outputBucket,
Key: key + '.mp3',
Body: audioStream
Body: audioBuffer
};

const s3Response = await s3.putObject(params).promise();
const s3Response = await s3.send(new PutObjectCommand(params));
let s3params = {
Bucket: outputBucket,
Key: key + '.mp3',
};
let url = s3.getSignedUrl("getObject", s3params);
let url = await getSignedUrl(s3, new GetObjectCommand(s3params));
console.log(url);
return { url, outputBucket, key: key + '.mp3' };
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const AWS = require('aws-sdk');
const transcribe = new AWS.TranscribeService();
const { TranscribeClient, GetTranscriptionJobCommand } = require('@aws-sdk/client-transcribe');
const transcribe = new TranscribeClient({});

module.exports.handler = async (event, context) => {
console.log(event)
Expand All @@ -12,7 +12,7 @@ module.exports.handler = async (event, context) => {
TranscriptionJobName: jobName
};

let jobData = await transcribe.getTranscriptionJob(params).promise();
let jobData = await transcribe.send(new GetTranscriptionJobCommand(params));
let jobStatus = jobData.TranscriptionJob.TranscriptionJobStatus;
if ( jobStatus == 'COMPLETED' || jobStatus == 'FAILED') {
let s3Loc = jobData.TranscriptionJob.Transcript.TranscriptFileUri;
Expand All @@ -25,4 +25,4 @@ module.exports.handler = async (event, context) => {
else {
return { continue: true, jobName, outputBucket, inputLanguageCode, outputLanguageCode }
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const path = require('path');
const AWS = require('aws-sdk');
const transcribe = new AWS.TranscribeService();
const { TranscribeClient, StartTranscriptionJobCommand } = require('@aws-sdk/client-transcribe');
const transcribe = new TranscribeClient({});

module.exports.handler = async (event, context) => {
console.log(event)
Expand All @@ -25,6 +25,6 @@ module.exports.handler = async (event, context) => {
OutputBucketName: OUTPUT_BUCKET
};
console.log(params);
await transcribe.startTranscriptionJob(params).promise();
await transcribe.send(new StartTranscriptionJobCommand(params));
return { jobName, outputBucket:OUTPUT_BUCKET, inputLanguageCode, outputLanguageCode };
};
15 changes: 8 additions & 7 deletions apigw-lambda-sfn-transcribe-translate-polly-sam/src/translate.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const translate = new AWS.Translate();
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
const { TranslateClient, TranslateTextCommand } = require('@aws-sdk/client-translate');
const s3 = new S3Client({});
const translate = new TranslateClient({});


module.exports.handler = async (event, context) => {
Expand Down Expand Up @@ -102,18 +103,18 @@ module.exports.handler = async (event, context) => {
}
}

const s3Body = await s3.getObject(params).promise()
const transcribedOutput = s3Body.Body.toString('utf-8');
const s3Body = await s3.send(new GetObjectCommand(params))
const transcribedOutput = await s3Body.Body.transformToString();
console.log(transcribedOutput)
const originalText = JSON.parse(transcribedOutput).results.transcripts[0].transcript;
let translateParams = {
Text: originalText,
SourceLanguageCode: sourceLanguageCode,
TargetLanguageCode: targetLanguageCode
}
const translatedResponse = await translate.translateText(translateParams).promise();
const translatedResponse = await translate.send(new TranslateTextCommand(translateParams));
const translatedText = translatedResponse.TranslatedText
console.log(translatedText)
return { translatedText, outputBucket, outputLanguageCode }

}
}
12 changes: 6 additions & 6 deletions apigw-lambda-sfn-transcribe-translate-polly-sam/template.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ Resources:
Properties:
Handler: src/transcribeLaunch.handler
FunctionName: "translator-dev-transcribeLaunch"
Runtime: nodejs20.x
Runtime: nodejs22.x
Architectures:
- x86_64
MemorySize: 128
Expand All @@ -65,7 +65,7 @@ Resources:
Properties:
Handler: src/transcribeCheck.handler
FunctionName: "translator-dev-transcribeCheck"
Runtime: nodejs20.x
Runtime: nodejs22.x
Architectures:
- x86_64
MemorySize: 128
Expand All @@ -76,7 +76,7 @@ Resources:
Properties:
Handler: src/translate.handler
FunctionName: "translator-dev-translate"
Runtime: nodejs20.x
Runtime: nodejs22.x
Architectures:
- x86_64
MemorySize: 128
Expand All @@ -87,7 +87,7 @@ Resources:
Properties:
Handler: src/speech.handler
FunctionName: "translator-dev-speech"
Runtime: nodejs20.x
Runtime: nodejs22.x
Architectures:
- x86_64
MemorySize: 128
Expand All @@ -111,7 +111,7 @@ Resources:
InvokerLambda:
Type: AWS::Serverless::Function
Properties:
Runtime: "nodejs16.x"
Runtime: "nodejs22.x"
FunctionName: "translator-dev-invokeTranslator"
Timeout: 300
MemorySize: 1024
Expand All @@ -134,7 +134,7 @@ Resources:
Type: AWS::Lambda::Function
Properties:
FunctionName: "translator-dev-authorizer"
Runtime: "nodejs18.x"
Runtime: "nodejs22.x"
Timeout: 300
MemorySize: 1024
Handler: index.handler
Expand Down