Skip to content

藥物擷取範例 🏥

LangExtract 擅長從臨床文本中擷取結構化醫療資訊,特別適合醫療健康應用場景。

WARNING

免責聲明: 本範例僅用於展示 LangExtract 的基礎功能,不代表成熟或已核准的產品,不用於診斷或建議任何疾病的治療,不應用於醫療建議。

基礎命名實體辨識 (NER)

以下範例展示 LangExtract 如何擷取結構化藥物資訊:

python
import langextract as lx

# 輸入文本
input_text = "病患服用布洛芬 400mg 口服 每4小時一次 連續兩天。"

# 定義擷取 prompt
prompt_description = "依照文本中出現的順序擷取藥物資訊,包括藥物名稱、劑量、給藥途徑、頻率和持續時間。"

# 定義範例資料
examples = [
    lx.data.ExampleData(
        text="病患接受頭孢唑林 250mg 靜脈注射 每日三次 連續一週。",
        extractions=[
            lx.data.Extraction(extraction_class="dosage", extraction_text="250mg"),
            lx.data.Extraction(extraction_class="route", extraction_text="靜脈注射"),
            lx.data.Extraction(extraction_class="medication", extraction_text="頭孢唑林"),
            lx.data.Extraction(extraction_class="frequency", extraction_text="每日三次"),
            lx.data.Extraction(extraction_class="duration", extraction_text="連續一週")
        ]
    )
]

result = lx.extract(
    text_or_documents=input_text,
    prompt_description=prompt_description,
    examples=examples,
    model_id="gemini-2.5-pro",
)

# 顯示擷取結果
print(f"輸入: {input_text}\n")
print("擷取的實體:")
for entity in result.extractions:
    position_info = ""
    if entity.char_interval:
        start, end = entity.char_interval.start_pos, entity.char_interval.end_pos
        position_info = f" (位置: {start}-{end})"
    print(f"• {entity.extraction_class}: {entity.extraction_text}{position_info}")

# 儲存並視覺化結果
lx.io.save_annotated_documents([result], output_name="medical_ner_extraction.jsonl", output_dir=".")

# 產生互動式視覺化
html_content = lx.visualize("medical_ner_extraction.jsonl")
with open("medical_ner_visualization.html", "w") as f:
    if hasattr(html_content, 'data'):
        f.write(html_content.data)
    else:
        f.write(html_content)

print("互動式視覺化已儲存至 medical_ner_visualization.html")

關係擷取 (RE)

對於涉及實體間關係的更複雜擷取,LangExtract 可以擷取藥物及其關聯屬性:

python
import langextract as lx

# 包含多個藥物的文本
input_text = """
病患上個月被開立了利辛普利和二甲雙胍處方。
他每天服用利辛普利 10mg 治療高血壓,但經常漏服
二甲雙胍 500mg,該藥應每日兩次服用以控制糖尿病。
"""

# 定義擷取 prompt
prompt_description = """
擷取藥物及其詳細資訊,使用屬性來分組相關資訊:

1. 依文本中出現的順序擷取實體
2. 每個實體必須有 'medication_group' 屬性將其連結到對應藥物
3. 同一藥物的所有詳細資訊應共享相同的 medication_group 值
"""

examples = [
    lx.data.ExampleData(
        text="病患每天服用阿斯匹靈 100mg 保護心臟,睡前服用辛伐他汀 20mg。",
        extractions=[
            lx.data.Extraction(
                extraction_class="medication",
                extraction_text="阿斯匹靈",
                attributes={"medication_group": "阿斯匹靈"}
            ),
            lx.data.Extraction(
                extraction_class="dosage",
                extraction_text="100mg",
                attributes={"medication_group": "阿斯匹靈"}
            ),
            lx.data.Extraction(
                extraction_class="frequency",
                extraction_text="每天",
                attributes={"medication_group": "阿斯匹靈"}
            ),
            lx.data.Extraction(
                extraction_class="medication",
                extraction_text="辛伐他汀",
                attributes={"medication_group": "辛伐他汀"}
            ),
            lx.data.Extraction(
                extraction_class="dosage",
                extraction_text="20mg",
                attributes={"medication_group": "辛伐他汀"}
            ),
            lx.data.Extraction(
                extraction_class="frequency",
                extraction_text="睡前",
                attributes={"medication_group": "辛伐他汀"}
            )
        ]
    )
]

result = lx.extract(
    text_or_documents=input_text,
    prompt_description=prompt_description,
    examples=examples,
    model_id="gemini-2.5-pro",
)

# 依藥物分組顯示
print("擷取的藥物:")
medication_groups = {}
for extraction in result.extractions:
    if extraction.attributes and "medication_group" in extraction.attributes:
        group_name = extraction.attributes["medication_group"]
        medication_groups.setdefault(group_name, []).append(extraction)

for med_name, extractions in medication_groups.items():
    print(f"\n* {med_name}")
    for extraction in extractions:
        print(f"  • {extraction.extraction_class}: {extraction.extraction_text}")

關鍵特性

  • 命名實體辨識: 擷取帶類型的實體(藥物、劑量、途徑等)
  • 關係擷取: 使用屬性將相關實體分組
  • 位置追蹤: 記錄擷取實體在來源文本中的精確位置
  • 結構化輸出: 以適合醫療應用的格式組織資訊
  • 互動式視覺化: 產生 HTML 視覺化介面探索複雜的醫療擷取結果

非官方指南。與 Google 無關。