Shorten workspace directory names to app, bot and core

This commit is contained in:
2026-12-03 04:26:31 +08:00
parent 3ae1097e1b
commit ef251ae339
28 changed files with 4 additions and 4 deletions
+77
View File
@@ -0,0 +1,77 @@
use jieba_rs::Jieba;
use std::{collections::BTreeSet, sync::OnceLock};
use unicode_normalization::UnicodeNormalization;
pub(crate) fn normalize(text: &str) -> String {
text.nfkc()
.flat_map(char::to_lowercase)
.collect::<String>()
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
}
fn han(c: char) -> bool {
matches!(c as u32, 0x3400..=0x4dbf | 0x4e00..=0x9fff | 0xf900..=0xfaff | 0x20000..=0x323af)
}
// Keep individual Han characters in the index for one-character queries;
// for longer Han runs query only the more selective overlapping bigrams.
fn tokens(text: &str, indexing: bool) -> Vec<String> {
let mut output = Vec::new();
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if han(c) {
let mut previous = c;
let mut single = true;
if indexing {
output.push(c.to_string());
}
while let Some(next) = chars.next_if(|&n| han(n)) {
output.push(format!("{previous}{next}"));
if indexing {
output.push(next.to_string());
}
single = false;
previous = next;
}
if single && !indexing {
output.push(c.to_string());
}
} else if c.is_alphanumeric() || c == '_' {
let mut word = String::from(c);
while let Some(next) = chars.next_if(|&n| !han(n) && (n.is_alphanumeric() || n == '_'))
{
word.push(next);
}
output.push(word);
}
}
output
}
pub(crate) fn index_tokens(text: &str) -> Vec<String> {
tokens(text, true)
}
pub(crate) fn query_terms(text: &str) -> BTreeSet<String> {
static LEXICON: OnceLock<Jieba> = OnceLock::new();
let mut terms = BTreeSet::new();
let mut rest = text;
while let Some(first) = rest.chars().next() {
let is_han = han(first);
let end = rest.find(|c: char| han(c) != is_han).unwrap_or(rest.len());
let (run, tail) = rest.split_at(end);
if is_han {
// Segment only the query. The existing character/bigram postings can
// match each dictionary word even in names absent from the dictionary.
for word in LEXICON.get_or_init(Jieba::new).cut(run, false) {
terms.extend(tokens(word, false));
}
} else {
terms.extend(tokens(run, false));
}
rest = tail;
}
terms
}
+33
View File
@@ -0,0 +1,33 @@
pub(crate) mod analysis;
pub(crate) mod rank;
pub(crate) mod retrieve;
mod scope;
use crate::{Document, Kind, Media};
#[derive(Clone, Debug)]
pub struct Query<'a> {
pub text: &'a str,
pub kind: Option<Kind>,
pub media: Option<Media>,
pub offset: usize,
pub limit: usize,
}
impl<'a> Query<'a> {
pub fn new(text: &'a str) -> Self {
Self {
text,
kind: None,
media: None,
offset: 0,
limit: 10,
}
}
}
#[derive(Debug)]
pub struct SearchPage {
pub total: usize,
pub hits: Vec<Document>,
}
+18
View File
@@ -0,0 +1,18 @@
// BM25F: normalize field frequencies before saturation. Title/username share
// the short field. Corpus-wide document frequency is counted once per term.
pub(crate) fn term_score(
counts: [usize; 2],
lengths: [usize; 2],
averages: [f64; 2],
n: usize,
df: usize,
) -> f64 {
let weights = [3.0, 1.0];
let mut frequency = 0.0;
for field in 0..2 {
let norm = 0.25 + 0.75 * lengths[field] as f64 / averages[field].max(1.0);
frequency += weights[field] * counts[field] as f64 / norm;
}
let idf = (1.0 + ((n - df) as f64 + 0.5) / (df as f64 + 0.5)).ln();
idf * (2.2 * frequency) / (1.2 + frequency)
}
+122
View File
@@ -0,0 +1,122 @@
use super::{analysis, rank, scope::Scope};
use crate::{index::IndexReader, DocumentId, Kind, Query, SearchPage};
use std::{
cmp::{Ordering, Reverse},
collections::BinaryHeap,
};
#[derive(Debug)]
struct Hit {
exact: bool,
score: f64,
id: DocumentId,
}
impl Ord for Hit {
fn cmp(&self, other: &Self) -> Ordering {
self.exact
.cmp(&other.exact)
.then_with(|| self.score.total_cmp(&other.score))
.then_with(|| other.id.cmp(&self.id))
}
}
impl PartialOrd for Hit {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Hit {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Hit {}
pub(crate) fn retrieve<R: IndexReader>(reader: &R, query: &Query) -> Result<SearchPage, R::Error> {
let empty = || SearchPage {
total: 0,
hits: Vec::new(),
};
let normalized = analysis::normalize(query.text);
let Some((scope, text)) = Scope::parse(&normalized) else {
return Ok(empty());
};
// Only closed quote pairs are operators; an unmatched trailing quote is punctuation.
let parts: Vec<_> = text.split('"').skip(1).collect();
let phrases: Vec<_> = parts
.chunks_exact(2)
.map(|pair| pair[0].trim())
.filter(|phrase| !phrase.is_empty())
.collect();
let mut lists = Vec::new();
for term in analysis::query_terms(text) {
let Some(postings) = reader.postings(&term)? else {
return Ok(empty());
};
lists.push(postings);
}
lists.sort_unstable_by_key(|list| list.len());
let Some(first) = lists.first() else {
return Ok(empty());
};
let (n, lengths) = reader.statistics()?;
let avg = lengths.map(|length| length as f64 / n.max(1) as f64);
let mut best = BinaryHeap::new();
let mut total = 0;
let window = query.offset.saturating_add(query.limit);
for id in first.keys() {
if !lists[1..].iter().all(|list| list.contains_key(id)) {
continue;
}
let entry = reader.document(*id)?;
if !scope.accepts(&entry)
|| query.kind.is_some_and(|kind| kind != entry.document.kind())
|| query
.media
.is_some_and(|media| Some(media) != entry.document.media)
{
continue;
}
if !phrases
.iter()
.all(|phrase| entry.title.contains(phrase) || entry.body.contains(phrase))
{
continue;
}
total += 1;
if query.limit == 0 || query.offset >= first.len() {
continue;
}
let mut score: f64 = lists
.iter()
.map(|list| rank::term_score(list[id], entry.lengths, avg, n, list.len()))
.sum();
if entry.title.contains(text) {
score += 2.0;
} else if entry.body.contains(text) {
score += 0.5;
}
let exact = entry.document.kind() != Kind::Post
&& (entry.title == text
|| entry.document.username.as_str() == text.trim_start_matches('@'));
let hit = Hit {
exact,
score,
id: *id,
};
if best.len() < window {
best.push(Reverse(hit));
} else if let Some(mut worst) = best.peek_mut() {
if hit > worst.0 {
*worst = Reverse(hit);
}
}
}
let hits = best
.into_sorted_vec()
.into_iter()
.skip(query.offset)
.map(|Reverse(hit)| reader.document(hit.id).map(|entry| entry.document.clone()))
.collect::<Result<Vec<_>, _>>()?;
Ok(SearchPage { total, hits })
}
+42
View File
@@ -0,0 +1,42 @@
//! Leading source and exclusion filters in normalized search text.
use crate::{index::IndexedDocument, PublicName};
#[derive(Default)]
pub(super) struct Scope<'a> {
source: Option<PublicName>,
excluded: Vec<&'a str>,
}
impl<'a> Scope<'a> {
pub fn parse(mut text: &'a str) -> Option<(Self, &'a str)> {
let mut scope = Self::default();
loop {
let (token, rest) = text.split_once(' ').unwrap_or((text, ""));
if let Some(source) = token.strip_prefix("from:") {
let name = PublicName::new(source)?;
if scope.source.as_ref().is_some_and(|s| s != &name) {
return None;
}
scope.source = Some(name);
} else if let Some(fragment) = token.strip_prefix("exclude:") {
if fragment.is_empty() {
return None;
}
scope.excluded.push(fragment);
} else {
return Some((scope, text));
}
text = rest;
}
}
pub fn accepts(&self, entry: &IndexedDocument) -> bool {
self.source
.as_ref()
.is_none_or(|s| s == &entry.document.username)
&& !self
.excluded
.iter()
.any(|f| entry.title.contains(f) || entry.body.contains(f))
}
}