Python 用 Azure Cognitive Services Health Insights がんプロファイリング クライアント ライブラリ - バージョン 1.0.0b1

Health Insights は、Azure Cognitive Services Framework を使用して構築された Azure Applied AI Service であり、複数の Cognitive Services、Healthcare API サービス、およびその他の Azure リソースを活用します。

がんプロファイリングモデルは、腫瘍患者の臨床記録を受け取り、臨床ステージTNMカテゴリーや病理ステージTNMカテゴリー、腫瘍部位、組織学などの癌ステージングを出力します。

ソースコード | パッケージ (PyPI) | API リファレンス ドキュメント | 製品ドキュメント | サンプル

作業の開始

前提条件

  • このパッケージを使用するには、Python 3.7 以降が必要です。
  • このパッケージを使用するには 、Azure サブスクリプション が必要です。
  • 既存の Cognitive Services Health Insights インスタンス。

パッケージをインストールする

pip install azure-healthinsights-cancerprofiling

SDK のバージョンとサービスのサポートされる API バージョンの関係を次の表に示します。

SDK バージョン サポートされている API バージョンのサービス
1.0.0b1 2023-03-01-preview

クライアントを認証する

エンドポイントを取得する

Health Insights サービス リソースのエンドポイントは、Azure Portal または Azure CLI を使用して見つけることができます

# Get the endpoint for the Health Insights service resource
az cognitiveservices account show --name "resource-name" --resource-group "resource-group-name" --query "properties.endpoint"

API キーを取得する

API キーは、Azure Portal の Health Insights サービス リソースから取得できます。 または、以下の Azure CLI スニペットを使用して、リソースの API キーを取得することもできます。

az cognitiveservices account keys list --resource-group <your-resource-group-name> --name <your-resource-name>

API キー資格情報を使用して CancerProfilingClient を作成する

API キーの値を取得したら、それを文字列として AzureKeyCredential のインスタンスに渡すことができます。 資格情報パラメーターとして キーを使用して、クライアントを認証します。

import os
from azure.core.credentials import AzureKeyCredential
from azure.healthinsights.cancerprofiling.aio import CancerProfilingClient

KEY = os.environ["HEALTHINSIGHTS_KEY"]
ENDPOINT = os.environ["HEALTHINSIGHTS_ENDPOINT"]

cancer_profiling_client = CancerProfilingClient(endpoint=ENDPOINT, credential=AzureKeyCredential(KEY))

Long-Running操作

実行時間の長い操作は、操作を開始するためにサービスに送信された最初の要求で構成される操作です。その後、間隔を指定してサービスをポーリングし、操作が完了したか失敗したか、成功したかどうかを判断して結果を取得します。

医療分析、カスタム テキスト分析、または複数の分析をサポートするメソッドは、実行時間の長い操作としてモデル化されます。 クライアントは、poller オブジェクトを begin_<method-name> 返すメソッドを公開します。 呼び出し元は、 メソッドから返された poller オブジェクトに対して を呼び出 result() して、操作が完了するまで待機する begin_<method-name> 必要があります。 実行時間の長い操作の使用例を示すために、サンプル コード スニペット 用意されています

主要な概念

がんプロファイリング モデルを使用すると、非構造化臨床ドキュメントから、腫瘍部位、組織学、臨床ステージ TNM カテゴリ、病理ステージ TNM カテゴリなどのがん属性を推論できます。

次のセクションでは、最も一般的な Health Insights - がんプロファイリング サービス タスクの一部をカバーするいくつかのコード スニペットを示します。

がんプロファイリング

腫瘍部位、組織学、臨床ステージTNMカテゴリ、病理ステージTNMカテゴリなどの主要な癌属性を患者の非構造化臨床ドキュメントから推論する。

import asyncio
import os
import datetime
from azure.core.credentials import AzureKeyCredential
from azure.healthinsights.cancerprofiling.aio import CancerProfilingClient
from azure.healthinsights.cancerprofiling import models

KEY = os.environ["HEALTHINSIGHTS_KEY"]
ENDPOINT = os.environ["HEALTHINSIGHTS_ENDPOINT"]

# Create an Onco Phenotype client
# <client>
cancer_profiling_client = CancerProfilingClient(endpoint=ENDPOINT,
                                                credential=AzureKeyCredential(KEY))
# </client>

# Construct patient
# <PatientConstructor>
patient_info = models.PatientInfo(sex=models.PatientInfoSex.FEMALE, birth_date=datetime.date(1979, 10, 8))
patient1 = models.PatientRecord(id="patient_id", info=patient_info)
# </PatientConstructor>

# Add document list
# <DocumentList>
doc_content1 = """
            15.8.2021
            Jane Doe 091175-8967
            42 year old female, married with 3 children, works as a nurse
            Healthy, no medications taken on a regular basis.
            PMHx is significant for migraines with aura, uses Mirena for contraception.
            Smoking history of 10 pack years (has stopped and relapsed several times).
            She is in c/o 2 weeks of productive cough and shortness of breath.
            She has a fever of 37.8 and general weakness.
            Denies night sweats and rash. She denies symptoms of rhinosinusitis, asthma, and heartburn.
            On PE:
            GENERAL: mild pallor, no cyanosis. Regular breathing rate.
            LUNGS: decreased breath sounds on the base of the right lung. Vesicular breathing. 
                No crackles, rales, and wheezes. Resonant percussion.
            PLAN:
            Will be referred for a chest x-ray.
            ======================================
            CXR showed mild nonspecific opacities in right lung base.
            PLAN:
            Findings are suggestive of a working diagnosis of pneumonia. The patient is referred to a
            follow-up CXR in 2 weeks."""

patient_document1 = models.PatientDocument(type=models.DocumentType.NOTE,
                                           id="doc1",
                                           content=models.DocumentContent(
                                               source_type=models.DocumentContentSourceType.INLINE,
                                               value=doc_content1),
                                           clinical_type=models.ClinicalDocumentType.IMAGING,
                                           language="en",
                                           created_date_time=datetime.datetime(2021, 8, 15))

doc_content2 = """
            Oncology Clinic
            20.10.2021
            Jane Doe 091175-8967
            42-year-old healthy female who works as a nurse in the ER of this hospital.
            First menstruation at 11 years old. First delivery- 27 years old. She has 3 children.
            Didn't breastfeed.
            Contraception- Mirena.
            Smoking- 10 pack years.
            Mother- Belarusian. Father- Georgian. 
            About 3 months prior to admission, she stated she had SOB and was febrile.
            She did a CXR as an outpatient which showed a finding in the base of the right lung-
            possibly an infiltrate.
            She was treated with antibiotics with partial response.
            6 weeks later a repeat CXR was performed- a few solid dense findings in the right lung.
            Therefore, she was referred for a PET-CT which demonstrated increased uptake in the right
            breast, lymph nodes on the right a few areas in the lungs and liver.
            On biopsy from the lesion in the right breast- triple negative adenocarcinoma. Genetic
            testing has not been done thus far.
            Genetic counseling- the patient denies a family history of breast, ovary, uterus,
            and prostate cancer. Her mother has chronic lymphocytic leukemia (CLL).
            She is planned to undergo genetic tests because the aggressive course of the disease,
            and her young age.
            Impression:
            Stage 4 triple negative breast adenocarcinoma.
            Could benefit from biological therapy.
            Different treatment options were explained- the patient wants to get a second opinion."""

patient_document2 = models.PatientDocument(type=models.DocumentType.NOTE,
                                           id="doc2",
                                           content=models.DocumentContent(
                                               source_type=models.DocumentContentSourceType.INLINE,
                                               value=doc_content2),
                                           clinical_type=models.ClinicalDocumentType.PATHOLOGY,
                                           language="en",
                                           created_date_time=datetime.datetime(2021, 10, 20))

doc_content3 = """
            PATHOLOGY REPORT
                                    Clinical Information
            Ultrasound-guided biopsy; A. 18 mm mass; most likely diagnosis based on imaging:  IDC
                                        Diagnosis
            A.  BREAST, LEFT AT 2:00 4 CM FN; ULTRASOUND-GUIDED NEEDLE CORE BIOPSIES:
            - Invasive carcinoma of no special type (invasive ductal carcinoma), grade 1
            Nottingham histologic grade:  1/3 (tubules 2; nuclear grade 2; mitotic rate 1;
            total score; 5/9)
            Fragments involved by invasive carcinoma:  2
            Largest measurement of invasive carcinoma on a single fragment:  7 mm
            Ductal carcinoma in situ (DCIS):  Present
            Architectural pattern:  Cribriform
            Nuclear grade:  2-
                            -intermediate
            Necrosis:  Not identified
            Fragments involved by DCIS:  1
            Largest measurement of DCIS on a single fragment:  Span 2 mm
            Microcalcifications:  Present in benign breast tissue and invasive carcinoma
            Blocks with invasive carcinoma:  A1
            Special studies: Pending"""

patient_document3 = models.PatientDocument(type=models.DocumentType.NOTE,
                                           id="doc3",
                                           content=models.DocumentContent(
                                               source_type=models.DocumentContentSourceType.INLINE,
                                               value=doc_content3),
                                           clinical_type=models.ClinicalDocumentType.PATHOLOGY,
                                           language="en",
                                           created_date_time=datetime.datetime(2022, 1, 1))

patient_doc_list = [patient_document1, patient_document2, patient_document3]
patient1.data = patient_doc_list
# <\DocumentList>

# Set configuration to include evidence for the cancer staging inferences
configuration = models.OncoPhenotypeModelConfiguration(include_evidence=True)

# Construct the request with the patient and configuration
cancer_profiling_data = models.OncoPhenotypeData(patients=[patient1], configuration=configuration)

poller = await cancer_profiling_client.begin_infer_cancer_profile(cancer_profiling_data)
cancer_profiling_result = await poller.result()
if cancer_profiling_result.status == models.JobStatus.SUCCEEDED:
    results = cancer_profiling_result.results
    for patient_result in results.patients:
        print(f"\n==== Inferences of Patient {patient_result.id} ====")
        for inference in patient_result.inferences:
            print(
                f"\n=== Clinical Type: {str(inference.type)} Value: {inference.value}\
                    ConfidenceScore: {inference.confidence_score} ===")
            for evidence in inference.evidence:
                data_evidence = evidence.patient_data_evidence
                print(
                    f"Evidence {data_evidence.id} {data_evidence.offset} {data_evidence.length}\
                        {data_evidence.text}")
else:
    errors = cancer_profiling_result.errors
    if errors is not None:
        for error in errors:
            print(f"{error.code} : {error.message}")

トラブルシューティング

全般

Health Insights がんプロファイル クライアント ライブラリでは、 Azure Core で定義されている例外が発生します。

ログの記録

このライブラリでは、標準の ログ記録 ライブラリを使用してログを記録します。

HTTP セッション (URL、ヘッダーなど) に関する基本情報は、レベルで INFO ログに記録されます。

要求/応答本文や未作成のヘッダーなど、詳細なDEBUGレベルのログ記録は、クライアントで有効にすることも、キーワード (keyword)引数を使用してlogging_enable操作ごとに有効にすることもできます。

SDK のログ記録に関する完全なドキュメントと例 については、こちらを参照してください

オプションの構成

省略可能なキーワード (keyword)引数は、クライアントレベルと操作ごとのレベルで渡すことができます。 azure-core リファレンス ドキュメント では、再試行、ログ記録、トランスポート プロトコルなどの使用可能な構成について説明しています。

次の手順

その他のドキュメント

Azure Health Insights のがんプロファイリングに関するより広範なドキュメントについては、docs.microsoft.com に関 するがんプロファイリングに関するドキュメント を参照してください。

共同作成

このプロジェクトでは、共同作成と提案を歓迎しています。 ほとんどの共同作成では、共同作成者使用許諾契約書 (CLA) にご同意いただき、ご自身の共同作成内容を使用する権利を Microsoft に供与する権利をお持ちであり、かつ実際に供与することを宣言していただく必要があります。 詳細については、 https://cla.microsoft.com を参照してください。

pull request を送信すると、CLA を提供して PR (ラベル、コメントなど) を適宜装飾する必要があるかどうかを CLA ボットが自動的に決定します。 ボットによって提供される手順にそのまま従ってください。 この操作は、Microsoft の CLA を使用するすべてのリポジトリについて、1 回だけ行う必要があります。

このプロジェクトでは、Microsoft オープン ソースの倫理規定を採用しています。 詳細については、「倫理規定の FAQ」をご覧ください。追加の質問やコメントがある場合は opencode@microsoft.com にお問い合わせください。