ProseGuard-ML / rust_src /src /stylometry.rs
ElderRyan's picture
Release ProseGuard-ML
99fb72f verified
Raw History Blame Contribute Delete
20.2 kB
//! 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,
})
}