Skip to content

web search done right

show homepage description in explorer

Mikkel Denkerf1f5cde7c582
diff --git a/core/src/api/mod.rs b/core/src/api/mod.rs
index 67677041..f0031168 100644
--- a/core/src/api/mod.rs
+++ b/core/src/api/mod.rs
@@ -29,7 +29,7 @@ use crate::{
qa_model::QaModel,
query_store::{self, ImprovementEvent},
ranking::models::{cross_encoder::CrossEncoderModel, lambdamart::LambdaMART},
- searcher::DistributedSearcher,
+ searcher::frontend::FrontendSearcher,
summarizer::Summarizer,
FrontendConfig,
};
@@ -63,7 +63,7 @@ mod webgraph;
pub struct HtmlTemplate<T>(T);
pub struct State {
- pub searcher: DistributedSearcher,
+ pub searcher: FrontendSearcher,
pub remote_webgraph: RemoteWebgraph,
pub autosuggest: Autosuggest,
pub search_counter_success: crate::metrics::Counter,
@@ -139,7 +139,7 @@ pub async fn router(
.await?,
);
let remote_webgraph = RemoteWebgraph::new(cluster.clone());
- let searcher = DistributedSearcher::new(cluster, crossencoder, lambda_model, qa_model, bangs);
+ let searcher = FrontendSearcher::new(cluster, crossencoder, lambda_model, qa_model, bangs);
let state = Arc::new(State {
searcher,
diff --git a/core/src/api/webgraph.rs b/core/src/api/webgraph.rs
index e5b0ff6c..156a6a9e 100644
--- a/core/src/api/webgraph.rs
+++ b/core/src/api/webgraph.rs
@@ -18,11 +18,10 @@ use std::{net::SocketAddr, sync::Arc, time::Duration};
use axum::{extract, response::IntoResponse, Json};
use http::StatusCode;
-use itertools::Itertools;
use crate::{
distributed::{cluster::Cluster, member::Service, retry_strategy::ExponentialBackoff, sonic},
- similar_sites::ScoredNode,
+ entrypoint::webgraph_server::ScoredSite,
webgraph::Node,
};
@@ -56,12 +55,6 @@ pub struct SimilarSitesParams {
pub top_n: usize,
}
-#[derive(serde::Serialize, serde::Deserialize)]
-struct ScoredSite {
- pub site: String,
- pub score: f64,
-}
-
#[allow(clippy::unused_async)]
pub async fn similar_sites(
extract::State(state): extract::State<Arc<State>>,
@@ -76,7 +69,7 @@ pub async fn similar_sites(
let mut conn = sonic::ResilientConnection::create(host, retry);
match conn
- .send_with_timeout::<_, Vec<ScoredNode>>(
+ .send_with_timeout::<_, Vec<ScoredSite>>(
&crate::entrypoint::webgraph_server::Request::SimilarSites {
sites: params.sites,
top_n: params.top_n,
@@ -85,15 +78,7 @@ pub async fn similar_sites(
)
.await
{
- Ok(sonic::Response::Content(nodes)) => Ok(Json(
- nodes
- .into_iter()
- .map(|node| ScoredSite {
- site: node.node.name,
- score: node.score,
- })
- .collect_vec(),
- )),
+ Ok(sonic::Response::Content(nodes)) => Ok(Json(nodes)),
Err(err) => {
tracing::error!("Failed to send request to webgraph: {}", err);
Err(StatusCode::INTERNAL_SERVER_ERROR)
diff --git a/core/src/entrypoint/search_server.rs b/core/src/entrypoint/search_server.rs
index 284919c4..734428de 100644
--- a/core/src/entrypoint/search_server.rs
+++ b/core/src/entrypoint/search_server.rs
@@ -14,7 +14,7 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
-use std::net::SocketAddr;
+use std::{collections::HashMap, net::SocketAddr};
use tracing::info;
@@ -32,6 +32,7 @@ use crate::{
models::{lambdamart::LambdaMART, linear::LinearRegression},
},
searcher::{self, LocalSearcher},
+ webpage::Url,
Result, SearchServerConfig,
};
@@ -114,6 +115,20 @@ pub async fn run(config: SearchServerConfig) -> Result<()> {
let result = local_searcher.get_webpage(url);
req.respond(sonic::Response::Content(result)).await.ok();
}
+ searcher::Request::GetHomepageDescriptions { urls } => {
+ let mut result = HashMap::with_capacity(urls.len());
+
+ for url in urls {
+ if let Some(homepage) = local_searcher.get_homepage(url) {
+ if let Some(desc) = homepage.description() {
+ result.insert(Url::from(url.clone()), desc.clone());
+ } else {
+ }
+ }
+ }
+
+ req.respond(sonic::Response::Content(result)).await.ok();
+ }
}
}
}
diff --git a/core/src/entrypoint/webgraph_server.rs b/core/src/entrypoint/webgraph_server.rs
index abfe4dcb..df90ca69 100644
--- a/core/src/entrypoint/webgraph_server.rs
+++ b/core/src/entrypoint/webgraph_server.rs
@@ -17,6 +17,7 @@
use std::net::SocketAddr;
use std::sync::Arc;
+use itertools::Itertools;
use serde::Deserialize;
use serde::Serialize;
use tracing::info;
@@ -26,9 +27,11 @@ use crate::distributed::member::Member;
use crate::distributed::member::Service;
use crate::distributed::sonic;
use crate::ranking::inbound_similarity::InboundSimilarity;
+use crate::searcher::DistributedSearcher;
use crate::similar_sites::SimilarSitesFinder;
use crate::webgraph::Node;
use crate::webgraph::WebgraphBuilder;
+use crate::webpage::Url;
use crate::Result;
use crate::WebgraphServerConfig;
@@ -38,19 +41,31 @@ pub enum Request {
Knows { site: String },
}
+#[derive(serde::Serialize, serde::Deserialize)]
+pub struct ScoredSite {
+ pub site: String,
+ pub score: f64,
+ pub description: Option<String>,
+}
+
+const MAX_SITES: usize = 20;
+
pub async fn run(config: WebgraphServerConfig) -> Result<()> {
let addr: SocketAddr = config.host;
// dropping the handle leaves the cluster
- let _cluster_handle = Cluster::join(
- Member {
- id: config.cluster_id,
- service: Service::Webgraph { host: addr },
- },
- config.gossip_addr,
- config.gossip_seed_nodes.unwrap_or_default(),
- )
- .await?;
+ let cluster = Arc::new(
+ Cluster::join(
+ Member {
+ id: config.cluster_id,
+ service: Service::Webgraph { host: addr },
+ },
+ config.gossip_addr,
+ config.gossip_seed_nodes.unwrap_or_default(),
+ )
+ .await?,
+ );
+ let searcher = DistributedSearcher::new(cluster);
let graph = Arc::new(WebgraphBuilder::new(config.graph_path).open());
let inbound_similarity = InboundSimilarity::open(config.inbound_similarity_path)?;
@@ -65,7 +80,31 @@ pub async fn run(config: WebgraphServerConfig) -> Result<()> {
if let Ok(req) = server.accept::<Request>().await {
match &req.body {
Request::SimilarSites { sites, top_n } => {
+ let sites = &sites[..std::cmp::min(sites.len(), MAX_SITES)];
let similar_sites = similar_sites_finder.find_similar_sites(sites, *top_n);
+
+ let urls = similar_sites
+ .iter()
+ .map(|s| s.node.name.clone())
+ .collect_vec();
+
+ let descriptions = searcher.get_homepage_descriptions(&urls).await;
+
+ let similar_sites = similar_sites
+ .into_iter()
+ .map(|site| {
+ let description = descriptions
+ .get(&Url::from(site.node.name.clone()))
+ .cloned();
+
+ ScoredSite {
+ site: site.node.name,
+ score: site.score,
+ description,
+ }
+ })
+ .collect_vec();
+
req.respond(sonic::Response::Content(similar_sites))
.await
.ok();
diff --git a/core/src/index.rs b/core/src/index.rs
index 835c740f..98fb2d25 100644
--- a/core/src/index.rs
+++ b/core/src/index.rs
@@ -239,6 +239,10 @@ impl Index {
pub(crate) fn get_webpage(&self, url: &str) -> Option<inverted_index::RetrievedWebpage> {
self.inverted_index.get_webpage(url)
}
+
+ pub fn get_homepage(&self, url: &str) -> Option<inverted_index::RetrievedWebpage> {
+ self.inverted_index.get_homepage(url)
+ }
}
#[derive(Debug, Serialize, Deserialize)]
diff --git a/core/src/inverted_index.rs b/core/src/inverted_index.rs
index d9c955f6..6d68e5b0 100644
--- a/core/src/inverted_index.rs
+++ b/core/src/inverted_index.rs
@@ -20,7 +20,7 @@ use tantivy::collector::{Collector, Count};
use tantivy::directory::MmapDirectory;
use tantivy::merge_policy::NoMergePolicy;
use tantivy::schema::Schema;
-use tantivy::tokenizer::{Tokenizer as _, TokenizerManager};
+use tantivy::tokenizer::TokenizerManager;
use tantivy::{Document, IndexReader, IndexWriter, SegmentMeta};
use crate::collector::Hashes;
@@ -37,7 +37,7 @@ use crate::snippet;
use crate::tokenizer::{BigramTokenizer, Identity, TrigramTokenizer};
use crate::webgraph::NodeID;
use crate::webpage::region::Region;
-use crate::webpage::{schema_org, StoredPrimaryImage, Webpage};
+use crate::webpage::{schema_org, StoredPrimaryImage, Url, Webpage};
use crate::Result;
use crate::{schema::create_schema, tokenizer::Tokenizer};
use std::collections::HashSet;
@@ -443,18 +443,33 @@ impl InvertedIndex {
let tv_searcher = self.reader.searcher();
let field = tv_searcher
.schema()
- .get_field(Field::Text(TextField::Url).name())
+ .get_field(Field::Text(TextField::UrlNoTokenizer).name())
.unwrap();
- let tokenizer = Tokenizer::default();
- let mut stream = tokenizer.token_stream(url);
- let mut term_queries = Vec::new();
- while let Some(tok) = stream.next() {
- let term = tantivy::Term::from_field_text(field, &tok.text);
- term_queries.push(term);
- }
+ let term = tantivy::Term::from_field_text(field, url);
+
+ let query = tantivy::query::TermQuery::new(term, tantivy::schema::IndexRecordOption::Basic);
+
+ let mut res = tv_searcher
+ .search(&query, &tantivy::collector::TopDocs::with_limit(1))
+ .unwrap();
+
+ res.pop()
+ .map(|(_, doc)| self.retrieve_doc(doc.into(), &tv_searcher).unwrap())
+ }
+
+ pub(crate) fn get_homepage(&self, url: &str) -> Option<RetrievedWebpage> {
+ let url = Url::from(url.to_string());
+ let tv_searcher = self.reader.searcher();
+ let field = tv_searcher
+ .schema()
+ .get_field(Field::Text(TextField::SiteNoTokenizer).name())
+ .unwrap();
+
+ let term = tantivy::Term::from_field_text(field, url.site());
+
+ let query = tantivy::query::TermQuery::new(term, tantivy::schema::IndexRecordOption::Basic);
- let query = tantivy::query::PhraseQuery::new(term_queries);
let mut res = tv_searcher
.search(&query, &tantivy::collector::TopDocs::with_limit(1))
.unwrap();
@@ -486,6 +501,11 @@ pub struct RetrievedWebpage {
pub schema_org: Vec<schema_org::Item>,
pub region: Region,
}
+impl RetrievedWebpage {
+ pub fn description(&self) -> Option<&String> {
+ self.description.as_ref().or(self.dmoz_description.as_ref())
+ }
+}
impl From<Document> for RetrievedWebpage {
fn from(doc: Document) -> Self {
@@ -1408,4 +1428,39 @@ mod tests {
assert_eq!(webpage.title, "News website".to_string());
assert_eq!(webpage.url, "https://www.example.com".to_string());
}
+
+ #[test]
+ fn get_homepage() {
+ let mut index = InvertedIndex::temporary().expect("Unable to open index");
+
+ index
+ .insert(Webpage::new(
+ &format!(
+ r#"
+ <html>
+ <head>
+ <title>News website</title>
+ <script type="application/ld+json">{{"@context":"http://schema.org","@type":"LiveBlogPosting","coverageStartTime":"2022-11-14T23:45:00+00:00","coverageEndTime":"2022-11-15T23:45:00.000Z","datePublished":"2022-11-14T23:45:00+00:00","articleBody":"","author":[{{"name":"DR"}}],"url":"https://www.example.com","mainEntityOfPage":"https://www.example.com"}}
+ </script>
+ </head>
+ <body>
+ {CONTENT} test
+ <article itemscope="" itemType="http://schema.org/NewsArticle">
+ <div itemProp="publisher" itemscope="" itemType="https://schema.org/Organization"><meta itemProp="name" content="DR"/>
+ </div>
+ </article>
+ </body>
+ </html>
+ "#
+ ),
+ "https://www.example.com",
+ ))
+ .expect("failed to insert webpage");
+
+ index.commit().expect("failed to commit index");
+
+ let webpage = index.get_homepage("https://www.example.com").unwrap();
+ assert_eq!(webpage.title, "News website".to_string());
+ assert_eq!(webpage.url, "https://www.example.com".to_string());
+ }
}
diff --git a/core/src/schema.rs b/core/src/schema.rs
index 815d41c7..7e4a6dab 100644
--- a/core/src/schema.rs
+++ b/core/src/schema.rs
@@ -30,9 +30,11 @@ pub enum TextField {
StemmedCleanBody,
AllBody,
Url,
+ UrlNoTokenizer,
Site,
Domain,
SiteNoTokenizer,
+ SiteIfHomepageNoTokenizer,
DomainNoTokenizer,
/// this field is only set if the webpage is the homepage for the site. Allows us to boost
DomainIfHomepage,
@@ -68,9 +70,11 @@ impl TextField {
TextField::StemmedCleanBody => Tokenizer::new_stemmed(),
TextField::AllBody => Tokenizer::default(),
TextField::Url => Tokenizer::default(),
+ TextField::UrlNoTokenizer => Tokenizer::Identity(Identity {}),
TextField::Site => Tokenizer::default(),
TextField::Domain => Tokenizer::default(),
TextField::SiteNoTokenizer => Tokenizer::Identity(Identity {}),
+ TextField::SiteIfHomepageNoTokenizer => Tokenizer::Identity(Identity {}),
TextField::DomainNoTokenizer => Tokenizer::Identity(Identity {}),
TextField::DomainIfHomepage => Tokenizer::default(),
TextField::DomainNameIfHomepageNoTokenizer => Tokenizer::Identity(Identity {}),
@@ -105,9 +109,11 @@ impl TextField {
TextField::StemmedCleanBody => false,
TextField::AllBody => false,
TextField::Url => true,
+ TextField::UrlNoTokenizer => false,
TextField::Site => true,
TextField::Domain => true,
TextField::SiteNoTokenizer => false,
+ TextField::SiteIfHomepageNoTokenizer => false,
TextField::DomainNoTokenizer => false,
TextField::DomainIfHomepage => false,
TextField::DomainNameIfHomepageNoTokenizer => false,
@@ -131,9 +137,11 @@ impl TextField {
TextField::Title => "title",
TextField::CleanBody => "body",
TextField::Url => "url",
+ TextField::UrlNoTokenizer => "url_no_tokenizer",
TextField::Site => "site",
TextField::Domain => "domain",
TextField::SiteNoTokenizer => "site_no_tokenizer",
+ TextField::SiteIfHomepageNoTokenizer => "site_if_homepage_no_tokenizer",
TextField::DomainNoTokenizer => "domain_no_tokenizer",
TextField::BacklinkText => "backlink_text",
TextField::StemmedTitle => "stemmed_title",
@@ -235,16 +243,18 @@ pub enum Field {
Text(TextField),
}
-pub static ALL_FIELDS: [Field; 52] = [
+pub static ALL_FIELDS: [Field; 54] = [
Field::Text(TextField::Title),
Field::Text(TextField::CleanBody),
Field::Text(TextField::StemmedTitle),
Field::Text(TextField::StemmedCleanBody),
Field::Text(TextField::AllBody),
Field::Text(TextField::Url),
+ Field::Text(TextField::UrlNoTokenizer),
Field::Text(TextField::Site),
Field::Text(TextField::Domain),
Field::Text(TextField::SiteNoTokenizer),
+ Field::Text(TextField::SiteIfHomepageNoTokenizer),
Field::Text(TextField::DomainNoTokenizer),
Field::Text(TextField::DomainIfHomepage),
Field::Text(TextField::DomainNameIfHomepageNoTokenizer),
@@ -319,7 +329,13 @@ impl Field {
Field::Text(TextField::Url) => {
IndexingOption::Text(self.default_text_options().set_stored())
}
+ Field::Text(TextField::UrlNoTokenizer) => {
+ IndexingOption::Text(self.default_text_options())
+ }
Field::Text(TextField::Site) => IndexingOption::Text(self.default_text_options()),
+ Field::Text(TextField::SiteIfHomepageNoTokenizer) => {
+ IndexingOption::Text(self.default_text_options())
+ }
Field::Text(TextField::Domain) => IndexingOption::Text(self.default_text_options()),
Field::Text(TextField::SiteNoTokenizer) => {
IndexingOption::Text(self.default_text_options())
diff --git a/core/src/searcher/distributed.rs b/core/src/searcher/distributed.rs
index 7aae15e4..26fb949d 100644
--- a/core/src/searcher/distributed.rs
+++ b/core/src/searcher/distributed.rs
@@ -15,50 +15,23 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::{
- bangs::{Bang, BangHit, Bangs},
- ceil_char_boundary,
- collector::BucketCollector,
distributed::{cluster::Cluster, member::Service, retry_strategy::ExponentialBackoff},
- floor_char_boundary,
inverted_index::{self, RetrievedWebpage},
- qa_model::QaModel,
- query,
- ranking::{
- models::{cross_encoder::CrossEncoderModel, lambdamart::LambdaMART},
- pipeline::{AsRankingWebsite, RankingPipeline, RankingWebsite},
- ALL_SIGNALS,
- },
- search_prettifier::{
- create_stackoverflow_sidebar, DisplayedAnswer, DisplayedWebpage,
- HighlightedSpellCorrection, Sidebar,
- },
- searcher::WebsitesResult,
- widgets::Widget,
+ ranking::pipeline::{AsRankingWebsite, RankingWebsite},
+ webpage::Url,
Result,
};
-use std::{
- cmp::Ordering,
- collections::HashMap,
- net::SocketAddr,
- ops::Range,
- sync::Arc,
- time::{Duration, Instant},
-};
+use std::{collections::HashMap, net::SocketAddr, sync::Arc, time::Duration};
use futures::stream::FuturesUnordered;
use futures::StreamExt;
-use itertools::intersperse;
-use optics::Optic;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::distributed::sonic;
-use super::{InitialWebsiteResult, SearchQuery, SearchResult};
-
-const STACKOVERFLOW_SIDEBAR_THRESHOLD: f64 = 100.0;
-const DISCUSSIONS_WIDGET_THRESHOLD: f64 = 100.0;
+use super::{InitialWebsiteResult, SearchQuery};
struct RemoteSearcher {
addr: SocketAddr,
@@ -130,6 +103,24 @@ impl RemoteSearcher {
Err(Error::WebpageNotFound.into())
}
+ async fn get_homepage_descriptions(&self, urls: &[String]) -> HashMap<Url, String> {
+ let mut conn = self.conn();
+
+ if let Ok(sonic::Response::Content(body)) = conn
+ .send_with_timeout(
+ &Request::GetHomepageDescriptions {
+ urls: urls.to_vec(),
+ },
+ Duration::from_secs(1),
+ )
+ .await
+ {
+ return body;
+ }
+
+ HashMap::new()
+ }
+
fn conn(&self) -> sonic::ResilientConnection<impl Iterator<Item = Duration>> {
let retry = ExponentialBackoff::from_millis(30)
.with_limit(Duration::from_millis(200))
@@ -211,12 +202,26 @@ impl Shard {
_ => Err(Error::WebpageNotFound.into()),
}
}
+
+ async fn get_homepage_descriptions(&self, urls: &[String]) -> HashMap<Url, String> {
+ match self
+ .replicas
+ .iter()
+ .map(|remote| remote.get_homepage_descriptions(urls))
+ .collect::<FuturesUnordered<_>>()
+ .next()
+ .await
+ {
+ Some(t) => t,
+ _ => HashMap::new(),
+ }
+ }
}
#[derive(Debug)]
-struct InitialSearchResultShard {
- local_result: InitialWebsiteResult,
- shard: ShardId,
+pub struct InitialSearchResultShard {
+ pub local_result: InitialWebsiteResult,
+ pub shard: ShardId,
}
#[derive(Serialize, Deserialize)]
@@ -229,20 +234,15 @@ pub enum Request {
GetWebpage {
url: String,
},
-}
-
-pub struct DistributedSearcher {
- cluster: Arc<Cluster>,
- cross_encoder: Arc<CrossEncoderModel>,
- lambda_model: Option<Arc<LambdaMART>>,
- qa_model: Option<Arc<QaModel>>,
- bangs: Bangs,
+ GetHomepageDescriptions {
+ urls: Vec<String>,
+ },
}
#[derive(Clone)]
-struct ScoredWebsitePointer {
- website: RankingWebsite,
- shard: ShardId,
+pub struct ScoredWebsitePointer {
+ pub website: RankingWebsite,
+ pub shard: ShardId,
}
impl AsRankingWebsite for ScoredWebsitePointer {
@@ -255,21 +255,13 @@ impl AsRankingWebsite for ScoredWebsitePointer {
}
}
+pub struct DistributedSearcher {
+ cluster: Arc<Cluster>,
+}
+
impl DistributedSearcher {
- pub fn new(
- cluster: Arc<Cluster>,
- cross_encoder: CrossEncoderModel,
- lambda_model: Option<LambdaMART>,
- qa_model: Option<QaModel>,
- bangs: Bangs,
- ) -> Self {
- Self {
- cluster,
- cross_encoder: Arc::new(cross_encoder),
- lambda_model: lambda_model.map(Arc::new),
- qa_model: qa_model.map(Arc::new),
- bangs,
- }
+ pub fn new(cluster: Arc<Cluster>) -> Self {
+ Self { cluster }
}
async fn shards(&self) -> Vec<Shard> {
@@ -292,34 +284,7 @@ impl DistributedSearcher {
.collect()
}
- fn combine_results(
- &self,
- initial_results: Vec<InitialSearchResultShard>,
- pipeline: RankingPipeline<ScoredWebsitePointer>,
- ) -> Vec<ScoredWebsitePointer> {
- let mut collector = BucketCollector::new(pipeline.collector_top_n());
-
- for result in initial_results {
- for website in result.local_result.websites {
- let pointer = ScoredWebsitePointer {
- website,
- shard: result.shard.clone(),
- };
-
- collector.insert(pointer);
- }
- }
-
- let top_websites = collector
- .into_sorted_vec(true)
- .into_iter()
- .take(pipeline.collector_top_n())
- .collect::<Vec<_>>();
-
- pipeline.apply(top_websites)
- }
-
- async fn retrieve_webpages(
+ pub async fn retrieve_webpages(
&self,
top_websites: &[ScoredWebsitePointer],
query: &str,
@@ -352,7 +317,7 @@ impl DistributedSearcher {
retrieved_webpages
}
- async fn search_initial(&self, query: &SearchQuery) -> Vec<InitialSearchResultShard> {
+ pub async fn search_initial(&self, query: &SearchQuery) -> Vec<InitialSearchResultShard> {
self.shards()
.await
.iter()
@@ -365,303 +330,7 @@ impl DistributedSearcher {
.collect::<Vec<_>>()
}
- async fn stackoverflow_sidebar(&self, query: &SearchQuery) -> Result<Option<Sidebar>> {
- let query = SearchQuery {
- query: query.query.clone(),
- num_results: 1,
- optic: Some(Optic::parse(include_str!("stackoverflow.optic")).unwrap()),
- ..Default::default()
- };
-
- let mut results: Vec<_> = self
- .search_initial(&query)
- .await
- .into_iter()
- .filter_map(|result| {
- result
- .local_result
- .websites
- .first()
- .cloned()
- .map(|website| (result.shard, website))
- })
- .collect();
-
- results.sort_by(|(_, a), (_, b)| a.score.partial_cmp(&b.score).unwrap_or(Ordering::Equal));
-
- if let Some((shard, website)) = results.pop() {
- if website.score > STACKOVERFLOW_SIDEBAR_THRESHOLD {
- let scored_websites = vec![ScoredWebsitePointer { website, shard }];
- let mut retrieved = self.retrieve_webpages(&scored_websites, &query.query).await;
-
- if let Some(res) = retrieved.pop() {
- return Ok(Some(create_stackoverflow_sidebar(res.schema_org, res.url)?));
- }
- }
- }
-
- Ok(None)
- }
-
- async fn sidebar(
- &self,
- initial_results: &[InitialSearchResultShard],
- query: &SearchQuery,
- ) -> Result<Option<Sidebar>> {
- let entity = initial_results
- .first()
- .and_then(|result| result.local_result.entity_sidebar.clone());
-
- match entity {
- Some(entity) => Ok(Some(Sidebar::Entity(entity))),
- None => Ok(self.stackoverflow_sidebar(query).await?),
- }
- }
-
- async fn check_bangs(&self, query: &SearchQuery) -> Result<Option<BangHit>> {
- let parsed_terms = query::parser::parse(&query.query);
-
- if parsed_terms.iter().any(|term| match term.as_ref() {
- query::parser::Term::PossibleBang(t) => t.is_empty(),
- _ => false,
- }) {
- let q: String = intersperse(
- parsed_terms
- .iter()
- .filter(|term| !matches!(term.as_ref(), query::parser::Term::PossibleBang(_)))
- .map(|term| term.to_string()),
- " ".to_string(),
- )
- .collect();
-
- let mut query = query.clone();
- query.query = q;
-
- let res = self.search_websites(&query).await?;
-
- return Ok(res.webpages.first().map(|webpage| BangHit {
- bang: Bang {
- category: None,
- sub_category: None,
- domain: None,
- ranking: None,
- site: None,
- tag: String::new(),
- url: webpage.url.clone(),
- },
- redirect_to: webpage.url.clone().into(),
- }));
- }
-
- Ok(self.bangs.get(&parsed_terms))
- }
-
- async fn discussions_widget(
- &self,
- query: &SearchQuery,
- ) -> Result<Option<Vec<DisplayedWebpage>>> {
- if query.optic.is_some() || query.page > 0 {
- return Ok(None);
- }
-
- const NUM_RESULTS: usize = 10;
-
- let mut query = SearchQuery {
- query: query.query.clone(),
- num_results: NUM_RESULTS,
- optic: Some(Optic::parse(include_str!("discussions.optic")).unwrap()),
- site_rankings: query.site_rankings.clone(),
- return_ranking_signals: query.return_ranking_signals,
- ..Default::default()
- };
-
- let pipeline: RankingPipeline<ScoredWebsitePointer> = RankingPipeline::reranking_for_query(
- &mut query,
- self.cross_encoder.clone(),
- self.lambda_model.clone(),
- )?;
-
- let initial_results = self.search_initial(&query).await;
-
- if initial_results.is_empty() {
- return Ok(None);
- }
-
- let num_results: usize = initial_results
- .iter()
- .map(|res| res.local_result.num_websites)
- .sum();
-
- if num_results < NUM_RESULTS / 2 {
- return Ok(None);
- }
-
- let top_websites = self.combine_results(initial_results, pipeline);
-
- let scores: Vec<_> = top_websites
- .iter()
- .map(|pointer| pointer.website.score)
- .collect();
-
- let median = if scores.len() % 2 == 0 {
- (scores[(scores.len() / 2) - 1] + scores[scores.len() / 2]) / 2.0
- } else {
- scores[scores.len() / 2]
- };
-
- if median < DISCUSSIONS_WIDGET_THRESHOLD {
- return Ok(None);
- }
-
- let mut result: Vec<DisplayedWebpage> = self
- .retrieve_webpages(&top_websites, &query.query)
- .await
- .into_iter()
- .map(DisplayedWebpage::from)
- .collect();
-
- if query.return_ranking_signals {
- self.add_ranking_signals(&mut result, &top_websites);
- }
-
- Ok(Some(result))
- }
-
- fn add_ranking_signals(
- &self,
- websites: &mut [DisplayedWebpage],
- pointers: &[ScoredWebsitePointer],
- ) {
- for (website, pointer) in websites.iter_mut().zip(pointers.iter()) {
- let mut signals = HashMap::with_capacity(ALL_SIGNALS.len());
-
- for signal in ALL_SIGNALS {
- signals.insert(
- signal,
- pointer.website.signals.get(signal).copied().unwrap_or(0.0),
- );
- }
-
- website.ranking_signals = Some(signals);
- }
- }
-
- async fn search_websites(&self, query: &SearchQuery) -> Result<WebsitesResult> {
- let start = Instant::now();
-
- if query.is_empty() {
- return Err(Error::EmptyQuery.into());
- }
-
- let mut search_query = query.clone();
- let pipeline: RankingPipeline<ScoredWebsitePointer> = RankingPipeline::reranking_for_query(
- &mut search_query,
- self.cross_encoder.clone(),
- self.lambda_model.clone(),
- )?;
-
- let initial_results = self.search_initial(&search_query).await;
-
- let sidebar = self.sidebar(&initial_results, query).await?;
- let discussions = self.discussions_widget(query).await?;
-
- let widget = self.widget(query);
-
- let spell_corrected_query = if widget.is_none() {
- initial_results
- .first()
- .and_then(|result| result.local_result.spell_corrected_query.clone())
- .map(HighlightedSpellCorrection::from)
- } else {
- None
- };
-
- let num_docs = initial_results
- .iter()
- .map(|result| result.local_result.num_websites)
- .sum();
-
- let has_more_results = initial_results.iter().any(|res| res.local_result.has_more);
- let top_websites = self.combine_results(initial_results, pipeline);
-
- // retrieve webpages
- let mut retrieved_webpages: Vec<_> = self
- .retrieve_webpages(&top_websites, &query.query)
- .await
- .into_iter()
- .map(DisplayedWebpage::from)
- .collect();
-
- if retrieved_webpages.len() != top_websites.len() {
- return Err(Error::SearchFailed.into());
- }
-
- if query.return_ranking_signals {
- self.add_ranking_signals(&mut retrieved_webpages, &top_websites);
- }
-
- let direct_answer = self.answer(&query.query, &mut retrieved_webpages);
-
- let search_duration_ms = start.elapsed().as_millis();
-
- Ok(WebsitesResult {
- spell_corrected_query,
- num_hits: num_docs,
- webpages: retrieved_webpages,
- direct_answer,
- sidebar,
- widget,
- discussions,
- search_duration_ms,
- has_more_results,
- })
- }
-
- pub async fn search(&self, query: &SearchQuery) -> Result<SearchResult> {
- if let Some(bang) = self.check_bangs(query).await? {
- return Ok(SearchResult::Bang(bang));
- }
-
- Ok(SearchResult::Websites(self.search_websites(query).await?))
- }
-
- fn widget(&self, query: &SearchQuery) -> Option<Widget> {
- if query.page > 0 {
- return None;
- }
-
- Widget::try_new(&query.query)
- }
-
- fn answer(&self, query: &str, webpages: &mut Vec<DisplayedWebpage>) -> Option<DisplayedAnswer> {
- self.qa_model.as_ref().and_then(|qa_model| {
- let contexts: Vec<_> = webpages
- .iter()
- .take(1)
- .map(|webpage| webpage.body.as_str())
- .collect();
-
- match qa_model.run(query, &contexts) {
- Some(answer) => {
- let answer_webpage = webpages.remove(answer.context_idx);
- Some(DisplayedAnswer {
- title: answer_webpage.title,
- url: answer_webpage.url,
- pretty_url: answer_webpage.pretty_url,
- snippet: generate_answer_snippet(
- &answer_webpage.body,
- answer.offset.clone(),
- ),
- answer: answer_webpage.body[answer.offset].to_string(),
- body: answer_webpage.body,
- })
- }
- None => None,
- }
- })
- }
-
- pub(crate) async fn get_webpage(&self, url: &str) -> Result<RetrievedWebpage> {
+ pub async fn get_webpage(&self, url: &str) -> Result<RetrievedWebpage> {
self.shards()
.await
.iter()
@@ -676,117 +345,17 @@ impl DistributedSearcher {
.pop()
.ok_or(Error::WebpageNotFound.into())
}
-}
-
-fn generate_answer_snippet(body: &str, answer_offset: Range<usize>) -> String {
- let mut best_start = 0;
- let mut best_end = 0;
- const SNIPPET_LENGTH: usize = 200;
-
- if body.is_empty() || answer_offset.start > body.len() - 1 {
- return body.to_string();
- }
-
- for (idx, _) in body.char_indices().filter(|(_, c)| *c == '.') {
- if idx > answer_offset.end + SNIPPET_LENGTH {
- break;
- }
-
- if idx < answer_offset.start {
- best_start = idx;
- }
-
- if idx > answer_offset.end {
- best_end = idx;
- }
- }
-
- if (answer_offset.end - best_start > SNIPPET_LENGTH) || (best_start >= best_end) {
- if answer_offset.end - answer_offset.start >= SNIPPET_LENGTH {
- let end = floor_char_boundary(body, answer_offset.start + SNIPPET_LENGTH);
-
- return "<b>".to_string() + &body[answer_offset.start..end] + "</b>";
- }
-
- let chars_either_side = (SNIPPET_LENGTH - (answer_offset.end - answer_offset.start)) / 2;
-
- let start = ceil_char_boundary(
- body,
- answer_offset
- .start
- .checked_sub(chars_either_side)
- .unwrap_or_default(),
- );
- let mut end = ceil_char_boundary(body, answer_offset.end + chars_either_side);
-
- if end >= body.len() {
- end = floor_char_boundary(body, body.len());
- }
-
- body[start..answer_offset.start].to_string()
- + "<b>"
- + &body[answer_offset.clone()]
- + "</b>"
- + &body[answer_offset.end..end]
- } else {
- let mut res = body[best_start..answer_offset.start].to_string()
- + "<b>"
- + &body[answer_offset.clone()]
- + "</b>";
-
- let remaining_chars = SNIPPET_LENGTH - (res.len() - 7);
- let end = ceil_char_boundary(body, (remaining_chars + answer_offset.end).min(best_end));
-
- res += &body[answer_offset.end..end];
-
- res
- }
-}
-#[cfg(test)]
-mod tests {
- use super::*;
- #[test]
- fn test_generate_answer_snippet() {
- assert_eq!(
- generate_answer_snippet("this is a test", 0..4),
- "<b>this</b> is a test".to_string()
- );
-
- assert_eq!(
- generate_answer_snippet("this is a test", 0..1000),
- "<b>this is a test</b>".to_string()
- );
- assert_eq!(
- generate_answer_snippet("this is a test", 1000..2000),
- "this is a test".to_string()
- );
- let input = r#"
-this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
-this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
-this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
-this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
-this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
-this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
-this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
-this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
-this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
-this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
-this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
-this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
-this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
-this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
-this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
-this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
- "#;
-
- let res = generate_answer_snippet(input, 0..500);
- assert!(!res.is_empty());
- assert!(res.len() > 100);
- assert!(res.len() < input.len());
- assert!(res.starts_with("<b>"));
- assert!(res.ends_with("</b>"));
-
- assert_eq!(generate_answer_snippet("", 0..2000), "".to_string());
+ pub async fn get_homepage_descriptions(&self, urls: &[String]) -> HashMap<Url, String> {
+ self.shards()
+ .await
+ .iter()
+ .map(|shard| shard.get_homepage_descriptions(urls))
+ .collect::<FuturesUnordered<_>>()
+ .collect::<Vec<_>>()
+ .await
+ .into_iter()
+ .flatten()
+ .collect()
}
}
diff --git a/core/src/searcher/frontend.rs b/core/src/searcher/frontend.rs
new file mode 100644
index 00000000..43ea8c41
--- /dev/null
+++ b/core/src/searcher/frontend.rs
@@ -0,0 +1,527 @@
+// Stract is an open source web search engine.
+// Copyright (C) 2023 Stract ApS
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+use std::cmp::Ordering;
+use std::collections::HashMap;
+use std::ops::Range;
+use std::sync::Arc;
+use std::time::Instant;
+
+use itertools::intersperse;
+use optics::Optic;
+
+use crate::bangs::{Bang, BangHit};
+use crate::inverted_index::RetrievedWebpage;
+use crate::ranking::ALL_SIGNALS;
+use crate::search_prettifier::{
+ create_stackoverflow_sidebar, DisplayedAnswer, DisplayedWebpage, HighlightedSpellCorrection,
+ Sidebar,
+};
+use crate::widgets::Widget;
+use crate::{
+ bangs::Bangs,
+ collector::BucketCollector,
+ distributed::cluster::Cluster,
+ qa_model::QaModel,
+ ranking::{
+ models::{cross_encoder::CrossEncoderModel, lambdamart::LambdaMART},
+ pipeline::RankingPipeline,
+ },
+};
+use crate::{ceil_char_boundary, floor_char_boundary, query, Result};
+
+use super::{
+ distributed, DistributedSearcher, InitialSearchResultShard, ScoredWebsitePointer, SearchQuery,
+ SearchResult, WebsitesResult,
+};
+
+const STACKOVERFLOW_SIDEBAR_THRESHOLD: f64 = 100.0;
+const DISCUSSIONS_WIDGET_THRESHOLD: f64 = 100.0;
+
+pub struct FrontendSearcher {
+ distributed_searcher: DistributedSearcher,
+ cross_encoder: Arc<CrossEncoderModel>,
+ lambda_model: Option<Arc<LambdaMART>>,
+ qa_model: Option<Arc<QaModel>>,
+ bangs: Bangs,
+}
+
+impl FrontendSearcher {
+ pub fn new(
+ cluster: Arc<Cluster>,
+ cross_encoder: CrossEncoderModel,
+ lambda_model: Option<LambdaMART>,
+ qa_model: Option<QaModel>,
+ bangs: Bangs,
+ ) -> Self {
+ Self {
+ distributed_searcher: DistributedSearcher::new(cluster),
+ cross_encoder: Arc::new(cross_encoder),
+ lambda_model: lambda_model.map(Arc::new),
+ qa_model: qa_model.map(Arc::new),
+ bangs,
+ }
+ }
+
+ fn combine_results(
+ &self,
+ initial_results: Vec<InitialSearchResultShard>,
+ pipeline: RankingPipeline<ScoredWebsitePointer>,
+ ) -> Vec<ScoredWebsitePointer> {
+ let mut collector = BucketCollector::new(pipeline.collector_top_n());
+
+ for result in initial_results {
+ for website in result.local_result.websites {
+ let pointer = ScoredWebsitePointer {
+ website,
+ shard: result.shard.clone(),
+ };
+
+ collector.insert(pointer);
+ }
+ }
+
+ let top_websites = collector
+ .into_sorted_vec(true)
+ .into_iter()
+ .take(pipeline.collector_top_n())
+ .collect::<Vec<_>>();
+
+ pipeline.apply(top_websites)
+ }
+
+ async fn stackoverflow_sidebar(&self, query: &SearchQuery) -> Result<Option<Sidebar>> {
+ let query = SearchQuery {
+ query: query.query.clone(),
+ num_results: 1,
+ optic: Some(Optic::parse(include_str!("stackoverflow.optic")).unwrap()),
+ ..Default::default()
+ };
+
+ let mut results: Vec<_> = self
+ .distributed_searcher
+ .search_initial(&query)
+ .await
+ .into_iter()
+ .filter_map(|result| {
+ result
+ .local_result
+ .websites
+ .first()
+ .cloned()
+ .map(|website| (result.shard, website))
+ })
+ .collect();
+
+ results.sort_by(|(_, a), (_, b)| a.score.partial_cmp(&b.score).unwrap_or(Ordering::Equal));
+
+ if let Some((shard, website)) = results.pop() {
+ if website.score > STACKOVERFLOW_SIDEBAR_THRESHOLD {
+ let scored_websites = vec![ScoredWebsitePointer { website, shard }];
+ let mut retrieved = self
+ .distributed_searcher
+ .retrieve_webpages(&scored_websites, &query.query)
+ .await;
+
+ if let Some(res) = retrieved.pop() {
+ return Ok(Some(create_stackoverflow_sidebar(res.schema_org, res.url)?));
+ }
+ }
+ }
+
+ Ok(None)
+ }
+
+ async fn sidebar(
+ &self,
+ initial_results: &[InitialSearchResultShard],
+ query: &SearchQuery,
+ ) -> Result<Option<Sidebar>> {
+ let entity = initial_results
+ .first()
+ .and_then(|result| result.local_result.entity_sidebar.clone());
+
+ match entity {
+ Some(entity) => Ok(Some(Sidebar::Entity(entity))),
+ None => Ok(self.stackoverflow_sidebar(query).await?),
+ }
+ }
+
+ async fn check_bangs(&self, query: &SearchQuery) -> Result<Option<BangHit>> {
+ let parsed_terms = query::parser::parse(&query.query);
+
+ if parsed_terms.iter().any(|term| match term.as_ref() {
+ query::parser::Term::PossibleBang(t) => t.is_empty(),
+ _ => false,
+ }) {
+ let q: String = intersperse(
+ parsed_terms
+ .iter()
+ .filter(|term| !matches!(term.as_ref(), query::parser::Term::PossibleBang(_)))
+ .map(|term| term.to_string()),
+ " ".to_string(),
+ )
+ .collect();
+
+ let mut query = query.clone();
+ query.query = q;
+
+ let res = self.search_websites(&query).await?;
+
+ return Ok(res.webpages.first().map(|webpage| BangHit {
+ bang: Bang {
+ category: None,
+ sub_category: None,
+ domain: None,
+ ranking: None,
+ site: None,
+ tag: String::new(),
+ url: webpage.url.clone(),
+ },
+ redirect_to: webpage.url.clone().into(),
+ }));
+ }
+
+ Ok(self.bangs.get(&parsed_terms))
+ }
+
+ async fn discussions_widget(
+ &self,
+ query: &SearchQuery,
+ ) -> Result<Option<Vec<DisplayedWebpage>>> {
+ if query.optic.is_some() || query.page > 0 {
+ return Ok(None);
+ }
+
+ const NUM_RESULTS: usize = 10;
+
+ let mut query = SearchQuery {
+ query: query.query.clone(),
+ num_results: NUM_RESULTS,
+ optic: Some(Optic::parse(include_str!("discussions.optic")).unwrap()),
+ site_rankings: query.site_rankings.clone(),
+ return_ranking_signals: query.return_ranking_signals,
+ ..Default::default()
+ };
+
+ let pipeline: RankingPipeline<ScoredWebsitePointer> = RankingPipeline::reranking_for_query(
+ &mut query,
+ self.cross_encoder.clone(),
+ self.lambda_model.clone(),
+ )?;
+
+ let initial_results = self.distributed_searcher.search_initial(&query).await;
+
+ if initial_results.is_empty() {
+ return Ok(None);
+ }
+
+ let num_results: usize = initial_results
+ .iter()
+ .map(|res| res.local_result.num_websites)
+ .sum();
+
+ if num_results < NUM_RESULTS / 2 {
+ return Ok(None);
+ }
+
+ let top_websites = self.combine_results(initial_results, pipeline);
+
+ let scores: Vec<_> = top_websites
+ .iter()
+ .map(|pointer| pointer.website.score)
+ .collect();
+
+ let median = if scores.len() % 2 == 0 {
+ (scores[(scores.len() / 2) - 1] + scores[scores.len() / 2]) / 2.0
+ } else {
+ scores[scores.len() / 2]
+ };
+
+ if median < DISCUSSIONS_WIDGET_THRESHOLD {
+ return Ok(None);
+ }
+
+ let mut result: Vec<DisplayedWebpage> = self
+ .distributed_searcher
+ .retrieve_webpages(&top_websites, &query.query)
+ .await
+ .into_iter()
+ .map(DisplayedWebpage::from)
+ .collect();
+
+ if query.return_ranking_signals {
+ self.add_ranking_signals(&mut result, &top_websites);
+ }
+
+ Ok(Some(result))
+ }
+
+ fn add_ranking_signals(
+ &self,
+ websites: &mut [DisplayedWebpage],
+ pointers: &[ScoredWebsitePointer],
+ ) {
+ for (website, pointer) in websites.iter_mut().zip(pointers.iter()) {
+ let mut signals = HashMap::with_capacity(ALL_SIGNALS.len());
+
+ for signal in ALL_SIGNALS {
+ signals.insert(
+ signal,
+ pointer.website.signals.get(signal).copied().unwrap_or(0.0),
+ );
+ }
+
+ website.ranking_signals = Some(signals);
+ }
+ }
+
+ async fn search_websites(&self, query: &SearchQuery) -> Result<WebsitesResult> {
+ let start = Instant::now();
+
+ if query.is_empty() {
+ return Err(distributed::Error::EmptyQuery.into());
+ }
+
+ let mut search_query = query.clone();
+ let pipeline: RankingPipeline<ScoredWebsitePointer> = RankingPipeline::reranking_for_query(
+ &mut search_query,
+ self.cross_encoder.clone(),
+ self.lambda_model.clone(),
+ )?;
+
+ let initial_results = self
+ .distributed_searcher
+ .search_initial(&search_query)
+ .await;
+
+ let sidebar = self.sidebar(&initial_results, query).await?;
+ let discussions = self.discussions_widget(query).await?;
+
+ let widget = self.widget(query);
+
+ let spell_corrected_query = if widget.is_none() {
+ initial_results
+ .first()
+ .and_then(|result| result.local_result.spell_corrected_query.clone())
+ .map(HighlightedSpellCorrection::from)
+ } else {
+ None
+ };
+
+ let num_docs = initial_results
+ .iter()
+ .map(|result| result.local_result.num_websites)
+ .sum();
+
+ let has_more_results = initial_results.iter().any(|res| res.local_result.has_more);
+ let top_websites = self.combine_results(initial_results, pipeline);
+
+ // retrieve webpages
+ let mut retrieved_webpages: Vec<_> = self
+ .distributed_searcher
+ .retrieve_webpages(&top_websites, &query.query)
+ .await
+ .into_iter()
+ .map(DisplayedWebpage::from)
+ .collect();
+
+ if retrieved_webpages.len() != top_websites.len() {
+ return Err(distributed::Error::SearchFailed.into());
+ }
+
+ if query.return_ranking_signals {
+ self.add_ranking_signals(&mut retrieved_webpages, &top_websites);
+ }
+
+ let direct_answer = self.answer(&query.query, &mut retrieved_webpages);
+
+ let search_duration_ms = start.elapsed().as_millis();
+
+ Ok(WebsitesResult {
+ spell_corrected_query,
+ num_hits: num_docs,
+ webpages: retrieved_webpages,
+ direct_answer,
+ sidebar,
+ widget,
+ discussions,
+ search_duration_ms,
+ has_more_results,
+ })
+ }
+
+ pub async fn search(&self, query: &SearchQuery) -> Result<SearchResult> {
+ if let Some(bang) = self.check_bangs(query).await? {
+ return Ok(SearchResult::Bang(bang));
+ }
+
+ Ok(SearchResult::Websites(self.search_websites(query).await?))
+ }
+
+ fn widget(&self, query: &SearchQuery) -> Option<Widget> {
+ if query.page > 0 {
+ return None;
+ }
+
+ Widget::try_new(&query.query)
+ }
+
+ fn answer(&self, query: &str, webpages: &mut Vec<DisplayedWebpage>) -> Option<DisplayedAnswer> {
+ self.qa_model.as_ref().and_then(|qa_model| {
+ let contexts: Vec<_> = webpages
+ .iter()
+ .take(1)
+ .map(|webpage| webpage.body.as_str())
+ .collect();
+
+ match qa_model.run(query, &contexts) {
+ Some(answer) => {
+ let answer_webpage = webpages.remove(answer.context_idx);
+ Some(DisplayedAnswer {
+ title: answer_webpage.title,
+ url: answer_webpage.url,
+ pretty_url: answer_webpage.pretty_url,
+ snippet: generate_answer_snippet(
+ &answer_webpage.body,
+ answer.offset.clone(),
+ ),
+ answer: answer_webpage.body[answer.offset].to_string(),
+ body: answer_webpage.body,
+ })
+ }
+ None => None,
+ }
+ })
+ }
+
+ pub async fn get_webpage(&self, url: &str) -> Result<RetrievedWebpage> {
+ self.distributed_searcher.get_webpage(url).await
+ }
+}
+
+fn generate_answer_snippet(body: &str, answer_offset: Range<usize>) -> String {
+ let mut best_start = 0;
+ let mut best_end = 0;
+ const SNIPPET_LENGTH: usize = 200;
+
+ if body.is_empty() || answer_offset.start > body.len() - 1 {
+ return body.to_string();
+ }
+
+ for (idx, _) in body.char_indices().filter(|(_, c)| *c == '.') {
+ if idx > answer_offset.end + SNIPPET_LENGTH {
+ break;
+ }
+
+ if idx < answer_offset.start {
+ best_start = idx;
+ }
+
+ if idx > answer_offset.end {
+ best_end = idx;
+ }
+ }
+
+ if (answer_offset.end - best_start > SNIPPET_LENGTH) || (best_start >= best_end) {
+ if answer_offset.end - answer_offset.start >= SNIPPET_LENGTH {
+ let end = floor_char_boundary(body, answer_offset.start + SNIPPET_LENGTH);
+
+ return "<b>".to_string() + &body[answer_offset.start..end] + "</b>";
+ }
+
+ let chars_either_side = (SNIPPET_LENGTH - (answer_offset.end - answer_offset.start)) / 2;
+
+ let start = ceil_char_boundary(
+ body,
+ answer_offset
+ .start
+ .checked_sub(chars_either_side)
+ .unwrap_or_default(),
+ );
+ let mut end = ceil_char_boundary(body, answer_offset.end + chars_either_side);
+
+ if end >= body.len() {
+ end = floor_char_boundary(body, body.len());
+ }
+
+ body[start..answer_offset.start].to_string()
+ + "<b>"
+ + &body[answer_offset.clone()]
+ + "</b>"
+ + &body[answer_offset.end..end]
+ } else {
+ let mut res = body[best_start..answer_offset.start].to_string()
+ + "<b>"
+ + &body[answer_offset.clone()]
+ + "</b>";
+
+ let remaining_chars = SNIPPET_LENGTH - (res.len() - 7);
+ let end = ceil_char_boundary(body, (remaining_chars + answer_offset.end).min(best_end));
+
+ res += &body[answer_offset.end..end];
+
+ res
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn test_generate_answer_snippet() {
+ assert_eq!(
+ generate_answer_snippet("this is a test", 0..4),
+ "<b>this</b> is a test".to_string()
+ );
+
+ assert_eq!(
+ generate_answer_snippet("this is a test", 0..1000),
+ "<b>this is a test</b>".to_string()
+ );
+ assert_eq!(
+ generate_answer_snippet("this is a test", 1000..2000),
+ "this is a test".to_string()
+ );
+ let input = r#"
+this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
+this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
+this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
+this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
+this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
+this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
+this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
+this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
+this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
+this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
+this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
+this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
+this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
+this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
+this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
+this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test this is a long test
+ "#;
+
+ let res = generate_answer_snippet(input, 0..500);
+ assert!(!res.is_empty());
+ assert!(res.len() > 100);
+ assert!(res.len() < input.len());
+ assert!(res.starts_with("<b>"));
+ assert!(res.ends_with("</b>"));
+
+ assert_eq!(generate_answer_snippet("", 0..2000), "".to_string());
+ }
+}
diff --git a/core/src/searcher/local.rs b/core/src/searcher/local.rs
index 167762fe..2e1599c4 100644
--- a/core/src/searcher/local.rs
+++ b/core/src/searcher/local.rs
@@ -393,6 +393,10 @@ impl LocalSearcher {
pub fn get_webpage(&self, url: &str) -> Option<RetrievedWebpage> {
self.index.get_webpage(url)
}
+
+ pub fn get_homepage(&self, url: &str) -> Option<RetrievedWebpage> {
+ self.index.get_homepage(url)
+ }
}
#[cfg(test)]
diff --git a/core/src/searcher/mod.rs b/core/src/searcher/mod.rs
index a6c5cb73..9204ac3a 100644
--- a/core/src/searcher/mod.rs
+++ b/core/src/searcher/mod.rs
@@ -15,6 +15,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pub mod distributed;
+pub mod frontend;
pub mod local;
pub use distributed::*;
diff --git a/core/src/webpage/mod.rs b/core/src/webpage/mod.rs
index 3abc99a7..be948834 100644
--- a/core/src/webpage/mod.rs
+++ b/core/src/webpage/mod.rs
@@ -414,6 +414,12 @@ impl Html {
}
while let Some((text, attributes)) = open_links.pop() {
+ if let Some(rel) = attributes.borrow().get("rel") {
+ if rel.contains("nofollow") {
+ continue;
+ }
+ }
+
if let Some(dest) = attributes.borrow().get("href") {
links.push(Link {
source: self.url.clone(),
@@ -426,7 +432,7 @@ impl Html {
links
}
- fn links_tag(&self) -> Vec<Link> {
+ fn _links_tag(&self) -> Vec<Link> {
let mut links = Vec::new();
for node in self.root.select("link").unwrap() {
@@ -444,7 +450,7 @@ impl Html {
links
}
- fn metadata_links(&self) -> Vec<Link> {
+ fn _metadata_links(&self) -> Vec<Link> {
self.metadata()
.into_iter()
.filter_map(|metadata| {
@@ -498,30 +504,31 @@ impl Html {
}
pub fn links(&self) -> Vec<Link> {
- let mut links = self.hyperlinks();
-
- links.extend(self.scripts().into_iter().filter_map(|script| {
- match script.attributes.get("src") {
- Some(url) => {
- let script_url = Url::from(url.as_str());
- if self.url().domain() != script_url.domain() {
- Some(Link {
- source: self.url.clone(),
- destination: script_url,
- text: String::new(),
- })
- } else {
- None
- }
- }
- None => None,
- }
- }));
-
- links.extend(self.links_tag().into_iter());
- links.extend(self.metadata_links().into_iter());
-
- links
+ // let mut links = self.hyperlinks();
+
+ // links.extend(self.scripts().into_iter().filter_map(|script| {
+ // match script.attributes.get("src") {
+ // Some(url) => {
+ // let script_url = Url::from(url.as_str());
+ // if self.url().domain() != script_url.domain() {
+ // Some(Link {
+ // source: self.url.clone(),
+ // destination: script_url,
+ // text: String::new(),
+ // })
+ // } else {
+ // None
+ // }
+ // }
+ // None => None,
+ // }
+ // }));
+
+ // links.extend(self.links_tag().into_iter());
+ // links.extend(self.metadata_links().into_iter());
+
+ // links
+ self.hyperlinks()
}
pub fn favicon(&self) -> Option<FaviconLink> {
@@ -804,6 +811,23 @@ impl Html {
Field::Text(TextField::Url) => {
doc.add_pre_tokenized_text(tantivy_field, url.clone())
}
+ Field::Text(TextField::UrlNoTokenizer) => {
+ let url = self.url().full();
+
+ doc.add_pre_tokenized_text(
+ tantivy_field,
+ PreTokenizedString {
+ text: url.clone(),
+ tokens: vec![tantivy::tokenizer::Token {
+ offset_from: 0,
+ offset_to: url.len(),
+ position: 0,
+ text: url,
+ position_length: 1,
+ }],
+ },
+ );
+ }
Field::Text(TextField::Site) => {
doc.add_pre_tokenized_text(tantivy_field, site.clone())
}
@@ -823,6 +847,25 @@ impl Html {
}],
},
),
+ Field::Text(TextField::SiteIfHomepageNoTokenizer) => {
+ if self.url().is_homepage() {
+ doc.add_pre_tokenized_text(
+ tantivy_field,
+ PreTokenizedString {
+ text: self.url().site().to_string(),
+ tokens: vec![tantivy::tokenizer::Token {
+ offset_from: 0,
+ offset_to: self.url().site().len(),
+ position: 0,
+ text: self.url().site().to_string(),
+ position_length: 1,
+ }],
+ },
+ )
+ } else {
+ doc.add_text(tantivy_field, "");
+ }
+ }
Field::Text(TextField::DomainNoTokenizer) => doc.add_pre_tokenized_text(
tantivy_field,
PreTokenizedString {
@@ -1908,16 +1951,16 @@ mod tests {
destination: "example.com".to_string().into(),
text: "Link to example".to_string()
},
- Link {
- source: "https://www.example.com/whatever".to_string().into(),
- destination: "test.com".to_string().into(),
- text: String::new()
- },
- Link {
- source: "https://www.example.com/whatever".to_string().into(),
- destination: "link.com".to_string().into(),
- text: String::new()
- },
+ // Link {
+ // source: "https://www.example.com/whatever".to_string().into(),
+ // destination: "test.com".to_string().into(),
+ // text: String::new()
+ // },
+ // Link {
+ // source: "https://www.example.com/whatever".to_string().into(),
+ // destination: "link.com".to_string().into(),
+ // text: String::new()
+ // },
]
);
}
diff --git a/frontend/src/pages/explore.astro b/frontend/src/pages/explore.astro
index da9fbb42..afc76bc6 100644
--- a/frontend/src/pages/explore.astro
+++ b/frontend/src/pages/explore.astro
@@ -25,7 +25,7 @@ import { askama } from "../askama";
<button id="add-site-btn" class="bg-brand text-sm text-white opacity-75 hover:opacity-100 transition-colors duration-50 rounded-full py-2 px-5">Add</button>
</div>
<label class="text-red-600 mb-4 hidden" for="site-input" id="site-input-error">Unfortunately, we don't know about that site yet.</label>
- <div class="flex flex-wrap gap-x-5 gap-y-2" id="sites-list"></div>
+ <div class="flex flex-wrap gap-x-5 gap-y-3" id="sites-list"></div>
</div>
<div class="hidden" id="result-container">
@@ -46,7 +46,7 @@ import { askama } from "../askama";
</div>
<a href="#" download="exported.optic" class="bg-brand text-white opacity-75 hover:opacity-100 transition-colors duration-50 rounded-full py-2 px-5" id="export-optic">Export as optic</a>
</div>
- <div id="result" class="grid grid-cols-[1fr_1fr_6fr]"></div>
+ <div id="result" class="grid grid-cols-[1fr_1fr_6fr] gap-y-2"></div>
<div class="w-full flex justify-center">
<div class="w-6 h-6 cursor-pointer rounded-full text-brand_contrast" id="more-btn">
<Hero icon={"chevron-down"} />
@@ -204,6 +204,7 @@ import { askama } from "../askama";
})
.then(response => response.json())
.then(data => {
+ console.log(data);
resultContainer.classList.remove("hidden");
result.innerHTML = "";
@@ -211,7 +212,7 @@ import { askama } from "../askama";
similarSites = data.map((res: {site: string, score: number}) => res.site);
- data.forEach((res: {site: string, score: number}) => {
+ data.forEach((res: {site: string, score: number, description: string | null}) => {
const addSiteDiv = document.createElement("div");
addSiteDiv.style.width = "1rem";
@@ -232,8 +233,11 @@ import { askama } from "../askama";
scoreDiv.innerHTML = res.score.toFixed(2);
result.appendChild(scoreDiv);
+ const desc = res.description === null ? "" : res.description;
+
const siteDiv = document.createElement("div");
siteDiv.innerHTML = "<a target=\"_blank\" class=\"underline\" href=\"https://" + res.site + "\">" + res.site + "</a>";
+ siteDiv.innerHTML += "<p class=\"text-sm\">" + desc + "</p>";
result.appendChild(siteDiv);
});