Download tools/statcheck.py from dmth10/tell: direct link, hf CLI and curl.
- Browser
- Download file 6.18 kB
-
https://huggingface.co/spaces/dmth10/tell/resolve/main/tools/statcheck.py
- Command line
-
hf download hf://spaces/dmth10/tell/tools/statcheck.py
-
curl -L -o statcheck.py https://huggingface.co/spaces/dmth10/tell/resolve/main/tools/statcheck.py
6.18 kB
| """ | |
| StatCheck: finds number tricks in headlines, captions, and posts. | |
| Two layers: | |
| 1. A language model pulls out every numerical claim as strict JSON (optional, | |
| needs ANTHROPIC_API_KEY). If no key is set, StatCheck still runs on rules. | |
| 2. Rule checks are the final judge. They decide which tricks are flagged. | |
| Tricks it catches: | |
| - relative_risk_no_baseline: "doubles your risk" with no starting number | |
| - big_percent_small_base: "up 400%!" where the base is tiny or unstated | |
| - missing_denominator: "3,000 people got sick" with no "out of" | |
| - correlation_as_cause: a study or "link" described with cause words | |
| """ | |
| import json | |
| import os | |
| import re | |
| # ---------- Rule patterns ---------- | |
| RELATIVE_WORDS = re.compile( | |
| r"\b(doubles?|doubled|triples?|tripled|quadruples?|halves|halved|" | |
| r"\d+(\.\d+)?\s*(x|times)\s+(more|less|higher|lower|as)\b|" | |
| r"\d+(\.\d+)?\s*%\s*(higher|lower|more|less|increase|decrease|greater)\b[^.]*\brisk|" | |
| r"(raises?|increases?|cuts?|lowers?|reduces?)\s+(your\s+)?risk)", | |
| re.IGNORECASE, | |
| ) | |
| BASELINE_WORDS = re.compile( | |
| r"\b(\d+\s+in\s+[\d,]+|\d+\s+out\s+of\s+[\d,]+|per\s+[\d,]+|" | |
| r"from\s+\d+(\.\d+)?\s*%?\s+to\s+\d+(\.\d+)?\s*%?|baseline|absolute\s+risk)\b", | |
| re.IGNORECASE, | |
| ) | |
| # 3+ digit percent, but not "100% of people" (that's a share, not a jump). Values over 100% | |
| # can only be changes, so they always count; exactly 100% counts only next to change words. | |
| BIG_PERCENT = re.compile(r"\b(\d{3,})\s*%(?!\s+of\b)", re.IGNORECASE) | |
| CHANGE_WORDS = re.compile(r"\b(increase|rise|rose|jump|spike|surge|up|more|growth|grew|higher)\w*", re.IGNORECASE) | |
| COUNT_CLAIM = re.compile( | |
| r"\b([\d,]{3,}|\d+(\.\d+)?\s*(thousand|million))\s+" | |
| r"(people|students|kids|teens|cases|users|deaths|patients)\b", | |
| re.IGNORECASE, | |
| ) | |
| DENOMINATOR = re.compile(r"\b(out\s+of|of\s+(the|all)|per\s+[\d,]+|%)", re.IGNORECASE) | |
| STUDY_WORDS = re.compile(r"\b(study|studies|research|survey|data|scientists)\b", re.IGNORECASE) | |
| CAUSE_WORDS = re.compile( | |
| r"\b(causes?|caused|makes?\s+you|leads?\s+to|turns?\s+you|" | |
| r"is\s+why|proves?|will\s+give\s+you)\b", | |
| re.IGNORECASE, | |
| ) | |
| def _sentences(text): | |
| parts = re.split(r"(?<=[.!?])\s+|\n+", text.strip()) | |
| return [p for p in parts if p] | |
| def rule_checks(text): | |
| """Return a list of findings. Each finding names a trick and quotes the line.""" | |
| findings = [] | |
| for s in _sentences(text): | |
| if RELATIVE_WORDS.search(s) and not BASELINE_WORDS.search(text): | |
| findings.append({ | |
| "trick": "relative_risk_no_baseline", | |
| "quote": s, | |
| "why": "It says how much the risk changed, but never how big the risk was to begin with.", | |
| }) | |
| m = BIG_PERCENT.search(s) | |
| if m and (int(m.group(1)) > 100 or CHANGE_WORDS.search(s)) and not BASELINE_WORDS.search(s): | |
| findings.append({ | |
| "trick": "big_percent_small_base", | |
| "quote": s, | |
| "why": f"A {m.group(1)}% jump sounds huge, but it can come from a tiny starting number.", | |
| }) | |
| if COUNT_CLAIM.search(s) and not DENOMINATOR.search(s): | |
| findings.append({ | |
| "trick": "missing_denominator", | |
| "quote": s, | |
| "why": "A raw count with no 'out of how many' can't tell you if this is common or rare.", | |
| }) | |
| if STUDY_WORDS.search(s) and CAUSE_WORDS.search(s): | |
| findings.append({ | |
| "trick": "correlation_as_cause", | |
| "quote": s, | |
| "why": "Studies usually find a link. Words like 'causes' claim more than a link proves.", | |
| }) | |
| return findings | |
| # ---------- Optional language model layer ---------- | |
| EXTRACT_PROMPT = """Extract every numerical claim from the text below. | |
| Return ONLY JSON in this exact shape, no other words: | |
| {"claims": [{"quote": "...", "relative_change": "e.g. doubles / 2x / +40% or null", | |
| "baseline_before": "e.g. 1 in 10,000 or null", "baseline_after": "or null"}]} | |
| Only fill baseline fields with numbers that are literally in the text. Never invent numbers. | |
| TEXT: | |
| """ | |
| def llm_extract(text): | |
| """Ask a language model for structured claims. Returns [] if no API key.""" | |
| key = os.environ.get("ANTHROPIC_API_KEY") | |
| if not key: | |
| return [] | |
| try: | |
| import anthropic | |
| client = anthropic.Anthropic(api_key=key) | |
| msg = client.messages.create( | |
| model=os.environ.get("TELL_LLM_MODEL", "claude-haiku-5-5"), | |
| max_tokens=800, | |
| messages=[{"role": "user", "content": EXTRACT_PROMPT + text}], | |
| ) | |
| raw = msg.content[0].text | |
| raw = raw[raw.find("{"): raw.rfind("}") + 1] | |
| return json.loads(raw).get("claims", []) | |
| except Exception as e: # never let the LLM crash the app | |
| print("StatCheck LLM error:", e) | |
| return [] | |
| def absolute_view(claims): | |
| """Turn 'before/after' baselines the text actually gave into a plain sentence.""" | |
| lines = [] | |
| for c in claims: | |
| b, a = c.get("baseline_before"), c.get("baseline_after") | |
| if b and a: | |
| lines.append(f"In real numbers: {b} becomes {a}.") | |
| return lines | |
| def analyze(text): | |
| """Main entry point used by app.py.""" | |
| if not text or not text.strip(): | |
| return {"tool": "StatCheck", "findings": [], "confidence": "n/a", "notes": ["No text given."]} | |
| findings = rule_checks(text) | |
| claims = llm_extract(text) | |
| notes = absolute_view(claims) | |
| return { | |
| "tool": "StatCheck", | |
| "findings": findings, | |
| "claims": claims, | |
| "notes": notes, | |
| "confidence": "high" if findings else "nothing flagged", | |
| } | |
| if __name__ == "__main__": | |
| tests = [ | |
| "New study: energy drinks double your risk of heart problems!", | |
| "Scooter injuries are up 400% this year.", | |
| "3,000 students said they hate the new schedule.", | |
| "Research shows that social media causes depression in teens.", | |
| "Risk went from 1 in 10,000 to 2 in 10,000 after the change.", | |
| ] | |
| for t in tests: | |
| print(t) | |
| for f in analyze(t)["findings"]: | |
| print(" ->", f["trick"]) | |