self.splitter = VideoSplitter()
self._create_widgets()
def _create_widgets(self):
# Main frame
main_frame = ttk.Frame(self.root, padding=10)
main_frame.pack(fill=tk.BOTH, expand=True)
# Input file selection
ttk.Label(main_frame, text="Input Video:").grid(row=0, column=0, sticky=tk.W, pady=5)
self.input_path_var = tk.StringVar()
ttk.Entry(main_frame, textvariable=self.input_path_var, width=50).grid(row=0, column=1, pady=5, padx=5)
ttk.Button(main_frame, text="Browse", command=self._select_input_file).grid(row=0, column=2, pady=5)
# Output folder selection
ttk.Label(main_frame, text="Output Folder:").grid(row=1, column=0, sticky=tk.W, pady=5)
self.output_path_var = tk.StringVar()
ttk.Entry(main_frame, textvariable=self.output_path_var, width=50).grid(row=1, column=1, pady=5, padx=5)
ttk.Button(main_frame, text="Browse", command=self._select_output_folder).grid(row=1, column=2, pady=5)
# Video information frame
info_frame = ttk.LabelFrame(main_frame, text="Video Information", padding=10)
info_frame.grid(row=2, column=0, columnspan=3, sticky=tk.EW, pady=10)
self.duration_var = tk.StringVar(value="Duration: Not available")
ttk.Label(info_frame, textvariable=self.duration_var).grid(row=0, column=0, sticky=tk.W)
self.gpu_var = tk.StringVar(value="GPU: Checking...")
ttk.Label(info_frame, textvariable=self.gpu_var).grid(row=1, column=0, sticky=tk.W)
# Splitting options frame
options_frame = ttk.LabelFrame(main_frame, text="Splitting Options", padding=10)
options_frame.grid(row=3, column=0, columnspan=3, sticky=tk.EW, pady=10)
# Split by duration
self.split_method = tk.StringVar(value="duration")
ttk.Radiobutton(options_frame, text="Split by Duration (seconds)",
variable=self.split_method, value="duration").grid(row=0, column=0, sticky=tk.W)
self.duration_input = ttk.Entry(options_frame, width=10)
self.duration_input.grid(row=0, column=1, padx=5)
self.duration_input.insert(0, "300") # Default 5 minutes
# Split by number of segments
ttk.Radiobutton(options_frame, text="Split into Equal Segments",
variable=self.split_method, value="segments").grid(row=1, column=0, sticky=tk.W)
self.segments_input = ttk.Entry(options_frame, width=10)
self.segments_input.grid(row=1, column=1, padx=5)
self.segments_input.insert(0, "3") # Default 3 segments
# Progress frame
progress_frame = ttk.Frame(main_frame)
progress_frame.grid(row=4, column=0, columnspan=3, sticky=tk.EW, pady=10)
self.progress_var = tk.StringVar(value="Ready")
ttk.Label(progress_frame, textvariable=self.progress_var).grid(row=0, column=0, sticky=tk.W)
self.progress_bar = ttk.Progressbar(progress_frame, mode="indeterminate")
self.progress_bar.grid(row=1, column=0, columnspan=3, sticky=tk.EW, pady=5)
# Action buttons
button_frame = ttk.Frame(main_frame)
button_frame.grid(row=5, column=0, columnspan=3, pady=10)
ttk.Button(button_frame, text="Split Video", command=self._start_splitting).pack(side=tk.LEFT, padx=5)
ttk.Button(button_frame, text="Exit", command=self.root.destroy).pack(side=tk.LEFT, padx=5)
# Update GPU status
self._update_gpu_status()
def _update_gpu_status(self):
if self.splitter.cuda_available:
self.gpu_var.set("GPU Acceleration: Available (NVENC)")
else:
self.gpu_var.set("GPU Acceleration: Not available (using CPU)")
def _select_input_file(self):
file_path = filedialog.askopenfilename(
title="Select Video File",
filetypes=[
("Video files", "*.mp4 *.avi *.mkv *.mov *.wmv"),
("All files", "*.*")
]
)
if file_path:
self.input_path_var.set(file_path)
self.splitter.input_file = file_path
self._update_video_info()
def _select_output_folder(self):
folder_path = filedialog.askdirectory(title="Select Output Folder")
if folder_path:
self.output_path_var.set(folder_path)
self.splitter.output_folder = folder_path
def _update_video_info(self):
if self.splitter.input_file:
duration = self.splitter.get_video_duration()
if duration > 0:
mins, secs = divmod(duration, 60)
hours, mins = divmod(mins, 60)
self.duration_var.set(f"Duration: {int(hours):02d}:{int(mins):02d}:{int(secs):02d}")
else:
self.duration_var.set("Duration: Could not determine")
def _start_splitting(self):
if not self.splitter.input_file:
messagebox.showerror("Error", "Please select an input video file")
return
if not self.splitter.output_folder:
messagebox.showerror("Error", "Please select an output folder")
return
# Start progress bar
self.progress_bar.start()
self.progress_var.set("Processing...")
# Run in a thread to keep GUI responsive
threading_method = self.split_method.get()
if threading_method == "duration":
try:
duration = float(self.duration_input.get())
if duration <= 0:
messagebox.showerror("Error", "Duration must be a positive number")
self.progress_bar.stop()
self.progress_var.set("Ready")
return
threading.Thread(target=self._run_split_by_duration, args=(duration,), daemon=True).start()
except ValueError:
messagebox.showerror("Error", "Invalid duration value")
self.progress_bar.stop()
self.progress_var.set("Ready")
else: # segments
try:
segments = int(self.segments_input.get())
if segments <= 0:
messagebox.showerror("Error", "Number of segments must be a positive integer")
self.progress_bar.stop()
self.progress_var.set("Ready")
return
threading.Thread(target=self._run_split_by_segments, args=(segments,), daemon=True).start()
except ValueError:
messagebox.showerror("Error", "Invalid number of segments")
self.progress_bar.stop()
self.progress_var.set("Ready")
def _run_split_by_duration(self, duration):
success, message = self.splitter.split_by_duration(duration)
self.root.after(0, self._processing_complete, success, message)
def _run_split_by_segments(self, segments):
success, message = self.splitter.split_by_segments(segments)
self.root.after(0, self._processing_complete, success, message)
def _processing_complete(self, success, message):
self.progress_bar.stop()
if success:
self.progress_var.set("Complete")
messagebox.showinfo("Success", message)
else:
self.progress_var.set("Failed")
messagebox.showerror("Error", message)
import os
import sys
import math
import subprocess
from datetime import timedelta
import tkinter as tk
from tkinter import filedialog, ttk, messagebox
import threading
# --- Backend Code (Video Splitter Logic) ---
class VideoSplitter:
def __init__(self):
self.input_file = ""
self.output_folder = ""
self.ffmpeg_path = "ffmpeg" # Assumes ffmpeg is in PATH
self.duration = 0
self.cuda_available = self._check_cuda()
def _check_cuda(self):
"""Check if CUDA/NVENC is available by running an ffmpeg command"""
try:
result = subprocess.run(
[self.ffmpeg_path, "-encoders"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
return "nvenc" in result.stdout.lower()
except Exception:
return False
def get_video_duration(self):
"""Get the duration of the input video file"""
try:
result = subprocess.run(
[self.ffmpeg_path, "-i", self.input_file],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
# FFmpeg outputs to stderr for some reason
output = result.stderr
# Look for duration in the output
for line in output.split('\n'):
if "Duration" in line:
time_str = line.split("Duration: ")[1].split(",")[0].strip()
h, m, s = time_str.split(':')
s, ms = s.split('.')
# Calculate total seconds
total_seconds = int(h) * 3600 + int(m) * 60 + int(s) + float(f"0.{ms}")
self.duration = total_seconds
return total_seconds
return 0
except Exception as e:
print(f"Error getting video duration: {e}")
return 0
def split_by_duration(self, segment_duration):
"""Split video into segments of specified duration in seconds"""
if not self.input_file or not self.output_folder:
return False, "Input file or output folder not specified"
if not self.duration:
self.get_video_duration()
if not self.duration:
return False, "Could not determine video duration"
num_segments = math.ceil(self.duration / segment_duration)
base_name = os.path.splitext(os.path.basename(self.input_file))[0]
for i in range(num_segments):
start_time = i * segment_duration
output_file = os.path.join(self.output_folder, f"{base_name}_part{i+1}.mp4")
# Use GPU acceleration if available
if self.cuda_available:
cmd = [
self.ffmpeg_path, "-hide_banner", "-y",
"-ss", str(timedelta(seconds=start_time)),
"-i", self.input_file,
"-t", str(segment_duration),
"-c:v", "h264_nvenc", "-preset", "p4", "-tune", "hq",
"-b:v", "5M", "-maxrate", "8M", "-bufsize", "10M",
"-c:a", "aac", "-b:a", "192k",
output_file
]
else:
cmd = [
self.ffmpeg_path, "-hide_banner", "-y",
"-ss", str(timedelta(seconds=start_time)),
"-i", self.input_file,
"-t", str(segment_duration),
"-c:v", "libx264", "-preset", "fast", "-crf", "22",
"-c:a", "aac", "-b:a", "192k",
output_file
]
try:
subprocess.run(cmd, check=True)
except subprocess.CalledProcessError as e:
return False, f"Error processing segment {i+1}: {e}"
return True, f"Successfully split video into {num_segments} segments"
def split_by_segments(self, num_segments):
"""Split video into a specified number of equal-duration segments"""
if not self.input_file or not self.output_folder:
return False, "Input file or output folder not specified"
if not self.duration:
self.get_video_duration()
if not self.duration:
return False, "Could not determine video duration"
segment_duration = self.duration / num_segments
base_name = os.path.splitext(os.path.basename(self.input_file))[0]
for i in range(num_segments):
start_time = i * segment_duration
output_file = os.path.join(self.output_folder, f"{base_name}_segment{i+1}.mp4")
# Use GPU acceleration if available
if self.cuda_available:
cmd = [
self.ffmpeg_path, "-hide_banner", "-y",
"-ss", str(timedelta(seconds=start_time)),
"-i", self.input_file,
"-t", str(segment_duration),
"-c:v", "h264_nvenc", "-preset", "p4", "-tune", "hq",
"-b:v", "5M", "-maxrate", "8M", "-bufsize", "10M",
"-c:a", "aac", "-b:a", "192k",
output_file
]
else:
cmd = [
self.ffmpeg_path, "-hide_banner", "-y",
"-ss", str(timedelta(seconds=start_time)),
"-i", self.input_file,
"-t", str(segment_duration),
"-c:v", "libx264", "-preset", "fast", "-crf", "22",
"-c:a", "aac", "-b:a", "192k",
output_file
]
try:
subprocess.run(cmd, check=True)
except subprocess.CalledProcessError as e:
return False, f"Error processing segment {i+1}: {e}"
return True, f"Successfully split video into {num_segments} segments"
# --- Frontend Code (Tkinter GUI) ---
class VideoSplitterGUI:
def __init__(self, root):
self.root = root
self.root.title("Video Splitter")
self.root.geometry("600x500")
self.root.resizable(True, True)
# --- Styling ---
self.primary_color = "#292929" # Dark background
self.secondary_color = "#383838" # Slightly lighter background
self.text_color = "#FFFFFF" # White text
self.accent_color = "#007AFF" # Apple's blue
self.font_family = "San Francisco" #System default on macOS
# ---
self.splitter = VideoSplitter()
self._configure_styling() # Setup styling
self._create_widgets()
def _configure_styling(self):
# Apply Styles
self.root.configure(bg=self.primary_color)
style = ttk.Style()
style.theme_use('default')
# Configure frames
style.configure("TFrame", background=self.primary_color)
style.configure("TLabelframe", background=self.primary_color, borderwidth=0)
style.configure("TLabelframe.Label", background=self.primary_color, foreground=self.text_color, font=(self.font_family, 14, 'bold'))
# Configure labels
style.configure("TLabel", background=self.primary_color, foreground=self.text_color, font=(self.font_family, 12))
# Configure buttons
style.configure("TButton",
font=(self.font_family, 12),
background=self.secondary_color,
foreground=self.text_color,
borderwidth=0,
padding=8,
relief="flat") # Remove border
style.map("TButton",
background=[("active", self.accent_color)], # Hover color
foreground=[("active", self.text_color)])
# Configure Entries
style.configure("TEntry",
fieldbackground=self.secondary_color,
foreground=self.text_color,
font=(self.font_family, 12),
borderwidth=0)
# Configure Radiobuttons
style.configure("TRadiobutton",
background=self.primary_color,
foreground=self.text_color,
font=(self.font_family, 12))
style.map("TRadiobutton",
foreground=[("active", self.text_color)],
background=[("active", self.secondary_color)])
# Configure Progressbar
style.configure("TProgressbar",
background=self.accent_color,
troughcolor=self.secondary_color,
borderwidth=0)
def _create_widgets(self):
# Main frame
main_frame = ttk.Frame(self.root, padding=15)
main_frame.pack(fill=tk.BOTH, expand=True)
# --- Input File Section ---
input_frame = ttk.Frame(main_frame)
input_frame.pack(fill=tk.X, pady=(0,10))
ttk.Label(input_frame, text="Input Video:").pack(side=tk.LEFT, padx=(0,5))
self.input_path_var = tk.StringVar()
input_entry = ttk.Entry(input_frame, textvariable=self.input_path_var)
input_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0,5))
ttk.Button(input_frame, text="Browse", command=self._select_input_file).pack(side=tk.LEFT)
# --- Output Folder Section ---
output_frame = ttk.Frame(main_frame)
output_frame.pack(fill=tk.X, pady=(0,10))
ttk.Label(output_frame, text="Output Folder:").pack(side=tk.LEFT, padx=(0,5))
self.output_path_var = tk.StringVar()
output_entry = ttk.Entry(output_frame, textvariable=self.output_path_var)
output_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0,5))
ttk.Button(output_frame, text="Browse", command=self._select_output_folder).pack(side=tk.LEFT)
# Video information frame
info_frame = ttk.LabelFrame(main_frame, text="Video Information", padding=10)
info_frame.pack(fill=tk.X, pady=(0,10))
self.duration_var = tk.StringVar(value="Duration: Not available")
ttk.Label(info_frame, textvariable=self.duration_var).grid(row=0, column=0, sticky=tk.W, pady=2)
self.gpu_var = tk.StringVar(value="GPU: Checking...")
ttk.Label(info_frame, textvariable=self.gpu_var).grid(row=1, column=0, sticky=tk.W, pady=2)
# Splitting options frame
options_frame = ttk.LabelFrame(main_frame, text="Splitting Options", padding=10)
options_frame.pack(fill=tk.X, pady=(0,10))
# Split by duration
self.split_method = tk.StringVar(value="duration")
ttk.Radiobutton(options_frame, text="Split by Duration (minutes)",
variable=self.split_method, value="duration").grid(row=0, column=0, sticky=tk.W, padx=5, pady=2)
self.duration_input = ttk.Entry(options_frame, width=5)
self.duration_input.grid(row=0, column=1, padx=5, pady=2)
self.duration_input.insert(0, "10") # Default 10 minutes
# Split by number of segments
ttk.Radiobutton(options_frame, text="Split into Equal Segments",
variable=self.split_method, value="segments").grid(row=1, column=0, sticky=tk.W, padx=5, pady=2)
self.segments_input = ttk.Entry(options_frame, width=5)
self.segments_input.grid(row=1, column=1, padx=5, pady=2)
self.segments_input.insert(0, "3") # Default 3 segments
# Progress frame
progress_frame = ttk.Frame(main_frame)
progress_frame.pack(fill=tk.X, pady=(0,10))
self.progress_var = tk.StringVar(value="Ready")
ttk.Label(progress_frame, textvariable=self.progress_var).pack(pady=5)
self.progress_bar = ttk.Progressbar(progress_frame, mode="indeterminate")
self.progress_bar.pack(fill=tk.X, pady=5)
# Action buttons
button_frame = ttk.Frame(main_frame)
button_frame.pack(pady=10)
ttk.Button(button_frame, text="Split Video", command=self._start_splitting).pack(side=tk.LEFT, padx=10)
ttk.Button(button_frame, text="Exit", command=self.root.destroy).pack(side=tk.LEFT, padx=10)
# Update GPU status
self._update_gpu_status()
def _update_gpu_status(self):
if self.splitter.cuda_available:
self.gpu_var.set("GPU Acceleration: Available (NVENC)")
else:
self.gpu_var.set("GPU Acceleration: Not available (using CPU)")
def _select_input_file(self):
file_path = filedialog.askopenfilename(
title="Select Video File",
filetypes=[
("Video files", "*.mp4 *.avi *.mkv *.mov *.wmv"),
("All files", "*.*")
]
)
if file_path:
self.input_path_var.set(file_path)
self.splitter.input_file = file_path
self._update_video_info()
def _select_output_folder(self):
folder_path = filedialog.askdirectory(title="Select Output Folder")
if folder_path:
self.output_path_var.set(folder_path)
self.splitter.output_folder = folder_path
def _update_video_info(self):
if self.splitter.input_file:
duration = self.splitter.get_video_duration()
if duration > 0:
mins, secs = divmod(duration, 60)
hours, mins = divmod(mins, 60)
self.duration_var.set(f"Duration: {int(hours):02d}:{int(mins):02d}:{int(secs):02d}")
else:
self.duration_var.set("Duration: Could not determine")
def _start_splitting(self):
if not self.splitter.input_file:
messagebox.showerror("Error", "Please select an input video file")
return
if not self.splitter.output_folder:
messagebox.showerror("Error", "Please select an output folder")
return
# Start progress bar
self.progress_bar.start()
self.progress_var.set("Processing...")
# Run in a thread to keep GUI responsive
threading_method = self.split_method.get()
if threading_method == "duration":
try:
duration = float(self.duration_input.get()) * 60 #Convert minutes to seconds
if duration <= 0:
messagebox.showerror("Error", "Duration must be a positive number")
self.progress_bar.stop()
self.progress_var.set("Ready")
return
threading.Thread(target=self._run_split_by_duration, args=(duration,), daemon=True).start()
except ValueError:
messagebox.showerror("Error", "Invalid duration value")
self.progress_bar.stop()
self.progress_var.set("Ready")
else: # segments
try:
segments = int(self.segments_input.get())
if segments <= 0:
messagebox.showerror("Error", "Number of segments must be a positive integer")
self.progress_bar.stop()
self.progress_var.set("Ready")
return
threading.Thread(target=self._run_split_by_segments, args=(segments,), daemon=True).start()
except ValueError:
messagebox.showerror("Error", "Invalid number of segments")
self.progress_bar.stop()
self.progress_var.set("Ready")
def _run_split_by_duration(self, duration):
success, message = self.splitter.split_by_duration(duration)
self.root.after(0, self._processing_complete, success, message)
def _run_split_by_segments(self, segments):
success, message = self.splitter.split_by_segments(segments)
self.root.after(0, self._processing_complete, success, message)
def _processing_complete(self, success, message):
self.progress_bar.stop()
if success:
self.progress_var.set("Complete")
messagebox.showinfo("Success", message)
else:
self.progress_var.set("Failed")
messagebox.showerror("Error", message)
if __name__ == "__main__":
root = tk.Tk()
app = VideoSplitterGUI(root)
root.mainloop()