structurerag 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,56 @@
1
+ """
2
+ StructureRAG: Deterministic Retrieval-Augmented Generation via Holistic Structural Forms.
3
+
4
+ Embedding-free retrieval with full traceability.
5
+ """
6
+
7
+ __version__ = "0.2.0"
8
+
9
+ from .core.hsf import HolisticStructuralForm, ElementaryFeature, CompositeFeature
10
+ from .core.builder import StructureBuilder, PatternMiner
11
+ from .core.reasoner import MultiHopReasoner, ReasoningResult, ReasoningPath
12
+ from .grounding.retriever import StructureRetriever, SearchResult
13
+ from .grounding.verifier import GroundingVerifier, Claim, VerificationResult, GroundingSpan
14
+ from .grounding.citation import CitationEngine, Citation
15
+ from .grounding.reranker import StructureReranker, CrossEncoderReranker
16
+ from .semantic import (
17
+ SemanticExpander, PhraseMatcher, SynonymGroup,
18
+ create_default_expander, create_default_phrase_matcher,
19
+ )
20
+ from .structurerag import StructureRAG, GroundedAnswer
21
+
22
+ __all__ = [
23
+ "StructureRAG",
24
+ "GroundedAnswer",
25
+ "HolisticStructuralForm",
26
+ "ElementaryFeature",
27
+ "CompositeFeature",
28
+ "StructureBuilder",
29
+ "PatternMiner",
30
+ "MultiHopReasoner",
31
+ "ReasoningResult",
32
+ "ReasoningPath",
33
+ "StructureRetriever",
34
+ "SearchResult",
35
+ "GroundingVerifier",
36
+ "Claim",
37
+ "VerificationResult",
38
+ "GroundingSpan",
39
+ "CitationEngine",
40
+ "Citation",
41
+ "SemanticExpander",
42
+ "PhraseMatcher",
43
+ "SynonymGroup",
44
+ "create_default_expander",
45
+ "create_default_phrase_matcher",
46
+ "StructureReranker",
47
+ "CrossEncoderReranker",
48
+ ]
49
+
50
+ # Backwards compatibility aliases.
51
+ # ``Context`` / ``ContextGraph`` were removed: the builder populated the graph
52
+ # but nothing in the library ever read it.
53
+ EnhancedSemanticExpander = SemanticExpander
54
+ EnhancedPhraseMatcher = PhraseMatcher
55
+ create_enhanced_expander = create_default_expander
56
+ create_enhanced_phrase_matcher = create_default_phrase_matcher
@@ -0,0 +1,16 @@
1
+ """Core HSF data structures and builders."""
2
+
3
+ from .hsf import HolisticStructuralForm, ElementaryFeature, CompositeFeature
4
+ from .builder import StructureBuilder, PatternMiner
5
+ from .reasoner import MultiHopReasoner, ReasoningResult, ReasoningPath
6
+
7
+ __all__ = [
8
+ "HolisticStructuralForm",
9
+ "ElementaryFeature",
10
+ "CompositeFeature",
11
+ "StructureBuilder",
12
+ "PatternMiner",
13
+ "MultiHopReasoner",
14
+ "ReasoningResult",
15
+ "ReasoningPath",
16
+ ]
@@ -0,0 +1,309 @@
1
+ """
2
+ Structure Builder: Transforms unstructured text into HSF representation.
3
+
4
+ The builder processes text through these levels:
5
+ - Word level (elementary features), with the exact source separator recorded
6
+ - Sentence level (composite features)
7
+ - Document level (composite feature)
8
+
9
+ Feature IDs embed the document ID, so several documents can be merged into one
10
+ corpus-level index without ID collisions.
11
+ """
12
+
13
+ import re
14
+ from typing import List, Dict, Optional, Tuple, Any, Iterator
15
+ from hashlib import sha256
16
+ from .hsf import ElementaryFeature, CompositeFeature, HolisticStructuralForm
17
+
18
+
19
+ class StructureBuilder:
20
+ """
21
+ Builds Holistic Structural Forms from unstructured text.
22
+
23
+ Each sentence becomes a composite feature whose children are the word
24
+ features that fall inside its character range. Words are elementary
25
+ features carrying their own offsets and the literal gap that preceded them,
26
+ which is what makes lossless reconstruction possible.
27
+ """
28
+
29
+ # Numbers ('3.5', '1,000') are one word token: a decimal point inside a
30
+ # number is punctuation in context, not a separator.
31
+ _TOKEN_RE = re.compile(r'\b\d[\d,]*(?:\.\d+)?\b|\b\w+\b|[^\w\s]')
32
+ # A '.' between digits is a decimal point, never a sentence boundary.
33
+ _SENTENCE_RE = re.compile(r'(?:\d[.](?=\d)|[^.!?])*[.!?]+')
34
+
35
+ def __init__(self, document_id: str = None):
36
+ self.document_id = document_id or sha256(b"auto").hexdigest()[:12]
37
+ self.hsf = HolisticStructuralForm(document_id=self.document_id, title="")
38
+ self._position_counter = 0
39
+ self._sentence_counter = 0
40
+
41
+ def build(self, text: str, title: str = "") -> HolisticStructuralForm:
42
+ """
43
+ Build HSF from raw text.
44
+
45
+ Args:
46
+ text: The unstructured text to transform
47
+ title: Optional document title
48
+
49
+ Returns:
50
+ Complete HolisticStructuralForm representation
51
+ """
52
+ self.hsf = HolisticStructuralForm(document_id=self.document_id, title=title)
53
+ self._position_counter = 0
54
+ self._sentence_counter = 0
55
+
56
+ self._ingest(text, base_offset=0)
57
+ return self.hsf
58
+
59
+ def build_from_chunks(self, chunks: List[str],
60
+ chunk_type: str = "paragraph") -> HolisticStructuralForm:
61
+ """
62
+ Build HSF from pre-split text chunks.
63
+
64
+ Each chunk is ingested as an ordinary slice of text, so it yields the
65
+ same sentence composite features as :meth:`build`. Chunked documents are
66
+ therefore searchable through exactly the same path as whole documents.
67
+
68
+ The gaps between caller-supplied chunks are not knowable, so chunks are
69
+ joined with a single space during reconstruction.
70
+
71
+ Args:
72
+ chunks: Pre-split text pieces, in source order
73
+ chunk_type: Label recorded in sentence metadata as ``chunk_type``
74
+
75
+ Returns:
76
+ Complete HolisticStructuralForm representation
77
+ """
78
+ self.hsf = HolisticStructuralForm(document_id=self.document_id, title="")
79
+ self._position_counter = 0
80
+ self._sentence_counter = 0
81
+
82
+ for chunk_num, (offset_in_text, chunk) in enumerate(self._iter_with_offsets(chunks)):
83
+ # Chunks are joined by a single space; see the docstring.
84
+ leading_sep = None if chunk_num == 0 else ' '
85
+ self._ingest(chunk, base_offset=offset_in_text,
86
+ chunk_type=chunk_type, leading_sep=leading_sep)
87
+
88
+ if not self.hsf.composite_features:
89
+ return self.hsf
90
+
91
+ self._attach_document()
92
+ return self.hsf
93
+
94
+ @staticmethod
95
+ def _iter_with_offsets(chunks: List[str]) -> Iterator[Tuple[int, str]]:
96
+ """Yield (base_offset, chunk) with chunks joined by a single space."""
97
+ offset = 0
98
+ for i, chunk in enumerate(chunks):
99
+ yield offset, chunk
100
+ offset += len(chunk) + (1 if i < len(chunks) - 1 else 0)
101
+
102
+ def _ingest(self, text: str, base_offset: int, chunk_type: Optional[str] = None,
103
+ leading_sep: Optional[str] = None) -> None:
104
+ """Tokenize one slice of text and attach its sentences to the HSF."""
105
+ words = self._tokenize(text, base_offset=base_offset, leading_sep=leading_sep)
106
+ sentences = self._split_sentences(text, base_offset=base_offset)
107
+ self._build_hierarchy(words, sentences, chunk_type=chunk_type)
108
+
109
+ # Whitespace after the last token survives no token, so it is recorded on
110
+ # the HSF. The last slice ingested wins, which is the document's tail.
111
+ self.hsf.metadata['trailing'] = text[self._last_token_end:]
112
+
113
+ # A document composite is created once, after the final slice is in.
114
+ if chunk_type is None:
115
+ self._attach_document()
116
+
117
+ def _attach_document(self) -> None:
118
+ """Create the document-level composite over every sentence built so far."""
119
+ sentence_ids = [
120
+ fid for fid, feat in self.hsf.composite_features.items()
121
+ if feat.feature_type == 'sentence'
122
+ ]
123
+ if not sentence_ids or f"document_{self.document_id}" in self.hsf.composite_features:
124
+ return
125
+
126
+ doc_id = f"document_{self.document_id}"
127
+ document = CompositeFeature(
128
+ id=doc_id,
129
+ feature_type='document',
130
+ child_ids=sentence_ids,
131
+ context="Root document",
132
+ )
133
+ self.hsf.add_composite_feature(document)
134
+ self.hsf.add_hierarchy(doc_id, sentence_ids)
135
+
136
+ def _make_id(self, feature_type: str, value: str, position: int) -> str:
137
+ """Deterministic ID, unique across documents in a corpus."""
138
+ content = f"{self.document_id}:{feature_type}:{value}:{position}"
139
+ return sha256(content.encode()).hexdigest()[:16]
140
+
141
+ def _tokenize(self, text: str, base_offset: int = 0,
142
+ leading_sep: Optional[str] = None) -> List[ElementaryFeature]:
143
+ """
144
+ Tokenize text into word features.
145
+
146
+ ``metadata['sep']`` holds the literal source characters between the
147
+ previous token and this one, which is what lets reconstruction restore
148
+ punctuation spacing instead of assuming a single space.
149
+
150
+ ``leading_sep`` overrides the separator before the very first token. It
151
+ is ``None`` for whole documents, so their leading whitespace survives,
152
+ and ``' '`` for chunks after the first, which are joined by a space.
153
+ """
154
+ words: List[ElementaryFeature] = []
155
+ prev_local_end = 0
156
+ self._last_token_end = 0
157
+
158
+ for m in self._TOKEN_RE.finditer(text):
159
+ token = m.group()
160
+ if not token.strip():
161
+ continue
162
+
163
+ sep = text[prev_local_end:m.start()]
164
+ if not words and leading_sep is not None:
165
+ sep = leading_sep
166
+
167
+ position = self._position_counter
168
+ feature = ElementaryFeature(
169
+ id=self._make_id('word', token, position),
170
+ value=token,
171
+ feature_type='word',
172
+ position=position,
173
+ metadata={
174
+ 'char_start': base_offset + m.start(),
175
+ 'char_end': base_offset + m.end(),
176
+ 'sep': sep,
177
+ },
178
+ )
179
+ prev_local_end = m.end()
180
+ self._last_token_end = m.end()
181
+ self._position_counter += 1
182
+
183
+ self.hsf.add_elementary_feature(feature)
184
+ words.append(feature)
185
+
186
+ return words
187
+
188
+ def _split_sentences(self, text: str,
189
+ base_offset: int = 0) -> List[Tuple[int, int, str]]:
190
+ """
191
+ Split text into sentences with character offset tracking.
192
+
193
+ Returns list of (char_start, char_end, sentence_text) tuples.
194
+ """
195
+ sentences = []
196
+ last_end = 0
197
+
198
+ for m in self._SENTENCE_RE.finditer(text):
199
+ sentence = m.group().strip()
200
+ if sentence:
201
+ sentences.append((base_offset + m.start(),
202
+ base_offset + m.end(), sentence))
203
+ last_end = m.end()
204
+
205
+ # Handle trailing text without sentence-ending punctuation
206
+ if last_end < len(text):
207
+ trailing = text[last_end:]
208
+ if trailing.strip():
209
+ sentences.append((base_offset + last_end,
210
+ base_offset + len(text), trailing.strip()))
211
+
212
+ return sentences
213
+
214
+ def _build_hierarchy(self, words: List[ElementaryFeature],
215
+ sentences: List[Tuple[int, int, str]],
216
+ chunk_type: Optional[str] = None) -> None:
217
+ """Assign each word to the sentence whose character range contains it."""
218
+ if not sentences:
219
+ return
220
+
221
+ assigned: List[List[ElementaryFeature]] = [[] for _ in sentences]
222
+ sent_idx = 0
223
+ for word in words:
224
+ char_start = word.metadata['char_start']
225
+ while sent_idx < len(sentences) - 1 and char_start >= sentences[sent_idx][1]:
226
+ sent_idx += 1
227
+ assigned[sent_idx].append(word)
228
+
229
+ for local_num, (start_pos, end_pos, sentence_text) in enumerate(sentences):
230
+ sentence_id = f"{self.document_id}_s{self._sentence_counter}"
231
+ self._sentence_counter += 1
232
+
233
+ metadata: Dict[str, Any] = {
234
+ 'char_start': start_pos,
235
+ 'char_end': end_pos,
236
+ }
237
+ if chunk_type is not None:
238
+ metadata['chunk_type'] = chunk_type
239
+
240
+ sentence = CompositeFeature(
241
+ id=sentence_id,
242
+ feature_type='sentence',
243
+ context=f"Sentence {sentence_id}",
244
+ metadata=metadata,
245
+ )
246
+ for word in assigned[local_num]:
247
+ sentence.add_child(word)
248
+ self.hsf.add_hierarchy(sentence_id, [word.id])
249
+
250
+ self.hsf.add_composite_feature(sentence)
251
+
252
+ def get_structure_stats(self) -> Dict[str, int]:
253
+ """Get statistics about the built structure."""
254
+ return self.hsf.get_structure_summary()
255
+
256
+
257
+ class PatternMiner:
258
+ """
259
+ Discovers recurring structural patterns in HSF.
260
+
261
+ - Identifies common patterns across composite features
262
+ - Creates reusable structural templates
263
+ """
264
+
265
+ def __init__(self):
266
+ self.patterns: Dict[str, List[str]] = {} # signature -> list of feature IDs
267
+
268
+ def mine(self, hsf: HolisticStructuralForm, min_frequency: int = 2) -> Dict[str, int]:
269
+ """
270
+ Mine recurring patterns from HSF.
271
+
272
+ Args:
273
+ hsf: The HSF to analyze
274
+ min_frequency: Minimum occurrences to consider a pattern
275
+
276
+ Returns:
277
+ Dictionary of pattern signatures to occurrence counts
278
+ """
279
+ pattern_counts: Dict[str, int] = {}
280
+
281
+ for feat_id, feature in hsf.composite_features.items():
282
+ sig = feature.structural_signature
283
+ pattern_counts[sig] = pattern_counts.get(sig, 0) + 1
284
+ self.patterns.setdefault(sig, []).append(feat_id)
285
+
286
+ return {sig: count for sig, count in pattern_counts.items()
287
+ if count >= min_frequency}
288
+
289
+ def get_pattern_templates(self, hsf: HolisticStructuralForm) -> List[Dict[str, Any]]:
290
+ """
291
+ Get reusable templates for frequent patterns.
292
+
293
+ Returns templates that can be used for faster matching and compression.
294
+ """
295
+ templates = []
296
+ frequent = self.mine(hsf, min_frequency=2)
297
+
298
+ for sig, occurrences in frequent.items():
299
+ for feature in hsf.composite_features.values():
300
+ if feature.structural_signature == sig:
301
+ templates.append({
302
+ 'signature': sig,
303
+ 'type': feature.feature_type,
304
+ 'occurrences': occurrences,
305
+ 'example_children': [c.value for c in feature.children[:3]]
306
+ })
307
+ break
308
+
309
+ return templates
@@ -0,0 +1,249 @@
1
+ """
2
+ Core data structures for Holistic Structural Form (HSF) representation.
3
+
4
+ This module defines the fundamental building blocks:
5
+ - ElementaryFeature: Basic units (words, tokens, characters)
6
+ - CompositeFeature: Hierarchical combinations of features
7
+ - HolisticStructuralForm: Container for the complete structure
8
+ """
9
+
10
+ from dataclasses import dataclass, field
11
+ from typing import List, Dict, Optional, Any
12
+ from hashlib import sha256
13
+ import json
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class ElementaryFeature:
18
+ """
19
+ An elementary (atomic) feature representing a basic unit of knowledge.
20
+
21
+ In text processing, these are typically tokens, words, or characters.
22
+ Each feature has a unique identifier based on its content and context.
23
+ """
24
+ id: str
25
+ value: str
26
+ feature_type: str # 'word', 'phrase', 'sentence', 'character', etc.
27
+ position: int # Position in the original sequence
28
+ metadata: Dict[str, Any] = field(default_factory=dict)
29
+
30
+ def __post_init__(self):
31
+ # Generate deterministic ID if not provided
32
+ if not self.id:
33
+ content = f"{self.feature_type}:{self.value}:{self.position}"
34
+ object.__setattr__(self, 'id', sha256(content.encode()).hexdigest()[:16])
35
+
36
+ def to_dict(self) -> Dict[str, Any]:
37
+ return {
38
+ 'id': self.id,
39
+ 'value': self.value,
40
+ 'type': self.feature_type,
41
+ 'position': self.position,
42
+ 'metadata': self.metadata
43
+ }
44
+
45
+ @classmethod
46
+ def from_dict(cls, data: Dict[str, Any]) -> 'ElementaryFeature':
47
+ return cls(
48
+ id=data['id'],
49
+ value=data['value'],
50
+ feature_type=data['type'],
51
+ position=data['position'],
52
+ metadata=data.get('metadata', {})
53
+ )
54
+
55
+
56
+ @dataclass
57
+ class CompositeFeature:
58
+ """
59
+ A composite feature representing a structured combination of elementary
60
+ or other composite features.
61
+
62
+ Composite features form the hierarchical structure, enabling:
63
+ - Pattern recognition across multiple levels
64
+ - Unique representation of recurring structures
65
+ - Lossless reconstruction of original text
66
+ """
67
+ id: str
68
+ feature_type: str # 'sentence', 'paragraph', 'section', 'document', etc.
69
+ children: List[ElementaryFeature] = field(default_factory=list)
70
+ child_ids: List[str] = field(default_factory=list)
71
+ context: Optional[str] = None
72
+ structural_signature: str = ""
73
+ metadata: Dict[str, Any] = field(default_factory=dict)
74
+
75
+ def __post_init__(self):
76
+ # Generate deterministic signature based on children structure
77
+ if not self.structural_signature:
78
+ self._compute_signature()
79
+
80
+ def _compute_signature(self):
81
+ """Compute a unique signature for this composite feature."""
82
+ # Sort children by position for deterministic signature
83
+ sorted_children = sorted(self.children, key=lambda c: c.position)
84
+ content_parts = [f"{c.feature_type}:{c.value}" for c in sorted_children]
85
+ signature_input = f"{self.feature_type}:{'|'.join(content_parts)}"
86
+ self.structural_signature = sha256(signature_input.encode()).hexdigest()[:16]
87
+
88
+ if not self.id:
89
+ object.__setattr__(self, 'id', self.structural_signature)
90
+
91
+ def add_child(self, feature: ElementaryFeature):
92
+ """Add a child feature to this composite feature."""
93
+ self.children.append(feature)
94
+ self.child_ids.append(feature.id)
95
+ # Recompute signature after modification
96
+ self._compute_signature()
97
+
98
+ def to_dict(self) -> Dict[str, Any]:
99
+ return {
100
+ 'id': self.id,
101
+ 'type': self.feature_type,
102
+ 'children': [c.to_dict() for c in self.children],
103
+ 'child_ids': self.child_ids,
104
+ 'context': self.context,
105
+ 'signature': self.structural_signature,
106
+ 'metadata': self.metadata
107
+ }
108
+
109
+ @classmethod
110
+ def from_dict(cls, data: Dict[str, Any]) -> 'CompositeFeature':
111
+ children = [ElementaryFeature.from_dict(c) for c in data.get('children', [])]
112
+ return cls(
113
+ id=data['id'],
114
+ feature_type=data['type'],
115
+ children=children,
116
+ child_ids=data.get('child_ids', []),
117
+ context=data.get('context'),
118
+ structural_signature=data.get('signature', ''),
119
+ metadata=data.get('metadata', {})
120
+ )
121
+
122
+
123
+ @dataclass
124
+ class HolisticStructuralForm:
125
+ """
126
+ The complete Holistic Structural Form representation.
127
+
128
+ HSF is a hierarchical structure that:
129
+ - Transforms unstructured text into deterministic structures
130
+ - Enables lossless reconstruction of original text
131
+ - Supports structure-based search and matching
132
+ - Provides full traceability to source documents
133
+ """
134
+ document_id: str
135
+ title: str = ""
136
+ elementary_features: Dict[str, ElementaryFeature] = field(default_factory=dict)
137
+ composite_features: Dict[str, CompositeFeature] = field(default_factory=dict)
138
+ hierarchy: Dict[str, List[str]] = field(default_factory=dict) # parent_id -> [child_ids]
139
+ metadata: Dict[str, Any] = field(default_factory=dict)
140
+
141
+ def add_elementary_feature(self, feature: ElementaryFeature):
142
+ """Add an elementary feature to the HSF."""
143
+ self.elementary_features[feature.id] = feature
144
+
145
+ def add_composite_feature(self, feature: CompositeFeature):
146
+ """Add a composite feature to the HSF."""
147
+ self.composite_features[feature.id] = feature
148
+
149
+ def add_hierarchy(self, parent_id: str, child_ids: List[str]):
150
+ """Establish hierarchical relationship between features."""
151
+ if parent_id not in self.hierarchy:
152
+ self.hierarchy[parent_id] = []
153
+ self.hierarchy[parent_id].extend(child_ids)
154
+
155
+ def get_feature(self, feature_id: str) -> Optional[ElementaryFeature | CompositeFeature]:
156
+ """Get a feature by its ID."""
157
+ if feature_id in self.elementary_features:
158
+ return self.elementary_features[feature_id]
159
+ if feature_id in self.composite_features:
160
+ return self.composite_features[feature_id]
161
+ return None
162
+
163
+ def get_children(self, parent_id: str) -> List[ElementaryFeature | CompositeFeature]:
164
+ """Get all children of a feature."""
165
+ children_ids = self.hierarchy.get(parent_id, [])
166
+ children = []
167
+ for cid in children_ids:
168
+ feature = self.get_feature(cid)
169
+ if feature:
170
+ children.append(feature)
171
+ return children
172
+
173
+ def reconstruct_text(self) -> str:
174
+ """
175
+ Reconstruct the original text from the HSF (lossless).
176
+
177
+ Every word token records the exact source gap that precedes it in
178
+ ``metadata['sep']``. Replaying those gaps in position order returns the
179
+ input verbatim, punctuation and whitespace included.
180
+
181
+ Tokens with no recorded separator fall back to a single space. Only the
182
+ first token of each chunk added by
183
+ :meth:`StructureBuilder.build_from_chunks` relies on that fallback, so
184
+ text assembled in chunks reconstructs chunk-by-chunk, not byte-exact at
185
+ the joins.
186
+ """
187
+ tokens = sorted(
188
+ (f for f in self.elementary_features.values() if f.feature_type == 'word'),
189
+ key=lambda f: f.position,
190
+ )
191
+ body = "".join(
192
+ (f.metadata.get('sep', ' ') if isinstance(f.metadata, dict) else ' ') + f.value
193
+ for f in tokens
194
+ )
195
+ return body + self.metadata.get('trailing', '')
196
+
197
+ def get_structure_summary(self) -> Dict[str, int]:
198
+ """Get a summary of the HSF structure."""
199
+ type_counts = {}
200
+ for feat in self.composite_features.values():
201
+ ftype = feat.feature_type
202
+ type_counts[ftype] = type_counts.get(ftype, 0) + 1
203
+
204
+ return {
205
+ 'total_elementary': len(self.elementary_features),
206
+ 'total_composite': len(self.composite_features),
207
+ 'by_type': type_counts,
208
+ 'hierarchy_levels': len(self.hierarchy)
209
+ }
210
+
211
+ def to_dict(self) -> Dict[str, Any]:
212
+ return {
213
+ 'document_id': self.document_id,
214
+ 'title': self.title,
215
+ 'elementary_features': {k: v.to_dict() for k, v in self.elementary_features.items()},
216
+ 'composite_features': {k: v.to_dict() for k, v in self.composite_features.items()},
217
+ 'hierarchy': self.hierarchy,
218
+ 'metadata': self.metadata
219
+ }
220
+
221
+ @classmethod
222
+ def from_dict(cls, data: Dict[str, Any]) -> 'HolisticStructuralForm':
223
+ hsf = cls(
224
+ document_id=data['document_id'],
225
+ title=data.get('title', '')
226
+ )
227
+
228
+ for feat_data in data.get('elementary_features', {}).values():
229
+ hsf.add_elementary_feature(ElementaryFeature.from_dict(feat_data))
230
+
231
+ for feat_data in data.get('composite_features', {}).values():
232
+ hsf.add_composite_feature(CompositeFeature.from_dict(feat_data))
233
+
234
+ hsf.hierarchy = data.get('hierarchy', {})
235
+ hsf.metadata = data.get('metadata', {})
236
+
237
+ return hsf
238
+
239
+ def save(self, filepath: str):
240
+ """Save HSF to a JSON file."""
241
+ with open(filepath, 'w', encoding='utf-8') as f:
242
+ json.dump(self.to_dict(), f, indent=2)
243
+
244
+ @classmethod
245
+ def load(cls, filepath: str) -> 'HolisticStructuralForm':
246
+ """Load HSF from a JSON file."""
247
+ with open(filepath, 'r', encoding='utf-8') as f:
248
+ data = json.load(f)
249
+ return cls.from_dict(data)