ragrock 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.
ragrock/__init__.py ADDED
@@ -0,0 +1,52 @@
1
+ """ragrock - PDF / DOCX / HTML / XML -> clean markdown + text for RAG pipelines."""
2
+
3
+ from .config import ExtractionConfig, LLMConfig, LLMMode, OCRConfig, PDFStrategy
4
+ from .extractor import DocumentExtractor, UnsupportedFileType
5
+ from .llm import (
6
+ CallableVisionClient,
7
+ LLMResult,
8
+ OpenRouterVisionClient,
9
+ VisionLLMClient,
10
+ )
11
+ from .log import disable_logging, setup_logging, to_std_logging
12
+ from .models import (
13
+ BoundingBox,
14
+ Document,
15
+ DocumentElement,
16
+ DocumentMetadata,
17
+ ElementType,
18
+ ExtractionMethod,
19
+ ExtractionStats,
20
+ FileType,
21
+ PageResult,
22
+ Table,
23
+ )
24
+
25
+ __all__ = [
26
+ "BoundingBox",
27
+ "CallableVisionClient",
28
+ "Document",
29
+ "DocumentElement",
30
+ "DocumentExtractor",
31
+ "DocumentMetadata",
32
+ "ElementType",
33
+ "ExtractionConfig",
34
+ "ExtractionMethod",
35
+ "ExtractionStats",
36
+ "FileType",
37
+ "LLMConfig",
38
+ "LLMMode",
39
+ "LLMResult",
40
+ "OCRConfig",
41
+ "OpenRouterVisionClient",
42
+ "PDFStrategy",
43
+ "PageResult",
44
+ "Table",
45
+ "UnsupportedFileType",
46
+ "VisionLLMClient",
47
+ "disable_logging",
48
+ "setup_logging",
49
+ "to_std_logging",
50
+ ]
51
+
52
+ __version__ = "0.1.0"
ragrock/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """``python -m ragrock``: same as the ``ragrock`` command."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ sys.exit(main())
ragrock/cli.py ADDED
@@ -0,0 +1,308 @@
1
+ """``ragrock`` command line: inspect and re-score saved runs.
2
+
3
+ Examples::
4
+
5
+ ragrock show runs/20261115T101500-ab12cd.jsonl
6
+ ragrock eval runs/20261115T101500-ab12cd.jsonl --evaluator mypkg.evals:RecallAtK
7
+ ragrock eval run.jsonl -e evals.py:make_ragas --min-score ragas.faithfulness=0.8
8
+
9
+ Objects are given as ``module:attribute`` (``mypkg.evals:RecallAtK``) or
10
+ ``path/to/file.py:attribute``. The attribute may be:
11
+
12
+ * a class: it is instantiated with no arguments;
13
+ * an instance (``Evaluator`` / ``RunEvaluator`` / ``Reporter``): used as is;
14
+ * a function with no required arguments: a *factory*, called once; it may
15
+ return one object or a list (use this when an evaluator needs an LLM client);
16
+ * for ``--evaluator`` only, a function ``fn(item, trace)``: used as an evaluator.
17
+
18
+ The current directory is put on ``sys.path`` first, so local packages import.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import importlib
25
+ import importlib.util
26
+ import inspect
27
+ import json
28
+ import sys
29
+ from collections.abc import Sequence
30
+ from pathlib import Path
31
+ from typing import Any
32
+
33
+ from . import __version__
34
+ from .evaluation import (
35
+ Evaluator,
36
+ JsonlReporter,
37
+ Reporter,
38
+ RunEvaluator,
39
+ RunSummary,
40
+ replay,
41
+ summarize_run,
42
+ )
43
+ from .evaluation.evaluator import FunctionEvaluator
44
+
45
+ EXIT_OK = 0
46
+ EXIT_GATE_FAILED = 1
47
+ EXIT_USAGE = 2
48
+
49
+
50
+ class CLIError(Exception):
51
+ """A user error: printed without a traceback, exit code 2."""
52
+
53
+ def import_attr(spec: str) -> Any:
54
+ """Import ``module:attr`` or ``file.py:attr`` (``attr`` may be dotted)."""
55
+ module_name, sep, attr = spec.rpartition(":")
56
+ if not sep or not module_name or not attr:
57
+ raise CLIError(f"{spec!r}: expected 'module:attribute' or 'file.py:attribute'")
58
+ if str(Path.cwd()) not in sys.path:
59
+ sys.path.insert(0, str(Path.cwd()))
60
+ try:
61
+ if module_name.endswith(".py"):
62
+ path = Path(module_name).resolve()
63
+ if not path.is_file():
64
+ raise CLIError(f"{spec!r}: file {module_name} not found")
65
+ mod_spec = importlib.util.spec_from_file_location(path.stem, path)
66
+ module = importlib.util.module_from_spec(mod_spec)
67
+ sys.modules[path.stem] = module # so pickling / dataclasses can find it
68
+ mod_spec.loader.exec_module(module)
69
+ else:
70
+ module = importlib.import_module(module_name)
71
+ except CLIError:
72
+ raise
73
+ except Exception as e:
74
+ raise CLIError(f"{spec!r}: cannot import {module_name}: {e!r}") from e
75
+ obj = module
76
+ for part in attr.split("."):
77
+ try:
78
+ obj = getattr(obj, part)
79
+ except AttributeError:
80
+ raise CLIError(f"{spec!r}: {module_name} has no attribute {attr!r}") from None
81
+ return obj
82
+
83
+
84
+ def _required_params(fn) -> int:
85
+ try:
86
+ sig = inspect.signature(fn)
87
+ except (TypeError, ValueError):
88
+ return 0
89
+ return sum(
90
+ p.default is p.empty and p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)
91
+ for p in sig.parameters.values()
92
+ )
93
+
94
+
95
+ def build(spec: str, kind: type, allow_function: bool = False) -> list:
96
+ """Turn one ``--evaluator`` / ``--run-evaluator`` / ``--reporter`` spec into objects."""
97
+ obj = import_attr(spec)
98
+ if isinstance(obj, type):
99
+ if not issubclass(obj, kind):
100
+ raise CLIError(f"{spec!r}: {obj.__name__} is not a {kind.__name__} subclass")
101
+ try:
102
+ obj = obj()
103
+ except TypeError as e:
104
+ raise CLIError(
105
+ f"{spec!r}: {obj.__name__}() needs arguments ({e}); "
106
+ "point to an instance or a no-argument factory function instead"
107
+ ) from e
108
+ elif not isinstance(obj, kind) and callable(obj):
109
+ if _required_params(obj) == 0:
110
+ obj = obj() # factory
111
+ elif allow_function:
112
+ return [FunctionEvaluator(obj)]
113
+ else:
114
+ raise CLIError(f"{spec!r}: expected a {kind.__name__} or a no-argument factory")
115
+ objs = list(obj) if isinstance(obj, (list, tuple)) else [obj]
116
+ for o in objs:
117
+ if not isinstance(o, kind):
118
+ raise CLIError(f"{spec!r}: got {type(o).__name__}, expected {kind.__name__}")
119
+ return objs
120
+
121
+
122
+ def parse_tags(items: Sequence[str]) -> dict[str, str]:
123
+ tags = {}
124
+ for item in items:
125
+ key, sep, value = item.partition("=")
126
+ if not sep or not key:
127
+ raise CLIError(f"--tag {item!r}: expected key=value")
128
+ tags[key] = value
129
+ return tags
130
+
131
+
132
+ def parse_gates(items: Sequence[str]) -> list[tuple[str, str, float]]:
133
+ """``evaluator.metric=0.8`` -> ``(evaluator, metric, 0.8)``."""
134
+ gates = []
135
+ for item in items:
136
+ name, sep, value = item.rpartition("=")
137
+ evaluator, dot, metric = name.rpartition(".")
138
+ if not sep or not dot or not evaluator or not metric:
139
+ raise CLIError(f"--min-score {item!r}: expected evaluator.metric=number")
140
+ try:
141
+ gates.append((evaluator, metric, float(value)))
142
+ except ValueError:
143
+ raise CLIError(f"--min-score {item!r}: {value!r} is not a number") from None
144
+ return gates
145
+
146
+
147
+ def check_gates(summary: RunSummary, gates) -> list[str]:
148
+ """Messages for every gate that failed (missing scores fail too)."""
149
+ failures = []
150
+ for evaluator, metric, minimum in gates:
151
+ got = summary.score(evaluator, metric)
152
+ if got is None:
153
+ failures.append(f"{evaluator}.{metric}: no score (known: {_known_scores(summary)})")
154
+ elif got < minimum:
155
+ failures.append(f"{evaluator}.{metric}: {got:.4g} < {minimum:g}")
156
+ return failures
157
+
158
+
159
+ def _known_scores(summary: RunSummary) -> str:
160
+ names = [f"{e}.{m}" for e, ms in summary.scores.items() for m in ms]
161
+ return ", ".join(names) or "none"
162
+
163
+
164
+ # ------------------------------------------------------------------ commands
165
+ def _output(summary: RunSummary, as_json: bool) -> None:
166
+ if as_json:
167
+ print(json.dumps(summary.to_dict(), indent=2, default=str))
168
+ else:
169
+ print(summary.table())
170
+ if summary.extra:
171
+ print(f"extra: {json.dumps(summary.extra, default=str)}")
172
+ sys.stdout.flush() # keep the summary above the stderr messages
173
+
174
+
175
+ def _file(path: str) -> Path:
176
+ p = Path(path)
177
+ if not p.is_file():
178
+ raise CLIError(f"{path}: no such file")
179
+ return p
180
+
181
+
182
+ def cmd_show(args: argparse.Namespace) -> int:
183
+ summary = summarize_run(_file(args.path))
184
+ _output(summary, args.json)
185
+ return EXIT_OK
186
+
187
+
188
+ def cmd_eval(args: argparse.Namespace) -> int:
189
+ path = _file(args.path)
190
+ evaluators = [e for spec in args.evaluator for e in build(spec, Evaluator, True)]
191
+ run_evaluators = [e for spec in args.run_evaluator for e in build(spec, RunEvaluator)]
192
+ reporters = [r for spec in args.reporter for r in build(spec, Reporter)]
193
+ if not evaluators and not run_evaluators:
194
+ raise CLIError("give at least one --evaluator or --run-evaluator")
195
+ saver = None
196
+ if args.out:
197
+ out = Path(args.out)
198
+ saver = JsonlReporter(path=out) if out.suffix == ".jsonl" else JsonlReporter(out)
199
+ reporters.append(saver)
200
+ gates = parse_gates(args.min_score)
201
+ if not 0.0 <= args.sample <= 1.0:
202
+ raise CLIError("--sample must be between 0 and 1")
203
+ if args.workers < 1:
204
+ raise CLIError("--workers must be >= 1")
205
+ summary = replay(
206
+ path,
207
+ evaluators,
208
+ run_evaluators,
209
+ reporters,
210
+ sample=args.sample,
211
+ workers=args.workers,
212
+ run_id=args.run_id,
213
+ tags=parse_tags(args.tag),
214
+ )
215
+ _output(summary, args.json)
216
+ if saver is not None:
217
+ print(f"saved {saver.path}", file=sys.stderr)
218
+ failures = check_gates(summary, gates)
219
+ for f in failures:
220
+ print(f"FAILED {f}", file=sys.stderr)
221
+ if gates and not failures:
222
+ print(f"all {len(gates)} score gate(s) passed", file=sys.stderr)
223
+ return EXIT_GATE_FAILED if failures else EXIT_OK
224
+
225
+
226
+ # ------------------------------------------------------------------ parser
227
+ def build_parser() -> argparse.ArgumentParser:
228
+ parser = argparse.ArgumentParser(
229
+ prog="ragrock",
230
+ description="Inspect and re-score runs saved by ragrock.evaluation.JsonlReporter.",
231
+ )
232
+ parser.add_argument("--version", action="version", version=f"ragrock {__version__}")
233
+ sub = parser.add_subparsers(dest="command", required=True, metavar="command")
234
+
235
+ show = sub.add_parser("show", help="print the summary of a saved run")
236
+ show.add_argument("path", help="run file (.jsonl)")
237
+ show.add_argument("--json", action="store_true", help="print the summary as JSON")
238
+ show.set_defaults(func=cmd_show)
239
+
240
+ ev = sub.add_parser(
241
+ "eval",
242
+ help="run evaluators over a saved run (the pipeline is not re-run)",
243
+ description=(
244
+ "Re-score the traces of a saved run. Objects are 'module:attr' or "
245
+ "'file.py:attr': a class (instantiated with no arguments), an instance, "
246
+ "or a no-argument factory function. Exit code 1 if a --min-score gate fails."
247
+ ),
248
+ )
249
+ ev.add_argument("path", help="run file (.jsonl) written with mode='full'")
250
+ ev.add_argument(
251
+ "-e",
252
+ "--evaluator",
253
+ action="append",
254
+ default=[],
255
+ metavar="SPEC",
256
+ help="item evaluator, or fn(item, trace); repeatable",
257
+ )
258
+ ev.add_argument(
259
+ "-r",
260
+ "--run-evaluator",
261
+ action="append",
262
+ default=[],
263
+ metavar="SPEC",
264
+ help="run evaluator; repeatable",
265
+ )
266
+ ev.add_argument(
267
+ "--reporter",
268
+ action="append",
269
+ default=[],
270
+ metavar="SPEC",
271
+ help="reporter for the new run (dashboard, webhook...); repeatable",
272
+ )
273
+ ev.add_argument(
274
+ "-o", "--out", metavar="PATH", help="save the re-scored run: a .jsonl file or a directory"
275
+ )
276
+ ev.add_argument(
277
+ "--min-score",
278
+ action="append",
279
+ default=[],
280
+ metavar="EVALUATOR.METRIC=N",
281
+ help="fail (exit 1) if the mean score is below N; repeatable",
282
+ )
283
+ ev.add_argument("--sample", type=float, default=1.0, help="fraction of items (default 1)")
284
+ ev.add_argument("--workers", type=int, default=8, help="items scored at once (default 8)")
285
+ ev.add_argument("--run-id", help="id of the new run")
286
+ ev.add_argument(
287
+ "--tag", action="append", default=[], metavar="KEY=VALUE", help="tag the new run"
288
+ )
289
+ ev.add_argument("--json", action="store_true", help="print the summary as JSON")
290
+ ev.set_defaults(func=cmd_eval)
291
+ return parser
292
+
293
+
294
+ def main(argv: Sequence[str] | None = None) -> int:
295
+ parser = build_parser()
296
+ args = parser.parse_args(argv)
297
+ try:
298
+ return args.func(args)
299
+ except CLIError as e:
300
+ print(f"ragrock: error: {e}", file=sys.stderr)
301
+ return EXIT_USAGE
302
+ except (OSError, json.JSONDecodeError, KeyError) as e:
303
+ print(f"ragrock: error: cannot read {args.path}: {e!r}", file=sys.stderr)
304
+ return EXIT_USAGE
305
+
306
+
307
+ if __name__ == "__main__": # pragma: no cover
308
+ sys.exit(main())
ragrock/config.py ADDED
@@ -0,0 +1,119 @@
1
+ """Configuration that controls which extraction methods are used and when."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import Enum
6
+ from typing import Any, Literal
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field
9
+
10
+
11
+ class PDFStrategy(str, Enum):
12
+ AUTO = "auto" # native text -> OCR if page has no/little text -> LLM if OCR confidence low
13
+ NATIVE = "native" # text layer only (fastest, no OCR/LLM)
14
+ OCR = "ocr" # force OCR on every page (LLM fallback still applies if enabled)
15
+ LLM = "llm" # send every page image to the vision LLM
16
+ OCR_ONLY = "ocr_only" # force OCR, never call the LLM
17
+
18
+
19
+ class LLMMode(str, Enum):
20
+ OFF = "off" # never call the LLM
21
+ FALLBACK = "fallback" # only when OCR confidence < llm_confidence_threshold
22
+ ALWAYS_FOR_SCANNED = "always_for_scanned" # every page that needed OCR goes to the LLM
23
+ ALWAYS = "always" # every PDF page goes to the LLM
24
+
25
+
26
+ class OCRConfig(BaseModel):
27
+ languages: str = Field(default="eng", description="Tesseract language codes, e.g. 'eng+hin'")
28
+ dpi: int = Field(default=300, ge=72, le=600)
29
+ psm: int = Field(default=3, description="Tesseract page segmentation mode")
30
+ oem: int = Field(default=3, description="Tesseract OCR engine mode")
31
+ tesseract_cmd: str | None = None
32
+ min_word_confidence: float = Field(
33
+ default=0.0,
34
+ ge=0.0,
35
+ le=1.0,
36
+ description="Drop OCR words below this confidence (0 keeps everything)",
37
+ )
38
+ low_word_confidence: float = Field(
39
+ default=0.6, ge=0.0, le=1.0, description="Words below this count as low-confidence"
40
+ )
41
+ preprocess: bool = Field(default=True, description="Grayscale + autocontrast before OCR")
42
+
43
+
44
+ class LLMConfig(BaseModel):
45
+ model_config = ConfigDict(arbitrary_types_allowed=True)
46
+
47
+ mode: LLMMode = LLMMode.FALLBACK
48
+ client: Any | None = Field(
49
+ default=None, description="An object implementing ragrock.llm.VisionLLMClient"
50
+ )
51
+ confidence_threshold: float = Field(
52
+ default=0.75,
53
+ ge=0.0,
54
+ le=1.0,
55
+ description="OCR page confidence below this triggers the LLM in FALLBACK mode",
56
+ )
57
+ dpi: int = Field(
58
+ default=200, ge=72, le=400, description="Render DPI for page images sent to LLM"
59
+ )
60
+ max_pages: int | None = Field(
61
+ default=None, description="Cap LLM calls per document (cost control)"
62
+ )
63
+ max_workers: int = Field(default=4, ge=1, description="Parallel LLM calls")
64
+ selection: Literal["prefer_llm", "highest_confidence"] = Field(
65
+ default="prefer_llm",
66
+ description=(
67
+ "prefer_llm: use the LLM result unless its confidence < min_llm_confidence. "
68
+ "highest_confidence: keep whichever of OCR / LLM reports the higher confidence."
69
+ ),
70
+ )
71
+ min_llm_confidence: float = Field(default=0.5, ge=0.0, le=1.0)
72
+ prompt: str | None = Field(
73
+ default=None, description="Override the default transcription prompt"
74
+ )
75
+
76
+
77
+ class ExtractionConfig(BaseModel):
78
+ model_config = ConfigDict(arbitrary_types_allowed=True)
79
+
80
+ pdf_strategy: PDFStrategy = PDFStrategy.AUTO
81
+ pdf_password: str | None = None
82
+ min_native_chars_per_page: int = Field(
83
+ default=50, description="Fewer native characters than this -> page treated as scanned"
84
+ )
85
+ ocr_if_image_coverage_above: float = Field(
86
+ default=0.6,
87
+ ge=0.0,
88
+ le=1.0,
89
+ description="Also OCR a page with a text layer if images cover more than this fraction of it",
90
+ )
91
+ extract_tables: bool = True
92
+ detect_headings: bool = True
93
+ remove_headers_footers: bool = Field(
94
+ default=True, description="Drop lines repeated at the top/bottom of most PDF pages"
95
+ )
96
+ include_page_markers: bool = Field(
97
+ default=False, description="Insert <!-- page N --> comments between pages in markdown"
98
+ )
99
+ page_separator: str = "\n\n"
100
+ html_remove_tags: list[str] = Field(
101
+ default_factory=lambda: [
102
+ "script",
103
+ "style",
104
+ "noscript",
105
+ "nav",
106
+ "footer",
107
+ "header",
108
+ "aside",
109
+ "form",
110
+ "iframe",
111
+ "svg",
112
+ ]
113
+ )
114
+ html_keep_links: bool = False
115
+ xml_text_only: bool = Field(
116
+ default=False, description="XML: emit only text nodes without element-name headings"
117
+ )
118
+ ocr: OCRConfig = Field(default_factory=OCRConfig)
119
+ llm: LLMConfig = Field(default_factory=LLMConfig)
@@ -0,0 +1,64 @@
1
+ """Per-stage metrics, evaluators and run summaries for pipelines.
2
+
3
+ Three pieces you plug into a :class:`~ragrock.pipeline.Pipeline`:
4
+
5
+ * stages **record** numbers with :func:`record` / :func:`capture`;
6
+ * **evaluators** score each item (:class:`Evaluator`) or the whole run
7
+ (:class:`RunEvaluator`) after the last stage;
8
+ * **reporters** (:class:`Reporter`) decide where traces and the final
9
+ :class:`RunSummary` go: log, file, dashboard, anything.
10
+
11
+ :class:`EvalOptions` switches it on per run, with no code changes::
12
+
13
+ pipe = Pipeline(*stages, evaluators=[RecallAtK()], reporters=[LogReporter()])
14
+ pipe.collect_sync(items) # off (or RAGROCK_EVAL)
15
+ pipe.collect_sync(items, evaluation=EvalOptions(evaluate=True))
16
+ """
17
+
18
+ from ..metrics import Labeled, StageRecord, Trace, capture, increment, is_recording, record
19
+ from .evaluator import (
20
+ EvaluationStage,
21
+ Evaluator,
22
+ FunctionEvaluator,
23
+ RunEvaluator,
24
+ evaluate_trace,
25
+ evaluator,
26
+ )
27
+ from .options import ENV_MODE, ENV_SAMPLE, EvalOptions
28
+ from .replay import areplay, load_run, replay, summarize_run
29
+ from .reporter import JsonlReporter, LogReporter, MemoryReporter, Reporter
30
+ from .session import EvalSession
31
+ from .summary import RunInfo, RunSummary, StageInfo, StageSummary, Stat
32
+
33
+ __all__ = [
34
+ "ENV_MODE",
35
+ "ENV_SAMPLE",
36
+ "EvalOptions",
37
+ "EvalSession",
38
+ "EvaluationStage",
39
+ "Evaluator",
40
+ "FunctionEvaluator",
41
+ "JsonlReporter",
42
+ "Labeled",
43
+ "LogReporter",
44
+ "MemoryReporter",
45
+ "Reporter",
46
+ "RunEvaluator",
47
+ "RunInfo",
48
+ "RunSummary",
49
+ "StageInfo",
50
+ "StageRecord",
51
+ "StageSummary",
52
+ "Stat",
53
+ "Trace",
54
+ "areplay",
55
+ "capture",
56
+ "evaluate_trace",
57
+ "evaluator",
58
+ "increment",
59
+ "is_recording",
60
+ "load_run",
61
+ "record",
62
+ "replay",
63
+ "summarize_run",
64
+ ]