File size: 9,235 Bytes
fdfe81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
"""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,
    )