Metadata-Version: 2.4
Name: csvnorm
Version: 1.5.0
Summary: A command-line utility to validate and normalize CSV files
Author-email: aborruso <aborruso@gmail.com>
License: MIT License
        
        Copyright (c) 2026 aborruso@gmail.com
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/aborruso/prepare_data
Project-URL: Issues, https://github.com/aborruso/prepare_data/issues
Keywords: csv,data,normalization,validation,etl
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
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: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Utilities
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: charset-normalizer>=3.0.0
Requires-Dist: duckdb<3,>=2.0.0
Requires-Dist: ftfy>=6.3.1
Requires-Dist: requests>=2.31.0
Requires-Dist: rich>=13.0.0
Requires-Dist: rich-argparse>=1.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.8.0; extra == "dev"
Requires-Dist: types-requests>=2.31.0; extra == "dev"
Dynamic: license-file

[![PyPI version](https://badge.fury.io/py/csvnorm.svg)](https://pypi.org/project/csvnorm/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/aborruso/csvnorm)

# csvnorm

A command-line utility to validate and normalize CSV files for initial exploration.

## Version 1.0 Breaking Change

**If upgrading from v0.x:** The default output has changed from file to stdout for better Unix composability.

```bash
# v0.x behavior
csvnorm data.csv              # Created data.csv in current directory

# v1.0 behavior (NEW)
csvnorm data.csv              # Outputs to stdout
csvnorm data.csv -o clean.csv  # Explicitly save to file
csvnorm data.csv > clean.csv   # Or use shell redirect
```

Never redirect to the input file (`csvnorm data.csv > data.csv`): the shell empties `data.csv` before csvnorm starts, and the data is lost. csvnorm refuses to overwrite its input only when the output path is given with `-o`.

This follows the Unix philosophy and matches tools like `jq`, `csvkit`, and `xsv`.

## Installation

Recommended (uv):

```bash
uv tool install csvnorm
```

Or with pip:

```bash
pip install csvnorm
```

The package and the command are both called `csvnorm`. Check the installed version and read the help (both work offline):

```bash
csvnorm --version
csvnorm --help
```

The help covers what csvnorm does and does not do, a first three-command path, the output, the exit codes and the limits. It describes the installed version; this README follows the `main` branch and can describe features not yet released.

## Purpose

This tool prepares CSV files for **basic exploratory data analysis (EDA)**, not for complex transformations. It focuses on achieving a clean, standardized baseline format that allows you to quickly assess data quality and structure before designing more sophisticated ETL pipelines.

**What it does:**
- Validates CSV structure and reports errors
- Normalizes encoding to UTF-8 when needed
- Normalizes delimiters and field names
- Creates a consistent starting point for data exploration

**What it doesn't do:**
- Complex data transformations or business logic
- Type inference or data validation beyond structure
- Heavy processing or aggregations

## Features

- **CSV Validation**: Checks for common CSV errors and inconsistencies using DuckDB
- **Delimiter Normalization**: Converts all field separators to standard commas (`,`)
- **Field Name Normalization**: Converts column headers to snake_case format (SQL keywords such as `select` keep their name, with any output delimiter)
- **Encoding Normalization**: Auto-detects encoding and converts to UTF-8 when needed (ASCII is already UTF-8 compatible)
- **Processing Summary**: Displays comprehensive statistics (rows, columns, file sizes) and error details
- **Error Reporting**: Exports detailed error file for invalid rows with summary panel
- **Remote URL Support**: Process CSV files directly from HTTP/HTTPS URLs without downloading (unless `--fix-mojibake` is used)

## Usage

```bash
csvnorm input.csv [options]
csvnorm -                    # read from stdin
```

**By default, csvnorm writes to stdout** for easy piping and composability with other Unix tools. Use `-` as input to read from stdin.

### Options

| Option | Description |
|--------|-------------|
| `-o, --output-file PATH` | Write to file instead of stdout |
| `-f, --force` | Force overwrite of existing output file (when `-o` is specified) |
| `-k, --keep-names` | Keep original column names (disable snake_case) |
| `-d, --delimiter CHAR` | Set custom output delimiter (default: `,`) |
| `-e, --encoding NAME` | Declare the input encoding (any Python codec name, e.g. `cp1252`, `latin-1`, `cp850`) and skip automatic detection; exit code 2 if the input cannot be decoded with it |
| `-s, --skip-rows N` | Skip first N rows of input file (useful for metadata/comments) |
| `--fix-mojibake [N]` | Fix mojibake using ftfy (optional sample size `N`; use `0` to force repair) |
| `--strict` | Write no output (stdout or file) if any validation errors occur; an existing output file is left untouched, even with `--force`. Exit code is 1 on validation errors with or without `--strict` |
| `--check` | Validate CSV without processing or normalizing (exit code 0 valid, 1 rows rejected, 2 could not run) |
| `--download-remote` | Deprecated, no effect: URLs are always downloaded before processing |
| `-V, --verbose` | Enable verbose output for debugging |
| `-v, --version` | Show version number (one plain line when not on a terminal) |
| `-h, --help` | Show help message |

### Examples

```bash
# Default: output to stdout
csvnorm data.csv

# Read from stdin
cat data.csv | csvnorm -
curl -s https://example.com/data.csv | csvnorm - -o clean.csv
csvnorm - --check < data.csv

# Preview first rows
csvnorm data.csv | head -20

# Pipe to other tools
csvnorm data.csv | csvcut -c name,age | csvstat

# Save to file
csvnorm data.csv -o output.csv

# Shell redirect
csvnorm data.csv > output.csv

# Process remote CSV from URL
csvnorm "https://raw.githubusercontent.com/aborruso/csvnorm/refs/heads/main/test/Trasporto%20Pubblico%20Locale%20Settore%20Pubblico%20Allargato%20-%20Indicatore%202000-2020%20Trasferimenti%20Correnti%20su%20Entrate%20Correnti.csv" -o output.csv

# Process remote compressed CSV (downloaded first, then handled locally)
csvnorm "https://example.com/data.csv.gz" -o output.csv

# Custom delimiter
csvnorm data.csv -d ';' -o output.csv

# Keep original headers
csvnorm data.csv --keep-names -o output.csv

# Skip first 2 rows (metadata or comments)
csvnorm data.csv --skip-rows 2 -o output.csv

# Declare the input encoding instead of detecting it
csvnorm data.csv -e cp1252 -o output.csv

# Force overwrite with verbose output
csvnorm data.csv -f -V -o processed.csv

# Fix mojibake using ftfy (default sample size)
csvnorm data.csv --fix-mojibake -o fixed.csv

# Fix mojibake with custom sample size
csvnorm data.csv --fix-mojibake 4000 -o fixed.csv

# Force mojibake repair even with low badness score
csvnorm data.csv --fix-mojibake 0 -o fixed.csv

# Fail-fast mode: exit with error if validation errors occur
csvnorm data.csv --strict > output.csv || echo "Validation failed!"

# Use in pipelines where data quality is critical
csvnorm remote_data.csv --strict | other_tool || handle_error

# Quick validation check (no processing or output)
csvnorm data.csv --check && echo "Valid CSV" || echo "Invalid CSV"

# Check remote CSV for validity
csvnorm https://example.com/data.csv --check

# Use in CI/CD pipelines for validation
csvnorm raw_data.csv --check || exit 1
```

### Output

**Default behavior (stdout):**
- Writes normalized CSV to stdout
- Progress and errors go to stderr
- Validation errors (if any) are shown to stderr **before** the output data
- Reject file saved in the system temp directory as `csvnorm_reject_errors_<id>.csv`; its full path is shown on stderr (`Details:`). Nothing is written in the current directory
- Perfect for piping to other tools or shell redirection

**File output (with `-o`):**
- Creates a normalized CSV file at the specified path with:
  - UTF-8 encoding
  - Consistent field delimiters
  - Normalized column names (unless `--keep-names` is specified)
- Error report if any invalid rows are found (saved as `{output_name}_reject_errors.csv` in the same directory)
- Shows success table with statistics (rows, columns, file sizes)
- Row endings are kept: CRLF input gives CRLF rows (newlines inside quoted cells stay as they are). Non-UTF-8 files keep their CR and CRLF too, also inside quoted cells, with the same output on every operating system
- The output is written to a hidden `.{output_name}.csvnorm-partial` file next to it and renamed at the end, so an error never leaves a partial output and never touches an existing one
- If the disk fills up, csvnorm stops with `No space left on device` and exit code 2; it warns before starting when free space looks too small
- Supports absolute and relative paths
- Any file extension is allowed (not limited to `.csv`)

**Input file protection:**
- csvnorm will **never** overwrite the input file, even with `--force`
- If you try to use the same path for input and output, you'll get an error
- Use `-o` to specify a different output path

**Remote URLs:**
- Always downloaded to a temporary file first (30 s network timeout), then processed like a local file: encoding detection or `-e`, `.zip` and `.gz` handling, `--fix-mojibake`

**Encoding detection limits:**
- Non-UTF-8 encodings are detected automatically with charset-normalizer, which can confuse single-byte encodings that share most characters (for example cp1252 with cp1250 or cp1258, or cp850 with cp1250). When scores tie, csvnorm prefers Western European encodings (cp1252).
- Files larger than 50 MiB are not analysed as a whole: csvnorm checks for valid UTF-8 in one pass and, for other files, lets charset-normalizer examine a small sample that contains every non-ASCII byte value of the file, preferring Western European encodings. This takes seconds instead of minutes, but on such large files Turkish, Polish, Baltic or Hungarian text can be detected as Western European without any error. Files up to 50 MiB are detected as in previous versions.
- Check accented and typographic characters (`à`, `ì`, `“ ”`, `€`) in the output of non-UTF-8 files. If they are wrong, declare the encoding with `-e` (see below).

**Declaring the input encoding (`-e, --encoding NAME`):**
- When you know the encoding of the file, `-e` skips detection and converts from that encoding. Use it when detection gets it wrong (for example `“Libro”` coming out as `ôLibroö`, or Turkish and Polish text in files above 50 MiB), or to save the detection time on large files.
- Any Python codec name works: `cp1252`, `latin-1`, `cp850`, `cp1250`, `utf-8`. An unknown name stops csvnorm with exit code 2 before the file is read.
- There is no fallback: if a byte cannot be decoded with the declared encoding, csvnorm stops with exit code 2 and reports the byte and its position in the file. With `-e utf-8` the file is only checked, not converted.
- Works with local files, stdin, URLs, `.zip` and `.gz` inputs, and with `--check`. A `.gz` input is decompressed to a temporary file first, since DuckDB would read it as UTF-8.

**Mojibake repair (`--fix-mojibake [N]`):**
- Mojibake is garbled text produced by decoding bytes with the wrong character encoding (e.g., `CittÃ ` instead of `Città`).
- Enables optional mojibake repair using ftfy (for already-misdecoded text).
- `N` is the sample size (number of characters) used by the detector; default is 5000.
- The repair runs only when ftfy's badness heuristic flags the sample as "bad."
- Use `N=0` to force repair without detection (useful for files with low badness scores but visible mojibake).
- **Note**: ftfy cannot recover bytes that were irreversibly lost in the original encoding. Replacement characters (`�`) may remain where data was corrupted beyond repair.
- HTTP timeout is set to 30 seconds
- Only public URLs are supported (no authentication)

The tool provides modern terminal output (shown only when using `-o` to write to a file) with:
- Progress indicators for multi-step processing
- Color-coded error messages with panels
- Success summary table with statistics (rows, columns, file sizes)
- Encoding conversion status (converted/no conversion/remote; ASCII is already UTF-8 compatible)
- Error summary panel with reject count and error types when validation fails
- ASCII art banner with `--version` and `-V` verbose mode

**Success Example:** (shown only when using `-o`)
```
 ✓ Success
 Input:        test/utf8_basic.csv
 Output:       output/utf8_basic.csv
 Encoding:     ascii (ASCII is UTF-8 compatible; no conversion needed)
 Rows:         2
 Columns:      3
 Input size:   42 B
 Output size:  43 B
 Headers:      normalized to snake_case
```

**Error Example:** (shown only when using `-o`)
```
 ✓ Success
 Input:        test/malformed_rows.csv
 Output:       output/malformed_rows.csv
 Encoding:     ascii (ASCII is UTF-8 compatible; no conversion needed)
 Rows:         1
 Columns:      4
 Input size:   24 B
 Output size:  40 B
 Headers:      normalized to snake_case

╭──────────────────────────── ! Validation Failed ─────────────────────────────╮
│ Validation Errors:                                                           │
│                                                                              │
│ Rejected rows: 2                                                             │
│                                                                              │
│ Error types:                                                                 │
│   • Expected Number of Columns: 3 Found: 2                                   │
│   • Expected Number of Columns: 3 Found: 4                                   │
│                                                                              │
│ Details: output/malformed_rows_reject_errors.csv                             │
╰──────────────────────────────────────────────────────────────────────────────╯
```

### Exit Codes

| Code | Meaning |
|------|---------|
| 0 | Clean: every row accepted |
| 1 | Rows rejected (with or without `--strict`; without it the accepted rows are still written) |
| 2 | Could not complete: invalid command line, file not found, download failure, undecodable declared encoding, disk full, unexpected error. No output is written |

Same convention as `grep` and `diff`. Since 1.5.0 fatal errors exit with 2; before they exited with 1, like rejected rows.

When stderr is not a terminal (pipes, files, agents), errors and the validation report are plain lines starting with `Error:`, `Warning:` or `! Validation Failed`, without boxes or colors.

## Requirements

- Python 3.11+
- Dependencies (automatically installed):
  - `charset-normalizer>=3.0.0` - Encoding detection
  - `duckdb>=2.0.0,<3` - CSV validation and normalization
  - `ftfy>=6.3.1` - Mojibake repair
  - `rich>=13.0.0` - Modern terminal output formatting
  - `rich-argparse>=1.0.0` - Enhanced CLI help formatting

Optional extras:
- `[dev]` - Development dependencies (`pytest>=7.0.0`, `pytest-cov>=4.0.0`, `ruff>=0.1.0`)

## Development

### Setup

```bash
git clone https://github.com/aborruso/csvnorm
cd csvnorm

# Create and activate venv with uv (recommended)
uv venv
source .venv/bin/activate
uv pip install -e ".[dev]"

# Or with pip
pip install -e ".[dev]"
```

### Testing

```bash
pytest tests/ -v
```

### Project Structure

```
csvnorm/
├── src/csvnorm/
│   ├── __init__.py      # Package version
│   ├── __main__.py      # python -m support
│   ├── cli.py           # CLI argument parsing
│   ├── core.py          # Main processing pipeline
│   ├── encoding.py      # Encoding detection/conversion
│   ├── validation.py    # DuckDB validation
│   └── utils.py         # Helper functions
├── tests/               # Test suite
├── test/                # CSV fixtures
└── pyproject.toml       # Package configuration
```

## Stay Updated

### Get notified of new releases
**Watch → Custom → ✓ Releases** to receive notifications for all new versions.

### Get notified of breaking changes only
**[Subscribe to Announcements](https://github.com/aborruso/csvnorm/discussions/categories/announcements)** to be notified only about:
- Breaking changes (major version bumps)
- Security updates
- Important deprecation notices

We follow [Semantic Versioning](https://semver.org/):
- **MAJOR** (e.g., 1.0.0 → 2.0.0): Breaking changes
- **MINOR** (e.g., 1.0.0 → 1.1.0): New features, backward compatible
- **PATCH** (e.g., 1.0.0 → 1.0.1): Bug fixes only

See [docs/COMMUNICATION.md](docs/COMMUNICATION.md) for details.

## License

MIT License (c) 2026 aborruso@gmail.com - See LICENSE file for details

## Acknowledgments

csvnorm is built on top of excellent open-source libraries:

- [**charset-normalizer**](https://github.com/Ousret/charset_normalizer) - Universal encoding detection
- [**DuckDB**](https://duckdb.org/) - Fast in-process analytical database for CSV processing
- [**ftfy**](https://github.com/rspeer/python-ftfy) - Fixes mojibake and other text encoding issues
- [**Rich**](https://github.com/Textualize/rich) - Beautiful terminal output formatting
- [**rich-argparse**](https://github.com/hamdanal/rich-argparse) - Enhanced CLI help formatting

We are grateful to the creators and maintainers of these libraries, without whom csvnorm would not exist and function.
