Text Classification
Transformers
ONNX
Safetensors
ai-detection
machine-generated-text
knowledge-distillation
modernbert
mmbert
webgpu
webassembly
lightgbm
treeshap
Run this model with HF Jobs
Run ElderRyan/proseguard on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/ElderRyan/proseguard. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/ElderRyan/proseguard on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use ElderRyan/proseguard with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use ElderRyan/proseguard with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="ElderRyan/proseguard")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("ElderRyan/proseguard", device_map="auto") - Notebooks
- Google Colab
- Kaggle
File size: 17,289 Bytes
1ddf025 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 | //! 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>,
}
|