Xander Labide
Claude Opus 4.7 (1M context)
Initial commit β€” Farient DeckCheck
fdfe81a
Raw History Blame Contribute Delete
9.24 kB
"""PPTX parser: ``parse_deck(path: Path) -> ParsedDeck``.
Design constraints
------------------
* Pure function β€” does NOT modify the source file in any way.
* Notes guard: ``if slide.has_notes_slide:`` is checked BEFORE ever touching
``slide.notes_slide`` to avoid the python-pptx lazy-creation side effect.
* Group flattening: GROUP shapes are recursed; child coordinates are
transformed to the slide reference frame (group_left + child_left, etc.)
so downstream consumers get slide-relative EMU without re-walking the tree.
* Color extraction: tries ``run.font.color.rgb``, falls back to
``run.font.color.theme_color``, records both; wraps all color access in
try/except because the color type may be None/_NoneColor.
* Table-as-image hint: a PICTURE shape whose height β‰₯ 609600 EMU (β‰₯ ~0.67 in)
and width/height ratio β‰₯ 1.5 is flagged as a possible pasted table image.
* Slide numbering is 1-indexed.
"""
from __future__ import annotations
from pathlib import Path
from typing import Optional
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE
from pptx.util import Emu
from schemas.parsed import ParsedDeck, ParsedSlide, RunInfo, ShapeInfo, TableInfo
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
# Minimum height (EMU) for a picture to be considered a possible table-image.
# 609600 EMU β‰ˆ 0.67 inches β€” a single-row table cell is rarely taller.
_TABLE_IMAGE_MIN_HEIGHT_EMU = 609600
# Minimum width-to-height aspect ratio for the table-as-image heuristic.
_TABLE_IMAGE_MIN_ASPECT = 1.5
# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------
def _color_info(run) -> tuple[Optional[str], Optional[str]]:
"""Return (rgb_hex, theme_color_name) for a run's font color.
Either value may be None. All exceptions are caught so a bad color object
never aborts parsing.
"""
rgb: Optional[str] = None
theme: Optional[str] = None
try:
color_type = run.font.color.type
if color_type is None:
return None, None
# Try RGB
try:
rgb_val = run.font.color.rgb
rgb = str(rgb_val) # e.g. "FF0000"
except Exception:
pass
# Try theme color
try:
tc = run.font.color.theme_color
# theme_color returns an MSO_THEME_COLOR enum; convert to name string.
theme = str(tc.name) if hasattr(tc, "name") else str(tc)
except Exception:
pass
except Exception:
pass
return rgb, theme
def _run_info(run) -> RunInfo:
"""Extract RunInfo from a python-pptx Run object."""
rgb, theme = _color_info(run)
font = run.font
return RunInfo(
text=run.text,
font_name=font.name,
font_size_pt=float(font.size.pt) if font.size else None,
bold=font.bold,
italic=font.italic,
color_rgb=rgb,
color_theme=theme,
)
def _table_cells(shape) -> list[TableInfo]:
"""Extract all table cells from a TABLE shape."""
cells: list[TableInfo] = []
table = shape.table
for r_idx, row in enumerate(table.rows):
for c_idx, cell in enumerate(row.cells):
tf = cell.text_frame
runs: list[RunInfo] = []
for para in tf.paragraphs:
for run in para.runs:
runs.append(_run_info(run))
cells.append(
TableInfo(
row=r_idx,
col=c_idx,
text=tf.text,
runs=runs,
)
)
return cells
def _is_table_as_image_hint(shape) -> bool:
"""Return True if a PICTURE shape looks like a pasted table image."""
if shape.shape_type != MSO_SHAPE_TYPE.PICTURE:
return False
h = shape.height
w = shape.width
if h <= 0:
return False
return h >= _TABLE_IMAGE_MIN_HEIGHT_EMU and (w / h) >= _TABLE_IMAGE_MIN_ASPECT
def _shape_type_name(shape) -> str:
"""Return the string name of a shape's MSO_SHAPE_TYPE."""
try:
return shape.shape_type.name
except Exception:
return str(shape.shape_type)
def _collect_runs(shape) -> list[RunInfo]:
"""Return all runs from a shape's text frame (if it has one)."""
if not shape.has_text_frame:
return []
runs: list[RunInfo] = []
for para in shape.text_frame.paragraphs:
for run in para.runs:
runs.append(_run_info(run))
return runs
def _shape_text(shape) -> str:
"""Return concatenated text from a shape's text frame."""
if shape.has_text_frame:
return shape.text_frame.text
return ""
def _flatten_shapes(
shapes,
slide_number: int,
group_left: int = 0,
group_top: int = 0,
shape_counter: list[int] | None = None,
) -> list[ShapeInfo]:
"""Recursively flatten shapes, transforming child coords to slide frame.
Parameters
----------
shapes:
An iterable of python-pptx shape objects.
slide_number:
1-indexed slide number (used in stable shape_id).
group_left / group_top:
Cumulative offset of the enclosing group in the slide frame (EMU).
Pass 0 for top-level shapes.
shape_counter:
Mutable list with a single int used as a counter so shape IDs are
unique and sequential across recursive calls.
"""
if shape_counter is None:
shape_counter = [0]
result: list[ShapeInfo] = []
for shape in shapes:
if shape.shape_type == MSO_SHAPE_TYPE.GROUP:
# Transform group's own position to slide frame, then recurse.
g_left = group_left + (shape.left or 0)
g_top = group_top + (shape.top or 0)
result.extend(
_flatten_shapes(
shape.shapes,
slide_number=slide_number,
group_left=g_left,
group_top=g_top,
shape_counter=shape_counter,
)
)
continue
shape_counter[0] += 1
shape_id = f"s{slide_number}.shape{shape_counter[0]}"
# Compute slide-relative position
left = group_left + (shape.left or 0)
top = group_top + (shape.top or 0)
width = shape.width or 0
height = shape.height or 0
text = _shape_text(shape)
runs = _collect_runs(shape)
table_cells: list[TableInfo] = []
if shape.has_table:
table_cells = _table_cells(shape)
result.append(
ShapeInfo(
shape_id=shape_id,
shape_type=_shape_type_name(shape),
name=shape.name,
left=int(left),
top=int(top),
width=int(width),
height=int(height),
text=text,
runs=runs,
table_cells=table_cells,
is_table_as_image_hint=_is_table_as_image_hint(shape),
)
)
return result
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
def parse_deck(path: Path) -> ParsedDeck:
"""Parse a ``.pptx`` file and return a :class:`~schemas.parsed.ParsedDeck`.
The source file is opened read-only and is **never modified**. In
particular, ``slide.notes_slide`` is only accessed after checking
``slide.has_notes_slide`` to avoid the python-pptx lazy-creation side
effect described at:
https://python-pptx.readthedocs.io/en/latest/user/notes.html
Parameters
----------
path:
Path to the ``.pptx`` file.
Returns
-------
ParsedDeck
Fully populated deck model with all slides, shapes, runs, tables, and
speaker notes.
"""
path = Path(path)
prs = Presentation(path)
slide_width_emu = int(prs.slide_width)
slide_height_emu = int(prs.slide_height)
parsed_slides: list[ParsedSlide] = []
for slide_idx, slide in enumerate(prs.slides):
slide_number = slide_idx + 1 # 1-indexed
# Flatten all shapes (groups recursed, coords slide-relative)
shapes = _flatten_shapes(slide.shapes, slide_number=slide_number)
# Build convenience extracted_text (all shape texts)
extracted_text = "\n".join(s.text for s in shapes if s.text)
# Notes: guard BEFORE accessing .notes_slide
notes_text = ""
if slide.has_notes_slide:
notes_text = slide.notes_slide.notes_text_frame.text
parsed_slides.append(
ParsedSlide(
slide_number=slide_number,
shapes=shapes,
extracted_text=extracted_text,
notes_text=notes_text,
)
)
return ParsedDeck(
slide_count=len(parsed_slides),
slide_width_emu=slide_width_emu,
slide_height_emu=slide_height_emu,
slides=parsed_slides,
)