@@ -70,102 +70,87 @@ def execute(self, image, history_size):
7070 history_folder = DEFAULT_HISTORY_FOLDER
7171
7272 # Ensure target directory exists
73- if not os .path .exists (history_folder ): # Use the constant directly
73+ if not os .path .exists (history_folder ):
7474 try :
75- os .makedirs (history_folder , exist_ok = True ) # Use the constant directly
76- print (f"[PreviewHistory] Created history directory: { history_folder } " ) # Use the constant directly
75+ os .makedirs (history_folder , exist_ok = True )
76+ print (f"[PreviewHistory] Created history directory: { history_folder } " )
7777 except OSError as e :
78- print (f"[PreviewHistory] Error creating directory { history_folder } : { e } . Cannot proceed." ) # Use the constant directly
78+ print (f"[PreviewHistory] Error creating directory { history_folder } : { e } . Cannot proceed." )
7979 return {"ui" : {"images" : []}}
8080
81- # --- Update History Files (if new image provided) ---
81+ # --- Save New Image (if provided) ---
8282 if image is not None and image .nelement () > 0 :
8383 new_pil_image = tensor2pil (image )
84-
85- with PreviewHistory ._dir_lock :
84+ with PreviewHistory ._dir_lock : # Lock specifically for saving
8685 try :
87- # Save the new image using numerical month timestamp
88- # Format: history_DD-MM-YYYY_HH-MM-SS.png
8986 now = datetime .now ()
90- # Format parts: %d=DD, %m=MM(numeric), %Y=YYYY, %H=HH(24h), %M=MM, %S=SS
91- timestamp_final = now .strftime ("%d-%m-%Y_%H-%M-%S" ) # Use %m for month number
92-
87+ timestamp_final = now .strftime ("%d-%m-%Y_%H-%M-%S" )
9388 new_filename = f"history_{ timestamp_final } .png"
94- new_path = os .path .join (history_folder , new_filename ) # Use the constant indirectly via the variable
95- # print(f"[PreviewHistory] Saving new file: {new_path}") # Debug
89+ new_path = os .path .join (history_folder , new_filename )
9690 new_pil_image .save (new_path , "PNG" , compress_level = 1 )
97-
98- # Cleanup: Remove oldest files beyond history_size
99- # 1. Get all .png files with modification times
100- all_files = []
101- for filename in os .listdir (history_folder ): # Use the constant indirectly
102- if filename .lower ().endswith (".png" ):
103- full_path = os .path .join (history_folder , filename ) # Use the constant indirectly
104- try :
105- if os .path .isfile (full_path ): # Ensure it's a file
106- mod_time = os .path .getmtime (full_path )
107- all_files .append ((mod_time , full_path ))
108- except OSError :
109- print (f"[PreviewHistory] Warning: Could not access file { full_path } during cleanup scan." )
110- continue # Skip file if cannot get mod_time
111-
112- # 2. Sort by modification time, newest first
113- all_files .sort (key = lambda x : x [0 ], reverse = True )
114-
115- # 3. Remove files exceeding the history size
116- if len (all_files ) > history_size :
117- files_to_remove = all_files [history_size :] # Get the oldest ones
118- # print(f"[PreviewHistory] Found {len(all_files)} files, keeping {history_size}, removing {len(files_to_remove)}.") # Debug
119- for mod_time , path_to_remove in files_to_remove :
120- try :
121- # print(f"[PreviewHistory] Removing old file: {path_to_remove}") # Debug
122- os .remove (path_to_remove )
123- except OSError as e :
124- print (f"[PreviewHistory] Error removing old file { path_to_remove } : { e } " )
125-
91+ # print(f"[PreviewHistory] Saved new file: {new_path}") # Debug
12692 except Exception as e :
127- print (f"[PreviewHistory] Error updating history files in '{ history_folder } ': { e } " ) # Use the constant indirectly
128- # Attempt to continue to preview whatever state we're in
93+ print (f"[PreviewHistory] Error saving new image to '{ history_folder } ': { e } " )
94+ # Continue even if saving fails, try to show existing history
95+
12996
130- # --- Load Images for Preview ---
97+ # --- Cleanup Old Files & Load Images for Preview ---
13198 preview_images_pil = []
13299 sorted_history_files = []
133- with PreviewHistory ._dir_lock : # Use lock for consistency during listing
100+ with PreviewHistory ._dir_lock : # Lock for listing, cleanup, and getting paths
134101 try :
135- # Get all .png files with modification times again for loading
136- temp_files = []
137- for filename in os .listdir (history_folder ): # Use the constant indirectly
102+ # Get all .png files with modification times for cleanup and loading
103+ all_files = []
104+ for filename in os .listdir (history_folder ):
138105 if filename .lower ().endswith (".png" ):
139- full_path = os .path .join (history_folder , filename ) # Use the constant indirectly
106+ full_path = os .path .join (history_folder , filename )
140107 try :
141108 if os .path .isfile (full_path ):
142109 mod_time = os .path .getmtime (full_path )
143- temp_files .append ((mod_time , full_path ))
110+ all_files .append ((mod_time , full_path ))
144111 except OSError :
145- # Error getting mod time during load, might be transient, skip file
146- print ( f"[PreviewHistory] Warning: Could not access file { full_path } during load scan." )
147- continue
112+ print ( f"[PreviewHistory] Warning: Could not access file { full_path } during scan." )
113+ continue # Skip file if cannot get mod_time
114+
148115 # Sort by modification time, newest first
149- temp_files .sort (key = lambda x : x [0 ], reverse = True )
150- # Keep only the paths, up to history_size
151- sorted_history_files = [f [1 ] for f in temp_files [:history_size ]]
116+ all_files .sort (key = lambda x : x [0 ], reverse = True )
117+
118+ # Cleanup: Remove files exceeding the current history_size
119+ if len (all_files ) > history_size :
120+ files_to_remove = all_files [history_size :] # Get the oldest ones
121+ # print(f"[PreviewHistory] Found {len(all_files)} files, keeping {history_size}, removing {len(files_to_remove)}.") # Debug
122+ for mod_time , path_to_remove in files_to_remove :
123+ try :
124+ # print(f"[PreviewHistory] Removing old file: {path_to_remove}") # Debug
125+ os .remove (path_to_remove )
126+ except OSError as e :
127+ print (f"[PreviewHistory] Error removing old file { path_to_remove } : { e } " )
128+ # Keep only the files that were not removed
129+ files_to_keep = all_files [:history_size ]
130+ else :
131+ files_to_keep = all_files # Keep all if within limit
132+
133+ # Get the paths for the files we are keeping for the preview
134+ sorted_history_files = [f [1 ] for f in files_to_keep ]
135+
152136 except Exception as e :
153- print (f"[PreviewHistory] Error listing files in { history_folder } for preview: { e } " ) # Use the constant indirectly
154- # Fall through with empty list
137+ print (f"[PreviewHistory] Error listing/cleaning files in { history_folder } for preview: { e } " )
138+ # Fall through with empty list if error during file operations
139+
155140
156141 # Determine a consistent size for placeholders if needed
157142 placeholder_size = (128 , 128 ) # Default
158- if sorted_history_files : # Check if we found any files
143+ if sorted_history_files : # Check if we have any files paths left after potential cleanup
159144 try :
160145 # Try loading the first actual image (newest one)
161146 first_image_path = sorted_history_files [0 ]
162147 temp_img = Image .open (first_image_path )
163148 placeholder_size = temp_img .size
164149 temp_img .close ()
165150 except Exception :
166- pass # Ignore if it fails, keep default
151+ pass # Ignore if it fails, keep default size
167152
168- # Load images from the sorted list
153+ # Load images from the potentially cleaned-up list
169154 for i , fp in enumerate (sorted_history_files ): # Iterate through the paths we collected
170155 try :
171156 img = Image .open (fp ).convert ('RGB' )
0 commit comments