Improve matches for Subdivx provider

pull/1248/head
vitiko98 4 years ago
parent 9d41d44d6d
commit 8b97c7c54e

@ -13,7 +13,7 @@ from requests import Session
from subliminal import __short_version__ from subliminal import __short_version__
from subliminal.exceptions import ServiceUnavailable from subliminal.exceptions import ServiceUnavailable
from subliminal.providers import ParserBeautifulSoup from subliminal.providers import ParserBeautifulSoup
from subliminal.subtitle import SUBTITLE_EXTENSIONS, fix_line_ending,guess_matches from subliminal.subtitle import SUBTITLE_EXTENSIONS, fix_line_ending, guess_matches
from subliminal.video import Episode, Movie from subliminal.video import Episode, Movie
from subliminal_patch.exceptions import APIThrottled from subliminal_patch.exceptions import APIThrottled
from six.moves import range from six.moves import range
@ -26,18 +26,20 @@ logger = logging.getLogger(__name__)
class SubdivxSubtitle(Subtitle): class SubdivxSubtitle(Subtitle):
provider_name = 'subdivx' provider_name = "subdivx"
hash_verifiable = False hash_verifiable = False
def __init__(self, language, video, page_link, title, description, uploader): def __init__(self, language, video, page_link, title, description, uploader):
super(SubdivxSubtitle, self).__init__(language, hearing_impaired=False, page_link=page_link) super(SubdivxSubtitle, self).__init__(
language, hearing_impaired=False, page_link=page_link
)
self.video = video self.video = video
self.title = title self.title = title
self.description = description self.description = description
self.uploader = uploader self.uploader = uploader
self.release_info = self.title self.release_info = self.title
if self.description and self.description.strip(): if self.description and self.description.strip():
self.release_info += ' | ' + self.description self.release_info += " | " + self.description
@property @property
def id(self): def id(self):
@ -49,60 +51,33 @@ class SubdivxSubtitle(Subtitle):
# episode # episode
if isinstance(video, Episode): if isinstance(video, Episode):
# already matched in search query # already matched in search query
matches.update(['title', 'series', 'season', 'episode', 'year']) matches.update(["title", "series", "season", "episode", "year"])
# movie # movie
elif isinstance(video, Movie): elif isinstance(video, Movie):
# already matched in search query # already matched in search query
matches.update(['title', 'year']) matches.update(["title", "year"])
# release_group # Special string comparisons are unnecessary. Guessit can match keys
if video.release_group and video.release_group.lower() in self.description: # from any string and find even more keywords.
matches.add('release_group') matches |= guess_matches(
video,
# resolution guessit(
if video.resolution and video.resolution.lower() in self.description: self.description,
matches.add('resolution') {"type": "episode" if isinstance(video, Episode) else "movie"},
),
# source )
if video.source:
formats = [video.source.lower()]
if formats[0] == "web":
formats.append("webdl")
formats.append("web-dl")
formats.append("webrip")
formats.append("web ")
for frmt in formats:
if frmt in self.description:
matches.add('source')
break
# video_codec
if video.video_codec:
video_codecs = [video.video_codec.lower()]
if video_codecs[0] == "h.264":
video_codecs.append("h264")
video_codecs.append("x264")
elif video_codecs[0] == "h.265":
video_codecs.append("h265")
video_codecs.append("x265")
elif video_codecs[0] == "divx":
video_codecs.append("divx")
for vc in video_codecs:
if vc in self.description:
matches.add('video_codec')
break
return matches return matches
class SubdivxSubtitlesProvider(Provider): class SubdivxSubtitlesProvider(Provider):
provider_name = 'subdivx' provider_name = "subdivx"
hash_verifiable = False hash_verifiable = False
languages = {Language.fromalpha2(lang) for lang in ['es']} languages = {Language.fromalpha2(lang) for lang in ["es"]}
subtitle_class = SubdivxSubtitle subtitle_class = SubdivxSubtitle
server_url = 'https://www.subdivx.com/' server_url = "https://www.subdivx.com/"
multi_result_throttle = 2 multi_result_throttle = 2
language_list = list(languages) language_list = list(languages)
@ -111,36 +86,31 @@ class SubdivxSubtitlesProvider(Provider):
def initialize(self): def initialize(self):
self.session = Session() self.session = Session()
self.session.headers['User-Agent'] = 'Subliminal/{}'.format(__short_version__) self.session.headers["User-Agent"] = f"Subliminal/{__short_version__}"
def terminate(self): def terminate(self):
self.session.close() self.session.close()
def query(self, video, languages): def query(self, video, languages):
if isinstance(video, Episode): if isinstance(video, Episode):
query = "{} S{:02d}E{:02d}".format(video.series, video.season, video.episode) query = f"{video.series} S{video.season:02}E{video.episode:02}"
else: else:
# Subdvix has problems searching foreign movies if the year is # Subdvix has problems searching foreign movies if the year is
# appended. For example: if we search "Memories of Murder 2003", # appended. A proper solution would be filtering results with the
# Subdix won't return any results; but if we search "Memories of # year in self._parse_subtitles_page.
# Murder", it will. That's because in Subdvix foreign titles have
# the year after the original title ("Salinui chueok (2003) aka
# Memories of Murder").
# A proper solution would be filtering results with the year in
# _parse_subtitles_page.
query = video.title query = video.title
params = { params = {
'q': query, # search string "q": query, # search string
'accion': 5, # action search "accion": 5, # action search
'oxdown': 1, # order by downloads descending "oxdown": 1, # order by downloads descending
'pg': 1 # page 1 "pg": 1, # page 1
} }
logger.debug('Searching subtitles %r', query) logger.debug(f"Searching subtitles: {query}")
subtitles = [] subtitles = []
language = self.language_list[0] language = self.language_list[0]
search_link = self.server_url + 'index.php' search_link = self.server_url + "index.php"
while True: while True:
response = self.session.get(search_link, params=params, timeout=20) response = self.session.get(search_link, params=params, timeout=20)
self._check_response(response) self._check_response(response)
@ -148,7 +118,7 @@ class SubdivxSubtitlesProvider(Provider):
try: try:
page_subtitles = self._parse_subtitles_page(video, response, language) page_subtitles = self._parse_subtitles_page(video, response, language)
except Exception as e: except Exception as e:
logger.error('Error parsing subtitles list: ' + str(e)) logger.error(f"Error parsing subtitles list: {e}")
break break
subtitles += page_subtitles subtitles += page_subtitles
@ -156,7 +126,7 @@ class SubdivxSubtitlesProvider(Provider):
if len(page_subtitles) < 100: if len(page_subtitles) < 100:
break # this is the last page break # this is the last page
params['pg'] += 1 # search next page params["pg"] += 1 # search next page
time.sleep(self.multi_result_throttle) time.sleep(self.multi_result_throttle)
return subtitles return subtitles
@ -167,14 +137,17 @@ class SubdivxSubtitlesProvider(Provider):
def download_subtitle(self, subtitle): def download_subtitle(self, subtitle):
if isinstance(subtitle, SubdivxSubtitle): if isinstance(subtitle, SubdivxSubtitle):
# download the subtitle # download the subtitle
logger.info('Downloading subtitle %r', subtitle) logger.info("Downloading subtitle %r", subtitle)
# get download link # get download link
download_link = self._get_download_link(subtitle) download_link = self._get_download_link(subtitle)
# download zip / rar file with the subtitle # download zip / rar file with the subtitle
response = self.session.get(self.server_url + download_link, headers={'Referer': subtitle.page_link}, response = self.session.get(
timeout=30) self.server_url + download_link,
headers={"Referer": subtitle.page_link},
timeout=30,
)
self._check_response(response) self._check_response(response)
# open the compressed archive # open the compressed archive
@ -187,9 +160,11 @@ class SubdivxSubtitlesProvider(Provider):
def _parse_subtitles_page(self, video, response, language): def _parse_subtitles_page(self, video, response, language):
subtitles = [] subtitles = []
page_soup = ParserBeautifulSoup(response.content.decode('utf-8', 'ignore'), ['lxml', 'html.parser']) page_soup = ParserBeautifulSoup(
title_soups = page_soup.find_all("div", {'id': 'menu_detalle_buscador'}) response.content.decode("utf-8", "ignore"), ["lxml", "html.parser"]
body_soups = page_soup.find_all("div", {'id': 'buscador_detalle'}) )
title_soups = page_soup.find_all("div", {"id": "menu_detalle_buscador"})
body_soups = page_soup.find_all("div", {"id": "buscador_detalle"})
for subtitle in range(0, len(title_soups)): for subtitle in range(0, len(title_soups)):
title_soup, body_soup = title_soups[subtitle], body_soups[subtitle] title_soup, body_soup = title_soups[subtitle], body_soups[subtitle]
@ -204,15 +179,17 @@ class SubdivxSubtitlesProvider(Provider):
page_link = title_soup.find("a")["href"] page_link = title_soup.find("a")["href"]
# description # description
description = body_soup.find("div", {'id': 'buscador_detalle_sub'}).text description = body_soup.find("div", {"id": "buscador_detalle_sub"}).text
description = description.replace(",", " ").lower() description = description.replace(",", " ").lower()
# uploader # uploader
uploader = body_soup.find("a", {'class': 'link1'}).text uploader = body_soup.find("a", {"class": "link1"}).text
subtitle = self.subtitle_class(language, video, page_link, title, description, uploader) subtitle = self.subtitle_class(
language, video, page_link, title, description, uploader
)
logger.debug('Found subtitle %r', subtitle) logger.debug("Found subtitle %r", subtitle)
subtitles.append(subtitle) subtitles.append(subtitle)
return subtitles return subtitles
@ -221,37 +198,39 @@ class SubdivxSubtitlesProvider(Provider):
response = self.session.get(subtitle.page_link, timeout=20) response = self.session.get(subtitle.page_link, timeout=20)
self._check_response(response) self._check_response(response)
try: try:
page_soup = ParserBeautifulSoup(response.content.decode('utf-8', 'ignore'), ['lxml', 'html.parser']) page_soup = ParserBeautifulSoup(
links_soup = page_soup.find_all("a", {'class': 'detalle_link'}) response.content.decode("utf-8", "ignore"), ["lxml", "html.parser"]
)
links_soup = page_soup.find_all("a", {"class": "detalle_link"})
for link_soup in links_soup: for link_soup in links_soup:
if link_soup['href'].startswith('bajar'): if link_soup["href"].startswith("bajar"):
return self.server_url + link_soup['href'] return self.server_url + link_soup["href"]
links_soup = page_soup.find_all("a", {'class': 'link1'}) links_soup = page_soup.find_all("a", {"class": "link1"})
for link_soup in links_soup: for link_soup in links_soup:
if "bajar.php" in link_soup['href']: if "bajar.php" in link_soup["href"]:
return link_soup['href'] return link_soup["href"]
except Exception as e: except Exception as e:
raise APIThrottled('Error parsing download link: ' + str(e)) raise APIThrottled(f"Error parsing download link: {e}")
raise APIThrottled('Download link not found') raise APIThrottled("Download link not found")
@staticmethod @staticmethod
def _check_response(response): def _check_response(response):
if response.status_code != 200: if response.status_code != 200:
raise ServiceUnavailable('Bad status code: ' + str(response.status_code)) raise ServiceUnavailable(f"Bad status code: {response.status_code}")
@staticmethod @staticmethod
def _get_archive(content): def _get_archive(content):
# open the archive # open the archive
archive_stream = io.BytesIO(content) archive_stream = io.BytesIO(content)
if rarfile.is_rarfile(archive_stream): if rarfile.is_rarfile(archive_stream):
logger.debug('Identified rar archive') logger.debug("Identified rar archive")
archive = rarfile.RarFile(archive_stream) archive = rarfile.RarFile(archive_stream)
elif zipfile.is_zipfile(archive_stream): elif zipfile.is_zipfile(archive_stream):
logger.debug('Identified zip archive') logger.debug("Identified zip archive")
archive = zipfile.ZipFile(archive_stream) archive = zipfile.ZipFile(archive_stream)
else: else:
raise APIThrottled('Unsupported compressed format') raise APIThrottled("Unsupported compressed format")
return archive return archive
@ -261,12 +240,16 @@ class SubdivxSubtitlesProvider(Provider):
for name in archive.namelist(): for name in archive.namelist():
# discard hidden files # discard hidden files
# discard non-subtitle files # discard non-subtitle files
if not os.path.split(name)[-1].startswith('.') and name.lower().endswith(SUBTITLE_EXTENSIONS): if not os.path.split(name)[-1].startswith(".") and name.lower().endswith(
SUBTITLE_EXTENSIONS
):
_valid_names.append(name) _valid_names.append(name)
# archive with only 1 subtitle # archive with only 1 subtitle
if len(_valid_names) == 1: if len(_valid_names) == 1:
logger.debug("returning from archive: {} (single subtitle file)".format(_valid_names[0])) logger.debug(
f"returning from archive: {_valid_names[0]} (single subtitle file)"
)
return archive.read(_valid_names[0]) return archive.read(_valid_names[0])
# in archives with more than 1 subtitle (season pack) we try to guess the best subtitle file # in archives with more than 1 subtitle (season pack) we try to guess the best subtitle file
@ -275,31 +258,36 @@ class SubdivxSubtitlesProvider(Provider):
_max_name = "" _max_name = ""
for name in _valid_names: for name in _valid_names:
_guess = guessit(name) _guess = guessit(name)
if 'season' not in _guess: if "season" not in _guess:
_guess['season'] = -1 _guess["season"] = -1
if 'episode' not in _guess: if "episode" not in _guess:
_guess['episode'] = -1 _guess["episode"] = -1
if isinstance(subtitle.video, Episode): if isinstance(subtitle.video, Episode):
logger.debug("guessing %s" % name) logger.debug("guessing %s" % name)
logger.debug("subtitle S{}E{} video S{}E{}".format( logger.debug(
_guess['season'], _guess['episode'], subtitle.video.season, subtitle.video.episode)) f"subtitle S{_guess['season']}E{_guess['episode']} video "
f"S{subtitle.video.season}E{subtitle.video.episode}"
if subtitle.video.episode != _guess['episode'] or subtitle.video.season != _guess['season']: )
logger.debug('subtitle does not match video, skipping')
if (
subtitle.video.episode != _guess["episode"]
or subtitle.video.season != _guess["season"]
):
logger.debug("subtitle does not match video, skipping")
continue continue
matches = set() matches = set()
matches |= guess_matches(subtitle.video, _guess) matches |= guess_matches(subtitle.video, _guess)
_score = sum((_scores.get(match, 0) for match in matches)) _score = sum((_scores.get(match, 0) for match in matches))
logger.debug('srt matches: %s, score %d' % (matches, _score)) logger.debug("srt matches: %s, score %d" % (matches, _score))
if _score > _max_score: if _score > _max_score:
_max_score = _score _max_score = _score
_max_name = name _max_name = name
logger.debug("new max: {} {}".format(name, _score)) logger.debug(f"new max: {name} {_score}")
if _max_score > 0: if _max_score > 0:
logger.debug("returning from archive: {} scored {}".format(_max_name, _max_score)) logger.debug(f"returning from archive: {_max_name} scored {_max_score}")
return archive.read(_max_name) return archive.read(_max_name)
raise APIThrottled('Can not find the subtitle in the compressed file') raise APIThrottled("Can not find the subtitle in the compressed file")

Loading…
Cancel
Save