Report and reuse selected export DPI
This commit is contained in:
parent
93c43c9026
commit
095e7c718b
|
|
@ -22,7 +22,9 @@ with quick-start examples and links to detailed documentation in `docs/`.
|
|||
and PdfCraft to render PDF pages as PNGs. It discovers CLI executables or
|
||||
locally installed AppImages. PDF-to-PDF is a successful no-op unless compression
|
||||
is requested. Ghostscript powers `--pdf-quality` and bounded `--target-size`
|
||||
attempts; an unmet target must not publish output or replace existing files.
|
||||
attempts; `--pdf-dpi` reuses an exact selected resolution. Report selected
|
||||
PDF and PNG resolutions in terminal output. An unmet target must not publish
|
||||
output or replace existing files.
|
||||
- `tests/test_exporter.py` covers exporter validation, no-op behavior, conversion
|
||||
failures, and overwrite behavior.
|
||||
- `tests/test_pptx_videos.py` covers slide discovery, extraction, temporary probing,
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ errors. Rendering completes in temporary storage before output is copied.
|
|||
```sh
|
||||
python3 tools/exporter.py presentation.pptx --output pdf --pdf-quality email
|
||||
python3 tools/exporter.py presentation.pptx --output pdf --target-size 5MB
|
||||
python3 tools/exporter.py presentation.pptx --output pdf --pdf-dpi 120
|
||||
python3 tools/exporter.py document.pdf --output pdf --pdf-quality email --target-size 5MB
|
||||
```
|
||||
|
||||
|
|
@ -64,6 +65,8 @@ These presets use Ghostscript's ebook compression settings with the indicated
|
|||
image resolution. They reduce image detail without deliberately rasterizing
|
||||
text and vector graphics. A quality preset alone does not guarantee a file size;
|
||||
the original is retained if it is smaller than the compressed result.
|
||||
Use `--pdf-dpi DPI` instead of a quality preset to select an exact PDF image
|
||||
resolution. `--dpi` remains specific to PNG exports.
|
||||
|
||||
`--target-size` accepts bytes or units such as `5MB`, `500KB`, and `2.5MiB`
|
||||
(`MB` = 1,000,000 bytes; `MiB` = 1,048,576 bytes). It starts at the selected
|
||||
|
|
@ -75,6 +78,12 @@ its resulting byte count. After the first completed pass, it estimates the
|
|||
remaining time from the average pass duration so far. A PDF already below the
|
||||
target is copied unchanged.
|
||||
|
||||
The final terminal message records the resolution actually selected. For
|
||||
example, `120 DPI images; reuse with --pdf-dpi 120` gives the exact option for
|
||||
the next export. If compression did not improve the file, it reports that the
|
||||
original/native image resolution was retained. PNG export messages similarly
|
||||
include their requested DPI.
|
||||
|
||||
Very small targets can noticeably degrade images, and some documents cannot
|
||||
reach the requested size. In that case the command fails, reports the smallest
|
||||
size achieved, and publishes no output; existing exports remain untouched.
|
||||
|
|
|
|||
|
|
@ -139,8 +139,9 @@ class ExporterTests(unittest.TestCase):
|
|||
with contextlib.redirect_stdout(io.StringIO()), \
|
||||
patch.object(exporter.shutil, 'which', return_value='/fake/gs'), \
|
||||
patch.object(exporter, 'run', side_effect=self.compressor([1500, 900], [])):
|
||||
result = exporter.compress_pdf(source, self.root, 'email', 1000, bar)
|
||||
result, selected_dpi = exporter.compress_pdf(source, self.root, 'email', 1000, bar)
|
||||
self.assertEqual(result.stat().st_size, 900)
|
||||
self.assertEqual(selected_dpi, 120)
|
||||
self.assertEqual(bar.set.call_args_list,
|
||||
[unittest.mock.call(0, 6), unittest.mock.call(1), unittest.mock.call(2)])
|
||||
|
||||
|
|
@ -168,6 +169,18 @@ class ExporterTests(unittest.TestCase):
|
|||
self.assertIn('-dColorImageResolution=150', commands[0])
|
||||
self.assertEqual((self.root / 'input_export/input.pdf').read_bytes(), source.read_bytes())
|
||||
|
||||
def test_exact_pdf_dpi_is_reusable_and_reported(self):
|
||||
source = self.root / 'input.pdf'
|
||||
source.write_bytes(b'x' * 1000)
|
||||
commands = []
|
||||
output = io.StringIO()
|
||||
with contextlib.redirect_stdout(output), contextlib.redirect_stderr(io.StringIO()), \
|
||||
patch.object(exporter.shutil, 'which', return_value='/fake/gs'), \
|
||||
patch.object(exporter, 'run', side_effect=self.compressor([500], commands)):
|
||||
self.assertEqual(exporter.main([str(source), '--output', 'pdf', '--pdf-dpi', '120']), 0)
|
||||
self.assertIn('-dColorImageResolution=120', commands[0])
|
||||
self.assertIn('120 DPI images; reuse with --pdf-dpi 120', output.getvalue())
|
||||
|
||||
def test_already_below_target_needs_no_compressor(self):
|
||||
source = self.root / 'input.pdf'
|
||||
source.write_bytes(b'pdf')
|
||||
|
|
@ -204,10 +217,14 @@ class ExporterTests(unittest.TestCase):
|
|||
self.assertEqual(exporter.byte_size('100'), 100)
|
||||
for args in [('--target-size', '0'), ('--target-size', '-2MB'),
|
||||
('--target-size', 'NaN'), ('--target-size', '5TB'),
|
||||
('--target-size', '2MB'), ('--pdf-quality', 'email')]:
|
||||
('--target-size', '2MB'), ('--pdf-quality', 'email'), ('--pdf-dpi', '120')]:
|
||||
with self.subTest(args=args), self.assertRaises(SystemExit) as error:
|
||||
self.invoke(self.root / 'input.pdf', '--output', 'images', *args)
|
||||
self.assertEqual(error.exception.code, 2)
|
||||
with self.assertRaises(SystemExit) as error:
|
||||
self.invoke(self.root / 'input.pdf', '--output', 'pdf',
|
||||
'--pdf-quality', 'email', '--pdf-dpi', '120')
|
||||
self.assertEqual(error.exception.code, 2)
|
||||
|
||||
def test_pptx_compresses_after_convert(self):
|
||||
source = self.root / 'input.pptx'
|
||||
|
|
|
|||
|
|
@ -53,22 +53,22 @@ def byte_size(value):
|
|||
return size
|
||||
|
||||
|
||||
def compress_pdf(source, work, quality, target_size, progress=None):
|
||||
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
|
||||
return source, None
|
||||
gs = shutil.which('gs')
|
||||
if not gs:
|
||||
raise RuntimeError('PDF compression requires Ghostscript (`gs`).\n' + GHOSTSCRIPT_INSTALL_HELP)
|
||||
first_dpi = {'original': 300, 'print': 300, 'email': 150, 'screen': 72}[quality]
|
||||
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 (150, 120, 96, 72, 50, 36) if dpi < first_dpi]
|
||||
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 = source, original_size
|
||||
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 '...'))
|
||||
|
|
@ -90,14 +90,16 @@ def compress_pdf(source, work, quality, target_size, progress=None):
|
|||
progress.set(attempt)
|
||||
status(f'Compression pass: {size:,} bytes (original {original_size:,}).')
|
||||
if size < best_size:
|
||||
best, best_size = candidate, 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. No output replaced. Try a larger target.')
|
||||
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
|
||||
return best, best_dpi
|
||||
|
||||
|
||||
def run(command, **kwargs):
|
||||
|
|
@ -149,9 +151,9 @@ def find_cli(app, override, work):
|
|||
|
||||
|
||||
def export(source, formats, destination, dpi, overwrite, cli_override, progress=None,
|
||||
pdf_quality='original', target_size=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
|
||||
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']
|
||||
|
|
@ -175,6 +177,7 @@ def export(source, formats, destination, dpi, overwrite, cli_override, progress=
|
|||
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'
|
||||
|
|
@ -183,7 +186,8 @@ def export(source, formats, destination, dpi, overwrite, cli_override, progress=
|
|||
if not pdf.is_file() or not pdf.stat().st_size:
|
||||
raise RuntimeError('DeckCraft did not create a PDF.')
|
||||
if compression:
|
||||
pdf = compress_pdf(pdf, work, pdf_quality, target_size, progress)
|
||||
pdf, selected_pdf_dpi = compress_pdf(
|
||||
pdf, work, pdf_quality, target_size, progress, pdf_dpi)
|
||||
if 'images' in formats:
|
||||
rendered.mkdir()
|
||||
if is_deck:
|
||||
|
|
@ -213,7 +217,9 @@ def export(source, formats, destination, dpi, overwrite, cli_override, progress=
|
|||
destination.mkdir(parents=True, exist_ok=True)
|
||||
if 'pdf' in formats:
|
||||
shutil.copy2(pdf, pdf_target)
|
||||
status(f'PDF: {pdf_target}', 'success', persist=True)
|
||||
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:
|
||||
|
|
@ -225,7 +231,7 @@ def export(source, formats, destination, dpi, overwrite, cli_override, progress=
|
|||
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', persist=True)
|
||||
status(f'Images: {images_target} — {dpi} DPI', 'success', persist=True)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
|
|
@ -238,9 +244,13 @@ def main(argv=None):
|
|||
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('--pdf-quality', choices=('original', 'print', 'email', 'screen'),
|
||||
default='original', help='PDF image quality: original (default), print (300 DPI), '
|
||||
'email (150 DPI), screen (72 DPI). Compression requires Ghostscript.')
|
||||
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.')
|
||||
|
|
@ -248,8 +258,9 @@ def main(argv=None):
|
|||
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.target_size is not None):
|
||||
parser.error('--pdf-quality and --target-size require --output pdf (or pdf,images).')
|
||||
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.')
|
||||
|
|
@ -261,7 +272,8 @@ def main(argv=None):
|
|||
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)
|
||||
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:
|
||||
|
|
|
|||
Loading…
Reference in New Issue