com.google.cloud.translate.Translation Java Examples

The following examples show how to use com.google.cloud.translate.Translation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Translate.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Translate the source text from source to target language.
 *
 * @param sourceText source text to be translated
 * @param sourceLang source language of the text
 * @param targetLang target language of translated text
 * @return source text translated into target language.
 */
public static String translateText(
    String sourceText,
    String sourceLang,
    String targetLang) {
  if (Strings.isNullOrEmpty(sourceLang)
      || Strings.isNullOrEmpty(targetLang)
      || sourceLang.equals(targetLang)) {
    return sourceText;
  }
  com.google.cloud.translate.Translate translate = createTranslateService();
  TranslateOption srcLang = TranslateOption.sourceLanguage(sourceLang);
  TranslateOption tgtLang = TranslateOption.targetLanguage(targetLang);

  Translation translation = translate.translate(sourceText, srcLang, tgtLang);
  return translation.getTranslatedText();
}
 
Example #2
Source File: DetectLanguageAndTranslate.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #3
Source File: ITTranslateSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testTranslateTextList() {
  // SNIPPET translateTexts
  List<String> texts = new LinkedList<>();
  texts.add("Hello, World!");
  texts.add("¡Hola Mundo!");
  List<Translation> translations = translate.translate(texts);
  // SNIPPET translateTexts

  Translation translation = translations.get(0);
  assertEquals("Hello, World!", translation.getTranslatedText());
  assertEquals("en", translation.getSourceLanguage());
  translation = translations.get(1);
  assertEquals("Hello World!", translation.getTranslatedText());
  assertEquals("es", translation.getSourceLanguage());
}
 
Example #4
Source File: ITTranslateSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testTranslateTextWithModel() {
  // [START translate_text_with_model]
  Translation translation =
      translate.translate(
          "Hola Mundo!",
          Translate.TranslateOption.sourceLanguage("es"),
          Translate.TranslateOption.targetLanguage("de"),
          // Use "base" for standard edition, "nmt" for the premium model.
          Translate.TranslateOption.model("nmt"));

  System.out.printf("TranslatedText:\nText: %s\n", translation.getTranslatedText());
  // [END translate_text_with_model]
  assertEquals("Hallo Welt!", translation.getTranslatedText());
  assertEquals("es", translation.getSourceLanguage());
}
 
Example #5
Source File: TranslateWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {
    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String toTranslate = (String) workItem.getParameter("ToTranslate");
        String sourceLang = (String) workItem.getParameter("SourceLang");
        String targetLang = (String) workItem.getParameter("TargetLang");
        Map<String, Object> results = new HashMap<String, Object>();

        translationService = googleTranslateAuth.getTranslationService(apiKey);

        TranslateOption srcLangOption = TranslateOption.sourceLanguage(sourceLang);
        TranslateOption targetLangOption = TranslateOption.targetLanguage(targetLang);

        Translation translation = translationService.translate(toTranslate,
                                                               srcLangOption,
                                                               targetLangOption);

        if (translation != null && translation.getTranslatedText() != null) {
            results.put(RESULTS_TRANSLATION,
                        translation.getTranslatedText());
        } else {
            logger.error("Could not translate provided text.");
            throw new IllegalArgumentException("Could not translate provided text.");
        }

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        logger.error("Error executing workitem: " + e.getMessage());
        handleException(e);
    }
}
 
Example #6
Source File: QuickstartSample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {
  // Instantiates a client
  Translate translate = TranslateOptions.getDefaultInstance().getService();

  // The text to translate
  String text = "Hello, world!";

  // Translates some text into Russian
  Translation translation =
      translate.translate(
          text, TranslateOption.sourceLanguage("en"), TranslateOption.targetLanguage("ru"));

  System.out.printf("Text: %s%n", text);
  System.out.printf("Translation: %s%n", translation.getTranslatedText());
}
 
Example #7
Source File: TranslateExample.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Translate translate, List<String> texts) {
  List<Translation> translations = translate.translate(texts);
  if (texts.size() == 1) {
    System.out.println("Translation is:");
  } else {
    System.out.println("Translations are:");
  }
  for (Translation translation : translations) {
    System.out.println(translation);
  }
}
 
Example #8
Source File: ITTranslateSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testTranslateTextListWithOptions() {
  // SNIPPET translateTextsWithOptions
  List<String> texts = new LinkedList<>();
  texts.add("¡Hola Mundo!");
  List<Translation> translations =
      translate.translate(
          texts,
          Translate.TranslateOption.sourceLanguage("es"),
          Translate.TranslateOption.targetLanguage("de"));
  // SNIPPET translateTextsWithOptions
  Translation translation = translations.get(0);
  assertEquals("Hallo Welt!", translation.getTranslatedText());
  assertEquals("es", translation.getSourceLanguage());
}
 
Example #9
Source File: ITTranslateSnippets.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testTranslateText() {
  // [START translate_translate_text]
  // TODO(developer): Uncomment these lines.
  // import com.google.cloud.translate.*;
  // Translate translate = TranslateOptions.getDefaultInstance().getService();

  Translation translation = translate.translate("¡Hola Mundo!");
  System.out.printf("Translated Text:\n\t%s\n", translation.getTranslatedText());
  // [END translate_translate_text]
  assertEquals("Hello World!", translation.getTranslatedText());
  assertEquals("es", translation.getSourceLanguage());
}
 
Example #10
Source File: Translator.java    From dualsub with GNU General Public License v3.0 5 votes vote down vote up
public String translate(String text, String languageFrom,
		String languageTo) {
	Translation translation = translate.translate(text,
			TranslateOption.sourceLanguage(languageFrom),
			TranslateOption.targetLanguage(languageTo));

	String translatedText = translation.getTranslatedText();
	log.trace("Translating {} [{}] to [{}] ... result={}", text,
			languageFrom, languageTo, translatedText);
	return translatedText;
}
 
Example #11
Source File: Translator.java    From dualsub with GNU General Public License v3.0 5 votes vote down vote up
public List<String> translate(List<String> text, String languageFrom,
		String languageTo) {
	List<Translation> translation = translate.translate(text,
			TranslateOption.sourceLanguage(languageFrom),
			TranslateOption.targetLanguage(languageTo));

	List<String> out = new ArrayList<String>();
	for (Translation t : translation) {
		String translatedText = t.getTranslatedText();
		out.add(translatedText);
		log.trace("Translating {} [{}] to [{}] ... result={}", text,
				languageFrom, languageTo, translatedText);
	}
	return out;
}
 
Example #12
Source File: TranslateServlet.java    From getting-started-java with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
  }
}