Add presentation video reports and document exporter
This commit is contained in:
parent
a85f5c9360
commit
c85fa86072
49
README.md
49
README.md
|
|
@ -1,3 +1,50 @@
|
|||
# beffroi-tools
|
||||
|
||||
Beffroi tools, for everyday usage
|
||||
Beffroi tools, for everyday usage
|
||||
|
||||
## PPTX video reports
|
||||
|
||||
Extract videos and create a Markdown timing report:
|
||||
|
||||
```sh
|
||||
python pptx_videos.py presentation.pptx
|
||||
```
|
||||
|
||||
Generate one or more report formats without keeping newly extracted videos:
|
||||
|
||||
```sh
|
||||
python pptx_videos.py presentation.pptx --timings-only --report html,pdf
|
||||
python pptx_videos.py presentation.pptx --report html,typst,pdf,md,txt,json
|
||||
```
|
||||
|
||||
`--report` accepts comma-separated formats and can be repeated. Markdown is the
|
||||
default. Reports are saved as `timings.*` in `<presentation-stem>_videos`, or the
|
||||
directory supplied with `-o`. PDF uses the Typst CLI and retains `timings.typ`
|
||||
for editing. HTML and Typst/PDF include colored summary cards and pills;
|
||||
Markdown and TXT use aligned tables. JSON includes numeric durations in seconds,
|
||||
sizes in bytes, and slide references.
|
||||
|
||||
Timings require `ffprobe` (from FFmpeg); PDF additionally requires `typst` on
|
||||
`PATH`. Use `--extract-only` to extract without a report. Presentations with no
|
||||
embedded videos produce no output. Terminal progress uses colors automatically;
|
||||
set `NO_COLOR` to disable them.
|
||||
|
||||
## Export presentations and PDF pages
|
||||
|
||||
```sh
|
||||
python exporter.py presentation.pptx --output pdf,images
|
||||
python exporter.py document.pdf --output images
|
||||
python exporter.py presentation.pptx --output images --dpi 192 -d exports
|
||||
```
|
||||
|
||||
`exporter.py` uses DeckCraft for PPTX exports and PdfCraft for PDF page rendering.
|
||||
It finds `deckcraft-cli` / `pdfcraft-cli` on `PATH`, or temporarily extracts the
|
||||
bundled CLI from the newest matching AppImage in `~/Applications`. You can
|
||||
specify a CLI executable or AppImage with `--deckcraft-cli` / `--pdfcraft-cli`,
|
||||
or the `DECKCRAFT_CLI` / `PDFCRAFT_CLI` environment variables.
|
||||
|
||||
Output goes to `<file-stem>_export/`: `<file-stem>.pdf` and/or numbered PNGs
|
||||
inside `images/`. Images default to 144 DPI. Existing output requires
|
||||
`--overwrite`, which replaces generated files and removes stale numbered
|
||||
slide/page PNGs. PDF-to-PDF is a successful no-op; other input extensions are
|
||||
errors. Rendering completes in temporary storage before output is copied.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,187 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Export PPTX to PDF/PNG with DeckCraft, or PDF to PNG with PdfCraft."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
|
||||
def status(message, level='info'):
|
||||
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 output_formats(value):
|
||||
formats = list(dict.fromkeys(item.strip().lower() for item in value.split(',')))
|
||||
if any(item not in ('pdf', 'images') for item in formats):
|
||||
raise argparse.ArgumentTypeError('Output must be pdf, images, or pdf,images.')
|
||||
return formats
|
||||
|
||||
|
||||
def positive_int(value):
|
||||
number = int(value)
|
||||
if number <= 0:
|
||||
raise argparse.ArgumentTypeError('Must be a positive integer.')
|
||||
return number
|
||||
|
||||
|
||||
def run(command, **kwargs):
|
||||
result = subprocess.run([str(arg) for arg in command], capture_output=True,
|
||||
text=True, errors='replace', **kwargs)
|
||||
if result.returncode:
|
||||
detail = result.stderr.strip() or result.stdout.strip() or f'exit code {result.returncode}'
|
||||
raise RuntimeError(f'{Path(command[0]).name}: {detail}')
|
||||
if result.stderr.strip():
|
||||
for line in result.stderr.strip().splitlines():
|
||||
status(line, 'warning' if re.search(r'\b(warning|error)\b', line, re.I) else 'info')
|
||||
return result.stdout
|
||||
|
||||
|
||||
def find_cli(app, override, work):
|
||||
"""Use PATH first, then a local AppImage's bundled CLI (no FUSE needed)."""
|
||||
candidate = override or os.environ.get(app.upper() + '_CLI')
|
||||
if candidate:
|
||||
path = Path(candidate).expanduser()
|
||||
if not path.is_file():
|
||||
found = shutil.which(candidate)
|
||||
if not found:
|
||||
raise RuntimeError(f'Cannot find {app} executable: {candidate}')
|
||||
path = Path(found)
|
||||
else:
|
||||
found = shutil.which(f'{app}-cli')
|
||||
if found:
|
||||
path = Path(found)
|
||||
else:
|
||||
images = list((Path.home() / 'Applications').glob(f'{app}-*.AppImage'))
|
||||
# Natural version ordering: 0.10 follows 0.9.
|
||||
images.sort(key=lambda p: [int(n) for n in re.findall(r'\d+', p.name)], reverse=True)
|
||||
if not images:
|
||||
raise RuntimeError(
|
||||
f'{app}-cli not found. Install {app}, place its AppImage in ~/Applications, '
|
||||
f'or pass --{app}-cli PATH (CLI executable or AppImage).')
|
||||
path = images[0]
|
||||
path = path.resolve()
|
||||
if path.suffix.lower() == '.appimage':
|
||||
status(f'Loading bundled {app}-cli from {path.name}...')
|
||||
unpack = work / app
|
||||
unpack.mkdir()
|
||||
run([path, '--appimage-extract', f'usr/bin/{app}-cli'], cwd=unpack)
|
||||
path = unpack / 'squashfs-root' / 'usr' / 'bin' / f'{app}-cli'
|
||||
if not path.is_file() or not os.access(path, os.X_OK):
|
||||
raise RuntimeError(f'CLI is missing or not executable: {path}')
|
||||
status(f'Using {app}: {path.name}')
|
||||
return path
|
||||
|
||||
|
||||
def export(source, formats, destination, dpi, overwrite, cli_override):
|
||||
is_deck = source.suffix.lower() == '.pptx'
|
||||
if not is_deck and 'pdf' in formats:
|
||||
status(f'Already PDF; nothing to convert: {source}', 'success')
|
||||
formats = [format for format in formats if format != 'pdf']
|
||||
if not formats:
|
||||
return
|
||||
pdf_target = destination / f'{source.stem}.pdf'
|
||||
images_target = destination / 'images'
|
||||
targets = ([pdf_target] if 'pdf' in formats else []) + ([images_target] if 'images' in formats else [])
|
||||
for target in targets:
|
||||
if target.is_symlink():
|
||||
raise RuntimeError(f'Refusing to write through an output symlink: {target}')
|
||||
if target.exists() and not overwrite:
|
||||
raise RuntimeError(f'Output already exists: {target}. Use --overwrite to replace generated files.')
|
||||
if target.exists() and (target == images_target) != target.is_dir():
|
||||
raise RuntimeError(f'Output has the wrong file type: {target}')
|
||||
if target.resolve() == source:
|
||||
raise RuntimeError(f'Output would replace the input: {source}')
|
||||
app = 'deckcraft' if is_deck else 'pdfcraft'
|
||||
with tempfile.TemporaryDirectory(prefix='exporter-') as temp:
|
||||
work = Path(temp)
|
||||
cli = find_cli(app, cli_override, work)
|
||||
rendered = work / 'images'
|
||||
if 'pdf' in formats:
|
||||
status('Exporting presentation to PDF...')
|
||||
run([cli, 'convert', source, work / 'export.pdf'])
|
||||
if not (work / 'export.pdf').is_file() or not (work / 'export.pdf').stat().st_size:
|
||||
raise RuntimeError('DeckCraft did not create a PDF.')
|
||||
if 'images' in formats:
|
||||
rendered.mkdir()
|
||||
if is_deck:
|
||||
status(f'Rendering all slides as PNG ({dpi} DPI)...')
|
||||
run([cli, 'render', source, '--all', '--scale', str(dpi / 72), rendered])
|
||||
else:
|
||||
status('Reading PDF page count...')
|
||||
info = json.loads(run([cli, 'info', source]))
|
||||
pages = info.get('pages')
|
||||
if type(pages) is not int or pages < 1:
|
||||
raise RuntimeError('PdfCraft did not report a positive page count.')
|
||||
for page in range(1, pages + 1):
|
||||
status(f'[{page}/{pages}] Rendering page at {dpi} DPI...')
|
||||
run([cli, 'render', source, '--page', str(page), '--dpi', str(dpi),
|
||||
'--out', rendered / f'page-{page:04d}.png'])
|
||||
images = sorted(rendered.glob('*.png'))
|
||||
if not images or any(image.stat().st_size == 0 for image in images):
|
||||
raise RuntimeError(f'{app} did not produce valid image output.')
|
||||
if not is_deck and len(images) != pages:
|
||||
raise RuntimeError('PdfCraft did not produce every requested page.')
|
||||
status(f'Rendered {len(images)} image(s).', 'success')
|
||||
# Publish only after all requested conversions succeed.
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
if 'pdf' in formats:
|
||||
shutil.copy2(work / 'export.pdf', pdf_target)
|
||||
status(f'PDF: {pdf_target}', 'success')
|
||||
if 'images' in formats:
|
||||
images_target.mkdir(exist_ok=True)
|
||||
if overwrite:
|
||||
for old in images_target.iterdir():
|
||||
if re.fullmatch(r'(slide|page)-\d+\.png', old.name) and old.is_file():
|
||||
old.unlink()
|
||||
for image in images:
|
||||
target = images_target / image.name
|
||||
if target.is_symlink():
|
||||
raise RuntimeError(f'Refusing to write through an output symlink: {target}')
|
||||
shutil.copy2(image, target)
|
||||
status(f'Images: {images_target}', 'success')
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('file', type=Path, help='Source .pptx or .pdf')
|
||||
parser.add_argument('--output', required=True, type=output_formats, metavar='pdf,images',
|
||||
help='Comma-separated output formats: pdf, images')
|
||||
parser.add_argument('-d', '--output-dir', type=Path,
|
||||
help='Destination directory (default: <file-stem>_export)')
|
||||
parser.add_argument('--dpi', type=positive_int, default=144, help='PNG resolution (default: 144)')
|
||||
parser.add_argument('--overwrite', action='store_true', help='Replace existing generated output files')
|
||||
parser.add_argument('--deckcraft-cli', help='DeckCraft CLI executable or AppImage')
|
||||
parser.add_argument('--pdfcraft-cli', help='PdfCraft CLI executable or AppImage')
|
||||
args = parser.parse_args(argv)
|
||||
source = args.file.expanduser().resolve()
|
||||
if source.suffix.lower() not in ('.pptx', '.pdf'):
|
||||
parser.error(f'Unsupported input type: {source.suffix or "(no extension)"}. Expected .pptx or .pdf.')
|
||||
if not source.is_file():
|
||||
parser.error(f'Not a file: {source}')
|
||||
destination = (args.output_dir.expanduser() if args.output_dir else source.with_name(source.stem + '_export')).resolve()
|
||||
try:
|
||||
status(f'Source: {source}')
|
||||
export(source, args.output, destination, args.dpi, args.overwrite,
|
||||
args.deckcraft_cli if source.suffix.lower() == '.pptx' else args.pdfcraft_cli)
|
||||
status('Done.', 'success')
|
||||
return 0
|
||||
except (OSError, RuntimeError, ValueError) as error:
|
||||
status(str(error), 'error')
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
|
|
@ -0,0 +1,457 @@
|
|||
#!/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())
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
import contextlib
|
||||
import io
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import exporter
|
||||
|
||||
|
||||
class ExporterTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
|
||||
def invoke(self, *args):
|
||||
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
||||
return exporter.main(list(map(str, args)))
|
||||
|
||||
def test_pdf_noop_needs_no_tool_and_creates_nothing(self):
|
||||
source = self.root / 'input.PDF'
|
||||
source.write_bytes(b'%PDF-1.7')
|
||||
with patch.object(exporter, 'find_cli', side_effect=AssertionError('must not load a tool')):
|
||||
self.assertEqual(self.invoke(source, '--output', 'pdf'), 0)
|
||||
self.assertEqual(list(self.root.iterdir()), [source])
|
||||
|
||||
def test_rejects_unknown_input_and_output(self):
|
||||
for name, format in [('input.txt', 'pdf'), ('input.pdf', 'html'), ('input.pdf', 'pdf,')]:
|
||||
with self.subTest(name=name, format=format), self.assertRaises(SystemExit) as error:
|
||||
self.invoke(self.root / name, '--output', format)
|
||||
self.assertEqual(error.exception.code, 2)
|
||||
|
||||
def test_failure_does_not_publish_partial_output(self):
|
||||
source = self.root / 'input.pptx'
|
||||
source.touch()
|
||||
destination = self.root / 'output'
|
||||
|
||||
def fake_run(command, **kwargs):
|
||||
if command[1] == 'convert':
|
||||
Path(command[-1]).write_bytes(b'%PDF-1.7')
|
||||
return ''
|
||||
raise RuntimeError('render failed')
|
||||
|
||||
with patch.object(exporter, 'find_cli', return_value=Path('/fake/cli')), patch.object(exporter, 'run', side_effect=fake_run):
|
||||
self.assertEqual(self.invoke(source, '--output', 'pdf,images', '-d', destination), 1)
|
||||
self.assertFalse(destination.exists())
|
||||
|
||||
def test_overwrite_removes_stale_pages_but_preserves_other_files(self):
|
||||
source = self.root / 'input.pdf'
|
||||
source.touch()
|
||||
destination = self.root / 'output'
|
||||
images = destination / 'images'
|
||||
images.mkdir(parents=True)
|
||||
(images / 'page-0002.png').write_bytes(b'old')
|
||||
(images / 'notes.txt').write_text('keep me')
|
||||
|
||||
def fake_run(command, **kwargs):
|
||||
if command[1] == 'info':
|
||||
return '{"pages": 1}'
|
||||
Path(command[-1]).write_bytes(b'new image')
|
||||
return ''
|
||||
|
||||
with patch.object(exporter, 'find_cli', return_value=Path('/fake/cli')), patch.object(exporter, 'run', side_effect=fake_run):
|
||||
self.assertEqual(self.invoke(source, '--output', 'images', '-d', destination), 1)
|
||||
self.assertEqual(self.invoke(source, '--output', 'images', '-d', destination, '--overwrite'), 0)
|
||||
self.assertEqual((images / 'notes.txt').read_text(), 'keep me')
|
||||
self.assertFalse((images / 'page-0002.png').exists())
|
||||
self.assertEqual((images / 'page-0001.png').read_bytes(), b'new image')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Loading…
Reference in New Issue