Skip to content

Commit

Permalink
updates to binary paths
Browse files Browse the repository at this point in the history
  • Loading branch information
andrei-g99 committed Oct 16, 2024
1 parent 5d56575 commit a73634c
Show file tree
Hide file tree
Showing 3 changed files with 129 additions and 34 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
__pycache__/
*.py[cod]
*$py.class

bin/
# C extensions
*.so

Expand Down
34 changes: 32 additions & 2 deletions run.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,30 @@
from pathlib import Path
import tkinter as tk
from tkinter import filedialog
from tkinter import font
from tkinter import ttk
import re
import os
import sys
from tkinter import messagebox
from tubecut.commands import _download_video, _trim_video

# Get the directory of the current executable or script
if getattr(sys, 'frozen', False): # If running as PyInstaller bundled exe
current_dir = Path(sys.executable).parent # Path of the binaries
else:
current_dir = Path(__file__).parent # For normal development


# Path to the local ffmpeg and yt-dlp binaries in the 'bin' folder
ffmpeg_path = current_dir / 'bin' / 'ffmpeg.exe'
ytdlp_path = current_dir / 'bin' / 'yt-dlp.exe'
print(ffmpeg_path)

# Ensure the binaries are executable (for UNIX-based systems)
os.chmod(ffmpeg_path, 0o755)
os.chmod(ytdlp_path, 0o755)

# Create the main window
root = tk.Tk()
root.title("TubeCut")
Expand Down Expand Up @@ -62,14 +81,25 @@ def on_download():
elif format == formats[3] or format == formats[4] or format == formats[5]:
audio_only = True

_download_video(url=download_url.get(), output_dir=download_output_dir_path.get(), filename=download_output_filename.get(), format=download_format_var.get(), audio_only=audio_only)
_download_video(url=download_url.get(),
output_dir=download_output_dir_path.get(),
filename=download_output_filename.get(),
format=download_format_var.get(),
ffmpeg_path=ffmpeg_path,
audio_only=audio_only)
messagebox.showinfo("Success", "Video downloaded successfully!")
except Exception as e:
messagebox.showerror("Error", f"Failed to download video: {str(e)}")

def on_trim():
try:
_trim_video(file_path=cut_file_path.get(), output_dir=cut_output_dir_path.get(), start_time=start_time.get(), end_time=end_time.get(), output_filename=cut_output_filename.get(), output_format=cut_format_var.get())
_trim_video(file_path=cut_file_path.get(),
output_dir=cut_output_dir_path.get(),
start_time=start_time.get(),
end_time=end_time.get(),
output_filename=cut_output_filename.get(),
ffmpeg_path=ffmpeg_path,
output_format=cut_format_var.get())
messagebox.showinfo("Success", "Video trimmed successfully!")
except Exception as e:
messagebox.showerror("Error", f"Failed to trim video: {str(e)}")
Expand Down
127 changes: 96 additions & 31 deletions tubecut/commands.py
Original file line number Diff line number Diff line change
@@ -1,58 +1,123 @@
import subprocess
import os
from pathlib import Path
import yt_dlp
import ffmpeg
import subprocess
from pathlib import Path

def _download_video(url, output_dir, filename, format="mp4", audio_only=False):
# Adjust the format options based on whether it's video or audio
def _download_video(url, output_dir, filename, ffmpeg_path, format="mp4", audio_only=False):
if audio_only:
# If audio_only is True, extract audio and save as MP3 (or another format)
ydl_opts = {
'format': 'bestaudio/best', # Download best audio
'outtmpl': f'{output_dir}/{filename}.%(ext)s', # Use extension of the extracted audio
'format': 'bestaudio/best',
'outtmpl': f'{output_dir}/{filename}.%(ext)s',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': format, # Convert to the desired audio format (e.g., 'mp3', 'm4a', 'opus')
'preferredquality': '192', # Audio quality (e.g., 192 kbps)
'preferredcodec': format,
'preferredquality': '192',
}],
'ffmpeg_location': str(ffmpeg_path), # Use local ffmpeg binary
}
else:
# If downloading video, select the best video and audio and merge into a single file
ydl_opts = {
'format': f'bestvideo[ext={format}]+bestaudio[ext=m4a]/best[ext={format}]', # Download best video with chosen format
'outtmpl': f'{output_dir}/{filename}.%(ext)s', # Output filename
'format': f'bestvideo[ext={format}]+bestaudio[ext=m4a]/best[ext={format}]',
'outtmpl': f'{output_dir}/{filename}.%(ext)s',
'postprocessors': [{
'key': 'FFmpegVideoConvertor',
'preferedformat': format, # Convert to the desired video format if needed
'preferedformat': format,
}],
'ffmpeg_location': str(ffmpeg_path), # Use local ffmpeg binary
}

# Perform the download
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
print(f"Download complete: {filename}.{format}")

def _trim_video(file_path, output_dir, start_time, end_time, output_filename, output_format):
def _trim_video(file_path, output_dir, start_time, end_time, output_filename, output_format, ffmpeg_path):

if (start_time == "") and (end_time == ""):
raise Exception('Start Time and End Time cannot be both empty.')
raise ValueError('Start Time and End Time cannot be both empty.')

# Ensure the output directory exists
if not os.path.exists(output_dir):
os.makedirs(output_dir)
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)

# Construct the full output file path and infer the output format
output_file = os.path.join(output_dir, f'{output_filename}.{output_format}')

# Trim the input file based on start_time and end_time
input_args = {}
if start_time != "":
input_args['ss'] = start_time
# Construct the full output file path
output_file = output_dir / f'{output_filename}.{output_format}'

command = [str(ffmpeg_path), '-i', str(file_path)]

# ffmpeg trimming with input arguments
if start_time == '':
command.extend(['-ss', '0'])
else:
command.extend(['-ss', start_time])
if end_time != "":
input_args['to'] = end_time
command.extend(['-to', end_time])

command.append(str(output_file))

try:
# Use the local ffmpeg binary
subprocess.run(command, check=True)
print(f"Trimmed video/audio saved to: {output_file}")
except subprocess.CalledProcessError as e:
print(f"Error trimming video: {e}")




# import subprocess
# import os
# from pathlib import Path
# import yt_dlp
# import ffmpeg

# def _download_video(url, output_dir, filename, format="mp4", audio_only=False):
# # Adjust the format options based on whether it's video or audio
# if audio_only:
# # If audio_only is True, extract audio and save as MP3 (or another format)
# ydl_opts = {
# 'format': 'bestaudio/best', # Download best audio
# 'outtmpl': f'{output_dir}/{filename}.%(ext)s', # Use extension of the extracted audio
# 'postprocessors': [{
# 'key': 'FFmpegExtractAudio',
# 'preferredcodec': format, # Convert to the desired audio format (e.g., 'mp3', 'm4a', 'opus')
# 'preferredquality': '192', # Audio quality (e.g., 192 kbps)
# }],
# }
# else:
# # If downloading video, select the best video and audio and merge into a single file
# ydl_opts = {
# 'format': f'bestvideo[ext={format}]+bestaudio[ext=m4a]/best[ext={format}]', # Download best video with chosen format
# 'outtmpl': f'{output_dir}/{filename}.%(ext)s', # Output filename
# 'postprocessors': [{
# 'key': 'FFmpegVideoConvertor',
# 'preferedformat': format, # Convert to the desired video format if needed
# }],
# }

# # Perform the download
# with yt_dlp.YoutubeDL(ydl_opts) as ydl:
# ydl.download([url])
# print(f"Download complete: {filename}.{format}")

# def _trim_video(file_path, output_dir, start_time, end_time, output_filename, output_format):
# if (start_time == "") and (end_time == ""):
# raise Exception('Start Time and End Time cannot be both empty.')

# # Ensure the output directory exists
# if not os.path.exists(output_dir):
# os.makedirs(output_dir)

# # Construct the full output file path and infer the output format
# output_file = os.path.join(output_dir, f'{output_filename}.{output_format}')

# # Trim the input file based on start_time and end_time
# input_args = {}
# if start_time != "":
# input_args['ss'] = start_time
# if end_time != "":
# input_args['to'] = end_time

# ffmpeg trimming with input arguments and specifying output format
ffmpeg.input(file_path, **input_args).output(output_file, format=output_format).run()
# # ffmpeg trimming with input arguments and specifying output format
# ffmpeg.input(file_path, **input_args).output(output_file, format=output_format).run()

print(f"Trimmed video/audio saved to: {output_file}")
# print(f"Trimmed video/audio saved to: {output_file}")

0 comments on commit a73634c

Please sign in to comment.