Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- import argparse
- import os
- import logging
- import subprocess
- logging.basicConfig(level=logging.DEBUG)
- args = ""
- #HEY YOU! This was meant to convert primarily from mkv to mp4 to be played back on a jailbroken Playstation 3.
- #You can edit the `command` variable in the `ffmpeg_convert_standard` function below to remove the junk if you know what you're doing.
- def parse_arguments():
- filename = __file__.split("/")[-1]
- usage = f"""{filename} -i input_dir -ie [input extensions] -oe output_ext -o output_dir\n ex: {filename} -i ./input -ie mkv ogg avi -oe mp4 -o ./output"""
- parser = argparse.ArgumentParser(description="Convert media files from one type to another while maintaining the directory structure", usage=usage)
- parser.add_argument("-i", "--in_dir", metavar="dir", default="", type=str, help="Directory containing media files", required=True)
- parser.add_argument("-ie", "--in_exts", metavar="ext", nargs="+", type=str, help="Input filename extensions", required=True)
- parser.add_argument("-oe", "--out_ext", metavar="ext", type=str, help="Output filename extension", required=True)
- parser.add_argument("-o", "--out_dir", metavar="dir", type=str, help="Directory in which to place the converted media files", required=True)
- parser.add_argument("-d", "--debug", action="store_true", help="Enable debug logging")
- parser.add_argument("-ns", "--no_sanatize", action="store_true", help="Do not remove symbols from the output file path")
- parser.add_argument("-f", "--overwrite", action="store_true", help="Make ffmpeg overwrite video files which already exist")
- args = parser.parse_args()
- #Need to make sure that the paths end in a slash for the sake of consistancy
- args.in_dir = add_slash(args.in_dir)
- args.out_dir = add_slash(args.out_dir)
- return args
- def overwrite():
- global args
- if args.overwrite:
- return "-y"
- else:
- return "-n"
- def is_input_file(filename):
- global args
- ext = filename.split(".")[-1]
- if ext in args.in_exts:
- return True
- else:
- return False
- def add_slash(path):
- if not path[-1] == "/":
- path += "/"
- return path
- """Iterate through all folders in a path and attempt to create them so the output folder structure is correct"""
- def ensure_path(path):
- path = add_slash(path)
- arr = path.split("/")
- for i in range(len(arr)):
- try:
- tmp = "/".join(arr[0:i])
- tmp = add_slash(tmp)
- os.mkdir(tmp)
- except Exception as e:
- if args.debug:
- logging.warn(f"[WARN] ensure_path: {e}")
- continue
- def name_sanitize(string):
- if args.no_sanatize: return string
- disallow = ["\"","!","?"]
- out = string
- for symbol in disallow:
- out = out.replace(symbol, "_")
- return out
- def make_paths(path, fname):
- global args
- base_path = add_slash(path).replace(args.in_dir, args.out_dir)
- filename = "".join(fname.split(".")[0:-1])
- ext = args.out_ext
- in_path = f"{add_slash(path)}{fname}"
- out_path = name_sanitize(f"""{base_path}{filename}.{ext}""")
- return (in_path, out_path)
- def get_total_input_files(filetree):
- total = 0
- for entry in filetree:
- for name in entry[2]:
- if is_input_file(name):
- total += 1
- return total
- def ffmpeg_convert_standard(in_path, out_path):
- global args
- if not os.path.exists(in_path):
- return f"[ERROR]: Path does not exist: {in_path}"
- ensure_path("/".join(out_path.split("/")[0:-1])) #strip the filename from the path and make output folder structure
- command = f"""ffmpeg -hide_banner -nostats {overwrite()} -i "{in_path}" -c:v libx264 -profile:v high -vf format=yuv420p -bsf:v h264_metadata=video_full_range_flag=0 -c:a aac -ac 2 -dn -map_metadata:c -1 -map_chapters:c -1 "{out_path}" """
- proc = subprocess.run(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
- stdout = proc.stderr.decode("utf-8")
- stderr = proc.stderr.decode("utf-8")
- output = stdout if stderr=="" else stderr
- if args.debug:
- logging.info(output)
- return
- """When called from the command line it'll use the arguments to convert some videos"""
- def main():
- global args
- args = parse_arguments()
- filetree = sorted(list(os.walk(args.in_dir)))
- current = 0
- total = get_total_input_files(filetree)
- #folder will be a tuple: (this_directory, [folders], [files])
- for thisdir, folders, files in filetree:
- for fname in files:
- if not is_input_file(fname):
- continue
- current += 1
- in_path, out_path = make_paths(thisdir, fname)
- logging.info(f"[{current}/{total}] Processing file: {in_path}")
- ffmpeg_convert_standard(in_path, out_path)
- if __name__ == "__main__":
- main()
Advertisement
Comments
-
- This is a refactor of this monstrosity: https://pastebin.com/ddaxpcvp
- Dear god, so much shoved into one function...
-
- Also btw this was meant for ps3 so you'll have to change the ffmpeg command to suit your mass-converting needs.
Add Comment
Please, Sign In to add comment
Advertisement