Metadata-Version: 2.4
Name: csvt-py
Version: 0.2.0
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Requires-Dist: pyarrow>=15
Requires-Dist: duckdb>=1.0 ; extra == 'duckdb'
Requires-Dist: pandas>=2.0 ; extra == 'pandas'
Requires-Dist: polars>=1.0 ; extra == 'polars'
Requires-Dist: pytest>=7 ; extra == 'test'
Requires-Dist: polars>=1.0 ; extra == 'test'
Requires-Dist: pandas>=2.0 ; extra == 'test'
Requires-Dist: duckdb>=1.0 ; extra == 'test'
Requires-Dist: mypy>=1.8 ; extra == 'test'
Requires-Dist: pyarrow-stubs ; extra == 'test'
Requires-Dist: pandas-stubs ; extra == 'test'
Requires-Dist: ruff>=0.6 ; extra == 'test'
Provides-Extra: duckdb
Provides-Extra: pandas
Provides-Extra: polars
Provides-Extra: test
Summary: CSVT — read schema-typed text tables as zero-copy Arrow data
Keywords: csv,arrow,parquet,polars,pandas,csvt
Author-email: Jörn Baetge <Joern@Baetge.net>
Maintainer-email: Jörn Baetge <Joern@Baetge.net>
License: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://codeberg.org/jb007/csvt
Project-URL: Issues, https://codeberg.org/jb007/csvt/issues
Project-URL: Repository, https://codeberg.org/jb007/csvt

# csvt — typed CSV for Python

Read [CSVT](https://codeberg.org/jb007/csvt) files — CSV with a YAML
front-matter schema — as **zero-copy Apache Arrow** data, and write Arrow data
back to typed, diff-friendly text.

```python
import csvt
import polars as pl

df = pl.from_arrow(csvt.reader("scores.csvt"))  # zero-copy
df = csvt.polars.read("scores.csvt")  # same data, cached as Parquet
csvt.write(df, "out.csvt", description="generated")
```

The package is a thin binding over the `csvt-core` Rust engine: the same
parser, schema merge and converter that power the `csvt` CLI. It is
library-only — use the CLI for command-line operations.

## Install

The distribution is published as `csvt-py`; the import package is `csvt`.

```bash
pip install csvt-py            # core (pyarrow)
pip install "csvt-py[polars]"  # extras: polars, pandas, duckdb
```

From a checkout:

```bash
uv venv .venv
uv pip install --python .venv/bin/python maturin pyarrow
.venv/bin/maturin develop --manifest-path csvt-py/Cargo.toml
```

Requirements: Python ≥ 3.10, `pyarrow` ≥ 15 (Rust ≥ 1.85 when building from
source). Optional extras: `polars`, `pandas`, `duckdb`.

## Quick start

```python
import csvt

# Front-matter + resolved columns as a dict
info = csvt.get_schema("data.csvt")
info["csvt_version"]  # "1.0"
[(c["name"], c["type"]) for c in info["columns"]]

# Zero-copy Arrow record batch reader
reader = csvt.reader("data.csvt")  # pyarrow.RecordBatchReader
table = reader.read_all()  # pyarrow.Table
```

Paths behave like the CLI: `.csvt.gz` / `.csv.gz` are decompressed
transparently, and a plain `.csv` picks up a sibling `<file>.csvt.yaml`
front-matter when present.

### Engines

`csvt.reader()` hands out a single-use stream, which makes it a poor fit for
repeated queries. The engine adapters parse the file once into a Parquet cache
and let the engine read that:

```python
import duckdb
import csvt

csvt.polars.scan("data.csvt")  # pl.LazyFrame — lazy, pushdown, reusable
csvt.polars.read("data.csvt")  # pl.DataFrame
csvt.pandas.read("data.csvt")  # pd.DataFrame

con = duckdb.connect()
csvt.duckdb.register(con, "data.csvt")  # view named "data", stays queryable
con.sql("SELECT * FROM data WHERE score > 90").show()
```

All three share one Parquet file per source, so mixing them costs one parse.
Each adapter is imported on first use — `import csvt` does not pull in Polars,
Pandas or DuckDB.

## API

| Function | Returns | Description |
| --- | --- | --- |
| `csvt.reader(path, cache_path=None)` | `pyarrow.RecordBatchReader` | Zero-copy stream of typed Arrow record batches (cached as Parquet) |
| `csvt.get_schema(path)` | `SchemaInfo` | Front-matter and resolved columns |
| `csvt.write(data, path, *, description=None, null_values=None, format=None)` | `None` | Serialize Arrow-compatible data (PyArrow, Polars, Pandas) to CSVT (or JSON Lines, by extension) |
| `csvt.polars.scan(path, *, cache=None)` | `polars.LazyFrame` | Lazy scan over the Parquet cache (predicate/projection pushdown) |
| `csvt.polars.read(path, *, cache=None)` | `polars.DataFrame` | Eager read of the Parquet cache |
| `csvt.pandas.read(path, *, cache=None, dtype_backend=None)` | `pandas.DataFrame` | Read the Parquet cache with pandas |
| `csvt.duckdb.register(con, path, *, name=None, cache=None, replace=False)` | `str` | Create a view over the Parquet cache; returns the view name |

All of them raise `csvt.CsvtError` on parse, merge, validation or I/O errors.

### Writing

```python
import pyarrow as pa

table = pa.table({"id": [1, 2], "name": ["a", "b"]})
csvt.write(table, "out.csvt", description="generated")

# Anything implementing the Arrow PyCapsule stream protocol works
import polars as pl

csvt.write(pl.DataFrame({"x": [1, 2]}), "out.csvt")
```

The CSVT schema is derived from the Arrow schema (names, types, nullability),
so `read → write → read` round-trips values, types and nulls. Empty tables
keep their typed schema as a header-only file.

### JSON Lines

Reading accepts both body syntaxes — `csvt.reader()` and `csvt.get_schema()`
handle `.jsonlt` (embedded front-matter) and plain `.jsonl` / `.ndjson`
(typed by a sibling `<file>.jsonl.csvt.yaml`). Writing picks the format from
the extension:

```python
csvt.write(table, "out.jsonlt")  # front-matter + one JSON object per row
csvt.write(table, "out.jsonl")  # body only — no schema in the file
csvt.write(table, "out.txt", format="jsonlt")  # explicit override
```

A `.jsonl` target cannot store `description`/`null_values`; passing either is
an error rather than a silent drop — write `.jsonlt` if you need them. v1
covers flat records: `variant` columns hold JSON *text*, and nested values are
rejected on read.

## Caching

`reader()` always caches the parsed data as Parquet in
`$TMPDIR/csvt-cache/`. Pass `cache_path` to reuse a specific file — you own its
invalidation:

```python
csvt.reader("data.csvt")  # fresh temp file each call
csvt.reader("data.csvt", cache_path="data.parquet")  # reuse this file
```

The engine adapters cache for you: one file per source, named after it, reused
while the source's size and modification time are unchanged and rebuilt when
they are not. Pass `cache=` to choose the directory (default
`$TMPDIR/csvt-cache`):

```python
csvt.polars.scan("data.csvt", cache="cache")  # cache/data-1a2b3c4d5e6f.parquet
```

See [docs/caching.md](https://codeberg.org/jb007/csvt/src/branch/main/docs/caching.md)
for details and benchmarks.

## Type checking

The package ships PEP 561 stubs (`py.typed` + `core.pyi`), so `mypy --strict`
and IDE completion work out of the box:

```python
import csvt

info = csvt.get_schema("data.csvt")  # csvt.core.SchemaInfo
name: str = info["columns"][0]["name"]
```

## Documentation

- [Python guide & cookbook](https://codeberg.org/jb007/csvt/src/branch/main/docs/python.md)
- [Getting started](https://codeberg.org/jb007/csvt/src/branch/main/docs/getting-started.md)
- [Format reference](https://codeberg.org/jb007/csvt/src/branch/main/docs/format-1.0.md)
- [CLI guide](https://codeberg.org/jb007/csvt/src/branch/main/docs/cli.md)

## Development

```bash
uv venv .venv
uv pip install --python .venv/bin/python maturin pyarrow pytest polars pandas duckdb mypy pyarrow-stubs pandas-stubs ruff
.venv/bin/maturin develop --manifest-path csvt-py/Cargo.toml
.venv/bin/pytest csvt-py/tests -v
.venv/bin/ruff format csvt-py
.venv/bin/ruff check csvt-py
```

## License

MIT

