beffroi-tools/pptx_videos.py

458 lines
24 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/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'<span class="pill slide">{slide}</span>' for slide in video['slides']) or '<span class="pill muted">Unreferenced</span>'
duration_class = 'duration' if video['duration_seconds'] is not None else 'warning'
row[1] = f'<span class="pill {duration_class}">{row[1]}</span>'
row[5] = f'<span class="pill muted">{row[5]}</span>'
if video['extracted_file']:
row[2] = f'<a href="{html.escape(quote(video["extracted_file"]))}">{row[2]}</a>'
table_rows.append('<tr>' + ''.join(f'<td>{value}</td>' for value in row) + '</tr>')
return (
'<!doctype html>\n<html lang="en"><head><meta charset="utf-8">\n'
'<meta name="viewport" content="width=device-width, initial-scale=1">\n'
f'<title>{html.escape(title)}</title>\n'
'<style>*{box-sizing:border-box}html{background:#f3f5fa}'
'body{font:15px/1.6 system-ui,sans-serif;max-width:1280px;margin:48px auto;padding:0 28px;color:#172033}'
'.eyebrow{color:#5744b5;font-size:12px;font-weight:750;letter-spacing:.16em;text-transform:uppercase}'
'h1{font-size:clamp(28px,4vw,42px);letter-spacing:-.04em;line-height:1.2;margin:10px 0}'
'.subtitle{color:#626b80;overflow-wrap:anywhere;margin:0 0 28px}'
'.metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px;margin:28px 0}'
'.metric{background:white;border:1px solid #e2e6f0;border-radius:16px;padding:18px 20px}'
'.metric span{display:block;font-size:12px;color:#626b80;margin-bottom:8px}'
'.metric strong{font-size:23px;letter-spacing:-.03em;font-variant-numeric:tabular-nums}'
'.metric:nth-child(2){background:#eeeafd;border-color:#ded6fa;color:#49359b}'
'.table{overflow-x:auto;background:white;border:1px solid #e2e6f0;border-radius:16px;box-shadow:0 8px 30px #17203306}'
'table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}'
'th,td{padding:15px 18px;text-align:left;border-bottom:1px solid #edf0f6}'
'th{background:#f8f9fc;color:#626b80;font-size:11px;text-transform:uppercase;letter-spacing:.07em}'
'tr:last-child td{border-bottom:0}tbody tr:hover{background:#faf9ff}'
'td:nth-child(2),td:nth-child(4){text-align:right;white-space:nowrap}'
'th:nth-child(2),th:nth-child(4){text-align:right}'
'td:nth-child(3){overflow-wrap:anywhere;min-width:180px;font-weight:600}'
'a{color:#5744b5;text-decoration:none}a:hover{text-decoration:underline}a:focus-visible{outline:2px solid #5744b5}'
'.pill{display:inline-block;border-radius:999px;padding:3px 10px;font-size:12px;font-weight:600;margin:2px 0}'
'.slide{background:#eeeafd;color:#49359b}.duration{background:#e3f4ee;color:#176349}'
'.warning{background:#fff0ce;color:#805300}.muted{background:#edf0f6;color:#566176}'
'footer{color:#626b80;font-size:12px;margin-top:24px;border-left:3px solid #dcd5f6;padding-left:16px}'
'footer p{margin:5px 0}@media(max-width:760px){body{margin:24px auto;padding:0 16px}.metrics{grid-template-columns:repeat(2,minmax(0,1fr))}.metric strong{font-size:18px}}'
'@media print{html{background:white}body{margin:0;padding:0;max-width:none}.table{overflow:visible;box-shadow:none}.metrics,.metric,tr{break-inside:avoid}thead{display:table-header-group}*{print-color-adjust:exact}}</style></head><body>\n'
'<header><div class="eyebrow">Presentation media report</div><h1>Video timings</h1>'
f'<p class="subtitle">{html.escape(data["presentation"])}</p></header><section class="metrics" aria-label="Summary">' +
''.join(f'<div class="metric"><span>{html.escape(label)}</span><strong>{html.escape(value)}</strong></div>' for label, value in metrics) +
'</section><div class="table"><table aria-label="Video timings by slide"><thead><tr>' +
''.join(f'<th scope="col">{heading}</th>' for heading in HEADERS) +
'</tr></thead><tbody>\n' + '\n'.join(table_rows) +
'</tbody></table></div><footer>' +
''.join(f'<p>{html.escape(note)}</p>' for note in notes) +
'</footer></body></html>\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: <presentation-stem>_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())