Search in sources :

Example 1 with OutputConfig

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();
    }
}
Also used : DataLabelingServiceClient(com.google.cloud.datalabeling.v1beta1.DataLabelingServiceClient) ExportDataRequest(com.google.cloud.datalabeling.v1beta1.ExportDataRequest) IOException(java.io.IOException) ExportDataOperationResponse(com.google.cloud.datalabeling.v1beta1.ExportDataOperationResponse) Entry(java.util.Map.Entry) OutputConfig(com.google.cloud.datalabeling.v1beta1.OutputConfig) ExportDataOperationMetadata(com.google.cloud.datalabeling.v1beta1.ExportDataOperationMetadata) DataLabelingServiceSettings(com.google.cloud.datalabeling.v1beta1.DataLabelingServiceSettings) GcsDestination(com.google.cloud.datalabeling.v1beta1.GcsDestination) LabelStats(com.google.cloud.datalabeling.v1beta1.LabelStats) ExecutionException(java.util.concurrent.ExecutionException)

Example 2 with OutputConfig

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());
    }
}
Also used : Options(com.google.cloud.asset.v1.IamPolicyAnalysisQuery.Options) AnalyzeIamPolicyLongrunningRequest(com.google.cloud.asset.v1.AnalyzeIamPolicyLongrunningRequest) IamPolicyAnalysisOutputConfig(com.google.cloud.asset.v1.IamPolicyAnalysisOutputConfig) AssetServiceClient(com.google.cloud.asset.v1.AssetServiceClient) ResourceSelector(com.google.cloud.asset.v1.IamPolicyAnalysisQuery.ResourceSelector) IamPolicyAnalysisQuery(com.google.cloud.asset.v1.IamPolicyAnalysisQuery) IOException(java.io.IOException) BigQueryDestination(com.google.cloud.asset.v1.IamPolicyAnalysisOutputConfig.BigQueryDestination) ExecutionException(java.util.concurrent.ExecutionException) ApiException(com.google.api.gax.rpc.ApiException)

Example 3 with OutputConfig

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);
    }
}
Also used : OutputConfig(com.google.cloud.asset.v1.OutputConfig) ExportAssetsRequest(com.google.cloud.asset.v1.ExportAssetsRequest) ProjectName(com.google.cloud.asset.v1.ProjectName) AssetServiceClient(com.google.cloud.asset.v1.AssetServiceClient) ExportAssetsResponse(com.google.cloud.asset.v1.ExportAssetsResponse)

Example 4 with OutputConfig

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);
    }
}
Also used : TranslationServiceClient(com.google.cloud.translate.v3beta1.TranslationServiceClient) GcsSource(com.google.cloud.translate.v3beta1.GcsSource) OutputConfig(com.google.cloud.translate.v3beta1.OutputConfig) BatchTranslateTextRequest(com.google.cloud.translate.v3beta1.BatchTranslateTextRequest) InputConfig(com.google.cloud.translate.v3beta1.InputConfig) GlossaryInputConfig(com.google.cloud.translate.v3beta1.GlossaryInputConfig) GcsDestination(com.google.cloud.translate.v3beta1.GcsDestination) BatchTranslateResponse(com.google.cloud.translate.v3beta1.BatchTranslateResponse) LocationName(com.google.cloud.translate.v3beta1.LocationName)

Example 5 with OutputConfig

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();
            }
        }
    }
}
Also used : BatchProcessDocumentsResponse(com.google.cloud.documentai.v1beta2.BatchProcessDocumentsResponse) DocumentUnderstandingServiceClient(com.google.cloud.documentai.v1beta2.DocumentUnderstandingServiceClient) GcsSource(com.google.cloud.documentai.v1beta2.GcsSource) Page(com.google.api.gax.paging.Page) Document(com.google.cloud.documentai.v1beta2.Document) InputConfig(com.google.cloud.documentai.v1beta2.InputConfig) FileReader(java.io.FileReader) BatchProcessDocumentsRequest(com.google.cloud.documentai.v1beta2.BatchProcessDocumentsRequest) OperationMetadata(com.google.cloud.documentai.v1beta2.OperationMetadata) ProcessDocumentRequest(com.google.cloud.documentai.v1beta2.ProcessDocumentRequest) KeyValuePairHint(com.google.cloud.documentai.v1beta2.KeyValuePairHint) Blob(com.google.cloud.storage.Blob) KeyValuePairHint(com.google.cloud.documentai.v1beta2.KeyValuePairHint) OutputConfig(com.google.cloud.documentai.v1beta2.OutputConfig) Storage(com.google.cloud.storage.Storage) Bucket(com.google.cloud.storage.Bucket) FormExtractionParams(com.google.cloud.documentai.v1beta2.FormExtractionParams) GcsDestination(com.google.cloud.documentai.v1beta2.GcsDestination) File(java.io.File)

Aggregations

AssetServiceClient (com.google.cloud.asset.v1.AssetServiceClient)4 BatchTranslateMetadata (com.google.cloud.translate.v3.BatchTranslateMetadata)4 BatchTranslateResponse (com.google.cloud.translate.v3.BatchTranslateResponse)4 BatchTranslateTextRequest (com.google.cloud.translate.v3.BatchTranslateTextRequest)4 GcsDestination (com.google.cloud.translate.v3.GcsDestination)4 GcsSource (com.google.cloud.translate.v3.GcsSource)4 InputConfig (com.google.cloud.translate.v3.InputConfig)4 LocationName (com.google.cloud.translate.v3.LocationName)4 OutputConfig (com.google.cloud.translate.v3.OutputConfig)4 TranslationServiceClient (com.google.cloud.translate.v3.TranslationServiceClient)4 GcsDestination (com.google.cloud.vision.v1.GcsDestination)4 OutputConfig (com.google.cloud.vision.v1.OutputConfig)4 Blob (com.google.cloud.storage.Blob)3 Bucket (com.google.cloud.storage.Bucket)3 Storage (com.google.cloud.storage.Storage)3 Page (com.google.api.gax.paging.Page)2 ApiException (com.google.api.gax.rpc.ApiException)2 AnalyzeIamPolicyLongrunningRequest (com.google.cloud.asset.v1.AnalyzeIamPolicyLongrunningRequest)2 ExportAssetsRequest (com.google.cloud.asset.v1.ExportAssetsRequest)2 ExportAssetsResponse (com.google.cloud.asset.v1.ExportAssetsResponse)2