intentforge / src /discovery /enhanced.rs
Likhith Sai Seemala
Deploy IntentForge v2 to HF Spaces
0ca462b
Raw History Blame Contribute Delete
7.54 kB
//! Enhanced discovery features for IntentForge v2
//!
//! Additional content discovery mechanisms including:
//! - Common Crawl URL extraction
//! - Additional sitemap sources
//! - API-based content discovery
use anyhow::{Context, Result};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::path::Path;
/// State of a Common Crawl ingestion
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CrawlState {
pub crawl_id: String,
pub completed_at: String,
pub urls_enqueued: u64,
pub urls_verified: u64,
pub urls_total: u64,
}
impl CrawlState {
pub fn load(data_dir: &str) -> Option<Self> {
let path = Path::new(data_dir).join("cc_state.json");
if let Ok(content) = std::fs::read_to_string(path) {
serde_json::from_str(&content).ok()
} else {
None
}
}
pub fn save(&self, data_dir: &str) -> Result<()> {
let path = Path::new(data_dir).join("cc_state.json");
let content = serde_json::to_string_pretty(self)?;
std::fs::write(path, content)?;
Ok(())
}
}
/// Common Crawl API integration for URL discovery
pub struct CommonCrawlDiscovery {
client: Client,
base_url: String,
}
impl CommonCrawlDiscovery {
pub fn new() -> Result<Self> {
let client = Client::builder()
.user_agent("IntentForge/0.1 (Content Discovery Bot)")
.timeout(std::time::Duration::from_secs(30))
.build()
.context("Failed to create HTTP client for CommonCrawlDiscovery")?;
Ok(Self {
client,
base_url: "https://index.commoncrawl.org".to_string(),
})
}
/// Search Common Crawl index for URLs matching a query
pub async fn search_urls(&self, query: &str, limit: usize) -> Result<Vec<String>> {
let latest_index = self.get_latest_index().await?;
let url = format!(
"{}/{}-index/search?url=*&output=json&limit={}&q={}",
self.base_url,
latest_index,
limit,
urlencoding::encode(query)
);
let response = self
.client
.get(&url)
.send()
.await
.context("Failed to fetch from Common Crawl API")?;
if !response.status().is_success() {
anyhow::bail!("Common Crawl API returned status {}", response.status());
}
let text = response.text().await?;
let urls = self.parse_common_crawl_response(&text)?;
Ok(urls)
}
/// Parse Common Crawl JSON response
fn parse_common_crawl_response(&self, text: &str) -> Result<Vec<String>> {
let mut urls = Vec::new();
let mut seen = HashSet::new();
// Common Crawl returns JSON lines
for line in text.lines() {
if let Ok(json) = serde_json::from_str::<serde_json::Value>(line) {
if let Some(url) = json.get("url").and_then(|v| v.as_str()) {
if seen.insert(url.to_string()) {
urls.push(url.to_string());
}
}
}
}
Ok(urls)
}
/// Get latest crawl index metadata
pub async fn get_latest_index(&self) -> Result<String> {
let response = self
.client
.get(format!("{}/collinfo.json", self.base_url))
.send()
.await
.context("Failed to fetch Common Crawl index info")?;
let indexes: Vec<serde_json::Value> = response.json().await?;
if let Some(latest) = indexes.first() {
if let Some(id) = latest.get("id").and_then(|v| v.as_str()) {
return Ok(id.to_string());
}
}
anyhow::bail!("No Common Crawl index found");
}
}
/// Additional sitemap discovery for tech content
pub fn get_additional_sitemaps() -> Vec<(String, String, String)> {
vec![
// Tech blogs
(
"Netflix Tech Blog".to_string(),
"https://netflixtechblog.com/feed/".to_string(),
"tech".to_string(),
),
(
"Uber Engineering".to_string(),
"https://eng.uber.com/feed/".to_string(),
"tech".to_string(),
),
(
"Airbnb Engineering".to_string(),
"https://medium.com/feed/airbnb-engineering".to_string(),
"tech".to_string(),
),
(
"Spotify Labs".to_string(),
"https://engineering.atspotify.com/feed/".to_string(),
"tech".to_string(),
),
(
"Stripe Engineering".to_string(),
"https://stripe.com/blog/engineering/feed".to_string(),
"tech".to_string(),
),
// AI/ML specific
(
"Distill.pub".to_string(),
"https://distill.pub/rss.xml".to_string(),
"ai".to_string(),
),
(
"Towards Data Science".to_string(),
"https://towardsdatascience.com/feed".to_string(),
"ai".to_string(),
),
(
"The Batch by DeepLearning.AI".to_string(),
"https://www.deeplearning.ai/the-batch/feed/".to_string(),
"ai".to_string(),
),
// Developer resources
(
"CSS-Tricks".to_string(),
"https://css-tricks.com/feed/".to_string(),
"devtools".to_string(),
),
(
"Smashing Magazine".to_string(),
"https://www.smashingmagazine.com/feed/".to_string(),
"devtools".to_string(),
),
(
"A List Apart".to_string(),
"https://alistapart.com/main/feed/".to_string(),
"devtools".to_string(),
),
// Security
(
"Krebs on Security".to_string(),
"https://krebsonsecurity.com/feed/".to_string(),
"tech".to_string(),
),
(
"Schneier on Security".to_string(),
"https://www.schneier.com/feed/atom/".to_string(),
"tech".to_string(),
),
]
}
/// Get additional domains to monitor with sitemaps
pub fn get_additional_domains() -> Vec<(String, String, String, Option<String>)> {
vec![
(
"Medium".to_string(),
"https://medium.com".to_string(),
"tech".to_string(),
Some("https://medium.com/sitemap/sitemap.xml".to_string()),
),
(
"Dev.to".to_string(),
"https://dev.to".to_string(),
"devtools".to_string(),
Some("https://dev.to/sitemap.xml".to_string()),
),
(
"Hashnode".to_string(),
"https://hashnode.com".to_string(),
"devtools".to_string(),
Some("https://hashnode.com/sitemap.xml".to_string()),
),
(
"Ars Technica".to_string(),
"https://arstechnica.com".to_string(),
"tech".to_string(),
Some("https://arstechnica.com/sitemap.xml".to_string()),
),
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_additional_sitemaps_not_empty() {
let sitemaps = get_additional_sitemaps();
assert!(!sitemaps.is_empty());
assert!(sitemaps.len() > 10);
}
#[test]
fn test_additional_domains_not_empty() {
let domains = get_additional_domains();
assert!(!domains.is_empty());
}
}