None of the progress stuff or status works here is code import ttkbootstrap as tb
from ttkbootstrap.constants import *
from ttkbootstrap.dialogs import Messagebox
from tkinter import filedialog
import os
import subprocess
import threading
import concurrent.futures
import queue
import psutil
import sys
def select_input_folders():
while True:
folder = filedialog.askdirectory(title="Select Input Folder (Cancel to finish)")
if folder:
if folder not in input_folders and folder not in input_videos:
input_folders.append(folder)
tree.insert('', 'end', iid=folder, values=(folder, "Folder", "Pending"))
else:
Messagebox.show_warning("Duplicate Entry", f"The entry '{folder}' is already selected.")
else:
break
def select_input_videos():
files = filedialog.askopenfilenames(title="Select Video Files",
filetypes=[("Video Files", "*.mp4 *.avi *.mov *.mkv *.flv *.wmv")])
for file in files:
if file not in input_videos and file not in input_folders:
input_videos.append(file)
tree.insert('', 'end', iid=file, values=(file, "Video File", "Pending"))
else:
Messagebox.show_warning("Duplicate Entry", f"The file '{file}' is already selected.")
def remove_selected_items():
selected_items = tree.selection()
for item in selected_items:
item_type = tree.set(item, "Type")
if item_type == "Folder":
input_folders.remove(item)
elif item_type == "Video File":
input_videos.remove(item)
tree.delete(item)
update_remove_button()
def sanitize_folder_name(name):
"""Sanitize the folder name to remove or replace problematic characters."""
return "".join(c if c.isalnum() or c in (' ', '', '-') else "" for c in name).replace(" ", "_")
def process_videos_thread():
"""Run the video processing in a separate thread."""
threading.Thread(target=process_videos, daemon=True).start()
def process_videos():
global is_paused
output_folder = output_folder_var.get()
code
Assistant
if not input_folders and not input_videos:
Messagebox.show_error("Error", "Please select at least one input folder or video file.")
return
if not output_folder:
Messagebox.show_error("Error", "Please select an output folder.")
return
# Ensure the output directory exists
os.makedirs(output_folder, exist_ok=True)
# Disable the process button and folder selection buttons to prevent multiple clicks
set_buttons_state(DISABLED)
# Initialize overall progress bar
total_tasks = len(input_folders) + len(input_videos)
progress_bar['maximum'] = total_tasks
progress_bar['value'] = 0
status_label.config(text="Starting processing...")
# Queue to receive progress updates
progress_queue = queue.Queue()
# List to collect errors
errors = []
# Create a combined tasks queue
tasks_queue = queue.Queue()
for folder in input_folders:
tasks_queue.put(("Folder", folder))
for video in input_videos:
tasks_queue.put(("Video File", video))
# Determine optimal number of workers based on CPU cores
max_workers = min(os.cpu_count() * 2 or DEFAULT_MAX_CONCURRENT_TASKS, 32)
def worker(task_type, path):
if is_paused:
# Wait until resumed
while is_paused:
if stop_all_event.is_set():
return
threading.Event().wait(0.1)
# Update Treeview status to "Processing"
progress_queue.put(("status", path, "Processing"))
base_name = os.path.basename(os.path.normpath(path))
sanitized_base = sanitize_folder_name(base_name)
if task_type == "Folder":
unique_output_dir = os.path.join(output_folder, f"{sanitized_base}_{base_name}")
input_path = path
elif task_type == "Video File":
name, _ = os.path.splitext(base_name)
unique_output_dir = os.path.join(output_folder, f"{sanitize_folder_name(name)}_output")
input_path = path
os.makedirs(unique_output_dir, exist_ok=True)
try:
# Retrieve the selected output format
selected_format = output_format_var.get()
# Run the video2image command with the unique output directory and selected format
if task_type == "Folder":
subprocess.run(
['video2image', '-i', input_path, '-o', unique_output_dir, '-f', selected_format],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
elif task_type == "Video File":
subprocess.run(
['video2image', '-i', input_path, '-o', unique_output_dir, '-f', selected_format],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
progress_queue.put(("success", path))
except subprocess.CalledProcessError as e:
error_msg = f"Failed to process {task_type.lower()}: {path}\nError Code: {e.returncode}"
progress_queue.put(("error", path, error_msg))
except Exception as ex:
error_msg = f"An unexpected error occurred while processing {task_type.lower()}: {path}\nError: {ex}"
progress_queue.put(("error", path, error_msg))
# Initialize ThreadPoolExecutor
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {}
for _ in range(min(max_workers, tasks_queue.qsize())):
if not tasks_queue.empty():
task_type, path = tasks_queue.get()
futures[executor.submit(worker, task_type, path)] = path
while futures:
done, _ = concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_COMPLETED)
for future in done:
folder = futures.pop(future)
try:
future.result()
except Exception as e:
error_msg = f"Error processing {folder}\nError: {e}"
progress_queue.put(("error", folder, error_msg))
if not tasks_queue.empty() and not is_paused:
task_type, next_path = tasks_queue.get()
futures[executor.submit(worker, task_type, next_path)] = next_path
# Finalize processing
finalize_processing(errors)
# Start disk space monitoring
monitor_disk_space()
def set_buttons_state(state):
process_button.config(state=state)
select_input_button.config(state=state)
select_output_button.config(state=state)
select_videos_button.config(state=state)
remove_button.config(state=NORMAL if (input_folders or input_videos) and state == NORMAL else DISABLED)
pause_button.config(state=state if state == NORMAL else DISABLED)
resume_button.config(state=DISABLED if state == NORMAL else NORMAL)
output_format_combobox.config(state=DISABLED if state == DISABLED else NORMAL)
def on_resume():
global is_paused
is_paused = False
status_label.config(text="Resuming processing...")
pause_button.config(state=NORMAL)
resume_button.config(state=DISABLED)
# Resume task submission by re-invoking process_videos_thread
process_videos_thread()
def monitor_disk_space():
output_path = output_folder_var.get() or '/'
try:
total, used, free = psutil.disk_usage(output_path)
if free < disk_space_threshold_mb * 1024 * 1024:
if not is_paused:
on_pause()
Messagebox.show_warning("Auto-Pause", "Disk space below threshold. Processing has been paused.")
except Exception as e:
Messagebox.show_error("Disk Space Error", f"Unable to determine disk space for '{output_path}'.\nError: {e}")
root.after(DISK_CHECK_INTERVAL, monitor_disk_space)
def set_disk_threshold():
try:
value = int(disk_threshold_entry.get())
if value <= 0:
raise ValueError
global disk_space_threshold_mb
disk_space_threshold_mb = value
Messagebox.show_info("Threshold Set", f"Auto-pause threshold set to {value} MB.")
except ValueError:
Messagebox.show_error("Invalid Input", "Please enter a valid positive integer for the disk space threshold.")
def update_remove_button():
"""Enable or disable the remove button based on folder selection."""
if input_folders or input_videos:
remove_button.config(state=NORMAL)
else:
remove_button.config(state=DISABLED)
def finalize_processing(errors):
set_buttons_state(NORMAL)
if errors:
error_message = "\n\n".join(errors)
Messagebox.show_error("Processing Completed with Errors", error_message)
else:
Messagebox.show_success("Success", "All videos have been successfully processed.")
progress_bar['value'] = 0
status_label.config(text="Processing completed.")
Monitor changes in the input_folders and input_videos lists to update the remove button state
def monitor_input_folders_and_videos():
"""Periodically check if input_folders or input_videos is empty to enable/disable the remove button."""
update_remove_button()
root.after(500, monitor_input_folders_and_videos)
It appears that your application isn't updating the progress bar or status labels as expected. After reviewing your code, the primary issue lies in how the progress_queue is being handled. Let's dive into the problem and provide a solution to ensure your progress indicators work correctly.
Identifying the Issue
Local vs. Global progress_queue:
Global Declaration:
python
# Queue for inter-thread communication
progress_queue = queue.Queue()
You correctly initialize a global progress_queue intended for communication between worker threads and the main GUI thread.
Inside the process_videos function, you redeclare progress_queue as a local variable. This means that any messages put into this local queue by worker threads won't be accessible to the update_progress function, which is listening to the globalprogress_queue.
Impact on Progress Updates:
Worker threads send progress messages to the localprogress_queue, but the main thread's update_progress function listens to the globalprogress_queue. As a result, the main thread never receives any updates, causing the progress bar and status labels to remain static.
Solution
To fix this issue, you need to ensure that both the worker threads and the update_progress function use the same progress_queue. Here's how you can do it:
Remove the Local Declaration:
Delete or Comment Out the Local progress_queue Initialization:
python
def process_videos():
...
# Remove or comment out the following line
# progress_queue = queue.Queue()
...
By doing this, any reference to progress_queue within process_videos and its nested functions will default to the global queue.
Ensure that errors is correctly updated by the update_progress function and passed to finalize_processing.
Full Corrected Code Snippet:
Here's the corrected version of your code with the necessary changes highlighted:
python
Additional Recommendations:
Thread Safety:
Ensure that any interactions with Tkinter widgets from worker threads are done safely, typically by using thread-safe queues (which you are already doing) and avoiding direct widget manipulation from non-main threads.
Error Handling:
In finalize_processing, you pass errors as an argument. Make sure that errors is correctly populated and passed around. Since errors is a global list being appended by update_progress, you might not need to pass it as a parameter.
Avoid Multiple Threads in on_resume:
Currently, on_resume calls process_videos_thread, which starts process_videos in a new thread. However, if processing is paused and you resume, this might unintentionally start another set of threads. Consider managing thread states more carefully to prevent spawning multiple processing threads.
Disk Space Monitoring:
Ensure that monitor_disk_space is correctly integrated and doesn't interfere with the main processing logic.
Conclusion
By ensuring that the progress_queue is consistently used across your threads and the main GUI thread, the progress bar and status updates should function as intended. Make sure to test the application thoroughly after making these changes to verify that all parts work seamlessly together.
If you encounter further issues or need more assistance, feel free to ask!
import ttkbootstrap as tb
from ttkbootstrap.constants import *
from ttkbootstrap.dialogs import Messagebox
from tkinter import filedialog
import os
import subprocess
import threading
import concurrent.futures
import queue
import psutil
import sys
# Constants for the application
APP_NAME = "DeepAscension Video2Image+"
DEFAULT_MAX_CONCURRENT_TASKS = 4
DISK_CHECK_INTERVAL = 5000 # in milliseconds
# Initialize the main window with ttkbootstrap
root = tb.Window(themename="darkly")
root.title(APP_NAME)
root.geometry("1200x800")
root.resizable(True, True) # Allow resizing for better usability
# Initialize the lists to store input folders and videos
input_folders = []
input_videos = []
# Variable to store output folder path
output_folder_var = tb.StringVar()
# Variable for disk space threshold
disk_space_threshold_mb = 500 # Default to 500 MB
# Variable for output format
output_format_var = tb.StringVar(value="jpg") # Default to 'jpg'
# Pause state
is_paused = False
# Event to signal stopping of all tasks
stop_all_event = threading.Event()
# Queue for inter-thread communication
progress_queue = queue.Queue()
# List to collect errors
errors = []
# Rest of your code...
def process_videos_thread():
"""Run the video processing in a separate thread."""
threading.Thread(target=process_videos, daemon=True).start()
def process_videos():
global is_paused
output_folder = output_folder_var.get()
if not input_folders and not input_videos:
Messagebox.show_error("Error", "Please select at least one input folder or video file.")
return
if not output_folder:
Messagebox.show_error("Error", "Please select an output folder.")
return
# Ensure the output directory exists
os.makedirs(output_folder, exist_ok=True)
# Disable the process button and folder selection buttons to prevent multiple clicks
set_buttons_state(DISABLED)
# Initialize overall progress bar
total_tasks = len(input_folders) + len(input_videos)
progress_bar['maximum'] = total_tasks
progress_bar['value'] = 0
status_label.config(text="Starting processing...")
# Queue to receive progress updates
# Removed the local declaration
# progress_queue = queue.Queue()
# List to collect errors
# Already using the global 'errors' list
# Create a combined tasks queue
tasks_queue = queue.Queue()
for folder in input_folders:
tasks_queue.put(("Folder", folder))
for video in input_videos:
tasks_queue.put(("Video File", video))
# Determine optimal number of workers based on CPU cores
max_workers = min(os.cpu_count() * 2 or DEFAULT_MAX_CONCURRENT_TASKS, 32)
def worker(task_type, path):
if is_paused:
# Wait until resumed
while is_paused:
if stop_all_event.is_set():
return
threading.Event().wait(0.1)
# Update Treeview status to "Processing"
progress_queue.put(("status", path, "Processing"))
base_name = os.path.basename(os.path.normpath(path))
sanitized_base = sanitize_folder_name(base_name)
if task_type == "Folder":
unique_output_dir = os.path.join(output_folder, f"{sanitized_base}_{base_name}")
input_path = path
elif task_type == "Video File":
name, _ = os.path.splitext(base_name)
unique_output_dir = os.path.join(output_folder, f"{sanitize_folder_name(name)}_output")
input_path = path
os.makedirs(unique_output_dir, exist_ok=True)
try:
# Retrieve the selected output format
selected_format = output_format_var.get()
# Run the video2image command with the unique output directory and selected format
subprocess.run(
['video2image', '-i', input_path, '-o', unique_output_dir, '-f', selected_format],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
progress_queue.put(("success", path))
except subprocess.CalledProcessError as e:
error_msg = f"Failed to process {task_type.lower()}: {path}\nError Code: {e.returncode}"
progress_queue.put(("error", path, error_msg))
except Exception as ex:
error_msg = f"An unexpected error occurred while processing {task_type.lower()}: {path}\nError: {ex}"
progress_queue.put(("error", path, error_msg))
# Initialize ThreadPoolExecutor
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {}
for _ in range(min(max_workers, tasks_queue.qsize())):
if not tasks_queue.empty():
task_type, path = tasks_queue.get()
futures[executor.submit(worker, task_type, path)] = path
while futures:
done, _ = concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_COMPLETED)
for future in done:
folder = futures.pop(future)
try:
future.result()
except Exception as e:
error_msg = f"Error processing {folder}\nError: {e}"
progress_queue.put(("error", folder, error_msg))
if not tasks_queue.empty() and not is_paused:
task_type, next_path = tasks_queue.get()
futures[executor.submit(worker, task_type, next_path)] = next_path
# Finalize processing
finalize_processing(errors)
# Start disk space monitoring
monitor_disk_space()
# Rest of your code...
# Periodically update the progress in the GUI
def periodic_update():
update_progress()
root.after(100, periodic_update)
periodic_update()
# Handle window closing to ensure all threads are properly terminated
def on_closing():
stop_all_event.set()
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_closing)
# Run the GUI loop
root.mainloop()