Metadata-Version: 2.5
Name: umf-tablespec
Version: 0.0.16
Summary: Python library for working with table schemas in Universal Metadata Format (UMF)
Author-email: Erik LaBianca <erik.labianca@gmail.com>
License-Expression: MIT OR Apache-2.0
License-File: LICENSE-APACHE
License-File: LICENSE-MIT
License-File: LICENSE.md
Keywords: data-quality,great-expectations,metadata,pyspark,schema,umf
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.11
Requires-Dist: click<9.0.0,>=8.0.0
Requires-Dist: gitpython<4.0.0,>=3.1.0
Requires-Dist: great-expectations<2.0.0,>=1.6.0
Requires-Dist: jsonschema<5.0.0,>=4.25.1
Requires-Dist: pydantic<3.0.0,>=2.0.0
Requires-Dist: pyyaml<7.0.0,>=6.0.0
Requires-Dist: rich<14.0.0,>=13.0.0
Requires-Dist: ruamel-yaml<1.0.0,>=0.18.0
Requires-Dist: sqlglot>=26.0.0
Requires-Dist: sqlparse<1.0.0,>=0.4.0
Requires-Dist: typer<0.26.0,>=0.9.0
Requires-Dist: umf-core==0.10.3
Provides-Extra: databricks
Requires-Dist: databricks-sdk<1.0.0,>=0.117.0; extra == 'databricks'
Provides-Extra: duckdb
Requires-Dist: duckdb-engine<1.0.0,>=0.15.0; extra == 'duckdb'
Requires-Dist: duckdb<2.0.0,>=1.0.0; extra == 'duckdb'
Requires-Dist: sqlalchemy<3.0.0,>=2.0.0; extra == 'duckdb'
Provides-Extra: excel
Requires-Dist: openpyxl>=3.1.0; extra == 'excel'
Provides-Extra: spark
Requires-Dist: pandas<4.0,>=2.0; extra == 'spark'
Requires-Dist: pyarrow<23.0.0,>=18.0.0; extra == 'spark'
Requires-Dist: pyspark<5.0.0,>=4.0.0; extra == 'spark'
Provides-Extra: tui
Requires-Dist: textual>=0.50.0; extra == 'tui'
Description-Content-Type: text/markdown

# tablespec

Python library for working with table schemas in Universal Metadata Format (UMF). Provides type-safe models, validation, profiling integration, and schema generation tools.

## Features

- **Type-Safe UMF Models**: Pydantic-based models with runtime validation
- **Schema Generation**: Generate SQL DDL, PySpark schemas, and JSON schemas from UMF
- **Great Expectations Integration**: Baseline expectation generation and constraint extraction
- **Profiling**: Native Spark profiles feed GX validation; schema reflection
  handles UMF creation for bootstrap
- **Validation**: Table validation against UMF specifications with Great Expectations
- **Type Mappings**: Convert between UMF, PySpark, JSON, and Great Expectations types
- **LLM Prompt Generation**: Generate structured prompts for documentation, validation rules, relationships, and survivorship logic
- **CLI**: Typer-based command-line interface with Rich output for schema management and conversion
- **Excel Conversion**: Bidirectional Excel export/import for domain expert collaboration
- **Split-Format UMF**: Git-friendly directory-based storage with automatic format detection
- **Sample Data Generation**: Healthcare-specific, constraint-aware sample data from UMF specs
- **Domain Type Inference**: Automatic detection of domain types (SSN, NPI, phone, state codes, etc.)
- **Change Management**: UMF diffing, atomic change application, and git-based changelogs
- **Data Profiling App**: Streamlit Databricks App for profiling, drift, load results, and in-app guidebook (`apps/data-profiling/`)

## Demo

[![asciicast](https://github.com/easel/tablespec/raw/main/examples/tablespec-demo.gif)](https://github.com/easel/tablespec/blob/main/examples/tablespec-demo.cast)

The demo walks through loading a UMF schema, generating SQL/PySpark/JSON schemas, type mappings, domain type inference, Great Expectations baseline generation, LLM prompt generation, UMF diffing, and PySpark validation with sample data generation.

[**Watch with narration (MP4)**](https://github.com/easel/tablespec/raw/main/examples/tablespec-demo-narrated.mp4)

Play the asciinema recording in your terminal:

```bash
# Install asciinema, then play the recording
asciinema play examples/tablespec-demo.cast

# Or run the demo live (requires umf-tablespec[spark])
uv run python examples/demo.py
```

## Installation

### Using uv (recommended)

```bash
# Add to your uv project
uv add umf-tablespec umf-core==0.10.3 --index https://documentdrivendx.github.io/tablespec/simple/ --default-index https://pypi.org/simple

# With Spark support (for profiling and validation)
uv add 'umf-tablespec[spark]' umf-core==0.10.3 --index https://documentdrivendx.github.io/tablespec/simple/ --default-index https://pypi.org/simple
```

### Using pip

```bash
# Install from GitHub Pages index
pip install umf-tablespec --index-url https://documentdrivendx.github.io/tablespec/simple/ --extra-index-url https://pypi.org/simple

# With Spark support
pip install 'umf-tablespec[spark]' --index-url https://documentdrivendx.github.io/tablespec/simple/ --extra-index-url https://pypi.org/simple
```

**Note**: The distribution is named `umf-tablespec`; its Python import package and CLI remain `tablespec`. Use the project index for `umf-tablespec` and PyPI for its dependencies.
`umf-core` distribution 0.10.3 is published on PyPI and is the direct package dependency. Its UMF document semantic version remains 0.10.0.

**Optional extras**:
- `umf-tablespec[spark]` - Adds PySpark support for `SparkToUmfMapper`, `TableValidator`, `SampleDataGenerator` (with Spark FK seeding), `BaselineService`, and table merge. Install this extra only if you need Spark-dependent features.

### Claude Code / Codex plugin

The tablespec agent skills ship as a plugin. In Claude Code:

```
/plugin marketplace add https://github.com/DocumentDrivenDX/tablespec
/plugin install tablespec@tablespec
```

The plugin ships six skills, loaded automatically by task relevance (or invoked directly, e.g.
`/tablespec:tablespec`):

- `tablespec` - routing layer and cross-cutting conventions
- `tablespec-umf-authoring` - authoring/editing split-format UMF specs
- `tablespec-pipeline` - bootstrap, compile the artifact tree, run the backbone
- `tablespec-validation` - Great Expectations suite lifecycle
- `tablespec-sql-plans` - derived/gold tables and SQL plan generation
- `tablespec-profiling-app` - the data-profiling Databricks App

The same skills also work without installing the plugin: a repo clone carries them under
`.claude/skills/` and `.agents/skills/`. For automation
(scripts, Dockerfiles), use the CLI form:

```bash
claude plugin marketplace add https://github.com/DocumentDrivenDX/tablespec
claude plugin install tablespec@tablespec
```

In Codex, the same plugin installs from the same marketplace:

```bash
codex plugin marketplace add DocumentDrivenDX/tablespec
codex plugin add tablespec@tablespec
```

The plugin version is pinned in `.claude-plugin/plugin.json`; each release bumps it so installed copies
refresh.

## Quick Start

### Loading and Saving UMF Files

```python
from tablespec import load_umf_from_yaml, save_umf_to_yaml, UMF

# Load UMF from YAML (see examples/ for sample files)
umf = load_umf_from_yaml("examples/schema.yaml")

# Access metadata
print(f"Table: {umf.table_name}")
print(f"Columns: {len(umf.columns)}")

# Modify and save
umf.description = "Updated description"
save_umf_to_yaml(umf, "updated_schema.yaml")
```

### Creating UMF Programmatically

```python
from tablespec import UMF, UMFColumn, Nullable

umf = UMF(
    version="1.0",
    table_name="Medical_Claims",
    description="Healthcare claims data",
    columns=[
        UMFColumn(
            name="claim_id",
            data_type="VARCHAR",
            length=50,
            description="Unique claim identifier",
            nullable=Nullable(MD=False, MP=False, ME=False)
        ),
        UMFColumn(
            name="claim_amount",
            data_type="DECIMAL",
            precision=10,
            scale=2,
            description="Claim amount in USD",
            nullable=Nullable(MD=True, MP=True, ME=True)
        )
    ]
)

save_umf_to_yaml(umf, "medical_claims.yaml")
```

### Generating Schemas

```python
from tablespec import generate_sql_ddl, generate_pyspark_schema, generate_json_schema

# Load UMF
umf = load_umf_from_yaml("examples/schema.yaml")
umf_dict = umf.model_dump()

# Generate SQL DDL
ddl = generate_sql_ddl(umf_dict)
print(ddl)

# Generate PySpark schema code
spark_schema = generate_pyspark_schema(umf_dict)
print(spark_schema)

# Generate JSON Schema
json_schema = generate_json_schema(umf_dict)
print(json_schema)
```

### Bootstrapping from Existing Spark Tables

```python
from tablespec import bootstrap_from_tables

artifacts = bootstrap_from_tables(
    spark,
    ["member"],
    "/tmp/tablespec-bootstrap",
    profile=True,
    dialect="databricks",
)

print(artifacts.manifest_path)
print(artifacts.table("member").suite_json)
```

`bootstrap_from_tables` reflects each Spark table into UMF, optionally profiles
the data to enrich the compiled validation suite, and persists the full
artifact tree in one call. The profiler enriches validation; it does not create
UMF.

Databricks-facing compile UX accepts `dialect="databricks"` for the Spark-family
SQL this bootstrap path emits. Internal emitters may normalize to `spark` when
the rendered SQL is identical.

This is the development bootstrap path. Production installs the published
`tablespec` wheel and consumes the committed artifact tree through the manifest;
it does not re-run the bootstrap orchestration from source-time Python.

### Generating a Guidebook

Render any directory of UMFs into a navigable, self-contained HTML guidebook —
one page per table, with per-column lineage (upstream derivation sources and
downstream consumers), validation rules, and a search index.

```bash
# Point it at a directory of UMFs
# (split table.yaml dirs, *.umf.json, and/or *.umf.yaml)
tablespec guidebook ./tables -o ./guidebook

# Then open ./guidebook/index.html in a browser, or serve it:
python -m http.server -d ./guidebook
```

```python
from pathlib import Path
from tablespec import generate_guidebook

written = generate_guidebook(root=Path("tables"), output_dir=Path("guidebook"))
print(f"Wrote {len(written)} files")
```

Discovery is flat and recursive. When UMFs live in subfolders, the guidebook
nests output as `<subfolder>/<table>.html` and the top index lists each
subfolder as a group; when every UMF sits at the root, the guidebook is flat.
Every page is self-contained (inline CSS, no JS frameworks, no network
requests) so it works opened from disk or served statically.

**Guidebook a Databricks catalog (two-step).** The guidebook consumes UMFs on
disk, so first generate UMFs from the catalog, then render them:

```python
from pathlib import Path
from tablespec import bootstrap_from_tables, generate_guidebook

# 1. Reflect catalog tables into UMFs (writes the artifact tree, incl. UMFs)
bootstrap_from_tables(spark, ["member", "claims"], "/tmp/catalog-umfs", profile=True)

# 2. Render the guidebook over the generated UMFs
generate_guidebook(root=Path("/tmp/catalog-umfs"), output_dir=Path("guidebook"))
```

`JdbcToUmfMapper` / `SparkToUmfMapper` (in `umf-tablespec[spark]`) are the lower-level
entry points if you want to control UMF generation directly before rendering.

**Without a Spark session** — e.g. inside a Databricks App, which has a SQL
warehouse but no `SparkSession` — reflect a UMF from `INFORMATION_SCHEMA` rows
instead. tablespec opens no connection; you supply the rows:

```python
from tablespec.profiling import umf_from_information_schema

umf = umf_from_information_schema("encounter", rows)  # rows from your warehouse
```

### Data Profiling App

`apps/data-profiling/` holds a Streamlit **Databricks App** that profiles and
compares Unity Catalog tables, tracks drift, shows nightly load + validation
results, and renders the guidebook in-app. See
[the guide](https://documentdrivendx.github.io/tablespec/guide/data-profiling-app/).

## Documentation

Full documentation is available at [documentdrivendx.github.io/tablespec](https://documentdrivendx.github.io/tablespec/):

- **[User Guide](https://documentdrivendx.github.io/tablespec/guide/umf-format/)** -- UMF format, schema generation, GX integration, CLI, Excel, and more
- **[API Reference](https://documentdrivendx.github.io/tablespec/api/models/)** -- Complete API documentation
- **[Development](https://documentdrivendx.github.io/tablespec/development/)** -- Setup, testing, and project structure

## License

Dual-licensed under MIT OR Apache-2.0, at your option. See [LICENSE.md](LICENSE.md).

## Shared UMF Python documents

TableSpec accepts UMF core 0.10.0 only. Retired core versions are refused.

TableSpec uses the official `umf-core` Python package from DocumentDrivenDX/umf
for shared document models, schemas, serialization and validation machinery.
TableSpec's pipeline extension remains in this repository.

```python
from tablespec.models import UMF
from tablespec.umf_loader import UMFLoader

loader = UMFLoader()
document = loader.load_document("tables/orders")  # legacy migration + archive
loader.save_document(document, "orders.umf.json")
view = UMF.from_document(document)  # existing compiler input
```

Normal JSON loading recognizes shared documents. Shared-loaded compiler views
retain their authoritative document; saving preserves unknown vocabularies. Edit
the document and derive a new view rather than modifying that view directly.
Legacy JSON/split APIs remain compatibility surfaces. Shared-to-split export
refuses because it would drop shared content.

Core Fields require explicit native `tablespec.pipeline` data_type refinements
for execution. The initial binding consumes shared names/descriptions/titles/
aliases and scalar families; other core constraints refuse until their native
execution mapping is qualified. Native contextual nullability, source declarations,
keys, relationships and pipeline policies remain TableSpec extension semantics.

### Document packs

Use `tablespec document-loader` for native Python fetch, complete BagIt/SHA-256
handoff, offline publication and periodic fixity audits. See the
[document-loader guide](docs/guide/document-loader.md) for DuckDB and named
Spark/Unity Catalog targets, preservation metadata and qualification limits.
