#!/usr/bin/env python3 """ Standalone PDF Export Script This script processes export requests from the gallery and creates merged PDFs. Usage: python export_plots.py [request_file.json] """ import sys import json import argparse from pathlib import Path from orchestration.pdf_export import PDFExporter, check_dependencies def main(): parser = argparse.ArgumentParser(description='Export gallery plots to merged PDF') parser.add_argument('request_file', nargs='?', default='export_request.json', help='JSON file containing export request') parser.add_argument('--output', '-o', help='Output PDF file path') parser.add_argument('--check-deps', action='store_true', help='Check available dependencies') args = parser.parse_args() if args.check_deps: deps = check_dependencies() print("Available dependencies:") for dep, available in deps.items(): status = "✓" if available else "✗" print(f" {status} {dep}") if not any(deps.values()): print("\nNo PDF merging tools available!") print("Install one of the following:") print(" - PyPDF2 and reportlab: pip install PyPDF2 reportlab") print(" - pdfjam: apt-get install texlive-extra-utils (on Ubuntu/Debian)") return request_file = Path(args.request_file) if not request_file.exists(): print(f"Error: Request file '{request_file}' not found") print("Create a JSON file with the following structure:") print(json.dumps({ "plots": ["/path/to/plot1.pdf", "/path/to/plot2.pdf"], "layout": {"rows": 1, "cols": 2}, "output_name": "merged_plots.pdf" }, indent=2)) return 1 try: with open(request_file, 'r') as f: request_data = json.load(f) except json.JSONDecodeError as e: print(f"Error: Invalid JSON in '{request_file}': {e}") return 1 # Validate request data if 'plots' not in request_data: print("Error: Missing 'plots' field in request") return 1 plot_paths = request_data['plots'] layout = request_data.get('layout', {'rows': 2, 'cols': 2}) output_name = args.output or request_data.get('output_name', 'merged_plots.pdf') # Validate plot files exist missing_files = [] for plot_path in plot_paths: if not Path(plot_path).exists(): missing_files.append(plot_path) if missing_files: print("Error: The following plot files were not found:") for missing in missing_files: print(f" - {missing}") return 1 print(f"Exporting {len(plot_paths)} plots to '{output_name}'...") print(f"Layout: {layout['rows']}x{layout['cols']}") # Create exporter and merge plots exporter = PDFExporter() try: pdf_bytes = exporter.merge_plots(plot_paths, layout, output_name) if not args.output and 'output_name' not in request_data: # Write to file if not already done by exporter with open(output_name, 'wb') as f: f.write(pdf_bytes) print(f"✓ Successfully created '{output_name}'") print(f" File size: {len(pdf_bytes) / 1024:.1f} KB") # Clean up request file if export was successful request_file.unlink(missing_ok=True) except Exception as e: print(f"Error during export: {e}") return 1 return 0 if __name__ == '__main__': sys.exit(main())