doc support: .doc auto-converts via Word COM (PowerShell, temp cleaned); no Word -> clear resave hint; UI accepts .doc

This commit is contained in:
Sadmin committed 2026-11-10 15:20:18 +03:00
1 parent 80d457b39f
commit 15c5ef89de
5 files changed
+119 -8

No files matched your search

+3 -2
View File
@@ -12,8 +12,9 @@
## Проверка документа ## Проверка документа
1. Перетащите файл (.docx / .xlsx / .pptx / .txt) в окно страницы и нажмите 1. Перетащите файл (.doc / .docx / .xlsx / .pptx / .txt) в окно страницы и нажмите
«Проверить». Старый формат .doc пересохраните в .docx. «Проверить». Старый .doc конвертируется автоматически (нужен установленный
Word); если конвертация не удалась — пересохраните в .docx вручную.
2. Дождитесь отчёта: чипы сверху показывают число замечаний по типам, 2. Дождитесь отчёта: чипы сверху показывают число замечаний по типам,
ниже — замечания по абзацам с подсветкой и вариантами исправления. ниже — замечания по абзацам с подсветкой и вариантами исправления.
3. Кнопка «Отчёт (.docx)» выгружает отчёт в Word. Кнопка «Словарь слов (txt)» 3. Кнопка «Отчёт (.docx)» выгружает отчёт в Word. Кнопка «Словарь слов (txt)»
+47 -1
View File
@@ -68,6 +68,52 @@ def clean_text(s: str) -> str:
# --- разбор документа --- # --- разбор документа ---
def doc_to_docx_bytes(data: bytes) -> bytes:
"""Конвертация .doc → .docx через установленный Word (COM из PowerShell).
Temp-файлы создаются и удаляются в %TEMP%; тексты наружу не уходят.
Без Word (или при сбое COM) — понятная подсказка оператору."""
import subprocess
import tempfile
import uuid
tmp = tempfile.gettempdir()
uid = uuid.uuid4().hex[:12]
src = os.path.join(tmp, "dc_%s.doc" % uid)
dst = os.path.join(tmp, "dc_%s.docx" % uid)
hint = ("Не удалось конвертировать .doc (нужен установленный Word): "
"пересохраните документ как .docx и загрузите снова")
try:
with open(src, "wb") as fh:
fh.write(data)
ps = (
"$ErrorActionPreference='Stop';"
"$w=New-Object -ComObject Word.Application;"
"$w.Visible=$false;$w.DisplayAlerts=0;"
"try{ $d=$w.Documents.Open('%s', $false, $true); "
"$d.SaveAs2('%s',16); $d.Close($false) }"
"finally{ $w.Quit() };"
"[GC]::Collect()"
) % (src, dst)
r = subprocess.run(
["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", ps],
timeout=90, capture_output=True)
if r.returncode != 0 or not os.path.exists(dst):
raise ValueError(hint)
with open(dst, "rb") as fh:
return fh.read()
except ValueError:
raise
except (OSError, subprocess.TimeoutExpired, subprocess.SubprocessError):
# TimeoutExpired может оставить невидимый WINWORD — не убиваем процесс
# пользователя принудительно (защита от потери его unsaved-документов).
raise ValueError(hint)
finally:
for p in (src, dst):
try:
if os.path.exists(p):
os.remove(p)
except OSError:
pass
MIN_CELL_CHARS = 20 # короче — это служебные ячейки, не проверяем MIN_CELL_CHARS = 20 # короче — это служебные ячейки, не проверяем
@@ -148,7 +194,7 @@ def extract_paragraphs(data: bytes, filename: str) -> List[str]:
text = data.decode("utf-8", "replace") text = data.decode("utf-8", "replace")
return [ln.rstrip() for ln in text.splitlines() if ln.strip()] return [ln.rstrip() for ln in text.splitlines() if ln.strip()]
if name.endswith(".doc"): if name.endswith(".doc"):
raise ValueError("Старый формат .doc: пересохраните документ как .docx и загрузите снова") return extract_paragraphs(doc_to_docx_bytes(data), name + "x")
if name.endswith(".xlsx"): if name.endswith(".xlsx"):
return extract_xlsx(data) return extract_xlsx(data)
if name.endswith(".pptx"): if name.endswith(".pptx"):
+2 -1
View File
@@ -55,7 +55,8 @@ Ollama и модель пунктуации. Установка идёт в по
## Форматы и ограничения ## Форматы и ограничения
- Проверяются `.docx`, `.xlsx` (ячейки с длинным текстом), `.pptx` (слайды, - Проверяются `.docx`, `.xlsx` (ячейки с длинным текстом), `.pptx` (слайды,
таблицы, заметки докладчика) и `.txt`; старые `.doc` — пересохранить таблицы, заметки докладчика) и `.txt`; старые `.doc` конвертируются автоматически
(нужен установленный Word), при сбое конвертации — пересохранить в `.docx`
- Словарь специальных сокращений пополняется после пробной эксплуатации — - Словарь специальных сокращений пополняется после пробной эксплуатации —
часть спецтерминов может подсвечиваться ошибочно, такие места отмечайте часть спецтерминов может подсвечиваться ошибочно, такие места отмечайте
для передачи администратору для передачи администратору
+4 -4
View File
@@ -43,8 +43,8 @@ details.pgroup > summary:hover { background:#f6f8fa; }
<div class="wrap"> <div class="wrap">
<h1>Проверка документов — орфография и пунктуация</h1> <h1>Проверка документов — орфография и пунктуация</h1>
<div class="panel" id="drop"> <div class="panel" id="drop">
Перетащите файл сюда или нажмите — <b>.docx</b>, <b>.xlsx</b>, <b>.pptx</b> или <b>.txt</b> (старый .doc пересохраните в .docx) Перетащите файл сюда или нажмите — <b>.docx</b>, <b>.xlsx</b>, <b>.pptx</b> или <b>.txt</b>; старый <b>.doc</b> конвертируется сам (нужен установленный Word)
<input type="file" id="file" accept=".docx,.xlsx,.pptx,.txt" style="display:none"> <input type="file" id="file" accept=".doc,.docx,.xlsx,.pptx,.txt" style="display:none">
<div id="fileinfo"></div> <div id="fileinfo"></div>
</div> </div>
<div class="panel" id="controls"> <div class="panel" id="controls">
@@ -95,10 +95,10 @@ function dragEvents() {
$("file").onchange = (e) => setFile(e.target.files[0]); $("file").onchange = (e) => setFile(e.target.files[0]);
function setFile(f) { function setFile(f) {
if (!f) return; if (!f) return;
const ok = /\.(docx|xlsx|pptx|txt)$/i.test(f.name); const ok = /\.(doc|docx|xlsx|pptx|txt)$/i.test(f.name);
file = ok ? f : null; file = ok ? f : null;
$("fileinfo").textContent = ok ? f.name + " — " + (f.size/1024/1024).toFixed(2) + " МБ" $("fileinfo").textContent = ok ? f.name + " — " + (f.size/1024/1024).toFixed(2) + " МБ"
: "Формат не поддержан: нужен .docx, .xlsx, .pptx или .txt (.doc пересохраните)"; : "Формат не поддержан: нужен .doc, .docx, .xlsx, .pptx или .txt";
$("go").disabled = !file; $("go").disabled = !file;
} }
+63
View File
@@ -0,0 +1,63 @@
# -*- coding: utf-8 -*-
"""Конвертация .doc через Word COM: без Word — внятная подсказка; temp-файлы чистятся."""
import io
import os
from types import SimpleNamespace
import pytest
import app
def _fake_run_factory(returncode=0, creates_dst=True):
"""Подмена subprocess.run: PowerShell 'конвертировал' — dst существует."""
calls = []
def fake_run(argv, timeout, capture_output):
calls.append((argv[-1], timeout))
if creates_dst:
dst = argv[-1].split("SaveAs2('", 1)[-1].split("'")[0]
open(dst, "wb").write(b"PK\x03\x04 fake-docx")
return SimpleNamespace(returncode=returncode)
return fake_run, calls
def test_doc_converted_and_temp_cleaned(monkeypatch):
import subprocess
fake_run, calls = _fake_run_factory()
monkeypatch.setattr(subprocess, "run", fake_run)
out = app.doc_to_docx_bytes(b"fake-doc-bytes")
assert out.startswith(b"PK")
assert len(calls) == 1 and calls[0][1] == 90
argv = calls[0][0]
# пути переданы: исходник с .doc, цель с .docx (SaveAs2 формат 16)
assert ".doc'" in argv and "SaveAs2('" in argv
dst = argv.split("SaveAs2('", 1)[-1].split("'")[0]
assert not os.path.exists(dst) # temp-файл удалён
def test_doc_without_word(monkeypatch):
import subprocess
fake_run, _ = _fake_run_factory(returncode=1, creates_dst=False)
monkeypatch.setattr(subprocess, "run", fake_run)
with pytest.raises(ValueError, match="пересохраните документ как .docx"):
app.doc_to_docx_bytes(b"broken")
def test_extract_paragraphs_doc_routes_through_converter(monkeypatch):
from docx import Document
doc = Document()
doc.add_paragraph("Первый абзац.")
doc.add_paragraph("Второй абзац.")
buf = io.BytesIO()
doc.save(buf)
seen = {}
def fake_convert(data):
seen["bytes"] = data
return buf.getvalue()
monkeypatch.setattr(app, "doc_to_docx_bytes", fake_convert)
paras = app.extract_paragraphs(b"whatever", "otchet.doc")
assert paras == ["Первый абзац.", "Второй абзац."]
assert seen["bytes"] == b"whatever"