bazarr/bazarr/list_subtitles.py

401 lines
20 KiB
Python
Raw Normal View History

# coding=utf-8
2019-09-13 19:12:26 +00:00
from __future__ import absolute_import
import gc
import os
import babelfish
import logging
import ast
import langdetect
import subliminal
import subliminal_patch
2019-08-20 10:23:25 +00:00
import operator
from subliminal import core
2018-11-29 13:53:13 +00:00
from subliminal_patch import search_external_subtitles
2019-11-04 02:48:21 +00:00
from subzero.language import Language
from bs4 import UnicodeDammit
2019-11-07 00:35:30 +00:00
import six
from binaryornot.check import is_binary
from get_args import args
2019-10-23 10:59:04 +00:00
from database import database
from get_languages import alpha2_from_alpha3, get_language_set
2018-12-15 00:36:28 +00:00
from config import settings
from helper import path_replace, path_replace_movie, path_replace_reverse, \
path_replace_reverse_movie, get_subtitle_destination_folder
from queueconfig import notifications
from embedded_subs_reader import embedded_subs_reader
2019-09-13 19:12:26 +00:00
import six
2018-12-31 17:49:11 +00:00
gc.enable()
2019-10-11 04:00:23 +00:00
def store_subtitles(original_path, reversed_path):
logging.debug('BAZARR started subtitles indexing for this file: ' + reversed_path)
actual_subtitles = []
2019-10-11 04:00:23 +00:00
if os.path.exists(reversed_path):
if settings.general.getboolean('use_embedded_subs'):
logging.debug("BAZARR is trying to index embedded subtitles.")
try:
2019-10-11 04:00:23 +00:00
subtitle_languages = embedded_subs_reader.list_languages(reversed_path)
for subtitle_language, subtitle_forced, subtitle_codec in subtitle_languages:
try:
if settings.general.getboolean("ignore_pgs_subs") and subtitle_codec == "hdmv_pgs_subtitle":
logging.debug("BAZARR skipping pgs sub for language: " + str(alpha2_from_alpha3(subtitle_language)))
continue
if alpha2_from_alpha3(subtitle_language) is not None:
lang = str(alpha2_from_alpha3(subtitle_language))
2019-04-27 12:13:47 +00:00
if subtitle_forced:
lang = lang + ":forced"
logging.debug("BAZARR embedded subtitles detected: " + lang)
actual_subtitles.append([lang, None])
except:
logging.debug("BAZARR unable to index this unrecognized language: " + subtitle_language)
pass
except Exception as e:
2019-06-11 18:45:48 +00:00
logging.exception(
2019-10-11 04:00:23 +00:00
"BAZARR error when trying to analyze this %s file: %s" % (os.path.splitext(reversed_path)[1], reversed_path))
pass
2019-10-11 04:00:23 +00:00
brazilian_portuguese = [".pt-br", ".pob", "pb"]
brazilian_portuguese_forced = [".pt-br.forced", ".pob.forced", "pb.forced"]
try:
dest_folder = get_subtitle_destination_folder()
subliminal_patch.core.CUSTOM_PATHS = [dest_folder] if dest_folder else []
2019-10-11 04:00:23 +00:00
subtitles = search_external_subtitles(reversed_path, languages=get_language_set(),
only_one=settings.general.getboolean('single_language'))
2019-11-07 00:35:30 +00:00
subtitles = guess_external_subtitles(get_subtitle_destination_folder() or os.path.dirname(reversed_path), subtitles)
except Exception as e:
logging.exception("BAZARR unable to index external subtitles.")
pass
else:
2019-09-13 19:12:26 +00:00
for subtitle, language in six.iteritems(subtitles):
2019-10-11 04:00:23 +00:00
subtitle_path = get_external_subtitles_path(reversed_path, subtitle)
2018-12-15 00:36:28 +00:00
if str(os.path.splitext(subtitle)[0]).lower().endswith(tuple(brazilian_portuguese)):
logging.debug("BAZARR external subtitles detected: " + "pb")
actual_subtitles.append(
2019-10-29 02:09:24 +00:00
[str("pb"), path_replace_reverse(subtitle_path)])
elif str(os.path.splitext(subtitle)[0]).lower().endswith(tuple(brazilian_portuguese_forced)):
logging.debug("BAZARR external subtitles detected: " + "pb:forced")
actual_subtitles.append(
2019-10-29 02:09:24 +00:00
[str("pb:forced"), path_replace_reverse(subtitle_path)])
2019-10-29 10:56:20 +00:00
elif not language:
continue
elif str(language) != 'und':
logging.debug("BAZARR external subtitles detected: " + str(language))
actual_subtitles.append(
2019-10-29 02:09:24 +00:00
[str(language), path_replace_reverse(subtitle_path)])
2019-10-27 01:16:59 +00:00
database.execute("UPDATE table_episodes SET subtitles=? WHERE path=?",
(str(actual_subtitles), original_path))
matching_episodes = database.execute("SELECT sonarrEpisodeId FROM table_episodes WHERE path=?",
(original_path,))
for episode in matching_episodes:
if episode:
logging.debug("BAZARR storing those languages to DB: " + str(actual_subtitles))
list_missing_subtitles(epno=episode['sonarrEpisodeId'])
else:
logging.debug("BAZARR haven't been able to update existing subtitles to DB : " + str(actual_subtitles))
2018-12-31 17:49:11 +00:00
else:
logging.debug("BAZARR this file doesn't seems to exist or isn't accessible.")
2019-01-15 16:25:13 +00:00
2019-10-11 04:00:23 +00:00
logging.debug('BAZARR ended subtitles indexing for this file: ' + reversed_path)
2019-10-19 20:37:40 +00:00
return actual_subtitles
2019-10-11 04:00:23 +00:00
def store_subtitles_movie(original_path, reversed_path):
logging.debug('BAZARR started subtitles indexing for this file: ' + reversed_path)
actual_subtitles = []
2019-10-11 04:00:23 +00:00
if os.path.exists(reversed_path):
if settings.general.getboolean('use_embedded_subs'):
logging.debug("BAZARR is trying to index embedded subtitles.")
try:
2019-10-11 04:00:23 +00:00
subtitle_languages = embedded_subs_reader.list_languages(reversed_path)
for subtitle_language, subtitle_forced, subtitle_codec in subtitle_languages:
try:
if settings.general.getboolean("ignore_pgs_subs") and subtitle_codec == "hdmv_pgs_subtitle":
logging.debug("BAZARR skipping pgs sub for language: " + str(alpha2_from_alpha3(subtitle_language)))
continue
if alpha2_from_alpha3(subtitle_language) is not None:
lang = str(alpha2_from_alpha3(subtitle_language))
2019-04-27 12:13:47 +00:00
if subtitle_forced:
lang = lang + ':forced'
logging.debug("BAZARR embedded subtitles detected: " + lang)
actual_subtitles.append([lang, None])
except:
logging.debug("BAZARR unable to index this unrecognized language: " + subtitle_language)
pass
except Exception as e:
2019-06-11 18:45:48 +00:00
logging.exception(
2019-10-11 04:00:23 +00:00
"BAZARR error when trying to analyze this %s file: %s" % (os.path.splitext(reversed_path)[1], reversed_path))
pass
brazilian_portuguese = [".pt-br", ".pob", "pb"]
brazilian_portuguese_forced = [".pt-br.forced", ".pob.forced", "pb.forced"]
try:
2019-11-04 02:48:21 +00:00
dest_folder = get_subtitle_destination_folder() or ''
subliminal_patch.core.CUSTOM_PATHS = [dest_folder] if dest_folder else []
subtitles = search_external_subtitles(reversed_path, languages=get_language_set())
subtitles = guess_external_subtitles(get_subtitle_destination_folder() or os.path.dirname(reversed_path), subtitles)
except Exception as e:
logging.exception("BAZARR unable to index external subtitles.")
pass
else:
2019-09-13 19:12:26 +00:00
for subtitle, language in six.iteritems(subtitles):
2019-10-29 02:09:24 +00:00
subtitle_path = get_external_subtitles_path(reversed_path, subtitle)
2019-10-11 04:00:23 +00:00
if str(os.path.splitext(subtitle)[0]).lower().endswith(tuple(brazilian_portuguese)):
logging.debug("BAZARR external subtitles detected: " + "pb")
2019-10-29 02:09:24 +00:00
actual_subtitles.append([str("pb"), path_replace_reverse_movie(subtitle_path)])
2019-10-11 04:00:23 +00:00
elif str(os.path.splitext(subtitle)[0]).lower().endswith(tuple(brazilian_portuguese_forced)):
logging.debug("BAZARR external subtitles detected: " + "pb:forced")
2019-10-29 02:09:24 +00:00
actual_subtitles.append([str("pb:forced"), path_replace_reverse_movie(subtitle_path)])
2019-10-29 10:56:20 +00:00
elif not language:
continue
elif str(language) != 'und':
logging.debug("BAZARR external subtitles detected: " + str(language))
2019-10-29 02:09:24 +00:00
actual_subtitles.append([str(language), path_replace_reverse_movie(subtitle_path)])
2019-01-15 16:25:13 +00:00
2019-10-24 02:05:55 +00:00
database.execute("UPDATE table_movies SET subtitles=? WHERE path=?",
(str(actual_subtitles), original_path))
matching_movies = database.execute("SELECT radarrId FROM table_movies WHERE path=?", (original_path,))
for movie in matching_movies:
if movie:
logging.debug("BAZARR storing those languages to DB: " + str(actual_subtitles))
list_missing_subtitles_movies(no=movie['radarrId'])
else:
logging.debug("BAZARR haven't been able to update existing subtitles to DB : " + str(actual_subtitles))
2018-12-31 17:49:11 +00:00
else:
logging.debug("BAZARR this file doesn't seems to exist or isn't accessible.")
2019-01-15 16:25:13 +00:00
2019-10-11 04:00:23 +00:00
logging.debug('BAZARR ended subtitles indexing for this file: ' + reversed_path)
2019-10-19 20:37:40 +00:00
return actual_subtitles
2019-10-19 20:37:40 +00:00
def list_missing_subtitles(no=None, epno=None):
2019-08-20 17:07:16 +00:00
if no is not None:
2019-10-26 18:52:22 +00:00
episodes_subtitles_clause = " WHERE table_episodes.sonarrSeriesId=" + str(no)
2019-10-19 20:37:40 +00:00
elif epno is not None:
2019-10-26 18:52:22 +00:00
episodes_subtitles_clause = " WHERE table_episodes.sonarrEpisodeId=" + str(epno)
2019-10-23 10:59:04 +00:00
else:
episodes_subtitles_clause = ""
episodes_subtitles = database.execute("SELECT table_shows.sonarrSeriesId, table_episodes.sonarrEpisodeId, "
"table_episodes.subtitles, table_shows.languages, table_shows.forced "
"FROM table_episodes LEFT JOIN table_shows "
"on table_episodes.sonarrSeriesId = table_shows.sonarrSeriesId" +
episodes_subtitles_clause)
2019-12-24 14:00:42 +00:00
if isinstance(episodes_subtitles, six.string_types):
logging.debug("BAZARR list missing subtitles query to DB returned this instead of rows: " + episodes_subtitles)
return
2019-08-20 10:23:25 +00:00
missing_subtitles_global = []
use_embedded_subs = settings.general.getboolean('use_embedded_subs')
for episode_subtitles in episodes_subtitles:
actual_subtitles_temp = []
2019-04-29 03:01:05 +00:00
desired_subtitles_temp = []
actual_subtitles = []
desired_subtitles = []
missing_subtitles = []
2019-10-26 18:52:22 +00:00
if episode_subtitles['subtitles'] is not None:
2018-12-15 00:36:28 +00:00
if use_embedded_subs:
2019-10-26 18:52:22 +00:00
actual_subtitles = ast.literal_eval(episode_subtitles['subtitles'])
else:
2019-10-26 18:52:22 +00:00
actual_subtitles_temp = ast.literal_eval(episode_subtitles['subtitles'])
for subtitle in actual_subtitles_temp:
2018-12-15 00:36:28 +00:00
if subtitle[1] is not None:
actual_subtitles.append(subtitle)
2019-10-26 18:52:22 +00:00
if episode_subtitles['languages'] is not None:
desired_subtitles = ast.literal_eval(episode_subtitles['languages'])
if episode_subtitles['forced'] == "True" and desired_subtitles is not None:
2019-04-02 02:34:03 +00:00
for i, desired_subtitle in enumerate(desired_subtitles):
desired_subtitles[i] = desired_subtitle + ":forced"
2019-10-26 18:52:22 +00:00
elif episode_subtitles['forced'] == "Both" and desired_subtitles is not None:
2019-04-29 03:01:05 +00:00
for desired_subtitle in desired_subtitles:
desired_subtitles_temp.append(desired_subtitle)
desired_subtitles_temp.append(desired_subtitle + ":forced")
desired_subtitles = desired_subtitles_temp
actual_subtitles_list = []
2018-12-15 00:36:28 +00:00
if desired_subtitles is None:
2019-10-26 18:52:22 +00:00
missing_subtitles_global.append(tuple(['[]', episode_subtitles['sonarrEpisodeId']]))
else:
for item in actual_subtitles:
if item[0] == "pt-BR":
actual_subtitles_list.append("pb")
2019-04-29 03:01:05 +00:00
elif item[0] == "pt-BR:forced":
actual_subtitles_list.append("pb:forced")
else:
actual_subtitles_list.append(item[0])
missing_subtitles = list(set(desired_subtitles) - set(actual_subtitles_list))
2019-10-26 18:52:22 +00:00
missing_subtitles_global.append(tuple([str(missing_subtitles), episode_subtitles['sonarrEpisodeId']]))
2019-08-20 10:23:25 +00:00
for missing_subtitles_item in missing_subtitles_global:
2019-10-27 01:16:59 +00:00
database.execute("UPDATE table_episodes SET missing_subtitles=? WHERE sonarrEpisodeId=?",
2019-10-23 10:59:04 +00:00
(missing_subtitles_item[0], missing_subtitles_item[1]))
2019-08-20 17:07:16 +00:00
def list_missing_subtitles_movies(no=None):
if no is not None:
2019-10-27 03:17:14 +00:00
movies_subtitles_clause = " WHERE radarrId=" + str(no)
2019-10-23 10:59:04 +00:00
else:
movies_subtitles_clause = ""
2019-08-20 14:18:01 +00:00
2019-10-23 10:59:04 +00:00
movies_subtitles = database.execute("SELECT radarrId, subtitles, languages, forced FROM table_movies" +
movies_subtitles_clause)
2019-12-24 14:00:42 +00:00
if isinstance(movies_subtitles, six.string_types):
logging.error("BAZARR list missing subtitles query to DB returned this instead of rows: " + movies_subtitles)
return
2019-01-15 16:25:13 +00:00
missing_subtitles_global = []
use_embedded_subs = settings.general.getboolean('use_embedded_subs')
for movie_subtitles in movies_subtitles:
actual_subtitles_temp = []
2019-04-29 03:01:05 +00:00
desired_subtitles_temp = []
actual_subtitles = []
desired_subtitles = []
missing_subtitles = []
2019-10-26 18:52:22 +00:00
if movie_subtitles['subtitles'] is not None:
2018-12-15 00:36:28 +00:00
if use_embedded_subs:
2019-10-26 18:52:22 +00:00
actual_subtitles = ast.literal_eval(movie_subtitles['subtitles'])
else:
2019-10-26 18:52:22 +00:00
actual_subtitles_temp = ast.literal_eval(movie_subtitles['subtitles'])
for subtitle in actual_subtitles_temp:
2018-12-15 00:36:28 +00:00
if subtitle[1] is not None:
actual_subtitles.append(subtitle)
2019-10-26 18:52:22 +00:00
if movie_subtitles['languages'] is not None:
desired_subtitles = ast.literal_eval(movie_subtitles['languages'])
if movie_subtitles['forced'] == "True" and desired_subtitles is not None:
2019-04-02 02:34:03 +00:00
for i, desired_subtitle in enumerate(desired_subtitles):
desired_subtitles[i] = desired_subtitle + ":forced"
2019-10-26 18:52:22 +00:00
elif movie_subtitles['forced'] == "Both" and desired_subtitles is not None:
2019-04-29 03:01:05 +00:00
for desired_subtitle in desired_subtitles:
desired_subtitles_temp.append(desired_subtitle)
desired_subtitles_temp.append(desired_subtitle + ":forced")
desired_subtitles = desired_subtitles_temp
actual_subtitles_list = []
2018-12-15 00:36:28 +00:00
if desired_subtitles is None:
2019-10-26 18:52:22 +00:00
missing_subtitles_global.append(tuple(['[]', movie_subtitles['radarrId']]))
else:
for item in actual_subtitles:
if item[0] == "pt-BR":
actual_subtitles_list.append("pb")
2019-04-29 03:01:05 +00:00
elif item[0] == "pt-BR:forced":
actual_subtitles_list.append("pb:forced")
else:
actual_subtitles_list.append(item[0])
missing_subtitles = list(set(desired_subtitles) - set(actual_subtitles_list))
2019-10-26 18:52:22 +00:00
missing_subtitles_global.append(tuple([str(missing_subtitles), movie_subtitles['radarrId']]))
2019-01-15 16:25:13 +00:00
2019-08-20 14:18:01 +00:00
for missing_subtitles_item in missing_subtitles_global:
2019-10-27 03:17:14 +00:00
database.execute("UPDATE table_movies SET missing_subtitles=? WHERE radarrId=?",
2019-10-23 10:59:04 +00:00
(missing_subtitles_item[0], missing_subtitles_item[1]))
def series_full_scan_subtitles():
2019-10-23 10:59:04 +00:00
episodes = database.execute("SELECT path FROM table_episodes")
count_episodes = len(episodes)
2019-06-11 18:45:48 +00:00
2019-04-10 20:05:33 +00:00
for i, episode in enumerate(episodes, 1):
2019-04-19 19:49:45 +00:00
notifications.write(msg='Updating all episodes subtitles from disk...',
2019-04-23 01:08:26 +00:00
queue='list_subtitles_series', item=i, length=count_episodes)
store_subtitles(episode['path'], path_replace(episode['path']))
2019-01-15 16:25:13 +00:00
gc.collect()
def movies_full_scan_subtitles():
2019-10-23 10:59:04 +00:00
movies = database.execute("SELECT path FROM table_movies")
count_movies = len(movies)
2019-06-11 18:45:48 +00:00
2019-04-10 20:05:33 +00:00
for i, movie in enumerate(movies, 1):
2019-04-19 19:49:45 +00:00
notifications.write(msg='Updating all movies subtitles from disk...',
2019-04-23 01:08:26 +00:00
queue='list_subtitles_movies', item=i, length=count_movies)
store_subtitles_movie(movie['path'], path_replace_movie(movie['path']))
2019-01-15 16:25:13 +00:00
gc.collect()
def series_scan_subtitles(no):
2019-10-23 10:59:04 +00:00
episodes = database.execute("SELECT path FROM table_episodes WHERE sonarrSeriesId=?", (no,))
2019-01-15 16:25:13 +00:00
for episode in episodes:
store_subtitles(episode['path'], path_replace(episode['path']))
def movies_scan_subtitles(no):
2019-10-23 10:59:04 +00:00
movies = database.execute("SELECT path FROM table_movies WHERE radarrId=?", (no,))
2019-01-15 16:25:13 +00:00
for movie in movies:
store_subtitles_movie(movie['path'], path_replace_movie(movie['path']))
def get_external_subtitles_path(file, subtitle):
fld = os.path.dirname(file)
2019-06-11 18:45:48 +00:00
if settings.general.subfolder == "current":
path = os.path.join(fld, subtitle)
elif settings.general.subfolder == "absolute":
custom_fld = settings.general.subfolder_custom
if os.path.exists(os.path.join(fld, subtitle)):
path = os.path.join(fld, subtitle)
elif os.path.exists(os.path.join(custom_fld, subtitle)):
path = os.path.join(custom_fld, subtitle)
else:
path = None
elif settings.general.subfolder == "relative":
custom_fld = os.path.join(fld, settings.general.subfolder_custom)
if os.path.exists(os.path.join(fld, subtitle)):
path = os.path.join(fld, subtitle)
elif os.path.exists(os.path.join(custom_fld, subtitle)):
path = os.path.join(custom_fld, subtitle)
else:
path = None
else:
path = None
2019-06-11 18:45:48 +00:00
return path
2019-11-04 02:48:21 +00:00
def guess_external_subtitles(dest_folder, subtitles):
2019-11-07 00:35:30 +00:00
for subtitle, language in six.iteritems(subtitles):
2019-11-04 02:48:21 +00:00
if not language:
subtitle_path = os.path.join(dest_folder, subtitle)
if os.path.exists(subtitle_path) and os.path.splitext(subtitle_path)[1] in core.SUBTITLE_EXTENSIONS:
logging.debug("BAZARR falling back to file content analysis to detect language.")
if is_binary(subtitle_path):
logging.debug("BAZARR subtitles file doesn't seems to be text based. Skipping this file: " +
subtitle_path)
continue
2019-11-04 02:48:21 +00:00
detected_language = None
if six.PY3:
with open(subtitle_path, 'r', errors='ignore') as f:
text = f.read()
else:
with open(subtitle_path, 'r') as f:
text = f.read()
try:
encoding = UnicodeDammit(text)
if six.PY2:
text = text.decode(encoding.original_encoding)
detected_language = langdetect.detect(text)
except Exception as e:
logging.exception('BAZARR Error trying to detect language for this subtitles file: ' +
subtitle_path + ' You should try to delete this subtitles file manually and ask '
'Bazarr to download it again.')
else:
if detected_language:
logging.debug("BAZARR external subtitles detected and guessed this language: " + str(
detected_language))
try:
subtitles[subtitle] = Language.rebuild(Language.fromietf(detected_language))
except:
pass
2019-11-04 02:48:21 +00:00
return subtitles