use of com.google.cloud.translate.v3.TranslationServiceClient in project java-translate by googleapis.
the class TranslateTextWithGlossary method translateTextWithGlossary.
// Translates a given text using a glossary.
public static void translateTextWithGlossary(String projectId, String sourceLanguage, String targetLanguage, String text, String glossaryId) throws IOException {
// the "close" method on the client to safely clean up any remaining background resources.
try (TranslationServiceClient client = TranslationServiceClient.create()) {
// Supported Locations: `global`, [glossary location], or [model location]
// Glossaries must be hosted in `us-central1`
// Custom Models must use the same location as your model. (us-central1)
String location = "us-central1";
LocationName parent = LocationName.of(projectId, location);
GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);
TranslateTextGlossaryConfig glossaryConfig = TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).build();
// Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats
TranslateTextRequest request = TranslateTextRequest.newBuilder().setParent(parent.toString()).setMimeType("text/plain").setSourceLanguageCode(sourceLanguage).setTargetLanguageCode(targetLanguage).addContents(text).setGlossaryConfig(glossaryConfig).build();
TranslateTextResponse response = client.translateText(request);
// Display the translation for each input text provided
for (Translation translation : response.getGlossaryTranslationsList()) {
System.out.printf("Translated text: %s\n", translation.getTranslatedText());
}
}
}
use of com.google.cloud.translate.v3.TranslationServiceClient in project google-cloud-java by GoogleCloudPlatform.
the class TranslateSnippetsBeta method deleteGlossary.
// [END translate_translate_text_with_glossary_beta]
/**
* Deletes a glossary.
*
* @param projectId - Id of the project.
* @param location - location name.
* @param name - Glossary name.
*/
// [START translate_delete_glossary_beta]
static DeleteGlossaryResponse deleteGlossary(String projectId, String location, String name) {
try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) {
GlossaryName glossaryName = GlossaryName.newBuilder().setProject(projectId).setLocation(location).setGlossary(name).build();
// Call the API
DeleteGlossaryResponse response = translationServiceClient.deleteGlossaryAsync(glossaryName.toString()).get(300, TimeUnit.SECONDS);
System.out.format("Deleted: %s\n", response.getName());
return response;
} catch (Exception e) {
throw new RuntimeException("Couldn't create client.", e);
}
}
use of com.google.cloud.translate.v3.TranslationServiceClient in project google-cloud-java by GoogleCloudPlatform.
the class TranslateSnippetsBeta method createGlossary.
// [END translate_batch_translate_text_beta]
/**
* Creates a glossary.
*
* @param projectId - Id of the project.
* @param location - location name.
* @param name - Glossary name.
* @param gcsUri - Google Cloud Storage URI where glossary is stored in csv format.
*/
// [START translate_create_glossary_beta]
static Glossary createGlossary(String projectId, String location, String name, String gcsUri) {
try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) {
LocationName locationName = LocationName.newBuilder().setProject(projectId).setLocation(location).build();
LanguageCodesSet languageCodesSet = LanguageCodesSet.newBuilder().addLanguageCodes("en").addLanguageCodes("es").build();
GcsSource gcsSource = GcsSource.newBuilder().setInputUri(gcsUri).build();
GlossaryInputConfig glossaryInputConfig = GlossaryInputConfig.newBuilder().setGcsSource(gcsSource).build();
GlossaryName glossaryName = GlossaryName.newBuilder().setProject(projectId).setLocation(location).setGlossary(name).build();
Glossary glossary = Glossary.newBuilder().setLanguageCodesSet(languageCodesSet).setInputConfig(glossaryInputConfig).setName(glossaryName.toString()).build();
CreateGlossaryRequest request = CreateGlossaryRequest.newBuilder().setParent(locationName.toString()).setGlossary(glossary).build();
// Call the API
Glossary response = translationServiceClient.createGlossaryAsync(request).get(300, TimeUnit.SECONDS);
System.out.format("Created: %s\n", response.getName());
System.out.format("Input Uri: %s\n", response.getInputConfig().getGcsSource());
return response;
} catch (Exception e) {
throw new RuntimeException("Couldn't create client.", e);
}
}
use of com.google.cloud.translate.v3.TranslationServiceClient in project google-cloud-java by GoogleCloudPlatform.
the class TranslateSnippetsBeta method translateText.
// [END translate_detect_language_beta]
// [START translate_translate_text_beta]
/**
* Translates a given text to a target language.
*
* @param projectId - Id of the project.
* @param location - location name.
* @param text - Text for translation.
* @param sourceLanguageCode - Language code of text. e.g. "en"
* @param targetLanguageCode - Language code for translation. e.g. "sr"
*/
static TranslateTextResponse translateText(String projectId, String location, String text, String sourceLanguageCode, String targetLanguageCode) {
try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) {
LocationName locationName = LocationName.newBuilder().setProject(projectId).setLocation(location).build();
TranslateTextRequest translateTextRequest = TranslateTextRequest.newBuilder().setParent(locationName.toString()).setMimeType("text/plain").setSourceLanguageCode(sourceLanguageCode).setTargetLanguageCode(targetLanguageCode).addContents(text).build();
// Call the API
TranslateTextResponse response = translationServiceClient.translateText(translateTextRequest);
System.out.format("Translated Text: %s", response.getTranslationsList().get(0).getTranslatedText());
return response;
} catch (Exception e) {
throw new RuntimeException("Couldn't create client.", e);
}
}
use of com.google.cloud.translate.v3.TranslationServiceClient in project java-docs-samples by GoogleCloudPlatform.
the class OcrProcessImage method detectText.
// [END functions_ocr_process]
// [START functions_ocr_detect]
private void detectText(String bucket, String filename) {
logger.info("Looking for text in image " + filename);
List<AnnotateImageRequest> visionRequests = new ArrayList<>();
String gcsPath = String.format("gs://%s/%s", bucket, filename);
ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
Image img = Image.newBuilder().setSource(imgSource).build();
Feature textFeature = Feature.newBuilder().setType(Feature.Type.TEXT_DETECTION).build();
AnnotateImageRequest visionRequest = AnnotateImageRequest.newBuilder().addFeatures(textFeature).setImage(img).build();
visionRequests.add(visionRequest);
// Detect text in an image using the Cloud Vision API
AnnotateImageResponse visionResponse;
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
visionResponse = client.batchAnnotateImages(visionRequests).getResponses(0);
if (visionResponse == null || !visionResponse.hasFullTextAnnotation()) {
logger.info(String.format("Image %s contains no text", filename));
return;
}
if (visionResponse.hasError()) {
// Log error
logger.log(Level.SEVERE, "Error in vision API call: " + visionResponse.getError().getMessage());
return;
}
} catch (IOException e) {
// Log error (since IOException cannot be thrown by a Cloud Function)
logger.log(Level.SEVERE, "Error detecting text: " + e.getMessage(), e);
return;
}
String text = visionResponse.getFullTextAnnotation().getText();
logger.info("Extracted text from image: " + text);
// Detect language using the Cloud Translation API
DetectLanguageRequest languageRequest = DetectLanguageRequest.newBuilder().setParent(LOCATION_NAME).setMimeType("text/plain").setContent(text).build();
DetectLanguageResponse languageResponse;
try (TranslationServiceClient client = TranslationServiceClient.create()) {
languageResponse = client.detectLanguage(languageRequest);
} catch (IOException e) {
// Log error (since IOException cannot be thrown by a function)
logger.log(Level.SEVERE, "Error detecting language: " + e.getMessage(), e);
return;
}
if (languageResponse.getLanguagesCount() == 0) {
logger.info("No languages were detected for text: " + text);
return;
}
String languageCode = languageResponse.getLanguages(0).getLanguageCode();
logger.info(String.format("Detected language %s for file %s", languageCode, filename));
// Send a Pub/Sub translation request for every language we're going to translate to
for (String targetLanguage : TO_LANGS) {
logger.info("Sending translation request for language " + targetLanguage);
OcrTranslateApiMessage message = new OcrTranslateApiMessage(text, filename, targetLanguage);
ByteString byteStr = ByteString.copyFrom(message.toPubsubData());
PubsubMessage pubsubApiMessage = PubsubMessage.newBuilder().setData(byteStr).build();
try {
publisher.publish(pubsubApiMessage).get();
} catch (InterruptedException | ExecutionException e) {
// Log error
logger.log(Level.SEVERE, "Error publishing translation request: " + e.getMessage(), e);
return;
}
}
}
Aggregations