doc support: .doc auto-converts via Word COM (PowerShell, temp cleaned); no Word -> clear resave hint; UI accepts .doc
This commit is contained in:
1 parent
80d457b39f
commit
15c5ef89de
5 files changed
+119
-8
No files matched your search
@@ -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 # короче — это служебные ячейки, не проверяем
|
||||
|
||||
|
||||
@@ -148,7 +194,7 @@ def extract_paragraphs(data: bytes, filename: str) -> List[str]:
|
||||
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 и загрузите снова")
|
||||
return extract_paragraphs(doc_to_docx_bytes(data), name + "x")
|
||||
if name.endswith(".xlsx"):
|
||||
return extract_xlsx(data)
|
||||
if name.endswith(".pptx"):
|
||||
|
||||
Reference in new issue
Block a user