Advertisement
here2share

# Image_Move_By_Height.py

Feb 19th, 2025 (edited)
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.59 KB | None | 0 0
  1. # Image_Move_By_Height.py
  2.  
  3. import tkinter as tk
  4. from tkinter import filedialog, messagebox
  5. from PIL import Image
  6. import os
  7. import shutil
  8. import re
  9.  
  10. source_folder = None
  11. stop_flag = False
  12. n = 0
  13. max_images = 4999
  14.  
  15. root = tk.Tk()
  16. root.title("Image Move By Height")
  17. root.geometry(f"{400}x{200}+10+10")
  18.  
  19. def select_source():
  20.     global source_folder, target_folder
  21.     source_folder = filedialog.askdirectory()
  22.     if source_folder:
  23.         target_folder = source_folder + '/QuickLoad/'
  24.         print(f"Target Folder: {source_folder}")
  25.  
  26. def start_moving():
  27.     global stop_flag, n
  28.     if not source_folder:
  29.         messagebox.showerror("Error", "Please Select A Source Folder First.")
  30.         return
  31.  
  32.     stop_flag = False
  33.     start_resume_button.config(text="Resume", state=tk.DISABLED)
  34.     select_button.config(state=tk.DISABLED)
  35.     move_images()
  36.  
  37. def stop_process():
  38.     global stop_flag
  39.     stop_flag = True
  40.     status_label.config(text="Process Stopped")
  41.     start_resume_button.config(text="Resume")
  42.     select_button.config(state=tk.NORMAL)
  43.  
  44. def resume_moving():
  45.     global stop_flag
  46.     if stop_flag:
  47.         stop_flag = False
  48.         status_label.config(text="Resuming...")
  49.         start_resume_button.config(state=tk.DISABLED)
  50.         move_images()
  51.        
  52. def count_jpg_files(directory):
  53.     count = sum(1 for file in os.listdir(directory)
  54.                 if file.lower().endswith('.jpg'))
  55.     return count
  56.    
  57. def get_digits(minus=0):
  58.     global new_folder_name
  59.     update_n()
  60.     new_folder_name = f"{str(n + minus).zfill(4)}"
  61.     return target_folder + new_folder_name
  62.  
  63. def new_folder():
  64.     global new_folder_path
  65.     new_folder_path = get_digits()
  66.     print("Target:", new_folder_path)
  67.  
  68. def update_n():
  69.     global n
  70.     for folder in os.listdir(target_folder):
  71.         match = re.match(r'^\d{4}$', folder)
  72.         if match:
  73.             n = max(n, int(folder))
  74.     n += 1
  75.  
  76. def check_last():
  77.     global new_folder_path
  78.     # Get the last folder number (n - 1)
  79.     new_folder_path = get_digits(-1)
  80.     count = count_jpg_files(new_folder_path)
  81.  
  82.     # Debug: Find the folder with the largest number in QuickLoad
  83.     max_folder_num = -1
  84.     max_folder_path = None
  85.     quickload_path = target_folder
  86.  
  87.     if os.path.exists(quickload_path):
  88.         for folder in os.listdir(quickload_path):
  89.             if re.match(r'^\d{4}$', folder):
  90.                 folder_num = int(folder)
  91.                 if folder_num > max_folder_num:
  92.                     max_folder_num = folder_num
  93.                     max_folder_path = os.path.join(quickload_path, folder)
  94.        
  95.         if max_folder_path:
  96.             max_folder_count = count_jpg_files(max_folder_path)
  97.             print(f"Debug: Largest numbered folder is '{max_folder_num}' at '{max_folder_path}'")
  98.             print(f"Debug: Contains {max_folder_count} JPG images")
  99.            
  100.             # If the largest folder has more than max_images, prepare next folder
  101.             if max_folder_count > max_images:
  102.                 count = 0  # Reset count since we're moving to a new folder
  103.                 new_folder()
  104.                 print(f"Debug: Last folder exceeds {max_images} images, moving to new folder: {new_folder_path}")
  105.                
  106.         # Test folder creation capability with a 'tmp' folder
  107.         tmp_path = os.path.join(target_folder, "tmp")
  108.         try:
  109.             os.makedirs(tmp_path, exist_ok=True)
  110.             print(f"Debug: Successfully created test folder 'tmp' at {tmp_path}")
  111.             # Clean up tmp folder
  112.             shutil.rmtree(tmp_path)
  113.             print(f"Debug: Removed test folder 'tmp'")
  114.         except OSError as e:
  115.             print(f"Error: Cannot create folder in {target_folder}: {e}")
  116.             status_label.config(text=f"Error: Cannot create folders in {target_folder}")
  117.             return -1  # Indicate failure
  118.         else:
  119.             print(f"Debug: No numbered folders found in {quickload_path}")
  120.             new_folder()  # Create the first folder if none exist
  121.     else:
  122.         print(f"Debug: QuickLoad path {quickload_path} does not exist")
  123.         new_folder()  # Create the first folder
  124.  
  125.     return count
  126.  
  127. def move_images():
  128.     images = []
  129.     count = check_last()
  130.     print(count)
  131.    
  132.     for filename in os.listdir(source_folder):
  133.         if filename.lower().endswith(('.jpg')):
  134.             img_path = os.path.join(source_folder, filename)
  135.             try:
  136.                 with Image.open(img_path) as img:
  137.                     images.append((filename, img.height, img_path))
  138.                 root.update()
  139.                 status_label.config(text=f"Reading Files ...{filename[-40:-4]}...")
  140.             except:
  141.                 print(f"Could Not Read: {filename[-40:-4]}...")
  142.     images.sort(key=lambda x: x[1], reverse=True)  # Sort by height descending
  143.  
  144.     while 1:
  145.         try:
  146.             filename, _, img_path = images.pop(0)
  147.         except:
  148.             status_label.config(text=f"All Attempts Made")
  149.  
  150.         try:
  151.             shutil.move(img_path, os.path.join(new_folder_path, filename))
  152.             count += 1
  153.             status_label.config(text=f"Moved {count} images")
  154.         except shutil.Error as e:
  155.             print(f"Error Moving {img_path} To {new_folder_path}: {e}")
  156.             return
  157.            
  158.         print([count, max_images])
  159.                
  160.         if count > max_images:
  161.             count = 0
  162.             new_folder()
  163.             if not os.path.exists(new_folder_path):
  164.                 try:
  165.                     os.makedirs(new_folder_path)
  166.                     print(f"Created folder: {new_folder_path}")
  167.                 except OSError as e:
  168.                     print(f"Error creating folder {new_folder_path}: {e}")
  169.                     status_label.config(text=f"Error: Could Not Create Folder {new_folder_name}")
  170.                     return
  171.        
  172.         root.update()
  173.        
  174.         if stop_flag:
  175.             break
  176.    
  177.     start_resume_button.config(state=tk.NORMAL, text="Resume")
  178.  
  179. select_button = tk.Button(root, text="Select Source Folder", command=select_source, anchor='w')
  180. select_button.pack(fill=tk.X, expand=True)
  181.  
  182. start_resume_button = tk.Button(root, text="Start/Resume", command=start_moving, anchor='w')
  183. start_resume_button.pack(fill=tk.X, expand=True)
  184.  
  185. stop_button = tk.Button(root, text="Stop", command=stop_process, anchor='w')
  186. stop_button.pack(fill=tk.X, expand=True)
  187.  
  188. status_label = tk.Label(root, text="Status: Idle", anchor='w')
  189. status_label.pack(fill=tk.X, expand=True)
  190.  
  191. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement