File size: 9,187 Bytes
99fb72f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
//! 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,
    }
}