To speed up your Image Sequence Combiner application, you can implement multithreading to perform file copy operations in parallel. This can significantly reduce the total time taken, especially when dealing with a large number of image files. Additionally, running the copy operations in a separate thread will keep the GUI responsive, preventing it from freezing during the process.
Below is the optimized version of your code with the following improvements:
- Multithreading with
concurrent.futures.ThreadPoolExecutor: This allows multiple files to be copied simultaneously.
- Progress Updates Using Thread-Safe Queues: Ensures that the GUI updates the progress bar correctly without race conditions.
- Enhanced Error Handling: Collects errors during the copy process and displays them all at once after completion.
Optimized Code
import os
import shutil
import threading
import concurrent.futures
from queue import Queue
from tkinter import (
Tk,
Button,
Label,
filedialog,
messagebox,
StringVar,
)
from tkinter.ttk import Progressbar
class ImageCombinerGUI:
def __init__(self, root):
self.root = root
self.root.title("Image Sequence Combiner")
self.source_folders = []
self.destination_folder = ""
# Queue for thread-safe progress updates
self.progress_queue = Queue()
self.error_queue = Queue()
# Source Folders Selection
self.btn_select_sources = Button(
root, text="Select Source Folders", command=self.select_source_folders
)
self.btn_select_sources.pack(pady=5)
self.lbl_sources = Label(root, text="No source folders selected.")
self.lbl_sources.pack()
# Destination Folder Selection
self.btn_select_destination = Button(
root, text="Select Destination Folder", command=self.select_destination_folder
)
self.btn_select_destination.pack(pady=5)
self.lbl_destination = Label(root, text="No destination folder selected.")
self.lbl_destination.pack()
# Start Button
self.btn_start = Button(
root, text="Combine Images", command=self.start_combining, state='normal'
)
self.btn_start.pack(pady=20)
# Progress Bar
self.progress = Progressbar(root, orient="horizontal", length=400, mode="determinate")
self.progress.pack(pady=10)
# Periodically check the queue for progress updates
self.root.after(100, self.process_queue)
def select_source_folders(self):
while True:
folder = filedialog.askdirectory(mustexist=True, title="Select a Source Folder")
if folder:
if folder not in self.source_folders:
self.source_folders.append(folder)
self.lbl_sources.config(text=f"Selected {len(self.source_folders)} source folder(s).")
else:
messagebox.showinfo("Duplicate Folder", "This folder has already been selected.")
# Ask if the user wants to select another folder
another = messagebox.askyesno("Select Another", "Do you want to select another source folder?")
if not another:
break
else:
break
def select_destination_folder(self):
folder = filedialog.askdirectory(mustexist=True, title="Select Destination Folder")
if folder:
self.destination_folder = folder
self.lbl_destination.config(text=f"Destination: {self.destination_folder}")
def start_combining(self):
if not self.source_folders:
messagebox.showwarning("No Source Folders", "Please select source folders first.")
return
if not self.destination_folder:
messagebox.showwarning("No Destination Folder", "Please select a destination folder.")
return
# Disable the start button to prevent multiple clicks
self.btn_start.config(state='disabled')
# Start the combining process in a separate thread
threading.Thread(target=self.combine_images, daemon=True).start()
def combine_images(self):
total_files = 0
file_operations = []
# Gather all image files with their new prefixed names
for src_folder in self.source_folders:
main_prefix = os.path.basename(os.path.normpath(src_folder))
for subdir, _, files in os.walk(src_folder):
sub_prefix = os.path.basename(os.path.normpath(subdir))
for file in files:
if self.is_image_file(file):
total_files += 1
new_prefix = f"{main_prefix}_{sub_prefix}"
new_filename = f"{new_prefix}_{file}"
src_file = os.path.join(subdir, file)
dest_file = os.path.join(self.destination_folder, new_filename)
file_operations.append((src_file, dest_file))
if total_files == 0:
messagebox.showinfo("No Images Found", "No image files were found in the selected source folders.")
self.btn_start.config(state='normal')
return
# Initialize progress bar
self.progress["maximum"] = total_files
self.progress["value"] = 0
# Use ThreadPoolExecutor for parallel copying
max_workers = min(32, os.cpu_count() + 4) # Choose an optimal number of threads
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = []
for src, dest in file_operations:
futures.append(executor.submit(self.copy_file, src, dest))
for future in concurrent.futures.as_completed(futures):
# Check for exceptions
exception = future.exception()
if exception:
self.error_queue.put(str(exception))
# Update progress
self.progress_queue.put(1)
# After all files are processed
if not self.error_queue.empty():
errors = []
while not self.error_queue.empty():
errors.append(self.error_queue.get())
error_message = "\n".join(errors)
messagebox.showerror("Errors Occurred", f"Some files failed to copy:\n{error_message}")
else:
messagebox.showinfo("Success", f"Successfully combined {total_files} images into '{self.destination_folder}'.")
# Re-enable the start button
self.btn_start.config(state='normal')
def copy_file(self, src, dest):
try:
shutil.copy2(src, dest) # copy2 preserves metadata
except Exception as e:
return f"Failed to copy {src} to {dest}.\nError: {e}"
return None
def process_queue(self):
while not self.progress_queue.empty():
self.progress["value"] += self.progress_queue.get()
self.root.after(100, self.process_queue)
@staticmethod
def is_image_file(filename):
image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff', '.webp')
return filename.lower().endswith(image_extensions)
def main():
root = Tk()
app = ImageCombinerGUI(root)
root.geometry("450x300")
root.resizable(False, False)
root.mainloop()
if __name__ == "__main__":
main()
Key Improvements Explained
-
Multithreading with ThreadPoolExecutor:
- The
ThreadPoolExecutor from the concurrent.futures module allows multiple files to be copied in parallel.
- The number of worker threads is set optimally based on the CPU count (
min(32, os.cpu_count() + 4)), but you can adjust this based on your specific needs and system capabilities.
-
Running the Copy Process in a Separate Thread:
- The
combine_images method is executed in a separate daemon thread to ensure that the GUI remains responsive.
- This prevents the application from freezing while the copy operations are in progress.
-
Thread-Safe Progress Updates Using Queues:
progress_queue: Used to communicate progress updates from the worker threads to the main thread.
error_queue: Collects any errors that occur during the copying process.
- The
process_queue method periodically checks these queues and updates the progress bar accordingly.
-
Enhanced Error Handling:
- Instead of stopping the entire process on the first error, the application collects all errors and displays them after all copy operations are attempted.
- This ensures that one failed file doesn't prevent the copying of other files.
-
Disabling the Start Button During Operation:
- The "Combine Images" button is disabled while the copying process is running to prevent the user from initiating multiple simultaneous operations.
-
Optimized GUI Updates:
- Progress updates are batched and handled via queues, reducing the number of GUI updates and improving performance.
Additional Recommendations
-
Limit the Number of Threads: While multithreading can speed up IO-bound operations like file copying, creating too many threads can lead to diminishing returns or even slowdowns. The provided code sets an optimal number of threads based on the system's CPU count, but you can experiment with this number based on your specific use case and system performance.
-
Use Faster Storage: Ensure that both the source and destination drives are not bottlenecks. SSDs generally provide faster read/write speeds compared to HDDs.
-
Avoid Unnecessary Metadata Copying: If preserving file metadata isn't crucial for your application, consider using shutil.copyfile instead of shutil.copy2, as it may offer slight performance improvements.
# Replace shutil.copy2 with shutil.copyfile if metadata preservation is not needed
shutil.copyfile(src, dest)
- Feedback on Completion: You might also want to add a timestamp or log of the operation for record-keeping or debugging purposes.
By implementing these optimizations, your application should handle larger batches of image files more efficiently while maintaining a responsive user interface.