Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.
fix: thread GraphML --force through export_ka_graphml
Cursor Agent8e5bd71fe7a5
diff --git a/docs/en/cli/commands/export.md b/docs/en/cli/commands/export.mdindex eae88f8..eaec0ca 100644--- a/docs/en/cli/commands/export.md+++ b/docs/en/cli/commands/export.md@@ -146,6 +146,7 @@ he export graphml KA_PATH -o FILE.graphml| Option | Alias | Default | Description ||--------|-------|---------|-------------|| `--output` | `-o` | *(required)* | Output GraphML file |+| `--force` | `-f` | `false` | Overwrite an existing, non-empty GraphML file |### Description@@ -153,6 +154,7 @@ he export graphml KA_PATH -o FILE.graphml- **N-ary hyperedges.** An edge with 3+ incident nodes becomes `<hyperedge>` plus `<endpoint node="…"/>` in the same order `incident_nodes_extractor` returns. Endpoints are never sorted.- **Attributes.** Scalar fields from each node's / edge's `model_dump()` (`str` / `int` / `float` / `bool`) become GraphML `<data>` keys. Nested values are stringified. XML special characters (`& < > " '`) are escaped.- **Dangling edges.** An edge whose source or target node is missing (or a hyperedge with any missing endpoint) is skipped (with a warning), not treated as a crash.+- **0/1-endpoint edges.** Edges with fewer than two endpoints are skipped with a warning. This export does not invent a unary GraphML encoding.Supported Auto-Types: `AutoGraph`, `AutoHypergraph`, and temporal/spatial subclasses. Non-graph types (`AutoList`, `AutoSet`, `AutoModel`) are not supported.diff --git a/docs/en/cli/index.md b/docs/en/cli/index.mdindex 7b44d52..3455b0f 100644--- a/docs/en/cli/index.md+++ b/docs/en/cli/index.md@@ -33,7 +33,7 @@ he --version| `he parse` | Extract knowledge from documents | `-t` template, `-o` output, `-l` language, `--source` attribution || `he show` | Visualize knowledge graph | — || `he export obsidian` | Export to an Obsidian vault | `-o` output, `--name`, `-f` force |-| `he export graphml` | Export a pairwise graph to GraphML | `-o` output file |+| `he export graphml` | Export pairwise `<edge>` and N-ary `<hyperedge>` GraphML | `-o` output file, `-f` force || `he export csv` | Export nodes/edges as CSV tables | `-o` directory, `-f` force || `he search` | Semantic search in knowledge abstract | `-n` top-k results, `--source`, `--tag` || `he talk` | Chat with knowledge abstract | `-i` interactive, `-q` query |@@ -172,7 +172,7 @@ he show ./output/- **[`he talk`](commands/talk.md)** — Chat with knowledge abstract- **[`he info`](commands/info.md)** — View knowledge abstract statistics- **[`he export obsidian`](commands/export.md)** — Export to an Obsidian vault-- **[`he export graphml`](commands/export.md#he-export-graphml)** — Export a pairwise graph to GraphML+- **[`he export graphml`](commands/export.md#he-export-graphml)** — Export pairwise `<edge>` and N-ary `<hyperedge>` GraphML- **[`he export csv`](commands/export.md#he-export-csv)** — Export nodes/edges as CSV tables### Managementdiff --git a/docs/zh/cli/commands/export.md b/docs/zh/cli/commands/export.mdindex 5ad6c54..fa6aebd 100644--- a/docs/zh/cli/commands/export.md+++ b/docs/zh/cli/commands/export.md@@ -146,6 +146,7 @@ he export graphml KA_PATH -o FILE.graphml| 选项 | 别名 | 默认值 | 说明 ||--------|-------|---------|-------------|| `--output` | `-o` | *(必填)* | 输出 GraphML 文件 |+| `--force` | `-f` | `false` | 覆盖已存在的非空 GraphML 文件 |### 说明@@ -153,6 +154,7 @@ he export graphml KA_PATH -o FILE.graphml- **N 元超边。** 3 个及以上端点的边写成 `<hyperedge>`,并按 `incident_nodes_extractor` 的返回顺序写出 `<endpoint node="…"/>`。端点不会被排序。- **属性。** 节点 / 边 `model_dump()` 中的标量字段(`str` / `int` / `float` / `bool`)成为 GraphML `<data>` 键。嵌套值转为字符串。XML 特殊字符(`& < > " '`)会被转义。- **悬空边。** 源或目标节点缺失的二元边(或任一端点缺失的超边)会被跳过(并记录 warning),不会导致崩溃。+- **0/1 个端点的边。** 端点少于两个的边会被跳过并记录 warning。本导出不会发明一元 GraphML 编码。支持的 Auto-Type:`AutoGraph`、`AutoHypergraph` 及其时空子类。非图谱类型(`AutoList`、`AutoSet`、`AutoModel`)不支持。diff --git a/docs/zh/cli/index.md b/docs/zh/cli/index.mdindex e8b2b64..04d1b71 100644--- a/docs/zh/cli/index.md+++ b/docs/zh/cli/index.md@@ -33,7 +33,7 @@ he --version| `he parse` | 从文档提取知识 | `-t` 模板, `-o` 输出, `-l` 语言, `--source` 来源标注 || `he show` | 可视化知识图谱 | — || `he export obsidian` | 导出为 Obsidian 知识库 | `-o` 输出, `--name`, `-f` 强制 |-| `he export graphml` | 将二元图导出为 GraphML | `-o` 输出文件 |+| `he export graphml` | 导出二元 `<edge>` 与 N 元 `<hyperedge>` GraphML | `-o` 输出文件, `-f` 强制 || `he export csv` | 将节点/边导出为 CSV 表 | `-o` 目录, `-f` 强制 || `he search` | 知识库语义搜索 | `-n` top-k 结果数, `--source`, `--tag` || `he talk` | 与知识库对话 | `-i` 交互模式, `-q` 查询 |@@ -172,7 +172,7 @@ he show ./output/- **[`he talk`](commands/talk.md)** — 与知识库对话- **[`he info`](commands/info.md)** — 查看知识库统计信息- **[`he export obsidian`](commands/export.md)** — 导出为 Obsidian 知识库-- **[`he export graphml`](commands/export.md#he-export-graphml)** — 将二元图导出为 GraphML+- **[`he export graphml`](commands/export.md#he-export-graphml)** — 导出二元 `<edge>` 与 N 元 `<hyperedge>` GraphML- **[`he export csv`](commands/export.md#he-export-csv)** — 将节点/边导出为 CSV 表### 管理diff --git a/hyperextract/cli/cli.py b/hyperextract/cli/cli.pyindex b31b13e..32578eb 100644--- a/hyperextract/cli/cli.py+++ b/hyperextract/cli/cli.py@@ -145,7 +145,7 @@ def main(),("he export graphml <ka_path> -o <file>",- "Export pairwise graph to GraphML",+ "pairwise <edge> + <hyperedge>",),("he export csv <ka_path> -o <dir>",@@ -591,6 +591,9 @@ def _load_graph_ka_for_export(ka_path: str):def export_graphml_cmd(ka_path: str = typer.Argument(..., help="Knowledge Abstract directory"),output: str = typer.Option(..., "--output", "-o", help="Output GraphML file"),+ force: bool = typer.Option(+ False, "--force", "-f", help="Overwrite an existing GraphML file"+ ),):"""Export a knowledge graph to GraphML.@@ -598,13 +601,25 @@ def export_graphml_cmd(or more endpoints are written as GraphML 1.0 `<hyperedge>` elements."""from hyperextract.utils.exporters import GraphMLHypergraphError+ from hyperextract.utils.exporters.common import resolve_export_filefrom hyperextract.utils.exporters.ka import GraphTypeError, export_ka_graphmllogger.info("command=export-graphml ka_path=%s output=%s", ka_path, output)- ka, _path, template = _load_graph_ka_for_export(ka_path)-output_path = Path(output)+ try:+ resolve_export_file(output_path, overwrite=force)+ except FileExistsError:+ console.print(+ "[red]Error:[/red] Output file already exists. "+ "Use --force / -f to overwrite it."+ )+ raise typer.Exit(1)+ except IsADirectoryError as e:+ console.print(f"[red]Error:[/red] {e}")+ raise typer.Exit(1)++ ka, _path, template = _load_graph_ka_for_export(ka_path)console.print(f"[blue]Knowledge Abstract:[/blue] {ka_path}")console.print(f"[blue]Template:[/blue] {template}")console.print(f"[blue]Output file:[/blue] {output}")@@ -612,13 +627,19 @@ def export_graphml_cmd(with console.status("[bold blue]Exporting to GraphML..."):try:- export_ka_graphml(ka, output_path)+ export_ka_graphml(ka, output_path, overwrite=force)except GraphTypeError as e:console.print(f"[red]Error:[/red] {e}")raise typer.Exit(1)except GraphMLHypergraphError as e:console.print(f"[red]Error:[/red] {e}")raise typer.Exit(1)+ except FileExistsError:+ console.print(+ "[red]Error:[/red] Output file already exists. "+ "Use --force / -f to overwrite it."+ )+ raise typer.Exit(1)except Exception as e:console.print(f"[red]Error during export:[/red] {e}")raise typer.Exit(1)diff --git a/hyperextract/mcp_server.py b/hyperextract/mcp_server.pyindex 313b43c..a232bf6 100644--- a/hyperextract/mcp_server.py+++ b/hyperextract/mcp_server.py@@ -221,12 +221,13 @@ def export_obsidian(return f"Exported {count} notes to {vault}"-def export_graphml(ka_path: str, output: str) -> str:+def export_graphml(ka_path: str, output: str, overwrite: bool = False) -> str:"""Export a knowledge abstract to GraphML.Args:ka_path: Path to the knowledge abstract directory.output: Destination ``.graphml`` file.+ overwrite: Overwrite an existing, non-empty GraphML file.Uses the same ``export_ka_graphml`` adapter as ``he export graphml``.Does not create, mutate, or delete the KA.@@ -236,11 +237,13 @@ def export_graphml(ka_path: str, output: str) -> str:ka = _load_ka(ka_path)try:- dest = export_ka_graphml(ka, output)+ dest = export_ka_graphml(ka, output, overwrite=overwrite)except GraphTypeError as e:return str(e)except GraphMLHypergraphError as e:return str(e)+ except FileExistsError as e:+ return f"{e} Pass overwrite=true to overwrite it."return f"Wrote GraphML to {dest}"diff --git a/hyperextract/utils/exporters/common.py b/hyperextract/utils/exporters/common.pyindex dc25947..905c89f 100644--- a/hyperextract/utils/exporters/common.py+++ b/hyperextract/utils/exporters/common.py@@ -141,8 +141,8 @@ def default_edge_id(def resolve_export_file(path: str | Path, *, overwrite: bool = False) -> Path:"""Resolve a file-export destination, optionally refusing overwrite.- GraphML CLI does not pass ``overwrite`` yet (#123 owns ``--force``).- JSON-LD / Cypher can reuse this helper after those PRs land.+ GraphML CLI ``--force`` and MCP ``overwrite`` map onto this flag.+ JSON-LD / Cypher can reuse the same helper after those PRs land."""dest = Path(path)if dest.exists() and dest.is_dir():diff --git a/hyperextract/utils/exporters/ka.py b/hyperextract/utils/exporters/ka.pyindex 86268cc..b272acd 100644--- a/hyperextract/utils/exporters/ka.py+++ b/hyperextract/utils/exporters/ka.py@@ -10,6 +10,7 @@ from __future__ import annotationsfrom pathlib import Pathfrom typing import Any+from .common import resolve_export_filefrom .csv_export import export_to_csvfrom .graphml import export_to_graphml@@ -37,9 +38,10 @@ def require_graph_ka(ka: Any) -> None:raise GraphTypeError(GRAPH_TYPE_ERROR)-def export_ka_graphml(ka: Any, dest: str | Path) -> Path:+def export_ka_graphml(ka: Any, dest: str | Path, *, overwrite: bool = False) -> Path:"""Export a loaded graph-family KA to GraphML."""require_graph_ka(ka)+ dest = resolve_export_file(dest, overwrite=overwrite)return export_to_graphml(ka.nodes,ka.edges,diff --git a/tests/cli/test_verbose.py b/tests/cli/test_verbose.pyindex dffaa27..3959448 100644--- a/tests/cli/test_verbose.py+++ b/tests/cli/test_verbose.py@@ -126,6 +126,8 @@ class TestCLINoVerboseFlag:assert "he tag" in result.outputassert "he remove" in result.outputassert "he clean" in result.output+ assert "hyperedge" in result.output+ assert "pairwise" in result.outputdef test_info_missing_ka_exits_with_error(self):"""he info <nonexistent> exits with error."""diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.pyindex 2d0ea23..d1cc725 100644--- a/tests/test_mcp_server.py+++ b/tests/test_mcp_server.py@@ -211,6 +211,19 @@ def test_export_graphml(monkeypatch, tmp_path):assert str(dest) in out+def test_export_graphml_requires_overwrite(monkeypatch, tmp_path):+ g = _graph_with_index()+ monkeypatch.setattr(mcp_server, "_load_ka", lambda p: g)+ dest = tmp_path / "out.graphml"+ dest.write_text("KEEP-ME", encoding="utf-8")+ out = mcp_server.export_graphml("x", str(dest))+ assert "overwrite" in out.lower()+ assert dest.read_text(encoding="utf-8") == "KEEP-ME"+ out = mcp_server.export_graphml("x", str(dest), overwrite=True)+ assert dest.read_text(encoding="utf-8") != "KEEP-ME"+ assert str(dest) in out++def test_export_csv(monkeypatch, tmp_path):g = _graph_with_index()monkeypatch.setattr(mcp_server, "_load_ka", lambda p: g)diff --git a/tests/utils/test_exporters.py b/tests/utils/test_exporters.pyindex 86e8c99..78508ec 100644--- a/tests/utils/test_exporters.py+++ b/tests/utils/test_exporters.py@@ -393,6 +393,16 @@ class TestCommonHelpers:export_ka_csv(FakeListKA(), tmp_path / "csv")assert str(exc.value) == GRAPH_TYPE_ERROR+ def test_export_ka_graphml_requires_overwrite(self, tmp_path):+ dest = tmp_path / "g.graphml"+ dest.write_text("KEEP", encoding="utf-8")+ fake = FakeGraphKA([Entity(name="A")], [])+ with pytest.raises(FileExistsError):+ export_ka_graphml(fake, dest)+ assert dest.read_text(encoding="utf-8") == "KEEP"+ export_ka_graphml(fake, dest, overwrite=True)+ assert dest.read_text(encoding="utf-8") != "KEEP"+class TestCLIExport:def test_graphml_writes_directed_edge(self, tmp_path):@@ -439,6 +449,43 @@ class TestCLIExport:assert "hyperedge" in xmlassert f'xmlns="{GRAPHML_NS}"' in xml+ def test_graphml_requires_force_for_existing_file(self, tmp_path):+ ka_dir = _ka_dir(tmp_path)+ dest = tmp_path / "out.graphml"+ dest.write_text("KEEP-ME", encoding="utf-8")+ fake = FakeGraphKA([Entity(name="A")], [])+ with (+ patch("hyperextract.cli.cli.validate_config"),+ patch(+ "hyperextract.cli.cli.get_template_from_ka", return_value=("t", "en")+ ),+ patch("hyperextract.cli.cli.Template.create", return_value=fake),+ ):+ result = runner.invoke(+ app, ["export", "graphml", str(ka_dir), "-o", str(dest)]+ )+ assert result.exit_code != 0+ assert "--force" in result.output or "-f" in result.output+ assert dest.read_text(encoding="utf-8") == "KEEP-ME"++ def test_graphml_force_overwrites_existing_file(self, tmp_path):+ ka_dir = _ka_dir(tmp_path)+ dest = tmp_path / "out.graphml"+ dest.write_text("KEEP-ME", encoding="utf-8")+ fake = FakeGraphKA([Entity(name="A")], [])+ with (+ patch("hyperextract.cli.cli.validate_config"),+ patch(+ "hyperextract.cli.cli.get_template_from_ka", return_value=("t", "en")+ ),+ patch("hyperextract.cli.cli.Template.create", return_value=fake),+ ):+ result = runner.invoke(+ app, ["export", "graphml", str(ka_dir), "-o", str(dest), "--force"]+ )+ assert result.exit_code == 0, result.output+ assert dest.read_text(encoding="utf-8") != "KEEP-ME"+def test_csv_writes_tables(self, tmp_path):ka_dir = _ka_dir(tmp_path)fake = FakeGraphKA(