Search in sources :

Example 1 with GcsDestination

use of com.google.cloud.aiplatform.v1.GcsDestination in project google-cloud-java by GoogleCloudPlatform.

the class TranslateSnippetsBeta method batchTranslateText.

// [END translate_translate_text_beta]
/**
 * Translates a batch of texts on GCS and stores the result in a GCS location.
 *
 * @param projectId - Id of the project.
 * @param location - location name.
 * @param sourceUri - Google Cloud Storage URI. Location where text is stored.
 * @param destinationUri - Google Cloud Storage URI where result will be stored.
 */
// [START translate_batch_translate_text_beta]
static BatchTranslateResponse batchTranslateText(String projectId, String location, String sourceUri, String destinationUri) {
    try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) {
        LocationName locationName = LocationName.newBuilder().setProject(projectId).setLocation(location).build();
        GcsSource gcsSource = GcsSource.newBuilder().setInputUri(sourceUri).build();
        InputConfig inputConfig = InputConfig.newBuilder().setGcsSource(gcsSource).setMimeType("text/plain").build();
        GcsDestination gcsDestination = GcsDestination.newBuilder().setOutputUriPrefix(destinationUri).build();
        OutputConfig outputConfig = OutputConfig.newBuilder().setGcsDestination(gcsDestination).build();
        BatchTranslateTextRequest batchTranslateTextRequest = BatchTranslateTextRequest.newBuilder().setParent(locationName.toString()).setSourceLanguageCode("en").addTargetLanguageCodes("sr").addInputConfigs(inputConfig).setOutputConfig(outputConfig).build();
        // Call the API
        BatchTranslateResponse response = translationServiceClient.batchTranslateTextAsync(batchTranslateTextRequest).get(300, TimeUnit.SECONDS);
        System.out.printf("Total Characters: %d\n", response.getTotalCharacters());
        System.out.printf("Translated Characters: %d\n", response.getTranslatedCharacters());
        return response;
    } catch (Exception e) {
        throw new RuntimeException("Couldn't create client.", e);
    }
}
Also used : TranslationServiceClient(com.google.cloud.translate.v3beta1.TranslationServiceClient) GcsSource(com.google.cloud.translate.v3beta1.GcsSource) OutputConfig(com.google.cloud.translate.v3beta1.OutputConfig) BatchTranslateTextRequest(com.google.cloud.translate.v3beta1.BatchTranslateTextRequest) InputConfig(com.google.cloud.translate.v3beta1.InputConfig) GlossaryInputConfig(com.google.cloud.translate.v3beta1.GlossaryInputConfig) GcsDestination(com.google.cloud.translate.v3beta1.GcsDestination) BatchTranslateResponse(com.google.cloud.translate.v3beta1.BatchTranslateResponse) LocationName(com.google.cloud.translate.v3beta1.LocationName)

Example 2 with GcsDestination

use of com.google.cloud.aiplatform.v1.GcsDestination in project spring-cloud-gcp by spring-cloud.

the class DocumentOcrTemplate method runOcrForDocument.

/**
 * Runs OCR processing for a specified {@code document} and generates OCR output files
 * under the path specified by {@code outputFilePathPrefix}.
 *
 * <p>
 * For example, if you specify an {@code outputFilePathPrefix} of
 * "gs://bucket_name/ocr_results/myDoc_", all the output files of OCR processing will be
 * saved under prefix, such as:
 *
 * <ul>
 * <li>gs://bucket_name/ocr_results/myDoc_output-1-to-5.json
 * <li>gs://bucket_name/ocr_results/myDoc_output-6-to-10.json
 * <li>gs://bucket_name/ocr_results/myDoc_output-11-to-15.json
 * </ul>
 *
 * <p>
 * Note: OCR processing operations may take several minutes to complete, so it may not be
 * advisable to block on the completion of the operation. One may use the returned
 * {@link ListenableFuture} to register callbacks or track the status of the operation.
 *
 * @param document The {@link GoogleStorageLocation} of the document to run OCR processing
 * @param outputFilePathPrefix The {@link GoogleStorageLocation} of a file, folder, or a
 *     bucket describing the path for which all output files shall be saved under
 *
 * @return A {@link ListenableFuture} allowing you to register callbacks or wait for the
 * completion of the operation.
 */
public ListenableFuture<DocumentOcrResultSet> runOcrForDocument(GoogleStorageLocation document, GoogleStorageLocation outputFilePathPrefix) {
    Assert.isTrue(document.isFile(), "Provided document location is not a valid file location: " + document);
    GcsSource gcsSource = GcsSource.newBuilder().setUri(document.uriString()).build();
    String contentType = extractContentType(document);
    InputConfig inputConfig = InputConfig.newBuilder().setMimeType(contentType).setGcsSource(gcsSource).build();
    GcsDestination gcsDestination = GcsDestination.newBuilder().setUri(outputFilePathPrefix.uriString()).build();
    OutputConfig outputConfig = OutputConfig.newBuilder().setGcsDestination(gcsDestination).setBatchSize(this.jsonOutputBatchSize).build();
    AsyncAnnotateFileRequest request = AsyncAnnotateFileRequest.newBuilder().addFeatures(DOCUMENT_OCR_FEATURE).setInputConfig(inputConfig).setOutputConfig(outputConfig).build();
    OperationFuture<AsyncBatchAnnotateFilesResponse, OperationMetadata> result = imageAnnotatorClient.asyncBatchAnnotateFilesAsync(Collections.singletonList(request));
    return extractOcrResultFuture(result);
}
Also used : GcsSource(com.google.cloud.vision.v1.GcsSource) OutputConfig(com.google.cloud.vision.v1.OutputConfig) AsyncBatchAnnotateFilesResponse(com.google.cloud.vision.v1.AsyncBatchAnnotateFilesResponse) InputConfig(com.google.cloud.vision.v1.InputConfig) AsyncAnnotateFileRequest(com.google.cloud.vision.v1.AsyncAnnotateFileRequest) GcsDestination(com.google.cloud.vision.v1.GcsDestination) OperationMetadata(com.google.cloud.vision.v1.OperationMetadata)

Example 3 with GcsDestination

use of com.google.cloud.aiplatform.v1.GcsDestination in project java-datalabeling by googleapis.

the class ExportData method exportData.

// Export data from an annotated dataset.
static void exportData(String datasetName, String annotatedDatasetName, String gcsOutputUri) throws IOException {
    // String datasetName = DataLabelingServiceClient.formatDatasetName(
    // "YOUR_PROJECT_ID", "YOUR_DATASETS_UUID");
    // String annotatedDatasetName = DataLabelingServiceClient.formatAnnotatedDatasetName(
    // "YOUR_PROJECT_ID",
    // "YOUR_DATASET_UUID",
    // "YOUR_ANNOTATED_DATASET_UUID");
    // String gcsOutputUri = "gs://YOUR_BUCKET_ID/export_path";
    // [END datalabeling_export_data_beta]
    String endpoint = System.getenv("DATALABELING_ENDPOINT");
    if (endpoint == null) {
        endpoint = DataLabelingServiceSettings.getDefaultEndpoint();
    }
    // [START datalabeling_export_data_beta]
    DataLabelingServiceSettings settings = DataLabelingServiceSettings.newBuilder().setEndpoint(endpoint).build();
    try (DataLabelingServiceClient dataLabelingServiceClient = DataLabelingServiceClient.create(settings)) {
        GcsDestination gcsDestination = GcsDestination.newBuilder().setOutputUri(gcsOutputUri).setMimeType("text/csv").build();
        OutputConfig outputConfig = OutputConfig.newBuilder().setGcsDestination(gcsDestination).build();
        ExportDataRequest exportDataRequest = ExportDataRequest.newBuilder().setName(datasetName).setOutputConfig(outputConfig).setAnnotatedDataset(annotatedDatasetName).build();
        OperationFuture<ExportDataOperationResponse, ExportDataOperationMetadata> operation = dataLabelingServiceClient.exportDataAsync(exportDataRequest);
        ExportDataOperationResponse response = operation.get();
        System.out.format("Exported item count: %d\n", response.getExportCount());
        LabelStats labelStats = response.getLabelStats();
        Set<Entry<String, Long>> entries = labelStats.getExampleCountMap().entrySet();
        for (Entry<String, Long> entry : entries) {
            System.out.format("\tLabel: %s\n", entry.getKey());
            System.out.format("\tCount: %d\n\n", entry.getValue());
        }
    } catch (IOException | InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
}
Also used : DataLabelingServiceClient(com.google.cloud.datalabeling.v1beta1.DataLabelingServiceClient) ExportDataRequest(com.google.cloud.datalabeling.v1beta1.ExportDataRequest) IOException(java.io.IOException) ExportDataOperationResponse(com.google.cloud.datalabeling.v1beta1.ExportDataOperationResponse) Entry(java.util.Map.Entry) OutputConfig(com.google.cloud.datalabeling.v1beta1.OutputConfig) ExportDataOperationMetadata(com.google.cloud.datalabeling.v1beta1.ExportDataOperationMetadata) DataLabelingServiceSettings(com.google.cloud.datalabeling.v1beta1.DataLabelingServiceSettings) GcsDestination(com.google.cloud.datalabeling.v1beta1.GcsDestination) LabelStats(com.google.cloud.datalabeling.v1beta1.LabelStats) ExecutionException(java.util.concurrent.ExecutionException)

Example 4 with GcsDestination

use of com.google.cloud.aiplatform.v1.GcsDestination in project java-translate by googleapis.

the class BatchTranslateTextWithGlossaryAndModel method batchTranslateTextWithGlossaryAndModel.

// Batch translate text with Model and Glossary
public static void batchTranslateTextWithGlossaryAndModel(String projectId, String sourceLanguage, String targetLanguage, String inputUri, String outputUri, String glossaryId, 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 glossary used in the request
        GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);
        TranslateTextGlossaryConfig glossaryConfig = TranslateTextGlossaryConfig.newBuilder().setGlossary(glossaryName.toString()).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).putGlossaries(targetLanguage, glossaryConfig).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 : TranslationServiceClient(com.google.cloud.translate.v3.TranslationServiceClient) GcsSource(com.google.cloud.translate.v3.GcsSource) TranslateTextGlossaryConfig(com.google.cloud.translate.v3.TranslateTextGlossaryConfig) BatchTranslateResponse(com.google.cloud.translate.v3.BatchTranslateResponse) LocationName(com.google.cloud.translate.v3.LocationName) BatchTranslateMetadata(com.google.cloud.translate.v3.BatchTranslateMetadata) OutputConfig(com.google.cloud.translate.v3.OutputConfig) BatchTranslateTextRequest(com.google.cloud.translate.v3.BatchTranslateTextRequest) GlossaryName(com.google.cloud.translate.v3.GlossaryName) InputConfig(com.google.cloud.translate.v3.InputConfig) GcsDestination(com.google.cloud.translate.v3.GcsDestination)

Example 5 with GcsDestination

use of com.google.cloud.aiplatform.v1.GcsDestination in project java-translate by googleapis.

the class BatchTranslateDocument method batchTranslateDocument.

// Batch translate document
public static void batchTranslateDocument(String projectId, String sourceLanguage, String targetLanguage, String inputUri, String outputUri, int timeout) throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // refer to https://github.com/googleapis/java-translate/issues/613
    TranslationServiceSettings.Builder translationServiceSettingsBuilder = TranslationServiceSettings.newBuilder();
    TimedRetryAlgorithm timedRetryAlgorithm = OperationTimedPollAlgorithm.create(RetrySettings.newBuilder().setTotalTimeout(Duration.ofSeconds(1000)).build());
    translationServiceSettingsBuilder.batchTranslateDocumentOperationSettings().setPollingAlgorithm(timedRetryAlgorithm);
    TranslationServiceSettings translationServiceSettings = translationServiceSettingsBuilder.build();
    // up any remaining background resources.
    try (TranslationServiceClient client = TranslationServiceClient.create(translationServiceSettings)) {
        // The ``global`` location is not supported for batch translation
        LocationName parent = LocationName.of(projectId, "us-central1");
        // Google Cloud Storage location for the source input. This can be a single file
        // (for example, ``gs://translation-test/input.docx``) or a wildcard
        // (for example, ``gs://translation-test/*``).
        // Supported file types: https://cloud.google.com/translate/docs/supported-formats
        GcsSource gcsSource = GcsSource.newBuilder().setInputUri(inputUri).build();
        BatchDocumentInputConfig batchDocumentInputConfig = BatchDocumentInputConfig.newBuilder().setGcsSource(gcsSource).build();
        GcsDestination gcsDestination = GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build();
        BatchDocumentOutputConfig batchDocumentOutputConfig = BatchDocumentOutputConfig.newBuilder().setGcsDestination(gcsDestination).build();
        BatchTranslateDocumentRequest request = BatchTranslateDocumentRequest.newBuilder().setParent(parent.toString()).setSourceLanguageCode(sourceLanguage).addTargetLanguageCodes(targetLanguage).addInputConfigs(batchDocumentInputConfig).setOutputConfig(batchDocumentOutputConfig).build();
        OperationFuture<BatchTranslateDocumentResponse, BatchTranslateDocumentMetadata> future = client.batchTranslateDocumentAsync(request);
        System.out.println("Waiting for operation to complete...");
        // random number between timeout
        long randomNumber = ThreadLocalRandom.current().nextInt(timeout, timeout + 100);
        BatchTranslateDocumentResponse response = future.get(randomNumber, TimeUnit.SECONDS);
        System.out.println("Total Pages: " + response.getTotalPages());
    }
}
Also used : TimedRetryAlgorithm(com.google.api.gax.retrying.TimedRetryAlgorithm) TranslationServiceClient(com.google.cloud.translate.v3beta1.TranslationServiceClient) GcsSource(com.google.cloud.translate.v3beta1.GcsSource) BatchTranslateDocumentMetadata(com.google.cloud.translate.v3beta1.BatchTranslateDocumentMetadata) BatchDocumentInputConfig(com.google.cloud.translate.v3beta1.BatchDocumentInputConfig) BatchDocumentOutputConfig(com.google.cloud.translate.v3beta1.BatchDocumentOutputConfig) LocationName(com.google.cloud.translate.v3beta1.LocationName) BatchTranslateDocumentRequest(com.google.cloud.translate.v3beta1.BatchTranslateDocumentRequest) TranslationServiceSettings(com.google.cloud.translate.v3beta1.TranslationServiceSettings) BatchTranslateDocumentResponse(com.google.cloud.translate.v3beta1.BatchTranslateDocumentResponse) GcsDestination(com.google.cloud.translate.v3beta1.GcsDestination)

Aggregations

GcsDestination (com.google.cloud.aiplatform.v1.GcsDestination)12 BatchPredictionJob (com.google.cloud.aiplatform.v1.BatchPredictionJob)8 GcsSource (com.google.cloud.aiplatform.v1.GcsSource)8 JobServiceClient (com.google.cloud.aiplatform.v1.JobServiceClient)8 JobServiceSettings (com.google.cloud.aiplatform.v1.JobServiceSettings)8 LocationName (com.google.cloud.aiplatform.v1.LocationName)8 ModelName (com.google.cloud.aiplatform.v1.ModelName)5 Value (com.google.protobuf.Value)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 GcsSource (com.google.cloud.translate.v3.GcsSource)4 InputConfig (com.google.cloud.translate.v3.InputConfig)4 LocationName (com.google.cloud.translate.v3.LocationName)4 OutputConfig (com.google.cloud.translate.v3.OutputConfig)4 TranslationServiceClient (com.google.cloud.translate.v3.TranslationServiceClient)4 GcsDestination (com.google.cloud.vision.v1.GcsDestination)4 ApiException (com.google.api.gax.rpc.ApiException)3 BatchDedicatedResources (com.google.cloud.aiplatform.v1.BatchDedicatedResources)3