Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
175 changes: 129 additions & 46 deletions src/features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}
Expand Down Expand Up @@ -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<usize> {
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<usize> {
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<usize> {
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<usize> {
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 {
Expand Down Expand Up @@ -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;
}

Expand All @@ -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
}
}
97 changes: 77 additions & 20 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
};
}

Expand All @@ -36,52 +48,90 @@ pub fn classify(text: &str) -> Classification {
/// Main classifier combining Tier 1 (structural) and Tier 2 (model).
pub struct Classifier {
model: ModelClassifier,
min_score: Option<f32>,
}

impl Classifier {
/// Create a classifier using Tier 1 only (no model).
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,
}
}

/// Create a classifier with a fasttext model for Tier 2.
pub fn with_model(model_path: &str) -> Result<Self, String> {
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.
Expand All @@ -96,6 +146,13 @@ impl Classifier {
}
}

fn filter_scores(scores: &mut BTreeMap<TextCategory, Vec<types::Detection>>, threshold: f32) {
scores.retain(|_, detections| {
detections.retain(|d| d.score >= threshold);
!detections.is_empty()
});
}

impl Default for Classifier {
fn default() -> Self {
Self::new()
Expand Down
Loading
Loading