你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 Python 的 Azure 认知服务 Health Insights 癌症分析客户端库 - 版本 1.0.0b1

Health Insights 是使用 Azure 认知服务框架构建的 Azure 应用 AI 服务,它利用多个认知服务、医疗保健 API 服务和其他 Azure 资源。

癌症分析模型接收肿瘤学患者的临床记录,并输出癌症分期,如临床阶段TNM类别和病理阶段TNM类别以及肿瘤部位、组织学。

源代码 | 包 (PyPI) | API 参考文档 | 产品文档 | 样品

入门

先决条件

  • 使用此包需要 Python 3.7 或更高版本。
  • 需要 Azure 订阅 才能使用此包。
  • 现有的认知服务运行状况见解实例。

安装包

pip install azure-healthinsights-cancerprofiling

此表显示了 SDK 版本与服务支持的 API 版本之间的关系:

SDK 版本 服务支持的 API 版本
1.0.0b1 2023-03-01-preview

验证客户端

获取终结点

可以使用 Azure 门户或 AzureCLI 查找 Health Insights 服务资源的终结点

# 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 密钥

可以从 Azure 门户中的 Health Insights 服务资源获取 API 密钥 。 或者,可以使用下面的 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操作

长时间运行的操作包括发送到服务以启动操作的初始请求,然后按间隔轮询服务以确定操作是否已完成或失败,如果操作成功,则获取结果。

支持医疗保健分析、自定义文本分析或多个分析的方法将建模为长时间运行的操作。 客户端公开一个 begin_<method-name> 返回轮询器对象的方法。 调用方应通过调用 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 中定义的异常。

Logging

此库使用标准 日志记录 库进行日志记录。

有关 HTTP 会话的基本信息 (URL、标头等) 记录在 INFO 级别。

可以使用 关键字 (keyword) 参数在客户端或每个操作logging_enable上启用详细DEBUG级别日志记录,包括请求/响应正文和未执行的标头。

请参阅此处的示例的完整 SDK 日志记录文档。

可选配置

可选的关键字 (keyword) 参数可以在客户端和每个操作级别传入。 azure-core 参考文档 介绍了重试、日志记录、传输协议等的可用配置。

后续步骤

其他文档

有关 Azure Health Insights 癌症分析的更多文档,请参阅有关 docs.microsoft.com 的 癌症分析文档

贡献

本项目欢迎贡献和建议。 大多数贡献要求你同意贡献者许可协议 (CLA),并声明你有权(并且确实有权)授予我们使用你的贡献的权利。 有关详细信息,请访问 https://cla.microsoft.com

提交拉取请求时,CLA 机器人将自动确定你是否需要提供 CLA,并相应地修饰 PR(例如标签、注释)。 直接按机器人提供的说明操作。 只需使用 CLA 对所有存储库执行一次这样的操作。

本项目采用 Microsoft 开源行为准则。 有关详细信息,请参阅“行为准则常见问题解答”,如有其他任何问题或意见,请联系 opencode@microsoft.com。