Likhith Sai Seemala
Deploy IntentForge v2 to HF Spaces
0ca462b
Raw History Blame Contribute Delete
24.6 kB
//! Video Intent Scoring Module v2
//!
//! Lightweight, CPU-efficient intent scoring using:
//! - Jaro-Winkler similarity for better text matching
//! - TF-IDF-like term weighting
//! - Pattern-based intent detection
//! - Heuristic clickbait detection
//!
//! No external ML dependencies - pure Rust implementation
use serde::{Deserialize, Serialize};
/// Video intent categories
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum VideoIntent {
/// Educational/tutorial content
Tutorial,
/// Product/service review
Review,
/// News or current events
News,
/// Entertainment (music, comedy, etc.)
Entertainment,
/// Documentation or conference talk
Documentation,
/// Commercial/promotional
Commercial,
/// Unknown or mixed
Unknown,
}
/// Video quality signals
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct VideoQualitySignals {
/// Has detailed description (>100 chars)
pub has_description: bool,
/// Has tags/categories
pub has_tags: bool,
/// Channel has verified badge or many subscribers
pub authoritative_source: bool,
/// Video has appropriate duration for topic
pub appropriate_duration: bool,
/// Title matches content (no clickbait)
pub title_honest: bool,
/// Has chapters/timestamps
pub has_chapters: bool,
}
/// Video intent scoring result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoIntentScore {
/// Overall intent score (0-1)
pub intent_score: f32,
/// Relevance to query (0-1)
pub relevance_score: f32,
/// Commercial intent (0-1, lower is better for educational)
pub commercial_score: f32,
/// Spam/clickbait likelihood (0-1, lower is better)
pub spam_score: f32,
/// Detected intent category
pub intent_category: VideoIntent,
/// Quality signals
pub quality_signals: VideoQualitySignals,
/// Overall quality gate (passes minimum thresholds)
pub quality_gate: bool,
}
impl Default for VideoIntentScore {
fn default() -> Self {
Self {
intent_score: 0.5,
relevance_score: 0.5,
commercial_score: 0.5,
spam_score: 0.5,
intent_category: VideoIntent::Unknown,
quality_signals: VideoQualitySignals::default(),
quality_gate: false,
}
}
}
/// Video intent scorer with optimized algorithms
pub struct VideoIntentScorer {
/// Query terms for relevance matching
query_terms: Vec<String>,
/// Query term weights (TF-IDF-like)
term_weights: Vec<f32>,
}
impl VideoIntentScorer {
pub fn new(query: &str) -> Self {
let terms: Vec<String> = query
.to_lowercase()
.split_whitespace()
.filter(|w| w.len() > 2)
.map(|s| s.to_string())
.collect();
// Calculate term weights (inverse document frequency approximation)
// Common words get lower weight, specific words get higher weight
let common_words = [
"the", "and", "for", "with", "that", "this", "from", "have", "been", "was",
];
let term_weights: Vec<f32> = terms
.iter()
.map(|term| {
if common_words.contains(&term.as_str()) {
0.5
} else if term.len() > 6 {
1.5 // Longer, more specific terms
} else {
1.0
}
})
.collect();
Self {
query_terms: terms,
term_weights,
}
}
/// Score a video based on its metadata
pub fn score(
&self,
title: &str,
description: Option<&str>,
channel: Option<&str>,
duration_secs: Option<u32>,
view_count: Option<u64>,
) -> VideoIntentScore {
let mut score = VideoIntentScore::default();
let desc = description.unwrap_or("");
// Detect intent category
score.intent_category = self.detect_intent(title, desc);
// Calculate relevance using Jaro-Winkler + term matching
score.relevance_score = self.calculate_relevance(title, desc);
// Calculate commercial score
score.commercial_score = self.calculate_commercial(title, desc, channel.unwrap_or(""));
// Calculate spam score
score.spam_score = self.calculate_spam(title, desc);
// Calculate intent score (combination of relevance and intent match)
score.intent_score = self.calculate_intent_score(&score);
// Analyze quality signals
score.quality_signals = self.analyze_quality_signals(
title,
desc,
channel.unwrap_or(""),
duration_secs,
view_count,
);
// Determine if video passes quality gate
score.quality_gate = self.passes_quality_gate(&score);
score
}
/// Detect video intent category from title and description
fn detect_intent(&self, title: &str, description: &str) -> VideoIntent {
let text = format!("{} {}", title.to_lowercase(), description.to_lowercase());
// Weighted keyword scoring for better accuracy
let intent_keywords: Vec<(&[&str], VideoIntent, f32)> = vec![
// Tutorial (high weight)
(
&[
"tutorial",
"how to",
"guide",
"learn",
"course",
"beginner",
"introduction",
"basics",
"step by step",
"walkthrough",
"explained",
"full course",
"complete guide",
"from scratch",
"getting started",
"quick start",
"for beginners",
"master",
"deep dive",
][..],
VideoIntent::Tutorial,
2.0,
),
// Review
(
&[
"review",
"unboxing",
"vs",
"comparison",
"best",
"top 10",
"worth it",
"honest review",
"pros and cons",
"tested",
"benchmark",
"performance",
"after using",
"long term review",
][..],
VideoIntent::Review,
1.8,
),
// Documentation/Talk
(
&[
"documentation",
"conference",
"keynote",
"talk",
"presentation",
"session",
"workshop",
"seminar",
"lecture",
"university",
"research",
][..],
VideoIntent::Documentation,
1.5,
),
// News
(
&[
"breaking",
"news",
"update",
"announced",
"released",
"just in",
"today",
"latest",
"new",
"coming soon",
"just released",
][..],
VideoIntent::News,
1.5,
),
// Entertainment
(
&[
"funny",
"comedy",
"music video",
"official video",
"lyrics",
"dance",
"prank",
"challenge",
"reaction",
"vlog",
"entertainment",
"meme",
][..],
VideoIntent::Entertainment,
1.3,
),
// Commercial (detect but don't boost)
(
&[
"buy now",
"discount",
"sale",
"promo",
"sponsor",
"affiliate",
"link in description",
"use code",
"limited time",
][..],
VideoIntent::Commercial,
1.0,
),
];
let mut best_intent = VideoIntent::Unknown;
let mut best_score = 0.0f32;
for (keywords, intent, weight) in intent_keywords {
let mut intent_score = 0.0f32;
for keyword in keywords {
if text.contains(keyword) {
// Bonus for title position
if title.to_lowercase().contains(keyword) {
intent_score += weight * 1.5;
} else {
intent_score += weight;
}
}
}
if intent_score > best_score {
best_score = intent_score;
best_intent = intent;
}
}
// Boost tutorial if query has tutorial intent
if best_score < 1.0 {
let query_lower = format!("{:?}", self.query_terms.join(" ")).to_lowercase();
if (query_lower.contains("tutorial")
|| query_lower.contains("how to")
|| query_lower.contains("learn"))
&& (title.to_lowercase().contains("tutorial")
|| title.to_lowercase().contains("course"))
{
return VideoIntent::Tutorial;
}
}
best_intent
}
/// Calculate relevance using Jaro-Winkler + weighted term matching
fn calculate_relevance(&self, title: &str, description: &str) -> f32 {
let title_lower = title.to_lowercase();
let desc_lower = description.to_lowercase();
if self.query_terms.is_empty() {
return 0.5;
}
let mut total_score = 0.0f32;
let mut total_weight = 0.0f32;
for (i, term) in self.query_terms.iter().enumerate() {
let weight = self.term_weights[i];
total_weight += weight;
// Exact match in title (highest score)
if title_lower.contains(term) {
total_score += weight * 1.0;
continue;
}
// Jaro-Winkler similarity for fuzzy matching
let best_title_sim = title_lower
.split_whitespace()
.map(|word| jaro_winkler(term, word))
.fold(0.0f32, f32::max);
let best_desc_sim = desc_lower
.split_whitespace()
.map(|word| jaro_winkler(term, word))
.fold(0.0f32, f32::max);
// Threshold for considering it a match
if best_title_sim > 0.85 {
total_score += weight * 0.9;
} else if best_desc_sim > 0.85 {
total_score += weight * 0.6;
} else if best_title_sim > 0.7 {
total_score += weight * 0.5;
} else if best_desc_sim > 0.7 {
total_score += weight * 0.3;
}
}
// Base score from weighted term matches
let mut score = if total_weight > 0.0 {
total_score / total_weight
} else {
0.0
};
// Bonus for exact phrase match in title
let query_phrase = self.query_terms.join(" ");
if title_lower.contains(&query_phrase) {
score = (score + 0.3).min(1.0);
}
// Bonus for all terms present
let matched_terms = self
.query_terms
.iter()
.filter(|t| title_lower.contains(*t) || desc_lower.contains(*t))
.count();
if matched_terms == self.query_terms.len() {
score = (score + 0.2).min(1.0);
}
score
}
/// Calculate commercial intent score
fn calculate_commercial(&self, title: &str, description: &str, channel: &str) -> f32 {
let text = format!(
"{} {} {}",
title.to_lowercase(),
description.to_lowercase(),
channel.to_lowercase()
);
let mut score = 0.0f32;
// Promotional patterns with weights
let promo_patterns: Vec<(&str, f32)> = vec![
("buy now", 0.2),
("shop now", 0.2),
("discount", 0.15),
("sale", 0.15),
("promo code", 0.2),
("affiliate link", 0.25),
("sponsored", 0.3),
("use my link", 0.25),
("get % off", 0.2),
("free trial", 0.15),
("sign up", 0.1),
("click here", 0.15),
("limited time", 0.15),
("exclusive offer", 0.2),
("deal", 0.1),
("coupon", 0.15),
];
for (pattern, weight) in &promo_patterns {
if text.contains(pattern) {
score += weight;
}
}
// URL-heavy descriptions (often promotional)
let url_count = text.matches("http").count();
if url_count > 5 {
score += 0.2;
} else if url_count > 3 {
score += 0.1;
}
// Official channels are less likely to be spam
if title.to_lowercase().contains("official") || channel.to_lowercase().contains("official")
{
score -= 0.1;
}
score.clamp(0.0, 1.0)
}
/// Calculate spam/clickbait score using heuristic patterns
fn calculate_spam(&self, title: &str, description: &str) -> f32 {
let mut score = 0.0f32;
let title_lower = title.to_lowercase();
// Clickbait patterns with severity weights
let clickbait_patterns: Vec<(&str, f32)> = vec![
("you won't believe", 0.3),
("shocking", 0.2),
("amazing", 0.15),
("incredible", 0.15),
("this changed everything", 0.25),
("goes viral", 0.2),
("everyone is talking", 0.2),
("must watch", 0.15),
("mind blowing", 0.25),
("life changing", 0.25),
("they don't want you to know", 0.3),
("one weird trick", 0.35),
("number ", 0.05),
("reasons why", 0.1),
];
for (pattern, weight) in &clickbait_patterns {
if title_lower.contains(pattern) {
score += weight;
}
}
// ALL CAPS title (spam signal) - only if significant length
let alpha_chars: String = title.chars().filter(|c| c.is_alphabetic()).collect();
if alpha_chars.len() > 10 && alpha_chars.to_uppercase() == alpha_chars {
score += 0.2;
}
// Excessive punctuation
let exclaim_count = title.matches('!').count();
let question_count = title.matches('?').count();
if exclaim_count > 2 {
score += 0.1 * exclaim_count.min(3) as f32;
}
if question_count > 2 {
score += 0.05 * question_count.min(3) as f32;
}
// Excessive emojis (Unicode range check)
let emoji_count = title
.chars()
.filter(|c| *c as u32 > 0x1F000 || (*c as u32 >= 0x2600 && *c as u32 <= 0x27BF))
.count();
if emoji_count > 3 {
score += 0.15;
}
// Very short description (low effort)
if description.len() < 50 && !description.is_empty() {
score += 0.1;
}
// Empty description
if description.is_empty() {
score += 0.05;
}
score.clamp(0.0, 1.0)
}
/// Calculate overall intent score
fn calculate_intent_score(&self, score: &VideoIntentScore) -> f32 {
// Weight relevance heavily, penalize commercial and spam
let base = score.relevance_score * 0.6;
let commercial_penalty = score.commercial_score * 0.2;
let spam_penalty = score.spam_score * 0.2;
let intent_score = base - commercial_penalty - spam_penalty + 0.3;
intent_score.clamp(0.0, 1.0)
}
/// Analyze quality signals
fn analyze_quality_signals(
&self,
title: &str,
description: &str,
channel: &str,
duration_secs: Option<u32>,
view_count: Option<u64>,
) -> VideoQualitySignals {
VideoQualitySignals {
has_description: description.len() > 100,
has_tags: description.contains('#') || description.to_lowercase().contains("tags:"),
authoritative_source: self.is_authoritative_source(channel, view_count),
appropriate_duration: self.is_appropriate_duration(title, duration_secs),
title_honest: self.is_title_honest(title),
has_chapters: description.contains("0:00")
|| description.to_lowercase().contains("chapters")
|| description.contains("timestamp"),
}
}
/// Check if source is authoritative
fn is_authoritative_source(&self, channel: &str, view_count: Option<u64>) -> bool {
// Known authoritative channels
let authoritative_channels = [
"freecodecamp",
"simplilearn",
"edureka",
"coursera",
"udemy",
"mit",
"stanford",
"harvard",
"nasa",
"national geographic",
"veritasium",
"3blue1brown",
"computerphile",
"fireship",
"google developers",
"microsoft developer",
"aws",
"azure",
];
let channel_lower = channel.to_lowercase();
if authoritative_channels
.iter()
.any(|c| channel_lower.contains(c))
{
return true;
}
// High view count indicates popularity
if let Some(views) = view_count {
if views > 100_000 {
return true;
}
}
false
}
/// Check if duration is appropriate for the content type
fn is_appropriate_duration(&self, title: &str, duration_secs: Option<u32>) -> bool {
let Some(duration) = duration_secs else {
return false;
};
let title_lower = title.to_lowercase();
// Tutorial should be longer
if title_lower.contains("tutorial")
|| title_lower.contains("course")
|| title_lower.contains("full")
{
return duration >= 300; // At least 5 minutes
}
// Quick tips should be shorter
if title_lower.contains("quick")
|| title_lower.contains("tips")
|| title_lower.contains("short")
{
return (60..=600).contains(&duration); // 1-10 minutes
}
// Default: reasonable video length
(60..=14400).contains(&duration) // 1 minute to 4 hours
}
/// Check if title appears honest (not clickbait)
fn is_title_honest(&self, title: &str) -> bool {
let title_lower = title.to_lowercase();
// Honest title indicators
let honest_patterns = [
"introduction to",
"getting started",
"basics of",
"how to",
"tutorial",
"guide to",
"explained",
"complete",
"comprehensive",
"step by step",
];
// Clickbait indicators
let clickbait_patterns = [
"you won't believe",
"shocking",
"secret",
"they don't want",
"one weird trick",
"miracle",
"instant",
"amazing",
];
let honest_count = honest_patterns
.iter()
.filter(|p| title_lower.contains(*p))
.count();
let clickbait_count = clickbait_patterns
.iter()
.filter(|p| title_lower.contains(*p))
.count();
honest_count > clickbait_count
}
/// Check if video passes quality gate
fn passes_quality_gate(&self, score: &VideoIntentScore) -> bool {
// Minimum thresholds
let min_intent = 0.3;
let min_relevance = 0.25;
let max_spam = 0.7;
score.intent_score >= min_intent
&& score.relevance_score >= min_relevance
&& score.spam_score <= max_spam
}
}
/// Jaro-Winkler similarity implementation
/// Returns a score between 0.0 and 1.0
/// Optimized for short strings (titles, terms)
fn jaro_winkler(s1: &str, s2: &str) -> f32 {
if s1.is_empty() && s2.is_empty() {
return 1.0;
}
if s1.is_empty() || s2.is_empty() {
return 0.0;
}
if s1 == s2 {
return 1.0;
}
let s1_chars: Vec<char> = s1.chars().collect();
let s2_chars: Vec<char> = s2.chars().collect();
let len1 = s1_chars.len();
let len2 = s2_chars.len();
if len1 == 0 || len2 == 0 {
return 0.0;
}
// Calculate match window
let match_distance = (len1.max(len2) / 2).saturating_sub(1);
// Find matches
let mut s1_matches = vec![false; len1];
let mut s2_matches = vec![false; len2];
let mut matches = 0;
for i in 0..len1 {
let start = i.saturating_sub(match_distance);
let end = (i + match_distance + 1).min(len2);
for j in start..end {
if s2_matches[j] || s1_chars[i] != s2_chars[j] {
continue;
}
s1_matches[i] = true;
s2_matches[j] = true;
matches += 1;
break;
}
}
if matches == 0 {
return 0.0;
}
// Calculate transpositions
let mut transpositions = 0;
let mut j = 0;
for i in 0..len1 {
if !s1_matches[i] {
continue;
}
while !s2_matches[j] {
j += 1;
}
if s1_chars[i] != s2_chars[j] {
transpositions += 1;
}
j += 1;
}
// Jaro score
let jaro = (matches as f32 / len1 as f32
+ matches as f32 / len2 as f32
+ (matches - transpositions / 2) as f32 / matches as f32)
/ 3.0;
// Winkler modification (boost for common prefix)
let prefix_len = s1_chars
.iter()
.zip(s2_chars.iter())
.take(4)
.take_while(|(a, b)| a == b)
.count();
let winkler = jaro + (prefix_len as f32 * 0.1 * (1.0 - jaro));
winkler.min(1.0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_jaro_winkler() {
assert!((jaro_winkler("tutorial", "tutorial") - 1.0).abs() < 0.01);
assert!(jaro_winkler("tutorial", "tutorials") > 0.9);
assert!(jaro_winkler("python", "pythn") > 0.8);
assert!(jaro_winkler("python", "java") < 0.5);
}
#[test]
fn test_detect_tutorial_intent() {
let scorer = VideoIntentScorer::new("python tutorial");
let intent = scorer.detect_intent(
"Python Tutorial for Beginners - Full Course",
"Learn Python programming from scratch in this complete tutorial.",
);
assert_eq!(intent, VideoIntent::Tutorial);
}
#[test]
fn test_detect_review_intent() {
let scorer = VideoIntentScorer::new("laptop review");
let intent = scorer.detect_intent(
"MacBook Pro M3 Review - Is it worth it?",
"Honest review of the new MacBook Pro with M3 chip. Pros and cons tested.",
);
assert_eq!(intent, VideoIntent::Review);
}
#[test]
fn test_relevance_scoring() {
let scorer = VideoIntentScorer::new("python programming");
let relevance = scorer.calculate_relevance(
"Python Programming Tutorial",
"Learn Python programming from basics",
);
assert!(relevance > 0.7);
}
#[test]
fn test_spam_detection() {
let scorer = VideoIntentScorer::new("make money");
let spam = scorer.calculate_spam("🔥 YOU WON'T BELIEVE THIS!!! 😱 Make $1000/day!!!", "");
assert!(spam > 0.5);
}
}