本文整理汇总了Python中subliminal.save_subtitles函数的典型用法代码示例。如果您正苦于以下问题:Python save_subtitles函数的具体用法?Python save_subtitles怎么用?Python save_subtitles使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了save_subtitles函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_best_subtitle
def get_best_subtitle(self):
# Get a subtitle for a given video file
self.status_bar.pop(self.context_id)
self.status_bar.push(self.context_id, "Downloading Subtitle")
self.timeout = GObject.timeout_add( 100, self.progress_pulse )
self.subtitle = download_best_subtitles(
[self.video],
{ Language( self.language_combo.get_active_text() ) },
providers=[self.provider_combo.get_active_text()] )
try:
self.subtitle = self.subtitle[self.video][0]
self.status_bar.pop(self.context_id)
self.status_bar.push(self.context_id, "Subtitle Downloaded Successfully")
except IndexError:
self.status_bar.pop(self.context_id)
self.status_bar.push(self.context_id, "No Subtitle Found")
GObject.source_remove(self.timeout)
self.progress_bar.set_fraction(0)
return False
save_subtitles(self.video, [self.subtitle])
GObject.source_remove(self.timeout)
self.progress_bar.set_fraction(1)
示例2: subtitle
def subtitle(self, episodes):
# Parse babelfish languages
bb_lang = {Language.fromietf(l) for l in self.languages}
# Create subliminal episode set
sub_episodes = set()
for episode in episodes:
ep_path = os.path.join(episode['dir'], episode['filename'])
sub_episode = Episode.fromguess(ep_path, episode)
# Look for external subtitles (not done automatically, apparently)
sub_episode.subtitle_languages |= set(search_external_subtitles(sub_episode.name).values())
sub_episodes.add(sub_episode)
# download subtitles in the specified language
subl_subtitles = download_best_subtitles(sub_episodes, bb_lang, providers=self.providers)
for video, subtitles in subl_subtitles.items():
save_subtitles(video, subtitles)
# save subtitle languages in episode dict
示例3: test_save_subtitles
def test_save_subtitles(self):
videos = [EPISODES[0], EPISODES[1]]
for video in videos:
video.name = os.path.join(TEST_DIR, os.path.split(video.name)[1])
languages = {Language('eng'), Language('fra')}
subtitles = list_subtitles(videos, languages)
# make a list of subtitles to download (one per language per video)
subtitles_to_download = []
for video, video_subtitles in subtitles.items():
video_subtitle_languages = set()
for video_subtitle in video_subtitles:
if video_subtitle.language in video_subtitle_languages:
continue
subtitles_to_download.append(video_subtitle)
video_subtitle_languages.add(video_subtitle.language)
if video_subtitle_languages == languages:
break
self.assertEqual(len(subtitles_to_download), 4)
# download
download_subtitles(subtitles_to_download)
save_subtitles(subtitles)
for video in videos:
self.assertTrue(os.path.exists(os.path.splitext(video.name)[0] + '.en.srt'))
self.assertTrue(os.path.exists(os.path.splitext(video.name)[0] + '.fr.srt'))
示例4: download_subs
def download_subs(videos, languages):
"""
Will scan for videos newer than one week and try to download
subtitles in English and Spanish for them.
Parameters
----------
videos: list of
languages: list of babelfish.language
"""
nu_vids = []
for vid in videos:
if len(vid.subtitle_languages) == 0:
nu_vids.append(vid)
# download
try:
subs = subliminal.download_best_subtitles(nu_vids, languages)
except:
raise
log.info('Subs found:')
log.info(subs)
# save
log.debug('Saving subtitle files.')
subliminal.save_subtitles(subs, single=False)
示例5: test_save_subtitles
def test_save_subtitles(movies, tmpdir, monkeypatch):
monkeypatch.chdir(str(tmpdir))
tmpdir.ensure(movies['man_of_steel'].name)
subtitle_no_content = Subtitle(Language('eng'))
subtitle = Subtitle(Language('fra'))
subtitle.content = b'Some content'
subtitle_other = Subtitle(Language('fra'))
subtitle_other.content = b'Some other content'
subtitle_pt_br = Subtitle(Language('por', 'BR'))
subtitle_pt_br.content = b'Some brazilian content'
subtitles = [subtitle_no_content, subtitle, subtitle_other, subtitle_pt_br]
save_subtitles(movies['man_of_steel'], subtitles)
# subtitle without content is skipped
path = os.path.join(str(tmpdir), os.path.splitext(movies['man_of_steel'].name)[0] + '.en.srt')
assert not os.path.exists(path)
# first subtitle with language is saved
path = os.path.join(str(tmpdir), os.path.splitext(movies['man_of_steel'].name)[0] + '.fr.srt')
assert os.path.exists(path)
assert io.open(path, 'rb').read() == b'Some content'
# ietf language in path
path = os.path.join(str(tmpdir), os.path.splitext(movies['man_of_steel'].name)[0] + '.pt-BR.srt')
assert os.path.exists(path)
assert io.open(path, 'rb').read() == b'Some brazilian content'
示例6: download_sub
def download_sub(self, language):
l = Language(language)
v = scan_video(self.path)
sub_path = get_subtitle_path(v.name, l)
if not os.path.isfile(sub_path):
sub = download_best_subtitles((v,), {l})
# TODO Save in tmp folder if regular is not available
save_subtitles(sub)
return sub_path
示例7: downloadSubtitles
def downloadSubtitles(subtitles_info):
existing_subtitles = subtitles_info['subtitles']
# First of all, check if we need subtitles
languages = getNeededLanguages(existing_subtitles)
if not languages:
logger.log(u'%s: No missing subtitles for S%02dE%02d' % (subtitles_info['show.indexerid'], subtitles_info['season'], subtitles_info['episode']), logger.DEBUG)
return (existing_subtitles, None)
subtitles_path = getSubtitlesPath(subtitles_info['location']).encode(sickbeard.SYS_ENCODING)
video_path = subtitles_info['location'].encode(sickbeard.SYS_ENCODING)
providers = getEnabledServiceList()
try:
video = subliminal.scan_video(video_path, subtitles=False, embedded_subtitles=False)
except Exception:
logger.log(u'%s: Exception caught in subliminal.scan_video for S%02dE%02d' %
(subtitles_info['show.indexerid'], subtitles_info['season'], subtitles_info['episode']), logger.DEBUG)
return (existing_subtitles, None)
try:
# TODO: Add gui option for hearing_impaired parameter ?
found_subtitles = subliminal.download_best_subtitles([video], languages=languages, hearing_impaired=False, only_one=not sickbeard.SUBTITLES_MULTI, providers=providers)
if not found_subtitles:
logger.log(u'%s: No subtitles found for S%02dE%02d on any provider' % (subtitles_info['show.indexerid'], subtitles_info['season'], subtitles_info['episode']), logger.DEBUG)
return (existing_subtitles, None)
for index, subtitle in enumerate(found_subtitles[video]):
encoding = subliminal.subtitle.Subtitle.guess_encoding(subtitle)
found_subtitles[video][index].encoding = encoding
subliminal.save_subtitles(video, found_subtitles[video], directory=subtitles_path, single=not sickbeard.SUBTITLES_MULTI)
for video, subtitles in found_subtitles.iteritems():
for subtitle in subtitles:
new_video_path = subtitles_path + "/" + video.name.rsplit("/", 1)[-1]
new_subtitles_path = subliminal.subtitle.get_subtitle_path(new_video_path, subtitle.language if sickbeard.SUBTITLES_MULTI else None)
sickbeard.helpers.chmodAsParent(new_subtitles_path)
sickbeard.helpers.fixSetGroupID(new_subtitles_path)
if not sickbeard.EMBEDDED_SUBTITLES_ALL and sickbeard.SUBTITLES_EXTRA_SCRIPTS and video_path.endswith(('.mkv','.mp4')):
run_subs_extra_scripts(subtitles_info, found_subtitles)
current_subtitles = subtitlesLanguages(video_path)[0]
new_subtitles = frozenset(current_subtitles).difference(existing_subtitles)
except Exception as e:
logger.log("Error occurred when downloading subtitles for: %s" % video_path)
logger.log(traceback.format_exc(), logger.ERROR)
return (existing_subtitles, None)
if sickbeard.SUBTITLES_HISTORY:
for video, subtitles in found_subtitles.iteritems():
for subtitle in subtitles:
logger.log(u'history.logSubtitle %s, %s' % (subtitle.provider_name, subtitle.language.opensubtitles), logger.DEBUG)
history.logSubtitle(subtitles_info['show.indexerid'], subtitles_info['season'], subtitles_info['episode'], subtitles_info['status'], subtitle)
return (current_subtitles, new_subtitles)
示例8: test_save_subtitles_single
def test_save_subtitles_single(self):
videos = [EPISODES[0], EPISODES[1]]
for video in videos:
video.name = os.path.join(TEST_DIR, os.path.split(video.name)[1])
languages = {Language('eng'), Language('fra')}
subtitles = download_best_subtitles(videos, languages)
save_subtitles(subtitles, single=True)
for video in videos:
self.assertIn(video, subtitles)
self.assertEqual(len(subtitles[video]), 2)
self.assertTrue(os.path.exists(os.path.splitext(video.name)[0] + '.srt'))
示例9: _download_subtitle
def _download_subtitle():
# download the subtitle
with ProviderPool(providers=self.config.providers, provider_configs=self.config.provider_configs) as pool:
pool.download_subtitle(subtitle)
# save the subtitle
save_subtitles(self.video, [subtitle], single=self.config.single)
# mark the subtitle as downloaded
model.set_value(iter, 6, True)
# stop the spinner
self.spinner.stop()
示例10: test_save_subtitles_single_directory_encoding
def test_save_subtitles_single_directory_encoding(movies, tmpdir):
subtitle = Subtitle(Language('jpn'))
subtitle.content = u'ハローワールド'.encode('shift-jis')
subtitle_pt_br = Subtitle(Language('por', 'BR'))
subtitle_pt_br.content = b'Some brazilian content'
subtitles = [subtitle, subtitle_pt_br]
save_subtitles(movies['man_of_steel'], subtitles, single=True, directory=str(tmpdir), encoding='utf-8')
# first subtitle only and correctly encoded
path = os.path.join(str(tmpdir), os.path.splitext(os.path.split(movies['man_of_steel'].name)[1])[0] + '.srt')
assert os.path.exists(path)
assert io.open(path, encoding='utf-8').read() == u'ハローワールド'
示例11: download_callback
def download_callback(self, menuitem, files):
# scan videos
videos = []
for f in files:
# ignore non-writable locations
if not f.can_write():
continue
# directories
if f.is_directory():
try:
scanned_videos = scan_videos(f.get_location().get_path())
except:
continue
for video in scanned_videos:
if check_video(video, languages=self.config.languages, age=self.config.age,
undefined=self.config.single):
video.subtitle_languages |= set(search_external_subtitles(video.name).values())
refine(video, episode_refiners=self.config.refiners, movie_refiners=self.config.refiners,
embedded_subtitles=self.config.embedded_subtitles)
videos.append(video)
continue
# other inputs
try:
video = scan_video(f.get_location().get_path())
except:
continue
if check_video(video, languages=self.config.languages, undefined=self.config.single):
video.subtitle_languages |= set(search_external_subtitles(video.name).values())
refine(video, episode_refiners=self.config.refiners, movie_refiners=self.config.refiners,
embedded_subtitles=self.config.embedded_subtitles)
videos.append(video)
# download best subtitles
downloaded_subtitles = defaultdict(list)
with AsyncProviderPool(providers=self.config.providers, provider_configs=self.config.provider_configs) as pool:
for v in videos:
scores = get_scores(v)
subtitles = pool.download_best_subtitles(
pool.list_subtitles(v, self.config.languages - v.subtitle_languages),
v, self.config.languages, min_score=scores['hash'] * self.config.min_score / 100,
hearing_impaired=self.config.hearing_impaired, only_one=self.config.single
)
downloaded_subtitles[v] = subtitles
# save subtitles
for v, subtitles in downloaded_subtitles.items():
save_subtitles(v, subtitles, single=self.config.single)
示例12: downloadsubtitles
def downloadsubtitles(self_) :
LOGGER.info('*** START DOWNLOADING SUBTITLES ***')
if SIMULATE_MODE :
return
# scan for videos in the folder and their subtitles
videos = subliminal.scan_videos(self_.scanPath, subtitles=True, embedded_subtitles=True)
# download
subs = subliminal.download_best_subtitles(videos, {babelfish.Language('eng')})
# save
for video, sub in subs.items():
subliminal.save_subtitles(video, sub)
示例13: save
def save(self):
"""
Save the subtitle without further handling
"""
log.info("Saving subtitle")
# Check download_item
if 'video' in self._keys and 'subtitles' in self._keys and 'single' in self._keys:
# Save the subtitle
video = self._download_item['video']
subliminal.save_subtitles(video, self._download_item['subtitles'][video], self._download_item['single'])
return True
else:
log.error("Download item is not complete, skipping")
return False
示例14: download_subs
def download_subs(file):
print(" Analyzing video file...")
try:
video = scan_video(file['full_path'])
except ValueError as ex:
print(" Failed to analyze video. ", ex)
return None
print(" Choosing subtitle from online providers...")
best_subtitles = download_best_subtitles({video}, {Language('eng')}, only_one=True)
if best_subtitles[video]:
sub = best_subtitles[video][0]
print(" Choosen subtitle: {f}".format(f=sub))
print(" Downloading...")
save_subtitles(video, [sub], single=True)
else:
print(" ERROR: No subtitles found online.")
示例15: import_subs
def import_subs(filename):
if not core.GETSUBS:
return
try:
subliminal.cache_region.configure('dogpile.cache.memory')
except:
pass
languages = set()
for item in core.SLANGUAGES:
try:
languages.add(Language(item))
except:
pass
if not languages:
return
logger.debug("Attempting to download subtitles for %s" %(filename), 'SUBTITLES')
try:
# subliminal.logger = subliminal.logging.getLogger('subliminal')
# subliminal.logger.setLevel(subliminal.logging.DEBUG)
# ch = subliminal.logging.StreamHandler()
# ch.setLevel(subliminal.logging.DEBUG)
# formatter = subliminal.logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# ch.setFormatter(formatter)
# subliminal.logger.addHandler(ch)
video = subliminal.scan_video(filename, subtitles=True, embedded_subtitles=True)
subtitles = subliminal.download_best_subtitles([video], languages, hearing_impaired=False)
saved_subtitles = subliminal.save_subtitles(video, subtitles[video])
logger.debug("Saved subtitles:%s" %(saved_subtitles), 'SUBTITLES')
except Exception as e:
logger.error("Failed to download subtitles for %s due to: %s" %(filename, e), 'SUBTITLES')