extract_comments.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. #!/usr/bin/env python3
  2. """Extract review comments (annotations) from PPTX files.
  3. Parses the Open XML package directly using zipfile + ElementTree.
  4. Phase 1: classic comments support.
  5. Usage:
  6. python extract_comments.py <path_to_pptx>
  7. python extract_comments.py <path_to_pptx> --slides 1,3,5
  8. python extract_comments.py <path_to_pptx> --range 2-4
  9. python extract_comments.py <path_to_pptx> --search "keyword" [--ignore-case]
  10. python extract_comments.py <path_to_pptx> --format json
  11. Works with Python >= 3.7, zero external dependencies.
  12. """
  13. from __future__ import annotations
  14. import argparse
  15. import json
  16. import posixpath
  17. import re
  18. import sys
  19. import zipfile
  20. import xml.etree.ElementTree as ET
  21. from dataclasses import dataclass, asdict
  22. # ---------------------------------------------------------------------------
  23. # Data model
  24. # ---------------------------------------------------------------------------
  25. @dataclass
  26. class CommentRecord:
  27. slide_number: int
  28. kind: str # "classic"
  29. author_id: str | None
  30. author_name: str | None
  31. author_initials: str | None
  32. created_at: str | None
  33. comment_id: str | None
  34. parent_id: str | None
  35. text: str
  36. part_name: str
  37. # ---------------------------------------------------------------------------
  38. # XML helpers
  39. # ---------------------------------------------------------------------------
  40. def local_name(tag: str) -> str:
  41. """Strip namespace URI, returning only the local element name."""
  42. if tag.startswith("{"):
  43. return tag.split("}", 1)[1]
  44. return tag
  45. def find_children_by_local_name(elem: ET.Element, name: str) -> list[ET.Element]:
  46. return [child for child in elem if local_name(child.tag) == name]
  47. def first_child_text(elem: ET.Element, name: str) -> str | None:
  48. for child in elem:
  49. if local_name(child.tag) == name:
  50. return (child.text or "").strip() or None
  51. return None
  52. def collect_all_text(elem: ET.Element) -> str:
  53. """Recursively collect all text content under an element."""
  54. parts: list[str] = []
  55. if elem.text:
  56. parts.append(elem.text)
  57. for child in elem:
  58. parts.append(collect_all_text(child))
  59. if child.tail:
  60. parts.append(child.tail)
  61. return "".join(parts)
  62. # ---------------------------------------------------------------------------
  63. # Package reader
  64. # ---------------------------------------------------------------------------
  65. def read_xml(zf: zipfile.ZipFile, entry: str) -> ET.Element | None:
  66. """Read and parse an XML entry from the ZIP, returning None on failure."""
  67. try:
  68. with zf.open(entry) as f:
  69. return ET.parse(f).getroot()
  70. except (KeyError, ET.ParseError) as exc:
  71. print(f"Warning: could not parse {entry}: {exc}", file=sys.stderr)
  72. return None
  73. # ---------------------------------------------------------------------------
  74. # Author lookup
  75. # ---------------------------------------------------------------------------
  76. def build_classic_author_map(
  77. zf: zipfile.ZipFile,
  78. ) -> dict[str, tuple[str | None, str | None]]:
  79. """Return {authorId_str: (name, initials)} from ppt/commentAuthors.xml."""
  80. author_map: dict[str, tuple[str | None, str | None]] = {}
  81. root = read_xml(zf, "ppt/commentAuthors.xml")
  82. if root is None:
  83. return author_map
  84. for child in root:
  85. if local_name(child.tag) == "cmAuthor":
  86. aid = child.get("id")
  87. if aid is not None:
  88. author_map[aid] = (child.get("name"), child.get("initials"))
  89. return author_map
  90. # ---------------------------------------------------------------------------
  91. # Relationship resolver
  92. # ---------------------------------------------------------------------------
  93. # Relationship types that point to classic comment parts
  94. _CLASSIC_COMMENT_REL_TYPES = {
  95. "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
  96. "http://schemas.microsoft.com/office/2011/relationships/comments",
  97. }
  98. def resolve_comment_parts(
  99. zf: zipfile.ZipFile, slide_entry: str
  100. ) -> list[tuple[str, str]]:
  101. """Return [(resolved_part_path, rel_type)] for comment-related rels of a slide."""
  102. rels_entry = (
  103. posixpath.dirname(slide_entry)
  104. + "/_rels/"
  105. + posixpath.basename(slide_entry)
  106. + ".rels"
  107. )
  108. root = read_xml(zf, rels_entry)
  109. if root is None:
  110. return []
  111. results: list[tuple[str, str]] = []
  112. for rel in root:
  113. if local_name(rel.tag) != "Relationship":
  114. continue
  115. rel_type = rel.get("Type", "")
  116. target = rel.get("Target", "")
  117. if not target:
  118. continue
  119. is_comment_rel = any(rt in rel_type for rt in _CLASSIC_COMMENT_REL_TYPES)
  120. if not is_comment_rel:
  121. continue
  122. # resolve relative target against slide directory
  123. if not target.startswith("/"):
  124. resolved = posixpath.normpath(
  125. posixpath.join(posixpath.dirname(slide_entry), target)
  126. )
  127. else:
  128. resolved = target.lstrip("/")
  129. results.append((resolved, rel_type))
  130. return results
  131. # ---------------------------------------------------------------------------
  132. # Classic comment parser
  133. # ---------------------------------------------------------------------------
  134. def parse_classic_comments(
  135. zf: zipfile.ZipFile,
  136. part_name: str,
  137. slide_number: int,
  138. author_map: dict[str, tuple[str | None, str | None]],
  139. ) -> list[CommentRecord]:
  140. root = read_xml(zf, part_name)
  141. if root is None:
  142. return []
  143. records: list[CommentRecord] = []
  144. for child in root:
  145. if local_name(child.tag) != "cm":
  146. continue
  147. author_id = child.get("authorId")
  148. author_name: str | None = None
  149. author_initials: str | None = None
  150. if author_id is not None and author_id in author_map:
  151. author_name, author_initials = author_map[author_id]
  152. # comment text lives in a <p:text> child (or similar local name "text")
  153. text = first_child_text(child, "text")
  154. if text is None:
  155. # fallback: try collecting all text recursively
  156. text = collect_all_text(child).strip()
  157. records.append(
  158. CommentRecord(
  159. slide_number=slide_number,
  160. kind="classic",
  161. author_id=author_id,
  162. author_name=author_name,
  163. author_initials=author_initials,
  164. created_at=child.get("dt"),
  165. comment_id=child.get("idx"),
  166. parent_id=None,
  167. text=text,
  168. part_name=part_name,
  169. )
  170. )
  171. return records
  172. # ---------------------------------------------------------------------------
  173. # Slide enumeration
  174. # ---------------------------------------------------------------------------
  175. _SLIDE_ENTRY_RE = re.compile(r"^ppt/slides/slide(\d+)\.xml$")
  176. def enumerate_slides(zf: zipfile.ZipFile) -> list[tuple[int, str]]:
  177. """Return sorted [(slide_number, entry_path)] for all slides in the package."""
  178. slides: list[tuple[int, str]] = []
  179. for entry in zf.namelist():
  180. m = _SLIDE_ENTRY_RE.match(entry)
  181. if m:
  182. slides.append((int(m.group(1)), entry))
  183. slides.sort(key=lambda x: x[0])
  184. return slides
  185. # ---------------------------------------------------------------------------
  186. # Main extraction
  187. # ---------------------------------------------------------------------------
  188. def extract_comments(pptx_path: str) -> list[CommentRecord]:
  189. """Extract all classic comments from a PPTX file."""
  190. with zipfile.ZipFile(pptx_path, "r") as zf:
  191. author_map = build_classic_author_map(zf)
  192. slides = enumerate_slides(zf)
  193. all_records: list[CommentRecord] = []
  194. for slide_number, slide_entry in slides:
  195. comment_parts = resolve_comment_parts(zf, slide_entry)
  196. for part_path, _rel_type in comment_parts:
  197. records = parse_classic_comments(
  198. zf, part_path, slide_number, author_map
  199. )
  200. all_records.extend(records)
  201. return all_records
  202. # ---------------------------------------------------------------------------
  203. # Slide filtering
  204. # ---------------------------------------------------------------------------
  205. def parse_slide_numbers(raw: str) -> set[int]:
  206. nums: set[int] = set()
  207. for chunk in raw.split(","):
  208. v = chunk.strip()
  209. if not v:
  210. continue
  211. if not v.isdigit():
  212. raise ValueError(
  213. f'Invalid slide number "{v}". Use comma-separated positive integers.'
  214. )
  215. n = int(v)
  216. if n < 1:
  217. raise ValueError("Slide numbers must be >= 1.")
  218. nums.add(n)
  219. if not nums:
  220. raise ValueError("At least one slide number must be provided.")
  221. return nums
  222. def parse_slide_range(raw: str) -> tuple[int, int]:
  223. m = re.fullmatch(r"\s*(\d+)\s*-\s*(\d+)\s*", raw)
  224. if not m:
  225. raise ValueError('Invalid range format. Use "start-end", for example "2-4".')
  226. start, end = int(m.group(1)), int(m.group(2))
  227. if start < 1 or end < 1:
  228. raise ValueError("Slide range values must be >= 1.")
  229. if start > end:
  230. raise ValueError("Slide range start must be <= end.")
  231. return start, end
  232. def filter_records(
  233. records: list[CommentRecord],
  234. selected_numbers: set[int] | None,
  235. selected_range: tuple[int, int] | None,
  236. search: str | None,
  237. ignore_case: bool,
  238. ) -> list[CommentRecord]:
  239. filtered = records
  240. if selected_numbers is not None:
  241. filtered = [r for r in filtered if r.slide_number in selected_numbers]
  242. elif selected_range is not None:
  243. start, end = selected_range
  244. filtered = [r for r in filtered if start <= r.slide_number <= end]
  245. if search is not None:
  246. if ignore_case:
  247. q = search.casefold()
  248. filtered = [r for r in filtered if q in r.text.casefold()]
  249. else:
  250. filtered = [r for r in filtered if search in r.text]
  251. return filtered
  252. # ---------------------------------------------------------------------------
  253. # Formatters
  254. # ---------------------------------------------------------------------------
  255. def group_by_slide(
  256. records: list[CommentRecord], include_empty: bool, total_slides: int
  257. ) -> list[tuple[int, list[CommentRecord]]]:
  258. """Group records by slide number; optionally include empty slides."""
  259. from collections import OrderedDict
  260. grouped: dict[int, list[CommentRecord]] = OrderedDict()
  261. if include_empty:
  262. for n in range(1, total_slides + 1):
  263. grouped[n] = []
  264. for r in records:
  265. grouped.setdefault(r.slide_number, []).append(r)
  266. return list(grouped.items())
  267. def format_text(
  268. records: list[CommentRecord], include_empty: bool, total_slides: int
  269. ) -> str:
  270. groups = group_by_slide(records, include_empty, total_slides)
  271. if not groups:
  272. return "No comments found."
  273. lines: list[str] = []
  274. for slide_num, comments in groups:
  275. lines.append(f"=== Slide {slide_num} ===")
  276. if not comments:
  277. lines.append("(no comments)")
  278. lines.append("")
  279. continue
  280. for c in comments:
  281. author = c.author_name or c.author_id or "Unknown"
  282. time_str = c.created_at or "unknown time"
  283. idx_str = f"idx={c.comment_id}" if c.comment_id else ""
  284. meta_parts = [author, time_str, c.kind]
  285. if idx_str:
  286. meta_parts.append(idx_str)
  287. meta = " | ".join(meta_parts)
  288. lines.append(f"- [{meta}]")
  289. lines.append(f" {c.text}")
  290. lines.append("")
  291. return "\n".join(lines)
  292. def format_json(
  293. records: list[CommentRecord], include_empty: bool, total_slides: int
  294. ) -> str:
  295. groups = group_by_slide(records, include_empty, total_slides)
  296. slides_out = []
  297. for slide_num, comments in groups:
  298. slide_obj: dict = {"slideNumber": slide_num, "comments": []}
  299. for c in comments:
  300. slide_obj["comments"].append(
  301. {
  302. "kind": c.kind,
  303. "authorName": c.author_name,
  304. "authorInitials": c.author_initials,
  305. "createdAt": c.created_at,
  306. "commentId": c.comment_id,
  307. "text": c.text,
  308. }
  309. )
  310. slides_out.append(slide_obj)
  311. return json.dumps({"slides": slides_out}, ensure_ascii=False, indent=2)
  312. # ---------------------------------------------------------------------------
  313. # CLI
  314. # ---------------------------------------------------------------------------
  315. def parse_args() -> argparse.Namespace:
  316. parser = argparse.ArgumentParser(
  317. description="Extract review comments (annotations) from PPTX files."
  318. )
  319. parser.add_argument("pptx_path", help="Path to the PPTX file.")
  320. selection = parser.add_mutually_exclusive_group()
  321. selection.add_argument(
  322. "--slides", help='Only inspect these slide numbers, e.g. "1,3,5".'
  323. )
  324. selection.add_argument(
  325. "--range", dest="slide_range", help='Continuous slide range, e.g. "2-4".'
  326. )
  327. parser.add_argument(
  328. "--search", help="Only show comments whose text matches this keyword."
  329. )
  330. parser.add_argument(
  331. "--ignore-case", action="store_true", help="Make search case-insensitive."
  332. )
  333. parser.add_argument(
  334. "--format",
  335. choices=["text", "json"],
  336. default="text",
  337. help="Output format (default: text).",
  338. )
  339. parser.add_argument(
  340. "--include-empty",
  341. action="store_true",
  342. help="Include slides that have no comments in the output.",
  343. )
  344. return parser.parse_args()
  345. def main() -> int:
  346. args = parse_args()
  347. pptx_path = args.pptx_path
  348. # validate file
  349. try:
  350. if not zipfile.is_zipfile(pptx_path):
  351. print("Failed to inspect PPTX comments: not a valid ZIP/PPTX file.", file=sys.stderr)
  352. return 1
  353. except (OSError, FileNotFoundError) as exc:
  354. print(f"Failed to inspect PPTX comments: {exc}", file=sys.stderr)
  355. return 1
  356. try:
  357. records = extract_comments(pptx_path)
  358. except Exception as exc:
  359. print(f"Failed to inspect PPTX comments: {exc}", file=sys.stderr)
  360. return 1
  361. # determine total slide count for --include-empty
  362. try:
  363. with zipfile.ZipFile(pptx_path, "r") as zf:
  364. total_slides = len(enumerate_slides(zf))
  365. except Exception:
  366. total_slides = max((r.slide_number for r in records), default=0)
  367. # apply filters
  368. try:
  369. selected_numbers = parse_slide_numbers(args.slides) if args.slides else None
  370. selected_range = (
  371. parse_slide_range(args.slide_range) if args.slide_range else None
  372. )
  373. records = filter_records(
  374. records, selected_numbers, selected_range, args.search, args.ignore_case
  375. )
  376. except ValueError as exc:
  377. print(str(exc), file=sys.stderr)
  378. return 1
  379. # output
  380. if args.format == "json":
  381. print(format_json(records, args.include_empty, total_slides))
  382. else:
  383. output = format_text(records, args.include_empty, total_slides)
  384. print(output)
  385. return 0
  386. if __name__ == "__main__":
  387. raise SystemExit(main())