906 lines
41 KiB
Python
906 lines
41 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""docchecker: проверка docx/txt документов.
|
||
|
||
Конвейер: загрузка -> разбор по абзацам (включая таблицы) -> чанки в
|
||
LanguageTool (орфография/грамматика) -> чанки в LLM (пунктуация) -> отчёт.
|
||
|
||
Всё выполняется локально на этой машине; никакие тексты наружу не уходят.
|
||
LLM необязательна: без неё отчёт делается только по LanguageTool.
|
||
"""
|
||
import io
|
||
import os
|
||
import json
|
||
import re
|
||
import threading
|
||
import time
|
||
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
|
||
from docx import Document as DocxDocument
|
||
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, всё со значениями по умолчанию) ---
|
||
LT_URL = os.environ.get("LT_URL", "http://localhost:8010")
|
||
LT_DISABLED = os.environ.get(
|
||
"LT_DISABLED_RULES",
|
||
# глушим шум на штабных документах: капс-бред, лишние пробелы/дефисы,
|
||
# правила «о том / о заседании» (несовместимы со склейкой таблиц слайдов)
|
||
"AllCaps,WHITESPACE_RULE,COMMA_PARENTHESIS_WHITESPACE,"
|
||
"TIRE,O_tom_chto,O_P_padeg,DOUBLE_PUNCTUATION",
|
||
)
|
||
LT_CHUNK = int(os.environ.get("LT_CHUNK_CHARS", "1800"))
|
||
LT_PARALLEL = int(os.environ.get("LT_PARALLEL", "6"))
|
||
LLM_BASE = os.environ.get("LLM_BASE_URL", "") # напр. http://llm:8081/v1
|
||
LLM_MODEL = os.environ.get("LLM_MODEL", "qwen3-4b-instruct")
|
||
LLM_VERIFY_MODE = os.environ.get("LLM_VERIFY", "on") # on|off — второй проход самопроверки
|
||
LLM_MODE = os.environ.get("LLM_MODE", "auto") # auto|on|off
|
||
LLM_CHUNK = int(os.environ.get("LLM_CHUNK_CHARS", "3200"))
|
||
LLM_PARALLEL = int(os.environ.get("LLM_PARALLEL", "2"))
|
||
MAX_MB = int(os.environ.get("MAX_UPLOAD_MB", "60"))
|
||
CHARS_PER_PAGE = 1800 # оценка страниц А4
|
||
|
||
app = FastAPI(title="docchecker", docs_url=None, redoc_url=None)
|
||
|
||
JOBS: dict = {}
|
||
JOBS_LOCK = threading.Lock()
|
||
|
||
_CTRL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
|
||
|
||
|
||
def clean_text(s: str) -> str:
|
||
"""Убрать управляющие символы (lxml/python-docx их не принимают; легаси Word их сыплет)."""
|
||
if not s:
|
||
return s
|
||
return _CTRL_RE.sub(" ", s).replace("\r", " ")
|
||
|
||
|
||
# --- разбор документа ---
|
||
|
||
MIN_CELL_CHARS = 20 # короче — это служебные ячейки, не проверяем
|
||
|
||
|
||
def extract_xlsx(data: bytes) -> List[str]:
|
||
"""Ячейки с осмысленным текстом (длинные, с пробелом), по листам."""
|
||
wb = openpyxl.load_workbook(io.BytesIO(data), data_only=True, read_only=True)
|
||
out: List[str] = []
|
||
for ws in wb.worksheets:
|
||
first_in_sheet = True
|
||
seen_sheet = set()
|
||
for row in ws.iter_rows():
|
||
for cell in row:
|
||
val = cell.value
|
||
if not isinstance(val, str):
|
||
continue
|
||
txt = val.strip()
|
||
if len(txt) < MIN_CELL_CHARS or " " not in txt or not any(c.isalpha() for c in txt):
|
||
continue
|
||
if txt in seen_sheet:
|
||
continue
|
||
seen_sheet.add(txt)
|
||
if first_in_sheet:
|
||
out.append(f"[лист «{ws.title}»] {txt}")
|
||
first_in_sheet = False
|
||
else:
|
||
out.append(txt)
|
||
wb.close()
|
||
return out
|
||
|
||
|
||
def extract_pptx(data: bytes) -> List[str]:
|
||
"""Текст слайдов, таблиц и заметок докладчика (по слайдам)."""
|
||
prs = Presentation(io.BytesIO(data))
|
||
out: List[str] = []
|
||
|
||
def push_frame(tf) -> None:
|
||
for para in tf.paragraphs:
|
||
txt = para.text.strip()
|
||
if txt:
|
||
out.append(txt)
|
||
|
||
for s_idx, slide in enumerate(prs.slides, start=1):
|
||
first_in_slide = True
|
||
for shape in slide.shapes:
|
||
marker = f"[слайд {s_idx}] " if first_in_slide else ""
|
||
if shape.has_text_frame:
|
||
before = len(out)
|
||
push_frame(shape.text_frame)
|
||
if len(out) > before and first_in_slide:
|
||
out[before] = marker + out[before]
|
||
first_in_slide = False
|
||
elif shape.has_table:
|
||
for row in shape.table.rows:
|
||
for cell in row.cells:
|
||
txt = cell.text.strip()
|
||
if txt:
|
||
out.append((marker if first_in_slide else "") + txt)
|
||
first_in_slide = False
|
||
if slide.has_notes_slide:
|
||
notes = slide.notes_slide.notes_text_frame.text.strip()
|
||
if notes:
|
||
out.append(f"[заметки к слайду {s_idx}] {notes}")
|
||
return out
|
||
|
||
|
||
def extract_paragraphs(data: bytes, filename: str) -> List[str]:
|
||
"""Абзацы документа в порядке следования, включая текст таблиц."""
|
||
name = (filename or "").lower()
|
||
if name.endswith(".txt"):
|
||
text = ""
|
||
for enc in ("utf-8-sig", "utf-8", "cp1251"):
|
||
try:
|
||
text = data.decode(enc)
|
||
break
|
||
except UnicodeDecodeError:
|
||
text = ""
|
||
if not text:
|
||
text = data.decode("utf-8", "replace")
|
||
return [ln.rstrip() for ln in text.splitlines() if ln.strip()]
|
||
if name.endswith(".doc"):
|
||
raise ValueError("Старый формат .doc: пересохраните документ как .docx и загрузите снова")
|
||
if name.endswith(".xlsx"):
|
||
return extract_xlsx(data)
|
||
if name.endswith(".pptx"):
|
||
return extract_pptx(data)
|
||
if not name.endswith(".docx"):
|
||
raise ValueError("Формат не поддержан: загрузите .docx, .xlsx, .pptx или .txt")
|
||
doc = DocxDocument(io.BytesIO(data))
|
||
out: List[str] = []
|
||
for child in doc.element.body.iterchildren():
|
||
if child.tag == qn("w:p"):
|
||
txt = Paragraph(child, doc).text.strip()
|
||
if txt:
|
||
out.append(txt)
|
||
elif child.tag == qn("w:tbl"):
|
||
tbl = Table(child, doc)
|
||
prev = None
|
||
for row in tbl.rows:
|
||
for cell in row.cells:
|
||
for p in cell.paragraphs:
|
||
txt = p.text.strip()
|
||
if txt and txt != prev:
|
||
out.append(txt)
|
||
prev = txt
|
||
return out
|
||
|
||
# --- чанкинг ---
|
||
|
||
def make_chunks(paras: List[str], max_chars: int, sep: str) -> List[Tuple[str, List[Tuple[int, int]]]]:
|
||
"""Склеивает абзацы в чанки. Возвращает (текст чанка, [(смещение абзаца, индекс абзаца)])."""
|
||
chunks = []
|
||
buf: List[str] = []
|
||
offs: List[Tuple[int, int]] = []
|
||
cur_len = 0
|
||
for idx, text in enumerate(paras):
|
||
need = len(text) + (len(sep) if buf else 0)
|
||
if buf and cur_len + need > max_chars:
|
||
chunks.append((sep.join(buf), offs))
|
||
buf, offs, cur_len = [], [], 0
|
||
start = cur_len + len(sep) if buf else 0
|
||
offs.append((start, idx))
|
||
cur_len = start + len(text)
|
||
buf.append(text)
|
||
if buf:
|
||
chunks.append((sep.join(buf), offs))
|
||
return chunks
|
||
|
||
def para_of_offset(offs: List[Tuple[int, int]], offset: int) -> int:
|
||
best = offs[0][1]
|
||
for start, idx in offs:
|
||
if start <= offset:
|
||
best = idx
|
||
else:
|
||
break
|
||
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(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:
|
||
if not os.path.exists(p):
|
||
continue
|
||
with open(p, encoding="utf-8") as fh:
|
||
for line in fh:
|
||
s = line.strip()
|
||
if not s or s.startswith("#"):
|
||
continue
|
||
s = s.split(" #", 1)[0].strip()
|
||
if s:
|
||
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
|
||
|
||
|
||
# --- кнопка «В словарь»: пользовательский слой *.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 = {
|
||
"TYPOS": "орфография",
|
||
"GRAMMAR": "грамматика",
|
||
"PUNCTUATION": "пунктуация",
|
||
"CASING": "заглавные",
|
||
"TYPOGRAPHY": "типографика",
|
||
}
|
||
|
||
def lt_stage(paras: List[str], progress) -> List[dict]:
|
||
chunks = make_chunks(paras, LT_CHUNK, "\n\n")
|
||
findings: List[dict] = []
|
||
total = max(1, len(chunks))
|
||
done = 0
|
||
|
||
def one(chunk_and_offs):
|
||
text, offs = chunk_and_offs
|
||
with httpx.Client(base_url=LT_URL) as c:
|
||
r = c.post("/v2/check", data={
|
||
"text": text, "language": "ru-RU",
|
||
"level": "picky", "disabledRules": LT_DISABLED,
|
||
}, timeout=300)
|
||
r.raise_for_status()
|
||
matches = r.json().get("matches", [])
|
||
found = []
|
||
for m in matches:
|
||
offset = m.get("offset", 0) or 0
|
||
length = m.get("length", 0) or 0 # в LT 6.8 errorLength умер, длина теперь здесь
|
||
s, e = max(0, offset - 60), min(len(text), offset + length + 60)
|
||
before, frag, after = text[s:offset], text[offset:offset + length], text[offset + length:e]
|
||
rule = m.get("rule", {})
|
||
cat = rule.get("category") or {}
|
||
found.append({
|
||
"para": para_of_offset(offs, offset) + 1,
|
||
"source": "LanguageTool",
|
||
"kind": LT_KIND.get(cat.get("id", ""), cat.get("name", "прочее")),
|
||
"rule": rule.get("id", ""),
|
||
"message": (m.get("message", "") or "").strip(),
|
||
"fragment": frag,
|
||
"context": [before, frag, after],
|
||
"replacements": [rep.get("value", "") for rep in m.get("replacements", [])][:5],
|
||
})
|
||
return found
|
||
|
||
with ThreadPoolExecutor(max_workers=LT_PARALLEL) as ex:
|
||
for found in ex.map(one, chunks):
|
||
done += 1
|
||
progress(0.05 + 0.62 * done / total, f"орфография и грамматика: {done}/{total} фрагментов")
|
||
findings.extend(found)
|
||
findings.sort(key=lambda f: f["para"])
|
||
return findings
|
||
|
||
# --- LLM (пунктуация) ---
|
||
|
||
LLM_SYSTEM = (
|
||
"Ты корректор русской пунктуации. Тебе дают нумерованные абзацы служебного документа. "
|
||
"Найди ТОЛЬКО очевидные пунктуационные ошибки: пропущенная запятая перед «что», «который», "
|
||
"«а», «но», «однако», и в деепричастных оборотах; явно лишняя запятая; пропущенное или лишнее тире; "
|
||
"незакрытые и лишние кавычки. "
|
||
"НЕ отмечай: авторские знаки, дефисы в составных словах, сокращения служб (МЧС, РОЧС, ГДЗС, "
|
||
"УЗ, ЦРБ, ПАСС и под.), склейки слов на границах абзацев, отсутствие тире в таблицах и списках. "
|
||
"НЕ исправляй слова, орфографию и формулировки. "
|
||
"Если в абзаце ошибок нет или сомневаешься — не включай его в ответ: ложная находка хуже пропущенной. "
|
||
'Ответом строго JSON-массив без пояснений: [{"para": <номер абзаца>, '
|
||
'"fragment": "<отрезок с ошибкой, дословно из текста, до 120 знаков>", '
|
||
'"fixed": "<тот же отрезок с исправленной пунктуацией>", "why": "<кратко, до 60 знаков>"}]. '
|
||
"Если ошибок нет, ответь []. "
|
||
'Пример: [{"para": 5, "fragment": "дежурный сообщил что", "fixed": "дежурный сообщил, что", "why": "запятая перед что"}]'
|
||
)
|
||
|
||
LLM_VERIFY_SYSTEM = (
|
||
"Ты строгий проверщик русской пунктуации. Тебе дают абзац текста и предполагаемую правку пунктуации. "
|
||
"Верни true ТОЛЬКО если правка обязательно нужна по правилам русской пунктуации и не меняет слова. "
|
||
'Сомневаешься, правка спорная или стилистическая — false. '
|
||
'Ответ строго JSON: {"is_error": true, "why": "..."} или {"is_error": false}.'
|
||
)
|
||
|
||
def _norm_ws(s: str) -> str:
|
||
return re.sub(r"\s+", " ", s).strip().lower()
|
||
|
||
def llm_find(client: httpx.Client, chunk_paras: List[Tuple[int, str]]) -> Tuple[List[dict], bool]:
|
||
"""chunk_paras: [(индекс абзаца, текст)]. Возвращает (находки, успех)."""
|
||
user = "\n\n".join(f"Абзац {idx}: {text}" for idx, text in chunk_paras)
|
||
payload = {
|
||
"model": LLM_MODEL,
|
||
"messages": [{"role": "system", "content": LLM_SYSTEM},
|
||
{"role": "user", "content": user}],
|
||
"temperature": 0,
|
||
"max_tokens": 1500,
|
||
"stream": False,
|
||
}
|
||
try:
|
||
r = client.post("/chat/completions", json=payload, timeout=420)
|
||
r.raise_for_status()
|
||
content = (r.json().get("choices") or [{}])[0].get("message", {}).get("content", "")
|
||
except Exception:
|
||
return [], False
|
||
lo, hi = content.find("["), content.rfind("]")
|
||
if lo < 0 or hi <= lo:
|
||
return [], True
|
||
try:
|
||
arr = json.loads(content[lo:hi + 1])
|
||
except json.JSONDecodeError:
|
||
return [], True
|
||
paras = dict(chunk_paras)
|
||
out = []
|
||
for it in arr if isinstance(arr, list) else []:
|
||
if not isinstance(it, dict):
|
||
continue
|
||
frag = str(it.get("fragment", "")).strip()
|
||
fixed = str(it.get("fixed", "")).strip()
|
||
why = str(it.get("why", "")).strip()
|
||
if not frag or not fixed or _norm_ws(frag) == _norm_ws(fixed):
|
||
continue
|
||
pnum = it.get("para")
|
||
target = paras.get(pnum) if isinstance(pnum, int) else None
|
||
if target is None:
|
||
for idx, text in chunk_paras:
|
||
if _norm_ws(frag) in _norm_ws(text):
|
||
target, pnum, = text, idx
|
||
break
|
||
if target is None or _norm_ws(frag) not in _norm_ws(target):
|
||
out.append({"para": pnum + 1 if isinstance(pnum, int) else 0,
|
||
"source": "LLM", "kind": "пунктуация (не найдена в тексте)",
|
||
"rule": "llm_punct", "message": why or "проверьте вручную",
|
||
"fragment": frag, "context": ["", frag, ""],
|
||
"replacements": [fixed]})
|
||
continue
|
||
pos = _norm_ws(target).find(_norm_ws(frag))
|
||
s, e = max(0, pos - 60), min(len(target), pos + len(frag) + 60)
|
||
out.append({"para": pnum + 1, "source": "LLM", "kind": "пунктуация",
|
||
"rule": "llm_punct", "message": why or "пунктуация: предложенная правка",
|
||
"fragment": frag,
|
||
"context": [target[s:pos], frag, target[pos + len(frag):e]],
|
||
"replacements": [fixed]})
|
||
return out, True
|
||
|
||
def llm_verify_one(client: httpx.Client, context: str, frag: str, fixed: str, why: str) -> bool:
|
||
"""Второй проход: подтверждает ли модель предложенную правку. True = оставляем находку."""
|
||
payload = {
|
||
"model": LLM_MODEL,
|
||
"messages": [
|
||
{"role": "system", "content": LLM_VERIFY_SYSTEM},
|
||
{"role": "user",
|
||
"content": f"Абзац: {context}\n\nПредполагаемая правка пунктуации: «{frag}» → «{fixed}»."
|
||
+ (f" Пояснение: {why}" if why else "")},
|
||
],
|
||
"temperature": 0,
|
||
"max_tokens": 200,
|
||
"stream": False,
|
||
}
|
||
try:
|
||
r = client.post("/chat/completions", json=payload, timeout=180)
|
||
r.raise_for_status()
|
||
content = (r.json().get("choices") or [{}])[0].get("message", {}).get("content", "")
|
||
lo, hi = content.find("{"), content.rfind("}")
|
||
if lo < 0 or hi <= lo:
|
||
return True
|
||
verdict = json.loads(content[lo:hi + 1])
|
||
return bool(verdict.get("is_error"))
|
||
except Exception:
|
||
return True # отказ связи/парсинга — находку не выбрасываем
|
||
|
||
|
||
def llm_available() -> bool:
|
||
if LLM_MODE == "off" or not LLM_BASE:
|
||
return False
|
||
if LLM_MODE == "on":
|
||
return True
|
||
try:
|
||
with httpx.Client(base_url=LLM_BASE) as c:
|
||
c.get("/models", timeout=4)
|
||
return True
|
||
except Exception:
|
||
return False
|
||
|
||
def llm_stage(paras: List[str], progress) -> Tuple[List[dict], dict]:
|
||
chunks = make_chunks(paras, LLM_CHUNK, "\n\n")
|
||
grouped = [[(idx, paras[idx]) for _, idx in offs] for _, offs in chunks]
|
||
findings: List[dict] = []
|
||
stats = {"llm_chunks": len(grouped), "llm_chunks_failed": 0, "llm_seconds": 0.0}
|
||
total = max(1, len(grouped))
|
||
done = 0
|
||
t0 = time.time()
|
||
|
||
def one(chunk_paras):
|
||
with httpx.Client(base_url=LLM_BASE) as c:
|
||
return llm_find(c, chunk_paras)
|
||
|
||
with ThreadPoolExecutor(max_workers=LLM_PARALLEL) as ex:
|
||
for found, ok in ex.map(one, grouped):
|
||
done += 1
|
||
stats["llm_chunks_failed"] += int(not ok)
|
||
findings.extend(found)
|
||
progress(0.70 + 0.26 * done / total, f"пунктуация (LLM): {done}/{total} фрагментов")
|
||
|
||
# второй проход: модель сама подтверждает каждую находку (борьба с перестраховкой)
|
||
stats["llm_verify_dropped"] = 0
|
||
if LLM_VERIFY_MODE == "on" and findings:
|
||
vtotal = max(1, len(findings))
|
||
vdone = 0
|
||
|
||
def verify_one(item):
|
||
pnum = item["para"]
|
||
target = paras[pnum - 1] if 0 < pnum <= len(paras) else ""
|
||
frag = item.get("fragment", "")
|
||
fixed = (item.get("replacements") or [""])[0]
|
||
lo = _norm_ws(target.lower()).find(_norm_ws(frag).lower()[:80]) if (frag and target) else -1
|
||
context = target[max(0, lo - 150): lo + len(frag) + 150] if lo >= 0 else (frag or target[:300])
|
||
with httpx.Client(base_url=LLM_BASE) as c:
|
||
keep = llm_verify_one(c, context, frag, fixed, item.get("message", ""))
|
||
return item, keep
|
||
|
||
with ThreadPoolExecutor(max_workers=LLM_PARALLEL) as ex:
|
||
for item, keep in ex.map(verify_one, list(findings)):
|
||
vdone += 1
|
||
progress(0.96 + 0.02 * vdone / vtotal, f"проверка правок (LLM): {vdone}/{vtotal}")
|
||
if not keep:
|
||
findings.remove(item)
|
||
stats["llm_verify_dropped"] = stats.get("llm_verify_dropped", 0) + 1
|
||
findings.sort(key=lambda f: f["para"])
|
||
stats["llm_seconds"] = round(time.time() - t0, 1)
|
||
return findings, stats
|
||
|
||
# --- worker ---
|
||
|
||
def run_job(job_id: str, data: bytes, filename: str, use_llm: bool):
|
||
try:
|
||
JOBS[job_id]["stage"] = "разбор документа"
|
||
JOBS[job_id]["progress"] = 0.02
|
||
paras = [clean_text(t) for t in extract_paragraphs(data, filename)]
|
||
if not paras:
|
||
raise ValueError("В документе не найдено текста")
|
||
JOBS[job_id]["total_paras"] = len(paras)
|
||
|
||
t0 = time.time()
|
||
def set_stage(p, s):
|
||
JOBS[job_id].update(stage=s, progress=max(JOBS[job_id].get("progress", 0), p))
|
||
lt_f = lt_stage(paras, set_stage)
|
||
lt_secs = round(time.time() - t0, 1)
|
||
|
||
items = list(lt_f)
|
||
llm_stats = {"enabled": False}
|
||
if use_llm and llm_available():
|
||
set_stage(0.69, "пунктуация (LLM)")
|
||
llm_f, llm_stats = llm_stage(paras, set_stage)
|
||
items.extend(llm_f)
|
||
llm_stats["enabled"] = True
|
||
elif use_llm:
|
||
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()
|
||
frag_first_repl: dict = {}
|
||
for it in items:
|
||
frag = (it.get("fragment") or "").strip().lower()
|
||
if frag:
|
||
frag_counts[frag] += 1
|
||
if frag not in frag_first_repl:
|
||
repls = it.get("replacements") or []
|
||
frag_first_repl[frag] = repls[0] if repls else ""
|
||
fragments_top = [
|
||
{"fragment": k, "count": v, "top_replacement": frag_first_repl.get(k, "")}
|
||
for k, v in frag_counts.most_common(100)
|
||
]
|
||
page_acc = 0
|
||
page_map = []
|
||
for p in paras:
|
||
page_map.append(page_acc // CHARS_PER_PAGE + 1)
|
||
page_acc += len(p)
|
||
report = {
|
||
"file": filename,
|
||
"paragraphs": len(paras),
|
||
"pages_est": page_acc // CHARS_PER_PAGE + 1,
|
||
"texts": paras, # полный текст абзацев — для подсветки в UI
|
||
"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"),
|
||
}
|
||
JOBS[job_id].update(status="done", progress=1.0, stage="готово", report=report)
|
||
except Exception as e: # noqa: BLE001
|
||
import traceback
|
||
traceback.print_exc()
|
||
JOBS[job_id].update(status="error", stage="", error=str(e))
|
||
|
||
# --- API ---
|
||
|
||
@app.get("/api/health")
|
||
def health():
|
||
lt = {"ok": False}
|
||
try:
|
||
with httpx.Client(base_url=LT_URL) as c:
|
||
lt = {"ok": c.get("/v2/languages", timeout=6).status_code == 200}
|
||
except Exception:
|
||
pass
|
||
llm = llm_available()
|
||
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")):
|
||
data = await file.read()
|
||
if len(data) > MAX_MB * 1024 * 1024:
|
||
raise HTTPException(413, f"Файл больше {MAX_MB} МБ")
|
||
if not data:
|
||
raise HTTPException(400, "Пустой файл")
|
||
job_id = uuid.uuid4().hex[:12]
|
||
JOBS[job_id] = {"status": "running", "progress": 0.0, "stage": "в очереди"}
|
||
threading.Thread(target=run_job, args=(job_id, data, file.filename, use_llm != "false"), daemon=True).start()
|
||
return {"job_id": job_id}
|
||
|
||
@app.get("/api/job/{job_id}")
|
||
def api_job(job_id: str):
|
||
j = JOBS.get(job_id)
|
||
if j is None:
|
||
raise HTTPException(404, "Задание не найдено")
|
||
snap = dict(j)
|
||
if snap.get("status") != "done":
|
||
snap.pop("report", None)
|
||
return snap
|
||
|
||
@app.get("/api/report/{job_id}")
|
||
def api_report(job_id: str):
|
||
j = JOBS.get(job_id)
|
||
if j is None:
|
||
raise HTTPException(404, "Задание не найдено")
|
||
if j.get("status") != "done":
|
||
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-отчёт той же логики, что и веб-страница: сводка -> замечания по
|
||
абзацам (текст абзаца с подсветкой ошибок + список правок) -> слова-топ."""
|
||
import re as _re # noqa: F401
|
||
from docx.shared import RGBColor, Pt
|
||
from collections import Counter as _Counter # noqa: F401
|
||
|
||
MARK_COLOR = RGBColor(0xB3, 0x26, 0x1E)
|
||
|
||
def mark_spans(text: str, frags: list) -> list:
|
||
"""Диапазоны фрагментов внутри текста (без пересечений)."""
|
||
spans = []
|
||
for fr in sorted({f.strip() for f in frags if f.strip()}, key=len, reverse=True):
|
||
idx = text.lower().find(fr.lower())
|
||
while idx >= 0:
|
||
spans.append((idx, idx + len(fr)))
|
||
idx = text.lower().find(fr.lower(), idx + 1)
|
||
spans.sort()
|
||
merged: list = []
|
||
for s, e in spans:
|
||
if merged and s < merged[-1][1]:
|
||
merged[-1] = (merged[-1][0], max(merged[-1][1], e))
|
||
else:
|
||
merged.append((s, e))
|
||
return merged
|
||
|
||
def add_marked(par, text: str, frags: list):
|
||
spans = mark_spans(text, frags)
|
||
pos = 0
|
||
for s, e in spans:
|
||
if pos < s:
|
||
par.add_run(clean_text(text[pos:s]))
|
||
r = par.add_run(clean_text(text[s:e]))
|
||
r.bold = True
|
||
r.font.color.rgb = MARK_COLOR
|
||
pos = e
|
||
if pos < len(text):
|
||
par.add_run(clean_text(text[pos:]))
|
||
if not text.strip():
|
||
par.add_run("—")
|
||
|
||
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"Файл: {clean_text(rep['file'])}").bold = True
|
||
total = sum(rep["counts"].values())
|
||
doc.add_paragraph(
|
||
f"Дата: {rep['finished']} Абзацев: {rep['paragraphs']} "
|
||
f"Объём: ≈{rep['pages_est']} стр. Замечаний: {total}"
|
||
)
|
||
# сводка типов — как чипы веба
|
||
st = doc.add_paragraph()
|
||
st.add_run("Типы замечаний: ").bold = True
|
||
for k, v in sorted(rep["counts"].items(), key=lambda kv: -kv[1]):
|
||
st.add_run(f"{k}: {v} ")
|
||
if rep.get("exceptions_dropped"):
|
||
doc.add_paragraph(f"Отсеяно по словарю-исключениям: {rep['exceptions_dropped']}")
|
||
llm_info = rep.get("llm") or {}
|
||
if llm_info.get("enabled"):
|
||
doc.add_paragraph(
|
||
f"Пунктуация (LLM): {llm_info.get('llm_seconds', 0)} с"
|
||
+ (f", моделью отфильтровано: {llm_info['llm_verify_dropped']}" if "llm_verify_dropped" in llm_info else "")
|
||
+ (f", фрагментов не обработано: {llm_info['llm_chunks_failed']}" if llm_info.get("llm_chunks_failed") else "")
|
||
)
|
||
elif llm_info.get("note"):
|
||
doc.add_paragraph(f"LLM: {llm_info['note']}")
|
||
|
||
# --- замечания по абзацам (логика веб-группировки) ---
|
||
doc.add_heading("Замечания по абзацам", level=1)
|
||
texts = rep.get("texts") or []
|
||
page_map = rep.get("page_map") or []
|
||
groups: dict = {}
|
||
for f in rep["findings"]:
|
||
groups.setdefault(f["para"], []).append(f)
|
||
if not groups:
|
||
doc.add_paragraph("Замечаний не найдено.")
|
||
for para in sorted(groups):
|
||
fs = groups[para]
|
||
kinds = sorted({fs_i.get("kind", "") for fs_i in fs})
|
||
hd = doc.add_paragraph()
|
||
r = hd.add_run(clean_text(f"Абзац № {para}"))
|
||
r.bold = True
|
||
page = page_map[para - 1] if para - 1 < len(page_map) else "?"
|
||
hd.add_run(f" (≈ стр. {page}) — {len(fs)} замеч. ({', '.join(kinds)})")
|
||
text = texts[para - 1] if para - 1 < len(texts) else ""
|
||
pt = doc.add_paragraph()
|
||
add_marked(pt, clean_text(text), [f.get("fragment", "") for f in fs])
|
||
for f in fs:
|
||
fp = doc.add_paragraph()
|
||
fp.paragraph_format.left_indent = Pt(18)
|
||
kb = fp.add_run(clean_text(f"[{f.get('kind', '')}] "))
|
||
kb.bold = True
|
||
msg = clean_text(f.get("message", "") or "")
|
||
if msg:
|
||
fp.add_run(msg + " ")
|
||
repls = [clean_text(x) for x in (f.get("replacements") or [])[:3]]
|
||
if repls:
|
||
fp.add_run("Варианты: ").italic = True
|
||
fp.add_run(" / ".join(repls))
|
||
if para != sorted(groups)[-1]:
|
||
doc.add_paragraph("")
|
||
|
||
# --- словарь частых фрагментов (как кнопка «Словарь слов» в вебе) ---
|
||
if rep.get("fragments_top"):
|
||
doc.add_heading("Частые фрагменты (кандидаты на словарь исключений)", level=2)
|
||
tbl = doc.add_table(rows=1, cols=3)
|
||
tbl.style = "Table Grid"
|
||
for i, htxt in enumerate(["Фрагмент", "Раз", "Подсказка LT"]):
|
||
tbl.rows[0].cells[i].text = htxt
|
||
for fr in rep["fragments_top"]:
|
||
row = tbl.add_row().cells
|
||
row[0].text = clean_text(fr["fragment"])
|
||
row[1].text = str(fr["count"])
|
||
row[2].text = clean_text(fr.get("top_replacement", ""))
|
||
|
||
buf: io.BytesIO = 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") |