Spaces:
Build error
Build error
File size: 59,345 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 | //! IntentForge v2 - Intent-First Discovery Engine
//!
//! A high-performance, resource-efficient discovery engine that identifies
//! and ranks content based on user intent signals with sub-50ms queries.
mod anti_detection;
mod anti_detection_client;
mod api;
mod cloudflare_bypass;
mod common_crawl;
mod config;
mod crawler;
mod discovery;
mod domain_manager;
mod image_indexer;
mod image_search;
mod indexer;
mod inference;
mod intent_classifier;
mod meta_search;
mod metrics;
mod query_expansion;
mod redis_store;
mod self_improvement;
mod sources;
mod trending;
mod utils;
mod video_discovery;
use anyhow::{Context, Result};
use reqwest::header::HeaderMap;
use std::net::SocketAddr;
use std::sync::Arc;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
use api::ApiState;
use config::Config;
use crawler::Crawler;
use discovery::DiscoveryService;
use indexer::Indexer;
use inference::EmbeddingModel;
use metrics::Metrics;
use redis_store::RedisStore;
use self_improvement::SelfImprovementService;
use trending::{SourcesConfig, TrendingMonitor};
use crate::discovery::enhanced::CommonCrawlDiscovery;
use crate::domain_manager::DomainManager;
use crate::image_search::ImageSearchService;
use crate::intent_classifier::{IntentClassifier, QueryIntent};
use crate::meta_search::MetaSearchAggregator;
use crate::query_expansion::QueryExpansionConfig;
use crate::video_discovery::VideoDiscoveryService;
use std::collections::HashMap;
/// Application state
pub struct AppState {
pub config: Config,
pub crawler: Crawler,
pub indexer: Indexer,
pub redis: Arc<RedisStore>,
pub trending: Arc<TrendingMonitor>,
pub discovery: Arc<DiscoveryService>,
pub metrics: Metrics,
pub embedding_model: EmbeddingModel,
pub self_improvement: Arc<SelfImprovementService>,
pub aggregator: Arc<MetaSearchAggregator>,
pub cc_discovery: Arc<CommonCrawlDiscovery>,
pub query_expansion_config: QueryExpansionConfig,
pub video_discovery: Arc<VideoDiscoveryService>,
pub image_search: Arc<ImageSearchService>,
pub intent_classifier: Arc<IntentClassifier>,
pub domain_manager: Arc<DomainManager>,
/// Queue for zero-result search queries that need background indexing
zero_result_queue: Arc<tokio::sync::Mutex<Vec<String>>>,
}
impl AppState {
/// Initialize application state from configuration
pub async fn from_config(config: Config) -> Result<Self> {
tracing::info!("AppState::from_config - starting");
// ... rest of initialization ...
// Initialize crawler with Trafilatura integration
let trafilatura_url = if config.extraction.trafilatura_url.is_empty() {
None
} else {
Some(config.extraction.trafilatura_url.as_str())
};
let crawler = Crawler::new(
config.crawler.rate_limit,
config.crawler.timeout_secs,
config.crawler.user_agent.clone(),
config.crawler.respect_robots,
config.crawler.static_first,
config.crawler.max_concurrent,
config.crawler.max_retries,
config.crawler.robots_cache_ttl_secs,
config.crawler.js_whitelist.clone(),
trafilatura_url,
config.extraction.batch_size,
config.extraction.timeout_secs,
)?;
tracing::info!("AppState::from_config - crawler created");
// Initialize Redis store
let redis = Arc::new(RedisStore::new(&config.redis.url)?);
redis.ensure_bloom_filters().await?;
tracing::info!("AppState::from_config - redis created and bloom filters ensured");
// Initialize indexer
let indexer = Indexer::new(
&config.qdrant.url,
config.qdrant.api_key.as_deref(),
&config.qdrant.collection_name,
)?
.with_redis(redis.clone());
indexer.ensure_settings().await?;
tracing::info!("AppState::from_config - indexer created and settings ensured in Qdrant");
// Initialize trending monitor
let sources = SourcesConfig::from_file("sources.yaml").unwrap_or_else(|_| SourcesConfig {
sources: Vec::new(),
domains: Vec::new(),
seed_urls: Vec::new(),
});
let sources = Arc::new(sources);
let trending = Arc::new(TrendingMonitor::new(sources.sources.clone())?);
tracing::info!("AppState::from_config - trending created");
// Initialize ONNX embedding model
let embedding_model = EmbeddingModel::new(
&config.inference.model_path,
config.inference.embedding_dim,
config.inference.max_seq_length,
config.inference.inference_batch_size,
config.inference.fast_intent_threshold,
)?;
tracing::info!("AppState::from_config - embedding model created");
// Initialize discovery service
let config_arc = Arc::new(config.clone());
let discovery = Arc::new(
DiscoveryService::new(
config_arc,
sources.clone(),
embedding_model.fast_scorer.clone(),
)
.await?,
);
tracing::info!("AppState::from_config - discovery created");
// Initialize self-improvement service
let self_improvement =
Arc::new(SelfImprovementService::new(config.self_improvement.enabled));
self_improvement
.init(
redis.clone(),
crawler.clone(),
indexer.clone(),
Arc::new(embedding_model.clone()),
config.self_improvement.min_gap_score,
config.self_improvement.max_results_per_query,
config.self_improvement.process_interval_secs,
config.self_improvement.min_urls_per_gap,
config.self_improvement.min_intent_score,
config.self_improvement.min_relevance_score,
config.self_improvement.max_search_rounds,
config.self_improvement.max_parallel_gaps,
)
.await?;
tracing::info!("AppState::from_config - self_improvement created");
// Initialize meta-search aggregator
let proxy_manager = Arc::new(crate::meta_search::proxy_manager::ProxyManager::new());
// Start proxy scraping in background
let pm_clone = proxy_manager.clone();
tokio::spawn(async move {
if let Err(e) = pm_clone.scrape_proxies().await {
tracing::warn!("Failed to scrape initial proxies: {}", e);
}
// Periodic re-scrape
loop {
tokio::time::sleep(tokio::time::Duration::from_secs(3600)).await;
let _ = pm_clone.scrape_proxies().await;
}
});
// Initialize Tor manager (primary transport for search providers)
let tor_manager = match crate::meta_search::tor::TorManager::new().await {
Ok(tm) => {
if tm.is_available() {
tracing::info!(
"Tor transport available - all search queries will route through Tor"
);
} else {
tracing::warn!("Tor not available - falling back to public proxies");
}
Some(Arc::new(tm))
}
Err(e) => {
tracing::warn!("Tor manager failed to initialize: {}", e);
None
}
};
let whoogle_url = if config.whoogle_url.is_empty() {
None
} else {
Some(config.whoogle_url.as_str())
};
let librex_url = if config.librex_url.is_empty() {
None
} else {
Some(config.librex_url.as_str())
};
let searxng_url = if config.searxng_url.is_empty() {
None
} else {
Some(config.searxng_url.as_str())
};
let aggregator = Arc::new(MetaSearchAggregator::new(
proxy_manager,
tor_manager,
whoogle_url,
librex_url,
searxng_url,
));
tracing::info!("AppState::from_config - aggregator created");
// Initialize Common Crawl discovery
let cc_discovery = Arc::new(CommonCrawlDiscovery::new()?);
tracing::info!("AppState::from_config - cc_discovery created");
// Initialize Video Discovery Service
let mut video_headers = HeaderMap::new();
video_headers.insert("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7".parse().unwrap());
video_headers.insert("Accept-Language", "en-US,en;q=0.9".parse().unwrap());
video_headers.insert(
"Sec-Ch-Ua",
"\"Not A(Brand\";v=\"99\", \"Google Chrome\";v=\"121\", \"Chromium\";v=\"121\""
.parse()
.unwrap(),
);
video_headers.insert("Sec-Ch-Ua-Mobile", "?0".parse().unwrap());
video_headers.insert("Sec-Ch-Ua-Platform", "\"Windows\"".parse().unwrap());
let video_client = reqwest::Client::builder()
.user_agent(&config.crawler.user_agent)
.default_headers(video_headers)
.timeout(std::time::Duration::from_secs(5))
.build()
.with_context(|| "Failed to create VideoDiscoveryService HTTP client")?;
let mut video_discovery_config =
crate::video_discovery::VideoDiscoveryConfig::from_app_config(&config.video_discovery);
// Final safety check: ensure env vars are applied if they exist
if let Ok(yt_key) = std::env::var("YOUTUBE_API_KEY") {
if !yt_key.is_empty() {
tracing::info!("Applying YouTube API Key from environment");
video_discovery_config.youtube_api_key = yt_key;
}
}
if let Ok(rapid_key) = std::env::var("RAPIDAPI_KEY") {
if !rapid_key.is_empty() {
tracing::info!("Applying RapidAPI Key from environment");
video_discovery_config.rapidapi_key = rapid_key;
}
}
let video_discovery = Arc::new(VideoDiscoveryService::new(
video_client,
video_discovery_config,
));
tracing::info!("AppState::from_config - video_discovery created");
// Initialize Image Search Service
let image_search_config =
crate::image_search::ImageSearchConfig::from_app_config(&config.image_search);
let image_client = reqwest::Client::builder()
.user_agent(&config.crawler.user_agent)
.timeout(std::time::Duration::from_secs(8))
.build()
.with_context(|| "Failed to create ImageSearchService HTTP client")?;
let image_search = Arc::new(ImageSearchService::new(image_client, image_search_config));
tracing::info!("AppState::from_config - image_search created");
let query_expansion_config = QueryExpansionConfig::default();
let zero_result_queue = Arc::new(tokio::sync::Mutex::new(Vec::new()));
let metrics = Metrics::new();
// Initialize intent classifier
let intent_classifier = Arc::new(IntentClassifier::new());
// Generate intent embeddings for semantic mapping
tracing::info!("AppState::from_config - generating intent embeddings");
let mut intent_vectors = HashMap::new();
let categories = QueryIntent::all_categories();
for category in categories {
let desc = category.description().to_string();
let emb = match embedding_model.embed_batch(std::slice::from_ref(&desc)) {
Ok(embs) => embs.into_iter().next(),
Err(_) => embedding_model
.embed_fallback(std::slice::from_ref(&desc))
.into_iter()
.next(),
};
if let Some(e) = emb {
intent_vectors.insert(category, e);
}
}
intent_classifier.set_intent_vectors(intent_vectors);
tracing::info!("AppState::from_config - intent_classifier created and vectorized");
// Initialize domain manager
let domain_manager = Arc::new(DomainManager::new(redis.clone()));
domain_manager.init_from_config(&sources).await?;
tracing::info!("AppState::from_config - domain_manager created");
Ok(Self {
config,
crawler,
indexer,
redis,
trending,
discovery,
metrics,
embedding_model,
self_improvement,
aggregator,
cc_discovery,
query_expansion_config,
video_discovery,
image_search,
intent_classifier,
domain_manager,
zero_result_queue,
})
}
/// Queue a query that returned zero results for background indexing
pub async fn queue_zero_result_search(&self, query: &str) -> Result<()> {
// Add to in-memory queue
{
let mut queue = self.zero_result_queue.lock().await;
// Deduplicate: don't add if already queued
if !queue.contains(&query.to_string()) {
queue.push(query.to_string());
}
}
Ok(())
}
/// Process queued zero-result queries in background using parallel tasks.
///
/// Each query is processed in its own tokio task with multi-round search
/// and quality-gated completion. Tasks run concurrently up to the configured
/// max_parallel_gaps limit.
pub async fn process_zero_result_queue(&self) -> Result<usize> {
use crate::indexer::IntentDocument;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
// Get queries from queue
let queries = {
let mut queue = self.zero_result_queue.lock().await;
std::mem::take(&mut *queue)
};
if queries.is_empty() {
return Ok(0);
}
tracing::info!(
"Processing {} zero-result queries in parallel",
queries.len()
);
let max_parallel = self.config.self_improvement.max_parallel_gaps;
let min_urls_per_gap = 15; // User requirement: 15 results
let min_intent_score = 0.35; // Relaxed intent gate for broader content acceptance
let max_search_rounds = self.config.self_improvement.max_search_rounds;
let max_results_per_query = self.config.self_improvement.max_results_per_query;
// Generate query variations for multi-round search
let make_variations = |query: &str| -> Vec<String> {
vec![
query.to_string(),
format!("{} guide", query),
format!("how to {}", query),
format!("{} documentation", query),
format!("{} deep dive", query),
]
};
let semaphore = Arc::new(tokio::sync::Semaphore::new(max_parallel));
let mut handles = Vec::with_capacity(queries.len());
for query in queries {
let permit = semaphore.clone().acquire_owned().await?;
let aggregator = self.aggregator.clone();
let crawler = self.crawler.clone();
let indexer = self.indexer.clone();
let embedding_model = self.embedding_model.clone();
let intent_classifier = self.intent_classifier.clone();
let handle = tokio::spawn(async move {
let _permit = permit;
tracing::info!("Zero-result task started for '{}'", query);
let query_embedding =
match embedding_model.embed_batch(std::slice::from_ref(&query)) {
Ok(embs) => embs.into_iter().next().unwrap_or_default(),
Err(_) => embedding_model
.embed_fallback(std::slice::from_ref(&query))
.into_iter()
.next()
.unwrap_or_default(),
};
// Classify query intent for verification
let query_intent_scores =
intent_classifier.classify_with_scores(&query, Some(&query_embedding));
let primary_group = query_intent_scores
.first()
.map(|s| s.group.clone())
.unwrap_or_default();
let variations = make_variations(&query);
let mut seen_urls: std::collections::HashSet<String> =
std::collections::HashSet::new();
let mut quality_count: usize = 0;
let mut total_indexed: usize = 0;
for round in 0..max_search_rounds {
if quality_count >= min_urls_per_gap {
break;
}
let search_query = &variations[round % variations.len()];
let external_results = match aggregator.search_results(search_query).await {
Ok(results) => results,
Err(e) => {
tracing::warn!(
"Meta-search failed round {} for '{}': {}",
round + 1,
query,
e
);
continue;
}
};
if external_results.is_empty() {
continue;
}
// Filter unseen URLs
let new_results: Vec<&crate::meta_search::SearchResult> = external_results
.iter()
.filter(|r| seen_urls.insert(r.url.clone()))
.take(max_results_per_query)
.collect();
if new_results.is_empty() {
continue;
}
let urls: Vec<&str> = new_results.iter().map(|r| r.url.as_str()).collect();
let crawl_results = match crawler.fetch_batch(urls).await {
Ok(results) => results,
Err(e) => {
tracing::warn!(
"Crawl failed round {} for '{}': {}",
round + 1,
query,
e
);
continue;
}
};
for (idx, crawl_result) in crawl_results.iter().enumerate() {
let ext_result = new_results.get(idx);
let source = ext_result.map(|r| r.source.as_str()).unwrap_or("external");
let rrf_score = ext_result.map(|r| r.score).unwrap_or(0.0);
let media_type = ext_result
.map(|r| r.media_type.clone())
.unwrap_or_else(|| "text".to_string());
let thumbnail_url = ext_result.and_then(|r| r.thumbnail_url.clone());
let text = format!("{} {}", crawl_result.title, crawl_result.content);
let embedding =
match embedding_model.embed_batch(std::slice::from_ref(&text)) {
Ok(embs) => embs.into_iter().next().unwrap_or_default(),
Err(_) => embedding_model
.embed_fallback(std::slice::from_ref(&text))
.into_iter()
.next()
.unwrap_or_default(),
};
let intent_score =
crate::utils::cosine_similarity(&query_embedding, &embedding)
.clamp(0.0, 1.0);
let quality_score =
embedding_model.calculate_quality_score(&text, &crawl_result.url);
// Verification Step: Does this document match the intent group of the query?
let doc_intent_scores =
intent_classifier.classify_with_scores(&crawl_result.title, None);
let doc_group = doc_intent_scores
.first()
.map(|s| s.group.clone())
.unwrap_or_default();
let group_match_boost =
if !primary_group.is_empty() && primary_group == doc_group {
0.2 // Significant boost for matching intent group
} else {
0.0
};
let relevance_score = (intent_score * 0.4
+ quality_score * 0.3
+ rrf_score.min(0.1)
+ group_match_boost)
.clamp(0.1, 1.0);
let mut hasher = DefaultHasher::new();
crawl_result.url.hash(&mut hasher);
let safe_id = format!("ext-{:x}", hasher.finish());
// 1. Store full content in Redis (compressed)
if let Err(e) = indexer
.get_redis()
.store_content(&safe_id, &crawl_result.content)
.await
{
tracing::warn!(
"Failed to store full content in Redis for {}: {}",
safe_id,
e
);
}
let content_snippet: String =
crawl_result.content.chars().take(500).collect();
let doc_text_for_intent =
format!("{} {}", crawl_result.title, content_snippet);
let dynamic_category = format!(
"{:?}",
intent_classifier.get_intent_for_text(&doc_text_for_intent)
);
let mut doc = IntentDocument::new(
safe_id,
crawl_result.title.clone(),
crawl_result.content.clone(),
crawl_result.url.clone(),
source.to_string(),
dynamic_category,
intent_score,
relevance_score,
embedding,
)
.with_extra_scores(0.0, 0.0);
if intent_score < 0.8 {
doc = doc.with_snippet(300);
}
doc.media_type = media_type;
doc.thumbnail_url = thumbnail_url;
// Only index if it meets a basic quality threshold for intent or group match
if intent_score >= 0.25 || group_match_boost > 0.0 {
if let Err(e) = indexer.index_document(&doc).await {
tracing::warn!(
"Failed to index zero-result fill {}: {}",
crawl_result.url,
e
);
} else {
total_indexed += 1;
let is_quality = intent_score >= min_intent_score
|| (group_match_boost > 0.0 && intent_score > 0.3);
if is_quality {
quality_count += 1;
}
tracing::info!(
"Indexed gap-fill: intent={:.3} cat={} group={} group_match={} \
quality_gate={} [{}/{}] | {}",
intent_score,
doc.category,
doc_group,
group_match_boost > 0.0,
is_quality,
quality_count,
min_urls_per_gap,
doc.title
);
if quality_count >= min_urls_per_gap {
break;
}
}
}
}
}
tracing::info!(
"Zero-result task complete for '{}': indexed={}, quality={}/{}",
query,
total_indexed,
quality_count,
min_urls_per_gap
);
total_indexed
});
handles.push(handle);
}
// Wait for all tasks and sum up indexed counts
let mut total_indexed = 0usize;
for handle in handles {
match handle.await {
Ok(count) => total_indexed += count,
Err(e) => tracing::error!("Zero-result task panicked: {}", e),
}
}
Ok(total_indexed)
}
}
/// Initialize logging
fn init_logging(config: &Config) -> Result<()> {
let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| config.logging.level.parse().unwrap_or_default());
tracing_subscriber::registry()
.with(env_filter)
.with(tracing_subscriber::fmt::layer())
.init();
Ok(())
}
/// Initialize Qdrant index with optimized settings
async fn init_index(indexer: &Indexer, _config: &Config) -> Result<()> {
tracing::info!("Initializing Qdrant collection...");
// Index settings are already applied by indexer.ensure_settings() during AppState::from_config
// Just log that the index is ready
tracing::info!("Collection '{}' ready in Qdrant", indexer.collection_name);
Ok(())
}
/// Main entry point
#[tokio::main]
async fn main() -> Result<()> {
println!("!!! DEBUG: MAIN STARTING !!!");
println!("--- INTENTFORGE STARTING ---");
// Load configuration
let config = Config::load().context("Failed to load configuration")?;
// Initialize logging
init_logging(&config)?;
tracing::info!("Starting IntentForge v2...");
tracing::info!("Loading config...");
// Initialize application state
let state = Arc::new(AppState::from_config(config).await?);
tracing::info!("Application state initialized");
// Initialize index
init_index(&state.indexer, &state.config).await?;
tracing::info!("IntentForge v2 is ready!");
tracing::info!(" - Meilisearch: {}", state.config.meilisearch.url);
tracing::info!(" - Redis: {}", state.config.redis.url);
tracing::info!(
" - Binary quantization: {}",
state.config.meilisearch.binary_quantization
);
tracing::info!(
" - Semantic ratio: {}",
state.config.meilisearch.semantic_ratio
);
tracing::info!(
" - Crawler max concurrent: {}",
state.config.crawler.max_concurrent
);
tracing::info!(
" - Trafilatura: {}",
state.config.extraction.trafilatura_url
);
tracing::info!(
" - ONNX model loaded: {}",
state.embedding_model.is_loaded()
);
tracing::info!(
" - Embedding dim: {}",
state.embedding_model.embedding_dim()
);
// Start HTTP API server
let api_state = Arc::new(ApiState {
metrics: state.metrics.clone(),
app: state,
});
let api_port: u16 = std::env::var("API_PORT")
.unwrap_or_else(|_| "9100".to_string())
.parse()
.unwrap_or(9100);
let addr = SocketAddr::from(([0, 0, 0, 0], api_port));
let router = api::create_router(api_state.clone());
tracing::info!("HTTP API listening on http://{}", addr);
tracing::info!(" - Health: http://{}/health", addr);
tracing::info!(" - Search: http://{}/search?q=<query>", addr);
tracing::info!(" - Crawl: http://{}/crawl?url=<url>", addr);
tracing::info!(" - Metrics: http://{}/metrics", addr);
tracing::info!(" - Discovery: http://{}/discovery/status", addr);
tracing::info!(" - Enqueue: POST http://{}/discovery/enqueue", addr);
// Spawn background discovery service
let discovery_service = api_state.app.discovery.clone();
tokio::spawn(async move {
discovery_service.run().await;
});
// Spawn self-improvement service (gap filling)
let self_improvement_service = api_state.app.self_improvement.clone();
tokio::spawn(async move {
if let Err(e) = self_improvement_service.run_background_loop().await {
tracing::error!("Self-improvement service failed: {}", e);
}
});
// Spawn zero-result search processor (processes queries that returned no results)
let zero_result_state = api_state.clone();
tokio::spawn(async move {
use std::time::Duration;
tracing::info!("Zero-result processor started (interval: 60s)");
loop {
tokio::time::sleep(Duration::from_secs(60)).await;
match zero_result_state.app.process_zero_result_queue().await {
Ok(count) => {
if count > 0 {
tracing::info!("Zero-result processor indexed {} documents", count);
}
}
Err(e) => {
tracing::error!("Zero-result processor error: {}", e);
}
}
}
});
// Spawn domain discovery task (runs every 6 hours)
let domain_manager = api_state.app.domain_manager.clone();
tokio::spawn(async move {
use std::time::Duration;
tracing::info!("Domain discovery task started (interval: 6 hours)");
loop {
tokio::time::sleep(Duration::from_secs(6 * 3600)).await;
match domain_manager.run_discovery().await {
Ok(count) => {
if count > 0 {
tracing::info!("Domain discovery found {} new sources", count);
}
}
Err(e) => {
tracing::error!("Domain discovery error: {}", e);
}
}
}
});
// Spawn Common Crawl delta ingestion task (monthly)
if let Some(ref cc_config) = api_state.app.config.discovery.common_crawl_delta {
if cc_config.enabled {
let cc_discovery = api_state.app.cc_discovery.clone();
let cc_config = cc_config.clone();
let redis_url = api_state.app.config.redis.url.clone();
tracing::info!(
"Common Crawl delta task spawned (interval: {}s, data_dir: {})",
cc_config.interval_secs,
cc_config.data_dir
);
tokio::spawn(async move {
use crate::common_crawl::{compute_url_quality, CdxClient};
use crate::discovery::enhanced::CrawlState;
use redis::AsyncCommands;
tracing::info!(
"Starting Common Crawl delta task (interval: {}s, domains: {}, data_dir: {})",
cc_config.interval_secs,
cc_config.domains.len(),
cc_config.data_dir
);
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(10))
.build()
.expect("Failed to create HEAD check client");
let redis_client = redis::Client::open(redis_url)
.expect("Failed to create Redis client for CC delta");
let mut interval =
tokio::time::interval(std::time::Duration::from_secs(cc_config.interval_secs));
loop {
interval.tick().await;
// 1. Resolve crawl ID and check state
let resolved_id = if cc_config.crawl_id.is_empty() {
match cc_discovery.get_latest_index().await {
Ok(id) => id,
Err(_) => "CC-MAIN-latest".to_string(),
}
} else {
cc_config.crawl_id.clone()
};
if let Some(state) = CrawlState::load(&cc_config.data_dir) {
if state.crawl_id == resolved_id {
tracing::info!(
"Common Crawl delta: crawl {} already processed. Skipping.",
resolved_id
);
continue;
}
}
tracing::info!(
"Running Common Crawl delta ingestion for {}...",
resolved_id
);
// 2. Query CDX for domain-filtered entries
let cdx_client = CdxClient::new();
let domain_refs: Vec<&str> =
cc_config.domains.iter().map(|s| s.as_str()).collect();
let entries = match cdx_client
.query_domains(
&domain_refs,
Some(&resolved_id),
cc_config.max_entries_per_domain,
)
.await
{
Ok(e) => e,
Err(e) => {
tracing::warn!("Common Crawl delta: CDX query failed: {}", e);
continue;
}
};
let total_entries = entries.len() as u64;
// 3. Filter and Quality Pre-filter
let mut quality_candidates: Vec<(String, f32)> = entries
.into_iter()
.filter(|e| e.mime.contains("html") || e.mime.contains("text"))
.map(|e| {
let q = compute_url_quality(&e.url);
(e.url, q)
})
.filter(|(_, q)| *q >= cc_config.quality_threshold)
.collect();
quality_candidates
.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
let candidates: Vec<(String, f32)> =
quality_candidates.into_iter().take(200).collect();
if candidates.is_empty() {
continue;
}
// 4. Verify live status
let mut live_urls = Vec::new();
let mut verify_tasks = Vec::new();
for (url, quality) in &candidates {
let c = client.clone();
let u = url.clone();
let q = *quality;
verify_tasks.push(tokio::spawn(async move {
match c.head(&u).send().await {
Ok(resp) if (200..400).contains(&resp.status().as_u16()) => {
Some((u, q))
}
_ => None,
}
}));
}
for result in futures::future::join_all(verify_tasks).await {
if let Ok(Some(data)) = result {
live_urls.push(data);
}
}
// 5. Enqueue and Update State
let mut enqueued = 0;
if let Ok(mut redis_conn) =
redis::aio::ConnectionManager::new(redis_client.clone()).await
{
for (url, quality) in &live_urls {
let is_new: bool = redis_conn
.sadd("crawl:seen", url.as_str())
.await
.unwrap_or(false);
if is_new {
let priority = ((*quality * 10.0) as u32).clamp(1, 9);
let now = chrono::Utc::now().timestamp();
let score = (priority as i64 * 100000) + (now % 100000);
let member = serde_json::to_string(&crate::discovery::QueuedUrl {
url: url.clone(),
category: "common_crawl".to_string(),
priority,
})
.unwrap_or_default();
if let Ok(()) = redis_conn
.zadd::<_, _, _, ()>("crawl:queue", member, score)
.await
{
enqueued += 1;
}
}
}
}
if enqueued > 0 {
let state = CrawlState {
crawl_id: resolved_id.clone(),
completed_at: chrono::Utc::now().to_rfc3339(),
urls_enqueued: enqueued as u64,
urls_verified: live_urls.len() as u64,
urls_total: total_entries,
};
let _ = state.save(&cc_config.data_dir);
tracing::info!("Common Crawl delta complete: enqueued {} URLs", enqueued);
}
}
});
}
}
// Spawn background trending/crawling task
let crawl_state = api_state.clone();
tokio::spawn(async move {
use crate::indexer::IntentDocument;
let refresh_interval = crawl_state.app.config.trending.refresh_interval;
tracing::info!(
"Starting background crawling loop (interval: {}s)",
refresh_interval
);
loop {
// 1. Process RSS feeds (Real-time signals)
tracing::info!("Fetching RSS feeds...");
match crawl_state.app.trending.clone().fetch_all().await {
Ok(items) => {
let trending = crawl_state.app.trending.calculate_trending(items);
tracing::info!(
"Found {} trending items, crawling top items...",
trending.len()
);
let top_items: Vec<_> = trending.iter().take(20).collect();
let urls: Vec<&str> = top_items.iter().map(|i| i.url.as_str()).collect();
match crawl_state.app.crawler.fetch_batch(urls).await {
Ok(results) => {
let mut texts = Vec::new();
for result in &results {
texts.push(format!("{} {}", result.title, result.content));
}
let embeddings = crawl_state
.app
.embedding_model
.embed_batch(&texts)
.unwrap_or_else(|_| {
crawl_state.app.embedding_model.embed_fallback(&texts)
});
for (idx, result) in results.into_iter().enumerate() {
let item = top_items[idx];
let embedding = embeddings[idx].clone();
let quality_score = crawl_state
.app
.embedding_model
.calculate_quality_score(&texts[idx], &result.url);
// Sanitize ID for Meilisearch
let safe_id: String = item
.id
.chars()
.map(|c| {
if c.is_alphanumeric() || c == '-' || c == '_' {
c
} else {
'-'
}
})
.collect();
let title_text = format!("{} {}", item.title, item.category);
let title_embedding = crawl_state
.app
.embedding_model
.embed_batch(std::slice::from_ref(&title_text))
.unwrap_or_else(|_| {
crawl_state
.app
.embedding_model
.embed_fallback(&[title_text])
});
let intent_score = if let Some(te) = title_embedding.first() {
crate::utils::cosine_similarity(te, &embedding).clamp(0.0, 1.0)
} else {
0.5
};
let relevance_score = (intent_score * 0.4
+ quality_score * 0.4
+ (item.trending_score / 10000.0).min(0.2))
.clamp(0.1, 1.0);
// 1. Store full content in Redis (compressed)
if let Err(e) = crawl_state
.app
.redis
.store_content(&safe_id, &result.content)
.await
{
tracing::warn!(
"Failed to store full content in Redis for {}: {}",
safe_id,
e
);
}
// 2. Tiered Indexing: Snippet-only for lower intent
let mut doc = IntentDocument::new(
safe_id,
result.title.clone(),
result.content.clone(),
result.url.clone(),
item.source.clone(),
item.category.clone(),
intent_score,
relevance_score,
embedding,
)
.with_extra_scores(0.0, 0.0);
if intent_score < 0.8 {
doc = doc.with_snippet(
crawl_state.app.config.indexer.snippet_length,
);
}
if let Err(e) = crawl_state.app.indexer.index_document(&doc).await {
tracing::warn!("Failed to index {}: {}", result.url, e);
} else {
tracing::info!("Indexed: {}", doc.title);
crawl_state.app.metrics.index_documents_total.inc();
}
// Extract and index images from page HTML (zero bandwidth)
if let Some(ref html) = result.html {
let image_contexts =
crate::image_indexer::extract_image_contexts(
html,
&result.url,
);
for img_ctx in image_contexts {
if !img_ctx.has_meaningful_context() {
continue;
}
let img_text = img_ctx.to_searchable_text();
if img_text.trim().len() < 5 {
continue;
}
let img_embedding = crawl_state
.app
.embedding_model
.embed_batch(std::slice::from_ref(&img_text))
.unwrap_or_else(|_| {
crawl_state
.app
.embedding_model
.embed_fallback(std::slice::from_ref(&img_text))
});
if let Some(emb) = img_embedding.first() {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
img_ctx.url.hash(&mut hasher);
let img_id = format!("img-{:x}", hasher.finish());
let img_doc = IntentDocument::new(
img_id,
img_ctx
.alt_text
.clone()
.unwrap_or_else(|| img_text.clone()),
img_text,
img_ctx.url.clone(),
item.source.clone(),
item.category.clone(),
intent_score * 0.8,
relevance_score * 0.7,
emb.clone(),
)
.with_media_type("image".to_string())
.with_extra_scores(0.0, 0.0);
if let Err(e) = crawl_state
.app
.indexer
.index_document(&img_doc)
.await
{
tracing::debug!(
"Failed to index image {}: {}",
img_ctx.url,
e
);
}
}
}
}
}
}
Err(e) => tracing::warn!("Batch crawl failed: {}", e),
}
}
Err(e) => tracing::error!("Feed fetch failed: {}", e),
}
tokio::time::sleep(std::time::Duration::from_secs(refresh_interval)).await;
}
});
// 2. Spawn independent Discovery Queue processing task (High-throughput)
let queue_state = api_state.clone();
tokio::spawn(async move {
use crate::indexer::IntentDocument;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
tracing::info!("Starting discovery queue processor...");
loop {
// Process discovered URLs from Redis queue (Self-expansion)
let mut queued_items = Vec::new();
// Reduce batch size slightly to ensure individual failures don't stall everything
for _ in 0..20 {
if let Ok(Some(queued)) = queue_state.app.discovery.pop_url().await {
tracing::trace!("Popped URL: {}", queued.url);
queued_items.push(queued);
} else {
break;
}
}
if queued_items.is_empty() {
// If queue is empty, wait a bit longer
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
continue;
}
tracing::info!(
"Discovery queue processor: Fetching batch of {} URLs",
queued_items.len()
);
let urls: Vec<&str> = queued_items.iter().map(|i| i.url.as_str()).collect();
match queue_state.app.crawler.fetch_batch(urls).await {
Ok(results) => {
tracing::info!(
"Discovery queue processor: Fetched {}/{} URLs successfully",
results.len(),
queued_items.len()
);
let mut texts = Vec::new();
for result in &results {
texts.push(format!("{} {}", result.title, result.content));
}
let embeddings = queue_state
.app
.embedding_model
.embed_batch(&texts)
.unwrap_or_else(|_| queue_state.app.embedding_model.embed_fallback(&texts));
for (idx, result) in results.into_iter().enumerate() {
let queued = &queued_items[idx];
let embedding = embeddings[idx].clone();
let quality_score = queue_state
.app
.embedding_model
.calculate_quality_score(&texts[idx], &result.url);
// Generate stable ID from URL hash
let mut hasher = DefaultHasher::new();
queued.url.hash(&mut hasher);
let safe_id = format!("ext-{:x}", hasher.finish());
let title_text = format!("{} {}", result.title, queued.category);
let title_embedding = queue_state
.app
.embedding_model
.embed_batch(std::slice::from_ref(&title_text))
.unwrap_or_else(|_| {
queue_state
.app
.embedding_model
.embed_fallback(&[title_text])
});
let intent_score = if let Some(te) = title_embedding.first() {
crate::utils::cosine_similarity(te, &embedding).clamp(0.0, 1.0)
} else {
0.5
};
let relevance_score = (intent_score * 0.4
+ quality_score * 0.4
+ (queued.priority as f32 / 1000.0).min(0.2))
.clamp(0.1, 1.0);
// 1. Store full content in Redis (compressed)
if let Err(e) = queue_state
.app
.redis
.store_content(&safe_id, &result.content)
.await
{
tracing::warn!(
"Failed to store full content in Redis for {}: {}",
safe_id,
e
);
}
// 2. Tiered Indexing: Snippet-only for lower intent
let mut doc = IntentDocument::new(
safe_id,
result.title.clone(),
result.content.clone(),
result.url.clone(),
"discovery".to_string(),
queued.category.clone(),
intent_score,
relevance_score,
embedding,
)
.with_extra_scores(0.0, 0.0);
if intent_score < 0.8 {
doc = doc.with_snippet(queue_state.app.config.indexer.snippet_length);
}
if let Err(e) = queue_state.app.indexer.index_document(&doc).await {
tracing::warn!("Failed to index discovery {}: {}", queued.url, e);
} else {
tracing::info!("Indexed (Discovery): {}", doc.title);
queue_state.app.metrics.index_documents_total.inc();
}
// Extract and index images
if let Some(ref html) = result.html {
let image_contexts =
crate::image_indexer::extract_image_contexts(html, &result.url);
for img_ctx in image_contexts {
if !img_ctx.has_meaningful_context() {
continue;
}
let img_text = img_ctx.to_searchable_text();
if img_text.trim().len() < 5 {
continue;
}
let img_embedding = queue_state
.app
.embedding_model
.embed_batch(std::slice::from_ref(&img_text))
.unwrap_or_else(|_| {
queue_state
.app
.embedding_model
.embed_fallback(std::slice::from_ref(&img_text))
});
if let Some(emb) = img_embedding.first() {
let mut img_hasher = DefaultHasher::new();
img_ctx.url.hash(&mut img_hasher);
let img_id = format!("img-{:x}", img_hasher.finish());
let img_doc = IntentDocument::new(
img_id,
img_ctx
.alt_text
.clone()
.unwrap_or_else(|| img_text.clone()),
img_text,
img_ctx.url.clone(),
"discovery".to_string(),
queued.category.clone(),
intent_score * 0.8,
relevance_score * 0.7,
emb.clone(),
)
.with_media_type("image".to_string())
.with_extra_scores(0.0, 0.0);
if queue_state
.app
.indexer
.index_document(&img_doc)
.await
.is_ok()
{
queue_state.app.metrics.index_documents_total.inc();
}
}
}
}
}
}
Err(e) => tracing::warn!("Discovery batch crawl failed: {}", e),
}
// Continuous processing with minimal sleep to yield
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
});
let listener = tokio::net::TcpListener::bind(addr)
.await
.with_context(|| format!("Failed to bind to {}", addr))?;
axum::serve(listener, router)
.with_graceful_shutdown(async {
tokio::signal::ctrl_c().await.ok();
tracing::info!("Shutting down HTTP API...");
})
.await
.context("HTTP server error")?;
tracing::info!("IntentForge v2 stopped");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_config_load() {
let config = Config::default_config().unwrap();
assert_eq!(config.qdrant.collection_name, "intentforge");
}
}
|