web / server /analyzer.py
qkrm's picture
deploy: no-singo site + FastAPI/Kiwi backend
b6f14c9 verified
Raw History Blame Contribute Delete
5.21 kB
"""동남 방언 의문형 어미(-노/-나/-고/-가) 판정기.
어절 단위로 방언을 표준어로 정규화한 뒤 Kiwi 형태소 분석으로
어간 품사(체언/용언)와 의문사 유무를 판별한다.
프런트엔드 휴리스틱과 동일한 응답 형태를 반환한다.
"""
import json
import re
from pathlib import Path
from kiwipiepy import Kiwi
# num_workers=1 + 오타/복합명사 사전 미로드: Render 무료 인스턴스(512MB) OOM 방지
_kiwi = Kiwi(num_workers=1, load_typo_dict=False, load_multi_dict=False)
_DIALECT_DIR = Path(__file__).parent / "dialects"
def _load_word_map() -> dict:
merged = {}
for path in sorted(_DIALECT_DIR.glob("*.json")):
data = json.loads(path.read_text(encoding="utf-8"))
merged.update(data.get("word_map", {}))
return merged
_WORD_MAP = _load_word_map()
_TRAIL_RE = re.compile(r"[\s?!.,~…;^ㅋㅎㅠㅜ]+$")
_WORD_RE = re.compile(r"\S+")
# 의문형 종결어미: 붙는 자리, 의문사 요구 여부
ENDINGS = {
"노": {"pos": "용언", "needsWh": True},
"나": {"pos": "용언", "needsWh": False},
"고": {"pos": "체언", "needsWh": True},
"꼬": {"pos": "체언", "needsWh": True},
"가": {"pos": "체언", "needsWh": False},
}
# 표준형 의문사 형태소 (정규화 후 매칭되므로 방언형은 사전에서 처리)
WH_FORMS = {
"뭐", "무엇", "뭣", "무슨", "뭔", "어디", "언제", "누구", "왜",
"어째", "어찌", "어쩌", "어떡", "몇", "어느", "어떻", "어떤", "얼마",
}
def _correct_ending(pos: str, has_wh: bool) -> str:
if pos == "용언":
return "노" if has_wh else "나"
return "고" if has_wh else "가"
def _stem_pos(tag: str) -> str:
"""어간 마지막 형태소 품사 태그 → 체언/용언."""
if tag == "VCP": # 지정사 '이-'는 체언에 붙으므로 체언 판정
return "체언"
if tag[0] in ("V", "E") or tag in ("XSV", "XSA"):
return "용언"
return "체언"
def _normalize(stripped: str):
"""어절 단위 방언→표준어 치환.
반환: (정규화 문자열, spans)
spans[i] = (정규화 시작, 정규화 끝, 원문 시작, 원문 끝) — 어절 단위 매핑.
"""
parts = []
spans = []
cursor = 0
for m in _WORD_RE.finditer(stripped):
word = m.group()
core = word.rstrip("?!.,~…;^")
tail = word[len(core):]
replaced = _WORD_MAP.get(core, core) + tail
if parts:
cursor += 1 # 어절 사이 공백
parts.append(replaced)
spans.append((cursor, cursor + len(replaced), m.start(), m.end()))
cursor += len(replaced)
return " ".join(parts), spans
def _orig_span(spans, norm_idx: int):
for norm_start, norm_end, orig_start, orig_end in spans:
if norm_start <= norm_idx < norm_end:
return orig_start, orig_end
return None
def analyze(raw: str) -> dict:
text = raw.strip()
if not text:
return {"state": "empty"}
stripped = _TRAIL_RE.sub("", text)
if not stripped:
return {"state": "empty"}
last = stripped[-1]
info = ENDINGS.get(last)
if info is None:
return {"state": "na", "text": text}
ending_index = len(stripped) - 1
norm, spans = _normalize(stripped)
stem_text = norm[:-1].rstrip() # 어미 한 글자 제거
# 어간만 주면 단음절 동사(자-, 가- 등)를 못 알아보므로
# 표준 의문형 어미 '니'를 붙여 분석 (동사·지정사 양쪽에 다 붙는다)
tokens = _kiwi.tokenize(stem_text + "니") if stem_text else []
# 덧붙인 '니'(및 그 자리에 생긴 가상 형태소) 제거
while tokens and tokens[-1].start >= len(stem_text):
tokens.pop()
# 의문사: 어간 형태소 중 표준형이 목록에 있는 것 → 원문 어절 span으로 역매핑
wh_list = []
seen_starts = set()
for t in tokens:
if t.form in WH_FORMS:
span = _orig_span(spans, t.start)
if span is None:
continue
start, end = span
end = min(end, ending_index) # 어미 글자와 하이라이트 겹침 방지
if start >= end or start in seen_starts:
continue
seen_starts.add(start)
wh_list.append({"start": start, "end": end, "name": t.form})
has_wh = len(wh_list) > 0
stem_pos = _stem_pos(tokens[-1].tag) if tokens else "체언"
ending_norm = "고" if last == "꼬" else last
expected = _correct_ending(stem_pos, has_wh)
ok = ending_norm == expected
pos_mismatch = ENDINGS[ending_norm]["pos"] != stem_pos
result = {
"state": "ok" if ok else "bad",
"text": text,
"stripped": stripped,
"ending": last,
"endingIndex": ending_index,
"info": info,
"whList": wh_list,
"hasWh": has_wh,
"posMismatch": pos_mismatch,
"realPos": stem_pos,
"fixed": None,
"source": "kiwi",
"normalized": norm,
"morphs": [[t.form, t.tag] for t in tokens],
}
if not ok:
result["fixed"] = stripped[:-1] + expected + "?"
return result