Python guessit.guessit() Examples

The following are 30 code examples of guessit.guessit(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module guessit , or try the search function .
Example #1
Source File: subs4free.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def get_matches(self, video):
        matches = set()

        # movie
        if isinstance(video, Movie):
            # title
            if video.title and (sanitize(self.title) in (
                    sanitize(name) for name in [video.title] + video.alternative_titles)):
                matches.add('title')
            # year
            if video.year and self.year == video.year:
                matches.add('year')

        # release_group
        if (video.release_group and self.version and
                any(r in sanitize_release_group(self.version)
                    for r in get_equivalent_release_groups(sanitize_release_group(video.release_group)))):
            matches.add('release_group')
        # other properties
        matches |= guess_matches(video, guessit(self.version, {'type': 'movie'}), partial=True)

        return matches 
Example #2
Source File: drone.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def get_guess(self, video, scene_name):
        """
        run guessit on scene_name
        :param video:
        :param scene_name:
        :return:
        """
        ext = os.path.splitext(video.name)[1]
        guess_from = remove_crap_from_fn(scene_name + ext)

        # guess
        hints = {
            "single_value": True,
            "type": "movie",
        }

        return guess_from, guessit(guess_from, options=hints) 
Example #3
Source File: drone.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def get_guess(self, video, scene_name):
        """
        run guessit on scene_name
        :param video:
        :param scene_name:
        :return:
        """
        ext = os.path.splitext(video.name)[1]
        guess_from = remove_crap_from_fn(scene_name + ext)

        # guess
        hints = {
            "single_value": True,
            "type": "episode",
        }

        return guess_from, guessit(guess_from, options=hints) 
Example #4
Source File: nekur.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def get_matches(self, video):
        matches = set()

        if isinstance(video, Movie):
            # title
            if video.title and sanitize(self.title) == sanitize(video.title):
                matches.add('title')
            # year
            if video.year and self.year == video.year:
                matches.add('year')
            # imdb id
            if video.imdb_id and self.imdb_id == video.imdb_id:
                matches.add('imdb_id')
            # fps
            if video.fps and self.fps and not framerate_equal(video.fps, self.fps):
                logger.warning("nekur: Wrong FPS (expected: %s, got: %s)", video.fps, self.fps)
            # guess additional info from notes 
            matches |= guess_matches(video, guessit(self.notes, {'type': 'movie'}), partial=True)          

        self.matches = matches
        return matches 
Example #5
Source File: video.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def fromguess(cls, name, guess):
        if guess['type'] != 'episode':
            raise ValueError('The guess must be an episode guess')

        if 'title' not in guess or 'episode' not in guess:
            raise ValueError('Insufficient data to process the guess')

        # Currently we only have single-ep support (guessit returns a multi-ep as a list with int values)
        # Most providers only support single-ep, so make sure it contains only 1 episode
        # In case of multi-ep, take the lowest episode (subtitles will normally be available on lowest episode number)
        episode_guess = guess.get('episode')
        episode = min(episode_guess) if episode_guess and isinstance(episode_guess, list) else episode_guess

        return cls(name, guess['title'], guess.get('season', 1), episode, title=guess.get('episode_title'),
                   year=guess.get('year'), format=guess.get('format'), original_series='year' not in guess,
                   release_group=guess.get('release_group'), resolution=guess.get('screen_size'),
                   video_codec=guess.get('video_codec'), audio_codec=guess.get('audio_codec')) 
Example #6
Source File: yavkanet.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def get_matches(self, video):
        matches = set()

        video_filename = video.name
        video_filename = os.path.basename(video_filename)
        video_filename, _ = os.path.splitext(video_filename)
        video_filename = sanitize_release_group(video_filename)

        subtitle_filename = self.filename
        subtitle_filename = os.path.basename(subtitle_filename)
        subtitle_filename, _ = os.path.splitext(subtitle_filename)
        subtitle_filename = sanitize_release_group(subtitle_filename)

        if video_filename == subtitle_filename:
             matches.add('hash')

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

        matches |= guess_matches(video, guessit(self.title, {'type': self.type, 'allowed_countries': [None]}))
        matches |= guess_matches(video, guessit(self.filename, {'type': self.type, 'allowed_countries': [None]}))
        return matches 
Example #7
Source File: subs4series.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def get_matches(self, video):
        matches = set()

        # episode
        if isinstance(video, Episode):
            # series name
            if video.series and sanitize(self.series) in (
                    sanitize(name) for name in [video.series] + video.alternative_series):
                matches.add('series')
            # year
            if video.original_series and self.year is None or video.year and video.year == self.year:
                matches.add('year')

        # release_group
        if (video.release_group and self.version and
                any(r in sanitize_release_group(self.version)
                    for r in get_equivalent_release_groups(sanitize_release_group(video.release_group)))):
            matches.add('release_group')
        # other properties
        matches |= guess_matches(video, guessit(self.version, {'type': 'episode'}), partial=True)

        return matches 
Example #8
Source File: subsunacs.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def get_matches(self, video):
        matches = set()

        video_filename = video.name
        video_filename = os.path.basename(video_filename)
        video_filename, _ = os.path.splitext(video_filename)
        video_filename = sanitize_release_group(video_filename)

        subtitle_filename = self.filename
        subtitle_filename = os.path.basename(subtitle_filename)
        subtitle_filename, _ = os.path.splitext(subtitle_filename)
        subtitle_filename = sanitize_release_group(subtitle_filename)

        if video_filename == subtitle_filename:
             matches.add('hash')

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

        matches |= guess_matches(video, guessit(self.title, {'type': self.type, 'allowed_countries': [None]}))
        matches |= guess_matches(video, guessit(self.filename, {'type': self.type, 'allowed_countries': [None]}))
        return matches 
Example #9
Source File: omdbapi.py    From Cinema with MIT License 6 votes vote down vote up
def search(self, name):
        infos = guessit.guessit(name)
        if not infos.get('title'):
            return
        try:
            params = urlencode({'s': infos['title'], 'y': infos['year'], 'type': 'movie', 'r': 'json', 'apikey': settings.OMDB_API_KEY})
        except KeyError:
            params = urlencode({'s': infos['title'], 'type': 'movie', 'r': 'json', 'apikey': settings.OMDB_API_KEY})
        url = 'http://www.omdbapi.com/?%s' % params

        async with self.aiohttp_session.get(url) as resp:
            data = await resp.text()
            print(url, data)
            resp = json.loads(data)
            if "Search" in resp:
                for res in resp['Search']:
                    poster = res['Poster'] if res['Poster'] != 'N/A' else ""
                    return Movie(
                        title=res['Title'],
                        imdbid=res['imdbID'],
                        poster=await save_poster(poster, self.loop, self.aiohttp_session),
                    ) 
Example #10
Source File: subtitles.py    From touchandgo with GNU General Public License v3.0 6 votes vote down vote up
def download(self, video_file):
        subtitle = None
        settings = get_settings()
        download_dir = settings.save_path
        log.info("Downloading subtitle")
        filepath = join(download_dir, video_file[0])
        guess = guessit(filepath)
        video = Video.fromguess(filepath, guess)
        video.size = video_file[1]
        try:
            subtitles = download_best_subtitles([video], {Language(self.lang)},
                                                only_one=True)
        except ValueError:
            pass
        if subtitles is not None and len(subtitles):
            subs = subtitles.values()[0]
            if len(subs):
                save_subtitles(video, subs, single=True, encoding="utf-8")
                subtitle = get_subtitle_path(video.name, None)

        log.info("video_file: %s, filepath: %s, guess: %s, video: %s, "
                 "subtitle: %s", video_file, filepath, guess, video, subtitle)
        return subtitle 
Example #11
Source File: wizdom.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def get_matches(self, video):
        matches = set()

        # episode
        if isinstance(video, Episode):
            # series
            if video.series and (sanitize(self.title) in (
                    sanitize(name) for name in [video.series] + video.alternative_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')
            # imdb_id
            if video.series_imdb_id and self.imdb_id == video.series_imdb_id:
                matches.add('series_imdb_id')
            # guess
            matches |= guess_matches(video, guessit(self.release, {'type': 'episode'}), partial=True)
        # movie
        elif isinstance(video, Movie):
            # guess
            matches |= guess_matches(video, guessit(self.release, {'type': 'movie'}), partial=True)

            # title
            if video.title and (sanitize(self.title) in (
                    sanitize(name) for name in [video.title] + video.alternative_titles)):
                matches.add('title')

        return matches 
Example #12
Source File: subdivx.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def _get_subtitle_from_archive(self, archive, subtitle):
        _max_score = 0
        _scores = get_scores (subtitle.video)

        for name in archive.namelist():
            # discard hidden files
            if os.path.split(name)[-1].startswith('.'):
                continue

            # discard non-subtitle files
            if not name.lower().endswith(SUBTITLE_EXTENSIONS):
                continue

            _guess = guessit (name)
            if isinstance(subtitle.video, Episode):
                logger.debug ("guessing %s" % name)
                logger.debug("subtitle S{}E{} video S{}E{}".format(_guess['season'],_guess['episode'],subtitle.video.season,subtitle.video.episode))

                if subtitle.video.episode != _guess['episode'] or subtitle.video.season != _guess['season']:
                    logger.debug('subtitle does not match video, skipping')
                    continue

            matches = set()
            matches |= guess_matches (subtitle.video, _guess)
            _score = sum ((_scores.get (match, 0) for match in matches))
            logger.debug('srt matches: %s, score %d' % (matches, _score))
            if _score > _max_score:
                _max_name = name
                _max_score = _score
                logger.debug("new max: {} {}".format(name, _score))

        if _max_score > 0:
            logger.debug("returning from archive: {} scored {}".format(_max_name, _max_score))
            return archive.read(_max_name)

        raise APIThrottled('Can not find the subtitle in the compressed file') 
Example #13
Source File: models.py    From GetSubtitles with MIT License 5 votes vote down vote up
def __init__(self, video_path, sub_store_path="", identifier=""):
        self.name, self.type = splitext(basename(video_path))
        self.path = abspath(dirname(video_path))
        self.sub_store_path = abspath(sub_store_path) if sub_store_path else self.path
        self.sub_identifier = identifier
        self.has_subtitle = Video.sub_exists(
            self.name, self.sub_store_path, self.sub_identifier
        )
        self.extracted_name = extract_name(self.name)
        self.info = guessit(self.extracted_name + self.type) 
Example #14
Source File: hosszupuska.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def get_matches(self, video):
        matches = set()
        # series
        if video.series and ( sanitize(self.series) == sanitize(fix_inconsistent_naming(video.series)) or sanitize(self.series) == sanitize(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')
        # year
        if ('series' in matches and video.original_series and self.year is None or
           video.year and video.year == self.year):
            matches.add('year')

        # release_group
        if (video.release_group and self.version and
                any(r in sanitize_release_group(self.version)
                    for r in get_equivalent_release_groups(sanitize_release_group(video.release_group)))):
            matches.add('release_group')
        # resolution
        if video.resolution and self.version and video.resolution in self.version.lower():
            matches.add('resolution')
        # format
        if video.format and self.version and video.format.lower() in self.version.lower():
            matches.add('format')
        # other properties
        matches |= guess_matches(video, guessit(self.release_info))

        return matches 
Example #15
Source File: greeksubtitles.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def get_matches(self, video):
        matches = set()

        # episode
        if isinstance(video, Episode):
            # other properties
            matches |= guess_matches(video, guessit(self.version, {'type': 'episode'}), partial=True)
        # movie
        elif isinstance(video, Movie):
            # other properties
            matches |= guess_matches(video, guessit(self.version, {'type': 'movie'}), partial=True)

        return matches 
Example #16
Source File: subssabbz.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def get_matches(self, video):
        matches = set()

        video_filename = video.name
        video_filename = os.path.basename(video_filename)
        video_filename, _ = os.path.splitext(video_filename)
        video_filename = sanitize_release_group(video_filename)

        subtitle_filename = self.filename
        subtitle_filename = os.path.basename(subtitle_filename)
        subtitle_filename, _ = os.path.splitext(subtitle_filename)
        subtitle_filename = sanitize_release_group(subtitle_filename)

        if video_filename == subtitle_filename:
             matches.add('hash')

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

        if isinstance(video, Movie):
            if video.imdb_id and self.imdb_id == video.imdb_id:
                matches.add('imdb_id')

        matches |= guess_matches(video, guessit(self.title, {'type': self.type, 'allowed_countries': [None]}))
        matches |= guess_matches(video, guessit(self.filename, {'type': self.type, 'allowed_countries': [None]}))
        return matches 
Example #17
Source File: subscene.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def get_matches(self, video):
        matches = set()

        if self.release_info.strip() == get_video_filename(video):
            logger.debug("Using hash match as the release name is the same")
            matches |= {"hash"}

        # episode
        if isinstance(video, Episode):
            guess = guessit(self.release_info, {'type': 'episode'})
            self.season = guess.get("season")
            self.episode = guess.get("episode")

            matches |= guess_matches(video, guess)
            if "season" in matches and "episode" not in guess:
                # pack
                matches.add("episode")
                logger.debug("%r is a pack", self)
                self.is_pack = True

        # movie
        else:
            guess = guessit(self.release_info, {'type': 'movie'})
            matches |= guess_matches(video, guess)

        if video.release_group and "release_group" not in matches and "release_group" in guess:
            if sanitize_release_group(video.release_group) in sanitize_release_group(guess["release_group"]):
                matches.add("release_group")

        self.matches = matches

        return matches 
Example #18
Source File: betaseries.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def get_matches(self, video):
        matches = self.matches

        if isinstance(video, Episode):
            matches |= guess_matches(video, guessit(
                self.video_name, {'type': 'episode'}), partial=True)

        return matches 
Example #19
Source File: assrt.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def _get_detail(self):
        if self._detail:
            return self._detail
        params = {'token': self.token, 'id': self.id}
        logger.info('Get subtitle detail: GET /sub/detail %r', params)
        r = self.session.get(server_url + '/sub/detail', params=params, timeout=10)
        r.raise_for_status()

        result = r.json()
        sub = result['sub']['subs'][0]
        files = sub['filelist']

        # first pass: guessit
        for f in files:
            guess = guessit(f['f'], self.guessit_options)
            langs = set()
            if 'language' in guess:
                langs.update(guess['language'])
            if 'subtitle_language' in guess:
                langs.update(guess['subtitle_language'])
            if self.language in langs:
                self._defail = f
                return f

        # second pass: keyword matching
        codes = language_converters['assrt'].codes
        for f in files:
            langs = set([ Language.fromassrt(k) for k in codes if k in f['f'] ])
            if self.language in langs:
                self._defail = f
                return f

        # fallback: pick up first file if nothing matches
        return files[0] 
Example #20
Source File: assrt.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def get_matches(self, video):
        matches = guess_matches(video, guessit(self.video_name))
        return matches 
Example #21
Source File: xsubs.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def get_matches(self, video):
        matches = set()

        if isinstance(video, Episode):
            # series name
            if video.series and sanitize(self.series) in (
                    sanitize(name) for name in [video.series] + video.alternative_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')
            # title of the episode
            if video.title and sanitize(self.title) == sanitize(video.title):
                matches.add('title')
            # year
            if video.original_series and self.year is None or video.year and video.year == self.year:
                matches.add('year')
            # release_group
            if (video.release_group and self.version and
                    any(r in sanitize_release_group(self.version)
                        for r in get_equivalent_release_groups(sanitize_release_group(video.release_group)))):
                matches.add('release_group')
            # other properties
            matches |= guess_matches(video, guessit(self.version, {'type': 'episode'}), partial=True)

        return matches 
Example #22
Source File: video.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def fromname(cls, name):
        return cls.fromguess(name, guessit(name, {'type': 'episode'})) 
Example #23
Source File: util.py    From GetSubtitles with MIT License 5 votes vote down vote up
def guess_subtitle(sublist, video_detail):
    """
    传入字幕列表,视频信息,返回得分最高字幕名

    params:
        sublist: list of str
        video_detail: result of guessit
    return:
        success: bool
        subname: str
    """

    if not sublist:
        return False, None

    scores, subs = [], []
    for one_sub in sublist:
        _, ftype = path.splitext(one_sub)
        if ftype not in SUB_FORMATS:
            continue
        subs.append(one_sub)
        subname = path.split(one_sub)[-1]  # extract subtitle name
        try:
            # zipfile:/Lib/zipfile.py:1211 Historical ZIP filename encoding
            # try cp437 encoding
            subname = subname.encode("cp437").decode("gbk")
        except Exception:
            pass
        score = compute_subtitle_score(video_detail, subname)
        scores.append(score)

    max_score = max(scores)
    max_pos = scores.index(max_score)
    return max_score > 0, subs[max_pos] 
Example #24
Source File: file_info.py    From trakt-scrobbler with GNU General Public License v2.0 5 votes vote down vote up
def use_guessit(file_path):
    return guessit.guessit(str(file_path)) 
Example #25
Source File: __init__.py    From touchandgo with GNU General Public License v3.0 5 votes vote down vote up
def guess(self, path):
        if self._guess is None:
            self._guess = guessit(path)
        return self._guess 
Example #26
Source File: resolvers.py    From Cinema with MIT License 5 votes vote down vote up
def resolve(self, path, movie):
        if movie.title:
            return movie
        #Report.fail += 1
        name, ext = os.path.splitext(os.path.basename(path))
        infos = guessit.guessit(name)
        if infos.get('title'):
            return Movie(title=infos['title'])
        else:
            return Movie(title=name) 
Example #27
Source File: metadata.py    From mnamer with MIT License 5 votes vote down vote up
def _parse_path_data(self, file_path: Path):
        options = {"type": getattr(self.media, "value", None)}
        raw_data = dict(guessit(str(file_path), options))
        if isinstance(raw_data.get("season"), list):
            raw_data = dict(guessit(str(file_path.parts[-1]), options))
        for k, v in raw_data.items():
            if hasattr(v, "alpha3"):
                self._path_data[k] = Language.parse(v)
            elif isinstance(v, (int, str, date)):
                self._path_data[k] = v
            elif isinstance(v, list) and all(
                [isinstance(_, (int, str)) for _ in v]
            ):
                self._path_data[k] = v[0] 
Example #28
Source File: legendastv.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def get_matches(self, video, hearing_impaired=False):
        matches = set()

        # episode
        if isinstance(video, Episode) and self.type == 'episode':
            # series
            if video.series and (sanitize(self.title) in (
                    sanitize(name) for name in [video.series] + video.alternative_series)):
                matches.add('series')

            # year
            if video.original_series and self.year is None or video.year and video.year == self.year:
                matches.add('year')

            # imdb_id
            if video.series_imdb_id and self.imdb_id == video.series_imdb_id:
                matches.add('series_imdb_id')

        # movie
        elif isinstance(video, Movie) and self.type == 'movie':
            # title
            if video.title and (sanitize(self.title) in (
                    sanitize(name) for name in [video.title] + video.alternative_titles)):
                matches.add('title')

            # year
            if video.year and self.year == video.year:
                matches.add('year')

            # imdb_id
            if video.imdb_id and self.imdb_id == video.imdb_id:
                matches.add('imdb_id')

        # name
        matches |= guess_matches(video, guessit(self.name, {'type': self.type}))

        return matches 
Example #29
Source File: tvsubtitles.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def get_matches(self, video):
        matches = set()

        # series
        if video.series and (sanitize(self.series) in (
                sanitize(name) for name in [video.series] + video.alternative_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')
        # year
        if video.original_series and self.year is None or video.year and video.year == self.year:
            matches.add('year')
        # release_group
        if (video.release_group and self.release and
                any(r in sanitize_release_group(self.release)
                    for r in get_equivalent_release_groups(sanitize_release_group(video.release_group)))):
            matches.add('release_group')
        # other properties
        if self.release:
            matches |= guess_matches(video, guessit(self.release, {'type': 'episode'}), partial=True)
        if self.rip:
            matches |= guess_matches(video, guessit(self.rip), partial=True)

        return matches 
Example #30
Source File: subscenter.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def get_matches(self, video):
        matches = set()

        # episode
        if isinstance(video, Episode):
            # series
            if video.series and sanitize(self.series) == sanitize(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, guessit(release, {'type': 'episode'}))
        # movie
        elif isinstance(video, Movie):
            # guess
            for release in self.releases:
                matches |= guess_matches(video, guessit(release, {'type': 'movie'}))

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

        return matches