InterestingITS's picture
Upload 11 files
cf2bed9 verified
Raw History Blame Contribute Delete
1.97 kB
"""Shared CSV validation and non-overwriting output helpers."""
import argparse
import os
from contextlib import contextmanager
from pathlib import Path
import tempfile
import numpy as np
import pandas as pd
def parser(description):
return argparse.ArgumentParser(description=description)
def require(df, columns):
missing = set(columns) - set(df.columns)
if missing:
raise ValueError(f"Missing columns: {sorted(missing)}")
def numeric(df, columns, integer=False):
require(df, columns)
for col in columns:
values = pd.to_numeric(df[col], errors="raise")
if not np.isfinite(values.to_numpy(dtype=float)).all():
raise ValueError(f"Non-finite values in {col}")
if integer:
if not (values == np.floor(values)).all():
raise ValueError(f"Non-integer values in {col}")
values = values.astype("int64")
df[col] = values
def unique(df, keys):
require(df, keys)
if df[keys].isna().any().any() or df.duplicated(keys).any():
raise ValueError(f"Missing or duplicate keys: {keys}")
def read_csv(path):
df = pd.read_csv(path, encoding="utf-8-sig")
if df.empty:
raise ValueError(f"Empty input: {path}")
return df
@contextmanager
def output_path(path):
path = Path(path)
if path.exists():
raise FileExistsError(f"Output exists; choose a new filename: {path}")
path.parent.mkdir(parents=True, exist_ok=True)
handle, temporary = tempfile.mkstemp(prefix=path.name + ".", dir=path.parent)
os.close(handle)
try:
yield temporary
if path.exists():
raise FileExistsError(path)
os.replace(temporary, path)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
def save_csv(df, path):
with output_path(path) as temporary:
df.to_csv(temporary, index=False, encoding="utf-8-sig")
print(f"Saved {len(df):,} rows: {path}")