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.
proseguard / ml /rust_src /src /model.rs
ElderRyan's picture
Release unified ProseGuard model suite (ml + mmbert-small + mmbert-base)
1ddf025 verified
Raw History Blame Contribute Delete
17.3 kB
//! 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>,
}