#!/usr/bin/env python3 """ Video Cutter - Cut out unwanted sections from video files. Uses ffmpeg to remove specified time ranges from video files. GUI built with tkinter, with built-in file browser โ€” no external dependencies. """ import tkinter as tk from tkinter import ttk, messagebox import subprocess import os import re from datetime import datetime VIDEO_EXTENSIONS = { '.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.m4v', '.mpg', '.mpeg', '.3gp', '.ogv', '.ts' } def format_time(seconds): """Format seconds as HH:MM:SS.microseconds for ffmpeg.""" if seconds is None or seconds < 0: return "00:00:00" hours = int(seconds // 3600) minutes = int((seconds % 3600) // 60) secs = seconds % 60 return f"{hours:02d}:{minutes:02d}:{secs:06.3f}" def parse_time(time_str): """Parse time string in various formats to seconds.""" time_str = time_str.strip().lower() hhmmss_pattern = r'(\d+):(\d{1,2})(?::(\d{1,2})(?:\.(\d+))?)?' match = re.match(hhmmss_pattern, time_str) if match: h = int(match.group(1)) m = int(match.group(2)) s = int(match.group(3)) if match.group(3) else 0 ms = 0 if match.group(4): ms_str = match.group(4)[:6].ljust(6, '0') ms = int(ms_str) return h * 3600 + m * 60 + s + ms / 1000000 try: return float(time_str) except ValueError: pass raise ValueError(f"Cannot parse time: {time_str}") def get_video_duration(filepath): """Get video duration using ffprobe.""" try: cmd = [ 'ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', filepath ] result = subprocess.run(cmd, capture_output=True, text=True, check=True, timeout=30) return float(result.stdout.strip()) except subprocess.SubprocessError as e: raise RuntimeError(f"ffprobe error: {e}") def has_audio_stream(filepath): """Check if video has an audio stream.""" try: cmd = [ 'ffprobe', '-v', 'error', '-select_streams', 'a', '-show_entries', 'stream=codec_type', '-of', 'csv=p=0', filepath ] result = subprocess.run(cmd, capture_output=True, text=True, check=True, timeout=30) return result.stdout.strip() != '' except subprocess.SubprocessError: return False def cut_video(input_path, output_path, cut_start, cut_end, video_duration, quality="Good (fast)"): """Cut out the section from cut_start to cut_end using segment files + concat.""" import tempfile if cut_start <= 0 and cut_end >= video_duration: raise RuntimeError("Would remove entire video!") segments = [] if cut_start > 0: segments.append({'start': 0, 'end': cut_start}) if cut_end < video_duration: segments.append({'start': cut_end, 'end': video_duration}) if not segments: raise RuntimeError("No content to keep!") has_audio = has_audio_stream(input_path) # Create a temp directory for segment files with tempfile.TemporaryDirectory() as tmpdir: segment_files = [] file_list = os.path.join(tmpdir, 'list.txt') for i, seg in enumerate(segments): seg_file = os.path.join(tmpdir, f'segment_{i}.mp4') segment_files.append(seg_file) seg_duration = seg['end'] - seg['start'] seg_start = seg['start'] cmd = ['ffmpeg', '-y', '-ss', f'{seg_start:.3f}', '-i', input_path, '-t', f'{seg_duration:.3f}'] qmap = { 'Smallest': {'preset': 'veryfast', 'crf': '30', 'ab': '64k'}, 'Compact': {'preset': 'fast', 'crf': '26', 'ab': '96k'}, 'Balanced': {'preset': 'medium', 'crf': '24', 'ab': '128k'}, 'Good': {'preset': 'slower', 'crf': '22', 'ab': '128k'}, } q = qmap[quality] cmd.extend(['-c:v', 'libx264', '-preset', q['preset'], '-crf', q['crf']]) if has_audio: cmd.extend(['-c:a', 'aac', '-b:a', q['ab']]) else: cmd.append('-an') # no audio cmd.extend(['-movflags', '+faststart', seg_file]) result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode != 0: raise RuntimeError(f"ffmpeg failed on segment {i}:\n{result.stderr}") # Build concat list file with open(file_list, 'w') as f: for sf in segment_files: f.write(f"file '{sf}'\n") # Concatenate cmd = ['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', file_list, '-c', 'copy'] # Copy audio codec if present if has_audio: cmd.extend(['-c:a', 'aac']) cmd.append(output_path) result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode != 0: raise RuntimeError(f"ffmpeg concat error:\n{result.stderr}") return True class FileBrowserPanel(ttk.Frame): """Built-in file browser panel โ€” embedded directly in the main window.""" def __init__(self, parent, on_select=None): super().__init__(parent, padding=5) self.on_select = on_select self.current_dir = os.path.expanduser("~") self.last_browsed_dir = os.path.expanduser("~") self._build_ui() self._refresh() def _build_ui(self): # --- Navigation bar --- nav = ttk.Frame(self) nav.pack(fill='x') ttk.Button(nav, text="โ†‘ Up", command=self._go_up, width=6).pack(side='left', padx=1) ttk.Button(nav, text="Home", command=self._go_home, width=6).pack(side='left', padx=1) ttk.Button(nav, text="Desktop", command=lambda: self._navigate("~/Desktop"), width=8).pack(side='left', padx=1) self.path_var = tk.StringVar(value=self.current_dir) ttk.Entry(nav, textvariable=self.path_var, width=45).pack(side='left', fill='x', expand=True, padx=3) ttk.Button(nav, text="Go", command=self._go_click, width=4).pack(side='left') ttk.Label(nav, text="Filter:").pack(side='right', padx=(5, 2)) self.filter_var = tk.StringVar() self.filter_var.trace_add('write', lambda *a: self._refresh()) ttk.Entry(nav, textvariable=self.filter_var, width=15).pack(side='right') # --- Quick-access bar --- qa = ttk.Frame(self) qa.pack(fill='x') ttk.Label(qa, text="Quick:", style='Info.TLabel').pack(side='left') locations = [ ("Videos", "~/Videos"), ("Downloads", "~/Downloads"), ("SSD", "/home/bob"), ("NAS", "/mnt/seagateNAS"), ] for label, path in locations: ttk.Button(qa, text=label, command=lambda p=path: self._navigate(p), width=7).pack(side='left', padx=1) # --- Tree --- tree_frame = ttk.Frame(self) tree_frame.pack(fill='both', expand=True, pady=3) vs = ttk.Scrollbar(tree_frame) vs.pack(side='right', fill='y') hs = ttk.Scrollbar(tree_frame, orient='horizontal') hs.pack(side='bottom', fill='x') self.tree = ttk.Treeview(tree_frame, columns=('size', 'modified'), show='headings', yscrollcommand=vs.set, xscrollcommand=hs.set, height=14) self.tree.pack(fill='both', expand=True) vs.config(command=self.tree.yview) hs.config(command=self.tree.xview) self.tree.heading('#0', text='Name', anchor='w') self.tree.heading('size', text='Size', anchor='e') self.tree.heading('modified', text='Modified', anchor='w') self.tree.column('#0', width=500, minwidth=200) self.tree.column('size', width=100) self.tree.column('modified', width=170) self.tree.bind('', self._on_double) self.tree.bind('', self._on_double) # --- Status bar --- self.status = ttk.Label(self, text="Ready", style='Info.TLabel') self.status.pack(fill='x', pady=(2, 0)) def _refresh(self, filter_text=None): for item in self.tree.get_children(): self.tree.delete(item) cur = self.current_dir if not os.path.isdir(cur): cur = os.path.dirname(cur) if not os.path.isdir(cur): cur = os.path.expanduser("~") self.current_dir = cur self.path_var.set(cur) filter_text = filter_text or self.filter_var.get().strip().lower() try: entries = [] for item in os.scandir(cur): try: if item.name.startswith('.'): continue if filter_text and filter_text not in item.name.lower(): continue entries.append(item) except (PermissionError, OSError): continue dirs = [] files = [] for item in entries: try: if item.is_dir(follow_symlinks=False): dirs.append((item.name, item, True)) else: files.append((item.name, item, False)) except (PermissionError, OSError): continue dirs.sort(key=lambda x: x[0].lower()) files.sort(key=lambda x: x[0].lower()) for name, entry, is_dir in dirs + files: icon = "๐Ÿ“" if is_dir else "๐ŸŽฌ" if os.path.splitext(name)[1].lower() in VIDEO_EXTENSIONS else "๐Ÿ“„" if is_dir: size_str = "โ€”" mod_str = "โ€”" else: try: size_str = self._fmt_size(entry.stat().st_size) except OSError: size_str = "?" try: mod_str = datetime.fromtimestamp(entry.stat().st_mtime).strftime("%Y-%m-%d %H:%M") except OSError: mod_str = "?" self.tree.insert('', 'end', values=(f"{icon} {name}", size_str, mod_str)) total = len(dirs) + len(files) self.status.config(text=f"{total} items | {cur}") except Exception as e: self.status.config(text=f"Error: {e}") def _fmt_size(self, size): for unit in ('B', 'KB', 'MB', 'GB'): if size < 1024: return f"{size:.0f} {unit}" if unit == 'B' else f"{size:.1f} {unit}" size /= 1024 def _on_double(self, event=None): sel = self.tree.selection() if not sel: return item = self.tree.item(sel[0]) name = item['values'][0].replace('๐Ÿ“ ', '').replace('๐ŸŽฌ ', '').replace('๐Ÿ“„ ', '') path = os.path.join(self.current_dir, name) if os.path.isdir(path): self._navigate(path) else: self.last_browsed_dir = self.current_dir if self.on_select: self.on_select(path) def _navigate(self, path): path = os.path.normpath(path) if os.path.isdir(path): self.current_dir = path self._refresh() def _go_up(self): p = os.path.dirname(self.current_dir) if p != self.current_dir: self._navigate(p) def _go_home(self): self._navigate(os.path.expanduser("~")) def _go_click(self): p = self.path_var.get().strip() if p: self._navigate(p) class VideoCutterApp: def __init__(self, root): self.root = root self.root.title("๐ŸŽฌ Video Cutter") self.root.geometry("780x1080") self.root.minsize(780, 1080) self.root.resizable(True, True) self.root.update_idletasks() self.input_path = tk.StringVar() self.cut_start = tk.StringVar() self.cut_end = tk.StringVar() self.video_duration = 0 self.output_path = tk.StringVar() self._build_ui() def _build_ui(self): main = ttk.Frame(self.root, padding=15) main.pack(fill='both', expand=True) # Title ttk.Label(main, text="๐ŸŽฌ Video Cutter", font=('Helvetica', 18, 'bold')).pack(pady=(0, 10)) # === VIDEO BROWSER PANEL === self.browser = FileBrowserPanel(main, on_select=self._on_file_selected) self.browser.pack(fill='x', expand=False) self.browser.pack(fill='both', expand=True) # Divider ttk.Separator(main, orient='horizontal').pack(fill='x', pady=8) # Selected file info info = ttk.Frame(main) info.pack(fill='x') ttk.Label(info, text="Selected video:").pack(side='left') ttk.Entry(info, textvariable=self.input_path, width=65).pack(side='left', padx=5, fill='x', expand=True) self.dur_lbl = ttk.Label(info, text="", style='Info.TLabel') self.dur_lbl.pack(side='left', padx=(10, 0)) # === CUT CONFIG === cut_frame = ttk.LabelFrame(main, text="Remove This Section", padding=8) cut_frame.pack(fill='x', pady=(8, 8)) row = ttk.Frame(cut_frame) row.pack(fill='x') ttk.Label(row, text="Start:", width=8).pack(side='left') start_f = ttk.Frame(row) start_f.pack(side='left', padx=5, expand=True, fill='x') ttk.Entry(start_f, textvariable=self.cut_start, width=20).pack(side='left', fill='x', expand=True) ttk.Label(start_f, text="HH:MM:SS", style='Info.TLabel').pack(side='left', padx=(4, 0)) ttk.Label(row, text="End:", width=5).pack(side='left', padx=(15, 0)) end_f = ttk.Frame(row) end_f.pack(side='left', padx=5, expand=True, fill='x') ttk.Entry(end_f, textvariable=self.cut_end, width=20).pack(side='left', fill='x', expand=True) ttk.Label(end_f, text="HH:MM:SS", style='Info.TLabel').pack(side='left', padx=(4, 0)) ttk.Label(cut_frame, text="โš  This section will be REMOVED from the video", style='Info.TLabel', foreground='red').pack(pady=(5, 0)) # === OUTPUT === out_frame = ttk.LabelFrame(main, text="Output File", padding=8) out_frame.pack(fill='x', pady=(0, 8)) ttk.Entry(out_frame, textvariable=self.output_path, width=70).pack(fill='x', padx=5, pady=2) # Quality selector q_frame = ttk.Frame(out_frame) q_frame.pack(fill='x', padx=5, pady=(2, 4)) ttk.Label(q_frame, text="Quality: โ†’ file size").pack(side='left') self.quality_var = tk.StringVar(value="Smallest") quality_opts = ["Smallest", "Compact", "Balanced", "Good"] ttk.OptionMenu(q_frame, self.quality_var, quality_opts[0], *quality_opts).pack(side='left', padx=4) ttk.Label(q_frame, text="Smallest โ‰ˆ 40% ยท Compact โ‰ˆ 90% ยท Balanced โ‰ˆ 110% ยท Good โ‰ˆ 125% (of proportional)", style='Info.TLabel', foreground='#339933').pack(side='left', padx=(5, 0)) ttk.Label(out_frame, text="Re-encoded for maximum compatibility. Original file is NOT modified.", style='Info.TLabel', foreground='#555').pack() self.size_hint = ttk.Label(out_frame, text="", style='Info.TLabel', foreground='#339933') self.size_hint.pack() # === HELP === ttk.Label(main, text="๐Ÿ’ก Double-click folders to navigate ยท Double-click a video to select it ยท " "Type a filter to search names ยท Click Quick buttons for fast access", style='Info.TLabel', justify='center').pack(pady=(0, 5)) # === BUTTONS === btns = ttk.Frame(main) btns.pack(fill='x') ttk.Button(btns, text="โœ‚๏ธ Cut Video!", command=self.cut_video, width=18).pack(side='left', expand=True, padx=5) ttk.Button(btns, text="Reset", command=self.reset, width=10).pack(side='left', expand=True, padx=5) ttk.Button(btns, text="Open Output Folder", command=self.open_output_folder, width=20).pack(side='left', expand=True, padx=5) self.progress = ttk.Progressbar(main, mode='indeterminate') self.progress.pack(fill='x', pady=(8, 0)) # Re-estimate size when times or quality change self.cut_start.trace_add('write', lambda *a: self.estimate_output_size(self.input_path.get())) self.cut_end.trace_add('write', lambda *a: self.estimate_output_size(self.input_path.get())) self.quality_var.trace_add('write', lambda *a: self.estimate_output_size(self.input_path.get())) def _on_file_selected(self, filepath): self.input_path.set(filepath) self.load_video_info(filepath) base = os.path.splitext(filepath)[0] ext = os.path.splitext(filepath)[1] self.output_path.set(f"{base}_edited{ext}") self.estimate_output_size(filepath) # Scroll tree to selected item sel = self.browser.tree.selection() if sel: self.browser.tree.see(sel[0]) self.browser.tree.focus(sel[0]) self.browser.tree.selection_set(sel[0]) def estimate_output_size(self, filepath): """Estimate output file size based on original bitrate and cut duration.""" try: r = subprocess.run( ['ffprobe', '-v', 'error', '-show_entries', 'stream=bit_rate,codec_type', '-of', 'csv=p=0', filepath], capture_output=True, text=True, timeout=10 ) if r.returncode == 0 and r.stdout.strip(): total_bitrate = sum(int(line.split(',')[0]) for line in r.stdout.strip().split('\n')) else: total_bitrate = 5_000_000 try: cut_start = parse_time(self.cut_start.get()) except ValueError: cut_start = 0 try: cut_end = parse_time(self.cut_end.get()) except ValueError: cut_end = 0 kept = self.video_duration - (cut_end - cut_start) kept = max(0, kept) cut_ratio = kept / self.video_duration if self.video_duration > 0 else 1.0 cut_ratio = max(0.1, min(1.0, cut_ratio)) est_bytes = total_bitrate * kept / 8 # Adjust estimate based on quality setting qmap = { 'Smallest': 0.42, 'Compact': 0.88, 'Balanced': 1.09, 'Good': 1.25 } multiplier = qmap.get(self.quality_var.get(), 0.42) est_bytes *= multiplier est_mb = est_bytes / (1024 * 1024) orig_mb = os.path.getsize(filepath) / (1024 * 1024) self.size_hint.config(text=f"๐Ÿ“Š Original: {orig_mb:.0f} MB โ†’ ~{est_mb:.0f} MB") except Exception: pass def load_video_info(self, filepath): try: duration = get_video_duration(filepath) self.video_duration = duration self.dur_lbl.config(text=f"โฑ {format_time(duration)}") except Exception as e: messagebox.showerror("Error", f"Could not read video info:\n{e}") self.dur_lbl.config(text="โฑ Error") def cut_video(self): input_path = self.input_path.get().strip() start_str = self.cut_start.get().strip() end_str = self.cut_end.get().strip() output_path = self.output_path.get().strip() if not input_path: messagebox.showerror("Error", "Select a video file from the browser above.") return if not os.path.exists(input_path): messagebox.showerror("Error", f"File not found:\n{input_path}") return if not start_str or not end_str: messagebox.showerror("Error", "Enter both start and end times.") return try: start = parse_time(start_str) except ValueError: messagebox.showerror("Error", f"Invalid start time: {start_str}") return try: end = parse_time(end_str) except ValueError: messagebox.showerror("Error", f"Invalid end time: {end_str}") return if start >= end: messagebox.showerror("Error", "Start must be before end.") return if end > self.video_duration: if not messagebox.askyesno("Warning", f"End time ({format_time(end)}) exceeds duration ({format_time(self.video_duration)}).\nProceed?"): return if not output_path: messagebox.showerror("Error", "Specify an output file.") return if not messagebox.askyesno("Confirm", f"Remove {format_time(start)} โ€“ {format_time(end)} from:\n {os.path.basename(input_path)}\n\n" f"Save as:\n {os.path.basename(output_path)}\n\n" f"Quality: {self.quality_var.get()}\n" f"โš  This will re-encode the video.\nOriginal is NOT modified."): return self.progress.start(10) self.root.update() try: cut_video(input_path, output_path, start, end, self.video_duration, self.quality_var.get()) self.progress.stop() messagebox.showinfo("Done", f"Video cut complete!\n\nRemoved: {format_time(start)} to {format_time(end)}\nSaved to: {output_path}") except Exception as e: self.progress.stop() messagebox.showerror("Error", f"Failed:\n{e}") def reset(self): self.input_path.set("") self.cut_start.set("") self.cut_end.set("") self.output_path.set("") self.video_duration = 0 self.dur_lbl.config(text="") self.size_hint.config(text="") def open_output_folder(self): path = self.output_path.get().strip() folder = os.path.dirname(path) or '.' if os.path.isdir(folder): os.system(f'xdg-open "{folder}" &') else: messagebox.showinfo("Info", "Specify an output file path first.") def main(): root = tk.Tk() # Set app icon if available try: root.iconname("Video Cutter") except Exception: pass app = VideoCutterApp(root) root.mainloop() if __name__ == "__main__": main()