use of com.google.cloud.automl.v1beta1.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());
}
}
use of com.google.cloud.automl.v1beta1.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.");
}
}
use of com.google.cloud.automl.v1beta1.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.");
}
}
use of com.google.cloud.automl.v1beta1.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);
}
use of com.google.cloud.automl.v1beta1.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();
}
}
}
}
Aggregations