workpermit / eval /extract.py
synaptex-community's picture
Категория 13 «Рабочий день»: 16 сквозных рабочих сценариев (136 задач); чтение и аудит PDF под паролем
f08abd2 verified
Raw History Blame Contribute Delete
9.77 kB
"""Текст файлов задач и ответов систем для проверок, судьи и аудита.
Выданные файлы любой системы читаются одним и тем же кодом: docx, xlsx, pptx, pdf, txt и md распространёнными
библиотеками Python. Оценка не зависит от того, чем система читает и пишет документы, и перепроверить её можно, не
запуская ни одну из сравниваемых систем. Таблицы Word идут строками с разделителем, ячейки книги Excel с адресом, формулы
вместе со значением (``B4: 576000 [=SUM(B2:B3)]``): так их видит судья; проверки кода сверяют значения без адресов и формул
(``checks.values_only``).
Значение формулы берётся таким, каким его увидит человек, открыв книгу. Библиотеки (openpyxl и другие) пишут формулы
без посчитанных значений, а Excel и LibreOffice считают их при открытии; поэтому книга, где у формул нет значений,
перед чтением пересчитывается LibreOffice (``soffice`` из PATH или переменной SOFFICE). Без LibreOffice такая формула
помечается «не посчитано»; оценка в контейнере ``eval/Dockerfile`` идёт с LibreOffice.
python extract.py <файл или папка> [<папка вывода>]
"""
from __future__ import annotations
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
def _tag(node) -> str:
"""Имя элемента без пространства имён; у комментария XML имени нет."""
return node.tag.rsplit("}", 1)[-1] if isinstance(node.tag, str) else ""
def _paragraph_text(paragraph) -> str:
"""Текст абзаца Word. Табуляция и разрыв строки внутри абзаца — пробел: без него «1 000», разрыв, «2 000» читались
одним числом «1 0002 000»."""
parts = []
for node in paragraph.iter():
tag = _tag(node)
if tag == "t":
parts.append(node.text or "")
elif tag in ("tab", "br", "cr"):
parts.append(" ")
return "".join(parts)
def _docx(path: Path) -> str:
import docx # python-docx
document = docx.Document(str(path))
lines: list[str] = []
# Элемент управления содержимым (sdt) и пользовательская разметка держат абзацы и таблицы внутри себя: без обхода
# их текст пропадал.
def walk(element) -> None:
for child in element.iterchildren():
tag = _tag(child)
if tag == "p":
text = _paragraph_text(child)
if text.strip():
lines.append(text)
elif tag == "tbl":
for row in child.iter():
if _tag(row) == "tr":
cells = []
for cell in row.iterchildren():
if _tag(cell) == "tc":
cells.append(" ".join(_paragraph_text(p) for p in cell.iter() if _tag(p) == "p").strip())
lines.append(" | ".join(cells))
elif tag in ("sdt", "sdtContent", "customXml"):
walk(child)
walk(document.element.body)
return "\n".join(lines)
def _soffice() -> str | None:
return os.environ.get("SOFFICE") or shutil.which("soffice") or shutil.which("libreoffice")
def _recalculated(path: Path) -> Path | None:
"""Копия книги, пересчитанная LibreOffice; None, если LibreOffice нет или пересчёт не удался."""
soffice = _soffice()
if soffice is None:
return None
folder = Path(tempfile.mkdtemp(prefix="bench-recalc-"))
profile = (folder / "profile").resolve().as_uri()
try:
subprocess.run([soffice, f"-env:UserInstallation={profile}", "--headless", "--norestore", "--convert-to",
"xlsx:Calc MS Excel 2007 XML", "--outdir", str(folder / "book"), str(path)],
capture_output=True, timeout=300, check=False)
except (OSError, subprocess.TimeoutExpired):
return None
result = folder / "book" / (path.stem + ".xlsx")
return result if result.exists() else None
def _xlsx(path: Path) -> str:
import openpyxl
formulas = openpyxl.load_workbook(str(path), data_only=False)
values = openpyxl.load_workbook(str(path), data_only=True)
def is_formula(cell) -> bool:
return isinstance(cell.value, str) and cell.value.startswith("=")
# Формулы без значений (книга записана библиотекой): значения из пересчёта, как их увидит человек в Excel.
unvalued = any(is_formula(cell) and values[sheet.title][cell.coordinate].value is None
for sheet in formulas.worksheets for row in sheet.iter_rows() for cell in row)
recalculated = _recalculated(path) if unvalued else None
if recalculated is not None:
values = openpyxl.load_workbook(str(recalculated), data_only=True)
lines: list[str] = []
for sheet in formulas.worksheets:
lines.append(f"## Лист «{sheet.title}»")
cached = values[sheet.title] if sheet.title in values.sheetnames else None
for row in sheet.iter_rows():
cells = []
for cell in row:
if cell.value is None:
continue
if is_formula(cell):
value = cached[cell.coordinate].value if cached is not None else None
shown = "не посчитано" if value is None and unvalued and recalculated is None else value
cells.append(f"{cell.coordinate}: {shown} [{cell.value}]")
else:
cells.append(f"{cell.coordinate}: {cell.value}")
if cells:
lines.append("; ".join(cells))
return "\n".join(lines)
def _pptx(path: Path) -> str:
from pptx import Presentation
deck = Presentation(str(path))
lines: list[str] = []
for number, slide in enumerate(deck.slides, 1):
lines.append(f"## Слайд {number}")
for shape in slide.shapes:
if shape.has_text_frame and shape.text_frame.text.strip():
lines.append(shape.text_frame.text)
if getattr(shape, "has_table", False) and shape.has_table:
for row in shape.table.rows:
lines.append(" | ".join(cell.text for cell in row.cells))
if slide.has_notes_slide and slide.notes_slide.notes_text_frame.text.strip():
lines.append("Заметки: " + slide.notes_slide.notes_text_frame.text)
return "\n".join(lines)
def _pdf(path: Path) -> str:
from pypdf import PdfReader
reader = PdfReader(str(path))
# Файл под паролем без пароля не читается: текст его — пометка об этом, а не сбой всего чтения (задача 13.12 даёт такой акт).
if reader.is_encrypted:
try:
if not reader.decrypt(""):
return "[PDF под паролем: без пароля текст не читается]"
except Exception:
return "[PDF под паролем: без пароля текст не читается]"
pages = []
for number, page in enumerate(reader.pages, 1):
pages.append(f"## Страница {number}\n{page.extract_text() or ''}")
return "\n".join(pages)
READERS = {".docx": _docx, ".xlsx": _xlsx, ".pptx": _pptx, ".pdf": _pdf}
def extract(path: str | Path) -> str:
"""Текст файла; для изображений и неизвестных форматов — пометка о виде файла."""
path = Path(path)
suffix = path.suffix.lower()
if suffix in READERS:
return READERS[suffix](path)
if suffix in {".txt", ".md", ".csv", ".json", ".py", ".cs", ".yml", ".yaml", ".log"}:
return path.read_text(encoding="utf-8", errors="replace")
return f"[файл {path.name}: {suffix or 'без расширения'}, текста нет]"
def main(argv: list[str]) -> int:
if len(argv) < 2:
print(__doc__)
return 2
source = Path(argv[1])
target = Path(argv[2]) if len(argv) > 2 else None
files = [source] if source.is_file() else sorted(p for p in source.rglob("*") if p.is_file())
for file in files:
if file.name == "manifest.json" or file.suffix == ".jsonl":
continue
text = extract(file)
if target is None:
print(f"===== {file}\n{text}\n")
else:
out = target / file.relative_to(source if source.is_dir() else source.parent)
out = out.with_name(out.name + ".txt")
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(text, encoding="utf-8")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))