Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.
feat: 添加中文示例文件和相关模板
yifanfeng97f67527ef7154
diff --git a/examples/README.md b/examples/README.mdindex 9ecf92e..fb1f135 100644--- a/examples/README.md+++ b/examples/README.md@@ -1,133 +1,88 @@# Hyper-Extract Examples-本目录包含 Hyper-Extract 的各种使用示例,按功能分为三个子目录。+Examples directory with bilingual demos (English & Chinese).-## 目录结构+## Quick Start-```-examples/-├── inputs/ # 统一的输入数据目录-│ ├── sci_fi_story.md # 科幻故事(用于 methods/ 系列演示)-│ └── mmorpg_guild_drama.md # 游戏公会剧情(用于 types/ 系列演示)-│-├── methods/ # 方法演示(Method-based Extraction)-│ ├── light_rag_demo.py # LightRAG 方法-│ ├── graph_rag_demo.py # GraphRAG 方法-│ ├── hyper_rag_demo.py # HyperRAG 方法-│ ├── hypergraph_rag_demo.py # HyperGraph-RAG 方法-│ ├── cog_rag_demo.py # CogRAG 方法-│ ├── atom_demo.py # Atom 时序知识图谱方法-│ ├── itext2kg_demo.py # iText2KG 方法-│ ├── itext2kg_star_demo.py # iText2KG-Star 方法-│ └── kg_gen_demo.py # KG-Gen 方法-│-├── types/ # 类型演示(AutoType Extraction)-│ ├── graph_demo.py # AutoGraph 图谱提取-│ ├── hypergraph_demo.py # AutoHypergraph 超图提取-│ ├── list_demo.py # AutoList 列表提取-│ ├── model_demo.py # AutoModel 模型提取-│ ├── set_demo.py # AutoSet 集合提取-│ ├── temporal_graph_demo.py # AutoTemporalGraph 时序图提取-│ ├── spatial_graph_demo.py # AutoSpatialGraph 空间图提取-│ └── spatio_temporal_graph_demo.py # AutoSpatioTemporalGraph 时空图提取-│-└── templates/ # 模板演示(Preset Template Testing)- ├── templates_mapping.yaml # 模板与测试数据映射表- ├── base_template.py # 基础模板测试框架- ├── finance_demo.py # Finance 领域模板测试- ├── general_demo.py # General 领域模板测试- ├── industry_demo.py # Industry 领域模板测试- ├── legal_demo.py # Legal 领域模板测试- ├── medicine_demo.py # Medicine 领域模板测试- └── tcm_demo.py # TCM 领域模板测试-```--## 快速开始--### 方法演示(Methods)--方法演示展示了不同的知识提取策略:+### English Demos```bash-# LightRAG 方法-python examples/methods/light_rag_demo.py--# GraphRAG 方法-python examples/methods/graph_rag_demo.py--# HyperRAG 方法(支持超边)-python examples/methods/hyper_rag_demo.py--# Atom 时序知识图谱-python examples/methods/atom_demo.py+cd examples+python en/autotypes/graph_demo.py```-### 类型演示(Types)--类型演示展示了不同的知识表示类型:+### 中文示例```bash-# 图谱提取-python examples/types/graph_demo.py--# 超图提取-python examples/types/hypergraph_demo.py+cd examples+python zh/autotypes/graph_demo.py+```-# 时序图谱-python examples/types/temporal_graph_demo.py+## Directory Structure-# 空间图谱-python examples/types/spatial_graph_demo.py+```+examples/+├── README.md+├── en/ # English demos+│ ├── tesla.md # Tesla biography data+│ ├── tesla_question.md # Query questions+│ ├── autotypes/ # AutoType demos+│ │ ├── graph_demo.py # Knowledge graph+│ │ ├── list_demo.py # List extraction+│ │ ├── set_demo.py # Set extraction+│ │ ├── model_demo.py # Model extraction+│ │ ├── temporal_demo.py # Temporal graph+│ │ ├── spatial_demo.py # Spatial graph+│ │ ├── spatio_temporal_demo.py # Spatio-temporal+│ │ └── hypergraph_demo.py # Hypergraph+│ ├── methods/ # RAG method demos+│ └── templates/ # Template demos+│+└── zh/ # Chinese demos+ ├── sushi.md # Su Shi biography data+ ├── sushi_question.md # Query questions+ ├── autotypes/ # AutoType demos+ ├── methods/ # RAG method demos+ └── templates/ # Template demos```-### 模板演示(Templates)--模板演示使用预设模板测试对应的测试数据:+## AutoType Demos++Each demo showcases a specific extraction type:++| Demo | Description |+|------|-------------|+| `graph_demo.py` | Extract entities & relationships (knowledge graph) |+| `list_demo.py` | Extract list of items |+| `set_demo.py` | Extract deduplicated set |+| `model_demo.py` | Extract structured summary |+| `temporal_demo.py` | Extract temporal relationships |+| `spatial_demo.py` | Extract spatial relationships |+| `spatio_temporal_demo.py` | Extract both time & space |+| `hypergraph_demo.py` | Extract multi-entity relationships |++## Data Files++### Tesla (en/tesla.md)+Nikola Tesla biography (1856-1943):+- Early life & education+- Work with Edison+- War of Currents+- Colorado Springs experiments+- Wardenclyffe Tower++### Su Shi (zh/sushi.md)+苏轼传记 (1037-1101):+- 早年与家学+- 仕途与起伏+- 乌台诗案+- 与佛印的友谊+- 杭州岁月+- 晚年与贬谪++## Requirements```bash-# 查看 Finance 领域可用的模板-python examples/templates/finance_demo.py--# 测试特定模板-python examples/templates/finance_demo.py earnings_summary-python examples/templates/general_demo.py base_graph+pip install hyperextract langchain-openai python-dotenv+export OPENAI_API_KEY=your-key```--## 输入数据--所有演示使用的输入数据统一存放在 `inputs/` 目录:--| 文件 | 用途 | 对应演示 |-|------|------|---------|-| `inputs/sci_fi_story.md` | 科幻故事 | methods/ 系列演示 |-| `inputs/mmorpg_guild_drama.md` | 游戏公会剧情 | types/graph_demo.py |--模板测试使用的详细测试数据位于 `tests/test_data/zh/` 目录,详见 `templates/templates_mapping.yaml`。--## 模板领域--Hyper-Extract 提供以下领域的预设模板:--| 领域 | 模板数量 | 测试数据目录 |-|------|---------|------------|-| Finance | 5 | `tests/test_data/zh/finance/` |-| General | 11 | `tests/test_data/zh/general/` |-| Industry | 5 | `tests/test_data/zh/industry/` |-| Legal | 5 | `tests/test_data/zh/legal/` |-| Medicine | 5 | `tests/test_data/zh/medicine/` |-| TCM | 5 | `tests/test_data/zh/tcm/` |--## 常见问题--### Q: 如何添加新的输入数据?--将数据文件放入 `examples/inputs/` 目录下的相应子目录,然后在示例文件中更新 `INPUT_FILE` 路径。--### Q: 如何测试新的模板?--1. 在 `templates/templates_mapping.yaml` 中添加模板与测试数据的映射-2. 运行对应的领域测试文件验证--### Q: 为什么某些模板测试文件没有运行实际提取?--模板测试框架目前提供模板和数据的加载与预览功能。完整的模板执行需要结合 `hyperextract` 的模板引擎。diff --git a/examples/en/autotypes/graph_demo.py b/examples/en/autotypes/graph_demo.pynew file mode 100644index 0000000..8f7d35f--- /dev/null+++ b/examples/en/autotypes/graph_demo.py@@ -0,0 +1,73 @@+"""+Graph Extraction Demo - Tesla Biography++Extract entities and relationships from text using AutoGraph.+This demo shows how to build a knowledge graph from unstructured text.++Usage:+ python examples/en/autotypes/graph_demo.py+"""++import sys+from pathlib import Path+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+import dotenv++dotenv.load_dotenv()++from pydantic import BaseModel, Field+from hyperextract.types import AutoGraph+++class Entity(BaseModel):+ """Entity in the knowledge graph"""+ name: str = Field(description="Entity name")+ type: str = Field(description="Entity type: person/location/invention", default="person")+++class Relation(BaseModel):+ """Relation between entities"""+ source: str = Field(description="Source entity")+ target: str = Field(description="Target entity")+ type: str = Field(description="Relation type: employer/partner/rival/invented")+++def main():+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")++ input_file = Path(__file__).parent.parent.parent / "en" / "tesla.md"+ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("\n" + "=" * 60)+ print(" Graph Extraction Demo")+ print("=" * 60)+ print("Extracting entities and relationships from Tesla's biography...")++ graph = AutoGraph[Entity, Relation](+ node_schema=Entity,+ edge_schema=Relation,+ llm_client=llm,+ embedder=embedder,+ )++ graph.feed_text(text)++ print(f"\nExtracted {len(graph.nodes)} entities and {len(graph.edges)} relations")++ graph.build_index()++ for q in [+ "What are Tesla's major inventions?",+ "What was the War of Currents?",+ "Tesla's relationship with Edison",+ ]:+ print(f"\nQuery: {q}")+ nodes, edges = graph.search(q, top_k_nodes=3, top_k_edges=3)+ print(f" Entities: {[n.name for n in nodes]}")+ print(f" Relations: {[e.type for e in edges]}")+++if __name__ == "__main__":+ main()diff --git a/examples/en/autotypes/hypergraph_demo.py b/examples/en/autotypes/hypergraph_demo.pynew file mode 100644index 0000000..d02dde3--- /dev/null+++ b/examples/en/autotypes/hypergraph_demo.py@@ -0,0 +1,72 @@+"""+Hypergraph Demo - Tesla Biography++Extract hyper-relationships from text using AutoHyperGraph.+This demo shows how to capture multi-entity relationships.++Usage:+ python examples/en/autotypes/hypergraph_demo.py+"""++import sys+from pathlib import Path+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+import dotenv++dotenv.load_dotenv()++from pydantic import BaseModel, Field+from hyperextract.types import AutoHyperGraph+++class Entity(BaseModel):+ """Entity node"""+ name: str = Field(description="Entity name")+ type: str = Field(description="Type: person/location/invention", default="person")+++class HyperEdge(BaseModel):+ """Hyper-edge (multi-entity relationship)"""+ description: str = Field(description="Relationship description")+ members: list[str] = Field(description="Entities involved")+ type: str = Field(description="Relationship type")+++def main():+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")++ input_file = Path(__file__).parent.parent.parent / "en" / "tesla.md"+ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("\n" + "=" * 60)+ print(" Hypergraph Demo")+ print("=" * 60)+ print("Extracting multi-entity relationships...")++ graph = AutoHyperGraph[Entity, HyperEdge](+ node_schema=Entity,+ edge_schema=HyperEdge,+ llm_client=llm,+ embedder=embedder,+ )++ graph.feed_text(text)++ print(f"\nExtracted {len(graph.nodes)} entities and {len(graph.edges)} hyper-edges")++ for edge in graph.edges[:5]:+ print(f"\n{edge.type}: {edge.description}")+ print(f" Members: {', '.join(edge.members)}")++ graph.build_index()++ for q in ["War of Currents", "inventions", "collaboration"]:+ print(f"\nQuery: {q}")+ nodes, edges = graph.search(q, top_k_nodes=3, top_k_edges=3)+ print(f" Found {len(edges)} related hyper-edges")+++if __name__ == "__main__":+ main()diff --git a/examples/en/autotypes/list_demo.py b/examples/en/autotypes/list_demo.pynew file mode 100644index 0000000..2dbfdc9--- /dev/null+++ b/examples/en/autotypes/list_demo.py@@ -0,0 +1,66 @@+"""+AutoList Demo - Tesla Timeline++Extract a list of items from text using AutoList.+This demo shows how to extract and merge items from multiple chunks.++Usage:+ python examples/en/autotypes/list_demo.py+"""++import sys+from pathlib import Path+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+import dotenv++dotenv.load_dotenv()++from pydantic import BaseModel, Field+from hyperextract import AutoList+++class TimelineEvent(BaseModel):+ """Timeline event"""+ year: str = Field(description="Year of the event")+ title: str = Field(description="Event title")+ description: str = Field(description="Event description")+++def main():+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")++ input_file = Path(__file__).parent.parent.parent / "en" / "tesla.md"+ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("\n" + "=" * 60)+ print(" AutoList Demo - Tesla Timeline")+ print("=" * 60)+ print("Extracting timeline events...")++ timeline = AutoList[TimelineEvent](+ item_schema=TimelineEvent,+ llm_client=llm,+ embedder=embedder,+ )++ timeline.feed_text(text)++ sorted_events = sorted(timeline.items, key=lambda x: x.year)+ print(f"\nExtracted {len(sorted_events)} events")++ for event in sorted_events[:5]:+ print(f" {event.year}: {event.title}")++ timeline.build_index()++ for q in ["inventions", "Edison", "Colorado Springs"]:+ print(f"\nQuery: {q}")+ results = timeline.search(q, top_k=3)+ for r in results:+ print(f" {r.year}: {r.title}")+++if __name__ == "__main__":+ main()diff --git a/examples/en/autotypes/model_demo.py b/examples/en/autotypes/model_demo.pynew file mode 100644index 0000000..7fcda3c--- /dev/null+++ b/examples/en/autotypes/model_demo.py@@ -0,0 +1,77 @@+"""+AutoModel Demo - Tesla Biography Summary++Extract a structured summary from text using AutoModel.+This demo shows how to merge multiple chunks into one consistent object.++Usage:+ python examples/en/autotypes/model_demo.py+"""++import sys+from pathlib import Path+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+import dotenv++dotenv.load_dotenv()++from pydantic import BaseModel, Field+from typing import List, Optional+from hyperextract import AutoModel+++class BiographySummary(BaseModel):+ """Biography summary schema"""+ title: str = Field(description="Title of the biography")+ subject: str = Field(description="Main subject name")+ birth_year: Optional[str] = Field(default="", description="Year of birth")+ death_year: Optional[str] = Field(default="", description="Year of death")+ nationality: str = Field(description="Nationality", default="")+ occupation: List[str] = Field(default_factory=list, description="Main occupations")+ summary: str = Field(description="Brief summary")+ major_inventions: List[str] = Field(default_factory=list, description="Major inventions")+++def main():+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")++ input_file = Path(__file__).parent.parent.parent / "en" / "tesla.md"+ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("\n" + "=" * 60)+ print(" AutoModel Demo - Tesla Summary")+ print("=" * 60)+ print("Extracting biography summary...")++ model = AutoModel(+ data_schema=BiographySummary,+ llm_client=llm,+ embedder=embedder,+ )++ model.feed_text(text)++ data = model.data+ print(f"\nSubject: {data.subject}")+ print(f"Lifespan: {data.birth_year} - {data.death_year}")+ print(f"Nationality: {data.nationality}")+ print(f"\nSummary: {data.summary}")++ if data.major_inventions:+ print(f"\nMajor Inventions:")+ for inv in data.major_inventions[:3]:+ print(f" - {inv}")++ model.build_index()++ for q in ["inventions", "Edison", "legacy"]:+ print(f"\nQuery: {q}")+ results = model.search(q, top_k=2)+ for r in results:+ print(f" {r}")+++if __name__ == "__main__":+ main()diff --git a/examples/en/autotypes/set_demo.py b/examples/en/autotypes/set_demo.pynew file mode 100644index 0000000..3102988--- /dev/null+++ b/examples/en/autotypes/set_demo.py@@ -0,0 +1,72 @@+"""+AutoSet Demo - Tesla Related Entities++Extract a deduplicated set of entities from text using AutoSet.+This demo shows how to extract and deduplicate entities based on unique keys.++Usage:+ python examples/en/autotypes/set_demo.py+"""++import sys+from pathlib import Path+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+import dotenv++dotenv.load_dotenv()++from pydantic import BaseModel, Field+from hyperextract import AutoSet+++class Entity(BaseModel):+ """Entity with unique key"""+ name: str = Field(description="Entity name")+ category: str = Field(description="Category: person/location/invention", default="person")+ description: str = Field(description="Brief description", default="")+++def main():+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")++ input_file = Path(__file__).parent.parent.parent / "en" / "tesla.md"+ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("\n" + "=" * 60)+ print(" AutoSet Demo - Tesla Entities")+ print("=" * 60)+ print("Extracting and deduplicating entities...")++ entities = AutoSet[Entity](+ item_schema=Entity,+ llm_client=llm,+ embedder=embedder,+ key_extractor=lambda x: x.name,+ )++ entities.feed_text(text)++ print(f"\nExtracted {len(entities.items)} unique entities")++ categories = {}+ for e in entities.items:+ categories.setdefault(e.category, []).append(e)++ for cat, items in sorted(categories.items()):+ print(f"\n{cat.upper()}:")+ for item in items[:5]:+ print(f" - {item.name}")++ entities.build_index()++ for q in ["Edison", "inventions", "Westinghouse"]:+ print(f"\nQuery: {q}")+ results = entities.search(q, top_k=3)+ for r in results:+ print(f" {r.name} ({r.category})")+++if __name__ == "__main__":+ main()diff --git a/examples/en/autotypes/spatial_demo.py b/examples/en/autotypes/spatial_demo.pynew file mode 100644index 0000000..9d39b9e--- /dev/null+++ b/examples/en/autotypes/spatial_demo.py@@ -0,0 +1,73 @@+"""+Spatial Graph Demo - Tesla Biography++Extract spatial relationships from text using AutoSpatialGraph.+This demo shows how to understand location-based relationships.++Usage:+ python examples/en/autotypes/spatial_demo.py+"""++import sys+from pathlib import Path+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+import dotenv++dotenv.load_dotenv()++from pydantic import BaseModel, Field+from hyperextract.types import AutoSpatialGraph+++class Location(BaseModel):+ """Location entity"""+ name: str = Field(description="Location name")+ category: str = Field(description="Category: university/corporate/historical", default="historical")+ description: str = Field(description="Brief description", default="")+++class SpatialRelation(BaseModel):+ """Spatial relationship"""+ source: str = Field(description="Source location")+ target: str = Field(description="Target location")+ relation: str = Field(description="Spatial relationship type")+++def main():+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")++ input_file = Path(__file__).parent.parent.parent / "en" / "tesla.md"+ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("\n" + "=" * 60)+ print(" Spatial Graph Demo")+ print("=" * 60)+ print("Extracting spatial relationships...")++ graph = AutoSpatialGraph[Location, SpatialRelation](+ node_schema=Location,+ edge_schema=SpatialRelation,+ llm_client=llm,+ embedder=embedder,+ observation_location="United States",+ )++ graph.feed_text(text)++ print(f"\nExtracted {len(graph.nodes)} locations and {len(graph.edges)} relations")++ for node in graph.nodes[:5]:+ print(f" {node.name}")++ graph.build_index()++ for q in ["New York", "Colorado Springs", "labs"]:+ print(f"\nQuery: {q}")+ nodes, edges = graph.search(q, top_k_nodes=3, top_k_edges=3)+ print(f" Locations: {[n.name for n in nodes]}")+++if __name__ == "__main__":+ main()diff --git a/examples/en/autotypes/spatio_temporal_demo.py b/examples/en/autotypes/spatio_temporal_demo.pynew file mode 100644index 0000000..1c49f0b--- /dev/null+++ b/examples/en/autotypes/spatio_temporal_demo.py@@ -0,0 +1,78 @@+"""+Spatio-Temporal Graph Demo - Tesla Biography++Extract spatio-temporal relationships using AutoSpatioTemporalGraph.+This demo shows how to understand both time and space together.++Usage:+ python examples/en/autotypes/spatio_temporal_demo.py+"""++import sys+from pathlib import Path+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+import dotenv++dotenv.load_dotenv()++from pydantic import BaseModel, Field+from typing import Optional+from hyperextract.types import AutoSpatioTemporalGraph+++class Entity(BaseModel):+ """Entity node"""+ name: str = Field(description="Entity name")+ category: str = Field(description="Category", default="person")+++class SpatioTemporalEvent(BaseModel):+ """Spatio-temporal event"""+ source: str = Field(description="Source entity")+ target: str = Field(description="Target entity")+ action: str = Field(description="Action or relationship")+ time: Optional[str] = Field(description="When", default=None)+ location: Optional[str] = Field(description="Where", default=None)+++def main():+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")++ input_file = Path(__file__).parent.parent.parent / "en" / "tesla.md"+ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("\n" + "=" * 60)+ print(" Spatio-Temporal Graph Demo")+ print("=" * 60)+ print("Extracting spatio-temporal events...")++ graph = AutoSpatioTemporalGraph[Entity, SpatioTemporalEvent](+ node_schema=Entity,+ edge_schema=SpatioTemporalEvent,+ llm_client=llm,+ embedder=embedder,+ observation_location="United States",+ )++ graph.feed_text(text)++ print(f"\nExtracted {len(graph.nodes)} entities and {len(graph.edges)} events")++ sorted_edges = sorted(graph.edges, key=lambda x: x.time or "")+ for edge in sorted_edges[:5]:+ time_info = f" ({edge.time})" if edge.time else ""+ loc_info = f" in {edge.location}" if edge.location else ""+ print(f" {edge.source} --[{edge.action}]--> {edge.target}{time_info}{loc_info}")++ graph.build_index()++ for q in ["New York", "Colorado Springs", "inventions"]:+ print(f"\nQuery: {q}")+ nodes, edges = graph.search(q, top_k_nodes=3, top_k_edges=3)+ print(f" Found {len(nodes)} entities, {len(edges)} events")+++if __name__ == "__main__":+ main()diff --git a/examples/en/autotypes/temporal_demo.py b/examples/en/autotypes/temporal_demo.pynew file mode 100644index 0000000..a03f65e--- /dev/null+++ b/examples/en/autotypes/temporal_demo.py@@ -0,0 +1,72 @@+"""+Temporal Graph Demo - Tesla Biography++Extract temporal relationships from text using AutoTemporalGraph.+This demo shows how to understand time-based relationships.++Usage:+ python examples/en/autotypes/temporal_demo.py+"""++import sys+from pathlib import Path+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+import dotenv++dotenv.load_dotenv()++from pydantic import BaseModel, Field+from hyperextract.types import AutoTemporalGraph+++class Entity(BaseModel):+ """Entity node"""+ name: str = Field(description="Entity name")+ type: str = Field(description="Type: person/location/invention", default="person")+++class TimelineEvent(BaseModel):+ """Timeline event"""+ time: str = Field(description="Time (year or date)")+ event: str = Field(description="Event description")+ entities: list[str] = Field(description="Entities involved")+++def main():+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")++ input_file = Path(__file__).parent.parent.parent / "en" / "tesla.md"+ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("\n" + "=" * 60)+ print(" Temporal Graph Demo")+ print("=" * 60)+ print("Extracting temporal relationships...")++ graph = AutoTemporalGraph[Entity, TimelineEvent](+ node_schema=Entity,+ edge_schema=TimelineEvent,+ llm_client=llm,+ embedder=embedder,+ )++ graph.feed_text(text)++ print(f"\nExtracted {len(graph.nodes)} entities and {len(graph.edges)} events")++ sorted_events = sorted(graph.edges, key=lambda x: x.time)+ for event in sorted_events[:5]:+ print(f" {event.time}: {event.event}")++ graph.build_index()++ for q in ["1884", "Colorado Springs", "Wardenclyffe"]:+ print(f"\nQuery: {q}")+ nodes, edges = graph.search(q, top_k_nodes=3, top_k_edges=3)+ print(f" Events: {[e.time for e in edges]}")+++if __name__ == "__main__":+ main()diff --git a/examples/en/methods/atom_demo.py b/examples/en/methods/atom_demo.pynew file mode 100644index 0000000..e8d936b--- /dev/null+++ b/examples/en/methods/atom_demo.py@@ -0,0 +1,51 @@+"""+Atom Demo: Tesla Biography Temporal Extraction++Extract temporal facts from Tesla's biography using Atom.++Usage:+ python examples/en/methods/atom_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.typical import Atom++load_dotenv()++INPUT_FILE = project_root / "examples" / "en" / "tesla.md"+QUESTION_FILE = project_root / "examples" / "en" / "tesla_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE) as f:+ text = f.read()+ with open(QUESTION_FILE) as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("Atom Demo")+ print("=" * 60)++ atom = Atom(llm_client=llm, embedder=embedder)+ atom.feed_text(text)++ print(f"\n✓ Extracted {len(atom.facts)} temporal facts\n")++ print("-" * 60)+ print("Q&A")+ print("-" * 60)+ for q in questions:+ print(f"\nQ: {q}")+ try:+ result = atom.chat(q)+ print(f"A: {result.content}")+ except Exception as e:+ print(f"Error: {e}")diff --git a/examples/en/methods/cog_rag_demo.py b/examples/en/methods/cog_rag_demo.pynew file mode 100644index 0000000..a905ac2--- /dev/null+++ b/examples/en/methods/cog_rag_demo.py@@ -0,0 +1,51 @@+"""+Cog RAG Demo: Tesla Biography Cognitive Knowledge Graph++Extract and query cognitive knowledge with themes and entities from Tesla's biography.++Usage:+ python examples/en/methods/cog_rag_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.rag import Cog_RAG++load_dotenv()++INPUT_FILE = project_root / "examples" / "en" / "tesla.md"+QUESTION_FILE = project_root / "examples" / "en" / "tesla_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE) as f:+ text = f.read()+ with open(QUESTION_FILE) as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("Cog RAG Demo")+ print("=" * 60)++ rag = Cog_RAG(llm_client=llm, embedder=embedder)+ rag.feed_text(text)++ print(f"\n✓ Extracted {len(rag.themes)} themes, {len(rag.nodes)} entities\n")++ print("-" * 60)+ print("Q&A")+ print("-" * 60)+ for q in questions:+ print(f"\nQ: {q}")+ try:+ result = rag.chat(q)+ print(f"A: {result.content}")+ except Exception as e:+ print(f"Error: {e}")diff --git a/examples/en/methods/graph_rag_demo.py b/examples/en/methods/graph_rag_demo.pynew file mode 100644index 0000000..8bcda98--- /dev/null+++ b/examples/en/methods/graph_rag_demo.py@@ -0,0 +1,51 @@+"""+Graph RAG Demo: Tesla Biography Knowledge Graph++Extract and query knowledge from Tesla's biography using Graph RAG.++Usage:+ python examples/en/methods/graph_rag_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.rag import Graph_RAG++load_dotenv()++INPUT_FILE = project_root / "examples" / "en" / "tesla.md"+QUESTION_FILE = project_root / "examples" / "en" / "tesla_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE) as f:+ text = f.read()+ with open(QUESTION_FILE) as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("Graph RAG Demo")+ print("=" * 60)++ rag = Graph_RAG(llm_client=llm, embedder=embedder)+ rag.feed_text(text)++ print(f"\n✓ Extracted {len(rag.nodes)} entities, {len(rag.edges)} relations\n")++ print("-" * 60)+ print("Q&A")+ print("-" * 60)+ for q in questions:+ print(f"\nQ: {q}")+ try:+ result = rag.chat(q)+ print(f"A: {result.content}")+ except Exception as e:+ print(f"Error: {e}")diff --git a/examples/en/methods/hyper_rag_demo.py b/examples/en/methods/hyper_rag_demo.pynew file mode 100644index 0000000..f4a6b01--- /dev/null+++ b/examples/en/methods/hyper_rag_demo.py@@ -0,0 +1,51 @@+"""+Hyper RAG Demo: Tesla Biography Hypergraph Extraction++Extract and query hypergraph knowledge from Tesla's biography.++Usage:+ python examples/en/methods/hyper_rag_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.rag import Hyper_RAG++load_dotenv()++INPUT_FILE = project_root / "examples" / "en" / "tesla.md"+QUESTION_FILE = project_root / "examples" / "en" / "tesla_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE) as f:+ text = f.read()+ with open(QUESTION_FILE) as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("Hyper RAG Demo")+ print("=" * 60)++ rag = Hyper_RAG(llm_client=llm, embedder=embedder)+ rag.feed_text(text)++ print(f"\n✓ Extracted {len(rag.nodes)} entities, {len(rag.hyper_edges)} hyperedges\n")++ print("-" * 60)+ print("Q&A")+ print("-" * 60)+ for q in questions:+ print(f"\nQ: {q}")+ try:+ result = rag.chat(q)+ print(f"A: {result.content}")+ except Exception as e:+ print(f"Error: {e}")diff --git a/examples/en/methods/hypergraph_rag_demo.py b/examples/en/methods/hypergraph_rag_demo.pynew file mode 100644index 0000000..aff79df--- /dev/null+++ b/examples/en/methods/hypergraph_rag_demo.py@@ -0,0 +1,51 @@+"""+HyperGraph RAG Demo: Tesla Biography Multi-entity Relations++Extract and query multi-entity relations from Tesla's biography.++Usage:+ python examples/en/methods/hypergraph_rag_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.rag import HyperGraph_RAG++load_dotenv()++INPUT_FILE = project_root / "examples" / "en" / "tesla.md"+QUESTION_FILE = project_root / "examples" / "en" / "tesla_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE) as f:+ text = f.read()+ with open(QUESTION_FILE) as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("HyperGraph RAG Demo")+ print("=" * 60)++ rag = HyperGraph_RAG(llm_client=llm, embedder=embedder)+ rag.feed_text(text)++ print(f"\n✓ Extracted {len(rag.nodes)} entities, {len(rag.hyper_edges)} hyperedges\n")++ print("-" * 60)+ print("Q&A")+ print("-" * 60)+ for q in questions:+ print(f"\nQ: {q}")+ try:+ result = rag.chat(q)+ print(f"A: {result.content}")+ except Exception as e:+ print(f"Error: {e}")diff --git a/examples/en/methods/itext2kg_demo.py b/examples/en/methods/itext2kg_demo.pynew file mode 100644index 0000000..b1b8230--- /dev/null+++ b/examples/en/methods/itext2kg_demo.py@@ -0,0 +1,51 @@+"""+iText2KG Demo: Tesla Biography Knowledge Extraction++Extract structured knowledge triples from Tesla's biography using iText2KG.++Usage:+ python examples/en/methods/itext2kg_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.typical import iText2KG++load_dotenv()++INPUT_FILE = project_root / "examples" / "en" / "tesla.md"+QUESTION_FILE = project_root / "examples" / "en" / "tesla_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE) as f:+ text = f.read()+ with open(QUESTION_FILE) as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("iText2KG Demo")+ print("=" * 60)++ ka = iText2KG(llm_client=llm, embedder=embedder)+ ka.feed_text(text)++ print(f"\n✓ Extracted {len(ka.nodes)} entities, {len(ka.edges)} relations\n")++ print("-" * 60)+ print("Q&A")+ print("-" * 60)+ for q in questions:+ print(f"\nQ: {q}")+ try:+ result = ka.chat(q)+ print(f"A: {result.content}")+ except Exception as e:+ print(f"Error: {e}")diff --git a/examples/en/methods/itext2kg_star_demo.py b/examples/en/methods/itext2kg_star_demo.pynew file mode 100644index 0000000..2cb96cf--- /dev/null+++ b/examples/en/methods/itext2kg_star_demo.py@@ -0,0 +1,51 @@+"""+iText2KG Star Demo: Tesla Biography Deduplicated Extraction++Extract knowledge with semantic deduplication from Tesla's biography.++Usage:+ python examples/en/methods/itext2kg_star_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.typical import iText2KG_Star++load_dotenv()++INPUT_FILE = project_root / "examples" / "en" / "tesla.md"+QUESTION_FILE = project_root / "examples" / "en" / "tesla_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE) as f:+ text = f.read()+ with open(QUESTION_FILE) as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("iText2KG Star Demo")+ print("=" * 60)++ ka = iText2KG_Star(llm_client=llm, embedder=embedder)+ ka.feed_text(text)++ print(f"\n✓ Extracted {len(ka.nodes)} entities, {len(ka.edges)} relations\n")++ print("-" * 60)+ print("Q&A")+ print("-" * 60)+ for q in questions:+ print(f"\nQ: {q}")+ try:+ result = ka.chat(q)+ print(f"A: {result.content}")+ except Exception as e:+ print(f"Error: {e}")diff --git a/examples/en/methods/kg_gen_demo.py b/examples/en/methods/kg_gen_demo.pynew file mode 100644index 0000000..db955a5--- /dev/null+++ b/examples/en/methods/kg_gen_demo.py@@ -0,0 +1,51 @@+"""+KG Gen Demo: Tesla Biography Graph Generation++Generate simple knowledge graph from Tesla's biography.++Usage:+ python examples/en/methods/kg_gen_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.typical import KG_Gen++load_dotenv()++INPUT_FILE = project_root / "examples" / "en" / "tesla.md"+QUESTION_FILE = project_root / "examples" / "en" / "tesla_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE) as f:+ text = f.read()+ with open(QUESTION_FILE) as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("KG Gen Demo")+ print("=" * 60)++ ka = KG_Gen(llm_client=llm, embedder=embedder)+ ka.feed_text(text)++ print(f"\n✓ Extracted {len(ka.nodes)} entities, {len(ka.edges)} relations\n")++ print("-" * 60)+ print("Q&A")+ print("-" * 60)+ for q in questions:+ print(f"\nQ: {q}")+ try:+ result = ka.chat(q)+ print(f"A: {result.content}")+ except Exception as e:+ print(f"Error: {e}")diff --git a/examples/en/methods/light_rag_demo.py b/examples/en/methods/light_rag_demo.pynew file mode 100644index 0000000..6ce96ab--- /dev/null+++ b/examples/en/methods/light_rag_demo.py@@ -0,0 +1,51 @@+"""+Light RAG Demo: Tesla Biography Simple Knowledge Graph++Extract and query simple knowledge from Tesla's biography.++Usage:+ python examples/en/methods/light_rag_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.rag import Light_RAG++load_dotenv()++INPUT_FILE = project_root / "examples" / "en" / "tesla.md"+QUESTION_FILE = project_root / "examples" / "en" / "tesla_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE) as f:+ text = f.read()+ with open(QUESTION_FILE) as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("Light RAG Demo")+ print("=" * 60)++ rag = Light_RAG(llm_client=llm, embedder=embedder)+ rag.feed_text(text)++ print(f"\n✓ Extracted {len(rag.nodes)} entities, {len(rag.edges)} relations\n")++ print("-" * 60)+ print("Q&A")+ print("-" * 60)+ for q in questions:+ print(f"\nQ: {q}")+ try:+ result = rag.chat(q)+ print(f"A: {result.content}")+ except Exception as e:+ print(f"Error: {e}")diff --git a/examples/en/templates/finance_template.py b/examples/en/templates/finance_template.pynew file mode 100644index 0000000..19e147b--- /dev/null+++ b/examples/en/templates/finance_template.py@@ -0,0 +1,75 @@+"""+Finance Domain Template Demo++Usage:+ python examples/en/templates/finance_template.py+"""++import sys+from pathlib import Path++project_root = Path(__file__).resolve().parent.parent.parent.parent+sys.path.append(str(project_root))++from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract import Template++import dotenv++dotenv.load_dotenv()++# ==================== Test Cases (uncomment to select test case) ====================++# // test for Event Timeline+test_data_file = "annual_report_sample.md"+template_name = "finance/event_timeline"++# // test for Ownership Graph+# test_data_file = "ipo_prospectus_sample.md"+# template_name = "finance/ownership_graph"++# // test for Risk Factor Set+# test_data_file = "annual_report_sample.md"+# template_name = "finance/risk_factor_set"++# // test for Sentiment Model+# test_data_file = "financial_news_sample.md"+# template_name = "finance/sentiment_model"++# // test for Earnings Call Summary+# test_data_file = "earnings_call_transcript_sample.md"+# template_name = "finance/earnings_summary"++# ==================== Main Function ====================++def main():+ test_data_dir = project_root / "tests" / "test_data" / "en" / "finance"+ input_file = test_data_dir / test_data_file++ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("=" * 80)+ print(f"🧪 Testing template: {template_name}")+ print(f"📂 Test data: {input_file}")+ print("=" * 80)++ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings()++ extractor = Template.create(+ template_name,+ language="en",+ llm_client=llm,+ embedder=embedder,+ )++ print("\n📥 Extracting knowledge summary...")+ extractor.feed_text(text)+ print("✅ Extraction complete!\n")++ extractor.show()+++if __name__ == "__main__":+ main()diff --git a/examples/en/templates/general_template.py b/examples/en/templates/general_template.pynew file mode 100644index 0000000..259447d--- /dev/null+++ b/examples/en/templates/general_template.py@@ -0,0 +1,75 @@+"""+General Domain Template Demo++Usage:+ python examples/en/templates/general_template.py+"""++import sys+from pathlib import Path++project_root = Path(__file__).resolve().parent.parent.parent.parent+sys.path.append(str(project_root))++from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract import Template++import dotenv++dotenv.load_dotenv()++# ==================== Test Cases (uncomment to select test case) ====================++# // test for Base Knowledge Graph+test_data_file = "arbitrary_tech_news.md"+template_name = "general/base_graph"++# // test for Base Hypergraph+# test_data_file = "encyclopedia_machine_learning.md"+# template_name = "general/base_hypergraph"++# // test for Base List+# test_data_file = "regulation_company_policy.md"+# template_name = "general/base_list"++# // test for Biography Graph+# test_data_file = "biography_scientist.md"+# template_name = "general/biography_graph"++# // test for Concept Graph+# test_data_file = "encyclopedia_machine_learning.md"+# template_name = "general/concept_graph"++# ==================== Main Function ====================++def main():+ test_data_dir = project_root / "tests" / "test_data" / "en" / "general"+ input_file = test_data_dir / test_data_file++ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("=" * 80)+ print(f"🧪 Testing template: {template_name}")+ print(f"📂 Test data: {input_file}")+ print("=" * 80)++ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings()++ extractor = Template.create(+ template_name,+ language="en",+ llm_client=llm,+ embedder=embedder,+ )++ print("\n📥 Extracting knowledge summary...")+ extractor.feed_text(text)+ print("✅ Extraction complete!\n")++ extractor.show()+++if __name__ == "__main__":+ main()diff --git a/examples/en/templates/industry_template.py b/examples/en/templates/industry_template.pynew file mode 100644index 0000000..00df6d8--- /dev/null+++ b/examples/en/templates/industry_template.py@@ -0,0 +1,75 @@+"""+Industry Domain Template Demo++Usage:+ python examples/en/templates/industry_template.py+"""++import sys+from pathlib import Path++project_root = Path(__file__).resolve().parent.parent.parent.parent+sys.path.append(str(project_root))++from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract import Template++import dotenv++dotenv.load_dotenv()++# ==================== Test Cases (uncomment to select test case) ====================++# // test for Equipment Topology+test_data_file = "equipment_technical_manual.md"+template_name = "industry/equipment_topology"++# // test for Operation Flow+# test_data_file = "operation_maintenance_manual.md"+# template_name = "industry/operation_flow"++# // test for Safety Control+# test_data_file = "safety_management_handbook.md"+# template_name = "industry/safety_control"++# // test for Emergency Response Timeline+# test_data_file = "safety_management_handbook.md"+# template_name = "industry/emergency_response"++# // test for Failure Case+# test_data_file = "failure_analysis_report.md"+# template_name = "industry/failure_case"++# ==================== Main Function ====================++def main():+ test_data_dir = project_root / "tests" / "test_data" / "en" / "industry"+ input_file = test_data_dir / test_data_file++ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("=" * 80)+ print(f"🧪 Testing template: {template_name}")+ print(f"📂 Test data: {input_file}")+ print("=" * 80)++ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings()++ extractor = Template.create(+ template_name,+ language="en",+ llm_client=llm,+ embedder=embedder,+ )++ print("\n📥 Extracting knowledge summary...")+ extractor.feed_text(text)+ print("✅ Extraction complete!\n")++ extractor.show()+++if __name__ == "__main__":+ main()diff --git a/examples/en/templates/legal_template.py b/examples/en/templates/legal_template.pynew file mode 100644index 0000000..d23bf00--- /dev/null+++ b/examples/en/templates/legal_template.py@@ -0,0 +1,75 @@+"""+Legal Domain Template Demo++Usage:+ python examples/en/templates/legal_template.py+"""++import sys+from pathlib import Path++project_root = Path(__file__).resolve().parent.parent.parent.parent+sys.path.append(str(project_root))++from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract import Template++import dotenv++dotenv.load_dotenv()++# ==================== Test Cases (uncomment to select test case) ====================++# // test for Case Citation Graph+# test_data_file = "legal_treatise_sample.md"+# template_name = "legal/case_citation"++# // test for Case Fact Timeline+# test_data_file = "court_judgment_sample.md"+# template_name = "legal/case_fact_timeline"++# // test for Compliance Checklist+# test_data_file = "compliance_filing_sample.md"+# template_name = "legal/compliance_list"++# // test for Contract Obligation+test_data_file = "msa_contract_sample.md"+template_name = "legal/contract_obligation"++# // test for Defined Terms+# test_data_file = "msa_contract_sample.md"+# template_name = "legal/defined_term_set"++# ==================== Main Function ====================++def main():+ test_data_dir = project_root / "tests" / "test_data" / "en" / "legal"+ input_file = test_data_dir / test_data_file++ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("=" * 80)+ print(f"🧪 Testing template: {template_name}")+ print(f"📂 Test data: {input_file}")+ print("=" * 80)++ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings()++ extractor = Template.create(+ template_name,+ language="en",+ llm_client=llm,+ embedder=embedder,+ )++ print("\n📥 Extracting knowledge summary...")+ extractor.feed_text(text)+ print("✅ Extraction complete!\n")++ extractor.show()+++if __name__ == "__main__":+ main()diff --git a/examples/en/templates/list_templates.py b/examples/en/templates/list_templates.pynew file mode 100644index 0000000..8e8a452--- /dev/null+++ b/examples/en/templates/list_templates.py@@ -0,0 +1,55 @@+"""+List Templates - List all available preset templates++Usage:+ python examples/en/templates/list_templates.py+"""++import sys+import yaml+from pathlib import Path++project_root = Path(__file__).resolve().parent.parent.parent.parent+sys.path.append(str(project_root))+++def list_templates():+ mapping_file = Path(__file__).parent / "templates_mapping.yaml"++ with open(mapping_file, "r", encoding="utf-8") as f:+ mappings = yaml.safe_load(f)++ print("\n" + "=" * 80)+ print("📋 Hyper-Extract Preset Templates")+ print("=" * 80)++ for domain, templates in mappings.items():+ if domain in ["test_data_root", "template_root"]:+ continue++ print(f"\n[{domain.upper()} DOMAIN] ({len(templates)} templates)")+ print("-" * 60)++ for name, info in templates.items():+ template_type = info.get("type", "unknown")+ description = info.get("description", "N/A")+ template_path = info.get("template", "")+ input_path = info.get("input", "")++ print(f" • {name}")+ print(f" Type: {template_type}")+ print(f" Description: {description}")+ print(f" Template: {template_path}.yaml")+ print(f" Test Data: tests/test_data/en/{input_path}")++ print("\n" + "=" * 80)+ print("\nUsage:")+ print(" python examples/en/templates/run_template.py -d <domain> -t <template_name>")+ print("\nExamples:")+ print(" python examples/en/templates/run_template.py -d finance -t earnings_summary")+ print(" python examples/en/templates/run_template.py -d general -t base_graph")+ print("\n" + "=" * 80 + "\n")+++if __name__ == "__main__":+ list_templates()diff --git a/examples/en/templates/medicine_template.py b/examples/en/templates/medicine_template.pynew file mode 100644index 0000000..2804fa8--- /dev/null+++ b/examples/en/templates/medicine_template.py@@ -0,0 +1,75 @@+"""+Medicine Domain Template Demo++Usage:+ python examples/en/templates/medicine_template.py+"""++import sys+from pathlib import Path++project_root = Path(__file__).resolve().parent.parent.parent.parent+sys.path.append(str(project_root))++from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract import Template++import dotenv++dotenv.load_dotenv()++# ==================== Test Cases (uncomment to select test case) ====================++# // test for Anatomy Structure Graph+# test_data_file = "textbook_sample.md"+# template_name = "medicine/anatomy_graph"++# // test for Discharge Instruction+test_data_file = "discharge_summary_sample.md"+template_name = "medicine/discharge_instruction"++# // test for Drug Interaction Graph+# test_data_file = "package_insert_sample.md"+# template_name = "medicine/drug_interaction"++# // test for Hospital Event Timeline+# test_data_file = "pathology_report_sample.md"+# template_name = "medicine/hospital_timeline"++# // test for Treatment Plan Graph+# test_data_file = "clinical_guideline_sample.md"+# template_name = "medicine/treatment_map"++# ==================== Main Function ====================++def main():+ test_data_dir = project_root / "tests" / "test_data" / "en" / "medicine"+ input_file = test_data_dir / test_data_file++ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("=" * 80)+ print(f"🧪 Testing template: {template_name}")+ print(f"📂 Test data: {input_file}")+ print("=" * 80)++ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings()++ extractor = Template.create(+ template_name,+ language="en",+ llm_client=llm,+ embedder=embedder,+ )++ print("\n📥 Extracting knowledge summary...")+ extractor.feed_text(text)+ print("✅ Extraction complete!\n")++ extractor.show()+++if __name__ == "__main__":+ main()diff --git a/examples/en/templates/tcm_template.py b/examples/en/templates/tcm_template.pynew file mode 100644index 0000000..321ce9c--- /dev/null+++ b/examples/en/templates/tcm_template.py@@ -0,0 +1,75 @@+"""+Traditional Chinese Medicine Domain Template Demo++Usage:+ python examples/en/templates/tcm_template.py+"""++import sys+from pathlib import Path++project_root = Path(__file__).resolve().parent.parent.parent.parent+sys.path.append(str(project_root))++from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract import Template++import dotenv++dotenv.load_dotenv()++# ==================== Test Cases (uncomment to select test case) ====================++# // test for Formula Composition Graph+# test_data_file = "prescription_formulary_sample.md"+# template_name = "tcm/formula_composition"++# // test for Herb Properties+# test_data_file = "herb_property_single.md"+# template_name = "tcm/herb_property"++# // test for Herb Relationship Graph+# test_data_file = "herbal_compendium_sample.md"+# template_name = "tcm/herb_relation"++# // test for Meridian Graph+# test_data_file = "meridian_treatise_sample.md"+# template_name = "tcm/meridian_graph"++# // test for Syndrome Reasoning+test_data_file = "medical_case_record_sample.md"+template_name = "tcm/syndrome_reasoning"++# ==================== Main Function ====================++def main():+ test_data_dir = project_root / "tests" / "test_data" / "en" / "tcm"+ input_file = test_data_dir / test_data_file++ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("=" * 80)+ print(f"🧪 Testing template: {template_name}")+ print(f"📂 Test data: {input_file}")+ print("=" * 80)++ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings()++ extractor = Template.create(+ template_name,+ language="en",+ llm_client=llm,+ embedder=embedder,+ )++ print("\n📥 Extracting knowledge summary...")+ extractor.feed_text(text)+ print("✅ Extraction complete!\n")++ extractor.show()+++if __name__ == "__main__":+ main()diff --git a/examples/en/tesla.md b/examples/en/tesla.mdnew file mode 100644index 0000000..4fa3b31--- /dev/null+++ b/examples/en/tesla.md@@ -0,0 +1,78 @@+# Nikola Tesla++Nikola Tesla (1856-1943) was a Serbian-American inventor, electrical engineer, mechanical engineer, and futurist best known for his contributions to the design of the modern alternating current (AC) electricity supply system.++## Early Life and Education++Tesla was born on July 10, 1856, in the village of Smiljan, which was then part of the Austrian Empire (now modern-day Croatia). His father was an Orthodox priest, and his mother was an inventor of household appliances.++Tesla studied engineering at the Austrian Polytechnic in Graz. He was an exceptional student, particularly in mathematics and physics. He later attended the Charles-Ferdinand University in Prague, but left after one semester due to the death of his father.++## Working with Edison++In 1882, Tesla moved to Budapest and worked at the Central Telephone Exchange. There, he conceived the idea for the induction motor, a device that uses alternating current to create a rotating magnetic field.++In 1884, Tesla emigrated to the United States and arrived in New York City with little more than the clothes on his back and four cents in his pocket. He went to work for Thomas Edison, the famous inventor who was then establishing the Edison Electric Light Company.++Tesla worked for Edison for about a year. According to Tesla's own account, he was offered $50,000 to redesign Edison's inefficient motors and generators. He successfully completed the task but was never paid the reward. This led to the famous "War of Currents" between Tesla and Edison.++## War of Currents++Tesla left Edison and founded the Tesla Electric Company in 1887. He developed the AC induction motor and the Tesla coil, which were essential components for the AC power system.++George Westinghouse, founder of Westinghouse Electric Company, bought the patents to Tesla's AC system. This sparked the "War of Currents" between Edison (who advocated DC power) and Tesla/Westinghouse (who advocated AC power).++Edison conducted a public relations campaign to discredit AC power, even demonstrating the dangers of AC by electrocuting animals. Tesla famously demonstrated the safety of AC by allowing himself to be subjected to AC current during public presentations.++In 1893, the World's Columbian Exposition in Chicago chose AC power for its electrical system, marking a major victory for Tesla. The contract to generate electricity for the exposition was won by Westinghouse.++## Colorado Springs++In 1899, Tesla moved to Colorado Springs to conduct experiments on wireless power transmission. He built a laboratory there and created the largest Tesla coil ever constructed, standing over 50 feet tall.++During this period, Tesla transmitted radio signals across long distances and received what he believed were signals from extraterrestrial intelligence. He called them "interplanetary messages."++## Wardenclyffe Tower++In 1901, Tesla began construction of the Wardenclyffe Tower in Shoreham, New York. This was an ambitious project intended to transmit messages and power wirelessly across the Atlantic Ocean.++However, financial troubles plagued the project. His main backer, J.P. Morgan, withdrew support when Tesla could not provide a working prototype for commercial wireless telegraphy.++The project was never completed, and the tower was demolished in 1917. This marked the beginning of Tesla's decline in fortunes.++## Later Years and Death++Tesla spent his later years living in hotels in New York City. He became increasingly eccentric and solitary. Despite his financial troubles, he continued to work on inventions.++In his 78th year, Tesla claimed he could split the Earth like an apple. He wrote a manifesto about what he called "telautodynamics," describing a system for transmitting mechanical power using radio waves.++Tesla died alone in Room 3327 of the New Yorker Hotel on January 7, 1943. He was 86 years old and reportedly worth just $2.30 at the time of his death.++## Notable Relationships++### Rivals+- Thomas Edison: His former employer and main rival in the "War of Currents"+- Edison's DC supporters: They conducted a campaign to discredit Tesla's AC system+- Guglielmo Marconi: Italian inventor who competed with Tesla over radio patents++### Partners and Supporters+- George Westinghouse: His key business partner who commercialized his AC patents+- J.P. Morgan: Initial financial backer of Wardenclyffe Tower project++### Intellectuals+- Mark Twain: Famous American writer who was a close friend and visited Tesla's laboratory+- Swami Vivekananda: Indian philosopher who discussed science and religion with Tesla++## Timeline++- 1856: Born in Smiljan (modern-day Croatia)+- 1875: Enrolled at Austrian Polytechnic in Graz+- 1882: Conceived the induction motor idea in Budapest+- 1884: Immigrated to the United States, worked for Edison+- 1887: Founded Tesla Electric Company+- 1891: Demonstrated the Tesla coil+- 1893: Won the contract to power the World's Columbian Exposition+- 1899: Moved to Colorado Springs for experiments+- 1901: Began construction of Wardenclyffe Tower+- 1917: Wardenclyffe Tower demolished+- 1943: Died in New York Citydiff --git a/examples/en/tesla_question.md b/examples/en/tesla_question.mdnew file mode 100644index 0000000..01568ff--- /dev/null+++ b/examples/en/tesla_question.md@@ -0,0 +1,5 @@+1. What are Tesla's major inventions and their significance?+2. What was the "War of Currents" and who were the main participants?+3. How did Tesla's relationship with Edison evolve over time?+4. What is Tesla's relationship with Westinghouse?+5. What happened at Wardenclyffe Tower?diff --git a/examples/inputs/mmorpg_guild_drama.md b/examples/inputs/mmorpg_guild_drama.mddeleted file mode 100644index 31c0a18..0000000--- a/examples/inputs/mmorpg_guild_drama.md+++ /dev/null@@ -1,171 +0,0 @@-# 【818】星辰阁公会昨晚解散的真相!团长黑装备还骂人!--## 场景背景--在一个名为《永恒之境》的游戏中,顶尖公会"星辰阁"在攻略最终BOSS时发生了严重的内讧。这段文本是一篇游戏论坛的"818"(八卦爆料)帖子。--## 难点--1. 术语混杂:ID、职业代称(主T、奶妈)、外号混用。-2. 关系复杂:涉及治疗、仇恨(Aggro)、装备分配(Loot)、公会管理。-3. 讽刺与隐喻:LLM 需要理解"划水"、"黑装备"等游戏黑话。-------楼主:匿名玩家(ID已隐藏)-发帖时间:今天 23:45--我是星辰阁的一个普通成员,昨晚目睹了整个悲剧的发生。我觉得必须把真相告诉大家。--首先介绍一下我们的团队阵容:-- 会长兼主坦克:雷霆之怒(真实ID:张三,40级战士,装备评分9999)-- 副坦克:坚如磐石(真实ID:李四,38级盾战士,评分8800,人很老实)-- 主奶妈(治疗):小甜甜(真实ID:王五,38级圣骑士,评分8600)-- 副奶妈:月光治愈者(真实ID:赵六,35级德鲁伊,评分7500)-- DPS输出1(弓箭手):暗影刺客(真实ID:孙七,39级猎手,评分9200)-- DPS输出2(法师):火球术一级(真实ID:周八,37级法师,评分8400)-- DPS输出3(剑客):风云剑侠(真实ID:吴九,36级剑士,评分7800)-- 远程法师:冰霜法咒(真实ID:郑十,35级冰法,评分7600)--昨晚晚上8点,我们集合在副本入口。这是星辰阁第三次挑战"深渊魔龙"这个最终BOSS。前两次都失败了,主要是因为配合不够默契。但是昨晚会长雷霆之怒发誓说一定要拿下这个BOSS。--副本开始,一切似乎很顺利。前5个小怪都被我们轻松秒杀。然后大家来到了BOSS房间——深渊魔龙的巢穴。这是一个超级庞大的紫龙,满血时候气势相当恐怖。--战斗一开始,雷霆之怒(会长)冲上去拉住了仇恨值。坚如磐石(副坦克)站在侧翼进行补充。小甜甜不断给雷霆之怒刷HOT(持续恢复)。月光治愈者给坚如磐石加盾。前期看起来非常完美,大家的DPS输出也打得相当漂亮。--但是,大约打了5分钟,问题出现了。--坚如磐石(副坦克)突然掉线了!这太糟糕了。我们在公会频道里看到他的在线状态变成了灰色。公会会长雷霆之怒看到这一幕,血压瞬间上升(我可以想象他的脸色)。--为什么副坦会掉线呢?大家后来才明白——坚如磐石的家里停电了。这真的是太不走运了。--没有副坦克的补充,所有的伤害都集中在了雷霆之怒身上。但是这个时候,事情开始变得诡异。--小甜甜(主奶妈)本应该全力治疗会长,但是我通过伤害统计面板发现,她的治疗量明显不足。更奇怪的是,她把大量的治疗都给了暗影刺客(弓箭手)。--这很不正常。暗影刺客作为DPS,血量本不应该这么低。我仔细看了一下暗影刺客的走位——哎哟,这哥们为了最大化伤害输出,站位超级靠前,几乎要贴到BOSS身上了。结果BOSS的爪子扫过来,一下子就把暗影刺客的血条扫到了20%以下。--关键时刻,小甜甜却把大治疗术给了暗影刺客。这让会长雷霆之怒的血量开始急速下降。--我当时就在YY频道里喊:"小甜甜,快给会长加血!"--月光治愈者也在拼命给会长加盾,但是她的输出能力有限,根本抵挡不住BOSS的伤害。--而且我还发现,月光治愈者的治疗也有一部分莫名其妙地给了其他人。看起来公会里有人在划水。--等等,我再看一下。哦天哪,火球术一级(法师)和冰霜法咒在BOSS的AoE范围内站了太长时间,导致他们频繁掉血。但是,更夸张的是,暗影刺客和小甜甜之间似乎有什么默契——每当暗影刺客掉血,小甜甜就立马给他加。--这时候,我想到了一个可能性。我在游戏论坛里看过一些帖子,有人提到暗影刺客和小甜甜好像是现实中的情侣!--妈呀,这下问题大了。在这么关键的时刻,小甜甜竟然偏心给她的男朋友加血,而忽视了作为团队大脑的会长!--大约在15分钟的时候,BOSS放出了一个大招——"魔龙吐息"。这个技能造成的伤害足以秒杀任何一个DPS。但是坦克(雷霆之怒)应该能扛住。--可是,小甜甜的治疗没有及时跟上。雷霆之怒的血条瞬间掉到了0。--会长倒地了!--随后,失去了坦克的护佑,暗影刺客也被BOSS的普通攻击打成了残血,然后被秒杀。紧接着是风云剑侠,然后是火球术一级。整个团队在短短30秒内全灭了。--副本失败。大家都复活在了副本入口。--这个时候,雷霆之怒(会长)的脾气彻底炸裂了。--他在YY频道里破口大骂:"小甜甜,你是干什么呢?!你是团队奶妈,不是暗影刺客的私人医生!治疗职业就是要保坦克,你这样的治疗我见过,但从没见过这么烂的!"--小甜甜试图辩解:"我……我只是……"--雷霆之怒直接打断她:"别给我狡辩!我决定了,你从今天起被踢出公会!而且暗影刺客这个摸鱼的家伙,我也要把他赶出去。两个人都别在星辰阁待着!"--但就在这个时候,事情发生了急转弯。--暗影刺客一句话都没说,只见他的角色突然冲向了BOSS房间。而就在这时,副本的第二个阶段秘密掉落物品——传说级别的武器"魔龙之牙"出现了!--这是一把超级稀有的武器,全服务器可能只有两三把。价值高达几百万金币。--没等任何人反应过来,暗影刺客就冲上去,一把拿起了"魔龙之牙"!--我们都懵了。"魔龙之牙"本来应该由队长(雷霆之怒)来分配,决定给谁。但是暗影刺客直接黑吃黑,把这把传说武器直接塞进了自己的背包里!--会长还在语音里骂人,根本没注意到这一幕。--紧接着,更狠的来了——暗影刺客在游戏里按下了"退出公会"的按钮。他直接,光速,毫不犹豫地退出了星辰阁!--然后他的角色在世界频道发了一句话:"拜拜,各位。我去找个真正尊重我的公会。"--说完,这哥们直接下线了。--我们的公会频道顿时炸锅了。--小甜甜也没做任何辩解,直接退出了公会。她甚至没有说一句话。--会长雷霆之怒这时候才意识到发生了什么。他看到了掉落物品的分配记录——"魔龙之牙"被暗影刺客拿走了,而不是团队共有。--他疯了。直接在世界频道开始刷屏:-"各位玩家,我要举报星辰阁的暗影刺客和小甜甜这两条狗!他们合谋黑装备!不要信任他们!全服通缉这两个垃圾!"--火球术一级(法师)现在也开始助威。他在世界频道里连发了十多条信息:-"赞同!这两个人太过分了!狗男女!不要和他们做交易!"--"冰霜法咒在副本里的表现也不太理想,看起来他好像和那对情侣有什么关系,因为我注意到在暗影刺客掉线的时候,冰霜法咒也莫名其妙地不进行输出了。"--有人开始怀疑冰霜法咒是不是也是那对情侣的朋友。--坚如磐石(副坦)这时候才上线。他看到了聊天记录,一脸懵逼。他在公会频道里问:"发生什么了?我家里停电了……"--没有人回答他。因为大家都在看这场大戏。--月光治愈者试图调和一下,她说:"大家冷静……这件事可能有误会……"--但是没有人听她的。因为这个时候,世界频道上的玩家也开始评论这件事。--有人说:"这就是为什么我不玩大公会。大公会水太深。"--还有人说:"我早就听说暗影刺客这个人在游戏里名声不太好。多次被指控在副本里贪图装备。"--有人挖出了暗影刺客的历史记录。原来他曾经在另一个公会里,也因为类似的事情被踢出来过。--这哥们简直就是个"装备贪心鬼"。--风云剑侠开始反思:"也许我们团队的问题不只是小甜甜。我们可能选错人了。"--火球术一级继续在世界频道里刷屏:"各位,我建议大家抵制这两个玩家。不要和他们一个队。"--这时候,一个名字叫做"游戏管理员001"的官方账号出现了。他说:"我们收到了关于玩家暗影刺客的举报。我们正在调查这件事。如果确认违规,将给予封号处理。"--暗影刺客的名字从世界频道消失了——他已经下线了。而且下线之前把"魔龙之牙"从背包里转移到了仓库。没人知道他把这把武器藏在了哪里。--最后,星辰阁的会长雷霆之怒在公会频道里宣布:-"各位成员,我决定了。星辰阁正式解散。这个公会不适合我继续管理。我会转移到一个小公会,和志同道合的朋友重新开始。"--很多成员试图挽留他。但是他的决心已定。--现在,星辰阁已经成为了一个"死公会"。只有一些离不开这个ID的成员还在。--这就是昨晚发生的一切。我作为一个旁观者,见证了这场游戏江湖的大戏。--最后的最后,我想说:游戏就是游戏。团队合作最重要。装备是身外之物。但是,为了装备而背叛队友,这绝对是游戏玩家中最可耻的行为。--希望游戏官方能够严肃处理暗影刺客的违规行为。也希望星辰阁的所有成员能够吸取教训,在各自的新公会里找到快乐。-------## 回复楼层--1楼:网络大侠-妈呀,这比小说还精彩。我已经截图保存,等着看后续。--2楼:游戏评论家-我注意到"冰霜法咒"在这件事里也有可疑之处。为什么他突然停止输出?楼主,能不能深入调查一下他和暗影刺客的关系?--3楼:前星辰阁成员(风云剑侠)-我想出来说两句话。昨晚我在现场。真相是:小甜甜确实有偏心。但是暗影刺客黑装备这件事更过分。会长的反应虽然情绪化,但也能理解。我已经离开了星辰阁,现在申请加入"日月神教"这个新兴公会。--4楼:月光治愈者(副奶妈)-我想为自己辩解一下。我在昨晚的治疗中没有任何划水行为。是小甜甜的治疗分配有问题,不是我。顺便说一下,我现在还在星辰阁,因为我对公会有感情。但是我也不太确定会不会继续留下来。--5楼:装备交易商-这就是为什么装备交易需要系统中间作为担保的原因。建议官方加强对装备分配的监管。--6楼:游戏社区版主-这个帖子已经标记为"关键事件记录"。我们会持续关注这件事的后续发展。请各位不要进行人身攻击和骚扰。相关玩家可以选择转服。diff --git a/examples/inputs/sci_fi_story.md b/examples/inputs/sci_fi_story.mddeleted file mode 100644index f92c2a6..0000000--- a/examples/inputs/sci_fi_story.md+++ /dev/null@@ -1,33 +0,0 @@-# 【银河纪元 3042年 - 赤红星云事件报告】--危机在这一周达到了顶峰。整个银河系似乎都陷入了暗流涌动的政治漩涡。--## 【第一阶段:秘密接触】--臭名昭著的星际海盗黑蛇驾驶着他的旗舰复仇号,在泰坦空间站秘密会见了银河联邦的背叛者议员 Valerius。目击者称,两人在午夜时分登上了空间站的顶层禁区。据情报部门推测,这是一次肮脏的交易——双方达成了针对皇室的同盟关系。参与此会议的还有 Valerius 手下的特务头目 Shadow,他负责处理所有不可告人的细节。这个同盟的形成标志着大麻烦即将到来。--## 【第二阶段:叛变与夺权】--在这次会议的两天后,事态急剧恶化。黑蛇这种疯狂的家伙竟然在极光星区伏击了皇家护卫队。这场突然的冲突中,皇家护卫队的队长 Leona 与副队长 Marcus 奋力抵抗,但他们陷入了黑蛇手下的精锐战士的包围。这场激战导致队长 Leona 身受重伤。而黑蛇的目标不是为了杀戮,而是为了夺取一件神圣的物品——传说中的虚空水晶。这枚水晶散发着幽蓝的光芒,据说能够打开先祖之门的第一道密封。黑蛇在战斗中成功夺取了水晶,但 Leona 在临终前用最后的力量将其重新夺回。--## 【第三阶段:流亡与隐藏】--Leona 被迫带着虚空水晶,从极光星区逃往荒凉的废土行星 Z-9。在这个被遗忘的角落,她向仅有的几个信任者求救:还有副队长 Marcus 以及隐秘组织"地下抵抗军"的领导人 Cipher。同时,议员 Valerius 非法持有了开启先祖之门的钥匙——这把钥匙本应被安全保管在皇家金库中。他现在藏匿在浮空都市中,与黑蛇遥相呼应,计划着下一步的政变。--## 【第四阶段:势力重组】--银河联邦的最高委员会得知了这一系列事件,决定采取行动。高级顾问 Artemis 被任命为特使,她与 Leona 在废土行星 Z-9 进行了秘密会晤,讨论如何制止这场即将到来的危机。同时,地下抵抗军的 Cipher 也加入了这次会议,三人共同制定了一个大胆的计划。--## 【第五阶段:最后的筹码】--虽然黑蛇未能获得虚空水晶,但他已经从 Valerius 那里获得了先祖之门钥匙的复制品。根据情报,这个复制品目前被秘密运往到黑蛇的秘密基地——位于辐射荒漠中的要塞。参与此次运送的还有 Shadow 和黑蛇手下的精锐战士群体。与此同时,Leona 和 Marcus 正在准备一场反击,他们计划在虚空水晶的力量下重新夺回局势的控制权。--## 目前局势--- 黑蛇:手持复制品钥匙,掌控旗舰复仇号,计划进行最终的攻击-- 议员 Valerius:躲在浮空都市中,与黑蛇保持联系-- Leona:守护虚空水晶,在废土行星 Z-9 养伤,准备反击-- 银河联邦:通过特使 Artemis 支持 Leona,正在调集力量-- 地下抵抗军:Cipher 领导,与 Leona 和 Marcus 联手,准备对抗黑蛇和 Valerius 的同盟--这场战争的走向仍不确定。虚空水晶、先祖之门、以及隐藏在这一切背后的秘密,都将在接下来的日子里浮出水面。银河的命运,可能就在这些关键人物和物品的碰撞中决定。diff --git a/examples/methods/atom_demo.py b/examples/methods/atom_demo.pydeleted file mode 100644index c82cdd4..0000000--- a/examples/methods/atom_demo.py+++ /dev/null@@ -1,99 +0,0 @@-"""-Atom Demo: Temporal Knowledge Graph Extraction from Product History--This demo demonstrates how to use Atom to extract structured knowledge from product iteration history.-Key features:-1. Extracting product release dates and version information-2. Key person and product associations-3. Company acquisitions and product strategy changes-4. Precise capture of temporal relationships (t_start, t_end)-5. Evidence tracking and source tracing--Usage:- python examples/methods/atom_demo.py-"""--import sys-from pathlib import Path--project_root = Path(__file__).resolve().parent.parent.parent-sys.path.append(str(project_root))--from dotenv import load_dotenv-from langchain_openai import ChatOpenAI, OpenAIEmbeddings--from hyperextract.methods.typical import Atom--load_dotenv()--INPUT_FILE = project_root / "examples" / "inputs" / "sci_fi_story.md"---if __name__ == "__main__":- print("=" * 80)- print("Initializing Atom System...")- print("=" * 80)-- print(f"\n📄 Reading input file: {INPUT_FILE}")- with open(INPUT_FILE, "r", encoding="utf-8") as f:- content = f.read()- print(f"✅ Loaded {len(content)} characters")-- llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)- embedder = OpenAIEmbeddings()-- atom = Atom(- llm_client=llm,- embedder=embedder,- observation_time="3042-12-01",- )-- print("\nFeeding content to the system...")- atom.feed_text(content)- print("✓ Content processed successfully\n")-- print("=" * 80)- print("EXTRACTED FACTS")- print("=" * 80)-- for i, fact in enumerate(atom.facts, 1):- print(f"\n{i}. Subject: {fact.subject}")- print(f" Predicate: {fact.predicate}")- print(f" Object: {fact.object}")- print(f" Start Time: {fact.t_start}")- print(f" End Time: {fact.t_end}")- print(f" Source: {fact.source}")-- print(f"\n✓ Total facts extracted: {len(atom.facts)}\n")-- print("=" * 80)- print("TEMPORAL STATISTICS")- print("=" * 80)-- print(f"\nEarliest event: {min(f.t_start for f in atom.facts if f.t_start)}")- print(f"Latest event: {max(f.t_end for f in atom.facts if f.t_end)}")-- print("\n" + "=" * 80)- print("Q&A: TEMPORAL SEARCH")- print("=" * 80)-- queries = [- "What events occurred?",- "Who are the key participants?",- "What is the timeline of events?",- ]-- for i, query in enumerate(queries, 1):- print(f"\n【Query {i}】{query}")- print("-" * 60)-- try:- facts = atom.search(query, top_k=5)- for fact in facts:- print(f" - {fact.subject} {fact.predicate} {fact.object}")- if fact.t_start:- print(f" Time: {fact.t_start}")- except Exception as e:- print(f" Search error: {str(e)}")-- print("\n" + "=" * 80 + "\n")diff --git a/examples/methods/cog_rag_demo.py b/examples/methods/cog_rag_demo.pydeleted file mode 100644index 0d09fc0..0000000--- a/examples/methods/cog_rag_demo.py+++ /dev/null@@ -1,139 +0,0 @@-"""-Cog_RAG Demo: Theme-based Knowledge Extraction + Entity-Relation Detail Retrieval--This demo demonstrates the unified Cog_RAG System Wrapper:-1. **Macro Layer (Theme Layer)**: Extracts Narrative Arcs (Themes) and their Participant Entities.-2. **Micro Layer (Detail Layer)**: Extracts Entities and their Semantic Relationships.-3. **Process**:- - Feeds the same story to the Unified System.- - The system automatically distributes extraction tasks to both layers.- - Performs a Dual-Layer Chat/Search.--Usage:- python examples/methods/cog_rag_demo.py-"""--import sys-from pathlib import Path--project_root = Path(__file__).resolve().parent.parent.parent-sys.path.append(str(project_root))--from dotenv import load_dotenv-load_dotenv()--from langchain_openai import ChatOpenAI, OpenAIEmbeddings-from hyperextract.methods.rag import Cog_RAG--INPUT_FILE = project_root / "examples" / "inputs" / "sci_fi_story.md"---if __name__ == "__main__":- print("=" * 80)- print("Initializing Cog-RAG System...")- print("=" * 80)-- print(f"\n📄 Reading input file: {INPUT_FILE}")- with open(INPUT_FILE, "r", encoding="utf-8") as f:- story = f.read()- print(f"✅ Loaded {len(story)} characters")-- llm_client = ChatOpenAI(- model="gpt-4o-mini",- )- embedder = OpenAIEmbeddings(model="text-embedding-3-small")-- rag = Cog_RAG(- llm_client=llm_client,- embedder=embedder,- chunk_size=1000,- )-- print("\nFeeding story to the system...")- rag.feed_text(story)- print("✓ Story processed successfully\n")-- print("=" * 80)- print("EXTRACTED THEMES (Macro Layer)")- print("=" * 80)-- for i, theme in enumerate(rag.themes, 1):- print(f"\n{i}. Theme: {theme.title}")- print(f" Summary: {theme.summary}")- print(f" Participants: {', '.join(theme.participants) if theme.participants else 'N/A'}")-- print(f"\n✓ Total themes extracted: {len(rag.themes)}\n")-- print("=" * 80)- print("EXTRACTED ENTITIES (Micro Layer)")- print("=" * 80)-- for node in rag.nodes:- print(f"\n【{node.name}】(Type: {node.type})")- print(f" Description: {node.description}")-- print(f"\n✓ Total entities extracted: {len(rag.nodes)}\n")-- print("=" * 80)- print("EXTRACTED RELATIONS (Micro Layer)")- print("=" * 80)-- for i, edge in enumerate(rag.edges, 1):- print(f"\n{i}. {edge.source} -> {edge.target}")- print(f" Description: {edge.description}")- print(f" Strength: {edge.strength}/10")-- print(f"\n✓ Total edges extracted: {len(rag.edges)}\n")-- print("=" * 80)- print("Building Semantic Index...")- print("=" * 80)-- rag.build_index()- print("✓ Semantic index built successfully\n")-- print("=" * 80)- print("Q&A: DUAL-LAYER SEARCH")- print("=" * 80)-- queries = [- "What happened to the crystal?",- "What is the conspiracy?",- "Who participated in the secret meeting?",- "What is Leona's current situation?",- ]-- for i, query in enumerate(queries, 1):- print(f"\n【Query {i}】{query}")- print("-" * 60)-- try:- themes, nodes, edges = rag.search(query, top_k=3)-- if themes:- print(" Relevant Themes:")- for t in themes[:2]:- print(f" - {t.title}: {t.summary[:50]}...")-- if edges:- print(" Relevant Relations:")- for e in edges[:2]:- print(f" - {e.source} -> {e.target}: {e.description[:50]}...")-- except Exception as e:- print(f" Search error: {str(e)}")-- print("\n" + "=" * 80)- print("💬 Interactive Chat with Cog-RAG")- print("=" * 80)- print("Engaging in multi-turn dialogue based on extracted knowledge...\n")-- for q in queries:- print(f"❓ User: {q}")- try:- response = rag.chat(q)- print(f"🤖 Cog-RAG: {response.content}\n")- except Exception as e:- print(f"⚠️ Chat error: {e}\n")-- print("\n" + "=" * 80 + "\n")diff --git a/examples/methods/graph_rag_demo.py b/examples/methods/graph_rag_demo.pydeleted file mode 100644index 0cd3172..0000000--- a/examples/methods/graph_rag_demo.py+++ /dev/null@@ -1,216 +0,0 @@-"""-Graph-RAG Demo: Entity-Relationship Extraction with Standard Binary Graphs--This demo demonstrates:-1. Extracting entities and binary relationships from a complex sci-fi story.-2. Analysis of standard graph relationships (Source -> Target).-3. Semantic Search over the constructed Knowledge Graph (Q&A).--Usage:- python examples/methods/graph_rag_demo.py-"""--import os-import sys-from pathlib import Path--project_root = Path(__file__).resolve().parent.parent.parent-sys.path.append(str(project_root))--from dotenv import load_dotenv-load_dotenv()--from langchain_openai import ChatOpenAI, OpenAIEmbeddings-from hyperextract.methods.rag import Graph_RAG--INPUT_FILE = project_root / "examples" / "inputs" / "sci_fi_story.md"---if __name__ == "__main__":- print("=" * 80)- print("Initializing Graph-RAG System...")- print("=" * 80)-- print(f"\n📄 Reading input file: {INPUT_FILE}")- with open(INPUT_FILE, "r", encoding="utf-8") as f:- story = f.read()- print(f"✅ Loaded {len(story)} characters")-- llm_client = ChatOpenAI(- model="gpt-4o-mini",- )- embedder = OpenAIEmbeddings(model="text-embedding-3-small")-- rag = Graph_RAG(- llm_client=llm_client,- embedder=embedder,- chunk_size=1000,- )-- print("\nFeeding story to the system...")- rag.feed_text(story)- print("✓ Story processed successfully\n")-- print("=" * 80)- print("EXTRACTED ENTITIES")- print("=" * 80)-- for node in rag.nodes:- print(f"\n【{node.name}】(Type: {node.type})")- print(f" Description: {node.description}")-- print(f"\n✓ Total entities extracted: {len(rag.nodes)}\n")-- print("=" * 80)- print("EXTRACTED EDGES (Binary Relationships)")- print("=" * 80)-- for i, edge in enumerate(rag.edges, 1):- print(f"\n{i}. {edge.source} -> {edge.target}")- print(f" Description: {edge.description}")- print(f" Strength: {edge.strength}/10")-- print(f"\n✓ Total edges extracted: {len(rag.edges)}\n")-- print("=" * 80)- print("STATISTICS")- print("=" * 80)-- type_counts = {}- for node in rag.nodes:- type_counts[node.type] = type_counts.get(node.type, 0) + 1-- print("\nEntity Type Distribution:")- for entity_type, count in sorted(type_counts.items()):- print(f" {entity_type}: {count}")-- if rag.edges:- avg_strength = sum(e.strength for e in rag.edges) / len(rag.edges)- print(f"\nAverage Edge Strength: {avg_strength:.2f}/10")-- print("\nEntity Centrality (Degree):")- centrality = {}- for edge in rag.edges:- centrality[edge.source] = centrality.get(edge.source, 0) + 1- centrality[edge.target] = centrality.get(edge.target, 0) + 1-- for entity, count in sorted(centrality.items(), key=lambda x: x[1], reverse=True)[:10]:- print(f" {entity}: {count}")-- print("\n" + "=" * 80)- print("Building Semantic Index & Communities...")- print("=" * 80)-- rag.build_index()- print("✓ Semantic index built successfully")-- rag.build_communities()- print("✓ Communities built successfully\n")-- print("=" * 80)- print("COMMUNITY REPORTS")- print("=" * 80)-- if not rag.community_reports:- print("No community reports generated.")- else:- for cid, report in rag.community_reports.items():- print(f"\n【{report.title}】 (ID: {report.id}, Rating: {report.rating}/10)")- print(f" Summary: {report.summary}")- print(f" Findings:")- for finding in report.findings:- print(f" - {finding.summary}")-- print("=" * 80)- print("Q&A: COMPARISON (Global vs Local vs Standard)")- print("=" * 80)-- queries = [- "What happened to the crystal?",- "What is the conspiracy between Black Snake and Valerius?",- "Who participated in the secret meeting at Titan Station?",- "What is Leona's current situation?",- ]-- print("\n" + "-" * 60)- print("[1. Standard Node & Edge Search] (use_community=False)")- print("-" * 60)-- for i, query in enumerate(queries, 1):- print(f"\n【Query {i}】{query}")- print("-" * 60)-- try:- results = rag.search_edges(query, top_k=3)-- if results:- for j, result in enumerate(results, 1):- edge = result[0] if isinstance(result, tuple) else result- score = result[1] if isinstance(result, tuple) else 1.0-- print(f"\n {j}. [Score: {score:.3f}]")- print(f" Relation: {edge.source} -> {edge.target}")- print(f" Description: {edge.description}")- print(f" Strength: {edge.strength}/10")- else:- print(" (No relevant relationships found)")- except Exception as e:- print(f" Search error: {str(e)}")-- print("\n" + "-" * 60)- print("[2. Community-Enhanced Search] (use_community=True)")- print("-" * 60)- for i, q in enumerate(queries, 1):- print(f"\n【Query {i}】{q}")- print("-" * 60)- try:- nodes, edges, community_context = rag.search(q, top_k=3, use_community=True)- if community_context:- print(" Community Summaries:")- for summary in community_context.get("summaries", []):- print(f" - [{summary['title']}] (rating: {summary['rating']})")- print(f" {summary['summary'][:100]}...")- if nodes:- print(f" Top nodes: {[n.name for n in nodes[:3]]}")- if edges:- print(f" Top edges: {[e.description[:50] for e in edges[:3]]}")- except Exception as e:- print(f" Error: {e}")-- print("\n" + "=" * 80)- print("💬 Interactive Chat with GraphRAG")- print("=" * 80)- print("Engaging in multi-turn dialogue based on extracted knowledge...\n")-- for q in queries:- print(f"❓ User: {q}")- try:- response = rag.chat(q)- print(f"🤖 GraphRAG: {response.content}\n")- except Exception as e:- print(f"⚠️ Chat error: {e}\n")-- print("\n" + "=" * 80)- print("Saving Results...")- print("=" * 80)-- try:- output_dir = "temp/graph_rag_demo"- rag.dump(output_dir)- print(f"✓ Results saved to {output_dir}/")-- saved_files = []- if os.path.exists(output_dir):- for root, dirs, files in os.walk(output_dir):- for file in files:- rel_path = os.path.relpath(os.path.join(root, file), output_dir)- saved_files.append(rel_path)-- if saved_files:- print("\n Saved files:")- for f in saved_files:- print(f" - {f}")- except Exception as e:- print(f"⚠️ Warning: Could not save results: {str(e)}")-- print("\n" + "=" * 80 + "\n")diff --git a/examples/methods/hyper_rag_demo.py b/examples/methods/hyper_rag_demo.pydeleted file mode 100644index e2ccf85..0000000--- a/examples/methods/hyper_rag_demo.py+++ /dev/null@@ -1,178 +0,0 @@-"""-Hyper-RAG Demo: Multi-entity Relationship Extraction with Hypergraph Support--This demo demonstrates:-1. Extracting entities and multi-entity relationships from a complex sci-fi story.-2. Analysis of complex n-ary relationships (Hyperedges).-3. Semantic Search over the constructed Hypergraph (Q&A).--Usage:- python examples/methods/hyper_rag_demo.py-"""--import os-import sys-from pathlib import Path--project_root = Path(__file__).resolve().parent.parent.parent-sys.path.append(str(project_root))--from dotenv import load_dotenv-from langchain_openai import ChatOpenAI, OpenAIEmbeddings--from hyperextract.methods.rag import Hyper_RAG--load_dotenv()--INPUT_FILE = project_root / "examples" / "inputs" / "sci_fi_story.md"---if __name__ == "__main__":- print("=" * 80)- print("Initializing Hyper-RAG System...")- print("=" * 80)-- print(f"\n📄 Reading input file: {INPUT_FILE}")- with open(INPUT_FILE, "r", encoding="utf-8") as f:- story = f.read()- print(f"✅ Loaded {len(story)} characters")-- llm_client = ChatOpenAI(- model="gpt-4o-mini",- )- embedder = OpenAIEmbeddings(model="text-embedding-3-small")-- rag = Hyper_RAG(- llm_client=llm_client,- embedder=embedder,- chunk_size=1000,- )-- print("\nFeeding story to the system...")- rag.feed_text(story)- print("✓ Story processed successfully\n")-- print("=" * 80)- print("EXTRACTED ENTITIES")- print("=" * 80)-- for node in rag.nodes:- print(f"\n【{node.name}】(Type: {node.type})")- print(f" Description: {node.description}")-- print(f"\n✓ Total entities extracted: {len(rag.nodes)}\n")-- print("=" * 80)- print("EXTRACTED HYPEREDGES")- print("=" * 80)-- low_order_edges = [e for e in rag.edges if len(e.participants) == 2]- high_order_edges = [e for e in rag.edges if len(e.participants) > 2]-- print(f"\n--- Low-Order Edges (Pairwise) ---")- for i, edge in enumerate(low_order_edges, 1):- print(f"\n{i}. Participants: {' <-> '.join(edge.participants)}")- print(f" Description: {edge.description}")- keywords_str = ", ".join(edge.keywords) if edge.keywords else "N/A"- print(f" Keywords: {keywords_str}")- print(f" Strength: {edge.strength}/10")-- print(f"\n--- High-Order Edges (Hyperedges) ---")- for i, edge in enumerate(high_order_edges, 1):- print(f"\n{i}. Participants: {' <-> '.join(edge.participants)}")- print(f" Description: {edge.description}")- keywords_str = ", ".join(edge.keywords) if edge.keywords else "N/A"- print(f" Keywords: {keywords_str}")- print(f" Strength: {edge.strength}/10")-- print(f"\n✓ Total edges extracted: {len(rag.edges)} ({len(low_order_edges)} low-order, {len(high_order_edges)} high-order)\n")-- print("=" * 80)- print("STATISTICS")- print("=" * 80)-- type_counts = {}- for node in rag.nodes:- type_counts[node.type] = type_counts.get(node.type, 0) + 1-- print("\nEntity Type Distribution:")- for entity_type, count in sorted(type_counts.items()):- print(f" {entity_type}: {count}")-- if rag.edges:- avg_strength = sum(e.strength for e in rag.edges) / len(rag.edges)- print(f"\nAverage Edge Strength: {avg_strength:.2f}/10")-- print("\nEntity Centrality (number of relationships):")- centrality = {}- for edge in rag.edges:- for participant in edge.participants:- centrality[participant] = centrality.get(participant, 0) + 1-- for entity, count in sorted(centrality.items(), key=lambda x: x[1], reverse=True)[:10]:- print(f" {entity}: {count}")-- print("\n" + "=" * 80)- print("Building Semantic Index...")- print("=" * 80)-- rag.build_index()- print("✓ Semantic index built successfully\n")-- print("=" * 80)- print("Q&A: SEMANTIC SEARCH")- print("=" * 80)-- queries = [- "What happened to the crystal?",- "What is the conspiracy?",- "Who participated in the secret meeting?",- "What is Leona's current situation?",- ]-- for i, query in enumerate(queries, 1):- print(f"\n【Query {i}】{query}")- print("-" * 60)-- try:- results = rag.search_edges(query, top_k=3)-- if results:- for j, result in enumerate(results, 1):- edge = result[0] if isinstance(result, tuple) else result- score = result[1] if isinstance(result, tuple) else 1.0-- print(f"\n {j}. [Score: {score:.3f}]")- print(f" Participants: {' <-> '.join(edge.participants)}")- print(f" Description: {edge.description}")- print(f" Strength: {edge.strength}/10")- else:- print(" (No relevant relationships found)")- except Exception as e:- print(f" Search error: {str(e)}")-- print("\n" + "=" * 80)- print("💬 Interactive Chat with HyperRAG")- print("=" * 80)- print("Engaging in multi-turn dialogue based on extracted knowledge...\n")-- for q in queries:- print(f"❓ User: {q}")- try:- response = rag.chat(q)- print(f"🤖 HyperRAG: {response.content}\n")- except Exception as e:- print(f"⚠️ Chat error: {e}\n")-- print("\n" + "=" * 80)- print("Saving Results...")- print("=" * 80)-- try:- output_dir = "temp/hyper_rag_demo"- rag.dump(output_dir)- print(f"✓ Results saved to {output_dir}/")- except Exception as e:- print(f"⚠️ Warning: Could not save results: {str(e)}")-- print("\n" + "=" * 80 + "\n")diff --git a/examples/methods/hypergraph_rag_demo.py b/examples/methods/hypergraph_rag_demo.pydeleted file mode 100644index 3a02033..0000000--- a/examples/methods/hypergraph_rag_demo.py+++ /dev/null@@ -1,129 +0,0 @@-"""-HyperGraph-RAG Demo: Extracting Hyperedges from Text--This script demonstrates the usage of the HyperGraph_RAG system, which is designed-to extract hyperedges from text.--Usage:- python examples/methods/hypergraph_rag_demo.py-"""--import os-import sys-from pathlib import Path--project_root = Path(__file__).resolve().parent.parent.parent-sys.path.append(str(project_root))--from dotenv import load_dotenv-from langchain_openai import ChatOpenAI, OpenAIEmbeddings--from hyperextract.methods.rag import HyperGraph_RAG--load_dotenv()--INPUT_FILE = project_root / "examples" / "inputs" / "sci_fi_story.md"---if __name__ == "__main__":- print("=" * 80)- print("Initializing HyperGraph-RAG System...")- print("=" * 80)-- print(f"\n📄 Reading input file: {INPUT_FILE}")- with open(INPUT_FILE, "r", encoding="utf-8") as f:- story = f.read()- print(f"✅ Loaded {len(story)} characters")-- llm_client = ChatOpenAI(- model="gpt-4o-mini",- )- embedder = OpenAIEmbeddings(model="text-embedding-3-small")-- rag = HyperGraph_RAG(- llm_client=llm_client,- embedder=embedder,- chunk_size=1000,- )-- print("\nFeeding story to the system...")- rag.feed_text(story)- print("✓ Story processed successfully\n")-- print("=" * 80)- print("EXTRACTED ENTITIES")- print("=" * 80)-- for node in rag.nodes:- print(f"\n【{node.name}】(Type: {node.type})")- print(f" Description: {node.description}")-- print(f"\n✓ Total entities extracted: {len(rag.nodes)}\n")-- print("=" * 80)- print("EXTRACTED HYPEREDGES")- print("=" * 80)-- for i, edge in enumerate(rag.edges, 1):- print(f"\n{i}. Participants: {' <-> '.join(edge.participants)}")- print(f" Description: {edge.description}")- keywords_str = ", ".join(edge.keywords) if edge.keywords else "N/A"- print(f" Keywords: {keywords_str}")- print(f" Strength: {edge.strength}/10")-- print(f"\n✓ Total edges extracted: {len(rag.edges)}\n")-- print("=" * 80)- print("STATISTICS")- print("=" * 80)-- type_counts = {}- for node in rag.nodes:- type_counts[node.type] = type_counts.get(node.type, 0) + 1-- print("\nEntity Type Distribution:")- for entity_type, count in sorted(type_counts.items()):- print(f" {entity_type}: {count}")-- if rag.edges:- avg_strength = sum(e.strength for e in rag.edges) / len(rag.edges)- print(f"\nAverage Edge Strength: {avg_strength:.2f}/10")-- print("\n" + "=" * 80)- print("Building Semantic Index...")- print("=" * 80)-- rag.build_index()- print("✓ Semantic index built successfully\n")-- print("=" * 80)- print("Q&A: SEMANTIC SEARCH")- print("=" * 80)-- queries = [- "What happened to the crystal?",- "What is the conspiracy?",- "Who participated in the secret meeting?",- ]-- for i, query in enumerate(queries, 1):- print(f"\n【Query {i}】{query}")- print("-" * 60)-- try:- results = rag.search_edges(query, top_k=3)-- if results:- for j, result in enumerate(results, 1):- edge = result[0] if isinstance(result, tuple) else result- score = result[1] if isinstance(result, tuple) else 1.0-- print(f"\n {j}. [Score: {score:.3f}]")- print(f" Participants: {' <-> '.join(edge.participants)}")- print(f" Description: {edge.description}")- else:- print(" (No relevant relationships found)")- except Exception as e:- print(f" Search error: {str(e)}")-- print("\n" + "=" * 80 + "\n")diff --git a/examples/methods/itext2kg_demo.py b/examples/methods/itext2kg_demo.pydeleted file mode 100644index 00ed0b6..0000000--- a/examples/methods/itext2kg_demo.py+++ /dev/null@@ -1,100 +0,0 @@-"""-iText2KG Demo: High-Quality Knowledge Graph Extraction--This demo shows how to use iText2KG to extract structured knowledge triples from unstructured text.-iText2KG uses a two-stage extraction strategy and enforces strict semantic Schema.--Usage:- python examples/methods/itext2kg_demo.py-"""--import os-import sys-from pathlib import Path--project_root = Path(__file__).resolve().parent.parent.parent-sys.path.append(str(project_root))--from dotenv import load_dotenv-from langchain_openai import ChatOpenAI, OpenAIEmbeddings--from hyperextract.methods.typical import iText2KG--load_dotenv()--INPUT_FILE = project_root / "examples" / "inputs" / "sci_fi_story.md"---if __name__ == "__main__":- print("=" * 80)- print("Initializing iText2KG System...")- print("=" * 80)-- print(f"\n📄 Reading input file: {INPUT_FILE}")- with open(INPUT_FILE, "r", encoding="utf-8") as f:- content = f.read()- print(f"✅ Loaded {len(content)} characters")-- llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)- embedder = OpenAIEmbeddings()-- extractor = iText2KG(- llm_client=llm,- embedder=embedder,- )-- print("\nExtracting knowledge from text...")- extractor.feed_text(content)- print("✓ Extraction completed\n")-- print("=" * 80)- print("EXTRACTED ENTITIES")- print("=" * 80)-- for i, node in enumerate(extractor.nodes, 1):- print(f"\n{i}. {node.name} (Type: {node.type})")- print(f" Description: {node.description}")-- print(f"\n✓ Total entities: {len(extractor.nodes)}\n")-- print("=" * 80)- print("EXTRACTED RELATIONS")- print("=" * 80)-- for i, edge in enumerate(extractor.edges, 1):- print(f"\n{i}. {edge.subject} -[{edge.predicate}]-> {edge.object}")- print(f" Confidence: {edge.confidence}")-- print(f"\n✓ Total relations: {len(extractor.edges)}\n")-- print("=" * 80)- print("Building Index...")- print("=" * 80)-- extractor.build_index()- print("✓ Index built\n")-- print("=" * 80)- print("Q&A: KNOWLEDGE SEARCH")- print("=" * 80)-- queries = [- "Who are the key characters?",- "What is the main conflict?",- "What events happened?",- ]-- for query in queries:- print(f"\n❓ Query: {query}")- try:- nodes, edges = extractor.search(query, top_k=3)- print(" Relevant entities:")- for n in nodes[:3]:- print(f" - {n.name}")- print(" Relevant relations:")- for e in edges[:3]:- print(f" - {e.subject} {e.predicate} {e.object}")- except Exception as e:- print(f" Error: {str(e)}")-- print("\n" + "=" * 80 + "\n")diff --git a/examples/methods/itext2kg_star_demo.py b/examples/methods/itext2kg_star_demo.pydeleted file mode 100644index e52a6e1..0000000--- a/examples/methods/itext2kg_star_demo.py+++ /dev/null@@ -1,97 +0,0 @@-"""-iText2KG_Star Demo: Knowledge Graph Extraction with Semantic Deduplication--This demo shows the advanced features of iText2KG_Star:-1. Single-stage extraction: Directly extract relations (triples) from text, automatically deriving entities.-2. Semantic deduplication: Use SemHash algorithm to merge similar entities.--Usage:- python examples/methods/itext2kg_star_demo.py-"""--import os-import sys-from pathlib import Path--project_root = Path(__file__).resolve().parent.parent.parent-sys.path.append(str(project_root))--from dotenv import load_dotenv-from langchain_openai import ChatOpenAI, OpenAIEmbeddings--from hyperextract.methods.typical import iText2KG_Star--load_dotenv()--INPUT_FILE = project_root / "examples" / "inputs" / "sci_fi_story.md"---if __name__ == "__main__":- print("=" * 80)- print("Initializing iText2KG_Star System...")- print("=" * 80)-- print(f"\n📄 Reading input file: {INPUT_FILE}")- with open(INPUT_FILE, "r", encoding="utf-8") as f:- content = f.read()- print(f"✅ Loaded {len(content)} characters")-- llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)- embedder = OpenAIEmbeddings()-- extractor = iText2KG_Star(- llm_client=llm,- embedder=embedder,- )-- print("\nExtracting knowledge with deduplication...")- extractor.feed_text(content)- print("✓ Extraction completed\n")-- print("=" * 80)- print("EXTRACTED ENTITIES (After Deduplication)")- print("=" * 80)-- for i, node in enumerate(extractor.nodes, 1):- print(f"\n{i}. {node.name} (Type: {node.type})")- print(f" Description: {node.description}")-- print(f"\n✓ Total unique entities: {len(extractor.nodes)}\n")-- print("=" * 80)- print("EXTRACTED RELATIONS")- print("=" * 80)-- for i, edge in enumerate(extractor.edges, 1):- print(f"\n{i}. {edge.subject} -[{edge.predicate}]-> {edge.object}")-- print(f"\n✓ Total relations: {len(extractor.edges)}\n")-- print("=" * 80)- print("Building Index...")- print("=" * 80)-- extractor.build_index()- print("✓ Index built\n")-- print("=" * 80)- print("Q&A: KNOWLEDGE SEARCH")- print("=" * 80)-- queries = [- "Who are the key characters?",- "What is the main conflict?",- ]-- for query in queries:- print(f"\n❓ Query: {query}")- try:- nodes, edges = extractor.search(query, top_k=3)- for n in nodes[:3]:- print(f" Entity: {n.name}")- for e in edges[:3]:- print(f" Relation: {e.subject} {e.predicate} {e.object}")- except Exception as e:- print(f" Error: {str(e)}")-- print("\n" + "=" * 80 + "\n")diff --git a/examples/methods/kg_gen_demo.py b/examples/methods/kg_gen_demo.pydeleted file mode 100644index f45b20e..0000000--- a/examples/methods/kg_gen_demo.py+++ /dev/null@@ -1,99 +0,0 @@-"""-KGGenGraph Demo: Knowledge Graph Generation--This demo shows how to use KGGenGraph to extract simple triple knowledge graphs from unstructured text.-KGGenGraph is a specialized wrapper for AutoGraph, optimized with prompts and data structures for triple extraction.--Usage:- python examples/methods/kg_gen_demo.py-"""--import os-import sys-from pathlib import Path--project_root = Path(__file__).resolve().parent.parent.parent-sys.path.append(str(project_root))--from dotenv import load_dotenv-from langchain_openai import ChatOpenAI, OpenAIEmbeddings--from hyperextract.methods.typical import KG_Gen--load_dotenv()--INPUT_FILE = project_root / "examples" / "inputs" / "sci_fi_story.md"---if __name__ == "__main__":- print("=" * 80)- print("Initializing KG_Gen System...")- print("=" * 80)-- print(f"\n📄 Reading input file: {INPUT_FILE}")- with open(INPUT_FILE, "r", encoding="utf-8") as f:- content = f.read()- print(f"✅ Loaded {len(content)} characters")-- llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)- embedder = OpenAIEmbeddings()-- kg = KG_Gen(- llm_client=llm,- embedder=embedder,- )-- print("\nGenerating knowledge graph...")- kg.feed_text(content)- print("✓ Generation completed\n")-- print("=" * 80)- print("EXTRACTED ENTITIES")- print("=" * 80)-- for i, node in enumerate(kg.nodes, 1):- print(f"\n{i}. {node.name} (Type: {node.type})")- print(f" Description: {node.description}")-- print(f"\n✓ Total entities: {len(kg.nodes)}\n")-- print("=" * 80)- print("EXTRACTED RELATIONS")- print("=" * 80)-- for i, edge in enumerate(kg.edges, 1):- print(f"\n{i}. {edge.source} -> {edge.target}")- print(f" Relation: {edge.relation}")-- print(f"\n✓ Total relations: {len(kg.edges)}\n")-- print("=" * 80)- print("Building Index...")- print("=" * 80)-- kg.build_index()- print("✓ Index built\n")-- print("=" * 80)- print("Q&A: KNOWLEDGE SEARCH")- print("=" * 80)-- queries = [- "Who are the main characters?",- "What is the story about?",- ]-- for query in queries:- print(f"\n❓ Query: {query}")- try:- nodes, edges = kg.search(query, top_k=3)- print(" Entities:")- for n in nodes[:3]:- print(f" - {n.name}")- print(" Relations:")- for e in edges[:3]:- print(f" - {e.source} -> {e.target}")- except Exception as e:- print(f" Error: {str(e)}")-- print("\n" + "=" * 80 + "\n")diff --git a/examples/methods/light_rag_demo.py b/examples/methods/light_rag_demo.pydeleted file mode 100644index 85d69c5..0000000--- a/examples/methods/light_rag_demo.py+++ /dev/null@@ -1,176 +0,0 @@-"""-Light-RAG Demo: Entity-Relationship Extraction with Standard Binary Graphs--This demo demonstrates:-1. Extracting entities and binary relationships from a complex sci-fi story.-2. Analysis of standard graph relationships (Source -> Target).-3. Semantic Search over the constructed Knowledge Graph (Q&A).--Usage:- python examples/methods/light_rag_demo.py-"""--import os-import sys-from pathlib import Path--project_root = Path(__file__).resolve().parent.parent.parent-sys.path.append(str(project_root))--from dotenv import load_dotenv-load_dotenv()--from langchain_openai import ChatOpenAI, OpenAIEmbeddings-from hyperextract.methods.rag import Light_RAG--INPUT_FILE = project_root / "examples" / "inputs" / "sci_fi_story.md"---if __name__ == "__main__":- print("=" * 80)- print("Initializing Light-RAG System...")- print("=" * 80)-- print(f"\n📄 Reading input file: {INPUT_FILE}")- with open(INPUT_FILE, "r", encoding="utf-8") as f:- story = f.read()- print(f"✅ Loaded {len(story)} characters")-- llm_client = ChatOpenAI(- model="gpt-4o-mini",- )- embedder = OpenAIEmbeddings(model="text-embedding-3-small")-- rag = Light_RAG(- llm_client=llm_client,- embedder=embedder,- chunk_size=1000,- )-- print("\nFeeding story to the system...")- rag.feed_text(story)- print("✓ Story processed successfully\n")-- print("=" * 80)- print("EXTRACTED ENTITIES")- print("=" * 80)-- for node in rag.nodes:- print(f"\n【{node.name}】(Type: {node.type})")- print(f" Description: {node.description}")-- print(f"\n✓ Total entities extracted: {len(rag.nodes)}\n")-- print("=" * 80)- print("EXTRACTED EDGES (Binary Relationships)")- print("=" * 80)-- for i, edge in enumerate(rag.edges, 1):- print(f"\n{i}. {edge.source} -> {edge.target}")- print(f" Description: {edge.description}")- print(f" Keywords: {edge.keywords}")- print(f" Strength: {edge.strength}/10")-- print(f"\n✓ Total edges extracted: {len(rag.edges)}\n")-- print("=" * 80)- print("STATISTICS")- print("=" * 80)-- type_counts = {}- for node in rag.nodes:- type_counts[node.type] = type_counts.get(node.type, 0) + 1-- print("\nEntity Type Distribution:")- for entity_type, count in sorted(type_counts.items()):- print(f" {entity_type}: {count}")-- if rag.edges:- avg_strength = sum(e.strength for e in rag.edges) / len(rag.edges)- print(f"\nAverage Edge Strength: {avg_strength:.2f}/10")-- print("\nEntity Centrality (Degree):")- centrality = {}- for edge in rag.edges:- centrality[edge.source] = centrality.get(edge.source, 0) + 1- centrality[edge.target] = centrality.get(edge.target, 0) + 1-- for entity, count in sorted(centrality.items(), key=lambda x: x[1], reverse=True)[:10]:- print(f" {entity}: {count}")-- print("\n" + "=" * 80)- print("Building Semantic Index...")- print("=" * 80)-- rag.build_index()- print("✓ Semantic index built successfully\n")-- print("=" * 80)- print("Q&A: SEMANTIC SEARCH")- print("=" * 80)-- queries = [- "What happened to the crystal?",- "What is the conspiracy between the characters?",- "Who participated in the secret meeting?",- "What is Leona's current situation?",- ]-- for i, query in enumerate(queries, 1):- print(f"\n【Query {i}】{query}")- print("-" * 60)-- try:- results = rag.search_edges(query, top_k=3)-- if results:- for j, result in enumerate(results, 1):- edge = result[0] if isinstance(result, tuple) else result- score = result[1] if isinstance(result, tuple) else 1.0-- print(f"\n {j}. [Score: {score:.3f}]")- print(f" Relation: {edge.source} -> {edge.target}")- print(f" Description: {edge.description}")- print(f" Strength: {edge.strength}/10")- else:- print(" (No relevant relationships found)")- except Exception as e:- print(f" Search error: {str(e)}")-- print("\n" + "=" * 80)- print("💬 Interactive Chat with LightRAG")- print("=" * 80)- print("Engaging in multi-turn dialogue based on extracted knowledge...\n")-- for q in queries:- print(f"❓ User: {q}")- try:- response = rag.chat(q)- print(f"🤖 LightRAG: {response.content}\n")- except Exception as e:- print(f"⚠️ Chat error: {e}\n")-- print("\n" + "=" * 80)- print("Saving Results...")- print("=" * 80)-- try:- output_dir = "temp/light_rag_demo"- rag.dump(output_dir)- print(f"✓ Results saved to {output_dir}/")-- saved_files = []- if os.path.exists(output_dir):- for root, dirs, files in os.walk(output_dir):- for file in files:- rel_path = os.path.relpath(os.path.join(root, file), output_dir)- saved_files.append(rel_path)-- if saved_files:- print("\n Saved files:")- for f in saved_files:- print(f" - {f}")- except Exception as e:- print(f"⚠️ Warning: Could not save results: {str(e)}")-- print("\n" + "=" * 80 + "\n")diff --git a/examples/templates/README.md b/examples/templates/README.mddeleted file mode 100644index 7b0ef46..0000000--- a/examples/templates/README.md+++ /dev/null@@ -1,158 +0,0 @@-# Templates 目录--本目录包含 Hyper-Extract 各领域预设模板的测试工具。--## 文件说明--| 文件 | 说明 |-|------|------|-| `list_templates.py` | 列出所有可用的预设模板 |-| `finance_template.py` | 金融领域模板测试 |-| `general_template.py` | 通用领域模板测试 |-| `industry_template.py` | 工业领域模板测试 |-| `legal_template.py` | 法律领域模板测试 |-| `medicine_template.py` | 医学领域模板测试 |-| `tcm_template.py` | 中医领域模板测试 |--## 使用方法--### 列出所有模板--```bash-python examples/templates/list_templates.py-```--### 运行领域模板测试--每个领域对应一个独立的测试文件,直接运行即可:--```bash-# 金融领域-python examples/templates/finance_template.py--# 通用领域-python examples/templates/general_template.py--# 工业领域-python examples/templates/industry_template.py--# 法律领域-python examples/templates/legal_template.py--# 医学领域-python examples/templates/medicine_template.py--# 中医领域-python examples/templates/tcm_template.py-```--### 切换测试用例--每个模板文件包含多个测试用例,通过注释的方式切换:--1. 打开对应的模板文件-2. 找到"测试用例"部分-3. 取消注释要测试的用例,注释其他用例-4. 修改 `main()` 函数中的 `text` 和 `template_name`--```python-# // test for 财报电话会议摘要-# text = """星河智能科技股份有限公司..."""-# template_name = "finance/earnings_summary"--# // test for 股权结构图(取消注释此行)-text = """IPO招股说明书"""-template_name = "finance/ownership_graph"-```--## 支持的领域--| 领域 | 文件 | 模板数量 | 描述 |-|------|------|---------|------|-| finance | finance_template.py | 5 | 金融领域:财报摘要、股权结构、风险因子等 |-| general | general_template.py | 11 | 通用领域:基础图谱、传记、概念图等 |-| industry | industry_template.py | 5 | 工业领域:设备拓扑、应急响应、故障分析等 |-| legal | legal_template.py | 5 | 法律领域:案例引用、合规清单、合同义务等 |-| medicine | medicine_template.py | 5 | 医学领域:解剖图谱、药物相互作用、治疗方案等 |-| tcm | tcm_template.py | 5 | 中医领域:方剂组成、经络图、证候推理等 |--## 各领域模板列表--### Finance (金融)--| 模板名称 | 类型 | 说明 |-|---------|------|------|-| earnings_summary | model | 财报电话会议摘要 |-| event_timeline | temporal_graph | 重大事件时间线 |-| ownership_graph | graph | 股权结构图 |-| risk_factor_set | set | 风险因子集合 |-| sentiment_model | model | 市场情绪模型 |--### General (通用)--| 模板名称 | 类型 | 说明 |-|---------|------|------|-| base_graph | graph | 基础知识图谱 |-| base_hypergraph | hypergraph | 基础超图 |-| base_list | list | 基础列表 |-| biography_graph | graph | 传记图谱 |-| concept_graph | graph | 概念图谱 |-| doc_structure | list | 文档结构 |-| workflow_graph | graph | 工作流程图 |-| base_model | model | 基础模型 |-| base_set | set | 基础集合 |-| base_temporal_graph | temporal_graph | 基础时序图 |-| base_spatial_graph | spatial_graph | 基础空间图 |--### Industry (工业)--| 模板名称 | 类型 | 说明 |-|---------|------|------|-| equipment_topology | graph | 设备拓扑图 |-| operation_flow | list | 操作流程 |-| safety_control | set | 安全控制 |-| emergency_response | temporal_graph | 应急响应时间线 |-| failure_case | hypergraph | 故障案例 |--### Legal (法律)--| 模板名称 | 类型 | 说明 |-|---------|------|------|-| case_citation | graph | 案例引用图 |-| case_fact_timeline | temporal_graph | 案件事实时间线 |-| compliance_list | list | 合规清单 |-| contract_obligation | set | 合同义务 |-| defined_term_set | set | 术语定义 |--### Medicine (医学)--| 模板名称 | 类型 | 说明 |-|---------|------|------|-| anatomy_graph | graph | 解剖结构图 |-| discharge_instruction | list | 出院指导 |-| drug_interaction | graph | 药物相互作用图 |-| hospital_timeline | temporal_graph | 医院事件时间线 |-| treatment_map | hypergraph | 治疗方案图 |--### TCM (中医)--| 模板名称 | 类型 | 说明 |-|---------|------|------|-| formula_composition | graph | 方剂组成图 |-| herb_property | model | 药材属性 |-| herb_relation | graph | 药材关系图 |-| meridian_graph | graph | 经络图 |-| syndrome_reasoning | hypergraph | 证候推理 |--## 模板类型--| 类型 | 对应 AutoType |-|------|--------------|-| graph | AutoGraph |-| hypergraph | AutoHypergraph |-| list | AutoList |-| model | AutoModel |-| set | AutoSet |-| temporal_graph | AutoTemporalGraph |-| spatial_graph | AutoSpatialGraph |-| spatio_temporal_graph | AutoSpatioTemporalGraph |diff --git a/examples/zh/autotypes/graph_demo.py b/examples/zh/autotypes/graph_demo.pynew file mode 100644index 0000000..6704a43--- /dev/null+++ b/examples/zh/autotypes/graph_demo.py@@ -0,0 +1,72 @@+"""+图谱提取示例 - 苏轼传记++使用 AutoGraph 从文本中提取实体和关系,构建知识图谱。++使用方法:+ python examples/zh/autotypes/graph_demo.py+"""++import sys+from pathlib import Path+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+import dotenv++dotenv.load_dotenv()++from pydantic import BaseModel, Field+from hyperextract.types import AutoGraph+++class Entity(BaseModel):+ """知识图谱中的实体"""+ name: str = Field(description="实体名称")+ type: str = Field(description="实体类型:人物/地名/作品", default="人物")+++class Relation(BaseModel):+ """实体之间的关系"""+ source: str = Field(description="关系起点实体")+ target: str = Field(description="关系终点实体")+ type: str = Field(description="关系类型:父亲/兄弟/师徒/朋友/政敌")+++def main():+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")++ input_file = Path(__file__).parent.parent.parent / "zh" / "sushi.md"+ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("\n" + "=" * 60)+ print(" 图谱提取示例")+ print("=" * 60)+ print("从苏轼传记中提取实体和关系...")++ graph = AutoGraph[Entity, Relation](+ node_schema=Entity,+ edge_schema=Relation,+ llm_client=llm,+ embedder=embedder,+ )++ graph.feed_text(text)++ print(f"\n提取了 {len(graph.nodes)} 个实体和 {len(graph.edges)} 个关系")++ graph.build_index()++ for q in [+ "苏轼的家庭关系有哪些?",+ "苏轼与哪些人有过师徒关系?",+ "苏轼创作了哪些著名作品?",+ ]:+ print(f"\n问题:{q}")+ nodes, edges = graph.search(q, top_k_nodes=3, top_k_edges=3)+ print(f" 实体:{[n.name for n in nodes]}")+ print(f" 关系:{[e.type for e in edges]}")+++if __name__ == "__main__":+ main()diff --git a/examples/zh/autotypes/hypergraph_demo.py b/examples/zh/autotypes/hypergraph_demo.pynew file mode 100644index 0000000..5dfbaa5--- /dev/null+++ b/examples/zh/autotypes/hypergraph_demo.py@@ -0,0 +1,71 @@+"""+超图示例 - 苏轼传记++使用 AutoHyperGraph 从文本中提取超关系。++使用方法:+ python examples/zh/autotypes/hypergraph_demo.py+"""++import sys+from pathlib import Path+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+import dotenv++dotenv.load_dotenv()++from pydantic import BaseModel, Field+from hyperextract.types import AutoHyperGraph+++class Entity(BaseModel):+ """实体节点"""+ name: str = Field(description="实体名称")+ type: str = Field(description="类型:人物/地名/作品", default="人物")+++class HyperEdge(BaseModel):+ """超边(多实体关系)"""+ description: str = Field(description="关系描述")+ members: list[str] = Field(description="参与的实体")+ type: str = Field(description="关系类型")+++def main():+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")++ input_file = Path(__file__).parent.parent.parent / "zh" / "sushi.md"+ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("\n" + "=" * 60)+ print(" 超图示例")+ print("=" * 60)+ print("提取多实体关系...")++ graph = AutoHyperGraph[Entity, HyperEdge](+ node_schema=Entity,+ edge_schema=HyperEdge,+ llm_client=llm,+ embedder=embedder,+ )++ graph.feed_text(text)++ print(f"\n提取了 {len(graph.nodes)} 个实体和 {len(graph.edges)} 个超边")++ for edge in graph.edges[:5]:+ print(f"\n{edge.type}:{edge.description}")+ print(f" 成员:{', '.join(edge.members)}")++ graph.build_index()++ for q in ["乌台诗案", "创作", "贬谪"]:+ print(f"\n查询:{q}")+ nodes, edges = graph.search(q, top_k_nodes=3, top_k_edges=3)+ print(f" 找到 {len(edges)} 个相关超边")+++if __name__ == "__main__":+ main()diff --git a/examples/zh/autotypes/list_demo.py b/examples/zh/autotypes/list_demo.pynew file mode 100644index 0000000..ec30c00--- /dev/null+++ b/examples/zh/autotypes/list_demo.py@@ -0,0 +1,65 @@+"""+AutoList 示例 - 苏轼人生事件++使用 AutoList 从文本中提取列表项,合并多个文本块。++使用方法:+ python examples/zh/autotypes/list_demo.py+"""++import sys+from pathlib import Path+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+import dotenv++dotenv.load_dotenv()++from pydantic import BaseModel, Field+from hyperextract import AutoList+++class TimelineEvent(BaseModel):+ """人生事件"""+ year: str = Field(description="事件发生年份")+ title: str = Field(description="事件标题")+ description: str = Field(description="事件描述")+++def main():+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")++ input_file = Path(__file__).parent.parent.parent / "zh" / "sushi.md"+ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("\n" + "=" * 60)+ print(" AutoList 示例 - 苏轼人生事件")+ print("=" * 60)+ print("提取人生事件时间线...")++ timeline = AutoList[TimelineEvent](+ item_schema=TimelineEvent,+ llm_client=llm,+ embedder=embedder,+ )++ timeline.feed_text(text)++ sorted_events = sorted(timeline.items, key=lambda x: x.year)+ print(f"\n提取了 {len(sorted_events)} 个事件")++ for event in sorted_events[:5]:+ print(f" {event.year}:{event.title}")++ timeline.build_index()++ for q in ["贬谪", "创作", "黄州"]:+ print(f"\n查询:{q}")+ results = timeline.search(q, top_k=3)+ for r in results:+ print(f" {r.year}:{r.title}")+++if __name__ == "__main__":+ main()diff --git a/examples/zh/autotypes/model_demo.py b/examples/zh/autotypes/model_demo.pynew file mode 100644index 0000000..7292708--- /dev/null+++ b/examples/zh/autotypes/model_demo.py@@ -0,0 +1,77 @@+"""+AutoModel 示例 - 苏轼传记摘要++使用 AutoModel 从文本中提取结构化摘要。++使用方法:+ python examples/zh/autotypes/model_demo.py+"""++import sys+from pathlib import Path+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+import dotenv++dotenv.load_dotenv()++from pydantic import BaseModel, Field+from typing import List, Optional+from hyperextract import AutoModel+++class BiographySummary(BaseModel):+ """传记摘要结构"""+ title: str = Field(description="作品标题")+ subject: str = Field(description="主人公姓名")+ birth_year: Optional[str] = Field(default="", description="出生年份")+ death_year: Optional[str] = Field(default="", description="逝世年份")+ style_name: str = Field(description="字/号", default="")+ era: str = Field(description="所属朝代", default="")+ identity: List[str] = Field(default_factory=list, description="主要身份")+ summary: str = Field(description="人物生平概述")+ major_works: List[str] = Field(default_factory=list, description="代表作品")+++def main():+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")++ input_file = Path(__file__).parent.parent.parent / "zh" / "sushi.md"+ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("\n" + "=" * 60)+ print(" AutoModel 示例 - 苏轼传记摘要")+ print("=" * 60)+ print("提取传记摘要...")++ model = AutoModel(+ data_schema=BiographySummary,+ llm_client=llm,+ embedder=embedder,+ )++ model.feed_text(text)++ data = model.data+ print(f"\n主人公:{data.subject}")+ print(f"生卒年份:{data.birth_year} - {data.death_year}")+ print(f"字号:{data.style_name}")+ print(f"\n摘要:{data.summary}")++ if data.major_works:+ print(f"\n代表作品:")+ for work in data.major_works[:3]:+ print(f" - {work}")++ model.build_index()++ for q in ["作品", "黄州", "影响"]:+ print(f"\n查询:{q}")+ results = model.search(q, top_k=2)+ for r in results:+ print(f" {r}")+++if __name__ == "__main__":+ main()diff --git a/examples/zh/autotypes/set_demo.py b/examples/zh/autotypes/set_demo.pynew file mode 100644index 0000000..68e35e8--- /dev/null+++ b/examples/zh/autotypes/set_demo.py@@ -0,0 +1,71 @@+"""+AutoSet 示例 - 苏轼相关人物++使用 AutoSet 从文本中提取去重的人物集合。++使用方法:+ python examples/zh/autotypes/set_demo.py+"""++import sys+from pathlib import Path+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+import dotenv++dotenv.load_dotenv()++from pydantic import BaseModel, Field+from hyperextract import AutoSet+++class Person(BaseModel):+ """人物实体"""+ name: str = Field(description="人物姓名")+ category: str = Field(description="类别:家人/师友/政敌", default="人物")+ description: str = Field(description="简要描述", default="")+++def main():+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")++ input_file = Path(__file__).parent.parent.parent / "zh" / "sushi.md"+ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("\n" + "=" * 60)+ print(" AutoSet 示例 - 苏轼相关人物")+ print("=" * 60)+ print("提取并去重人物...")++ entities = AutoSet[Person](+ item_schema=Person,+ llm_client=llm,+ embedder=embedder,+ key_extractor=lambda x: x.name,+ )++ entities.feed_text(text)++ print(f"\n提取了 {len(entities.items)} 个不同人物")++ categories = {}+ for p in entities.items:+ categories.setdefault(p.category, []).append(p)++ for cat, persons in sorted(categories.items()):+ print(f"\n{cat}:")+ for p in persons[:5]:+ print(f" - {p.name}")++ entities.build_index()++ for q in ["苏洵", "王安石", "欧阳修"]:+ print(f"\n查询:{q}")+ results = entities.search(q, top_k=3)+ for r in results:+ print(f" {r.name}({r.category})")+++if __name__ == "__main__":+ main()diff --git a/examples/zh/autotypes/spatial_demo.py b/examples/zh/autotypes/spatial_demo.pynew file mode 100644index 0000000..f336132--- /dev/null+++ b/examples/zh/autotypes/spatial_demo.py@@ -0,0 +1,72 @@+"""+空间图示例 - 苏轼传记++使用 AutoSpatialGraph 从文本中提取空间关系。++使用方法:+ python examples/zh/autotypes/spatial_demo.py+"""++import sys+from pathlib import Path+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+import dotenv++dotenv.load_dotenv()++from pydantic import BaseModel, Field+from hyperextract.types import AutoSpatialGraph+++class Location(BaseModel):+ """地点实体"""+ name: str = Field(description="地点名称")+ category: str = Field(description="类别:城市/建筑/地区", default="地区")+ description: str = Field(description="简要描述", default="")+++class SpatialRelation(BaseModel):+ """空间关系"""+ source: str = Field(description="起点地点")+ target: str = Field(description="终点地点")+ relation: str = Field(description="空间关系类型")+++def main():+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")++ input_file = Path(__file__).parent.parent.parent / "zh" / "sushi.md"+ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("\n" + "=" * 60)+ print(" 空间图示例")+ print("=" * 60)+ print("提取空间关系...")++ graph = AutoSpatialGraph[Location, SpatialRelation](+ node_schema=Location,+ edge_schema=SpatialRelation,+ llm_client=llm,+ embedder=embedder,+ observation_location="北宋疆域",+ )++ graph.feed_text(text)++ print(f"\n提取了 {len(graph.nodes)} 个地点和 {len(graph.edges)} 个关系")++ for node in graph.nodes[:5]:+ print(f" {node.name}")++ graph.build_index()++ for q in ["眉山", "黄州", "杭州"]:+ print(f"\n查询:{q}")+ nodes, edges = graph.search(q, top_k_nodes=3, top_k_edges=3)+ print(f" 地点:{[n.name for n in nodes]}")+++if __name__ == "__main__":+ main()diff --git a/examples/zh/autotypes/spatio_temporal_demo.py b/examples/zh/autotypes/spatio_temporal_demo.pynew file mode 100644index 0000000..31fcfe9--- /dev/null+++ b/examples/zh/autotypes/spatio_temporal_demo.py@@ -0,0 +1,77 @@+"""+时空图示例 - 苏轼传记++使用 AutoSpatioTemporalGraph 从文本中提取时空关系。++使用方法:+ python examples/zh/autotypes/spatio_temporal_demo.py+"""++import sys+from pathlib import Path+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+import dotenv++dotenv.load_dotenv()++from pydantic import BaseModel, Field+from typing import Optional+from hyperextract.types import AutoSpatioTemporalGraph+++class Entity(BaseModel):+ """实体节点"""+ name: str = Field(description="实体名称")+ category: str = Field(description="类别", default="人物")+++class SpatioTemporalEvent(BaseModel):+ """时空事件"""+ source: str = Field(description="起点实体")+ target: str = Field(description="终点实体")+ action: str = Field(description="动作或关系")+ time: Optional[str] = Field(description="何时", default=None)+ location: Optional[str] = Field(description="何地", default=None)+++def main():+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")++ input_file = Path(__file__).parent.parent.parent / "zh" / "sushi.md"+ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("\n" + "=" * 60)+ print(" 时空图示例")+ print("=" * 60)+ print("提取时空事件...")++ graph = AutoSpatioTemporalGraph[Entity, SpatioTemporalEvent](+ node_schema=Entity,+ edge_schema=SpatioTemporalEvent,+ llm_client=llm,+ embedder=embedder,+ observation_location="北宋",+ )++ graph.feed_text(text)++ print(f"\n提取了 {len(graph.nodes)} 个实体和 {len(graph.edges)} 个事件")++ sorted_edges = sorted(graph.edges, key=lambda x: x.time or "")+ for edge in sorted_edges[:5]:+ time_info = f"({edge.time})" if edge.time else ""+ loc_info = f" 在 {edge.location}" if edge.location else ""+ print(f" {edge.source} --[{edge.action}]--> {edge.target}{time_info}{loc_info}")++ graph.build_index()++ for q in ["黄州", "杭州", "贬谪"]:+ print(f"\n查询:{q}")+ nodes, edges = graph.search(q, top_k_nodes=3, top_k_edges=3)+ print(f" 找到 {len(nodes)} 个实体,{len(edges)} 个事件")+++if __name__ == "__main__":+ main()diff --git a/examples/zh/autotypes/temporal_demo.py b/examples/zh/autotypes/temporal_demo.pynew file mode 100644index 0000000..ed164c2--- /dev/null+++ b/examples/zh/autotypes/temporal_demo.py@@ -0,0 +1,71 @@+"""+时序图示例 - 苏轼传记++使用 AutoTemporalGraph 从文本中提取时序关系。++使用方法:+ python examples/zh/autotypes/temporal_demo.py+"""++import sys+from pathlib import Path+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+import dotenv++dotenv.load_dotenv()++from pydantic import BaseModel, Field+from hyperextract.types import AutoTemporalGraph+++class Entity(BaseModel):+ """实体节点"""+ name: str = Field(description="实体名称")+ type: str = Field(description="类型:人物/地名/作品", default="人物")+++class TimelineEvent(BaseModel):+ """时间线事件"""+ time: str = Field(description="时间(年份)")+ event: str = Field(description="事件描述")+ entities: list[str] = Field(description="参与实体")+++def main():+ llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)+ embedder = OpenAIEmbeddings(model="text-embedding-3-small")++ input_file = Path(__file__).parent.parent.parent / "zh" / "sushi.md"+ with open(input_file, "r", encoding="utf-8") as f:+ text = f.read()++ print("\n" + "=" * 60)+ print(" 时序图示例")+ print("=" * 60)+ print("提取时序关系...")++ graph = AutoTemporalGraph[Entity, TimelineEvent](+ node_schema=Entity,+ edge_schema=TimelineEvent,+ llm_client=llm,+ embedder=embedder,+ )++ graph.feed_text(text)++ print(f"\n提取了 {len(graph.nodes)} 个实体和 {len(graph.edges)} 个事件")++ sorted_events = sorted(graph.edges, key=lambda x: x.time)+ for event in sorted_events[:5]:+ print(f" {event.time}:{event.event}")++ graph.build_index()++ for q in ["黄州", "贬谪", "乌台诗案"]:+ print(f"\n查询:{q}")+ nodes, edges = graph.search(q, top_k_nodes=3, top_k_edges=3)+ print(f" 事件:{[e.time for e in edges]}")+++if __name__ == "__main__":+ main()diff --git a/examples/zh/methods/atom_demo.py b/examples/zh/methods/atom_demo.pynew file mode 100644index 0000000..450c524--- /dev/null+++ b/examples/zh/methods/atom_demo.py@@ -0,0 +1,51 @@+"""+Atom 示例:苏轼传记时序抽取++使用 Atom 从苏轼传记中提取时序事实。++Usage:+ python examples/zh/methods/atom_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.typical import Atom++load_dotenv()++INPUT_FILE = project_root / "examples" / "zh" / "sushi.md"+QUESTION_FILE = project_root / "examples" / "zh" / "sushi_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE, encoding="utf-8") as f:+ text = f.read()+ with open(QUESTION_FILE, encoding="utf-8") as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("Atom 示例")+ print("=" * 60)++ atom = Atom(llm_client=llm, embedder=embedder)+ atom.feed_text(text)++ print(f"\n✓ 提取了 {len(atom.facts)} 条时序事实\n")++ print("-" * 60)+ print("问答")+ print("-" * 60)+ for q in questions:+ print(f"\n问: {q}")+ try:+ result = atom.chat(q)+ print(f"答: {result.content}")+ except Exception as e:+ print(f"错误: {e}")diff --git a/examples/zh/methods/cog_rag_demo.py b/examples/zh/methods/cog_rag_demo.pynew file mode 100644index 0000000..af51574--- /dev/null+++ b/examples/zh/methods/cog_rag_demo.py@@ -0,0 +1,51 @@+"""+Cog RAG 示例:苏轼传记认知知识图谱++使用 Cog RAG 从苏轼传记中提取主题和实体的认知知识。++Usage:+ python examples/zh/methods/cog_rag_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.rag import Cog_RAG++load_dotenv()++INPUT_FILE = project_root / "examples" / "zh" / "sushi.md"+QUESTION_FILE = project_root / "examples" / "zh" / "sushi_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE, encoding="utf-8") as f:+ text = f.read()+ with open(QUESTION_FILE, encoding="utf-8") as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("Cog RAG 示例")+ print("=" * 60)++ rag = Cog_RAG(llm_client=llm, embedder=embedder)+ rag.feed_text(text)++ print(f"\n✓ 提取了 {len(rag.themes)} 个主题,{len(rag.nodes)} 个实体\n")++ print("-" * 60)+ print("问答")+ print("-" * 60)+ for q in questions:+ print(f"\n问: {q}")+ try:+ result = rag.chat(q)+ print(f"答: {result.content}")+ except Exception as e:+ print(f"错误: {e}")diff --git a/examples/zh/methods/graph_rag_demo.py b/examples/zh/methods/graph_rag_demo.pynew file mode 100644index 0000000..9512f76--- /dev/null+++ b/examples/zh/methods/graph_rag_demo.py@@ -0,0 +1,51 @@+"""+Graph RAG 示例:苏轼传记知识图谱++使用 Graph RAG 从苏轼传记中提取和查询知识。++Usage:+ python examples/zh/methods/graph_rag_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.rag import Graph_RAG++load_dotenv()++INPUT_FILE = project_root / "examples" / "zh" / "sushi.md"+QUESTION_FILE = project_root / "examples" / "zh" / "sushi_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE, encoding="utf-8") as f:+ text = f.read()+ with open(QUESTION_FILE, encoding="utf-8") as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("Graph RAG 示例")+ print("=" * 60)++ rag = Graph_RAG(llm_client=llm, embedder=embedder)+ rag.feed_text(text)++ print(f"\n✓ 提取了 {len(rag.nodes)} 个实体,{len(rag.edges)} 条关系\n")++ print("-" * 60)+ print("问答")+ print("-" * 60)+ for q in questions:+ print(f"\n问: {q}")+ try:+ result = rag.chat(q)+ print(f"答: {result.content}")+ except Exception as e:+ print(f"错误: {e}")diff --git a/examples/zh/methods/hyper_rag_demo.py b/examples/zh/methods/hyper_rag_demo.pynew file mode 100644index 0000000..175c56d--- /dev/null+++ b/examples/zh/methods/hyper_rag_demo.py@@ -0,0 +1,51 @@+"""+Hyper RAG 示例:苏轼传记超图抽取++使用 Hyper RAG 从苏轼传记中提取超图知识。++Usage:+ python examples/zh/methods/hyper_rag_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.rag import Hyper_RAG++load_dotenv()++INPUT_FILE = project_root / "examples" / "zh" / "sushi.md"+QUESTION_FILE = project_root / "examples" / "zh" / "sushi_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE, encoding="utf-8") as f:+ text = f.read()+ with open(QUESTION_FILE, encoding="utf-8") as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("Hyper RAG 示例")+ print("=" * 60)++ rag = Hyper_RAG(llm_client=llm, embedder=embedder)+ rag.feed_text(text)++ print(f"\n✓ 提取了 {len(rag.nodes)} 个实体,{len(rag.hyper_edges)} 个超边\n")++ print("-" * 60)+ print("问答")+ print("-" * 60)+ for q in questions:+ print(f"\n问: {q}")+ try:+ result = rag.chat(q)+ print(f"答: {result.content}")+ except Exception as e:+ print(f"错误: {e}")diff --git a/examples/zh/methods/hypergraph_rag_demo.py b/examples/zh/methods/hypergraph_rag_demo.pynew file mode 100644index 0000000..4254885--- /dev/null+++ b/examples/zh/methods/hypergraph_rag_demo.py@@ -0,0 +1,51 @@+"""+HyperGraph RAG 示例:苏轼传记多实体关系++使用 HyperGraph RAG 从苏轼传记中提取多实体关系。++Usage:+ python examples/zh/methods/hypergraph_rag_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.rag import HyperGraph_RAG++load_dotenv()++INPUT_FILE = project_root / "examples" / "zh" / "sushi.md"+QUESTION_FILE = project_root / "examples" / "zh" / "sushi_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE, encoding="utf-8") as f:+ text = f.read()+ with open(QUESTION_FILE, encoding="utf-8") as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("HyperGraph RAG 示例")+ print("=" * 60)++ rag = HyperGraph_RAG(llm_client=llm, embedder=embedder)+ rag.feed_text(text)++ print(f"\n✓ 提取了 {len(rag.nodes)} 个实体,{len(rag.hyper_edges)} 个超边\n")++ print("-" * 60)+ print("问答")+ print("-" * 60)+ for q in questions:+ print(f"\n问: {q}")+ try:+ result = rag.chat(q)+ print(f"答: {result.content}")+ except Exception as e:+ print(f"错误: {e}")diff --git a/examples/zh/methods/itext2kg_demo.py b/examples/zh/methods/itext2kg_demo.pynew file mode 100644index 0000000..c2a2629--- /dev/null+++ b/examples/zh/methods/itext2kg_demo.py@@ -0,0 +1,51 @@+"""+iText2KG 示例:苏轼传记知识抽取++使用 iText2KG 从苏轼传记中提取结构化知识三元组。++Usage:+ python examples/zh/methods/itext2kg_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.typical import iText2KG++load_dotenv()++INPUT_FILE = project_root / "examples" / "zh" / "sushi.md"+QUESTION_FILE = project_root / "examples" / "zh" / "sushi_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE, encoding="utf-8") as f:+ text = f.read()+ with open(QUESTION_FILE, encoding="utf-8") as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("iText2KG 示例")+ print("=" * 60)++ ka = iText2KG(llm_client=llm, embedder=embedder)+ ka.feed_text(text)++ print(f"\n✓ 提取了 {len(ka.nodes)} 个实体,{len(ka.edges)} 条关系\n")++ print("-" * 60)+ print("问答")+ print("-" * 60)+ for q in questions:+ print(f"\n问: {q}")+ try:+ result = ka.chat(q)+ print(f"答: {result.content}")+ except Exception as e:+ print(f"错误: {e}")diff --git a/examples/zh/methods/itext2kg_star_demo.py b/examples/zh/methods/itext2kg_star_demo.pynew file mode 100644index 0000000..886e73a--- /dev/null+++ b/examples/zh/methods/itext2kg_star_demo.py@@ -0,0 +1,51 @@+"""+iText2KG Star 示例:苏轼传记去重抽取++使用 iText2KG_Star 从苏轼传记中提取带语义去重的知识。++Usage:+ python examples/zh/methods/itext2kg_star_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.typical import iText2KG_Star++load_dotenv()++INPUT_FILE = project_root / "examples" / "zh" / "sushi.md"+QUESTION_FILE = project_root / "examples" / "zh" / "sushi_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE, encoding="utf-8") as f:+ text = f.read()+ with open(QUESTION_FILE, encoding="utf-8") as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("iText2KG Star 示例")+ print("=" * 60)++ ka = iText2KG_Star(llm_client=llm, embedder=embedder)+ ka.feed_text(text)++ print(f"\n✓ 提取了 {len(ka.nodes)} 个实体,{len(ka.edges)} 条关系\n")++ print("-" * 60)+ print("问答")+ print("-" * 60)+ for q in questions:+ print(f"\n问: {q}")+ try:+ result = ka.chat(q)+ print(f"答: {result.content}")+ except Exception as e:+ print(f"错误: {e}")diff --git a/examples/zh/methods/kg_gen_demo.py b/examples/zh/methods/kg_gen_demo.pynew file mode 100644index 0000000..51fad2b--- /dev/null+++ b/examples/zh/methods/kg_gen_demo.py@@ -0,0 +1,51 @@+"""+KG Gen 示例:苏轼传记图谱生成++使用 KG_Gen 从苏轼传记中生成简单知识图谱。++Usage:+ python examples/zh/methods/kg_gen_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.typical import KG_Gen++load_dotenv()++INPUT_FILE = project_root / "examples" / "zh" / "sushi.md"+QUESTION_FILE = project_root / "examples" / "zh" / "sushi_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE, encoding="utf-8") as f:+ text = f.read()+ with open(QUESTION_FILE, encoding="utf-8") as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("KG Gen 示例")+ print("=" * 60)++ ka = KG_Gen(llm_client=llm, embedder=embedder)+ ka.feed_text(text)++ print(f"\n✓ 提取了 {len(ka.nodes)} 个实体,{len(ka.edges)} 条关系\n")++ print("-" * 60)+ print("问答")+ print("-" * 60)+ for q in questions:+ print(f"\n问: {q}")+ try:+ result = ka.chat(q)+ print(f"答: {result.content}")+ except Exception as e:+ print(f"错误: {e}")diff --git a/examples/zh/methods/light_rag_demo.py b/examples/zh/methods/light_rag_demo.pynew file mode 100644index 0000000..749c803--- /dev/null+++ b/examples/zh/methods/light_rag_demo.py@@ -0,0 +1,51 @@+"""+Light RAG 示例:苏轼传记简单知识图谱++使用 Light RAG 从苏轼传记中提取简单知识。++Usage:+ python examples/zh/methods/light_rag_demo.py+"""++import sys+from pathlib import Path+project_root = Path(__file__).resolve().parent.parent.parent+sys.path.append(str(project_root))++from dotenv import load_dotenv+from langchain_openai import ChatOpenAI, OpenAIEmbeddings+from hyperextract.methods.rag import Light_RAG++load_dotenv()++INPUT_FILE = project_root / "examples" / "zh" / "sushi.md"+QUESTION_FILE = project_root / "examples" / "zh" / "sushi_question.md"++if __name__ == "__main__":+ with open(INPUT_FILE, encoding="utf-8") as f:+ text = f.read()+ with open(QUESTION_FILE, encoding="utf-8") as f:+ questions = [line.strip() for line in f if line.strip()]++ llm = ChatOpenAI(model="gpt-4o-mini")+ embedder = OpenAIEmbeddings()++ print("=" * 60)+ print("Light RAG 示例")+ print("=" * 60)++ rag = Light_RAG(llm_client=llm, embedder=embedder)+ rag.feed_text(text)++ print(f"\n✓ 提取了 {len(rag.nodes)} 个实体,{len(rag.edges)} 条关系\n")++ print("-" * 60)+ print("问答")+ print("-" * 60)+ for q in questions:+ print(f"\n问: {q}")+ try:+ result = rag.chat(q)+ print(f"答: {result.content}")+ except Exception as e:+ print(f"错误: {e}")diff --git a/examples/zh/sushi.md b/examples/zh/sushi.mdnew file mode 100644index 0000000..a7c59e8--- /dev/null+++ b/examples/zh/sushi.md@@ -0,0 +1,81 @@+# 苏轼传++苏轼,字子瞻,号东坡居士,是北宋著名的文学家、书画家、政治家。他与父亲苏洵、弟弟苏辙并称"三苏",同列唐宋八大家。++## 早年与家学++苏轼于1037年出生于眉州眉山。他的父亲苏洵是著名学者,对苏轼和弟弟苏辙的教育极为严格。苏轼自幼聪慧,在父亲的教导下,与弟弟苏辙一起苦读诗文。++1056年,19岁的苏轼与父亲、弟弟一起进京赶考。当时的主考官是大文豪欧阳修,欧阳修对苏轼的策论赞叹不已,认为他日后必成大器。++## 仕途与起伏++1057年,苏轼与弟弟苏辙同科中举,被任命为福昌县主簿。但苏轼心中有大志,他参加了制科考试,以优异成绩被任命为大理评事。++1069年,苏轼回到京城开封,适逢王安石推行新法。苏轼与王安石政见不合,多次上书反对新法。他认为新法过于激进,损害了百姓利益。++1071年,苏轼主动请求外放,被任命为杭州通判。此后,他先后在密州、徐州、湖州等地任职。++## 乌台诗案++1079年,苏轼在湖州任上写了许多讽刺新法的诗作,被人告发。这就是著名的"乌台诗案"。苏轼被押送回京,下狱待审。++在狱中,苏轼几乎以为自己必死无疑。他的弟弟苏辙上书请求以自己的官职为哥哥赎罪。许多朋友和官员也为他求情。++最终,苏轼被贬为黄州团练副使,这是一个没有实权的闲职。在黄州期间,苏轼开垦荒地,自号"东坡居士",创作了许多著名诗文,包括《念奴娇·赤壁怀古》和前、后《赤壁赋》。++## 与佛印的友谊++在黄州期间,苏轼与高僧佛印禅师结为好友。两人经常在一起参禅论道,留下了许多趣事。++一次,苏轼写诗说自己"八风吹不动",佛印回复"放屁"二字。苏轼大怒,过江找佛印理论。佛印笑着说:"你不是八风吹不动吗?怎么一屁就打过江来了?"++苏轼哑然失笑,从此更加敬重佛印。++## 杭州岁月++1089年,苏轼任杭州知州。他关心民生,治理西湖,修建了著名的"苏堤"。这道堤坝至今仍是西湖十景之一。++在杭州,苏轼还救治了许多贫苦百姓。他自己生活简朴,却经常资助他人。++## 晚年与贬谪++1093年,苏轼的结发妻子王弗病逝,他悲痛欲绝。后来,侍妾朝云一直陪伴在他身边。++1097年,62岁的苏轼被贬至惠州,后又被贬至更远的海南岛儋州。在那个时代,儋州是极偏僻的地方,几乎等同于流放。++但苏轼依然乐观豁达。他与当地百姓相处融洽,教书育人,传播文化。++## 逝世++1101年,苏轼获准北归,但身体已经衰弱。他病逝于常州,享年65岁。++苏轼一生坎坷,却始终保持旷达的心态。他的诗文、书画流传千古,他与弟弟苏辙的手足之情也被传为佳话。++## 人物关系++### 家人+- 父亲苏洵:著名学者,教导苏轼成才+- 弟弟苏辙:同为文学家,苏轼最亲密的手足+- 妻子王弗:结发妻子,早年病逝+- 侍妾朝云:陪伴苏轼晚年的红颜知己++### 师友+- 欧阳修:恩师,苏轼科考的主考官+- 佛印禅师:高僧好友,常与苏轼论禅+- 黄庭坚:学生,书法家++### 政敌+- 王安石:变法领袖,与苏轼政见不合+- 变法派:多次迫害苏轼++## 重要时间线++- 1037年:出生于眉州眉山+- 1056年:随父、弟进京赶考+- 1057年:科考中举,师从欧阳修+- 1069年:回京,反对王安石变法+- 1079年:乌台诗案,被贬黄州+- 1089年:任杭州知州,修建苏堤+- 1097年:被贬惠州,后至儋州+- 1101年:病逝于常州diff --git a/examples/zh/sushi_question.md b/examples/zh/sushi_question.mdnew file mode 100644index 0000000..820fca5--- /dev/null+++ b/examples/zh/sushi_question.md@@ -0,0 +1,3 @@+1. 苏轼的家庭关系和师友有哪些?+2. 苏轼的仕途经历如何影响了他的文学创作?+3. 苏轼被贬谪期间创作了哪些著名作品?diff --git a/examples/templates/finance_template.py b/examples/zh/templates/finance_template.pysimilarity index 100%rename from examples/templates/finance_template.pyrename to examples/zh/templates/finance_template.pydiff --git a/examples/templates/general_template.py b/examples/zh/templates/general_template.pysimilarity index 100%rename from examples/templates/general_template.pyrename to examples/zh/templates/general_template.pydiff --git a/examples/templates/industry_template.py b/examples/zh/templates/industry_template.pysimilarity index 100%rename from examples/templates/industry_template.pyrename to examples/zh/templates/industry_template.pydiff --git a/examples/templates/legal_template.py b/examples/zh/templates/legal_template.pysimilarity index 100%rename from examples/templates/legal_template.pyrename to examples/zh/templates/legal_template.pydiff --git a/examples/templates/list_templates.py b/examples/zh/templates/list_templates.pysimilarity index 100%rename from examples/templates/list_templates.pyrename to examples/zh/templates/list_templates.pydiff --git a/examples/templates/medicine_template.py b/examples/zh/templates/medicine_template.pysimilarity index 100%rename from examples/templates/medicine_template.pyrename to examples/zh/templates/medicine_template.pydiff --git a/examples/templates/tcm_template.py b/examples/zh/templates/tcm_template.pysimilarity index 100%rename from examples/templates/tcm_template.pyrename to examples/zh/templates/tcm_template.py