fansub-utils/auto-CRC.py

70 lines
2.1 KiB
Python
Raw Permalink Normal View History

2019-03-18 11:55:59 +00:00
#!/usr/bin/env python
"""
2019-03-24 19:28:01 +00:00
This script appends CRC-32s to the end of the files in a directory.
This is intended for anime fansubbing releases.
2019-07-16 11:41:24 +00:00
You can change what it checks by modifying the 'ext' (extension) on L47.
Can be run both from the command line, and imported.
2019-03-18 11:55:59 +00:00
"""
import argparse
import binascii
import glob
import mimetypes
import os
2019-03-18 11:55:59 +00:00
import re
__author__ = "LightArrowsEXE"
__license__ = 'MIT'
__version__ = '1.1'
2019-03-18 11:55:59 +00:00
def calculateCRC(f):
with open(f, 'rb') as file:
calc = file.read()
return "%08X" % (binascii.crc32(calc) & 0xFFFFFFFF)
2019-03-18 11:55:59 +00:00
def strip_crc(f):
if re.search(r'\[[0-9a-fA-F]{8}\]', f):
strip = re.sub(r'\[[0-9a-fA-F]{8}\]', '', f)
# Hate how re.sub leaves some whitespace
filename = os.path.splitext(strip)[0]
filename = filename[:-1] + os.path.splitext(strip)[1]
os.rename(f, filename)
print(f"[-] {f} stripped")
def main(recursive=False):
if args.recursive:
filelist = glob.glob('**/*', recursive=True)
2019-03-18 11:55:59 +00:00
else:
filelist = glob.glob('*')
2019-03-18 11:55:59 +00:00
2019-03-24 19:28:01 +00:00
for f in filelist:
mime = mimetypes.types_map.get(os.path.splitext(f)[-1], "")
if mime.startswith("video/") or f.endswith('.mkv'):
if args.strip:
strip_crc(f)
else:
crc = calculateCRC(f)
if re.search(crc, f):
print(f"[*] {f}, correct CRC already present in filename")
else:
filename = f'{os.path.splitext(f)[0]} [{crc}]{os.path.splitext(f)[1]}'
os.rename(f, filename)
print(f"[+] {f}, CRC: [{crc}]")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-R", "--recursive",
action="store_true", default=False,
help="check recursively (default: %(default)s)")
parser.add_argument("-S", "--strip",
action="store_true", default=False,
help="strip CRCs from filenames (default: %(default)s)")
parser.parse_args()
args = parser.parse_args()
main()