beffroi-tools/tools/exporter.py

286 lines
14 KiB
Python

#!/usr/bin/env python3
"""Export PPTX to PDF/PNG with DeckCraft, or PDF to PNG with PdfCraft."""
import argparse
from decimal import Decimal
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
if __package__:
from .progress import Progress, status
else:
from progress import Progress, status
GHOSTSCRIPT_INSTALL_HELP = '''Ghostscript is installed as the `ghostscript` package; its command is `gs`:
Debian / Ubuntu: sudo apt install ghostscript
Fedora / RHEL: sudo dnf install ghostscript
Arch Linux: sudo pacman -S ghostscript
openSUSE: sudo zypper install ghostscript
Alpine Linux: sudo apk add ghostscript
macOS (Homebrew): brew install ghostscript'''
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 byte_size(value):
match = re.fullmatch(r'\s*(\d+(?:\.\d+)?)\s*(B|KB|MB|GB|KiB|MiB|GiB)?\s*', value, re.I)
if not match:
raise argparse.ArgumentTypeError('Use a positive size such as 5MB or 2.5MiB.')
unit = (match[2] or 'B').upper()
scale = {'B': 1, 'KB': 1000, 'MB': 1000**2, 'GB': 1000**3,
'KIB': 1024, 'MIB': 1024**2, 'GIB': 1024**3}[unit]
size = int(Decimal(match[1]) * scale)
if size < 1:
raise argparse.ArgumentTypeError('Target size must be at least one byte.')
return size
def compress_pdf(source, work, quality, target_size, progress=None, requested_dpi=None):
"""Try bounded downsampling passes, always using the original PDF."""
original_size = source.stat().st_size
if target_size and original_size < target_size:
status(f'PDF already under target: {original_size:,} bytes.', 'success')
return source, None
gs = shutil.which('gs')
if not gs:
raise RuntimeError('PDF compression requires Ghostscript (`gs`).\n' + GHOSTSCRIPT_INSTALL_HELP)
first_dpi = requested_dpi or {'original': 300, 'print': 300, 'email': 150, 'screen': 72}[quality]
resolutions = [first_dpi]
if target_size:
resolutions += [dpi for dpi in (300, 150, 120, 96, 72, 50, 36) if dpi < first_dpi]
if progress:
progress.set(0, len(resolutions))
best, best_size, best_dpi = source, original_size, None
for attempt, dpi in enumerate(resolutions, 1):
status(f'Compressing PDF [{attempt}/{len(resolutions)}]: {dpi} DPI images'
+ (f', target < {target_size:,} bytes...' if target_size else '...'))
candidate = work / f'compressed-{attempt}.pdf'
command = [gs, '-sDEVICE=pdfwrite', '-dSAFER', '-dBATCH', '-dNOPAUSE',
'-dPDFSETTINGS=/ebook', '-dAutoRotatePages=/None',
'-dEmbedAllFonts=true', '-dSubsetFonts=true',
'-dPassThroughJPEGImages=false', '-dPassThroughJPXImages=false',
f'-sOutputFile={candidate}']
for kind in ('Color', 'Gray', 'Mono'):
command += [f'-dDownsample{kind}Images=true',
f'-d{kind}ImageResolution={dpi}',
f'-d{kind}ImageDownsampleThreshold=1.0']
run([*command, '-f', source])
if not candidate.is_file() or not candidate.stat().st_size:
raise RuntimeError('Ghostscript did not create a PDF.')
size = candidate.stat().st_size
if progress:
progress.set(attempt)
status(f'Compression pass: {size:,} bytes (original {original_size:,}).')
if size < best_size:
best, best_size, best_dpi = candidate, size, dpi
if target_size and best_size < target_size:
break
if target_size and best_size >= target_size:
raise RuntimeError(f'Could not reach target < {target_size:,} bytes; smallest result '
f'was {best_size:,} bytes'
+ (f' at {best_dpi} DPI' if best_dpi else ' without downsampling')
+ '. No output replaced. Try a larger target.')
status(f'PDF size: {original_size:,} → {best_size:,} bytes.', 'success', persist=True)
return best, best_dpi
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, progress=None,
pdf_quality='original', target_size=None, pdf_dpi=None):
is_deck = source.suffix.lower() == '.pptx'
compression = pdf_quality != 'original' or target_size is not None or pdf_dpi is not None
if not is_deck and 'pdf' in formats and not compression:
status(f'Already PDF; nothing to convert: {source}', 'success', persist=True)
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) if is_deck or 'images' in formats else None
rendered = work / 'images'
pdf = source
selected_pdf_dpi = None
if 'pdf' in formats:
if is_deck:
pdf = work / 'export.pdf'
status('Exporting presentation to PDF...')
run([cli, 'convert', source, pdf])
if not pdf.is_file() or not pdf.stat().st_size:
raise RuntimeError('DeckCraft did not create a PDF.')
if compression:
pdf, selected_pdf_dpi = compress_pdf(
pdf, work, pdf_quality, target_size, progress, pdf_dpi)
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.')
if progress:
progress.set(0, pages)
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'])
if progress:
progress.set(page)
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(pdf, pdf_target)
detail = (f'{selected_pdf_dpi} DPI images; reuse with --pdf-dpi {selected_pdf_dpi}'
if selected_pdf_dpi else 'original/native image resolution')
status(f'PDF: {pdf_target} — {detail}', 'success', persist=True)
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} — {dpi} DPI', 'success', persist=True)
def main(argv=None):
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='PDF compression dependency:\n' + GHOSTSCRIPT_INSTALL_HELP)
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)')
pdf_resolution = parser.add_mutually_exclusive_group()
pdf_resolution.add_argument('--pdf-quality', choices=('original', 'print', 'email', 'screen'),
default='original', help='PDF image quality: original (default), print '
'(300 DPI), email (150 DPI), screen (72 DPI). Requires Ghostscript.')
pdf_resolution.add_argument('--pdf-dpi', type=positive_int, metavar='DPI',
help='Exact PDF image resolution. Useful for reusing the result of '
'--target-size; requires Ghostscript.')
parser.add_argument('--target-size', type=byte_size, metavar='SIZE',
help='Try progressively stronger PDF compression to get below e.g. 5MB. '
'Fails without publishing if the target cannot be reached.')
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)
if 'pdf' not in args.output and (args.pdf_quality != 'original' or args.pdf_dpi is not None
or args.target_size is not None):
parser.error('--pdf-quality, --pdf-dpi, and --target-size require --output pdf (or pdf,images).')
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:
with Progress() as progress:
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,
progress=progress, pdf_quality=args.pdf_quality, target_size=args.target_size,
pdf_dpi=args.pdf_dpi)
status('Done.', 'success', persist=True)
return 0
except (OSError, RuntimeError, ValueError) as error:
status(str(error), 'error')
return 1
if __name__ == '__main__':
sys.exit(main())