From 7df303ba0ee8d3485a89b8d2c7669843e7c7ac54 Mon Sep 17 00:00:00 2001 From: Viktor Antropov Date: Mon, 2 Nov 2026 17:27:02 +0300 Subject: [PATCH] Exceptions dictionary (exceptions.txt), per-jobs word list, docx report endpoint; LLM prompt knows org abbreviations --- app.py | 113 +++++++++++++++++++++++++++++++- delivery/README-setup.md | 18 +++++ exceptions.txt | 17 +++++ installer/SETUP_GUIDE-ONLINE.md | 8 ++- installer/setup_online.bat | 6 ++ static/index.html | 11 +++- 6 files changed, 166 insertions(+), 7 deletions(-) create mode 100644 exceptions.txt diff --git a/app.py b/app.py index a06434b..2546289 100644 --- a/app.py +++ b/app.py @@ -17,6 +17,9 @@ import uuid from concurrent.futures import ThreadPoolExecutor from typing import List, Optional, Tuple +import urllib.parse as _urlparse +from collections import Counter + import httpx import openpyxl from pptx import Presentation @@ -25,6 +28,7 @@ from docx.oxml.ns import qn from docx.table import Table from docx.text.paragraph import Paragraph from fastapi import FastAPI, File, Form, HTTPException, UploadFile +from fastapi.responses import Response from fastapi.staticfiles import StaticFiles # --- конфиг (env, всё со значениями по умолчанию) --- @@ -183,6 +187,47 @@ def para_of_offset(offs: List[Tuple[int, int]], offset: int) -> int: break return best +# --- словарь-исключения --- +EXCEPTIONS_FILES = [ + os.path.join(os.path.dirname(os.path.abspath(__file__)), "exceptions.txt"), + os.path.join(os.getcwd(), "exceptions.txt"), + # родитель комплекта (C:\docchecker у онлайн-установки) — переживает update кода + os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "exceptions.txt"), +] + + +def load_exceptions() -> set: + """Слова и фразы, которые НЕ считать ошибками. Читается при каждой проверке.""" + words: set = set() + for p in EXCEPTIONS_FILES: + try: + if not os.path.exists(p): + continue + with open(p, encoding="utf-8") as fh: + for line in fh: + s = line.strip() + if s and not s.startswith("#"): + words.add(s.lower()) + except OSError: + continue + return words # set: проверка принадлежности — O(1) + + +def apply_exceptions(items: List[dict], whitelist: set) -> Tuple[List[dict], int]: + """Отбросить находки, фрагмент которых ЦЕЛИКОМ есть в словаре-исключениях.""" + if not whitelist: + return items, 0 + out: List[dict] = [] + dropped = 0 + for f in items: + frag = (f.get("fragment") or "").strip().lower() + if frag and frag in whitelist: + dropped += 1 + continue + out.append(f) + return out, dropped + + # --- LanguageTool --- LT_KIND = { @@ -245,7 +290,8 @@ LLM_SYSTEM = ( 'Ответом строго JSON-массив без пояснений: [{"para": <номер абзаца>, ' '"fragment": "<отрезок с ошибкой, дословно из текста, до 120 знаков>", ' '"fixed": "<тот же отрезок с исправленной пунктуацией>", "why": "<кратко, до 60 знаков>"}]. ' - "Если ошибок нет, ответь []." + "Если ошибок нет, ответь []. " + "Сокращения государственных органов и служб (МЧС, РОЧС, ГРОЧС, ОУСиС, РЦУРЧС, УМЧС, ГДЗС, СИЗ, УЗ, ЦРБ, ПАСС и подобные) — нормальные слова, не ошибки." ) def _norm_ws(s: str) -> str: @@ -371,9 +417,16 @@ def run_job(job_id: str, data: bytes, filename: str, use_llm: bool): llm_stats = {"enabled": False, "note": "LLM недоступна — отчёт только по орфографии/грамматике"} items.sort(key=lambda f: (f["para"], 0 if f["source"] == "LanguageTool" else 1)) + items, exc_dropped = apply_exceptions(items, load_exceptions()) counts: dict = {} for it in items: counts[it["kind"]] = counts.get(it["kind"], 0) + 1 + frag_counts = Counter() + for it in items: + frag = (it.get("fragment") or "").strip().lower() + if frag: + frag_counts[frag] += 1 + fragments_top = [{"fragment": k, "count": v} for k, v in frag_counts.most_common(100)] page_acc = 0 page_map = [] for p in paras: @@ -387,6 +440,8 @@ def run_job(job_id: str, data: bytes, filename: str, use_llm: bool): "page_map": page_map, # оценочная страница каждого абзаца "findings": items, "counts": counts, + "exceptions_dropped": exc_dropped, + "fragments_top": fragments_top, "lt_seconds": lt_secs, "llm": llm_stats, "finished": time.strftime("%Y-%m-%d %H:%M:%S"), @@ -408,7 +463,9 @@ def health(): except Exception: pass llm = llm_available() - return {"lt": lt, "llm": {"available": llm, "model": LLM_MODEL if llm else None}} + return {"lt": lt, "llm": {"available": llm, "model": LLM_MODEL if llm else None}, + "exceptions": len(load_exceptions()), + "exceptions_files": [bool(os.path.exists(p)) for p in EXCEPTIONS_FILES]} @app.post("/api/check") async def api_check(file: UploadFile = File(...), use_llm: str = Form("true")): @@ -441,4 +498,56 @@ def api_report(job_id: str): raise HTTPException(409, f"Задание ещё выполняется: {j.get('stage')}") return j["report"] +@app.get("/api/report/{job_id}/docx") +def api_report_docx(job_id: str): + """Отчёт в виде Word-документа (.docx): сводка + таблица замечаний.""" + j = JOBS.get(job_id) + if j is None: + raise HTTPException(404, "Задание не найдено") + if j.get("status") != "done": + raise HTTPException(409, f"Задание ещё выполняется: {j.get('stage')}") + rep = j["report"] + doc = DocxDocument() + doc.add_heading("Отчёт проверки документа", 0) + p = doc.add_paragraph() + p.add_run(f"Файл: {rep['file']}").bold = True + total = sum(rep["counts"].values()) + doc.add_paragraph(f"Дата: {rep['finished']} Абзацев: {rep['paragraphs']} Замечаний: {total}") + counts_line = "; ".join(f"{k}: {v}" for k, v in sorted(rep["counts"].items(), key=lambda kv: -kv[1])) + doc.add_paragraph("Типы: " + (counts_line or "—")) + if rep.get("exceptions_dropped"): + doc.add_paragraph(f"Отсеяно по словарю-исключениям: {rep['exceptions_dropped']}") + if rep.get("llm") and rep["llm"].get("note"): + doc.add_paragraph(f"LLM: {rep['llm']['note']}") + doc.add_heading("Замечания", level=1) + table = doc.add_table(rows=1, cols=5) + table.style = "Table Grid" + for i, text in enumerate(["Абзац", "Тип", "Фрагмент", "Контекст", "Вариант исправления"]): + table.rows[0].cells[i].text = text + for f in rep["findings"]: + row = table.add_row().cells + row[0].text = str(f["para"]) + row[1].text = f.get("kind", "") + row[2].paragraphs[0].add_run(f.get("fragment", "")).bold = True + pc = row[3].paragraphs[0] + b, frag, a = (f.get("context") or ["", "", ""]) + b = b.replace("\n", " ").strip() + a = a.replace("\n", " ").strip() + if b: + pc.add_run("…" + b[-45:] if len(b) > 45 else b) + if frag: + pc.add_run(frag).bold = True + else: + pc.add_run("<—>") + if a: + pc.add_run(a[:45] + ("…" if len(a) > 45 else "")) + row[4].text = " / ".join((f.get("replacements") or [])[:3]) or "—" + buf = io.BytesIO() + doc.save(buf) + return Response( + content=buf.getvalue(), + media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document", + headers={"Content-Disposition": f"attachment; filename=report-{job_id}.docx"}, + ) + app.mount("/", StaticFiles(directory="static", html=True), name="static") \ No newline at end of file diff --git a/delivery/README-setup.md b/delivery/README-setup.md index ef68d59..97e7615 100644 --- a/delivery/README-setup.md +++ b/delivery/README-setup.md @@ -35,6 +35,24 @@ исправления (нажать — скопируется). Кнопка «Скачать отчёт» сохраняет отчет в виде отдельного файла. +## Словарь исключений (важно) + +В комплекте лежит файл `exceptions.txt` (рядом с `app.py`). В нём перечислены +слова и фразы, которые **не** считать ошибками — специальные сокращения +(РОЧС, ГРОЧС, ОУСиС, РЦУРЧС, ГДЗС, СИЗ, ЦРБ…), фамилии, географические +названия и т.п. + +Как насытить словарь под свои документы: +1. Прогнать типовой документ (например, еженедельный доклад). +2. В отчёте нажать кнопку **«Словарь слов (txt)»** — скачается список всех + слов, которые программа посчитала ошибками, с числом повторений. +3. Открыть его, вычеркнуть настоящие опечатки, а всё остальное перенести + в `exceptions.txt` (Блокнотом, одна запись на строку). +4. Сохранить файл — следующая проверка уже применит словарь. + +На реальном большом документе большая часть «ошибок» обычно — именно такие +специальные слова; после заполнения словаря список сокращается в разы. + ## Замечания по работе - Старый формат .doc — пересохраните в .docx (Открыть в Word → Сохранить как). diff --git a/exceptions.txt b/exceptions.txt new file mode 100644 index 0000000..f363804 --- /dev/null +++ b/exceptions.txt @@ -0,0 +1,17 @@ +# Словарь-исключения: слова и фразы, которые НЕ считать ошибками. +# Одна запись на строку. Регистр не важен. Файл перечитывается при каждой проверке — +# правьте Блокнотом и сохраняйте; пересоздавать ничего не нужно. +# Как пополнять: прогнать документ -> кнопка «Словарь слов (txt)» -> вычеркнуть +# настоящие ошибки -> остальное перенести сюда. Одна запись на строку, целиком. +РОЧС +ГРОЧС +ОУСиС +РЦУРЧС +УМЧС +ГДЗС +СИЗ +ЦРБ +ПАСС +УЗ +Щучинская +Бучинская diff --git a/installer/SETUP_GUIDE-ONLINE.md b/installer/SETUP_GUIDE-ONLINE.md index 9dfa62f..28efa35 100644 --- a/installer/SETUP_GUIDE-ONLINE.md +++ b/installer/SETUP_GUIDE-ONLINE.md @@ -32,9 +32,11 @@ Ollama и модель пунктуации. Установка идёт в по - Остановка: закрыть два служебных окна (LT и docchecker) - Повторный запуск `setup_online.bat` безопасен: готовые шаги пропускаются, оборванные загрузки продолжаются с места обрыва -- Обновление кода: запустить `setup_online.bat` ещё раз — скрипт не обновляет - ранее распакованный архив (чтобы не затирать настройки); обновление кода — - через перезапуск с удалением папки `app` (настройки там не хранятся) +- Обновление кода: запустить `setup_online.bat update` (например, через cmd: + `C:\docchecker\setup_online.bat update`). Код перекачивается из Gitea, + установленные компоненты и словарь исключений `C:\docchecker\exceptions.txt` + не трогаются. Сам словарь: открой файл Блокнотом, одна запись на строку + (то, что НЕ надо считать ошибкой); правка начинает действовать со следующей проверки ## Если что-то пошло не так diff --git a/installer/setup_online.bat b/installer/setup_online.bat index 71d3d83..14121f6 100644 --- a/installer/setup_online.bat +++ b/installer/setup_online.bat @@ -7,6 +7,11 @@ echo Windows 10 1803+ / internet needed / about 4 GB download echo Everything is installed into the subfolder "app" echo ============================================================ +if /i not "%~1"=="update" goto :step0 +echo UPDATE: re-downloading project code, installed components stay... +if exist app rmdir /s /q app +if exist repo.zip del /q repo.zip +:step0 if exist app\docchecker\app.py goto :app_ready echo [1/6] Downloading project archive from Gitea... if not exist repo.zip curl -L -f --retry 3 -o repo.zip https://gitea.viktot14.com/Sadmin/docchecker/archive/main.zip || goto :err @@ -15,6 +20,7 @@ if exist app\docchecker rmdir /s /q app\docchecker tar -xf repo.zip -C app || goto :err for /d %%D in (app\docchecker*) do ren "%%D" "docchecker" if not exist app\docchecker\app.py goto :err +if exist app\docchecker\exceptions.txt if not exist ..\exceptions.txt copy /y app\docchecker\exceptions.txt ..\exceptions.txt >nul del repo.zip :app_ready cd /d app\docchecker || goto :err diff --git a/static/index.html b/static/index.html index cc4bfe6..373607e 100644 --- a/static/index.html +++ b/static/index.html @@ -159,7 +159,7 @@ function render(r) { "орфография/грамматика " + rep.lt_seconds + " с" + (L.enabled ? " · пунктуация (LLM) " + (L.llm_seconds||0) + " с" + (L.llm_chunks_failed ? ", фрагментов не обработано: " + L.llm_chunks_failed : "") : " · LLM: " + esc(L.note || "не использовалась")) + '
' + chips.join("") + - ' '; + ' '; const groups = {}; rep.findings.forEach(f => (groups[f.para] = groups[f.para] || []).push(f)); @@ -180,7 +180,14 @@ function render(r) { $("report").innerHTML = info + (body || '
Замечаний не найдено.
'); document.querySelectorAll(".chip").forEach(ch => ch.onclick = () => filter(ch.dataset.f)); document.querySelectorAll(".repl").forEach(b => b.onclick = () => { navigator.clipboard.writeText(b.dataset.t); b.title = "скопировано"; }); - const dl = $("dl"); if (dl) dl.onclick = download; + const dl = $("dlw"); if (dl) dl.onclick = () => { window.location = "/api/report/" + jobId + "/docx"; }; + const dl2 = $("dlw2"); if (dl2) dl2.onclick = () => { + const top = (lastReport.fragments_top || []).map(x => x.count + " " + x.fragment).join("\r\n"); + const a = document.createElement("a"); + a.href = URL.createObjectURL(new Blob(["сколько фрагмент\r\n" + top], {type: "text/plain;charset=utf-8"})); + a.download = "spisok_slov.txt"; + a.click(); + }; } function filter(f) {