Last active
December 19, 2015 10:09
-
-
Save noonat/5938608 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
from __future__ import print_function | |
import argparse | |
import os | |
import requests | |
import sys | |
import zlib | |
from pythonopensubtitles import opensubtitles, utils | |
def get_column_width(rows, column_index): | |
"""Get the maximum width of the given column index.""" | |
return max(len(unicode(row[column_index]).strip()) for row in rows) | |
def print_rows(rows, **kwargs): | |
"""Prints out a table of data, padded for alignment.""" | |
padding = [get_column_width(rows, i) for i in range(len(rows[0]))] | |
for row in rows: | |
columns = [unicode(column).strip().ljust(padding[i] + 2) | |
for i, column in enumerate(row)] | |
print(''.join(columns).rstrip(), **kwargs) | |
def choose_subtitle(items): | |
print('Found {0} subtitles:'.format(len(items))) | |
rows = [['', 'format', 'lang', 'name', 'year', 'cds', 'release']] | |
for index, item in enumerate(items): | |
rows.append([index + 1, item['SubFormat'], item['LanguageName'], | |
item['MovieName'], item['MovieYear'], item['SubSumCD'], | |
item['MovieReleaseName']]) | |
print_rows(rows) | |
while True: | |
try: | |
selected_index = int(raw_input('Choose one: ').strip()) | |
if 0 < selected_index <= len(items): | |
return selected_index - 1 | |
except ValueError: | |
pass | |
print('Invalid choice') | |
def download_subtitle(item, video_filename): | |
print('Downloading subtitle from {0}'.format(item['SubDownloadLink'])) | |
video_dir = os.path.dirname(video_filename) | |
video_name, _ = os.path.splitext(os.path.basename(video_filename)) | |
filename = '.'.join([video_name, item['ISO639'], item['SubFormat']]) | |
filename = os.path.join(video_dir, filename) | |
response = requests.get(item['SubDownloadLink'], stream=True) | |
if response.status_code == 200: | |
content = None | |
try: | |
decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS) | |
content = decompressor.decompress(response.content) | |
except: | |
pass | |
with open(filename, 'wb') as f: | |
f.write(content or response.content) | |
else: | |
print('Error downloading {0}'.format(item['SubDownloadLink'])) | |
def search(osdb, language='eng', movie_hash=None, movie_byte_size=None, | |
imdb_id=None, query=None, season=None, episode=None, tag=None): | |
params = {'sublanguageid': language, | |
'moviehash': movie_hash, | |
'moviebytesize': str(movie_byte_size), | |
'imdbid': imdb_id, | |
'query': query, | |
'season': season, | |
'episode': episode, | |
'tag': tag} | |
params = {k: v for k, v in params.iteritems() if v is not None} | |
return osdb.search_subtitles([params]) or [] | |
def search_by_video(osdb, video_filename, language='eng'): | |
video = utils.File(video_filename) | |
return search(osdb, movie_hash=video.get_hash(), | |
movie_byte_size=video.size()) | |
def setup_parser(): | |
parser = argparse.ArgumentParser(description='Download subtitles.') | |
parser.add_argument('--language', default='eng') | |
parser.add_argument('--imdb', metavar='ID') | |
parser.add_argument('--query') | |
parser.add_argument('--username', default=os.getenv('OSDB_USERNAME')) | |
parser.add_argument('--password', default=os.getenv('OSDB_PASSWORD')) | |
parser.add_argument('video', type=os.path.abspath) | |
return parser | |
def main(args, parser): | |
osdb = opensubtitles.OpenSubtitles() | |
osdb.login(args.username, args.password) | |
if args.imdb: | |
items = search(osdb, imdb_id=args.imdb, language=args.language) | |
elif args.query: | |
items = search(osdb, query=args.query, language=args.language) | |
else: | |
items = search_by_video(osdb, args.video, language=args.language) | |
if len(items) > 1: | |
index = choose_subtitle(items) | |
download_subtitle(items[index], args.video) | |
elif len(items) == 1: | |
download_subtitle(items[0], args.video) | |
else: | |
print('No subtitles found') | |
if __name__ == '__main__': | |
parser = setup_parser() | |
main(parser.parse_args(), parser) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment