Metadata-Version: 2.5
Name: uniparser2
Version: 0.8.0
Summary: A declarative, deterministic, serializable text parsing engine
Project-URL: Homepage, https://github.com/ClericPy/uniparser2
Project-URL: Repository, https://github.com/ClericPy/uniparser2
Project-URL: Issues, https://github.com/ClericPy/uniparser2/issues
Project-URL: Changelog, https://github.com/ClericPy/uniparser2/blob/master/CHANGELOG.md
Project-URL: Documentation, https://github.com/ClericPy/uniparser2/blob/master/README.md
Author: ClericPy
License-Expression: MIT
License-File: LICENSE
Keywords: declarative,dsl,extraction,html,json,llm,parser
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Text Processing :: Markup
Classifier: Typing :: Typed
Requires-Python: >=3.12
Provides-Extra: all
Requires-Dist: html-to-markdown>=3.0; extra == 'all'
Requires-Dist: jmespath>=1.0.1; extra == 'all'
Requires-Dist: lxml>=5.0; extra == 'all'
Requires-Dist: selectolax>=1.0; extra == 'all'
Provides-Extra: code
Requires-Dist: pydantic-monty>=1.0.0; extra == 'code'
Provides-Extra: html
Requires-Dist: selectolax>=1.0; extra == 'html'
Provides-Extra: json
Requires-Dist: jmespath>=1.0.1; extra == 'json'
Provides-Extra: md
Requires-Dist: html-to-markdown>=3.0; extra == 'md'
Provides-Extra: xml
Requires-Dist: lxml>=5.0; extra == 'xml'
Description-Content-Type: text/markdown

# uniparser2

[![PyPI](https://img.shields.io/pypi/v/uniparser2.svg)](https://pypi.org/project/uniparser2/)
[![Python](https://img.shields.io/pypi/pyversions/uniparser2.svg)](https://pypi.org/project/uniparser2/)
[![CI](https://github.com/ClericPy/uniparser2/actions/workflows/ci.yml/badge.svg)](https://github.com/ClericPy/uniparser2/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

**Turn text into structured data with JSON rules.** A declarative, self-describing parsing DSL:
deterministic, side-effect-free, and readable by humans and LLMs.

```jsonc
[["css1", "text", "h1.article-title"], ["py", "normalize_space"]]

// "<h1>  Hello   world </h1>"  →  "Hello world"
```

- **Rules are data.** A rule is JSON: diffable, storable, generated by an LLM, shipped without a release.
- **No side effects in the kernel.** The kernel performs no I/O and knows nothing about the host; the
  same input and rule produce the same output. The only non-determinism is an explicit host `udf`.
- **Failures are diagnostics.** A bad rule fails at **compile time** with a `UP2-E*` code, a JSON
  Pointer and a one-line fix.
- **Stories compose.** A story is a map of named nodes: call one from another, iterate a list with
  `each`, and fetch through a host `udf` — the engine stays synchronous and pure.

> Not "self-explanatory": a `css1` stage still needs CSS. It is **self-describing** — the JSON carries
> the operator, action and parameters, so a reader (or an LLM) can see what a rule does without the
> implementation, and move it between projects as data.

<details>
<summary><b>Install</b></summary>

```bash
uv add uniparser2             # kernel: zero third-party dependencies
uv add "uniparser2[html]"     # css / css1 (selectolax)
uv add "uniparser2[all]"      # every operator except the code sandbox
```

Python ≥ 3.12. Each operator declares its own extra; a missing one fails with `UP2-E1107` and the
install line, never a silent wrong value.

</details>

<details>
<summary><b>Security: what a rule can and cannot do</b></summary>

A default install — including `uniparser2[all]` — **carries no code execution**. A chain can only call
the operators and actions the registry declares. Custom logic enters through two explicit doors:

- `udf`: the chain names a function the host registered beforehand; the chain contains no body.
- `code`: an optional, language-level sandbox, not installed by default and not part of `[all]`; it is
  **not** OS-level isolation. The surfaces it lacks and the ones it merely blocks are listed in
  [`docs/specs/004` §11.3](docs/specs/004-persistence-and-sop.md).

Either door is greppable in the frozen rule (`udf` / `code`); there is no hidden host table.

</details>

<details>
<summary><b>30-second tour: a chain</b></summary>

A **chain** is a JSON array of stages `[operator, action, parameter]`:

```python
import uniparser2 as up2

chain = [["css1", "text", "h1"], ["py", "normalize_space"]]
outcome = up2.eval_field(up2.compile_field(chain), "<h1>  Hello   world </h1>")
print(outcome)  # Ok(value='Hello world')
```

A query that matches nothing is a **value** (`""` / `[]` / `None`), not an error; a bad stage stops the
chain with a code. The CLI gives the same run plus compile-time validation:

```bash
uv run up2 lint chain.json
uv run up2 trial chain.json --input 'text=<h1>  Hello   world </h1>' --json
# {"state": "ok", "value": "Hello world"}
```

</details>

<details>
<summary><b>Stories: nodes that call each other</b></summary>

A **story** is `{"globals": {...}, "nodes": {...}}`. A node body is a **chain** (array; `[]` is
identity) or a **field map** (object). A chain calls another node with `["node", name]`; a field map
evaluates every field on the node input, writes **every** result into `$locals`, and puts the fields
without a `_` prefix into the product. `["type", name]` ends a chain with a host-registered validator.

```jsonc
{
  "globals": {"base_url": "https://quotes.toscrape.com"},
  "nodes": {
    "authors": [["node", "links"], ["each", [["node", "author"]]]],
    "links": [
      ["py", "strip"], ["ctx", "dict", {"url": "obj"}],
      ["udf", "fetch"], ["py", "getattr", "text"],
      ["css", "@href", "div.quote a[href^='/author/']"], ["py", "uniq"],
      ["each", [["py", "urljoin", "$globals.base_url"]]]
    ],
    "author": [
      ["ctx", "dict", {"url": "obj"}],
      ["udf", "fetch"], ["node", "fields"], ["type", "Author"]
    ],
    "fields": {
      "url": [["py", "getattr", "url"]],
      "name": [["py", "getattr", "text"], ["css1", "text", "h3.author-title"],
               ["py", "normalize_space"]]
    }
  }
}
```

```python
import uniparser2 as up2

up2.register_type("Author", Author)  # a validator, not a container
product = up2.run(
    story, "authors", "https://quotes.toscrape.com", udfs={"fetch": my_fetch}
)  # synchronous; `fetch` blocks
```

`run(story, node=None, input=None, *, globals=None, udfs=None, trace=None)` returns the node's product
(the first node is the default). `globals` merges over the story's constants for that run. The exit and
a `type` stage require JSON; a response object may flow mid-chain and be read with `py.getattr`.
`fetch` takes a **request object** (`{"url": …}`); `["ctx","dict",{"url":"obj"}]` builds one from the
current value.

</details>

<details>
<summary><b>The GitHub pinned example (tested in the suite)</b></summary>

This is the template the test suite runs offline against fixtures
([`tests/chains/test_story.py`](tests/chains/test_story.py)): fetch a profile, take the first pinned
item, fetch its detail page, and read the status code plus an `[class*="Actions"]` text.

```jsonc
{
  "globals": {"base_url": "https://github.com"},
  "nodes": {
    "pinned": [
      ["node", "list"],
      ["each", [["udf", "claim"]]],
      ["py", "filter"],
      ["py", "first"],
      ["node", "detail"]
    ],
    "list": [
      ["py", "strip"],
      ["ctx", "dict", {"url": "obj"}],
      ["udf", "fetch"],
      ["py", "getattr", "text"],
      ["css", "nodes", "div.js-pinned-items-reorder-container ol > li"],
      ["each", {"url": [["css1", "@href", "a"],
                        ["py", "urljoin", "$globals.base_url"]]}]
    ],
    "detail": [
      ["node", "detail_request"],
      ["udf", "fetch"],
      ["py", "sleep", 2],
      ["node", "detail_parse"]
    ],
    "detail_request": {"url": [["py", "getitem", "url"]]},
    "detail_parse": {
      "url": [["py", "getattr", "url"]],
      "status": [["py", "getattr", "status_code"]],
      "actions": [
        ["py", "getattr", "text"],
        ["css1", "text", "[class*=\"Actions\"]"],
        ["py", "normalize_space"]
      ]
    }
  }
}
```

```python
import uniparser2 as up2
from uniparser2.net import RequestCache, fetch

cache = RequestCache()
seen: set[str] = set()


def cached_fetch(request):
    hit = cache.get(request)
    if hit is not None:
        return hit
    response = fetch(request)
    cache.put(request, response)
    return response


def claim(item):
    # Pretend this is the external dedupe store: a real one asks the DB/Redis.
    # The toy answers the item on first sight, None on a repeat; `py.filter` drops the None.
    if item["url"] in seen:
        return None
    seen.add(item["url"])
    return item


product = up2.run(
    story,
    "pinned",
    "https://github.com/ClericPy",
    udfs={"fetch": cached_fetch, "claim": claim},
)
# {"url": "https://github.com/ClericPy/awesome", "status": 200, "actions": "Actions"}
```

The offline fixture for this example carries the same pinned URL twice: `claim` answers the first
one and `None` for the second, and `py.filter` removes the `None` before `first`/`detail` run. A real
dedupe is a `udf` over the external store — that is the only IO in this pattern; the chain stays
pure. The toy uses a set rather than a coin flip so the documented product stays reproducible.

To fetch every pinned item, keep the claim/filter before the fan-out and replace `["py", "first"]`
with an `each` over the detail node, pausing after it:

```jsonc
"pinned": [
  ["node", "list"], ["each", [["udf", "claim"]]], ["py", "filter"],
  ["each", [["node", "detail"], ["py", "sleep", 2]]]
]
```

The selectors are site-specific; `fetch` is not built in — it is the conventional name for the host's
downloader.

</details>

<details>
<summary><b>More ETL examples</b></summary>

Eleven runnable stories live in [`examples/etl/`](examples/etl/): CSV rows, log lines, JSON orders,
an HTML table, an XML feed, one article, dedupe/sort, a typed invoice, a host `udf`, nested node
calls, and a nullable JSON field. Each case is `story.json` + `input.txt` + `expected.json`;
`uv run pytest tests/examples -q` runs every one and compares it with its committed product. They are
offline: no network, no store.

</details>

<details>
<summary><b>Operators</b></summary>

**12 operators, 81 `(operator, action)` pairs**; the registry is the authority, so ask it:

```bash
uv run up2 ops --json     # arity, slots, actions, parameter schema, dependencies, availability
```

| Operator | Engine (extra) | Actions |
|---|---|---|
| `css` / `css1` | selectolax (`[html]`) | `text` · `html` · `outer` · `@<attr>` · `remove` · `self` · `nodes` — all matches vs. first match |
| `xpath` | lxml (`[xml]`) | `text` · `self` · `nodes` |
| `json` | jmespath (`[json]`) | `get` — a jmespath expression |
| `re` | stdlib | `search` · `findall` · `sub` |
| `py` | stdlib | **48** allowlisted functions: text, collections, URL, time, encoding, conversion, predicates, `filter`, `sleep` |
| `ctx` | stdlib | `get` · `set` · `del` · `dict` · `list` (scope reads and writes) |
| `each` | stdlib | one field map or one chain per element of a list |
| `udf` | host-registered | any function in the run's table; DTO / `*` / `**` / one explicit argument |
| `node` | story | call another node with the current value as its `$in` |
| `type` | story | validate a chain-tail product against a registered type |
| `code` | pydantic-monty (`[code]`, not in `[all]`) | `run` — in-chain code in a language-level sandbox |

`py` has no `eval` / `exec` / `import`; `udf` is the only way host code enters. The kernel is the
standard library only and performs no I/O.

</details>

<details>
<summary><b>CLI and the template store</b></summary>

```bash
uv run up2 ops [--json]                 # the registry: write chains against this, not memory
uv run up2 lint site.json               # compile-time validation (does not execute)
uv run up2 trial site.json --node pinned --input text=@page.html --json
uv run up2 trial site.json --node pinned --trace    # one line per evaluated stage
uv run up2 conformance --check          # every declared pair/code has a visible test
```

A story that calls a `udf` needs a host; the CLI has none, so `up2 trial` reports `UP2-E1010` for it —
run it through a host recipe, or use `up2 snapshot` / `up2 test` with a filled request cache.

A finished rule is stored under a business identity (`04` §1–§6): `publish` is the only write entry
point, it lints again before writing, keeps one row per `(root_domain, tpl_key)` and appends a
fingerprint to an append-only audit.

```bash
export UP2_HOME=~/.uniparser2          # UP2_STORE=sqlite for SQLite
uv run up2 publish site.json --domain example.com --key 政府文件列表 --actor llm:claude --source agent
uv run up2 get example.com 政府文件列表      # the row + its fingerprint
uv run up2 audit example.com 政府文件列表    # who changed it to which fingerprint, when
uv run up2 snapshot site.json --domain … --key … --case list-2026-09 --accept
uv run up2 test example.com 政府文件列表     # a mismatch prints a JSON Pointer difference
```

</details>

<details>
<summary><b>Status and roadmap</b></summary>

**0.8.0.** L1 (the operator layer) is complete and mechanically audited. L2 is the **story** model:
`globals` + `nodes`, node calls, field maps and `$locals`, `["type", …]`, the synchronous `run`
facade, and `fetch` as a host `udf`. L3's **template store** is in: file and SQLite implementations,
fingerprints, append-only audit, and the `publish` / `get` / `audit` / `snapshot` / `test` / `doctor`
commands. The committed `samples/*/site.json` and their hosts run end to end.

Not there yet: `up2 list`, the in-place trial UI (`006`, design only), ADRs, pagination loops and
`first_ok` fallback groups (deferred changes). See [`docs/specs/007`
§3](docs/specs/007-source-decisions-and-roadmap.md).

The public API is `compile_field` / `compile_stage` / `compile_story` / `eval_field` / `run` plus the
value, scope and trace types. The store is its own layer, `uniparser2.store`.

</details>

<details>
<summary><b>Development</b></summary>

```bash
uv sync
uv run ruff format --check
uv run ruff check
uv run mypy
uv run pytest --cov=uniparser2.core --cov-fail-under=95   # `-n 4` for a parallel local run
uv run up2 conformance --check
```

The 8 design notes live in `docs/specs/` (index in [`docs/README.md`](docs/README.md)) and are the
source of truth for interfaces and DSL syntax. `uv run python demo.py` shows the operator layer;
`tools/demo_report.py` regenerates the machine-written catalogue. The operator table above is a
summary — the registry (`up2 ops --json`) is the authority.

</details>

## Documentation

- [`docs/README.md`](docs/README.md) — the design notes (`00`–`07`) and reference pages.
- [`docs/operator-reference.md`](docs/operator-reference.md) — every action and its worked example.
- [`docs/report/up2-report.md`](docs/report/up2-report.md) — one case per covered pair, generated
  (the coverage check at the top names any pair still missing).

## License

MIT. See [`LICENSE`](LICENSE).
