Last active
September 30, 2026 10:36
-
-
Save CharlesNepote/b0cfabf0f508338e79b3e537f6cddf51 to your computer and use it in GitHub Desktop.
csv2datasette.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env -S uv run --script | |
| # /// script | |
| # requires-python = ">=3.9" | |
| # dependencies = [ | |
| # "datasette", | |
| # "pyyaml", | |
| # "Unidecode", | |
| # "datasette-copyable", | |
| # "datasette-json-html", | |
| # "datasette-sqlite-regex", | |
| # ] | |
| # /// | |
| """ | |
| csv2datasette (bigdata variant) — explore CSV files directly in Datasette. | |
| CSV files are streamed straight into SQLite in batches instead of being | |
| fully loaded into Python lists first. This keeps peak memory bounded | |
| (roughly one batch of rows, plus one column at a time when computing | |
| --stats) instead of scaling with file size, so files bigger than | |
| available RAM can be ingested. | |
| Usage (with uv installed and the script made executable): | |
| ./c2d_bigdata.py [options] file.csv [file2.csv ...] | |
| Or explicitly: | |
| uv run c2d_bigdata.py [options] file.csv [file2.csv ...] | |
| Falls back to a plain `python3 c2d_bigdata.py ...` too, as long as | |
| `datasette` is already installed in that Python environment. | |
| Each CSV file becomes its own table in a single temporary SQLite | |
| database, opened with Datasette in your browser. The database is | |
| deleted when Datasette is stopped (Ctrl+C). | |
| To run tests (uv reads the dependencies from the PEP 723 block above): | |
| uv run c2d_bigdata.py --self-test | |
| """ | |
| import argparse | |
| import atexit | |
| import csv | |
| import doctest | |
| import re | |
| import shutil | |
| import socket | |
| import sqlite3 | |
| import statistics | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| import unidecode | |
| from collections import Counter | |
| from pathlib import Path | |
| import yaml | |
| SCRIPT_START = time.monotonic() | |
| # --------------------------------------------------------------------------- | |
| # Helpers: name sanitizing | |
| # --------------------------------------------------------------------------- | |
| def sanitize_name(name: str) -> str: | |
| """Turn a filename or column name into a safe SQL identifier. | |
| >>> sanitize_name("2024 sales.csv") | |
| 'col_2024_sales_csv' | |
| >>> sanitize_name("customer-id") | |
| 'customer_id' | |
| >>> sanitize_name("") | |
| 'col' | |
| """ | |
| name = re.sub(r"[.\-\s]+", "_", name) | |
| # Replace accented characters with non-accented equivalents | |
| name = (unidecode.unidecode(name)) | |
| name = re.sub(r"[^0-9A-Za-z_]", "_", name) | |
| if re.match(r"^[0-9]", name): | |
| name = f"col_{name}" | |
| return name or "col" | |
| def table_name_from_path(path: Path) -> str: | |
| """Return a sanitized table name based on a CSV path. | |
| >>> table_name_from_path(Path("monthly sales.csv")) | |
| 'monthly_sales' | |
| >>> table_name_from_path(Path("réceptions & fêtes.csv")) | |
| 'receptions___fetes' | |
| """ | |
| return sanitize_name(path.stem) | |
| # --------------------------------------------------------------------------- | |
| # Helpers: value typing (replaces the SQL REGEXP-based logic) | |
| # --------------------------------------------------------------------------- | |
| _NUMERIC_RE = re.compile(r"^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$") | |
| _LEADING_ZERO_RE = re.compile(r"^[+-]?0[0-9]+") # e.g. "056", "-082" -> treat as code, not number | |
| _ISO_DATE_RE = re.compile( # Compile the regex pattern for matching ISO-formatted dates | |
| r"^" # Start anchor | |
| r"[1-9][0-9]{0,3}" # year: 1-4 digits, starting with 1-9 (no leading zero, allows years 1-9999) | |
| r"(-?(0[13578]|1[02])(-?(0[1-9]|[12][0-9]|3[01]))?" # Case 1: 31-day months (Jan,Mar,May,Jul,Aug,Oct,Dec), optional dash separators, optional day | |
| r"|-?(0[469]|11)-?(0[1-9]|[12][0-9]|30)?" # Case 2: 30-day months (Apr,Jun,Sep,Nov), optional dash separators, optional day | |
| r"|-?02-?(0[1-9]|[12][0-9])?)?" # Case 3: February (month 02), days 01-29, optional day component | |
| r"(" # Start of time component | |
| r"(T| )(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])" # Time separator (T or space) + hours (00-23) + minutes (00-59) | |
| r"(:(0[0-9]|[1-5][0-9])" # Optional seconds | |
| r"(\.[0-9]{1,7})?" # + fractional seconds (1-7 decimals) | |
| r"(Z|[+-][0-2][0-9]:[0-5][0-9])?" # + timezone (Z or offset) | |
| r")?" | |
| r")?" # End of time component | |
| r"$" # End anchor | |
| ) | |
| def is_numeric(value: str) -> bool: | |
| """Return whether *value* is numeric and not a leading-zero code. | |
| >>> is_numeric("-12.5"), is_numeric(".5"), is_numeric("+12"), is_numeric("12.") | |
| (True, True, True, True) | |
| >>> is_numeric("1e3") | |
| True | |
| >>> is_numeric("056"), is_numeric("-082") | |
| (False, False) | |
| >>> is_numeric(""), is_numeric("1,5"), is_numeric("not a number") | |
| (False, False, False) | |
| """ | |
| if not _NUMERIC_RE.match(value): | |
| return False | |
| if _LEADING_ZERO_RE.match(value): | |
| return False | |
| return True | |
| def is_probable_iso_date(value: str) -> bool: | |
| """Return whether *value* resembles the supported ISO date formats. | |
| The check is intentionally approximate; it identifies values for stats | |
| reporting and does not replace full date validation. | |
| >>> is_probable_iso_date("2024-02-29") | |
| True | |
| >>> is_probable_iso_date("2024-02-29T12:30:00Z") | |
| True | |
| >>> is_probable_iso_date("2024-02-29T12:59:00.1234567") | |
| True | |
| >>> is_probable_iso_date("2024-02-29T12:30:00+02:30") | |
| True | |
| >>> is_probable_iso_date("30") | |
| False | |
| >>> is_probable_iso_date("2024-02-29T12:60:00") | |
| False | |
| >>> is_probable_iso_date("2024-13-01"), is_probable_iso_date("2024-01-01T24:00") | |
| (False, False) | |
| """ | |
| if not _ISO_DATE_RE.match(value): | |
| return False | |
| # avoid false positives on bare short numbers (e.g. "30", "25") | |
| # by requiring either a 4-digit year or an actual date/time separator. | |
| return bool(re.match(r"^\d{4}", value)) or bool(re.search(r"[-T:]", value)) | |
| def apply_decimal_separator(value: str, decimal_sep: str) -> str: | |
| """Convert a configured decimal separator to SQLite's ``.`` format. | |
| >>> apply_decimal_separator("12,50", ",") | |
| '12.50' | |
| >>> apply_decimal_separator("12.50", ",") | |
| '12.50' | |
| >>> apply_decimal_separator("12,50", None) | |
| '12,50' | |
| """ | |
| if decimal_sep and decimal_sep in value: | |
| return value.replace(decimal_sep, ".") | |
| return value | |
| # --------------------------------------------------------------------------- | |
| # CSV reading: streamed straight into SQLite (no full-file list in memory) | |
| # --------------------------------------------------------------------------- | |
| INSERT_BATCH_SIZE = 10_000 | |
| def _dedupe_headers(headers): | |
| seen = {} | |
| unique_headers = [] | |
| for h in headers: | |
| if h in seen: | |
| seen[h] += 1 | |
| h = f"{h}_{seen[h]}" | |
| else: | |
| seen[h] = 0 | |
| unique_headers.append(h) | |
| return unique_headers | |
| def stream_csv_to_table(conn, table: str, path: Path, separator: str, | |
| generate_columns: bool, decimal_sep: str, | |
| batch_size: int = INSERT_BATCH_SIZE): | |
| """Create *table* in *conn* and stream *path*'s rows into it in batches. | |
| Never holds more than one batch of rows in memory (plus, for | |
| --generate-column-names, a single running max() while pre-scanning | |
| column counts), so CSV files bigger than available RAM can be ingested. | |
| Returns the list of sanitized column names, or [] if the file is empty. | |
| >>> import sqlite3 | |
| >>> conn = sqlite3.connect(":memory:") | |
| >>> with tempfile.TemporaryDirectory() as directory: | |
| ... path = Path(directory) / "data.csv" | |
| ... _ = path.write_text("\\ufeffName,Name\\nAlice\\nBob,too,many", encoding="utf-8") | |
| ... stream_csv_to_table(conn, "t", path, ",", False, None, batch_size=1) | |
| ['Name', 'Name_1'] | |
| >>> conn.execute('SELECT * FROM t ORDER BY "Name"').fetchall() | |
| [('Alice', ''), ('Bob', 'too')] | |
| >>> conn2 = sqlite3.connect(":memory:") | |
| >>> with tempfile.TemporaryDirectory() as directory: | |
| ... path = Path(directory) / "data.csv" | |
| ... _ = path.write_text("Alice,1\\nBob,2", encoding="utf-8") | |
| ... stream_csv_to_table(conn2, "t", path, ",", True, None) | |
| ['col_1', 'col_2'] | |
| >>> conn3 = sqlite3.connect(":memory:") | |
| >>> with tempfile.TemporaryDirectory() as directory: | |
| ... path = Path(directory) / "empty.csv" | |
| ... _ = path.write_text("", encoding="utf-8") | |
| ... stream_csv_to_table(conn3, "t", path, ",", False, None) | |
| [] | |
| """ | |
| # CSV field size limit is 128 KB by default; increase this limit with a hardcoded value | |
| csv.field_size_limit(10*1000*1000) # 10 MB limit | |
| if generate_columns: | |
| # Pre-scan once to find the widest row, without keeping any row around. | |
| n_cols = 0 | |
| with path.open(newline="", encoding="utf-8-sig", errors="replace") as f: | |
| for row in csv.reader(f, delimiter=separator): | |
| n_cols = max(n_cols, len(row)) | |
| if n_cols == 0: | |
| return [] | |
| headers = [f"col_{i+1}" for i in range(n_cols)] | |
| skip_first_row = False | |
| else: | |
| with path.open(newline="", encoding="utf-8-sig", errors="replace") as f: | |
| first_row = next(csv.reader(f, delimiter=separator), None) | |
| if first_row is None: | |
| return [] | |
| headers = [sanitize_name(h) or f"col_{i+1}" for i, h in enumerate(first_row)] | |
| skip_first_row = True | |
| headers = _dedupe_headers(headers) | |
| n = len(headers) | |
| col_defs = ", ".join(f'"{h}" TEXT' for h in headers) | |
| conn.execute(f'CREATE TABLE "{table}" ({col_defs});') | |
| insert_sql = f'INSERT INTO "{table}" VALUES ({", ".join("?" for _ in headers)});' | |
| with path.open(newline="", encoding="utf-8-sig", errors="replace") as f: | |
| reader = csv.reader(f, delimiter=separator) | |
| if skip_first_row: | |
| next(reader, None) | |
| batch = [] | |
| for row in reader: | |
| if len(row) < n: | |
| row = row + [""] * (n - len(row)) | |
| elif len(row) > n: | |
| row = row[:n] | |
| if decimal_sep: | |
| row = [apply_decimal_separator(v, decimal_sep) for v in row] | |
| batch.append(row) | |
| if len(batch) >= batch_size: | |
| conn.executemany(insert_sql, batch) | |
| batch = [] | |
| if batch: | |
| conn.executemany(insert_sql, batch) | |
| conn.commit() | |
| return headers | |
| # --------------------------------------------------------------------------- | |
| # Stats computation (replaces the SQL-based --stats block) | |
| # --------------------------------------------------------------------------- | |
| def percentile(sorted_values, p): | |
| """Return the value at percentage *p* using the existing nearest-rank rule. | |
| >>> percentile([], 50) is None | |
| True | |
| >>> percentile([10, 20, 30, 40], 50) | |
| 30 | |
| >>> percentile([10, 20, 30, 40], 100) | |
| 40 | |
| >>> percentile([42], 10), percentile([42], 90) | |
| (42, 42) | |
| """ | |
| if not sorted_values: | |
| return None | |
| idx = int(len(sorted_values) * p / 100) | |
| idx = min(idx, len(sorted_values) - 1) | |
| return sorted_values[idx] | |
| def confidence_pct(matching: int, total: int) -> float: | |
| """Percentage of *matching* values out of *total*, rounded to 3 decimals. | |
| Never rounds up to 100 unless *matching* == *total*, so a column that's | |
| not fully consistent with its inferred type never displays as "100%". | |
| >>> confidence_pct(3, 3) | |
| 100.0 | |
| >>> confidence_pct(0, 0), confidence_pct(1, 3) | |
| (0.0, 33.333) | |
| >>> confidence_pct(999999, 1000000) | |
| 99.999 | |
| """ | |
| if total == 0: | |
| return 0.0 | |
| if matching == total: | |
| return 100.0 | |
| pct = round(matching / total * 100, 3) | |
| return min(pct, 99.999) | |
| def compute_column_stats(col_name: str, values, decimal_sep: str): | |
| """Compute the summary row used by the optional stats table. | |
| Values are kept as strings for display, while numeric summaries use the | |
| configured decimal separator. | |
| >>> stats = compute_column_stats("amount", ["1,5", "", "2,5", "1,5"], ",") | |
| >>> (stats["filled"], stats["missing"], stats["fill_rate"]) | |
| (3, 1, 75.0) | |
| >>> (stats["uniq"], stats["dupes"]) | |
| (2, 1) | |
| >>> (stats["inf_type"], stats["pct_ok"], stats["min"], stats["max"], stats["sum"]) | |
| ('numeric', 100.0, 1.5, 2.5, 5.5) | |
| >>> (stats["avg"], stats["med"], stats["stddev"]) | |
| (1.83333, 1.5, 0.4714) | |
| >>> stats["percentiles_10_25_50_75_90"] | |
| '1.5, 1.5, 1.5, 2.5, 2.5' | |
| >>> stats["top_3_freq"] | |
| '1,5 (2)\\n2,5 (1)' | |
| Date columns are identified when more than 90% of their values look like dates: | |
| >>> dates = compute_column_stats("created", ["2024-01-01", "2024-02-29"], None) | |
| >>> (dates["inf_type"], dates["pct_ok"], dates["probISODate"]) | |
| ('date', 100.0, 2) | |
| Text columns retain lexical bounds and report their text confidence: | |
| >>> text = compute_column_stats("name", ["Alice", "Bob", "Alice"], None) | |
| >>> (text["inf_type"], text["pct_ok"], text["min"], text["max"]) | |
| ('text', 100.0, 'Alice', 'Bob') | |
| A single numeric value has zero population standard deviation: | |
| >>> single = compute_column_stats("count", ["7"], None) | |
| >>> (single["inf_type"], single["avg"], single["stddev"], single["sum"]) | |
| ('numeric', 7.0, 0.0, 7.0) | |
| Mixed values fall back to text with confidence below 100%: | |
| >>> mixed = compute_column_stats("value", ["1", "unknown"], None) | |
| >>> (mixed["inf_type"], mixed["pct_ok"]) | |
| ('text', 50.0) | |
| Only the three most frequent values are included: | |
| >>> frequent = compute_column_stats("status", ["a", "a", "b", "c", "d"], None) | |
| >>> frequent["top_3_freq"] | |
| 'a (2)\\nb (1)\\nc (1)' | |
| A column with no filled values gets a placeholder "empty" row: | |
| >>> empty = compute_column_stats("notes", ["", ""], None) | |
| >>> (empty["inf_type"], empty["filled"], empty["missing"]) | |
| ('empty', 0, 2) | |
| """ | |
| n_total = len(values) | |
| filled = [v for v in values if v != ""] | |
| missing = n_total - len(filled) | |
| uniq = len(set(filled)) | |
| fill_rate = round(len(filled) / n_total * 100, 1) if n_total else 0.0 | |
| row = { | |
| "column_name": col_name, | |
| "inf_type": "empty", | |
| "pct_ok": None, | |
| "filled": len(filled), | |
| "missing": missing, | |
| "fill_rate": fill_rate, | |
| "uniq": uniq, | |
| "dupes": len(filled) - uniq, | |
| "min": None, "max": None, | |
| "avg": None, "med": None, "stddev": None, "sum": None, | |
| "percentiles_10_25_50_75_90": None, | |
| "shortestStr": None, "longestStr": None, | |
| "probISODate": 0, | |
| "top_3_freq": None, | |
| } | |
| # If all values are missing, return early with the row containing only metadata. | |
| if not filled: | |
| return row | |
| normed = [apply_decimal_separator(v, decimal_sep) for v in filled] | |
| numeric_flags = [is_numeric(v) for v in normed] | |
| n_numeric = sum(numeric_flags) | |
| n_text = len(filled) - n_numeric | |
| row["probISODate"] = sum(1 for v in filled if is_probable_iso_date(v)) | |
| row["shortestStr"] = min(len(v) for v in filled) | |
| row["longestStr"] = max(len(v) for v in filled) | |
| top3 = Counter(filled).most_common(3) | |
| row["top_3_freq"] = "\n".join(f"{val} ({cnt})" for val, cnt in top3) | |
| text_ratio = n_text / len(filled) * 100 | |
| is_text_col = text_ratio > 90 | |
| date_ratio = row["probISODate"] / len(filled) * 100 | |
| if is_text_col: | |
| row["inf_type"] = "date" if date_ratio > 90 else "text" | |
| row["pct_ok"] = confidence_pct( | |
| row["probISODate"] if row["inf_type"] == "date" else n_text, len(filled) | |
| ) | |
| row["min"] = min(filled) | |
| row["max"] = max(filled) | |
| else: | |
| try: | |
| nums = sorted(float(v) for v in normed) | |
| row["inf_type"] = "numeric" | |
| row["pct_ok"] = confidence_pct(n_numeric, len(filled)) | |
| row["min"] = nums[0] | |
| row["max"] = nums[-1] | |
| row["med"] = round(statistics.median(nums), 5) | |
| row["stddev"] = round(statistics.pstdev(nums), 5) if len(nums) > 1 else 0.0 | |
| pcts = [percentile(nums, p) for p in (10, 25, 50, 75, 90)] | |
| row["percentiles_10_25_50_75_90"] = ", ".join(str(p) for p in pcts) | |
| row["avg"] = round(sum(nums) / len(nums), 5) | |
| row["sum"] = round(sum(nums), 5) | |
| except ValueError: | |
| row["inf_type"] = "text" | |
| row["pct_ok"] = confidence_pct(n_text, len(filled)) | |
| row["min"] = min(filled) | |
| row["max"] = max(filled) | |
| return row | |
| # --------------------------------------------------------------------------- | |
| # Datasette plumbing | |
| # --------------------------------------------------------------------------- | |
| STATS_COLUMNS_ORDER = [ | |
| "column_name", "inf_type", "pct_ok", | |
| "filled", "missing", "fill_rate", "uniq", "dupes", | |
| "top_3_freq", | |
| "min", "max", | |
| "avg", "med", "stddev", "sum", "percentiles_10_25_50_75_90", | |
| "shortestStr", "longestStr", | |
| "probISODate", | |
| ] | |
| STATS_COLUMNS_HELP = """ | |
| <li><code>column_name</code>: the name of the column</li> | |
| <li><code>inf_type</code>: inferred type: numeric / date / text, based on the column's content</li> | |
| <li><code>pct_ok</code>: percentage of filled values that actually match the <code>inf_type</code></li> | |
| <li><code>filled</code>: the number of filled rows</li> | |
| <li><code>missing</code>: the number of missing (empty) values</li> | |
| <li><code>fill_rate</code>: percentage of rows filled</li> | |
| <li><code>uniq</code>: the number of unique values</li> | |
| <li><code>dupes</code> (duplicates): filled - uniq</li> | |
| <li><code>min</code>: the lowest value</li> | |
| <li><code>max</code>: the highest value</li> | |
| <li><code>avg</code>: the mean (numeric columns only)</li> | |
| <li><code>med</code>: the median (numeric columns only)</li> | |
| <li><code>stddev</code>: the population standard deviation (numeric columns only)</li> | |
| <li><code>sum</code>: the sum (numeric columns only)</li> | |
| <li><code>percentiles_10_25_50_75_90</code>: the 10th/25th/50th/75th/90th percentiles</li> | |
| <li><code>shortestStr</code> / <code>longestStr</code>: shortest / longest string length</li> | |
| <li><code>probISODate</code>: number of values that look like ISO dates</li> | |
| <li><code>top_3_freq</code>: the 3 most frequent values</li> | |
| """.strip() | |
| def get_free_port() -> int: | |
| s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| s.bind(("", 0)) | |
| port = s.getsockname()[1] | |
| s.close() | |
| return port | |
| def get_datasette_major_version() -> str: | |
| try: | |
| out = subprocess.run( | |
| [sys.executable, "-m", "datasette", "--version"], | |
| capture_output=True, text=True, check=True, | |
| ).stdout | |
| except Exception: | |
| print("Datasette is not installed or not reachable. " | |
| "See https://datasette.io/", file=sys.stderr) | |
| sys.exit(1) | |
| if re.search(r"\b0\.", out): | |
| return "0" | |
| if re.search(r"\b1\.0", out): | |
| return "1" | |
| print(f"Unsupported Datasette version: {out.strip()}", file=sys.stderr) | |
| sys.exit(1) | |
| def write_static_assets(static_dir: Path): | |
| static_dir.mkdir(parents=True, exist_ok=True) | |
| js = r""" | |
| window.addEventListener('load', function () { | |
| let classes = ["col-filled", "col-missing", "col-numericValues", "col-textValues", "col-probISODate"]; | |
| for (const c of classes) { | |
| let x = document.getElementsByClassName(c); | |
| for (let i = 0; i < x.length; i++) { | |
| if (x[i].innerText == 0) { x[i].classList.add('zero'); } | |
| } | |
| } | |
| enhanceStatsCells(); | |
| }); | |
| function configureScrolling() { | |
| const scrolling = document.querySelector('.table-wrapper'); | |
| const thead = document.querySelector('.rows-and-columns thead'); | |
| if (!scrolling || !thead) return; | |
| const translate = () => { | |
| const scroll = window.scrollY; | |
| const headerTop = scrolling.offsetTop; | |
| if (scroll > headerTop) { | |
| thead.style.setProperty('transform', `translateY(${Math.floor(Math.abs(scroll - headerTop))}px)`); | |
| } else { | |
| thead.style.removeProperty('transform'); | |
| } | |
| }; | |
| document.addEventListener('scroll', translate); | |
| } | |
| addEventListener('DOMContentLoaded', configureScrolling); | |
| /* --- Visual enhancements for the stats_* tables --- */ | |
| /* No-op on regular data tables: the col-fill_rate / col-inf_type / | |
| col-top_3_freq classes only exist on stats tables, so all the | |
| querySelectorAll calls below simply return nothing there. */ | |
| function enhanceStatsCells() { | |
| /* fill_rate: colored bar, red (low) -> green (high) */ | |
| document.querySelectorAll('td.col-fill_rate').forEach(function (cell) { | |
| var pct = parseFloat(cell.textContent); | |
| if (isNaN(pct)) return; | |
| var hue = Math.max(0, Math.min(120, pct * 1.2)); | |
| cell.style.background = 'linear-gradient(90deg, hsla(' + hue + ',65%,45%,0.35) ' + pct + '%, transparent ' + pct + '%)'; | |
| cell.classList.add('bar-cell'); | |
| }); | |
| /* dupes: neutral bar showing duplicates / filled */ | |
| document.querySelectorAll('td.col-dupes').forEach(function (cell) { | |
| var row = cell.closest('tr'); | |
| var filledCell = row ? row.querySelector('td.col-filled') : null; | |
| var dup = parseFloat(cell.textContent); | |
| var filled = filledCell ? parseFloat(filledCell.textContent) : NaN; | |
| if (isNaN(dup) || isNaN(filled) || filled === 0) return; | |
| var pct = (dup / filled) * 100; | |
| cell.style.background = 'linear-gradient(90deg, hsla(210,60%,50%,0.30) ' + pct + '%, transparent ' + pct + '%)'; | |
| cell.classList.add('bar-cell'); | |
| cell.title = pct.toFixed(1) + '% of filled values are duplicates'; | |
| }); | |
| /* inf_type: small colored badge instead of plain text */ | |
| document.querySelectorAll('td.col-inf_type').forEach(function (cell) { | |
| if (cell.querySelector('.type-badge')) return; | |
| var val = cell.textContent.trim(); | |
| if (!val) return; | |
| cell.textContent = ''; | |
| var span = document.createElement('span'); | |
| span.className = 'type-badge type-' + val; | |
| span.textContent = val; | |
| cell.appendChild(span); | |
| }); | |
| /* top_3_freq: mini horizontal bar chart, each bar sized relative to "filled" */ | |
| document.querySelectorAll('td.col-top_3_freq').forEach(function (cell) { | |
| if (cell.querySelector('.freq-bars')) return; | |
| var row = cell.closest('tr'); | |
| var filledCell = row ? row.querySelector('td.col-filled') : null; | |
| var total = filledCell ? parseFloat(filledCell.textContent) : NaN; | |
| var raw = cell.textContent.trim(); | |
| if (!raw) return; | |
| var lines = raw.split('\n').map(function (l) { return l.trim(); }).filter(Boolean); | |
| var container = document.createElement('div'); | |
| container.className = 'freq-bars'; | |
| var addedAny = false; | |
| lines.forEach(function (line) { | |
| var m = line.match(/^(.*) \((\d+)\)$/); | |
| if (!m) return; | |
| var label = m[1]; | |
| var count = parseInt(m[2], 10); | |
| var pct = (!isNaN(total) && total > 0) ? (count / total * 100) : 0; | |
| addedAny = true; | |
| var barRow = document.createElement('div'); | |
| barRow.className = 'freq-bar-row'; | |
| var track = document.createElement('div'); | |
| track.className = 'freq-bar-track'; | |
| var fill = document.createElement('div'); | |
| fill.className = 'freq-bar-fill'; | |
| fill.style.width = Math.max(pct, 2) + '%'; | |
| track.appendChild(fill); | |
| var labelSpan = document.createElement('span'); | |
| labelSpan.className = 'freq-bar-label'; | |
| labelSpan.textContent = label + ' (' + count + (total > 0 ? ', ' + pct.toFixed(0) + '%' : '') + ')'; | |
| barRow.appendChild(track); | |
| barRow.appendChild(labelSpan); | |
| container.appendChild(barRow); | |
| }); | |
| if (addedAny) { | |
| cell.textContent = ''; | |
| cell.appendChild(container); | |
| } | |
| }); | |
| } | |
| """.strip() | |
| css = """ | |
| /* Display `0` values in a lighter color */ | |
| .zero { color: RGBA(0,0,0,.2) !important; } | |
| /* Table styling */ | |
| .rows-and-columns { border-collapse: separate; } | |
| .rows-and-columns thead { background-color: white; position: sticky; top: 0; } | |
| .rows-and-columns thead th { border-bottom: 1px solid #aaa; } | |
| /* Stats table visual enhancements */ | |
| td.bar-cell { background-repeat: no-repeat; } | |
| .type-badge { | |
| display: inline-block; | |
| padding: 1px 9px; | |
| border-radius: 10px; | |
| font-size: 0.82em; | |
| font-weight: 600; | |
| color: white; | |
| white-space: nowrap; | |
| } | |
| .type-numeric { background-color: #2b6cb0; } | |
| .type-date { background-color: #6b46c1; } | |
| .type-text { background-color: #718096; } | |
| .type-empty { background-color: #cbd5e0; color: #333; } | |
| /* Top 3 frequency column styling */ | |
| .col-top_3_freq { max-width: 40rem; white-space: normal; } | |
| .freq-bars { display: flex; flex-direction: column; gap: 3px; min-width: 15rem; } | |
| .freq-bar-row { display: flex; align-items: center; gap: 6px; } | |
| .freq-bar-track { | |
| flex: 0 0 5.25rem; | |
| height: 8px; | |
| background: #eee; | |
| border-radius: 4px; | |
| overflow: hidden; | |
| } | |
| .freq-bar-fill { height: 100%; background: #4299e1; border-radius: 4px; } | |
| .freq-bar-label { font-size: 0.82em; white-space: normal; } | |
| """.strip() | |
| (static_dir / "datasette2csv.js").write_text(js, encoding="utf-8") | |
| (static_dir / "datasette2csv.css").write_text(css, encoding="utf-8") | |
| def write_metadata(tempdir: Path, table_names, with_stats: bool, datasette_major: str): | |
| tables = {} | |
| for t in table_names: | |
| if with_stats: | |
| tables[t] = { | |
| "description_html": f'<p>See <a href="./{t}_stats">stats</a> for this table.</p>' | |
| } | |
| tables[f"{t}_stats"] = { | |
| "description_html": ( | |
| f'<p>Stats about the <a href="./{t}">{t}</a> table:</p>' | |
| f'<ul style="list-style: inside;">{STATS_COLUMNS_HELP}</ul>' | |
| ) | |
| } | |
| # If there's nothing to say about a table, omit it entirely rather | |
| # than emitting an empty YAML mapping (Datasette chokes on `table: ` | |
| # with no value, since it comes back as None instead of a dict). | |
| metadata = {"databases": {"db": {"tables": tables}}} if tables else {} | |
| extra = { | |
| "extra_css_urls": ["/static/datasette2csv.css"], | |
| "extra_js_urls": ["/static/datasette2csv.js"], | |
| } | |
| metadata_path = tempdir / "metadata.yml" | |
| if datasette_major == "1": | |
| metadata_path.write_text( | |
| yaml.safe_dump(metadata, allow_unicode=True, sort_keys=False) if metadata else "", | |
| encoding="utf-8", | |
| ) | |
| (tempdir / "datasette.yml").write_text( | |
| yaml.safe_dump(extra, allow_unicode=True, sort_keys=False), encoding="utf-8" | |
| ) | |
| else: | |
| metadata.update(extra) | |
| metadata_path.write_text( | |
| yaml.safe_dump(metadata, allow_unicode=True, sort_keys=False), encoding="utf-8" | |
| ) | |
| return metadata_path | |
| ABOUT_PAGE_CSS = """ | |
| .about-content code { background: #f0f0f0; padding: 0.1em 0.3em; border-radius: 3px; } | |
| .about-content pre code { display: block; padding: 0.75em 1em; overflow-x: auto; } | |
| """.strip() | |
| ABOUT_PAGE_HTML = """ | |
| {% extends "base.html" %} | |
| {% block title %}About csv2datasette{% endblock %} | |
| {% block content %} | |
| <style>""" + ABOUT_PAGE_CSS + """</style> | |
| <div class="about-content"> | |
| <h1>About csv2datasette</h1> | |
| <p>csv2datasette streams CSV file(s) into a temporary SQLite database and opens them | |
| in <a href="https://datasette.io/">Datasette</a> so you can explore the data in your | |
| browser. Each CSV becomes its own table; the database is deleted once Datasette is | |
| stopped.</p> | |
| <h2>Explore data with the UI</h2> | |
| <p>Every table page lets you sort and filter without writing SQL:</p> | |
| <ul> | |
| <li><strong>Sort:</strong> click a column header to sort ascending, click again to | |
| sort descending.</li> | |
| <li><strong>Facet:</strong> use "Suggested facets" at the top of a table, or add | |
| <code>?_facet=column_name</code> to the URL, to see the most common values in a | |
| column and filter by clicking one of them.</li> | |
| <li><strong>Filter:</strong> use the filter form above the table (e.g. "column is | |
| blank", "column contains ...") to narrow down rows.</li> | |
| </ul> | |
| <p>See the <a href="https://docs.datasette.io/en/stable/facets.html">Datasette facets | |
| documentation</a> for more.</p> | |
| <h2>Explore data with SQL</h2> | |
| <p>Click "Execute SQL" (or open <code>/db</code>) to run arbitrary <code>SELECT</code> | |
| queries against the tables. This is the fastest way to filter, join, or aggregate | |
| data beyond what the UI filters allow. See the | |
| <a href="https://docs.datasette.io/en/stable/sql_queries.html">Datasette SQL queries | |
| documentation</a>.</p> | |
| <h2>The stats table</h2> | |
| <p>Run csv2datasette with <code>--stats</code> to get a <code><table>_stats</code> | |
| table alongside each data table, with one row per column:</p> | |
| <ul>""" + STATS_COLUMNS_HELP + """</ul> | |
| <h2>Regular expressions (regexp)</h2> | |
| <p>Thanks to the <a href="https://github.com/asg017/sqlite-regex">sqlite-regex</a> | |
| extension, SQL queries can use the <code>regexp</code> operator to match values | |
| against a regular expression, for example to find French postal codes:</p> | |
| <pre><code>select * from mytable where column_name regexp '^[0-9]{5}$';</code></pre> | |
| <p>See the <a href="https://github.com/asg017/sqlite-regex#usage">sqlite-regex usage | |
| documentation</a> for the full set of available functions (find, replace, split, | |
| capture groups...).</p> | |
| <h2>Exporting data</h2> | |
| <p>Any table or query result can be exported:</p> | |
| <ul> | |
| <li><strong>CSV:</strong> use the "This data as CSV" link at the bottom of a table | |
| or query page (see the | |
| <a href="https://docs.datasette.io/en/stable/csv_export.html">CSV export | |
| documentation</a>).</li> | |
| <li><strong>Copyable:</strong> thanks to | |
| <a href="https://datasette.io/plugins/datasette-copyable">datasette-copyable</a>, | |
| the "copyable" link lets you copy the current table or query results straight to | |
| your clipboard, ready to paste into a spreadsheet.</li> | |
| </ul> | |
| </div> | |
| {% endblock %} | |
| """.strip() | |
| def write_about_page(tempdir: Path) -> Path: | |
| """Write a custom /about page, served via Datasette's templates/pages/ convention.""" | |
| pages_dir = tempdir / "templates" / "pages" | |
| pages_dir.mkdir(parents=True, exist_ok=True) | |
| (pages_dir / "about.html").write_text(ABOUT_PAGE_HTML, encoding="utf-8") | |
| return tempdir / "templates" | |
| def write_menu_plugin(tempdir: Path) -> Path: | |
| """Write a tiny plugin that adds an "About" link to Datasette's top nav menu.""" | |
| plugins_dir = tempdir / "plugins" | |
| plugins_dir.mkdir(parents=True, exist_ok=True) | |
| (plugins_dir / "menu_links.py").write_text( | |
| 'from datasette import hookimpl\n\n\n' | |
| '@hookimpl\n' | |
| 'def menu_links(datasette, actor, request):\n' | |
| ' return [{"href": "/about", "label": "About"}]\n', | |
| encoding="utf-8", | |
| ) | |
| return plugins_dir | |
| def read_rc_args() -> list: | |
| """Optional ~/.config/csv2datasette/extra_args — one datasette CLI arg per line.""" | |
| rc = Path.home() / ".config" / "csv2datasette" / "extra_args" | |
| if rc.is_file(): | |
| return [line.strip() for line in rc.read_text(encoding="utf-8").splitlines() if line.strip()] | |
| return [] | |
| # --------------------------------------------------------------------------- | |
| # Main | |
| # --------------------------------------------------------------------------- | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| prog="csv2datasette", | |
| description="Explore CSV file(s) directly in Datasette.", | |
| ) | |
| parser.add_argument("files", nargs="*", type=Path, help="CSV file(s) to explore") | |
| parser.add_argument("-e", "--generate-column-names", action="store_true", | |
| help="Auto-generate column names (col_1, col_2, ...) if the CSV has none") | |
| parser.add_argument("-s", "--separator", default=",", help='Field separator (default: ",")') | |
| parser.add_argument("-t", "--tsv", action="store_true", help="Separator is a tab") | |
| parser.add_argument("-d", "--decimal-separator", default=None, | |
| help='Decimal separator used in numbers (e.g. "," for French numbers)') | |
| parser.add_argument("--stats", action="store_true", help="Add WTFCsv-like stats table(s)") | |
| parser.add_argument("--self-test", action="store_true", | |
| help="Run this module's doctests (via uv, using the PEP 723 deps) and exit") | |
| parser.add_argument("-v", "--verbose", action="store_true") | |
| args = parser.parse_args() | |
| # Run doctests if requested, then exit with the appropriate status code. | |
| if args.self_test: | |
| results = doctest.testmod(verbose=args.verbose) | |
| sys.exit(1 if results.failed else 0) | |
| if not args.files: | |
| parser.error("the following arguments are required: files") | |
| def log(msg): | |
| if args.verbose: | |
| print(f"[+{time.monotonic() - SCRIPT_START:.3f}s] {msg}") | |
| separator = "\t" if args.tsv else args.separator | |
| for f in args.files: | |
| if not f.is_file(): | |
| print(f"{f} does not exist.", file=sys.stderr) | |
| sys.exit(1) | |
| datasette_major = get_datasette_major_version() | |
| log(f"Datasette major version: {datasette_major}") | |
| tempdir = Path(tempfile.mkdtemp(prefix="csv2datasette.")) | |
| # Register a cleanup function to remove the temporary directory when the program exits | |
| atexit.register(lambda: shutil.rmtree(tempdir, ignore_errors=True)) | |
| log(f"Temp dir: {tempdir}") | |
| db_path = tempdir / "db.sqlite3" | |
| conn = sqlite3.connect(db_path) | |
| table_names = [] | |
| for f in args.files: | |
| table = table_name_from_path(f) | |
| # avoid collisions between multiple files sharing a sanitized name | |
| base_table, i = table, 1 | |
| while table in table_names: | |
| i += 1 | |
| table = f"{base_table}_{i}" | |
| table_names.append(table) | |
| log(f"Streaming {f} into table [{table}]...") | |
| headers = stream_csv_to_table(conn, table, f, separator, args.generate_column_names, | |
| args.decimal_separator) | |
| if not headers: | |
| print(f"Warning: {f} appears empty, skipping.", file=sys.stderr) | |
| continue | |
| if args.stats: | |
| log(f"Computing stats for table [{table}]...") | |
| # Pull one column at a time from SQLite instead of transposing the | |
| # whole table in Python, so peak memory doesn't scale with the | |
| # number of columns. | |
| stats_rows = [] | |
| for h in headers: | |
| log(f"Computing stats for column [{h}]...") | |
| vals = [row[0] for row in conn.execute(f'SELECT "{h}" FROM "{table}";')] | |
| stats_rows.append(compute_column_stats(h, vals, args.decimal_separator)) | |
| stats_table = f"{table}_stats" | |
| col_types = { | |
| "column_name": "TEXT", "inf_type": "TEXT", "pct_ok": "REAL", | |
| "filled": "INT", "missing": "INT", "fill_rate": "REAL", | |
| "uniq": "INT", "dupes": "INT", | |
| "min": "TEXT", "max": "TEXT", | |
| "avg": "REAL", "med": "REAL", "stddev": "REAL", "sum": "REAL", | |
| "percentiles_10_25_50_75_90": "TEXT", | |
| "shortestStr": "INT", "longestStr": "INT", | |
| "probISODate": "INT", "top_3_freq": "TEXT", | |
| } | |
| col_defs_sql = ", ".join(f'"{c}" {col_types[c]}' for c in STATS_COLUMNS_ORDER) | |
| conn.execute(f'CREATE TABLE "{stats_table}" ({col_defs_sql});') | |
| conn.executemany( | |
| f'INSERT INTO "{stats_table}" VALUES ({", ".join("?" for _ in STATS_COLUMNS_ORDER)});', | |
| [[r[c] for c in STATS_COLUMNS_ORDER] for r in stats_rows], | |
| ) | |
| # Create a dictionnary with { "column1": "column1", [...] } | |
| STATS_COLUMNS_LINKS_DICT = dict(zip(STATS_COLUMNS_ORDER, STATS_COLUMNS_ORDER)) | |
| # For some stats' columns, build links to data | |
| # facet by column name | |
| # /db/table?_facet=frequency#facet-frequency | |
| STATS_COLUMNS_LINKS_DICT["column_name"] = (f""" | |
| json_object("href", "/db/" || "{table}?_facet=" || column_name || "#facet-", | |
| "label", column_name, | |
| "title", "faceted browse by " || column_name | |
| ) as column_name | |
| """) | |
| # missing | |
| STATS_COLUMNS_LINKS_DICT["missing"] = (f""" | |
| json_object("href", "/db/" || "{table}?" || column_name || "__isblank=1", | |
| "label", missing, | |
| "title", column_name || " column: missing data" | |
| ) as missing | |
| """) | |
| # /db/table?_facet=frequency#facet-frequency | |
| STATS_COLUMNS_LINKS_DICT["dupes"] = (f""" | |
| json_object("href", "/db/" || "{table}?_facet=" || column_name || "#facet-" || column_name, | |
| "label", dupes, | |
| "title", column_name || " column: dupes" | |
| ) as dupes | |
| """) | |
| # /db/table?_sort=createdAt | |
| STATS_COLUMNS_LINKS_DICT["min"] = (f""" | |
| json_object("href", "/db/" || "{table}?_sort=" || column_name, | |
| "label", min, | |
| "title", column_name || " column: sort ascending" | |
| ) as min | |
| """) | |
| # /db/table?_sort_desc=createdAt | |
| STATS_COLUMNS_LINKS_DICT["max"] = (f""" | |
| json_object("href", "/db/" || "{table}?_sort_desc=" || column_name, | |
| "label", max, | |
| "title", column_name || " column: sort descending" | |
| ) as max | |
| """) | |
| # Use dictionnary's values to build a view | |
| STATS_COLUMNS_LINKS = ", ".join(STATS_COLUMNS_LINKS_DICT.values()) | |
| # log(f"STATS_COLUMNS_LINKS: {STATS_COLUMNS_LINKS}") | |
| conn.execute(f'CREATE VIEW "{stats_table}_links" AS SELECT {STATS_COLUMNS_LINKS} FROM "{stats_table}";') | |
| conn.commit() | |
| conn.close() | |
| write_static_assets(tempdir / "static") | |
| write_metadata(tempdir, table_names, args.stats, datasette_major) | |
| template_dir = write_about_page(tempdir) | |
| plugins_dir = write_menu_plugin(tempdir) | |
| rc_args = read_rc_args() | |
| port = get_free_port() | |
| cmd = [ | |
| sys.executable, "-m", "datasette", str(db_path), | |
| "-h", "127.0.0.1", "-p", str(port), "--open", | |
| "--setting", "facet_time_limit_ms", "20000", | |
| "--setting", "facet_suggest_time_limit_ms", "10000", | |
| "--setting", "sql_time_limit_ms", "20000", | |
| "--setting", "max_returned_rows", "100000", | |
| "--setting", "truncate_cells_html", "500", | |
| "--metadata", str(tempdir / "metadata.yml"), | |
| "--static", f"static:{tempdir / 'static'}", | |
| "--template-dir", str(template_dir), | |
| "--plugins-dir", str(plugins_dir), | |
| ] | |
| # Datasette 1.x uses a separate datasette.yml for | |
| # extra_js_urls / extra_css_urls, while 0.x uses the metadata.yml for that. | |
| if datasette_major == "1": | |
| cmd += ["--config", str(tempdir / "datasette.yml")] | |
| cmd += rc_args | |
| log(f"Launching: {' '.join(cmd)}") | |
| try: | |
| subprocess.run(cmd) | |
| except KeyboardInterrupt: | |
| pass | |
| # temp dir cleanup happens via atexit | |
| if __name__ == "__main__": | |
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env -S uv run --script | |
| # /// script | |
| # requires-python = ">=3.9" | |
| # dependencies = [ | |
| # "datasette", | |
| # "pyyaml", | |
| # ] | |
| # /// | |
| """ | |
| csv2datasette — explore CSV files directly in Datasette. | |
| Cross-platform reimplementation (pure Python) of the original bash | |
| csv2datasette script. The only system-wide dependency is `uv` | |
| (https://docs.astral.sh/uv/) — it reads the PEP 723 block above and | |
| runs this script in an ephemeral, cached environment with `datasette` | |
| installed, without ever installing anything permanently. No csvkit, | |
| no sed/awk/grep, no external sqlite3 binary (sqlite3 is used via | |
| Python's built-in module), no manual `pip install`. | |
| Usage (with uv installed and the script made executable): | |
| ./csv2datasette.py [options] file.csv [file2.csv ...] | |
| Or explicitly: | |
| uv run csv2datasette.py [options] file.csv [file2.csv ...] | |
| Falls back to a plain `python3 csv2datasette.py ...` too, as long as | |
| `datasette` is already installed in that Python environment. | |
| Each CSV file becomes its own table in a single temporary SQLite | |
| database, opened with Datasette in your browser. The database is | |
| deleted when Datasette is stopped (Ctrl+C). | |
| """ | |
| import argparse | |
| import atexit | |
| import csv | |
| import re | |
| import shutil | |
| import socket | |
| import sqlite3 | |
| import statistics | |
| import subprocess | |
| import sys | |
| import tempfile | |
| from collections import Counter | |
| from pathlib import Path | |
| import yaml | |
| # --------------------------------------------------------------------------- | |
| # Helpers: name sanitizing | |
| # --------------------------------------------------------------------------- | |
| def sanitize_name(name: str) -> str: | |
| """Turn a filename or column name into a safe SQL identifier.""" | |
| name = re.sub(r"[.\-\s]+", "_", name) | |
| name = re.sub(r"[^0-9A-Za-z_]", "_", name) | |
| if re.match(r"^[0-9]", name): | |
| name = f"col_{name}" | |
| return name or "col" | |
| def table_name_from_path(path: Path) -> str: | |
| return sanitize_name(path.stem) | |
| # --------------------------------------------------------------------------- | |
| # Helpers: value typing (replaces the SQL REGEXP-based logic) | |
| # --------------------------------------------------------------------------- | |
| _NUMERIC_RE = re.compile(r"^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$") | |
| _LEADING_ZERO_RE = re.compile(r"^[+-]?0[0-9]+") # e.g. "056", "-082" -> treat as code, not number | |
| _ISO_DATE_RE = re.compile( # Compile the regex pattern for matching ISO-formatted dates | |
| r"^[1-9][0-9]{0,3}" # Start anchor + year: 1-4 digits, starting with 1-9 (no leading zero, allows years 1-9999) | |
| r"(-?(0[13578]|1[02])(-?(0[1-9]|[12][0-9]|3[01]))?" # Case 1: 31-day months (Jan,Mar,May,Jul,Aug,Oct,Dec), optional dash separators, optional day | |
| r"|-?(0[469]|11)-?(0[1-9]|[12][0-9]|30)?" # Case 2: 30-day months (Apr,Jun,Sep,Nov), optional dash separators, optional day | |
| r"|-?02-?(0[1-9]|[12][0-9])?)?" # Case 3: February (month 02), days 01-29, optional day component | |
| r"((T| )(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])" # Time separator (T or space) + hours (00-23) + minutes (00-59) | |
| r"(:(0[0-9]|[1-5][0-9])(\.[0-9]{1,3})?(Z|[+-][0-2][0-9]:[0-5][0-9])?)?)?" # Optional seconds + fractional seconds (1-3 decimals) + timezone (Z or offset) | |
| r"$" # End anchor | |
| ) | |
| def is_numeric(value: str) -> bool: | |
| if not _NUMERIC_RE.match(value): | |
| return False | |
| if _LEADING_ZERO_RE.match(value): | |
| return False | |
| return True | |
| def is_probable_iso_date(value: str) -> bool: | |
| if not _ISO_DATE_RE.match(value): | |
| return False | |
| # avoid false positives on bare short numbers (e.g. "30", "25") | |
| # by requiring either a 4-digit year or an actual date/time separator. | |
| return bool(re.match(r"^\d{4}", value)) or bool(re.search(r"[-T:]", value)) | |
| def apply_decimal_separator(value: str, decimal_sep: str) -> str: | |
| if decimal_sep and decimal_sep in value: | |
| return value.replace(decimal_sep, ".") | |
| return value | |
| # --------------------------------------------------------------------------- | |
| # CSV reading | |
| # --------------------------------------------------------------------------- | |
| def read_csv(path: Path, separator: str, generate_columns: bool): | |
| """Return (headers, rows) as lists of strings.""" | |
| with path.open(newline="", encoding="utf-8-sig", errors="replace") as f: | |
| reader = csv.reader(f, delimiter=separator) | |
| rows = list(reader) | |
| if not rows: | |
| return [], [] | |
| if generate_columns: | |
| n_cols = max(len(r) for r in rows) | |
| headers = [f"col_{i+1}" for i in range(n_cols)] | |
| data_rows = rows | |
| else: | |
| headers = [sanitize_name(h) or f"col_{i+1}" for i, h in enumerate(rows[0])] | |
| data_rows = rows[1:] | |
| # dedupe accidental duplicate column names | |
| seen = {} | |
| unique_headers = [] | |
| for h in headers: | |
| if h in seen: | |
| seen[h] += 1 | |
| h = f"{h}_{seen[h]}" | |
| else: | |
| seen[h] = 0 | |
| unique_headers.append(h) | |
| headers = unique_headers | |
| # pad/truncate rows to header length | |
| n = len(headers) | |
| normalized = [] | |
| for r in data_rows: | |
| if len(r) < n: | |
| r = r + [""] * (n - len(r)) | |
| elif len(r) > n: | |
| r = r[:n] | |
| normalized.append(r) | |
| return headers, normalized | |
| # --------------------------------------------------------------------------- | |
| # Stats computation (replaces the SQL-based --stats block) | |
| # --------------------------------------------------------------------------- | |
| def percentile(sorted_values, p): | |
| if not sorted_values: | |
| return None | |
| idx = int(len(sorted_values) * p / 100) | |
| idx = min(idx, len(sorted_values) - 1) | |
| return sorted_values[idx] | |
| def compute_column_stats(col_name: str, values, decimal_sep: str): | |
| n_total = len(values) | |
| filled = [v for v in values if v != ""] | |
| missing = n_total - len(filled) | |
| uniq = len(set(filled)) | |
| row = { | |
| "column_name": col_name, | |
| "uniq": uniq, | |
| "filled": len(filled), | |
| "missing": missing, | |
| "min": None, "max": None, "med": None, | |
| "cntls_10_25_50_75_90": None, | |
| "avg": None, "sum": None, | |
| "shortestStr": None, "longestStr": None, | |
| "numericValues": 0, "textValues": 0, "probISODate": 0, | |
| "top_3_freq": None, | |
| } | |
| if not filled: | |
| return row | |
| normed = [apply_decimal_separator(v, decimal_sep) for v in filled] | |
| numeric_flags = [is_numeric(v) for v in normed] | |
| n_numeric = sum(numeric_flags) | |
| n_text = len(filled) - n_numeric | |
| row["numericValues"] = n_numeric | |
| row["textValues"] = n_text | |
| row["probISODate"] = sum(1 for v in filled if is_probable_iso_date(v)) | |
| row["shortestStr"] = min(len(v) for v in filled) | |
| row["longestStr"] = max(len(v) for v in filled) | |
| top3 = Counter(filled).most_common(3) | |
| row["top_3_freq"] = "\n".join(f"{val} ({cnt})" for val, cnt in top3) | |
| text_ratio = n_text / len(filled) * 100 | |
| is_text_col = text_ratio > 90 | |
| if is_text_col: | |
| row["min"] = min(filled) | |
| row["max"] = max(filled) | |
| else: | |
| try: | |
| nums = sorted(float(v) for v in normed) | |
| row["min"] = nums[0] | |
| row["max"] = nums[-1] | |
| row["med"] = round(statistics.median(nums), 5) | |
| pcts = [percentile(nums, p) for p in (10, 25, 50, 75, 90)] | |
| row["cntls_10_25_50_75_90"] = ", ".join(str(p) for p in pcts) | |
| row["avg"] = round(sum(nums) / len(nums), 5) | |
| row["sum"] = round(sum(nums), 5) | |
| except ValueError: | |
| row["min"] = min(filled) | |
| row["max"] = max(filled) | |
| return row | |
| # --------------------------------------------------------------------------- | |
| # Datasette plumbing | |
| # --------------------------------------------------------------------------- | |
| STATS_COLUMNS_HELP = """ | |
| <li><code>column_name</code>: the name of the column</li> | |
| <li><code>uniq</code>: the number of unique values</li> | |
| <li><code>filled</code>: the number of filled row</li> | |
| <li><code>missing</code>: the number of missing values</li> | |
| <li><code>min</code>: the lowest value</li> | |
| <li><code>max</code>: the highest value</li> | |
| <li><code>med</code>: the median (numeric columns only)</li> | |
| <li><code>cntls_10_25_50_75_90</code>: the 10th/25th/50th/75th/90th percentiles</li> | |
| <li><code>avg</code>: the mean (numeric columns only)</li> | |
| <li><code>sum</code>: the sum (numeric columns only)</li> | |
| <li><code>shortestStr</code> / <code>longestStr</code>: shortest / longest string length</li> | |
| <li><code>numericValues</code> / <code>textValues</code>: counts by type</li> | |
| <li><code>probISODate</code>: number of values that look like ISO dates</li> | |
| <li><code>top_3_freq</code>: the 3 most frequent values</li> | |
| """.strip() | |
| def get_free_port() -> int: | |
| s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| s.bind(("", 0)) | |
| port = s.getsockname()[1] | |
| s.close() | |
| return port | |
| def get_datasette_major_version() -> str: | |
| try: | |
| out = subprocess.run( | |
| [sys.executable, "-m", "datasette", "--version"], | |
| capture_output=True, text=True, check=True, | |
| ).stdout | |
| except Exception: | |
| print("Datasette is not installed or not reachable. " | |
| "See https://datasette.io/", file=sys.stderr) | |
| sys.exit(1) | |
| if re.search(r"\b0\.", out): | |
| return "0" | |
| if re.search(r"\b1\.0", out): | |
| return "1" | |
| print(f"Unsupported Datasette version: {out.strip()}", file=sys.stderr) | |
| sys.exit(1) | |
| def write_static_assets(static_dir: Path): | |
| static_dir.mkdir(parents=True, exist_ok=True) | |
| js = """ | |
| window.addEventListener('load', function () { | |
| let classes = ["col-filled", "col-missing", "col-numericValues", "col-textValues", "col-probISODate"]; | |
| for (const c of classes) { | |
| let x = document.getElementsByClassName(c); | |
| for (let i = 0; i < x.length; i++) { | |
| if (x[i].innerText == 0) { x[i].classList.add('zero'); } | |
| } | |
| } | |
| }); | |
| function configureScrolling() { | |
| const scrolling = document.querySelector('.table-wrapper'); | |
| const thead = document.querySelector('.rows-and-columns thead'); | |
| if (!scrolling || !thead) return; | |
| const translate = () => { | |
| const scroll = window.scrollY; | |
| const headerTop = scrolling.offsetTop; | |
| if (scroll > headerTop) { | |
| thead.style.setProperty('transform', `translateY(${Math.floor(Math.abs(scroll - headerTop))}px)`); | |
| } else { | |
| thead.style.removeProperty('transform'); | |
| } | |
| }; | |
| document.addEventListener('scroll', translate); | |
| } | |
| addEventListener('DOMContentLoaded', configureScrolling); | |
| """.strip() | |
| css = """ | |
| .zero { color: RGBA(0,0,0,.2) !important; } | |
| .rows-and-columns { border-collapse: separate; } | |
| .rows-and-columns thead { background-color: white; position: sticky; top: 0; } | |
| .rows-and-columns thead th { border-bottom: 1px solid #aaa; } | |
| """.strip() | |
| (static_dir / "datasette2csv.js").write_text(js, encoding="utf-8") | |
| (static_dir / "datasette2csv.css").write_text(css, encoding="utf-8") | |
| def write_metadata(tempdir: Path, table_names, with_stats: bool, datasette_major: str): | |
| tables = {} | |
| for t in table_names: | |
| if with_stats: | |
| tables[t] = { | |
| "description_html": f'<p>See <a href="./stats_{t}">stats</a> for this table.</p>' | |
| } | |
| tables[f"stats_{t}"] = { | |
| "description_html": ( | |
| f'<p>Stats about the <a href="./{t}">{t}</a> table:</p>' | |
| f'<ul style="list-style: inside;">{STATS_COLUMNS_HELP}</ul>' | |
| ) | |
| } | |
| # If there's nothing to say about a table, omit it entirely rather | |
| # than emitting an empty YAML mapping (Datasette chokes on `table: ` | |
| # with no value, since it comes back as None instead of a dict). | |
| metadata = {"databases": {"db": {"tables": tables}}} if tables else {} | |
| extra = { | |
| "extra_css_urls": ["/static/datasette2csv.css"], | |
| "extra_js_urls": ["/static/datasette2csv.js"], | |
| } | |
| metadata_path = tempdir / "metadata.yml" | |
| if datasette_major == "1": | |
| metadata_path.write_text( | |
| yaml.safe_dump(metadata, allow_unicode=True, sort_keys=False) if metadata else "", | |
| encoding="utf-8", | |
| ) | |
| (tempdir / "datasette.yml").write_text( | |
| yaml.safe_dump(extra, allow_unicode=True, sort_keys=False), encoding="utf-8" | |
| ) | |
| else: | |
| metadata.update(extra) | |
| metadata_path.write_text( | |
| yaml.safe_dump(metadata, allow_unicode=True, sort_keys=False), encoding="utf-8" | |
| ) | |
| return metadata_path | |
| def read_rc_args() -> list: | |
| """Optional ~/.config/csv2datasette/extra_args — one datasette CLI arg per line.""" | |
| rc = Path.home() / ".config" / "csv2datasette" / "extra_args" | |
| if rc.is_file(): | |
| return [line.strip() for line in rc.read_text(encoding="utf-8").splitlines() if line.strip()] | |
| return [] | |
| # --------------------------------------------------------------------------- | |
| # Main | |
| # --------------------------------------------------------------------------- | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| prog="csv2datasette", | |
| description="Explore CSV file(s) directly in Datasette.", | |
| ) | |
| parser.add_argument("files", nargs="+", type=Path, help="CSV file(s) to explore") | |
| parser.add_argument("-e", "--generate-column-names", action="store_true", | |
| help="Auto-generate column names (col_1, col_2, ...) if the CSV has none") | |
| parser.add_argument("-s", "--separator", default=",", help='Field separator (default: ",")') | |
| parser.add_argument("-t", "--tsv", action="store_true", help="Separator is a tab") | |
| parser.add_argument("-d", "--decimal-separator", default=None, | |
| help='Decimal separator used in numbers (e.g. "," for French numbers)') | |
| parser.add_argument("--stats", action="store_true", help="Add WTFCsv-like stats table(s)") | |
| parser.add_argument("-v", "--verbose", action="store_true") | |
| args = parser.parse_args() | |
| def log(msg): | |
| if args.verbose: | |
| print(msg) | |
| separator = "\t" if args.tsv else args.separator | |
| for f in args.files: | |
| if not f.is_file(): | |
| print(f"{f} does not exist.", file=sys.stderr) | |
| sys.exit(1) | |
| datasette_major = get_datasette_major_version() | |
| log(f"Datasette major version: {datasette_major}") | |
| tempdir = Path(tempfile.mkdtemp(prefix="csv2datasette.")) | |
| atexit.register(lambda: shutil.rmtree(tempdir, ignore_errors=True)) | |
| log(f"Temp dir: {tempdir}") | |
| db_path = tempdir / "db.sqlite3" | |
| conn = sqlite3.connect(db_path) | |
| table_names = [] | |
| for f in args.files: | |
| table = table_name_from_path(f) | |
| # avoid collisions between multiple files sharing a sanitized name | |
| base_table, i = table, 1 | |
| while table in table_names: | |
| i += 1 | |
| table = f"{base_table}_{i}" | |
| table_names.append(table) | |
| log(f"Reading {f} into table [{table}]...") | |
| headers, rows = read_csv(f, separator, args.generate_column_names) | |
| if not headers: | |
| print(f"Warning: {f} appears empty, skipping.", file=sys.stderr) | |
| continue | |
| col_defs = ", ".join(f'"{h}" TEXT' for h in headers) | |
| conn.execute(f'CREATE TABLE "{table}" ({col_defs});') | |
| placeholders = ", ".join("?" for _ in headers) | |
| conn.executemany( | |
| f'INSERT INTO "{table}" VALUES ({placeholders});', | |
| [[apply_decimal_separator(v, args.decimal_separator) if args.decimal_separator else v | |
| for v in row] for row in rows], | |
| ) | |
| conn.commit() | |
| if args.stats: | |
| log(f"Computing stats for [{table}]...") | |
| columns = [(h, [row[idx] for row in rows]) for idx, h in enumerate(headers)] | |
| stats_rows = [compute_column_stats(h, vals, args.decimal_separator) for h, vals in columns] | |
| stats_table = f"stats_{table}" | |
| conn.execute(f''' | |
| CREATE TABLE "{stats_table}" ( | |
| column_name TEXT, uniq INT, filled INT, missing INT, | |
| min TEXT, max TEXT, med REAL, cntls_10_25_50_75_90 TEXT, | |
| avg REAL, sum REAL, shortestStr INT, longestStr INT, | |
| numericValues INT, textValues INT, probISODate INT, top_3_freq TEXT | |
| ); | |
| ''') | |
| cols_order = ["column_name", "uniq", "filled", "missing", "min", "max", "med", | |
| "cntls_10_25_50_75_90", "avg", "sum", "shortestStr", "longestStr", | |
| "numericValues", "textValues", "probISODate", "top_3_freq"] | |
| conn.executemany( | |
| f'INSERT INTO "{stats_table}" VALUES ({", ".join("?" for _ in cols_order)});', | |
| [[r[c] for c in cols_order] for r in stats_rows], | |
| ) | |
| conn.commit() | |
| conn.close() | |
| write_static_assets(tempdir / "static") | |
| write_metadata(tempdir, table_names, args.stats, datasette_major) | |
| rc_args = read_rc_args() | |
| port = get_free_port() | |
| cmd = [ | |
| sys.executable, "-m", "datasette", str(db_path), | |
| "-h", "127.0.0.1", "-p", str(port), "--open", | |
| "--setting", "facet_time_limit_ms", "20000", | |
| "--setting", "facet_suggest_time_limit_ms", "10000", | |
| "--setting", "sql_time_limit_ms", "20000", | |
| "--setting", "max_returned_rows", "100000", | |
| "--setting", "truncate_cells_html", "500", | |
| "--metadata", str(tempdir / "metadata.yml"), | |
| "--static", f"static:{tempdir / 'static'}", | |
| ] | |
| if datasette_major == "1": | |
| cmd += ["--config", str(tempdir / "datasette.yml")] | |
| cmd += rc_args | |
| log(f"Launching: {' '.join(cmd)}") | |
| try: | |
| subprocess.run(cmd) | |
| except KeyboardInterrupt: | |
| pass | |
| # temp dir cleanup happens via atexit | |
| if __name__ == "__main__": | |
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env -S uv run --script | |
| # /// script | |
| # requires-python = ">=3.9" | |
| # dependencies = [ | |
| # "datasette", | |
| # "pyyaml", | |
| # "Unidecode", | |
| # "datasette-copyable", | |
| # "datasette-json-html", | |
| # ] | |
| # /// | |
| """ | |
| csv2datasette — explore CSV files directly in Datasette. | |
| Cross-platform reimplementation (pure Python) of the original bash | |
| csv2datasette script. The only system-wide dependency is `uv` | |
| (https://docs.astral.sh/uv/) — it reads the PEP 723 block above and | |
| runs this script in an ephemeral, cached environment with `datasette` | |
| installed, without ever installing anything permanently. No csvkit, | |
| no sed/awk/grep, no external sqlite3 binary (sqlite3 is used via | |
| Python's built-in module), no manual `pip install`. | |
| Usage (with uv installed and the script made executable): | |
| ./csv2datasette.py [options] file.csv [file2.csv ...] | |
| Or explicitly: | |
| uv run csv2datasette.py [options] file.csv [file2.csv ...] | |
| Falls back to a plain `python3 csv2datasette.py ...` too, as long as | |
| `datasette` is already installed in that Python environment. | |
| Each CSV file becomes its own table in a single temporary SQLite | |
| database, opened with Datasette in your browser. The database is | |
| deleted when Datasette is stopped (Ctrl+C). | |
| To run tests (uv reads the dependencies from the PEP 723 block above): | |
| uv run c2d.py --self-test | |
| @TODO | |
| - [P1] test with very big files (gigabytes) | |
| - [P2] --stats by default; replace by --nostats (?) | |
| - [P2] in the stats table, add a column for mask analysis: | |
| if the field is less than 80 chars long, | |
| replace letters by `L` and digits by `D` but keep | |
| ponctuation and/or symbols and display the 3 | |
| most given values (like top_3_freq); eg. LLLL@LLLL.LLL | |
| """ | |
| import argparse | |
| import atexit | |
| import csv | |
| import doctest | |
| import re | |
| import shutil | |
| import socket | |
| import sqlite3 | |
| import statistics | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| import unidecode | |
| from collections import Counter | |
| from pathlib import Path | |
| import yaml | |
| SCRIPT_START = time.monotonic() | |
| # --------------------------------------------------------------------------- | |
| # Helpers: name sanitizing | |
| # --------------------------------------------------------------------------- | |
| def sanitize_name(name: str) -> str: | |
| """Turn a filename or column name into a safe SQL identifier. | |
| >>> sanitize_name("2024 sales.csv") | |
| 'col_2024_sales_csv' | |
| >>> sanitize_name("customer-id") | |
| 'customer_id' | |
| >>> sanitize_name("") | |
| 'col' | |
| """ | |
| name = re.sub(r"[.\-\s]+", "_", name) | |
| # Replace accented characters with non-accented equivalents | |
| name = (unidecode.unidecode(name)) | |
| name = re.sub(r"[^0-9A-Za-z_]", "_", name) | |
| if re.match(r"^[0-9]", name): | |
| name = f"col_{name}" | |
| return name or "col" | |
| def table_name_from_path(path: Path) -> str: | |
| """Return a sanitized table name based on a CSV path. | |
| >>> table_name_from_path(Path("monthly sales.csv")) | |
| 'monthly_sales' | |
| >>> table_name_from_path(Path("réceptions & fêtes.csv")) | |
| 'receptions___fetes' | |
| """ | |
| return sanitize_name(path.stem) | |
| # --------------------------------------------------------------------------- | |
| # Helpers: value typing (replaces the SQL REGEXP-based logic) | |
| # --------------------------------------------------------------------------- | |
| _NUMERIC_RE = re.compile(r"^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$") | |
| _LEADING_ZERO_RE = re.compile(r"^[+-]?0[0-9]+") # e.g. "056", "-082" -> treat as code, not number | |
| _ISO_DATE_RE = re.compile( # Compile the regex pattern for matching ISO-formatted dates | |
| r"^" # Start anchor | |
| r"[1-9][0-9]{0,3}" # year: 1-4 digits, starting with 1-9 (no leading zero, allows years 1-9999) | |
| r"(-?(0[13578]|1[02])(-?(0[1-9]|[12][0-9]|3[01]))?" # Case 1: 31-day months (Jan,Mar,May,Jul,Aug,Oct,Dec), optional dash separators, optional day | |
| r"|-?(0[469]|11)-?(0[1-9]|[12][0-9]|30)?" # Case 2: 30-day months (Apr,Jun,Sep,Nov), optional dash separators, optional day | |
| r"|-?02-?(0[1-9]|[12][0-9])?)?" # Case 3: February (month 02), days 01-29, optional day component | |
| r"(" # Start of time component | |
| r"(T| )(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])" # Time separator (T or space) + hours (00-23) + minutes (00-59) | |
| r"(:(0[0-9]|[1-5][0-9])" # Optional seconds | |
| r"(\.[0-9]{1,7})?" # + fractional seconds (1-7 decimals) | |
| r"(Z|[+-][0-2][0-9]:[0-5][0-9])?" # + timezone (Z or offset) | |
| r")?" | |
| r")?" # End of time component | |
| r"$" # End anchor | |
| ) | |
| def is_numeric(value: str) -> bool: | |
| """Return whether *value* is numeric and not a leading-zero code. | |
| >>> is_numeric("-12.5"), is_numeric(".5"), is_numeric("+12"), is_numeric("12.") | |
| (True, True, True, True) | |
| >>> is_numeric("1e3") | |
| True | |
| >>> is_numeric("056"), is_numeric("-082") | |
| (False, False) | |
| >>> is_numeric(""), is_numeric("1,5"), is_numeric("not a number") | |
| (False, False, False) | |
| """ | |
| if not _NUMERIC_RE.match(value): | |
| return False | |
| if _LEADING_ZERO_RE.match(value): | |
| return False | |
| return True | |
| def is_probable_iso_date(value: str) -> bool: | |
| """Return whether *value* resembles the supported ISO date formats. | |
| The check is intentionally approximate; it identifies values for stats | |
| reporting and does not replace full date validation. | |
| >>> is_probable_iso_date("2024-02-29") | |
| True | |
| >>> is_probable_iso_date("2024-02-29T12:30:00Z") | |
| True | |
| >>> is_probable_iso_date("2024-02-29T12:59:00.1234567") | |
| True | |
| >>> is_probable_iso_date("2024-02-29T12:30:00+02:30") | |
| True | |
| >>> is_probable_iso_date("30") | |
| False | |
| >>> is_probable_iso_date("2024-02-29T12:60:00") | |
| False | |
| >>> is_probable_iso_date("2024-13-01"), is_probable_iso_date("2024-01-01T24:00") | |
| (False, False) | |
| """ | |
| if not _ISO_DATE_RE.match(value): | |
| return False | |
| # avoid false positives on bare short numbers (e.g. "30", "25") | |
| # by requiring either a 4-digit year or an actual date/time separator. | |
| return bool(re.match(r"^\d{4}", value)) or bool(re.search(r"[-T:]", value)) | |
| def apply_decimal_separator(value: str, decimal_sep: str) -> str: | |
| """Convert a configured decimal separator to SQLite's ``.`` format. | |
| >>> apply_decimal_separator("12,50", ",") | |
| '12.50' | |
| >>> apply_decimal_separator("12.50", ",") | |
| '12.50' | |
| >>> apply_decimal_separator("12,50", None) | |
| '12,50' | |
| """ | |
| if decimal_sep and decimal_sep in value: | |
| return value.replace(decimal_sep, ".") | |
| return value | |
| # --------------------------------------------------------------------------- | |
| # CSV reading | |
| # --------------------------------------------------------------------------- | |
| def read_csv(path: Path, separator: str, generate_columns: bool): | |
| """Return (headers, rows) as lists of strings. | |
| Short rows are padded, long rows are truncated, and duplicate headers are | |
| made unique. A UTF-8 BOM is ignored by the reader. | |
| >>> with tempfile.TemporaryDirectory() as directory: | |
| ... path = Path(directory) / "data.csv" | |
| ... _ = path.write_text("\\ufeffName,Name\\nAlice\\nBob,too,many", encoding="utf-8") | |
| ... read_csv(path, ",", False) | |
| (['Name', 'Name_1'], [['Alice', ''], ['Bob', 'too']]) | |
| >>> with tempfile.TemporaryDirectory() as directory: | |
| ... path = Path(directory) / "data.csv" | |
| ... _ = path.write_text("Alice,1\\nBob,2", encoding="utf-8") | |
| ... read_csv(path, ",", True) | |
| (['col_1', 'col_2'], [['Alice', '1'], ['Bob', '2']]) | |
| >>> with tempfile.TemporaryDirectory() as directory: | |
| ... path = Path(directory) / "empty.csv" | |
| ... _ = path.write_text("", encoding="utf-8") | |
| ... read_csv(path, ",", False) | |
| ([], []) | |
| """ | |
| # CSV field size limit is 128 KB by default; increase this limit with a hardcoded value | |
| csv.field_size_limit(10*1000*1000) # 10 MB limit | |
| with path.open(newline="", encoding="utf-8-sig", errors="replace") as f: | |
| reader = csv.reader(f, delimiter=separator) | |
| rows = list(reader) | |
| if not rows: | |
| return [], [] | |
| if generate_columns: | |
| n_cols = max(len(r) for r in rows) | |
| headers = [f"col_{i+1}" for i in range(n_cols)] | |
| data_rows = rows | |
| else: | |
| headers = [sanitize_name(h) or f"col_{i+1}" for i, h in enumerate(rows[0])] | |
| data_rows = rows[1:] | |
| # dedupe accidental duplicate column names | |
| seen = {} | |
| unique_headers = [] | |
| for h in headers: | |
| if h in seen: | |
| seen[h] += 1 | |
| h = f"{h}_{seen[h]}" | |
| else: | |
| seen[h] = 0 | |
| unique_headers.append(h) | |
| headers = unique_headers | |
| # pad/truncate rows to header length | |
| n = len(headers) | |
| normalized = [] | |
| for r in data_rows: | |
| if len(r) < n: | |
| r = r + [""] * (n - len(r)) | |
| elif len(r) > n: | |
| r = r[:n] | |
| normalized.append(r) | |
| return headers, normalized | |
| # --------------------------------------------------------------------------- | |
| # Stats computation (replaces the SQL-based --stats block) | |
| # --------------------------------------------------------------------------- | |
| def percentile(sorted_values, p): | |
| """Return the value at percentage *p* using the existing nearest-rank rule. | |
| >>> percentile([], 50) is None | |
| True | |
| >>> percentile([10, 20, 30, 40], 50) | |
| 30 | |
| >>> percentile([10, 20, 30, 40], 100) | |
| 40 | |
| >>> percentile([42], 10), percentile([42], 90) | |
| (42, 42) | |
| """ | |
| if not sorted_values: | |
| return None | |
| idx = int(len(sorted_values) * p / 100) | |
| idx = min(idx, len(sorted_values) - 1) | |
| return sorted_values[idx] | |
| def confidence_pct(matching: int, total: int) -> float: | |
| """Percentage of *matching* values out of *total*, rounded to 3 decimals. | |
| Never rounds up to 100 unless *matching* == *total*, so a column that's | |
| not fully consistent with its inferred type never displays as "100%". | |
| >>> confidence_pct(3, 3) | |
| 100.0 | |
| >>> confidence_pct(0, 0), confidence_pct(1, 3) | |
| (0.0, 33.333) | |
| >>> confidence_pct(999999, 1000000) | |
| 99.999 | |
| """ | |
| if total == 0: | |
| return 0.0 | |
| if matching == total: | |
| return 100.0 | |
| pct = round(matching / total * 100, 3) | |
| return min(pct, 99.999) | |
| def compute_column_stats(col_name: str, values, decimal_sep: str): | |
| """Compute the summary row used by the optional stats table. | |
| Values are kept as strings for display, while numeric summaries use the | |
| configured decimal separator. | |
| >>> stats = compute_column_stats("amount", ["1,5", "", "2,5", "1,5"], ",") | |
| >>> (stats["filled"], stats["missing"], stats["fill_rate"]) | |
| (3, 1, 75.0) | |
| >>> (stats["uniq"], stats["duplicates"]) | |
| (2, 1) | |
| >>> (stats["inferred_type"], stats["type_confidence_pct"], stats["min"], stats["max"], stats["sum"]) | |
| ('numeric', 100.0, 1.5, 2.5, 5.5) | |
| >>> (stats["avg"], stats["med"], stats["stddev"]) | |
| (1.83333, 1.5, 0.4714) | |
| >>> stats["percentiles_10_25_50_75_90"] | |
| '1.5, 1.5, 1.5, 2.5, 2.5' | |
| >>> stats["top_3_freq"] | |
| '1,5 (2)\\n2,5 (1)' | |
| Date columns are identified when more than 90% of their values look like dates: | |
| >>> dates = compute_column_stats("created", ["2024-01-01", "2024-02-29"], None) | |
| >>> (dates["inferred_type"], dates["type_confidence_pct"], dates["probISODate"]) | |
| ('date', 100.0, 2) | |
| Text columns retain lexical bounds and report their text confidence: | |
| >>> text = compute_column_stats("name", ["Alice", "Bob", "Alice"], None) | |
| >>> (text["inferred_type"], text["type_confidence_pct"], text["min"], text["max"]) | |
| ('text', 100.0, 'Alice', 'Bob') | |
| A single numeric value has zero population standard deviation: | |
| >>> single = compute_column_stats("count", ["7"], None) | |
| >>> (single["inferred_type"], single["avg"], single["stddev"], single["sum"]) | |
| ('numeric', 7.0, 0.0, 7.0) | |
| Mixed values fall back to text with confidence below 100%: | |
| >>> mixed = compute_column_stats("value", ["1", "unknown"], None) | |
| >>> (mixed["inferred_type"], mixed["type_confidence_pct"]) | |
| ('text', 50.0) | |
| Only the three most frequent values are included: | |
| >>> frequent = compute_column_stats("status", ["a", "a", "b", "c", "d"], None) | |
| >>> frequent["top_3_freq"] | |
| 'a (2)\\nb (1)\\nc (1)' | |
| A column with no filled values gets a placeholder "empty" row: | |
| >>> empty = compute_column_stats("notes", ["", ""], None) | |
| >>> (empty["inferred_type"], empty["filled"], empty["missing"]) | |
| ('empty', 0, 2) | |
| """ | |
| n_total = len(values) | |
| filled = [v for v in values if v != ""] | |
| missing = n_total - len(filled) | |
| uniq = len(set(filled)) | |
| fill_rate = round(len(filled) / n_total * 100, 1) if n_total else 0.0 | |
| row = { | |
| "column_name": col_name, | |
| "inferred_type": "empty", | |
| "type_confidence_pct": None, | |
| "filled": len(filled), | |
| "missing": missing, | |
| "fill_rate": fill_rate, | |
| "uniq": uniq, | |
| "duplicates": len(filled) - uniq, | |
| "min": None, "max": None, | |
| "avg": None, "med": None, "stddev": None, "sum": None, | |
| "percentiles_10_25_50_75_90": None, | |
| "shortestStr": None, "longestStr": None, | |
| "probISODate": 0, | |
| "top_3_freq": None, | |
| } | |
| # If all values are missing, return early with the row containing only metadata. | |
| if not filled: | |
| return row | |
| normed = [apply_decimal_separator(v, decimal_sep) for v in filled] | |
| numeric_flags = [is_numeric(v) for v in normed] | |
| n_numeric = sum(numeric_flags) | |
| n_text = len(filled) - n_numeric | |
| row["probISODate"] = sum(1 for v in filled if is_probable_iso_date(v)) | |
| row["shortestStr"] = min(len(v) for v in filled) | |
| row["longestStr"] = max(len(v) for v in filled) | |
| top3 = Counter(filled).most_common(3) | |
| row["top_3_freq"] = "\n".join(f"{val} ({cnt})" for val, cnt in top3) | |
| text_ratio = n_text / len(filled) * 100 | |
| is_text_col = text_ratio > 90 | |
| date_ratio = row["probISODate"] / len(filled) * 100 | |
| if is_text_col: | |
| row["inferred_type"] = "date" if date_ratio > 90 else "text" | |
| row["type_confidence_pct"] = confidence_pct( | |
| row["probISODate"] if row["inferred_type"] == "date" else n_text, len(filled) | |
| ) | |
| row["min"] = min(filled) | |
| row["max"] = max(filled) | |
| else: | |
| try: | |
| nums = sorted(float(v) for v in normed) | |
| row["inferred_type"] = "numeric" | |
| row["type_confidence_pct"] = confidence_pct(n_numeric, len(filled)) | |
| row["min"] = nums[0] | |
| row["max"] = nums[-1] | |
| row["med"] = round(statistics.median(nums), 5) | |
| row["stddev"] = round(statistics.pstdev(nums), 5) if len(nums) > 1 else 0.0 | |
| pcts = [percentile(nums, p) for p in (10, 25, 50, 75, 90)] | |
| row["percentiles_10_25_50_75_90"] = ", ".join(str(p) for p in pcts) | |
| row["avg"] = round(sum(nums) / len(nums), 5) | |
| row["sum"] = round(sum(nums), 5) | |
| except ValueError: | |
| row["inferred_type"] = "text" | |
| row["type_confidence_pct"] = confidence_pct(n_text, len(filled)) | |
| row["min"] = min(filled) | |
| row["max"] = max(filled) | |
| return row | |
| # --------------------------------------------------------------------------- | |
| # Datasette plumbing | |
| # --------------------------------------------------------------------------- | |
| STATS_COLUMNS_ORDER = [ | |
| "column_name", "inferred_type", "type_confidence_pct", | |
| "filled", "missing", "fill_rate", "uniq", "duplicates", | |
| "min", "max", | |
| "avg", "med", "stddev", "sum", "percentiles_10_25_50_75_90", | |
| "shortestStr", "longestStr", | |
| "probISODate", | |
| "top_3_freq", | |
| ] | |
| STATS_COLUMNS_HELP = """ | |
| <li><code>column_name</code>: the name of the column</li> | |
| <li><code>inferred_type</code>: numeric / date / text, based on the column's content</li> | |
| <li><code>type_confidence_pct</code>: percentage of filled values that actually match the <code>inferred_type</code></li> | |
| <li><code>filled</code>: the number of filled rows</li> | |
| <li><code>missing</code>: the number of missing (empty) values</li> | |
| <li><code>fill_rate</code>: percentage of rows filled</li> | |
| <li><code>uniq</code>: the number of unique values</li> | |
| <li><code>duplicates</code>: filled - uniq</li> | |
| <li><code>min</code>: the lowest value</li> | |
| <li><code>max</code>: the highest value</li> | |
| <li><code>avg</code>: the mean (numeric columns only)</li> | |
| <li><code>med</code>: the median (numeric columns only)</li> | |
| <li><code>stddev</code>: the population standard deviation (numeric columns only)</li> | |
| <li><code>sum</code>: the sum (numeric columns only)</li> | |
| <li><code>percentiles_10_25_50_75_90</code>: the 10th/25th/50th/75th/90th percentiles</li> | |
| <li><code>shortestStr</code> / <code>longestStr</code>: shortest / longest string length</li> | |
| <li><code>probISODate</code>: number of values that look like ISO dates</li> | |
| <li><code>top_3_freq</code>: the 3 most frequent values</li> | |
| """.strip() | |
| def get_free_port() -> int: | |
| s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| s.bind(("", 0)) | |
| port = s.getsockname()[1] | |
| s.close() | |
| return port | |
| def get_datasette_major_version() -> str: | |
| try: | |
| out = subprocess.run( | |
| [sys.executable, "-m", "datasette", "--version"], | |
| capture_output=True, text=True, check=True, | |
| ).stdout | |
| except Exception: | |
| print("Datasette is not installed or not reachable. " | |
| "See https://datasette.io/", file=sys.stderr) | |
| sys.exit(1) | |
| if re.search(r"\b0\.", out): | |
| return "0" | |
| if re.search(r"\b1\.0", out): | |
| return "1" | |
| print(f"Unsupported Datasette version: {out.strip()}", file=sys.stderr) | |
| sys.exit(1) | |
| def write_static_assets(static_dir: Path): | |
| static_dir.mkdir(parents=True, exist_ok=True) | |
| js = r""" | |
| window.addEventListener('load', function () { | |
| let classes = ["col-filled", "col-missing", "col-numericValues", "col-textValues", "col-probISODate"]; | |
| for (const c of classes) { | |
| let x = document.getElementsByClassName(c); | |
| for (let i = 0; i < x.length; i++) { | |
| if (x[i].innerText == 0) { x[i].classList.add('zero'); } | |
| } | |
| } | |
| enhanceStatsCells(); | |
| }); | |
| function configureScrolling() { | |
| const scrolling = document.querySelector('.table-wrapper'); | |
| const thead = document.querySelector('.rows-and-columns thead'); | |
| if (!scrolling || !thead) return; | |
| const translate = () => { | |
| const scroll = window.scrollY; | |
| const headerTop = scrolling.offsetTop; | |
| if (scroll > headerTop) { | |
| thead.style.setProperty('transform', `translateY(${Math.floor(Math.abs(scroll - headerTop))}px)`); | |
| } else { | |
| thead.style.removeProperty('transform'); | |
| } | |
| }; | |
| document.addEventListener('scroll', translate); | |
| } | |
| addEventListener('DOMContentLoaded', configureScrolling); | |
| /* --- Visual enhancements for the stats_* tables --- */ | |
| /* No-op on regular data tables: the col-fill_rate / col-inferred_type / | |
| col-top_3_freq classes only exist on stats tables, so all the | |
| querySelectorAll calls below simply return nothing there. */ | |
| function enhanceStatsCells() { | |
| /* fill_rate: colored bar, red (low) -> green (high) */ | |
| document.querySelectorAll('td.col-fill_rate').forEach(function (cell) { | |
| var pct = parseFloat(cell.textContent); | |
| if (isNaN(pct)) return; | |
| var hue = Math.max(0, Math.min(120, pct * 1.2)); | |
| cell.style.background = 'linear-gradient(90deg, hsla(' + hue + ',65%,45%,0.35) ' + pct + '%, transparent ' + pct + '%)'; | |
| cell.classList.add('bar-cell'); | |
| }); | |
| /* duplicates: neutral bar showing duplicates / filled */ | |
| document.querySelectorAll('td.col-duplicates').forEach(function (cell) { | |
| var row = cell.closest('tr'); | |
| var filledCell = row ? row.querySelector('td.col-filled') : null; | |
| var dup = parseFloat(cell.textContent); | |
| var filled = filledCell ? parseFloat(filledCell.textContent) : NaN; | |
| if (isNaN(dup) || isNaN(filled) || filled === 0) return; | |
| var pct = (dup / filled) * 100; | |
| cell.style.background = 'linear-gradient(90deg, hsla(210,60%,50%,0.30) ' + pct + '%, transparent ' + pct + '%)'; | |
| cell.classList.add('bar-cell'); | |
| cell.title = pct.toFixed(1) + '% of filled values are duplicates'; | |
| }); | |
| /* inferred_type: small colored badge instead of plain text */ | |
| document.querySelectorAll('td.col-inferred_type').forEach(function (cell) { | |
| if (cell.querySelector('.type-badge')) return; | |
| var val = cell.textContent.trim(); | |
| if (!val) return; | |
| cell.textContent = ''; | |
| var span = document.createElement('span'); | |
| span.className = 'type-badge type-' + val; | |
| span.textContent = val; | |
| cell.appendChild(span); | |
| }); | |
| /* top_3_freq: mini horizontal bar chart, each bar sized relative to "filled" */ | |
| document.querySelectorAll('td.col-top_3_freq').forEach(function (cell) { | |
| if (cell.querySelector('.freq-bars')) return; | |
| var row = cell.closest('tr'); | |
| var filledCell = row ? row.querySelector('td.col-filled') : null; | |
| var total = filledCell ? parseFloat(filledCell.textContent) : NaN; | |
| var raw = cell.textContent.trim(); | |
| if (!raw) return; | |
| var lines = raw.split('\n').map(function (l) { return l.trim(); }).filter(Boolean); | |
| var container = document.createElement('div'); | |
| container.className = 'freq-bars'; | |
| var addedAny = false; | |
| lines.forEach(function (line) { | |
| var m = line.match(/^(.*) \((\d+)\)$/); | |
| if (!m) return; | |
| var label = m[1]; | |
| var count = parseInt(m[2], 10); | |
| var pct = (!isNaN(total) && total > 0) ? (count / total * 100) : 0; | |
| addedAny = true; | |
| var barRow = document.createElement('div'); | |
| barRow.className = 'freq-bar-row'; | |
| var track = document.createElement('div'); | |
| track.className = 'freq-bar-track'; | |
| var fill = document.createElement('div'); | |
| fill.className = 'freq-bar-fill'; | |
| fill.style.width = Math.max(pct, 2) + '%'; | |
| track.appendChild(fill); | |
| var labelSpan = document.createElement('span'); | |
| labelSpan.className = 'freq-bar-label'; | |
| labelSpan.textContent = label + ' (' + count + (total > 0 ? ', ' + pct.toFixed(0) + '%' : '') + ')'; | |
| barRow.appendChild(track); | |
| barRow.appendChild(labelSpan); | |
| container.appendChild(barRow); | |
| }); | |
| if (addedAny) { | |
| cell.textContent = ''; | |
| cell.appendChild(container); | |
| } | |
| }); | |
| } | |
| """.strip() | |
| css = """ | |
| .zero { color: RGBA(0,0,0,.2) !important; } | |
| .rows-and-columns { border-collapse: separate; } | |
| .rows-and-columns thead { background-color: white; position: sticky; top: 0; } | |
| .rows-and-columns thead th { border-bottom: 1px solid #aaa; } | |
| /* Stats table visual enhancements */ | |
| td.bar-cell { background-repeat: no-repeat; } | |
| .type-badge { | |
| display: inline-block; | |
| padding: 1px 9px; | |
| border-radius: 10px; | |
| font-size: 0.82em; | |
| font-weight: 600; | |
| color: white; | |
| white-space: nowrap; | |
| } | |
| .type-numeric { background-color: #2b6cb0; } | |
| .type-date { background-color: #6b46c1; } | |
| .type-text { background-color: #718096; } | |
| .type-empty { background-color: #cbd5e0; color: #333; } | |
| .freq-bars { display: flex; flex-direction: column; gap: 3px; min-width: 150px; } | |
| .freq-bar-row { display: flex; align-items: center; gap: 6px; } | |
| .freq-bar-track { | |
| flex: 0 0 60px; | |
| height: 8px; | |
| background: #eee; | |
| border-radius: 4px; | |
| overflow: hidden; | |
| } | |
| .freq-bar-fill { height: 100%; background: #4299e1; border-radius: 4px; } | |
| .freq-bar-label { font-size: 0.82em; white-space: nowrap; } | |
| """.strip() | |
| (static_dir / "datasette2csv.js").write_text(js, encoding="utf-8") | |
| (static_dir / "datasette2csv.css").write_text(css, encoding="utf-8") | |
| def write_metadata(tempdir: Path, table_names, with_stats: bool, datasette_major: str): | |
| tables = {} | |
| for t in table_names: | |
| if with_stats: | |
| tables[t] = { | |
| "description_html": f'<p>See <a href="./{t}_stats">stats</a> for this table.</p>' | |
| } | |
| tables[f"{t}_stats"] = { | |
| "description_html": ( | |
| f'<p>Stats about the <a href="./{t}">{t}</a> table:</p>' | |
| f'<ul style="list-style: inside;">{STATS_COLUMNS_HELP}</ul>' | |
| ) | |
| } | |
| # If there's nothing to say about a table, omit it entirely rather | |
| # than emitting an empty YAML mapping (Datasette chokes on `table: ` | |
| # with no value, since it comes back as None instead of a dict). | |
| metadata = {"databases": {"db": {"tables": tables}}} if tables else {} | |
| extra = { | |
| "extra_css_urls": ["/static/datasette2csv.css"], | |
| "extra_js_urls": ["/static/datasette2csv.js"], | |
| } | |
| metadata_path = tempdir / "metadata.yml" | |
| if datasette_major == "1": | |
| metadata_path.write_text( | |
| yaml.safe_dump(metadata, allow_unicode=True, sort_keys=False) if metadata else "", | |
| encoding="utf-8", | |
| ) | |
| (tempdir / "datasette.yml").write_text( | |
| yaml.safe_dump(extra, allow_unicode=True, sort_keys=False), encoding="utf-8" | |
| ) | |
| else: | |
| metadata.update(extra) | |
| metadata_path.write_text( | |
| yaml.safe_dump(metadata, allow_unicode=True, sort_keys=False), encoding="utf-8" | |
| ) | |
| return metadata_path | |
| def read_rc_args() -> list: | |
| """Optional ~/.config/csv2datasette/extra_args — one datasette CLI arg per line.""" | |
| rc = Path.home() / ".config" / "csv2datasette" / "extra_args" | |
| if rc.is_file(): | |
| return [line.strip() for line in rc.read_text(encoding="utf-8").splitlines() if line.strip()] | |
| return [] | |
| # --------------------------------------------------------------------------- | |
| # Main | |
| # --------------------------------------------------------------------------- | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| prog="csv2datasette", | |
| description="Explore CSV file(s) directly in Datasette.", | |
| ) | |
| parser.add_argument("files", nargs="*", type=Path, help="CSV file(s) to explore") | |
| parser.add_argument("-e", "--generate-column-names", action="store_true", | |
| help="Auto-generate column names (col_1, col_2, ...) if the CSV has none") | |
| parser.add_argument("-s", "--separator", default=",", help='Field separator (default: ",")') | |
| parser.add_argument("-t", "--tsv", action="store_true", help="Separator is a tab") | |
| parser.add_argument("-d", "--decimal-separator", default=None, | |
| help='Decimal separator used in numbers (e.g. "," for French numbers)') | |
| parser.add_argument("--stats", action="store_true", help="Add WTFCsv-like stats table(s)") | |
| parser.add_argument("--self-test", action="store_true", | |
| help="Run this module's doctests (via uv, using the PEP 723 deps) and exit") | |
| parser.add_argument("-v", "--verbose", action="store_true") | |
| args = parser.parse_args() | |
| # Run doctests if requested, then exit with the appropriate status code. | |
| if args.self_test: | |
| results = doctest.testmod(verbose=args.verbose) | |
| sys.exit(1 if results.failed else 0) | |
| if not args.files: | |
| parser.error("the following arguments are required: files") | |
| def log(msg): | |
| if args.verbose: | |
| print(f"[+{time.monotonic() - SCRIPT_START:.3f}s] {msg}") | |
| separator = "\t" if args.tsv else args.separator | |
| for f in args.files: | |
| if not f.is_file(): | |
| print(f"{f} does not exist.", file=sys.stderr) | |
| sys.exit(1) | |
| datasette_major = get_datasette_major_version() | |
| log(f"Datasette major version: {datasette_major}") | |
| tempdir = Path(tempfile.mkdtemp(prefix="csv2datasette.")) | |
| # Register a cleanup function to remove the temporary directory when the program exits | |
| atexit.register(lambda: shutil.rmtree(tempdir, ignore_errors=True)) | |
| log(f"Temp dir: {tempdir}") | |
| db_path = tempdir / "db.sqlite3" | |
| conn = sqlite3.connect(db_path) | |
| table_names = [] | |
| for f in args.files: | |
| table = table_name_from_path(f) | |
| # avoid collisions between multiple files sharing a sanitized name | |
| base_table, i = table, 1 | |
| while table in table_names: | |
| i += 1 | |
| table = f"{base_table}_{i}" | |
| table_names.append(table) | |
| log(f"Reading {f} into table [{table}]...") | |
| headers, rows = read_csv(f, separator, args.generate_column_names) | |
| if not headers: | |
| print(f"Warning: {f} appears empty, skipping.", file=sys.stderr) | |
| continue | |
| col_defs = ", ".join(f'"{h}" TEXT' for h in headers) | |
| conn.execute(f'CREATE TABLE "{table}" ({col_defs});') | |
| placeholders = ", ".join("?" for _ in headers) | |
| conn.executemany( | |
| f'INSERT INTO "{table}" VALUES ({placeholders});', | |
| [[apply_decimal_separator(v, args.decimal_separator) if args.decimal_separator else v | |
| for v in row] for row in rows], | |
| ) | |
| conn.commit() | |
| if args.stats: | |
| log(f"Computing stats for [{table}]...") | |
| columns = [(h, [row[idx] for row in rows]) for idx, h in enumerate(headers)] | |
| stats_rows = [compute_column_stats(h, vals, args.decimal_separator) for h, vals in columns] | |
| stats_table = f"{table}_stats" | |
| col_types = { | |
| "column_name": "TEXT", "inferred_type": "TEXT", "type_confidence_pct": "REAL", | |
| "filled": "INT", "missing": "INT", "fill_rate": "REAL", | |
| "uniq": "INT", "duplicates": "INT", | |
| "min": "TEXT", "max": "TEXT", | |
| "avg": "REAL", "med": "REAL", "stddev": "REAL", "sum": "REAL", | |
| "percentiles_10_25_50_75_90": "TEXT", | |
| "shortestStr": "INT", "longestStr": "INT", | |
| "probISODate": "INT", "top_3_freq": "TEXT", | |
| } | |
| col_defs_sql = ", ".join(f'"{c}" {col_types[c]}' for c in STATS_COLUMNS_ORDER) | |
| conn.execute(f'CREATE TABLE "{stats_table}" ({col_defs_sql});') | |
| conn.executemany( | |
| f'INSERT INTO "{stats_table}" VALUES ({", ".join("?" for _ in STATS_COLUMNS_ORDER)});', | |
| [[r[c] for c in STATS_COLUMNS_ORDER] for r in stats_rows], | |
| ) | |
| # Create a dictionnary with { "column1": "column1", [...] } | |
| STATS_COLUMNS_LINKS_DICT = dict(zip(STATS_COLUMNS_ORDER, STATS_COLUMNS_ORDER)) | |
| # For some stats' columns, build links to data | |
| # facet by column name | |
| # /db/table?_facet=frequency#facet-frequency | |
| STATS_COLUMNS_LINKS_DICT["column_name"] = (f""" | |
| json_object("href", "/db/" || "{table}?_facet=" || column_name || "#facet-", | |
| "label", column_name, | |
| "title", "faceted browse by " || column_name | |
| ) as column_name | |
| """) | |
| # missing | |
| STATS_COLUMNS_LINKS_DICT["missing"] = (f""" | |
| json_object("href", "/db?sql=--+" || column_name || "+column%3A+missing+data%0D%0A" | |
| || "select+*+from+" || "{table}" || "+where+" || column_name | |
| || "+=+''+limit+100", | |
| "label", missing, | |
| "title", column_name || " column: missing data" | |
| ) as missing | |
| """) | |
| # /db/mydb?_facet=frequency#facet-frequency | |
| STATS_COLUMNS_LINKS_DICT["duplicates"] = (f""" | |
| json_object("href", "/db?sql=--+" || column_name || "+column%3A+duplicates%0D%0A" | |
| || "select+*+from+" || "{table}" | |
| || "+group+by+" || column_name || "+having+count(*)+>+1+" | |
| || "limit+100", | |
| "label", duplicates, | |
| "title", column_name || " column: duplicates" | |
| ) as duplicates | |
| """) | |
| # /db/table?_sort=createdAt | |
| STATS_COLUMNS_LINKS_DICT["min"] = (f""" | |
| json_object("href", "/db/" || "{table}?_sort=" || column_name, | |
| "label", min, | |
| "title", column_name || " column: sort ascending" | |
| ) as min | |
| """) | |
| # /db/table?_sort_desc=createdAt | |
| STATS_COLUMNS_LINKS_DICT["max"] = (f""" | |
| json_object("href", "/db/" || "{table}?_sort_desc=" || column_name, | |
| "label", max, | |
| "title", column_name || " column: sort descending" | |
| ) as max | |
| """) | |
| # Use dictionnary's values to build a view | |
| STATS_COLUMNS_LINKS = ", ".join(STATS_COLUMNS_LINKS_DICT.values()) | |
| # log(f"STATS_COLUMNS_LINKS: {STATS_COLUMNS_LINKS}") | |
| conn.execute(f'CREATE VIEW "{stats_table}_links" AS SELECT {STATS_COLUMNS_LINKS} FROM "{stats_table}";') | |
| conn.commit() | |
| conn.close() | |
| write_static_assets(tempdir / "static") | |
| write_metadata(tempdir, table_names, args.stats, datasette_major) | |
| rc_args = read_rc_args() | |
| port = get_free_port() | |
| cmd = [ | |
| sys.executable, "-m", "datasette", str(db_path), | |
| "-h", "127.0.0.1", "-p", str(port), "--open", | |
| "--setting", "facet_time_limit_ms", "20000", | |
| "--setting", "facet_suggest_time_limit_ms", "10000", | |
| "--setting", "sql_time_limit_ms", "20000", | |
| "--setting", "max_returned_rows", "100000", | |
| "--setting", "truncate_cells_html", "500", | |
| "--metadata", str(tempdir / "metadata.yml"), | |
| "--static", f"static:{tempdir / 'static'}", | |
| ] | |
| # Datasette 1.x uses a separate datasette.yml for | |
| # extra_js_urls / extra_css_urls, while 0.x uses the metadata.yml for that. | |
| if datasette_major == "1": | |
| cmd += ["--config", str(tempdir / "datasette.yml")] | |
| cmd += rc_args | |
| log(f"Launching: {' '.join(cmd)}") | |
| try: | |
| subprocess.run(cmd) | |
| except KeyboardInterrupt: | |
| pass | |
| # temp dir cleanup happens via atexit | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment