Switch the progress to a cool setup on cmd and also name the gui DeepAscension Video2Image+ and also make it so you know how for folder can go at once make it so if one finishes it will start another so always 4 are going instead of having to wait saving time and also add a pause and resume button and also a auto pause setting that you set to a specific amount of storage left and if drive the output folder is on hits that it auto pauses and make the gui Egyptian ascension space themed here is code import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import os
import subprocess
import threading
import concurrent.futures
import queue
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:
input_folders.append(folder)
input_listbox.insert(tk.END, folder)
else:
messagebox.showwarning("Duplicate Folder", f"The folder '{folder}' is already selected.")
else:
break
def remove_selected_folders():
selected_indices = list(input_listbox.curselection())
selected_indices.reverse() # Remove from the end to avoid index shifting
for index in selected_indices:
folder = input_listbox.get(index)
input_folders.remove(folder)
input_listbox.delete(index)
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()
if not input_folders:
messagebox.showerror("Error", "Please select at least one input folder.")
return
if not output_folder:
messagebox.showerror("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(tk.DISABLED)
# Initialize progress bar
progress_bar.config(maximum=len(input_folders))
progress_bar['value'] = 0
status_label.config(text="Starting processing...")
# Queue to receive progress updates
progress_queue = queue.Queue()
# List to collect errors
errors = []
def worker(folder):
base_name = os.path.basename(os.path.normpath(folder))
sanitized_base = sanitize_folder_name(base_name)
unique_output_dir = os.path.join(output_folder, f"{sanitized_base}_{base_name}")
os.makedirs(unique_output_dir, exist_ok=True)
try:
# Run the video2image command with the unique output directory
subprocess.run(
['video2image', '-i', folder, '-o', unique_output_dir, '-f', 'jpg'],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
progress_queue.put(("success", folder))
except subprocess.CalledProcessError as e:
error_msg = f"Failed to process folder: {folder}\nError: {e.stderr.decode().strip()}"
progress_queue.put(("error", error_msg))
except Exception as ex:
error_msg = f"An unexpected error occurred while processing folder: {folder}\nError: {ex}"
progress_queue.put(("error", error_msg))
# Determine the number of workers based on CPU count
max_workers = min(4, os.cpu_count() or 1) # Adjust this number as needed
executor = concurrent.futures.ThreadPoolExecutor(max_workers=max_workers)
# Submit all tasks
futures = [executor.submit(worker, folder) for folder in input_folders]
# Function to periodically check the queue
def check_queue():
try:
while True:
status, info = progress_queue.get_nowait()
if status == "success":
progress_bar['value'] += 1
status_label.config(text=f"Processed: {info}")
elif status == "error":
errors.append(info)
progress_bar['value'] += 1
status_label.config(text=f"Error: {info}")
if progress_bar['value'] >= len(input_folders):
executor.shutdown(wait=False)
finalize_processing()
except queue.Empty:
pass
if progress_bar['value'] < len(input_folders):
root.after(100, check_queue)
# Start checking the queue
root.after(100, check_queue)
def finalize_processing():
set_buttons_state(tk.NORMAL)
if errors:
error_message = "\n\n".join(errors)
messagebox.showerror("Processing Completed with Errors", error_message)
else:
messagebox.showinfo("Success", "All videos have been successfully processed.")
progress_bar['value'] = 0
status_label.config(text="Processing completed.")
def set_buttons_state(state):
process_button.config(state=state)
select_input_button.config(state=state)
select_output_button.config(state=state)
remove_button.config(state=state if input_folders else tk.DISABLED)
Initialize the main window
root = tk.Tk()
root.title("Video to Image Converter")
root.geometry("800x600")
root.resizable(True, True) # Allow resizing for better usability
Initialize the list to store input folders
input_folders = []
Variable to store output folder path
output_folder_var = tk.StringVar()
Style configuration
style = ttk.Style(root)
style.theme_use('clam') # You can choose another theme like 'default', 'alt', 'classic', etc.
style.configure("TButton", padding=6)
style.configure("TLabelFrame", padding=10)
style.configure("Horizontal.TProgressbar", troughcolor='white', bordercolor='black',
background='green', lightcolor='green', darkcolor='green')
def on_input_folders_change(*args):
"""Enable or disable the remove button based on folder selection."""
if input_folders:
remove_button.config(state=tk.NORMAL)
else:
remove_button.config(state=tk.DISABLED)
Monitor changes in the input_folders list to update the remove button state
def monitor_input_folders():
"""Periodically check if input_folders is empty to enable/disable the remove button."""
on_input_folders_change()
root.after(500, monitor_input_folders)
monitor_input_folders()
Run the GUI loop
root.mainloop()
Certainly! Below is the enhanced version of your Video2Image converter with all the requested features:
GUI Renamed to "DeepAscension Video2Image+": The window title has been updated.
Concurrent Processing with Always 4 Active Tasks: The application maintains up to four concurrent processing tasks, automatically starting new ones as others finish.
Pause and Resume Functionality: Added buttons to pause and resume processing.
Auto-Pause Based on Disk Space: The application will automatically pause processing when the available disk space falls below a user-defined threshold.
Egyptian Ascension Space Themed GUI: The GUI has been styled with an Egyptian space theme using appropriate colors and fonts.
Enhanced Progress Display: The progress bar has been stylized to look more visually appealing, resembling a command-line interface.
Dependencies
Before running the code, ensure you have the following dependencies installed:
bash
pip install psutil
Enhanced Code
python
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import os
import subprocess
import threading
import concurrent.futures
import queue
import psutil
import sys
from functools import partial
# Constants for the application
APP_NAME = "DeepAscension Video2Image+"
MAX_CONCURRENT_TASKS = 4
DISK_CHECK_INTERVAL = 5000 # in milliseconds
# Colors for the Egyptian Ascension Space Theme
BACKGROUND_COLOR = "#1B1B2F" # Dark Blue
FRAME_COLOR = "#16213E"
BUTTON_COLOR = "#0F3460"
LABEL_COLOR = "#E94560"
PROGRESS_BG = "#0F3460"
PROGRESS_FG = "#E94560"
STATUS_BG = "#0F3460"
STATUS_FG = "#FFFFFF"
def select_input_folders():
while True:
folder = filedialog.askdirectory(title="Select Input Folder (Cancel to finish)")
if folder:
if folder not in input_folders:
input_folders.append(folder)
input_listbox.insert(tk.END, folder)
else:
messagebox.showwarning("Duplicate Folder", f"The folder '{folder}' is already selected.")
else:
break
def remove_selected_folders():
selected_indices = list(input_listbox.curselection())
selected_indices.reverse() # Remove from the end to avoid index shifting
for index in selected_indices:
folder = input_listbox.get(index)
input_folders.remove(folder)
input_listbox.delete(index)
def select_output_folder():
folder = filedialog.askdirectory(title="Select Output Folder")
if folder:
output_folder_var.set(folder)
output_entry.config(state='normal')
output_entry.delete(0, tk.END)
output_entry.insert(0, folder)
output_entry.config(state='readonly')
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()
if not input_folders:
messagebox.showerror("Error", "Please select at least one input folder.")
return
if not output_folder:
messagebox.showerror("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(tk.DISABLED)
# Initialize progress bar
progress_bar.config(maximum=len(input_folders))
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 copy of input_folders to iterate over
tasks_queue = queue.Queue()
for folder in input_folders:
tasks_queue.put(folder)
def worker(folder):
base_name = os.path.basename(os.path.normpath(folder))
sanitized_base = sanitize_folder_name(base_name)
unique_output_dir = os.path.join(output_folder, f"{sanitized_base}_{base_name}")
os.makedirs(unique_output_dir, exist_ok=True)
try:
# Run the video2image command with the unique output directory
subprocess.run(
['video2image', '-i', folder, '-o', unique_output_dir, '-f', 'jpg'],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
progress_queue.put(("success", folder))
except subprocess.CalledProcessError as e:
error_msg = f"Failed to process folder: {folder}\nError: {e.stderr.decode().strip()}"
progress_queue.put(("error", error_msg))
except Exception as ex:
error_msg = f"An unexpected error occurred while processing folder: {folder}\nError: {ex}"
progress_queue.put(("error", error_msg))
# Initialize ThreadPoolExecutor
executor = concurrent.futures.ThreadPoolExecutor(max_workers=MAX_CONCURRENT_TASKS)
futures = []
def submit_tasks():
while not tasks_queue.empty() and not is_paused:
folder = tasks_queue.get()
future = executor.submit(worker, folder)
futures.append(future)
# Initially submit tasks
submit_tasks()
def check_queue():
try:
while True:
status, info = progress_queue.get_nowait()
if status == "success":
progress_bar['value'] += 1
status_label.config(text=f"Processed: {info}")
elif status == "error":
errors.append(info)
progress_bar['value'] += 1
status_label.config(text=f"Error: {info}")
if not tasks_queue.empty() and not is_paused:
submit_tasks()
if progress_bar['value'] >= len(input_folders):
executor.shutdown(wait=False)
finalize_processing()
except queue.Empty:
pass
if progress_bar['value'] < len(input_folders):
root.after(100, check_queue)
# Start checking the queue
root.after(100, check_queue)
def finalize_processing():
set_buttons_state(tk.NORMAL)
if errors:
error_message = "\n\n".join(errors)
messagebox.showerror("Processing Completed with Errors", error_message)
else:
messagebox.showinfo("Success", "All videos have been successfully processed.")
progress_bar['value'] = 0
status_label.config(text="Processing completed.")
# 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)
remove_button.config(state=state if input_folders else tk.DISABLED)
pause_button.config(state=state)
resume_button.config(state=state)
def on_pause():
global is_paused
is_paused = True
status_label.config(text="Processing paused.")
pause_button.config(state=tk.DISABLED)
resume_button.config(state=tk.NORMAL)
def on_resume():
global is_paused
is_paused = False
status_label.config(text="Resuming processing...")
pause_button.config(state=tk.NORMAL)
resume_button.config(state=tk.DISABLED)
# Resume task submission
threading.Thread(target=process_videos, daemon=True).start()
def monitor_disk_space():
total, used, free = psutil.disk_usage(output_folder_var.get() or '/')
if free < disk_space_threshold_mb * 1024 * 1024:
if not is_paused:
on_pause()
messagebox.showwarning("Auto-Pause", "Disk space below threshold. Processing has been paused.")
root.after(DISK_CHECK_INTERVAL, monitor_disk_space)
def set_disk_threshold():
try:
value = int(disk_threshold_entry.get())
global disk_space_threshold_mb
disk_space_threshold_mb = value
messagebox.showinfo("Threshold Set", f"Auto-pause threshold set to {value} MB.")
except ValueError:
messagebox.showerror("Invalid Input", "Please enter a valid integer for the disk space threshold.")
def update_remove_button(*args):
"""Enable or disable the remove button based on folder selection."""
if input_folders:
remove_button.config(state=tk.NORMAL)
else:
remove_button.config(state=tk.DISABLED)
# Initialize the main window
root = tk.Tk()
root.title(APP_NAME)
root.geometry("900x700")
root.resizable(True, True) # Allow resizing for better usability
root.configure(bg=BACKGROUND_COLOR)
# Initialize the list to store input folders
input_folders = []
# Variable to store output folder path
output_folder_var = tk.StringVar()
# Variable for disk space threshold
disk_space_threshold_mb = 500 # Default to 500 MB
# Pause state
is_paused = False
# Style configuration
style = ttk.Style(root)
style.theme_use('clam') # Use 'clam' theme as base
# Customize styles for the theme
style.configure("TButton",
foreground=LABEL_COLOR,
background=BUTTON_COLOR,
font=('Helvetica', 10, 'bold'))
style.map("TButton",
background=[('active', '#E94560')])
style.configure("TLabel",
foreground=LABEL_COLOR,
background=BACKGROUND_COLOR,
font=('Helvetica', 10, 'bold'))
style.configure("TLabelFrame",
foreground=LABEL_COLOR,
background=FRAME_COLOR,
font=('Helvetica', 12, 'bold'))
style.configure("Horizontal.TProgressbar",
troughcolor=PROGRESS_BG,
background=PROGRESS_FG,
bordercolor=PROGRESS_BG,
lightcolor=PROGRESS_FG,
darkcolor=PROGRESS_FG)
style.configure("TEntry",
foreground=BACKGROUND_COLOR,
background=LABEL_COLOR,
font=('Helvetica', 10),
fieldbackground=LABEL_COLOR)
style.configure("Status.TLabel",
foreground=STATUS_FG,
background=STATUS_BG,
font=('Helvetica', 10))
# Frame for Input Folders
input_frame = ttk.LabelFrame(root, text="Input Folders", padding=(20, 10))
input_frame.pack(fill="both", expand=True, padx=20, pady=10)
# Listbox to display selected input folders
input_listbox = tk.Listbox(input_frame, selectmode=tk.MULTIPLE, height=15, bg=FRAME_COLOR, fg=LABEL_COLOR, selectbackground="#E94560", selectforeground=BACKGROUND_COLOR)
input_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0,5), pady=5)
# Scrollbar for the listbox
input_scroll = ttk.Scrollbar(input_frame, orient=tk.VERTICAL, command=input_listbox.yview)
input_scroll.pack(side=tk.RIGHT, fill=tk.Y)
input_listbox.config(yscrollcommand=input_scroll.set)
# Frame for Input Buttons
input_button_frame = ttk.Frame(root, padding=(20, 0))
input_button_frame.pack(fill='x', padx=20, pady=(0,10))
# Button to select input folders
select_input_button = ttk.Button(input_button_frame, text="Select Input Folders", command=select_input_folders)
select_input_button.pack(side=tk.LEFT, padx=5)
# Button to remove selected input folders
remove_button = ttk.Button(input_button_frame, text="Remove Selected", command=remove_selected_folders, state=tk.DISABLED)
remove_button.pack(side=tk.LEFT, padx=5)
# Frame for Output Folder
output_frame = ttk.LabelFrame(root, text="Output Folder", padding=(20, 10))
output_frame.pack(fill="both", expand=True, padx=20, pady=10)
# Entry widget to display selected output folder
output_entry = ttk.Entry(output_frame, textvariable=output_folder_var, width=80, state='readonly', style="TEntry")
output_entry.pack(side=tk.LEFT, padx=(0, 5), expand=True, fill=tk.X)
# Button to select output folder
select_output_button = ttk.Button(output_frame, text="Select Output Folder", command=select_output_folder)
select_output_button.pack(side=tk.LEFT, padx=5)
# Frame for Disk Space Threshold
disk_frame = ttk.LabelFrame(root, text="Auto-Pause Disk Space Threshold (MB)", padding=(20, 10))
disk_frame.pack(fill="x", expand=True, padx=20, pady=10)
disk_threshold_entry = ttk.Entry(disk_frame, width=10, justify='center')
disk_threshold_entry.insert(0, str(disk_space_threshold_mb))
disk_threshold_entry.pack(side=tk.LEFT, padx=(0,5))
set_threshold_button = ttk.Button(disk_frame, text="Set Threshold", command=set_disk_threshold)
set_threshold_button.pack(side=tk.LEFT, padx=5)
# Progress Frame
progress_frame = ttk.Frame(root, padding=(20, 10))
progress_frame.pack(fill='x', padx=20, pady=10)
progress_label = ttk.Label(progress_frame, text="Processing Progress:", style="TLabel")
progress_label.pack(anchor='w')
progress_bar = ttk.Progressbar(progress_frame, orient='horizontal', length=760,
mode='determinate', style="Horizontal.TProgressbar")
progress_bar.pack(pady=5, fill='x')
# Status Label
status_label = ttk.Label(root, text="Ready.", style="Status.TLabel", relief='sunken', anchor='w')
status_label.pack(fill='x', padx=20, pady=(0,10))
# Frame for Control Buttons
control_button_frame = ttk.Frame(root, padding=(20, 0))
control_button_frame.pack(fill='x', padx=20, pady=10)
# Process Button
process_button = ttk.Button(control_button_frame, text="Process Videos", command=process_videos_thread)
process_button.pack(side=tk.LEFT, padx=5, ipadx=10, ipady=5)
# Pause Button
pause_button = ttk.Button(control_button_frame, text="Pause", command=on_pause, state=tk.DISABLED)
pause_button.pack(side=tk.LEFT, padx=5, ipadx=10, ipady=5)
# Resume Button
resume_button = ttk.Button(control_button_frame, text="Resume", command=on_resume, state=tk.DISABLED)
resume_button.pack(side=tk.LEFT, padx=5, ipadx=10, ipady=5)
# Monitor changes in the input_folders list to update the remove button state
def monitor_input_folders():
"""Periodically check if input_folders is empty to enable/disable the remove button."""
update_remove_button()
root.after(500, monitor_input_folders)
monitor_input_folders()
# Run the GUI loop
root.mainloop()
Explanation of the Enhancements
GUI Renaming and Theming:
Title Change: The window title is updated to "DeepAscension Video2Image+".
Color Scheme: Adopted a dark blue and gold color scheme to reflect an Egyptian space theme.
Fonts and Styles: Enhanced fonts and button styles to match the theme.
Concurrent Processing:
ThreadPoolExecutor: Initialized with MAX_CONCURRENT_TASKS = 4 to ensure only four tasks run concurrently.
Task Submission: Tasks are submitted to the executor only when not paused and when there are tasks in the queue.
Pause and Resume Functionality:
Buttons: Added "Pause" and "Resume" buttons.
State Management: The is_paused flag controls whether new tasks are submitted.
Button States: When paused, the "Pause" button is disabled, and the "Resume" button is enabled, and vice versa.
Auto-Pause Based on Disk Space:
Disk Monitoring: Uses the psutil library to monitor disk space at regular intervals (DISK_CHECK_INTERVAL).
Threshold Setting: Users can set the disk space threshold (in MB) at which the application auto-pauses processing.
Auto-Pause Trigger: If available disk space falls below the threshold, processing is automatically paused, and the user is notified.
Enhanced Progress Display:
Progress Bar Styling: Customized the progress bar to match the theme with appropriate colors.
Status Messages: Updated status messages to inform the user about processing states, errors, and completion.
Additional Features:
Disk Space Threshold Input: Added an input field and button for users to set their desired disk space threshold for auto-pausing.
Error Handling: Enhanced error collection and display to inform users about any issues during processing.
Notes
Dependencies: Ensure that the psutil library is installed as it's used for monitoring disk space.
video2image Command: The code assumes that the video2image command is available in your system's PATH. If it's a custom command or script, ensure it's properly installed or provide the absolute path in the subprocess.run call.
Thread Safety: The GUI updates from threads are managed using the queue module and the Tkinter after method to ensure thread safety.
Styling Limitations: Tkinter's styling capabilities are limited compared to other GUI frameworks. For more advanced theming, consider using libraries like ttkbootstrap or integrating images and icons.
Running the Application
Install Dependencies:
bash
pip install psutil
Execute the Script:
bash
python deepascension_video2image.py
Replace deepascension_video2image.py with the filename you've saved the script as.
Usage:
Select Input Folders: Click to add folders containing videos you want to process.
Select Output Folder: Choose the destination folder for the output images.
Set Disk Space Threshold: Enter the minimum free disk space (in MB) before the application auto-pauses processing.
Process Videos: Start the processing. You can pause or resume at any time using the respective buttons.
Feel free to further customize the GUI and functionalities to better suit your needs!