#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Script pour convertir une carte HTML générée par Folium en image JPG. Utilise imgkit qui s'appuie sur wkhtmltoimage. """ import os import sys import argparse import logging import subprocess from pathlib import Path # Configuration de la journalisation logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) def convert_html_to_jpg(html_path, output_path=None, method='wkhtmltoimage'): """ Convertit un fichier HTML en image JPG. Args: html_path (str): Chemin vers le fichier HTML à convertir output_path (str, optional): Chemin où sauvegarder l'image JPG. Si None, utilise le même nom que le HTML. method (str): Méthode de conversion ('wkhtmltoimage', 'imgkit', 'cutycapt') Returns: str: Chemin vers l'image JPG générée ou None en cas d'erreur """ if not os.path.exists(html_path): logger.error(f"Le fichier HTML n'existe pas: {html_path}") return None # Définir le chemin de sortie si non spécifié if not output_path: output_path = os.path.splitext(html_path)[0] + '.jpg' try: if method == 'wkhtmltoimage': # Utiliser wkhtmltoimage (doit être installé sur le système) logger.info(f"Conversion avec wkhtmltoimage: {html_path} -> {output_path}") cmd = [ 'wkhtmltoimage', '--quality', '90', '--width', '1200', '--height', '800', '--javascript-delay', '2000', # Attendre 2 secondes pour le chargement JavaScript html_path, output_path ] process = subprocess.run(cmd, capture_output=True, text=True) if process.returncode != 0: logger.error(f"Erreur lors de la conversion: {process.stderr}") return None elif method == 'imgkit': # Utiliser imgkit (doit être installé via pip) try: import imgkit logger.info(f"Conversion avec imgkit: {html_path} -> {output_path}") options = { 'quality': 90, 'width': 1200, 'height': 800, 'javascript-delay': 2000 } imgkit.from_file(html_path, output_path, options=options) except ImportError: logger.error("imgkit n'est pas installé. Installez-le avec 'pip install imgkit'") return None elif method == 'cutycapt': # Utiliser cutycapt (doit être installé sur le système) logger.info(f"Conversion avec cutycapt: {html_path} -> {output_path}") cmd = [ 'cutycapt', '--url', f"file://{os.path.abspath(html_path)}", '--out', output_path, '--min-width', '1200', '--min-height', '800', '--delay', '2000' # Attendre 2 secondes ] process = subprocess.run(cmd, capture_output=True, text=True) if process.returncode != 0: logger.error(f"Erreur lors de la conversion: {process.stderr}") return None else: logger.error(f"Méthode de conversion non reconnue: {method}") return None # Vérifier si le fichier a été créé if os.path.exists(output_path): logger.info(f"Conversion réussie: {output_path}") return output_path else: logger.error("Le fichier de sortie n'a pas été créé") return None except Exception as e: logger.error(f"Erreur lors de la conversion: {str(e)}") # Proposer des solutions alternatives logger.info("Suggestions pour résoudre le problème:") logger.info("1. Installez wkhtmltopdf/wkhtmltoimage: https://wkhtmltopdf.org/downloads.html") logger.info("2. Installez imgkit: pip install imgkit") logger.info("3. Utilisez un navigateur pour ouvrir le fichier HTML et faites une capture d'écran manuellement") return None def main(): """ Fonction principale qui traite les arguments de ligne de commande et convertit le fichier HTML en JPG. """ parser = argparse.ArgumentParser(description='Convertit un fichier HTML en image JPG.') parser.add_argument('html_path', type=str, help='Chemin vers le fichier HTML à convertir') parser.add_argument('-o', '--output', type=str, help='Chemin où sauvegarder l\'image JPG') parser.add_argument('-m', '--method', type=str, choices=['wkhtmltoimage', 'imgkit', 'cutycapt'], default='wkhtmltoimage', help='Méthode de conversion à utiliser') parser.add_argument('-v', '--verbose', action='store_true', help='Afficher les messages de débogage') args = parser.parse_args() # Configurer le niveau de journalisation if args.verbose: logger.setLevel(logging.DEBUG) # Convertir le fichier HTML en JPG output_path = convert_html_to_jpg(args.html_path, args.output, args.method) if output_path: logger.info(f"Conversion réussie: {output_path}") else: logger.error("Échec de la conversion") sys.exit(1) if __name__ == "__main__": main()