use of com.google.cloud.redis.v1beta1.OutputConfig 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();
}
}
use of com.google.cloud.redis.v1beta1.OutputConfig in project java-asset by googleapis.
the class ExportAssetsExample method exportAssets.
// Export assets for a project.
// @param exportPath where the results will be exported to.
public static void exportAssets(String exportPath, ContentType contentType) throws IOException, IllegalArgumentException, InterruptedException, ExecutionException {
try (AssetServiceClient client = AssetServiceClient.create()) {
ProjectName parent = ProjectName.of(projectId);
OutputConfig outputConfig = OutputConfig.newBuilder().setGcsDestination(GcsDestination.newBuilder().setUri(exportPath).build()).build();
ExportAssetsRequest request = ExportAssetsRequest.newBuilder().setParent(parent.toString()).setOutputConfig(outputConfig).setContentType(contentType).build();
ExportAssetsResponse response = client.exportAssetsAsync(request).get();
System.out.println(response);
}
}
use of com.google.cloud.redis.v1beta1.OutputConfig 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);
}
}
use of com.google.cloud.redis.v1beta1.OutputConfig 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.redis.v1beta1.OutputConfig 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);
}
Aggregations