diff --git a/pom.xml b/pom.xml index 47dbb39c5..a9e30b625 100644 --- a/pom.xml +++ b/pom.xml @@ -565,6 +565,11 @@ org.flywaydb flyway-mysql + + org.jsoup + jsoup + 1.24.1 + UTF-8 diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/author/project/TranslatableText.java b/src/main/java/org/wise/portal/presentation/web/controllers/author/project/TranslatableText.java index b77090b3a..d33ebfd26 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/author/project/TranslatableText.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/author/project/TranslatableText.java @@ -1,5 +1,8 @@ package org.wise.portal.presentation.web.controllers.author.project; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.Getter; @Getter @@ -7,11 +10,22 @@ public class TranslatableText { protected String srcLangCode; protected String targetLangCode; protected String srcText; + protected String contentType; public TranslatableText(String srcLang, String targetLang, String srcText) { + this(srcLang, targetLang, srcText, "text"); + } + + @JsonCreator + public TranslatableText( + @JsonProperty("srcLang") String srcLang, + @JsonProperty("targetLang") String targetLang, + @JsonProperty("srcText") String srcText, + @JsonProperty("contentType") String contentType) { this.srcLangCode = this.convertLanguageToAWSCode(srcLang); this.targetLangCode = this.convertLanguageToAWSCode(targetLang); this.srcText = srcText; + this.contentType = contentType == null ? "text" : contentType; } private String convertLanguageToAWSCode(String language) throws IllegalArgumentException { diff --git a/src/main/java/org/wise/portal/presentation/web/controllers/author/project/TranslationSuggestionAPIController.java b/src/main/java/org/wise/portal/presentation/web/controllers/author/project/TranslationSuggestionAPIController.java index 08d76ac9e..8aec27890 100644 --- a/src/main/java/org/wise/portal/presentation/web/controllers/author/project/TranslationSuggestionAPIController.java +++ b/src/main/java/org/wise/portal/presentation/web/controllers/author/project/TranslationSuggestionAPIController.java @@ -1,7 +1,11 @@ package org.wise.portal.presentation.web.controllers.author.project; import java.io.IOException; +import java.util.List; +import org.jsoup.nodes.Element; +import org.jsoup.nodes.Node; +import org.jsoup.parser.Parser; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.security.access.annotation.Secured; @@ -14,8 +18,12 @@ import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.translate.TranslateClient; +import software.amazon.awssdk.services.translate.model.Document; +import software.amazon.awssdk.services.translate.model.TranslateDocumentRequest; +import software.amazon.awssdk.services.translate.model.TranslateDocumentResponse; import software.amazon.awssdk.services.translate.model.TranslateTextRequest; import software.amazon.awssdk.services.translate.model.TranslateTextResponse; @@ -34,8 +42,9 @@ public class TranslationSuggestionAPIController { private String region; @PostMapping - protected String getSuggestedTranslation(Authentication auth, @RequestBody TranslatableText translatableText) + protected String getSuggestedTranslation(Authentication auth, @RequestBody TranslatableText translatableText) throws IOException, IllegalArgumentException, ResponseStatusException { + validateContentType(translatableText); if (accessKey.equals("") || secretKey.equals("") || region.equals("")) { throw new ResponseStatusException( HttpStatus.INTERNAL_SERVER_ERROR, @@ -43,12 +52,33 @@ protected String getSuggestedTranslation(Authentication auth, @RequestBody Trans ); } else { TranslateClient translateClient = buildTranslateClient(); - TranslateTextRequest request = buildTranslateTextRequest(translatableText); - return this.translateText(translateClient, request); + if (translatableText.getContentType().equals("html")) { + TranslateDocumentRequest request = buildTranslateDocumentRequest(translatableText); + String translatedHtml = this.translateDocument(translateClient, request); + return this.translateLinkTextAttributes(translateClient, translatableText, translatedHtml); + } else { + TranslateTextRequest request = buildTranslateTextRequest(translatableText); + return this.translateText(translateClient, request); + } + } + } + + private void validateContentType(TranslatableText translatableText) throws ResponseStatusException { + String contentType = translatableText.getContentType(); + if (!contentType.equals("text") && !contentType.equals("html")) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unsupported content type: " + contentType); + } else if (contentType.equals("html") && nonEnglishTranslation(translatableText)) { + throw new ResponseStatusException( + HttpStatus.BAD_REQUEST, + "HTML translation requires English as either the source or target language"); } } - private TranslateClient buildTranslateClient() { + private boolean nonEnglishTranslation(TranslatableText translatableText) { + return !translatableText.getSrcLangCode().equals("en") && !translatableText.getTargetLangCode().equals("en"); + } + + protected TranslateClient buildTranslateClient() { AwsBasicCredentials credentials = AwsBasicCredentials.create(accessKey, secretKey); return TranslateClient.builder() .region(Region.of(region)) @@ -57,11 +87,27 @@ private TranslateClient buildTranslateClient() { } private TranslateTextRequest buildTranslateTextRequest(TranslatableText translatableText) { + return buildTranslateTextRequest(translatableText.getSrcText(), translatableText); + } + + private TranslateTextRequest buildTranslateTextRequest(String text, TranslatableText translatableText) { return TranslateTextRequest.builder() - .text(translatableText.getSrcText()) - .sourceLanguageCode(translatableText.getSrcLangCode()) - .targetLanguageCode(translatableText.getTargetLangCode()) - .build(); + .text(text) + .sourceLanguageCode(translatableText.getSrcLangCode()) + .targetLanguageCode(translatableText.getTargetLangCode()) + .build(); + } + + private TranslateDocumentRequest buildTranslateDocumentRequest(TranslatableText translatableText) { + Document document = Document.builder() + .content(SdkBytes.fromUtf8String(translatableText.getSrcText())) + .contentType("text/html") + .build(); + return TranslateDocumentRequest.builder() + .document(document) + .sourceLanguageCode(translatableText.getSrcLangCode()) + .targetLanguageCode(translatableText.getTargetLangCode()) + .build(); } private String translateText(TranslateClient client, TranslateTextRequest request) throws ResponseStatusException { @@ -76,4 +122,80 @@ private String translateText(TranslateClient client, TranslateTextRequest reques } return textResponse.translatedText(); } + + private String translateDocument(TranslateClient client, TranslateDocumentRequest request) + throws ResponseStatusException { + TranslateDocumentResponse documentResponse; + try { + documentResponse = client.translateDocument(request); + } catch (Exception e) { + throw new ResponseStatusException( + HttpStatus.INTERNAL_SERVER_ERROR, + "Translation failed"); + } + return documentResponse.translatedDocument().content().asUtf8String(); + } + + private String translateLinkTextAttributes(TranslateClient client, TranslatableText translatableText, + String translatedHtml) { + List sourceValues = getLinkTextValues(translatableText.getSrcText()); + if (sourceValues.isEmpty()) { + return translatedHtml; + } + Element translatedDocument = parseHtmlFragment(translatedHtml); + List translatedLinks = getLinksWithText(translatedDocument); + if (translatedLinks.size() != sourceValues.size()) { + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, + "Translation failed to preserve link-text attributes"); + } + List translatedValues = translateLinkTextValues(client, translatableText, sourceValues); + replaceLinkTextValues(translatedLinks, translatedValues); + return translatedDocument.html(); + } + + private List getLinkTextValues(String html) { + return getLinksWithText(parseHtmlFragment(html)).stream() + .map(link -> link.attr("link-text")) + .toList(); + } + + private List getLinksWithText(Element html) { + return html.getElementsByTag("wiselink").stream() + .filter(link -> link.hasAttr("link-text")) + .toList(); + } + + private Element parseHtmlFragment(String html) { + Element root = new Element("wise-root"); + for (Node node : Parser.parseFragment(html, root, "")) { + root.appendChild(node); + } + return root; + } + + private List translateLinkTextValues(TranslateClient client, TranslatableText translatableText, + List sourceValues) { + List translatedValues = translateValues(client, translatableText, sourceValues); + if (translatedValues.size() == sourceValues.size()) { + return translatedValues; + } else { + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, + "Translation failed to preserve link-text lines"); + } + } + + private List translateValues(TranslateClient client, + TranslatableText translatableText, List sourceValues) { + String joinedSourceValues = String.join("\n", sourceValues); + String joinedTranslatedValues = + translateText(client, buildTranslateTextRequest(joinedSourceValues, translatableText)); + List translatedValues = List.of(joinedTranslatedValues.split("\\R", -1)); + return translatedValues; + } + + private void replaceLinkTextValues(List translatedLinks, List translatedValues) { + for (int i = 0; i < translatedValues.size(); i++) { + translatedLinks.get(i).attr("link-text", translatedValues.get(i)); + } + } } diff --git a/src/test/java/org/wise/portal/presentation/web/controllers/author/project/TranslationSuggestionAPIControllerTest.java b/src/test/java/org/wise/portal/presentation/web/controllers/author/project/TranslationSuggestionAPIControllerTest.java index 8a99d888a..5663b397b 100644 --- a/src/test/java/org/wise/portal/presentation/web/controllers/author/project/TranslationSuggestionAPIControllerTest.java +++ b/src/test/java/org/wise/portal/presentation/web/controllers/author/project/TranslationSuggestionAPIControllerTest.java @@ -1,31 +1,220 @@ package org.wise.portal.presentation.web.controllers.author.project; -import org.easymock.EasyMockExtension; -import org.easymock.TestSubject; +import static org.easymock.EasyMock.capture; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.newCapture; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.easymock.Capture; +import org.easymock.EasyMockExtension; +import org.jsoup.Jsoup; +import org.jsoup.nodes.Element; +import org.jsoup.select.Elements; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.server.ResponseStatusException; import org.wise.portal.presentation.web.controllers.APIControllerTest; +import com.fasterxml.jackson.databind.ObjectMapper; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.services.translate.TranslateClient; +import software.amazon.awssdk.services.translate.model.Document; +import software.amazon.awssdk.services.translate.model.TranslateDocumentRequest; +import software.amazon.awssdk.services.translate.model.TranslateDocumentResponse; +import software.amazon.awssdk.services.translate.model.TranslateTextRequest; +import software.amazon.awssdk.services.translate.model.TranslateTextResponse; +import software.amazon.awssdk.services.translate.model.TranslatedDocument; + @ExtendWith(EasyMockExtension.class) public class TranslationSuggestionAPIControllerTest extends APIControllerTest { - @TestSubject - private final TranslationSuggestionAPIController controller = new TranslationSuggestionAPIController(); + private static final String TRANSLATABLE_TEXT_JSON = + "{\"srcLang\":\"Spanish\",\"targetLang\":\"Italian\",\"srcText\":\"texto para traducir\"}"; + + @Test + public void getSuggestedTranslation_UsesTextTranslationWhenContentTypeIsOmitted() throws Exception { + TranslateClient translateClient = createMock(TranslateClient.class); + Capture requestCapture = newCapture(); + expect(translateClient.translateText(capture(requestCapture))) + .andReturn(TranslateTextResponse.builder().translatedText("testo tradotto").build()); + replay(translateClient); + + TranslationSuggestionAPIController controller = createController(translateClient); + TranslatableText request = readRequest(TRANSLATABLE_TEXT_JSON); + + assertEquals("text", request.getContentType()); + assertEquals("testo tradotto", controller.getSuggestedTranslation(teacherAuth, request)); + assertEquals("texto para traducir", requestCapture.getValue().text()); + assertEquals("es-MX", requestCapture.getValue().sourceLanguageCode()); + assertEquals("it", requestCapture.getValue().targetLanguageCode()); + verify(translateClient); + } + + @Test + public void getSuggestedTranslation_UsesDocumentTranslationWhenHtmlHasNoLinkText() throws Exception { + assertHtmlTranslation( + "{\"srcLang\":\"English\",\"targetLang\":\"Spanish\",\"srcText\":\"

Hello

\"," + + "\"contentType\":\"html\"}", + "

Hello

", + "

Hola

", + "en", + "es-MX"); + } + + @Test + public void getSuggestedTranslation_TranslatesHtmlIntoEnglish() throws Exception { + assertHtmlTranslation( + "{\"srcLang\":\"Italian\",\"targetLang\":\"English\",\"srcText\":\"

Ciao

\"," + + "\"contentType\":\"html\"}", + "

Ciao

", + "

Hello

", + "it", + "en"); + } + + @Test + public void getSuggestedTranslation_TranslatesLinkTextAttributesAndPreservesHtml() throws Exception { + String sourceHtml = + "

Visit then " + + ".

"; + String translatedDocumentHtml = + "

Visita luego " + + ".

"; + TranslateClient translateClient = createMock(TranslateClient.class); + Capture documentRequestCapture = newCapture(); + Capture textRequestCapture = newCapture(); + expect(translateClient.translateDocument(capture(documentRequestCapture))) + .andReturn(TranslateDocumentResponse.builder() + .translatedDocument(TranslatedDocument.builder() + .content(SdkBytes.fromUtf8String(translatedDocumentHtml)) + .build()) + .build()); + expect(translateClient.translateText(capture(textRequestCapture))) + .andReturn(TranslateTextResponse.builder() + .translatedText("descripción del curso\nsiguiente paso") + .build()); + replay(translateClient); + + TranslationSuggestionAPIController controller = createController(translateClient); + TranslatableText request = new TranslatableText("English", "Spanish", sourceHtml, "html"); + + String translatedHtml = controller.getSuggestedTranslation(teacherAuth, request); + org.jsoup.nodes.Document translatedDocument = Jsoup.parseBodyFragment(translatedHtml); + + assertEquals(1, translatedDocument.select("p").size()); + assertEquals("Visita luego .", translatedDocument.selectFirst("p").text()); + + Elements translatedLinks = translatedDocument.select("wiselink[link-text]"); + Element courseOverviewLink = translatedLinks.get(0); + Element nextStepLink = translatedLinks.get(1); + assertEquals(2, translatedLinks.size()); + assertEquals("keep-me", courseOverviewLink.attr("id")); + assertEquals("descripción del curso", courseOverviewLink.attr("link-text")); + assertEquals("keep-me-too", nextStepLink.attr("id")); + assertEquals("siguiente paso", nextStepLink.attr("link-text")); + assertEquals("course & overview\nnext step", textRequestCapture.getValue().text()); + verify(translateClient); + } @Test - public void getSuggestedTranslation_ThrowIfPropertiesEmpty() throws Exception { + public void getSuggestedTranslation_RejectsHtmlWithoutEnglishLanguage() throws Exception { + assertRequestRejected( + "{\"srcLang\":\"Spanish\",\"targetLang\":\"Italian\",\"srcText\":\"texto\"," + + "\"contentType\":\"html\"}", + "HTML translation requires English as either the source or target language"); + } + + @Test + public void getSuggestedTranslation_RejectsUnsupportedContentType() throws Exception { + assertRequestRejected( + "{\"srcLang\":\"English\",\"targetLang\":\"Spanish\",\"srcText\":\"Hello\"," + + "\"contentType\":\"xml\"}", + "Unsupported content type: xml"); + } + + @Test + public void getSuggestedTranslation_ThrowsIfPropertiesEmpty() throws Exception { + TranslateClient translateClient = createMock(TranslateClient.class); + TranslationSuggestionAPIController controller = new TestTranslationSuggestionAPIController(translateClient); ReflectionTestUtils.setField(controller, "accessKey", ""); ReflectionTestUtils.setField(controller, "secretKey", ""); ReflectionTestUtils.setField(controller, "region", ""); - TranslatableText tt = new TranslatableText("English", "Spanish", "text to translate"); + TranslatableText request = readRequest(TRANSLATABLE_TEXT_JSON); + + ResponseStatusException exception = assertThrows(ResponseStatusException.class, + () -> controller.getSuggestedTranslation(teacherAuth, request)); - assertThrows(ResponseStatusException.class, () -> { - controller.getSuggestedTranslation(teacherAuth, tt); - }); + assertEquals(500, exception.getStatusCode().value()); } -} + private void assertHtmlTranslation(String requestJson, String sourceHtml, String translatedHtml, + String sourceLanguageCode, String targetLanguageCode) throws Exception { + TranslateClient translateClient = createMock(TranslateClient.class); + Capture requestCapture = newCapture(); + expect(translateClient.translateDocument(capture(requestCapture))) + .andReturn(TranslateDocumentResponse.builder() + .translatedDocument(TranslatedDocument.builder() + .content(SdkBytes.fromUtf8String(translatedHtml)) + .build()) + .build()); + replay(translateClient); + + TranslationSuggestionAPIController controller = createController(translateClient); + TranslatableText request = readRequest(requestJson); + + assertEquals(translatedHtml, controller.getSuggestedTranslation(teacherAuth, request)); + Document document = requestCapture.getValue().document(); + assertEquals("text/html", document.contentType()); + assertEquals(sourceHtml, document.content().asUtf8String()); + assertEquals(sourceLanguageCode, requestCapture.getValue().sourceLanguageCode()); + assertEquals(targetLanguageCode, requestCapture.getValue().targetLanguageCode()); + verify(translateClient); + } + + private void assertRequestRejected(String requestJson, String expectedReason) throws Exception { + TranslateClient translateClient = createMock(TranslateClient.class); + replay(translateClient); + TranslationSuggestionAPIController controller = createController(translateClient); + TranslatableText request = readRequest(requestJson); + + ResponseStatusException exception = assertThrows(ResponseStatusException.class, + () -> controller.getSuggestedTranslation(teacherAuth, request)); + + assertEquals(400, exception.getStatusCode().value()); + assertEquals(expectedReason, exception.getReason()); + verify(translateClient); + } + + private TranslationSuggestionAPIController createController(TranslateClient translateClient) { + TranslationSuggestionAPIController controller = new TestTranslationSuggestionAPIController(translateClient); + ReflectionTestUtils.setField(controller, "accessKey", "access-key"); + ReflectionTestUtils.setField(controller, "secretKey", "secret-key"); + ReflectionTestUtils.setField(controller, "region", "us-east-1"); + return controller; + } + + private TranslatableText readRequest(String json) throws Exception { + return new ObjectMapper().readValue(json, TranslatableText.class); + } + + private static class TestTranslationSuggestionAPIController extends TranslationSuggestionAPIController { + + private final TranslateClient translateClient; + + private TestTranslationSuggestionAPIController(TranslateClient translateClient) { + this.translateClient = translateClient; + } + + @Override + protected TranslateClient buildTranslateClient() { + return translateClient; + } + } +}