Skip to content

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

feat: Add templates for TCM and Wuxia domains

yifanfeng9781261d584465
diff --git a/hyperextract/templates/en/README.md b/hyperextract/templates/en/README.md
index b00231e..1a8ba3b 100644
--- a/hyperextract/templates/en/README.md
+++ b/hyperextract/templates/en/README.md
@@ -26,7 +26,7 @@ Welcome to the **Hyper-Extract Domain Templates** library. This directory contai
| **`medicine`** | Western and clinical medicine. | Diagnosis, symptom mapping, pharma. |
| **`movie`** | Film, TV, and scripts. | Screenplay beats, cast & crew networks. |
| **`news`** | Media and trending topics. | Investigative boards, causality analysis. |
-| **`physics`** | Particle physics, astronomy, and circuits. | Celestial systems, circuit paths. |
+
## Usage
Simply import the template you need:
diff --git a/hyperextract/templates/en/__init__.py b/hyperextract/templates/en/__init__.py
index f45d0ea..557ab06 100644
--- a/hyperextract/templates/en/__init__.py
+++ b/hyperextract/templates/en/__init__.py
@@ -2,6 +2,10 @@
from .agriculture import CropCycleGraph, LivestockGraph, AgriPestControl
from .biology import TaxonomyGraph, BiologicalNetwork, MetabolicHypergraph
from .chemistry import MolecularStructureGraph, ChemicalReactionHyper, LabProtocolTemporal
+from .literature import CharacterRelationshipGraph, NarrativeTimeline, SymbolismSet
+from .medicine import DrugInteractionGraph, ClinicalTreatmentTimeline, DiagnosticCriteriaSet
+from .movie import ScriptSceneGraph, CharacterArcTracker, CinematicTriviaSet
+from .news import BreakingEventGraph, TopicTimeline, OpinionSet
__all__ = [
"KnowledgeGraph",
@@ -16,4 +20,16 @@ __all__ = [
"MolecularStructureGraph",
"ChemicalReactionHyper",
"LabProtocolTemporal",
+ "CharacterRelationshipGraph",
+ "NarrativeTimeline",
+ "SymbolismSet",
+ "DrugInteractionGraph",
+ "ClinicalTreatmentTimeline",
+ "DiagnosticCriteriaSet",
+ "ScriptSceneGraph",
+ "CharacterArcTracker",
+ "CinematicTriviaSet",
+ "BreakingEventGraph",
+ "TopicTimeline",
+ "OpinionSet",
]
diff --git a/hyperextract/templates/en/game/__init__.py b/hyperextract/templates/en/game/__init__.py
index e69de29..9b7e976 100644
--- a/hyperextract/templates/en/game/__init__.py
+++ b/hyperextract/templates/en/game/__init__.py
@@ -0,0 +1,15 @@
+"""Game domain templates for knowledge extraction."""
+
+from .game_item_compendium import GameItemCompendium
+from .game_character_compendium import GameCharacterCompendium
+from .game_monster_compendium import GameMonsterCompendium
+from .patch_note_changelog import PatchNoteChangelog
+from .lore_faction_network import LoreFactionNetwork
+
+__all__ = [
+ "GameItemCompendium",
+ "GameCharacterCompendium",
+ "GameMonsterCompendium",
+ "PatchNoteChangelog",
+ "LoreFactionNetwork",
+]
diff --git a/hyperextract/templates/en/game/game_character_compendium.py b/hyperextract/templates/en/game/game_character_compendium.py
new file mode 100644
index 0000000..9f5efdc
--- /dev/null
+++ b/hyperextract/templates/en/game/game_character_compendium.py
@@ -0,0 +1,174 @@
+"""Game Character Compendium - Extracts unique game characters from various sources.
+
+This template builds a comprehensive character encyclopedia by automatically
+merging information from multiple sources: official lore, strategy guides,
+character guides, and patch notes.
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoSet
+
+# ==============================================================================
+# Schema Definition
+# ==============================================================================
+
+class GameCharacterSchema(BaseModel):
+ """Schema for individual game characters in the compendium."""
+
+ character_name: str = Field(
+ ..., description="The standard name of the character, e.g., 'Yasuo'"
+ )
+ character_class: str = Field(
+ ...,
+ description="Character class/role: 'Swordsman', 'Mage', 'Archer', 'Tank', 'Support', etc.",
+ )
+ background_story: Optional[str] = Field(
+ None, description="Character lore, origin story, and background"
+ )
+ signature_abilities: Optional[str] = Field(
+ None,
+ description="List of main/signature skills and abilities this character possesses",
+ )
+ base_stats: Optional[str] = Field(
+ None,
+ description="Base attributes: HP, mana, attack, defense, speed, etc. with numerical values",
+ )
+ recommended_playstyle: Optional[str] = Field(
+ None,
+ description="How to effectively play this character: positioning, combos, item builds, etc.",
+ )
+ origin_region: Optional[str] = Field(
+ None, description="The region/world area this character comes from"
+ )
+ faction_affiliation: Optional[str] = Field(
+ None, description="Which faction, team, or organization this character belongs to"
+ )
+ voice_actor: Optional[str] = Field(
+ None,
+ description="Official voice actor name(s) for this character in different languages",
+ )
+
+
+# ==============================================================================
+# Extraction Prompt
+# ==============================================================================
+
+_PROMPT = """You are an expert game lore specialist and character guide author.
+Your task is to extract comprehensive information about game characters from the provided text.
+
+For each character mentioned, extract:
+1. **character_name**: The official name of the character
+2. **character_class**: The combat role/class of the character
+3. **background_story**: Origin story, lore, and character background
+4. **signature_abilities**: Main and special abilities/skills this character has
+5. **base_stats**: Core numerical attributes: HP, mana, attack power, defense, etc.
+6. **recommended_playstyle**: Strategic guidance on how to effectively play this character
+7. **origin_region**: Which region or world area the character is from
+8. **faction_affiliation**: Which team, organization, or faction the character belongs to
+9. **voice_actor**: The official voice actor's name(s) if mentioned
+
+Extract only information explicitly stated in the text. If a field is not mentioned, leave it empty.
+Be comprehensive and capture all character details mentioned, even if scattered across the text.
+
+### Source Text:
+"""
+
+
+# ==============================================================================
+# Template Class
+# ==============================================================================
+
+class GameCharacterCompendium(AutoSet[GameCharacterSchema]):
+ """Applicable to: Character background stories, Skill guides, Official character bio, Strategy guides
+
+ Extracts a comprehensive game character encyclopedia by automatically
+ deduplicating and merging character information from multiple sources.
+
+ Information about the same character from different sources (official lore,
+ strategy guides, patch notes) is automatically combined into a single
+ enriched character profile.
+
+ Example:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> from hyperextract.templates.en.game import GameCharacterCompendium
+ >>>
+ >>> llm = ChatOpenAI(model="gpt-4", temperature=0)
+ >>> embedder = OpenAIEmbeddings()
+ >>>
+ >>> characters = GameCharacterCompendium(
+ ... llm_client=llm,
+ ... embedder=embedder
+ ... )
+ >>>
+ >>> # Feed multiple sources
+ >>> characters.feed_text(
+ ... "Yasuo was a swordsman of great honor from the Ionian isles. "
+ ... "He wields a blade with unmatched precision and speed."
+ ... )
+ >>> characters.feed_text(
+ ... "Yasuo's abilities include: Steel Tempest (Q), Wind Wall (W), Sweeping Blade (E), Last Breath (R). "
+ ... "Stats: 550 HP, 50 attack, 25 armor."
+ ... )
+ >>> characters.feed_text(
+ ... "As an ADC (attack-carry), Yasuo works best with items that increase attack speed "
+ ... "and critical chance. Position carefully in teamfights."
+ ... )
+ >>>
+ >>> # All info automatically merged into single Yasuo profile
+ >>> characters.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ """Initialize the Game Character Compendium template.
+
+ Args:
+ llm_client: Language model for character extraction (e.g., ChatOpenAI).
+ embedder: Embedding model for semantic indexing (e.g., OpenAIEmbeddings).
+ chunk_size: Maximum characters per text chunk (default 2048).
+ chunk_overlap: Overlapping characters between chunks (default 256).
+ **kwargs: Additional arguments passed to AutoSet parent class.
+ """
+ super().__init__(
+ item_schema=GameCharacterSchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ key_extractor=lambda x: x.character_name.strip().lower(),
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 3,
+ top_k_for_chat: int = 3,
+ ) -> None:
+ """Display the game character compendium as an interactive knowledge graph.
+
+ Args:
+ top_k_for_search: Number of top results for semantic search.
+ top_k_for_chat: Number of top results for chat context.
+ """
+
+ def character_label_extractor(item: GameCharacterSchema) -> str:
+ """Extract display label: name with class."""
+ class_label = f" ({item.character_class})" if item.character_class else ""
+ return f"{item.character_name}{class_label}"
+
+ super().show(
+ item_label_extractor=character_label_extractor,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/en/game/game_item_compendium.py b/hyperextract/templates/en/game/game_item_compendium.py
new file mode 100644
index 0000000..c40869c
--- /dev/null
+++ b/hyperextract/templates/en/game/game_item_compendium.py
@@ -0,0 +1,175 @@
+"""Game Item Compendium - Extracts unique game items from various sources.
+
+This template builds a comprehensive item library by automatically merging
+information about the same item from multiple sources (guides, wikis, patch notes).
+Uses AutoSet to deduplicate and combine item attributes.
+
+Example Sources:
+- Game Wiki pages describing item properties
+- Official strategy guides with item recommendations
+- Patch notes mentioning item changes
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoSet
+
+# ==============================================================================
+# Schema Definition
+# ==============================================================================
+
+class GameItemSchema(BaseModel):
+ """Schema for individual game items in the compendium."""
+
+ item_name: str = Field(
+ ..., description="The standard English or localized name of the item"
+ )
+ category: str = Field(
+ ...,
+ description="Item classification: 'Weapon', 'Armor', 'Consumable', 'Accessory', 'Material', etc.",
+ )
+ stat_bonuses: Optional[str] = Field(
+ None,
+ description="Attribute bonuses provided by this item, e.g., '+50 attack, +100 HP'",
+ )
+ crafting_recipe: Optional[str] = Field(
+ None, description="How to craft this item from other materials or items"
+ )
+ drop_sources: Optional[str] = Field(
+ None,
+ description="Where to obtain this item: which monsters drop it, NPCs who sell it, quest rewards, etc.",
+ )
+ suitable_heroes: Optional[str] = Field(
+ None, description="Which character classes or heroes benefit most from this item"
+ )
+ lore_background: Optional[str] = Field(
+ None, description="The gameplay lore or in-world story of this item"
+ )
+
+
+# ==============================================================================
+# Extraction Prompt
+# ==============================================================================
+
+_PROMPT = """You are an expert game designer and community guide author familiar with game item systems.
+Your task is to extract structured information about game items from the provided text.
+
+For each item mentioned in the text, extract:
+1. **item_name**: The official or standard name of the item
+2. **category**: The type/class of item (weapon, armor, consumable, etc.)
+3. **stat_bonuses**: Any attribute, damage, defense, or status effect bonuses this item provides
+4. **crafting_recipe**: How players can craft or combine items to create this item
+5. **drop_sources**: Where/who drops this item, shops that sell it, quest rewards, etc.
+6. **suitable_heroes**: Which character classes or heroes are recommended to use this item
+7. **lore_background**: Any in-game story, legend, or lore associated with this item
+
+Extract only information explicitly mentioned in the text. If a field is not described, leave it empty.
+Focus on being comprehensive and capturing all items mentioned, even if only briefly.
+
+### Source Text:
+"""
+
+
+# ==============================================================================
+# Template Class
+# ==============================================================================
+
+class GameItemCompendium(AutoSet[GameItemSchema]):
+ """Applicable to: Game Wiki pages, Strategy guides, Official item manuals, Patch notes
+
+ Extracts a comprehensive game item compendium by automatically deduplicating
+ and merging information about items from multiple sources.
+
+ This template is particularly useful for:
+ - Building unified item databases from scattered wiki information
+ - Merging item data from different strategy guides and patch notes
+ - Consolidating character recommendations and item synergies
+ - Creating rich item profiles by combining properties from multiple sources
+
+ When multiple text chunks describe the same item (identified by exact name matching),
+ their attributes are intelligently merged into a single enriched entry. This allows
+ gradual knowledge accumulation about each item across multiple documents.
+
+ Example:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> from hyperextract.templates.en.game import GameItemCompendium
+ >>>
+ >>> llm = ChatOpenAI(model="gpt-4", temperature=0)
+ >>> embedder = OpenAIEmbeddings()
+ >>>
+ >>> compendium = GameItemCompendium(
+ ... llm_client=llm,
+ ... embedder=embedder
+ ... )
+ >>>
+ >>> # Feed multiple sources
+ >>> compendium.feed_text(
+ ... "Endless Blade is a legendary weapon that grants +80 attack power. "
+ ... "It can be crafted by combining a Long Sword and a Crystal Core."
+ ... )
+ >>> compendium.feed_text(
+ ... "Endless Blade synergizes perfectly with Yasuo and Aatrox, "
+ ... "enabling powerful critical strike combos with these champions."
+ ... )
+ >>> compendium.feed_text(
+ ... "The Endless Blade has a dark lore: forged from the tears "
+ ... "of a fallen god to prevent the eternal night."
+ ... )
+ >>>
+ >>> # All information is automatically merged under 'Endless Blade'
+ >>> compendium.show() # Visualize the merged item compendium
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ """Initialize the Game Item Compendium template.
+
+ Args:
+ llm_client: Language model for item extraction (e.g., ChatOpenAI).
+ embedder: Embedding model for semantic indexing (e.g., OpenAIEmbeddings).
+ chunk_size: Maximum characters per text chunk (default 2048).
+ chunk_overlap: Overlapping characters between chunks (default 256).
+ **kwargs: Additional arguments passed to AutoSet parent class.
+ """
+ super().__init__(
+ item_schema=GameItemSchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ key_extractor=lambda x: x.item_name.strip().lower(),
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 3,
+ top_k_for_chat: int = 3,
+ ) -> None:
+ """Display the game item compendium as an interactive knowledge graph.
+
+ Args:
+ top_k_for_search: Number of top results to retrieve for semantic search queries.
+ top_k_for_chat: Number of top results to show in chat/dialogue context.
+ """
+
+ def item_label_extractor(item: GameItemSchema) -> str:
+ """Extract display label for an item: name with category."""
+ category_label = f" ({item.category})" if item.category else ""
+ return f"{item.item_name}{category_label}"
+
+ 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/game/game_monster_compendium.py b/hyperextract/templates/en/game/game_monster_compendium.py
new file mode 100644
index 0000000..c852860
--- /dev/null
+++ b/hyperextract/templates/en/game/game_monster_compendium.py
@@ -0,0 +1,179 @@
+"""Game Monster Compendium - Extracts unique game monsters from various sources.
+
+This template builds a comprehensive monster database by automatically merging
+information from guides, wikis, and bestiary entries.
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoSet
+
+# ==============================================================================
+# Schema Definition
+# ==============================================================================
+
+class GameMonsterSchema(BaseModel):
+ """Schema for individual game monsters in the compendium."""
+
+ monster_name: str = Field(
+ ..., description="The standard name of the monster, e.g., 'Goblin Warrior'"
+ )
+ monster_type: str = Field(
+ ...,
+ description="Monster species/racial classification: 'Goblin', 'Dragon', 'Undead', 'Beast', etc.",
+ )
+ rarity_tier: Optional[str] = Field(
+ None,
+ description="Rarity level of the monster: 'Common', 'Elite', 'Boss', 'Legendary', etc.",
+ )
+ habitat: Optional[str] = Field(
+ None, description="Map areas or regions where this monster typically appears"
+ )
+ combat_stats: Optional[str] = Field(
+ None,
+ description="Combat attributes with numerical values: HP, attack, defense, magic resist, etc.",
+ )
+ special_abilities: Optional[str] = Field(
+ None,
+ description="Unique skills or special attacks this monster can perform",
+ )
+ elemental_weakness: Optional[str] = Field(
+ None,
+ description="Element types this monster is weak to: Fire, Ice, Wind, Holy, Dark, etc.",
+ )
+ drop_table: Optional[str] = Field(
+ None,
+ description="Items dropped when defeated, including drop probability and item names",
+ )
+ respawn_timer: Optional[str] = Field(
+ None, description="How long it takes for this monster to respawn after defeat"
+ )
+ encounter_difficulty: Optional[str] = Field(
+ None, description="Recommended player level or difficulty assessment for encountering this monster"
+ )
+
+
+# ==============================================================================
+# Extraction Prompt
+# ==============================================================================
+
+_PROMPT = """You are an expert game bestiary and monster guide author.
+Your task is to extract structured information about game monsters from the provided text.
+
+For each monster mentioned, extract:
+1. **monster_name**: The official name of the monster
+2. **monster_type**: The species or racial type of the monster
+3. **rarity_tier**: How rare or powerful this monster is
+4. **habitat**: Locations where this monster can be found
+5. **combat_stats**: Numerical combat attributes (HP, ATK, DEF, etc.)
+6. **special_abilities**: Unique or dangerous abilities this monster has
+7. **elemental_weakness**: Element types that deal extra damage to this monster
+8. **drop_table**: What items this monster drops and with what probability
+9. **respawn_timer**: How long after defeat before the monster respawns
+10. **encounter_difficulty**: Recommended player level or challenge rating
+
+Extract only information explicitly mentioned. If a field is not described, leave it empty.
+Be comprehensive in capturing all monster details, even if scattered throughout the text.
+
+### Source Text:
+"""
+
+
+# ==============================================================================
+# Template Class
+# ==============================================================================
+
+class GameMonsterCompendium(AutoSet[GameMonsterSchema]):
+ """Applicable to: Monster guides, Bestiary entries, Farming guides, Patch notes
+
+ Extracts a comprehensive game monster database by automatically deduplicating
+ and merging monster information from multiple sources.
+
+ This template is particularly useful for:
+ - Building unified monster databases from scattered wiki information
+ - Merging monster data from multiple farming or hunting guides
+ - Consolidating stat information and drop tables
+ - Creating detailed monster profiles by combining data from multiple sources
+
+ Example:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> from hyperextract.templates.en.game import GameMonsterCompendium
+ >>>
+ >>> llm = ChatOpenAI(model="gpt-4", temperature=0)
+ >>> embedder = OpenAIEmbeddings()
+ >>>
+ >>> monsters = GameMonsterCompendium(
+ ... llm_client=llm,
+ ... embedder=embedder
+ ... )
+ >>>
+ >>> # Feed multiple sources
+ >>> monsters.feed_text(
+ ... "The Goblin Warrior is a melee fighter with 150 HP and 45 attack power. "
+ ... "Found in the Dark Forest zone, they respawn every 5 minutes."
+ ... )
+ >>> monsters.feed_text(
+ ... "Goblin Warriors are weak to Fire damage. They can use Shield Bash and Cleave attacks."
+ ... )
+ >>> monsters.feed_text(
+ ... "When defeated, Goblin Warriors drop: Leather Armor (20% chance), "
+ ... "Iron Sword (5% chance), and Gold Coins (100%)."
+ ... )
+ >>>
+ >>> # All info automatically merged into single Goblin Warrior profile
+ >>> monsters.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ """Initialize the Game Monster Compendium template.
+
+ Args:
+ llm_client: Language model for monster extraction (e.g., ChatOpenAI).
+ embedder: Embedding model for semantic indexing (e.g., OpenAIEmbeddings).
+ chunk_size: Maximum characters per text chunk (default 2048).
+ chunk_overlap: Overlapping characters between chunks (default 256).
+ **kwargs: Additional arguments passed to AutoSet parent class.
+ """
+ super().__init__(
+ item_schema=GameMonsterSchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ key_extractor=lambda x: x.monster_name.strip().lower(),
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 3,
+ top_k_for_chat: int = 3,
+ ) -> None:
+ """Display the game monster compendium as an interactive knowledge base.
+
+ Args:
+ top_k_for_search: Number of top results for semantic search.
+ top_k_for_chat: Number of top results for chat context.
+ """
+
+ def monster_label_extractor(item: GameMonsterSchema) -> str:
+ """Extract display label: name with type."""
+ type_label = f" ({item.monster_type})" if item.monster_type else ""
+ return f"{item.monster_name}{type_label}"
+
+ super().show(
+ item_label_extractor=monster_label_extractor,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/en/game/lore_faction_network.py b/hyperextract/templates/en/game/lore_faction_network.py
new file mode 100644
index 0000000..8051277
--- /dev/null
+++ b/hyperextract/templates/en/game/lore_faction_network.py
@@ -0,0 +1,231 @@
+"""Lore Faction Network - Extracts faction relationships from game lore.
+
+This template builds a political/social relationship graph showing how characters,
+factions, and regions interact within the game world.
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoGraph
+
+# ==============================================================================
+# Schema Definitions
+# ==============================================================================
+
+class LoreEntitySchema(BaseModel):
+ """Schema for entities in the lore network (characters, factions, regions)."""
+
+ entity_id: str = Field(..., description="Unique identifier for this entity")
+ entity_type: str = Field(
+ ...,
+ description="Type of entity: 'Hero' (character), 'Faction' (organization), or 'Region' (location)",
+ )
+ entity_name: str = Field(..., description="Name of the entity")
+ description: Optional[str] = Field(
+ None, description="Brief description of the entity's background or characteristics"
+ )
+
+
+class LoreRelationshipSchema(BaseModel):
+ """Schema for relationships in the lore network."""
+
+ source_entity: str = Field(..., description="Name of the source entity")
+ target_entity: str = Field(..., description="Name of the target entity")
+ relationship_type: str = Field(
+ ...,
+ description="Type of relationship: 'Belongs_To' (allegiance), 'At_War_With' (conflict), "
+ "'Betrayed' (betrayal), 'Founded' (founding), 'Ally_With' (alliance), etc.",
+ )
+ context: Optional[str] = Field(
+ None, description="Background context or explanation for this relationship"
+ )
+
+
+# ==============================================================================
+# Extraction Prompts - One-Stage and Two-Stage
+# ==============================================================================
+
+_PROMPT = """You are an expert game lore analyst specializing in world-building and faction relationships.
+Your task is to extract entities (Nodes) and their political/social relationships (Edges) from game lore text.
+
+Extract:
+1. **Entities (Nodes)**: All characters (heroes), factions (organizations), and regions mentioned
+ - For characters: name, type='Hero'
+ - For factions: name, type='Faction'
+ - For regions: name, type='Region'
+
+2. **Relationships (Edges)**: Political, military, and social connections
+ - Belongs_To: A character belongs to a faction or resides in a region
+ - At_War_With: Two factions or entities are in conflict
+ - Betrayed: A character/faction betrayed another
+ - Founded: A character founded a faction
+ - Ally_With: Formal alliance between factions
+ - Other relationship types based on context
+
+CRITICAL: Every edge must connect two entities that are present in the extracted nodes list.
+Do not create edges between entities that are not explicitly identified as nodes.
+
+Extract only information explicitly stated in the text.
+
+### Source Text:
+"""
+
+_NODE_PROMPT = """You are an expert entity recognition specialist for game lore.
+Your task is to extract all distinct entities from the text that will serve as nodes in a lore network.
+
+Extract three types of entities:
+1. **Heroes/Characters**: Individual persons with names (e.g., "Yasuo", "Ahri")
+2. **Factions/Organizations**: Groups, orders, nations, guilds (e.g., "Ionia", "Noxus", "The Watchers")
+3. **Regions/Locations**: Geographic areas and places (e.g., "Shadow Isles", "Piltover", "Demacia")
+
+For each entity, provide:
+- The entity name (as appears in text)
+- The entity type (Hero/Faction/Region)
+- A brief description if available
+
+Focus on completeness. Extract every entity mentioned, no matter how briefly.
+
+### Source Text:
+"""
+
+_EDGE_PROMPT = """You are an expert relationship extraction specialist for game lore networks.
+Your task is to extract relationships (edges) between the provided entities.
+
+Given the known entities list below, extract all relationships that connect them:
+- Belongs_To: Character belongs to faction; faction controls region
+- At_War_With: Entities in armed conflict
+- Betrayed: One entity betrayed another
+- Founded: Character founded a faction
+- Ally_With: Formal alliance between factions
+- Opposes: Opposition without necessarily warfare
+
+CRITICAL RULES:
+1. ONLY extract edges connecting entities from the known entity list provided below
+2. DO NOT invent or hallucinate new entities not in the provided list
+3. If an entity appears in text but isn't in the known list, DO NOT create edges involving it
+4. Focus on explicit relationship statements in the text
+
+Extract only explicitly stated relationships. Do not infer relationships not clearly described.
+
+### Source Text:
+"""
+
+
+# ==============================================================================
+# Template Class
+# ==============================================================================
+
+class LoreFactionNetwork(AutoGraph[LoreEntitySchema, LoreRelationshipSchema]):
+ """Applicable to: Game background stories, Lore documents, Character bios, Setting guides
+
+ Extracts a political and social relationship graph from game lore,
+ showing how characters, factions, and regions interact within the game world.
+
+ This template is particularly useful for:
+ - Visualizing faction relationships and hierarchies
+ - Understanding character allegiances and conflicts
+ - Building world-building maps of political structures
+ - Analyzing geopolitical dynamics in game settings
+
+ Example:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> from hyperextract.templates.en.game import LoreFactionNetwork
+ >>>
+ >>> llm = ChatOpenAI(model="gpt-4", temperature=0)
+ >>> embedder = OpenAIEmbeddings()
+ >>>
+ >>> lore_graph = LoreFactionNetwork(
+ ... llm_client=llm,
+ ... embedder=embedder,
+ ... extraction_mode="two_stage"
+ ... )
+ >>>
+ >>> lore_graph.feed_text('''
+ ... Yasuo is a swordsman from the region of Ionia. He belongs to the traditionalist faction.
+ ... Ionia is at war with Noxus for control of the eastern territories.
+ ... Ahri is a fox spirit who betrayed Yasuo when she sided with Noxus.
+ ... ''')
+ >>>
+ >>> # Nodes: Yasuo, Ionia, Noxus, Ahri
+ >>> # Edges: Yasuo->Ionia (Belongs_To), Ionia->Noxus (At_War_With), Ahri->Yasuo (Betrayed)
+ >>> lore_graph.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ extraction_mode: str = "two_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ """Initialize the Lore Faction Network template.
+
+ Args:
+ llm_client: Language model for extraction (e.g., ChatOpenAI).
+ embedder: Embedding model for semantic indexing (e.g., OpenAIEmbeddings).
+ extraction_mode: 'one_stage' (faster, simpler) or 'two_stage' (more accurate).
+ chunk_size: Maximum characters per text chunk (default 2048).
+ chunk_overlap: Overlapping characters between chunks (default 256).
+ **kwargs: Additional arguments passed to AutoGraph parent class.
+ """
+ super().__init__(
+ node_schema=LoreEntitySchema,
+ edge_schema=LoreRelationshipSchema,
+ node_key_extractor=lambda x: x.entity_name.strip().lower(),
+ edge_key_extractor=lambda x: (
+ f"{x.source_entity.strip().lower()}|"
+ f"{x.relationship_type.strip().lower()}|"
+ f"{x.target_entity.strip().lower()}"
+ ),
+ nodes_in_edge_extractor=lambda x: (
+ x.source_entity.strip().lower(),
+ x.target_entity.strip().lower(),
+ ),
+ llm_client=llm_client,
+ embedder=embedder,
+ extraction_mode=extraction_mode,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 5,
+ top_k_for_chat: int = 5,
+ ) -> None:
+ """Display the lore faction network as an interactive relationship graph.
+
+ Args:
+ top_k_for_search: Number of top entities to retrieve for search.
+ top_k_for_chat: Number of top entities to show in chat context.
+ """
+
+ def node_label_extractor(node: LoreEntitySchema) -> str:
+ """Extract display label showing entity type."""
+ type_emoji = {
+ "Hero": "👤",
+ "Faction": "🏛️",
+ "Region": "🗺️",
+ }
+ emoji = type_emoji.get(node.entity_type, "●")
+ return f"{emoji} {node.entity_name}"
+
+ def edge_label_extractor(edge: LoreRelationshipSchema) -> str:
+ """Extract display label for relationships."""
+ return edge.relationship_type.replace("_", " ")
+
+ 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/en/game/patch_note_changelog.py b/hyperextract/templates/en/game/patch_note_changelog.py
new file mode 100644
index 0000000..6ff9c6b
--- /dev/null
+++ b/hyperextract/templates/en/game/patch_note_changelog.py
@@ -0,0 +1,156 @@
+"""Patch Note Changelog - Extracts all individual changes from patch notes.
+
+This template extracts a comprehensive changelog of all game changes, modifications,
+and balance updates without deduplication, preserving every individual change entry.
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoList
+
+# ==============================================================================
+# Schema Definition
+# ==============================================================================
+
+class PatchChangeSchema(BaseModel):
+ """Schema for individual patch note entries."""
+
+ entity_name: str = Field(
+ ..., description="Name of the entity modified: character name, item name, etc."
+ )
+ change_type: str = Field(
+ ...,
+ description="Type of change: 'Buff' (increase), 'Nerf' (decrease), 'Mechanic Change', 'Bug Fix', 'Rework', etc.",
+ )
+ old_value: Optional[str] = Field(
+ None, description="Previous value or state before modification"
+ )
+ new_value: Optional[str] = Field(
+ None, description="New value or state after modification"
+ )
+ patch_version: Optional[str] = Field(
+ None, description="Version number or patch date when this change took effect"
+ )
+ developer_note: Optional[str] = Field(
+ None, description="Official explanation or reasoning for the change provided by developers"
+ )
+
+
+# ==============================================================================
+# Extraction Prompt
+# ==============================================================================
+
+_PROMPT = """You are an expert patch note analyst and game balance specialist.
+Your task is to extract detailed information about each individual game change from patch notes.
+
+For each change or modification mentioned, extract:
+1. **entity_name**: What is being modified (character, item, ability, system, etc.)
+2. **change_type**: The nature of the change (Buff, Nerf, Mechanic Change, Bug Fix, Rework, etc.)
+3. **old_value**: The previous value, stat, or mechanic before the change
+4. **new_value**: The new value, stat, or mechanic after the change
+5. **patch_version**: The patch version or date when this change was implemented
+6. **developer_note**: Any explanation or reasoning provided for the change
+
+CRITICAL: Extract EVERY individual change as a separate entry.
+If an entity has multiple changes in a patch (e.g., both attack nerfed AND defense buffed),
+create separate entries for each change to preserve complete change history.
+
+Extract only information explicitly mentioned in the text.
+Be comprehensive and capture all modifications, no matter how minor.
+
+### Source Text:
+"""
+
+
+# ==============================================================================
+# Template Class
+# ==============================================================================
+
+class PatchNoteChangelog(AutoList[PatchChangeSchema]):
+ """Applicable to: Official patch notes, Version changelogs, Balance updates
+
+ Extracts a detailed changelog of all game modifications from patch documentation.
+
+ Unlike AutoSet which deduplicates, this template preserves EVERY individual change
+ as a separate entry. This is essential for:
+ - Tracking complete balance history of each entity
+ - Analyzing multiple changes to the same entity in one patch
+ - Auditing game design decisions over time
+ - Building comprehensive patch databases without data loss
+
+ Example:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> from hyperextract.templates.en.game import PatchNoteChangelog
+ >>>
+ >>> llm = ChatOpenAI(model="gpt-4", temperature=0)
+ >>> embedder = OpenAIEmbeddings()
+ >>>
+ >>> changelog = PatchNoteChangelog(
+ ... llm_client=llm,
+ ... embedder=embedder
+ ... )
+ >>>
+ >>> # Feed patch notes
+ >>> changelog.feed_text('''
+ ... Patch 2.3.0 - Balance Update
+ ... Yasuo: Attack increased from 50 to 55 (buff to late-game scaling)
+ ... Yasuo: Wind Wall cooldown reduced from 25s to 20s (quality of life)
+ ... Endless Blade: Attack bonus increased from 80 to 85
+ ... ''')
+ >>>
+ >>> # Each change is preserved as separate entry, not merged
+ >>> # So we get 3 entries total, even though Yasuo has 2 changes
+ >>> changelog.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ """Initialize the Patch Note Changelog template.
+
+ Args:
+ llm_client: Language model for change extraction (e.g., ChatOpenAI).
+ embedder: Embedding model for semantic indexing (e.g., OpenAIEmbeddings).
+ chunk_size: Maximum characters per text chunk (default 2048).
+ chunk_overlap: Overlapping characters between chunks (default 256).
+ **kwargs: Additional arguments passed to AutoList parent class.
+ """
+ super().__init__(
+ item_schema=PatchChangeSchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 3,
+ top_k_for_chat: int = 3,
+ ) -> None:
+ """Display the patch changelog as an interactive database.
+
+ Args:
+ top_k_for_search: Number of top results for semantic search.
+ top_k_for_chat: Number of top results for chat context.
+ """
+
+ def change_label_extractor(item: PatchChangeSchema) -> str:
+ """Extract display label: entity with change type."""
+ return f"{item.entity_name} ({item.change_type})"
+
+ super().show(
+ item_label_extractor=change_label_extractor,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/en/history/__init__.py b/hyperextract/templates/en/history/__init__.py
index e69de29..44bea21 100644
--- a/hyperextract/templates/en/history/__init__.py
+++ b/hyperextract/templates/en/history/__init__.py
@@ -0,0 +1,11 @@
+"""History domain templates for knowledge extraction."""
+
+from .cultural_artifact_registry import CulturalArtifactRegistry
+from .war_timeline_graph import WarTimelineGraph
+from .diplomatic_event_hypergraph import DiplomaticEventHypergraph
+
+__all__ = [
+ "CulturalArtifactRegistry",
+ "WarTimelineGraph",
+ "DiplomaticEventHypergraph",
+]
diff --git a/hyperextract/templates/en/history/cultural_artifact_registry.py b/hyperextract/templates/en/history/cultural_artifact_registry.py
new file mode 100644
index 0000000..ea8a465
--- /dev/null
+++ b/hyperextract/templates/en/history/cultural_artifact_registry.py
@@ -0,0 +1,89 @@
+"""Cultural Artifact Registry - Extracts artifact information from historical sources.
+
+Builds a unified artifact knowledge base by merging data from museum catalogs,
+archaeological reports, and artifact descriptions.
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoSet
+
+
+class ArtifactSchema(BaseModel):
+ artifact_name: str = Field(..., description="Official name of the artifact")
+ material: Optional[str] = Field(None, description="Primary material composition")
+ excavation_year: Optional[str] = Field(
+ None, description="Year the artifact was discovered"
+ )
+ excavation_location: Optional[str] = Field(
+ None, description="Geographic location of excavation"
+ )
+ current_museum: Optional[str] = Field(
+ None, description="Current museum or collection location"
+ )
+ dimensions: Optional[str] = Field(
+ None, description="Size and weight specifications"
+ )
+ symbolic_meaning: Optional[str] = Field(
+ None, description="Cultural or religious significance"
+ )
+ historical_period: Optional[str] = Field(
+ None, description="Civilization or historical era"
+ )
+
+
+_PROMPT = """You are a professional archaeologist and museum curator.
+Extract comprehensive artifact information from the text:
+1. artifact_name: Official artifact name
+2. material: Material composition
+3. excavation_year: Discovery year
+4. excavation_location: Excavation site
+5. current_museum: Current location/museum
+6. dimensions: Physical measurements
+7. symbolic_meaning: Cultural significance
+8. historical_period: Historical era/dynasty
+
+Extract only explicitly mentioned information.
+
+### Source Text:
+"""
+
+
+class CulturalArtifactRegistry(AutoSet[ArtifactSchema]):
+ """Applicable to: Museum catalogs, Archaeological reports, Artifact documentation
+
+ Extracts comprehensive artifact encyclopedia by automatically merging information
+ from multiple historical sources.
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ super().__init__(
+ item_schema=ArtifactSchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ key_extractor=lambda x: x.artifact_name.strip().lower(),
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(self, *, top_k_for_search: int = 3, top_k_for_chat: int = 3) -> None:
+ def label_extractor(item: ArtifactSchema) -> str:
+ period = f" ({item.historical_period})" if item.historical_period else ""
+ return f"{item.artifact_name}{period}"
+
+ super().show(
+ item_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/en/history/diplomatic_event_hypergraph.py b/hyperextract/templates/en/history/diplomatic_event_hypergraph.py
new file mode 100644
index 0000000..e537f82
--- /dev/null
+++ b/hyperextract/templates/en/history/diplomatic_event_hypergraph.py
@@ -0,0 +1,96 @@
+"""Diplomatic Event Hypergraph - Extracts multi-party historical events.
+
+Models complex diplomatic events where multiple nations participate simultaneously,
+such as treaties and international conferences.
+"""
+
+from typing import Any, Optional, 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 CountrySchema(BaseModel):
+ entity_id: str = Field(..., description="Unique identifier")
+ country_name: str = Field(..., description="Name of the country/nation")
+
+
+class DiplomaticEventSchema(BaseModel):
+ hyperedge_id: str = Field(..., description="Unique identifier")
+ event_type: str = Field(..., description="'Treaty', 'Conference', 'Alliance', etc.")
+ event_name: str = Field(
+ ..., description="Name of the event (e.g., 'Treaty of Versailles')"
+ )
+ signing_date: Optional[str] = Field(None, description="Date of the event")
+ member_countries: List[str] = Field(
+ default_factory=list, description="All participating countries"
+ )
+ key_terms: Optional[str] = Field(
+ None, description="Summary of key terms or outcomes"
+ )
+ leading_country: Optional[str] = Field(
+ None, description="Leading or initiating country"
+ )
+
+
+_PROMPT = """Extract nodes (countries) and hyperedges (diplomatic events) from the text.
+A hyperedge connects multiple countries participating in a single event.
+
+### Source Text:
+"""
+
+_NODE_PROMPT = """Extract all country/nation names mentioned in the text."""
+
+_EDGE_PROMPT = """Extract diplomatic events involving multiple countries.
+For each event, list all participating countries in the member_countries field."""
+
+
+class DiplomaticEventHypergraph(AutoHypergraph[CountrySchema, DiplomaticEventSchema]):
+ """Applicable to: Treaties, International conference records, Diplomatic history
+
+ Extracts multi-party diplomatic events as hyperedges connecting multiple nations
+ simultaneously. Perfect for modeling complex international agreements.
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ extraction_mode: str = "two_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ super().__init__(
+ node_schema=CountrySchema,
+ edge_schema=DiplomaticEventSchema,
+ node_key_extractor=lambda x: x.country_name.strip().lower(),
+ edge_key_extractor=lambda x: f"{x.event_name.lower()}",
+ nodes_in_edge_extractor=lambda x: tuple(
+ c.strip().lower() for c in x.member_countries
+ ),
+ llm_client=llm_client,
+ embedder=embedder,
+ extraction_mode=extraction_mode,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(self, *, top_k_for_search: int = 5, top_k_for_chat: int = 5) -> None:
+ def node_label(node: CountrySchema) -> str:
+ return f"🏛️ {node.country_name}"
+
+ def edge_label(edge: DiplomaticEventSchema) -> str:
+ return f"{edge.event_type}: {edge.event_name}"
+
+ super().show(
+ node_label_extractor=node_label,
+ edge_label_extractor=edge_label,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/en/history/war_timeline_graph.py b/hyperextract/templates/en/history/war_timeline_graph.py
new file mode 100644
index 0000000..8687259
--- /dev/null
+++ b/hyperextract/templates/en/history/war_timeline_graph.py
@@ -0,0 +1,93 @@
+"""War Timeline Graph - Extracts temporal relationships in historical conflicts.
+
+Captures territorial changes, leadership transitions, and military events with
+time boundaries for precise historical analysis.
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoTemporalGraph
+
+class HistoricalEntitySchema(BaseModel):
+ entity_id: str = Field(..., description="Unique identifier")
+ entity_type: str = Field(..., description="'Polity' (state), 'City' (location), or 'General' (person)")
+ entity_name: str = Field(..., description="Name of the entity")
+
+class TemporalEventSchema(BaseModel):
+ source_entity: str = Field(..., description="Acting entity")
+ target_entity: str = Field(..., description="Affected entity")
+ edge_type: str = Field(..., description="'Occupied', 'Ruled_By', 'Besieged', etc.")
+ start_timestamp: Optional[int] = Field(None, description="Start year or timestamp")
+ end_timestamp: Optional[int] = Field(None, description="End year (if applicable)")
+ description: Optional[str] = Field(None, description="Event details")
+
+_PROMPT = """Extract historical entities (Nodes) and temporal events (Edges) showing
+territorial control and leadership changes during the specified period.
+
+For Nodes, extract: polities, cities, and key military leaders.
+For Edges, extract relationships with time boundaries:
+- start_timestamp: Begin year of the event
+- end_timestamp: End year (leave empty if ongoing)
+Ensure all edges connect nodes that exist in the extracted nodes list.
+
+### Source Text:
+"""
+
+_NODE_PROMPT = """Extract all historical entities mentioned: polities (states), cities,
+and military leaders. Include their names and basic descriptions."""
+
+_EDGE_PROMPT = """Extract temporal relationships between the known entities.
+For each relationship, provide exact year ranges when available.
+Only connect entities from the known entity list provided."""
+
+class WarTimelineGraph(AutoTemporalGraph[HistoricalEntitySchema, TemporalEventSchema]):
+ """Applicable to: Historical chronicles, War records, Textbook chapters
+
+ Extracts temporal knowledge graph capturing territorial control and military
+ events with precise time boundaries for historical analysis.
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ observation_time: str = "2024-01-01",
+ extraction_mode: str = "two_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ super().__init__(
+ node_schema=HistoricalEntitySchema,
+ edge_schema=TemporalEventSchema,
+ node_key_extractor=lambda x: x.entity_name.strip().lower(),
+ edge_key_extractor=lambda x: (
+ f"{x.source_entity.lower()}|{x.edge_type.lower()}|{x.target_entity.lower()}"
+ ),
+ time_in_edge_extractor=lambda x: f"{x.start_timestamp or ''}",
+ nodes_in_edge_extractor=lambda x: (x.source_entity.lower(), x.target_entity.lower()),
+ llm_client=llm_client,
+ embedder=embedder,
+ observation_time=observation_time,
+ extraction_mode=extraction_mode,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(self, *, top_k_for_search: int = 5, top_k_for_chat: int = 5) -> None:
+ def node_label(node: HistoricalEntitySchema) -> str:
+ return f"{node.entity_name} ({node.entity_type})"
+ def edge_label(edge: TemporalEventSchema) -> str:
+ return f"{edge.edge_type} ({edge.start_timestamp or '?'})"
+ super().show(
+ node_label_extractor=node_label,
+ edge_label_extractor=edge_label,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/en/legal/__init__.py b/hyperextract/templates/en/legal/__init__.py
index e69de29..6fcca93 100644
--- a/hyperextract/templates/en/legal/__init__.py
+++ b/hyperextract/templates/en/legal/__init__.py
@@ -0,0 +1,11 @@
+"""Legal domain templates for knowledge extraction."""
+
+from .contract_obligation_checklist import ContractObligationChecklist
+from .corporate_equity_graph import CorporateEquityGraph
+from .case_precedent_library import CasePrecedentLibrary
+
+__all__ = [
+ "ContractObligationChecklist",
+ "CorporateEquityGraph",
+ "CasePrecedentLibrary",
+]
diff --git a/hyperextract/templates/en/legal/case_precedent_library.py b/hyperextract/templates/en/legal/case_precedent_library.py
new file mode 100644
index 0000000..741e909
--- /dev/null
+++ b/hyperextract/templates/en/legal/case_precedent_library.py
@@ -0,0 +1,71 @@
+"""Case Precedent Library - Extracts and indexes legal precedents.
+
+Builds a searchable legal precedent database by automatically merging information
+about the same case from multiple sources.
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoSet
+
+class PrecedentSchema(BaseModel):
+ case_citation: str = Field(..., description="Official case citation/reference")
+ court_name: Optional[str] = Field(None, description="Court that decided the case")
+ judgment_year: Optional[str] = Field(None, description="Year of judgment")
+ legal_issues: Optional[str] = Field(None, description="Legal questions raised")
+ holding: Optional[str] = Field(None, description="Court's decision and legal principle")
+ cited_statutes: Optional[str] = Field(None, description="Laws referenced in judgment")
+ presiding_judges: Optional[str] = Field(None, description="Judge(s) who decided")
+ impact_assessment: Optional[str] = Field(None, description="Impact on subsequent law")
+
+_PROMPT = """You are a legal research specialist.
+Extract precedent case information:
+1. case_citation: Official case name/citation
+2. court_name: Court that heard it
+3. judgment_year: Decision year
+4. legal_issues: Legal questions
+5. holding: Court's ruling and principle
+6. cited_statutes: Applicable laws
+7. presiding_judges: Deciding judges
+8. impact_assessment: Influence on future cases
+
+### Source Text:
+"""
+
+class CasePrecedentLibrary(AutoSet[PrecedentSchema]):
+ """Applicable to: Court decisions, Legal databases, Case law reports
+
+ Extracts and indexes legal precedents by automatically merging case information
+ from multiple sources into a unified searchable library.
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ super().__init__(
+ item_schema=PrecedentSchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ key_extractor=lambda x: x.case_citation.strip().lower(),
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(self, *, top_k_for_search: int = 3, top_k_for_chat: int = 3) -> None:
+ def label_extractor(item: PrecedentSchema) -> str:
+ year = f" ({item.judgment_year})" if item.judgment_year else ""
+ return f"{item.case_citation}{year}"
+ super().show(
+ item_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/en/legal/contract_obligation_checklist.py b/hyperextract/templates/en/legal/contract_obligation_checklist.py
new file mode 100644
index 0000000..d7c57a3
--- /dev/null
+++ b/hyperextract/templates/en/legal/contract_obligation_checklist.py
@@ -0,0 +1,67 @@
+"""Contract Obligation Checklist - Extracts obligations and prohibitions from contracts.
+
+Builds a comprehensive compliance checklist by extracting all duties, responsibilities,
+and restrictions without deduplication to preserve complete audit trails.
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoList
+
+class ObligationSchema(BaseModel):
+ obligated_party: str = Field(..., description="Party responsible for performance")
+ obligation_type: str = Field(..., description="'MUST' (required) or 'MUST_NOT' (prohibited)")
+ action_description: str = Field(..., description="Specific action or requirement")
+ trigger_condition: Optional[str] = Field(None, description="When/if the obligation applies")
+ breach_penalty: Optional[str] = Field(None, description="Consequences of non-performance")
+ clause_reference: Optional[str] = Field(None, description="Original contract clause number")
+
+_PROMPT = """You are a contract lawyer and compliance auditor.
+Extract all obligations and restrictions from the contract:
+1. obligated_party: Who must perform
+2. obligation_type: MUST (required) or MUST_NOT (prohibited)
+3. action_description: Specific action/requirement
+4. trigger_condition: When obligation applies
+5. breach_penalty: Penalty for non-compliance
+6. clause_reference: Contract clause number
+
+Extract EVERY obligation independently. No merging.
+
+### Source Text:
+"""
+
+class ContractObligationChecklist(AutoList[ObligationSchema]):
+ """Applicable to: Contracts, ToS, Agreements, Compliance documents
+
+ Extracts a complete compliance checklist preserving every obligation separately
+ for comprehensive audit and risk analysis.
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ super().__init__(
+ item_schema=ObligationSchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(self, *, top_k_for_search: int = 3, top_k_for_chat: int = 3) -> None:
+ def label_extractor(item: ObligationSchema) -> str:
+ return f"{item.obligation_type}: {item.action_description[:50]}"
+ super().show(
+ item_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/en/legal/corporate_equity_graph.py b/hyperextract/templates/en/legal/corporate_equity_graph.py
new file mode 100644
index 0000000..f879193
--- /dev/null
+++ b/hyperextract/templates/en/legal/corporate_equity_graph.py
@@ -0,0 +1,81 @@
+"""Corporate Equity Graph - Extracts ownership and control relationships.
+
+Builds a shareholding graph showing investment relationships, control structures,
+and ultimate beneficial ownership through corporate pyramids.
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoGraph
+
+class EntitySchema(BaseModel):
+ entity_id: str = Field(..., description="Unique identifier")
+ entity_type: str = Field(..., description="'Company', 'Individual', or 'Fund'")
+ entity_name: str = Field(..., description="Legal name")
+ registration_number: Optional[str] = Field(None, description="Registration or ID number")
+
+class EquityRelationshipSchema(BaseModel):
+ source_entity: str = Field(..., description="Shareholder/owner name")
+ target_entity: str = Field(..., description="Company/entity name")
+ relationship_type: str = Field(..., description="'Owns_Shares', 'Controls', 'Serves_As_Officer'")
+ stake_percentage: Optional[str] = Field(None, description="Ownership percentage")
+ context: Optional[str] = Field(None, description="Additional context")
+
+_PROMPT = """Extract corporate entities and their ownership/control relationships."""
+
+_NODE_PROMPT = """Extract all entities: companies, individuals, funds mentioned."""
+
+_EDGE_PROMPT = """Extract ownership and control relationships between entities.
+Only connect entities from the known entity list."""
+
+class CorporateEquityGraph(AutoGraph[EntitySchema, EquityRelationshipSchema]):
+ """Applicable to: Due diligence reports, Prospectuses, Corporate filings
+
+ Extracts corporate ownership structures and ultimate beneficial ownership through
+ multi-level equity chains.
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ extraction_mode: str = "two_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ super().__init__(
+ node_schema=EntitySchema,
+ edge_schema=EquityRelationshipSchema,
+ node_key_extractor=lambda x: x.entity_name.strip().lower(),
+ edge_key_extractor=lambda x: (
+ f"{x.source_entity.lower()}|{x.relationship_type.lower()}|{x.target_entity.lower()}"
+ ),
+ nodes_in_edge_extractor=lambda x: (x.source_entity.lower(), x.target_entity.lower()),
+ llm_client=llm_client,
+ embedder=embedder,
+ extraction_mode=extraction_mode,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(self, *, top_k_for_search: int = 5, top_k_for_chat: int = 5) -> None:
+ def node_label(node: EntitySchema) -> str:
+ type_icon = {"Company": "🏢", "Individual": "👤", "Fund": "💼"}
+ icon = type_icon.get(node.entity_type, "●")
+ return f"{icon} {node.entity_name}"
+ def edge_label(edge: EquityRelationshipSchema) -> str:
+ pct = f" ({edge.stake_percentage})" if edge.stake_percentage else ""
+ return f"{edge.relationship_type}{pct}"
+ super().show(
+ node_label_extractor=node_label,
+ edge_label_extractor=edge_label,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/en/literature/__init__.py b/hyperextract/templates/en/literature/__init__.py
index e69de29..15ac04d 100644
--- a/hyperextract/templates/en/literature/__init__.py
+++ b/hyperextract/templates/en/literature/__init__.py
@@ -0,0 +1,9 @@
+from .character_relationship_graph import CharacterRelationshipGraph
+from .narrative_timeline import NarrativeTimeline
+from .symbolism_set import SymbolismSet
+
+__all__ = [
+ "CharacterRelationshipGraph",
+ "NarrativeTimeline",
+ "SymbolismSet",
+]
diff --git a/hyperextract/templates/en/literature/character_relationship_graph.py b/hyperextract/templates/en/literature/character_relationship_graph.py
new file mode 100644
index 0000000..90c92f7
--- /dev/null
+++ b/hyperextract/templates/en/literature/character_relationship_graph.py
@@ -0,0 +1,145 @@
+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 Character(BaseModel):
+ """A character entity in a literary work."""
+ name: str = Field(description="The full or most common name of the character.")
+ aliases: List[str] = Field(default_factory=list, description="Other names, titles, or nicknames used for the character.")
+ traits: List[str] = Field(default_factory=list, description="Core personality traits, skills, or physical attributes.")
+ description: Optional[str] = Field(description="A brief description of the character's role and significance in the story.")
+
+class Relationship(BaseModel):
+ """Social or emotional interaction between characters."""
+ source: str = Field(description="The name of the character initiating or participating in the relationship.")
+ target: str = Field(description="The name of the second character in the relationship.")
+ relation_type: str = Field(description="The nature of the relationship (e.g., Kinship, Romance, Rivalry, Mentorship).")
+ sentiment: str = Field(description="The emotional tone (e.g., Positive, Negative, Ambivalent, Intense).")
+ evidence: str = Field(description="Brief textual evidence or plot point supporting this relationship.")
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are a sophisticated literary critic and character analysis expert. "
+ "Your task is to extract character entities and their relationship networks from the literary text.\n\n"
+ "Extraction Guidelines:\n"
+ "1. **Character Identification**: Identify all significant characters. Record their names, aliases, and core character traits.\n"
+ "2. **Relationship Analysis**: Analyze dialogues, actions, and narrative descriptions to extract deep connections. "
+ "Focus not only on kinship but also on emotional bonds, ideological conflicts, and shifting allegiances.\n"
+ "3. **Evidence-Based**: Provide short textual evidence for each relationship.\n"
+ "- Ensure every edge connects two nodes that are explicitly listed in the character nodes."
+)
+
+_NODE_PROMPT = (
+ "As a literary expert, extract all key characters. For each character, provide their name, any known aliases, core personality tags, and a brief description of their role/status."
+)
+
+_EDGE_PROMPT = (
+ "Based on the extracted characters, identify the social and emotional relationships between them. "
+ "Specify the relationship type, emotional sentiment, and provide a brief justification based on the text."
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+class CharacterRelationshipGraph(AutoGraph[Character, Relationship]):
+ """
+ Applicable to: [Novels, Screenplays, Biographies, Dramas]
+
+ Knowledge pattern for extracting character networks and social structures in literature.
+
+ This template captures dynamic interactions, emotional tones, and structured connections,
+ supporting two-stage extraction for higher precision in complex narrative webs.
+
+ Example:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> # Initialize template
+ >>> characters = CharacterRelationshipGraph(llm_client=llm, embedder=embedder)
+ >>> # Feed text
+ >>> text = "Elizabeth Bennet's initial prejudice against Mr. Darcy was challenged by his noble actions."
+ >>> characters.feed_text(text)
+ >>> characters.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 CharacterRelationshipGraph template.
+
+ Args:
+ llm_client: The language model client.
+ embedder: Embeddings model for deduplication and indexing.
+ extraction_mode: "one_stage" (fast) or "two_stage" (accurate).
+ chunk_size: Max characters per processing chunk.
+ chunk_overlap: Overlap between chunks.
+ max_workers: Number of parallel extraction workers.
+ verbose: Enable detailed logging.
+ **kwargs: Extra arguments for AutoGraph.
+ """
+ super().__init__(
+ node_schema=Character,
+ edge_schema=Relationship,
+ 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,
+ 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 character relationship graph.
+
+ Args:
+ top_k_for_search: Number of nodes/edges to retrieve for search context.
+ top_k_for_chat: Number of nodes/edges to retrieve for chat context.
+ """
+ def node_label_extractor(node: Character) -> str:
+ return node.name
+
+ def edge_label_extractor(edge: Relationship) -> str:
+ return f"{edge.relation_type} ({edge.sentiment})"
+
+ 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/literature/narrative_timeline.py b/hyperextract/templates/en/literature/narrative_timeline.py
new file mode 100644
index 0000000..ed6470f
--- /dev/null
+++ b/hyperextract/templates/en/literature/narrative_timeline.py
@@ -0,0 +1,145 @@
+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 PlotPoint(BaseModel):
+ """A significant event or moment in the narrative flow."""
+ name: str = Field(description="A short title for the plot point or event (e.g., 'The Departure', 'Unexpected Reunion').")
+ location: Optional[str] = Field(description="Where the event takes place.")
+ characters_involved: List[str] = Field(default_factory=list, description="List of characters participating in this event.")
+ description: str = Field(description="Detailed description of the plot content, including key actions and shifts.")
+
+class TimeProgression(BaseModel):
+ """The temporal and logical connection between plot points."""
+ source: str = Field(description="The name of the preceding plot point.")
+ target: str = Field(description="The name of the subsequent plot point.")
+ time: str = Field(description="The resolved timestamp or absolute date of the event. You MUST resolve relative time expressions (e.g., 'three days later', 'next morning') into absolute dates (e.g., '2024-05-12') or specific years based on context and observation time.")
+ logic: str = Field(description="The logical relationship between events (e.g., Causality, Escalation, Sudden Twist).")
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are a narrative structure analyst. Your task is to reconstruct the temporal and logical blueprint of the story from the text.\n\n"
+ "Extraction Requirements:\n"
+ "1. **Event Identification**: Extract nodes with narrative significance, recording location and participants.\n"
+ "2. **Timeline Construction**: Establish connections with temporal attributes. Pay close attention to time indicators and markers.\n"
+ "3. **Logical Chains**: Beyond chronological order, identify the causal drivers between events.\n"
+ "Note: Time must be extracted on the edge (Progression), not as a standalone node."
+)
+
+_NODE_PROMPT = (
+ "Identify and extract all key plot points. Name each point and provide its location and the characters involved."
+)
+
+_EDGE_PROMPT = (
+ "Establish connections between the plot points. Accurately resolve temporal cues mentioned in the text into absolute dates or years, and describe how these events are linked in narrative logic."
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+class NarrativeTimeline(AutoTemporalGraph[PlotPoint, TimeProgression]):
+ """
+ Applicable to: [Chronicles, Epic Literature, Detective Novels, History Books]
+
+ Knowledge pattern for reconstructing narrative timelines and plot progressions.
+
+ Leveraging AutoTemporalGraph, this template embeds temporal information within relationships
+ to visualize the 'Cause-Process-Effect' dynamic of a story.
+
+ Example:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> # Initialize template
+ >>> timeline = NarrativeTimeline(llm_client=llm, embedder=embedder)
+ >>> # Feed text with temporal shifts
+ >>> text = "After the council, Frodo left the Shire. Months later, he reached the gates of Mordor."
+ >>> timeline.feed_text(text)
+ >>> timeline.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 NarrativeTimeline template.
+
+ Args:
+ llm_client: The language model client.
+ embedder: Embeddings model for deduplication and indexing.
+ observation_time: Base date for resolving relative time expressions like 'today' or 'yesterday'.
+ extraction_mode: Defaults to 'two_stage' for higher temporal resolution accuracy.
+ chunk_size: Max characters per processing chunk.
+ chunk_overlap: Overlap between chunks.
+ max_workers: Number of parallel extraction workers.
+ verbose: Enable detailed logging.
+ **kwargs: Extra arguments for AutoTemporalGraph.
+ """
+ super().__init__(
+ node_schema=PlotPoint,
+ edge_schema=TimeProgression,
+ node_key_extractor=lambda x: x.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 narrative timeline.
+
+ Args:
+ top_k_for_search: Number of nodes/edges to retrieve for search context.
+ top_k_for_chat: Number of nodes/edges to retrieve for chat context.
+ """
+ def node_label_extractor(node: PlotPoint) -> str:
+ return node.name
+
+ def edge_label_extractor(edge: TimeProgression) -> str:
+ return f"[{edge.time}] {edge.logic}"
+
+ 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/literature/symbolism_set.py b/hyperextract/templates/en/literature/symbolism_set.py
new file mode 100644
index 0000000..c180b56
--- /dev/null
+++ b/hyperextract/templates/en/literature/symbolism_set.py
@@ -0,0 +1,112 @@
+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 ImagerySymbol(BaseModel):
+ """An image or symbol in a literary work."""
+ symbol_name: str = Field(description="The name of the symbol/image (e.g., 'The Ocean', 'The Red Room', 'The Mockingbird').")
+ literal_meanings: List[str] = Field(description="Literal references or descriptions of the image in the text.")
+ metaphorical_meanings: List[str] = Field(description="Implicit symbolic meanings or deep metaphors associated with the image.")
+ contexts: List[str] = Field(description="Key textual snippets or chapter summaries where the symbol appears.")
+ thematic_connection: Optional[str] = Field(description="The connection between the symbol and the overall themes of the work.")
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are an expert literary critic. Your task is to identify and analyze recurring imagery and symbols within the text.\n\n"
+ "Analysis Guidelines:\n"
+ "1. **Normalization**: Ensure that variations of the same symbol (e.g., 'moonlight' and 'the moon') are grouped under a single standard symbol name to allow for information accumulation.\n"
+ "2. **Layered Interpretation**: Distinguish between the literal description of the image and its symbolic significance.\n"
+ "3. **Synthesis**: If a symbol appears in multiple parts of the text, continuously enrich its entry with new layers of meaning, context, and thematic significance.\n"
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+class SymbolismSet(AutoSet[ImagerySymbol]):
+ """
+ Applicable to: [Poetry, Modernist Novels, Literary Criticism, Essays]
+
+ Knowledge pattern for aggregating and deeply analyzing literary imagery and symbols.
+
+ Leveraging AutoSet's key-accumulation mechanism, this template automatically merges information
+ about the same symbol (literal descriptions, metaphors, thematic links) from across the entire work into a single enriched entry.
+
+ Example:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> # Initialize template
+ >>> symbolism = SymbolismSet(llm_client=llm, embedder=embedder)
+ >>> # Feed text from different chapters
+ >>> symbolism.feed_text("The green light at the end of the dock symbolizes Gatsby's hopes and dreams.")
+ >>> symbolism.feed_text("Gatsby reached out towards the green light, representing the unattainable past.")
+ >>> symbolism.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 SymbolismSet 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=ImagerySymbol,
+ key_extractor=lambda x: x.symbol_name.strip().lower(), # Exact key match 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 symbolism and imagery repository.
+
+ Args:
+ top_k_for_search: Items to retrieve for search.
+ top_k_for_chat: Items to retrieve for chat.
+ """
+ def item_label_extractor(item: ImagerySymbol) -> str:
+ return item.symbol_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/__init__.py b/hyperextract/templates/en/medicine/__init__.py
index e69de29..423c4b3 100644
--- a/hyperextract/templates/en/medicine/__init__.py
+++ b/hyperextract/templates/en/medicine/__init__.py
@@ -0,0 +1,9 @@
+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.py
new file mode 100644
index 0000000..1f78a8a
--- /dev/null
+++ b/hyperextract/templates/en/medicine/clinical_treatment_timeline.py
@@ -0,0 +1,143 @@
+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.py
new file mode 100644
index 0000000..739b54d
--- /dev/null
+++ b/hyperextract/templates/en/medicine/diagnostic_criteria_set.py
@@ -0,0 +1,112 @@
+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.py
new file mode 100644
index 0000000..19e7029
--- /dev/null
+++ b/hyperextract/templates/en/medicine/drug_interaction_graph.py
@@ -0,0 +1,142 @@
+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/en/movie/__init__.py b/hyperextract/templates/en/movie/__init__.py
index e69de29..200eca4 100644
--- a/hyperextract/templates/en/movie/__init__.py
+++ b/hyperextract/templates/en/movie/__init__.py
@@ -0,0 +1,5 @@
+from .character_arc_tracker import CharacterArcTracker
+from .cinematic_trivia_set import CinematicTriviaSet
+from .script_scene_graph import ScriptSceneGraph
+
+__all__ = ["CharacterArcTracker", "CinematicTriviaSet", "ScriptSceneGraph"]
diff --git a/hyperextract/templates/en/movie/character_arc_tracker.py b/hyperextract/templates/en/movie/character_arc_tracker.py
new file mode 100644
index 0000000..4a3ed52
--- /dev/null
+++ b/hyperextract/templates/en/movie/character_arc_tracker.py
@@ -0,0 +1,86 @@
+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 CharacterState(BaseModel):
+ """The state of a film character at a specific narrative point."""
+ character_name: str = Field(description="Name of the character.")
+ psychological_state: str = Field(description="The core emotional or psychological state of the character at this moment.")
+ current_goal: str = Field(description="The primary objective of the character at this moment.")
+ situation: str = Field(description="The external circumstances or conflicts the character is facing.")
+
+class CharacterDevelopment(BaseModel):
+ """Evolution and arc shifts between character states."""
+ source: str = Field(description="Starting state.")
+ target: str = Field(description="Resulting state.")
+ time: str = Field(description="The point or phase in the plot where the shift occurs (e.g., 'Act II', 'Pre-climax').")
+ trigger_event: str = Field(description="The key plot event that triggers this shift in state.")
+ arc_direction: str = Field(description="Direction of the arc (e.g., Growth, Corruption, Awakening, Realization).")
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are a sophisticated script analyst and character study expert. Your task is to track the 'character arc' from scripts or deep film reviews.\n\n"
+ "Extraction Guidelines:\n"
+ "1. **State Slicing**: Extract nodes representing the character's psychology, goals, and situation at different stages of the story.\n"
+ "2. **Trigger Identification**: Identify the key driving events that cause the transition between two character states.\n"
+ "3. **Timeline Resolution**: Clearly specify when the shift occurs (e.g., script page numbers, acts, or relative story phases).\n"
+)
+
+_NODE_PROMPT = "Identify and extract the character's internal and external states at key plot points. Record their emotions, current goals, and primary situations."
+_EDGE_PROMPT = "Analyze the evolution between character states. Point out what plot events triggered the psychological journey and summarize the direction of the arc."
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+class CharacterArcTracker(AutoTemporalGraph[CharacterState, CharacterDevelopment]):
+ """
+ Applicable to: [Character Biographies, Dramatic Scripts, Literary Adaptations, Film Reviews]
+
+ Template for analyzing film character growth paths and psychological arcs.
+
+ This template focuses on 'why' and 'how' a character changes, ideal for deep character studies and dramatic conflict analysis.
+
+ Example:
+ >>> arc = CharacterArcTracker(llm_client=llm, embedder=embedder)
+ >>> text = "At the start, Jack is a timid clerk. After the explosion, he realizes the value of life and shows incredible courage in the finale."
+ >>> arc.feed_text(text).show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "two_stage",
+ **kwargs: Any
+ ):
+ super().__init__(
+ node_schema=CharacterState,
+ edge_schema=CharacterDevelopment,
+ node_key_extractor=lambda x: f"{x.character_name}-{x.psychological_state[:10]}",
+ 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,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ extraction_mode=extraction_mode,
+ **kwargs
+ )
+
+ def show(self, **kwargs):
+ def n_label(node: CharacterState) -> str: return f"{node.character_name}: {node.psychological_state}"
+ def e_label(edge: CharacterDevelopment) -> str: return f"[{edge.time}] {edge.arc_direction}"
+ super().show(node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs)
diff --git a/hyperextract/templates/en/movie/cinematic_trivia_set.py b/hyperextract/templates/en/movie/cinematic_trivia_set.py
new file mode 100644
index 0000000..1959ad4
--- /dev/null
+++ b/hyperextract/templates/en/movie/cinematic_trivia_set.py
@@ -0,0 +1,69 @@
+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 Definitions
+# ==============================================================================
+
+class CinematicTrivia(BaseModel):
+ """Film elements, easter eggs, production trivia, or specific narrative elements."""
+ topic: str = Field(description="The theme or name of the trivia/element (e.g., 'Homage to 2001: A Space Odyssey', 'Fourth Wall Break').")
+ description: str = Field(description="Detailed content or production background of the element.")
+ timestamp: Optional[str] = Field(description="Specific time point in the film where the element appears (e.g., '01:23:45').")
+ significance: List[str] = Field(description="Artistic significance, narrative function, or special meaning to fans.")
+ source: List[str] = Field(description="Source of the information (e.g., Director's Commentary, IMDb, specific trivia sites).")
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are an expert film critic and cinema encyclopedist. Your task is to extract structured film trivia and encyclopedic points from reviews and production notes.\n\n"
+ "Analysis Guidelines:\n"
+ "1. **Topic Deduplication**: Merge multiple snippets regarding the same topic (e.g., 'Stan Lee Cameo'). Ensure standardized naming.\n"
+ "2. **Deep Dive**: Extract not just 'what' the element is, but also the artistic intent (significance) behind it.\n"
+ "3. **Accumulation**: Enrich the same topic with descriptions, timestamps, and sources over multiple text feeds.\n"
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+class CinematicTriviaSet(AutoSet[CinematicTrivia]):
+ """
+ Applicable to: [Production Notes, DVD Commentary, Behind-the-scenes, IMDB Trivia, Film Reviews]
+
+ Template for building and aggregating film encyclopedias and trivia.
+
+ This template leverages AutoSet's enrichment capabilities to aggregate scattered trivia knowledge across documents.
+
+ Example:
+ >>> trivia = CinematicTriviaSet(llm_client=llm, embedder=embedder)
+ >>> trivia.feed_text("The director placed a hidden homage to Kubrick at 86 minutes.").feed_text("The red chair is a direct nod to The Shining.")
+ >>> trivia.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ chunk_size: int = 2048,
+ **kwargs: Any
+ ):
+ super().__init__(
+ item_schema=CinematicTrivia,
+ key_extractor=lambda x: x.topic.strip().lower(),
+ llm_client=llm_client,
+ embedder=embedder,
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ **kwargs
+ )
+
+ def show(self, **kwargs):
+ def label(item: CinematicTrivia) -> str: return item.topic
+ super().show(item_label_extractor=label, **kwargs)
diff --git a/hyperextract/templates/en/movie/script_scene_graph.py b/hyperextract/templates/en/movie/script_scene_graph.py
new file mode 100644
index 0000000..60caaf4
--- /dev/null
+++ b/hyperextract/templates/en/movie/script_scene_graph.py
@@ -0,0 +1,91 @@
+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 Scene(BaseModel):
+ """A scene node in a screenplay."""
+ title: str = Field(description="Standard scene heading (e.g., 'INT. COFFEE SHOP - DAY').")
+ location: str = Field(description="Specific location where the scene occurs.")
+ time_of_day: str = Field(description="Time period (e.g., DAY, NIGHT, DUSK, DAWN).")
+ description: str = Field(description="Brief summary of actions or the core event within the scene.")
+
+class SceneTransition(BaseModel):
+ """Transition and logical flow between scenes."""
+ source: str = Field(description="Source scene title.")
+ target: str = Field(description="Target scene title.")
+ time: str = Field(description="Duration or time offset passed between scenes. You MUST resolve this into an absolute duration or precise timestamp/offset.")
+ transition_type: str = Field(description="Type of transition (e.g., CUT TO, FADE IN, DISSOLVE).")
+ logic: str = Field(description="Narrative logic (e.g., Continuous Action, Time Jump, Parallel Editing).")
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are an expert screenwriter and film director. Your task is to extract the scene flow and narrative logic from screenplays or storyboards.\n\n"
+ "Extraction Guidelines:\n"
+ "1. **Scene Identification**: Extract all independent scene nodes, recording the exact heading, location, and time of day.\n"
+ "2. **Rhythm Analysis**: Identify transition methods and accurately parse the passage of time between scenes.\n"
+ "3. **Narrative Logic**: Describe how scenes drive each other on a storytelling level.\n"
+)
+
+_NODE_PROMPT = "Extract all scenes from the script. Record the standard heading, location, time period, and a core plot summary for each."
+_EDGE_PROMPT = "Establish transitions between identified scenes. Note the transition method, and accurately infer the time span and narrative logical relationship."
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+class ScriptSceneGraph(AutoTemporalGraph[Scene, SceneTransition]):
+ """
+ Applicable to: [Movie Screenplays, Teleplays, Storyboards, Narrative Outlines]
+
+ Template for extracting scene flow and editing rhythm from screenplays.
+
+ This template focuses on presenting narrative tempo and scene shifts,
+ ideal for director-level script breakdown and visualization.
+
+ Example:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> script = ScriptSceneGraph(llm_client=llm, embedder=embedder)
+ >>> text = "SCENE 1: INT. LAB - DAY. Scientist experimenting. CUT TO: SCENE 2: EXT. STREET - NIGHT. Three hours later, he's walking."
+ >>> script.feed_text(text)
+ >>> script.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "two_stage",
+ **kwargs: Any
+ ):
+ super().__init__(
+ node_schema=Scene,
+ edge_schema=SceneTransition,
+ node_key_extractor=lambda x: x.title.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,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ extraction_mode=extraction_mode,
+ **kwargs
+ )
+
+ def show(self, **kwargs):
+ def n_label(node: Scene) -> str: return node.title
+ def e_label(edge: SceneTransition) -> str: return f"{edge.transition_type} ({edge.time})"
+ super().show(node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs)
diff --git a/hyperextract/templates/en/news/__init__.py b/hyperextract/templates/en/news/__init__.py
index e69de29..b33b750 100644
--- a/hyperextract/templates/en/news/__init__.py
+++ b/hyperextract/templates/en/news/__init__.py
@@ -0,0 +1,5 @@
+from .breaking_event_graph import BreakingEventGraph
+from .topic_timeline import TopicTimeline
+from .opinion_set import OpinionSet
+
+__all__ = ["BreakingEventGraph", "TopicTimeline", "OpinionSet"]
diff --git a/hyperextract/templates/en/news/breaking_event_graph.py b/hyperextract/templates/en/news/breaking_event_graph.py
new file mode 100644
index 0000000..597e3bd
--- /dev/null
+++ b/hyperextract/templates/en/news/breaking_event_graph.py
@@ -0,0 +1,84 @@
+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 Definition
+# ==============================================================================
+
+class NewsEntity(BaseModel):
+ """Actors or objects involved in a breaking news event."""
+ name: str = Field(description="Name of the person, organization, location, or country.")
+ category: str = Field(description="Type (e.g., Politician, NGO, Media, Government Body).")
+ attributes: List[str] = Field(description="Key descriptors or current status (e.g., 'Sanctioned', 'Reporting', 'Victim').")
+
+class NewsAction(BaseModel):
+ """Actions, statements, or events linking two news entities."""
+ source: str = Field(description="The initiator of the action.")
+ target: str = Field(description="The recipient or object of the action.")
+ action_type: str = Field(description="Nature of the action (e.g., Condemnation, Signing Agreement, Direct Strike).")
+ details: str = Field(description="Specific context or key information about the interaction.")
+ evidence: List[str] = Field(description="Source quotes or specific facts supporting this action.")
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are an expert geopolitical intelligence analyst. Your task is to extract the core structure of breaking events from news reports.\n\n"
+ "Extraction Requirements:\n"
+ "1. **Entity Identification**: Focus on main stakeholders (individuals, organizations, or nations).\n"
+ "2. **Dynamic Interaction**: Capture the 'Who did What to Whom'.\n"
+ "3. **Evidence Extraction**: Ensure specific actions are backed by verified statements or observable facts reported in the text.\n"
+)
+
+_NODE_PROMPT = "Identify all significant stakeholders in the breaking news. Categorize them and list their current roles or status mentioned."
+_EDGE_PROMPT = "Connect the stakeholders through their interactions. Define the nature of these actions and provide supporting evidence from the text."
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+class BreakingEventGraph(AutoGraph[NewsEntity, NewsAction]):
+ """
+ Applicable to: [Breaking News, Flash Reports, International Incidents, Press Releases]
+
+ A template designed for rapid mapping of key actors and their interactions in urgent news scenarios.
+
+ It excels at clarifying complex multilateral relationships during sudden events or crises.
+
+ Example:
+ >>> graph = BreakingEventGraph(llm_client=llm, embedder=embedder)
+ >>> text = "Country A imposed sanctions on Entity B, while Organization C called for a ceasefire."
+ >>> graph.feed_text(text).show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "two_stage",
+ **kwargs: Any
+ ):
+ super().__init__(
+ node_schema=NewsEntity,
+ edge_schema=NewsAction,
+ node_key_extractor=lambda x: x.name.strip(),
+ edge_key_extractor=lambda x: f"{x.source}->{x.action_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):
+ def n_label(node: NewsEntity) -> str: return f"{node.name} ({node.category})"
+ def e_label(edge: NewsAction) -> str: return f"{edge.action_type}"
+ super().show(node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs)
diff --git a/hyperextract/templates/en/news/opinion_set.py b/hyperextract/templates/en/news/opinion_set.py
new file mode 100644
index 0000000..d7d62db
--- /dev/null
+++ b/hyperextract/templates/en/news/opinion_set.py
@@ -0,0 +1,69 @@
+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 Definition
+# ==============================================================================
+
+class OpinionStance(BaseModel):
+ """The stance and viewpoint held by an entity on a specific topic."""
+ entity: str = Field(description="The individual, organization, media outlet, or group expressing the view.")
+ stance: str = Field(description="Core stance label (e.g., Support, Strong Opposition, Neutral, Questioning).")
+ key_argument: str = Field(description="The central argument or demand supporting this stance.")
+ evidence_provided: List[str] = Field(description="Supporting evidence, data, or facts provided by the entity.")
+ potential_interest: Optional[str] = Field(description="Implicit interests or motivations behind this stance.")
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are a multi-dimensional public opinion analyst. Your task is to identify and summarize the viewpoints and stances of different stakeholders from reports or commentaries.\n\n"
+ "Extraction Requirements:\n"
+ "1. **Entity Definition**: Clearly identify who is speaking.\n"
+ "2. **Stance Deconstruction**: Don't just record what was said; interpret the core attitude (stance) through tone and context.\n"
+ "3. **Argument Mapping**: Extract persuasive evidence from their statements.\n"
+ "4. **Horizontal Consolidation**: If multiple texts mention the same stance from the same entity, accumulate the new evidence into the existing entry.\n"
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+class OpinionSet(AutoSet[OpinionStance]):
+ """
+ Applicable to: [Public Opinion Analysis, Media Reviews, Debate Transcripts, Editorial Columns]
+
+ A knowledge mining template for summarizing the distribution of viewpoints and evidence across different actors in news and discourse.
+
+ Uses an AutoSet structure, accumulating knowledge based on the 'Entity + Stance' key, suitable for mapping complex debates.
+
+ Example:
+ >>> opinion_set = OpinionSet(llm_client=llm, embedder=embedder)
+ >>> text = "Organization A opposed the project, citing wetland destruction. The government argued it creates jobs."
+ >>> opinion_set.feed_text(text).show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ **kwargs: Any
+ ):
+ super().__init__(
+ schema=OpinionStance,
+ # Use combination of Entity and Stance as the key to accumulate similar views
+ key_extractor=lambda x: f"{x.entity.strip()}:{x.stance.strip()}",
+ llm_client=llm_client,
+ embedder=embedder,
+ prompt=_PROMPT,
+ **kwargs
+ )
+
+ def show(self, **kwargs):
+ def label_func(item: OpinionStance) -> str:
+ return f"[{item.stance}] {item.entity}: {item.key_argument}"
+ super().show(label_extractor=label_func, **kwargs)
diff --git a/hyperextract/templates/en/news/topic_timeline.py b/hyperextract/templates/en/news/topic_timeline.py
new file mode 100644
index 0000000..2802a1b
--- /dev/null
+++ b/hyperextract/templates/en/news/topic_timeline.py
@@ -0,0 +1,85 @@
+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 Definition
+# ==============================================================================
+
+class NewsEventNode(BaseModel):
+ """Core milestone nodes in a topical news story."""
+ event_summary: str = Field(description="Short title or summary of the event.")
+ location: Optional[str] = Field(description="Specific geographic location of the event.")
+ key_participants: List[str] = Field(description="List of core people or organizations involved.")
+
+class NewsTimelineProgression(BaseModel):
+ """The logic of event evolution over time."""
+ source: str = Field(description="Summary of the preceding event.")
+ target: str = Field(description="Summary of the subsequent event.")
+ time: str = Field(description="Exact point in time. You MUST resolve relative expressions (e.g., 'two weeks later') into absolute dates based on the context.")
+ evolution_type: str = Field(description="Nature of the development (e.g., Escalation, Turning Point, De-escalation, Chain Reaction).")
+ description: str = Field(description="Detailed description of this specific stage of evolution.")
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are a senior investigative journalist. Your task is to organize scattered news reports into a coherent narrative thread of development.\n\n"
+ "Extraction Requirements:\n"
+ "1. **Event Extraction**: Identify single, milestone events.\n"
+ "2. **Temporal Alignment**: Resolve all temporal markers into absolute formats and place them on the edges (Progression).\n"
+ "3. **Dynamic Links**: Emphasize how events are logically triggered by time and causality.\n"
+)
+
+_NODE_PROMPT = "Identify key milestone events in the reporting. Provide concise titles, locations, and core participants for each."
+_EDGE_PROMPT = "Establish a chronological chain between milestone events. Resolve relative time based on the provided reference dates."
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+class TopicTimeline(AutoTemporalGraph[NewsEventNode, NewsTimelineProgression]):
+ """
+ Applicable to: [Series Reports, Long-form Investigative Journalism, Dossiers, Historical Retrospectives]
+
+ A template used to link disconnected news reports into a coherent topical evolution timeline.
+
+ Focuses on the vertical development trajectory of an issue, suitable for tracking long-term social trends or policy changes.
+
+ Example:
+ >>> timeline = TopicTimeline(llm_client=llm, embedder=embedder)
+ >>> text = "Bill proposed in 2023. Six months later, it passed after debate. Effective next month."
+ >>> timeline.feed_text(text).show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "two_stage",
+ **kwargs: Any
+ ):
+ super().__init__(
+ node_schema=NewsEventNode,
+ edge_schema=NewsTimelineProgression,
+ node_key_extractor=lambda x: x.event_summary.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,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ extraction_mode=extraction_mode,
+ **kwargs
+ )
+
+ def show(self, **kwargs):
+ def n_label(node: NewsEventNode) -> str: return node.event_summary
+ def e_label(edge: NewsTimelineProgression) -> str: return f"[{edge.time}] {edge.evolution_type}"
+ super().show(node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs)
diff --git a/hyperextract/templates/en/physics/__init__.py b/hyperextract/templates/en/physics/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/hyperextract/templates/zh/README.md b/hyperextract/templates/zh/README.md
index 2c4ce32..64316a7 100644
--- a/hyperextract/templates/zh/README.md
+++ b/hyperextract/templates/zh/README.md
@@ -23,14 +23,13 @@
| **`agriculture`** | 农业与养殖 | 作物生长周期、病虫害防治、畜牧谱系与饲养标准。 |
| **`biology`** | 生物科学 | 生物分类学、蛋白质相互作用、基因调控网络。 |
| **`chemistry`** | 化学科学 | 分子结构、化学反应方程式路径、材料物化特性。 |
-| **`physics`** | 物理与天文 | 天体运行系统、量子物理现象、电路逻辑连接图。 |
| **`environment`** | 环境与气候 | 气象变化趋势、碳排放追踪、生态系统食物网。 |
| **`movie`** | 影视 | 剧本节拍器拆解、演员与幕后人员网络、影评情感。 |
| **`news`** | 新闻传媒 | 事件因果链、新闻专题聚类、深度报道事实板。 |
| **`tcm`** | **中医 (特色)** | 中草药方剂、经络穴位、辨证施治过程等。 |
| **`wuxia`** | **武侠/修真 (特色)** | 门派恩怨、功法境界、修仙等级体系、法宝神兵。 |
-*(注:英文版对应的 16 个通用领域在中文版中均有映射文件夹,中医与武侠为中文版独有)*
+*(注:英文版对应的 15 个通用领域在中文版中均有映射文件夹,中医与武侠为中文版独有)*
## 快速上手
```python
diff --git a/hyperextract/templates/zh/__init__.py b/hyperextract/templates/zh/__init__.py
index f45d0ea..2366158 100644
--- a/hyperextract/templates/zh/__init__.py
+++ b/hyperextract/templates/zh/__init__.py
@@ -2,6 +2,18 @@
from .agriculture import CropCycleGraph, LivestockGraph, AgriPestControl
from .biology import TaxonomyGraph, BiologicalNetwork, MetabolicHypergraph
from .chemistry import MolecularStructureGraph, ChemicalReactionHyper, LabProtocolTemporal
+from .literature import CharacterRelationshipGraph, NarrativeTimeline, SymbolismSet
+from .medicine import DrugInteractionGraph, ClinicalTreatmentTimeline, DiagnosticCriteriaSet
+from .movie import ScriptSceneGraph, CharacterArcTracker, CinematicTriviaSet
+from .news import BreakingEventGraph, TopicTimeline, OpinionSet
+from .tcm import (
+ PrescriptionCompositionGraph,
+ SyndromeTreatmentLoop,
+ MeridianAcupointSpatial,
+ PrescriptionManualSet,
+ HerbInteractionHypergraph,
+)
+from .wuxia import CultivationSystemMap, SectRelationGraph, ArtifactRegistry
__all__ = [
"KnowledgeGraph",
@@ -16,4 +28,24 @@ __all__ = [
"MolecularStructureGraph",
"ChemicalReactionHyper",
"LabProtocolTemporal",
+ "CharacterRelationshipGraph",
+ "NarrativeTimeline",
+ "SymbolismSet",
+ "DrugInteractionGraph",
+ "ClinicalTreatmentTimeline",
+ "DiagnosticCriteriaSet",
+ "ScriptSceneGraph",
+ "CharacterArcTracker",
+ "CinematicTriviaSet",
+ "BreakingEventGraph",
+ "TopicTimeline",
+ "OpinionSet",
+ "PrescriptionCompositionGraph",
+ "SyndromeTreatmentLoop",
+ "MeridianAcupointSpatial",
+ "PrescriptionManualSet",
+ "HerbInteractionHypergraph",
+ "CultivationSystemMap",
+ "SectRelationGraph",
+ "ArtifactRegistry",
]
diff --git a/hyperextract/templates/zh/game/__init__.py b/hyperextract/templates/zh/game/__init__.py
index e69de29..2c65399 100644
--- a/hyperextract/templates/zh/game/__init__.py
+++ b/hyperextract/templates/zh/game/__init__.py
@@ -0,0 +1,15 @@
+"""游戏领域模板。"""
+
+from .game_item_compendium import GameItemCompendium
+from .game_character_compendium import GameCharacterCompendium
+from .game_monster_compendium import GameMonsterCompendium
+from .patch_note_changelog import PatchNoteChangelog
+from .lore_faction_network import LoreFactionNetwork
+
+__all__ = [
+ "GameItemCompendium",
+ "GameCharacterCompendium",
+ "GameMonsterCompendium",
+ "PatchNoteChangelog",
+ "LoreFactionNetwork",
+]
diff --git a/hyperextract/templates/zh/game/game_character_compendium.py b/hyperextract/templates/zh/game/game_character_compendium.py
new file mode 100644
index 0000000..a5befd3
--- /dev/null
+++ b/hyperextract/templates/zh/game/game_character_compendium.py
@@ -0,0 +1,145 @@
+"""游戏角色百科 - 从多个来源自动合并游戏角色信息。
+
+该模板通过合并来自官方背景故事、策略指南、角色指南和补丁说明的多个来源的信息
+来提取全面的游戏角色百科。
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoSet
+
+# ==============================================================================
+# Schema 定义
+# ==============================================================================
+
+class GameCharacterSchema(BaseModel):
+ """游戏角色百科中单个角色的数据结构。"""
+
+ character_name: str = Field(..., description="角色的标准名称,如'亚索'")
+ character_class: str = Field(..., description="角色职业/角色定位:'剑士'、'法师'、'射手'、'坦克'、'辅助'等")
+ background_story: Optional[str] = Field(None, description="角色的背景故事、起源和身世")
+ signature_abilities: Optional[str] = Field(None, description="该角色拥有的主要技能和招牌能力清单")
+ base_stats: Optional[str] = Field(None, description="基础属性:生命值、魔法值、攻击力、防御力、速度等数值")
+ recommended_playstyle: Optional[str] = Field(None, description="如何有效地使用该角色:位置、连击、装备搭配等")
+ origin_region: Optional[str] = Field(None, description="该角色来自的游戏世界区域")
+ faction_affiliation: Optional[str] = Field(None, description="该角色所属的阵营、队伍或组织")
+ voice_actor: Optional[str] = Field(None, description="该角色的官方配音演员信息")
+
+
+# ==============================================================================
+# 提取 Prompt
+# ==============================================================================
+
+_PROMPT = """你是一位游戏背景设定专家和角色指南作者。
+你的任务是从文本中提取游戏角色的全面信息。
+
+对于文本中提到的每个角色,提取:
+1. **character_name**:角色的官方名称
+2. **character_class**:角色的职业/定位
+3. **background_story**:角色的起源故事和背景
+4. **signature_abilities**:该角色拥有的主要和特殊能力/技能
+5. **base_stats**:核心数值属性:生命值、魔法值、攻击力、防御力等
+6. **recommended_playstyle**:战略指导,如何有效地使用该角色
+7. **origin_region**:角色来自的区域或世界地区
+8. **faction_affiliation**:角色所属的队伍、组织或阵营
+9. **voice_actor**:官方配音演员的名字(如提及)
+
+仅提取文本中明确说明的信息。如果某个字段未提及,空置即可。
+全面捕捉所有角色详情,即使它们分散在文本中。
+
+### 源文本:
+"""
+
+
+# ==============================================================================
+# 模板类
+# ==============================================================================
+
+class GameCharacterCompendium(AutoSet[GameCharacterSchema]):
+ """适用于:角色背景故事、技能指南、官方角色资料、策略指南
+
+ 通过自动去重和合并来自多个来源的角色信息来提取全面的游戏角色百科。
+
+ 来自不同来源(官方背景、策略指南、补丁说明)关于同一角色的信息会自动
+ 组合成单个富集的角色档案。
+
+ 示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> from hyperextract.templates.zh.game import GameCharacterCompendium
+ >>>
+ >>> llm = ChatOpenAI(model="gpt-4", temperature=0)
+ >>> embedder = OpenAIEmbeddings()
+ >>>
+ >>> characters = GameCharacterCompendium(
+ ... llm_client=llm,
+ ... embedder=embedder
+ ... )
+ >>>
+ >>> # 输入多个来源
+ >>> characters.feed_text(
+ ... "亚索是来自印度群岛的一位荣誉剑士。"
+ ... "他以无与伦比的精准度和速度挥舞刀刃。"
+ ... )
+ >>> characters.feed_text(
+ ... "亚索的能力包括:钢铁飓风(Q)、风之障壁(W)、"
+ ... "逐风剑术(E)、最后通牒(R)。"
+ ... "属性:550生命值,50攻击力,25护甲。"
+ ... )
+ >>>
+ >>> # 所有信息自动合并为单个亚索档案
+ >>> characters.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ """初始化游戏角色百科模板。
+
+ 参数:
+ llm_client:语言模型客户端,用于角色提取(如 ChatOpenAI)
+ embedder:嵌入模型,用于语义索引(如 OpenAIEmbeddings)
+ chunk_size:单个文本块的最大字符数(默认2048)
+ chunk_overlap:相邻块之间的重叠字符数(默认256)
+ **kwargs:传递给 AutoSet 父类的其他参数
+ """
+ super().__init__(
+ item_schema=GameCharacterSchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ key_extractor=lambda x: x.character_name.strip().lower(),
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 3,
+ top_k_for_chat: int = 3,
+ ) -> None:
+ """展示游戏角色百科为交互式知识图谱。
+
+ 参数:
+ top_k_for_search:语义搜索返回的前 K 个结果数
+ top_k_for_chat:对话上下文中显示的前 K 个结果数
+ """
+
+ def character_label_extractor(item: GameCharacterSchema) -> str:
+ """提取展示标签:角色名称带职业"""
+ class_label = f" ({item.character_class})" if item.character_class else ""
+ return f"{item.character_name}{class_label}"
+
+ super().show(
+ item_label_extractor=character_label_extractor,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/zh/game/game_item_compendium.py b/hyperextract/templates/zh/game/game_item_compendium.py
new file mode 100644
index 0000000..19aab18
--- /dev/null
+++ b/hyperextract/templates/zh/game/game_item_compendium.py
@@ -0,0 +1,144 @@
+"""游戏物品图鉴 - 从多个来源自动合并游戏物品信息。
+
+该模板通过自动合并来自攻略、Wiki、补丁说明等多个来源的物品信息来构建完整的物品库。
+使用 AutoSet 按物品名称精确匹配去重并融合属性信息。
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoSet
+
+# ==============================================================================
+# Schema 定义
+# ==============================================================================
+
+class GameItemSchema(BaseModel):
+ """游戏物品图鉴中单个物品的数据结构。"""
+
+ item_name: str = Field(..., description="物品的标准名称")
+ category: str = Field(..., description="物品分类:'武器'、'防具'、'消耗品'、'配饰'、'材料'等")
+ stat_bonuses: Optional[str] = Field(
+ None, description="物品提供的属性加成,如'攻击力+50,生命值+100'"
+ )
+ crafting_recipe: Optional[str] = Field(None, description="如何通过合成其他物品获得该物品")
+ drop_sources: Optional[str] = Field(
+ None, description="物品的获取方式:掉落怪物、NPC商店、任务奖励等"
+ )
+ suitable_heroes: Optional[str] = Field(None, description="最适合装备该物品的职业或角色")
+ lore_background: Optional[str] = Field(None, description="物品的游戏进度设定或背景故事")
+
+
+# ==============================================================================
+# 提取 Prompt
+# ==============================================================================
+
+_PROMPT = """你是一位游戏设计师和游戏攻略作者,对游戏物品系统非常熟悉。
+你的任务是从文本中提取游戏物品的结构化信息。
+
+对于文本中提到的每个物品,提取:
+1. **item_name**:物品的标准名称
+2. **category**:物品的类型(武器、防具、消耗品等)
+3. **stat_bonuses**:该物品提供的属性、伤害、防御或状态效果加成
+4. **crafting_recipe**:玩家如何制作或合成该物品
+5. **drop_sources**:物品的掉落来源、商人、任务奖励等
+6. **suitable_heroes**:推荐哪些职业或角色使用该物品
+7. **lore_background**:与该物品相关的游戏故事或设定
+
+仅提取文本中明确提及的信息。如果某个字段没有描述,空置即可。
+重点是全面捕捉所有提到的物品及其详细信息。
+
+### 源文本:
+"""
+
+
+# ==============================================================================
+# 模板类
+# ==============================================================================
+
+class GameItemCompendium(AutoSet[GameItemSchema]):
+ """适用于:游戏 Wiki 页面、策略指南、官方物品手册、补丁说明
+
+ 通过自动去重和合并来自多个来源的物品信息来提取游戏物品图鉴。
+
+ 当多个文本块描述同一物品(通过精确名称匹配识别)时,其属性被智能合并为单一条目。
+ 这允许跨多个文档逐步积累关于每个物品的知识。
+
+ 示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> from hyperextract.templates.zh.game import GameItemCompendium
+ >>>
+ >>> llm = ChatOpenAI(model="gpt-4", temperature=0)
+ >>> embedder = OpenAIEmbeddings()
+ >>>
+ >>> compendium = GameItemCompendium(
+ ... llm_client=llm,
+ ... embedder=embedder
+ ... )
+ >>>
+ >>> # 输入多个来源
+ >>> compendium.feed_text(
+ ... "无尽之刃是一件传奇武器,提供+80攻击力。"
+ ... "可以通过长剑和魔晶合成获得。"
+ ... )
+ >>> compendium.feed_text(
+ ... "无尽之刃与亚索和亚托克斯完美契合,"
+ ... "能够启动这些英雄的强大暴击连击。"
+ ... )
+ >>>
+ >>> # 所有信息自动在"无尽之刃"下合并
+ >>> compendium.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ """初始化游戏物品图鉴模板。
+
+ 参数:
+ llm_client:语言模型客户端,用于物品提取(如 ChatOpenAI)
+ embedder:嵌入模型,用于语义索引(如 OpenAIEmbeddings)
+ chunk_size:单个文本块的最大字符数(默认2048)
+ chunk_overlap:相邻块之间的重叠字符数(默认256)
+ **kwargs:传递给 AutoSet 父类的其他参数
+ """
+ super().__init__(
+ item_schema=GameItemSchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ key_extractor=lambda x: x.item_name.strip().lower(),
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 3,
+ top_k_for_chat: int = 3,
+ ) -> None:
+ """展示游戏物品图鉴为交互式知识图谱。
+
+ 参数:
+ top_k_for_search:语义搜索返回的前 K 个结果数
+ top_k_for_chat:对话上下文中显示的前 K 个结果数
+ """
+
+ def item_label_extractor(item: GameItemSchema) -> str:
+ """提取展示标签:物品名称带分类"""
+ category_label = f" ({item.category})" if item.category else ""
+ return f"{item.item_name}{category_label}"
+
+ 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/game/game_monster_compendium.py b/hyperextract/templates/zh/game/game_monster_compendium.py
new file mode 100644
index 0000000..9a110b6
--- /dev/null
+++ b/hyperextract/templates/zh/game/game_monster_compendium.py
@@ -0,0 +1,148 @@
+"""游戏怪物百科 - 从多个来源自动合并游戏怪物信息。
+
+该模板通过合并来自攻略、Wiki、怪物掉落手册的多个来源的信息来构建
+全面的游戏怪物数据库。
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoSet
+
+# ==============================================================================
+# Schema 定义
+# ==============================================================================
+
+class GameMonsterSchema(BaseModel):
+ """游戏怪物百科中单个怪物的数据结构。"""
+
+ monster_name: str = Field(..., description="怪物的标准名称,如'哥布林战士'")
+ monster_type: str = Field(..., description="怪物种族分类:'哥布林'、'龙'、'亡灵'、'野兽'等")
+ rarity_tier: Optional[str] = Field(None, description="怪物的稀有程度:'普通'、'精英'、'首领'、'传奇'等")
+ habitat: Optional[str] = Field(None, description="该怪物通常出现的地图区域")
+ combat_stats: Optional[str] = Field(None, description="战斗属性和数值:生命值、攻击力、防御力、魔抗等")
+ special_abilities: Optional[str] = Field(None, description="该怪物拥有的独特技能或特殊攻击方式")
+ elemental_weakness: Optional[str] = Field(None, description="该怪物克制的元素类型:火、冰、风、圣、暗等")
+ drop_table: Optional[str] = Field(None, description="打败该怪物掉落的物品及掉落概率")
+ respawn_timer: Optional[str] = Field(None, description="该怪物被击败后的复活周期")
+ encounter_difficulty: Optional[str] = Field(None, description="遭遇该怪物的推荐玩家等级或难度评估")
+
+
+# ==============================================================================
+# 提取 Prompt
+# ==============================================================================
+
+_PROMPT = """你是一位游戏怪物图鉴和刷怪攻略作者。
+你的任务是从文本中提取游戏怪物的结构化信息。
+
+对于文本中提到的每个怪物,提取:
+1. **monster_name**:怪物的官方名称
+2. **monster_type**:怪物的种族或生物类型
+3. **rarity_tier**:该怪物的稀有程度或强度等级
+4. **habitat**:可以发现该怪物的位置或地图区域
+5. **combat_stats**:战斗属性的数值(生命值、攻击力、防御力等)
+6. **special_abilities**:该怪物拥有的独特或危险的能力
+7. **elemental_weakness**:克制该怪物的元素类型
+8. **drop_table**:打败该怪物可能掉落的物品和概率
+9. **respawn_timer**:怪物被击败后复活所需的时间
+10. **encounter_difficulty**:推荐的玩家等级或挑战难度评估
+
+仅提取文本中明确提及的信息。如果某个字段未描述,空置即可。
+全面捕捉所有怪物详情,即使分散在文本中。
+
+### 源文本:
+"""
+
+
+# ==============================================================================
+# 模板类
+# ==============================================================================
+
+class GameMonsterCompendium(AutoSet[GameMonsterSchema]):
+ """适用于:怪物指南、图鉴条目、刷怪指南、补丁说明
+
+ 通过自动去重和合并来自多个来源的怪物信息来提取全面的游戏怪物数据库。
+
+ 该模板特别适用于:
+ - 从分散的 Wiki 信息构建统一的怪物数据库
+ - 合并来自多个刷怪指南的怪物数据
+ - 整合属性信息和掉落表
+ - 通过合并来自多个来源的数据创建详细的怪物档案
+
+ 示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> from hyperextract.templates.zh.game import GameMonsterCompendium
+ >>>
+ >>> llm = ChatOpenAI(model="gpt-4", temperature=0)
+ >>> embedder = OpenAIEmbeddings()
+ >>>
+ >>> monsters = GameMonsterCompendium(
+ ... llm_client=llm,
+ ... embedder=embedder
+ ... )
+ >>>
+ >>> # 输入多个来源
+ >>> monsters.feed_text(
+ ... "哥布林战士是一个近战格斗者,拥有150生命值和45攻击力。"
+ ... "在黑暗森林区域发现,每5分钟复活一次。"
+ ... )
+ >>> monsters.feed_text(
+ ... "哥布林战士对火消伤害克制。它可以使用盾牌冲击和横扫攻击。"
+ ... )
+ >>>
+ >>> # 所有信息自动合并为单个哥布林战士档案
+ >>> monsters.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ """初始化游戏怪物百科模板。
+
+ 参数:
+ llm_client:语言模型客户端,用于怪物提取(如 ChatOpenAI)
+ embedder:嵌入模型,用于语义索引(如 OpenAIEmbeddings)
+ chunk_size:单个文本块的最大字符数(默认2048)
+ chunk_overlap:相邻块之间的重叠字符数(默认256)
+ **kwargs:传递给 AutoSet 父类的其他参数
+ """
+ super().__init__(
+ item_schema=GameMonsterSchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ key_extractor=lambda x: x.monster_name.strip().lower(),
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 3,
+ top_k_for_chat: int = 3,
+ ) -> None:
+ """展示游戏怪物百科为交互式知识库。
+
+ 参数:
+ top_k_for_search:语义搜索返回的前 K 个结果数
+ top_k_for_chat:对话上下文中显示的前 K 个结果数
+ """
+
+ def monster_label_extractor(item: GameMonsterSchema) -> str:
+ """提取展示标签:怪物名称带种族"""
+ type_label = f" ({item.monster_type})" if item.monster_type else ""
+ return f"{item.monster_name}{type_label}"
+
+ super().show(
+ item_label_extractor=monster_label_extractor,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/zh/game/lore_faction_network.py b/hyperextract/templates/zh/game/lore_faction_network.py
new file mode 100644
index 0000000..22f7c6d
--- /dev/null
+++ b/hyperextract/templates/zh/game/lore_faction_network.py
@@ -0,0 +1,226 @@
+"""世界观势力网 - 从游戏背景故事中提取势力关系。
+
+该模板构建政治/社会关系图,显示游戏世界中角色、阵营和地区之间的互动。
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoGraph
+
+# ==============================================================================
+# Schema 定义
+# ==============================================================================
+
+class LoreEntitySchema(BaseModel):
+ """背景故事网络中的实体(角色、阵营、地区)。"""
+
+ entity_id: str = Field(..., description="该实体的唯一标识符")
+ entity_type: str = Field(
+ ...,
+ description="实体的类型:'英雄'(角色)、'阵营'(组织)或'地区'(地点)",
+ )
+ entity_name: str = Field(..., description="实体的名称")
+ description: Optional[str] = Field(None, description="对该实体的背景或特征的简要描述")
+
+
+class LoreRelationshipSchema(BaseModel):
+ """背景故事网络中的关系。"""
+
+ source_entity: str = Field(..., description="关系的来源实体名称")
+ target_entity: str = Field(..., description="关系的目标实体名称")
+ relationship_type: str = Field(
+ ...,
+ description="关系类型:'隶属'(忠诚)、'敌对'(冲突)、"
+ "'背叛'(背叛)、'建立'(建立)、'盟友'(联盟)等",
+ )
+ context: Optional[str] = Field(None, description="该关系的背景信息或解释")
+
+
+# ==============================================================================
+# 提取 Prompt
+# ==============================================================================
+
+_PROMPT = """你是一位游戏背景故事分析专家,擅长世界构建和势力关系。
+你的任务是从游戏背景故事文本中提取实体(节点)及其政治/社会关系(边)。
+
+提取:
+1. **实体(节点)**:提到的所有角色(英雄)、阵营(组织)和地区
+ - 对于角色:名称,类型='英雄'
+ - 对于阵营:名称,类型='阵营'
+ - 对于地区:名称,类型='地区'
+
+2. **关系(边)**:政治、军事和社会联系
+ - 隶属:一个角色隶属于一个阵营或居住在一个地区
+ - 敌对:两个阵营或实体处于冲突中
+ - 背叛:一个角色/阵营背叛了另一个
+ - 建立:一个角色建立了一个阵营
+ - 盟友:阵营之间的正式联盟
+ - 其他基于背景的关系类型
+
+关键:每条边必须连接提取的节点列表中存在的两个实体。
+不创建不是显式识别为节点的实体之间的边。
+
+仅提取文本中明确说明的信息。
+
+### 源文本:
+"""
+
+_NODE_PROMPT = """你是一位游戏背景故事实体识别专家。
+你的任务是从文本中提取所有不同的实体,这些实体将成为背景故事网络的节点。
+
+提取三种类型的实体:
+1. **英雄/角色**:具有名字的个人(如"亚索"、"阿狸")
+2. **阵营/组织**:团体、组织、国家、公会(如"印度群岛"、"诺克萨斯"、"监视者")
+3. **地区/地点**:地理区域和地方(如"暗影岛"、"皮尔特沃夫"、"德玛西亚")
+
+对于每个实体,提供:
+- 实体名称(如文中所示)
+- 实体类型(英雄/阵营/地区)
+- 如果有的话,简要描述
+
+重点放在完整性上。提取每个提到的实体,无论多么短暂。
+
+### 源文本:
+"""
+
+_EDGE_PROMPT = """你是一位游戏背景故事网络关系提取专家。
+你的任务是提取已提供实体之间的关系(边)。
+
+给定下面的已知实体列表,提取连接它们的所有关系:
+- 隶属:角色属于阵营;阵营控制地区
+- 敌对:实体进行武装冲突
+- 背叛:一个实体背叛了另一个
+- 建立:角色建立了一个阵营
+- 盟友:阵营之间的正式联盟
+- 反对:反对而不一定是战争
+
+关键规则:
+1. 仅提取连接已提供实体列表中的实体的边
+2. 不要发明或虚构不在提供的列表中的新实体
+3. 如果实体出现在文本但不在已知列表中,不创建涉及它的边
+4. 关注文本中的显式关系陈述
+
+仅提取明确陈述的关系。不推断文中未清楚描述的关系。
+
+### 源文本:
+"""
+
+
+# ==============================================================================
+# 模板类
+# ==============================================================================
+
+class LoreFactionNetwork(AutoGraph[LoreEntitySchema, LoreRelationshipSchema]):
+ """适用于:游戏背景故事、背景文档、角色传记、设定指南
+
+ 从游戏背景故事中提取政治和社会关系图,显示游戏世界中
+ 角色、阵营和地区如何相互作用。
+
+ 该模板特别适用于:
+ - 可视化阵营关系和层级
+ - 理解角色忠诚度和冲突
+ - 构建世界构建图
+ - 分析游戏背景中的地缘政治动态
+
+ 示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> from hyperextract.templates.zh.game import LoreFactionNetwork
+ >>>
+ >>> llm = ChatOpenAI(model="gpt-4", temperature=0)
+ >>> embedder = OpenAIEmbeddings()
+ >>>
+ >>> lore_graph = LoreFactionNetwork(
+ ... llm_client=llm,
+ ... embedder=embedder,
+ ... extraction_mode="two_stage"
+ ... )
+ >>>
+ >>> lore_graph.feed_text('''
+ ... 亚索是来自Ionia地区的剑士。他属于传统主义阵营。
+ ... 印度群岛与诺克萨斯为争夺东方领土而交战。
+ ... 阿狸是一只狐狸精,当她转向诺克萨斯一方时背叛了亚索。
+ ... ''')
+ >>>
+ >>> # 节点:亚索、印度群岛、诺克萨斯、阿狸
+ >>> # 边:亚索->印度群岛(隶属)、印度群岛->诺克萨斯(敌对)、阿狸->亚索(背叛)
+ >>> lore_graph.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ extraction_mode: str = "two_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ """初始化世界观势力网模板。
+
+ 参数:
+ llm_client:语言模型客户端,用于提取(如 ChatOpenAI)
+ embedder:嵌入模型,用于语义索引(如 OpenAIEmbeddings)
+ extraction_mode:'one_stage'(更快、更简单)或'two_stage'(更准确)
+ chunk_size:单个文本块的最大字符数(默认2048)
+ chunk_overlap:相邻块之间的重叠字符数(默认256)
+ **kwargs:传递给 AutoGraph 父类的其他参数
+ """
+ super().__init__(
+ node_schema=LoreEntitySchema,
+ edge_schema=LoreRelationshipSchema,
+ node_key_extractor=lambda x: x.entity_name.strip().lower(),
+ edge_key_extractor=lambda x: (
+ f"{x.source_entity.strip().lower()}|"
+ f"{x.relationship_type.strip().lower()}|"
+ f"{x.target_entity.strip().lower()}"
+ ),
+ nodes_in_edge_extractor=lambda x: (
+ x.source_entity.strip().lower(),
+ x.target_entity.strip().lower(),
+ ),
+ llm_client=llm_client,
+ embedder=embedder,
+ extraction_mode=extraction_mode,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 5,
+ top_k_for_chat: int = 5,
+ ) -> None:
+ """展示世界观势力网为交互式关系图。
+
+ 参数:
+ top_k_for_search:搜索检索的前 K 个实体数
+ top_k_for_chat:对话上下文中显示的前 K 个实体数
+ """
+
+ def node_label_extractor(node: LoreEntitySchema) -> str:
+ """提取展示标签,显示实体类型"""
+ type_emoji = {
+ "英雄": "👤",
+ "阵营": "🏛️",
+ "地区": "🗺️",
+ }
+ emoji = type_emoji.get(node.entity_type, "●")
+ return f"{emoji} {node.entity_name}"
+
+ def edge_label_extractor(edge: LoreRelationshipSchema) -> str:
+ """提取关系的展示标签"""
+ return edge.relationship_type.replace("_", " ")
+
+ 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/game/patch_note_changelog.py b/hyperextract/templates/zh/game/patch_note_changelog.py
new file mode 100644
index 0000000..9654899
--- /dev/null
+++ b/hyperextract/templates/zh/game/patch_note_changelog.py
@@ -0,0 +1,146 @@
+"""版本更新日志 - 从补丁说明提取所有单独的游戏改动。
+
+该模板提取游戏补丁的全面变更日志,所有修改、平衡更新和错误修复,
+无去重,保留每个独立的变更条目。
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoList
+
+# ==============================================================================
+# Schema 定义
+# ==============================================================================
+
+class PatchChangeSchema(BaseModel):
+ """补丁说明中单个变更条目的数据结构。"""
+
+ entity_name: str = Field(..., description="被修改的对象名称:角色名称、物品名称等")
+ change_type: str = Field(
+ ...,
+ description="变更类型:'增强'(提升)、'削弱'(下降)、'机制调整'、'错误修复'、'重做'等",
+ )
+ old_value: Optional[str] = Field(None, description="修改前的数值或状态")
+ new_value: Optional[str] = Field(None, description="修改后的数值或状态")
+ patch_version: Optional[str] = Field(None, description="该变更生效的版本号或补丁日期")
+ developer_note: Optional[str] = Field(None, description="开发者提供的变更理由或说明")
+
+
+# ==============================================================================
+# 提取 Prompt
+# ==============================================================================
+
+_PROMPT = """你是一位补丁说明分析专家和游戏平衡设计师。
+你的任务是从补丁说明中提取每个单独的游戏变更的详细信息。
+
+对于提到的每个变更或修改,提取:
+1. **entity_name**:被修改的对象(角色、物品、能力、系统等)
+2. **change_type**:变更的性质(增强、削弱、机制调整、错误修复、重做等)
+3. **old_value**:变更前的数值、属性或机制
+4. **new_value**:变更后的数值、属性或机制
+5. **patch_version**:该变更实施的补丁版本或日期
+6. **developer_note**:对变更的解释或理由(如提供)
+
+关键:将每个单独的变更作为单个条目提取。
+如果一个对象在一个补丁中有多个变更(例如,既被削弱攻击力又增强防御力),
+为每个变更创建单独的条目以保留完整的变更历史。
+
+仅提取文本中明确提及的信息。
+全面捕捉所有修改,无论多么细微。
+
+### 源文本:
+"""
+
+
+# ==============================================================================
+# 模板类
+# ==============================================================================
+
+class PatchNoteChangelog(AutoList[PatchChangeSchema]):
+ """适用于:官方补丁说明、版本变更日志、平衡更新
+
+ 从补丁文档中提取游戏修改的详细变更日志。
+
+ 与进行去重的 AutoSet 不同,该模板保留每个单独的变更作为单个条目。
+ 这对于以下方面至关重要:
+ - 追踪每个对象的完整平衡历史
+ - 分析同一补丁中对同一对象的多个变更
+ - 审查游戏设计决定的演变
+ - 构建全面的补丁数据库而不丢失数据
+
+ 示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> from hyperextract.templates.zh.game import PatchNoteChangelog
+ >>>
+ >>> llm = ChatOpenAI(model="gpt-4", temperature=0)
+ >>> embedder = OpenAIEmbeddings()
+ >>>
+ >>> changelog = PatchNoteChangelog(
+ ... llm_client=llm,
+ ... embedder=embedder
+ ... )
+ >>>
+ >>> # 输入补丁说明
+ >>> changelog.feed_text('''
+ ... 补丁 2.3.0 - 平衡更新
+ ... 亚索:攻击力从50增加到55(增强后期伤害)
+ ... 亚索:风之障壁冷却时间从25秒降低到20秒(生活质量改进)
+ ... 无尽之刃:攻击力加成从80增加到85
+ ... ''')
+ >>>
+ >>> # 每个变更都作为单独条目保留,不合并
+ >>> # 即使亚索有2个变更,总共得到3条条目
+ >>> changelog.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ """初始化版本更新日志模板。
+
+ 参数:
+ llm_client:语言模型客户端,用于变更提取(如 ChatOpenAI)
+ embedder:嵌入模型,用于语义索引(如 OpenAIEmbeddings)
+ chunk_size:单个文本块的最大字符数(默认2048)
+ chunk_overlap:相邻块之间的重叠字符数(默认256)
+ **kwargs:传递给 AutoList 父类的其他参数
+ """
+ super().__init__(
+ item_schema=PatchChangeSchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 3,
+ top_k_for_chat: int = 3,
+ ) -> None:
+ """展示补丁变更日志为交互式数据库。
+
+ 参数:
+ top_k_for_search:语义搜索返回的前 K 个结果数
+ top_k_for_chat:对话上下文中显示的前 K 个结果数
+ """
+
+ def change_label_extractor(item: PatchChangeSchema) -> str:
+ """提取展示标签:对象名称带变更类型"""
+ return f"{item.entity_name} ({item.change_type})"
+
+ super().show(
+ item_label_extractor=change_label_extractor,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/zh/history/__init__.py b/hyperextract/templates/zh/history/__init__.py
index e69de29..44bea21 100644
--- a/hyperextract/templates/zh/history/__init__.py
+++ b/hyperextract/templates/zh/history/__init__.py
@@ -0,0 +1,11 @@
+"""History domain templates for knowledge extraction."""
+
+from .cultural_artifact_registry import CulturalArtifactRegistry
+from .war_timeline_graph import WarTimelineGraph
+from .diplomatic_event_hypergraph import DiplomaticEventHypergraph
+
+__all__ = [
+ "CulturalArtifactRegistry",
+ "WarTimelineGraph",
+ "DiplomaticEventHypergraph",
+]
diff --git a/hyperextract/templates/zh/history/cultural_artifact_registry.py b/hyperextract/templates/zh/history/cultural_artifact_registry.py
new file mode 100644
index 0000000..cfade04
--- /dev/null
+++ b/hyperextract/templates/zh/history/cultural_artifact_registry.py
@@ -0,0 +1,71 @@
+"""考古文物档案 - 从历史文献中提取文物信息。
+
+通过合并博物馆目录、考古报告和文物描述中的数据来构建统一的文物知识库。
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoSet
+
+class ArtifactSchema(BaseModel):
+ artifact_name: str = Field(..., description="文物的官方名称")
+ material: Optional[str] = Field(None, description="主要材料成分")
+ excavation_year: Optional[str] = Field(None, description="发现年份")
+ excavation_location: Optional[str] = Field(None, description="出土地点")
+ current_museum: Optional[str] = Field(None, description="当前收藏地/博物馆")
+ dimensions: Optional[str] = Field(None, description="尺寸和重量规格")
+ symbolic_meaning: Optional[str] = Field(None, description="文化或宗教意义")
+ historical_period: Optional[str] = Field(None, description="历史时期/朝代")
+
+_PROMPT = """你是一位专业的考古学家和博物馆策展人。
+从文本中提取全面的文物信息:
+1. artifact_name:文物官方名称
+2. material:材料成分
+3. excavation_year:发现年份
+4. excavation_location:出土地点
+5. current_museum:当前位置/博物馆
+6. dimensions:物理尺寸
+7. symbolic_meaning:文化意义
+8. historical_period:历史时期/朝代
+
+仅提取文本中明确提及的信息。
+
+### 源文本:
+"""
+
+class CulturalArtifactRegistry(AutoSet[ArtifactSchema]):
+ """适用于:博物馆目录、考古报告、文物文档
+
+ 通过自动合并来自多个历史来源的信息来提取全面的文物百科。
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ super().__init__(
+ item_schema=ArtifactSchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ key_extractor=lambda x: x.artifact_name.strip().lower(),
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(self, *, top_k_for_search: int = 3, top_k_for_chat: int = 3) -> None:
+ def label_extractor(item: ArtifactSchema) -> str:
+ period = f" ({item.historical_period})" if item.historical_period else ""
+ return f"{item.artifact_name}{period}"
+ super().show(
+ item_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/history/diplomatic_event_hypergraph.py b/hyperextract/templates/zh/history/diplomatic_event_hypergraph.py
new file mode 100644
index 0000000..29ca583
--- /dev/null
+++ b/hyperextract/templates/zh/history/diplomatic_event_hypergraph.py
@@ -0,0 +1,79 @@
+"""外交事件与条约 - 提取多方历史事件。
+
+模型化多个国家同时参与的复杂外交事件,如条约和国际会议。
+"""
+
+from typing import Any, Optional, Tuple, 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 CountrySchema(BaseModel):
+ entity_id: str = Field(..., description="唯一标识符")
+ country_name: str = Field(..., description="国家/民族名称")
+
+class DiplomaticEventSchema(BaseModel):
+ hyperedge_id: str = Field(..., description="唯一标识符")
+ event_type: str = Field(..., description="'条约'、'会议'、'联盟'等")
+ event_name: str = Field(..., description="事件名称,如'凡尔赛条约'")
+ signing_date: Optional[str] = Field(None, description="事件日期")
+ member_countries: List[str] = Field(default_factory=list, description="所有参与国")
+ key_terms: Optional[str] = Field(None, description="关键条款摘要")
+ leading_country: Optional[str] = Field(None, description="主导或发起国")
+
+_PROMPT = """从文本中提取节点(国家)和超边(外交事件)。
+超边连接参与单一事件的多个国家。
+
+### 源文本:
+"""
+
+_NODE_PROMPT = """提取文本中提到的所有国家/民族名称。"""
+
+_EDGE_PROMPT = """提取涉及多个国家的外交事件。为每个事件在member_countries字段列出所有参与国。"""
+
+class DiplomaticEventHypergraph(AutoHypergraph[CountrySchema, DiplomaticEventSchema]):
+ """适用于:条约、国际会议记录、外交史
+
+ 提取进行多方外交事件为同时连接多个国家的超边。非常适合建模复杂的国际协议。
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ extraction_mode: str = "two_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ super().__init__(
+ node_schema=CountrySchema,
+ edge_schema=DiplomaticEventSchema,
+ node_key_extractor=lambda x: x.country_name.strip().lower(),
+ edge_key_extractor=lambda x: f"{x.event_name.lower()}",
+ nodes_in_edge_extractor=lambda x: tuple(
+ c.strip().lower() for c in x.member_countries
+ ),
+ llm_client=llm_client,
+ embedder=embedder,
+ extraction_mode=extraction_mode,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(self, *, top_k_for_search: int = 5, top_k_for_chat: int = 5) -> None:
+ def node_label(node: CountrySchema) -> str:
+ return f"🏛️ {node.country_name}"
+ def edge_label(edge: DiplomaticEventSchema) -> str:
+ return f"{edge.event_type}:{edge.event_name}"
+ super().show(
+ node_label_extractor=node_label,
+ edge_label_extractor=edge_label,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/zh/history/war_timeline_graph.py b/hyperextract/templates/zh/history/war_timeline_graph.py
new file mode 100644
index 0000000..d49f504
--- /dev/null
+++ b/hyperextract/templates/zh/history/war_timeline_graph.py
@@ -0,0 +1,82 @@
+"""战争演变史 - 从历史文献中提取时间相关的战争关系。
+
+捕捉领土控制、权力交接和军事事件的时间范围,用于精确的历史分析。
+"""
+
+from typing import Any, Optional, Tuple
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoTemporalGraph
+
+class HistoricalEntitySchema(BaseModel):
+ entity_id: str = Field(..., description="唯一标识符")
+ entity_type: str = Field(..., description="'政权'、'城市'或'将领'")
+ entity_name: str = Field(..., description="实体名称")
+
+class TemporalEventSchema(BaseModel):
+ source_entity: str = Field(..., description="行为实体")
+ target_entity: str = Field(..., description="受影响实体")
+ edge_type: str = Field(..., description="'占领'、'统治'、'围攻'等")
+ start_timestamp: Optional[int] = Field(None, description="起始年份")
+ end_timestamp: Optional[int] = Field(None, description="结束年份")
+ description: Optional[str] = Field(None, description="事件详情")
+
+_PROMPT = """提取历史实体(节点)和时间事件(边),显示领土控制和权力交接。
+确保所有边连接提取的节点列表中存在的实体。
+
+### 源文本:
+"""
+
+_NODE_PROMPT = """提取所有提到的历史实体:政权、城市、军事领导人及其描述。"""
+
+_EDGE_PROMPT = """提取已知实体之间的时间关系。为每个关系提供确切的年份范围。"""
+
+class WarTimelineGraph(AutoTemporalGraph[HistoricalEntitySchema, TemporalEventSchema]):
+ """适用于:历史编年史、战争记录、教科书章节
+
+ 提取时间知识图,捕捉领土控制和军事事件的精确时间范围。
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ observation_time: str = "2024-01-01",
+ extraction_mode: str = "two_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ super().__init__(
+ node_schema=HistoricalEntitySchema,
+ edge_schema=TemporalEventSchema,
+ node_key_extractor=lambda x: x.entity_name.strip().lower(),
+ edge_key_extractor=lambda x: (
+ f"{x.source_entity.lower()}|{x.edge_type.lower()}|{x.target_entity.lower()}"
+ ),
+ time_in_edge_extractor=lambda x: f"{x.start_timestamp or ''}",
+ nodes_in_edge_extractor=lambda x: (x.source_entity.lower(), x.target_entity.lower()),
+ llm_client=llm_client,
+ embedder=embedder,
+ observation_time=observation_time,
+ extraction_mode=extraction_mode,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(self, *, top_k_for_search: int = 5, top_k_for_chat: int = 5) -> None:
+ def node_label(node: HistoricalEntitySchema) -> str:
+ return f"{node.entity_name} ({node.entity_type})"
+ def edge_label(edge: TemporalEventSchema) -> str:
+ return f"{edge.edge_type} ({edge.start_timestamp or '?'})"
+ super().show(
+ node_label_extractor=node_label,
+ edge_label_extractor=edge_label,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/zh/legal/__init__.py b/hyperextract/templates/zh/legal/__init__.py
index e69de29..6fcca93 100644
--- a/hyperextract/templates/zh/legal/__init__.py
+++ b/hyperextract/templates/zh/legal/__init__.py
@@ -0,0 +1,11 @@
+"""Legal domain templates for knowledge extraction."""
+
+from .contract_obligation_checklist import ContractObligationChecklist
+from .corporate_equity_graph import CorporateEquityGraph
+from .case_precedent_library import CasePrecedentLibrary
+
+__all__ = [
+ "ContractObligationChecklist",
+ "CorporateEquityGraph",
+ "CasePrecedentLibrary",
+]
diff --git a/hyperextract/templates/zh/legal/case_precedent_library.py b/hyperextract/templates/zh/legal/case_precedent_library.py
new file mode 100644
index 0000000..6e2c4e2
--- /dev/null
+++ b/hyperextract/templates/zh/legal/case_precedent_library.py
@@ -0,0 +1,70 @@
+"""判例法要旨库 - 提取和索引法律判例。
+
+通过自动合并来自多个来源关于同一案件的信息来构建可搜索的法律判例数据库。
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoSet
+
+class PrecedentSchema(BaseModel):
+ case_citation: str = Field(..., description="官方案号/引用")
+ court_name: Optional[str] = Field(None, description="做出决定的法院")
+ judgment_year: Optional[str] = Field(None, description="判决年份")
+ legal_issues: Optional[str] = Field(None, description="提出的法律问题")
+ holding: Optional[str] = Field(None, description="法院的判决和法律原则")
+ cited_statutes: Optional[str] = Field(None, description="判决中引用的法律")
+ presiding_judges: Optional[str] = Field(None, description="做出决定的法官")
+ impact_assessment: Optional[str] = Field(None, description="对后续法律的影响")
+
+_PROMPT = """你是一位法律研究专家。
+提取判例案件信息:
+1. case_citation:官方案名/案号
+2. court_name:审理的法院
+3. judgment_year:判决年份
+4. legal_issues:法律问题
+5. holding:法院的判决和原则
+6. cited_statutes:适用法律
+7. presiding_judges:做出裁定的法官
+8. impact_assessment:对未来案件的影响
+
+### 源文本:
+"""
+
+class CasePrecedentLibrary(AutoSet[PrecedentSchema]):
+ """适用于:法院判决、法律数据库、案例法报告
+
+ 通过自动合并来自多个来源的案件信息来提取和索引法律判例,
+ 成为统一的可搜索库。
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ super().__init__(
+ item_schema=PrecedentSchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ key_extractor=lambda x: x.case_citation.strip().lower(),
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(self, *, top_k_for_search: int = 3, top_k_for_chat: int = 3) -> None:
+ def label_extractor(item: PrecedentSchema) -> str:
+ year = f" ({item.judgment_year})" if item.judgment_year else ""
+ return f"{item.case_citation}{year}"
+ super().show(
+ item_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/legal/contract_obligation_checklist.py b/hyperextract/templates/zh/legal/contract_obligation_checklist.py
new file mode 100644
index 0000000..2268aad
--- /dev/null
+++ b/hyperextract/templates/zh/legal/contract_obligation_checklist.py
@@ -0,0 +1,65 @@
+"""法定义务审查 - 从合同中提取义务和禁止条款。
+
+通过提取所有义务、责任和限制而无去重来构建全面的合规清单,保留完整的审计记录。
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoList
+
+class ObligationSchema(BaseModel):
+ obligated_party: str = Field(..., description="负责履行的当事人")
+ obligation_type: str = Field(..., description="'必须'(要求)或'不得'(禁止)")
+ action_description: str = Field(..., description="具体行动或要求")
+ trigger_condition: Optional[str] = Field(None, description="何时/何种情况下义务适用")
+ breach_penalty: Optional[str] = Field(None, description="不履行的后果")
+ clause_reference: Optional[str] = Field(None, description="原合同条款号")
+
+_PROMPT = """你是一位合同律师和合规审计员。
+从合同中提取所有义务和限制:
+1. obligated_party:谁必须履行
+2. obligation_type:必须(要求)或不得(禁止)
+3. action_description:具体行动/要求
+4. trigger_condition:义务何时适用
+5. breach_penalty:不合规罚款
+6. clause_reference:合同条款号
+
+独立提取每个义务。无合并。
+
+### 源文本:
+"""
+
+class ContractObligationChecklist(AutoList[ObligationSchema]):
+ """适用于:合同、服务条款、协议、合规文件
+
+ 提取完整的合规清单,保留每个义务单独存在,用于全面的审计和风险分析。
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ super().__init__(
+ item_schema=ObligationSchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(self, *, top_k_for_search: int = 3, top_k_for_chat: int = 3) -> None:
+ def label_extractor(item: ObligationSchema) -> str:
+ return f"{item.obligation_type}:{item.action_description[:50]}"
+ super().show(
+ item_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/legal/corporate_equity_graph.py b/hyperextract/templates/zh/legal/corporate_equity_graph.py
new file mode 100644
index 0000000..7c51b69
--- /dev/null
+++ b/hyperextract/templates/zh/legal/corporate_equity_graph.py
@@ -0,0 +1,78 @@
+"""股权结构穿透 - 提取所有权和控制关系。
+
+构建股权图显示投资关系、控制结构和通过企业金字塔的最终实益所有权。
+"""
+
+from typing import Any, Optional
+from pydantic import BaseModel, Field
+from langchain_core.language_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoGraph
+
+class EntitySchema(BaseModel):
+ entity_id: str = Field(..., description="唯一标识符")
+ entity_type: str = Field(..., description="'公司'、'个人'或'基金'")
+ entity_name: str = Field(..., description="法人名称")
+ registration_number: Optional[str] = Field(None, description="登记号或身份证号")
+
+class EquityRelationshipSchema(BaseModel):
+ source_entity: str = Field(..., description="股东/所有者名称")
+ target_entity: str = Field(..., description="公司/实体名称")
+ relationship_type: str = Field(..., description="'持股'、'控制'、'任职为'")
+ stake_percentage: Optional[str] = Field(None, description="所有权百分比")
+ context: Optional[str] = Field(None, description="附加背景信息")
+
+_PROMPT = """提取企业实体及其所有权/控制关系。"""
+
+_NODE_PROMPT = """提取所有实体:公司、个人、基金。"""
+
+_EDGE_PROMPT = """提取实体之间的所有权和控制关系。仅连接已知实体列表中的实体。"""
+
+class CorporateEquityGraph(AutoGraph[EntitySchema, EquityRelationshipSchema]):
+ """适用于:尽职调查报告、招股说明书、企业备案
+
+ 通过多级股权链提取企业所有权结构和最终实益所有权。
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ extraction_mode: str = "two_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ **kwargs: Any,
+ ):
+ super().__init__(
+ node_schema=EntitySchema,
+ edge_schema=EquityRelationshipSchema,
+ node_key_extractor=lambda x: x.entity_name.strip().lower(),
+ edge_key_extractor=lambda x: (
+ f"{x.source_entity.lower()}|{x.relationship_type.lower()}|{x.target_entity.lower()}"
+ ),
+ nodes_in_edge_extractor=lambda x: (x.source_entity.lower(), x.target_entity.lower()),
+ llm_client=llm_client,
+ embedder=embedder,
+ extraction_mode=extraction_mode,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ **kwargs,
+ )
+
+ def show(self, *, top_k_for_search: int = 5, top_k_for_chat: int = 5) -> None:
+ def node_label(node: EntitySchema) -> str:
+ type_icon = {"公司": "🏢", "个人": "👤", "基金": "💼"}
+ icon = type_icon.get(node.entity_type, "●")
+ return f"{icon} {node.entity_name}"
+ def edge_label(edge: EquityRelationshipSchema) -> str:
+ pct = f" ({edge.stake_percentage})" if edge.stake_percentage else ""
+ return f"{edge.relationship_type}{pct}"
+ super().show(
+ node_label_extractor=node_label,
+ edge_label_extractor=edge_label,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/zh/literature/__init__.py b/hyperextract/templates/zh/literature/__init__.py
index e69de29..15ac04d 100644
--- a/hyperextract/templates/zh/literature/__init__.py
+++ b/hyperextract/templates/zh/literature/__init__.py
@@ -0,0 +1,9 @@
+from .character_relationship_graph import CharacterRelationshipGraph
+from .narrative_timeline import NarrativeTimeline
+from .symbolism_set import SymbolismSet
+
+__all__ = [
+ "CharacterRelationshipGraph",
+ "NarrativeTimeline",
+ "SymbolismSet",
+]
diff --git a/hyperextract/templates/zh/literature/character_relationship_graph.py b/hyperextract/templates/zh/literature/character_relationship_graph.py
new file mode 100644
index 0000000..bc286c8
--- /dev/null
+++ b/hyperextract/templates/zh/literature/character_relationship_graph.py
@@ -0,0 +1,141 @@
+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 Character(BaseModel):
+ """文学作品中的人物实体。"""
+ name: str = Field(description="人物的正式姓名或最常用称呼。")
+ aliases: List[str] = Field(default_factory=list, description="人物的其他称呼、头衔或绰号。")
+ traits: List[str] = Field(default_factory=list, description="人物的核心性格、能力或生理特征。")
+ description: Optional[str] = Field(description="关于人物在作品中地位及核心情节的简要描述。")
+
+class Relationship(BaseModel):
+ """人物之间的互动与联系。"""
+ source: str = Field(description="发起关系的或关系的第一个人物名称。")
+ target: str = Field(description="关系指向的或关系的第二个人物名称。")
+ relation_type: str = Field(description="关系的性质(如:亲属、爱慕、仇恨、师徒、盟友)。")
+ sentiment: str = Field(description="关系的情感倾向(如:正面、负面、中立、复杂)。")
+ evidence: str = Field(description="支持该关系的文本证据或关键情节简述。")
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一位资深的文学评论家和角色分析专家。你的任务是从文学文本中提取人物及其关系网络。\n\n"
+ "提取指南:\n"
+ "1. **人物识别**:准确识别文本中出现的所有重要人物。记录他们的姓名、绰号及核心特征。\n"
+ "2. **关系识别**:分析人物间的对话、行为互动及旁白,提取他们之间的深层联系。不仅仅限于亲属关系,也要捕捉情感纽带和利益冲突。\n"
+ "3. **证据至上**:为每个关系提供简短的文本依据。\n"
+ "- 确保边连接的两个人物都已在节点列表中列出。"
+)
+
+_NODE_PROMPT = (
+ "作为文学分析专家,请从文本中提取所有关键人物。记录其姓名、所有已知的别称、核心性格标签以及简要的生平或地位描述。"
+)
+
+_EDGE_PROMPT = (
+ "基于已提取的人物列表,识别他们之间的社交与情感关系。请说明关系的类型(如‘宿敌’)、情感色彩(如‘强烈恨意’)并提供证据。"
+)
+
+# ==============================================================================
+# 3. 模板类 (Template Class)
+# ==============================================================================
+
+class CharacterRelationshipGraph(AutoGraph[Character, Relationship]):
+ """
+ 适用于:[小说, 剧本, 传记, 戏剧]
+
+ 用于提取文学作品中复杂人物关系的图谱模板。
+
+ 该模板旨在捕捉人物间的动态互动、情感倾向和结构化联系,支持多阶段提取以确保深度关系的准确性。
+
+ 示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> # 初始化模板
+ >>> characters = CharacterRelationshipGraph(llm_client=llm, embedder=embedder)
+ >>> # 输入文本块
+ >>> text = "贾宝玉是贾政之子,与林黛玉青梅竹马,彼此情深意切。"
+ >>> characters.feed_text(text)
+ >>> characters.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
+ ):
+ """
+ 初始化 CharacterRelationshipGraph 模板。
+
+ Args:
+ llm_client: 用于提取的语言模型客户端。
+ embedder: 用于实体去重和索引的嵌入模型。
+ extraction_mode: 提取模式,支持 "one_stage" 和 "two_stage"。
+ chunk_size: 文本块大小。
+ chunk_overlap: 文本块重叠大小。
+ max_workers: 最大并行工作线程数。
+ verbose: 是否开启详细日志。
+ **kwargs: 其他传给 AutoGraph 的参数。
+ """
+ super().__init__(
+ node_schema=Character,
+ edge_schema=Relationship,
+ 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,
+ 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: Character) -> str:
+ return node.name
+
+ def edge_label_extractor(edge: Relationship) -> str:
+ return f"{edge.relation_type} ({edge.sentiment})"
+
+ 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/literature/narrative_timeline.py b/hyperextract/templates/zh/literature/narrative_timeline.py
new file mode 100644
index 0000000..9870c09
--- /dev/null
+++ b/hyperextract/templates/zh/literature/narrative_timeline.py
@@ -0,0 +1,144 @@
+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 NarrativePoint(BaseModel):
+ """叙事流中的核心情节节点。"""
+ name: str = Field(description="情节或事件的短标题(如‘鸿门宴’、‘初遇’)。")
+ location: Optional[str] = Field(description="事件发生的地点。")
+ characters_involved: List[str] = Field(default_factory=list, description="参与该事件的人物名单。")
+ description: str = Field(description="对情节内容的具体描述,包括核心动作和转折。")
+
+class TimeTransition(BaseModel):
+ """情节节点之间的时间演变与逻辑关联。"""
+ source: str = Field(description="起始情节名称。")
+ target: str = Field(description="后续情节名称。")
+ time: str = Field(description="事实发生的时间。你必须结合上下文和观察日期,将相对时间(如‘三天后’、‘次日’)解析并转换为绝对日期(如‘2024-01-15’)或具体年份。")
+ logic: str = Field(description="事件间的逻辑关系(如:因果、递进、意外转折)。")
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一位资深的叙事学家。你的任务是从文本中还原情节发展的时空蓝图。\n\n"
+ "提取要求:\n"
+ "1. **情节识别**:提取具有独立叙事意义的节点,记录其发生的地点及参与者。\n"
+ "2. **时间轴构建**:在情节间建立带时间属性的连线。特别注意文本中的时间指示词(如‘过了半晌’、‘数月无话’)。\n"
+ "3. **逻辑链条**:除了时间先后,还要识别事件间的因果驱动力。\n"
+ "注意:时间必须提取在边(Transition)上,不要作为独立的节点。"
+)
+
+_NODE_PROMPT = (
+ "请识别并提取文本中所有的关键情节节点(Plot Points)。为每个节点命名,并提供地点描述及涉及的人物。"
+)
+
+_EDGE_PROMPT = (
+ "在给定的情节节点之间建立联系。请精确提取文本中提及的时间线索,并描述这些事件是如何在叙事逻辑上相互连接的。"
+)
+
+# ==============================================================================
+# 3. 模板类 (Template Class)
+# ==============================================================================
+
+class NarrativeTimeline(AutoTemporalGraph[NarrativePoint, TimeTransition]):
+ """
+ 适用于:[编年史, 史诗文学, 侦探小说, 史书]
+
+ 用于还原文学或历史叙述中情节演变的时间线图谱模板。
+
+ 该模板利用 AutoTemporalGraph 的时序特性,将时间信息嵌入关系中,专注于呈现“起因-经过-结果”的动态过程。
+
+ 示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> # 初始化模板
+ >>> timeline = NarrativeTimeline(llm_client=llm, embedder=embedder)
+ >>> # 输入包含时间跨度的文本
+ >>> text = "隆中对之后,刘备三顾茅庐请出诸葛亮。数年后,曹操南下,引发了赤壁之战。"
+ >>> timeline.feed_text(text)
+ >>> timeline.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
+ ):
+ """
+ 初始化 NarrativeTimeline 模板。
+
+ Args:
+ llm_client: 用于提取的语言模型客户端。
+ embedder: 用于实体去重和索引的嵌入模型。
+ observation_time: 设定的基准参考日期,用于解析相对时间(如‘今天’)。
+ extraction_mode: 默认使用 two_stage 以保证时间解析的精准度。
+ chunk_size: 文本块大小。
+ chunk_overlap: 文本块重叠大小。
+ max_workers: 最大并行工作线程数。
+ verbose: 是否开启详细日志。
+ **kwargs: 其他传给 AutoTemporalGraph 的参数。
+ """
+ super().__init__(
+ node_schema=NarrativePoint,
+ edge_schema=TimeTransition,
+ node_key_extractor=lambda x: x.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: NarrativePoint) -> str:
+ return node.name
+
+ def edge_label_extractor(edge: TimeTransition) -> str:
+ return f"[{edge.time}] {edge.logic}"
+
+ 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/literature/symbolism_set.py b/hyperextract/templates/zh/literature/symbolism_set.py
new file mode 100644
index 0000000..cebe18c
--- /dev/null
+++ b/hyperextract/templates/zh/literature/symbolism_set.py
@@ -0,0 +1,110 @@
+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 ImagerySymbol(BaseModel):
+ """文学作品中的意象或符号。"""
+ symbol_name: str = Field(description="意象的名称(如‘月亮’、‘荒原’、‘白鲸’)。")
+ literal_meanings: List[str] = Field(description="该意象在文中的字面指代或描述。")
+ metaphorical_meanings: List[str] = Field(description="该意象隐含的象征意义或深层隐喻。")
+ contexts: List[str] = Field(description="提取该意象的关键原文片段或章节摘要。")
+ thematic_connection: Optional[str] = Field(description="该意象与作品主题(如‘孤独’、‘命运’)的关联。")
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一位资深的文学批评家。你的任务是从文本中识别并分析反复出现的关键意象与符号。\n\n"
+ "分析指南:\n"
+ "1. **意象标准化**:请确保同一个意象(如‘月色’与‘月亮’)被归类到同一个标准的意象名称下,以便信息累加。\n"
+ "2. **分层解读**:区分意象的字面描写(它是什么)与其象征意义(它代表了什么)。\n"
+ "3. **信息聚合**:如果你在多处文本中发现了同一个意象,请持续丰富该意象的内涵、上下文和它对主题的贡献。\n"
+)
+
+# ==============================================================================
+# 3. 模板类 (Template Class)
+# ==============================================================================
+
+class SymbolismSet(AutoSet[ImagerySymbol]):
+ """
+ 适用于:[诗歌, 现代主义小说, 文学评论, 散文]
+
+ 用于从文学作品中聚合与深度分析意象隐喻的集合模板。
+
+ 该模板利用 AutoSet 的键值累加特性,能够将散落在全书各处的关于同一个符号的信息(字面描写、深层隐喻、主题关联)自动合并为一个富集的词条。
+
+ 示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> # 初始化模板
+ >>> symbolism = SymbolismSet(llm_client=llm, embedder=embedder)
+ >>> # 多次喂入不同章节的文本
+ >>> symbolism.feed_text("海明威笔下的大海是永恒的荒原,象征着不可战胜的自然。").feed_text("在大海深处,老人与马林鱼的搏斗体现了尊严。")
+ >>> symbolism.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
+ ):
+ """
+ 初始化 SymbolismSet 模板。
+
+ Args:
+ llm_client: 用于提取的语言模型客户端。
+ embedder: 用于语义检索和可视化的嵌入模型。
+ chunk_size: 文本块大小。
+ chunk_overlap: 文本块重叠大小。
+ max_workers: 最大并行工作线程数。
+ verbose: 是否开启详细日志。
+ **kwargs: 其他传给 AutoSet 的参数。
+ """
+ super().__init__(
+ item_schema=ImagerySymbol,
+ key_extractor=lambda x: x.symbol_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: ImagerySymbol) -> str:
+ return item.symbol_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/__init__.py b/hyperextract/templates/zh/medicine/__init__.py
index e69de29..423c4b3 100644
--- a/hyperextract/templates/zh/medicine/__init__.py
+++ b/hyperextract/templates/zh/medicine/__init__.py
@@ -0,0 +1,9 @@
+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/zh/medicine/clinical_treatment_timeline.py b/hyperextract/templates/zh/medicine/clinical_treatment_timeline.py
new file mode 100644
index 0000000..0e9bb5a
--- /dev/null
+++ b/hyperextract/templates/zh/medicine/clinical_treatment_timeline.py
@@ -0,0 +1,142 @@
+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/diagnostic_criteria_set.py b/hyperextract/templates/zh/medicine/diagnostic_criteria_set.py
new file mode 100644
index 0000000..76e363b
--- /dev/null
+++ b/hyperextract/templates/zh/medicine/diagnostic_criteria_set.py
@@ -0,0 +1,111 @@
+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/drug_interaction_graph.py b/hyperextract/templates/zh/medicine/drug_interaction_graph.py
new file mode 100644
index 0000000..6c1b865
--- /dev/null
+++ b/hyperextract/templates/zh/medicine/drug_interaction_graph.py
@@ -0,0 +1,141 @@
+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/movie/character_arc_tracker.py b/hyperextract/templates/zh/movie/character_arc_tracker.py
new file mode 100644
index 0000000..71d1302
--- /dev/null
+++ b/hyperextract/templates/zh/movie/character_arc_tracker.py
@@ -0,0 +1,86 @@
+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 定义
+# ==============================================================================
+
+class CharacterState(BaseModel):
+ """电影人物在特定时刻的状态节点。"""
+ character_name: str = Field(description="人物名称。")
+ psychological_state: str = Field(description="人物此时的心理状态或核心情绪。")
+ current_goal: str = Field(description="人物此时的核心目标。")
+ situation: str = Field(description="人物所处的外部处境或冲突。")
+
+class CharacterDevelopment(BaseModel):
+ """人物状态的演变与弧光转变。"""
+ source: str = Field(description="起始状态。")
+ target: str = Field(description="转变后的状态。")
+ time: str = Field(description="发生转变的时间点或剧情阶段(如‘第二幕’、‘决战前夕’)。")
+ trigger_event: str = Field(description="导致这一状态转变的关键剧情事件。")
+ arc_direction: str = Field(description="弧光方向(如:成长、堕落、觉醒、发现)。")
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一位资深的剧本分析师和角色研究专家。你的任务是从剧本或长篇影评中追踪角色的‘人物弧光’。\n\n"
+ "提取要求:\n"
+ "1. **状态切片**:提取人物在故事不同阶段的心理、目标和处境节点。\n"
+ "2. **转变触发**:识别导致人物在两个状态之间发生转变的关键驱动事件。\n"
+ "3. **时间线解析**:明确转变发生的时间节点(如剧本页码、幕数或相对时间)。\n"
+)
+
+_NODE_PROMPT = "请识别并提取角色在剧本关键节点的内部与外部状态。记录其情绪、当下的目标以及面临的主要处境。"
+_EDGE_PROMPT = "分析角色状态之间的演变。请指出是什么剧情事件触发了角色的心路历程转变,并归纳其弧光的发展方向。"
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+class CharacterArcTracker(AutoTemporalGraph[CharacterState, CharacterDevelopment]):
+ """
+ 适用于:[角色传记, 戏剧脚本, 文学改编, 影评]
+
+ 用于分析电影角色成长路径与心理弧光的时序图谱模板。
+
+ 该模板专注于呈现“为什么变”和“怎么变”,适合深度角色研究与戏剧冲突分析。
+
+ 示例:
+ >>> arc = CharacterArcTracker(llm_client=llm, embedder=embedder)
+ >>> text = "故事开始时,杰克是个胆怯的职员。在经历那场爆炸后,他意识到生命的可贵,在决战中展现了惊人的勇气。"
+ >>> arc.feed_text(text).show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "two_stage",
+ **kwargs: Any
+ ):
+ super().__init__(
+ node_schema=CharacterState,
+ edge_schema=CharacterDevelopment,
+ node_key_extractor=lambda x: f"{x.character_name}-{x.psychological_state[:10]}",
+ 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,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ extraction_mode=extraction_mode,
+ **kwargs
+ )
+
+ def show(self, **kwargs):
+ def n_label(node: CharacterState) -> str: return f"{node.character_name}: {node.psychological_state}"
+ def e_label(edge: CharacterDevelopment) -> str: return f"[{edge.time}] {edge.arc_direction}"
+ super().show(node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs)
diff --git a/hyperextract/templates/zh/movie/cinematic_trivia_set.py b/hyperextract/templates/zh/movie/cinematic_trivia_set.py
new file mode 100644
index 0000000..0ac707c
--- /dev/null
+++ b/hyperextract/templates/zh/movie/cinematic_trivia_set.py
@@ -0,0 +1,69 @@
+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 CinematicTrivia(BaseModel):
+ """电影要素、彩蛋、制作花絮或特殊叙事元素。"""
+ topic: str = Field(description="电影要素或彩蛋的主题名称(如‘致敬《2001太空漫游》’、‘打破第四面墙’)。")
+ description: str = Field(description="该要素的具体表现或花絮内容详情。")
+ timestamp: Optional[str] = Field(description="元素在电影中出现的具体时间点(如 '01:23:45')。")
+ significance: List[str] = Field(description="该元素的艺术意义、叙事功能或对影迷的特殊含义。")
+ source: List[str] = Field(description="该知识点的来源(如评论音轨、特定网站、IMDb)。")
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一位资深的影评人和电影百科专家。你的任务是从影评、制作手册和花絮文本中提取结构化的电影百科知识点。\n\n"
+ "分析指南:\n"
+ "1. **主题去重**:将关于同一个知识点(如‘斯坦·李客串’)的多个片段合并。LLM 应确保名称标准化。\n"
+ "2. **深度挖掘**:不仅提取是什么,还要提取这一设计背后的艺术意图(significance)。\n"
+ "3. **信息累加**:通过多次读取文本,不断丰富同一个主题下的描述、时间点和来源记录。\n"
+)
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+class CinematicTriviaSet(AutoSet[CinematicTrivia]):
+ """
+ 适用于:[制作笔记, 评论音轨, 幕后花絮, 影迷趣闻, 长篇影评]
+
+ 用于构建和聚合电影百科知识、场景彩蛋与艺术表现元素的集合模板。
+
+ 该模板利用 AutoSet 的富集特性,能够跨文档聚合零散的影迷百科知识。
+
+ 示例:
+ >>> trivia = CinematicTriviaSet(llm_client=llm, embedder=embedder)
+ >>> trivia.feed_text("导演在86分钟处设置了一个致敬库布里克的隐藏镜头。").feed_text("那个红色的椅子其实是致敬《闪灵》。")
+ >>> trivia.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ chunk_size: int = 2048,
+ **kwargs: Any
+ ):
+ super().__init__(
+ item_schema=CinematicTrivia,
+ key_extractor=lambda x: x.topic.strip().lower(),
+ llm_client=llm_client,
+ embedder=embedder,
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ **kwargs
+ )
+
+ def show(self, **kwargs):
+ def label(item: CinematicTrivia) -> str: return item.topic
+ super().show(item_label_extractor=label, **kwargs)
diff --git a/hyperextract/templates/zh/movie/script_scene_graph.py b/hyperextract/templates/zh/movie/script_scene_graph.py
new file mode 100644
index 0000000..a639693
--- /dev/null
+++ b/hyperextract/templates/zh/movie/script_scene_graph.py
@@ -0,0 +1,90 @@
+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 定义
+# ==============================================================================
+
+class Scene(BaseModel):
+ """电影剧本中的场景节点。"""
+ title: str = Field(description="场景标题(如 'INT. COFFEE SHOP - DAY')。")
+ location: str = Field(description="场景发生的具体地点。")
+ time_of_day: str = Field(description="场景发生的时间段(如 DAY, NIGHT, DUSK)。")
+ description: str = Field(description="场景的简要动作描述或核心事件。")
+
+class SceneTransition(BaseModel):
+ """场景间的转场与逻辑演变。"""
+ source: str = Field(description="起始场景标题。")
+ target: str = Field(description="目标场景标题。")
+ time: str = Field(description="场景间逝去的时间描述。你必须将其解析为绝对的持续时间或精确的时间偏移。")
+ transition_type: str = Field(description="转场方式(如 CUT TO, FADE IN, CROSSFADE)。")
+ logic: str = Field(description="场景间的叙事关联(如 动作延续、时间跳跃、平行剪辑)。")
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一位资深的电影编剧和导演。你的任务是从剧本或分镜脚本中提取场景流及其叙事逻辑。\n\n"
+ "提取要求:\n"
+ "1. **场景识别**:提取所有独立的场景节点,完整记录其标题、地点和光影时间。\n"
+ "2. **节奏分析**:识别场景间的转场方式,并准确解析场景间的时间流逝。\n"
+ "3. **叙事逻辑**:描述场景之间是如何在故事层面上相互驱动的。\n"
+)
+
+_NODE_PROMPT = "请从剧本中提取所有场景(Scene)。记录每个场景的标准标题、地点、时间段及核心情节摘要。"
+_EDGE_PROMPT = "在已识别的场景间建立联系(Transition)。请指出转场手段,并精确推断场景间的时间跨度与叙事逻辑关系。"
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+class ScriptSceneGraph(AutoTemporalGraph[Scene, SceneTransition]):
+ """
+ 适用于:[电影剧本, 电视剧本, 故事板, 叙事大纲]
+
+ 用于提取电影剧本中场景流与剪辑节奏的时序图谱模板。
+
+ 该模板专注于呈现电影的叙事节奏和场景变换,适合导演视角下的剧本拆解与可视化。
+
+ 示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> script = ScriptSceneGraph(llm_client=llm, embedder=embedder)
+ >>> text = "场景1:INT. LAB - DAY。科学家正在实验。CUT TO: 场景2:EXT. STREET - NIGHT。三小时后,他出现在街头。"
+ >>> script.feed_text(text)
+ >>> script.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "two_stage",
+ **kwargs: Any
+ ):
+ super().__init__(
+ node_schema=Scene,
+ edge_schema=SceneTransition,
+ node_key_extractor=lambda x: x.title.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,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ extraction_mode=extraction_mode,
+ **kwargs
+ )
+
+ def show(self, **kwargs):
+ def n_label(node: Scene) -> str: return node.title
+ def e_label(edge: SceneTransition) -> str: return f"{edge.transition_type} ({edge.time})"
+ super().show(node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs)
diff --git a/hyperextract/templates/zh/news/__init__.py b/hyperextract/templates/zh/news/__init__.py
index e69de29..b33b750 100644
--- a/hyperextract/templates/zh/news/__init__.py
+++ b/hyperextract/templates/zh/news/__init__.py
@@ -0,0 +1,5 @@
+from .breaking_event_graph import BreakingEventGraph
+from .topic_timeline import TopicTimeline
+from .opinion_set import OpinionSet
+
+__all__ = ["BreakingEventGraph", "TopicTimeline", "OpinionSet"]
diff --git a/hyperextract/templates/zh/news/breaking_event_graph.py b/hyperextract/templates/zh/news/breaking_event_graph.py
new file mode 100644
index 0000000..0254198
--- /dev/null
+++ b/hyperextract/templates/zh/news/breaking_event_graph.py
@@ -0,0 +1,84 @@
+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 NewsEntity(BaseModel):
+ """新闻事件中的关键实体(人物、组织、国家、核心物件)。"""
+ name: str = Field(description="实体的全称或最常用名。")
+ category: str = Field(description="实体类别(如:政治人物、国际组织、政府机构、抗议团体)。")
+ role: str = Field(description="该实体在当前新闻事件中扮演的角色或立场(如:发起者、受害者、调停方)。")
+
+class NewsAction(BaseModel):
+ """实体间的具体动作、行为或声明。"""
+ source: str = Field(description="动作的发起方。")
+ target: str = Field(description="动作的对象或接收方。")
+ action_type: str = Field(description="动作类型(如:谴责、签署协议、发起进攻、发布声明)。")
+ impact: str = Field(description="该动作产生的直接影响、结果或背景动机。")
+ evidence: str = Field(description="对应的原文核心表述片段。")
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一位资深的新闻编辑和地缘政治分析师。你的任务是从新闻报道中快速提取突发事件的全景图。\n\n"
+ "提取要求:\n"
+ "1. **实体定位**:提取所有关键参与方,并明确其在事件中的角色。\n"
+ "2. **互动追踪**:分析各方之间的实体动作(Action),区分言语声明与实际行为。\n"
+ "3. **影响评估**:捕捉动作背后的影响和核心动机。\n"
+)
+
+_NODE_PROMPT = "提取新闻中提及的所有关键人物、组织和国家。请注明其所属类别及在事件中的主要角色。"
+_EDGE_PROMPT = "识别各方之间的具体行为与互动逻辑。请描述动作的性质、影响,并附带原文证据。"
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+class BreakingEventGraph(AutoGraph[NewsEntity, NewsAction]):
+ """
+ 适用于:[突发新闻报道, 地缘政治简报, 新闻稿, 情报摘要]
+
+ 用于快速解析突发新闻中“谁对谁做了什么”的全景图谱模板。
+
+ 该模板适合快速梳理复杂国际事件、经济纠纷或突发社会事件中各方的互动网。
+
+ 示例:
+ >>> news = BreakingEventGraph(llm_client=llm, embedder=embedder)
+ >>> text = "联合国秘书长今日公开谴责某国的军事行动,并呼吁立即停火。"
+ >>> news.feed_text(text).show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "one_stage",
+ **kwargs: Any
+ ):
+ super().__init__(
+ node_schema=NewsEntity,
+ edge_schema=NewsAction,
+ node_key_extractor=lambda x: x.name.strip(),
+ edge_key_extractor=lambda x: f"{x.source}-{x.action_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):
+ def n_label(node: NewsEntity) -> str: return f"{node.name} ({node.role})"
+ def e_label(edge: NewsAction) -> str: return edge.action_type
+ super().show(node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs)
diff --git a/hyperextract/templates/zh/news/opinion_set.py b/hyperextract/templates/zh/news/opinion_set.py
new file mode 100644
index 0000000..b1e1d7c
--- /dev/null
+++ b/hyperextract/templates/zh/news/opinion_set.py
@@ -0,0 +1,69 @@
+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 OpinionStance(BaseModel):
+ """在该话题下,某个主体持有的观点与立场。"""
+ entity: str = Field(description="表达观点的个人、组织、媒体或团体。")
+ stance: str = Field(description="核心立场标签(如:支持、强烈反对、中立、质疑)。")
+ key_argument: str = Field(description="支撑该立场的核心论点或诉求。")
+ evidence_provided: List[str] = Field(description="主体提供的论据、数据或事实支撑。")
+ potential_interest: Optional[str] = Field(description="该立场背后可能隐含的利益诉求或动机。")
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一位多维舆情分析师。你的任务是从新闻报道、杂谈或评论中识别并归纳不同利益相关方的观点立场。\n\n"
+ "提取要求:\n"
+ "1. **主体识别**:清晰界定发声的主体。\n"
+ "2. **立场解构**:不仅要记录‘说了什么’,还要通过细微的语调判断其核心态度(立场)。\n"
+ "3. **论证梳理**:提取其陈述中具有说服力的事实依据。\n"
+ "4. **横向沉淀**:如果多个文本提到了同一个主体的相同立场,请将新的论据补充到该主体条目中。\n"
+)
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+class OpinionSet(AutoSet[OpinionStance]):
+ """
+ 适用于:[舆情分析, 媒体评论, 辩论实录, 社论专栏]
+
+ 用于从新闻和评论中归纳不同主体观点分布及论据的知识挖掘模板。
+
+ 该模板使用 AutoSet 结构,根据“主体+立场”作为主键进行知识沉淀,适合梳理复杂议题下的舆论博弈格局。
+
+ 示例:
+ >>> opinion_set = OpinionSet(llm_client=llm, embedder=embedder)
+ >>> text = "环保组织A发表声明反对该项目,称其会破坏湿地。当地政府则表示项目能带动就业。"
+ >>> opinion_set.feed_text(text).show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ **kwargs: Any
+ ):
+ super().__init__(
+ schema=OpinionStance,
+ # 以 实体 和 立场 的组合作为主键,沉淀同类观点
+ key_extractor=lambda x: f"{x.entity.strip()}:{x.stance.strip()}",
+ llm_client=llm_client,
+ embedder=embedder,
+ prompt=_PROMPT,
+ **kwargs
+ )
+
+ def show(self, **kwargs):
+ def label_func(item: OpinionStance) -> str:
+ return f"【{item.stance}】{item.entity}: {item.key_argument}"
+ super().show(label_extractor=label_func, **kwargs)
diff --git a/hyperextract/templates/zh/news/topic_timeline.py b/hyperextract/templates/zh/news/topic_timeline.py
new file mode 100644
index 0000000..261f488
--- /dev/null
+++ b/hyperextract/templates/zh/news/topic_timeline.py
@@ -0,0 +1,103 @@
+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 定义
+# ==============================================================================
+
+
+class NewsEventNode(BaseModel):
+ """专题新闻中的核心事件节点。"""
+
+ event_summary: str = Field(description="事件的简短标题或摘要。")
+ location: Optional[str] = Field(description="事件发生的具体地理位置。")
+ key_participants: List[str] = Field(description="涉及的核心人物或组织列表。")
+
+
+class NewsTimelineProgression(BaseModel):
+ """事件随时间的演进逻辑。"""
+
+ source: str = Field(description="前导事件摘要。")
+ target: str = Field(description="后续事件摘要。")
+ time: str = Field(
+ description="事件发生的具体时间节点。你必须解析文本中的模糊表达(如‘两周后’)为绝对日期。"
+ )
+ evolution_type: str = Field(
+ description="事态演变性质(如:升级、转折、平息、连锁反应)。"
+ )
+ description: str = Field(description="这一阶段演进的具体内容描述。")
+
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一位资深的时政调查记者。你的任务是从深度报道或系列新闻中梳理事件发展的脉络。\n\n"
+ "提取要求:\n"
+ "1. **节点提取**:识别具有里程碑意义的单一事件节点。\n"
+ "2. **时间对齐**:根据基准日期解析出的所有时间信息,并将其体现在边(Progression)上。\n"
+ "3. **动态关联**:侧重描述事件之间是如何由时间驱动并产生因果联系的。\n"
+)
+
+_NODE_PROMPT = (
+ "识别新闻报道中的关键里程碑事件。为每个事件提供简明标题、地点及核心参与者。"
+)
+_EDGE_PROMPT = "在里程碑事件间建立时序链。请基于提供的观察日期解析相对时间词,并说明事态是如何演变或连锁触发的。"
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class TopicTimeline(AutoTemporalGraph[NewsEventNode, NewsTimelineProgression]):
+ """
+ 适用于:[系列报道, 长篇调查新闻, 专题档案, 历史回顾]
+
+ 用于将零散新闻报道串联成连贯主题演化时间轴的模板。
+
+ 该模板专注于呈现事态的纵向发展轨迹,适合追踪长期社会热点或政策演变。
+
+ 示例:
+ >>> timeline = TopicTimeline(llm_client=llm, embedder=embedder)
+ >>> text = "2023年法案提出。半年后,经过激烈辩论获得通过。次月正式生效。"
+ >>> timeline.feed_text(text).show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "two_stage",
+ **kwargs: Any,
+ ):
+ super().__init__(
+ node_schema=NewsEventNode,
+ edge_schema=NewsTimelineProgression,
+ node_key_extractor=lambda x: x.event_summary.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,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ extraction_mode=extraction_mode,
+ **kwargs,
+ )
+
+ def show(self, **kwargs):
+ def n_label(node: NewsEventNode) -> str:
+ return node.event_summary
+
+ def e_label(edge: NewsTimelineProgression) -> str:
+ return f"[{edge.time}] {edge.evolution_type}"
+
+ super().show(
+ node_label_extractor=n_label, edge_label_extractor=e_label, **kwargs
+ )
diff --git a/hyperextract/templates/zh/physics/__init__.py b/hyperextract/templates/zh/physics/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/hyperextract/templates/zh/tcm/__init__.py b/hyperextract/templates/zh/tcm/__init__.py
index e69de29..16221ec 100644
--- a/hyperextract/templates/zh/tcm/__init__.py
+++ b/hyperextract/templates/zh/tcm/__init__.py
@@ -0,0 +1,13 @@
+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
+
+__all__ = [
+ "PrescriptionCompositionGraph",
+ "SyndromeTreatmentLoop",
+ "MeridianAcupointSpatial",
+ "PrescriptionManualSet",
+ "HerbInteractionHypergraph",
+]
diff --git a/hyperextract/templates/zh/tcm/herb_interaction_hypergraph.py b/hyperextract/templates/zh/tcm/herb_interaction_hypergraph.py
new file mode 100644
index 0000000..b784660
--- /dev/null
+++ b/hyperextract/templates/zh/tcm/herb_interaction_hypergraph.py
@@ -0,0 +1,118 @@
+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/meridian_acupoint_spatial.py b/hyperextract/templates/zh/tcm/meridian_acupoint_spatial.py
new file mode 100644
index 0000000..b1a412f
--- /dev/null
+++ b/hyperextract/templates/zh/tcm/meridian_acupoint_spatial.py
@@ -0,0 +1,120 @@
+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/prescription_composition_graph.py b/hyperextract/templates/zh/tcm/prescription_composition_graph.py
new file mode 100644
index 0000000..8e615c1
--- /dev/null
+++ b/hyperextract/templates/zh/tcm/prescription_composition_graph.py
@@ -0,0 +1,122 @@
+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.py
new file mode 100644
index 0000000..e8a4aaa
--- /dev/null
+++ b/hyperextract/templates/zh/tcm/prescription_manual_set.py
@@ -0,0 +1,96 @@
+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/syndrome_treatment_loop.py b/hyperextract/templates/zh/tcm/syndrome_treatment_loop.py
new file mode 100644
index 0000000..578f519
--- /dev/null
+++ b/hyperextract/templates/zh/tcm/syndrome_treatment_loop.py
@@ -0,0 +1,117 @@
+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/hyperextract/templates/zh/wuxia/__init__.py b/hyperextract/templates/zh/wuxia/__init__.py
index e69de29..b236940 100644
--- a/hyperextract/templates/zh/wuxia/__init__.py
+++ b/hyperextract/templates/zh/wuxia/__init__.py
@@ -0,0 +1,9 @@
+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
new file mode 100644
index 0000000..cb31513
--- /dev/null
+++ b/hyperextract/templates/zh/wuxia/artifact_registry.py
@@ -0,0 +1,97 @@
+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
new file mode 100644
index 0000000..ca6f06e
--- /dev/null
+++ b/hyperextract/templates/zh/wuxia/cultivation_system_map.py
@@ -0,0 +1,137 @@
+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
new file mode 100644
index 0000000..335332e
--- /dev/null
+++ b/hyperextract/templates/zh/wuxia/sect_relation_graph.py
@@ -0,0 +1,134 @@
+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
+ )