From 11f67f095a7e6273552e18fbed99eceb1f8d557f Mon Sep 17 00:00:00 2001 From: scmacdon Date: Thu, 31 Aug 2023 15:43:57 -0400 Subject: [PATCH] add java files --- javav2/usecases/creating_fsa_app/pom.xml | 218 ++++++++++++++++++ .../example/fsa/FSAApplicationResources.java | 11 + .../java/com/example/fsa/ModifyLambda.java | 65 ++++++ .../example/fsa/handlers/PollyHanlder.java | 85 +++++++ .../com/example/fsa/handlers/S3Handler.java | 27 +++ .../fsa/handlers/SentimentHandler.java | 39 ++++ .../fsa/handlers/TranslateHandler.java | 48 ++++ .../fsa/services/DetectSentimentService.java | 68 ++++++ .../fsa/services/ExtractTextService.java | 53 +++++ .../example/fsa/services/PollyService.java | 44 ++++ .../com/example/fsa/services/S3Service.java | 47 ++++ .../fsa/services/TranslateService.java | 29 +++ .../src/test/java/FSATests.java | 49 ++++ 13 files changed, 783 insertions(+) create mode 100644 javav2/usecases/creating_fsa_app/pom.xml create mode 100644 javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/FSAApplicationResources.java create mode 100644 javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/ModifyLambda.java create mode 100644 javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/handlers/PollyHanlder.java create mode 100644 javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/handlers/S3Handler.java create mode 100644 javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/handlers/SentimentHandler.java create mode 100644 javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/handlers/TranslateHandler.java create mode 100644 javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/DetectSentimentService.java create mode 100644 javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/ExtractTextService.java create mode 100644 javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/PollyService.java create mode 100644 javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/S3Service.java create mode 100644 javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/TranslateService.java create mode 100644 javav2/usecases/creating_fsa_app/src/test/java/FSATests.java diff --git a/javav2/usecases/creating_fsa_app/pom.xml b/javav2/usecases/creating_fsa_app/pom.xml new file mode 100644 index 00000000000..1d1feff875f --- /dev/null +++ b/javav2/usecases/creating_fsa_app/pom.xml @@ -0,0 +1,218 @@ + + + 4.0.0 + org.example + creating_fsa_app + 1.0-SNAPSHOT + + 17 + 17 + UTF-8 + + + + + software.amazon.awssdk + bom + 2.20.45 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.19.0 + pom + import + + + + + + software.amazon.awssdk + dynamodb + + + commons-logging + commons-logging + 1.2 + + + com.fasterxml.jackson.core + jackson-databind + 2.12.5 + + + software.amazon.awssdk + dynamodb-enhanced + + + software.amazon.awssdk + apache-client + + + commons-logging + commons-logging + + + + + org.apache.logging.log4j + log4j-core + + + org.apache.logging.log4j + log4j-api + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-1.2-api + + + software.amazon.awssdk + ses + + + software.amazon.awssdk + rekognition + + + com.amazonaws + aws-lambda-java-events + 3.11.1 + + + software.amazon.awssdk + s3 + + + software.amazon.awssdk + textract + + + software.amazon.awssdk + s3control + + + com.amazonaws + aws-lambda-java-core + 1.2.2 + + + software.amazon.awssdk + translate + + + software.amazon.awssdk + comprehend + + + org.json + json + 20230227 + + + software.amazon.awssdk + polly + + + software.amazon.awssdk + dynamodb + + + software.amazon.awssdk + dynamodb-enhanced + + + software.amazon.awssdk + sns + + + org.apache.maven.surefire + surefire-booter + 3.0.0-M3 + + + software.amazon.awssdk + lambda + + + com.google.code.gson + gson + 2.10.1 + + + commons-io + commons-io + 2.5 + + + org.junit.jupiter + junit-jupiter-engine + 5.9.0 + test + + + com.googlecode.json-simple + json-simple + 1.1 + + + org.junit.jupiter + junit-jupiter-api + 5.9.0 + test + + + + + + maven-surefire-plugin + 2.22.2 + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.1.2 + + checkstyle.xml + UTF-8 + true + true + false + + + + validate + validate + + check + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.3.0 + + false + + + + package + + shade + + + + + + + \ No newline at end of file diff --git a/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/FSAApplicationResources.java b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/FSAApplicationResources.java new file mode 100644 index 00000000000..ad53fd7e4dd --- /dev/null +++ b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/FSAApplicationResources.java @@ -0,0 +1,11 @@ +/* + Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ + +package com.example.fsa; + +public class FSAApplicationResources { + + public static final String STORAGE_BUCKET = "fsa-scmacdon-javascript-mediabucket8240391c-1wba4q2k3xco9"; +} diff --git a/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/ModifyLambda.java b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/ModifyLambda.java new file mode 100644 index 00000000000..4a34fddd829 --- /dev/null +++ b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/ModifyLambda.java @@ -0,0 +1,65 @@ +/* + Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ + +package com.example.fsa; + +import software.amazon.awssdk.core.waiters.WaiterResponse; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.lambda.LambdaClient; +import software.amazon.awssdk.services.lambda.model.GetFunctionConfigurationRequest; +import software.amazon.awssdk.services.lambda.model.GetFunctionConfigurationResponse; +import software.amazon.awssdk.services.lambda.model.LambdaException; +import software.amazon.awssdk.services.lambda.model.UpdateFunctionCodeRequest; +import software.amazon.awssdk.services.lambda.model.UpdateFunctionCodeResponse; +import software.amazon.awssdk.services.lambda.waiters.LambdaWaiter; + +public class ModifyLambda { + + public static void main(String[]args) { + String analyzeSentimentLambda = "fsa-scmacdon-javascript-fnAnalyzeSentimentCEDFFDBD-wd0RnOdSxMsv" ; + String synthesizeAudioLambda = "fsa-scmacdon-javascript-fnSynthesizeAudio134971D4-x8Q5178Y4ZBH" ; + String extractTextLambda = "fsa-scmacdon-javascript-fnExtractText98FC28B4-NRiFEZmyPPlo" ; + String translateTextLambda = "fsa-scmacdon-javascript-fnAnalyzeSentimentCEDFFDBD-wd0RnOdSxMsv" ; + String bucketName = FSAApplicationResources.STORAGE_BUCKET; + String key = "creating_fsa_app-1.0-SNAPSHOT.jar"; + + Region region = Region.US_EAST_1; + LambdaClient awsLambda = LambdaClient.builder() + .region(region) + .build(); + + // Update all four Lambda functions. + updateFunctionCode(awsLambda, analyzeSentimentLambda, bucketName, key); + updateFunctionCode(awsLambda, synthesizeAudioLambda, bucketName, key); + updateFunctionCode(awsLambda, extractTextLambda, bucketName, key); + updateFunctionCode(awsLambda, translateTextLambda, bucketName, key); + System.out.println("You have successfully updated the AWS Lambda functions"); + } + + public static void updateFunctionCode(LambdaClient awsLambda, String functionName, String bucketName, String key) { + try { + LambdaWaiter waiter = awsLambda.waiter(); + UpdateFunctionCodeRequest functionCodeRequest = UpdateFunctionCodeRequest.builder() + .functionName(functionName) + .publish(true) + .s3Bucket(bucketName) + .s3Key(key) + .build(); + + UpdateFunctionCodeResponse response = awsLambda.updateFunctionCode(functionCodeRequest) ; + GetFunctionConfigurationRequest getFunctionConfigRequest = GetFunctionConfigurationRequest.builder() + .functionName(functionName) + .build(); + + WaiterResponse waiterResponse = waiter.waitUntilFunctionUpdated(getFunctionConfigRequest); + waiterResponse.matched().response().ifPresent(System.out::println); + System.out.println("The last modified value is " +response.lastModified()); + + } catch(LambdaException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } +} diff --git a/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/handlers/PollyHanlder.java b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/handlers/PollyHanlder.java new file mode 100644 index 00000000000..158f862be0f --- /dev/null +++ b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/handlers/PollyHanlder.java @@ -0,0 +1,85 @@ +/* + Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ + +package com.example.fsa.handlers; + +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import com.example.fsa.services.PollyService; +import com.example.fsa.services.S3Service; +import java.io.IOException; +import java.io.InputStream; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.Map; + +public class PollyHanlder implements RequestHandler, String> { + @Override + public String handleRequest(Map requestObject, Context context) { + S3Service s3Service = new S3Service(); + PollyService pollyService = new PollyService(); + String myValues = requestObject.toString(); + context.getLogger().log("*** ALL values: " +myValues); + String translatedText = getTranslatedText(myValues); + String key = getKeyName(myValues); + String newFileName = convertFileEx(key); + context.getLogger().log("*** Translated Text: " +translatedText +" and new key is "+newFileName); + try { + InputStream is = pollyService.synthesize(translatedText); + String audioFile = s3Service.putAudio(is, newFileName); + context.getLogger().log("You have successfully added the " +audioFile +" in the S3 bucket"); + return audioFile ; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + // This method extracts the value following translated_text using Reg Exps. + private String getTranslatedText(String myString) { + // Define the regular expression pattern to match key-value pair. + Pattern pattern = Pattern.compile("translated_text\\s*=\\s*([^,}]*)"); + Matcher matcher = pattern.matcher(myString); + + String extractedValue = null; + if (matcher.find()) { + // Find the second occurrence. + if (matcher.find()) { + extractedValue = matcher.group(1); + } + } + + if (extractedValue != null) { + return extractedValue; + } + return ""; + } + + // This method extracts the key using Reg Exps. + private static String getKeyName(String input) { + String pattern = "object=([^,}]+)"; + Pattern r = Pattern.compile(pattern); + Matcher m = r.matcher(input); + + if (m.find()) { + System.out.println("Found value: " + m.group(1)); + return m.group(1); + } + return ""; + } + + // Replaces the file extension to mp3. + public static String convertFileEx(String originalFileName) { + String newExtension = "mp3"; + + // Get the index of the last dot (.) in the filename. + int lastIndex = originalFileName.lastIndexOf("."); + if (lastIndex > 0) { + // Extract the file name without extension. + String fileNameWithoutExtension = originalFileName.substring(0, lastIndex); + return fileNameWithoutExtension + "." + newExtension; + } + return ""; + } +} diff --git a/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/handlers/S3Handler.java b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/handlers/S3Handler.java new file mode 100644 index 00000000000..d9dd8746eba --- /dev/null +++ b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/handlers/S3Handler.java @@ -0,0 +1,27 @@ +/* + Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ + +package com.example.fsa.handlers; + +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import com.example.fsa.FSAApplicationResources; +import com.example.fsa.services.ExtractTextService; +import java.util.Map; + +public class S3Handler implements RequestHandler, String>{ + + @Override + public String handleRequest(Map requestObject, Context context) { + // Get the Amazon Simple Storage Service (Amazon S3) bucket and object key from the Amazon S3 event. + ExtractTextService textService = new ExtractTextService(); + String bucket = (String) requestObject.getOrDefault("bucket", ""); + String fileName = (String) requestObject.getOrDefault("object", ""); + context.getLogger().log("*** Bucket: " + bucket + ", fileName: " + fileName); + String myText = textService.getCardText(FSAApplicationResources.STORAGE_BUCKET, fileName); + context.getLogger().log("*** Text: " + myText); + return myText; + } +} diff --git a/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/handlers/SentimentHandler.java b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/handlers/SentimentHandler.java new file mode 100644 index 00000000000..3012c0896c2 --- /dev/null +++ b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/handlers/SentimentHandler.java @@ -0,0 +1,39 @@ +/* + Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ + +package com.example.fsa.handlers; + +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import com.example.fsa.services.DetectSentimentService; +import org.json.simple.JSONObject; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class SentimentHandler implements RequestHandler, JSONObject> { + + @Override + public JSONObject handleRequest(Map requestObject, Context context) { + // Log the entire JSON input. + String inputString = requestObject.toString(); + context.getLogger().log("Received JSON: " + inputString); + String value = extractValueFromRequestObject(inputString); + context.getLogger().log("Extracted text: " + value); + DetectSentimentService detectSentimentService = new DetectSentimentService(); + JSONObject jsonOb = detectSentimentService.detectSentiments(value); + context.getLogger().log("NEW JSON: " + jsonOb.toJSONString()); + return jsonOb; + } + + private static String extractValueFromRequestObject(String inputString) { + Matcher matcher = Pattern.compile("source_text=([^,}]+)").matcher(inputString); + if (matcher.find()) { + return matcher.group(1); + } + return ""; + } +} + diff --git a/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/handlers/TranslateHandler.java b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/handlers/TranslateHandler.java new file mode 100644 index 00000000000..1d86f351421 --- /dev/null +++ b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/handlers/TranslateHandler.java @@ -0,0 +1,48 @@ +/* + Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ + +package com.example.fsa.handlers; + +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; +import com.example.fsa.services.DetectSentimentService; +import com.example.fsa.services.TranslateService; +import org.json.simple.JSONObject; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class TranslateHandler implements RequestHandler, JSONObject> { + + @Override + public JSONObject handleRequest(Map requestObject, Context context) { + TranslateService translateService = new TranslateService(); + String preValStr = requestObject.toString(); + context.getLogger().log("Pre Value: " + preValStr); + String sourceText = getTranslatedText(preValStr); + context.getLogger().log("NEW Value: " + sourceText); + + // We have the source text - need to figure out what language its in. + DetectSentimentService sentimentService = new DetectSentimentService(); + String lanCode = sentimentService.detectTheDominantLanguage(sourceText); + String translatedText; + translatedText = translateService.translateText(lanCode, sourceText); + context.getLogger().log("Translated text : " + translatedText); + JSONObject jsonResponse = new JSONObject(); + jsonResponse.put("translated_text", translatedText); + return jsonResponse; + } + + private String getTranslatedText(String myString) { + String extractedValue; + Pattern pattern = Pattern.compile("extracted_text\\s*=\\s*([^,}]*)"); + Matcher matcher = pattern.matcher(myString); + if (matcher.find()) { + extractedValue = matcher.group(1); + return extractedValue; + } + return ""; + } +} \ No newline at end of file diff --git a/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/DetectSentimentService.java b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/DetectSentimentService.java new file mode 100644 index 00000000000..9aafe9aad16 --- /dev/null +++ b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/DetectSentimentService.java @@ -0,0 +1,68 @@ +/* + Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ + +package com.example.fsa.services; +import org.json.simple.JSONObject; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.comprehend.ComprehendClient; +import software.amazon.awssdk.services.comprehend.model.ComprehendException; +import software.amazon.awssdk.services.comprehend.model.DetectDominantLanguageRequest; +import software.amazon.awssdk.services.comprehend.model.DetectDominantLanguageResponse; +import software.amazon.awssdk.services.comprehend.model.DetectSentimentRequest; +import software.amazon.awssdk.services.comprehend.model.DetectSentimentResponse; +import software.amazon.awssdk.services.comprehend.model.DominantLanguage; +import java.util.List; + +public class DetectSentimentService { + + private ComprehendClient getClient() { + return ComprehendClient.builder() + .region(Region.US_EAST_1) + .build(); + } + + public JSONObject detectSentiments(String text){ + try { + String languageCode = detectTheDominantLanguage(text); + DetectSentimentRequest detectSentimentRequest = DetectSentimentRequest.builder() + .text(text) + .languageCode(languageCode) + .build(); + + DetectSentimentResponse detectSentimentResult = getClient().detectSentiment(detectSentimentRequest); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("sentiment", detectSentimentResult.sentimentAsString()); + jsonObject.put("language_code", languageCode); + return jsonObject; + + } catch (ComprehendException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + return null; + } + + public String detectTheDominantLanguage(String text){ + try { + DetectDominantLanguageRequest request = DetectDominantLanguageRequest.builder() + .text(text) + .build(); + + String lanCode =""; + DetectDominantLanguageResponse resp = getClient().detectDominantLanguage(request); + List allLanList = resp.languages(); + for (DominantLanguage lang : allLanList) { + System.out.println("Language is " + lang.languageCode()); + lanCode = lang.languageCode(); + } + return lanCode; + + } catch (ComprehendException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + return ""; + } +} diff --git a/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/ExtractTextService.java b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/ExtractTextService.java new file mode 100644 index 00000000000..35483020245 --- /dev/null +++ b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/ExtractTextService.java @@ -0,0 +1,53 @@ +/* + Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ + +package com.example.fsa.services; + +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.textract.model.BlockType; +import software.amazon.awssdk.services.textract.model.Document; +import software.amazon.awssdk.services.textract.model.DetectDocumentTextRequest; +import software.amazon.awssdk.services.textract.model.DetectDocumentTextResponse; +import software.amazon.awssdk.services.textract.model.Block; +import software.amazon.awssdk.services.textract.TextractClient; +import software.amazon.awssdk.services.textract.model.S3Object; + +public class ExtractTextService { + + public String getCardText(String bucketName, String obName) { + Region region = Region.US_EAST_1; + TextractClient textractClient = TextractClient.builder() + .region(region) + .build(); + + S3Object s3Object = S3Object.builder() + .bucket(bucketName) + .name(obName) + .build(); + + // Create a Document object and reference the s3Object instance. + Document myDoc = Document.builder() + .s3Object(s3Object) + .build(); + + DetectDocumentTextRequest detectDocumentTextRequest = DetectDocumentTextRequest.builder() + .document(myDoc) + .build(); + + // Use StringBuilder to build the complete text. + StringBuilder completeText = new StringBuilder(); + DetectDocumentTextResponse textResponse = textractClient.detectDocumentText(detectDocumentTextRequest); + for (Block block : textResponse.blocks()) { + if (block.blockType() == BlockType.WORD) { + if (completeText.length() == 0) { + completeText.append(block.text()); + } else { + completeText.append(" ").append(block.text()); + } + } + } + return completeText.toString(); + } +} diff --git a/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/PollyService.java b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/PollyService.java new file mode 100644 index 00000000000..5bf5667e977 --- /dev/null +++ b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/PollyService.java @@ -0,0 +1,44 @@ +/* + Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ + +package com.example.fsa.services; + +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.polly.PollyClient; +import software.amazon.awssdk.services.polly.model.DescribeVoicesRequest; +import software.amazon.awssdk.services.polly.model.SynthesizeSpeechRequest; +import software.amazon.awssdk.services.polly.model.Voice; +import software.amazon.awssdk.services.polly.model.DescribeVoicesResponse; +import software.amazon.awssdk.services.polly.model.OutputFormat; +import java.io.IOException; +import java.io.InputStream; + + +public class PollyService { + + public InputStream synthesize(String text) throws IOException { + PollyClient polly = PollyClient.builder() + .region(Region.US_EAST_1) + .build(); + + DescribeVoicesRequest describeVoiceRequest = DescribeVoicesRequest.builder() + .engine("neural") + .build(); + + DescribeVoicesResponse describeVoicesResult = polly.describeVoices(describeVoiceRequest); + Voice voice = describeVoicesResult.voices().stream() + .filter(v -> v.name().equals("Joanna")) + .findFirst() + .orElseThrow(() -> new RuntimeException("Voice not found")); + + SynthesizeSpeechRequest synthReq = SynthesizeSpeechRequest.builder() + .text(text) + .outputFormat(OutputFormat.MP3) + .voiceId(voice.id()) + .build(); + + return polly.synthesizeSpeech(synthReq); + } +} diff --git a/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/S3Service.java b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/S3Service.java new file mode 100644 index 00000000000..326711cb730 --- /dev/null +++ b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/S3Service.java @@ -0,0 +1,47 @@ +/* + Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ + +package com.example.fsa.services; + +import com.example.fsa.FSAApplicationResources; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; + +public class S3Service { + + // Put the audio file into the Amazon S3 bucket. + public String putAudio(InputStream is, String key) throws IOException { + S3Client s3 = S3Client.builder() + .region(Region.US_EAST_1) + .build(); + + PutObjectRequest putOb = PutObjectRequest.builder() + .bucket(FSAApplicationResources.STORAGE_BUCKET) + .contentType("audio/mp3") + .key(key) + .build(); + + s3.putObject(putOb, RequestBody.fromBytes(inputStreamToBytes(is))); + return key; + } + + public static byte[] inputStreamToBytes(InputStream inputStream) throws IOException { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + byte[] data = new byte[1024]; + int nRead; + + while ((nRead = inputStream.read(data, 0, data.length)) != -1) { + buffer.write(data, 0, nRead); + } + + buffer.flush(); + return buffer.toByteArray(); + } +} diff --git a/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/TranslateService.java b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/TranslateService.java new file mode 100644 index 00000000000..ccf8cf5c1d5 --- /dev/null +++ b/javav2/usecases/creating_fsa_app/src/main/java/com/example/fsa/services/TranslateService.java @@ -0,0 +1,29 @@ +/* + Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ + +package com.example.fsa.services; + +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.translate.TranslateClient; +import software.amazon.awssdk.services.translate.model.TranslateTextRequest; +import software.amazon.awssdk.services.translate.model.TranslateTextResponse; + +public class TranslateService { + + public String translateText(String lanCode, String text) { + TranslateClient translateClient = TranslateClient.builder() + .region(Region.US_EAST_1) + .build(); + + TranslateTextRequest textRequest = TranslateTextRequest.builder() + .sourceLanguageCode(lanCode) + .targetLanguageCode("en") + .text(text) + .build(); + + TranslateTextResponse textResponse = translateClient.translateText(textRequest); + return textResponse.translatedText(); + } +} diff --git a/javav2/usecases/creating_fsa_app/src/test/java/FSATests.java b/javav2/usecases/creating_fsa_app/src/test/java/FSATests.java new file mode 100644 index 00000000000..fece1fe5f7b --- /dev/null +++ b/javav2/usecases/creating_fsa_app/src/test/java/FSATests.java @@ -0,0 +1,49 @@ +/* + Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +import com.example.fsa.FSAApplicationResources; +import com.example.fsa.services.DetectSentimentService; +import com.example.fsa.services.ExtractTextService; +import com.example.fsa.services.PollyService; +import com.example.fsa.services.S3Service; +import com.example.fsa.services.TranslateService; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestMethodOrder; +import java.io.IOException; +import java.io.InputStream; + +@TestInstance(TestInstance.Lifecycle.PER_METHOD) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +public class FSATests { + + @Test + @Tag("IntegrationTest") + @Order(1) + public void testFSA() throws IOException { + ExtractTextService textService = new ExtractTextService(); + TranslateService translateService = new TranslateService(); + PollyService pollyService = new PollyService(); + S3Service s3Service = new S3Service(); + JSONParser parser = new JSONParser(); + DetectSentimentService sentimentService = new DetectSentimentService(); + + + DetectSentimentService detectSentimentService = new DetectSentimentService(); + String text = textService.getCardText(FSAApplicationResources.STORAGE_BUCKET, "french6.png"); + detectSentimentService.detectSentiments(text); + String lanCode = sentimentService.detectTheDominantLanguage(text); + String translatedText = translateService.translateText(lanCode, text); + System.out.println(translatedText); + InputStream is = pollyService.synthesize(translatedText); + String audioFile = s3Service.putAudio(is, "french3.png"); + System.out.println("You have successfully added the FSA audio file in the S3 bucket"); + System.out.println("You have successfully converted the comment card!"); + } +}