Spaces:
Build error
Build error
File size: 55,779 Bytes
0ca462b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 | //! 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
);
}
}
|