Exemples d'Amazon Polly utilisant SDK for JavaScript (v3) - AWS SDK for JavaScript

Le guide de API référence AWS SDK for JavaScript V3 décrit en détail toutes les API opérations de la AWS SDK for JavaScript version 3 (V3).

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

Exemples d'Amazon Polly utilisant SDK for JavaScript (v3)

Les exemples de code suivants vous montrent comment effectuer des actions et implémenter des scénarios courants à l'aide de la version AWS SDK for JavaScript (v3) avec Amazon Polly.

Les scénarios sont des exemples de code qui vous montrent comment accomplir des tâches spécifiques en appelant plusieurs fonctions au sein d'un service ou en les combinant à d'autres Services AWS.

Chaque exemple inclut un lien vers le code source complet, où vous trouverez des instructions sur la façon de configurer et d'exécuter le code en contexte.

Rubriques

Scénarios

L'exemple de code suivant montre comment créer une application qui analyse les cartes de commentaires des clients, les traduit depuis leur langue d'origine, détermine leur sentiment et génère un fichier audio à partir du texte traduit.

SDKpour JavaScript (v3)

Cet exemple d’application analyse et stocke les cartes de commentaires des clients. Plus précisément, elle répond aux besoins d’un hôtel fictif situé à New York. L’hôtel reçoit les commentaires des clients dans différentes langues sous la forme de cartes de commentaires physiques. Ces commentaires sont chargés dans l’application via un client Web. Après avoir chargé l’image d’une carte de commentaires, les étapes suivantes se déroulent :

  • Le texte est extrait de l’image à l’aide d’Amazon Textract.

  • Amazon Comprehend détermine le sentiment du texte extrait et sa langue.

  • Le texte extrait est traduit en anglais à l’aide d’Amazon Translate.

  • Amazon Polly synthétise un fichier audio à partir du texte extrait.

L’application complète peut être déployée avec AWS CDK. Pour le code source et les instructions de déploiement, consultez le projet dans GitHub. Les extraits suivants montrent comment le AWS SDK for JavaScript est utilisé dans les fonctions Lambda.

import { ComprehendClient, DetectDominantLanguageCommand, DetectSentimentCommand, } from "@aws-sdk/client-comprehend"; /** * Determine the language and sentiment of the extracted text. * * @param {{ source_text: string}} extractTextOutput */ export const handler = async (extractTextOutput) => { const comprehendClient = new ComprehendClient({}); const detectDominantLanguageCommand = new DetectDominantLanguageCommand({ Text: extractTextOutput.source_text, }); // The source language is required for sentiment analysis and // translation in the next step. const { Languages } = await comprehendClient.send( detectDominantLanguageCommand, ); const languageCode = Languages[0].LanguageCode; const detectSentimentCommand = new DetectSentimentCommand({ Text: extractTextOutput.source_text, LanguageCode: languageCode, }); const { Sentiment } = await comprehendClient.send(detectSentimentCommand); return { sentiment: Sentiment, language_code: languageCode, }; };
import { DetectDocumentTextCommand, TextractClient, } from "@aws-sdk/client-textract"; /** * Fetch the S3 object from the event and analyze it using Amazon Textract. * * @param {import("@types/aws-lambda").EventBridgeEvent<"Object Created">} eventBridgeS3Event */ export const handler = async (eventBridgeS3Event) => { const textractClient = new TextractClient(); const detectDocumentTextCommand = new DetectDocumentTextCommand({ Document: { S3Object: { Bucket: eventBridgeS3Event.bucket, Name: eventBridgeS3Event.object, }, }, }); // Textract returns a list of blocks. A block can be a line, a page, word, etc. // Each block also contains geometry of the detected text. // For more information on the Block type, see https://docs.aws.amazon.com/textract/latest/dg/API_Block.html. const { Blocks } = await textractClient.send(detectDocumentTextCommand); // For the purpose of this example, we are only interested in words. const extractedWords = Blocks.filter((b) => b.BlockType === "WORD").map( (b) => b.Text, ); return extractedWords.join(" "); };
import { PollyClient, SynthesizeSpeechCommand } from "@aws-sdk/client-polly"; import { S3Client } from "@aws-sdk/client-s3"; import { Upload } from "@aws-sdk/lib-storage"; /** * Synthesize an audio file from text. * * @param {{ bucket: string, translated_text: string, object: string}} sourceDestinationConfig */ export const handler = async (sourceDestinationConfig) => { const pollyClient = new PollyClient({}); const synthesizeSpeechCommand = new SynthesizeSpeechCommand({ Engine: "neural", Text: sourceDestinationConfig.translated_text, VoiceId: "Ruth", OutputFormat: "mp3", }); const { AudioStream } = await pollyClient.send(synthesizeSpeechCommand); const audioKey = `${sourceDestinationConfig.object}.mp3`; // Store the audio file in S3. const s3Client = new S3Client(); const upload = new Upload({ client: s3Client, params: { Bucket: sourceDestinationConfig.bucket, Key: audioKey, Body: AudioStream, ContentType: "audio/mp3", }, }); await upload.done(); return audioKey; };
import { TranslateClient, TranslateTextCommand, } from "@aws-sdk/client-translate"; /** * Translate the extracted text to English. * * @param {{ extracted_text: string, source_language_code: string}} textAndSourceLanguage */ export const handler = async (textAndSourceLanguage) => { const translateClient = new TranslateClient({}); const translateCommand = new TranslateTextCommand({ SourceLanguageCode: textAndSourceLanguage.source_language_code, TargetLanguageCode: "en", Text: textAndSourceLanguage.extracted_text, }); const { TranslatedText } = await translateClient.send(translateCommand); return { translated_text: TranslatedText }; };
Les services utilisés dans cet exemple
  • Amazon Comprehend

  • Lambda

  • Amazon Polly

  • Amazon Textract

  • Amazon Translate