Files
docchecker/app.py
T

553 lines
23 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- 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")
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_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()
# --- разбор документа ---
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
# --- словарь-исключения ---
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 = {
"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 знаков>"}]. '
"Если ошибок нет, ответь []. "
"Сокращения государственных органов и служб (МЧС, РОЧС, ГРОЧС, ОУСиС, РЦУРЧС, УМЧС, ГДЗС, СИЗ, УЗ, ЦРБ, ПАСС и подобные) — нормальные слова, не ошибки."
)
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_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} фрагментов")
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 = 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()
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:
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.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")