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
19 changes: 19 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ classifier fine-tuned on examples. It is an evaluation harness, not a detector p
- Local detectors: `binoculars`; `generate_mirrors`, `train_data`, `train_classifier`, `classify`.
- Comparison of everything on held-out halves: `compare`, `compare_report`.
- Private writing: `private_eval` scores documents listed in `RAW_DATA_DIR/private/manifest.jsonl`.
- Detector service: `calibration` (reference scores), `detector` (passages and bands, no PyTorch),
`worker` (model process), `serve` (web page, JSON API and MCP endpoint), `static/index.html`.
- `data/` — both evaluation sets, the texts generated for them, and the training mirrors (committed).
- `results/` — scores per detector, summaries, reports and figures (committed deliverables).
- Raw third-party downloads and trained model weights live outside Git in `RAW_DATA_DIR` (default
Expand Down Expand Up @@ -51,6 +53,23 @@ classifier fine-tuned on examples. It is an evaluation harness, not a detector p
gigabytes of free memory. Run one at a time. CI does not install that group, so modules that need
PyTorch import it inside `main()` and tests cover only the NumPy parts.

## The deployed detector

The service is deployed on the Mac mini through the app launcher as `ai-detector`
(https://app-ai-detector.chenagent.com, owner sign-in) from [launcher.json](launcher.json), and is
registered in the MCP hub as the lazy HTTP backend `ai-detector` (tools prefixed `ai_detector__`).

- It runs from this canonical checkout with its own environment at
`/Volumes/SamsungSSD1/tools/ai-text-detection/venv`, so `ci/run.sh` and `uv sync` here do not disturb
it. Code changes take effect on restart: `node src/cli.mjs restart ai-detector` in the launcher checkout.
Keep the checkout on `main` when not actively working, or develop service changes in a worktree.
- 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.
- `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`.

## Setup and validation

```sh
Expand Down
37 changes: 36 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,38 @@ Verified here: the pipeline ran through a private MCP gateway in front of Cloudf
Pointing `MCP_URL` directly at `https://mcp.cloudflare.com/mcp` uses the same tool and should behave the
same, but that path was not run.

## Use the detector: web app and MCP server

The trained classifier, with Binoculars as an optional second opinion, runs as a small local service.
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)

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.

```sh
uv sync --group ml --group serve
# put the trained classifier in RAW_DATA_DIR/models/mirrors (release v0.3.0, see Artifacts)
uv run python -m detecteval.calibration # reference scores from the committed results
uv run python -m detecteval.serve # http://127.0.0.1:8941
```

- **Web page:** `http://127.0.0.1:8941/`. JSON API: `POST /api/detect` with `{"text": "...", "binoculars": false}`.
- **MCP:** streamable HTTP at `http://127.0.0.1:8941/mcp`, tools `detect_ai_text` and
`about_ai_text_detector`. The endpoint answers only requests addressed to localhost, so a reverse proxy
that serves the page under another hostname does not expose it.
- **Memory:** the service itself is about 50 MB. The models run in a worker process that starts on the
first request (10 to 30 seconds) and is stopped after five idle minutes. The classifier needs about
0.5 GB; Binoculars adds about 3 GB and is skipped when the machine is short of memory.
- **A harder human reference:** if you have run the private-writing test, `python -m detecteval.calibration
--private` adds your own certainly-human documents as a second reference. It stays outside the repository.

[launcher.json](launcher.json) is the manifest this project's own deployment uses with a personal app
launcher; its paths are specific to that machine and are not needed to run the service.

## Testing your own writing

Private documents written before language models were common are the cleanest test of false accusations:
Expand Down Expand Up @@ -304,6 +336,7 @@ Binoculars and the classifier run locally: about 30 minutes and 60 minutes on an
| Scores per detector | [results/scores/](results/scores/), [results/scores_long/](results/scores_long/), [results/detectors/](results/detectors/) | JSON Lines | `score`, `score_long`, `binoculars`, `classify` |
| Reports | [results/report.md](results/report.md), [results/comparison.md](results/comparison.md), [results/private_writing.md](results/private_writing.md), with `.json` twins | Markdown, JSON | `report`, `compare`, `private_eval report` |
| Figures | [results/figures/](results/figures/) | PNG | `report`, `compare` |
| Reference scores for the detector app | [results/calibration.json](results/calibration.json) | JSON | `calibration` |
| Trained classifiers (2 × 306 MB) | [release v0.3.0](https://github.com/ichen27/ai-text-detection-eval/releases/tag/v0.3.0) | Hugging Face model folders, gzipped tar | Extract into `RAW_DATA_DIR/models/`, then `python -m detecteval.classify raid mirrors`; or retrain with `train_classifier` |

SHA-256 of the release files: `classifier-raid.tar.gz` `81ae99d8aa214fe596a5799cac1b5a19c8f67da5989284e9639a3431d535a9f5`,
Expand All @@ -322,7 +355,9 @@ results/ report.md, summary.json first study
private_writing.md, .json false accusations on private writing (aggregates only)
scores/, scores_long/, detectors/ raw scores per detector
figures/
tests/ unit tests for metrics, text preparation, splits and detector statistics
launcher.json deployment manifest for the detector app (machine-specific)
docs/screenshots/ the detector page
tests/ unit tests for metrics, text preparation, splits, detector statistics and result bands
ci/run.sh single lint-and-test entry point used locally and in CI
```

Expand Down
Binary file added 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.
19 changes: 19 additions & 0 deletions launcher.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"id": "ai-detector",
"name": "AI Text Detector",
"description": "Scores how AI-like a text is and how often human writing scores the same. Runs locally.",
"icon": "AI",
"color": "#d9e4f2",
"tags": ["tools", "writing"],
"favorite": false,
"cwd": "/Volumes/SamsungSSD1/code/ai-text-detection-eval",
"build": [
["/usr/bin/env", "UV_PROJECT_ENVIRONMENT=/Volumes/SamsungSSD1/tools/ai-text-detection/venv",
"/Users/chenagent/.local/bin/uv", "sync", "--locked", "--no-dev", "--group", "ml", "--group", "serve"]
],
"command": ["/Volumes/SamsungSSD1/tools/ai-text-detection/venv/bin/python", "-m", "detecteval.serve"],
"port": 8941,
"healthPath": "/health",
"runtime": "native",
"envFile": "/Volumes/SamsungSSD1/tools/ai-text-detection/app.env"
}
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ dependencies = ["numpy>=1.26", "matplotlib>=3.8", "duckdb>=1.1"]
dev = ["pytest>=8", "ruff>=0.6"]
# Local detectors (Binoculars and the trained classifier). Not needed for the tests or the report.
ml = ["torch>=2.6", "transformers>=4.48", "accelerate>=1.2"]
# The detector web app and MCP server. Needs the ml group as well, for the model worker.
serve = ["starlette>=0.40", "uvicorn>=0.30", "mcp>=2"]

[build-system]
requires = ["hatchling"]
Expand Down
1 change: 1 addition & 0 deletions results/calibration.json

Large diffs are not rendered by default.

92 changes: 92 additions & 0 deletions src/detecteval/calibration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
"""Reference score distributions that turn a raw detector score into "how unusual is this for human text".

python -m detecteval.calibration # public reference from the committed long-set scores
python -m detecteval.calibration --private # also a private human reference, kept outside the repository

The public file (results/calibration.json) holds, for each detector and text length, the sorted scores of
every human and every AI text in the long set. The optional private file
(RAW_DATA_DIR/private/calibration.json) holds the scores of one group of private human documents, by
default the writer's pre-ChatGPT work, which is the harder and more realistic comparison.
"""
from __future__ import annotations

import argparse
import bisect
import json

from . import compare, config
from .items import private_dir, private_documents

DETECTORS = ["classifier-mirrors", "binoculars"]
PRIVATE_GROUP = "own_pre_ai"


def public_path():
return config.RESULTS_DIR / "calibration.json"


def private_path():
return private_dir() / "calibration.json"


def build_public() -> dict:
texts, scores = compare.load_texts(), compare.load_scores()
out: dict = {}
for name in DETECTORS:
out[name] = {}
for rung in config.RUNGS:
keys = [key for key in compare.keys_of(texts, "long", rung) if key in scores[name]]
out[name][str(rung)] = {
label: sorted(round(scores[name][key], 4) for key in keys if texts[key]["label"] == label)
for label in ("human", "ai")}
return out


def build_private(group: str = PRIVATE_GROUP) -> dict:
from .private_eval import load_private_scores

scores = load_private_scores()
documents = [row["id"] for row in private_documents() if row["group"] == group]
return {name: {str(rung): {"human": sorted(round(scores[name][f"{doc}@{rung}"], 4) for doc in documents
if f"{doc}@{rung}" in scores[name])}
for rung in config.RUNGS}
for name in DETECTORS if name in scores}


def load() -> dict:
"""{"public": ..., "private": ... or None}. Raises if the public reference has not been built."""
with open(public_path()) as handle:
public = json.load(handle)
private = None
if private_path().exists():
with open(private_path()) as handle:
private = json.load(handle)
return {"public": public, "private": private}


def share_at_least(reference: list[float], score: float) -> float | None:
"""Share of the sorted reference scores that are at least ``score``; None without a reference."""
if not reference:
return None
return (len(reference) - bisect.bisect_left(reference, score)) / len(reference)


def share_at_most(reference: list[float], score: float) -> float | None:
if not reference:
return None
return bisect.bisect_right(reference, score) / len(reference)


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")
args = parser.parse_args()
public_path().write_text(json.dumps(build_public()) + "\n")
print("wrote", public_path())
if args.private:
private_path().write_text(json.dumps(build_private()) + "\n")
print("wrote", private_path())


if __name__ == "__main__":
main()
106 changes: 106 additions & 0 deletions src/detecteval/detector.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
"""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.
"""
from __future__ import annotations

from . import config
from .calibration import 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")]
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 "
"present, comes from one student's pre-ChatGPT work.",
"Text a person wrote and an AI then polished usually scores as AI.",
"Text from AI models newer than the training data may score as human.",
f"Under about 150 words the result is unreliable; under {MIN_WORDS} words no result is given.",
]


def split_passages(text: str) -> tuple[list[dict], bool]:
"""Consecutive passages of up to 500 words, each cut to the longest reference length it can fill.

Returns (passages, truncated). A passage is {"index", "words", "rung", "text"}; ``text`` is what the
detectors score. Texts too short for the shortest reference length give no passages."""
words = normalise(strip_markdown(text)).split(" ")
passages, start = [], 0
while len(words) - start >= MIN_WORDS and len(passages) < MAX_PASSAGES:
piece = trim_words(" ".join(words[start:]), config.LONG_MAX_WORDS, MIN_WORDS)
rung = max(r for r in config.RUNGS if rung_text(piece, r, config.RUNG_FILL) is not None)
passages.append({"index": len(passages) + 1, "words": len(piece.split(" ")), "rung": rung,
"text": rung_text(piece, rung, config.RUNG_FILL)})
start += len(piece.split(" "))
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 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)]
human = {"public": share_at_least(public["human"], score)}
counts = {"public": len(public["human"])}
private = (calibration.get("private") or {}).get(detector, {}).get(str(rung), {}).get("human")
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,
"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"])}


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]
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."
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}


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 = []
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}
out_passages.append({"index": passage["index"], "words": passage["words"],
"scored_at_words": passage["rung"], "start": passage["text"][:90],
"detectors": detectors})
notes = list(notes or [])
if truncated:
notes.append(f"Only the first {MAX_PASSAGES} passages were scored.")
if any(passage["rung"] < 150 for passage in passages):
notes.append("Some passages are under 150 words, where results are unreliable.")
return {"ok": True, "summary": summarise(out_passages), "passages": out_passages, "notes": notes,
"private_reference": bool(calibration.get("private")), "limits": LIMITS}


def too_short() -> dict:
return {"ok": False, "error": f"Need at least {MIN_WORDS} words to give any result.", "limits": LIMITS}
Loading
Loading