#!/usr/bin/env python3 """Extract embedded PPTX videos and report their slide references and metadata.""" import argparse import html import json import math import posixpath import re import shutil import subprocess import sys import tempfile import zipfile from collections import defaultdict from pathlib import Path from urllib.parse import quote from xml.etree import ElementTree as ET if __package__: from .ontime import ontime_project from .progress import Progress, status from .playback import effective_playback, shape_playbacks else: from ontime import ontime_project from progress import Progress, status from playback import effective_playback, shape_playbacks VIDEO_EXTS = {'.mp4', '.m4v', '.mov', '.avi', '.wmv', '.webm', '.mpg', '.mpeg', '.mkv', '.asf', '.3gp', '.ts'} REL_NS = 'http://schemas.openxmlformats.org/package/2006/relationships' R_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships' P_NS = 'http://schemas.openxmlformats.org/presentationml/2006/main' REPORT_FORMATS = ('html', 'typst', 'pdf', 'pdf-dense', 'md', 'txt', 'json', 'ontime') HEADERS = ('Slide(s)', 'Duration', 'Video', 'Size', 'Resolution', 'Codec', 'Original', 'Playback') REPORT_NOTES = ( 'Duration applies PowerPoint trimming per video occurrence. Original is the media file duration. ' 'Loops and unsupported timing are listed but excluded from duration totals and Ontime.', 'Durations describe one playback, not total slide time; click delays and slide transitions are not simulated. Extracted files remain untrimmed.', 'Videos linked externally are not downloaded. Slide numbers follow presentation order.', ) def xml(z, name): try: return ET.fromstring(z.read(name)) except (KeyError, ET.ParseError): return None def rels(z, source): directory, basename = posixpath.split(source) path = posixpath.join(directory, '_rels', basename + '.rels') root = xml(z, path) if root is None: return {} result = {} for rel in root.findall(f'{{{REL_NS}}}Relationship'): rid = rel.get('Id') target = rel.get('Target', '') if not rid: continue if rel.get('TargetMode', '').lower() == 'external': result[rid] = (None, rel.get('Type', '')) else: # Targets can be package-root absolute or relative to the source part. target = target.split('#', 1)[0].split('?', 1)[0] resolved = posixpath.normpath(target.lstrip('/') if target.startswith('/') else posixpath.join(directory, target)) result[rid] = (resolved, rel.get('Type', '')) return result def slide_paths(z): root = xml(z, 'ppt/presentation.xml') mapping = rels(z, 'ppt/presentation.xml') if root is not None: ordered = [] for slide in root.findall(f'.//{{{P_NS}}}sldId'): target = mapping.get(slide.get(f'{{{R_NS}}}id'), (None, ''))[0] if target: ordered.append(target) if ordered: return ordered return sorted((n for n in z.namelist() if re.fullmatch(r'ppt/slides/slide\d+\.xml', n)), key=lambda n: int(re.search(r'slide(\d+)', n).group(1))) def discover(z): """Map actual archive media parts to presentation-order slide numbers.""" names = set(z.namelist()) videos = sorted((n for n in names if n.startswith('ppt/media/') and Path(n).suffix.lower() in VIDEO_EXTS)) uses = defaultdict(set) external = set() for index, slide in enumerate(slide_paths(z), 1): root = xml(z, slide) if root is None: continue mapping = rels(z, slide) # Only relationships referenced by videoFile or p14:media elements; # excludes audio-only attachments and poster images. for el in root.iter(): tag = el.tag.rsplit('}', 1)[-1] if tag not in ('videoFile', 'media'): continue for attr in (f'{{{R_NS}}}link', f'{{{R_NS}}}embed'): rid = el.get(attr) if not rid or rid not in mapping: continue target, rel_type = mapping[rid] if tag == 'media' and not rel_type.endswith('/media'): continue if target is None: if tag == 'videoFile' or rel_type.endswith('/media'): external.add(index) elif target in names and Path(target).suffix.lower() in VIDEO_EXTS: uses[target].add(index) return videos, uses, external def size_fmt(n): for unit in ('B', 'KiB', 'MiB', 'GiB', 'TiB'): if n < 1024 or unit == 'TiB': return f'{n:.0f} {unit}' if unit == 'B' else f'{n:.2f} {unit}' n /= 1024 def playback_settings(z, videos): settings = defaultdict(list) for index, slide in enumerate(slide_paths(z), 1): root = xml(z, slide) if root is not None: for item in shape_playbacks(root, rels(z, slide), set(videos), index): settings[item['archive_path']].append(item) return settings def time_fmt(seconds): if seconds is None: return 'Unknown' millis = round(seconds * 1000) h, rem = divmod(millis, 3600000) m, rem = divmod(rem, 60000) s, ms = divmod(rem, 1000) return f'{h:02}:{m:02}:{s:02}.{ms:03}' def probe(path): try: p = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration:stream=codec_type,width,height,codec_name', '-of', 'json', str(path)], capture_output=True, text=True, check=True) data = json.loads(p.stdout) duration = data.get('format', {}).get('duration') duration = float(duration) if duration not in (None, 'N/A') else None if duration is not None and (not math.isfinite(duration) or duration < 0): duration = None streams = data.get('streams', []) video = next((s for s in streams if s.get('codec_type') == 'video'), {}) resolution = f"{video['width']}×{video['height']}" if video.get('width') and video.get('height') else 'Unknown' return duration, resolution, video.get('codec_name', 'Unknown') except (subprocess.CalledProcessError, OSError, ValueError, json.JSONDecodeError): return None, 'Unknown', 'Unknown' def esc(s): return str(s).replace('|', '\\|').replace('\n', ' ') def aligned_table(cells, markdown=True): headers = HEADERS widths = [max(3, *(len(row[i]) for row in [headers, *cells])) for i in range(len(headers))] right_aligned = {1, 3, 6} def render(row): return '| ' + ' | '.join( value.rjust(widths[i]) if i in right_aligned else value.ljust(widths[i]) for i, value in enumerate(row) ) + ' |' separators = [ '-' * (width - 1) + ':' if markdown and i in right_aligned else '-' * width for i, width in enumerate(widths) ] return [render(headers), render(separators), *(render(row) for row in cells)] def report_formats(value): formats = [item.strip().lower() for item in value.split(',')] if any(item not in (*REPORT_FORMATS, 'all') for item in formats): raise argparse.ArgumentTypeError('Choose comma-separated formats from: ' + ', '.join((*REPORT_FORMATS, 'all'))) return list(dict.fromkeys( format for item in formats for format in (REPORT_FORMATS if item == 'all' else (item,)) )) def report_data(source, rows, uses, external, out, settings=None): videos = [] for part, name, size, duration, resolution, codec in sorted( rows, key=lambda row: (min(uses[row[0]], default=float('inf')), row[1])): videos.append({ 'slides': sorted(uses[part]), 'duration_seconds': duration, 'name': name, 'size_bytes': size, 'resolution': resolution, 'codec': codec, 'archive_path': part, 'extracted_file': f'../videos/{name}' if (out / 'videos' / name).is_file() else None, }) playbacks = [] for video in videos: occurrences = list((settings or {}).get(video['archive_path'], [])) covered = {item['slide'] for item in occurrences} # Retain references without recognized shape metadata, and orphan media. for slide in (video['slides'] or [None]): if slide not in covered: occurrences.append({'slide': slide, 'shape_id': None, 'trim_start_seconds': 0.0, 'trim_end_seconds': 0.0, 'playback_status': 'normal', 'playback_notes': []}) playbacks.extend(effective_playback(video, item) for item in occurrences) playbacks.sort(key=lambda item: (item['slide'] if item['slide'] is not None else math.inf, item['name'], item['shape_id'] or '')) return { 'presentation': source.name, 'embedded_videos': len(videos), 'total_size_bytes': sum(v['size_bytes'] for v in videos), 'total_duration_seconds': sum(v['duration_seconds'] for v in playbacks if v['duration_seconds'] is not None), 'total_media_duration_seconds': sum(v['duration_seconds'] for v in videos if v['duration_seconds'] is not None), 'known_durations': sum(v['duration_seconds'] is not None for v in videos), 'known_playback_durations': sum(v['duration_seconds'] is not None for v in playbacks), 'playbacks': playbacks, 'videos': videos, 'external_media_slides': sorted(external), 'notes': list(REPORT_NOTES), } def typst_string(value): # Encode as a literal string, never as executable Typst markup. return '"' + ''.join( '\\' + c if c in ('\\', '"') else f'\\u{{{ord(c):x}}}' if ord(c) < 32 else c for c in value ) + '"' def trim_detail(video): start = video.get('trim_start_seconds', 0) end = video.get('trim_end_seconds', 0) if not (start or end): return '' return f'Trim removed · start {time_fmt(start)} · end {time_fmt(end)}' def typst_media(video, dense=False): """Keep playback annotations with the media, without adding table columns.""" detail = trim_detail(video) if not detail and video['playback_status'] != 'looping': return typst_string(video['name']) content = '#' + typst_string(video['name']) if video['playback_status'] == 'looping': colors = '"#fff0ce", "#805300"' if dense else 'bg: "#fff0ce", fg: "#805300"' content += f' #pill("Looping", {colors})' if detail: content += '\n#par(leading: 2pt, text(size: 7pt, fill: rgb("#626b80"), ' + typst_string(detail) + '))' return '[' + content + ']' def render_report(data, format): if format == 'ontime': return json.dumps(ontime_project(data), ensure_ascii=False, indent=2, allow_nan=False) + '\n' title = f'Video timings — {data["presentation"]}' report_rows = data['playbacks'] metrics = [ ('Embedded videos', str(data['embedded_videos'])), ('Total duration', time_fmt(data['total_duration_seconds'])), ('Total size', size_fmt(data['total_size_bytes'])), ('Durations available', f'{data["known_playback_durations"]} / {len(report_rows)}'), ] summary = [ f'Embedded videos: {data["embedded_videos"]}', f'Total size: {size_fmt(data["total_size_bytes"])}', f'Total duration: {time_fmt(data["total_duration_seconds"])} ' f'({data["known_playback_durations"]}/{len(report_rows)} occurrences with known playback duration)', ] notes = list(data['notes']) if data['external_media_slides']: notes.append('Slides with external media links: ' + ', '.join(map(str, data['external_media_slides'])) + ' (not extracted).') labels = {'looping': 'Looping', 'custom-timing': 'Custom timing', 'invalid-trim': 'Invalid trim'} cells = [ [', '.join(map(str, v['slides'])) or 'Unreferenced', labels.get(v['playback_status'], time_fmt(v['duration_seconds'])), v['name'], size_fmt(v['size_bytes']), v['resolution'], v['codec'], time_fmt(v['original_duration_seconds']), v['playback_status']] for v in report_rows ] if format == 'json': return json.dumps(data, ensure_ascii=False, indent=2, allow_nan=False) + '\n' if format in ('md', 'txt'): for row, video in zip(cells, report_rows): detail = trim_detail(video) if detail: row[7] += '; ' + detail row[:] = [esc(value) if format == 'md' else value.replace('\n', ' ') for value in row] if format == 'md' and video['extracted_file']: row[2] = f'[{row[2]}]({quote(video["extracted_file"])})' lines = [('# ' if format == 'md' else '') + title, ''] lines += ['- ' + line for line in summary] lines += ['', *aligned_table(cells, markdown=format == 'md'), ''] lines += [('> ' if format == 'md' else '') + note for note in notes] return '\n'.join(lines) + '\n' if format == 'html': table_rows = [] for row, video in zip(cells, report_rows): row = [html.escape(value) for value in row] row[0] = ' '.join(f'{slide}' for slide in video['slides']) or 'Unreferenced' duration_class = 'duration' if video['duration_seconds'] is not None else 'warning' row[1] = f'{row[1]}' row[5] = f'{row[5]}' if video['extracted_file']: row[2] = f'{row[2]}' if video['playback_status'] == 'looping': row[1] = '—' row[2] += ' Looping' detail = trim_detail(video) if detail: row[2] += f'{html.escape(detail)}' table_rows.append('' + ''.join(f'{value}' for value in row) + '') return ( '\n\n' '\n' f'{html.escape(title)}\n' '\n' '
Presentation media report

Video timings

' f'

{html.escape(data["presentation"])}

' + ''.join(f'
{html.escape(label)}{html.escape(value)}
' for label, value in metrics) + '
' + ''.join(f'' for heading in HEADERS) + '\n' + '\n'.join(table_rows) + '
{heading}
\n' ) if format == 'pdf-dense': lines = [ '#set page(paper: "a4", margin: 14mm,', ' footer: context align(right, text(size: 7pt, fill: rgb("#626b80"), counter(page).display("1"))))', '#set text(font: "DejaVu Sans", size: 9pt, fill: rgb("#172033"))', '#set par(justify: false)', '#let pill(body, bg, fg) = box(fill: rgb(bg), radius: 20pt,', ' inset: (x: 7pt, y: 2pt), text(size: 8pt, fill: rgb(fg), body))', '#par(text(size: 10pt, fill: rgb("#626b80"), ' + typst_string(title) + '))', '#v(4pt)', '#table(', ' columns: (30mm, 1fr, auto),', ' align: (left + horizon, left + horizon, right + horizon),', ' inset: (x: 8pt, y: 4pt),', ' stroke: (top: none, left: none, right: none, bottom: 0.4pt + rgb("#e2e6f0")),', ' fill: (x, y) => if y == 0 { rgb("#eeeafd") } else if calc.even(y) { rgb("#f8f9fc") },', ' table.header(strong("Slide(s)"), strong("Media"), strong("Duration")),', ] for row, video in zip(cells, report_rows): bg, fg = ('#e3f4ee', '#176349') if video['duration_seconds'] is not None else ('#fff0ce', '#805300') duration = '"—"' if video['playback_status'] == 'looping' else f'pill({typst_string(row[1])}, "{bg}", "{fg}")' lines.append(f' {typst_string(row[0])}, {typst_media(video, dense=True)}, {duration},') lines += [')', '#v(6pt)'] lines += ['#par(text(size: 7pt, fill: rgb("#626b80"), ' + typst_string(note) + '))' for note in notes] return '\n'.join(lines) + '\n' if format == 'typst': lines = [ '#set page(paper: "a4", flipped: true, margin: 16mm,', ' footer: context align(right, text(size: 8pt, fill: rgb("#626b80"), counter(page).display("1"))))', '#set text(font: "DejaVu Sans", size: 9pt, fill: rgb("#172033"))', '#set par(justify: false)', '#let pill(body, bg: "#eeeafd", fg: "#49359b") = box(', ' fill: rgb(bg), radius: 20pt, inset: (x: 7pt, y: 3pt),', ' text(size: 8pt, weight: "medium", fill: rgb(fg), body))', '#let metric(label, value) = block(width: 100%, fill: rgb("#f3f1fc"),', ' radius: 8pt, inset: 12pt)[', ' #text(size: 8pt, fill: rgb("#626b80"), label)', ' #v(5pt)', ' #text(size: 17pt, weight: "bold", fill: rgb("#49359b"), value)', ']', '#text(size: 8pt, weight: "bold", fill: rgb("#5744b5"), tracking: 1pt)[PRESENTATION MEDIA REPORT]', '#v(5pt)', '#text(size: 28pt, weight: "bold")[Video timings]', '#par(text(fill: rgb("#626b80"), ' + typst_string(data['presentation']) + '))', '#v(8pt)', '#grid(columns: (1fr, 1fr, 1fr, 1fr), gutter: 10pt,', ] lines += [' metric(' + typst_string(label) + ', ' + typst_string(value) + '),' for label, value in metrics] lines += [')'] lines += [ '#v(16pt)', '#table(', ' columns: (22mm, auto, 1fr, auto, auto, auto, auto, auto),', ' align: (left + horizon, right + horizon, left + horizon, right + horizon, left + horizon, left + horizon, right + horizon, left + horizon),', ' inset: 5pt,', ' stroke: (top: none, left: none, right: none, bottom: 0.4pt + rgb("#e2e6f0")),', ' fill: (x, y) => if y == 0 { rgb("#eeeafd") } else if calc.even(y) { rgb("#f8f9fc") },', ' table.header(' + ', '.join('text(size: 8pt, weight: "bold", fill: rgb("#49359b"), ' + typst_string(h) + ')' for h in HEADERS) + '),', ] for row, video in zip(cells, report_rows): values = [typst_string(value) for value in row] values[0] = '[' + ' '.join('#pill(' + typst_string(str(slide)) + ')' for slide in video['slides']) + ']' if video['slides'] else 'text(size: 8pt, fill: rgb("#626b80"), "Unreferenced")' bg, fg = ('#e3f4ee', '#176349') if video['duration_seconds'] is not None else ('#fff0ce', '#805300') values[1] = f'pill({values[1]}, bg: "{bg}", fg: "{fg}")' if video['playback_status'] == 'looping': values[1] = '"—"' values[2] = typst_media(video) values[5] = f'pill({values[5]}, bg: "#edf0f6", fg: "#566176")' lines.append(' ' + ', '.join(values) + ',') lines += [')', '#v(10pt)'] lines += ['#par(text(size: 8pt, fill: rgb("#626b80"), ' + typst_string(note) + '))' for note in notes] return '\n'.join(lines) + '\n' raise ValueError(f'Unsupported report format: {format}') def write_reports(data, formats, out): # Keep the source beside the PDF so it can be edited and compiled again. if 'pdf' in formats and 'typst' not in formats: formats = [*formats, 'typst'] for format in formats: if format == 'pdf': continue extension = {'typst': 'typ', 'ontime': 'ontime.json'}.get(format, format) report = out / ('timings-dense.typ' if format == 'pdf-dense' else f'timings.{extension}') status(f'Writing report: {report}') report.write_text(render_report(data, format), encoding='utf-8') status(f'Report: {report}', 'success', persist=True) for format in ('pdf', 'pdf-dense'): if format not in formats: continue stem = 'timings-dense' if format == 'pdf-dense' else 'timings' report = out / f'{stem}.pdf' status(f'Compiling PDF with Typst: {report}') subprocess.run(['typst', 'compile', str((out / f'{stem}.typ').resolve()), str(report.resolve())], check=True, capture_output=True, text=True) status(f'Report: {report}', 'success', persist=True) def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('presentation', type=Path, help='Source .pptx file') parser.add_argument('-o', '--output', type=Path, help='Output directory (default: _videos)') mode = parser.add_mutually_exclusive_group() mode.add_argument('--extract-only', action='store_true', help='Extract embedded videos without a report') mode.add_argument('--timings-only', action='store_true', help='Report video timings without keeping newly extracted videos') parser.add_argument('--overwrite', action='store_true', help='Overwrite already extracted files') parser.add_argument('--report', type=report_formats, action='append', metavar='FORMAT[,FORMAT...]', help='Report formats: html, typst, pdf, pdf-dense, md, txt, json, ontime, or all. Repeatable; default: md,ontime. PDFs require typst and keep their .typ sources.') args = parser.parse_args() if args.extract_only and args.report: parser.error('--report cannot be combined with --extract-only.') formats = list(dict.fromkeys(format for group in (args.report or [['md', 'ontime']]) for format in group)) source = args.presentation if not source.is_file(): parser.error(f'Not a file: {source}') out = args.output or source.with_name(source.stem + '_videos') video_dir = out / 'videos' report_dir = out / 'reports' try: with Progress() as progress, zipfile.ZipFile(source) as z: status(f'Scanning presentation: {source}') videos, uses, external = discover(z) settings = playback_settings(z, videos) if not args.extract_only else {} if external: status(f'External media on slide(s) {", ".join(map(str, sorted(external)))} will not be downloaded.', 'warning') if not videos: status('No embedded video files found; no output created.', 'warning') return 0 status(f'Found {len(videos)} embedded video(s), {size_fmt(sum(z.getinfo(part).file_size for part in videos))} in the presentation.') if not args.extract_only and shutil.which('ffprobe') is None: parser.error('ffprobe is required for timings. Install ffmpeg or use --extract-only.') if not args.extract_only and {'pdf', 'pdf-dense'}.intersection(formats) and shutil.which('typst') is None: parser.error('typst is required for PDF reports. Install the Typst CLI or choose --report typst to generate source only.') mode_label = 'extraction only' if args.extract_only else 'timings only' if args.timings_only else 'extraction and timings' status(f'Mode: {mode_label}. Output: {out}') if not args.timings_only: video_dir.mkdir(parents=True, exist_ok=True) rows = [] total_bytes = 0 progress.set(0, len(videos)) for index, part in enumerate(videos, 1): name = posixpath.basename(part) dest = video_dir / name slides = ', '.join(map(str, sorted(uses[part]))) or 'unreferenced' status(f'[{index}/{len(videos)}] {name} — {size_fmt(z.getinfo(part).file_size)} — slide(s): {slides}') if not args.timings_only: if dest.exists() and not args.overwrite: status(f' Keeping existing file: {dest}') else: status(f' Extracting to: {dest}') with z.open(part) as src, dest.open('wb') as dst: shutil.copyfileobj(src, dst) status(' Extraction complete.', 'success') if args.extract_only: progress.set(index) continue if not dest.is_file(): # A seekable temporary file supports media whose metadata # cannot be read reliably from a pipe. with tempfile.TemporaryDirectory(prefix='pptx-videos-') as tmp: temporary_video = Path(tmp) / name status(' Extracting a temporary copy for probing...') with z.open(part) as src, temporary_video.open('wb') as dst: shutil.copyfileobj(src, dst) size = temporary_video.stat().st_size status(' Probing temporary video with ffprobe...') duration, resolution, codec = probe(temporary_video) status(' Temporary copy removed.') else: size = dest.stat().st_size status(f' Probing with ffprobe: {dest}') duration, resolution, codec = probe(dest) total_bytes += size status(f' Original duration: {time_fmt(duration)} | Resolution: {resolution} | Codec: {codec}', 'success' if duration is not None else 'warning') if duration is None: status(' ffprobe could not determine the duration; continuing with available metadata.', 'warning') rows.append((part, name, size, duration, resolution, codec)) progress.set(index) if args.extract_only: status(f'Done: {len(videos)} video(s) processed. Output: {video_dir}', 'success', persist=True) return 0 report_dir.mkdir(parents=True, exist_ok=True) data = report_data(source, rows, uses, external, out, settings) write_reports(data, formats, report_dir) status(f'Done: {data["known_playback_durations"]}/{len(data["playbacks"])} playback durations available, {time_fmt(data["total_duration_seconds"])} total, {size_fmt(total_bytes)}.', 'success', persist=True) return 0 except subprocess.CalledProcessError as e: status(f'Typst compilation failed: {e.stderr.strip()}', 'error') return 1 except (zipfile.BadZipFile, OSError, ET.ParseError) as e: status(str(e), 'error') return 1 if __name__ == '__main__': sys.exit(main())