#!/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.', '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'' 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('
{html.escape(data["presentation"])}
| {heading} | ' for heading in HEADERS) + '
|---|