Пример #1
0
    def compute_matches(self, video):
        matches = set()
        # episode
        if isinstance(video, Episode):
            # series
            if video.series and self.series.lower() == video.series.lower():
                matches.add('series')
            # season
            if video.season and self.season == video.season:
                matches.add('season')
            # episode
            if video.episode and self.episode == video.episode:
                matches.add('episode')
            # guess
            matches |= compute_guess_matches(video, guessit.guess_episode_info(self.release + '.mkv'))
        elif isinstance(video, Movie):
            if video.year and self.year == video.year:
                matches.add('year')

            if video.title and self.movie == video.title:
                matches.add('title')

            # guess
            matches |= compute_guess_matches(video, guessit.guess_movie_info(self.release + '.mkv'))
        else:
            logger.info('%r is not a valid movie_kind for %r', self.movie_kind, video)
            return matches

        if self.subber and "yyets" in self.subber.lower():
            matches.add("yyets")
            
        return matches
 def compute_matches(self, video):
     matches = set()
     # episode
     if isinstance(video, Episode) and self.movie_kind == 'episode':
         # series
         if video.series and self.series_name.lower() == video.series.lower():
             matches.add('series')
         # season
         if video.season and self.series_season == video.season:
             matches.add('season')
         # episode
         if video.episode and self.series_episode == video.episode:
             matches.add('episode')
         # guess
         matches |= compute_guess_matches(video, guessit.guess_episode_info(self.movie_release_name + '.mkv'))
     # movie
     elif isinstance(video, Movie) and self.movie_kind == 'movie':
         # year
         if video.year and self.movie_year == video.year:
             matches.add('year')
         # guess
         matches |= compute_guess_matches(video, guessit.guess_movie_info(self.movie_release_name + '.mkv'))
     else:
         logger.info('%r is not a valid movie_kind for %r', self.movie_kind, video)
         return matches
     # hash
     if 'opensubtitles' in video.hashes and self.hash == video.hashes['opensubtitles']:
         matches.add('hash')
     # imdb_id
     if video.imdb_id and self.movie_imdb_id == video.imdb_id:
         matches.add('imdb_id')
     # title
     if video.title and self.movie_name.lower() == video.title.lower():
         matches.add('title')
     return matches
Пример #3
0
    def _guess_from_metadata(self):
        parse = lambda s: s.split(":")
        guesses = []
        for filename in self.files:
            filename = get_filename(filename)
            if not isinstance(filename, unicode):
                filename, realname = unicodeFilename(filename), filename
            else:
                realname = filename

            parser = createParser(filename, realname)
            if parser:
                try:
                    metadata = extractMetadata(parser)
                except HachoirError:
                    continue

                for line in metadata.exportPlaintext():
                    entries = dict((parse(normalize(l)) for l in line if 'comment' in l or 'title' in l))
                    entries = dict(((k, guessit.guess_episode_info(v)) for (k, v) in entries.items()))
                    if 'title' in entries:
                        guesses.append(entries['title'])
                    elif 'comment' in entries:
                        guesses.append(entries['comment'])
        return guesses
 def compute_matches(self, video):
     matches = set()
     # episode
     if isinstance(video, Episode) and self.movie_kind == "episode":
         # series
         if video.series and self.series_name.lower() == video.series.lower():
             matches.add("series")
         # season
         if video.season and self.series_season == video.season:
             matches.add("season")
         # episode
         if video.episode and self.series_episode == video.episode:
             matches.add("episode")
         # guess
         matches |= compute_guess_matches(video, guessit.guess_episode_info(self.movie_release_name + ".mkv"))
     # movie
     elif isinstance(video, Movie) and self.movie_kind == "movie":
         # year
         if video.year and self.movie_year == video.year:
             matches.add("year")
         # guess
         matches |= compute_guess_matches(video, guessit.guess_movie_info(self.movie_release_name + ".mkv"))
     else:
         logger.info("%r is not a valid movie_kind for %r", self.movie_kind, video)
         return matches
     # hash
     if "opensubtitles" in video.hashes and self.hash == video.hashes["opensubtitles"]:
         matches.add("hash")
     # imdb_id
     if video.imdb_id and self.movie_imdb_id == video.imdb_id:
         matches.add("imdb_id")
     # title
     if video.title and self.movie_name.lower() == video.title.lower():
         matches.add("title")
     return matches
Пример #5
0
    def compute_matches(self, video):
        matches = set()
        # episode
        if isinstance(video, Episode):
            # series
            if video.series and self.series.lower() == video.series.lower():
                matches.add('series')
            # season
            if video.season and self.season == video.season:
                matches.add('season')
            # episode
            if video.episode and self.episode == video.episode:
                matches.add('episode')
            # guess
            matches |= compute_guess_matches(
                video, guessit.guess_episode_info(self.release + '.mkv'))
        elif isinstance(video, Movie):
            if video.year and self.year == video.year:
                matches.add('year')

            if video.title and self.movie == video.title:
                matches.add('title')

            # guess
            matches |= compute_guess_matches(
                video, guessit.guess_movie_info(self.release + '.mkv'))
        else:
            logger.info('%r is not a valid movie_kind for %r', self.movie_kind,
                        video)
            return matches

        if self.subber and "yyets" in self.subber.lower():
            matches.add("yyets")

        return matches
Пример #6
0
    def get_matches(self, video, hearing_impaired=False):
        matches = super(SubsCenterSubtitle, self).get_matches(video, hearing_impaired=hearing_impaired)

        # episode
        if isinstance(video, Episode):
            # series
            if video.series and sanitized_string_equal(self.series, video.series):
                matches.add('series')
            # season
            if video.season and self.season == video.season:
                matches.add('season')
            # episode
            if video.episode and self.episode == video.episode:
                matches.add('episode')
            # guess
            for release in self.releases:
                matches |= guess_matches(video, guess_episode_info(release + '.mkv'))
        # movie
        elif isinstance(video, Movie):
            # guess
            for release in self.releases:
                matches |= guess_matches(video, guess_movie_info(release + '.mkv'))

        # title
        if video.title and sanitized_string_equal(self.title, video.title):
            matches.add('title')

        return matches
Пример #7
0
    def get_matches(self, video, hearing_impaired=False):
        matches = super(PodnapisiSubtitle, self).get_matches(video, hearing_impaired=hearing_impaired)

        # episode
        if isinstance(video, Episode):
            # series
            if video.series and self.title.lower() == video.series.lower():
                matches.add('series')
            # season
            if video.season and self.season == video.season:
                matches.add('season')
            # episode
            if video.episode and self.episode == video.episode:
                matches.add('episode')
            # guess
            for release in self.releases:
                matches |= guess_matches(video, guess_episode_info(release + '.mkv'))
        # movie
        elif isinstance(video, Movie):
            # title
            if video.title and self.title.lower() == video.title.lower():
                matches.add('title')
            # guess
            for release in self.releases:
                matches |= guess_matches(video, guess_movie_info(release + '.mkv'))
        # year
        if video.year and self.year == video.year:
            matches.add('year')

        return matches
Пример #8
0
 def handle_file(self, parent_folder, item):
     item = self.format_file_name(item)
     file_details = guessit.guess_file_info(item)
     # Force type for strange filenames (Mini-series without seasons, etc.)
     if "episode" in str(item).lower():
         file_details['type'] = 'episode'
     if 'container' in file_details:
         if file_details['type'] == 'movie':
             details = guessit.guess_movie_info(parent_folder+item)
             details.update({
                            'file_dir': "%s/" % parent_folder,
                            'file_name': item
                            })
             file_object_storage.append(Movie(**details))
         elif file_details['type'] == 'episode':
             details = guessit.guess_episode_info(parent_folder+item)
             details.update({
                            'file_dir': "%s/" % parent_folder,
                            'file_name': item
                            })
             if len(file_location_storage) > 0:
                 temp_file_location_storage = file_location_storage.copy()
                 for i in temp_file_location_storage:
                     if i is details['file_dir']:
                         file_location_storage[i].append(
                             details['file_name']
                             )
                     else:
                         file_location_storage[details['file_dir']] = [details['file_name']]
             else:
                 file_location_storage[details['file_dir']] = [details['file_name']]
             file_object_storage.append(Episode(**details))
Пример #9
0
    def _guess_from_metadata(self):
        parse = lambda s: s.split(":")
        guesses = []
        for filename in self.files:
            filename = get_filename(filename)
            if not isinstance(filename, unicode):
                filename, realname = unicodeFilename(filename), filename
            else:
                realname = filename

            parser = createParser(filename, realname)
            if parser:
                try:
                    metadata = extractMetadata(parser)
                except HachoirError:
                    continue

                for line in metadata.exportPlaintext():
                    entries = dict((parse(normalize(l)) for l in line
                                    if 'comment' in l or 'title' in l))
                    entries = dict(((k, guessit.guess_episode_info(v))
                                    for (k, v) in entries.items()))
                    if 'title' in entries:
                        guesses.append(entries['title'])
                    elif 'comment' in entries:
                        guesses.append(entries['comment'])
        return guesses
Пример #10
0
 def compute_matches(self, video):
     matches = set()
     # episode
     if isinstance(video, Episode):
         # series
         if video.series and self.series.lower() == video.series.lower():
             matches.add('series')
         # season
         if video.season and self.season == video.season:
             matches.add('season')
         # episode
         if video.episode and self.episode == video.episode:
             matches.add('episode')
         # guess
         for release in self.releases:
             matches |= compute_guess_matches(video, guessit.guess_episode_info(release + '.mkv'))
     # movie
     elif isinstance(video, Movie):
         # title
         if video.title and self.title.lower() == video.title.lower():
             matches.add('title')
         # guess
         for release in self.releases:
             matches |= compute_guess_matches(video, guessit.guess_movie_info(release + '.mkv'))
     # year
     if self.year == video.year:
         matches.add('year')
     return matches
Пример #11
0
    def get_matches(self, video, hearing_impaired=False):
        matches = super(SubsCenterSubtitle,
                        self).get_matches(video,
                                          hearing_impaired=hearing_impaired)

        # episode
        if isinstance(video, Episode):
            # series
            if video.series and sanitized_string_equal(self.series,
                                                       video.series):
                matches.add('series')
            # season
            if video.season and self.season == video.season:
                matches.add('season')
            # episode
            if video.episode and self.episode == video.episode:
                matches.add('episode')
            # guess
            for release in self.releases:
                matches |= guess_matches(video,
                                         guess_episode_info(release + '.mkv'))
        # movie
        elif isinstance(video, Movie):
            # guess
            for release in self.releases:
                matches |= guess_matches(video,
                                         guess_movie_info(release + '.mkv'))

        # title
        if video.title and sanitized_string_equal(self.title, video.title):
            matches.add('title')

        return matches
Пример #12
0
    def parse_name_guessit(self, file_name):

        # Check if the given file exists and is a regular file.
        if self.verbose:
            print 'Trying guessit match.\nAnalyzing ' + file_name
        info = guess_episode_info(file_name, info=['hash_mpc'])
        guessed_senumbers = (info['season'], info['episodeNumber'])
        if self.verbose:
            print 'Guessit results: %s' % guessed_senumbers
        print guessed_senumbers
        return guessed_senumbers
Пример #13
0
 def infer_metadata_from_tvshow_file(self, path_to_file):
     guess = guessit.guess_episode_info(path_to_file, info=['filename'])
     if guess is None or len(guess) == 0:
         self.log("[Warning] Failed to guess tv show metadata")
         return None
     return Helper._extract_metadata_from_guessit_dict(
         guess,
         mappings={
             "episodeNumber": Helper.Keys.TVEpisodeNumber,
             "season": Helper.Keys.TVSeasonNumber,
             "series": Helper.Keys.TVShow
         })
Пример #14
0
    def _get_episode_info(self, f):
        """Get episode information for each file from from the tvdb.Series object.

        return : dict or None
            Dict of episode information.
            None indicates that no such episode exists.
        """
        g = guessit.guess_episode_info(f)
        ep = self.series.get(g['season'])
        if ep:
            ep = ep.get(g['episodeNumber'])

        return ep
Пример #15
0
    def _get_episode_info(self, f):
        """Get episode information for each file from from the tvdb.Series object.

        return : dict or None
            Dict of episode information.
            None indicates that no such episode exists.
        """
        g = guessit.guess_episode_info(f)
        ep = self.series.get(g['season'])
        if ep:
            ep = ep.get(g['episodeNumber'])

        return ep
Пример #16
0
    def get_matches(self, video, hearing_impaired=False):
        matches = super(OpenSubtitlesSubtitle,
                        self).get_matches(video,
                                          hearing_impaired=hearing_impaired)

        # episode
        if isinstance(video, Episode) and self.movie_kind == 'episode':
            # series
            if video.series and sanitized_string_equal(self.series_name,
                                                       video.series):
                matches.add('series')
            # season
            if video.season and self.series_season == video.season:
                matches.add('season')
            # episode
            if video.episode and self.series_episode == video.episode:
                matches.add('episode')
            # title
            if video.title and sanitized_string_equal(self.series_title,
                                                      video.title):
                matches.add('title')
            # guess
            matches |= guess_matches(
                video, guess_episode_info(self.movie_release_name + '.mkv'))
        # movie
        elif isinstance(video, Movie) and self.movie_kind == 'movie':
            # title
            if video.title and sanitized_string_equal(self.movie_name,
                                                      video.title):
                matches.add('title')
            # year
            if video.year and self.movie_year == video.year:
                matches.add('year')
            # guess
            matches |= guess_matches(
                video, guess_movie_info(self.movie_release_name + '.mkv'))
        else:
            logger.info('%r is not a valid movie_kind', self.movie_kind)
            return matches

        # hash
        if 'opensubtitles' in video.hashes and self.hash == video.hashes[
                'opensubtitles']:
            matches.add('hash')
        # imdb_id
        if video.imdb_id and self.movie_imdb_id == video.imdb_id:
            matches.add('imdb_id')

        return matches
Пример #17
0
 def compute_matches(self, video):
     matches = set()
     # tvdb_id
     if video.tvdb_id and self.tvdb_id == video.tvdb_id:
         matches.add('tvdb_id')
     # series
     if video.series and self.series == video.series:
         matches.add('series')
     # season
     if video.season and self.season == video.season:
         matches.add('season')
     # episode
     if video.episode and self.episode == video.episode:
         matches.add('episode')
     matches |= compute_guess_matches(video, guessit.guess_episode_info(self.filename + '.mkv'))
     return matches
Пример #18
0
    def get_matches(self, video, hearing_impaired=False):
        matches = super(MakeDieSubtitle, self).get_matches(video, hearing_impaired=hearing_impaired)

        # episode
        if isinstance(video, Episode):
            # guess
            for release in self.releases:
                matches |= guess_matches(video, guess_episode_info(release + ".mkv"))

        # movie
        elif isinstance(video, Movie):
            for release in self.releases:
                matches |= guess_matches(video, guess_movie_info(release + ".mkv"))

        # Other mesaurements
        #   * upload_date
        #   * downloads
        # not included in subliminal, but use its score
        # hearing_impaired (1) -> audio_codec (2) -> video_codec (4)
        try:
            if self.upload_date and video.year:
                from datetime import datetime, date

                format = "%Y-%m-%d %H:%M:%S"
                d0 = datetime.strptime(str(video.year) + "-01-01 00:00:00", format)
                d1 = datetime.strptime(self.upload_date, format)
                level = (d1 - d0).days // 100
                if level == 1:
                    matches.add("hearing_impaired")
                elif level == 2:
                    matches.add("audio_codec")
                else:
                    matches.add("video_codec")

            # self defined scores, plus one (use audio_codec to mark)
            if self.downloads:
                level = int(self.downloads) // 1000
                if level == 1:
                    matches.add("hearing_impaired")
                elif level == 2:
                    matches.add("audio_codec")
                else:
                    matches.add("video_codec")
        except:
            logger.info("Wrong data fetched from makedie")

        return matches
Пример #19
0
def guessInfo(fileName, tvdbid=None):
    if tvdbid:
        guess = guessit.guess_episode_info(fileName)
        return tvdbInfo(guess, tvdbid)
    if not settings.fullpathguess:
        fileName = os.path.basename(fileName)
    guess = guessit.guess_file_info(fileName)
    try:
        if guess['type'] == 'movie':
            return tmdbInfo(guess)
        elif guess['type'] == 'episode':
            return tvdbInfo(guess, tvdbid)
        else:
            return None
    except Exception as e:
        print(e)
        return None
    def _guess(self, feed_item):
        # Try to guess the episode info from the filename.
        guess = guessit.guess_episode_info(feed_item.title)

        try:
            feed_item.episode_number = None if not "episodeNumber" in guess else int(guess["episodeNumber"])
            feed_item.episode_title = None if not "title" in guess else guess["title"]
            feed_item.season_number = None if not "season" in guess else int(guess["season"])
            feed_item.title_parsed = title if not "series" in guess else guess["series"]
            feed_item.year = None if not "year" in guess else int(guess["year"])

            self.logger.info(
                'Guessed "%s" [%s] from %s.' % (feed_item.title_canonical, feed_item.episode_string, feed_item.title)
            )
        except Exception:
            self.logger.error(guess)
            raise
Пример #21
0
 def compute_matches(self, video):
     matches = set()
     # tvdb_id
     if video.tvdb_id and self.tvdb_id == video.tvdb_id:
         matches.add('tvdb_id')
     # series
     if video.series and self.series == video.series:
         matches.add('series')
     # season
     if video.season and self.season == video.season:
         matches.add('season')
     # episode
     if video.episode and self.episode == video.episode:
         matches.add('episode')
     matches |= compute_guess_matches(
         video, guessit.guess_episode_info(self.filename + '.mkv'))
     return matches
Пример #22
0
def guessInfo(fileName, tvdbid=None):
    if tvdbid:
        guess = guessit.guess_episode_info(fileName)
        return tvdbInfo(guess, tvdbid)
    if not settings.fullpathguess:
        fileName = os.path.basename(fileName)
    guess = guessit.guess_file_info(fileName)
    try:
        if guess['type'] == 'movie':
            return tmdbInfo(guess)
        elif guess['type'] == 'episode':
            return tvdbInfo(guess, tvdbid)
        else:
            return None
    except Exception as e:
        print(e)
        return None
Пример #23
0
    def perform(self, query):
        self.checkValid(query)

        media = query.find_one(Media)

        episodeMetadata = guess_episode_info(media.filename)
        episodeMetadata = guessitToPygoo(episodeMetadata)

        averageConfidence = sum(episodeMetadata.confidence(prop) for prop in episodeMetadata) / len(episodeMetadata)

        # put the result of guessit in a form that smewt understands
        series = query.Series(title = episodeMetadata.pop('series'))
        episode = query.Episode(allow_incomplete = True, confidence = averageConfidence, series = series, **episodeMetadata)

        result = foundMetadata(query, episode)
        #result.display_graph()

        return result
Пример #24
0
    def __init__(self, file_path, config):
        """
        Initalizing class for file specified in file_path

        Attributes:
            file_path: String with absolute path to file

        Raises:
            IOError: if file does not exist in that location
        """
        self.config = config
        self.file_path = file_path
        self.file_name = os.path.basename(file_path)
        self.file_size = os.path.getsize(file_path)

        self.ep_info = guessit.guess_episode_info(file_path)

        self.subtitles = []
Пример #25
0
    def testPeriscopeSubtitle(self):
        for subdata in yaml.load(open(datafile('subsdata.yaml')).read()):
            video = subdata['video']
            lang =  subdata['language']
            subfile = subdata['result']

            ep = guess_episode_info(video)

            series = ep.pop('series')

            g = MemoryObjectGraph()
            ep = g.Episode(series = g.Series(title = series), **ep)
            videofile = g.Media(filename = datafile(video), metadata = ep)

            subtask = SubtitleTask(ep, lang)
            sub = subtask.downloadEpisodeSubtitleText()

            self.assert_(self.subtitlesEqual(sub, open(datafile(subfile)).read()))
Пример #26
0
def classify():
    if request.content_type == "application/json":
        form = ClassifyForm(data=request.get_json(force=True))
    else:
        form = ClassifyForm(request.form)
    if form.validate():
        release_name = form.release_name.data
        options = {"name_only": True}
        if form.media_type.data == "unknown":
            data = guessit.guess_file_info(release_name, options=options)
        elif form.media_type.data == "tv":
            data = guessit.guess_episode_info(release_name, options=options)
        else:
            data = guessit.guess_movie_info(release_name, options=options)
        try:
            jsonify()
            return json.dumps(data, default=json_serial)
        except Exception as err:
            return json.dumps({"err": str(err)}, default=json_serial)
Пример #27
0
def classify():
    if request.content_type == "application/json":
        form = ClassifyForm(data=request.get_json(force=True))
    else:
        form = ClassifyForm(request.form)
    if form.validate():
        release_name = form.release_name.data
        options = {'name_only': True}
        if form.media_type.data == "unknown":
            data = guessit.guess_file_info(release_name, options=options)
        elif form.media_type.data == "tv":
            data = guessit.guess_episode_info(release_name, options=options)
        else:
            data = guessit.guess_movie_info(release_name, options=options)
        try:
            jsonify()
            return json.dumps(data, default=json_serial)
        except Exception as err:
            return json.dumps({"err": str(err)}, default=json_serial)
Пример #28
0
    def testPeriscopeSubtitle(self):
        for subdata in yaml.load(open(datafile('subsdata.yaml')).read()):
            video = subdata['video']
            lang = subdata['language']
            subfile = subdata['result']

            ep = guess_episode_info(video)

            series = ep.pop('series')

            g = MemoryObjectGraph()
            ep = g.Episode(series=g.Series(title=series), **ep)
            videofile = g.Media(filename=datafile(video), metadata=ep)

            subtask = SubtitleTask(ep, lang)
            sub = subtask.downloadEpisodeSubtitleText()

            self.assert_(
                self.subtitlesEqual(sub,
                                    open(datafile(subfile)).read()))
Пример #29
0
    def get_matches(self, video, hearing_impaired=False):
        matches = super(OpenSubtitlesSubtitle, self).get_matches(video, hearing_impaired=hearing_impaired)

        # episode
        if isinstance(video, Episode) and self.movie_kind == 'episode':
            # series
            if video.series and self.series_name.lower() == video.series.lower():
                matches.add('series')
            # season
            if video.season and self.series_season == video.season:
                matches.add('season')
            # episode
            if video.episode and self.series_episode == video.episode:
                matches.add('episode')
            # title
            if video.title and self.series_title.lower() == video.title.lower():
                matches.add('title')
            # guess
            matches |= guess_matches(video, guess_episode_info(self.movie_release_name + '.mkv'))
        # movie
        elif isinstance(video, Movie) and self.movie_kind == 'movie':
            # title
            if video.title and self.movie_name.lower() == video.title.lower():
                matches.add('title')
            # year
            if video.year and self.movie_year == video.year:
                matches.add('year')
            # guess
            matches |= guess_matches(video, guess_movie_info(self.movie_release_name + '.mkv'))
        else:
            logger.info('%r is not a valid movie_kind', self.movie_kind)
            return matches

        # hash
        if 'opensubtitles' in video.hashes and self.hash == video.hashes['opensubtitles']:
            matches.add('hash')
        # imdb_id
        if video.imdb_id and self.movie_imdb_id == video.imdb_id:
            matches.add('imdb_id')

        return matches
    def _guess(self, feed_item):
        # Try to guess the episode info from the filename.
        guess = guessit.guess_episode_info(feed_item.title)

        try:
            feed_item.episode_number = None if not 'episodeNumber' in guess else int(
                guess['episodeNumber'])
            feed_item.episode_title = None if not 'title' in guess else guess[
                'title']
            feed_item.season_number = None if not 'season' in guess else int(
                guess['season'])
            feed_item.title_parsed = title if not 'series' in guess else guess[
                'series']
            feed_item.year = None if not 'year' in guess else int(
                guess['year'])

            self.logger.info('Guessed "%s" [%s] from %s.' %
                             (feed_item.title_canonical,
                              feed_item.episode_string, feed_item.title))
        except Exception:
            self.logger.error(guess)
            raise
Пример #31
0
    def perform(self, query):
        self.checkValid(query)

        media = query.find_one(Media)

        episodeMetadata = guess_episode_info(media.filename)
        episodeMetadata = guessitToPygoo(episodeMetadata)

        averageConfidence = sum(
            episodeMetadata.confidence(prop)
            for prop in episodeMetadata) / len(episodeMetadata)

        # put the result of guessit in a form that smewt understands
        series = query.Series(title=episodeMetadata.pop('series'))
        episode = query.Episode(allow_incomplete=True,
                                confidence=averageConfidence,
                                series=series,
                                **episodeMetadata)

        result = foundMetadata(query, episode)
        #result.display_graph()

        return result
Пример #32
0
def get_anime_info(name):
    global titleCache
    """Find anime information"""
    anime_title = name.replace('/', ' ')
    if anime_title[0] == '.':
        anime_title = anime_title[1:]
    anime_info = guess_episode_info(name, options={'allowed_languages': ['fr']})
    # anime_title = anime_info.get('series', anime_info.get('title', None))
    if anime_title != None:
        if anime_title.lower() in titleCache:
            return {'Cached': True}
        response = None
        print(name)
        if 'year' in anime_info:
            response = hummingbird(anime_title, anime_info['year'])
        else:
            response = hummingbird(anime_title, None)
        titleCache[anime_title.lower()] = True
        if response['Title'].lower() in titleCache:
            return {'Cached': True}
        titleCache[response['Title'].lower()] = True
        return response
    else:
        not_a_anime.append(name)
Пример #33
0
 def fromname(cls, name):
     return cls.fromguess(
         os.path.split(name)[1], guessit.guess_episode_info(name))
Пример #34
0
    def process(self, directory, series_bdd, series_imdb):
        self.reset_infos()
        self.path = os.path.abspath(directory).replace(
            settings.FTP_ROOT, '', 1)
        self.filename = os.path.basename(self.path)
        self.season_directory = os.path.dirname(self.path)

        # Check if the episode is already in database
        filter = EpisodeDirectory.objects.filter(location=self.path)
        if filter.exists():
            return filter[0]

        # Extract infos from directory name
        guess = guessit.guess_episode_info(self.filename)
        if 'season' in guess.keys() and 'episodeNumber' in guess.keys():
            self.season_nb = guess['season']
            self.episode_nb = guess['episodeNumber']
        else:
            print self.path
            print 'Error: Episode wrongly named'
            return
        self.quality = guess['screenSize'] if 'screenSize' in guess else 'SD'

        # Create Season
        filter = Season.objects.filter(series=series_bdd,
                                       season_number=self.season_nb)
        if filter.exists():
            self.season = filter[0]
        else:
            self.season = Season.objects.create(series=series_bdd,
                                                season_number=self.season_nb,
                                                number_of_episodes=0)

        filter = SeasonDirectory.objects.filter(season=self.season,
                                                location=self.season_directory,
                                                quality=self.quality)
        if filter.exists():
            self.season_dir = filter[0]
        else:
            self.season_dir = SeasonDirectory.objects.create(
                    season=self.season, location=self.season_directory,
                    quality=self.quality)

        filter = Episode.objects.filter(season=self.season,
                                        episode_number=self.episode_nb)
        if filter.exists():
            self.episode = filter[0]
        else:
            if (self.season_nb in series_imdb.keys() and
                    self.episode_nb in series_imdb[self.season_nb].keys()):
                self.episode = self.episode_processor.process(
                        series_imdb[self.season_nb][self.episode_nb].movieID,
                        self.season, self.episode_nb)
            else:
                print "Episode doesn't exists in IMDb database: %s"%(
                        self.filename)
                l = log.logger(log.SERIES)
                l.error("Episode doesn't exists in IMDb database: %s"%(
                        self.filename), NOT_ON_IMDB_CODE)
                return None

        #Size of the directory in Mo
        #TODO understand why the result is different from du
        self.size = (get_size(directory, log.SERIES) + 500000) // 1000000

        # Finally, create the EpisodeDirectory
        return EpisodeDirectory.objects.create(episode=self.episode,
                                               location=self.path,
                                               quality=self.quality,
                                               size=self.size)
Пример #35
0
 def _guess_from_filename(self):
     guesses = (guessit.guess_episode_info(get_filename(f))
                for f in self.files)
     return [g for g in guesses if 'series' in g]
Пример #36
0
 def fromname(cls, name):
     return cls.fromguess(os.path.split(name)[1], guessit.guess_episode_info(name))
Пример #37
0
def find_dupes_and_missing():
    lowignore = ["moomi","adventure time with finn and jake","Adventure Time","HJØRDIS"]
    ignore = []
    newName = ""
    for word in lowignore:
        ignore.append(word.upper())

    all_missing = []
    dupes = []
    extensionsToCheck = ("mkv", "mp4", "avi")
    missing = []

    #print "Finding missing episodes and removing duplicates"
    t = threading.Thread(target=animate)
    t.start()

    #go through all files and folders:
    for root, dirs, files in os.walk('PATH/TO/SERIES'):
        missing = []
        newName = []
        if "SEASON" in root.upper():
            #print root
            season = []
            for fname in files:
                if str(fname).endswith(extensionsToCheck):
                    guess = guessit.guess_episode_info(fname)

                    if "episodeNumber" in guess and str(guess['series']).upper() not in ignore:
                        episode = [guess['series'], guess["season"], guess["episodeNumber"], os.path.join(root, fname)]
                        season.append(episode)

                        if "episodeList" in guess:
                            for number in guess['episodeList']:
                                if number != guess["episodeNumber"]:
                                    newEpisode = list(episode)
                                    newEpisode[2] = number
                                    #print newEpisode
                                    season.append(newEpisode)


            if len(season) > 0:
                season = sorted(season, key=itemgetter(2))
                try:
                    if len(season) > 1:
                        maks = find_maks(str(season[0][0]),season[0][1])#season[-1][2] # find number of episodes in a folder
                        actualMaks = find_maks(str(season[0][0]),season[0][1])
                        if actualMaks == -1:
                            actualMaks = maks

                except Exception as e:
                            print e
                if maks != actualMaks:
                    missing,dupes,newName = logic(season,maks)
                    for i in range(maks+1,actualMaks+1):
                        missing.append(i)
                if (len(season) != maks):
                    missing,dupes,newName = logic(season,maks)

            if len(missing) > 0:
                sname = season[0][0]+" S%02d" % (season[0][1])
                all_missing.append([sname,missing])
    global done
    done = True
    time.sleep(1)
    print

    if len(dupes) > 0:
        print "Found duplicated episode(s): "
        for ep in dupes:
            print "removed ",ep
    if len(newName) > 0:
        print "Found double episode(s): "
        for ep in newName:
            oldnew = ep.split(":")
            print "Rewrote ", oldnew[0]
    if len(all_missing) > 0:
        print "Found missing episodes: "
        for liste in all_missing:
            print liste[0]
            for number in liste[1]:
                print number,
            print
        saveFile(all_missing)
        print "Trying to download missing episodes"
        os.system("/path/to/torrent.py")
    else:
        print "No missing episodes found :)"
Пример #38
0
def search_subtitles(file_list):
    #TODO: Instead of performing search for each file, construct queries and execute them all at once
    """
    :rtype : object
    :param file_list: list of video files(with full path) for which to search subtitles
    """
    #TODO: Check if user is over the download limit
    #http://trac.opensubtitles.org/projects/opensubtitles/wiki/XMLRPC#ServerInfo
    count = 0
    try:
        session = server.LogIn("", "", sub_language, useragent)
    except:
        print("Error logging in to opensubtiles API.")
        exit()

    if session['status'] != "200 OK":
        print("Error logging in to opensubtiles API.", session['status'])
        exit()
    else:
        token = session["token"]

    for file_path in file_list:

        count += 1
        ep_info = None
        file_name = os.path.basename(file_path)
        sub_path = os.path.dirname(os.path.abspath(file_path))
        sub_path += os.sep if SUBFOLDER is None else os.sep + SUBFOLDER + os.sep

        print("-" * 50 + '\nSearching subtitle for "{}" | ({}/{})'.format(file_name,
                                                                          count,
                                                                          len(file_list)))

        if not OVERWRITE:
            type_1 = "{0}{1}".format(sub_path, file_name)  #with original file ext
            type_2 = "{0}{1}".format(sub_path,  #without
                                     "".join(file_name.split('.')[:-1]))
            sub_exists = False

            for sub_format in SUB_EXT:
                if os.path.exists(type_1 + sub_format) or os.path.exists(type_2 + sub_format):
                    sub_exists = True
                    break
            if sub_exists:
                print("Subtitle already exist, skipping...")
                continue

        file_size = os.path.getsize(file_path)
        current_hash = get_hash(file_path, file_size)

        if current_hash is None:
            print("Can't calculate hash for {}".format(file_path))
            hash_search = False
            hash_results = None
        else:
            hash_search_query = [{"sublanguageid": sub_language,
                                  'moviehash': current_hash,
                                  'moviebytesize': file_size}]
            hash_search = True

        try:
            ep_info = guessit.guess_episode_info(file_path)

            tv_show = ep_info['series']
            season = ep_info['season']
            episode = ep_info['episodeNumber']

            query_info = "{} S{:02d}E{:02d}".format(tv_show,  # TODO: season & episode redundant?
                                                    int(season),
                                                    int(episode),
            ).replace(" ", "+")


            # if/elif/elif:
            # **If you define moviehash and moviebytesize, then imdbid and query in same array are ignored.**
            # If you define imdbid, then moviehash, moviebytesize and query is ignored.
            # If you define query, then moviehash, moviebytesize and imdbid is ignored.
            file_search_query = [{'sublanguageid': sub_language,
                                  'query': query_info,
                                  'season': season,
                                  'episode': episode}]
            query_search = True
        except:
            print("Can't determine enough info about series/episode from the filename.")
            query_search = False

        if query_search:
            query_results = server.SearchSubtitles(token, file_search_query)
            if query_results['status'] != "200 OK":
                print("Query search failed ", query_results['status'])
                query_results = None
            else:
                if not query_results['data']:
                    query_results = None
                else:
                    query_results = query_results['data']

        #if False:
         #   hash_results = server.SearchSubtitles(token, hash_search_query)
            #if hash_results['status'] != '200 OK':
             #   print('"Hash search failed', hash_results['status'])
              #  hash_results = None
            #else:
             #   hash_results = hash_results['data']

        if query_search is False and hash_search is False:
            do_download = False
            print("Couldn't find any subtitles :_(")
        else:
            do_download = True
        if do_download:
            ep_info["filename"] = file_path
            ep_info['sub_folder'] = sub_path
            subtitles_list = []
            if query_results:  # Subtitle results exist
                subtitles_list += [item for item in query_results if '0' == item['SubHearingImpaired']]
            #if hash_results:
            #    subtitles_list += [item for item in hash_results if '0' == item['SubHearingImpaired']]

            if subtitles_list == []:
                print("Couldn't find any subtitles :_(")
            else:
                download_subtitle(subtitles_list[0], ep_info)

    server.LogOut(token)
Пример #39
0
 def _guess_from_filename(self):
     guesses = (guessit.guess_episode_info(get_filename(f)) for f in self.files)
     return [g for g in guesses if 'series' in g]
Пример #40
0
    token_file.write(token)
    token_file.close()

# Prompt the user to choose the tv shows directory
print("You will now be prompted to select the Tv Shows directory")
input("Press ENTER . . .")
Tk().withdraw()  # we don't want a full GUI, so keep the root window from appearing
directory = askdirectory()  # show an "Open" dialog box and return the path to the selected file

# Walk the 'Tv Show' directory
shows = dict()
# for _, _, files_current_dir in os.walk(r'R:\Torrent\Tv Shows'):
for _, _, files_current_dir in os.walk(directory):
    for file in files_current_dir:
        # Guess the file infos
        guess = guessit.guess_episode_info(file)

        # Save the infos in the dictionary
        save_episode_progress(shows, guess)


print("////////////////////////")
print("// LAST AIRED EPISODE //")
print("////////////////////////")

for tv_show_name, progress in shows.items():
    show_infos, _ = tvst.get_show_infos(tv_show_name)

    if show_infos is not None:
        progress_table = PrettyTable(["", "Season", "Episode"])
        progress_table.align[""] = "l"
Пример #41
0
 def fromname(cls, name):
     return cls.fromguess(name, guess_episode_info(name))
Пример #42
0
 def infer_metadata_from_tvshow_file(self, path_to_file):
     guess = guessit.guess_episode_info(path_to_file, info=['filename'])
     if guess is None or len(guess) == 0:
         self.log("[Warning] Failed to guess tv show metadata")
         return None
     return Helper._extract_metadata_from_guessit_dict(guess, mappings={"episodeNumber": Helper.Keys.TVEpisodeNumber, "season": Helper.Keys.TVSeasonNumber, "series": Helper.Keys.TVShow})
Пример #43
0
 def fromname(cls, name):
     return cls.fromguess(name, guess_episode_info(name))
Пример #44
0
    def auto_download(self):
        """
        Automatically choose best subtitle based on
        how similar the subtitle and video file names are
        or based on the type of match.

        Returns:
            True if suitable subtitle is found else False

        """
        sequence = difflib.SequenceMatcher(None, "", "")
        possible_matches = []
        best_choice = None

        for subtitle in self.subtitles:

            sub_info = guessit.guess_episode_info(subtitle.sub_filename)

            sub_series = sub_info.get('series', "None Found").lower().encode('utf-8')
            sub_season = sub_info.get('season', None)
            sub_episode = sub_info.get('episodeNumber', None)

            vid_series = self.ep_info.get('series', "None").lower().encode('utf-8')
            vid_season = self.ep_info.get('season', None)
            vid_episode = self.ep_info.get('episodeNumber', None)

            if vid_series == sub_series:
                if sub_season and vid_season and sub_episode and vid_episode:
                    if [sub_season, sub_episode] == [vid_season, vid_episode]:
                        possible_matches.append(subtitle)
                    else:
                        continue

            subtitle_title_name = re.sub(r'[^a-zA-Z0-9\s+]', '',
                                         subtitle.movie_name).lower()
            episode_title_name = "{} {}".format(
                self.ep_info.get('series', "0").lower().encode('utf-8'),
                self.ep_info.get('title', "0").lower().encode('utf-8')
            )

            sequence.set_seqs(subtitle_title_name, episode_title_name)
            if sequence.ratio() > self.config['cutoff']:
                possible_matches.append(subtitle)
                continue

            if subtitle.synced:
                possible_matches.append(subtitle)

        for sub in possible_matches:
            if not best_choice:
                best_choice = sub
            elif sub.download_count > best_choice.download_count:
                if best_choice.synced and sub.synced is False:
                    continue
                else:
                    best_choice = sub

        if best_choice:
            best_choice.download()
            return True
        else:
            return False