keyword_search.py

파일 다운로드

"""작은 한국어 자료의 부분 문자열 일치 기준선."""
import re
import unicodedata
from aliases import canonicalize

ENDINGS = ("해주세요", "되나요", "인가요", "알려주세요", "은", "는", "이", "가", "을", "를", "의")
TERM_ALIASES = {"출근용": "출근"}
STOPWORDS = {"얼마", "무엇", "어떻게", "있나요", "되나요", "찾아주세요", "알려주세요"}


def terms(text, use_aliases=True):
    normalized = canonicalize(text) if use_aliases else unicodedata.normalize("NFKC", text)
    values = re.findall(r"[a-z]{2}-\d{3}|[가-힣a-z0-9]+", normalized.lower())
    result = set()
    for word in values:
        if word in STOPWORDS:
            continue
        for ending in ENDINGS:
            if word.endswith(ending) and len(word) - len(ending) >= 2:
                word = word[:-len(ending)]
                break
        word = TERM_ALIASES.get(word, word)
        if len(word) >= 2:
            result.add(word)
    return result


def keyword_search(query, chunks, top_k=3, use_aliases=True):
    if not isinstance(top_k, int) or not 1 <= top_k <= 20:
        raise ValueError("top_k는 1~20의 정수입니다.")
    query_terms = terms(query, use_aliases)
    candidates = []
    for row in chunks:
        text = "\n".join(str(row.get(key, "")) for key in ("title", "heading", "text"))
        text = canonicalize(text) if use_aliases else text
        compact = re.sub(r"\s+", "", unicodedata.normalize("NFKC", text).lower())
        matched = [word for word in query_terms if word in compact]
        if matched:
            score = len(matched) / len(query_terms)
            candidates.append({"chunk_id": row["chunk_id"], "document_id": row["document_id"],
                               "score": score, "method": "keyword"})
    candidates.sort(key=lambda row: (-row["score"], row["chunk_id"]))
    return [dict(row, rank=rank) for rank, row in enumerate(candidates[:top_k], 1)]