Files
docchecker/static/index.html
T

257 lines
16 KiB
HTML
Raw Permalink 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.
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Проверка документов</title>
<style>
:root { --line:#d7d7d7; --bg:#f5f5f4; --panel:#fff; }
* { box-sizing: border-box; }
body { font: 13px/1.45 -apple-system, "Segoe UI", Roboto, Arial, sans-serif; color:#1c1c1c; background:var(--bg); margin:0; padding:24px; }
.wrap { max-width: 1000px; margin: 0 auto; }
h1 { font-size: 18px; margin: 0 0 14px; font-weight: 600; }
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 6px; padding: 14px; margin-bottom: 14px; }
.badge { display:inline-block; padding: 1px 8px; border-radius: 10px; font-size: 11px; color:#fff; margin-right:6px; }
.b-spell { background:#b3261e; } .b-grammar { background:#c47f17; } .b-punct { background:#2455a4; } .b-llm { background:#6a3fa0; } .b-ok { background:#2e7d32; } .b-off { background:#9e9e9e; }
.btn { background:#1a4d8f; color:#fff; border:0; border-radius:5px; padding:8px 18px; font-size:14px; cursor:pointer; }
.btn:disabled { background:#a3b7cc; cursor:default; }
#drop { border: 2px dashed var(--line); border-radius: 6px; padding: 26px; text-align:center; color:#555; cursor:pointer; margin-bottom:12px; }
#drop.drag { border-color:#1a4d8f; background:#eef3f9; }
#fileinfo { margin-top: 8px; font-size: 12px; color:#555; }
.prog { height: 8px; background:#e5e5e5; border-radius: 4px; overflow: hidden; margin: 10px 0 6px; }
.prog > div { height: 100%; background: #1a4d8f; width: 0%; transition: width .4s; }
#stage { font-size: 12px; color:#555; }
.summary .chip { display:inline-block; border:1px solid var(--line); background:#fff; border-radius: 14px; padding: 3px 12px; margin: 2px 6px 2px 0; cursor:pointer; font-size:12px; }
.summary .chip.active { background:#1a4d8f; border-color:#1a4d8f; color:#fff; }
details.pgroup { border: 1px solid var(--line); border-radius: 5px; margin-bottom: 8px; background: #fff; }
details.pgroup > summary { cursor: pointer; padding: 8px 12px; font-size: 13px; list-style: none; display: flex; justify-content: space-between; align-items: center; }
details.pgroup > summary::-webkit-details-marker { display: none; }
details.pgroup > summary:hover { background:#f6f8fa; }
.ptext { padding: 8px 12px; border-top: 1px solid var(--line); color:#444; font-size: 12px; }
.ptext mark.err { background: #ffd7d2; border-bottom: 2px solid #b3261e; padding: 0 2px; }
.finding { padding: 8px 12px; border-top: 1px solid var(--line); font-size: 13px; }
.finding .ctx { font-family: "Segoe UI", Arial, sans-serif; }
.finding .ins { color:#b3261e; font-weight: 600; border-bottom: 2px solid #b3261e; }
.finding .why { color:#555; font-size: 12px; font-style: italic; }
.repl { display:inline-block; border:1px solid #2e7d32; color:#2e7d32; border-radius: 4px; padding: 1px 8px; margin: 3px 6px 0 0; cursor: pointer; font-size: 12px; background:#f2f8f2; }
.repl:hover { background:#e2f0e2; }
#statusline { font-size: 12px; color:#555; margin-bottom: 10px; }
.errbox { background:#fdecea; border:1px solid #f5c6c1; color:#8c1d18; border-radius:5px; padding:10px 12px; }
</style>
</head>
<body>
<div class="wrap">
<h1>Проверка документов — орфография и пунктуация</h1>
<div class="panel" id="drop">
Перетащите файл сюда или нажмите — <b>.docx</b>, <b>.xlsx</b>, <b>.pptx</b> или <b>.txt</b> (старый .doc пересохраните в .docx)
<input type="file" id="file" accept=".docx,.xlsx,.pptx,.txt" style="display:none">
<div id="fileinfo"></div>
</div>
<div class="panel" id="controls">
<label><input type="checkbox" id="usellm" checked> проверка пунктуации (LLM)</label>
<label><input type="checkbox" id="addforms" checked> в словарь — со всеми формами</label>
<button class="btn" id="go" disabled>Проверить</button>
<span id="statusline"></span>
<div class="prog" id="prog" style="display:none"><div></div></div>
<div id="stage"></div>
</div>
<div id="report"></div>
</div>
<script>
const $ = (id) => document.getElementById(id);
const KIND_BADGE = (k) => {
const s = (k||"").toLowerCase();
if (s.startsWith("орф")) return ["b-spell", k];
if (s.startsWith("грам")) return ["b-grammar", k];
if (s.startsWith("пунк")) return s.includes("llm") ? ["b-llm", "пунктуация (LLM)"] : ["b-punct", k];
return ["b-off", k || "прочее"];
};
let file = null, jobId = null, timer = null, lastReport = null, activeFilter = "all";
// health
async function health() {
try {
const r = await fetch("/api/health");
const h = await r.json();
$("statusline").innerHTML =
'Сервис проверки: <span class="badge ' + (h.lt.ok ? "b-ok" : "b-off") + '">' + (h.lt.ok ? "работает" : "недоступен") + "</span>" +
' Пунктуация (LLM): <span class="badge ' + (h.llm.available ? "b-llm" : "b-off") + '">' + (h.llm.available ? "подключена" : "не подключена") + "</span>";
if (!h.llm.available) $("usellm").disabled = true;
} catch (e) { $("statusline").textContent = "Сервис недоступен"; }
}
health();
// file pick
const drop = $("drop");
drop.onclick = () => $("file").click();
dragEvents();
function dragEvents() {
["dragover", "dragleave", "drop"].forEach(ev => drop.addEventListener(ev, e => {
e.preventDefault();
drop.classList.toggle("drag", ev === "dragover");
if (ev === "drop") setFile(e.dataTransfer.files[0]);
}));
}
$("file").onchange = (e) => setFile(e.target.files[0]);
function setFile(f) {
if (!f) return;
const ok = /\.(docx|xlsx|pptx|txt)$/i.test(f.name);
file = ok ? f : null;
$("fileinfo").textContent = ok ? f.name + " — " + (f.size/1024/1024).toFixed(2) + " МБ"
: "Формат не поддержан: нужен .docx, .xlsx, .pptx или .txt (.doc пересохраните)";
$("go").disabled = !file;
}
// run
$("go").onclick = () => {
if (!file) return;
const fd = new FormData();
fd.append("file", file);
fd.append("use_llm", $("usellm").checked && !$("usellm").disabled ? "true" : "false");
$("go").disabled = true;
$("report").innerHTML = "";
$("prog").style.display = "block"; $("prog").firstElementChild.style.width = "0%";
const xhr = new XMLHttpRequest();
xhr.open("POST", "/api/check");
xhr.upload.onprogress = (e) => { if (e.lengthComputable) $("prog").firstElementChild.style.width = (e.loaded/e.total*10).toFixed(0) + "%"; };
xhr.onload = () => {
if (xhr.status !== 200) { fail("Ошибка отправки: " + xhr.responseText); return; }
jobId = JSON.parse(xhr.responseText).job_id;
$("stage").textContent = "в очереди…";
timer = setInterval(poll, 700);
};
xhr.onerror = () => fail("Сеть: не удалось отправить файл");
xhr.send(fd);
};
function fail(msg) {
$("prog").style.display = "none";
$("report").innerHTML = '<div class="panel errbox">' + msg + "</div>";
$("go").disabled = false;
}
async function poll() {
let j;
try { j = await (await fetch("/api/job/" + jobId)).json(); } catch (e) { return; }
if (j.status === "error") { clearInterval(timer); fail("Ошибка: " + (j.error || "неизвестная")); return; }
$("stage").textContent = j.stage + (j.total_paras ? " — абзацев в документе: " + j.total_paras : "");
$("prog").firstElementChild.style.width = Math.round((j.progress||0)*95) + "%";
if (j.status === "done") {
clearInterval(timer);
$("prog").firstElementChild.style.width = "100%";
try { lastReport = await (await fetch("/api/report/" + jobId)).json(); } catch (e) { lastReport = null; }
render(loadFallback(j));
}
}
async function loadFallback(j) { return j; }
// report rendering
function render(r) {
if (r.report) lastReport = r.report;
const rep = lastReport;
if (!rep) { fail("Отчёт недоступен"); return; }
const L = rep.llm || {};
const chips = ['<span class="chip active" data-f="all">все: ' + rep.findings.length + "</span>"];
const byKind = {};
rep.findings.forEach(f => { const k = f.kind.split("(")[0].trim(); byKind[k] = (byKind[k]||0)+1; });
Object.entries(byKind).forEach(([k,v]) => chips.push('<span class="chip" data-f="' + k + '">' + esc(k) + ": " + v + "</span>"));
let info = '<div class="panel summary">' +
"<b>" + esc(rep.file) + "</b> — " + rep.paragraphs + " абзацев ≈ " + rep.pages_est + " стр. · " +
"орфография/грамматика " + rep.lt_seconds + " с" +
(L.enabled ? " · пунктуация (LLM) " + (L.llm_seconds||0) + " с" + (L.llm_chunks_failed ? ", фрагментов не обработано: " + L.llm_chunks_failed : "") : " · LLM: " + esc(L.note || "не использовалась")) +
'<br>' + chips.join("") +
' <span style="float:right"><button class="btn" style="padding:4px 10px;font-size:12px;background:#6a3fa0" id="dlw">Отчёт (.docx)</button> <button class="btn" style="padding:4px 10px;font-size:12px;background:#555" id="dlw2">Словарь слов (txt)</button></span></div>';
const groups = {};
rep.findings.forEach(f => (groups[f.para] = groups[f.para] || []).push(f));
let body = Object.entries(groups).sort((a,b)=>a[0]-b[0]).map(([para, fs]) => {
const badges = fs.map(f => { const [cls,name] = KIND_BADGE(f.kind); return '<span class="badge ' + cls + '">' + esc(name) + "</span>"; }).join("");
const items = fs.map(f => {
const [b, c, aRaw] = f.context || ["", "", ""];
const a = aRaw || "";
const repls = (f.replacements || []).map(x => '<span class="repl" data-t="' + esc(x) + '">' + esc(x) + "</span>").join("");
const fi = rep.findings.indexOf(f);
const dictbtns = '<span class="dictbtns"><button class="btn dictadd" style="padding:1px 8px;font-size:11px;background:#2e7d32" data-i="' + fi + '" data-t="exceptions" title="Больше не показывать этот фрагмент (запись в exceptions.local.txt; словарь перечитывается при каждой проверке — рестарт не нужен)">В словарь</button>' +
' <button class="btn dictadd" style="padding:1px 8px;font-size:11px;background:#616161" data-i="' + fi + '" data-t="toponyms" title="Топоним/слово из наименований — запись в toponyms.local.txt">Топоним</button></span>';
return '<div class="finding"><span class="badge ' + KIND_BADGE(f.kind)[0] + '">' + esc(KIND_BADGE(f.kind)[1]) + "</span> " +
'<span class="ctx">' + esc(tail(b.replace(/\s+/g, " "), 50)) + '<span class="ins">' + esc(f.fragment) + "</span>" + esc(head(a.replace(/\s+/g, " "), 50)) + "</span> " +
(f.message && !f.message.includes(f.fragment) ? '<div class="why">' + esc(f.message) + "</div>" : "") +
(repls ? "<div>Варианты <span class='why'>(нажмите — копируется)</span>: " + repls + "</div>" : "") + dictbtns + "</div>";
}).join("");
return '<details class="pgroup" ' + (Object.keys(groups).length < 4 ? "open" : "") + "><summary><span>№ " + para + " " + (rep.page_map ? "(≈ стр. " + rep.page_map[para-1] + ")" : "") + "</span><span>" + badges + "</span></summary>" +
(rep.texts ? '<div class="ptext">' + paraHtml(rep.texts[para-1], fs) + "</div>" : "") + items + "</details>";
}).join("");
$("report").innerHTML = info + (body || '<div class="panel">Замечаний не найдено.</div>');
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 = "скопировано"; });
document.querySelectorAll(".dictadd").forEach(b => b.onclick = () => dictAdd(b));
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 + (x.top_replacement ? " -> " + x.top_replacement.replace(/\s+/g, " ") : "")).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) {
activeFilter = f;
document.querySelectorAll(".chip").forEach(c => c.classList.toggle("active", c.dataset.f === f));
document.querySelectorAll("details.pgroup").forEach(d => {
const hit = d.querySelectorAll(".finding").length === 0;
d.style.display = "none"; // групповой фильтр упрощаем: скрываем группы без совпадений выбранного вида
let any = false;
d.querySelectorAll(".finding .badge").forEach(b => { if (f === "all" || b.textContent.startsWith(f)) any = true; });
d.style.display = any ? "" : "none";
});
}
// кнопка «В словарь»: запись в пользовательский слой *.local.txt
async function dictAdd(btn) {
const i = parseInt(btn.dataset.i, 10);
const frag = (lastReport.findings[i] || {}).fragment || "";
const body = { job_id: jobId, fragment: frag, target: btn.dataset.t, forms: $("addforms").checked };
const send = () => fetch("/api/dict/add", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
let r = await send();
if (r.status === 409) {
let j = null; try { j = (await r.json()).detail; } catch (e) {}
const sugg = j && j.suggestion ? j.suggestion : "";
if (!window.confirm("Похоже на опечатку: LT предлагает «" + sugg + "».\nВсё равно исключить фрагмент «" + frag + "» из проверок?")) return;
body.confirm = true;
r = await send();
}
let j = {};
try { j = await r.json(); } catch (e) {}
if (!r.ok) { alert("Не добавлено: " + (j.detail && j.detail.message ? j.detail.message : (j.detail || r.status))); return; }
if (j.already) { btn.textContent = "уже в словаре"; btn.disabled = true; return; }
btn.textContent = "в словаре ✓";
btn.disabled = true;
const row = btn.closest(".finding");
if (row) { setTimeout(() => { row.style.display = "none"; }, 700); }
}
function esc(s) { const d = document.createElement("i"); d.textContent = s == null ? "" : String(s); return d.innerHTML; }
function tail(s, n) { return s && s.length > n ? "…" + s.slice(-n) : (s||""); }
function head(s, n) { return s && s.length > n ? s.slice(0, n) + "…" : (s||""); }
function paraHtml(text, fs) {
let out = esc(text);
(fs||[]).slice().sort((x,y)=>(y.fragment||"").length-(x.fragment||"").length).forEach(f => {
if (!f.fragment) return;
const rx = new RegExp(f.fragment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\s+/g, "\\s+"), "g");
out = out.replace(rx, (m) => "<mark class='err'>" + m + "</mark>");
});
return out;
}
function download() {
const rep = lastReport; if (!rep) return;
const html = "<html><meta charset='utf-8'><title>Отчёт " + esc(rep.file) + "</title><body style='font-family:Arial;width:900px'><h2>Отчёт: " + esc(rep.file) + "</h2><p>Всего замечаний: " + rep.findings.length + " · " + esc(rep.finished) + "</p>" +
rep.findings.map(f => "<p><b>№" + f.para + "</b> [" + esc(f.kind) + "] " + esc(f.message||"") + "<br>…<u>" + esc(f.fragment) + "</u>… " + ((f.replacements||[]).length ? " → <b>" + esc(f.replacements[0]) + "</b>" : "") + "</p>").join("") + "</body></html>";
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([html], {type: "text/html"}));
a.download = "otchet_" + (rep.file||"").replace(/\.[^.]+$/, "") + ".html";
a.click();
}
</script>
</body>
</html>