ki-brain / src /model.cpp
Arian8888's picture
KI-Brain initial
85b4c6d
Raw History Blame Contribute Delete
9.95 kB
#include "model.h"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <sstream>
namespace mm {
static const std::unordered_set<std::string> STOP = {
"der","die","das","den","dem","des","ein","eine","einen","einer","eines","einem",
"und","oder","aber","doch","sondern","denn","weil","dass","ob","wenn","als","wie",
"ich","du","er","sie","es","wir","ihr","mich","dich","sich","mir","dir","uns","euch",
"mein","dein","sein","unser","euer","ist","sind","war","waren","bin","bist",
"habe","hast","hat","haben","hatte","hatten","werde","wirst","wird","werden","wurde",
"auf","unter","ueber","vor","nach","bei","mit","ohne","von","aus","zu","zur","zum",
"in","im","an","am","durch","fuer","gegen","um","auch","nicht","nur","sehr","mehr",
"schon","noch","also","so","dann","dort","hier","da","ja","nein","kein","keine",
"the","a","an","of","on","at","to","for","with","by","from","is","are","was","were",
"be","been","being","this","that","these","those","it","its","as","if","than","then",
"there","here","not","no","do","does","did","has","have","had","i","you","he","she",
"we","they","my","your","our","their","me","us","them"
};
static bool is_letter(unsigned char c) {
if (std::isalpha(c)) return true;
return c == 0xC4 || c == 0xD6 || c == 0xDC || c == 0xE4 || c == 0xF6 || c == 0xFC || c == 0xDF;
}
static std::string to_lower(const std::string& s) {
std::string out = s;
for (auto& c : out) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
// Umlaute normalisieren (zum besseren Matching)
std::string r; r.reserve(out.size());
for (size_t i=0;i<out.size();++i) {
unsigned char c = (unsigned char)out[i];
if (c == 0xE4) r += "ae";
else if (c == 0xF6) r += "oe";
else if (c == 0xFC) r += "ue";
else if (c == 0xDF) r += "ss";
else r += (char)c;
}
return r;
}
std::vector<std::string> tokenize(const std::string& text) {
std::vector<std::string> out;
std::string cur;
for (unsigned char c : text) {
if (is_letter(c)) cur += (char)c;
else {
if (cur.size() >= 2) {
std::string low = to_lower(cur);
if (!STOP.count(low)) out.push_back(low);
}
cur.clear();
}
}
if (cur.size() >= 2) {
std::string low = to_lower(cur);
if (!STOP.count(low)) out.push_back(low);
}
return out;
}
std::vector<std::string> split_sentences(const std::string& text) {
std::vector<std::string> sents;
std::string cur;
for (size_t i = 0; i < text.size(); ++i) {
char c = text[i];
cur += c;
if (c == '.' || c == '!' || c == '?') {
// Trim
while (!cur.empty() && std::isspace((unsigned char)cur.front())) cur.erase(cur.begin());
if (cur.size() > 20) sents.push_back(cur);
cur.clear();
}
}
if (cur.size() > 20) sents.push_back(cur);
return sents;
}
// ---------- TF-IDF ----------
void TfIdf::add(const std::string& id, const std::string& text) {
Doc d;
d.id = id;
d.text = text;
d.tokens = tokenize(text);
for (auto& t : d.tokens) d.tf[t]++;
std::unordered_set<std::string> uniq(d.tokens.begin(), d.tokens.end());
for (auto& w : uniq) df_[w]++;
docs_.push_back(std::move(d));
idf_.clear();
}
void TfIdf::build() {
double N = (double)docs_.size();
idf_.clear();
for (auto& kv : df_) {
idf_[kv.first] = std::log((N + 1.0) / (kv.second + 1.0)) + 1.0;
}
}
std::unordered_map<std::string,double> TfIdf::vec(const std::vector<std::string>& toks) const {
std::unordered_map<std::string,double> v;
if (toks.empty()) return v;
std::unordered_map<std::string,int> c;
for (auto& t : toks) c[t]++;
double len = (double)toks.size();
double fallback = std::log((double)docs_.size() + 1.0);
for (auto& kv : c) {
auto it = idf_.find(kv.first);
double idf = (it != idf_.end()) ? it->second : fallback;
v[kv.first] = (kv.second / len) * idf;
}
return v;
}
double TfIdf::cosine(const std::unordered_map<std::string,double>& a,
const std::unordered_map<std::string,double>& b) {
if (a.empty() || b.empty()) return 0.0;
double dot=0, na=0, nb=0;
for (auto& kv : a) {
na += kv.second * kv.second;
auto it = b.find(kv.first);
if (it != b.end()) dot += kv.second * it->second;
}
for (auto& kv : b) nb += kv.second * kv.second;
if (na == 0 || nb == 0) return 0.0;
return dot / (std::sqrt(na) * std::sqrt(nb));
}
std::vector<ScoredDoc> TfIdf::search(const std::string& query, size_t top_k) const {
std::vector<ScoredDoc> out;
if (docs_.empty()) return out;
if (idf_.empty()) const_cast<TfIdf*>(this)->build();
auto q = vec(tokenize(query));
std::vector<ScoredDoc> all;
for (auto& d : docs_) {
auto dv = vec(d.tokens);
double s = cosine(q, dv);
all.push_back({d.id, d.text, s});
}
std::sort(all.begin(), all.end(), [](const ScoredDoc& x, const ScoredDoc& y){ return x.score > y.score; });
for (size_t i=0; i<all.size() && i<top_k; ++i) {
if (all[i].score > 0.01) out.push_back(all[i]);
}
return out;
}
// ---------- Summarize ----------
std::string summarize(const std::string& text, size_t max_sentences, const std::string& focus) {
auto sents = split_sentences(text);
if (sents.empty()) return text.substr(0, std::min<size_t>(text.size(), 1000));
std::unordered_map<std::string,int> freq;
std::vector<std::vector<std::string>> stoks;
stoks.reserve(sents.size());
for (auto& s : sents) {
auto t = tokenize(s);
for (auto& w : t) freq[w]++;
stoks.push_back(std::move(t));
}
int maxf = 1;
for (auto& kv : freq) maxf = std::max(maxf, kv.second);
std::unordered_set<std::string> focusTok;
if (!focus.empty()) {
auto f = tokenize(focus);
focusTok.insert(f.begin(), f.end());
}
struct S { size_t idx; std::string text; double score; };
std::vector<S> scored;
for (size_t i = 0; i < sents.size(); ++i) {
auto& toks = stoks[i];
if (toks.empty()) continue;
double sum = 0;
bool hasFocus = false;
for (auto& t : toks) {
sum += (double)freq[t] / (double)maxf;
if (focusTok.count(t)) hasFocus = true;
}
double sc = sum / std::sqrt((double)toks.size());
if (hasFocus) sc *= 1.5;
if (i < 5) sc *= 1.0 + (5 - (double)i) * 0.05;
scored.push_back({i, sents[i], sc});
}
std::sort(scored.begin(), scored.end(), [](const S& a, const S& b){ return a.score > b.score; });
if (scored.size() > max_sentences) scored.resize(max_sentences);
std::sort(scored.begin(), scored.end(), [](const S& a, const S& b){ return a.idx < b.idx; });
std::string out;
for (auto& s : scored) { out += s.text; out += " "; }
return out;
}
// ---------- Intent ----------
static const std::vector<std::string> GREET = {"hi","hallo","hey","moin","servus"};
static const std::vector<std::string> BYE = {"tschuess","tschüss","bye","ciao","wiedersehen"};
static const std::vector<std::string> WHO = {"wer bist du","wie heisst du","wie heißt du","was bist du"};
static const std::vector<std::string> LIST = {"was weisst du","was weißt du","was hast du gelernt","welche themen","liste themen"};
static const std::vector<std::string> LEARN = {"lerne ueber","lerne über","lerne","recherchiere","informiere dich",
"suche","such ","finde heraus","was ist","was sind",
"wer ist","wer war","erklaere","erkläre","definiere","definition von"};
static bool starts_with(const std::string& s, const std::string& p) {
return s.size() >= p.size() && std::equal(p.begin(), p.end(), s.begin());
}
static bool contains(const std::string& s, const std::string& p) {
return s.find(p) != std::string::npos;
}
IntentResult detect_intent(const std::string& msg) {
std::string low = to_lower(msg);
while (!low.empty() && std::isspace((unsigned char)low.back())) low.pop_back();
while (!low.empty() && std::isspace((unsigned char)low.front())) low.erase(low.begin());
for (auto& g : GREET) if (low == g || starts_with(low, g + " ") || starts_with(low, g + "!")) return {Intent::Greet, ""};
for (auto& g : BYE) if (contains(low, g)) return {Intent::Bye, ""};
for (auto& g : WHO) if (contains(low, g)) return {Intent::Identity, ""};
for (auto& g : LIST) if (contains(low, g)) return {Intent::ListTopics, ""};
for (auto& t : LEARN) {
size_t pos = low.find(t);
if (pos != std::string::npos) {
std::string rest = low;
// Alle Trigger entfernen
for (auto& tt : LEARN) {
size_t p;
while ((p = rest.find(tt)) != std::string::npos) rest.replace(p, tt.size(), " ");
}
// Trim und Punktuation
std::string topic;
bool prev_space = true;
for (char c : rest) {
if (std::isspace((unsigned char)c)) {
if (!prev_space) topic += ' ';
prev_space = true;
} else if (c == '?' || c == '!' || c == '.' || c == ',' || c == ':') {
continue;
} else {
topic += c;
prev_space = false;
}
}
while (!topic.empty() && std::isspace((unsigned char)topic.back())) topic.pop_back();
while (!topic.empty() && std::isspace((unsigned char)topic.front())) topic.erase(topic.begin());
if (!topic.empty()) return {Intent::Learn, topic};
}
}
return {Intent::Ask, msg};
}
} // namespace mm