カスタム正規表現検出器の作成

正規表現(regex)カスタム infoType 検出器では、Cloud DLP で正規表現パターンに基づいて一致を検出するための独自の検出器を作成できます。たとえば、###-#-##### という形式のカルテ番号があるとします。この場合、次のような正規表現パターンを定義できます。

[0-9]{3}-[0-9]{1}-[0-9]{5}

Cloud DLP は次のような項目を照合します。

012-4-56789

正規表現のカスタム infoType 検出器の詳細

正規表現のカスタム infoType 検出器を作成するには、API の概要で説明されているように以下を指定して CustomInfoType オブジェクトを定義します。

  • カスタム infoType 検出器に付ける名前。InfoType オブジェクト内に指定します。
  • オプションの Likelihood 値。指定しない場合、正規表現一致ではデフォルトの可能性の値 VERY_LIKELY が返されます。正規表現のカスタム infoType 検出器で返される結果に誤判定が多すぎると思われる場合は、基本の可能性の値を引き下げ、検出ルールを使用してコンテキスト情報によって可能性の値を引き上げてみてください。詳細については、結果の可能性のカスタマイズをご覧ください。
  • DetectionRule またはホットワード ルール(省略可)。こうしたルールを適用すると、指定したホットワードの所定の近接範囲内にある結果の可能性を調整できます。ホットワード ルールの詳細については、結果の可能性のカスタマイズをご覧ください。
  • オプションの SensitivityScore 値。このフィールドを省略すると、正規表現と一致したものについて、デフォルトの機密性レベル HIGH が返されます。

    機密性スコアはデータ プロファイルで使用されます。データをプロファイリングする際、Cloud DLP は infoType の機密スコアを使用して機密レベルを計算します。

  • Regex オブジェクト。正規表現を定義する単一のパターンで構成されます。

正規表現のカスタム infoType 検出器は JSON オブジェクトとしてすべての任意指定コンポーネントを含み、次のようになります。

{
  "customInfoTypes":[
    {
      "infoType":{
        "name":"CUSTOM_INFOTYPE_NAME"
      },
      "likelihood":"LIKELIHOOD_LEVEL",
      "detectionRules":[
        {
          "hotwordRule":{
            HOTWORD_RULE
          }
        },
      "sensitivityScore":{
          "score": "SENSITIVITY_SCORE"
        },
      ],
      "regex":{
        "pattern":"REGULAR_EXPRESSION_PATTERN"
      }
    }
  ],
  ...
}

正規表現の例: カルテ番号を照合する

次の JSON スニペットと複数の言語のコードは、入力テキスト「Patient's MRN 444-5-22222」のカルテ番号を照合し、各一致に POSSIBLE の可能性を割り当てるように Cloud DLP に指示する正規表現カスタム infoType 検出器を示しています。

プロトコル

JSON で DLP API を使用する方法については、JSON クイックスタートをご覧ください。

JSON 入力:

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

{
  "item":{
    "value":"Patients MRN 444-5-22222"
  },
  "inspectConfig":{
    "customInfoTypes":[
      {
        "infoType":{
          "name":"C_MRN"
        },
        "regex":{
          "pattern":"[1-9]{3}-[1-9]{1}-[1-9]{5}"
        },
        "likelihood":"POSSIBLE"
      }
    ]
  }
}

JSON 出力:

{
  "result":{
    "findings":[
      {
        "infoType":{
          "name":"C_MRN"
        },
        "likelihood":"POSSIBLE",
        "location":{
          "byteRange":{
            "start":"13",
            "end":"24"
          },
          "codepointRange":{
            "start":"13",
            "end":"24"
          }
        },
        "createTime":"2018-11-30T01:29:37.799Z"
      }
    ]
  }
}

この出力は、指定された「C_MRN」という名前を持つカスタム infoType 検出器とそのカスタム正規表現を使用して、Cloud DLP でカルテ番号が正しく識別され、指定された POSSIBLE という確実性がこの一致に割り当てられたことを示しています。

一致の可能性のカスタマイズでは、この例を基にしてコンテキスト ワードを含めます。

Java

Cloud DLP 用のクライアント ライブラリをインストールして使用する方法については、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.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.Likelihood;
import com.google.privacy.dlp.v2.LocationName;
import com.google.protobuf.ByteString;
import java.io.IOException;

public class InspectWithCustomRegex {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String textToInspect = "Patients MRN 444-5-22222";
    String customRegexPattern = "[1-9]{3}-[1-9]{1}-[1-9]{5}";
    inspectWithCustomRegex(projectId, textToInspect, customRegexPattern);
  }

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

      // Construct the configuration for the Inspect request.
      InspectConfig config =
          InspectConfig.newBuilder()
              .addCustomInfoTypes(customInfoType)
              .setIncludeQuote(true)
              .setMinLikelihood(Likelihood.POSSIBLE)
              .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 クライアント ライブラリをご覧ください。

Cloud DLP に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

import google.cloud.dlp  # noqa: E402, F811

def inspect_with_medical_record_number_custom_regex_detector(
    project: str,
    content_string: str,
) -> None:
    """Uses the Data Loss Prevention API to analyze string with medical record
       number custom regex 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.
    """

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