Skip to content

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

docs: 更新文档内容并优化模板描述

yifanfeng97b793462fb9de
diff --git a/README.md b/README.md
index 3df16c4..9258f92 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,9 @@
<br/>
<br/>
-**Smart Knowledge Extraction CLI — Transform documents into structured knowledge with one command.**
+**Smart Knowledge Extraction CLI**
+
+**Transform documents into structured knowledge with one command.**
[📖 English Version](./README.md) · [中文版](./README_ZH.md)
diff --git a/README_ZH.md b/README_ZH.md
index fd3a7bb..567b636 100644
--- a/README_ZH.md
+++ b/README_ZH.md
@@ -9,7 +9,9 @@
<br/>
<br/>
-**智能知识提取 CLI —— 一行命令,将文档转化为结构化知识。**
+**智能知识提取 CLI**
+
+**一行命令,将文档转化为结构化知识。**
[📖 English Version](./README.md) · [中文版](./README_ZH.md)
diff --git a/docs/assets/logo/logo-app.svg b/docs/assets/logo/logo-app.svg
index f7eb5cc..69e3020 100644
--- a/docs/assets/logo/logo-app.svg
+++ b/docs/assets/logo/logo-app.svg
@@ -1,7 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500" width="100%" height="100%">
<!-- Dark background rounded rectangle for app icon / avatar -->
<rect width="500" height="500" rx="40" fill="#0D0715"/>
- <g transform="translate(0, -20)">
+ <g transform="translate(0, -35)">
<polyline points="250,150 150,200 150,300 250,350" fill="none" stroke="#7A52BD" stroke-width="15" stroke-dasharray="16, 20" stroke-linecap="round" stroke-linejoin="round"/>
<polyline points="250,150 350,200 350,300 250,350" fill="none" stroke="#B275FF" stroke-width="17" stroke-linecap="round" stroke-linejoin="round"/>
<line x1="250" y1="250" x2="160" y2="198" stroke="#7A52BD" stroke-width="12" stroke-linecap="round" stroke-dasharray="16, 20"/>
@@ -13,7 +13,7 @@
<circle cx="350" cy="200" r="10" fill="#FFFFFF"/>
<circle cx="350" cy="300" r="10" fill="#FFFFFF"/>
</g>
- <text x="250" y="440" font-family="system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" font-size="36" font-weight="900" fill="#FFFFFF" text-anchor="middle" letter-spacing="8">
+ <text x="250" y="420" font-family="system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" font-size="36" font-weight="900" fill="#FFFFFF" text-anchor="middle" letter-spacing="8">
HYPER<tspan fill="#A259FF">EXTRACT</tspan>
</text>
</svg>
\ No newline at end of file
diff --git a/docs/assets/logo/logo-horizontal-dark.svg b/docs/assets/logo/logo-horizontal-dark.svg
index 57dcd95..072588c 100644
--- a/docs/assets/logo/logo-horizontal-dark.svg
+++ b/docs/assets/logo/logo-horizontal-dark.svg
@@ -1,4 +1,4 @@
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 120" width="100%" height="100%">
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 720 120" width="100%" height="100%">
<!-- Horizontal layout for Dark Mode environments -->
<g transform="translate(15, -55) scale(0.45)">
<polyline points="250,150 150,200 150,300 250,350" fill="none" stroke="#9A77E2" stroke-width="15" stroke-dasharray="16, 20" stroke-linecap="round" stroke-linejoin="round"/>
@@ -11,7 +11,7 @@
<circle cx="350" cy="200" r="10" fill="#FFFFFF"/>
<circle cx="350" cy="300" r="10" fill="#FFFFFF"/>
</g>
- <text x="180" y="75" font-family="system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" font-size="50" font-weight="900" fill="#FFFFFF" letter-spacing="4">
+ <text x="215" y="75" font-family="system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" font-size="50" font-weight="900" fill="#FFFFFF" letter-spacing="4">
HYPER<tspan fill="#A259FF">EXTRACT</tspan>
</text>
</svg>
\ No newline at end of file
diff --git a/docs/assets/logo/logo-horizontal.svg b/docs/assets/logo/logo-horizontal.svg
index 5a6a2e4..fce1907 100644
--- a/docs/assets/logo/logo-horizontal.svg
+++ b/docs/assets/logo/logo-horizontal.svg
@@ -1,4 +1,4 @@
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 120" width="100%" height="100%">
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 720 120" width="100%" height="100%">
<!-- Horizontal layout for light document backgrounds -->
<!-- Shrink icon and center vertically to left of text -->
<g transform="translate(15, -55) scale(0.45)">
@@ -12,7 +12,7 @@
<circle cx="350" cy="200" r="10" fill="#1C1032"/>
<circle cx="350" cy="300" r="10" fill="#1C1032"/>
</g>
- <text x="180" y="75" font-family="system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" font-size="50" font-weight="900" fill="#181A1F" letter-spacing="4">
+ <text x="215" y="75" font-family="system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" font-size="50" font-weight="900" fill="#181A1F" letter-spacing="4">
HYPER<tspan fill="#A259FF">EXTRACT</tspan>
</text>
</svg>
\ No newline at end of file
diff --git a/docs/assets/logo/logo-vertical-dark.svg b/docs/assets/logo/logo-vertical-dark.svg
index 11292e9..7d90856 100644
--- a/docs/assets/logo/logo-vertical-dark.svg
+++ b/docs/assets/logo/logo-vertical-dark.svg
@@ -1,6 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500" width="100%" height="100%">
<!-- Vertical Stack layout for Dark/Black backgrounds -->
- <g transform="translate(0, -20)">
+ <g transform="translate(0, -35)">
<polyline points="250,150 150,200 150,300 250,350" fill="none" stroke="#9A77E2" stroke-width="15" stroke-dasharray="16, 20" stroke-linecap="round" stroke-linejoin="round"/>
<polyline points="250,150 350,200 350,300 250,350" fill="none" stroke="#D1ABFF" stroke-width="17" stroke-linecap="round" stroke-linejoin="round"/>
<line x1="250" y1="250" x2="160" y2="198" stroke="#9A77E2" stroke-width="12" stroke-linecap="round" stroke-dasharray="16, 20"/>
@@ -12,7 +12,7 @@
<circle cx="350" cy="200" r="10" fill="#FFFFFF"/>
<circle cx="350" cy="300" r="10" fill="#FFFFFF"/>
</g>
- <text x="250" y="440" font-family="system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" font-size="42" font-weight="900" fill="#FFFFFF" text-anchor="middle" letter-spacing="8">
+ <text x="250" y="420" font-family="system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" font-size="42" font-weight="900" fill="#FFFFFF" text-anchor="middle" letter-spacing="8">
HYPER<tspan fill="#A259FF">EXTRACT</tspan>
</text>
</svg>
\ No newline at end of file
diff --git a/docs/assets/logo/logo-vertical.svg b/docs/assets/logo/logo-vertical.svg
index 637bb10..3198486 100644
--- a/docs/assets/logo/logo-vertical.svg
+++ b/docs/assets/logo/logo-vertical.svg
@@ -1,6 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500" width="100%" height="100%">
<!-- Vertical Stack layout for Light backgrounds -->
- <g transform="translate(0, -20)">
+ <g transform="translate(0, -35)">
<polyline points="250,150 150,200 150,300 250,350" fill="none" stroke="#7A52BD" stroke-width="15" stroke-dasharray="16, 20" stroke-linecap="round" stroke-linejoin="round"/>
<polyline points="250,150 350,200 350,300 250,350" fill="none" stroke="#B275FF" stroke-width="17" stroke-linecap="round" stroke-linejoin="round"/>
<line x1="250" y1="250" x2="160" y2="198" stroke="#7A52BD" stroke-width="12" stroke-linecap="round" stroke-dasharray="16, 20"/>
@@ -12,7 +12,7 @@
<circle cx="350" cy="200" r="10" fill="#1C1032"/>
<circle cx="350" cy="300" r="10" fill="#1C1032"/>
</g>
- <text x="250" y="440" font-family="system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" font-size="42" font-weight="900" fill="#181A1F" text-anchor="middle" letter-spacing="8">
+ <text x="250" y="420" font-family="system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" font-size="42" font-weight="900" fill="#181A1F" text-anchor="middle" letter-spacing="8">
HYPER<tspan fill="#A259FF">EXTRACT</tspan>
</text>
</svg>
\ No newline at end of file
diff --git a/docs/en/cli/index.md b/docs/en/cli/index.md
index 3ce68c2..ec6543f 100644
--- a/docs/en/cli/index.md
+++ b/docs/en/cli/index.md
@@ -6,9 +6,17 @@ The Hyper-Extract CLI (`he`) provides a powerful, easy-to-use interface for know
## Installation
-```bash
-pip install hyper-extract
-```
+=== "uv (recommended)"
+
+ ```bash
+ uv pip install hyper-extract
+ ```
+
+=== "pip"
+
+ ```bash
+ pip install hyper-extract
+ ```
Verify installation:
@@ -39,19 +47,31 @@ he --version
The typical workflow for extracting and interacting with knowledge:
```mermaid
-graph LR
- A[Document] -->|he parse| B[Knowledge Base]
- B -->|he show| C[Visualize]
- B -->|he search| D[Search]
- B -->|he talk| E[Chat]
- B -->|he feed| B[Update]
+flowchart TB
+ subgraph Create ["🚀 Create"]
+ D[📄 Document] -->|he parse| KB[(💡 Knowledge Base)]
+ end
+
+ subgraph Enhance ["✨ Enhance (Optional)"]
+ KB -->|he feed| KB
+ KB -->|he build-index| IDX[(🔍 Index)]
+ end
+
+ subgraph Explore ["🔍 Explore"]
+ KB -->|he show| VIS[👁️ Visualize]
+ IDX -->|he search| SRCH[🔎 Search]
+ IDX -->|he talk| CHAT[💬 Chat]
+ end
+
+ subgraph Save ["💾 Save"]
+ KB -->|he dump| DISK[💾 Disk]
+ end
```
-1. **Parse** — Extract knowledge from documents
-2. **Show** — Visualize the knowledge graph
-3. **Search** — Find specific information
-4. **Talk** — Have a conversation about the content
-5. **Feed** — Add more documents incrementally
+1. **Create** — Extract knowledge from documents (`he parse`)
+2. **Enhance** — Add documents incrementally (`he feed`), build index (`he build-index`)
+3. **Explore** — Visualize (`he show`), search (`he search`), chat (`he talk`)
+4. **Save** — Persist to disk (`he dump`)
→ [Detailed Workflow Walkthrough](workflow.md)
diff --git a/docs/en/concepts/autotypes.md b/docs/en/concepts/autotypes.md
index c5b93f0..796c590 100644
--- a/docs/en/concepts/autotypes.md
+++ b/docs/en/concepts/autotypes.md
@@ -330,14 +330,16 @@ result = ka.parse(text)
# Incremental update
result.feed_text(more_text)
-# Search (requires index)
+# Build index (required for search, chat, and interactive visualization)
result.build_index()
+
+# Search
results = result.search("query")
-# Chat (requires index)
+# Chat
response = result.chat("question")
-# Visualization
+# Visualization (interactive with search/chat capabilities)
result.show()
# Persistence
diff --git a/docs/en/getting-started/cli-quickstart.md b/docs/en/getting-started/cli-quickstart.md
index f6fee7f..c7b542d 100644
--- a/docs/en/getting-started/cli-quickstart.md
+++ b/docs/en/getting-started/cli-quickstart.md
@@ -7,12 +7,23 @@ Get your first knowledge extraction running in 5 minutes using the terminal.
## Prerequisites
- [Hyper-Extract installed](installation.md)
-- API key configured (via `he config init` or environment variable)
- A text file to extract from (we'll use an example)
---
-## Step 1: Download Sample Document
+## Step 1: Configure API Key
+
+Run the following command to configure your API key:
+
+```bash
+he config init -k YOUR_OPENAI_API_KEY
+```
+
+This creates a configuration file at `~/.he/config.toml`. You only need to do this once.
+
+---
+
+## Step 2: Download Sample Document
```bash
# Download a sample biography
@@ -30,12 +41,24 @@ contributions to the design of the modern alternating current
Born: July 10, 1856, Smiljan, Croatia
Died: January 7, 1943, New York City, NY
+
+Tesla immigrated to the United States in 1884 and briefly worked
+with Thomas Edison before the two parted ways due to conflicting
+business and scientific interests. He later established his own
+laboratory and developed numerous revolutionary inventions,
+including the Tesla coil, induction motor, and wireless transmission
+technologies.
+
+Despite his brilliance, Tesla struggled financially in his later years
+and died impoverished in a New York hotel room. His legacy was
+largely overlooked during his lifetime but has since been recognized
+worldwide, with the Tesla unit of magnetic flux density named in his honor.
EOF
```
---
-## Step 2: Extract Knowledge
+## Step 3: Extract Knowledge
Run the `parse` command to extract knowledge:
@@ -67,7 +90,7 @@ What's next?
---
-## Step 3: Visualize the Knowledge Graph
+## Step 4: Visualize the Knowledge Graph
```bash
he show ./output/
@@ -77,9 +100,11 @@ This opens an interactive visualization in your browser, showing:
- **Entities** (people, places, events) as nodes
- **Relationships** as edges connecting the nodes
+![Knowledge Graph Visualization](../../assets/en_show.png)
+
---
-## Step 4: Search Your Knowledge Base
+## Step 5: Search Your Knowledge Base
```bash
he search ./output/ "What were Tesla's major inventions?"
@@ -100,7 +125,7 @@ Result 1:
---
-## Step 5: Chat with Your Knowledge
+## Step 6: Chat with Your Knowledge
Interactive mode:
@@ -116,7 +141,7 @@ he talk ./output/ -q "Summarize Tesla's career in three sentences"
---
-## Step 6: Incrementally Add Knowledge
+## Step 7: Incrementally Add Knowledge
Got more documents? Add them without reprocessing:
diff --git a/docs/en/getting-started/index.md b/docs/en/getting-started/index.md
index c871a51..ebd90d9 100644
--- a/docs/en/getting-started/index.md
+++ b/docs/en/getting-started/index.md
@@ -18,7 +18,7 @@ Welcome to Hyper-Extract! This guide will help you get up and running quickly, w
- Need to batch process files
- Prefer terminal workflows
- **Start here:** [:octicons-arrow-right-24: Installation](installation.md) → [:octicons-arrow-right-24: CLI Quickstart](cli-quickstart.md)
+ **Start here:** [Installation](installation.md) [:octicons-arrow-right-24: CLI Quickstart](cli-quickstart.md)
- :material-language-python:{ .lg .middle } __I want to use Python__
@@ -30,7 +30,7 @@ Welcome to Hyper-Extract! This guide will help you get up and running quickly, w
- Need to integrate with existing code
- Want full programmatic control
- **Start here:** [:octicons-arrow-right-24: Installation](installation.md) → [:octicons-arrow-right-24: Python Quickstart](python-quickstart.md)
+ **Start here:** [Installation](installation.md) [:octicons-arrow-right-24: Python Quickstart](python-quickstart.md)
</div>
diff --git a/docs/en/getting-started/installation.md b/docs/en/getting-started/installation.md
index ade68f3..e653db0 100644
--- a/docs/en/getting-started/installation.md
+++ b/docs/en/getting-started/installation.md
@@ -6,16 +6,16 @@ Hyper-Extract requires **Python 3.11+**.
## Install from PyPI
-=== "pip"
+=== "uv (recommended)"
```bash
- pip install hyper-extract
+ uv pip install hyper-extract
```
-=== "uv (recommended)"
+=== "pip"
```bash
- uv pip install hyper-extract
+ pip install hyper-extract
```
=== "conda"
@@ -40,65 +40,6 @@ Hyper-Extract CLI version 0.1.0
---
-## Optional Dependencies
-
-=== "Anthropic Claude Support"
-
- ```bash
- pip install hyper-extract[anthropic]
- ```
-
-=== "Google Gemini Support"
-
- ```bash
- pip install hyper-extract[google]
- ```
-
-=== "All Optional Dependencies"
-
- ```bash
- pip install hyper-extract[all]
- ```
-
----
-
-## Configuration
-
-Before using Hyper-Extract, you need to configure your LLM API credentials.
-
-### Option 1: Using CLI (Recommended)
-
-```bash
-he config init -k YOUR_OPENAI_API_KEY
-```
-
-This creates a configuration file at `~/.he/config.toml`.
-
-### Option 2: Using Environment Variables
-
-```bash
-export OPENAI_API_KEY=your-api-key
-export OPENAI_BASE_URL=https://api.openai.com/v1 # Optional
-```
-
-### Option 3: Using .env File (Python Only)
-
-Create a `.env` file in your project root:
-
-```
-OPENAI_API_KEY=your-api-key
-OPENAI_BASE_URL=https://api.openai.com/v1
-```
-
-Then load it in your Python code:
-
-```python
-from dotenv import load_dotenv
-load_dotenv()
-```
-
----
-
## Development Installation
If you want to contribute or modify the source code:
diff --git a/docs/en/getting-started/python-quickstart.md b/docs/en/getting-started/python-quickstart.md
index d9b1fc2..0da4a1b 100644
--- a/docs/en/getting-started/python-quickstart.md
+++ b/docs/en/getting-started/python-quickstart.md
@@ -7,7 +7,6 @@ Get your first knowledge extraction running in 5 minutes using Python.
## Prerequisites
- [Hyper-Extract installed](installation.md)
-- API key configured (via `.env` file or environment variable)
---
@@ -37,13 +36,6 @@ Create a `.env` file:
echo "OPENAI_API_KEY=your-api-key" > .env
```
-Or set it in your code:
-
-```python
-import os
-os.environ["OPENAI_API_KEY"] = "your-api-key"
-```
-
---
## Step 3: Create Your First Extraction Script
@@ -70,20 +62,35 @@ contributions to the design of the modern alternating current
Born: July 10, 1856, Smiljan, Croatia
Died: January 7, 1943, New York City, NY
+
+Tesla immigrated to the United States in 1884 and briefly worked
+with Thomas Edison before the two parted ways due to conflicting
+business and scientific interests. He later established his own
+laboratory and developed numerous revolutionary inventions,
+including the Tesla coil, induction motor, and wireless transmission
+technologies.
+
+Despite his brilliance, Tesla struggled financially in his later years
+and died impoverished in a New York hotel room. His legacy was
+largely overlooked during his lifetime but has since been recognized
+worldwide, with the Tesla unit of magnetic flux density named in his honor.
"""
# Extract knowledge
result = ka.parse(text)
# Access the extracted data
-print(f"Nodes: {len(result.data.nodes)}")
-print(f"Edges: {len(result.data.edges)}")
+print(f"Nodes: {len(result.nodes)}")
+print(f"Edges: {len(result.edges)}")
# Print first node
-if result.data.nodes:
- node = result.data.nodes[0]
+if result.nodes:
+ node = result.nodes[0]
print(f"\nFirst node: {node.name} ({node.type})")
+# Build index for search/chat capabilities
+result.build_index()
+
# Visualize
result.show()
```
@@ -107,6 +114,8 @@ First entity: Nikola Tesla (person)
And a browser window will open showing the interactive knowledge graph.
+![Knowledge Graph Visualization](../../assets/en_show.png)
+
---
## Step 5: Working with Results
@@ -115,11 +124,11 @@ Access different parts of the extraction:
```python
# Iterate over all nodes
-for node in result.data.nodes:
+for node in result.nodes:
print(f"- {node.name}: {node.description}")
# Iterate over all edges
-for edge in result.data.edges:
+for edge in result.edges:
print(f"- {edge.source} --{edge.type}--> {edge.target}")
# Search within the knowledge base
@@ -161,6 +170,9 @@ They had a contentious relationship due to differing views on DC vs AC power.
# Feed adds to existing knowledge
result.feed_text(additional_text)
+# Rebuild index after feeding new data
+result.build_index()
+
# Visualize the updated graph
result.show()
```
@@ -203,8 +215,8 @@ def main():
# Print summary
print(f"\nExtraction complete:")
- print(f" - Nodes: {len(result.data.nodes)}")
- print(f" - Edges: {len(result.data.edges)}")
+ print(f" - Nodes: {len(result.nodes)}")
+ print(f" - Edges: {len(result.edges)}")
# Build search index
print("Building search index...")
diff --git a/docs/en/index.md b/docs/en/index.md
index 6cf5fe6..450dfee 100644
--- a/docs/en/index.md
+++ b/docs/en/index.md
@@ -1,9 +1,5 @@
<div align="center">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="../assets/logo/logo-horizontal-dark.svg">
- <source media="(prefers-color-scheme: light)" srcset="../assets/logo/logo-horizontal.svg">
- <img alt="Hyper-Extract Logo" src="../assets/logo/logo-horizontal.svg" width="500">
- </picture>
+ <img alt="Hyper-Extract Logo" src="../assets/logo/logo-horizontal.svg" width="500">
</div>
<br/>
@@ -153,20 +149,24 @@ Hyper-Extract follows a **three-layer architecture**:
```mermaid
graph TD
- A[Your Document] --> B[Template / Method]
- B --> C[Auto-Type]
- C --> D[Structured Knowledge]
-
- subgraph "Layer 3: Templates"
- B
+ A[Your Document] --> B[CLI / Python API]
+ B --> C[Template]
+ B --> D[Method]
+ C --> E[Auto-Type]
+ D --> E
+ E --> F[Structured Knowledge]
+
+ subgraph "Layer 3: Templates & Methods"
+ C
+ D
end
-
- subgraph "Layer 2: Methods"
- B
+
+ subgraph "Layer 2: Core Engine"
+ E
end
-
- subgraph "Layer 1: Auto-Types"
- C
+
+ subgraph "Layer 1: Output"
+ F
end
```
diff --git a/docs/en/python/core-concepts.md b/docs/en/python/core-concepts.md
index 100f4a9..7b2acaa 100644
--- a/docs/en/python/core-concepts.md
+++ b/docs/en/python/core-concepts.md
@@ -89,10 +89,10 @@ ka = Template.create("general/knowledge_graph", "en")
result = ka.parse(text)
# Access graph data
-for node in result.data.nodes:
+for node in result.nodes:
print(f"Node: {node.name}")
-for edge in result.data.edges:
+for edge in result.edges:
print(f"{edge.source} --{edge.type}--> {edge.target}")
```
@@ -220,7 +220,10 @@ ka = Template.create("general/biography_graph", "en")
# 2. Extract
result = ka.parse(text)
-# 3. Use
+# 3. Build index for search/chat capabilities
+result.build_index()
+
+# 4. Use
result.show()
```
diff --git a/docs/en/python/guides/custom-templates.md b/docs/en/python/guides/custom-templates.md
new file mode 100644
index 0000000..404747b
--- /dev/null
+++ b/docs/en/python/guides/custom-templates.md
@@ -0,0 +1,349 @@
+# Creating Custom Templates
+
+Learn how to create your own templates for specialized extraction tasks.
+
+---
+
+## Overview
+
+Custom templates allow you to define:
+
+- **Output schema** — What entities and relationships to extract
+- **Extraction rules** — Guidelines for the LLM
+- **Display configuration** — How to visualize results
+
+---
+
+## Quick Start
+
+### 1. Create Template File
+
+Create a YAML file in `~/.hyperextract/templates/`:
+
+```bash
+mkdir -p ~/.hyperextract/templates/my_domain
+```
+
+### 2. Define Template Structure
+
+```yaml
+language: [zh, en]
+
+name: my_template
+type: graph
+tags: [custom, domain]
+
+description:
+ zh: "自定义模板描述"
+ en: "Custom template description"
+
+output:
+ description:
+ zh: "输出描述"
+ en: "Output description"
+ entities:
+ description:
+ zh: "实体描述"
+ en: "Entity description"
+ fields:
+ - name: name
+ type: str
+ description:
+ zh: "名称"
+ en: "Name"
+ required: true
+ - name: category
+ type: str
+ description:
+ zh: "类别"
+ en: "Category"
+ required: true
+
+ relations:
+ description:
+ zh: "关系描述"
+ en: "Relation description"
+ fields:
+ - name: type
+ type: str
+ description:
+ zh: "关系类型"
+ en: "Relation type"
+ required: true
+
+guideline:
+ target:
+ zh: "提取目标描述"
+ en: "Extraction target description"
+ rules_for_entities:
+ zh:
+ - "规则1"
+ - "规则2"
+ en:
+ - "Rule 1"
+ - "Rule 2"
+ rules_for_relations:
+ zh:
+ - "关系规则1"
+ en:
+ - "Relation rule 1"
+
+identifiers:
+ entity_id: name
+ relation_id: "{source}|{type}|{target}"
+ relation_members:
+ source: source
+ target: target
+
+display:
+ entity_label: "{name} ({category})"
+ relation_label: "{type}"
+```
+
+### 3. Validate and Use
+
+```python
+from hyperextract import Template
+
+# Load your custom template
+ka = Template.create("my_domain/my_template", "en")
+
+# Use it
+result = ka.parse("Your document text here")
+```
+
+---
+
+## Field Types
+
+| Type | Description | Example |
+|------|-------------|---------|
+| `str` | String value | `"Hello"` |
+| `int` | Integer | `42` |
+| `float` | Floating point | `3.14` |
+| `bool` | Boolean | `true` |
+| `list[str]` | List of strings | `["a", "b"]` |
+| `datetime` | Date/time | `"2024-01-01"` |
+| `enum` | Enumerated values | See below |
+
+### Enum Type
+
+For fields with predefined values:
+
+```yaml
+- name: priority
+ type: str
+ description:
+ zh: "优先级: high/medium/low"
+ en: "Priority: high/medium/low"
+ required: true
+```
+
+---
+
+## Auto-Types
+
+Choose the appropriate Auto-Type for your data:
+
+| Type | Use Case | Features |
+|------|----------|----------|
+| `graph` | General knowledge graphs | Entities + Relations |
+| `temporal_graph` | Time-series data | + Temporal events |
+| `spatial_graph` | Geospatial data | + Location coordinates |
+| `hypergraph` | Complex relationships | + Hyperedges |
+| `tree` | Hierarchical data | Parent-child structure |
+| `table` | Structured records | Row-based data |
+
+---
+
+## Best Practices
+
+### 1. Clear Descriptions
+
+Write detailed descriptions to guide the LLM:
+
+```yaml
+# Good
+description:
+ en: "Extract product information including name, price, and category"
+
+# Bad
+description:
+ en: "Product info"
+```
+
+### 2. Specific Rules
+
+Provide concrete extraction rules:
+
+```yaml
+guideline:
+ rules_for_entities:
+ en:
+ - "Only extract products mentioned in the pricing section"
+ - "Category must be one of: electronics, clothing, food, other"
+ - "Round prices to 2 decimal places"
+```
+
+### 3. Required Fields
+
+Mark critical fields as required:
+
+```yaml
+fields:
+ - name: id
+ type: str
+ required: true # Extraction will fail if missing
+ - name: notes
+ type: str
+ required: false # Optional field
+```
+
+### 4. Validation
+
+Test your template with sample documents:
+
+```python
+# Test extraction
+test_doc = """
+Sample document text for testing...
+"""
+
+result = ka.parse(test_doc)
+print(result.data.entities)
+print(result.data.relations)
+```
+
+---
+
+## Example: Product Catalog Template
+
+```yaml
+language: [zh, en]
+
+name: product_catalog
+type: table
+tags: [ecommerce, products]
+
+description:
+ zh: "从商品目录中提取产品信息"
+ en: "Extract product information from catalogs"
+
+output:
+ description:
+ zh: "产品信息表"
+ en: "Product information table"
+ entities:
+ description:
+ zh: "产品实体"
+ en: "Product entities"
+ fields:
+ - name: sku
+ type: str
+ description:
+ zh: "产品SKU(唯一标识)"
+ en: "Product SKU (unique identifier)"
+ required: true
+ - name: name
+ type: str
+ description:
+ zh: "产品名称"
+ en: "Product name"
+ required: true
+ - name: price
+ type: float
+ description:
+ zh: "价格(数字)"
+ en: "Price (numeric value)"
+ required: true
+ - name: category
+ type: str
+ description:
+ zh: "类别:electronics/clothing/food/home/other"
+ en: "Category: electronics/clothing/food/home/other"
+ required: true
+ - name: in_stock
+ type: bool
+ description:
+ zh: "是否有库存"
+ en: "Whether in stock"
+ required: false
+
+guideline:
+ target:
+ zh: "提取所有产品信息,忽略缺货商品"
+ en: "Extract all product info, skip out-of-stock items"
+ rules_for_entities:
+ en:
+ - "Extract products from tables and bullet lists"
+ - "Convert price strings to numeric values"
+ - "Map category names to standard values"
+ - "Set in_stock=false if explicitly mentioned as out of stock"
+
+identifiers:
+ entity_id: sku
+
+display:
+ entity_label: "{name} (${price})"
+```
+
+---
+
+## Sharing Templates
+
+### Register Globally
+
+Place templates in the system directory:
+
+```bash
+# System-wide (all users)
+/usr/share/hyperextract/templates/
+
+# User-specific
+~/.hyperextract/templates/
+```
+
+### Template Registry
+
+To share with the community:
+
+1. Fork the [Hyper-Extract repository](https://github.com/yifanfeng97/hyper-extract)
+2. Add your template to `hyperextract/templates/`
+3. Submit a pull request
+
+---
+
+## Troubleshooting
+
+### Template Not Found
+
+```python
+# Check template path
+Template.list_available() # List all templates
+
+# Verify directory
+import os
+print(os.listdir("~/.hyperextract/templates/"))
+```
+
+### Poor Extraction Quality
+
+1. **Add more examples** in guidelines
+2. **Refine field descriptions** with specific constraints
+3. **Split complex templates** into smaller ones
+4. **Use stricter rules** to constrain output
+
+### Validation Errors
+
+```bash
+# Validate YAML syntax
+python -c "import yaml; yaml.safe_load(open('template.yaml'))"
+```
+
+---
+
+## See Also
+
+- [Template Format Reference](../../concepts/templates-format.md) — Complete YAML specification
+- [Using Templates](using-templates.md) — How to use templates in code
+- [Template Library](../../templates/index.md) — Browse existing templates
diff --git a/docs/en/python/guides/incremental-updates.md b/docs/en/python/guides/incremental-updates.md
index 89a3187..38942e9 100644
--- a/docs/en/python/guides/incremental-updates.md
+++ b/docs/en/python/guides/incremental-updates.md
@@ -23,11 +23,11 @@ ka = Template.create("general/biography_graph", "en")
# Initial extraction
result = ka.parse(initial_text)
-print(f"Initial: {len(result.data.nodes)} nodes")
+print(f"Initial: {len(result.nodes)} nodes")
# Add more content
result.feed_text(additional_text)
-print(f"After feed: {len(result.data.nodes)} nodes")
+print(f"After feed: {len(result.nodes)} nodes")
```
---
@@ -46,7 +46,10 @@ kb.feed_text(career_text)
# Add later years
kb.feed_text(later_years_text)
-# Final result combines all periods
+# Rebuild index after feeding new data
+kb.build_index()
+
+# Final result combines all periods (with interactive search/chat)
kb.show()
```
@@ -58,7 +61,7 @@ kb = ka.parse(documents[0])
for doc in documents[1:]:
kb.feed_text(doc)
- print(f"Added document, now {len(kb.data.nodes)} nodes")
+ print(f"Added document, now {len(kb.nodes)} nodes")
```
### Updating with New Information
@@ -136,9 +139,9 @@ kb.dump("./kb_v2/")
### 4. Monitor Growth
```python
-initial_count = len(kb.data.nodes)
+initial_count = len(kb.nodes)
kb.feed_text(new_text)
-new_count = len(kb.data.nodes)
+new_count = len(kb.nodes)
print(f"Added {new_count - initial_count} new nodes")
```
@@ -171,7 +174,7 @@ def build_knowledge_base(source_dir, output_dir):
for file in files[1:]:
print(f"Adding {file.name}...")
kb.feed_text(file.read_text())
- print(f" Now {len(kb.data.nodes)} nodes")
+ print(f" Now {len(kb.nodes)} nodes")
# Build index for search/chat
print("Building search index...")
diff --git a/docs/en/python/guides/saving-loading.md b/docs/en/python/guides/saving-loading.md
index 012f5db..19800a3 100644
--- a/docs/en/python/guides/saving-loading.md
+++ b/docs/en/python/guides/saving-loading.md
@@ -64,7 +64,7 @@ ka = Template.create("general/biography_graph", "en")
ka.load("./my_kb/")
# Use
-print(f"Loaded {len(ka.data.nodes)} nodes")
+print(f"Loaded {len(ka.nodes)} nodes")
```
### Verify Loaded Data
@@ -76,8 +76,8 @@ ka.load("./my_kb/")
if ka.empty():
print("Warning: No data loaded")
else:
- print(f"Nodes: {len(ka.data.nodes)}")
- print(f"Edges: {len(ka.data.edges)}")
+ print(f"Nodes: {len(ka.nodes)}")
+ print(f"Edges: {len(ka.edges)}")
```
---
diff --git a/docs/en/python/guides/using-templates.md b/docs/en/python/guides/using-templates.md
index 2d95017..5384eb2 100644
--- a/docs/en/python/guides/using-templates.md
+++ b/docs/en/python/guides/using-templates.md
@@ -156,11 +156,14 @@ with open("biography.md") as f:
result = ka.parse(f.read())
# Access timeline data
-for edge in result.data.edges:
+for edge in result.edges:
if hasattr(edge, 'time'):
print(f"{edge.time}: {edge.source} -> {edge.target}")
-result.show() # Visualize life timeline
+# Build index for interactive visualization
+result.build_index()
+
+result.show() # Visualize life timeline with search/chat
```
### Pattern 2: Financial Report
diff --git a/docs/en/python/guides/working-with-autotypes.md b/docs/en/python/guides/working-with-autotypes.md
index 1bf0f1c..683f2a9 100644
--- a/docs/en/python/guides/working-with-autotypes.md
+++ b/docs/en/python/guides/working-with-autotypes.md
@@ -81,12 +81,12 @@ ka = Template.create("general/knowledge_graph", "en")
result = ka.parse(text)
# Access nodes
-for node in result.data.nodes:
+for node in result.nodes:
print(f"{node.name} ({node.type})")
print(f" Description: {node.description}")
# Access edges
-for edge in result.data.edges:
+for edge in result.edges:
print(f"{edge.source} --{edge.type}--> {edge.target}")
```
@@ -101,7 +101,7 @@ ka = Template.create("general/base_hypergraph", "en")
result = ka.parse(text)
# Hyperedges connect multiple entities
-for edge in result.data.edges:
+for edge in result.edges:
print(f"Type: {edge.type}")
print(f"Entities: {edge.entities}")
```
@@ -117,7 +117,7 @@ ka = Template.create("general/base_temporal_graph", "en")
result = ka.parse(text)
# Relations include time information
-for edge in result.data.edges:
+for edge in result.edges:
print(f"{edge.source} --{edge.type}--> {edge.target}")
if hasattr(edge, 'time'):
print(f" Time: {edge.time}")
@@ -134,7 +134,7 @@ ka = Template.create("general/base_spatial_graph", "en")
result = ka.parse(text)
# Nodes/edges include location
-for node in result.data.nodes:
+for node in result.nodes:
if hasattr(node, 'location'):
print(f"{node.name} at {node.location}")
```
@@ -150,7 +150,7 @@ ka = Template.create("general/base_spatio_temporal_graph", "en")
result = ka.parse(text)
# Full context: who, what, when, where
-for edge in result.data.edges:
+for edge in result.edges:
print(f"Event: {edge.type}")
if hasattr(edge, 'time'):
print(f" When: {edge.time}")
@@ -168,7 +168,7 @@ for edge in result.data.edges:
if result.empty():
print("No data extracted")
else:
- print(f"Extracted {len(result.data.nodes)} nodes")
+ print(f"Extracted {len(result.nodes)} nodes")
```
### Clearing Data
@@ -202,8 +202,8 @@ combined = result1 + result2
result = ka.parse(text)
# Direct property access (Pydantic model)
-nodes = result.data.nodes
-edges = result.data.edges
+nodes = result.nodes
+edges = result.edges
# Dictionary conversion
data_dict = result.data.model_dump()
@@ -230,14 +230,14 @@ with open("output.json", "w") as f:
```python
# Iterate nodes
-for node in result.data.nodes:
+for node in result.nodes:
print(f"Name: {node.name}")
print(f"Type: {node.type}")
if hasattr(node, 'description'):
print(f"Description: {node.description}")
# Iterate edges with filtering
-for edge in result.data.edges:
+for edge in result.edges:
if edge.type == "worked_with":
print(f"{edge.source} worked with {edge.target}")
```
@@ -246,24 +246,24 @@ for edge in result.data.edges:
```python
# Filter nodes by type
-people = [n for n in result.data.nodes if n.type == "person"]
-organizations = [n for n in result.data.nodes if n.type == "organization"]
+people = [n for n in result.nodes if n.type == "person"]
+organizations = [n for n in result.nodes if n.type == "organization"]
# Filter edges
-inventions = [e for e in result.data.edges if "invent" in e.type.lower()]
+inventions = [e for e in result.edges if "invent" in e.type.lower()]
```
### Statistics
```python
# Basic counts
-node_count = len(result.data.nodes)
-edge_count = len(result.data.edges)
+node_count = len(result.nodes)
+edge_count = len(result.edges)
# Type distribution
from collections import Counter
-node_types = Counter(n.type for n in result.data.nodes)
-edge_types = Counter(e.type for e in result.data.edges)
+node_types = Counter(n.type for n in result.nodes)
+edge_types = Counter(e.type for e in result.edges)
print(f"Nodes: {node_types}")
print(f"Edges: {edge_types}")
diff --git a/docs/en/python/index.md b/docs/en/python/index.md
index 87c3064..d33b029 100644
--- a/docs/en/python/index.md
+++ b/docs/en/python/index.md
@@ -31,8 +31,11 @@ with open("document.md") as f:
result = ka.parse(f.read())
# Access data
-print(f"Nodes: {len(result.data.nodes)}")
-print(f"Edges: {len(result.data.edges)}")
+print(f"Nodes: {len(result.nodes)}")
+print(f"Edges: {len(result.edges)}")
+
+# Build index for search/chat capabilities
+result.build_index()
# Visualize
result.show()
@@ -221,8 +224,8 @@ ka: AutoGraph = Template.create("general/knowledge_graph", "en")
result = ka.parse(text)
# IDE autocomplete works
-nodes = result.data.nodes
-edges = result.data.edges
+nodes = result.nodes
+edges = result.edges
```
---
diff --git a/docs/en/python/quickstart.md b/docs/en/python/quickstart.md
index 4e8898d..de13239 100644
--- a/docs/en/python/quickstart.md
+++ b/docs/en/python/quickstart.md
@@ -51,12 +51,12 @@ scientific fields.
result = ka.parse(text)
# Access results
-print(f"Nodes: {len(result.data.nodes)}")
-print(f"Edges: {len(result.data.edges)}")
+print(f"Nodes: {len(result.nodes)}")
+print(f"Edges: {len(result.edges)}")
# Print first node
-if result.data.nodes:
- node = result.data.nodes[0]
+if result.nodes:
+ node = result.nodes[0]
print(f"\nFirst: {node.name} ({node.type})")
print(f"Description: {node.description}")
```
@@ -73,6 +73,9 @@ Description: Polish-French physicist and chemist
### 3. Visualize
```python
+# Build index for search/chat capabilities
+result.build_index()
+
# Open interactive visualization
result.show()
```
@@ -139,12 +142,12 @@ def main():
# Display results
print(f"\nExtraction Results:")
- print(f" Nodes: {len(result.data.nodes)}")
- print(f" Edges: {len(result.data.edges)}")
+ print(f" Nodes: {len(result.nodes)}")
+ print(f" Edges: {len(result.edges)}")
# List nodes
print("\nNodes found:")
- for node in result.data.nodes:
+ for node in result.nodes:
print(f" - {node.name} ({node.type})")
# Build index and search
diff --git a/docs/en/resources/contributing.md b/docs/en/resources/contributing.md
index 5c9ac97..b311723 100644
--- a/docs/en/resources/contributing.md
+++ b/docs/en/resources/contributing.md
@@ -130,7 +130,7 @@ ka = Template.create("domain/my_template", "en")
result = ka.parse(test_text)
# Verify output
-assert len(result.data.nodes) > 0
+assert len(result.nodes) > 0
```
### Submitting Templates
diff --git a/docs/en/resources/faq.md b/docs/en/resources/faq.md
index 35eb182..911652b 100644
--- a/docs/en/resources/faq.md
+++ b/docs/en/resources/faq.md
@@ -170,6 +170,9 @@ he show ./output/
Or in Python:
```python
+# Build index for interactive search/chat in visualization
+result.build_index()
+
result.show()
```
diff --git a/docs/en/templates/finance.md b/docs/en/templates/finance.md
index 52c2e6a..80526e3 100644
--- a/docs/en/templates/finance.md
+++ b/docs/en/templates/finance.md
@@ -77,7 +77,10 @@ he parse proxy.md -t finance/ownership_graph -l en
**Visualization:**
```python
-result.show() # Shows ownership network
+# Build index for interactive search/chat in visualization
+result.build_index()
+
+result.show() # Shows ownership network with interactive features
```
---
diff --git a/docs/en/templates/general/index.md b/docs/en/templates/general/index.md
index 773f0d9..6a0929b 100644
--- a/docs/en/templates/general/index.md
+++ b/docs/en/templates/general/index.md
@@ -246,11 +246,13 @@ print(result.data)
ka = Template.create("general/biography_graph", "en")
result = ka.parse(biography_text)
-# Visualize life events
+# Build index for interactive features
+result.build_index()
+
+# Visualize life events (with search/chat capabilities)
result.show()
# Ask questions
-result.build_index()
response = result.chat("What were the major achievements?")
print(response.content)
```
@@ -262,10 +264,10 @@ ka = Template.create("general/concept_graph", "en")
result = ka.parse(paper_text)
# Get concept map
-for node in result.data.nodes:
+for node in result.nodes:
print(f"Concept: {node.name}")
-for edge in result.data.edges:
+for edge in result.edges:
print(f"{edge.source} → {edge.target}")
```
diff --git a/docs/en/templates/industry.md b/docs/en/templates/industry.md
index 1db7209..263ae44 100644
--- a/docs/en/templates/industry.md
+++ b/docs/en/templates/industry.md
@@ -41,7 +41,10 @@ he parse system_diagram.md -t industry/equipment_topology -l en
**Visualization:**
```python
-result.show() # Shows equipment network
+# Build index for interactive search/chat in visualization
+result.build_index()
+
+result.show() # Shows equipment network with interactive features
```
---
@@ -202,11 +205,13 @@ for hazard in hazards:
ka = Template.create("industry/operation_flow", "en")
procedure = ka.parse(sop_document)
-# Visualize workflow
+# Build index for interactive visualization
+procedure.build_index()
+
+# Visualize workflow with search/chat capabilities
procedure.show()
# Search for specific steps
-procedure.build_index()
results = procedure.search("startup sequence")
```
diff --git a/docs/en/templates/medicine.md b/docs/en/templates/medicine.md
index 6d2990b..aa0ebcb 100644
--- a/docs/en/templates/medicine.md
+++ b/docs/en/templates/medicine.md
@@ -191,11 +191,13 @@ for i in interactions:
ka = Template.create("medicine/anatomy_graph", "en")
anatomy = ka.parse(textbook_chapter)
-# Visualize
+# Build index for interactive visualization
+anatomy.build_index()
+
+# Visualize with search/chat capabilities
anatomy.show()
# Search
-anatomy.build_index()
results = anatomy.search("nerves in hand")
```
diff --git a/docs/en/tutorials/knowledge-base/step1-setup.md b/docs/en/tutorials/knowledge-base/step1-setup.md
index 35c58ae..0d13ffc 100644
--- a/docs/en/tutorials/knowledge-base/step1-setup.md
+++ b/docs/en/tutorials/knowledge-base/step1-setup.md
@@ -214,8 +214,8 @@ test_text = "This is a test document for template validation."
result = ka.parse(test_text)
print(f"Template: {config['template']}")
-print(f"Nodes: {len(result.data.nodes)}")
-print(f"Edges: {len(result.data.edges)}")
+print(f"Nodes: {len(result.nodes)}")
+print(f"Edges: {len(result.edges)}")
```
---
diff --git a/docs/en/tutorials/knowledge-base/step2-ingest.md b/docs/en/tutorials/knowledge-base/step2-ingest.md
index 304af83..cb204b9 100644
--- a/docs/en/tutorials/knowledge-base/step2-ingest.md
+++ b/docs/en/tutorials/knowledge-base/step2-ingest.md
@@ -162,16 +162,16 @@ def main():
# Print stats
print("\nKnowledge Base Stats:")
- print(f" Nodes: {len(kb.data.nodes)}")
- print(f" Edges: {len(kb.data.edges)}")
+ print(f" Nodes: {len(kb.nodes)}")
+ print(f" Edges: {len(kb.edges)}")
elif args.add:
# Add specific documents
kb = manager.add_documents(args.add)
print("\nKnowledge Base Stats:")
- print(f" Nodes: {len(kb.data.nodes)}")
- print(f" Edges: {len(kb.data.edges)}")
+ print(f" Nodes: {len(kb.nodes)}")
+ print(f" Edges: {len(kb.edges)}")
if __name__ == "__main__":
main()
diff --git a/docs/en/tutorials/knowledge-base/step3-query.md b/docs/en/tutorials/knowledge-base/step3-query.md
index 84b4b96..d81f4c9 100644
--- a/docs/en/tutorials/knowledge-base/step3-query.md
+++ b/docs/en/tutorials/knowledge-base/step3-query.md
@@ -124,13 +124,13 @@ Commands:
return
print("\nKnowledge Base Statistics:")
- print(f" Nodes: {len(self.kb.data.nodes)}")
- print(f" Edges: {len(self.kb.data.edges)}")
+ print(f" Nodes: {len(self.kb.nodes)}")
+ print(f" Edges: {len(self.kb.edges)}")
print(f" Template: {self.manager.config.template}")
# Node types
from collections import Counter
- types = Counter(n.type for n in self.kb.data.nodes)
+ types = Counter(n.type for n in self.kb.nodes)
print("\nNode Types:")
for t, count in types.most_common():
print(f" {t}: {count}")
diff --git a/docs/en/tutorials/research-assistant/step1-extract.md b/docs/en/tutorials/research-assistant/step1-extract.md
index 2ffc12a..bc410e1 100644
--- a/docs/en/tutorials/research-assistant/step1-extract.md
+++ b/docs/en/tutorials/research-assistant/step1-extract.md
@@ -102,12 +102,12 @@ def main():
# Display results
print(f"\nExtraction Complete:")
- print(f" Nodes: {len(result.data.nodes)}")
- print(f" Edges: {len(result.data.edges)}")
+ print(f" Nodes: {len(result.nodes)}")
+ print(f" Edges: {len(result.edges)}")
# Show sample nodes
print("\nSample Concepts:")
- for node in result.data.nodes[:5]:
+ for node in result.nodes[:5]:
print(f" - {node.name} ({node.type})")
# Save
diff --git a/docs/zh/cli/commands/feed.md b/docs/zh/cli/commands/feed.md
index 3dc53a4..7521b92 100644
--- a/docs/zh/cli/commands/feed.md
+++ b/docs/zh/cli/commands/feed.md
@@ -48,10 +48,10 @@ he feed KA_PATH INPUT [OPTIONS]
```bash
# 初始提取
-he parse tesla_bio.md -t general/biography_graph -o ./tesla_kb/ -l en
+he parse sushi.md -t general/biography_graph -o ./sushi_kb/ -l zh
# 添加更多内容
-he feed ./tesla_kb/ tesla_inventions.md
+he feed ./sushi_kb/ more_sushi.md
```
### 喂养多个文档
diff --git a/docs/zh/cli/commands/info.md b/docs/zh/cli/commands/info.md
index cec265d..5fb808e 100644
--- a/docs/zh/cli/commands/info.md
+++ b/docs/zh/cli/commands/info.md
@@ -56,7 +56,7 @@ Index Built
### 提取后
```bash
-he parse tesla.md -t general/biography_graph -o ./kb/ -l en
+he parse sushi.md -t general/biography_graph -o ./kb/ -l zh
he info ./kb/
```
diff --git a/docs/zh/cli/commands/search.md b/docs/zh/cli/commands/search.md
index a1aadca..3f9a410 100644
--- a/docs/zh/cli/commands/search.md
+++ b/docs/zh/cli/commands/search.md
@@ -42,7 +42,7 @@ he search KA_PATH QUERY [OPTIONS]
### 基本搜索
```bash
-he search ./output/ "Tesla's inventions"
+he search ./output/ "苏轼的代表作"
```
### 获取更多结果
@@ -55,8 +55,8 @@ he search ./output/ "electrical engineering" -n 10
```bash
he search ./kb/ "主要成就是什么?"
-he search ./kb/ "与爱迪生一起工作的人"
-he search ./kb/ "时间线上的重要日期"
+he search ./kb/ "与欧阳修相关的人"
+he search ./kb/ "苏轼生平重要年份"
```
### 构建索引后
@@ -78,17 +78,17 @@ Found 3 result(s):
Result 1:
{
- "name": "Nikola Tesla",
- "type": "person",
- "description": "Serbian-American inventor, electrical engineer..."
+ "name": "苏轼",
+ "type": "人物",
+ "description": "北宋文学家、书画家,号东坡居士"
}
Result 2:
{
- "source": "Nikola Tesla",
- "target": "Thomas Edison",
- "type": "worked_with",
- "description": "Tesla worked for Edison in 1884"
+ "source": "苏轼",
+ "target": "欧阳修",
+ "type": "师生",
+ "description": "欧阳修赏识苏轼才华,预言其将超越自己"
}
Result 3:
@@ -108,7 +108,7 @@ Result 3:
## 更好搜索的技巧
1. **使用自然语言** — "电气工程方面的发明" vs "发明 电气"
-2. **要具体** — "特斯拉在交流电方面的工作" vs "特斯拉 工作"
+2. **要具体** — "苏轼在词作方面的成就" vs "苏轼 成就"
3. **尝试同义词** — 如果 "发明" 不行,尝试 "发现"
4. **增加 top-k** — 使用 `-n 10` 获取更广泛的结果
diff --git a/docs/zh/cli/commands/show.md b/docs/zh/cli/commands/show.md
index 1162ce9..83d9c91 100644
--- a/docs/zh/cli/commands/show.md
+++ b/docs/zh/cli/commands/show.md
@@ -40,20 +40,20 @@ he show ./output/
```bash
# 先提取
-he parse tesla.md -t general/biography_graph -o ./tesla_kb/ -l en
+he parse sushi.md -t general/biography_graph -o ./sushi_kb/ -l zh
# 然后可视化
-he show ./tesla_kb/
+he show ./sushi_kb/
```
### 增量更新后
```bash
# 添加更多内容
-he feed ./tesla_kb/ additional_info.md
+he feed ./sushi_kb/ additional_info.md
# 可视化更新后的图谱
-he show ./tesla_kb/
+he show ./sushi_kb/
```
---
diff --git a/docs/zh/cli/commands/talk.md b/docs/zh/cli/commands/talk.md
index ec77e52..0e5c7dc 100644
--- a/docs/zh/cli/commands/talk.md
+++ b/docs/zh/cli/commands/talk.md
@@ -43,31 +43,29 @@ he talk KA_PATH [OPTIONS]
### 单个问题
```bash
-he talk ./output/ -q "特斯拉的主要成就是什么?"
+he talk ./output/ -q "苏轼的主要成就是什么?"
```
**输出:**
```
-Query: 特斯拉的主要成就是什么?
+Query: 苏轼的主要成就是什么?
Knowledge Abstract: ./output/
Top K: 3
-Nikola Tesla made numerous groundbreaking contributions to electrical
-engineering. His major achievements include:
+苏轼在文学、艺术领域取得了卓越成就,主要贡献包括:
-1. Development of the alternating current (AC) electrical system, which
- became the dominant method of power transmission worldwide.
+1. 开创了豪放词派,《念奴娇·赤壁怀古》成为千古名篇,
+ 对后世词坛影响深远。
-2. Invention of the Tesla coil, used in radio technology and electrical
- resonant circuits.
+2. 与黄庭坚并称"苏黄",诗歌清新豪健;书法为"宋四家"之首,
+ 《黄州寒食诗帖》被誉为"天下第三行书"。
-3. Contributions to the development of X-ray imaging and wireless
- communication technologies.
+3. 散文为"唐宋八大家"之一,其《赤壁赋》等作品至今仍被广泛传诵。
Retrieved context:
-1. Nikola Tesla: Serbian-American inventor, electrical engineer...
-2. AC Power System: Type: invention, Description: System for alternating...
-3. Tesla Coil: Type: invention, Description: Resonant transformer circuit...
+1. 苏轼: 北宋文学家、书画家,号东坡居士...
+2. 《念奴娇·赤壁怀古》: 类型: 作品, 描述: 豪放词代表作...
+3. 黄州: 类型: 地点, 描述: 苏轼被贬之地,东坡居士名号由来...
```
### 交互模式
@@ -84,18 +82,17 @@ Knowledge Abstract: ./output/
Template: general/biography_graph
Top K: 3
-> 谁是 Nikola Tesla?
-Nikola Tesla 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.
+> 苏轼是谁?
+苏轼(1037-1101),字子瞻,号东坡居士,是北宋时期最杰出的
+文学家、书画家、政治家,唐宋八大家之一。
-> 他什么时候出生的?
-Nikola Tesla 于 1856 年 7 月 10 日出生在克罗地亚的 Smiljan。
+> 他是什么时候出生的?
+苏轼于 1037 年出生于眉州眉山(今四川眉山)。
-> 他与爱迪生的关系如何?
-Tesla 于 1884 年在纽约市为 Thomas Edison 工作。由于在直流电(DC)
-和交流电(AC)电力系统方面的不同观点,他们的关系存在争议。
+> 他与王安石的关系如何?
+苏轼与王安石政见不合。王安石推行新法时,苏轼多次上书批评,
+认为新法过于激进,损害百姓利益。1079年因此发生"乌台诗案",
+苏轼被贬黄州。
> exit
Goodbye!
@@ -144,7 +141,7 @@ he talk ./contract_kb/ -q "终止条件是什么?"
### 历史研究
```bash
-he talk ./bio_kb/ -q "哪些事件导致了特斯拉的经济困难?"
+he talk ./bio_kb/ -q "哪些事件导致了苏轼的政治生涯坎坷?"
```
---
@@ -160,7 +157,7 @@ he talk ./bio_kb/ -q "哪些事件导致了特斯拉的经济困难?"
## 更好答案的技巧
-1. **要具体** — "特斯拉创造了什么发明?" vs "告诉我关于特斯拉的事"
+1. **要具体** — "苏轼创作了哪些词作?" vs "告诉我关于苏轼的事"
2. **追问** — 通过对话构建上下文
3. **调整 top-k** — 对于复杂问题使用 `-n 5` 或更高
4. **检查来源** — 审查 "Retrieved context" 的准确性
diff --git a/docs/zh/cli/index.md b/docs/zh/cli/index.md
index ee7b121..96b7841 100644
--- a/docs/zh/cli/index.md
+++ b/docs/zh/cli/index.md
@@ -6,9 +6,17 @@ Hyper-Extract CLI (`he`) 提供了强大、易用的界面,可直接从终端
## 安装
-```bash
-pip install hyper-extract
-```
+=== "uv (推荐)"
+
+ ```bash
+ uv pip install hyper-extract
+ ```
+
+=== "pip"
+
+ ```bash
+ pip install hyper-extract
+ ```
验证安装:
@@ -39,19 +47,31 @@ he --version
提取和交互知识的典型工作流程:
```mermaid
-graph LR
- A[Document] -->|he parse| B[Knowledge Base]
- B -->|he show| C[Visualize]
- B -->|he search| D[Search]
- B -->|he talk| E[Chat]
- B -->|he feed| B[Update]
+flowchart TB
+ subgraph Create ["🚀 创建"]
+ D[📄 Document] -->|he parse| KB[(💡 Knowledge Base)]
+ end
+
+ subgraph Enhance ["✨ 增强(可选)"]
+ KB -->|he feed| KB
+ KB -->|he build-index| IDX[(🔍 Index)]
+ end
+
+ subgraph Explore ["🔍 探索"]
+ KB -->|he show| VIS[👁️ Visualize]
+ IDX -->|he search| SRCH[🔎 Search]
+ IDX -->|he talk| CHAT[💬 Chat]
+ end
+
+ subgraph Save ["💾 保存"]
+ KB -->|he dump| DISK[💾 Disk]
+ end
```
-1. **Parse** — 从文档提取知识
-2. **Show** — 可视化知识图谱
-3. **Search** — 查找特定信息
-4. **Talk** — 关于内容进行对话
-5. **Feed** — 增量添加更多文档
+1. **创建** — 从文档提取知识 (`he parse`)
+2. **增强** — 增量添加文档 (`he feed`)、构建索引 (`he build-index`)
+3. **探索** — 可视化 (`he show`)、搜索 (`he search`)、对话 (`he talk`)
+4. **保存** — 持久化到磁盘 (`he dump`)
→ [详细工作流程指南](workflow.md)
diff --git a/docs/zh/concepts/architecture.md b/docs/zh/concepts/architecture.md
index 5deb311..257556f 100644
--- a/docs/zh/concepts/architecture.md
+++ b/docs/zh/concepts/architecture.md
@@ -39,12 +39,12 @@ graph LR
```python
# 输入:原始文本
-text = "Nikola Tesla was an inventor..."
+text = "苏轼是北宋著名文学家..."
# 如果 text > chunk_size,拆分为块
chunks = [
- "Nikola Tesla was an inventor...",
- "He developed the AC system...",
+ "苏轼是北宋著名文学家...",
+ "他创作了《赤壁赋》...",
# ...
]
```
diff --git a/docs/zh/concepts/autotypes.md b/docs/zh/concepts/autotypes.md
index 85e701c..94d467d 100644
--- a/docs/zh/concepts/autotypes.md
+++ b/docs/zh/concepts/autotypes.md
@@ -50,10 +50,12 @@ graph TD
**示例输出**:
```python
{
- "company_name": "Tesla Inc",
- "revenue": 81.46,
- "eps": 4.07,
- "employees": 127855
+ "name": "苏轼",
+ "style_name": "子瞻",
+ "art_name": "东坡居士",
+ "dynasty": "北宋",
+ "birth_year": 1037,
+ "masterpiece": "念奴娇·赤壁怀古"
}
```
@@ -76,9 +78,9 @@ graph TD
```python
{
"items": [
- {"name": "AC Motor", "year": 1888},
- {"name": "Tesla Coil", "year": 1891},
- {"name": "Radio", "year": 1898}
+ {"name": "《念奴娇·赤壁怀古》", "year": 1082},
+ {"name": "《水调歌头·明月几时有》", "year": 1076},
+ {"name": "《赤壁赋》", "year": 1082}
]
}
```
@@ -102,10 +104,10 @@ graph TD
```python
{
"items": [
- "Electrical Engineering",
- "Physics",
- "Invention",
- "Renewable Energy"
+ "豪放词",
+ "行书",
+ "文人画",
+ "宋四家"
]
}
```
@@ -131,13 +133,15 @@ graph TD
```python
{
"nodes": [
- {"name": "Tesla", "type": "person"},
- {"name": "Edison", "type": "person"},
- {"name": "AC Motor", "type": "invention"}
+ {"name": "苏轼", "type": "人物"},
+ {"name": "苏辙", "type": "人物"},
+ {"name": "欧阳修", "type": "人物"},
+ {"name": "《赤壁赋》", "type": "作品"}
],
"edges": [
- {"source": "Tesla", "target": "AC Motor", "type": "invented"},
- {"source": "Tesla", "target": "Edison", "type": "rivals"}
+ {"source": "苏轼", "target": "苏辙", "type": "兄弟"},
+ {"source": "苏轼", "target": "欧阳修", "type": "师生"},
+ {"source": "苏轼", "target": "《赤壁赋》", "type": "创作"}
]
}
```
@@ -163,9 +167,9 @@ graph TD
"nodes": [...],
"edges": [
{
- "entities": ["Tesla", "Westinghouse", "Niagara"],
- "type": "collaboration",
- "description": "Power plant project"
+ "entities": ["苏轼", "苏辙", "苏洵"],
+ "type": "三苏",
+ "description": "父子三人同列唐宋八大家"
}
]
}
@@ -193,16 +197,16 @@ graph TD
"nodes": [...],
"edges": [
{
- "source": "Tesla",
- "target": "AC Motor",
- "type": "invented",
- "time": "1888"
+ "source": "苏轼",
+ "target": "《念奴娇·赤壁怀古》",
+ "type": "创作",
+ "time": "1082"
},
{
- "source": "Tesla",
- "target": "Wardenclyffe Tower",
- "type": "built",
- "time": "1901-1902"
+ "source": "苏轼",
+ "target": "黄州",
+ "type": "贬谪",
+ "time": "1080-1084"
}
]
}
@@ -228,17 +232,17 @@ graph TD
{
"nodes": [
{
- "name": "Colorado Springs",
- "type": "location",
- "coordinates": "38.8339,-104.8214"
+ "name": "黄州",
+ "type": "地点",
+ "coordinates": "湖北省黄冈市"
}
],
"edges": [
{
- "source": "Tesla",
- "target": "Colorado Springs",
- "type": "conducted_experiments",
- "location": "Colorado Springs"
+ "source": "苏轼",
+ "target": "黄州",
+ "type": "躬耕",
+ "location": "东坡"
}
]
}
@@ -264,12 +268,12 @@ graph TD
"nodes": [...],
"edges": [
{
- "source": "Tesla",
- "target": "AC Motor",
- "type": "demonstrated",
- "time": "1888",
- "location": "Pittsburgh",
- "description": "Demonstration at Westinghouse"
+ "source": "苏轼",
+ "target": "《赤壁赋》",
+ "type": "创作",
+ "time": "1082",
+ "location": "黄州",
+ "description": "夜游赤壁,饮酒赋诗"
}
]
}
@@ -330,14 +334,16 @@ result = ka.parse(text)
# 增量更新
result.feed_text(more_text)
-# 搜索(需要索引)
+# 构建索引(搜索、聊天和交互式可视化都需要)
result.build_index()
+
+# 搜索
results = result.search("query")
-# 聊天(需要索引)
+# 聊天
response = result.chat("question")
-# 可视化
+# 可视化(支持搜索/对话的交互式可视化)
result.show()
# 持久化
diff --git a/docs/zh/getting-started/cli-quickstart.md b/docs/zh/getting-started/cli-quickstart.md
index da6aa5f..81033e9 100644
--- a/docs/zh/getting-started/cli-quickstart.md
+++ b/docs/zh/getting-started/cli-quickstart.md
@@ -1,97 +1,198 @@
# CLI 快速入门
-使用命令行从终端提取知识。
+使用命令行在 5 分钟内完成首次知识提取。
---
## 前置要求
-- Hyper-Extract 已安装
-- API 密钥已配置
-
-→ 如果尚未完成,请查看[安装指南](installation.md)
+- [Hyper-Extract 已安装](installation.md)
+- 一个待提取的文本文档(我们将使用示例)
---
-## 快速示例
+## 第 1 步:配置 API 密钥
-### 1. 从文档提取知识
+运行以下命令配置 API 密钥:
```bash
-he parse tesla.md -t general/biography_graph -o ./output/ -l en
+he config init -k YOUR_OPENAI_API_KEY
```
-这将从 `tesla.md` 中提取知识图谱并保存到 `./output/` 目录。
+这会在 `~/.he/config.toml` 创建配置文件,只需配置一次。
+
+---
-### 2. 可视化结果
+## 第 2 步:下载示例文档
```bash
-he show ./output/
+# 下载示例传记
+curl -o sushi.md https://raw.githubusercontent.com/yifanfeng97/hyper-extract/main/examples/zh/sushi.md
```
-### 3. 搜索知识库
+或创建一个简单的测试文件:
```bash
-he search ./output/ "AC motor invention"
+cat > sample.txt << 'EOF'
+苏轼,字子瞻,号东坡居士,是北宋时期最杰出的文学家、书画家、政治家。
+他与父亲苏洵、弟弟苏辙并称"三苏",同列唐宋八大家。
+
+苏轼于1037年出生于眉州眉山。1057年科举中举,受欧阳修赏识。
+后因乌台诗案被贬黄州,创作了大量千古传诵的名篇。
+
+代表作:《念奴娇·赤壁怀古》《水调歌头·明月几时有》《赤壁赋》
+
+苏轼一生宦海浮沉,历任杭州、密州、徐州、湖州等地知州。
+在杭州任上,他疏浚西湖,修筑苏堤,留下"欲把西湖比西子"的千古名句。
+晚年因新党执政被贬至惠州、儋州,仍心系百姓,兴办学堂,传播中原文化。
+
+其文学成就横跨诗、词、文、赋,书法位列"宋四家"之首,
+绘画开文人画先河,是中国历史上罕见的全才式人物。
+EOF
```
-### 4. 与知识库对话
+---
+
+## 第 3 步:提取知识
+
+运行 `parse` 命令提取知识:
```bash
-he talk ./output/ -q "What were Tesla's major inventions?"
+he parse sushi.md -t general/biography_graph -o ./output/ -l zh
+```
+
+参数说明:
+- `-t general/biography_graph` — 使用传记图谱模板
+- `-o ./output/` — 保存结果到输出目录
+- `-l zh` — 使用中文处理
+
+**输出示例:**
+```
+Input: sushi.md
+Output: ./output/
+Template: general/biography_graph
+Language: en
+Build Index: Yes
+
+Template resolved: Biography Graph Template
+✓ Knowledge extracted to ./output/
+
+What's next?
+ he show ./output/ # 可视化知识图谱
+ he search ./output/ "keyword" # 语义搜索
+ he talk ./output/ -i # 交互式对话
```
---
-## 完整工作流程
+## 第 4 步:可视化知识图谱
+
+```bash
+he show ./output/
+```
+
+这会在浏览器中打开交互式可视化,显示:
+- **实体**(人物、地点、事件)作为节点
+- **关系** 作为连接节点的边
+
+![知识图谱可视化](../../assets/zh_show.png)
-```mermaid
-graph LR
- A[Document] -->|he parse| B[Knowledge Base]
- B -->|he show| C[Visualize]
- B -->|he search| D[Search]
- B -->|he talk| E[Chat]
- B -->|he feed| B[Update]
+---
+
+## 第 5 步:搜索知识库
+
+```bash
+he search ./output/ "苏轼的代表作有哪些"
```
-1. **Parse** — 从文档提取知识
-2. **Show** — 可视化知识图谱
-3. **Search** — 查找特定信息
-4. **Talk** — 关于内容进行对话
-5. **Feed** — 增量添加更多文档
+**输出示例:**
+```
+Found 3 result(s):
+
+Result 1:
+{
+ "name": "苏轼",
+ "type": "人物",
+ "description": "北宋文学家、书画家,号东坡居士"
+}
+...
+```
---
-## 常用命令
+## 第 6 步:与知识库对话
-### 解析文档
+交互模式:
```bash
-# 使用模板
-he parse doc.md -t general/biography_graph -o ./out/ -l en
+he talk ./output/ -i
+```
-# 使用方法
-he parse doc.md -m light_rag -o ./out/
+或提问单个问题:
+
+```bash
+he talk ./output/ -q "用三句话总结苏轼的生平"
```
-### 构建索引
+---
+
+## 第 7 步:增量添加知识
+
+有更多文档?无需重新处理即可添加:
```bash
-# 构建搜索索引(搜索和聊天需要)
-he build-index ./output/
+he feed ./output/ additional_document.md
+```
+
+然后可视化更新后的知识:
+
+```bash
+he show ./output/
```
-### 查看信息
+---
+
+## 完整工作流程
+
+以下是典型的工作流程:
```bash
-# 查看知识库统计
-he info ./output/
+# 1. 提取知识
+he parse document.md -t general/biography_graph -o ./output/ -l en
+
+# 2. 可视化
+he show ./output/
+
+# 3. 搜索
+he search ./output/ "your query"
+
+# 4. 对话
+he talk ./output/ -i
+
+# 5. 添加更多文档
+he feed ./output/ another_document.md
+
+# 6. 如需重新构建索引
+he build-index ./output/
```
---
## 下一步
-- 深入了解 [CLI 命令](../cli/index.md)
-- 浏览 [模板库](../templates/index.md)
-- 理解 [核心概念](../concepts/index.md)
+- [CLI 工作流程指南](../cli/workflow.md) — 完整工作流程演示
+- [所有 CLI 命令](../cli/index.md) — 详细命令参考
+- [模板库](../templates/index.md) — 找到适合您用例的模板
+
+---
+
+## 故障排除
+
+**"No API key found"**
+→ 运行 `he config init -k YOUR_API_KEY`
+
+**"Template not found"**
+→ 使用 `he list template` 查看可用模板
+
+**"Output directory already exists"**
+→ 添加 `-f` 标志强制覆盖,或选择不同的输出路径
diff --git a/docs/zh/getting-started/index.md b/docs/zh/getting-started/index.md
index e18d825..7974abb 100644
--- a/docs/zh/getting-started/index.md
+++ b/docs/zh/getting-started/index.md
@@ -18,7 +18,7 @@
- 需要批量处理文件
- 更喜欢终端工作流程
- **从这里开始:** [:octicons-arrow-right-24: 安装](installation.md) → [:octicons-arrow-right-24: CLI 快速入门](cli-quickstart.md)
+ **从这里开始:** [安装](installation.md) [:octicons-arrow-right-24: CLI 快速入门](cli-quickstart.md)
- :material-language-python:{ .lg .middle } __我想使用 Python__
@@ -30,7 +30,7 @@
- 需要与现有代码集成
- 想要完全的程序化控制
- **从这里开始:** [:octicons-arrow-right-24: 安装](installation.md) → [:octicons-arrow-right-24: Python 快速入门](python-quickstart.md)
+ **从这里开始:** [安装](installation.md) [:octicons-arrow-right-24: Python 快速入门](python-quickstart.md)
</div>
diff --git a/docs/zh/getting-started/installation.md b/docs/zh/getting-started/installation.md
index 326fa28..508a707 100644
--- a/docs/zh/getting-started/installation.md
+++ b/docs/zh/getting-started/installation.md
@@ -6,16 +6,16 @@ Hyper-Extract 需要 **Python 3.11+**。
## 从 PyPI 安装
-=== "pip"
+=== "uv (推荐)"
```bash
- pip install hyper-extract
+ uv pip install hyper-extract
```
-=== "uv (推荐)"
+=== "pip"
```bash
- uv pip install hyper-extract
+ pip install hyper-extract
```
=== "conda"
@@ -40,65 +40,6 @@ Hyper-Extract CLI version 0.1.0
---
-## 可选依赖
-
-=== "Anthropic Claude 支持"
-
- ```bash
- pip install hyper-extract[anthropic]
- ```
-
-=== "Google Gemini 支持"
-
- ```bash
- pip install hyper-extract[google]
- ```
-
-=== "所有可选依赖"
-
- ```bash
- pip install hyper-extract[all]
- ```
-
----
-
-## 配置
-
-在使用 Hyper-Extract 之前,您需要配置 LLM API 凭证。
-
-### 选项 1:使用 CLI(推荐)
-
-```bash
-he config init -k YOUR_OPENAI_API_KEY
-```
-
-这将在 `~/.he/config.toml` 创建配置文件。
-
-### 选项 2:使用环境变量
-
-```bash
-export OPENAI_API_KEY=your-api-key
-export OPENAI_BASE_URL=https://api.openai.com/v1 # 可选
-```
-
-### 选项 3:使用 .env 文件(仅限 Python)
-
-在项目根目录创建 `.env` 文件:
-
-```
-OPENAI_API_KEY=your-api-key
-OPENAI_BASE_URL=https://api.openai.com/v1
-```
-
-然后在 Python 代码中加载:
-
-```python
-from dotenv import load_dotenv
-load_dotenv()
-```
-
----
-
## 开发安装
如果您想贡献或修改源代码:
diff --git a/docs/zh/getting-started/python-quickstart.md b/docs/zh/getting-started/python-quickstart.md
index 71916d2..eb290ad 100644
--- a/docs/zh/getting-started/python-quickstart.md
+++ b/docs/zh/getting-started/python-quickstart.md
@@ -1,125 +1,254 @@
# Python 快速入门
-使用 Python API 进行知识提取。
+使用 Python 在 5 分钟内完成首次知识提取。
---
## 前置要求
-- Hyper-Extract 已安装
-- API 密钥已配置
-
-→ 如果尚未完成,请查看[安装指南](installation.md)
+- [Hyper-Extract 已安装](installation.md)
---
-## 基本示例
+## 第 1 步:搭建项目
-### 1. 创建模板
+创建新目录并设置环境:
-```python
-from hyperextract import Template
+```bash
+mkdir my_extraction_project
+cd my_extraction_project
+
+# 创建虚拟环境(可选但推荐)
+python -m venv venv
+source venv/bin/activate # Windows: venv\Scripts\activate
-ka = Template.create("general/biography_graph", language="en")
+# 安装 hyper-extract
+pip install hyper-extract
```
-### 2. 提取知识
+---
-```python
-with open("document.md") as f:
- result = ka.parse(f.read())
-```
+## 第 2 步:配置 API 密钥
-### 3. 访问数据
+创建 `.env` 文件:
-```python
-print(f"节点数量: {len(result.data.nodes)}")
-print(f"边数量: {len(result.data.edges)}")
+```bash
+echo "OPENAI_API_KEY=your-api-key" > .env
```
-### 4. 可视化
+---
+
+## 第 3 步:创建首个提取脚本
+
+创建文件 `extract.py`:
```python
+from dotenv import load_dotenv
+
+# 从 .env 文件加载 API 密钥
+load_dotenv()
+
+from hyperextract import Template
+
+# 创建模板实例
+ka = Template.create("general/biography_graph", language="zh")
+
+# 示例文本
+text = """
+苏轼,字子瞻,号东坡居士,是北宋时期最杰出的文学家、书画家、政治家。
+他与父亲苏洵、弟弟苏辙并称"三苏",同列唐宋八大家。
+
+苏轼于1037年出生于眉州眉山。1057年科举中举,受欧阳修赏识。
+后因乌台诗案被贬黄州,创作了大量千古传诵的名篇。
+
+代表作:《念奴娇·赤壁怀古》《水调歌头·明月几时有》《赤壁赋》
+
+苏轼一生宦海浮沉,历任杭州、密州、徐州、湖州等地知州。
+在杭州任上,他疏浚西湖,修筑苏堤,留下"欲把西湖比西子"的千古名句。
+晚年因新党执政被贬至惠州、儋州,仍心系百姓,兴办学堂,传播中原文化。
+
+其文学成就横跨诗、词、文、赋,书法位列"宋四家"之首,
+绘画开文人画先河,是中国历史上罕见的全才式人物。
+"""
+
+# 提取知识
+result = ka.parse(text)
+
+# 访问提取的数据
+print(f"节点: {len(result.nodes)}")
+print(f"边: {len(result.edges)}")
+
+# 打印第一个节点
+if result.nodes:
+ node = result.nodes[0]
+ print(f"\n第一个节点: {node.name} ({node.type})")
+
+# 构建索引以支持搜索/对话功能
+result.build_index()
+
+# 可视化
result.show()
```
---
-## 完整示例
+## 第 4 步:运行脚本
-```python
-from hyperextract import Template
+```bash
+python extract.py
+```
-# 创建模板
-ka = Template.create("general/biography_graph", language="en")
+你应该看到:
-# 提取知识
-with open("tesla.md") as f:
- result = ka.parse(f.read())
+```
+节点: 5
+边: 4
+
+第一个节点: 苏轼 (人物)
+```
+
+同时会打开浏览器窗口显示交互式知识图谱。
+
+![知识图谱可视化](../../assets/zh_show.png)
+
+---
-# 访问数据
-print(f"节点: {len(result.data.nodes)}")
-print(f"边: {len(result.data.edges)}")
+## 第 5 步:处理结果
-# 构建搜索索引
+访问提取结果的不同部分:
+
+```python
+# 遍历所有节点
+for node in result.nodes:
+ print(f"- {node.name}: {node.description}")
+
+# 遍历所有边
+for edge in result.edges:
+ print(f"- {edge.source} --{edge.type}--> {edge.target}")
+
+# 在知识库中搜索
result.build_index()
+nodes, edges = result.search("代表作", top_k=3)
+for node in nodes:
+ print(f"节点: {node.name}")
+for edge in edges:
+ print(f"边: {edge.source} -> {edge.target}")
+```
+
+---
-# 搜索
-results = result.search("AC motor")
-print(results)
+## 第 6 步:保存和加载
-# 聊天
-response = result.chat("What were Tesla's major inventions?")
-print(response.content)
+保存知识库以便后续使用:
-# 保存
-result.dump("./output/")
+```python
+# 保存到磁盘
+result.dump("./my_knowledge_base/")
-# 加载
-result.load("./output/")
+# 稍后加载回来
+new_ka = Template.create("general/biography_graph", language="en")
+new_ka.load("./my_knowledge_base/")
```
---
-## 增量更新
+## 第 7 步:增量更新
-向现有知识库添加更多文档:
+添加更多文本而不会丢失现有知识:
```python
-# 初始提取
-kb = ka.parse(doc1_text)
+additional_text = """
+1071年,苏轼主动请求外放,任杭州通判。在杭州期间他常常泛舟西湖,
+写下了著名的《饮湖上初晴后雨》:"欲把西湖比西子,淡妆浓抹总相宜。"
+"""
+
+# feed 添加到现有知识
+result.feed_text(additional_text)
-# 添加更多文档
-kb.feed_text(doc2_text)
-kb.feed_text(doc3_text)
+# 重新构建索引
+result.build_index()
-# 保存
-kb.dump("./my_kb/")
+# 可视化更新后的图谱
+result.show()
```
---
-## 使用不同模板
+## 完整示例
+
+以下是完整的、可用于生产的脚本:
```python
-# 财务报告
-ka = Template.create("finance/earnings_summary", language="en")
-report = ka.parse(earnings_text)
-print(report.data.revenue)
-
-# 法律文档
-ka = Template.create("legal/contract_obligation", language="en")
-contract = ka.parse(contract_text)
-
-# 医疗记录
-ka = Template.create("medicine/symptom_list", language="en")
-symptoms = ka.parse(medical_text)
+"""从文档中提取知识并与之交互。"""
+
+import os
+from pathlib import Path
+from dotenv import load_dotenv
+from hyperextract import Template
+
+# 配置
+load_dotenv()
+
+INPUT_FILE = "document.txt"
+OUTPUT_DIR = "./output/"
+TEMPLATE = "general/biography_graph"
+LANGUAGE = "zh"
+
+
+def main():
+ # 创建模板
+ print(f"创建模板: {TEMPLATE}")
+ ka = Template.create(TEMPLATE, language=LANGUAGE)
+
+ # 读取文档
+ print(f"读取: {INPUT_FILE}")
+ text = Path(INPUT_FILE).read_text(encoding="utf-8")
+
+ # 提取知识
+ print("提取知识...")
+ result = ka.parse(text)
+
+ # 打印摘要
+ print(f"\n提取完成:")
+ print(f" - 节点: {len(result.nodes)}")
+ print(f" - 边: {len(result.edges)}")
+
+ # 构建搜索索引
+ print("构建搜索索引...")
+ result.build_index()
+
+ # 保存到磁盘
+ print(f"保存到: {OUTPUT_DIR}")
+ result.dump(OUTPUT_DIR)
+
+ # 交互式可视化
+ print("打开可视化...")
+ result.show()
+
+ print("\n完成!")
+
+
+if __name__ == "__main__":
+ main()
```
---
## 下一步
-- 阅读 [Python SDK 文档](../python/index.md)
-- 探索 [模板库](../templates/index.md)
-- 理解 [核心概念](../concepts/index.md)
+- [Python SDK 概览](../python/index.md) — 完整 API 参考
+- [使用模板](../python/guides/using-templates.md) — 模板使用指南
+- [自动类型指南](../concepts/autotypes.md) — 选择合适的数据结构
+
+---
+
+## 故障排除
+
+**"No module named 'hyperextract'"**
+→ 运行 `pip install hyper-extract`
+
+**"API key not found"**
+→ 检查 `.env` 文件或设置 `OPENAI_API_KEY` 环境变量
+
+**"Template not found"**
+→ 使用 `Template.list()` 查看可用模板
diff --git a/docs/zh/index.md b/docs/zh/index.md
index f4194b1..d8c991b 100644
--- a/docs/zh/index.md
+++ b/docs/zh/index.md
@@ -1,9 +1,5 @@
<div align="center">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="../assets/logo/logo-horizontal-dark.svg">
- <source media="(prefers-color-scheme: light)" srcset="../assets/logo/logo-horizontal.svg">
- <img alt="Hyper-Extract Logo" src="../assets/logo/logo-horizontal.svg" width="500">
- </picture>
+ <img alt="Hyper-Extract Logo" src="../assets/logo/logo-horizontal.svg" width="500">
</div>
<br/>
@@ -28,7 +24,7 @@
he config init -k YOUR_OPENAI_API_KEY
# 3. 从文档中提取知识
- he parse tesla.md -t general/biography_graph -o ./output/ -l en
+ he parse sushi.md -t general/biography_graph -o ./output/ -l zh
# 4. 可视化知识图谱
he show ./output/
@@ -40,10 +36,10 @@
from hyperextract import Template
# 1. 创建模板
- ka = Template.create("general/biography_graph", "en")
+ ka = Template.create("general/biography_graph", "zh")
# 2. 提取知识
- with open("tesla.md") as f:
+ with open("sushi.md") as f:
result = ka.parse(f.read())
# 3. 可视化
@@ -153,20 +149,24 @@ Hyper-Extract 采用**三层架构**:
```mermaid
graph TD
- A[Your Document] --> B[Template / Method]
- B --> C[Auto-Type]
- C --> D[Structured Knowledge]
-
- subgraph "Layer 3: Templates"
- B
+ A[您的文档] --> B[CLI / Python API]
+ B --> C[模板]
+ B --> D[方法]
+ C --> E[自动类型]
+ D --> E
+ E --> F[结构化知识]
+
+ subgraph "Layer 3: 模板与方法"
+ C
+ D
end
-
- subgraph "Layer 2: Methods"
- B
+
+ subgraph "Layer 2: 核心引擎"
+ E
end
-
- subgraph "Layer 1: Auto-Types"
- C
+
+ subgraph "Layer 1: 输出"
+ F
end
```
diff --git a/docs/zh/python/core-concepts.md b/docs/zh/python/core-concepts.md
index 0892749..7033d1a 100644
--- a/docs/zh/python/core-concepts.md
+++ b/docs/zh/python/core-concepts.md
@@ -89,10 +89,10 @@ ka = Template.create("general/knowledge_graph", "en")
result = ka.parse(text)
# 访问图谱数据
-for node in result.data.nodes:
+for node in result.nodes:
print(f"Node: {node.name}")
-for edge in result.data.edges:
+for edge in result.edges:
print(f"{edge.source} --{edge.type}--> {edge.target}")
```
@@ -220,7 +220,10 @@ ka = Template.create("general/biography_graph", "en")
# 2. 提取
result = ka.parse(text)
-# 3. 使用
+# 3. 构建索引以支持搜索/对话功能
+result.build_index()
+
+# 4. 使用
result.show()
```
diff --git a/docs/zh/python/guides/incremental-updates.md b/docs/zh/python/guides/incremental-updates.md
index ad2710d..8b4eed8 100644
--- a/docs/zh/python/guides/incremental-updates.md
+++ b/docs/zh/python/guides/incremental-updates.md
@@ -19,15 +19,15 @@
```python
from hyperextract import Template
-ka = Template.create("general/biography_graph", "en")
+ka = Template.create("general/biography_graph", "zh")
# 初始提取
result = ka.parse(initial_text)
-print(f"初始: {len(result.data.nodes)} 个节点")
+print(f"初始: {len(result.nodes)} 个节点")
# 添加更多内容
result.feed_text(additional_text)
-print(f"Feed 后: {len(result.data.nodes)} 个节点")
+print(f"Feed 后: {len(result.nodes)} 个节点")
```
---
@@ -37,7 +37,7 @@ print(f"Feed 后: {len(result.data.nodes)} 个节点")
### 随着时间构建知识
```python
-ka = Template.create("general/biography_graph", "en")
+ka = Template.create("general/biography_graph", "zh")
kb = ka.parse(early_life_text)
# 添加职业信息
@@ -46,7 +46,10 @@ kb.feed_text(career_text)
# 添加晚年
kb.feed_text(later_years_text)
-# 最终结果组合所有时期
+# 在 feed 新数据后重建索引
+kb.build_index()
+
+# 最终结果组合所有时期(支持交互式搜索/对话)
kb.show()
```
@@ -58,7 +61,7 @@ kb = ka.parse(documents[0])
for doc in documents[1:]:
kb.feed_text(doc)
- print(f"已添加文档,现在有 {len(kb.data.nodes)} 个节点")
+ print(f"已添加文档,现在有 {len(kb.nodes)} 个节点")
```
### 使用新信息更新
@@ -136,9 +139,9 @@ kb.dump("./kb_v2/")
### 4. 监控增长
```python
-initial_count = len(kb.data.nodes)
+initial_count = len(kb.nodes)
kb.feed_text(new_text)
-new_count = len(kb.data.nodes)
+new_count = len(kb.nodes)
print(f"添加了 {new_count - initial_count} 个新节点")
```
@@ -154,7 +157,7 @@ from hyperextract import Template
from pathlib import Path
def build_knowledge_base(source_dir, output_dir):
- ka = Template.create("general/biography_graph", "en")
+ ka = Template.create("general/biography_graph", "zh")
# 获取所有文本文件
files = sorted(Path(source_dir).glob("*.md"))
@@ -171,7 +174,7 @@ def build_knowledge_base(source_dir, output_dir):
for file in files[1:]:
print(f"添加 {file.name}...")
kb.feed_text(file.read_text())
- print(f" 现在有 {len(kb.data.nodes)} 个节点")
+ print(f" 现在有 {len(kb.nodes)} 个节点")
# 为搜索/聊天构建索引
print("构建搜索索引...")
@@ -258,7 +261,7 @@ for batch in chunks(documents, batch_size=5):
规范化实体名称:
```python
-# 不要"Nikola Tesla"和"Tesla"混用
+# 不要"苏轼"和"苏东坡"混用
# 使用一致的命名
```
diff --git a/docs/zh/python/guides/saving-loading.md b/docs/zh/python/guides/saving-loading.md
index c1be9ec..061c9f7 100644
--- a/docs/zh/python/guides/saving-loading.md
+++ b/docs/zh/python/guides/saving-loading.md
@@ -20,7 +20,7 @@ Hyper-Extract 提供序列化支持:
```python
from hyperextract import Template
-ka = Template.create("general/biography_graph", "en")
+ka = Template.create("general/biography_graph", "zh")
result = ka.parse(text)
# 保存到目录
@@ -58,13 +58,13 @@ result.dump("./my_kb/")
from hyperextract import Template
# 创建模板(必须与原始匹配)
-ka = Template.create("general/biography_graph", "en")
+ka = Template.create("general/biography_graph", "zh")
# 加载保存的数据
ka.load("./my_kb/")
# 使用
-print(f"加载了 {len(ka.data.nodes)} 个节点")
+print(f"加载了 {len(ka.nodes)} 个节点")
```
### 验证加载的数据
@@ -76,8 +76,8 @@ ka.load("./my_kb/")
if ka.empty():
print("警告:未加载数据")
else:
- print(f"节点: {len(ka.data.nodes)}")
- print(f"边: {len(ka.data.edges)}")
+ print(f"节点: {len(ka.nodes)}")
+ print(f"边: {len(ka.edges)}")
```
---
@@ -243,16 +243,16 @@ class KnowledgeBaseManager:
manager = KnowledgeBaseManager()
# 保存
-ka = Template.create("general/biography_graph", "en")
+ka = Template.create("general/biography_graph", "zh")
result = ka.parse(text)
-manager.save(result, "tesla_biography")
+manager.save(result, "苏轼传记")
# 列出
-print(manager.list()) # ['tesla_biography']
+print(manager.list()) # ['苏轼传记']
# 加载
-kb = manager.load("tesla_biography")
-print(kb.chat("特斯拉发明了什么?"))
+kb = manager.load("苏轼传记")
+print(kb.chat("苏轼创作了哪些代表作?"))
```
---
@@ -263,7 +263,7 @@ print(kb.chat("特斯拉发明了什么?"))
```python
# 使用模板 X 保存
-ka = Template.create("general/biography_graph", "en")
+ka = Template.create("general/biography_graph", "zh")
# 使用相同模板加载
ka2 = Template.create("general/biography_graph", "en")
@@ -296,7 +296,7 @@ except FileNotFoundError:
```python
# 好
-result.dump("./kb/tesla_2024_01_15/")
+result.dump("./kb/sushi_2024_01_15/")
# 避免
result.dump("./kb/temp/")
diff --git a/docs/zh/python/guides/search-and-chat.md b/docs/zh/python/guides/search-and-chat.md
index 15f9810..62d96c2 100644
--- a/docs/zh/python/guides/search-and-chat.md
+++ b/docs/zh/python/guides/search-and-chat.md
@@ -20,7 +20,7 @@
```python
from hyperextract import Template
-ka = Template.create("general/biography_graph", "en")
+ka = Template.create("general/biography_graph", "zh")
result = ka.parse(text)
# 构建搜索索引
@@ -37,7 +37,7 @@ result.build_index()
```python
# 搜索相关项目(返回节点和边的元组)
-nodes, edges = result.search("inventions", top_k=5)
+nodes, edges = result.search("代表作", top_k=5)
for node in nodes:
print(f"节点: {node.name}")
@@ -49,7 +49,7 @@ for edge in edges:
```python
nodes, edges = result.search(
- query="electrical engineering achievements",
+ query="苏轼文学成就",
top_k=10 # 节点和边的结果数量
)
```
@@ -72,13 +72,13 @@ for edge in edges:
```python
# 查找特定人物
-people_nodes, people_edges = result.search("scientists who worked with Tesla", top_k=10)
+people_nodes, people_edges = result.search("与苏轼相关的人物", top_k=10)
# 查找概念
-concept_nodes, concept_edges = result.search("alternating current system", top_k=5)
+concept_nodes, concept_edges = result.search("豪放词", top_k=5)
# 查找事件
-event_nodes, event_edges = result.search("important dates in Tesla's life", top_k=10)
+event_nodes, event_edges = result.search("苏轼生平重要年份", top_k=10)
```
---
@@ -89,7 +89,7 @@ event_nodes, event_edges = result.search("important dates in Tesla's life", top_
```python
# 提问
-response = result.chat("特斯拉的主要成就是什么?")
+response = result.chat("苏轼的主要成就是什么?")
print(response.content)
```
@@ -97,7 +97,7 @@ print(response.content)
### 访问检索到的上下文
```python
-response = result.chat("特斯拉发明了什么?")
+response = result.chat("苏轼创作了哪些作品?")
print(response.content)
@@ -111,7 +111,7 @@ print(f"基于 {len(retrieved_nodes)} 个节点和 {len(retrieved_edges)} 条边
```python
response = result.chat(
- query="解释电流战争",
+ query="解释乌台诗案",
top_k=10 # 复杂问题需要更多上下文
)
```
@@ -120,16 +120,16 @@ response = result.chat(
```python
# 摘要
-summary = result.chat("用三句话总结特斯拉的职业生涯")
+summary = result.chat("用三句话总结苏轼的生平")
# 解释
-explanation = result.chat("特斯拉线圈的意义是什么?")
+explanation = result.chat("《赤壁赋》的意义是什么?")
# 比较
-comparison = result.chat("特斯拉的方法与爱迪生有何不同?")
+comparison = result.chat("苏轼与王安石的政见有何不同?")
# 时间线
-timeline = result.chat("特斯拉在 1880-1890 年间发生了什么?")
+timeline = result.chat("苏轼在 1080-1090 年间发生了什么?")
```
---
@@ -166,7 +166,7 @@ timeline = result.chat("特斯拉在 1880-1890 年间发生了什么?")
```python
# 首先,搜索特定节点
-nodes, edges = result.search("wireless technology", top_k=5)
+nodes, edges = result.search("东坡赤壁", top_k=5)
# 然后,询问它们
if nodes:
@@ -183,11 +183,11 @@ response = result.chat("本文档中的主要主题是什么?")
print(response.content)
# 深入了解
-response = result.chat("更多关于特斯拉线圈的信息")
+response = result.chat("更多关于赤壁赋的信息")
print(response.content)
# 特定问题
-response = result.chat("特斯拉线圈是如何工作的?")
+response = result.chat("赤壁赋的创作背景是什么?")
print(response.content)
```
@@ -196,7 +196,7 @@ print(response.content)
```python
class ResearchAssistant:
def __init__(self, kb_path):
- self.ka = Template.create("general/concept_graph", "en")
+ self.ka = Template.create("general/concept_graph", "zh")
self.ka.load(kb_path)
self.ka.build_index()
@@ -222,8 +222,8 @@ print(assistant.ask("有哪些局限性?"))
### 搜索技巧
-1. **使用自然语言** — "无线传输"而非"无线"
-2. **要具体** — "特斯拉的专利"而非"特斯拉"
+1. **使用自然语言** — "文学成就"而非"文学"
+2. **要具体** — "苏轼的作品"而非"苏轼"
3. **广泛查询时增加 top_k** — `top_k=10` 或更多
4. **按类型筛选结果** — 检查 `hasattr(item, 'name')`
@@ -254,7 +254,7 @@ results = result.search("discoveries")
results = result.search("contributions")
# 增加 top_k
-results = result.search("Tesla", top_k=20)
+results = result.search("苏轼", top_k=20)
```
### "无关的聊天响应"
diff --git a/docs/zh/python/guides/using-templates.md b/docs/zh/python/guides/using-templates.md
index 25e6824..e847c1d 100644
--- a/docs/zh/python/guides/using-templates.md
+++ b/docs/zh/python/guides/using-templates.md
@@ -156,11 +156,14 @@ with open("biography.md") as f:
result = ka.parse(f.read())
# 访问时间线数据
-for edge in result.data.edges:
+for edge in result.edges:
if hasattr(edge, 'time'):
print(f"{edge.time}: {edge.source} -> {edge.target}")
-result.show() # 可视化生平时间线
+# 构建索引以支持交互式可视化
+result.build_index()
+
+result.show() # 可视化生平时间线(支持搜索/对话功能)
```
### 模式 2:财务报告
diff --git a/docs/zh/python/guides/working-with-autotypes.md b/docs/zh/python/guides/working-with-autotypes.md
index 31a281e..4d768c3 100644
--- a/docs/zh/python/guides/working-with-autotypes.md
+++ b/docs/zh/python/guides/working-with-autotypes.md
@@ -81,12 +81,12 @@ ka = Template.create("general/knowledge_graph", "en")
result = ka.parse(text)
# 访问节点
-for node in result.data.nodes:
+for node in result.nodes:
print(f"{node.name} ({node.type})")
print(f" 描述: {node.description}")
# 访问边
-for edge in result.data.edges:
+for edge in result.edges:
print(f"{edge.source} --{edge.type}--> {edge.target}")
```
@@ -101,7 +101,7 @@ ka = Template.create("general/base_hypergraph", "en")
result = ka.parse(text)
# 超边连接多个实体
-for edge in result.data.edges:
+for edge in result.edges:
print(f"类型: {edge.type}")
print(f"实体: {edge.entities}")
```
@@ -117,7 +117,7 @@ ka = Template.create("general/base_temporal_graph", "en")
result = ka.parse(text)
# 边包含时间信息
-for edge in result.data.edges:
+for edge in result.edges:
print(f"{edge.source} --{edge.type}--> {edge.target}")
if hasattr(edge, 'time'):
print(f" 时间: {edge.time}")
@@ -134,7 +134,7 @@ ka = Template.create("general/base_spatial_graph", "en")
result = ka.parse(text)
# 节点/边包含位置
-for node in result.data.nodes:
+for node in result.nodes:
if hasattr(node, 'location'):
print(f"{node.name} at {node.location}")
```
@@ -150,7 +150,7 @@ ka = Template.create("general/base_spatio_temporal_graph", "en")
result = ka.parse(text)
# 完整上下文:谁、什么、何时、何地
-for edge in result.data.edges:
+for edge in result.edges:
print(f"事件: {edge.type}")
if hasattr(edge, 'time'):
print(f" 何时: {edge.time}")
@@ -168,7 +168,7 @@ for edge in result.data.edges:
if result.empty():
print("未提取到数据")
else:
- print(f"提取了 {len(result.data.nodes)} 个节点")
+ print(f"提取了 {len(result.nodes)} 个节点")
```
### 清除数据
@@ -202,8 +202,8 @@ combined = result1 + result2
result = ka.parse(text)
# 直接属性访问(Pydantic 模型)
-nodes = result.data.nodes
-edges = result.data.edges
+nodes = result.nodes
+edges = result.edges
# 字典转换
data_dict = result.data.model_dump()
@@ -230,14 +230,14 @@ with open("output.json", "w") as f:
```python
# 遍历节点
-for node in result.data.nodes:
+for node in result.nodes:
print(f"名称: {node.name}")
print(f"类型: {node.type}")
if hasattr(node, 'description'):
print(f"描述: {node.description}")
# 带筛选的边迭代
-for edge in result.data.edges:
+for edge in result.edges:
if edge.type == "worked_with":
print(f"{edge.source} 与 {edge.target} 合作")
```
@@ -246,24 +246,24 @@ for edge in result.data.edges:
```python
# 按类型筛选节点
-people = [n for n in result.data.nodes if n.type == "person"]
-organizations = [n for n in result.data.nodes if n.type == "organization"]
+people = [n for n in result.nodes if n.type == "person"]
+organizations = [n for n in result.nodes if n.type == "organization"]
# 筛选边
-inventions = [e for e in result.data.edges if "invent" in e.type.lower()]
+inventions = [e for e in result.edges if "invent" in e.type.lower()]
```
### 统计
```python
# 基本计数
-node_count = len(result.data.nodes)
-edge_count = len(result.data.edges)
+node_count = len(result.nodes)
+edge_count = len(result.edges)
# 类型分布
from collections import Counter
-node_types = Counter(n.type for n in result.data.nodes)
-edge_types = Counter(e.type for e in result.data.edges)
+node_types = Counter(n.type for n in result.nodes)
+edge_types = Counter(e.type for e in result.edges)
print(f"节点: {node_types}")
print(f"边: {edge_types}")
diff --git a/docs/zh/python/index.md b/docs/zh/python/index.md
index 5534107..5c64a34 100644
--- a/docs/zh/python/index.md
+++ b/docs/zh/python/index.md
@@ -31,8 +31,11 @@ with open("document.md") as f:
result = ka.parse(f.read())
# 访问数据
-print(f"节点数: {len(result.data.nodes)}")
-print(f"边数: {len(result.data.edges)}")
+print(f"节点数: {len(result.nodes)}")
+print(f"边数: {len(result.edges)}")
+
+# 构建索引以支持搜索/对话功能
+result.build_index()
# 可视化
result.show()
@@ -221,8 +224,8 @@ ka: AutoGraph = Template.create("general/knowledge_graph", "en")
result = ka.parse(text)
# IDE 自动完成有效
-nodes = result.data.nodes
-edges = result.data.edges
+nodes = result.nodes
+edges = result.edges
```
---
diff --git a/docs/zh/python/quickstart.md b/docs/zh/python/quickstart.md
index 0a9a6bd..777a34f 100644
--- a/docs/zh/python/quickstart.md
+++ b/docs/zh/python/quickstart.md
@@ -51,12 +51,12 @@ scientific fields.
result = ka.parse(text)
# 访问结果
-print(f"节点数: {len(result.data.nodes)}")
-print(f"边数: {len(result.data.edges)}")
+print(f"节点数: {len(result.nodes)}")
+print(f"边数: {len(result.edges)}")
# 打印第一个节点
-if result.data.nodes:
- node = result.data.nodes[0]
+if result.nodes:
+ node = result.nodes[0]
print(f"\n第一个: {node.name} ({node.type})")
print(f"描述: {node.description}")
```
@@ -73,6 +73,9 @@ Description: Polish-French physicist and chemist
### 3. 可视化
```python
+# 构建索引以支持搜索/对话功能
+result.build_index()
+
# 打开交互式可视化
result.show()
```
@@ -141,12 +144,12 @@ def main():
# 显示结果
print(f"\n提取结果:")
- print(f" 节点数: {len(result.data.nodes)}")
- print(f" 边数: {len(result.data.edges)}")
+ print(f" 节点数: {len(result.nodes)}")
+ print(f" 边数: {len(result.edges)}")
# 列出节点
print("\n发现的节点:")
- for node in result.data.nodes:
+ for node in result.nodes:
print(f" - {node.name} ({node.type})")
# 构建索引和搜索
diff --git a/docs/zh/resources/faq.md b/docs/zh/resources/faq.md
index 730d6bc..2a4c640 100644
--- a/docs/zh/resources/faq.md
+++ b/docs/zh/resources/faq.md
@@ -170,6 +170,9 @@ he show ./output/
或在 Python 中:
```python
+# 构建索引以支持可视化中的交互式搜索/对话
+result.build_index()
+
result.show()
```
diff --git a/docs/zh/templates/finance.md b/docs/zh/templates/finance.md
index 2014520..ddc9b14 100644
--- a/docs/zh/templates/finance.md
+++ b/docs/zh/templates/finance.md
@@ -77,7 +77,10 @@ he parse proxy.md -t finance/ownership_graph -l en
**可视化:**
```python
-result.show() # 显示所有权网络
+# 构建索引以支持可视化中的交互式搜索/对话
+result.build_index()
+
+result.show() # 显示带有交互功能的所有权网络
```
---
diff --git a/docs/zh/templates/general/index.md b/docs/zh/templates/general/index.md
index dbca1e7..80c1778 100644
--- a/docs/zh/templates/general/index.md
+++ b/docs/zh/templates/general/index.md
@@ -119,7 +119,7 @@ he parse doc.md -t general/base_graph -l en
**示例使用:**
```bash
-he parse tesla_bio.md -t general/biography_graph -l en
+he parse sushi.md -t general/biography_graph -l zh
```
**特性**:
@@ -131,15 +131,15 @@ he parse tesla_bio.md -t general/biography_graph -l en
```python
{
"entities": [
- {"name": "Nikola Tesla", "type": "person"},
- {"name": "AC Motor", "type": "invention"}
+ {"name": "苏轼", "type": "人物"},
+ {"name": "《念奴娇·赤壁怀古》", "type": "作品"}
],
"relations": [
{
- "source": "Nikola Tesla",
- "target": "AC Motor",
- "type": "invented",
- "time": "1888"
+ "source": "苏轼",
+ "target": "《念奴娇·赤壁怀古》",
+ "type": "创作",
+ "time": "1082"
}
]
}
@@ -246,11 +246,13 @@ print(result.data)
ka = Template.create("general/biography_graph", "en")
result = ka.parse(biography_text)
-# 可视化生平事件
+# 构建索引以支持交互功能
+result.build_index()
+
+# 可视化生平事件(支持搜索/对话功能)
result.show()
# 提问
-result.build_index()
response = result.chat("主要成就是什么?")
print(response.content)
```
@@ -262,10 +264,10 @@ ka = Template.create("general/concept_graph", "en")
result = ka.parse(paper_text)
# 获取概念图
-for node in result.data.nodes:
+for node in result.nodes:
print(f"概念: {node.name}")
-for edge in result.data.edges:
+for edge in result.edges:
print(f"{edge.source} → {edge.target}")
```
diff --git a/docs/zh/templates/industry.md b/docs/zh/templates/industry.md
index b714eaa..cc102d1 100644
--- a/docs/zh/templates/industry.md
+++ b/docs/zh/templates/industry.md
@@ -41,7 +41,10 @@ he parse system_diagram.md -t industry/equipment_topology -l en
**可视化:**
```python
-result.show() # 显示设备网络
+# 构建索引以支持可视化中的交互式搜索/对话
+result.build_index()
+
+result.show() # 显示带有交互功能的设备网络
```
---
@@ -202,11 +205,13 @@ for hazard in hazards:
ka = Template.create("industry/operation_flow", "en")
procedure = ka.parse(sop_document)
-# 可视化工作流
+# 构建索引以支持交互式可视化
+procedure.build_index()
+
+# 可视化工作流(支持搜索/对话功能)
procedure.show()
# 搜索特定步骤
-procedure.build_index()
results = procedure.search("启动序列")
```
diff --git a/docs/zh/templates/medicine.md b/docs/zh/templates/medicine.md
index 660c298..e012a15 100644
--- a/docs/zh/templates/medicine.md
+++ b/docs/zh/templates/medicine.md
@@ -191,11 +191,13 @@ for i in interactions:
ka = Template.create("medicine/anatomy_graph", "en")
anatomy = ka.parse(textbook_chapter)
-# 可视化
+# 构建索引以支持交互式可视化
+anatomy.build_index()
+
+# 可视化(支持搜索/对话功能)
anatomy.show()
# 搜索
-anatomy.build_index()
results = anatomy.search("手部神经")
```
diff --git a/docs/zh/tutorials/knowledge-base/step1-setup.md b/docs/zh/tutorials/knowledge-base/step1-setup.md
index e7529d3..8cdfa26 100644
--- a/docs/zh/tutorials/knowledge-base/step1-setup.md
+++ b/docs/zh/tutorials/knowledge-base/step1-setup.md
@@ -214,8 +214,8 @@ test_text = "This is a test document for template validation."
result = ka.parse(test_text)
print(f"模板: {config['template']}")
-print(f"节点: {len(result.data.nodes)}")
-print(f"边: {len(result.data.edges)}")
+print(f"节点: {len(result.nodes)}")
+print(f"边: {len(result.edges)}")
```
---
diff --git a/docs/zh/tutorials/research-assistant/step1-extract.md b/docs/zh/tutorials/research-assistant/step1-extract.md
index b44641f..7bb1973 100644
--- a/docs/zh/tutorials/research-assistant/step1-extract.md
+++ b/docs/zh/tutorials/research-assistant/step1-extract.md
@@ -102,12 +102,12 @@ def main():
# 显示结果
print(f"\n提取完成:")
- print(f" 节点: {len(result.data.nodes)}")
- print(f" 边: {len(result.data.edges)}")
+ print(f" 节点: {len(result.nodes)}")
+ print(f" 边: {len(result.edges)}")
# 显示样例节点
print("\n样例概念:")
- for node in result.data.nodes[:5]:
+ for node in result.nodes[:5]:
print(f" - {node.name} ({node.type})")
# 保存
diff --git a/hyperextract/methods/typical/kg_gen.py b/hyperextract/methods/typical/kg_gen.py
index 2cc3376..1f3b28a 100644
--- a/hyperextract/methods/typical/kg_gen.py
+++ b/hyperextract/methods/typical/kg_gen.py
@@ -169,7 +169,7 @@ class KG_Gen(AutoGraph[NodeSchema, EdgeSchema]):
self,
graph_data: AutoGraphSchema[NodeSchema, EdgeSchema],
threshold: float = 0.9,
- ):
+ ) -> AutoGraphSchema[NodeSchema, EdgeSchema]:
"""Internal helper to apply SemHash deduplication on a graph data object.
Args:
diff --git a/hyperextract/templates/presets/finance/event_timeline.yaml b/hyperextract/templates/presets/finance/event_timeline.yaml
index a0d2315..0e81d11 100644
--- a/hyperextract/templates/presets/finance/event_timeline.yaml
+++ b/hyperextract/templates/presets/finance/event_timeline.yaml
@@ -26,8 +26,8 @@ output:
- name: entity_type
type: str
description:
- zh: '实体类型:公司/事件/公告类型'
- en: 'Entity type: company/event/announcement type'
+ zh: '实体类型:公司/事件/公告/产品发布/并购重组/融资/诉讼/监管处罚等'
+ en: 'Entity type: company/event/announcement/product_launch/m_a/financing/litigation/regulatory_penalty, etc.'
required: true
relations:
description:
@@ -49,14 +49,14 @@ output:
- name: type
type: str
description:
- zh: '关系类型:先于/导致/触发'
- en: 'Relation type: precedes/causes/triggers'
+ zh: '关系类型:先于/导致/触发/回应/依据等'
+ en: 'Relation type: precedes/causes/triggers/responds_to/based_on, etc.'
required: true
- name: time
type: str
description:
- zh: '事件日期'
- en: 'Event date'
+ zh: '事件发生时间。例如:2024-01-15/2024年第一季度/公告发布日等'
+ en: 'Event occurrence time. Examples: 2024-01-15/Q1_2024/announcement_date, etc.'
required: true
- name: description
type: str
diff --git a/hyperextract/templates/presets/finance/ownership_graph.yaml b/hyperextract/templates/presets/finance/ownership_graph.yaml
index ef5645b..d486b18 100644
--- a/hyperextract/templates/presets/finance/ownership_graph.yaml
+++ b/hyperextract/templates/presets/finance/ownership_graph.yaml
@@ -26,8 +26,8 @@ output:
- name: shareholder_type
type: str
description:
- zh: '股东类型:机构投资者/个人/关联方/上市公司'
- en: 'Shareholder type: institutional investor/individual/related party/public company'
+ zh: '股东类型:机构投资者/个人/关联方/上市公司等'
+ en: 'Shareholder type: institutional investor/individual/related party/public company, etc.'
required: true
- name: description
type: str
@@ -55,8 +55,8 @@ output:
- name: type
type: str
description:
- zh: '关系类型:控制/属于/持股'
- en: 'Relation type: controls/belongs_to/holds_shares'
+ zh: '关系类型:控制/属于/持股/一致行动等'
+ en: 'Relation type: controls/belongs_to/holds_shares/acting_in_concert, etc.'
required: true
- name: ownership_percentage
type: str
diff --git a/hyperextract/templates/presets/finance/risk_factor_set.yaml b/hyperextract/templates/presets/finance/risk_factor_set.yaml
index 095405f..671f4bd 100644
--- a/hyperextract/templates/presets/finance/risk_factor_set.yaml
+++ b/hyperextract/templates/presets/finance/risk_factor_set.yaml
@@ -22,14 +22,14 @@ output:
- name: category
type: str
description:
- zh: '风险类别:经营风险/财务风险/市场风险/法规风险'
- en: 'Risk category: operational/financial/market/regulatory'
+ zh: '风险类别:经营风险/财务风险/市场风险/法规风险/信用风险/操作风险/声誉风险等'
+ en: 'Risk category: operational/financial/market/regulatory/credit/operational/reputational, etc.'
required: true
- name: severity
type: str
description:
- zh: '严重程度:高/中/低'
- en: 'Severity: high/medium/low'
+ zh: '严重程度:高/中/低/极高/极低等'
+ en: 'Severity: high/medium/low/critical/minimal, etc.'
required: true
guideline:
diff --git a/hyperextract/templates/presets/general/base_graph.yaml b/hyperextract/templates/presets/general/base_graph.yaml
index da49c7e..e6a144c 100644
--- a/hyperextract/templates/presets/general/base_graph.yaml
+++ b/hyperextract/templates/presets/general/base_graph.yaml
@@ -25,8 +25,8 @@ output:
- name: type
type: str
description:
- zh: '实体类型,如人物、地点、组织、物品、概念、事件、制度、技术等。'
- en: 'Entity type, such as person, location, organization, object, concept, event, institution, technology, etc.'
+ zh: '实体类型。例如:人物/地点/组织/物品/概念/事件/制度/技术/产品/服务等'
+ en: 'Entity type. Examples: person/location/organization/object/concept/event/institution/technology/product/service, etc.'
- name: description
type: str
description:
@@ -51,8 +51,8 @@ output:
- name: type
type: str
description:
- zh: '关系类型,使用简洁明确的语义词概括两个实体之间的连接方式。'
- en: 'Relation type, using concise and clear semantic words to describe the connection between two entities.'
+ zh: '关系类型,使用简洁明确的语义词概括两个实体之间的连接方式。例如:创建/属于/位于/使用/影响/导致/参与/拥有/相关等'
+ en: 'Relation type, using concise and clear semantic words to describe the connection between two entities. Examples: created/belongs_to/located_at/uses/affects/causes/participates_in/owns/related_to, etc.'
- name: description
type: str
description:
diff --git a/hyperextract/templates/presets/general/base_hypergraph.yaml b/hyperextract/templates/presets/general/base_hypergraph.yaml
index 94b613a..c3d88c8 100644
--- a/hyperextract/templates/presets/general/base_hypergraph.yaml
+++ b/hyperextract/templates/presets/general/base_hypergraph.yaml
@@ -25,8 +25,8 @@ output:
- name: type
type: str
description:
- zh: '节点类型,如实体、概念、地点、组织、物品等。'
- en: 'Node type, such as entity, concept, location, organization, object, etc.'
+ zh: '节点类型。例如:实体/概念/地点/组织/物品/人物/事件等'
+ en: 'Node type. Examples: entity/concept/location/organization/object/person/event, etc.'
- name: description
type: str
description:
@@ -46,8 +46,8 @@ output:
- name: type
type: str
description:
- zh: '超边的类型,如事件、会议、合作、冲突、交易、协议等。'
- en: 'Type of the hyperedge, such as event, meeting, cooperation, conflict, transaction, agreement, etc.'
+ zh: '超边的类型。例如:会议/合作/冲突/交易/协议/比赛/选举/诉讼/并购/发布会等'
+ en: 'Type of the hyperedge. Examples: meeting/collaboration/conflict/transaction/agreement/competition/election/lawsuit/acquisition/launch_event, etc.'
- name: participants
type: list
description:
diff --git a/hyperextract/templates/presets/general/base_list.yaml b/hyperextract/templates/presets/general/base_list.yaml
index bf2daab..5c0a48a 100644
--- a/hyperextract/templates/presets/general/base_list.yaml
+++ b/hyperextract/templates/presets/general/base_list.yaml
@@ -21,8 +21,8 @@ output:
- name: type
type: str
description:
- zh: '列表项的类型或分类标签。'
- en: 'Type or category label of the list item.'
+ zh: '列表项的类型或分类标签。例如:技术栈/功能模块/风险项/依赖项/约束条件/里程碑/交付物等'
+ en: 'Type or category label of the list item. Examples: tech_stack/feature_module/risk_item/dependency/constraint/milestone/deliverable, etc.'
required: false
- name: description
type: str
diff --git a/hyperextract/templates/presets/general/base_model.yaml b/hyperextract/templates/presets/general/base_model.yaml
index f388978..277732b 100644
--- a/hyperextract/templates/presets/general/base_model.yaml
+++ b/hyperextract/templates/presets/general/base_model.yaml
@@ -27,8 +27,8 @@ output:
- name: type
type: str
description:
- zh: '对象的类型或分类标签。'
- en: 'Type or category label of the object.'
+ zh: '对象的类型或分类标签。例如:用户信息/产品规格/配置参数/元数据/摘要信息等'
+ en: 'Type or category label of the object. Examples: user_info/product_spec/config_param/metadata/summary, etc.'
required: false
guideline:
diff --git a/hyperextract/templates/presets/general/base_set.yaml b/hyperextract/templates/presets/general/base_set.yaml
index bb5a17b..80c566f 100644
--- a/hyperextract/templates/presets/general/base_set.yaml
+++ b/hyperextract/templates/presets/general/base_set.yaml
@@ -21,8 +21,8 @@ output:
- name: type
type: str
description:
- zh: '实体类型,如人物、机构、地点、物品、概念、事件、其他。'
- en: 'Entity type, such as person, organization, location, object, concept, event, other.'
+ zh: '实体类型。例如:人物/机构/地点/物品/概念/事件/产品/服务/其他等'
+ en: 'Entity type. Examples: person/organization/location/object/concept/event/product/service/other, etc.'
- name: description
type: str
description:
diff --git a/hyperextract/templates/presets/general/base_spatial_graph.yaml b/hyperextract/templates/presets/general/base_spatial_graph.yaml
index 99534c8..7531719 100644
--- a/hyperextract/templates/presets/general/base_spatial_graph.yaml
+++ b/hyperextract/templates/presets/general/base_spatial_graph.yaml
@@ -25,8 +25,8 @@ output:
- name: type
type: str
description:
- zh: '实体类型,如人物、地点、组织、物品、概念、事件、制度等。'
- en: 'Entity type, such as person, location, organization, object, concept, event, institution, etc.'
+ zh: '实体类型。例如:人物/地点/组织/物品/概念/事件/制度/技术/产品/服务等'
+ en: 'Entity type. Examples: person/location/organization/object/concept/event/institution/technology/product/service, etc.'
- name: description
type: str
description:
@@ -51,13 +51,13 @@ output:
- name: type
type: str
description:
- zh: '关系类型,用简洁词语概括两个实体之间的连接方式。'
- en: 'Relation type, concisely describing the connection between two entities.'
+ zh: '关系类型,用简洁词语概括两个实体之间的连接方式。例如:创建/属于/位于/使用/影响/导致/参与/拥有/相关等'
+ en: 'Relation type, concisely describing the connection between two entities. Examples: created/belongs_to/located_at/uses/affects/causes/participates_in/owns/related_to, etc.'
- name: location
type: str
description:
- zh: '关系对应的位置信息;无明确位置时可留空。'
- en: 'Location information associated with the relation; can be left empty if no explicit location is available.'
+ zh: '关系对应的位置信息;无明确位置时可留空。例如:北京市/会议室A/华东地区/现场等'
+ en: 'Location information associated with the relation; can be left empty if no explicit location is available. Examples: Beijing/c Meeting_Room_A/East_China_region/on_site, etc.'
required: false
- name: description
type: str
diff --git a/hyperextract/templates/presets/general/base_spatio_temporal_graph.yaml b/hyperextract/templates/presets/general/base_spatio_temporal_graph.yaml
index 0f87f9d..e2924ae 100644
--- a/hyperextract/templates/presets/general/base_spatio_temporal_graph.yaml
+++ b/hyperextract/templates/presets/general/base_spatio_temporal_graph.yaml
@@ -25,8 +25,8 @@ output:
- name: type
type: str
description:
- zh: '实体类型,如人物、地点、组织、物品、概念、事件、制度等。'
- en: 'Entity type, such as person, location, organization, object, concept, event, institution, etc.'
+ zh: '实体类型。例如:人物/地点/组织/物品/概念/事件/制度/技术/产品/服务等'
+ en: 'Entity type. Examples: person/location/organization/object/concept/event/institution/technology/product/service, etc.'
- name: description
type: str
description:
@@ -51,19 +51,19 @@ output:
- name: type
type: str
description:
- zh: '关系类型,用简洁词语概括两个实体之间的连接方式。'
- en: 'Relation type, concisely describing the connection between two entities.'
+ zh: '关系类型,用简洁词语概括两个实体之间的连接方式。例如:创建/属于/位于/使用/影响/导致/参与/拥有/相关等'
+ en: 'Relation type, concisely describing the connection between two entities. Examples: created/belongs_to/located_at/uses/affects/causes/participates_in/owns/related_to, etc.'
- name: time
type: str
description:
- zh: '关系对应的时间;无明确时间时可留空。'
- en: 'Time associated with the relation; can be left empty if no explicit time is available.'
+ zh: '关系对应的时间;无明确时间时可留空。例如:2024年/20岁时/任职期间/2020年代初等'
+ en: 'Time associated with the relation; can be left empty if no explicit time is available. Examples: 2024/at_age_20/during_tenure/early_2020s, etc.'
required: false
- name: location
type: str
description:
- zh: '关系对应的位置信息;无明确位置时可留空。'
- en: 'Location information associated with the relation; can be left empty if no explicit location is available.'
+ zh: '关系对应的位置信息;无明确位置时可留空。例如:北京市/会议室A/华东地区/现场等'
+ en: 'Location information associated with the relation; can be left empty if no explicit location is available. Examples: Beijing_Meeting_Room_A/East_China_region/on_site, etc.'
required: false
- name: description
type: str
diff --git a/hyperextract/templates/presets/general/base_temporal_graph.yaml b/hyperextract/templates/presets/general/base_temporal_graph.yaml
index 7e97825..0b9bf77 100644
--- a/hyperextract/templates/presets/general/base_temporal_graph.yaml
+++ b/hyperextract/templates/presets/general/base_temporal_graph.yaml
@@ -25,8 +25,8 @@ output:
- name: type
type: str
description:
- zh: '实体类型,如人物、地点、组织、物品、概念、事件、制度等。'
- en: 'Entity type, such as person, location, organization, object, concept, event, institution, etc.'
+ zh: '实体类型。例如:人物/地点/组织/物品/概念/事件/制度/技术/产品/服务等'
+ en: 'Entity type. Examples: person/location/organization/object/concept/event/institution/technology/product/service, etc.'
- name: description
type: str
description:
@@ -51,13 +51,13 @@ output:
- name: type
type: str
description:
- zh: '关系类型,用简洁词语概括两个实体之间的连接方式。'
- en: 'Relation type, concisely describing the connection between two entities.'
+ zh: '关系类型,用简洁词语概括两个实体之间的连接方式。例如:创建/属于/位于/使用/影响/导致/参与/拥有/相关/先于/后续等'
+ en: 'Relation type, concisely describing the connection between two entities. Examples: created/belongs_to/located_at/uses/affects/causes/participates_in/owns/related_to/precedes/follows, etc.'
- name: time
type: str
description:
- zh: '关系对应的时间;无明确时间时可留空。'
- en: 'Time associated with the relation; can be left empty if no explicit time is available.'
+ zh: '关系对应的时间;无明确时间时可留空。例如:2024年/20岁时/任职期间/2020年代初等'
+ en: 'Time associated with the relation; can be left empty if no explicit time is available. Examples: 2024/at_age_20/during_tenure/early_2020s, etc.'
required: false
- name: description
type: str
diff --git a/hyperextract/templates/presets/general/biography_graph.yaml b/hyperextract/templates/presets/general/biography_graph.yaml
index ae74558..f878d0f 100644
--- a/hyperextract/templates/presets/general/biography_graph.yaml
+++ b/hyperextract/templates/presets/general/biography_graph.yaml
@@ -26,8 +26,8 @@ output:
- name: type
type: str
description:
- zh: '实体类型,如人物、地点、组织、作品、事件、成就等'
- en: 'Entity type, such as person, location, organization, work, event, achievement, etc.'
+ zh: '实体类型,如:人物/地点/组织/作品/事件/成就/荣誉/职位等'
+ en: 'Entity type, e.g., person/location/organization/work/event/achievement/honor/position, etc.'
required: true
- name: description
type: str
@@ -55,14 +55,14 @@ output:
- name: type
type: str
description:
- zh: '关系类型,用简洁词语概括两个实体之间的连接方式'
- en: 'Relation type, concisely describing the connection between two entities'
+ zh: '关系类型,用简洁词语概括两个实体之间的连接方式。例如:师从/任职于/发明/创作/获得荣誉/亲属关系/合作关系/影响等'
+ en: 'Relation type, concisely describing the connection between two entities. Examples: mentored_by/employed_by/invented/created/received_honor/related_to/collaborated_with/influenced, etc.'
required: true
- name: time
type: str
description:
- zh: '关系对应的时间;无明确时间时可留空'
- en: 'Time associated with the relation; can be left empty if no explicit time'
+ zh: '关系对应的时间;无明确时间时可留空。例如:1985年/20岁时/任职期间/2020年代初等'
+ en: 'Time associated with the relation; can be left empty if no explicit time. Examples: 1985/at_age_20/during_tenure/early_2020s, etc.'
required: false
- name: description
type: str
@@ -123,4 +123,4 @@ identifiers:
display:
entity_label: '{name}'
- relation_label: '{type}'
+ relation_label: '{type}@{time}'
diff --git a/hyperextract/templates/presets/general/concept_graph.yaml b/hyperextract/templates/presets/general/concept_graph.yaml
index 2793b6c..9d2999c 100644
--- a/hyperextract/templates/presets/general/concept_graph.yaml
+++ b/hyperextract/templates/presets/general/concept_graph.yaml
@@ -26,8 +26,8 @@ output:
- name: type
type: str
description:
- zh: '概念类型:实体/抽象概念/过程/关系'
- en: 'Concept type: entity/abstract/process/relation'
+ zh: '概念类型:实体/抽象概念/过程/关系等'
+ en: 'Concept type: entity/abstract/process/relation, etc.'
required: true
- name: definition
type: str
@@ -55,8 +55,8 @@ output:
- name: type
type: str
description:
- zh: '关系类型,用简洁词语概括两个概念之间的连接方式'
- en: 'Relation type, concisely describing the connection between two concepts'
+ zh: '关系类型,用简洁词语概括两个概念之间的连接方式。例如:属于/包含/导致/相关/对立/示例/扩展等'
+ en: 'Relation type, concisely describing the connection between two concepts. Examples: is_a/part_of/causes/related_to/opposite/example_of/extends, etc.'
required: true
- name: description
type: str
diff --git a/hyperextract/templates/presets/general/doc_structure.yaml b/hyperextract/templates/presets/general/doc_structure.yaml
index 5fcd66c..b427147 100644
--- a/hyperextract/templates/presets/general/doc_structure.yaml
+++ b/hyperextract/templates/presets/general/doc_structure.yaml
@@ -26,8 +26,8 @@ output:
- name: node_type
type: str
description:
- zh: '节点类型:章/节/小节/段落/代码/表格/图表'
- en: 'Node type: chapter/section/subsection/paragraph/code/table/figure'
+ zh: '节点类型:章/节/小节/段落/代码块/表格/图表/附录/参考文献等'
+ en: 'Node type: chapter/section/subsection/paragraph/code_block/table/figure/appendix/reference, etc.'
required: true
- name: level
type: int
@@ -61,8 +61,8 @@ output:
- name: type
type: str
description:
- zh: '关系类型,用简洁词语概括两个节点之间的连接方式'
- en: 'Relation type, concisely describing the connection between two nodes'
+ zh: '关系类型,用简洁词语概括两个节点之间的连接方式。例如:包含/引用/前置/后续/相关/解释等'
+ en: 'Relation type, concisely describing the connection between two nodes. Examples: contains/references/precedes/follows/relates_to/explains, etc.'
required: true
- name: reference_context
type: str
diff --git a/hyperextract/templates/presets/general/workflow_graph.yaml b/hyperextract/templates/presets/general/workflow_graph.yaml
index 2e897eb..6da97ca 100644
--- a/hyperextract/templates/presets/general/workflow_graph.yaml
+++ b/hyperextract/templates/presets/general/workflow_graph.yaml
@@ -26,8 +26,8 @@ output:
- name: type
type: str
description:
- zh: '步骤类型:调用技能/普通步骤/条件判断/分支节点'
- en: 'Step type: skill/step/condition/branch'
+ zh: '步骤类型:调用技能/普通步骤/条件判断/分支节点/输入节点/输出节点/循环节点等'
+ en: 'Step type: skill_call/process_step/condition/branch_node/input_node/output_node/loop_node, etc.'
required: true
- name: description
type: str
@@ -67,8 +67,8 @@ output:
- name: type
type: str
description:
- zh: '关系类型,用简洁词语概括两个步骤之间的连接方式'
- en: 'Relation type, concisely describing the connection between two steps'
+ zh: '关系类型,用简洁词语概括两个步骤之间的连接方式。例如:下一步/条件为真/条件为假/输入/输出/依赖/触发等'
+ en: 'Relation type, concisely describing the connection between two steps. Examples: next/if_true/if_false/input_to/output_from/depends_on/triggers, etc.'
required: true
- name: condition
type: str
diff --git a/hyperextract/templates/presets/industry/emergency_response.yaml b/hyperextract/templates/presets/industry/emergency_response.yaml
index ea35599..6d2784a 100644
--- a/hyperextract/templates/presets/industry/emergency_response.yaml
+++ b/hyperextract/templates/presets/industry/emergency_response.yaml
@@ -26,8 +26,8 @@ output:
- name: type
type: str
description:
- zh: '要素类型:事故场景/响应动作/资源'
- en: 'Element type: accident scenario/response action/resource'
+ zh: '要素类型:事故场景/响应动作/资源/责任人/应急设备等'
+ en: 'Element type: accident_scenario/response_action/resource/responsible_person/emergency_equipment, etc.'
required: true
- name: description
type: str
@@ -55,8 +55,8 @@ output:
- name: type
type: str
description:
- zh: '关系类型:触发/执行/需要'
- en: 'Relation type: triggers/executed_by/requires'
+ zh: '关系类型:触发/执行/需要/通知/协调/上报等'
+ en: 'Relation type: triggers/executed_by/requires/notifies/coordinates/reports_to, etc.'
required: true
- name: responsible_role
type: str
diff --git a/hyperextract/templates/presets/industry/equipment_topology.yaml b/hyperextract/templates/presets/industry/equipment_topology.yaml
index 2c14d2f..1ea0c70 100644
--- a/hyperextract/templates/presets/industry/equipment_topology.yaml
+++ b/hyperextract/templates/presets/industry/equipment_topology.yaml
@@ -26,14 +26,14 @@ output:
- name: type
type: str
description:
- zh: '设备类型'
- en: 'Equipment type'
+ zh: '设备类型。例如:主机/从机/传感器/执行器/控制器/网络设备/电源设备等'
+ en: 'Equipment type. Examples: master/slave/sensor/actuator/controller/network_device/power_device, etc.'
required: true
- name: location
type: str
description:
- zh: '安装位置'
- en: 'Installation location'
+ zh: '安装位置。例如:机柜A/控制室/现场/室外/楼顶等'
+ en: 'Installation location. Examples: cabinet_A/control_room/site/outdoor/rooftop, etc.'
required: false
- name: specifications
type: str
@@ -61,8 +61,8 @@ output:
- name: type
type: str
description:
- zh: '关系类型:连接/位于/包含'
- en: 'Relation type: connected_to/located_in/contains'
+ zh: '关系类型:连接/位于/包含/控制/供电/通信等'
+ en: 'Relation type: connected_to/located_in/contains/controls/powers/communicates_with, etc.'
required: true
guideline:
diff --git a/hyperextract/templates/presets/industry/failure_case.yaml b/hyperextract/templates/presets/industry/failure_case.yaml
index fb0d0f4..0b8386f 100644
--- a/hyperextract/templates/presets/industry/failure_case.yaml
+++ b/hyperextract/templates/presets/industry/failure_case.yaml
@@ -26,8 +26,8 @@ output:
- name: type
type: str
description:
- zh: '要素类型:故障现象/原因/措施'
- en: 'Element type: phenomenon/cause/measure'
+ zh: '要素类型:故障现象/根本原因/直接原因/修复措施/预防措施等'
+ en: 'Element type: symptom/root_cause/direct_cause/repair_measure/preventive_measure, etc.'
required: true
- name: description
type: str
@@ -55,8 +55,8 @@ output:
- name: type
type: str
description:
- zh: '关系类型:caused_by/resolved_by/prevented_by'
- en: 'Relation type: caused_by/resolved_by/prevented_by'
+ zh: '关系类型:由...导致/由...修复/由...预防/表现为/引起等'
+ en: 'Relation type: caused_by/resolved_by/prevented_by/manifests_as/leads_to, etc.'
required: true
- name: lesson
type: str
diff --git a/hyperextract/templates/presets/industry/operation_flow.yaml b/hyperextract/templates/presets/industry/operation_flow.yaml
index 85a27ad..2ec6942 100644
--- a/hyperextract/templates/presets/industry/operation_flow.yaml
+++ b/hyperextract/templates/presets/industry/operation_flow.yaml
@@ -26,8 +26,8 @@ output:
- name: type
type: str
description:
- zh: '步骤类型:动作/检查/切换'
- en: 'Step type: action/inspection/switch'
+ zh: '步骤类型:动作/检查/切换/确认步骤/异常处理等'
+ en: 'Step type: action/check/switch/confirmation_step/exception_handling, etc.'
required: true
- name: equipment_state
type: str
@@ -61,8 +61,8 @@ output:
- name: type
type: str
description:
- zh: '关系类型:后续/触发/导致'
- en: 'Relation type: next/triggers/results_in'
+ zh: '关系类型:后续/触发/导致/检查/条件为真/条件为假等'
+ en: 'Relation type: followed_by/triggers/leads_to/checks/if_true/if_false, etc.'
required: true
- name: description
type: str
diff --git a/hyperextract/templates/presets/industry/safety_control.yaml b/hyperextract/templates/presets/industry/safety_control.yaml
index b8cdc1a..5b5a601 100644
--- a/hyperextract/templates/presets/industry/safety_control.yaml
+++ b/hyperextract/templates/presets/industry/safety_control.yaml
@@ -26,8 +26,8 @@ output:
- name: type
type: str
description:
- zh: '要素类型:危险源/风险点/控制措施'
- en: 'Element type: hazard/risk point/control measure'
+ zh: '要素类型:危险源/风险点/控制措施/防护设备/应急预案/责任人等'
+ en: 'Element type: hazard/risk_point/control_measure/protective_equipment/emergency_plan/responsible_person, etc.'
required: true
- name: description
type: str
@@ -55,8 +55,8 @@ output:
- name: type
type: str
description:
- zh: '关系类型:导致/缓解/分配给'
- en: 'Relation type: causes/mitigates/assigned_to'
+ zh: '关系类型:导致/缓解/分配给/需要/预防/控制等'
+ en: 'Relation type: causes/mitigates/assigned_to/requires/prevents/controls, etc.'
required: true
- name: responsible_role
type: str
diff --git a/hyperextract/templates/presets/legal/case_citation.yaml b/hyperextract/templates/presets/legal/case_citation.yaml
index 936f0c4..f3f83d9 100644
--- a/hyperextract/templates/presets/legal/case_citation.yaml
+++ b/hyperextract/templates/presets/legal/case_citation.yaml
@@ -26,8 +26,8 @@ output:
- name: type
type: str
description:
- zh: '实体类型:案件/条款/法规'
- en: 'Entity type: case/provision/regulation'
+ zh: '实体类型:案件/条款/法规/司法解释/指导意见等'
+ en: 'Entity type: case/provision/regulation/judicial_interpretation/guiding_opinion, etc.'
required: true
- name: court
type: str
@@ -55,8 +55,8 @@ output:
- name: type
type: str
description:
- zh: '关系类型:引用/区分/推翻'
- en: 'Relation type: cites/distinguished_from/overruled_by'
+ zh: '关系类型:引用/区分/推翻/遵循/参照等'
+ en: 'Relation type: cites/distinguished_from/overruled_by/follows/refers_to, etc.'
required: true
- name: description
type: str
diff --git a/hyperextract/templates/presets/legal/case_fact_timeline.yaml b/hyperextract/templates/presets/legal/case_fact_timeline.yaml
index e994dfa..15b07a8 100644
--- a/hyperextract/templates/presets/legal/case_fact_timeline.yaml
+++ b/hyperextract/templates/presets/legal/case_fact_timeline.yaml
@@ -26,8 +26,8 @@ output:
- name: type
type: str
description:
- zh: '实体类型:事实/证据'
- en: 'Entity type: fact/evidence'
+ zh: '实体类型:事实/证据/证人/物证/书证/鉴定意见/勘验笔录等'
+ en: 'Entity type: fact/evidence/witness/physical_evidence/documentary_evidence/expert_opinion/inspection_record, etc.'
required: true
- name: description
type: str
@@ -55,14 +55,14 @@ output:
- name: type
type: str
description:
- zh: '关系类型:先于/证明/争议'
- en: 'Relation type: preceded_by/proves/disputes'
+ zh: '关系类型:先于/证明/争议/确认/否认/采信/排除等'
+ en: 'Relation type: precedes/proves/disputed/confirmed/denied/admitted/excluded, etc.'
required: true
- name: time
type: str
description:
- zh: '事实发生日期'
- en: 'Fact occurrence date'
+ zh: '事实发生日期。例如:2024-01-15/2024年1月/案发当日等'
+ en: 'Fact occurrence date. Examples: 2024-01-15/January_2024/day_of_incident, etc.'
required: false
- name: disputed
type: str
diff --git a/hyperextract/templates/presets/legal/contract_obligation.yaml b/hyperextract/templates/presets/legal/contract_obligation.yaml
index d7ef394..1bb03ed 100644
--- a/hyperextract/templates/presets/legal/contract_obligation.yaml
+++ b/hyperextract/templates/presets/legal/contract_obligation.yaml
@@ -26,8 +26,8 @@ output:
- name: type
type: str
description:
- zh: '实体类型:当事人/义务/条件/例外'
- en: 'Entity type: party/obligation/condition/exception'
+ zh: '实体类型:当事人/义务/权利/条件/例外/违约/赔偿等'
+ en: 'Entity type: party/obligation/right/condition/exception/breach/compensation, etc.'
required: true
relations:
description:
@@ -61,8 +61,8 @@ output:
- name: type
type: str
description:
- zh: '关系类型:must_perform/triggered_by/exempt_by'
- en: 'Relation type: must_perform/triggered_by/exempt_by'
+ zh: '关系类型:必须履行/由...触发/由...豁免/享有权利/承担义务等'
+ en: 'Relation type: must_perform/triggered_by/exempt_by/entitled_to/obligated_to, etc.'
required: true
guideline:
diff --git a/hyperextract/templates/presets/medicine/anatomy_graph.yaml b/hyperextract/templates/presets/medicine/anatomy_graph.yaml
index f881efc..315832b 100644
--- a/hyperextract/templates/presets/medicine/anatomy_graph.yaml
+++ b/hyperextract/templates/presets/medicine/anatomy_graph.yaml
@@ -26,14 +26,14 @@ output:
- name: level
type: str
description:
- zh: '结构层级:系统/器官/组织/细胞'
- en: 'Structure level: system/organ/tissue/cell'
+ zh: '结构层级:系统/器官/组织/细胞/亚细胞结构等'
+ en: 'Structure level: system/organ/tissue/cell/subcellular_structure, etc.'
required: true
- name: location
type: str
description:
- zh: '空间位置'
- en: 'Spatial location'
+ zh: '空间位置。例如:胸腔/腹腔/颅内/四肢/体表等'
+ en: 'Spatial location. Examples: thoracic_cavity/abdominal_cavity/cranial/extremities/body_surface, etc.'
required: false
relations:
description:
@@ -55,8 +55,8 @@ output:
- name: type
type: str
description:
- zh: '关系类型:包含/位于'
- en: 'Relation type: contains/located_in'
+ zh: '关系类型:包含/位于/连接/供应/支配等'
+ en: 'Relation type: contains/located_in/connects_to/supplies/innervates, etc.'
required: true
guideline:
diff --git a/hyperextract/templates/presets/medicine/drug_interaction.yaml b/hyperextract/templates/presets/medicine/drug_interaction.yaml
index 19ec754..2612fbf 100644
--- a/hyperextract/templates/presets/medicine/drug_interaction.yaml
+++ b/hyperextract/templates/presets/medicine/drug_interaction.yaml
@@ -55,8 +55,8 @@ output:
- name: type
type: str
description:
- zh: '相互作用类型:协同/拮抗/禁用'
- en: 'Interaction type: synergistic/antagonistic/contraindicated'
+ zh: '相互作用类型:协同/拮抗/禁用/增效/减效/毒性增强等'
+ en: 'Interaction type: synergistic/antagonistic/contraindicated/enhances/reduces/toxicity_increased, etc.'
required: true
- name: mechanism
type: str
diff --git a/hyperextract/templates/presets/medicine/hospital_timeline.yaml b/hyperextract/templates/presets/medicine/hospital_timeline.yaml
index 1257f42..a8f9f12 100644
--- a/hyperextract/templates/presets/medicine/hospital_timeline.yaml
+++ b/hyperextract/templates/presets/medicine/hospital_timeline.yaml
@@ -26,8 +26,8 @@ output:
- name: type
type: str
description:
- zh: '事件类型:入院/检查/手术/用药/会诊/出院'
- en: 'Event type: admission/examination/surgery/medication/consultation/discharge'
+ zh: '事件类型:入院/检查/手术/用药/会诊/转科/出院/诊断/治疗等'
+ en: 'Event type: admission/examination/surgery/medication/consultation/transfer/discharge/diagnosis/treatment, etc.'
required: true
- name: description
type: str
@@ -55,14 +55,14 @@ output:
- name: type
type: str
description:
- zh: '关系类型:后续/导致'
- en: 'Relation type: follows/results_in'
+ zh: '关系类型:后续/导致/触发/依据/准备等'
+ en: 'Relation type: followed_by/leads_to/triggers/based_on/prepares_for, etc.'
required: true
- name: time
type: str
description:
- zh: '事件发生日期'
- en: 'Event date'
+ zh: '事件发生日期。例如:2024-01-15/入院第3天/术后第1天等'
+ en: 'Event date. Examples: 2024-01-15/day_3_after_admission/day_1_after_surgery, etc.'
required: true
- name: performer
type: str
diff --git a/hyperextract/templates/presets/medicine/treatment_map.yaml b/hyperextract/templates/presets/medicine/treatment_map.yaml
index 4ace2af..5d41ef2 100644
--- a/hyperextract/templates/presets/medicine/treatment_map.yaml
+++ b/hyperextract/templates/presets/medicine/treatment_map.yaml
@@ -26,8 +26,8 @@ output:
- name: type
type: str
description:
- zh: '要素类型:患者特征/诊断/治疗/结果'
- en: 'Element type: patient characteristic/diagnosis/treatment/outcome'
+ zh: '要素类型:患者特征/诊断/症状/体征/治疗/药物/手术/结果/预后等'
+ en: 'Element type: patient_characteristic/diagnosis/symptom/sign/treatment/medication/surgery/outcome/prognosis, etc.'
required: true
- name: description
type: str
@@ -67,8 +67,8 @@ output:
- name: type
type: str
description:
- zh: '关系类型:适用于/禁忌联合'
- en: 'Relation type: indicates/contraindicated_with'
+ zh: '关系类型:适用于/禁忌联合/导致/改善/首选方案/替代方案等'
+ en: 'Relation type: indicated_for/contraindicated_with/leads_to/improves/first_line/alternative, etc.'
required: true
guideline:
diff --git a/hyperextract/templates/presets/tcm/formula_composition.yaml b/hyperextract/templates/presets/tcm/formula_composition.yaml
index 5bb4272..a531d26 100644
--- a/hyperextract/templates/presets/tcm/formula_composition.yaml
+++ b/hyperextract/templates/presets/tcm/formula_composition.yaml
@@ -26,8 +26,8 @@ output:
- name: type
type: str
description:
- zh: '实体类型:方剂/药材'
- en: 'Entity type: formula/herb'
+ zh: '实体类型:方剂/药材/剂型/功效/主治等'
+ en: 'Entity type: formula/herb/dosage_form/efficacy/indication, etc.'
required: true
- name: description
type: str
diff --git a/hyperextract/templates/presets/tcm/herb_relation.yaml b/hyperextract/templates/presets/tcm/herb_relation.yaml
index fcfbc93..3e4452d 100644
--- a/hyperextract/templates/presets/tcm/herb_relation.yaml
+++ b/hyperextract/templates/presets/tcm/herb_relation.yaml
@@ -49,8 +49,8 @@ output:
- name: type
type: str
description:
- zh: '配伍类型:相须/相使/相畏/相杀/相恶/相反'
- en: 'Compatibility type: synergistic/mutual-enhancing/mutual-repressing/toxicity-reducing/antagonistic/incompatible'
+ zh: '配伍类型:相须/相使/相畏/相杀/相恶/相反等'
+ en: 'Compatibility type: synergistic/mutual-enhancing/mutual-repressing/toxicity-reducing/antagonistic/incompatible, etc.'
required: true
- name: description
type: str
diff --git a/hyperextract/templates/presets/tcm/meridian_graph.yaml b/hyperextract/templates/presets/tcm/meridian_graph.yaml
index ebaee42..a0d90e8 100644
--- a/hyperextract/templates/presets/tcm/meridian_graph.yaml
+++ b/hyperextract/templates/presets/tcm/meridian_graph.yaml
@@ -26,14 +26,14 @@ output:
- name: type
type: str
description:
- zh: '实体类型:穴位/经脉'
- en: 'Entity type: acupoint/meridian'
+ zh: '实体类型:穴位/经脉/络脉/特定穴/经筋/皮部等'
+ en: 'Entity type: acupoint/meridian/collateral/specific_point/muscle_region/cutaneous_region, etc.'
required: true
- name: location
type: str
description:
- zh: '位置描述'
- en: 'Location description'
+ zh: '位置描述。例如:前臂桡侧/小腿外侧/足背等'
+ en: 'Location description. Examples: lateral_forearm/lateral_lower_leg/dorsum_of_foot, etc.'
required: false
relations:
description:
@@ -55,8 +55,8 @@ output:
- name: type
type: str
description:
- zh: '关系类型:located_on/flows_to'
- en: 'Relation type: located_on/flows_to'
+ zh: '关系类型:位于/流注/属络/交会/表里/同名等'
+ en: 'Relation type: located_on/flows_to/connects/intersects/interior_exterior/same_name, etc.'
required: true
guideline:
diff --git a/hyperextract/templates/presets/tcm/syndrome_reasoning.yaml b/hyperextract/templates/presets/tcm/syndrome_reasoning.yaml
index c3a7b6a..d9934a6 100644
--- a/hyperextract/templates/presets/tcm/syndrome_reasoning.yaml
+++ b/hyperextract/templates/presets/tcm/syndrome_reasoning.yaml
@@ -26,8 +26,8 @@ output:
- name: type
type: str
description:
- zh: '要素类型:症状/证候/治法/方剂。'
- en: 'Element type: symptom/syndrome/treatment/formula.'
+ zh: '要素类型:症状/证候/治法/方剂/病因/病位/病性等'
+ en: 'Element type: symptom/syndrome/treatment/formula/etiology/location/nature, etc.'
required: true
- name: description
type: str
@@ -49,8 +49,8 @@ output:
- name: reasoning_type
type: str
description:
- zh: '推理类型:辨证论治(根据证候确定治法)/ 随证加减(根据症状变化调整处方)。'
- en: 'Reasoning type: syndrome differentiation (determining treatment based on syndrome) / treatment adjustment (modifying formula based on symptom changes).'
+ zh: '推理类型:辨证论治/随证加减/方证对应/病机分析等'
+ en: 'Reasoning type: syndrome_differentiation/treatment_adjustment/formula_syndrome_correspondence/pathogenesis_analysis, etc.'
required: true
- name: symptoms
type: list
diff --git a/hyperextract/types/graph.py b/hyperextract/types/graph.py
index e984e7f..bc9ecbb 100644
--- a/hyperextract/types/graph.py
+++ b/hyperextract/types/graph.py
@@ -351,6 +351,8 @@ class AutoGraph(
prompt=self.prompt,
prompt_for_node_extraction=self.node_prompt,
prompt_for_edge_extraction=self.edge_prompt,
+ node_label_extractor=self._node_label_extractor,
+ edge_label_extractor=self._edge_label_extractor,
chunk_size=self.chunk_size,
chunk_overlap=self.chunk_overlap,
max_workers=self.max_workers,
diff --git a/hyperextract/types/hypergraph.py b/hyperextract/types/hypergraph.py
index e92dbd5..b0aaa15 100644
--- a/hyperextract/types/hypergraph.py
+++ b/hyperextract/types/hypergraph.py
@@ -361,6 +361,8 @@ class AutoHypergraph(
prompt=self.prompt,
prompt_for_node_extraction=self.node_prompt,
prompt_for_edge_extraction=self.edge_prompt,
+ node_label_extractor=self._node_label_extractor,
+ edge_label_extractor=self._edge_label_extractor,
chunk_size=self.chunk_size,
chunk_overlap=self.chunk_overlap,
max_workers=self.max_workers,
diff --git a/hyperextract/types/list.py b/hyperextract/types/list.py
index e523599..51fbcec 100644
--- a/hyperextract/types/list.py
+++ b/hyperextract/types/list.py
@@ -908,7 +908,8 @@ class AutoList(BaseAutoType[AutoListSchema[ItemSchema]], Generic[ItemSchema]):
"""Check if two items are equal.
Args:
- item1, item2: Items to compare.
+ item1: First item to compare.
+ item2: Second item to compare.
Returns:
True if items are equal, False otherwise.
diff --git a/hyperextract/types/model.py b/hyperextract/types/model.py
index 4c74566..f82835e 100644
--- a/hyperextract/types/model.py
+++ b/hyperextract/types/model.py
@@ -2,7 +2,7 @@
from pathlib import Path
from datetime import datetime
-from typing import List, Any, Type, Callable
+from typing import List, Any, Type, Callable, Union
from ontomem.merger import MergeStrategy, create_merger, BaseMerger
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.embeddings import Embeddings
@@ -361,7 +361,7 @@ class AutoModel(BaseAutoType[T]):
# ==================== Operators ====================
- def __add__(self, other):
+ def __add__(self, other: Union["AutoModel", "AutoList"]) -> "AutoList":
"""Operator overload for '+' to combine AutoModel instances into AutoList.
Supports multiple combination patterns:
diff --git a/hyperextract/types/set.py b/hyperextract/types/set.py
index 13f2095..c1e89c4 100644
--- a/hyperextract/types/set.py
+++ b/hyperextract/types/set.py
@@ -12,6 +12,7 @@ from typing import (
Generic,
Optional,
Callable,
+ Iterator,
TYPE_CHECKING,
)
from pathlib import Path
@@ -449,10 +450,10 @@ class AutoSet(BaseAutoType[AutoSetSchema[ItemSchema]], Generic[ItemSchema]):
"""Returns a user-friendly string representation."""
return f"AutoSet with {len(self)} unique {self.item_schema.__name__} items"
- def __iter__(self):
+ def __iter__(self) -> Iterator[ItemSchema]:
"""Enables iteration over all items in the set.
- Returns:
+ Yields:
Iterator over all unique items.
Examples:
@@ -557,9 +558,6 @@ class AutoSet(BaseAutoType[AutoSetSchema[ItemSchema]], Generic[ItemSchema]):
def pop(self) -> ItemSchema:
"""Removes and returns an arbitrary item from the set.
- Args:
- None
-
Returns:
The removed item.
diff --git a/hyperextract/types/spatial_graph.py b/hyperextract/types/spatial_graph.py
index a53ac3f..2d0424a 100644
--- a/hyperextract/types/spatial_graph.py
+++ b/hyperextract/types/spatial_graph.py
@@ -164,7 +164,7 @@ class AutoSpatialGraph(AutoGraph[NodeSchema, EdgeSchema]):
nodes_in_edge_extractor: Function to extract (source_key, target_key) from edge.
llm_client: LangChain BaseChatModel for extraction.
embedder: LangChain Embeddings for semantic operations.
- observation_time: Date context for relative time resolution (default: today in YYYY-MM-DD format).
+ observation_location: Location context for spatial resolution (default: "Unknown Location").
extraction_mode: "one_stage" or "two_stage" (default: "two_stage").
node_strategy_or_merger: Merge strategy for duplicate nodes (default: LLM.BALANCED).
edge_strategy_or_merger: Merge strategy for duplicate edges (default: LLM.BALANCED).
@@ -313,6 +313,8 @@ class AutoSpatialGraph(AutoGraph[NodeSchema, EdgeSchema]):
extraction_mode=self.extraction_mode,
node_strategy_or_merger=self.node_merger,
edge_strategy_or_merger=self.edge_merger,
+ node_label_extractor=self._node_label_extractor,
+ edge_label_extractor=self._edge_label_extractor,
chunk_size=self.chunk_size,
chunk_overlap=self.chunk_overlap,
max_workers=self.max_workers,
diff --git a/hyperextract/types/spatio_temporal_graph.py b/hyperextract/types/spatio_temporal_graph.py
index be2a15e..3f45692 100644
--- a/hyperextract/types/spatio_temporal_graph.py
+++ b/hyperextract/types/spatio_temporal_graph.py
@@ -334,6 +334,8 @@ class AutoSpatioTemporalGraph(AutoGraph[NodeSchema, EdgeSchema]):
extraction_mode=self.extraction_mode,
node_strategy_or_merger=self.node_merger,
edge_strategy_or_merger=self.edge_merger,
+ node_label_extractor=self._node_label_extractor,
+ edge_label_extractor=self._edge_label_extractor,
chunk_size=self.chunk_size,
chunk_overlap=self.chunk_overlap,
max_workers=self.max_workers,
diff --git a/hyperextract/types/temporal_graph.py b/hyperextract/types/temporal_graph.py
index 170dea7..0571c83 100644
--- a/hyperextract/types/temporal_graph.py
+++ b/hyperextract/types/temporal_graph.py
@@ -325,6 +325,8 @@ class AutoTemporalGraph(AutoGraph[NodeSchema, EdgeSchema]):
extraction_mode=self.extraction_mode,
node_strategy_or_merger=self.node_merger,
edge_strategy_or_merger=self.edge_merger,
+ node_label_extractor=self._node_label_extractor,
+ edge_label_extractor=self._edge_label_extractor,
chunk_size=self.chunk_size,
chunk_overlap=self.chunk_overlap,
max_workers=self.max_workers,
diff --git a/hyperextract/utils/template_engine/template.py b/hyperextract/utils/template_engine/template.py
index 92dd0e4..1e53323 100644
--- a/hyperextract/utils/template_engine/template.py
+++ b/hyperextract/utils/template_engine/template.py
@@ -3,7 +3,7 @@
Provides a clean API for searching and creating knowledge extraction templates.
"""
-from typing import Dict, Optional
+from typing import Dict, Optional, Any
from langchain_core.language_models import BaseChatModel
from langchain_core.embeddings import Embeddings
@@ -41,8 +41,8 @@ class Template:
language: Optional[str] = None,
llm_client: Optional[BaseChatModel] = None,
embedder: Optional[Embeddings] = None,
- **kwargs,
- ):
+ **kwargs: Any,
+ ) -> "BaseAutoType":
"""Create template instance.
Args:
diff --git a/mkdocs.yml b/mkdocs.yml
index 7c50716..8797727 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -86,6 +86,7 @@ plugins:
- python/guides/using-templates.md
- python/guides/choosing-methods.md
- python/guides/working-with-autotypes.md
+ - python/guides/custom-templates.md
- python/guides/search-and-chat.md
- python/guides/incremental-updates.md
- python/guides/saving-loading.md
@@ -114,6 +115,19 @@ plugins:
- resources/faq.md
- resources/troubleshooting.md
- resources/contributing.md
+ - Tutorials:
+ - tutorials/index.md
+ - Research Assistant:
+ - tutorials/research-assistant/index.md
+ - tutorials/research-assistant/step1-extract.md
+ - tutorials/research-assistant/step2-search.md
+ - tutorials/research-assistant/step3-chat.md
+ - Knowledge Base:
+ - tutorials/knowledge-base/index.md
+ - tutorials/knowledge-base/step1-setup.md
+ - tutorials/knowledge-base/step2-ingest.md
+ - tutorials/knowledge-base/step3-query.md
+ - Document Analysis: tutorials/document-analysis/index.md
- locale: zh
name: 中文
build: true