Created
February 14, 2024 23:50
-
-
Save qrkourier/1f5e3df5cd1693cae8d15d7ce5d6d6ff to your computer and use it in GitHub Desktop.
to convert videos in a folder to MP4 and remove the old file if successful, say "python transcode-to-mp4.py FOLDER --delete"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
from os import chdir, walk | |
from os.path import dirname, getsize, join | |
from pathlib import Path | |
from shutil import move | |
import ffmpeg | |
import filetype | |
def convert_video(input_file, output_file): | |
( | |
ffmpeg | |
.input(input_file) | |
.output(output_file) | |
.overwrite_output() | |
.run() | |
) | |
def replace_extension_with_mp4(filename): | |
# Split the filename into the name and the extension | |
name, _ = os.path.splitext(filename) | |
# Add .mp4 as the new extension | |
new_filename = name + '.mp4' | |
return new_filename | |
def get_extension(filename): | |
# Split the filename into the name and the extension | |
name, _ = os.path.splitext(filename) | |
return _ | |
def sizeof_fmt(num, suffix="B"): | |
for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]: | |
if abs(num) < 1024.0: | |
return f"{num:3.1f}{unit}{suffix}" | |
num /= 1024.0 | |
return f"{num:.1f}Yi{suffix}" | |
def main(): | |
# The top argument for walk | |
topdir = sys.argv[1] | |
chdir(topdir) | |
total_bytes = 0 | |
for root, dirs, files in walk('.'): | |
for name in files: | |
if Path(join(root, name)).is_symlink(): | |
continue | |
elif filetype.is_video(join(root, name)): | |
if get_extension(name) == ".mp4": | |
continue | |
size = getsize(join(root, name)) | |
total_bytes = size+total_bytes | |
rename = replace_extension_with_mp4(name) | |
dest = Path(join(topdir, root.strip('./'), rename)) | |
print("Transcoding:", join(root, name), sizeof_fmt(size), "->", dest) | |
try: | |
# parent = Path(dirname(dest)) | |
# parent.mkdir(parents=True, exist_ok=True) | |
convert_video(join(topdir, root, name), dest.as_posix()) | |
if len(sys.argv) > 2 and sys.argv[2] == "--delete": | |
os.remove(join(topdir, root, name)) | |
except Exception: | |
raise | |
else: | |
pass | |
print("Total:", sizeof_fmt(total_bytes)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment