Guest User

Untitled

a guest
Dec 9th, 2024
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.84 KB | Source Code | 0 0
  1. import json
  2. import os
  3. import argparse
  4. from PIL import Image
  5. from multiprocessing import Pool, cpu_count
  6. from tqdm import tqdm  # For progress bar
  7.  
  8. def convert_single_image(args):
  9.     filename, input_dir, output_dir, quality, keep_metadata = args
  10.     try:
  11.         img_path = os.path.join(input_dir, filename)
  12.         img = Image.open(img_path)
  13.         output_filename = os.path.splitext(filename)[0] + '.webp'
  14.         output_path = os.path.join(output_dir, output_filename)
  15.  
  16.         # Handle duplicate filenames
  17.         if os.path.exists(output_path):
  18.             base_name = os.path.splitext(output_filename)[0]
  19.             counter = 1
  20.             while os.path.exists(output_path):
  21.                 output_filename = f"{base_name}_{counter}.webp"
  22.                 output_path = os.path.join(output_dir, output_filename)
  23.                 counter += 1
  24.  
  25.         if keep_metadata:
  26.             try:
  27.                 dict_of_info = img.info.copy()
  28.                 try:
  29.                     c = json.loads(dict_of_info.get("workflow"))
  30.                     nodes = c.get('nodes')
  31.                     for n in nodes:
  32.                         if n['type'] == 'LoraInfo':
  33.                             nodes.remove(n)
  34.                     dict_of_info['workflow'] = json.dumps(c)
  35.                 except Exception:
  36.                     pass
  37.  
  38.                 img_exif = img.getexif()
  39.                 user_comment = dict_of_info.get("workflow", "")
  40.                 img_exif[0x010e] = "Workflow:" + user_comment
  41.                 img.convert("RGB").save(output_path, lossless=False,
  42.                                      quality=quality, webp_method=6,
  43.                                      exif=img_exif)
  44.             except Exception as e:
  45.                 return (filename, False, str(e))
  46.         else:
  47.             img.save(output_path, 'webp', quality=quality)
  48.  
  49.         return (filename, True, output_filename)
  50.  
  51.     except Exception as e:
  52.         return (filename, False, str(e))
  53.  
  54. def convert_images_to_webp(input_dir, output_dir, quality=97, keep_metadata=True):
  55.     os.makedirs(output_dir, exist_ok=True)
  56.  
  57.     # Get all PNG files
  58.     png_files = [f for f in os.listdir(input_dir) if f.lower().endswith('.png')]
  59.     if not png_files:
  60.         print("No PNG files found in input directory")
  61.         return
  62.  
  63.     # Prepare arguments for parallel processing
  64.     args = [(f, input_dir, output_dir, quality, keep_metadata) for f in png_files]
  65.  
  66.     # Use all available cores except one
  67.     num_workers = max(1, cpu_count() - 4)
  68.  
  69.     print(f"Converting {len(png_files)} files using {num_workers} processes...")
  70.  
  71.     # Process files in parallel with progress bar
  72.     with Pool(num_workers) as pool:
  73.         results = list(tqdm(
  74.             pool.imap(convert_single_image, args),
  75.             total=len(png_files),
  76.             desc="Converting"
  77.         ))
  78.  
  79.     # Process results
  80.     success = [r for r in results if r[1]]
  81.     failures = [r for r in results if not r[1]]
  82.  
  83.     print(f"\nSuccessfully converted {len(success)} of {len(png_files)} files")
  84.     if failures:
  85.         print("\nFailed conversions:")
  86.         for f in failures:
  87.             print(f"  {f[0]}: {f[2]}")
  88.  
  89. if __name__ == '__main__':
  90.     parser = argparse.ArgumentParser(description='Convert PNG images to WebP format')
  91.     parser.add_argument('--quality', type=int, default=97, help='WebP quality (1-100)')
  92.     parser.add_argument('--no-metadata', action='store_true', help='Do not preserve ComfyUI workflow metadata')
  93.     parser.add_argument('--input-dir', default='.', help='Input directory (default: current directory)')
  94.     parser.add_argument('--output-dir', default='./converted', help='Output directory (default: ./converted)')
  95.  
  96.     args = parser.parse_args()
  97.  
  98.     convert_images_to_webp(
  99.         args.input_dir,
  100.         args.output_dir,
  101.         args.quality,
  102.         not args.no_metadata
  103.     )
  104.  
Tags: python
Advertisement
Add Comment
Please, Sign In to add comment