use of com.google.cloud.asset.v1.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.asset.v1.OutputConfig in project java-asset by googleapis.
the class AnalyzeIamPolicyLongrunningBigqueryExample method analyzeIamPolicyLongrunning.
// Analyzes accessible IAM policies that match a request.
public static void analyzeIamPolicyLongrunning(String scope, String fullResourceName, String dataset, String tablePrefix) {
ResourceSelector resourceSelector = ResourceSelector.newBuilder().setFullResourceName(fullResourceName).build();
Options options = Options.newBuilder().setExpandGroups(true).setOutputGroupEdges(true).build();
IamPolicyAnalysisQuery query = IamPolicyAnalysisQuery.newBuilder().setScope(scope).setResourceSelector(resourceSelector).setOptions(options).build();
BigQueryDestination bigQueryDestination = BigQueryDestination.newBuilder().setDataset(dataset).setTablePrefix(tablePrefix).build();
IamPolicyAnalysisOutputConfig outputConfig = IamPolicyAnalysisOutputConfig.newBuilder().setBigqueryDestination(bigQueryDestination).build();
AnalyzeIamPolicyLongrunningRequest request = AnalyzeIamPolicyLongrunningRequest.newBuilder().setAnalysisQuery(query).setOutputConfig(outputConfig).build();
// the "close" method on the client to safely clean up any remaining background resources.
try (AssetServiceClient client = AssetServiceClient.create()) {
System.out.println("Analyze completed successfully:\n" + client.analyzeIamPolicyLongrunningAsync(request).getMetadata().get());
} catch (IOException e) {
System.out.println("Failed to create client:\n" + e.toString());
} catch (InterruptedException e) {
System.out.println("Operation was interrupted:\n" + e.toString());
} catch (ExecutionException e) {
System.out.println("Operation was aborted:\n" + e.toString());
} catch (ApiException e) {
System.out.println("Error during AnalyzeIamPolicyLongrunning:\n" + e.toString());
}
}
use of com.google.cloud.asset.v1.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.asset.v1.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.asset.v1.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();
}
}
}
}
Aggregations