-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathconfig.py
More file actions
191 lines (165 loc) · 7.03 KB
/
Copy pathconfig.py
File metadata and controls
191 lines (165 loc) · 7.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
"""Configuration helpers for Lance-backed knowledge graphs."""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Mapping, Optional
import pyarrow.fs
import yaml
from lance_graph import GraphConfig
@dataclass(slots=True)
class KnowledgeGraphConfig:
"""Root configuration for the Lance-backed knowledge graph."""
storage_path: Path | str
schema_path: Optional[Path | str] = None
default_dataset: Optional[str] = None
entity_types: tuple[str, ...] = field(default_factory=tuple)
relationship_types: tuple[str, ...] = field(default_factory=tuple)
storage_options: Optional[dict[str, str]] = None
@classmethod
def from_root(
cls,
root: Path | str,
*,
default_dataset: Optional[str] = None,
storage_options: Optional[dict[str, str]] = None,
) -> KnowledgeGraphConfig:
"""Create a configuration anchored at ``root``."""
if isinstance(root, str) and "://" in root:
schema_path = f"{root.rstrip('/')}/graph.yaml"
else:
if isinstance(root, str):
root = Path(root)
schema_path = root / "graph.yaml"
return cls(
storage_path=root,
schema_path=schema_path,
default_dataset=default_dataset,
storage_options=storage_options,
)
@classmethod
def default(cls) -> KnowledgeGraphConfig:
"""Use a storage folder relative to the current working directory."""
return cls.from_root(Path.cwd() / "knowledge_graph_data")
def resolved_schema_path(self) -> Path | str:
"""Return the expected path to the graph schema definition."""
if self.schema_path:
return self.schema_path
if isinstance(self.storage_path, str) and "://" in self.storage_path:
return f"{self.storage_path.rstrip('/')}/graph.yaml"
if isinstance(self.storage_path, str):
return Path(self.storage_path) / "graph.yaml"
return self.storage_path / "graph.yaml"
def ensure_directories(self) -> None:
"""Create required directories for persistent storage."""
if isinstance(self.storage_path, str) and "://" in self.storage_path:
return
path = (
self.storage_path
if isinstance(self.storage_path, Path)
else Path(self.storage_path)
)
path.mkdir(parents=True, exist_ok=True)
schema = self.resolved_schema_path()
if isinstance(schema, Path):
schema.parent.mkdir(parents=True, exist_ok=True)
def with_schema(self, schema_path: Path | str) -> KnowledgeGraphConfig:
"""Return a copy of the config with an explicit schema path."""
return KnowledgeGraphConfig(
storage_path=self.storage_path,
schema_path=schema_path,
default_dataset=self.default_dataset,
entity_types=self.entity_types,
relationship_types=self.relationship_types,
storage_options=self.storage_options,
)
def load_graph_config(self) -> GraphConfig:
"""Load the Lance ``GraphConfig`` from the schema document."""
payload = self._load_schema_payload()
entity_types = payload.get("entity_types") or []
relationship_types = payload.get("relationship_types") or []
self.entity_types = _normalize_type_list(entity_types)
self.relationship_types = _normalize_type_list(relationship_types)
if not payload.get("nodes") and not payload.get("relationships"):
return build_default_graph_config()
return build_graph_config_from_mapping(payload)
def type_hints(self) -> dict[str, tuple[str, ...]]:
"""Return configured entity and relationship type hints."""
# Ensure the latest schema values are loaded.
try:
self.load_graph_config()
except FileNotFoundError:
pass
return {
"entity_types": self.entity_types,
"relationship_types": self.relationship_types,
}
def _load_schema_payload(self) -> Mapping[str, Any]:
schema_path = self.resolved_schema_path()
if isinstance(schema_path, str) and "://" in schema_path:
fs, path = pyarrow.fs.FileSystem.from_uri(schema_path)
try:
with fs.open_input_stream(path) as f:
payload = yaml.safe_load(f.read()) or {}
except FileNotFoundError:
raise FileNotFoundError(
f"Graph schema configuration not found at {schema_path}"
)
else:
if isinstance(schema_path, str):
schema_path = Path(schema_path)
if not schema_path.exists():
raise FileNotFoundError(
f"Graph schema configuration not found at {schema_path}"
)
with schema_path.open("r", encoding="utf-8") as handle:
payload = yaml.safe_load(handle) or {}
if not isinstance(payload, Mapping):
raise ValueError("Graph schema configuration must be a mapping")
return payload # type: ignore[return-value]
def build_graph_config_from_mapping(data: Mapping[str, Any]) -> GraphConfig:
"""Create a ``GraphConfig`` instance from a schema mapping."""
builder = GraphConfig.builder()
for label, node_spec in data.get("nodes", {}).items():
if isinstance(node_spec, str):
builder = builder.with_node_label(label, node_spec)
else:
id_field = node_spec.get("id_field")
if not id_field:
raise ValueError(f"Node '{label}' is missing 'id_field'")
builder = builder.with_node_label(label, id_field)
for rel_type, rel_spec in data.get("relationships", {}).items():
if not isinstance(rel_spec, Mapping):
raise ValueError(
(
f"Relationship '{rel_type}' must be a mapping with 'source' and "
"'target'"
)
)
source_field = rel_spec.get("source")
target_field = rel_spec.get("target")
if not (source_field and target_field):
raise ValueError(
f"Relationship '{rel_type}' must define 'source' and 'target' fields"
)
builder = builder.with_relationship(rel_type, source_field, target_field)
return builder.build()
def build_default_graph_config() -> GraphConfig:
builder = GraphConfig.builder()
builder = builder.with_node_label("Entity", "entity_id")
builder = builder.with_relationship(
"RELATIONSHIP",
"source_entity_id",
"target_entity_id",
)
return builder.build()
def _normalize_type_list(values: Any) -> tuple[str, ...]:
if not isinstance(values, list):
return tuple()
cleaned: list[str] = []
for item in values:
if not isinstance(item, str):
continue
trimmed = item.strip()
if trimmed:
cleaned.append(trimmed)
return tuple(cleaned)