dict add button: POST /api/dict/add with anti-injection, provenance lines, forms grid, typo guard (lev<=2); UI buttons; dict_promote; local *.txt layer survives update

This commit is contained in:
Sadmin committed 2026-11-10 13:13:15 +03:00
1 parent 68be624fb2
commit 7791d3422f
6 files changed
+1387 -14

No files matched your search

+192 -10
View File
@@ -205,20 +205,25 @@ def para_of_offset(offs: List[Tuple[int, int]], offset: int) -> int:
return best
# --- словарь-исключения ---
# Четыре имени в трёх местах: рядом с app.py → cwd → родитель комплекта.
# *.local.txt — пользовательский слой (кнопка «В словарь» пишет туда); этих файлов
# нет в архиве репо, поэтому robocopy-update их не трогает (переживают обновление).
DICT_BASENAMES = ("exceptions.txt", "toponyms.txt", "exceptions.local.txt", "toponyms.local.txt")
def _dict_dir_candidates():
here = os.path.dirname(os.path.abspath(__file__))
return [here, os.getcwd(), os.path.dirname(here)]
EXCEPTIONS_FILES = [
os.path.join(os.path.dirname(os.path.abspath(__file__)), "exceptions.txt"),
# автогенерируемый справочник топонимов РБ (scripts/gen_toponyms.py)
os.path.join(os.path.dirname(os.path.abspath(__file__)), "toponyms.txt"),
os.path.join(os.getcwd(), "exceptions.txt"),
os.path.join(os.getcwd(), "toponyms.txt"),
# родитель комплекта (C:\docchecker у онлайн-установки) — переживает update кода
os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "exceptions.txt"),
os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "toponyms.txt"),
os.path.join(d, b) for d in _dict_dir_candidates() for b in DICT_BASENAMES
]
def load_exceptions() -> set:
"""Слова и фразы, которые НЕ считать ошибками. Читается при каждой проверке."""
"""Слова и фразы, которые НЕ считать ошибками. Читается при каждой проверке.
Инлайн-провенанс вида «слово # 2026-11-10, прогон …» отсекается по « #»."""
words: set = set()
for p in EXCEPTIONS_FILES:
try:
@@ -227,7 +232,10 @@ def load_exceptions() -> set:
with open(p, encoding="utf-8") as fh:
for line in fh:
s = line.strip()
if s and not s.startswith("#"):
if not s or s.startswith("#"):
continue
s = s.split(" #", 1)[0].strip()
if s:
words.add(s.lower())
except OSError:
continue
@@ -249,6 +257,95 @@ def apply_exceptions(items: List[dict], whitelist: set) -> Tuple[List[dict], int
return out, dropped
# --- кнопка «В словарь»: пользовательский слой *.local.txt ---
DICT_ADD_LOCK = threading.Lock()
FRAG_MAX_CHARS = 64
DICT_FRAG_ALPHABET = re.compile(r"[А-Яа-яЁёA-Za-z \-.«»]+")
FRAGMENTS_PER_JOB_LIMIT = 100
# прилагательные: сетка строится от стема (скилл: стем = слово минус «ский», не минус «ий»)
def declension_forms(word: str) -> List[str]:
"""Сетка форм (скилл: прилагательное 11-12, существительное 10-11).
Эвристика: сомнительные слова возвращаются как есть — лишняя форма в словаре
безвредна, недостающая проявится на следующем прогоне."""
w = word.strip()
if not w or not DICT_FRAG_ALPHABET.fullmatch(w):
return [w]
low = w.lower()
if low.endswith("ский"):
stem = w[:-4]
return [w] + [stem + s for s in ("ского", "скому", "ским", "ском",
"ская", "ской", "ское", "ские", "ских", "скими")]
if low.endswith("ний"):
stem = w[:-3]
return [w] + [stem + s for s in ("его", "ему", "им", "ем",
"няя", "ней", "нее", "ние", "них", "ними")]
if low.endswith("ый") or low.endswith("ой"):
stem = w[:-2]
return [w] + [stem + s for s in ("ого", "ому", "ым", "ом",
"ая", "ой", "ое", "ые", "ых", "ыми")]
if low.endswith("ий"):
stem = w[:-2] # редкий твёрдый тип: худший случай — одна лишняя форма
return [w] + [stem + s for s in ("его", "ему", "им", "ем",
"ая", "ей", "ое", "ие", "их", "ими")]
if low[-1] in "бвгджзклмнпрстфхцчшщь":
gen = "и" if low[-1] in "гкхжчшщь" else "ы"
return [w, w + "а", w + "у", w + "ом", w + "е", w + gen, w + "ов", w + "ам", w + "ами", w + "ах"]
if low.endswith("а"):
s = w[:-1]
return [w, s + "ы", s + "е", s + "у", s + "ой", s + "ам", s + "ами", s + "ах"]
if low.endswith("я"):
s = w[:-1]
return [w, s + "и", s + "е", s + "ю", s + "ей", s + "ям", s + "ями", s + "ях"]
return [w]
def _norm_frag(s: str) -> str:
return " ".join((s or "").strip().lower().split())
def levenshtein(a: str, b: str, cutoff: int = 2) -> int:
if abs(len(a) - len(b)) > cutoff:
return cutoff + 1
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
cur = [i]
for j, cb in enumerate(b, 1):
cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
if min(cur) > cutoff:
return cutoff + 1
prev = cur
return prev[-1]
def local_dict_path(target: str) -> str:
"""Куда писать exceptions.local.txt / toponyms.local.txt: каталог комплекта,
где уже лежит tracked-словарь; иначе каталог app.py."""
name = "exceptions.local.txt" if target == "exceptions" else "toponyms.local.txt"
dirs = [os.path.dirname(os.path.abspath(__file__)), os.getcwd(),
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))]
for d in dirs:
if any(os.path.exists(os.path.join(d, base)) for base in ("exceptions.txt", "toponyms.txt")):
return os.path.join(d, name)
return os.path.join(dirs[0], name)
def _validate_fragment(fragment: str) -> Optional[str]:
"""None = ок, иначе текст ошибки (400)."""
if not fragment:
return "Пустой фрагмент"
if len(fragment) > FRAG_MAX_CHARS:
return f"Фрагмент длиннее {FRAG_MAX_CHARS} знаков"
if re.search(r"[\x00-\x1f\x7f]", fragment):
return "Управляющие символы в фрагменте"
for ch in fragment:
if not (ch == " " or ch == "-" or ch == "." or ch == "«" or ch == "»"
or ch.isalpha()):
return f"Недопустимый символ: {ch!r}"
return None
# --- LanguageTool ---
LT_KIND = {
@@ -590,6 +687,91 @@ def api_report(job_id: str):
raise HTTPException(409, f"Задание ещё выполняется: {j.get('stage')}")
return j["report"]
@app.post("/api/dict/add")
async def api_dict_add(payload: dict):
"""Кнопка «В словарь»: запись фрагмента в пользовательский слой *.local.txt.
Требования: фрагмент должен присутствовать среди находок указанного job
(анти-инъекция), без переводов строк и спецсимволов, ограничение частоты.
target: exceptions | toponyms; forms: добавить слово со всеми формами.
Служба словарь перечитывает при каждой проверке — рестарт не нужен."""
job_id = str(payload.get("job_id") or "").strip()
fragment = str(payload.get("fragment") or "").strip()
target = str(payload.get("target") or "exceptions").strip().lower()
confirm = bool(payload.get("confirm"))
forms_wanted = bool(payload.get("forms"))
job = JOBS.get(job_id)
if job is None or job.get("status") != "done" or not job.get("report"):
raise HTTPException(404, "Задание не найдено или ещё не готово")
if target not in ("exceptions", "toponyms"):
raise HTTPException(400, "target: exceptions | toponyms")
err = _validate_fragment(fragment)
if err:
raise HTTPException(400, err)
rep = job["report"]
norm = _norm_frag(fragment)
if norm not in {_norm_frag(f.get("fragment", "")) for f in rep.get("findings", [])}:
raise HTTPException(400, "Фрагмент отсутствует среди находок этого прогона")
# ограничение частоты на job (анти-спам кнопки)
adds = job.setdefault("dict_adds", {})
if sum(adds.values()) >= FRAGMENTS_PER_JOB_LIMIT:
raise HTTPException(429, f"Превышен лимит добавлений для этого прогона ({FRAGMENTS_PER_JOB_LIMIT})")
# уже в словаре (вместе с локальным слоем)?
if norm in load_exceptions():
return {"added": 0, "already": True, "fragment": fragment}
# подсказка LT для этого фрагмента (по фрагменту целиком)
hint = ""
for fr in rep.get("fragments_top", []):
if _norm_frag(fr.get("fragment", "")) == norm:
hint = (fr.get("top_replacement") or "").strip()
break
if not hint:
for f in rep.get("findings", []):
if _norm_frag(f.get("fragment", "")) == norm:
hint = ((f.get("replacements") or [""])[0] or "").strip()
break
# защита от глушения системной опечатки: LT предлагает правку того же корня
if hint and not confirm and levenshtein(norm, _norm_frag(hint)) <= 2:
raise HTTPException(409, detail={"need_confirm": True, "suggestion": hint,
"message": f"Похоже на опечатку: LT предлагает «{hint}»"})
words = declension_forms(fragment) if forms_wanted else [fragment]
words = [w for w in words if _validate_fragment(w) is None]
path = local_dict_path(target)
stamp = time.strftime("%Y-%m-%d")
origin = f"# {stamp}, прогон {rep.get('file', '?')}" + (f", LT: {hint}" if hint else "")
lines = []
for w in words:
key = _norm_frag(w)
if key in adds:
continue
adds[key] = adds.get(key, 0) + 1
lines.append(f"{w} {origin}")
added = 0
with DICT_ADD_LOCK:
if lines:
try:
with open(path, "a", encoding="utf-8") as fh:
fh.write("\n".join(lines) + "\n")
logf = os.path.join(os.path.dirname(path), "dict_added.log")
with open(logf, "a", encoding="utf-8") as fh:
fh.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')}\tjob {job_id}\t"
f"{fragment}\ttarget={target}\tforms={len(words)}\t"
f"lt_hint={hint}\n")
added = len(lines)
except OSError as e:
raise HTTPException(500, f"Не удалось записать словарь: {e}")
return {"added": added, "already": False, "path": path, "fragment": fragment,
"forms": words if forms_wanted else [fragment]}
@app.get("/api/report/{job_id}/docx")
def api_report_docx(job_id: str):
"""Word-отчёт той же логики, что и веб-страница: сводка -> замечания по