Initial import: document checker (LanguageTool + punctuation LLM, offline)
This commit is contained in:
commit
a34d7c8478
18 files changed
+1166
No files matched your search
@@ -0,0 +1,373 @@
|
||||
# -*- 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 httpx
|
||||
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.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()
|
||||
|
||||
# --- разбор документа ---
|
||||
|
||||
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 not name.endswith(".docx"):
|
||||
raise ValueError("Формат не поддержан: загрузите .docx или .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
|
||||
|
||||
# --- 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))
|
||||
counts: dict = {}
|
||||
for it in items:
|
||||
counts[it["kind"]] = counts.get(it["kind"], 0) + 1
|
||||
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,
|
||||
"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}}
|
||||
|
||||
@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.mount("/", StaticFiles(directory="static", html=True), name="static")
|
||||
Reference in new issue
Block a user