Spaces:
Build error
Build error
Download src/intent_classifier/mod.rs from LuckyMod/intentforge: direct link, hf CLI and curl.
- Browser
- Download file 55.8 kB
-
https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/src/intent_classifier/mod.rs
- Command line
-
hf download hf://spaces/LuckyMod/intentforge/src/intent_classifier/mod.rs
-
curl -L -o mod.rs https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/src/intent_classifier/mod.rs
55.8 kB
//! Intent Classification Module for IntentForge v2
//!
//! Comprehensive intent detection across 20+ categories for smart gap filling,
//! source routing, and domain-specific quality gating.
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::RwLock;
/// Query intent categories - comprehensive coverage beyond just cooking/tourism/programming
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[allow(clippy::upper_case_acronyms)]
pub enum QueryIntent {
// === Technology & Development ===
Programming, // "python async tutorial", "rust web framework"
DevOps, // "kubernetes deployment", "docker compose best practices"
WebDevelopment, // "react hooks tutorial", "css grid layout"
Database, // "postgresql query optimization", "mongodb indexing"
CloudComputing, // "aws lambda pricing", "azure vs gcp"
Cybersecurity, // "sql injection prevention", "zero trust architecture"
DataScience, // "machine learning algorithms", "pandas dataframe tutorial"
AIML, // "transformer architecture", "fine-tune LLM"
// === Lifestyle & Hobbies ===
Cooking, // "pasta recipe", "how to make curry"
Travel, // "paris attractions", "japan visa requirements"
Fitness, // "home workout routine", "protein intake calculator"
Gaming, // "best gaming laptop 2025", "elden ring boss guide"
Photography, // "camera settings for portraits", "lightroom presets"
Music, // "guitar chords for beginners", "music production software"
// === Shopping & Products ===
ProductReview, // "best laptop 2025", "iphone vs samsung"
ProductComparison, // "graphql vs rest", "react vs vue"
PriceComparison, // "cheapest flight to tokyo", "laptop price comparison"
// === News & Current Events ===
News, // "latest ai news", "tech startup funding"
Sports, // "nba scores today", "world cup schedule"
Finance, // "stock market today", "crypto price prediction"
// === Education & Learning ===
Academic, // "quantum computing paper", "machine learning research"
Tutorial, // "how to use git", "excel pivot table tutorial"
LanguageLearning, // "learn spanish app", "french grammar rules"
// === Health & Medical ===
Health, // "symptoms of flu", "vitamin d benefits"
Medical, // "diabetes treatment guidelines", "hypertension medication"
MentalHealth, // "anxiety coping strategies", "meditation techniques"
// === Business & Professional ===
Business, // "startup funding options", "business plan template"
Marketing, // "seo best practices 2025", "social media strategy"
Career, // "software engineer interview questions", "resume tips"
// === Home & Garden ===
HomeImprovement, // "kitchen renovation ideas", "diy bathroom remodel"
Gardening, // "vegetable garden planning", "indoor plants low light"
// === Automotive ===
Automotive, // "best electric cars 2025", "car maintenance schedule"
// === Real Estate ===
RealEstate, // "housing market trends 2025", "mortgage rates"
// === Legal & Government ===
Legal, // "copyright law explained", "llc vs corporation"
Government, // "tax filing deadline", "passport renewal"
// === General ===
HowTo, // "how to fix leaky faucet", "how to boil eggs"
Definition, // "what is blockchain", "define quantum entanglement"
General, // Everything else
}
impl QueryIntent {
/// Get a semantic description of the intent for embedding-based matching
pub fn description(&self) -> &'static str {
match self {
QueryIntent::Programming => "Software development, source code, programming languages, debugging, and software architecture.",
QueryIntent::DevOps => "Infrastructure as code, containerization, CI/CD pipelines, cloud orchestration, and systems engineering.",
QueryIntent::WebDevelopment => "Frontend and backend web technologies, HTML, CSS, JavaScript frameworks, and web design.",
QueryIntent::Database => "Data storage, SQL and NoSQL databases, query optimization, and data modeling.",
QueryIntent::CloudComputing => "Cloud platforms like AWS, Azure, and GCP, serverless computing, and distributed systems.",
QueryIntent::Cybersecurity => "Information security, encryption, penetration testing, threat detection, and privacy protection.",
QueryIntent::DataScience => "Data analysis, statistical modeling, big data processing, and data visualization.",
QueryIntent::AIML => "Artificial intelligence, machine learning, neural networks, LLMs, and natural language processing.",
QueryIntent::Cooking => "Food preparation, recipes, culinary techniques, baking, and meal planning.",
QueryIntent::Travel => "Tourism, destination guides, travel planning, flights, hotels, and cultural attractions.",
QueryIntent::Fitness => "Physical exercise, workout routines, strength training, cardio, and athletic performance.",
QueryIntent::Gaming => "Video games, gaming hardware, walkthroughs, esports, and game reviews.",
QueryIntent::Photography => "Digital and film photography, camera settings, lighting, and photo editing.",
QueryIntent::Music => "Musical instruments, music production, artist reviews, and music theory.",
QueryIntent::ProductReview => "Detailed evaluations, ratings, and expert opinions on consumer products.",
QueryIntent::ProductComparison => "Side-by-side comparisons of different products, services, or technologies.",
QueryIntent::PriceComparison => "Finding the best deals, discounts, and cost comparisons for items or services.",
QueryIntent::News => "Current events, breaking news, journalism, and recent global or local developments.",
QueryIntent::Sports => "Athletic competitions, team scores, player statistics, and sporting events.",
QueryIntent::Finance => "Personal finance, stock market, investing, cryptocurrency, and economic trends.",
QueryIntent::Academic => "Scholarly research, scientific papers, peer-reviewed journals, and higher education.",
QueryIntent::Tutorial => "Step-by-step educational instructions, learning guides, and beginner-friendly lessons.",
QueryIntent::LanguageLearning => "Learning new languages, grammar rules, vocabulary, and linguistic study.",
QueryIntent::Health => "General wellness, nutrition, lifestyle health, and preventive care.",
QueryIntent::Medical => "Clinical medicine, diseases, diagnoses, medications, and professional healthcare.",
QueryIntent::MentalHealth => "Psychology, emotional well-being, therapy, meditation, and mental health support.",
QueryIntent::Business => "Entrepreneurship, startup management, corporate strategy, and business operations.",
QueryIntent::Marketing => "Advertising, SEO, social media strategy, branding, and market research.",
QueryIntent::Career => "Job searching, professional development, resumes, and workplace advice.",
QueryIntent::HomeImprovement => "DIY home repairs, renovation projects, interior design, and home maintenance.",
QueryIntent::Gardening => "Plant care, landscape design, vegetable growing, and outdoor maintenance.",
QueryIntent::Automotive => "Vehicle maintenance, car reviews, automotive engineering, and transportation technology.",
QueryIntent::RealEstate => "Property buying and selling, housing market trends, mortgages, and rentals.",
QueryIntent::Legal => "Law, legal rights, regulations, contracts, and judicial processes.",
QueryIntent::Government => "Public policy, government services, civic information, and official documentation.",
QueryIntent::HowTo => "General instructions on how to perform a specific task or solve a problem.",
QueryIntent::Definition => "Explanations of what something is, terminology, and encyclopedic entries.",
QueryIntent::General => "Broad or uncategorized information not fitting other specific intents.",
}
}
/// Get all intent categories as a vector
pub fn all_categories() -> Vec<QueryIntent> {
vec![
// Technology
QueryIntent::Programming,
QueryIntent::DevOps,
QueryIntent::WebDevelopment,
QueryIntent::Database,
QueryIntent::CloudComputing,
QueryIntent::Cybersecurity,
QueryIntent::DataScience,
QueryIntent::AIML,
// Lifestyle
QueryIntent::Cooking,
QueryIntent::Travel,
QueryIntent::Fitness,
QueryIntent::Gaming,
QueryIntent::Photography,
QueryIntent::Music,
// Shopping
QueryIntent::ProductReview,
QueryIntent::ProductComparison,
QueryIntent::PriceComparison,
// News
QueryIntent::News,
QueryIntent::Sports,
QueryIntent::Finance,
// Education
QueryIntent::Academic,
QueryIntent::Tutorial,
QueryIntent::LanguageLearning,
// Health
QueryIntent::Health,
QueryIntent::Medical,
QueryIntent::MentalHealth,
// Business
QueryIntent::Business,
QueryIntent::Marketing,
QueryIntent::Career,
// Home
QueryIntent::HomeImprovement,
QueryIntent::Gardening,
// Automotive
QueryIntent::Automotive,
// Real Estate
QueryIntent::RealEstate,
// Legal
QueryIntent::Legal,
QueryIntent::Government,
// General
QueryIntent::HowTo,
QueryIntent::Definition,
QueryIntent::General,
]
}
/// Get intent group (for broader categorization)
pub fn get_group(&self) -> &'static str {
match self {
// Technology group
QueryIntent::Programming
| QueryIntent::DevOps
| QueryIntent::WebDevelopment
| QueryIntent::Database
| QueryIntent::CloudComputing
| QueryIntent::Cybersecurity
| QueryIntent::DataScience
| QueryIntent::AIML => "technology",
// Lifestyle group
QueryIntent::Cooking
| QueryIntent::Travel
| QueryIntent::Fitness
| QueryIntent::Gaming
| QueryIntent::Photography
| QueryIntent::Music => "lifestyle",
// Shopping group
QueryIntent::ProductReview
| QueryIntent::ProductComparison
| QueryIntent::PriceComparison => "shopping",
// News group
QueryIntent::News | QueryIntent::Sports | QueryIntent::Finance => "news",
// Education group
QueryIntent::Academic | QueryIntent::Tutorial | QueryIntent::LanguageLearning => {
"education"
}
// Health group
QueryIntent::Health | QueryIntent::Medical | QueryIntent::MentalHealth => "health",
// Business group
QueryIntent::Business | QueryIntent::Marketing | QueryIntent::Career => "business",
// Home group
QueryIntent::HomeImprovement | QueryIntent::Gardening => "home",
// Other groups
QueryIntent::Automotive => "automotive",
QueryIntent::RealEstate => "real_estate",
QueryIntent::Legal | QueryIntent::Government => "legal_government",
// General
QueryIntent::HowTo | QueryIntent::Definition | QueryIntent::General => "general",
}
}
}
/// Intent classifier with keyword patterns and domain boosts
pub struct IntentClassifier {
keyword_patterns: HashMap<QueryIntent, Vec<&'static str>>,
domain_patterns: HashMap<QueryIntent, Vec<&'static str>>,
howto_prefixes: Vec<&'static str>,
comparison_keywords: Vec<&'static str>,
intent_vectors: RwLock<HashMap<QueryIntent, Vec<f32>>>,
}
/// Score for an intent group
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupScore {
pub group: String,
pub score: f32,
pub primary_intent: QueryIntent,
pub description: String,
}
impl IntentClassifier {
/// Create a new intent classifier with comprehensive patterns
pub fn new() -> Self {
let mut keyword_patterns: HashMap<QueryIntent, Vec<&'static str>> = HashMap::new();
let mut domain_patterns: HashMap<QueryIntent, Vec<&'static str>> = HashMap::new();
// === Technology Patterns ===
// Programming
keyword_patterns.insert(
QueryIntent::Programming,
vec![
"tutorial",
"guide",
"how to code",
"programming",
"coding",
"function",
"class",
"object",
"variable",
"loop",
"recursion",
"debug",
"compile",
"runtime",
"syntax",
"algorithm",
"data structure",
"api",
"library",
"framework",
"package",
"rust",
"python",
"javascript",
"typescript",
"java",
"c++",
"go",
"react",
"vue",
"angular",
"django",
"flask",
"spring",
"async",
"await",
"futures",
"tokio",
"serde",
"cargo",
"abstraction",
"zero cost",
"memory safety",
"binary size",
"garbage collection",
"performance",
"low level",
"high level",
],
);
domain_patterns.insert(
QueryIntent::Programming,
vec![
"github.com",
"stackoverflow.com",
"dev.to",
"medium.com",
"rust-lang.org",
"python.org",
"nodejs.org",
"docs.rs",
],
);
// DevOps
keyword_patterns.insert(
QueryIntent::DevOps,
vec![
"kubernetes",
"k8s",
"docker",
"container",
"orchestration",
"ci/cd",
"pipeline",
"jenkins",
"gitlab",
"github actions",
"terraform",
"ansible",
"puppet",
"chef",
"deployment",
"infrastructure",
"devops",
"sre",
"helm",
"istio",
"prometheus",
"grafana",
],
);
// Web Development
keyword_patterns.insert(
QueryIntent::WebDevelopment,
vec![
"html",
"css",
"javascript",
"frontend",
"backend",
"responsive",
"web design",
"ui",
"ux",
"react",
"vue",
"angular",
"svelte",
"webpack",
"vite",
"npm",
"yarn",
"rest api",
"graphql",
"http",
"webhook",
],
);
// Database
keyword_patterns.insert(
QueryIntent::Database,
vec![
"sql",
"nosql",
"database",
"query",
"index",
"postgresql",
"mysql",
"mongodb",
"redis",
"elasticsearch",
"transaction",
"replication",
"sharding",
"normalization",
"orm",
"migration",
"schema",
],
);
// Cloud Computing
keyword_patterns.insert(
QueryIntent::CloudComputing,
vec![
"aws",
"azure",
"gcp",
"google cloud",
"cloud computing",
"ec2",
"lambda",
"s3",
"cloudfront",
"virtual machine",
"serverless",
"microservice",
"cloudformation",
"terraform",
],
);
// Cybersecurity
keyword_patterns.insert(
QueryIntent::Cybersecurity,
vec![
"security",
"encryption",
"authentication",
"authorization",
"firewall",
"vpn",
"malware",
"phishing",
"zero trust",
"zero cost",
"penetration testing",
"vulnerability",
"owasp",
"cve",
"exploit",
],
);
// Data Science
keyword_patterns.insert(
QueryIntent::DataScience,
vec![
"data science",
"analytics",
"visualization",
"pandas",
"numpy",
"scikit-learn",
"jupyter",
"statistical analysis",
"hypothesis testing",
"data cleaning",
"feature engineering",
],
);
// AI/ML
keyword_patterns.insert(
QueryIntent::AIML,
vec![
"machine learning",
"deep learning",
"neural network",
"transformer",
"llm",
"gpt",
"bert",
"training",
"inference",
"model",
"epoch",
"pytorch",
"tensorflow",
"keras",
"nlp",
"computer vision",
"reinforcement learning",
],
);
// === Lifestyle Patterns ===
// Cooking
keyword_patterns.insert(
QueryIntent::Cooking,
vec![
"recipe",
"cook",
"baking",
"ingredient",
"how to make",
"how to cook",
"preparation",
"dish",
"meal",
"cuisine",
"flavor",
"oven",
"stove",
"pan",
"pot",
"breakfast",
"lunch",
"dinner",
"dessert",
"vegetarian",
"vegan",
"gluten-free",
],
);
domain_patterns.insert(
QueryIntent::Cooking,
vec![
"allrecipes.com",
"foodnetwork.com",
"epicurious.com",
"bonappetit.com",
"seriouseats.com",
],
);
// Travel
keyword_patterns.insert(
QueryIntent::Travel,
vec![
"travel",
"tourist",
"attraction",
"visit",
"hotel",
"flight",
"booking",
"reservation",
"visa",
"passport",
"itinerary",
"beach",
"mountain",
"city tour",
"sightseeing",
"vacation",
"holiday",
"trip",
],
);
domain_patterns.insert(
QueryIntent::Travel,
vec![
"tripadvisor.com",
"booking.com",
"expedia.com",
"lonelyplanet.com",
"trip.com",
],
);
// Fitness
keyword_patterns.insert(
QueryIntent::Fitness,
vec![
"workout",
"exercise",
"gym",
"training",
"muscle",
"cardio",
"strength",
"flexibility",
"protein",
"nutrition",
"diet",
"calorie",
"running",
"cycling",
"yoga",
"pilates",
],
);
// Gaming
keyword_patterns.insert(
QueryIntent::Gaming,
vec![
"game",
"gaming",
"gamer",
"esports",
"walkthrough",
"guide",
"boss",
"level",
"pc gaming",
"console",
"playstation",
"xbox",
"nintendo",
"steam",
"epic games",
],
);
// === Shopping Patterns ===
// Product Review
keyword_patterns.insert(
QueryIntent::ProductReview,
vec![
"best",
"top",
"review",
"rating",
"recommend",
"worth it",
"buying guide",
"2025",
"2026",
"latest",
"new",
],
);
// Product Comparison
keyword_patterns.insert(
QueryIntent::ProductComparison,
vec![
"vs",
"versus",
"compared",
"comparison",
"better than",
"difference between",
"which one",
"choose between",
],
);
// === News Patterns ===
// News
keyword_patterns.insert(
QueryIntent::News,
vec![
"news",
"latest",
"breaking",
"update",
"announced",
"released",
"launched",
"today",
"this week",
"recent",
],
);
// Sports
keyword_patterns.insert(
QueryIntent::Sports,
vec![
"score",
"game",
"match",
"team",
"player",
"league",
"championship",
"nba",
"nfl",
"mlb",
"premier league",
],
);
// Finance
keyword_patterns.insert(
QueryIntent::Finance,
vec![
"stock",
"market",
"trading",
"investment",
"crypto",
"bitcoin",
"ethereum",
"price",
"forecast",
"prediction",
"portfolio",
"dividend",
],
);
// === Education Patterns ===
// Academic
keyword_patterns.insert(
QueryIntent::Academic,
vec![
"paper",
"research",
"study",
"journal",
"arxiv",
"pubmed",
"ieee",
"acm",
"citation",
"abstract",
"peer-reviewed",
"thesis",
"dissertation",
],
);
domain_patterns.insert(
QueryIntent::Academic,
vec!["arxiv.org", "pubmed.gov", "ieee.org", "scholar.google.com"],
);
// Tutorial
keyword_patterns.insert(
QueryIntent::Tutorial,
vec![
"tutorial",
"step by step",
"beginner",
"introduction",
"getting started",
"learn",
"course",
"lesson",
],
);
// === Health Patterns ===
// Health
keyword_patterns.insert(
QueryIntent::Health,
vec![
"health",
"wellness",
"symptom",
"treatment",
"vitamin",
"supplement",
"nutrition",
"exercise",
"sleep",
"stress",
],
);
// Medical
keyword_patterns.insert(
QueryIntent::Medical,
vec![
"disease",
"condition",
"diagnosis",
"medication",
"doctor",
"hospital",
"clinic",
"prescription",
"therapy",
"surgery",
],
);
// Mental Health
keyword_patterns.insert(
QueryIntent::MentalHealth,
vec![
"anxiety",
"depression",
"stress",
"mental health",
"therapy",
"counseling",
"meditation",
"mindfulness",
"self-care",
],
);
// === Business Patterns ===
// Business
keyword_patterns.insert(
QueryIntent::Business,
vec![
"business",
"startup",
"entrepreneur",
"funding",
"investment",
"venture capital",
"revenue",
"profit",
"growth",
],
);
// Marketing
keyword_patterns.insert(
QueryIntent::Marketing,
vec![
"marketing",
"seo",
"sem",
"social media",
"content marketing",
"email marketing",
"brand",
"advertising",
"campaign",
],
);
// Career
keyword_patterns.insert(
QueryIntent::Career,
vec![
"career",
"job",
"interview",
"resume",
"cv",
"salary",
"hiring",
"recruitment",
"promotion",
"career change",
],
);
// === Home Patterns ===
// Home Improvement
keyword_patterns.insert(
QueryIntent::HomeImprovement,
vec![
"renovation",
"remodel",
"diy",
"home improvement",
"kitchen",
"bathroom",
"basement",
"attic",
"painting",
"flooring",
"roofing",
],
);
// Gardening
keyword_patterns.insert(
QueryIntent::Gardening,
vec![
"garden",
"gardening",
"plant",
"flower",
"vegetable",
"herb",
"compost",
"pruning",
"watering",
"soil",
],
);
// === Automotive Patterns ===
keyword_patterns.insert(
QueryIntent::Automotive,
vec![
"car",
"auto",
"vehicle",
"automotive",
"engine",
"transmission",
"brake",
"maintenance",
"repair",
"oil change",
"electric car",
"ev",
"hybrid",
"tesla",
"ford",
"toyota",
"bmw",
],
);
// === Real Estate Patterns ===
keyword_patterns.insert(
QueryIntent::RealEstate,
vec![
"real estate",
"property",
"house",
"home",
"mortgage",
"loan",
"interest rate",
"buy",
"sell",
"rent",
"lease",
"market",
"price",
"value",
],
);
// === Legal Patterns ===
keyword_patterns.insert(
QueryIntent::Legal,
vec![
"legal",
"law",
"attorney",
"lawyer",
"court",
"case",
"lawsuit",
"contract",
"agreement",
"liability",
"copyright",
"trademark",
"patent",
],
);
// Government
keyword_patterns.insert(
QueryIntent::Government,
vec![
"government",
"tax",
"irs",
"filing",
"passport",
"visa",
"immigration",
"benefits",
"social security",
"election",
"vote",
],
);
// How-to prefixes
let howto_prefixes = vec![
"how to",
"how do i",
"how can i",
"what is the best way to",
"steps to",
];
// Comparison keywords
let comparison_keywords = vec![
"vs",
"versus",
"compared to",
"compared with",
"difference between",
"better than",
"worse than",
];
Self {
keyword_patterns,
domain_patterns,
howto_prefixes,
comparison_keywords,
intent_vectors: RwLock::new(HashMap::new()),
}
}
/// Set semantic vectors for each intent (calculated at startup)
pub fn set_intent_vectors(&self, vectors: HashMap<QueryIntent, Vec<f32>>) {
let mut lock = self.intent_vectors.write().unwrap();
*lock = vectors;
}
/// Classify a query into an intent category with group-weighted disambiguation
pub fn classify(&self, query: &str) -> QueryIntent {
let scores = self.classify_with_scores(query, None);
if let Some(best) = scores.first() {
return best.primary_intent.clone();
}
QueryIntent::General
}
/// Classify query and return sorted group scores
pub fn classify_with_scores(
&self,
query: &str,
query_embedding: Option<&[f32]>,
) -> Vec<GroupScore> {
let query_lower = query.to_lowercase();
let mut intent_scores: HashMap<QueryIntent, f32> = HashMap::new();
// 1. Calculate base scores for all intents
let intent_vectors_lock = self.intent_vectors.read().unwrap();
for intent in QueryIntent::all_categories() {
let mut score = self.calculate_intent_score(&query_lower, &intent);
// Add vector similarity if available
if let Some(emb) = query_embedding {
if let Some(intent_emb) = intent_vectors_lock.get(&intent) {
let mut sem_score = crate::utils::cosine_similarity(emb, intent_emb).max(0.0);
// Confidence Adjustment: If no keywords matched AND it's a single word,
// reduce the semantic score to avoid false-positive '1.0' collisions.
if score == 0.0 && !query_lower.contains(' ') {
sem_score *= 0.5;
}
// Use max to let either strong keywords or strong semantic match win
score = score.max(sem_score);
}
}
if score > 0.0 {
intent_scores.insert(intent, score);
}
}
// 2. Apply domain boosts
for (intent, domains) in &self.domain_patterns {
for domain in domains {
if query_lower.contains(domain) {
let score = intent_scores.entry(intent.clone()).or_insert(0.0);
*score += 0.5;
}
}
}
// 3. Handle specific prefixes (HowTo, etc.)
let is_howto = self
.howto_prefixes
.iter()
.any(|p| query_lower.starts_with(p));
if is_howto {
// HowTo queries are often ambiguous. If we have a specific signal
// (e.g. Cooking), we should favor that.
let specific_intents = [
QueryIntent::Programming,
QueryIntent::Cooking,
QueryIntent::HomeImprovement,
QueryIntent::Automotive,
QueryIntent::Photography,
QueryIntent::WebDevelopment,
];
let mut has_specific = false;
for intent in &specific_intents {
if let Some(score) = intent_scores.get_mut(intent) {
if *score > 0.1 {
*score += 0.4; // Boost specific intent
has_specific = true;
}
}
}
if !has_specific {
let howto_score = intent_scores.entry(QueryIntent::HowTo).or_insert(0.0);
*howto_score += 0.6; // Only strong boost for general HowTo if no specific intent
} else {
let howto_score = intent_scores.entry(QueryIntent::HowTo).or_insert(0.0);
*howto_score += 0.2; // Minor boost for HowTo if it's alongside a specific intent
}
}
let is_comparison = self
.comparison_keywords
.iter()
.any(|k| query_lower.contains(k));
if is_comparison {
let comp_score = intent_scores
.entry(QueryIntent::ProductComparison)
.or_insert(0.0);
*comp_score += 0.7; // Strong signal for Comparison
}
// 4. Aggregate by group and find primary intent per group
let mut group_map: HashMap<&'static str, (f32, QueryIntent)> = HashMap::new();
for (intent, score) in &intent_scores {
let group = intent.get_group();
let entry = group_map.entry(group).or_insert((0.0, intent.clone()));
// Add to total group score (with slight damping to prevent group-inflation
// from over-powering a very strong specific intent)
entry.0 += score * 0.8;
// Keep track of primary (highest scoring) intent in this group
// We compare original scores here to pick the best representative
let current_best_score = intent_scores.get(&entry.1).cloned().unwrap_or(0.0);
if *score > current_best_score {
entry.1 = intent.clone();
}
}
// 5. Convert to sorted vector of GroupScore
let mut results: Vec<GroupScore> = group_map
.into_iter()
.map(|(group, (group_score, primary_intent))| {
// The group score should be at least as high as its best intent
let best_intent_score = intent_scores.get(&primary_intent).cloned().unwrap_or(0.0);
let final_score = (group_score + best_intent_score * 0.5).min(1.0);
GroupScore {
group: group.to_string(),
score: final_score,
description: primary_intent.description().to_string(),
primary_intent,
}
})
.collect();
results.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap());
// Default if empty
if results.is_empty() {
results.push(GroupScore {
group: "general".to_string(),
score: 0.1,
primary_intent: QueryIntent::General,
description: QueryIntent::General.description().to_string(),
});
}
results
}
/// Dynamically determine the best intent for a given category string or document title.
pub fn get_intent_for_text(&self, text: &str) -> QueryIntent {
let text_lower = text.to_lowercase();
let mut best_intent = QueryIntent::General;
let mut best_score = 0.0;
for intent in QueryIntent::all_categories() {
let score = self.calculate_intent_score(&text_lower, &intent);
if score > best_score {
best_score = score;
best_intent = intent;
}
}
if best_score > 0.2 {
best_intent
} else {
QueryIntent::General
}
}
/// Calculate a dynamic alignment score between a query's intent and a document's category/title.
/// Uses vector similarity for a true Zero-Shot Contrastive Penalty.
pub fn calculate_alignment_boost(&self, query_intent: &QueryIntent, doc_text: &str) -> f32 {
if *query_intent == QueryIntent::General {
return 1.0;
}
let doc_intent = self.get_intent_for_text(doc_text);
if doc_intent == QueryIntent::General {
return 1.0; // Neutral for general content
}
if *query_intent == doc_intent {
return 1.2; // Exact match boost
}
// Calculate semantic distance using startup embeddings
let intent_vectors_lock = self.intent_vectors.read().unwrap();
if let (Some(q_emb), Some(d_emb)) = (
intent_vectors_lock.get(query_intent),
intent_vectors_lock.get(&doc_intent),
) {
let sim = crate::utils::cosine_similarity(q_emb, d_emb);
// Map similarity to boost/penalty:
// High similarity (>0.6) -> Neutral to slight boost (1.0 - 1.1)
// Medium similarity (0.3 - 0.6) -> Moderate penalty (0.6 - 0.9)
// Low similarity (<0.3) -> Severe contrastive penalty (0.1 - 0.5)
if sim > 0.6 {
return 1.0 + (sim - 0.6) * 0.25; // max 1.1
} else if sim > 0.3 {
return 0.6 + (sim - 0.3); // 0.6 to 0.9
} else {
return (sim * 1.6).max(0.1); // 0.1 to 0.48
}
}
// Fallback to group-level logic if vectors are missing
if query_intent.get_group() == doc_intent.get_group() {
1.1
} else {
0.5 // Default strict cross-domain penalty
}
}
/// Batch version of calculate_alignment_boost for multiple documents.
/// Classifies all documents first, then computes alignment scores in one pass.
pub fn calculate_alignment_boost_batch(
&self,
query_intent: &QueryIntent,
doc_texts: &[&str],
) -> Vec<f32> {
if *query_intent == QueryIntent::General {
return vec![1.0; doc_texts.len()];
}
// Pre-fetch query intent vector once
let query_emb = self
.intent_vectors
.read()
.unwrap()
.get(query_intent)
.cloned();
// Classify all documents
let doc_intents: Vec<QueryIntent> = doc_texts
.iter()
.map(|text| self.get_intent_for_text(text))
.collect();
// Compute alignment for each
let intent_vectors = self.intent_vectors.read().unwrap();
doc_intents
.iter()
.map(|doc_intent| {
if *doc_intent == QueryIntent::General {
return 1.0;
}
if *query_intent == *doc_intent {
return 1.2;
}
if let (Some(q_emb), Some(d_emb)) = (&query_emb, intent_vectors.get(doc_intent)) {
let sim = crate::utils::cosine_similarity(q_emb, d_emb);
if sim > 0.6 {
return 1.0 + (sim - 0.6) * 0.25;
} else if sim > 0.3 {
return 0.6 + (sim - 0.3);
} else {
return (sim * 1.6).max(0.1);
}
}
if query_intent.get_group() == doc_intent.get_group() {
1.1
} else {
0.5
}
})
.collect()
}
/// Check if query matches a specific intent
#[allow(dead_code)]
fn matches_intent(&self, query: &str, intent: &QueryIntent) -> bool {
self.calculate_intent_score(query, intent) > 0.3
}
/// Calculate intent score for a query
pub fn calculate_intent_score(&self, query: &str, intent: &QueryIntent) -> f32 {
let keywords = self.keyword_patterns.get(intent);
if keywords.is_none() {
return 0.0;
}
let keywords = keywords.unwrap();
let mut score = 0.0;
let mut match_count = 0;
for keyword in keywords {
if query.contains(keyword) {
match_count += 1;
// Weight by keyword specificity and match type
let weight = if keyword.len() > 10 { 0.4 } else { 0.2 };
// Extra weight for exact word matches (surrounded by non-alphanumeric)
let is_exact = query
.split(|c: char| !c.is_alphanumeric())
.any(|w| w == *keyword);
score += if is_exact { weight * 1.5 } else { weight };
}
}
// Clash Detection: Hard penalties for common cross-domain noise
let is_tech = matches!(
intent,
QueryIntent::Programming
| QueryIntent::DevOps
| QueryIntent::Cybersecurity
| QueryIntent::Database
);
if is_tech
&& (query.contains("recipe")
|| query.contains("cook")
|| query.contains("cake")
|| query.contains("bake"))
{
score -= 0.5;
}
// Normalize by number of keywords matched
if match_count > 0 {
score *= (match_count as f32).min(4.0) / 3.0;
}
score.clamp(0.0, 1.0)
}
/// Get recommended sources for an intent
pub fn get_recommended_sources(&self, intent: &QueryIntent) -> Vec<&'static str> {
match intent {
// Technology sources
QueryIntent::Programming => {
vec!["github", "stackoverflow", "dev.to", "medium", "arxiv"]
}
QueryIntent::DevOps => vec![
"github",
"stackoverflow",
"kubernetes.io",
"docker.com",
"aws",
],
QueryIntent::WebDevelopment => {
vec!["github", "stackoverflow", "mdn", "dev.to", "css-tricks"]
}
QueryIntent::Database => {
vec!["stackoverflow", "postgresql.org", "mongodb.com", "redis.io"]
}
QueryIntent::CloudComputing => vec![
"aws",
"azure",
"cloud.google.com",
"stackoverflow",
"github",
],
QueryIntent::Cybersecurity => {
vec!["owasp", "cve.mitre.org", "github", "stackoverflow", "arxiv"]
}
QueryIntent::DataScience => {
vec!["kaggle", "arxiv", "stackoverflow", "medium", "github"]
}
QueryIntent::AIML => vec![
"arxiv",
"github",
"huggingface",
"pytorch.org",
"tensorflow.org",
],
// Lifestyle sources
QueryIntent::Cooking => vec![
"allrecipes",
"foodnetwork",
"epicurious",
"seriouseats",
"bbc_good_food",
],
QueryIntent::Travel => vec!["tripadvisor", "booking.com", "lonelyplanet", "expedia"],
QueryIntent::Fitness => vec![
"bodybuilding.com",
"muscleandfitness",
"yogajournal",
"reddit_fitness",
],
QueryIntent::Gaming => vec!["ign", "gamespot", "steam", "polygon", "kotaku"],
QueryIntent::Photography => {
vec!["petapixel", "dpreview", "fstoppers", "youtube_photography"]
}
QueryIntent::Music => vec!["allmusic", "pitchfork", "rollingstone", "youtube_music"],
// Shopping sources
QueryIntent::ProductReview => {
vec!["consumer_reports", "cnet", "techradar", "reddit_reviews"]
}
QueryIntent::ProductComparison => {
vec!["versus.com", "diffen", "consumer_reports", "reddit"]
}
QueryIntent::PriceComparison => {
vec!["google_shopping", "camelcamelcamel", "pcpartpicker"]
}
// News sources
QueryIntent::News => vec!["google_news", "duckduckgo_news", "reddit_news", "twitter"],
QueryIntent::Sports => {
vec!["espn", "bleacher_report", "nba.com", "nfl.com", "bbc_sport"]
}
QueryIntent::Finance => {
vec!["bloomberg", "reuters", "cnbc", "yahoo_finance", "coindesk"]
}
// Education sources
QueryIntent::Academic => vec!["arxiv", "google_scholar", "pubmed", "ieee", "acm"],
QueryIntent::Tutorial => vec!["youtube", "udemy", "coursera", "freecodecamp", "dev.to"],
QueryIntent::LanguageLearning => {
vec!["duolingo", "babbel", "reddit_language", "youtube_language"]
}
// Health sources
QueryIntent::Health => vec!["webmd", "healthline", "mayo_clinic", "nih"],
QueryIntent::Medical => vec!["pubmed", "mayo_clinic", "cdc", "who", "medlineplus"],
QueryIntent::MentalHealth => vec!["psychology_today", "nimh", "headspace", "calm"],
// Business sources
QueryIntent::Business => vec!["forbes", "entrepreneur", "inc", "bloomberg", "wsj"],
QueryIntent::Marketing => vec!["hubspot", "moz", "searchengineland", "marketingland"],
QueryIntent::Career => vec!["linkedin", "indeed", "glassdoor", "reddit_career"],
// Home sources
QueryIntent::HomeImprovement => {
vec!["hgtv", "this_old_house", "bob_vila", "reddit_diy"]
}
QueryIntent::Gardening => vec![
"gardening_know_how",
"bhg",
"reddit_gardening",
"youtube_gardening",
],
// Automotive sources
QueryIntent::Automotive => {
vec!["car_and_driver", "motortrend", "edmunds", "reddit_cars"]
}
// Real Estate sources
QueryIntent::RealEstate => vec!["zillow", "realtor.com", "redfin", "biggerpockets"],
// Legal sources
QueryIntent::Legal => vec!["findlaw", "nolo", "justia", "cornell_law"],
QueryIntent::Government => vec!["usa.gov", "irs.gov", "travel.state.gov", "ssa.gov"],
// General sources
QueryIntent::HowTo => vec!["wikihow", "youtube", "instructables", "reddit_howto"],
QueryIntent::Definition => {
vec!["britannica", "dictionary.com", "wolfram_alpha"]
}
QueryIntent::General => vec!["google", "bing", "duckduckgo", "brave"],
}
}
/// Get quality thresholds for an intent
pub fn get_quality_thresholds(&self, intent: &QueryIntent) -> (f32, f32) {
match intent {
// Lower thresholds for academic/technical content
QueryIntent::Academic | QueryIntent::AIML | QueryIntent::DataScience => (0.15, 0.30),
QueryIntent::Programming | QueryIntent::DevOps | QueryIntent::Database => (0.20, 0.35),
// Relaxed thresholds for lifestyle content
QueryIntent::Cooking | QueryIntent::Travel | QueryIntent::Fitness => (0.30, 0.50),
// Medium thresholds for most categories
QueryIntent::Health | QueryIntent::Medical | QueryIntent::MentalHealth => (0.25, 0.45),
QueryIntent::Business | QueryIntent::Marketing | QueryIntent::Career => (0.25, 0.40),
// Lower for news (time-sensitive)
QueryIntent::News | QueryIntent::Sports | QueryIntent::Finance => (0.20, 0.35),
// Default
_ => (0.25, 0.45),
}
}
/// Generate query variations based on intent
pub fn generate_variations(&self, query: &str, intent: &QueryIntent) -> Vec<String> {
let mut variations = Vec::new();
// Always include original
variations.push(query.to_string());
match intent {
QueryIntent::Programming | QueryIntent::DevOps | QueryIntent::WebDevelopment => {
variations.push(format!("{} tutorial", query));
variations.push(format!("{} best practices", query));
variations.push(format!("{} github", query));
variations.push(format!("{} stackoverflow", query));
variations.push(format!("{} 2025", query));
}
QueryIntent::Cooking => {
variations.push(format!("{} recipe", query));
variations.push(format!("how to cook {}", query));
variations.push(format!("{} ingredients", query));
variations.push(format!("{} step by step", query));
variations.push(format!("easy {}", query));
}
QueryIntent::Travel => {
variations.push(format!("{} travel guide", query));
variations.push(format!("best time to visit {}", query));
variations.push(format!("{} attractions", query));
variations.push(format!("{} itinerary", query));
variations.push(format!("{} hotels", query));
}
QueryIntent::Academic | QueryIntent::AIML | QueryIntent::DataScience => {
variations.push(format!("{} paper", query));
variations.push(format!("{} research", query));
variations.push(format!("{} arxiv", query));
variations.push(format!("{} survey", query));
variations.push(format!("{} 2025", query));
}
QueryIntent::ProductReview | QueryIntent::ProductComparison => {
variations.push(format!("best {}", query));
variations.push(format!("{} review", query));
variations.push(format!("{} buying guide", query));
variations.push(format!("{} 2025", query));
variations.push(format!("{} reddit", query));
}
QueryIntent::Health | QueryIntent::Medical => {
variations.push(format!("{} symptoms", query));
variations.push(format!("{} treatment", query));
variations.push(format!("{} mayo clinic", query));
variations.push(format!("{} webmd", query));
}
QueryIntent::Tutorial | QueryIntent::HowTo => {
variations.push(format!("{} step by step", query));
variations.push(format!("{} for beginners", query));
variations.push(format!("{} guide", query));
variations.push(format!("how to {}", query));
}
_ => {
// Default variations
variations.push(format!("{} guide", query));
variations.push(format!("how to {}", query));
variations.push(format!("{} 2025", query));
variations.push(format!("{} best", query));
}
}
variations
}
}
impl Default for IntentClassifier {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_programming_intent() {
let classifier = IntentClassifier::new();
assert_eq!(
classifier.classify("rust async tutorial"),
QueryIntent::Programming
);
assert_eq!(
classifier.classify("python web framework comparison"),
QueryIntent::Programming
);
}
#[test]
fn test_cooking_intent() {
let classifier = IntentClassifier::new();
assert_eq!(
classifier.classify("pasta recipe easy"),
QueryIntent::Cooking
);
assert_eq!(
classifier.classify("how to make curry"),
QueryIntent::Cooking
);
}
#[test]
fn test_travel_intent() {
let classifier = IntentClassifier::new();
assert_eq!(
classifier.classify("paris tourist attractions"),
QueryIntent::Travel
);
assert_eq!(
classifier.classify("japan visa requirements"),
QueryIntent::Travel
);
}
#[test]
fn test_academic_intent() {
let classifier = IntentClassifier::new();
assert_eq!(
classifier.classify("machine learning paper arxiv"),
QueryIntent::Academic
);
}
#[test]
fn test_comparison_intent() {
let classifier = IntentClassifier::new();
assert_eq!(
classifier.classify("graphql vs rest"),
QueryIntent::ProductComparison
);
}
#[test]
fn test_howto_intent() {
let classifier = IntentClassifier::new();
assert_eq!(
classifier.classify("how to fix leaky faucet"),
QueryIntent::HowTo
);
}
#[test]
fn test_domain_boost() {
let classifier = IntentClassifier::new();
// Domain should boost intent
assert_eq!(
classifier.classify("tutorial github.com"),
QueryIntent::Programming
);
assert_eq!(
classifier.classify("recipe allrecipes.com"),
QueryIntent::Cooking
);
}
}
//! Intent Classification Module for IntentForge v2
//!
//! Comprehensive intent detection across 20+ categories for smart gap filling,
//! source routing, and domain-specific quality gating.
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::RwLock;
/// Query intent categories - comprehensive coverage beyond just cooking/tourism/programming
pub enum QueryIntent {
// === Technology & Development ===
Programming, // "python async tutorial", "rust web framework"
DevOps, // "kubernetes deployment", "docker compose best practices"
WebDevelopment, // "react hooks tutorial", "css grid layout"
Database, // "postgresql query optimization", "mongodb indexing"
CloudComputing, // "aws lambda pricing", "azure vs gcp"
Cybersecurity, // "sql injection prevention", "zero trust architecture"
DataScience, // "machine learning algorithms", "pandas dataframe tutorial"
AIML, // "transformer architecture", "fine-tune LLM"
// === Lifestyle & Hobbies ===
Cooking, // "pasta recipe", "how to make curry"
Travel, // "paris attractions", "japan visa requirements"
Fitness, // "home workout routine", "protein intake calculator"
Gaming, // "best gaming laptop 2025", "elden ring boss guide"
Photography, // "camera settings for portraits", "lightroom presets"
Music, // "guitar chords for beginners", "music production software"
// === Shopping & Products ===
ProductReview, // "best laptop 2025", "iphone vs samsung"
ProductComparison, // "graphql vs rest", "react vs vue"
PriceComparison, // "cheapest flight to tokyo", "laptop price comparison"
// === News & Current Events ===
News, // "latest ai news", "tech startup funding"
Sports, // "nba scores today", "world cup schedule"
Finance, // "stock market today", "crypto price prediction"
// === Education & Learning ===
Academic, // "quantum computing paper", "machine learning research"
Tutorial, // "how to use git", "excel pivot table tutorial"
LanguageLearning, // "learn spanish app", "french grammar rules"
// === Health & Medical ===
Health, // "symptoms of flu", "vitamin d benefits"
Medical, // "diabetes treatment guidelines", "hypertension medication"
MentalHealth, // "anxiety coping strategies", "meditation techniques"
// === Business & Professional ===
Business, // "startup funding options", "business plan template"
Marketing, // "seo best practices 2025", "social media strategy"
Career, // "software engineer interview questions", "resume tips"
// === Home & Garden ===
HomeImprovement, // "kitchen renovation ideas", "diy bathroom remodel"
Gardening, // "vegetable garden planning", "indoor plants low light"
// === Automotive ===
Automotive, // "best electric cars 2025", "car maintenance schedule"
// === Real Estate ===
RealEstate, // "housing market trends 2025", "mortgage rates"
// === Legal & Government ===
Legal, // "copyright law explained", "llc vs corporation"
Government, // "tax filing deadline", "passport renewal"
// === General ===
HowTo, // "how to fix leaky faucet", "how to boil eggs"
Definition, // "what is blockchain", "define quantum entanglement"
General, // Everything else
}
impl QueryIntent {
/// Get a semantic description of the intent for embedding-based matching
pub fn description(&self) -> &'static str {
match self {
QueryIntent::Programming => "Software development, source code, programming languages, debugging, and software architecture.",
QueryIntent::DevOps => "Infrastructure as code, containerization, CI/CD pipelines, cloud orchestration, and systems engineering.",
QueryIntent::WebDevelopment => "Frontend and backend web technologies, HTML, CSS, JavaScript frameworks, and web design.",
QueryIntent::Database => "Data storage, SQL and NoSQL databases, query optimization, and data modeling.",
QueryIntent::CloudComputing => "Cloud platforms like AWS, Azure, and GCP, serverless computing, and distributed systems.",
QueryIntent::Cybersecurity => "Information security, encryption, penetration testing, threat detection, and privacy protection.",
QueryIntent::DataScience => "Data analysis, statistical modeling, big data processing, and data visualization.",
QueryIntent::AIML => "Artificial intelligence, machine learning, neural networks, LLMs, and natural language processing.",
QueryIntent::Cooking => "Food preparation, recipes, culinary techniques, baking, and meal planning.",
QueryIntent::Travel => "Tourism, destination guides, travel planning, flights, hotels, and cultural attractions.",
QueryIntent::Fitness => "Physical exercise, workout routines, strength training, cardio, and athletic performance.",
QueryIntent::Gaming => "Video games, gaming hardware, walkthroughs, esports, and game reviews.",
QueryIntent::Photography => "Digital and film photography, camera settings, lighting, and photo editing.",
QueryIntent::Music => "Musical instruments, music production, artist reviews, and music theory.",
QueryIntent::ProductReview => "Detailed evaluations, ratings, and expert opinions on consumer products.",
QueryIntent::ProductComparison => "Side-by-side comparisons of different products, services, or technologies.",
QueryIntent::PriceComparison => "Finding the best deals, discounts, and cost comparisons for items or services.",
QueryIntent::News => "Current events, breaking news, journalism, and recent global or local developments.",
QueryIntent::Sports => "Athletic competitions, team scores, player statistics, and sporting events.",
QueryIntent::Finance => "Personal finance, stock market, investing, cryptocurrency, and economic trends.",