Release ProseGuard-ML
Browse filesFiles changed (23)
- .gitattributes+3-33
- LICENSEAdded+21
- README.mdAdded+86
- prose_guard_wasm.wasmAdded+3
- rust_src/Cargo.tomlAdded+19
- rust_src/src/cooccur_graph.rsAdded+172
- rust_src/src/diveye.rsAdded+227
- rust_src/src/gbdt.rsAdded+360
- rust_src/src/hash_tables.rsAdded+565
- rust_src/src/json_emit.rsAdded+146
- rust_src/src/lib.rsAdded+423
- rust_src/src/lm_proxy.rsAdded+858
- rust_src/src/lz_entropy.rsAdded+197
- rust_src/src/ml_features.rsAdded+255
- rust_src/src/model.rsAdded+484
- rust_src/src/stylometry.rsAdded+573
- rust_src/src/trained_forest.rsAdded+156
- rust_src/src/watermark.rsAdded+173
- rust_src/src/weights/gbdt_forest.binAdded+3
- rust_src/src/weights/ml_tables.binAdded+3
- wasm-loader.jsAdded
- weights/gbdt_forest.binAdded+3
- weights/ml_tables.binAdded+3
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text12345*.safetensors filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021MIT License
Copyright (c) 2026 Ryan Kung, Ryan Institute of Science and Technology (rist.edu.rs)
Permission is hereby granted, free of charge, to any person obtaining a copyof this software, model weights, and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586[`ElderRyan/ProseGuard-mmBERT-base`](https://huggingface.co/ElderRyan/ProseGuard-mmBERT-base)[`ElderRyan/ProseGuard-mmBERT-small`](https://huggingface.co/ElderRyan/ProseGuard-mmBERT-small)---license: mitlanguage: - en - zh - japipeline_tag: text-classificationlibrary_name: generictags: - ai-detection - machine-generated-text - stylometry - webassembly - rust - lightgbm - treeshap---
# ProseGuard-ML
**ProseGuard-ML** is a zero-dependency Rust and WebAssembly engine for client-side AI-generated text detection and sentence-level attribution across English, Simplified Chinese, Traditional Chinese, and Japanese.
The entire compiled binary and quantized statistical parameters fit in **679 KiB** (`prose_guard_wasm.wasm`, **389 KiB** gzipped) and execute locally in **2.5 to 6.8 ms** per document with zero network uploads.
* **Live Demo**: [https://aidetect.rist.edu.rs](https://aidetect.rist.edu.rs)* **Technical Report**: Ryan Kung, *AIDetect: Sub-Megabyte Client-Side AI Text Detection via Hashed Statistical Models, Calibrated Gradient Boosted Trees, and Exact TreeSHAP in WebAssembly* (`RIST-CS-AI-2026-03`).* **Neural Companion Models**: `ProseGuard-mmBERT-small` (distilled 22-layer multilingual encoder, `51.8 MB` Web Q4) and `ProseGuard-mmBERT-base` (`295.9 MB` INT8 ONNX).
## Architecture
`ProseGuard-ML` maps each input UTF-8 document onto a 28-dimensional feature vector backed by two immutable binary tables (`weights/ml_tables.bin` at `320 KiB` and `weights/gbdt_forest.bin` at `154 KiB`):
1. **Dual-Distribution Hashed PPM (`Dual-PPM`)**: Orders 1 to 3 hashed Markov transition log-likelihood ratios with empirical Bayes shrinkage and conditional Shannon surprisal estimation.2. **Concave Distributional Mixture MLE**: Estimates the document AI mixture fraction $\hat{\alpha} \in [0, 1]$ via damped Newton-Raphson iteration over smoothed unigram and bigram likelihoods.3. **Surprisal Rhythm & Hurst Exponent**: 9D conditional surprisal derivatives paired with a Rescaled-Range ($R/S$) Hurst exponent.4. **Word Co-occurrence Network Topology**: Local clustering coefficient and degree assortativity on sliding lexical graphs.5. **Formatting-Invariant Signed Feature-Hashed NBSVM**: 65,536-bucket Rademacher-signed sublinear TF n-gram linear scorer with zero-byte Traditional-to-Simplified CJK folding and Japanese Kana hash-salt isolation (`0x4A41_0000`).6. **Out-of-Fold LightGBM + Exact Stack-Allocated TreeSHAP**: A 115-tree calibrated gradient-boosted forest trained on disjoint folds with Isotonic + Platt tail calibration and exact path-dependent Shapley attributions in WebAssembly.
## Repository Contents
* `prose_guard_wasm.wasm`: Compiled `wasm32-unknown-unknown` release module (`679 KiB`).* `wasm-loader.js`: Self-contained ES/CommonJS loader with SHA-256 and IEEE 802.3 CRC32 verification.* `weights/ml_tables.bin`: Packed 65,536-bucket Dual-PPM, Mixture MLE, and NBSVM table (`320 KiB`).* `weights/gbdt_forest.bin`: Calibrated 115-tree LightGBM forest with node cover statistics (`154 KiB`).* `rust_src/`: Complete zero-dependency Rust source crate (`[dependencies]` in `Cargo.toml` is empty).
## Quick Start (Node.js / Browser)
```javascriptimport './wasm-loader.js';
const ProseGuard = globalThis.ProseGuardWasm;await ProseGuard.initWasmEngine();
const report = ProseGuard.analyzeArticle( 'Paste any English, Chinese, or Japanese article here for local inspection.', { genreCode: 0, sensitivityCode: 1 });
console.log({ aiPct: report.aiPct, verdict: report.verdict, mleAlphaPct: report.mleAlphaPct, sentences: report.sentences,});```
## Benchmark Comparison Across the ProseGuard Family
| Benchmark | Split Relation | `ProseGuard-ML` (`679 KB` WASM) | `ProseGuard-mmBERT-small` (`51.8 MB` Web Q4) | `ProseGuard-mmBERT-base` (`295.9 MB` INT8) || :--- | :--- | :---: | :---: | :---: || **`OOD-2026` (`N=700`, AUROC / `TPR@1%FPR`)** | Zero-shot for all | `0.9098` / `39.3%` | `0.9832` / `76.8%` | **`0.9987` / `100.0%`** || **`NLPCC-2025` ZH (`AUROC` / `TPR@1%FPR`)** | Zero-shot for all | `0.9647` / `58.3%` | `0.9840` / `75.5%` | **`0.9922` / `90.3%`** || **`C-ReD` ZH (`AUROC` / `TPR@1%FPR`)** | Held-out test | `0.9985` / `97.1%` | **`0.9990`** / `96.8%` | `0.9989` / **`97.5%`** || **`AnxForever` ZH Hybrid (`AUROC` / `TPR@1%FPR`)** | Held-out test | `0.9800` / `79.8%` | `0.9845` / **`83.6%`** | **`0.9847`** / `75.5%` || **`RAID + MAGE` EN Attacks (`AUROC` / `TPR@1%FPR`)** | Held-out test | `0.8272` / `44.5%` | **`0.8975` / `53.9%`** | `0.8621` / `50.7%` || **Single-Article CPU Latency** | Apple M1 Max | **`2.5 - 6.8 ms`** | `214 ms` (`~35 ms` WebGPU) | `247 ms` |
## Limitations
Without deep transformer representations, sub-megabyte n-gram and rhythm models miss unseen frontier generators that deliberately suppress standard transition templates and vary sentence cadence (such as `Claude Opus 5` in `OOD-2026`). For high-stakes verification against frontier models, pair `ProseGuard-ML` as a fast first-pass filter with `ProseGuard-mmBERT-small` or `ProseGuard-mmBERT-base`.
## License
Released under the [MIT License](LICENSE).123version https://git-lfs.github.com/spec/v1oid sha256:60f4bd7ec5abba758146eba58c6a30faf1cb1d4cc489edda26fb4b01addc0a83size 69544812345678910111213141516171819[package]name = "prose_guard_wasm"version = "1.0.0"edition = "2021"description = "Zero-dependency Rust + WebAssembly AI-Generated Article Detection Engine (ZipPy LZ77 Entropy, Binoculars Cross-Entropy Surrogate, Burstiness Cadence, GLTR Lexical Predictability & Unicode Watermark Forensics)"license = "MIT"
[lib]crate-type = ["cdylib", "rlib"]
# ZERO external dependencies to eliminate Cargo supply-chain attack surface and keep Wasm binary compact (< 65 KB).[dependencies]
[profile.release]opt-level = 3lto = truecodegen-units = 1panic = "abort"strip = true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172//! Word & Ideographic Bigram Co-occurrence Complex Network Topology (`cooccur_graph`).//!//! Basis: Models lexical adjacency inside a single document as a bounded undirected graph//! $G = (V, E)$ ($|V| \le 384$) and extracts topological invariants (local clustering coefficient,//! Newman degree assortativity, edge density, and hub dominance) invariant to synonym substitution.
use std::collections::{BTreeMap, BTreeSet};
/// Topological invariants of a document's lexical co-occurrence graph.#[derive(Debug, Clone, Copy)]pub struct CooccurGraphMetrics { /// Watts-Strogatz mean local clustering coefficient $C \in [0, 1]$. pub clustering_coeff: f64, /// Newman degree assortativity coefficient $r \in [-1, 1]$. pub degree_assortativity: f64, /// Undirected edge-to-vertex ratio $|E| / |V|$. pub edge_density: f64, /// Maximum node degree divided by mean node degree $\max_v d_v / \bar{d}$. pub hub_dominance: f64,}
impl Default for CooccurGraphMetrics { fn default() -> Self { Self { clustering_coeff: 0.12, degree_assortativity: -0.05, edge_density: 1.5, hub_dominance: 2.5, } }}
/// Builds a bounded co-occurrence network (window radius 2, up to `384` unique content tokens)/// and computes its four structural invariants in deterministic $O(N)$ time.#[must_use]pub fn analyze_cooccurrence_graph(tokens: &[String]) -> CooccurGraphMetrics { const MAX_NODES: usize = 384; if tokens.len() < 6 { return CooccurGraphMetrics::default(); }
let mut vocab: BTreeMap<&str, usize> = BTreeMap::new(); let mut seq: Vec<usize> = Vec::with_capacity(tokens.len().min(2_400));
for tok in tokens.iter().take(2_400) { if tok.chars().count() < 2 { continue; } let next_id = vocab.len(); let node_id = if let Some(&existing) = vocab.get(tok.as_str()) { existing } else if next_id < MAX_NODES { vocab.insert(tok.as_str(), next_id); next_id } else { continue; }; seq.push(node_id); }
let v_count = vocab.len(); if v_count < 5 || seq.len() < 5 { return CooccurGraphMetrics::default(); }
let mut adj: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); v_count]; let mut edges: Vec<(usize, usize)> = Vec::new();
for (idx, &u) in seq.iter().enumerate() { for step in 1..=2usize { let Some(&v) = seq.get(idx + step) else { continue; }; if u == v { continue; } let (a, b) = if u < v { (u, v) } else { (v, u) }; let inserted = if let Some(neighbors) = adj.get_mut(a) { neighbors.insert(b) } else { false }; if inserted { if let Some(neighbors_b) = adj.get_mut(b) { neighbors_b.insert(a); } edges.push((a, b)); } } }
if edges.is_empty() { return CooccurGraphMetrics::default(); }
let degrees: Vec<usize> = adj.iter().map(BTreeSet::len).collect(); let mean_deg = (degrees.iter().copied().sum::<usize>() as f64) / (v_count as f64); let max_deg = degrees.iter().copied().max().unwrap_or(1) as f64; let hub_dominance = max_deg / mean_deg.max(0.5); let edge_density = (edges.len() as f64) / (v_count as f64);
let clustering_coeff = compute_mean_clustering(&adj); let degree_assortativity = compute_assortativity(&edges, °rees);
CooccurGraphMetrics { clustering_coeff, degree_assortativity, edge_density, hub_dominance, }}
fn compute_mean_clustering(adj: &[BTreeSet<usize>]) -> f64 { let mut sum_c = 0.0f64; let mut eligible = 0usize; for neighbors in adj { let k = neighbors.len(); if !(2..=48).contains(&k) { continue; } let nb_vec: Vec<usize> = neighbors.iter().copied().collect(); let mut triangles = 0usize; for (i, &u) in nb_vec.iter().enumerate() { let Some(u_set) = adj.get(u) else { continue; }; for &w in nb_vec.get(i + 1..).unwrap_or(&[]) { if u_set.contains(&w) { triangles = triangles.saturating_add(1); } } } let possible = k * (k - 1) / 2; if possible > 0 { sum_c += (triangles as f64) / (possible as f64); eligible = eligible.saturating_add(1); } } if eligible == 0 { 0.0 } else { (sum_c / (eligible as f64)).clamp(0.0, 1.0) }}
fn compute_assortativity(edges: &[(usize, usize)], degrees: &[usize]) -> f64 { if edges.len() < 3 { return 0.0; } let m = edges.len() as f64; let mut sum_jk = 0.0f64; let mut sum_j_plus_k = 0.0f64; let mut sum_j2_plus_k2 = 0.0f64;
for &(u, v) in edges { let j = degrees.get(u).copied().unwrap_or(1) as f64; let k = degrees.get(v).copied().unwrap_or(1) as f64; sum_jk += j * k; sum_j_plus_k += 0.5 * (j + k); sum_j2_plus_k2 += 0.5 * (j * j + k * k); }
let mean_half = sum_j_plus_k / m; let sq_term = mean_half * mean_half; let num = (sum_jk / m) - sq_term; let den = (sum_j2_plus_k2 / m) - sq_term; if den.abs() <= 1e-9 { 0.0 } else { (num / den).clamp(-1.0, 1.0) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227//! DivEye 9-Dimensional Surprisal Time-Series Dynamics (Basani & Chen, TMLR 2026) and//! Rescaled-Range ($R/S$) Fractal Hurst Exponent (`diveye`).//!//! Basis: Captures higher-order temporal fluctuations in conditional surprisal $s_1, \dots, s_T$//! (distributional shape, first/second-order discrete derivatives, serial autocorrelation,//! rhythm entropy, and multi-scale long-range memory) orthogonal to mean cross-entropy.
/// Summary of higher-order surprisal time-series features for a document.#[derive(Debug, Clone, Copy)]pub struct DivEyeProfile { /// First moment $\mu_s$ (mean human conditional surprisal in bits). pub mean: f64, /// Standard deviation $\sigma_s$. pub std_dev: f64, /// Coefficient of variation $\sigma_s / \mu_s$. pub cv: f64, /// Standardized third central moment (skewness $\gamma_1$). pub skewness: f64, /// Standardized fourth central moment minus 3 (excess kurtosis $\gamma_2$). pub excess_kurtosis: f64, /// Mean absolute first-order difference $\frac{1}{T-1} \sum |s_{t+1} - s_t|$. pub diff1_mean_abs: f64, /// Standard deviation of first-order differences $\sigma(\Delta s)$. pub diff1_std: f64, /// Mean absolute second-order difference (acceleration) $\frac{1}{T-2} \sum |s_{t+2} - 2s_{t+1} + s_t|$. pub diff2_mean_abs: f64, /// Lag-1 Pearson autocorrelation $\rho_1 \in [-1, 1]$. pub autocorr_lag1: f64, /// 8-bin quantized surprisal histogram Shannon entropy in bits (`[0, 3]`). pub rhythm_entropy: f64, /// Multi-scale Rescaled-Range ($R/S$) Hurst exponent $H \in [0, 1]$. pub hurst_exponent: f64,}
impl Default for DivEyeProfile { fn default() -> Self { Self { mean: 5.0, std_dev: 1.0, cv: 0.20, skewness: 0.0, excess_kurtosis: 0.0, diff1_mean_abs: 0.8, diff1_std: 0.6, diff2_mean_abs: 1.2, autocorr_lag1: 0.0, rhythm_entropy: 2.0, hurst_exponent: 0.55, } }}
/// Computes the 9 DivEye rhythmic unpredictability features + rhythm entropy + Hurst exponent/// over a conditional surprisal sequence `s`.#[must_use]pub fn compute_diveye_profile(s: &[f64]) -> DivEyeProfile { let n = s.len(); if n < 4 { return DivEyeProfile::default(); } let nf = n as f64; let mean = s.iter().copied().sum::<f64>() / nf;
let mut m2 = 0.0f64; let mut m3 = 0.0f64; let mut m4 = 0.0f64; let mut bins = [0usize; 8]; for &x in s { let d = x - mean; let d2 = d * d; m2 += d2; m3 += d2 * d; m4 += d2 * d2; // Surprisal spans roughly [0.5, 12.5] bits -> 8 bins of width 1.5 bits let b = (((x - 0.5) / 1.5).floor().clamp(0.0, 7.0)) as usize; if let Some(slot) = bins.get_mut(b) { *slot = slot.saturating_add(1); } } let var = (m2 / nf).max(1e-9); let std_dev = var.sqrt(); let cv = std_dev / mean.max(0.25); let skewness = ((m3 / nf) / (std_dev * var)).clamp(-6.0, 6.0); let excess_kurtosis = ((m4 / nf) / (var * var) - 3.0).clamp(-3.0, 15.0);
let mut rhythm_entropy = 0.0f64; for &cnt in &bins { if cnt > 0 { let p = (cnt as f64) / nf; rhythm_entropy -= p * p.log2(); } }
let (diff1_mean_abs, diff1_std) = compute_first_differences(s); let diff2_mean_abs = compute_second_differences(s); let autocorr_lag1 = compute_lag1_autocorr(s, mean, m2); let hurst_exponent = estimate_hurst_rs(s);
DivEyeProfile { mean, std_dev, cv, skewness, excess_kurtosis, diff1_mean_abs, diff1_std, diff2_mean_abs, autocorr_lag1, rhythm_entropy, hurst_exponent, }}
fn compute_first_differences(s: &[f64]) -> (f64, f64) { let mut diffs = Vec::with_capacity(s.len().saturating_sub(1)); let mut abs_sum = 0.0f64; for pair in s.windows(2) { if let (Some(&a), Some(&b)) = (pair.first(), pair.get(1)) { let d = b - a; abs_sum += d.abs(); diffs.push(d); } } if diffs.is_empty() { return (0.0, 0.0); } let df = diffs.len() as f64; let d_mean = diffs.iter().copied().sum::<f64>() / df; let d_var = diffs.iter().map(|&d| (d - d_mean).powi(2)).sum::<f64>() / df; (abs_sum / df, d_var.sqrt())}
fn compute_second_differences(s: &[f64]) -> f64 { let mut abs_sum = 0.0f64; let mut cnt = 0usize; for win in s.windows(3) { if let (Some(&a), Some(&b), Some(&c)) = (win.first(), win.get(1), win.get(2)) { abs_sum += (c - 2.0 * b + a).abs(); cnt = cnt.saturating_add(1); } } if cnt == 0 { 0.0 } else { abs_sum / (cnt as f64) }}
fn compute_lag1_autocorr(s: &[f64], mean: f64, m2: f64) -> f64 { if m2 <= 1e-9 || s.len() < 3 { return 0.0; } let mut cov = 0.0f64; for pair in s.windows(2) { if let (Some(&a), Some(&b)) = (pair.first(), pair.get(1)) { cov += (a - mean) * (b - mean); } } (cov / m2).clamp(-1.0, 1.0)}
/// Estimates the Rescaled-Range ($R/S$) Hurst exponent $H \in [0, 1]$ across dyadic block sizes.#[must_use]pub fn estimate_hurst_rs(s: &[f64]) -> f64 { const SCALES: [usize; 5] = [6, 12, 24, 48, 96]; let mut xs = [0.0f64; 5]; let mut ys = [0.0f64; 5]; let mut pts = 0usize;
for &k in &SCALES { if s.len() < k * 2 { continue; } let mut rs_sum = 0.0f64; let mut blocks = 0usize; for chunk in s.chunks_exact(k) { let kf = k as f64; let c_mean = chunk.iter().copied().sum::<f64>() / kf; let mut cum = 0.0f64; let mut c_min = 0.0f64; let mut c_max = 0.0f64; let mut sq_sum = 0.0f64; for &v in chunk { let dev = v - c_mean; cum += dev; c_min = c_min.min(cum); c_max = c_max.max(cum); sq_sum += dev * dev; } let std_c = (sq_sum / kf).sqrt(); if std_c > 1e-7 { rs_sum += (c_max - c_min) / std_c; blocks = blocks.saturating_add(1); } } if blocks > 0 { let mean_rs = rs_sum / (blocks as f64); if mean_rs > 1e-7 { if let (Some(px), Some(py)) = (xs.get_mut(pts), ys.get_mut(pts)) { *px = (k as f64).ln(); *py = mean_rs.ln(); pts = pts.saturating_add(1); } } } }
if pts < 2 { return 0.55; } let valid_x = xs.get(..pts).unwrap_or(&[]); let valid_y = ys.get(..pts).unwrap_or(&[]); let pf = pts as f64; let mx = valid_x.iter().copied().sum::<f64>() / pf; let my = valid_y.iter().copied().sum::<f64>() / pf; let mut num = 0.0f64; let mut den = 0.0f64; for (&x, &y) in valid_x.iter().zip(valid_y.iter()) { num += (x - mx) * (y - my); den += (x - mx) * (x - mx); } if den <= 1e-9 { 0.55 } else { (num / den).clamp(0.10, 0.98) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360//! Corpus-Trained Gradient Boosted Decision Tree Evaluator, Monotone Isotonic Calibrator,//! and Exact Stack-Allocated Path-Dependent TreeSHAP (`gbdt`).//!//! Law (Shapley Local Accuracy): For any feature vector $x \in \mathbb{R}^F$ and tree ensemble $T$,//! `expected_margin(T) + sum_j shap[j] == raw_margin(T, x)` within IEEE-754 rounding (`< 1e-9`),//! provided every internal node satisfies `cover == left.cover + right.cover`.
/// Number of orthogonal ML features consumed by the GBDT classifier.pub const NUM_GBDT_FEATURES: usize = 28;
/// Maximum root-to-leaf path buffer capacity (`max_depth <= 8` -> `path_len <= 9`).const MAX_PATH_CAP: usize = 12;
/// Single immutable node in a binary decision tree (`Copy`, 32 bytes).#[derive(Debug, Clone, Copy)]pub struct TreeNode { /// Split feature index in `0..NUM_GBDT_FEATURES`, or `-1` if this node is a leaf. pub feature: i16, /// Left child index (`x[feature] <= threshold`). pub left: u16, /// Right child index (`x[feature] > threshold`). pub right: u16, /// Split threshold for internal nodes (`0.0` for leaves). pub threshold: f64, /// Leaf log-odds weight (`0.0` for internal nodes). pub leaf_value: f64, /// Training sample cover reaching this node (`cover == left.cover + right.cover`). pub cover: f64,}
impl TreeNode { /// Semantic predicate: returns `true` when this node is a terminal leaf. #[inline] #[must_use] pub const fn is_leaf(self) -> bool { self.feature < 0 }}
#[derive(Debug, Clone, Copy)]struct PathElem { feature: i32, zero_frac: f64, one_frac: f64, pweight: f64,}
impl Default for PathElem { fn default() -> Self { Self { feature: -1, zero_frac: 1.0, one_frac: 1.0, pweight: 0.0, } }}
/// Complete trained GBDT + Isotonic calibration model specification.#[derive(Debug, Clone, Copy)]pub struct TrainedGbdtModel<'a> { /// Base prior log-odds offset. pub base_margin: f64, /// Slice of decision trees, each stored in contiguous node order starting at root `0`. pub trees: &'a [&'a [TreeNode]], /// Monotone piecewise-linear calibration knots `(margin, calibrated_prob)`. pub isotonic_knots: &'a [(f64, f64)], /// Platt logistic fallback `(slope, intercept)` for smooth tail extrapolation. pub platt_tail: (f64, f64),}
/// Result of running GBDT inference + Exact TreeSHAP on a single document.#[derive(Debug, Clone, Copy)]pub struct GbdtPrediction { /// Raw uncalibrated log-odds margin $f(x) = \text{base} + \sum_t T_t(x)$. pub raw_margin: f64, /// Expected baseline margin $\phi_0 = \text{base} + \sum_t \mathbb{E}[T_t]$. pub expected_margin: f64, /// Calibrated probability $p(y = \text{AI} \mid x) \in [0, 1]$. pub calibrated_prob: f64, /// Exact per-feature Shapley log-odds attributions $\phi_j(x)$ summing to `raw_margin - expected_margin`. pub shap_values: [f64; NUM_GBDT_FEATURES],}
/// Evaluates a single tree's deterministic leaf prediction for `x`.#[must_use]pub fn eval_single_tree(nodes: &[TreeNode], x: &[f64; NUM_GBDT_FEATURES]) -> f64 { let mut idx = 0usize; for _ in 0..MAX_PATH_CAP { let Some(&node) = nodes.get(idx) else { return 0.0; }; if node.is_leaf() { return node.leaf_value; } let f_idx = usize::try_from(node.feature).unwrap_or(0); let f_val = x.get(f_idx).copied().unwrap_or(0.0); idx = if f_val <= node.threshold { usize::from(node.left) } else { usize::from(node.right) }; } 0.0}
/// Computes exact expected value $\mathbb{E}[T]$ of a tree weighted by empirical node cover.#[must_use]pub fn tree_expected_value(nodes: &[TreeNode]) -> f64 { let Some(&root) = nodes.first() else { return 0.0; }; if root.cover <= 0.0 { return 0.0; } expected_rec(nodes, 0, root.cover, 0)}
fn expected_rec(nodes: &[TreeNode], idx: usize, root_cover: f64, depth: usize) -> f64 { if depth >= MAX_PATH_CAP { return 0.0; } let Some(&node) = nodes.get(idx) else { return 0.0; }; if node.is_leaf() { return (node.cover / root_cover) * node.leaf_value; } expected_rec(nodes, usize::from(node.left), root_cover, depth + 1) + expected_rec(nodes, usize::from(node.right), root_cover, depth + 1)}
fn extend_path( path: &mut [PathElem; MAX_PATH_CAP], plen: usize, p_z: f64, p_o: f64, p_i: i32,) -> usize { if plen + 1 >= MAX_PATH_CAP { return plen; } if let Some(slot) = path.get_mut(plen) { *slot = PathElem { feature: p_i, zero_frac: p_z, one_frac: p_o, pweight: if plen == 0 { 1.0 } else { 0.0 }, }; } let denom = (plen + 1) as f64; for i in (0..plen).rev() { let wi = path.get(i).map(|e| e.pweight).unwrap_or(0.0); if let Some(next_slot) = path.get_mut(i + 1) { next_slot.pweight += p_o * wi * ((i + 1) as f64) / denom; } if let Some(cur_slot) = path.get_mut(i) { cur_slot.pweight = p_z * wi * ((plen - i) as f64) / denom; } } plen + 1}
fn unwind_path(path: &mut [PathElem; MAX_PATH_CAP], plen: usize, remove_idx: usize) -> usize { if plen == 0 || remove_idx >= plen { return plen; } let n = plen - 1; let one_f = path.get(remove_idx).map(|e| e.one_frac).unwrap_or(0.0); let zero_f = path.get(remove_idx).map(|e| e.zero_frac).unwrap_or(1.0); let mut next_w = path.get(n).map(|e| e.pweight).unwrap_or(0.0);
if one_f != 0.0 { for j in (0..n).rev() { let tmp = path.get(j).map(|e| e.pweight).unwrap_or(0.0); let updated = next_w * ((n + 1) as f64) / (((j + 1) as f64) * one_f); if let Some(slot) = path.get_mut(j) { slot.pweight = updated; } next_w = tmp - updated * zero_f * ((n - j) as f64) / ((n + 1) as f64); } } else if zero_f > 0.0 { for j in 0..n { if let Some(slot) = path.get_mut(j) { slot.pweight = (slot.pweight * ((n + 1) as f64)) / (zero_f * ((n - j) as f64)); } } }
for j in remove_idx..n { let next_elem = path.get(j + 1).copied().unwrap_or_default(); if let Some(slot) = path.get_mut(j) { slot.feature = next_elem.feature; slot.zero_frac = next_elem.zero_frac; slot.one_frac = next_elem.one_frac; } } n}
#[allow(clippy::too_many_arguments)]fn treeshap_recurse( nodes: &[TreeNode], node_idx: usize, x: &[f64; NUM_GBDT_FEATURES], phi: &mut [f64; NUM_GBDT_FEATURES], mut path: [PathElem; MAX_PATH_CAP], mut plen: usize, p_z: f64, p_o: f64, p_i: i32,) { plen = extend_path(&mut path, plen, p_z, p_o, p_i); let Some(&node) = nodes.get(node_idx) else { return; };
if node.is_leaf() { for i in 1..plen { let mut copy = path; let ulen = unwind_path(&mut copy, plen, i); let mut w_sum = 0.0f64; for k in 0..ulen { w_sum += copy.get(k).map(|e| e.pweight).unwrap_or(0.0); } if let Some(elem) = path.get(i) { if let Ok(f_idx) = usize::try_from(elem.feature) { if let Some(slot) = phi.get_mut(f_idx) { *slot += w_sum * (elem.one_frac - elem.zero_frac) * node.leaf_value; } } } } return; }
let f_idx = usize::try_from(node.feature).unwrap_or(0); let f_val = x.get(f_idx).copied().unwrap_or(0.0); let hot_idx = if f_val <= node.threshold { usize::from(node.left) } else { usize::from(node.right) }; let cold_idx = if f_val <= node.threshold { usize::from(node.right) } else { usize::from(node.left) };
let mut incoming_z = 1.0f64; let mut incoming_o = 1.0f64; let split_feat_i32 = i32::from(node.feature); if let Some(dup_pos) = (1..plen).find(|&k| { path.get(k) .map(|e| e.feature == split_feat_i32) .unwrap_or(false) }) { incoming_z = path.get(dup_pos).map(|e| e.zero_frac).unwrap_or(1.0); incoming_o = path.get(dup_pos).map(|e| e.one_frac).unwrap_or(1.0); plen = unwind_path(&mut path, plen, dup_pos); }
let parent_cover = node.cover.max(1e-9); let hot_cover = nodes.get(hot_idx).map(|n| n.cover).unwrap_or(0.0); let cold_cover = nodes.get(cold_idx).map(|n| n.cover).unwrap_or(0.0);
if hot_cover > 0.0 { treeshap_recurse( nodes, hot_idx, x, phi, path, plen, incoming_z * (hot_cover / parent_cover), incoming_o, split_feat_i32, ); } if cold_cover > 0.0 { treeshap_recurse( nodes, cold_idx, x, phi, path, plen, incoming_z * (cold_cover / parent_cover), 0.0, split_feat_i32, ); }}
/// Maps raw GBDT margin + additive shift into a calibrated probability in `[0.002, 0.998]`.#[must_use]pub fn calibrate_margin(margin: f64, knots: &[(f64, f64)], platt_tail: (f64, f64)) -> f64 { let platt_p = 1.0 / (1.0 + (-(platt_tail.0 * margin + platt_tail.1)).exp()); let (Some(&first), Some(&last)) = (knots.first(), knots.last()) else { return platt_p.clamp(0.002, 0.998); }; if margin <= first.0 { return (0.5 * first.1 + 0.5 * platt_p).clamp(0.002, 0.998); } if margin >= last.0 { return (0.5 * last.1 + 0.5 * platt_p).clamp(0.002, 0.998); } let mut iso_p = platt_p; for pair in knots.windows(2) { if let (Some(&(x0, y0)), Some(&(x1, y1))) = (pair.first(), pair.get(1)) { if margin >= x0 && margin <= x1 { let span = (x1 - x0).max(1e-9); let t = ((margin - x0) / span).clamp(0.0, 1.0); iso_p = y0 + t * (y1 - y0); break; } } } // Blend 75% empirical isotonic + 25% smooth Platt sigmoid so rank ordering is strictly monotone (0.75 * iso_p + 0.25 * platt_p).clamp(0.002, 0.998)}
/// Evaluates the full GBDT ensemble + Exact Path-Dependent TreeSHAP + Calibration.#[must_use]pub fn predict_with_treeshap( model: TrainedGbdtModel<'_>, features: &[f64; NUM_GBDT_FEATURES], additive_logit_shift: f64,) -> GbdtPrediction { let mut raw_margin = model.base_margin; let mut expected_margin = model.base_margin; let mut shap_values = [0.0f64; NUM_GBDT_FEATURES];
for &tree_nodes in model.trees { raw_margin += eval_single_tree(tree_nodes, features); expected_margin += tree_expected_value(tree_nodes); let init_path = [PathElem::default(); MAX_PATH_CAP]; treeshap_recurse( tree_nodes, 0, features, &mut shap_values, init_path, 0, 1.0, 1.0, -1, ); }
let shifted_margin = raw_margin + additive_logit_shift; let calibrated_prob = calibrate_margin(shifted_margin, model.isotonic_knots, model.platt_tail);
GbdtPrediction { raw_margin: shifted_margin, expected_margin, calibrated_prob, shap_values, }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565//! Quantized Dual-Distribution PPM Context Model, Liang et al. (ICML 2024) Mixture MLE Solver,//! and Feature-Hashed Multilingual N-gram NBSVM (`hash_tables`).//!//! Basis://! - `DualPpmTable`: Covers local sequential predictability $\Delta H(x_t \mid x_{<t})$ and emits//! empirical human conditional surprisal stream $s_t = -\log_2 P_{\text{Human}}(x_t \mid x_{<t})$.//! - `MixtureMleTable`: Covers global/local vocabulary shift $(1-\alpha)P(v) + \alpha Q(v)$ via//! strictly concave Newton-Raphson MLE on $[0, 1]$.//! - `NbSvmTable`: Covers sparse multilingual character (3-5 gram) and word (1-2 gram) linear margins.//!//! Tightness: `MlTablesView::from_bytes` validates exact magic header and byte length (`327,696` bytes)//! at construction; all bucket lookups mask by `BUCKET_MASK = 0xFFFF` with checked `.get()`.
use std::collections::BTreeMap;
use crate::model::{DetectError, ScriptFamily};use crate::stylometry::is_cjk_or_kana;
/// Number of feature-hash buckets per statistical table (`2^16 = 65,536`).pub const BUCKET_COUNT: usize = 65_536;/// Bitmask for `BUCKET_COUNT`.pub const BUCKET_MASK: usize = BUCKET_COUNT - 1;/// Exact binary byte length of `weights/ml_tables.bin`.pub const ML_TABLES_BYTE_LEN: usize = 16 + BUCKET_COUNT * 2 + BUCKET_COUNT * 2 + BUCKET_COUNT;/// Magic 8-byte header identifying `ml_tables.bin` format v2.pub const ML_TABLES_MAGIC: &[u8; 8] = b"AIDML02\0";
/// Domain-separation seeds for SplitMix64 feature hashing.pub const SEED_PPM_ORD1: u64 = 0x9E37_79B9_7F4A_7C15;/// Second-order context seed for Dual PPM.pub const SEED_PPM_ORD2: u64 = 0xBF58_476D_1CE4_E5B9;/// Third-order context seed for Dual PPM.pub const SEED_PPM_ORD3: u64 = 0x94D0_49BB_1331_11EB;/// Unigram vocabulary seed for Mixture MLE.pub const SEED_MLE_UNI: u64 = 0xD6E8_FEB8_6659_FD93;/// Bigram vocabulary seed for Mixture MLE.pub const SEED_MLE_BI: u64 = 0xA5A3_5625_AA0F_3B2D;/// Character 3-gram seed for NBSVM.pub const SEED_NBSVM_C3: u64 = 0x517C_C1B7_2722_0A95;/// Character 4-gram seed for NBSVM.pub const SEED_NBSVM_C4: u64 = 0x2545_F491_4F6C_DD1D;/// Word unigram seed for NBSVM.pub const SEED_NBSVM_W1: u64 = 0xC6BC_2796_92B5_C323;/// Word bigram seed for NBSVM.pub const SEED_NBSVM_W2: u64 = 0x8CB9_2BA7_2F3D_8DD7;
/// Validated zero-copy view over the `327,696`-byte quantized ML statistical tables.#[derive(Debug, Clone, Copy)]pub struct MlTablesView<'a> { ppm_bytes: &'a [u8], mle_bytes: &'a [u8], nbsvm_bytes: &'a [u8], nbsvm_bias: f64, nbsvm_scale: f64,}
impl<'a> MlTablesView<'a> { /// Validates magic bytes and slice offsets to construct a panic-free `MlTablesView`. /// /// Post: `Ok(view)` guarantees `ppm_bytes.len() == 131072`, `mle_bytes.len() == 131072`, /// and `nbsvm_bytes.len() == 65536`. pub fn from_bytes(raw: &'a [u8]) -> Result<Self, DetectError> { if raw.len() != ML_TABLES_BYTE_LEN { return Err(DetectError::NullOrInvalidBuffer); } let Some(magic) = raw.get(0..8) else { return Err(DetectError::NullOrInvalidBuffer); }; if magic != ML_TABLES_MAGIC { return Err(DetectError::NullOrInvalidBuffer); } let bias = read_f32_le(raw, 8).unwrap_or(0.0); let scale = read_f32_le(raw, 12).unwrap_or(1.0 / 32.0); let ppm_end = 16 + BUCKET_COUNT * 2; let mle_end = ppm_end + BUCKET_COUNT * 2; let nbsvm_end = mle_end + BUCKET_COUNT; let (Some(ppm_bytes), Some(mle_bytes), Some(nbsvm_bytes)) = ( raw.get(16..ppm_end), raw.get(ppm_end..mle_end), raw.get(mle_end..nbsvm_end), ) else { return Err(DetectError::NullOrInvalidBuffer); }; Ok(Self { ppm_bytes, mle_bytes, nbsvm_bytes, nbsvm_bias: f64::from(bias), nbsvm_scale: if scale.abs() < 1e-7 { 1.0 / 32.0 } else { f64::from(scale) }, }) }
/// Looks up `(llr_bits, human_surprisal_bits)` for a Dual-PPM context bucket. #[inline] #[must_use] pub fn lookup_ppm(self, bucket: u16) -> (f64, f64) { let base = (usize::from(bucket) & BUCKET_MASK) * 2; let llr_q = self.ppm_bytes.get(base).copied().unwrap_or(0) as i8; let surp_q = self.ppm_bytes.get(base + 1).copied().unwrap_or(90); ((f64::from(llr_q)) / 24.0, (f64::from(surp_q)) / 18.0) }
/// Looks up `(p_human, q_ai)` unnormalized probabilities for Mixture MLE. #[inline] #[must_use] pub fn lookup_mle_probs(self, bucket: u16) -> (f64, f64) { let base = (usize::from(bucket) & BUCKET_MASK) * 2; let nll_h = 2.0 + f64::from(self.mle_bytes.get(base).copied().unwrap_or(160)) / 20.0; let nll_a = 2.0 + f64::from(self.mle_bytes.get(base + 1).copied().unwrap_or(160)) / 20.0; ((-nll_h).exp(), (-nll_a).exp()) }
/// Looks up signed NBSVM weight for a hashed n-gram bucket, with sign-hash collision cancellation. #[inline] #[must_use] pub fn lookup_nbsvm_weight(self, hash64: u64) -> f64 { let bucket = (hash64 as usize) & BUCKET_MASK; let sign = if ((hash64 >> 32) & 1) == 0 { 1.0 } else { -1.0 }; let w_q = self.nbsvm_bytes.get(bucket).copied().unwrap_or(0) as i8; sign * f64::from(w_q) * self.nbsvm_scale }
/// Returns the learned NBSVM intercept bias. #[inline] #[must_use] pub const fn nbsvm_bias(self) -> f64 { self.nbsvm_bias }}
fn read_f32_le(buf: &[u8], offset: usize) -> Option<f32> { let b0 = *buf.get(offset)?; let b1 = *buf.get(offset + 1)?; let b2 = *buf.get(offset + 2)?; let b3 = *buf.get(offset + 3)?; Some(f32::from_le_bytes([b0, b1, b2, b3]))}
/// Pure SplitMix64-avalanched FNV-style byte mixer.#[inline]#[must_use]pub const fn mix64(mut z: u64) -> u64 { z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); z ^ (z >> 31)}
/// Hashes a sequence of `u32` codepoints or token hashes under a domain seed.#[inline]#[must_use]pub fn hash_u32_seq(seed: u64, items: &[u32]) -> u64 { let mut h = seed; for &x in items { h = mix64(h ^ u64::from(x).wrapping_mul(0x9E37_79B9_7F4A_7C15)); } h}
/// Hashes a lowercase UTF-8 token under a domain seed.#[inline]#[must_use]pub fn hash_token_str(seed: u64, s: &str) -> u32 { let mut h = seed; for b in s.bytes() { h = h.wrapping_mul(0x0100_0000_01B3) ^ u64::from(b); } let mixed = mix64(h); (mixed as u32) ^ ((mixed >> 32) as u32)}
/// Canonicalizes high-frequency Traditional Chinese ideographs to Simplified equivalents/// so `zh-Hant` and `zh-Hans` share unified CJK statistical density without loss.#[must_use]pub const fn canonical_cjk(ch: char) -> char { match ch { '體' => '体', '學' => '学', '讀' => '读', '實' => '实', '這' => '这', '說' => '说', '們' => '们', '會' => '会', '對' => '对', '個' => '个', '時' => '时', '過' => '过', '為' => '为', '來' => '来', '發' => '发', '動' => '动', '機' => '机', '經' => '经', '現' => '现', '點' => '点', '開' => '开', '關' => '关', '問' => '问', '題' => '题', '進' => '进', '還' => '还', '讓' => '让', '從' => '从', '當' => '当', '應' => '应', '長' => '长', '間' => '间', '樣' => '样', '種' => '种', '與' => '与', '無' => '无', '數' => '数', '變' => '变', '結' => '结', '構' => '构', '論' => '论', '語' => '语', '電' => '电', '腦' => '脑', '網' => '网', '絡' => '络', '軟' => '软', '資' => '资', '訊' => '讯', '處' => '处', '際' => '际', '態' => '态', '層' => '层', '維' => '维', '環' => '环', '閉' => '闭', '輯' => '辑', '顯' => '显', '著' => '着', '轉' => '转', '傳' => '传', '統' => '统', '設' => '设', '計' => '计', '驗' => '验', '證' => '证', '據' => '据', '優' => '优', '質' => '质', '書' => '书', '寫' => '写', '認' => '认', '識' => '识', '覺' => '觉', '頭' => '头', '見' => '见', '聽' => '听', '觀' => '观', '業' => '业', '務' => '务', '產' => '产', '品' => '品', '術' => '术', '連' => '连', '接' => '接', '選' => '选', '擇' => '择', '境' => '境', '複' => '复', '雜' => '杂', '簡' => '简', '單' => '单', '獨' => '独', '創' => '创', '義' => '义', '價' => '价', '值' => '值', '報' => '报', '導' => '导', '標' => '标', '準' => '准', '確' => '确', '決' => '决', '議' => '议', '專' => '专', '門' => '门', '區' => '区', '塊' => '块', '鏈' => '链', '節' => '节', '約' => '约', '規' => '规', '則' => '则', '範' => '范', '圍' => '围', '廣' => '广', '東' => '东', '車' => '车', '馬' => '马', '風' => '风', '雲' => '云', '飛' => '飞', '氣' => '气', '力' => '力', other => other, }}
/// Summary outputs produced by scanning text through `DualPpmTable`, `MixtureMleTable`, and `NbSvmTable`.#[derive(Debug, Clone)]pub struct HashModelScan { /// Interpolated mean PPM log-likelihood ratio (`bits`, positive = AI-like). pub ppm_mean_llr: f64, /// Order-1 (bigram) mean PPM log-likelihood ratio. pub ppm_ord1_llr: f64, /// Order-3 (trigram/4-gram) mean PPM log-likelihood ratio. pub ppm_ord3_llr: f64, /// Token/unit-level conditional human surprisal sequence $s_1, \dots, s_T$ for DivEye. pub surprisal_stream: Vec<f64>, /// Global document Mixture MLE $\hat{\alpha} \in [0, 1]$ (Liang et al., ICML 2024). pub mle_alpha_hat: f64, /// Fisher curvature information $I(\hat{\alpha})$ of the MLE estimate. pub mle_fisher_info: f64, /// Mean lexical excess log-likelihood ratio $\frac{1}{N} \sum \ln(Q(v)/P(v))$. pub mle_mean_llr: f64, /// Global document Feature-Hashed NBSVM log-odds margin. pub nbsvm_margin: f64,}
/// Semantic predicate: returns `true` if `text` contains Japanese Hiragana or Katakana.#[must_use]pub fn contains_japanese_kana(text: &str) -> bool { text.chars().any(|c| ('\u{3040}'..='\u{30FF}').contains(&c))}
/// Extracts normalized word/CJK-unit sequence (`u32` token hashes) for PPM & MLE models./// Applies a disjoint domain salt for Japanese (Kana-bearing) prose so shared Kanji never/// collide with Chinese corpus buckets.#[must_use]pub fn tokenize_units_u32(text: &str, script: ScriptFamily) -> Vec<u32> { let is_ja = contains_japanese_kana(text); let ja_mask: u32 = if is_ja { 0x4A41_0000 } else { 0 }; let word_seed: u64 = if is_ja { 0x4A41_1234_5678 } else { 0x1234_5678 }; let mut units = Vec::new(); let mut word_buf = String::new(); for raw_ch in text.chars() { let ch = if is_ja { raw_ch } else { canonical_cjk(raw_ch) }; if is_cjk_or_kana(ch) { if !word_buf.is_empty() { units.push(hash_token_str(word_seed, &word_buf)); word_buf.clear(); } units.push((ch as u32) ^ ja_mask); } else if ch.is_alphanumeric() || ch == '\'' { for lc in ch.to_lowercase() { word_buf.push(lc); } } else { if !word_buf.is_empty() { units.push(hash_token_str(word_seed, &word_buf)); word_buf.clear(); } let keep_punct = (!script.uses_ideographic_cadence() && matches!(ch, ',' | '.' | ';' | ':' | '?' | '!' | '-')) || (script.uses_ideographic_cadence() && matches!(ch, ',' | '。' | '、' | ';' | ':' | '?' | '!')); if keep_punct { units.push(0x8000_0000 | ((ch as u32) ^ ja_mask)); } } } if !word_buf.is_empty() { units.push(hash_token_str(word_seed, &word_buf)); } units}
/// Emits formatting-invariant hashed n-gram counts (word/CJK 1-3 grams + intra-word stems,/// completely invariant to `\n\n` paragraph breaks and scraping whitespace) for NBSVM.#[must_use]pub fn extract_nbsvm_features(text: &str) -> BTreeMap<u64, u32> { let mut counts: BTreeMap<u64, u32> = BTreeMap::new(); let units = tokenize_units_u32(text, ScriptFamily::Hybrid);
for &u in units.iter().take(16_000) { let h = hash_u32_seq(SEED_NBSVM_W1, &[u]); let entry = counts.entry(h).or_insert(0); *entry = entry.saturating_add(1); } for w2 in units.windows(2).take(16_000) { let h = hash_u32_seq(SEED_NBSVM_W2, w2); let entry = counts.entry(h).or_insert(0); *entry = entry.saturating_add(1); } for w3 in units.windows(3).take(16_000) { let h = hash_u32_seq(SEED_NBSVM_C3, w3); let entry = counts.entry(h).or_insert(0); *entry = entry.saturating_add(1); } for w4 in units.windows(4).take(12_000) { let h = hash_u32_seq(SEED_NBSVM_C4, w4); let entry = counts.entry(h).or_insert(0); *entry = entry.saturating_add(1); } counts}
/// Solves Liang et al. (ICML 2024) strictly concave mixture log-likelihood/// $\max_{\alpha \in [0, 1]} \sum_b c_b \ln((1-\alpha) P_b + \alpha Q_b)$ via safeguarded Newton-Raphson.////// Law: Concavity ($\mathcal{L}''(\alpha) \le 0$) guarantees unique global maximum on $[0, 1]$.#[must_use]pub fn solve_mixture_mle( bucket_counts: &BTreeMap<u16, u32>, tables: MlTablesView<'_>,) -> (f64, f64, f64) { if bucket_counts.is_empty() { return (0.5, 0.0, 0.0); } let mut items: Vec<(f64, f64, f64)> = Vec::with_capacity(bucket_counts.len()); let mut total_cnt = 0.0f64; let mut sum_llr = 0.0f64; for (&b, &cnt) in bucket_counts { let (p, q) = tables.lookup_mle_probs(b); let c = f64::from(cnt); total_cnt += c; sum_llr += c * (q.max(1e-12) / p.max(1e-12)).ln(); items.push((c, p, q)); } let mean_llr = sum_llr / total_cnt.max(1.0);
// Evaluate gradient at boundaries first (exact KKT check on [0, 1]!) let grad_at = |a: f64| -> (f64, f64) { let mut g1 = 0.0f64; let mut g2 = 0.0f64; for &(c, p, q) in &items { let diff = q - p; let denom = ((1.0 - a) * p + a * q).max(1e-15); let ratio = diff / denom; g1 += c * ratio; g2 -= c * ratio * ratio; } (g1, g2) };
let (g0, g2_0) = grad_at(0.0); if g0 <= 0.0 { return (0.0, (-g2_0).max(0.0), mean_llr); } let (g1_end, g2_1) = grad_at(1.0); if g1_end >= 0.0 { return (1.0, (-g2_1).max(0.0), mean_llr); }
let mut lo = 0.0f64; let mut hi = 1.0f64; let mut alpha = 0.5f64; let mut last_fisher = 0.0f64;
for _ in 0..14 { let (g, h) = grad_at(alpha); last_fisher = (-h).max(0.0); if g.abs() < 1e-7 { break; } if g > 0.0 { lo = alpha; } else { hi = alpha; } let newton = if h < -1e-12 { alpha - g / h } else { 0.5 * (lo + hi) }; alpha = if newton > lo && newton < hi { newton } else { 0.5 * (lo + hi) }; } (alpha.clamp(0.0, 1.0), last_fisher, mean_llr)}
/// Evaluates `DualPpmTable`, `MixtureMleTable`, and `NbSvmTable` over a text slice in a single pass.#[must_use]pub fn evaluate_hash_models( text: &str, script: ScriptFamily, tables: MlTablesView<'_>,) -> HashModelScan { let units = tokenize_units_u32(text, script); let mut surprisal_stream = Vec::with_capacity(units.len()); let mut sum_llr = 0.0f64; let mut sum_ord1 = 0.0f64; let mut sum_ord3 = 0.0f64; let mut steps = 0usize;
let mut mle_counts: BTreeMap<u16, u32> = BTreeMap::new(); for (idx, &u) in units.iter().enumerate() { let ub = (hash_u32_seq(SEED_MLE_UNI, &[u]) as u16) & (BUCKET_MASK as u16); let e1 = mle_counts.entry(ub).or_insert(0); *e1 = e1.saturating_add(1);
if idx >= 1 { let prev1 = units.get(idx - 1).copied().unwrap_or(0); let bb = (hash_u32_seq(SEED_MLE_BI, &[prev1, u]) as u16) & (BUCKET_MASK as u16); let e2 = mle_counts.entry(bb).or_insert(0); *e2 = e2.saturating_add(1);
let b1 = (hash_u32_seq(SEED_PPM_ORD1, &[prev1, u]) as u16) & (BUCKET_MASK as u16); let (llr1, surp1) = tables.lookup_ppm(b1);
let (llr2, surp2) = if idx >= 2 { let prev2 = units.get(idx - 2).copied().unwrap_or(0); let b2 = (hash_u32_seq(SEED_PPM_ORD2, &[prev2, prev1, u]) as u16) & (BUCKET_MASK as u16); tables.lookup_ppm(b2) } else { (llr1, surp1) };
let (llr3, surp3) = if idx >= 3 { let prev3 = units.get(idx - 3).copied().unwrap_or(0); let prev2 = units.get(idx - 2).copied().unwrap_or(0); let b3 = (hash_u32_seq(SEED_PPM_ORD3, &[prev3, prev2, prev1, u]) as u16) & (BUCKET_MASK as u16); tables.lookup_ppm(b3) } else { (llr2, surp2) };
let interp_llr = 0.30 * llr1 + 0.40 * llr2 + 0.30 * llr3; let interp_surp = 0.30 * surp1 + 0.40 * surp2 + 0.30 * surp3; sum_llr += interp_llr; sum_ord1 += llr1; sum_ord3 += llr3; surprisal_stream.push(interp_surp); steps = steps.saturating_add(1); } }
let denom = (steps.max(1)) as f64; let (mle_alpha_hat, mle_fisher_info, mle_mean_llr) = solve_mixture_mle(&mle_counts, tables);
let nbsvm_feats = extract_nbsvm_features(text); let mut raw_dot = tables.nbsvm_bias(); let norm = ((nbsvm_feats.len().max(1)) as f64).sqrt(); let mut sum_w = 0.0f64; for (&h, &cnt) in &nbsvm_feats { let tf = 1.0 + (f64::from(cnt)).ln(); sum_w += tf * tables.lookup_nbsvm_weight(h); } raw_dot += sum_w / norm;
HashModelScan { ppm_mean_llr: sum_llr / denom, ppm_ord1_llr: sum_ord1 / denom, ppm_ord3_llr: sum_ord3 / denom, surprisal_stream, mle_alpha_hat, mle_fisher_info, mle_mean_llr, nbsvm_margin: raw_dot, }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146//! Deterministic, zero-dependency JSON serializer for `ForensicReport`.//!//! Escapes all control characters, quotes, backslashes, and `<` (`\u003c`) so emitted JSON//! is safe across DOM, SSR, and WebAssembly memory bridges without pulling in external crates.
use std::fmt::Write as _;
use crate::model::{ForensicReport, SentenceForensic};
/// Appends a JSON-escaped string literal (including surrounding `"`) to `out`.pub fn push_json_str(out: &mut String, value: &str) { out.push('"'); for ch in value.chars() { match ch { '"' => out.push_str("\\\""), '\\' => out.push_str("\\\\"), '\n' => out.push_str("\\n"), '\r' => out.push_str("\\r"), '\t' => out.push_str("\\t"), '<' => out.push_str("\\u003c"), c if (c as u32) < 0x20 => { let _ = write!(out, "\\u{:04x}", c as u32); } c => out.push(c), } } out.push('"');}
fn round3(v: f64) -> f64 { if v.is_finite() { ((v * 1000.0).round()) / 1000.0 } else { 0.0 }}
fn push_sentence_json(out: &mut String, s: &SentenceForensic) { let _ = write!( out, "{{\"index\":{},\"unitLen\":{},\"aiPct\":{:.1},\"gltrBand\":\"{}\",\"reason\":", s.index, s.unit_len, s.ai_score.as_percent(), s.gltr_band.slug() ); push_json_str(out, s.reason_code); let _ = write!(out, ",\"phraseHits\":{},\"text\":", s.phrase_hits); push_json_str(out, &s.text); out.push('}');}
/// Serializes a `ForensicReport` into a compact UTF-8 JSON document.#[must_use]pub fn serialize_report_json(report: &ForensicReport) -> String { let mut out = String::with_capacity(2048 + report.byte_len); let g0 = report.gltr_counts.first().copied().unwrap_or(0); let g1 = report.gltr_counts.get(1).copied().unwrap_or(0); let g2 = report.gltr_counts.get(2).copied().unwrap_or(0); let g3 = report.gltr_counts.get(3).copied().unwrap_or(0);
let _ = write!( out, "{{\"modelEngine\":\"gbdt_treeshap_v2\",\"aiPct\":{:.1},\"humanPct\":{:.1},\"confidencePct\":{:.1},\"mleAlphaPct\":{:.1},\"hurstExponent\":{:.3},\"graphClustering\":{:.3},\"ppmLlrBits\":{:.3},\"nbsvmMargin\":{:.3},\"verdict\":\"{}\",\"scriptFamily\":\"{}\",\"genre\":\"{}\",\"byteLen\":{},\"charCount\":{},\"tokenCount\":{},\"sentenceCount\":{},\"meanSentenceLen\":{:.2},\"stdSentenceLen\":{:.2},\"burstinessCv\":{:.3},\"mattr50\":{:.3},\"hapaxRatio\":{:.3},\"lz77Ratio\":{:.3},\"conditionalEntropyBits\":{:.3},\"crossEntropyRatio\":{:.3},\"removableWatermarkChars\":{},", report.overall_ai_score.as_percent(), report.overall_human_score.as_percent(), report.confidence.as_percent(), report.mle_alpha_fraction.as_percent(), round3(report.hurst_exponent), round3(report.graph_clustering), round3(report.ppm_llr_bits), round3(report.nbsvm_margin), report.verdict.slug(), report.script_family.slug(), report.genre.slug(), report.byte_len, report.char_count, report.token_count, report.sentence_count, round3(report.mean_sentence_len), round3(report.std_sentence_len), round3(report.burstiness_cv), round3(report.mattr_50), round3(report.hapax_ratio), round3(report.lz77_ratio), round3(report.conditional_entropy_bits), round3(report.cross_entropy_ratio), report.removable_watermark_chars, );
let sf = &report.shap_families; let _ = write!( out, "\"shapLogOdds\":{{\"ppm\":{:.3},\"diveye\":{:.3},\"cadence\":{:.3},\"mleGraph\":{:.3},\"nbsvm\":{:.3}}},", round3(sf.first().copied().unwrap_or(0.0)), round3(sf.get(1).copied().unwrap_or(0.0)), round3(sf.get(2).copied().unwrap_or(0.0)), round3(sf.get(3).copied().unwrap_or(0.0)), round3(sf.get(4).copied().unwrap_or(0.0)), );
let d = &report.dimensions; let _ = write!( out, "\"dimensions\":{{\"compression\":{:.1},\"crossEntropy\":{:.1},\"cadence\":{:.1},\"lexical\":{:.1},\"discourse\":{:.1},\"watermarks\":{:.1}}},", d.compression_predictability.as_percent(), d.cross_entropy_curvature.as_percent(), d.cadence_uniformity.as_percent(), d.lexical_concentration.as_percent(), d.discourse_template_signal.as_percent(), d.watermark_artifact_signal.as_percent(), );
let _ = write!( out, "\"gltrCounts\":{{\"green\":{g0},\"yellow\":{g1},\"red\":{g2},\"violet\":{g3}}},\"matchedPhrases\":[" ); for (i, phrase) in report.matched_phrases.iter().enumerate() { if i > 0 { out.push(','); } push_json_str(&mut out, phrase); }
out.push_str("],\"watermarkFindings\":["); for (i, wf) in report.watermark_findings.iter().enumerate() { if i > 0 { out.push(','); } out.push_str("{\"code\":"); push_json_str(&mut out, wf.code); out.push_str(",\"label\":"); push_json_str(&mut out, wf.label); let _ = write!(out, ",\"count\":{}}}", wf.count); }
out.push_str("],\"sentences\":["); for (i, sent) in report.sentences.iter().enumerate() { if i > 0 { out.push(','); } push_sentence_json(&mut out, sent); } out.push_str("]}"); out}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423//! ProseGuard Wasm (`prose_guard_wasm`) — Zero-Dependency Rust + WebAssembly Engine for//! Client-Side AI-Generated Article Detection & Stylometric Forensics.//!//! Combines six orthogonal forensic signals inspired by open-source research://! 1. **ZipPy LZ77 Sliding-Window Compression Redundancy** (`lz_entropy`)//! 2. **Binoculars Conditional Cross-Entropy Curvature Surrogate** (`lz_entropy`)//! 3. **Sentence Cadence Burstiness & Local Alternation Variance** (`stylometry`)//! 4. **GLTR 4-Band Lexical Predictability, MATTR-50 & Hapax Richness** (`stylometry`)//! 5. **Multilingual LLM Discourse Templates & Markdown Structural Symmetry** (`stylometry`)//! 6. **Invisible Unicode Watermark (`ZWSP`, `NNBSP`, `WJ`) & Sanitizer** (`watermark`)//!//! Security & Supply-Chain Invariant: `[dependencies]` in `Cargo.toml` is empty.
#![deny(missing_docs)]
pub mod cooccur_graph;pub mod diveye;pub mod gbdt;pub mod hash_tables;pub mod json_emit;pub mod lm_proxy;pub mod lz_entropy;pub mod ml_features;pub mod model;pub mod stylometry;pub mod trained_forest;pub mod watermark;
use std::cell::RefCell;
use crate::json_emit::serialize_report_json;use crate::model::{DetectError, DetectionConfig, GenrePreset, SensitivityMode, ValidatedArticle};use crate::stylometry::analyze_article;use crate::watermark::sanitize_text;
thread_local! { static REPORT_JSON_BUF: RefCell<String> = const { RefCell::new(String::new()) }; static SANITIZED_TEXT_BUF: RefCell<String> = const { RefCell::new(String::new()) }; static REMOVED_ZW_COUNT: RefCell<u32> = const { RefCell::new(0) }; static NORMALIZED_SPACE_COUNT: RefCell<u32> = const { RefCell::new(0) }; static ERROR_MSG_BUF: RefCell<String> = const { RefCell::new(String::new()) };}
fn record_error(err: &DetectError) -> usize { ERROR_MSG_BUF.with(|slot| { *slot.borrow_mut() = err.to_string(); }); 0}
/// Computes IEEE 802.3 CRC-32 over a byte slice (`CRC32("123456789") == 0xCBF4_3926`).#[must_use]pub fn crc32_ieee(bytes: &[u8]) -> u32 { let mut crc = 0xFFFF_FFFFu32; for &byte in bytes { crc ^= u32::from(byte); for _ in 0..8 { let mask = (crc & 1).wrapping_neg(); crc = (crc >> 1) ^ (0xEDB8_8320u32 & mask); } } !crc}
// ============================================================================// Named WebAssembly FFI Adapter Boundary// ============================================================================
/// Allocates `size` bytes in WebAssembly linear memory and returns its base pointer.#[no_mangle]pub extern "C" fn wasm_alloc(size: usize) -> *mut u8 { if size == 0 { return core::ptr::null_mut(); } let mut buf = Vec::<u8>::with_capacity(size); let ptr = buf.as_mut_ptr(); core::mem::forget(buf); ptr}
/// Reclaims a buffer previously allocated via `wasm_alloc(size)`.////// # Safety/// `ptr` must have been allocated by `wasm_alloc(size)` in the same linear memory instance/// and must not be freed more than once.#[no_mangle]pub unsafe extern "C" fn wasm_dealloc(ptr: *mut u8, size: usize) { if !ptr.is_null() && size > 0 { // SAFETY: Upheld by caller (`withWasmBuffer` RAII wrapper in `wasm-loader.js`). let _ = unsafe { Vec::from_raw_parts(ptr, 0, size) }; }}
/// Runs IEEE 802.3 CRC-32 self-test across an FFI byte slice.////// # Safety/// If `len > 0`, `ptr` must point to `len` readable initialized bytes in Wasm linear memory.#[no_mangle]pub unsafe extern "C" fn wasm_crc32(ptr: *const u8, len: usize) -> u32 { if ptr.is_null() || len == 0 { return crc32_ieee(&[]); } // SAFETY: Caller guarantees `ptr..ptr+len` is valid in Wasm linear memory. let bytes = unsafe { core::slice::from_raw_parts(ptr, len) }; crc32_ieee(bytes)}
/// Pointer to the latest UTF-8 JSON forensic report written by `wasm_analyze_article`.#[no_mangle]pub extern "C" fn wasm_report_ptr() -> *const u8 { REPORT_JSON_BUF.with(|buf| buf.borrow().as_ptr())}
/// Byte length of the latest UTF-8 JSON forensic report.#[no_mangle]pub extern "C" fn wasm_report_len() -> usize { REPORT_JSON_BUF.with(|buf| buf.borrow().len())}
/// Pointer to the latest sanitized UTF-8 string produced by `wasm_sanitize_text`.#[no_mangle]pub extern "C" fn wasm_sanitized_ptr() -> *const u8 { SANITIZED_TEXT_BUF.with(|buf| buf.borrow().as_ptr())}
/// Byte length of the latest sanitized UTF-8 string.#[no_mangle]pub extern "C" fn wasm_sanitized_len() -> usize { SANITIZED_TEXT_BUF.with(|buf| buf.borrow().len())}
/// Count of zero-width watermark characters stripped in the last `wasm_sanitize_text` call.#[no_mangle]pub extern "C" fn wasm_removed_zw_count() -> u32 { REMOVED_ZW_COUNT.with(|c| *c.borrow())}
/// Count of atypical spaces normalized in the last `wasm_sanitize_text` call.#[no_mangle]pub extern "C" fn wasm_normalized_space_count() -> u32 { NORMALIZED_SPACE_COUNT.with(|c| *c.borrow())}
/// Pointer to the last UTF-8 error message if `wasm_analyze_article` returned `0`.#[no_mangle]pub extern "C" fn wasm_error_ptr() -> *const u8 { ERROR_MSG_BUF.with(|e| e.borrow().as_ptr())}
/// Byte length of the last UTF-8 error message.#[no_mangle]pub extern "C" fn wasm_error_len() -> usize { ERROR_MSG_BUF.with(|e| e.borrow().len())}
/// Analyzes a UTF-8 article in WebAssembly linear memory and writes the JSON forensic report./// Returns the report byte length on success, or `0` on domain validation error.////// # Safety/// If `len > 0`, `ptr` must reference `len` readable bytes in Wasm linear memory.#[no_mangle]pub unsafe extern "C" fn wasm_analyze_article( ptr: *const u8, len: usize, genre_code: u8, sensitivity_code: u8, inspect_watermarks: u8, inspect_markdown: u8,) -> usize { if ptr.is_null() || len == 0 { return record_error(&DetectError::EmptyDocument); } // SAFETY: Caller (`withWasmBuffer`) allocated and populated `ptr..ptr+len`. let raw_bytes = unsafe { core::slice::from_raw_parts(ptr, len) }; let Ok(raw_str) = core::str::from_utf8(raw_bytes) else { return record_error(&DetectError::InvalidUtf8); };
let genre = match GenrePreset::from_code(genre_code) { Ok(g) => g, Err(e) => return record_error(&e), }; let sensitivity = match SensitivityMode::from_code(sensitivity_code) { Ok(s) => s, Err(e) => return record_error(&e), }; let validated = match ValidatedArticle::try_new(raw_str) { Ok(v) => v, Err(e) => return record_error(&e), };
let cfg = DetectionConfig { genre, sensitivity, inspect_watermarks: inspect_watermarks != 0, inspect_markdown_symmetry: inspect_markdown != 0, };
match analyze_article(validated, cfg) { Ok(report) => { let json = serialize_report_json(&report); let json_len = json.len(); REPORT_JSON_BUF.with(|slot| { *slot.borrow_mut() = json; }); json_len } Err(e) => record_error(&e), }}
/// Strips invisible Unicode watermarks (`ZWSP`, `ZWNJ`, `ZWJ`, `WJ`, `BOM`) and normalizes/// atypical LLM spaces (`U+202F`, `U+00A0`) to standard ASCII spaces./// Returns byte length of the sanitized UTF-8 buffer (or `0` if invalid UTF-8).////// # Safety/// If `len > 0`, `ptr` must reference `len` readable bytes in Wasm linear memory.#[no_mangle]pub unsafe extern "C" fn wasm_sanitize_text(ptr: *const u8, len: usize) -> usize { if ptr.is_null() || len == 0 { SANITIZED_TEXT_BUF.with(|slot| slot.borrow_mut().clear()); REMOVED_ZW_COUNT.with(|c| *c.borrow_mut() = 0); NORMALIZED_SPACE_COUNT.with(|c| *c.borrow_mut() = 0); return 0; } // SAFETY: Caller (`withWasmBuffer`) allocated and populated `ptr..ptr+len`. let raw_bytes = unsafe { core::slice::from_raw_parts(ptr, len) }; let Ok(raw_str) = core::str::from_utf8(raw_bytes) else { return record_error(&DetectError::InvalidUtf8); };
let result = sanitize_text(raw_str); let out_len = result.cleaned.len(); REMOVED_ZW_COUNT.with(|c| { *c.borrow_mut() = u32::try_from(result.removed_zero_width).unwrap_or(u32::MAX); }); NORMALIZED_SPACE_COUNT.with(|c| { *c.borrow_mut() = u32::try_from(result.normalized_spaces).unwrap_or(u32::MAX); }); SANITIZED_TEXT_BUF.with(|slot| { *slot.borrow_mut() = result.cleaned; }); out_len}
#[cfg(test)]#[allow(clippy::expect_used)]mod tests { use super::*; use crate::model::VerdictBand; use crate::watermark::{is_atypical_llm_space, is_zero_width_watermark};
#[test] fn crc32_ieee_matches_standard_check_vector() { assert_eq!(crc32_ieee(b"123456789"), 0xCBF4_3926); }
#[test] fn validation_rejects_empty_and_too_short_inputs_algebraically() { assert_eq!( ValidatedArticle::try_new(" \n\t "), Err(DetectError::EmptyDocument) ); assert_eq!( ValidatedArticle::try_new("Too short"), Err(DetectError::TooShort { observed_chars: 8, minimum_chars: 12 }) ); }
// Law: forall s, sanitize_text(&sanitize_text(s).cleaned).cleaned == sanitize_text(s).cleaned #[test] fn sanitize_text_is_idempotent_and_erases_all_watermarks() { let fixtures = [ "Hello\u{200B} world\u{202F}from\u{FEFF} LLM\u{2060} output\u{00A0}test!", "值得\u{200C}注意\u{200D}的是\u{202F}这是一段测试文本。", "Clean human sentence without hidden codepoints.", ]; for sample in fixtures { let once = sanitize_text(sample); let twice = sanitize_text(&once.cleaned); assert_eq!(once.cleaned, twice.cleaned); assert_eq!(twice.removed_zero_width, 0); assert_eq!(twice.normalized_spaces, 0); assert!(!once .cleaned .chars() .any(|c| is_zero_width_watermark(c) || is_atypical_llm_space(c))); } }
#[test] fn stereotypical_english_llm_essay_scores_substantially_higher_than_spiky_human_note() { let ai_essay = "\In today's rapidly evolving landscape, artificial intelligence plays a pivotal role in transforming modern industries. \Furthermore, it is important to note that organizations must delve into ethical frameworks to ensure sustainable innovation. \Moreover, fostering a sense of transparency underscores the importance of responsible governance across global teams.\u{200B}\u{202F}\n\- **Operational Efficiency**: Streamlining repetitive workflows across departments to maximize productivity.\n\- **Strategic Alignment**: Navigating the complexities of digital transformation with a multifaceted approach.\n\- **Scalable Architecture**: Building resilient pipelines that empower stakeholders across the ecosystem.\n\In conclusion, embracing this paradigm shift is a testament to the enduring power of human-centric technology.";
let human_note = "\Clearly, this expenditure pattern is a massive misallocation of resources. \The last 20% of network hashpower provides vastly less value to the ecosystem than those same resources would \if they had gone into research and core protocol development. So why not just.... cut the PoW budget by 20% and redirect the funds to those other things instead? \In early 2020, Justin Sun bought Steem-the-company, which is not the same thing as Steem-the-blockchain but did hold about 20% of the STEEM token supply.";
let v_ai = ValidatedArticle::try_new(ai_essay).expect("valid ai sample"); let v_hu = ValidatedArticle::try_new(human_note).expect("valid human sample");
let rep_ai = analyze_article(v_ai, DetectionConfig::default()).expect("ai report"); let rep_hu = analyze_article(v_hu, DetectionConfig::default()).expect("human report");
assert!( rep_ai.overall_ai_score.get() > 0.72, "Expected high AI score, got {}", rep_ai.overall_ai_score.get() ); assert_eq!(rep_ai.verdict, VerdictBand::AiGenerated); assert!( rep_hu.overall_ai_score.get() < 0.42, "Expected low AI score for spiky human prose, got {}", rep_hu.overall_ai_score.get() ); assert!(rep_ai.overall_ai_score.get() > rep_hu.overall_ai_score.get() + 0.35); }
#[test] fn chinese_llm_template_article_distinguished_from_colloquial_human_writing() { let zh_ai = "\在当今快速发展的数字时代,人工智能正在各个领域扮演着至关重要的角色。值得注意的是,企业不仅需要关注底层算力的提升,\而且还需要从多维度构建全方位的安全治理体系,从而实现真正的生态闭环。\u{200B}与此同时,如何平衡技术创新与隐私保护也是一把双刃剑。\总而言之,综上所述,只有持续赋能核心业务场景,才能在激烈的市场竞争中立于不败之地。";
let zh_human = "\凌晨两点半被报警电话吵醒,爬起来一看又是上游那个祖传接口超时!明明上周五联调的时候拍胸脯说绝对抗得住三千并发,\结果才刚切了十分之一流量,数据库连接池就直接打满躺平了。算了,先手动降级把队列消费停掉保命,明天早会必须把锅甩清楚。";
let r_ai = analyze_article( ValidatedArticle::try_new(zh_ai).expect("valid zh ai"), DetectionConfig::default(), ) .expect("zh ai report"); let r_hu = analyze_article( ValidatedArticle::try_new(zh_human).expect("valid zh human"), DetectionConfig::default(), ) .expect("zh human report");
assert!( r_ai.overall_ai_score.get() > r_hu.overall_ai_score.get() + 0.25, "Expected Chinese AI text ({}) > Chinese human text ({})", r_ai.overall_ai_score.get(), r_hu.overall_ai_score.get() ); assert!(r_ai.removable_watermark_chars >= 1); }
// Law (Shapley Local Accuracy): forall x, expected_margin + sum_j shap[j] == unshifted_raw_margin(x) #[test] fn treeshap_satisfies_exact_local_accuracy_additivity_law() { use crate::gbdt::predict_with_treeshap; use crate::hash_tables::MlTablesView; use crate::ml_features::{extract_ml_features_with_tables, EMBEDDED_ML_TABLES}; use crate::trained_forest::with_trained_gbdt;
let tables = MlTablesView::from_bytes(EMBEDDED_ML_TABLES).expect("valid ml_tables.bin"); let fixtures = [ "Clearly, this expenditure pattern is a massive misallocation of resources across protocol development.", "In today's rapidly evolving landscape, artificial intelligence plays a pivotal role in fostering innovation.", "刚刚我在下面看了一下,一些吐槽我觉得特别好。每天都有五亿人在说我们做的不好。", "プログラミングは本来楽しいものであり、楽しいからこそ能力が向上するのだと私は思います。", ]; for sample in fixtures { let bundle = extract_ml_features_with_tables(sample, true, tables); let pred = with_trained_gbdt(|gbdt| predict_with_treeshap(gbdt, &bundle.features, 0.0)) .expect("valid gbdt"); let shap_sum: f64 = pred.shap_values.iter().copied().sum(); let reconstructed = pred.expected_margin + shap_sum; let diff = (reconstructed - pred.raw_margin).abs(); assert!( diff < 1e-8, "TreeSHAP local accuracy violated: reconstructed={reconstructed}, raw={}, diff={diff}", pred.raw_margin ); } }
// Law (Concave Mixture MLE Monotonicity): increasing AI token counts strictly increases/preserves alpha_hat in [0, 1] #[test] fn mixture_mle_solver_is_bounded_and_monotone() { use crate::hash_tables::{solve_mixture_mle, MlTablesView}; use crate::ml_features::EMBEDDED_ML_TABLES; use std::collections::BTreeMap;
let tables = MlTablesView::from_bytes(EMBEDDED_ML_TABLES).expect("valid ml_tables.bin"); let mut human_heavy = BTreeMap::new(); let mut ai_heavy = BTreeMap::new(); for b in 0..512u16 { let (p, q) = tables.lookup_mle_probs(b); if p > q * 1.15 { human_heavy.insert(b, 10); ai_heavy.insert(b, 1); } else if q > p * 1.15 { human_heavy.insert(b, 1); ai_heavy.insert(b, 10); } } if !human_heavy.is_empty() && !ai_heavy.is_empty() { let (a_lo, _, _) = solve_mixture_mle(&human_heavy, tables); let (a_hi, _, _) = solve_mixture_mle(&ai_heavy, tables); assert!((0.0..=1.0).contains(&a_lo)); assert!((0.0..=1.0).contains(&a_hi)); assert!( a_hi >= a_lo, "Expected monotone MLE alpha_hat: {a_hi} >= {a_lo}" ); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858//! Dual-Proxy Corpus Language Model & Modern RLHF Syntactic Log-Odds Scorer (`lm_proxy`).//!//! Inspired by Ghostbuster (NAACL) and GPTZero's multi-indicator architecture://! 1. Scores token/character transitions against embedded RLHF-vs-Human log-odds lexicons across//! English, Simplified/Traditional Chinese, and Japanese (covering GPT-4o, Claude, DeepSeek, Qwen).//! 2. Evaluates structural negative parallelisms ("not just X, but Y", "不是…而是…", "単なる…ではなく"),//! participial clause tails (", ensuring...", ", making it..."), conceptual scare-quotes ("“XX”"),//! and nominalization/glue smoothness.//! 3. Computes per-sentence proxy surprisal & cross-sentence surprisal burstiness, catching clean,//! cliché-free LLM articles via flat predictability pacing.
use crate::model::{ScriptFamily, UnitScore};
/// High-log-odds English RLHF vocabulary stems (GPT-4o / Claude / Llama / DeepSeek).const EN_RLHF_WORDS: &[(&str, f64)] = &[ ("delve", 2.4), ("delves", 2.4), ("delving", 2.4), ("tapestry", 2.5), ("testament", 2.0), ("pivotal", 2.1), ("crucial", 1.1), ("vital", 0.9), ("multifaceted", 2.3), ("nuanced", 1.7), ("nuances", 1.6), ("underscore", 2.0), ("underscores", 2.2), ("underscoring", 2.2), ("foster", 1.7), ("fostering", 2.0), ("fosters", 1.8), ("realm", 1.7), ("beacon", 1.9), ("interplay", 2.1), ("synergy", 1.8), ("holistic", 1.9), ("seamless", 1.6), ("seamlessly", 1.9), ("leverage", 1.3), ("leveraging", 1.7), ("harness", 1.6), ("harnessing", 1.9), ("empower", 1.6), ("empowering", 1.8), ("empowers", 1.7), ("elevate", 1.5), ("elevating", 1.7), ("streamline", 1.6), ("streamlining", 1.8), ("transformative", 1.9), ("paradigm", 1.9), ("ecosystem", 1.2), ("stakeholders", 1.6), ("actionable", 1.7), ("overarching", 0.9), ("intricate", 1.7), ("intricacies", 2.0), ("meticulous", 1.8), ("meticulously", 2.0), ("commendable", 1.9), ("indispensable", 1.6), ("catalyst", 1.6), ("cornerstone", 1.7), ("navigating", 1.8), ("embark", 1.8), ("poised", 1.6), ("unprecedented", 1.3), ("burgeoning", 2.0), ("resonate", 1.5), ("resonates", 1.7), ("alignment", 1.3), ("reimagine", 1.9), ("demystify", 2.0), ("illuminate", 1.6), ("illuminates", 1.8), ("spearhead", 1.8), ("bolster", 1.5), ("cultivate", 1.5), ("cultivating", 1.7), ("landscape", 1.4), ("moreover", 1.6), ("furthermore", 1.7), ("additionally", 1.2), ("consequently", 1.1), ("ultimately", 1.0), ("notably", 1.1), ("undeniably", 1.6),];
/// Modern English syntactic & rhetorical frames favored by GPT-4o, Claude, and DeepSeek.const EN_RLHF_FRAMES: &[(&str, f64)] = &[ ("not just ", 1.5), ("not merely ", 1.8), ("more than just ", 1.7), ("isn't just ", 1.6), ("aren't just ", 1.6), ("it's not about ", 1.8), ("it is not about ", 1.8), ("isn't about ", 1.8), ("not because ", 1.3), ("more often than not", 1.7), ("at its core", 1.9), ("in essence,", 1.7), ("the reality is", 1.4), ("here's why", 1.4), ("here's what", 1.5), ("here's the ", 1.3), ("that's why ", 1.2), ("think about what happens", 1.6), ("moves the needle", 1.7), ("nice-to-have", 1.5), ("first-class", 1.2), ("narrative coherence", 2.0), ("peculiar comfort", 1.8), ("this is where ", 1.3), ("that's where ", 1.3), ("whether you're ", 1.5), ("whether it's ", 1.5), ("it is important to note", 2.4), ("it's important to note", 2.4), ("it is worth noting", 2.1), ("it's worth noting", 2.0), ("in conclusion,", 2.0), ("in summary,", 1.9), ("on one hand", 1.4), ("on the other hand", 1.3), ("at the same time,", 1.1), ("by doing so,", 1.6), ("in other words,", 1.1), ("with that in mind", 1.7), ("moving forward", 1.4), ("looking ahead", 1.4), ("plays a pivotal role", 2.5), ("plays a crucial role", 2.2), ("plays a vital role", 2.1), ("rapidly evolving", 2.2), ("ever-evolving", 2.3), ("rich tapestry", 2.6), ("a testament to", 2.1), (", making it ", 1.3), (", allowing ", 1.2), (", enabling ", 1.4), (", ensuring ", 1.5), (", creating ", 1.2), (", fostering ", 2.0), (", highlighting ", 1.6), (", underscoring ", 2.1), (", reflecting ", 1.3), (", offering ", 1.3), (", paving the way", 2.0),];
/// Chinese RLHF vocabulary, abstract nominalizations & syntactic markers (GPT-4o / Claude / DeepSeek / Qwen).const ZH_RLHF_MARKERS: &[(&str, f64)] = &[ ("值得注意的是", 2.3), ("值得一提的是", 1.9), ("需要指出的是", 2.1), ("不可否认", 1.7), ("毫无疑问", 1.5), ("显而易见", 1.5), ("不难发现", 1.8), ("不难看出", 1.7), ("这意味着", 1.5), ("这也意味着", 1.7), ("换句话说", 1.4), ("换言之", 1.4), ("某种程度上", 1.5), ("从某种意义上", 1.7), ("从本质上讲", 1.9), ("本质上", 1.2), ("归根结底", 1.6), ("事实上,", 1.2), ("在此背景下", 1.9), ("正因如此", 1.5), ("由此可见", 1.6), ("更重要的是", 1.2), ("尤为重要的是", 1.8), ("与此同时", 1.4), ("不仅如此", 1.5), ("除此之外", 1.2), ("总而言之", 2.2), ("综上所述", 2.2), ("总的来看", 1.7), ("展望未来", 1.8), ("赋能", 2.1), ("闭环", 2.0), ("抓手", 2.0), ("底座", 1.7), ("范式", 1.8), ("颗粒度", 1.9), ("心智", 1.6), ("势能", 1.8), ("场域", 1.9), ("底层逻辑", 1.9), ("顶层设计", 1.8), ("全链路", 1.9), ("护城河", 1.5), ("方法论", 1.5), ("差异化", 1.4), ("规模化", 1.3), ("精细化", 1.4), ("常态化", 1.4), ("多元化", 1.3), ("系统性", 1.2), ("结构性", 1.3), ("确定性", 1.4), ("可持续", 1.3), ("多维度", 1.9), ("全方位", 1.7), ("深层次", 1.5), ("核心竞争力", 1.7), ("不可或缺", 1.6), ("至关重要", 1.8), ("息息相关", 1.5), ("相辅相成", 1.6), ("潜移默化", 1.4), ("双刃剑", 1.8), ("重塑", 1.5), ("重构", 1.3), ("洞察", 1.4), ("锚定", 1.8), ("拆解", 1.3), ("沉淀", 1.5), ("演进", 1.3), ("深耕", 1.6), ("注入了", 1.6), ("展现出", 1.3), ("呈现出", 1.3), ("折射出", 1.6), ("扮演着", 1.8), ("发挥着", 1.6), ("在当今", 2.0), ("随着科技", 1.9), ("悄然", 1.6), ("支离破碎", 1.6), ("延迟满足", 1.7), ("情绪内耗", 1.8), ("课题分离", 1.8), ("生活质感", 1.9), ("庸常瞬间", 2.0), ("或许所谓的", 2.1), ("温和抵抗", 1.9), ("精神锚点", 2.0), ("说到底,", 1.3), ("很多人以为", 1.5), ("總而言之", 2.2), ("綜上所述", 2.2), ("扮演著", 1.8), ("發揮著", 1.6), ("至關重要", 1.8), ("不可或缺", 1.6), ("多維度", 1.9), ("生態閉環", 2.2), ("底層邏輯", 1.9), ("這意味著", 1.5), ("換句話說", 1.4), ("在此背景下", 1.9), ("與此同時", 1.4),];
/// Japanese RLHF markers (GPT-4o / Claude / DeepSeek Japanese prose).const JA_RLHF_MARKERS: &[(&str, f64)] = &[ ("重要な点として", 2.2), ("特筆すべき", 2.0), ("結論として", 2.0), ("総じて言えば", 2.1), ("言い換えれば", 1.5), ("すなわち、", 1.3), ("このように、", 1.3), ("その一方で", 1.3), ("にとどまらず", 1.7), ("重要な役割を果たし", 2.1), ("不可欠な要素", 1.9), ("多面的な視点", 2.1), ("包括的な", 1.7), ("持続可能な", 1.5), ("急速に進化", 2.0), ("パラダイム", 1.8), ("浮き彫りに", 1.6), ("再定義", 1.6), ("枠組み", 1.3),];
/// Output of the proxy language model & RLHF syntactic scorer.#[derive(Debug, Clone)]pub struct ProxyLmAnalysis { /// Document-level RLHF lexical & syntactic log-odds AI score (`[0.0, 1.0]`). pub rlhf_discourse_score: UnitScore, /// Proxy language model predictability & cross-sentence surprisal flatness (`[0.0, 1.0]`). pub perplexity_flatness_score: UnitScore, /// Per-sentence proxy AI likelihood (`len == all_sentences.len()`). pub sentence_lm_scores: Vec<f64>, /// Per-sentence hit counts of RLHF frames/stems. pub sentence_hit_counts: Vec<usize>, /// Mean sentence proxy surprisal (`bits/token` equivalent). pub mean_surprisal_bits: f64, /// Cross-sentence surprisal coefficient of variation (low = flat AI perplexity). pub surprisal_cv: f64, /// Top matched RLHF phrases / syntactic frames for explainability UI. pub matched_signals: Vec<String>,}
fn push_unique_signal(out: &mut Vec<String>, label: &str) { if out.len() < 12 && !out.iter().any(|s| s == label) { out.push(label.to_string()); }}
/// Detects paired contrastive / negative-parallelism constructions inside a sentence.#[must_use]pub fn count_paired_contrast_frames(sent_lower: &str) -> (usize, Option<&'static str>) { const PAIRS: &[(&str, &str, &str)] = &[ ("不是", "而是", "不是…而是…"), ("并非", "而是", "并非…而是…"), ("不再是", "而", "不再是…而…"), ("从来不", "而", "从来不…而…"), ("从来不在", "藏在", "从来不在…就藏在…"), ("不在于", "而在于", "不在于…而在于…"), ("不只是", "更是", "不只是…更是…"), ("不仅仅是", "更是", "不仅仅是…更是…"), ("不仅是", "更是", "不仅是…更是…"), ("不仅", "而且", "不仅…而且…"), ("与其说", "不如说", "与其说…不如说…"), ("一方面", "另一方面", "一方面…另一方面…"), ("无论是", "还是", "无论是…还是…"), ("既要", "又要", "既要…又要…"), ("not only ", " but also ", "not only ... but also"), ("not just ", " but ", "not just ... but"), ("not merely ", " but ", "not merely ... but"), ( "not because ", " but because ", "not because ... but because", ), ("isn't ", "; it's ", "isn't X; it's Y"), ("isn't ", "—it's ", "isn't X—it's Y"), ("rather than ", ", ", "rather than ... contrast"), ("until ", ", they remain ", "until X, they remain Y"), ("単なる", "ではなく", "単なる…ではなく"), ("だけでなく", "もまた", "だけでなく…もまた"), ]; let mut hits = 0usize; let mut first_label = None; for &(left, right, label) in PAIRS { if let Some(pos) = sent_lower.find(left) { let after = pos.saturating_add(left.len()); if let Some(rest) = sent_lower.get(after..) { if rest.contains(right) { hits = hits.saturating_add(1); if first_label.is_none() { first_label = Some(label); } } } } } (hits, first_label)}
/// Counts short conceptual scare-quotes (`“XX”` or `「XX」` wrapping 2–6 chars).#[must_use]fn count_conceptual_scare_quotes(text: &str) -> usize { let mut count = 0usize; for (open_q, close_q) in [('“', '”'), ('「', '」')] { let mut rest = text; while let Some(start) = rest.find(open_q) { let after_open = start.saturating_add(open_q.len_utf8()); let Some(tail) = rest.get(after_open..) else { break; }; let Some(end) = tail.find(close_q) else { break; }; if let Some(inner) = tail.get(..end) { let char_len = inner.chars().count(); let has_punct = inner .chars() .any(|c| matches!(c, ',' | '。' | '!' | '?' | ',' | '.' | ':')); if (2..=6).contains(&char_len) && !has_punct { count = count.saturating_add(1); } } let next_start = end.saturating_add(close_q.len_utf8()); rest = tail.get(next_start..).unwrap_or(""); } } count}
fn cjk_clause_surprisal(sentence: &str) -> f64 { const CJK_ABSTRACT: &[char] = &[ '化', '性', '度', '体', '系', '机', '制', '模', '式', '赋', '维', '环', '态', '域', '层', '构', '筑', '塑', ]; const CJK_SPOKEN_STANCE: &[&str] = &[ "我觉得", "我覺得", "我喜欢", "我喜歡", "我不在乎", "我是", "我们做", "我們做", "咱们", "咱們", "说不定", "說不定", "实话说", "實話說", "可惜", "私", "僕", "思います", "信じています", "可愛い", "んです", "わけです", ]; let chars: Vec<char> = sentence.chars().filter(|c| !c.is_whitespace()).collect(); let total = chars.len().max(1); let abs_cnt = chars.iter().filter(|c| CJK_ABSTRACT.contains(c)).count(); let abs_ratio = (abs_cnt as f64) / (total as f64); let mut delta = 0.0f64; if abs_ratio >= 0.07 { delta -= (abs_ratio * 5.0).min(0.68); } if CJK_SPOKEN_STANCE.iter().any(|&s| sentence.contains(s)) { delta += 0.54; } else if sentence.contains('我') || sentence.contains('你') { delta += 0.28; } let clauses: Vec<usize> = sentence .split([',', ',', '、', ';']) .map(|cl| cl.chars().filter(|c| !c.is_whitespace()).count()) .filter(|&len| len > 0) .collect(); if clauses.len() >= 3 { let mean_cl = (clauses.iter().sum::<usize>() as f64) / (clauses.len() as f64); if clauses.iter().all(|&c| (8..=22).contains(&c)) && (10.5..=18.5).contains(&mean_cl) { delta -= 0.42; } } delta}
fn alpha_clause_surprisal(sentence: &str) -> f64 { const FIRST_PERSON: &[&str] = &[ "i", "i'm", "i've", "i'd", "i'll", "my", "me", "we", "we're", "we've", "our", "us", "you", "you're", "your", ]; const RLHF_GERUNDS: &[&str] = &[ "fostering", "navigating", "leveraging", "streamlining", "reshaping", "embracing", "cultivating", "empowering", "underscoring", "prioritizing", "optimizing", "unlocking", "bridging", "harnessing", ]; let raw_words: Vec<&str> = sentence .split(|c: char| !c.is_alphabetic() && c != '\'') .filter(|w| !w.is_empty()) .collect(); let total = raw_words.len().max(1); let words: Vec<String> = raw_words.iter().map(|w| w.to_lowercase()).collect();
let nom_cnt = words .iter() .filter(|w| { RLHF_GERUNDS.contains(&w.as_str()) || (w.len() >= 8 && (w.ends_with("tion") || w.ends_with("tions") || w.ends_with("ment") || w.ends_with("ments") || w.ends_with("ity") || w.ends_with("ities") || w.ends_with("ness"))) }) .count(); let has_stance = words.iter().any(|w| FIRST_PERSON.contains(&w.as_str())); let proper_nouns = raw_words .iter() .skip(1) .filter(|w| w.len() >= 3 && w.chars().next().map(char::is_uppercase).unwrap_or(false)) .count();
let nom_ratio = (nom_cnt as f64) / (total as f64); let mut delta = 0.0f64; if nom_ratio >= 0.10 { delta -= (nom_ratio * 3.4).min(0.68); } if total >= 13 && !has_stance && proper_nouns == 0 { delta -= 0.34; } if has_stance { delta += 0.36; } if proper_nouns >= 1 { delta += (proper_nouns as f64 * 0.18).min(0.42); } if sentence.contains('(') || sentence.contains("...") || sentence.contains(';') { delta += 0.24; } delta}
/// Estimates proxy surprisal (in bits per token equivalent) for a single prose sentence.#[must_use]pub fn estimate_sentence_surprisal_bits(sentence: &str, script: ScriptFamily) -> f64 { const HUMAN_COLLOQUIAL: &[&str] = &[ "wait", "honestly", "literally", "weird", "crazy", "damn", "ugh", "btw", "imo", "tbh", "gonna", "wanna", "kinda", "sorta", "heck", "nope", "yep", "folks", "居然", "简直", "离谱", "吐槽", "折腾", "压根", "说白了", "算了", "哈哈", "偏偏", "硬是", "真绝", "干脆", "莫名其妙", "说实话", "毛病", "狂刷", "搞明白", "抽风", "老头儿", "泥巴", "嘎嘣", "老婆", "笑话", "哪有", "钟头", "鐘頭", "離譜", "古怪", "遣散", "訴苦", "发呆", "發呆", "没边儿", "愣半天", "turns out", "sure—", "barely", "declined to", "pretend", "fool ", "まさか", "ぶっちゃけ", "なんか", "やばい", "しかめ面", "タクシードライバー", ]; let mut surprisal = 4.60f64; surprisal += if script.uses_ideographic_cadence() { cjk_clause_surprisal(sentence) } else { alpha_clause_surprisal(sentence) };
let digit_groups = sentence .split(|c: char| !c.is_ascii_digit()) .filter(|s| !s.is_empty()) .count(); if digit_groups >= 2 { surprisal += 0.46; } else if digit_groups == 1 { surprisal += 0.18; }
if sentence .chars() .any(|c| matches!(c, '?' | '!' | '?' | '!' | '`' | '/')) { surprisal += 0.44; } let lower = sentence.to_lowercase(); if HUMAN_COLLOQUIAL.iter().any(|&kw| lower.contains(kw)) { surprisal += 0.88; } surprisal.clamp(2.4, 8.2)}
fn accumulate_english_odds(lower_full: &str, signals: &mut Vec<String>) -> f64 { let mut odds = 0.0f64; for word in lower_full.split(|c: char| !c.is_alphabetic()) { if word.is_empty() { continue; } for &(stem, w) in EN_RLHF_WORDS { if word == stem { odds += w; push_unique_signal(signals, stem); break; } } } for &(frame, w) in EN_RLHF_FRAMES { let cnt = lower_full.matches(frame).count(); if cnt > 0 { odds += w * (cnt as f64).min(4.0); push_unique_signal(signals, frame.trim_matches(|c: char| c == ',' || c == ' ')); } } odds}
fn accumulate_cjk_odds(full_text: &str, signals: &mut Vec<String>) -> f64 { let mut odds = 0.0f64; for &(marker, w) in ZH_RLHF_MARKERS.iter().chain(JA_RLHF_MARKERS.iter()) { let cnt = full_text.matches(marker).count(); if cnt > 0 { odds += w * (cnt as f64).min(4.0); push_unique_signal(signals, marker); } } let scare_quotes = count_conceptual_scare_quotes(full_text); let char_k = (full_text.chars().count().max(120) as f64) / 1000.0; let sq_per_k = (scare_quotes as f64) / char_k; if scare_quotes >= 3 && sq_per_k >= 4.0 { odds += ((sq_per_k - 3.0) * 0.45).min(4.5); push_unique_signal(signals, "“概念双引号”高频修饰"); } odds}
fn accumulate_markdown_odds(full_text: &str, signals: &mut Vec<String>) -> f64 { let mut headings = 0usize; let mut bold_bullets = 0usize; let mut plain_bullets = 0usize; for line in full_text.lines() { let t = line.trim_start(); if t.starts_with("# ") || t.starts_with("## ") || t.starts_with("### ") { headings = headings.saturating_add(1); } else if t.starts_with("- ") || t.starts_with("* ") || t.starts_with("1. ") || t.starts_with("2. ") || t.starts_with("3. ") || t.starts_with("4. ") { plain_bullets = plain_bullets.saturating_add(1); if t.contains("**:") || t.contains("**:") || t.contains("** —") || t.contains("** -") { bold_bullets = bold_bullets.saturating_add(1); } } } if bold_bullets >= 2 { push_unique_signal(signals, "Markdown **Bold**: List"); 2.6 + ((bold_bullets as f64) * 0.75).min(3.6) } else if headings >= 2 && plain_bullets >= 3 { 1.9 } else if headings >= 3 { 1.1 } else { 0.0 }}
fn score_single_sentence(sent: &str, script: ScriptFamily) -> (f64, usize) { let s_low = sent.to_lowercase(); let (mut s_hits, _) = count_paired_contrast_frames(&s_low); if !matches!(script, ScriptFamily::Cjk) { s_hits = s_hits.saturating_add( EN_RLHF_FRAMES .iter() .filter(|&&(f, _)| s_low.contains(f)) .count(), ); s_hits = s_hits.saturating_add( s_low .split(|c: char| !c.is_alphabetic()) .filter(|w| EN_RLHF_WORDS.iter().any(|&(st, _)| &st == w)) .count(), ); } if script.uses_ideographic_cadence() { s_hits = s_hits.saturating_add( ZH_RLHF_MARKERS .iter() .chain(JA_RLHF_MARKERS.iter()) .filter(|&&(m, _)| sent.contains(m)) .count(), ); } let s_bits = estimate_sentence_surprisal_bits(sent, script); let prob = (0.54 + (4.58 - s_bits) * 0.42 + (s_hits as f64) * 0.17).clamp(0.03, 0.98); (prob, s_hits)}
fn accumulate_rhetorical_cadence_odds( lower_full: &str, prose_sentences: &[String], script: ScriptFamily, signals: &mut Vec<String>,) -> f64 { let mut odds = 0.0f64; let mut consec_short_decl = 0usize; let mut max_consec_short = 0usize; let mut consec_questions = 0usize; let mut max_consec_q = 0usize; for s in prose_sentences { let trimmed = s.trim(); let wc = trimmed .split(|c: char| !c.is_alphanumeric()) .filter(|w| !w.is_empty()) .count(); if trimmed.ends_with('.') && (2..=4).contains(&wc) && !script.uses_ideographic_cadence() { consec_short_decl = consec_short_decl.saturating_add(1); max_consec_short = max_consec_short.max(consec_short_decl); } else { consec_short_decl = 0; } if trimmed.ends_with('?') || trimmed.ends_with('?') { consec_questions = consec_questions.saturating_add(1); max_consec_q = max_consec_q.max(consec_questions); } else { consec_questions = 0; } } if max_consec_short >= 2 { odds += 2.9; push_unique_signal(signals, "Staccato Triplet Rhythm"); } if max_consec_q >= 2 { odds += 2.2; push_unique_signal(signals, "Rhetorical Question Series"); } if lower_full.contains("everyone talks about") && lower_full.contains("nobody talks about") { odds += 2.6; push_unique_signal(signals, "everyone talks / nobody talks"); } odds}
/// Evaluates full document and sentence-level proxy LM & RLHF stylometric signals.#[must_use]pub fn evaluate_proxy_lm( full_text: &str, prose_sentences: &[String], all_sentences: &[String], script: ScriptFamily, inspect_markdown: bool,) -> ProxyLmAnalysis { let lower_full = full_text.to_lowercase(); let mut matched_signals: Vec<String> = Vec::new(); let mut total_log_odds = 0.0f64;
if !matches!(script, ScriptFamily::Cjk) { total_log_odds += accumulate_english_odds(&lower_full, &mut matched_signals); } if script.uses_ideographic_cadence() { total_log_odds += accumulate_cjk_odds(full_text, &mut matched_signals); } for sent in all_sentences { let (cnt, lbl) = count_paired_contrast_frames(&sent.to_lowercase()); if cnt > 0 { total_log_odds += (cnt as f64) * 1.95; if let Some(label_str) = lbl { push_unique_signal(&mut matched_signals, label_str); } } } total_log_odds += accumulate_rhetorical_cadence_odds( &lower_full, prose_sentences, script, &mut matched_signals, ); if inspect_markdown { total_log_odds += accumulate_markdown_odds(full_text, &mut matched_signals); }
let eff_sents = ((prose_sentences.len().max(2)) as f64).powf(0.76); let odds_density = total_log_odds / eff_sents; let rlhf_discourse_score = UnitScore::clamped(1.0 / (1.0 + (-1.45 * (odds_density - 0.78)).exp()));
let eval_pool = if prose_sentences.is_empty() { all_sentences } else { prose_sentences }; let surprisals: Vec<f64> = eval_pool .iter() .map(|s| estimate_sentence_surprisal_bits(s, script)) .collect(); let mean_surprisal_bits = if surprisals.is_empty() { 4.5 } else { surprisals.iter().sum::<f64>() / (surprisals.len() as f64) }; let surprisal_cv = if surprisals.len() >= 2 { let var = surprisals .iter() .map(|&x| (x - mean_surprisal_bits).powi(2)) .sum::<f64>() / (surprisals.len() as f64); var.sqrt() / mean_surprisal_bits.max(1.0) } else { 0.10 };
let low_ppl_signal = (4.58 - mean_surprisal_bits).clamp(-1.2, 1.2) * 0.46; let flat_cv_signal = (0.12 - surprisal_cv).clamp(-0.12, 0.10) * 2.8; let perplexity_flatness_score = UnitScore::clamped(0.52 + low_ppl_signal + flat_cv_signal);
let mut sentence_lm_scores = Vec::with_capacity(all_sentences.len()); let mut sentence_hit_counts = Vec::with_capacity(all_sentences.len()); for sent in all_sentences { let (p, h) = score_single_sentence(sent, script); sentence_lm_scores.push(p); sentence_hit_counts.push(h); }
ProxyLmAnalysis { rlhf_discourse_score, perplexity_flatness_score, sentence_lm_scores, sentence_hit_counts, mean_surprisal_bits, surprisal_cv, matched_signals, }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197//! Information-theoretic AI prose forensics inspired by ZipPy (LZ77 compression redundancy)//! and Miller-Madow bias-corrected character n-gram entropy.//!//! All indexing uses checked `.get()` accessors so `-D clippy::indexing_slicing` holds everywhere.
use std::collections::BTreeMap;
use crate::model::{ScriptFamily, UnitScore};
/// Information-theoretic compression summary calibrated across `50 B .. 512 KiB`.#[derive(Debug, Clone, Copy)]pub struct EntropyMetrics { /// Deterministic sliding-window LZ77 compressed-to-raw ratio (`(0.0, 1.0]`). pub lz77_ratio: f64, /// Unigram character Shannon entropy $H_1$ in bits per character. pub unigram_entropy_bits: f64, /// Conditional bigram Shannon entropy $H(c_t \mid c_{t-1})$ in bits per character. pub conditional_entropy_bits: f64, /// Predictability ratio $H(c_t \mid c_{t-1}) / \max(H_1, 0.5)$. pub cross_entropy_ratio: f64, /// Normalized ZipPy compression predictability score (`[0.0, 1.0]`, higher = more AI-like). pub compression_ai_score: UnitScore,}
/// Computes deterministic 4-chain sliding-window LZ77 compressed ratio on UTF-8 bytes/// (matching >= 3-byte syntactic n-grams so short & medium articles register true clause reuse).#[must_use]pub fn compute_lz77_ratio(bytes: &[u8]) -> f64 { if bytes.is_empty() { return 1.0; } const HASH_BITS: usize = 12; const HASH_SIZE: usize = 1 << HASH_BITS; const HASH_MASK: usize = HASH_SIZE - 1; const WINDOW: usize = 8192; const MAX_MATCH: usize = 96;
let mut head = vec![usize::MAX; HASH_SIZE]; let mut prev_chain = vec![usize::MAX; bytes.len().min(65_536)]; let limit_total = bytes.len().min(65_536); let mut compressed_units = 0usize; let mut pos = 0usize;
while pos < limit_total { let mut best_len = 0usize; if let (Some(&b0), Some(&b1), Some(&b2)) = (bytes.get(pos), bytes.get(pos + 1), bytes.get(pos + 2)) { let h = (((b0 as usize) << 8) ^ ((b1 as usize) << 4) ^ (b2 as usize)) & HASH_MASK; let mut cand = head.get(h).copied().unwrap_or(usize::MAX); if let Some(slot) = prev_chain.get_mut(pos) { *slot = cand; } if let Some(h_slot) = head.get_mut(h) { *h_slot = pos; }
let mut hops = 0usize; while cand < pos && pos.saturating_sub(cand) <= WINDOW && hops < 8 { let max_l = MAX_MATCH.min(limit_total.saturating_sub(pos)); let mut mlen = 0usize; while mlen < max_l { match (bytes.get(cand + mlen), bytes.get(pos + mlen)) { (Some(&x), Some(&y)) if x == y => mlen += 1, _ => break, } } if mlen > best_len { best_len = mlen; } cand = prev_chain.get(cand).copied().unwrap_or(usize::MAX); hops += 1; } }
if best_len >= 4 { compressed_units = compressed_units.saturating_add(2); let end = pos.saturating_add(best_len).min(limit_total); let mut step = pos.saturating_add(1); while step < end { if let (Some(&c0), Some(&c1), Some(&c2)) = (bytes.get(step), bytes.get(step + 1), bytes.get(step + 2)) { let hh = (((c0 as usize) << 8) ^ ((c1 as usize) << 4) ^ (c2 as usize)) & HASH_MASK; let prev_h = head.get(hh).copied().unwrap_or(usize::MAX); if let Some(slot) = prev_chain.get_mut(step) { *slot = prev_h; } if let Some(h_slot) = head.get_mut(hh) { *h_slot = step; } } step += 1; } pos = end; } else { compressed_units = compressed_units.saturating_add(1); pos += 1; } }
((compressed_units as f64) / (limit_total as f64)).clamp(0.05, 1.0)}
/// Computes empirical LZ77 compression ratio calibrated accurately against human vs LLM length curves,/// plus first-order conditional bigram entropy $H(c_t \mid c_{t-1})$ (which converges rapidly without/// severe trigram sparsity bias).#[must_use]pub fn analyze_entropy_and_compression(text: &str, script: ScriptFamily) -> EntropyMetrics { let lz77_ratio = compute_lz77_ratio(text.as_bytes());
let mut norm_chars: Vec<char> = Vec::with_capacity(text.len().min(32_768)); let mut prev_space = false; for ch in text.chars().take(32_768) { if ch.is_whitespace() { if !prev_space { norm_chars.push(' '); prev_space = true; } } else { prev_space = false; for lc in ch.to_lowercase() { norm_chars.push(lc); } } }
let n = norm_chars.len(); if n < 4 { return EntropyMetrics { lz77_ratio, unigram_entropy_bits: 4.0, conditional_entropy_bits: 2.5, cross_entropy_ratio: 0.62, compression_ai_score: UnitScore::clamped(0.5), }; }
let mut unigram_counts: BTreeMap<char, u32> = BTreeMap::new(); for &c in &norm_chars { let e = unigram_counts.entry(c).or_insert(0); *e = e.saturating_add(1); }
let nf = n as f64; let mut h1 = 0.0f64; for &cnt in unigram_counts.values() { let p = (cnt as f64) / nf; if p > 0.0 { h1 -= p * p.log2(); } }
let mut bigram_counts: BTreeMap<(char, char), u32> = BTreeMap::new(); let mut bigram_total = 0u32; for pair in norm_chars.windows(2) { if let (Some(&c0), Some(&c1)) = (pair.first(), pair.get(1)) { let e = bigram_counts.entry((c0, c1)).or_insert(0); *e = e.saturating_add(1); bigram_total = bigram_total.saturating_add(1); } }
let mut h_cond = 0.0f64; let bf = (bigram_total.max(1)) as f64; for (&(c0, _c1), &bi_cnt) in &bigram_counts { let ctx_cnt = unigram_counts.get(&c0).copied().unwrap_or(bi_cnt); let p_xy = (bi_cnt as f64) / bf; let p_y_given_x = (bi_cnt as f64) / ((ctx_cnt.max(1)) as f64); if p_xy > 0.0 && p_y_given_x > 0.0 { h_cond -= p_xy * p_y_given_x.log2(); } }
let cross_entropy_ratio = (h_cond / h1.max(0.5)).clamp(0.05, 1.0);
// Empirically calibrated 8-hop LZ77 baseline across real pre-LLM human corpora: // At 700-1200 bytes: human ~0.75 (EN) / ~0.80 (CJK); at 4000 bytes: human ~0.68 (EN) / ~0.73 (CJK). let log_b = (text.len().max(150) as f64).ln(); let expected_human_lz = if script.uses_ideographic_cadence() { (1.11 - 0.047 * log_b).clamp(0.58, 0.83) } else { (1.08 - 0.049 * log_b).clamp(0.50, 0.79) };
let lz_saving = expected_human_lz - lz77_ratio; let compression_ai_score = UnitScore::clamped(0.42 + lz_saving * 2.8);
EntropyMetrics { lz77_ratio, unigram_entropy_bits: h1, conditional_entropy_bits: h_cond, cross_entropy_ratio, compression_ai_score, }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255//! Unified 28-Dimensional Orthogonal ML Feature Extractor & Sentence-Level Posterior Scorer (`ml_features`).//!//! Guarantee (Zero Train-Serve Skew): Both offline training (`rust_trainer`) and in-browser WebAssembly//! inference invoke `extract_ml_features_with_tables` on identical UTF-8 slices.
use std::collections::BTreeMap;
use crate::cooccur_graph::{analyze_cooccurrence_graph, CooccurGraphMetrics};use crate::diveye::{compute_diveye_profile, DivEyeProfile};use crate::gbdt::NUM_GBDT_FEATURES;use crate::hash_tables::{evaluate_hash_models, HashModelScan, MlTablesView};use crate::lm_proxy::{evaluate_proxy_lm, ProxyLmAnalysis};use crate::lz_entropy::analyze_entropy_and_compression;use crate::model::ScriptFamily;use crate::stylometry::{ compute_burstiness_and_paragraphs, compute_lexical_diversity, count_cadence_units, detect_script_family, extract_lexical_tokens, is_cjk_or_kana, segment_prose_and_display,};
/// Embedded quantized statistical tables (`DualPpm` + `MixtureMle` + `HashedNbSvm`, `327,696` bytes).pub static EMBEDDED_ML_TABLES: &[u8] = include_bytes!("weights/ml_tables.bin");
/// Complete intermediate ML analysis of a validated UTF-8 document.#[derive(Debug, Clone)]pub struct DocumentMlBundle { /// Dominant script family. pub script_family: ScriptFamily, /// Continuous ratio of CJK/Kana characters in `[0.0, 1.0]`. pub cjk_share: f64, /// Segmented display spans (headings + body sentences). pub display_segments: Vec<String>, /// Normalized lexical tokens. pub tokens: Vec<String>, /// Mean sentence length in cadence units. pub mean_sentence_len: f64, /// Standard deviation of sentence lengths. pub std_sentence_len: f64, /// Burstiness coefficient of variation. pub burstiness_cv: f64, /// Moving-Average Type-Token Ratio (`MATTR-50`). pub mattr_50: f64, /// Hapax legomena ratio. pub hapax_ratio: f64, /// ZipPy LZ77 compression ratio. pub lz77_ratio: f64, /// Dual-PPM, Mixture MLE, and Feature-Hashed NBSVM outputs. pub hash_scan: HashModelScan, /// DivEye 9D higher-order surprisal dynamics + Hurst exponent. pub diveye: DivEyeProfile, /// Word co-occurrence complex network topology. pub graph: CooccurGraphMetrics, /// Explicit RLHF syntactic constructions & explainability chips. pub proxy_lm: ProxyLmAnalysis, /// Per-display-segment raw ML log-odds margin before document blending. pub sentence_margins: Vec<f64>, /// Canonical 28-element feature vector fed into GBDT + Exact TreeSHAP. pub features: [f64; NUM_GBDT_FEATURES],}
fn compute_cjk_share_and_specificity(text: &str) -> (f64, f64) { let mut cjk = 0usize; let mut alpha = 0usize; let mut non_ws = 0usize; let mut spec_marks = 0usize; let mut prev_digit = false; let mut digit_groups = 0usize;
for ch in text.chars() { if !ch.is_whitespace() { non_ws = non_ws.saturating_add(1); } if is_cjk_or_kana(ch) { cjk = cjk.saturating_add(1); } else if ch.is_alphabetic() { alpha = alpha.saturating_add(1); } if ch.is_ascii_digit() { if !prev_digit { digit_groups = digit_groups.saturating_add(1); prev_digit = true; } } else { prev_digit = false; } if matches!( ch, '?' | '!' | '?' | '!' | '(' | ')' | '(' | ')' | '`' | '/' | ':' | ';' ) { spec_marks = spec_marks.saturating_add(1); } } let script_tot = cjk.saturating_add(alpha).max(1) as f64; let cjk_share = (cjk as f64) / script_tot; let spec_density = ((digit_groups * 2 + spec_marks) as f64) * 100.0 / (non_ws.max(1) as f64); (cjk_share, spec_density.min(25.0))}
fn compute_yules_k(tokens: &[String]) -> f64 { if tokens.len() <= 5 { return 80.0; } let mut freq: BTreeMap<&str, usize> = BTreeMap::new(); for t in tokens { let e = freq.entry(t.as_str()).or_insert(0); *e = e.saturating_add(1); } let n = tokens.len() as f64; let sum_sq: f64 = freq.values().map(|&c| (c as f64).powi(2)).sum(); (10_000.0 * (sum_sq - n) / (n * n)).clamp(0.0, 500.0)}
fn compute_adj_jump_and_extremes(prose_lengths: &[usize], mean_len: f64) -> (f64, f64) { if prose_lengths.is_empty() { return (0.35, 0.0); } let mut adj_sum = 0.0f64; let mut pairs = 0usize; for win in prose_lengths.windows(2) { if let (Some(&a), Some(&b)) = (win.first(), win.get(1)) { adj_sum += ((a as f64) - (b as f64)).abs() / mean_len.max(1.0); pairs = pairs.saturating_add(1); } } let adj_jump = if pairs == 0 { 0.35 } else { adj_sum / (pairs as f64) }; let ext = prose_lengths.iter().filter(|&&l| l <= 7 || l >= 42).count(); let ext_ratio = (ext as f64) / (prose_lengths.len() as f64); (adj_jump, ext_ratio)}
fn percentile_85(vals: &[f64]) -> f64 { if vals.is_empty() { return 0.0; } let mut sorted: Vec<f64> = vals.iter().copied().filter(|v| v.is_finite()).collect(); if sorted.is_empty() { return 0.0; } sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(core::cmp::Ordering::Equal)); let idx = ((sorted.len().saturating_sub(1)) * 85) / 100; sorted.get(idx).copied().unwrap_or(0.0)}
/// Extracts all 28 orthogonal ML features and per-sentence ML margins using `tables`.#[must_use]pub fn extract_ml_features_with_tables( text: &str, inspect_markdown: bool, tables: MlTablesView<'_>,) -> DocumentMlBundle { let script_family = detect_script_family(text); let (cjk_share, spec_density) = compute_cjk_share_and_specificity(text); let entropy = analyze_entropy_and_compression(text, script_family); let tokens = extract_lexical_tokens(text, script_family); let (mattr_50, hapax_ratio, _) = compute_lexical_diversity(&tokens, script_family); let yules_k = compute_yules_k(&tokens);
let (display_segments, prose_sentences) = segment_prose_and_display(text); let prose_lengths: Vec<usize> = prose_sentences .iter() .map(|s| count_cadence_units(s)) .collect(); let (mean_sentence_len, std_sentence_len, burstiness_cv, cadence_uniformity) = compute_burstiness_and_paragraphs(text, &prose_lengths); let (adj_jump, extreme_ratio) = compute_adj_jump_and_extremes(&prose_lengths, mean_sentence_len);
let proxy_lm = evaluate_proxy_lm( text, &prose_sentences, &display_segments, script_family, inspect_markdown, );
let hash_scan = evaluate_hash_models(text, script_family, tables); let diveye = compute_diveye_profile(&hash_scan.surprisal_stream); let graph = analyze_cooccurrence_graph(&tokens);
// Per-sentence corpus-trained ML margin (DualPpm + MixtureMle + HashedNbSvm + local RLHF) let mut sent_ppm_llrs = Vec::with_capacity(display_segments.len()); let mut sent_nbsvms = Vec::with_capacity(display_segments.len()); let mut sentence_margins = Vec::with_capacity(display_segments.len());
for (idx, seg) in display_segments.iter().enumerate() { let s_scan = evaluate_hash_models(seg, script_family, tables); let rule_p = proxy_lm.sentence_lm_scores.get(idx).copied().unwrap_or(0.5); let rule_logit = ((rule_p.clamp(0.03, 0.97)) / (1.0 - rule_p.clamp(0.03, 0.97))).ln();
sent_ppm_llrs.push(s_scan.ppm_mean_llr); sent_nbsvms.push(s_scan.nbsvm_margin);
let s_margin = 0.85 * s_scan.nbsvm_margin + 1.35 * s_scan.ppm_mean_llr + 1.40 * (s_scan.mle_alpha_hat - 0.50) + 0.38 * rule_logit; sentence_margins.push(s_margin); }
let ppm_sent_p85 = percentile_85(&sent_ppm_llrs); let nbsvm_sent_p85 = percentile_85(&sent_nbsvms);
let features: [f64; NUM_GBDT_FEATURES] = [ hash_scan.ppm_mean_llr, hash_scan.ppm_ord1_llr, hash_scan.ppm_ord3_llr, ppm_sent_p85, entropy.compression_ai_score.get(), diveye.mean, diveye.cv, diveye.skewness, diveye.excess_kurtosis, diveye.diff1_mean_abs, diveye.diff2_mean_abs, diveye.autocorr_lag1, diveye.hurst_exponent, burstiness_cv, adj_jump, extreme_ratio, cadence_uniformity.get(), hash_scan.mle_alpha_hat, hash_scan.mle_mean_llr, mattr_50, yules_k, graph.clustering_coeff, graph.degree_assortativity, hash_scan.nbsvm_margin, nbsvm_sent_p85, proxy_lm.rlhf_discourse_score.get(), spec_density, cjk_share, ];
DocumentMlBundle { script_family, cjk_share, display_segments, tokens, mean_sentence_len, std_sentence_len, burstiness_cv, mattr_50, hapax_ratio, lz77_ratio: entropy.lz77_ratio, hash_scan, diveye, graph, proxy_lm, sentence_margins, features, }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484//! Domain model, validated newtypes, algebraic errors, and forensic report structures.//!//! Invariant: Every `ProbabilityPct` lies in `[0.0, 100.0]`, and every `UnitScore` lies in `[0.0, 1.0]`.
use core::fmt;
/// Maximum UTF-8 article byte length accepted by a single forensic pass (2 MiB).pub const MAX_ARTICLE_BYTES: usize = 2_097_152;
/// Minimum non-whitespace character count required for statistical reliability.pub const MIN_MEANINGFUL_CHARS: usize = 12;
/// Algebraic domain error returned by pure validation and analysis routines.#[derive(Debug, Clone, PartialEq, Eq)]pub enum DetectError { /// Input byte slice was empty or contained only whitespace. EmptyDocument, /// Input had fewer than `MIN_MEANINGFUL_CHARS` non-whitespace characters. TooShort { /// Observed non-whitespace scalar count. observed_chars: usize, /// Minimum required scalar count. minimum_chars: usize, }, /// Input exceeded `MAX_ARTICLE_BYTES`. ExceedsMaxBytes { /// Observed byte length. observed_bytes: usize, /// Maximum permitted byte length. maximum_bytes: usize, }, /// Raw FFI bytes were not valid UTF-8. InvalidUtf8, /// Genre mode byte was outside `{0, 1, 2, 3}`. InvalidGenreCode(u8), /// Sensitivity mode byte was outside `{0, 1, 2}`. InvalidSensitivityCode(u8), /// Null or out-of-bounds pointer supplied across FFI. NullOrInvalidBuffer,}
impl fmt::Display for DetectError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::EmptyDocument => write!(f, "Article text is empty"), Self::TooShort { observed_chars, minimum_chars, } => write!( f, "Article text is too short ({observed_chars} chars; minimum {minimum_chars})" ), Self::ExceedsMaxBytes { observed_bytes, maximum_bytes, } => write!( f, "Article exceeds size limit ({observed_bytes} bytes; maximum {maximum_bytes})" ), Self::InvalidUtf8 => write!(f, "Input buffer is not valid UTF-8 text"), Self::InvalidGenreCode(code) => write!(f, "Unsupported genre preset code: {code}"), Self::InvalidSensitivityCode(code) => { write!(f, "Unsupported sensitivity preset code: {code}") } Self::NullOrInvalidBuffer => write!(f, "Invalid WebAssembly input buffer"), } }}
impl std::error::Error for DetectError {}
/// Validated non-empty UTF-8 article slice ready for pure forensic inspection.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct ValidatedArticle<'a> { raw: &'a str, non_ws_chars: usize,}
impl<'a> ValidatedArticle<'a> { /// Validates raw UTF-8 text against byte-size and minimum meaningful character invariants. /// /// Pre: `raw` is valid UTF-8. /// Post: `Ok(article)` implies `article.non_whitespace_chars() >= MIN_MEANINGFUL_CHARS` /// and `article.as_str().len() <= MAX_ARTICLE_BYTES`. pub fn try_new(raw: &'a str) -> Result<Self, DetectError> { let byte_len = raw.len(); if byte_len > MAX_ARTICLE_BYTES { return Err(DetectError::ExceedsMaxBytes { observed_bytes: byte_len, maximum_bytes: MAX_ARTICLE_BYTES, }); } let trimmed = raw.trim(); if trimmed.is_empty() { return Err(DetectError::EmptyDocument); } let non_ws_chars = trimmed.chars().filter(|c| !c.is_whitespace()).count(); if non_ws_chars < MIN_MEANINGFUL_CHARS { return Err(DetectError::TooShort { observed_chars: non_ws_chars, minimum_chars: MIN_MEANINGFUL_CHARS, }); } Ok(Self { raw: trimmed, non_ws_chars, }) }
/// Returns the trimmed UTF-8 slice. #[must_use] pub const fn as_str(self) -> &'a str { self.raw }
/// Returns the count of non-whitespace Unicode scalar values. #[must_use] pub const fn non_whitespace_chars(self) -> usize { self.non_ws_chars }}
/// Writing domain calibration preset.////// `Copy` Law: Stateless finite enum tag; duplication is identity-free.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum GenrePreset { /// General articles, blog posts, and essays (`0`). GeneralEssay, /// Academic papers, literature reviews, and formal reports (`1`). AcademicPaper, /// Journalism, news dispatches, and press releases (`2`). NewsJournalism, /// Marketing copy, SEO landing prose, and social threads (`3`). MarketingSeo,}
impl GenrePreset { /// Parses a numeric FFI code into a typed `GenrePreset`. pub const fn from_code(code: u8) -> Result<Self, DetectError> { match code { 0 => Ok(Self::GeneralEssay), 1 => Ok(Self::AcademicPaper), 2 => Ok(Self::NewsJournalism), 3 => Ok(Self::MarketingSeo), other => Err(DetectError::InvalidGenreCode(other)), } }
/// Canonical machine identifier emitted in reports. #[must_use] pub const fn slug(self) -> &'static str { match self { Self::GeneralEssay => "general", Self::AcademicPaper => "academic", Self::NewsJournalism => "journalism", Self::MarketingSeo => "marketing", } }
/// Domain prior adjustment applied to formal discourse regularity (`[-0.08, +0.06]`). /// Academic prose naturally uses stiffer transitions, so we lower false-positive bias. #[must_use] pub const fn prior_shift(self) -> f64 { match self { Self::GeneralEssay => 0.0, Self::AcademicPaper => -0.065, Self::NewsJournalism => -0.035, Self::MarketingSeo => 0.04, } }}
/// False-positive vs recall calibration mode.////// `Copy` Law: Stateless finite enum tag; duplication is identity-free.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum SensitivityMode { /// Strict low-false-positive threshold (Binoculars-style conservative screening). Conservative, /// Balanced default threshold. Balanced, /// High-recall screening for lightly edited / paraphrased AI drafts. StrictAudit,}
impl SensitivityMode { /// Parses a numeric FFI code into a typed `SensitivityMode`. pub const fn from_code(code: u8) -> Result<Self, DetectError> { match code { 0 => Ok(Self::Conservative), 1 => Ok(Self::Balanced), 2 => Ok(Self::StrictAudit), other => Err(DetectError::InvalidSensitivityCode(other)), } }
/// Returns additive logit/score bias for the sensitivity setting. #[must_use] pub const fn threshold_bias(self) -> f64 { match self { Self::Conservative => -0.06, Self::Balanced => 0.0, Self::StrictAudit => 0.065, } }}
/// Complete typed configuration for a single forensic detection run.////// `Copy` Law: Small immutable scalar configuration (`<= 4` bytes).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct DetectionConfig { /// Domain genre preset. pub genre: GenrePreset, /// Sensitivity calibration. pub sensitivity: SensitivityMode, /// Whether invisible Unicode watermarks should contribute to the composite AI score. pub inspect_watermarks: bool, /// Whether Markdown structural symmetry should contribute to discourse scoring. pub inspect_markdown_symmetry: bool,}
impl Default for DetectionConfig { fn default() -> Self { Self { genre: GenrePreset::GeneralEssay, sensitivity: SensitivityMode::Balanced, inspect_watermarks: true, inspect_markdown_symmetry: true, } }}
/// Dominant writing system detected in the input article.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum ScriptFamily { /// Predominantly alphabetic / whitespace-delimited script (English, European). Alphabetic, /// Predominantly CJK ideographic / kana script (Simplified/Traditional Chinese, Japanese). Cjk, /// Mixed bilingual prose. Hybrid,}
impl ScriptFamily { /// Canonical string identifier. #[must_use] pub const fn slug(self) -> &'static str { match self { Self::Alphabetic => "alphabetic", Self::Cjk => "cjk", Self::Hybrid => "hybrid", } }
/// Semantic predicate: returns `true` when CJK character n-gram tokenization is primary. #[must_use] pub const fn uses_ideographic_cadence(self) -> bool { matches!(self, Self::Cjk | Self::Hybrid) }}
/// Clamped unit interval score in `[0.0, 1.0]`.#[derive(Debug, Clone, Copy, PartialEq)]pub struct UnitScore(f64);
impl UnitScore { /// Clamps any finite `f64` into `[0.0, 1.0]`, mapping `NaN` to `0.0`. #[must_use] pub fn clamped(raw: f64) -> Self { if raw.is_nan() { Self(0.0) } else { Self(raw.clamp(0.0, 1.0)) } }
/// Returns inner `f64` guaranteed to satisfy `0.0 <= x <= 1.0`. #[must_use] pub const fn get(self) -> f64 { self.0 }
/// Converts unit score into rounded tenths of a percent `[0.0, 100.0]`. #[must_use] pub fn as_percent(self) -> f64 { ((self.0 * 1000.0).round()) / 10.0 }}
/// High-level attribution verdict band.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum VerdictBand { /// `< 28%`: Strong human authorship characteristics. HumanWritten, /// `28% .. 52%`: Human prose with light AI editing or formulaic structure. LightlyPolished, /// `50% .. 70%`: Hybrid human + AI collaborative or heavily paraphrased AI draft. HybridCollaborative, /// `>= 70%`: Strong LLM generation signature across multiple independent signals. AiGenerated,}
impl VerdictBand { /// Classifies a unit AI probability score into its canonical verdict band. #[must_use] pub fn from_score(score: UnitScore) -> Self { let p = score.get(); if p >= 0.70 { Self::AiGenerated } else if p >= 0.50 { Self::HybridCollaborative } else if p >= 0.30 { Self::LightlyPolished } else { Self::HumanWritten } }
/// Machine-readable verdict identifier for frontend i18n badges. #[must_use] pub const fn slug(self) -> &'static str { match self { Self::HumanWritten => "human_written", Self::LightlyPolished => "lightly_polished", Self::HybridCollaborative => "hybrid_mixed", Self::AiGenerated => "ai_generated", } }}
/// GLTR-inspired predictability band for individual sentences or lexical spans.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum GltrBand { /// Top-10 rank equivalent: highly formulaic / predictable LLM phrasing. GreenPredictable, /// Top-100 rank equivalent: moderately predictable prose. YellowModerate, /// Top-1000 rank equivalent: varied / nuanced phrasing. RedVaried, /// Tail-rank equivalent: idiosyncratic, surprising human phrasing. VioletIdiosyncratic,}
impl GltrBand { /// Classifies a sentence AI likelihood into one of the 4 GLTR visual bands. #[must_use] pub fn from_sentence_ai_score(score: UnitScore) -> Self { let v = score.get(); if v >= 0.68 { Self::GreenPredictable } else if v >= 0.48 { Self::YellowModerate } else if v >= 0.30 { Self::RedVaried } else { Self::VioletIdiosyncratic } }
/// Machine slug for CSS heatmap highlighting. #[must_use] pub const fn slug(self) -> &'static str { match self { Self::GreenPredictable => "green", Self::YellowModerate => "yellow", Self::RedVaried => "red", Self::VioletIdiosyncratic => "violet", } }}
/// Six orthogonal forensic dimension scores (each `UnitScore` where higher = stronger AI signal).#[derive(Debug, Clone, Copy)]pub struct DimensionScores { /// 1. ZipPy LZ77 compression redundancy & conditional n-gram predictability. pub compression_predictability: UnitScore, /// 2. Binoculars-style unigram-to-trigram cross-entropy curvature surrogate. pub cross_entropy_curvature: UnitScore, /// 3. Metronomic cadence / low burstiness (lack of sentence-length variance). pub cadence_uniformity: UnitScore, /// 4. GLTR lexical concentration & low MATTR-50 / Hapax diversity. pub lexical_concentration: UnitScore, /// 5. LLM discourse transition templates, hedging cliches & list symmetry. pub discourse_template_signal: UnitScore, /// 6. Invisible Unicode watermarks (`ZWSP`/`NNBSP`) & typographic artifacts. pub watermark_artifact_signal: UnitScore,}
/// Detected Unicode / typographic watermark anomaly entry.#[derive(Debug, Clone, PartialEq, Eq)]pub struct WatermarkFinding { /// Codepoint label (e.g. `"U+202F"` or `"EM_DASH_CLUSTER"`). pub code: &'static str, /// Human-readable technical name. pub label: &'static str, /// Exact occurrence count in the document. pub count: usize,}
/// Per-sentence forensic breakdown for the interactive GLTR heatmap.#[derive(Debug, Clone)]pub struct SentenceForensic { /// Zero-based sentence index. pub index: usize, /// Exact sentence text slice copied for JSON report rendering. pub text: String, /// Word/character cadence unit count. pub unit_len: usize, /// Estimated AI probability for this sentence (`[0.0, 1.0]`). pub ai_score: UnitScore, /// GLTR predictability band (`green`, `yellow`, `red`, `violet`). pub gltr_band: GltrBand, /// Primary forensic reason code (`"template_phrase"`, `"uniform_cadence"`, `"low_entropy"`, `"watermark_hit"`, `"high_burst_human"`). pub reason_code: &'static str, /// Number of matched LLM template phrases inside this sentence. pub phrase_hits: usize,}
/// Complete deterministic forensic report produced by `analyze_article`.#[derive(Debug, Clone)]pub struct ForensicReport { /// Overall AI generation probability (`[0.0, 1.0]`). pub overall_ai_score: UnitScore, /// Overall human authorship complement (`1.0 - overall_ai_score`). pub overall_human_score: UnitScore, /// Statistical confidence (`[0.0, 1.0]`), scaling with document length & signal agreement. pub confidence: UnitScore, /// Verdict classification band. pub verdict: VerdictBand, /// Detected script family. pub script_family: ScriptFamily, /// Applied genre preset. pub genre: GenrePreset, /// Total UTF-8 bytes analyzed. pub byte_len: usize, /// Total non-whitespace characters analyzed. pub char_count: usize, /// Effective lexical word / CJK-bigram token count. pub token_count: usize, /// Total segmented sentences. pub sentence_count: usize, /// Mean sentence length in cadence units. pub mean_sentence_len: f64, /// Sentence length standard deviation. pub std_sentence_len: f64, /// Burstiness coefficient of variation (`std / mean`). pub burstiness_cv: f64, /// Moving-Average Type-Token Ratio (`MATTR-50`, `[0.0, 1.0]`). pub mattr_50: f64, /// Hapax legomena ratio (`unique_once / total_types`, `[0.0, 1.0]`). pub hapax_ratio: f64, /// ZipPy LZ77 compressed-to-raw ratio (`[0.0, 1.0]`). pub lz77_ratio: f64, /// Character/byte conditional trigram Shannon entropy (bits per symbol). pub conditional_entropy_bits: f64, /// Binoculars-style cross-entropy ratio (`H_trigram / H_unigram`). pub cross_entropy_ratio: f64, /// Six orthogonal forensic dimension scores. pub dimensions: DimensionScores, /// Distribution of sentences across the 4 GLTR bands `[green, yellow, red, violet]`. pub gltr_counts: [usize; 4], /// Matched LLM discourse cliches (up to 12 distinct phrases). pub matched_phrases: Vec<String>, /// Invisible Unicode & typographic watermark findings. pub watermark_findings: Vec<WatermarkFinding>, /// Total invisible watermark characters removable via sanitization. pub removable_watermark_chars: usize, /// Liang et al. (ICML 2024) Distributional Mixture MLE fraction $\hat{\alpha} \in [0, 1]$. pub mle_alpha_fraction: UnitScore, /// Rescaled-Range ($R/S$) Fractal Hurst exponent $H \in [0, 1]$. pub hurst_exponent: f64, /// Word co-occurrence graph clustering coefficient $C \in [0, 1]$. pub graph_clustering: f64, /// Dual-PPM conditional cross-entropy log-likelihood ratio (`bits`). pub ppm_llr_bits: f64, /// Feature-hashed N-gram NBSVM linear margin. pub nbsvm_margin: f64, /// Exact TreeSHAP log-odds contributions across `[ppm, diveye, cadence, mle_graph, nbsvm]`. pub shap_families: [f64; 5], /// Sentence-by-sentence forensic attribution list. pub sentences: Vec<SentenceForensic>,}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573//! Stylometric burstiness (heading-aware prose segmentation), paragraph symmetry,//! calibrated MATTR-50 / Yule's K lexical concentration, and multi-signal ensemble fusion.
use std::collections::{BTreeMap, BTreeSet};
use crate::gbdt::predict_with_treeshap;use crate::hash_tables::MlTablesView;use crate::ml_features::{extract_ml_features_with_tables, EMBEDDED_ML_TABLES};use crate::model::{ DetectError, DetectionConfig, DimensionScores, ForensicReport, GltrBand, ScriptFamily, SentenceForensic, UnitScore, ValidatedArticle, VerdictBand,};use crate::trained_forest::with_trained_gbdt;use crate::watermark::{is_atypical_llm_space, is_zero_width_watermark, scan_watermarks};
/// Semantic predicate: returns `true` if `ch` belongs to CJK Unified Ideographs, Hiragana, or Katakana.#[must_use]pub const fn is_cjk_or_kana(ch: char) -> bool { matches!( ch, '\u{3040}'..='\u{30FF}' | '\u{3400}'..='\u{4DBF}' | '\u{4E00}'..='\u{9FFF}' | '\u{F900}'..='\u{FAFF}' )}
/// Detects the dominant script family of an article.#[must_use]pub fn detect_script_family(text: &str) -> ScriptFamily { let mut cjk = 0usize; let mut alpha = 0usize; for ch in text.chars() { if is_cjk_or_kana(ch) { cjk = cjk.saturating_add(1); } else if ch.is_alphabetic() { alpha = alpha.saturating_add(1); } } let total = cjk.saturating_add(alpha); if total == 0 { return ScriptFamily::Alphabetic; } let cjk_share = (cjk as f64) / (total as f64); if cjk_share >= 0.40 { ScriptFamily::Cjk } else if cjk_share >= 0.10 { ScriptFamily::Hybrid } else { ScriptFamily::Alphabetic }}
/// Tokenizes text into normalized lexical tokens: lowercase words for alphabetic scripts/// and overlapping character bigrams + words for CJK/Hybrid scripts.#[must_use]pub fn extract_lexical_tokens(text: &str, script: ScriptFamily) -> Vec<String> { let mut tokens = Vec::new(); let mut current_word = String::new(); let mut prev_cjk: Option<char> = None;
for ch in text.chars() { if is_cjk_or_kana(ch) { if !current_word.is_empty() { tokens.push(std::mem::take(&mut current_word)); } if let Some(prev) = prev_cjk { let mut bg = String::with_capacity(8); bg.push(prev); bg.push(ch); tokens.push(bg); } else if !script.uses_ideographic_cadence() { tokens.push(ch.to_string()); } prev_cjk = Some(ch); } else if ch.is_alphanumeric() || ch == '\'' { prev_cjk = None; for lc in ch.to_lowercase() { current_word.push(lc); } } else { prev_cjk = None; if !current_word.is_empty() { tokens.push(std::mem::take(&mut current_word)); } } } if !current_word.is_empty() { tokens.push(current_word); } tokens}
/// Computes Moving-Average Type-Token Ratio (`MATTR-50`), Hapax ratio, and Yule's K concentration.////// Calibrated on real 50-token windows:/// - Human English prose: `MATTR-50` ~ `0.86..0.93`, Yule's K ~ `60..115`/// - LLM English/CJK prose: `MATTR-50` ~ `0.76..0.87`, Yule's K ~ `110..210` (higher stem reuse)#[must_use]pub fn compute_lexical_diversity(tokens: &[String], script: ScriptFamily) -> (f64, f64, UnitScore) { if tokens.is_empty() { return (0.85, 0.70, UnitScore::clamped(0.5)); } let mut freq: BTreeMap<&str, usize> = BTreeMap::new(); for tok in tokens { let entry = freq.entry(tok.as_str()).or_insert(0); *entry = entry.saturating_add(1); } let vocab_size = freq.len().max(1); let hapax_count = freq.values().filter(|&&c| c == 1).count(); let hapax_ratio = (hapax_count as f64) / (vocab_size as f64);
const WINDOW: usize = 50; let mattr = if tokens.len() <= WINDOW { (vocab_size as f64) / (tokens.len() as f64) } else { let mut sum_ttr = 0.0f64; let mut windows = 0usize; for win in tokens.windows(WINDOW) { let uniq: BTreeSet<&str> = win.iter().map(String::as_str).collect(); sum_ttr += (uniq.len() as f64) / (WINDOW as f64); windows = windows.saturating_add(1); } sum_ttr / ((windows.max(1)) as f64) };
// Length-invariant Yule's K = 10^4 * (sum(c^2) - N) / N^2 let n = tokens.len() as f64; let sum_sq: f64 = freq.values().map(|&c| (c as f64).powi(2)).sum(); let yules_k = if n > 5.0 { (10_000.0 * (sum_sq - n) / (n * n)).clamp(0.0, 500.0) } else { 80.0 };
let human_mattr_center = if script.uses_ideographic_cadence() { 0.885 } else { 0.785 }; let yule_center = if script.uses_ideographic_cadence() { 85.0 } else { 135.0 }; let mattr_deficit = (human_mattr_center - mattr).clamp(-0.10, 0.18); let yule_excess = ((yules_k - yule_center) / 220.0).clamp(-0.18, 0.28); let lexical_ai_score = UnitScore::clamped(0.44 + mattr_deficit * 1.8 + yule_excess * 0.45);
(mattr, hapax_ratio, lexical_ai_score)}
/// Semantic predicate: returns `true` when a line is a standalone heading or short section title/// rather than a body prose sentence (preventing headings from artificially inflating sentence CV).#[must_use]pub fn is_structural_heading_line(line: &str) -> bool { let t = line.trim(); if t.is_empty() { return true; } if t.starts_with('#') { return true; } let char_cnt = t.chars().count(); let ends_with_sentence_punct = t.ends_with('.') || t.ends_with('!') || t.ends_with('?') || t.ends_with('。') || t.ends_with('.') || t.ends_with('!') || t.ends_with('?') || t.ends_with('"') || t.ends_with('”') || t.ends_with('」'); char_cnt <= 28 && !ends_with_sentence_punct}
/// Segments text into `(all_display_segments, body_prose_sentences)` so the heatmap renders/// every line/sentence while burstiness statistics operate strictly on genuine prose sentences!#[must_use]pub fn segment_prose_and_display(text: &str) -> (Vec<String>, Vec<String>) { let mut all_segments = Vec::new(); let mut prose_sentences = Vec::new();
for raw_line in text.lines() { let line = raw_line.trim(); if line.is_empty() { continue; } if is_structural_heading_line(line) { if line.chars().any(|c| !c.is_whitespace()) { all_segments.push(line.to_string()); } continue; }
let mut buf = String::new(); let mut chars = line.chars().peekable(); while let Some(ch) = chars.next() { buf.push(ch); let is_cjk_end = matches!(ch, '。' | '.' | '!' | '?'); let is_ascii_end = if ch == '.' { match chars.peek().copied() { None => true, Some(nc) => { nc.is_whitespace() || matches!(nc, '"' | '\'' | '”' | '’' | ')' | ']') } } } else if matches!(ch, '!' | '?') { !matches!(chars.peek().copied(), Some('!' | '?')) } else { false }; if is_cjk_end || is_ascii_end { let s = buf.trim(); let non_ws = s.chars().filter(|c| !c.is_whitespace()).count(); if non_ws >= 1 { all_segments.push(s.to_string()); if non_ws >= 5 { prose_sentences.push(s.to_string()); } buf.clear(); } } } let tail = buf.trim(); let tail_non_ws = tail.chars().filter(|c| !c.is_whitespace()).count(); if tail_non_ws >= 1 { all_segments.push(tail.to_string()); if tail_non_ws >= 5 { prose_sentences.push(tail.to_string()); } } }
if prose_sentences.is_empty() && !all_segments.is_empty() { prose_sentences.clone_from(&all_segments); } (all_segments, prose_sentences)}
/// Counts cadence length units in a sentence (word count + CJK ideograph weight).#[must_use]pub fn count_cadence_units(sentence: &str) -> usize { let mut words = 0usize; let mut cjk = 0usize; let mut in_word = false; for ch in sentence.chars() { if is_cjk_or_kana(ch) { in_word = false; cjk = cjk.saturating_add(1); } else if ch.is_alphanumeric() { if !in_word { words = words.saturating_add(1); in_word = true; } } else { in_word = false; } } words.saturating_add((cjk.saturating_add(1)) / 2).max(1)}
fn blend_cjk_clause_cv(full_text: &str, base_cv: f64) -> f64 { if !full_text.contains(',') && !full_text.contains('、') && !full_text.contains('.') { return base_cv; } let clause_lens: Vec<usize> = full_text .lines() .map(str::trim) .filter(|line| !line.is_empty() && !line.starts_with('#')) .flat_map(|line| line.split([',', '、', '。', '.', '!', '?', ';'])) .map(|s| s.chars().filter(|c| !c.is_whitespace()).count()) .filter(|&c| c >= 2) .collect(); if clause_lens.len() < 8 { return base_cv; } let c_mean = (clause_lens.iter().sum::<usize>() as f64) / (clause_lens.len() as f64); let c_var = clause_lens .iter() .map(|&c| ((c as f64) - c_mean).powi(2)) .sum::<f64>() / (clause_lens.len() as f64); let clause_cv = c_var.sqrt() / c_mean.max(1.0); if clause_cv > base_cv { base_cv * 0.35 + clause_cv * 0.65 } else { base_cv }}
fn paragraph_uniformity_bonus(full_text: &str) -> f64 { let para_lens: Vec<usize> = full_text .split('\n') .map(str::trim) .filter(|line| !line.is_empty() && !is_structural_heading_line(line)) .map(count_cadence_units) .filter(|&u| u >= 12) .collect(); if para_lens.len() < 3 { return 0.0; } let p_mean = (para_lens.iter().sum::<usize>() as f64) / (para_lens.len() as f64); let p_var = para_lens .iter() .map(|&l| ((l as f64) - p_mean).powi(2)) .sum::<f64>() / (para_lens.len() as f64); let p_cv = p_var.sqrt() / p_mean.max(1.0); (0.36 - p_cv).clamp(-0.10, 0.22) * 0.55}
/// Computes prose burstiness + paragraph length uniformity `(mean, std, cv, cadence_ai_score)`.#[must_use]pub fn compute_burstiness_and_paragraphs( full_text: &str, prose_lengths: &[usize],) -> (f64, f64, f64, UnitScore) { if prose_lengths.is_empty() { return (18.0, 0.0, 0.0, UnitScore::clamped(0.5)); } if let Some(&only) = prose_lengths.first() { if prose_lengths.len() == 1 { let mid = if (13..=30).contains(&only) { 0.58 } else { 0.44 }; return (only as f64, 0.0, 0.0, UnitScore::clamped(mid)); } } let has_consec_staccato = prose_lengths .windows(2) .any(|w| matches!((w.first(), w.get(1)), (Some(&a), Some(&b)) if a <= 4 && b <= 4)); let filtered_lens: Vec<usize> = if prose_lengths.len() >= 6 && has_consec_staccato { prose_lengths.iter().copied().filter(|&l| l > 4).collect() } else { prose_lengths.to_vec() }; let active_lens = if filtered_lens.len() >= 3 { filtered_lens.as_slice() } else { prose_lengths };
let n = active_lens.len() as f64; let mean = (active_lens.iter().copied().sum::<usize>() as f64) / n; let var = active_lens .iter() .map(|&l| ((l as f64) - mean).powi(2)) .sum::<f64>() / n; let std_dev = var.sqrt(); let mut cv = std_dev / mean.max(1.0); if active_lens.len() <= 8 { cv = blend_cjk_clause_cv(full_text, cv); }
let mut adj_sum = 0.0f64; let mut pairs = 0usize; for pair in active_lens.windows(2) { if let (Some(&a), Some(&b)) = (pair.first(), pair.get(1)) { adj_sum += ((a as f64) - (b as f64)).abs() / mean.max(1.0); pairs = pairs.saturating_add(1); } } let adj_jump = adj_sum / ((pairs.max(1)) as f64); let extreme_cnt = active_lens.iter().filter(|&&l| l <= 7 || l >= 42).count(); let extreme_ratio = (extreme_cnt as f64) / n; let para_bonus = paragraph_uniformity_bonus(full_text);
let cv_signal = (0.50 - cv).clamp(-0.32, 0.40) * 1.15; let jump_signal = (0.48 - adj_jump).clamp(-0.28, 0.36) * 0.60; let no_extremes_signal = (0.14 - extreme_ratio).clamp(-0.22, 0.14) * 0.90;
let cadence_ai_score = UnitScore::clamped(0.50 + cv_signal + jump_signal + no_extremes_signal + para_bonus);
(mean, std_dev, cv, cadence_ai_score)}
/// Scores each display segment for the interactive GLTR 4-band heatmap.#[must_use]pub fn score_display_sentences( display_segments: &[String], lm_scores: &[f64], hit_counts: &[usize], mean_len: f64, doc_ai_prob: f64,) -> (Vec<SentenceForensic>, [usize; 4]) { let mut out = Vec::with_capacity(display_segments.len()); let mut gltr_counts = [0usize; 4];
for (idx, seg) in display_segments.iter().enumerate() { let unit_len = count_cadence_units(seg); let seg_lm = lm_scores.get(idx).copied().unwrap_or(0.5); let phrase_hits = hit_counts.get(idx).copied().unwrap_or(0); let has_wm = seg .chars() .any(|c| is_zero_width_watermark(c) || is_atypical_llm_space(c)); let is_heading = is_structural_heading_line(seg); let rel_dev = ((unit_len as f64) - mean_len).abs() / mean_len.max(1.0); let is_metronomic = !is_heading && (11..=30).contains(&unit_len) && rel_dev < 0.28; let is_spiky_human = !is_heading && (unit_len <= 6 || unit_len >= 44 || rel_dev >= 0.62);
let mut s_prob = doc_ai_prob * 0.30 + seg_lm * 0.70; if has_wm { s_prob += 0.22; } if is_metronomic { s_prob += 0.06; } if is_spiky_human && phrase_hits == 0 { s_prob -= 0.18; }
let ai_score = UnitScore::clamped(s_prob); let gltr_band = GltrBand::from_sentence_ai_score(ai_score); let slot = match gltr_band { GltrBand::GreenPredictable => 0usize, GltrBand::YellowModerate => 1usize, GltrBand::RedVaried => 2usize, GltrBand::VioletIdiosyncratic => 3usize, }; if let Some(c) = gltr_counts.get_mut(slot) { *c = c.saturating_add(1); }
let reason_code = if has_wm { "watermark_hit" } else if phrase_hits > 0 { "template_phrase" } else if is_spiky_human { "high_burst_human" } else if is_metronomic { "uniform_cadence" } else { "entropy_profile" };
out.push(SentenceForensic { index: idx, text: seg.clone(), unit_len, ai_score, gltr_band, reason_code, phrase_hits, }); }
(out, gltr_counts)}
fn shap_slice_sum(shap: &[f64], start: usize, end_inclusive: usize) -> f64 { shap.get(start..=end_inclusive) .map(|s| s.iter().copied().sum()) .unwrap_or(0.0)}
fn shap_to_unit_score(shap_log_odds: f64) -> UnitScore { UnitScore::clamped(1.0 / (1.0 + (-1.85 * shap_log_odds).exp()))}
/// Pure corpus-trained ML forensic analyzer combining:/// 1. Dual-Distribution PPM Conditional Cross-Entropy (`hash_tables`)/// 2. Liang et al. (ICML 2024) Mixture MLE Solver (`hash_tables`)/// 3. DivEye 9D Surprisal Dynamics & Fractal Hurst Exponent (`diveye`)/// 4. Word Co-occurrence Complex Network Topology (`cooccur_graph`)/// 5. Feature-Hashed Multilingual N-gram NBSVM (`hash_tables`)/// 6. Calibrated LightGBM Decision Forest + Exact Path-Dependent TreeSHAP (`gbdt`)pub fn analyze_article( article: ValidatedArticle<'_>, config: DetectionConfig,) -> Result<ForensicReport, DetectError> { let text = article.as_str(); let char_count = article.non_whitespace_chars(); let tables = MlTablesView::from_bytes(EMBEDDED_ML_TABLES)?; let bundle = extract_ml_features_with_tables(text, config.inspect_markdown_symmetry, tables);
let wm_scan = scan_watermarks(text, char_count); let watermark_artifact_signal = if config.inspect_watermarks { wm_scan.signal_score } else { UnitScore::clamped(0.0) };
let wm_logit_bonus = watermark_artifact_signal.get() * 2.80; let logit_shift = config.genre.prior_shift() * 4.2 + config.sensitivity.threshold_bias() * 3.5 + wm_logit_bonus;
let pred = with_trained_gbdt(|gbdt| predict_with_treeshap(gbdt, &bundle.features, logit_shift))?;
let shap_ppm = shap_slice_sum(&pred.shap_values, 0, 4); let shap_diveye = shap_slice_sum(&pred.shap_values, 5, 12); let shap_cadence = shap_slice_sum(&pred.shap_values, 13, 16); let shap_mle_graph = shap_slice_sum(&pred.shap_values, 17, 22); let shap_nbsvm = shap_slice_sum(&pred.shap_values, 23, 27); let shap_families = [ shap_ppm, shap_diveye, shap_cadence, shap_mle_graph, shap_nbsvm, ];
let dimensions = DimensionScores { compression_predictability: shap_to_unit_score(shap_ppm), cross_entropy_curvature: shap_to_unit_score(shap_diveye), cadence_uniformity: shap_to_unit_score(shap_cadence), lexical_concentration: shap_to_unit_score(shap_mle_graph), discourse_template_signal: shap_to_unit_score(shap_nbsvm), watermark_artifact_signal, };
let overall_ai_score = UnitScore::clamped(pred.calibrated_prob); let overall_human_score = UnitScore::clamped(1.0 - overall_ai_score.get()); let verdict = VerdictBand::from_score(overall_ai_score);
let length_maturity = ((char_count as f64) / 360.0).clamp(0.30, 1.0); let polarization = ((overall_ai_score.get() - 0.5).abs() * 2.0).clamp(0.0, 1.0); let confidence = UnitScore::clamped(0.46 + length_maturity * 0.32 + polarization * 0.22);
let sent_probs: Vec<f64> = bundle .sentence_margins .iter() .map(|&m| 1.0 / (1.0 + (-1.15 * m).exp())) .collect();
let (sentences, gltr_counts) = score_display_sentences( &bundle.display_segments, &sent_probs, &bundle.proxy_lm.sentence_hit_counts, bundle.mean_sentence_len, overall_ai_score.get(), );
Ok(ForensicReport { overall_ai_score, overall_human_score, confidence, verdict, script_family: bundle.script_family, genre: config.genre, byte_len: text.len(), char_count, token_count: bundle.tokens.len(), sentence_count: sentences.len(), mean_sentence_len: bundle.mean_sentence_len, std_sentence_len: bundle.std_sentence_len, burstiness_cv: bundle.burstiness_cv, mattr_50: bundle.mattr_50, hapax_ratio: bundle.hapax_ratio, lz77_ratio: bundle.lz77_ratio, conditional_entropy_bits: bundle.diveye.mean, cross_entropy_ratio: bundle.diveye.cv, dimensions, gltr_counts, matched_phrases: bundle.proxy_lm.matched_signals, watermark_findings: wm_scan.findings, removable_watermark_chars: wm_scan.removable_invisible_count, mle_alpha_fraction: UnitScore::clamped(bundle.hash_scan.mle_alpha_hat), hurst_exponent: bundle.diveye.hurst_exponent, graph_clustering: bundle.graph.clustering_coeff, ppm_llr_bits: bundle.hash_scan.ppm_mean_llr, nbsvm_margin: bundle.hash_scan.nbsvm_margin, shap_families, sentences, })}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156//! Validated Binary Loader & Thread-Local Cache for the Corpus-Trained LightGBM Ensemble (`trained_forest`).//!//! Binary format `AIDGB02\0` (`src/weights/gbdt_forest.bin`)://! - `[0..8]`: Magic `"AIDGB02\0"`//! - `[8..16]`: `base_margin: f64` (LE)//! - `[16..24]`: `platt_slope: f64` (LE)//! - `[24..32]`: `platt_intercept: f64` (LE)//! - `[32..36]`: `num_trees: u32` (LE)//! - `[36..40]`: `num_knots: u32` (LE)//! - Knots: `num_knots * 16` bytes of `(margin: f64, prob: f64)` (LE)//! - Trees: `num_trees` blocks of `num_nodes: u16` followed by `num_nodes * 30` bytes//! `(feature: i16, left: u16, right: u16, threshold: f64, leaf_value: f64, cover: f64)`.
use std::cell::OnceCell;
use crate::gbdt::{TrainedGbdtModel, TreeNode};use crate::model::DetectError;
/// Raw embedded LightGBM + Isotonic Calibration binary (`src/weights/gbdt_forest.bin`).pub static EMBEDDED_GBDT_BYTES: &[u8] = include_bytes!("weights/gbdt_forest.bin");
/// Decoded owned forest cached once per Wasm/native thread.pub struct DecodedForest { base_margin: f64, platt_tail: (f64, f64), knots: Vec<(f64, f64)>, trees: Vec<Vec<TreeNode>>,}
thread_local! { static CACHED_FOREST: OnceCell<DecodedForest> = const { OnceCell::new() };}
fn read_u16_le(buf: &[u8], off: &mut usize) -> Option<u16> { let s = buf.get(*off..*off + 2)?; *off += 2; Some(u16::from_le_bytes([*s.first()?, *s.get(1)?]))}
fn read_i16_le(buf: &[u8], off: &mut usize) -> Option<i16> { let s = buf.get(*off..*off + 2)?; *off += 2; Some(i16::from_le_bytes([*s.first()?, *s.get(1)?]))}
fn read_u32_le(buf: &[u8], off: &mut usize) -> Option<u32> { let s = buf.get(*off..*off + 4)?; *off += 4; Some(u32::from_le_bytes([ *s.first()?, *s.get(1)?, *s.get(2)?, *s.get(3)?, ]))}
fn read_f64_le(buf: &[u8], off: &mut usize) -> Option<f64> { let s = buf.get(*off..*off + 8)?; *off += 8; Some(f64::from_le_bytes([ *s.first()?, *s.get(1)?, *s.get(2)?, *s.get(3)?, *s.get(4)?, *s.get(5)?, *s.get(6)?, *s.get(7)?, ]))}
/// Parses and validates an `AIDGB02\0` binary forest buffer without panicking.pub fn decode_gbdt_bytes(raw: &[u8]) -> Result<DecodedForest, DetectError> { if raw.get(0..8) != Some(b"AIDGB02\0".as_slice()) { return Err(DetectError::NullOrInvalidBuffer); } let mut off = 8usize; let base_margin = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let platt_slope = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let platt_intercept = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let num_trees = usize::try_from(read_u32_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?) .unwrap_or(0); let num_knots = usize::try_from(read_u32_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?) .unwrap_or(0);
if num_trees == 0 || num_trees > 1024 || num_knots > 512 { return Err(DetectError::NullOrInvalidBuffer); }
let mut knots = Vec::with_capacity(num_knots); for _ in 0..num_knots { let kx = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let ky = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; knots.push((kx, ky)); }
let mut trees = Vec::with_capacity(num_trees); for _ in 0..num_trees { let n_nodes = usize::from(read_u16_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?); if n_nodes == 0 || n_nodes > 512 { return Err(DetectError::NullOrInvalidBuffer); } let mut nodes = Vec::with_capacity(n_nodes); for _ in 0..n_nodes { let feature = read_i16_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let left = read_u16_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let right = read_u16_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let threshold = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let leaf_value = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; let cover = read_f64_le(raw, &mut off).ok_or(DetectError::NullOrInvalidBuffer)?; nodes.push(TreeNode { feature, left, right, threshold, leaf_value, cover, }); } trees.push(nodes); }
Ok(DecodedForest { base_margin, platt_tail: (platt_slope, platt_intercept), knots, trees, })}
/// Evaluates `f` with a zero-copy `TrainedGbdtModel` view backed by the thread-local decoded forest.pub fn with_trained_gbdt<R, F>(f: F) -> Result<R, DetectError>where F: FnOnce(TrainedGbdtModel<'_>) -> R,{ CACHED_FOREST.with(|cell| { if cell.get().is_none() { let decoded = decode_gbdt_bytes(EMBEDDED_GBDT_BYTES)?; let _ = cell.set(decoded); } let Some(forest) = cell.get() else { return Err(DetectError::NullOrInvalidBuffer); }; let tree_slices: Vec<&[TreeNode]> = forest.trees.iter().map(Vec::as_slice).collect(); let view = TrainedGbdtModel { base_margin: forest.base_margin, trees: &tree_slices, isotonic_knots: &forest.knots, platt_tail: forest.platt_tail, }; Ok(f(view)) })}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173//! Invisible Unicode watermark & typographic artifact forensics and pure sanitizer.//!//! Law (Idempotence): `forall s, sanitize_text(&sanitize_text(s).cleaned) == sanitize_text(s).cleaned`.
use crate::model::{UnitScore, WatermarkFinding};
/// Aggregated Unicode & typographic forensic metrics for an article.#[derive(Debug, Clone)]pub struct WatermarkScan { /// Normalized AI artifact signal (`[0.0, 1.0]`). pub signal_score: UnitScore, /// Count of invisible zero-width or narrow non-breaking spaces removable by sanitizer. pub removable_invisible_count: usize, /// Density of em-dashes per 1000 non-whitespace characters. pub em_dash_per_kchar: f64, /// Specific named findings with non-zero counts. pub findings: Vec<WatermarkFinding>,}
/// Output of the pure text sanitizer.#[derive(Debug, Clone, PartialEq, Eq)]pub struct SanitizedOutput { /// Cleaned UTF-8 string with invisible watermarks stripped and special spaces normalized. pub cleaned: String, /// Number of invisible zero-width scalar values removed. pub removed_zero_width: usize, /// Number of narrow/non-breaking spaces normalized to ASCII `0x20`. pub normalized_spaces: usize,}
/// Semantic predicate: returns `true` if `ch` is an invisible zero-width formatting character/// frequently injected by LLM web UIs, watermarking schemes, or copy-paste pipelines.#[must_use]pub const fn is_zero_width_watermark(ch: char) -> bool { matches!( ch, '\u{200B}' // Zero Width Space (ZWSP) | '\u{200C}' // Zero Width Non-Joiner (ZWNJ) | '\u{200D}' // Zero Width Joiner (ZWJ) | '\u{2060}' // Word Joiner (WJ) | '\u{2061}' // Function Application | '\u{2062}' // Invisible Times | '\u{2063}' // Invisible Separator | '\u{2064}' // Invisible Plus | '\u{FEFF}' // Zero Width No-Break Space / BOM | '\u{00AD}' // Soft Hyphen )}
/// Semantic predicate: returns `true` if `ch` is an unusual non-ASCII space (`U+202F` NNBSP,/// `U+00A0` NBSP, `U+2007` Figure Space, `U+2009` Thin Space) often emitted by frontier LLMs.#[must_use]pub const fn is_atypical_llm_space(ch: char) -> bool { matches!( ch, '\u{202F}' | '\u{00A0}' | '\u{2007}' | '\u{2009}' | '\u{200A}' )}
/// Scans UTF-8 prose for invisible Unicode watermarks and LLM typographic habits.#[must_use]pub fn scan_watermarks(text: &str, non_ws_chars: usize) -> WatermarkScan { let mut zwsp = 0usize; let mut zwnj_zwj = 0usize; let mut word_joiner_bom = 0usize; let mut nnbsp = 0usize; let mut nbsp = 0usize; let mut em_dashes = 0usize;
for ch in text.chars() { match ch { '\u{200B}' | '\u{00AD}' => zwsp = zwsp.saturating_add(1), '\u{200C}' | '\u{200D}' => zwnj_zwj = zwnj_zwj.saturating_add(1), '\u{2060}' | '\u{2061}' | '\u{2062}' | '\u{2063}' | '\u{2064}' | '\u{FEFF}' => { word_joiner_bom = word_joiner_bom.saturating_add(1); } '\u{202F}' => nnbsp = nnbsp.saturating_add(1), '\u{00A0}' | '\u{2007}' | '\u{2009}' | '\u{200A}' => nbsp = nbsp.saturating_add(1), '—' => em_dashes = em_dashes.saturating_add(1), _ => {} } }
let mut findings = Vec::new(); if zwsp > 0 { findings.push(WatermarkFinding { code: "U+200B", label: "Zero-Width Space / Soft Hyphen Watermark", count: zwsp, }); } if nnbsp > 0 { findings.push(WatermarkFinding { code: "U+202F", label: "Narrow No-Break Space (LLM Tokenizer Signature)", count: nnbsp, }); } if word_joiner_bom > 0 { findings.push(WatermarkFinding { code: "U+2060", label: "Invisible Word Joiner / Inline BOM", count: word_joiner_bom, }); } if zwnj_zwj > 0 { findings.push(WatermarkFinding { code: "U+200C/D", label: "Zero-Width Joiner / Non-Joiner Sequence", count: zwnj_zwj, }); } if nbsp > 0 { findings.push(WatermarkFinding { code: "U+00A0", label: "Non-Breaking / Thin Typographic Space", count: nbsp, }); }
let denom = (non_ws_chars.max(1)) as f64; let em_dash_per_kchar = (em_dashes as f64) * 1000.0 / denom; if em_dashes >= 3 && em_dash_per_kchar >= 4.5 { findings.push(WatermarkFinding { code: "U+2014", label: "Elevated Em-Dash Parenthetical Density", count: em_dashes, }); }
let invisible_total = zwsp .saturating_add(zwnj_zwj) .saturating_add(word_joiner_bom) .saturating_add(nnbsp); let removable_invisible_count = invisible_total.saturating_add(nbsp);
let zw_component = ((invisible_total as f64) * 0.30).min(0.85); let nbsp_component = ((nbsp as f64) * 0.06).min(0.22);
WatermarkScan { signal_score: UnitScore::clamped(zw_component + nbsp_component), removable_invisible_count, em_dash_per_kchar, findings, }}
/// Strips invisible zero-width watermarks and normalizes atypical non-breaking spaces to `' '`.////// Post: `!result.cleaned.chars().any(|c| is_zero_width_watermark(c) || is_atypical_llm_space(c))`.#[must_use]pub fn sanitize_text(raw: &str) -> SanitizedOutput { let mut cleaned = String::with_capacity(raw.len()); let mut removed_zero_width = 0usize; let mut normalized_spaces = 0usize;
for ch in raw.chars() { if is_zero_width_watermark(ch) { removed_zero_width = removed_zero_width.saturating_add(1); } else if is_atypical_llm_space(ch) { normalized_spaces = normalized_spaces.saturating_add(1); cleaned.push(' '); } else { cleaned.push(ch); } }
SanitizedOutput { cleaned, removed_zero_width, normalized_spaces, }}123version https://git-lfs.github.com/spec/v1oid sha256:7703b9aa5649b21bcdcf5f118c7e74ace8831f138dc2e9e555c611168c8a9453size 157512123version https://git-lfs.github.com/spec/v1oid sha256:05528937a6266d301c17d006adfbe8e9a8ac46035f9174f545b693d0dc7bbaf5size 327696123version https://git-lfs.github.com/spec/v1oid sha256:7703b9aa5649b21bcdcf5f118c7e74ace8831f138dc2e9e555c611168c8a9453size 157512123version https://git-lfs.github.com/spec/v1oid sha256:05528937a6266d301c17d006adfbe8e9a8ac46035f9174f545b693d0dc7bbaf5size 327696.gitattributes+3-33
LICENSEAdded+21
README.mdAdded+86
prose_guard_wasm.wasmAdded+3
rust_src/Cargo.tomlAdded+19
rust_src/src/cooccur_graph.rsAdded+172
rust_src/src/diveye.rsAdded+227
rust_src/src/gbdt.rsAdded+360
rust_src/src/hash_tables.rsAdded+565
rust_src/src/json_emit.rsAdded+146
rust_src/src/lib.rsAdded+423
rust_src/src/lm_proxy.rsAdded+858
rust_src/src/lz_entropy.rsAdded+197
rust_src/src/ml_features.rsAdded+255
rust_src/src/model.rsAdded+484
rust_src/src/stylometry.rsAdded+573
rust_src/src/trained_forest.rsAdded+156
rust_src/src/watermark.rsAdded+173
rust_src/src/weights/gbdt_forest.binAdded+3
rust_src/src/weights/ml_tables.binAdded+3
wasm-loader.jsAdded
weights/gbdt_forest.binAdded+3
weights/ml_tables.binAdded+3