feat: GLM-путь читает .xls/.doc/.gsfx, таблицы .docx, OCR PDF-сканов, честный отказ .esw

Пункты 3,4,5,7,8 (GLM-путь _read_work_dir_files): .xls через xlrd (openpyxl BIFF не умеет);
.doc через catdoc; .docx теперь с ТАБЛИЦАМИ (сметные docx = таблицы, GLM их упускал);
.gsfx инлайн через parse_gsfx_file; PDF-скан (fitz дал <40 симв) → OCR tesseract-rus;
.esw/.oew/.cew/.bma → честный отказ «экспортируйте в АРПС/Excel», не тихий пропуск.
Хост-инструменты доставлены (xlrd/docx уже были; catdoc+pytesseract поставлены; tesseract+rus).
Real-тест на настоящих файлах: .xls(2125 строк)/.doc/.docx/.gsfx/.esw + OCR скана (2063 симв).
APP_VERSION→2026-07-15e.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-07-15 20:58:05 +10:00
co-authored by Claude Opus 4.8
parent 151a00656c
commit 3e9d832e19
4 changed files with 196 additions and 8 deletions
+126 -7
View File
@@ -199,6 +199,93 @@ def is_allowed_file(filename: str) -> bool:
return Path(filename).suffix.lower() in ALLOWED_EXTENSIONS
# Проприетарные бинарные форматы сметных программ — питон-распаковщика нет,
# реверс не окупается: честный отказ вместо тихого пропуска/выдумки.
_UNSUPPORTED_SMETA = {".esw", ".oew", ".cew", ".bma", ".gsp"}
def _read_xls_via_xlrd(path: Path, max_chars: int) -> str | None:
"""Легаси .xls (BIFF) — openpyxl не умеет, нужен xlrd>=2. None если xlrd нет."""
try:
import xlrd
except ImportError:
return None
try:
book = xlrd.open_workbook(str(path))
except Exception:
return None
out: list[str] = []
used = 0
for sh in book.sheets():
if used >= max_chars:
break
out.append(f"\n### Файл: {path.name}, Лист: {sh.name} "
f"(строк: {sh.nrows}, колонок: {sh.ncols})")
for r in range(sh.nrows):
vals = [str(sh.cell_value(r, c))[:300] for c in range(sh.ncols)
if str(sh.cell_value(r, c)).strip()]
if not vals:
continue
line = f"стр{r + 1}: " + " | ".join(vals)
if used + len(line) > max_chars:
break
out.append(line)
used += len(line)
return "\n".join(out)
def _read_doc_via_catdoc(path: Path) -> str | None:
"""Старый .doc (OLE2) — python-docx не умеет; catdoc → текст. None если нет catdoc."""
import shutil
import subprocess
if not shutil.which("catdoc"):
return None
try:
r = subprocess.run(["catdoc", "-w", str(path)],
capture_output=True, timeout=60)
text = r.stdout.decode("utf-8", "replace").strip()
return text or None
except Exception:
return None
def _read_docx(path: Path, max_chars: int) -> str:
""".docx: параграфы + ТАБЛИЦЫ (сметные docx — почти целиком таблицы, их и упускал GLM)."""
import docx
d = docx.Document(str(path))
chunks = [p.text for p in d.paragraphs if p.text.strip()]
for tbl in d.tables:
for row in tbl.rows:
cells = [c.text.strip() for c in row.cells]
if any(cells):
chunks.append(" | ".join(cells))
return "\n".join(chunks)[:max_chars]
def _ocr_pdf_scan(path: Path, max_pages: int = 5) -> str | None:
"""PDF-скан без текстового слоя → OCR (tesseract rus). None если стек OCR не стоит."""
import shutil
if not shutil.which("tesseract"):
return None
try:
import io
import fitz
import pytesseract
from PIL import Image
except ImportError:
return None
try:
doc = fitz.open(str(path))
out = []
for page in doc[:max_pages]:
pix = page.get_pixmap(dpi=200)
img = Image.open(io.BytesIO(pix.tobytes("png")))
out.append(pytesseract.image_to_string(img, lang="rus"))
return "\n".join(out).strip() or None
except Exception:
return None
def _read_work_dir_files(work_dir: Path, max_chars: int = 150000) -> str:
"""Read files from work directory and return text summary for LLM context."""
parts = []
@@ -208,7 +295,7 @@ def _read_work_dir_files(work_dir: Path, max_chars: int = 150000) -> str:
continue
ext = f.suffix.lower()
try:
if ext in (".xlsx", ".xlsm", ".xls"):
if ext in (".xlsx", ".xlsm"):
import openpyxl
wb = openpyxl.load_workbook(str(f), data_only=True)
n_sheets = max(1, len(wb.worksheets))
@@ -267,6 +354,28 @@ def _read_work_dir_files(work_dir: Path, max_chars: int = 150000) -> str:
chunk += f"\n[... лист обрезан на per-sheet лимите, доступно ещё {real_total - len(rows_lines)} строк]"
parts.append(chunk)
total += len(chunk)
elif ext == ".xls":
xls_text = _read_xls_via_xlrd(f, max_chars - total)
if xls_text:
parts.append(xls_text)
total += len(xls_text)
else:
parts.append(f"\n### Файл: {f.name} (старый формат .xls — не удалось прочитать)")
elif ext == ".gsfx":
from gge_tools import parse_gsfx_file
g = parse_gsfx_file(f)
if "error" in g:
parts.append(f"\n### Файл: {f.name} (.gsfx, ошибка: {g['error']})")
else:
poss = "\n".join(f" {p['code']} | {p['name'][:80]} | {p['quantity']} {p['unit']}"
for p in g["positions"][:40])
chunk = (f"\n### Смета .gsfx: {f.name}\nШифр: {g['code']} | {g['name']}\n"
f"Регион: {g['region']} | Итог: {g['total']} руб | позиций: {g['positions_count']}\n{poss}")
parts.append(chunk)
total += len(chunk)
elif ext in _UNSUPPORTED_SMETA:
parts.append(f"\n### Файл: {f.name} (формат {ext} проприетарный, "
f"автоматически не читается — экспортируйте смету в АРПС (.arp) или Excel)")
elif ext in (".csv", ".txt", ".xml", ".json", ".yaml", ".yml"):
text = f.read_text(encoding="utf-8", errors="ignore")[:max_chars]
parts.append(f"\n### Файл: {f.name}\n{text}")
@@ -278,19 +387,29 @@ def _read_work_dir_files(work_dir: Path, max_chars: int = 150000) -> str:
text = ""
for page in doc[:5]: # first 5 pages
text += page.get_text()
# Скан без текстового слоя → OCR (tesseract rus), если стек стоит.
if len(text.strip()) < 40:
ocr = _ocr_pdf_scan(f)
if ocr:
text = ocr
parts.append(f"\n### Файл: {f.name} ({doc.page_count} стр.)\n{text[:max_chars]}")
total += min(len(text), max_chars)
except ImportError:
parts.append(f"\n### Файл: {f.name} (PDF, не удалось прочитать)")
elif ext in (".docx", ".doc"):
elif ext == ".docx":
try:
import docx
doc = docx.Document(str(f))
text = "\n".join(p.text for p in doc.paragraphs)[:max_chars]
text = _read_docx(f, max_chars)
parts.append(f"\n### Файл: {f.name}\n{text}")
total += len(text)
except ImportError:
parts.append(f"\n### Файл: {f.name} (Word, не удалось прочитать)")
except Exception as e:
parts.append(f"\n### Файл: {f.name} (.docx, не удалось прочитать: {e})")
elif ext == ".doc":
text = _read_doc_via_catdoc(f)
if text:
parts.append(f"\n### Файл: {f.name}\n{text[:max_chars]}")
total += min(len(text), max_chars)
else:
parts.append(f"\n### Файл: {f.name} (старый формат .doc — не удалось извлечь текст)")
elif ext == ".zip":
# Listing only — содержимое не извлекаем. Этого достаточно,
# чтобы модель не выдумывала, что внутри.
+1 -1
View File
@@ -138,7 +138,7 @@ MAX_MESSAGE_LEN = 10_000
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
APP_VERSION = "2026-07-15d"
APP_VERSION = "2026-07-15e"
# Audit: path → action name mapping
_AUDIT_MAP = [
+4
View File
@@ -14,3 +14,7 @@ pymorphy2==0.9.1
python-docx==1.2.0
PyMuPDF==1.27.2.2
faiss-cpu==1.13.2
xlrd==2.0.2 # легаси .xls (BIFF) — openpyxl не умеет
pytesseract==0.3.13 # OCR PDF-сканов (нужен apt: tesseract-ocr tesseract-ocr-rus)
Pillow>=10 # рендер страниц PDF для OCR
# apt-зависимости (не pip): catdoc (чтение старых .doc), tesseract-ocr + tesseract-ocr-rus (OCR)
+65
View File
@@ -0,0 +1,65 @@
"""Real-тест чтения форматов в GLM-пути (_read_work_dir_files) на НАСТОЯЩИХ файлах
из загруженных архивов (гонять на dev2, где стоят xlrd/catdoc/tesseract/docx).
Вытаскивает по одному образцу .xls/.doc/.docx/.gsfx/.esw и проверяет вывод."""
import shutil
import sys
import tempfile
import zipfile
from pathlib import Path
from claude_bridge_glm import _read_work_dir_files
BASE = Path("/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100")
# (архив, расширение, имя-образца)
SAMPLES = [
("40_Калинина.zip", ".xls", "sample.xls"),
("!_ТЗ ДЛЯ.zip", ".doc", "sample.doc"),
("!_ТЗ ДЛЯ.zip", ".docx", "sample.docx"),
("АРХИВ ОБЩИЙ_Гранд-смета.zip", ".gsfx", "sample.gsfx"),
("очистные тумнин.zip", ".esw", "sample.esw"),
]
tmp = Path(tempfile.mkdtemp())
got = {}
for arch, ext, outname in SAMPLES:
ap = BASE / arch
if not ap.exists():
print(f" ПРОПУСК {arch} (нет)")
continue
with zipfile.ZipFile(ap) as z:
entry = next((n for n in z.namelist()
if n.lower().endswith(ext) and not n.endswith("/")), None)
if not entry:
print(f" в {arch} нет {ext}")
continue
(tmp / outname).write_bytes(z.read(entry))
got[ext] = outname
out = _read_work_dir_files(tmp)
print("=== вывод _read_work_dir_files (обрезано) ===")
for line in out.splitlines():
if line.startswith("###") or "проприетарный" in line or "не удалось" in line:
print(" " + line[:110])
fails = 0
def chk(name, cond, hint=""):
global fails
print((" ok: " if cond else " FAIL: ") + name + ("" if cond else f" — {hint}"))
if not cond:
fails += 1
if ".xls" in got:
chk(".xls читается (xlrd)", "Лист:" in out and "не удалось" not in out.split("sample.xls")[1][:200], "нет данных листа")
if ".doc" in got:
seg = out.split("sample.doc")[1][:400] if "sample.doc" in out else ""
chk(".doc читается (catdoc)", "не удалось" not in seg and len(seg.strip()) > 20, "пустой/ошибка")
if ".docx" in got:
chk(".docx читается", "sample.docx" in out, "нет вывода")
if ".gsfx" in got:
chk(".gsfx парсится (Смета)", "Смета .gsfx" in out and "Шифр:" in out, "не распознан")
if ".esw" in got:
chk(".esw честный отказ", "проприетарный" in out, "нет отказа")
shutil.rmtree(tmp, ignore_errors=True)
print("ALL PASS" if not fails else f"{fails} FAILED")
sys.exit(fails)