File size: 9,772 Bytes
082acf6 434adef 67df8f6 082acf6 67df8f6 082acf6 67df8f6 082acf6 f08abd2 082acf6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | """Текст файлов задач и ответов систем для проверок, судьи и аудита.
Выданные файлы любой системы читаются одним и тем же кодом: 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))
|