Skip to content

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

Merge PR #141 with #144/#139: Cypher export via shared guard; update GRAPH_TYPE_ERROR message

yifanfeng977d3b78a475ee
diff --cc docs/en/cli/commands/export.md
index dfa15a6,778c11c..7f16680
--- a/docs/en/cli/commands/export.md
+++ b/docs/en/cli/commands/export.md
@@@ -2,7 -2,7 +2,7 @@@
Export a knowledge abstract to an [Obsidian](https://obsidian.md) vault — a folder of Markdown notes linked by `[[wikilinks]]`.
- `export` is a command group. Formats: `obsidian`, `graphml`, `jsonld`, `csv`.
-`export` is a command group. Formats: `obsidian`, `graphml`, `cypher`, `csv`.
++`export` is a command group. Formats: `obsidian`, `graphml`, `jsonld`, `cypher`, `csv`.
---
@@@ -167,30 -165,23 +167,41 @@@ he export graphml ./tesla_kb/ -o ./tesl
---
+## he export jsonld
+
+Export a knowledge graph to JSON-LD (stdlib `json`, no RDFLib). Binary edges are `@type: Edge` with `source` / `target`. Edges with three or more endpoints are `@type: Hyperedge` with an `endpoint` list in extractor order (never sorted). 0/1-endpoint or missing-endpoint edges are skipped with a warning, same as GraphML.
+ ## he export cypher
+
+ Export a Neo4j / Memgraph-compatible Cypher MERGE script (`cypher-shell < file.cypher`). Binary edges become relationships (`:REL`, or a legal `type`/`label` ident). Edges with three or more endpoints become `(:Hyperedge)` nodes plus `(n)-[:IN]->(h)` in extractor order — never a pairwise clique. 0/1-endpoint or missing-endpoint edges are skipped with a warning.
Existing non-empty output files require `--force` / `-f`.
### Synopsis
```bash
+he export jsonld KA_PATH -o FILE.jsonld [--force]
+```
+
+### Options
+
+| Option | Alias | Default | Description |
+|--------|-------|---------|-------------|
+| `--output` | `-o` | *(required)* | Output JSON-LD file |
+| `--force` | `-f` | off | Overwrite an existing non-empty file |
+
+### Examples
+
+```bash
+he export jsonld ./tesla_kb/ -o ./tesla.jsonld
+he export jsonld ./tesla_kb/ -o ./tesla.jsonld --force
+ he export cypher KA_PATH -o FILE.cypher [--force]
+ ```
+
+ ### Examples
+
+ ```bash
+ he export cypher ./tesla_kb/ -o ./tesla.cypher
+ he export cypher ./tesla_kb/ -o ./tesla.cypher --force
```
---
@@@ -250,7 -241,7 +261,12 @@@ The same capability is available on gra
```python
ka.export_obsidian("./tesla_vault/", vault_name="Tesla KB", overwrite=True)
- from hyperextract.utils.exporters import export_to_graphml, export_to_csv, export_to_jsonld
-from hyperextract.utils.exporters import export_to_graphml, export_to_csv, export_to_cypher
++from hyperextract.utils.exporters import (
++ export_to_graphml,
++ export_to_csv,
++ export_to_jsonld,
++ export_to_cypher,
++)
export_to_graphml(
ka.nodes,
@@@ -269,12 -260,12 +285,14 @@@ export_to_csv
overwrite=True,
)
+export_to_jsonld(
+ export_to_cypher(
ka.nodes,
ka.edges,
node_id_extractor=ka.node_key_extractor,
incident_nodes_extractor=ka.nodes_in_edge_extractor,
+ file_path="./tesla.jsonld",
+ file_path="./tesla.cypher",
)
```
diff --cc docs/en/cli/index.md
index 29b2877,d736df5..eb959f0
--- a/docs/en/cli/index.md
+++ b/docs/en/cli/index.md
@@@ -33,12 -33,8 +33,11 @@@ he --versio
| `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 |
- <<<<<<< HEAD
--| `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 jsonld` | Export pairwise edges and N-ary hyperedges to JSON-LD | `-o` output file, `-f` force |
+=======
- | `he export graphml` | Export pairwise `<edge>` and N-ary `<hyperedge>` GraphML | `-o` output file, `-f` force |
- >>>>>>> origin/main
+ | `he export cypher` | Export Neo4j-compatible MERGE (N-ary as Hyperedge nodes) | `-o` output file, `-f` force |
++>>>>>>> pr-141-src
| `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 |
@@@ -177,12 -173,8 +176,11 @@@ 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
- <<<<<<< HEAD
--- **[`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 jsonld`](commands/export.md#he-export-jsonld)** — Export pairwise edges and N-ary hyperedges to JSON-LD
+=======
- - **[`he export graphml`](commands/export.md#he-export-graphml)** — Export pairwise `<edge>` and N-ary `<hyperedge>` GraphML
- >>>>>>> origin/main
+ - **[`he export cypher`](commands/export.md#he-export-cypher)** — Export a Neo4j-compatible Cypher MERGE script
++>>>>>>> pr-141-src
- **[`he export csv`](commands/export.md#he-export-csv)** — Export nodes/edges as CSV tables
### Management
diff --cc docs/zh/cli/commands/export.md
index f9bdbc2,f55dff5..851cf57
--- a/docs/zh/cli/commands/export.md
+++ b/docs/zh/cli/commands/export.md
@@@ -2,7 -2,7 +2,8 @@@
将知识摘要导出为 [Obsidian](https://obsidian.md) 知识库——一个由 `[[双向链接]]` 关联的 Markdown 笔记文件夹。
+`export` 是一个命令组。目前支持的格式:`obsidian`、`graphml`、`jsonld`、`csv`。
+ `export` 是一个命令组。目前支持的格式:`obsidian`、`graphml`、`cypher`、`csv`。
---
@@@ -167,30 -165,23 +168,41 @@@ he export graphml ./tesla_kb/ -o ./tesl
---
+## he export jsonld
+
+将知识图谱导出为 JSON-LD(标准库 `json`,不引入 RDFLib)。二元边为 `@type: Edge`,带 `source` / `target`。三个及以上端点的边为 `@type: Hyperedge`,`endpoint` 列表保持抽取器顺序(不排序)。0/1 个端点或缺失端点的边会跳过并记 warning,与 GraphML 一致。
+ ## he export cypher
+
+ 导出 Neo4j / Memgraph 可用的 Cypher MERGE 脚本(`cypher-shell < file.cypher`)。二元边写成关系(`:REL`,或合法的 `type`/`label` ident)。三个及以上端点的边写成 `(:Hyperedge)` 节点,并用 `(n)-[:IN]->(h)` 按抽取器顺序连接——不会拆成两两团。0/1 个端点或缺失端点的边会跳过并记 warning。
目标文件已存在且非空时需要 `--force` / `-f`。
### 用法
```bash
+he export jsonld KA_PATH -o FILE.jsonld [--force]
+```
+
+### 选项
+
+| 选项 | 别名 | 默认值 | 说明 |
+|--------|-------|---------|-------------|
+| `--output` | `-o` | *(必填)* | 输出 JSON-LD 文件 |
+| `--force` | `-f` | 关闭 | 覆盖已存在的非空文件 |
+
+### 示例
+
+```bash
+he export jsonld ./tesla_kb/ -o ./tesla.jsonld
+he export jsonld ./tesla_kb/ -o ./tesla.jsonld --force
+ he export cypher KA_PATH -o FILE.cypher [--force]
+ ```
+
+ ### 示例
+
+ ```bash
+ he export cypher ./tesla_kb/ -o ./tesla.cypher
+ he export cypher ./tesla_kb/ -o ./tesla.cypher --force
```
---
@@@ -250,7 -241,7 +262,12 @@@ Obsidian 导出是图谱 Auto-Type 上�
```python
ka.export_obsidian("./tesla_vault/", vault_name="Tesla KB", overwrite=True)
- from hyperextract.utils.exporters import export_to_graphml, export_to_csv, export_to_jsonld
-from hyperextract.utils.exporters import export_to_graphml, export_to_csv, export_to_cypher
++from hyperextract.utils.exporters import (
++ export_to_graphml,
++ export_to_csv,
++ export_to_jsonld,
++ export_to_cypher,
++)
export_to_graphml(
ka.nodes,
@@@ -269,12 -260,12 +286,14 @@@ export_to_csv
overwrite=True,
)
+export_to_jsonld(
+ export_to_cypher(
ka.nodes,
ka.edges,
node_id_extractor=ka.node_key_extractor,
incident_nodes_extractor=ka.nodes_in_edge_extractor,
+ file_path="./tesla.jsonld",
+ file_path="./tesla.cypher",
)
```
diff --cc docs/zh/cli/index.md
index 0196e7d,5f3718b..7a9d9e8
--- a/docs/zh/cli/index.md
+++ b/docs/zh/cli/index.md
@@@ -33,12 -33,8 +33,11 @@@ he --versio
| `he parse` | 从文档提取知识 | `-t` 模板, `-o` 输出, `-l` 语言, `--source` 来源标注 |
| `he show` | 可视化知识图谱 | — |
| `he export obsidian` | 导出为 Obsidian 知识库 | `-o` 输出, `--name`, `-f` 强制 |
- <<<<<<< HEAD
--| `he export graphml` | 将二元图导出为 GraphML | `-o` 输出文件 |
++| `he export graphml` | 导出二元 `<edge>` 与 N 元 `<hyperedge>` GraphML | `-o` 输出文件, `-f` 强制 |
+| `he export jsonld` | 将二元边与 N 元超边导出为 JSON-LD | `-o` 输出文件, `-f` 强制 |
+=======
- | `he export graphml` | 导出二元 `<edge>` 与 N 元 `<hyperedge>` GraphML | `-o` 输出文件, `-f` 强制 |
- >>>>>>> origin/main
+ | `he export cypher` | 导出 Neo4j 兼容 MERGE(N 元边为 Hyperedge 节点) | `-o` 输出文件, `-f` 强制 |
++>>>>>>> pr-141-src
| `he export csv` | 将节点/边导出为 CSV 表 | `-o` 目录, `-f` 强制 |
| `he search` | 知识库语义搜索 | `-n` top-k 结果数, `--source`, `--tag` |
| `he talk` | 与知识库对话 | `-i` 交互模式, `-q` 查询 |
@@@ -177,12 -173,8 +176,11 @@@ he show ./output
- **[`he talk`](commands/talk.md)** — 与知识库对话
- **[`he info`](commands/info.md)** — 查看知识库统计信息
- **[`he export obsidian`](commands/export.md)** — 导出为 Obsidian 知识库
- <<<<<<< HEAD
--- **[`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 jsonld`](commands/export.md#he-export-jsonld)** — 将二元边与 N 元超边导出为 JSON-LD
+=======
- - **[`he export graphml`](commands/export.md#he-export-graphml)** — 导出二元 `<edge>` 与 N 元 `<hyperedge>` GraphML
- >>>>>>> origin/main
+ - **[`he export cypher`](commands/export.md#he-export-cypher)** — 导出 Neo4j 兼容的 Cypher MERGE 脚本
++>>>>>>> pr-141-src
- **[`he export csv`](commands/export.md#he-export-csv)** — 将节点/边导出为 CSV 表
### 管理
diff --cc hyperextract/cli/cli.py
index 99f3393,348fd1f..950ef83
--- a/hyperextract/cli/cli.py
+++ b/hyperextract/cli/cli.py
@@@ -701,9 -630,67 +701,65 @@@ def export_jsonld_cmd
raise typer.Exit(1)
console.print()
- console.print(f"[bold green]Success![/bold green] Wrote GraphML to {output_path}")
- console.print()
- console.print("[dim]Open the file in Gephi, yEd, or another GraphML tool.[/dim]")
+ console.print(f"[bold green]Success![/bold green] Wrote JSON-LD to {output_path}")
+ @export_app.command(name="cypher")
+ def export_cypher_cmd(
+ ka_path: str = typer.Argument(..., help="Knowledge Abstract directory"),
+ output: str = typer.Option(..., "--output", "-o", help="Output Cypher file"),
+ force: bool = typer.Option(
+ False, "--force", "-f", help="Overwrite an existing Cypher file"
+ ),
+ ):
+ """Export a knowledge graph to a Neo4j-compatible Cypher MERGE script.
+
+ Binary edges become relationships. N-ary edges become Hyperedge nodes
+ with IN membership (not a pairwise clique).
+ """
+ from hyperextract.utils.exporters import export_to_cypher
+
+ logger.info("command=export-cypher ka_path=%s output=%s", ka_path, output)
+
+ output_path = Path(output)
+ existing_nonempty = (
+ output_path.exists()
+ and output_path.is_file()
+ and output_path.stat().st_size > 0
+ )
+ if existing_nonempty and not force:
+ console.print(
+ "[red]Error:[/red] Output file already exists. "
+ "Use --force / -f to overwrite it."
+ )
+ 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}")
+ console.print()
+
+ with console.status("[bold blue]Exporting to Cypher..."):
+ try:
+ export_to_cypher(
+ ka.nodes,
+ ka.edges,
+ node_id_extractor=ka.node_key_extractor,
+ incident_nodes_extractor=ka.nodes_in_edge_extractor,
+ file_path=output_path,
+ edge_id_extractor=getattr(ka, "edge_key_extractor", None),
+ )
+ except Exception as e:
+ console.print(f"[red]Error during export:[/red] {e}")
+ raise typer.Exit(1)
+
+ console.print()
+ console.print(f"[bold green]Success![/bold green] Wrote Cypher to {output_path}")
+ console.print()
+ console.print("[dim]Load with cypher-shell < file.cypher (Neo4j / Memgraph).[/dim]")
+
+
@export_app.command(name="csv")
def export_csv_cmd(
ka_path: str = typer.Argument(..., help="Knowledge Abstract directory"),
diff --cc hyperextract/utils/exporters/__init__.py
index cf0a7da,955a993..f6a86b0
--- a/hyperextract/utils/exporters/__init__.py
+++ b/hyperextract/utils/exporters/__init__.py
@@@ -1,4 -1,4 +1,4 @@@
- """Read-only graph exporters (GraphML, CSV, JSON-LD).
-"""Read-only graph exporters (GraphML, CSV, Cypher).
++"""Read-only graph exporters (GraphML, CSV, JSON-LD, Cypher).
These are pure functions over node/edge models, matching
:func:`hyperextract.utils.obsidian.export_to_obsidian`. They are not methods
@@@ -19,13 -19,13 +19,15 @@@ Example:
from .common import HYPEREDGE_MEMBER_SEP
from .csv_export import export_to_csv
+ from .cypher import export_to_cypher
from .graphml import GraphMLHypergraphError, export_to_graphml
+from .jsonld import export_to_jsonld
__all__ = [
"HYPEREDGE_MEMBER_SEP",
"GraphMLHypergraphError",
"export_to_csv",
+ "export_to_cypher",
"export_to_graphml",
+ "export_to_jsonld",
]
diff --cc tests/test_mcp_server.py
index 1a3c489,ef4c689..308140d
--- a/tests/test_mcp_server.py
+++ b/tests/test_mcp_server.py
@@@ -293,29 -166,6 +293,29 @@@ def test_export_csv(monkeypatch, tmp_pa
assert "nodes.csv + edges.csv" in out
+def test_export_graphml_rejects_non_graph(monkeypatch, tmp_path):
+ class _ListKA:
+ pass
+
+ monkeypatch.setattr(mcp_server, "_load_ka", lambda p: _ListKA())
+ out = mcp_server.export_graphml("x", str(tmp_path / "out.graphml"))
+ assert out == (
- "GraphML/CSV export is only supported for graph-type knowledge abstracts "
- "(graph, hypergraph, temporal/spatial graphs)."
++ "Graph export (GraphML/CSV/JSON-LD) is only supported for graph-type "
++ "knowledge abstracts (graph, hypergraph, temporal/spatial graphs)."
+ )
+
+
+def test_export_csv_rejects_non_graph_with_same_message(monkeypatch, tmp_path):
+ class _ListKA:
+ pass
+
+ monkeypatch.setattr(mcp_server, "_load_ka", lambda p: _ListKA())
+ graphml = mcp_server.export_graphml("x", str(tmp_path / "out.graphml"))
+ csv_out = mcp_server.export_csv("x", str(tmp_path / "csv"))
+ assert graphml == csv_out
+ assert "graph-type knowledge abstracts" in graphml
+
+
# ---------------------------------------------------------------------------
# FastMCP wiring (needs the optional `mcp` package)
# ---------------------------------------------------------------------------
diff --cc tests/utils/test_exporters.py
index 81a4ba0,9dd66f7..8989ba5
--- a/tests/utils/test_exporters.py
+++ b/tests/utils/test_exporters.py
@@@ -18,15 -18,8 +18,16 @@@ from hyperextract.cli.cli import ap
from hyperextract.utils.exporters import (
HYPEREDGE_MEMBER_SEP,
export_to_csv,
- export_to_cypher,
export_to_graphml,
+ export_to_jsonld,
++ export_to_cypher,
+)
+from hyperextract.utils.exporters.common import default_edge_id, resolve_export_file
+from hyperextract.utils.exporters.ka import (
+ GRAPH_TYPE_ERROR,
+ GraphTypeError,
+ export_ka_csv,
+ export_ka_graphml,
)
from hyperextract.utils.exporters.graphml import GRAPHML_NS
@@@ -214,533 -207,420 +215,954 @@@ class TestGraphMLPairwise
assert _edge_endpoints(graph, ns) == []
+# ---------------------------------------------------------------------------
+# JSON-LD — pairwise source/target, N-ary Hyperedge order
+# ---------------------------------------------------------------------------
+
+
+def _load_jsonld(path):
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+class TestJSONLDExport:
+ def test_pairwise_has_source_target(self, tmp_path):
+ nodes = [Entity(name="A"), Entity(name="B")]
+ edges = [Relation(source="B", target="A", relation_type="leads_to")]
+ path = export_to_jsonld(
+ nodes,
+ edges,
+ node_id_extractor=lambda n: n.name,
+ incident_nodes_extractor=lambda e: (e.source, e.target),
+ file_path=tmp_path / "g.jsonld",
+ )
+ doc = _load_jsonld(path)
+ assert "source" in doc["@context"]
+ assert doc["@context"]["source"]["@type"] == "@id"
+ assert doc["@context"]["endpoint"]["@container"] == "@list"
+ edges_out = [item for item in doc["@graph"] if item.get("@type") == "Edge"]
+ assert len(edges_out) == 1
+ assert edges_out[0]["source"] == "B"
+ assert edges_out[0]["target"] == "A"
+ assert edges_out[0]["@type"] == "Edge"
+ assert not any(item.get("@type") == "Hyperedge" for item in doc["@graph"])
+
+ def test_nary_writes_hyperedge_in_extractor_order(self, tmp_path):
+ nodes = [Entity(name="A"), Entity(name="B"), Entity(name="C")]
+ edges = [Event(label="meeting", participants=["C", "A", "B"])]
+ path = export_to_jsonld(
+ nodes,
+ edges,
+ node_id_extractor=lambda n: n.name,
+ incident_nodes_extractor=lambda e: tuple(e.participants),
+ file_path=tmp_path / "g.jsonld",
+ edge_id_extractor=lambda e: e.label,
+ )
+ doc = _load_jsonld(path)
+ hypers = [item for item in doc["@graph"] if item.get("@type") == "Hyperedge"]
+ assert len(hypers) == 1
+ assert hypers[0]["@type"] == "Hyperedge"
+ assert hypers[0]["endpoint"] == ["C", "A", "B"]
+ assert hypers[0]["endpoint"] != sorted(hypers[0]["endpoint"])
+ assert not any(item.get("@type") == "Edge" for item in doc["@graph"])
+
+ def test_unary_and_missing_endpoints_are_skipped(self, tmp_path):
+ nodes = [Entity(name="Apple")]
+ edges = [
+ Event(label="solo", participants=["Apple"]),
+ Relation(source="Apple", target="Ghost", relation_type="x"),
+ ]
+
+ def _incident(edge):
+ if isinstance(edge, Event):
+ return tuple(edge.participants)
+ return (edge.source, edge.target)
+
+ path = export_to_jsonld(
+ nodes,
+ edges,
+ node_id_extractor=lambda n: n.name,
+ incident_nodes_extractor=_incident,
+ file_path=tmp_path / "g.jsonld",
+ )
+ doc = _load_jsonld(path)
+ typed = [
+ item
+ for item in doc["@graph"]
+ if item.get("@type") in ("Edge", "Hyperedge")
+ ]
+ nodes_out = [
+ item["@id"] for item in doc["@graph"] if item.get("@type") == "Node"
+ ]
+ assert typed == []
+ assert nodes_out == ["Apple"]
+
+
+# ---------------------------------------------------------------------------
+# CSV — round-trip, quoting, direction, dangling, hypergraph
+# ---------------------------------------------------------------------------
+
+
+class TestCSVPairwise:
+ def test_round_trip_and_quoting(self, tmp_path):
+ nodes = [
+ Entity(name="Apple, Inc.", type="ORG", note='He said "hi"'),
+ Entity(name="Jobs", type="PERSON", note="line1\nline2"),
+ ]
+ edges = [
+ Relation(
+ source="Apple, Inc.",
+ target="Jobs",
+ relation_type="founded_by",
+ description="a, b",
+ )
+ ]
+ folder = _export_csv(tmp_path / "csv", nodes, edges)
+
+ with (folder / "nodes.csv").open(encoding="utf-8", newline="") as handle:
+ node_rows = list(csv.DictReader(handle))
+ with (folder / "edges.csv").open(encoding="utf-8", newline="") as handle:
+ edge_rows = list(csv.DictReader(handle))
+
+ assert [row["id"] for row in node_rows] == ["Apple, Inc.", "Jobs"]
+ assert node_rows[0]["name"] == "Apple, Inc."
+ assert node_rows[0]["note"] == 'He said "hi"'
+ assert node_rows[1]["note"] == "line1\nline2"
+
+ assert edge_rows[0]["source"] == "Apple, Inc."
+ assert edge_rows[0]["target"] == "Jobs"
+ assert edge_rows[0]["description"] == "a, b"
+ header = (folder / "nodes.csv").read_text(encoding="utf-8").splitlines()[0]
+ assert header.startswith("id,")
+
+ def test_preserves_direction_b_to_a(self, tmp_path):
+ nodes = [Entity(name="A"), Entity(name="B")]
+ edges = [Relation(source="B", target="A", relation_type="leads_to")]
+ folder = _export_csv(tmp_path / "csv", nodes, edges)
+ with (folder / "edges.csv").open(encoding="utf-8", newline="") as handle:
+ rows = list(csv.DictReader(handle))
+ assert rows[0]["source"] == "B"
+ assert rows[0]["target"] == "A"
+
+ def test_missing_endpoint_is_skipped(self, tmp_path):
+ nodes = [Entity(name="Apple")]
+ edges = [Relation(source="Apple", target="Ghost", relation_type="x")]
+ folder = _export_csv(tmp_path / "csv", nodes, edges)
+ with (folder / "edges.csv").open(encoding="utf-8", newline="") as handle:
+ rows = list(csv.DictReader(handle))
+ assert rows == []
+ with (folder / "nodes.csv").open(encoding="utf-8", newline="") as handle:
+ assert [r["id"] for r in csv.DictReader(handle)] == ["Apple"]
+
+ def test_raises_on_nonempty_dir(self, tmp_path):
+ dest = tmp_path / "csv"
+ dest.mkdir()
+ (dest / "keep.txt").write_text("keep", encoding="utf-8")
+ with pytest.raises(FileExistsError):
+ _export_csv(dest, [Entity(name="Apple")], [])
+
+ def test_overwrite_allows_nonempty_dir(self, tmp_path):
+ dest = tmp_path / "csv"
+ dest.mkdir()
+ (dest / "keep.txt").write_text("keep", encoding="utf-8")
+ _export_csv(dest, [Entity(name="Apple")], [], overwrite=True)
+ assert (dest / "nodes.csv").exists()
+ assert (dest / "keep.txt").exists()
+
+
+class TestCSVHypergraph:
+ def test_members_sorted_stable_delimiter(self, tmp_path):
+ nodes = [Entity(name="A"), Entity(name="B"), Entity(name="C")]
+ edges = [Event(label="meeting", participants=["C", "A", "B"])]
+ folder = export_to_csv(
+ nodes,
+ edges,
+ node_id_extractor=lambda n: n.name,
+ incident_nodes_extractor=lambda e: tuple(e.participants),
+ folder_path=tmp_path / "csv",
+ edge_id_extractor=lambda e: e.label,
+ hypergraph=True,
+ )
+ assert (folder / "hyperedges.csv").exists()
+ assert not (folder / "edges.csv").exists()
+ with (folder / "hyperedges.csv").open(encoding="utf-8", newline="") as handle:
+ rows = list(csv.DictReader(handle))
+ assert rows[0]["id"] == "meeting"
+ assert rows[0]["members"] == HYPEREDGE_MEMBER_SEP.join(["A", "B", "C"])
+ assert rows[0]["label"] == "meeting"
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+
+class FakeGraphKA:
+ def __init__(self, nodes, edges, hypergraph=False):
+ self.nodes = nodes
+ self.edges = edges
+ self.node_key_extractor = lambda n: n.name
+ if hypergraph:
+ self.nodes_in_edge_extractor = lambda e: tuple(e.participants)
+ self.edge_key_extractor = lambda e: e.label
+ self.metadata = {"type": "hypergraph"}
+ else:
+ self.nodes_in_edge_extractor = lambda e: (e.source, e.target)
+ self.edge_key_extractor = lambda e: (
+ f"{e.source}-{e.relation_type}-{e.target}"
+ )
+ self.metadata = {"type": "graph"}
+
+ def export_obsidian(self, *args, **kwargs):
+ return None
+
+ def load(self, path):
+ return None
+
+
+class FakeListKA:
+ def load(self, path):
+ return None
+
+
+def _ka_dir(tmp_path):
+ ka = tmp_path / "ka"
+ ka.mkdir()
+ (ka / "data.json").write_text(
+ json.dumps({"nodes": [], "edges": []}), encoding="utf-8"
+ )
+ (ka / "metadata.json").write_text(
+ json.dumps({"template": "general/biography_graph", "lang": "en"}),
+ encoding="utf-8",
+ )
+ return ka
+
+
+class TestCommonHelpers:
+ def test_default_edge_id_falls_back(self):
+ def _boom(_edge):
+ raise ValueError("no id")
+
+ assert default_edge_id(object(), 3, None) == "e3"
+ assert default_edge_id(object(), 1, lambda e: None) == "e1"
+ assert default_edge_id(object(), 1, lambda e: "") == "e1"
+ assert default_edge_id(object(), 1, _boom) == "e1"
+ assert default_edge_id(object(), 1, lambda e: "rel") == "rel"
+
+ def test_resolve_export_file_refuses_nonempty_without_overwrite(self, tmp_path):
+ dest = tmp_path / "out.graphml"
+ dest.write_text("KEEP", encoding="utf-8")
+ with pytest.raises(FileExistsError):
+ resolve_export_file(dest, overwrite=False)
+ assert dest.read_text(encoding="utf-8") == "KEEP"
+ resolved = resolve_export_file(dest, overwrite=True)
+ assert resolved == dest
+
+ def test_export_ka_graphml_and_csv_match_encoders(self, tmp_path):
+ fake = FakeGraphKA(
+ [Entity(name="A"), Entity(name="B")],
+ [Relation(source="B", target="A", relation_type="leads_to")],
+ )
+ path = export_ka_graphml(fake, tmp_path / "g.graphml")
+ _root, graph, ns = _parse_graphml(path)
+ assert _edge_endpoints(graph, ns) == [("B", "A")]
+ folder = export_ka_csv(fake, tmp_path / "csv")
+ with (folder / "edges.csv").open(encoding="utf-8", newline="") as handle:
+ rows = list(csv.DictReader(handle))
+ assert rows[0]["source"] == "B"
+
+ def test_export_ka_rejects_non_graph(self, tmp_path):
+ with pytest.raises(GraphTypeError, match="graph-type"):
+ export_ka_graphml(FakeListKA(), tmp_path / "g.graphml")
+ with pytest.raises(GraphTypeError) as exc:
+ 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):
+ ka_dir = _ka_dir(tmp_path)
+ fake = FakeGraphKA(
+ [Entity(name="A"), Entity(name="B")],
+ [Relation(source="B", target="A", relation_type="leads_to")],
+ )
+ out = tmp_path / "out.graphml"
+ 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(out)]
+ )
+ assert result.exit_code == 0, result.output
+ _root, graph, ns = _parse_graphml(out)
+ assert _edge_endpoints(graph, ns) == [("B", "A")]
+
+ def test_graphml_exports_hypergraph(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ fake = FakeGraphKA(
+ [Entity(name="A"), Entity(name="B"), Entity(name="C")],
+ [Event(label="meeting", participants=["A", "B", "C"])],
+ hypergraph=True,
+ )
+ out = tmp_path / "out.graphml"
+ 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(out)]
+ )
+ assert result.exit_code == 0, result.output
+ xml = out.read_text(encoding="utf-8")
+ assert "hyperedge" in xml
+ assert 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(
+ [Entity(name="A"), Entity(name="B")],
+ [Relation(source="B", target="A", relation_type="leads_to")],
+ )
+ out = tmp_path / "csv_out"
+ 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", "csv", str(ka_dir), "-o", str(out)])
+ assert result.exit_code == 0, result.output
+ with (out / "edges.csv").open(encoding="utf-8", newline="") as handle:
+ rows = list(csv.DictReader(handle))
+ assert rows[0]["source"] == "B"
+ assert rows[0]["target"] == "A"
+
+ def test_csv_hypergraph_writes_hyperedges(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ fake = FakeGraphKA(
+ [Entity(name="A"), Entity(name="B"), Entity(name="C")],
+ [Event(label="meeting", participants=["C", "A", "B"])],
+ hypergraph=True,
+ )
+ out = tmp_path / "csv_out"
+ 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", "csv", str(ka_dir), "-o", str(out)])
+ assert result.exit_code == 0, result.output
+ assert (out / "hyperedges.csv").exists()
+ assert not (out / "edges.csv").exists()
+
+ def test_csv_requires_force_for_nonempty_dir(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ dest = tmp_path / "csv_out"
+ dest.mkdir()
+ (dest / "existing.txt").write_text("x", 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", "csv", str(ka_dir), "-o", str(dest)])
+ assert result.exit_code == 1
+ assert "--force" in result.output or "not empty" in result.output
+
+ def test_csv_force_writes_nonempty_dir(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ dest = tmp_path / "csv_out"
+ dest.mkdir()
+ (dest / "existing.txt").write_text("x", 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", "csv", str(ka_dir), "-o", str(dest), "--force"]
+ )
+ assert result.exit_code == 0, result.output
+ assert (dest / "nodes.csv").exists()
+
+ def test_rejects_non_graph_ka(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ fake = FakeListKA()
+ 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(tmp_path / "g.graphml")],
+ )
+ assert result.exit_code == 1
+ assert "graph" in result.output.lower()
+
+ def test_jsonld_writes_pairwise_and_hyperedge(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ fake = FakeGraphKA(
+ [Entity(name="A"), Entity(name="B")],
+ [Relation(source="B", target="A", relation_type="leads_to")],
+ )
+ out = tmp_path / "out.jsonld"
+ 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", "jsonld", str(ka_dir), "-o", str(out)]
+ )
+ assert result.exit_code == 0, result.output
+ doc = _load_jsonld(out)
+ edges_out = [item for item in doc["@graph"] if item.get("@type") == "Edge"]
+ assert edges_out[0]["source"] == "B"
+ assert edges_out[0]["target"] == "A"
+
+ fake_h = FakeGraphKA(
+ [Entity(name="A"), Entity(name="B"), Entity(name="C")],
+ [Event(label="meeting", participants=["C", "A", "B"])],
+ hypergraph=True,
+ )
+ out_h = tmp_path / "h.jsonld"
+ 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_h),
+ ):
+ result = runner.invoke(
+ app, ["export", "jsonld", str(ka_dir), "-o", str(out_h)]
+ )
+ assert result.exit_code == 0, result.output
+ doc_h = _load_jsonld(out_h)
+ hypers = [item for item in doc_h["@graph"] if item.get("@type") == "Hyperedge"]
+ assert hypers[0]["endpoint"] == ["C", "A", "B"]
+
+ def test_jsonld_requires_force_for_existing_file(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ dest = tmp_path / "out.jsonld"
+ dest.write_text("SENTINEL", 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", "jsonld", 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") == "SENTINEL"
+
+ def test_jsonld_force_overwrites_existing_file(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ dest = tmp_path / "out.jsonld"
+ dest.write_text("SENTINEL", 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", "jsonld", str(ka_dir), "-o", str(dest), "--force"]
+ )
+ assert result.exit_code == 0, result.output
+ doc = _load_jsonld(dest)
+ assert any(item.get("@type") == "Node" for item in doc["@graph"])
++
++
++
++
+ # ---------------------------------------------------------------------------
+ # Cypher — pairwise REL, N-ary Hyperedge (no clique)
+ # ---------------------------------------------------------------------------
+
+
+ class TypedRel(BaseModel):
+ source: str
+ target: str
+ type: str
+
+
+ class TestCypherExport:
+ def test_pairwise_uses_rel_and_direction(self, tmp_path):
+ nodes = [Entity(name="A"), Entity(name="B")]
+ edges = [Relation(source="B", target="A", relation_type="leads_to")]
+ path = export_to_cypher(
+ nodes,
+ edges,
+ node_id_extractor=lambda n: n.name,
+ incident_nodes_extractor=lambda e: (e.source, e.target),
+ file_path=tmp_path / "g.cypher",
+ )
+ text = path.read_text(encoding="utf-8")
+ assert 'MERGE (n:Node {id: "A"})' in text
+ assert 'MERGE (n:Node {id: "B"})' in text
+ assert ":REL" in text
+ assert 'id: "B"' in text
+ assert ']->(b)' in text
+ assert text.index('MERGE (a:Node {id: "B"})') < text.index(
+ 'MERGE (b:Node {id: "A"})'
+ )
+
+ def test_legal_type_becomes_rel_ident(self, tmp_path):
+ nodes = [Entity(name="A"), Entity(name="B")]
+ edges = [TypedRel(source="A", target="B", type="KNOWS")]
+ path = export_to_cypher(
+ nodes,
+ edges,
+ node_id_extractor=lambda n: n.name,
+ incident_nodes_extractor=lambda e: (e.source, e.target),
+ file_path=tmp_path / "g.cypher",
+ )
+ assert ":KNOWS" in path.read_text(encoding="utf-8")
+
+ def test_nary_is_hyperedge_not_clique(self, tmp_path):
+ nodes = [Entity(name="A"), Entity(name="B"), Entity(name="C")]
+ edges = [Event(label="meeting", participants=["C", "A", "B"])]
+ path = export_to_cypher(
+ nodes,
+ edges,
+ node_id_extractor=lambda n: n.name,
+ incident_nodes_extractor=lambda e: tuple(e.participants),
+ file_path=tmp_path / "g.cypher",
+ edge_id_extractor=lambda e: e.label,
+ )
+ text = path.read_text(encoding="utf-8")
+ assert ":Hyperedge" in text
+ assert "[:IN]" in text
+ assert text.count("[:IN]") == 3
+ in_order = [
+ line
+ for line in text.splitlines()
+ if "[:IN]" in line or "MERGE (n:Node {id:" in line
+ ]
+ member_ids = [
+ line.split('id: "')[1].split('"')[0]
+ for line in in_order
+ if "MERGE (n:Node {id:" in line
+ and "Hyperedge" not in line
+ and line.split('id: "')[1].split('"')[0] in {"A", "B", "C"}
+ ]
+ # Membership MERGEs after the Hyperedge, in extractor order C, A, B
+ assert member_ids[-3:] == ["C", "A", "B"]
+ assert "-[:REL]" not in text
+ assert not any(
+ pair in text
+ for pair in (
+ '(a)-[r:REL {id: "C-A"}]',
+ '(a)-[r:REL {id: "A-B"}]',
+ '(a)-[r:REL {id: "C-B"}]',
+ )
+ )
+
+ def test_escapes_backslash_and_quote(self, tmp_path):
+ nodes = [Entity(name='say "hi"\\')]
+ path = export_to_cypher(
+ nodes,
+ [],
+ node_id_extractor=lambda n: n.name,
+ incident_nodes_extractor=lambda e: (),
+ file_path=tmp_path / "g.cypher",
+ )
+ text = path.read_text(encoding="utf-8")
+ assert r"say \"hi\"\\" in text
+
+
+ # ---------------------------------------------------------------------------
+ # CSV — round-trip, quoting, direction, dangling, hypergraph
+ # ---------------------------------------------------------------------------
+
+
+ class TestCSVPairwise:
+ def test_round_trip_and_quoting(self, tmp_path):
+ nodes = [
+ Entity(name="Apple, Inc.", type="ORG", note='He said "hi"'),
+ Entity(name="Jobs", type="PERSON", note="line1\nline2"),
+ ]
+ edges = [
+ Relation(
+ source="Apple, Inc.",
+ target="Jobs",
+ relation_type="founded_by",
+ description="a, b",
+ )
+ ]
+ folder = _export_csv(tmp_path / "csv", nodes, edges)
+
+ with (folder / "nodes.csv").open(encoding="utf-8", newline="") as handle:
+ node_rows = list(csv.DictReader(handle))
+ with (folder / "edges.csv").open(encoding="utf-8", newline="") as handle:
+ edge_rows = list(csv.DictReader(handle))
+
+ assert [row["id"] for row in node_rows] == ["Apple, Inc.", "Jobs"]
+ assert node_rows[0]["name"] == "Apple, Inc."
+ assert node_rows[0]["note"] == 'He said "hi"'
+ assert node_rows[1]["note"] == "line1\nline2"
+
+ assert edge_rows[0]["source"] == "Apple, Inc."
+ assert edge_rows[0]["target"] == "Jobs"
+ assert edge_rows[0]["description"] == "a, b"
+ header = (folder / "nodes.csv").read_text(encoding="utf-8").splitlines()[0]
+ assert header.startswith("id,")
+
+ def test_preserves_direction_b_to_a(self, tmp_path):
+ nodes = [Entity(name="A"), Entity(name="B")]
+ edges = [Relation(source="B", target="A", relation_type="leads_to")]
+ folder = _export_csv(tmp_path / "csv", nodes, edges)
+ with (folder / "edges.csv").open(encoding="utf-8", newline="") as handle:
+ rows = list(csv.DictReader(handle))
+ assert rows[0]["source"] == "B"
+ assert rows[0]["target"] == "A"
+
+ def test_missing_endpoint_is_skipped(self, tmp_path):
+ nodes = [Entity(name="Apple")]
+ edges = [Relation(source="Apple", target="Ghost", relation_type="x")]
+ folder = _export_csv(tmp_path / "csv", nodes, edges)
+ with (folder / "edges.csv").open(encoding="utf-8", newline="") as handle:
+ rows = list(csv.DictReader(handle))
+ assert rows == []
+ with (folder / "nodes.csv").open(encoding="utf-8", newline="") as handle:
+ assert [r["id"] for r in csv.DictReader(handle)] == ["Apple"]
+
+ def test_raises_on_nonempty_dir(self, tmp_path):
+ dest = tmp_path / "csv"
+ dest.mkdir()
+ (dest / "keep.txt").write_text("keep", encoding="utf-8")
+ with pytest.raises(FileExistsError):
+ _export_csv(dest, [Entity(name="Apple")], [])
+
+ def test_overwrite_allows_nonempty_dir(self, tmp_path):
+ dest = tmp_path / "csv"
+ dest.mkdir()
+ (dest / "keep.txt").write_text("keep", encoding="utf-8")
+ _export_csv(dest, [Entity(name="Apple")], [], overwrite=True)
+ assert (dest / "nodes.csv").exists()
+ assert (dest / "keep.txt").exists()
+
+
+ class TestCSVHypergraph:
+ def test_members_sorted_stable_delimiter(self, tmp_path):
+ nodes = [Entity(name="A"), Entity(name="B"), Entity(name="C")]
+ edges = [Event(label="meeting", participants=["C", "A", "B"])]
+ folder = export_to_csv(
+ nodes,
+ edges,
+ node_id_extractor=lambda n: n.name,
+ incident_nodes_extractor=lambda e: tuple(e.participants),
+ folder_path=tmp_path / "csv",
+ edge_id_extractor=lambda e: e.label,
+ hypergraph=True,
+ )
+ assert (folder / "hyperedges.csv").exists()
+ assert not (folder / "edges.csv").exists()
+ with (folder / "hyperedges.csv").open(encoding="utf-8", newline="") as handle:
+ rows = list(csv.DictReader(handle))
+ assert rows[0]["id"] == "meeting"
+ assert rows[0]["members"] == HYPEREDGE_MEMBER_SEP.join(["A", "B", "C"])
+ assert rows[0]["label"] == "meeting"
+
+
+ # ---------------------------------------------------------------------------
+ # CLI
+ # ---------------------------------------------------------------------------
+
+
+ class FakeGraphKA:
+ def __init__(self, nodes, edges, hypergraph=False):
+ self.nodes = nodes
+ self.edges = edges
+ self.node_key_extractor = lambda n: n.name
+ if hypergraph:
+ self.nodes_in_edge_extractor = lambda e: tuple(e.participants)
+ self.edge_key_extractor = lambda e: e.label
+ self.metadata = {"type": "hypergraph"}
+ else:
+ self.nodes_in_edge_extractor = lambda e: (e.source, e.target)
+ self.edge_key_extractor = lambda e: (
+ f"{e.source}-{e.relation_type}-{e.target}"
+ )
+ self.metadata = {"type": "graph"}
+
+ def export_obsidian(self, *args, **kwargs):
+ return None
+
+ def load(self, path):
+ return None
+
+
+ class FakeListKA:
+ def load(self, path):
+ return None
+
+
+ def _ka_dir(tmp_path):
+ ka = tmp_path / "ka"
+ ka.mkdir()
+ (ka / "data.json").write_text(
+ json.dumps({"nodes": [], "edges": []}), encoding="utf-8"
+ )
+ (ka / "metadata.json").write_text(
+ json.dumps({"template": "general/biography_graph", "lang": "en"}),
+ encoding="utf-8",
+ )
+ return ka
+
+
+ class TestCLIExport:
+ def test_graphml_writes_directed_edge(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ fake = FakeGraphKA(
+ [Entity(name="A"), Entity(name="B")],
+ [Relation(source="B", target="A", relation_type="leads_to")],
+ )
+ out = tmp_path / "out.graphml"
+ 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(out)]
+ )
+ assert result.exit_code == 0, result.output
+ _root, graph, ns = _parse_graphml(out)
+ assert _edge_endpoints(graph, ns) == [("B", "A")]
+
+ def test_graphml_exports_hypergraph(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ fake = FakeGraphKA(
+ [Entity(name="A"), Entity(name="B"), Entity(name="C")],
+ [Event(label="meeting", participants=["A", "B", "C"])],
+ hypergraph=True,
+ )
+ out = tmp_path / "out.graphml"
+ 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(out)]
+ )
+ assert result.exit_code == 0, result.output
+ xml = out.read_text(encoding="utf-8")
+ assert "hyperedge" in xml
+ assert f'xmlns="{GRAPHML_NS}"' in xml
+
+ def test_csv_writes_tables(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ fake = FakeGraphKA(
+ [Entity(name="A"), Entity(name="B")],
+ [Relation(source="B", target="A", relation_type="leads_to")],
+ )
+ out = tmp_path / "csv_out"
+ 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", "csv", str(ka_dir), "-o", str(out)])
+ assert result.exit_code == 0, result.output
+ with (out / "edges.csv").open(encoding="utf-8", newline="") as handle:
+ rows = list(csv.DictReader(handle))
+ assert rows[0]["source"] == "B"
+ assert rows[0]["target"] == "A"
+
+ def test_csv_hypergraph_writes_hyperedges(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ fake = FakeGraphKA(
+ [Entity(name="A"), Entity(name="B"), Entity(name="C")],
+ [Event(label="meeting", participants=["C", "A", "B"])],
+ hypergraph=True,
+ )
+ out = tmp_path / "csv_out"
+ 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", "csv", str(ka_dir), "-o", str(out)])
+ assert result.exit_code == 0, result.output
+ assert (out / "hyperedges.csv").exists()
+ assert not (out / "edges.csv").exists()
+
+ def test_csv_requires_force_for_nonempty_dir(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ dest = tmp_path / "csv_out"
+ dest.mkdir()
+ (dest / "existing.txt").write_text("x", 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", "csv", str(ka_dir), "-o", str(dest)])
+ assert result.exit_code == 1
+ assert "--force" in result.output or "not empty" in result.output
+
+ def test_csv_force_writes_nonempty_dir(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ dest = tmp_path / "csv_out"
+ dest.mkdir()
+ (dest / "existing.txt").write_text("x", 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", "csv", str(ka_dir), "-o", str(dest), "--force"]
+ )
+ assert result.exit_code == 0, result.output
+ assert (dest / "nodes.csv").exists()
+
+ def test_rejects_non_graph_ka(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ fake = FakeListKA()
+ 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(tmp_path / "g.graphml")],
+ )
+ assert result.exit_code == 1
+ assert "graph" in result.output.lower()
+
+ def test_cypher_writes_hyperedge_membership(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ fake = FakeGraphKA(
+ [Entity(name="A"), Entity(name="B"), Entity(name="C")],
+ [Event(label="meeting", participants=["C", "A", "B"])],
+ hypergraph=True,
+ )
+ out = tmp_path / "out.cypher"
+ 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", "cypher", str(ka_dir), "-o", str(out)]
+ )
+ assert result.exit_code == 0, result.output
+ text = out.read_text(encoding="utf-8")
+ assert ":Hyperedge" in text
+ assert "[:IN]" in text
+ assert "-[:REL]->" not in text
+
+ def test_cypher_requires_force_for_existing_file(self, tmp_path):
+ ka_dir = _ka_dir(tmp_path)
+ dest = tmp_path / "out.cypher"
+ dest.write_text("SENTINEL", 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", "cypher", 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") == "SENTINEL"