roop/core/utils.py

65 lines
2.0 KiB
Python
Raw Normal View History

2023-05-28 17:49:40 +03:00
import os
import shutil
2023-05-29 16:22:16 +03:00
sep = "/"
if os.name == "nt":
2023-05-29 18:54:40 +03:00
sep = "\\"
def path(string):
if sep == "\\":
return string.replace("/", "\\")
return string
2023-05-29 16:22:16 +03:00
2023-05-28 17:49:40 +03:00
def run_command(command, mode="silent"):
if mode == "debug":
return os.system(command)
return os.popen(command).read()
2023-05-28 17:49:40 +03:00
def detect_fps(input_path):
2023-05-29 18:54:40 +03:00
input_path = path(input_path)
2023-05-29 14:10:36 +03:00
output = os.popen(f'ffprobe -v error -select_streams v -of default=noprint_wrappers=1:nokey=1 -show_entries stream=r_frame_rate "{input_path}"').read()
2023-05-28 17:49:40 +03:00
if "/" in output:
try:
2023-05-31 16:17:20 +03:00
return int(output.split("/")[0]) // int(output.split("/")[1]), output
2023-05-28 17:49:40 +03:00
except:
pass
2023-05-31 16:17:20 +03:00
return 30, 30
2023-05-28 17:49:40 +03:00
def set_fps(input_path, output_path, fps):
2023-05-29 18:54:40 +03:00
input_path, output_path = path(input_path), path(output_path)
2023-05-29 14:10:36 +03:00
os.system(f'ffmpeg -i "{input_path}" -filter:v fps=fps={fps} "{output_path}"')
2023-05-28 17:49:40 +03:00
def create_video(video_name, fps, output_dir):
2023-05-29 18:54:40 +03:00
output_dir = path(output_dir)
2023-05-31 16:17:20 +03:00
os.system(f'ffmpeg -framerate "{fps}" -i "{output_dir}{sep}%04d.png" -c:v libx264 -crf 7 -pix_fmt yuv420p -y "{output_dir}{sep}output.mp4"')
2023-05-28 17:49:40 +03:00
def extract_frames(input_path, output_dir):
2023-05-29 18:54:40 +03:00
input_path, output_dir = path(input_path), path(output_dir)
2023-05-29 16:22:16 +03:00
os.system(f'ffmpeg -i "{input_path}" "{output_dir}{sep}%04d.png"')
2023-05-28 17:49:40 +03:00
2023-05-31 16:17:20 +03:00
def add_audio(output_dir, target_path, video, keep_frames, output_file):
2023-05-28 17:49:40 +03:00
video_name = video.split(".")[0]
save_to = output_file if output_file else output_dir + "/swapped-" + video_name + ".mp4"
2023-05-29 18:54:40 +03:00
save_to_ff, output_dir_ff = path(save_to), path(output_dir)
os.system(f'ffmpeg -i "{output_dir_ff}{sep}output.mp4" -i "{output_dir_ff}{sep}{video}" -c:v copy -map 0:v:0 -map 1:a:0 -y "{save_to_ff}"')
2023-05-29 14:10:36 +03:00
if not os.path.isfile(save_to):
2023-05-31 16:19:58 +03:00
shutil.move(f'{output_dir}{sep}output.mp4', save_to)
2023-05-28 17:49:40 +03:00
if not keep_frames:
shutil.rmtree(output_dir)
def is_img(path):
return path.lower().endswith(("png", "jpg", "jpeg", "bmp"))
2023-05-28 17:49:40 +03:00
def rreplace(s, old, new, occurrence):
li = s.rsplit(old, occurrence)
return new.join(li)