# -*- coding: utf-8 -*- """ models/thyroid.py This script sets up a series of data extraction models using the dspy library for pathology reports, specifically focusing on thyroid cancer. It includes model loading, signature definitions for various cancer types, and functions to convert model predictions into structured JSON formats. author: Hong-Kai (Walther) Chen, Po-Yen Tzeng and Kai-Po Chang @ Med NLP Lab, China Medical University date: 2025-10-13" """ __version__ = "1.0.0" __date__ = "2025-10-13" __author__ = ["Hong-Kai (Walther) Chen", "Po-Yen Tzeng", "Kai-Po Chang"] __copyright__ = "Copyright 2025, Med NLP Lab, China Medical University" __license__ = "MIT" __ajcc_version__ = 8 __cap_version__ = "4.4.0.0" import dspy from typing import Literal from pydantic import BaseModel, Field class ThyroidMargin(BaseModel): margin_category: ( Literal["outmost", "anterior_outmost", "posterior_outmost", "isthmus", "others"] | None ) = Field( None, description="acceptable value for surgical margins in thyroid cancer. If not included in these standard margins, should be classified as others.", ) margin_involved: bool distance: int | None = Field( None, description="If margin is involved, return 0. If margin is uninvolved/free, try your best to find the distance at both microscopic and macroscopic(gross) description, and specify the distance from tumor to margin in mm, rounded to integer. If the margin is uninvolved/free and, after your best effort, the distance is still not specified, return null", ) description: str | None class ThyroidLN(BaseModel): lymph_node_side: Literal["right", "left", "midline"] | None = Field( None, description="acceptable value for lymph node side in cervical cancer. If not included in these standard sides, should be classified as None.", ) lymph_node_category: ( Literal[ "level_vi_central", "level_i", "level_ii", "level_iii", "level_iv", "level_v", "level_vii", "others", ] | None ) = Field( None, description="acceptable value for lymph node categories in thyroid cancer. If not included in these standard lymph node 'station' number, should be classified as others.", ) involved: int examined: int station_name: str | None = Field( None, description="specify the name of the lymph node station here." ) class ThyroidCancerNonnested(dspy.Signature): """you need to extract the value of the specified items below from the given pancreas cancer excision report. DO NOT JUST RETURN NULL. IF SOME ITEM IS NOT PRESENT, RETURN NULL FOR THAT ITEM, BUT TRY YOUR BEST TO FILL IN THE OTHERS.""" report: list = dspy.InputField( desc="this is a pathological report for thyroid cancer excision, separated into paragraphs." ) report_jsonized: dict = dspy.InputField( desc="this is a roughly structured json summary of the pathological report, which is generated by another model." ) predisposing_condition: Literal["radiation", "family_history"] | None = ( dspy.OutputField( desc='identify any predisposing condition mentioned in the report, such as "Hashimoto thyroiditis" or "radiation exposure". If none mentioned, return None' ) ) procedure: ( Literal[ "partial_excision", "right_lobectomy", "left_lobectomy", "total_thyroidectomy", "others", ] | None ) = dspy.OutputField( desc="identify which surgery procedure was used. e.g. partial thyroidectomy" ) tumor_focality: Literal["unifocal", "multifocal", "not_specified"] | None = ( dspy.OutputField( desc="identify whether the tumor is unifocal or multifocal. If not specified, return not_specified" ) ) tumor_site: ( Literal["right_lobe", "left_lobe", "isthmus", "both_lobe", "others"] | None ) = dspy.OutputField( desc="identify the primary site of cancer. e.g. right lobe of thyroid" ) histology: ( Literal[ "papillary_thyroid_carcinoma", "follicular_thyroid_carcinoma", "medullary_thyroid_carcinoma", "anaplastic_thyroid_carcinoma", "others", ] | None ) = dspy.OutputField( desc="identify the histological type of the cancer. e.g. papillary thyroid carcinoma" ) tumor_size: int | None = dspy.OutputField( desc="identify the size of the tumor in mm, rounded, if multiple tumors are present, please provide the size of the largest tumor" ) mitotic_activity: Literal["less_than_3", "3_to_5", "more_than_5"] | None = ( dspy.OutputField( desc="identify the mitotic activity of the tumor, in mitoses per 10 high power fields. if not specified, return null" ) ) extrathyroid_extension: ( Literal[ "microscopic_strap_muscle", "macroscopic_strap_muscle_t3b", "subcutaneous_trachea_esophagus_rln_t4a", "prevertebral_carotid_mediastinal_t4b", ] | None ) = dspy.OutputField( desc="identify if clinically extrathyroid extension is present, only four categories are allowed, if none specified, return None" ) tumor_necrosis: bool | None = dspy.OutputField( desc="check whether or not tumor necrosis is present" ) lymphovascular_invasion: bool | None = dspy.OutputField( desc="check whether or not lymphovascular invasion is present" ) perineural_invasion: bool | None = dspy.OutputField( desc="check whether or not perineural invasion is present" ) distant_metastasis: bool | None = dspy.OutputField( desc="check whether or not distant metastasis is present" ) treatment_effect: str | None = dspy.OutputField( desc='check the treatment effect of the cancer. If you see "No known presurgical therapy", return None' ) class ThyroidCancerStaging(dspy.Signature): """you need to extract the value of the specified items below from the given thyroid cancer excision report. DO NOT JUST RETURN NULL. IF SOME ITEM IS NOT PRESENT, RETURN NULL FOR THAT ITEM, BUT TRY YOUR BEST TO FILL IN THE OTHERS.""" report: list = dspy.InputField( desc="this is a pathological report for thyroid cancer excision, separated into paragraphs." ) report_jsonized: dict = dspy.InputField( desc="this is a roughly structured json summary of the pathological report, which is generated by another model." ) tnm_descriptor: Literal["y", "r", "m"] | None = dspy.OutputField( desc='identify the tnm descriptor of the tumor. e.g., "y" (post-therapy), "r", etc.' ) pt_category: ( Literal["tx", "t1a", "t1b", "t2", "t3a", "t3b", "t4a", "t4b"] | None ) = dspy.OutputField(desc="identify the pt category of the tumor") pn_category: Literal["nx", "n0", "n1a", "n1b"] | None = dspy.OutputField( desc="identify the pn category of the tumor" ) pm_category: Literal["mx", "m0", "m1"] | None = dspy.OutputField( desc="identify the pm category of the tumor. if you see cM0 or cM1, etc., code as mx, since pathological M category is not available" ) overall_stage: Literal["i", "ii", "iii", "iva", "ivb", "ivc"] | None = ( dspy.OutputField(desc="identify the overall stage of the tumor") ) ajcc_version: int | None = dspy.OutputField( desc="identify the ajcc version of the pathological staging" ) class ThyroidCancerMargins(dspy.Signature): """you need to extract the value of the specified items below from the given thyroid cancer excision report. DO NOT JUST RETURN NULL. IF SOME ITEM IS NOT PRESENT, RETURN NULL FOR THAT ITEM, BUT TRY YOUR BEST TO FILL IN THE OTHERS.""" report: list = dspy.InputField( desc="this is a pathological report for thyroid cancer excision, separated into paragraphs." ) report_jsonized: dict = dspy.InputField( desc="this is a roughly structured json summary of the pathological report, which is generated by another model." ) margins: list[ThyroidMargin] | None = dspy.OutputField( desc="""return all of the possible involved margins and its distance from cancer. example:[ {"margin_category": "anterior_outmost", "margin_involved": false, "distance": 10}, {"margin_category": "isthmus", "margin_involved": false, "distance": null}]. If not present, just output null for every margin""" ) class ThyroidCancerLN(dspy.Signature): """you need to extract the value of the specified items below from the given thyroid cancer excision report. DO NOT JUST RETURN NULL. IF SOME ITEM IS NOT PRESENT, RETURN NULL FOR THAT ITEM, BUT TRY YOUR BEST TO FILL IN THE OTHERS.""" report: list = dspy.InputField( desc="this is a pathological report for thyroid cancer excision, separated into paragraphs." ) report_jsonized: dict = dspy.InputField( desc="this is a roughly structured json summary of the pathological report, which is generated by another model." ) regional_lymph_node: list[ThyroidLN] | None = dspy.OutputField( desc="""return all of the involved regional lymph node. example:[{"lymph_node_side": "left", "lymph_node_category": "level_vi_central", "involved": 2, "examined": 5, "station_name": "station 6"}, {"lymph_node_side": "right", "lymph_node_category": "level_ii", "involved": 0, "examined": 3, "station_name": "station 6"}, ...]. If not present, just output null for every lymph node""" ) extranodal_extension: bool | None = dspy.OutputField( desc="check whether or not extranodal extension is present; if no lymph node metastasis, should be None" ) maximal_ln_size: int | None = dspy.OutputField( desc="check the maximal size of node metastatic tumor in mm, rounded to integer; if no lymph node metastasis, should be None" )