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.
- structurerag/__init__.py +56 -0
- structurerag/core/__init__.py +16 -0
- structurerag/core/builder.py +309 -0
- structurerag/core/hsf.py +249 -0
- structurerag/core/reasoner.py +305 -0
- structurerag/grounding/__init__.py +20 -0
- structurerag/grounding/citation.py +173 -0
- structurerag/grounding/reranker.py +160 -0
- structurerag/grounding/retriever.py +980 -0
- structurerag/grounding/verifier.py +774 -0
- structurerag/loaders/__init__.py +6 -0
- structurerag/loaders/pdf.py +36 -0
- structurerag/loaders/text.py +16 -0
- structurerag/semantic.py +307 -0
- structurerag/structurerag.py +455 -0
- structurerag-0.1.0.dist-info/METADATA +186 -0
- structurerag-0.1.0.dist-info/RECORD +20 -0
- structurerag-0.1.0.dist-info/WHEEL +5 -0
- structurerag-0.1.0.dist-info/licenses/LICENSE +21 -0
- structurerag-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""PDF file loader."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def load_pdf(filepath: str) -> str:
|
|
5
|
+
"""
|
|
6
|
+
Load text content from a PDF file.
|
|
7
|
+
|
|
8
|
+
Requires pdfplumber or PyPDF2 to be installed. The first that is present is
|
|
9
|
+
used; pdfplumber is preferred because it preserves layout better.
|
|
10
|
+
|
|
11
|
+
Args:
|
|
12
|
+
filepath: Path to the PDF file
|
|
13
|
+
|
|
14
|
+
Returns:
|
|
15
|
+
Extracted text content
|
|
16
|
+
"""
|
|
17
|
+
try:
|
|
18
|
+
import pdfplumber
|
|
19
|
+
with pdfplumber.open(filepath) as pdf:
|
|
20
|
+
return "\n\n".join(page.extract_text() or "" for page in pdf.pages)
|
|
21
|
+
except ImportError:
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
try:
|
|
25
|
+
import PyPDF2
|
|
26
|
+
with open(filepath, 'rb') as f:
|
|
27
|
+
reader = PyPDF2.PdfReader(f)
|
|
28
|
+
return "\n\n".join(page.extract_text() or "" for page in reader.pages)
|
|
29
|
+
except ImportError:
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
raise ImportError(
|
|
33
|
+
"No PDF library found. Install one of:\n"
|
|
34
|
+
" pip install pdfplumber\n"
|
|
35
|
+
" pip install PyPDF2"
|
|
36
|
+
)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Text file loader."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def load_text_file(filepath: str, encoding: str = 'utf-8') -> str:
|
|
5
|
+
"""
|
|
6
|
+
Load text content from a file.
|
|
7
|
+
|
|
8
|
+
Args:
|
|
9
|
+
filepath: Path to the text file
|
|
10
|
+
encoding: File encoding (default: utf-8)
|
|
11
|
+
|
|
12
|
+
Returns:
|
|
13
|
+
File content as string
|
|
14
|
+
"""
|
|
15
|
+
with open(filepath, 'r', encoding=encoding) as f:
|
|
16
|
+
return f.read()
|
structurerag/semantic.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Semantic Expansion Module — merged v1/v2/v3.
|
|
3
|
+
|
|
4
|
+
Provides deterministic synonym recognition, phrase normalization,
|
|
5
|
+
and acronym expansion while maintaining core deterministic properties.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
from typing import Dict, List, Set, Tuple, Any
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
# ─── Synonym Handling ────────────────────────────────────────────────────────
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class SynonymGroup:
|
|
19
|
+
"""A group of semantically equivalent terms with optional context awareness."""
|
|
20
|
+
canonical: str
|
|
21
|
+
synonyms: Set[str] = field(default_factory=set)
|
|
22
|
+
contexts: Dict[str, Set[str]] = field(default_factory=dict)
|
|
23
|
+
|
|
24
|
+
def all_terms(self) -> Set[str]:
|
|
25
|
+
return {self.canonical} | self.synonyms
|
|
26
|
+
|
|
27
|
+
def get_relevant(self, context: str = None) -> Set[str]:
|
|
28
|
+
if context and context in self.contexts:
|
|
29
|
+
return {self.canonical} | self.contexts[context]
|
|
30
|
+
return self.all_terms()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class SemanticExpander:
|
|
34
|
+
"""Deterministic semantic expansion with context-aware synonyms and morphology."""
|
|
35
|
+
|
|
36
|
+
def __init__(self):
|
|
37
|
+
self.synonym_groups: Dict[str, SynonymGroup] = {}
|
|
38
|
+
# Each rule is (suffix, replacement, min_stem_length).
|
|
39
|
+
self.morphology_rules: List[Tuple[str, str, int]] = []
|
|
40
|
+
|
|
41
|
+
def add_synonym(self, canonical: str, synonym: str, context: str = None):
|
|
42
|
+
canonical = canonical.lower()
|
|
43
|
+
synonym = synonym.lower()
|
|
44
|
+
if canonical not in self.synonym_groups:
|
|
45
|
+
self.synonym_groups[canonical] = SynonymGroup(canonical=canonical)
|
|
46
|
+
group = self.synonym_groups[canonical]
|
|
47
|
+
group.synonyms.add(synonym)
|
|
48
|
+
if synonym not in self.synonym_groups:
|
|
49
|
+
self.synonym_groups[synonym] = SynonymGroup(canonical=canonical, synonyms={canonical})
|
|
50
|
+
if context:
|
|
51
|
+
group.contexts.setdefault(context, set()).add(synonym)
|
|
52
|
+
|
|
53
|
+
def add_morphology_rule(self, suffix: str, replacement: str = "",
|
|
54
|
+
min_stem_length: int = 3):
|
|
55
|
+
"""
|
|
56
|
+
Register a suffix rule.
|
|
57
|
+
|
|
58
|
+
A rule applies when the term ends with ``suffix`` and what remains is at
|
|
59
|
+
least ``min_stem_length`` characters. The guard stops short common words
|
|
60
|
+
from being shredded ("is" -> "i").
|
|
61
|
+
"""
|
|
62
|
+
self.morphology_rules.append((suffix, replacement, min_stem_length))
|
|
63
|
+
|
|
64
|
+
def morphological_variants(self, term: str) -> Set[str]:
|
|
65
|
+
"""Suffix-stripped forms of a term. Rules only ever shorten, never extend."""
|
|
66
|
+
term = term.lower()
|
|
67
|
+
variants = set()
|
|
68
|
+
for suffix, replacement, min_stem_length in self.morphology_rules:
|
|
69
|
+
if not suffix or len(term) <= len(suffix) or not term.endswith(suffix):
|
|
70
|
+
continue
|
|
71
|
+
stem = term[:-len(suffix)]
|
|
72
|
+
if len(stem) < min_stem_length:
|
|
73
|
+
continue
|
|
74
|
+
variants.add(stem + replacement)
|
|
75
|
+
return variants
|
|
76
|
+
|
|
77
|
+
def expand_term(self, term: str, context: str = None) -> Set[str]:
|
|
78
|
+
term = term.lower()
|
|
79
|
+
results = {term}
|
|
80
|
+
if term in self.synonym_groups:
|
|
81
|
+
results.update(self.synonym_groups[term].get_relevant(context))
|
|
82
|
+
results.update(self.morphological_variants(term))
|
|
83
|
+
return results
|
|
84
|
+
|
|
85
|
+
def expand_query(self, query: str, context: str = None) -> Tuple[List[str], Dict[str, List[str]]]:
|
|
86
|
+
tokens = re.findall(r'\b\w+\b', query.lower())
|
|
87
|
+
expanded_terms = []
|
|
88
|
+
expansion_map = {}
|
|
89
|
+
for token in tokens:
|
|
90
|
+
# sorted() makes the expansion order deterministic across
|
|
91
|
+
# processes: expand_term returns a set, whose iteration order
|
|
92
|
+
# follows the hash seed.
|
|
93
|
+
expansions = sorted(self.expand_term(token, context))
|
|
94
|
+
expanded_terms.extend(expansions)
|
|
95
|
+
expansion_map[token] = expansions
|
|
96
|
+
seen = set()
|
|
97
|
+
unique = []
|
|
98
|
+
for term in expanded_terms:
|
|
99
|
+
if term not in seen:
|
|
100
|
+
seen.add(term)
|
|
101
|
+
unique.append(term)
|
|
102
|
+
return unique, expansion_map
|
|
103
|
+
|
|
104
|
+
def load_from_dict(self, synonym_dict: Dict[str, Any]):
|
|
105
|
+
for canonical, data in synonym_dict.items():
|
|
106
|
+
if isinstance(data, dict):
|
|
107
|
+
for synonym in data.get('synonyms', []):
|
|
108
|
+
self.add_synonym(canonical, synonym)
|
|
109
|
+
for ctx, ctx_synonyms in data.get('contexts', {}).items():
|
|
110
|
+
for synonym in ctx_synonyms:
|
|
111
|
+
self.add_synonym(canonical, synonym, context=ctx)
|
|
112
|
+
else:
|
|
113
|
+
for synonym in data:
|
|
114
|
+
self.add_synonym(canonical, synonym)
|
|
115
|
+
|
|
116
|
+
def load_from_file(self, filepath: str):
|
|
117
|
+
with open(filepath, 'r', encoding='utf-8') as f:
|
|
118
|
+
self.load_from_dict(json.load(f))
|
|
119
|
+
|
|
120
|
+
def save_to_file(self, filepath: str):
|
|
121
|
+
data = {}
|
|
122
|
+
for canonical, group in self.synonym_groups.items():
|
|
123
|
+
data[canonical] = list(group.synonyms - {canonical})
|
|
124
|
+
with open(filepath, 'w', encoding='utf-8') as f:
|
|
125
|
+
json.dump(data, f, indent=2, sort_keys=True)
|
|
126
|
+
|
|
127
|
+
def get_statistics(self) -> Dict[str, int]:
|
|
128
|
+
total_groups = len(self.synonym_groups)
|
|
129
|
+
total_synonyms = sum(len(g.synonyms) for g in self.synonym_groups.values())
|
|
130
|
+
return {
|
|
131
|
+
'total_groups': total_groups,
|
|
132
|
+
'total_synonyms': total_synonyms,
|
|
133
|
+
'average_synonyms_per_group': total_synonyms / max(1, total_groups)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
# ─── Phrase Matching & Normalization ─────────────────────────────────────────
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass
|
|
141
|
+
class PhrasePattern:
|
|
142
|
+
"""A recognized phrase pattern with normalization."""
|
|
143
|
+
pattern: str
|
|
144
|
+
canonical_form: str
|
|
145
|
+
synonyms: Set[str] = field(default_factory=set)
|
|
146
|
+
priority: int = 0
|
|
147
|
+
|
|
148
|
+
def matches(self, text: str) -> bool:
|
|
149
|
+
text_lower = text.lower()
|
|
150
|
+
return self.pattern.lower() in text_lower or any(s in text_lower for s in self.synonyms)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class PhraseMatcher:
|
|
154
|
+
"""Pattern matcher for phrase normalization, acronym expansion, and synonyms."""
|
|
155
|
+
|
|
156
|
+
def __init__(self):
|
|
157
|
+
self.patterns: Dict[str, PhrasePattern] = {}
|
|
158
|
+
self.acronym_map: Dict[str, str] = {}
|
|
159
|
+
self.full_to_acronym: Dict[str, str] = {}
|
|
160
|
+
|
|
161
|
+
def add_pattern(self, pattern: str, canonical: str = None,
|
|
162
|
+
synonyms: List[str] = None, priority: int = 0):
|
|
163
|
+
canonical = canonical or pattern
|
|
164
|
+
self.patterns[pattern.lower()] = PhrasePattern(
|
|
165
|
+
pattern=pattern, canonical_form=canonical,
|
|
166
|
+
synonyms=set(s.lower() for s in (synonyms or [])), priority=priority
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
def add_acronym(self, full_form: str, acronym: str):
|
|
170
|
+
# Keys are stored lowercased: queries are lowercased before lookup,
|
|
171
|
+
# so an uppercase key could never match (see normalize_query).
|
|
172
|
+
self.acronym_map[acronym.lower()] = full_form.lower()
|
|
173
|
+
self.full_to_acronym[full_form.lower()] = acronym.upper()
|
|
174
|
+
|
|
175
|
+
def find_patterns(self, text: str) -> List[Tuple[str, str, float]]:
|
|
176
|
+
text_lower = text.lower()
|
|
177
|
+
matches = []
|
|
178
|
+
for pattern, pp in self.patterns.items():
|
|
179
|
+
if pp.matches(text_lower):
|
|
180
|
+
if pattern in text_lower:
|
|
181
|
+
confidence = 1.0
|
|
182
|
+
elif any(s in text_lower for s in pp.synonyms):
|
|
183
|
+
confidence = 0.85
|
|
184
|
+
else:
|
|
185
|
+
confidence = 0.7
|
|
186
|
+
matches.append((pattern, pp.canonical_form, confidence))
|
|
187
|
+
matches.sort(key=lambda x: (self.patterns[x[0]].priority, x[2]), reverse=True)
|
|
188
|
+
return matches
|
|
189
|
+
|
|
190
|
+
@staticmethod
|
|
191
|
+
def _replace_whole_word(text: str, term: str, replacement: str) -> str:
|
|
192
|
+
"""Replace ``term`` only at word boundaries ('rag' never hits 'storage')."""
|
|
193
|
+
return re.sub(rf'\b{re.escape(term)}\b', replacement, text)
|
|
194
|
+
|
|
195
|
+
def normalize_query(self, query: str) -> Tuple[str, List[Tuple[str, str]]]:
|
|
196
|
+
# Expand acronyms first. Keys are lowercase and iterated in sorted
|
|
197
|
+
# order so the result is identical in every process, regardless of
|
|
198
|
+
# the hash seed.
|
|
199
|
+
normalized = query.lower()
|
|
200
|
+
replacements = []
|
|
201
|
+
for acronym in sorted(self.acronym_map):
|
|
202
|
+
full_form = self.acronym_map[acronym]
|
|
203
|
+
if re.search(rf'\b{re.escape(acronym)}\b', normalized):
|
|
204
|
+
normalized = self._replace_whole_word(normalized, acronym, full_form)
|
|
205
|
+
replacements.append((acronym, full_form))
|
|
206
|
+
# Apply phrase patterns
|
|
207
|
+
for original, canonical, _ in self.find_patterns(normalized):
|
|
208
|
+
if original != canonical and re.search(rf'\b{re.escape(original)}\b', normalized):
|
|
209
|
+
normalized = self._replace_whole_word(normalized, original, canonical)
|
|
210
|
+
replacements.append((original, canonical))
|
|
211
|
+
return normalized, replacements
|
|
212
|
+
|
|
213
|
+
def expand_query_with_patterns(self, query: str) -> Tuple[str, List[Tuple[str, str]]]:
|
|
214
|
+
return self.normalize_query(query)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
# ─── Default Dictionaries ────────────────────────────────────────────────────
|
|
218
|
+
|
|
219
|
+
DEFAULT_SYNONYM_DICT = {
|
|
220
|
+
"retrieval": {"synonyms": ["search", "find", "locate", "query", "fetch"],
|
|
221
|
+
"contexts": {"database": ["query", "fetch"], "information": ["search", "find"]}},
|
|
222
|
+
"generation": ["create", "produce", "generate", "synthesize"],
|
|
223
|
+
"embedding": ["vector", "representation", "encoding", "projection"],
|
|
224
|
+
"deterministic": ["predictable", "consistent", "reproducible"],
|
|
225
|
+
"structure": ["format", "organization", "hierarchy"],
|
|
226
|
+
"matching": ["compare", "match", "align"],
|
|
227
|
+
"similarity": ["resemblance", "likeness", "comparable"],
|
|
228
|
+
"semantic": ["meaning", "interpretation", "context"],
|
|
229
|
+
"system": {"synonyms": ["platform", "framework", "architecture", "solution"],
|
|
230
|
+
"contexts": {"software": ["platform", "framework"], "design": ["architecture"]}},
|
|
231
|
+
"method": ["approach", "technique", "way", "strategy"],
|
|
232
|
+
"process": ["procedure", "workflow", "operation", "mechanism"],
|
|
233
|
+
"feature": ["characteristic", "attribute", "property", "aspect"],
|
|
234
|
+
"component": ["part", "element", "module"],
|
|
235
|
+
"model": ["framework", "structure", "representation"],
|
|
236
|
+
"transform": ["convert", "change", "modify"],
|
|
237
|
+
"analyze": ["examine", "inspect", "evaluate"],
|
|
238
|
+
"identify": ["recognize", "detect", "find"],
|
|
239
|
+
"extract": ["retrieve", "pull", "obtain"],
|
|
240
|
+
"accurate": ["precise", "correct", "exact"],
|
|
241
|
+
"efficient": ["fast", "quick", "optimized"],
|
|
242
|
+
"reliable": ["consistent", "dependable", "stable"],
|
|
243
|
+
"document": ["text", "content", "passage", "file"],
|
|
244
|
+
"sentence": ["statement", "clause", "utterance"],
|
|
245
|
+
"paragraph": ["section", "block", "chunk", "segment"],
|
|
246
|
+
"word": ["term", "token", "string"],
|
|
247
|
+
"use": ["utilize", "employ", "apply", "leverage"],
|
|
248
|
+
"provide": ["offer", "give", "deliver", "supply"],
|
|
249
|
+
"enable": ["allow", "permit", "facilitate"],
|
|
250
|
+
"fast": ["quick", "rapid", "efficient", "swift"],
|
|
251
|
+
"traceability": ["tracking", "audit trail", "lineage"],
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
DEFAULT_PATTERNS = {
|
|
255
|
+
"structure based": {"canonical": "structure-based", "priority": 10},
|
|
256
|
+
"embedding based": {"canonical": "embedding-based", "priority": 10},
|
|
257
|
+
"vector similarity": {"canonical": "vector-similarity", "synonyms": ["cosine similarity", "semantic similarity"]},
|
|
258
|
+
"machine learning": {"canonical": "ml", "synonyms": ["ml", "ai", "deep learning"]},
|
|
259
|
+
"natural language processing": {"canonical": "nlp", "synonyms": ["nlp", "language processing"]},
|
|
260
|
+
"information retrieval": {"canonical": "ir", "synonyms": ["ir", "document retrieval"]},
|
|
261
|
+
"retrieval augmented generation": {"canonical": "rag", "synonyms": ["rag"]},
|
|
262
|
+
"knowledge base": {"canonical": "knowledge-base", "synonyms": ["kb", "database", "repository"]},
|
|
263
|
+
"hallucination detection": {"canonical": "hallucination-detection", "synonyms": ["hallucination", "verification"]},
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
DEFAULT_ACRONYMS = [
|
|
267
|
+
("retrieval augmented generation", "RAG"),
|
|
268
|
+
("machine learning", "ML"),
|
|
269
|
+
("natural language processing", "NLP"),
|
|
270
|
+
("information retrieval", "IR"),
|
|
271
|
+
("large language model", "LLM"),
|
|
272
|
+
("artificial intelligence", "AI"),
|
|
273
|
+
("deep learning", "DL"),
|
|
274
|
+
("knowledge base", "KB"),
|
|
275
|
+
("state of the art", "SOTA"),
|
|
276
|
+
]
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
# ─── Factory Functions ───────────────────────────────────────────────────────
|
|
280
|
+
|
|
281
|
+
def create_default_expander() -> SemanticExpander:
|
|
282
|
+
expander = SemanticExpander()
|
|
283
|
+
expander.load_from_dict(DEFAULT_SYNONYM_DICT)
|
|
284
|
+
# Longest suffix first, so "es" wins over "s" where both apply.
|
|
285
|
+
expander.add_morphology_rule("es", "")
|
|
286
|
+
expander.add_morphology_rule("s", "")
|
|
287
|
+
return expander
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def create_default_phrase_matcher() -> PhraseMatcher:
|
|
291
|
+
matcher = PhraseMatcher()
|
|
292
|
+
for pattern, config in DEFAULT_PATTERNS.items():
|
|
293
|
+
matcher.add_pattern(
|
|
294
|
+
pattern, canonical=config.get("canonical", pattern),
|
|
295
|
+
synonyms=config.get("synonyms", []), priority=config.get("priority", 0)
|
|
296
|
+
)
|
|
297
|
+
for full_form, acronym in DEFAULT_ACRONYMS:
|
|
298
|
+
matcher.add_acronym(full_form, acronym)
|
|
299
|
+
return matcher
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
# ─── Backwards compatibility aliases ─────────────────────────────────────────
|
|
303
|
+
|
|
304
|
+
EnhancedSemanticExpander = SemanticExpander
|
|
305
|
+
EnhancedPhraseMatcher = PhraseMatcher
|
|
306
|
+
create_enhanced_expander = create_default_expander
|
|
307
|
+
create_enhanced_phrase_matcher = create_default_phrase_matcher
|