Search in sources :

Example 6 with GcsDestination

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

the class BatchTranslateTextWithGlossary method batchTranslateTextWithGlossary.

// Batch Translate Text with a Glossary.
public static void batchTranslateTextWithGlossary(String projectId, String sourceLanguage, String targetLanguage, String inputUri, String outputUri, String glossaryId) 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();
        // 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).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 7 with GcsDestination

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

the class BatchPredict method batchPredict.

static void batchPredict(String projectId, String modelId, String inputUri, String outputUri) throws IOException, ExecutionException, InterruptedException {
    // the "close" method on the client to safely clean up any remaining background resources.
    try (PredictionServiceClient client = PredictionServiceClient.create()) {
        // Get the full path of the model.
        ModelName name = ModelName.of(projectId, "us-central1", modelId);
        // Configure the source of the file from a GCS bucket
        GcsSource gcsSource = GcsSource.newBuilder().addInputUris(inputUri).build();
        BatchPredictInputConfig inputConfig = BatchPredictInputConfig.newBuilder().setGcsSource(gcsSource).build();
        // Configure where to store the output in a GCS bucket
        GcsDestination gcsDestination = GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build();
        BatchPredictOutputConfig outputConfig = BatchPredictOutputConfig.newBuilder().setGcsDestination(gcsDestination).build();
        // Build the request that will be sent to the API
        BatchPredictRequest request = BatchPredictRequest.newBuilder().setName(name.toString()).setInputConfig(inputConfig).setOutputConfig(outputConfig).build();
        // Start an asynchronous request
        OperationFuture<BatchPredictResult, OperationMetadata> future = client.batchPredictAsync(request);
        System.out.println("Waiting for operation to complete...");
        BatchPredictResult response = future.get();
        System.out.println("Batch Prediction results saved to specified Cloud Storage bucket.");
    }
}
Also used : BatchPredictRequest(com.google.cloud.automl.v1beta1.BatchPredictRequest) ModelName(com.google.cloud.automl.v1beta1.ModelName) GcsSource(com.google.cloud.automl.v1beta1.GcsSource) BatchPredictInputConfig(com.google.cloud.automl.v1beta1.BatchPredictInputConfig) BatchPredictOutputConfig(com.google.cloud.automl.v1beta1.BatchPredictOutputConfig) BatchPredictResult(com.google.cloud.automl.v1beta1.BatchPredictResult) GcsDestination(com.google.cloud.automl.v1beta1.GcsDestination) OperationMetadata(com.google.cloud.automl.v1beta1.OperationMetadata) PredictionServiceClient(com.google.cloud.automl.v1beta1.PredictionServiceClient)

Example 8 with GcsDestination

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

the class BatchPredict method batchPredict.

static void batchPredict(String projectId, String modelId, String inputUri, String outputUri) throws IOException, ExecutionException, InterruptedException {
    // the "close" method on the client to safely clean up any remaining background resources.
    try (PredictionServiceClient client = PredictionServiceClient.create()) {
        // Get the full path of the model.
        ModelName name = ModelName.of(projectId, "us-central1", modelId);
        GcsSource gcsSource = GcsSource.newBuilder().addInputUris(inputUri).build();
        BatchPredictInputConfig inputConfig = BatchPredictInputConfig.newBuilder().setGcsSource(gcsSource).build();
        GcsDestination gcsDestination = GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build();
        BatchPredictOutputConfig outputConfig = BatchPredictOutputConfig.newBuilder().setGcsDestination(gcsDestination).build();
        BatchPredictRequest request = BatchPredictRequest.newBuilder().setName(name.toString()).setInputConfig(inputConfig).setOutputConfig(outputConfig).build();
        OperationFuture<BatchPredictResult, OperationMetadata> future = client.batchPredictAsync(request);
        System.out.println("Waiting for operation to complete...");
        BatchPredictResult response = future.get();
        System.out.println("Batch Prediction results saved to specified Cloud Storage bucket.");
    }
}
Also used : BatchPredictRequest(com.google.cloud.automl.v1.BatchPredictRequest) ModelName(com.google.cloud.automl.v1.ModelName) GcsSource(com.google.cloud.automl.v1.GcsSource) BatchPredictInputConfig(com.google.cloud.automl.v1.BatchPredictInputConfig) BatchPredictOutputConfig(com.google.cloud.automl.v1.BatchPredictOutputConfig) BatchPredictResult(com.google.cloud.automl.v1.BatchPredictResult) GcsDestination(com.google.cloud.automl.v1.GcsDestination) OperationMetadata(com.google.cloud.automl.v1.OperationMetadata) PredictionServiceClient(com.google.cloud.automl.v1.PredictionServiceClient)

Example 9 with GcsDestination

use of com.google.cloud.translate.v3.GcsDestination in project spring-cloud-gcp by GoogleCloudPlatform.

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 10 with GcsDestination

use of com.google.cloud.translate.v3.GcsDestination in project java-document-ai by googleapis.

the class BatchParseFormBeta method batchParseFormGcs.

public static void batchParseFormGcs(String projectId, String location, String outputGcsBucketName, String outputGcsPrefix, String inputGcsUri) throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DocumentUnderstandingServiceClient client = DocumentUnderstandingServiceClient.create()) {
        // Configure the request for processing the PDF
        String parent = String.format("projects/%s/locations/%s", projectId, location);
        // Improve form parsing results by providing key-value pair hints.
        // For each key hint, key is text that is likely to appear in the
        // document as a form field name (i.e. "DOB").
        // Value types are optional, but can be one or more of:
        // ADDRESS, LOCATION, ORGANIZATION, PERSON, PHONE_NUMBER, ID,
        // NUMBER, EMAIL, PRICE, TERMS, DATE, NAME
        KeyValuePairHint keyValuePairHint = KeyValuePairHint.newBuilder().setKey("Phone").addValueTypes("PHONE_NUMBER").build();
        KeyValuePairHint keyValuePairHint2 = KeyValuePairHint.newBuilder().setKey("Contact").addValueTypes("EMAIL").addValueTypes("NAME").build();
        // Setting enabled=True enables form extraction
        FormExtractionParams params = FormExtractionParams.newBuilder().setEnabled(true).addKeyValuePairHints(keyValuePairHint).addKeyValuePairHints(keyValuePairHint2).build();
        GcsSource inputUri = GcsSource.newBuilder().setUri(inputGcsUri).build();
        // mime_type can be application/pdf, image/tiff,
        // and image/gif, or application/json
        InputConfig config = InputConfig.newBuilder().setGcsSource(inputUri).setMimeType("application/pdf").build();
        GcsDestination gcsDestination = GcsDestination.newBuilder().setUri(String.format("gs://%s/%s", outputGcsBucketName, outputGcsPrefix)).build();
        OutputConfig outputConfig = OutputConfig.newBuilder().setGcsDestination(gcsDestination).setPagesPerShard(1).build();
        ProcessDocumentRequest request = ProcessDocumentRequest.newBuilder().setFormExtractionParams(params).setInputConfig(config).setOutputConfig(outputConfig).build();
        BatchProcessDocumentsRequest requests = BatchProcessDocumentsRequest.newBuilder().addRequests(request).setParent(parent).build();
        // Batch process document using a long-running operation.
        OperationFuture<BatchProcessDocumentsResponse, OperationMetadata> future = client.batchProcessDocumentsAsync(requests);
        // Wait for operation to complete.
        System.out.println("Waiting for operation to complete...");
        future.get(360, TimeUnit.SECONDS);
        System.out.println("Document processing complete.");
        Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
        Bucket bucket = storage.get(outputGcsBucketName);
        // List all of the files in the Storage bucket.
        Page<Blob> blobs = bucket.list(Storage.BlobListOption.currentDirectory(), Storage.BlobListOption.prefix(outputGcsPrefix));
        int idx = 0;
        for (Blob blob : blobs.iterateAll()) {
            if (!blob.isDirectory()) {
                System.out.printf("Fetched file #%d\n", ++idx);
                // Read the results
                // Download and store json data in a temp file.
                File tempFile = File.createTempFile("file", ".json");
                Blob fileInfo = storage.get(BlobId.of(outputGcsBucketName, blob.getName()));
                fileInfo.downloadTo(tempFile.toPath());
                // Parse json file into Document.
                FileReader reader = new FileReader(tempFile);
                Document.Builder builder = Document.newBuilder();
                JsonFormat.parser().merge(reader, builder);
                Document document = builder.build();
                // Get all of the document text as one big string.
                String text = document.getText();
                // Process the output.
                if (document.getPagesCount() > 0) {
                    Document.Page page1 = document.getPages(0);
                    for (Document.Page.FormField field : page1.getFormFieldsList()) {
                        String fieldName = getText(field.getFieldName(), text);
                        String fieldValue = getText(field.getFieldValue(), text);
                        System.out.println("Extracted form fields pair:");
                        System.out.printf("\t(%s, %s))", fieldName, fieldValue);
                    }
                }
                // Clean up temp file.
                tempFile.deleteOnExit();
            }
        }
    }
}
Also used : BatchProcessDocumentsResponse(com.google.cloud.documentai.v1beta2.BatchProcessDocumentsResponse) DocumentUnderstandingServiceClient(com.google.cloud.documentai.v1beta2.DocumentUnderstandingServiceClient) GcsSource(com.google.cloud.documentai.v1beta2.GcsSource) Page(com.google.api.gax.paging.Page) Document(com.google.cloud.documentai.v1beta2.Document) InputConfig(com.google.cloud.documentai.v1beta2.InputConfig) FileReader(java.io.FileReader) BatchProcessDocumentsRequest(com.google.cloud.documentai.v1beta2.BatchProcessDocumentsRequest) OperationMetadata(com.google.cloud.documentai.v1beta2.OperationMetadata) ProcessDocumentRequest(com.google.cloud.documentai.v1beta2.ProcessDocumentRequest) KeyValuePairHint(com.google.cloud.documentai.v1beta2.KeyValuePairHint) Blob(com.google.cloud.storage.Blob) KeyValuePairHint(com.google.cloud.documentai.v1beta2.KeyValuePairHint) OutputConfig(com.google.cloud.documentai.v1beta2.OutputConfig) Storage(com.google.cloud.storage.Storage) Bucket(com.google.cloud.storage.Bucket) FormExtractionParams(com.google.cloud.documentai.v1beta2.FormExtractionParams) GcsDestination(com.google.cloud.documentai.v1beta2.GcsDestination) File(java.io.File)

Aggregations

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 OutputConfig (com.google.cloud.vision.v1.OutputConfig)4 Blob (com.google.cloud.storage.Blob)3 Bucket (com.google.cloud.storage.Bucket)3 Storage (com.google.cloud.storage.Storage)3 Page (com.google.api.gax.paging.Page)2 GcsDestination (com.google.cloud.automl.v1.GcsDestination)2 GlossaryName (com.google.cloud.translate.v3.GlossaryName)2 TranslateTextGlossaryConfig (com.google.cloud.translate.v3.TranslateTextGlossaryConfig)2 GcsDestination (com.google.cloud.translate.v3beta1.GcsDestination)2 GcsSource (com.google.cloud.translate.v3beta1.GcsSource)2