tell / tools /chartcheck.py
dmth10's picture
Upload 53 files
fb4fcd0 verified
Raw History Blame Contribute Delete
6.22 kB
"""
ChartCheck: finds misleading tricks in charts.
Two layers that vote together:
1. RULE CHECKS on the axis numbers (works now, no training needed).
2. A CLASSIFIER you fine-tune on Misviz in notebooks/ (plug in when trained).
How axis numbers get in:
- For now: read_axis_ticks() uses OCR to pull the numbers along the left edge.
- Upgrade later: an axis-extraction model (the Misviz paper used DePlot).
"""
import os
# ---------- Layer 1: rule checks on extracted axis numbers ----------
def check_truncated_axis(y_ticks, chart_type="bar"):
"""Bar charts should start at zero. A y-axis starting far above zero exaggerates gaps."""
if not y_ticks or chart_type != "bar":
return None
low, high = min(y_ticks), max(y_ticks)
if low > 0 and high > 0 and low / high > 0.2:
return {
"trick": "truncated_axis",
"why": f"The y-axis starts at {low:g}, not 0, so small differences look huge.",
}
return None
def check_inverted_axis(y_ticks_top_to_bottom):
"""Numbers should get bigger going UP. If they grow going down, the chart is flipped."""
t = y_ticks_top_to_bottom
if t and len(t) >= 3 and all(a < b for a, b in zip(t, t[1:])):
return {
"trick": "inverted_axis",
"why": "The y-axis is upside down, so a rise looks like a fall.",
}
return None
def check_uneven_ticks(y_ticks):
"""Tick labels should be evenly spaced in value (e.g. 0, 10, 20, 30)."""
t = sorted(y_ticks or [])
if len(t) < 4:
return None
gaps = [b - a for a, b in zip(t, t[1:])]
if max(gaps) > 1.5 * min(gaps) and min(gaps) > 0:
return {
"trick": "uneven_ticks",
"why": "The axis steps are not equal, which stretches some parts of the chart.",
}
return None
def rule_checks(y_ticks_top_to_bottom, chart_type="bar"):
findings = []
for f in (
check_truncated_axis(y_ticks_top_to_bottom, chart_type),
check_inverted_axis(y_ticks_top_to_bottom),
check_uneven_ticks(y_ticks_top_to_bottom),
):
if f:
findings.append(f)
return findings
# ---------- Axis reading with OCR ----------
def read_axis_ticks(image):
"""
Very simple first version: OCR the left 18% of the chart and keep the numbers,
ordered top to bottom. Good enough for clean charts; improve later.
"""
try:
import numpy as np
from core.ocr import get_reader
_reader = get_reader()
w, h = image.size
strip = image.crop((0, 0, int(w * 0.18), h))
results = _reader.readtext(np.array(strip))
nums = []
for box, text, conf in results:
clean = text.replace(",", "").replace("%", "").replace("$", "").strip()
try:
y_center = sum(p[1] for p in box) / 4
nums.append((y_center, float(clean)))
except ValueError:
pass
nums.sort(key=lambda p: p[0]) # top to bottom
return [v for _, v in nums]
except Exception as e:
print("ChartCheck OCR error:", e)
return []
# ---------- Layer 2: trained classifier (you train this in notebooks/) ----------
MODEL_REPO = os.environ.get("CHARTCHECK_MODEL") # "your-hf-name/tell-chartcheck" or a local folder
_model, _cfg = None, None
def _pad_resize(img, size):
"""MUST match pad_resize in training/chart_train.py."""
from PIL import Image
img = img.convert("RGB")
w, h = img.size
s = max(w, h)
canvas = Image.new("RGB", (s, s), (255, 255, 255))
canvas.paste(img, ((s - w) // 2, (s - h) // 2))
return canvas.resize((size, size), Image.BILINEAR)
def _load():
global _model, _cfg
if _model is not None:
return
import json
import timm
from safetensors.torch import load_file
if os.path.isdir(MODEL_REPO):
cfg_path = os.path.join(MODEL_REPO, "config.json")
w_path = os.path.join(MODEL_REPO, "model.safetensors")
else:
from huggingface_hub import hf_hub_download
tok = os.environ.get("HF_TOKEN")
cfg_path = hf_hub_download(MODEL_REPO, "config.json", token=tok)
w_path = hf_hub_download(MODEL_REPO, "model.safetensors", token=tok)
_cfg = json.load(open(cfg_path))
m = timm.create_model(_cfg["arch"], pretrained=False, num_classes=len(_cfg["classes"]))
m.load_state_dict(load_file(w_path))
_model = m.eval()
def classifier_predict(image):
"""Returns [(label, probability)] for tricks above the threshold. [] if no model."""
if not MODEL_REPO:
return []
try:
import numpy as np
import torch
_load()
img = _pad_resize(image, _cfg["img_size"])
a = (np.asarray(img, dtype=np.float32) / 255.0 - _cfg["mean"]) / _cfg["std"]
x = torch.from_numpy(a.transpose(2, 0, 1)).float().unsqueeze(0)
with torch.no_grad():
probs = torch.softmax(_model(x), 1)[0].tolist()
return [(c, p) for c, p in zip(_cfg["classes"], probs)
if c != "none" and p >= _cfg["threshold"]]
except Exception as e:
print("ChartCheck model error:", e)
return []
def analyze(image, chart_type="bar"):
ticks = read_axis_ticks(image)
findings = rule_checks(ticks, chart_type)
model_hits = classifier_predict(image)
for label, p in model_hits:
if label not in {f["trick"] for f in findings}:
findings.append({"trick": label, "why": f"Flagged by the trained ChartCheck model ({p:.0%} sure)."})
return {
"tool": "ChartCheck",
"findings": findings,
"y_ticks": ticks,
"confidence": ("high (rules and model agree)" if findings and model_hits and ticks else
"high" if findings else
"nothing flagged" if (ticks or MODEL_REPO) else "low: couldn't read the axis"),
}
if __name__ == "__main__":
print(rule_checks([100, 99, 98, 97, 96, 95])) # truncated
print(rule_checks([0, 10, 20, 30, 40])) # inverted
print(rule_checks([100, 50, 20, 10, 0])) # uneven
print(rule_checks([40, 30, 20, 10, 0])) # honest