extract_pptx.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. #!/usr/bin/env python3
  2. """Extract or search PPTX text content, slide by slide.
  3. Usage:
  4. python extract_pptx.py <path_to_pptx>
  5. python extract_pptx.py <path_to_pptx> --slides 1,3,5
  6. python extract_pptx.py <path_to_pptx> --range 2-4
  7. python extract_pptx.py <path_to_pptx> --search QUERY [--ignore-case]
  8. python extract_pptx.py <path_to_pptx> --search PATTERN --regex [--ignore-case]
  9. python extract_pptx.py <path_to_pptx> --notes
  10. Requires: python-pptx (pip install python-pptx)
  11. Works with Python >= 3.7 (no Python 3.10+ requirement).
  12. """
  13. from __future__ import annotations
  14. import argparse
  15. import re
  16. import sys
  17. from dataclasses import dataclass
  18. from pptx import Presentation
  19. @dataclass
  20. class SlideContent:
  21. slide_number: int
  22. lines: list[str]
  23. notes: str | None = None
  24. def collect_slide_notes(slide) -> str | None:
  25. """Extract speaker notes text from a slide, if present."""
  26. if not slide.has_notes_slide:
  27. return None
  28. notes_text = slide.notes_slide.notes_text_frame.text.strip()
  29. return notes_text if notes_text else None
  30. def collect_slide_lines(slide) -> list[str]:
  31. lines: list[str] = []
  32. for shape in slide.shapes:
  33. if shape.has_text_frame:
  34. for paragraph in shape.text_frame.paragraphs:
  35. text = paragraph.text.strip()
  36. if text:
  37. lines.append(text)
  38. if shape.has_table:
  39. for row in shape.table.rows:
  40. cells = [cell.text.strip() for cell in row.cells if cell.text.strip()]
  41. if cells:
  42. lines.append(" | ".join(cells))
  43. return lines
  44. def load_presentation_content(pptx_path: str) -> list[SlideContent]:
  45. presentation = Presentation(pptx_path)
  46. return [
  47. SlideContent(
  48. slide_number=index,
  49. lines=collect_slide_lines(slide),
  50. notes=collect_slide_notes(slide),
  51. )
  52. for index, slide in enumerate(presentation.slides, 1)
  53. ]
  54. def build_matcher(query: str, use_regex: bool, ignore_case: bool):
  55. if use_regex:
  56. flags = re.IGNORECASE if ignore_case else 0
  57. pattern = re.compile(query, flags)
  58. return pattern.search
  59. normalized_query = query.casefold() if ignore_case else query
  60. def contains(text: str):
  61. haystack = text.casefold() if ignore_case else text
  62. return normalized_query in haystack
  63. return contains
  64. def parse_slide_numbers(raw_value: str) -> set[int]:
  65. slide_numbers: set[int] = set()
  66. for chunk in raw_value.split(","):
  67. value = chunk.strip()
  68. if not value:
  69. continue
  70. if not value.isdigit():
  71. raise ValueError(
  72. f'Invalid slide number "{value}". Use comma-separated positive integers.'
  73. )
  74. slide_number = int(value)
  75. if slide_number < 1:
  76. raise ValueError("Slide numbers must be >= 1.")
  77. slide_numbers.add(slide_number)
  78. if not slide_numbers:
  79. raise ValueError("At least one slide number must be provided.")
  80. return slide_numbers
  81. def parse_slide_range(raw_value: str) -> tuple[int, int]:
  82. match = re.fullmatch(r"\s*(\d+)\s*-\s*(\d+)\s*", raw_value)
  83. if not match:
  84. raise ValueError('Invalid range format. Use "start-end", for example "2-4".')
  85. start = int(match.group(1))
  86. end = int(match.group(2))
  87. if start < 1 or end < 1:
  88. raise ValueError("Slide range values must be >= 1.")
  89. if start > end:
  90. raise ValueError("Slide range start must be <= end.")
  91. return start, end
  92. def select_slides(
  93. slides: list[SlideContent],
  94. selected_numbers: set[int] | None,
  95. selected_range: tuple[int, int] | None,
  96. ) -> list[SlideContent]:
  97. total_slides = len(slides)
  98. if selected_numbers is not None:
  99. invalid = sorted(
  100. slide_number
  101. for slide_number in selected_numbers
  102. if slide_number > total_slides
  103. )
  104. if invalid:
  105. raise ValueError(
  106. f"Requested slide(s) out of range: {', '.join(str(value) for value in invalid)}. "
  107. f"Presentation has {total_slides} slide(s)."
  108. )
  109. return [slide for slide in slides if slide.slide_number in selected_numbers]
  110. if selected_range is not None:
  111. start, end = selected_range
  112. if start > total_slides:
  113. raise ValueError(
  114. f"Requested range {start}-{end} is out of range. Presentation has {total_slides} slide(s)."
  115. )
  116. if end > total_slides:
  117. raise ValueError(
  118. f"Requested range end {end} is out of range. Presentation has {total_slides} slide(s)."
  119. )
  120. return [slide for slide in slides if start <= slide.slide_number <= end]
  121. return slides
  122. def print_slide_content(slides: list[SlideContent], show_notes: bool) -> None:
  123. for slide in slides:
  124. print(f"=== Slide {slide.slide_number} ===")
  125. for line in slide.lines:
  126. print(line)
  127. if show_notes and slide.notes:
  128. print("[Speaker Notes]")
  129. print(slide.notes)
  130. print()
  131. def print_search_results(
  132. slides: list[SlideContent],
  133. query: str,
  134. use_regex: bool,
  135. ignore_case: bool,
  136. show_notes: bool,
  137. ) -> None:
  138. matcher = build_matcher(query, use_regex, ignore_case)
  139. matched_slides = 0
  140. matched_lines = 0
  141. for slide in slides:
  142. matches = [line for line in slide.lines if matcher(line)]
  143. notes_match = show_notes and slide.notes and matcher(slide.notes)
  144. if not matches and not notes_match:
  145. continue
  146. matched_slides += 1
  147. matched_lines += len(matches)
  148. if notes_match:
  149. matched_lines += 1
  150. print(f"=== Slide {slide.slide_number} ===")
  151. for line in matches:
  152. print(line)
  153. if notes_match:
  154. print("[Speaker Notes]")
  155. print(slide.notes)
  156. print()
  157. if matched_lines == 0:
  158. print(f'No matches found for "{query}".')
  159. return
  160. print(
  161. f'Found {matched_lines} matching line(s) across {matched_slides} slide(s).'
  162. )
  163. def parse_args() -> argparse.Namespace:
  164. parser = argparse.ArgumentParser(
  165. description="Extract all PPTX text or search matching content."
  166. )
  167. parser.add_argument("pptx_path", help="Path to the PPTX file to inspect.")
  168. selection_group = parser.add_mutually_exclusive_group()
  169. selection_group.add_argument(
  170. "--slides",
  171. help='Only inspect these slide numbers, for example "1,3,5".',
  172. )
  173. selection_group.add_argument(
  174. "--range",
  175. dest="slide_range",
  176. help='Only inspect a continuous slide range, for example "2-4".',
  177. )
  178. parser.add_argument(
  179. "--search",
  180. help="Only print lines that match this query instead of the full deck.",
  181. )
  182. parser.add_argument(
  183. "--regex",
  184. action="store_true",
  185. help="Treat --search as a regular expression.",
  186. )
  187. parser.add_argument(
  188. "--ignore-case",
  189. action="store_true",
  190. help="Make search case-insensitive.",
  191. )
  192. parser.add_argument(
  193. "--notes",
  194. action="store_true",
  195. help="Include speaker notes in the output.",
  196. )
  197. return parser.parse_args()
  198. def main() -> int:
  199. args = parse_args()
  200. if args.regex and not args.search:
  201. print("--regex requires --search.", file=sys.stderr)
  202. return 1
  203. try:
  204. slides = load_presentation_content(args.pptx_path)
  205. selected_numbers = parse_slide_numbers(args.slides) if args.slides else None
  206. selected_range = (
  207. parse_slide_range(args.slide_range) if args.slide_range else None
  208. )
  209. slides = select_slides(slides, selected_numbers, selected_range)
  210. if args.search:
  211. print_search_results(
  212. slides,
  213. query=args.search,
  214. use_regex=args.regex,
  215. ignore_case=args.ignore_case,
  216. show_notes=args.notes,
  217. )
  218. else:
  219. print_slide_content(slides, show_notes=args.notes)
  220. except ValueError as error:
  221. print(str(error), file=sys.stderr)
  222. return 1
  223. except re.error as error:
  224. print(f"Invalid regular expression: {error}", file=sys.stderr)
  225. return 1
  226. except Exception as error:
  227. print(f"Failed to inspect PPTX: {error}", file=sys.stderr)
  228. return 1
  229. return 0
  230. if __name__ == "__main__":
  231. raise SystemExit(main())