use of com.google.cloud.automl.v1.GcsSource in project java-automl by googleapis.
the class ImportDataset method importDataset.
// Import a dataset
static void importDataset(String projectId, String datasetId, String path) throws IOException, ExecutionException, InterruptedException, TimeoutException {
// the "close" method on the client to safely clean up any remaining background resources.
try (AutoMlClient client = AutoMlClient.create()) {
// Get the complete path of the dataset.
DatasetName datasetFullId = DatasetName.of(projectId, "us-central1", datasetId);
// Get multiple Google Cloud Storage URIs to import data from
GcsSource gcsSource = GcsSource.newBuilder().addAllInputUris(Arrays.asList(path.split(","))).build();
// Import data from the input URI
InputConfig inputConfig = InputConfig.newBuilder().setGcsSource(gcsSource).build();
System.out.println("Processing import...");
// Start the import job
OperationFuture<Empty, OperationMetadata> operation = client.importDataAsync(datasetFullId, inputConfig);
System.out.format("Operation name: %s%n", operation.getName());
// If you want to wait for the operation to finish, adjust the timeout appropriately. The
// operation will still run if you choose not to wait for it to complete. You can check the
// status of your operation using the operation's name.
Empty response = operation.get(45, TimeUnit.MINUTES);
System.out.format("Dataset imported. %s%n", response);
} catch (TimeoutException e) {
System.out.println("The operation's polling period was not long enough.");
System.out.println("You can use the Operation's name to get the current status.");
System.out.println("The import job is still running and will complete as expected.");
throw e;
}
}
use of com.google.cloud.automl.v1.GcsSource 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();
}
}
}
}
use of com.google.cloud.automl.v1.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);
}
}
}
}
use of com.google.cloud.automl.v1.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);
}
use of com.google.cloud.automl.v1.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());
}
}
}
}
}
}
}
}
Aggregations