Last active
November 18, 2019 15:22
-
-
Save jeffarese/e3559260aff9d987af6c1b5162ad05b2 to your computer and use it in GitHub Desktop.
Script to recursively sync all the subtitles of a folder and overwrite the old one (after backing it up). It won't try to sync previously synced subs on next iterations
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 fnmatch | |
| import os | |
| import subprocess | |
| SUBSYNC_PATH = 'subsync' | |
| VIDEO_EXTENSIONS = ['.mkv', '.mp4', '.avi'] | |
| SUBTITLE_EXTENSION_TO_SYNC = '.es.srt' | |
| TEMP_OUTPUT_NAME = 'output.srt' | |
| OLD_SUFFIX = '.old' | |
| FAILED_SUFFIX = '.failed' | |
| matches = [] | |
| for root, dirnames, filenames in os.walk('.'): | |
| for filename in fnmatch.filter(filenames, '*' + SUBTITLE_EXTENSION_TO_SYNC): | |
| videoMatch = None | |
| basename = os.path.join(filename.split(SUBTITLE_EXTENSION_TO_SYNC)[0]) | |
| subtitleWithPath = os.path.join(root, filename) | |
| fileBaseNameWithPath = os.path.join( | |
| root, filename.split(SUBTITLE_EXTENSION_TO_SYNC)[0]) | |
| for extension in VIDEO_EXTENSIONS: | |
| videoFileToCheck = f"{fileBaseNameWithPath}{extension}" | |
| if os.path.exists(videoFileToCheck): | |
| videoMatch = videoFileToCheck | |
| break | |
| if videoMatch is not None: | |
| if os.path.exists(f"{subtitleWithPath}{OLD_SUFFIX}"): | |
| print("Sub already synced") | |
| elif os.path.exists(f"{subtitleWithPath}{FAILED_SUFFIX}"): | |
| print("This video failed previously, won't try again") | |
| else: | |
| try: | |
| print(f"Starting sync process of: {filename}") | |
| outputFilenameWithPath = os.path.join( | |
| root, TEMP_OUTPUT_NAME, ) | |
| failedFilePath = f"{subtitleWithPath}{FAILED_SUFFIX}" | |
| with open(failedFilePath, "w+") as outfile: | |
| outCode = subprocess.call( | |
| [SUBSYNC_PATH, videoMatch, "-i", subtitleWithPath, "-o", outputFilenameWithPath], | |
| stderr=outfile) | |
| if outCode != 0: | |
| raise Exception | |
| os.rename(subtitleWithPath, f"{subtitleWithPath}{OLD_SUFFIX}") | |
| os.rename(outputFilenameWithPath, subtitleWithPath) | |
| os.remove(f"{subtitleWithPath}{FAILED_SUFFIX}") | |
| except Exception as e: | |
| print(f"There has been an error in the syncing process of: ${filename}") | |
| else: | |
| print(f"There's no video file for: {filename}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment