Exceptions dictionary (exceptions.txt), per-jobs word list, docx report endpoint; LLM prompt knows org abbreviations
This commit is contained in:
1 parent
e03b0bc1c6
commit
7df303ba0e
6 files changed
+166
-7
No files matched your search
@@ -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")
|
||||
Reference in new issue
Block a user