entropyguard 1.22.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.
- entropyguard/__init__.py +14 -0
- entropyguard/chunking/__init__.py +13 -0
- entropyguard/chunking/splitter.py +318 -0
- entropyguard/cli/__init__.py +13 -0
- entropyguard/cli/main.py +1096 -0
- entropyguard/core/__init__.py +37 -0
- entropyguard/core/checkpoint.py +325 -0
- entropyguard/core/config_loader.py +200 -0
- entropyguard/core/config_validator.py +123 -0
- entropyguard/core/constants.py +26 -0
- entropyguard/core/error_messages.py +201 -0
- entropyguard/core/errors.py +78 -0
- entropyguard/core/exit_codes.py +39 -0
- entropyguard/core/logger.py +116 -0
- entropyguard/core/memory_profiler.py +230 -0
- entropyguard/core/metrics.py +132 -0
- entropyguard/core/pipeline.py +918 -0
- entropyguard/core/progress_tracker.py +157 -0
- entropyguard/core/resource_guards.py +296 -0
- entropyguard/core/retry.py +157 -0
- entropyguard/core/sanitization_lazy.py +165 -0
- entropyguard/core/types.py +69 -0
- entropyguard/deduplication/__init__.py +13 -0
- entropyguard/deduplication/embedder.py +102 -0
- entropyguard/deduplication/index.py +257 -0
- entropyguard/ingestion/__init__.py +11 -0
- entropyguard/ingestion/loader.py +203 -0
- entropyguard/sanitization/__init__.py +21 -0
- entropyguard/sanitization/core.py +228 -0
- entropyguard/validation/__init__.py +13 -0
- entropyguard/validation/validator.py +186 -0
- entropyguard-1.22.0.dist-info/METADATA +368 -0
- entropyguard-1.22.0.dist-info/RECORD +36 -0
- entropyguard-1.22.0.dist-info/WHEEL +4 -0
- entropyguard-1.22.0.dist-info/entry_points.txt +3 -0
- entropyguard-1.22.0.dist-info/licenses/LICENSE +23 -0
entropyguard/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""
|
|
2
|
+
EntropyGuard - AI Data Sanitation Infrastructure
|
|
3
|
+
|
|
4
|
+
A high-performance data sanitization system for enterprise environments.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
__version__ = "1.22.0"
|
|
8
|
+
__author__ = "EntropyGuard Team"
|
|
9
|
+
|
|
10
|
+
from typing import Final
|
|
11
|
+
|
|
12
|
+
# Core module exports (to be implemented)
|
|
13
|
+
__all__: Final[list[str]] = []
|
|
14
|
+
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Text chunking utilities for preparing long documents for embedding.
|
|
3
|
+
|
|
4
|
+
Provides a lightweight, dependency-free recursive splitter inspired by
|
|
5
|
+
RecursiveCharacterTextSplitter, implemented using only the Python stdlib
|
|
6
|
+
and Polars primitives.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from entropyguard.chunking.splitter import Chunker
|
|
10
|
+
|
|
11
|
+
__all__: list[str] = ["Chunker"]
|
|
12
|
+
|
|
13
|
+
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Advanced chunking utilities for splitting long texts into smaller fragments.
|
|
3
|
+
|
|
4
|
+
Design goals:
|
|
5
|
+
- No external NLP / LangChain dependencies
|
|
6
|
+
- Flexible recursive splitting with custom separators
|
|
7
|
+
- Hard fallback for CJK languages (Chinese, Japanese, Korean) and other languages without whitespace
|
|
8
|
+
- Polars-native integration: chunking a DataFrame via explode() while preserving metadata
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import codecs
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Callable, Iterable, Sequence
|
|
16
|
+
|
|
17
|
+
import polars as pl
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Chunker:
|
|
22
|
+
"""
|
|
23
|
+
Advanced recursive text chunker for RAG-style pipelines.
|
|
24
|
+
|
|
25
|
+
Splits text into overlapping character windows using a recursive,
|
|
26
|
+
delimiter-aware strategy with hard fallback for languages without whitespace.
|
|
27
|
+
|
|
28
|
+
Features:
|
|
29
|
+
- Custom separator hierarchy (default: paragraphs, lines, words, characters)
|
|
30
|
+
- Recursive splitting: tries each separator level before falling back
|
|
31
|
+
- Hard character-level splitting for CJK languages and continuous text
|
|
32
|
+
- Configurable length function (default: len, can be extended to tokenizers)
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
chunk_size: int = 512
|
|
36
|
+
chunk_overlap: int = 50
|
|
37
|
+
separators: list[str] = field(default_factory=lambda: ["\n\n", "\n", " ", ""])
|
|
38
|
+
length_function: Callable[[str], int] = field(default_factory=lambda: len)
|
|
39
|
+
|
|
40
|
+
def __post_init__(self) -> None:
|
|
41
|
+
"""Validate configuration parameters."""
|
|
42
|
+
if self.chunk_size <= 0:
|
|
43
|
+
raise ValueError("chunk_size must be > 0")
|
|
44
|
+
if self.chunk_overlap < 0:
|
|
45
|
+
raise ValueError("chunk_overlap must be >= 0")
|
|
46
|
+
if self.chunk_overlap >= self.chunk_size:
|
|
47
|
+
raise ValueError("chunk_overlap must be smaller than chunk_size")
|
|
48
|
+
if not self.separators:
|
|
49
|
+
raise ValueError("separators list cannot be empty")
|
|
50
|
+
|
|
51
|
+
# ---- Core text API -------------------------------------------------
|
|
52
|
+
|
|
53
|
+
def split_text(self, text: str) -> list[str]:
|
|
54
|
+
"""
|
|
55
|
+
Split a single text into chunks with overlap.
|
|
56
|
+
|
|
57
|
+
Algorithm:
|
|
58
|
+
1. Recursively split on separators in order (largest to smallest).
|
|
59
|
+
2. If segments are still too large, try next separator level.
|
|
60
|
+
3. Merge small segments back together up to chunk_size.
|
|
61
|
+
4. Apply overlap between consecutive chunks.
|
|
62
|
+
5. Hard fallback: if text still exceeds chunk_size (CJK, DNA, Base64),
|
|
63
|
+
split character-by-character.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
text: Input text to split
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
List of text chunks, each <= chunk_size characters
|
|
70
|
+
"""
|
|
71
|
+
if not text:
|
|
72
|
+
return []
|
|
73
|
+
|
|
74
|
+
# Step 1: Recursive splitting
|
|
75
|
+
segments = self._split_recursively(text, self.separators)
|
|
76
|
+
|
|
77
|
+
# Step 2: Merge segments with overlap
|
|
78
|
+
chunks = self._merge_segments_with_overlap(segments)
|
|
79
|
+
|
|
80
|
+
return chunks
|
|
81
|
+
|
|
82
|
+
# ---- Polars integration --------------------------------------------
|
|
83
|
+
|
|
84
|
+
def chunk_dataframe(
|
|
85
|
+
self,
|
|
86
|
+
df: pl.DataFrame | pl.LazyFrame,
|
|
87
|
+
text_col: str,
|
|
88
|
+
) -> pl.DataFrame | pl.LazyFrame:
|
|
89
|
+
"""
|
|
90
|
+
Chunk a Polars DataFrame/LazyFrame by exploding a text column into chunks.
|
|
91
|
+
|
|
92
|
+
Each input row becomes N rows (one per chunk) while all other columns,
|
|
93
|
+
including IDs or original indexes, are preserved and duplicated as needed.
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
df: Input DataFrame or LazyFrame
|
|
97
|
+
text_col: Name of the text column to chunk
|
|
98
|
+
|
|
99
|
+
Returns:
|
|
100
|
+
Chunked DataFrame or LazyFrame with exploded text column
|
|
101
|
+
"""
|
|
102
|
+
if text_col not in df.columns: # type: ignore[attr-defined]
|
|
103
|
+
raise ValueError(f"Text column '{text_col}' not found in DataFrame")
|
|
104
|
+
|
|
105
|
+
def _split(value: str | None) -> list[str]:
|
|
106
|
+
if value is None:
|
|
107
|
+
return []
|
|
108
|
+
return self.split_text(str(value))
|
|
109
|
+
|
|
110
|
+
if isinstance(df, pl.LazyFrame):
|
|
111
|
+
chunked = df.with_columns(
|
|
112
|
+
pl.col(text_col).map_elements(
|
|
113
|
+
_split,
|
|
114
|
+
return_dtype=pl.List(pl.Utf8),
|
|
115
|
+
)
|
|
116
|
+
).explode(text_col)
|
|
117
|
+
return chunked
|
|
118
|
+
|
|
119
|
+
# Eager DataFrame
|
|
120
|
+
chunked_df = df.with_columns(
|
|
121
|
+
pl.col(text_col).map_elements(
|
|
122
|
+
_split,
|
|
123
|
+
return_dtype=pl.List(pl.Utf8),
|
|
124
|
+
)
|
|
125
|
+
).explode(text_col)
|
|
126
|
+
|
|
127
|
+
return chunked_df
|
|
128
|
+
|
|
129
|
+
# ---- Internal helpers ----------------------------------------------
|
|
130
|
+
|
|
131
|
+
def _split_recursively(
|
|
132
|
+
self, text: str, separators: Sequence[str]
|
|
133
|
+
) -> list[str]:
|
|
134
|
+
"""
|
|
135
|
+
Recursively split text by separators, trying each level in order.
|
|
136
|
+
|
|
137
|
+
Large segments are broken down using the current separator.
|
|
138
|
+
If segments are still too large, recursively try the next separator.
|
|
139
|
+
Small segments are preserved to maintain semantic structure.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
text: Text to split
|
|
143
|
+
separators: List of separators to try (in order, largest to smallest)
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
List of text segments, each <= chunk_size (or as small as possible)
|
|
147
|
+
"""
|
|
148
|
+
# Base case: text is small enough
|
|
149
|
+
if self.length_function(text) <= self.chunk_size:
|
|
150
|
+
return [text.strip()] if text.strip() else []
|
|
151
|
+
|
|
152
|
+
# Try each separator level
|
|
153
|
+
for i, sep in enumerate(separators):
|
|
154
|
+
# Hard fallback: empty separator means character-level splitting
|
|
155
|
+
if sep == "":
|
|
156
|
+
return self._hard_split(text)
|
|
157
|
+
|
|
158
|
+
# Split by current separator
|
|
159
|
+
parts = text.split(sep)
|
|
160
|
+
|
|
161
|
+
# If separator not found, try next one
|
|
162
|
+
if len(parts) == 1:
|
|
163
|
+
continue
|
|
164
|
+
|
|
165
|
+
# Recursively split each part that's still too large
|
|
166
|
+
segments: list[str] = []
|
|
167
|
+
for part in parts:
|
|
168
|
+
part = part.strip()
|
|
169
|
+
if not part:
|
|
170
|
+
continue
|
|
171
|
+
|
|
172
|
+
if self.length_function(part) <= self.chunk_size:
|
|
173
|
+
segments.append(part)
|
|
174
|
+
else:
|
|
175
|
+
# Recursively try remaining separators
|
|
176
|
+
remaining_seps = separators[i + 1 :]
|
|
177
|
+
if remaining_seps:
|
|
178
|
+
segments.extend(
|
|
179
|
+
self._split_recursively(part, remaining_seps)
|
|
180
|
+
)
|
|
181
|
+
else:
|
|
182
|
+
# No more separators, hard split
|
|
183
|
+
segments.extend(self._hard_split(part))
|
|
184
|
+
|
|
185
|
+
# If we got good segments, return them
|
|
186
|
+
if segments:
|
|
187
|
+
return segments
|
|
188
|
+
|
|
189
|
+
# Fallback: if all separators failed, hard split
|
|
190
|
+
return self._hard_split(text)
|
|
191
|
+
|
|
192
|
+
def _hard_split(self, text: str) -> list[str]:
|
|
193
|
+
"""
|
|
194
|
+
Hard character-level split for CJK languages and continuous text.
|
|
195
|
+
|
|
196
|
+
Used when:
|
|
197
|
+
- No separators are available (empty separator list)
|
|
198
|
+
- All separators failed to split the text (e.g., Chinese without spaces)
|
|
199
|
+
- Text is continuous (DNA sequences, Base64, etc.)
|
|
200
|
+
|
|
201
|
+
Args:
|
|
202
|
+
text: Text to split character-by-character
|
|
203
|
+
|
|
204
|
+
Returns:
|
|
205
|
+
List of fixed-size chunks (exactly chunk_size, except possibly the last)
|
|
206
|
+
"""
|
|
207
|
+
chunks: list[str] = []
|
|
208
|
+
start = 0
|
|
209
|
+
text_len = self.length_function(text)
|
|
210
|
+
|
|
211
|
+
while start < text_len:
|
|
212
|
+
end = min(start + self.chunk_size, text_len)
|
|
213
|
+
chunk = text[start:end]
|
|
214
|
+
if chunk.strip(): # Skip empty chunks
|
|
215
|
+
chunks.append(chunk)
|
|
216
|
+
start = end
|
|
217
|
+
|
|
218
|
+
return chunks if chunks else [text] # Ensure at least one chunk
|
|
219
|
+
|
|
220
|
+
def _merge_segments_with_overlap(self, segments: Iterable[str]) -> list[str]:
|
|
221
|
+
"""
|
|
222
|
+
Merge small segments into fixed-size overlapping chunks.
|
|
223
|
+
|
|
224
|
+
Greedily combines segments up to chunk_size, then starts a new chunk
|
|
225
|
+
with overlap from the previous one.
|
|
226
|
+
|
|
227
|
+
Args:
|
|
228
|
+
segments: Iterable of text segments to merge
|
|
229
|
+
|
|
230
|
+
Returns:
|
|
231
|
+
List of chunks with overlap
|
|
232
|
+
"""
|
|
233
|
+
chunks: list[str] = []
|
|
234
|
+
current_chunk = ""
|
|
235
|
+
|
|
236
|
+
for seg in segments:
|
|
237
|
+
seg = seg.strip()
|
|
238
|
+
if not seg:
|
|
239
|
+
continue
|
|
240
|
+
|
|
241
|
+
seg_len = self.length_function(seg)
|
|
242
|
+
|
|
243
|
+
# If segment alone exceeds chunk_size, hard split it
|
|
244
|
+
if seg_len > self.chunk_size:
|
|
245
|
+
# Flush current chunk first
|
|
246
|
+
if current_chunk:
|
|
247
|
+
chunks.append(current_chunk)
|
|
248
|
+
current_chunk = ""
|
|
249
|
+
|
|
250
|
+
# Hard split the oversized segment
|
|
251
|
+
hard_chunks = self._hard_split(seg)
|
|
252
|
+
for i, hc in enumerate(hard_chunks):
|
|
253
|
+
if i == 0 and current_chunk:
|
|
254
|
+
# Try to merge first hard chunk with current
|
|
255
|
+
if (
|
|
256
|
+
self.length_function(current_chunk)
|
|
257
|
+
+ self.length_function(hc)
|
|
258
|
+
<= self.chunk_size
|
|
259
|
+
):
|
|
260
|
+
current_chunk = f"{current_chunk} {hc}".strip()
|
|
261
|
+
continue
|
|
262
|
+
chunks.append(hc)
|
|
263
|
+
continue
|
|
264
|
+
|
|
265
|
+
# Try to add segment to current chunk
|
|
266
|
+
current_len = self.length_function(current_chunk)
|
|
267
|
+
separator_len = 1 if current_chunk else 0
|
|
268
|
+
combined_len = current_len + separator_len + seg_len
|
|
269
|
+
|
|
270
|
+
if combined_len <= self.chunk_size:
|
|
271
|
+
# Can fit, add to current chunk
|
|
272
|
+
if current_chunk:
|
|
273
|
+
current_chunk = f"{current_chunk} {seg}".strip()
|
|
274
|
+
else:
|
|
275
|
+
current_chunk = seg
|
|
276
|
+
else:
|
|
277
|
+
# Doesn't fit, start new chunk with overlap
|
|
278
|
+
if current_chunk:
|
|
279
|
+
chunks.append(current_chunk)
|
|
280
|
+
|
|
281
|
+
# Calculate overlap prefix (character-level, no separator added)
|
|
282
|
+
if self.chunk_overlap > 0 and current_len > self.chunk_overlap:
|
|
283
|
+
overlap_prefix = current_chunk[-self.chunk_overlap :]
|
|
284
|
+
# Merge overlap with new segment (no separator, direct concatenation)
|
|
285
|
+
overlap_with_seg = f"{overlap_prefix}{seg}".strip()
|
|
286
|
+
if self.length_function(overlap_with_seg) <= self.chunk_size:
|
|
287
|
+
current_chunk = overlap_with_seg
|
|
288
|
+
else:
|
|
289
|
+
# Overlap + segment too large, just use segment
|
|
290
|
+
current_chunk = seg
|
|
291
|
+
else:
|
|
292
|
+
current_chunk = seg
|
|
293
|
+
else:
|
|
294
|
+
current_chunk = seg
|
|
295
|
+
|
|
296
|
+
# Flush remaining chunk
|
|
297
|
+
if current_chunk:
|
|
298
|
+
chunks.append(current_chunk)
|
|
299
|
+
|
|
300
|
+
return chunks
|
|
301
|
+
|
|
302
|
+
@staticmethod
|
|
303
|
+
def decode_separator(sep: str) -> str:
|
|
304
|
+
"""
|
|
305
|
+
Decode separator string from CLI (handles escape sequences like \\n).
|
|
306
|
+
|
|
307
|
+
Args:
|
|
308
|
+
sep: Separator string from command line (may contain \\n, \\t, etc.)
|
|
309
|
+
|
|
310
|
+
Returns:
|
|
311
|
+
Decoded separator string
|
|
312
|
+
"""
|
|
313
|
+
try:
|
|
314
|
+
# Try to decode escape sequences
|
|
315
|
+
return codecs.decode(sep, "unicode_escape")
|
|
316
|
+
except (UnicodeDecodeError, ValueError):
|
|
317
|
+
# If decoding fails, return as-is
|
|
318
|
+
return sep
|