Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Image_Move_By_Height.py
- import tkinter as tk
- from tkinter import filedialog, messagebox
- from PIL import Image
- import os
- import shutil
- import re
- source_folder = None
- stop_flag = False
- n = 0
- max_images = 4999
- root = tk.Tk()
- root.title("Image Move By Height")
- root.geometry(f"{400}x{200}+10+10")
- def select_source():
- global source_folder, target_folder
- source_folder = filedialog.askdirectory()
- if source_folder:
- target_folder = source_folder + '/QuickLoad/'
- print(f"Target Folder: {source_folder}")
- def start_moving():
- global stop_flag, n
- if not source_folder:
- messagebox.showerror("Error", "Please Select A Source Folder First.")
- return
- stop_flag = False
- start_resume_button.config(text="Resume", state=tk.DISABLED)
- select_button.config(state=tk.DISABLED)
- move_images()
- def stop_process():
- global stop_flag
- stop_flag = True
- status_label.config(text="Process Stopped")
- start_resume_button.config(text="Resume")
- select_button.config(state=tk.NORMAL)
- def resume_moving():
- global stop_flag
- if stop_flag:
- stop_flag = False
- status_label.config(text="Resuming...")
- start_resume_button.config(state=tk.DISABLED)
- move_images()
- def count_jpg_files(directory):
- count = sum(1 for file in os.listdir(directory)
- if file.lower().endswith('.jpg'))
- return count
- def get_digits(minus=0):
- global new_folder_name
- update_n()
- new_folder_name = f"{str(n + minus).zfill(4)}"
- return target_folder + new_folder_name
- def new_folder():
- global new_folder_path
- new_folder_path = get_digits()
- print("Target:", new_folder_path)
- def update_n():
- global n
- for folder in os.listdir(target_folder):
- match = re.match(r'^\d{4}$', folder)
- if match:
- n = max(n, int(folder))
- n += 1
- def check_last():
- global new_folder_path
- # Get the last folder number (n - 1)
- new_folder_path = get_digits(-1)
- count = count_jpg_files(new_folder_path)
- # Debug: Find the folder with the largest number in QuickLoad
- max_folder_num = -1
- max_folder_path = None
- quickload_path = target_folder
- if os.path.exists(quickload_path):
- for folder in os.listdir(quickload_path):
- if re.match(r'^\d{4}$', folder):
- folder_num = int(folder)
- if folder_num > max_folder_num:
- max_folder_num = folder_num
- max_folder_path = os.path.join(quickload_path, folder)
- if max_folder_path:
- max_folder_count = count_jpg_files(max_folder_path)
- print(f"Debug: Largest numbered folder is '{max_folder_num}' at '{max_folder_path}'")
- print(f"Debug: Contains {max_folder_count} JPG images")
- # If the largest folder has more than max_images, prepare next folder
- if max_folder_count > max_images:
- count = 0 # Reset count since we're moving to a new folder
- new_folder()
- print(f"Debug: Last folder exceeds {max_images} images, moving to new folder: {new_folder_path}")
- # Test folder creation capability with a 'tmp' folder
- tmp_path = os.path.join(target_folder, "tmp")
- try:
- os.makedirs(tmp_path, exist_ok=True)
- print(f"Debug: Successfully created test folder 'tmp' at {tmp_path}")
- # Clean up tmp folder
- shutil.rmtree(tmp_path)
- print(f"Debug: Removed test folder 'tmp'")
- except OSError as e:
- print(f"Error: Cannot create folder in {target_folder}: {e}")
- status_label.config(text=f"Error: Cannot create folders in {target_folder}")
- return -1 # Indicate failure
- else:
- print(f"Debug: No numbered folders found in {quickload_path}")
- new_folder() # Create the first folder if none exist
- else:
- print(f"Debug: QuickLoad path {quickload_path} does not exist")
- new_folder() # Create the first folder
- return count
- def move_images():
- images = []
- count = check_last()
- print(count)
- for filename in os.listdir(source_folder):
- if filename.lower().endswith(('.jpg')):
- img_path = os.path.join(source_folder, filename)
- try:
- with Image.open(img_path) as img:
- images.append((filename, img.height, img_path))
- root.update()
- status_label.config(text=f"Reading Files ...{filename[-40:-4]}...")
- except:
- print(f"Could Not Read: {filename[-40:-4]}...")
- images.sort(key=lambda x: x[1], reverse=True) # Sort by height descending
- while 1:
- try:
- filename, _, img_path = images.pop(0)
- except:
- status_label.config(text=f"All Attempts Made")
- try:
- shutil.move(img_path, os.path.join(new_folder_path, filename))
- count += 1
- status_label.config(text=f"Moved {count} images")
- except shutil.Error as e:
- print(f"Error Moving {img_path} To {new_folder_path}: {e}")
- return
- print([count, max_images])
- if count > max_images:
- count = 0
- new_folder()
- if not os.path.exists(new_folder_path):
- try:
- os.makedirs(new_folder_path)
- print(f"Created folder: {new_folder_path}")
- except OSError as e:
- print(f"Error creating folder {new_folder_path}: {e}")
- status_label.config(text=f"Error: Could Not Create Folder {new_folder_name}")
- return
- root.update()
- if stop_flag:
- break
- start_resume_button.config(state=tk.NORMAL, text="Resume")
- select_button = tk.Button(root, text="Select Source Folder", command=select_source, anchor='w')
- select_button.pack(fill=tk.X, expand=True)
- start_resume_button = tk.Button(root, text="Start/Resume", command=start_moving, anchor='w')
- start_resume_button.pack(fill=tk.X, expand=True)
- stop_button = tk.Button(root, text="Stop", command=stop_process, anchor='w')
- stop_button.pack(fill=tk.X, expand=True)
- status_label = tk.Label(root, text="Status: Idle", anchor='w')
- status_label.pack(fill=tk.X, expand=True)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement