Search in sources :

Example 16 with GcsSource

use of com.google.cloud.datalabeling.v1beta1.GcsSource in project java-document-ai by googleapis.

the class ParseFormBeta method parseForm.

public static void parseForm(String projectId, String location, String inputGcsUri) throws IOException, ExecutionException, InterruptedException {
    // 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 uri = GcsSource.newBuilder().setUri(inputGcsUri).build();
        // mime_type can be application/pdf, image/tiff,
        // and image/gif, or application/json
        InputConfig config = InputConfig.newBuilder().setGcsSource(uri).setMimeType("application/pdf").build();
        ProcessDocumentRequest request = ProcessDocumentRequest.newBuilder().setParent(parent).setFormExtractionParams(params).setInputConfig(config).build();
        // Recognizes text entities in the PDF document
        Document response = client.processDocument(request);
        // Get all of the document text as one big string
        String text = response.getText();
        // Process the output
        if (response.getPagesCount() > 0) {
            Document.Page page1 = response.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);
            }
        }
    }
}
Also used : KeyValuePairHint(com.google.cloud.documentai.v1beta2.KeyValuePairHint) DocumentUnderstandingServiceClient(com.google.cloud.documentai.v1beta2.DocumentUnderstandingServiceClient) GcsSource(com.google.cloud.documentai.v1beta2.GcsSource) FormExtractionParams(com.google.cloud.documentai.v1beta2.FormExtractionParams) InputConfig(com.google.cloud.documentai.v1beta2.InputConfig) Document(com.google.cloud.documentai.v1beta2.Document) ProcessDocumentRequest(com.google.cloud.documentai.v1beta2.ProcessDocumentRequest)

Example 17 with GcsSource

use of com.google.cloud.datalabeling.v1beta1.GcsSource 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 18 with GcsSource

use of com.google.cloud.datalabeling.v1beta1.GcsSource in project java-vision by googleapis.

the class BatchAnnotateFilesGcs method batchAnnotateFilesGcs.

public static void batchAnnotateFilesGcs(String gcsUri) throws IOException {
    // the "close" method on the client to safely clean up any remaining background resources.
    try (ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create()) {
        // You can send multiple files to be annotated, this sample demonstrates how to do this with
        // one file. If you want to use multiple files, you have to create a `AnnotateImageRequest`
        // object for each file that you want annotated.
        // First specify where the vision api can find the image
        GcsSource gcsSource = GcsSource.newBuilder().setUri(gcsUri).build();
        // Specify the input config with the file's uri and its type.
        // Supported mime_type: application/pdf, image/tiff, image/gif
        // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#inputconfig
        InputConfig inputConfig = InputConfig.newBuilder().setMimeType("application/pdf").setGcsSource(gcsSource).build();
        // Set the type of annotation you want to perform on the file
        // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.Feature.Type
        Feature feature = Feature.newBuilder().setType(Feature.Type.DOCUMENT_TEXT_DETECTION).build();
        // Build the request object for that one file. Note: for additional file you have to create
        // additional `AnnotateFileRequest` objects and store them in a list to be used below.
        // Since we are sending a file of type `application/pdf`, we can use the `pages` field to
        // specify which pages to process. The service can process up to 5 pages per document file.
        // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.AnnotateFileRequest
        AnnotateFileRequest fileRequest = AnnotateFileRequest.newBuilder().setInputConfig(inputConfig).addFeatures(feature).addPages(// Process the first page
        1).addPages(// Process the second page
        2).addPages(// Process the last page
        -1).build();
        // Add each `AnnotateFileRequest` object to the batch request.
        BatchAnnotateFilesRequest request = BatchAnnotateFilesRequest.newBuilder().addRequests(fileRequest).build();
        // Make the synchronous batch request.
        BatchAnnotateFilesResponse response = imageAnnotatorClient.batchAnnotateFiles(request);
        // sample.
        for (AnnotateImageResponse imageResponse : response.getResponsesList().get(0).getResponsesList()) {
            System.out.format("Full text: %s%n", imageResponse.getFullTextAnnotation().getText());
            for (Page page : imageResponse.getFullTextAnnotation().getPagesList()) {
                for (Block block : page.getBlocksList()) {
                    System.out.format("%nBlock confidence: %s%n", block.getConfidence());
                    for (Paragraph par : block.getParagraphsList()) {
                        System.out.format("\tParagraph confidence: %s%n", par.getConfidence());
                        for (Word word : par.getWordsList()) {
                            System.out.format("\t\tWord confidence: %s%n", word.getConfidence());
                            for (Symbol symbol : word.getSymbolsList()) {
                                System.out.format("\t\t\tSymbol: %s, (confidence: %s)%n", symbol.getText(), symbol.getConfidence());
                            }
                        }
                    }
                }
            }
        }
    }
}
Also used : GcsSource(com.google.cloud.vision.v1.GcsSource) Word(com.google.cloud.vision.v1.Word) BatchAnnotateFilesRequest(com.google.cloud.vision.v1.BatchAnnotateFilesRequest) Symbol(com.google.cloud.vision.v1.Symbol) ImageAnnotatorClient(com.google.cloud.vision.v1.ImageAnnotatorClient) Page(com.google.cloud.vision.v1.Page) Feature(com.google.cloud.vision.v1.Feature) Paragraph(com.google.cloud.vision.v1.Paragraph) BatchAnnotateFilesResponse(com.google.cloud.vision.v1.BatchAnnotateFilesResponse) AnnotateImageResponse(com.google.cloud.vision.v1.AnnotateImageResponse) AnnotateFileRequest(com.google.cloud.vision.v1.AnnotateFileRequest) Block(com.google.cloud.vision.v1.Block) InputConfig(com.google.cloud.vision.v1.InputConfig)

Example 19 with GcsSource

use of com.google.cloud.datalabeling.v1beta1.GcsSource 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 20 with GcsSource

use of com.google.cloud.datalabeling.v1beta1.GcsSource 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

GcsSource (com.google.cloud.aiplatform.v1.GcsSource)16 BatchPredictionJob (com.google.cloud.aiplatform.v1.BatchPredictionJob)8 DatasetName (com.google.cloud.aiplatform.v1.DatasetName)8 DatasetServiceClient (com.google.cloud.aiplatform.v1.DatasetServiceClient)8 DatasetServiceSettings (com.google.cloud.aiplatform.v1.DatasetServiceSettings)8 GcsDestination (com.google.cloud.aiplatform.v1.GcsDestination)8 ImportDataConfig (com.google.cloud.aiplatform.v1.ImportDataConfig)8 ImportDataOperationMetadata (com.google.cloud.aiplatform.v1.ImportDataOperationMetadata)8 ImportDataResponse (com.google.cloud.aiplatform.v1.ImportDataResponse)8 JobServiceClient (com.google.cloud.aiplatform.v1.JobServiceClient)8 JobServiceSettings (com.google.cloud.aiplatform.v1.JobServiceSettings)8 LocationName (com.google.cloud.aiplatform.v1.LocationName)7 Document (com.google.cloud.documentai.v1beta2.Document)5 DocumentUnderstandingServiceClient (com.google.cloud.documentai.v1beta2.DocumentUnderstandingServiceClient)5 GcsSource (com.google.cloud.documentai.v1beta2.GcsSource)5 InputConfig (com.google.cloud.documentai.v1beta2.InputConfig)5 ProcessDocumentRequest (com.google.cloud.documentai.v1beta2.ProcessDocumentRequest)5 GcsSource (com.google.cloud.translate.v3.GcsSource)5 LocationName (com.google.cloud.translate.v3.LocationName)5 TranslationServiceClient (com.google.cloud.translate.v3.TranslationServiceClient)5