oxide-parse 0.9.0__cp310-abi3-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.
@@ -0,0 +1,95 @@
1
+ """Declarative HTML and JSON extraction compiler backed by Rust.
2
+
3
+ Build schemas using the `T` expression builder, serialize or inspect them as JSON-compatible IR, and execute them on
4
+ single-pass streaming (`stream`), arena DOM (`lite`), html5ever DOM (`scraper`), or `json` backends. Network IO and
5
+ LLM calls stay outside the core via `Session`, `follow`, `paginate`, and `adaptive` repair callbacks.
6
+
7
+ Examples:
8
+ Extract structured fields from HTML:
9
+
10
+ >>> from oxide_parse import T, compile
11
+ >>> html = "<h1>Shop</h1><div class='p'><b>Item</b><i>$12.50</i></div>"
12
+ >>> schema = {"title": T.css("h1").text(), "items": T.css(".p").map({"name": T.css("b").text(), "price": T.css("i").text().float()})}
13
+ >>> compile(schema, backend="auto").extract(html)
14
+ {'title': 'Shop', 'items': [{'name': 'Item', 'price': 12.5}]}
15
+
16
+ Round-trip a schema through JSON IR and back to Python code:
17
+
18
+ >>> from oxide_parse import decompile, to_ir
19
+ >>> ir = to_ir({"title": T.css("h1").text().strip()})
20
+ >>> print(decompile(ir).strip())
21
+ from oxide_parse import T
22
+ <BLANKLINE>
23
+ schema = {
24
+ 'title': T.css('h1').text().strip(),
25
+ }
26
+ """
27
+ from .crawl import CrawlPage, acrawl, canonicalize_url, crawl
28
+ from .decompile import decompile
29
+ from .expr import Expr, T, coalesce, follow, if_, paginate, to_ir
30
+ from .formats import (
31
+ FORMATS,
32
+ FormatCodec,
33
+ FormatRegistry,
34
+ available_formats,
35
+ dumps_format,
36
+ get_format,
37
+ loads_format,
38
+ register_format,
39
+ unregister_format,
40
+ )
41
+ from .plan import (
42
+ Detailed,
43
+ EngineInfo,
44
+ OxideParseError,
45
+ Plan,
46
+ RepairResult,
47
+ Session,
48
+ compile,
49
+ decode_html,
50
+ distill,
51
+ engines,
52
+ extract,
53
+ ir_schema,
54
+ markdown,
55
+ validate_ir,
56
+ )
57
+
58
+ __all__ = [
59
+ "T",
60
+ "Expr",
61
+ "to_ir",
62
+ "if_",
63
+ "coalesce",
64
+ "follow",
65
+ "paginate",
66
+ "FORMATS",
67
+ "FormatCodec",
68
+ "FormatRegistry",
69
+ "register_format",
70
+ "unregister_format",
71
+ "get_format",
72
+ "available_formats",
73
+ "dumps_format",
74
+ "loads_format",
75
+ "CrawlPage",
76
+ "canonicalize_url",
77
+ "crawl",
78
+ "acrawl",
79
+ "Plan",
80
+ "compile",
81
+ "extract",
82
+ "decompile",
83
+ "OxideParseError",
84
+ "engines",
85
+ "EngineInfo",
86
+ "Detailed",
87
+ "RepairResult",
88
+ "Session",
89
+ "decode_html",
90
+ "distill",
91
+ "markdown",
92
+ "validate_ir",
93
+ "ir_schema",
94
+ ]
95
+ __version__ = "0.9.0"
@@ -0,0 +1,326 @@
1
+ """Command-line interface (`python -m oxide_parse ...` or `oxide-parse ...`).
2
+
3
+ Examples:
4
+ Run from a shell:
5
+
6
+ oxide-parse distill page.html --max-chars 8000
7
+ oxide-parse markdown page.html --selector article --without ".ad, .share"
8
+ oxide-parse run schema.json page.html --backend auto --explain
9
+ oxide-parse decompile schema.json --out schema.py
10
+ oxide-parse validate schema.json
11
+ oxide-parse migrate --from crawl4ai strategy.json --format python
12
+ oxide-parse prompt generate
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import pathlib
19
+ import sys
20
+ from typing import Any, List, Optional
21
+
22
+ from . import __version__
23
+
24
+
25
+ class CliError(Exception):
26
+ """Expected CLI error printed as a single concise line (exit status 1)."""
27
+
28
+
29
+ def _read_text(path: str) -> str:
30
+ if path == "-":
31
+ return sys.stdin.read()
32
+ try:
33
+ return pathlib.Path(path).read_text(encoding="utf-8", errors="replace")
34
+ except OSError as e:
35
+ raise CliError(f"cannot read {path}: {e.strerror or e}") from e
36
+
37
+
38
+ def _write(text: str, out: Optional[str]) -> None:
39
+ if out:
40
+ pathlib.Path(out).write_bytes(text.encode("utf-8"))
41
+ print(f"wrote {out}", file=sys.stderr)
42
+ else:
43
+ sys.stdout.write(text if text.endswith("\n") else text + "\n")
44
+
45
+
46
+ def _load_schema(path: str) -> Any:
47
+ """Return `(ir_dict, None)` for serialized IR files or `(None, schema)` for a `.py` module."""
48
+ from .formats import FORMATS
49
+
50
+ text = _read_text(path)
51
+ suffix = pathlib.Path(path).suffix.lower() if path != "-" else ""
52
+ if suffix == ".py":
53
+ ns: dict = {"__name__": "oxide_parse_schema", "__file__": path}
54
+ try:
55
+ exec(compile(text, path, "exec"), ns)
56
+ except Exception as e:
57
+ raise CliError(f"{path}: {type(e).__name__}: {e}") from e
58
+ for name in ("schema", "SCHEMA"):
59
+ if name in ns:
60
+ return None, ns[name]
61
+ raise CliError(f"{path} must define a variable `schema`")
62
+
63
+ fmt = "json"
64
+ if suffix:
65
+ try:
66
+ fmt = FORMATS.for_path(path).name
67
+ except ValueError:
68
+ fmt = "json"
69
+ try:
70
+ data = FORMATS.loads(text, fmt)
71
+ except ImportError as e:
72
+ raise CliError(str(e)) from e
73
+ except Exception as e:
74
+ raise CliError(f"{path}: invalid {fmt.upper()} ({e})") from e
75
+ if isinstance(data, dict) and "baseSelector" in data:
76
+ raise CliError(f"{path} looks like a Crawl4AI schema: convert it first, `oxide-parse migrate --from crawl4ai {path}`")
77
+ return data, None
78
+
79
+
80
+ def _plan(path: str, backend: str) -> Any:
81
+ from .plan import Plan
82
+
83
+ ir, schema = _load_schema(path)
84
+ return Plan.from_ir(ir, backend) if schema is None else Plan(schema, backend)
85
+
86
+
87
+ def _ir_of(path: str) -> dict:
88
+ from .expr import to_ir
89
+
90
+ ir, schema = _load_schema(path)
91
+ return ir if schema is None else to_ir(schema)
92
+
93
+
94
+ # -- commands ---------------------------------------------------------------------------------------------------------------
95
+ def _cmd_distill(a: argparse.Namespace) -> int:
96
+ from .plan import distill
97
+
98
+ _write(distill(_read_text(a.html), keep=a.keep, max_text=a.max_text, max_chars=a.max_chars), a.out)
99
+ return 0
100
+
101
+
102
+ def _cmd_markdown(a: argparse.Namespace) -> int:
103
+ from .plan import markdown
104
+
105
+ _write(markdown(_read_text(a.html), a.selector, without=a.without, backend=a.backend), a.out)
106
+ return 0
107
+
108
+
109
+ def _cmd_run(a: argparse.Namespace) -> int:
110
+ from .formats import FORMATS
111
+
112
+ plan = _plan(a.schema, a.backend)
113
+ result = plan.extract(_read_text(a.html))
114
+ print(f"engine: {plan.engine}", file=sys.stderr)
115
+ if a.explain:
116
+ print(plan.explain(), file=sys.stderr)
117
+ try:
118
+ opts = {"indent": 2} if FORMATS.get(a.format).name == "json" else {}
119
+ rendered = FORMATS.dumps(result, a.format, **opts)
120
+ except (ImportError, ValueError) as e:
121
+ raise CliError(str(e)) from e
122
+ _write(rendered, a.out)
123
+ return 0
124
+
125
+
126
+ def _cmd_decompile(a: argparse.Namespace) -> int:
127
+ from .decompile import decompile
128
+
129
+ _write(decompile(_ir_of(a.schema), a.name), a.out)
130
+ return 0
131
+
132
+
133
+ def _cmd_validate(a: argparse.Namespace) -> int:
134
+ from .plan import validate_ir
135
+
136
+ errors = validate_ir(_ir_of(a.schema), a.backend)
137
+ for e in errors:
138
+ print(e, file=sys.stderr)
139
+ if not errors:
140
+ print("ok", file=sys.stderr)
141
+ return 1 if errors else 0
142
+
143
+
144
+ def _cmd_migrate(a: argparse.Namespace) -> int:
145
+ from . import migrate as m
146
+ from .formats import FORMATS
147
+
148
+ text = _read_text(a.file)
149
+ data: Any = None
150
+ loaded = False
151
+ if a.file != "-":
152
+ try:
153
+ codec = FORMATS.for_path(a.file)
154
+ if not codec.ir_only:
155
+ data = FORMATS.loads(text, codec.name)
156
+ loaded = True
157
+ except Exception:
158
+ loaded = False
159
+ if not loaded:
160
+ last_err: Optional[Exception] = None
161
+ for candidate in ("json", "yaml", "toml"):
162
+ try:
163
+ data = FORMATS.loads(text, candidate)
164
+ if not isinstance(data, dict):
165
+ raise ValueError(f"{candidate.upper()} schema must be an object")
166
+ loaded = True
167
+ break
168
+ except Exception as exc:
169
+ last_err = exc
170
+ if not loaded:
171
+ raise CliError(f"{a.file}: neither JSON, YAML, nor TOML ({last_err})")
172
+ try:
173
+ ir = m.from_crawl4ai(data, kind=a.kind, wrap=a.wrap) if a.source == "crawl4ai" else m.from_selector_map(data)
174
+ except m.MigrationError as e:
175
+ raise CliError(str(e)) from e
176
+ target_fmt = "json" if a.format == "ir" else a.format
177
+ try:
178
+ norm = FORMATS.get(target_fmt).name
179
+ if norm == "python":
180
+ rendered = FORMATS.dumps(ir, "python", name=a.name)
181
+ elif norm == "json":
182
+ rendered = FORMATS.dumps(ir, "json", indent=2)
183
+ else:
184
+ rendered = FORMATS.dumps(ir, norm)
185
+ except (ImportError, ValueError) as e:
186
+ raise CliError(str(e)) from e
187
+ _write(rendered, a.out)
188
+ return 0
189
+
190
+
191
+ def _cmd_prompt(a: argparse.Namespace) -> int:
192
+ from . import prompts
193
+
194
+ if a.kind == "generate":
195
+ fmt = getattr(a, "format", "python")
196
+ if fmt == "ir":
197
+ _write(prompts.ir_generate_prompt(kind=getattr(a, "kind_sel", "css")), a.out)
198
+ elif fmt == "crawl4ai":
199
+ _write(prompts.crawl4ai_schema_prompt(schema_type=getattr(a, "kind_sel", "css").upper(), output="crawl4ai"), a.out)
200
+ else:
201
+ _write(prompts.generate_prompt(), a.out)
202
+ else:
203
+ try:
204
+ _write(prompts.migrate_prompt(a.source), a.out)
205
+ except ValueError as e:
206
+ raise CliError(str(e)) from e
207
+ return 0
208
+
209
+
210
+ def _cmd_ir_schema(a: argparse.Namespace) -> int:
211
+ from .plan import ir_schema
212
+
213
+ _write(json.dumps(ir_schema(), ensure_ascii=False, indent=2), a.out)
214
+ return 0
215
+
216
+
217
+ def build_parser() -> argparse.ArgumentParser:
218
+ """Build the top-level CLI `ArgumentParser` with all `oxide-parse` subcommands.
219
+
220
+ Returns:
221
+ Configured parser instance.
222
+
223
+ Examples:
224
+ >>> from oxide_parse.__main__ import build_parser
225
+ >>> build_parser().parse_args(["validate", "schema.json"]).command
226
+ 'validate'
227
+ """
228
+ p = argparse.ArgumentParser(prog="oxide-parse", description="oxide_parse: declarative HTML extraction, from the shell.")
229
+ p.add_argument("--version", action="version", version=f"oxide-parse {__version__}")
230
+ sub = p.add_subparsers(dest="command", metavar="<command>")
231
+ sub.required = True
232
+
233
+ def add(name: str, help: str, fn: Any) -> argparse.ArgumentParser:
234
+ sp = sub.add_parser(name, help=help, description=help)
235
+ sp.set_defaults(fn=fn)
236
+ return sp
237
+
238
+ def out(sp: argparse.ArgumentParser) -> None:
239
+ sp.add_argument("--out", "-o", metavar="FILE", help="write here instead of stdout")
240
+
241
+ s = add("distill", "shrink an HTML file to a skeleton for a human or an LLM prompt", _cmd_distill)
242
+ s.add_argument("html", help="HTML file (- for stdin)")
243
+ s.add_argument("--max-chars", type=int, default=20000)
244
+ s.add_argument("--keep", type=int, default=2, help="similar siblings kept before folding (default 2)")
245
+ s.add_argument("--max-text", type=int, default=80, help="characters of text kept per node (default 80)")
246
+ out(s)
247
+
248
+ s = add("markdown", "convert an HTML file (or one element of it) to Markdown", _cmd_markdown)
249
+ s.add_argument("html", help="HTML file (- for stdin)")
250
+ s.add_argument("--selector", default="body", help="CSS selector of the element (default body)")
251
+ s.add_argument("--without", help="CSS selector of subtrees to leave out, e.g. '.ad, .share'")
252
+ s.add_argument("--backend", default="html")
253
+ out(s)
254
+
255
+ s = add("run", "run a schema (.json / .yaml / .toml IR, or a .py file defining `schema`) on an HTML file", _cmd_run)
256
+ s.add_argument("schema")
257
+ s.add_argument("html", help="HTML file (- for stdin)")
258
+ s.add_argument("--backend", default="auto", help="auto, html, lite, scraper, stream, xml (default auto)")
259
+ s.add_argument("--explain", action="store_true", help="print the execution plan to stderr")
260
+ s.add_argument("--format", choices=("json", "yaml", "toml"), default="json")
261
+ out(s)
262
+
263
+ s = add("decompile", "turn a JSON/YAML/TOML IR (or a .py schema) into readable Python code", _cmd_decompile)
264
+ s.add_argument("schema")
265
+ s.add_argument("--name", default="schema", help="variable name in the generated code")
266
+ out(s)
267
+
268
+ s = add("validate", "check a schema (.json/.yaml/.toml/.py) and report every problem with its path (exit 1 if any)", _cmd_validate)
269
+ s.add_argument("schema")
270
+ s.add_argument("--backend", default="auto")
271
+
272
+ s = add("migrate", "convert another tool's schema (Crawl4AI, flat selector map) to oxide_parse", _cmd_migrate)
273
+ s.add_argument("file", help="JSON/YAML/TOML file")
274
+ s.add_argument("--from", dest="source", choices=("crawl4ai", "selector-map"), required=True)
275
+ s.add_argument("--format", choices=("ir", "json", "python", "yaml", "toml"), default="ir")
276
+ s.add_argument("--kind", choices=("css", "xpath"), help="Crawl4AI strategy kind (default: guessed)")
277
+ s.add_argument("--wrap", metavar="NAME", help='return {"NAME": [...]} instead of the bare list')
278
+ s.add_argument("--name", default="schema", help="variable name for --format python")
279
+ out(s)
280
+
281
+ s = add("prompt", "print a system prompt for an LLM that writes or migrates schemas", _cmd_prompt)
282
+ s.add_argument("kind", choices=("generate", "migrate"))
283
+ s.add_argument("--from", dest="source", default="bs4", help="migrate: bs4, crawl4ai, scrapy, selectolax, lxml")
284
+ s.add_argument("--format", choices=("python", "ir", "crawl4ai"), default="python", help="generate target format")
285
+ s.add_argument("--selector-kind", dest="kind_sel", choices=("css", "xpath"), default="css", help="selector mode for --format ir")
286
+ out(s)
287
+
288
+ s = add("ir-schema", "print the JSON Schema of the IR", _cmd_ir_schema)
289
+ out(s)
290
+ return p
291
+
292
+
293
+ def main(argv: Optional[List[str]] = None) -> int:
294
+ """CLI entry point returning an integer process exit status.
295
+
296
+ Args:
297
+ argv: Argument vector excluding program name (defaults to `sys.argv[1:]`).
298
+
299
+ Returns:
300
+ `0` on success, `1` on handled CLI/schema/runtime errors.
301
+
302
+ Examples:
303
+ >>> from oxide_parse.__main__ import main
304
+ >>> main(["prompt", "generate", "--out", ""]) >= 0
305
+ True
306
+ """
307
+ for stream in (sys.stdout, sys.stderr):
308
+ try:
309
+ stream.reconfigure(encoding="utf-8") # type: ignore[union-attr] # Windows consoles default to cp125x
310
+ except (AttributeError, ValueError):
311
+ pass
312
+ args = build_parser().parse_args(argv)
313
+ try:
314
+ return int(args.fn(args))
315
+ except CliError as e:
316
+ print(f"oxide-parse: {e}", file=sys.stderr)
317
+ return 1
318
+ except BrokenPipeError:
319
+ return 0
320
+ except Exception as e:
321
+ print(f"oxide-parse: {type(e).__name__}: {e}", file=sys.stderr)
322
+ return 1
323
+
324
+
325
+ if __name__ == "__main__":
326
+ sys.exit(main())
oxide_parse/_core.pyd ADDED
Binary file
oxide_parse/_core.pyi ADDED
@@ -0,0 +1,114 @@
1
+ """Type stubs for the native extension module (`crates/py/src/lib.rs`).
2
+
3
+ Keep names aligned with `crates/py/src/lib.rs`: `tests/test_cli_and_release.py` verifies stub parity against the
4
+ compiled module when present.
5
+ """
6
+ from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
7
+
8
+ Source = Union[str, bytes, bytearray]
9
+
10
+ __version__: str
11
+ """Version string of the compiled Rust extension crate (`oxide_parse._core`)."""
12
+
13
+
14
+ class OxideParseError(Exception):
15
+ """Compilation, extraction, and session errors raised by the native extension."""
16
+
17
+
18
+ def engines() -> List[Tuple[str, str, bool, str]]:
19
+ """Return `(name, kind, xpath_supported, description)` tuples for compiled-in engines.
20
+
21
+ Examples:
22
+ >>> from oxide_parse import _core
23
+ >>> any(name == "json" for name, _, _, _ in _core.engines())
24
+ True
25
+ """
26
+
27
+
28
+ def distill(html: Source, keep: int = 2, max_text: int = 80, max_chars: int = 20000) -> str:
29
+ """Shrink HTML into a compact skeleton for LLM prompts or debugging (`lite` feature required).
30
+
31
+ Args:
32
+ html: HTML `str`, UTF-8 `bytes`, or `bytearray`.
33
+ keep: Similar sibling count retained before folding (`<!-- +N similar ... -->`).
34
+ max_text: Character limit per text node.
35
+ max_chars: Hard character limit on returned HTML.
36
+
37
+ Returns:
38
+ Distilled HTML skeleton string.
39
+ """
40
+
41
+
42
+ class Session:
43
+ """In-progress extraction holding pending `fetch` requests (`follow`/`paginate`) and selector `repair` requests."""
44
+
45
+ def pending(self) -> List[Tuple[int, Dict[str, Any]]]:
46
+ """Return open fetch requests as `(id, params)` tuples for `fetch(**params)`."""
47
+
48
+ def requests_json(self) -> str:
49
+ """Serialize all open requests (`fetch` and `repair`) as a JSON array string."""
50
+
51
+ def overrides(self) -> List[Tuple[str, str]]:
52
+ """Return selectors supplied by repairs so far as `(key, css)` tuples."""
53
+
54
+ def done(self) -> bool:
55
+ """Return `True` when no fetch requests remain pending (repairs are optional)."""
56
+
57
+ def errors(self) -> List[Tuple[str, str]]:
58
+ """Return records quarantined by `map(..., on_error=...)` as `(path, message)` tuples."""
59
+
60
+ def misses_json(self) -> str:
61
+ """Return unresolved `adaptive` selector misses serialized as JSON."""
62
+
63
+ def resume(self, items: List[Tuple[int, Any]]) -> None:
64
+ """Feed `(id, document)`, `(id, (document, meta_json))` fetches, `(id, {key: css})` repairs, or `(id, None)` declines."""
65
+
66
+ def result(self) -> Any:
67
+ """Consume and return the final extracted Python value once `done()` is `True`."""
68
+
69
+
70
+ class Plan:
71
+ """Thread-safe compiled extraction plan executed in Rust with the GIL released."""
72
+
73
+ def __init__(
74
+ self,
75
+ ir_json: str,
76
+ backend: str = "html",
77
+ adaptive_store: Optional[str] = None,
78
+ adaptive_state: Optional[str] = None,
79
+ ) -> None:
80
+ """Compile a JSON IR string for `backend` (`auto`, `html`, `stream`, `lite`, `scraper`, `xml`, `json`)."""
81
+
82
+ @property
83
+ def backend(self) -> str:
84
+ """Resolved execution engine name."""
85
+
86
+ def explain(self) -> str:
87
+ """Return the multi-line execution plan (selectors, peephole rewrites, streaming capture table)."""
88
+
89
+ def ir_json(self) -> str:
90
+ """Serialize the plan's IR back to JSON."""
91
+
92
+ def start(self, source: Source, meta_json: Optional[str] = None) -> Session:
93
+ """Start a stateful `Session` for `follow`, `paginate`, or manual `adaptive` repair."""
94
+
95
+ def extract(self, source: Source, meta_json: Optional[str] = None) -> Any:
96
+ """Run one-shot extraction over `source` (raises if pending requests are emitted)."""
97
+
98
+ def run_native(self, source: Source) -> int:
99
+ """Run extraction without creating Python objects; returns extracted value count for benchmarking."""
100
+
101
+ def extract_many(self, sources: Iterable[Source]) -> List[Any]:
102
+ """Extract all documents in parallel using Rayon with the GIL released."""
103
+
104
+ def extract_batch(self, sources: Iterable[Source], threads: Optional[int] = None, collect_errors: bool = False) -> Tuple[List[Any], List[Tuple[int, str]]]:
105
+ """Extract documents on a Rayon pool; with `collect_errors=True`, failed pages yield `(index, message)`."""
106
+
107
+ def export_adaptive_store(self) -> str:
108
+ """Serialize all learned `adaptive` selector fingerprints as JSON."""
109
+
110
+ def import_adaptive_store(self, state: str) -> int:
111
+ """Merge serialized fingerprints from `export_adaptive_store()`; returns count loaded."""
112
+
113
+ def forget_adaptive_keys(self, keys: List[str]) -> None:
114
+ """Delete stored baseline and `#healed` fingerprints for `keys`."""