209 lines
7.4 KiB
Python
209 lines
7.4 KiB
Python
from __future__ import annotations
|
|
|
|
import re
|
|
import unicodedata
|
|
from difflib import SequenceMatcher
|
|
from math import log
|
|
import weakref
|
|
import networkx as nx
|
|
|
|
|
|
SYNONYMS = {
|
|
"slovensky": {
|
|
"slovak",
|
|
"slovenska",
|
|
"slovenskom",
|
|
"slovensky jazyk",
|
|
"slovencina",
|
|
"slovak language",
|
|
"slovak language and literature",
|
|
},
|
|
"jazyku": {"jazyk", "jazykovy"},
|
|
"uciva": {"učiť", "ucenie", "vzdelavanie", "predmet", "temy"},
|
|
"vzdelava": {"uciva", "ucenie", "temy"},
|
|
"literatura": {"literarne", "literarny", "literarne dielo", "sjl"},
|
|
}
|
|
STOP_WORDS = {
|
|
"co", "sa", "na", "aku", "ake", "ako", "pre", "je", "ci",
|
|
"v", "do", "pri", "o", "a",
|
|
"a", "an", "the", "what", "does", "about", "prepare", "lesson",
|
|
"in", "for", "grade", "subject", "include", "objectives", "activities",
|
|
"differentiation", "assessment", "homework", "minute", "minutes",
|
|
}
|
|
_INDEX_CACHE: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
|
|
|
|
|
|
def _normalise_text(value: str) -> str:
|
|
value = unicodedata.normalize("NFKD", value.lower())
|
|
value = "".join(char for char in value if not unicodedata.combining(char))
|
|
value = re.sub(r"[^a-z0-9]+", " ", value)
|
|
return " ".join(value.split())
|
|
|
|
|
|
def _expanded_terms(query: str) -> set[str]:
|
|
words = {
|
|
word for word in _normalise_text(query).split()
|
|
if (
|
|
word not in STOP_WORDS
|
|
and not word.isdigit()
|
|
and not re.fullmatch(r"\d+(?:st|nd|rd|th)", word)
|
|
)
|
|
}
|
|
expanded = set(words)
|
|
for word in words:
|
|
expanded.update(SYNONYMS.get(word, set()))
|
|
for synonym_set in SYNONYMS.values():
|
|
if word in synonym_set:
|
|
expanded.update(synonym_set)
|
|
return expanded
|
|
|
|
|
|
def _graph_index(graph: nx.Graph) -> dict:
|
|
cached = _INDEX_CACHE.get(graph)
|
|
if cached is not None:
|
|
return cached
|
|
|
|
node_records = []
|
|
inverted: dict[str, set[str]] = {}
|
|
for node in graph.nodes:
|
|
words = _normalise_text(str(node)).split()
|
|
text = " ".join(words)
|
|
node_records.append((node, words, text))
|
|
for word in set(words):
|
|
inverted.setdefault(word, set()).add(node)
|
|
cached = {
|
|
"node_records": node_records,
|
|
"inverted": inverted,
|
|
"node_count": len(node_records),
|
|
}
|
|
_INDEX_CACHE[graph] = cached
|
|
return cached
|
|
|
|
|
|
def retrieve_subgraph(graph: nx.Graph, query: str, limit: int = 60) -> str:
|
|
terms = _expanded_terms(query)
|
|
normalised_query = _normalise_text(query)
|
|
index = _graph_index(graph)
|
|
node_records = index["node_records"]
|
|
inverted = index["inverted"]
|
|
document_frequency = {
|
|
term: len(inverted.get(term, set()))
|
|
for term in terms
|
|
}
|
|
ranked = []
|
|
exact_candidates = set().union(*(inverted.get(term, set()) for term in terms))
|
|
candidates = (
|
|
{record[0] for record in node_records}
|
|
if not exact_candidates
|
|
else exact_candidates
|
|
)
|
|
for node, node_words, node_text in node_records:
|
|
if node not in candidates:
|
|
continue
|
|
exact_terms = {
|
|
term for term in terms
|
|
if term in node_words or (len(term.split()) > 1 and term in node_text)
|
|
}
|
|
exact_score = sum(
|
|
(log((index["node_count"] + 1) / (document_frequency[term] + 1)) + 1)
|
|
for term in exact_terms
|
|
)
|
|
fuzzy_score = SequenceMatcher(None, normalised_query, node_text).ratio()
|
|
token_score = max(
|
|
(
|
|
SequenceMatcher(None, term, node_term).ratio()
|
|
if len(term) >= 4 and len(node_term) >= 4
|
|
else 0
|
|
for term in terms
|
|
for node_term in node_text.split()
|
|
),
|
|
default=0,
|
|
)
|
|
score = exact_score * 2 + fuzzy_score + token_score
|
|
partial_match = any(
|
|
len(term) >= 5 and term in node_text
|
|
for term in terms
|
|
)
|
|
if exact_score or partial_match or (
|
|
fuzzy_score >= 0.42 and token_score >= 0.78
|
|
):
|
|
ranked.append((score, node))
|
|
|
|
# If exact terms exist but only produce weak candidates, retain a small
|
|
# fuzzy pass so typos and inflections are not discarded.
|
|
if not ranked and exact_candidates:
|
|
for node, node_words, node_text in node_records:
|
|
fuzzy_score = SequenceMatcher(None, normalised_query, node_text).ratio()
|
|
if fuzzy_score >= 0.42:
|
|
ranked.append((fuzzy_score, node))
|
|
|
|
context_lines: list[str] = []
|
|
seen_edges: set[tuple[str, str, str, str]] = set()
|
|
seed_nodes = [node for _, node in sorted(ranked, reverse=True)[:15]]
|
|
|
|
def add_edge(source: str, target: str, data: dict) -> None:
|
|
relation = str(data.get("relation", "related_to"))
|
|
source_doc = str(
|
|
data.get("source_doc")
|
|
or graph.nodes[source].get("source_doc")
|
|
or graph.nodes[target].get("source_doc")
|
|
or "unknown source"
|
|
)
|
|
edge_key = (source, target, relation, source_doc)
|
|
if edge_key not in seen_edges:
|
|
seen_edges.add(edge_key)
|
|
context_lines.append(
|
|
f"{source} --{relation}--> {target} [source: {source_doc}]"
|
|
)
|
|
|
|
# Direct node/edge matches are collected first.
|
|
undirected = graph.to_undirected()
|
|
for source, target, data in graph.edges(data=True):
|
|
source_text = _normalise_text(str(source))
|
|
target_text = _normalise_text(str(target))
|
|
edge_text = f"{source_text} {target_text} {_normalise_text(str(data.get('relation', '')))}"
|
|
if any(term in edge_text for term in terms):
|
|
add_edge(str(source), str(target), data)
|
|
if len(context_lines) >= limit:
|
|
return "\n".join(context_lines)
|
|
|
|
# Expand from the strongest seeds in both directions. This recovers facts
|
|
# several hops away and avoids hiding a match behind a broad hub node.
|
|
for seed in seed_nodes:
|
|
frontier = {seed}
|
|
visited = set()
|
|
for _depth in range(3):
|
|
next_frontier = set()
|
|
for node in frontier:
|
|
if node in visited:
|
|
continue
|
|
visited.add(node)
|
|
neighbours = set(undirected.neighbors(node))
|
|
for neighbor in neighbours:
|
|
if graph.has_edge(node, neighbor):
|
|
add_edge(str(node), str(neighbor), graph[node][neighbor])
|
|
if graph.has_edge(neighbor, node):
|
|
add_edge(str(neighbor), str(node), graph[neighbor][node])
|
|
next_frontier.add(neighbor)
|
|
if len(context_lines) >= limit:
|
|
break
|
|
if len(context_lines) >= limit:
|
|
break
|
|
frontier = next_frontier
|
|
if len(context_lines) >= limit:
|
|
break
|
|
if len(context_lines) >= limit:
|
|
break
|
|
|
|
# Include the nodes themselves as a final fallback. For isolates this is
|
|
# still graph evidence; for other nodes it supplements sparse edge data.
|
|
for _, node in sorted(ranked, reverse=True)[:15]:
|
|
source_doc = graph.nodes[node].get("source_doc") or "unknown source"
|
|
line = f"{node} (type: {graph.nodes[node].get('type', 'concept')}) [source: {source_doc}]"
|
|
if line not in context_lines:
|
|
context_lines.append(line)
|
|
if len(context_lines) >= limit:
|
|
break
|
|
|
|
return "\n".join(dict.fromkeys(context_lines))
|