diff --git a/AGENTS.md b/AGENTS.md index 7bab0c0..63c11ba 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,8 +66,10 @@ registered in the MCP hub as the lazy HTTP backend `ai-detector` (tools prefixed - After changing dependencies, redeploy with the launcher's `deploy` command so the build step runs. - The service must stay light: models load in the worker on demand and the worker is stopped when idle. This machine has restarted from memory exhaustion before; do not make the models resident. -- Labels describe the score ("AI-like"), never the author ("written by AI"), and every label comes with - how often human writing scores that high. Keep the labels tied to the stricter human reference. +- Labels describe the score ("AI-like"), never the author ("written by AI"), and every result comes with + how often human writing scores that high. The percentage is an equal-prior likelihood from + `calibration.probability_curve`; keep the private human reference in that curve when it exists, and + recheck the held-out calibration figures in the README if the classifier or reference scores change. - `results/calibration.json` is derived from committed scores; rebuild it with `calibration` whenever the long-set scores or the classifier change. The private reference lives in `RAW_DATA_DIR/private`. diff --git a/README.md b/README.md index ef6342d..4260bc7 100644 --- a/README.md +++ b/README.md @@ -277,10 +277,18 @@ writing to be shown as a signal. Nothing leaves the machine. ![The detector page scoring three passages](docs/screenshots/detector-app.png) -For each passage of up to 500 words the result gives a label (Human-like, Slightly AI-like, AI-like, -Strongly AI-like) and one sentence saying how often human writing scores that high, such as "Only about -1 in 30 human texts score this high." The label describes the score, not the author, and it follows the -stricter human reference. The exact rates are one click away under "Show the numbers". +For each passage of up to 500 words the result gives an AI likelihood from 1% to 99%, a label that follows +it (Human-like under 30%, Slightly AI-like, AI-like from 60%, Strongly AI-like from 85%) and one sentence +saying how often human writing scores that high, such as "Only about 1 in 30 human texts score this +high." The whole text gets the average, weighted by passage length. + +The likelihood is the chance a passage is AI-written if AI and human text were equally likely +beforehand. It is read off a never-decreasing curve fitted to the reference scores, with the private +human reference, when present, counting as much as the public one. Fitted on the calibration half and +checked on the test half at 300 words, passages given 85% or more were AI-written 99% of the time, those +given 60 to 85% were 72%, 30 to 60% were 39%, and under 30% were 3%. Where most text is human-written the +real chance is lower than the number shown. The label describes the score, not the author, and the exact +rates are one click away under "Show the numbers". ```sh uv sync --group ml --group serve diff --git a/docs/screenshots/detector-app.png b/docs/screenshots/detector-app.png index 4cd8551..424fd6d 100644 Binary files a/docs/screenshots/detector-app.png and b/docs/screenshots/detector-app.png differ diff --git a/src/detecteval/calibration.py b/src/detecteval/calibration.py index c747ecf..74db7c5 100644 --- a/src/detecteval/calibration.py +++ b/src/detecteval/calibration.py @@ -77,6 +77,40 @@ def share_at_most(reference: list[float], score: float) -> float | None: return bisect.bisect_right(reference, score) / len(reference) +def probability_curve(human_sets: list[list[float]], ai: list[float]) -> tuple[list[float], list[float]]: + """Score-to-likelihood curve: an isotonic (never decreasing) fit of "is AI" against score. + + Human and AI text carry equal total weight, so the result is the chance a text is AI-written when + the two were equally likely beforehand. Several human reference sets share the human weight + equally, so a small set of harder human texts counts as much as a large set of easier ones. + Returns (scores, likelihoods) to interpolate between.""" + points = [(score, 1.0, 0.5 / len(ai)) for score in ai] + for reference in human_sets: + points += [(score, 0.0, 0.5 / len(human_sets) / len(reference)) for score in reference] + points.sort() + blocks: list[list[float]] = [] # [weighted score sum, weighted label sum, weight] + for score, label, weight in points: + blocks.append([score * weight, label * weight, weight]) + while len(blocks) > 1 and blocks[-2][1] / blocks[-2][2] >= blocks[-1][1] / blocks[-1][2]: + last = blocks.pop() + blocks[-1] = [a + b for a, b in zip(blocks[-1], last, strict=True)] + return [block[0] / block[2] for block in blocks], [block[1] / block[2] for block in blocks] + + +def likelihood(curve: tuple[list[float], list[float]], score: float, floor: float = 0.01) -> float: + """Likelihood for one score, interpolated along the curve and kept away from 0 and 1.""" + scores, values = curve + if score <= scores[0]: + value = values[0] + elif score >= scores[-1]: + value = values[-1] + else: + right = bisect.bisect_right(scores, score) + span = scores[right] - scores[right - 1] + value = values[right - 1] + (values[right] - values[right - 1]) * (score - scores[right - 1]) / span + return min(1 - floor, max(floor, value)) + + def main() -> None: parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("--private", action="store_true", help="also write the private human reference") diff --git a/src/detecteval/detector.py b/src/detecteval/detector.py index b9c1e7c..9a9387e 100644 --- a/src/detecteval/detector.py +++ b/src/detecteval/detector.py @@ -1,28 +1,29 @@ """Turn a text into passages, and raw detector scores into a cautious, readable result. This module holds the logic shared by the web app and the MCP server and needs neither PyTorch nor a -web framework. A result describes the score, not the author: a label from "Human-like" to "Strongly -AI-like", and one sentence saying how often human writing scores that high ("about 1 in 30"). The -label follows the stricter human reference available. The exact rates stay in the result for anyone -who wants them. +web framework. A result describes the score, not the author. Each passage gets an AI likelihood from +1% to 99%: the chance it is AI-written if AI and human text were equally likely beforehand, read off a +curve fitted to the reference scores. A label from "Human-like" to "Strongly AI-like" follows that +number, and one sentence says how often human writing scores as high ("about 1 in 30"), using the +stricter human reference. When a private human reference is present it shares the human weight +equally with the public one, which lowers the likelihood for writing like the private texts. """ from __future__ import annotations from . import config -from .calibration import share_at_least, share_at_most +from .calibration import likelihood, probability_curve, share_at_least, share_at_most from .textprep import normalise, rung_text, strip_markdown, trim_words MAX_PASSAGES = 12 MIN_WORDS = int(config.RUNGS[0] * config.RUNG_FILL) -# Bands by the share of human reference texts that score at least this high. -BANDS = [(0.01, "strong", "1% or fewer of human reference texts score this high"), - (0.05, "moderate", "5% or fewer of human reference texts score this high"), - (0.20, "weak", "20% or fewer of human reference texts score this high"), - (1.01, "none", "human reference texts often score this high")] +# Bands by AI likelihood: below 30%, 30 to 60%, 60 to 85%, and 85% or more. +BANDS = [(0.30, "none"), (0.60, "weak"), (0.85, "moderate"), (1.01, "strong")] LABELS = {"none": "Human-like", "weak": "Slightly AI-like", "moderate": "AI-like", "strong": "Strongly AI-like"} _ROUND_ODDS = [2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 25, 30, 40, 50, 60, 80, 100, 150, 200, 250, 300, 400, 500, 1000] LIMITS = [ "This is a score with error rates, not proof. Do not use it on its own to accuse anyone.", + "The percentage assumes AI and human text were equally likely beforehand. If most of what you check is " + "human-written, the real chance is lower than the number shown.", "Formal school essays are flagged more often than other human writing; the private reference, when " "present, comes from one student's pre-ChatGPT work.", "Text a person wrote and an AI then polished usually scores as AI.", @@ -47,11 +48,11 @@ def split_passages(text: str) -> tuple[list[dict], bool]: return passages, len(words) - start >= MIN_WORDS -def band_for(human_share: float) -> tuple[str, str]: - for limit, name, meaning in BANDS: - if human_share <= limit: - return name, meaning - raise ValueError("share must be at most 1") +def band_for(ai_likelihood: float) -> str: + for limit, name in BANDS: + if ai_likelihood < limit: + return name + raise ValueError("likelihood must be at most 1") def one_in(share: float) -> int: @@ -66,7 +67,7 @@ def plain_reading(band: str, human_share: float, human_count: int, ai_share: flo if human_share == 0: return f"None of the {human_count} human reference texts scored this high." if band != "none": - prefix = "Only about" if band in ("moderate", "strong") else "About" + prefix = "Only about" if human_share <= 0.05 else "About" return f"{prefix} 1 in {one_in(human_share)} human texts score this high." common = ("More than half of human texts score this high." if human_share >= 0.5 else f"About 1 in {one_in(human_share)} human texts score this high, which is common.") @@ -77,7 +78,14 @@ def plain_reading(band: str, human_share: float, human_count: int, ai_share: flo return common + f" About 1 in {one_in(ai_share)} AI texts score this low too, so this does not rule AI out." -def interpret(detector: str, rung: int, score: float, calibration: dict) -> dict: +def curves_for(detector: str, rung: int, calibration: dict) -> tuple[list[float], list[float]]: + """The score-to-likelihood curve for one detector and length, from every human reference available.""" + public = calibration["public"][detector][str(rung)] + private = (calibration.get("private") or {}).get(detector, {}).get(str(rung), {}).get("human") + return probability_curve([public["human"]] + ([private] if private else []), public["ai"]) + + +def interpret(detector: str, rung: int, score: float, calibration: dict, curve=None) -> dict: """One detector's reading of one passage against the public and, if present, private references.""" public = calibration["public"][detector][str(rung)] human = {"public": share_at_least(public["human"], score)} @@ -86,21 +94,25 @@ def interpret(detector: str, rung: int, score: float, calibration: dict) -> dict if private: human["private"] = share_at_least(private, score) counts["private"] = len(private) - strictest = max(human.values()) - band, meaning = band_for(strictest) + ai_likelihood = likelihood(curve or curves_for(detector, rung, calibration), score) + band = band_for(ai_likelihood) ai_share = share_at_most(public["ai"], score) - return {"label": LABELS[band], "plain": plain_reading(band, strictest, sum(counts.values()), ai_share), - "band": band, "meaning": meaning, "score": round(score, 4), + return {"ai_likelihood_percent": round(100 * ai_likelihood), "label": LABELS[band], + "plain": plain_reading(band, max(human.values()), sum(counts.values()), ai_share), + "band": band, "score": round(score, 4), "human_texts_scoring_at_least_this": human, "human_reference_sizes": counts, "ai_texts_scoring_at_most_this": ai_share, "ai_reference_size": len(public["ai"])} def summarise(passages: list[dict]) -> dict: - """A label and one sentence for the whole text, from the main detector's reading of each passage.""" + """A likelihood, a label and one sentence for the whole text, from the main detector's passage readings.""" readings = [passage["detectors"]["classifier-mirrors"] for passage in passages] bands = [reading["band"] for reading in readings] - counts = {name: bands.count(name) for _, name, _ in BANDS} + counts = {name: bands.count(name) for _, name in BANDS} total, ai_like = len(bands), counts["strong"] + counts["moderate"] + words = [passage.get("words", 1) for passage in passages] + weighted = sum(reading["ai_likelihood_percent"] * count for reading, count in zip(readings, words, strict=True)) + percent = round(weighted / sum(words)) # longer passages count for more if total == 1: label, reading = readings[0]["label"], readings[0]["plain"] elif ai_like == total: @@ -110,21 +122,28 @@ def summarise(passages: list[dict]) -> dict: verb = "reads" if ai_like == 1 else "read" label, reading = "Mixed", f"{ai_like} of {total} passages {verb} as AI-like." elif counts["weak"]: - label = "Mostly human-like" verb = "leans" if counts["weak"] == 1 else "lean" + label = "Mostly human-like" reading = f"{counts['weak']} of {total} passages {verb} slightly AI-like; none is clearly AI-like." else: label, reading = LABELS["none"], f"All {total} passages read as human-like." - return {"passages": total, "bands": counts, "label": label, "reading": reading} + return {"ai_likelihood_percent": percent, "passages": total, "bands": counts, "label": label, + "reading": reading} def build_result(passages: list[dict], truncated: bool, scores: dict[str, list[float] | None], calibration: dict, notes: list[str] | None = None) -> dict: """Assemble the full response from passages and per-detector score lists (None = detector not run).""" - out_passages = [] + out_passages, curves = [], {} for position, passage in enumerate(passages): - detectors = {name: interpret(name, passage["rung"], values[position], calibration) - for name, values in scores.items() if values is not None} + detectors = {} + for name, values in scores.items(): + if values is None: + continue + key = (name, passage["rung"]) + if key not in curves: + curves[key] = curves_for(name, passage["rung"], calibration) + detectors[name] = interpret(name, passage["rung"], values[position], calibration, curves[key]) out_passages.append({"index": passage["index"], "words": passage["words"], "scored_at_words": passage["rung"], "start": passage["text"][:90], "detectors": detectors}) diff --git a/src/detecteval/serve.py b/src/detecteval/serve.py index 10ebd0d..8a98ec9 100644 --- a/src/detecteval/serve.py +++ b/src/detecteval/serve.py @@ -57,7 +57,9 @@ "models. Optional second opinion; weak on short text from current models.", }, "measured": "At 300 words the classifier caught 91% of AI text with the bar set to flag 5% of public " - "human texts. On one student's private pre-ChatGPT essays that same bar flagged 8%.", + "human texts. On one student's private pre-ChatGPT essays that same bar flagged 8%. On " + "held-out texts, passages given an AI likelihood of 85% or more were AI-written about 98% of " + "the time, and those given under 30% about 3% of the time.", "limits": detector.LIMITS, } @@ -223,12 +225,14 @@ async def api_detect(request: Request) -> JSONResponse: async def detect_ai_text(text: str, use_binoculars: bool = False) -> dict: """Score how AI-like a piece of English prose is. Runs locally; the text is not sent anywhere. - The text is cut into passages of up to 500 words. ``summary.label`` and ``summary.reading`` describe the - whole text; each passage has a ``label`` (Human-like, Slightly AI-like, AI-like, Strongly AI-like) and - a ``plain`` sentence saying how often human writing scores that high, for example "Only about 1 in 30 - human texts score this high." Labels describe the score, not the author: report them with that - sentence and never as proof. Needs at least 63 words; under 150 words it is unreliable. Text a person - wrote and an AI then polished usually scores as AI-like. Set use_binoculars for a slower second opinion. + Returns ``summary.ai_likelihood_percent`` (1 to 99) with ``summary.label`` and ``summary.reading`` for + the whole text, and the same for each passage of up to 500 words, plus a ``plain`` sentence saying how + often human writing scores that high. The percentage is the chance the text is AI-written if AI and + human text were equally likely beforehand; where most text is human-written the real chance is lower. + On held-out texts, passages given 85% or more were AI-written about 98% of the time and those under + 30% about 3% of the time. Report the number with that caveat and never as proof. Needs at least 63 + words; under 150 words it is unreliable. Text a person wrote and an AI then polished usually scores + as AI-like. Set use_binoculars for a slower second opinion. """ try: return await detect(text, use_binoculars) diff --git a/src/detecteval/static/index.html b/src/detecteval/static/index.html index 8e51da2..86f0d9f 100644 --- a/src/detecteval/static/index.html +++ b/src/detecteval/static/index.html @@ -50,7 +50,10 @@ .status { color: var(--muted); font-size: 0.875rem; min-height: 1.4rem; margin-top: 0.6rem; } .error { color: var(--ink); background: var(--zone-5); border-left: 3px solid var(--ai); padding: 0.7rem 0.9rem; } .verdict { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0.35rem 1rem; margin: 0 0 0.35rem; } - .label { font-size: 1.75rem; line-height: 1.2; font-weight: 600; letter-spacing: -0.01em; margin: 0; } + .headline { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0.2rem 0.9rem; margin: 0 0 0.3rem; } + .number { font-size: 3.25rem; line-height: 1; font-weight: 600; letter-spacing: -0.02em; } + .label { font-size: 1.5rem; line-height: 1.2; font-weight: 600; letter-spacing: -0.01em; } + .caption { color: var(--muted); font-size: 0.875rem; margin: 0 0 0.6rem; } .reading { font-size: 1.0625rem; max-width: 36rem; margin: 0 0 0.9rem; } .map { display: flex; gap: 4px; margin: 0 0 0.4rem; max-width: 36rem; } .map a { flex: 1; height: 1.1rem; border-radius: 3px; } @@ -65,10 +68,10 @@ .passage-label { font-size: 1.25rem; font-weight: 600; margin: 0 0 0.15rem; display: flex; align-items: center; gap: 0.55rem; } .dot { flex: none; width: 0.8rem; height: 0.8rem; border-radius: 50%; background: var(--level); } .plain { margin: 0 0 0.6rem; max-width: 36rem; } - .meter { display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px; max-width: 26rem; margin: 0.5rem 0 0.2rem; } - .meter span { height: 0.5rem; border-radius: 3px; background: var(--rule); } - .meter span.on { background: var(--level); } - .meter-ends { display: flex; justify-content: space-between; max-width: 26rem; color: var(--muted); font-size: 0.8125rem; margin-bottom: 0.6rem; } + .passage-number { font-variant-numeric: tabular-nums; min-width: 3.2rem; } + .bar { position: relative; height: 0.6rem; max-width: 26rem; border-radius: 3px; background: var(--rule); margin: 0.5rem 0 0.2rem; overflow: hidden; } + .bar span { position: absolute; left: 0; top: 0; bottom: 0; border-radius: 3px; background: var(--level); } + .bar-ends { display: flex; justify-content: space-between; max-width: 26rem; color: var(--muted); font-size: 0.8125rem; margin-bottom: 0.6rem; } .second { color: var(--muted); margin: 0 0 0.6rem; max-width: 36rem; } .second strong { color: var(--ink); font-weight: 600; } details { margin: 0.35rem 0 0.5rem; } @@ -100,8 +103,8 @@

AI text detector

-

Paste writing to see how AI-like it scores, and how often real human writing scores the - same. Everything runs on this machine; the text is not sent anywhere.

+

Paste writing to get an AI likelihood from 1% to 99%, and how often real human writing + scores the same. Everything runs on this machine; the text is not sent anywhere.

@@ -116,7 +119,8 @@

AI text detector