Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.
feat(zh/tcm): 新增中医领域知识模板及测试样本
yifanfeng97ef7908b2a8a1
diff --git a/examples/template_general_demo.py b/examples/template_general_demo.pyindex e69726e..b9c575b 100644--- a/examples/template_general_demo.py+++ b/examples/template_general_demo.py@@ -140,19 +140,18 @@ def main():return# 读取输入文件内容- print(f"\n📖 读取文件内容...")+ print("\n📖 读取文件内容...")with open(INPUT_FILE, "r", encoding="utf-8") as f:content = f.read()print(f"✅ 读取成功,共 {len(content)} 字符")# 初始化模板并进行知识提取- print(f"\n🧠 开始知识提取...")+ print("\n🧠 开始知识提取...")try:# 初始化模板template = TEMPLATE(llm_client=llm,embedder=embedder,- extraction_mode="two_stage",verbose=True,)diff --git a/examples/template_medicine_demo.py b/examples/template_medicine_demo.pynew file mode 100644index 0000000..5729b53--- /dev/null+++ b/examples/template_medicine_demo.py@@ -0,0 +1,184 @@+"""+Medical 知识模板测试演示++这个文件用于测试 hyperextract 中医学领域的所有知识模板。+只需要选择模板,程序会自动匹配对应的输入文件。++使用方法:+1. 选择知识模板(修改 TEMPLATE 变量)+2. 运行文件:python examples/template_medicine_demo.py+"""++import os+import sys++# Add project root to path+sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from pathlib import Path+from dotenv import load_dotenv++# 导入所有医学知识模板+from hyperextract.templates.zh.medicine import (+ # 医学教科书与专著+ PathologyHypergraph,+ MedicalConceptNet,+ PharmacologyGraph,+ AnatomyHierarchy,+ SymptomDifferential,+ # 临床诊疗指南+ TreatmentRegimenMap,+ ClinicalPathway,+ LevelOfEvidence,+ # 出院小结+ SurgicalEventGraph,+ HospitalCourseTimeline,+ DischargeInstruction,+ # 病理报告+ TumorStagingItem,+ MicroscopicFeatureSet,+ # 药品说明书+ ComplexInteractionNet,+ ContraindicationList,+ AdverseReactionStats,+)++# 导入必要的 LLM 客户端+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+++# ==========================================+# 配置:模板与输入文件自动映射+# ==========================================++# 测试文件根目录+TEST_SAMPLES_ROOT = Path(__file__).parent.parent / "tests" / "fixtures" / "test_samples" / "zh" / "medicine"++# 模板到输入文件的映射关系(根据 README 中的典型应用场景)+TEMPLATE_TO_INPUT = {+ # 医学教科书与专著 -> 病理学教材+ PathologyHypergraph: TEST_SAMPLES_ROOT / "textbook_sample.md",+ MedicalConceptNet: TEST_SAMPLES_ROOT / "textbook_sample.md",+ PharmacologyGraph: TEST_SAMPLES_ROOT / "textbook_sample.md",+ AnatomyHierarchy: TEST_SAMPLES_ROOT / "textbook_sample.md",+ SymptomDifferential: TEST_SAMPLES_ROOT / "textbook_sample.md",+ # 临床诊疗指南 -> 临床指南+ TreatmentRegimenMap: TEST_SAMPLES_ROOT / "clinical_guideline_sample.md",+ ClinicalPathway: TEST_SAMPLES_ROOT / "clinical_guideline_sample.md",+ LevelOfEvidence: TEST_SAMPLES_ROOT / "clinical_guideline_sample.md",+ # 出院小结 -> 出院小结+ SurgicalEventGraph: TEST_SAMPLES_ROOT / "discharge_summary_sample.md",+ HospitalCourseTimeline: TEST_SAMPLES_ROOT / "discharge_summary_sample.md",+ DischargeInstruction: TEST_SAMPLES_ROOT / "discharge_summary_sample.md",+ # 病理报告 -> 病理报告+ TumorStagingItem: TEST_SAMPLES_ROOT / "pathology_report_sample.md",+ MicroscopicFeatureSet: TEST_SAMPLES_ROOT / "pathology_report_sample.md",+ # 药品说明书 -> 药品说明书+ ComplexInteractionNet: TEST_SAMPLES_ROOT / "package_insert_sample.md",+ ContraindicationList: TEST_SAMPLES_ROOT / "package_insert_sample.md",+ AdverseReactionStats: TEST_SAMPLES_ROOT / "package_insert_sample.md",+}++# ==========================================+# 选择知识模板(只需要修改这一行)+# ==========================================++# 医学教科书与专著+# TEMPLATE = PathologyHypergraph # 多因素病理机制图+# TEMPLATE = MedicalConceptNet # 医学概念网络+# TEMPLATE = PharmacologyGraph # 药理机制图+# TEMPLATE = AnatomyHierarchy # 解剖层级树+TEMPLATE = SymptomDifferential # 鉴别诊断表++# 临床诊疗指南+# TEMPLATE = TreatmentRegimenMap # 综合治疗方案图+# TEMPLATE = ClinicalPathway # 临床路径图+# TEMPLATE = LevelOfEvidence # 证据评级表++# 出院小结+# TEMPLATE = SurgicalEventGraph # 手术事件超图+# TEMPLATE = HospitalCourseTimeline # 住院病程时间轴+# TEMPLATE = DischargeInstruction # 出院医嘱摘要++# 病理报告+# TEMPLATE = TumorStagingItem # TNM 分期表+# TEMPLATE = MicroscopicFeatureSet # 微观特征集++# 药品说明书+# TEMPLATE = ComplexInteractionNet # 条件性相互作用网+# TEMPLATE = ContraindicationList # 禁忌症清单+# TEMPLATE = AdverseReactionStats # 不良反应统计++# 自动获取对应的输入文件+INPUT_FILE = TEMPLATE_TO_INPUT[TEMPLATE]+++def main():+ """+ 主函数:执行知识提取和展示流程+ """+ print("=" * 60)+ print("Medical 知识模板测试演示")+ print("=" * 60)++ # 加载环境变量+ load_dotenv()++ # 验证输入文件是否存在+ if not INPUT_FILE.exists():+ print(f"❌ 错误:找不到文件 {INPUT_FILE}")+ return++ print(f"\n📄 输入文件: {INPUT_FILE.name}")+ print(f"🎯 使用模板: {TEMPLATE.__name__}")++ # 初始化 LLM 客户端+ print("\n🔧 初始化 LLM 客户端...")+ try:+ llm = ChatOpenAI(+ model="gpt-4o-mini",+ temperature=0,+ )+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")+ print("✅ LLM 客户端初始化成功")+ except Exception as e:+ print(f"❌ LLM 客户端初始化失败: {e}")+ print("💡 请确保您已经正确设置了 OPENAI_API_KEY 环境变量")+ return++ # 读取输入文件内容+ print("\n📖 读取文件内容...")+ with open(INPUT_FILE, "r", encoding="utf-8") as f:+ content = f.read()+ print(f"✅ 读取成功,共 {len(content)} 字符")++ # 初始化模板并进行知识提取+ print("\n🧠 开始知识提取...")+ try:+ # 初始化模板+ template = TEMPLATE(+ llm_client=llm,+ embedder=embedder,+ verbose=True,+ )++ # 喂入文本+ template.feed_text(content)+ print("✅ 知识提取完成")++ # 展示结果+ template.build_index()+ print("\n" + "=" * 60)+ print("📊 提取结果展示")+ print("=" * 60)+ template.show()++ except Exception as e:+ print(f"❌ 知识提取失败: {e}")+ import traceback++ traceback.print_exc()+++if __name__ == "__main__":+ main()diff --git a/examples/template_tcm_demo.py b/examples/template_tcm_demo.pynew file mode 100644index 0000000..4000672--- /dev/null+++ b/examples/template_tcm_demo.py@@ -0,0 +1,162 @@+"""+TCM 知识模板测试演示++这个文件用于测试 hyperextract 中医领域的所有知识模板。+只需要选择模板,程序会自动匹配对应的输入文件。++使用方法:+1. 选择知识模板(修改 TEMPLATE 变量)+2. 运行文件:python examples/template_tcm_demo.py+"""++import os+import sys++# Add project root to path+sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from pathlib import Path+from dotenv import load_dotenv++# 导入所有中医知识模板+from hyperextract.templates.zh.tcm import (+ # 本草典籍+ HerbPropertyModel,+ ProcessingMethod,+ CompatibilityNet,+ # 方剂规范+ FormulaComposition,+ FunctionIndicationMap,+ # 经络腧穴专著+ MeridianFlowGraph,+ AcupointLocationMap,+ # 名医医案+ SyndromeReasoningGraph,+ PrescriptionModification,+ PulseTongueRecord,+)++# 导入必要的 LLM 客户端+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+++# ==========================================+# 配置:模板与输入文件自动映射+# ==========================================++# 测试文件根目录+TEST_SAMPLES_ROOT = Path(__file__).parent.parent / "tests" / "fixtures" / "test_samples" / "zh" / "tcm"++# 模板到输入文件的映射关系(根据 README 中的典型应用场景)+TEMPLATE_TO_INPUT = {+ # 本草典籍 -> 本草纲目+ HerbPropertyModel: TEST_SAMPLES_ROOT / "herbal_compendium_sample.md",+ ProcessingMethod: TEST_SAMPLES_ROOT / "herbal_compendium_sample.md",+ CompatibilityNet: TEST_SAMPLES_ROOT / "herbal_compendium_sample.md",+ # 方剂规范 -> 伤寒论+ FormulaComposition: TEST_SAMPLES_ROOT / "prescription_formulary_sample.md",+ FunctionIndicationMap: TEST_SAMPLES_ROOT / "prescription_formulary_sample.md",+ # 经络腧穴专著 -> 黄帝内经十二经脉+ MeridianFlowGraph: TEST_SAMPLES_ROOT / "meridian_treatise_sample.md",+ AcupointLocationMap: TEST_SAMPLES_ROOT / "meridian_treatise_sample.md",+ # 名医医案+ SyndromeReasoningGraph: TEST_SAMPLES_ROOT / "medical_case_record_sample.md",+ PrescriptionModification: TEST_SAMPLES_ROOT / "medical_case_record_sample.md",+ PulseTongueRecord: TEST_SAMPLES_ROOT / "medical_case_record_sample.md",+}++# ==========================================+# 选择知识模板(只需要修改这一行)+# ==========================================++# 本草典籍+# TEMPLATE = HerbPropertyModel # 药物性味归经+# TEMPLATE = ProcessingMethod # 炮制方法列表+# TEMPLATE = CompatibilityNet # 七情配伍网络++# 方剂规范+# TEMPLATE = FormulaComposition # 君臣佐使结构图+TEMPLATE = FunctionIndicationMap # 主治功效映射++# 经络腧穴专著+# TEMPLATE = MeridianFlowGraph # 经络流注图+# TEMPLATE = AcupointLocationMap # 腧穴空间定位++# 名医医案+# TEMPLATE = SyndromeReasoningGraph # 辨证论治逻辑图+# TEMPLATE = PrescriptionModification # 处方加减逻辑+# TEMPLATE = PulseTongueRecord # 舌脉特征提取++# 自动获取对应的输入文件+INPUT_FILE = TEMPLATE_TO_INPUT[TEMPLATE]+++def main():+ """+ 主函数:执行知识提取和展示流程+ """+ print("=" * 60)+ print("TCM 知识模板测试演示")+ print("=" * 60)++ # 加载环境变量+ load_dotenv()++ # 验证输入文件是否存在+ if not INPUT_FILE.exists():+ print(f"❌ 错误:找不到文件 {INPUT_FILE}")+ return++ print(f"\n📄 输入文件: {INPUT_FILE.name}")+ print(f"🎯 使用模板: {TEMPLATE.__name__}")++ # 初始化 LLM 客户端+ print("\n🔧 初始化 LLM 客户端...")+ try:+ llm = ChatOpenAI(+ model="gpt-4o-mini",+ temperature=0,+ )+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")+ print("✅ LLM 客户端初始化成功")+ except Exception as e:+ print(f"❌ LLM 客户端初始化失败: {e}")+ print("💡 请确保您已经正确设置了 OPENAI_API_KEY 环境变量")+ return++ # 读取输入文件内容+ print("\n📖 读取文件内容...")+ with open(INPUT_FILE, "r", encoding="utf-8") as f:+ content = f.read()+ print(f"✅ 读取成功,共 {len(content)} 字符")++ # 初始化模板并进行知识提取+ print("\n🧠 开始知识提取...")+ try:+ # 初始化模板+ template = TEMPLATE(+ llm_client=llm,+ embedder=embedder,+ verbose=True,+ )++ # 喂入文本+ template.feed_text(content)+ print("✅ 知识提取完成")++ # 展示结果+ template.build_index()+ print("\n" + "=" * 60)+ print("📊 提取结果展示")+ print("=" * 60)+ template.show()++ except Exception as e:+ print(f"❌ 知识提取失败: {e}")+ import traceback++ traceback.print_exc()+++if __name__ == "__main__":+ main()diff --git a/hyperextract/templates/en/__init__.py b/hyperextract/templates/en/__init__.pyindex 5f14636..f2a4884 100644--- a/hyperextract/templates/en/__init__.py+++ b/hyperextract/templates/en/__init__.py@@ -1,33 +1,22 @@from .general import (- # Knowledge Graph+ # Arbitrary TextKnowledgeGraph,- # Entity RegistryEntityRegistry,- # Keyword ListKeywordList,- # Encyclopedia Item+ # Wikipedia/Baidu Baike EntriesEncyclopediaItem,- # Concept HierarchyConceptHierarchy,- # Cross Reference NetworkCrossReferenceNet,- # Personal Profile+ # Biographies and MemoirsPersonalProfile,- # Social NetworkSocialNetwork,- # Life Event TimelineLifeEventTimeline,- # Regulation Profile+ # Rules and Compliance DocumentsRegulationProfile,- # Clause ListClauseList,- # Penalty RegistryPenaltyRegistry,- # Operational ProcedureOperationalProcedure,- # Penalty MappingPenaltyMapping,- # Compliance LogicComplianceLogic,)from .agriculture import CropCycleGraph, LivestockGraph, AgriPestControl@@ -58,44 +47,28 @@ from .finance import (MarketNarrativeTimeline,)from .literature import CharacterRelationshipGraph, NarrativeTimeline, SymbolismSet-from .medicine import DrugInteractionGraph, ClinicalTreatmentTimeline, DiagnosticCriteriaSet+# from .medicine import DrugInteractionGraph, ClinicalTreatmentTimeline, DiagnosticCriteriaSetfrom .news import BreakingEventGraph, TopicTimeline, OpinionSet__all__ = [# general- ## Knowledge Graph"KnowledgeGraph",- ## Entity Registry"EntityRegistry",- ## Keyword List"KeywordList",- ## Encyclopedia Item"EncyclopediaItem",- ## Concept Hierarchy"ConceptHierarchy",- ## Cross Reference Network"CrossReferenceNet",- ## Personal Profile"PersonalProfile",- ## Social Network"SocialNetwork",- ## Life Event Timeline"LifeEventTimeline",- ## Regulation Profile"RegulationProfile",- ## Clause List"ClauseList",- ## Penalty Registry"PenaltyRegistry",- ## Operational Procedure"OperationalProcedure",- ## Penalty Mapping"PenaltyMapping",- ## Compliance Logic"ComplianceLogic",# Finance"RiskAssessmentGraph",- "MarketSentimentGraph","SupplyChainGraph","FilingFinancialSnapshot","MDANarrativeGraph",@@ -122,12 +95,6 @@ __all__ = ["CharacterRelationshipGraph","NarrativeTimeline","SymbolismSet",- "DrugInteractionGraph",- "ClinicalTreatmentTimeline",- "DiagnosticCriteriaSet",- "ScriptSceneGraph",- "CharacterArcTracker",- "CinematicTriviaSet","BreakingEventGraph","TopicTimeline","OpinionSet",@@ -139,7 +106,4 @@ __all__ = ["TaxonomyGraph","BiologicalNetwork","MetabolicHypergraph",- "MolecularStructureGraph",- "ChemicalReactionHyper",- "LabProtocolTemporal",]diff --git a/hyperextract/templates/en/medicine/__init__.py b/hyperextract/templates/en/medicine/__init__.pyindex 423c4b3..e69de29 100644--- a/hyperextract/templates/en/medicine/__init__.py+++ b/hyperextract/templates/en/medicine/__init__.py@@ -1,9 +0,0 @@-from .drug_interaction_graph import DrugInteractionGraph-from .clinical_treatment_timeline import ClinicalTreatmentTimeline-from .diagnostic_criteria_set import DiagnosticCriteriaSet--__all__ = [- "DrugInteractionGraph",- "ClinicalTreatmentTimeline",- "DiagnosticCriteriaSet",-]diff --git a/hyperextract/templates/en/medicine/clinical_treatment_timeline.py b/hyperextract/templates/en/medicine/clinical_treatment_timeline.pydeleted file mode 100644index 1f78a8a..0000000--- a/hyperextract/templates/en/medicine/clinical_treatment_timeline.py+++ /dev/null@@ -1,143 +0,0 @@-from typing import List, Optional, Any, Tuple-from pydantic import BaseModel, Field-from langchain_core.language_models.chat_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoTemporalGraph--# ==============================================================================-# 1. Schema Definitions-# ==============================================================================--class MedicalEvent(BaseModel):- """A single medical event within a clinical pathway."""- event_name: str = Field(description="Event name or diagnostic summary (e.g., 'Admission Diagnosis', 'ECG Exam', 'Splenectomy').")- event_type: str = Field(description="Type of event (e.g., Chief Complaint, Physical Exam, Lab Test, Diagnosis, Medication, Surgery, Discharge).")- finding: Optional[str] = Field(description="Specific finding, result, or treatment detail (e.g., 'Hb 90g/L', 'Surgery successful').")--class ClinicalProgression(BaseModel):- """The progression of medical events over time."""- source: str = Field(description="Preceding medical event.")- target: str = Field(description="Subsequent medical event.")- time: str = Field(description="Relative or absolute time of the event. You MUST resolve fuzzy expressions (e.g., 'a few hours later') into absolute timestamps (e.g., '2024-01-01 10:00') or standard offsets (e.g., '6h post-op') based on the base date/context.")- status_change: str = Field(description="Change in patient condition or treatment response (e.g., 'Improvement', 'Deterioration', 'Stable').")--# ==============================================================================-# 2. Prompts-# ==============================================================================--_PROMPT = (- "You are an expert clinical documentation analyst. Your task is to extract the diagnostic and therapeutic progression from medical records or clinical pathway documents.\n\n"- "Analysis Guidelines:\n"- "1. **Medical Fact Extraction**: Record every significant medical activity (tests, medications, surgeries) and its core results.\n"- "2. **Temporal Logic Chain**: Establish links in strict chronological order. Use time markers in the text (e.g., '30 mins before surgery', 'next morning') to connect events.\n"- "3. **Dynamic Tracking**: Focus on describing the evolution of the patient's status (status_change) following clinical interventions.\n"-)--_NODE_PROMPT = (- "Extract all key clinical nodes from the record, including chief complaints, vital signs, lab results, diagnoses, clinical procedures, and surgeries."-)--_EDGE_PROMPT = (- "Establish temporal connections between clinical nodes. Resolve chronological cues into specific times or offsets and summarize the dynamic changes in patient condition."-)--# ==============================================================================-# 3. Template Class-# ==============================================================================--class ClinicalTreatmentTimeline(AutoTemporalGraph[MedicalEvent, ClinicalProgression]):- """- Applicable to: [Electronic Medical Records (EMR), Discharge Summaries, Case Reports, Nursing Notes]-- Knowledge pattern for reconstructing a patient's clinical lifecycle as a temporal pathway.-- Leveraging AutoTemporalGraph, this template focuses on the 'Diagnosis-Intervention-Feedback' logic- to facilitate retrospective case analysis.-- Example:- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings- >>> llm = ChatOpenAI(model="gpt-4o")- >>> embedder = OpenAIEmbeddings()- >>> # Initialize template- >>> pathway = ClinicalTreatmentTimeline(llm_client=llm, embedder=embedder)- >>> # Feed medical record text- >>> text = "Patient admitted on Jan 10. Appendectomy performed on Jan 11. Recovered well and discharged on Jan 15."- >>> pathway.feed_text(text)- >>> pathway.show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- observation_time: Optional[str] = None,- extraction_mode: str = "two_stage",- chunk_size: int = 2048,- chunk_overlap: int = 256,- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any- ):- """- Initialize ClinicalTreatmentTimeline template.-- Args:- llm_client: Language model client.- embedder: Embeddings model for indexing.- observation_time: Admission date or reference date.- extraction_mode: Defaults to 'two_stage' for complex medical history parsing.- chunk_size: Processing chunk size.- chunk_overlap: Chunk overlap.- max_workers: Parallel workers.- verbose: Enable detailed logging.- **kwargs: Extra arguments for AutoTemporalGraph.- """- super().__init__(- node_schema=MedicalEvent,- edge_schema=ClinicalProgression,- node_key_extractor=lambda x: x.event_name.strip(),- edge_key_extractor=lambda x: f"{x.source}>>{x.target}",- time_in_edge_extractor=lambda x: x.time,- nodes_in_edge_extractor=lambda x: (x.source, x.target),- llm_client=llm_client,- embedder=embedder,- observation_time=observation_time,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- extraction_mode=extraction_mode,- chunk_size=chunk_size,- chunk_overlap=chunk_overlap,- max_workers=max_workers,- verbose=verbose,- **kwargs- )-- def show(- self,- *,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,- ) -> None:- """- Visualize the clinical treatment timeline.-- Args:- top_k_for_search: Search context depth.- top_k_for_chat: Chat context depth.- """- def node_label_extractor(node: MedicalEvent) -> str:- return f"[{node.event_type}] {node.event_name}"-- def edge_label_extractor(edge: ClinicalProgression) -> str:- return f"({edge.time}) {edge.status_change}"-- super().show(- node_label_extractor=node_label_extractor,- edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,- )diff --git a/hyperextract/templates/en/medicine/diagnostic_criteria_set.py b/hyperextract/templates/en/medicine/diagnostic_criteria_set.pydeleted file mode 100644index 739b54d..0000000--- a/hyperextract/templates/en/medicine/diagnostic_criteria_set.py+++ /dev/null@@ -1,112 +0,0 @@-from typing import List, Optional, Any, Callable-from pydantic import BaseModel, Field-from langchain_core.language_models.chat_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoSet--# ==============================================================================-# 1. Schema Definitions-# ==============================================================================--class DiagnosticCriteria(BaseModel):- """Diagnostic criteria and clinical classification for a disease."""- disease_name: str = Field(description="Standardized name of the disease (e.g., 'Type 2 Diabetes', 'Acute Myocardial Infarction').")- major_criteria: List[str] = Field(description="Core mandatory conditions or major diagnostic indicators.")- minor_criteria: List[str] = Field(description="Supporting conditions or minor diagnostic indicators.")- exclusion_criteria: List[str] = Field(description="Conditions that, if present, exclude the diagnosis.")- biomarkers: List[str] = Field(description="Key laboratory findings or biomarkers (e.g., 'HbA1c > 6.5%').")- source_guideline: str = Field(description="Source of this criteria, e.g., 'ADA 2024 Guidelines', 'WHO Classification'.")--# ==============================================================================-# 2. Prompts-# ==============================================================================--_PROMPT = (- "You are an expert in parsing clinical practice guidelines. Your task is to extract structured diagnostic criteria for specific diseases from medical literature.\n\n"- "Extraction Principles:\n"- "1. **Normalization**: Ensure all information for the same disease is aggregated under its standard medical name.\n"- "2. **Strict Differentiation**: Clearly distinguish between 'Major Criteria', 'Minor Criteria', and 'Exclusion Criteria'.\n"- "3. **Cumulative Information**: If criteria for the same disease is found in different parts of the text or across multiple sessions, merge them and list all sources in the source_guideline field.\n"-)--# ==============================================================================-# 3. Template Class-# ==============================================================================--class DiagnosticCriteriaSet(AutoSet[DiagnosticCriteria]):- """- Applicable to: [Clinical Practice Guidelines, Specialist Consensus, Medical Textbooks]-- Knowledge pattern for aggregating and maintaining diagnostic criteria libraries from medical guidelines.-- Leveraging AutoSet's key-accumulation feature, this template merges criteria from different- versions or organizations into a single, comprehensive reference for clinical use.-- Example:- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings- >>> llm = ChatOpenAI(model="gpt-4o")- >>> embedder = OpenAIEmbeddings()- >>> # Initialize template- >>> criteria_lib = DiagnosticCriteriaSet(llm_client=llm, embedder=embedder)- >>> # Feed guidelines from different sources- >>> criteria_lib.feed_text("ADA 2024 states HbA1c > 6.5% for T2D.").feed_text("WHO notes fasting glucose remains a key criterion.")- >>> criteria_lib.show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- chunk_size: int = 2048,- chunk_overlap: int = 256,- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any- ):- """- Initialize DiagnosticCriteriaSet template.-- Args:- llm_client: Language model client.- embedder: Embeddings model for retrieval and visualization.- chunk_size: Max characters per processing chunk.- chunk_overlap: Overlap between chunks.- max_workers: Parallel workers.- verbose: Enable detailed logging.- **kwargs: Extra arguments for AutoSet.- """- super().__init__(- item_schema=DiagnosticCriteria,- key_extractor=lambda x: x.disease_name.strip().lower(), # Matches disease name for normalization- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- chunk_size=chunk_size,- chunk_overlap=chunk_overlap,- max_workers=max_workers,- verbose=verbose,- **kwargs- )-- def show(- self,- *,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,- ) -> None:- """- Visualize the diagnostic criteria library.-- Args:- top_k_for_search: Items for search.- top_k_for_chat: Items for chat.- """- def item_label_extractor(item: DiagnosticCriteria) -> str:- return item.disease_name-- super().show(- item_label_extractor=item_label_extractor,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,- )diff --git a/hyperextract/templates/en/medicine/drug_interaction_graph.py b/hyperextract/templates/en/medicine/drug_interaction_graph.pydeleted file mode 100644index 19e7029..0000000--- a/hyperextract/templates/en/medicine/drug_interaction_graph.py+++ /dev/null@@ -1,142 +0,0 @@-from typing import List, Optional, Any, Tuple-from pydantic import BaseModel, Field-from langchain_core.language_models.chat_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoGraph--# ==============================================================================-# 1. Schema Definitions-# ==============================================================================--class MedicalSubstance(BaseModel):- """A drug, active ingredient, or dietary supplement."""- name: str = Field(description="The generic name or major brand name of the substance (e.g., 'Aspirin', 'Warfarin').")- category: str = Field(description="Therapeutic category (e.g., 'NSAID', 'Anticoagulant').")- description: Optional[str] = Field(description="Primary function or indication of the substance.")--class DrugInteraction(BaseModel):- """Properties of the interaction between two substances."""- source: str = Field(description="First drug/substance name.")- target: str = Field(description="Second drug/substance name.")- interaction_type: str = Field(description="Nature of interaction (e.g., Contraindicated, Use with caution, Synergistic, Antagonistic).")- severity: str = Field(description="Severity levels (e.g., Major, Moderate, Minor).")- mechanism: str = Field(description="Pharmacological mechanism (e.g., 'Competition for CYP enzymes leading to increased blood levels').")- recommendation: str = Field(description="Clinical action/advice (e.g., 'Strictly avoid combination', 'Monitor PT/INR').")--# ==============================================================================-# 2. Prompts-# ==============================================================================--_PROMPT = (- "You are a professional clinical pharmacologist. Your task is to extract drug-drug interactions from medical literature, labels, or guidelines.\n\n"- "Extraction Rules:\n"- "1. **Normalization**: Prefer generic names (INN). If only brand names are present, record them as is.\n"- "2. **Rigorous Mapping**: Accurately capture the interaction type, severity, and the underlying medical mechanism.\n"- "3. **Clinical Guidance**: Always include the clinical recommendation or precautionary advice mentioned in the text.\n"- "- Ensure every interaction connects nodes that are identified in the medical substance list."-)--_NODE_PROMPT = (- "Extract all medical substances, chemical names, or supplements mentioned in the text. Clearly identify their category and primary pharmacological effect."-)--_EDGE_PROMPT = (- "Identify explicit interactions between the extracted substances. Specify the type, severity, and detailed mechanism for each interaction based on the text."-)--# ==============================================================================-# 3. Template Class-# ==============================================================================--class DrugInteractionGraph(AutoGraph[MedicalSubstance, DrugInteraction]):- """- Applicable to: [Drug Labels/Inserts, Pharmacopoeias, Clinical Practice Guidelines, Medical Journals]-- Knowledge pattern for constructing drug contraindication and synergy networks.-- Using a two-stage extraction process, this template parses rigorous medical literature- to create structured interaction graphs for clinical decision support.-- Example:- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings- >>> llm = ChatOpenAI(model="gpt-4o")- >>> embedder = OpenAIEmbeddings()- >>> # Initialize template- >>> drug_map = DrugInteractionGraph(llm_client=llm, embedder=embedder)- >>> # Feed text from a drug label- >>> text = "Combining Warfarin with Aspirin significantly increases bleeding risk (Major). Avoid concurrent use."- >>> drug_map.feed_text(text)- >>> drug_map.show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- extraction_mode: str = "one_stage",- chunk_size: int = 2048,- chunk_overlap: int = 256,- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any- ):- """- Initialize DrugInteractionGraph template.-- Args:- llm_client: Language model client.- embedder: Embeddings model for deduplication.- extraction_mode: "one_stage" for quick drafts, "two_stage" for rigorous medical extraction.- chunk_size: Max characters per processing chunk.- chunk_overlap: Overlap between chunks.- max_workers: Parallel workers.- verbose: Enable detailed logging.- **kwargs: Extra arguments for AutoGraph.- """- super().__init__(- node_schema=MedicalSubstance,- edge_schema=DrugInteraction,- node_key_extractor=lambda x: x.name.strip().lower(),- edge_key_extractor=lambda x: f"{x.source}|{x.target}",- nodes_in_edge_extractor=lambda x: (x.source, x.target),- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- extraction_mode=extraction_mode,- chunk_size=chunk_size,- chunk_overlap=chunk_overlap,- max_workers=max_workers,- verbose=verbose,- **kwargs- )-- def show(- self,- *,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,- ) -> None:- """- Visualize the drug interaction graph.-- Args:- top_k_for_search: Nodes/edges for search.- top_k_for_chat: Nodes/edges for chat.- """- def node_label_extractor(node: MedicalSubstance) -> str:- return node.name.capitalize()-- def edge_label_extractor(edge: DrugInteraction) -> str:- return f"{edge.interaction_type} ({edge.severity})"-- super().show(- node_label_extractor=node_label_extractor,- edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,- )diff --git a/hyperextract/templates/zh/__init__.py b/hyperextract/templates/zh/__init__.pyindex c303507..00331e9 100644--- a/hyperextract/templates/zh/__init__.py+++ b/hyperextract/templates/zh/__init__.py@@ -1,33 +1,22 @@from .general import (- # 知识图谱+ # 任意文本KnowledgeGraph,- # 实体集合EntityRegistry,- # 关键词列表KeywordList,- # 百科条目+ # 维基百科/百度百科条目EncyclopediaItem,- # 概念层级图ConceptHierarchy,- # 引用网络CrossReferenceNet,- # 个人档案+ # 人物传记与回忆录PersonalProfile,- # 社会网络SocialNetwork,- # 生平时序图LifeEventTimeline,- # 规章元数据快照+ # 规章制度与合规文档RegulationProfile,- # 规章条文清单ClauseList,- # 违规处罚对照表PenaltyRegistry,- # 执行程序流程图OperationalProcedure,- # 违规处罚因果链PenaltyMapping,- # 合规行为超图ComplianceLogic,)from .agriculture import CropCycleGraph, LivestockGraph, AgriPestControl@@ -59,50 +48,64 @@ from .finance import ()from .literature import CharacterRelationshipGraph, NarrativeTimeline, SymbolismSetfrom .medicine import (- DrugInteractionGraph,- ClinicalTreatmentTimeline,- DiagnosticCriteriaSet,+ # 医学教科书与专著+ PathologyHypergraph,+ MedicalConceptNet,+ PharmacologyGraph,+ AnatomyHierarchy,+ SymptomDifferential,+ # 临床诊疗指南+ TreatmentRegimenMap,+ ClinicalPathway,+ LevelOfEvidence,+ # 出院小结+ SurgicalEventGraph,+ HospitalCourseTimeline,+ DischargeInstruction,+ # 病理报告+ TumorStagingItem,+ MicroscopicFeatureSet,+ # 药品说明书+ ComplexInteractionNet,+ ContraindicationList,+ AdverseReactionStats,)+from .news import BreakingEventGraph, TopicTimeline, OpinionSet+from .tcm import (- PrescriptionCompositionGraph,- SyndromeTreatmentLoop,- MeridianAcupointSpatial,- PrescriptionManualSet,- HerbInteractionHypergraph,+ # 本草典籍+ HerbPropertyModel,+ ProcessingMethod,+ CompatibilityNet,+ # 方剂规范+ FormulaComposition,+ FunctionIndicationMap,+ # 经络腧穴专著+ MeridianFlowGraph,+ AcupointLocationMap,+ # 名医医案+ SyndromeReasoningGraph,+ PrescriptionModification,+ PulseTongueRecord,)__all__ = [- # general- ## 知识图谱+ # General"KnowledgeGraph",- ## 实体集合"EntityRegistry",- ## 关键词列表"KeywordList",- ## 百科条目"EncyclopediaItem",- ## 概念层级图"ConceptHierarchy",- ## 引用网络"CrossReferenceNet",- ## 个人档案"PersonalProfile",- ## 社会网络"SocialNetwork",- ## 生平时序图"LifeEventTimeline",- ## 规章元数据快照"RegulationProfile",- ## 规章条文清单"ClauseList",- ## 违规处罚对照表"PenaltyRegistry",- ## 执行程序流程图"OperationalProcedure",- ## 违规处罚因果链"PenaltyMapping",- ## 合规行为超图"ComplianceLogic",# Finance"RiskAssessmentGraph",@@ -133,23 +136,40 @@ __all__ = ["CharacterRelationshipGraph","NarrativeTimeline","SymbolismSet",- "DrugInteractionGraph",- "ClinicalTreatmentTimeline",- "DiagnosticCriteriaSet",+ # Medicine+ "PathologyHypergraph",+ "MedicalConceptNet",+ "PharmacologyGraph",+ "AnatomyHierarchy",+ "SymptomDifferential",+ "TreatmentRegimenMap",+ "ClinicalPathway",+ "LevelOfEvidence",+ "SurgicalEventGraph",+ "HospitalCourseTimeline",+ "DischargeInstruction",+ "TumorStagingItem",+ "MicroscopicFeatureSet",+ "ComplexInteractionNet",+ "ContraindicationList",+ "AdverseReactionStats","ScriptSceneGraph","CharacterArcTracker","CinematicTriviaSet","BreakingEventGraph","TopicTimeline","OpinionSet",- "PrescriptionCompositionGraph",- "SyndromeTreatmentLoop",- "MeridianAcupointSpatial",- "PrescriptionManualSet",- "HerbInteractionHypergraph",- "CultivationSystemMap",- "SectRelationGraph",- "ArtifactRegistry",+ # TCM+ "HerbPropertyModel",+ "ProcessingMethod",+ "CompatibilityNet",+ "FormulaComposition",+ "FunctionIndicationMap",+ "MeridianFlowGraph",+ "AcupointLocationMap",+ "SyndromeReasoningGraph",+ "PrescriptionModification",+ "PulseTongueRecord",# Agriculture"CropCycleGraph","LivestockGraph",diff --git a/hyperextract/templates/zh/general/life_event_timeline.py b/hyperextract/templates/zh/general/life_event_timeline.pyindex 7011eb5..383ac88 100644--- a/hyperextract/templates/zh/general/life_event_timeline.py+++ b/hyperextract/templates/zh/general/life_event_timeline.py@@ -1,180 +1,99 @@-"""生平时序图 - 提取带时间戳的事件,并按时间顺序排列。--适用于人物传记、年表、回忆录等。-"""--from typing import Any, Optional-from pydantic import BaseModel, Field+from typing import Any+from datetime import datetimefrom langchain_core.language_models import BaseChatModelfrom langchain_core.embeddings import Embeddings+from pydantic import BaseModel, Fieldfrom hyperextract.types import AutoTemporalGraph-class LifeEntity(BaseModel):- """生活实体节点"""- name: str = Field(description="实体名称")- type: str = Field(description="实体类型:人物、地点、组织、物品、概念、其他")+class PersonEntity(BaseModel):+ """人物实体"""+ name: str = Field(description="人物姓名")description: str = Field(description="简要描述", default="")class LifeEvent(BaseModel):- """生活事件边(带可选时间戳)"""- source: str = Field(description="事件主体/相关实体")- target: str = Field(description="事件对象/相关实体")- eventType: str = Field(description="事件类型:出生、逝世、教育、工作、成就、交往、旅行、其他")- eventDate: Optional[str] = Field(description="事件日期,格式为年-月-日或年份,可选", default=None)- details: str = Field(description="事件详细描述", default="")+ """生活事件"""+ source: str = Field(description="相关人物")+ eventType: str = Field(description="事件类型:出生、教育、工作、婚姻、死亡等")+ eventName: str = Field(description="事件名称")+ timeInfo: str = Field(description="时间信息,统一格式为年-月-日(如 2023-06-15)")+ location: str = Field(description="事件地点", default="")+ description: str = Field(description="事件描述", default="")_PROMPT = """## 角色与任务-你是一位专业的传记年表专家,请从文本中提取人物、地点、组织等实体以及生活事件,构建生平时序图。+你是一位专业的生活事件提取专家,请从文本中提取人物及其生活事件。## 核心概念定义-- **节点 (Node)**:本模板中的"节点"指生活实体,包括人物、地点、组织、物品、概念等类型,用于表示生平时序中的实体。-- **边 (Edge)**:本模板中的"边"指生活事件,连接多个实体,记录出生、教育、工作、成就等人生经历的二元关系。-- **时间**:本模板中的"时间"指事件发生的时间信息,用于按时间顺序排列生活事件,支持相对时间解析。+- **节点 (Node)**:本模板中的"节点"指人物,包括人物姓名和简要描述。+- **边 (Edge)**:本模板中的"边"指生活事件,包括事件类型、名称、时间、地点和描述。## 提取规则### 节点提取规则-1. 提取所有相关实体:人物、地点、组织、物品、概念等-2. 为每个实体指定类型:人物、地点、组织、物品、概念、其他-3. 为每个实体添加简要描述+1. 提取所有人物,包括其姓名和简要描述+2. 保持人物姓名与原文一致### 事件提取规则-1. 仅从提取的实体中创建事件边-2. 事件类型包括:- - 出生:出生事件- - 逝世:逝世事件- - 教育:学习、受教育事件- - 工作:工作、职业事件- - 成就:取得成就、获得荣誉事件- - 交往:人际交往、社会活动事件- - 旅行:旅行、迁居事件- - 其他:其他事件-3. 事件日期为可选提取项,仅在文本中明确提及时才提取-4. 日期格式:年-月-日(如 429-01-01)或年份(如 429)-5. 每条边必须连接已提取的节点--### 中文时间计算规则-当前观察日期:{observation_time}--1. **相对时间解析**:必须根据观察日期解析相对时间表达- - "去年" → 计算为 {observation_time} 前一年- - "今年" → {observation_time} 所属年份- - "明年" → {observation_time} 后一年- - "昨天" → {observation_time} 前一天- - "今天" → {observation_time}- - "明天" → {observation_time} 后一天- - "上个月" → {observation_time} 前一个月的第一天- - "这个月" → {observation_time} 所属月份的第一天- - "下个月" → {observation_time} 后一个月的第一天- - "十年前" → {observation_time} 前十年- - "五年后" → {observation_time} 后五年- - "年初" → 当年的 1月1日- - "年末" → 当年的 12月31日- - "世纪初" → 该世纪的第 1 年(如 2000 年)- - "世纪末" → 该世纪的最后 1 年(如 2099 年)- - "朝代" → 保留朝代名称(如"唐朝"、"宋代"),无需转换--2. **明确日期**:保持原文中的明确日期格式不变- - 年份(如 429 年、2023 年)→ 429、2023- - 年-月(如 429年3月)→ 429-03- - 年-月-日(如 429年3月14日)→ 429-03-14- - 中文数字日期(如"民国三十八年")→ 转换为公元纪年--3. **缺失时间**:如果文本中没有时间信息,将 eventDate 留空(None),不要编造日期--### 约束条件-- 不要创建未在文本中提及的实体或事件-- 保持客观准确,不添加文本中没有的信息+1. 提取所有生活事件,包括事件类型、名称、时间、地点和描述+2. 每条事件必须连接相关的人物+3. 时间信息必须统一转换为「年-月-日」格式(如 2023-06-15)++### 时间解析规则+当前观察日期: {observation_time}++1. 相对时间解析(基于观察日期):+ - "去年" → {observation_time} 的前一年,格式化为 YYYY-01-01+ - "上月" → {observation_time} 的前一个月,格式化为 YYYY-MM-01### 源文本:"""_NODE_PROMPT = """## 角色与任务-你是一位专业的实体识别专家,请从文本中提取所有相关实体作为节点。+你是一位专业的人物识别专家,请从文本中提取所有人物作为节点。## 核心概念定义-- **节点 (Node)**:本模板中的"节点"指生活实体,包括人物、地点、组织、物品、概念等类型,用于表示生平时序中的实体。+- **节点 (Node)**:本模板中的"节点"指人物,包括人物姓名和简要描述。## 提取规则-1. 提取所有相关实体:人物、地点、组织、物品、概念等-2. 为每个实体指定类型:人物、地点、组织、物品、概念、其他-3. 为每个实体添加简要描述+1. 提取所有人物,包括其姓名和简要描述+2. 保持人物姓名与原文一致### 源文本:"""_EDGE_PROMPT = """## 角色与任务-你是一位专业的生活事件提取专家,请从给定实体列表中提取生活事件。+你是一位专业的生活事件提取专家,请从给定人物列表中提取生活事件。## 核心概念定义-- **节点 (Node)**:本模板中的"节点"指生活实体,作为生活事件的参与者。-- **边 (Edge)**:本模板中的"边"指生活事件,连接多个实体,记录出生、教育、工作、成就等人生经历的二元关系。-- **时间**:本模板中的"时间"指事件发生的时间信息,用于按时间顺序排列生活事件,支持相对时间解析。+- **节点 (Node)**:本模板中的"节点"指人物,作为生活事件的参与者。+- **边 (Edge)**:本模板中的"边"指生活事件,包括事件类型、名称、时间、地点和描述。## 提取规则-### 事件类型说明-- 出生:出生事件-- 逝世:逝世事件-- 教育:学习、受教育事件-- 工作:工作、职业事件-- 成就:取得成就、获得荣誉事件-- 交往:人际交往、社会活动事件-- 旅行:旅行、迁居事件-- 其他:其他事件--### 中文时间计算规则-当前观察日期:{observation_time}--1. **相对时间解析**:必须根据观察日期解析相对时间表达- - "去年" → 计算为 {observation_time} 前一年- - "今年" → {observation_time} 所属年份- - "明年" → {observation_time} 后一年- - "昨天" → {observation_time} 前一天- - "今天" → {observation_time}- - "明天" → {observation_time} 后一天- - "上个月" → {observation_time} 前一个月的第一天- - "这个月" → {observation_time} 所属月份的第一天- - "下个月" → {observation_time} 后一个月的第一天- - "十年前" → {observation_time} 前十年- - "五年后" → {observation_time} 后五年- - "年初" → 当年的 1月1日- - "年末" → 当年的 12月31日- - "世纪初" → 该世纪的第 1 年(如 2000 年)- - "世纪末" → 该世纪的最后 1 年(如 2099 年)- - "朝代" → 保留朝代名称(如"唐朝"、"宋代"),无需转换--2. **明确日期**:保持原文中的明确日期格式不变- - 年份(如 429 年、2023 年)→ 429、2023- - 年-月(如 429年3月)→ 429-03- - 年-月-日(如 429年3月14日)→ 429-03-14- - 中文数字日期(如"民国三十八年")→ 转换为公元纪年--3. **缺失时间**:如果文本中没有时间信息,将 eventDate 留空(None),不要编造日期--### 日期格式要求-- 所有日期信息统一转换为「年-月-日」格式(如 429-01-01)或年份(如 429)-- 时间信息为可选提取项,仅在文本中明确提及时才提取--### 约束条件-1. 仅从下方已知实体列表中提取事件-2. 不要创建未列出的实体-3. 时间信息为可选,仅在文本中明确提及时才提取+1. 仅从下方已知人物列表中提取事件+2. 每条事件必须连接相关的人物+3. 时间信息必须统一转换为「年-月-日」格式(如 2023-06-15)++### 时间解析规则+当前观察日期: {observation_time}++1. 相对时间解析(基于观察日期):+ - "去年" → {observation_time} 的前一年,格式化为 YYYY-01-01+ - "上月" → {observation_time} 的前一个月,格式化为 YYYY-MM-01"""-class LifeEventTimeline(AutoTemporalGraph[LifeEntity, LifeEvent]):+class LifeEventTimeline(AutoTemporalGraph[PersonEntity, LifeEvent]):"""- 适用文档: 人物传记、年表、回忆录、自传-+ 适用文档: 人物传记、历史人物资料、个人履历+功能介绍:- 提取带时间戳的事件,并按时间顺序排列。适用于人物传记、年表、回忆录等。-+ 提取人物的生活事件时间线,如出生、教育、工作、婚姻、死亡等重要事件。+Example:>>> template = LifeEventTimeline(llm_client=llm, embedder=embedder)- >>> template.feed_text("祖冲之(429年-500年),字文远,范阳遒县人...")+ >>> template.feed_text("...")>>> template.show()"""@@ -183,32 +102,36 @@ class LifeEventTimeline(AutoTemporalGraph[LifeEntity, LifeEvent]):llm_client: BaseChatModel,embedder: Embeddings,*,- observation_time: str | None = None,extraction_mode: str = "two_stage",+ observation_time: str | None = None,max_workers: int = 10,verbose: bool = False,**kwargs: Any,):"""- 初始化生平时序图模板。+ 初始化生活事件时间线模板。Args:llm_client: LLM 客户端,用于知识提取embedder: 嵌入模型,用于语义检索- observation_time: 观察日期,用于解析相对时间表达,默认为今天extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ observation_time: 观察时间,用于解析相对时间表达,+ 如未指定则使用当前日期max_workers: 最大工作线程数,默认为 10verbose: 是否输出详细日志,默认为 False**kwargs: 其他技术参数,传递给基类"""+ if observation_time is None:+ observation_time = datetime.now().strftime("%Y-%m-%d")+super().__init__(- node_schema=LifeEntity,+ node_schema=PersonEntity,edge_schema=LifeEvent,node_key_extractor=lambda x: x.name,- edge_key_extractor=lambda x: f"{x.source}|{x.eventType}|{x.target}",- time_in_edge_extractor=lambda x: x.eventDate,- nodes_in_edge_extractor=lambda x: (x.source, x.target),+ edge_key_extractor=lambda x: f"{x.source}|{x.eventType}|{x.eventName}",+ time_in_edge_extractor=lambda x: x.timeInfo or "",+ nodes_in_edge_extractor=lambda x: (x.source, x.source),llm_client=llm_client,embedder=embedder,observation_time=observation_time,@@ -228,25 +151,21 @@ class LifeEventTimeline(AutoTemporalGraph[LifeEntity, LifeEvent]):top_k_for_chat: int = 3,):"""- 展示生平时序图。+ 展示生活事件时间线。Args:top_k_for_search: 语义检索返回的节点/边数量,默认为 3top_k_for_chat: 问答使用的节点/边数量,默认为 3"""- def node_label_extractor(node: LifeEntity) -> str:- return f"{node.name} ({node.type})"+ def node_label_extractor(node: PersonEntity) -> str:+ return node.namedef edge_label_extractor(edge: LifeEvent) -> str:- if edge.eventDate:- return f"{edge.eventType} ({edge.eventDate})"- return edge.eventType+ return f"{edge.eventType}: {edge.eventName}"super().show(node_label_extractor=node_label_extractor,edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,- )+ top_k_for_search=top_k_for_search,+ top_k_for_chat=top_k_for_chat,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/__init__.py b/hyperextract/templates/zh/medicine/__init__.pyindex 423c4b3..a8c2936 100644--- a/hyperextract/templates/zh/medicine/__init__.py+++ b/hyperextract/templates/zh/medicine/__init__.py@@ -1,9 +1,42 @@-from .drug_interaction_graph import DrugInteractionGraph-from .clinical_treatment_timeline import ClinicalTreatmentTimeline-from .diagnostic_criteria_set import DiagnosticCriteriaSet+"""医学领域知识模板"""++from hyperextract.templates.zh.medicine.pathology_hypergraph import PathologyHypergraph+from hyperextract.templates.zh.medicine.medical_concept_net import MedicalConceptNet+from hyperextract.templates.zh.medicine.pharmacology_graph import PharmacologyGraph+from hyperextract.templates.zh.medicine.anatomy_hierarchy import AnatomyHierarchy+from hyperextract.templates.zh.medicine.symptom_differential import SymptomDifferential+from hyperextract.templates.zh.medicine.treatment_regimen_map import TreatmentRegimenMap+from hyperextract.templates.zh.medicine.clinical_pathway import ClinicalPathway+from hyperextract.templates.zh.medicine.level_of_evidence import LevelOfEvidence+from hyperextract.templates.zh.medicine.surgical_event_graph import SurgicalEventGraph+from hyperextract.templates.zh.medicine.hospital_course_timeline import HospitalCourseTimeline+from hyperextract.templates.zh.medicine.discharge_instruction import DischargeInstruction+from hyperextract.templates.zh.medicine.tumor_staging_item import TumorStagingItem+from hyperextract.templates.zh.medicine.microscopic_feature_set import MicroscopicFeatureSet+from hyperextract.templates.zh.medicine.complex_interaction_net import ComplexInteractionNet+from hyperextract.templates.zh.medicine.contraindication_list import ContraindicationList+from hyperextract.templates.zh.medicine.adverse_reaction_stats import AdverseReactionStats__all__ = [- "DrugInteractionGraph",- "ClinicalTreatmentTimeline",- "DiagnosticCriteriaSet",-]+ # 医学教科书与专著+ "PathologyHypergraph",+ "MedicalConceptNet",+ "PharmacologyGraph",+ "AnatomyHierarchy",+ "SymptomDifferential",+ # 临床诊疗指南+ "TreatmentRegimenMap",+ "ClinicalPathway",+ "LevelOfEvidence",+ # 出院小结+ "SurgicalEventGraph",+ "HospitalCourseTimeline",+ "DischargeInstruction",+ # 病理报告+ "TumorStagingItem",+ "MicroscopicFeatureSet",+ # 药品说明书+ "ComplexInteractionNet",+ "ContraindicationList",+ "AdverseReactionStats",+]\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/adverse_reaction_stats.py b/hyperextract/templates/zh/medicine/adverse_reaction_stats.pynew file mode 100644index 0000000..964cc43--- /dev/null+++ b/hyperextract/templates/zh/medicine/adverse_reaction_stats.py@@ -0,0 +1,102 @@+"""不良反应统计 - 提取各系统的不良反应表现及其发生率描述。++适用于药品说明书中关于不良反应的内容。+"""++from typing import Any+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoList+++class AdverseReactionItem(BaseModel):+ """不良反应条目"""+ system: str = Field(description="系统名称,如胃肠道、全身、皮肤等")+ reaction: str = Field(description="不良反应表现")+ incidence: str = Field(description="发生率")+ details: str = Field(description="详细描述", default="")+++_PROMPT = """## 角色与任务+你是一位专业的临床药师,请从文本中提取各系统的不良反应表现及其发生率描述,构建不良反应统计。++## 核心概念定义+- **条目 (Item)**:本模板中的"条目"指不良反应条目,包含系统名称、不良反应表现、发生率和详细描述的结构化信息。++## 提取规则+1. 提取所有不良反应,包括系统名称、不良反应表现和发生率+2. 为每个不良反应添加详细描述(如果文本中提供)+3. 保持不良反应表现与原文一致++### 约束条件+- 只提取文本中明确提及的不良反应和发生率+- 保持客观准确,不添加文本中没有的信息++### 源文本:+"""+++class AdverseReactionStats(AutoList[AdverseReactionItem]):+ """+ 适用文档: 药品说明书、药物安全性监测报告++ 功能介绍:+ 提取各系统的不良反应表现及其发生率描述,适用于药物警戒、安全性评价。++ Example:+ >>> template = AdverseReactionStats(llm_client=llm, embedder=embedder)+ >>> template.feed_text("胃肠道不良反应:恶心(5.2%)、呕吐(2.6%)...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化不良反应统计模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ item_schema=AdverseReactionItem,+ llm_client=llm_client,+ embedder=embedder,+ prompt=_PROMPT,+ max_workers=max_workers,+ verbose=verbose,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示不良反应统计。++ Args:+ top_k_for_search: 语义检索返回的条目数量,默认为 3+ top_k_for_chat: 问答使用的条目数量,默认为 3+ """+ def item_label_extractor(item: AdverseReactionItem) -> str:+ return f"{item.system}: {item.reaction} ({item.incidence})"++ super().show(+ item_label_extractor=item_label_extractor,+ top_k_items_for_search=top_k_for_search,+ top_k_items_for_chat=top_k_for_chat,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/anatomy_hierarchy.py b/hyperextract/templates/zh/medicine/anatomy_hierarchy.pynew file mode 100644index 0000000..6ff950b--- /dev/null+++ b/hyperextract/templates/zh/medicine/anatomy_hierarchy.py@@ -0,0 +1,165 @@+"""解剖层级树 - 构建解剖位置的包含 (Part-Of) 和毗邻 (Connected-To) 关系。++适用于医学教科书与专著中关于解剖学的内容。+"""++from typing import Any+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoGraph+++class AnatomyEntity(BaseModel):+ """解剖实体节点"""+ name: str = Field(description="解剖结构名称,如器官、组织、血管等")+ category: str = Field(description="解剖类型:器官、组织、血管、神经、骨骼等")+ description: str = Field(description="简要描述", default="")+++class AnatomyRelation(BaseModel):+ """解剖关系边"""+ source: str = Field(description="源解剖结构")+ target: str = Field(description="目标解剖结构")+ relationType: str = Field(description="关系类型:包含(Part-Of)、毗邻(Connected-To)、分支、供应等")+ details: str = Field(description="详细描述", default="")+++_PROMPT = """## 角色与任务+你是一位专业的解剖学家,请从文本中提取解剖结构及其关系,构建解剖层级树。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指解剖实体,包括器官、组织、血管、神经、骨骼等类型,用于表示解剖学中的基本结构。+- **边 (Edge)**:本模板中的"边"指解剖结构之间的关系,包括包含(Part-Of)、毗邻(Connected-To)、分支、供应等关系类型。++## 提取规则+### 节点提取规则+1. 提取所有解剖结构:器官名称、组织、血管、神经、骨骼等+2. 为每个解剖结构指定类型:器官、组织、血管、神经、骨骼等+3. 为每个解剖结构添加简要描述++### 关系提取规则+1. 仅从提取的解剖结构中创建关系边+2. 关系类型包括:包含(Part-Of)、毗邻(Connected-To)、分支、供应等+3. 为每个关系添加详细描述++### 约束条件+- 每条边必须连接已提取的节点+- 不要创建未在文本中提及的解剖结构或关系+- 保持客观准确,不添加文本中没有的信息++### 源文本:+"""++_NODE_PROMPT = """## 角色与任务+你是一位专业的解剖结构识别专家,请从文本中提取所有解剖结构作为节点。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指解剖实体,包括器官、组织、血管、神经、骨骼等类型,用于表示解剖学中的基本结构。++## 提取规则+1. 提取所有解剖结构:器官名称、组织、血管、神经、骨骼等+2. 为每个解剖结构指定类型:器官、组织、血管、神经、骨骼等+3. 为每个解剖结构添加简要描述++### 源文本:+"""++_EDGE_PROMPT = """## 角色与任务+你是一位专业的解剖关系提取专家,请从给定解剖结构列表中提取它们之间的关系。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指解剖实体,作为解剖关系的参与者。+- **边 (Edge)**:本模板中的"边"指解剖结构之间的关系,包括包含(Part-Of)、毗邻(Connected-To)、分支、供应等关系类型。++## 提取规则+1. 仅从下方已知解剖结构列表中提取边+2. 关系类型包括:包含(Part-Of)、毗邻(Connected-To)、分支、供应等+3. 为每个关系添加详细描述++### 约束条件+1. 不要创建未列出的解剖结构+2. 每条边必须连接已提取的节点++"""+++class AnatomyHierarchy(AutoGraph[AnatomyEntity, AnatomyRelation]):+ """+ 适用文档: 医学教科书、医学专著、解剖学图谱++ 功能介绍:+ 构建解剖位置的包含 (Part-Of) 和毗邻 (Connected-To) 关系,适用于解剖学图谱、手术导航基础。++ Example:+ >>> template = AnatomyHierarchy(llm_client=llm, embedder=embedder)+ >>> template.feed_text("心脏位于胸腔内,分为左心房、左心室、右心房、右心室...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化解剖层级树模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ node_schema=AnatomyEntity,+ edge_schema=AnatomyRelation,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: f"{x.source}|{x.relationType}|{x.target}",+ nodes_in_edge_extractor=lambda x: (x.source, x.target),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示解剖层级树。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def node_label_extractor(node: AnatomyEntity) -> str:+ return f"{node.name} ({node.category})"++ def edge_label_extractor(edge: AnatomyRelation) -> str:+ return edge.relationType++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_for_search,+ top_k_edges_for_search=top_k_for_search,+ top_k_nodes_for_chat=top_k_for_chat,+ top_k_edges_for_chat=top_k_for_chat,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/clinical_pathway.py b/hyperextract/templates/zh/medicine/clinical_pathway.pynew file mode 100644index 0000000..081b5e7--- /dev/null+++ b/hyperextract/templates/zh/medicine/clinical_pathway.py@@ -0,0 +1,165 @@+"""临床路径图 - 提取"If 症状A Then 检查B Else 治疗C"的决策树结构。++适用于临床诊疗指南中关于决策路径的内容。+"""++from typing import Any+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoGraph+++class ClinicalNode(BaseModel):+ """临床节点"""+ name: str = Field(description="节点名称,如症状、检查、治疗等")+ category: str = Field(description="节点类型:症状、检查、治疗、诊断、决策点等")+ description: str = Field(description="简要描述", default="")+++class ClinicalEdge(BaseModel):+ """临床路径边"""+ source: str = Field(description="源节点")+ target: str = Field(description="目标节点")+ condition: str = Field(description="条件描述,如If 症状A Then")+ details: str = Field(description="详细描述", default="")+++_PROMPT = """## 角色与任务+你是一位专业的临床医生,请从文本中提取"If 症状A Then 检查B Else 治疗C"的决策树结构,构建临床路径图。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指临床节点,包括症状、检查、治疗、诊断、决策点等类型,用于表示临床路径中的基本要素。+- **边 (Edge)**:本模板中的"边"指临床路径边,连接节点并包含条件描述,表达决策逻辑。++## 提取规则+### 节点提取规则+1. 提取所有临床相关节点:症状、检查项目、治疗方法、诊断结果、决策点等+2. 为每个节点指定类型:症状、检查、治疗、诊断、决策点等+3. 为每个节点添加简要描述++### 边提取规则+1. 仅从提取的节点中创建边+2. 边应包含条件描述,如"If 症状A Then"、"Else"等+3. 为每个边添加详细描述,说明具体的决策逻辑++### 约束条件+- 每条边必须连接已提取的节点+- 不要创建未在文本中提及的节点或边+- 保持客观准确,不添加文本中没有的信息++### 源文本:+"""++_NODE_PROMPT = """## 角色与任务+你是一位专业的临床节点识别专家,请从文本中提取所有临床相关节点。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指临床节点,包括症状、检查、治疗、诊断、决策点等类型,用于表示临床路径中的基本要素。++## 提取规则+1. 提取所有临床相关节点:症状、检查项目、治疗方法、诊断结果、决策点等+2. 为每个节点指定类型:症状、检查、治疗、诊断、决策点等+3. 为每个节点添加简要描述++### 源文本:+"""++_EDGE_PROMPT = """## 角色与任务+你是一位专业的临床路径提取专家,请从给定节点列表中提取决策树结构,构建临床路径边。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指临床节点,作为临床路径的组成部分。+- **边 (Edge)**:本模板中的"边"指临床路径边,连接节点并包含条件描述,表达决策逻辑。++## 提取规则+1. 仅从下方已知节点列表中提取边+2. 边应包含条件描述,如"If 症状A Then"、"Else"等+3. 为每个边添加详细描述,说明具体的决策逻辑++### 约束条件+1. 不要创建未列出的节点+2. 每条边必须连接已提取的节点++"""+++class ClinicalPathway(AutoGraph[ClinicalNode, ClinicalEdge]):+ """+ 适用文档: 临床诊疗指南、决策路径手册++ 功能介绍:+ 提取"If 症状A Then 检查B Else 治疗C"的决策树结构,适用于临床路径管理、诊疗规范化。++ Example:+ >>> template = ClinicalPathway(llm_client=llm, embedder=embedder)+ >>> template.feed_text("如果患者出现胸痛,应进行心电图检查;否则,给予对症治疗...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化临床路径图模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ node_schema=ClinicalNode,+ edge_schema=ClinicalEdge,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: f"{x.source}|{x.condition}|{x.target}",+ nodes_in_edge_extractor=lambda x: (x.source, x.target),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示临床路径图。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def node_label_extractor(node: ClinicalNode) -> str:+ return f"{node.name} ({node.category})"++ def edge_label_extractor(edge: ClinicalEdge) -> str:+ return edge.condition++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_for_search,+ top_k_edges_for_search=top_k_for_search,+ top_k_nodes_for_chat=top_k_for_chat,+ top_k_edges_for_chat=top_k_for_chat,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/clinical_treatment_timeline.py b/hyperextract/templates/zh/medicine/clinical_treatment_timeline.pydeleted file mode 100644index 0e9bb5a..0000000--- a/hyperextract/templates/zh/medicine/clinical_treatment_timeline.py+++ /dev/null@@ -1,142 +0,0 @@-from typing import List, Optional, Any, Tuple-from pydantic import BaseModel, Field-from langchain_core.language_models.chat_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoTemporalGraph--# ==============================================================================-# 1. Schema 定义 (Schema Definitions)-# ==============================================================================--class MedicalEvent(BaseModel):- """临床诊疗路径中的单个医疗事件。"""- event_name: str = Field(description="事件名称或诊断摘要(如‘入院诊断’、‘心电图检查’、‘脾切除术’)。")- event_type: str = Field(description="事件类型(如:主诉、体格检查、实验室检查、诊断、用药、手术、出院)。")- finding: Optional[str] = Field(description="该事件的具体发现、结果或处理详情(如‘血红蛋白 90g/L’、‘手术顺利’)。")--class ClinicalProgression(BaseModel):- """医疗事件随时间的发展过程。"""- source: str = Field(description="前序医疗事件名称。")- target: str = Field(description="后续医疗事件名称。")- time: str = Field(description="医疗事件发生的具体时间或相对于入院时间的偏移。你必须将模糊的相对时间(如‘数小时后’)根据上下文解析为绝对时间(2024-01-01 10:00)或标准偏移量(如‘术后6小时’)。")- status_change: str = Field(description="病情变化或治疗反应(如‘好转’、‘病情恶化’、‘维持稳定’)。")--# ==============================================================================-# 2. 提示词 (Prompts)-# ==============================================================================--_PROMPT = (- "你是一位专业的临床文档分析专家。你的任务是从病历、病程记录或临床路径文档中提取诊疗演变过程。\n\n"- "分析指南:\n"- "1. **医疗事实提取**:记录每一项重要的医疗活动(检查、用药、手术)及其核心结果。\n"- "2. **时间逻辑链**:严格按照病程顺序建立连接。利用文本中的时间标记(如‘术前半小时’、‘次晨’)来链接事件。\n"- "3. **动态追踪**:侧重描述治疗干预后患者状态的演变(status_change)。\n"-)--_NODE_PROMPT = (- "请提取病历中提及的所有关键诊疗节点。包括患者的主诉、关键体征检查、主要化验结果、诊断结论、用药操作及手术项目。"-)--_EDGE_PROMPT = (- "在诊疗节点之间建立时序联系。请根据病历的时间描述,指出不同医疗事件发生的先后关系与时间间隔,并总结病情随干预产生的动态变化。"-)--# ==============================================================================-# 3. 模板类 (Template Class)-# ==============================================================================--class ClinicalTreatmentTimeline(AutoTemporalGraph[MedicalEvent, ClinicalProgression]):- """- 适用于:[电子病历 (EMR), 出院小结, 病例报告, 护理记录]-- 用于还原患者临床诊疗全生命周期的时序路径模板。-- 该模板利用 AutoTemporalGraph 的时序特性,专注于呈现“诊断-干预-反馈”的完整医学逻辑,适合对复杂病例进行回顾性分析。-- 示例:- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings- >>> llm = ChatOpenAI(model="gpt-4o")- >>> embedder = OpenAIEmbeddings()- >>> # 初始化模板- >>> pathway = ClinicalTreatmentTimeline(llm_client=llm, embedder=embedder)- >>> # 输入病程记录- >>> text = "2月10日患者入院。2月11日急行阑尾切除术。术后恢复良好,于2月15日出院。"- >>> pathway.feed_text(text)- >>> pathway.show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- observation_time: Optional[str] = None,- extraction_mode: str = "two_stage",- chunk_size: int = 2048,- chunk_overlap: int = 256,- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any- ):- """- 初始化 ClinicalTreatmentTimeline 模板。-- Args:- llm_client: 用于提取的语言模型客户端。- embedder: 用于实体去重和索引的嵌入模型。- observation_time: 入院日期或当前日期。- extraction_mode: 默认使用 two_stage 以保证复杂病史的时序解析。- chunk_size: 文本块大小。- chunk_overlap: 文本块重叠大小。- max_workers: 最大并行工作线程数。- verbose: 是否开启详细日志。- **kwargs: 其他传给 AutoTemporalGraph 的参数。- """- super().__init__(- node_schema=MedicalEvent,- edge_schema=ClinicalProgression,- node_key_extractor=lambda x: x.event_name.strip(),- edge_key_extractor=lambda x: f"{x.source}>>{x.target}",- time_in_edge_extractor=lambda x: x.time,- nodes_in_edge_extractor=lambda x: (x.source, x.target),- llm_client=llm_client,- embedder=embedder,- observation_time=observation_time,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- extraction_mode=extraction_mode,- chunk_size=chunk_size,- chunk_overlap=chunk_overlap,- max_workers=max_workers,- verbose=verbose,- **kwargs- )-- def show(- self,- *,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,- ) -> None:- """- 可视化临床诊疗全过程。-- Args:- top_k_for_search: 搜索时找回的相关节点/边数量。- top_k_for_chat: 聊天时找回的相关节点/边数量。- """- def node_label_extractor(node: MedicalEvent) -> str:- return f"[{node.event_type}] {node.event_name}"-- def edge_label_extractor(edge: ClinicalProgression) -> str:- return f"({edge.time}) {edge.status_change}"-- super().show(- node_label_extractor=node_label_extractor,- edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,- )diff --git a/hyperextract/templates/zh/medicine/complex_interaction_net.py b/hyperextract/templates/zh/medicine/complex_interaction_net.pynew file mode 100644index 0000000..892a849--- /dev/null+++ b/hyperextract/templates/zh/medicine/complex_interaction_net.py@@ -0,0 +1,167 @@+"""条件性相互作用网 - 建模"药A+药B+特定体质 -> 不良反应"的高阶依赖。++适用于药品说明书中关于药物相互作用的内容。+"""++from typing import Any, List+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoHypergraph+++class InteractionEntity(BaseModel):+ """相互作用实体节点"""+ name: str = Field(description="实体名称,如药物、体质、不良反应等")+ category: str = Field(description="实体类型:药物、体质、不良反应、其他等")+ description: str = Field(description="简要描述", default="")+++class InteractionHyperedge(BaseModel):+ """相互作用超边"""+ name: str = Field(description="超边名称,如药物相互作用")+ nodes: List[str] = Field(description="参与超边的节点列表")+ interactionType: str = Field(description="相互作用类型:增强、减弱、不良反应等")+ details: str = Field(description="详细描述,如具体的相互作用机制")+++_PROMPT = """## 角色与任务+你是一位专业的临床药师,请从文本中提取药物相互作用信息,构建条件性相互作用网。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指相互作用实体,包括药物、体质、不良反应等类型,用于表示药物相互作用中的基本要素。+- **边 (Edge)**:本模板中的"边"指相互作用超边,连接多个节点,表达完整的药物相互作用。++## 提取规则+### 节点提取规则+1. 提取所有相互作用相关实体:药物名称、体质类型、不良反应等+2. 为每个实体指定类型:药物、体质、不良反应、其他等+3. 为每个实体添加简要描述++### 超边提取规则+1. 仅从提取的实体中创建超边+2. 超边应表示完整的药物相互作用,包含药物、体质、不良反应等多个要素+3. 为每个超边指定相互作用类型:增强、减弱、不良反应等+4. 为每个超边添加详细描述,说明具体的相互作用机制++### 约束条件+- 每条超边必须连接多个已提取的节点+- 不要创建未在文本中提及的实体或关系+- 保持客观准确,不添加文本中没有的信息++### 源文本:+"""++_NODE_PROMPT = """## 角色与任务+你是一位专业的临床药师,请从文本中提取与药物相互作用相关的所有关键实体作为节点。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指相互作用实体,包括药物、体质、不良反应等类型,用于表示药物相互作用中的基本要素。++## 提取规则+1. 提取所有相互作用相关实体:药物名称、体质类型、不良反应等+2. 为每个实体指定类型:药物、体质、不良反应、其他等+3. 为每个实体添加简要描述++### 源文本:+"""++_EDGE_PROMPT = """## 角色与任务+你是一位专业的临床药师,请从给定实体列表中提取药物相互作用,构建条件性相互作用网。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指相互作用实体,作为药物相互作用的参与者。+- **边 (Edge)**:本模板中的"边"指相互作用超边,连接多个节点,表达完整的药物相互作用。++## 提取规则+1. 仅从下方已知实体列表中创建超边+2. 超边应表示完整的药物相互作用,包含药物、体质、不良反应等多个要素+3. 为每个超边指定相互作用类型:增强、减弱、不良反应等+4. 为每个超边添加详细描述,说明具体的相互作用机制++### 约束条件+1. 不要创建未列出的实体+2. 每条超边必须连接多个节点++"""+++class ComplexInteractionNet(AutoHypergraph[InteractionEntity, InteractionHyperedge]):+ """+ 适用文档: 药品说明书、药物相互作用指南++ 功能介绍:+ 建模"药A+药B+特定体质 -> 不良反应"的高阶依赖,适用于合理用药系统 (高级版)。++ Example:+ >>> template = ComplexInteractionNet(llm_client=llm, embedder=embedder)+ >>> template.feed_text("二甲双胍与磺酰脲类合用可增加低血糖风险...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化条件性相互作用网模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ node_schema=InteractionEntity,+ edge_schema=InteractionHyperedge,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: x.name,+ nodes_in_edge_extractor=lambda x: x.nodes,+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示条件性相互作用网。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def node_label_extractor(node: InteractionEntity) -> str:+ return f"{node.name} ({node.category})"++ def edge_label_extractor(edge: InteractionHyperedge) -> str:+ return f"{edge.name}: {edge.interactionType}"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_for_search,+ top_k_edges_for_search=top_k_for_search,+ top_k_nodes_for_chat=top_k_for_chat,+ top_k_edges_for_chat=top_k_for_chat,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/contraindication_list.py b/hyperextract/templates/zh/medicine/contraindication_list.pynew file mode 100644index 0000000..cab3d68--- /dev/null+++ b/hyperextract/templates/zh/medicine/contraindication_list.py@@ -0,0 +1,102 @@+"""禁忌症清单 - 提取绝对禁忌(如孕妇、严重肾衰竭等)的明确列表。++适用于药品说明书中关于禁忌症的内容。+"""++from typing import Any+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoList+++class ContraindicationItem(BaseModel):+ """禁忌症条目"""+ contraindication: str = Field(description="禁忌症描述")+ contraindicationType: str = Field(description="禁忌症类型:绝对禁忌、相对禁忌等")+ details: str = Field(description="详细描述", default="")+++_PROMPT = """## 角色与任务+你是一位专业的临床药师,请从文本中提取绝对禁忌(如孕妇、严重肾衰竭等)的明确列表,构建禁忌症清单。++## 核心概念定义+- **条目 (Item)**:本模板中的"条目"指禁忌症条目,包含禁忌症描述、禁忌症类型和详细描述的结构化信息。++## 提取规则+1. 提取所有禁忌症,包括绝对禁忌和相对禁忌+2. 为每个禁忌症指定类型:绝对禁忌、相对禁忌等+3. 为每个禁忌症添加详细描述(如果文本中提供)+4. 保持禁忌症描述与原文一致++### 约束条件+- 只提取文本中明确提及的禁忌症+- 保持客观准确,不添加文本中没有的信息++### 源文本:+"""+++class ContraindicationList(AutoList[ContraindicationItem]):+ """+ 适用文档: 药品说明书、临床用药指南++ 功能介绍:+ 提取绝对禁忌(如孕妇、严重肾衰竭等)的明确列表,适用于处方拦截、用药安全监测。++ Example:+ >>> template = ContraindicationList(llm_client=llm, embedder=embedder)+ >>> template.feed_text("绝对禁忌症:对二甲双胍及其他成分过敏者...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化禁忌症清单模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ item_schema=ContraindicationItem,+ llm_client=llm_client,+ embedder=embedder,+ prompt=_PROMPT,+ max_workers=max_workers,+ verbose=verbose,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示禁忌症清单。++ Args:+ top_k_for_search: 语义检索返回的条目数量,默认为 3+ top_k_for_chat: 问答使用的条目数量,默认为 3+ """+ def item_label_extractor(item: ContraindicationItem) -> str:+ return f"{item.contraindication} ({item.contraindicationType})"++ super().show(+ item_label_extractor=item_label_extractor,+ top_k_items_for_search=top_k_for_search,+ top_k_items_for_chat=top_k_for_chat,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/diagnostic_criteria_set.py b/hyperextract/templates/zh/medicine/diagnostic_criteria_set.pydeleted file mode 100644index 76e363b..0000000--- a/hyperextract/templates/zh/medicine/diagnostic_criteria_set.py+++ /dev/null@@ -1,111 +0,0 @@-from typing import List, Optional, Any, Callable-from pydantic import BaseModel, Field-from langchain_core.language_models.chat_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoSet--# ==============================================================================-# 1. Schema 定义 (Schema Definitions)-# ==============================================================================--class DiagnosticCriteria(BaseModel):- """疾病的诊断标准与临床分类。"""- disease_name: str = Field(description="标准化疾病名称(如‘2型糖尿病’、‘急性心肌梗死’)。")- major_criteria: List[str] = Field(description="主要诊断指标(Major Criteria)或必备条件。")- minor_criteria: List[str] = Field(description="次要诊断指标(Minor Criteria)或辅助条件。")- exclusion_criteria: List[str] = Field(description="排除标准(即出现何种情况可排除该疾病)。")- biomarkers: List[str] = Field(description="相关的关键生物标志物或实验室检查项(如‘HbA1c > 6.5%’)。")- source_guideline: str = Field(description="该标准的来源,如‘ADA 2024 指南’、‘专家共识’。")--# ==============================================================================-# 2. 提示词 (Prompts)-# ==============================================================================--_PROMPT = (- "你是一位专业的临床指南解读专家。你的任务是从医学文献和指南中提取特定疾病的结构化诊断标准。\n\n"- "提取原则:\n"- "1. **疾病名标准化**:确保同一个疾病的所有信息被聚合到其标准的医学名称下。\n"- "2. **严谨区分**:精确区分哪些是‘主标准’,哪些是‘次标准’或‘排除标准’。\n"- "3. **信息累加**:如果你从多篇文献中提取了同一个疾病的诊断标准,请合并这些信息,并在 source_guideline 中记录所有来源。\n"-)--# ==============================================================================-# 3. 模板类 (Template Class)-# ==============================================================================--class DiagnosticCriteriaSet(AutoSet[DiagnosticCriteria]):- """- 适用于:[临床实践指南, 专家共识, 医学教材]-- 用于从海量医学指南中聚合与维护疾病诊断标准的库模板。-- 该模板利用 AutoSet 的键值累加特性,能够将不同年份、不同组织发布的关于同一疾病的诊断标准、标志物要求自动合并,形成最全面的诊疗参考。-- 示例:- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings- >>> llm = ChatOpenAI(model="gpt-4o")- >>> embedder = OpenAIEmbeddings()- >>> # 初始化模板- >>> criteria_lib = DiagnosticCriteriaSet(llm_client=llm, embedder=embedder)- >>> # 喂入不同版本的指南- >>> criteria_lib.feed_text("2023指南规定糖尿病需空腹血糖>7.0。").feed_text("2024年指南补充了 HbA1c 作为主指标。")- >>> criteria_lib.show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- chunk_size: int = 2048,- chunk_overlap: int = 256,- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any- ):- """- 初始化 DiagnosticCriteriaSet 模板。-- Args:- llm_client: 用于提取的语言模型客户端。- embedder: 用于语义检索和可视化的嵌入模型。- chunk_size: 文本块大小。- chunk_overlap: 文本块重叠大小。- max_workers: 最大并行工作线程数。- verbose: 是否开启详细日志。- **kwargs: 其他传给 AutoSet 的参数。- """- super().__init__(- item_schema=DiagnosticCriteria,- key_extractor=lambda x: x.disease_name.strip().lower(), # 精确键值匹配疾病名- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- chunk_size=chunk_size,- chunk_overlap=chunk_overlap,- max_workers=max_workers,- verbose=verbose,- **kwargs- )-- def show(- self,- *,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,- ) -> None:- """- 可视化诊断标准库。-- Args:- top_k_for_search: 搜索时找回的相关条目数量。- top_k_for_chat: 聊天时找回的相关条目数量。- """- def item_label_extractor(item: DiagnosticCriteria) -> str:- return item.disease_name-- super().show(- item_label_extractor=item_label_extractor,- top_k_for_search=top_k_for_search,- top_k_for_chat=top_k_for_chat,- )diff --git a/hyperextract/templates/zh/medicine/discharge_instruction.py b/hyperextract/templates/zh/medicine/discharge_instruction.pynew file mode 100644index 0000000..3bedaf1--- /dev/null+++ b/hyperextract/templates/zh/medicine/discharge_instruction.py@@ -0,0 +1,102 @@+"""出院医嘱摘要 - 提取出院带药、复诊计划及康复建议的结构化信息。++适用于出院小结中关于出院医嘱的内容。+"""++from typing import Any, List+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoModel+++class DischargeInstructionInfo(BaseModel):+ """出院医嘱信息"""+ medications: List[dict] = Field(description="出院带药列表,每个药物包含名称、剂量、用法、频次等信息")+ followUp: List[dict] = Field(description="复诊计划列表,每个复诊包含时间、科室、检查项目等信息")+ rehabilitation: List[str] = Field(description="康复建议列表")+ diet: List[str] = Field(description="饮食建议列表", default_factory=list)+ activity: List[str] = Field(description="活动建议列表", default_factory=list)+ notes: List[str] = Field(description="其他注意事项列表", default_factory=list)+++_PROMPT = """## 角色与任务+你是一位专业的医生,请从文本中提取出院带药、复诊计划及康复建议的结构化信息,构建出院医嘱摘要。++## 核心概念定义+- **对象 (Object)**:本模板中的"对象"指出院医嘱信息,包含出院带药、复诊计划、康复建议、饮食建议、活动建议和其他注意事项的结构化信息。++## 提取规则+1. 提取所有出院带药信息,每个药物包含名称、剂量、用法、频次等信息+2. 提取所有复诊计划信息,每个复诊包含时间、科室、检查项目等信息+3. 提取所有康复建议、饮食建议、活动建议和其他注意事项+4. 保持信息与原文一致++### 约束条件+- 只提取文本中明确提及的信息+- 保持客观准确,不添加文本中没有的信息++### 源文本:+"""+++class DischargeInstruction(AutoModel[DischargeInstructionInfo]):+ """+ 适用文档: 出院小结、出院记录++ 功能介绍:+ 提取出院带药、复诊计划及康复建议的结构化信息,适用于患者随访、慢病续方。++ Example:+ >>> template = DischargeInstruction(llm_client=llm, embedder=embedder)+ >>> template.feed_text("出院带药:阿司匹林100mg qd...")+ >>> print(template.data.medications)+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化出院医嘱摘要模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ data_schema=DischargeInstructionInfo,+ llm_client=llm_client,+ embedder=embedder,+ prompt=_PROMPT,+ max_workers=max_workers,+ verbose=verbose,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k: int = 3,+ ):+ """+ 展示出院医嘱摘要。++ Args:+ top_k: 问答使用的条目数量,默认为 3+ """+ def label_extractor(item: DischargeInstructionInfo) -> str:+ return "出院医嘱摘要"++ super().show(+ label_extractor=label_extractor,+ top_k=top_k,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/drug_interaction_graph.py b/hyperextract/templates/zh/medicine/drug_interaction_graph.pydeleted file mode 100644index 6c1b865..0000000--- a/hyperextract/templates/zh/medicine/drug_interaction_graph.py+++ /dev/null@@ -1,141 +0,0 @@-from typing import List, Optional, Any, Tuple-from pydantic import BaseModel, Field-from langchain_core.language_models.chat_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoGraph--# ==============================================================================-# 1. Schema 定义 (Schema Definitions)-# ==============================================================================--class MedicalSubstance(BaseModel):- """药品、有效成分或膳食补充剂。"""- name: str = Field(description="药物成分的通用名或主要商品名(如‘阿司匹林’、‘维C’)。")- category: str = Field(description="药物类别(如‘非甾体抗炎药’、‘抗凝药’)。")- description: Optional[str] = Field(description="该药物的主要功能或适应症。")--class DrugInteraction(BaseModel):- """两种药物/成分之间的相互作用属性。"""- source: str = Field(description="首个药物/成分名称。")- target: str = Field(description="第二个药物/成分名称。")- interaction_type: str = Field(description="作用类型(如:禁忌、慎用、协同、拮抗)。")- severity: str = Field(description="严重程度(如:严重、中等、轻微)。")- mechanism: str = Field(description="相互作用的药理机制描述(如‘代谢酶竞争导致血药浓度升高’)。")- recommendation: str = Field(description="临床操作建议(如‘严禁联用’、‘监测血药浓度’)。")--# ==============================================================================-# 2. 提示词 (Prompts)-# ==============================================================================--_PROMPT = (- "你是一位专业的临床药理学家。你的任务是从医药文献、说明书或临床指南中提取药物间的相互作用关系。\n\n"- "提取准则:\n"- "1. **成分标准化**:优先提取通用名。若只有商品名,请记录商品名。\n"- "2. **严谨映射**:准确提取相互作用的性质、严重程度及其背后的医学机制。\n"- "3. **操作指导**:必须保留文中提及的临床建议选项。\n"- "- 确保提取的互动关系仅存在于已识别的药物列表中。"-)--_NODE_PROMPT = (- "请从医药文本中提取所有提及的药物成分、化学名称或补充剂。明确它们的分类和主要药理作用。"-)--_EDGE_PROMPT = (- "在给定的药物列表之间,基于文本提取明确的相互作用(Interaction)。请详细说明互动类型、分级严重程度以及具体的医学机制。"-)--# ==============================================================================-# 3. 模板类 (Template Class)-# ==============================================================================--class DrugInteractionGraph(AutoGraph[MedicalSubstance, DrugInteraction]):- """- 适用于:[药品说明书, 药典, 临床实践指南, 医学期刊]-- 用于构建药物禁忌与协同作用网络的图谱模板。-- 该模板通过双阶段提取,从专业医药文献中梳理出严谨的药物相互作用图谱,为临床决策支持提供结构化数据支持。-- 示例:- >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings- >>> llm = ChatOpenAI(model="gpt-4o")- >>> embedder = OpenAIEmbeddings()- >>> # 初始化模板- >>> drug_map = DrugInteractionGraph(llm_client=llm, embedder=embedder)- >>> # 输入说明书文本- >>> text = "华法林与阿司匹林联用会显著增加出血风险(高度危险)。建议避免同时使用。"- >>> drug_map.feed_text(text)- >>> drug_map.show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- extraction_mode: str = "one_stage",- chunk_size: int = 2048,- chunk_overlap: int = 256,- max_workers: int = 10,- verbose: bool = False,- **kwargs: Any- ):- """- 初始化 DrugInteractionGraph 模板。-- Args:- llm_client: 用于提取的语言模型客户端。- embedder: 用于实体去重和索引的嵌入模型。- extraction_mode: 默认为 one_stage 以获取快速初步图谱,专业场景建议 two_stage。- chunk_size: 文本块大小。- chunk_overlap: 文本块重叠大小。- max_workers: 最大并行工作线程数。- verbose: 是否开启详细日志。- **kwargs: 其他传给 AutoGraph 的参数。- """- super().__init__(- node_schema=MedicalSubstance,- edge_schema=DrugInteraction,- node_key_extractor=lambda x: x.name.strip(),- edge_key_extractor=lambda x: f"{x.source}|{x.target}",- nodes_in_edge_extractor=lambda x: (x.source, x.target),- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- extraction_mode=extraction_mode,- chunk_size=chunk_size,- chunk_overlap=chunk_overlap,- max_workers=max_workers,- verbose=verbose,- **kwargs- )-- def show(- self,- *,- top_k_for_search: int = 3,- top_k_for_chat: int = 3,- ) -> None:- """- 可视化药物相互作用图谱。-- Args:- top_k_for_search: 搜索时找回的相关节点/边数量。- top_k_for_chat: 聊天时找回的相关节点/边数量。- """- def node_label_extractor(node: MedicalSubstance) -> str:- return node.name-- def edge_label_extractor(edge: DrugInteraction) -> str:- return f"{edge.interaction_type} ({edge.severity})"-- super().show(- node_label_extractor=node_label_extractor,- edge_label_extractor=edge_label_extractor,- top_k_nodes_for_search=top_k_for_search,- top_k_edges_for_search=top_k_for_search,- top_k_nodes_for_chat=top_k_for_chat,- top_k_edges_for_chat=top_k_for_chat,- )diff --git a/hyperextract/templates/zh/medicine/hospital_course_timeline.py b/hyperextract/templates/zh/medicine/hospital_course_timeline.pynew file mode 100644index 0000000..ffc55db--- /dev/null+++ b/hyperextract/templates/zh/medicine/hospital_course_timeline.py@@ -0,0 +1,201 @@+"""住院病程时间轴 - 严格按时间顺序提取入院、检查、治疗、转归等节点。++适用于出院小结中关于住院病程的内容。+"""++from typing import Any+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoTemporalGraph+++class HospitalEntity(BaseModel):+ """住院实体节点"""+ name: str = Field(description="节点名称,如入院、检查、治疗、转归等")+ category: str = Field(description="节点类型:入院、检查、治疗、手术、转归、其他等")+ description: str = Field(description="简要描述", default="")+++class HospitalEvent(BaseModel):+ """住院事件边"""+ source: str = Field(description="源节点")+ target: str = Field(description="目标节点")+ eventType: str = Field(description="事件类型:入院、检查、治疗、手术、转归等")+ eventDate: str = Field(description="事件日期,格式为年-月-日")+ details: str = Field(description="详细描述", default="")+++_PROMPT = """## 角色与任务+你是一位专业的医院管理人员,请从文本中严格按时间顺序提取入院、检查、治疗、转归等节点,构建住院病程时间轴。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指住院实体,包括入院、检查、治疗、手术、转归等类型,用于表示住院病程中的基本要素。+- **边 (Edge)**:本模板中的"边"指住院事件边,连接节点并包含时间信息,表达住院病程中的事件。+- **时间**:本模板中的"时间"指事件发生的时间信息,用于按时间顺序排列住院事件,支持相对时间解析。++## 提取规则+### 节点提取规则+1. 提取所有住院相关节点:入院、检查项目、治疗方法、手术、转归等+2. 为每个节点指定类型:入院、检查、治疗、手术、转归、其他等+3. 为每个节点添加简要描述++### 事件提取规则+1. 仅从提取的节点中创建事件边+2. 为每个事件指定类型:入院、检查、治疗、手术、转归等+3. 为每个事件指定日期,格式为年-月-日+4. 为每个事件添加详细描述(如果文本中提供)++### 时间解析规则+当前观察日期:{observation_time}++1. **相对时间解析**:必须根据观察日期解析相对时间表达+ - "入院当天" → 使用入院日期+ - "术后第一天" → 手术日期的后一天+ - "昨天" → {observation_time} 前一天+ - "今天" → {observation_time}++2. **明确日期**:保持原文中的明确日期格式不变+ - 年-月-日(如 2026-02-01)→ 2026-02-01++3. **缺失时间**:如果文本中没有时间信息,将 eventDate 留空,不要编造日期++### 约束条件+- 每条边必须连接已提取的节点+- 不要创建未在文本中提及的节点或事件+- 保持客观准确,不添加文本中没有的信息++### 源文本:+"""++_NODE_PROMPT = """## 角色与任务+你是一位专业的医院管理人员,请从文本中提取所有住院相关节点。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指住院实体,包括入院、检查、治疗、手术、转归等类型,用于表示住院病程中的基本要素。++## 提取规则+1. 提取所有住院相关节点:入院、检查项目、治疗方法、手术、转归等+2. 为每个节点指定类型:入院、检查、治疗、手术、转归、其他等+3. 为每个节点添加简要描述++### 源文本:+"""++_EDGE_PROMPT = """## 角色与任务+你是一位专业的医院管理人员,请从给定节点列表中提取住院事件,构建住院病程时间轴。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指住院实体,作为住院事件的参与者。+- **边 (Edge)**:本模板中的"边"指住院事件边,连接节点并包含时间信息,表达住院病程中的事件。+- **时间**:本模板中的"时间"指事件发生的时间信息,用于按时间顺序排列住院事件,支持相对时间解析。++## 提取规则+### 时间解析规则+当前观察日期:{observation_time}++1. **相对时间解析**:必须根据观察日期解析相对时间表达+ - "入院当天" → 使用入院日期+ - "术后第一天" → 手术日期的后一天+ - "昨天" → {observation_time} 前一天+ - "今天" → {observation_time}++2. **明确日期**:保持原文中的明确日期格式不变+ - 年-月-日(如 2026-02-01)→ 2026-02-01++3. **缺失时间**:如果文本中没有时间信息,将 eventDate 留空,不要编造日期++### 日期格式要求+- 所有日期信息统一转换为「年-月-日」格式(如 2026-02-01)++### 约束条件+1. 仅从下方已知节点列表中提取事件+2. 不要创建未列出的节点+3. 时间信息为必填项,必须为每个事件指定日期++"""+++class HospitalCourseTimeline(AutoTemporalGraph[HospitalEntity, HospitalEvent]):+ """+ 适用文档: 出院小结、住院病历++ 功能介绍:+ 严格按时间顺序提取入院、检查、治疗、转归等节点,适用于病历质控、医疗纠纷溯源。++ Example:+ >>> template = HospitalCourseTimeline(llm_client=llm, embedder=embedder)+ >>> template.feed_text("患者于2026年2月1日入院,2月2日进行心电图检查...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ observation_time: str | None = None,+ extraction_mode: str = "two_stage",+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化住院病程时间轴模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ observation_time: 观察日期,用于解析相对时间表达,默认为今天+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ node_schema=HospitalEntity,+ edge_schema=HospitalEvent,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: f"{x.source}|{x.eventType}|{x.target}",+ time_in_edge_extractor=lambda x: x.eventDate,+ nodes_in_edge_extractor=lambda x: (x.source, x.target),+ llm_client=llm_client,+ embedder=embedder,+ observation_time=observation_time,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示住院病程时间轴。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def node_label_extractor(node: HospitalEntity) -> str:+ return f"{node.name} ({node.category})"++ def edge_label_extractor(edge: HospitalEvent) -> str:+ return f"{edge.eventType} ({edge.eventDate})"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_for_search,+ top_k_edges_for_search=top_k_for_search,+ top_k_nodes_for_chat=top_k_for_chat,+ top_k_edges_for_chat=top_k_for_chat,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/level_of_evidence.py b/hyperextract/templates/zh/medicine/level_of_evidence.pynew file mode 100644index 0000000..8a953df--- /dev/null+++ b/hyperextract/templates/zh/medicine/level_of_evidence.py@@ -0,0 +1,103 @@+"""证据评级表 - 提取指南中的具体推荐意见及其对应的证据等级。++适用于临床诊疗指南中关于推荐意见和证据等级的内容。+"""++from typing import Any+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoList+++class EvidenceItem(BaseModel):+ """证据条目"""+ recommendation: str = Field(description="推荐意见")+ evidenceLevel: str = Field(description="证据等级,如A、B、C、1a、1b等")+ recommendationLevel: str = Field(description="推荐级别,如强推荐、弱推荐等")+ details: str = Field(description="详细描述", default="")+++_PROMPT = """## 角色与任务+你是一位专业的循证医学专家,请从文本中提取指南中的具体推荐意见及其对应的证据等级,构建证据评级表。++## 核心概念定义+- **条目 (Item)**:本模板中的"条目"指证据条目,包含推荐意见、证据等级、推荐级别和详细描述的结构化信息。++## 提取规则+1. 提取所有推荐意见及其对应的证据等级+2. 为每个推荐意见指定推荐级别(如强推荐、弱推荐等)+3. 为每个推荐意见添加详细描述(如果文本中提供)+4. 保持推荐意见与原文一致++### 约束条件+- 只提取文本中明确提及的推荐意见和证据等级+- 保持客观准确,不添加文本中没有的信息++### 源文本:+"""+++class LevelOfEvidence(AutoList[EvidenceItem]):+ """+ 适用文档: 临床诊疗指南、循证医学指南++ 功能介绍:+ 提取指南中的具体推荐意见及其对应的证据等级,适用于设计临床质控方案、科研引用。++ Example:+ >>> template = LevelOfEvidence(llm_client=llm, embedder=embedder)+ >>> template.feed_text("推荐级别A,证据等级1a:所有2型糖尿病患者应接受生活方式干预...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化证据评级表模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ item_schema=EvidenceItem,+ llm_client=llm_client,+ embedder=embedder,+ prompt=_PROMPT,+ max_workers=max_workers,+ verbose=verbose,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示证据评级表。++ Args:+ top_k_for_search: 语义检索返回的条目数量,默认为 3+ top_k_for_chat: 问答使用的条目数量,默认为 3+ """+ def item_label_extractor(item: EvidenceItem) -> str:+ return f"{item.recommendationLevel} (证据等级: {item.evidenceLevel})"++ super().show(+ item_label_extractor=item_label_extractor,+ top_k_items_for_search=top_k_for_search,+ top_k_items_for_chat=top_k_for_chat,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/medical_concept_net.py b/hyperextract/templates/zh/medicine/medical_concept_net.pynew file mode 100644index 0000000..1e81896--- /dev/null+++ b/hyperextract/templates/zh/medicine/medical_concept_net.py@@ -0,0 +1,165 @@+"""医学概念网络 - 提取医学术语及其关联属性(如:属于、定义为)。++适用于医学教科书与专著中关于医学术语和概念的内容。+"""++from typing import Any+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoGraph+++class MedicalConcept(BaseModel):+ """医学概念节点"""+ name: str = Field(description="概念名称,如医学术语、疾病名称、解剖部位等")+ category: str = Field(description="概念类型:疾病、解剖部位、生理过程、药物、症状、体征等")+ definition: str = Field(description="概念定义", default="")+++class MedicalRelation(BaseModel):+ """医学概念关系边"""+ source: str = Field(description="源概念")+ target: str = Field(description="目标概念")+ relationType: str = Field(description="关系类型:属于、定义为、包含、组成、位于、导致、治疗等")+ details: str = Field(description="详细描述", default="")+++_PROMPT = """## 角色与任务+你是一位专业的医学术语专家,请从文本中提取医学术语及其关联属性,构建医学概念网络。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指医学概念,包括疾病、解剖部位、生理过程、药物、症状、体征等类型,用于表示医学领域的基本术语。+- **边 (Edge)**:本模板中的"边"指医学概念之间的关系,包括属于、定义为、包含、组成、位于、导致、治疗等关系类型。++## 提取规则+### 节点提取规则+1. 提取所有医学术语和概念:疾病名称、解剖部位、生理过程、药物名称、症状、体征等+2. 为每个概念指定类型:疾病、解剖部位、生理过程、药物、症状、体征等+3. 为每个概念添加定义(如果文本中提供)++### 关系提取规则+1. 仅从提取的概念中创建关系边+2. 关系类型包括:属于、定义为、包含、组成、位于、导致、治疗等+3. 为每个关系添加详细描述(如果文本中提供)++### 约束条件+- 每条边必须连接已提取的节点+- 不要创建未在文本中提及的概念或关系+- 保持客观准确,不添加文本中没有的信息++### 源文本:+"""++_NODE_PROMPT = """## 角色与任务+你是一位专业的医学术语识别专家,请从文本中提取所有医学术语和概念作为节点。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指医学概念,包括疾病、解剖部位、生理过程、药物、症状、体征等类型,用于表示医学领域的基本术语。++## 提取规则+1. 提取所有医学术语和概念:疾病名称、解剖部位、生理过程、药物名称、症状、体征等+2. 为每个概念指定类型:疾病、解剖部位、生理过程、药物、症状、体征等+3. 为每个概念添加定义(如果文本中提供)++### 源文本:+"""++_EDGE_PROMPT = """## 角色与任务+你是一位专业的医学概念关系提取专家,请从给定医学概念列表中提取概念之间的关系。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指医学概念,作为关系的参与者。+- **边 (Edge)**:本模板中的"边"指医学概念之间的关系,包括属于、定义为、包含、组成、位于、导致、治疗等关系类型。++## 提取规则+1. 仅从下方已知概念列表中提取边+2. 关系类型包括:属于、定义为、包含、组成、位于、导致、治疗等+3. 为每个关系添加详细描述(如果文本中提供)++### 约束条件+1. 不要创建未列出的概念+2. 每条边必须连接已提取的节点++"""+++class MedicalConceptNet(AutoGraph[MedicalConcept, MedicalRelation]):+ """+ 适用文档: 医学教科书、医学专著、医学词典++ 功能介绍:+ 提取医学术语及其关联属性(如:属于、定义为),构建医学概念网络。++ Example:+ >>> template = MedicalConceptNet(llm_client=llm, embedder=embedder)+ >>> template.feed_text("慢性阻塞性肺疾病是一种以持续气流受限为特征的疾病...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化医学概念网络模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ node_schema=MedicalConcept,+ edge_schema=MedicalRelation,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: f"{x.source}|{x.relationType}|{x.target}",+ nodes_in_edge_extractor=lambda x: (x.source, x.target),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示医学概念网络。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def node_label_extractor(node: MedicalConcept) -> str:+ return f"{node.name} ({node.category})"++ def edge_label_extractor(edge: MedicalRelation) -> str:+ return edge.relationType++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_for_search,+ top_k_edges_for_search=top_k_for_search,+ top_k_nodes_for_chat=top_k_for_chat,+ top_k_edges_for_chat=top_k_for_chat,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/microscopic_feature_set.py b/hyperextract/templates/zh/medicine/microscopic_feature_set.pynew file mode 100644index 0000000..0a3fb47--- /dev/null+++ b/hyperextract/templates/zh/medicine/microscopic_feature_set.py@@ -0,0 +1,105 @@+"""微观特征集 - 提取免疫组化指标(如 HER2+, Ki67)及基因突变状态。++适用于病理报告中关于免疫组化和分子检测的内容。+"""++from typing import Any+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoSet+++class MicroscopicFeatureItem(BaseModel):+ """微观特征条目"""+ featureName: str = Field(description="特征名称,如免疫组化指标、基因突变等")+ featureType: str = Field(description="特征类型:免疫组化、基因突变、其他等")+ value: str = Field(description="特征值,如阳性、阴性、百分比等")+ description: str = Field(description="特征描述", default="")+++_PROMPT = """## 角色与任务+你是一位专业的病理学家,请从文本中提取免疫组化指标(如 HER2+, Ki67)及基因突变状态,构建微观特征集。++## 核心概念定义+- **元素 (Element)**:本模板中的"元素"指微观特征条目,包含特征名称、特征类型、特征值和特征描述的结构化信息。++## 提取规则+1. 提取所有免疫组化指标和基因突变状态+2. 为每个特征指定类型:免疫组化、基因突变、其他等+3. 为每个特征添加特征值,如阳性、阴性、百分比等+4. 为每个特征添加简要描述(如果文本中提供)+5. 保持特征名称与原文一致++### 约束条件+- 只提取文本中明确提及的特征和值+- 保持客观准确,不添加文本中没有的信息++### 源文本:+"""+++class MicroscopicFeatureSet(AutoSet[MicroscopicFeatureItem]):+ """+ 适用文档: 病理报告、免疫组化结果、分子检测报告++ 功能介绍:+ 提取免疫组化指标(如 HER2+, Ki67)及基因突变状态,适用于靶向药匹配、科研入组筛选。++ Example:+ >>> template = MicroscopicFeatureSet(llm_client=llm, embedder=embedder)+ >>> template.feed_text("免疫组化结果:ER(+, 90%), PR(+, 70%), HER2(2+)...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化微观特征集模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ item_schema=MicroscopicFeatureItem,+ key_extractor=lambda x: x.featureName,+ llm_client=llm_client,+ embedder=embedder,+ prompt=_PROMPT,+ max_workers=max_workers,+ verbose=verbose,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示微观特征集。++ Args:+ top_k_for_search: 语义检索返回的条目数量,默认为 3+ top_k_for_chat: 问答使用的条目数量,默认为 3+ """+ def label_extractor(item: MicroscopicFeatureItem) -> str:+ return f"{item.featureName} ({item.featureType}): {item.value}"++ super().show(+ label_extractor=label_extractor,+ top_k_items_for_search=top_k_for_search,+ top_k_items_for_chat=top_k_for_chat,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/pathology_hypergraph.py b/hyperextract/templates/zh/medicine/pathology_hypergraph.pynew file mode 100644index 0000000..432e5dc--- /dev/null+++ b/hyperextract/templates/zh/medicine/pathology_hypergraph.py@@ -0,0 +1,167 @@+"""多因素病理机制图 - 建模"基因+环境+诱因 -> 疾病"的复杂致病逻辑。++适用于医学教科书与专著中关于疾病病理机制的内容。+"""++from typing import Any, List+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoHypergraph+++class PathologyEntity(BaseModel):+ """病理实体节点"""+ name: str = Field(description="实体名称,如基因、环境因素、诱因、疾病等")+ category: str = Field(description="实体类型:基因、环境因素、诱因、疾病、病理过程、症状等")+ description: str = Field(description="简要描述", default="")+++class PathologyHyperedge(BaseModel):+ """病理机制超边"""+ name: str = Field(description="超边名称,如致病机制、发病过程等")+ nodes: List[str] = Field(description="参与超边的节点列表")+ relationType: str = Field(description="关系类型:致病、诱发、促进、抑制等")+ details: str = Field(description="详细描述,如具体的致病机制")+++_PROMPT = """## 角色与任务+你是一位专业的病理学家,请从文本中提取与疾病病理机制相关的实体和它们之间的复杂关联关系,构建多因素病理机制图。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指病理实体,包括基因、环境因素、诱因、疾病、病理过程、症状等类型,用于表示病理机制中的基本要素。+- **边 (Edge)**:本模板中的"边"指病理机制超边,连接多个节点,表达"基因+环境+诱因 -> 疾病"的复杂致病逻辑。++## 提取规则+### 节点提取规则+1. 提取所有相关实体:基因、环境因素、诱因、疾病、病理过程、症状等+2. 为每个实体指定类型:基因、环境因素、诱因、疾病、病理过程、症状等+3. 为每个实体添加简要描述++### 超边提取规则+1. 仅从提取的实体中创建超边+2. 超边应表示多个实体之间的复杂关联关系,如"基因+环境+诱因 -> 疾病"+3. 关系类型包括:致病、诱发、促进、抑制等+4. 为每个超边添加详细描述,说明具体的致病机制++### 约束条件+- 每条超边必须连接多个已提取的节点+- 不要创建未在文本中提及的实体或关系+- 保持客观准确,不添加文本中没有的信息++### 源文本:+"""++_NODE_PROMPT = """## 角色与任务+你是一位专业的病理实体识别专家,请从文本中提取与疾病病理机制相关的所有关键实体作为节点。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指病理实体,包括基因、环境因素、诱因、疾病、病理过程、症状等类型,用于表示病理机制中的基本要素。++## 提取规则+1. 提取所有相关实体:基因、环境因素、诱因、疾病、病理过程、症状等+2. 为每个实体指定类型:基因、环境因素、诱因、疾病、病理过程、症状等+3. 为每个实体添加简要描述++### 源文本:+"""++_EDGE_PROMPT = """## 角色与任务+你是一位专业的病理机制分析师,请从给定实体列表中提取它们之间的复杂关联关系,构建病理机制超边。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指病理实体,作为病理机制的参与者。+- **边 (Edge)**:本模板中的"边"指病理机制超边,连接多个节点,表达"基因+环境+诱因 -> 疾病"的复杂致病逻辑。++## 提取规则+1. 仅从下方已知实体列表中创建超边+2. 超边应表示多个实体之间的复杂关联关系,如"基因+环境+诱因 -> 疾病"+3. 关系类型包括:致病、诱发、促进、抑制等+4. 为每个超边添加详细描述,说明具体的致病机制++### 约束条件+1. 不要创建未列出的实体+2. 每条超边必须连接多个节点++"""+++class PathologyHypergraph(AutoHypergraph[PathologyEntity, PathologyHyperedge]):+ """+ 适用文档: 医学教科书、医学专著、病理生理学教材++ 功能介绍:+ 建模"基因+环境+诱因 -> 疾病"的复杂致病逻辑,从文本中提取病理相关实体及其复杂关联关系。++ Example:+ >>> template = PathologyHypergraph(llm_client=llm, embedder=embedder)+ >>> template.feed_text("慢性阻塞性肺疾病的发病机制涉及遗传因素、环境因素和炎症反应...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化多因素病理机制图模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ node_schema=PathologyEntity,+ edge_schema=PathologyHyperedge,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: x.name,+ nodes_in_edge_extractor=lambda x: x.nodes,+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示多因素病理机制图。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def node_label_extractor(node: PathologyEntity) -> str:+ return f"{node.name} ({node.category})"++ def edge_label_extractor(edge: PathologyHyperedge) -> str:+ return f"{edge.name}: {edge.relationType}"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_for_search,+ top_k_edges_for_search=top_k_for_search,+ top_k_nodes_for_chat=top_k_for_chat,+ top_k_edges_for_chat=top_k_for_chat,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/pharmacology_graph.py b/hyperextract/templates/zh/medicine/pharmacology_graph.pynew file mode 100644index 0000000..2b2fac8--- /dev/null+++ b/hyperextract/templates/zh/medicine/pharmacology_graph.py@@ -0,0 +1,165 @@+"""药理机制图 - 提取药物、受体、靶点及生理反应之间的相互作用路径。++适用于医学教科书与专著中关于药物药理机制的内容。+"""++from typing import Any+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoGraph+++class PharmacologyEntity(BaseModel):+ """药理实体节点"""+ name: str = Field(description="实体名称,如药物、受体、靶点、生理反应等")+ category: str = Field(description="实体类型:药物、受体、靶点、生理反应、信号通路等")+ description: str = Field(description="简要描述", default="")+++class PharmacologyRelation(BaseModel):+ """药理机制关系边"""+ source: str = Field(description="源实体")+ target: str = Field(description="目标实体")+ relationType: str = Field(description="关系类型:结合、激活、抑制、调节、诱导、抑制等")+ details: str = Field(description="详细描述,如具体的作用机制")+++_PROMPT = """## 角色与任务+你是一位专业的药理学家,请从文本中提取药物、受体、靶点及生理反应之间的相互作用路径,构建药理机制图。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指药理实体,包括药物、受体、靶点、生理反应、信号通路等类型,用于表示药理机制中的基本要素。+- **边 (Edge)**:本模板中的"边"指药理实体之间的关系,包括结合、激活、抑制、调节、诱导、抑制等关系类型。++## 提取规则+### 节点提取规则+1. 提取所有相关实体:药物名称、受体类型、靶点、生理反应、信号通路等+2. 为每个实体指定类型:药物、受体、靶点、生理反应、信号通路等+3. 为每个实体添加简要描述++### 关系提取规则+1. 仅从提取的实体中创建关系边+2. 关系类型包括:结合、激活、抑制、调节、诱导、抑制等+3. 为每个关系添加详细描述,说明具体的作用机制++### 约束条件+- 每条边必须连接已提取的节点+- 不要创建未在文本中提及的实体或关系+- 保持客观准确,不添加文本中没有的信息++### 源文本:+"""++_NODE_PROMPT = """## 角色与任务+你是一位专业的药理实体识别专家,请从文本中提取与药理机制相关的所有关键实体作为节点。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指药理实体,包括药物、受体、靶点、生理反应、信号通路等类型,用于表示药理机制中的基本要素。++## 提取规则+1. 提取所有相关实体:药物名称、受体类型、靶点、生理反应、信号通路等+2. 为每个实体指定类型:药物、受体、靶点、生理反应、信号通路等+3. 为每个实体添加简要描述++### 源文本:+"""++_EDGE_PROMPT = """## 角色与任务+你是一位专业的药理机制分析师,请从给定实体列表中提取它们之间的相互作用路径,构建药理机制关系边。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指药理实体,作为药理机制的参与者。+- **边 (Edge)**:本模板中的"边"指药理实体之间的关系,包括结合、激活、抑制、调节、诱导、抑制等关系类型。++## 提取规则+1. 仅从下方已知实体列表中提取边+2. 关系类型包括:结合、激活、抑制、调节、诱导、抑制等+3. 为每个关系添加详细描述,说明具体的作用机制++### 约束条件+1. 不要创建未列出的实体+2. 每条边必须连接已提取的节点++"""+++class PharmacologyGraph(AutoGraph[PharmacologyEntity, PharmacologyRelation]):+ """+ 适用文档: 医学教科书、医学专著、药理学教材++ 功能介绍:+ 提取药物、受体、靶点及生理反应之间的相互作用路径,构建药理机制图。++ Example:+ >>> template = PharmacologyGraph(llm_client=llm, embedder=embedder)+ >>> template.feed_text("二甲双胍通过激活AMPK信号通路降低血糖...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化药理机制图模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ node_schema=PharmacologyEntity,+ edge_schema=PharmacologyRelation,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: f"{x.source}|{x.relationType}|{x.target}",+ nodes_in_edge_extractor=lambda x: (x.source, x.target),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示药理机制图。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def node_label_extractor(node: PharmacologyEntity) -> str:+ return f"{node.name} ({node.category})"++ def edge_label_extractor(edge: PharmacologyRelation) -> str:+ return edge.relationType++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_for_search,+ top_k_edges_for_search=top_k_for_search,+ top_k_nodes_for_chat=top_k_for_chat,+ top_k_edges_for_chat=top_k_for_chat,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/surgical_event_graph.py b/hyperextract/templates/zh/medicine/surgical_event_graph.pynew file mode 100644index 0000000..5718a53--- /dev/null+++ b/hyperextract/templates/zh/medicine/surgical_event_graph.py@@ -0,0 +1,170 @@+"""手术事件超图 - 将手术建模为 {医生, 部位, 术式, 器械} 共同参与的复杂事件。++适用于出院小结中关于手术事件的内容。+"""++from typing import Any, List+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoHypergraph+++class SurgicalEntity(BaseModel):+ """手术实体节点"""+ name: str = Field(description="实体名称,如医生、部位、术式、器械等")+ category: str = Field(description="实体类型:医生、部位、术式、器械、麻醉方式等")+ description: str = Field(description="简要描述", default="")+++class SurgicalHyperedge(BaseModel):+ """手术事件超边"""+ name: str = Field(description="超边名称,如手术名称")+ nodes: List[str] = Field(description="参与超边的节点列表")+ date: str = Field(description="手术日期")+ duration: str = Field(description="手术时长", default="")+ details: str = Field(description="详细描述,如手术过程")+++_PROMPT = """## 角色与任务+你是一位专业的外科医生,请从文本中提取手术事件及其相关实体,构建手术事件超图。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指手术实体,包括医生、部位、术式、器械、麻醉方式等类型,用于表示手术事件中的基本要素。+- **边 (Edge)**:本模板中的"边"指手术事件超边,连接多个节点,表达完整的手术事件。++## 提取规则+### 节点提取规则+1. 提取所有手术相关实体:医生姓名、手术部位、手术术式、手术器械、麻醉方式等+2. 为每个实体指定类型:医生、部位、术式、器械、麻醉方式等+3. 为每个实体添加简要描述++### 超边提取规则+1. 仅从提取的实体中创建超边+2. 超边应表示完整的手术事件,包含医生、部位、术式、器械等多个要素+3. 为每个超边指定手术日期+4. 为每个超边添加手术时长(如果文本中提供)+5. 为每个超边添加详细描述,说明具体的手术过程++### 约束条件+- 每条超边必须连接多个已提取的节点+- 不要创建未在文本中提及的实体或关系+- 保持客观准确,不添加文本中没有的信息++### 源文本:+"""++_NODE_PROMPT = """## 角色与任务+你是一位专业的手术实体识别专家,请从文本中提取与手术事件相关的所有关键实体作为节点。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指手术实体,包括医生、部位、术式、器械、麻醉方式等类型,用于表示手术事件中的基本要素。++## 提取规则+1. 提取所有手术相关实体:医生姓名、手术部位、手术术式、手术器械、麻醉方式等+2. 为每个实体指定类型:医生、部位、术式、器械、麻醉方式等+3. 为每个实体添加简要描述++### 源文本:+"""++_EDGE_PROMPT = """## 角色与任务+你是一位专业的手术事件提取专家,请从给定实体列表中提取完整的手术事件,构建手术事件超边。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指手术实体,作为手术事件的组成部分。+- **边 (Edge)**:本模板中的"边"指手术事件超边,连接多个节点,表达完整的手术事件。++## 提取规则+1. 仅从下方已知实体列表中创建超边+2. 超边应表示完整的手术事件,包含医生、部位、术式、器械等多个要素+3. 为每个超边指定手术日期+4. 为每个超边添加手术时长(如果文本中提供)+5. 为每个超边添加详细描述,说明具体的手术过程++### 约束条件+1. 不要创建未列出的实体+2. 每条超边必须连接多个节点++"""+++class SurgicalEventGraph(AutoHypergraph[SurgicalEntity, SurgicalHyperedge]):+ """+ 适用文档: 出院小结、手术记录++ 功能介绍:+ 将手术建模为 {医生, 部位, 术式, 器械} 共同参与的复杂事件,适用于手术质控、绩效评估。++ Example:+ >>> template = SurgicalEventGraph(llm_client=llm, embedder=embedder)+ >>> template.feed_text("2026年2月4日,王医生为患者进行了冠状动脉旁路移植术...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化手术事件超图模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ node_schema=SurgicalEntity,+ edge_schema=SurgicalHyperedge,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: x.name,+ nodes_in_edge_extractor=lambda x: x.nodes,+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示手术事件超图。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def node_label_extractor(node: SurgicalEntity) -> str:+ return f"{node.name} ({node.category})"++ def edge_label_extractor(edge: SurgicalHyperedge) -> str:+ return f"{edge.name} ({edge.date})"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_for_search,+ top_k_edges_for_search=top_k_for_search,+ top_k_nodes_for_chat=top_k_for_chat,+ top_k_edges_for_chat=top_k_for_chat,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/symptom_differential.py b/hyperextract/templates/zh/medicine/symptom_differential.pynew file mode 100644index 0000000..6459f1c--- /dev/null+++ b/hyperextract/templates/zh/medicine/symptom_differential.py@@ -0,0 +1,103 @@+"""鉴别诊断表 - 汇总症状与其对应的鉴别疾病列表,形成症状-疾病映射。++适用于医学教科书与专著中关于症状鉴别诊断的内容。+"""++from typing import Any+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoSet+++class SymptomDifferentialItem(BaseModel):+ """鉴别诊断条目"""+ symptom: str = Field(description="症状名称")+ diseases: list[str] = Field(description="对应的鉴别疾病列表")+ description: str = Field(description="症状描述", default="")+++_PROMPT = """## 角色与任务+你是一位专业的诊断学家,请从文本中提取症状与其对应的鉴别疾病列表,构建鉴别诊断表。++## 核心概念定义+- **元素 (Element)**:本模板中的"元素"指鉴别诊断条目,包含症状名称、对应的鉴别疾病列表和症状描述的结构化信息。++## 提取规则+1. 提取所有症状及其对应的鉴别疾病列表+2. 为每个症状添加简要描述(如果文本中提供)+3. 保持症状名称与原文一致+4. 确保每个症状对应的疾病列表完整++### 约束条件+- 只提取文本中明确提及的症状和疾病+- 保持客观准确,不添加文本中没有的信息++### 源文本:+"""+++class SymptomDifferential(AutoSet[SymptomDifferentialItem]):+ """+ 适用文档: 医学教科书、医学专著、诊断学教材++ 功能介绍:+ 汇总症状与其对应的鉴别疾病列表,形成症状-疾病映射,适用于CDSS辅助诊断、教学系统。++ Example:+ >>> template = SymptomDifferential(llm_client=llm, embedder=embedder)+ >>> template.feed_text("胸痛的鉴别诊断包括冠心病、胸膜炎、肺炎等...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化鉴别诊断表模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ item_schema=SymptomDifferentialItem,+ key_extractor=lambda x: x.symptom,+ llm_client=llm_client,+ embedder=embedder,+ prompt=_PROMPT,+ max_workers=max_workers,+ verbose=verbose,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示鉴别诊断表。++ Args:+ top_k_for_search: 语义检索返回的条目数量,默认为 3+ top_k_for_chat: 问答使用的条目数量,默认为 3+ """+ def label_extractor(item: SymptomDifferentialItem) -> str:+ return f"{item.symptom}: {', '.join(item.diseases[:3])}{'...' if len(item.diseases) > 3 else ''}"++ super().show(+ label_extractor=label_extractor,+ top_k_items_for_search=top_k_for_search,+ top_k_items_for_chat=top_k_for_chat,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/treatment_regimen_map.py b/hyperextract/templates/zh/medicine/treatment_regimen_map.pynew file mode 100644index 0000000..df24a0b--- /dev/null+++ b/hyperextract/templates/zh/medicine/treatment_regimen_map.py@@ -0,0 +1,167 @@+"""综合治疗方案图 - 提取由"药物组合+理疗+生活干预"构成的多因素治疗方案。++适用于临床诊疗指南中关于治疗方案的内容。+"""++from typing import Any, List+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoHypergraph+++class TreatmentEntity(BaseModel):+ """治疗实体节点"""+ name: str = Field(description="实体名称,如药物、理疗方法、生活干预等")+ category: str = Field(description="实体类型:药物、理疗、生活干预、检查、手术等")+ description: str = Field(description="简要描述", default="")+++class TreatmentHyperedge(BaseModel):+ """治疗方案超边"""+ name: str = Field(description="超边名称,如治疗方案、康复计划等")+ nodes: List[str] = Field(description="参与超边的节点列表")+ disease: str = Field(description="针对的疾病")+ details: str = Field(description="详细描述,如具体的治疗方案内容")+++_PROMPT = """## 角色与任务+你是一位专业的临床医生,请从文本中提取由"药物组合+理疗+生活干预"构成的多因素治疗方案,构建综合治疗方案图。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指治疗实体,包括药物、理疗方法、生活干预、检查、手术等类型,用于表示治疗方案中的基本要素。+- **边 (Edge)**:本模板中的"边"指治疗方案超边,连接多个节点,表达完整的治疗方案。++## 提取规则+### 节点提取规则+1. 提取所有治疗相关实体:药物名称、理疗方法、生活干预措施、检查项目、手术方式等+2. 为每个实体指定类型:药物、理疗、生活干预、检查、手术等+3. 为每个实体添加简要描述++### 超边提取规则+1. 仅从提取的实体中创建超边+2. 超边应表示完整的治疗方案,包含药物组合、理疗和生活干预等多个要素+3. 为每个超边指定针对的疾病+4. 为每个超边添加详细描述,说明具体的治疗方案内容++### 约束条件+- 每条超边必须连接多个已提取的节点+- 不要创建未在文本中提及的实体或关系+- 保持客观准确,不添加文本中没有的信息++### 源文本:+"""++_NODE_PROMPT = """## 角色与任务+你是一位专业的治疗实体识别专家,请从文本中提取与治疗方案相关的所有关键实体作为节点。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指治疗实体,包括药物、理疗方法、生活干预、检查、手术等类型,用于表示治疗方案中的基本要素。++## 提取规则+1. 提取所有治疗相关实体:药物名称、理疗方法、生活干预措施、检查项目、手术方式等+2. 为每个实体指定类型:药物、理疗、生活干预、检查、手术等+3. 为每个实体添加简要描述++### 源文本:+"""++_EDGE_PROMPT = """## 角色与任务+你是一位专业的治疗方案提取专家,请从给定实体列表中提取完整的治疗方案,构建治疗方案超边。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指治疗实体,作为治疗方案的组成部分。+- **边 (Edge)**:本模板中的"边"指治疗方案超边,连接多个节点,表达完整的治疗方案。++## 提取规则+1. 仅从下方已知实体列表中创建超边+2. 超边应表示完整的治疗方案,包含药物组合、理疗和生活干预等多个要素+3. 为每个超边指定针对的疾病+4. 为每个超边添加详细描述,说明具体的治疗方案内容++### 约束条件+1. 不要创建未列出的实体+2. 每条超边必须连接多个节点++"""+++class TreatmentRegimenMap(AutoHypergraph[TreatmentEntity, TreatmentHyperedge]):+ """+ 适用文档: 临床诊疗指南、治疗方案手册++ 功能介绍:+ 提取由"药物组合+理疗+生活干预"构成的多因素治疗方案,适用于肿瘤化疗方案、慢病管理。++ Example:+ >>> template = TreatmentRegimenMap(llm_client=llm, embedder=embedder)+ >>> template.feed_text("2型糖尿病的治疗方案包括二甲双胍、饮食控制和运动...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化综合治疗方案图模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ node_schema=TreatmentEntity,+ edge_schema=TreatmentHyperedge,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: x.name,+ nodes_in_edge_extractor=lambda x: x.nodes,+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示综合治疗方案图。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def node_label_extractor(node: TreatmentEntity) -> str:+ return f"{node.name} ({node.category})"++ def edge_label_extractor(edge: TreatmentHyperedge) -> str:+ return f"{edge.name} - {edge.disease}"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_for_search,+ top_k_edges_for_search=top_k_for_search,+ top_k_nodes_for_chat=top_k_for_chat,+ top_k_edges_for_chat=top_k_for_chat,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/medicine/tumor_staging_item.py b/hyperextract/templates/zh/medicine/tumor_staging_item.pynew file mode 100644index 0000000..84f89cb--- /dev/null+++ b/hyperextract/templates/zh/medicine/tumor_staging_item.py@@ -0,0 +1,105 @@+"""TNM 分期表 - 提取肿瘤大小(T)、淋巴结(N)、转移(M)及分期结果。++适用于病理报告中关于肿瘤分期的内容。+"""++from typing import Any+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoModel+++class TumorStagingInfo(BaseModel):+ """肿瘤分期信息"""+ tStage: str = Field(description="T分期,如T1、T2、T3、T4等")+ nStage: str = Field(description="N分期,如N0、N1、N2、N3等")+ mStage: str = Field(description="M分期,如M0、M1等")+ pathologicalStage: str = Field(description="病理分期,如I期、II期、III期、IV期等")+ tDetails: str = Field(description="T分期详细描述,如肿瘤大小")+ nDetails: str = Field(description="N分期详细描述,如淋巴结转移数量")+ mDetails: str = Field(description="M分期详细描述,如远处转移部位")+++_PROMPT = """## 角色与任务+你是一位专业的病理学家,请从文本中提取肿瘤大小(T)、淋巴结(N)、转移(M)及分期结果,构建TNM分期表。++## 核心概念定义+- **对象 (Object)**:本模板中的"对象"指肿瘤分期信息,包含T分期、N分期、M分期、病理分期及详细描述的结构化信息。++## 提取规则+1. 提取T分期、N分期、M分期和病理分期+2. 为每个分期添加详细描述:+ - T分期详细描述:肿瘤大小、浸润深度等+ - N分期详细描述:淋巴结转移数量、部位等+ - M分期详细描述:远处转移部位等+3. 保持信息与原文一致++### 约束条件+- 只提取文本中明确提及的信息+- 保持客观准确,不添加文本中没有的信息++### 源文本:+"""+++class TumorStagingItem(AutoModel[TumorStagingInfo]):+ """+ 适用文档: 病理报告、肿瘤分期记录++ 功能介绍:+ 提取肿瘤大小(T)、淋巴结(N)、转移(M)及分期结果,适用于肿瘤登记、预后评估。++ Example:+ >>> template = TumorStagingItem(llm_client=llm, embedder=embedder)+ >>> template.feed_text("T分期:T2(肿瘤最大径>2cm且≤5cm)...")+ >>> print(template.data.pathologicalStage)+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化TNM分期表模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ data_schema=TumorStagingInfo,+ llm_client=llm_client,+ embedder=embedder,+ prompt=_PROMPT,+ max_workers=max_workers,+ verbose=verbose,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k: int = 3,+ ):+ """+ 展示TNM分期表。++ Args:+ top_k: 问答使用的条目数量,默认为 3+ """+ def label_extractor(item: TumorStagingInfo) -> str:+ return f"TNM分期: {item.tStage}{item.nStage}{item.mStage} ({item.pathologicalStage})"++ super().show(+ label_extractor=label_extractor,+ top_k=top_k,+ )\ No newline at end of filediff --git a/hyperextract/templates/zh/tcm/__init__.py b/hyperextract/templates/zh/tcm/__init__.pyindex 16221ec..757619d 100644--- a/hyperextract/templates/zh/tcm/__init__.py+++ b/hyperextract/templates/zh/tcm/__init__.py@@ -1,13 +1,31 @@-from .prescription_composition_graph import PrescriptionCompositionGraph-from .syndrome_treatment_loop import SyndromeTreatmentLoop-from .meridian_acupoint_spatial import MeridianAcupointSpatial-from .prescription_manual_set import PrescriptionManualSet-from .herb_interaction_hypergraph import HerbInteractionHypergraph+# 本草典籍+from .herb_property_model import HerbPropertyModel+from .processing_method import ProcessingMethod+from .compatibility_net import CompatibilityNet+# 方剂规范+from .formula_composition import FormulaComposition+from .function_indication_map import FunctionIndicationMap+# 经络腧穴专著+from .meridian_flow_graph import MeridianFlowGraph+from .acupoint_location_map import AcupointLocationMap+# 名医医案+from .syndrome_reasoning_graph import SyndromeReasoningGraph+from .prescription_modification import PrescriptionModification+from .pulse_tongue_record import PulseTongueRecord__all__ = [- "PrescriptionCompositionGraph",- "SyndromeTreatmentLoop",- "MeridianAcupointSpatial",- "PrescriptionManualSet",- "HerbInteractionHypergraph",+ # 本草典籍+ "HerbPropertyModel",+ "ProcessingMethod",+ "CompatibilityNet",+ # 方剂规范+ "FormulaComposition",+ "FunctionIndicationMap",+ # 经络腧穴专著+ "MeridianFlowGraph",+ "AcupointLocationMap",+ # 名医医案+ "SyndromeReasoningGraph",+ "PrescriptionModification",+ "PulseTongueRecord",]diff --git a/hyperextract/templates/zh/tcm/acupoint_location_map.py b/hyperextract/templates/zh/tcm/acupoint_location_map.pynew file mode 100644index 0000000..e911b0f--- /dev/null+++ b/hyperextract/templates/zh/tcm/acupoint_location_map.py@@ -0,0 +1,169 @@+"""腧穴空间定位 - 基于人体解剖标志提取穴位的相对位置关系(如"脐旁2寸")。++适用于针灸教学可视化、穴位图谱。+"""++from typing import Any+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoGraph+++class AcupointNode(BaseModel):+ """穴位节点"""+ name: str = Field(description="穴位名称:如合谷、足三里、三阴交等")+ meridian: str = Field(description="所属经脉", default="")+ location: str = Field(description="位置描述:如脐旁2寸、腕横纹上3寸等")+ indications: str = Field(description="主治功能", default="")+++class LocationRelation(BaseModel):+ """位置关系边"""+ source: str = Field(description="源穴位或解剖标志名称")+ target: str = Field(description="目标穴位名称")+ relationType: str = Field(description="关系类型:位于")+ relativePosition: str = Field(description="相对位置描述:如脐旁2寸、腕横纹上3寸等")+++_PROMPT = """## 角色与任务+你是一位专业的针灸学专家,请从文本中提取穴位的相对位置关系。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指穴位实体或解剖标志,包括名称、所属经脉、位置描述、主治功能等信息。+- **边 (Edge)**:本模板中的"边"指穴位之间或穴位与解剖标志之间的位置关系,包括源实体、目标穴位、相对位置描述等信息。++## 提取规则+### 节点提取规则+1. 提取所有穴位实体:如合谷、足三里、三阴交等+2. 提取所有解剖标志:如脐、腕横纹、肘横纹等+3. 为每个穴位指定所属经脉+4. 提取每个穴位的位置描述和主治功能++### 关系提取规则+1. 提取穴位之间或穴位与解剖标志之间的位置关系+2. 为每种关系指定类型:位于+3. 提取相对位置描述:如脐旁2寸、腕横纹上3寸等++### 约束条件+- 每条边必须连接已提取的节点+- 不要创建未在文本中提及的实体或关系+- 保持客观准确,符合针灸学专业术语规范++### 源文本:+"""++_NODE_PROMPT = """## 角色与任务+你是一位专业的针灸学专家,请从文本中提取所有穴位实体和解剖标志作为节点。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指穴位实体或解剖标志,包括名称、所属经脉、位置描述、主治功能等信息。++## 提取规则+1. 提取所有穴位实体:如合谷、足三里、三阴交等+2. 提取所有解剖标志:如脐、腕横纹、肘横纹等+3. 为每个穴位指定所属经脉+4. 提取每个穴位的位置描述和主治功能++### 源文本:+"""++_EDGE_PROMPT = """## 角色与任务+你是一位专业的针灸学专家,请从给定实体列表中提取穴位的相对位置关系。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指穴位实体或解剖标志,作为位置关系的参与者。+- **边 (Edge)**:本模板中的"边"指穴位之间或穴位与解剖标志之间的位置关系,包括源实体、目标穴位、相对位置描述等信息。++## 提取规则+1. 提取穴位之间或穴位与解剖标志之间的位置关系+2. 为每种关系指定类型:位于+3. 提取相对位置描述:如脐旁2寸、腕横纹上3寸等++### 约束条件+1. 仅从下方已知实体列表中提取边+2. 不要创建未列出的实体+3. 每条边必须包含 source、target、relationType、relativePosition++"""+++class AcupointLocationMap(AutoGraph[AcupointNode, LocationRelation]):+ """+ 适用文档: 针灸学教材、穴位图谱、黄帝内经等++ 功能介绍:+ 基于人体解剖标志提取穴位的相对位置关系(如"脐旁2寸"),适用于针灸教学可视化、穴位图谱。++ Example:+ >>> template = AcupointLocationMap(llm_client=llm, embedder=embedder)+ >>> template.feed_text("合谷穴:在手背,第1、2掌骨间,当第2掌骨桡侧的中点处...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化腧穴空间定位模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ node_schema=AcupointNode,+ edge_schema=LocationRelation,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: f"{x.source}|{x.relationType}|{x.target}",+ nodes_in_edge_extractor=lambda x: (x.source, x.target),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示腧穴空间定位图。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def node_label_extractor(node: AcupointNode) -> str:+ return f"{node.name} ({node.meridian})"++ def edge_label_extractor(edge: LocationRelation) -> str:+ return edge.relativePosition++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_for_search,+ top_k_edges_for_search=top_k_for_search,+ top_k_nodes_for_chat=top_k_for_chat,+ top_k_edges_for_chat=top_k_for_chat,+ )diff --git a/hyperextract/templates/zh/tcm/compatibility_net.py b/hyperextract/templates/zh/tcm/compatibility_net.pynew file mode 100644index 0000000..1fe90e1--- /dev/null+++ b/hyperextract/templates/zh/tcm/compatibility_net.py@@ -0,0 +1,159 @@+"""七情配伍网络 - 提取药物间的相须、相使、相畏、相杀、十八反十九畏关系。++适用于配伍禁忌预警、方剂组网分析。+"""++from typing import Any+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoGraph+++class HerbEntity(BaseModel):+ """药物实体节点"""+ name: str = Field(description="药物名称")+ description: str = Field(description="简要描述", default="")+++class CompatibilityRelation(BaseModel):+ """配伍关系边"""+ source: str = Field(description="源药物")+ target: str = Field(description="目标药物")+ relationType: str = Field(description="配伍关系类型:相须、相使、相畏、相杀、相恶、相反、十八反、十九畏")+ effect: str = Field(description="配伍效果描述", default="")+++_PROMPT = """## 角色与任务+你是一位专业的中药配伍专家,请从文本中提取药物间的配伍关系。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指中药药物实体,用于表示知识图谱中的基本药物。+- **边 (Edge)**:本模板中的"边"指药物之间的配伍关系,包括相须、相使、相畏、相杀、相恶、相反、十八反、十九畏等关系类型。++## 提取规则+### 节点提取规则+1. 提取所有药物实体+2. 为每个药物添加简要描述++### 关系提取规则+1. 提取所有药物之间的配伍关系+2. 为每种配伍关系指定类型:相须、相使、相畏、相杀、相恶、相反、十八反、十九畏+3. 提取每种配伍关系的效果描述++### 约束条件+- 每条边必须连接已提取的节点+- 不要创建未在文本中提及的实体或关系+- 保持客观准确,符合中药配伍专业术语规范++### 源文本:+"""++_NODE_PROMPT = """## 角色与任务+你是一位专业的中药识别专家,请从文本中提取所有药物实体作为节点。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指中药药物实体,用于表示知识图谱中的基本药物。++## 提取规则+1. 提取所有药物实体+2. 为每个药物添加简要描述++### 源文本:+"""++_EDGE_PROMPT = """## 角色与任务+你是一位专业的中药配伍专家,请从给定药物列表中提取药物之间的配伍关系。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指中药药物实体,作为配伍关系的参与者。+- **边 (Edge)**:本模板中的"边"指药物之间的配伍关系,包括相须、相使、相畏、相杀、相恶、相反、十八反、十九畏等关系类型。++## 提取规则+1. 仅从下方已知药物列表中提取边+2. 不要创建未列出的药物+3. 为每种配伍关系指定类型:相须、相使、相畏、相杀、相恶、相反、十八反、十九畏+4. 提取每种配伍关系的效果描述++"""+++class CompatibilityNet(AutoGraph[HerbEntity, CompatibilityRelation]):+ """+ 适用文档: 本草典籍、中药配伍指南、方剂学教材等++ 功能介绍:+ 提取药物间的相须、相使、相畏、相杀、十八反十九畏关系,适用于配伍禁忌预警、方剂组网分析。++ Example:+ >>> template = CompatibilityNet(llm_client=llm, embedder=embedder)+ >>> template.feed_text("甘草反大戟、芫花、甘遂、海藻...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化七情配伍网络模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ node_schema=HerbEntity,+ edge_schema=CompatibilityRelation,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: f"{x.source}|{x.relationType}|{x.target}",+ nodes_in_edge_extractor=lambda x: (x.source, x.target),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示七情配伍网络。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def node_label_extractor(node: HerbEntity) -> str:+ return node.name++ def edge_label_extractor(edge: CompatibilityRelation) -> str:+ return edge.relationType++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_for_search,+ top_k_edges_for_search=top_k_for_search,+ top_k_nodes_for_chat=top_k_for_chat,+ top_k_edges_for_chat=top_k_for_chat,+ )diff --git a/hyperextract/templates/zh/tcm/formula_composition.py b/hyperextract/templates/zh/tcm/formula_composition.pynew file mode 100644index 0000000..6df424b--- /dev/null+++ b/hyperextract/templates/zh/tcm/formula_composition.py@@ -0,0 +1,173 @@+"""君臣佐使结构图 - 将方剂建模为 {君药, 臣药, 佐药, 使药} 的层级化超边结构。++适用于方剂结构解析、组方规律研究。+"""++from typing import Any, List+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoHypergraph+++class HerbNode(BaseModel):+ """药物节点"""+ name: str = Field(description="药物名称")+ role: str = Field(description="药物角色:君药、臣药、佐药、使药")+ dosage: str = Field(description="药物剂量", default="")+ effect: str = Field(description="药物功效", default="")+++class FormulaHyperedge(BaseModel):+ """方剂超边"""+ formulaName: str = Field(description="方剂名称")+ junHerbs: List[str] = Field(description="君药列表")+ chenHerbs: List[str] = Field(description="臣药列表")+ zuoHerbs: List[str] = Field(description="佐药列表")+ shiHerbs: List[str] = Field(description="使药列表")+ functions: List[str] = Field(description="方剂功能", default_factory=list)+ indications: List[str] = Field(description="主治证候", default_factory=list)+ decoctionMethod: str = Field(description="煎服法", default="")+++_PROMPT = """## 角色与任务+你是一位专业的方剂学专家,请从文本中提取方剂的君臣佐使结构。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指方剂中的药物实体,包括药物名称、角色、剂量、功效等信息。+- **边 (Edge)**:本模板中的"边"指方剂超边,包含方剂名称、君药、臣药、佐药、使药列表、方剂功能、主治证候、煎服法等信息。++## 提取规则+### 节点提取规则+1. 提取方剂中的所有药物实体+2. 为每个药物指定角色:君药、臣药、佐药、使药+3. 提取每个药物的剂量和功效++### 边提取规则+1. 提取方剂名称+2. 提取君药、臣药、佐药、使药列表+3. 提取方剂功能和主治证候+4. 提取煎服法++### 约束条件+- 每条边必须包含方剂名称和至少一种角色的药物列表+- 不要创建未在文本中提及的实体或关系+- 保持客观准确,符合方剂学专业术语规范++### 源文本:+"""++_NODE_PROMPT = """## 角色与任务+你是一位专业的药物识别专家,请从文本中提取方剂中的所有药物实体作为节点。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指方剂中的药物实体,包括药物名称、角色、剂量、功效等信息。++## 提取规则+1. 提取方剂中的所有药物实体+2. 为每个药物指定角色:君药、臣药、佐药、使药+3. 提取每个药物的剂量和功效++### 源文本:+"""++_EDGE_PROMPT = """## 角色与任务+你是一位专业的方剂学专家,请从给定药物列表中提取方剂的君臣佐使结构。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指方剂中的药物实体,作为方剂的组成部分。+- **边 (Edge)**:本模板中的"边"指方剂超边,包含方剂名称、君药、臣药、佐药、使药列表、方剂功能、主治证候、煎服法等信息。++## 提取规则+1. 提取方剂名称+2. 从已知药物列表中提取君药、臣药、佐药、使药列表+3. 提取方剂功能和主治证候+4. 提取煎服法++### 约束条件+1. 仅从下方已知药物列表中提取药物+2. 不要创建未列出的药物+3. 每条边必须包含方剂名称和至少一种角色的药物列表++"""+++class FormulaComposition(AutoHypergraph[HerbNode, FormulaHyperedge]):+ """+ 适用文档: 方剂规范、伤寒论、金匮要略、方剂学教材等++ 功能介绍:+ 将方剂建模为 {君药, 臣药, 佐药, 使药} 的层级化超边结构,适用于方剂结构解析、组方规律研究。++ Example:+ >>> template = FormulaComposition(llm_client=llm, embedder=embedder)+ >>> template.feed_text("桂枝汤:桂枝三两,芍药三两,甘草二两,生姜三两,大枣十二枚...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化君臣佐使结构图模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ node_schema=HerbNode,+ edge_schema=FormulaHyperedge,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: x.formulaName,+ nodes_in_edge_extractor=lambda x: (x.junHerbs, x.chenHerbs, x.zuoHerbs, x.shiHerbs),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示君臣佐使结构图。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def node_label_extractor(node: HerbNode) -> str:+ return f"{node.name} ({node.role})"++ def edge_label_extractor(edge: FormulaHyperedge) -> str:+ return edge.formulaName++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_for_search,+ top_k_edges_for_search=top_k_for_search,+ top_k_nodes_for_chat=top_k_for_chat,+ top_k_edges_for_chat=top_k_for_chat,+ )diff --git a/hyperextract/templates/zh/tcm/function_indication_map.py b/hyperextract/templates/zh/tcm/function_indication_map.pynew file mode 100644index 0000000..140cd81--- /dev/null+++ b/hyperextract/templates/zh/tcm/function_indication_map.py@@ -0,0 +1,168 @@+"""主治功效映射 - 关联 方剂 -> 功能(如清热解毒) -> 主治证候。++适用于方剂推荐系统。+"""++from typing import Any+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoGraph+++class GeneralEntity(BaseModel):+ """通用实体节点"""+ name: str = Field(description="实体名称")+ category: str = Field(description="实体类型:方剂、功能、主治证候")+ description: str = Field(description="简要描述", default="")+++class GeneralRelation(BaseModel):+ """通用关系边"""+ source: str = Field(description="源实体")+ target: str = Field(description="目标实体")+ relationType: str = Field(description="关系类型:具有功能、主治")+ details: str = Field(description="详细描述", default="")+++_PROMPT = """## 角色与任务+你是一位专业的方剂学专家,请从文本中提取方剂、功能和主治证候之间的关联关系。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指通用实体,包括方剂、功能、主治证候等类型,用于表示知识图谱中的基本元素。+- **边 (Edge)**:本模板中的"边"指实体之间的二元关系,包括具有功能、主治等关系类型。++## 提取规则+### 节点提取规则+1. 提取所有实体:方剂、功能、主治证候+2. 为每个实体指定类型:方剂、功能、主治证候+3. 保持实体名称与原文一致+4. 为每个实体添加简要描述++### 关系提取规则+1. 提取方剂与功能之间的关系(具有功能)+2. 提取功能与主治证候之间的关系(主治)+3. 为每种关系添加详细描述++### 约束条件+- 每条边必须连接已提取的节点+- 不要创建未在文本中提及的实体或关系+- 保持客观准确,符合方剂学专业术语规范++### 源文本:+"""++_NODE_PROMPT = """## 角色与任务+你是一位专业的实体识别专家,请从文本中提取所有方剂、功能和主治证候实体作为节点。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指通用实体,包括方剂、功能、主治证候等类型,用于表示知识图谱中的基本元素。++## 提取规则+1. 提取所有实体:方剂、功能、主治证候+2. 为每个实体指定类型:方剂、功能、主治证候+3. 保持实体名称与原文一致+4. 为每个实体添加简要描述++### 源文本:+"""++_EDGE_PROMPT = """## 角色与任务+你是一位专业的关系提取专家,请从给定实体列表中提取方剂、功能和主治证候之间的关联关系。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指通用实体,作为关系的参与者。+- **边 (Edge)**:本模板中的"边"指实体之间的二元关系,包括具有功能、主治等关系类型。++## 提取规则+1. 提取方剂与功能之间的关系(具有功能)+2. 提取功能与主治证候之间的关系(主治)+3. 为每种关系添加详细描述++### 约束条件+1. 仅从下方已知实体列表中提取边+2. 不要创建未列出的实体+3. 每条边必须包含 source、target、relationType++"""+++class FunctionIndicationMap(AutoGraph[GeneralEntity, GeneralRelation]):+ """+ 适用文档: 方剂规范、伤寒论、金匮要略、方剂学教材等++ 功能介绍:+ 关联 方剂 -> 功能(如清热解毒) -> 主治证候,适用于方剂推荐系统。++ Example:+ >>> template = FunctionIndicationMap(llm_client=llm, embedder=embedder)+ >>> template.feed_text("桂枝汤:解肌发表,调和营卫。主治太阳中风...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化主治功效映射模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ node_schema=GeneralEntity,+ edge_schema=GeneralRelation,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: f"{x.source}|{x.relationType}|{x.target}",+ nodes_in_edge_extractor=lambda x: (x.source, x.target),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示主治功效映射。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def node_label_extractor(node: GeneralEntity) -> str:+ return f"{node.name} ({node.category})"++ def edge_label_extractor(edge: GeneralRelation) -> str:+ return edge.relationType++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_for_search,+ top_k_edges_for_search=top_k_for_search,+ top_k_nodes_for_chat=top_k_for_chat,+ top_k_edges_for_chat=top_k_for_chat,+ )diff --git a/hyperextract/templates/zh/tcm/herb_interaction_hypergraph.py b/hyperextract/templates/zh/tcm/herb_interaction_hypergraph.pydeleted file mode 100644index b784660..0000000--- a/hyperextract/templates/zh/tcm/herb_interaction_hypergraph.py+++ /dev/null@@ -1,118 +0,0 @@-from typing import List, Optional, Any, Tuple-from pydantic import BaseModel, Field-from langchain_core.language_models.chat_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoHypergraph--# ==============================================================================-# 1. Schema 定义-# ==============================================================================--class HerbNode(BaseModel):- """单味中药材。"""- name: str = Field(description="药材标准名称。")- nature_flavor: str = Field(description="性味归经(如:苦寒,归胃经)。")--class InteractionHyperEdge(BaseModel):- """- 描述多味中药材之间复杂的相互作用关系。- 这不仅仅是一对一的药对,也可能是多味药的协同(如:反佐、十八反)。- """- herbs_involved: List[str] = Field(description="参与该相互作用的所有药材名称列表。")- interaction_type: str = Field(description="交互类型:七情配伍(相须、相使、相畏...)、十八反、十九畏、协同增强、拮抗减毒。")- mechanism: str = Field(description="具体的药理机制或配伍效果描述(如:生姜与半夏相畏,能解其毒)。")- clinical_significance: Optional[str] = Field(description="临床指导意义(如:用于妊娠呕吐,或绝对禁止同用)。")--# ==============================================================================-# 2. 提示词 (Prompts)-# ==============================================================================--_PROMPT = (- "你是一位深谙中药理论及现代药理学的药剂师。你的任务是分析文献中提到的药物配伍相互作用(包括但不限于七情、十八反)。\n\n"- "### 核心提取规则:\n"- "1. **多向识别**:某些配伍涉及多味药(如一种药同时‘相恶’多种药,或多方药联合导致的毒性变化),必须建立涉及所有方的超边。\n"- "2. **七情辨识**:精准区分协同作用(相须、相使)、减毒作用(相畏、相杀)、减效作用(相恶)和增毒作用(相反)。\n"- "3. **机制还原**:在 `mechanism` 字段中详细描述为何会产生此反应(如‘生姜能消除半夏的刺激性毒性’)。\n"- "4. **安全警示**:对于禁忌类配伍,在 `clinical_significance` 中明确标注‘严禁同用’等字样。"-)--_NODE_PROMPT = (- "你是一位中药药性研究专家。请识别文本中提到的所有中药材实体。\n\n"- "### 提取规则:\n"- "1. **实体规范**:统一使用《药典》标准名称。\n"- "2. **药性关联**:尽可能标注每味药的典型性味归经属性。"-)--_EDGE_PROMPT = (- "你是一位精准药理交互分析师。请在已识别的药材间分析复杂的相互关系。\n\n"- "### 逻辑连接规则:\n"- "1. **集合聚合**:将所有同时参与一个反应或配伍原则的药材归为一个列表(herbs_involved)。\n"- "2. **关系定性**:根据‘七情合和’理论给交互类型定性(如‘相使’)。\n"- "3. **效果量化**:描述该组合是增强了主药功效,还是抑制了副反应。"-)--# ==============================================================================-# 3. 模板类-# ==============================================================================--class HerbInteractionHypergraph(AutoHypergraph[HerbNode, InteractionHyperEdge]):- """- 适用于:[本草纲目等药典, 药理学论文, 配伍禁忌预警]-- 一个基于传统“七情”理论及现代药理学,用于分析多种中药间复杂非线性相互作用的超图模板。-- Key Features:- - 捕获涉及两个以上实体的多药相互作用关系。- - 对传统的交互类型(如“相畏”、“相杀”)进行分类。- - 保留对安全性至关重要的机制解释和临床意义。-- Example:- >>> from hyperextract.templates.zh.tcm import HerbInteractionHypergraph- >>> hyper = HerbInteractionHypergraph(llm_client=llm, embedder=embedder)- >>> text = "半夏与生姜相畏,生姜能解半夏毒;乌头反半夏、贝母、瓜蒌。"- >>> hyper.feed_text(text).show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- extraction_mode: str = "two_stage",- **kwargs: Any- ):- """- 初始化 HerbInteractionHypergraph。-- Args:- llm_client (BaseChatModel): 用于提取的语言模型客户端。- embedder (Embeddings): 用于索引的嵌入模型。- extraction_mode (str): 提取模式,'one_stage' 或 'two_stage'。默认为 'two_stage'。- **kwargs: 传递给 AutoHypergraph 的额外参数。- """- super().__init__(- node_schema=HerbNode,- edge_schema=InteractionHyperEdge,- node_key_extractor=lambda x: x.name.strip(),- edge_key_extractor=lambda x: f"{sorted(x.herbs_involved)}-{x.interaction_type}",- nodes_in_edge_extractor=lambda x: x.herbs_involved,- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- extraction_mode=extraction_mode,- **kwargs- )-- def show(self, **kwargs):- """- 可视化中药相互作用超图。-- Args:- **kwargs: 传递给基础 show() 方法的参数。- """- def n_label(node: HerbNode) -> str: return node.name- def e_label(edge: InteractionHyperEdge) -> str:- return f"[{edge.interaction_type}] {edge.mechanism}"- super().show(node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs)diff --git a/hyperextract/templates/zh/tcm/herb_property_model.py b/hyperextract/templates/zh/tcm/herb_property_model.pynew file mode 100644index 0000000..09a0253--- /dev/null+++ b/hyperextract/templates/zh/tcm/herb_property_model.py@@ -0,0 +1,117 @@+"""药物性味归经 - 提取单味药的四气五味、归经、毒性及推荐剂量。++适用于中药基础数据库构建。+"""++from typing import Any, List+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoModel+++class HerbProperty(BaseModel):+ """药物性味归经信息"""+ name: str = Field(description="药物正名")+ alternativeNames: List[str] = Field(description="别名、俗称", default_factory=list)+ properties: List[str] = Field(description="四气:寒、热、温、凉、平", default_factory=list)+ flavors: List[str] = Field(description="五味:酸、苦、甘、辛、咸", default_factory=list)+ meridians: List[str] = Field(description="归经:如肺经、肝经、脾经等", default_factory=list)+ toxicity: str = Field(description="毒性:无毒、小毒、有毒、大毒", default="无毒")+ dosage: str = Field(description="推荐剂量", default="")+ collection: str = Field(description="采集时间和方法", default="")+ processing: str = Field(description="炮制方法", default="")+ indications: List[str] = Field(description="功效主治", default_factory=list)+ contraindications: List[str] = Field(description="配伍禁忌", default_factory=list)+++_PROMPT = """## 角色与任务+你是一位专业的中药学家,请从文本中提取单味药的性味归经、毒性及推荐剂量等信息。++## 核心概念定义+- **对象 (Object)**:本模板中的"对象"指单一中药药物,包含正名、别名、四气、五味、归经、毒性、剂量、采集、炮制、功效主治、配伍禁忌等多个字段的结构化信息。++## 提取规则+1. 识别文本的核心药物主体+2. 提取药物的正名和所有别名、俗称+3. 提取药物的四气(寒、热、温、凉、平)+4. 提取药物的五味(酸、苦、甘、辛、咸)+5. 提取药物的归经(如肺经、肝经、脾经等)+6. 提取药物的毒性(无毒、小毒、有毒、大毒)+7. 提取药物的推荐剂量+8. 提取药物的采集时间和方法+9. 提取药物的炮制方法+10. 提取药物的功效主治+11. 提取药物的配伍禁忌++### 约束条件+- 只提取文本中明确提及的信息,不添加额外内容+- 保持客观准确,符合中药学专业术语规范++### 源文本:+"""+++class HerbPropertyModel(AutoModel[HerbProperty]):+ """+ 适用文档: 本草典籍、中药志、中药大辞典等++ 功能介绍:+ 提取单味药的四气五味、归经、毒性及推荐剂量,适用于中药基础数据库构建。++ Example:+ >>> template = HerbPropertyModel(llm_client=llm, embedder=embedder)+ >>> template.feed_text("人参,味甘,微寒,无毒。主补五脏,安精神...")+ >>> print(template.data.name)+ >>> print(template.data.properties)+ >>> print(template.data.flavors)+ >>> print(template.data.meridians)+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化药物性味归经模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ data_schema=HerbProperty,+ llm_client=llm_client,+ embedder=embedder,+ prompt=_PROMPT,+ max_workers=max_workers,+ verbose=verbose,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k: int = 3,+ ):+ """+ 展示药物性味归经信息。++ Args:+ top_k: 问答使用的条目数量,默认为 3+ """+ def label_extractor(item: HerbProperty) -> str:+ return f"{item.name} ({', '.join(item.properties)},{', '.join(item.flavors)})"++ super().show(+ label_extractor=label_extractor,+ top_k=top_k,+ )diff --git a/hyperextract/templates/zh/tcm/meridian_acupoint_spatial.py b/hyperextract/templates/zh/tcm/meridian_acupoint_spatial.pydeleted file mode 100644index b1a412f..0000000--- a/hyperextract/templates/zh/tcm/meridian_acupoint_spatial.py+++ /dev/null@@ -1,120 +0,0 @@-from typing import List, Optional, Any, Tuple-from pydantic import BaseModel, Field-from langchain_core.language_models.chat_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoSpatialGraph--# ==============================================================================-# 1. Schema 定义-# ==============================================================================--class AcupointNode(BaseModel):- """经络系统中的学位或体表部位。"""- name: str = Field(description="穴位标准名称(如:足三里、合谷)或身体部位(如:外膝眼下三寸)。")- belongs_to_meridian: Optional[str] = Field(description="归属经脉(如:足阳明胃经)。部位节点可留空。")- function_main: Optional[str] = Field(description="主治功效概要(如:理脾胃、调气血)。")--class MeridianFlow(BaseModel):- """描述经气在人体空间的流注方向或定位关系。"""- source: str = Field(description="起点穴位或部位。")- target: str = Field(description="终点穴位或部位。")- direction: str = Field(description="流注方向(如:循行向下、绕过、直入)。")- spatial_desc: str = Field(description="具体的空间定位描述(如‘循胫骨外廉’、‘入属于胃’)。这是关键的空间信息。")--# ==============================================================================-# 2. 提示词 (Prompts)-# ==============================================================================--_PROMPT = (- "你是一位精通《灵枢·经脉》的经络学家。你的任务是从古籍或医学解剖描述中,解析经络在人体上的空间循行路径及流注关系。\n\n"- "### 核心提取规则:\n"- "1. **解剖定位**:精准提取‘循、入、出、下、绕、挟’等描述空间拓扑的动词。\n"- "2. **流注顺序**:确保提取的连接是有向的,反映经气(Qi)的流动方向。\n"- "3. **归经标注**:对于所有穴位,必须尝试识别并归纳其所述的十二正经或奇经八脉。\n"- "4. **空间细化**:在 `spatial_desc` 中完整保留‘循胫骨外廉’、‘入属于胃’等具体的解剖描述。"-)--_NODE_PROMPT = (- "你是一位人体解剖与穴位专家。请识别文本中出现的穴位名称、解剖标志(如‘鼻之交頞’)及经脉系统。\n\n"- "### 提取要求:\n"- "1. **节点涵盖**:除了标准穴位名,也应提取作为转向点的解剖部位。\n"- "2. **功能关联**:若文中提到穴位的主治作用,应将其记录在 `function_main` 字段。\n"- "3. **层级区分**:区分经脉总称(如足阳明胃经)与具体穴位节点。"-)--_EDGE_PROMPT = (- "你是一位经络循行分析师。请根据已识别的穴位与部位,建立经络的空间流注链条。\n\n"- "### 空间连接要求:\n"- "1. **动词驱动**:关注‘起于’、‘下循’、‘旁约’等词汇,确定方向(Direction)。\n"- "2. **路径描述**:在 `spatial_desc` 中详细记录路径中的空间方位和解剖细节。\n"- "3. **拓扑连续性**:构建连续的流注路径,避免出现孤立的节点对。"-)--# ==============================================================================-# 3. 模板类-# ==============================================================================--class MeridianAcupointSpatial(AutoSpatialGraph[AcupointNode, MeridianFlow]):- """- 适用于:[针灸学教材, 经络挂图, 黄帝内经等经典]-- 一个旨在映射人体经络空间循行轨迹及穴位分布的图谱模板。-- Key Features:- - 将人体视为“气”流动的拓扑地图进行分析。- - 捕获详细的解剖路径描述(如“沿胫骨外侧后缘”)。- - 建立代表经气运行顺序的方向性关系。-- Example:- >>> from hyperextract.templates.zh.tcm import MeridianAcupointSpatial- >>> spatial = MeridianAcupointSpatial(llm_client=llm, embedder=embedder)- >>> text = "胃足阳明之脉,起于鼻之交頞中,旁约太阳之脉,下循鼻外。"- >>> spatial.feed_text(text).show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- extraction_mode: str = "two_stage",- **kwargs: Any- ):- """- 初始化 MeridianAcupointSpatial 图谱。-- Args:- llm_client (BaseChatModel): 用于提取的语言模型客户端。- embedder (Embeddings): 用于索引的嵌入模型。- extraction_mode (str): 提取模式,'one_stage' 或 'two_stage'。默认为 'two_stage'。- **kwargs: 传递给 AutoSpatialGraph 的额外参数。- """- super().__init__(- node_schema=AcupointNode,- edge_schema=MeridianFlow,- node_key_extractor=lambda x: x.name.strip(),- edge_key_extractor=lambda x: f"{x.source}->{x.direction}->{x.target}",- location_in_edge_extractor=lambda x: x.spatial_desc,- nodes_in_edge_extractor=lambda x: (x.source, x.target),- observation_location="人体经络系统 (Human Meridian System)",- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- extraction_mode=extraction_mode,- **kwargs- )-- def show(self, **kwargs):- """- 可视化经络流注网络。-- Args:- **kwargs: 传递给基础 show() 方法的参数。- """- def n_label(node: AcupointNode) -> str:- meridian = f"[{node.belongs_to_meridian}]" if node.belongs_to_meridian else ""- return f"{meridian} {node.name}"- def e_label(edge: MeridianFlow) -> str: return f"{edge.direction} ({edge.spatial_desc})"- super().show(node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs)diff --git a/hyperextract/templates/zh/tcm/meridian_flow_graph.py b/hyperextract/templates/zh/tcm/meridian_flow_graph.pynew file mode 100644index 0000000..4d310b5--- /dev/null+++ b/hyperextract/templates/zh/tcm/meridian_flow_graph.py@@ -0,0 +1,172 @@+"""经络流注图 - 提取十二经脉的循行路线及经气流注次序。++适用于经络理论教学。+"""++from typing import Any+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoGraph+++class MeridianNode(BaseModel):+ """经脉节点"""+ name: str = Field(description="经脉名称:如手太阴肺经、手阳明大肠经等")+ category: str = Field(description="经脉类别:阴经、阳经")+ associatedOrgan: str = Field(description="关联脏腑", default="")+ circulationPath: str = Field(description="循行路线", default="")+++class MeridianFlowRelation(BaseModel):+ """经络流注关系边"""+ source: str = Field(description="源经脉名称")+ target: str = Field(description="目标经脉名称")+ relationType: str = Field(description="关系类型:流注")+ flowOrder: int = Field(description="流注次序")+ connectionPoint: str = Field(description="连接部位", default="")+++_PROMPT = """## 角色与任务+你是一位专业的经络学专家,请从文本中提取十二经脉的循行路线及经气流注次序。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指经脉实体,包括经脉名称、类别、关联脏腑、循行路线等信息。+- **边 (Edge)**:本模板中的"边"指经脉之间的流注关系,包括源经脉、目标经脉、流注次序、连接部位等信息。++## 提取规则+### 节点提取规则+1. 提取所有经脉实体:手太阴肺经、手阳明大肠经、足阳明胃经、足太阴脾经、手少阴心经、手太阳小肠经、足太阳膀胱经、足少阴肾经、手厥阴心包经、手少阳三焦经、足少阳胆经、足厥阴肝经+2. 为每个经脉指定类别:阴经、阳经+3. 提取每个经脉的关联脏腑+4. 提取每个经脉的循行路线++### 关系提取规则+1. 提取经脉之间的流注关系+2. 为每种关系指定类型:流注+3. 提取流注次序+4. 提取连接部位++### 约束条件+- 每条边必须连接已提取的节点+- 不要创建未在文本中提及的实体或关系+- 保持客观准确,符合经络学专业术语规范++### 源文本:+"""++_NODE_PROMPT = """## 角色与任务+你是一位专业的经络学专家,请从文本中提取所有经脉实体作为节点。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指经脉实体,包括经脉名称、类别、关联脏腑、循行路线等信息。++## 提取规则+1. 提取所有经脉实体:手太阴肺经、手阳明大肠经、足阳明胃经、足太阴脾经、手少阴心经、手太阳小肠经、足太阳膀胱经、足少阴肾经、手厥阴心包经、手少阳三焦经、足少阳胆经、足厥阴肝经+2. 为每个经脉指定类别:阴经、阳经+3. 提取每个经脉的关联脏腑+4. 提取每个经脉的循行路线++### 源文本:+"""++_EDGE_PROMPT = """## 角色与任务+你是一位专业的经络学专家,请从给定经脉列表中提取经脉之间的流注关系。++## 核心概念定义+- **节点 (Node)**:本模板中的"节点"指经脉实体,作为流注关系的参与者。+- **边 (Edge)**:本模板中的"边"指经脉之间的流注关系,包括源经脉、目标经脉、流注次序、连接部位等信息。++## 提取规则+1. 提取经脉之间的流注关系+2. 为每种关系指定类型:流注+3. 提取流注次序+4. 提取连接部位++### 约束条件+1. 仅从下方已知经脉列表中提取边+2. 不要创建未列出的经脉+3. 每条边必须包含 source、target、relationType、flowOrder++"""+++class MeridianFlowGraph(AutoGraph[MeridianNode, MeridianFlowRelation]):+ """+ 适用文档: 黄帝内经、经络学教材、针灸学教材等++ 功能介绍:+ 提取十二经脉的循行路线及经气流注次序,适用于经络理论教学。++ Example:+ >>> template = MeridianFlowGraph(llm_client=llm, embedder=embedder)+ >>> template.feed_text("手太阴肺经起于中焦,下络大肠...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化经络流注图模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ node_schema=MeridianNode,+ edge_schema=MeridianFlowRelation,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: f"{x.source}|{x.relationType}|{x.target}",+ nodes_in_edge_extractor=lambda x: (x.source, x.target),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示经络流注图。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def node_label_extractor(node: MeridianNode) -> str:+ return f"{node.name} ({node.category})"++ def edge_label_extractor(edge: MeridianFlowRelation) -> str:+ return f"流注 #{edge.flowOrder}"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_for_search,+ top_k_edges_for_search=top_k_for_search,+ top_k_nodes_for_chat=top_k_for_chat,+ top_k_edges_for_chat=top_k_for_chat,+ )diff --git a/hyperextract/templates/zh/tcm/prescription_composition_graph.py b/hyperextract/templates/zh/tcm/prescription_composition_graph.pydeleted file mode 100644index 8e615c1..0000000--- a/hyperextract/templates/zh/tcm/prescription_composition_graph.py+++ /dev/null@@ -1,122 +0,0 @@-from typing import List, Optional, Any, Tuple-from pydantic import BaseModel, Field-from langchain_core.language_models.chat_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoGraph--# ==============================================================================-# 1. Schema 定义-# ==============================================================================--class HerbNode(BaseModel):- """中药方剂中的核心实体:方剂名或单味药材。"""- name: str = Field(description="方剂名称(如‘麻黄汤’)或药材名称(如‘桂枝’)。")- category: str = Field(description="实体类别(如:方剂、解表药、补气药)。")- nature_flavor: Optional[str] = Field(description="药材的性味归经(如:辛温,归肺膀胱经)。对于方剂可留空。")--class CompositionRole(BaseModel):- """描述方剂中药材的配伍地位(君臣佐使)及具体用法。"""- source: str = Field(description="所属方剂名称。")- target: str = Field(description="组成该方剂的药材名称。")- role: str = Field(description="配伍角色:君药、臣药、佐药、使药。如未明确指出,可填‘组成’。")- dosage: Optional[str] = Field(description="药材的剂量(如:三钱、9g)。保留原单位。")- preparation: Optional[str] = Field(description="特殊炮制或煎煮方法(如:先煎、后下、蜜炙、去皮)。")- explanation: str = Field(description="该药在方中的具体功效解释(如:发汗解表以散风寒)。")--# ==============================================================================-# 2. 提示词 (Prompts)-# ==============================================================================--_PROMPT = (- "你是一位精通‘君臣佐使’理论的中医方剂学家。你的任务是从方剂学教材或古籍中解析方剂的严密组方结构及配伍内涵。\n\n"- "### 核心提取规则:\n"- "1. **角色界定**:必须准确识别君药(核心治疗)、臣药(辅助)、佐药(兼治/制约)、使药(引经/调和)。\n"- "2. **细节保留**:严禁遗漏剂量和炮制要求(如‘生用’、‘酒炒’),这些对方剂的安全性和有效性至关重要。\n"- "3. **术语标准**:提取药名时去除琐碎修饰词,但炮制信息应放入 `preparation` 字段。\n"- "4. **逻辑解释**:在 `explanation` 中总结该药为何处于此配伍地位及其发挥的具体药理作用。"-)--_NODE_PROMPT = (- "你是一位资深中医文档分析师。请识别文本中出现的方剂名和单味药材名称。\n\n"- "### 提取要求:\n"- "1. **节点去重**:同一方剂名在文中多次出现时应视为一个节点。\n"- "2. **性味补充**:尽可能利用文本线索补充药材的‘性味归经’属性。\n"- "3. **实体边界**:药名应简洁,例如‘炙甘草’提取为药名‘甘草’,炮制属性‘炙’记录在后期连接环节。"-)--_EDGE_PROMPT = (- "你是一位精通方剂配伍理论的分析师。请在已识别的方剂与药材间建立‘组方关系’。\n\n"- "### 关系提取要求:\n"- "1. **角色属性**:依据文本中‘为君’、‘辅助’、‘兼见’等表述,映射到标准的‘君、臣、佐、使’角色。\n"- "2. **剂量解析**:准确识别数量及单位(如‘三钱’、‘12g’)。\n"- "3. **煎服法捕捉**:捕捉‘先煎’、‘后下’、‘烊化’等特殊煎服法描述放入 `preparation`。"-)--# ==============================================================================-# 3. 模板类-# ==============================================================================--class PrescriptionCompositionGraph(AutoGraph[HerbNode, CompositionRole]):- """- 适用于:[方剂学教材, 伤寒杂病论医案, 中药处方]-- 一个基于“君臣佐使”理论对方剂结构进行层级解构的专用图谱模板。-- Key Features:- - 提取方剂层级结构及具体的角色分配(君臣佐使)。- - 捕获精确的剂量和炮制煎服方法。- - 将药材与其在方剂环境下的药理解释相关联。-- Example:- >>> from hyperextract.templates.zh.tcm import PrescriptionCompositionGraph- >>> graph = PrescriptionCompositionGraph(llm_client=llm, embedder=embedder)- >>> text = "麻黄汤中,麻黄为君,发汗解表;桂枝为臣,助麻黄解肌。"- >>> graph.feed_text(text).show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- extraction_mode: str = "two_stage",- **kwargs: Any- ):- """- 初始化 PrescriptionCompositionGraph。-- Args:- llm_client (BaseChatModel): 用于提取的语言模型客户端。- embedder (Embeddings): 用于索引的嵌入模型。- extraction_mode (str): 提取模式,'one_stage' 或 'two_stage'。默认为 'two_stage'。- **kwargs: 传递给 AutoGraph 的额外参数。- """- super().__init__(- node_schema=HerbNode,- edge_schema=CompositionRole,- node_key_extractor=lambda x: x.name.strip(),- # 边的主键:方剂-角色-药材- edge_key_extractor=lambda x: f"{x.source}-{x.role}-{x.target}",- nodes_in_edge_extractor=lambda x: (x.source, x.target),- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- extraction_mode=extraction_mode,- **kwargs- )-- def show(self, **kwargs):- """- 可视化方剂配伍结构。-- Args:- **kwargs: 传递给基础 show() 方法的参数。- """- def n_label(node: HerbNode) -> str: return f"{node.name} [{node.category}]"- def e_label(edge: CompositionRole) -> str:- extra = f"({edge.dosage})" if edge.dosage else ""- prep = f"[{edge.preparation}]" if edge.preparation else ""- return f"{edge.role}{extra}{prep}: {edge.explanation}"- super().show(node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs)diff --git a/hyperextract/templates/zh/tcm/prescription_manual_set.py b/hyperextract/templates/zh/tcm/prescription_manual_set.pydeleted file mode 100644index e8a4aaa..0000000--- a/hyperextract/templates/zh/tcm/prescription_manual_set.py+++ /dev/null@@ -1,96 +0,0 @@-from typing import List, Optional, Any-from pydantic import BaseModel, Field-from langchain_core.language_models.chat_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoSet--# ==============================================================================-# 1. Schema 定义-# ==============================================================================---class PrescriptionManual(BaseModel):- """方剂的完整使用说明书条目。"""-- prescription_name: str = Field(description="方剂的标准名称。")- main_functions: List[str] = Field(- description="核心功效(如:平肝潜阳、镇心安神)。"- )- indications: List[str] = Field(description="主治病症(如:高血压、头痛眩晕)。")- contraindications: List[str] = Field(- description="禁忌人群或情况(如:孕妇慎用、脾胃虚寒者忌)。"- )- modifications: List[str] = Field(- description="随症加减的常见法则(如:兼有胸闷者加瓜蒌)。"- )- usage_method: Optional[str] = Field(description="服用方法或煎煮说明。")---# ==============================================================================-# 2. 提示词 (Prompts)-# ==============================================================================--_PROMPT = (- "你是一位致力于整理中医典籍的临床药理专家。你的任务是从各类文献中归纳并富集成标准的方剂说明书。\n\n"- "### 知识累加规则:\n"- "1. **信息聚合**:如果不同文本提到了同一个方剂,必须将新的主治功效、加减法或禁忌证补充到该条目中,形成富集后的详尽档案。\n"- "2. **结构标准化**:将叙述性文字转化为结构化的列表。例如,在 `contraindications` 中明确区分生理禁忌(如孕妇)与病理禁忌。\n"- "3. **加减法捕捉**:细致记录‘若...则加/减...’的化裁规律,这对方剂的动态应用至关重要。\n"- "4. **安全性优先**:重点关注原文中提及的任何不良反应或服用警示信息。"-)--# ==============================================================================-# 3. 模板类-# ==============================================================================---class PrescriptionManualSet(AutoSet[PrescriptionManual]):- """- 适用于:[中国药典, 药品说明书, 经典方剂汇编]-- 一个用于从多源中医文本中综合合成方剂详细用药手册的知识累加器模板。-- Key Features:- - 使用“方剂名称”作为唯一键来合并和丰富来自不同来源的数据。- - 聚合多维信息,包括功效、主治病症、随症加减法和禁忌证。- - 自动处理去重和增量知识更新。-- Example:- >>> from hyperextract.templates.zh.tcm import PrescriptionManualSet- >>> manual_set = PrescriptionManualSet(llm_client=llm, embedder=embedder)- >>> text1 = "六味地黄丸,滋阴补肾,用于腰膝酸软。"- >>> text2 = "六味地黄丸禁用于脾胃虚寒、食少便溏者。"- >>> manual_set.feed_text(text1).feed_text(text2).show()- """-- def __init__(self, llm_client: BaseChatModel, embedder: Embeddings, **kwargs: Any):- """- 初始化 PrescriptionManualSet。-- Args:- llm_client (BaseChatModel): 用于提取的语言模型客户端。- embedder (Embeddings): 用于索引和检索的嵌入模型。- **kwargs: 传递给 AutoSet 的额外参数。- """- super().__init__(- schema=PrescriptionManual,- # 以方剂名称作为唯一键进行归并- key_extractor=lambda x: x.prescription_name.strip(),- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- **kwargs,- )-- def show(self, **kwargs):- """- 可视化富集后的方剂说明书集合。-- Args:- **kwargs: 传递给基础 show() 方法的参数。- """-- def label_func(item: PrescriptionManual) -> str:- return f"【{item.prescription_name}】主治: {', '.join(item.indications[:3])}... | 禁忌: {', '.join(item.contraindications)}"-- super().show(label_extractor=label_func, **kwargs)diff --git a/hyperextract/templates/zh/tcm/prescription_modification.py b/hyperextract/templates/zh/tcm/prescription_modification.pynew file mode 100644index 0000000..3167f7e--- /dev/null+++ b/hyperextract/templates/zh/tcm/prescription_modification.py@@ -0,0 +1,170 @@+"""处方加减逻辑 - 提取基于特定症状对基础方剂进行的药物加减(如"随证加减")。++适用于临证用药规律分析。+"""++from typing import Any+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from pydantic import BaseModel, Field+from hyperextract.types import AutoGraph++class PrescriptionEntity(BaseModel):+ """处方实体节点"""+ name: str = Field(description="实体名称,如方剂名、药物名、症状名")+ category: str = Field(description="实体类型:方剂、药物、症状")+ description: str = Field(description="简要描述", default="")++class ModificationRelation(BaseModel):+ """处方加减关系边"""+ source: str = Field(description="源实体,如症状或证型")+ target: str = Field(description="目标实体,如药物")+ modificationType: str = Field(description="加减类型:加、减、替换")+ reason: str = Field(description="加减原因", default="")+ dosage: str = Field(description="药物剂量", default="")+ baseFormula: str = Field(description="基础方剂名称", default="")++_NODE_PROMPT = """## 角色与任务+你是一位专业的中医方剂专家,请从文本中提取所有关键实体作为节点。++## 核心概念定义+- **节点 (Node)**:图谱中的实体+- **边 (Edge)**:节点之间的二元关系++## 提取规则+1. 提取所有方剂、药物、症状等实体+2. 为每个实体指定类型:方剂、药物、症状+3. 保持实体名称与原文一致+4. 方剂应包含完整的方剂名称+5. 药物应包含具体的中药名称+6. 症状应包含具体的临床表现++### 源文本:+"""++_EDGE_PROMPT = """## 角色与任务+你是一位专业的中医方剂专家,请从给定实体列表中提取处方加减逻辑。++## 核心概念定义+- **节点 (Node)**:图谱中的实体+- **边 (Edge)**:节点之间的二元关系++## 提取规则+1. 仅从下方已知实体列表中提取边+2. 不要创建未列出的实体+3. 每条边必须包含 source、target、modificationType+4. source 应为症状或证型+5. target 应为药物+6. modificationType 应为:加、减、替换+7. 提取加减的原因和剂量信息+8. 提取基础方剂名称++"""++_PROMPT = """## 角色与任务+你是一位专业的中医方剂专家,请从文本中提取实体和处方加减逻辑。++## 核心概念定义+- **节点 (Node)**:图谱中的实体,如方剂、药物、症状等+- **边 (Edge)**:节点之间的二元关系,如症状与药物的加减关系++## 提取规则+### 节点提取规则+1. 提取所有方剂、药物、症状等实体+2. 为每个实体指定类型:方剂、药物、症状+3. 保持实体名称与原文一致++### 关系提取规则+1. 提取基于特定症状对基础方剂进行的药物加减+2. 每条边必须包含 source、target、modificationType+3. source 应为症状或证型+4. target 应为药物+5. modificationType 应为:加、减、替换+6. 提取加减的原因和剂量信息+7. 提取基础方剂名称++### 源文本:+"""++# ==============================================================================+# 3. 模板类+# ==============================================================================++class PrescriptionModification(AutoGraph[PrescriptionEntity, ModificationRelation]):+ """+ 适用文档: 中医方剂学著作、临床医案++ 功能介绍:+ 从中医文本中提取基于特定症状对基础方剂进行的药物加减逻辑,+ 如"随证加减"等临证用药规律。++ Example:+ >>> template = PrescriptionModification(llm_client=llm, embedder=embedder)+ >>> template.feed_text("...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化处方加减逻辑模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ node_schema=PrescriptionEntity,+ edge_schema=ModificationRelation,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: f"{x.source}|{x.modificationType}|{x.target}",+ nodes_in_edge_extractor=lambda x: (x.source, x.target),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示处方加减逻辑图。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def node_label_extractor(node: PrescriptionEntity) -> str:+ return f"{node.name} ({node.category})"++ def edge_label_extractor(edge: ModificationRelation) -> str:+ return f"{edge.modificationType}: {edge.target}"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_for_search=top_k_for_search,+ top_k_for_chat=top_k_for_chat,+ )diff --git a/hyperextract/templates/zh/tcm/processing_method.py b/hyperextract/templates/zh/tcm/processing_method.pynew file mode 100644index 0000000..18edd76--- /dev/null+++ b/hyperextract/templates/zh/tcm/processing_method.py@@ -0,0 +1,107 @@+"""炮制方法列表 - 提取药物的不同炮制方法(如蜜炙、酒炒)及其对药效的影响。++适用于中药炮制规范、饮片管理。+"""++from typing import Any+from pydantic import BaseModel, Field+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoList+++class ProcessingMethodItem(BaseModel):+ """炮制方法条目"""+ herbName: str = Field(description="药物名称")+ methodName: str = Field(description="炮制方法名称:如蜜炙、酒炒、醋制、盐制等")+ process: str = Field(description="具体炮制工艺流程")+ effectChange: str = Field(description="炮制对药效的影响")+ application: str = Field(description="适用病症或方剂")+++_PROMPT = """## 角色与任务+你是一位专业的中药炮制专家,请从文本中提取药物的不同炮制方法及其对药效的影响。++## 核心概念定义+- **条目 (Item)**:本模板中的"条目"指单一炮制方法,包含药物名称、炮制方法名称、具体工艺流程、对药效的影响、适用病症或方剂等字段的结构化信息。++## 提取规则+1. 识别文本中提到的所有药物及其炮制方法+2. 提取每种炮制方法的名称(如蜜炙、酒炒、醋制、盐制等)+3. 提取每种炮制方法的具体工艺流程+4. 提取炮制对药效的影响+5. 提取该炮制方法的适用病症或方剂++### 约束条件+- 只提取文本中明确提及的信息,不添加额外内容+- 保持客观准确,符合中药炮制专业术语规范++### 源文本:+"""+++class ProcessingMethod(AutoList[ProcessingMethodItem]):+ """+ 适用文档: 中药炮制规范、饮片管理手册、本草典籍等++ 功能介绍:+ 提取药物的不同炮制方法(如蜜炙、酒炒)及其对药效的影响,适用于中药炮制规范、饮片管理。++ Example:+ >>> template = ProcessingMethod(llm_client=llm, embedder=embedder)+ >>> template.feed_text("甘草:蜜炙甘草,取净甘草片,加入炼蜜拌匀...")+ >>> for item in template.data:+ >>> print(item.methodName)+ >>> print(item.effectChange)+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化炮制方法列表模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ item_schema=ProcessingMethodItem,+ llm_client=llm_client,+ embedder=embedder,+ prompt=_PROMPT,+ max_workers=max_workers,+ verbose=verbose,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示炮制方法列表。++ Args:+ top_k_for_search: 语义检索返回的条目数量,默认为 3+ top_k_for_chat: 问答使用的条目数量,默认为 3+ """+ def label_extractor(item: ProcessingMethodItem) -> str:+ return f"{item.herbName} - {item.methodName}"++ super().show(+ label_extractor=label_extractor,+ top_k_for_search=top_k_for_search,+ top_k_for_chat=top_k_for_chat,+ )diff --git a/hyperextract/templates/zh/tcm/pulse_tongue_record.py b/hyperextract/templates/zh/tcm/pulse_tongue_record.pynew file mode 100644index 0000000..d23b231--- /dev/null+++ b/hyperextract/templates/zh/tcm/pulse_tongue_record.py@@ -0,0 +1,104 @@+"""舌脉特征提取 - 结构化提取舌象(质、苔)与脉象描述,用于统计分析。++适用于中医诊断客观化研究。+"""++from typing import Any+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from pydantic import BaseModel, Field+from hyperextract.types import AutoList++class PulseTongueItem(BaseModel):+ """舌脉特征项"""+ type: str = Field(description="特征类型:舌象、脉象")+ subType: str = Field(description="子类型:如舌质、舌苔、脉位、脉率、脉势等")+ feature: str = Field(description="具体特征描述,如淡红、薄白、浮、沉、迟、数等")+ description: str = Field(description="详细描述", default="")+ clinicalSignificance: str = Field(description="临床意义", default="")+ source: str = Field(description="来源,如医案名称、章节等", default="")++_PROMPT = """## 角色与任务+你是一位专业的中医诊断专家,请从文本中提取舌象和脉象的特征信息。++## 核心概念定义+- **条目 (Item)**:从文本中提取的重复模式实例,如舌象特征或脉象特征++## 提取规则+1. 提取所有舌象特征,包括舌质(颜色、形态)、舌苔(颜色、厚薄、干湿等)+2. 提取所有脉象特征,包括脉位(浮、沉)、脉率(迟、数)、脉势(有力、无力)等+3. 为每个特征指定类型和子类型+4. 保持特征描述与原文一致+5. 提取特征的临床意义(如果有)+6. 提取特征的来源信息(如果有)++### 源文本:+"""++# ==============================================================================+# 3. 模板类+# ==============================================================================++class PulseTongueRecord(AutoList[PulseTongueItem]):+ """+ 适用文档: 中医医案、诊断记录++ 功能介绍:+ 从中医文本中结构化提取舌象(质、苔)与脉象描述,用于统计分析和中医诊断客观化研究。++ Example:+ >>> template = PulseTongueRecord(llm_client=llm, embedder=embedder)+ >>> template.feed_text("...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化舌脉特征提取模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ item_schema=PulseTongueItem,+ llm_client=llm_client,+ embedder=embedder,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示舌脉特征记录。++ Args:+ top_k_for_search: 语义检索返回的条目数量,默认为 3+ top_k_for_chat: 问答使用的条目数量,默认为 3+ """+ def item_label_extractor(item: PulseTongueItem) -> str:+ return f"{item.type} - {item.subType}: {item.feature}"++ super().show(+ item_label_extractor=item_label_extractor,+ top_k_for_search=top_k_for_search,+ top_k_for_chat=top_k_for_chat,+ )diff --git a/hyperextract/templates/zh/tcm/syndrome_reasoning_graph.py b/hyperextract/templates/zh/tcm/syndrome_reasoning_graph.pynew file mode 100644index 0000000..9f29ccb--- /dev/null+++ b/hyperextract/templates/zh/tcm/syndrome_reasoning_graph.py@@ -0,0 +1,165 @@+"""辨证论治逻辑图 - 建模 {症状群} -> 证型 -> 治则 -> {处方} 的完整推理链条。++适用于医案数据挖掘、名老中医经验传承。+"""++from typing import Any, List+from langchain_core.language_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from pydantic import BaseModel, Field+from hyperextract.types import AutoHypergraph++class TCMEntity(BaseModel):+ """中医实体节点"""+ name: str = Field(description="实体名称,如症状、证型、治则、药物等")+ category: str = Field(description="实体类型:症状、证型、治则、药物")+ description: str = Field(description="简要描述", default="")++class SyndromeReasoningEdge(BaseModel):+ """辨证论治逻辑边"""+ nodes: List[str] = Field(description="参与推理的节点列表,按推理顺序排列:[症状1, 症状2, ..., 证型, 治则, 药物1, 药物2, ...]")+ reasoningType: str = Field(description="推理类型:辨证论治、随证加减")+ reasoningProcess: str = Field(description="推理过程描述", default="")+ source: str = Field(description="推理来源,如医案名称、章节等", default="")++_NODE_PROMPT = """## 角色与任务+你是一位专业的中医辨证论治专家,请从文本中提取所有关键实体作为节点。++## 核心概念定义+- **节点 (Node)**:图谱中的实体+- **边 (Edge)**:连接多个节点的超边,表达复杂的推理关系++## 提取规则+1. 提取所有症状、证型、治则、药物等实体+2. 为每个实体指定类型:症状、证型、治则、药物+3. 保持实体名称与原文一致+4. 症状应包含望闻问切所获得的各种临床表现+5. 证型应包含中医诊断的证候类型+6. 治则应包含治疗原则和方法+7. 药物应包含处方中的各种中药++### 源文本:+"""++_EDGE_PROMPT = """## 角色与任务+你是一位专业的中医辨证论治专家,请从给定实体列表中提取辨证论治的推理逻辑。++## 核心概念定义+- **节点 (Node)**:图谱中的实体+- **边 (Edge)**:连接多个节点的超边,表达复杂的推理关系++## 提取规则+1. 仅从下方已知实体列表中提取边+2. 不要创建未列出的实体+3. 每条边必须包含 nodes、reasoningType、reasoningProcess+4. nodes 列表必须按推理顺序排列:[症状1, 症状2, ..., 证型, 治则, 药物1, 药物2, ...]+5. reasoningType 应为"辨证论治"或"随证加减"+6. reasoningProcess 应详细描述从症状到证型、证型到治则、治则到处方的推理过程++"""++_PROMPT = """## 角色与任务+你是一位专业的中医辨证论治专家,请从文本中提取中医实体和它们之间的辨证论治推理逻辑。++## 核心概念定义+- **节点 (Node)**:图谱中的实体,如症状、证型、治则、药物等+- **边 (Edge)**:连接多个节点的超边,表达复杂的推理关系++## 提取规则+### 节点提取规则+1. 提取所有症状、证型、治则、药物等实体+2. 为每个实体指定类型:症状、证型、治则、药物+3. 保持实体名称与原文一致++### 边提取规则+1. 提取从症状到证型、证型到治则、治则到处方的完整推理链条+2. 每条边必须包含 nodes、reasoningType、reasoningProcess+3. nodes 列表必须按推理顺序排列:[症状1, 症状2, ..., 证型, 治则, 药物1, 药物2, ...]+4. reasoningType 应为"辨证论治"或"随证加减"+5. reasoningProcess 应详细描述推理过程++### 源文本:+"""++# ==============================================================================+# 3. 模板类+# ==============================================================================++class SyndromeReasoningGraph(AutoHypergraph[TCMEntity, SyndromeReasoningEdge]):+ """+ 适用文档: 中医医案、名医临床实录++ 功能介绍:+ 从中医医案中提取辨证论治的完整推理链条,建模 {症状群} -> 证型 -> 治则 -> {处方} 的逻辑关系,+ 支持复杂的多实体关联关系。++ Example:+ >>> template = SyndromeReasoningGraph(llm_client=llm, embedder=embedder)+ >>> template.feed_text("...")+ >>> template.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "two_stage",+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化辨证论治逻辑图模板。++ Args:+ llm_client: LLM 客户端,用于知识提取+ embedder: 嵌入模型,用于语义检索+ extraction_mode: 提取模式,可选 "one_stage"(同时提取节点和边)+ 或 "two_stage"(先提取节点,再提取边),默认为 "two_stage"+ max_workers: 最大工作线程数,默认为 10+ verbose: 是否输出详细日志,默认为 False+ **kwargs: 其他技术参数,传递给基类+ """+ super().__init__(+ node_schema=TCMEntity,+ edge_schema=SyndromeReasoningEdge,+ node_key_extractor=lambda x: x.name,+ edge_key_extractor=lambda x: f"{x.reasoningType}|{'-'.join(x.nodes)}",+ nodes_in_edge_extractor=lambda x: x.nodes,+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ):+ """+ 展示辨证论治逻辑图。++ Args:+ top_k_for_search: 语义检索返回的节点/边数量,默认为 3+ top_k_for_chat: 问答使用的节点/边数量,默认为 3+ """+ def node_label_extractor(node: TCMEntity) -> str:+ return f"{node.name} ({node.category})"++ def edge_label_extractor(edge: SyndromeReasoningEdge) -> str:+ return edge.reasoningType++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_for_search=top_k_for_search,+ top_k_for_chat=top_k_for_chat,+ )diff --git a/hyperextract/templates/zh/tcm/syndrome_treatment_loop.py b/hyperextract/templates/zh/tcm/syndrome_treatment_loop.pydeleted file mode 100644index 578f519..0000000--- a/hyperextract/templates/zh/tcm/syndrome_treatment_loop.py+++ /dev/null@@ -1,117 +0,0 @@-from typing import List, Optional, Any, Tuple-from pydantic import BaseModel, Field-from langchain_core.language_models.chat_models import BaseChatModel-from langchain_core.embeddings import Embeddings-from hyperextract.types import AutoGraph--# ==============================================================================-# 1. Schema 定义-# ==============================================================================--class TcmConceptNode(BaseModel):- """中医诊疗过程中涉及的概念:症状体征、证型、治法、方药。"""- name: str = Field(description="概念名称,如‘胁肋胀痛’(症状)、‘肝气郁结’(证型)、‘疏肝解郁’(治法)。")- category: str = Field(description="实体类别:症状、证候、病机、治法、方剂、药物。")- detail: Optional[str] = Field(description="对该概念的补充描述(如‘苔薄白、脉弦’)。")--class ClinicalLogic(BaseModel):- """诊疗逻辑链条中的推导关系。"""- source: str = Field(description="前导概念(如:某一症状)。")- target: str = Field(description="推导出结论(如:某一证型)。")- logic_type: str = Field(description="逻辑类型:辨证为、导致(病机)、确立(治法)、选用(方药)。")- reasoning: str = Field(description="具体的推导依据或说明(如‘因舌苔白腻,故知湿困脾胃’)。")--# ==============================================================================-# 2. 提示词 (Prompts)-# ==============================================================================--_PROMPT = (- "你是一位临床经验丰富的中医学家。你的任务是从复杂的医案或古籍中逻辑化地提取‘辨证论治’全过程。\n\n"- "### 核心提取规则:\n"- "1. **逻辑链条**:必须构建‘症状 -> 证候/病机 -> 治法 -> 方药’的完整逻辑回路。\n"- "2. **术语对齐**:使用标准的中医术语。例如,将‘不想吃饭’标准化为‘纳呆’,‘嗓子不舒服’标准化为‘咽干/咽痛’。\n"- "3. **因果保留**:关键是要提取出‘为何得出此证’和‘为何立此法’的证据,保存在 `reasoning` 字段中。\n"- "4. **主次分明**:识别主证(Key Symptoms)并将其与一般随见症状区分开。"-)--_NODE_PROMPT = (- "你是一位中医知识图谱专家。请从医案中识别所有诊疗相关的核心概念。\n\n"- "### 提取规则:\n"- "1. **分类识别**:严格区分症状(Symptom)、证候(Syndrome)、治法(Therapy)与方药(Formula/Herb)。\n"- "2. **细节捕捉**:舌相、脉相必须作为症状节点的 `detail` 属性进行提取。\n"- "3. **实体统一**:确保同一个概念在不同句子中出现时使用统一的、标准化的名称。"-)--_EDGE_PROMPT = (- "你是一位中医临床逻辑分析师。请根据已识别的概念,建立它们之间的诊疗映射关系。\n\n"- "### 逻辑连接规则:\n"- "1. **辨证连接**:将关键症状连接到其归纳出的证候(逻辑类型:‘辨证为’)。\n"- "2. **立法连接**:将证候连接到根据病机确立的治法(逻辑类型:‘确立治法’)。\n"- "3. **处方连接**:将治法连接到最终选用的方剂或主药(逻辑类型:‘选用方药’)。\n"- "4. **证据关联**:在 `reasoning` 字段中详细解释该逻辑推导的具体依据。"-)--# ==============================================================================-# 3. 模板类-# ==============================================================================--class SyndromeTreatmentLoop(AutoGraph[TcmConceptNode, ClinicalLogic]):- """- 适用于:[中医医案, 诊断学教材, 诊疗指南]-- 一个专门逻辑化捕获“症状 -> 证候 -> 治法 -> 方药”这一核心中医诊疗过程的图谱模板。-- Key Features:- - 完整提取中医辨证论治的因果逻辑链条。- - 将散落的临床表现标准化为结构化的逻辑节点。- - 保留每个诊疗结论背后的辨证依据。-- Example:- >>> from hyperextract.templates.zh.tcm import SyndromeTreatmentLoop- >>> loop = SyndromeTreatmentLoop(llm_client=llm, embedder=embedder)- >>> text = "患者两胁胀痛,脉弦,此为肝气郁结,治宜疏肝理气,方用柴胡疏肝散。"- >>> loop.feed_text(text).show()- """-- def __init__(- self,- llm_client: BaseChatModel,- embedder: Embeddings,- *,- extraction_mode: str = "two_stage",- **kwargs: Any- ):- """- 初始化 SyndromeTreatmentLoop。-- Args:- llm_client (BaseChatModel): 用于提取的语言模型客户端。- embedder (Embeddings): 用于索引的嵌入模型。- extraction_mode (str): 提取模式,'one_stage' 或 'two_stage'。默认为 'two_stage'。- **kwargs: 传递给 AutoGraph 的额外参数。- """- super().__init__(- node_schema=TcmConceptNode,- edge_schema=ClinicalLogic,- node_key_extractor=lambda x: x.name.strip(),- edge_key_extractor=lambda x: f"{x.source}->{x.logic_type}->{x.target}",- nodes_in_edge_extractor=lambda x: (x.source, x.target),- llm_client=llm_client,- embedder=embedder,- prompt=_PROMPT,- prompt_for_node_extraction=_NODE_PROMPT,- prompt_for_edge_extraction=_EDGE_PROMPT,- extraction_mode=extraction_mode,- **kwargs- )-- def show(self, **kwargs):- """- 可视化临床辨证论治逻辑闭环。-- Args:- **kwargs: 传递给基础 show() 方法的参数。- """- def n_label(node: TcmConceptNode) -> str: return f"{node.name} [{node.category}]"- def e_label(edge: ClinicalLogic) -> str: return f"[{edge.logic_type}]: {edge.reasoning}"- super().show(node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs)diff --git a/tests/fixtures/test_samples/en/medicine/clinical_guideline_sample.md b/tests/fixtures/test_samples/en/medicine/clinical_guideline_sample.mdnew file mode 100644index 0000000..6bb40dc--- /dev/null+++ b/tests/fixtures/test_samples/en/medicine/clinical_guideline_sample.md@@ -0,0 +1,142 @@+# Guidelines for the Prevention and Treatment of Type 2 Diabetes Mellitus (2020 Edition)++## 1. Overview++Type 2 diabetes mellitus (T2DM) is a common chronic metabolic disease characterized by insulin resistance and insulin secretory deficiency, leading to elevated blood glucose levels. This guideline aims to provide standardized diagnostic and therapeutic recommendations for clinicians to improve the prevention and treatment of type 2 diabetes.++## 2. Diagnostic Criteria++### 2.1 Diabetes Diagnostic Criteria+- Glycated hemoglobin (HbA1c) ≥6.5%+- Fasting plasma glucose (FPG) ≥7.0mmol/L+- 2-hour plasma glucose ≥11.1mmol/L during oral glucose tolerance test (OGTT)+- Random plasma glucose ≥11.1mmol/L with typical diabetes symptoms++### 2.2 Prediabetes Diagnostic Criteria+- Impaired fasting glucose (IFG): 6.1≤FPG<7.0mmol/L+- Impaired glucose tolerance (IGT): 7.8≤2-hour plasma glucose<11.1mmol/L during OGTT+- Glycated hemoglobin: 5.7%≤HbA1c<6.5%++## 3. Treatment Pathway++### 3.1 Lifestyle Intervention+**Recommendation Level**: A+**Evidence Grade**: 1a++All patients with type 2 diabetes should receive lifestyle intervention, including:+- Rational diet: Control total calories, properly distribute carbohydrates, proteins and fats+- Regular exercise: At least 150 minutes of moderate-intensity aerobic exercise per week+- Weight control: Maintain BMI below 24kg/m²+- Smoking cessation and alcohol restriction+- Psychological balance++### 3.2 Glycemic Control Targets+**Recommendation Level**: A+**Evidence Grade**: 1a++- General adults: HbA1c<7.0%+- Elderly patients (over 65 years): HbA1c<7.5% (good health status) or <8.0% (poor health status)+- Gestational diabetes: HbA1c<6.5%+- Patients with severe complications or high hypoglycemia risk: HbA1c<8.0%++### 3.3 Pharmacological Treatment Pathway++#### 3.3.1 Monotherapy+**Recommendation Level**: A+**Evidence Grade**: 1a++- First-line: Metformin: Initial dose 500mg, 2-3 times daily, maximum dose 2000mg/day+- If metformin intolerance, alternatives include:+ - Sulfonylureas: Glimepiride 1-4mg/day+ - Thiazolidinediones: Pioglitazone 15-45mg/day+ - DPP-4 inhibitors: Sitagliptin 100mg/day+ - SGLT-2 inhibitors: Dapagliflozin 10mg/day++#### 3.3.2 Dual Therapy+**Recommendation Level**: A+**Evidence Grade**: 1a++If HbA1c does not reach target after 3 months of monotherapy, initiate dual therapy:+- Metformin + sulfonylureas+- Metformin + thiazolidinediones+- Metformin + DPP-4 inhibitors+- Metformin + SGLT-2 inhibitors+- Metformin + GLP-1 receptor agonists++#### 3.3.3 Triple Therapy+**Recommendation Level**: A+**Evidence Grade**: 1b++If HbA1c does not reach target after 3 months of dual therapy, initiate triple therapy:+- Metformin + sulfonylureas + thiazolidinediones+- Metformin + sulfonylureas + DPP-4 inhibitors+- Metformin + sulfonylureas + SGLT-2 inhibitors+- Metformin + sulfonylureas + GLP-1 receptor agonists++#### 3.3.4 Insulin Therapy+**Recommendation Level**: A+**Evidence Grade**: 1a++If HbA1c does not reach target after 3 months of triple therapy, initiate insulin therapy:+- Basal insulin: Insulin glargine, initial dose 0.1-0.2U/kg/day+- Premixed insulin: Insulin aspart 30, initial dose 0.2-0.4U/kg/day, injected before breakfast and dinner+- Prandial + basal insulin: Insulin aspart + insulin glargine, adjust dose according to blood glucose++## 4. Complication Screening and Management++### 4.1 Macrovascular Complications+**Recommendation Level**: A+**Evidence Grade**: 1a++- Cardiovascular disease: Annual electrocardiogram examination, cardiovascular risk assessment+- Cerebrovascular disease: Regular carotid artery ultrasound examination+- Lower extremity vascular disease: Annual ankle-brachial index (ABI) examination++### 4.2 Microvascular Complications+**Recommendation Level**: A+**Evidence Grade**: 1a++- Diabetic nephropathy: Annual urinary albumin/creatinine ratio (UACR) and serum creatinine examination+- Diabetic retinopathy: Annual fundus examination+- Diabetic neuropathy: Annual foot sensory examination++## 5. Follow-up and Monitoring++### 5.1 Follow-up Frequency+- Newly diagnosed patients: Follow-up every 2-4 weeks until blood glucose reaches target+- Patients with stable blood glucose control: Follow-up every 3-6 months+- Patients with complications: Increase follow-up frequency according to complication severity++### 5.2 Monitoring Indicators+- Blood glucose: Fasting blood glucose, 2-hour postprandial blood glucose+- Glycated hemoglobin: Test every 3 months+- Blood lipids: Test every 6 months+- Blood pressure: Measure at each follow-up+- Body weight: Measure at each follow-up+- Foot examination: Conduct every 3 months++## 6. Special Population Management++### 6.1 Elderly Diabetes Patients+**Recommendation Level**: B+**Evidence Grade**: 2a++- Appropriate relaxation of glycemic control targets to avoid hypoglycemia+- Prioritize drugs with low hypoglycemia risk+- Comprehensive assessment of cardiac and renal function, adjust drug doses++### 6.2 Gestational Diabetes Patients+**Recommendation Level**: A+**Evidence Grade**: 1a++- Strict blood glucose control, targets: Fasting blood glucose <5.3mmol/L, 1-hour postprandial blood glucose <7.8mmol/L, 2-hour postprandial blood glucose <6.7mmol/L+- Insulin therapy is preferred+- OGTT recheck 6-12 weeks after delivery++### 6.3 Patients with Cardiovascular Disease+**Recommendation Level**: A+**Evidence Grade**: 1a++- Prioritize drugs with cardiovascular benefits: SGLT-2 inhibitors, GLP-1 receptor agonists+- Blood pressure control target: <130/80mmHg+- Lipid control target: LDL-C <1.8mmol/L\ No newline at end of filediff --git a/tests/fixtures/test_samples/en/medicine/discharge_summary_sample.md b/tests/fixtures/test_samples/en/medicine/discharge_summary_sample.mdnew file mode 100644index 0000000..bc1cf95--- /dev/null+++ b/tests/fixtures/test_samples/en/medicine/discharge_summary_sample.md@@ -0,0 +1,90 @@+# Discharge Summary++## Basic Information+- **Name**: John Smith+- **Gender**: Male+- **Age**: 65 years+- **Hospitalization Number**: 20260201001+- **Admission Date**: February 1, 2026+- **Discharge Date**: February 10, 2026+- **Admission Diagnosis**: 1. Coronary atherosclerotic heart disease 2. Unstable angina pectoris 3. Hypertension grade 3 (very high risk)+- **Discharge Diagnosis**: 1. Coronary atherosclerotic heart disease 2. Unstable angina pectoris 3. Hypertension grade 3 (very high risk) 4. Type 2 diabetes mellitus++## Hospitalization Course++### February 1, 2026+- **Admission Condition**: The patient was admitted due to "recurrent chest pain for 2 weeks, aggravated for 1 day". On admission, the chest pain was oppressive, located in the precordial area, about the size of a palm, radiating to the left shoulder, lasting about 15 minutes, relieved after rest.+- **Physical Examination**: Temperature 36.5℃, pulse 72 beats/min, respiration 18 breaths/min, blood pressure 160/95mmHg. No cardiac enlargement, heart rate 72 beats/min, regular rhythm, no murmurs in all valve auscultation areas.+- **Auxiliary Examination**: Electrocardiogram: Sinus rhythm, ST segment depression 0.1-0.2mV in V1-V4 leads. Blood routine, liver and kidney function, electrolytes were normal.++### February 2, 2026+- **Examination**: Myocardial enzymes: Troponin I 0.05ng/ml (normal), CK-MB 15U/L (normal). Echocardiogram: Left ventricular ejection fraction 60%, normal chamber sizes, no obvious abnormal wall motion.+- **Treatment**: Aspirin 100mg qd, Clopidogrel 75mg qd, Atorvastatin 20mg qn, Metoprolol 25mg bid, Valsartan 80mg qd, Isosorbide mononitrate 20mg bid.++### February 3, 2026+- **Examination**: Coronary angiography: No significant stenosis in left main coronary artery, 80% stenosis in proximal left anterior descending artery, 50% stenosis in mid circumflex artery, 40% stenosis in mid right coronary artery.+- **Diagnosis**: Coronary atherosclerotic heart disease, unstable angina pectoris, three-vessel disease.++### February 4, 2026+- **Operation**: Coronary artery bypass grafting (CABG)+ - **Surgeons**: Dr. Wang (chief surgeon), Dr. Li (assistant)+ - **Operation Time**: 08:30-14:30+ - **Operation Method**: Off-pump coronary artery bypass grafting+ - **Grafts**: Left internal mammary artery → left anterior descending artery, great saphenous vein → circumflex artery, great saphenous vein → right coronary artery+ - **Intraoperative Condition**: The operation was successful, blood loss about 300ml, no blood transfusion.++### February 5, 2026+- **Postoperative Condition**: The patient was transferred to intensive care unit, with mechanical ventilation, vital signs stable.+- **Treatment**: Dopamine 3μg/kg/min intravenous pump, nitroglycerin 5μg/min intravenous pump, cefuroxime 1.5g q8h intravenous drip, omeprazole 40mg q12h intravenous injection.++### February 6, 2026+- **Postoperative Condition**: The patient was extubated, changed to nasal cannula oxygen, oxygen saturation 98%.+- **Treatment**: Discontinued dopamine, continued nitroglycerin intravenous pump, adjusted to 3μg/min.++### February 7, 2026+- **Postoperative Condition**: The patient was transferred to general ward, vital signs stable, no chest pain, dyspnea or other discomfort.+- **Examination**: Blood routine: White blood cell count 8.5×10⁹/L, hemoglobin 120g/L, platelet count 180×10⁹/L. Liver and kidney function, electrolytes were normal.+- **Treatment**: Discontinued nitroglycerin intravenous pump, changed to isosorbide mononitrate 20mg bid oral.++### February 8, 2026+- **Examination**: Blood glucose: Fasting blood glucose 7.8mmol/L, 2-hour postprandial blood glucose 11.2mmol/L.+- **Diagnosis**: Type 2 diabetes mellitus.+- **Treatment**: Added metformin 500mg bid oral.++### February 9, 2026+- **Examination**: Electrocardiogram: Sinus rhythm, ST segment in V1-V4 leads improved compared to previous.+- **Treatment**: Adjusted metoprolol dose to 50mg bid oral.++### February 10, 2026+- **Discharge Assessment**: The patient's general condition was good, no chest pain, dyspnea or other discomfort, vital signs stable. Wound healing was good, no redness, exudation.+- **Discharge Instructions**: See discharge instructions section.++## Discharge Instructions++### Medication Treatment+- **Antiplatelet drugs**: Aspirin 100mg qd, lifetime use; Clopidogrel 75mg qd, use for 12 months+- **Lipid-lowering drugs**: Atorvastatin 20mg qn, lifetime use+- **β-blockers**: Metoprolol 50mg bid, adjust dose according to heart rate+- **ACEI/ARB**: Valsartan 80mg qd, lifetime use+- **Nitrates**: Isosorbide mononitrate 20mg bid, can gradually reduce dose after symptom relief+- **Antidiabetic drugs**: Metformin 500mg bid, monitor blood glucose+- **Antibiotics**: Cefuroxime axetil 250mg bid, use for 3 days++### Diet and Activity+- **Diet**: Low-salt, low-fat, diabetic diet, control total calories, daily salt intake <5g+- **Activity**: Avoid strenuous exercise within 1 month after surgery, can perform mild activities such as walking; gradually resume normal activities after 3 months+- **Weight**: Control weight, target BMI <24kg/m²++### Follow-up Plan+- **1 week after discharge**: Cardiology outpatient follow-up, recheck blood routine, liver and kidney function, electrolytes+- **2 weeks after discharge**: Suture removal, thoracic surgery outpatient follow-up+- **1 month after discharge**: Cardiology outpatient follow-up, recheck electrocardiogram, echocardiogram+- **3 months after discharge**: Cardiology outpatient follow-up, recheck coronary CTA+- **6 months after discharge**: Cardiology outpatient follow-up, comprehensive assessment of cardiac function++### Notes+- Keep the wound clean and dry, avoid infection+- Take medication on time, do not adjust dosage without authorization+- Regularly monitor blood pressure and blood glucose+- Seek medical attention promptly if chest pain, dyspnea, fever or other discomfort occurs+- Quit smoking and limit alcohol, maintain good living habits\ No newline at end of filediff --git a/tests/fixtures/test_samples/en/medicine/package_insert_sample.md b/tests/fixtures/test_samples/en/medicine/package_insert_sample.mdnew file mode 100644index 0000000..de94b0b--- /dev/null+++ b/tests/fixtures/test_samples/en/medicine/package_insert_sample.md@@ -0,0 +1,158 @@+# Package Insert++## [Drug Name]+Generic Name: Metformin Hydrochloride Sustained-release Tablets+Brand Name: Glucophage+English Name: Metformin Hydrochloride Sustained-release Tablets++## [Ingredients]+The main ingredient of this product is metformin hydrochloride, whose chemical name is 1,1-dimethylbiguanide hydrochloride.+Molecular Formula: C4H11N5·HCl+Molecular Weight: 165.63++## [Properties]+This product is a white or off-white film-coated tablet, which appears white after removing the coating.++## [Indications]+1. For patients with type 2 diabetes mellitus whose blood glucose cannot be controlled satisfactorily by diet alone, especially obese patients, it may also have a weight-reducing effect.+2. It can be effective for patients who respond poorly to sulfonylureas.+3. It can be used in combination with sulfonylureas or insulin to improve blood glucose control.++## [Specification]+500mg (calculated as metformin hydrochloride)++## [Dosage and Administration]+Oral administration, taken with meals or after meals. The usual starting dose is 500mg once daily with dinner. The dose is adjusted according to blood glucose and urine glucose levels, with a maximum daily dose not exceeding 2000mg. If a single daily dose of 2000mg fails to achieve satisfactory efficacy, it can be changed to 1000mg twice daily.++## [Adverse Reactions]+### 1. Common Adverse Reactions (incidence >1%)+- **Gastrointestinal reactions**: Nausea, vomiting, diarrhea, abdominal pain, dyspepsia, heartburn+- **Systemic reactions**: Fatigue, headache, dizziness++### 2. Uncommon Adverse Reactions (incidence 0.1%-1%)+- **Skin reactions**: Rash, pruritus+- **Metabolic abnormalities**: Hypoglycemia (when used in combination with sulfonylureas or insulin)+- **Laboratory test abnormalities**: Elevated lactate dehydrogenase, elevated alanine aminotransferase, elevated aspartate aminotransferase++### 3. Rare Adverse Reactions (incidence <0.1%)+- **Lactic acidosis**: Manifested as fatigue, nausea, vomiting, abdominal pain, deep and rapid breathing, consciousness disturbance+- **Hematological system**: Granulocytopenia, thrombocytopenia+- **Allergic reactions**: Urticaria, angioedema+- **Hepatobiliary abnormalities**: Hepatitis, cholestatic jaundice++### 4. Adverse Reaction Incidence Statistics+| System | Adverse Reaction | Incidence |+| :--- | :--- | :--- |+| **Gastrointestinal** | Nausea | 5.2% |+| **Gastrointestinal** | Vomiting | 2.6% |+| **Gastrointestinal** | Diarrhea | 4.5% |+| **Gastrointestinal** | Abdominal pain | 2.1% |+| **Systemic** | Fatigue | 1.8% |+| **Systemic** | Headache | 1.5% |+| **Skin** | Rash | 0.3% |+| **Metabolic** | Hypoglycemia | 0.2% (when used alone), 1.5% (when used with sulfonylureas) |+| **Hepatobiliary** | Elevated transaminases | 0.1% |+| **Hematological** | Granulocytopenia | <0.1% |++## [Contraindications]+1. **Absolute Contraindications**:+ - Patients allergic to metformin and other ingredients+ - Severe renal impairment (eGFR <30ml/min/1.73m²)+ - Metabolic acidosis (including diabetic ketoacidosis)+ - Severe infection, shock or other diseases that may cause tissue hypoxia+ - Alcoholics+ - Patients with uncorrected vitamin B12 or folate deficiency+ - Within 48 hours before and after intravenous injection of iodinated contrast media++2. **Relative Contraindications**:+ - Renal impairment (eGFR 30-45ml/min/1.73m²)+ - Hepatic impairment+ - Heart failure+ - Severe pulmonary insufficiency+ - Pregnant and lactating women++## [Precautions]+1. **Lactic Acidosis**: Metformin can cause lactic acidosis, which is rare but fatal. Once it occurs, stop taking the drug immediately and seek medical attention.+2. **Renal Function Monitoring**: Renal function should be checked before and during treatment, especially in elderly patients.+3. **Liver Function Monitoring**: Liver function should be checked regularly during treatment.+4. **Blood Glucose Monitoring**: Blood glucose and glycated hemoglobin should be monitored regularly during treatment.+5. **Vitamin B12 Deficiency**: Long-term use of metformin may reduce vitamin B12 absorption, so it is recommended to monitor vitamin B12 levels regularly.+6. **Before and After Surgery**: Metformin should be temporarily discontinued before elective surgery and can be resumed after renal function recovery.+7. **Contrast Examination**: Metformin should be temporarily discontinued 48 hours before and after intravenous injection of iodinated contrast media.++## [Drug Interactions]++### 1. Interactions with Other Antidiabetic Drugs+- **Sulfonylureas**: Combined use may increase the risk of hypoglycemia+- **Insulin**: Combined use may increase the risk of hypoglycemia, and insulin dose should be reduced+- **Meglitinides**: Combined use may increase the risk of hypoglycemia+- **GLP-1 receptor agonists**: Combined use may enhance hypoglycemic effect+- **SGLT-2 inhibitors**: Combined use may enhance hypoglycemic effect and reduce the risk of hypoglycemia++### 2. Interactions with Other Drugs+- **Antihypertensive drugs**: ACEI, ARB, calcium channel blockers, etc. may enhance the hypoglycemic effect of metformin+- **Lipid-lowering drugs**: Statins may increase the blood concentration of metformin+- **Antibiotics**: Some antibiotics (such as cephalosporins) may increase the risk of lactic acidosis+- **Anticoagulants**: Warfarin combined with metformin may increase the risk of bleeding+- **Diuretics**: Thiazide diuretics may reduce the hypoglycemic effect of metformin+- **Glucocorticoids**: May reduce the hypoglycemic effect of metformin+- **Contraceptives**: May reduce the hypoglycemic effect of metformin++### 3. Conditional Interactions+| Drug Combination | Patient Characteristics | Interaction Result | Clinical Recommendation |+| :--- | :--- | :--- | :--- |+| **Metformin + Sulfonylureas** | Elderly patients | Increased risk of hypoglycemia | Reduce sulfonylurea dose, closely monitor blood glucose |+| **Metformin + Insulin** | Renal impairment | Increased risk of hypoglycemia and lactic acidosis | Reduce insulin dose, monitor renal function |+| **Metformin + Statins** | Hepatic impairment | Increased risk of liver damage | Monitor liver function, reduce statin dose if necessary |+| **Metformin + Diuretics** | Heart failure | Reduced hypoglycemic effect, increased cardiovascular risk | Avoid combination, choose other antihypertensive drugs |+| **Metformin + Glucocorticoids** | Any patient | Reduced hypoglycemic effect, elevated blood glucose | Increase monitoring frequency, adjust dose if necessary |++## [Use in Special Populations]++### 1. Pregnant and Lactating Women+- **Pregnant Women**: Metformin is not recommended during pregnancy unless clearly needed.+- **Lactating Women**: Metformin can be secreted into breast milk, so it is not recommended during lactation.++### 2. Pediatric Use+- Children aged 10-16 years: Same dose as adults, maximum dose not exceeding 2000mg/day.+- Children under 10 years: Safety and efficacy have not been established.++### 3. Geriatric Use+- Elderly patients over 65 years should have regular renal function checks and adjust doses according to renal function.+- No dose adjustment is needed for elderly patients with normal renal function.++## [Overdose]+- **Symptoms**: Mainly manifested as lactic acidosis, including nausea, vomiting, abdominal pain, deep and rapid breathing, consciousness disturbance.+- **Treatment**: Stop taking the drug immediately, seek medical attention. Hemodialysis can be performed to remove accumulated metformin from the body.++## [Pharmacology and Toxicology]++### 1. Pharmacological Actions+- **Mechanism of Action**: Metformin lowers blood glucose by inhibiting hepatic glucose production, reducing intestinal glucose absorption, increasing peripheral tissue glucose uptake and utilization, and improving insulin sensitivity.+- **Pharmacokinetics**: Absorbed from the small intestine after oral administration, bioavailability is 50%-60%, peak time is 2.5-4 hours, half-life is 4-8 hours, mainly excreted by the kidneys.++### 2. Toxicological Studies+- **Acute Toxicity**: Oral LD50 in mice is 3g/kg, oral LD50 in rats is 6g/kg.+- **Chronic Toxicity**: No obvious toxic reactions were observed in rats and dogs after long-term administration (2 years).+- **Teratogenicity**: No teratogenic effects were observed in animal experiments.+- **Carcinogenicity**: No carcinogenic effects were observed in animal experiments.++## [Storage]+Sealed, stored below 25℃.++## [Packaging]+Aluminum-plastic packaging, 30 tablets/box.++## [Expiration Date]+36 months.++## [Approval Number]+National Drug Approval Number: H20023370++## [Manufacturer]+Manufacturer: Sino-American Shanghai Squibb Pharmaceuticals Ltd.+Address: No. 1315 Jianchuan Road, Minhang District, Shanghai+Postal Code: 200240+Telephone: 021-54220000+Fax: 021-54220100+Website: www.bms.com.cn\ No newline at end of filediff --git a/tests/fixtures/test_samples/en/medicine/pathology_report_sample.md b/tests/fixtures/test_samples/en/medicine/pathology_report_sample.mdnew file mode 100644index 0000000..dd62b79--- /dev/null+++ b/tests/fixtures/test_samples/en/medicine/pathology_report_sample.md@@ -0,0 +1,82 @@+# Pathology Report++## Basic Information+- **Pathology Number**: 2026-02001+- **Patient Name**: Jane Doe+- **Gender**: Female+- **Age**: 58 years+- **Submitting Department**: Breast Surgery+- **Submission Date**: February 15, 2026+- **Report Date**: February 20, 2026++## Specimen Information+- **Specimen Type**: Right modified radical mastectomy specimen+- **Specimen Size**: 20cm×15cm×5cm+- **Tumor Location**: Right breast, upper outer quadrant+- **Tumor Size**: 3.5cm×2.5cm×2.0cm+- **Margin Status**: Superior, inferior, medial, lateral, and basal margins all free of carcinoma++## Histological Examination++### Gross Examination+- **Tumor Morphology**: Irregular shape, hard consistency, ill-defined borders+- **Cut Surface Characteristics**: Gray-white, fish-fleshed appearance, with necrosis+- **Surrounding Tissue**: Fat tissue shows carcinoma infiltration++### Microscopic Examination+- **Histological Type**: Invasive ductal carcinoma, no special type+- **Histological Grade**: Grade II (Bloom-Richardson grading)+- **Mitotic Count**: 10 mitoses/10HPF+- **Necrosis**: Focal necrosis present+- **Vascular Invasion**: Lymphatic invasion present, no vascular invasion+- **Nerve Invasion**: No nerve invasion++## Immunohistochemical Examination++### Routine Immunohistochemistry+- **ER**: (+, 90%)+- **PR**: (+, 70%)+- **HER2**: (2+)+- **Ki-67**: (+, 30%)+- **E-cadherin**: (+)+- **P120**: (membrane+)+- **CK5/6**: (-)+- **EGFR**: (-)++### FISH Test+- **HER2 Gene Amplification**: Positive (HER2/CEP17 ratio=3.2)++## Molecular Testing++### Genetic Testing+- **BRCA1**: Wild type+- **BRCA2**: Wild type+- **PIK3CA**: E545K mutation+- **TP53**: R273H mutation+- **ERBB2**: No mutation++## Lymph Node Examination+- **Axillary Lymph Nodes**: 20 nodes, 3 with metastatic carcinoma+- **Sentinel Lymph Nodes**: 2 nodes, 1 with metastatic carcinoma+- **Internal Mammary Lymph Nodes**: 0 nodes, no metastatic carcinoma++## TNM Staging+- **T Stage**: T2 (tumor greatest dimension >2cm and ≤5cm)+- **N Stage**: N1 (1-3 axillary lymph nodes with metastasis)+- **M Stage**: M0 (no distant metastasis)+- **Pathological Stage**: pT2N1M0, Stage IIB++## Other Examinations+- **Intravascular Tumor Thrombus**: Positive+- **Perineural Invasion**: Negative+- **Skin Invasion**: Negative+- **Pectoral Fascia Invasion**: Negative++## Pathological Diagnosis+Right breast invasive ductal carcinoma, no special type, Grade II, pT2N1M0, Stage IIB. Immunohistochemistry: ER (+, 90%), PR (+, 70%), HER2 (2+, FISH positive), Ki-67 (+, 30%). Molecular testing: PIK3CA E545K mutation, TP53 R273H mutation, BRCA1/2 wild type. Axillary lymph node metastasis (3/20), sentinel lymph node metastasis (1/2).++## Notes+1. Suggest comprehensive judgment combined with clinical and other examination results+2. Suggest HER2-targeted therapy+3. Suggest endocrine therapy+4. Suggest regular follow-up\ No newline at end of filediff --git a/tests/fixtures/test_samples/en/medicine/textbook_sample.md b/tests/fixtures/test_samples/en/medicine/textbook_sample.mdnew file mode 100644index 0000000..13a7cff--- /dev/null+++ b/tests/fixtures/test_samples/en/medicine/textbook_sample.md@@ -0,0 +1,113 @@+# Internal Medicine (8th Edition)++## Chapter 1 Respiratory System Diseases++### 1.1 Chronic Obstructive Pulmonary Disease++#### 1.1.1 Etiology and Pathogenesis+Chronic obstructive pulmonary disease (COPD) is a preventable and treatable disease characterized by persistent airflow limitation that usually progresses. The airflow limitation is associated with an enhanced chronic inflammatory response in the airways and lungs to noxious particles or gases, primarily from cigarette smoke.++**Risk Factors**:+- **Environmental Factors**: Tobacco smoke, occupational dust and chemicals, air pollution, infection+- **Individual Factors**: Genetic factors (e.g., α1-antitrypsin deficiency), lung development abnormalities, airway hyperresponsiveness++**Pathogenesis**:+1. Airway inflammation: Involvement of neutrophils, macrophages, T lymphocytes, etc.+2. Oxidative stress: Increased production of oxidants, decreased antioxidant capacity+3. Protease-antiprotease imbalance: Enhanced protease activity, decreased antiprotease activity+4. Airway remodeling: Structural changes in airways leading to airflow limitation++### 1.2 Bronchial Asthma++#### 1.2.1 Definition and Classification+Bronchial asthma is a heterogeneous disease characterized by chronic airway inflammation involving various cells (e.g., eosinophils, mast cells, T lymphocytes, neutrophils, airway epithelial cells) and cellular components.++**Classification**:+- Allergic asthma+- Non-allergic asthma+- Late-onset asthma+- Severe asthma++### 1.3 Pneumonia++#### 1.3.1 Classification+- Anatomical classification: Lobar pneumonia, lobular pneumonia, interstitial pneumonia+- Etiological classification: Bacterial pneumonia, viral pneumonia, mycoplasma pneumonia, fungal pneumonia+- Classification by acquisition setting: Community-acquired pneumonia, hospital-acquired pneumonia++## Chapter 2 Cardiovascular System Diseases++### 2.1 Hypertension++#### 2.1.1 Definition and Classification+Hypertension is defined as a systolic blood pressure (SBP) ≥140 mmHg and/or diastolic blood pressure (DBP) ≥90 mmHg measured on three separate occasions without antihypertensive medication.++**Blood Pressure Classification**:+- Normal blood pressure: SBP <120 mmHg and DBP <80 mmHg+- Elevated blood pressure: SBP 120-139 mmHg and/or DBP 80-89 mmHg+- Hypertension:+ - Stage 1 hypertension: SBP 140-159 mmHg and/or DBP 90-99 mmHg+ - Stage 2 hypertension: SBP ≥160 mmHg and/or DBP ≥100 mmHg++### 2.2 Coronary Heart Disease++#### 2.2.1 Pathophysiology+Coronary atherosclerosis is the main cause of coronary heart disease, with pathological changes including lipid deposition, fibrous tissue proliferation, plaque formation, and ultimately stenosis or occlusion of coronary arteries, leading to myocardial ischemia, hypoxia, or necrosis.++**Clinical Types**:+- Asymptomatic myocardial ischemia+- Angina pectoris+- Myocardial infarction+- Ischemic cardiomyopathy+- Sudden cardiac death++## Chapter 3 Digestive System Diseases++### 3.1 Peptic Ulcer++#### 3.1.1 Etiology and Pathogenesis+Peptic ulcer mainly refers to chronic ulcers occurring in the stomach and duodenum, namely gastric ulcer (GU) and duodenal ulcer (DU).++**Main Etiological Factors**:+- Helicobacter pylori (Hp) infection+- Non-steroidal anti-inflammatory drugs (NSAIDs) use+- Gastric acid and pepsin+- Genetic factors+- Other factors: Smoking, alcohol consumption, stress, etc.++**Pathogenesis**:+Imbalance between defensive factors and aggressive factors in the gastric and duodenal mucosa. Either enhanced aggressive factors or weakened defensive factors can lead to peptic ulcer formation.++## Chapter 4 Endocrine System Diseases++### 4.1 Diabetes Mellitus++#### 4.1.1 Definition and Classification+Diabetes mellitus is a group of metabolic diseases characterized by chronic hyperglycemia resulting from defects in insulin secretion, insulin action, or both.++**Classification**:+- Type 1 diabetes mellitus (T1DM): Destruction of pancreatic β cells, leading to absolute insulin deficiency+- Type 2 diabetes mellitus (T2DM): Predominantly insulin resistance with progressive insulin secretory deficiency, or predominantly insulin secretory deficiency with insulin resistance+- Other specific types of diabetes+- Gestational diabetes mellitus (GDM)++#### 4.1.2 Clinical Manifestations+- Polyuria, polydipsia, polyphagia, weight loss ("three polys and one loss")+- Skin infections, slow wound healing+- Blurred vision+- Fatigue++## Chapter 5 Nervous System Diseases++### 5.1 Stroke++#### 5.1.1 Classification and Etiology+Stroke, also known as cerebrovascular accident, refers to diseases caused by cerebral blood circulation disorders and brain tissue functional or structural damage due to cerebrovascular occlusion or rupture.++**Classification**:+- Ischemic stroke: Cerebral thrombosis, cerebral embolism, lacunar infarction+- Hemorrhagic stroke: Intracerebral hemorrhage, subarachnoid hemorrhage++**Risk Factors**:+- Non-modifiable factors: Age, gender, race, genetic factors+- Modifiable factors: Hypertension, diabetes, hyperlipidemia, smoking, alcohol consumption, obesity, physical inactivity, atrial fibrillation, etc.\ No newline at end of filediff --git a/tests/fixtures/test_samples/en/tcm/herbal_compendium_sample.md b/tests/fixtures/test_samples/en/tcm/herbal_compendium_sample.mdnew file mode 100644index 0000000..f3d35ae--- /dev/null+++ b/tests/fixtures/test_samples/en/tcm/herbal_compendium_sample.md@@ -0,0 +1,55 @@+# Herbal Compendium Sample++## Ginseng++### Alternative Names+Ginseng, also known as Yellow Ginseng, Blood Ginseng, Human Bearing, Ghost Cover, Divine Herb, Earth Essence, Sea Cream, and Wrinkled Face Rejuvenation.++### Collection and Identification+*Bielu* states: Ginseng grows in the valleys of Shangdang and Liaodong. The roots are collected in the first ten days of February, April, and August, scraped with a bamboo knife, and dried in the sun, avoiding wind exposure.++### Properties and Flavors+Sweet, slightly cold, non-toxic.++### Indications+Tonifies the five viscera, calms the spirit, stabilizes the soul, stops palpitations, eliminates pathogenic factors, improves eyesight, opens the heart, and enhances wisdom. Long-term use promotes lightness of body and prolongs life.++### Attached Prescriptions+1. Yin Deficiency and Yang Exhaustion Syndrome: 1 liang of ginseng, 1 piece of prepared aconite, divided into four doses, decocted with water.+2. Spleen and Stomach Weakness: 2 qian each of ginseng and atractylodes, 1 qian each of poria and licorice, decocted with water.++## Licorice++### Alternative Names+Licorice, also known as Honey Sweet, Honey Herb, Beautiful Herb, Spirit Herb, and National Elder.++### Collection and Identification+*Bielu* states: Licorice grows in the valleys and sandy mountains of Hexi and Shangjun. It is collected on the last day of February and August, dried in the sun for ten days to complete.++### Properties and Flavors+Sweet, neutral, non-toxic.++### Indications+Treats cold-heat pathogenic factors of the five viscera and six bowels, strengthens tendons and bones, promotes muscle growth, increases strength, heals sores from metal wounds, and detoxifies. Long-term use promotes lightness of body and prolongs life.++### Attached Prescriptions+1. Cold Damage with Sore Throat: 2 liang of licorice, 1 liang of platycodon, decocted with water.+2. Childhood Heat Cough: 2 liang of licorice, soaked in pig bile for five nights, roasted and ground into powder, made into mung bean-sized pills with honey, take ten pills after meals with mint soup.++## Astragalus++### Alternative Names+Astragalus, also known as Dai Shen, Dai Shen, Bai Ben, Wang Sun, Hundred Medicine Cotton, Cotton Astragalus, Du Shen, Shu Zhi, and Huang Qi.++### Collection and Identification+*Bielu* states: Astragalus grows in the valleys of Shu County, Baishui, and Hanzhong. It is collected in February and October, and dried in the shade.++### Properties and Flavors+Sweet, slightly warm, non-toxic.++### Indications+Treats long-term ulcerative sores, expels pus and relieves pain, severe leprosy, five types of hemorrhoids and fistulas, tonifies deficiency, and treats various childhood diseases.++### Attached Prescriptions+1. Qi Deficiency with Night Sweats: 2 liang of astragalus, 1 liang of atractylodes, 0.5 liang of saposhnikovia, ground into powder, take 3 qian each time, decocted with water.+2. Qi Deficiency with Fatigue: 1 liang each of astragalus and ginseng, decocted with water.diff --git a/tests/fixtures/test_samples/en/tcm/medical_case_record_sample.md b/tests/fixtures/test_samples/en/tcm/medical_case_record_sample.mdnew file mode 100644index 0000000..5475121--- /dev/null+++ b/tests/fixtures/test_samples/en/tcm/medical_case_record_sample.md@@ -0,0 +1,61 @@+# Medical Case Record Sample++## Taiyang Wind Stroke Case++### Symptoms+Fever, sweating, aversion to wind, moderate pulse, nasal congestion, retching.++### Syndrome Differentiation+In Taiyang wind stroke, the yang is floating while the yin is weak. When yang floats, heat arises spontaneously; when yin is weak, sweat emerges on its own. For symptoms such as slight aversion to cold, mild aversion to wind, gentle fever, nasal congestion, and retching, Guizhi Decoction is the main treatment.++### Treatment Principle+Relieve the muscles to expel exterior pathogens, harmonize nutritive and defensive qi.++### Prescription+Guizhi Decoction: Cinnamon Twig 3 liang (peeled), Peony 3 liang, Licorice 2 liang (prepared), Ginger 3 liang (sliced), Jujube 12 pieces (broken).++### Decoction Method+Take the five ingredients, cut three of them, add 7 sheng of water, simmer over low heat to obtain 3 sheng, remove the dregs, adjust to suitable temperature, and take 1 sheng. Soon after taking, drink about 1 sheng of hot rice gruel to aid the medicinal effect, cover with a blanket for about one hour, and it is better to have a slight sweat all over the body; do not let the sweat flow profusely, otherwise the disease will not be cured.++### Case Analysis+This case is a typical Taiyang wind stroke syndrome. The patient experienced wind pathogen invasion, unconsolidated defensive qi, and leakage of nutritive yin, resulting in symptoms such as fever, sweating, and aversion to wind. Treatment with Guizhi Decoction to relieve the muscles, expel exterior pathogens, and harmonize nutritive and defensive qi, leading to pathogen elimination and recovery.++## Taiyang Cold Damage Case++### Symptoms+Headache, fever, body pain, low back pain, joint pain, aversion to wind, absence of sweating, and asthma.++### Syndrome Differentiation+In Taiyang disease, for symptoms such as headache, fever, body pain, low back pain, joint pain, aversion to wind, absence of sweating, and asthma, Mahuang Decoction is the main treatment.++### Treatment Principle+Induce sweating to expel exterior pathogens, ventilate the lungs to relieve asthma.++### Prescription+Mahuang Decoction: Ephedra 3 liang (de-jointed), Cinnamon Twig 2 liang (peeled), Licorice 1 liang (prepared), Apricot Kernel 70 pieces (peeled and tipped).++### Decoction Method+Take the four ingredients, add 9 sheng of water, first boil Ephedra to reduce by 2 sheng, remove the froth, add the other ingredients, boil to obtain 2.5 sheng, remove the dregs, warm and take 8 he, cover to induce slight sweating, no need to drink porridge, follow the same aftercare as Guizhi Decoction.++### Case Analysis+This case is a typical Taiyang cold damage syndrome. The patient experienced cold pathogen invasion, which constrained defensive yang and stagnated nutritive yin, resulting in symptoms such as headache, fever, body pain, and absence of sweating. Treatment with Mahuang Decoction to induce sweating, expel exterior pathogens, ventilate the lungs, and relieve asthma, allowing cold pathogens to be expelled with sweat.++## Shaoyang Disease Case++### Symptoms+Alternating chills and fever, fullness and discomfort in the chest and hypochondria, reluctance to talk and eat, vexation and propensity to vomit, bitter taste in the mouth, dry throat, and dizziness.++### Syndrome Differentiation+In cold damage or wind stroke of five to six days, for symptoms such as alternating chills and fever, fullness and discomfort in the chest and hypochondria, reluctance to talk and eat, vexation and propensity to vomit, or chest vexation without vomiting, or thirst, or abdominal pain, or hypochondriac fullness and hardness, or palpitations in the epigastrium and urinary difficulty, or absence of thirst with slight fever, or cough, Xiaochaihu Decoction is the main treatment.++### Treatment Principle+Harmonize Shaoyang.++### Prescription+Xiaochaihu Decoction: Bupleurum 8 liang, Scutellaria 3 liang, Ginseng 3 liang, Licorice 3 liang (prepared), Ginger 3 liang (sliced), Jujube 12 pieces (broken), Pinellia 0.5 sheng (washed).++### Decoction Method+Take the seven ingredients, add 12 sheng of water, boil to obtain 6 sheng, remove the dregs, simmer again to obtain 3 sheng, warm and take 1 sheng, three times a day.++### Case Analysis+This case is a typical Shaoyang disease syndrome. The patient experienced pathogen invasion of Shaoyang, which disrupted the pivot function, resulting in symptoms such as alternating chills and fever, fullness and discomfort in the chest and hypochondria, and vexation and propensity to vomit. Treatment with Xiaochaihu Decoction to harmonize Shaoyang, leading to pathogen elimination and recovery.diff --git a/tests/fixtures/test_samples/en/tcm/meridian_treatise_sample.md b/tests/fixtures/test_samples/en/tcm/meridian_treatise_sample.mdnew file mode 100644index 0000000..d2f03eb--- /dev/null+++ b/tests/fixtures/test_samples/en/tcm/meridian_treatise_sample.md@@ -0,0 +1,57 @@+# Meridian Treatise Sample++## Circulation of the Twelve Meridians++### Lung Meridian of Hand-Taiyin+Originates in the middle jiao, descends to connect with the large intestine, returns to circle the stomach, ascends across the diaphragm to belong to the lung. From the lung system, it transversely exits the axilla, descends along the medial aspect of the upper arm, traveling anterior to the Heart Meridian of Hand-Shaoyin and Pericardium Meridian of Hand-Jueyin, enters the cubital fossa, follows the medial aspect of the forearm along the radial bone, enters the cunkou (wrist pulse), ascends to the thenar eminence, follows the thenar eminence, and exits at the tip of the thumb. Its branch: from behind the wrist, straightly exits to the medial side of the index finger, ending at its tip.++### Large Intestine Meridian of Hand-Yangming+Originates at the tip of the index finger, follows the radial side of the finger, exits between the first and second metacarpal bones, enters the space between the two tendons, follows the lateral aspect of the forearm, enters the lateral aspect of the elbow, ascends the lateral anterior aspect of the upper arm, reaches the shoulder, exits anterior to the acromion, ascends to the meeting point of the Du Meridian at the highest point of the shoulder, descends into the supraclavicular fossa, connects with the lung, descends across the diaphragm, and belongs to the large intestine. Its branch: from the supraclavicular fossa, ascends the neck, penetrates the cheek, enters the lower teeth, returns to curve around the mouth, crosses the philtrum, from left to right and right to left, ascending to flanking the nostrils.++### Stomach Meridian of Foot-Yangming+Originates at the meeting point of the nose, joins the Bladder Meridian of Foot-Taiyang at the side, descends along the lateral side of the nose, enters the upper teeth, returns to curve around the mouth, circles the lips, descends to meet at the mentolabial groove, then follows the lower margin of the mandible, exits at Daying (ST 5), follows the angle of the mandible, ascends in front of the ear, passes through Tinggong (SI 19), follows the hairline, and reaches the forehead. Its branch: from before Daying (ST 5), descends to Renying (ST 9), follows the throat, enters the supraclavicular fossa, descends across the diaphragm, belongs to the stomach, and connects with the spleen. Its straight branch: from the supraclavicular fossa, descends the medial aspect of the breast, follows the lateral side of the umbilicus, and enters the qijie (气街, energy thoroughfare). Its branch: originates from the stomach orifice, descends along the abdomen, and joins at the qijie. From there, it descends through Biguan (ST 31), reaches Futu (ST 32), descends the knee, follows the lateral aspect of the tibia, descends to the dorsum of the foot, and enters the space between the middle toes. Its branch: separates 3 cun below the knee, descends to the lateral side of the middle toe. Its branch: separates on the dorsum of the foot, enters the space between the first and second toes, ending at its tip.++### Spleen Meridian of Foot-Taiyin+Originates at the tip of the big toe, follows the medial side of the toe along the white skin margin, passes behind the ball of the foot, ascends the anterior aspect of the medial malleolus, ascends the medial aspect of the lower leg, follows the posterior aspect of the tibia, crosses and emerges anterior to the Liver Meridian of Foot-Jueyin, ascends the medial aspect of the thigh, enters the abdomen, belongs to the spleen, connects with the stomach, ascends across the diaphragm, flanks the throat, connects with the root of the tongue, and spreads over the lower surface of the tongue. Its branch: from the stomach, ascends across the diaphragm, and flows into the heart.++### Heart Meridian of Hand-Shaoyin+Originates in the heart, exits to belong to the heart system, descends across the diaphragm, and connects with the small intestine. Its branch: from the heart system, ascends to flank the throat, and connects with the eye system. Its straight branch: from the heart system, ascends to the lung, descends to exit the axilla, follows the medial posterior aspect of the upper arm, traveling posterior to the Lung Meridian of Hand-Taiyin and Pericardium Meridian of Hand-Jueyin, enters the cubital fossa, follows the medial posterior aspect of the forearm, reaches the ulnar side of the wrist, enters the palm, follows the medial side of the little finger, and exits at its tip.++### Small Intestine Meridian of Hand-Taiyang+Originates at the tip of the little finger, follows the lateral side of the hand, ascends the wrist, exits the ulnar styloid process, ascends straight along the posterior aspect of the forearm, exits between the two bones at the medial aspect of the elbow, ascends the lateral posterior aspect of the upper arm, exits the scapular region, circles the scapula, crosses the shoulder, enters the supraclavicular fossa, connects with the heart, follows the esophagus, descends across the diaphragm, reaches the stomach, and belongs to the small intestine. Its branch: from the supraclavicular fossa, ascends the neck, reaches the cheek, goes to the outer canthus, and enters the ear. Its branch: from the cheek, ascends to the inferior margin of the nose, reaches the inner canthus, and obliquely connects to the zygomatic region.++### Bladder Meridian of Foot-Taiyang+Originates at the inner canthus, ascends the forehead, and meets at the vertex. Its branch: from the vertex to the upper angle of the ear. Its straight branch: from the vertex, enters to connect with the brain, returns to exit and descends along the posterior aspect of the neck, follows the medial aspect of the scapulae, flanks the spine, reaches the lumbar region, enters the paravertebral muscles, connects with the kidney, and belongs to the bladder. Its branch: from the lumbar region, descends flanking the spine, penetrates the gluteal region, and enters the popliteal fossa. Its branch: from the medial aspect of the scapulae, descends bilaterally through the scapulae, flanks the spine internally, passes through the hip joint, follows the lateral posterior aspect of the thigh, and joins in the popliteal fossa — from there, it descends through the calf, exits posterior to the lateral malleolus, follows Jinggu (BL 64) to the lateral side of the little toe.++### Kidney Meridian of Foot-Shaoyin+Originates below the little toe, curves to the sole of the foot, emerges below Rangu (KI 2), follows behind the medial malleolus, enters the heel, ascends the medial aspect of the lower leg, exits the medial aspect of the popliteal fossa, ascends the medial posterior aspect of the thigh, penetrates the spine to belong to the kidney, and connects with the bladder. Its straight branch: from the kidney, ascends through the liver and diaphragm, enters the lung, follows the throat, and flanks the root of the tongue. Its branch: from the lung, connects with the heart, and flows into the chest.++### Pericardium Meridian of Hand-Jueyin+Originates in the chest, exits to belong to the pericardium, descends across the diaphragm, and sequentially connects with the triple energizer. Its branch: follows the chest, exits the costal region, descends 3 cun below the axilla, ascends to the axilla, follows the medial aspect of the upper arm, traveling between the Lung Meridian of Hand-Taiyin and Heart Meridian of Hand-Shaoyin, enters the cubital fossa, descends the forearm between the two tendons, enters the palm, follows the middle finger, and exits at its tip. Its branch: separates in the palm, follows the ring finger, and exits at its tip.++### Triple Energizer Meridian of Hand-Shaoyang+Originates at the tip of the ring finger, ascends through the space between the ring and middle fingers, follows the dorsal aspect of the wrist, exits between the two bones of the forearm, ascends through the elbow, follows the lateral aspect of the upper arm, ascends the shoulder, and crosses behind the Gallbladder Meridian of Foot-Shaoyang, enters the supraclavicular fossa, spreads in the chest, disperses to connect with the pericardium, descends across the diaphragm, and pertains to the triple energizer. Its branch: from the chest, ascends the supraclavicular fossa, ascends the neck, connects behind the ear, ascends straight to the upper angle of the ear, bends downward to the cheek, and reaches the mandible. Its branch: from behind the ear, enters the ear, exits in front of the ear, passes in front of Tinggong (SI 19), crosses the cheek, and reaches the outer canthus.++### Gallbladder Meridian of Foot-Shaoyang+Originates at the outer canthus, ascends to the corner of the forehead, descends behind the ear, follows the neck, travels anterior to the Triple Energizer Meridian of Hand-Shaoyang, reaches the shoulder, then crosses behind the Triple Energizer Meridian of Hand-Shaoyang, and enters the supraclavicular fossa. Its branch: from behind the ear, enters the ear, exits in front of the ear, and reaches behind the outer canthus. Its branch: separates from the outer canthus, descends to Daying (ST 5), joins the Triple Energizer Meridian of Hand-Shaoyang, reaches the mandible, descends to Jiache (ST 6), descends the neck, and joins the supraclavicular fossa — from there, it descends the chest, penetrates the diaphragm, connects with the liver, belongs to the gallbladder, follows the costal region, exits the qijie, circles the pubic region, and transversely enters the hip joint. Its straight branch: from the supraclavicular fossa, descends the axilla, follows the chest, passes the hypochondrium, and joins in the hip joint. From there, it follows the lateral aspect of the thigh, exits the lateral aspect of the knee, descends the anterior aspect of the fibula, straightly descends to the tip of the fibula, descends anterior to the lateral malleolus, follows the dorsum of the foot, and enters the space between the fourth and fifth toes. Its branch: separates on the dorsum of the foot, enters the space between the first and second toes, follows the medial aspect of the first metatarsal bone, ends at its tip, and then penetrates the toenail to reach the三毛 region.++### Liver Meridian of Foot-Jueyin+Originates at the lateral side of the big toe, ascends along the dorsum of the foot, 1 cun away from the medial malleolus, ascends 8 cun above the medial malleolus, crosses and emerges posterior to the Spleen Meridian of Foot-Taiyin, ascends the medial aspect of the popliteal fossa, follows the medial aspect of the thigh, enters the pubic region, circles the external genitalia, reaches the lower abdomen, flanks the stomach, belongs to the liver, connects with the gallbladder, ascends through the diaphragm, spreads over the costal region, follows the posterior aspect of the throat, enters the nasopharynx, connects with the eye system, ascends to the forehead, and meets the Du Meridian at the vertex. Its branch: from the eye system, descends the cheek, and circles the inner aspect of the lips. Its branch: again separates from the liver, penetrates the diaphragm, and flows into the lung.++## Commonly Used Acupoints++### Hegu (LI 4)+Location: On the dorsum of the hand, between the first and second metacarpal bones, at the midpoint of the second metacarpal bone on the radial side.+Indications: Headache, redness and swelling of the eyes, nosebleed, toothache, lockjaw, facial paralysis, deafness, mumps, sore throat, febrile disease without sweating, excessive sweating, abdominal pain, constipation, amenorrhea, difficult labor.++### Zusanli (ST 36)+Location: On the anterolateral side of the lower leg, 3 cun below Dubi (ST 35), one finger-width (middle finger) lateral to the anterior crest of the tibia.+Indications: Stomachache, vomiting, dysphagia, abdominal distension, diarrhea, dysentery, constipation, breast abscess, intestinal abscess, lower limb pain, edema, mania, beriberi, consumptive disease with emaciation.++### Sanyinjiao (SP 6)+Location: On the medial side of the lower leg, 3 cun above the tip of the medial malleolus, posterior to the medial crest of the tibia.+Indications: Borborygmus, abdominal distension, diarrhea, irregular menstruation, leukorrhea, uterine prolapse, infertility, difficult labor, spermatorrhea, impotence, enuresis, hernia, insomnia, lower limb weakness, beriberi.++### Guanyuan (CV 4)+Location: On the lower abdomen, on the anterior midline, 3 cun below the umbilicus.+Indications: Collapse syndrome, consumptive cold and exhaustion, emaciation and weakness, lower abdominal pain, cholera with vomiting and diarrhea, dysentery, rectal prolapse, hernia, blood in the stool, blood in the urine, difficult urination, frequent urination, urinary retention, spermatorrhea, white turbidity, impotence, premature ejaculation, irregular menstruation, amenorrhea, dysmenorrhea, leukorrhea, uterine prolapse, uterine bleeding, vaginal itching, lochiorrhea, retained placenta, diabetes, dizziness.diff --git a/tests/fixtures/test_samples/en/tcm/prescription_formulary_sample.md b/tests/fixtures/test_samples/en/tcm/prescription_formulary_sample.mdnew file mode 100644index 0000000..2c1ae34--- /dev/null+++ b/tests/fixtures/test_samples/en/tcm/prescription_formulary_sample.md@@ -0,0 +1,52 @@+# Prescription Formulary Sample++## Guizhi Decoction++### Composition+Cinnamon Twig 3 liang (peeled), Peony 3 liang, Licorice 2 liang (prepared), Ginger 3 liang (sliced), Jujube 12 pieces (broken)++### Decoction Method+Take the five ingredients, cut three of them, add 7 sheng of water, simmer over low heat to obtain 3 sheng, remove the dregs, adjust to suitable temperature, and take 1 sheng. Soon after taking, drink about 1 sheng of hot rice gruel to aid the medicinal effect, cover with a blanket for about one hour, and it is better to have a slight sweat all over the body; do not let the sweat flow profusely, otherwise the disease will not be cured. If symptoms are relieved after one dose, stop taking the remaining medicine; if not sweating, take another dose according to the previous method; if still not sweating, shorten the interval between doses, taking three doses within half a day. For severe cases, take the medicine day and night, observing the condition continuously; if symptoms persist after one dose, prepare another dose; if no sweating occurs, take up to two or three doses.++### Functions and Indications+Relieves the muscles to expel exterior pathogens, harmonizes nutritive and defensive qi. Indicated for Taiyang wind stroke, with floating yang and weak yin; floating yang causes spontaneous heat, weak yin causes spontaneous sweating. Symptoms include slight aversion to cold, mild aversion to wind, gentle fever, nasal congestion, and retching.++### Monarch-Minister-Assistant-Guide Analysis+- Monarch herb: Cinnamon Twig, acrid and warm, relieves the muscles to expel exterior pathogens, warms and unblocks meridians+- Minister herb: Peony, sour, bitter, and slightly cold, nourishes yin and consolidates nutritive qi+- Assistant herbs: Ginger, acrid and warm, assists Cinnamon Twig in expelling exterior pathogens; Jujube, sweet and warm, supplements qi and nourishes the middle+- Guide herb: Licorice, sweet and warm, harmonizes all herbs++## Mahuang Decoction++### Composition+Ephedra 3 liang (de-jointed), Cinnamon Twig 2 liang (peeled), Licorice 1 liang (prepared), Apricot Kernel 70 pieces (peeled and tipped)++### Decoction Method+Take the four ingredients, add 9 sheng of water, first boil Ephedra to reduce by 2 sheng, remove the froth, add the other ingredients, boil to obtain 2.5 sheng, remove the dregs, warm and take 8 he, cover to induce slight sweating, no need to drink porridge, follow the same aftercare as Guizhi Decoction.++### Functions and Indications+Induces sweating to expel exterior pathogens, ventilates the lungs to relieve asthma. Indicated for Taiyang disease with headache, fever, body pain, low back pain, joint pain, aversion to wind, and absence of sweating with asthma.++### Monarch-Minister-Assistant-Guide Analysis+- Monarch herb: Ephedra, acrid and warm, induces sweating to expel exterior pathogens, ventilates the lungs to relieve asthma+- Minister herb: Cinnamon Twig, acrid and warm, relieves the muscles to expel exterior pathogens, warms and unblocks meridians+- Assistant herb: Apricot Kernel, bitter and warm, descends and benefits lung qi, relieves asthma and stops cough+- Guide herb: Licorice, sweet and warm, harmonizes all herbs++## Xiaochaihu Decoction++### Composition+Bupleurum 8 liang, Scutellaria 3 liang, Ginseng 3 liang, Licorice 3 liang (prepared), Ginger 3 liang (sliced), Jujube 12 pieces (broken), Pinellia 0.5 sheng (washed)++### Decoction Method+Take the seven ingredients, add 12 sheng of water, boil to obtain 6 sheng, remove the dregs, simmer again to obtain 3 sheng, warm and take 1 sheng, three times a day.++### Functions and Indications+Harmonizes Shaoyang. Indicated for cold damage or wind stroke of five to six days, with alternating chills and fever, fullness and discomfort in the chest and hypochondria, reluctance to talk and eat, vexation and propensity to vomit, or chest vexation without vomiting, or thirst, or abdominal pain, or hypochondriac fullness and hardness, or palpitations in the epigastrium and urinary difficulty, or absence of thirst with slight fever, or cough.++### Monarch-Minister-Assistant-Guide Analysis+- Monarch herb: Bupleurum, bitter and neutral, harmonizes Shaoyang, soothes the liver and resolves stagnation+- Minister herb: Scutellaria, bitter and cold, clears heat in Shaoyang+- Assistant herbs: Ginseng, Jujube, and Licorice, supplement qi and strengthen the spleen; Pinellia and Ginger, harmonize the stomach and descend rebellious qi+- Guide herb: Licorice, harmonizes all herbsdiff --git a/tests/fixtures/test_samples/zh/medicine/clinical_guideline_sample.md b/tests/fixtures/test_samples/zh/medicine/clinical_guideline_sample.mdnew file mode 100644index 0000000..27eda43--- /dev/null+++ b/tests/fixtures/test_samples/zh/medicine/clinical_guideline_sample.md@@ -0,0 +1,142 @@+# 2型糖尿病防治指南(2020版)++## 一、概述++2型糖尿病(T2DM)是一种常见的慢性代谢性疾病,其主要特征是胰岛素抵抗和胰岛素分泌不足,导致血糖水平升高。本指南旨在为临床医生提供规范化的诊疗建议,以提高2型糖尿病的防治水平。++## 二、诊断标准++### 2.1 糖尿病诊断标准+- 糖化血红蛋白(HbA1c)≥6.5%+- 空腹血糖(FPG)≥7.0mmol/L+- 口服葡萄糖耐量试验(OGTT)2小时血糖≥11.1mmol/L+- 随机血糖≥11.1mmol/L且伴有典型糖尿病症状++### 2.2 糖尿病前期诊断标准+- 空腹血糖受损(IFG):6.1≤FPG<7.0mmol/L+- 糖耐量减低(IGT):7.8≤OGTT 2小时血糖<11.1mmol/L+- 糖化血红蛋白:5.7%≤HbA1c<6.5%++## 三、治疗路径++### 3.1 生活方式干预+**推荐级别**:A+**证据等级**:1a++所有2型糖尿病患者都应接受生活方式干预,包括:+- 合理饮食:控制总热量,合理分配碳水化合物、蛋白质和脂肪+- 规律运动:每周至少150分钟中等强度有氧运动+- 控制体重:将BMI控制在24kg/m²以下+- 戒烟限酒+- 心理平衡++### 3.2 血糖控制目标+**推荐级别**:A+**证据等级**:1a++- 一般成人:HbA1c<7.0%+- 老年患者(65岁以上):HbA1c<7.5%(健康状况良好)或<8.0%(健康状况较差)+- 妊娠糖尿病:HbA1c<6.5%+- 有严重并发症或低血糖风险高的患者:HbA1c<8.0%++### 3.3 药物治疗路径++#### 3.3.1 单药治疗+**推荐级别**:A+**证据等级**:1a++- 首选二甲双胍:起始剂量500mg,每日2-3次,最大剂量2000mg/日+- 若二甲双胍不耐受,可选择:+ - 磺脲类:格列美脲1-4mg/日+ - 噻唑烷二酮类:吡格列酮15-45mg/日+ - DPP-4抑制剂:西格列汀100mg/日+ - SGLT-2抑制剂:达格列净10mg/日++#### 3.3.2 二联治疗+**推荐级别**:A+**证据等级**:1a++若单药治疗3个月后HbA1c未达标,应启动二联治疗:+- 二甲双胍 + 磺脲类+- 二甲双胍 + 噻唑烷二酮类+- 二甲双胍 + DPP-4抑制剂+- 二甲双胍 + SGLT-2抑制剂+- 二甲双胍 + GLP-1受体激动剂++#### 3.3.3 三联治疗+**推荐级别**:A+**证据等级**:1b++若二联治疗3个月后HbA1c未达标,应启动三联治疗:+- 二甲双胍 + 磺脲类 + 噻唑烷二酮类+- 二甲双胍 + 磺脲类 + DPP-4抑制剂+- 二甲双胍 + 磺脲类 + SGLT-2抑制剂+- 二甲双胍 + 磺脲类 + GLP-1受体激动剂++#### 3.3.4 胰岛素治疗+**推荐级别**:A+**证据等级**:1a++若三联治疗3个月后HbA1c未达标,应启动胰岛素治疗:+- 基础胰岛素:甘精胰岛素,起始剂量0.1-0.2U/kg/日+- 预混胰岛素:门冬胰岛素30,起始剂量0.2-0.4U/kg/日,早晚餐前注射+- 餐时+基础胰岛素:门冬胰岛素+甘精胰岛素,根据血糖调整剂量++## 四、并发症筛查与管理++### 4.1 大血管并发症+**推荐级别**:A+**证据等级**:1a++- 心血管疾病:每年进行一次心电图检查,评估心血管风险+- 脑血管疾病:定期进行颈部血管超声检查+- 下肢血管疾病:每年进行一次踝肱指数(ABI)检查++### 4.2 微血管并发症+**推荐级别**:A+**证据等级**:1a++- 糖尿病肾病:每年进行一次尿白蛋白/肌酐比值(UACR)和血肌酐检查+- 糖尿病视网膜病变:每年进行一次眼底检查+- 糖尿病神经病变:每年进行一次足部感觉检查++## 五、随访与监测++### 5.1 随访频率+- 新诊断患者:每2-4周随访一次,直至血糖达标+- 血糖控制稳定患者:每3-6个月随访一次+- 有并发症患者:根据并发症严重程度增加随访频率++### 5.2 监测指标+- 血糖:空腹血糖、餐后2小时血糖+- 糖化血红蛋白:每3个月检测一次+- 血脂:每6个月检测一次+- 血压:每次随访时检测+- 体重:每次随访时检测+- 足部检查:每3个月进行一次++## 六、特殊人群管理++### 6.1 老年糖尿病患者+**推荐级别**:B+**证据等级**:2a++- 血糖控制目标应适当放宽,避免低血糖+- 优先考虑低血糖风险低的药物+- 综合评估心肾功能,调整药物剂量++### 6.2 妊娠糖尿病患者+**推荐级别**:A+**证据等级**:1a++- 严格控制血糖,目标:空腹血糖<5.3mmol/L,餐后1小时血糖<7.8mmol/L,餐后2小时血糖<6.7mmol/L+- 首选胰岛素治疗+- 产后6-12周进行OGTT复查++### 6.3 合并心血管疾病患者+**推荐级别**:A+**证据等级**:1a++- 优先选择有心血管获益的药物:SGLT-2抑制剂、GLP-1受体激动剂+- 血压控制目标:<130/80mmHg+- 血脂控制目标:LDL-C<1.8mmol/L\ No newline at end of filediff --git a/tests/fixtures/test_samples/zh/medicine/discharge_summary_sample.md b/tests/fixtures/test_samples/zh/medicine/discharge_summary_sample.mdnew file mode 100644index 0000000..5b35cb0--- /dev/null+++ b/tests/fixtures/test_samples/zh/medicine/discharge_summary_sample.md@@ -0,0 +1,90 @@+# 出院小结++## 基本信息+- **姓名**:张三+- **性别**:男+- **年龄**:65岁+- **住院号**:20260201001+- **入院日期**:2026年02月01日+- **出院日期**:2026年02月10日+- **入院诊断**:1. 冠状动脉粥样硬化性心脏病 2. 不稳定型心绞痛 3. 高血压病3级(很高危)+- **出院诊断**:1. 冠状动脉粥样硬化性心脏病 2. 不稳定型心绞痛 3. 高血压病3级(很高危) 4. 2型糖尿病++## 住院经过++### 2026年02月01日+- **入院情况**:患者因"反复胸痛2周,加重1天"入院。入院时胸痛呈压榨样,位于心前区,范围约手掌大小,向左肩放射,持续约15分钟,休息后可缓解。+- **体格检查**:体温36.5℃,脉搏72次/分,呼吸18次/分,血压160/95mmHg。心界无扩大,心率72次/分,律齐,各瓣膜听诊区未闻及杂音。+- **辅助检查**:心电图:窦性心律,V1-V4导联ST段压低0.1-0.2mV。血常规、肝肾功能、电解质正常。++### 2026年02月02日+- **检查**:心肌酶谱:肌钙蛋白I 0.05ng/ml(正常),CK-MB 15U/L(正常)。超声心动图:左心室射血分数60%,各心腔大小正常,室壁运动未见明显异常。+- **治疗**:给予阿司匹林100mg qd,氯吡格雷75mg qd,阿托伐他汀20mg qn,美托洛尔25mg bid,缬沙坦80mg qd,单硝酸异山梨酯20mg bid。++### 2026年02月03日+- **检查**:冠状动脉造影:左主干未见明显狭窄,前降支近段狭窄80%,回旋支中段狭窄50%,右冠状动脉中段狭窄40%。+- **诊断**:冠状动脉粥样硬化性心脏病,不稳定型心绞痛,三支血管病变。++### 2026年02月04日+- **手术**:冠状动脉旁路移植术(CABG)+ - **手术医生**:王医生(主刀)、李医生(助手)+ - **手术时间**:08:30-14:30+ - **手术方式**:非体外循环下冠状动脉旁路移植术+ - **移植物**:左乳内动脉→前降支,大隐静脉→回旋支,大隐静脉→右冠状动脉+ - **术中情况**:手术顺利,出血约300ml,未输血。++### 2026年02月05日+- **术后情况**:患者转入重症监护病房,呼吸机辅助呼吸,生命体征平稳。+- **治疗**:给予多巴胺3μg/kg/min静脉泵入,硝酸甘油5μg/min静脉泵入,头孢呋辛1.5g q8h静脉滴注,奥美拉唑40mg q12h静脉推注。++### 2026年02月06日+- **术后情况**:患者拔除气管插管,改为鼻导管吸氧,氧饱和度98%。+- **治疗**:停多巴胺,继续硝酸甘油静脉泵入,调整为3μg/min。++### 2026年02月07日+- **术后情况**:患者转入普通病房,生命体征平稳,无胸痛、呼吸困难等不适。+- **检查**:血常规:白细胞计数8.5×10⁹/L,血红蛋白120g/L,血小板计数180×10⁹/L。肝肾功能、电解质正常。+- **治疗**:停硝酸甘油静脉泵入,改为单硝酸异山梨酯20mg bid口服。++### 2026年02月08日+- **检查**:血糖:空腹血糖7.8mmol/L,餐后2小时血糖11.2mmol/L。+- **诊断**:2型糖尿病。+- **治疗**:加用二甲双胍500mg bid口服。++### 2026年02月09日+- **检查**:心电图:窦性心律,V1-V4导联ST段较前改善。+- **治疗**:调整美托洛尔剂量为50mg bid口服。++### 2026年02月10日+- **出院评估**:患者一般情况良好,无胸痛、呼吸困难等不适,生命体征平稳。伤口愈合良好,无红肿、渗液。+- **出院医嘱**:详见出院医嘱部分。++## 出院医嘱++### 药物治疗+- **抗血小板药物**:阿司匹林100mg qd,终身服用;氯吡格雷75mg qd,服用12个月+- **调脂药物**:阿托伐他汀20mg qn,终身服用+- **β受体阻滞剂**:美托洛尔50mg bid,根据心率调整剂量+- **ACEI/ARB**:缬沙坦80mg qd,终身服用+- **硝酸酯类**:单硝酸异山梨酯20mg bid,症状缓解后可逐渐减量+- **降糖药物**:二甲双胍500mg bid,监测血糖+- **抗生素**:头孢呋辛酯250mg bid,服用3天++### 饮食与活动+- **饮食**:低盐低脂糖尿病饮食,控制总热量,每日食盐摄入量<5g+- **活动**:术后1个月内避免剧烈运动,可进行散步等轻度活动;术后3个月可逐渐恢复正常活动+- **体重**:控制体重,BMI目标<24kg/m²++### 随访计划+- **出院后1周**:心内科门诊复诊,复查血常规、肝肾功能、电解质+- **出院后2周**:伤口拆线,胸外科门诊复诊+- **出院后1个月**:心内科门诊复诊,复查心电图、超声心动图+- **出院后3个月**:心内科门诊复诊,复查冠状动脉CTA+- **出院后6个月**:心内科门诊复诊,全面评估心脏功能++### 注意事项+- 保持伤口清洁干燥,避免感染+- 按时服药,不可自行增减药量+- 定期监测血压、血糖+- 若出现胸痛、呼吸困难、发热等不适,及时就诊+- 戒烟限酒,保持良好的生活习惯\ No newline at end of filediff --git a/tests/fixtures/test_samples/zh/medicine/package_insert_sample.md b/tests/fixtures/test_samples/zh/medicine/package_insert_sample.mdnew file mode 100644index 0000000..ee61f63--- /dev/null+++ b/tests/fixtures/test_samples/zh/medicine/package_insert_sample.md@@ -0,0 +1,158 @@+# 药品说明书++## 【药品名称】+通用名称:二甲双胍缓释片+商品名称:格华止+英文名称:Metformin Hydrochloride Sustained-release Tablets++## 【成分】+本品主要成分为盐酸二甲双胍,其化学名称为:1,1-二甲基双胍盐酸盐。+分子式:C4H11N5·HCl+分子量:165.63++## 【性状】+本品为白色或类白色薄膜衣片,除去包衣后显白色。++## 【适应症】+1. 用于单纯饮食控制不满意的2型糖尿病患者,尤其是肥胖者,还可能有减轻体重的作用。+2. 对某些磺酰脲类疗效差的患者可奏效。+3. 可与磺酰脲类或胰岛素合用以改善血糖控制。++## 【规格】+500mg(以盐酸二甲双胍计)++## 【用法用量】+口服,进食时或餐后服。开始用量通常为每日一次,一次500mg,晚餐时服用,根据血糖和尿糖调整用量,每日最大剂量不超过2000mg。如果每日一次,每次2000mg不能达到满意的疗效,可改为每日两次,每次1000mg。++## 【不良反应】+### 1. 常见不良反应(发生率>1%)+- **胃肠道反应**:恶心、呕吐、腹泻、腹痛、消化不良、胃灼热感+- **全身反应**:乏力、头痛、头晕++### 2. 少见不良反应(发生率0.1%-1%)+- **皮肤反应**:皮疹、瘙痒+- **代谢异常**:低血糖(与磺酰脲类或胰岛素合用时)+- **实验室检查异常**:乳酸脱氢酶升高、丙氨酸氨基转移酶升高、天门冬氨酸氨基转移酶升高++### 3. 罕见不良反应(发生率<0.1%)+- **乳酸酸中毒**:表现为乏力、恶心、呕吐、腹痛、呼吸深快、意识障碍+- **血液系统**:粒细胞减少、血小板减少+- **过敏反应**:荨麻疹、血管神经性水肿+- **肝胆异常**:肝炎、胆汁淤积性黄疸++### 4. 不良反应发生率统计+| 系统 | 不良反应 | 发生率 |+| :--- | :--- | :--- |+| **胃肠道** | 恶心 | 5.2% |+| **胃肠道** | 呕吐 | 2.6% |+| **胃肠道** | 腹泻 | 4.5% |+| **胃肠道** | 腹痛 | 2.1% |+| **全身** | 乏力 | 1.8% |+| **全身** | 头痛 | 1.5% |+| **皮肤** | 皮疹 | 0.3% |+| **代谢** | 低血糖 | 0.2%(单独使用),1.5%(与磺酰脲类合用) |+| **肝胆** | 转氨酶升高 | 0.1% |+| **血液** | 粒细胞减少 | <0.1% |++## 【禁忌症】+1. **绝对禁忌症**:+ - 对二甲双胍及其他成分过敏者+ - 严重肾功能不全(eGFR<30ml/min/1.73m²)+ - 代谢性酸中毒(包括糖尿病酮症酸中毒)+ - 严重感染、休克或其他可能导致组织缺氧的疾病+ - 酗酒者+ - 维生素B12、叶酸缺乏未纠正者+ - 接受血管内注射碘化造影剂前后48小时内++2. **相对禁忌症**:+ - 肾功能不全(eGFR 30-45ml/min/1.73m²)+ - 肝功能不全+ - 心力衰竭+ - 严重肺功能不全+ - 孕妇及哺乳期妇女++## 【注意事项】+1. **乳酸酸中毒**:二甲双胍可引起乳酸酸中毒,虽然罕见,但可致命。一旦发生,应立即停药并就医。+2. **肾功能监测**:用药前及用药期间应定期检查肾功能,特别是老年患者。+3. **肝功能监测**:用药期间应定期检查肝功能。+4. **血糖监测**:用药期间应定期监测血糖、糖化血红蛋白。+5. **维生素B12缺乏**:长期使用二甲双胍可能导致维生素B12吸收减少,建议定期监测维生素B12水平。+6. **手术前后**:择期手术前应暂停使用二甲双胍,术后肾功能恢复后可重新开始使用。+7. **造影检查**:接受血管内注射碘化造影剂前后48小时内应暂停使用二甲双胍。++## 【药物相互作用】++### 1. 与其他降糖药物的相互作用+- **磺酰脲类药物**:合用可增加低血糖风险+- **胰岛素**:合用可增加低血糖风险,应减少胰岛素剂量+- **格列奈类**:合用可增加低血糖风险+- **GLP-1受体激动剂**:合用可增强降糖效果+- **SGLT-2抑制剂**:合用可增强降糖效果,减少低血糖风险++### 2. 与其他药物的相互作用+- **降压药**:ACEI、ARB、钙通道阻滞剂等可增强二甲双胍的降糖效果+- **降脂药**:他汀类药物可增加二甲双胍的血药浓度+- **抗生素**:某些抗生素(如头孢菌素类)可增加乳酸酸中毒风险+- **抗凝药**:华法林与二甲双胍合用可能增加出血风险+- **利尿剂**:噻嗪类利尿剂可降低二甲双胍的降糖效果+- **糖皮质激素**:可降低二甲双胍的降糖效果+- **避孕药**:可降低二甲双胍的降糖效果++### 3. 条件性相互作用+| 药物组合 | 患者特征 | 相互作用结果 | 临床建议 |+| :--- | :--- | :--- | :--- |+| **二甲双胍 + 磺酰脲类** | 老年患者 | 增加低血糖风险 | 减少磺酰脲类剂量,密切监测血糖 |+| **二甲双胍 + 胰岛素** | 肾功能不全 | 增加低血糖风险和乳酸酸中毒风险 | 减少胰岛素剂量,监测肾功能 |+| **二甲双胍 + 他汀类** | 肝功能不全 | 增加肝损伤风险 | 监测肝功能,必要时减少他汀类剂量 |+| **二甲双胍 + 利尿剂** | 心力衰竭 | 降低降糖效果,增加心血管风险 | 避免合用,选择其他降压药 |+| **二甲双胍 + 糖皮质激素** | 任何患者 | 降低降糖效果,升高血糖 | 增加监测频率,必要时调整剂量 |++## 【特殊人群用药】++### 1. 孕妇及哺乳期妇女+- **孕妇**:妊娠期间不建议使用二甲双胍,除非明确需要。+- **哺乳期妇女**:二甲双胍可通过乳汁分泌,不建议哺乳期使用。++### 2. 儿童用药+- 10-16岁儿童:剂量同成人,最大剂量不超过2000mg/日。+- 10岁以下儿童:安全性和有效性尚未确立。++### 3. 老年用药+- 65岁以上老年患者应定期检查肾功能,根据肾功能调整剂量。+- 肾功能正常的老年患者无需调整剂量。++## 【药物过量】+- **症状**:主要表现为乳酸酸中毒,症状包括恶心、呕吐、腹痛、呼吸深快、意识障碍。+- **处理**:立即停药,就医。进行血液透析以清除体内蓄积的二甲双胍。++## 【药理毒理】++### 1. 药理作用+- **作用机制**:二甲双胍通过抑制肝脏葡萄糖的产生,减少肠道对葡萄糖的吸收,增加外周组织对葡萄糖的摄取和利用,提高胰岛素敏感性。+- **药代动力学**:口服后由小肠吸收,生物利用度为50%-60%,达峰时间为2.5-4小时,半衰期为4-8小时,主要经肾脏排泄。++### 2. 毒理研究+- **急性毒性**:小鼠口服LD50为3g/kg,大鼠口服LD50为6g/kg。+- **长期毒性**:大鼠和犬长期给药(2年)未见明显毒性反应。+- **致畸性**:动物实验未见致畸作用。+- **致癌性**:动物实验未见致癌作用。++## 【贮藏】+密封,25℃以下保存。++## 【包装】+铝塑包装,30片/盒。++## 【有效期】+36个月。++## 【批准文号】+国药准字H20023370++## 【生产企业】+企业名称:中美上海施贵宝制药有限公司+生产地址:上海市闵行区剑川路1315号+邮政编码:200240+电话号码:021-54220000+传真号码:021-54220100+网址:www.bms.com.cn\ No newline at end of filediff --git a/tests/fixtures/test_samples/zh/medicine/pathology_report_sample.md b/tests/fixtures/test_samples/zh/medicine/pathology_report_sample.mdnew file mode 100644index 0000000..fa4af69--- /dev/null+++ b/tests/fixtures/test_samples/zh/medicine/pathology_report_sample.md@@ -0,0 +1,82 @@+# 病理检查报告++## 基本信息+- **病理号**:2026-02001+- **患者姓名**:李四+- **性别**:女+- **年龄**:58岁+- **送检科室**:乳腺外科+- **送检日期**:2026年02月15日+- **报告日期**:2026年02月20日++## 标本信息+- **标本类型**:右侧乳腺改良根治术标本+- **标本大小**:20cm×15cm×5cm+- **肿瘤位置**:右侧乳腺外上象限+- **肿瘤大小**:3.5cm×2.5cm×2.0cm+- **切缘情况**:上切缘、下切缘、内切缘、外切缘、基底切缘均未见癌组织++## 组织学检查++### 大体检查+- **肿瘤形态**:不规则形,质地硬,边界不清+- **切面特征**:灰白色,鱼肉样,伴有坏死+- **周围组织**:脂肪组织中可见癌浸润++### 镜下检查+- **组织学类型**:浸润性导管癌,非特殊型+- **组织学分级**:Ⅱ级(Bloom-Richardson分级)+- **核分裂象**:10个/10HPF+- **坏死**:可见片状坏死+- **脉管侵犯**:可见淋巴管侵犯,未见血管侵犯+- **神经侵犯**:未见神经侵犯++## 免疫组化检查++### 常规免疫组化+- **ER**:(+,90%)+- **PR**:(+,70%)+- **HER2**:(2+)+- **Ki-67**:(+,30%)+- **E-cadherin**:(+)+- **P120**:(膜+)+- **CK5/6**:(-)+- **EGFR**:(-)++### FISH检测+- **HER2基因扩增**:阳性(HER2/CEP17比值=3.2)++## 分子检测++### 基因检测+- **BRCA1**:野生型+- **BRCA2**:野生型+- **PIK3CA**:E545K突变+- **TP53**:R273H突变+- **ERBB2**:无突变++## 淋巴结检查+- **腋窝淋巴结**:20枚,其中3枚见癌转移+- **前哨淋巴结**:2枚,其中1枚见癌转移+- **内乳淋巴结**:0枚,未见癌转移++## TNM分期+- **T分期**:T2(肿瘤最大径>2cm且≤5cm)+- **N分期**:N1(1-3枚腋窝淋巴结转移)+- **M分期**:M0(无远处转移)+- **病理分期**:pT2N1M0,ⅡB期++## 其他检查+- **脉管内癌栓**:阳性+- **周围神经侵犯**:阴性+- **皮肤侵犯**:阴性+- **胸肌筋膜侵犯**:阴性++## 病理诊断+右侧乳腺浸润性导管癌,非特殊型,Ⅱ级,pT2N1M0,ⅡB期。免疫组化:ER(+,90%),PR(+,70%),HER2(2+,FISH阳性),Ki-67(+,30%)。分子检测:PIK3CA E545K突变,TP53 R273H突变,BRCA1/2野生型。腋窝淋巴结转移(3/20),前哨淋巴结转移(1/2)。++## 备注+1. 建议结合临床及其他检查结果综合判断+2. 建议进行HER2靶向治疗+3. 建议进行内分泌治疗+4. 建议定期随访\ No newline at end of filediff --git a/tests/fixtures/test_samples/zh/medicine/textbook_sample.md b/tests/fixtures/test_samples/zh/medicine/textbook_sample.mdnew file mode 100644index 0000000..1d66a2e--- /dev/null+++ b/tests/fixtures/test_samples/zh/medicine/textbook_sample.md@@ -0,0 +1,113 @@+# 内科学(第八版)++## 第一章 呼吸系统疾病++### 1.1 慢性阻塞性肺疾病++#### 1.1.1 病因与发病机制+慢性阻塞性肺疾病(COPD)是一种以持续气流受限为特征的可以预防和治疗的疾病,其气流受限多呈进行性发展,与气道和肺组织对烟草烟雾等有害气体或有害颗粒的慢性炎症反应增强有关。++**危险因素**:+- **环境因素**:烟草烟雾、职业粉尘和化学物质、空气污染、感染+- **个体因素**:遗传因素(如α1-抗胰蛋白酶缺乏)、肺发育不良、气道高反应性++**发病机制**:+1. 气道炎症:中性粒细胞、巨噬细胞、T淋巴细胞等炎症细胞参与+2. 氧化应激:氧化物产生增加,抗氧化能力下降+3. 蛋白酶-抗蛋白酶失衡:蛋白酶活性增强,抗蛋白酶活性降低+4. 气道重塑:气道结构发生改变,导致气流受限++### 1.2 支气管哮喘++#### 1.2.1 定义与分类+支气管哮喘是由多种细胞(如嗜酸性粒细胞、肥大细胞、T淋巴细胞、中性粒细胞、气道上皮细胞等)和细胞组分参与的气道慢性炎症为特征的异质性疾病。++**分类**:+- 过敏性哮喘+- 非过敏性哮喘+- 迟发型哮喘+- 重症哮喘++### 1.3 肺炎++#### 1.3.1 分类+- 按解剖分类:大叶性肺炎、小叶性肺炎、间质性肺炎+- 按病因分类:细菌性肺炎、病毒性肺炎、支原体肺炎、真菌性肺炎+- 按患病环境分类:社区获得性肺炎、医院获得性肺炎++## 第二章 循环系统疾病++### 2.1 高血压++#### 2.1.1 定义与分级+高血压是指在未使用降压药物的情况下,非同日3次测量诊室血压,收缩压≥140mmHg和(或)舒张压≥90mmHg。++**血压水平分类**:+- 正常血压:收缩压<120mmHg和舒张压<80mmHg+- 正常高值:收缩压120-139mmHg和(或)舒张压80-89mmHg+- 高血压:+ - 1级高血压:收缩压140-159mmHg和(或)舒张压90-99mmHg+ - 2级高血压:收缩压≥160mmHg和(或)舒张压≥100mmHg++### 2.2 冠心病++#### 2.2.1 病理生理+冠状动脉粥样硬化是冠心病的主要病因,其病理变化包括脂质沉积、纤维组织增生、斑块形成,最终导致冠状动脉管腔狭窄或阻塞,引起心肌缺血、缺氧或坏死。++**临床类型**:+- 无症状性心肌缺血+- 心绞痛+- 心肌梗死+- 缺血性心肌病+- 猝死++## 第三章 消化系统疾病++### 3.1 消化性溃疡++#### 3.1.1 病因与发病机制+消化性溃疡主要指发生在胃和十二指肠的慢性溃疡,即胃溃疡(GU)和十二指肠溃疡(DU)。++**主要病因**:+- 幽门螺杆菌(Hp)感染+- 非甾体抗炎药(NSAIDs)使用+- 胃酸和胃蛋白酶+- 遗传因素+- 其他因素:吸烟、饮酒、应激等++**发病机制**:+胃、十二指肠黏膜的防御因素与侵袭因素失衡,侵袭因素增强或防御因素减弱,均可导致消化性溃疡的发生。++## 第四章 内分泌系统疾病++### 4.1 糖尿病++#### 4.1.1 定义与分类+糖尿病是一组由多病因引起的以慢性高血糖为特征的代谢性疾病,是由于胰岛素分泌和(或)作用缺陷所引起。++**分类**:+- 1型糖尿病(T1DM):胰岛β细胞破坏,导致胰岛素绝对缺乏+- 2型糖尿病(T2DM):胰岛素抵抗为主伴胰岛素进行性分泌不足,或胰岛素分泌不足为主伴胰岛素抵抗+- 其他特殊类型糖尿病+- 妊娠糖尿病(GDM)++#### 4.1.2 临床表现+- 多饮、多食、多尿、体重减轻("三多一少")+- 皮肤感染、伤口愈合缓慢+- 视力模糊+- 乏力++## 第五章 神经系统疾病++### 5.1 脑卒中++#### 5.1.1 分类与病因+脑卒中又称脑血管意外,是指因脑血管阻塞或破裂引起的脑血流循环障碍和脑组织功能或结构损害的疾病。++**分类**:+- 缺血性脑卒中:脑血栓形成、脑栓塞、腔隙性脑梗死+- 出血性脑卒中:脑出血、蛛网膜下腔出血++**危险因素**:+- 不可干预因素:年龄、性别、种族、遗传因素+- 可干预因素:高血压、糖尿病、高脂血症、吸烟、酗酒、肥胖、缺乏运动、心房颤动等\ No newline at end of filediff --git a/tests/fixtures/test_samples/zh/tcm/herbal_compendium_sample.md b/tests/fixtures/test_samples/zh/tcm/herbal_compendium_sample.mdnew file mode 100644index 0000000..146fdff--- /dev/null+++ b/tests/fixtures/test_samples/zh/tcm/herbal_compendium_sample.md@@ -0,0 +1,55 @@+# 本草典籍样本++## 人参++### 释名+人参,亦名黄参、血参、人衔、鬼盖、神草、土精、地精、海腴、皱面还丹。++### 集解+《别录》曰:人参生上党山谷及辽东,二月、四月、八月上旬采根,竹刀刮暴干,无令见风。++### 气味+甘,微寒,无毒。++### 主治+补五脏,安精神,定魂魄,止惊悸,除邪气,明目,开心益智。久服轻身延年。++### 附方+1. 阴亏阳绝之证:人参一两,附子一枚(炮),分作四服,水煎服。+2. 脾胃虚弱:人参、白术各二钱,茯苓、甘草各一钱,水煎服。++## 甘草++### 释名+甘草,亦名蜜甘、蜜草、美草、草、灵通、国老。++### 集解+《别录》曰:甘草生河西川谷积沙山及上郡。二月、八月除日采根,暴干,十日成。++### 气味+甘,平,无毒。++### 主治+五脏六腑寒热邪气,坚筋骨,长肌肉,倍气力,金疮肿,解毒。久服轻身延年。++### 附方+1. 伤寒咽痛:甘草二两,桔梗一两,水煎服。+2. 小儿热嗽:甘草二两,猪胆汁浸五宿,炙研末,蜜丸绿豆大,食后薄荷汤下十丸。++## 黄芪++### 释名+黄芪,亦名戴糁、戴椹、百本、王孙、百药绵、绵黄耆、独椹、蜀脂、黄耆。++### 集解+《别录》曰:黄芪生蜀郡山谷、白水、汉中。二月、十月采,阴干。++### 气味+甘,微温,无毒。++### 主治+痈疽久败疮,排脓止痛,大风癞疾,五痔鼠瘘,补虚,小儿百病。++### 附方+1. 气虚盗汗:黄芪二两,白术一两,防风半两,研末,每服三钱,水煎服。+2. 气虚乏力:黄芪、人参各一两,水煎服。diff --git a/tests/fixtures/test_samples/zh/tcm/medical_case_record_sample.md b/tests/fixtures/test_samples/zh/tcm/medical_case_record_sample.mdnew file mode 100644index 0000000..3874b1f--- /dev/null+++ b/tests/fixtures/test_samples/zh/tcm/medical_case_record_sample.md@@ -0,0 +1,61 @@+# 名医医案样本++## 太阳中风案++### 症状+发热,汗出,恶风,脉缓,鼻鸣,干呕。++### 辨证分析+太阳中风,阳浮而阴弱,阳浮者,热自发;阴弱者,汗自出。啬啬恶寒,淅淅恶风,翕翕发热,鼻鸣干呕者,桂枝汤主之。++### 治法+解肌发表,调和营卫。++### 处方+桂枝汤:桂枝三两(去皮)、芍药三两、甘草二两(炙)、生姜三两(切)、大枣十二枚(擘)。++### 煎服法+上五味,咀三味,以水七升,微火煮取三升,去滓,适寒温,服一升。服已须臾,啜热稀粥一升余,以助药力,温覆令一时许,遍身微似有汗者益佳;不可令如水流离,病必不除。++### 医案解析+本案例为典型的太阳中风证,患者因感受风邪,卫气不固,营阴外泄,故见发热、汗出、恶风等症。治以桂枝汤解肌发表,调和营卫,使邪去正安。++## 太阳伤寒案++### 症状+头痛,发热,身疼,腰痛,骨节疼痛,恶风,无汗而喘。++### 辨证分析+太阳病,头痛、发热、身疼、腰痛、骨节疼痛、恶风、无汗而喘者,麻黄汤主之。++### 治法+发汗解表,宣肺平喘。++### 处方+麻黄汤:麻黄三两(去节)、桂枝二两(去皮)、甘草一两(炙)、杏仁七十个(去皮尖)。++### 煎服法+上四味,以水九升,先煮麻黄,减二升,去上沫,内诸药,煮取二升半,去滓,温服八合,覆取微似汗,不须啜粥,余如桂枝法将息。++### 医案解析+本案例为典型的太阳伤寒证,患者因感受寒邪,卫阳被遏,营阴郁滞,故见头痛、发热、身疼、无汗等症。治以麻黄汤发汗解表,宣肺平喘,使寒邪随汗而解。++## 少阳病案++### 症状+往来寒热,胸胁苦满,嘿嘿不欲饮食,心烦喜呕,口苦,咽干,目眩。++### 辨证分析+伤寒五六日中风,往来寒热,胸胁苦满、嘿嘿不欲饮食、心烦喜呕,或胸中烦而不呕,或渴,或腹中痛,或胁下痞硬,或心下悸、小便不利,或不渴、身有微热,或咳者,小柴胡汤主之。++### 治法+和解少阳。++### 处方+小柴胡汤:柴胡半斤、黄芩三两、人参三两、甘草三两(炙)、生姜三两(切)、大枣十二枚(擘)、半夏半升(洗)。++### 煎服法+上七味,以水一斗二升,煮取六升,去滓,再煎取三升,温服一升,日三服。++### 医案解析+本案例为典型的少阳病,患者因邪犯少阳,枢机不利,故见往来寒热、胸胁苦满、心烦喜呕等症。治以小柴胡汤和解少阳,使邪去病愈。diff --git a/tests/fixtures/test_samples/zh/tcm/meridian_treatise_sample.md b/tests/fixtures/test_samples/zh/tcm/meridian_treatise_sample.mdnew file mode 100644index 0000000..f67025f--- /dev/null+++ b/tests/fixtures/test_samples/zh/tcm/meridian_treatise_sample.md@@ -0,0 +1,57 @@+# 经络腧穴专著样本++## 十二经脉循行++### 手太阴肺经+起于中焦,下络大肠,还循胃口,上膈属肺。从肺系,横出腋下,下循臑内,行少阴、心主之前,下肘中,循臂内上骨下廉,入寸口,上鱼,循鱼际,出大指之端。其支者:从腕后,直出次指内廉,出其端。++### 手阳明大肠经+起于大指次指之端,循指上廉,出合谷两骨之间,上入两筋之中,循臂上廉,入肘外廉,上臑外前廉,上肩,出髃骨之前廉,上出于柱骨之会上,下入缺盆,络肺,下膈,属大肠。其支者:从缺盆上颈,贯颊,入下齿中;还出挟口,交人中,左之右,右之左,上挟鼻孔。++### 足阳明胃经+起于鼻之交頞中,旁纳太阳之脉,下循鼻外,入上齿中,还出挟口,环唇,下交承浆,却循颐后下廉,出大迎,循颊车,上耳前,过客主人,循发际,至额颅。其支者:从大迎前,下人迎,循喉咙,入缺盆,下膈,属胃,络脾。其直者:从缺盆下乳内廉,下挟脐,入气街中。其支者:起于胃口,下循腹里,下至气街中而合。以下髀关,抵伏兔,下膝膑中,下循胫外廉,下足跗,入中指内间。其支者:下廉三寸而别,下入中指外间。其支者:别跗上,入大指间,出其端。++### 足太阴脾经+起于大指之端,循指内侧白肉际,过核骨后,上内踝前廉,上踹内,循胫骨后,交出厥阴之前,上膝股内前廉,入腹,属脾,络胃,上膈,挟咽,连舌本,散舌下。其支者:复从胃别,上膈,注心中。++### 手少阴心经+起于心中,出属心系,下膈,络小肠。其支者:从心系,上挟咽,系目系。其直者:复从心系,却上肺,下出腋下,下循臑内后廉,行太阴、心主之后,下肘内,循臂内后廉,抵掌后锐骨之端,入掌内后廉,循小指之内,出其端。++### 手太阳小肠经+起于小指之端,循手外侧上腕,出踝中,直上循臂骨下廉,出肘内侧两筋之间,上循臑外后廉,出肩解,绕肩胛,交肩上,入缺盆,络心,循咽下膈,抵胃,属小肠。其支者:从缺盆循颈,上颊,至目锐眦,却入耳中。其支者:别颊上抵鼻,至目内眦,斜络于颧。++### 足太阳膀胱经+起于目内眦,上额,交巅。其支者:从巅至耳上角。其直者:从巅入络脑,还出别下项,循肩膊内,挟脊抵腰中,入循膂,络肾,属膀胱。其支者:从腰中,下挟脊,贯臀,入腘中。其支者:从膊内左右别下贯胛,挟脊内,过髀枢,循髀外后廉下合腘中——以下贯踹内,出外踝之后,循京骨至小指外侧。++### 足少阴肾经+起于小指之下,邪走足心,出于然谷之下,循内踝之后,别入跟中,以上踹内,出腘内廉,上股内后廉,贯脊属肾,络膀胱。其直者:从肾上贯肝膈,入肺中,循喉咙,挟舌本。其支者:从肺出,络心,注胸中。++### 手厥阴心包经+起于胸中,出属心包络,下膈,历络三焦。其支者:循胸出胁,下腋三寸,上抵腋下,循臑内,行太阴、少阴之间,入肘中,下臂,行两筋之间,入掌中,循中指,出其端。其支者:别掌中,循小指次指,出其端。++### 手少阳三焦经+起于小指次指之端,上出两指之间,循手表腕,出臂外两骨之间,上贯肘,循臑外上肩,而交出足少阳之后,入缺盆,布膻中,散络心包,下膈,遍属三焦。其支者:从膻中,上出缺盆,上项,系耳后,直上出耳上角,以屈下颊至 。其支者:从耳后入耳中,出走耳前,过客主人前,交颊,至目锐眦。++### 足少阳胆经+起于目锐眦,上抵头角,下耳后,循颈,行手少阳之前,至肩上,却交出手少阳之后,入缺盆。其支者:从耳后入耳中,出走耳前,至目锐眦后。其支者:别锐眦,下大迎,合于手少阳,抵于 ,下加颊车,下颈,合缺盆——以下胸中,贯膈,络肝,属胆,循胁里,出气街,绕毛际,横入髀厌中。其直者:从缺盆下腋,循胸,过季胁,下合髀厌中。以下循髀阳,出膝外廉,下外辅骨之前,直下抵绝骨之端,下出外踝之前,循足跗上,入小指次指之间。其支者:别跗上,入大指之间,循大指歧骨内,出其端,还贯爪甲,出三毛。++### 足厥阴肝经+起于大指丛毛之际,上循足跗上廉,去内踝一寸,上踝八寸,交出太阴之后,上腘内廉,循股阴,入毛中,环阴器,抵小腹,挟胃,属肝,络胆,上贯膈,布胁肋,循喉咙之后,上入颃颡,连目系,上出额,与督脉会于巅。其支者:从目系下颊里,环唇内。其支者:复从肝别贯膈,上注肺。++## 常用穴位++### 合谷穴+位置:在手背,第1、2掌骨间,当第2掌骨桡侧的中点处。+主治:头痛,目赤肿痛,鼻衄,齿痛,牙关紧闭,口眼歪斜,耳聋,痄腮,咽喉肿痛,热病无汗,多汗,腹痛,便秘,经闭,滞产。++### 足三里穴+位置:在小腿前外侧,当犊鼻下3寸,距胫骨前缘一横指(中指)。+主治:胃痛,呕吐,噎膈,腹胀,泄泻,痢疾,便秘,乳痈,肠痈,下肢痹痛,水肿,癫狂,脚气,虚劳羸瘦。++### 三阴交穴+位置:在小腿内侧,当足内踝尖上3寸,胫骨内侧缘后方。+主治:肠鸣腹胀,泄泻,月经不调,带下,阴挺,不孕,滞产,遗精,阳痿,遗尿,疝气,失眠,下肢痿痹,脚气。++### 关元穴+位置:在下腹部,前正中线上,当脐中下3寸。+主治:中风脱证,虚劳冷惫,羸瘦无力,少腹疼痛,霍乱吐泻,痢疾,脱肛,疝气,便血,溺血,小便不利,尿频,尿闭,遗精,白浊,阳痿,早泄,月经不调,经闭,经痛,赤白带下,阴挺,崩漏,阴门瘙痒,恶露不止,胞衣不下,消渴,眩晕。diff --git a/tests/fixtures/test_samples/zh/tcm/prescription_formulary_sample.md b/tests/fixtures/test_samples/zh/tcm/prescription_formulary_sample.mdnew file mode 100644index 0000000..c67c107--- /dev/null+++ b/tests/fixtures/test_samples/zh/tcm/prescription_formulary_sample.md@@ -0,0 +1,52 @@+# 方剂规范样本++## 桂枝汤++### 组成+桂枝三两(去皮)、芍药三两、甘草二两(炙)、生姜三两(切)、大枣十二枚(擘)++### 煎服法+上五味,咀三味,以水七升,微火煮取三升,去滓,适寒温,服一升。服已须臾,啜热稀粥一升余,以助药力,温覆令一时许,遍身微似有汗者益佳;不可令如水流离,病必不除。若一服汗出病瘥,停后服,不必尽剂;若不汗,更服,根据前法;又不汗,后服小促其间,半日许令三服尽。若病重者,一日一夜服,周时观之,服一剂尽,病证犹在者,更作服;若汗不出,乃服至二、三剂。++### 功能主治+解肌发表,调和营卫。主治太阳中风,阳浮而阴弱,阳浮者,热自发;阴弱者,汗自出。啬啬恶寒,淅淅恶风,翕翕发热,鼻鸣干呕者。++### 君臣佐使分析+- 君药:桂枝,辛温,解肌发表,温通经脉+- 臣药:芍药,酸苦微寒,益阴敛营+- 佐药:生姜,辛温,助桂枝解表;大枣,甘温,益气补中+- 使药:甘草,甘温,调和诸药++## 麻黄汤++### 组成+麻黄三两(去节)、桂枝二两(去皮)、甘草一两(炙)、杏仁七十个(去皮尖)++### 煎服法+上四味,以水九升,先煮麻黄,减二升,去上沫,内诸药,煮取二升半,去滓,温服八合,覆取微似汗,不须啜粥,余如桂枝法将息。++### 功能主治+发汗解表,宣肺平喘。主治太阳病,头痛、发热、身疼、腰痛、骨节疼痛、恶风、无汗而喘者。++### 君臣佐使分析+- 君药:麻黄,辛温,发汗解表,宣肺平喘+- 臣药:桂枝,辛温,解肌发表,温通经脉+- 佐药:杏仁,苦温,降利肺气,平喘止咳+- 使药:甘草,甘温,调和诸药++## 小柴胡汤++### 组成+柴胡半斤、黄芩三两、人参三两、甘草三两(炙)、生姜三两(切)、大枣十二枚(擘)、半夏半升(洗)++### 煎服法+上七味,以水一斗二升,煮取六升,去滓,再煎取三升,温服一升,日三服。++### 功能主治+和解少阳。主治伤寒五六日中风,往来寒热,胸胁苦满、嘿嘿不欲饮食、心烦喜呕,或胸中烦而不呕,或渴,或腹中痛,或胁下痞硬,或心下悸、小便不利,或不渴、身有微热,或咳者。++### 君臣佐使分析+- 君药:柴胡,苦平,和解少阳,疏泄肝胆+- 臣药:黄芩,苦寒,清泄少阳之热+- 佐药:人参、大枣、甘草,益气健脾;半夏、生姜,和胃降逆+- 使药:甘草,调和诸药