Certainly! Let's address both of your concerns:
- Ensure Output is Written to the Output Folder
- Customize the GUI with an "Egyptian Space Ascension" Theme
1. Ensuring Output is Written to the Output Folder
From your provided code, it appears that the actual processing logic is simulated with a time.sleep loop. To ensure that your processed files are correctly saved to the selected output folder, you need to implement the actual processing logic where the placeholder is.
Steps to Ensure Proper Output:
- Implement Processing Logic: Replace the placeholder processing code with your actual video processing logic.
- Use the
output_folder Variable: Ensure that all processed files are saved to the directory specified by the output_folder variable.
- Handle Exceptions Gracefully: Ensure that any errors during processing are caught and reported to the user.
Example Implementation:
Below is an example where we simulate processing by copying selected video files to the output folder. You should replace the copying logic with your actual video processing code.
import ttkbootstrap as tb
from ttkbootstrap.constants import *
from tkinter import filedialog, messagebox
import os
import threading
import psutil
import sys
import shutil # For file operations
# Initialize the main window
root = tb.Window(themename="darkly") # Changed theme to 'darkly' for a more modern look
root.title("DeepAscension Video2Image+")
root.geometry("900x700") # Increased window size for better UI
# Define any global variables you might be using
input_folders = []
input_videos = []
output_folder = ""
disk_space_threshold_mb = 500 # Example default value
DISK_CHECK_INTERVAL = 5000 # in milliseconds
stop_all_event = threading.Event()
errors = []
is_paused = False
output_folder_var = tb.StringVar()
# Define your UI components here
frame = tb.Frame(root)
frame.pack(fill=BOTH, expand=True)
from ttkbootstrap import Treeview
tree = Treeview(frame, columns=("Path", "Type", "Status"), show='headings')
tree.heading("Path", text="Path")
tree.heading("Type", text="Type")
tree.heading("Status", text="Status")
tree.pack(fill=BOTH, expand=True, padx=10, pady=10)
# Example Progress Bar and Status Label
progress_bar = tb.Progressbar(root, mode='determinate') # Changed to 'determinate' for progress updates
progress_bar.pack(fill=X, padx=10, pady=5)
status_label = tb.Label(root, text="Ready")
status_label.pack(fill=X, padx=10, pady=5)
def on_closing():
"""Handle window closing to ensure all threads are properly terminated."""
if messagebox.askokcancel("Quit", "Do you want to quit?"):
stop_all_event.set()
root.destroy()
def select_input_folders():
"""Allow user to select multiple 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.showwarning("Duplicate Entry", f"The entry '{folder}' is already selected.")
else:
break
def select_input_videos():
"""Allow user to select multiple video files."""
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.showwarning("Duplicate Entry", f"The file '{file}' is already selected.")
def select_output_folder():
"""Allow user to select an output folder and set the output_folder_var."""
global output_folder # Declare global before using
folder = filedialog.askdirectory(title="Select Output Folder")
if folder:
output_folder_var.set(folder)
output_folder = folder # Now safe to modify after declaring global
# Update UI elements that display the output folder
if 'output_label' in globals():
output_label.config(text=f"Output Folder: {folder}")
else:
output_label = tb.Label(root, text=f"Output Folder: {folder}")
output_label.pack(pady=5)
def process_videos():
"""Main function to process videos and folders."""
if not input_folders and not input_videos:
messagebox.showerror("Error", "Please select at least one input folder or video file.")
set_buttons_state(NORMAL)
return
if not output_folder_var.get():
messagebox.showerror("Error", "Please select an output folder.")
set_buttons_state(NORMAL)
return
# Start processing in a separate thread to avoid blocking the UI
processing_thread = threading.Thread(target=run_processing)
processing_thread.start()
def run_processing():
"""Run the actual video processing."""
set_buttons_state(DISABLED)
progress_bar.start()
status_label.config(text="Processing...")
# Initialize progress bar
total_tasks = len(input_folders) + len(input_videos)
if total_tasks == 0:
finalize_processing()
return
progress_bar['maximum'] = total_tasks
progress_bar['value'] = 0
try:
# Process folders
for folder in input_folders:
if stop_all_event.is_set():
raise Exception("Processing stopped by user.")
# Example: Process all video files in the folder
for root_dir, _, files in os.walk(folder):
for file in files:
if file.lower().endswith(('.mp4', '.avi', '.mov', '.mkv', '.flv', '.wmv')):
input_path = os.path.join(root_dir, file)
relative_path = os.path.relpath(input_path, folder)
output_path = os.path.join(output_folder, relative_path)
os.makedirs(os.path.dirname(output_path), exist_ok=True)
# Replace the following line with actual processing logic
shutil.copy2(input_path, output_path) # Example: Copying file
tree.item(input_path, values=(input_path, "Folder Video", "Processed"))
progress_bar['value'] += 1
root.update_idletasks()
# Process individual video files
for video in input_videos:
if stop_all_event.is_set():
raise Exception("Processing stopped by user.")
filename = os.path.basename(video)
output_path = os.path.join(output_folder, filename)
# Replace the following line with actual processing logic
shutil.copy2(video, output_path) # Example: Copying file
tree.item(video, values=(video, "Video File", "Processed"))
progress_bar['value'] += 1
root.update_idletasks()
# Simulate additional processing time if needed
# import time
# time.sleep(2)
# Simulate completion
finalize_processing()
except Exception as e:
errors.append(str(e))
finalize_processing()
def set_disk_threshold():
"""Set the disk space threshold for auto-pausing."""
global disk_space_threshold_mb # Declare global before using
try:
value = int(disk_threshold_entry.get())
if value <= 0:
raise ValueError
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 positive integer for the disk space threshold.")
def finalize_processing():
"""Finalize the processing by updating the UI and displaying any errors."""
set_buttons_state(NORMAL)
progress_bar.stop()
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 monitor_disk_space():
"""Monitor disk space and auto-pause if below threshold."""
if stop_all_event.is_set():
return
output_path = output_folder_var.get()
if not output_path:
# If output path is not set, skip checking
root.after(DISK_CHECK_INTERVAL, monitor_disk_space)
return
try:
usage = psutil.disk_usage(output_path)
free = usage.free
if free < disk_space_threshold_mb * 1024 * 1024:
global is_paused
if not is_paused:
on_pause()
is_paused = True
messagebox.showwarning("Auto-Pause", "Disk space below threshold. Processing has been paused.")
except Exception as e:
messagebox.showerror("Disk Space Error", f"Unable to determine disk space for '{output_path}'.\nError: {e}")
if not stop_all_event.is_set():
root.after(DISK_CHECK_INTERVAL, monitor_disk_space)
def on_pause():
"""Handle pause action."""
global is_paused
# Implement your pause functionality here
is_paused = True
# Example: Update status
status_label.config(text="Processing paused due to low disk space.")
def on_resume():
"""Handle resume action."""
global is_paused
# Implement your resume functionality here
is_paused = False
# Example: Update status
status_label.config(text="Processing resumed.")
# Restart disk monitoring if paused
monitor_disk_space()
def set_buttons_state(state):
"""Enable or disable buttons during processing."""
for widget in controls_frame.winfo_children():
if isinstance(widget, tb.Button):
widget.config(state=state)
# Register the on_closing function to handle window close event
root.protocol("WM_DELETE_WINDOW", on_closing)
# Optionally, start monitoring disk space after the main loop starts
root.after(1000, monitor_disk_space) # Start after 1 second
# Add UI Components for selecting input folders, videos, output folder, and setting disk threshold
controls_frame = tb.Frame(root)
controls_frame.pack(pady=10)
select_folders_button = tb.Button(controls_frame, text="Select Input Folders", command=select_input_folders)
select_folders_button.grid(row=0, column=0, padx=5)
select_videos_button = tb.Button(controls_frame, text="Select Input Videos", command=select_input_videos)
select_videos_button.grid(row=0, column=1, padx=5)
output_button = tb.Button(controls_frame, text="Select Output Folder", command=select_output_folder)
output_button.grid(row=0, column=2, padx=5)
process_button = tb.Button(root, text="Process", command=process_videos)
process_button.pack(pady=10)
disk_threshold_label = tb.Label(root, text="Disk Space Threshold (MB):")
disk_threshold_label.pack(pady=5)
disk_threshold_entry = tb.Entry(root, textvariable=tb.StringVar(value=str(disk_space_threshold_mb)))
disk_threshold_entry.pack(pady=5)
set_threshold_button = tb.Button(root, text="Set Threshold", command=set_disk_threshold)
set_threshold_button.pack(pady=10)
# Run the GUI loop
root.mainloop()
Explanation of Changes:
-
Processing Logic Implementation:
- Copying Files: For demonstration, the code copies video files from input folders or input video selections to the output folder using
shutil.copy2. Replace this with your actual video processing logic.
- Progress Bar Update: Changed the progress bar to
determinate mode and updated its value based on the number of tasks completed.
- Treeview Status Update: After processing each file, the status in the Treeview is updated to "Processed".
-
Thread Safety:
- Ensured that UI updates (
tree.item, progress_bar['value'], etc.) are thread-safe by calling root.update_idletasks() after each update.
-
UI Enhancements:
- Increased the window size for better visibility.
- Changed the theme to
darkly for a more modern look (you can choose any other theme that fits your preference).
2. Customizing the GUI with an "Egyptian Space Ascension" Theme
Creating a unique and visually appealing theme like "Egyptian Space Ascension" involves combining elements inspired by Egyptian aesthetics with futuristic space motifs. Since Tkinter has limited built-in styling capabilities, we'll enhance the GUI by:
-
Using Background Images:
- Adding a background image that reflects the desired theme.
-
Customizing Widgets:
- Applying custom colors, fonts, and styles to widgets.
-
Incorporating Icons and Graphics:
- Using icons or images that represent the theme.
Steps to Customize the GUI:
-
Prepare Assets:
- Background Image: Obtain a high-quality image that represents "Egyptian Space Ascension". Ensure it's appropriately sized for your window (e.g., 900x700 pixels).
- Icons: Gather icons that match the theme for buttons and other widgets.
-
Integrate Background Image:
- Use a
Canvas widget to place the background image.
-
Customize Widget Styles:
- Use custom fonts and colors that align with the theme.
-
Overlay Widgets on Background:
- Position widgets on top of the background image.
Example Implementation:
Here's how you can integrate a background image and customize the GUI accordingly.
import ttkbootstrap as tb
from ttkbootstrap.constants import *
from tkinter import filedialog, messagebox
import os
import threading
import psutil
import sys
import shutil
from PIL import Image, ImageTk # Requires Pillow library
# Initialize the main window
root = tb.Window(themename="darkly") # Base theme
root.title("DeepAscension Video2Image+")
root.geometry("900x700") # Ensure this matches your background image size
# Load background image
BACKGROUND_IMAGE_PATH = "path_to_your_background_image.jpg" # Replace with your image path
try:
bg_image = Image.open(BACKGROUND_IMAGE_PATH)
bg_photo = ImageTk.PhotoImage(bg_image)
except Exception as e:
messagebox.showerror("Image Load Error", f"Failed to load background image.\nError: {e}")
bg_photo = None
# Create a Canvas to place the background
canvas = tb.Canvas(root, width=900, height=700)
canvas.pack(fill="both", expand=True)
if bg_photo:
canvas.create_image(0, 0, image=bg_photo, anchor="nw")
# Create a semi-transparent frame over the background for better readability
overlay_frame = tb.Frame(root, bg="#000000", opacity=0.5)
overlay_window = canvas.create_window(50, 50, anchor="nw", window=overlay_frame, width=800, height=600)
# Define any global variables you might be using
input_folders = []
input_videos = []
output_folder = ""
disk_space_threshold_mb = 500 # Example default value
DISK_CHECK_INTERVAL = 5000 # in milliseconds
stop_all_event = threading.Event()
errors = []
is_paused = False
output_folder_var = tb.StringVar()
# Define your UI components here within the overlay_frame
tree = Treeview(overlay_frame, columns=("Path", "Type", "Status"), show='headings', style="Custom.Treeview")
tree.heading("Path", text="Path")
tree.heading("Type", text="Type")
tree.heading("Status", text="Status")
tree.pack(fill=BOTH, expand=True, padx=10, pady=10)
# Example Progress Bar and Status Label
progress_bar = tb.Progressbar(overlay_frame, mode='determinate', bootstyle="success-10")
progress_bar.pack(fill=X, padx=10, pady=5)
status_label = tb.Label(overlay_frame, text="Ready", font=("Helvetica", 12, "bold"), foreground="#FFD700")
status_label.pack(fill=X, padx=10, pady=5)
def on_closing():
"""Handle window closing to ensure all threads are properly terminated."""
if messagebox.askokcancel("Quit", "Do you want to quit?"):
stop_all_event.set()
root.destroy()
def select_input_folders():
"""Allow user to select multiple 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.showwarning("Duplicate Entry", f"The entry '{folder}' is already selected.")
else:
break
def select_input_videos():
"""Allow user to select multiple video files."""
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.showwarning("Duplicate Entry", f"The file '{file}' is already selected.")
def select_output_folder():
"""Allow user to select an output folder and set the output_folder_var."""
global output_folder # Declare global before using
folder = filedialog.askdirectory(title="Select Output Folder")
if folder:
output_folder_var.set(folder)
output_folder = folder # Now safe to modify after declaring global
# Update UI elements that display the output folder
if 'output_label' in globals():
output_label.config(text=f"Output Folder: {folder}")
else:
output_label = tb.Label(overlay_frame, text=f"Output Folder: {folder}", font=("Helvetica", 10, "italic"), foreground="#87CEEB")
output_label.pack(pady=5)
def process_videos():
"""Main function to process videos and folders."""
if not input_folders and not input_videos:
messagebox.showerror("Error", "Please select at least one input folder or video file.")
set_buttons_state(NORMAL)
return
if not output_folder_var.get():
messagebox.showerror("Error", "Please select an output folder.")
set_buttons_state(NORMAL)
return
# Start processing in a separate thread to avoid blocking the UI
processing_thread = threading.Thread(target=run_processing)
processing_thread.start()
def run_processing():
"""Run the actual video processing."""
set_buttons_state(DISABLED)
progress_bar.start()
status_label.config(text="Processing...")
# Initialize progress bar
total_tasks = len(input_folders) + len(input_videos)
if total_tasks == 0:
finalize_processing()
return
progress_bar['maximum'] = total_tasks
progress_bar['value'] = 0
try:
# Process folders
for folder in input_folders:
if stop_all_event.is_set():
raise Exception("Processing stopped by user.")
# Example: Process all video files in the folder
for root_dir, _, files in os.walk(folder):
for file in files:
if file.lower().endswith(('.mp4', '.avi', '.mov', '.mkv', '.flv', '.wmv')):
input_path = os.path.join(root_dir, file)
relative_path = os.path.relpath(input_path, folder)
output_path = os.path.join(output_folder, relative_path)
os.makedirs(os.path.dirname(output_path), exist_ok=True)
# Replace the following line with actual processing logic
shutil.copy2(input_path, output_path) # Example: Copying file
tree.item(input_path, values=(input_path, "Folder Video", "Processed"))
progress_bar['value'] += 1
root.update_idletasks()
# Process individual video files
for video in input_videos:
if stop_all_event.is_set():
raise Exception("Processing stopped by user.")
filename = os.path.basename(video)
output_path = os.path.join(output_folder, filename)
# Replace the following line with actual processing logic
shutil.copy2(video, output_path) # Example: Copying file
tree.item(video, values=(video, "Video File", "Processed"))
progress_bar['value'] += 1
root.update_idletasks()
# Simulate additional processing time if needed
# import time
# time.sleep(2)
# Simulate completion
finalize_processing()
except Exception as e:
errors.append(str(e))
finalize_processing()
def set_disk_threshold():
"""Set the disk space threshold for auto-pause."""
global disk_space_threshold_mb # Declare global before using
try:
value = int(disk_threshold_entry.get())
if value <= 0:
raise ValueError
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 positive integer for the disk space threshold.")
def finalize_processing():
"""Finalize the processing by updating the UI and displaying any errors."""
set_buttons_state(NORMAL)
progress_bar.stop()
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 monitor_disk_space():
"""Monitor disk space and auto-pause if below threshold."""
if stop_all_event.is_set():
return
output_path = output_folder_var.get()
if not output_path:
# If output path is not set, skip checking
root.after(DISK_CHECK_INTERVAL, monitor_disk_space)
return
try:
usage = psutil.disk_usage(output_path)
free = usage.free
if free < disk_space_threshold_mb * 1024 * 1024:
global is_paused
if not is_paused:
on_pause()
is_paused = True
messagebox.showwarning("Auto-Pause", "Disk space below threshold. Processing has been paused.")
except Exception as e:
messagebox.showerror("Disk Space Error", f"Unable to determine disk space for '{output_path}'.\nError: {e}")
if not stop_all_event.is_set():
root.after(DISK_CHECK_INTERVAL, monitor_disk_space)
def on_pause():
"""Handle pause action."""
global is_paused
# Implement your pause functionality here
is_paused = True
# Example: Update status
status_label.config(text="Processing paused due to low disk space.")
def on_resume():
"""Handle resume action."""
global is_paused
# Implement your resume functionality here
is_paused = False
# Example: Update status
status_label.config(text="Processing resumed.")
# Restart disk monitoring if paused
monitor_disk_space()
def set_buttons_state(state):
"""Enable or disable buttons during processing."""
for widget in controls_frame.winfo_children():
if isinstance(widget, tb.Button):
widget.config(state=state)
# Register the on_closing function to handle window close event
root.protocol("WM_DELETE_WINDOW", on_closing)
# Optionally, start monitoring disk space after the main loop starts
root.after(1000, monitor_disk_space) # Start after 1 second
# Add UI Components for selecting input folders, videos, output folder, and setting disk threshold
controls_frame = tb.Frame(overlay_frame, bg="#000000", padx=10, pady=10)
controls_frame.pack(pady=10)
select_folders_button = tb.Button(controls_frame, text="📁 Input Folders", command=select_input_folders, bootstyle="primary-outline")
select_folders_button.grid(row=0, column=0, padx=5, pady=5)
select_videos_button = tb.Button(controls_frame, text="🎬 Input Videos", command=select_input_videos, bootstyle="primary-outline")
select_videos_button.grid(row=0, column=1, padx=5, pady=5)
output_button = tb.Button(controls_frame, text="📤 Output Folder", command=select_output_folder, bootstyle="primary-outline")
output_button.grid(row=0, column=2, padx=5, pady=5)
process_button = tb.Button(overlay_frame, text="🚀 Process", command=process_videos, bootstyle="success")
process_button.pack(pady=10)
disk_threshold_label = tb.Label(overlay_frame, text="Disk Space Threshold (MB):", font=("Helvetica", 10, "bold"), foreground="#FFD700", bg="#000000")
disk_threshold_label.pack(pady=5)
disk_threshold_entry = tb.Entry(overlay_frame, textvariable=tb.StringVar(value=str(disk_space_threshold_mb)), width=10, font=("Helvetica", 10))
disk_threshold_entry.pack(pady=5)
set_threshold_button = tb.Button(overlay_frame, text="Set Threshold", command=set_disk_threshold, bootstyle="info")
set_threshold_button.pack(pady=10)
# Custom styles for Treeview
style = tb.Style()
style.configure("Custom.Treeview",
background="#2E2E2E",
foreground="#FFFFFF",
fieldbackground="#2E2E2E",
font=("Helvetica", 10),
rowheight=25)
style.map("Custom.Treeview",
background=[('selected', '#1E90FF')])
# Run the GUI loop
root.mainloop()
Explanation of Enhancements:
-
Background Image Integration:
- Pillow Library: Utilized the
Pillow library (PIL) to handle images. Ensure you install it using pip install Pillow.
- Canvas Widget: Created a
Canvas widget to place the background image.
- Overlay Frame: Added a semi-transparent frame over the background to improve readability of widgets.
-
Custom Styled Widgets:
- Fonts and Colors: Applied custom fonts and colors to labels and buttons to align with the "Egyptian Space Ascension" theme. For example, using gold-colored text (
#FFD700) to give an Egyptian touch.
- Icons in Buttons: Added emojis to button texts (e.g., 📁, 🎬, 📤, 🚀) to make them more visually appealing and thematic.
-
Treeview Styling:
- Custom Colors: Configured the Treeview to have a dark background with white text.
- Row Heights: Increased row heights for better visibility.
- Selection Color: Changed the selection color to a vibrant blue (
#1E90FF).
-
Opacity Handling:
- Overlay Frame Opacity: Tkinter doesn’t support widget opacity directly. As a workaround, the background frame is set with a semi-transparent color manually if needed, but Tkinter's basic widgets have limitations. Third-party libraries or more advanced techniques would be required for true opacity effects.
-
Layout Adjustments:
- Consistent Padding: Ensured consistent padding around widgets for a clean look.
- Button Placement: Organized buttons logically with icons for better user experience.
Assets Preparation:
-
Background Image: Choose a high-resolution image that combines Egyptian motifs (like pyramids, hieroglyphics) with space elements (like stars, galaxies). Place this image in your project directory and update the BACKGROUND_IMAGE_PATH accordingly.
-
Icons: Consider replacing emojis with actual icons or images for a more polished look. You can use image files (e.g., PNGs) and integrate them into buttons using the image parameter.
Additional Tips:
-
Custom Fonts: Use fonts that evoke an Egyptian aesthetic, such as hieroglyph-inspired fonts. Ensure the fonts are free for use and properly licensed.
-
Color Scheme: Stick to a consistent color palette that reflects both ancient Egyptian and futuristic space themes. Gold, black, deep blues, and silvers can work well.
-
Responsive Design: Ensure that the GUI scales properly on different screen sizes. You might need to adjust the layout or widget sizes accordingly.
-
Animations and Effects: While Tkinter is limited in terms of animations, you can simulate effects like blinking stars or moving elements by updating images or widget properties periodically.
Final Thoughts:
Creating a unique and thematic GUI enhances user engagement and provides a memorable experience. While Tkinter offers basic styling capabilities, integrating it with ttkbootstrap and Pillow significantly expands your design possibilities. For more advanced designs, consider frameworks like PyQt or Kivy, which offer more flexibility and control over the UI elements.
Feel free to adjust and enhance the provided code further to better fit your vision of the "Egyptian Space Ascension" theme!