Metadata-Version: 2.5
Name: rowport
Version: 0.1.0
Summary: Spreadsheet imports for your product: map the columns, see every bad cell, fix them, get clean typed rows.
Project-URL: Homepage, https://github.com/GebleaAlex/rowport
Project-URL: Documentation, https://github.com/GebleaAlex/rowport#readme
Project-URL: Issues, https://github.com/GebleaAlex/rowport/issues
Project-URL: Changelog, https://github.com/GebleaAlex/rowport/blob/main/CHANGELOG.md
Author: Alex Geblea
License-Expression: MIT
License-File: LICENSE
Keywords: column mapping,csv import,data cleaning,data import,data onboarding,data validation,excel import,fastapi,importer,polars,spreadsheet
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Office/Business
Classifier: Topic :: Software Development :: Libraries
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: fastexcel>=0.12
Requires-Dist: polars>=1.20
Provides-Extra: dev
Requires-Dist: fastapi>=0.110; extra == 'dev'
Requires-Dist: httpx>=0.27; extra == 'dev'
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: openpyxl>=3.1; extra == 'dev'
Requires-Dist: pydantic>=2; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: python-multipart>=0.0.9; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Requires-Dist: uvicorn[standard]>=0.29; extra == 'dev'
Requires-Dist: xlsxwriter>=3.1; extra == 'dev'
Provides-Extra: server
Requires-Dist: fastapi>=0.110; extra == 'server'
Requires-Dist: httpx>=0.27; extra == 'server'
Requires-Dist: pydantic>=2; extra == 'server'
Requires-Dist: python-multipart>=0.0.9; extra == 'server'
Requires-Dist: uvicorn[standard]>=0.29; extra == 'server'
Requires-Dist: xlsxwriter>=3.1; extra == 'server'
Description-Content-Type: text/markdown

# rowport

[![CI](https://github.com/GebleaAlex/rowport/actions/workflows/ci.yml/badge.svg)](https://github.com/GebleaAlex/rowport/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/GebleaAlex/rowport/blob/main/LICENSE)
![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)

**Spreadsheet imports for your product.** Your users upload a CSV or Excel file; rowport matches its
columns to your fields, shows every cell that is wrong and why, lets them fix it in place, and hands
your application clean, typed rows.

![The review step: issues grouped on the left, the grid with bad cells marked on the right](https://raw.githubusercontent.com/GebleaAlex/rowport/main/docs/review.png)

It comes in three layers, and you can stop at any of them:

| Layer | What it is | Use it when |
| --- | --- | --- |
| **Engine** | A Python library on top of Polars | You have a file and a schema and want rows and errors |
| **Server** | An HTTP API (FastAPI) with an OpenAPI description | Your backend is not Python, or imports need a UI |
| **Widget** | A React component and a `<rowport-importer>` custom element | You want the upload → match → review → import screens |

## Why another importer

Every B2B product ends up writing this screen, usually twice. The hard parts are always the same:

* **The file is never what you asked for.** A title above the header, `1.234,50` next to `1,234.50`,
  `03/04/2024` that is April in one office and March in another, three spellings of one country.
* **"Row 4812 is invalid" helps nobody.** People need the cell, the reason, and a way to fix 400
  identical mistakes at once.
* **It has to work at 500,000 rows**, not just in the demo.

rowport reads conventions from the column as a whole (and tells the user what it assumed), reports
issues per cell with a message a non-developer can act on, groups them so one fix covers every
occurrence, and does all of it in Polars: a million rows are read and validated in under a second.

## Try it in a minute

```bash
pip install "rowport[server]"
rowport serve --demo --schema customers.schema.json
```

Open <http://127.0.0.1:8787> and drop in a file. `--demo` needs no API key and is meant for your
laptop only. The repository has an example schema and a deliberately messy file to try:
[`examples/`](https://github.com/GebleaAlex/rowport/tree/main/examples).

Or with Docker, from a checkout:
`docker build -t rowport . && docker run -p 8787:8787 -e ROWPORT_DEMO=1 rowport`.

## The engine

```python
from rowport import Choice, Field, Rule, Schema, check

schema = Schema(
    fields=[
        Field("name", label="Full name", required=True),
        Field("email", type="email", required=True, unique=True),
        Field("country", type="choice", choices=[Choice("RO", "Romania"), Choice("DE", "Germany")]),
        Field("signup", type="date"),
        Field("amount", type="decimal", scale=2),
        Field("seats", type="integer", minimum=1, maximum=4),
        Field("end", type="date"),
    ],
    rules=[Rule("compare", left="end", op=">=", right="signup")],
)

result = check("customers.xlsx", schema)

result.valid_row_count, result.invalid_row_count   # (1031, 169)
for row in result.rows():                          # only the valid ones, typed
    ...                                            # {'name': 'Ana Pop', 'signup': date(2024, 12, 31), 'amount': Decimal('1234.50'), ...}
result.issues                                      # a Polars frame: row, field, code, value, detail
result.notes                                       # what was assumed about whole columns
result.write("clean.parquet")                      # or .csv, .jsonl
```

The same from a shell, with a non-zero exit code when something is wrong:

```console
$ rowport check customers-messy.csv --schema customers.schema.json
1,200 rows: 1,054 valid, 146 with issues
  row 9, E-mail: Must be an e-mail address, like name@example.com. (got 'carol.radu5example.com')
  row 13, Full name: This field is required. (got None)
  row 14, Country: Not one of the allowed values. Did you mean Romania? (got 'Rumania')
  ...
```

### What it works out for you

* **Where the table starts.** Titles and blank lines above the header are skipped; row numbers in
  messages are the ones the user sees in their file.
* **Encoding and delimiter** of CSV files (UTF-8 with or without BOM, UTF-16, Windows-1250 and
  1252; comma, semicolon, tab, pipe). Ragged rows keep their extra cells, and when a guess is
  wrong the user, or your code, can name the encoding and the delimiter.
* **Which column is which field**, from the header (against key, label and aliases, ignoring case,
  accents and punctuation) and from the content (a column of e-mail addresses is the e-mail field
  whatever it is called). Each match comes with a confidence and a reason.
* **Decimal comma or decimal point**, per column. `1.234,5` and `12,5` settle it; `1,234` alone does
  not, so it follows the rest of the column, and you get a note when the whole column is ambiguous.
  Digit grouping has to be real grouping: a stray `12,5` in a column of `1,234.50` is reported, not
  read as 125.
* **Day-first or month-first dates**, per column. One `25/04/2024` settles it for the column. Excel
  dates and serial numbers are read as dates, and timestamps with a UTC offset are converted to UTC;
  both leave a note saying so.
* **Exact decimals.** A `decimal` field never passes through a float: `1.10` stays `1.10`, and its
  bounds and comparisons are exact to 18 decimal places.
* **Choices by any spelling**: value, label or alias, ignoring case and accents, with a suggestion
  for near misses (`Rumania` → `Romania`).

### Field types and options

| Type | Reads | Options |
| --- | --- | --- |
| `string` | text | `min_length`, `max_length`, `pattern`, `case` |
| `integer` | `42`, `1 000`, `3.0` | `minimum`, `maximum` |
| `number` | floats, currency symbols, `(100)` as negative | `minimum`, `maximum`, `decimal_separator`, `percent` |
| `decimal` | the same, kept exact | plus `scale` |
| `boolean` | yes/no, true/false, 1/0, da/nu, x | |
| `date`, `datetime` | ISO, `31/12/2024`, `12/31/2024`, `31 Dec 2024`, Excel serials | `minimum`, `maximum`, `formats`, `day_first` |
| `email`, `url` | | |
| `choice` | any spelling of a listed value | `choices` |

Every field also takes `label`, `required`, `unique`, `default`, `aliases`, `description` and
`example`. Rules across fields: `compare` (end ≥ start), `unique_together`, `required_if`.

A schema is plain data: `schema.to_json()` / `Schema.from_json()`. That JSON is what a non-Python
host sends to the server.

Rows come out typed: `result.rows()` gives Python `date`, `datetime`, `Decimal`, `int`, `bool`. In
files, a `decimal` is written as text (`"1234.50"`) so that no reader rounds it, and a `datetime`
as ISO 8601.

## The server

```bash
export ROWPORT_API_KEYS=change-me          # your backend's key; several, comma-separated
export ROWPORT_SECRET=$(openssl rand -hex 32)
export ROWPORT_SCHEMA_DIR=./schemas        # one JSON file per import, served by its "name"
export ROWPORT_CORS_ORIGINS=https://app.example.com   # the pages that embed the widget
uvicorn rowport.server.asgi:app --host 0.0.0.0 --port 8787 --workers 4
```

or `docker build -t rowport . && docker run -p 8787:8787 -v rowport-data:/data -e ROWPORT_API_KEYS=... rowport`.

The flow, from any language:

```bash
# 1. your backend starts an import and gets a token for the browser
curl -X POST $ROWPORT/v1/sessions -H "Authorization: Bearer $KEY" \
     -H "Content-Type: application/json" \
     -d '{"schema_name": "customers", "metadata": {"tenant": "acme", "user": 42}}'
# → {"id": "…", "token": "rp1.…", "expires_at": 1767225600, …}

# 2. the widget (or you) uploads, maps, reviews, fixes and commits with that token
#    PUT /v1/sessions/{id}/file · PUT …/source · PUT …/mapping · GET …/rows · GET …/issues
#    PATCH …/cells · POST …/replace · POST …/delete-rows · POST …/commit

# 3. your backend receives the rows: by webhook, or by fetching them
curl "$ROWPORT/v1/sessions/$ID/result?format=jsonl" -H "Authorization: Bearer $KEY"
```

Every call, its answer and every error code are in [docs/api.md](https://github.com/GebleaAlex/rowport/blob/main/docs/api.md). A running server
also describes its requests at `/docs` and `/openapi.json`.

**Getting the rows.** Pick what suits your stack:

* **Webhook** (`ROWPORT_WEBHOOK_URL`, `ROWPORT_WEBHOOK_SECRET`): batches of `import.rows` events and
  a closing `import.completed`. Each request is signed together with its timestamp, so it can be
  neither forged nor replayed, and carries an `X-Rowport-Delivery` id that stays the same across
  retries. The outcome is on the session as `delivery`; `POST /v1/sessions/{id}/deliver` sends a
  failed one again.

  ```python
  from rowport.server import verify_webhook

  genuine = verify_webhook(secret, raw_body, headers["X-Rowport-Signature"], headers["X-Rowport-Timestamp"])
  # elsewhere: signature == "sha256=" + hex(hmac_sha256(secret, timestamp + "." + raw_body))
  ```
* **Pull**: `GET /v1/sessions/{id}/result` as `jsonl`, `csv` or `parquet`.
* **In-process**, when you embed the server in a Python application. The import is only marked
  committed after your function returns; if it raises, the user sees an error and can try again.

```python
from fastapi import FastAPI
from rowport.server import ServerConfig, create_app

def save(session, result):
    tenant = session.meta["metadata"]["tenant"]
    Customer.objects.bulk_create(Customer(tenant=tenant, **row) for row in result.rows())

app = FastAPI()
app.mount("/imports", create_app(ServerConfig(api_keys={"…"}, schemas={"customers": schema}, on_commit=save)))
```

## The widget

React:

```tsx
import { RowportImporter } from "rowport";
import "rowport/rowport.css";

<RowportImporter
  apiUrl="https://imports.example.com"
  sessionId={session.id}
  token={session.token}
  locale="en"
  onComplete={(summary) => refetchCustomers()}
/>
```

Anything else (Vue, Angular, a Django template): one script, one element.

```html
<script src="https://imports.example.com/widget/rowport.element.js"></script>
<rowport-importer api-url="https://imports.example.com" session-id="…" token="…" locale="ro"></rowport-importer>
<script>
  document.querySelector("rowport-importer").addEventListener("rowport:complete", (e) => console.log(e.detail));
</script>
```

It walks the user through **Upload → Match columns → Review → Done**, in English or Romanian, light
or dark, and themes with CSS variables (`--rp-accent`, `--rp-radius`, …). The grid loads rows on
demand, so it stays responsive on a million-row file. A page reload resumes where the user was.
Details: [`web/README.md`](https://github.com/GebleaAlex/rowport/blob/main/web/README.md).

| | |
| --- | --- |
| ![Matching columns to fields, with confidence and sample values](https://raw.githubusercontent.com/GebleaAlex/rowport/main/docs/match.png) | ![Dark theme, Romanian](https://raw.githubusercontent.com/GebleaAlex/rowport/main/docs/review-dark-ro.png) |

## Built to run in production

* **Stateless workers.** A session is a directory (the upload, the rows as Parquet, the last
  validation). Any worker can serve any request; put the data directory on a shared volume and run
  as many as you need, with no sticky sessions.
* **No lost updates.** A change takes an operating-system lock on the session, released even if the
  worker dies, and carries the version the client saw: a stale edit is refused, never merged silently.
* **Two kinds of credential.** Your backend holds an API key. The browser only ever gets a signed,
  expiring token that opens one session: it cannot create sessions, see other sessions or your
  metadata, or (unless you allow it) download the result.
* **Limits that hold.** Upload size is enforced while the bytes arrive, not after; rows and columns
  are capped; a workbook is measured before it is opened (what it really unzips to, and the grid
  its sheets span), so a 20 kB file cannot ask for 20 GB; the number of requests holding a whole
  file in memory is bounded, and the rest get `503 busy` with `Retry-After` instead of taking the
  server down.
* **A commit that cannot half-happen.** With `on_commit`, a failure in your code leaves the import
  open. Committing twice is harmless. Webhook deliveries are signed, tried up to four times, and
  can be sent again on request.
* **An audit log** of who did what to which session (upload, map, edit, replace, commit, download)
  with counts and never cell contents, in a file and on the `rowport.audit` logger.
* **Safe files out.** The "rows with issues" download is opened in Excel, and its content came from
  an upload, so cells that would run as formulas are neutralised.
* **One error shape.** Every failure, including unknown routes and invalid requests, is
  `{"error": {"code", "message"}}`; unexpected errors are logged and never echoed.
* **Typed and tested.** `mypy --strict`, Ruff, and a test suite over the engine, the reader, the
  session store and the HTTP API, which passes on both the oldest and the newest supported
  dependencies. The examples in this README are run by that suite.

Settings, sizing and a go-live checklist: [docs/configuration.md](https://github.com/GebleaAlex/rowport/blob/main/docs/configuration.md).
What it defends against, and what is left to you: [SECURITY.md](https://github.com/GebleaAlex/rowport/blob/main/SECURITY.md).

## Speed

`python benchmarks/bench.py` on a 1,000,000-row, 8-column, 77 MB CSV with about 12% bad rows
(Intel Core i5-14600K, 32 GB, Windows 11, Python 3.14, Polars 2.2):

| Step | Time |
| --- | ---: |
| Read the file, find the header, suggest the mapping | 0.5 s |
| Validate every cell | 0.8 s |
| Fetch a page of 200 rows with issues | 0.03 s |
| Replace one misspelt value everywhere and re-validate | 0.8 s |
| Edit one cell and re-validate | 0.8 s |
| Drop the rows that still have issues | 0.7 s |

A 300,000-row `.xlsx` (14 MB) reads in 1.5 s, of which 0.6 s is measuring the workbook before it is
opened, and validates in 0.3 s on the same machine. The worst case, a million rows in which every
cell of every field is wrong (eight million issues), validates in 0.6 s and still pages in under
0.2 s.
Your numbers will differ; the script is there so you can measure your own.

## What it does not do (yet)

* **Storage is a directory.** Shared volumes (NFS, EFS, a Kubernetes PVC) work; object storage such
  as S3 is not supported directly.
* **A file is held in memory while a request works on it.** That is comfortable for the million-row
  case above and is what the row limit is for; it is not a streaming engine for files larger than RAM.
* **Phone numbers, addresses and other locale-heavy types** are plain strings with a `pattern`.
* **No rate limiting, TLS or virus scanning** in the server; put those in front of it.
* **Two interface languages** (English, Romanian). Messages are a small dictionary and more are
  welcome. The `message` of an API error is English only; clients branch on its `code`.
* **Error cells of a workbook** (`#N/A`, `#DIV/0!`) arrive as empty cells, so a required field
  reports them as missing rather than as an error value.

## Development

```bash
python -m venv .venv && . .venv/bin/activate      # .venv\Scripts\activate on Windows
pip install -e ".[dev]"
pytest && ruff check src tests && mypy

cd web && npm install && npm run build             # builds the widget and copies it into the server
python examples/make_samples.py                    # regenerate the example schema and file
```

See [CONTRIBUTING.md](https://github.com/GebleaAlex/rowport/blob/main/CONTRIBUTING.md). Licensed under the [MIT License](https://github.com/GebleaAlex/rowport/blob/main/LICENSE).
