airust 0.2.18

A modular Rust knowledge engine: lexical search, text matching, optional semantic retrieval and reranking
Documentation
use sha2::{Digest, Sha256};
use std::sync::Arc;

use super::models::BotConfig;
use crate::web::db::Database;

pub struct ProcessorBot;

#[derive(Debug, Clone)]
pub struct QAPair {
    pub input: String,
    pub output: String,
}

impl ProcessorBot {
    pub fn process(db: &Arc<Database>, config: &BotConfig) -> Result<(i64, i64), String> {
        let pending = db.get_pending_raw_data()?;
        let mut items_found: i64 = 0;
        let mut items_added: i64 = 0;

        for raw in &pending {
            if Self::is_binary_content(&raw.content) {
                eprintln!("Skipping binary content for raw_data id={}", raw.id);
                db.approve_raw_data(raw.id)?;
                continue;
            }

            db.approve_raw_data(raw.id)?;

            let cleaned = Self::clean_content(&raw.content);
            if cleaned.is_empty() {
                continue;
            }

            let mut pairs = match config.strategy.as_str() {
                "paragraph" => Self::strategy_paragraph(&cleaned, config.min_length),
                "sentence" => Self::strategy_sentence(&cleaned, config.min_length),
                _ => Self::strategy_heading_content(&cleaned, config.min_length),
            };

            if let Some(ref title) = raw.title {
                let summary_pairs = Self::generate_page_summary_qa(title, &cleaned);
                pairs.extend(summary_pairs);
            }

            items_found += pairs.len() as i64;

            for pair in pairs {
                let mut hasher = Sha256::new();
                hasher.update(format!("{}:{}", pair.input, pair.output).as_bytes());
                let hash = format!("{:x}", hasher.finalize());

                let existing = db.insert_raw_data(
                    raw.bot_run_id,
                    raw.url.as_deref(),
                    Some(&pair.input),
                    &pair.output,
                    &hash,
                )?;

                if existing > 0 {
                    db.insert_approved_data(
                        Some(raw.id),
                        &pair.input,
                        &pair.output,
                        1.0,
                        raw.url.as_deref(),
                    )?;
                    items_added += 1;
                }
            }
        }

        Ok((items_found, items_added))
    }

    fn is_binary_content(text: &str) -> bool {
        let total = text.chars().count();
        if total == 0 {
            return true;
        }

        let non_printable = text
            .chars()
            .filter(|c| {
                !c.is_alphanumeric()
                    && !c.is_whitespace()
                    && !c.is_ascii_punctuation()
                    && *c != 'ä'
                    && *c != 'ö'
                    && *c != 'ü'
                    && *c != 'Ä'
                    && *c != 'Ö'
                    && *c != 'Ü'
                    && *c != 'ß'
                    && *c != 'é'
                    && *c != 'è'
                    && *c != 'à'
                    && *c != 'ñ'
            })
            .count();

        let replacements = text.chars().filter(|&c| c == '\u{FFFD}').count();
        non_printable as f64 / total as f64 > 0.10 || replacements as f64 / total as f64 > 0.10
    }

    fn clean_content(text: &str) -> String {
        if Self::is_binary_content(text) {
            return String::new();
        }

        let lines: Vec<String> = text
            .lines()
            .map(|line| {
                let mut result = String::new();
                let mut prev_space = false;
                for c in line.trim().chars() {
                    if c.is_whitespace() {
                        if !prev_space {
                            result.push(' ');
                            prev_space = true;
                        }
                    } else {
                        result.push(c);
                        prev_space = false;
                    }
                }
                result
            })
            .filter(|line| !line.trim().is_empty())
            .collect();

        lines.join("\n")
    }

    fn heading_to_question(heading: &str) -> String {
        let h = heading.trim();

        if h.ends_with('?') {
            return h.to_string();
        }

        let lower = h.to_lowercase();

        if lower.starts_with("über ") || lower == "über uns" {
            return format!(
                "What can be learned about {}?",
                h[5..].trim_end_matches(':')
            );
        }
        if lower.starts_with("about ") || lower == "about us" {
            return format!("What is {}?", h[6..].trim_end_matches(':'));
        }
        if lower.starts_with("how to") || lower.starts_with("wie ") {
            return format!("{}?", h.trim_end_matches(':'));
        }
        if lower.starts_with("warum") || lower.starts_with("why") {
            return format!("{}?", h.trim_end_matches(':'));
        }
        if lower.starts_with("kontakt") || lower.starts_with("contact") {
            return format!("How can {} be contacted?", h.trim_end_matches(':'));
        }
        if lower.starts_with("faq") || lower.starts_with("häufige fragen") {
            return format!(
                "What frequently asked questions concern {}?",
                h.trim_end_matches(':')
            );
        }

        format!("What is {}?", h.trim_end_matches(':'))
    }

    fn truncate_at_sentence(text: &str, max_len: usize) -> String {
        if text.len() <= max_len {
            return text.to_string();
        }

        let truncated = &text[..max_len];

        let last_period = truncated.rfind(". ");
        let last_excl = truncated.rfind("! ");
        let last_quest = truncated.rfind("? ");

        let best = [last_period, last_excl, last_quest]
            .iter()
            .filter_map(|&pos| pos)
            .max();

        match best {
            Some(pos) => text[..=pos].trim().to_string(),
            None => match truncated.rfind(' ') {
                Some(pos) => format!("{}...", text[..pos].trim()),
                None => format!("{}...", truncated),
            },
        }
    }

    fn split_sentences(text: &str) -> Vec<String> {
        let mut sentences = Vec::new();
        let mut current = String::new();
        let chars: Vec<char> = text.chars().collect();
        let len = chars.len();
        let mut i = 0;

        let abbrevs = [
            "Dr.", "Mr.", "Mrs.", "Ms.", "Prof.", "Nr.", "St.", "Str.", "z.B.", "d.h.", "u.a.",
            "o.ä.", "etc.", "bzw.", "inkl.", "zzgl.", "ca.", "max.", "min.", "tel.", "Tel.",
            "Fax.", "Abs.", "e.V.", "i.d.R.", "u.U.", "z.T.",
        ];

        while i < len {
            current.push(chars[i]);

            if (chars[i] == '.' || chars[i] == '!' || chars[i] == '?')
                && i + 1 < len
                && chars[i + 1].is_whitespace()
            {
                let current_trimmed = current.trim();
                let is_abbrev = abbrevs.iter().any(|a| current_trimmed.ends_with(a));

                if !is_abbrev {
                    let sentence = current.trim().to_string();
                    if !sentence.is_empty() {
                        sentences.push(sentence);
                    }
                    current = String::new();
                }
            }
            i += 1;
        }

        let remainder = current.trim().to_string();
        if !remainder.is_empty() {
            sentences.push(remainder);
        }

        sentences
    }

    fn sentence_to_question(sentence: &str) -> String {
        let s = sentence
            .trim()
            .trim_end_matches('.')
            .trim_end_matches('!')
            .trim();
        if s.ends_with('?') {
            return s.to_string();
        }
        if s.is_empty() {
            return String::new();
        }

        let lower = s.to_lowercase();
        if lower.starts_with("wir ")
            || lower.starts_with("unser")
            || lower.starts_with("die ")
            || lower.starts_with("das ")
            || lower.starts_with("der ")
        {
            format!("What does this mean: {}?", s)
        } else {
            format!("What is {}?", s)
        }
    }

    fn strategy_heading_content(content: &str, min_length: usize) -> Vec<QAPair> {
        let mut pairs = Vec::new();
        let lines: Vec<&str> = content.lines().collect();
        let mut i = 0;

        while i < lines.len() {
            let line = lines[i].trim();

            let is_heading = !line.is_empty()
                && line.len() < 100
                && !line.ends_with('.')
                && (line
                    .chars()
                    .next()
                    .map(|c| c.is_uppercase())
                    .unwrap_or(false));

            if is_heading && i + 1 < lines.len() {
                let mut body = Vec::new();
                let mut j = i + 1;
                while j < lines.len() {
                    let next = lines[j].trim();
                    if next.is_empty() && !body.is_empty() {
                        break;
                    }
                    if !next.is_empty() {
                        body.push(next);
                    }
                    j += 1;
                }

                let full_answer = body.join(" ");
                let answer = Self::truncate_at_sentence(&full_answer, 500);

                if line.len() >= min_length && answer.len() >= min_length {
                    let question = Self::heading_to_question(line);
                    pairs.push(QAPair {
                        input: question,
                        output: answer,
                    });
                }
                i = j;
            } else {
                i += 1;
            }
        }

        pairs
    }

    fn strategy_paragraph(content: &str, min_length: usize) -> Vec<QAPair> {
        let mut pairs = Vec::new();
        let paragraphs: Vec<&str> = content.split("\n\n").collect();

        for para in paragraphs {
            let text = para.trim();
            if text.len() < min_length {
                continue;
            }

            let sentences = Self::split_sentences(text);
            if sentences.is_empty() {
                continue;
            }

            let first_sentence = sentences[0].trim();
            if first_sentence.len() >= min_length && text.len() > first_sentence.len() {
                let question = Self::sentence_to_question(first_sentence);
                let answer = Self::truncate_at_sentence(text, 500);
                if !question.is_empty() {
                    pairs.push(QAPair {
                        input: question,
                        output: answer,
                    });
                }
            }
        }

        pairs
    }

    fn strategy_sentence(content: &str, min_length: usize) -> Vec<QAPair> {
        let mut pairs = Vec::new();
        let sentences = Self::split_sentences(content);
        let filtered: Vec<&String> = sentences.iter().filter(|s| s.len() >= min_length).collect();

        for chunk in filtered.chunks(2) {
            if chunk.len() == 2 {
                let question = Self::sentence_to_question(chunk[0]);
                let answer = Self::truncate_at_sentence(chunk[1], 500);
                if !question.is_empty() {
                    pairs.push(QAPair {
                        input: question,
                        output: answer,
                    });
                }
            }
        }

        pairs
    }

    fn generate_page_summary_qa(title: &str, content: &str) -> Vec<QAPair> {
        let mut pairs = Vec::new();
        let title = title.trim();

        if title.is_empty() || title.len() < 3 || content.trim().is_empty() {
            return pairs;
        }

        let first_para = content.split("\n\n").next().unwrap_or(content).trim();

        let answer = if first_para.len() >= 20 {
            Self::truncate_at_sentence(first_para, 500)
        } else {
            Self::truncate_at_sentence(content, 500)
        };

        if answer.len() < 20 {
            return pairs;
        }

        pairs.push(QAPair {
            input: format!("What is {}?", title),
            output: answer.clone(),
        });

        if !title.ends_with('?') {
            pairs.push(QAPair {
                input: format!("{}?", title),
                output: answer,
            });
        }

        pairs
    }
}