Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ 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.
- A result must never state a verdict. Keep the bands tied to the stricter human reference.
- 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.
- `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`.

Expand Down
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -275,11 +275,12 @@ The trained classifier, with Binoculars as an optional second opinion, runs as a
It has a web page and an MCP endpoint. It does not include Clef, which flagged too much real student
writing to be shown as a signal. Nothing leaves the machine.

![The detector page with one AI passage and one human passage](docs/screenshots/detector-app.png)
![The detector page scoring three passages](docs/screenshots/detector-app.png)

A result never says "AI" or "human". For each passage of up to 500 words it gives a band (none, weak,
moderate, strong) and the numbers behind it: how many human reference texts score at least as high, and
how many AI reference texts score at most as high. The band follows the stricter human reference.
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".

```sh
uv sync --group ml --group serve
Expand Down
Binary file modified docs/screenshots/detector-app.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
71 changes: 53 additions & 18 deletions src/detecteval/detector.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
"""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 never says "AI" or "human". For each passage and detector it reports how
often human reference text scores at least as high, and how often AI reference text scores at most as
high, and sorts that into a band by the stricter human reference available.
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.
"""
from __future__ import annotations

Expand All @@ -18,6 +19,8 @@
(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")]
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.",
"Formal school essays are flagged more often than other human writing; the private reference, when "
Expand Down Expand Up @@ -51,6 +54,29 @@ def band_for(human_share: float) -> tuple[str, str]:
raise ValueError("share must be at most 1")


def one_in(share: float) -> int:
"""A share as round odds: 0.034 -> 30, read "about 1 in 30"."""
if not 0 < share <= 1:
raise ValueError("share must be above 0 and at most 1")
return min(_ROUND_ODDS, key=lambda n: abs(n - 1 / share) / n)


def plain_reading(band: str, human_share: float, human_count: int, ai_share: float | None) -> str:
"""One or two sentences a non-specialist can act on."""
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"
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.")
if not ai_share:
return common + " No AI reference text scored this low."
if ai_share < 0.05:
return common + f" Few AI texts score this low (about 1 in {one_in(ai_share)})."
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:
"""One detector's reading of one passage against the public and, if present, private references."""
public = calibration["public"][detector][str(rung)]
Expand All @@ -60,27 +86,36 @@ def interpret(detector: str, rung: int, score: float, calibration: dict) -> dict
if private:
human["private"] = share_at_least(private, score)
counts["private"] = len(private)
band, meaning = band_for(max(human.values()))
return {"score": round(score, 4), "band": band, "meaning": meaning,
strictest = max(human.values())
band, meaning = band_for(strictest)
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),
"human_texts_scoring_at_least_this": human, "human_reference_sizes": counts,
"ai_texts_scoring_at_most_this": share_at_most(public["ai"], score),
"ai_reference_size": len(public["ai"])}
"ai_texts_scoring_at_most_this": ai_share, "ai_reference_size": len(public["ai"])}


def summarise(passages: list[dict]) -> dict:
"""Counts of passages per band for the main detector, and a one-line plain reading."""
bands = [passage["detectors"]["classifier-mirrors"]["band"] for passage in passages]
"""A label and one sentence for the whole text, from the main detector's reading of each passage."""
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}
total = len(bands)
if counts["strong"] + counts["moderate"] == 0:
reading = "No passage scores in a range that is unusual for human writing."
elif counts["strong"] == total:
reading = "Every passage scores in a range that 1% or fewer of human reference texts reach."
total, ai_like = len(bands), counts["strong"] + counts["moderate"]
if total == 1:
label, reading = readings[0]["label"], readings[0]["plain"]
elif ai_like == total:
label = LABELS["strong"] if counts["strong"] == total else LABELS["moderate"]
reading = f"All {total} passages read as AI-like."
elif ai_like:
verb = "reads" if ai_like == 1 else "read"
label, reading = "Mixed", f"{ai_like} of {total} passages {verb} as AI-like; the rest do not."
elif counts["weak"]:
label = "Mostly human-like"
verb = "leans" if counts["weak"] == 1 else "lean"
reading = f"{counts['weak']} of {total} passages {verb} slightly AI-like; none is clearly AI-like."
else:
unusual = counts["strong"] + counts["moderate"]
reading = (f"{unusual} of {total} passage{'s' if total != 1 else ''} score in a range that 5% or fewer "
"of human reference texts reach.")
return {"passages": total, "bands": counts, "reading": reading}
label, reading = LABELS["none"], f"All {total} passages read as human-like."
return {"passages": total, "bands": counts, "label": label, "reading": reading}


def build_result(passages: list[dict], truncated: bool, scores: dict[str, list[float] | None],
Expand Down
11 changes: 6 additions & 5 deletions src/detecteval/serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,11 +223,12 @@ 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. For each passage the result gives a band
(none, weak, moderate, strong) and the share of human reference texts that score at least as high,
for public human texts and, when available, one student's private pre-ChatGPT essays. It never says
"AI" or "human". Needs at least 63 words; under 150 words it is unreliable. Text a person wrote and
an AI then polished usually scores as AI. Set use_binoculars for a slower second opinion.
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.
"""
try:
return await detect(text, use_binoculars)
Expand Down
106 changes: 79 additions & 27 deletions src/detecteval/static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@
:root {
--paper: #eef1f4; --surface: #ffffff; --ink: #16202b; --muted: #5b6673; --rule: #d5dbe2;
--human: #2a78d6; --ai: #eb6834; --zone-5: #fbe3d6; --zone-1: #f5c3a8; --focus: #16202b;
--ai-1: #f3b48f; --ai-2: #eb6834; --ai-3: #b9401a;
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root {
--paper: #10151b; --surface: #171e26; --ink: #e6eaee; --muted: #9aa6b2; --rule: #2a333d;
--human: #5b9ae6; --ai: #f0875c; --zone-5: #3b2a22; --zone-1: #5a3524; --focus: #e6eaee;
--ai-1: #a8684a; --ai-2: #e0733f; --ai-3: #ff9a66;
color-scheme: dark;
}
}
Expand Down Expand Up @@ -47,15 +49,33 @@
.count { margin-left: auto; color: var(--muted); font-size: 0.875rem; }
.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; }
.reading { font-size: 1.25rem; line-height: 1.35; font-weight: 600; max-width: 36rem; margin: 0 0 0.25rem; }
.passage { border-top: 1px solid var(--rule); padding: 1.25rem 0 0.5rem; }
.passage h3 { font-size: 1rem; font-weight: 600; margin: 0; }
.start { color: var(--muted); font-size: 0.875rem; margin: 0.15rem 0 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; }
.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; }
.map-caption { color: var(--muted); font-size: 0.875rem; margin: 0 0 1rem; }
[data-band="none"] { --level: var(--human); }
[data-band="weak"] { --level: var(--ai-1); }
[data-band="moderate"] { --level: var(--ai-2); }
[data-band="strong"] { --level: var(--ai-3); }
.map a { background: var(--level); }
.passage { border-top: 1px solid var(--rule); padding: 1.25rem 0 0.75rem; scroll-margin-top: 1rem; }
.passage h3 { font-size: 0.9375rem; font-weight: 400; color: var(--muted); margin: 0 0 0.35rem; }
.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; }
.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; }
summary { cursor: pointer; color: var(--muted); font-size: 0.9375rem; width: fit-content; }
.start { color: var(--muted); font-size: 0.875rem; margin: 0.75rem 0 0.9rem; }
.detector { margin: 0 0 1.25rem; }
.detector-head { display: flex; flex-wrap: wrap; gap: 0.25rem 1rem; justify-content: space-between; }
.detector-name { font-weight: 600; }
.band { color: var(--muted); }
.band[data-band="moderate"], .band[data-band="strong"] { color: var(--ink); font-weight: 600; }
.detector-name { font-weight: 600; font-size: 0.9375rem; }
.track { position: relative; height: 2.6rem; margin: 0.5rem 0 0.2rem; }
.rail {
position: absolute; left: 0; right: 0; top: 0.55rem; height: 0.7rem; border-radius: 3px;
Expand Down Expand Up @@ -95,8 +115,13 @@ <h1>AI text detector</h1>
</form>

<section id="result" hidden aria-live="polite">
<h2>Reading</h2>
<h2>Result</h2>
<p class="label" id="label"></p>
<p class="reading" id="reading"></p>
<div id="overview" hidden>
<div class="map" id="map"></div>
<p class="map-caption">One block per passage, in order. Blue reads as human-like; deeper orange reads as more AI-like.</p>
</div>
<ul class="notes" id="notes"></ul>
<div id="passages"></div>
</section>
Expand All @@ -109,12 +134,6 @@ <h2>What this can and cannot tell you</h2>

<script>
const $ = (id) => document.getElementById(id);
const BAND_TEXT = {
none: "In the usual range for human writing",
weak: "Slightly unusual for human writing",
moderate: "Unusual for human writing",
strong: "Very unusual for human writing",
};
const DETECTOR_NAME = {"classifier-mirrors": "Trained classifier", "binoculars": "Second opinion (Binoculars)"};

// The track zooms in on the top of the human range, where the decision is made.
Expand Down Expand Up @@ -146,7 +165,19 @@ <h2>What this can and cannot tell you</h2>
return node;
}

function renderDetector(name, d) {
const LEVELS = ["none", "weak", "moderate", "strong"];

function meter(band) {
const level = LEVELS.indexOf(band);
return [
el("div", {class: "meter", "data-band": band, role: "img", "aria-label": `Level ${level + 1} of 4`},
...LEVELS.map((_, i) => el("span", i <= level ? {class: "on"} : {}))),
el("div", {class: "meter-ends"}, el("span", {}, "Human-like"), el("span", {}, "Strongly AI-like")),
];
}

// The exact numbers, for anyone who wants to check the label.
function renderNumbers(name, d) {
const below = (share) => 100 * (1 - share);
const shares = d.human_texts_scoring_at_least_this, sizes = d.human_reference_sizes;
const track = el("div", {class: "track", role: "img",
Expand All @@ -166,23 +197,44 @@ <h2>What this can and cannot tell you</h2>
facts.append(el("li", {}, el("span", {class: "key ai"}),
`${pct(d.ai_texts_scoring_at_most_this)} of ${d.ai_reference_size} AI texts score this low or lower.`));
return el("div", {class: "detector"},
el("div", {class: "detector-head"},
el("span", {class: "detector-name"}, DETECTOR_NAME[name] || name),
el("span", {class: "band", "data-band": d.band}, BAND_TEXT[d.band])),
el("div", {class: "detector-name"}, `${DETECTOR_NAME[name] || name}: where this passage falls among human texts`),
track, facts);
}

function renderPassage(p, many) {
const main = p.detectors["classifier-mirrors"], second = p.detectors["binoculars"];
const length = p.words <= p.scored_at_words ? `${p.words} words`
: `${p.words} words, scored on the first ${p.scored_at_words}`;
const parts = [
el("h3", {}, many ? `Passage ${p.index}, ${length}` : length),
el("p", {class: "passage-label", "data-band": main.band}, el("span", {class: "dot"}), main.label),
el("p", {class: "plain"}, main.plain),
...meter(main.band),
];
if (second) {
const agrees = (second.band === "none") === (main.band === "none");
parts.push(el("p", {class: "second"}, "Second opinion: ", el("strong", {}, second.label),
agrees ? ", which agrees." : ", which disagrees. Treat this passage as uncertain."));
}
parts.push(el("details", {},
el("summary", {}, "Show the numbers"),
el("p", {class: "start"}, `Begins: “${p.start}…”`),
...Object.entries(p.detectors).map(([name, d]) => renderNumbers(name, d))));
return el("div", {class: "passage", id: `passage-${p.index}`}, ...parts);
}

function render(result) {
const many = result.passages.length > 1;
$("label").textContent = result.summary.label;
$("reading").textContent = result.summary.reading;
$("notes").replaceChildren(...result.notes.map((note) => el("li", {}, note)));
$("passages").replaceChildren(...result.passages.map((p) => {
const length = p.words <= p.scored_at_words ? `${p.words} words`
: `${p.words} words, scored on the first ${p.scored_at_words}`;
return el("div", {class: "passage"},
el("h3", {}, result.passages.length > 1 ? `Passage ${p.index}, ${length}` : `${length}`),
el("p", {class: "start"}, `Begins: “${p.start}…”`),
...Object.entries(p.detectors).map(([name, d]) => renderDetector(name, d)));
$("overview").hidden = !many;
$("map").replaceChildren(...result.passages.map((p) => {
const d = p.detectors["classifier-mirrors"];
return el("a", {href: `#passage-${p.index}`, "data-band": d.band, title: `Passage ${p.index}: ${d.label}`,
"aria-label": `Passage ${p.index}: ${d.label}`});
}));
$("notes").replaceChildren(...result.notes.map((note) => el("li", {}, note)));
$("passages").replaceChildren(...result.passages.map((p) => renderPassage(p, many)));
$("limits").replaceChildren(...result.limits.map((limit) => el("li", {}, limit)));
$("result").hidden = false;
}
Expand Down
Loading
Loading