diff --git a/src/features.rs b/src/features.rs index 1fee4be..85ddb1d 100644 --- a/src/features.rs +++ b/src/features.rs @@ -94,7 +94,8 @@ pub fn extract_features(text: &str) -> FeatureVector { list_item_ratio: compute_list_item_ratio(&non_empty, n_non_empty), parenthesis_density: compute_parenthesis_density(sample, total_chars), section_header_ratio: compute_section_header_ratio(&non_empty, n_non_empty), - json_lines_ratio: compute_json_lines_ratio(&non_empty, n_non_empty), + json_lines_ratio: compute_json_lines_ratio(truncated), + shebang_present: compute_shebang_present(sample), line_count: n_lines, } } @@ -972,64 +973,131 @@ fn compute_operator_density(text: &str, total_chars: f32) -> f32 { /// Inline markup patterns per 1000 characters. /// Detects **bold**, `code`, *italic*, [link](url). fn compute_inline_markup_count(text: &str, total_chars: f32) -> f32 { + // Mirrors Python regex: **bold** | `code` | *italic* | [link](url) + // Uses a single-pass scan to match Python's re.findall (non-overlapping). + let bytes = text.as_bytes(); + let len = bytes.len(); let mut count = 0usize; + let mut i = 0; - // Count **bold** patterns - let mut rest = text; - while let Some(start) = rest.find("**") { - let after = &rest[start + 2..]; - if let Some(end) = after.find("**") { - if end > 0 { + while i < len { + if bytes[i] == b'*' && i + 1 < len && bytes[i + 1] == b'*' { + // Try **bold**: \*\*[^*]+\*\* + if let Some(end) = find_bold_end(bytes, i + 2) { count += 1; + i = end; + continue; } - rest = &after[end + 2..]; - } else { - break; } - } - - // Count `code` patterns - rest = text; - while let Some(start) = rest.find('`') { - let after = &rest[start + 1..]; - if let Some(stripped) = after.strip_prefix('`') { - // Skip `` (double backtick) - rest = stripped; - continue; + if bytes[i] == b'`' { + // Try `code`: `[^`]+` + if let Some(end) = find_backtick_end(bytes, i + 1) { + count += 1; + i = end; + continue; + } } - if let Some(end) = after.find('`') { - if end > 0 { + if bytes[i] == b'*' { + // Try *italic*: \*[^*\s][^*]*\* + if let Some(end) = find_italic_end(bytes, i + 1) { count += 1; + i = end; + continue; } - rest = &after[end + 1..]; - } else { - break; } - } - - // Count [link](url) patterns - rest = text; - while let Some(start) = rest.find("](") { - // Check for [ before ] - let before = &rest[..start]; - if before.rfind('[').is_some() { - let after = &rest[start + 2..]; - if let Some(end) = after.find(')') { - if end > 0 { - count += 1; - } - rest = &after[end + 1..]; - } else { - break; + if bytes[i] == b'[' { + // Try [link](url): \[[^\]]+\]\([^)]+\) + if let Some(end) = find_link_end(bytes, i + 1) { + count += 1; + i = end; + continue; } - } else { - rest = &rest[start + 2..]; } + i += 1; } count as f32 / total_chars * 1000.0 } +/// Match `[^*]+\*\*` starting at `start` (after the opening `**`). +fn find_bold_end(bytes: &[u8], start: usize) -> Option { + let mut i = start; + let len = bytes.len(); + // Must have at least one non-* char + if i >= len || bytes[i] == b'*' { + return None; + } + while i < len { + if bytes[i] == b'*' && i + 1 < len && bytes[i + 1] == b'*' { + return Some(i + 2); + } + i += 1; + } + None +} + +/// Match `[^`]+`` starting at `start` (after the opening backtick). +fn find_backtick_end(bytes: &[u8], start: usize) -> Option { + let mut i = start; + let len = bytes.len(); + if i >= len || bytes[i] == b'`' { + return None; + } + while i < len { + if bytes[i] == b'`' { + return Some(i + 1); + } + i += 1; + } + None +} + +/// Match `[^*\s][^*]*\*` starting at `start` (after the opening `*`). +fn find_italic_end(bytes: &[u8], start: usize) -> Option { + let mut i = start; + let len = bytes.len(); + // First char must be non-* and non-whitespace + if i >= len || bytes[i] == b'*' || bytes[i].is_ascii_whitespace() { + return None; + } + i += 1; + while i < len { + if bytes[i] == b'*' { + return Some(i + 1); + } + i += 1; + } + None +} + +/// Match `[^\]]+\]\([^)]+\)` starting at `start` (after the opening `[`). +fn find_link_end(bytes: &[u8], start: usize) -> Option { + let mut i = start; + let len = bytes.len(); + // Must have at least one non-] char + if i >= len || bytes[i] == b']' { + return None; + } + // Find ] + while i < len && bytes[i] != b']' { + i += 1; + } + // Must be followed by ]( + if i + 1 >= len || bytes[i + 1] != b'(' { + return None; + } + i += 2; // skip ]( + let paren_start = i; + // Find ) with at least one char inside + while i < len && bytes[i] != b')' { + i += 1; + } + if i >= len || i == paren_start { + return None; + } + Some(i + 1) +} + /// Whether indentation follows a regular pattern (0.0-1.0). /// Code has consistent indentation (multiples of 2, 3, or 4). fn compute_indentation_consistency(lines: &[&str]) -> f32 { @@ -1250,8 +1318,14 @@ fn is_section_header(trimmed: &str) -> bool { } /// Fraction of non-empty lines that look like JSON lines (start with `{`, end with `}`). -fn compute_json_lines_ratio(non_empty: &[&str], n_non_empty: usize) -> f32 { - if n_non_empty == 0 { +/// +/// Must be computed on **raw** text (before `\n` normalization) because +/// normalization splits embedded newlines inside JSON strings, destroying +/// the `{…}` single-line pattern that defines JSONL. +fn compute_json_lines_ratio(raw: &str) -> f32 { + let non_empty: Vec<&str> = raw.lines().filter(|l| !l.trim().is_empty()).collect(); + let n = non_empty.len(); + if n == 0 { return 0.0; } @@ -1262,5 +1336,14 @@ fn compute_json_lines_ratio(non_empty: &[&str], n_non_empty: usize) -> f32 { trimmed.starts_with('{') && trimmed.ends_with('}') }) .count(); - count as f32 / n_non_empty as f32 + count as f32 / n as f32 +} + +/// 1.0 if the text starts with a shebang (`#!`), 0.0 otherwise. +fn compute_shebang_present(sample: &str) -> f32 { + if sample.trim_start().starts_with("#!") { + 1.0 + } else { + 0.0 + } } diff --git a/src/lib.rs b/src/lib.rs index b1c2472..78108fd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,16 +16,28 @@ use std::collections::BTreeMap; /// Classify a text string using Tier 1 structural features only. /// /// Convenience function for simple usage without a model. -/// For short texts (< 5 words), returns Skip immediately. +/// For short texts (< 5 words), returns low-confidence Prose. pub fn classify(text: &str) -> Classification { - if text.trim().is_empty() || tier1::is_too_short(text) { + if text.trim().is_empty() { return Classification { - category: TextCategory::Skip, + category: TextCategory::Prose, sub_type: None, - confidence: 1.0, - reason: "too short".to_string(), + confidence: 0.0, + reason: "empty or no content".to_string(), tier: Tier::Structural, detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), + }; + } + if tier1::is_too_short(text) { + return Classification { + category: TextCategory::Prose, + sub_type: None, + confidence: 0.5, + reason: "too short for reliable classification".to_string(), + tier: Tier::Structural, + detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), }; } @@ -36,6 +48,7 @@ pub fn classify(text: &str) -> Classification { /// Main classifier combining Tier 1 (structural) and Tier 2 (model). pub struct Classifier { model: ModelClassifier, + min_score: Option, } impl Classifier { @@ -43,6 +56,19 @@ impl Classifier { pub fn new() -> Self { Self { model: ModelClassifier::without_model(), + min_score: None, + } + } + + /// Create a classifier with the embedded ONNX model for Tier 2. + /// + /// When compiled with `--features onnx-model`, loads the model + /// baked into the binary at compile time. Without the feature, + /// this is equivalent to `new()`. + pub fn with_embedded_model() -> Self { + Self { + model: ModelClassifier::new(), + min_score: None, } } @@ -50,38 +76,62 @@ impl Classifier { pub fn with_model(model_path: &str) -> Result { Ok(Self { model: ModelClassifier::with_model(model_path)?, + min_score: None, }) } + /// Set a minimum score threshold for `sub_type_scores` and `detections`. + /// + /// Scores below this threshold are dropped from the output. + /// Default is `None` (no filtering — all scores included). + pub fn min_score(mut self, threshold: f32) -> Self { + self.min_score = Some(threshold); + self + } + /// Classify a single text string. /// - /// 1. Short text (< 5 words) -> Skip - /// 2. Tier 1 structural features -> if confidence >= 0.95, return - /// 3. Tier 2 model (if loaded) -> return model decision - /// 4. No model -> return low-confidence fallback + /// When the ONNX model is loaded, all non-trivial samples go through + /// the model (model-first). When no model is available, falls back + /// to Tier 1 rule-based classification. pub fn classify(&self, text: &str) -> Classification { - if text.trim().is_empty() || tier1::is_too_short(text) { + if text.trim().is_empty() { + return Classification { + category: TextCategory::Prose, + sub_type: None, + confidence: 0.0, + reason: "empty or no content".to_string(), + tier: Tier::Structural, + detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), + }; + } + if tier1::is_too_short(text) { return Classification { - category: TextCategory::Skip, + category: TextCategory::Prose, sub_type: None, - confidence: 1.0, - reason: "too short".to_string(), + confidence: 0.5, + reason: "too short for reliable classification".to_string(), tier: Tier::Structural, detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), }; } let features = features::extract_features(text); - let tier1_result = tier1::classify_tier1(&features); - // Only accept Tier 1 for very high-confidence short-circuits - let threshold = 0.95; - if tier1_result.confidence >= threshold { - return tier1_result; + let mut result = if self.model.has_model() { + self.model.classify(&features) + } else { + tier1::classify_tier1(&features) + }; + + if let Some(threshold) = self.min_score { + filter_scores(&mut result.sub_type_scores, threshold); + filter_scores(&mut result.detections, threshold); } - // Otherwise, fall through to Tier 2 - self.model.classify(&features) + result } /// Classify multiple texts in parallel using rayon. @@ -96,6 +146,13 @@ impl Classifier { } } +fn filter_scores(scores: &mut BTreeMap>, threshold: f32) { + scores.retain(|_, detections| { + detections.retain(|d| d.score >= threshold); + !detections.is_empty() + }); +} + impl Default for Classifier { fn default() -> Self { Self::new() diff --git a/src/main.rs b/src/main.rs index 7621f57..1a6fcf0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,6 +15,11 @@ struct Cli { #[arg(long)] human: bool, + /// Minimum score threshold for sub-type scores and detections. + /// Scores below this are dropped from output. + #[arg(long)] + min_score: Option, + #[command(subcommand)] command: Option, } @@ -286,7 +291,10 @@ impl Evaluator { fn main() -> Result<(), Box> { let cli = Cli::parse(); - let classifier = Classifier::new(); + let mut classifier = Classifier::with_embedded_model(); + if let Some(threshold) = cli.min_score { + classifier = classifier.min_score(threshold); + } match cli.command { None => { @@ -457,13 +465,7 @@ fn classify_file( let mut doc: serde_json::Value = serde_json::from_str(&line)?; if let Some(text) = resolve_field(&doc, text_field) { let result = classifier.classify(text); - doc["_classification"] = serde_json::json!({ - "category": result.category, - "sub_type": result.sub_type, - "confidence": result.confidence, - "reason": result.reason, - "tier": result.tier, - }); + doc["_classification"] = serde_json::to_value(&result)?; } else { missing_field += 1; } @@ -590,10 +592,21 @@ fn extract_features_file( let reader = open_reader(input)?; let mut out = io::BufWriter::new(std::fs::File::create(output)?); - // CSV header + // CSV header — all 41 model features in model-expected order writeln!( out, - "line_length_cv,char_entropy,leading_whitespace_ratio,tab_density,sentence_punctuation_rate,paragraph_break_rate,alpha_ratio,line_uniqueness,short_line_ratio,symbol_ratio,delimiter_consistency,json_brace_depth,key_value_ratio,xml_tag_ratio,log_line_ratio,comment_ratio,numeric_field_ratio,repetitive_structure_score,line_count" + "line_length_cv,char_entropy,leading_whitespace_ratio,tab_density,\ + sentence_punctuation_rate,paragraph_break_rate,alpha_ratio,line_uniqueness,\ + short_line_ratio,symbol_ratio,delimiter_consistency,json_brace_depth,\ + key_value_ratio,xml_tag_ratio,log_line_ratio,comment_ratio,\ + numeric_field_ratio,repetitive_structure_score,hyphenated_line_break_ratio,\ + short_repeated_line_ratio,page_number_density,label_value_line_ratio,\ + table_fragment_score,uppercase_header_ratio,dictionary_word_ratio,\ + encoding_error_ratio,repeated_ngram_ratio,sentence_coherence_score,\ + avg_words_per_line,operator_density,inline_markup_count,\ + indentation_consistency,markup_heading_ratio,code_fence_density,\ + prose_paragraph_ratio,semicolon_line_ending_ratio,list_item_ratio,\ + parenthesis_density,section_header_ratio,json_lines_ratio,shebang_present" )?; let mut count = 0; @@ -608,7 +621,11 @@ fn extract_features_file( let f = classifier.extract_features(text); writeln!( out, - "{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{}", + "{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},\ + {:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},\ + {:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},\ + {:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4},\ + {:.4}", f.line_length_cv, f.char_entropy, f.leading_whitespace_ratio, @@ -627,7 +644,29 @@ fn extract_features_file( f.comment_ratio, f.numeric_field_ratio, f.repetitive_structure_score, - f.line_count + f.hyphenated_line_break_ratio, + f.short_repeated_line_ratio, + f.page_number_density, + f.label_value_line_ratio, + f.table_fragment_score, + f.uppercase_header_ratio, + f.dictionary_word_ratio, + f.encoding_error_ratio, + f.repeated_ngram_ratio, + f.sentence_coherence_score, + f.avg_words_per_line, + f.operator_density, + f.inline_markup_count, + f.indentation_consistency, + f.markup_heading_ratio, + f.code_fence_density, + f.prose_paragraph_ratio, + f.semicolon_line_ending_ratio, + f.list_item_ratio, + f.parenthesis_density, + f.section_header_ratio, + f.json_lines_ratio, + f.shebang_present, )?; count += 1; } @@ -696,6 +735,29 @@ fn label_corpus( "comment_ratio": features.comment_ratio, "numeric_field_ratio": features.numeric_field_ratio, "repetitive_structure_score": features.repetitive_structure_score, + "hyphenated_line_break_ratio": features.hyphenated_line_break_ratio, + "short_repeated_line_ratio": features.short_repeated_line_ratio, + "page_number_density": features.page_number_density, + "label_value_line_ratio": features.label_value_line_ratio, + "table_fragment_score": features.table_fragment_score, + "uppercase_header_ratio": features.uppercase_header_ratio, + "dictionary_word_ratio": features.dictionary_word_ratio, + "encoding_error_ratio": features.encoding_error_ratio, + "repeated_ngram_ratio": features.repeated_ngram_ratio, + "sentence_coherence_score": features.sentence_coherence_score, + "avg_words_per_line": features.avg_words_per_line, + "operator_density": features.operator_density, + "inline_markup_count": features.inline_markup_count, + "indentation_consistency": features.indentation_consistency, + "markup_heading_ratio": features.markup_heading_ratio, + "code_fence_density": features.code_fence_density, + "prose_paragraph_ratio": features.prose_paragraph_ratio, + "semicolon_line_ending_ratio": features.semicolon_line_ending_ratio, + "list_item_ratio": features.list_item_ratio, + "parenthesis_density": features.parenthesis_density, + "section_header_ratio": features.section_header_ratio, + "json_lines_ratio": features.json_lines_ratio, + "shebang_present": features.shebang_present, }); } @@ -943,7 +1005,7 @@ mod tests { .get("features") .expect("features should be present when with_features is true"); assert!(features.is_object()); - // Check all 18 feature fields are present + // Check all 41 feature fields are present let expected_fields = [ "line_length_cv", "char_entropy", @@ -963,6 +1025,29 @@ mod tests { "comment_ratio", "numeric_field_ratio", "repetitive_structure_score", + "hyphenated_line_break_ratio", + "short_repeated_line_ratio", + "page_number_density", + "label_value_line_ratio", + "table_fragment_score", + "uppercase_header_ratio", + "dictionary_word_ratio", + "encoding_error_ratio", + "repeated_ngram_ratio", + "sentence_coherence_score", + "avg_words_per_line", + "operator_density", + "inline_markup_count", + "indentation_consistency", + "markup_heading_ratio", + "code_fence_density", + "prose_paragraph_ratio", + "semicolon_line_ending_ratio", + "list_item_ratio", + "parenthesis_density", + "section_header_ratio", + "json_lines_ratio", + "shebang_present", ]; for field in &expected_fields { assert!( @@ -998,6 +1083,7 @@ mod tests { reason: "high alpha ratio".to_string(), tier: text_classifier::Tier::Structural, detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), }; let output = format_human_friendly(&result); assert_eq!(output, "prose (confidence: 0.95, tier: structural)"); @@ -1012,6 +1098,7 @@ mod tests { reason: "config detected".to_string(), tier: text_classifier::Tier::Structural, detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), }; let output = format_human_friendly(&result); assert_eq!(output, "code/yaml (confidence: 0.85, tier: structural)"); @@ -1100,6 +1187,7 @@ mod tests { reason: "model".to_string(), tier: text_classifier::Tier::Model, detections, + sub_type_scores: BTreeMap::new(), }; let output = format_human_friendly(&result); assert!(output.contains("detections:")); @@ -1137,6 +1225,7 @@ mod tests { reason: "model".to_string(), tier: text_classifier::Tier::Model, detections, + sub_type_scores: BTreeMap::new(), }; let output = format_human_friendly(&result); // Should contain detections sorted by score descending @@ -1162,6 +1251,7 @@ mod tests { reason: "high alpha ratio".to_string(), tier: text_classifier::Tier::Structural, detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), }; let output = format_human_friendly(&result); assert!(!output.contains("detections:")); @@ -1186,6 +1276,7 @@ mod tests { reason: "model".to_string(), tier: text_classifier::Tier::Model, detections, + sub_type_scores: BTreeMap::new(), }; let output = format_human_friendly(&result); // Score 0.40 is below 0.5 threshold, so no detections suffix diff --git a/src/model.onnx b/src/model.onnx index a0a856b..8d7bb9d 100644 Binary files a/src/model.onnx and b/src/model.onnx differ diff --git a/src/model_config.json b/src/model_config.json index 798ecb5..dd54316 100644 --- a/src/model_config.json +++ b/src/model_config.json @@ -39,91 +39,94 @@ "list_item_ratio", "parenthesis_density", "section_header_ratio", - "json_lines_ratio" + "json_lines_ratio", + "shebang_present" ], "feature_mean": [ - 0.6890163421630859, - 4.7008466720581055, - 0.1718541830778122, - 0.005313715431839228, - 0.01896430365741253, - 0.10152948647737503, - 0.8574573993682861, - 0.8588656783103943, - 0.1815190315246582, - 0.05420548841357231, - 0.1081424355506897, - 0.007781723979860544, - 0.2529405951499939, - 0.04956423491239548, - 0.007686051074415445, - 0.04826904088258743, - 0.03433968871831894, - 0.3398450016975403, - 0.0012237651972100139, - 0.1270494908094406, - 0.0011345000239089131, - 0.045632075518369675, - 0.34092098474502563, - 0.023010579869151115, - 0.48544013500213623, - 0.0005950411432422698, - 0.04497946798801422, - 0.14731571078300476, - 61.998626708984375, - 2.154758930206299, - 0.6517844200134277, - 0.3409189283847809, - 0.025441881269216537, - 0.0021014350932091475, - 0.13242113590240479, - 0.057640861719846725, - 0.028252307325601578, - 7.735301971435547, - 0.00749941123649478, - 0.014394442550837994 + 0.8004229068756104, + 4.754919052124023, + 0.21073386073112488, + 0.004415265750139952, + 0.018821636214852333, + 0.12205729633569717, + 0.8508036732673645, + 0.8244237899780273, + 0.18349526822566986, + 0.06024371460080147, + 0.090770423412323, + 0.00882804300636053, + 0.2801662087440491, + 0.05141352862119675, + 0.0022761330474168062, + 0.05925000086426735, + 0.026637202128767967, + 0.3296829164028168, + 0.0011861433740705252, + 0.16153617203235626, + 0.0010314120445400476, + 0.05012809485197067, + 0.3053745925426483, + 0.026474010199308395, + 0.5093384981155396, + 0.0004975409829057753, + 0.05471445992588997, + 0.11200858652591705, + 68.47679138183594, + 2.767969846725464, + 0.8039880394935608, + 0.41734564304351807, + 0.031832318753004074, + 0.002873446559533477, + 0.10470637679100037, + 0.07502559572458267, + 0.03702828288078308, + 9.946778297424316, + 0.005861266981810331, + 0.02842649258673191, + 0.027843736112117767 ], "feature_std": [ - 0.6134119033813477, - 0.5874835848808289, - 0.27703994512557983, - 0.020296555012464523, - 0.027148647233843803, - 0.13588790595531464, - 0.09615051001310349, - 0.17069196701049805, - 0.21155153214931488, - 0.05668779835104942, - 0.2711528241634369, - 0.014279451221227646, - 0.3233777582645416, - 0.18267080187797546, - 0.08544522523880005, - 0.1184808760881424, - 0.10556890815496445, - 0.26649951934814453, - 0.011777455918490887, - 0.21196195483207703, - 0.01927615888416767, - 0.13523578643798828, - 0.39692214131355286, - 0.08067207038402557, - 0.2710053622722626, - 0.0066087148152291775, - 0.09011807292699814, - 0.324241042137146, - 216.29464721679688, - 9.888690948486328, - 2.4525647163391113, - 0.45970410108566284, - 0.08465984463691711, - 0.030681803822517395, - 0.2848948538303375, - 0.15720009803771973, - 0.10139095038175583, - 13.496188163757324, - 0.041099175810813904, - 0.11487831920385361 + 0.6218932271003723, + 0.46051737666130066, + 0.2941332161426544, + 0.017283529043197632, + 0.026878200471401215, + 0.14247570931911469, + 0.09157270938158035, + 0.17792117595672607, + 0.18261797726154327, + 0.056362755596637726, + 0.2317957580089569, + 0.014758943580091, + 0.32165369391441345, + 0.1798916459083557, + 0.046029239892959595, + 0.12655188143253326, + 0.08021397143602371, + 0.22647403180599213, + 0.011869662441313267, + 0.22756293416023254, + 0.014366354793310165, + 0.13851656019687653, + 0.3648563325405121, + 0.0836302787065506, + 0.23915934562683105, + 0.006065250374376774, + 0.0972866490483284, + 0.27491798996925354, + 246.6176300048828, + 11.275725364685059, + 2.754995822906494, + 0.47671717405319214, + 0.0928511768579483, + 0.03504341468214989, + 0.23795510828495026, + 0.17535266280174255, + 0.11525464057922363, + 14.201077461242676, + 0.036764755845069885, + 0.16137635707855225, + 0.1644771844148636 ], "category_map": { "prose": 0, @@ -131,35 +134,37 @@ "structured": 2 }, "sub_type_map": { - "css": 0, - "csv": 1, - "dockerfile": 2, - "fixed_width": 3, - "go": 4, - "html": 5, - "ini": 6, - "java": 7, - "javascript": 8, - "json": 9, - "jsonl": 10, - "key_value": 11, - "latex": 12, - "log_lines": 13, - "makefile": 14, - "markdown": 15, - "pipe_table": 16, - "plain": 17, - "python": 18, - "rst": 19, - "rust": 20, - "shell": 21, - "sql": 22, - "toml": 23, - "tsv": 24, - "typescript": 25, - "unknown": 26, - "xml": 27, - "yaml": 28 + "c_cpp": 0, + "css": 1, + "csv": 2, + "dockerfile": 3, + "fixed_width": 4, + "go": 5, + "html": 6, + "ini": 7, + "java": 8, + "javascript": 9, + "json": 10, + "jsonl": 11, + "key_value": 12, + "latex": 13, + "log_lines": 14, + "makefile": 15, + "markdown": 16, + "objc": 17, + "pipe_table": 18, + "plain": 19, + "python": 20, + "rst": 21, + "rust": 22, + "shell": 23, + "sql": 24, + "toml": 25, + "tsv": 26, + "typescript": 27, + "unknown": 28, + "xml": 29, + "yaml": 30 }, "detection_threshold": 0.3 } diff --git a/src/python.rs b/src/python.rs index e4ed6f2..2954b30 100644 --- a/src/python.rs +++ b/src/python.rs @@ -21,11 +21,14 @@ struct PyClassification { tier: String, #[pyo3(get)] detections: String, + #[pyo3(get)] + sub_type_scores: String, } impl From for PyClassification { fn from(c: Classification) -> Self { let detections = serde_json::to_string(&c.detections).unwrap_or_default(); + let sub_type_scores = serde_json::to_string(&c.sub_type_scores).unwrap_or_default(); PyClassification { category: c.category.to_string(), sub_type: c.sub_type.map(|s| s.label().to_string()), @@ -34,6 +37,7 @@ impl From for PyClassification { reason: c.reason, tier: c.tier.to_string(), detections, + sub_type_scores, } } } @@ -73,10 +77,13 @@ struct PyClassifier { #[pymethods] impl PyClassifier { #[new] - fn new() -> PyResult { - Ok(PyClassifier { - inner: RustClassifier::new(), - }) + #[pyo3(signature = (min_score=None))] + fn new(min_score: Option) -> PyResult { + let mut clf = RustClassifier::with_embedded_model(); + if let Some(threshold) = min_score { + clf = clf.min_score(threshold); + } + Ok(PyClassifier { inner: clf }) } fn classify(&self, text: &str) -> PyClassification { @@ -113,14 +120,36 @@ impl PyClassifier { dict.set_item("comment_ratio", f.comment_ratio)?; dict.set_item("numeric_field_ratio", f.numeric_field_ratio)?; dict.set_item("repetitive_structure_score", f.repetitive_structure_score)?; - dict.set_item("line_count", f.line_count)?; + dict.set_item("hyphenated_line_break_ratio", f.hyphenated_line_break_ratio)?; + dict.set_item("short_repeated_line_ratio", f.short_repeated_line_ratio)?; + dict.set_item("page_number_density", f.page_number_density)?; + dict.set_item("label_value_line_ratio", f.label_value_line_ratio)?; + dict.set_item("table_fragment_score", f.table_fragment_score)?; + dict.set_item("uppercase_header_ratio", f.uppercase_header_ratio)?; + dict.set_item("dictionary_word_ratio", f.dictionary_word_ratio)?; + dict.set_item("encoding_error_ratio", f.encoding_error_ratio)?; + dict.set_item("repeated_ngram_ratio", f.repeated_ngram_ratio)?; + dict.set_item("sentence_coherence_score", f.sentence_coherence_score)?; + dict.set_item("avg_words_per_line", f.avg_words_per_line)?; + dict.set_item("operator_density", f.operator_density)?; + dict.set_item("inline_markup_count", f.inline_markup_count)?; + dict.set_item("indentation_consistency", f.indentation_consistency)?; + dict.set_item("markup_heading_ratio", f.markup_heading_ratio)?; + dict.set_item("code_fence_density", f.code_fence_density)?; + dict.set_item("prose_paragraph_ratio", f.prose_paragraph_ratio)?; + dict.set_item("semicolon_line_ending_ratio", f.semicolon_line_ending_ratio)?; + dict.set_item("list_item_ratio", f.list_item_ratio)?; + dict.set_item("parenthesis_density", f.parenthesis_density)?; + dict.set_item("section_header_ratio", f.section_header_ratio)?; + dict.set_item("json_lines_ratio", f.json_lines_ratio)?; + dict.set_item("shebang_present", f.shebang_present)?; Ok(dict) } } #[pyfunction] fn classify(text: &str) -> PyClassification { - let classifier = RustClassifier::new(); + let classifier = RustClassifier::with_embedded_model(); classifier.classify(text).into() } @@ -195,6 +224,7 @@ mod tests { reason: "prose detected".to_string(), tier: Tier::Structural, detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), }; let py_c = PyClassification::from(c); let parsed: serde_json::Value = diff --git a/src/tier1.rs b/src/tier1.rs index 60556f6..34317dc 100644 --- a/src/tier1.rs +++ b/src/tier1.rs @@ -15,12 +15,13 @@ pub fn classify_tier1(features: &FeatureVector) -> Classification { // Short-circuit: empty / no content if features.alpha_ratio == 0.0 && features.sentence_punctuation_rate == 0.0 { return Classification { - category: TextCategory::Skip, + category: TextCategory::Prose, sub_type: None, - confidence: 1.0, + confidence: 0.0, reason: "empty or no content".to_string(), tier: Tier::Structural, detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), }; } @@ -40,6 +41,7 @@ pub fn classify_tier1(features: &FeatureVector) -> Classification { ), tier: Tier::Structural, detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), }; } @@ -58,6 +60,7 @@ pub fn classify_tier1(features: &FeatureVector) -> Classification { ), tier: Tier::Structural, detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), }; } @@ -77,17 +80,19 @@ pub fn classify_tier1(features: &FeatureVector) -> Classification { ), tier: Tier::Structural, detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), }; } // Default fallback: low confidence to trigger Tier 2 Classification { - category: TextCategory::Skip, + category: TextCategory::Prose, sub_type: None, confidence: 0.40, reason: "ambiguous — deferring to model".to_string(), tier: Tier::Structural, detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), } } diff --git a/src/tier2.rs b/src/tier2.rs index d13be42..24453f8 100644 --- a/src/tier2.rs +++ b/src/tier2.rs @@ -249,15 +249,17 @@ impl ModelClassifier { reason: "no model — fallback: moderate prose signals".to_string(), tier: Tier::Structural, detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), } } else { Classification { - category: TextCategory::Skip, + category: TextCategory::Prose, sub_type: None, - confidence: 0.5, + confidence: 0.3, reason: "no model — fallback: insufficient prose signals".to_string(), tier: Tier::Structural, detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), } } } @@ -265,7 +267,7 @@ impl ModelClassifier { /// Number of features in the feature vector (must match model input size). #[cfg(any(feature = "onnx-model", test))] -const NUM_FEATURES: usize = 40; +const NUM_FEATURES: usize = 41; /// Extract features from a FeatureVector in model-expected order. #[cfg(any(feature = "onnx-model", test))] @@ -312,6 +314,7 @@ fn feature_vector_to_array(f: &FeatureVector) -> [f32; NUM_FEATURES] { f.parenthesis_density, f.section_header_ratio, f.json_lines_ratio, + f.shebang_present, ] } @@ -339,7 +342,7 @@ fn parse_category(s: &str) -> TextCategory { "prose" => TextCategory::Prose, "code" => TextCategory::Code, "structured" => TextCategory::Structured, - _ => TextCategory::Skip, + _ => TextCategory::Prose, } } @@ -364,8 +367,11 @@ fn parse_sub_type(s: &str) -> ContentSubType { "ini" | "ini_config" => ContentSubType::Ini, "dockerfile" => ContentSubType::Dockerfile, "makefile" => ContentSubType::Makefile, + "c_cpp" => ContentSubType::CCpp, + "objc" => ContentSubType::ObjC, "html" => ContentSubType::Html, - "xml" | "sgml" => ContentSubType::Xml, + "xml" => ContentSubType::Xml, + "sgml" => ContentSubType::Sgml, "csv" | "csv_data" => ContentSubType::Csv, "tsv" | "tsv_data" => ContentSubType::Tsv, "pipe_table" => ContentSubType::PipeTable, @@ -447,7 +453,7 @@ fn build_classification( let (marginalized_cat, marginalized_conf) = cat_accum .into_iter() .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)) - .unwrap_or((TextCategory::Skip, 0.0)); + .unwrap_or((TextCategory::Prose, 0.0)); let detections = match (det_logits, inv_det) { (Some(logits), Some(inv_det)) => { @@ -457,6 +463,28 @@ fn build_classification( _ => BTreeMap::new(), }; + // Full sub-type probability distribution (no threshold filtering) + let mut sub_type_scores: BTreeMap> = BTreeMap::new(); + for (idx, &prob) in sub_probs.iter().enumerate() { + let label = inv_sub.get(&idx).map(|s| s.as_str()).unwrap_or("unknown"); + let sub_type = parse_sub_type(label); + let category = sub_type.category(); + sub_type_scores + .entry(category) + .or_default() + .push(Detection { + sub_type, + score: prob, + }); + } + for scores in sub_type_scores.values_mut() { + scores.sort_by(|a, b| { + b.score + .partial_cmp(&a.score) + .unwrap_or(std::cmp::Ordering::Equal) + }); + } + Classification { category: marginalized_cat, sub_type: Some(parse_sub_type(sub_label)), @@ -466,6 +494,7 @@ fn build_classification( ), tier: Tier::Model, detections, + sub_type_scores, } } @@ -531,9 +560,9 @@ mod tests { assert_eq!(parse_category("prose"), TextCategory::Prose); assert_eq!(parse_category("code"), TextCategory::Code); assert_eq!(parse_category("structured"), TextCategory::Structured); - assert_eq!(parse_category("skip"), TextCategory::Skip); - assert_eq!(parse_category("artifact"), TextCategory::Skip); // removed category falls to default - assert_eq!(parse_category("unknown_value"), TextCategory::Skip); + assert_eq!(parse_category("skip"), TextCategory::Prose); + assert_eq!(parse_category("artifact"), TextCategory::Prose); // removed category falls to default + assert_eq!(parse_category("unknown_value"), TextCategory::Prose); } #[test] @@ -577,12 +606,12 @@ mod tests { } #[test] - fn test_fallback_skip() { + fn test_fallback_low_confidence_prose() { let classifier = ModelClassifier::without_model(); let features = skip_features(); let result = classifier.classify(&features); - assert_eq!(result.category, TextCategory::Skip); - assert!((result.confidence - 0.5).abs() < f32::EPSILON); + assert_eq!(result.category, TextCategory::Prose); + assert!((result.confidence - 0.3).abs() < f32::EPSILON); } #[test] @@ -736,10 +765,10 @@ mod tests { let scores = vec![0.9]; let result = build_detections(&scores, &inv_map, 0.5); - // "unknown" label maps to ContentSubType::Unknown, category Skip - assert!(result.contains_key(&TextCategory::Skip)); + // "unknown" label maps to ContentSubType::Unknown, category Prose + assert!(result.contains_key(&TextCategory::Prose)); assert_eq!( - result[&TextCategory::Skip][0].sub_type, + result[&TextCategory::Prose][0].sub_type, ContentSubType::Unknown ); } @@ -757,12 +786,11 @@ mod tests { use std::collections::HashMap; // cat_probs: code is highest at 0.60 - let cat_probs = vec![0.15, 0.60, 0.20, 0.05]; // prose, code, structured, skip + let cat_probs = vec![0.15, 0.60, 0.25]; // prose, code, structured let mut inv_cat = HashMap::new(); inv_cat.insert(0, "prose".to_string()); inv_cat.insert(1, "code".to_string()); inv_cat.insert(2, "structured".to_string()); - inv_cat.insert(3, "skip".to_string()); // sub_probs: ini(0.35) + key_value(0.30) + toml(0.15) = 0.80 for structured // remaining 0.20 spread across code sub-types @@ -826,11 +854,11 @@ mod tests { DEFAULT_DETECTION_THRESHOLD, ); - // Unknown sub-types map to ContentSubType::Unknown -> TextCategory::Skip + // Unknown sub-types map to ContentSubType::Unknown -> TextCategory::Prose assert_eq!( classification.category, - TextCategory::Skip, - "unknown sub-types should result in Skip category" + TextCategory::Prose, + "unknown sub-types should result in Prose category" ); } @@ -955,7 +983,7 @@ mod tests { #[cfg(feature = "onnx-model")] #[test] - fn test_model_config_has_40_features() { + fn test_model_config_has_expected_features() { let config: serde_json::Value = serde_json::from_str(CONFIG_JSON).expect("CONFIG_JSON should parse"); let names = config["feature_names"] @@ -963,8 +991,8 @@ mod tests { .expect("feature_names should be an array"); assert_eq!( names.len(), - 40, - "model_config.json should have 40 features, got {}", + NUM_FEATURES, + "model_config.json should have {NUM_FEATURES} features, got {}", names.len() ); } diff --git a/src/types.rs b/src/types.rs index 8186e92..a7e4473 100644 --- a/src/types.rs +++ b/src/types.rs @@ -8,7 +8,6 @@ pub enum TextCategory { Prose, Code, Structured, - Skip, } /// Backward-compatible alias for `TextCategory`. @@ -26,7 +25,6 @@ impl std::fmt::Display for TextCategory { TextCategory::Prose => write!(f, "prose"), TextCategory::Code => write!(f, "code"), TextCategory::Structured => write!(f, "structured"), - TextCategory::Skip => write!(f, "skip"), } } } @@ -59,7 +57,9 @@ pub enum ContentSubType { Latex, // Code Python, + #[serde(rename = "javascript")] JavaScript, + #[serde(rename = "typescript")] TypeScript, Rust, Go, @@ -70,6 +70,10 @@ pub enum ContentSubType { // Code > Config Dockerfile, Makefile, + // Code > Native + CCpp, + #[serde(rename = "objc")] + ObjC, // Code > Markup Html, Xml, @@ -114,6 +118,8 @@ impl ContentSubType { | ContentSubType::Css | ContentSubType::Dockerfile | ContentSubType::Makefile + | ContentSubType::CCpp + | ContentSubType::ObjC | ContentSubType::Html | ContentSubType::Xml | ContentSubType::Sgml => TextCategory::Code, @@ -132,7 +138,7 @@ impl ContentSubType { | ContentSubType::Ini => TextCategory::Structured, // Fallback - ContentSubType::Unknown => TextCategory::Skip, + ContentSubType::Unknown => TextCategory::Prose, } } @@ -157,6 +163,8 @@ impl ContentSubType { ContentSubType::Ini => "ini", ContentSubType::Dockerfile => "dockerfile", ContentSubType::Makefile => "makefile", + ContentSubType::CCpp => "c_cpp", + ContentSubType::ObjC => "objc", ContentSubType::Html => "html", ContentSubType::Xml => "xml", ContentSubType::Sgml => "sgml", @@ -190,6 +198,10 @@ pub struct Classification { pub tier: Tier, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub detections: BTreeMap>, + /// Full sub-type probability distribution from the softmax head, + /// grouped by parent category. All 31 sub-types, no threshold. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub sub_type_scores: BTreeMap>, } /// A detected sub-type with its confidence score. @@ -251,6 +263,7 @@ pub struct FeatureVector { pub parenthesis_density: f32, pub section_header_ratio: f32, pub json_lines_ratio: f32, + pub shebang_present: f32, /// Number of lines in the sampled text. Used by rules that need /// a minimum sample size (e.g. tabular detection). pub line_count: usize, @@ -300,6 +313,7 @@ impl FeatureVector { parenthesis_density: 0.0, section_header_ratio: 0.0, json_lines_ratio: 0.0, + shebang_present: 0.0, line_count: 0, } } diff --git a/tests/test_contracts.rs b/tests/test_contracts.rs index 59c598a..c2835be 100644 --- a/tests/test_contracts.rs +++ b/tests/test_contracts.rs @@ -27,7 +27,6 @@ fn contract_text_category_variants() { let _: TextCategory = TextCategory::Prose; let _: TextCategory = TextCategory::Code; let _: TextCategory = TextCategory::Structured; - let _: TextCategory = TextCategory::Skip; } #[test] @@ -43,7 +42,7 @@ fn contract_content_sub_type_category_mapping() { ContentSubType::LogLines.category(), TextCategory::Structured ); - assert_eq!(ContentSubType::Unknown.category(), TextCategory::Skip); + assert_eq!(ContentSubType::Unknown.category(), TextCategory::Prose); } #[test] @@ -62,6 +61,7 @@ fn contract_classification_has_category_and_sub_type() { reason: "test".to_string(), tier: Tier::Structural, detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), }; assert_eq!(c.category, TextCategory::Code); assert_eq!(c.sub_type, Some(ContentSubType::Python)); @@ -101,7 +101,6 @@ fn contract_text_category_display() { assert_eq!(TextCategory::Prose.to_string(), "prose"); assert_eq!(TextCategory::Code.to_string(), "code"); assert_eq!(TextCategory::Structured.to_string(), "structured"); - assert_eq!(TextCategory::Skip.to_string(), "skip"); } #[test] @@ -109,7 +108,6 @@ fn contract_text_category_is_prose() { assert!(TextCategory::Prose.is_prose()); assert!(!TextCategory::Code.is_prose()); assert!(!TextCategory::Structured.is_prose()); - assert!(!TextCategory::Skip.is_prose()); } #[test] @@ -138,6 +136,7 @@ fn contract_classification_text_type_deprecated_accessor() { reason: "test".to_string(), tier: Tier::Structural, detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), }; assert_eq!(c.text_type(), TextCategory::Code); } @@ -200,7 +199,7 @@ fn contract_content_sub_type_all_category_mappings() { assert_eq!(ContentSubType::Ini.category(), TextCategory::Structured); // Fallback - assert_eq!(ContentSubType::Unknown.category(), TextCategory::Skip); + assert_eq!(ContentSubType::Unknown.category(), TextCategory::Prose); } #[test] @@ -271,29 +270,24 @@ fn contract_feature_vector_zeroed_all_zero() { assert_eq!(f.line_count, 0); } -/// Verify that TextCategory has exactly 4 variants after simplification. +/// Verify that TextCategory has exactly 3 variants: Prose, Code, Structured. #[test] -fn contract_text_category_no_artifact_variants() { - // TextCategory should only have Prose, Code, Structured, Skip - // This test verifies the enum is exhaustive with exactly these 4 variants +fn contract_text_category_exhaustive() { let categories = [ TextCategory::Prose, TextCategory::Code, TextCategory::Structured, - TextCategory::Skip, ]; for cat in &categories { - // Each variant should have a valid display string let s = cat.to_string(); assert!(!s.is_empty()); } } -/// Verify that ContentSubType no longer has artifact or skip sub-types. +/// Verify that ContentSubType::Unknown maps to Prose (safe fallback). #[test] -fn contract_content_sub_type_no_artifact_skip_subtypes() { - // Unknown is the only fallback, mapping to Skip - assert_eq!(ContentSubType::Unknown.category(), TextCategory::Skip); +fn contract_content_sub_type_unknown_maps_to_prose() { + assert_eq!(ContentSubType::Unknown.category(), TextCategory::Prose); assert_eq!(ContentSubType::Unknown.label(), "unknown"); } @@ -316,6 +310,7 @@ fn contract_classification_has_detections() { reason: "test".to_string(), tier: Tier::Model, detections: BTreeMap::new(), + sub_type_scores: BTreeMap::new(), }; assert!(c.detections.is_empty()); } @@ -337,6 +332,7 @@ fn contract_classification_detections_serialized() { reason: "test".to_string(), tier: Tier::Model, detections, + sub_type_scores: BTreeMap::new(), }; let json = serde_json::to_string(&c).unwrap(); assert!(json.contains("detections")); diff --git a/tests/test_integration.rs b/tests/test_integration.rs index 955e0d0..9db3264 100644 --- a/tests/test_integration.rs +++ b/tests/test_integration.rs @@ -127,18 +127,19 @@ fn end_to_end_shell_code() { // --- Basic skip tests --- #[test] -fn short_text_is_skip() { +fn short_text_is_low_confidence_prose() { let clf = Classifier::new(); let result = clf.classify("hello"); - assert_eq!(result.category, TextCategory::Skip); - assert_eq!(result.confidence, 1.0); + assert_eq!(result.category, TextCategory::Prose); + assert!((result.confidence - 0.5).abs() < f32::EPSILON); } #[test] -fn empty_text_is_skip() { +fn empty_text_is_zero_confidence_prose() { let clf = Classifier::new(); let result = clf.classify(""); - assert_eq!(result.category, TextCategory::Skip); + assert_eq!(result.category, TextCategory::Prose); + assert_eq!(result.confidence, 0.0); } #[test] @@ -151,7 +152,7 @@ fn batch_classification_works() { ]; let results = clf.classify_batch(&texts); assert_eq!(results.len(), 3); - assert_eq!(results[2].category, TextCategory::Skip); + assert_eq!(results[2].category, TextCategory::Prose); } #[test] diff --git a/tests/test_tier1.rs b/tests/test_tier1.rs index 34ed4fd..68738b7 100644 --- a/tests/test_tier1.rs +++ b/tests/test_tier1.rs @@ -85,7 +85,7 @@ fn ambiguous_text_low_confidence() { // --- Default fallback behavior --- #[test] -fn fallback_returns_low_confidence_skip() { +fn fallback_returns_low_confidence_prose() { let features = FeatureVector { line_length_cv: 0.5, char_entropy: 3.5, @@ -109,7 +109,7 @@ fn fallback_returns_low_confidence_skip() { ..FeatureVector::zeroed() }; let result = classify_tier1(&features); - assert_eq!(result.category, TextCategory::Skip); + assert_eq!(result.category, TextCategory::Prose); assert!( result.confidence <= 0.40, "fallback confidence should be <= 0.40, got {}", @@ -120,22 +120,23 @@ fn fallback_returns_low_confidence_skip() { // --- Existing basic tests updated for new thresholds --- #[test] -fn short_text_classified_as_skip() { +fn short_text_classified_as_low_confidence_prose() { let result = classify("hello world"); - assert_eq!(result.category, TextCategory::Skip); - assert_eq!(result.confidence, 1.0); + assert_eq!(result.category, TextCategory::Prose); + assert!((result.confidence - 0.5).abs() < f32::EPSILON); } #[test] -fn empty_text_classified_as_skip() { +fn empty_text_classified_as_zero_confidence_prose() { let result = classify(""); - assert_eq!(result.category, TextCategory::Skip); + assert_eq!(result.category, TextCategory::Prose); + assert_eq!(result.confidence, 0.0); } #[test] -fn empty_features_classified_as_skip() { +fn empty_features_classified_as_zero_confidence_prose() { let features = FeatureVector::zeroed(); let result = classify_tier1(&features); - assert_eq!(result.category, TextCategory::Skip); - assert_eq!(result.confidence, 1.0); + assert_eq!(result.category, TextCategory::Prose); + assert_eq!(result.confidence, 0.0); }