Skip to content

Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.

Add domain-specific knowledge extraction templates and instructions

yifanfeng97f6fa7e8664ed
diff --git a/hyperextract/templates/README.md b/hyperextract/templates/README.md
new file mode 100644
index 0000000..24359e6
--- /dev/null
+++ b/hyperextract/templates/README.md
@@ -0,0 +1,104 @@
+# Hyper-Extract Domain Knowledge Templates
+
+The **Hyper-Extract Domain Templates** library allows you to extract structured knowledge graphs (Temporal, Spatial, Hypergraph, etc.) directly from raw documents.
+
+This library is organized by **Domain**, ensuring that the extraction logic matches the specific vocabulary, document structures, and extraction goals of different industries.
+
+## Domain Index
+
+| Domain | Description | Key Focus |
+| :--- | :--- | :--- |
+| **`general`** | General Purpose | Encyclopedias, Biographies, Webpages |
+| **`finance`** | Finance & Investment | Reports, Filings, Transcripts |
+| **`medicine`** | Medicine & Health | Clinical Records, Guidelines, Drug Info |
+| **`tcm`** | Traditional Chinese Medicine | Case Records, Herbology, Acupuncture |
+| **`industry`** | Industry | Maintenance, Safety, Operations |
+| **`biology`** | Biological Science | Genomics, Proteomics, Ecology |
+| **`legal`** | Legal & Compliance | Contracts, Judgments, Regulations |
+| **`history`** | History & Culture | Chronicles, Timelines, Archives |
+| **`literature`** | Literature & Fiction | Scripts, Novels, World Building |
+| **`travel`** | Travel & Geography | Itineraries, Guides, Spatial Maps |
+| **`news`** | News & Media | Investigative Reports, Breaking News |
+| **`agriculture`** | Agriculture | Crop Management, Soil Analysis |
+| **`food`** | Food & Culinary | Recipes, Menu Engineering |
+
+---
+
+## Domain Details and Typical Documents
+
+### 1. `general` (General Purpose)
+The default choice for unstructured text that doesn't fit a specific industry.
+* **Wikipedia Articles / Encyclopedias**: Comprehensive descriptions of entities with structured infobox-like attributes.
+* **Biographies**: Life stories of individuals, focusing on key life events and relationships.
+* **Company "About Us" Pages**: Corporate self-descriptions focusing on history, mission, and key personnel.
+
+### 2. `finance` (Finance)
+Optimized for complex financial relationships, market sentiment, and temporal events.
+* **Equity Research Reports**: Detailed analysis by analysts containing ratings (Buy/Sell), target prices, valuation logic, and risk factors.
+* **Earnings Call Transcripts**: Dialogue between management and analysts, rich in non-structured performance attribution and strategic outlook.
+* **Prospectuses / IPO Filings (S-1)**: Comprehensive disclosures of company history, shareholder structure, and use of proceeds prior to listing.
+* **M&A Due Diligence Reports**: Documents detailing legal risks, business synergies, and financial health of target companies.
+
+### 3. `medicine` (Medicine)
+Focuses on causality, standardized terminology (UMLS mappings), and precise relationships.
+* **Clinical Practice Guidelines**: Standardized procedures for treating diseases, defining "Symptom -> Diagnosis -> Treatment" decision trees.
+* **Discharge Summaries**: Narrative records of a patient's hospital stay, including admission reason, hospital course, and discharge instructions.
+* **Pathology Reports**: Microscopic descriptions of tissue samples, detailing tumor grades, invasion depths, and histological features.
+* **Drug Package Inserts**: Legal documents listing indications, contraindications, dosage, and adverse reactions.
+
+### 4. `tcm` (Traditional Chinese Medicine)
+Specialized for the unique logic of syndrome differentiation (`Bian Zheng`) and herbal compatibility.
+* **Medical Case Records (Yi An)**: Clinical records from famous practitioners detailing symptoms, pattern differentiation logic, and the reasoning behind prescribed formulas.
+* **Herbal Compendiums (Ben Cao)**: Encyclopedic entries for single herbs describing their nature (Qi), flavor, meridian tropism, and functions.
+* **Prescription Formularies (Fang Zhu)**: Documents defining herbal formulas, including the role of each ingredient (Monarch, Minister, Assistant, Envoy).
+* **Meridian & Acupoint Treatises**: Texts defining the anatomical location of acupoints and their specific therapeutic effects.
+
+### 5. `industry` (Industry)
+Focuses on unstructured operational data in manufacturing, energy, and power sectors.
+* **Maintenance Logs & Work Orders**: Field records of equipment failures, repair actions taken, and parts replaced. often containing jargon and abbreviations.
+* **HSE Incident Reports**: Investigations into safety incidents, detailing the sequence of events, root causes, and corrective actions.
+* **Shift Handover Logs**: Summaries written by operators regarding equipment status changes, anomalies, and ongoing issues.
+* **Technical Specifications / Datasheets**: Semi-structured text describing equipment parameters, design standards, and performance curves.
+
+### 6. `biology` (Biology)
+Goes beyond genomics to include proteomics, metabolism, and ecology.
+* **Protein Structure Summaries (PDB Headers)**: Descriptions of protein crystal structures, ligand binding sites, and post-translational modifications.
+* **Metabolic Pathway Descriptions**: Texts explaining biochemical cascades, detailing enzymes, substrates, products, and regulation mechanisms.
+* **Ecological Survey Reports**: Documents recording species distribution, abundance, and habitat characteristics in specific geographic areas.
+* **Taxonomic Descriptions**: Detailed physical characterizations of organisms used for classification and identification.
+
+### 7. `legal` (Legal)
+Handles precise logical conditions, obligations, and citations.
+* **Master Service Agreements (MSA)**: Contracts defining long-term business relationships, liability limits, and intellectual property rights.
+* **Court Judgments**: Final rulings by judges, containing fact-finding sections, legal reasoning, and citations of precedents.
+* **Regulatory Compliance Filings**: Detailed reports submitted to government bodies regarding data privacy, anti-money laundering, or environmental impact.
+
+### 8. `history` (History)
+Heavily focused on long-span timelines and social networks.
+* **Chronicles & Annals**: Year-by-year records of events, focusing on temporal sequencing and regime changes.
+* **Oral History Transcripts**: First-person narratives, often non-linear and focused on personal experiences within historical events.
+* **Archival Correspondence**: Personal exchanges revealing social networks, hidden intents, and dates of specific interactions.
+
+### 9. `literature` (Literature & Fiction)
+Focuses on narrative structure, character interactions, and world-building.
+* **Screenplays / Scripts**: Highly structured texts (Scene Heading, Action, Dialogue) ideal for extracting character interaction graphs.
+* **Character Bibles**: Internal documents describing character backstories, personality traits, and relationships.
+* **Literary Criticism**: Analytical texts exploring themes, motifs, and intertextuality.
+
+### 10. `travel` (Travel)
+Focuses on spatial relationships and temporal sequences.
+* **Travel Itineraries**: Sequential plans including times, locations (POIs), transport modes, and accommodation.
+* **Destination Guides**: Comprehensive descriptions of places, including top logical relations (Next To, Inside) and cultural tips.
+
+### 11. `news` (News)
+Focuses on the "5Ws" (Who, What, Where, When, Why) and causality.
+* **Investigative Features**: Long-form reporting revealing complex causal chains and multi-party stakeholder relationships.
+* **Breaking News Wires**: Short, factual updates focusing on immediate events and entities.
+
+### 12. `agriculture` (Agriculture)
+* **Crop Scouting Reports**: Observations of crop growth stages, pest identification, and disease severity.
+* **Soil Analysis Reports**: Textual descriptions of soil chemical properties and corresponding fertilizer recommendations.
+
+### 13. `food` (Food)
+* **Standardized Recipes**: Step-by-step instructions including ingredients, preparation methods, and critical control points.
+* **Menu Engineering Reports**: Analysis of dishes involving flavor profiles, ingredients, and customer preferences.
diff --git a/hyperextract/templates/README_ZH.md b/hyperextract/templates/README_ZH.md
new file mode 100644
index 0000000..d8fe84d
--- /dev/null
+++ b/hyperextract/templates/README_ZH.md
@@ -0,0 +1,104 @@
+# Hyper-Extract 领域知识抽取模板
+
+**Hyper-Extract 领域模板库** 旨在为不同垂直行业提供专业的非结构化文本抽取能力。
+
+本库按 **领域 (Domain)** 组织,每个领域针对其特定的文档类型、行业术语和业务逻辑进行了优化。以下是各领域及其典型处理文档的介绍。
+
+## 领域索引
+
+| 领域代码 | 领域名称 | 核心关注点 |
+| :--- | :--- | :--- |
+| **`general`** | 通用百科 | 百科全书、人物传记、网页介绍 |
+| **`finance`** | 金融投资 | 研报、公告、会议纪要 |
+| **`medicine`** | 医疗健康 | 临床指南、病历、药品文档 |
+| **`tcm`** | 中医中药 | 医案、本草、方剂、经络 |
+| **`industry`** | 工业 | 运维日志、安全报告、技术规格 |
+| **`biology`** | 生物科学 | 蛋白组、代谢通路、生态调查 |
+| **`legal`** | 法律合规 | 合同协议、判决书、监管文件 |
+| **`history`** | 历史文化 | 编年史、信札、口述历史 |
+| **`literature`** | 文学与剧情 | 剧本、小说、设定集 |
+| **`travel`** | 旅游与地理 | 行程单、导览指南 |
+| **`news`** | 新闻传媒 | 调查报道、突发快讯 |
+| **`agriculture`** | 农业 | 巡田报告、土壤分析 |
+| **`food`** | 美食餐饮 | 标准化食谱、菜单分析 |
+
+---
+
+## 领域详情与典型文档
+
+### 1. `general` (通用领域)
+适用于无法归类或多领域交叉的文本,通过提取基础实体和SPO关系构建通用图谱。
+* **维基百科/百度百科条目**:对实体(人物、组织、地点)的综合性描述,包含结构化的属性信息。
+* **人物传记**:记录个人生平事迹、主要成就及社会关系的叙事性文本。
+* **企业官网“关于我们”**:描述公司历史、愿景及核心团队的官方文本。
+
+### 2. `finance` (金融)
+专注于提取复杂的交易关系、市场观点及时间敏感事件。
+* **股票研究报告 (Equity Research)**:分析师撰写的深度报告,包含评级(买入/卖出)、目标价、估值模型及风险提示。
+* **业绩电话会实录 (Earnings Call Transcripts)**:管理层与分析师的问答记录,包含非结构化的业绩归因及前瞻性指引。
+* **招股说明书 (Prospectus/IPO)**:企业上市前的全面披露文件,详述股权结构、募集资金用途及关联交易。
+* **并购尽职调查报告 (Due Diligence)**:详述目标公司的法律风险、业务协同效应及财务健康状况。
+
+### 3. `medicine` (医学)
+专注于疾病诊疗逻辑、标准化术语映射及因果关系提取。
+* **临床诊疗指南 (Clinical Guidelines)**:权威机构发布的标准化文档,定义了“症状-诊断-治疗-预后”的决策路径。
+* **出院小结 (Discharge Summaries)**:患者住院全过程的叙述性记录,包含入院主诉、诊疗经过及出院医嘱。
+* **病理报告 (Pathology Reports)**:对组织样本的微观描述,包含肿瘤分级、侵润深度及细胞学特征。
+* **药品说明书 (Package Inserts)**:法律规定的药品文档,包含适应症、禁忌症、不良反应及药物相互作用。
+
+### 4. `tcm` (中医中药)
+针对中医特有的辨证论治逻辑和药性理论进行优化。
+* **名医医案 (Medical Case Records)**:记录“望闻问切”症状、辨证分析(理)、治法(法)及处方(方药)的临床实录。
+* **本草典籍 (Herbal Compendiums)**:描述单味药的四气五味、归经、功效主治及配伍禁忌的文本。
+* **方剂规范 (Prescription Formularies)**:记载方剂组成的文档,包含君臣佐使的配伍结构及煎服法。
+* **经络腧穴专著 (Meridian Treatises)**:描述穴位解剖定位、归经及其特定主治功能的文本。
+
+### 5. `industry` (工业)
+专注于电力、制造、能源等行业的运维数据与非结构化日志分析。
+* **维修日志与工单 (Maintenance Logs)**:现场人员记录的设备故障现象、维修措施及备件更换情况,常包含大量行业术语。
+* **HSE安全事故报告 (Incident Reports)**:对生产事故的调查报告,包含事件时间线、根本原因分析 (RCA) 及整改措施。
+* **交接班记录 (Shift Handover)**:运行人员记录的设备状态变化、异常参数及遗留问题。
+* **技术规格书 (Technical Specifications)**:描述设备额定参数、材质标准及性能曲线的半结构化文本。
+
+### 6. `biology` (生物科学)
+从单一的基因组扩展到蛋白质组学、代谢通路及生态学。
+* **蛋白质结构摘要 (Protein Structure Summaries)**:描述蛋白质晶体结构、配体结合位点及修饰位点的文本。
+* **代谢通路描述 (Metabolic Pathways)**:解释生物化学反应级联的文本,涉及酶、底物、产物及调控机制。
+* **生态调查报告 (Ecological Surveys)**:记录特定区域内物种分布、种群数量及生境特征的考察文档。
+* **分类学描述 (Taxonomic Descriptions)**:对物种形态特征、鉴别要点及系统发育关系的详细记录。
+
+### 7. `legal` (法律)
+专注于提取权利义务逻辑、条件约束及法律事实。
+* **主服务协议 (MSA)**:定义长期商业合作框架的合同,包含责任限制、知识产权归属及违约条款。
+* **法院判决书 (Judgments)**:法官对案件的最终裁定,包含事实认定、法律推理及判例引用。
+* **合规申报文件 (Compliance Filings)**:企业提交给监管机构的关于数据合规、反洗钱或环境影响的详细陈述。
+
+### 8. `history` (历史)
+专注于长跨度的时间线梳理及人物社会网络构建。
+* **编年史 (Chronicles)**:按严格时间顺序记录的历史事件,侧重于时序演变。
+* **口述历史 (Oral History)**:亲历者的第一人称回忆录,包含非线性叙事及个人视角细节。
+* **档案馆藏信札 (Archival Correspondence)**:历史人物间的往来书信,揭示隐秘的社交网络和事件细节。
+
+### 9. `literature` (文学与影视)
+专注于叙事结构分析、角色互动及世界观设定。
+* **影视剧本 (Screenplays)**:格式严格的文本(场景头、动作、对白),适合提取角色互动图谱。
+* **角色设定集 (Character Bibles)**:描述角色背景故事、性格特征及人际关系的内部文档。
+* **文学评论 (Literary Criticism)**:对作品主题、隐喻及互文性关系的深度剖析。
+
+### 10. `travel` (旅游)
+专注于地理空间关系及路线规划。
+* **旅行行程单 (Itineraries)**:包含时间、地点 (POI)、交通及住宿安排的序列化文本。
+* **目的地指南 (Destination Guides)**:对地点的综合介绍,包含方位关系(位于、毗邻)及文化贴士。
+
+### 11. `news` (新闻)
+专注于新闻要素 (5W1H) 及事件因果链提取。
+* **深度调查报道 (Investigative Features)**:揭示复杂事件背后利益链条及多方博弈关系的长文。
+* **突发新闻电讯 (Breaking News)**:短小精悍、注重时效性和事实要素的实时消息。
+
+### 12. `agriculture` (农业)
+* **巡田报告 (Crop Scouting Reports)**:对作物生长阶段及病虫害情况的实地观察记录。
+* **土壤分析报告 (Soil Analysis)**:描述土壤化学成分及对应施肥建议的文本。
+
+### 13. `food` (美食餐饮)
+* **标准化食谱 (Standardized Recipes)**:包含配料表、烹饪步骤及关键控制点的结构化文本。
+* **菜单工程分析 (Menu Engineering)**:结合菜品描述与销售数据的分析文档。
diff --git a/hyperextract/templates/INSTRUCTION.md b/hyperextract/templates/en/INSTRUCTION.md
similarity index 100%
rename from hyperextract/templates/INSTRUCTION.md
rename to hyperextract/templates/en/INSTRUCTION.md
diff --git a/hyperextract/templates/en/README.md b/hyperextract/templates/en/README.md
deleted file mode 100644
index 8b263a2..0000000
--- a/hyperextract/templates/en/README.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# Hyper-Extract Domain Templates (English)
-
-Welcome to the **Hyper-Extract Domain Templates** library. This directory contains a robust, flat collection of pre-defined schemas, prompts, and extraction models tailored for specific industries and expertise areas.
-
-## Design Philosophy
-- **Flat Discovery**: No deep nesting. Find your domain directly in the top-level folders.
-- **Intuitive Naming**: Folders are named after common industry terminology (e.g., `finance`, `medicine`, `game`).
-- **Schema-Driven**: Each template provides a professional Pydantic schema to ensure high-quality extraction.
-
-## Domain Index
-
-| Folder | Description | Potential Use Cases |
-| :--- | :--- | :--- |
-| **`agriculture`** | Farming, livestock, and crop management. | Crop rotation, irrigation systems. |
-| **`biology`** | Life sciences, genetics, and taxonomy. | Protein interactions, species classification. |
-| **`finance`** | Banking, stocks, and investments. | Earnings reports, stock analysis. |
-| **`food`** | Culinary, recipes, and nutrition. | Menu planning, recipe breakdown. |
-| **`general`** | Basic encyclopedic knowledge. | General Person/Org/Event extraction. |
-| **`history`** | Events, timelines, and figures. | War campaigns, historical biographies. |
-| **`legal`** | Law, contracts, and compliance. | Contract obligations, court rulings. |
-| **`literature`** | Fiction, poetry, and character arcs. | Character maps, literary themes. |
-| **`medicine`** | Western and clinical medicine. | Diagnosis, symptom mapping, pharma. |
-| **`news`** | Media and trending topics. | Investigative boards, causality analysis. |
-| **`travel`** | Geography, tourism, and locations. | Travel guides, spatial relationships, tourism routes. |
-
-
-## Usage
-Simply import the template you need:
-```python
-from hyperextract.templates.en.finance import StockGraph
-```
diff --git a/hyperextract/templates/INSTRUCTION_ZH.md b/hyperextract/templates/zh/INSTRUCTION.md
similarity index 100%
rename from hyperextract/templates/INSTRUCTION_ZH.md
rename to hyperextract/templates/zh/INSTRUCTION.md
diff --git a/hyperextract/templates/zh/README.md b/hyperextract/templates/zh/README.md
deleted file mode 100644
index fef551e..0000000
--- a/hyperextract/templates/zh/README.md
+++ /dev/null
@@ -1,33 +0,0 @@
-# Hyper-Extract 领域知识模板 (中文版)
-
-欢迎使用 **Hyper-Extract 领域模板库**。这里提供了一系列针对中文语境和国内行业标准优化的提取模板。
-
-## 设计理念
-- **直觉导航**:采用扁平化目录结构,拒绝深层嵌套。
-- **行业深度**:每个模板均由特定领域的知识结构(Schema)和提示词(Prompt)驱动。
-- **文化融合**:在保持与国际标准接轨的同时,特别加入了如中医(TCM)、武侠(Wuxia)等中国特色文化领域。
-
-## 领域索引
-
-| 目录名称 | 说明 | 应用场景示例 |
-| :--- | :--- | :--- |
-| **`general`** | 通用百科 | 人物、机构、事件、地点等基础实体的快速抽取。 |
-| **`finance`** | 金融投资 | A股/港股研报、基金招募说明书、上市公司季报。 |
-| **`legal`** | 法律合规 | 合同关键要素(义务、权利)、案情调查、法条引用。 |
-| **`medicine`** | 医学健康 | 疾病症状映射、临床诊疗路径、西药说明书结构化。 |
-| **`food`** | 美食餐饮 | 中餐菜谱(刀工、火候)、食材配比、八大菜系特征。 |
-| **`history`** | 历史文化 | 朝代更迭时间线、重大战役、历史人物生平关系。 |
-| **`literature`** | 文学 | 小说人物关系网、文学流派演变、古诗词意象关联。 |
-| **`travel`** | 旅游与地理 | 游记、地理百科、地点空间关系、旅游路线规划。 |
-| **`agriculture`** | 农业与养殖 | 作物生长周期、病虫害防治、畜牧谱系与饲养标准。 |
-| **`biology`** | 生物科学 | 生物分类学、蛋白质相互作用、基因调控网络。 |
-| **`news`** | 新闻传媒 | 事件因果链、新闻专题聚类、深度报道事实板。 |
-| **`tcm`** | 中医 | 中草药方剂、经络穴位、辨证施治过程等。 |
-| **`wuxia`** | 武侠/修真 | 门派恩怨、功法境界、修仙等级体系、法宝神兵。 |
-
-*(注:英文版对应的 11 个通用领域在中文版中均有映射文件夹,中医与武侠为中文版独有)*
-
-## 快速上手
-```python
-from hyperextract.templates.zh.tcm import HerbGraph
-```
diff --git a/hyperextract/templates/zh/__init__.py b/hyperextract/templates/zh/__init__.py
index 2366158..dc5dabd 100644
--- a/hyperextract/templates/zh/__init__.py
+++ b/hyperextract/templates/zh/__init__.py
@@ -13,7 +13,7 @@ from .tcm import (
PrescriptionManualSet,
HerbInteractionHypergraph,
)
-from .wuxia import CultivationSystemMap, SectRelationGraph, ArtifactRegistry
+from .fantasy import CultivationSystemMap, SectRelationGraph, ArtifactRegistry
__all__ = [
"KnowledgeGraph",
diff --git a/hyperextract/templates/zh/wuxia/__init__.py b/hyperextract/templates/zh/wuxia/__init__.py
deleted file mode 100644
index b236940..0000000
--- a/hyperextract/templates/zh/wuxia/__init__.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from .cultivation_system_map import CultivationSystemMap
-from .sect_relation_graph import SectRelationGraph
-from .artifact_registry import ArtifactRegistry
-
-__all__ = [
- "CultivationSystemMap",
- "SectRelationGraph",
- "ArtifactRegistry",
-]
diff --git a/hyperextract/templates/zh/wuxia/artifact_registry.py b/hyperextract/templates/zh/wuxia/artifact_registry.py
deleted file mode 100644
index cb31513..0000000
--- a/hyperextract/templates/zh/wuxia/artifact_registry.py
+++ /dev/null
@@ -1,97 +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 DivineArtifact(BaseModel):
- """修真界或武侠世界中的神兵、法宝、丹药或天材地宝。"""
-
- name: str = Field(description="宝物名称(如:屠龙刀、九转金丹)。")
- grade: str = Field(description="品阶(如:天阶上品、神器、后天至宝)。")
- origin: Optional[str] = Field(
- description="来历或创造者(如:太上老君炼制、上古遗迹出土)。"
- )
- special_effects: List[str] = Field(
- description="独特神通或功效(如:吞噬神魂、破防、延寿千载)。"
- )
- spirit_consciousness: Optional[str] = Field(
- description="器灵或灵性描述(如:有一丝懵懂意识、器灵沉睡中)。"
- )
- current_owner: Optional[str] = Field(description="最近已知的持有者。")
-
-
-# ==============================================================================
-# 2. 提示词 (Prompts)
-# ==============================================================================
-
-_PROMPT = (
- "你是一位痴迷于搜集天下奇珍异宝的‘鉴宝宗师’。你的任务是从小说描述中建立一份神兵法宝、天材地宝及稀世丹药的名录。\n\n"
- "### 核心提取规则:\n"
- "1. **属性详尽性**:准确提取法宝的品阶(grade)、来历(origin)及核心用途。\n"
- "2. **神通动态更新**:解析法宝携带的独特神通(special_effects)。由于同一法宝在不同阶段显示的威力不同,请确保持续补充新发现的能力。\n"
- "3. **灵性洞察**:特别标注法宝是否具备‘器灵’(spirit_consciousness)及其性格特征或苏醒状态。\n"
- "4. **传承链条**:识别并更新该法宝的历史持有者及当前主人(current_owner)。\n"
- "5. **命名规范**:确保同一件法宝使用统一的名称作为主键,合并琐碎的描述。"
-)
-
-# ==============================================================================
-# 3. 模板类
-# ==============================================================================
-
-
-class ArtifactRegistry(AutoSet[DivineArtifact]):
- """
- 适用于:[武侠/仙侠小说, 奇幻游戏道具, 重宝名录]
-
- 一个旨在积累并完善神兵利器、法宝及稀世丹药属性的图鉴模板。
-
- Key Features:
- - 使用 AutoSet 逻辑合并同一法宝的多源信息。
- - 记录每件物品的品阶、创造者及必杀技。
- - 追踪贯穿叙事始终的器灵意识及归属权变更。
-
- Example:
- >>> from hyperextract.templates.zh.wuxia import ArtifactRegistry
- >>> registry = ArtifactRegistry(llm_client=llm, embedder=embedder)
- >>> text = "此剑名曰青索,乃紫青双剑之一,曾属长眉真人,剑中藏有一尊沉睡的青龙器灵。"
- >>> registry.feed_text(text).show()
- """
-
- def __init__(self, llm_client: BaseChatModel, embedder: Embeddings, **kwargs: Any):
- """
- 初始化 ArtifactRegistry。
-
- Args:
- llm_client (BaseChatModel): 用于提取的语言模型客户端。
- embedder (Embeddings): 用于索引的嵌入模型。
- **kwargs: 传递给 AutoSet 的额外参数。
- """
- super().__init__(
- schema=DivineArtifact,
- # 以名称作为唯一键
- key_extractor=lambda x: x.name.strip(),
- llm_client=llm_client,
- embedder=embedder,
- prompt=_PROMPT,
- **kwargs,
- )
-
- def show(self, **kwargs):
- """
- 展示法宝图鉴列表。
-
- Args:
- **kwargs: 传递给基础 show() 方法的参数。
- """
-
- def label_func(item: DivineArtifact) -> str:
- effects = ", ".join(item.special_effects[:2])
- return f"【{item.grade}】{item.name}: {effects}..."
-
- super().show(label_extractor=label_func, **kwargs)
diff --git a/hyperextract/templates/zh/wuxia/cultivation_system_map.py b/hyperextract/templates/zh/wuxia/cultivation_system_map.py
deleted file mode 100644
index ca6f06e..0000000
--- a/hyperextract/templates/zh/wuxia/cultivation_system_map.py
+++ /dev/null
@@ -1,137 +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 CultivationRealm(BaseModel):
- """武侠/修真体系中的修炼境界节点。"""
-
- name: str = Field(description="境界名称(如:练气期、元婴期、宗师境)。")
- system: str = Field(description="所属体系(如:仙道、武道、魔门、魂修)。")
- key_feature: Optional[str] = Field(
- description="该境界的核心特征(如:内力外放、御剑飞行、元神出窍)。"
- )
-
-
-class AdvancementCondition(BaseModel):
- """从一个境界突破到下一个境界的条件与风险。"""
-
- source: str = Field(description="当前境界。")
- target: str = Field(description="下一境界。")
- requirements: List[str] = Field(
- description="突破的前置条件(如:筑基丹、感悟剑意、渡雷劫)。"
- )
- risk: Optional[str] = Field(
- description="突破失败的后果或风险(如:走火入魔、修为尽废)。"
- )
- method: str = Field(
- description="修炼或突破的具体方法描述(如:闭关、双修、顿悟)。"
- )
-
-
-# ==============================================================================
-# 2. 提示词 (Prompts)
-# ==============================================================================
-
-_PROMPT = (
- "你是一位通晓诸天万界修炼体系的‘百晓生’。你的任务是分析并提取小说中的等级境界体系及晋升路径。\n\n"
- "### 核心提取规则:\n"
- "1. **层级严谨性**:确定境界的线性或分支关系(如从‘练气’到‘筑基’)。\n"
- "2. **突破细节**:识别每个大境界或小境界突破时的核心指标、所需外物(丹药、机缘)及外部环境(如雷劫、感悟)。\n"
- "3. **风险评估**:特别标注突破失败可能导致的走火入魔、修为跌落甚至陨落等描述。\n"
- "4. **体系独立性**:如果文本中存在多套体系(如武道与神修并存),确保互不混淆。"
-)
-
-_NODE_PROMPT = (
- "你是一位异世界设定分析师。请识别文本中出现的修炼境界节点及境界体系名称。\n\n"
- "### 提取要求:\n"
- "1. **粒度控制**:除了提取大境界名,也应提取具有显著特征的小层级(如‘大圆满’)。\n"
- "2. **属性补全**:捕捉该境界独有的神通或身体异化(如‘紫府初开’)。"
-)
-
-_EDGE_PROMPT = (
- "你是一位功法大演化专家。请在已识别的修炼境界间建立晋升脉络。\n\n"
- "### 逻辑连接规则:\n"
- "1. **进阶关系**:建立有向边,表示修行进阶的方向。\n"
- "2. **因果与条件**:详细提取‘如何突破’的动作(闭关、战斗突破等)及所需资源映射到 `requirements`。"
-)
-
-# ==============================================================================
-# 3. 模板类
-# ==============================================================================
-
-
-class CultivationSystemMap(AutoGraph[CultivationRealm, AdvancementCondition]):
- """
- 适用于:[仙侠/武侠小说, 游戏世界观设定, RPG 升级指南]
-
- 一个专门设计用于映射玄幻小说中复杂修炼等级及进阶逻辑的图谱模板。
-
- Key Features:
- - 厘清修炼境界的层级结构(如从“练气”到“筑基”)。
- - 捕获进阶所需的特定条件,如丹药、顿悟或雷劫。
- - 记录潜在的风险,包括修为倒退或走火入魔。
-
- Example:
- >>> from hyperextract.templates.zh.wuxia import CultivationSystemMap
- >>> cult_map = CultivationSystemMap(llm_client=llm, embedder=embedder)
- >>> text = "由筑基入金丹,需服九转金丹,历经三九雷劫,方可碎丹成婴。"
- >>> cult_map.feed_text(text).show()
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- *,
- extraction_mode: str = "two_stage",
- **kwargs: Any,
- ):
- """
- 初始化 CultivationSystemMap。
-
- Args:
- llm_client (BaseChatModel): 用于提取的语言模型客户端。
- embedder (Embeddings): 用于索引的嵌入模型。
- extraction_mode (str): 提取模式,'one_stage' 或 'two_stage'。默认为 'two_stage'。
- **kwargs: 传递给 AutoGraph 的额外参数。
- """
- super().__init__(
- node_schema=CultivationRealm,
- edge_schema=AdvancementCondition,
- 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,
- **kwargs,
- )
-
- def show(self, **kwargs):
- """
- 可视化修炼进阶图谱。
-
- Args:
- **kwargs: 传递给基础 show() 方法的参数。
- """
-
- def n_label(node: CultivationRealm) -> str:
- return f"{node.system}: {node.name}"
-
- def e_label(edge: AdvancementCondition) -> str:
- reqs = ",".join(edge.requirements)
- return f"突破条件: {reqs} | 风险: {edge.risk or '无'}"
-
- super().show(
- node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs
- )
diff --git a/hyperextract/templates/zh/wuxia/sect_relation_graph.py b/hyperextract/templates/zh/wuxia/sect_relation_graph.py
deleted file mode 100644
index 335332e..0000000
--- a/hyperextract/templates/zh/wuxia/sect_relation_graph.py
+++ /dev/null
@@ -1,134 +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 SectEntity(BaseModel):
- """武侠或修真世界中的势力实体:宗门、帮派、家族。"""
-
- name: str = Field(description="宗门名称(如:少林寺、天魔教、慕容世家)。")
- alignment: str = Field(
- description="阵营或正邪倾向(如:正道魁首、魔门六道、隐世家族)。"
- )
- location_base: Optional[str] = Field(description="山门驻地(如:嵩山、海外仙岛)。")
-
-
-class DiplomaticStance(BaseModel):
- """描述势力之间的复杂关系:盟友、世仇、联姻、主从。"""
-
- source: str = Field(description="发起方势力。")
- target: str = Field(description="对象势力。")
- relation_type: str = Field(
- description="关系性质(如:血海深仇、战略同盟、依附、表面交好)。"
- )
- origin_story: str = Field(
- description="该关系的成因或历史渊源(如:百年前正邪大战、争夺矿脉、老祖间的约定)。"
- )
- current_status: str = Field(description="当前状态(如:开战中、冷战、频繁往来)。")
-
-
-# ==============================================================================
-# 2. 提示词 (Prompts)
-# ==============================================================================
-
-_PROMPT = (
- "你是一位研究武林史的学者。你的任务是分析江湖中各大门派、世家、帮派之间的外交关系与势力消长。\n\n"
- "### 核心提取规则:\n"
- "1. **身份锚定**:准确区分‘名门正派’、‘魔教反派’、‘中立势力’及‘隐世家族’。\n"
- "2. **关系动态**:不仅识别当前的盟友或敌对状态,更要挖掘导致这种关系的‘历史恩怨’(origin_story)或‘共同利益’。\n"
- "3. **状态敏感性**:区分当前是‘交战中’、‘貌合神离’还是‘盟约稳固’。\n"
- "4. **势力冲突**:特别提取多方势力之间爆发的武林战争、围攻或利益纷争。"
-)
-
-_NODE_PROMPT = (
- "你是一位江湖密探。请识别文本中出现的门派、势力名称及其江湖地位。\n\n"
- "### 提取要求:\n"
- "1. **分类识别**:根据其行事风格将其分类为‘正、邪、中立’等。\n"
- "2. **驻位捕捉**:提取该门派的山门驻地或总坛位置。"
-)
-
-_EDGE_PROMPT = (
- "你是一位分析江湖纠葛的谋士。请识别各大势力间的互动与关联。\n\n"
- "### 逻辑连接规则:\n"
- "1. **关系定性**:在 `relation_type` 中明确标注‘同盟’、‘死敌’、‘附庸’或‘世代结亲’。\n"
- "2. **背景追溯**:在 `origin_story` 中记录导致该关系的标志性事件(如某次围攻黑木崖)。"
-)
-
-# ==============================================================================
-# 3. 模板类
-# ==============================================================================
-
-
-class SectRelationGraph(AutoGraph[SectEntity, DiplomaticStance]):
- """
- 适用于:[武侠/仙侠小说, 历史演义, 外交分析]
-
- 一个专注于建模虚构门派与势力间复杂社会政治关系的图谱模板。
-
- Key Features:
- - 将势力按道德立场分类(名门正派、魔门、中立)。
- - 映射主要门派的地理驻地。
- - 追踪历史恩怨的起源及当前的外交紧张局势。
-
- Example:
- >>> from hyperextract.templates.zh.wuxia import SectRelationGraph
- >>> sect_graph = SectRelationGraph(llm_client=llm, embedder=embedder)
- >>> text = "少林与武当交厚,共御魔教百年;然因屠龙刀现世,各大门派貌合神离。"
- >>> sect_graph.feed_text(text).show()
- """
-
- def __init__(
- self,
- llm_client: BaseChatModel,
- embedder: Embeddings,
- *,
- extraction_mode: str = "two_stage",
- **kwargs: Any,
- ):
- """
- 初始化 SectRelationGraph。
-
- Args:
- llm_client (BaseChatModel): 用于提取的语言模型客户端。
- embedder (Embeddings): 用于索引的嵌入模型。
- extraction_mode (str): 提取模式,'one_stage' 或 'two_stage'。默认为 'two_stage'。
- **kwargs: 传递给 AutoGraph 的额外参数。
- """
- super().__init__(
- node_schema=SectEntity,
- edge_schema=DiplomaticStance,
- node_key_extractor=lambda x: x.name.strip(),
- edge_key_extractor=lambda x: f"{x.source}->{x.relation_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: SectEntity) -> str:
- return f"[{node.alignment}] {node.name}"
-
- def e_label(edge: DiplomaticStance) -> str:
- return f"{edge.relation_type}: {edge.origin_story[:20]}..."
-
- super().show(
- node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs
- )