Search in sources :

Example 6 with Translate

use of com.google.cloud.translate.Translate in project structr by structr.

the class TranslateFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) {
    if (arrayHasLengthAndAllElementsNotNull(sources, 3)) {
        try {
            final String gctAPIKey = TranslationModule.TranslationAPIKey.getValue();
            if (gctAPIKey == null) {
                logger.error("Google Cloud Translation API Key not configured in structr.conf");
                return "";
            }
            final String text = sources[0].toString();
            final String sourceLanguage = sources[1].toString();
            final String targetLanguage = sources[2].toString();
            final Translate translate = TranslateOptions.builder().apiKey(gctAPIKey).build().service();
            Translation translation = translate.translate(text, TranslateOption.sourceLanguage(sourceLanguage), TranslateOption.targetLanguage(targetLanguage));
            return translation.translatedText();
        } catch (TranslateException te) {
            logger.error("TranslateException: {}", te.getLocalizedMessage());
        } catch (Throwable t) {
            logException(t, "{}: Exception for parameter: {}", new Object[] { getName(), getParametersAsString(sources) });
        }
        return "";
    } else {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
    }
    return usage(ctx.isJavaScriptContext());
}
Also used : Translation(com.google.cloud.translate.Translation) TranslateException(com.google.cloud.translate.TranslateException) Translate(com.google.cloud.translate.Translate)

Example 7 with Translate

use of com.google.cloud.translate.Translate in project google-cloud-java by GoogleCloudPlatform.

the class TranslateExample method main.

@SuppressWarnings("unchecked")
public static void main(String... args) throws Exception {
    if (args.length < 1) {
        System.out.println("Missing required action");
        printUsage();
        return;
    }
    TranslateOptions.Builder optionsBuilder = TranslateOptions.newBuilder();
    TranslateAction action;
    String actionName;
    if (args.length >= 3 && !ACTIONS.containsKey(args[1])) {
        optionsBuilder.setApiKey(args[0]);
        actionName = args[2];
        optionsBuilder.setTargetLanguage(args[1]);
        args = Arrays.copyOfRange(args, 3, args.length);
    } else if (args.length >= 2 && !ACTIONS.containsKey(args[0])) {
        optionsBuilder.setTargetLanguage(args[0]);
        actionName = args[1];
        args = Arrays.copyOfRange(args, 2, args.length);
    } else {
        actionName = args[0];
        args = Arrays.copyOfRange(args, 1, args.length);
    }
    action = ACTIONS.get(actionName);
    if (action == null) {
        System.out.println("Unrecognized action.");
        printUsage();
        return;
    }
    Object arg;
    try {
        arg = action.parse(args);
    } catch (IllegalArgumentException ex) {
        System.out.printf("Invalid input for action '%s'. %s%n", actionName, ex.getMessage());
        System.out.printf("Expected: %s%n", action.params());
        return;
    } catch (Exception ex) {
        System.out.println("Failed to parse arguments.");
        ex.printStackTrace();
        return;
    }
    Translate translate = optionsBuilder.build().getService();
    action.run(translate, arg);
}
Also used : TranslateOptions(com.google.cloud.translate.TranslateOptions) Translate(com.google.cloud.translate.Translate)

Example 8 with Translate

use of com.google.cloud.translate.Translate in project google-cloud-java by GoogleCloudPlatform.

the class DetectLanguageAndTranslate method main.

public static void main(String... args) {
    // Create a service object
    // 
    // If no explicit credentials or API key are set, requests are authenticated using Application
    // Default Credentials if available; otherwise, using an API key from the GOOGLE_API_KEY
    // environment variable
    Translate translate = TranslateOptions.getDefaultInstance().getService();
    // Text of an "unknown" language to detect and then translate into English
    final String mysteriousText = "Hola Mundo";
    // Detect the language of the mysterious text
    Detection detection = translate.detect(mysteriousText);
    String detectedLanguage = detection.getLanguage();
    // Translate the mysterious text to English
    Translation translation = translate.translate(mysteriousText, TranslateOption.sourceLanguage(detectedLanguage), TranslateOption.targetLanguage("en"));
    System.out.println(translation.getTranslatedText());
}
Also used : Translation(com.google.cloud.translate.Translation) Detection(com.google.cloud.translate.Detection) Translate(com.google.cloud.translate.Translate)

Example 9 with Translate

use of com.google.cloud.translate.Translate in project java-docs-samples by GoogleCloudPlatform.

the class TranslateText method translateTextWithOptionsAndModel.

/**
 * Translate the source text from source to target language.
 * Make sure that your project is whitelisted.
 *
 * @param sourceText source text to be translated
 * @param sourceLang source language of the text
 * @param targetLang target language of translated text
 * @param out print stream
 */
public static void translateTextWithOptionsAndModel(String sourceText, String sourceLang, String targetLang, PrintStream out) {
    Translate translate = createTranslateService();
    TranslateOption srcLang = TranslateOption.sourceLanguage(sourceLang);
    TranslateOption tgtLang = TranslateOption.targetLanguage(targetLang);
    // Use translate `model` parameter with `base` and `nmt` options.
    TranslateOption model = TranslateOption.model("nmt");
    Translation translation = translate.translate(sourceText, srcLang, tgtLang, model);
    out.printf("Source Text:\n\tLang: %s, Text: %s\n", sourceLang, sourceText);
    out.printf("TranslatedText:\n\tLang: %s, Text: %s\n", targetLang, translation.getTranslatedText());
}
Also used : Translation(com.google.cloud.translate.Translation) TranslateOption(com.google.cloud.translate.Translate.TranslateOption) Translate(com.google.cloud.translate.Translate)

Example 10 with Translate

use of com.google.cloud.translate.Translate in project getting-started-java by GoogleCloudPlatform.

the class TranslateServlet method doPost.

// [END getting_started_background_app_list]
/**
 * Handle a posted message from Pubsub.
 *
 * @param req The message Pubsub posts to this process.
 * @param resp Not used.
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    // Block requests that don't contain the proper verification token.
    String pubsubVerificationToken = PUBSUB_VERIFICATION_TOKEN;
    if (req.getParameter("token").compareTo(pubsubVerificationToken) != 0) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    // [START getting_started_background_translate_string]
    String body = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
    PubSubMessage pubsubMessage = gson.fromJson(body, PubSubMessage.class);
    TranslateMessage message = pubsubMessage.getMessage();
    // Use Translate service client to translate the message.
    Translate translate = (Translate) this.getServletContext().getAttribute("translate");
    message.setData(decode(message.getData()));
    Translation translation = translate.translate(message.getData(), Translate.TranslateOption.sourceLanguage(message.getAttributes().getSourceLang()), Translate.TranslateOption.targetLanguage(message.getAttributes().getTargetLang()));
    // [END getting_started_background_translate_string]
    message.setTranslatedText(translation.getTranslatedText());
    try {
        // [START getting_started_background_translate]
        // Use Firestore service client to store the translation in Firestore.
        Firestore firestore = (Firestore) this.getServletContext().getAttribute("firestore");
        CollectionReference translations = firestore.collection("translations");
        ApiFuture<WriteResult> setFuture = translations.document().set(message, SetOptions.merge());
        setFuture.get();
        resp.getWriter().write(translation.getTranslatedText());
    // [END getting_started_background_translate]
    } catch (InterruptedException | ExecutionException e) {
        throw new ServletException("Exception storing data in Firestore.", e);
    }
}
Also used : Translation(com.google.cloud.translate.Translation) CollectionReference(com.google.cloud.firestore.CollectionReference) ServletException(javax.servlet.ServletException) WriteResult(com.google.cloud.firestore.WriteResult) Firestore(com.google.cloud.firestore.Firestore) PubSubMessage(com.getstarted.background.objects.PubSubMessage) TranslateMessage(com.getstarted.background.objects.TranslateMessage) ExecutionException(java.util.concurrent.ExecutionException) Translate(com.google.cloud.translate.Translate)

Aggregations

Translate (com.google.cloud.translate.Translate)11 Translation (com.google.cloud.translate.Translation)7 Firestore (com.google.cloud.firestore.Firestore)2 Detection (com.google.cloud.translate.Detection)2 TranslateOption (com.google.cloud.translate.Translate.TranslateOption)2 PubSubMessage (com.getstarted.background.objects.PubSubMessage)1 TranslateMessage (com.getstarted.background.objects.TranslateMessage)1 CollectionReference (com.google.cloud.firestore.CollectionReference)1 WriteResult (com.google.cloud.firestore.WriteResult)1 Publisher (com.google.cloud.pubsub.v1.Publisher)1 Language (com.google.cloud.translate.Language)1 LanguageListOption (com.google.cloud.translate.Translate.LanguageListOption)1 TranslateException (com.google.cloud.translate.TranslateException)1 TranslateOptions (com.google.cloud.translate.TranslateOptions)1 TopicName (com.google.pubsub.v1.TopicName)1 IOException (java.io.IOException)1 ExecutionException (java.util.concurrent.ExecutionException)1 ServletException (javax.servlet.ServletException)1