自定义匹配可能性

热词规则可让您通过强大的上下文规则进一步扩展内置及自定义的 infoType 检测器。借助热词规则,您可将正则表达式和邻近度检测器添加到现有的 infoType 检测器,并适当地调整匹配可能性值。热词规则是一种在规则集中指定的检查规则。每个规则集都会应用于一组 infoType,这些 infoType 可以是自定义或内置类型。

热词规则详解

infoType 检测器可以具有零项或多项热词规则。每条热词规则(HotwordRule 对象)都在检查规则(InspectionRule 对象)中进行定义。每条检查规则都在 InspectionRuleSet 对象中指定,而该对象又包含在 InspectConfig 对象中。

作为 JSON 对象,"inspectionRules" 数组中的单条热词规则如下所示:

"inspectionRules":[
  {
    "hotwordRule":{
      "hotwordRegex":{
        "pattern":"[REGEX_PATTERN]"
      },
      "proximity":{
        "windowAfter":"[NUM_CHARS_TO_CONSIDER_AFTER_FINDING]",
        "windowBefore":"[NUM_CHARS_TO_CONSIDER_BEFORE_FINDING]"
      }
      "likelihoodAdjustment":{
        "fixedLikelihood":"[LIKELIHOOD_VALUE]"
             -- OR --
        "relativeLikelihood":"[LIKELIHOOD_ADJUSTMENT]"
      },
    }
  },
  ...
]

每条热词规则均由三部分组成:

  • "hotwordRegex":一个定义热词条件的正则表达式模式(Regex 对象)。
  • "proximity":必须包含整个热词的发现结果的邻近度。该字段包含一个 Proximity 对象,后者由下面两个值组成:

    • "windowBefore":要考虑的位于发现结果前面的字符数。
    • "windowAfter":要考虑的位于发现结果后面的字符数。
  • "likelihoodAdjustment":对发现结果可能性的调整。该字段包含一个 LikelihoodAdjustment 对象,后者可设为下述任一值:

    • "fixedLikelihood":要将发现结果设为的固定 Likelihood 值。
    • "relativeLikelihood":一个数字,表示提高/降低发现结果可能性所依据的级别。例如,如果在未应用检测规则时发现结果是 POSSIBLE,且 relativeLikelihood 为 1,则可能性将升级为 LIKELY;如果值为 -1,则可能性降级为 UNLIKELY。可能性永远不会低于 VERY_UNLIKELY 或超过 VERY_LIKELY,因此如果在基本可能性为 VERY_LIKELY 时依次应用调整值 1 和 -1,则最终的可能性将为 LIKELY

热词示例:匹配医疗记录编号

假设您想要检测采用“###-#-#####”形式的自定义 infoType(例如医疗记录编号),并且您希望在此编号前面(而非之后)出现热词“MRN”时提升 Cloud DLP 发现结果的匹配可能性。因此:

  • 123-4-56789 将匹配为 POSSIBLE
  • MRN 123-4-56789 将匹配为 VERY_LIKELY

下面的 JSON 示例和代码段显示了按创建正则表达式 infoType 检测器中所述的自定义正则表达式,但添加了相应的热词规则:

协议

如需详细了解如何将 Cloud DLP API 与 JSON 配合使用,请参阅 JSON 快速入门

JSON 输入:

POST https://dlp.googleapis.com/v2/projects/[PROJECT_ID]/content:inspect?key={YOUR_API_KEY}

{
  "item":{
    "value":"Patient's MRN 444-5-22222 and just a number 333-2-33333"
  },
  "inspectConfig":{
    "customInfoTypes":[
      {
        "infoType":{
          "name":"C_MRN"
        },
        "regex":{
          "pattern":"[0-9]{3}-[0-9]{1}-[0-9]{5}"
        },
        "likelihood":"POSSIBLE",
      }
    ],
    "ruleSet":[
        {
        "infoTypes": [{"name" : "C_MRN"}],
        "rules":[
          {
            "hotwordRule":{
              "hotwordRegex":{
                "pattern":"(?i)(mrn|medical)(?-i)"
              },
              "likelihoodAdjustment":{
                "fixedLikelihood":"VERY_LIKELY"
              },
              "proximity":{
                "windowBefore":10
              }
            }
          }
        ]
      }
    ]
  }
}

JSON 输出(简化版本)

{
  "result": {
    "findings": [
      {
        "infoType": {
          "name": "C_MRN"
        },
        "likelihood": "VERY_LIKELY",
        "location": {
          "byteRange": {
            "start": "14",
            "end": "25"
          },
          "codepointRange": { ... }
        }
      },
      {
        "infoType": {
          "name": "C_MRN"
        },
        "likelihood": "POSSIBLE",
          "byteRange": {
            "start": "44",
            "end": "55"
          },
          "codepointRange": { ... }
        }
      }
    ]
  }
}

输出显示,借助我们命名为 C_MRN 的自定义 infoType 检测器和自定义正则表达式,Cloud DLP 正确识别了医疗记录编号。此外,由于热词规则中的上下文匹配,Cloud DLP 根据配置为第一个结果(旁边带有 MRN)分配了确定性 VERY_LIKELY。第二个发现结果缺少上下文,因此确定性保持在 POSSIBLE

Java

如需了解如何安装和使用 Cloud DLP 客户端库,请参阅 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.DetectionRule.HotwordRule;
import com.google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment;
import com.google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity;
import com.google.privacy.dlp.v2.CustomInfoType.Regex;
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.Likelihood;
import com.google.privacy.dlp.v2.LocationName;
import com.google.protobuf.ByteString;
import java.io.IOException;

public class InspectWithHotwordRules {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String textToInspect = "Patient's MRN 444-5-22222 and just a number 333-2-33333";
    String customRegexPattern = "[1-9]{3}-[1-9]{1}-[1-9]{5}";
    String hotwordRegexPattern = "(?i)(mrn|medical)(?-i)";
    inspectWithHotwordRules(projectId, textToInspect, customRegexPattern, hotwordRegexPattern);
  }

  // Inspects a BigQuery Table
  public static void inspectWithHotwordRules(
      String projectId, String textToInspect, String customRegexPattern, String hotwordRegexPattern)
      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();

      // Specify the regex pattern the inspection will look for.
      Regex regex = Regex.newBuilder().setPattern(customRegexPattern).build();

      // Construct the custom regex detector.
      InfoType infoType = InfoType.newBuilder().setName("C_MRN").build();
      CustomInfoType customInfoType =
          CustomInfoType.newBuilder().setInfoType(infoType).setRegex(regex).build();

      // Specify hotword likelihood adjustment.
      LikelihoodAdjustment likelihoodAdjustment =
          LikelihoodAdjustment.newBuilder().setFixedLikelihood(Likelihood.VERY_LIKELY).build();

      // Specify a window around a finding to apply a detection rule.
      Proximity proximity = Proximity.newBuilder().setWindowBefore(10).build();

      // Construct hotword rule.
      HotwordRule hotwordRule =
          HotwordRule.newBuilder()
              .setHotwordRegex(Regex.newBuilder().setPattern(hotwordRegexPattern).build())
              .setLikelihoodAdjustment(likelihoodAdjustment)
              .setProximity(proximity)
              .build();

      // Construct rule set for the inspect config.
      InspectionRuleSet inspectionRuleSet =
          InspectionRuleSet.newBuilder()
              .addInfoTypes(infoType)
              .addRules(InspectionRule.newBuilder().setHotwordRule(hotwordRule))
              .build();

      // Construct the configuration for the Inspect request.
      InspectConfig config =
          InspectConfig.newBuilder()
              .addCustomInfoTypes(customInfoType)
              .setIncludeQuote(true)
              .setMinLikelihood(Likelihood.POSSIBLE)
              .addRuleSet(inspectionRuleSet)
              .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

如需了解如何安装和使用 Cloud DLP 客户端库,请参阅 Cloud DLP 客户端库

def inspect_with_medical_record_number_w_custom_hotwords(
    project, content_string,
):
    """Uses the Data Loss Prevention API to analyze string with medical record
       number custom regex detector, with custom hotwords rules to boost finding
       certainty under some circumstances.

    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 info type called "C_MRN",
    # with ###-#-##### pattern, where each # represents a digit from 1 to 9.
    # The detector has a detection likelihood of POSSIBLE.
    custom_info_types = [
        {
            "info_type": {"name": "C_MRN"},
            "regex": {"pattern": "[1-9]{3}-[1-9]{1}-[1-9]{5}"},
            "likelihood": google.cloud.dlp_v2.Likelihood.POSSIBLE,
        }
    ]

    # Construct a rule set with hotwords "mrn" and "medical", with a likelohood
    # boost to VERY_LIKELY when hotwords are present within the 10 character-
    # window preceding the PII finding.
    hotword_rule = {
        "hotword_regex": {"pattern": "(?i)(mrn|medical)(?-i)"},
        "likelihood_adjustment": {
            "fixed_likelihood": google.cloud.dlp_v2.Likelihood.VERY_LIKELY
        },
        "proximity": {"window_before": 10},
    }

    rule_set = [
        {"info_types": [{"name": "C_MRN"}], "rules": [{"hotword_rule": hotword_rule}]}
    ]

    # Construct the configuration dictionary with the custom regex info type.
    inspect_config = {
        "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.")