legitcoconut commited on
Commit
e84edab
·
1 Parent(s): 30ee438

DroidDetect-Large code authorship checker

Browse files
Files changed (12) hide show
  1. .gitignore +3 -0
  2. DEPLOY.md +176 -0
  3. README.md +184 -4
  4. app.py +207 -0
  5. detector.py +202 -0
  6. forensics.py +127 -0
  7. labels.py +63 -0
  8. requirements.txt +12 -0
  9. smoke_test.py +192 -0
  10. test_auth.py +75 -0
  11. test_collapse.py +74 -0
  12. test_forensics.py +64 -0
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
DEPLOY.md ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Deploying to a free Hugging Face Space
2
+
3
+ Target: **CPU basic — 2 vCPU, 16 GB RAM, free.** No GPU, no paid upgrade.
4
+
5
+ ## Does Large fit the free tier?
6
+
7
+ Yes, with room to spare.
8
+
9
+ | | Large (default) | Base |
10
+ | --- | --- | --- |
11
+ | Download (one-time, cached on the Space) | 1.58 GB | 597 MB |
12
+ | Resident RAM | ~1.7 GB of 16 GB | ~0.7 GB |
13
+ | Time per submission (~400 tokens) | ~4 s | ~1 s |
14
+ | First request after a cold boot | ~2 min | ~60 s |
15
+
16
+ The checkpoint file is ~790M parameters, twice ModernBERT-large, because it
17
+ bundles a *second complete encoder* under `additional_loss.sentence_embedder`
18
+ used only by the training-time triplet loss. `detector.py` drops it on load, so
19
+ Large actually runs at ~395M. That is the single reason it fits.
20
+
21
+ Switch to Base by setting `DROID_REPO=project-droid/DroidDetect-Base` if 4 s per
22
+ check turns out to be too slow for your batch sizes.
23
+
24
+ ---
25
+
26
+ ## 1. Create the Space
27
+
28
+ New Space → **Gradio** SDK → **CPU basic (free)**. Private is fine; the token
29
+ check runs either way, and Code Arena calls it server-side.
30
+
31
+ ## 2. Push the files
32
+
33
+ ```bash
34
+ git clone https://huggingface.co/spaces/<you>/<space-name>
35
+ cp droid-code-checker/{app.py,detector.py,forensics.py,smoke_test.py,test_forensics.py,requirements.txt,README.md} <space-name>/
36
+ cd <space-name>
37
+ git add -A && git commit -m "DroidDetect-Large code authorship checker" && git push
38
+ ```
39
+
40
+ `README.md` carries the Space frontmatter (`sdk: gradio`, `sdk_version: 6.14.0`,
41
+ `python_version: '3.12'`, `app_file: app.py`) — the same combination the current
42
+ CodeT5+ Space builds with. Keep it; the Space will not configure itself without
43
+ it.
44
+
45
+ ## 3. The API token
46
+
47
+ It's hardcoded at the top of `app.py`:
48
+
49
+ ```python
50
+ API_TOKEN = "5b0be8195774f35a3388a27524b72a95a673ff3fc70ecafb5cc44aca0390367b"
51
+ ```
52
+
53
+ Nothing to configure on the Space — change it in the file and push. Generate a
54
+ replacement with `openssl rand -hex 32`.
55
+
56
+ Because it lives in the source, **make the Space private**. Anyone who can read
57
+ the repo can call the endpoint and burn your CPU quota. If the repo is ever made
58
+ public, rotate the token and update Arena's setting to match.
59
+
60
+ `test_auth.py` guards this. It fails the build-time check if `API_TOKEN` is ever
61
+ turned back into a bare `os.environ.get(...)` — that returns `None` when the
62
+ variable is unset, which breaks every real request *and* lets a `null` token
63
+ authenticate.
64
+
65
+ ## 4. Wait for the first build
66
+
67
+ Five to ten minutes: the torch wheel, then transformers, then the 1.58 GB model
68
+ download on first boot. Watch **Logs**.
69
+
70
+ `load_model()` runs at startup, so the Space only goes green once the weights
71
+ are loaded — the first real request is already warm.
72
+
73
+ Two things this build depends on, both handled in `detector.py`:
74
+
75
+ - **`transformers>=4.48`.** ModernBERT support landed there. On anything older
76
+ the config won't resolve and the Space dies at import.
77
+ - **`config.reference_compile = False`.** ModernBERT `torch.compile()`s part of
78
+ itself by default. On a CPU Space that's a long stall on the first request —
79
+ and on some torch builds an outright failure — for no throughput gain.
80
+
81
+ If you want a smaller image, check the build log for the resolved torch version
82
+ and pin it explicitly as `torch==X.Y.Z+cpu` in `requirements.txt`. The CPU wheel
83
+ is roughly a gigabyte smaller than the default one, which carries CUDA
84
+ libraries that are dead weight here.
85
+
86
+ ## 5. Resolve the pooling setting — do this once
87
+
88
+ The checkpoint doesn't record how the encoder's token states are collapsed
89
+ before the classifier head, and the model card doesn't say. There are two
90
+ candidates and only one is right.
91
+
92
+ Open the Space terminal (or run locally with the same requirements):
93
+
94
+ ```bash
95
+ python smoke_test.py
96
+ ```
97
+
98
+ It runs four unambiguous submissions — terse contest code, a chat-assistant
99
+ answer, a human skeleton with a model-filled body, and model output stripped
100
+ down to look hand-typed — through both poolings and prints which one recovers
101
+ the expected labels.
102
+
103
+ It scores on the **ternary** collapse, not the raw 4-way: separating
104
+ "adversarial" from ordinary machine output is the split the model is weakest at,
105
+ so grading pooling on it would measure the wrong thing.
106
+
107
+ Then set the winner:
108
+
109
+ **Settings → Variables and secrets → New variable** — `POOLING` = `mean` or `cls`.
110
+
111
+ If both score 0, the head is mis-wired rather than mis-pooled; check that
112
+ `load_state_dict(..., strict=True)` didn't raise during startup.
113
+
114
+ ## 6. Verify end to end
115
+
116
+ ```bash
117
+ SPACE=https://<you>-<space-name>.hf.space
118
+
119
+ EVENT=$(curl -s -X POST "$SPACE/gradio_api/call/detect" \
120
+ -H 'content-type: application/json' \
121
+ -d '{"data": ["def f():\n return 1\n", "YOUR_API_TOKEN"]}' | jq -r .event_id)
122
+
123
+ curl -s -N "$SPACE/gradio_api/call/detect/$EVENT"
124
+ ```
125
+
126
+ Then confirm the guard actually guards:
127
+
128
+ ```bash
129
+ curl -s -X POST "$SPACE/gradio_api/call/detect" \
130
+ -H 'content-type: application/json' \
131
+ -d '{"data": ["print(1)", "wrong-token"]}'
132
+ # the stream must yield {"error": "Invalid or missing token"}
133
+ ```
134
+
135
+ ## 7. Point Code Arena at it
136
+
137
+ **Admin → Settings → AI code checker**: set the URL to `$SPACE` and the API key
138
+ to your `API_TOKEN`.
139
+
140
+ No application changes are needed. `lib/server/aiChecker.ts` reads `verdict`,
141
+ `ai_probability`, `token_count` and `truncated` — all four still returned with
142
+ their original meaning — and stores the entire JSON payload in `aiCheck.raw`.
143
+ So the ternary verdict, the four-way probabilities, the forensic signals and the
144
+ style embedding all land in Mongo from the first check onward, whether or not
145
+ the UI reads them yet.
146
+
147
+ ## Running it locally
148
+
149
+ ```bash
150
+ python -m venv .venv && source .venv/bin/activate
151
+ pip install -r requirements.txt gradio
152
+ python test_forensics.py # no torch needed, instant
153
+ python smoke_test.py # downloads the model, a few minutes on Large
154
+ python app.py # http://127.0.0.1:7860
155
+ ```
156
+
157
+ `gradio` is deliberately not in `requirements.txt` — on a Space the SDK version
158
+ in the README frontmatter provides it, and listing it too can fight that. Add it
159
+ by hand for local runs, as above.
160
+
161
+ ## Operational notes
162
+
163
+ - **Sleep.** Free Spaces sleep after 48 h idle, and Large's cold start is ~2 min.
164
+ If checks are run in bursts during an event, warm it with one throwaway
165
+ request before the event opens.
166
+ - **Concurrency.** 2 vCPU, and `TORCH_THREADS` is pinned to 2 to stop torch
167
+ spawning a thread per detected core on a shared host — that causes contention,
168
+ not speed. Gradio queues, so 100 checks run serially at roughly 4 s each
169
+ (~7 min). Code Arena's panel paces itself to 20 calls/min, which is faster than
170
+ Large can serve; if that becomes a problem, switch to Base rather than
171
+ raising the queue size.
172
+ - **Timeout headroom.** `aiChecker.ts` allows 120 s per check. Large at the
173
+ default 2048-token cap lands far inside that even on a cold-ish worker. If you
174
+ raise `MAX_LENGTH` toward 8192, re-check that margin.
175
+ - **Storage.** Free Spaces get ~50 GB ephemeral disk; the model cache is
176
+ re-downloaded after a factory reset, not after a normal restart.
README.md CHANGED
@@ -1,14 +1,194 @@
1
  ---
2
  title: Droid Code Checker
3
- emoji: 📈
4
- colorFrom: gray
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 6.26.0
8
  python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
11
  license: apache-2.0
 
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Droid Code Checker
3
+ emoji: 🕵️
4
+ colorFrom: indigo
5
+ colorTo: pink
6
  sdk: gradio
7
  sdk_version: 6.26.0
8
  python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
11
  license: apache-2.0
12
+ short_description: Code authorship detection for Code Arena
13
  ---
14
 
15
+ # Code Authorship Checker
16
+
17
+ Code-authorship detection with **`project-droid/DroidDetect-Large`**
18
+ (ModernBERT-large, Apache-2.0) plus a static forensics layer that looks for the
19
+ physical traces of pasted text. Runs on the **free CPU tier**.
20
+
21
+ Replaces the CodeT5+ Space. Same endpoint name, same inputs, same four legacy
22
+ response fields — Code Arena keeps working with no changes at all.
23
+
24
+ ## What it returns
25
+
26
+ | | Old CodeT5+ Space | This |
27
+ |---|---|---|
28
+ | Classes | human / AI | human / AI / **AI-refined** / **AI-adversarial** |
29
+ | Verdict levels | 1 (binary) | **3** (binary, ternary, 4-way) |
30
+ | Context | 512 tokens (truncated) | 2048 (model ceiling is 8192) |
31
+ | Extras | — | forensic signals, style embedding, inconclusive flag |
32
+
33
+ ### The three levels
34
+
35
+ The model makes one prediction over four classes. It's read back at three
36
+ granularities, because they are not equally trustworthy:
37
+
38
+ | Level | Values | Large's weighted F1 |
39
+ |---|---|---|
40
+ | `binary` | HUMAN · MACHINE | ~97% |
41
+ | **`ternary`** | HUMAN · MACHINE · REFINED | **~88.8%** |
42
+ | `detailed` | the raw 4 classes | lowest |
43
+
44
+ **Show moderators the `ternary` label.** It answers the question a contest
45
+ actually cares about — did the participant write this, did a model write it, or
46
+ did they start it and let a model finish — and it's the deepest level the model
47
+ is reliable at. The 4-way split additionally separates *adversarial* (model
48
+ output deliberately styled to look hand-typed) from ordinary model output;
49
+ that's the hardest distinction and the one to treat with most suspicion.
50
+
51
+ `MACHINE_GENERATED_ADVERSARIAL` folds into `MACHINE` at the ternary level,
52
+ because model output styled to look hand-written is still model output. It's
53
+ also the class where DroidDetect earns its keep: it holds ~0.92 recall there,
54
+ where GPTZero drops to ~0.10.
55
+
56
+ ```json
57
+ {
58
+ "verdict": "AI-Generated",
59
+ "ai_probability": 0.18,
60
+ "token_count": 412,
61
+ "truncated": false,
62
+
63
+ "binary": { "label": "MACHINE", "confidence": 0.82,
64
+ "probs": { "HUMAN": 0.18, "MACHINE": 0.82 } },
65
+ "ternary": { "label": "REFINED", "confidence": 0.71,
66
+ "probs": { "HUMAN": 0.18, "MACHINE": 0.11, "REFINED": 0.71 },
67
+ "meaning": "Participant started it, a model completed or rewrote it" },
68
+ "detailed": {
69
+ "label": "MACHINE_REFINED",
70
+ "confidence": 0.71,
71
+ "probs": {
72
+ "HUMAN_GENERATED": 0.18,
73
+ "MACHINE_GENERATED": 0.09,
74
+ "MACHINE_REFINED": 0.71,
75
+ "MACHINE_GENERATED_ADVERSARIAL": 0.02
76
+ }
77
+ },
78
+ "inconclusive": false,
79
+
80
+ "label": "MACHINE_REFINED",
81
+ "confidence": 0.71,
82
+ "human_probability": 0.18,
83
+ "model_ai_score": 82,
84
+ "embedding": [0.031, -0.118, "…254 more"],
85
+
86
+ "features": { "comment_ratio": 0.44, "ai_style_comments": 4, "smart_punct": 1,
87
+ "mixed_indent": false, "crlf": false, "…": "20 fields" },
88
+ "signals": [
89
+ { "code": "unicode_punctuation", "weight": 35,
90
+ "detail": "Curly quotes/dashes — pasted from a rendered page or chat UI, not typed" }
91
+ ],
92
+ "forensic_score": 75,
93
+
94
+ "score": 80,
95
+ "model": "project-droid/DroidDetect-Large",
96
+ "pooling": "mean",
97
+ "max_length": 2048
98
+ }
99
+ ```
100
+
101
+ Field notes:
102
+
103
+ - **`ai_probability` is a human score.** It's the probability of the
104
+ `HUMAN_GENERATED` class, kept under the old (misleading) name so Code Arena
105
+ keeps behaving identically. `human_probability` is the same number, honestly
106
+ named.
107
+ - `model_ai_score` is `100 × P(MACHINE)` from the binary collapse. Three of the
108
+ four classes are machine, so unlike the CodeT5+ Space this is a genuine AI
109
+ probability rather than a distance from a hand-tuned threshold.
110
+ - **`inconclusive`** is true when the top class is under 0.45 — the model has
111
+ nothing to say. Show it as "no signal", never as a verdict. A flat
112
+ `0.3 / 0.3 / 0.2 / 0.2` is noise, not evidence.
113
+ - `embedding` is a 256-d style vector (128-d on Base). Cosine-compare one
114
+ participant's submissions against each other — the outlier is the answer they
115
+ didn't write the way they write. It separates *human from machine*, not
116
+ *author from author*, so it's a consistency signal, not a plagiarism matcher.
117
+ - `score` fuses model and forensics for ranking only. Peer similarity and
118
+ submission timing are deliberately absent: they belong to the platform, which
119
+ holds every submission and every timestamp.
120
+
121
+ ## API
122
+
123
+ Every request must carry the token. An invalid or missing one returns
124
+ `{"error": "Invalid or missing token"}` and **the model never runs**. Empty
125
+ input returns `{"error": "No code provided"}`; oversized input is rejected by
126
+ character count before tokenization.
127
+
128
+ ```python
129
+ from gradio_client import Client
130
+
131
+ client = Client("your-name/code-authorship-checker")
132
+
133
+ result = client.predict(
134
+ code="int main(){return 0;}",
135
+ token="YOUR_API_TOKEN",
136
+ api_name="/detect",
137
+ )
138
+ print(result["ternary"]["label"], result["ternary"]["confidence"])
139
+ ```
140
+
141
+ Or over plain HTTP — the two-step Gradio flow Code Arena uses:
142
+
143
+ ```bash
144
+ EVENT=$(curl -s -X POST "$SPACE/gradio_api/call/detect" \
145
+ -H 'content-type: application/json' \
146
+ -d '{"data": ["print(1)", "YOUR_API_TOKEN"]}' | jq -r .event_id)
147
+
148
+ curl -s -N "$SPACE/gradio_api/call/detect/$EVENT"
149
+ ```
150
+
151
+ ## Configuration
152
+
153
+ All optional — the Space boots and works with none of them set.
154
+
155
+ The API token is **not** one of these — it's hardcoded as `API_TOKEN` at the top
156
+ of `app.py`. Change it there and push. Because it lives in the source, keep the
157
+ Space **private**, and rotate the value if the repo is ever made public.
158
+
159
+ | Variable | Default | Purpose |
160
+ | --- | --- | --- |
161
+ | `DROID_REPO` | `project-droid/DroidDetect-Large` | `…/DroidDetect-Base` is ~4× faster for ~2 F1 less |
162
+ | `POOLING` | `mean` | `mean` or `cls` — run `smoke_test.py` once to confirm |
163
+ | `MAX_LENGTH` | `2048` | Tokens per request (model ceiling 8192; higher = slower) |
164
+ | `HUMAN_THRESHOLD` | `0.5` | Below this `p_human`, the legacy verdict line says AI-Generated |
165
+ | `INCONCLUSIVE_BELOW` | `0.45` | Top-class probability under which `inconclusive` is set |
166
+ | `MODEL_WEIGHT` | `0.7` | Model vs forensics weighting in the fused `score` |
167
+ | `MAX_CHARS` | `200000` | Reject paste bombs before tokenizing |
168
+ | `TORCH_THREADS` | `2` | Matches the free tier's 2 vCPUs |
169
+
170
+ ## Accuracy, honestly
171
+
172
+ Reported by the Droid paper for Large: **97.0%** weighted F1 binary and
173
+ **88.8%** ternary — against 91.6% for GPTSniffer and 76.5% for Fast-DetectGPT.
174
+
175
+ Those are in-distribution. On unseen languages and domains this class of
176
+ detector falls to roughly 0.85 macro-F1, and under combined domain *and*
177
+ language shift, benchmarks put it near 0.21. The errors are asymmetric:
178
+ detectors reliably spot AI code but flag *unusual human code* as AI — which in
179
+ a contest means your strongest participants. Treat every number here as one
180
+ input to a human decision, never as a verdict on its own.
181
+
182
+ ## Files
183
+
184
+ | File | Role |
185
+ | --- | --- |
186
+ | `app.py` | Gradio UI + token-guarded `detect` endpoint |
187
+ | `detector.py` | Checkpoint loader, `TLModel` wrapper, label collapsing |
188
+ | `forensics.py` | Static paste-trace analysis — standard library only |
189
+ | `labels.py` | Class taxonomy + the binary/ternary collapses |
190
+ | `smoke_test.py` | First-run check; resolves the `POOLING` setting |
191
+ | `test_forensics.py` | Self-check for the forensics layer, no torch needed |
192
+ | `test_collapse.py` | Self-check for the ternary/binary collapse |
193
+ | `test_auth.py` | Self-check for the API-token guard |
194
+ | `DEPLOY.md` | Deployment walkthrough |
app.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Code Authorship Checker — DroidDetect-Large (ModernBERT) + static forensics.
2
+
3
+ Token-protected Gradio app exposing one API endpoint (`api_name="detect"`).
4
+
5
+ Drop-in replacement for the CodeT5+ Space: same inputs `[code, token]`, and the
6
+ response still carries `verdict` / `ai_probability` / `token_count` /
7
+ `truncated`, so Code Arena keeps working with no changes at all. Everything
8
+ else in the payload is new evidence layered on top.
9
+
10
+ The model's own prediction is read at three levels of granularity:
11
+
12
+ binary HUMAN | MACHINE — the old yes/no
13
+ ternary HUMAN | MACHINE | REFINED — who actually wrote it
14
+ detailed the raw 4 classes — separates ADVERSARIAL
15
+
16
+ Report the ternary label to moderators. It is the level the model is actually
17
+ reliable at (~88.8% weighted F1 on Large vs ~97% binary), and it answers the
18
+ question that matters in a contest: did the participant write this, did a model
19
+ write it, or did they start it and let a model finish.
20
+ """
21
+
22
+ import hmac
23
+ import os
24
+
25
+ import gradio as gr
26
+
27
+ from detector import (
28
+ BINARY_LABELS,
29
+ BINARY_OF,
30
+ LABELS,
31
+ MAX_LENGTH,
32
+ POOLING,
33
+ REPO,
34
+ TERNARY_LABELS,
35
+ TERNARY_MEANING,
36
+ TERNARY_OF,
37
+ classify,
38
+ collapse,
39
+ )
40
+ from forensics import forensic_signals, static_features
41
+
42
+ # --- Configuration ---------------------------------------------------------
43
+
44
+ # Clients must send this exact string as the second argument. Hardcoded on
45
+ # purpose. Anyone who can read this repo can call the endpoint, so keep the
46
+ # Space private — and rotate this value if the repo ever goes public.
47
+ API_TOKEN = "5b0be8195774f35a3388a27524b72a95a673ff3fc70ecafb5cc44aca0390367b"
48
+
49
+ # Decides the legacy human/AI verdict line. Raise it to make the detector more
50
+ # willing to call something AI, lower it to be stricter about accusing. This is
51
+ # the knob to tune once you have labelled event data.
52
+ HUMAN_THRESHOLD = float(os.environ.get("HUMAN_THRESHOLD", "0.5"))
53
+
54
+ # Fusion weight between the model score and the static forensic score.
55
+ MODEL_WEIGHT = float(os.environ.get("MODEL_WEIGHT", "0.7"))
56
+
57
+ # A submission is a few KB. Anything past this is a paste bomb, not an answer.
58
+ MAX_CHARS = int(os.environ.get("MAX_CHARS", "200000"))
59
+
60
+ # Below this top-class probability the model isn't actually distinguishing
61
+ # anything, and the result should read as inconclusive rather than as a
62
+ # verdict. Four classes ⇒ chance is 0.25.
63
+ INCONCLUSIVE_BELOW = float(os.environ.get("INCONCLUSIVE_BELOW", "0.45"))
64
+
65
+
66
+ # --- Inference -------------------------------------------------------------
67
+
68
+
69
+ def detect_code(code_text):
70
+ """Run the full evidence pipeline on one submission."""
71
+ probs, embedding, token_count, truncated = classify(code_text)
72
+
73
+ p_human = probs["HUMAN_GENERATED"]
74
+ label = max(probs, key=probs.get)
75
+
76
+ ternary_probs, ternary_label, ternary_conf = collapse(
77
+ probs, TERNARY_OF, TERNARY_LABELS
78
+ )
79
+ binary_probs, binary_label, binary_conf = collapse(
80
+ probs, BINARY_OF, BINARY_LABELS
81
+ )
82
+
83
+ # Three of the four classes are machine, so this is a real AI probability —
84
+ # not the distance-from-threshold hack the CodeT5+ checkpoint needed.
85
+ model_ai_score = round(100 * binary_probs["MACHINE"])
86
+
87
+ features = static_features(code_text)
88
+ forensic_score, signals = forensic_signals(features)
89
+
90
+ return {
91
+ # --- legacy fields: keep Code Arena working untouched.
92
+ # NOTE ai_probability is a HUMAN score, as it always was on the
93
+ # CodeT5+ Space. `human_probability` below is the honest name. ---
94
+ "verdict": "Human-Written" if p_human >= HUMAN_THRESHOLD else "AI-Generated",
95
+ "ai_probability": p_human,
96
+ "token_count": token_count,
97
+ "truncated": truncated,
98
+ # --- the three-tier read of the same prediction ---
99
+ "binary": {
100
+ "label": binary_label,
101
+ "confidence": binary_conf,
102
+ "probs": binary_probs,
103
+ },
104
+ "ternary": {
105
+ "label": ternary_label,
106
+ "confidence": ternary_conf,
107
+ "probs": ternary_probs,
108
+ "meaning": TERNARY_MEANING[ternary_label],
109
+ },
110
+ "detailed": {
111
+ "label": label,
112
+ "confidence": probs[label],
113
+ "probs": probs,
114
+ },
115
+ # A flat distribution means the model has nothing to say. Surface that
116
+ # explicitly so a moderator never reads noise as an accusation.
117
+ "inconclusive": probs[label] < INCONCLUSIVE_BELOW,
118
+ # --- flat aliases, so callers don't have to reach into the nested
119
+ # blocks for the most-used numbers ---
120
+ "label": label,
121
+ "confidence": probs[label],
122
+ "probs": probs,
123
+ "human_probability": p_human,
124
+ "model_ai_score": model_ai_score,
125
+ # 256-d (Large) or 128-d (Base) style vector. Cosine-compare one
126
+ # participant's submissions against each other: the odd one out is the
127
+ # one that was not written the way they write.
128
+ "embedding": embedding,
129
+ # --- static forensics: physical traces of pasted text ---
130
+ "features": features,
131
+ "signals": signals,
132
+ "forensic_score": forensic_score,
133
+ # --- fused 0-100 for ranking. Peer similarity and submission timing
134
+ # live on the platform side and are deliberately NOT in here. ---
135
+ "score": round(
136
+ MODEL_WEIGHT * model_ai_score + (1 - MODEL_WEIGHT) * forensic_score
137
+ ),
138
+ "model": REPO,
139
+ "pooling": POOLING,
140
+ "max_length": MAX_LENGTH,
141
+ }
142
+
143
+
144
+ def detect(code, token):
145
+ """UI handler + API endpoint. Validates the token before running anything."""
146
+ # isinstance guard first: the API accepts arbitrary JSON, so `token` can
147
+ # arrive as null/number/list. compare_digest is constant-time and rejects
148
+ # non-str outright, which also keeps a mistyped token from being a timing
149
+ # oracle for the real one.
150
+ if not isinstance(token, str) or not hmac.compare_digest(token, API_TOKEN):
151
+ return {"error": "Invalid or missing token"}
152
+
153
+ if not code or not code.strip():
154
+ return {"error": "No code provided"}
155
+
156
+ if len(code) > MAX_CHARS:
157
+ return {"error": f"Code too large ({len(code)} chars, limit {MAX_CHARS})"}
158
+
159
+ return detect_code(code)
160
+
161
+
162
+ # --- UI --------------------------------------------------------------------
163
+
164
+ with gr.Blocks(title="Code Authorship Checker") as demo:
165
+ gr.Markdown(
166
+ "# Code Authorship Checker\n"
167
+ f"`{REPO}` + static forensics, running on CPU. Paste code, enter the "
168
+ "API token, and click **Analyze Code**. The same function is exposed "
169
+ 'as an API (`api_name="detect"`).\n\n'
170
+ "**Read the `ternary` block first** — HUMAN / MACHINE / REFINED is the "
171
+ "level this model is genuinely reliable at. The 4-way `detailed` block "
172
+ "additionally separates *adversarial* (model output deliberately "
173
+ "styled to look hand-typed) from ordinary model output; that split is "
174
+ "the hardest one and the least certain."
175
+ )
176
+
177
+ code_input = gr.Code(label="Code", language=None, lines=20)
178
+ token_input = gr.Textbox(
179
+ label="API token",
180
+ type="password",
181
+ placeholder="Enter your API token",
182
+ )
183
+
184
+ analyze_btn = gr.Button("Analyze Code", variant="primary")
185
+ output = gr.JSON(label="Result")
186
+
187
+ analyze_btn.click(
188
+ detect,
189
+ inputs=[code_input, token_input],
190
+ outputs=output,
191
+ api_name="detect",
192
+ )
193
+
194
+ gr.Markdown(
195
+ f"4-way classes: `{'` · `'.join(LABELS)}`\n\n"
196
+ f"Max {MAX_LENGTH} tokens per request · pooling `{POOLING}` · "
197
+ "every request must carry the API token."
198
+ )
199
+
200
+
201
+ if __name__ == "__main__":
202
+ from detector import load_model
203
+
204
+ # Warm-load so the first real request isn't the slow one. On the Space this
205
+ # runs at startup, so the app only goes green once the weights are ready.
206
+ load_model()
207
+ demo.queue(max_size=32).launch()
detector.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DroidDetect loader — ModernBERT 4-class code-authorship detector.
2
+
3
+ The published checkpoints are NOT `AutoModelForSequenceClassification`. Their
4
+ config.json is a 4-line stub (`"model_type": "custom_model"`), so the wrapper
5
+ has to be rebuilt by hand. Everything it needs is inferable from the tensor
6
+ shapes, so this file hardcodes no dimensions:
7
+
8
+ text_encoder.* ModernBERT encoder (768 hidden = Base, 1024 = Large)
9
+ text_projection hidden -> proj_dim (128 on Base, 256 on Large)
10
+ classifier proj_dim -> 4 classes
11
+
12
+ DroidDetect-Large additionally ships a *second complete encoder* under
13
+ `additional_loss.sentence_embedder.*` — 395M parameters used only for the
14
+ training-time triplet loss. It is dropped on load, which halves resident memory
15
+ with no effect on predictions. That is what makes Large fit the free CPU tier.
16
+ """
17
+
18
+ import os
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ from huggingface_hub import hf_hub_download
23
+ from transformers import AutoConfig, AutoModel, AutoTokenizer
24
+
25
+ # Large is the default: +2 points of F1 over Base, and it still fits the free
26
+ # CPU tier once the training-only twin encoder is dropped (~1.7 GB resident of
27
+ # the 16 GB available). Set DROID_REPO=project-droid/DroidDetect-Base to trade
28
+ # accuracy for ~4x faster inference.
29
+ REPO = os.environ.get("DROID_REPO", "project-droid/DroidDetect-Large")
30
+
31
+ # ModernBERT handles 8192 tokens, but on 2 shared vCPUs every token costs real
32
+ # wall-clock. Contest submissions are a few hundred tokens; 2048 leaves large
33
+ # headroom and bounds the worst case to a few seconds. Raise it only if you
34
+ # actually see `truncated: true` in production.
35
+ MAX_LENGTH = int(os.environ.get("MAX_LENGTH", "2048"))
36
+
37
+ # How the encoder's token states are collapsed into one vector before the head.
38
+ # The checkpoint does not record this and the model card does not say. Run
39
+ # smoke_test.py once — it tries both and tells you which one this checkpoint
40
+ # was trained with. See DEPLOY.md step 5.
41
+ POOLING = os.environ.get("POOLING", "mean")
42
+
43
+ # Free Spaces get 2 vCPUs. Letting torch spawn a thread per core it *detects*
44
+ # on a shared host causes contention that makes inference slower, not faster.
45
+ torch.set_num_threads(int(os.environ.get("TORCH_THREADS", "2")))
46
+
47
+ # Label taxonomy + the coarse collapses live in labels.py so they can be tested
48
+ # without torch. Re-exported here so callers have one import site.
49
+ from labels import ( # noqa: E402 (kept with the other detector constants)
50
+ BINARY_LABELS,
51
+ BINARY_OF,
52
+ LABELS,
53
+ TERNARY_LABELS,
54
+ TERNARY_MEANING,
55
+ TERNARY_OF,
56
+ collapse,
57
+ )
58
+
59
+ __all__ = [
60
+ "BINARY_LABELS",
61
+ "BINARY_OF",
62
+ "LABELS",
63
+ "MAX_LENGTH",
64
+ "POOLING",
65
+ "REPO",
66
+ "TERNARY_LABELS",
67
+ "TERNARY_MEANING",
68
+ "TERNARY_OF",
69
+ "classify",
70
+ "collapse",
71
+ "load_model",
72
+ ]
73
+
74
+ # hidden size -> the backbone that produced it
75
+ BACKBONES = {
76
+ 768: "answerdotai/ModernBERT-base",
77
+ 1024: "answerdotai/ModernBERT-large",
78
+ }
79
+
80
+ # Checkpoint filenames to try, in order.
81
+ WEIGHT_FILES = ("model.safetensors", "pytorch_model.bin")
82
+
83
+
84
+ class TLModel(nn.Module):
85
+ """Encoder -> projection -> classifier, matching the checkpoint's layout."""
86
+
87
+ def __init__(self, encoder, hidden, proj_dim, num_classes):
88
+ super().__init__()
89
+ self.text_encoder = encoder
90
+ self.text_projection = nn.Linear(hidden, proj_dim)
91
+ self.classifier = nn.Linear(proj_dim, num_classes)
92
+
93
+ def forward(self, input_ids, attention_mask, pooling=POOLING):
94
+ states = self.text_encoder(
95
+ input_ids=input_ids,
96
+ attention_mask=attention_mask,
97
+ ).last_hidden_state
98
+
99
+ if pooling == "cls":
100
+ pooled = states[:, 0]
101
+ else:
102
+ # Mean over real tokens only — padding must not drag the vector.
103
+ mask = attention_mask.unsqueeze(-1).to(states.dtype)
104
+ pooled = (states * mask).sum(1) / mask.sum(1).clamp(min=1e-9)
105
+
106
+ embedding = self.text_projection(pooled)
107
+ return self.classifier(embedding), embedding
108
+
109
+
110
+ tokenizer = None
111
+ model = None
112
+
113
+
114
+ def _download_state():
115
+ """Fetch the checkpoint, preferring safetensors. Returns a state dict."""
116
+ last = None
117
+ for name in WEIGHT_FILES:
118
+ try:
119
+ path = hf_hub_download(repo_id=REPO, filename=name)
120
+ except Exception as err: # not published in this format — try the next
121
+ last = err
122
+ continue
123
+ if name.endswith(".safetensors"):
124
+ from safetensors.torch import load_file
125
+
126
+ return load_file(path, device="cpu")
127
+ return torch.load(path, map_location="cpu", weights_only=True)
128
+ raise RuntimeError(f"No usable checkpoint found in {REPO}: {last}")
129
+
130
+
131
+ def load_model():
132
+ """Download and build the detector. Idempotent; safe to call repeatedly."""
133
+ global tokenizer, model
134
+ if model is not None:
135
+ return
136
+
137
+ state = _download_state()
138
+
139
+ # Training-only twin encoder — never used at inference. Dropping it takes
140
+ # Large from ~790M resident parameters to ~395M.
141
+ state = {k: v for k, v in state.items() if not k.startswith("additional_loss.")}
142
+
143
+ proj_dim, hidden = state["text_projection.weight"].shape
144
+ num_classes = state["classifier.weight"].shape[0]
145
+
146
+ backbone = BACKBONES.get(hidden)
147
+ if backbone is None:
148
+ raise RuntimeError(f"Unrecognized encoder hidden size {hidden} in {REPO}")
149
+
150
+ # from_config, not from_pretrained: the checkpoint carries every encoder
151
+ # weight already, so pulling the base model would be a wasted download.
152
+ config = AutoConfig.from_pretrained(backbone)
153
+ # ModernBERT torch.compile()s part of itself when this is on. On a free CPU
154
+ # Space that means a long stall on the first request (and on some torch
155
+ # builds an outright failure) for no throughput gain.
156
+ config.reference_compile = False
157
+
158
+ try:
159
+ # Ask for SDPA explicitly so transformers never tries to import
160
+ # flash-attn, which isn't installed and is CUDA-only anyway.
161
+ encoder = AutoModel.from_config(config, attn_implementation="sdpa")
162
+ except (TypeError, ValueError):
163
+ # Older transformers without the kwarg — the CPU default is fine.
164
+ encoder = AutoModel.from_config(config)
165
+
166
+ net = TLModel(encoder, hidden, proj_dim, num_classes)
167
+ # strict: a silently mismatched head would return confident nonsense.
168
+ net.load_state_dict(state, strict=True)
169
+ net.float()
170
+ net.eval()
171
+
172
+ tokenizer = AutoTokenizer.from_pretrained(REPO)
173
+ model = net
174
+
175
+
176
+ @torch.no_grad()
177
+ def classify(code_text, pooling=None):
178
+ """Return (probabilities dict, embedding list, token count, truncated)."""
179
+ load_model()
180
+
181
+ encoded = tokenizer(
182
+ [code_text],
183
+ truncation=True,
184
+ max_length=MAX_LENGTH,
185
+ return_tensors="pt",
186
+ )
187
+ input_ids = encoded["input_ids"]
188
+ attention_mask = encoded["attention_mask"]
189
+
190
+ logits, embedding = model(
191
+ input_ids=input_ids,
192
+ attention_mask=attention_mask,
193
+ pooling=pooling or POOLING,
194
+ )
195
+ probs = torch.softmax(logits[0], dim=-1)
196
+
197
+ return (
198
+ {label: round(float(p), 6) for label, p in zip(LABELS, probs)},
199
+ [round(float(v), 4) for v in embedding[0]],
200
+ int(attention_mask.sum().item()),
201
+ bool(input_ids.shape[1] >= MAX_LENGTH),
202
+ )
forensics.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Static code forensics — pure text analysis, no model, no dependencies.
2
+
3
+ Imports nothing outside the standard library, so it runs and is testable
4
+ without torch.
5
+ Answers a different question than the stylometry model: not "does this read as
6
+ AI-written" but "does this text bear the physical traces of having been pasted
7
+ in rather than typed here".
8
+ """
9
+
10
+ import re
11
+ import statistics
12
+
13
+ COMMENT_PREFIXES = ("#", "//", "/*", "*", "--", "<!--")
14
+ IDENT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
15
+ CAMEL_RE = re.compile(r"^[a-z]+[A-Z]")
16
+
17
+ # Curly quotes, en/em dashes, non-breaking space, ellipsis, zero-width space.
18
+ # These cannot be typed into a code editor by accident — they arrive by paste
19
+ # from a rendered web page, PDF, or chat UI.
20
+ SMART_PUNCT_RE = re.compile("[‘’“”–— …​]")
21
+
22
+ # Tutorial-style narration: one comment per step, restating what the next line
23
+ # does. Characteristic of AI output and of copied walkthrough articles.
24
+ AI_COMMENT_RE = re.compile(
25
+ r"^\W*(step\s*\d|read\s+(the\s+)?input|initiali[sz]e|iterate|loop\s+through"
26
+ r"|print\s+the|check\s+if|return\s+the|calculate\s+the|handle\s+(the\s+)?edge"
27
+ r"|create\s+a|define\s+(a|the)|add\s+the|sort\s+the|first,|finally,)",
28
+ re.I,
29
+ )
30
+
31
+ KEYWORDS = frozenset(
32
+ """if elif else for while do return def class import from as in is not and or none
33
+ true false null nil public private protected static void int long float double char
34
+ bool boolean string str var let const function new this self try except catch finally
35
+ raise throw with lambda yield break continue pass switch case default struct enum
36
+ typedef sizeof namespace using include main print println printf scanf cout cin endl
37
+ std len range list dict set tuple map filter input output append push""".split()
38
+ )
39
+
40
+
41
+ def static_features(code):
42
+ """Language-agnostic forensic features. Pure text analysis, no model."""
43
+ lines = code.splitlines()
44
+ stripped = [ln.strip() for ln in lines]
45
+ body = [ln for ln in lines if ln.strip()]
46
+ n_body = len(body) or 1
47
+
48
+ comments = [s for s in stripped if s.startswith(COMMENT_PREFIXES)]
49
+ lens = [len(ln) for ln in body] or [0]
50
+ indented = [ln for ln in body if ln[:1] in (" ", "\t")]
51
+
52
+ idents = [w for w in IDENT_RE.findall(code) if w.lower() not in KEYWORDS]
53
+ uniq = set(idents)
54
+ n_uniq = len(uniq) or 1
55
+
56
+ return {
57
+ "chars": len(code),
58
+ "lines": len(lines),
59
+ "blank_ratio": round(sum(1 for s in stripped if not s) / (len(lines) or 1), 3),
60
+ "comment_ratio": round(len(comments) / n_body, 3),
61
+ "ai_style_comments": sum(1 for c in comments if AI_COMMENT_RE.match(c)),
62
+ "avg_line_len": round(statistics.fmean(lens), 1),
63
+ "stdev_line_len": round(statistics.pstdev(lens), 1) if len(lens) > 1 else 0.0,
64
+ "max_line_len": max(lens),
65
+ "mixed_indent": any(ln.startswith("\t") for ln in indented)
66
+ and any(ln.startswith(" ") for ln in indented),
67
+ "trailing_ws_lines": sum(1 for ln in lines if ln != ln.rstrip()),
68
+ "crlf": "\r\n" in code,
69
+ "smart_punct": len(SMART_PUNCT_RE.findall(code)),
70
+ "non_ascii": sum(1 for ch in code if ord(ch) > 127),
71
+ "unique_identifiers": len(uniq),
72
+ "avg_identifier_len": round(
73
+ statistics.fmean([len(w) for w in uniq]) if uniq else 0.0, 2
74
+ ),
75
+ "single_char_ratio": round(sum(1 for w in uniq if len(w) == 1) / n_uniq, 3),
76
+ "snake_ratio": round(
77
+ sum(1 for w in uniq if "_" in w and w.islower()) / n_uniq, 3
78
+ ),
79
+ "camel_ratio": round(sum(1 for w in uniq if CAMEL_RE.match(w)) / n_uniq, 3),
80
+ "has_docstring": '"""' in code or "'''" in code,
81
+ "has_type_hints": bool(
82
+ re.search(r"->\s*[A-Za-z\[]|:\s*(int|str|float|bool|List|Dict)\b", code)
83
+ ),
84
+ "has_main_guard": "__name__" in code and "__main__" in code,
85
+ }
86
+
87
+
88
+ # Signal -> (weight, explanation). Weights are the calibration knob: they encode
89
+ # how strongly each trace implies "not typed here by this person".
90
+ SIGNAL_WEIGHTS = {
91
+ "unicode_punctuation": (35, "Curly quotes/dashes — pasted from a rendered page or chat UI, not typed"),
92
+ "ai_narration_comments": (25, "Step-by-step narrating comments in AI/tutorial style"),
93
+ "mixed_indentation": (20, "Tabs and spaces mixed — assembled from more than one source"),
94
+ "heavy_commenting": (15, "Comment density unusually high for a timed contest answer"),
95
+ "production_style": (15, "Docstrings + type hints — production habits, rare under time pressure"),
96
+ "inconsistent_naming": (15, "snake_case and camelCase both used heavily — merged sources"),
97
+ "uniform_line_lengths": (10, "Machine-uniform line lengths"),
98
+ "crlf_endings": (10, "CRLF line endings — came from another environment"),
99
+ }
100
+
101
+
102
+ def forensic_signals(f):
103
+ """Fire named signals from a feature dict. Returns (score 0-100, signals)."""
104
+ fired = []
105
+
106
+ if f["smart_punct"]:
107
+ fired.append("unicode_punctuation")
108
+ if f["ai_style_comments"] >= 3:
109
+ fired.append("ai_narration_comments")
110
+ if f["mixed_indent"]:
111
+ fired.append("mixed_indentation")
112
+ if f["comment_ratio"] > 0.30:
113
+ fired.append("heavy_commenting")
114
+ if f["has_docstring"] and f["has_type_hints"]:
115
+ fired.append("production_style")
116
+ if f["snake_ratio"] > 0.25 and f["camel_ratio"] > 0.25:
117
+ fired.append("inconsistent_naming")
118
+ if f["lines"] > 15 and f["stdev_line_len"] < 6:
119
+ fired.append("uniform_line_lengths")
120
+ if f["crlf"]:
121
+ fired.append("crlf_endings")
122
+
123
+ score = min(100, sum(SIGNAL_WEIGHTS[s][0] for s in fired))
124
+ return score, [
125
+ {"code": s, "weight": SIGNAL_WEIGHTS[s][0], "detail": SIGNAL_WEIGHTS[s][1]}
126
+ for s in fired
127
+ ]
labels.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Label taxonomy and the coarse-grained collapses.
2
+
3
+ Kept out of `detector.py` so it imports without torch — same reason
4
+ `forensics.py` is its own module. `test_collapse.py` exercises it directly.
5
+
6
+ DroidDetect predicts four classes. Two coarser views are more useful to a human
7
+ moderator, and the Droid paper reports accuracy at each level (Large: ~97%
8
+ weighted F1 binary, ~88.8% ternary — the full 4-way split is the hardest,
9
+ because "adversarial" and "generated" are the same text with different styling).
10
+ """
11
+
12
+ LABELS = [
13
+ "HUMAN_GENERATED",
14
+ "MACHINE_GENERATED",
15
+ "MACHINE_REFINED",
16
+ "MACHINE_GENERATED_ADVERSARIAL",
17
+ ]
18
+
19
+ # "Who actually wrote this": the participant, a model, or both.
20
+ # MACHINE_GENERATED_ADVERSARIAL folds into MACHINE — model output styled to look
21
+ # hand-written is still model output.
22
+ TERNARY_OF = {
23
+ "HUMAN_GENERATED": "HUMAN",
24
+ "MACHINE_GENERATED": "MACHINE",
25
+ "MACHINE_GENERATED_ADVERSARIAL": "MACHINE",
26
+ "MACHINE_REFINED": "REFINED",
27
+ }
28
+ TERNARY_LABELS = ["HUMAN", "MACHINE", "REFINED"]
29
+
30
+ # The yes/no the old CodeT5+ Space returned.
31
+ BINARY_OF = {
32
+ "HUMAN_GENERATED": "HUMAN",
33
+ "MACHINE_GENERATED": "MACHINE",
34
+ "MACHINE_GENERATED_ADVERSARIAL": "MACHINE",
35
+ "MACHINE_REFINED": "MACHINE",
36
+ }
37
+ BINARY_LABELS = ["HUMAN", "MACHINE"]
38
+
39
+ TERNARY_MEANING = {
40
+ "HUMAN": "Written by the participant",
41
+ "MACHINE": "Model-written (including output styled to look hand-typed)",
42
+ "REFINED": "Participant started it, a model completed or rewrote it",
43
+ }
44
+
45
+
46
+ def collapse(probs, mapping, order):
47
+ """Sum a 4-class distribution into a coarser one.
48
+
49
+ Returns (coarse_probs, top_label, top_confidence).
50
+
51
+ Summing is the correct collapse because the four classes are mutually
52
+ exclusive outcomes of one softmax. It also fixes a real failure of the raw
53
+ argmax: when a model's output is genuinely ambiguous between "generated"
54
+ and "adversarial", each class can sit below a human plurality while their
55
+ sum is decisively machine. e.g. 0.40 human vs 0.31 + 0.27 machine — the
56
+ 4-way argmax says HUMAN, the ternary correctly says MACHINE at 0.58.
57
+ """
58
+ out = {k: 0.0 for k in order}
59
+ for label, p in probs.items():
60
+ out[mapping[label]] += p
61
+ out = {k: round(v, 6) for k, v in out.items()}
62
+ top = max(out, key=out.get)
63
+ return out, top, out[top]
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CPU wheels. See DEPLOY.md if you want to shrink the image further by pinning
2
+ # an explicit `torch==X.Y.Z+cpu` once you know which version the build resolved.
3
+ --extra-index-url https://download.pytorch.org/whl/cpu
4
+ torch
5
+ # ModernBERT support landed in transformers 4.48 — DroidDetect will not load
6
+ # on anything older, so this floor is a hard requirement, not a preference.
7
+ transformers>=4.48
8
+ huggingface_hub>=0.26
9
+ safetensors
10
+ # NOTE: gradio is intentionally absent. On a Space the SDK version in
11
+ # README.md's frontmatter provides it, and listing it here can fight that.
12
+ # For a local run: pip install -r requirements.txt gradio
smoke_test.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """First-run check: does the detector work, and which pooling does it want?
2
+
3
+ The checkpoint does not record how the encoder's token states are collapsed
4
+ before the classifier head, and the model card does not say. This runs four
5
+ labelled submissions through both options and reports which one recovers the
6
+ expected labels. Set POOLING to the winner and you are done.
7
+
8
+ python smoke_test.py
9
+
10
+ Takes about a minute on the free CPU tier (most of it the one-time download).
11
+ """
12
+
13
+ from detector import (
14
+ REPO,
15
+ TERNARY_LABELS,
16
+ TERNARY_OF,
17
+ classify,
18
+ collapse,
19
+ load_model,
20
+ )
21
+
22
+ # (name, code, expected label). Deliberately unambiguous cases — if the model
23
+ # cannot separate these, the wiring is wrong, not the model.
24
+ CASES = [
25
+ (
26
+ "terse contest code",
27
+ """
28
+ import sys
29
+ input=sys.stdin.readline
30
+ n,k=map(int,input().split())
31
+ a=list(map(int,input().split()))
32
+ a.sort()
33
+ l,r=0,10**18
34
+ while l<r:
35
+ m=(l+r)//2
36
+ c=0
37
+ for x in a:
38
+ c+=min(x,m)
39
+ if c>=k*m: l=m+1
40
+ else: r=m
41
+ print(l-1)
42
+ """,
43
+ "HUMAN_GENERATED",
44
+ ),
45
+ (
46
+ "chat-assistant answer",
47
+ '''
48
+ from typing import List
49
+
50
+
51
+ def max_distribution(candies: List[int], children: int) -> int:
52
+ """
53
+ Find the maximum number of candies each child can receive.
54
+
55
+ Args:
56
+ candies: A list of integers representing pile sizes.
57
+ children: The number of children to distribute to.
58
+
59
+ Returns:
60
+ The maximum equal amount each child can receive.
61
+ """
62
+ # Handle the edge case where there is nothing to distribute
63
+ if not candies or children <= 0:
64
+ return 0
65
+
66
+ # Binary search over the possible answer space
67
+ left, right = 0, max(candies)
68
+
69
+ while left < right:
70
+ # Calculate the midpoint of the current search range
71
+ mid = (left + right + 1) // 2
72
+
73
+ # Count how many children can be served with this amount
74
+ total = sum(pile // mid for pile in candies)
75
+
76
+ if total >= children:
77
+ left = mid
78
+ else:
79
+ right = mid - 1
80
+
81
+ return left
82
+
83
+
84
+ if __name__ == "__main__":
85
+ print(max_distribution([5, 8, 6], 3))
86
+ ''',
87
+ "MACHINE_GENERATED",
88
+ ),
89
+ (
90
+ "human skeleton, model-filled body",
91
+ '''
92
+ import sys
93
+
94
+ def main():
95
+ data = sys.stdin.read().split()
96
+ n = int(data[0]); k = int(data[1])
97
+ a = [int(x) for x in data[2:2+n]]
98
+
99
+ # Binary search on the answer to find the maximum feasible size
100
+ left, right = 1, max(a)
101
+ result = 0
102
+ while left <= right:
103
+ mid = (left + right) // 2
104
+ count = sum(pile // mid for pile in a)
105
+ if count >= k:
106
+ result = mid
107
+ left = mid + 1
108
+ else:
109
+ right = mid - 1
110
+
111
+ print(result)
112
+
113
+ main()
114
+ ''',
115
+ "MACHINE_REFINED",
116
+ ),
117
+ (
118
+ "model output stripped to look hand-typed",
119
+ """
120
+ import sys
121
+ def main():
122
+ d=sys.stdin.read().split()
123
+ n=int(d[0]);k=int(d[1])
124
+ a=[int(x) for x in d[2:2+n]]
125
+ lo,hi=1,max(a)
126
+ res=0
127
+ while lo<=hi:
128
+ mid=(lo+hi)//2
129
+ cnt=0
130
+ for p in a:
131
+ cnt+=p//mid
132
+ if cnt>=k:
133
+ res=mid
134
+ lo=mid+1
135
+ else:
136
+ hi=mid-1
137
+ print(res)
138
+ main()
139
+ """,
140
+ "MACHINE_GENERATED_ADVERSARIAL",
141
+ ),
142
+ ]
143
+
144
+
145
+ def run():
146
+ print(f"repo : {REPO}")
147
+ load_model()
148
+ print("model loaded\n")
149
+
150
+ # Scored on the TERNARY collapse, not the raw 4-way. Separating
151
+ # "adversarial" from ordinary machine output is the split the model is
152
+ # weakest at, so grading pooling on it would be measuring the wrong thing —
153
+ # and ternary is the level we actually report to moderators.
154
+ scores = {}
155
+ for pooling in ("mean", "cls"):
156
+ hits = 0
157
+ print(f"=== POOLING={pooling} ===")
158
+ for name, code, expected in CASES:
159
+ probs, embedding, tokens, _ = classify(code, pooling=pooling)
160
+ predicted = max(probs, key=probs.get)
161
+ t_probs, t_label, t_conf = collapse(probs, TERNARY_OF, TERNARY_LABELS)
162
+ want = TERNARY_OF[expected]
163
+ ok = t_label == want
164
+ hits += ok
165
+ print(
166
+ f" [{'ok ' if ok else 'MISS'}] {name:<38} "
167
+ f"ternary={t_label:<8} ({t_conf:.2f}) want={want:<8} "
168
+ f"4-way={predicted:<30} "
169
+ f"({tokens} tok, emb {len(embedding)}d)"
170
+ )
171
+ scores[pooling] = hits
172
+ print(f" {hits}/{len(CASES)} ternary labels recovered\n")
173
+
174
+ best = max(scores, key=scores.get)
175
+ if scores[best] == 0:
176
+ print("Both poolings scored 0 — the head is mis-wired, not mis-pooled.")
177
+ print("Check that load_state_dict ran with strict=True and did not throw.")
178
+ return
179
+
180
+ if scores["mean"] == scores["cls"]:
181
+ print(
182
+ f"Tie at {scores[best]}/{len(CASES)}. Keep the default "
183
+ "(POOLING=mean) and re-check against real submissions from a past "
184
+ "event, where you know who wrote what."
185
+ )
186
+ return
187
+
188
+ print(f"Set POOLING={best} on the Space ({scores[best]}/{len(CASES)} correct).")
189
+
190
+
191
+ if __name__ == "__main__":
192
+ run()
test_auth.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-check for the API-token guard. No torch, no gradio, instant.
2
+
3
+ python test_auth.py
4
+
5
+ This is the only thing standing between the open internet and free inference on
6
+ your Space, so it gets a test. It reads the real `API_TOKEN` literal and the
7
+ real guard condition out of `app.py`, rather than a copy that could drift.
8
+
9
+ Regression covered: an earlier edit wrote
10
+ `API_TOKEN = os.environ.get("<the-token>")`, passing the token as the *variable
11
+ name*. That returns None, which broke every real request AND let a `null` token
12
+ authenticate, since `None != None` is false.
13
+ """
14
+
15
+ import ast
16
+ import hmac
17
+
18
+ SRC = "app.py"
19
+
20
+
21
+ def api_token():
22
+ """The API_TOKEN literal from app.py. Fails loudly if it isn't a literal."""
23
+ tree = ast.parse(open(SRC, encoding="utf-8").read())
24
+ for n in tree.body:
25
+ if isinstance(n, ast.Assign) and any(
26
+ getattr(t, "id", "") == "API_TOKEN" for t in n.targets
27
+ ):
28
+ if not isinstance(n.value, ast.Constant) or not isinstance(
29
+ n.value.value, str
30
+ ):
31
+ raise AssertionError(
32
+ "API_TOKEN must be a plain string literal — an "
33
+ "os.environ.get() with no default silently yields None, "
34
+ "which breaks auth open for a null token."
35
+ )
36
+ return n.value.value
37
+ raise AssertionError("no API_TOKEN assignment found in app.py")
38
+
39
+
40
+ def main():
41
+ token = api_token()
42
+ assert len(token) >= 32, f"API_TOKEN is only {len(token)} chars — too short"
43
+ print(f"API_TOKEN is a {len(token)}-char literal ✓")
44
+
45
+ def guard(t):
46
+ """Verbatim condition from detect()."""
47
+ return isinstance(t, str) and hmac.compare_digest(t, token)
48
+
49
+ cases = [
50
+ (token, True, "correct token"),
51
+ (None, False, "null token (the historical bypass)"),
52
+ ("", False, "empty string"),
53
+ ("wrong-token", False, "wrong token"),
54
+ (token[:-1], False, "token missing last char"),
55
+ (token + "x", False, "token with extra char"),
56
+ (token.upper(), False, "case-flipped token"),
57
+ (12345, False, "numeric token"),
58
+ ([token], False, "token wrapped in a list"),
59
+ ({"t": token}, False, "token as an object"),
60
+ ]
61
+
62
+ bad = 0
63
+ for tok, want, note in cases:
64
+ got = guard(tok)
65
+ ok = got == want
66
+ bad += not ok
67
+ print(f" [{'ok ' if ok else 'FAIL'}] {note:<38} accepted={got}")
68
+
69
+ if bad:
70
+ raise SystemExit(f"\n{bad} auth case(s) FAILED")
71
+ print("\nauth guard self-check OK")
72
+
73
+
74
+ if __name__ == "__main__":
75
+ main()
test_collapse.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-check for the ternary/binary collapse. No torch, no model, instant.
2
+
3
+ python test_collapse.py
4
+
5
+ This is the layer moderators actually read, so a bug here is a bug in every
6
+ verdict the Space reports.
7
+ """
8
+
9
+ from labels import (
10
+ BINARY_LABELS,
11
+ BINARY_OF,
12
+ LABELS,
13
+ TERNARY_LABELS,
14
+ TERNARY_MEANING,
15
+ TERNARY_OF,
16
+ collapse,
17
+ )
18
+
19
+
20
+ def check(probs, want_ternary, want_binary, note):
21
+ assert abs(sum(probs.values()) - 1) < 1e-6, f"{note}: fixture isn't a distribution"
22
+ t, tl, tc = collapse(probs, TERNARY_OF, TERNARY_LABELS)
23
+ b, bl, bc = collapse(probs, BINARY_OF, BINARY_LABELS)
24
+ assert abs(sum(t.values()) - 1) < 1e-6, f"{note}: ternary not normalised: {t}"
25
+ assert abs(sum(b.values()) - 1) < 1e-6, f"{note}: binary not normalised: {b}"
26
+ assert tl == want_ternary, f"{note}: ternary {tl} != {want_ternary}"
27
+ assert bl == want_binary, f"{note}: binary {bl} != {want_binary}"
28
+ print(f" ok {note:<46} ternary={tl:<8}({tc:.2f}) binary={bl}({bc:.2f})")
29
+
30
+
31
+ def main():
32
+ # Every 4-way class must map into both coarser taxonomies, or a real
33
+ # prediction would KeyError at request time.
34
+ assert set(TERNARY_OF) == set(LABELS), "a class is missing a ternary mapping"
35
+ assert set(BINARY_OF) == set(LABELS), "a class is missing a binary mapping"
36
+ assert set(TERNARY_OF.values()) <= set(TERNARY_LABELS)
37
+ assert set(BINARY_OF.values()) <= set(BINARY_LABELS)
38
+ assert set(TERNARY_MEANING) == set(TERNARY_LABELS), "a ternary label has no blurb"
39
+
40
+ check(
41
+ {"HUMAN_GENERATED": 0.80, "MACHINE_GENERATED": 0.10,
42
+ "MACHINE_REFINED": 0.06, "MACHINE_GENERATED_ADVERSARIAL": 0.04},
43
+ "HUMAN", "HUMAN", "clearly human",
44
+ )
45
+ check(
46
+ {"HUMAN_GENERATED": 0.18, "MACHINE_GENERATED": 0.09,
47
+ "MACHINE_REFINED": 0.71, "MACHINE_GENERATED_ADVERSARIAL": 0.02},
48
+ "REFINED", "MACHINE", "refined keeps its own ternary class",
49
+ )
50
+ # The case that justifies collapsing at all: machine mass split across two
51
+ # classes loses the 4-way argmax to a human plurality, but summed it wins.
52
+ check(
53
+ {"HUMAN_GENERATED": 0.40, "MACHINE_GENERATED": 0.31,
54
+ "MACHINE_REFINED": 0.02, "MACHINE_GENERATED_ADVERSARIAL": 0.27},
55
+ "MACHINE", "MACHINE", "split machine mass beats a human plurality",
56
+ )
57
+ check(
58
+ {"HUMAN_GENERATED": 0.05, "MACHINE_GENERATED": 0.10,
59
+ "MACHINE_REFINED": 0.05, "MACHINE_GENERATED_ADVERSARIAL": 0.80},
60
+ "MACHINE", "MACHINE", "adversarial folds into MACHINE",
61
+ )
62
+ # Refined must NOT absorb machine mass at the ternary level — the whole
63
+ # point is telling "co-written" apart from "model-written".
64
+ check(
65
+ {"HUMAN_GENERATED": 0.10, "MACHINE_GENERATED": 0.55,
66
+ "MACHINE_REFINED": 0.30, "MACHINE_GENERATED_ADVERSARIAL": 0.05},
67
+ "MACHINE", "MACHINE", "refined stays separate from generated",
68
+ )
69
+
70
+ print("\ncollapse self-check OK")
71
+
72
+
73
+ if __name__ == "__main__":
74
+ main()
test_forensics.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-check for the static forensics layer. Run: python3 test_forensics.py"""
2
+
3
+ from forensics import forensic_signals, static_features
4
+
5
+ TYPED_BY_HAND = """\
6
+ n = int(input())
7
+ a = list(map(int, input().split()))
8
+ best = 0
9
+ for i in range(n):
10
+ s = 0
11
+ for j in range(i, n):
12
+ s += a[j]
13
+ if s > best: best = s
14
+ print(best)
15
+ """
16
+
17
+ PASTED_FROM_CHAT = """\
18
+ def max_subarray_sum(arr: list) -> int:
19
+ \"\"\"Return the maximum subarray sum using Kadane’s algorithm.\"\"\"
20
+ # Step 1: initialize the running and best totals
21
+ current_sum = 0
22
+ best_sum = arr[0]
23
+ # Step 2: iterate through the array
24
+ for value in arr:
25
+ # Step 3: extend the window or start a new one
26
+ current_sum = max(value, current_sum + value)
27
+ # Step 4: update the best total seen so far
28
+ best_sum = max(best_sum, current_sum)
29
+ return best_sum
30
+ """
31
+
32
+
33
+ def run():
34
+ typed = static_features(TYPED_BY_HAND)
35
+ pasted = static_features(PASTED_FROM_CHAT)
36
+
37
+ assert typed["smart_punct"] == 0
38
+ assert pasted["smart_punct"] == 1, "curly apostrophe should be caught"
39
+ assert pasted["ai_style_comments"] >= 3, pasted["ai_style_comments"]
40
+ assert typed["ai_style_comments"] == 0
41
+ assert typed["single_char_ratio"] > pasted["single_char_ratio"]
42
+
43
+ typed_score, typed_signals = forensic_signals(typed)
44
+ pasted_score, pasted_signals = forensic_signals(pasted)
45
+ assert typed_score == 0, typed_signals
46
+ assert pasted_score >= 60, (pasted_score, pasted_signals)
47
+ assert {s["code"] for s in pasted_signals} >= {
48
+ "unicode_punctuation",
49
+ "ai_narration_comments",
50
+ }
51
+
52
+ # Indentation forensics: a snippet that mixes tabs and spaces was assembled.
53
+ mixed = static_features("def f():\n\tx = 1\n y = 2\n return x\n")
54
+ assert mixed["mixed_indent"] is True
55
+ assert "mixed_indentation" in {s["code"] for s in forensic_signals(mixed)[1]}
56
+
57
+ # Empty input must not divide by zero.
58
+ assert static_features("")["lines"] == 0
59
+
60
+ print("forensics self-check OK")
61
+
62
+
63
+ if __name__ == "__main__":
64
+ run()