1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import io
import os
import logging
from urllib.parse import unquote
from zipfile import ZipFile, is_zipfile
from rarfile import RarFile, is_rarfile
from guessit import guessit
from subliminal_patch.http import RetryingCFSession
import chardet
from bs4 import NavigableString, UnicodeDammit
from subzero.language import Language
from subliminal_patch.providers import Provider
from subliminal_patch.providers.mixins import ProviderSubtitleArchiveMixin
from subliminal_patch.subtitle import Subtitle, guess_matches
from subliminal_patch.score import get_scores, framerate_equal
from subliminal.providers import ParserBeautifulSoup
from subliminal.subtitle import sanitize, SUBTITLE_EXTENSIONS
from subliminal.video import Episode, Movie
from .utils import FIRST_THOUSAND_OR_SO_USER_AGENTS as AGENT_LIST
logger = logging.getLogger(__name__)
class SoustitreseuSubtitle(Subtitle):
"""Sous-Titres.eu Subtitle."""
provider_name = 'soustitreseu'
def __init__(self, language, video, name, data, content, is_perfect_match):
self.language = language
self.srt_filename = name
self.release_info = name
self.page_link = None
self.download_link = None
self.data = data
self.video = video
self.matches = None
self.content = content
self.hearing_impaired = None
self.is_perfect_match = is_perfect_match
self._guessed_encoding = None
@property
def id(self):
return self.srt_filename
def get_matches(self, video):
matches = set()
if self.is_perfect_match:
if isinstance(video, Episode):
matches.add('series')
else:
matches.add('title')
# guess additional info from data
matches |= guess_matches(video, self.data)
self.matches = matches
self.data = None # removing this make the subtitles object unpickable
return matches
def guess_encoding(self):
# override default subtitle guess_encoding method to not include language-specific encodings guessing
# chardet encoding detection seem to yield better results
"""Guess encoding using chardet.
:return: the guessed encoding.
:rtype: str
"""
if self._guessed_encoding:
return self._guessed_encoding
logger.info('Guessing encoding for language %s', self.language)
# guess/detect encoding using chardet
encoding = chardet.detect(self.content)['encoding']
logger.info('Chardet found encoding %s', encoding)
if not encoding:
# fallback on bs4
logger.info('Falling back to bs4 detection')
a = UnicodeDammit(self.content)
logger.info("bs4 detected encoding: %s", a.original_encoding)
if a.original_encoding:
self._guessed_encoding = a.original_encoding
return a.original_encoding
raise ValueError(u"Couldn't guess the proper encoding for %s", self)
self._guessed_encoding = encoding
return encoding
class SoustitreseuProvider(Provider, ProviderSubtitleArchiveMixin):
"""Sous-Titres.eu Provider."""
subtitle_class = SoustitreseuSubtitle
languages = {Language(l) for l in ['fra', 'eng']}
video_types = (Episode, Movie)
server_url = 'https://www.sous-titres.eu/'
search_url = server_url + 'search.html'
def __init__(self):
self.session = None
self.is_perfect_match = False
def initialize(self):
self.session = RetryingCFSession()
self.session.headers['Referer'] = self.server_url
def terminate(self):
self.session.close()
def query_series(self, video, title):
subtitles = []
r = self.session.get(self.search_url, params={'q': title}, timeout=30)
r.raise_for_status()
soup = ParserBeautifulSoup(r.content.decode('utf-8', 'ignore'), ['html.parser'])
# loop over series name
self.is_perfect_match = False
series_url = []
series = soup.select('.serie > h3 > a')
for item in series:
# title
if title in item.text:
series_url.append(item.attrs['href'])
self.is_perfect_match = True
series_subs_archives_url = []
for series_page in series_url:
page_link = self.server_url + series_page
r = self.session.get(page_link, timeout=30)
r.raise_for_status()
soup = ParserBeautifulSoup(r.content.decode('utf-8', 'ignore'), ['html.parser'])
series_subs_archives = soup.select('a.subList')
for item in series_subs_archives:
matching_archive = False
subtitles_archive_name = unquote(item.attrs['href'].split('/')[-1:][0][:-4])
guessed_subs = guessit(subtitles_archive_name, {'type': 'episode'})
try:
season, episode = item.select_one('.episodenum').text.split('×')
guessed_subs.update({'season': int(season), 'episode': int(episode)})
except ValueError:
season = item.select_one('.episodenum').text[1:]
episode = None
guessed_subs.update({'season': int(season)})
if guessed_subs['season'] == video.season:
if 'episode' in guessed_subs:
if guessed_subs['episode'] == video.episode:
matching_archive = True
else:
matching_archive = True
if matching_archive:
download_link = self.server_url + 'series/' + item.attrs['href']
res = self.session.get(download_link, timeout=30)
res.raise_for_status()
archive = self._get_archive(res.content)
# extract the subtitle
if archive:
subtitles_from_archive = self._get_subtitle_from_archive(archive, video)
for subtitle in subtitles_from_archive:
subtitle.page_link = page_link
subtitle.download_link = download_link
subtitles.append(subtitle)
return subtitles
def query_movies(self, video, title):
subtitles = []
r = self.session.get(self.search_url, params={'q': title}, timeout=30)
r.raise_for_status()
soup = ParserBeautifulSoup(r.content.decode('utf-8', 'ignore'), ['html.parser'])
# loop over movies name
movies_url = []
self.is_perfect_match = False
movies = soup.select('.film > h3 > a')
for item in movies:
# title
if title.lower() in item.text.lower():
movies_url.append(item.attrs['href'])
self.is_perfect_match = True
series_subs_archives_url = []
for movies_page in movies_url:
page_link = self.server_url + movies_page
r = self.session.get(page_link, timeout=30)
r.raise_for_status()
soup = ParserBeautifulSoup(r.content.decode('utf-8', 'ignore'), ['html.parser'])
movies_subs_archives = soup.select('a.subList')
for item in movies_subs_archives:
download_link = self.server_url + 'films/' + item.attrs['href']
res = self.session.get(download_link, timeout=30)
res.raise_for_status()
archive = self._get_archive(res.content)
# extract the subtitle
if archive:
subtitles_from_archive = self._get_subtitle_from_archive(archive, video)
for subtitle in subtitles_from_archive:
subtitle.page_link = page_link
subtitle.download_link = download_link
subtitles.append(subtitle)
return subtitles
def list_subtitles(self, video, languages):
subtitles = []
# query for subtitles
if isinstance(video, Episode):
subtitles += [s for s in self.query_series(video, video.series) if s.language in languages]
else:
subtitles += [s for s in self.query_movies(video, video.title) if s.language in languages]
return subtitles
def download_subtitle(self, subtitle):
return subtitle
def _get_archive(self, content):
# open the archive
archive_stream = io.BytesIO(content)
if is_rarfile(archive_stream):
logger.debug('Sous-Titres.eu: Identified rar archive')
archive = RarFile(archive_stream)
elif is_zipfile(archive_stream):
logger.debug('Sous-Titres.eu: Identified zip archive')
archive = ZipFile(archive_stream)
else:
logger.error('Sous-Titres.eu: Unsupported compressed format')
return None
return archive
def _get_subtitle_from_archive(self, archive, video):
subtitles = []
# some files have a non subtitle with .txt extension
_tmp = list(SUBTITLE_EXTENSIONS)
_tmp.remove('.txt')
_subtitle_extensions = tuple(_tmp)
_scores = get_scores(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
# get subtitles language
if '.en.' in name.lower():
language = Language.fromopensubtitles('eng')
else:
language = Language.fromopensubtitles('fre')
release = name[:-4].lower().rstrip('tag').rstrip('en').rstrip('fr')
_guess = guessit(release)
if isinstance(video, Episode):
if video.episode != _guess['episode'] or video.season != _guess['season']:
continue
matches = set()
matches |= guess_matches(video, _guess)
_score = sum((_scores.get(match, 0) for match in matches))
content = archive.read(name)
subtitles.append(SoustitreseuSubtitle(language, video, name, _guess, content, self.is_perfect_match))
return subtitles
|