예제 #1
0
def watch_for_new_files(t: Task):
    folder = os.path.abspath(t.src_path)
    print(
        f"\nPreparing to watch directory (press CTRL+C to quit):\n {folder}\n")

    event_handler = OptimizeImageEventHandler(t)
    observer = Observer()
    observer.schedule(event_handler, folder, recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\b \n\n  == Operation was interrupted by the user. ==\n")
        observer.stop()

    observer.join()

    if event_handler.new_files > 0:
        show_final_report(event_handler.new_files,
                          event_handler.optimized_files,
                          event_handler.total_src_size,
                          event_handler.total_bytes_saved, -1)
    else:
        print("No files were processed.\n")
예제 #2
0
def main():
    appstart = timer()
    line_width, our_pool_executor, workers = adjust_for_platform()
    (src_path, recursive, quality, remove_transparency, reduce_colors,
     max_colors, max_w, max_h, keep_exif, convert_all, conv_big, force_del,
     bg_color, grayscale, ignore_size_comparison, fast_mode) = get_args()
    found_files = 0
    optimized_files = 0
    total_src_size = 0
    total_bytes_saved = 0

    # Optimize all images in a directory
    if os.path.isdir(src_path):
        recursion_txt = 'Recursively searching' if recursive else 'Searching'
        opt_msg = 'and optimizing image files'
        exif_txt = '(keeping exif data) ' if keep_exif else ''
        print(f"\n{recursion_txt} {opt_msg} {exif_txt}in:\n{src_path}\n")

        tasks = (Task(img_path, quality, remove_transparency, reduce_colors,
                      max_colors, max_w, max_h, keep_exif, convert_all,
                      conv_big, force_del, bg_color, grayscale,
                      ignore_size_comparison, fast_mode)
                 for img_path in search_images(src_path, recursive=recursive))

        with our_pool_executor(max_workers=workers) as executor:
            for r in executor.map(do_optimization, tasks):
                found_files += 1
                total_src_size += r.orig_size
                if r.was_optimized:
                    optimized_files += 1
                    total_bytes_saved += r.orig_size - r.final_size
                show_file_status(r, line_width)

    # Optimize a single image
    elif os.path.isfile(src_path):
        found_files += 1

        img_task = Task(src_path, quality, remove_transparency, reduce_colors,
                        max_colors, max_w, max_h, keep_exif, convert_all,
                        conv_big, force_del, bg_color, grayscale,
                        ignore_size_comparison, fast_mode)

        r = do_optimization(img_task)
        total_src_size = r.orig_size
        if r.was_optimized:
            optimized_files = 1
            total_bytes_saved = r.orig_size - r.final_size
        show_file_status(r, line_width)
    else:
        print(
            "No image files were found. Please enter a valid path to the "
            "image file or the folder containing any images to be processed.")
        exit()

    if found_files:
        time_passed = timer() - appstart
        show_final_report(found_files, optimized_files, total_src_size,
                          total_bytes_saved, time_passed)
    else:
        print(
            "No supported image files were found in the specified directory.\n"
        )
예제 #3
0
def optimize_batch(src_path, watch_dir, recursive, quality, remove_transparency,
                   reduce_colors, max_colors, max_w, max_h, keep_exif, convert_all,
                   conv_big, force_del, bg_color, grayscale, ignore_size_comparison, 
                   fast_mode, jobs, output_config):
    appstart = timer()
    line_width, our_pool_executor, workers = adjust_for_platform()

    if jobs != 0:
        workers = jobs

    found_files = 0
    optimized_files = 0
    skipped_files = 0
    total_src_size = 0
    total_bytes_saved = 0

    if watch_dir:
        if not os.path.isdir(os.path.abspath(src_path)):
            msg = "\nPlease specify a valid path to an existing folder."
            raise OIInvalidPathError(msg)

        watch_task = Task(src_path, quality, remove_transparency, reduce_colors,
                          max_colors, max_w, max_h, keep_exif, convert_all,
                          conv_big, force_del, bg_color, grayscale,
                          ignore_size_comparison, fast_mode, output_config)

        from optimize_images.watch import watch_for_new_files
        watch_for_new_files(watch_task)
        return

    # Optimize all images in a directory
    elif os.path.isdir(src_path):

        if not output_config.quiet_mode:
            icons = IconGenerator()
            recursion_txt = 'Recursively searching' if recursive else 'Searching'
            opt_msg = 'and optimizing image files'
            exif_txt = '(keeping exif data) ' if keep_exif else ''
            print(f"\n{recursion_txt} {opt_msg} {exif_txt}in:\n{src_path}\n")

        tasks = (Task(img_path, quality, remove_transparency, reduce_colors,
                      max_colors, max_w, max_h, keep_exif, convert_all, conv_big,
                      force_del, bg_color, grayscale, ignore_size_comparison, fast_mode,
                      output_config)
                 for img_path in search_images(src_path, recursive=recursive))

        num_images, tasks = count_gen(tasks)
        with our_pool_executor(max_workers=workers) as executor:
            current_img = ''
            try:
                for result in executor.map(do_optimization, tasks):
                    current_img = result.img
                    found_files += 1
                    total_src_size += result.orig_size
                    if result.was_optimized:
                        optimized_files += 1
                        total_bytes_saved += result.orig_size - result.final_size
                    else:
                        skipped_files += 1

                    if result.output_config.quiet_mode:
                        continue

                    if result.output_config.show_overall_progress:
                        cur_time_passed = round(timer() - appstart)
                        perc_done = found_files / num_images * 100
                        message = f"[{cur_time_passed:.1f}s {perc_done:.1f}%] {icons.optimized} {optimized_files} {icons.skipped} {skipped_files}, saved {human(total_bytes_saved)}"
                        print(message, end='\r')
                    else:
                        show_file_status(result, line_width, icons)
                    
            except concurrent.futures.process.BrokenProcessPool as bppex:
                show_img_exception(bppex, current_img)
            except KeyboardInterrupt:
                msg = "\b \n\n  == Operation was interrupted by the user. ==\n"
                raise OIKeyboardInterrupt(msg)

    # Optimize a single image
    elif os.path.isfile(src_path) and '~temp~' not in src_path:
        found_files += 1

        img_task = Task(src_path, quality, remove_transparency, reduce_colors,
                        max_colors, max_w, max_h, keep_exif, convert_all, conv_big,
                        force_del, bg_color, grayscale, ignore_size_comparison, fast_mode, 
                        output_config)

        result = do_optimization(img_task)
        total_src_size = result.orig_size
        if result.was_optimized:
            optimized_files = 1
            total_bytes_saved = result.orig_size - result.final_size
        
        if not result.output_config.quiet_mode:
            icons = IconGenerator()
            show_file_status(result, line_width, icons)
    else:
        msg = "\nNo image files were found. Please enter a valid path to the " \
              "image file or the folder containing any images to be processed."
        raise OIImagesNotFoundError(msg)

    if found_files:
        time_passed = timer() - appstart
        show_final_report(found_files, optimized_files, total_src_size,
                          total_bytes_saved, time_passed, output_config)
    else:
        msg = "\nNo supported image files were found in the specified directory."
        raise OIImagesNotFoundError(msg)
예제 #4
0
def main():
    appstart = timer()
    line_width, our_pool_executor, workers = adjust_for_platform()

    (watch_dir, src_path, recursive, quality, remove_transparency,
     reduce_colors, max_colors, max_w, max_h, keep_exif, convert_all, conv_big,
     force_del, bg_color, grayscale, ignore_size_comparison, fast_mode, jobs) \
        = get_args()

    if jobs != 0:
        workers = jobs

    found_files = 0
    optimized_files = 0
    total_src_size = 0
    total_bytes_saved = 0

    if watch_dir:
        if not os.path.isdir(os.path.abspath(src_path)):
            print("\nPlease secify a valid path to an existing folder.")
            sys.exit(1)

        watch_task = Task(src_path, quality, remove_transparency,
                          reduce_colors, max_colors, max_w, max_h, keep_exif,
                          convert_all, conv_big, force_del, bg_color,
                          grayscale, ignore_size_comparison, fast_mode)

        watch_for_new_files(watch_task)
        sys.exit()

    # Optimize all images in a directory
    elif os.path.isdir(src_path):
        icons = IconGenerator()
        recursion_txt = 'Recursively searching' if recursive else 'Searching'
        opt_msg = 'and optimizing image files'
        exif_txt = '(keeping exif data) ' if keep_exif else ''
        print(f"\n{recursion_txt} {opt_msg} {exif_txt}in:\n{src_path}\n")

        tasks = (Task(img_path, quality, remove_transparency, reduce_colors,
                      max_colors, max_w, max_h, keep_exif, convert_all,
                      conv_big, force_del, bg_color, grayscale,
                      ignore_size_comparison, fast_mode)
                 for img_path in search_images(src_path, recursive=recursive))

        with our_pool_executor(max_workers=workers) as executor:
            current_img = ''
            try:
                for result in executor.map(do_optimization, tasks):
                    current_img = result.img
                    found_files += 1
                    total_src_size += result.orig_size
                    if result.was_optimized:
                        optimized_files += 1
                        total_bytes_saved += result.orig_size - result.final_size
                    show_file_status(result, line_width, icons)
            except concurrent.futures.process.BrokenProcessPool as bppex:
                show_img_exception(bppex, current_img)
            except KeyboardInterrupt:
                print(
                    "\b \n\n  == Operation was interrupted by the user. ==\n")

    # Optimize a single image
    elif os.path.isfile(src_path) and '~temp~' not in src_path:
        icons = IconGenerator()
        found_files += 1

        img_task = Task(src_path, quality, remove_transparency, reduce_colors,
                        max_colors, max_w, max_h, keep_exif, convert_all,
                        conv_big, force_del, bg_color, grayscale,
                        ignore_size_comparison, fast_mode)

        result = do_optimization(img_task)
        total_src_size = result.orig_size
        if result.was_optimized:
            optimized_files = 1
            total_bytes_saved = result.orig_size - result.final_size
        show_file_status(result, line_width, icons)
    else:
        print(
            "\nNo image files were found. Please enter a valid path to the "
            "image file or the folder containing any images to be processed.")
        sys.exit()

    if found_files:
        time_passed = timer() - appstart
        show_final_report(found_files, optimized_files, total_src_size,
                          total_bytes_saved, time_passed)
    else:
        print(
            "\nNo supported image files were found in the specified directory.\n"
        )