Compare commits

..
4 Commits
8 changed files with 206 additions and 9 deletions

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"):
+3 -1
View File
@@ -2,4 +2,6 @@ fastapi
uvicorn uvicorn
httpx httpx
python-docx python-docx
python-multipart python-multipart
openpyxl
python-pptx
+2 -1
View File
@@ -55,7 +55,8 @@ Ollama и модель пунктуации. Установка идёт в по
## Форматы и ограничения ## Форматы и ограничения
- Проверяются `.docx`, `.xlsx` (ячейки с длинным текстом), `.pptx` (слайды, - Проверяются `.docx`, `.xlsx` (ячейки с длинным текстом), `.pptx` (слайды,
таблицы, заметки докладчика) и `.txt`; старые `.doc` — пересохранить таблицы, заметки докладчика) и `.txt`; старые `.doc` конвертируются автоматически
(нужен установленный Word), при сбое конвертации — пересохранить в `.docx`
- Словарь специальных сокращений пополняется после пробной эксплуатации — - Словарь специальных сокращений пополняется после пробной эксплуатации —
часть спецтерминов может подсвечиваться ошибочно, такие места отмечайте часть спецтерминов может подсвечиваться ошибочно, такие места отмечайте
для передачи администратору для передачи администратору
+19
View File
@@ -0,0 +1,19 @@
@echo off
REM Undo enable_ssh.bat: stop and disable sshd, close the debug firewall rule.
net session >nul 2>&1
if %errorlevel% neq 0 (
echo Need admin rights. Relaunching elevated...
powershell -NoProfile -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
exit /b
)
echo === Stop and disable sshd ===
net stop sshd 2>nul
sc config sshd start= disabled >nul
sc query sshd | findstr STATE
netsh advfirewall firewall delete rule name="docdebug-ssh" >nul
echo Firewall rule docdebug-ssh removed.
echo.
echo === SSH access disabled ===
pause
+65
View File
@@ -0,0 +1,65 @@
@echo off
REM Enable LAN-only SSH access on this PC for docchecker remote debugging. v2
REM v2 changes: 1) portable OpenSSH from GitHub fallback when Windows Update
REM refuses the FoD capability (error 0x80242005); 2) ACL via language-neutral
REM SIDs (local name mapping broke on ru-Windows); 3) honest final check -
REM DONE only when the sshd service is actually RUNNING and port 22 listens.
REM Scope stays LAN-only: firewall rule allows TCP 22 from 192.168.0.0/24, key auth only.
REM Revert with disable_ssh.bat from the same folder.
net session >nul 2>&1
if %errorlevel% neq 0 (
echo Need admin rights. Relaunching elevated...
powershell -NoProfile -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
exit /b
)
echo === 1. OpenSSH Server: try Windows capability ===
powershell -NoProfile -Command "$c = Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH.Server*'; if ($c.State -ne 'Installed') { try { $c | Add-WindowsCapability -Online | Out-Null } catch {}; $s = (Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH.Server*').State; Write-Output ('STATE=' + $s) } else { Write-Output 'STATE=Installed' }"
powershell -NoProfile -Command "if ((Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH.Server*').State -eq 'Installed') { exit 0 } else { exit 1 }"
if %errorlevel% equ 0 goto :svc
echo === 1b. Windows Update refused - portable OpenSSH from GitHub ===
if not exist "C:\ProgramData\sshportable" mkdir "C:\ProgramData\sshportable"
powershell -NoProfile -Command "try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -UseBasicParsing -Uri 'https://github.com/PowerShell/Win32-OpenSSH/releases/download/v9.5.0.0p1-Beta/OpenSSH-Win64.zip' -OutFile 'C:\ProgramData\sshportable\ssh.zip'; exit 0 } catch { Write-Output $_.Exception.Message; exit 1 }"
if %errorlevel% neq 0 goto :err
powershell -NoProfile -Command "Expand-Archive -Force 'C:\ProgramData\sshportable\ssh.zip' 'C:\ProgramData\sshportable'"
powershell -NoProfile -ExecutionPolicy Bypass -File "C:\ProgramData\sshportable\OpenSSH-Win64\install-sshd.ps1"
if %errorlevel% neq 0 goto :err
:svc
echo === 2. Public key for administrators - ACL via SIDs ===
if not exist "C:\ProgramData\ssh" mkdir "C:\ProgramData\ssh"
echo ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKdrZtRRqRwyQYHHJTepJnUFS159250wMVQxnVnfjC5H docchecker-debug@macbookair>"C:\ProgramData\ssh\administrators_authorized_keys"
icacls "C:\ProgramData\ssh\administrators_authorized_keys" /inheritance:r /grant *S-1-5-18:F /grant *S-1-5-32-544:F >nul
if %errorlevel% neq 0 goto :err
if exist "C:\ProgramData\sshportable\OpenSSH-Win64\sshd_default_config" if not exist "C:\ProgramData\ssh\sshd_config" copy /y "C:\ProgramData\sshportable\OpenSSH-Win64\sshd_default_config" "C:\ProgramData\ssh\sshd_config" >nul
echo === 3. Service sshd: automatic + start ===
sc config sshd start= auto >nul
net start sshd 2>nul
sc query sshd | findstr "STATE"
echo === 4. Firewall: TCP 22 only from 192.168.0.0/24 ===
netsh advfirewall firewall delete rule name="docdebug-ssh" >nul 2>&1
netsh advfirewall firewall add rule name="docdebug-ssh" dir=in action=allow protocol=TCP localport=22 remoteip=192.168.0.0/24 profile=any >nul
echo === 5. Verify ===
powershell -NoProfile -Command "$svc = Get-Service sshd -ErrorAction SilentlyContinue; if ($svc -and $svc.Status -eq 'Running' -and (netstat -ano | Select-String ':22.*LISTENING')) { Write-Output 'CHECK=OK' } else { Write-Output 'CHECK=FAILED'; exit 1 }"
if %errorlevel% neq 0 goto :err
echo.
echo === DONE ===
echo OPERATOR LINE - copy or photo this:
whoami
hostname
echo.
pause
exit /b 0
:err
echo.
echo === FAILED - take a photo of this window ===
pause
exit /b 1
+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"