# -*- coding: utf-8 -*- """ models/colon.py This script sets up a series of data extraction models using the dspy library for pathology reports, specifically focusing on colorectal 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-15 """ __version__ = "1.0.1" __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.3.1.0" import dspy from typing import Literal from pydantic import BaseModel, Field class ColonMargin(BaseModel): margin_category: ( Literal[ "proximal", "distal", "mesenteric_pedicle", "radial_or_circumferencial", "outmost_of_adhered_tissue", "others", ] | None ) = Field( None, description="acceptable value for surgical margins in colon 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 ColonLN(BaseModel): lymph_node_category: Literal["regional", "mesenteric", "others"] | None = Field( None, description="acceptable value for lymph node categories in colon 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 group/station here." ) class ColonBiomarker(BaseModel): biomarker_category: ( Literal["mlh1", "msh2", "msh6", "pms2", "her2", "others"] | None ) = Field( None, description="acceptable value for biomarker categories in colon cancer. If not included in these standard categories, should be classified as others.", ) expression: bool | None = Field( None, description="specify whether or not the biomarker is expressed here.For Her-2 please refer to the score field, and don't fill in this field.", ) percentage: int | None = Field( None, description="the percentage of tumor cells showing positive expression of the biomarker, rounded to integer. if not specified, return null", ) score: Literal[0, 1, 2, 3] | None = Field( None, description="specify the Her-2 expression score, negative: score 0 or 1, equivocal: score 2, positive: score 3 of the biomarker here, if applicable.", ) biomarker_name: str | None = Field( None, description="specify the name of the biomarker here." ) class ColonCancerNonnested(dspy.Signature): """you need to extract the value of the specified items below from the given colon cancer 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 colon 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." ) procedure: ( Literal[ "right_hemicolectomy", "extended_right_hemicolectomy", "left_hemicolectomy", "low_anterior_resection", "anterior_resection", "abdominoperineal_resection", "total_mesorectal_excision", "total_colectomy", "subtotal_colectomy", "segmental_colectomy", "transanal_local_excision", "polypectomy", "others", ] | None ) = dspy.OutputField( desc="identify which surgery procedure was used. e.g. polypectomy" ) surgical_technique: ( Literal["open", "laparoscopic", "robotic", "ta_tme", "hybrid", "others"] | None ) = dspy.OutputField(desc="identify how the surgery was taken. e.g. laparoscopic") cancer_primary_site: ( Literal[ "cecum", "ascending_colon", "hepatic_flexure", "transverse_colon", "splenic_flexure", "descending_colon", "sigmoid_colon", "rectosigmoid_junction", "rectum", "appendix", ] | None ) = dspy.OutputField(desc="identify the primary site of cancer. e.g. sigmoid colon") histology: ( Literal[ "adenocarcinoma", "mucinous_adenocarcinoma", "signet_ring_cell_carcinoma", "medullary_carcinoma", "micropapillary_adenocarcinoma", "serrated_adenocarcinoma", "adenosquamous_carcinoma", "neuroendocrine_carcinoma", "others", ] | None ) = dspy.OutputField( desc="identify the histological type of the cancer. e.g. adenocarcinoma, if not in the list, classify as others" ) grade: int | None = dspy.OutputField( desc="identify the grade of the cancer, well->1, moderate->2, poor->3, undiff-4" ) tumor_invasion: ( Literal[ "lamina_propria", "submucosa", "muscularis_propria", "pericolorectal_tissue", "visceral_peritoneum_surface", "adjacent_organs_structures", ] | None ) = dspy.OutputField( desc="identify the part invasioned by tumor, e.g lamina propria" ) 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" ) extracellular_mucin: bool | None = dspy.OutputField( desc="check whether or not extracellular mucin is present" ) signet_ring: bool | None = dspy.OutputField( desc="check whether or not signet ring cell is present" ) tumor_budding: int | None = dspy.OutputField( desc="identify the number of tumor budding of the cancer.low->0, moderate->1, high->2" ) type_of_polyp: ( Literal[ "tubular_adenoma", "tubulovillous_adenoma", "villous_adenoma", "sessile_serrated_adenoma", "traditional_serrated_adenoma", ] | None ) = dspy.OutputField(desc="identify the type of polyp of the tumor") 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 ColonCancerStaging(dspy.Signature): """you need to extract the value of the specified items below from the given colon cancer 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 colon 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" means post-therapy, "m" means multiple primary tumor, "r" means recurrent tumor, code this if the report explicitly mean this, dont guess' ) pt_category: Literal["tx", "tis", "t1", "t2", "t3", "t4a", "t4b"] | None = ( dspy.OutputField(desc="identify the pt category of the tumor") ) pn_category: Literal["nx", "n0", "n1a", "n1b", "n1c", "n2a", "n2b"] | None = ( dspy.OutputField(desc="identify the pn category of the tumor") ) pm_category: Literal["mx", "m0", "m1a", "m1b", "m1c"] | 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" ) stage_group: ( Literal[ "0", "i", "iia", "iib", "iic", "iiia", "iiib", "iiic", "iva", "ivb", "ivc" ] | None ) = dspy.OutputField(desc="identify the stage group of the tumor") ajcc_version: int | None = dspy.OutputField( desc="identify the ajcc version of the pathological staging" ) class ColonCancerMargins(dspy.Signature): """you need to extracting the value of the specified items below from the given pathological cancer 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 colon 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[ColonMargin] | None = dspy.OutputField( desc="""return all of the possible involved margins and its distance from cancer. example:[{"margin_category": "proximal", "margin_involved": true, "distance": 5}, {"margin_category": "distal", "margin_involved": false, "distance": null}, {"margin_category": "mesenteric", "margin_involved": false, "distance": null}]. If not present, just output null for every margin""" ) class ColonCancerLN(dspy.Signature): """you need to extracting the value of the specified items below from the given pathological cancer 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 colon 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[ColonLN] | None = dspy.OutputField( desc="""return all of the involved regional lymph node. example:[{"lymph_node_category": "regional", "involved": 2, "examined": 5}, {"lymph_node_category": "mesenteric", "involved": 0, "examined": 3}]. 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" ) class ColonCancerBiomarkers(dspy.Signature): """you need to extracting the value of the specified items below from the given pathological cancer 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 colon 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." ) biomarkers: list[ColonBiomarker] | None = dspy.OutputField( desc="""return all of the examined immunoreceptors using immunohistochemistry techniques,like mlh1, msh2, etc. in JSON format. example:{"MSH6": {"expression": true,"percentage": 90}, "PMS2": {"expression": true, "percentage": 100}},"mlh1": {"expression": true, "percentage": 100}}.""" )