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 automotive manufacturing, biology, business, and chemistry domains
yifanfeng97d922ba63f35b
diff --git a/examples/auto_hypergraph_demo.py b/examples/auto_hypergraph_demo.pyindex c5d74dd..c458380 100644--- a/examples/auto_hypergraph_demo.py+++ b/examples/auto_hypergraph_demo.py@@ -371,6 +371,11 @@ def main():print("✅ 分析完成!")print("=" * 70)+ hypergraph.show(+ node_label_extractor=lambda n: f"{n.name}\n({n.category})",+ edge_label_extractor=lambda e: f"{e.edge_type}",+ )+if __name__ == "__main__":main()diff --git a/hyperextract/graphs/base.py b/hyperextract/graphs/base.pyindex a5fe623..260ce56 100644--- a/hyperextract/graphs/base.py+++ b/hyperextract/graphs/base.py@@ -872,12 +872,21 @@ class AutoGraph(self,node_label_extractor: Callable[[NodeSchema], str],edge_label_extractor: Callable[[EdgeSchema], str],+ *,+ top_k_nodes_for_search: int = 3,+ top_k_edges_for_search: int = 3,+ top_k_nodes_for_chat: int = 3,+ top_k_edges_for_chat: int = 3,) -> None:"""Visualize the graph using OntoSight.Args:node_label_extractor: A function that takes a NodeSchema and returns a string label for visualization.edge_label_extractor: A function that takes an EdgeSchema and returns a string label for visualization.+ top_k_nodes_for_search: Number of nodes to retrieve for search callback (default: 3).+ top_k_edges_for_search: Number of edges to retrieve for search callback (default: 3).+ top_k_nodes_for_chat: Number of nodes to retrieve for chat callback (default: 3).+ top_k_edges_for_chat: Number of edges to retrieve for chat callback (default: 3)."""if self._node_memory.has_index() and self._edge_memory.has_index():@@ -886,10 +895,10 @@ class AutoGraph()def search_callback(query: str) -> None:- return self.search(query, top_k_nodes=3, top_k_edges=3)+ return self.search(query, top_k_nodes=top_k_nodes_for_search, top_k_edges=top_k_edges_for_search)def chat_callback(question: str) -> None:- response = self.chat(question, top_k_nodes=3, top_k_edges=3)+ response = self.chat(question, top_k_nodes=top_k_nodes_for_chat, top_k_edges=top_k_edges_for_chat)content = response.contentretrieved_nodes = response.additional_kwargs.get("retrieved_nodes", [])retrieved_edges = response.additional_kwargs.get("retrieved_edges", [])diff --git a/hyperextract/hypergraphs/base.py b/hyperextract/hypergraphs/base.pyindex 097c8eb..e7e3902 100644--- a/hyperextract/hypergraphs/base.py+++ b/hyperextract/hypergraphs/base.py@@ -23,6 +23,7 @@ from langchain_core.language_models.chat_models import BaseChatModelfrom langchain_core.prompts import ChatPromptTemplatefrom ontomem import OMemfrom ontomem.merger import MergeStrategy, create_merger, BaseMerger+from ontosight import view_hypergraphfrom hyperextract.core import BaseAutoTypefrom hyperextract.utils.logging import logger@@ -809,3 +810,58 @@ class AutoHypergraph(self._edge_memory.load_index(str(edge_index_path))except Exception as e:logger.warning(f"Failed to load edge index: {e}")++ def show(+ self,+ node_label_extractor: Callable[[NodeSchema], str],+ edge_label_extractor: Callable[[EdgeSchema], str],+ *,+ top_k_nodes_for_search: int = 3,+ top_k_edges_for_search: int = 3,+ top_k_nodes_for_chat: int = 3,+ top_k_edges_for_chat: int = 3,+ ) -> None:+ """Visualize the hypergraph using OntoSight.++ Args:+ node_label_extractor: A function that takes a NodeSchema and returns a string label for visualization.+ edge_label_extractor: A function that takes an EdgeSchema and returns a string label for visualization.+ top_k_nodes_for_search: Number of nodes to retrieve for search callback (default: 3).+ top_k_edges_for_search: Number of edges to retrieve for search callback (default: 3).+ top_k_nodes_for_chat: Number of nodes to retrieve for chat callback (default: 3).+ top_k_edges_for_chat: Number of edges to retrieve for chat callback (default: 3).+ """++ if self._node_memory.has_index() and self._edge_memory.has_index():+ logger.info(+ "Visualizing hypergraph with search and chat capabilities (indices detected)."+ )++ def search_callback(query: str) -> None:+ return self.search(query, top_k_nodes=top_k_nodes_for_search, top_k_edges=top_k_edges_for_search)++ def chat_callback(question: str) -> None:+ response = self.chat(question, top_k_nodes=top_k_nodes_for_chat, top_k_edges=top_k_edges_for_chat)+ content = response.content+ retrieved_nodes = response.additional_kwargs.get("retrieved_nodes", [])+ retrieved_edges = response.additional_kwargs.get("retrieved_edges", [])+ return content, (retrieved_nodes, retrieved_edges)+ else:+ logger.info(+ "Visualizing hypergraph without search and chat capabilities (no indices detected)."+ )+ search_callback = None+ chat_callback = None++ view_hypergraph(+ node_list=self.nodes,+ edge_list=self.edges,+ node_schema=self.node_schema,+ edge_schema=self.edge_schema,+ node_id_extractor=self.node_key_extractor,+ node_ids_in_edge_extractor=self.nodes_in_edge_extractor,+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ on_search=search_callback,+ on_chat=chat_callback,+ )diff --git a/hyperextract/templates/en/__init__.py b/hyperextract/templates/en/__init__.pyindex 0050835..ada7ed1 100644--- a/hyperextract/templates/en/__init__.py+++ b/hyperextract/templates/en/__init__.py@@ -1,9 +1,45 @@from .general.knowledge_graph import KnowledgeGraphfrom .general.concept_map import ConceptMapfrom .general.logic_graph import LogicGraph+from .agriculture.crop import CropStatusGraph+from .agriculture.supply_chain import AgriSupplyChainGraph+from .agriculture.soil import SoilNutritionGraph+from .art.history import ArtHistoryGraph+from .art.style import ArtStyleGraph+from .art.exhibition import ExhibitionGraph+from .automotive.vehicle import VehicleSpecGraph+from .automotive.diagnosis import VehicleDiagnosisGraph+from .automotive.market import AutoMarketGraph+from .biology.taxonomy import TaxonomyGraph+from .biology.network import BiologicalNetwork+from .biology.metabolic import MetabolicHypergraph+from .business.equity import EquityStructureGraph+from .business.strategy import StrategicChainGraph+from .business.ecosystem import MarketEcosystemHyper+from .chemistry.molecular import MolecularStructureGraph+from .chemistry.reaction import ChemicalReactionHyper+from .chemistry.protocol import LabProtocolTemporal__all__ = ["KnowledgeGraph","ConceptMap","LogicGraph",+ "CropStatusGraph",+ "AgriSupplyChainGraph",+ "SoilNutritionGraph",+ "ArtHistoryGraph",+ "ArtStyleGraph",+ "ExhibitionGraph",+ "VehicleSpecGraph",+ "VehicleDiagnosisGraph",+ "AutoMarketGraph",+ "TaxonomyGraph",+ "BiologicalNetwork",+ "MetabolicHypergraph",+ "EquityStructureGraph",+ "StrategicChainGraph",+ "MarketEcosystemHyper",+ "MolecularStructureGraph",+ "ChemicalReactionHyper",+ "LabProtocolTemporal",]diff --git a/hyperextract/templates/en/agriculture/__init__.py b/hyperextract/templates/en/agriculture/__init__.pyindex e69de29..34c0d82 100644--- a/hyperextract/templates/en/agriculture/__init__.py+++ b/hyperextract/templates/en/agriculture/__init__.py@@ -0,0 +1,15 @@+from .crop_cycle import CropCycleGraph, AgriEntity, AgriRelation+from .livestock import LivestockGraph, AnimalNode, BreedingRelation+from .supply_chain import AgriSupplyChain, SupplyEntity, SupplyFlow++__all__ = [+ "CropCycleGraph",+ "AgriEntity",+ "AgriRelation",+ "LivestockGraph",+ "AnimalNode",+ "BreedingRelation",+ "AgriSupplyChain",+ "SupplyEntity",+ "SupplyFlow"+]diff --git a/hyperextract/templates/en/agriculture/crop_cycle.py b/hyperextract/templates/en/agriculture/crop_cycle.pynew file mode 100644index 0000000..8f4b54f--- /dev/null+++ b/hyperextract/templates/en/agriculture/crop_cycle.py@@ -0,0 +1,111 @@+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.graphs import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class AgriEntity(BaseModel):+ """An entity in the agricultural domain (e.g., Crop, Soil, Pest, Pest Control, Equipment)."""+ name: str = Field(description="The name of the agricultural entity.")+ category: str = Field(+ description="Category: 'Crop', 'Growth Stage', 'Soil/Climate Condition', 'Task/Activity', 'Stress/Pest', 'Input/Fertilizer'."+ )+ description: Optional[str] = Field(description="Specific characteristics or state of the entity.")++class AgriRelation(BaseModel):+ """A relationship between agricultural entities (e.g., 'requires', 'affected by', 'follows')."""+ source: str = Field(description="The source entity name.")+ target: str = Field(description="The target entity name.")+ relation_type: str = Field(+ description="Type: 'is at stage', 'impacts', 'requires task', 'applied to', 'leads to next stage'."+ )+ specification: Optional[str] = Field(description="Dosage, timing, or specific impact details.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++CROP_CYCLE_PROMPT = (+ "You are an expert agronomist. Extract a crop growth and management graph from the text.\n\n"+ "Guidelines:\n"+ "- Identify the crop and its specific growth stages (e.g., Sowing, Flowering).\n"+ "- Map soil conditions, weather requirements, and necessary farming activities (irrigation, fertilization) to specific stages.\n"+ "- Note any threats like pests or diseases and their impact on the crop."+)++CROP_CYCLE_NODE_PROMPT = (+ "Extract key agricultural components: crop types, growth stages, environmental conditions (soil/pH/temp), "+ "farming tasks, and biological stresses (pests/fungi). Provide a clear category for each."+)++CROP_CYCLE_EDGE_PROMPT = (+ "Establish logical links in the crop cycle. Connect stages in sequence, link tasks to the stages they belong to, "+ "and map environmental requirements to the entities they affect. Use specific relation types like 'requires' or 'inhibits'."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class CropCycleGraph(AutoGraph[AgriEntity, AgriRelation]):+ """+ Template for mapping crop growth stages, environmental requirements, and farming activities.++ Ideal for precision agriculture, crop management guides, and seasonal planning.++ Example:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> graph = CropCycleGraph(llm_client=llm, embedder=embedder)+ >>> text = "Corn requires high nitrogen during the vegetative stage."+ >>> graph.feed_text(text)+ >>> print(graph.nodes) # Extracted Corn, Nitrogen, Vegetative Stage+ """+ 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 the CropCycleGraph template.++ Args:+ llm_client: The language model client for extraction.+ embedder: The embedding model for deduplication.+ extraction_mode: "one_stage" or "two_stage".+ chunk_size: Max characters per chunk.+ chunk_overlap: Overlap between chunks.+ max_workers: Parallel processing workers.+ verbose: Enable progress logging.+ **kwargs: Extra arguments for AutoGraph.+ """+ super().__init__(+ node_schema=AgriEntity,+ edge_schema=AgriRelation,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation_type.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=CROP_CYCLE_PROMPT,+ prompt_for_node_extraction=CROP_CYCLE_NODE_PROMPT,+ prompt_for_edge_extraction=CROP_CYCLE_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/agriculture/livestock.py b/hyperextract/templates/en/agriculture/livestock.pynew file mode 100644index 0000000..fbd71fd--- /dev/null+++ b/hyperextract/templates/en/agriculture/livestock.py@@ -0,0 +1,111 @@+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.graphs import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class AnimalNode(BaseModel):+ """An entity in livestock management (e.g., individual animal, breed, group, health condition)."""+ name: str = Field(description="Name or ID of the animal/group.")+ category: str = Field(+ description="Category: 'Individual', 'Breed', 'Strain', 'Health Status', 'Nutrient/Feed', 'Facility'."+ )+ traits: Optional[str] = Field(description="Key physical traits, genetic markers, or health metrics.")++class BreedingRelation(BaseModel):+ """Relationships in breeding and health management."""+ source: str = Field(description="The source livestock entity.")+ target: str = Field(description="The target livestock entity.")+ relation_type: str = Field(+ description="Type: 'parent of', 'bred with', 'member of', 'diagnosed with', 'fed with'."+ )+ details: Optional[str] = Field(description="Inherited traits, dosage, or specific health observations.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++LIVESTOCK_GRAPH_PROMPT = (+ "You are a livestock specialist and geneticist. Extract a breeding and health management graph.\n\n"+ "Guidelines:\n"+ "- Identify individual animals and their breeds.\n"+ "- Map pedigree relationships (parent-offspring) and breeding pairs.\n"+ "- Link animals to their health status, vaccinations, and nutrition records."+)++LIVESTOCK_NODE_PROMPT = (+ "Extract livestock entities: identify specific animals (by ID or name), breeds, health conditions, "+ "vaccines, and specific feed types. Provide relevant traits or metrics for each."+)++LIVESTOCK_EDGE_PROMPT = (+ "Link livestock entities logically. Map family trees (parental links), breeding history, "+ "and medical/nutritional events. Ensure relation types like 'bred with' or 'fed with' are used accurately."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):+ """+ Template for managing livestock pedigrees, health records, and breeding programs.++ Useful for farm management software, veterinary records, and genetic tracking.++ Example:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> graph = LivestockGraph(llm_client=llm, embedder=embedder)+ >>> text = "Cow #402 (Angus) was crossbred with Bull #09 to improve meat quality."+ >>> graph.feed_text(text)+ >>> print(graph.edges) # Extracted breeding relationship+ """+ 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 the LivestockGraph template.++ Args:+ llm_client: The language model client for extraction.+ embedder: The embedding model for deduplication.+ extraction_mode: "one_stage" or "two_stage".+ chunk_size: Max characters per chunk.+ chunk_overlap: Overlap between chunks.+ max_workers: Parallel processing workers.+ verbose: Enable progress logging.+ **kwargs: Extra arguments for AutoGraph.+ """+ super().__init__(+ node_schema=AnimalNode,+ edge_schema=BreedingRelation,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation_type.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=LIVESTOCK_GRAPH_PROMPT,+ prompt_for_node_extraction=LIVESTOCK_NODE_PROMPT,+ prompt_for_edge_extraction=LIVESTOCK_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/agriculture/supply_chain.py b/hyperextract/templates/en/agriculture/supply_chain.pynew file mode 100644index 0000000..e9cb0a1--- /dev/null+++ b/hyperextract/templates/en/agriculture/supply_chain.py@@ -0,0 +1,111 @@+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.graphs import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class SupplyEntity(BaseModel):+ """An actor or asset in the agri-supply chain (e.g., Farm, Warehouse, Processor, Logistics, Retailer)."""+ name: str = Field(description="Name of the organization, facility, or batch ID.")+ category: str = Field(+ description="Category: 'Producer/Farm', 'Processor', 'Distributor', 'Logistics Provider', 'Retailer', 'Batch/Product'."+ )+ location_or_cert: Optional[str] = Field(description="Geographic location or quality certification (e.g., Organic, ISO).")++class SupplyFlow(BaseModel):+ """The flow of products or information between supply chain actors."""+ source: str = Field(description="The starting entity (sender/producer).")+ target: str = Field(description="The receiving entity (buyer/processor).")+ flow_type: str = Field(+ description="Type: 'Ships to', 'Processes', 'Sells to', 'Tests', 'Certifies'."+ )+ specification: Optional[str] = Field(description="Quantity, transportation mode, or quality check result.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++AGRI_SUPPLY_CHAIN_PROMPT = (+ "You are a supply chain analyst specializing in agriculture. Extract a traceability and logistics graph.\n\n"+ "Guidelines:\n"+ "- Identify all actors involved from the farm to the fork (Producer, Processor, Distributor).\n"+ "- Map the flow of specific batches or products through various stages.\n"+ "- Capture quality checks, certifications, and transportation modes mentioned in the text."+)++AGRI_SUPPLY_CHAIN_NODE_PROMPT = (+ "Extract supply chain entities: identify specific farms, factories, logistics hubs, and retailers. "+ "Note their roles, locations, and any quality certifications mentioned."+)++AGRI_SUPPLY_CHAIN_EDGE_PROMPT = (+ "Establish the movement of goods and information. Connect producers to processors, and processors to retailers. "+ "Use specific relation types like 'Ships to' or 'Processes', and include details like transport methods or quantities."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class AgriSupplyChain(AutoGraph[SupplyEntity, SupplyFlow]):+ """+ Template for agricultural traceability, logistics mapping, and supply chain transparency.++ Ideal for food safety tracking, logistics optimization, and trade analysis.++ Example:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> graph = AgriSupplyChain(llm_client=llm, embedder=embedder)+ >>> text = "Batch #A102 was shipped from GreenFarm (Organic) to CentralProcessor via cold-chain truck."+ >>> graph.feed_text(text)+ >>> print(graph.edges) # Extracted logistics flow+ """+ 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 the AgriSupplyChain template.++ Args:+ llm_client: The language model client for extraction.+ embedder: The embedding model for deduplication.+ extraction_mode: "one_stage" or "two_stage".+ chunk_size: Max characters per chunk.+ chunk_overlap: Overlap between chunks.+ max_workers: Parallel processing workers.+ verbose: Enable progress logging.+ **kwargs: Extra arguments for AutoGraph.+ """+ super().__init__(+ node_schema=SupplyEntity,+ edge_schema=SupplyFlow,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.flow_type.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=AGRI_SUPPLY_CHAIN_PROMPT,+ prompt_for_node_extraction=AGRI_SUPPLY_CHAIN_NODE_PROMPT,+ prompt_for_edge_extraction=AGRI_SUPPLY_CHAIN_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/art/__init__.py b/hyperextract/templates/en/art/__init__.pyindex e69de29..96cb725 100644--- a/hyperextract/templates/en/art/__init__.py+++ b/hyperextract/templates/en/art/__init__.py@@ -0,0 +1,9 @@+from .provenance import ProvenanceGraph+from .movement import ArtMovementGraph+from .exhibition import ExhibitionGraph++__all__ = [+ "ProvenanceGraph",+ "ArtMovementGraph",+ "ExhibitionGraph",+]diff --git a/hyperextract/templates/en/art/exhibition.py b/hyperextract/templates/en/art/exhibition.pynew file mode 100644index 0000000..588e31a--- /dev/null+++ b/hyperextract/templates/en/art/exhibition.py@@ -0,0 +1,109 @@+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.graphs import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class ExhibitionEntity(BaseModel):+ """An element of an art exhibition (Curator, Theme, Work, Venue, Sponsor)."""+ name: str = Field(description="Name of the exhibition, artist, or curator.")+ type: str = Field(+ description="Type: 'Exhibition', 'Theme', 'Artwork', 'Curator', 'Venue', 'Partner'."+ )+ details: Optional[str] = Field(description="Exhibition dates, conceptual notes, or location.")++class ExhibitionRelation(BaseModel):+ """Connectivity within an exhibition's planning and execution."""+ source: str = Field(description="The organizing or controlling entity.")+ target: str = Field(description="The related work or participant.")+ relation_type: str = Field(+ description="Type: 'Curated by', 'Featured in', 'Hosted at', 'Sponsored by', 'Thematically linked to'."+ )+ context: Optional[str] = Field(description="Specific room, loan conditions, or thematic sub-group.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++EXHIBITION_GRAPH_PROMPT = (+ "You are a museum curator and exhibition designer. Map the structure of an art exhibition.\n\n"+ "Guidelines:\n"+ "- Identify the exhibition title, its central themes, and the participating artists/works.\n"+ "- Connect works to their thematic sections and the curators responsible.\n"+ "- Capture logistics like venues and sponsors."+)++EXHIBITION_NODE_PROMPT = (+ "Extract exhibition components: titles, venues, themes, specific artworks, and key personnel (curators, designers)."+)++EXHIBITION_EDGE_PROMPT = (+ "Link items within the exhibition. Show which artworks belong to which theme and identify the hosting venue and sponsors."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class ExhibitionGraph(AutoGraph[ExhibitionEntity, ExhibitionRelation]):+ """+ Template for curatorial planning and exhibition analysis.++ Tracks the relationships between artworks, themes, curators, and venues.++ Example:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI()+ >>> embedder = OpenAIEmbeddings()+ >>> graph = ExhibitionGraph(llm_client=llm, embedder=embedder)+ >>> text = "The 'Surrealist Dreams' exhibition was curated by Alice Smith at the Tate Modern."+ >>> graph.feed_text(text)+ >>> print(graph.edges) # Exhibition connections+ """+ 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 the ExhibitionGraph template.++ Args:+ llm_client: The language model client for extraction.+ embedder: The embedding model for deduplication.+ extraction_mode: "one_stage" or "two_stage".+ chunk_size: Max characters per chunk.+ chunk_overlap: Overlap between chunks.+ max_workers: Parallel processing workers.+ verbose: Enable progress logging.+ **kwargs: Extra arguments for AutoGraph.+ """+ super().__init__(+ node_schema=ExhibitionEntity,+ edge_schema=ExhibitionRelation,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation_type.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=EXHIBITION_GRAPH_PROMPT,+ prompt_for_node_extraction=EXHIBITION_NODE_PROMPT,+ prompt_for_edge_extraction=EXHIBITION_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/art/movement.py b/hyperextract/templates/en/art/movement.pynew file mode 100644index 0000000..83cf41b--- /dev/null+++ b/hyperextract/templates/en/art/movement.py@@ -0,0 +1,110 @@+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.graphs import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class MovementEntity(BaseModel):+ """An art movement, style, artist, or influential work."""+ name: str = Field(description="Name of the movement (e.g., Impressionism) or Artist.")+ category: str = Field(+ description="Category: 'Movement', 'Style', 'Artist', 'Manifesto', 'Masterpiece'."+ )+ attributes: Optional[str] = Field(description="Key characteristics, materials, or timeframe.")++class ArtInfluenceEdge(BaseModel):+ """Influence, derivation, or membership relations in art history."""+ source: str = Field(description="The precursor or movement.")+ target: str = Field(description="The follower or specific work/artist.")+ relation: str = Field(+ description="Relation: 'Influenced', 'Founder of', 'Member of', 'Reaction against', 'Derived from'."+ )+ details: Optional[str] = Field(description="Specific stylistic techniques or historical events.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++MOVEMENT_GRAPH_PROMPT = (+ "You are an art historian specializing in the evolution of artistic styles. Extract a graph of art movements and their influences.\n\n"+ "Guidelines:\n"+ "- Identify distinct art movements and the artists associated with them.\n"+ "- Map how one movement influenced another (e.g., Post-Impressionism reacting to Impressionism).\n"+ "- Capture the core philosophies and visual characteristics defined in manifestos or works."+)++MOVEMENT_NODE_PROMPT = (+ "Extract art movements, styles, associated artists, and pivotal artworks. Describe their visual language and key theories."+)++MOVEMENT_EDGE_PROMPT = (+ "Define connections between movements and individuals. Use relations like 'Reaction against' or 'Influenced'. "+ "Note specific techniques passed between generations."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class ArtMovementGraph(AutoGraph[MovementEntity, ArtInfluenceEdge]):+ """+ Template for mapping art movements, stylistic influences, and artist school affiliations.++ Useful for educational applications and art historical analysis.++ Example:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI()+ >>> embedder = OpenAIEmbeddings()+ >>> graph = ArtMovementGraph(llm_client=llm, embedder=embedder)+ >>> text = "Impressionism, led by Monet, was later challenged by the structured approach of Post-Impressionism."+ >>> graph.feed_text(text)+ >>> print(graph.nodes) # Movement and Artist details+ """+ 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 the ArtMovementGraph template.++ Args:+ llm_client: The language model client for extraction.+ embedder: The embedding model for deduplication.+ extraction_mode: "one_stage" or "two_stage".+ chunk_size: Max characters per chunk.+ chunk_overlap: Overlap between chunks.+ max_workers: Parallel processing workers.+ verbose: Enable progress logging.+ **kwargs: Extra arguments for AutoGraph.+ """+ super().__init__(+ node_schema=MovementEntity,+ edge_schema=ArtInfluenceEdge,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=MOVEMENT_GRAPH_PROMPT,+ prompt_for_node_extraction=MOVEMENT_NODE_PROMPT,+ prompt_for_edge_extraction=MOVEMENT_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/art/provenance.py b/hyperextract/templates/en/art/provenance.pynew file mode 100644index 0000000..212fa98--- /dev/null+++ b/hyperextract/templates/en/art/provenance.py@@ -0,0 +1,111 @@+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.graphs import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class ArtEntity(BaseModel):+ """An entity in the art world (e.g., Artwork, Artist, Museum, Collector, Auction House)."""+ name: str = Field(description="Name of the artwork, person, or organization.")+ category: str = Field(+ description="Category: 'Artwork', 'Artist', 'Collector', 'Institution', 'Location'."+ )+ description: Optional[str] = Field(description="Medium, creation date, or historical status.")++class ProvenanceEdge(BaseModel):+ """The transfer of ownership or location of an artwork."""+ source: str = Field(description="Previous owner or starting location.")+ target: str = Field(description="New owner or destination.")+ transfer_type: str = Field(+ description="Type: 'Acquired by', 'Sold to', 'Donated to', 'Lent to', 'Commissioned by'."+ )+ specification: Optional[str] = Field(description="Date of transfer, sale price, or auction details.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++PROVENANCE_GRAPH_PROMPT = (+ "You are a fine arts historian and provenance researcher. Extract an artwork's ownership history graph.\n\n"+ "Guidelines:\n"+ "- Identify the core artwork and all its historical owners (Collectors, Museums, Kings).\n"+ "- Map the chronological sequence of transfers (Sales, Inheritances, Looting, Donations).\n"+ "- Capture specific dates and monetary values if mentioned."+)++PROVENANCE_NODE_PROMPT = (+ "Extract art entities: identify the artwork itself, the artists, collectors, museums, and auction houses. "+ "Note the medium of the artwork and roles of the people/institutions."+)++PROVENANCE_EDGE_PROMPT = (+ "Establish the chain of title. Connect previous owners to current owners using transfer types like 'Sold to' or 'Donated to'. "+ "Include time periods and transaction details in the specification."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class ProvenanceGraph(AutoGraph[ArtEntity, ProvenanceEdge]):+ """+ Template for tracking the ownership history (provenance) of artworks and artifacts.++ Essential for art authentication, museum archives, and historical research.++ Example:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> graph = ProvenanceGraph(llm_client=llm, embedder=embedder)+ >>> text = "The painting was acquired by the Louvre in 1815 from the Borghese collection."+ >>> graph.feed_text(text)+ >>> print(graph.edges) # Extracted ownership transfer+ """+ 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 the ProvenanceGraph template.++ Args:+ llm_client: The language model client for extraction.+ embedder: The embedding model for deduplication.+ extraction_mode: "one_stage" or "two_stage".+ chunk_size: Max characters per chunk.+ chunk_overlap: Overlap between chunks.+ max_workers: Parallel processing workers.+ verbose: Enable progress logging.+ **kwargs: Extra arguments for AutoGraph.+ """+ super().__init__(+ node_schema=ArtEntity,+ edge_schema=ProvenanceEdge,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.transfer_type.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=PROVENANCE_GRAPH_PROMPT,+ prompt_for_node_extraction=PROVENANCE_NODE_PROMPT,+ prompt_for_edge_extraction=PROVENANCE_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/automotive/__init__.py b/hyperextract/templates/en/automotive/__init__.pyindex e69de29..0184d1b 100644--- a/hyperextract/templates/en/automotive/__init__.py+++ b/hyperextract/templates/en/automotive/__init__.py@@ -0,0 +1,9 @@+from .car_spec import CarSpecGraph+from .maintenance import CarMaintenanceGraph+from .manufacturing import AutomotiveMfgGraph++__all__ = [+ "CarSpecGraph",+ "CarMaintenanceGraph",+ "AutomotiveMfgGraph",+]diff --git a/hyperextract/templates/en/automotive/car_spec.py b/hyperextract/templates/en/automotive/car_spec.pynew file mode 100644index 0000000..158e68d--- /dev/null+++ b/hyperextract/templates/en/automotive/car_spec.py@@ -0,0 +1,109 @@+from typing import Optional, Any+from pydantic import BaseModel, Field+from langchain_core.language_models.chat_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.graphs import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class CarComponent(BaseModel):+ """A vehicle component or specification category (Engine, Battery, ADAS, Transmission)."""+ name: str = Field(description="Name of the car model or specific component.")+ category: str = Field(+ description="Category: 'Model', 'Powertrain', 'Chassis', 'Safety System', 'Infotainment'."+ )+ specification: Optional[str] = Field(description="Detailed specs (e.g., Horsepower, Capacity, Version).")++class CarSystemRelation(BaseModel):+ """The hierarchy or technical relationship between car systems."""+ source: str = Field(description="Parent system or vehicle model.")+ target: str = Field(description="Sub-component or feature.")+ relation_type: str = Field(+ description="Type: 'Equipped with', 'Powered by', 'Integrated with', 'Compatible with'."+ )+ performance_note: Optional[str] = Field(description="Benchmark data or integration details.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++CAR_SPEC_GRAPH_PROMPT = (+ "You are an automotive engineer and technical reviewer. Extract a technical specification graph for a vehicle.\n\n"+ "Guidelines:\n"+ "- Identify the vehicle model and its primary systems (Engine, Motor, Battery, ADAS).\n"+ "- Map the hierarchy of components (e.g., Battery contains Cells, Engine uses Turbocharger).\n"+ "- Capture quantifiable specs like 0-60 mph, Range, Peak Power, and Torque."+)++CAR_SPEC_NODE_PROMPT = (+ "Extract car models and technical components. Focus on names and their measurable specifications (e.g., 500hp, 80kWh)."+)++CAR_SPEC_EDGE_PROMPT = (+ "Define technical dependencies. Show which components belong to which car system. Use relations like 'Powered by' or 'Equipped with'."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class CarSpecGraph(AutoGraph[CarComponent, CarSystemRelation]):+ """+ Template for extracting vehicle technical data and specification hierarchies.++ Ideal for competitive analysis, e-commerce car data, and technical documentation.++ Example:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI()+ >>> embedder = OpenAIEmbeddings()+ >>> graph = CarSpecGraph(llm_client=llm, embedder=embedder)+ >>> text = "The Tesla Model 3 Performance features a dual-motor AWD system delivering 510 hp."+ >>> graph.feed_text(text)+ >>> print(graph.nodes) # Vehicle and component specs+ """+ 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 the CarSpecGraph template.++ Args:+ llm_client: The language model client for extraction.+ embedder: The embedding model for deduplication.+ extraction_mode: "one_stage" or "two_stage".+ chunk_size: Max characters per chunk.+ chunk_overlap: Overlap between chunks.+ max_workers: Parallel processing workers.+ verbose: Enable progress logging.+ **kwargs: Extra arguments for AutoGraph.+ """+ super().__init__(+ node_schema=CarComponent,+ edge_schema=CarSystemRelation,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation_type.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=CAR_SPEC_GRAPH_PROMPT,+ prompt_for_node_extraction=CAR_SPEC_NODE_PROMPT,+ prompt_for_edge_extraction=CAR_SPEC_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/automotive/maintenance.py b/hyperextract/templates/en/automotive/maintenance.pynew file mode 100644index 0000000..dc25ac1--- /dev/null+++ b/hyperextract/templates/en/automotive/maintenance.py@@ -0,0 +1,105 @@+from typing import Optional, Any+from pydantic import BaseModel, Field+from langchain_core.language_models.chat_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.graphs import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class MaintenanceItem(BaseModel):+ """A maintenance task or vehicle part (Oil Change, Brake Pad, Timing Belt)."""+ item_name: str = Field(description="Name of the part or maintenance service.")+ category: str = Field(description="Category: 'Fluid', 'Wearable Part', 'Inspection', 'Software'.")+ interval: Optional[str] = Field(description="Suggested mileage or time interval (e.g., 5,000 miles).")++class MaintenanceSequence(BaseModel):+ """The dependency or sequence of maintenance actions."""+ source: str = Field(description="Prerequisite component or initial state.")+ target: str = Field(description="Maintenance task or replacement part.")+ action: str = Field(description="Action: 'Replace', 'Inspect', 'Flush', 'Calibrate'.")+ precaution: Optional[str] = Field(description="Safety warnings or required tools.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++MAINTENANCE_GRAPH_PROMPT = (+ "You are a master mechanic and service consultant. Extract a vehicle maintenance and repair graph.\n\n"+ "Guidelines:\n"+ "- Identify specific maintenance items and parts mentioned in the manual or log.\n"+ "- Map the conditions that trigger maintenance (e.g., Mileage, Warning Light, Visual Inspection).\n"+ "- Link parts to their respective systems and required actions."+)++MAINTENANCE_NODE_PROMPT = (+ "Extract maintenance tasks, parts, and fluid types. Include recommended intervals if specified."+)++MAINTENANCE_EDGE_PROMPT = (+ "Connect triggers to actions. Show which parts need replacement or inspection. Note specific precautions for each task."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class CarMaintenanceGraph(AutoGraph[MaintenanceItem, MaintenanceSequence]):+ """+ Template for vehicle service manuals, repair guides, and ownership logs.++ Helps organize maintenance schedules and part compatibility information.++ Example:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI()+ >>> embedder = OpenAIEmbeddings()+ >>> graph = CarMaintenanceGraph(llm_client=llm, embedder=embedder)+ >>> text = "Change engine oil and filter every 10,000 km using synthetic 0W-20."+ >>> graph.feed_text(text)+ >>> print(graph.nodes) # Maintenance items+ """+ 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 the CarMaintenanceGraph template.++ Args:+ llm_client: The language model client for extraction.+ embedder: The embedding model for deduplication.+ extraction_mode: "one_stage" or "two_stage".+ chunk_size: Max characters per chunk.+ chunk_overlap: Overlap between chunks.+ max_workers: Parallel processing workers.+ verbose: Enable progress logging.+ **kwargs: Extra arguments for AutoGraph.+ """+ super().__init__(+ node_schema=MaintenanceItem,+ edge_schema=MaintenanceSequence,+ node_key_extractor=lambda x: x.item_name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.action.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=MAINTENANCE_GRAPH_PROMPT,+ prompt_for_node_extraction=MAINTENANCE_NODE_PROMPT,+ prompt_for_edge_extraction=MAINTENANCE_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/automotive/manufacturing.py b/hyperextract/templates/en/automotive/manufacturing.pynew file mode 100644index 0000000..7030b0b--- /dev/null+++ b/hyperextract/templates/en/automotive/manufacturing.py@@ -0,0 +1,109 @@+from typing import Optional, Any+from pydantic import BaseModel, Field+from langchain_core.language_models.chat_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.graphs import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class ManufacturingEntity(BaseModel):+ """An entity in the automotive supply chain or production line (Supplier, Factory, Assembly Step)."""+ name: str = Field(description="Name of the company, factory, or production process.")+ category: str = Field(+ description="Category: 'Supplier', 'Factory', 'Process', 'Material', 'Quality Check'."+ )+ specification: Optional[str] = Field(description="Production capacity, certifications, or lead times.")++class SupplyChainRelation(BaseModel):+ """Connectivity between players and steps in automotive manufacturing."""+ source: str = Field(description="The upstream supplier or process.")+ target: str = Field(description="The downstream factory or product.")+ relation_type: str = Field(+ description="Type: 'Supplies to', 'Assembled at', 'Processed by', 'Certified for'."+ )+ logistics_details: Optional[str] = Field(description="Incoterms, transit times, or volume commitments.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++MFG_GRAPH_PROMPT = (+ "You are a supply chain analyst for a major auto manufacturer. Extract the manufacturing and supply chain graph.\n\n"+ "Guidelines:\n"+ "- Identify the tiers of suppliers (Tier 1, Tier 2) and the components they provide.\n"+ "- Map the assembly sequence from raw materials to the final vehicle roll-out.\n"+ "- Capture geographic locations of factories and specific logistics constraints."+)++MFG_NODE_PROMPT = (+ "Extract suppliers, manufacturing plants, and critical production steps. Note their roles in the vehicle production cycle."+)++MFG_EDGE_PROMPT = (+ "Define the material and process flow. Connect suppliers to assembly plants and plants to the final car delivery."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class AutomotiveMfgGraph(AutoGraph[ManufacturingEntity, SupplyChainRelation]):+ """+ Template for automotive production lines, supply chain logistics, and supplier management.++ Helps visualize dependencies in the global automotive manufacturing ecosystem.++ Example:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI()+ >>> embedder = OpenAIEmbeddings()+ >>> graph = AutomotiveMfgGraph(llm_client=llm, embedder=embedder)+ >>> text = "CATL supplies battery cells to the Tesla Gigafactory in Berlin for Model Y assembly."+ >>> graph.feed_text(text)+ >>> print(graph.edges) # Supply chain flow+ """+ 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 the AutomotiveMfgGraph template.++ Args:+ llm_client: The language model client for extraction.+ embedder: The embedding model for deduplication.+ extraction_mode: "one_stage" or "two_stage".+ chunk_size: Max characters per chunk.+ chunk_overlap: Overlap between chunks.+ max_workers: Parallel processing workers.+ verbose: Enable progress logging.+ **kwargs: Extra arguments for AutoGraph.+ """+ super().__init__(+ node_schema=ManufacturingEntity,+ edge_schema=SupplyChainRelation,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation_type.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=MFG_GRAPH_PROMPT,+ prompt_for_node_extraction=MFG_NODE_PROMPT,+ prompt_for_edge_extraction=MFG_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/biology/__init__.py b/hyperextract/templates/en/biology/__init__.pyindex e69de29..74ca094 100644--- a/hyperextract/templates/en/biology/__init__.py+++ b/hyperextract/templates/en/biology/__init__.py@@ -0,0 +1,9 @@+from .taxonomy import TaxonomyGraph+from .network import BiologicalNetwork+from .metabolic import MetabolicHypergraph++__all__ = [+ "TaxonomyGraph",+ "BiologicalNetwork",+ "MetabolicHypergraph",+]diff --git a/hyperextract/templates/en/biology/metabolic.py b/hyperextract/templates/en/biology/metabolic.pynew file mode 100644index 0000000..7b7b9a4--- /dev/null+++ b/hyperextract/templates/en/biology/metabolic.py@@ -0,0 +1,89 @@+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.hypergraphs.base import AutoHypergraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class MetaboliteNode(BaseModel):+ """+ Any physical substance (substrate or product) involved in a metabolic reaction.+ """+ name: str = Field(description="Chemical or common name of the molecule (e.g., 'Pyruvate').")+ formula: Optional[str] = Field(None, description="Chemical formula/notation.")+ charge: Optional[int] = Field(None, description="Net electrical charge of the metabolite.")+ compartment: Optional[str] = Field(description="Cellular location: 'Cytosol', 'Mitochondria', 'Extracellular'.")++class MetabolicReactionHyperedge(BaseModel):+ """+ A multi-reagent biochemical reaction where multiple substrates yield multiple products.+ """+ reaction_id: str = Field(description="Unique identifier or EC number (e.g., 'EC 1.1.1.1').")+ substrates: List[str] = Field(description="List of substrate metabolite names.")+ products: List[str] = Field(description="List of product metabolite names.")+ enzymes: List[str] = Field(default_factory=list, description="List of catalysts (enzymes) involved.")+ stoichiometry: Optional[str] = Field(None, description="Balancing coefficients if mentioned in text.")+ reversibility: bool = Field(True, description="Whether the reaction is reversible.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++METABOLIC_CONSOLIDATED_PROMPT = (+ "You are a biochemist specializing in metabolic engineering. Extract complex N-ary reactions.\n\n"+ "Rules:\n"+ "- Group all participants (substrates, products, and enzymes) into a single Hyperedge.\n"+ "- Distinguish between reactants (substrates) and results (products).\n"+ "- Capture the catalytic enzymes as part of the hyperedge participants."+)++METABOLIC_NODE_PROMPT = (+ "Identify all chemical substances (metabolites) and enzymes. Focus on accurate nomenclature."+)++METABOLIC_EDGE_PROMPT = (+ "Define hyperedges representing metabolic reactions. Include ALL participating metabolites and enzymes "+ "for each identified reaction event."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class MetabolicHypergraph(AutoHypergraph[MetaboliteNode, MetabolicReactionHyperedge]):+ """+ Complex hypergraph template for metabolic pathways involving multi-substrate/multi-product reactions.+ """+ 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+ ):+ super().__init__(+ node_schema=MetaboliteNode,+ edge_schema=MetabolicReactionHyperedge,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: x.reaction_id.strip(),+ nodes_in_edge_extractor=lambda x: tuple(set(x.substrates + x.products + x.enzymes)),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=METABOLIC_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=METABOLIC_NODE_PROMPT,+ prompt_for_edge_extraction=METABOLIC_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/biology/network.py b/hyperextract/templates/en/biology/network.pynew file mode 100644index 0000000..09c609c--- /dev/null+++ b/hyperextract/templates/en/biology/network.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.graphs.base import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class BioEntityNode(BaseModel):+ """+ A fundamental biological unit representing a gene, protein, or small molecule.+ """+ name: str = Field(description="Standardized symbol or name (e.g., 'BRCA1', 'cAMP').")+ category: str = Field(description="Entity type: 'Gene', 'Protein', 'RNA', 'Metabolite', 'Enzyme', 'Transcription Factor'.")+ synonyms: Optional[str] = Field(None, description="Alternative names or database IDs (e.g., UniProt, Entrez).")+ biological_function: Optional[str] = Field(None, description="Dominant molecular function or cellular localization.")++class BioInteractionEdge(BaseModel):+ """+ A direct physical or functional interaction between two biological entities.+ """+ source: str = Field(description="The upstream or acting entity.")+ target: str = Field(description="The downstream or acted-upon entity.")+ interaction_type: str = Field(description="Type: 'Phosphorylates', 'Inhibits', 'Activates', 'Binds', 'Regulates', 'Cleaves'.")+ mechanism: Optional[str] = Field(None, description="Specific biochemical mechanism (e.g., 'Allosteric inhibition').")+ strength: Optional[str] = Field(None, description="Confidence score or binding affinity if available.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++NETWORK_CONSOLIDATED_PROMPT = (+ "You are a bioinformatics expert specializing in molecular signaling and regulatory networks. "+ "Extract interactions from the text to build a biological network graph.\n\n"+ "Rules:\n"+ "- Distinguish between different molecular types (Protein vs Gene).\n"+ "- Identify directed interactions (e.g., Enzyme A phosphorylates Protein B).\n"+ "- Capture the specific biochemical mechanism for each edge."+)++NETWORK_NODE_PROMPT = (+ "Identify all genes, proteins, and molecules mentioned. Normalize names to standard symbols where possible. "+ "Ignore generic terms like 'the protein' or 'this molecule' unless they refer to a specific named entity."+)++NETWORK_EDGE_PROMPT = (+ "Extract functional and physical interactions between the identified bio-entities. "+ "Define the direction and nature of the interaction (Activation, Inhibition, etc.)."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class BiologicalNetwork(AutoGraph[BioEntityNode, BioInteractionEdge]):+ """+ Template for modeling molecular signaling, metabolic pathways (binary), and regulatory networks.+ """+ 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+ ):+ super().__init__(+ node_schema=BioEntityNode,+ edge_schema=BioInteractionEdge,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.interaction_type.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=NETWORK_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=NETWORK_NODE_PROMPT,+ prompt_for_edge_extraction=NETWORK_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/biology/taxonomy.py b/hyperextract/templates/en/biology/taxonomy.pynew file mode 100644index 0000000..832ab4e--- /dev/null+++ b/hyperextract/templates/en/biology/taxonomy.py@@ -0,0 +1,88 @@+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.graphs.base import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class TaxonNode(BaseModel):+ """+ Represents a biological taxon in the Tree of Life.+ """+ name: str = Field(description="Scientific name (Latin) or standardized common name of the organism/group.")+ rank: str = Field(description="Taxonomic rank: 'Domain', 'Kingdom', 'Phylum', 'Class', 'Order', 'Family', 'Genus', 'Species'.")+ common_name: Optional[str] = Field(None, description="General name used in non-scientific contexts.")+ description: Optional[str] = Field(None, description="Brief biological characteristics, habitat, or distinguishing traits.")++class TaxonomyRelation(BaseModel):+ """+ A direct hierarchical relationship between two taxons.+ """+ source: str = Field(description="The parent taxon (e.g., 'Mammalia').")+ target: str = Field(description="The child taxon (e.g., 'Primates').")+ type: str = Field("parent_of", description="Relationship type: 'parent_of', 'subspecies_of', 'classified_under'.")+ evidence: Optional[str] = Field(None, description="Reference to phenotypic or genomic data justifying the classification.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++TAXONOMY_CONSOLIDATED_PROMPT = (+ "You are a professional taxonomist and systematic biologist. Extract the biological hierarchy (Taxonomy) from the text.\n\n"+ "Rules:\n"+ "- Identify all taxons (Kingdom to Species) and their specific ranks.\n"+ "- Construct a strict tree-like hierarchy using 'parent_of' relationships.\n"+ "- Capture both scientific names and common names where available."+)++TAXONOMY_NODE_PROMPT = (+ "Extract all biological taxonomic groups (Nodes). Identify their ranks (e.g., Family: Hominidae). "+ "Focus on formal classifications and exclude transient or non-standard groupings."+)++TAXONOMY_EDGE_PROMPT = (+ "Map the lineage of the provided taxons. Create edges that reflect the phylogenetic descent "+ "or classification tree. Ensure the source is higher or equal in rank to the target."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class TaxonomyGraph(AutoGraph[TaxonNode, TaxonomyRelation]):+ """+ High-fidelity template for biological classification and phylogenetic hierarchies.+ """+ 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+ ):+ super().__init__(+ node_schema=TaxonNode,+ edge_schema=TaxonomyRelation,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.type})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=TAXONOMY_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=TAXONOMY_NODE_PROMPT,+ prompt_for_edge_extraction=TAXONOMY_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/business/__init__.py b/hyperextract/templates/en/business/__init__.pyindex e69de29..8da251c 100644--- a/hyperextract/templates/en/business/__init__.py+++ b/hyperextract/templates/en/business/__init__.py@@ -0,0 +1,9 @@+from .equity import EquityStructureGraph+from .strategy import StrategicChainGraph+from .ecosystem import MarketEcosystemHyper++__all__ = [+ "EquityStructureGraph",+ "StrategicChainGraph",+ "MarketEcosystemHyper",+]diff --git a/hyperextract/templates/en/business/ecosystem.py b/hyperextract/templates/en/business/ecosystem.pynew file mode 100644index 0000000..b676cc7--- /dev/null+++ b/hyperextract/templates/en/business/ecosystem.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.hypergraphs.base import AutoHypergraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class IndustryParticipant(BaseModel):+ """+ An entity (Company, Regulatory Body, NGO) within an industrial ecosystem.+ """+ name: str = Field(description="Name of the actor (e.g., 'TSMC', 'European Commission').")+ rank: Optional[str] = Field(None, description="Market position: 'Tier 1 Supplier', 'Market Leader', 'Challenger'.")+ technological_focus: Optional[str] = Field(None, description="Primary tech or domain (e.g., '5G', 'Lithography').")++class CollectiveAlliance(BaseModel):+ """+ A hyperedge representing a consortium, alliance, market cartel, or joint standard-setting body.+ """+ alliance_id: str = Field(description="Name or identifier of the alliance (e.g., 'CHIPS Alliance').")+ participants: List[str] = Field(description="Names of all entities collaborating or competing in this group.")+ shared_goal: str = Field(description="The objective: 'Standardization', 'Anti-monopoly Review', 'Joint R&D'.")+ governance: Optional[str] = Field(None, description="Rules of participation or leading entity.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++ECOSYSTEM_CONSOLIDATED_PROMPT = (+ "You are a market strategist and antitrust expert. Extract market ecosystem dynamics.\n\n"+ "Rules:\n"+ "- Use Hyperedges to link multiple entities (3+) participating in a joint venture or alliance.\n"+ "- Capture non-binary group relations like cartels, industrial clusters, and regulatory coalitions.\n"+ "- Define the shared goal of these groups clearly."+)++ECOSYSTEM_NODE_PROMPT = (+ "Identify all business and regulatory actors in the ecosystem. Note their market ranks and tech focus."+)++ECOSYSTEM_EDGE_PROMPT = (+ "Extract collective alliances. Group participating entities into clusters (hyperedges). "+ "Focus on consortiums, standard-setting bodies, and joint market actions."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class MarketEcosystemHyper(AutoHypergraph[IndustryParticipant, CollectiveAlliance]):+ """+ Hypergraph template for industrial clusters, ecosystem coalitions, and complex market alliances.+ """+ 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+ ):+ super().__init__(+ node_schema=IndustryParticipant,+ edge_schema=CollectiveAlliance,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: x.alliance_id.strip(),+ nodes_in_edge_extractor=lambda x: tuple(x.participants),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=ECOSYSTEM_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=ECOSYSTEM_NODE_PROMPT,+ prompt_for_edge_extraction=ECOSYSTEM_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/business/equity.py b/hyperextract/templates/en/business/equity.pynew file mode 100644index 0000000..e344eff--- /dev/null+++ b/hyperextract/templates/en/business/equity.py@@ -0,0 +1,89 @@+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.graphs.base import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class StakeholderNode(BaseModel):+ """+ A legal or natural person holding equity or control in a business.+ """+ name: str = Field(description="Full registry name of the company or individual's full name.")+ type: str = Field(description="Type: 'Natural Person', 'Public Company', 'Private Company', 'State-Owned Enterprise', 'Venture Capital'.")+ jurisdiction: Optional[str] = Field(None, description="Country or region of incorporation/residence.")+ is_ubo: bool = Field(False, description="Whether this entity is identified as an Ultimate Beneficial Owner.")++class OwnershipRelation(BaseModel):+ """+ A stakeholding or control link between two entities.+ """+ source: str = Field(description="The shareholder or parent entity.")+ target: str = Field(description="The company being owned or controlled (subsidiary).")+ stake_percentage: Optional[float] = Field(None, description="Percentage of ownership (0.0 to 100.0).")+ control_type: str = Field("Equity", description="Nature of link: 'Equity Acquisition', 'Voting Rights', 'Nominee Shareholding', 'Direct Control'.")+ as_of_date: Optional[str] = Field(None, description="The date or fiscal period when this ownership was recorded.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++EQUITY_CONSOLIDATED_PROMPT = (+ "You are a corporate paralegal and financial analyst. Extract complex ownership structures.\n\n"+ "Rules:\n"+ "- Prioritize identifying the percentage of shares held by each entity.\n"+ "- Distinguish between direct shareholders and Ultimate Beneficial Owners (UBO).\n"+ "- Map the hierarchy from the parent organization down to the smallest subsidiary."+)++EQUITY_NODE_PROMPT = (+ "Extract all companies, investment funds, and individuals mentioned in the context of ownership. "+ "Classify them into 'Natural Person', 'Private Company', etc."+)++EQUITY_EDGE_PROMPT = (+ "Construct ownership edges. Capture the percentage of equity and the specific type of control. "+ "Identify the flow of capital from shareholder to the target entity."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class EquityStructureGraph(AutoGraph[StakeholderNode, OwnershipRelation]):+ """+ Precision template for corporate registries, M&A analysis, and KYC/UBO tracking.+ """+ 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+ ):+ super().__init__(+ node_schema=StakeholderNode,+ edge_schema=OwnershipRelation,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}->{x.target.strip()}_at_{x.stake_percentage}%",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=EQUITY_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=EQUITY_NODE_PROMPT,+ prompt_for_edge_extraction=EQUITY_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/business/strategy.py b/hyperextract/templates/en/business/strategy.pynew file mode 100644index 0000000..519aa42--- /dev/null+++ b/hyperextract/templates/en/business/strategy.py@@ -0,0 +1,89 @@+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.graphs.temporal_graph import AutoTemporalGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class StrategicNode(BaseModel):+ """+ An organizational entity, business division, or strategic objective.+ """+ name: str = Field(description="Name of the strategic unit or goal (e.g., 'Azure', 'Carbon Neutrality').")+ scope: str = Field(description="Scope: 'Global', 'Regional', 'Product-specific', 'Corporate-wide'.")+ importance: Optional[str] = Field(None, description="Criticality: 'Core Business', 'Emerging Market', 'Legacy'.")++class StrategicPivot(BaseModel):+ """+ A temporal transition representing a change in strategic focus, investment, or divestiture.+ """+ source: str = Field(description="The original area of focus or acting entity.")+ target: str = Field(description="The new target, direction, or goal.")+ action: str = Field(description="Strategic action: 'Pivot to', 'Acquire', 'Divest', 'Merge', 'Sunset', 'Scale'.")+ timestamp: str = Field(description="When the shift occurred (e.g., 'Q4 2022', '2025-01-01').")+ rationale: Optional[str] = Field(None, description="The 'Why' behind the move (market pressure, CEO change, tech shift).")+ budget: Optional[str] = Field(None, description="Financial commitment mentioned alongside the pivot.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++STRATEGY_CONSOLIDATED_PROMPT = (+ "You are a management consultant and industry analyst. Extract the evolution of corporate strategy.\n\n"+ "Rules:\n"+ "- Focus on 'Pivots': movements from one business area to another.\n"+ "- Link specific actions to concrete timestamps.\n"+ "- Capture the underlying reasoning (rationale) for each strategic change."+)++STRATEGY_NODE_PROMPT = (+ "Extract business units, product lines, and high-level corporate goals. Identify their organizational importance."+)++STRATEGY_EDGE_PROMPT = (+ "Map strategic transitions over time. Ensure the 'timestamp' is resolved to specific periods. "+ "Identify what the company moved FROM (source) and what it moved TO (target)."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class StrategicChainGraph(AutoTemporalGraph[StrategicNode, StrategicPivot]):+ """+ Temporal template for tracking corporate strategy, longitudinal organizational change, and market shifts.+ """+ 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+ ):+ super().__init__(+ node_schema=StrategicNode,+ edge_schema=StrategicPivot,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}-({x.action})->{x.target.strip()}",+ time_in_edge_extractor=lambda x: x.timestamp.strip(),+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=STRATEGY_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=STRATEGY_NODE_PROMPT,+ prompt_for_edge_extraction=STRATEGY_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/chemistry/__init__.py b/hyperextract/templates/en/chemistry/__init__.pyindex e69de29..eb82d62 100644--- a/hyperextract/templates/en/chemistry/__init__.py+++ b/hyperextract/templates/en/chemistry/__init__.py@@ -0,0 +1,9 @@+from .molecular import MolecularStructureGraph+from .reaction import ChemicalReactionHyper+from .protocol import LabProtocolTemporal++__all__ = [+ "MolecularStructureGraph",+ "ChemicalReactionHyper",+ "LabProtocolTemporal",+]diff --git a/hyperextract/templates/en/chemistry/molecular.py b/hyperextract/templates/en/chemistry/molecular.pynew file mode 100644index 0000000..2368f4b--- /dev/null+++ b/hyperextract/templates/en/chemistry/molecular.py@@ -0,0 +1,89 @@+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.graphs.spatial_graph import AutoSpatialGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class AtomNode(BaseModel):+ """+ An individual atom in a chemical structure.+ """+ name: str = Field(description="Atom identifier (e.g., 'C1', 'O2') or element symbol.")+ element: str = Field(description="The chemical element (e.g., 'Carbon', 'H').")+ hybridization: Optional[str] = Field(None, description="Electronic state: 'sp3', 'sp2', 'sp'.")+ formal_charge: int = Field(0, description="The electrical charge assigned to the atom.")++class ChemicalBond(BaseModel):+ """+ A chemical bond between two atoms, including spatial/positional metadata.+ """+ source: str = Field(description="The originating atom (e.g., 'C1').")+ target: str = Field(description="The connected atom (e.g., 'C2').")+ bond_type: str = Field(description="Type: 'Single', 'Double', 'Triple', 'Aromatic', 'Hydrogen'.")+ spatial_position: str = Field(description="The physical or logical position in the molecule (e.g., 'C4 position', 'Axial', 'Equatorial').")+ bond_length: Optional[float] = Field(None, description="Distance between atoms in Angstroms.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++MOLECULAR_CONSOLIDATED_PROMPT = (+ "You are a computational chemist and crystallographer. Extract the 3D molecular topology.\n\n"+ "Rules:\n"+ "- Identify every atom as a node.\n"+ "- Define bonds including their specific spatial orientation (e.g., 'Alpha', 'Beta', 'Cis', 'Trans').\n"+ "- Capture the formal charge and hybridization of each atom."+)++MOLECULAR_NODE_PROMPT = (+ "Extract all individual atoms. Note their element type and electronic hybridization states."+)++MOLECULAR_EDGE_PROMPT = (+ "Map the connectivity (bonds) between atoms. Specifically identify the spatial position "+ "where the connection occurs within the molecular framework."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class MolecularStructureGraph(AutoSpatialGraph[AtomNode, ChemicalBond]):+ """+ Spatial graph template for high-resolution molecular modeling and structural biology.+ """+ 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+ ):+ super().__init__(+ node_schema=AtomNode,+ edge_schema=ChemicalBond,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.bond_type})-->{x.target.strip()}",+ location_in_edge_extractor=lambda x: x.spatial_position.strip(),+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=MOLECULAR_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=MOLECULAR_NODE_PROMPT,+ prompt_for_edge_extraction=MOLECULAR_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/chemistry/protocol.py b/hyperextract/templates/en/chemistry/protocol.pynew file mode 100644index 0000000..57f0ea1--- /dev/null+++ b/hyperextract/templates/en/chemistry/protocol.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.graphs.temporal_graph import AutoTemporalGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class LabOperation(BaseModel):+ """+ A specific step or action in a chemical or biological protocol (e.g., 'Centrifugation', 'Titration').+ """+ op_id: str = Field(description="Action name (e.g., 'Centrifuge', 'Heat', 'Add').")+ equipment: Optional[str] = Field(None, description="Device used (e.g., 'Microcentrifuge', 'Bunsen burner').")+ reagents_added: List[str] = Field(default_factory=list, description="Chemicals introduced during this specific step.")+ precautions: Optional[str] = Field(None, description="Safety or accuracy warnings (e.g., 'Keep on ice').")++class ProtocolTransition(BaseModel):+ """+ The sequential transition between protocol steps, capturing duration and order.+ """+ transition_id: str = Field(description="Unique id for the step transition.")+ source_step: str = Field(description="The preceding operation.")+ target_step: str = Field(description="The succeeding operation.")+ duration: Optional[str] = Field(None, description="Time spent in or between steps (e.g., '15 mins', 'Overnight').")+ timestamp: str = Field(description="The sequence order or relative time marker (e.g., 'T+0', 'Step 2').")+ wait_condition: Optional[str] = Field(None, description="Condition to proceed (e.g., 'Until precipitate forms').")++# ==============================================================================+# 2. Prompts+# ==============================================================================++PROTOCOL_CONSOLIDATED_PROMPT = (+ "You are a laboratory technician specializing in protocol documentation. Extract sequential lab steps.\n\n"+ "Rules:\n"+ "- Represent each operation as a Node.\n"+ "- Represent the sequence and duration between operations as Temporal Edges.\n"+ "- Capture specific reagents/equipment associated with each step.\n"+ "- Map the timeline precisely (e.g., 'Step 1' -> 'Step 2')."+)++PROTOCOL_NODE_PROMPT = (+ "Identify individual laboratory operations, actions, and the equipment/reagents used for each."+)++PROTOCOL_EDGE_PROMPT = (+ "Track the chronological flow between these operations. Identify the time elapsed or conditions required to move between steps."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class LabProtocolTemporal(AutoTemporalGraph[LabOperation, ProtocolTransition]):+ """+ Temporal graph template for capturing step-by-step laboratory procedures and experimental workflows.+ """+ 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+ ):+ super().__init__(+ node_schema=LabOperation,+ edge_schema=ProtocolTransition,+ node_key_extractor=lambda x: x.op_id.strip(),+ edge_key_extractor=lambda x: x.transition_id.strip(),+ nodes_in_edge_extractor=lambda x: (x.source_step.strip(), x.target_step.strip()),+ time_in_edge_extractor=lambda x: x.timestamp.strip(),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=PROTOCOL_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=PROTOCOL_NODE_PROMPT,+ prompt_for_edge_extraction=PROTOCOL_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/en/chemistry/reaction.py b/hyperextract/templates/en/chemistry/reaction.pynew file mode 100644index 0000000..cd74958--- /dev/null+++ b/hyperextract/templates/en/chemistry/reaction.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.hypergraphs.base import AutoHypergraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class ChemicalEntity(BaseModel):+ """+ A chemical substance (Reagent, Product, Catalyst, Solvent).+ """+ name: str = Field(description="IUPAC name or common name (e.g., 'Sulfuric Acid').")+ formula: Optional[str] = Field(None, description="Chemical formula (e.g., 'H2SO4').")+ cas_number: Optional[str] = Field(None, description="CAS Registry Number.")+ phase: str = Field("Unknown", description="Physical state: 'Gas', 'Liquid', 'Solid', 'Aqueous'.")++class ReactionEvent(BaseModel):+ """+ A chemical reaction involving multiple reagents, specific conditions, and resulting products.+ """+ reaction_id: str = Field(description="Name or short description of the reaction (e.g., 'Haber Process').")+ reactants: List[str] = Field(description="List of starting chemical entity names.")+ products: List[str] = Field(description="List of resulting chemical entity names.")+ catalysts: List[str] = Field(default_factory=list, description="Names of substances facilitating the reaction.")+ solvents: List[str] = Field(default_factory=list, description="The medium in which the reaction occurs.")+ temperature: Optional[str] = Field(None, description="Operating temperature (e.g., '250°C').")+ pressure: Optional[str] = Field(None, description="Operating pressure (e.g., '200 atm').")+ yield_info: Optional[str] = Field(None, description="Percentage/amount of product obtained.")++# ==============================================================================+# 2. Prompts+# ==============================================================================++REACTION_CONSOLIDATED_PROMPT = (+ "You are an expert organic and inorganic chemist. Extract multi-component reaction events.\n\n"+ "Rules:\n"+ "- Represent each reaction as a Hyperedge connecting all reactants, products, and catalysts.\n"+ "- Capture detailed conditions like temperature, pressure, and specific solvents.\n"+ "- Identify the role of each chemical entity correctly in the reaction context."+)++REACTION_NODE_PROMPT = (+ "Identify all chemical entities mentioned. Look for IUPAC names, formulas, and CAS numbers."+)++REACTION_EDGE_PROMPT = (+ "Map reactions involving these chemicals. Group all participants into single reaction hyperedges. "+ "Ensure reactants and products are clearly distinguished."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class ChemicalReactionHyper(AutoHypergraph[ChemicalEntity, ReactionEvent]):+ """+ Hypergraph template for complex chemical synthesis, industrial processes, and reaction pathways.+ """+ 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+ ):+ super().__init__(+ node_schema=ChemicalEntity,+ edge_schema=ReactionEvent,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: x.reaction_id.strip(),+ nodes_in_edge_extractor=lambda x: tuple(set(x.reactants + x.products + x.catalysts + x.solvents)),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=REACTION_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=REACTION_NODE_PROMPT,+ prompt_for_edge_extraction=REACTION_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/__init__.py b/hyperextract/templates/zh/__init__.pyindex 0050835..ada7ed1 100644--- a/hyperextract/templates/zh/__init__.py+++ b/hyperextract/templates/zh/__init__.py@@ -1,9 +1,45 @@from .general.knowledge_graph import KnowledgeGraphfrom .general.concept_map import ConceptMapfrom .general.logic_graph import LogicGraph+from .agriculture.crop import CropStatusGraph+from .agriculture.supply_chain import AgriSupplyChainGraph+from .agriculture.soil import SoilNutritionGraph+from .art.history import ArtHistoryGraph+from .art.style import ArtStyleGraph+from .art.exhibition import ExhibitionGraph+from .automotive.vehicle import VehicleSpecGraph+from .automotive.diagnosis import VehicleDiagnosisGraph+from .automotive.market import AutoMarketGraph+from .biology.taxonomy import TaxonomyGraph+from .biology.network import BiologicalNetwork+from .biology.metabolic import MetabolicHypergraph+from .business.equity import EquityStructureGraph+from .business.strategy import StrategicChainGraph+from .business.ecosystem import MarketEcosystemHyper+from .chemistry.molecular import MolecularStructureGraph+from .chemistry.reaction import ChemicalReactionHyper+from .chemistry.protocol import LabProtocolTemporal__all__ = ["KnowledgeGraph","ConceptMap","LogicGraph",+ "CropStatusGraph",+ "AgriSupplyChainGraph",+ "SoilNutritionGraph",+ "ArtHistoryGraph",+ "ArtStyleGraph",+ "ExhibitionGraph",+ "VehicleSpecGraph",+ "VehicleDiagnosisGraph",+ "AutoMarketGraph",+ "TaxonomyGraph",+ "BiologicalNetwork",+ "MetabolicHypergraph",+ "EquityStructureGraph",+ "StrategicChainGraph",+ "MarketEcosystemHyper",+ "MolecularStructureGraph",+ "ChemicalReactionHyper",+ "LabProtocolTemporal",]diff --git a/hyperextract/templates/zh/agriculture/__init__.py b/hyperextract/templates/zh/agriculture/__init__.pyindex e69de29..34c0d82 100644--- a/hyperextract/templates/zh/agriculture/__init__.py+++ b/hyperextract/templates/zh/agriculture/__init__.py@@ -0,0 +1,15 @@+from .crop_cycle import CropCycleGraph, AgriEntity, AgriRelation+from .livestock import LivestockGraph, AnimalNode, BreedingRelation+from .supply_chain import AgriSupplyChain, SupplyEntity, SupplyFlow++__all__ = [+ "CropCycleGraph",+ "AgriEntity",+ "AgriRelation",+ "LivestockGraph",+ "AnimalNode",+ "BreedingRelation",+ "AgriSupplyChain",+ "SupplyEntity",+ "SupplyFlow"+]diff --git a/hyperextract/templates/zh/agriculture/crop_cycle.py b/hyperextract/templates/zh/agriculture/crop_cycle.pynew file mode 100644index 0000000..fd979c5--- /dev/null+++ b/hyperextract/templates/zh/agriculture/crop_cycle.py@@ -0,0 +1,109 @@+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.graphs import AutoGraph++# ==============================================================================+# 1. Schema 定义 (Schema Definitions)+# ==============================================================================++class AgriEntity(BaseModel):+ """农业领域实体(如作物、土壤、病虫害、防治措施、农机具)。"""+ name: str = Field(description="农业实体的名称。")+ category: str = Field(+ description="类别:'作物', '生长阶段', '土壤/气候条件', '农事活动', '逆境/病虫害', '农资/肥料'。"+ )+ description: Optional[str] = Field(description="实体的具体特征或状态描述。")++class AgriRelation(BaseModel):+ """农业实体间的关系(如'需求'、'受...影响'、'继...之后')。"""+ source: str = Field(description="源实体名称。")+ target: str = Field(description="目标实体名称。")+ relation_type: str = Field(+ description="类型:'处于阶段', '影响', '需要操作', '施用于', '进入下一阶段'。"+ )+ specification: Optional[str] = Field(description="具体的用量、时机或影响细节。")++# ==============================================================================+# 2. 提示词 (Prompts)+# ==============================================================================++CROP_CYCLE_PROMPT = (+ "你是一位资深农艺师。请从文本中提取作物生长与管理图谱。\n\n"+ "提取指南:\n"+ "- 识别作物及其具体的生长阶段(如:播种、开花、成熟)。\n"+ "- 将土壤条件、天气要求以及必要的农事活动(灌溉、施肥)关联到具体的阶段。\n"+ "- 记录任何提及的威胁因素(如病虫害)及其对作物的影响。"+)++CROP_CYCLE_NODE_PROMPT = (+ "请提取关键农业组成要素:作物类型、生长阶段、环境条件(土壤/pH值/温度)、农事任务以及生物逆境(病虫害/真菌)。为每一项提供清晰的类别。"+)++CROP_CYCLE_EDGE_PROMPT = (+ "在作物周期中建立逻辑链路。按顺序连接生长阶段,将农事任务关联到其所属的阶段,并将环境要求映射到它们影响的实体上。使用'需要'、'抑制'等具体的对应关系类型。"+)++# ==============================================================================+# 3. 模板类 (Template Class)+# ==============================================================================++class CropCycleGraph(AutoGraph[AgriEntity, AgriRelation]):+ """+ 用于映射作物生长阶段、环境要求和农事活动的模板。++ 适用于精准农业、作物管理指南以及季节性种植规划。++ 示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> graph = CropCycleGraph(llm_client=llm, embedder=embedder)+ >>> text = "玉米在营养生长阶段需要大量的氮肥。"+ >>> graph.feed_text(text)+ >>> print(graph.nodes) # 提取出:玉米、氮肥、营养生长阶段+ """+ 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+ ):+ """+ 初始化 CropCycleGraph 模板。++ Args:+ llm_client: 用于提取的语言模型客户端。+ embedder: 用于去重的嵌入模型。+ extraction_mode: "one_stage" 或 "two_stage"。+ chunk_size: 每个分块的最大字符数。+ chunk_overlap: 分块间的重叠字符数。+ max_workers: 并行处理的最大 worker 数量。+ verbose: 是否开启进度日志。+ **kwargs: 传递给 AutoGraph 的其他参数。+ """+ super().__init__(+ node_schema=AgriEntity,+ edge_schema=AgriRelation,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation_type.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=CROP_CYCLE_PROMPT,+ prompt_for_node_extraction=CROP_CYCLE_NODE_PROMPT,+ prompt_for_edge_extraction=CROP_CYCLE_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/agriculture/livestock.py b/hyperextract/templates/zh/agriculture/livestock.pynew file mode 100644index 0000000..51b2d30--- /dev/null+++ b/hyperextract/templates/zh/agriculture/livestock.py@@ -0,0 +1,109 @@+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.graphs import AutoGraph++# ==============================================================================+# 1. Schema 定义 (Schema Definitions)+# ==============================================================================++class AnimalNode(BaseModel):+ """畜牧管理中的实体(如个体动物、品种、群体、健康状况)。"""+ name: str = Field(description="动物个体或群体的名称/ID。")+ category: str = Field(+ description="类别:'个体', '品种', '品系', '健康状况', '营养/饲料', '设施'。"+ )+ traits: Optional[str] = Field(description="关键体貌特征、基因标记或健康指标。")++class BreedingRelation(BaseModel):+ """育种与健康管理中的关系。"""+ source: str = Field(description="源畜牧实体。")+ target: str = Field(description="目标畜牧实体。")+ relation_type: str = Field(+ description="类型:'父代/母代', '与...交配', '属于', '诊断为', '饲喂'。"+ )+ details: Optional[str] = Field(description="继承特征、剂量或具体的健康观察。")++# ==============================================================================+# 2. 提示词 (Prompts)+# ==============================================================================++LIVESTOCK_GRAPH_PROMPT = (+ "你是一位畜牧专家和遗传学家。请从文本中提取育种与健康管理图谱。\n\n"+ "提取指南:\n"+ "- 识别动物个体及其品种。\n"+ "- 映射家谱关系(亲子关系)和育种配对。\n"+ "- 将动物与其健康状况、疫苗接种和营养记录关联起来。"+)++LIVESTOCK_NODE_PROMPT = (+ "请提取畜牧实体:识别特定动物(通过ID或名称)、品种、健康状况、疫苗类型以及特定的饲料。为每一项提供相关的特征或指标。"+)++LIVESTOCK_EDGE_PROMPT = (+ "逻辑化地连接畜牧实体。映射家族树(亲缘链接)、育种历史以及医疗/营养事件。确保准确使用'与...交配'或'饲喂'等关系类型。"+)++# ==============================================================================+# 3. 模板类 (Template Class)+# ==============================================================================++class LivestockGraph(AutoGraph[AnimalNode, BreedingRelation]):+ """+ 用于管理畜牧系谱、健康记录和育种计划的模板。++ 适用于牧场管理软件、兽医记录和基因追踪。++ 示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> graph = LivestockGraph(llm_client=llm, embedder=embedder)+ >>> text = "402号母牛(安格斯)与09号公牛配种以提高肉质。"+ >>> graph.feed_text(text)+ >>> print(graph.edges) # 提取育种关系+ """+ 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+ ):+ """+ 初始化 LivestockGraph 模板。++ Args:+ llm_client: 用于提取的语言模型客户端。+ embedder: 用于去重的嵌入模型。+ extraction_mode: "one_stage" 或 "two_stage"。+ chunk_size: 每个分块的最大字符数。+ chunk_overlap: 分块间的重叠字符数。+ max_workers: 并行处理的最大 worker 数量。+ verbose: 是否开启进度日志。+ **kwargs: 传递给 AutoGraph 的其他参数。+ """+ super().__init__(+ node_schema=AnimalNode,+ edge_schema=BreedingRelation,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation_type.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=LIVESTOCK_GRAPH_PROMPT,+ prompt_for_node_extraction=LIVESTOCK_NODE_PROMPT,+ prompt_for_edge_extraction=LIVESTOCK_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/agriculture/supply_chain.py b/hyperextract/templates/zh/agriculture/supply_chain.pynew file mode 100644index 0000000..e1cdf9c--- /dev/null+++ b/hyperextract/templates/zh/agriculture/supply_chain.py@@ -0,0 +1,109 @@+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.graphs import AutoGraph++# ==============================================================================+# 1. Schema 定义 (Schema Definitions)+# ==============================================================================++class SupplyEntity(BaseModel):+ """农产品供应链中的参与者或资产(如农场、仓库、加工商、物流商、零售商)。"""+ name: str = Field(description="机构、设施的名称或批次ID。")+ category: str = Field(+ description="类别:'生产者/农场', '加工商', '分销商', '物流商', '零售商', '批次/产品'。"+ )+ location_or_cert: Optional[str] = Field(description="地理位置或质量认证(如:有机认证、ISO)。")++class SupplyFlow(BaseModel):+ """供应链参与者之间的产品或信息流。"""+ source: str = Field(description="起始实体(发送方/生产者)。")+ target: str = Field(description="接收实体(购买方/加工商)。")+ flow_type: str = Field(+ description="类型:'发货至', '加工', '销售给', '检测', '认证'。"+ )+ specification: Optional[str] = Field(description="数量、运输方式或质量检测结果。")++# ==============================================================================+# 2. 提示词 (Prompts)+# ==============================================================================++AGRI_SUPPLY_CHAIN_PROMPT = (+ "你是一位专注于农业的供应链分析师。请从文本中提取溯源与物流图谱。\n\n"+ "提取指南:\n"+ "- 识别从农田到餐桌(生产者、加工商、分销商)涉及的所有参与者。\n"+ "- 映射特定批次或产品经过各个阶段的流动情况。\n"+ "- 捕获文本中提到的质量检测、认证和运输方式。"+)++AGRI_SUPPLY_CHAIN_NODE_PROMPT = (+ "请提取供应链实体:识别特定的农场、工厂、物流枢纽和零售商。记录它们的角色、位置以及提及的任何质量认证。"+)++AGRI_SUPPLY_CHAIN_EDGE_PROMPT = (+ "建立货物与信息的流动。连接生产者到加工商,以及加工商到零售商。使用'发货至'或'加工'等具体的关系类型,并包含运输方式或数量等细节。"+)++# ==============================================================================+# 3. 模板类 (Template Class)+# ==============================================================================++class AgriSupplyChain(AutoGraph[SupplyEntity, SupplyFlow]):+ """+ 用于农产品溯源、物流映射和供应链透明化的模板。++ 适用于食品安全追踪、物流优化和贸易分析。++ 示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> graph = AgriSupplyChain(llm_client=llm, embedder=embedder)+ >>> text = "批次#A102通过冷链卡车从绿色农场(有机认证)运往中央处理厂。"+ >>> graph.feed_text(text)+ >>> print(graph.edges) # 提取物流流向+ """+ 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+ ):+ """+ 初始化 AgriSupplyChain 模板。++ Args:+ llm_client: 用于提取的语言模型客户端。+ embedder: 用于去重的嵌入模型。+ extraction_mode: "one_stage" 或 "two_stage"。+ chunk_size: 每个分块的最大字符数。+ chunk_overlap: 分块间的重叠字符数。+ max_workers: 并行处理的最大 worker 数量。+ verbose: 是否开启进度日志。+ **kwargs: 传递给 AutoGraph 的其他参数。+ """+ super().__init__(+ node_schema=SupplyEntity,+ edge_schema=SupplyFlow,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.flow_type.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=AGRI_SUPPLY_CHAIN_PROMPT,+ prompt_for_node_extraction=AGRI_SUPPLY_CHAIN_NODE_PROMPT,+ prompt_for_edge_extraction=AGRI_SUPPLY_CHAIN_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/art/__init__.py b/hyperextract/templates/zh/art/__init__.pyindex e69de29..96cb725 100644--- a/hyperextract/templates/zh/art/__init__.py+++ b/hyperextract/templates/zh/art/__init__.py@@ -0,0 +1,9 @@+from .provenance import ProvenanceGraph+from .movement import ArtMovementGraph+from .exhibition import ExhibitionGraph++__all__ = [+ "ProvenanceGraph",+ "ArtMovementGraph",+ "ExhibitionGraph",+]diff --git a/hyperextract/templates/zh/art/exhibition.py b/hyperextract/templates/zh/art/exhibition.pynew file mode 100644index 0000000..1fc04e7--- /dev/null+++ b/hyperextract/templates/zh/art/exhibition.py@@ -0,0 +1,109 @@+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.graphs import AutoGraph++# ==============================================================================+# 1. 模式定义 (Schema)+# ==============================================================================++class ExhibitionEntity(BaseModel):+ """艺术展览的组成要素(策展人、主题、作品、场馆、赞助商)。"""+ name: str = Field(description="展览名称、艺术家姓名或策展人姓名。")+ type: str = Field(+ description="类型:'展览'、'主题'、'艺术品'、'策展人'、'场馆'、'合作伙伴'。"+ )+ details: Optional[str] = Field(description="展览日期、理念说明或地理位置。")++class ExhibitionRelation(BaseModel):+ """展览策划与执行中的连接关系。"""+ source: str = Field(description="组织或控制实体。")+ target: str = Field(description="相关的作品 or 参与者。")+ relation_type: str = Field(+ description="类型:'策展自'、'参展于'、'举办于'、'赞助自'、'主题关联至'。"+ )+ context: Optional[str] = Field(description="具体展厅、借展条件或主题子组。")++# ==============================================================================+# 2. 提示词 (Prompts)+# ==============================================================================++EXHIBITION_GRAPH_PROMPT = (+ "你是一位博物馆馆长和展览设计师。请映射艺术展览的结构图谱。\n\n"+ "准则:\n"+ "- 识别展览名称、核心主题以及参展的艺术家和作品。\n"+ "- 将作品连接到其所属的主题板块以及负责的策展人。\n"+ "- 捕捉场馆和赞助商等物流信息。"+)++EXHIBITION_NODE_PROMPT = (+ "提取展览组件:展览名称、场馆、主题、具体艺术品以及关键人员(策展人、设计师)。"+)++EXHIBITION_EDGE_PROMPT = (+ "连接展览内的各项内容。展示哪些作品属于哪个主题,并识别举办场馆和赞助商。"+)++# ==============================================================================+# 3. 模板类+# ==============================================================================++class ExhibitionGraph(AutoGraph[ExhibitionEntity, ExhibitionRelation]):+ """+ 展览策划图谱模板,用于策划筹备和展览分析。++ 追踪艺术品、主题、策展人和场馆之间的关系。++ 示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI()+ >>> embedder = OpenAIEmbeddings()+ >>> graph = ExhibitionGraph(llm_client=llm, embedder=embedder)+ >>> text = "'超现实之梦'展览由 Alice Smith 在泰特现代美术馆策划。"+ >>> graph.feed_text(text)+ >>> print(graph.edges) # 展览关联信息+ """+ 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+ ):+ """+ 初始化展览策划图谱模板。++ Args:+ llm_client: 语言模型客户端。+ embedder: 嵌入模型。+ extraction_mode: 提取模式,"one_stage" 或 "two_stage"。+ chunk_size: 分块大小。+ chunk_overlap: 分块重叠大小。+ max_workers: 最大并行工作线程数。+ verbose: 是否开启详细日志。+ **kwargs: 传递给 AutoGraph 的额外参数。+ """+ super().__init__(+ node_schema=ExhibitionEntity,+ edge_schema=ExhibitionRelation,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation_type.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=EXHIBITION_GRAPH_PROMPT,+ prompt_for_node_extraction=EXHIBITION_NODE_PROMPT,+ prompt_for_edge_extraction=EXHIBITION_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/art/movement.py b/hyperextract/templates/zh/art/movement.pynew file mode 100644index 0000000..bd00990--- /dev/null+++ b/hyperextract/templates/zh/art/movement.py@@ -0,0 +1,109 @@+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.graphs import AutoGraph++# ==============================================================================+# 1. 模式定义 (Schema)+# ==============================================================================++class MovementEntity(BaseModel):+ """艺术流派、风格、艺术家或具有影响力的作品。"""+ name: str = Field(description="流派名称(如:印象派)或艺术家姓名。")+ category: str = Field(+ description="类别:'流派'、'风格'、'艺术家'、'宣言'、'代表作'。"+ )+ attributes: Optional[str] = Field(description="核心特征、常用媒介或流行时期。")++class ArtInfluenceEdge(BaseModel):+ """艺术史中的影响、衍生或成员关系。"""+ source: str = Field(description="前驱流派 or 影响源。")+ target: str = Field(description="后继流派、具体作品或艺术家。")+ relation: str = Field(+ description="关系:'影响了'、'创始人'、'成员'、'是对...的反叛'、'衍生自'。"+ )+ details: Optional[str] = Field(description="具体的风格技巧传承或历史事件。")++# ==============================================================================+# 2. 提示词 (Prompts)+# ==============================================================================++MOVEMENT_GRAPH_PROMPT = (+ "你是一位专门研究艺术风格演变的艺术史学家。请提取艺术流派及其相互影响的图谱。\n\n"+ "准则:\n"+ "- 识别不同的艺术流派以及与之相关的艺术家。\n"+ "- 映射流派之间的演进关系(例如:后印象派对印象派的反思与继承)。\n"+ "- 捕捉宣言或作品中定义的各种核心哲学和视觉特征。"+)++MOVEMENT_NODE_PROMPT = (+ "提取艺术流派、风格、相关艺术家及关键作品。描述其视觉语言和核心理论。"+)++MOVEMENT_EDGE_PROMPT = (+ "定义流派与个人之间的联系。使用诸如'是对...的反叛'或'影响了'等关系词。记录代际之间传递的具体技法。"+)++# ==============================================================================+# 3. 模板类+# ==============================================================================++class ArtMovementGraph(AutoGraph[MovementEntity, ArtInfluenceEdge]):+ """+ 艺术流派图谱模板,用于映射艺术风格、流派影响力和艺术家所属流派。++ 适用于教学应用和艺术史深度分析。++ 示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI()+ >>> embedder = OpenAIEmbeddings()+ >>> graph = ArtMovementGraph(llm_client=llm, embedder=embedder)+ >>> text = "以莫奈为首的印象派,后来受到了后印象派结构化方法的挑战。"+ >>> graph.feed_text(text)+ >>> print(graph.nodes) # 流派与艺术家详情+ """+ 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+ ):+ """+ 初始化艺术流派图谱模板。++ Args:+ llm_client: 语言模型客户端。+ embedder: 嵌入模型。+ extraction_mode: 提取模式,"one_stage" 或 "two_stage"。+ chunk_size: 分块大小。+ chunk_overlap: 分块重叠大小。+ max_workers: 最大并行工作线程数。+ verbose: 是否开启详细日志。+ **kwargs: 传递给 AutoGraph 的额外参数。+ """+ super().__init__(+ node_schema=MovementEntity,+ edge_schema=ArtInfluenceEdge,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=MOVEMENT_GRAPH_PROMPT,+ prompt_for_node_extraction=MOVEMENT_NODE_PROMPT,+ prompt_for_edge_extraction=MOVEMENT_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/art/provenance.py b/hyperextract/templates/zh/art/provenance.pynew file mode 100644index 0000000..542d710--- /dev/null+++ b/hyperextract/templates/zh/art/provenance.py@@ -0,0 +1,109 @@+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.graphs import AutoGraph++# ==============================================================================+# 1. 模式定义 (Schema)+# ==============================================================================++class ArtEntity(BaseModel):+ """艺术领域实体(如:作品、艺术家、博物馆、私人收藏家、拍卖行)。"""+ name: str = Field(description="艺术品名称、人物姓名或机构名称。")+ category: str = Field(+ description="类别:'艺术品'、'艺术家'、'收藏家'、'机构'、'地理位置'。"+ )+ description: Optional[str] = Field(description="材质、创作日期或历史地位描述。")++class ProvenanceEdge(BaseModel):+ """艺术品的所有权或流转记录。"""+ source: str = Field(description="原持有者或起始地点。")+ target: str = Field(description="新持有者或目的地。")+ transfer_type: str = Field(+ description="流转类型:'收购自'、'出售给'、'捐赠予'、'借展给'、'委托'。"+ )+ specification: Optional[str] = Field(description="流转日期、成交价格或拍卖详情。")++# ==============================================================================+# 2. 提示词 (Prompts)+# ==============================================================================++PROVENANCE_GRAPH_PROMPT = (+ "你是一位资深的艺术史学家和流传考证专家。请提取艺术品的流传历程图谱。\n\n"+ "准则:\n"+ "- 识别核心艺术品及其所有历史持有者(私人收藏家、博物馆、王室)。\n"+ "- 按照时间顺序映射所有权转移(出售、继承、掠夺、捐赠)。\n"+ "- 捕捉提到的具体日期、成交价格及传承细节。"+)++PROVENANCE_NODE_PROMPT = (+ "提取艺术实体:识别作品、艺术家、收藏家、博物馆和拍卖行。标注作品的材质及相关人物/机构的角色。"+)++PROVENANCE_EDGE_PROMPT = (+ "构建传承链条。将前任所有者与现任所有者联系起来,标注流转类型(如'捐赠予')。包含流转的时间段和交易详情。"+)++# ==============================================================================+# 3. 模板类+# ==============================================================================++class ProvenanceGraph(AutoGraph[ArtEntity, ProvenanceEdge]):+ """+ 艺术品流传图谱模板,用于追踪艺术品和文物的历史所有权。++ 适用于艺术品鉴定、馆藏档案管理和历史研究。++ 示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> graph = ProvenanceGraph(llm_client=llm, embedder=embedder)+ >>> text = "该画作于1815年由卢浮宫从博尔盖塞收藏中购得。"+ >>> graph.feed_text(text)+ >>> print(graph.edges) # 提取的作品所有权转移记录+ """+ 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+ ):+ """+ 初始化艺术品流传图谱模板。++ Args:+ llm_client: 语言模型客户端。+ embedder: 嵌入模型。+ extraction_mode: 提取模式,"one_stage" 或 "two_stage"。+ chunk_size: 分块大小。+ chunk_overlap: 分块重叠大小。+ max_workers: 最大并行工作线程数。+ verbose: 是否开启详细日志。+ **kwargs: 传递给 AutoGraph 的额外参数。+ """+ super().__init__(+ node_schema=ArtEntity,+ edge_schema=ProvenanceEdge,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.transfer_type.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=PROVENANCE_GRAPH_PROMPT,+ prompt_for_node_extraction=PROVENANCE_NODE_PROMPT,+ prompt_for_edge_extraction=PROVENANCE_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/automotive/__init__.py b/hyperextract/templates/zh/automotive/__init__.pyindex e69de29..0184d1b 100644--- a/hyperextract/templates/zh/automotive/__init__.py+++ b/hyperextract/templates/zh/automotive/__init__.py@@ -0,0 +1,9 @@+from .car_spec import CarSpecGraph+from .maintenance import CarMaintenanceGraph+from .manufacturing import AutomotiveMfgGraph++__all__ = [+ "CarSpecGraph",+ "CarMaintenanceGraph",+ "AutomotiveMfgGraph",+]diff --git a/hyperextract/templates/zh/automotive/car_spec.py b/hyperextract/templates/zh/automotive/car_spec.pynew file mode 100644index 0000000..34b18a3--- /dev/null+++ b/hyperextract/templates/zh/automotive/car_spec.py@@ -0,0 +1,109 @@+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.graphs import AutoGraph++# ==============================================================================+# 1. 模式定义 (Schema)+# ==============================================================================++class CarComponent(BaseModel):+ """车辆组件或参数类别(发动机、电池、自动驾驶、传动系统)。"""+ name: str = Field(description="车型名称或具体组件名称。")+ category: str = Field(+ description="类别:'车型'、'动力系统'、'底盘'、'安全系统'、'信息娱乐'。"+ )+ specification: Optional[str] = Field(description="详细参数(如:马力、电量、版本)。")++class CarSystemRelation(BaseModel):+ """汽车系统间的层级或技术关系。"""+ source: str = Field(description="父系统或车辆型号。")+ target: str = Field(description="子组件或功能。")+ relation_type: str = Field(+ description="类型:'配备'、'动力源自'、'集成'、'兼容'。"+ )+ performance_note: Optional[str] = Field(description="性能指标或集成细节。")++# ==============================================================================+# 2. 提示词 (Prompts)+# ==============================================================================++CAR_SPEC_GRAPH_PROMPT = (+ "你是一位汽车工程师和技术评论员。请提取车辆的技术参数图谱。\n\n"+ "准则:\n"+ "- 识别车型及其核心系统(发动机、电机、电池、支驾系统)。\n"+ "- 映射组件层级关系(例如:电池包含电芯,发动机使用涡轮增压器)。\n"+ "- 捕捉可量化的参数,如 0-100km/h 加速、续航里程、峰值功率和扭矩。"+)++CAR_SPEC_NODE_PROMPT = (+ "提取车型和技术组件。重点关注名称及其可测量的参数指标(如:500马力、80kWh)。"+)++CAR_SPEC_EDGE_PROMPT = (+ "定义技术依赖关系。展示哪些组件属于哪个汽车系统。使用诸如'动力源自'或'配备'等关系。"+)++# ==============================================================================+# 3. 模板类+# ==============================================================================++class CarSpecGraph(AutoGraph[CarComponent, CarSystemRelation]):+ """+ 汽车参数图谱模板,用于提取车辆技术数据和参数层级。++ 适用于竞品分析、汽车垂直媒体和技术文档处理。++ 示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI()+ >>> embedder = OpenAIEmbeddings()+ >>> graph = CarSpecGraph(llm_client=llm, embedder=embedder)+ >>> text = "特斯拉 Model 3 高性能版采用双电机全轮驱动,可输出 510 马力。"+ >>> graph.feed_text(text)+ >>> print(graph.nodes) # 车辆及其组件参数+ """+ 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+ ):+ """+ 初始化汽车参数图谱模板。++ Args:+ llm_client: 语言模型客户端。+ embedder: 嵌入模型。+ extraction_mode: 提取模式,"one_stage" 或 "two_stage"。+ chunk_size: 分块大小。+ chunk_overlap: 分块重叠大小。+ max_workers: 最大并行工作线程数。+ verbose: 是否开启详细日志。+ **kwargs: 传递给 AutoGraph 的额外参数。+ """+ super().__init__(+ node_schema=CarComponent,+ edge_schema=CarSystemRelation,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation_type.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=CAR_SPEC_GRAPH_PROMPT,+ prompt_for_node_extraction=CAR_SPEC_NODE_PROMPT,+ prompt_for_edge_extraction=CAR_SPEC_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/automotive/maintenance.py b/hyperextract/templates/zh/automotive/maintenance.pynew file mode 100644index 0000000..ae1fb0f--- /dev/null+++ b/hyperextract/templates/zh/automotive/maintenance.py@@ -0,0 +1,105 @@+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.graphs import AutoGraph++# ==============================================================================+# 1. 模式定义 (Schema)+# ==============================================================================++class MaintenanceItem(BaseModel):+ """保养项目或车辆零部件(机油、刹车片、正时皮带)。"""+ item_name: str = Field(description="零部件名称或保养服务名称。")+ category: str = Field(description="类别:'油液'、'易损件'、'检查项'、'软件更新'。")+ interval: Optional[str] = Field(description="建议的里程或时间间隔(如:5,000公里)。")++class MaintenanceSequence(BaseModel):+ """保养行动的依赖或序列关系。"""+ source: str = Field(description="触发保养的部件或初始状态。")+ target: str = Field(description="保养任务或更换的零部件。")+ action: str = Field(description="动作:'更换'、'检查'、'清洗'、'校准'。")+ precaution: Optional[str] = Field(description="安全警告或所需工具。")++# ==============================================================================+# 2. 提示词 (Prompts)+# ==============================================================================++MAINTENANCE_GRAPH_PROMPT = (+ "你是一位资深技师和售后顾问。请提取车辆保养与维修图谱。\n\n"+ "准则:\n"+ "- 识别手册或日志中提到的具体保养项目和零部件。\n"+ "- 映射触发保养的条件(如:里程、报警灯、视觉检查结果)。\n"+ "- 将零部件连接到对应的系统及所需的维保动作。"+)++MAINTENANCE_NODE_PROMPT = (+ "提取保养任务、零部件和油液类型。如果指定了建议间隔,请一并记录。"+)++MAINTENANCE_EDGE_PROMPT = (+ "将触发条件与动作联系起来。展示哪些部件需要更换或检查。记录每项任务的具体注意事项。"+)++# ==============================================================================+# 3. 模板类+# ==============================================================================++class CarMaintenanceGraph(AutoGraph[MaintenanceItem, MaintenanceSequence]):+ """+ 汽车保养图谱模板,用于处理车辆服务手册、维修指南和保养日志。++ 有助于整理维保计划和零部件兼容性信息。++ 示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI()+ >>> embedder = OpenAIEmbeddings()+ >>> graph = CarMaintenanceGraph(llm_client=llm, embedder=embedder)+ >>> text = "每10,000公里更换发动机机油和机滤,使用 0W-20 全合成机油。"+ >>> graph.feed_text(text)+ >>> print(graph.nodes) # 保养项目详情+ """+ 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+ ):+ """+ 初始化汽车保养图谱模板。++ Args:+ llm_client: 语言模型客户端。+ embedder: 嵌入模型。+ extraction_mode: 提取模式,"one_stage" 或 "two_stage"。+ chunk_size: 分块大小。+ chunk_overlap: 分块重叠大小。+ max_workers: 最大并行工作线程数。+ verbose: 是否开启详细日志。+ **kwargs: 传递给 AutoGraph 的额外参数。+ """+ super().__init__(+ node_schema=MaintenanceItem,+ edge_schema=MaintenanceSequence,+ node_key_extractor=lambda x: x.item_name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.action.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=MAINTENANCE_GRAPH_PROMPT,+ prompt_for_node_extraction=MAINTENANCE_NODE_PROMPT,+ prompt_for_edge_extraction=MAINTENANCE_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/automotive/manufacturing.py b/hyperextract/templates/zh/automotive/manufacturing.pynew file mode 100644index 0000000..38bf846--- /dev/null+++ b/hyperextract/templates/zh/automotive/manufacturing.py@@ -0,0 +1,109 @@+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.graphs import AutoGraph++# ==============================================================================+# 1. 模式定义 (Schema)+# ==============================================================================++class ManufacturingEntity(BaseModel):+ """汽车供应链或生产线上的实体(供应商、工厂、组装环节)。"""+ name: str = Field(description="公司名称、工厂名称或生产工艺名称。")+ category: str = Field(+ description="类别:'供应商'、'工厂'、'工艺'、'原材料'、'质检'。"+ )+ specification: Optional[str] = Field(description="产能、资质认证或交付周期。")++class SupplyChainRelation(BaseModel):+ """汽车制造中参与方与环节之间的连接关系。"""+ source: str = Field(description="上游供应商或工艺环节。")+ target: str = Field(description="下游工厂或产品。")+ relation_type: str = Field(+ description="类型:'供货给'、'组装于'、'处理自'、'认证用于'。"+ )+ logistics_details: Optional[str] = Field(description="贸易术语、运输时间或供应量承诺。")++# ==============================================================================+# 2. 提示词 (Prompts)+# ==============================================================================++MFG_GRAPH_PROMPT = (+ "你是一位大型汽车制造商的供应链分析师。请提取汽车制造与供应链图谱。\n\n"+ "准则:\n"+ "- 识别各级供应商(一级、二级供应商)及其提供的零部件。\n"+ "- 映射从原材料到整车下线的组装序列。\n"+ "- 捕捉工厂的地理位置及特定的物流限制条件。"+)++MFG_NODE_PROMPT = (+ "提取供应商、制造工厂和关键生产步骤。标注它们在车辆生产周期中的角色。"+)++MFG_EDGE_PROMPT = (+ "定义物料流和工艺流。连接供应商到组装工厂,以及工厂到最终的整车交付环节。"+)++# ==============================================================================+# 3. 模板类+# ==============================================================================++class AutomotiveMfgGraph(AutoGraph[ManufacturingEntity, SupplyChainRelation]):+ """+ 汽车制造图谱模板,用于生产线流程、供应链物流和供应商管理。++ 有助于可视化全球汽车制造生态系统中的依赖关系。++ 示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI()+ >>> embedder = OpenAIEmbeddings()+ >>> graph = AutomotiveMfgGraph(llm_client=llm, embedder=embedder)+ >>> text = "宁德时代向特斯拉柏林超级工厂供应电池芯,用于 Model Y 的组装。"+ >>> graph.feed_text(text)+ >>> print(graph.edges) # 供应链流动信息+ """+ 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+ ):+ """+ 初始化汽车制造图谱模板。++ Args:+ llm_client: 语言模型客户端。+ embedder: 嵌入模型。+ extraction_mode: 提取模式,"one_stage" 或 "two_stage"。+ chunk_size: 分块大小。+ chunk_overlap: 分块重叠大小。+ max_workers: 最大并行工作线程数。+ verbose: 是否开启详细日志。+ **kwargs: 传递给 AutoGraph 的额外参数。+ """+ super().__init__(+ node_schema=ManufacturingEntity,+ edge_schema=SupplyChainRelation,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.relation_type.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=MFG_GRAPH_PROMPT,+ prompt_for_node_extraction=MFG_NODE_PROMPT,+ prompt_for_edge_extraction=MFG_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/biology/__init__.py b/hyperextract/templates/zh/biology/__init__.pyindex e69de29..74ca094 100644--- a/hyperextract/templates/zh/biology/__init__.py+++ b/hyperextract/templates/zh/biology/__init__.py@@ -0,0 +1,9 @@+from .taxonomy import TaxonomyGraph+from .network import BiologicalNetwork+from .metabolic import MetabolicHypergraph++__all__ = [+ "TaxonomyGraph",+ "BiologicalNetwork",+ "MetabolicHypergraph",+]diff --git a/hyperextract/templates/zh/biology/metabolic.py b/hyperextract/templates/zh/biology/metabolic.pynew file mode 100644index 0000000..097fc64--- /dev/null+++ b/hyperextract/templates/zh/biology/metabolic.py@@ -0,0 +1,88 @@+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.hypergraphs.base import AutoHypergraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class MetaboliteNode(BaseModel):+ """+ 代谢反应中涉及的任何物理物质(底物或产物)。+ """+ name: str = Field(description="分子的化学名或常用名(如:'丙酮酸')。")+ formula: Optional[str] = Field(None, description="化学式/表示法。")+ charge: Optional[int] = Field(None, description="代谢物的净电荷。")+ compartment: Optional[str] = Field(description="细胞定位:'细胞质'、'线粒体'、'细胞外'。")++class MetabolicReactionHyperedge(BaseModel):+ """+ 一种多试剂生化反应,其中多个底物产生多个产物。+ """+ reaction_id: str = Field(description="唯一标识符或 EC 编号(如:'EC 1.1.1.1')。")+ substrates: List[str] = Field(description="底物代谢物名称列表。")+ products: List[str] = Field(description="产物代谢物名称列表。")+ enzymes: List[str] = Field(default_factory=list, description="涉及的催化剂(酶)列表。")+ stoichiometry: Optional[str] = Field(None, description="如果文本中提到,则记录化学计量系数。")+ reversibility: bool = Field(True, description="反应是否可逆。")++# ==============================================================================+# 2. Prompts+# ==============================================================================++METABOLIC_CONSOLIDATED_PROMPT = (+ "你是一位擅长代谢工程的生物化学家。请提取复杂的 N 元反应。\n\n"+ "规则:\n"+ "- 将所有参与者(底物、产物和酶)归为一个超边(Hyperedge)。\n"+ "- 区分反应物(底物)和结果(产物)。\n"+ "- 将催化酶作为超边参与者的一部分进行捕获。"+)++METABOLIC_NODE_PROMPT = (+ "识别所有化学物质(代谢物)和酶。专注于精确的命名。"+)++METABOLIC_EDGE_PROMPT = (+ "定义代表代谢反应的超边。包含每个识别出的反应事件中所有的代谢物和酶参与者。"+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class MetabolicHypergraph(AutoHypergraph[MetaboliteNode, MetabolicReactionHyperedge]):+ """+ 用于涉及多底物/多产物反应的代谢途径的复杂超图模板。+ """+ 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+ ):+ super().__init__(+ node_schema=MetaboliteNode,+ edge_schema=MetabolicReactionHyperedge,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: x.reaction_id.strip(),+ nodes_in_edge_extractor=lambda x: tuple(set(x.substrates + x.products + x.enzymes)),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=METABOLIC_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=METABOLIC_NODE_PROMPT,+ prompt_for_edge_extraction=METABOLIC_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/biology/network.py b/hyperextract/templates/zh/biology/network.pynew file mode 100644index 0000000..a26a287--- /dev/null+++ b/hyperextract/templates/zh/biology/network.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.graphs.base import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class BioEntityNode(BaseModel):+ """+ 代表基因、蛋白质或小分子的基础生物单位。+ """+ name: str = Field(description="标准化符号或名称(如:'BRCA1'、'cAMP')。")+ category: str = Field(description="实体类型:'基因'、'蛋白质'、'RNA'、'代谢物'、'酶'、'转录因子'。")+ synonyms: Optional[str] = Field(None, description="替代名称或数据库 ID(如:UniProt、Entrez)。")+ biological_function: Optional[str] = Field(None, description="主要分子功能或细胞定位。")++class BioInteractionEdge(BaseModel):+ """+ 两个生物实体之间直接的物理或功能相互作用。+ """+ source: str = Field(description="上游或施加动作的实体。")+ target: str = Field(description="下游或接受动作的实体。")+ interaction_type: str = Field(description="类型:'磷酸化'、'抑制'、'激活'、'结合'、'调节'、'切割'。")+ mechanism: Optional[str] = Field(None, description="具体的生化机制(如:'别构抑制')。")+ strength: Optional[str] = Field(None, description="置信度评分或结合亲和力(如果可用)。")++# ==============================================================================+# 2. Prompts+# ==============================================================================++NETWORK_CONSOLIDATED_PROMPT = (+ "你是一位擅长分子信号转导和调节网络的生物信息学专家。"+ "请从文本中提取相互作用,以构建生物网络图。\n\n"+ "规则:\n"+ "- 区分不同的分子类型(如蛋白质与基因)。\n"+ "- 识别有向相互作用(例如:酶 A 磷酸化蛋白质 B)。\n"+ "- 捕捉每条边具体的生化机制。"+)++NETWORK_NODE_PROMPT = (+ "识别提及的所有基因、蛋白质和分子。尽可能将名称规范化为标准符号。"+ "忽略诸如 '该蛋白质' 或 '此分子' 之类的泛指词,除非它们指向特定的具名实体。"+)++NETWORK_EDGE_PROMPT = (+ "提取已识别生物实体之间的功能性和物理性相互作用。"+ "定义相互作用的方向和性质(激活、抑制等)。"+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class BiologicalNetwork(AutoGraph[BioEntityNode, BioInteractionEdge]):+ """+ 用于建模分子信号、二元代谢途径和调节网络的模板。+ """+ 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+ ):+ super().__init__(+ node_schema=BioEntityNode,+ edge_schema=BioInteractionEdge,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.interaction_type.lower()})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=NETWORK_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=NETWORK_NODE_PROMPT,+ prompt_for_edge_extraction=NETWORK_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/biology/taxonomy.py b/hyperextract/templates/zh/biology/taxonomy.pynew file mode 100644index 0000000..20a6930--- /dev/null+++ b/hyperextract/templates/zh/biology/taxonomy.py@@ -0,0 +1,88 @@+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.graphs.base import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class TaxonNode(BaseModel):+ """+ 表示生命之树中的生物分类单元。+ """+ name: str = Field(description="生物体或群体的学名(拉丁语)或标准俗名。")+ rank: str = Field(description="分类等级:'域'、'界'、'门'、'纲'、'目'、'科'、'属'、'种'。")+ common_name: Optional[str] = Field(None, description="在非科学背景下使用的通用名称。")+ description: Optional[str] = Field(None, description="简要的生物特征、栖息地或区别性性状。")++class TaxonomyRelation(BaseModel):+ """+ 两个分类单元之间直接的层级关系。+ """+ source: str = Field(description="父级分类单元(如:'哺乳纲')。")+ target: str = Field(description="子级分类单元(如:'灵长目')。")+ type: str = Field("parent_of", description="关系类型:'parent_of'(父级)、'subspecies_of'(亚种)、'classified_under'(归类于)。")+ evidence: Optional[str] = Field(None, description="证明该分类合理的表型或基因组数据引用。")++# ==============================================================================+# 2. Prompts+# ==============================================================================++TAXONOMY_CONSOLIDATED_PROMPT = (+ "你是一位专业的分类学家和系统生物学家。请从文本中提取生物层级(分类学)信息。\n\n"+ "规则:\n"+ "- 识别所有分类阶元(从界到种)及其特定的等级。\n"+ "- 使用 'parent_of' 关系构建严格的树状层级。\n"+ "- 捕捉可用的学名和常用名。"+)++TAXONOMY_NODE_PROMPT = (+ "提取所有生物分类群(节点)。识别它们的等级(例如:科:人科)。"+ "专注于正式分类,排除临时或非标准的分类。"+)++TAXONOMY_EDGE_PROMPT = (+ "映射所提供的分类单元的谱系。创建反映系统发育演化或分类树的边。"+ "确保源节点的等级高于或等于目标节点的等级。"+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class TaxonomyGraph(AutoGraph[TaxonNode, TaxonomyRelation]):+ """+ 生物分类和系统发育层级的高精度提取模板。+ """+ 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+ ):+ super().__init__(+ node_schema=TaxonNode,+ edge_schema=TaxonomyRelation,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.type})-->{x.target.strip()}",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=TAXONOMY_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=TAXONOMY_NODE_PROMPT,+ prompt_for_edge_extraction=TAXONOMY_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/business/__init__.py b/hyperextract/templates/zh/business/__init__.pyindex e69de29..8da251c 100644--- a/hyperextract/templates/zh/business/__init__.py+++ b/hyperextract/templates/zh/business/__init__.py@@ -0,0 +1,9 @@+from .equity import EquityStructureGraph+from .strategy import StrategicChainGraph+from .ecosystem import MarketEcosystemHyper++__all__ = [+ "EquityStructureGraph",+ "StrategicChainGraph",+ "MarketEcosystemHyper",+]diff --git a/hyperextract/templates/zh/business/ecosystem.py b/hyperextract/templates/zh/business/ecosystem.pynew file mode 100644index 0000000..b92f7b4--- /dev/null+++ b/hyperextract/templates/zh/business/ecosystem.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.hypergraphs.base import AutoHypergraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class IndustryParticipant(BaseModel):+ """+ 产业生态系统中的实体(公司、监管机构、非政府组织)。+ """+ name: str = Field(description="参与者名称(如:'台积电'、'欧盟委员会')。")+ rank: Optional[str] = Field(None, description="市场地位:'一级供应商'、'市场领导者'、'挑战者'。")+ technological_focus: Optional[str] = Field(None, description="主要技术或领域(如:'5G'、'光刻技术')。")++class CollectiveAlliance(BaseModel):+ """+ 代表财团、联盟、市场卡特尔或联合标准制定机构的超边。+ """+ alliance_id: str = Field(description="联盟的名称或标识符(如:'芯片联盟')。")+ participants: List[str] = Field(description="在该团体中进行合作或竞争的所有实体的名称列表。")+ shared_goal: str = Field(description="目标:'标准化'、'反垄断审查'、'联合研发'。")+ governance: Optional[str] = Field(None, description="参与原则或领导实体。")++# ==============================================================================+# 2. Prompts+# ==============================================================================++ECOSYSTEM_CONSOLIDATED_PROMPT = (+ "你是一位市场战略家和反垄断专家。请提取市场生态系统的动态。\n\n"+ "规则:\n"+ "- 使用超边(Hyperedges)将参与合资企业或联盟的多个实体(3个或更多)联系起来。\n"+ "- 捕获非二元的群体关系,如卡特尔、产业集群和监管联盟。\n"+ "- 清晰地定义这些群体的共同目标。"+)++ECOSYSTEM_NODE_PROMPT = (+ "识别生态系统中的所有业务和监管参与者。记录它们的市场地位核心技术重点。"+)++ECOSYSTEM_EDGE_PROMPT = (+ "提取集体联盟。将参与实体分组为集群(超边)。专注于财团、标准制定机构和联合市场行动。"+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class MarketEcosystemHyper(AutoHypergraph[IndustryParticipant, CollectiveAlliance]):+ """+ 用于产业集群、生态系统联盟和复杂市场协同的超图模板。+ """+ 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+ ):+ super().__init__(+ node_schema=IndustryParticipant,+ edge_schema=CollectiveAlliance,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: x.alliance_id.strip(),+ nodes_in_edge_extractor=lambda x: tuple(x.participants),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=ECOSYSTEM_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=ECOSYSTEM_NODE_PROMPT,+ prompt_for_edge_extraction=ECOSYSTEM_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/business/equity.py b/hyperextract/templates/zh/business/equity.pynew file mode 100644index 0000000..a0b7f24--- /dev/null+++ b/hyperextract/templates/zh/business/equity.py@@ -0,0 +1,87 @@+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.graphs.base import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class StakeholderNode(BaseModel):+ """+ 在业务中持有股份或拥有控制权的法人或自然人。+ """+ name: str = Field(description="公司注册全称或个人全名。")+ type: str = Field(description="类型:'自然人'、'上市公司'、'私有公司'、'国有企业'、'风险投资'。")+ jurisdiction: Optional[str] = Field(None, description="注册地或居住地所属的国家或地区。")+ is_ubo: bool = Field(False, description="该实体是否被识别为最终受益人(UBO)。")++class OwnershipRelation(BaseModel):+ """+ 两个实体之间的持股或控制联系。+ """+ source: str = Field(description="股东或母公司实体。")+ target: str = Field(description="被拥有或控制的公司(子公司)。")+ stake_percentage: Optional[float] = Field(None, description="持股比例(0.0 到 100.0)。")+ control_type: str = Field("Equity", description="联系性质:'股权收购'、'投票权'、'代持股份'、'直接控制'。")+ as_of_date: Optional[str] = Field(None, description="记录该所有权的时间点或财务周期。")++# ==============================================================================+# 2. Prompts+# ==============================================================================++EQUITY_CONSOLIDATED_PROMPT = (+ "你是一位企业法务助理和财务分析师。请提取复杂的股权结构。\n\n"+ "规则:\n"+ "- 优先识别每个实体持有的股份比例。\n"+ "- 区分直接股东和最终受益人(UBO)。\n"+ "- 映射从母公司到最小子公司的层级结构。"+)++EQUITY_NODE_PROMPT = (+ "在股权背景下提取提及的所有公司、投资基金和个人。将他们分类为 '自然人'、'私有公司' 等。"+)++EQUITY_EDGE_PROMPT = (+ "构建所有权边。捕获股权比例和特定的控制类型。识别从股东到目标实体的资金或控制流向。"+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class EquityStructureGraph(AutoGraph[StakeholderNode, OwnershipRelation]):+ """+ 用于企业登记、并购分析及 KYC/UBO 追踪的高精度模板。+ """+ 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+ ):+ super().__init__(+ node_schema=StakeholderNode,+ edge_schema=OwnershipRelation,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}->{x.target.strip()}_at_{x.stake_percentage}%",+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=EQUITY_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=EQUITY_NODE_PROMPT,+ prompt_for_edge_extraction=EQUITY_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/business/strategy.py b/hyperextract/templates/zh/business/strategy.pynew file mode 100644index 0000000..4df6bdd--- /dev/null+++ b/hyperextract/templates/zh/business/strategy.py@@ -0,0 +1,89 @@+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.graphs.temporal_graph import AutoTemporalGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class StrategicNode(BaseModel):+ """+ 组织实体、业务部门或战略目标。+ """+ name: str = Field(description="战略单元或目标的名称(如:'Azure'、'碳中和')。")+ scope: str = Field(description="范围:'全球'、'区域'、'特定产品'、'集团层面'。")+ importance: Optional[str] = Field(None, description="重要性:'核心业务'、'新兴市场'、'传统存量'。")++class StrategicPivot(BaseModel):+ """+ 代表战略重点转移、投资或剥离的时间性转变。+ """+ source: str = Field(description="原始关注领域或施加动作的实体。")+ target: str = Field(description="新的目标、方向或目的。")+ action: str = Field(description="战略动作:'转型为'、'收购'、'剥离'、'合并'、'关停'、'规模化'。")+ timestamp: str = Field(description="转型发生的时间(如:'2022年第四季度'、'2025-01-01')。")+ rationale: Optional[str] = Field(None, description="举措背后的原因(市场压力、CEO 变动、技术变革)。")+ budget: Optional[str] = Field(None, description="与转型相关的财务承诺或预算。")++# ==============================================================================+# 2. Prompts+# ==============================================================================++STRATEGY_CONSOLIDATED_PROMPT = (+ "你是一位管理顾问和行业分析师。请提取公司战略的演变过程。\n\n"+ "规则:\n"+ "- 专注于 '转型(Pivots)':从一个业务领域向另一个业务领域的转移。\n"+ "- 将特定动作与具体时间戳联系起来。\n"+ "- 捕获每次战略变革背后的深层原因(rationale)。"+)++STRATEGY_NODE_PROMPT = (+ "提取业务部门、产品线和高层公司目标。识别它们的组织重要性。"+)++STRATEGY_EDGE_PROMPT = (+ "映射随时间推移的战略转变。确保 'timestamp' 被解析为具体时段。"+ "识别公司从什么(source)转向了什么(target)。"+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class StrategicChainGraph(AutoTemporalGraph[StrategicNode, StrategicPivot]):+ """+ 用于追踪公司战略、长期组织变革和市场表现的时序模板。+ """+ 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+ ):+ super().__init__(+ node_schema=StrategicNode,+ edge_schema=StrategicPivot,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}-({x.action})->{x.target.strip()}",+ time_in_edge_extractor=lambda x: x.timestamp.strip(),+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=STRATEGY_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=STRATEGY_NODE_PROMPT,+ prompt_for_edge_extraction=STRATEGY_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/chemistry/__init__.py b/hyperextract/templates/zh/chemistry/__init__.pyindex e69de29..eb82d62 100644--- a/hyperextract/templates/zh/chemistry/__init__.py+++ b/hyperextract/templates/zh/chemistry/__init__.py@@ -0,0 +1,9 @@+from .molecular import MolecularStructureGraph+from .reaction import ChemicalReactionHyper+from .protocol import LabProtocolTemporal++__all__ = [+ "MolecularStructureGraph",+ "ChemicalReactionHyper",+ "LabProtocolTemporal",+]diff --git a/hyperextract/templates/zh/chemistry/molecular.py b/hyperextract/templates/zh/chemistry/molecular.pynew file mode 100644index 0000000..ddeeb53--- /dev/null+++ b/hyperextract/templates/zh/chemistry/molecular.py@@ -0,0 +1,88 @@+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.graphs.spatial_graph import AutoSpatialGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class AtomNode(BaseModel):+ """+ 化学结构中的单个原子。+ """+ name: str = Field(description="原子标识符(如:'C1'、'O2')或元素符号。")+ element: str = Field(description="化学元素(如:'碳'、'H')。")+ hybridization: Optional[str] = Field(None, description="电子状态:'sp3'、'sp2'、'sp'。")+ formal_charge: int = Field(0, description="分配给原子的形式电荷。")++class ChemicalBond(BaseModel):+ """+ 两个原子之间的化学键,包括空间/位置元数据。+ """+ source: str = Field(description="起始原子(如:'C1')。")+ target: str = Field(description="连接原子(如:'C2')。")+ bond_type: str = Field(description="类型:'单键'、'双键'、'三键'、'芳香键'、'氢键'。")+ spatial_position: str = Field(description="在分子中的物理或逻辑位置(如:'C4位'、'轴向'、'赤道向')。")+ bond_length: Optional[float] = Field(None, description="原子间的距离(单位:埃)。")++# ==============================================================================+# 2. Prompts+# ==============================================================================++MOLECULAR_CONSOLIDATED_PROMPT = (+ "你是一位计算化学家和晶体学家。请提取 3D 分子拓扑结构。\n\n"+ "规则:\n"+ "- 将每个原子识别为一个节点。\n"+ "- 定义化学键,包括它们的特定空间取向(例如:'Alpha'、'Beta'、'顺式'、'反式')。\n"+ "- 捕获每个原子的形式电荷和杂化轨道。"+)++MOLECULAR_NODE_PROMPT = (+ "提取所有单个原子。记录它们的元素类型和电子杂化状态。"+)++MOLECULAR_EDGE_PROMPT = (+ "映射原子间的连接性(化学键)。特别识别分子框架内发生连接的空间位置。"+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class MolecularStructureGraph(AutoSpatialGraph[AtomNode, ChemicalBond]):+ """+ 用于高分辨率分子建模和结构生物学的空间图模板。+ """+ 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+ ):+ super().__init__(+ node_schema=AtomNode,+ edge_schema=ChemicalBond,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: f"{x.source.strip()}--({x.bond_type})-->{x.target.strip()}",+ location_in_edge_extractor=lambda x: x.spatial_position.strip(),+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=MOLECULAR_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=MOLECULAR_NODE_PROMPT,+ prompt_for_edge_extraction=MOLECULAR_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/chemistry/protocol.py b/hyperextract/templates/zh/chemistry/protocol.pynew file mode 100644index 0000000..5cb4ff9--- /dev/null+++ b/hyperextract/templates/zh/chemistry/protocol.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.graphs.temporal_graph import AutoTemporalGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class LabOperation(BaseModel):+ """+ 化学或生物实验方案中的具体步骤或动作(如:'离心'、'滴定')。+ """+ op_id: str = Field(description="动作名称(如:'离心'、'加热'、'加入')。")+ equipment: Optional[str] = Field(None, description="使用的设备(如:'微量离心机'、'本生灯')。")+ reagents_added: List[str] = Field(default_factory=list, description="此具体步骤中引入的化学物质。")+ precautions: Optional[str] = Field(None, description="安全或准确性警告(如:'在冰上操作')。")++class ProtocolTransition(BaseModel):+ """+ 实验步骤之间的顺序转换,捕获持续时间和顺序。+ """+ transition_id: str = Field(description="步骤转换的唯一标识符。")+ source_step: str = Field(description="前序操作。")+ target_step: str = Field(description="后续操作。")+ duration: Optional[str] = Field(None, description="步骤内或步骤间的耗时(如:'15 分钟'、'过夜')。")+ timestamp: str = Field(description="顺序编号或相对时间标记(如:'T+0'、'步骤 2')。")+ wait_condition: Optional[str] = Field(None, description="继续操作的条件(如:'直到形成沉淀')。")++# ==============================================================================+# 2. Prompts+# ==============================================================================++PROTOCOL_CONSOLIDATED_PROMPT = (+ "你是一位擅长实验方案记录的实验室技术员。请提取顺序性的实验步骤。\n\n"+ "规则:\n"+ "- 将每个操作表示为一个节点(Node)。\n"+ "- 将操作之间的顺序和持续时间表示为时间边(Temporal Edges)。\n"+ "- 捕获与每个步骤相关的特定试剂/设备。\n"+ "- 精确映射时间线(例如:'步骤 1' -> '步骤 2')。"+)++PROTOCOL_NODE_PROMPT = (+ "识别具体的实验室操作、动作以及每个环节使用的设备/试剂。"+)++PROTOCOL_EDGE_PROMPT = (+ "跟踪这些操作之间的按时间顺序的流向。识别步骤转换之间经过的时间或所需的条件。"+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class LabProtocolTemporal(AutoTemporalGraph[LabOperation, ProtocolTransition]):+ """+ 用于捕获逐步实验室程序和实验工作流的时间图模板。+ """+ 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+ ):+ super().__init__(+ node_schema=LabOperation,+ edge_schema=ProtocolTransition,+ node_key_extractor=lambda x: x.op_id.strip(),+ edge_key_extractor=lambda x: x.transition_id.strip(),+ nodes_in_edge_extractor=lambda x: (x.source_step.strip(), x.target_step.strip()),+ time_in_edge_extractor=lambda x: x.timestamp.strip(),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=PROTOCOL_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=PROTOCOL_NODE_PROMPT,+ prompt_for_edge_extraction=PROTOCOL_EDGE_PROMPT,+ **kwargs+ )diff --git a/hyperextract/templates/zh/chemistry/reaction.py b/hyperextract/templates/zh/chemistry/reaction.pynew file mode 100644index 0000000..5bb3809--- /dev/null+++ b/hyperextract/templates/zh/chemistry/reaction.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.hypergraphs.base import AutoHypergraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================++class ChemicalEntity(BaseModel):+ """+ 一种化学物质(试剂、产物、催化剂、溶剂)。+ """+ name: str = Field(description="IUPAC 名称或常用名称(如:'硫酸')。")+ formula: Optional[str] = Field(None, description="化学式(如:'H2SO4')。")+ cas_number: Optional[str] = Field(None, description="CAS 登记号。")+ phase: str = Field("Unknown", description="物理状态:'气态'、'液态'、'固态'、'水溶液'。")++class ReactionEvent(BaseModel):+ """+ 涉及多种试剂、特定条件和所得产物的化学反应。+ """+ reaction_id: str = Field(description="反应的名称或简短描述(如:'哈伯制氨法')。")+ reactants: List[str] = Field(description="起始化学实体名称列表。")+ products: List[str] = Field(description="所得化学实体名称列表。")+ catalysts: List[str] = Field(default_factory=list, description="促进反应的物质名称。")+ solvents: List[str] = Field(default_factory=list, description="反应发生的介质。")+ temperature: Optional[str] = Field(None, description="操作温度(如:'250°C')。")+ pressure: Optional[str] = Field(None, description="操作压力(如:'200 atm')。")+ yield_info: Optional[str] = Field(None, description="获得的产率/产量。")++# ==============================================================================+# 2. Prompts+# ==============================================================================++REACTION_CONSOLIDATED_PROMPT = (+ "你是一位专业的有机和无机化学家。请提取多组分的反应事件。\n\n"+ "规则:\n"+ "- 将每个反应表示为一个超边(Hyperedge),连接所有反应物、产物和催化剂。\n"+ "- 捕获详细的反应条件,如温度、压力和特定溶剂。\n"+ "- 在反应语境中正确识别每个化学实体的角色。"+)++REACTION_NODE_PROMPT = (+ "识别提及的所有化学实体。查找 IUPAC 名称、化学式和 CAS 号。"+)++REACTION_EDGE_PROMPT = (+ "映射涉及这些化学物质的反应。将所有参与者归入单个反应超边中。确保清晰地区分反应物和产物。"+)++# ==============================================================================+# 3. Template Class+# ==============================================================================++class ChemicalReactionHyper(AutoHypergraph[ChemicalEntity, ReactionEvent]):+ """+ 用于复杂化学合成、工业流程和反应路径的超图模板。+ """+ 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+ ):+ super().__init__(+ node_schema=ChemicalEntity,+ edge_schema=ReactionEvent,+ node_key_extractor=lambda x: x.name.strip(),+ edge_key_extractor=lambda x: x.reaction_id.strip(),+ nodes_in_edge_extractor=lambda x: tuple(set(x.reactants + x.products + x.catalysts + x.solvents)),+ llm_client=llm_client,+ embedder=embedder,+ extraction_mode=extraction_mode,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=REACTION_CONSOLIDATED_PROMPT,+ prompt_for_node_extraction=REACTION_NODE_PROMPT,+ prompt_for_edge_extraction=REACTION_EDGE_PROMPT,+ **kwargs+ )