Omite coincidencias de análisis de un detector PERSON_NAME que se superponen con un detector personalizado
Explora más
Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:
Muestra de código
C#
Para obtener información sobre cómo instalar y usar la biblioteca cliente de Cloud DLP, consulta Bibliotecas cliente de Cloud DLP.
using System;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;
using static Google.Cloud.Dlp.V2.CustomInfoType.Types;
public class InspectStringCustomOmitOverlap
{
public static InspectContentResponse Inspect(string projectId, string textToInspect)
{
var dlp = DlpServiceClient.Create();
var byteItem = new ByteContentItem
{
Type = ByteContentItem.Types.BytesType.TextUtf8,
Data = Google.Protobuf.ByteString.CopyFromUtf8(textToInspect)
};
var contentItem = new ContentItem { ByteItem = byteItem };
var customInfoType = new CustomInfoType
{
InfoType = new InfoType { Name = "VIP_DETECTOR" },
Regex = new CustomInfoType.Types.Regex { Pattern = "Larry Page|Sergey Brin" },
ExclusionType = ExclusionType.Exclude
};
var exclusionRule = new ExclusionRule
{
ExcludeInfoTypes = new ExcludeInfoTypes { InfoTypes = { customInfoType.InfoType } },
MatchingType = MatchingType.FullMatch
};
var ruleSet = new InspectionRuleSet
{
InfoTypes = { new InfoType { Name = "PERSON_NAME" } },
Rules = { new InspectionRule { ExclusionRule = exclusionRule } }
};
var config = new InspectConfig
{
InfoTypes = { new InfoType { Name = "PERSON_NAME" } },
CustomInfoTypes = { customInfoType },
IncludeQuote = true,
RuleSet = { ruleSet }
};
var request = new InspectContentRequest
{
Parent = new LocationName(projectId, "global").ToString(),
Item = contentItem,
InspectConfig = config
};
var response = dlp.InspectContent(request);
Console.WriteLine($"Findings: {response.Result.Findings.Count}");
foreach (var f in response.Result.Findings)
{
Console.WriteLine("\tQuote: " + f.Quote);
Console.WriteLine("\tInfo type: " + f.InfoType.Name);
Console.WriteLine("\tLikelihood: " + f.Likelihood);
}
return response;
}
}
Java
Para obtener información sobre cómo instalar y usar la biblioteca cliente de Cloud DLP, consulta Bibliotecas cliente de Cloud DLP.
import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.ByteContentItem;
import com.google.privacy.dlp.v2.ByteContentItem.BytesType;
import com.google.privacy.dlp.v2.ContentItem;
import com.google.privacy.dlp.v2.CustomInfoType;
import com.google.privacy.dlp.v2.CustomInfoType.ExclusionType;
import com.google.privacy.dlp.v2.CustomInfoType.Regex;
import com.google.privacy.dlp.v2.ExcludeInfoTypes;
import com.google.privacy.dlp.v2.ExclusionRule;
import com.google.privacy.dlp.v2.Finding;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectContentRequest;
import com.google.privacy.dlp.v2.InspectContentResponse;
import com.google.privacy.dlp.v2.InspectionRule;
import com.google.privacy.dlp.v2.InspectionRuleSet;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.MatchingType;
import com.google.protobuf.ByteString;
import java.io.IOException;
public class InspectStringCustomOmitOverlap {
public static void main(String[] args) throws Exception {
// TODO(developer): Replace these variables before running the sample.
String projectId = "your-project-id";
String textToInspect = "Name: Jane Doe. Name: Larry Page.";
inspectStringCustomOmitOverlap(projectId, textToInspect);
}
// Inspects the provided text, avoiding matches specified in the exclusion list.
public static void inspectStringCustomOmitOverlap(String projectId, String textToInspect)
throws IOException {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (DlpServiceClient dlp = DlpServiceClient.create()) {
// Specify the type and content to be inspected.
ByteContentItem byteItem =
ByteContentItem.newBuilder()
.setType(BytesType.TEXT_UTF8)
.setData(ByteString.copyFromUtf8(textToInspect))
.build();
ContentItem item = ContentItem.newBuilder().setByteItem(byteItem).build();
// Construct the custom infotype.
CustomInfoType customInfoType =
CustomInfoType.newBuilder()
.setInfoType(InfoType.newBuilder().setName("VIP_DETECTOR"))
.setRegex(Regex.newBuilder().setPattern("Larry Page|Sergey Brin"))
.setExclusionType(ExclusionType.EXCLUSION_TYPE_EXCLUDE)
.build();
// Exclude matches that also match the custom infotype.
ExclusionRule exclusionRule =
ExclusionRule.newBuilder()
.setExcludeInfoTypes(
ExcludeInfoTypes.newBuilder().addInfoTypes(customInfoType.getInfoType()))
.setMatchingType(MatchingType.MATCHING_TYPE_FULL_MATCH)
.build();
// Construct a ruleset that applies the exclusion rule to the PERSON_NAME infotype.
InspectionRuleSet ruleSet =
InspectionRuleSet.newBuilder()
.addInfoTypes(InfoType.newBuilder().setName("PERSON_NAME"))
.addRules(InspectionRule.newBuilder().setExclusionRule(exclusionRule))
.build();
// Construct the configuration for the Inspect request, including the ruleset.
InspectConfig config =
InspectConfig.newBuilder()
.addInfoTypes(InfoType.newBuilder().setName("PERSON_NAME"))
.addCustomInfoTypes(customInfoType)
.setIncludeQuote(true)
.addRuleSet(ruleSet)
.build();
// Construct the Inspect request to be sent by the client.
InspectContentRequest request =
InspectContentRequest.newBuilder()
.setParent(LocationName.of(projectId, "global").toString())
.setItem(item)
.setInspectConfig(config)
.build();
// Use the client to send the API request.
InspectContentResponse response = dlp.inspectContent(request);
// Parse the response and process results
System.out.println("Findings: " + response.getResult().getFindingsCount());
for (Finding f : response.getResult().getFindingsList()) {
System.out.println("\tQuote: " + f.getQuote());
System.out.println("\tInfo type: " + f.getInfoType().getName());
System.out.println("\tLikelihood: " + f.getLikelihood());
}
}
}
}
Python
Para obtener información sobre cómo instalar y usar la biblioteca cliente de Cloud DLP, consulta Bibliotecas cliente de Cloud DLP.
def inspect_string_custom_omit_overlap(project, content_string):
"""Matches PERSON_NAME and a custom detector,
but if they overlap only matches the custom detector
Uses the Data Loss Prevention API to omit matches on a built-in detector
if they overlap with matches from a custom detector
Args:
project: The Google Cloud project id to use as a parent resource.
content_string: The string to inspect.
Returns:
None; the response from the API is printed to the terminal.
"""
# Import the client library.
import google.cloud.dlp
# Instantiate a client.
dlp = google.cloud.dlp_v2.DlpServiceClient()
# Construct a custom regex detector for names
custom_info_types = [
{
"info_type": {"name": "VIP_DETECTOR"},
"regex": {"pattern": "Larry Page|Sergey Brin"},
"exclusion_type": google.cloud.dlp_v2.CustomInfoType.ExclusionType.EXCLUSION_TYPE_EXCLUDE,
}
]
# Construct a rule set that will exclude PERSON_NAME matches
# that overlap with VIP_DETECTOR matches
rule_set = [
{
"info_types": [{"name": "PERSON_NAME"}],
"rules": [
{
"exclusion_rule": {
"exclude_info_types": {
"info_types": [{"name": "VIP_DETECTOR"}]
},
"matching_type": google.cloud.dlp_v2.MatchingType.MATCHING_TYPE_FULL_MATCH,
}
}
],
}
]
# Construct the configuration dictionary
inspect_config = {
"info_types": [{"name": "PERSON_NAME"}],
"custom_info_types": custom_info_types,
"rule_set": rule_set,
"include_quote": True,
}
# Construct the `item`.
item = {"value": content_string}
# Convert the project id into a full resource id.
parent = f"projects/{project}"
# Call the API.
response = dlp.inspect_content(
request={"parent": parent, "inspect_config": inspect_config, "item": item}
)
# Print out the results.
if response.result.findings:
for finding in response.result.findings:
print(f"Quote: {finding.quote}")
print(f"Info type: {finding.info_type.name}")
print(f"Likelihood: {finding.likelihood}")
else:
print("No findings.")
¿Qué sigue?
Para buscar y filtrar muestras de código en otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.