preembed 0.2.0__cp313-cp313-win_amd64.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.
preembed/__init__.py ADDED
@@ -0,0 +1,56 @@
1
+ """Python API for preembed."""
2
+
3
+ __all__ = [
4
+ "Chunk",
5
+ "ChunkMetadata",
6
+ "DedupeResult",
7
+ "Pipeline",
8
+ "PipelineResult",
9
+ "PipelineStats",
10
+ "PreembedError",
11
+ "Scorer",
12
+ "Tokenizer",
13
+ "chunk_spans",
14
+ "chunk_text",
15
+ "clean_text",
16
+ "clear_cleaners",
17
+ "clear_score_rules",
18
+ "clear_scorers",
19
+ "dedupe_chunks",
20
+ "register_cleaner",
21
+ "register_score_rule",
22
+ "register_scorer",
23
+ "score_chunks",
24
+ ]
25
+
26
+ from .pipeline import Pipeline
27
+ from .text import (
28
+ PreembedError,
29
+ chunk_spans,
30
+ chunk_text,
31
+ clean_text,
32
+ clear_cleaners,
33
+ clear_score_rules,
34
+ clear_scorers,
35
+ dedupe_chunks,
36
+ register_cleaner,
37
+ register_score_rule,
38
+ register_scorer,
39
+ score_chunks,
40
+ )
41
+ from .types import (
42
+ Chunk,
43
+ ChunkMetadata,
44
+ DedupeResult,
45
+ PipelineResult,
46
+ PipelineStats,
47
+ Scorer,
48
+ Tokenizer,
49
+ )
50
+
51
+ try:
52
+ from importlib.metadata import version as _get_version
53
+
54
+ __version__ = _get_version("preembed")
55
+ except Exception:
56
+ __version__ = "0.0.0"
preembed/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Allow running the preembed CLI with ``python -m preembed``."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
preembed/cli.py ADDED
@@ -0,0 +1,421 @@
1
+ """Command-line interface for validating and exporting corpora with preembed."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from collections import Counter
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from . import __version__
13
+ from .pipeline import Pipeline, _is_supported_text_file
14
+ from .types import Chunk, PipelineResult, Tokenizer
15
+
16
+ EXIT_OK = 0
17
+ EXIT_THRESHOLD = 1
18
+ EXIT_USAGE = 2
19
+
20
+ _WORST_CHUNK_COUNT = 5
21
+ _PREVIEW_CHARS = 80
22
+ _TOP_WARNING_COUNT = 5
23
+
24
+
25
+ def _positive_int(value: str) -> int:
26
+ try:
27
+ number = int(value)
28
+ except ValueError:
29
+ raise argparse.ArgumentTypeError(f"expected an integer, got {value!r}")
30
+ if number <= 0:
31
+ raise argparse.ArgumentTypeError(f"must be greater than 0, got {number}")
32
+ return number
33
+
34
+
35
+ def _non_negative_int(value: str) -> int:
36
+ try:
37
+ number = int(value)
38
+ except ValueError:
39
+ raise argparse.ArgumentTypeError(f"expected an integer, got {value!r}")
40
+ if number < 0:
41
+ raise argparse.ArgumentTypeError(f"must be >= 0, got {number}")
42
+ return number
43
+
44
+
45
+ def _unit_float(value: str) -> float:
46
+ try:
47
+ number = float(value)
48
+ except ValueError:
49
+ raise argparse.ArgumentTypeError(f"expected a number, got {value!r}")
50
+ if not 0.0 <= number <= 1.0:
51
+ raise argparse.ArgumentTypeError(f"must be between 0 and 1, got {number}")
52
+ return number
53
+
54
+
55
+ def _add_pipeline_args(parser: argparse.ArgumentParser) -> None:
56
+ parser.add_argument(
57
+ "source", metavar="SOURCE", help="path to a file or folder to process"
58
+ )
59
+ parser.add_argument(
60
+ "--chunk-size",
61
+ type=_positive_int,
62
+ metavar="N",
63
+ default=512,
64
+ help="maximum words per chunk (default: 512)",
65
+ )
66
+ parser.add_argument(
67
+ "--overlap",
68
+ type=_non_negative_int,
69
+ metavar="N",
70
+ default=64,
71
+ help="words of overlap between chunks; must be < chunk size (default: 64)",
72
+ )
73
+ parser.add_argument("--no-clean", action="store_true", help="skip text cleaning")
74
+ parser.add_argument(
75
+ "--no-dedupe", action="store_true", help="skip duplicate removal"
76
+ )
77
+ parser.add_argument(
78
+ "--tokenizer",
79
+ metavar="SPEC",
80
+ default=None,
81
+ help=(
82
+ "measure chunk size and token counts with a real tokenizer, e.g. "
83
+ "tiktoken:cl100k_base (requires `pip install tiktoken`); default: words"
84
+ ),
85
+ )
86
+
87
+
88
+ def build_parser() -> argparse.ArgumentParser:
89
+ """Build the argparse parser for the preembed CLI."""
90
+ parser = argparse.ArgumentParser(
91
+ prog="preembed",
92
+ description="Clean, chunk, dedupe, and score documents before embedding.",
93
+ )
94
+ parser.add_argument(
95
+ "--version", action="version", version=f"%(prog)s {__version__}"
96
+ )
97
+ subparsers = parser.add_subparsers(dest="command", metavar="COMMAND")
98
+ subparsers.required = True
99
+
100
+ check = subparsers.add_parser(
101
+ "check",
102
+ help="validate corpus quality against thresholds",
103
+ description=(
104
+ "Run the pipeline on SOURCE and report corpus quality. Exits 0 when "
105
+ "all thresholds pass, 1 when any fails, 2 on usage or input errors."
106
+ ),
107
+ )
108
+ _add_pipeline_args(check)
109
+ check.add_argument(
110
+ "--min-score",
111
+ type=_unit_float,
112
+ metavar="F",
113
+ default=0.5,
114
+ help="chunks scoring below this are low quality (default: 0.5)",
115
+ )
116
+ check.add_argument(
117
+ "--max-low-quality-ratio",
118
+ type=_unit_float,
119
+ metavar="F",
120
+ default=0.25,
121
+ help="fail if the low-quality chunk ratio exceeds this (default: 0.25)",
122
+ )
123
+ check.add_argument(
124
+ "--max-duplicate-ratio",
125
+ type=_unit_float,
126
+ metavar="F",
127
+ default=None,
128
+ help="fail if the duplicate ratio exceeds this (default: unset)",
129
+ )
130
+ check.add_argument(
131
+ "--report",
132
+ metavar="PATH",
133
+ default=None,
134
+ help="also write a full report (.json, .md, or .html)",
135
+ )
136
+ check.add_argument(
137
+ "--format",
138
+ choices=("text", "json"),
139
+ default="text",
140
+ help="summary output format (default: text)",
141
+ )
142
+
143
+ export = subparsers.add_parser(
144
+ "export",
145
+ help="write processed chunks to JSONL",
146
+ description="Stream SOURCE through the pipeline and write chunks as JSONL.",
147
+ )
148
+ _add_pipeline_args(export)
149
+ export.add_argument(
150
+ "--output",
151
+ "-o",
152
+ metavar="PATH",
153
+ required=True,
154
+ help="destination .jsonl file",
155
+ )
156
+ export.add_argument(
157
+ "--min-score",
158
+ type=_unit_float,
159
+ metavar="F",
160
+ default=None,
161
+ help="drop chunks scoring below this (default: keep all)",
162
+ )
163
+ return parser
164
+
165
+
166
+ def main(argv: list[str] | None = None) -> int:
167
+ """Run the preembed CLI and return a process exit code."""
168
+ parser = build_parser()
169
+ try:
170
+ args = parser.parse_args(argv)
171
+ except SystemExit as exc:
172
+ return exc.code if isinstance(exc.code, int) else EXIT_USAGE
173
+
174
+ if args.overlap >= args.chunk_size:
175
+ return _usage_error(
176
+ f"--overlap ({args.overlap}) must be smaller than "
177
+ f"--chunk-size ({args.chunk_size})"
178
+ )
179
+
180
+ source = Path(args.source)
181
+ if not source.exists():
182
+ return _usage_error(
183
+ f"source path does not exist: {args.source} "
184
+ "(preembed CLI accepts a file or folder path, not raw text)"
185
+ )
186
+ if not (source.is_file() or source.is_dir()):
187
+ return _usage_error(f"source must be a file or folder: {args.source}")
188
+
189
+ try:
190
+ tokenizer = _load_tokenizer(args.tokenizer)
191
+ except ValueError as exc:
192
+ return _usage_error(str(exc))
193
+
194
+ pipeline = Pipeline(
195
+ clean=not args.no_clean,
196
+ chunk_size=args.chunk_size,
197
+ overlap=args.overlap,
198
+ dedupe=not args.no_dedupe,
199
+ score=True,
200
+ tokenizer=tokenizer,
201
+ )
202
+ try:
203
+ if args.command == "check":
204
+ return _run_check(args, pipeline)
205
+ return _run_export(args, pipeline)
206
+ except (OSError, ValueError) as exc:
207
+ return _usage_error(str(exc))
208
+
209
+
210
+ def _load_tokenizer(spec: str | None) -> Tokenizer | None:
211
+ if spec is None:
212
+ return None
213
+ backend, _, name = spec.partition(":")
214
+ if backend != "tiktoken" or not name:
215
+ raise ValueError(
216
+ f"unsupported --tokenizer {spec!r}; expected tiktoken:<encoding>"
217
+ )
218
+ try:
219
+ import tiktoken
220
+ except ImportError as exc:
221
+ raise ValueError(
222
+ "--tokenizer tiktoken:... requires `pip install tiktoken`"
223
+ ) from exc
224
+ try:
225
+ encoding = tiktoken.get_encoding(name)
226
+ except Exception as exc:
227
+ raise ValueError(f"cannot load tiktoken encoding {name!r}: {exc}") from exc
228
+ # encode_ordinary treats special-token text such as "<|endoftext|>" as plain text.
229
+ encode: Tokenizer = encoding.encode_ordinary
230
+ return encode
231
+
232
+
233
+ def _usage_error(message: str) -> int:
234
+ print(f"preembed: error: {message}", file=sys.stderr)
235
+ return EXIT_USAGE
236
+
237
+
238
+ def _run_check(args: argparse.Namespace, pipeline: Pipeline) -> int:
239
+ result = pipeline.run(str(args.source))
240
+ summary = _summarize(result, min_score=args.min_score)
241
+ summary["source"] = str(args.source)
242
+ failures = _threshold_failures(
243
+ summary,
244
+ max_low_quality_ratio=args.max_low_quality_ratio,
245
+ max_duplicate_ratio=args.max_duplicate_ratio,
246
+ )
247
+ summary["thresholds"] = {
248
+ "min_score": args.min_score,
249
+ "max_low_quality_ratio": args.max_low_quality_ratio,
250
+ "max_duplicate_ratio": args.max_duplicate_ratio,
251
+ }
252
+ summary["passed"] = not failures
253
+ summary["failures"] = failures
254
+
255
+ if args.report:
256
+ result.save_report(args.report)
257
+ summary["report"] = args.report
258
+
259
+ if args.format == "json":
260
+ print(json.dumps(summary, indent=2))
261
+ else:
262
+ _print_text_summary(summary)
263
+ return EXIT_THRESHOLD if failures else EXIT_OK
264
+
265
+
266
+ def _summarize(result: PipelineResult, *, min_score: float) -> dict[str, Any]:
267
+ stats = result.stats
268
+ chunks = result.scored_chunks
269
+ low_quality = sum(
270
+ 1 for chunk in chunks if chunk.score is not None and chunk.score < min_score
271
+ )
272
+ low_quality_ratio = low_quality / len(chunks) if chunks else 0.0
273
+ warning_counts = Counter(w for chunk in chunks for w in chunk.warnings)
274
+ worst = sorted(
275
+ chunks,
276
+ key=lambda c: (
277
+ c.score if c.score is not None else 1.0,
278
+ c.source_document or "",
279
+ c.chunk_index if c.chunk_index is not None else 0,
280
+ ),
281
+ )[:_WORST_CHUNK_COUNT]
282
+ return {
283
+ "source": None,
284
+ "documents": stats.total_documents,
285
+ "chunks": stats.total_chunks,
286
+ "average_chunk_size": stats.average_chunk_size,
287
+ "duplicate_ratio": stats.duplicate_ratio,
288
+ "low_quality_count": low_quality,
289
+ "low_quality_ratio": low_quality_ratio,
290
+ "warning_counts": dict(warning_counts.most_common(_TOP_WARNING_COUNT)),
291
+ "pipeline_warnings": list(result.warnings),
292
+ "worst_chunks": [_chunk_summary(chunk) for chunk in worst],
293
+ }
294
+
295
+
296
+ def _chunk_summary(chunk: Chunk) -> dict[str, Any]:
297
+ return {
298
+ "source_document": chunk.source_document,
299
+ "chunk_index": chunk.chunk_index,
300
+ "score": None if chunk.score is None else round(chunk.score, 4),
301
+ "warnings": list(chunk.warnings),
302
+ "preview": _preview(chunk.text),
303
+ }
304
+
305
+
306
+ def _preview(text: str) -> str:
307
+ flat = " ".join(text.split())
308
+ if len(flat) <= _PREVIEW_CHARS:
309
+ return flat
310
+ return flat[: _PREVIEW_CHARS - 3].rstrip() + "..."
311
+
312
+
313
+ def _threshold_failures(
314
+ summary: dict[str, Any],
315
+ *,
316
+ max_low_quality_ratio: float,
317
+ max_duplicate_ratio: float | None,
318
+ ) -> list[str]:
319
+ if summary["chunks"] == 0:
320
+ return ["no chunks produced"]
321
+ failures: list[str] = []
322
+ if summary["low_quality_ratio"] > max_low_quality_ratio:
323
+ failures.append(
324
+ f"low-quality ratio {summary['low_quality_ratio']:.2%} exceeds "
325
+ f"--max-low-quality-ratio {max_low_quality_ratio:.2%}"
326
+ )
327
+ if (
328
+ max_duplicate_ratio is not None
329
+ and summary["duplicate_ratio"] > max_duplicate_ratio
330
+ ):
331
+ failures.append(
332
+ f"duplicate ratio {summary['duplicate_ratio']:.2%} exceeds "
333
+ f"--max-duplicate-ratio {max_duplicate_ratio:.2%}"
334
+ )
335
+ return failures
336
+
337
+
338
+ def _print_text_summary(summary: dict[str, Any]) -> None:
339
+ lines = [
340
+ f"documents: {summary['documents']}",
341
+ f"chunks: {summary['chunks']}",
342
+ f"avg chunk size: {summary['average_chunk_size']:.1f} words",
343
+ f"duplicate ratio: {summary['duplicate_ratio']:.2%}",
344
+ (
345
+ f"low quality: {summary['low_quality_count']} "
346
+ f"({summary['low_quality_ratio']:.2%}, score < "
347
+ f"{summary['thresholds']['min_score']})"
348
+ ),
349
+ ]
350
+ if summary["warning_counts"]:
351
+ top = ", ".join(f"{k}={v}" for k, v in summary["warning_counts"].items())
352
+ lines.append(f"top warnings: {top}")
353
+ if summary["worst_chunks"]:
354
+ lines.append("")
355
+ lines.append("worst chunks:")
356
+ for chunk in summary["worst_chunks"]:
357
+ score = "n/a" if chunk["score"] is None else f"{chunk['score']:.2f}"
358
+ warnings = ",".join(chunk["warnings"]) or "-"
359
+ lines.append(
360
+ f" {score} {chunk['source_document']}#{chunk['chunk_index']}"
361
+ f" [{warnings}]"
362
+ )
363
+ lines.append(f" {chunk['preview']}")
364
+ if summary.get("report"):
365
+ lines.append("")
366
+ lines.append(f"report written to {summary['report']}")
367
+ lines.append("")
368
+ if summary["failures"]:
369
+ lines.append("FAIL")
370
+ lines.extend(f" - {failure}" for failure in summary["failures"])
371
+ else:
372
+ lines.append("PASS")
373
+ print("\n".join(lines))
374
+
375
+
376
+ def _run_export(args: argparse.Namespace, pipeline: Pipeline) -> int:
377
+ output = Path(args.output)
378
+ if _aliases_input(output, Path(args.source)):
379
+ return _usage_error(
380
+ f"--output {output} would overwrite an input document; "
381
+ "write it outside SOURCE or use a non-document suffix such as .jsonl"
382
+ )
383
+ output.parent.mkdir(parents=True, exist_ok=True)
384
+ written = 0
385
+ with output.open("w", encoding="utf-8") as handle:
386
+ for batch in pipeline.stream(str(args.source), batch_size=50):
387
+ for chunk in batch.scored_chunks:
388
+ if (
389
+ args.min_score is not None
390
+ and chunk.score is not None
391
+ and chunk.score < args.min_score
392
+ ):
393
+ continue
394
+ handle.write(json.dumps(_chunk_record(chunk), ensure_ascii=False))
395
+ handle.write("\n")
396
+ written += 1
397
+ print(f"wrote {written} chunks to {output}", file=sys.stderr)
398
+ return EXIT_OK
399
+
400
+
401
+ def _aliases_input(output: Path, source: Path) -> bool:
402
+ resolved_output = output.resolve()
403
+ resolved_source = source.resolve()
404
+ if resolved_source.is_file():
405
+ return resolved_output == resolved_source
406
+ return resolved_output.is_relative_to(resolved_source) and _is_supported_text_file(
407
+ resolved_output
408
+ )
409
+
410
+
411
+ def _chunk_record(chunk: Chunk) -> dict[str, Any]:
412
+ return {
413
+ "text": chunk.text,
414
+ "score": chunk.score,
415
+ "tokens": chunk.tokens,
416
+ "warnings": list(chunk.warnings),
417
+ "source_document": chunk.source_document,
418
+ "chunk_index": chunk.chunk_index,
419
+ "start_offset": chunk.start_offset,
420
+ "end_offset": chunk.end_offset,
421
+ }
@@ -0,0 +1,5 @@
1
+ """Framework adapters for LangChain and LlamaIndex.
2
+
3
+ Import the submodule for your framework, e.g. ``preembed.integrations.langchain``
4
+ or ``preembed.integrations.llamaindex``; frameworks are only imported on demand.
5
+ """
@@ -0,0 +1,122 @@
1
+ """Shared helpers for framework adapters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from dataclasses import dataclass, field
7
+
8
+ from ..text import chunk_text, clean_text, dedupe_chunks, score_chunks
9
+ from ..types import Tokenizer
10
+
11
+ SCORE_KEY = "preembed_score"
12
+ WARNINGS_KEY = "preembed_warnings"
13
+
14
+
15
+ @dataclass(slots=True)
16
+ class Selection:
17
+ """Index of a kept input item plus its optional quality score and warnings."""
18
+
19
+ index: int
20
+ score: float | None = None
21
+ warnings: list[str] = field(default_factory=list)
22
+
23
+
24
+ def missing_dependency(framework: str, extra: str) -> ImportError:
25
+ """Build an ImportError telling the user how to install a framework extra."""
26
+ return ImportError(
27
+ f"preembed.integrations.{extra} requires {framework}. "
28
+ f'Install it with: pip install "preembed[{extra}]"'
29
+ )
30
+
31
+
32
+ def validate_split_config(
33
+ chunk_size: int, chunk_overlap: int, mode: str, tokenizer: Tokenizer | None
34
+ ) -> None:
35
+ """Validate splitter settings eagerly so errors surface at construction time."""
36
+ if chunk_size <= 0:
37
+ raise ValueError("chunk_size must be greater than 0.")
38
+ if chunk_overlap < 0:
39
+ raise ValueError("chunk_overlap must be greater than or equal to 0.")
40
+ if chunk_overlap >= chunk_size:
41
+ raise ValueError("chunk_overlap must be smaller than chunk_size.")
42
+ if mode not in {"word", "token"}:
43
+ raise ValueError("mode must be 'word' or 'token'.")
44
+ if mode == "token" and (tokenizer is None or not callable(tokenizer)):
45
+ raise TypeError("token mode requires a callable tokenizer.")
46
+
47
+
48
+ def validate_filter_config(
49
+ dedupe: bool, score: bool, min_score: float | None, threshold: float
50
+ ) -> None:
51
+ """Validate dedupe/score filter settings."""
52
+ for name, value in {"dedupe": dedupe, "score": score}.items():
53
+ if not isinstance(value, bool):
54
+ raise TypeError(f"{name} must be a boolean.")
55
+ if min_score is not None:
56
+ if isinstance(min_score, bool) or not isinstance(min_score, (int, float)):
57
+ raise TypeError("min_score must be a number or None.")
58
+ if not 0 <= min_score <= 1:
59
+ raise ValueError("min_score must be between 0 and 1.")
60
+ if not score:
61
+ raise ValueError("min_score requires score=True.")
62
+ if not 0 <= threshold <= 1:
63
+ raise ValueError("near_duplicate_threshold must be between 0 and 1.")
64
+
65
+
66
+ def split(
67
+ text: str,
68
+ *,
69
+ chunk_size: int,
70
+ chunk_overlap: int,
71
+ clean: bool,
72
+ preserve_headings: bool,
73
+ mode: str,
74
+ tokenizer: Tokenizer | None,
75
+ ) -> list[str]:
76
+ """Optionally clean text, then chunk it with preembed."""
77
+ if clean:
78
+ text = clean_text(text, preserve_structure=True)
79
+ if not text.strip():
80
+ return []
81
+ return chunk_text(
82
+ text,
83
+ chunk_size,
84
+ chunk_overlap,
85
+ preserve_headings,
86
+ mode=mode,
87
+ tokenizer=tokenizer,
88
+ )
89
+
90
+
91
+ def select(
92
+ texts: Sequence[str],
93
+ *,
94
+ dedupe: bool,
95
+ score: bool,
96
+ min_score: float | None,
97
+ near_duplicate_threshold: float,
98
+ ) -> list[Selection]:
99
+ """Dedupe (keeping first occurrences) and score texts, returning kept indices."""
100
+ indices = list(range(len(texts)))
101
+ if dedupe and texts:
102
+ result = dedupe_chunks(
103
+ list(texts),
104
+ return_stats=True,
105
+ near_duplicate_threshold=near_duplicate_threshold,
106
+ )
107
+ removed = {item["index"] for item in result.duplicate_metadata}
108
+ indices = [index for index in indices if index not in removed]
109
+
110
+ selections = [Selection(index) for index in indices]
111
+ if not score or not selections:
112
+ return selections
113
+
114
+ for selection, chunk in zip(
115
+ selections, score_chunks([texts[i] for i in indices]), strict=True
116
+ ):
117
+ selection.score = chunk.score
118
+ selection.warnings = list(chunk.warnings)
119
+
120
+ if min_score is None:
121
+ return selections
122
+ return [s for s in selections if s.score is not None and s.score >= min_score]