You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
388 lines
13 KiB
388 lines
13 KiB
3 years ago
|
# -*- coding: utf-8 -*-
|
||
|
|
||
3 years ago
|
import functools
|
||
1 year ago
|
import hashlib
|
||
1 year ago
|
import logging
|
||
3 years ago
|
import os
|
||
2 years ago
|
import re
|
||
3 years ago
|
import shutil
|
||
|
import tempfile
|
||
2 years ago
|
from typing import List
|
||
3 years ago
|
|
||
|
from babelfish import language_converters
|
||
2 years ago
|
from fese import container
|
||
3 years ago
|
from fese import FFprobeSubtitleStream
|
||
|
from fese import FFprobeVideoContainer
|
||
2 years ago
|
from fese import tags
|
||
1 year ago
|
from fese.exceptions import ExtractionError
|
||
2 years ago
|
from fese.exceptions import InvalidSource
|
||
3 years ago
|
from subliminal_patch.core import Episode
|
||
|
from subliminal_patch.core import Movie
|
||
|
from subliminal_patch.providers import Provider
|
||
1 year ago
|
from subliminal_patch.providers.utils import blacklist_on
|
||
3 years ago
|
from subliminal_patch.subtitle import Subtitle
|
||
|
from subzero.language import Language
|
||
|
|
||
|
logger = logging.getLogger(__name__)
|
||
|
|
||
|
# Replace Babelfish's Language with Subzero's Language
|
||
2 years ago
|
tags.Language = Language
|
||
3 years ago
|
|
||
|
|
||
|
class EmbeddedSubtitle(Subtitle):
|
||
|
provider_name = "embeddedsubtitles"
|
||
|
hash_verifiable = False
|
||
1 year ago
|
hearing_impaired_verifiable = True
|
||
3 years ago
|
|
||
3 years ago
|
def __init__(self, stream, container, matches, media_type):
|
||
3 years ago
|
super().__init__(stream.language, stream.disposition.hearing_impaired)
|
||
3 years ago
|
if stream.disposition.forced:
|
||
|
self.language = Language.rebuild(stream.language, forced=True)
|
||
|
|
||
3 years ago
|
self.stream: FFprobeSubtitleStream = stream
|
||
|
self.container: FFprobeVideoContainer = container
|
||
3 years ago
|
self.forced = stream.disposition.forced
|
||
3 years ago
|
self.page_link = self.container.path
|
||
3 years ago
|
self.release_info = _get_pretty_release_name(stream, container)
|
||
3 years ago
|
self.media_type = media_type
|
||
|
|
||
|
self._matches: set = matches
|
||
3 years ago
|
|
||
|
def get_matches(self, video):
|
||
1 year ago
|
if self.language.hi:
|
||
|
self._matches.add("hearing_impaired")
|
||
|
|
||
3 years ago
|
self._matches.add("hash")
|
||
1 year ago
|
|
||
3 years ago
|
return self._matches
|
||
|
|
||
|
@property
|
||
|
def id(self):
|
||
|
return f"{self.container.path}_{self.stream.index}"
|
||
|
|
||
|
|
||
2 years ago
|
_ALLOWED_CODECS = ("ass", "subrip", "webvtt", "mov_text")
|
||
|
|
||
|
|
||
3 years ago
|
class EmbeddedSubtitlesProvider(Provider):
|
||
|
provider_name = "embeddedsubtitles"
|
||
|
|
||
|
languages = {Language("por", "BR"), Language("spa", "MX")} | {
|
||
|
Language.fromalpha2(l) for l in language_converters["alpha2"].codes
|
||
|
}
|
||
|
languages.update(set(Language.rebuild(lang, hi=True) for lang in languages))
|
||
3 years ago
|
languages.update(set(Language.rebuild(lang, forced=True) for lang in languages))
|
||
3 years ago
|
|
||
|
video_types = (Episode, Movie)
|
||
|
subtitle_class = EmbeddedSubtitle
|
||
3 years ago
|
_blacklist = set()
|
||
3 years ago
|
|
||
|
def __init__(
|
||
3 years ago
|
self,
|
||
2 years ago
|
included_codecs=None,
|
||
3 years ago
|
cache_dir=None,
|
||
|
ffprobe_path=None,
|
||
|
ffmpeg_path=None,
|
||
3 years ago
|
hi_fallback=False,
|
||
3 years ago
|
timeout=600,
|
||
9 months ago
|
unknown_as_fallback=False,
|
||
|
fallback_lang="en",
|
||
3 years ago
|
):
|
||
2 years ago
|
self._included_codecs = set(included_codecs or _ALLOWED_CODECS)
|
||
|
|
||
|
for codec in self._included_codecs:
|
||
|
if codec not in _ALLOWED_CODECS:
|
||
|
logger.warning("Unallowed codec: %s", codec)
|
||
|
|
||
3 years ago
|
self._cache_dir = os.path.join(
|
||
|
cache_dir or tempfile.gettempdir(), self.__class__.__name__.lower()
|
||
|
)
|
||
3 years ago
|
self._hi_fallback = hi_fallback
|
||
9 months ago
|
self._unknown_as_fallback = unknown_as_fallback
|
||
|
self._fallback_lang = fallback_lang
|
||
3 years ago
|
self._cached_paths = {}
|
||
2 years ago
|
self._timeout = int(timeout)
|
||
3 years ago
|
|
||
2 years ago
|
container.FFPROBE_PATH = ffprobe_path or container.FFPROBE_PATH
|
||
|
container.FFMPEG_PATH = ffmpeg_path or container.FFMPEG_PATH
|
||
3 years ago
|
|
||
|
if logger.getEffectiveLevel() == logging.DEBUG:
|
||
2 years ago
|
container.FF_LOG_LEVEL = "warning"
|
||
3 years ago
|
else:
|
||
|
# Default is True
|
||
2 years ago
|
container.FFMPEG_STATS = False
|
||
3 years ago
|
|
||
9 months ago
|
tags.LANGUAGE_FALLBACK = self._fallback_lang if self._unknown_as_fallback and self._fallback_lang else None
|
||
2 years ago
|
logger.debug("Language fallback set: %s", tags.LANGUAGE_FALLBACK)
|
||
|
|
||
3 years ago
|
def initialize(self):
|
||
|
os.makedirs(self._cache_dir, exist_ok=True)
|
||
|
|
||
|
def terminate(self):
|
||
|
# Remove leftovers
|
||
|
shutil.rmtree(self._cache_dir, ignore_errors=True)
|
||
|
|
||
3 years ago
|
def query(self, path: str, languages, media_type):
|
||
3 years ago
|
video = _get_memoized_video_container(path)
|
||
3 years ago
|
|
||
|
try:
|
||
2 years ago
|
streams = list(_filter_subtitles(video.get_subtitles()))
|
||
2 years ago
|
except InvalidSource as error:
|
||
3 years ago
|
logger.error("Error trying to get subtitles for %s: %s", video, error)
|
||
1 year ago
|
|
||
3 years ago
|
self._blacklist.add(path)
|
||
3 years ago
|
streams = []
|
||
|
|
||
1 year ago
|
_rebuild_langs(streams)
|
||
|
|
||
2 years ago
|
streams = _discard_possible_incomplete_subtitles(streams)
|
||
3 years ago
|
|
||
3 years ago
|
if not streams:
|
||
|
logger.debug("No subtitles found for container: %s", video)
|
||
|
|
||
1 year ago
|
if self._hi_fallback:
|
||
|
_check_hi_fallback(streams, languages)
|
||
|
|
||
3 years ago
|
only_forced = all(lang.forced for lang in languages)
|
||
|
also_forced = any(lang.forced for lang in languages)
|
||
|
|
||
3 years ago
|
allowed_streams = []
|
||
3 years ago
|
|
||
|
for stream in streams:
|
||
2 years ago
|
if stream.codec_name not in self._included_codecs:
|
||
1 year ago
|
logger.debug("Ignoring codec %s [%s]", stream, self._included_codecs)
|
||
3 years ago
|
continue
|
||
|
|
||
|
if stream.language not in languages:
|
||
1 year ago
|
logger.debug("%r not in %r", stream.language, languages)
|
||
3 years ago
|
continue
|
||
|
|
||
|
disposition = stream.disposition
|
||
3 years ago
|
|
||
|
if only_forced and not disposition.forced:
|
||
|
continue
|
||
|
|
||
|
if (
|
||
|
disposition.generic
|
||
|
or disposition.hearing_impaired
|
||
|
or (disposition.forced and also_forced)
|
||
|
):
|
||
3 years ago
|
logger.debug("Appending subtitle: %s", stream)
|
||
3 years ago
|
allowed_streams.append(stream)
|
||
3 years ago
|
else:
|
||
|
logger.debug("Ignoring unwanted subtitle: %s", stream)
|
||
|
|
||
3 years ago
|
logger.debug("Cache info: %s", _get_memoized_video_container.cache_info())
|
||
|
|
||
3 years ago
|
return [
|
||
|
EmbeddedSubtitle(stream, video, {"hash"}, media_type)
|
||
|
for stream in allowed_streams
|
||
|
]
|
||
3 years ago
|
|
||
|
def list_subtitles(self, video, languages):
|
||
3 years ago
|
if not self._is_path_valid(video.original_path):
|
||
|
logger.debug("Ignoring video: %s", video)
|
||
3 years ago
|
return []
|
||
|
|
||
3 years ago
|
return self.query(
|
||
|
video.original_path,
|
||
|
languages,
|
||
|
"series" if isinstance(video, Episode) else "movie",
|
||
|
)
|
||
3 years ago
|
|
||
1 year ago
|
@blacklist_on(ExtractionError)
|
||
2 years ago
|
def download_subtitle(self, subtitle: EmbeddedSubtitle):
|
||
10 months ago
|
try:
|
||
|
path = self._get_subtitle_path(subtitle)
|
||
|
except KeyError: # TODO: add MustGetBlacklisted support
|
||
|
logger.error("Couldn't get subtitle path")
|
||
|
return None
|
||
2 years ago
|
|
||
1 year ago
|
modifiers = _type_modifiers.get(subtitle.stream.codec_name) or set()
|
||
|
logger.debug("Found modifiers for %s type: %s", subtitle.stream, modifiers)
|
||
2 years ago
|
|
||
1 year ago
|
for mod in modifiers:
|
||
|
logger.debug("Running %s modifier for %s", mod, path)
|
||
|
try:
|
||
2 years ago
|
mod(path, path)
|
||
1 year ago
|
except Exception as error:
|
||
|
logger.debug("'%s' raised running modifier", error)
|
||
2 years ago
|
|
||
3 years ago
|
with open(path, "rb") as sub:
|
||
1 year ago
|
subtitle.content = sub.read()
|
||
3 years ago
|
|
||
|
def _get_subtitle_path(self, subtitle: EmbeddedSubtitle):
|
||
|
container = subtitle.container
|
||
|
|
||
|
# Check if the container is not already in the instance
|
||
|
if container.path not in self._cached_paths:
|
||
|
# Extract all subittle streams to avoid reading the entire
|
||
|
# container over and over
|
||
2 years ago
|
subs = list(_filter_subtitles(container.get_subtitles()))
|
||
|
|
||
2 years ago
|
extracted = container.copy_subtitles(
|
||
2 years ago
|
subs,
|
||
2 years ago
|
self._cache_dir,
|
||
|
timeout=self._timeout,
|
||
|
fallback_to_convert=True,
|
||
1 year ago
|
basename_callback=_basename_callback,
|
||
3 years ago
|
)
|
||
3 years ago
|
# Add the extracted paths to the containter path key
|
||
|
self._cached_paths[container.path] = extracted
|
||
|
|
||
|
cached_path = self._cached_paths[container.path]
|
||
|
# Get the subtitle file by index
|
||
2 years ago
|
return cached_path[subtitle.stream.index]
|
||
3 years ago
|
|
||
3 years ago
|
def _is_path_valid(self, path):
|
||
|
if path in self._blacklist:
|
||
|
logger.debug("Blacklisted path: %s", path)
|
||
|
return False
|
||
|
|
||
|
if not os.path.isfile(path):
|
||
|
logger.debug("Inexistent file: %s", path)
|
||
|
return False
|
||
|
|
||
|
return True
|
||
|
|
||
3 years ago
|
|
||
3 years ago
|
class _MemoizedFFprobeVideoContainer(FFprobeVideoContainer):
|
||
3 years ago
|
# 128 is the default value for maxsize since Python 3.8. We ste it here for previous versions.
|
||
|
@functools.lru_cache(maxsize=128)
|
||
3 years ago
|
def get_subtitles(self, *args, **kwargs):
|
||
|
return super().get_subtitles(*args, **kwargs)
|
||
|
|
||
|
|
||
|
@functools.lru_cache(maxsize=8096)
|
||
|
def _get_memoized_video_container(path: str):
|
||
|
return _MemoizedFFprobeVideoContainer(path)
|
||
|
|
||
|
|
||
2 years ago
|
def _filter_subtitles(subtitles: List[FFprobeSubtitleStream]):
|
||
|
for subtitle in subtitles:
|
||
|
if subtitle.codec_name not in _ALLOWED_CODECS:
|
||
|
logger.debug("Unallowed codec: %s", subtitle)
|
||
|
continue
|
||
|
|
||
|
if subtitle.tags.language_fallback is True and any(
|
||
|
(subtitle.language == sub.language) and (subtitle.index != sub.index)
|
||
|
for sub in subtitles
|
||
|
):
|
||
|
logger.debug("Not using language fallback. Language already found")
|
||
|
continue
|
||
2 years ago
|
|
||
2 years ago
|
yield subtitle
|
||
3 years ago
|
|
||
|
|
||
|
def _check_hi_fallback(streams, languages):
|
||
|
for language in languages:
|
||
1 year ago
|
logger.debug("Checking HI fallback for '%r' language", language)
|
||
3 years ago
|
|
||
1 year ago
|
streams_ = [
|
||
|
stream for stream in streams if stream.language.alpha3 == language.alpha3
|
||
|
]
|
||
3 years ago
|
if len(streams_) == 1 and streams_[0].disposition.hearing_impaired:
|
||
1 year ago
|
stream_ = streams_[0]
|
||
3 years ago
|
logger.debug(
|
||
|
"HI fallback: updating %s HI to False (only subtitle found is HI)",
|
||
1 year ago
|
stream_,
|
||
3 years ago
|
)
|
||
1 year ago
|
stream_.disposition.hearing_impaired = False
|
||
|
stream_.disposition.generic = True
|
||
|
stream_.language.hi = False
|
||
3 years ago
|
|
||
|
elif all(stream.disposition.hearing_impaired for stream in streams_):
|
||
|
for stream in streams_:
|
||
|
logger.debug(
|
||
|
"HI fallback: updating %s HI to False (all subtitles are HI)",
|
||
|
stream,
|
||
|
)
|
||
3 years ago
|
stream.disposition.hearing_impaired = False
|
||
3 years ago
|
stream.disposition.generic = True
|
||
1 year ago
|
stream.language.hi = False
|
||
3 years ago
|
|
||
1 year ago
|
elif any(stream.disposition.hearing_impaired for stream in streams_):
|
||
|
logger.debug(
|
||
|
"HI fallback not needed: %r (There's already one non-hi stream)",
|
||
|
streams_,
|
||
|
)
|
||
3 years ago
|
else:
|
||
1 year ago
|
logger.debug("Unknown use-case: %r. Not doing anything.", streams_)
|
||
|
|
||
|
|
||
|
def _rebuild_langs(streams):
|
||
|
for stream in streams:
|
||
|
kwargs = stream.disposition.language_kwargs()
|
||
|
stream.language = Language.rebuild(stream.language, **kwargs)
|
||
|
|
||
|
logger.debug("Rebuild language: %r", stream.language)
|
||
3 years ago
|
|
||
|
|
||
3 years ago
|
def _discard_possible_incomplete_subtitles(streams):
|
||
2 years ago
|
"""Check frame properties from subtitle streams in order to find
|
||
3 years ago
|
supposedly incomplete subtitles"""
|
||
|
try:
|
||
2 years ago
|
max_frames = max(stream.tags.frames for stream in streams)
|
||
3 years ago
|
except ValueError:
|
||
|
return []
|
||
|
|
||
|
# Blatantly assume there's nothing to discard as some ffprobe streams don't
|
||
|
# have number_of_frames tags
|
||
|
if not max_frames:
|
||
1 year ago
|
logger.debug("No max frames. Assuming good subtitles.")
|
||
3 years ago
|
return streams
|
||
|
|
||
|
logger.debug("Checking possible incomplete subtitles (max frames: %d)", max_frames)
|
||
|
|
||
|
valid_streams = []
|
||
|
|
||
|
for stream in streams:
|
||
|
# 500 < 1200
|
||
1 year ago
|
if not stream.language.forced and stream.tags.frames < max_frames // 3:
|
||
3 years ago
|
logger.debug(
|
||
|
"Possible bad subtitle found: %s (%s frames - %s frames)",
|
||
|
stream,
|
||
2 years ago
|
stream.tags.frames,
|
||
3 years ago
|
max_frames,
|
||
|
)
|
||
|
continue
|
||
|
|
||
|
valid_streams.append(stream)
|
||
|
|
||
|
return valid_streams
|
||
|
|
||
|
|
||
3 years ago
|
def _get_pretty_release_name(stream, container):
|
||
|
bname = os.path.basename(container.path)
|
||
|
return f"{os.path.splitext(bname)[0]}.{stream.suffix}"
|
||
2 years ago
|
|
||
|
|
||
1 year ago
|
def _basename_callback(path: str):
|
||
|
path, ext = os.path.splitext(path)
|
||
|
return hashlib.md5(path.encode()).hexdigest() + ext
|
||
|
|
||
|
|
||
2 years ago
|
# TODO: improve this
|
||
|
_SIGNS_LINE_RE = re.compile(r",([\w|_]{,15}(sign|fx|karaoke))", flags=re.IGNORECASE)
|
||
|
|
||
|
|
||
|
def _clean_ass_subtitles(path, output_path):
|
||
|
"""An attempt to ignore extraneous lines from ASS anime subtitles. Experimental."""
|
||
|
|
||
|
clean_lines = []
|
||
|
|
||
1 year ago
|
with open(path, "r", encoding="utf-8", errors="ignore") as f:
|
||
2 years ago
|
lines = f.readlines()
|
||
|
for line in lines:
|
||
|
if _SIGNS_LINE_RE.search(line) is None:
|
||
|
clean_lines.append(line)
|
||
|
|
||
|
logger.debug("Cleaned lines: %d", abs(len(lines) - len(clean_lines)))
|
||
|
|
||
|
with open(output_path, "w") as f:
|
||
|
f.writelines(clean_lines)
|
||
|
logger.debug("Lines written to output path: %s", output_path)
|
||
|
|
||
|
|
||
|
_type_modifiers = {"ass": {_clean_ass_subtitles}}
|