#!/usr/bin/env python3 """Extract embedded PPTX videos and report their slide references and metadata.""" import argparse import html import json import os 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 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', 'md', 'txt', 'json') HEADERS = ('Slide(s)', 'Duration', 'Video', 'Size', 'Resolution', 'Codec') REPORT_NOTES = ( 'Duration is the original media file duration, not slide playback time ' '(PowerPoint trimming, looping, and animation are not applied).', 'Videos linked externally are not downloaded. Slide numbers follow presentation order.', ) def status(message, level='info'): """Keep redirected output plain and flush progress before slow operations.""" stream = sys.stderr if level in ('warning', 'error') else sys.stdout label, color = { 'info': ('INFO', '36'), 'success': ('OK', '32'), 'warning': ('WARN', '33'), 'error': ('ERROR', '31'), }[level] prefix = f'[{label}]' if stream.isatty() and 'NO_COLOR' not in os.environ and os.environ.get('TERM') != 'dumb': prefix = f'\033[{color}m{prefix}\033[0m' print(f'{prefix} {message}', file=stream, flush=True) 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 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 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} 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 for item in formats): raise argparse.ArgumentTypeError('Choose comma-separated formats from: ' + ', '.join(REPORT_FORMATS)) return formats def report_data(source, rows, uses, external, out): 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': name if (out / name).is_file() else None, }) 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 videos if v['duration_seconds'] is not None), 'known_durations': sum(v['duration_seconds'] is not None for v in videos), '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 render_report(data, format): title = f'Video timings — {data["presentation"]}' 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_durations"]} / {data["embedded_videos"]}'), ] 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_durations"]}/{data["embedded_videos"]} successfully probed; each file counted once)', ] 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).') cells = [ [', '.join(map(str, v['slides'])) or 'Unreferenced', time_fmt(v['duration_seconds']), v['name'], size_fmt(v['size_bytes']), v['resolution'], v['codec']] for v in data['videos'] ] 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, data['videos']): 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, data['videos']): 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]}' 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 == '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: (34mm, auto, 1fr, auto, auto, auto),', ' align: (left + horizon, right + horizon, left + horizon, right + horizon, left + horizon, left + horizon),', ' inset: 8pt,', ' 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, data['videos']): 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}")' 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 report = out / ('timings.typ' if format == 'typst' else f'timings.{format}') status(f'Writing report: {report}') report.write_text(render_report(data, format), encoding='utf-8') status(f'Report: {report}', 'success') if 'pdf' in formats: report = out / 'timings.pdf' status(f'Compiling PDF with Typst: {report}') subprocess.run(['typst', 'compile', str((out / 'timings.typ').resolve()), str(report.resolve())], check=True, capture_output=True, text=True) status(f'Report: {report}', 'success') 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, md, txt, json. Repeatable; default: md. PDF requires typst and keeps timings.typ.') 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']]) 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') try: status(f'Scanning presentation: {source}') with zipfile.ZipFile(source) as z: videos, uses, external = discover(z) 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' in 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}') out.mkdir(parents=True, exist_ok=True) rows = [] total_bytes = 0 total_seconds = 0.0 known = 0 for index, part in enumerate(videos, 1): name = posixpath.basename(part) dest = out / 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: 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 if duration is not None: total_seconds += duration known += 1 status(f' 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)) if args.extract_only: status(f'Done: {len(videos)} video(s) processed.', 'success') return 0 write_reports(report_data(source, rows, uses, external, out), formats, out) status(f'Done: {known}/{len(videos)} durations available, {time_fmt(total_seconds)} total, {size_fmt(total_bytes)}.', 'success') 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())