Add xlsx and pptx support: sheet cells, slide text and tables, speaker notes
This commit is contained in:
1 parent
2bb2dc82a1
commit
4ea34eba8d
7 files changed
+116
-10
No files matched your search
@@ -18,6 +18,8 @@ from concurrent.futures import ThreadPoolExecutor
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
import httpx
|
||||
import openpyxl
|
||||
from pptx import Presentation
|
||||
from docx import Document as DocxDocument
|
||||
from docx.oxml.ns import qn
|
||||
from docx.table import Table
|
||||
@@ -45,6 +47,71 @@ JOBS_LOCK = threading.Lock()
|
||||
|
||||
# --- разбор документа ---
|
||||
|
||||
MIN_CELL_CHARS = 20 # короче — это служебные ячейки, не проверяем
|
||||
|
||||
|
||||
def extract_xlsx(data: bytes) -> List[str]:
|
||||
"""Ячейки с осмысленным текстом (длинные, с пробелом), по листам."""
|
||||
wb = openpyxl.load_workbook(io.BytesIO(data), data_only=True, read_only=True)
|
||||
out: List[str] = []
|
||||
for ws in wb.worksheets:
|
||||
first_in_sheet = True
|
||||
seen_sheet = set()
|
||||
for row in ws.iter_rows():
|
||||
for cell in row:
|
||||
val = cell.value
|
||||
if not isinstance(val, str):
|
||||
continue
|
||||
txt = val.strip()
|
||||
if len(txt) < MIN_CELL_CHARS or " " not in txt or not any(c.isalpha() for c in txt):
|
||||
continue
|
||||
if txt in seen_sheet:
|
||||
continue
|
||||
seen_sheet.add(txt)
|
||||
if first_in_sheet:
|
||||
out.append(f"[лист «{ws.title}»] {txt}")
|
||||
first_in_sheet = False
|
||||
else:
|
||||
out.append(txt)
|
||||
wb.close()
|
||||
return out
|
||||
|
||||
|
||||
def extract_pptx(data: bytes) -> List[str]:
|
||||
"""Текст слайдов, таблиц и заметок докладчика (по слайдам)."""
|
||||
prs = Presentation(io.BytesIO(data))
|
||||
out: List[str] = []
|
||||
|
||||
def push_frame(tf) -> None:
|
||||
for para in tf.paragraphs:
|
||||
txt = para.text.strip()
|
||||
if txt:
|
||||
out.append(txt)
|
||||
|
||||
for s_idx, slide in enumerate(prs.slides, start=1):
|
||||
first_in_slide = True
|
||||
for shape in slide.shapes:
|
||||
marker = f"[слайд {s_idx}] " if first_in_slide else ""
|
||||
if shape.has_text_frame:
|
||||
before = len(out)
|
||||
push_frame(shape.text_frame)
|
||||
if len(out) > before and first_in_slide:
|
||||
out[before] = marker + out[before]
|
||||
first_in_slide = False
|
||||
elif shape.has_table:
|
||||
for row in shape.table.rows:
|
||||
for cell in row.cells:
|
||||
txt = cell.text.strip()
|
||||
if txt:
|
||||
out.append((marker if first_in_slide else "") + txt)
|
||||
first_in_slide = False
|
||||
if slide.has_notes_slide:
|
||||
notes = slide.notes_slide.notes_text_frame.text.strip()
|
||||
if notes:
|
||||
out.append(f"[заметки к слайду {s_idx}] {notes}")
|
||||
return out
|
||||
|
||||
|
||||
def extract_paragraphs(data: bytes, filename: str) -> List[str]:
|
||||
"""Абзацы документа в порядке следования, включая текст таблиц."""
|
||||
name = (filename or "").lower()
|
||||
@@ -61,8 +128,12 @@ def extract_paragraphs(data: bytes, filename: str) -> List[str]:
|
||||
return [ln.rstrip() for ln in text.splitlines() if ln.strip()]
|
||||
if name.endswith(".doc"):
|
||||
raise ValueError("Старый формат .doc: пересохраните документ как .docx и загрузите снова")
|
||||
if name.endswith(".xlsx"):
|
||||
return extract_xlsx(data)
|
||||
if name.endswith(".pptx"):
|
||||
return extract_pptx(data)
|
||||
if not name.endswith(".docx"):
|
||||
raise ValueError("Формат не поддержан: загрузите .docx или .txt")
|
||||
raise ValueError("Формат не поддержан: загрузите .docx, .xlsx, .pptx или .txt")
|
||||
doc = DocxDocument(io.BytesIO(data))
|
||||
out: List[str] = []
|
||||
for child in doc.element.body.iterchildren():
|
||||
|
||||
Reference in new issue
Block a user