本文整理汇总了Python中babelfish.Language.fromopensubtitles方法的典型用法代码示例。如果您正苦于以下问题:Python Language.fromopensubtitles方法的具体用法?Python Language.fromopensubtitles怎么用?Python Language.fromopensubtitles使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类babelfish.Language
的用法示例。
在下文中一共展示了Language.fromopensubtitles方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_converter_opensubtitles
# 需要导入模块: from babelfish import Language [as 别名]
# 或者: from babelfish.Language import fromopensubtitles [as 别名]
def test_converter_opensubtitles(self):
self.assertEqual(Language('fra').opensubtitles, Language('fra').alpha3b)
self.assertEqual(Language('por', 'BR').opensubtitles, 'pob')
self.assertEqual(Language.fromopensubtitles('fre'), Language('fra'))
self.assertEqual(Language.fromopensubtitles('pob'), Language('por', 'BR'))
self.assertEqual(Language.fromopensubtitles('pb'), Language('por', 'BR'))
# Montenegrin is not recognized as an ISO language (yet?) but for now it is
# unofficially accepted as Serbian from Montenegro
self.assertEqual(Language.fromopensubtitles('mne'), Language('srp', 'ME'))
self.assertEqual(Language.fromcode('pob', 'opensubtitles'), Language('por', 'BR'))
with self.assertRaises(LanguageReverseError):
Language.fromopensubtitles('zzz')
with self.assertRaises(LanguageConvertError):
Language('aaa').opensubtitles
self.assertEqual(len(get_language_converter('opensubtitles').codes), 606)
# test with all the languages from the opensubtitles api
# downloaded from: http://www.opensubtitles.org/addons/export_languages.php
f = resource_stream('babelfish', 'data/opensubtitles_languages.txt')
f.readline()
for l in f:
idlang, alpha2, _, upload_enabled, web_enabled = l.decode('utf-8').strip().split('\t')
if not int(upload_enabled) and not int(web_enabled):
# do not test languages that are too esoteric / not widely available
continue
self.assertEqual(Language.fromopensubtitles(idlang).opensubtitles, idlang)
if alpha2:
self.assertEqual(Language.fromopensubtitles(idlang), Language.fromopensubtitles(alpha2))
f.close()
示例2: scan_subtitle_languages
# 需要导入模块: from babelfish import Language [as 别名]
# 或者: from babelfish.Language import fromopensubtitles [as 别名]
def scan_subtitle_languages(path):
language_extensions = tuple('.' + c for c in language_converters['opensubtitles'].codes)
dirpath, filename = os.path.split(path)
subtitles = set()
for p in os.listdir(dirpath):
if not isinstance(p, bytes) and p.startswith(os.path.splitext(filename)[0]) and p.endswith(subliminal.video.SUBTITLE_EXTENSIONS):
if os.path.splitext(p)[0].endswith(language_extensions) and len(os.path.splitext(p)[0].rsplit('.', 1)[1]) is 2:
subtitles.add(Language.fromopensubtitles(os.path.splitext(p)[0][-2:]))
elif os.path.splitext(p)[0].endswith(language_extensions) and len(os.path.splitext(p)[0].rsplit('.', 1)[1]) is 3:
subtitles.add(Language.fromopensubtitles(os.path.splitext(p)[0][-3:]))
else:
subtitles.add(Language('und'))
return subtitles
示例3: fix_subtitles_codes
# 需要导入模块: from babelfish import Language [as 别名]
# 或者: from babelfish.Language import fromopensubtitles [as 别名]
def fix_subtitles_codes(self):
sqlResults = self.connection.select(
"SELECT subtitles, episode_id FROM tv_episodes WHERE subtitles != '' AND subtitles_lastsearch < ?;",
[datetime.datetime(2015, 7, 15, 17, 20, 44, 326380).strftime(dateTimeFormat)])
validLanguages = [Language.fromopensubtitles(language).opensubtitles for language in language_converters['opensubtitles'].codes if len(language) == 3]
if not sqlResults:
return
for sqlResult in sqlResults:
langs = []
logger.log("Checking subtitle codes for episode_id: %s, codes: %s" %
(sqlResult['episode_id'], sqlResult['subtitles']), logger.DEBUG)
for subcode in sqlResult['subtitles'].split(','):
if not len(subcode) is 3 or not subcode in validLanguages:
logger.log("Fixing subtitle codes for episode_id: %s, invalid code: %s" %
(sqlResult['episode_id'], subcode), logger.DEBUG)
continue
langs.append(subcode)
self.connection.action("UPDATE tv_episodes SET subtitles = ?, subtitles_lastsearch = ? WHERE episode_id = ?;",
[','.join(langs), datetime.datetime.now().strftime(dateTimeFormat), sqlResult['episode_id']])
示例4: query
# 需要导入模块: from babelfish import Language [as 别名]
# 或者: from babelfish.Language import fromopensubtitles [as 别名]
def query(self, languages, hash=None, size=None, imdb_id=None, query=None, season=None, episode=None, tag=None):
# fill the search criteria
criteria = []
if hash and size:
criteria.append({'moviehash': hash, 'moviebytesize': str(size)})
if imdb_id:
if season and episode:
criteria.append({'imdbid': imdb_id[2:], 'season': season, 'episode': episode})
else:
criteria.append({'imdbid': imdb_id[2:]})
if tag:
criteria.append({'tag': tag})
if query and season and episode:
criteria.append({'query': query.replace('\'', ''), 'season': season, 'episode': episode})
elif query:
criteria.append({'query': query.replace('\'', '')})
if not criteria:
raise ValueError('Not enough information')
# add the language
for criterion in criteria:
criterion['sublanguageid'] = ','.join(sorted(l.opensubtitles for l in languages))
# query the server
logger.info('Searching subtitles %r', criteria)
response = checked(self.server.SearchSubtitles(self.token, criteria))
subtitles = []
# exit if no data
if not response['data']:
logger.debug('No subtitles found')
return subtitles
# loop over subtitle items
for subtitle_item in response['data']:
# read the item
language = Language.fromopensubtitles(subtitle_item['SubLanguageID'])
hearing_impaired = bool(int(subtitle_item['SubHearingImpaired']))
page_link = subtitle_item['SubtitlesLink']
subtitle_id = int(subtitle_item['IDSubtitleFile'])
matched_by = subtitle_item['MatchedBy']
movie_kind = subtitle_item['MovieKind']
hash = subtitle_item['MovieHash']
movie_name = subtitle_item['MovieName']
movie_release_name = subtitle_item['MovieReleaseName']
movie_year = int(subtitle_item['MovieYear']) if subtitle_item['MovieYear'] else None
movie_imdb_id = 'tt' + subtitle_item['IDMovieImdb']
series_season = int(subtitle_item['SeriesSeason']) if subtitle_item['SeriesSeason'] else None
series_episode = int(subtitle_item['SeriesEpisode']) if subtitle_item['SeriesEpisode'] else None
filename = subtitle_item['SubFileName']
encoding = subtitle_item.get('SubEncoding') or None
subtitle = self.subtitle_class(language, hearing_impaired, page_link, subtitle_id, matched_by, movie_kind,
hash, movie_name, movie_release_name, movie_year, movie_imdb_id,
series_season, series_episode, filename, encoding)
logger.debug('Found subtitle %r by %s', subtitle, matched_by)
subtitles.append(subtitle)
return subtitles
示例5: from_code
# 需要导入模块: from babelfish import Language [as 别名]
# 或者: from babelfish.Language import fromopensubtitles [as 别名]
def from_code(code, unknown='und'):
"""Convert an opensubtitles language code to a proper babelfish.Language object.
:param code: an opensubtitles language code to be converted
:type code: str
:param unknown: the code to be returned for unknown language codes
:type unknown: str
:return: a language object
:rtype: babelfish.Language
"""
code = code.strip()
if code and code in language_converters['opensubtitles'].codes:
return Language.fromopensubtitles(code) # pylint: disable=no-member
return Language(unknown) if unknown else None
示例6: fromietf
# 需要导入模块: from babelfish import Language [as 别名]
# 或者: from babelfish.Language import fromopensubtitles [as 别名]
def fromietf(language):
return Language.fromopensubtitles(language)
示例7: subtitleCodeFilter
# 需要导入模块: from babelfish import Language [as 别名]
# 或者: from babelfish.Language import fromopensubtitles [as 别名]
def subtitleCodeFilter():
return [Language.fromopensubtitles(language).opensubtitles for language in language_converters['opensubtitles'].codes if len(language) == 3]
示例8: from_code
# 需要导入模块: from babelfish import Language [as 别名]
# 或者: from babelfish.Language import fromopensubtitles [as 别名]
def from_code(language):
language = language.strip()
if language and language in language_converters['opensubtitles'].codes:
return Language.fromopensubtitles(language) # pylint: disable=no-member
return Language('und')
示例9: from_code
# 需要导入模块: from babelfish import Language [as 别名]
# 或者: from babelfish.Language import fromopensubtitles [as 别名]
def from_code(language):
language = language.strip()
if language and language in language_converters['opensubtitles'].codes:
return Language.fromopensubtitles(language)
return Language('und')
示例10: _do_search_subtitles
# 需要导入模块: from babelfish import Language [as 别名]
# 或者: from babelfish.Language import fromopensubtitles [as 别名]
def _do_search_subtitles(self, videos_hashcode, languages):
""" Search list of subtitles. """
subtitles_infos = []
# Search subtitles
hashcodes_sizes = [
{'moviehash': hash_code, 'moviebytesize': video.size}
for hash_code, video in videos_hashcode.items()
]
response = self._proxy.SearchSubtitles(
self._session_string, hashcodes_sizes)
if self.status_ok(response):
if 'data' in response and response['data']:
for data_subtitle in response['data']:
# Retrieve important info
sub_video_hashcode = data_subtitle['MovieHash']
sub_video = videos_hashcode[sub_video_hashcode]
sub_lang = Language.fromopensubtitles(
data_subtitle['SubLanguageID'])
if sub_lang in sub_video.languages_to_download \
and sub_lang in languages:
# Subtitle infos
sub_id = data_subtitle['IDSubtitleFile']
sub_rating = float(data_subtitle['SubRating'])
sub_format = data_subtitle['SubFormat']
# Video infos
sub_video_name = data_subtitle['MovieName']
if data_subtitle['MovieKind'] == "movie":
sub_video = VideoFactory.make_from_type(
sub_video, Movie)
elif data_subtitle['MovieKind'] == "episode":
sub_video = VideoFactory.make_from_type(
sub_video, Episode)
videos_hashcode[sub_video_hashcode] = sub_video
if isinstance(sub_video, Movie):
sub_video.name = sub_video_name
elif isinstance(sub_video, Episode):
# Retrieves serie name and episode name
match_result = re.match(
self._series_regexp, sub_video_name)
sub_video.name = match_result.group("serie_name")
sub_video.episode_name = match_result.group(
"episode_name")
sub_video.season = int(
data_subtitle['SeriesSeason'])
sub_video.episode = int(
data_subtitle['SeriesEpisode'])
subtitle = Subtitle(
sub_id, sub_lang, sub_video,
sub_rating, sub_format)
subtitles_infos.append(subtitle)
else:
raise SubtitleServerError(
self, "There is no result when searching for subtitles.")
else:
raise SubtitleServerError(self, self.get_status_reason(response))
return subtitles_infos