• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python helpers.remove_non_release_groups函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sickbeard.helpers.remove_non_release_groups函数的典型用法代码示例。如果您正苦于以下问题:Python remove_non_release_groups函数的具体用法?Python remove_non_release_groups怎么用?Python remove_non_release_groups使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了remove_non_release_groups函数的18个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _downloadPropers

    def _downloadPropers(self, properList):
        """
        Download proper (snatch it)

        :param properList:
        """

        for curProper in properList:

            historyLimit = datetime.datetime.today() - datetime.timedelta(days=30)

            # make sure the episode has been downloaded before
            myDB = db.DBConnection()
            historyResults = myDB.select(
                "SELECT resource FROM history " +
                "WHERE showid = ? AND season = ? AND episode = ? AND quality = ? AND date >= ? " +
                "AND action IN (" + ",".join([str(x) for x in Quality.SNATCHED + Quality.DOWNLOADED]) + ")",
                [curProper.indexerid, curProper.season, curProper.episode, curProper.quality,
                 historyLimit.strftime(History.date_format)])

            # if we didn't download this episode in the first place we don't know what quality to use for the proper so we can't do it
            if len(historyResults) == 0:
                logger.log(
                    u"Unable to find an original history entry for proper " + curProper.name + " so I'm not downloading it.")
                continue

            else:

                # make sure that none of the existing history downloads are the same proper we're trying to download
                clean_proper_name = self._genericName(helpers.remove_non_release_groups(curProper.name))
                isSame = False
                for curResult in historyResults:
                    # if the result exists in history already we need to skip it
                    if self._genericName(helpers.remove_non_release_groups(curResult["resource"])) == clean_proper_name:
                        isSame = True
                        break
                if isSame:
                    logger.log(u"This proper is already in history, skipping it", logger.DEBUG)
                    continue

                # get the episode object
                epObj = curProper.show.getEpisode(curProper.season, curProper.episode)

                # make the result object
                result = curProper.provider.getResult([epObj])
                result.show = curProper.show
                result.url = curProper.url
                result.name = curProper.name
                result.quality = curProper.quality
                result.release_group = curProper.release_group
                result.version = curProper.version
                result.content = curProper.content

                # snatch it
                snatchEpisode(result, SNATCHED_PROPER)
                time.sleep(cpu_presets[sickbeard.CPU_PRESET])
开发者ID:hernandito,项目名称:SickRage,代码行数:56,代码来源:properFinder.py


示例2: _downloadPropers

def _downloadPropers(properList):

    for curProper in properList:

        historyLimit = datetime.datetime.today() - datetime.timedelta(days=30)

        # make sure the episode has been downloaded before
        myDB = db.DBConnection()
        historyResults = myDB.select(
            'SELECT resource FROM history '
            'WHERE showid = ? AND season = ? AND episode = ? AND quality = ? AND date >= ? '
            'AND action IN (' + ','.join([str(x) for x in Quality.SNATCHED]) + ')',
            [curProper.indexerid, curProper.season, curProper.episode, curProper.quality,
             historyLimit.strftime(history.dateFormat)])

        # if we didn't download this episode in the first place we don't know what quality to use for the proper so we can't do it
        if len(historyResults) == 0:
            logger.log(
                u'Unable to find an original history entry for proper ' + curProper.name + ' so I\'m not downloading it.')
            continue

        else:

            # make sure that none of the existing history downloads are the same proper we're trying to download
            clean_proper_name = _genericName(helpers.remove_non_release_groups(curProper.name))
            isSame = False
            for curResult in historyResults:
                # if the result exists in history already we need to skip it
                if _genericName(helpers.remove_non_release_groups(curResult['resource'])) == clean_proper_name:
                    isSame = True
                    break
            if isSame:
                logger.log(u'This proper is already in history, skipping it', logger.DEBUG)
                continue

            # get the episode object
            showObj = helpers.findCertainShow(sickbeard.showList, curProper.indexerid)
            if showObj == None:
                logger.log(u'Unable to find the show with indexerid ' + str(
                    curProper.indexerid) + ' so unable to download the proper', logger.ERROR)
                continue
            epObj = showObj.getEpisode(curProper.season, curProper.episode)

            # make the result object
            result = curProper.provider.get_result([epObj], curProper.url)
            if None is result:
                continue
            result.name = curProper.name
            result.quality = curProper.quality
            result.version = curProper.version

            # snatch it
            search.snatchEpisode(result, SNATCHED_PROPER)
开发者ID:joshguerette,项目名称:SickGear,代码行数:53,代码来源:properFinder.py


示例3: _finalize

    def _finalize(self, parse_result):
        """
        Store parse result if it is complete and final

        :param parse_result: Result of parsers
        """
        self.release_group = parse_result.release_group

        # remember whether it's a proper
        if parse_result.extra_info:
            self.is_proper = re.search(r'(^|[\. _-])(proper|repack)([\. _-]|$)', parse_result.extra_info, re.I) != None

        # if the result is complete then remember that for later
        # if the result is complete then set release name
        if parse_result.series_name and ((parse_result.season_number is not None and parse_result.episode_numbers)
                                         or parse_result.air_date) and parse_result.release_group:

            if not self.release_name:
                self.release_name = helpers.remove_non_release_groups(helpers.remove_extension(ek(os.path.basename, parse_result.original_name)))

        else:
            logger.log(u"Parse result not sufficient (all following have to be set). will not save release name",
                       logger.DEBUG)
            logger.log(u"Parse result(series_name): " + str(parse_result.series_name), logger.DEBUG)
            logger.log(u"Parse result(season_number): " + str(parse_result.season_number), logger.DEBUG)
            logger.log(u"Parse result(episode_numbers): " + str(parse_result.episode_numbers), logger.DEBUG)
            logger.log(u" or Parse result(air_date): " + str(parse_result.air_date), logger.DEBUG)
            logger.log(u"Parse result(release_group): " + str(parse_result.release_group), logger.DEBUG)
开发者ID:nono20004,项目名称:SickRage,代码行数:28,代码来源:postProcessor.py


示例4: test_remove_non_release_groups

 def test_remove_non_release_groups(self):
     test_names = {
         ('[HorribleSubs] Hidan no Aria AA - 08 [1080p]', True): '[HorribleSubs] Hidan no Aria AA - 08 [1080p]',
         ('The.Last.Man.On.Earth.S02E08.No.Bull.1080p.WEB-DL.DD5.1.H264-BTN[rartv]', False): 'The.Last.Man.On.Earth.S02E08.No.Bull.1080p.WEB-DL.DD5.1.H264-BTN',
     }
     for test_name, test_result in test_names.items():
         self.assertEqual(test_result, helpers.remove_non_release_groups(test_name[0], test_name[1]))
开发者ID:JackDandy,项目名称:SickGear,代码行数:7,代码来源:helpers_tests.py


示例5: parse

    def parse(self, name):

        name = self._unicodify(name)

        cached = name_parser_cache.get(name)
        if cached:
            return cached

        # break it into parts if there are any (dirname, file name, extension)
        dir_name, file_name = ek.ek(os.path.split, name)

        if self.is_file_name:
            base_file_name = helpers.remove_non_release_groups(helpers.remove_extension(file_name))
        else:
            base_file_name = file_name

        # use only the direct parent dir
        dir_name = ek.ek(os.path.basename, dir_name)

        # set up a result to use
        final_result = ParseResult(name)

        # try parsing the file name
        file_name_result = self._parse_string(base_file_name)

        # parse the dirname for extra info if needed
        dir_name_result = self._parse_string(dir_name)

        # build the ParseResult object
        final_result.air_date = self._combine_results(file_name_result, dir_name_result, 'air_date')

        if not final_result.air_date:
            final_result.season_number = self._combine_results(file_name_result, dir_name_result, 'season_number')
            final_result.episode_numbers = self._combine_results(file_name_result, dir_name_result, 'episode_numbers')

        final_result.is_proper = self._combine_results(file_name_result, dir_name_result, 'is_proper')

        # if the dirname has a release group/show name I believe it over the filename
        final_result.series_name = self._combine_results(dir_name_result, file_name_result, 'series_name')
        final_result.extra_info = self._combine_results(dir_name_result, file_name_result, 'extra_info')
        final_result.release_group = self._combine_results(dir_name_result, file_name_result, 'release_group')

        final_result.which_regex = []
        if final_result == file_name_result:
            final_result.which_regex = file_name_result.which_regex
        elif final_result == dir_name_result:
            final_result.which_regex = dir_name_result.which_regex
        else:
            if file_name_result:
                final_result.which_regex += file_name_result.which_regex
            if dir_name_result:
                final_result.which_regex += dir_name_result.which_regex

        # if there's no useful info in it then raise an exception
        if final_result.season_number is None and not final_result.episode_numbers and final_result.air_date is None and not final_result.series_name:
            raise InvalidNameException("Unable to parse " + name.encode(sickbeard.SYS_ENCODING, 'xmlcharrefreplace'))

        name_parser_cache.add(name, final_result)
        # return it
        return final_result
开发者ID:PermaNulled,项目名称:SickBeard-XG,代码行数:60,代码来源:parser.py


示例6: _test

 def _test(self):
     """
     Generate tests
     :param self:
     :return: test to run
     """
     for test_string in test_strings:
         self.assertEqual(helpers.remove_non_release_groups(test_string), TEST_RESULT)
开发者ID:DazzFX,项目名称:SickRage,代码行数:8,代码来源:helpers_tests.py


示例7: refine

def refine(video, release_name=None, release_file=None, extension='release', **kwargs):
    """Refine a video by using the original release name.
    The refiner will first try:
    - Read the file video_name.<extension> seeking for a release name
    - If no release name, it will read the file release file seeking for a release name
    - If no release name, it will use the release_name passed as an argument
    - If no release name, then no change in the video object is made

    When a release name is found, the video object will be enhanced using the guessit properties extracted from it.

    Several :class:`~subliminal.video.Video` attributes can be found:

      * :attr:`~subliminal.video.Video.title`
      * :attr:`~subliminal.video.Video.series`
      * :attr:`~subliminal.video.Video.season`
      * :attr:`~subliminal.video.Video.episode`
      * :attr:`~subliminal.video.Video.year`
      * :attr:`~subliminal.video.Video.format`
      * :attr:`~subliminal.video.Video.release_group`
      * :attr:`~subliminal.video.Video.resolution`
      * :attr:`~subliminal.video.Video.video_codec`
      * :attr:`~subliminal.video.Video.audio_codec`

    :param video: the video to refine.
    :param str release_name: the release name to be used.
    :param str release_file: the release file to be used
    :param str extension: the release file extension.

    """
    logger.debug(u'Starting release refiner [extension=%s, release_name=%s, release_file=%s]',
                 extension, release_name, release_file)
    dirpath, filename = os.path.split(video.name)
    dirpath = dirpath or '.'
    fileroot, fileext = os.path.splitext(filename)
    release_file = get_release_file(dirpath, fileroot, extension) or release_file
    release_name = remove_non_release_groups(get_release_name(release_file) or release_name)

    if not release_name:
        logger.debug(u'No release name for %s', video.name)
        return

    release_path = os.path.join(dirpath, release_name + fileext)
    logger.debug(u'Guessing using %s', release_path)

    guess = guessit(release_path)
    attributes = MOVIE_ATTRIBUTES if guess.get('type') == 'movie' else EPISODE_ATTRIBUTES
    for key, value in attributes.items():
        old_value = getattr(video, key)
        new_value = guess.get(value)

        if new_value and old_value != new_value:
            setattr(video, key, new_value)
            logger.debug(u'Attribute %s changed from %s to %s', key, old_value, new_value)
开发者ID:Eiber,项目名称:SickRage-Medusa,代码行数:53,代码来源:release.py


示例8: _analyze_name

    def _analyze_name(self, name, file=True):
        """
        Takes a name and tries to figure out a show, season, and episode from it.

        name: A string which we want to analyze to determine show info from (unicode)

        Returns a (indexer_id, season, [episodes]) tuple. The first two may be None and episodes may be []
        if none were found.
        """

        logger.log(u"Analyzing name " + repr(name))

        to_return = (None, None, [], None, None)

        if not name:
            return to_return

        name = helpers.remove_non_release_groups(helpers.remove_extension(name))

        # parse the name to break it into show name, season, and episode
        np = NameParser(file, tryIndexers=True, convert=True)
        parse_result = np.parse(name)

        # show object
        show = parse_result.show

        if parse_result.is_air_by_date:
            season = -1
            episodes = [parse_result.air_date]
        elif parse_result.is_sports:
            season = -1
            episodes = [parse_result.sports_air_date]
        else:
            season = parse_result.season_number
            episodes = parse_result.episode_numbers

        to_return = (show, season, episodes, parse_result.quality, None)

        self._finalize(parse_result)
        return to_return
开发者ID:GreenOst,项目名称:SickRage,代码行数:40,代码来源:postProcessor.py


示例9: _analyze_name

    def _analyze_name(self, name, resource=True):
        """
        Takes a name and tries to figure out a show, season, and episode from it.

        name: A string which we want to analyze to determine show info from (unicode)

        Returns a (indexer_id, season, [episodes]) tuple. The first two may be None and episodes may be []
        if none were found.
        """

        logger.log(u'Analyzing name ' + repr(name))

        to_return = (None, None, [], None)

        if not name:
            return to_return

        name = helpers.remove_non_release_groups(helpers.remove_extension(name))

        # parse the name to break it into show name, season, and episode
        np = NameParser(resource, try_indexers=True, try_scene_exceptions=True, convert=True)
        parse_result = np.parse(name)
        self._log(u'Parsed %s<br />.. into %s' % (name, str(parse_result).decode('utf-8', 'xmlcharrefreplace')), logger.DEBUG)

        if parse_result.is_air_by_date:
            season = -1
            episodes = [parse_result.air_date]
        else:
            season = parse_result.season_number
            episodes = parse_result.episode_numbers

        # show object
        show = parse_result.show
        to_return = (show, season, episodes, parse_result.quality)

        self._finalize(parse_result)
        return to_return
开发者ID:Koernia,项目名称:SickGear,代码行数:37,代码来源:postProcessor.py


示例10: execute

    def execute(self):
        backupDatabase(16)

        logger.log(u"Setting special episodes status to SKIPPED.")
        self.connection.action("UPDATE tv_episodes SET status = ? WHERE status = ? AND season = 0", [common.SKIPPED, common.WANTED])

        fix_ep_rls_group = []
        fix_ep_release_name = []

        # re-analyze snatched data
        logger.log(u"Analyzing history to correct bad data (this could take a moment, be patient)...")
        history_results = self.connection.select("SELECT * FROM history WHERE action % 100 = 2 ORDER BY date ASC")
        for cur_result in history_results:
            # find the associated download, if there isn't one then ignore it
            download_results = self.connection.select("SELECT * FROM history WHERE action % 100 = 4 AND showid = ? AND season = ? AND episode = ? AND quality = ? AND date > ?",
                                                    [cur_result["showid"], cur_result["season"], cur_result["episode"], cur_result["quality"], cur_result["date"]])
            # only continue if there was a download found (thats newer than the snatched)
            if not download_results:
                logger.log(u"Found a snatch in the history for " + cur_result["resource"] + " but couldn't find the associated download, skipping it", logger.DEBUG)
                continue

            # take the snatched nzb, clean it up so we can store it for the corresponding tv_episodes entry
            clean_nzb_name = helpers.remove_non_release_groups(helpers.remove_extension(cur_result["resource"]))

            # fixed known bad release_group data
            if download_results[0]["provider"].upper() in ["-1", "RP", "NZBGEEK"] or "." in download_results[0]["provider"]:
                try:
                    np = NameParser(False)
                    parse_result = np.parse(clean_nzb_name)
                except InvalidNameException:
                    continue

                # leave off check for episode number so we can update season rip data as well?
                if parse_result.series_name and parse_result.season_number is not None and parse_result.release_group:
                    fix_ep_rls_group.append(["UPDATE history SET provider = ? WHERE action = ? AND showid = ? AND season = ? AND episode = ? AND quality = ? AND date = ?", \
                               [parse_result.release_group, download_results[0]["action"], download_results[0]["showid"], download_results[0]["season"], download_results[0]["episode"], download_results[0]["quality"], download_results[0]["date"]]
                               ])

            # find the associated episode on disk
            ep_results = self.connection.select("SELECT episode_id, status, release_name FROM tv_episodes WHERE showid = ? AND season = ? AND episode = ? AND location != ''",
                                                [cur_result["showid"], cur_result["season"], cur_result["episode"]])
            if not ep_results:
                logger.log(u"The episode " + cur_result["resource"] + " was found in history but doesn't exist on disk anymore, skipping", logger.DEBUG)
                continue

            # skip items that appears to have a 'scene' name already to avoid replacing locally pp/manually moved items
            match = re.search(".(xvid|x264|h.?264|mpeg-?2)", ep_results[0]["release_name"], re.I)
            if match:
                continue

            # get the status/quality of the existing ep and make sure it's what we expect
            ep_status, ep_quality = common.Quality.splitCompositeStatus(int(ep_results[0]["status"]))
            if ep_status != common.DOWNLOADED:
                continue

            if ep_quality != int(cur_result["quality"]):
                continue

            # take the extension off the filename, it's not needed
            file_name = ek.ek(os.path.basename, download_results[0]["resource"])
            if '.' in file_name:
                file_name = file_name.rpartition('.')[0]

            # make sure this is actually a real release name and not a season pack or something
            for cur_name in (clean_nzb_name, file_name):
                logger.log(u"Checking if " + cur_name + " is actually a good release name", logger.DEBUG)
                try:
                    np = NameParser(False)
                    parse_result = np.parse(cur_name)
                except InvalidNameException:
                    continue

                if parse_result.series_name and parse_result.season_number is not None and parse_result.episode_numbers and parse_result.release_group:
                    # if all is well by this point we'll just put the release name into the database
                    fix_ep_release_name.append(["UPDATE tv_episodes SET release_name = ? WHERE episode_id = ?", [cur_name, ep_results[0]["episode_id"]]])
                    break

        logger.log(u"Corrected " + str(len(fix_ep_release_name)) + " release names (" + str(len(fix_ep_rls_group)) + " release groups) out of the " + str(len(history_results)) + " releases analyzed.")
        if len(fix_ep_rls_group) > 0:
            self.connection.mass_action(fix_ep_rls_group)
        if len(fix_ep_release_name) > 0:
            self.connection.mass_action(fix_ep_release_name)

        # now cleanup all downloaded release groups in the history
        fix_ep_rls_group = []
        logger.log(u"Analyzing downloaded history release groups...")
        history_results = self.connection.select("SELECT * FROM history WHERE action % 100 = 4 ORDER BY date ASC")
        for cur_result in history_results:
            clean_provider = helpers.remove_non_release_groups(helpers.remove_extension(cur_result["provider"]))
            # take the data on the left of the _, fixes 'LOL_repost'
            if clean_provider and "_" in clean_provider:
                clean_provider = clean_provider.rsplit('_', 1)[0]
            if clean_provider != cur_result["provider"]:
                fix_ep_rls_group.append(["UPDATE history SET provider = ? WHERE action = ? AND showid = ? AND season = ? AND episode = ? AND quality = ? AND date = ?", \
                                         [clean_provider, cur_result["action"], cur_result["showid"], cur_result["season"], cur_result["episode"], cur_result["quality"], cur_result["date"]]
                                         ])
        logger.log(u"Corrected " + str(len(fix_ep_rls_group)) + " release groups.")
        if len(fix_ep_rls_group) > 0:
            self.connection.mass_action(fix_ep_rls_group)

#.........这里部分代码省略.........
开发者ID:riksmith,项目名称:Sick-Beard,代码行数:101,代码来源:mainDB.py


示例11: _test

 def _test(self):
     for test_string in test_strings:
         self.assertEqual(remove_non_release_groups(test_string), test_result)
开发者ID:coderbone,项目名称:SickRage,代码行数:3,代码来源:test_helpers.py


示例12: _parse_string

    def _parse_string(self, name):
        if not name:
            return

        matches = []

        for regex in self.compiled_regexes:
            for (cur_regex_num, cur_regex_name, cur_regex) in self.compiled_regexes[regex]:
                match = cur_regex.match(name)

                if not match:
                    continue

                result = ParseResult(name)
                result.which_regex = [cur_regex_name]
                result.score = 0 - cur_regex_num

                named_groups = match.groupdict().keys()

                if 'series_name' in named_groups:
                    result.series_name = match.group('series_name')
                    if result.series_name:
                        result.series_name = self.clean_series_name(result.series_name)
                        result.score += 1

                if 'series_num' in named_groups and match.group('series_num'):
                    result.score += 1

                if 'season_num' in named_groups:
                    tmp_season = int(match.group('season_num'))
                    if 'bare' == cur_regex_name and tmp_season in (19, 20):
                        continue
                    result.season_number = tmp_season
                    result.score += 1

                if 'ep_num' in named_groups:
                    ep_num = self._convert_number(match.group('ep_num'))
                    if 'extra_ep_num' in named_groups and match.group('extra_ep_num'):
                        result.episode_numbers = range(ep_num, self._convert_number(match.group('extra_ep_num')) + 1)
                        result.score += 1
                    else:
                        result.episode_numbers = [ep_num]
                    result.score += 1

                if 'ep_ab_num' in named_groups:
                    ep_ab_num = self._convert_number(match.group('ep_ab_num'))
                    if 'extra_ab_ep_num' in named_groups and match.group('extra_ab_ep_num'):
                        result.ab_episode_numbers = range(ep_ab_num,
                                                          self._convert_number(match.group('extra_ab_ep_num')) + 1)
                        result.score += 1
                    else:
                        result.ab_episode_numbers = [ep_ab_num]
                    result.score += 1

                if 'air_year' in named_groups and 'air_month' in named_groups and 'air_day' in named_groups:
                    year = int(match.group('air_year'))
                    month = int(match.group('air_month'))
                    day = int(match.group('air_day'))
                    # make an attempt to detect YYYY-DD-MM formats
                    if 12 < month:
                        tmp_month = month
                        month = day
                        day = tmp_month
                    try:
                        result.air_date = datetime.date(year, month, day)
                    except ValueError as e:
                        raise InvalidNameException(ex(e))

                if 'extra_info' in named_groups:
                    tmp_extra_info = match.group('extra_info')

                    # Show.S04.Special or Show.S05.Part.2.Extras is almost certainly not every episode in the season
                    if tmp_extra_info and 'season_only' == cur_regex_name and re.search(
                            r'([. _-]|^)(special|extra)s?\w*([. _-]|$)', tmp_extra_info, re.I):
                        continue
                    result.extra_info = tmp_extra_info
                    result.score += 1

                if 'release_group' in named_groups:
                    result.release_group = helpers.remove_non_release_groups(match.group('release_group'))
                    result.score += 1

                if 'version' in named_groups:
                    # assigns version to anime file if detected using anime regex. Non-anime regex receives -1
                    version = match.group('version')
                    if version:
                        result.version = version
                    else:
                        result.version = 1
                else:
                    result.version = -1

                matches.append(result)

            if len(matches):
                # pick best match with highest score based on placement
                best_result = max(sorted(matches, reverse=True, key=lambda x: x.which_regex), key=lambda x: x.score)

                show = None
                if not self.naming_pattern:
#.........这里部分代码省略.........
开发者ID:Apocrathia,项目名称:SickGear,代码行数:101,代码来源:parser.py


示例13: _genericName

 def _genericName(name, **kwargs):
     if kwargs.pop('remove', True):
         name = remove_non_release_groups(name, clean_proper=kwargs.pop('clean_proper', False))
     return name.replace('.', ' ').replace('-', ' ').replace('_', ' ').lower()
开发者ID:Thraxis,项目名称:pymedusa,代码行数:4,代码来源:properFinder.py


示例14: subtitles_download_in_pp

    def subtitles_download_in_pp():  # pylint: disable=too-many-locals, too-many-branches
        logger.log(u'Checking for needed subtitles in Post-Process folder', logger.INFO)

        providers = enabled_service_list()
        provider_configs = {'addic7ed': {'username': sickbeard.ADDIC7ED_USER,
                                         'password': sickbeard.ADDIC7ED_PASS},
                            'legendastv': {'username': sickbeard.LEGENDASTV_USER,
                                           'password': sickbeard.LEGENDASTV_PASS},
                            'opensubtitles': {'username': sickbeard.OPENSUBTITLES_USER,
                                              'password': sickbeard.OPENSUBTITLES_PASS}}

        pool = subliminal.api.ProviderPool(providers=providers, provider_configs=provider_configs)

        # Search for all wanted languages
        languages = {from_code(language) for language in wanted_languages()}
        if not languages:
            return

        run_post_process = False
        # Check if PP folder is set
        if sickbeard.TV_DOWNLOAD_DIR and ek(os.path.isdir, sickbeard.TV_DOWNLOAD_DIR):
            for root, _, files in ek(os.walk, sickbeard.TV_DOWNLOAD_DIR, topdown=False):
                for video_filename in sorted(files):
                    try:
                        # Remove non release groups from video file. Needed to match subtitles
                        new_video_filename = remove_non_release_groups(video_filename)
                        if new_video_filename != video_filename:
                            os.rename(video_filename, new_video_filename)
                            video_filename = new_video_filename
                    except Exception as error:
                        logger.log(u'Could not remove non release groups from video file. Error: %r'
                                   % ex(error), logger.DEBUG)
                    if isMediaFile(video_filename):
                        try:
                            video = subliminal.scan_video(os.path.join(root, video_filename),
                                                          subtitles=False, embedded_subtitles=False)
                            subtitles_list = pool.list_subtitles(video, languages)

                            if not subtitles_list:
                                logger.log(u'No subtitles found for %s'
                                           % ek(os.path.join, root, video_filename), logger.DEBUG)
                                continue

                            logger.log(u'Found subtitle(s) canditate(s) for %s' % video_filename, logger.INFO)
                            hearing_impaired = sickbeard.SUBTITLES_HEARING_IMPAIRED
                            user_score = 132 if sickbeard.SUBTITLES_PERFECT_MATCH else 111
                            found_subtitles = pool.download_best_subtitles(subtitles_list, video, languages=languages,
                                                                           hearing_impaired=hearing_impaired,
                                                                           min_score=user_score,
                                                                           only_one=not sickbeard.SUBTITLES_MULTI)

                            for subtitle in subtitles_list:
                                matches = subtitle.get_matches(video, hearing_impaired=False)
                                score = subliminal.subtitle.compute_score(matches, video)
                                logger.log(u"[%s] Subtitle score for %s is: %s (min=%s)"
                                           % (subtitle.provider_name, subtitle.id, score, user_score), logger.DEBUG)

                            downloaded_languages = set()
                            for subtitle in found_subtitles:
                                logger.log(u"Found subtitle for %s in %s provider with language %s"
                                           % (os.path.join(root, video_filename), subtitle.provider_name,
                                              subtitle.language.opensubtitles), logger.DEBUG)
                                subliminal.save_subtitles(video, found_subtitles, directory=root,
                                                          single=not sickbeard.SUBTITLES_MULTI)

                                subtitles_multi = not sickbeard.SUBTITLES_MULTI
                                subtitle_path = subliminal.subtitle.get_subtitle_path(video.name,
                                                                                      None if subtitles_multi else
                                                                                      subtitle.language)
                                if root is not None:
                                    subtitle_path = ek(os.path.join, root, ek(os.path.split, subtitle_path)[1])
                                sickbeard.helpers.chmodAsParent(subtitle_path)
                                sickbeard.helpers.fixSetGroupID(subtitle_path)

                                downloaded_languages.add(subtitle.language.opensubtitles)

                            # Don't run post processor unless at least one file has all of the needed subtitles
                            if not needs_subtitles(downloaded_languages):
                                run_post_process = True
                        except Exception as error:
                            logger.log(u"Error occurred when downloading subtitles for: %s. Error: %r"
                                       % (os.path.join(root, video_filename), ex(error)))
            if run_post_process:
                logger.log(u"Starting post-process with default settings now that we found subtitles")
                processTV.processDir(sickbeard.TV_DOWNLOAD_DIR)
开发者ID:madtrix74,项目名称:SickRage,代码行数:85,代码来源:subtitles.py


示例15: subtitles_download_in_pp

    def subtitles_download_in_pp():  # pylint: disable=too-many-locals, too-many-branches
        logger.log(u'Checking for needed subtitles in Post-Process folder', logger.INFO)

        providers = enabled_service_list()
        provider_configs = {'addic7ed': {'username': sickbeard.ADDIC7ED_USER,
                                         'password': sickbeard.ADDIC7ED_PASS},
                            'legendastv': {'username': sickbeard.LEGENDASTV_USER,
                                           'password': sickbeard.LEGENDASTV_PASS},
                            'opensubtitles': {'username': sickbeard.OPENSUBTITLES_USER,
                                              'password': sickbeard.OPENSUBTITLES_PASS}}

        pool = ProviderPool(providers=providers, provider_configs=provider_configs)

        # Search for all wanted languages
        languages = {from_code(language) for language in wanted_languages()}
        if not languages:
            return

        run_post_process = False
        # Check if PP folder is set
        if sickbeard.TV_DOWNLOAD_DIR and os.path.isdir(sickbeard.TV_DOWNLOAD_DIR):

            for root, _, files in os.walk(sickbeard.TV_DOWNLOAD_DIR, topdown=False):
                rar_files = [x for x in files if isRarFile(x)]
                if rar_files and sickbeard.UNPACK:
                    video_files = [x for x in files if isMediaFile(x)]
                    if u'_UNPACK' not in root and (not video_files or root == sickbeard.TV_DOWNLOAD_DIR):
                        logger.log(u'Found rar files in post-process folder: {}'.format(rar_files), logger.DEBUG)
                        result = processTV.ProcessResult()
                        processTV.unRAR(root, rar_files, False, result)
                elif rar_files and not sickbeard.UNPACK:
                    logger.log(u'Unpack is disabled. Skipping: {}'.format(rar_files), logger.WARNING)

            for root, _, files in os.walk(sickbeard.TV_DOWNLOAD_DIR, topdown=False):
                for video_filename in sorted(files):
                    try:
                        # Remove non release groups from video file. Needed to match subtitles
                        new_video_filename = remove_non_release_groups(video_filename)
                        if new_video_filename != video_filename:
                            os.rename(video_filename, new_video_filename)
                            video_filename = new_video_filename
                    except Exception as error:
                        logger.log(u'Couldn\'t remove non release groups from video file. Error: {}'.format
                                   (ex(error)), logger.DEBUG)
                    if isMediaFile(video_filename):
                        try:
                            video = subliminal.scan_video(os.path.join(root, video_filename),
                                                          subtitles=False, embedded_subtitles=False)
                            subtitles_list = pool.list_subtitles(video, languages)

                            for provider in providers:
                                if provider in pool.discarded_providers:
                                    logger.log(u'Could not search in {} provider. Discarding for now'.format(provider), logger.DEBUG)

                            if not subtitles_list:
                                logger.log(u'No subtitles found for {}'.format
                                           (os.path.join(root, video_filename)), logger.DEBUG)
                                continue

                            logger.log(u'Found subtitle(s) canditate(s) for {}'.format(video_filename), logger.INFO)
                            hearing_impaired = sickbeard.SUBTITLES_HEARING_IMPAIRED
                            user_score = 213 if sickbeard.SUBTITLES_PERFECT_MATCH else 204
                            found_subtitles = pool.download_best_subtitles(subtitles_list, video, languages=languages,
                                                                           hearing_impaired=hearing_impaired,
                                                                           min_score=user_score,
                                                                           only_one=not sickbeard.SUBTITLES_MULTI)

                            for subtitle in subtitles_list:
                                score = subliminal.score.compute_score(subtitle, video, hearing_impaired=sickbeard.SUBTITLES_HEARING_IMPAIRED)
                                logger.log(u'[{}] Subtitle score for {} is: {} (min={})'.format
                                           (subtitle.provider_name, subtitle.id, score, user_score), logger.DEBUG)

                            downloaded_languages = set()
                            for subtitle in found_subtitles:
                                logger.log(u'Found subtitle for {} in {} provider with language {}'.format
                                           (os.path.join(root, video_filename), subtitle.provider_name,
                                            subtitle.language.opensubtitles), logger.DEBUG)
                                subliminal.save_subtitles(video, found_subtitles, directory=root,
                                                          single=not sickbeard.SUBTITLES_MULTI)

                                subtitles_multi = not sickbeard.SUBTITLES_MULTI
                                subtitle_path = subliminal.subtitle.get_subtitle_path(video.name,
                                                                                      None if subtitles_multi else
                                                                                      subtitle.language)
                                if root is not None:
                                    subtitle_path = os.path.join(root, os.path.split(subtitle_path)[1])
                                sickbeard.helpers.chmodAsParent(subtitle_path)
                                sickbeard.helpers.fixSetGroupID(subtitle_path)

                                downloaded_languages.add(subtitle.language.opensubtitles)

                            # Don't run post processor unless at least one file has all of the needed subtitles
                            if not needs_subtitles(downloaded_languages):
                                run_post_process = True
                        except Exception as error:
                            logger.log(u'Error occurred when downloading subtitles for: {}. Error: {}'.format
                                       (os.path.join(root, video_filename), ex(error)))
            if run_post_process:
                logger.log(u'Starting post-process with default settings now that we found subtitles')
                processTV.processDir(sickbeard.TV_DOWNLOAD_DIR)
开发者ID:pedro2d10,项目名称:SickRage-FR,代码行数:100,代码来源:subtitles.py


示例16: subtitles_download_in_pp

    def subtitles_download_in_pp():  # pylint: disable=too-many-locals, too-many-branches, too-many-statements
        logger.log(u'Checking for needed subtitles in Post-Process folder', logger.INFO)

        providers = enabled_service_list()
        pool = SubtitleProviderPool()

        # Search for all wanted languages
        languages = {from_code(language) for language in wanted_languages()}
        if not languages:
            return

        # Dict of language exceptions to use with subliminal
        language_exceptions = {'pt-br': 'pob'}

        run_post_process = False
        # Check if PP folder is set
        if sickbeard.TV_DOWNLOAD_DIR and os.path.isdir(sickbeard.TV_DOWNLOAD_DIR):

            for dirpath, dirnames_, files in os.walk(sickbeard.TV_DOWNLOAD_DIR, topdown=False):
                rar_files = [rar_file for rar_file in files if isRarFile(rar_file)]
                if rar_files and sickbeard.UNPACK:
                    video_files = [video_file for video_file in files if isMediaFile(video_file)]
                    if u'_UNPACK' not in dirpath and (not video_files or dirpath == sickbeard.TV_DOWNLOAD_DIR):
                        logger.log(u'Found rar files in post-process folder: {0}'.format(rar_files), logger.DEBUG)
                        result = processTV.ProcessResult()
                        processTV.unRAR(dirpath, rar_files, False, result)
            

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python helpers.replaceExtension函数代码示例发布时间:2022-05-27
下一篇:
Python helpers.remove_file_failed函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap