Search in sources :

Example 21 with TranslationServiceClient

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

the class OcrTranslateText method accept.

@Override
public void accept(Message message, Context context) {
    OcrTranslateApiMessage ocrMessage = OcrTranslateApiMessage.fromPubsubData(message.getData().getBytes(StandardCharsets.UTF_8));
    String targetLang = ocrMessage.getLang();
    logger.info("Translating text into " + targetLang);
    // Translate text to target language
    String text = ocrMessage.getText();
    TranslateTextRequest request = TranslateTextRequest.newBuilder().setParent(LOCATION_NAME).setMimeType("text/plain").setTargetLanguageCode(targetLang).addContents(text).build();
    TranslateTextResponse response;
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
        response = client.translateText(request);
    } catch (IOException e) {
        // Log error (since IOException cannot be thrown by a function)
        logger.log(Level.SEVERE, "Error translating text: " + e.getMessage(), e);
        return;
    }
    if (response.getTranslationsCount() == 0) {
        return;
    }
    String translatedText = response.getTranslations(0).getTranslatedText();
    logger.info("Translated text: " + translatedText);
    // Send translated text to (subsequent) Pub/Sub topic
    String filename = ocrMessage.getFilename();
    OcrTranslateApiMessage translateMessage = new OcrTranslateApiMessage(translatedText, filename, targetLang);
    try {
        ByteString byteStr = ByteString.copyFrom(translateMessage.toPubsubData());
        PubsubMessage pubsubApiMessage = PubsubMessage.newBuilder().setData(byteStr).build();
        publisher.publish(pubsubApiMessage).get();
        logger.info("Text translated to " + targetLang);
    } catch (InterruptedException | ExecutionException e) {
        // Log error (since these exception types cannot be thrown by a function)
        logger.log(Level.SEVERE, "Error publishing translation save request: " + e.getMessage(), e);
    }
}
Also used : TranslationServiceClient(com.google.cloud.translate.v3.TranslationServiceClient) ByteString(com.google.protobuf.ByteString) TranslateTextRequest(com.google.cloud.translate.v3.TranslateTextRequest) ByteString(com.google.protobuf.ByteString) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) TranslateTextResponse(com.google.cloud.translate.v3.TranslateTextResponse) PubsubMessage(com.google.pubsub.v1.PubsubMessage)

Example 22 with TranslationServiceClient

use of com.google.cloud.translate.v3.TranslationServiceClient in project java-translate by googleapis.

the class BatchTranslateTextWithModel method batchTranslateTextWithModel.

// Batch translate text using AutoML Translation model
public static void batchTranslateTextWithModel(String projectId, String sourceLanguage, String targetLanguage, String inputUri, String outputUri, String modelId) throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // 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);
        // Configure the source of the file from a GCS bucket
        GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build();
        // Supported Mime Types: https://cloud.google.com/translate/docs/supported-formats
        InputConfig inputConfig = InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build();
        // Configure where to store the output in a GCS bucket
        GcsDestination gcsDestination = GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build();
        OutputConfig outputConfig = OutputConfig.newBuilder().setGcsDestination(gcsDestination).build();
        // Configure the model used in the request
        String modelPath = String.format("projects/%s/locations/%s/models/%s", projectId, location, modelId);
        // Build the request that will be sent to the API
        BatchTranslateTextRequest request = BatchTranslateTextRequest.newBuilder().setParent(parent.toString()).setSourceLanguageCode(sourceLanguage).addTargetLanguageCodes(targetLanguage).addInputConfigs(inputConfig).setOutputConfig(outputConfig).putModels(targetLanguage, modelPath).build();
        // Start an asynchronous request
        OperationFuture<BatchTranslateResponse, BatchTranslateMetadata> future = client.batchTranslateTextAsync(request);
        System.out.println("Waiting for operation to complete...");
        // random number between 300 - 450 (maximum allowed seconds)
        long randomNumber = ThreadLocalRandom.current().nextInt(450, 600);
        BatchTranslateResponse response = future.get(randomNumber, TimeUnit.SECONDS);
        // Display the translation for each input text provided
        System.out.printf("Total Characters: %s\n", response.getTotalCharacters());
        System.out.printf("Translated Characters: %s\n", response.getTranslatedCharacters());
    }
}
Also used : BatchTranslateMetadata(com.google.cloud.translate.v3.BatchTranslateMetadata) TranslationServiceClient(com.google.cloud.translate.v3.TranslationServiceClient) GcsSource(com.google.cloud.translate.v3.GcsSource) OutputConfig(com.google.cloud.translate.v3.OutputConfig) BatchTranslateTextRequest(com.google.cloud.translate.v3.BatchTranslateTextRequest) InputConfig(com.google.cloud.translate.v3.InputConfig) GcsDestination(com.google.cloud.translate.v3.GcsDestination) BatchTranslateResponse(com.google.cloud.translate.v3.BatchTranslateResponse) LocationName(com.google.cloud.translate.v3.LocationName)

Example 23 with TranslationServiceClient

use of com.google.cloud.translate.v3.TranslationServiceClient in project java-translate by googleapis.

the class DeleteGlossary method deleteGlossary.

// Delete a specific glossary based on the glossary ID
public static void deleteGlossary(String projectId, String glossaryId) throws InterruptedException, ExecutionException, 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)
        GlossaryName glossaryName = GlossaryName.of(projectId, "us-central1", glossaryId);
        DeleteGlossaryRequest request = DeleteGlossaryRequest.newBuilder().setName(glossaryName.toString()).build();
        // Start an asynchronous request
        OperationFuture<DeleteGlossaryResponse, DeleteGlossaryMetadata> future = client.deleteGlossaryAsync(request);
        System.out.println("Waiting for operation to complete...");
        DeleteGlossaryResponse response = future.get();
        System.out.format("Deleted Glossary: %s\n", response.getName());
    }
}
Also used : DeleteGlossaryRequest(com.google.cloud.translate.v3.DeleteGlossaryRequest) DeleteGlossaryResponse(com.google.cloud.translate.v3.DeleteGlossaryResponse) TranslationServiceClient(com.google.cloud.translate.v3.TranslationServiceClient) GlossaryName(com.google.cloud.translate.v3.GlossaryName) DeleteGlossaryMetadata(com.google.cloud.translate.v3.DeleteGlossaryMetadata)

Example 24 with TranslationServiceClient

use of com.google.cloud.translate.v3.TranslationServiceClient in project java-translate by googleapis.

the class GetGlossary method getGlossary.

// Get a particular glossary based on the glossary ID
public static void getGlossary(String projectId, 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)
        GlossaryName glossaryName = GlossaryName.of(projectId, "us-central1", glossaryId);
        GetGlossaryRequest request = GetGlossaryRequest.newBuilder().setName(glossaryName.toString()).build();
        Glossary response = client.getGlossary(request);
        System.out.printf("Glossary name: %s\n", response.getName());
        System.out.printf("Entry count: %s\n", response.getEntryCount());
        System.out.printf("Input URI: %s\n", response.getInputConfig().getGcsSource().getInputUri());
    }
}
Also used : GetGlossaryRequest(com.google.cloud.translate.v3.GetGlossaryRequest) TranslationServiceClient(com.google.cloud.translate.v3.TranslationServiceClient) Glossary(com.google.cloud.translate.v3.Glossary) GlossaryName(com.google.cloud.translate.v3.GlossaryName)

Example 25 with TranslationServiceClient

use of com.google.cloud.translate.v3.TranslationServiceClient in project java-translate by googleapis.

the class TranslateTextWithModel method translateTextWithModel.

// Translating Text with Model
public static void translateTextWithModel(String projectId, String sourceLanguage, String targetLanguage, String text, String modelId) 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);
        String modelPath = String.format("projects/%s/locations/%s/models/%s", projectId, location, modelId);
        // 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).setModel(modelPath).build();
        TranslateTextResponse response = client.translateText(request);
        // Display the translation for each input text provided
        for (Translation translation : response.getTranslationsList()) {
            System.out.printf("Translated text: %s\n", translation.getTranslatedText());
        }
    }
}
Also used : Translation(com.google.cloud.translate.v3.Translation) TranslationServiceClient(com.google.cloud.translate.v3.TranslationServiceClient) TranslateTextRequest(com.google.cloud.translate.v3.TranslateTextRequest) TranslateTextResponse(com.google.cloud.translate.v3.TranslateTextResponse) LocationName(com.google.cloud.translate.v3.LocationName)

Aggregations

TranslationServiceClient (com.google.cloud.translate.v3.TranslationServiceClient)17 LocationName (com.google.cloud.translate.v3.LocationName)13 TranslationServiceClient (com.google.cloud.translate.v3beta1.TranslationServiceClient)12 LocationName (com.google.cloud.translate.v3beta1.LocationName)10 GlossaryName (com.google.cloud.translate.v3.GlossaryName)7 GcsSource (com.google.cloud.translate.v3.GcsSource)5 TranslateTextRequest (com.google.cloud.translate.v3.TranslateTextRequest)5 TranslateTextResponse (com.google.cloud.translate.v3.TranslateTextResponse)5 BatchTranslateMetadata (com.google.cloud.translate.v3.BatchTranslateMetadata)4 BatchTranslateResponse (com.google.cloud.translate.v3.BatchTranslateResponse)4 BatchTranslateTextRequest (com.google.cloud.translate.v3.BatchTranslateTextRequest)4 GcsDestination (com.google.cloud.translate.v3.GcsDestination)4 InputConfig (com.google.cloud.translate.v3.InputConfig)4 OutputConfig (com.google.cloud.translate.v3.OutputConfig)4 TranslateTextGlossaryConfig (com.google.cloud.translate.v3.TranslateTextGlossaryConfig)4 Translation (com.google.cloud.translate.v3.Translation)4 GlossaryName (com.google.cloud.translate.v3beta1.GlossaryName)4 Glossary (com.google.cloud.translate.v3.Glossary)3 BatchTranslateTextRequest (com.google.cloud.translate.v3beta1.BatchTranslateTextRequest)3 GcsSource (com.google.cloud.translate.v3beta1.GcsSource)3