Update image_error_fix.py
Browse files- image_error_fix.py +348 -348
image_error_fix.py
CHANGED
@@ -1,348 +1,348 @@
|
|
1 |
-
import tkinter as tk
|
2 |
-
from tkinter import filedialog, ttk, messagebox
|
3 |
-
import os
|
4 |
-
import threading, queue
|
5 |
-
from PIL import Image, UnidentifiedImageError
|
6 |
-
|
7 |
-
# Global variables for managing state and errors
|
8 |
-
stop_processing = False
|
9 |
-
error_messages = []
|
10 |
-
selected_files = []
|
11 |
-
error_list = []
|
12 |
-
|
13 |
-
def open_image_error_fix():
|
14 |
-
global stop_processing, error_messages, selected_files, status_var, num_files_var, errors_var, progress, q, error_list, error_window, thread_count_var
|
15 |
-
|
16 |
-
# Initialize the main Tkinter window
|
17 |
-
root = tk.Tk()
|
18 |
-
root.title("Image Error Fix")
|
19 |
-
|
20 |
-
# Initialize Tkinter variables
|
21 |
-
status_var = tk.StringVar()
|
22 |
-
num_files_var = tk.StringVar()
|
23 |
-
errors_var = tk.StringVar(value="Errors: 0")
|
24 |
-
progress = tk.IntVar()
|
25 |
-
thread_count_var = tk.StringVar(value="
|
26 |
-
q = queue.Queue()
|
27 |
-
|
28 |
-
def center_window(window):
|
29 |
-
window.update_idletasks()
|
30 |
-
width = window.winfo_width() + 120
|
31 |
-
height = window.winfo_height()
|
32 |
-
x = (window.winfo_screenwidth() // 2) - (width // 2)
|
33 |
-
y = (window.winfo_screenheight() // 2) - (height // 2)
|
34 |
-
window.geometry(f'{width}x{height}+{x}+{y}')
|
35 |
-
|
36 |
-
def validate_number(P):
|
37 |
-
return P.isdigit() or P == ""
|
38 |
-
|
39 |
-
def validate_thread_count(var):
|
40 |
-
value = var.get()
|
41 |
-
if value != "":
|
42 |
-
try:
|
43 |
-
int_value = int(value)
|
44 |
-
if int_value <= 0:
|
45 |
-
raise ValueError
|
46 |
-
except ValueError:
|
47 |
-
messagebox.showerror("Invalid Input", "Please enter a valid number of threads.")
|
48 |
-
var.set("")
|
49 |
-
|
50 |
-
def select_files():
|
51 |
-
global selected_files
|
52 |
-
filetypes = [
|
53 |
-
("All Image files", "*.jpg;*.jpeg;*.png;*.gif;*.bmp;*.tiff;*.tif;*.svg;*.webp"),
|
54 |
-
("JPEG files", "*.jpg;*.jpeg"),
|
55 |
-
("PNG files", "*.png"),
|
56 |
-
("GIF files", "*.gif"),
|
57 |
-
("BMP files", "*.bmp"),
|
58 |
-
("TIFF files", "*.tiff;*.tif"),
|
59 |
-
("SVG files", "*.svg"),
|
60 |
-
("WEBP files", "*.webp")
|
61 |
-
]
|
62 |
-
filepaths = filedialog.askopenfilenames(title="Select Image Files", filetypes=filetypes)
|
63 |
-
if filepaths:
|
64 |
-
selected_files.clear()
|
65 |
-
selected_files.extend(filepaths)
|
66 |
-
num_files_var.set(f"{len(selected_files)} files selected.")
|
67 |
-
|
68 |
-
def detect_errors(file_path):
|
69 |
-
"""Detect potential errors in an image file."""
|
70 |
-
errors = []
|
71 |
-
if not os.access(file_path, os.R_OK):
|
72 |
-
errors.append("Permission Denied")
|
73 |
-
# Additional error checks
|
74 |
-
try:
|
75 |
-
with Image.open(file_path) as img:
|
76 |
-
img.verify() # Verify the image integrity
|
77 |
-
img = Image.open(file_path)
|
78 |
-
img.load() # Load the image data to ensure it's not truncated
|
79 |
-
except UnidentifiedImageError:
|
80 |
-
errors.append("Unidentified image format or corrupted file")
|
81 |
-
except IOError as e:
|
82 |
-
errors.append(f"IOError: {str(e)}")
|
83 |
-
except Exception as e:
|
84 |
-
errors.append(f"Unknown error: {str(e)}")
|
85 |
-
return errors
|
86 |
-
|
87 |
-
def fix_error(file_path, error_type):
|
88 |
-
"""Fix errors in an image file, if possible."""
|
89 |
-
if error_type == "Permission Denied":
|
90 |
-
# Attempt to change permissions
|
91 |
-
try:
|
92 |
-
os.chmod(file_path, 0o644)
|
93 |
-
return "Permissions fixed. File permissions were successfully updated."
|
94 |
-
except Exception as e:
|
95 |
-
return f"Failed to fix permissions. Ensure you have the necessary permissions to modify this file. Error: {str(e)}"
|
96 |
-
elif error_type == "Unidentified image format or corrupted file":
|
97 |
-
return "The file format is unrecognized or the file is corrupted. Please try to re-download or restore from a backup."
|
98 |
-
elif error_type == "Invalid Format":
|
99 |
-
return ("Cannot automatically fix invalid formats. Ensure the file extension matches the file content.\n"
|
100 |
-
"To fix this issue, please follow these steps:\n"
|
101 |
-
"1. Identify the correct file format by using a file type checker tool (e.g., CheckFileType.com).\n"
|
102 |
-
"2. Rename the file with the correct extension:\n"
|
103 |
-
" - Right-click on the file and select 'Rename'.\n"
|
104 |
-
" - Change the file extension to the correct format (e.g., .jpg, .png).\n"
|
105 |
-
" - Press Enter to save the changes.\n"
|
106 |
-
"3. Try opening the file again. If the problem persists, the file may be corrupted or contain unsupported data.")
|
107 |
-
elif error_type == "File Not Found":
|
108 |
-
return ("The file could not be found at the specified path. Please ensure that the file has not been moved or deleted.\n"
|
109 |
-
"1. Verify the file path is correct.\n"
|
110 |
-
"2. If the file has been moved, update the path in the application or locate the file manually.\n"
|
111 |
-
"3. If the file was deleted, check your Recycle Bin or use a data recovery tool to attempt to restore it.")
|
112 |
-
elif error_type == "File Path Too Long":
|
113 |
-
return ("The file path exceeds the system limit. Windows has a maximum path length of 260 characters.\n"
|
114 |
-
"To fix this issue:\n"
|
115 |
-
"1. Move the file to a location with a shorter path, closer to the root directory (e.g., C:\\).\n"
|
116 |
-
"2. Rename folders in the path to shorter names.\n"
|
117 |
-
"3. Enable long path support in Windows if using Windows 10 (version 1607 hoặc cao hơn):\n"
|
118 |
-
" - Open the Group Policy Editor (gpedit.msc).\n"
|
119 |
-
" - Navigate to 'Local Computer Policy > Computer Configuration > Administrative Templates > System > Filesystem'.\n"
|
120 |
-
" - Enable the 'Enable Win32 long paths' option.")
|
121 |
-
elif error_type == "Transmission Errors":
|
122 |
-
return ("The file may be incomplete or corrupted due to transmission errors. This can happen if the file was downloaded or transferred incorrectly.\n"
|
123 |
-
"To fix this issue:\n"
|
124 |
-
"1. Re-download hoặc re-transfer the file.\n"
|
125 |
-
"2. Use a reliable network connection to ensure the file is not corrupted during transfer.\n"
|
126 |
-
"3. Verify the integrity of the file by comparing checksums (if available).")
|
127 |
-
elif error_type == "Unsupported Format":
|
128 |
-
return ("The file format is not supported by this application. Supported formats include JPEG, PNG, GIF, BMP, TIFF, SVG, và WEBP.\n"
|
129 |
-
"To fix this issue:\n"
|
130 |
-
"1. Convert the file to a supported format using an image converter tool.\n"
|
131 |
-
"2. Ensure that the file is not corrupted and can be opened with other image viewers or editors.")
|
132 |
-
else:
|
133 |
-
return "No action taken. This error type is not recognized or cannot be fixed automatically."
|
134 |
-
|
135 |
-
def delete_file(file_path):
|
136 |
-
"""Delete the specified file."""
|
137 |
-
try:
|
138 |
-
os.remove(file_path)
|
139 |
-
# Remove from selected files
|
140 |
-
selected_files.remove(file_path)
|
141 |
-
num_files_var.set(f"{len(selected_files)} files selected.")
|
142 |
-
return f"File {file_path} deleted successfully."
|
143 |
-
except Exception as e:
|
144 |
-
return f"Failed to delete file {file_path}. Error: {str(e)}"
|
145 |
-
|
146 |
-
def process_image(file_path, q):
|
147 |
-
if stop_processing:
|
148 |
-
return
|
149 |
-
|
150 |
-
errors = detect_errors(file_path)
|
151 |
-
if errors:
|
152 |
-
q.put((file_path, errors))
|
153 |
-
|
154 |
-
def worker():
|
155 |
-
try:
|
156 |
-
progress.set(0)
|
157 |
-
total_files = len(selected_files)
|
158 |
-
thread_count = int(thread_count_var.get()) # Get the number of threads
|
159 |
-
for i, input_path in enumerate(selected_files, 1):
|
160 |
-
if stop_processing:
|
161 |
-
break
|
162 |
-
|
163 |
-
thread = threading.Thread(target=process_image, args=(input_path, q))
|
164 |
-
thread.start()
|
165 |
-
thread.join()
|
166 |
-
|
167 |
-
# Update progress bar
|
168 |
-
progress.set(int(i / total_files * 100))
|
169 |
-
|
170 |
-
q.put(None)
|
171 |
-
except Exception as e:
|
172 |
-
if not stop_processing:
|
173 |
-
q.put(e)
|
174 |
-
|
175 |
-
def update_progress():
|
176 |
-
try:
|
177 |
-
global error_list
|
178 |
-
error_list = []
|
179 |
-
while True:
|
180 |
-
item = q.get()
|
181 |
-
if item is None:
|
182 |
-
break
|
183 |
-
if isinstance(item, tuple):
|
184 |
-
error_list.append(item)
|
185 |
-
|
186 |
-
if not error_list:
|
187 |
-
messagebox.showinfo("No Errors Found", "No errors were detected in the selected images.")
|
188 |
-
else:
|
189 |
-
errors_var.set(f"Errors: {len(error_list)}")
|
190 |
-
display_errors(error_list)
|
191 |
-
except Exception as e:
|
192 |
-
if not stop_processing:
|
193 |
-
root.after(0, status_var.set, f"Error: {e}")
|
194 |
-
|
195 |
-
def update_error_display():
|
196 |
-
"""Update the display of errors in the error window."""
|
197 |
-
global error_list, frame
|
198 |
-
# Clear all existing widgets in the frame
|
199 |
-
for widget in frame.winfo_children():
|
200 |
-
widget.destroy()
|
201 |
-
|
202 |
-
# Repopulate the frame with updated error list
|
203 |
-
for file_path, errors in error_list:
|
204 |
-
for error in errors:
|
205 |
-
frame_row = tk.Frame(frame)
|
206 |
-
frame_row.pack(fill="x", pady=2)
|
207 |
-
|
208 |
-
# Hiển thị đường dẫn đầy đủ và tự động xuống dòng
|
209 |
-
file_label = tk.Label(frame_row, text=f"{file_path}: {error}", anchor="w", wraplength=500, justify='left')
|
210 |
-
file_label.pack(side=tk.LEFT, fill="x", expand=True)
|
211 |
-
|
212 |
-
delete_button = tk.Button(frame_row, text="Delete", command=lambda fp=file_path: delete_file_action(fp))
|
213 |
-
delete_button.pack(side=tk.RIGHT)
|
214 |
-
|
215 |
-
fix_button = tk.Button(frame_row, text="Fix", command=lambda fp=file_path, et=error: fix_error_action(fp, et))
|
216 |
-
fix_button.pack(side=tk.RIGHT)
|
217 |
-
|
218 |
-
# Thêm dấu phân cách giữa các lỗi
|
219 |
-
separator = ttk.Separator(frame, orient='horizontal')
|
220 |
-
separator.pack(fill='x', pady=5)
|
221 |
-
|
222 |
-
frame.update_idletasks()
|
223 |
-
canvas.configure(scrollregion=canvas.bbox("all"))
|
224 |
-
|
225 |
-
def display_errors(error_list):
|
226 |
-
global error_window, canvas, frame
|
227 |
-
# Create or raise the error window
|
228 |
-
if 'error_window' in globals() and error_window.winfo_exists():
|
229 |
-
error_window.lift()
|
230 |
-
else:
|
231 |
-
error_window = tk.Toplevel(root)
|
232 |
-
error_window.title("Error Details")
|
233 |
-
error_window.geometry("600x400")
|
234 |
-
|
235 |
-
canvas = tk.Canvas(error_window)
|
236 |
-
canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
|
237 |
-
|
238 |
-
scrollbar = tk.Scrollbar(error_window, command=canvas.yview)
|
239 |
-
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
|
240 |
-
|
241 |
-
canvas.configure(yscrollcommand=scrollbar.set)
|
242 |
-
|
243 |
-
frame = tk.Frame(canvas)
|
244 |
-
canvas.create_window((0, 0), window=frame, anchor="nw")
|
245 |
-
|
246 |
-
update_error_display()
|
247 |
-
|
248 |
-
def fix_error_action(file_path, error_type):
|
249 |
-
fix_message = fix_error(file_path, error_type)
|
250 |
-
messagebox.showinfo("Fix Error", fix_message)
|
251 |
-
|
252 |
-
def delete_file_action(file_path):
|
253 |
-
global error_list
|
254 |
-
delete_message = delete_file(file_path)
|
255 |
-
messagebox.showinfo("Delete File", delete_message)
|
256 |
-
# Remove the error from the error_list and refresh the display
|
257 |
-
error_list = [(fp, errs) for fp, errs in error_list if fp != file_path]
|
258 |
-
errors_var.set(f"Errors: {len(error_list)}")
|
259 |
-
update_error_display()
|
260 |
-
|
261 |
-
def delete_all_errors():
|
262 |
-
global error_list
|
263 |
-
for file_path, _ in error_list:
|
264 |
-
delete_file(file_path)
|
265 |
-
error_list.clear()
|
266 |
-
errors_var.set("Errors: 0")
|
267 |
-
messagebox.showinfo("Delete All Files", "All files with errors have been deleted.")
|
268 |
-
update_error_display() # Update the error display after deleting all errors
|
269 |
-
|
270 |
-
def scan_and_fix():
|
271 |
-
global stop_processing, error_messages
|
272 |
-
stop_processing = False
|
273 |
-
error_messages.clear()
|
274 |
-
errors_var.set("Errors: 0")
|
275 |
-
if not selected_files:
|
276 |
-
status_var.set("Please select images to scan.")
|
277 |
-
return
|
278 |
-
|
279 |
-
threading.Thread(target=worker).start()
|
280 |
-
threading.Thread(target=update_progress).start()
|
281 |
-
|
282 |
-
def stop_processing_func():
|
283 |
-
global stop_processing
|
284 |
-
stop_processing = True
|
285 |
-
status_var.set("Processing stopped.")
|
286 |
-
|
287 |
-
def return_to_menu():
|
288 |
-
stop_processing_func()
|
289 |
-
root.destroy()
|
290 |
-
import main
|
291 |
-
main.open_main_menu()
|
292 |
-
|
293 |
-
def on_closing():
|
294 |
-
return_to_menu()
|
295 |
-
|
296 |
-
# Create GUI elements
|
297 |
-
validate_command = root.register(validate_number)
|
298 |
-
|
299 |
-
back_button = tk.Button(root, text="<-", font=('Helvetica', 14), command=return_to_menu)
|
300 |
-
back_button.pack(anchor='nw', padx=10, pady=10)
|
301 |
-
|
302 |
-
title_label = tk.Label(root, text="Image Error Fix", font=('Helvetica', 16))
|
303 |
-
title_label.pack(pady=10)
|
304 |
-
|
305 |
-
select_files_button = tk.Button(root, text="Select Files", command=select_files)
|
306 |
-
select_files_button.pack(pady=5)
|
307 |
-
|
308 |
-
num_files_label = tk.Label(root, textvariable=num_files_var)
|
309 |
-
num_files_label.pack(pady=5)
|
310 |
-
|
311 |
-
thread_count_label = tk.Label(root, text="Number of Threads:")
|
312 |
-
thread_count_label.pack(pady=5)
|
313 |
-
|
314 |
-
thread_count_var = tk.StringVar(value="4")
|
315 |
-
thread_count_entry = tk.Entry(root, textvariable=thread_count_var, width=3, justify='center', validate="key", validatecommand=(validate_command, '%P'))
|
316 |
-
thread_count_entry.pack(pady=5)
|
317 |
-
|
318 |
-
# Separator for aesthetics
|
319 |
-
separator = ttk.Separator(root, orient='horizontal')
|
320 |
-
separator.pack(fill='x', pady=10)
|
321 |
-
|
322 |
-
scan_fix_button = tk.Button(root, text="Scan and Fix", command=scan_and_fix)
|
323 |
-
scan_fix_button.pack(pady=10)
|
324 |
-
|
325 |
-
stop_button = tk.Button(root, text="Stop", command=stop_processing_func)
|
326 |
-
stop_button.pack(pady=5)
|
327 |
-
|
328 |
-
progress_bar = ttk.Progressbar(root, variable=progress, maximum=100)
|
329 |
-
progress_bar.pack(pady=5, fill=tk.X)
|
330 |
-
|
331 |
-
delete_all_label = tk.Label(root, text="Click 'Delete All' to remove all files with errors.")
|
332 |
-
delete_all_label.pack(pady=5)
|
333 |
-
|
334 |
-
delete_all_button = tk.Button(root, text="Delete All", command=delete_all_errors)
|
335 |
-
delete_all_button.pack(pady=5)
|
336 |
-
|
337 |
-
errors_label = tk.Label(root, textvariable=errors_var, fg="red")
|
338 |
-
errors_label.pack(pady=5)
|
339 |
-
|
340 |
-
status_label = tk.Label(root, textvariable=status_var, fg="green")
|
341 |
-
status_label.pack(pady=5)
|
342 |
-
|
343 |
-
center_window(root)
|
344 |
-
root.protocol("WM_DELETE_WINDOW", on_closing)
|
345 |
-
root.mainloop()
|
346 |
-
|
347 |
-
if __name__ == "__main__":
|
348 |
-
open_image_error_fix()
|
|
|
1 |
+
import tkinter as tk
|
2 |
+
from tkinter import filedialog, ttk, messagebox
|
3 |
+
import os
|
4 |
+
import threading, queue
|
5 |
+
from PIL import Image, UnidentifiedImageError
|
6 |
+
|
7 |
+
# Global variables for managing state and errors
|
8 |
+
stop_processing = False
|
9 |
+
error_messages = []
|
10 |
+
selected_files = []
|
11 |
+
error_list = []
|
12 |
+
|
13 |
+
def open_image_error_fix():
|
14 |
+
global stop_processing, error_messages, selected_files, status_var, num_files_var, errors_var, progress, q, error_list, error_window, thread_count_var
|
15 |
+
|
16 |
+
# Initialize the main Tkinter window
|
17 |
+
root = tk.Tk()
|
18 |
+
root.title("Image Error Fix")
|
19 |
+
|
20 |
+
# Initialize Tkinter variables
|
21 |
+
status_var = tk.StringVar()
|
22 |
+
num_files_var = tk.StringVar()
|
23 |
+
errors_var = tk.StringVar(value="Errors: 0")
|
24 |
+
progress = tk.IntVar()
|
25 |
+
thread_count_var = tk.StringVar(value="1") # Default thread count
|
26 |
+
q = queue.Queue()
|
27 |
+
|
28 |
+
def center_window(window):
|
29 |
+
window.update_idletasks()
|
30 |
+
width = window.winfo_width() + 120
|
31 |
+
height = window.winfo_height()
|
32 |
+
x = (window.winfo_screenwidth() // 2) - (width // 2)
|
33 |
+
y = (window.winfo_screenheight() // 2) - (height // 2)
|
34 |
+
window.geometry(f'{width}x{height}+{x}+{y}')
|
35 |
+
|
36 |
+
def validate_number(P):
|
37 |
+
return P.isdigit() or P == ""
|
38 |
+
|
39 |
+
def validate_thread_count(var):
|
40 |
+
value = var.get()
|
41 |
+
if value != "":
|
42 |
+
try:
|
43 |
+
int_value = int(value)
|
44 |
+
if int_value <= 0:
|
45 |
+
raise ValueError
|
46 |
+
except ValueError:
|
47 |
+
messagebox.showerror("Invalid Input", "Please enter a valid number of threads.")
|
48 |
+
var.set("")
|
49 |
+
|
50 |
+
def select_files():
|
51 |
+
global selected_files
|
52 |
+
filetypes = [
|
53 |
+
("All Image files", "*.jpg;*.jpeg;*.png;*.gif;*.bmp;*.tiff;*.tif;*.svg;*.webp"),
|
54 |
+
("JPEG files", "*.jpg;*.jpeg"),
|
55 |
+
("PNG files", "*.png"),
|
56 |
+
("GIF files", "*.gif"),
|
57 |
+
("BMP files", "*.bmp"),
|
58 |
+
("TIFF files", "*.tiff;*.tif"),
|
59 |
+
("SVG files", "*.svg"),
|
60 |
+
("WEBP files", "*.webp")
|
61 |
+
]
|
62 |
+
filepaths = filedialog.askopenfilenames(title="Select Image Files", filetypes=filetypes)
|
63 |
+
if filepaths:
|
64 |
+
selected_files.clear()
|
65 |
+
selected_files.extend(filepaths)
|
66 |
+
num_files_var.set(f"{len(selected_files)} files selected.")
|
67 |
+
|
68 |
+
def detect_errors(file_path):
|
69 |
+
"""Detect potential errors in an image file."""
|
70 |
+
errors = []
|
71 |
+
if not os.access(file_path, os.R_OK):
|
72 |
+
errors.append("Permission Denied")
|
73 |
+
# Additional error checks
|
74 |
+
try:
|
75 |
+
with Image.open(file_path) as img:
|
76 |
+
img.verify() # Verify the image integrity
|
77 |
+
img = Image.open(file_path)
|
78 |
+
img.load() # Load the image data to ensure it's not truncated
|
79 |
+
except UnidentifiedImageError:
|
80 |
+
errors.append("Unidentified image format or corrupted file")
|
81 |
+
except IOError as e:
|
82 |
+
errors.append(f"IOError: {str(e)}")
|
83 |
+
except Exception as e:
|
84 |
+
errors.append(f"Unknown error: {str(e)}")
|
85 |
+
return errors
|
86 |
+
|
87 |
+
def fix_error(file_path, error_type):
|
88 |
+
"""Fix errors in an image file, if possible."""
|
89 |
+
if error_type == "Permission Denied":
|
90 |
+
# Attempt to change permissions
|
91 |
+
try:
|
92 |
+
os.chmod(file_path, 0o644)
|
93 |
+
return "Permissions fixed. File permissions were successfully updated."
|
94 |
+
except Exception as e:
|
95 |
+
return f"Failed to fix permissions. Ensure you have the necessary permissions to modify this file. Error: {str(e)}"
|
96 |
+
elif error_type == "Unidentified image format or corrupted file":
|
97 |
+
return "The file format is unrecognized or the file is corrupted. Please try to re-download or restore from a backup."
|
98 |
+
elif error_type == "Invalid Format":
|
99 |
+
return ("Cannot automatically fix invalid formats. Ensure the file extension matches the file content.\n"
|
100 |
+
"To fix this issue, please follow these steps:\n"
|
101 |
+
"1. Identify the correct file format by using a file type checker tool (e.g., CheckFileType.com).\n"
|
102 |
+
"2. Rename the file with the correct extension:\n"
|
103 |
+
" - Right-click on the file and select 'Rename'.\n"
|
104 |
+
" - Change the file extension to the correct format (e.g., .jpg, .png).\n"
|
105 |
+
" - Press Enter to save the changes.\n"
|
106 |
+
"3. Try opening the file again. If the problem persists, the file may be corrupted or contain unsupported data.")
|
107 |
+
elif error_type == "File Not Found":
|
108 |
+
return ("The file could not be found at the specified path. Please ensure that the file has not been moved or deleted.\n"
|
109 |
+
"1. Verify the file path is correct.\n"
|
110 |
+
"2. If the file has been moved, update the path in the application or locate the file manually.\n"
|
111 |
+
"3. If the file was deleted, check your Recycle Bin or use a data recovery tool to attempt to restore it.")
|
112 |
+
elif error_type == "File Path Too Long":
|
113 |
+
return ("The file path exceeds the system limit. Windows has a maximum path length of 260 characters.\n"
|
114 |
+
"To fix this issue:\n"
|
115 |
+
"1. Move the file to a location with a shorter path, closer to the root directory (e.g., C:\\).\n"
|
116 |
+
"2. Rename folders in the path to shorter names.\n"
|
117 |
+
"3. Enable long path support in Windows if using Windows 10 (version 1607 hoặc cao hơn):\n"
|
118 |
+
" - Open the Group Policy Editor (gpedit.msc).\n"
|
119 |
+
" - Navigate to 'Local Computer Policy > Computer Configuration > Administrative Templates > System > Filesystem'.\n"
|
120 |
+
" - Enable the 'Enable Win32 long paths' option.")
|
121 |
+
elif error_type == "Transmission Errors":
|
122 |
+
return ("The file may be incomplete or corrupted due to transmission errors. This can happen if the file was downloaded or transferred incorrectly.\n"
|
123 |
+
"To fix this issue:\n"
|
124 |
+
"1. Re-download hoặc re-transfer the file.\n"
|
125 |
+
"2. Use a reliable network connection to ensure the file is not corrupted during transfer.\n"
|
126 |
+
"3. Verify the integrity of the file by comparing checksums (if available).")
|
127 |
+
elif error_type == "Unsupported Format":
|
128 |
+
return ("The file format is not supported by this application. Supported formats include JPEG, PNG, GIF, BMP, TIFF, SVG, và WEBP.\n"
|
129 |
+
"To fix this issue:\n"
|
130 |
+
"1. Convert the file to a supported format using an image converter tool.\n"
|
131 |
+
"2. Ensure that the file is not corrupted and can be opened with other image viewers or editors.")
|
132 |
+
else:
|
133 |
+
return "No action taken. This error type is not recognized or cannot be fixed automatically."
|
134 |
+
|
135 |
+
def delete_file(file_path):
|
136 |
+
"""Delete the specified file."""
|
137 |
+
try:
|
138 |
+
os.remove(file_path)
|
139 |
+
# Remove from selected files
|
140 |
+
selected_files.remove(file_path)
|
141 |
+
num_files_var.set(f"{len(selected_files)} files selected.")
|
142 |
+
return f"File {file_path} deleted successfully."
|
143 |
+
except Exception as e:
|
144 |
+
return f"Failed to delete file {file_path}. Error: {str(e)}"
|
145 |
+
|
146 |
+
def process_image(file_path, q):
|
147 |
+
if stop_processing:
|
148 |
+
return
|
149 |
+
|
150 |
+
errors = detect_errors(file_path)
|
151 |
+
if errors:
|
152 |
+
q.put((file_path, errors))
|
153 |
+
|
154 |
+
def worker():
|
155 |
+
try:
|
156 |
+
progress.set(0)
|
157 |
+
total_files = len(selected_files)
|
158 |
+
thread_count = int(thread_count_var.get()) # Get the number of threads
|
159 |
+
for i, input_path in enumerate(selected_files, 1):
|
160 |
+
if stop_processing:
|
161 |
+
break
|
162 |
+
|
163 |
+
thread = threading.Thread(target=process_image, args=(input_path, q))
|
164 |
+
thread.start()
|
165 |
+
thread.join()
|
166 |
+
|
167 |
+
# Update progress bar
|
168 |
+
progress.set(int(i / total_files * 100))
|
169 |
+
|
170 |
+
q.put(None)
|
171 |
+
except Exception as e:
|
172 |
+
if not stop_processing:
|
173 |
+
q.put(e)
|
174 |
+
|
175 |
+
def update_progress():
|
176 |
+
try:
|
177 |
+
global error_list
|
178 |
+
error_list = []
|
179 |
+
while True:
|
180 |
+
item = q.get()
|
181 |
+
if item is None:
|
182 |
+
break
|
183 |
+
if isinstance(item, tuple):
|
184 |
+
error_list.append(item)
|
185 |
+
|
186 |
+
if not error_list:
|
187 |
+
messagebox.showinfo("No Errors Found", "No errors were detected in the selected images.")
|
188 |
+
else:
|
189 |
+
errors_var.set(f"Errors: {len(error_list)}")
|
190 |
+
display_errors(error_list)
|
191 |
+
except Exception as e:
|
192 |
+
if not stop_processing:
|
193 |
+
root.after(0, status_var.set, f"Error: {e}")
|
194 |
+
|
195 |
+
def update_error_display():
|
196 |
+
"""Update the display of errors in the error window."""
|
197 |
+
global error_list, frame
|
198 |
+
# Clear all existing widgets in the frame
|
199 |
+
for widget in frame.winfo_children():
|
200 |
+
widget.destroy()
|
201 |
+
|
202 |
+
# Repopulate the frame with updated error list
|
203 |
+
for file_path, errors in error_list:
|
204 |
+
for error in errors:
|
205 |
+
frame_row = tk.Frame(frame)
|
206 |
+
frame_row.pack(fill="x", pady=2)
|
207 |
+
|
208 |
+
# Hiển thị đường dẫn đầy đủ và tự động xuống dòng
|
209 |
+
file_label = tk.Label(frame_row, text=f"{file_path}: {error}", anchor="w", wraplength=500, justify='left')
|
210 |
+
file_label.pack(side=tk.LEFT, fill="x", expand=True)
|
211 |
+
|
212 |
+
delete_button = tk.Button(frame_row, text="Delete", command=lambda fp=file_path: delete_file_action(fp))
|
213 |
+
delete_button.pack(side=tk.RIGHT)
|
214 |
+
|
215 |
+
fix_button = tk.Button(frame_row, text="Fix", command=lambda fp=file_path, et=error: fix_error_action(fp, et))
|
216 |
+
fix_button.pack(side=tk.RIGHT)
|
217 |
+
|
218 |
+
# Thêm dấu phân cách giữa các lỗi
|
219 |
+
separator = ttk.Separator(frame, orient='horizontal')
|
220 |
+
separator.pack(fill='x', pady=5)
|
221 |
+
|
222 |
+
frame.update_idletasks()
|
223 |
+
canvas.configure(scrollregion=canvas.bbox("all"))
|
224 |
+
|
225 |
+
def display_errors(error_list):
|
226 |
+
global error_window, canvas, frame
|
227 |
+
# Create or raise the error window
|
228 |
+
if 'error_window' in globals() and error_window.winfo_exists():
|
229 |
+
error_window.lift()
|
230 |
+
else:
|
231 |
+
error_window = tk.Toplevel(root)
|
232 |
+
error_window.title("Error Details")
|
233 |
+
error_window.geometry("600x400")
|
234 |
+
|
235 |
+
canvas = tk.Canvas(error_window)
|
236 |
+
canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
|
237 |
+
|
238 |
+
scrollbar = tk.Scrollbar(error_window, command=canvas.yview)
|
239 |
+
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
|
240 |
+
|
241 |
+
canvas.configure(yscrollcommand=scrollbar.set)
|
242 |
+
|
243 |
+
frame = tk.Frame(canvas)
|
244 |
+
canvas.create_window((0, 0), window=frame, anchor="nw")
|
245 |
+
|
246 |
+
update_error_display()
|
247 |
+
|
248 |
+
def fix_error_action(file_path, error_type):
|
249 |
+
fix_message = fix_error(file_path, error_type)
|
250 |
+
messagebox.showinfo("Fix Error", fix_message)
|
251 |
+
|
252 |
+
def delete_file_action(file_path):
|
253 |
+
global error_list
|
254 |
+
delete_message = delete_file(file_path)
|
255 |
+
messagebox.showinfo("Delete File", delete_message)
|
256 |
+
# Remove the error from the error_list and refresh the display
|
257 |
+
error_list = [(fp, errs) for fp, errs in error_list if fp != file_path]
|
258 |
+
errors_var.set(f"Errors: {len(error_list)}")
|
259 |
+
update_error_display()
|
260 |
+
|
261 |
+
def delete_all_errors():
|
262 |
+
global error_list
|
263 |
+
for file_path, _ in error_list:
|
264 |
+
delete_file(file_path)
|
265 |
+
error_list.clear()
|
266 |
+
errors_var.set("Errors: 0")
|
267 |
+
messagebox.showinfo("Delete All Files", "All files with errors have been deleted.")
|
268 |
+
update_error_display() # Update the error display after deleting all errors
|
269 |
+
|
270 |
+
def scan_and_fix():
|
271 |
+
global stop_processing, error_messages
|
272 |
+
stop_processing = False
|
273 |
+
error_messages.clear()
|
274 |
+
errors_var.set("Errors: 0")
|
275 |
+
if not selected_files:
|
276 |
+
status_var.set("Please select images to scan.")
|
277 |
+
return
|
278 |
+
|
279 |
+
threading.Thread(target=worker).start()
|
280 |
+
threading.Thread(target=update_progress).start()
|
281 |
+
|
282 |
+
def stop_processing_func():
|
283 |
+
global stop_processing
|
284 |
+
stop_processing = True
|
285 |
+
status_var.set("Processing stopped.")
|
286 |
+
|
287 |
+
def return_to_menu():
|
288 |
+
stop_processing_func()
|
289 |
+
root.destroy()
|
290 |
+
import main
|
291 |
+
main.open_main_menu()
|
292 |
+
|
293 |
+
def on_closing():
|
294 |
+
return_to_menu()
|
295 |
+
|
296 |
+
# Create GUI elements
|
297 |
+
validate_command = root.register(validate_number)
|
298 |
+
|
299 |
+
back_button = tk.Button(root, text="<-", font=('Helvetica', 14), command=return_to_menu)
|
300 |
+
back_button.pack(anchor='nw', padx=10, pady=10)
|
301 |
+
|
302 |
+
title_label = tk.Label(root, text="Image Error Fix", font=('Helvetica', 16))
|
303 |
+
title_label.pack(pady=10)
|
304 |
+
|
305 |
+
select_files_button = tk.Button(root, text="Select Files", command=select_files)
|
306 |
+
select_files_button.pack(pady=5)
|
307 |
+
|
308 |
+
num_files_label = tk.Label(root, textvariable=num_files_var)
|
309 |
+
num_files_label.pack(pady=5)
|
310 |
+
|
311 |
+
thread_count_label = tk.Label(root, text="Number of Threads:")
|
312 |
+
thread_count_label.pack(pady=5)
|
313 |
+
|
314 |
+
thread_count_var = tk.StringVar(value="4")
|
315 |
+
thread_count_entry = tk.Entry(root, textvariable=thread_count_var, width=3, justify='center', validate="key", validatecommand=(validate_command, '%P'))
|
316 |
+
thread_count_entry.pack(pady=5)
|
317 |
+
|
318 |
+
# Separator for aesthetics
|
319 |
+
separator = ttk.Separator(root, orient='horizontal')
|
320 |
+
separator.pack(fill='x', pady=10)
|
321 |
+
|
322 |
+
scan_fix_button = tk.Button(root, text="Scan and Fix", command=scan_and_fix)
|
323 |
+
scan_fix_button.pack(pady=10)
|
324 |
+
|
325 |
+
stop_button = tk.Button(root, text="Stop", command=stop_processing_func)
|
326 |
+
stop_button.pack(pady=5)
|
327 |
+
|
328 |
+
progress_bar = ttk.Progressbar(root, variable=progress, maximum=100)
|
329 |
+
progress_bar.pack(pady=5, fill=tk.X)
|
330 |
+
|
331 |
+
delete_all_label = tk.Label(root, text="Click 'Delete All' to remove all files with errors.")
|
332 |
+
delete_all_label.pack(pady=5)
|
333 |
+
|
334 |
+
delete_all_button = tk.Button(root, text="Delete All", command=delete_all_errors)
|
335 |
+
delete_all_button.pack(pady=5)
|
336 |
+
|
337 |
+
errors_label = tk.Label(root, textvariable=errors_var, fg="red")
|
338 |
+
errors_label.pack(pady=5)
|
339 |
+
|
340 |
+
status_label = tk.Label(root, textvariable=status_var, fg="green")
|
341 |
+
status_label.pack(pady=5)
|
342 |
+
|
343 |
+
center_window(root)
|
344 |
+
root.protocol("WM_DELETE_WINDOW", on_closing)
|
345 |
+
root.mainloop()
|
346 |
+
|
347 |
+
if __name__ == "__main__":
|
348 |
+
open_image_error_fix()
|