"""Authorship detector with Unicode offsets into raw_text and cleaned text.""" import argparse from datetime import date import json import pathlib import re import sys import unicodedata import numpy as np import torch # Hub cache scripts are symlinks to blobs. Their siblings live in the snapshot. _runtime_dir = str(pathlib.Path(__file__).absolute().parent) if _runtime_dir not in sys.path: sys.path.insert(0, _runtime_dir) from corpus_text import word_count from raw_offsets import View, join, visible from language import document_language REPO = "CoderBak/anagram-detectors" LABELS = ("human", "ai_assisted", "ai_generated") _RULES = [ (re.compile("[\u2018\u2019\u201a\u2032]"), "'"), # curly single quotes (re.compile("[\u201c\u201d\u201e\u2033]"), '"'), # curly double quotes (re.compile("\\s*\u2014\\s*"), " -- "), # em dash (re.compile("(?<=\\w)\u2013(?=\\w)"), "-"), # en dash in ranges: 1990-1995 (re.compile("\\s*\u2013\\s*"), " - "), (re.compile("\u2026"), "..."), # ellipsis character (re.compile("[\u00a0\u2009\u202f]"), " "), # non-breaking and thin spaces (re.compile("[\u200b\u200c\u200d\ufeff]"), ""), # zero-width characters ] _RULES.extend([(re.compile(r"[ \t]+\n"), "\n"), (re.compile(r"[ \t]{2,}"), " "), (re.compile(r"\n{3,}"), "\n\n")]) def normalize(text): text = unicodedata.normalize("NFC", text) for pattern, replacement in _RULES: text = pattern.sub(replacement, text) return text.strip() def normalize_view(view): """Apply the checkpoint typography rules while tracing surviving source characters.""" def replacement(match, value): left, right = match.span() part = view.slice(left, right) if value in (" -- ", " - "): dash = left + match[0].index("—" if value == " -- " else "–") before = view.slice(dash-1, dash).as_glyph(" ") if dash > left else View(" ") after = view.slice(dash+1, dash+2).as_glyph(" ") if dash+1 < right else View(" ") return join([before, view.slice(dash, dash+1).as_glyph(value.strip()), after]) if not value: return View("") if value == "\n": return view.slice(right-1, right) if value == "\n\n": return view.slice(left, left+2) if value == " " and right-left > 1: return view.slice(left, left+1).as_glyph(" ") return part.as_glyph(value) for pattern, value in _RULES: view = view.substitute((m.start(), m.end(), replacement(m, value)) for m in pattern.finditer(view.text) if m[0] != value) return view.strip() _RAW_LABELS = ("na", "human", "AA", "AG") # Each bit records a contributing label. A conflicting assignment is unassessed. _MASK_TO_LABEL = np.array([0, 1, 2, 0, 3, 0, 0, 0], dtype=np.uint8) def raw_segments(view, raw_length, chars, boundaries): """Project displayed CRF labels back onto a complete partition of the original.""" def span(a, b, index): return {"start": int(a), "end": int(b), "label": _RAW_LABELS[int(index)]} if len(view.runs) == 1: a, b, start, end, linear = view.runs[0] if linear and a == 0 and b == len(chars): # Plain prose (optionally trimmed) needs only one operation per displayed segment. result = [span(0, start, 0)] if start else [] result.extend(span(start+x, start+y, chars[x]+1) for x, y in zip(boundaries[:-1], boundaries[1:])) if end < raw_length: result.append(span(end, raw_length, 0)) return result evidence = np.zeros(raw_length, dtype=np.uint8) bits = np.left_shift(np.uint8(1), chars.astype(np.uint8)) for a, b, start, end, linear in view.runs: if linear: evidence[start:end] |= bits[a:b] else: evidence[start:end] |= np.bitwise_or.reduce(bits[a:b]) labels = _MASK_TO_LABEL[evidence] cuts = np.r_[0, np.flatnonzero(np.diff(labels)) + 1, raw_length] return [span(a, b, labels[a]) for a, b in zip(cuts[:-1], cuts[1:]) if a < b] _BUCKETS = np.arange(15) / 14 # the segment head's buckets, as AI fractions from 0 to 1 _PHI = np.stack([np.maximum(0, 1 - 2 * _BUCKETS), np.maximum(0, 1 - 2 * np.abs(_BUCKETS - 0.5)), np.maximum(0, 2 * _BUCKETS - 1)]) # each bucket's weight on human / AI-assisted / AI-generated _SENTENCE_END = re.compile("[.!?\u2026]+[\\\"'\u201d\u2019)\\]]*(?=\\s|$)|\\n\\s*\\n") def _windows(n, window, stride): if n <= 0: return [] if n <= window: return [(0, n)] starts = list(range(0, n - window + 1, stride)) if starts[-1] != n - window: starts.append(n - window) return [(s, s + window) for s in starts] def _unary(x, crf): return x @ np.asarray(crf["W"]).T + np.asarray(crf["alpha"]) + np.asarray(crf["delta"]) def decode(unary, mixed, lam, gamma): """Numerically stable three-state CRF with the deployed decoder's tie rule.""" n = len(unary) score = unary[0].copy() path = np.empty(n, np.int8) back = np.zeros((n, 3), np.int8) forward = np.zeros((n, 3)) forward[0] = unary[0] backward = np.zeros((n, 3)) for i in range(1, n): cost = min(0.0, -lam + gamma * (mixed[i - 1] + mixed[i]) / 2) future = np.empty(3) for k in range(3): first, second = (1, 2) if k == 0 else (0, 2) if k == 1 else (0, 1) alternative = first if score[first] >= score[second] else second take = k if score[k] >= score[alternative] + cost else alternative back[i, k] = take future[k] = unary[i, k] + score[take] + (0.0 if take == k else cost) alt_log = np.logaddexp(forward[i - 1, first], forward[i - 1, second]) forward[i, k] = unary[i, k] + np.logaddexp(forward[i - 1, k], alt_log + cost) score = future current = np.argmax(score) for i in range(n - 1, -1, -1): path[i] = current current = back[i, current] for i in range(n - 2, -1, -1): cost = min(0.0, -lam + gamma * (mixed[i] + mixed[i + 1]) / 2) step = unary[i + 1] + backward[i + 1] for k in range(3): first, second = (1, 2) if k == 0 else (0, 2) if k == 1 else (0, 1) alt_log = np.logaddexp(step[first], step[second]) backward[i, k] = np.logaddexp(step[k], alt_log + cost) probabilities = forward + backward for i in range(n): normalizer = np.logaddexp(np.logaddexp(probabilities[i, 0], probabilities[i, 1]), probabilities[i, 2]) probabilities[i] = np.exp(probabilities[i] - normalizer) return path, probabilities try: from numba import njit except ImportError: pass else: decode = njit(cache=True)(decode) def _sentence_ids(text, offsets): """Index of the sentence each token belongs to (by the token's middle character).""" ends = np.asarray([m.end() for m in _SENTENCE_END.finditer(text)], np.int64) middle = (offsets[:, 0] + np.maximum(offsets[:, 1] - 1, offsets[:, 0])) // 2 return np.searchsorted(ends, middle, side="right") def _sentence_vote(labels, sentence): labels = labels.copy() cut = np.flatnonzero(np.diff(sentence)) + 1 for a, b in zip(np.r_[0, cut], np.r_[cut, len(labels)]): labels[a:b] = np.bincount(labels[a:b], minlength=3).argmax() return labels def _merge_short(labels, l_min): """Merge runs shorter than l_min tokens into a neighbour (the longer one when the two neighbours differ).""" if l_min <= 1 or not len(labels): return labels cut = np.flatnonzero(np.diff(labels)) + 1 runs = [[int(labels[a]), int(b - a)] for a, b in zip(np.r_[0, cut], np.r_[cut, len(labels)])] while len(runs) > 1: i = next((k for k, (_, n) in enumerate(runs) if n < l_min), None) if i is None: break if i == 0 or i == len(runs) - 1: j = 1 if i == 0 else i - 1 elif runs[i - 1][0] == runs[i + 1][0]: j = i - 1 else: j = i - 1 if runs[i - 1][1] >= runs[i + 1][1] else i + 1 runs[j][1] += runs[i][1] del runs[i] k = 0 while k < len(runs) - 1: if runs[k][0] == runs[k + 1][0]: runs[k][1] += runs[k + 1][1] del runs[k + 1] else: k += 1 return np.repeat([r[0] for r in runs], [r[1] for r in runs]).astype(np.int8) class Detector: def __init__(self, model=None, device=None, batch_size=32, revision=None): """Load a local release or a Hub model branch such as 2026-11-14-400m-research.""" from safetensors.torch import load_file from transformers import AutoModel, AutoTokenizer if type(batch_size) is not int or batch_size < 1: raise ValueError("batch_size must be a positive integer") path = _resolve(model, revision) self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu")) self.meta = json.loads((path / "model.json").read_text()) if self.meta.get("format") != "anagram-detector/1" or tuple(self.meta["classes"]) != LABELS: raise ValueError("This runtime needs an anagram-detector/1 release with the standard class order") if self.meta["heads"] != ["token", "segment", "mixed"]: raise ValueError("This runtime supports the token, segment and mixed heads") self.release = self.meta.get("release_id") if self.release is None: self.release = f"{self.meta['release_date']}-{self.meta['size']}" if self.meta["channel"] == "internal-research-test": self.release += "-research" elif self.meta["channel"] != "release": raise ValueError("Unknown release channel") if revision and _TAG.fullmatch(revision) and revision != self.release: raise ValueError(f"Release metadata identifies {self.release}, expected {revision}") self.crf = json.loads((path / "crf.json").read_text()) self.tokenizer = AutoTokenizer.from_pretrained(path / "tokenizer") self.tokenizer.model_max_length = 10 ** 9 # windows are cut here, not by the tokenizer self.architecture = self.meta.get("architecture", "modernbert") state = load_file(path / "head.safetensors") if self.architecture == "qwen3_5_text": from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5TextModel if self.meta["copies"] != 2: raise ValueError("This Qwen detector requires two copies per window.") backbone = Qwen3_5TextModel.from_pretrained(path / "backbone", dtype=torch.bfloat16, attn_implementation="sdpa") state = {k.replace(".", "_head.", 1): v for k, v in state.items()} elif self.architecture == "modernbert": backbone = AutoModel.from_pretrained(path / "backbone", attn_implementation="sdpa").float() else: raise ValueError(f"Unsupported architecture {self.architecture}") self.backbone = backbone.to(self.device).eval() self.heads = {k: v.float().to(self.device) for k, v in state.items()} self.batch_size = batch_size def _encode_windows(self, ids, batch): lengths = np.asarray([b - a for a, b in batch], dtype=np.int64) maximum = int(lengths.max()) qwen = self.architecture == "qwen3_5_text" width = ((2 * maximum + 31) // 32) * 32 if qwen else maximum + 2 inputs = np.full((len(batch), width), self.tokenizer.pad_token_id, np.int64) for row, (a, b) in enumerate(batch): length = b - a if qwen: inputs[row, :length] = inputs[row, length:2 * length] = ids[a:b] else: inputs[row, 0] = self.tokenizer.cls_token_id inputs[row, 1:length + 1] = ids[a:b] inputs[row, length + 1] = self.tokenizer.sep_token_id input_ids = torch.as_tensor(inputs, device=self.device) lengths = torch.as_tensor(lengths, device=self.device) positions = torch.arange(width, device=self.device) if qwen: mask = positions < (2 * lengths[:, None]) hidden = self.backbone(input_ids=input_ids, attention_mask=mask, use_cache=False).last_hidden_state rows = torch.arange(len(batch), device=self.device) second = lengths[:, None] + positions[:maximum] return hidden[rows[:, None], second].float(), hidden[rows, 2 * lengths - 1].float() mask = (positions < (lengths[:, None] + 2)).long() with torch.autocast(self.device.type, dtype=torch.bfloat16, enabled=self.device.type == "cuda" and torch.cuda.is_bf16_supported()): hidden = self.backbone(input_ids=input_ids, attention_mask=mask).last_hidden_state return hidden[:, 1:-1].float(), hidden[:, 0].float() @torch.inference_mode() def _features(self, ids, observations=None): """Per token: three token logits and three segment log-priors, averaged over the windows that contain the token [N, 6], and the mixed-authorship log-odds, weighted towards each window's centre [N].""" n = len(ids) tok, seg = np.zeros((n, 3), np.float32), np.zeros((n, 3), np.float32) count, mix, mix_weight = np.zeros(n, np.float32), np.zeros(n, np.float32), np.zeros(n, np.float32) windows = _windows(n, self.meta["window"], self.meta["stride"]) linear = torch.nn.functional.linear for k in range(0, len(windows), self.batch_size): batch = windows[k:k + self.batch_size] hidden, pooled = self._encode_windows(ids, batch) token_logits = linear(hidden, self.heads["token_head.weight"]).cpu().numpy() segment = linear(pooled, self.heads["segment_head.weight"], self.heads["segment_head.bias"]) mixed = linear(pooled, self.heads["mixed_head.weight"], self.heads["mixed_head.bias"]) buckets = torch.softmax(segment, -1).cpu().numpy() prior = buckets.astype(np.float64) @ _PHI.T if observations is not None: mixed_probs = torch.softmax(mixed, -1)[:, 1].cpu().numpy() for r, (a, b) in enumerate(batch): observations.append(dict(token_start=a, token_end=b, buckets=buckets[r].tolist(), mixed_probability=float(mixed_probs[r]))) log_prior = np.log(np.maximum(prior / prior.sum(1, keepdims=True), 1e-6)).astype(np.float32) log_odds = (mixed[:, 1] - mixed[:, 0]).cpu().numpy() for r, (a, b) in enumerate(batch): size = b - a tok[a:b] += token_logits[r, :size] seg[a:b] += log_prior[r] count[a:b] += 1 centre = 1 - np.abs(np.arange(size) - (size - 1) / 2) / ((size + 1) / 2) mix[a:b] += centre * log_odds[r] mix_weight[a:b] += centre c = np.maximum(count, 1)[:, None] return np.concatenate([tok / c, seg / c], 1), mix / np.maximum(mix_weight, 1e-6) def detect(self, text, normalise=True, *, tokens=False, windows=False, source_map=False, source_id="rendered_prose"): """Score English prose. Optional detail uses the same encoder and decoder pass.""" if not isinstance(text, str): raise TypeError("text must be a string") raw_text = text status = "insufficient_text" try: prose = visible(raw_text, source_id) if normalise else View.original(raw_text) except RecursionError: # A deeply nested publisher document can exceed its parser's nesting limit. prose, status = View(""), "unparseable_text" has_prose = any(char.isalpha() for char in prose.text) and not re.fullmatch( r"\s*\[(?:removed|deleted)\]\s*", prose.text, re.IGNORECASE) words = word_count(prose.text) if has_prose else 0 analyzed = normalize_view(prose) if normalise else prose text = analyzed.text result = dict(schema_version=1, release=self.release, channel=self.meta["channel"], text=text, raw_text=raw_text, source_length=len(raw_text), word_count=words, token_length=0, raw_segments=[dict(start=0, end=len(raw_text), label="na")] if raw_text else [], status=status, language=None, prediction_short=None, verdict=None, fractions=None, human_fraction=None, ai_fraction=None, weighted_ai_fraction=None, posterior_ai_share=None, segment_counts=None, segments=[], sentences=[]) if source_map: result["source_map"] = analyzed.public_map() if tokens: result["tokens"] = [] if windows: result["windows"] = [] if words < self.meta["min_words"]: return result result["language"] = document_language(prose.text) if result["language"] != "english": result["status"] = "unsupported_language" return result enc = self.tokenizer(text, add_special_tokens=False, return_offsets_mapping=True, return_attention_mask=False, truncation=False) ids = np.asarray(enc["input_ids"], np.int32) offsets = np.asarray(enc["offset_mapping"], np.int64).reshape(-1, 2) if not len(ids): return result x, mixed = self._features(ids, result.get("windows")) unary = _unary(x, self.crf) viterbi, probabilities = decode(unary, mixed, self.crf["lambda"], self.crf["gamma"]) sentence = _sentence_ids(text, offsets) labels = _merge_short(_sentence_vote(viterbi, sentence), self.crf["l_min"]) # Each character belongs to the last token starting at or before it, including whitespace gaps. owner = np.maximum(np.searchsorted(offsets[:, 0], np.arange(len(text)), side="right") - 1, 0) chars = labels[owner] counts = np.bincount(chars, minlength=3) fractions = dict(zip(LABELS, (counts / len(text)).tolist())) nonspace = np.fromiter((not c.isspace() for c in text), bool, len(text)) weighted = fractions["ai_generated"] + 0.5 * fractions["ai_assisted"] if self.meta.get("document_fraction_basis") == "all_labeled_characters": h, aa, ag = counts.tolist() n = h + aa + ag prediction = verdict = "Human" if 10 * h >= 9 * n else "AI" if 5 * (2 * ag + aa) >= 8 * n else "Mixed" human, ai_share = fractions["human"], weighted else: solid_shares = np.bincount(chars[nonspace], minlength=3) / nonspace.sum() human, assisted, generated = solid_shares.tolist() ai_share = generated + 0.5 * assisted verdict = _verdict(human, ai_share) prediction = _verdict(fractions["human"], fractions["ai_generated"]) post_ai = probabilities[:, 2] + 0.5 * probabilities[:, 1] def span(a, b, left, right, label): marginals = probabilities[left:right] mean = marginals.mean(axis=0) return dict(start=a, end=b, text=text[a:b], word_count=word_count(text[a:b]), token_length=right-left, label=LABELS[label], probabilities=dict(zip(LABELS, mean.tolist())), ai_assistance_score=float(mean[2] + 0.5 * mean[1]), displayed_label_support=float(mean[label]), mean_token_confidence=float(marginals.max(axis=1).mean())) # Byte pieces of one Unicode character can share offsets. Token groups # follow character midpoints so every token is counted exactly once. mids = (offsets[:, 0] + np.maximum(offsets[:, 1] - 1, offsets[:, 0])) // 2 boundaries = np.r_[0, np.flatnonzero(np.diff(chars)) + 1, len(text)] token_cuts = np.searchsorted(mids, boundaries) segments = [span(int(a), int(b), int(left), int(right), int(chars[a])) for a, b, left, right in zip(boundaries[:-1], boundaries[1:], token_cuts[:-1], token_cuts[1:])] cuts = np.r_[0, np.flatnonzero(np.diff(sentence)) + 1, len(ids)] starts = [0, *offsets[cuts[1:-1], 0].tolist(), len(text)] sentences = [span(a, b, int(left), int(right), int(labels[left])) for a, b, left, right in zip(starts[:-1], starts[1:], cuts[:-1], cuts[1:])] result.update(status="assessed", token_length=len(ids), fractions=fractions, prediction_short=prediction, weighted_ai_fraction=weighted, human_fraction=human, ai_fraction=ai_share, verdict=verdict, posterior_ai_share=float(np.average(post_ai, weights=np.bincount(owner[nonspace], minlength=len(ids)))), segment_counts={label: sum(s["label"] == label for s in segments) for label in LABELS}, raw_segments=raw_segments(analyzed, len(raw_text), chars, boundaries), segments=segments, sentences=sentences) if tokens: result["tokens"] = [ dict(id=int(i), start=int(a), end=int(b), label=LABELS[label], viterbi_label=LABELS[path_label], probabilities=dict(zip(LABELS, probs.tolist())), confidence=float(probs.max()), token_logits=features[:3].tolist(), segment_log_prior=features[3:].tolist(), mixed_log_odds=float(m), unary=u.tolist()) for i, (a, b), label, path_label, probs, features, m, u in zip(ids, offsets, labels, viterbi, probabilities, x, mixed, unary) ] if windows: for window in result["windows"]: window["start"] = int(offsets[window["token_start"], 0]) window["end"] = int(offsets[window["token_end"] - 1, 1]) return result def _verdict(human_share, ai_share): return "Human" if human_share >= 0.90 else "AI" if ai_share >= 0.80 else "Mixed" _TAG = re.compile(r"(\d{4}-\d{2}-\d{2})-((?:0|[1-9]\d*)(?:\.\d+)?[mb])(-research|-[a-z][a-z0-9.-]*_research)?") def list_releases(repo=REPO): """Discover dated model branches without downloading weights.""" from huggingface_hub import HfApi releases = [] for branch in HfApi().list_repo_refs(repo).branches: match = _TAG.fullmatch(branch.name) if match: day, size, research = match.groups() try: date.fromisoformat(day) except ValueError: continue channel = "internal-research-test" if research == "-research" else "research" if research else "release" releases.append(dict(date=day, size=size, channel=channel, revision=branch.name, commit=branch.target_commit)) return sorted(releases, key=lambda r: (r["date"], r["size"]), reverse=True) def _resolve(model, revision): if model is not None and pathlib.Path(model).is_dir(): if revision or not (pathlib.Path(model) / "model.json").is_file(): raise ValueError("Pass a local checkpoint folder containing model.json, or select a Hub model branch.") return pathlib.Path(model) if revision == "main": raise ValueError("Select a dated model branch with --revision, or use --list to discover models.") from huggingface_hub import snapshot_download return pathlib.Path(snapshot_download(model or REPO, revision=revision or "default", allow_patterns=["model.json", "crf.json", "head.safetensors", "backbone/*", "tokenizer/*"])) def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("file", nargs="?", help="UTF-8 text file, or - for stdin") ap.add_argument("--model", help="Local release directory or Hub repository ID") ap.add_argument("--revision", help="Model branch or checkpoint commit (defaults to the default branch)") ap.add_argument("--list", action="store_true", help="List released dates and sizes") ap.add_argument("--device", help="Torch device, e.g. cpu or cuda:0") ap.add_argument("--json", action="store_true") ap.add_argument("--tokens", action="store_true") ap.add_argument("--windows", action="store_true") ap.add_argument("--source-id", default="rendered_prose", help="Corpus source ID for publisher-specific markup") ap.add_argument("--source-map", action="store_true") args = ap.parse_args() if args.list: print(json.dumps(list_releases(args.model or REPO), indent=2)) return if args.file is None: ap.error("Specify a text file or --list") data = sys.stdin.buffer.read() if args.file == "-" else pathlib.Path(args.file).read_bytes() text = data.decode("utf-8") result = Detector(args.model, args.device, revision=args.revision).detect( text, tokens=args.tokens, windows=args.windows, source_map=args.source_map, source_id=args.source_id) if args.json or args.tokens or args.windows or args.source_map: print(json.dumps(result, ensure_ascii=False, allow_nan=False)) else: print(result["prediction_short"] or result["status"]) for segment in result["raw_segments"]: excerpt = text[segment["start"]:segment["end"]] print(f"[{segment['label']}] {excerpt}") if __name__ == "__main__": main()