TextAnalyticsClient クラス

言語サービス API は、クラス最高の Microsoft 機械学習アルゴリズムを使用して構築された自然言語処理 (NLP) スキルのスイートです。 API を使用して、感情分析、キー フレーズ抽出、エンティティ認識、言語検出などのタスクに対して非構造化テキストを分析できます。

その他のドキュメントについては、次のページを参照してください。 https://docs.microsoft.com/azure/cognitive-services/language-service/overview

継承
azure.ai.textanalytics._base_client.TextAnalyticsClientBase
TextAnalyticsClient

コンストラクター

TextAnalyticsClient(endpoint: str, credential: AzureKeyCredential | TokenCredential, *, default_language: str | None = None, default_country_hint: str | None = None, api_version: str | TextAnalyticsApiVersion | None = None, **kwargs: Any)

パラメーター

endpoint
str
必須

サポートされている Cognitive Services または言語リソース エンドポイント (プロトコルとホスト名(例: 'https://.cognitiveservices.azure.com')。

credential
AzureKeyCredential または TokenCredential
必須

クライアントが Azure に接続するために必要な資格情報。 Cognitive Services/Language API キーまたは からの identityトークン資格情報を使用する場合は、AzureKeyCredential のインスタンスを指定できます。

default_country_hint
str

すべての操作に使用する既定のcountry_hintを設定します。 既定値は "US" です。 国ヒントを使用しない場合は、文字列 "none" を渡します。

default_language
str

すべての操作に使用する既定の言語を設定します。 既定値は "en" です。

api_version
str または TextAnalyticsApiVersion

要求に使用するサービスの API バージョン。 既定値は最新のサービス バージョンです。 古いバージョンに設定すると、機能の互換性が低下する可能性があります。

エンドポイントと API キーを使用して TextAnalyticsClient を作成する。


   import os
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import TextAnalyticsClient
   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(endpoint, AzureKeyCredential(key))

Azure Active Directory からのエンドポイントとトークン資格情報を使用して TextAnalyticsClient を作成する。


   import os
   from azure.ai.textanalytics import TextAnalyticsClient
   from azure.identity import DefaultAzureCredential

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   credential = DefaultAzureCredential()

   text_analytics_client = TextAnalyticsClient(endpoint, credential=credential)

メソッド

analyze_sentiment

ドキュメントのバッチのセンチメントを分析します。 show_opinion_miningを使用してオピニオン マイニングを有効にします。

ドキュメントとその中の各文のセンチメント予測と、各センチメント クラス (Positive、Negative、Neutral) のセンチメント スコアを返します。

サービス データの制限に関するページを参照してください https://aka.ms/azsdk/textanalytics/data-limits

バージョン v3.1 の新機能: show_opinion_miningdisable_service_logsstring_index_typeキーワード (keyword)引数。

begin_abstract_summary

実行時間の長い抽象要約操作を開始します。

抽象要約の概念的な説明については、サービスのドキュメントを参照してください。 https://learn.microsoft.com/azure/cognitive-services/language-service/summarization/overview

バージョン 2023-04-01 の新機能: begin_abstract_summary クライアント メソッド。

begin_analyze_actions

実行時間の長い操作を開始して、ドキュメントのバッチに対してさまざまなテキスト分析アクションを実行します。

より大きなドキュメントを分析する場合、または複数のテキスト分析アクションを 1 回の呼び出しに結合する場合は、この関数を使用することをお勧めします。 それ以外の場合は、アクション固有のエンドポイント (例: analyze_sentiment) を使用することをお勧めします。

Note

カスタム アクション機能のリージョン サポートについては、サービスドキュメントを参照してください。

https://aka.ms/azsdk/textanalytics/customfunctionalities

バージョン v3.1 の新機能: begin_analyze_actions クライアント メソッド。

バージョン 2022-05-01 の新機能: RecognizeCustomEntitiesActionSingleLabelClassifyActionMultiLabelClassifyActionAnalyzeHealthcareEntitiesAction 入力オプション、および対応する RecognizeCustomEntitiesResultClassifyDocumentResultAnalyzeHealthcareEntitiesResult 結果オブジェクト

バージョン 2023-04-01 の新機能: ExtractiveSummaryAction および AbstractiveSummaryAction 入力オプションと、対応する ExtractiveSummaryResult および AbstractiveSummaryResult 結果オブジェクト。

begin_analyze_healthcare_entities

医療エンティティを分析し、ドキュメントのバッチでこれらのエンティティ間のリレーションシップを特定します。

エンティティは、UMLS、CHV、MSH などの既存のナレッジ ベースで見つかる参照に関連付けられます。

我々はまた、エンティティ間で見つかった関係を抽出します, 例えば、「対象は100mgのイブプロフェンを取った」, 我々は、間の関係を抽出します "100 mg" 投与量と "イブプロフェン" 薬.

バージョン v3.1 の新機能: begin_analyze_healthcare_entities クライアント メソッド。

バージョン 2022-05-01 の新機能: 引数 display_name キーワード (keyword)。

begin_extract_summary

実行時間の長い抽出要約操作を開始します。

抽出要約の概念については、サービスのドキュメントを参照してください。 https://learn.microsoft.com/azure/cognitive-services/language-service/summarization/overview

バージョン 2023-04-01 の新機能: begin_extract_summary クライアント メソッド。

begin_multi_label_classify

実行時間の長いカスタム の複数ラベル分類操作を開始します。

カスタム機能の地域的なサポートと、ドキュメントを分類するためのモデルのトレーニング方法については、次を参照してください。 https://aka.ms/azsdk/textanalytics/customfunctionalities

バージョン 2022-05-01 の新機能: begin_multi_label_classify クライアント メソッド。

begin_recognize_custom_entities

実行時間の長いカスタムの名前付きエンティティ認識操作を開始します。

カスタム機能のリージョンサポートと、カスタム エンティティを認識するようにモデルをトレーニングする方法については、以下を参照してください。 https://aka.ms/azsdk/textanalytics/customentityrecognition

バージョン 2022-05-01 の新機能: begin_recognize_custom_entities クライアント メソッド。

begin_single_label_classify

実行時間の長いカスタム 単一ラベル分類操作を開始します。

カスタム機能の地域的なサポートと、ドキュメントを分類するためのモデルのトレーニング方法については、次を参照してください。 https://aka.ms/azsdk/textanalytics/customfunctionalities

バージョン 2022-05-01 の新機能: begin_single_label_classify クライアント メソッド。

close

クライアントによって開かれたソケットを閉じます。 クライアントをコンテキスト マネージャーとして使用する場合、このメソッドの呼び出しは不要です。

detect_language

ドキュメントのバッチの言語を検出します。

検出された言語と、0 から 1 までの数値スコアを返します。 1 に近いスコアは、識別された言語が true であることを 100% 確実性で示します。 有効な言語の一覧については、「」を参照してください https://aka.ms/talangs

サービス データの制限に関するページを参照してください https://aka.ms/azsdk/textanalytics/data-limits

バージョン v3.1 の新機能: disable_service_logs キーワード (keyword)引数。

extract_key_phrases

ドキュメントのバッチからキー フレーズを抽出します。

入力テキスト内のキー フレーズを示す文字列の一覧を返します。 たとえば、"食べ物は美味しく、素晴らしいスタッフがいました" という入力テキストの場合、API は"food" と "wonderful staff" というメインの話し合いポイントを返します。

サービス データの制限に関するページを参照してください https://aka.ms/azsdk/textanalytics/data-limits

バージョン v3.1 の新機能: disable_service_logs キーワード (keyword)引数。

recognize_entities

ドキュメントのバッチのエンティティを認識します。

テキスト内のエンティティをユーザー、場所、組織、日付/時刻、数量、パーセンテージ、通貨などに識別して分類します。 サポートされているエンティティ型の一覧については、次チェック。https://aka.ms/taner

サービス データの制限に関するページを参照してください https://aka.ms/azsdk/textanalytics/data-limits

バージョン v3.1 の新機能: 引数のdisable_service_logsstring_index_typeキーワード (keyword)。

recognize_linked_entities

ドキュメントのバッチについて、既知のサポート情報からリンクされたエンティティを認識します。

テキストで見つかった各エンティティの ID を識別し、あいまいさを解消します (たとえば、Mars という単語の出現が惑星を指しているのか、ローマの戦争の神を指しているのかを判断します)。 認識されたエンティティは、Wikipedia などのよく知られたサポート情報への URL に関連付けられます。

サービス データの制限に関するページを参照してください https://aka.ms/azsdk/textanalytics/data-limits

バージョン v3.1 の新機能: 引数のdisable_service_logsstring_index_typeキーワード (keyword)。

recognize_pii_entities

ドキュメントのバッチの個人情報を含むエンティティを認識します。

ドキュメント内の個人情報エンティティ ("SSN"、"銀行口座"など) の一覧を返します。 サポートされているエンティティ型の一覧については、チェック https://aka.ms/azsdk/language/pii

サービス データの制限に関するページを参照してください https://aka.ms/azsdk/textanalytics/data-limits

バージョン v3.1 の新機能: recognize_pii_entities クライアント メソッド。

analyze_sentiment

ドキュメントのバッチのセンチメントを分析します。 show_opinion_miningを使用してオピニオン マイニングを有効にします。

ドキュメントとその中の各文のセンチメント予測と、各センチメント クラス (Positive、Negative、Neutral) のセンチメント スコアを返します。

サービス データの制限に関するページを参照してください https://aka.ms/azsdk/textanalytics/data-limits

バージョン v3.1 の新機能: show_opinion_miningdisable_service_logsstring_index_typeキーワード (keyword)引数。

analyze_sentiment(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], *, disable_service_logs: bool | None = None, language: str | None = None, model_version: str | None = None, show_opinion_mining: bool | None = None, show_stats: bool | None = None, string_index_type: str | None = None, **kwargs: Any) -> List[AnalyzeSentimentResult | DocumentError]

パラメーター

documents
list[str] または list[TextDocumentInput] または list[dict[str, str]]
必須

このバッチの一部として処理するドキュメントのセット。 項目ごとに ID と言語を指定する場合は、入力として list[TextDocumentInput] または 、{"id": "1"、"language": "en"、"text": "hello world"} などの dict 表現TextDocumentInputのリストとして使用する必要があります。

show_opinion_mining
bool

文の意見をマイニングし、製品またはサービスの側面に関してより詳細な分析を行うかどうか (アスペクトベースの感情分析とも呼ばれます)。 true に設定すると、返される SentenceSentiment オブジェクトには、この分析の結果を含むプロパティ mined_opinions があります。 API バージョン v3.1 以降でのみ使用できます。

language
str

バッチ全体の 2 文字の ISO 639-1 言語表現。 たとえば、英語の場合は "en" を使用します。スペイン語などの "es"設定されていない場合は、英語の "en" を既定として使用します。 ドキュメントごとの言語は、バッチ言語全体よりも優先されます。 言語 API でサポートされている言語については、「」を参照してください https://aka.ms/talangs

model_version
str

分析に使用するモデル バージョン ("最新" など)。 モデル バージョンが指定されていない場合、API は既定で最新のプレビュー以外のバージョンになります。 詳細については、こちらを参照してください。 https://aka.ms/text-analytics-model-versioning

show_stats
bool

true に設定すると、応答にはドキュメント レベルの応答の統計フィールドにドキュメント レベルの 統計 が含まれます。

string_index_type
str

文字列オフセットの解釈に使用するメソッドを指定します。 Python エンコードである UnicodeCodePoint が既定です。 Python の既定値をオーバーライドするには、 Utf16CodeUnit または TextElement_v8 を渡すこともできます。 詳細については、以下を参照してください。 https://aka.ms/text-analytics-offsets

disable_service_logs
bool

true に設定すると、トラブルシューティングのためにテキスト入力がサービス側でログに記録されるのをオプトアウトします。 既定では、言語サービスは入力テキストを 48 時間ログに記録します。これは、サービスの自然言語処理機能を提供する際の問題のトラブルシューティングのみを可能にします。 このパラメーターを true に設定すると、入力ログが無効になり、発生した問題を修復する機能が制限される可能性があります。 詳細については、「Cognitive Services のコンプライアンスとプライバシーに関する注意事項 https://aka.ms/cs-compliance 」、および「Microsoft の責任ある AI の原則 https://www.microsoft.com/ai/responsible-ai」を参照してください。

戻り値

元のドキュメントが AnalyzeSentimentResult 渡された順序での と DocumentError の組み合わせリスト。

の戻り値の型 :

例外

ドキュメントのバッチでセンチメントを分析します。


   import os
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import TextAnalyticsClient

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))

   documents = [
       """I had the best day of my life. I decided to go sky-diving and it made me appreciate my whole life so much more.
       I developed a deep-connection with my instructor as well, and I feel as if I've made a life-long friend in her.""",
       """This was a waste of my time. All of the views on this drop are extremely boring, all I saw was grass. 0/10 would
       not recommend to any divers, even first timers.""",
       """This was pretty good! The sights were ok, and I had fun with my instructors! Can't complain too much about my experience""",
       """I only have one word for my experience: WOW!!! I can't believe I have had such a wonderful skydiving company right
       in my backyard this whole time! I will definitely be a repeat customer, and I want to take my grandmother skydiving too,
       I know she'll love it!"""
   ]


   result = text_analytics_client.analyze_sentiment(documents, show_opinion_mining=True)
   docs = [doc for doc in result if not doc.is_error]

   print("Let's visualize the sentiment of each of these documents")
   for idx, doc in enumerate(docs):
       print(f"Document text: {documents[idx]}")
       print(f"Overall sentiment: {doc.sentiment}")

begin_abstract_summary

実行時間の長い抽象要約操作を開始します。

抽象要約の概念的な説明については、サービスのドキュメントを参照してください。 https://learn.microsoft.com/azure/cognitive-services/language-service/summarization/overview

バージョン 2023-04-01 の新機能: begin_abstract_summary クライアント メソッド。

begin_abstract_summary(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], *, continuation_token: str | None = None, disable_service_logs: bool | None = None, display_name: str | None = None, language: str | None = None, polling_interval: int | None = None, show_stats: bool | None = None, model_version: str | None = None, string_index_type: str | None = None, sentence_count: int | None = None, **kwargs: Any) -> TextAnalysisLROPoller[ItemPaged[AbstractiveSummaryResult | DocumentError]]

パラメーター

documents
list[str] または list[TextDocumentInput] または list[dict[str, str]]
必須

このバッチの一部として処理するドキュメントのセット。 項目ごとに ID と言語を指定する場合は、入力として list[TextDocumentInput] または 、{"id": "1"、"language": "en"、"text": "hello world"} などの dict 表現TextDocumentInputのリストとして使用する必要があります。

language
str

バッチ全体の 2 文字の ISO 639-1 言語表現。 たとえば、英語の場合は "en" を使用します。スペイン語などの "es"設定されていない場合は、英語の "en" を既定として使用します。 ドキュメントごとの言語は、バッチ言語全体よりも優先されます。 言語 API でサポートされている言語については、「」を参照してください https://aka.ms/talangs

show_stats
bool

true に設定すると、応答にはドキュメント レベルの統計が含まれます。

sentence_count
Optional[int]

出力サマリー内の文のおおよその数を制御します。

model_version
Optional[str]

分析に使用するモデル バージョン ("最新" など)。 モデル バージョンが指定されていない場合、API は既定で最新のプレビュー以外のバージョンになります。 詳細については、こちらを参照してください。 https://aka.ms/text-analytics-model-versioning

string_index_type
Optional[str]

文字列オフセットの解釈に使用するメソッドを指定します。

disable_service_logs
bool

true に設定すると、トラブルシューティングのためにテキスト入力がサービス側でログに記録されるのをオプトアウトします。 既定では、言語サービスは入力テキストを 48 時間ログに記録します。これは、サービスの自然言語処理機能を提供する際の問題のトラブルシューティングのみを可能にします。 このパラメーターを true に設定すると、入力ログが無効になり、発生した問題を修復する機能が制限される可能性があります。 詳細については、「Cognitive Services のコンプライアンスとプライバシーに関する注意事項 https://aka.ms/cs-compliance 」、および「Microsoft の責任ある AI の原則 https://www.microsoft.com/ai/responsible-ai」を参照してください。

polling_interval
int

Retry-After ヘッダーが存在しない場合、LRO 操作の 2 つのポーリングの間の待機時間。 既定値は 5 秒です。

continuation_token
str

poller オブジェクト で continuation_token() を呼び出して、実行時間の長い操作 (LRO) 状態を不透明なトークンに保存します。 値を continuation_token キーワード (keyword) 引数として渡して、保存された状態から LRO を再起動します。

display_name
str

要求された分析に設定するオプションの表示名。

戻り値

TextAnalysisLROPoller のインスタンス。 このオブジェクトで result() を呼び出して、 と DocumentErrorAbstractiveSummaryResult異種ページング可能を返します。

の戻り値の型 :

例外

ドキュメントのバッチに対して抽象要約を実行します。


   import os
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import TextAnalyticsClient

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(
       endpoint=endpoint,
       credential=AzureKeyCredential(key),
   )

   document = [
       "At Microsoft, we have been on a quest to advance AI beyond existing techniques, by taking a more holistic, "
       "human-centric approach to learning and understanding. As Chief Technology Officer of Azure AI Cognitive "
       "Services, I have been working with a team of amazing scientists and engineers to turn this quest into a "
       "reality. In my role, I enjoy a unique perspective in viewing the relationship among three attributes of "
       "human cognition: monolingual text (X), audio or visual sensory signals, (Y) and multilingual (Z). At the "
       "intersection of all three, there's magic-what we call XYZ-code as illustrated in Figure 1-a joint "
       "representation to create more powerful AI that can speak, hear, see, and understand humans better. "
       "We believe XYZ-code will enable us to fulfill our long-term vision: cross-domain transfer learning, "
       "spanning modalities and languages. The goal is to have pretrained models that can jointly learn "
       "representations to support a broad range of downstream AI tasks, much in the way humans do today. "
       "Over the past five years, we have achieved human performance on benchmarks in conversational speech "
       "recognition, machine translation, conversational question answering, machine reading comprehension, "
       "and image captioning. These five breakthroughs provided us with strong signals toward our more ambitious "
       "aspiration to produce a leap in AI capabilities, achieving multisensory and multilingual learning that "
       "is closer in line with how humans learn and understand. I believe the joint XYZ-code is a foundational "
       "component of this aspiration, if grounded with external knowledge sources in the downstream AI tasks."
   ]

   poller = text_analytics_client.begin_abstract_summary(document)
   abstract_summary_results = poller.result()
   for result in abstract_summary_results:
       if result.kind == "AbstractiveSummarization":
           print("Summaries abstracted:")
           [print(f"{summary.text}\n") for summary in result.summaries]
       elif result.is_error is True:
           print("...Is an error with code '{}' and message '{}'".format(
               result.error.code, result.error.message
           ))

begin_analyze_actions

実行時間の長い操作を開始して、ドキュメントのバッチに対してさまざまなテキスト分析アクションを実行します。

より大きなドキュメントを分析する場合、または複数のテキスト分析アクションを 1 回の呼び出しに結合する場合は、この関数を使用することをお勧めします。 それ以外の場合は、アクション固有のエンドポイント (例: analyze_sentiment) を使用することをお勧めします。

Note

カスタム アクション機能のリージョン サポートについては、サービスドキュメントを参照してください。

https://aka.ms/azsdk/textanalytics/customfunctionalities

バージョン v3.1 の新機能: begin_analyze_actions クライアント メソッド。

バージョン 2022-05-01 の新機能: RecognizeCustomEntitiesActionSingleLabelClassifyActionMultiLabelClassifyActionAnalyzeHealthcareEntitiesAction 入力オプション、および対応する RecognizeCustomEntitiesResultClassifyDocumentResultAnalyzeHealthcareEntitiesResult 結果オブジェクト

バージョン 2023-04-01 の新機能: ExtractiveSummaryAction および AbstractiveSummaryAction 入力オプションと、対応する ExtractiveSummaryResult および AbstractiveSummaryResult 結果オブジェクト。

begin_analyze_actions(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], actions: List[RecognizeEntitiesAction | RecognizeLinkedEntitiesAction | RecognizePiiEntitiesAction | ExtractKeyPhrasesAction | AnalyzeSentimentAction | RecognizeCustomEntitiesAction | SingleLabelClassifyAction | MultiLabelClassifyAction | AnalyzeHealthcareEntitiesAction | ExtractiveSummaryAction | AbstractiveSummaryAction], *, continuation_token: str | None = None, display_name: str | None = None, language: str | None = None, polling_interval: int | None = None, show_stats: bool | None = None, **kwargs: Any) -> TextAnalysisLROPoller[ItemPaged[List[RecognizeEntitiesResult | RecognizeLinkedEntitiesResult | RecognizePiiEntitiesResult | ExtractKeyPhrasesResult | AnalyzeSentimentResult | RecognizeCustomEntitiesResult | ClassifyDocumentResult | AnalyzeHealthcareEntitiesResult | ExtractiveSummaryResult | AbstractiveSummaryResult | DocumentError]]]

パラメーター

documents
list[str] または list[TextDocumentInput] または list[dict[str, str]]
必須

このバッチの一部として処理するドキュメントのセット。 項目ごとに ID と言語を指定する場合は、入力として list[TextDocumentInput] または 、{"id": "1"、"language": "en"、"text": "hello world"} などの dict 表現TextDocumentInputのリストとして使用する必要があります。

actions
list[RecognizeEntitiesAction または RecognizePiiEntitiesAction または ExtractKeyPhrasesAction または RecognizeLinkedEntitiesAction または AnalyzeSentimentAction または RecognizeCustomEntitiesAction または SingleLabelClassifyAction または MultiLabelClassifyAction または AnalyzeHealthcareEntitiesAction または ExtractiveSummaryAction または AbstractiveSummaryAction]
必須

入力ドキュメントに対して実行するアクションの異種リスト。 各アクション オブジェクトは、特定のアクションの種類に使用されるパラメーターをカプセル化します。 アクションの結果は、入力アクションと同じ順序になります。

display_name
str

要求された分析に設定するオプションの表示名。

language
str

バッチ全体の 2 文字の ISO 639-1 言語表現。 たとえば、英語の場合は "en" を使用します。スペイン語などの "es"設定されていない場合は、英語の "en" を既定として使用します。 ドキュメントごとの言語は、バッチ言語全体よりも優先されます。 言語 API でサポートされている言語については、「」を参照してください https://aka.ms/talangs

show_stats
bool

true に設定すると、応答にはドキュメント レベルの統計が含まれます。

polling_interval
int

Retry-After ヘッダーが存在しない場合、LRO 操作の 2 つのポーリングの間の待機時間。 既定値は 5 秒です。

continuation_token
str

poller オブジェクト で continuation_token() を呼び出して、実行時間の長い操作 (LRO) 状態を不透明なトークンに保存します。 値を continuation_token キーワード (keyword) 引数として渡して、保存された状態から LRO を再起動します。

戻り値

TextAnalysisLROPoller のインスタンス。 poller オブジェクトで result() を呼び出して、ページング可能な異種リストのリストを返します。 このリストの一覧は、最初に入力したドキュメントで並べ替え、次に入力したアクションで並べ替えます。 たとえば、リストの一覧を反復処理するときに、ドキュメントの入力 ["Hello"、"world"]、および actions RecognizeEntitiesActionAnalyzeSentimentActionがある場合は、最初に "Hello" ドキュメントのアクション結果を反復処理し、"Hello" を取得し、次に "Hello" を取得 RecognizeEntitiesResult します AnalyzeSentimentResult 。 次に、"世界" の と AnalyzeSentimentResult を取得RecognizeEntitiesResultします。

の戻り値の型 :

例外

実行時間の長い操作を開始して、ドキュメントのバッチに対してさまざまなテキスト分析アクションを実行します。


   import os
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import (
       TextAnalyticsClient,
       RecognizeEntitiesAction,
       RecognizeLinkedEntitiesAction,
       RecognizePiiEntitiesAction,
       ExtractKeyPhrasesAction,
       AnalyzeSentimentAction,
   )

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(
       endpoint=endpoint,
       credential=AzureKeyCredential(key),
   )

   documents = [
       'We went to Contoso Steakhouse located at midtown NYC last week for a dinner party, and we adore the spot! '
       'They provide marvelous food and they have a great menu. The chief cook happens to be the owner (I think his name is John Doe) '
       'and he is super nice, coming out of the kitchen and greeted us all.'
       ,

       'We enjoyed very much dining in the place! '
       'The Sirloin steak I ordered was tender and juicy, and the place was impeccably clean. You can even pre-order from their '
       'online menu at www.contososteakhouse.com, call 312-555-0176 or send email to order@contososteakhouse.com! '
       'The only complaint I have is the food didn\'t come fast enough. Overall I highly recommend it!'
   ]

   poller = text_analytics_client.begin_analyze_actions(
       documents,
       display_name="Sample Text Analysis",
       actions=[
           RecognizeEntitiesAction(),
           RecognizePiiEntitiesAction(),
           ExtractKeyPhrasesAction(),
           RecognizeLinkedEntitiesAction(),
           AnalyzeSentimentAction(),
       ],
   )

   document_results = poller.result()
   for doc, action_results in zip(documents, document_results):
       print(f"\nDocument text: {doc}")
       for result in action_results:
           if result.kind == "EntityRecognition":
               print("...Results of Recognize Entities Action:")
               for entity in result.entities:
                   print(f"......Entity: {entity.text}")
                   print(f".........Category: {entity.category}")
                   print(f".........Confidence Score: {entity.confidence_score}")
                   print(f".........Offset: {entity.offset}")

           elif result.kind == "PiiEntityRecognition":
               print("...Results of Recognize PII Entities action:")
               for pii_entity in result.entities:
                   print(f"......Entity: {pii_entity.text}")
                   print(f".........Category: {pii_entity.category}")
                   print(f".........Confidence Score: {pii_entity.confidence_score}")

           elif result.kind == "KeyPhraseExtraction":
               print("...Results of Extract Key Phrases action:")
               print(f"......Key Phrases: {result.key_phrases}")

           elif result.kind == "EntityLinking":
               print("...Results of Recognize Linked Entities action:")
               for linked_entity in result.entities:
                   print(f"......Entity name: {linked_entity.name}")
                   print(f".........Data source: {linked_entity.data_source}")
                   print(f".........Data source language: {linked_entity.language}")
                   print(
                       f".........Data source entity ID: {linked_entity.data_source_entity_id}"
                   )
                   print(f".........Data source URL: {linked_entity.url}")
                   print(".........Document matches:")
                   for match in linked_entity.matches:
                       print(f"............Match text: {match.text}")
                       print(f"............Confidence Score: {match.confidence_score}")
                       print(f"............Offset: {match.offset}")
                       print(f"............Length: {match.length}")

           elif result.kind == "SentimentAnalysis":
               print("...Results of Analyze Sentiment action:")
               print(f"......Overall sentiment: {result.sentiment}")
               print(
                   f"......Scores: positive={result.confidence_scores.positive}; \
                   neutral={result.confidence_scores.neutral}; \
                   negative={result.confidence_scores.negative} \n"
               )

           elif result.is_error is True:
               print(
                   f"...Is an error with code '{result.error.code}' and message '{result.error.message}'"
               )

       print("------------------------------------------")


begin_analyze_healthcare_entities

医療エンティティを分析し、ドキュメントのバッチでこれらのエンティティ間のリレーションシップを特定します。

エンティティは、UMLS、CHV、MSH などの既存のナレッジ ベースで見つかる参照に関連付けられます。

我々はまた、エンティティ間で見つかった関係を抽出します, 例えば、「対象は100mgのイブプロフェンを取った」, 我々は、間の関係を抽出します "100 mg" 投与量と "イブプロフェン" 薬.

バージョン v3.1 の新機能: begin_analyze_healthcare_entities クライアント メソッド。

バージョン 2022-05-01 の新機能: 引数 display_name キーワード (keyword)。

begin_analyze_healthcare_entities(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], *, continuation_token: str | None = None, disable_service_logs: bool | None = None, display_name: str | None = None, language: str | None = None, model_version: str | None = None, polling_interval: int | None = None, show_stats: bool | None = None, string_index_type: str | None = None, **kwargs: Any) -> AnalyzeHealthcareEntitiesLROPoller[ItemPaged[AnalyzeHealthcareEntitiesResult | DocumentError]]

パラメーター

documents
list[str] または list[TextDocumentInput] または list[dict[str, str]]
必須

このバッチの一部として処理するドキュメントのセット。 項目ごとに ID と言語を指定する場合は、入力として、{"id": "1","language": "en", "text": "hello world"} などの、list[TextDocumentInput] または dict 表現TextDocumentInputのリストとして使用する必要があります。

model_version
str

分析に使用するモデル バージョン (例: "latest")。 モデル バージョンが指定されていない場合、API は既定で最新のプレビュー以外のバージョンになります。 詳細については、こちらを参照してください。 https://aka.ms/text-analytics-model-versioning

show_stats
bool

true に設定すると、応答にはドキュメント レベルの統計情報が含まれます。

language
str

バッチ全体の 2 文字の ISO 639-1 言語表現。 たとえば、英語には "en" を使用します。スペイン語などの "es"設定されていない場合は、既定で英語に "en" を使用します。 ドキュメントごとの言語は、バッチ言語全体よりも優先されます。 言語 API でサポートされている言語については、「」を参照してください https://aka.ms/talangs

display_name
str

要求された分析に設定するオプションの表示名。

string_index_type
str

文字列オフセットを解釈するために使用するメソッドを指定します。 UnicodeCodePoint (Python エンコード) が既定値です。 Python の既定値をオーバーライドするには、 Utf16CodeUnit または TextElement_v8を渡すこともできます。 詳細については、次を参照してください。 https://aka.ms/text-analytics-offsets

polling_interval
int

Retry-After ヘッダーがない場合の LRO 操作の 2 つのポーリング間の待機時間。 既定値は 5 秒です。

continuation_token
str

poller オブジェクト で continuation_token() を呼び出して、実行時間の長い操作 (LRO) 状態を不透明なトークンに保存します。 値を continuation_token キーワード (keyword) 引数として渡して、保存された状態から LRO を再起動します。

disable_service_logs
bool

既定値は true です。つまり、言語サービスはトラブルシューティングのためにサービス側で入力テキストをログに記録しません。 False に設定すると、言語サービスは入力テキストを 48 時間ログに記録します。これは、サービスの自然言語処理機能を提供する際の問題のトラブルシューティングのみを可能にするためです。 詳細については、Cognitive Services のコンプライアンスとプライバシーに関する注意事項 https://aka.ms/cs-compliance に関するページ、および Microsoft 責任ある AI の原則については、 を https://www.microsoft.com/ai/responsible-ai参照してください。

戻り値

AnalyzeHealthcareEntitiesLROPoller のインスタンス。 このオブジェクトで result() を呼び出して、 と DocumentErrorAnalyzeHealthcareEntitiesResult異種ページング可能な を返します。

の戻り値の型 :

例外

ドキュメントのバッチで医療エンティティを認識します。


   import os
   import typing
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import TextAnalyticsClient, HealthcareEntityRelation

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(
       endpoint=endpoint,
       credential=AzureKeyCredential(key),
   )

   documents = [
       """
       Patient needs to take 100 mg of ibuprofen, and 3 mg of potassium. Also needs to take
       10 mg of Zocor.
       """,
       """
       Patient needs to take 50 mg of ibuprofen, and 2 mg of Coumadin.
       """
   ]

   poller = text_analytics_client.begin_analyze_healthcare_entities(documents)
   result = poller.result()

   docs = [doc for doc in result if not doc.is_error]

   print("Let's first visualize the outputted healthcare result:")
   for doc in docs:
       for entity in doc.entities:
           print(f"Entity: {entity.text}")
           print(f"...Normalized Text: {entity.normalized_text}")
           print(f"...Category: {entity.category}")
           print(f"...Subcategory: {entity.subcategory}")
           print(f"...Offset: {entity.offset}")
           print(f"...Confidence score: {entity.confidence_score}")
           if entity.data_sources is not None:
               print("...Data Sources:")
               for data_source in entity.data_sources:
                   print(f"......Entity ID: {data_source.entity_id}")
                   print(f"......Name: {data_source.name}")
           if entity.assertion is not None:
               print("...Assertion:")
               print(f"......Conditionality: {entity.assertion.conditionality}")
               print(f"......Certainty: {entity.assertion.certainty}")
               print(f"......Association: {entity.assertion.association}")
       for relation in doc.entity_relations:
           print(f"Relation of type: {relation.relation_type} has the following roles")
           for role in relation.roles:
               print(f"...Role '{role.name}' with entity '{role.entity.text}'")
       print("------------------------------------------")

   print("Now, let's get all of medication dosage relations from the documents")
   dosage_of_medication_relations = [
       entity_relation
       for doc in docs
       for entity_relation in doc.entity_relations if entity_relation.relation_type == HealthcareEntityRelation.DOSAGE_OF_MEDICATION
   ]

begin_extract_summary

実行時間の長い抽出要約操作を開始します。

抽出要約の概念については、サービスのドキュメントを参照してください。 https://learn.microsoft.com/azure/cognitive-services/language-service/summarization/overview

バージョン 2023-04-01 の新機能: begin_extract_summary クライアント メソッド。

begin_extract_summary(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], *, continuation_token: str | None = None, disable_service_logs: bool | None = None, display_name: str | None = None, language: str | None = None, polling_interval: int | None = None, show_stats: bool | None = None, model_version: str | None = None, string_index_type: str | None = None, max_sentence_count: int | None = None, order_by: Literal['Rank', 'Offset'] | None = None, **kwargs: Any) -> TextAnalysisLROPoller[ItemPaged[ExtractiveSummaryResult | DocumentError]]

パラメーター

documents
list[str] または list[TextDocumentInput] または list[dict[str, str]]
必須

このバッチの一部として処理するドキュメントのセット。 項目ごとに ID と言語を指定する場合は、入力として、{"id": "1","language": "en", "text": "hello world"} などの、list[TextDocumentInput] または dict 表現TextDocumentInputのリストとして使用する必要があります。

language
str

バッチ全体の 2 文字の ISO 639-1 言語表現。 たとえば、英語には "en" を使用します。スペイン語などの "es"設定されていない場合は、既定で英語に "en" を使用します。 ドキュメントごとの言語は、バッチ言語全体よりも優先されます。 言語 API でサポートされている言語については、「」を参照してください https://aka.ms/talangs

show_stats
bool

true に設定すると、応答にはドキュメント レベルの統計情報が含まれます。

max_sentence_count
Optional[int]

返される文の最大数。 既定値は 3 です。

order_by
Optional[str]

指定できる値は、"Offset"、"Rank" です。 既定値は "Offset" です。

model_version
Optional[str]

分析に使用するモデル バージョン (例: "latest")。 モデル バージョンが指定されていない場合、API は既定で最新のプレビュー以外のバージョンになります。 詳細については、こちらを参照してください。 https://aka.ms/text-analytics-model-versioning

string_index_type
Optional[str]

文字列オフセットを解釈するために使用するメソッドを指定します。

disable_service_logs
bool

true に設定した場合、トラブルシューティングのためにサービス側でテキスト入力がログに記録されるのをオプトアウトします。 既定では、言語サービスは、サービスの自然言語処理機能を提供する際の問題のトラブルシューティングのみを可能にするために、入力テキストを 48 時間ログに記録します。 このパラメーターを true に設定すると、入力ログが無効になり、発生した問題を修復する機能が制限される可能性があります。 詳細については、Cognitive Services のコンプライアンスとプライバシーに関する注意事項 https://aka.ms/cs-compliance に関するページ、および Microsoft 責任ある AI の原則については、 を https://www.microsoft.com/ai/responsible-ai参照してください。

polling_interval
int

Retry-After ヘッダーがない場合の LRO 操作の 2 つのポーリング間の待機時間。 既定値は 5 秒です。

continuation_token
str

poller オブジェクト で continuation_token() を呼び出して、実行時間の長い操作 (LRO) 状態を不透明なトークンに保存します。 値を continuation_token キーワード (keyword) 引数として渡して、保存された状態から LRO を再起動します。

display_name
str

要求された分析に設定するオプションの表示名。

戻り値

TextAnalysisLROPoller のインスタンス。 このオブジェクトで result() を呼び出して、 と DocumentErrorExtractiveSummaryResult異種ページング可能な を返します。

の戻り値の型 :

例外

ドキュメントのバッチに対して抽出要約を実行します。


   import os
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import TextAnalyticsClient

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(
       endpoint=endpoint,
       credential=AzureKeyCredential(key),
   )

   document = [
       "At Microsoft, we have been on a quest to advance AI beyond existing techniques, by taking a more holistic, "
       "human-centric approach to learning and understanding. As Chief Technology Officer of Azure AI Cognitive "
       "Services, I have been working with a team of amazing scientists and engineers to turn this quest into a "
       "reality. In my role, I enjoy a unique perspective in viewing the relationship among three attributes of "
       "human cognition: monolingual text (X), audio or visual sensory signals, (Y) and multilingual (Z). At the "
       "intersection of all three, there's magic-what we call XYZ-code as illustrated in Figure 1-a joint "
       "representation to create more powerful AI that can speak, hear, see, and understand humans better. "
       "We believe XYZ-code will enable us to fulfill our long-term vision: cross-domain transfer learning, "
       "spanning modalities and languages. The goal is to have pretrained models that can jointly learn "
       "representations to support a broad range of downstream AI tasks, much in the way humans do today. "
       "Over the past five years, we have achieved human performance on benchmarks in conversational speech "
       "recognition, machine translation, conversational question answering, machine reading comprehension, "
       "and image captioning. These five breakthroughs provided us with strong signals toward our more ambitious "
       "aspiration to produce a leap in AI capabilities, achieving multisensory and multilingual learning that "
       "is closer in line with how humans learn and understand. I believe the joint XYZ-code is a foundational "
       "component of this aspiration, if grounded with external knowledge sources in the downstream AI tasks."
   ]

   poller = text_analytics_client.begin_extract_summary(document)
   extract_summary_results = poller.result()
   for result in extract_summary_results:
       if result.kind == "ExtractiveSummarization":
           print("Summary extracted: \n{}".format(
               " ".join([sentence.text for sentence in result.sentences]))
           )
       elif result.is_error is True:
           print("...Is an error with code '{}' and message '{}'".format(
               result.error.code, result.error.message
           ))

begin_multi_label_classify

実行時間の長いカスタム の複数ラベル分類操作を開始します。

カスタム機能の地域的なサポートと、ドキュメントを分類するためのモデルのトレーニング方法については、次を参照してください。 https://aka.ms/azsdk/textanalytics/customfunctionalities

バージョン 2022-05-01 の新機能: begin_multi_label_classify クライアント メソッド。

begin_multi_label_classify(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], project_name: str, deployment_name: str, *, continuation_token: str | None = None, disable_service_logs: bool | None = None, display_name: str | None = None, language: str | None = None, polling_interval: int | None = None, show_stats: bool | None = None, **kwargs: Any) -> TextAnalysisLROPoller[ItemPaged[ClassifyDocumentResult | DocumentError]]

パラメーター

documents
list[str] または list[TextDocumentInput] または list[dict[str, str]]
必須

このバッチの一部として処理するドキュメントのセット。 項目ごとに ID と言語を指定する場合は、入力として、{"id": "1","language": "en", "text": "hello world"} などの、list[TextDocumentInput] または dict 表現TextDocumentInputのリストとして使用する必要があります。

project_name
str
必須

必須。 このフィールドは、モデルのプロジェクト名を示します。

deployment_name
str
必須

このフィールドは、モデルのデプロイ名を示します。

language
str

バッチ全体の 2 文字の ISO 639-1 言語表現。 たとえば、英語には "en" を使用します。スペイン語などの "es"設定されていない場合は、既定で英語に "en" を使用します。 ドキュメントごとの言語は、バッチ言語全体よりも優先されます。 言語 API でサポートされている言語については、「」を参照してください https://aka.ms/talangs

show_stats
bool

true に設定すると、応答にはドキュメント レベルの統計情報が含まれます。

disable_service_logs
bool

true に設定した場合、トラブルシューティングのためにサービス側でテキスト入力がログに記録されるのをオプトアウトします。 既定では、言語サービスは、サービスの自然言語処理機能を提供する際の問題のトラブルシューティングのみを可能にするために、入力テキストを 48 時間ログに記録します。 このパラメーターを true に設定すると、入力ログが無効になり、発生した問題を修復する機能が制限される可能性があります。 詳細については、Cognitive Services のコンプライアンスとプライバシーに関する注意事項 https://aka.ms/cs-compliance に関するページ、および Microsoft 責任ある AI の原則については、 を https://www.microsoft.com/ai/responsible-ai参照してください。

polling_interval
int

Retry-After ヘッダーがない場合の LRO 操作の 2 つのポーリング間の待機時間。 既定値は 5 秒です。

continuation_token
str

poller オブジェクト で continuation_token() を呼び出して、実行時間の長い操作 (LRO) 状態を不透明なトークンに保存します。 値を continuation_token キーワード (keyword) 引数として渡して、保存された状態から LRO を再起動します。

display_name
str

要求された分析に設定するオプションの表示名。

戻り値

TextAnalysisLROPoller のインスタンス。 このオブジェクトで result() を呼び出して、 と DocumentErrorClassifyDocumentResult異種ページング可能な を返します。

の戻り値の型 :

例外

ドキュメントのバッチに対して複数ラベル分類を実行します。


   import os
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import TextAnalyticsClient

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]
   project_name = os.environ["MULTI_LABEL_CLASSIFY_PROJECT_NAME"]
   deployment_name = os.environ["MULTI_LABEL_CLASSIFY_DEPLOYMENT_NAME"]
   path_to_sample_document = os.path.abspath(
       os.path.join(
           os.path.abspath(__file__),
           "..",
           "./text_samples/custom_classify_sample.txt",
       )
   )

   text_analytics_client = TextAnalyticsClient(
       endpoint=endpoint,
       credential=AzureKeyCredential(key),
   )

   with open(path_to_sample_document) as fd:
       document = [fd.read()]

   poller = text_analytics_client.begin_multi_label_classify(
       document,
       project_name=project_name,
       deployment_name=deployment_name
   )

   document_results = poller.result()
   for doc, classification_result in zip(document, document_results):
       if classification_result.kind == "CustomDocumentClassification":
           classifications = classification_result.classifications
           print(f"\nThe movie plot '{doc}' was classified as the following genres:\n")
           for classification in classifications:
               print("'{}' with confidence score {}.".format(
                   classification.category, classification.confidence_score
               ))
       elif classification_result.is_error is True:
           print("Movie plot '{}' has an error with code '{}' and message '{}'".format(
               doc, classification_result.error.code, classification_result.error.message
           ))

begin_recognize_custom_entities

実行時間の長いカスタムの名前付きエンティティ認識操作を開始します。

カスタム機能のリージョンサポートと、カスタム エンティティを認識するようにモデルをトレーニングする方法については、以下を参照してください。 https://aka.ms/azsdk/textanalytics/customentityrecognition

バージョン 2022-05-01 の新機能: begin_recognize_custom_entities クライアント メソッド。

begin_recognize_custom_entities(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], project_name: str, deployment_name: str, *, continuation_token: str | None = None, disable_service_logs: bool | None = None, display_name: str | None = None, language: str | None = None, polling_interval: int | None = None, show_stats: bool | None = None, string_index_type: str | None = None, **kwargs: Any) -> TextAnalysisLROPoller[ItemPaged[RecognizeCustomEntitiesResult | DocumentError]]

パラメーター

documents
list[str] または list[TextDocumentInput] または list[dict[str, str]]
必須

このバッチの一部として処理するドキュメントのセット。 項目ごとに ID と言語を指定する場合は、入力として、{"id": "1","language": "en", "text": "hello world"} などの、list[TextDocumentInput] または dict 表現TextDocumentInputのリストとして使用する必要があります。

project_name
str
必須

必須。 このフィールドは、モデルのプロジェクト名を示します。

deployment_name
str
必須

このフィールドは、モデルのデプロイ名を示します。

language
str

バッチ全体の 2 文字の ISO 639-1 言語表現。 たとえば、英語には "en" を使用します。スペイン語などの "es"設定されていない場合は、既定で英語に "en" を使用します。 ドキュメントごとの言語は、バッチ言語全体よりも優先されます。 言語 API でサポートされている言語については、「」を参照してください https://aka.ms/talangs

show_stats
bool

true に設定すると、応答にはドキュメント レベルの統計情報が含まれます。

disable_service_logs
bool

true に設定した場合、トラブルシューティングのためにサービス側でテキスト入力がログに記録されるのをオプトアウトします。 既定では、言語サービスは、サービスの自然言語処理機能を提供する際の問題のトラブルシューティングのみを可能にするために、入力テキストを 48 時間ログに記録します。 このパラメーターを true に設定すると、入力ログが無効になり、発生した問題を修復する機能が制限される可能性があります。 詳細については、Cognitive Services のコンプライアンスとプライバシーに関する注意事項 https://aka.ms/cs-compliance に関するページ、および Microsoft 責任ある AI の原則については、 を https://www.microsoft.com/ai/responsible-ai参照してください。

string_index_type
str

文字列オフセットを解釈するために使用するメソッドを指定します。 UnicodeCodePoint (Python エンコード) が既定値です。 Python の既定値をオーバーライドするには、 Utf16CodeUnit または TextElement_v8を渡すこともできます。 詳細については、次を参照してください。 https://aka.ms/text-analytics-offsets

polling_interval
int

Retry-After ヘッダーがない場合の LRO 操作の 2 つのポーリング間の待機時間。 既定値は 5 秒です。

continuation_token
str

poller オブジェクト で continuation_token() を呼び出して、実行時間の長い操作 (LRO) 状態を不透明なトークンに保存します。 値を continuation_token キーワード (keyword) 引数として渡して、保存された状態から LRO を再起動します。

display_name
str

要求された分析に設定するオプションの表示名。

戻り値

TextAnalysisLROPoller のインスタンス。 このオブジェクトで result() を呼び出して、 と DocumentErrorRecognizeCustomEntitiesResult異種ページング可能な を返します。

の戻り値の型 :

例外

ドキュメントのバッチ内のカスタム エンティティを認識します。


   import os
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import TextAnalyticsClient

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]
   project_name = os.environ["CUSTOM_ENTITIES_PROJECT_NAME"]
   deployment_name = os.environ["CUSTOM_ENTITIES_DEPLOYMENT_NAME"]
   path_to_sample_document = os.path.abspath(
       os.path.join(
           os.path.abspath(__file__),
           "..",
           "./text_samples/custom_entities_sample.txt",
       )
   )

   text_analytics_client = TextAnalyticsClient(
       endpoint=endpoint,
       credential=AzureKeyCredential(key),
   )

   with open(path_to_sample_document) as fd:
       document = [fd.read()]

   poller = text_analytics_client.begin_recognize_custom_entities(
       document,
       project_name=project_name,
       deployment_name=deployment_name
   )

   document_results = poller.result()
   for custom_entities_result in document_results:
       if custom_entities_result.kind == "CustomEntityRecognition":
           for entity in custom_entities_result.entities:
               print(
                   "Entity '{}' has category '{}' with confidence score of '{}'".format(
                       entity.text, entity.category, entity.confidence_score
                   )
               )
       elif custom_entities_result.is_error is True:
           print("...Is an error with code '{}' and message '{}'".format(
               custom_entities_result.error.code, custom_entities_result.error.message
               )
           )

begin_single_label_classify

実行時間の長いカスタム 単一ラベル分類操作を開始します。

カスタム機能の地域的なサポートと、ドキュメントを分類するためのモデルのトレーニング方法については、次を参照してください。 https://aka.ms/azsdk/textanalytics/customfunctionalities

バージョン 2022-05-01 の新機能: begin_single_label_classify クライアント メソッド。

begin_single_label_classify(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], project_name: str, deployment_name: str, *, continuation_token: str | None = None, disable_service_logs: bool | None = None, display_name: str | None = None, language: str | None = None, polling_interval: int | None = None, show_stats: bool | None = None, **kwargs: Any) -> TextAnalysisLROPoller[ItemPaged[ClassifyDocumentResult | DocumentError]]

パラメーター

documents
list[str] または list[TextDocumentInput] または list[dict[str, str]]
必須

このバッチの一部として処理するドキュメントのセット。 項目ごとに ID と言語を指定する場合は、入力として、{"id": "1","language": "en", "text": "hello world"} などの、list[TextDocumentInput] または dict 表現TextDocumentInputのリストとして使用する必要があります。

project_name
str
必須

必須。 このフィールドは、モデルのプロジェクト名を示します。

deployment_name
str
必須

このフィールドは、モデルのデプロイ名を示します。

language
str

バッチ全体の 2 文字の ISO 639-1 言語表現。 たとえば、英語には "en" を使用します。スペイン語などの "es"設定されていない場合は、既定で英語に "en" を使用します。 ドキュメントごとの言語は、バッチ言語全体よりも優先されます。 言語 API でサポートされている言語については、「」を参照してください https://aka.ms/talangs

show_stats
bool

true に設定すると、応答にはドキュメント レベルの統計情報が含まれます。

disable_service_logs
bool

true に設定した場合、トラブルシューティングのためにサービス側でテキスト入力がログに記録されるのをオプトアウトします。 既定では、言語サービスは、サービスの自然言語処理機能を提供する際の問題のトラブルシューティングのみを可能にするために、入力テキストを 48 時間ログに記録します。 このパラメーターを true に設定すると、入力ログが無効になり、発生した問題を修復する機能が制限される可能性があります。 詳細については、Cognitive Services のコンプライアンスとプライバシーに関する注意事項 https://aka.ms/cs-compliance に関するページ、および Microsoft 責任ある AI の原則については、 を https://www.microsoft.com/ai/responsible-ai参照してください。

polling_interval
int

Retry-After ヘッダーがない場合の LRO 操作の 2 つのポーリング間の待機時間。 既定値は 5 秒です。

continuation_token
str

poller オブジェクト で continuation_token() を呼び出して、実行時間の長い操作 (LRO) 状態を不透明なトークンに保存します。 値を continuation_token キーワード (keyword) 引数として渡して、保存された状態から LRO を再起動します。

display_name
str

要求された分析に設定するオプションの表示名。

戻り値

TextAnalysisLROPoller のインスタンス。 このオブジェクトで result() を呼び出して、 と DocumentErrorClassifyDocumentResult異種ページング可能な を返します。

の戻り値の型 :

例外

ドキュメントのバッチに対して 1 つのラベル分類を実行します。


   import os
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import TextAnalyticsClient

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]
   project_name = os.environ["SINGLE_LABEL_CLASSIFY_PROJECT_NAME"]
   deployment_name = os.environ["SINGLE_LABEL_CLASSIFY_DEPLOYMENT_NAME"]
   path_to_sample_document = os.path.abspath(
       os.path.join(
           os.path.abspath(__file__),
           "..",
           "./text_samples/custom_classify_sample.txt",
       )
   )

   text_analytics_client = TextAnalyticsClient(
       endpoint=endpoint,
       credential=AzureKeyCredential(key),
   )

   with open(path_to_sample_document) as fd:
       document = [fd.read()]

   poller = text_analytics_client.begin_single_label_classify(
       document,
       project_name=project_name,
       deployment_name=deployment_name
   )

   document_results = poller.result()
   for doc, classification_result in zip(document, document_results):
       if classification_result.kind == "CustomDocumentClassification":
           classification = classification_result.classifications[0]
           print("The document text '{}' was classified as '{}' with confidence score {}.".format(
               doc, classification.category, classification.confidence_score)
           )
       elif classification_result.is_error is True:
           print("Document text '{}' has an error with code '{}' and message '{}'".format(
               doc, classification_result.error.code, classification_result.error.message
           ))

close

クライアントによって開かれたソケットを閉じます。 クライアントをコンテキスト マネージャーとして使用する場合、このメソッドの呼び出しは不要です。

close() -> None

例外

detect_language

ドキュメントのバッチの言語を検出します。

検出された言語と、0 から 1 までの数値スコアを返します。 1 に近いスコアは、識別された言語が true であることを 100% 確実性で示します。 有効な言語の一覧については、「」を参照してください https://aka.ms/talangs

サービス データの制限に関するページを参照してください https://aka.ms/azsdk/textanalytics/data-limits

バージョン v3.1 の新機能: disable_service_logs キーワード (keyword)引数。

detect_language(documents: List[str] | List[DetectLanguageInput] | List[Dict[str, str]], *, country_hint: str | None = None, disable_service_logs: bool | None = None, model_version: str | None = None, show_stats: bool | None = None, **kwargs: Any) -> List[DetectLanguageResult | DocumentError]

パラメーター

documents
list[str] または list[DetectLanguageInput] または list[dict[str, str]]
必須

このバッチの一部として処理するドキュメントのセット。 ID とcountry_hintを項目ごとに指定する場合は、入力として list[DetectLanguageInput] またはの dict 表現 DetectLanguageInputのリストとして使用する必要があります ( 例: {"id": "1", "country_hint": "us", "text": "hello world"})。

country_hint
str

バッチ全体の原産国ヒント。 ISO 3166-1 alpha-2 で指定された 2 文字の国コードを受け入れます。 ドキュメントごとの国単位のヒントは、バッチ ヒント全体よりも優先されます。 既定値は "US" です。 国ヒントを使用しない場合は、文字列 "none" を渡します。

model_version
str

分析に使用するモデル バージョン (例: "latest")。 モデル バージョンが指定されていない場合、API は既定で最新のプレビュー以外のバージョンになります。 詳細については、こちらを参照してください。 https://aka.ms/text-analytics-model-versioning

show_stats
bool

true に設定すると、応答にはドキュメント レベルの応答の統計フィールドにドキュメント レベルの 統計 が含まれます。

disable_service_logs
bool

true に設定した場合、トラブルシューティングのためにサービス側でテキスト入力がログに記録されるのをオプトアウトします。 既定では、言語サービスは、サービスの自然言語処理機能を提供する際の問題のトラブルシューティングのみを可能にするために、入力テキストを 48 時間ログに記録します。 このパラメーターを true に設定すると、入力ログが無効になり、発生した問題を修復する機能が制限される可能性があります。 詳細については、Cognitive Services のコンプライアンスとプライバシーに関する注意事項 https://aka.ms/cs-compliance に関するページ、および Microsoft 責任ある AI の原則については、 を https://www.microsoft.com/ai/responsible-ai参照してください。

戻り値

元のドキュメントが DetectLanguageResult 渡された順序での と DocumentError の組み合わせリスト。

の戻り値の型 :

例外

ドキュメントのバッチでの言語の検出。


   import os
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import TextAnalyticsClient

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
   documents = [
       """
       The concierge Paulette was extremely helpful. Sadly when we arrived the elevator was broken, but with Paulette's help we barely noticed this inconvenience.
       She arranged for our baggage to be brought up to our room with no extra charge and gave us a free meal to refurbish all of the calories we lost from
       walking up the stairs :). Can't say enough good things about my experience!
       """,
       """
       最近由于工作压力太大,我们决定去富酒店度假。那儿的温泉实在太舒服了,我跟我丈夫都完全恢复了工作前的青春精神!加油!
       """
   ]

   result = text_analytics_client.detect_language(documents)
   reviewed_docs = [doc for doc in result if not doc.is_error]

   print("Let's see what language each review is in!")

   for idx, doc in enumerate(reviewed_docs):
       print("Review #{} is in '{}', which has ISO639-1 name '{}'\n".format(
           idx, doc.primary_language.name, doc.primary_language.iso6391_name
       ))

extract_key_phrases

ドキュメントのバッチからキー フレーズを抽出します。

入力テキスト内のキー フレーズを示す文字列の一覧を返します。 たとえば、"食べ物は美味しく、素晴らしいスタッフがいました" という入力テキストの場合、API は"food" と "wonderful staff" というメインの話し合いポイントを返します。

サービス データの制限に関するページを参照してください https://aka.ms/azsdk/textanalytics/data-limits

バージョン v3.1 の新機能: disable_service_logs キーワード (keyword)引数。

extract_key_phrases(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], *, disable_service_logs: bool | None = None, language: str | None = None, model_version: str | None = None, show_stats: bool | None = None, **kwargs: Any) -> List[ExtractKeyPhrasesResult | DocumentError]

パラメーター

documents
list[str] または list[TextDocumentInput] または list[dict[str, str]]
必須

このバッチの一部として処理するドキュメントのセット。 項目ごとに ID と言語を指定する場合は、入力として、{"id": "1","language": "en", "text": "hello world"} などの、list[TextDocumentInput] または dict 表現TextDocumentInputのリストとして使用する必要があります。

language
str

バッチ全体の 2 文字の ISO 639-1 言語表現。 たとえば、英語には "en" を使用します。スペイン語などの "es"設定されていない場合は、既定で英語に "en" を使用します。 ドキュメントごとの言語は、バッチ言語全体よりも優先されます。 言語 API でサポートされている言語については、「」を参照してください https://aka.ms/talangs

model_version
str

分析に使用するモデル バージョン (例: "latest")。 モデル バージョンが指定されていない場合、API は既定で最新のプレビュー以外のバージョンになります。 詳細については、こちらを参照してください。 https://aka.ms/text-analytics-model-versioning

show_stats
bool

true に設定すると、応答にはドキュメント レベルの応答の統計フィールドにドキュメント レベルの 統計 が含まれます。

disable_service_logs
bool

true に設定した場合、トラブルシューティングのためにサービス側でテキスト入力がログに記録されるのをオプトアウトします。 既定では、言語サービスは、サービスの自然言語処理機能を提供する際の問題のトラブルシューティングのみを可能にするために、入力テキストを 48 時間ログに記録します。 このパラメーターを true に設定すると、入力ログが無効になり、発生した問題を修復する機能が制限される可能性があります。 詳細については、Cognitive Services のコンプライアンスとプライバシーに関する注意事項 https://aka.ms/cs-compliance に関するページ、および Microsoft 責任ある AI の原則については、 を https://www.microsoft.com/ai/responsible-ai参照してください。

戻り値

元のドキュメントが ExtractKeyPhrasesResult 渡された順序での と DocumentError の組み合わせリスト。

の戻り値の型 :

例外

ドキュメントのバッチでキー フレーズを抽出します。


   import os
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import TextAnalyticsClient

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
   articles = [
       """
       Washington, D.C. Autumn in DC is a uniquely beautiful season. The leaves fall from the trees
       in a city chock-full of forests, leaving yellow leaves on the ground and a clearer view of the
       blue sky above...
       """,
       """
       Redmond, WA. In the past few days, Microsoft has decided to further postpone the start date of
       its United States workers, due to the pandemic that rages with no end in sight...
       """,
       """
       Redmond, WA. Employees at Microsoft can be excited about the new coffee shop that will open on campus
       once workers no longer have to work remotely...
       """
   ]

   result = text_analytics_client.extract_key_phrases(articles)
   for idx, doc in enumerate(result):
       if not doc.is_error:
           print("Key phrases in article #{}: {}".format(
               idx + 1,
               ", ".join(doc.key_phrases)
           ))

recognize_entities

ドキュメントのバッチのエンティティを認識します。

テキスト内のエンティティをユーザー、場所、組織、日付/時刻、数量、パーセンテージ、通貨などに識別して分類します。 サポートされているエンティティ型の一覧については、次チェック。https://aka.ms/taner

サービス データの制限に関するページを参照してください https://aka.ms/azsdk/textanalytics/data-limits

バージョン v3.1 の新機能: 引数のdisable_service_logsstring_index_typeキーワード (keyword)。

recognize_entities(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], *, disable_service_logs: bool | None = None, language: str | None = None, model_version: str | None = None, show_stats: bool | None = None, string_index_type: str | None = None, **kwargs: Any) -> List[RecognizeEntitiesResult | DocumentError]

パラメーター

documents
list[str] または list[TextDocumentInput] または list[dict[str, str]]
必須

このバッチの一部として処理するドキュメントのセット。 項目ごとに ID と言語を指定する場合は、入力として、{"id": "1","language": "en", "text": "hello world"} などの、list[TextDocumentInput] または dict 表現TextDocumentInputのリストとして使用する必要があります。

language
str

バッチ全体の 2 文字の ISO 639-1 言語表現。 たとえば、英語には "en" を使用します。スペイン語などの "es"設定されていない場合は、既定で英語に "en" を使用します。 ドキュメントごとの言語は、バッチ言語全体よりも優先されます。 言語 API でサポートされている言語については、「」を参照してください https://aka.ms/talangs

model_version
str

分析に使用するモデル バージョン (例: "latest")。 モデル バージョンが指定されていない場合、API は既定で最新のプレビュー以外のバージョンになります。 詳細については、こちらを参照してください。 https://aka.ms/text-analytics-model-versioning

show_stats
bool

true に設定すると、応答にはドキュメント レベルの応答の統計フィールドにドキュメント レベルの 統計 が含まれます。

string_index_type
str

文字列オフセットを解釈するために使用するメソッドを指定します。 UnicodeCodePoint (Python エンコード) が既定値です。 Python の既定値をオーバーライドするには、 Utf16CodeUnit または TextElement_v8を渡すこともできます。 詳細については、次を参照してください。 https://aka.ms/text-analytics-offsets

disable_service_logs
bool

true に設定した場合、トラブルシューティングのためにサービス側でテキスト入力がログに記録されるのをオプトアウトします。 既定では、言語サービスは、サービスの自然言語処理機能を提供する際の問題のトラブルシューティングのみを可能にするために、入力テキストを 48 時間ログに記録します。 このパラメーターを true に設定すると、入力ログが無効になり、発生した問題を修復する機能が制限される可能性があります。 詳細については、Cognitive Services のコンプライアンスとプライバシーに関する注意事項 https://aka.ms/cs-compliance に関するページ、および Microsoft 責任ある AI の原則については、 を https://www.microsoft.com/ai/responsible-ai参照してください。

戻り値

元のドキュメントが RecognizeEntitiesResult 渡された順序での と DocumentError の組み合わせリスト。

の戻り値の型 :

例外

ドキュメントのバッチ内のエンティティを認識します。


   import os
   import typing
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import TextAnalyticsClient

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
   reviews = [
       """I work for Foo Company, and we hired Contoso for our annual founding ceremony. The food
       was amazing and we all can't say enough good words about the quality and the level of service.""",
       """We at the Foo Company re-hired Contoso after all of our past successes with the company.
       Though the food was still great, I feel there has been a quality drop since their last time
       catering for us. Is anyone else running into the same problem?""",
       """Bar Company is over the moon about the service we received from Contoso, the best sliders ever!!!!"""
   ]

   result = text_analytics_client.recognize_entities(reviews)
   result = [review for review in result if not review.is_error]
   organization_to_reviews: typing.Dict[str, typing.List[str]] = {}

   for idx, review in enumerate(result):
       for entity in review.entities:
           print(f"Entity '{entity.text}' has category '{entity.category}'")
           if entity.category == 'Organization':
               organization_to_reviews.setdefault(entity.text, [])
               organization_to_reviews[entity.text].append(reviews[idx])

   for organization, reviews in organization_to_reviews.items():
       print(
           "\n\nOrganization '{}' has left us the following review(s): {}".format(
               organization, "\n\n".join(reviews)
           )
       )

recognize_linked_entities

ドキュメントのバッチについて、既知のサポート情報からリンクされたエンティティを認識します。

テキストで見つかった各エンティティの ID を識別し、あいまいさを解消します (たとえば、Mars という単語の出現が惑星を指しているのか、ローマの戦争の神を指しているのかを判断します)。 認識されたエンティティは、Wikipedia などのよく知られたサポート情報への URL に関連付けられます。

サービス データの制限に関するページを参照してください https://aka.ms/azsdk/textanalytics/data-limits

バージョン v3.1 の新機能: 引数のdisable_service_logsstring_index_typeキーワード (keyword)。

recognize_linked_entities(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], *, disable_service_logs: bool | None = None, language: str | None = None, model_version: str | None = None, show_stats: bool | None = None, string_index_type: str | None = None, **kwargs: Any) -> List[RecognizeLinkedEntitiesResult | DocumentError]

パラメーター

documents
list[str] または list[TextDocumentInput] または list[dict[str, str]]
必須

このバッチの一部として処理するドキュメントのセット。 項目ごとに ID と言語を指定する場合は、入力として、{"id": "1","language": "en", "text": "hello world"} などの、list[TextDocumentInput] または dict 表現TextDocumentInputのリストとして使用する必要があります。

language
str

バッチ全体の 2 文字の ISO 639-1 言語表現。 たとえば、英語には "en" を使用します。スペイン語などの "es"設定されていない場合は、既定で英語に "en" を使用します。 ドキュメントごとの言語は、バッチ言語全体よりも優先されます。 言語 API でサポートされている言語については、「」を参照してください https://aka.ms/talangs

model_version
str

分析に使用するモデル バージョン (例: "latest")。 モデル バージョンが指定されていない場合、API は既定で最新のプレビュー以外のバージョンになります。 詳細については、こちらを参照してください。 https://aka.ms/text-analytics-model-versioning

show_stats
bool

true に設定すると、応答にはドキュメント レベルの応答の統計フィールドにドキュメント レベルの 統計 が含まれます。

string_index_type
str

文字列オフセットを解釈するために使用するメソッドを指定します。 UnicodeCodePoint (Python エンコード) が既定値です。 Python の既定値をオーバーライドするには、 Utf16CodeUnit または TextElement_v8を渡すこともできます。 詳細については、次を参照してください。 https://aka.ms/text-analytics-offsets

disable_service_logs
bool

true に設定した場合、トラブルシューティングのためにサービス側でテキスト入力がログに記録されるのをオプトアウトします。 既定では、言語サービスは、サービスの自然言語処理機能を提供する際の問題のトラブルシューティングのみを可能にするために、入力テキストを 48 時間ログに記録します。 このパラメーターを true に設定すると、入力ログが無効になり、発生した問題を修復する機能が制限される可能性があります。 詳細については、Cognitive Services のコンプライアンスとプライバシーに関する注意事項 https://aka.ms/cs-compliance に関するページ、および Microsoft 責任ある AI の原則については、 を https://www.microsoft.com/ai/responsible-ai参照してください。

戻り値

元のドキュメントが RecognizeLinkedEntitiesResult 渡された順序での と DocumentError の組み合わせリスト。

の戻り値の型 :

例外

ドキュメントのバッチ内のリンクされたエンティティを認識します。


   import os
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import TextAnalyticsClient

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
   documents = [
       """
       Microsoft was founded by Bill Gates with some friends he met at Harvard. One of his friends,
       Steve Ballmer, eventually became CEO after Bill Gates as well. Steve Ballmer eventually stepped
       down as CEO of Microsoft, and was succeeded by Satya Nadella.
       Microsoft originally moved its headquarters to Bellevue, Washington in January 1979, but is now
       headquartered in Redmond.
       """
   ]

   result = text_analytics_client.recognize_linked_entities(documents)
   docs = [doc for doc in result if not doc.is_error]

   print(
       "Let's map each entity to it's Wikipedia article. I also want to see how many times each "
       "entity is mentioned in a document\n\n"
   )
   entity_to_url = {}
   for doc in docs:
       for entity in doc.entities:
           print("Entity '{}' has been mentioned '{}' time(s)".format(
               entity.name, len(entity.matches)
           ))
           if entity.data_source == "Wikipedia":
               entity_to_url[entity.name] = entity.url

recognize_pii_entities

ドキュメントのバッチの個人情報を含むエンティティを認識します。

ドキュメント内の個人情報エンティティ ("SSN"、"銀行口座"など) の一覧を返します。 サポートされているエンティティ型の一覧については、チェック https://aka.ms/azsdk/language/pii

サービス データの制限に関するページを参照してください https://aka.ms/azsdk/textanalytics/data-limits

バージョン v3.1 の新機能: recognize_pii_entities クライアント メソッド。

recognize_pii_entities(documents: List[str] | List[TextDocumentInput] | List[Dict[str, str]], *, categories_filter: List[str | PiiEntityCategory] | None = None, disable_service_logs: bool | None = None, domain_filter: str | PiiEntityDomain | None = None, language: str | None = None, model_version: str | None = None, show_stats: bool | None = None, string_index_type: str | None = None, **kwargs: Any) -> List[RecognizePiiEntitiesResult | DocumentError]

パラメーター

documents
list[str] または list[TextDocumentInput] または list[dict[str, str]]
必須

このバッチの一部として処理するドキュメントのセット。 項目ごとに ID と言語を指定する場合は、入力として、{"id": "1","language": "en", "text": "hello world"} などの、list[TextDocumentInput] または dict 表現TextDocumentInputのリストとして使用する必要があります。

language
str

バッチ全体の 2 文字の ISO 639-1 言語表現。 たとえば、英語には "en" を使用します。スペイン語などの "es"設定されていない場合は、既定で英語に "en" を使用します。 ドキュメントごとの言語は、バッチ言語全体よりも優先されます。 言語 API でサポートされている言語については、「」を参照してください https://aka.ms/talangs

model_version
str

分析に使用するモデル バージョン (例: "latest")。 モデル バージョンが指定されていない場合、API は既定で最新のプレビュー以外のバージョンになります。 詳細については、こちらを参照してください。 https://aka.ms/text-analytics-model-versioning

show_stats
bool

true に設定すると、応答にはドキュメント レベルの応答の統計フィールドにドキュメント レベルの 統計 が含まれます。

domain_filter
str または PiiEntityDomain

応答エンティティを、指定されたドメインにのみ含まれるものにフィルター処理します。 つまり、'phi' に設定すると、Protected Healthcare Information ドメイン内のエンティティのみが返されます。 詳細については、「 https://aka.ms/azsdk/language/pii 」を参照してください。

categories_filter
list[str または PiiEntityCategory]

すべての PII エンティティ カテゴリをフィルター処理する代わりに、フィルター処理する特定の PII エンティティ カテゴリの一覧を渡すことができます。たとえば、ドキュメント内の米国の社会保障番号のみを除外する場合は、この kwarg に [PiiEntityCategory.US_SOCIAL_SECURITY_NUMBER] を 渡すことができます。

string_index_type
str

文字列オフセットを解釈するために使用するメソッドを指定します。 UnicodeCodePoint (Python エンコード) が既定値です。 Python の既定値をオーバーライドするには、 Utf16CodeUnit または TextElement_v8を渡すこともできます。 詳細については、次を参照してください。 https://aka.ms/text-analytics-offsets

disable_service_logs
bool

既定値は true です。つまり、言語サービスはトラブルシューティングのためにサービス側で入力テキストをログに記録しません。 False に設定すると、言語サービスは入力テキストを 48 時間ログに記録します。これは、サービスの自然言語処理機能を提供する際の問題のトラブルシューティングのみを可能にするためです。 詳細については、Cognitive Services のコンプライアンスとプライバシーに関する注意事項 https://aka.ms/cs-compliance に関するページ、および Microsoft 責任ある AI の原則については、 を https://www.microsoft.com/ai/responsible-ai参照してください。

戻り値

元のドキュメントが RecognizePiiEntitiesResult 渡された順序での と DocumentError の組み合わせリスト。

の戻り値の型 :

例外

ドキュメントのバッチで個人を特定できる情報エンティティを認識します。


   import os
   from azure.core.credentials import AzureKeyCredential
   from azure.ai.textanalytics import TextAnalyticsClient

   endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
   key = os.environ["AZURE_LANGUAGE_KEY"]

   text_analytics_client = TextAnalyticsClient(
       endpoint=endpoint, credential=AzureKeyCredential(key)
   )
   documents = [
       """Parker Doe has repaid all of their loans as of 2020-04-25.
       Their SSN is 859-98-0987. To contact them, use their phone number
       555-555-5555. They are originally from Brazil and have Brazilian CPF number 998.214.865-68"""
   ]

   result = text_analytics_client.recognize_pii_entities(documents)
   docs = [doc for doc in result if not doc.is_error]

   print(
       "Let's compare the original document with the documents after redaction. "
       "I also want to comb through all of the entities that got redacted"
   )
   for idx, doc in enumerate(docs):
       print(f"Document text: {documents[idx]}")
       print(f"Redacted document text: {doc.redacted_text}")
       for entity in doc.entities:
           print("...Entity '{}' with category '{}' got redacted".format(
               entity.text, entity.category
           ))