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.
File size: 20,247 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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! 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,
    })
}