-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Subliminal.py
executable file
·2919 lines (2507 loc) · 100 KB
/
Subliminal.py
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Subliminal post-processing script for NZBGet and SABnzbd
#
# Copyright (C) 2015-2019 Chris Caron <[email protected]>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
### NZBGET POST-PROCESSING/SCHEDULER SCRIPT ###
# Download Subtitles.
#
# The script searches subtitles on various web-sites and saves them into
# destination directory near video files.
#
# This post-processing script is a wrapper for "Subliminal",
# a python library to search and download subtitles, written
# by Antoine Bertin (Diaoul Ael).
#
# Info about this Subliminal NZB Script:
# Author: Chris Caron ([email protected]).
# Date: Sun, Feb 21th, 2019.
# License: GPLv3 (http://www.gnu.org/licenses/gpl.html).
# Script Version: 1.0.1
#
# NOTE: This script requires Python to be installed on your system.
#
##############################################################################
### OPTIONS ###
# List of language codes.
#
# Language code according to ISO 639-1.
# Few examples: English - en, German - de, Dutch - nl, French - fr.
# For the full list of language codes see
# http://www.loc.gov/standards/iso639-2/php/English_list.php.
# Language Setting
#
# Subtitles for multiple languages can be downloaded. Separate multiple
# languages with some type of delimiter (space, comma, etc)
# codes with commas. Example: en, fr
#Languages=en
# Subliminal Single Mode Setting (yes, no).
#
# Download content without the language code in the subtitles filename.
# NOTE: If multiple languages are specified while this flag is set, then then
# the the search is ceased in the event that subtitles were found using at
# least one of the specified languages.
#Single=yes
# Subtitle Fetch Mode (ImpairedOnly, StandardOnly, BestScore, ImpairedFirst, StandardFirst).
#
# Define the types of subtitles you would like to scan for, the options
# break down as follows:
# ImpairedOnly - Only download hearing-impaired subtitles.
# StandardOnly - Only download non hearing-impaired subtitles.
# BestScore - Download the best matching subtitles reguardless of if they
# are flagged for the hearing-impaired or not.
# ImpairedFirst - Attempt to download the hearing-impaired subtitles
# first. In the event that they there are not available,
# then attempt to acquire the non hearing-impaired versions
# instead.
# StandardFirst - Attempt to download the standard (non hearing-impaired)
# subtitles first. In the event that they are not available,
# then attempt to acquire the the hearing-impaired versions
# instead.
#FetchMode=BestScore
# Search Mode (basic, advanced).
#
# basic - presumed subtitles are guessed based on the (deobsfucated)
# filename alone.
# advanced - presumed subtiltes are guessed based on the (deobsfucated)
# filename (same as basic). But further processing occurs to
# help obtain more accurate results. Meta data extracted from
# the actual video in question such as it's length, FPS, and
# encoding (including if subs are already included or not).
# This mode yields the best results but at the cost of additional
# time and CPU.
#SearchMode=advanced
# Ignore Embedded Subtitle Matching (yes, no).
#
# Identify how you want to handle embedded subititles if they are detected
# in the video file being scanned. If you set this value to 'no', you will
# use match embedded subtitles instead and no further script processing
# will take place.
# If you set this to 'yes', The script will then attempt to detect any embedded
# subtitles already present with the video (in addition to their languages). If
# the language is already present then no further processing is done.
# NOTE: Embedded subtitles can only be detected if you are using the advanced
# search mode identified above. Therefore this switch has no bearing
# on a Basic check.
# NOTE: This feature can not detect hard-coded subtitles; these are ones that are
# permanently embedded in the video itself.
#IgnoreEmbedded=no
# Minimum File Size (in MB)
#
# Any video that is equal to this size or larger will not be filtered out from
# having it checked for subtitles. This option prevents unnecessary queries
# to subtitle providers when the video in question is just a sample or preview
# file anyway. The sample/preview videos will get filtered out by this option
# but still allow for a subtitle checks against the real thing.
# Setting this value to 0 (zero) will disable this filter feature and attempted
# to fetch subtitles on all matched video formats (not recommended).
#MinSize=150
# Minimum File Score
#
# When more then one subtitle is matched against a video, they are individually
# scored based on their likelyhood of being an exact match to the video they
# are being searched on. The highest scored match is the chosen one at the
# end of the day. A high score (almost perfect) is 50ish, but most videos
# score in the high 30's and low 40's. This score identifies the elimination
# which subtitles should not even be considered if it scores this value or
# lower. If you set this too high, you'll never match any subtitles. If
# you set this too low, you'll almost always acqurie a subtitle for the video
# in question, but it may not be the correct one.
# If 0 is specified, the default value assigned by the subliminal core
# application will be used.
#MinScore=20
# Default Core Subtitle Providers
#
# Supply a core (master) list of subtitle providers you want to reference
# against each video you scan. The specified subtitle providers should be
# separated by a comma and or a space. The default (if none is
# specified) are used: opensubtitles, tvsubtitles, podnapisi, addic7ed, thesubdb
#Providers=opensubtitles, tvsubtitles, podnapisi, addic7ed, thesubdb
# Movie (Exclusive) Subtitle Providers
#
# Optionally specify Movie Providers you wish to exclusively use when
# a movie is detected. If nothing is specified, then the Default
# Core Subtitle Providers (identified above) are used instead.
#
# Providers specified should be separated by a comma and or a space. An example
# of what one might specify here is: opensubtitles, podnapisi, thesubdb
#MovieProviders=
# TV Show (Exclusive) Subtitle Providers
#
# Optionally specify TV Show Providers you wish to exclusively use when
# a TV Show is detected. If nothing is specified, then the Default
# Core Subtitle Providers (identified above) are used instead.
#
# Providers specified should be separated by a comma and or a space.
# An example of what one might specify here is: tvsubtitles, addic7ed
#TVShowProviders=
# File extensions for video files.
#
# Only files with these extensions are processed. Extensions must
# be separated with commas.
# Example=.mkv,.avi,.divx,.xvid,.mov,.wmv,.mp4,.mpg,.mpeg,.vob,.iso
#VideoExtensions=.mkv,.avi,.divx,.xvid,.mov,.wmv,.mp4,.mpg,.mpeg,.vob,.iso
# Force Subtitle Encoding (None, UTF-8, UTF-16, ISO-8859-1, ISO-8859-2).
#
# Force the encoding of a subtitle file to be of a certain type. If set to
# None, then the subtitle will left as it was retrieved.
# - UTF-8: This is the encoding used by most Linux/Unix filesystems. just
# check the global variable $LANG to see if that's what you are.
# - UTF-16: This is the encoding usually used by OS/X systems and NTFS.
# - ISO-8859-1: Also referred to as Latin-1; Microsoft Windows used this
# encoding for years (in the past), and still do in some
# cases. It supports the English, Spanish, and French language
# character sets.
# - ISO-8859-2: Also referred to as Latin-2; It supports Czech, German,
# Hungarian, Polish, Romanian, Croatian, Slovak, and
# Slovene character sets.
#
# If you wish to add another encoding; just email me and i'll add it.
#ForceEncoding=None
# My Systems File Encoding (UTF-8, UTF-16, ISO-8859-1, ISO-8859-2).
#
# All systems have their own encoding; here is a loose guide you can use
# to determine what encoding you are (if you're not sure):
# - UTF-8: This is the encoding used by most Linux/Unix filesystems. just
# check the global variable $LANG to see if that's what you are.
# - UTF-16: This is the encoding usually used by OS/X systems and NTFS.
# - ISO-8859-1: Also referred to as Latin-1; Microsoft Windows used this
# encoding for years (in the past), and still do in some
# cases. It supports the English, Spanish, and French language
# character sets.
# - ISO-8859-2: Also referred to as Latin-2; It supports Czech, German,
# Hungarian, Polish, Romanian, Croatian, Slovak, and
# Slovene character sets.
#
# If you wish to add another encoding; just email me and i'll add it.
# All files that are downloaded will be written to your filesystem using
# the same encoding your operating system uses. Since there is no way
# to detect this (yet), by specifying it here, you can make it possible
# to handle files with the extended character sets.
#
#SystemEncoding=UTF-8
# Cross Reference File Paths.
#
# Specify directories local to NZBGet that contain subtitles previously
# downloaded. Once found, they'll be automatically moved over and will
# take priority over actually checking the internet. You can specify
# more then one local directory using the space (and or comma) to
# delimit each entry.
#XRefPaths=
# Cache Directory
#
# This directory is used for storing temporary cache files created when
# fetching subtitles.
#CacheDir=${TempDir}/subliminal
# List of TV categories.
#
# Comma separated list of categories for TV. VideoSort automatically
# distinguishes movies from series and dated TV shows. But it needs help
# to distinguish movies from other TV shows because they are named
# using same conventions. If a download has associated category listed in
# option <TvCategories>, Subliminal uses this information to help figure out
# the video being scanned sometimes.
# NOTE: This option is only applied to Post Processing.
#
# Category names must match categories defined in NZBGet.
#TvCategories=tv, tv2, Series
# Overwrite Mode (yes, no).
#
# Overwrite subtitles even if they previously exist.
# NOTE: This option is only applied to Post Processing.
#Overwrite=no
# Correct Videos Timestamp (yes, no).
#
# Set this to yes if you want freshly downloaded videos to have their file
# timestamp updated to `now`.
# NOTE: This option is only applied to Post Processing.
#UpdateTimestamp=yes
# Correct Video Permissions (yes, no).
#
# Set this to yes if you want to adjust the permissions associated with
# all downloaded videos (Unix/Linux only).
# NOTE: This option is only applied to Post Processing.
#UpdatePermissions=no
# Video Permission Value
#
# Specify the video permissions to set. This is only used if UpdatePermissions
# (identified above) is set to yes.
# NOTE: This option is only applied to Post Processing.
#VideoPermissions=644
# Directories to Scan
#
# Specify any number of directories this script can (recursively) check
# delimited by a comma and or space. ie: /home/nuxref/mystuff, /path/no3, etc
# For windows users, you can specify: C:\My Downloads, \\My\Network\Path, etc.
# NOTE: This option is only applied to Scheduling.
#ScanDirectories=
# Maximum File Age
#
# The maximum amount of time that can elapse before we can assume that if
# there are still no subtitles after this duration, then there never will
# be. This option prevents thrashing and requesting subtitles for something
# over and over again for no reason. This value is identified in hours
# relative to each file checked.
#
# NOTE: This option is only applied to Scheduling.
#MaxAge=24
# Addic7ed Username
#
# If you wish to utilize the addic7ed provider, you are additionally required
# to provide a username and password. Specify the `username` here.
#Addic7edUser=
# Addic7ed Password
#
# If you wish to utilize the addic7ed provider, you are additionally required
# to provide a username and password. Specify the `password` here.
#Addic7edPass=
# Open Subtitles Username
#
# If you wish to utilize the Open Subtitles provider, you are additionally
# required to provide a username and password. Specify the `username` here.
#OpenSubtitlesUser=
# Open Subtitles Password
#
# If you wish to utilize the Open Subtitles provider, you are additionally
# required to provide a username and password. Specify the `password` here.
#OpenSubtitlesPass=
# Notify URLs
#
# Define as many Notification URLs as you want (separated by a space and/or
# comma) to have services notified after a subtitle has been retrieved. For
# Information on how to construct these URLs, visit:
# https://github.com/caronc/apprise .
#NotifyURLs=
# Throttle Threshold.
#
# The threshold defines the number of concurrent requests made to the remote
# subtitle websites before a temporary wait/pause occurs (defined by
# Throttle). The goal of the threshold is to prevent one from being
# banned for abusing the server (which can happen if you make to many
# requests). This setting is ideal for those users who are scanning and
# getting subtitles for a very large media library. Set this value to 0 (zero)
# if you want to disable this feature.
#ThrottleThreshold=5
# Throttle.
#
# Defines the number of seconds a throttle/block will occur for when/if
# a Throttle Threshold is reached.
#Throttle=3
# Enable debug logging (yes, no).
#
# If subtitles are not downloaded as expected, activate debug logging
# to get a more verbose output from subliminal. This will greatly help in
# diagnosing the problem.
#Debug=no
# Tidy Subtitles (on, off).
#
# Open the downloaded subtitle file and perform some additional optimizations
# to it. This is a work in progress, currently it does the following:
# - Correct all EOL (End of Lines) in the event they're inconsistent
#TidySub=off
# Issue a scan of any directories you defined above here:
#SubliminalScan@Scan Defined Paths
### NZBGET POST-PROCESSING/SCHEDULER SCRIPT ###
##############################################################################
import re
from os import sep as os_sep
from os.path import join
import errno
from shutil import move as _move
from os import getcwd
from os.path import split
from os.path import basename
from os.path import abspath
from os.path import dirname
from os.path import splitext
from os.path import isfile
from os.path import exists
from os.path import isdir
from os import unlink
from os import chdir
from os import makedirs
from time import sleep
import logging
from ConfigParser import ConfigParser
from ConfigParser import Error as ConfigException
from ConfigParser import NoOptionError as ConfigNoOption
# This is required if the below environment variables
# are not included in your environment already
import sys
sys.path.insert(0, join(abspath(dirname(__file__)), 'Subliminal'))
# For copying our configuration file
from shutil import copy
from shutil import copyfile
# Script dependencies identified below
from guessit import matcher
from guessit import Guess
from datetime import timedelta
from datetime import datetime
from subliminal import Video
from subliminal import Episode
from subliminal import MutexLock
from subliminal import cache_region
from subliminal import scan_video
from subliminal import download_best_subtitles
from subliminal.subtitle import detect
import babelfish
# pynzbget Script Wrappers
from nzbget import SABPostProcessScript
from nzbget import PostProcessScript
from nzbget import SchedulerScript
from nzbget import EXIT_CODE
from nzbget import SCRIPT_MODE
# Inherit Push Notification Scripts
from apprise import Apprise
from apprise import NotifyType
from apprise import NotifyFormat
from apprise import AppriseAsset
def move(src, dst):
"""
This move() function was written for people using this script to write
their content in Linux to a fuse based filesystem that does not have
support for the move() command.
"""
try:
# first try the standard approach
_move(src, dst)
except OSError, e:
if e[0] == errno.ENOSYS:
# Function not implimented error; try a copy/remove instead
# without tracking metadata (this is useful when we're
# moving files across different filesystems such as
# xfs -> fat32 or ext4 -> ntfs which can't preserve the
# linux modes and settings.
try:
copyfile(src, dst)
try:
unlink(src)
except:
raise OSError(errno.EPERM, "copyfile() failed.")
except OSError:
# most likely error 38 again (ENOSYS)
pass
else:
# the move failed...
raise
return
class FETCH_MODE(object):
IMPAIRED_ONLY = "ImpairedOnly"
STANDARD_ONLY = "StandardOnly"
BESTSCORE = "BestScore"
IMPAIRED_FIRST = "ImpairedFirst"
STANDARD_FIRST = "StandardFirst"
FETCH_MODES = (
FETCH_MODE.IMPAIRED_ONLY,
FETCH_MODE.STANDARD_ONLY,
FETCH_MODE.BESTSCORE,
FETCH_MODE.STANDARD_FIRST,
FETCH_MODE.IMPAIRED_FIRST,
)
FETCH_MODE_DEFAULT = FETCH_MODE.BESTSCORE
class SEARCH_MODE(object):
BASIC = "basic"
ADVANCED = "advanced"
# A file that provides system defaults when populated that override
# the defaults defined below in this file
# the syntax looks like this
# [main]
# IgnoreEmbedded: Yes
DEFAULTS_CONFIG_FILE = join(abspath(dirname(__file__)), 'Subliminal.ini')
# If our default configuration file isn't present, then we attempt to
# gracefully copy a default configuration file in place.
SAMPLE_CONFIG_FILE = join(abspath(dirname(__file__)), 'Subliminal.ini.sample')
# Ensure everything is defined under this [main] heading
DEFAULTS_CONFIG_FILE_SECTION = 'main'
# Some Default Environment Variables (used with CLI)
DEFAULT_EXTENSIONS = \
'.mkv,.avi,.divx,.xvid,.mov,.wmv,.mp4,.mpg,.mpeg,.vob,.iso'
DEFAULT_MAXAGE = 24
DEFAULT_LANGUAGE = 'en'
DEFAULT_PROVIDERS = [
'opensubtitles',
'tvsubtitles',
'podnapisi',
'addic7ed',
'thesubdb',
]
# System Encodings
DEFAULT_ENCODINGS = (
# Most Linux Systems
'UTF-8',
# NTFS/OS-X
'UTF-16',
# Most French/English/Spanish Windows Systems
'ISO-8859-1',
# Czech, German, Hungarian, Polish, Romanian,
# Croatian, Slovak, Slovene.
'ISO-8859-2',
)
DEFAULT_UPDATE_TIMESTAMP = False
DEFAULT_UPDATE_PERMISSIONS = False
DEFAULT_VIDEO_PERMISSIONS = 0o644
DEFAULT_SINGLE = False
DEFAULT_FORCE = 'no'
DEFAULT_TIDYSUB = 'no'
DEFAULT_SEARCH_MODE = SEARCH_MODE.ADVANCED
DEFAULT_IGNORE_EMBEDDED = 'no'
DEFAULT_FORCE_ENCODING = 'None'
DEFAULT_SYSTEM_ENCODING = 'UTF-8'
DEFAULT_THROTTLE_THRESHOLD = 5
DEFAULT_THROTTLE_WAITTIME = 3
# A list of compiled regular expressions identifying files to not parse ever
IGNORE_FILELIST_RE = (
# Samples
re.compile('^.*[-.]sample(\.[^.]*)?$', re.IGNORECASE),
re.compile('^sample-.*$', re.IGNORECASE),
)
# The number of MegaBytes the detected video must be (with respect
# to it's filesize). If it is less than this value, then it is presumed
# no subtitles exists for it.
DEFAULT_MIN_VIDEO_SIZE_MB = 150
# The minimum score to accept a potentially matched subtitle that
# was paired against a video.
DEFAULT_MIN_VIDEO_SCORE = 20
# A simple regular expression that scans the video downloaded and
# detects the season/episode information from it.
DETECT_TVSHOW_RE = re.compile(
r'^.*[^A-Za-z0-9]?S([0-9]{1,4})E([0-9]{1,4}(E[0-9]{1,4})*)[^A-Za-z0-9]',
re.IGNORECASE,
)
# stat is used to test if the .srt file was fetched okay or not
from os import stat
# used for updating timestamp of the video
from os import utime
# used for updating video permissions
from os import chmod
def _to_alpha2(lang):
"""
A wrapper to babbelfish to lookup the alpha2 code associated with
a language defined by it's ISO 639-2 Terminology (T) and
Bibliographic (B) alpha3 code.
None is returned if the code could not be resolved otherwise
the 2 leter alpha2 code is returned.
"""
_lang = None
if len(lang) > 3:
try:
# Try by name (such as English, French, Dutch, etc)
_lang = babelfish.Language.fromcode(lang, 'name')
return _lang
except babelfish.exceptions.LanguageReverseError:
pass
elif len(lang) == 3:
try:
# Terminology
_lang = babelfish.Language.fromcode(lang, 'alpha3t')
return _lang
except babelfish.exceptions.LanguageReverseError:
try:
# Bibliographic
_lang = babelfish.Language.fromcode(lang, 'alpha3b')
return _lang
except babelfish.exceptions.LanguageReverseError:
pass
elif len(lang) == 2:
try:
_lang = babelfish.Language.fromcode(lang.lower(), 'alpha2')
return _lang
except babelfish.exceptions.LanguageReverseError:
pass
return _lang
def decode(str_data, encoding=None, lang=None):
"""
Returns the unicode string of the data passed in
otherwise it throws a ValueError() exception. This function makes
use of the chardet library
If encoding == None then it is attempted to be detected by chardet
If encoding is a string, then only that encoding is used
If encoding is a list or tuple, then each item is tried before
giving up.
"""
if isinstance(str_data, unicode):
return str_data
if encoding is None:
decoded = detect(str_data, lang)
encoding = decoded['encoding']
if isinstance(encoding, str):
encoding = ( encoding, )
if not isinstance(encoding, (tuple, list)):
return str_data
# Convert to unicode
for enc in encoding:
try:
str_data = str_data.decode(
enc,
errors='ignore',
)
return str_data
except UnicodeError:
raise ValueError(
'%s contains invalid characters' % (
str_data,
))
except KeyError:
raise ValueError(
'%s encoding could not be detected ' % (
str_data,
))
except TypeError:
try:
str_data = str_data.decode(
enc,
'ignore',
)
return str_data
except UnicodeError:
raise ValueError(
'%s contains invalid characters' % (
str_data,
))
except KeyError:
raise ValueError(
'%s encoding could not be detected ' % (
str_data,
))
return None
class SubliminalScript(SABPostProcessScript, PostProcessScript,
SchedulerScript):
"""A wrapper to Subliminal written for NZBGet
"""
# Default theme to use
default_theme = 'general'
# A list of possible subtitles to use found locally
# that take priority over a check on the internet
# if matched.
xref_paths = []
def apply_nzbheaders(self, guess):
""" Applies NZB headers (if exist) """
nzb_used = False
nzb_proper_name = self.nzb_get('propername', '')
nzb_episode_name = self.nzb_get('episodename', '')
nzb_movie_year = self.nzb_get('movieyear', '')
nzb_more_info = self.nzb_get('moreinfo', '')
if nzb_proper_name != '':
nzb_used = True
self.logger.debug('Using DNZB-ProperName')
if guess['vtype'] == 'series':
proper_name = nzb_proper_name
guess['series'] = proper_name
else:
guess['title'] = nzb_proper_name
if nzb_episode_name != '' and guess['vtype'] == 'series':
nzb_used = True
self.logger.debug('Using DNZB-EpisodeName')
guess['title'] = nzb_episode_name
if nzb_movie_year != '':
nzb_used = True
self.logger.debug('Using DNZB-MovieYear')
guess['year'] = nzb_movie_year
if nzb_more_info != '':
nzb_used = True
self.logger.debug('Using DNZB-MoreInfo')
if guess['type'] == 'movie':
regex = re.compile(
r'^http://www.imdb.com/title/(tt[0-9]+)/$', re.IGNORECASE)
matches = regex.match(nzb_more_info)
if matches:
guess['imdb'] = matches.group(1)
guess['cpimdb'] = 'cp(' + guess['imdb'] + ')'
if nzb_used:
if isinstance(guess, Guess):
self.logger.debug(guess.nice_string())
else:
self.logger.debug(str(guess))
def guess_info(self, filename, shared,
deobfuscate=True, use_nzbheaders=True):
""" Parses the filename using guessit-library """
# Year regular expression checker
year_re = re.compile('^[^(]+\((?P<year>[123][0-9]{3})\).+$')
tv_categories = [
cat.lower() for cat in \
self.parse_list(self.get('TvCategories', [])) ]
if deobfuscate:
filename = self.deobfuscate(filename)
if isinstance(filename, str):
system_encoding = self.get('SystemEncoding', DEFAULT_SYSTEM_ENCODING)
_filename = decode(filename, system_encoding)
if not _filename:
# could not detect unicode type
self.logger.debug('Could not detect unicode type.')
else:
filename = _filename
if isinstance(filename, unicode):
self.logger.debug('Guessing using: %s' % filename.encode('utf-8'))
else:
self.logger.debug('Guessing using: %s' % filename)
# Acquire a default year if we can
result = year_re.match(filename)
detected_year = None
if result:
detected_year = result.group('year')
# Pull Guess from NZBGet
if shared:
guess = self.pull_guess()
else:
guess = None
if not guess:
_matcher = matcher.IterativeMatcher(
decode(filename),
filetype='autodetect',
opts={'nolanguage': True, 'nocountry': True},
)
mtree = _matcher.match_tree
guess = _matcher.matched()
if self.vdebug:
# Verbose Mode Only
self.logger.vdebug(mtree)
for node in mtree.nodes():
if node.guess:
self.logger.vdebug(node.guess)
# Guess output prior to mangling it
self.logger.vdebug(guess.nice_string())
# fix some strange guessit guessing:
# if guessit doesn't find a year in the file name it
# thinks it is episode, but we prefer it to be handled
# as movie instead
if guess.get('type') == 'episode' and \
guess.get('episodeNumber', '') == '':
guess['type'] = 'movie'
guess['title'] = guess.get('series')
guess['year'] = '1900'
self.logger.debug(
'An episode without episode # becomes a movie',
)
# detect if year is part of series name
if guess['type'] == 'episode':
last_node = None
for node in mtree.nodes():
if node.guess:
if last_node != None and \
node.guess.get('year') != None and \
last_node.guess.get('series') != None:
if 'year' in guess:
if detected_year != str(guess['year']):
self.logger.debug(
'Detected year (%s) updated to %s!' % (
guess['year'], detected_year,
))
# Apply override
guess['year'] = detected_year
guess['series'] += ' ' + str(guess['year'])
self.logger.debug('Detected year as part of title.')
break
last_node = node
if 'year' not in guess and detected_year:
self.logger.debug(
'Setting detected year %s!' % (
detected_year,
))
# Apply override
guess['year'] = detected_year
if 'series' in guess:
guess['series'] += ' ' + str(guess['year'])
if guess['type'] == 'movie':
category = self.get('CATEGORY', '').lower()
force_tv = category in tv_categories
matches = DETECT_TVSHOW_RE.match(filename)
if matches:
# Enforce TV Show
force_tv = True
# Help out with guessed info
_season = int(matches.group(1))
_episodeList = sorted(re.split('[eE]', matches.group(2)), key=int)
_episode = int(_episodeList[0])
if u'episode' not in guess:
guess[u'episode'] = _episode
if u'season' not in guess:
guess[u'season'] = _season
if len(_episodeList) > 1 and u'episodeList' not in guess:
guess[u'episodeList'] = _episodeList
date = guess.get('date')
if date:
guess['vtype'] = 'dated'
elif force_tv:
guess['vtype'] = 'othertv'
else:
guess['vtype'] = 'movie'
if detected_year:
if 'year' not in guess:
self.logger.debug(
'Setting detected year %s!' % (
detected_year,
))
# Apply override
guess['year'] = detected_year
elif detected_year != str(guess['year']):
self.logger.debug(
'Detected year (%s) updated to %s!' % (
guess['year'], detected_year,
))
# Apply override
guess['year'] = detected_year
elif guess['type'] == 'episode':
guess['vtype'] = 'series'
self.logger.debug(guess.nice_string())
else:
self.logger.debug('Guessed content already provided by NZBGet!')
if 'vtype' not in guess:
raise ValueError("Non-guessable filename.")
self.logger.debug('Type: %s' % guess['vtype'])
if use_nzbheaders:
# Apply nzb meta information to guess if present
self.apply_nzbheaders(guess)
if shared:
# Push Guess to NZBGet
self.push_guess(guess)
return guess
def tidy_subtitle(self, fname):
"""post process applied to filename
"""
self.logger.debug(
'Post processing subtitle %s' % \
basename(fname),
)
tmp_fname = '%s.tmp' % fname
old_fname = '%s.old' % fname
try:
unlink(tmp_fname)
#self.logger.debug(
# 'Removed temporary srt re-encode file : %s' % \
# basename(tmp_fname),
#)
except:
# no problem
pass
try:
unlink(old_fname)
#self.logger.debug(
# 'Removed old srt re-encode file : %s' % \
# basename(old_fname),
#)
except:
# no problem
pass
try:
f = open(fname, 'rb')
except IOError:
self.logger.error(
'Could not open %s for post processing.' % \
basename(fname),
)
return False
try:
fw = open(tmp_fname, 'wb')
except:
self.logger.error(
'Could not create new file %s.' % \
basename(tmp_fname),
)
try:
f.close()
except:
pass
return False
# Broken Lines
# These have been appearing in Python 2.7.11 results
re_broken_lines = re.compile('\r\r\n', re.MULTILINE)
def readchunk():
"""Lazsy function (generator) to read a file piece by piece.
Default chunk size: 204800 bytes (200K)."""
return f.read(204800)
for chunk in iter(readchunk, ''):
processed = re_broken_lines.sub('\r\n', chunk)
try:
fw.write(processed)
except:
self.logger.error(
'Could not write to new file %s.' % \
basename(tmp_fname),
)
try:
f.close()
except:
pass
try:
fw.close()
except:
pass
return False
try:
f.close()
except:
pass
try:
fw.close()
except:
pass
try:
move(fname, old_fname)
except OSError:
self.logger.error(
'Could not move %s to %s' % (
basename(fname),
basename(old_fname),
)