Skip to content

Commit

Permalink
fix fstrings and improve code base
Browse files Browse the repository at this point in the history
  • Loading branch information
Tetrax-10 committed Oct 16, 2024
1 parent c7553d1 commit 5046551
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 64 deletions.
21 changes: 11 additions & 10 deletions preview.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import utils.utils as utils
import tempfile


def process_previews(args, video_files):
temp_folder_path = glob.join_path(tempfile.gettempdir(), "preview-temp")
glob.delete_folder(temp_folder_path)
Expand All @@ -27,19 +28,19 @@ def process_previews(args, video_files):
video_duration = ffmpeg.get_video_duration(video_file)

expected_preview_duration = round(args.segments * args.sduration)
if (expected_preview_duration < round(video_duration)):
ratio = round(video_duration/args.segments, 3)
if expected_preview_duration < round(video_duration):
ratio = round(video_duration / args.segments, 3)
temp_file_contents = ""

video_segment_prog = IncrementalBar(utils.wrap_text(relative_path), max=round(args.segments) + 1, suffix='%(percent)d%%')
video_segment_prog = IncrementalBar(utils.wrap_text(relative_path), max=round(args.segments) + 1, suffix="%(percent)d%%")

count = 0
v_bitrate = ffmpeg.get_video_bitrate(video_file)
a_bitrate = ffmpeg.get_audio_bitrate(video_file)
while count < round(args.segments):
if count == 0:
video_segment_prog.update() # prints the progress bar even before finishing this loop event
start_time = args.skip if count == 0 else round(count*ratio, 3)
start_time = args.skip if count == 0 else round(count * ratio, 3)
ffmpeg.generate_preview_chunck(video_file, start_time, v_bitrate, a_bitrate, args, temp_folder_path, f"{index}-{count}")
temp_file_contents += f"file '{index}-{count}.mp4'\n"
video_segment_prog.next()
Expand All @@ -49,21 +50,21 @@ def process_previews(args, video_files):
with open(temp_file_path, "w") as file:
file.write(temp_file_contents)

if(args.samepath):
if args.samepath:
out = glob.join_path(glob.get_dirname(video_file), args.out)
else:
out = args.out

glob.create_folder(out)
ffmpeg.generate_preview(temp_file_path, f"{glob.join_path(out, f"{file_name} preview")}", args)
ffmpeg.generate_preview(temp_file_path, glob.join_path(out, f"{file_name} preview"), args)

video_segment_prog.next()
video_segment_prog.finish()
else:
if video_duration > 0:
print(colored(f"skiped [Invalid duration ({round(video_duration)}:{expected_preview_duration})]: ", "yellow"), relative_path)
print(colored(f"skipped [Invalid duration ({round(video_duration)}:{expected_preview_duration})]: ", "yellow"), relative_path)
else:
print(colored(f"skiped [Unavailable duration]", "yellow"), relative_path)
print(colored("skipped [Unavailable duration]", "yellow"), relative_path)

is_invalid_duration = True
else:
Expand All @@ -72,8 +73,8 @@ def process_previews(args, video_files):
if is_invalid_duration:
print()
print(colored("Warning codes:", "yellow"))
print(colored(" 1.Unavailable duration: Can't fetch the video duration", "yellow"))
print(colored(" 2.Invalid duration (video duration:expected preview duration): Estimated preview video is equal or longer than the actual video", "yellow"))
print(colored(" 1. Unavailable duration: Can't fetch the video duration", "yellow"))
print(colored(" 2. Invalid duration (video duration:expected preview duration): Estimated preview video is equal or longer than the actual video", "yellow"))

glob.delete_folder(temp_folder_path)

Expand Down
103 changes: 51 additions & 52 deletions utils/commander.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def init():
default_quality = "normal"
default_compression = "slow"

parser = argparse.ArgumentParser(description=f"Generates preview videos and GIFs using FFmpeg CLI in batch. Visit {colored("https://github.com/Tetrax-10/batch-preview-generator#arguments", "blue")} to view detailed docs")
parser = argparse.ArgumentParser(description=f'Generates preview videos and GIFs using FFmpeg CLI in batch. Visit {colored("https://github.com/Tetrax-10/batch-preview-generator#arguments", "blue")} to view detailed docs')
parser.add_argument("-p", "--path", help="Path of the video or folder for batch processing", type=str, metavar="")
parser.add_argument("-o", "--out", help="Output folder for generated previews", type=str, metavar="")
parser.add_argument("-r", "--resolution", help="Preview video resolution", type=int, metavar="")
Expand Down Expand Up @@ -60,106 +60,105 @@ def init():
exit_program()

if not any(value is not None and value is not False for value in vars(args).values()):

def pathCompleter(text, state):
matches = []
for x in globpy.glob(text + '*'):
for x in globpy.glob(text + "*"):
if not os.path.isfile(x):
x += "/"
matches.append(x.replace("\\", "/"))
return matches[state]

try:
readline.set_completer_delims('\t')
readline.set_completer_delims("\t")
readline.parse_and_bind("tab: complete")
readline.set_completer(pathCompleter)

input_path = input(colored(f"Path of the video or folder ({colored(default_path, "yellow")}{f"{colored("): ", "blue")}"}", "blue")).strip()
input_path = input(colored(f'Path of the video or folder ({colored(default_path, "yellow")}{colored("): ", "blue")}', "blue")).strip()
args.path = glob.get_abs_path(glob.correct_path(input_path)) if input_path != "" else default_path

if glob.is_file(args.path):
default_out = glob.join_path(glob.get_dirname(args.path), "previews")
else:
default_out = glob.join_path(args.path, "previews")
input_out = input(colored(f"Output folder ({colored(default_out, "yellow")}{f"{colored("): ", "blue")}"}", "blue")).strip()
input_out = input(colored(f'Output folder ({colored(default_out, "yellow")}{colored("): ", "blue")}', "blue")).strip()
args.out = glob.get_abs_path(glob.correct_path(input_out)) if input_out != "" else default_out

readline.set_completer(None)

input_resolution = input(colored(f"Resolution ({colored(default_resolution, "yellow")}{f"{colored("): ", "blue")}"}", "blue"))
input_resolution = input(colored(f'Resolution ({colored(default_resolution, "yellow")}{colored("): ", "blue")}', "blue"))
args.resolution = int(input_resolution) if input_resolution != "" else default_resolution

input_segments = input(colored(f"No. of segments ({colored(default_segments, "yellow")}{f"{colored("): ", "blue")}"}", "blue"))
input_segments = input(colored(f'No. of segments ({colored(default_segments, "yellow")}{colored("): ", "blue")}', "blue"))
args.segments = int(input_segments) if input_segments != "" else default_segments

input_sduration = input(colored(f"Segment duration ({colored(default_sduration, "yellow")}{f"{colored("): ", "blue")}"}", "blue"))
input_sduration = input(colored(f'Segment duration ({colored(default_sduration, "yellow")}{colored("): ", "blue")}', "blue"))
args.sduration = float(input_sduration) if input_sduration != "" else default_sduration

input_skip = input(colored(f"Skip first n seconds ({colored(default_skip_first_n_sec, "yellow")}{f"{colored("): ", "blue")}"}", "blue"))
input_skip = input(colored(f'Skip first n seconds ({colored(default_skip_first_n_sec, "yellow")}{colored("): ", "blue")}', "blue"))
args.skip = float(input_skip) if input_skip != "" else default_skip_first_n_sec

input_audio = input(colored(f"Audio ({colored("false", "yellow")}{f"{colored("): ", "blue")}"}", "blue")).strip()
args.audio = True if input_audio == "true" else False
input_audio = input(colored(f'Audio ({colored("false", "yellow")}{colored("): ", "blue")}', "blue")).strip()
args.audio = True if input_audio.lower() == "true" else False

if not args.audio:
input_gif = input(colored(f"Gif ({colored("false", "yellow")}{f"{colored("): ", "blue")}"}", "blue")).strip()
args.gif = True if input_gif == "true" else False
input_gif = input(colored(f'Gif ({colored("false", "yellow")}{colored("): ", "blue")}', "blue")).strip()
args.gif = True if input_gif.lower() == "true" else False

input_fps = input(colored(f"FPS ({colored(default_gif_fps if args.gif else default_fps, "yellow")}{f"{colored("): ", "blue")}"}", "blue")).strip()
args.fps = int(input_fps) if input_fps != "" else default_gif_fps if args.gif else default_fps
input_fps = input(colored(f'FPS ({colored(default_gif_fps if args.gif else default_fps, "yellow")}{colored("): ", "blue")}', "blue")).strip()
args.fps = int(input_fps) if input_fps != "" else (default_gif_fps if args.gif else default_fps)

input_quality = input(colored(f"Quality (low/normal/high) ({colored(default_quality, "yellow")}{f"{colored("): ", "blue")}"}", "blue")).strip()
input_quality = input(colored(f'Quality (low/normal/high) ({colored(default_quality, "yellow")}{colored("): ", "blue")}', "blue")).strip()
args.quality = input_quality.lower() if input_quality != "" else default_quality

input_compression = input(colored(f"Compression mode (fast/slow/veryslow) ({colored(default_compression, "yellow")}{f"{colored("): ", "blue")}"}", "blue")).strip()
input_compression = input(colored(f'Compression mode (fast/slow/veryslow) ({colored(default_compression, "yellow")}{colored("): ", "blue")}', "blue")).strip()
args.compression = input_compression.lower() if input_compression != "" else default_compression

input_hwacc = input(colored(f"Hardware acceleration (false/cuda) ({colored("false", "yellow")}{f"{colored("): ", "blue")}"}", "blue")).strip()
args.cuda = True if input_hwacc == "cuda" else False
input_hwacc = input(colored(f'Hardware acceleration (false/cuda) ({colored("false", "yellow")}{colored("): ", "blue")}', "blue")).strip()
args.cuda = True if input_hwacc.lower() == "cuda" else False

os.system('cls')
os.system("cls")
except Exception as err:
print()
if ("invalid literal for int()" in str(err)):
if "invalid literal for int()" in str(err):
print(colored("Invalid input type, That field only accepts numbers", "red"))
else:
print(colored("Invalid input type", "red"))

exit_program()

else:
args.path = glob.get_abs_path(glob.correct_path(args.path)) if args.path != None and args.path != "" else default_path
args.out = glob.correct_path(args.out) if args.out != None and args.out != "" else default_out
args.resolution = args.resolution if args.resolution != None else default_resolution
args.segments = args.segments if args.segments != None else default_segments
args.sduration = args.sduration if args.sduration != None else default_sduration
args.skip = float(args.skip) if args.skip != None else default_skip_first_n_sec
args.audio = args.audio if args.audio != None else default_audio
args.gif = args.gif if args.gif != None else default_gif
args.fps = args.fps if args.fps != None else default_gif_fps if args.gif else default_fps
args.quality = args.quality.lower() if args.quality != None and args.quality != "" else default_quality
args.compression = args.compression.lower() if args.compression != None and args.compression != "" else default_compression
args.path = glob.get_abs_path(glob.correct_path(args.path)) if args.path else default_path
args.out = glob.correct_path(args.out) if args.out else default_out
args.resolution = args.resolution if args.resolution else default_resolution
args.segments = args.segments if args.segments else default_segments
args.sduration = args.sduration if args.sduration else default_sduration
args.skip = float(args.skip) if args.skip else default_skip_first_n_sec
args.audio = args.audio if args.audio else default_audio
args.gif = args.gif if args.gif else default_gif
args.fps = args.fps if args.fps else (default_gif_fps if args.gif else default_fps)
args.quality = args.quality.lower() if args.quality else default_quality
args.compression = args.compression.lower() if args.compression else default_compression

print()

args.version = version

if (args.samepath):
if(default_out != args.out):
if(glob.is_abs(args.out)):
if args.samepath:
if default_out != args.out:
if glob.is_abs(args.out):
print(colored("Outpath should be a relative path when using --samepath", "red"))
exit_program()
else:
args.out = "."

print(args.path, args.out)
else:
args.out = glob.get_abs_path(args.out)

if (args.gif):
if args.gif:
args.audio = False

args.quality = "high" if (args.quality == "high") else ("low" if (args.quality == "low") else default_quality)
args.compression = "veryslow" if (args.compression == "veryslow") else ("fast" if (args.compression == "fast") else default_compression)
args.quality = "high" if args.quality == "high" else ("low" if args.quality == "low" else default_quality)
args.compression = "veryslow" if args.compression == "veryslow" else ("fast" if args.compression == "fast" else default_compression)

shared["args"] = vars(args)
return args
Expand All @@ -168,20 +167,20 @@ def pathCompleter(text, state):
def log_args(args):
print(colored("Configuration:", "yellow", attrs=["bold", "underline"]))
print()
print(colored(f"Input Path:", "blue"), colored(f"{args.path}", "yellow"))
print(colored(f"Output path:", "blue"), colored(f"{args.out}", "yellow"))
print(colored(f"Resolution:", "blue"), colored(f"{args.resolution}", "yellow"))
print(colored(f"No. of Segments:", "blue"), colored(f"{args.segments}", "yellow"))
print(colored(f"Segment Duration:", "blue"), colored(f"{args.sduration}", "yellow"))
print(colored(f"Skip first n sec:", "blue"), colored(f"{args.skip}", "yellow"))
print(colored("Input Path:", "blue"), colored(args.path, "yellow"))
print(colored("Output path:", "blue"), colored(args.out, "yellow"))
print(colored("Resolution:", "blue"), colored(args.resolution, "yellow"))
print(colored("No. of Segments:", "blue"), colored(args.segments, "yellow"))
print(colored("Segment Duration:", "blue"), colored(args.sduration, "yellow"))
print(colored("Skip first n sec:", "blue"), colored(args.skip, "yellow"))
if not args.gif:
print(colored(f"Audio:", "blue"), colored(f"{args.audio}", "yellow"))
print(colored("Audio:", "blue"), colored(args.audio, "yellow"))
if not args.audio:
print(colored(f"Gif:", "blue"), colored(f"{args.gif}", "yellow"))
print(colored(f"FPS:", "blue"), colored(f"{args.fps}", "yellow"))
print(colored(f"Quality:", "blue"), colored(f"{args.quality}", "yellow"))
print(colored(f"Compression mode:", "blue"), colored(f"{args.compression}", "yellow"))
print(colored(f"Hardware acceleration:", "blue"), colored(f"{"cuda" if args.cuda else False}", "yellow"))
print(colored("Gif:", "blue"), colored(args.gif, "yellow"))
print(colored("FPS:", "blue"), colored(args.fps, "yellow"))
print(colored("Quality:", "blue"), colored(args.quality, "yellow"))
print(colored("Compression mode:", "blue"), colored(args.compression, "yellow"))
print(colored("Hardware acceleration:", "blue"), colored("cuda" if args.cuda else "False", "yellow"))
print()


Expand Down
4 changes: 2 additions & 2 deletions utils/ffmpeg.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def generate_preview_chunck(file, start_duration, v_bitrate, a_bitrate, args, te
elif preset == "fast":
preset = "p3"

ffmpeg_cmd = f'ffmpeg -v panic -y -xerror{hw_acc_pre_input} -ss {start_duration} -i "{file}" -t {args.sduration} -max_muxing_queue_size 1024 -c:v {encoder} -vf {scale}=-1:{args.resolution}{video} -profile:v high -level 4.2 -preset {preset} -crf {crf} -r {args.fps} -strict -2 {audio} "{temp_path}/{out_file_name}.mp4"'
ffmpeg_cmd = f'ffmpeg -v panic -y -xerror{hw_acc_pre_input} -ss {start_duration} -i "{file}" -t {args.sduration} -max_muxing_queue_size 1024 -c:v {encoder} -vf {scale}=-2:{args.resolution}{video} -profile:v high -level 4.2 -preset {preset} -crf {crf} -r {args.fps} -strict -2 {audio} "{temp_path}/{out_file_name}.mp4"'

run_cmd(ffmpeg_cmd)

Expand All @@ -126,7 +126,7 @@ def generate_preview(temp_file_path, preview_file_path, args):
if args.quality == "high":
ffmpeg_cmd = f'ffmpeg -v panic -y -f concat -i "{temp_file_path}" -max_muxing_queue_size 1024 -threads 4 -vf "fps={args.fps},scale=-2:{args.resolution}:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" -c:v gif -loop 0 -strict -2 "{preview_file_path}.gif"'
else:
ffmpeg_cmd = f'ffmpeg -v panic -y -f concat -i "{temp_file_path}" -max_muxing_queue_size 1024 -threads 4 -vf "fps={args.fps},scale=-2:{args.resolution}:flags=lanczos" -c:v gif -loop 0 -strict -2 "{preview_file_path}.gif"'
ffmpeg_cmd = f'ffmpeg -v panic -y -f concat -i "{temp_file_path}" -max_muxing_queue_size 1024 -threads 4 -vf "fps={args.fps},scale=-2:{args.resolution}:flags=lanczos" -c:v gif -loop 0 -strict -2 "{preview_file_path}.gif"'
else:
ffmpeg_cmd = f'ffmpeg -v panic -y -f concat -i "{temp_file_path}" -max_muxing_queue_size 1024 -threads 4 -c:v copy -c:a copy -strict -2 "{preview_file_path}.mp4"'

Expand Down

0 comments on commit 5046551

Please sign in to comment.