freelance-samples / data_cleaning /make_previews.py
protoneko's picture
Upload folder using huggingface_hub
61bb557 verified
Raw History Blame Contribute Delete
4.23 kB
"""
make_previews.py — Render before/after PNG previews of the first rows.
Reads messy_orders.csv (before) and clean.csv (after), and renders the first
N rows of each as a PNG table using Pillow (monospace font, header row
highlighted). Pure stdlib + Pillow, no matplotlib needed.
Usage:
python make_previews.py [messy.csv] [clean.csv] [n_rows]
Writes:
before_messy.png
after_clean.png
"""
from __future__ import annotations
import sys
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
N_ROWS_DEFAULT = 14
COL_PAD = 14
ROW_H = 30
HEADER_BG = (38, 50, 56)
HEADER_FG = (255, 255, 255)
ROW_BG_A = (255, 255, 255)
ROW_BG_B = (245, 247, 249)
GRID = (200, 208, 214)
TEXT = (33, 37, 41)
TITLE_BG = (27, 33, 37)
def load_font(size: int) -> ImageFont.FreeTypeFont:
candidates = [
"C:/Windows/Fonts/consola.ttf",
"C:/Windows/Fonts/DejaVuSansMono.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
"C:/Windows/Fonts/lucidaconsole.ttf",
]
for path in candidates:
if Path(path).exists():
return ImageFont.truetype(path, size)
return ImageFont.load_default()
def truncate(s: str, width: int, font) -> str:
if font.getlength(s) <= width:
return s
while s and font.getlength(s + "…") > width:
s = s[:-1]
return s + "…"
def render(path: Path, title: str, rows: list[list[str]],
font: ImageFont.FreeTypeFont) -> None:
ncols = max(len(r) for r in rows) if rows else 1
# column widths from content (capped)
caps = [260, 220, 260, 150, 130, 90, 120, 120, 150, 120]
widths = []
for c in range(ncols):
cells = [r[c] if c < len(r) else "" for r in rows]
natural = max((font.getlength(s) for s in cells), default=60) + 2 * COL_PAD
cap = caps[c] if c < len(caps) else 200
widths.append(int(min(max(natural, 70), cap)))
total_w = sum(widths) + 2
title_h = 56
total_h = title_h + len(rows) * ROW_H + 2
img = Image.new("RGB", (total_w, total_h), ROW_BG_A)
d = ImageDraw.Draw(img)
# title bar
d.rectangle([0, 0, total_w, title_h], fill=TITLE_BG)
d.text((16, 16), title, font=font, fill=(255, 255, 255))
# header row
y = title_h
d.rectangle([0, y, total_w, y + ROW_H], fill=HEADER_BG)
x = 1
for c, w in enumerate(widths):
label = rows[0][c] if c < len(rows[0]) else ""
d.text((x + COL_PAD, y + 6), truncate(label, w - 2 * COL_PAD, font),
font=font, fill=HEADER_FG)
x += w
y += ROW_H
# data rows
for i, row in enumerate(rows[1:]):
bg = ROW_BG_A if i % 2 == 0 else ROW_BG_B
d.rectangle([0, y, total_w, y + ROW_H], fill=bg)
x = 1
for c, w in enumerate(widths):
val = row[c] if c < len(row) else ""
d.text((x + COL_PAD, y + 6), truncate(val, w - 2 * COL_PAD, font),
font=font, fill=TEXT)
x += w
y += ROW_H
# grid lines
x = 1
for w in widths:
d.line([x + w - 1, title_h, x + w - 1, total_h], fill=GRID, width=1)
x += w
for ry in range(title_h, total_h, ROW_H):
d.line([0, ry, total_w, ry], fill=GRID, width=1)
img.save(path)
print(f"wrote {path} ({total_w}x{total_h})")
def read_rows(path: Path, n: int) -> list[list[str]]:
import csv
with path.open(newline="", encoding="utf-8") as fh:
r = csv.reader(fh)
header = next(r)
rows = [header]
for i, row in enumerate(r):
if i >= n - 1:
break
rows.append(row)
return rows
def main() -> None:
args = sys.argv[1:]
messy = Path(args[0]) if len(args) > 0 else Path("messy_orders.csv")
clean = Path(args[1]) if len(args) > 1 else Path("clean.csv")
n = int(args[2]) if len(args) > 2 else N_ROWS_DEFAULT
font = load_font(15)
render(Path("before_messy.png"),
"BEFORE — messy_orders.csv (raw legacy export)",
read_rows(messy, n), font)
render(Path("after_clean.png"),
"AFTER — clean.csv (typed, deduplicated, ISO dates)",
read_rows(clean, n), font)
if __name__ == "__main__":
main()