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 supply chain analysis, culinary dishes, flavor pairing, HACCP safety, and recipe processes
yifanfeng97e8ba55e27939
diff --git a/hyperextract/templates/INSTRUCTION.md b/hyperextract/templates/INSTRUCTION.mdindex 50efbc2..615a6e9 100644--- a/hyperextract/templates/INSTRUCTION.md+++ b/hyperextract/templates/INSTRUCTION.md@@ -11,6 +11,14 @@ Before writing any code, you MUST:## 1. Design Phase: Feasibility & Selection+### Document-First Protocol+Before designing any template, you **MUST** answer the following:+* **What is the target document?**: Which core document type(s) in this domain is the template designed for? (e.g., Annual Reports, SOP Manuals, Court Filings, HACCP Safety Plans).+* **Is the logic structure native to the text?**: Does this structure naturally exist in the original document, or is it artificially imposed? (Reject designs for "imagined knowledge structures").+* **Is extraction evidence clear?**: Are there explicit linguistic cues in the text that allow the LLM to extract accurately?++Never design templates for abstract knowledge graphs disconnected from real documents. Templates must map the **inherent logical structures** of actual text.+### The Extractability RuleBefore designing a Schema, ask yourself:* **Evidence Availability**: Does the input text explicitly contain evidence for this field? (Do not design fields for dynamic data typically found in external databases).@@ -22,7 +30,7 @@ Before designing a Schema, ask yourself:| :--- | :--- | :--- | :--- || **Single Object** (Summary/Meta) | `AutoModel` | `hyperextract/types/model.py` | One object per document || **Pattern Collection** (Repeating) | `AutoList` | `hyperextract/types/list.py` | No deduplication. Extracts all instances found. |-| **Unique Collection** (Glossary) | `AutoSet` | `hyperextract/types/set.py` | Auto-deduplication; requires `key_extractor` |+| **Key-Based Accumulator** (Glossary) | `AutoSet` | `hyperextract/types/set.py` | Information Accumulation by Exact Key; requires `key_extractor` || **Binary Graph** (Entity-Relation) | `AutoGraph` | `hyperextract/types/graph.py` | Standard binary relationships || **Temporal Graph** (Timestamps) | `AutoTemporalGraph` | `hyperextract/types/temporal_graph.py` | Edges MUST have time fields || **Spatial Graph** (Locations) | `AutoSpatialGraph` | `hyperextract/types/spatial_graph.py` | Nodes/Edges MUST have location/coords |@@ -55,7 +63,13 @@ Before designing a Schema, ask yourself:### B. Class Structure* **Schemas**: All Pydantic fields MUST include a `description` attribute. This is vital for the LLM to understand the target.* **Documentation**:- * **Class Docstring**: Must include a high-level description and a usage **Example** showing how to instantiate and use the template.+ * **Class Docstring**:+ * **Mandatory Declaration (First Line)**: At the **very beginning** of the class docstring, you **MUST** declare the **applicable document types** using this format:+ ```+ Applicable to: [List specific document types, e.g., "SEC 10-K Item 1A, Prospectus Filings"]+ ```+ * High-level functional description.+ * A usage **Example** showing how to instantiate and use the template.* **Method Docstrings**: The `__init__` and `show` methods MUST include standard Google-style docstrings with detailed `Args` descriptions for every parameter.* **Parameter Accuracy**: Verify that every argument in your `__init__` exists in the base class. Common mistake: `extraction_mode` exists in `AutoGraph` but NOT in `AutoSet`.* **Initialization**: Explicitly list parameters (`llm_client`, `embedder`, etc.) and pass the prompt to `super().__init__(..., prompt=_TEMPLATE_PROMPT, ...)`.@@ -120,3 +134,129 @@ class MyTemplate(AutoType[ItemSchema]): # Replace with actual base class (AutoLitop_k_for_chat=top_k_for_chat,)```+++---++## 4. Runtime Behavior & Usage Guide++### Automatic Extraction++After calling the `feed_text()` method, the Hyper-Extract framework will **automatically and immediately** process the text and execute knowledge extraction:++```python+template = MyTemplate(llm_client=..., embedder=...)++# 1. Input text+template.feed_text("Your input text here...")++# 2. Framework handles it automatically! No need to call extract()+# - Text automatically chunked+# - Schemas automatically extracted+# - Deduplication and relationships established automatically++# 3. Directly view results or visualize+print(template.items) # View extracted items+template.show() # Visualize knowledge graph+```++**Key Points**:+- `feed_text()` action automatically triggers the full extraction pipeline+- **No need to call `extract()` method** (this is an internal implementation detail)+- Supports method chaining: `template.feed_text(...).show()`+- Supports accumulation: multiple calls to `feed_text()` accumulate knowledge++### Custom Extraction Mode++For `AutoGraph` series templates, you can choose the extraction strategy during initialization:++```python+# One-stage: Extract nodes and edges simultaneously (faster)+template = MyGraph(llm_client=..., embedder=..., extraction_mode="one_stage")++# Two-stage: Extract nodes first, then edges (more accurate)+template = MyGraph(llm_client=..., embedder=..., extraction_mode="two_stage")+```+++---++## 4. Runtime Behavior & Usage Guide++### Automatic Extraction++After calling the `feed_text()` method, the Hyper-Extract framework will **automatically and immediately** process the text and execute knowledge extraction:++```python+template = MyTemplate(llm_client=..., embedder=...)++# 1. Input text+template.feed_text("Your input text here...")++# 2. Framework handles it automatically! No need to call extract()+# - Text automatically chunked+# - Schemas automatically extracted+# - Deduplication and relationships established automatically++# 3. Directly view results or visualize+print(template.items) # View extracted items+template.show() # Visualize knowledge graph+```++**Key Points**:+- `feed_text()` action automatically triggers the full extraction pipeline+- **No need to call `extract()` method** (this is an internal implementation detail)+- Supports method chaining: `template.feed_text(...).show()`+- Supports accumulation: multiple calls to `feed_text()` accumulate knowledge++### Custom Extraction Mode++For `AutoGraph` series templates, you can choose the extraction strategy during initialization:++```python+# One-stage: Extract nodes and edges simultaneously (faster)+template = MyGraph(llm_client=..., embedder=..., extraction_mode="one_stage")++# Two-stage: Extract nodes first, then edges (more accurate)+template = MyGraph(llm_client=..., embedder=..., extraction_mode="two_stage")+```++## 4. Runtime Behavior & Usage++### Automatic Extraction++Once the `feed_text()` method is called, the Hyper-Extract framework **automatically and immediately** processes the text and executes the knowledge extraction pipeline:++```python+template = MyTemplate(llm_client=..., embedder=...)++# 1. Input Text+template.feed_text("Your input text here...")++# 2. Framework handles extraction automatically! No need to call extract()+# - Automatic Text Chunking+# - Automatic Schema Extraction+# - Automatic Deduplication / Relation Building++# 3. View Results or Visualize+print(template.items) # Access extracted items+template.show() # Visualize the graph+```++**Key Points**:+- The `feed_text()` action automatically triggers the complete extraction pipeline.+- **Do NOT call the `extract()` method manually** (this is an internal implementation detail).+- Supports chain calling: `template.feed_text(...).show()`+- Supports accumulation: Multiple calls to `feed_text()` will accumulate knowledge.++### Custom Extraction Mode++For `AutoGraph` family templates, you can choose the extraction strategy during initialization:++```python+# One Stage: Extract Nodes and Edges simultaneously (Faster)+template = MyGraph(llm_client=..., embedder=..., extraction_mode="one_stage")++# Two Stage: Extract Nodes first, then Edges (Higher Precision)+template = MyGraph(llm_client=..., embedder=..., extraction_mode="two_stage")+```diff --git a/hyperextract/templates/INSTRUCTION_ZH.md b/hyperextract/templates/INSTRUCTION_ZH.mdindex 3a810a1..c5b7dd4 100644--- a/hyperextract/templates/INSTRUCTION_ZH.md+++ b/hyperextract/templates/INSTRUCTION_ZH.md@@ -11,6 +11,14 @@## 1. 设计阶段:可行性与选型+### 文档源优先 (Document-First Protocol)+在设计任何模板前,你**必须**明确回答以下问题:+* **目标文档是什么?**:该模板是为该领域的哪类核心文档而设计?(如年报、SOP 手册、法律判决书、食品安全计划书)。+* **文本逻辑是否原生?**:该结构是否在原始文档中自然存在,而非人为设计?(拒绝为"想当然的知识"设计结构)。+* **提取证据清晰吗?**:文本中是否有显式的线索让 LLM 能够准确提取?++绝不设计为空中楼阁的知识图谱。模板必须映射真实文本的**已有逻辑结构**。+### 可提取性原则 (Extractability)在设计 Schema 前自问:* **证据可用性**:输入文本是否显式包含该字段的证据?(拒绝为外部数据库才有的动态数据设计字段)。@@ -22,7 +30,7 @@| :--- | :--- | :--- | :--- || **单对象** (摘要/元数据) | `AutoModel` | `hyperextract/types/model.py` | 每个文档只提一个对象 || **模式集合** (重复提取) | `AutoList` | `hyperextract/types/list.py` | 不去重。提取文本中出现的所有模式实例 |-| **唯一集合** (术语/清单) | `AutoSet` | `hyperextract/types/set.py` | 自动去重,需定义 `key_extractor` |+| **键值累加器** (术语/清单) | `AutoSet` | `hyperextract/types/set.py` | 按精确键累加信息,需定义 `key_extractor` || **标准图谱** (实体-关系) | `AutoGraph` | `hyperextract/types/graph.py` | 标准二元关系 || **时序图谱** (含时间戳) | `AutoTemporalGraph` | `hyperextract/types/temporal_graph.py` | 边必须包含时间字段 || **空间关系图谱** | `AutoSpatialGraph` | `hyperextract/types/spatial_graph.py` | 节点/边需包含位置坐标信息 |@@ -55,7 +63,13 @@### B. 类结构* **Schema**:所有 Pydantic 字段必须包含 `description` 属性,这是 LLM 理解抽取目标的关键。* **文档注释 (Documentation)**:- * **类文档字符串 (Class Docstring)**:必须包含高层功能描述,以及一个展示如何初始化和使用的 **示例 (Example)**。+ * **类文档字符串 (Class Docstring)**:+ * **强制声明(第一行)**:在类文档字符串的**最开头**,你**必须**用下列格式声明该模板的**适用文档类型**:+ ```+ Applicable to: [List specific document types, e.g., "SEC 10-K Item 1A, Prospectus Filings"]+ ```+ * 高层功能描述。+ * 一个展示如何初始化和使用的 **示例 (Example)**。* **方法文档字符串 (Method Docstring)**:`__init__` 和 `show` 方法必须包含标准的 Google 风格文档字符串,详细说明每个参数 (`Args`)。* **参数准确性 (Parameter Accuracy)**:确保 `__init__` 中的每一个参数都在基类中存在。常见错误:`extraction_mode` 仅存在于 `AutoGraph` 系列中,**不存在**于 `AutoSet` 或 `AutoList` 中。* **初始化 (`__init__`)**:显式列参数(`llm_client`, `embedder` 等),并正确调用 `super().__init__(..., prompt=_TEMPLATE_PROMPT, ...)`。@@ -120,3 +134,87 @@ class MyTemplate(AutoType[ItemSchema]): # 替换为 AutoList, AutoSet 等top_k_for_chat=top_k_for_chat,)```+++---++## 4. 运行时行为与使用说明 (Runtime Behavior & Usage)++### 自动提取 (Automatic Extraction)++调用 feed_text() 方法后,Hyper-Extract 框架会**自动并立即**处理文本并执行知识抽取:++\\python+template = MyTemplate(llm_client=..., embedder=...)++# 1. 输入文本+template.feed_text('你的输入文本...')++# 2. 框架自动处理!无需显式调用 extract()+# - 文本自动分块+# - Schema 自动抽取+# - 去重/关系建立自动完成++# 3. 直接查看结果或可视化+print(template.items) # 查看提取的项目+template.show() # 可视化知识图谱+\+**关键点**:+- feed_text() 动作会自动触发完整的提取流水线+- **不需要调用 extract() 方法**(这是内部实现细节)+- 支持链式调用:template.feed_text(...).show()+- 支持累积:多次调用 feed_text() 会累加知识++### 自定义提取模式 (Custom Extraction Mode)++对于 AutoGraph 系列模板,可在初始化时选择提取策略:++\\python+# 一阶段:同时提取节点和边(速度快)+template = MyGraph(llm_client=..., embedder=..., extraction_mode='one_stage')++# 二阶段:先提取节点,再提取边(精度高)+template = MyGraph(llm_client=..., embedder=..., extraction_mode='two_stage')+\++---++## 4. 运行时行为与使用说明 (Runtime Behavior & Usage)++### 自动提取 (Automatic Extraction)++调用 `feed_text()` 方法后,Hyper-Extract 框架会**自动并立即**处理文本并执行知识抽取:++```python+template = MyTemplate(llm_client=..., embedder=...)++# 1. 输入文本+template.feed_text("你的输入文本...")++# 2. 框架自动处理!无需显式调用 extract()+# - 文本自动分块+# - Schema 自动抽取+# - 去重/关系建立自动完成++# 3. 直接查看结果或可视化+print(template.items) # 查看提取的项目+template.show() # 可视化知识图谱+```++**关键点**:+- `feed_text()` 动作会自动触发完整的提取流水线+- **不需要调用 `extract()` 方法**(这是内部实现细节)+- 支持链式调用:`template.feed_text(...).show()`+- 支持累积:多次调用 `feed_text()` 会累加知识++### 自定义提取模式 (Custom Extraction Mode)++对于 `AutoGraph` 系列模板,可在初始化时选择提取策略:++```python+# 一阶段:同时提取节点和边(速度快)+template = MyGraph(llm_client=..., embedder=..., extraction_mode="one_stage")++# 二阶段:先提取节点,再提取边(精度高)+template = MyGraph(llm_client=..., embedder=..., extraction_mode="two_stage")+```diff --git a/hyperextract/templates/en/finance/__init__.py b/hyperextract/templates/en/finance/__init__.pyindex e69de29..6fbf0ee 100644--- a/hyperextract/templates/en/finance/__init__.py+++ b/hyperextract/templates/en/finance/__init__.py@@ -0,0 +1,15 @@+"""+Finance domain templates for extracting structured knowledge from financial documents.++Includes templates for risk assessment, market sentiment, and supply chain analysis.+"""++from .risk_assessment import RiskAssessmentGraph+from .market_sentiment import MarketSentimentGraph+from .supply_chain import SupplyChainGraph++__all__ = [+ "RiskAssessmentGraph",+ "MarketSentimentGraph",+ "SupplyChainGraph",+]diff --git a/hyperextract/templates/en/finance/market_sentiment.py b/hyperextract/templates/en/finance/market_sentiment.pynew file mode 100644index 0000000..3a96e6a--- /dev/null+++ b/hyperextract/templates/en/finance/market_sentiment.py@@ -0,0 +1,201 @@+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.types import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================+++class MarketDriver(BaseModel):+ """+ A macroeconomic or company-specific factor that influences market outlook.+ """++ name: str = Field(+ description="Name of the driver (e.g., 'AI Demand', 'Interest Rate Cut', 'Regulatory Clarity')."+ )+ driver_type: str = Field(+ description="Type: 'Macro', 'Industry', 'Company-Specific', 'Catalyst'."+ )+ description: Optional[str] = Field(+ None, description="Detailed explanation of why this driver matters."+ )+++class MarketTarget(BaseModel):+ """+ A trading asset or financial metric that is influenced by market drivers.+ """++ ticker: str = Field(description="Ticker symbol (e.g., 'AAPL', 'AI Index').")+ asset_type: str = Field(+ description="Type: 'Equity', 'Index', 'Bond', 'Commodity', 'Currency'."+ )+ metric: Optional[str] = Field(+ None, description="Specific metric if applicable (e.g., 'EPS', 'P/E Ratio')."+ )+++class AnalystInfluence(BaseModel):+ """+ Represents how a market driver influences an asset's outlook.+ """++ source: str = Field(description="The market driver name.")+ target: str = Field(description="The affected asset/metric ticker.")+ sentiment: str = Field(+ description="Sentiment direction: 'Positive', 'Negative', 'Neutral'."+ )+ strength: str = Field(+ description="Influence strength: 'Strong', 'Moderate', 'Weak'."+ )+ analyst_view: str = Field(+ description="Analyst recommendation or target adjustment (e.g., 'Upgrade to Buy', 'Raise PT to $150')."+ )+ time_horizon: Optional[str] = Field(+ None, description="Expected timeline (e.g., 'FY24', '6-12 months', 'Long-term')."+ )+ source_firm: Optional[str] = Field(+ None, description="Name of the research firm or analyst source."+ )+++# ==============================================================================+# 2. Prompts+# ==============================================================================++_PROMPT = (+ "You are an equity research analyst. Extract market drivers, target assets, and analyst sentiment "+ "from research reports and macroeconomic commentary.\n\n"+ "Rules:\n"+ "- Identify market drivers (catalysts, policy changes, sector trends).\n"+ "- Identify which assets (stocks, indices, bonds) are affected.\n"+ "- Extract the sentiment direction and analyst recommendations.\n"+ "- Capture time horizons and source attributions."+)++_NODE_PROMPT = (+ "You are an equity research analyst. Extract all market drivers and target assets (Nodes) from the text.\n\n"+ "Extraction Rules:\n"+ "- Identify macroeconomic factors, policy shifts, and catalyst events.\n"+ "- Identify tickers and specific financial metrics being discussed.\n"+ "- Classify each node by type (Macro, Company-Specific, etc.).\n"+ "- DO NOT establish how drivers influence assets at this stage."+)++_EDGE_PROMPT = (+ "You are an equity research analyst. Given the list of market drivers and target assets, extract "+ "the influence relationships (Edges).\n\n"+ "Extraction Rules:\n"+ "- Connect each driver to the specific assets it influences.\n"+ "- Extract analyst sentiment (upgrade/downgrade language, target price changes).\n"+ "- Classify sentiment direction and influence strength.\n"+ "- Document the firm/analyst source and expected time horizon.\n"+ "- Only create edges between nodes that exist in the provided lists."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================+++class MarketSentimentGraph(AutoGraph[MarketDriver, AnalystInfluence]):+ """+ Applicable to: Equity Research Reports, Macro Strategy Calls, Earnings Call Transcripts,+ Macroeconomic Commentary, Analyst Alerts and Updates.++ Template for extracting and mapping market drivers to their expected impact on+ asset valuations and analyst recommendations. Enables tracking of investment thesis+ evolution and consensus shifts.++ Example Usage:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> sentiment = MarketSentimentGraph(llm_client=llm, embedder=embedder)+ >>> report = "AI demand acceleration is a key driver. We upgrade Tech stocks to Overweight..."+ >>> sentiment.feed_text(report)+ >>> sentiment.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "one_stage",+ chunk_size: int = 2048,+ chunk_overlap: int = 256,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ Initialize the Market Sentiment Graph template.++ Args:+ llm_client (BaseChatModel): The LLM for driver and sentiment extraction.+ embedder (Embeddings): Embedding model for deduplication.+ extraction_mode (str): "one_stage" or "two_stage".+ chunk_size (int): Max characters per chunk.+ chunk_overlap (int): Overlap between chunks.+ max_workers (int): Parallel processing workers.+ verbose (bool): Enable progress logging.+ **kwargs: Additional arguments for AutoGraph.+ """+ super().__init__(+ node_schema=MarketDriver,+ edge_schema=AnalystInfluence,+ node_key_extractor=lambda x: x.name.strip().lower(),+ edge_key_extractor=lambda x: (+ f"{x.source.strip()}--({x.sentiment})-->{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=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ 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 market sentiment graph using OntoSight.++ Args:+ top_k_nodes_for_search (int): Number of drivers to retrieve. Default 3.+ top_k_edges_for_search (int): Number of influences to retrieve. Default 3.+ top_k_nodes_for_chat (int): Drivers for chat context. Default 3.+ top_k_edges_for_chat (int): Influences for chat context. Default 3.+ """++ def node_label_extractor(node: MarketDriver) -> str:+ return f"{node.name} ({node.driver_type})"++ def edge_label_extractor(edge: AnalystInfluence) -> str:+ return f"[{edge.sentiment}/{edge.strength}] {edge.analyst_view}"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_nodes_for_search,+ top_k_edges_for_search=top_k_edges_for_search,+ top_k_nodes_for_chat=top_k_nodes_for_chat,+ top_k_edges_for_chat=top_k_edges_for_chat,+ )diff --git a/hyperextract/templates/en/finance/risk_assessment.py b/hyperextract/templates/en/finance/risk_assessment.pynew file mode 100644index 0000000..f68d99c--- /dev/null+++ b/hyperextract/templates/en/finance/risk_assessment.py@@ -0,0 +1,197 @@+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.types import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================+++class RiskFactor(BaseModel):+ """+ A specific risk factor identified in corporate disclosure documents.+ """++ name: str = Field(+ description="Name or category of the risk (e.g., 'Supply Chain Disruption', 'Currency Fluctuation')."+ )+ category: str = Field(+ description="Risk category: 'Market', 'Operational', 'Regulatory', 'Reputational', 'Geopolitical'."+ )+ description: Optional[str] = Field(+ None, description="Detailed explanation of what the risk entails."+ )+++class FinancialImpact(BaseModel):+ """+ A financial or business metric that can be adversely affected by risks.+ """++ name: str = Field(+ description="Financial metric or business area (e.g., 'Operating Margin', 'Revenue', 'Stock Price')."+ )+ metric_type: str = Field(+ description="Type: 'Revenue', 'Profitability', 'Liquidity', 'Valuation', 'Reputation'."+ )+++class RiskTransmissionEdge(BaseModel):+ """+ Represents the causal link from a risk factor to a financial impact.+ """++ source: str = Field(description="The risk factor name.")+ target: str = Field(description="The affected financial metric or business area.")+ impact_description: str = Field(+ description="How the risk could adversely affect the target (e.g., 'could reduce', 'may increase')."+ )+ likelihood: str = Field(+ description="Probability characterization: 'Possible', 'Probable', 'Uncertain', 'Remote'."+ )+ severity: str = Field(+ description="Severity level: 'Material', 'Significant', 'Severe', 'Catastrophic'."+ )+ mitigation: Optional[str] = Field(+ None, description="Any disclosed mitigation strategies or controls."+ )+++# ==============================================================================+# 2. Prompts+# ==============================================================================++_PROMPT = (+ "You are a financial risk analyst specializing in corporate risk disclosure. Extract risk factors and their "+ "transmission paths to financial impacts from SEC filings and prospectuses.\n\n"+ "Rules:\n"+ "- Identify explicit risk factors mentioned in Item 1A or similar risk disclosure sections.\n"+ "- For each risk, extract the explicit causal links to financial/operational impacts.\n"+ "- Use the exact severity and likelihood language from the source text.\n"+ "- Capture any disclosed mitigation strategies."+)++_NODE_PROMPT = (+ "You are a financial risk analyst. Extract all risk factors and financial metrics (Nodes) from the text.\n\n"+ "Extraction Rules:\n"+ "- Identify and categorize risk factors (Market, Operational, Regulatory, Reputational, Geopolitical).\n"+ "- Identify financial or operational metrics that could be affected (Revenue, Margin, Valuation).\n"+ "- Use exact names and descriptions from the source text.\n"+ "- DO NOT establish the causal relationships between risks and impacts at this stage."+)++_EDGE_PROMPT = (+ "You are a financial risk analyst. Given the list of risk factors and financial metrics, extract the causal "+ "transmission paths (Edges).\n\n"+ "Extraction Rules:\n"+ "- Connect each risk factor to the specific financial metrics it could adversely affect.\n"+ "- Extract the exact impact description using language like 'could have a material adverse effect on'.\n"+ "- Classify the likelihood and severity using disclosed characterizations.\n"+ "- Document any mitigation strategies mentioned in conjunction with the risk.\n"+ "- Only create edges between nodes that exist in the provided lists."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================+++class RiskAssessmentGraph(AutoGraph[RiskFactor, RiskTransmissionEdge]):+ """+ Applicable to: SEC 10-K/10-Q Item 1A (Risk Factors), Prospectus Risk Sections (S-1),+ Debt Rating Reports, Risk Disclosure Filings.++ Template for systematically extracting and mapping corporate risk factors to their+ financial impacts. Enables structured risk monitoring and comparative analysis across+ multiple filings.++ Example Usage:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> risk_graph = RiskAssessmentGraph(llm_client=llm, embedder=embedder)+ >>> filing_text = "Item 1A. Risk Factors: Currency fluctuations could materially impact our margins..."+ >>> risk_graph.feed_text(filing_text)+ >>> risk_graph.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "one_stage",+ chunk_size: int = 2048,+ chunk_overlap: int = 256,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ Initialize the Risk Assessment Graph template.++ Args:+ llm_client (BaseChatModel): The LLM for risk and impact extraction.+ embedder (Embeddings): Embedding model for entity deduplication.+ extraction_mode (str): "one_stage" or "two_stage".+ chunk_size (int): Max characters per chunk.+ chunk_overlap (int): Overlap between chunks.+ max_workers (int): Parallel processing workers.+ verbose (bool): Enable progress logging.+ **kwargs: Additional arguments for AutoGraph.+ """+ super().__init__(+ node_schema=RiskFactor,+ edge_schema=RiskTransmissionEdge,+ node_key_extractor=lambda x: x.name.strip().lower(),+ edge_key_extractor=lambda x: (+ f"{x.source.strip()}--({x.likelihood}/{x.severity})-->{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=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ 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 risk transmission graph using OntoSight.++ Args:+ top_k_nodes_for_search (int): Number of risk nodes to retrieve. Default 3.+ top_k_edges_for_search (int): Number of transmission paths to retrieve. Default 3.+ top_k_nodes_for_chat (int): Nodes for chat context. Default 3.+ top_k_edges_for_chat (int): Edges for chat context. Default 3.+ """++ def node_label_extractor(node: RiskFactor) -> str:+ return f"{node.name} ({node.category})"++ def edge_label_extractor(edge: RiskTransmissionEdge) -> str:+ return f"[{edge.likelihood}/{edge.severity}]"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_nodes_for_search,+ top_k_edges_for_search=top_k_edges_for_search,+ top_k_nodes_for_chat=top_k_nodes_for_chat,+ top_k_edges_for_chat=top_k_edges_for_chat,+ )diff --git a/hyperextract/templates/en/finance/supply_chain.py b/hyperextract/templates/en/finance/supply_chain.pynew file mode 100644index 0000000..76b014c--- /dev/null+++ b/hyperextract/templates/en/finance/supply_chain.py@@ -0,0 +1,191 @@+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.types import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================+++class SupplyEntity(BaseModel):+ """+ A participant in the supply chain (company, supplier, customer, distributor).+ """++ name: str = Field(description="Entity name (company or supplier).")+ entity_type: str = Field(+ description="Type: 'Customer', 'Supplier', 'Strategic Partner', 'Distributor', 'Our Company'."+ )+ jurisdiction: Optional[str] = Field(+ None, description="Geographic location or headquarters region."+ )+ notes: Optional[str] = Field(+ None, description="Additional details (e.g., 'Certified Organic', 'ISO Compliant')."+ )+++class SupplyTransaction(BaseModel):+ """+ A supply chain relationship between entities.+ """++ source: str = Field(description="The supplier or upstream entity.")+ target: str = Field(description="The buyer or downstream entity.")+ transaction_type: str = Field(+ description="Type: 'Supply', 'Purchase', 'Distribution', 'Strategic Partnership'."+ )+ product_service: str = Field(+ description="What is being supplied or transacted (e.g., 'Lithium Chips', 'Logistics Services')."+ )+ dependency: str = Field(+ description="Dependency level: 'Critical', 'High', 'Moderate', 'Low'."+ )+ volume_percentage: Optional[str] = Field(+ None, description="Percentage of total supply/revenue if disclosed (e.g., '80%')."+ )+ geographic_origin: Optional[str] = Field(+ None, description="Source region or geopolitical consideration."+ )+ risks: Optional[str] = Field(+ None,+ description="Any disclosed risks or vulnerabilities (e.g., 'Single-source supplier', 'Tariff exposure').",+ )+++# ==============================================================================+# 2. Prompts+# ==============================================================================++_PROMPT = (+ "You are a supply chain analyst. Extract supply chain entities and their relationships "+ "from corporate filings and supply chain audits.\n\n"+ "Rules:\n"+ "- Identify key suppliers, customers, and strategic partners mentioned.\n"+ "- Extract transaction types and product/service descriptions.\n"+ "- Assess dependency levels based on disclosed volume or importance.\n"+ "- Document any geopolitical or regulatory risks."+)++_NODE_PROMPT = (+ "You are a supply chain analyst. Extract all supply chain participants (Nodes) from the text.\n\n"+ "Extraction Rules:\n"+ "- Identify companies, suppliers, customers, and distribution partners.\n"+ "- Classify each entity's role in the supply chain.\n"+ "- Note jurisdiction and any certifications or compliance notes.\n"+ "- DO NOT establish transaction relationships at this stage."+)++_EDGE_PROMPT = (+ "You are a supply chain analyst. Given the list of supply chain entities, extract the "+ "transaction relationships (Edges).\n\n"+ "Extraction Rules:\n"+ "- Connect supplier to buyer with the specific product/service being transacted.\n"+ "- Assess dependency level based on disclosed volume percentages or importance keywords.\n"+ "- Extract geographic origin and any disclosed risks (tariffs, single-source).\n"+ "- Only connect entities that exist in the provided list."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================+++class SupplyChainGraph(AutoGraph[SupplyEntity, SupplyTransaction]):+ """+ Applicable to: Business Overview sections in 10-K filings, Supplier Audit Reports,+ Supply Chain Resilience Disclosures (10-K Item 1A), ESG Reports, Vendor Management Documents.++ Template for mapping corporate supply chain dependencies and partnerships. Enables+ identification of critical suppliers, geopolitical exposure, and supply chain resilience risks.++ Example Usage:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> supply_chain = SupplyChainGraph(llm_client=llm, embedder=embedder)+ >>> filing = "Supplier XYZ provides 70% of our components. We also depend on..."+ >>> supply_chain.feed_text(filing)+ >>> supply_chain.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "one_stage",+ chunk_size: int = 2048,+ chunk_overlap: int = 256,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ Initialize the Supply Chain Graph template.++ Args:+ llm_client (BaseChatModel): The LLM for entity and relationship extraction.+ embedder (Embeddings): Embedding model for deduplication.+ extraction_mode (str): "one_stage" or "two_stage".+ chunk_size (int): Max characters per chunk.+ chunk_overlap (int): Overlap between chunks.+ max_workers (int): Parallel processing workers.+ verbose (bool): Enable progress logging.+ **kwargs: Additional arguments for AutoGraph.+ """+ super().__init__(+ node_schema=SupplyEntity,+ edge_schema=SupplyTransaction,+ node_key_extractor=lambda x: x.name.strip().lower(),+ edge_key_extractor=lambda x: (+ f"{x.source.strip()}--({x.product_service})-->{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=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ 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 supply chain graph using OntoSight.++ Args:+ top_k_nodes_for_search (int): Number of entities to retrieve. Default 3.+ top_k_edges_for_search (int): Number of relationships to retrieve. Default 3.+ top_k_nodes_for_chat (int): Entities for chat context. Default 3.+ top_k_edges_for_chat (int): Relationships for chat context. Default 3.+ """++ def node_label_extractor(node: SupplyEntity) -> str:+ return f"{node.name} ({node.entity_type})"++ def edge_label_extractor(edge: SupplyTransaction) -> str:+ vol = f" {edge.volume_percentage}" if edge.volume_percentage else ""+ return f"{edge.product_service}{vol} [{edge.dependency}]"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_nodes_for_search,+ top_k_edges_for_search=top_k_edges_for_search,+ top_k_nodes_for_chat=top_k_nodes_for_chat,+ top_k_edges_for_chat=top_k_edges_for_chat,+ )diff --git a/hyperextract/templates/en/food/__init__.py b/hyperextract/templates/en/food/__init__.pyindex e69de29..cb9481b 100644--- a/hyperextract/templates/en/food/__init__.py+++ b/hyperextract/templates/en/food/__init__.py@@ -0,0 +1,17 @@+"""+Food & Agriculture domain templates for extracting structured knowledge from food industry documents.++Includes templates for HACCP safety, recipe processes, flavor pairing, and culinary collections.+"""++from .haccp_safety import FoodSafetyHACCPGraph+from .recipe_process import RecipeProcessGraph+from .flavor_pairing import FlavorPairingGraph+from .culinary_dish import CulinaryDishSet++__all__ = [+ "FoodSafetyHACCPGraph",+ "RecipeProcessGraph",+ "FlavorPairingGraph",+ "CulinaryDishSet",+]diff --git a/hyperextract/templates/en/food/culinary_dish.py b/hyperextract/templates/en/food/culinary_dish.pynew file mode 100644index 0000000..c7b4cea--- /dev/null+++ b/hyperextract/templates/en/food/culinary_dish.py@@ -0,0 +1,149 @@+from typing import Optional, List, Any+from pydantic import BaseModel, Field+from langchain_core.language_models.chat_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoSet++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================+++class CulinaryDish(BaseModel):+ """+ A representative culinary dish with standardized characteristics.+ """++ name: str = Field(+ description="Standardized dish name (e.g., 'Kung Pao Chicken', 'Mapo Tofu', 'Risotto')."+ )+ cuisine: str = Field(+ description="Cuisine origin (e.g., 'Sichuan', 'Italian', 'French', 'Indian', 'Thai')."+ )+ region: Optional[str] = Field(+ None, description="Specific geographic region or city of origin if applicable."+ )+ primary_ingredients: List[str] = Field(+ default_factory=list, description="Core ingredients defining the dish (e.g., ['Chicken', 'Peanuts', 'Dried Chilies'])."+ )+ protein_type: Optional[str] = Field(+ None,+ description="Main protein: 'Chicken', 'Beef', 'Pork', 'Seafood', 'Plant-based', 'No protein'.",+ )+ flavor_profile: str = Field(+ description="Predominant taste characteristics (e.g., 'Spicy & Numbing', 'Sweet & Sour', 'Umami-rich')."+ )+ cooking_method: Optional[str] = Field(+ None, description="Primary cooking technique (e.g., 'Stir-fry', 'Braised', 'Steamed', 'Grilled')."+ )+ dietary_attributes: List[str] = Field(+ default_factory=list,+ description="Dietary tags (e.g., 'Contains Nuts', 'Gluten-Free', 'Vegetarian', 'Dairy-Free').",+ )+ serving_suggestion: Optional[str] = Field(+ None, description="Typical serving context (e.g., 'Appetizer', 'Main course', 'Side dish')."+ )+ seasonal_note: Optional[str] = Field(+ None, description="Seasonal availability or association (e.g., 'Summer dish', 'Winter comfort food')."+ )+++# ==============================================================================+# 2. Prompts+# ==============================================================================++_PROMPT = (+ "You are a culinary expert and food historian. Your task is to extract and standardize "+ "representative culinary dishes from menus, cookbooks, recipe collections, and food reviews.\n\n"+ "Extraction Rules:\n"+ "- Standardize dish names to their most recognized form (e.g., 'Kung Pao Chicken' vs. 'Gong Bao Ji Ding').\n"+ "- Identify the cuisine origin and specific geographic region.\n"+ "- Extract core ingredients that define the dish.\n"+ "- Capture the predominant flavor profile using precise descriptors.\n"+ "- Note dietary attributes and allergenic ingredients.\n"+ "- Deduplicate: If the same dish appears with slight variations, merge into one entry.\n"+)++# ==============================================================================+# 3. Template Class+# ==============================================================================+++class CulinaryDishSet(AutoSet[CulinaryDish]):+ """+ Applicable to: Restaurant Menus, Cookbooks, Food Encyclopedias, Recipe Websites,+ Food Blogs, Culinary Magazine Articles, Restaurant Review Databases, Dining Guides.++ Template for building a deduplicated collection of canonical culinary dishes.+ Standardizes dish names across cultural and linguistic variations, capturing their+ defining characteristics. Useful for culinary reference systems, recipe discovery,+ and food journalism.++ Example Usage:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> dishes = CulinaryDishSet(llm_client=llm, embedder=embedder)+ >>> menu_text = "Our menu features Gong Bao Chicken, Kung Pao Chicken, and authentic Sichuan peanut chicken..."+ >>> dishes.feed_text(menu_text)+ >>> dishes.show() # Automatically accumulates information for identical dish keys (e.g. 'Kung Pao Chicken')+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ chunk_size: int = 2048,+ chunk_overlap: int = 256,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ Initialize the Culinary Dish Set template.++ Args:+ llm_client (BaseChatModel): The LLM for dish extraction and standardization.+ embedder (Embeddings): Embedding model for retrieval and visualization.+ chunk_size (int): Size of text chunks for processing.+ chunk_overlap (int): Overlap between chunks.+ max_workers (int): Parallel processing workers.+ verbose (bool): Enable progress logging.+ **kwargs: Additional parameters for AutoSet.+ """+ super().__init__(+ item_schema=CulinaryDish,+ key_extractor=lambda x: x.name.strip().lower(),+ llm_client=llm_client,+ embedder=embedder,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_for_search: int = 3,+ top_k_for_chat: int = 3,+ ) -> None:+ """+ Display the culinary dish collection using OntoSight.++ Args:+ top_k_for_search (int): Number of dishes to retrieve for search context. Default 3.+ top_k_for_chat (int): Number of dishes to retrieve for chat context. Default 3.+ """++ def item_label_extractor(dish: CulinaryDish) -> str:+ return f"{dish.name} ({dish.cuisine})"++ super().show(+ item_label_extractor=item_label_extractor,+ top_k_for_search=top_k_for_search,+ top_k_for_chat=top_k_for_chat,+ )diff --git a/hyperextract/templates/en/food/flavor_pairing.py b/hyperextract/templates/en/food/flavor_pairing.pynew file mode 100644index 0000000..ceba4ed--- /dev/null+++ b/hyperextract/templates/en/food/flavor_pairing.py@@ -0,0 +1,190 @@+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.types import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================+++class FlavorComponent(BaseModel):+ """+ A food ingredient or flavor compound involved in pairing relationships.+ """++ name: str = Field(description="Name of food/ingredient/compound (e.g., 'Strawberry', 'Furaneol', 'Vanilla').")+ component_type: str = Field(+ description="Type: 'Ingredient', 'Chemical Compound', 'Flavor Note', 'Aroma'."+ )+ description: Optional[str] = Field(+ None, description="Additional details (e.g., chemical formula, source, sensory profile)."+ )+++class FlavorRelationship(BaseModel):+ """+ A pairing or flavor relationship between two components.+ """++ source: str = Field(description="First component.")+ target: str = Field(description="Second component.")+ relationship_type: str = Field(+ description="Type: 'Contains', 'Pairs_Well', 'Conflicts', 'Complements', 'Shared_Flavor'."+ )+ pairing_mechanism: str = Field(+ description="Why they pair or connect (e.g., 'Shared sulfur compounds', 'Complementary sweetness', 'Similar volatile compounds')."+ )+ pairing_quality: Optional[str] = Field(+ None, description="Quality assessment (e.g., 'Strong', 'Moderate', 'Subtle', 'Surprising')."+ )+ culinary_context: Optional[str] = Field(+ None,+ description="In what culinary context they pair well (e.g., 'Sweet desserts', 'Savory broths', 'Asian cuisine').",+ )+ supporting_evidence: Optional[str] = Field(+ None,+ description="Scientific evidence or reference (e.g., 'Clinical taste panel study', 'Food Chemistry Journal').",+ )+++# ==============================================================================+# 2. Prompts+# ==============================================================================++_PROMPT = (+ "You are a food chemist and flavor scientist. Extract flavor components and their pairing "+ "relationships from food science literature and sensory evaluation reports.\n\n"+ "Rules:\n"+ "- Identify food ingredients, volatile compounds, and flavor molecules mentioned.\n"+ "- Extract flavor pairing relationships and the chemistry/science behind them.\n"+ "- Distinguish between complementary, conflicting, and surprising pairings.\n"+ "- Document the evidence basis (taste panel, chemical analysis, etc.)."+)++_NODE_PROMPT = (+ "You are a food chemist. Extract all flavor components and compounds (Nodes) from the text.\n\n"+ "Extraction Rules:\n"+ "- Identify food ingredients (Strawberry, Tomato) and flavor compounds (Furaneol, Vanillin).\n"+ "- Classify each as Ingredient, Chemical Compound, or Flavor Note.\n"+ "- Include sensory or chemical descriptors where provided.\n"+ "- DO NOT establish pairings or relationships at this stage."+)++_EDGE_PROMPT = (+ "You are a food chemist. Given the list of flavor components, extract their pairing and "+ "relationship connections (Edges).\n\n"+ "Extraction Rules:\n"+ "- Connect components that share flavor molecules or pair well culinarily.\n"+ "- Extract the scientific mechanism (shared compounds, complementary tastes).\n"+ "- Assess pairing quality and context (when/why they work together).\n"+ "- Include supporting evidence from research or sensory studies.\n"+ "- Only connect components that exist in the provided list."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================+++class FlavorPairingGraph(AutoGraph[FlavorComponent, FlavorRelationship]):+ """+ Applicable to: Food Chemistry Research Papers (journals like Food Chemistry, LWT),+ Sensory Evaluation Reports, Recipe Development Studies, Flavor Science Books,+ Culinary Science Databases, Molecular Gastronomy Guides.++ Template for extracting and mapping flavor and culinary science knowledge. Enables+ understanding of ingredients' chemical similarities, predicting novel flavor combinations,+ and supporting data-driven recipe development.++ Example Usage:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> flavors = FlavorPairingGraph(llm_client=llm, embedder=embedder)+ >>> paper = "Strawberries and tomatoes both contain furaneol, leading to surprising pairing potential..."+ >>> flavors.feed_text(paper)++ >>> flavors.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "one_stage",+ chunk_size: int = 2048,+ chunk_overlap: int = 256,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ Initialize the Flavor Pairing Graph template.++ Args:+ llm_client (BaseChatModel): The LLM for component and relationship extraction.+ embedder (Embeddings): Embedding model for deduplication.+ extraction_mode (str): "one_stage" or "two_stage".+ chunk_size (int): Max characters per chunk.+ chunk_overlap (int): Overlap between chunks.+ max_workers (int): Parallel processing workers.+ verbose (bool): Enable progress logging.+ **kwargs: Additional arguments for AutoGraph.+ """+ super().__init__(+ node_schema=FlavorComponent,+ edge_schema=FlavorRelationship,+ node_key_extractor=lambda x: x.name.strip().lower(),+ edge_key_extractor=lambda x: (+ f"{x.source.strip()}--({x.relationship_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=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ 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 flavor pairing graph using OntoSight.++ Args:+ top_k_nodes_for_search (int): Number of components to retrieve. Default 3.+ top_k_edges_for_search (int): Number of relationships to retrieve. Default 3.+ top_k_nodes_for_chat (int): Components for chat context. Default 3.+ top_k_edges_for_chat (int): Relationships for chat context. Default 3.+ """++ def node_label_extractor(node: FlavorComponent) -> str:+ return f"{node.name} ({node.component_type})"++ def edge_label_extractor(edge: FlavorRelationship) -> str:+ quality = f" ({edge.pairing_quality})" if edge.pairing_quality else ""+ return f"{edge.relationship_type}{quality}"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_nodes_for_search,+ top_k_edges_for_search=top_k_edges_for_search,+ top_k_nodes_for_chat=top_k_nodes_for_chat,+ top_k_edges_for_chat=top_k_edges_for_chat,+ )diff --git a/hyperextract/templates/en/food/haccp_safety.py b/hyperextract/templates/en/food/haccp_safety.pynew file mode 100644index 0000000..f193203--- /dev/null+++ b/hyperextract/templates/en/food/haccp_safety.py@@ -0,0 +1,206 @@+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.types import AutoGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================+++class BiologicalHazard(BaseModel):+ """+ A biological hazard that must be controlled in food production.+ """++ name: str = Field(+ description="Hazard pathogen name (e.g., 'Salmonella', 'Listeria monocytogenes', 'E. coli O157:H7')."+ )+ hazard_type: str = Field(+ description="Type: 'Bacterial', 'Viral', 'Parasitic', 'Fungal'."+ )+ health_consequence: Optional[str] = Field(+ None, description="Potential health effect (e.g., 'Severe gastroenteritis', 'Sepsis')."+ )+++class CriticalControlPoint(BaseModel):+ """+ A step or process in food production where a hazard can be controlled.+ """++ name: str = Field(+ description="CCP name (e.g., 'Pasteurization', 'Metal Detection', 'Cold Storage')."+ )+ process_stage: str = Field(+ description="Stage in production: 'Raw Material', 'Receiving', 'Processing', 'Cooking', 'Cooling', 'Packaging', 'Storage'."+ )+ description: Optional[str] = Field(+ None, description="Detailed description of the CCP."+ )+++class ControlMeasure(BaseModel):+ """+ A control measure linking a hazard to a CCP.+ """++ source: str = Field(description="The biological hazard name.")+ target: str = Field(description="The CCP name.")+ critical_limit: str = Field(+ description="Critical limit defining the boundary between safe/unsafe (e.g., '>=72°C for >=15 seconds', 'pH < 4.6')."+ )+ monitoring_procedure: str = Field(+ description="How the CCP is monitored (e.g., 'Thermometer reading every batch', 'pH meter daily')."+ )+ monitoring_frequency: str = Field(+ description="How often monitoring occurs (e.g., 'Every 2 hours', 'Per batch', 'Daily')."+ )+ corrective_action: str = Field(+ description="Action if critical limit is not met (e.g., 'Discard product', 'Reprocess', 'Alert QA')."+ )+ verification: Optional[str] = Field(+ None, description="Verification method to confirm effectiveness (e.g., 'Culture tests monthly')."+ )+++# ==============================================================================+# 2. Prompts+# ==============================================================================++_PROMPT = (+ "You are a food safety specialist trained in HACCP principles. Extract hazards, critical control points, "+ "and their control measures from HACCP plans and food safety documentation.\n\n"+ "Rules:\n"+ "- Identify biological hazards relevant to the product and process.\n"+ "- Identify CCPs where hazards can be eliminated or controlled.\n"+ "- Extract critical limits, monitoring procedures, and corrective actions.\n"+ "- Ensure each CCP is linked to specific hazard(s) it controls."+)++_NODE_PROMPT = (+ "You are a food safety specialist. Extract all hazards and CCPs (Nodes) from the HACCP documentation.\n\n"+ "Extraction Rules:\n"+ "- Identify all biological hazards mentioned (pathogens, allergens if applicable).\n"+ "- Identify all CCPs (cooking, cooling, metal detection stages).\n"+ "- Classify each hazard by type (Bacterial, Viral, Fungal, Parasitic).\n"+ "- Classify each CCP by production stage.\n"+ "- DO NOT establish control relationships at this stage."+)++_EDGE_PROMPT = (+ "You are a food safety specialist. Given the list of hazards and CCPs, extract the control relationships (Edges).\n\n"+ "Extraction Rules:\n"+ "- Connect each hazard to the CCP(s) that control it.\n"+ "- Extract critical limits with precise thresholds and units.\n"+ "- Extract monitoring procedures and frequency from the HACCP document.\n"+ "- Extract corrective actions to be taken if limits are violated.\n"+ "- Include verification methods when documented.\n"+ "- Only create edges between hazards and CCPs that exist in the provided lists."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================+++class FoodSafetyHACCPGraph(AutoGraph[BiologicalHazard, ControlMeasure]):+ """+ Applicable to: HACCP Plans, Food Safety Plans (ISO 22000), SOP Manuals,+ FDA Guidance Documents, Food Company Quality Procedures, Supplier Audit Reports.++ Template for systematically extracting and structuring HACCP-based food safety+ controls. Enables compliance verification, supplier auditing, and continuous+ safety monitoring across food production operations.++ Example Usage:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> haccp = FoodSafetyHACCPGraph(llm_client=llm, embedder=embedder)+ >>> plan = "Critical Control Point: Pasteurization. Hazard: Salmonella. Critical limit: 72°C for 15s..."+ >>> haccp.feed_text(plan)+ >>> haccp.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "one_stage",+ chunk_size: int = 2048,+ chunk_overlap: int = 256,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ Initialize the Food Safety HACCP Graph template.++ Args:+ llm_client (BaseChatModel): The LLM for hazard and control extraction.+ embedder (Embeddings): Embedding model for deduplication.+ extraction_mode (str): "one_stage" or "two_stage".+ chunk_size (int): Max characters per chunk.+ chunk_overlap (int): Overlap between chunks.+ max_workers (int): Parallel processing workers.+ verbose (bool): Enable progress logging.+ **kwargs: Additional arguments for AutoGraph.+ """+ super().__init__(+ node_schema=BiologicalHazard,+ edge_schema=ControlMeasure,+ node_key_extractor=lambda x: x.name.strip().lower(),+ edge_key_extractor=lambda x: (+ f"{x.source.strip()}--({x.target.strip()}): {x.critical_limit.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=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ 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 food safety control graph using OntoSight.++ Args:+ top_k_nodes_for_search (int): Number of hazards/CCPs to retrieve. Default 3.+ top_k_edges_for_search (int): Number of control measures to retrieve. Default 3.+ top_k_nodes_for_chat (int): Nodes for chat context. Default 3.+ top_k_edges_for_chat (int): Edges for chat context. Default 3.+ """++ def node_label_extractor(node: BiologicalHazard) -> str:+ if isinstance(node, BiologicalHazard):+ return f"{node.name} ({node.hazard_type})"+ return str(node)++ def edge_label_extractor(edge: ControlMeasure) -> str:+ return f"{edge.critical_limit}"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_nodes_for_search,+ top_k_edges_for_search=top_k_edges_for_search,+ top_k_nodes_for_chat=top_k_nodes_for_chat,+ top_k_edges_for_chat=top_k_edges_for_chat,+ )diff --git a/hyperextract/templates/en/food/recipe_process.py b/hyperextract/templates/en/food/recipe_process.pynew file mode 100644index 0000000..7d1499e--- /dev/null+++ b/hyperextract/templates/en/food/recipe_process.py@@ -0,0 +1,197 @@+from typing import List, Optional, Any+from pydantic import BaseModel, Field+from langchain_core.language_models.chat_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoTemporalGraph++# ==============================================================================+# 1. Schema Definitions+# ==============================================================================+++class IngredientState(BaseModel):+ """+ The state of ingredients/materials at a particular stage in the recipe process.+ """++ name: str = Field(+ description="State descriptor (e.g., 'Blended Mixture', 'Heated Dough', 'Cooled Slurry')."+ )+ composition: str = Field(+ description="What's in this state (e.g., 'Eggs + Sugar', 'Flour + Water + Salt')."+ )+ physical_state: Optional[str] = Field(+ None, description="Physical form: 'Liquid', 'Solid', 'Powder', 'Dough', 'Emulsion', 'Foam'."+ )+++class ProcessingStep(BaseModel):+ """+ A transformation step connecting two ingredient states.+ """++ step_id: str = Field(description="Step identifier (e.g., 'Step 1', '1.1', 'Mixing').")+ source_state: str = Field(description="The starting ingredient state.")+ target_state: str = Field(description="The resulting ingredient state after processing.")+ action: str = Field(+ description="The processing action (e.g., 'Blend', 'Heat', 'Cool', 'Rest', 'Knead', 'Ferment')."+ )+ duration: str = Field(+ description="How long the action takes (e.g., '10 mins', '2 hours', 'Overnight', '15s')."+ )+ temperature: Optional[str] = Field(+ None, description="Temperature setting if applicable (e.g., '175°C', 'Room temperature', '4°C')."+ )+ equipment: Optional[str] = Field(+ None, description="Equipment used (e.g., 'Stand Mixer', 'Oven', 'Water Bath', 'Thermometer')."+ )+ parameters: Optional[str] = Field(+ None,+ description="Additional parameters (speed, pressure, etc., e.g., 'Medium speed', '200 PSI').",+ )+ notes: Optional[str] = Field(+ None, description="Special instructions or observations (e.g., 'A light cream should form')."+ )+++# ==============================================================================+# 2. Prompts+# ==============================================================================++_PROMPT = (+ "You are a professional chef and food scientist. Extract the step-by-step recipe or industrial "+ "food production process from formulation sheets and SOPs.\n\n"+ "Rules:\n"+ "- Identify each distinct processing action and transformation.\n"+ "- Extract ingredient states before and after each step.\n"+ "- Capture timing, temperature, and equipment precisely.\n"+ "- Maintain strict sequence order (Step 1 -> Step 2, etc.).\n"+ "- Include any notes on texture, appearance, or sensory cues."+)++_NODE_PROMPT = (+ "You are a professional chef and food scientist. Extract all ingredient states (Nodes) from the recipe.\n\n"+ "Extraction Rules:\n"+ "- Identify distinct states/stages in the recipe (raw, mixed, heated, cooled, rested).\n"+ "- Describe what ingredients are present at each state.\n"+ "- Note the physical form (liquid, solid, dough, etc.).\n"+ "- Maintain exact names and descriptions from the source.\n"+ "- DO NOT describe the actions or transitions between states at this stage."+)++_EDGE_PROMPT = (+ "You are a professional chef. Given the list of ingredient states, extract the processing "+ "steps that transform one state into another (Edges).\n\n"+ "Extraction Rules:\n"+ "- Connect each source state to its target state with the specific action.\n"+ "- Extract duration, temperature, and equipment for each step.\n"+ "- Extract any special parameters (speed, pressure) or sensory cues.\n"+ "- Maintain strict step ordering (Step 1, Step 2, etc.).\n"+ "- Only connect states that exist in the provided list."+)++# ==============================================================================+# 3. Template Class+# ==============================================================================+++class RecipeProcessGraph(AutoTemporalGraph[IngredientState, ProcessingStep]):+ """+ Applicable to: Industrial Formulation Sheets, Recipe SOPs, Food Science Research,+ Production Batch Records, Chef's Recipes, Cooking Manuals, R&D Experimental Protocols.++ Template for extracting and mapping sequential food production processes with+ precise timing and parameters. Enables recipe standardization, process optimization,+ and knowledge transfer in culinary and industrial food settings.++ Example Usage:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> recipe = RecipeProcessGraph(llm_client=llm, embedder=embedder)+ >>> process = "Step 1: Blend eggs and sugar for 5 mins. Step 2: Heat to 175°C..."+ >>> recipe.feed_text(process)+ >>> recipe.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "one_stage",+ chunk_size: int = 2048,+ chunk_overlap: int = 256,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ Initialize the Recipe Process Graph template.++ Args:+ llm_client (BaseChatModel): The LLM for state and step extraction.+ embedder (Embeddings): Embedding model for deduplication.+ extraction_mode (str): "one_stage" or "two_stage".+ chunk_size (int): Max characters per chunk.+ chunk_overlap (int): Overlap between chunks.+ max_workers (int): Parallel processing workers.+ verbose (bool): Enable progress logging.+ **kwargs: Additional arguments for AutoTemporalGraph.+ """+ super().__init__(+ node_schema=IngredientState,+ edge_schema=ProcessingStep,+ node_key_extractor=lambda x: x.name.strip().lower(),+ edge_key_extractor=lambda x: x.step_id.strip(),+ nodes_in_edge_extractor=lambda x: (+ x.source_state.strip(),+ x.target_state.strip(),+ ),+ time_in_edge_extractor=lambda x: x.step_id.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=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ 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 recipe process timeline using OntoSight.++ Args:+ top_k_nodes_for_search (int): Number of states to retrieve. Default 3.+ top_k_edges_for_search (int): Number of steps to retrieve. Default 3.+ top_k_nodes_for_chat (int): States for chat context. Default 3.+ top_k_edges_for_chat (int): Steps for chat context. Default 3.+ """++ def node_label_extractor(node: IngredientState) -> str:+ return f"{node.name} ({node.physical_state if node.physical_state else 'Unknown'})"++ def edge_label_extractor(edge: ProcessingStep) -> str:+ temp = f" {edge.temperature}" if edge.temperature else ""+ return f"{edge.action} ({edge.duration}){temp}"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_nodes_for_search,+ top_k_edges_for_search=top_k_edges_for_search,+ top_k_nodes_for_chat=top_k_nodes_for_chat,+ top_k_edges_for_chat=top_k_edges_for_chat,+ )diff --git a/hyperextract/templates/zh/finance/__init__.py b/hyperextract/templates/zh/finance/__init__.pyindex e69de29..05c9906 100644--- a/hyperextract/templates/zh/finance/__init__.py+++ b/hyperextract/templates/zh/finance/__init__.py@@ -0,0 +1,15 @@+"""+金融领域模板,用于从财务文档中提取结构化知识。++包含风险评估、市场观点和供应链分析等模板。+"""++from .risk_assessment import RiskAssessmentGraph+from .market_sentiment import MarketSentimentGraph+from .supply_chain import SupplyChainGraph++__all__ = [+ "RiskAssessmentGraph",+ "MarketSentimentGraph",+ "SupplyChainGraph",+]diff --git a/hyperextract/templates/zh/finance/market_sentiment.py b/hyperextract/templates/zh/finance/market_sentiment.pynew file mode 100644index 0000000..4a8a4b6--- /dev/null+++ b/hyperextract/templates/zh/finance/market_sentiment.py@@ -0,0 +1,196 @@+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.types import AutoGraph++# ==============================================================================+# 1. Schema 定义+# ==============================================================================+++class MarketDriver(BaseModel):+ """+ 影响市场前景的宏观经济或公司特定因素。+ """++ name: str = Field(+ description='驱动因素名称,例如"AI 需求"、"降息预期"、"监管明确化"等。'+ )+ driver_type: str = Field(+ description='类型:"宏观"、"行业"、"公司特定"、"催化剂"。'+ )+ description: Optional[str] = Field(+ None, description="为什么这个驱动因素重要的详细解释。"+ )+++class MarketTarget(BaseModel):+ """+ 受市场驱动因素影响的交易资产或财务指标。+ """++ ticker: str = Field(description='股票代码,例如"AAPL"、"AI 指数"。')+ asset_type: str = Field(+ description='类型:"股票"、"指数"、"债券"、"商品"、"货币"。'+ )+ metric: Optional[str] = Field(+ None, description='具体指标(如适用),例如"EPS"、"P/E 比率"。'+ )+++class AnalystInfluence(BaseModel):+ """+ 表示市场驱动因素如何影响资产前景。+ """++ source: str = Field(description="市场驱动因素名称。")+ target: str = Field(description="受影响资产/指标的股票代码。")+ sentiment: str = Field(+ description='情绪方向:"正面"、"负面"、"中性"。'+ )+ strength: str = Field(+ description='影响力强度:"强"、"中等"、"弱"。'+ )+ analyst_view: str = Field(+ description='分析师建议或目标调整,例如"升级为买入"、"将目标价上调至 150 美元"等。'+ )+ time_horizon: Optional[str] = Field(+ None, description='预期时间框架,例如"FY24"、"6-12 个月"、"长期"。'+ )+ source_firm: Optional[str] = Field(+ None, description="研究机构或分析师来源的名称。"+ )+++# ==============================================================================+# 2. 提示词 (Prompts)+# ==============================================================================++_PROMPT = (+ "你是股票研究分析师。从研究报告和宏观经济评论中提取市场驱动因素、目标资产和分析师观点。\n\n"+ "规则:\n"+ "- 识别市场驱动因素(催化剂、政策变化、行业趋势)。\n"+ "- 识别哪些资产(股票、指数、债券)受影响。\n"+ "- 提取情绪方向和分析师建议。\n"+ "- 记录时间框架和来源归属。"+)++_NODE_PROMPT = (+ "你是股票研究分析师。从文本中提取所有市场驱动因素和目标资产(节点)。\n\n"+ "提取规则:\n"+ "- 识别宏观经济因素、政策变化和催化剂事件。\n"+ "- 识别被讨论的股票代码和具体财务指标。\n"+ "- 按类型分类每个节点(宏观、公司特定等)。\n"+ "- 此阶段不建立驱动因素如何影响资产的关系。"+)++_EDGE_PROMPT = (+ "你是股票研究分析师。在获得市场驱动因素和目标资产清单的基础上,提取影响关系(边)。\n\n"+ "提取规则:\n"+ "- 将每个驱动因素连接到它影响的具体资产。\n"+ "- 提取分析师观点(升级/降级语言、目标价变化)。\n"+ "- 分类情绪方向和影响力强度。\n"+ "- 记录机构/分析师来源和预期时间框架。\n"+ "- 仅在提供的列表中存在的节点之间创建边。"+)++# ==============================================================================+# 3. 模板类+# ==============================================================================+++class MarketSentimentGraph(AutoGraph[MarketDriver, AnalystInfluence]):+ """+ 适用文档: 股票研究报告、宏观策略观点、财报电话会议记录、宏观经济评论、分析师警报和更新。++ 模板用于提取和映射市场驱动因素到其对资产估值和分析师建议的预期影响。支持跟踪投资主题演变和共识转变。++ 使用示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> sentiment = MarketSentimentGraph(llm_client=llm, embedder=embedder)+ >>> report = "AI 需求加速是关键驱动因素。我们将科技股升级为增持..."+ >>> sentiment.feed_text(report)+ >>> sentiment.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "one_stage",+ chunk_size: int = 2048,+ chunk_overlap: int = 256,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化市场观点图谱模板。++ Args:+ llm_client (BaseChatModel): 用于驱动因素和观点提取的 LLM。+ embedder (Embeddings): 用于去重的嵌入模型。+ extraction_mode (str): "one_stage" 或 "two_stage"。+ chunk_size (int): 每个分块的最大字符数。+ chunk_overlap (int): 分块之间的重叠。+ max_workers (int): 并行处理工作线程数。+ verbose (bool): 是否启用进度日志。+ **kwargs: AutoGraph 的其他参数。+ """+ super().__init__(+ node_schema=MarketDriver,+ edge_schema=AnalystInfluence,+ node_key_extractor=lambda x: x.name.strip().lower(),+ edge_key_extractor=lambda x: (+ f"{x.source.strip()}--({x.sentiment})-->{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=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ 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:+ """+ 使用 OntoSight 可视化市场观点图。++ Args:+ 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。+ """++ def node_label_extractor(node: MarketDriver) -> str:+ return f"{node.name} ({node.driver_type})"++ def edge_label_extractor(edge: AnalystInfluence) -> str:+ return f"[{edge.sentiment}/{edge.strength}] {edge.analyst_view}"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_nodes_for_search,+ top_k_edges_for_search=top_k_edges_for_search,+ top_k_nodes_for_chat=top_k_nodes_for_chat,+ top_k_edges_for_chat=top_k_edges_for_chat,+ )diff --git a/hyperextract/templates/zh/finance/risk_assessment.py b/hyperextract/templates/zh/finance/risk_assessment.pynew file mode 100644index 0000000..2c95dad--- /dev/null+++ b/hyperextract/templates/zh/finance/risk_assessment.py@@ -0,0 +1,192 @@+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.types import AutoGraph++# ==============================================================================+# 1. Schema 定义+# ==============================================================================+++class RiskFactor(BaseModel):+ """+ 从企业披露文件中识别的具体风险因子。+ """++ name: str = Field(+ description='风险名称或类别,例如"供应链中断"、"汇率波动"等。'+ )+ category: str = Field(+ description='风险类别:"市场"、"运营"、"监管"、"声誉"、"地缘政治"。'+ )+ description: Optional[str] = Field(+ None, description="风险的详细解释。"+ )+++class FinancialImpact(BaseModel):+ """+ 可能受风险不利影响的财务或业务指标。+ """++ name: str = Field(+ description='财务指标或业务领域,例如"营业利润率"、"收入"、"股价"等。'+ )+ metric_type: str = Field(+ description='指标类型:"收入"、"盈利能力"、"流动性"、"估值"、"声誉"。'+ )+++class RiskTransmissionEdge(BaseModel):+ """+ 表示从风险因子到财务影响的传导链。+ """++ source: str = Field(description="风险因子名称。")+ target: str = Field(description="受影响的财务指标或业务领域名称。")+ impact_description: str = Field(+ description='风险可能如何不利影响目标,例如"可能降低"、"可能增加"等。'+ )+ likelihood: str = Field(+ description='概率特征:"可能"、"较可能"、"不确定"、"罕见"。'+ )+ severity: str = Field(+ description='严重程度:"重要"、"显著"、"严重"、"灾难性"。'+ )+ mitigation: Optional[str] = Field(+ None, description="任何公开的缓解策略或控制措施。"+ )+++# ==============================================================================+# 2. 提示词 (Prompts)+# ==============================================================================++_PROMPT = (+ "你是专业的金融风险分析师,专门研究企业风险披露。请从 SEC 财报和招股说明书中提取风险因子及其对财务影响的传导路径。\n\n"+ "规则:\n"+ "- 识别风险披露部分(如 Item 1A)中明确提及的风险因子。\n"+ "- 对每项风险,提取其对财务/运营指标的因果链。\n"+ "- 使用源文本中确切的严重程度和概率语言。\n"+ "- 捕捉任何公开的缓解策略。"+)++_NODE_PROMPT = (+ "你是专业的金融风险分析师。从文本中提取所有风险因子和财务指标(节点)。\n\n"+ "提取规则:\n"+ "- 识别并分类风险因子(市场、运营、监管、声誉、地缘政治)。\n"+ "- 识别可能受影响的财务或运营指标(收入、利润率、估值)。\n"+ "- 使用源文本中的确切名称和描述。\n"+ "- 此阶段不建立风险与影响之间的因果关系。"+)++_EDGE_PROMPT = (+ "你是专业的金融风险分析师。在获得风险因子和财务指标清单的基础上,提取因果传导路径(边)。\n\n"+ "提取规则:\n"+ "- 将每个风险因子连接到它可能不利影响的具体财务指标。\n"+ "- 提取确切的影响描述,使用'可能对...产生重大不利影响'等语言。\n"+ "- 使用公开的表述分类概率和严重程度。\n"+ "- 记录与风险相关联的任何缓解策略。\n"+ "- 仅在提供的列表中存在的节点之间创建边。"+)++# ==============================================================================+# 3. 模板类+# ==============================================================================+++class RiskAssessmentGraph(AutoGraph[RiskFactor, RiskTransmissionEdge]):+ """+ 适用文档: SEC 10-K/10-Q Item 1A(风险因子)、招股说明书风险部分(S-1)、债券评级报告、风险披露文件。++ 模板用于系统地从企业披露中提取和映射风险因子及其财务影响。支持结构化风险监测和多份财报的对比分析。++ 使用示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> risk_graph = RiskAssessmentGraph(llm_client=llm, embedder=embedder)+ >>> filing_text = "Item 1A. 风险因子:汇率波动可能对利润率造成重大不利影响..."+ >>> risk_graph.feed_text(filing_text)+ >>> risk_graph.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "one_stage",+ chunk_size: int = 2048,+ chunk_overlap: int = 256,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化风险评估图谱模板。++ Args:+ llm_client (BaseChatModel): 用于风险和影响提取的 LLM。+ embedder (Embeddings): 用于实体去重的嵌入模型。+ extraction_mode (str): "one_stage" 或 "two_stage"。+ chunk_size (int): 每个分块的最大字符数。+ chunk_overlap (int): 分块之间的重叠。+ max_workers (int): 并行处理工作线程数。+ verbose (bool): 是否启用进度日志。+ **kwargs: AutoGraph 的其他参数。+ """+ super().__init__(+ node_schema=RiskFactor,+ edge_schema=RiskTransmissionEdge,+ node_key_extractor=lambda x: x.name.strip().lower(),+ edge_key_extractor=lambda x: (+ f"{x.source.strip()}--({x.likelihood}/{x.severity})-->{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=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ 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:+ """+ 使用 OntoSight 可视化风险传导图。++ Args:+ 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。+ """++ def node_label_extractor(node: RiskFactor) -> str:+ return f"{node.name} ({node.category})"++ def edge_label_extractor(edge: RiskTransmissionEdge) -> str:+ return f"[{edge.likelihood}/{edge.severity}]"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_nodes_for_search,+ top_k_edges_for_search=top_k_edges_for_search,+ top_k_nodes_for_chat=top_k_nodes_for_chat,+ top_k_edges_for_chat=top_k_edges_for_chat,+ )diff --git a/hyperextract/templates/zh/finance/supply_chain.py b/hyperextract/templates/zh/finance/supply_chain.pynew file mode 100644index 0000000..bb1d79e--- /dev/null+++ b/hyperextract/templates/zh/finance/supply_chain.py@@ -0,0 +1,187 @@+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.types import AutoGraph++# ==============================================================================+# 1. Schema 定义+# ==============================================================================+++class SupplyEntity(BaseModel):+ """+ 供应链中的参与者(公司、供应商、客户、分销商)。+ """++ name: str = Field(description="实体名称(公司或供应商)。")+ entity_type: str = Field(+ description='类型:"客户"、"供应商"、"战略伙伴"、"分销商"、"本公司"。'+ )+ jurisdiction: Optional[str] = Field(+ None, description="地理位置或总部所在地。"+ )+ notes: Optional[str] = Field(+ None, description='其他详情,例如"有机认证"、"ISO 合规"等。'+ )+++class SupplyTransaction(BaseModel):+ """+ 实体间的供应链关系。+ """++ source: str = Field(description="上游供应商或提供方。")+ target: str = Field(description="下游买方或需求方。")+ transaction_type: str = Field(+ description='类型:"供应"、"采购"、"分销"、"战略合作"。'+ )+ product_service: str = Field(+ description='被供应或交易的内容,例如"锂芯片"、"物流服务"等。'+ )+ dependency: str = Field(+ description='依赖程度:"关键"、"高"、"中等"、"低"。'+ )+ volume_percentage: Optional[str] = Field(+ None, description='如有披露,总供应或收入的百分比,例如"80%"。'+ )+ geographic_origin: Optional[str] = Field(+ None, description="来源地区或地缘政治考量。"+ )+ risks: Optional[str] = Field(+ None,+ description='披露的风险或脆弱性,例如"单一来源供应商"、"关税暴露"。'+ )+++# ==============================================================================+# 2. 提示词 (Prompts)+# ==============================================================================++_PROMPT = (+ "你是供应链分析师。从企业财报和供应链审计中提取供应链实体及其关系。\n\n"+ "规则:\n"+ "- 识别提及的关键供应商、客户和战略伙伴。\n"+ "- 提取交易类型和产品/服务描述。\n"+ "- 根据披露的数量或重要性评估依赖程度。\n"+ "- 记录任何地缘政治或监管风险。"+)++_NODE_PROMPT = (+ "你是供应链分析师。从文本中提取所有供应链参与者(节点)。\n\n"+ "提取规则:\n"+ "- 识别公司、供应商、客户和分销合作伙伴。\n"+ "- 对每个实体在供应链中的角色进行分类。\n"+ "- 记录司法管辖区和任何认证或合规说明。\n"+ "- 此阶段不建立交易关系。"+)++_EDGE_PROMPT = (+ "你是供应链分析师。在获得供应链实体清单的基础上,提取交易关系(边)。\n\n"+ "提取规则:\n"+ "- 将供应商连接到买方,说明具体的产品/服务。\n"+ "- 根据披露的数量百分比或重要性关键词评估依赖程度。\n"+ "- 提取地理来源和任何披露的风险(关税、单一来源)。\n"+ "- 仅连接提供列表中存在的实体。"+)++# ==============================================================================+# 3. 模板类+# ==============================================================================+++class SupplyChainGraph(AutoGraph[SupplyEntity, SupplyTransaction]):+ """+ 适用文档: 10-K 财报中的业务概览部分、供应商审计报告、供应链韧性披露(10-K Item 1A)、环境社会治理报告、供应商管理文件。++ 模板用于映射企业供应链依赖和伙伴关系。支持识别关键供应商、地缘政治敞口和供应链韧性风险。++ 使用示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> supply_chain = SupplyChainGraph(llm_client=llm, embedder=embedder)+ >>> filing = "供应商 XYZ 提供我们 70% 的零部件。我们还依赖于..."+ >>> supply_chain.feed_text(filing)+ >>> supply_chain.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "one_stage",+ chunk_size: int = 2048,+ chunk_overlap: int = 256,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化供应链图谱模板。++ Args:+ llm_client (BaseChatModel): 用于实体和关系提取的 LLM。+ embedder (Embeddings): 用于去重的嵌入模型。+ extraction_mode (str): "one_stage" 或 "two_stage"。+ chunk_size (int): 每个分块的最大字符数。+ chunk_overlap (int): 分块之间的重叠。+ max_workers (int): 并行处理工作线程数。+ verbose (bool): 是否启用进度日志。+ **kwargs: AutoGraph 的其他参数。+ """+ super().__init__(+ node_schema=SupplyEntity,+ edge_schema=SupplyTransaction,+ node_key_extractor=lambda x: x.name.strip().lower(),+ edge_key_extractor=lambda x: (+ f"{x.source.strip()}--({x.product_service})-->{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=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ 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:+ """+ 使用 OntoSight 可视化供应链图。++ Args:+ 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。+ """++ def node_label_extractor(node: SupplyEntity) -> str:+ return f"{node.name} ({node.entity_type})"++ def edge_label_extractor(edge: SupplyTransaction) -> str:+ vol = f" {edge.volume_percentage}" if edge.volume_percentage else ""+ return f"{edge.product_service}{vol} [{edge.dependency}]"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_nodes_for_search,+ top_k_edges_for_search=top_k_edges_for_search,+ top_k_nodes_for_chat=top_k_nodes_for_chat,+ top_k_edges_for_chat=top_k_edges_for_chat,+ )diff --git a/hyperextract/templates/zh/food/__init__.py b/hyperextract/templates/zh/food/__init__.pyindex e69de29..efd1d48 100644--- a/hyperextract/templates/zh/food/__init__.py+++ b/hyperextract/templates/zh/food/__init__.py@@ -0,0 +1,17 @@+"""+食品与农业领域模板,用于从食品工业文档中提取结构化知识。++包含 HACCP 安全、食谱流程、风味配对和烹饪菜谱集等模板。+"""++from .haccp_safety import FoodSafetyHACCPGraph+from .recipe_process import RecipeProcessGraph+from .flavor_pairing import FlavorPairingGraph+from .culinary_dish import CulinaryDishSet++__all__ = [+ "FoodSafetyHACCPGraph",+ "RecipeProcessGraph",+ "FlavorPairingGraph",+ "CulinaryDishSet",+]diff --git a/hyperextract/templates/zh/food/culinary_dish.py b/hyperextract/templates/zh/food/culinary_dish.pynew file mode 100644index 0000000..9f31448--- /dev/null+++ b/hyperextract/templates/zh/food/culinary_dish.py@@ -0,0 +1,145 @@+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.types import AutoSet++# ==============================================================================+# 1. Schema 定义+# ==============================================================================+++class CulinaryDish(BaseModel):+ """+ 菜肴条目,包括其身份、成分和烹饪特征。+ """++ name: str = Field(description="菜肴的标准名称,例如宫保鸡丁或红烧肉。")+ cuisine: Optional[str] = Field(+ None, description="烹饪传统或菜系,例如四川、法式、意大利、日式。"+ )+ region: Optional[str] = Field(+ None, description="地理原产地,例如中国四川、法国普罗旺斯。"+ )+ primary_ingredients: Optional[str] = Field(+ None,+ description="主要成分列表,例如鸡、花生、干辣椒、酱油、糖。"+ )+ protein_type: Optional[str] = Field(+ None, description="主要蛋白质或基础:鸡肉、猪肉、鱼、豆腐、蔬菜。"+ )+ flavor_profile: Optional[str] = Field(+ None,+ description="总体味道特征,例如辛辣甜蜜、香气温暖、咸香鲜美。"+ )+ cooking_method: Optional[str] = Field(+ None, description="烹饪技术,例如炒、炖、烧烤、炸、蒸。"+ )+ dietary_attributes: Optional[str] = Field(+ None,+ description="饮食特征,例如素食、无麸质、低钠、高蛋白。"+ )+ serving_suggestion: Optional[str] = Field(+ None, description="典型的供菜方式或配菜,例如配米饭和蔬菜。"+ )+ seasonal_note: Optional[str] = Field(+ None, description="季节性或时间相关性,例如冬季舒适食物、夏季开胃菜。"+ )+++# ==============================================================================+# 2. 提示词 (Prompts)+# ==============================================================================++_PROMPT = (+ "你是美食知识库管理员。从菜单、食谱甚至非结构化美食文本中提取菜肴。\n\n"+ "规则:\n"+ "- 识别每个不同的菜肴名称和变体。\n"+ "- 捕捉烹饪传统、地理原产地、主要成分。\n"+ "- 记录烹饪方法、风味特征和任何特殊属性。\n"+ "- 保持原始文本中的名称和描述。\n"+ "- 为后续去重标准化做准备(名称、成分)。"+)++# ==============================================================================+# 3. 模板类+# ==============================================================================+++class CulinaryDishSet(AutoSet[CulinaryDish]):+ """+ 适用文档: 餐厅菜单、美食博客、烹饪书籍、食材供应商列表、菜肴数据库、美食指南、社交媒体。++ 模板用于从多个来源提取和去重菜肴条目。在菜肴名称的变体(例如"宫保鸡丁"与"宫爆鸡丁")中自动融合相同的菜肴。支持菜单标准化、美食知识积累和跨文化菜肴对应。++ 使用示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> dishes = CulinaryDishSet(llm_client=llm, embedder=embedder)+ >>> menu = "1. Kung Pao Chicken - 宫保鸡丁。2. 宫爆鸡丁(四川焦糖鸡丁)"+ >>> dishes.feed_text(menu)+ >>> dishes.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ chunk_size: int = 2048,+ chunk_overlap: int = 256,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化食物菜肴集合模板。++ Args:+ llm_client (BaseChatModel): 用于提取的 LLM。+ embedder (Embeddings): 用于检索和可视化的嵌入模型。+ chunk_size (int): 每个分块的最大字符数。+ chunk_overlap (int): 分块之间的重叠。+ max_workers (int): 并行处理工作线程数。+ verbose (bool): 是否启用进度日志。+ **kwargs: AutoSet 的其他参数。+ """+ super().__init__(+ item_schema=CulinaryDish,+ key_extractor=lambda x: x.name.strip().lower(),+ llm_client=llm_client,+ embedder=embedder,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ max_workers=max_workers,+ verbose=verbose,+ prompt=_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_items_for_search: int = 10,+ top_k_items_for_chat: int = 10,+ ) -> None:+ """+ 使用 OntoSight 可视化菜肴集合。++ Args:+ top_k_items_for_search (int): 检索的菜肴数。默认 10。+ top_k_items_for_chat (int): 对话上下文中的菜肴数。默认 10。+ """++ def item_label_extractor(item: CulinaryDish) -> str:+ parts = [item.name]+ if item.cuisine:+ parts.append(f"({item.cuisine})")+ return " ".join(parts)++ super().show(+ item_label_extractor=item_label_extractor,+ top_k_items_for_search=top_k_items_for_search,+ top_k_items_for_chat=top_k_items_for_chat,+ )diff --git a/hyperextract/templates/zh/food/flavor_pairing.py b/hyperextract/templates/zh/food/flavor_pairing.pynew file mode 100644index 0000000..dc74825--- /dev/null+++ b/hyperextract/templates/zh/food/flavor_pairing.py@@ -0,0 +1,187 @@+from typing import Optional, Any, Literal+from pydantic import BaseModel, Field+from langchain_core.language_models.chat_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoGraph++# ==============================================================================+# 1. Schema 定义+# ==============================================================================+++class FlavorComponent(BaseModel):+ """+ 个别风味分子或复合物及其性质。+ """++ name: str = Field(description="风味成分的名称,例如木质素、硫含物、咖啡因。")+ component_type: str = Field(+ description="分类:分子、香气、甜味、苦味、酸味、鲜味、油质、烤焙、花卉。"+ )+ description: str = Field(+ description="来自文本的成分特征,例如温暖、烟熏、柔和的甜味。"+ )+++class FlavorRelationship(BaseModel):+ """+ 两个风味成分之间的关系。+ """++ source_component: str = Field(description="第一个风味成分的名称。")+ target_component: str = Field(description="第二个风味成分的名称。")+ relationship_type: Literal[+ "Contains", "Pairs_Well", "Confirms", "Complements", "Contrasts"+ ] = Field(+ description="关系类型:Contains(包含)、Pairs_Well(配对好)、Confirms(确认)、Complements(补充)、Contrasts(对比)。"+ )+ pairing_mechanism: Optional[str] = Field(+ None,+ description="为什么这两个成分会一起工作,例如共享的木质素分子或互补的甜度曲线。"+ )+ pairing_quality: Optional[str] = Field(+ None, description="配对质量的评估:优秀、好、可接受、有冲突。"+ )+ culinary_context: Optional[str] = Field(+ None, description='应用这个配对的烹饪环境或菜肴,例如"法式高汤"或"甜点"。'+ )+++# ==============================================================================+# 2. 提示词 (Prompts)+# ==============================================================================++_PROMPT = (+ "你是美食科学家。从美食科学论文中提取风味配对和感官关系。\n\n"+ "规则:\n"+ "- 识别个别风味分子和复合物。\n"+ "- 链接配对好的成分和为什么它们有效。\n"+ "- 提取描述性术语(温暖、烟熏、花卉等)。\n"+ "- 关注共享分子或感官相补性的机制。\n"+ "- 记录烹饪环境(酱料、甜点、肉类等)。"+)++_NODE_PROMPT = (+ "你是美食科学家。从食品科学论文或菜谱中提取所有风味成分(节点)。\n\n"+ "提取规则:\n"+ "- 列出所有提到的风味分子、香气或感官特征。\n"+ "- 分类为 molecules、aromas、tastes、textures 等。\n"+ "- 包括来自源文本的描述性特征(工作、柔软、复杂)。\n"+ "- 不包括有关如何将成分配对的信息。\n"+ "- 此阶段保持所有成分作为独立实体。"+)++_EDGE_PROMPT = (+ "你是美食科学家。给定一个成分列表,识别哪些成分配对好(边),以及为什么。\n\n"+ "配对规则:\n"+ "- 连接列表中存在的成分。\n"+ "- 说明配对机制(共享分子、互补风味)。\n"+ "- 评评对质量(优秀、好、可接受、冲突)。\n"+ "- 记录烹饪应用(什么菜肴、什么菜系)。\n"+ "- 来自源文本中的链接只存在于显式提及的成分。"+)++# ==============================================================================+# 3. 模板类+# ==============================================================================+++class FlavorPairingGraph(AutoGraph[FlavorComponent, FlavorRelationship]):+ """+ 适用文档: 美食科学期刊、经验烹饪书、感官评估报告、风味科学研究、菜单设计指南、R&D 笔记。++ 模板用于从感官和分子证据中提取风味配对知识。支持菜单创新、厨师培训和结构化食物组合理论。++ 使用示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> flavors = FlavorPairingGraph(llm_client=llm, embedder=embedder)+ >>> text = "草莓和黑胡椒通过共有的木质素分子进行配对"+ >>> flavors.feed_text(text)+ >>> flavors.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "one_stage",+ chunk_size: int = 2048,+ chunk_overlap: int = 256,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化风味配对图谱模板。++ Args:+ llm_client (BaseChatModel): 用于提取的 LLM。+ embedder (Embeddings): 用于去重的嵌入模型。+ extraction_mode (str): "one_stage" 或 "two_stage"。+ chunk_size (int): 每个分块的最大字符数。+ chunk_overlap (int): 分块之间的重叠。+ max_workers (int): 并行处理工作线程数。+ verbose (bool): 是否启用进度日志。+ **kwargs: AutoGraph 的其他参数。+ """+ super().__init__(+ node_schema=FlavorComponent,+ edge_schema=FlavorRelationship,+ node_key_extractor=lambda x: x.name.strip().lower(),+ edge_key_extractor=lambda x: (+ x.source_component.strip().lower(),+ x.target_component.strip().lower(),+ ),+ nodes_in_edge_extractor=lambda x: (+ x.source_component.strip(),+ x.target_component.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=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ top_k_nodes_for_search: int = 5,+ top_k_edges_for_search: int = 5,+ top_k_nodes_for_chat: int = 5,+ top_k_edges_for_chat: int = 5,+ ) -> None:+ """+ 使用 OntoSight 可视化风味配对网络。++ Args:+ top_k_nodes_for_search (int): 检索的成分数。默认 5。+ top_k_edges_for_search (int): 检索的配对数。默认 5。+ top_k_nodes_for_chat (int): 对话上下文中的成分数。默认 5。+ top_k_edges_for_chat (int): 对话上下文中的配对数。默认 5。+ """++ def node_label_extractor(node: FlavorComponent) -> str:+ return f"{node.name} ({node.component_type})"++ def edge_label_extractor(edge: FlavorRelationship) -> str:+ quality = f" [{edge.pairing_quality}]" if edge.pairing_quality else ""+ return f"{edge.relationship_type}{quality}"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_nodes_for_search,+ top_k_edges_for_search=top_k_edges_for_search,+ top_k_nodes_for_chat=top_k_nodes_for_chat,+ top_k_edges_for_chat=top_k_edges_for_chat,+ )diff --git a/hyperextract/templates/zh/food/haccp_safety.py b/hyperextract/templates/zh/food/haccp_safety.pynew file mode 100644index 0000000..7d4b3f0--- /dev/null+++ b/hyperextract/templates/zh/food/haccp_safety.py@@ -0,0 +1,202 @@+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.types import AutoGraph++# ==============================================================================+# 1. Schema 定义+# ==============================================================================+++class BiologicalHazard(BaseModel):+ """+ 在食品生产中必须控制的生物学危害。+ """++ name: str = Field(+ description='危害病原体名称,例如"沙门氏菌"、"单核细胞增生李斯特菌"、"O157:H7 大肠杆菌"等。'+ )+ hazard_type: str = Field(+ description='类型:"细菌"、"病毒"、"寄生虫"、"真菌"。'+ )+ health_consequence: Optional[str] = Field(+ None, description='潜在健康影响,例如"严重肠胃炎"、"败血症"等。'+ )+++class CriticalControlPoint(BaseModel):+ """+ 食品生产中可以控制危害的步骤或工序。+ """++ name: str = Field(+ description='CCP 名称,例如"巴氏杀菌"、"金属检测"、"冷藏"等。'+ )+ process_stage: str = Field(+ description='生产阶段:"原料"、"收货"、"加工"、"烹饪"、"冷却"、"包装"、"储存"。'+ )+ description: Optional[str] = Field(+ None, description="CCP 的详细描述。"+ )+++class ControlMeasure(BaseModel):+ """+ 连接危害和 CCP 的控制措施。+ """++ source: str = Field(description="生物学危害名称。")+ target: str = Field(description="CCP 名称。")+ critical_limit: str = Field(+ description='定义安全/不安全分界线的关键限值,例如">=72°C 持续 >=15 秒"、"pH < 4.6"等。'+ )+ monitoring_procedure: str = Field(+ description='如何监测 CCP,例如"每批次温度计读数"、"每天 pH 计测量"等。'+ )+ monitoring_frequency: str = Field(+ description='监测频率,例如"每 2 小时"、"每批次"、"每天"等。'+ )+ corrective_action: str = Field(+ description='如果不达到关键限值的行动,例如"销毁产品"、"重新加工"、"警报 QA"等。'+ )+ verification: Optional[str] = Field(+ None, description='验证有效性的方法,例如"每月进行培养测试"等。'+ )+++# ==============================================================================+# 2. 提示词 (Prompts)+# ==============================================================================++_PROMPT = (+ "你是食品安全专家,熟悉 HACCP 原则。从 HACCP 计划和食品安全文件中提取危害、关键控制点及其控制措施。\n\n"+ "规则:\n"+ "- 识别与产品和工序相关的生物学危害。\n"+ "- 识别可以消除或控制危害的 CCP。\n"+ "- 提取关键限值、监测程序和纠偏行动。\n"+ "- 确保每个 CCP 链接到它控制的具体危害。"+)++_NODE_PROMPT = (+ "你是食品安全专家。从 HACCP 文件中提取所有危害和 CCP(节点)。\n\n"+ "提取规则:\n"+ "- 识别所有提及的生物学危害(病原体、过敏原如适用)。\n"+ "- 识别所有 CCP(烹饪、冷却、金属检测阶段)。\n"+ "- 按类型对每个危害进行分类(细菌、病毒、真菌、寄生虫)。\n"+ "- 按生产阶段对每个 CCP 进行分类。\n"+ "- 此阶段不建立控制关系。"+)++_EDGE_PROMPT = (+ "你是食品安全专家。在获得危害和 CCP 清单的基础上,提取控制关系(边)。\n\n"+ "提取规则:\n"+ "- 将每个危害连接到控制它的 CCP。\n"+ "- 提取具有精确阈值和单位的关键限值。\n"+ "- 从 HACCP 文件中提取监测程序和频率。\n"+ "- 提取超过限值时应采取的纠偏行动。\n"+ "- 在有文件记录时包括验证方法。\n"+ "- 仅在提供的列表中存在的危害和 CCP 之间创建边。"+)++# ==============================================================================+# 3. 模板类+# ==============================================================================+++class FoodSafetyHACCPGraph(AutoGraph[BiologicalHazard, ControlMeasure]):+ """+ 适用文档: HACCP 计划、食品安全计划(ISO 22000)、SOP 手册、FDA 指导文件、食品公司质量规程、供应商审计报告。++ 模板用于系统地从基于 HACCP 的食品安全控制中提取和结构化信息。支持合规验证、供应商审计和整个食品生产运营中的持续安全监测。++ 使用示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> haccp = FoodSafetyHACCPGraph(llm_client=llm, embedder=embedder)+ >>> plan = "关键控制点:巴氏杀菌。危害:沙门氏菌。关键限值:72°C 持续 15 秒..."+ >>> haccp.feed_text(plan)+ >>> haccp.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "one_stage",+ chunk_size: int = 2048,+ chunk_overlap: int = 256,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化食品安全 HACCP 图谱模板。++ Args:+ llm_client (BaseChatModel): 用于危害和控制提取的 LLM。+ embedder (Embeddings): 用于去重的嵌入模型。+ extraction_mode (str): "one_stage" 或 "two_stage"。+ chunk_size (int): 每个分块的最大字符数。+ chunk_overlap (int): 分块之间的重叠。+ max_workers (int): 并行处理工作线程数。+ verbose (bool): 是否启用进度日志。+ **kwargs: AutoGraph 的其他参数。+ """+ super().__init__(+ node_schema=BiologicalHazard,+ edge_schema=ControlMeasure,+ node_key_extractor=lambda x: x.name.strip().lower(),+ edge_key_extractor=lambda x: (+ f"{x.source.strip()}--({x.target.strip()}): {x.critical_limit.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=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ 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:+ """+ 使用 OntoSight 可视化食品安全控制图。++ Args:+ top_k_nodes_for_search (int): 检索的危害/CCP 数。默认 3。+ top_k_edges_for_search (int): 检索的控制措施数。默认 3。+ top_k_nodes_for_chat (int): 对话上下文中的节点数。默认 3。+ top_k_edges_for_chat (int): 对话上下文中的边数。默认 3。+ """++ def node_label_extractor(node: BiologicalHazard) -> str:+ if isinstance(node, BiologicalHazard):+ return f"{node.name} ({node.hazard_type})"+ return str(node)++ def edge_label_extractor(edge: ControlMeasure) -> str:+ return f"{edge.critical_limit}"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_nodes_for_search,+ top_k_edges_for_search=top_k_edges_for_search,+ top_k_nodes_for_chat=top_k_nodes_for_chat,+ top_k_edges_for_chat=top_k_edges_for_chat,+ )diff --git a/hyperextract/templates/zh/food/recipe_process.py b/hyperextract/templates/zh/food/recipe_process.pynew file mode 100644index 0000000..0ec0aed--- /dev/null+++ b/hyperextract/templates/zh/food/recipe_process.py@@ -0,0 +1,192 @@+from typing import List, Optional, Any+from pydantic import BaseModel, Field+from langchain_core.language_models.chat_models import BaseChatModel+from langchain_core.embeddings import Embeddings+from hyperextract.types import AutoTemporalGraph++# ==============================================================================+# 1. Schema 定义+# ==============================================================================+++class IngredientState(BaseModel):+ """+ 食材/材料在食谱工序特定阶段的状态。+ """++ name: str = Field(+ description="状态描述符,例如混合液、加热面团、冷却浆液。"+ )+ composition: str = Field(+ description="这个状态中的物质,例如蛋+糖、面粉+水+盐。"+ )+ physical_state: Optional[str] = Field(+ None, description="物理形态:液体、固体、粉末、面团、乳液、泡沫。"+ )+++class ProcessingStep(BaseModel):+ """+ 连接两个食材状态的转换步骤。+ """++ step_id: str = Field(description="步骤标识符,例如步骤 1、1.1、混合。")+ source_state: str = Field(description="开始时的食材状态。")+ target_state: str = Field(description="加工后的食材状态。")+ action: str = Field(+ description="加工动作,例如混合、加热、冷却、静置、揉搓、发酵。"+ )+ duration: str = Field(+ description="动作持续时间,例如10分钟、2小时、一夜、15秒。"+ )+ temperature: Optional[str] = Field(+ None, description="温度设置(如适用),例如175°C、室温、4°C。"+ )+ equipment: Optional[str] = Field(+ None, description="使用的设备,例如台式搅拌机、烤箱、水浴、温度计。"+ )+ parameters: Optional[str] = Field(+ None,+ description="其他参数(速度、压力等),例如中等速度、200 PSI。"+ )+ notes: Optional[str] = Field(+ None, description='特殊说明或观察,例如"应形成轻微奶油状"。'+ )+++# ==============================================================================+# 2. 提示词 (Prompts)+# ==============================================================================++_PROMPT = (+ "你是专业厨师和食品科学家。从配方单和 SOP 中提取分步食谱或工业食品生产工序。\n\n"+ "规则:\n"+ "- 识别每个不同的加工动作和转换。\n"+ "- 提取每个步骤前后的食材状态。\n"+ "- 精确捕捉时间、温度和设备。\n"+ "- 保持严格的顺序(步骤 1 -> 步骤 2 等)。\n"+ "- 包括关于质地、外观或感官线索的说明。"+)++_NODE_PROMPT = (+ "你是专业厨师和食品科学家。从食谱中提取所有食材状态(节点)。\n\n"+ "提取规则:\n"+ "- 识别食谱中的不同状态/阶段(原始、混合、加热、冷却、静置)。\n"+ "- 描述每个状态下存在的食材。\n"+ "- 记录物理形态(液体、固体、面团等)。\n"+ "- 保持源文本中的确切名称和描述。\n"+ "- 此阶段不描述状态之间的动作或转换。"+)++_EDGE_PROMPT = (+ "你是专业厨师。在获得食材状态清单的基础上,提取将一个状态转换为另一个状态的加工步骤(边)。\n\n"+ "提取规则:\n"+ "- 将每个源状态连接到其目标状态,说明具体动作。\n"+ "- 提取每个步骤的时间、温度和设备。\n"+ "- 提取任何特殊参数(速度、压力)或感官线索。\n"+ "- 保持严格的步骤顺序(步骤 1、步骤 2 等)。\n"+ "- 仅连接提供列表中存在的状态。"+)++# ==============================================================================+# 3. 模板类+# ==============================================================================+++class RecipeProcessGraph(AutoTemporalGraph[IngredientState, ProcessingStep]):+ """+ 适用文档: 工业配方单、食谱 SOP、食品科学研究、生产批记录、厨师食谱、烹饪手册、R&D 实验规程。++ 模板用于提取和映射具有精确时间和参数的顺序食品生产工序。支持食谱标准化、工序优化以及烹饪和工业食品环境中的知识转移。++ 使用示例:+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings+ >>> llm = ChatOpenAI(model="gpt-4o")+ >>> embedder = OpenAIEmbeddings()+ >>> recipe = RecipeProcessGraph(llm_client=llm, embedder=embedder)+ >>> process = "步骤 1:将蛋和糖混合 5 分钟。步骤 2:加热至 175°C"+ >>> recipe.feed_text(process)+ >>> recipe.show()+ """++ def __init__(+ self,+ llm_client: BaseChatModel,+ embedder: Embeddings,+ *,+ extraction_mode: str = "one_stage",+ chunk_size: int = 2048,+ chunk_overlap: int = 256,+ max_workers: int = 10,+ verbose: bool = False,+ **kwargs: Any,+ ):+ """+ 初始化食谱工序图谱模板。++ Args:+ llm_client (BaseChatModel): 用于状态和步骤提取的 LLM。+ embedder (Embeddings): 用于去重的嵌入模型。+ extraction_mode (str): "one_stage" 或 "two_stage"。+ chunk_size (int): 每个分块的最大字符数。+ chunk_overlap (int): 分块之间的重叠。+ max_workers (int): 并行处理工作线程数。+ verbose (bool): 是否启用进度日志。+ **kwargs: AutoTemporalGraph 的其他参数。+ """+ super().__init__(+ node_schema=IngredientState,+ edge_schema=ProcessingStep,+ node_key_extractor=lambda x: x.name.strip().lower(),+ edge_key_extractor=lambda x: x.step_id.strip(),+ nodes_in_edge_extractor=lambda x: (+ x.source_state.strip(),+ x.target_state.strip(),+ ),+ time_in_edge_extractor=lambda x: x.step_id.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=_PROMPT,+ prompt_for_node_extraction=_NODE_PROMPT,+ prompt_for_edge_extraction=_EDGE_PROMPT,+ **kwargs,+ )++ def show(+ self,+ *,+ 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:+ """+ 使用 OntoSight 可视化食谱工序时间线。++ Args:+ 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。+ """++ def node_label_extractor(node: IngredientState) -> str:+ return f"{node.name} ({node.physical_state if node.physical_state else '未知'})"++ def edge_label_extractor(edge: ProcessingStep) -> str:+ temp = f" {edge.temperature}" if edge.temperature else ""+ return f"{edge.action} ({edge.duration}){temp}"++ super().show(+ node_label_extractor=node_label_extractor,+ edge_label_extractor=edge_label_extractor,+ top_k_nodes_for_search=top_k_nodes_for_search,+ top_k_edges_for_search=top_k_edges_for_search,+ top_k_nodes_for_chat=top_k_nodes_for_chat,+ top_k_edges_for_chat=top_k_edges_for_chat,+ )