-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubnuker.py
614 lines (468 loc) · 17.6 KB
/
subnuker.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Remove advertising from subtitle files
This script is intended to scan subtitle files (or folders containing subtitle
files) and prompt to remove cells with advertising. Subtitle files may be
searched via regular expression or text matches. The script can handle srt
subtitle files natively or other formats (ass, srt, ssa, sub) via the aeidon
Python package.
"""
import logging
import os
import re
import sys
__program__ = 'subnuker'
__version__ = '0.4.5'
LOGGER = logging.getLogger(__program__)
class Config: # pylint: disable=R0903
"""Store global script configuration values."""
CHARFIXES = {'¶': '♪'}
REGEX = ['1x', '2x', '3x', '4x', '5x', '6x', '7x', '8x', '9x',
r'\bhttps?://', r'(?<!\.)\.(co\.uk|com|net|org)',
'air date', 'Art Subs', 'caption', 'download', 'Hawkeye147',
r'[Nn]anban', 'subtitle', 'sync', 'TVShow',
r'(?<![A-Za-z0-9])www\.', 'âª', r'^♪$', r'^\*\*$']
TERMS = ['1x', '2x', '3x', '4x', '5x', '6x', '7x', '8x', '9x',
'http://', 'https://', '.co.uk', '.com', '.net', '.org',
'air date', 'Art Subs', 'caption', 'download', 'Hawkeye147',
'Nanban', 'nanban', 'subtitle', 'sync', 'TVShow',
'www.', 'âª']
# bool switch
results = False
# store parsed options/arguments
arguments = None
options = None
# store terms or compiled regex
patterns = []
class AeidonProject:
"""Process individual subtitle files with python3-aeidon."""
def __init__(self, filename):
try:
import aeidon
except ImportError:
prerequisites()
sys.exit(1)
self.fix = Config.options.fix
self.filename = filename
self.project = aeidon.Project() # pylint: disable=W0201
self.open()
self.fixchars()
if not self.fix:
matches = self.search()
if matches:
Config.results = True
deletions = self.prompt(matches)
if deletions:
self.project.remove_subtitles(deletions)
if self.modified:
self.save()
elif self.fix:
LOGGER.info("No changes were made to '%s'", self.filename)
def fixchars(self):
"""Replace characters or strings within subtitle file."""
for key in Config.CHARFIXES:
self.project.set_search_string(key)
self.project.set_search_replacement(Config.CHARFIXES[key])
self.project.replace_all()
@property
def modified(self):
"""Check whether subtitle file has been modified."""
return self.project.main_changed > 0
def open(self):
"""Open the subtitle file into an Aeidon project."""
try:
self.project.open_main(self.filename)
except UnicodeDecodeError:
with open(self.filename, 'rb') as openfile:
encoding = get_encoding(openfile.read())
try:
self.project.open_main(self.filename, encoding)
except UnicodeDecodeError:
LOGGER.error("'%s' encountered a fatal encoding error",
self.filename)
sys.exit(1)
except: # pylint: disable=W0702
open_error(self.filename)
except: # pylint: disable=W0702
open_error(self.filename)
def prompt(self, matches):
"""Prompt user to remove cells from subtitle file."""
if Config.options.autoyes:
return matches
deletions = []
for match in matches:
os.system('clear')
print(self.project.subtitles[match].main_text)
print('----------------------------------------')
print("Delete cell %s of '%s'?" % (str(match + 1), self.filename))
response = getch().lower()
if response == 'y':
os.system('clear')
deletions.append(match)
elif response == 'n':
os.system('clear')
else:
if deletions or self.modified:
LOGGER.warning("Not saving changes made to '%s'",
self.filename)
sys.exit(0)
return deletions
def save(self):
"""Save subtitle file."""
try:
# ensure file is encoded properly while saving
self.project.main_file.encoding = 'utf_8'
self.project.save_main()
if self.fix:
LOGGER.info("Saved changes to '%s'", self.filename)
except: # pylint: disable=W0702
LOGGER.error("Unable to save '%s'", self.filename)
sys.exit(1)
def search(self):
"""Search srt in project for cells matching list of terms."""
matches = []
for pattern in Config.patterns:
matches += self.termfinder(pattern)
return sorted(set(matches), key=int)
def termfinder(self, pattern):
"""Search srt in project for cells matching term."""
if Config.options.regex:
flags = re.M | re.S | \
(0 if Config.options.case_sensitive else re.I)
self.project.set_search_regex(
pattern, flags=flags)
else:
self.project.set_search_string(
pattern, ignore_case=not Config.options.case_sensitive)
matches = []
while True:
try:
if matches:
last = matches[-1]
new = self.project.find_next(last + 1)[0]
if new != last and new > last:
matches.append(new)
else:
break
else:
matches.append(self.project.find_next()[0])
except StopIteration:
break
return matches
class SrtProject:
"""Process individual srt files."""
def __init__(self, filename):
self.filename = filename
self.modified = False
text = self.open()
if Config.CHARFIXES:
text = self.fixchars(text)
self.cells = self.split(text)
matches = self.search()
if matches:
Config.results = True
deletions = self.prompt(matches)
if deletions:
self.cells = remove_elements(self.cells, deletions)
self.modified = True
if self.modified:
try:
self.save()
except:
LOGGER.error("Failed to save '%s'\nConsider running '--fix' "
"or use the '--aeidon' option.", self.filename)
def fixchars(self, text):
"""Find and replace problematic characters."""
keys = ''.join(Config.CHARFIXES.keys())
values = ''.join(Config.CHARFIXES.values())
fixed = text.translate(str.maketrans(keys, values))
if fixed != text:
self.modified = True
return fixed
def open(self):
"""Open the subtitle file (detect encoding if necessary)."""
with open(self.filename, 'rb') as file_open:
binary = file_open.read()
try:
return binary.decode()
except UnicodeDecodeError:
encoding = get_encoding(binary)
try:
return binary.decode(encoding)
except LookupError:
return binary.decode(errors='ignore')
except: # pylint: disable=W0702
open_error(self.filename)
except: # pylint: disable=W0702
open_error(self.filename)
def prompt(self, matches):
"""Prompt user to remove cells from subtitle file."""
if Config.options.autoyes:
return matches
deletions = []
for match in matches:
os.system('clear')
print(self.cells[match])
print('----------------------------------------')
print("Delete cell %s of '%s'?" % (str(match + 1), self.filename))
response = getch().lower()
if response == 'y':
os.system('clear')
deletions.append(match)
elif response == 'n':
os.system('clear')
else:
if deletions or self.modified:
LOGGER.warning("Not saving changes made to '%s'",
self.filename)
sys.exit(0)
return deletions
def renumber(self):
"""Re-number cells."""
num = 0
for cell in self.cells:
cell_split = cell.splitlines()
if len(cell_split) >= 2:
num += 1
cell_split[0] = str(num)
yield '\n'.join(cell_split)
def save(self):
"""Format and save cells."""
# re-number cells
self.cells = list(self.renumber())
# add a newline to the last line if necessary
if not self.cells[-1].endswith('\n'):
self.cells[-1] += '\n'
# save the rejoined the list of cells
with open(self.filename, 'w') as file_open:
file_open.write('\n\n'.join(self.cells))
def search(self):
"""Return list of cells to be removed."""
matches = []
for index, cell in enumerate(self.cells):
for pattern in Config.patterns:
if ismatch(cell, pattern):
matches.append(index)
break
return matches
def split(self, text):
"""Split text into a list of cells."""
import re
if re.search('\n\n', text):
return text.split('\n\n')
elif re.search('\r\n\r\n', text):
return text.split('\r\n\r\n')
else:
LOGGER.error("'%s' does not appear to be a 'srt' subtitle file",
self.filename)
sys.exit(1)
def get_encoding(binary):
"""Return the encoding type."""
try:
from chardet import detect
except ImportError:
LOGGER.error("Please install the 'chardet' module")
sys.exit(1)
encoding = detect(binary).get('encoding')
return 'iso-8859-1' if encoding == 'CP949' else encoding
def getch():
"""Request a single character input from the user."""
if sys.platform in ['darwin', 'linux']:
import termios
import tty
file_descriptor = sys.stdin.fileno()
settings = termios.tcgetattr(file_descriptor)
try:
tty.setraw(file_descriptor)
return sys.stdin.read(1)
finally:
termios.tcsetattr(file_descriptor, termios.TCSADRAIN, settings)
elif sys.platform in ['cygwin', 'win32']:
import msvcrt
return msvcrt.getwch()
def ismatch(text, pattern):
"""Test whether text contains string or matches regex."""
if hasattr(pattern, 'search'):
return pattern.search(text) is not None
else:
return pattern in text if Config.options.case_sensitive \
else pattern.lower() in text.lower()
def logger():
"""Configure program logger."""
scriptlogger = logging.getLogger(__program__)
# ensure logger is not reconfigured
if not scriptlogger.hasHandlers():
# set log level
scriptlogger.setLevel(logging.INFO)
fmt = '%(name)s:%(levelname)s: %(message)s'
# configure terminal log
streamhandler = logging.StreamHandler()
streamhandler.setFormatter(logging.Formatter(fmt))
scriptlogger.addHandler(streamhandler)
def main(args=None):
"""Start application."""
Config.options, Config.args = parse(args)
logger()
if Config.options.aeidon or Config.options.fix:
start_aeidon()
else:
start_srt()
if Config.options.fix:
sys.exit(0)
if not Config.results:
basenames = [os.path.basename(os.path.abspath(x)) for x in Config.args]
print('Search of', basenames, 'returned no results.')
# leave the terminal open long enough to read message
if Config.options.gui:
from time import sleep
sleep(2)
def open_error(filename):
"""Display a generic error message upon failure to open file."""
LOGGER.error("Unable to open '%s'", filename)
sys.exit(1)
def parse(args):
"""Parse command-line arguments. Arguments may consist of any
combination of directories, files, and options."""
import argparse
parser = argparse.ArgumentParser(
add_help=False,
description="Remove spam and advertising from subtitle files.",
usage="%(prog)s [OPTION]... TARGET...")
parser.add_argument(
"-a", "--aeidon",
action="store_true",
dest="aeidon",
help="use python3-aeidon to process subtitles")
parser.add_argument(
"-f", "--file",
action="append",
dest="pattern_files",
help="obtain matches from FILE")
parser.add_argument(
"--fix",
action="store_true",
dest="fix",
help="repair potentially damaged subtitle files with aeidon")
parser.add_argument(
"-g", "--gui",
action="store_true",
dest="gui",
help="indicate use from a GUI")
parser.add_argument(
"-h", "--help",
action="help",
help=argparse.SUPPRESS)
parser.add_argument(
"-r", "--regex",
action="store_true",
dest="regex",
help="perform regex matching")
parser.add_argument(
"-s", "--case-sensitive",
action="store_true",
default=False,
dest="case_sensitive",
help="match case-sensitively")
parser.add_argument(
"-y", "--yes",
action="store_true",
dest="autoyes",
help="automatic yes to prompts")
parser.add_argument(
"--version",
action="version",
version='%(prog)s ' + __version__)
parser.add_argument(
dest="targets",
help=argparse.SUPPRESS,
nargs="*")
options = parser.parse_args(args)
arguments = options.targets
return options, arguments
def pattern_logic_aeidon():
"""Return patterns to be used for searching subtitles via aeidon."""
if Config.options.pattern_files:
return prep_patterns(Config.options.pattern_files)
elif Config.options.regex:
return Config.REGEX
else:
return Config.TERMS
def pattern_logic_srt():
"""Return patterns to be used for searching srt subtitles."""
if Config.options.pattern_files and Config.options.regex:
return prep_regex(prep_patterns(Config.options.pattern_files))
elif Config.options.pattern_files:
return prep_patterns(Config.options.pattern_files)
elif Config.options.regex:
return prep_regex(Config.REGEX)
else:
return Config.TERMS
def prep_files(paths, extensions):
"""Parses `paths` (which may consist of files and/or directories).
Removes duplicates, sorts, and returns verified srt files."""
from batchpath import GeneratePaths
filenames = GeneratePaths().files(paths, os.W_OK, extensions, 0, True)
if filenames:
return filenames
else:
LOGGER.error('No valid targets were specified')
sys.exit(1)
def prep_patterns(filenames):
"""Load pattern files passed via options and return list of patterns."""
patterns = []
for filename in filenames:
try:
with open(filename) as file:
patterns += [l.rstrip('\n') for l in file]
except: # pylint: disable=W0702
LOGGER.error("Unable to load pattern file '%s'" % filename)
sys.exit(1)
if patterns:
# return a set to eliminate duplicates
return set(patterns)
else:
LOGGER.error('No terms were loaded')
sys.exit(1)
def prep_regex(patterns):
"""Compile regex patterns."""
flags = 0 if Config.options.case_sensitive else re.I
return [re.compile(pattern, flags) for pattern in patterns]
def prerequisites():
"""Display information about obtaining the aeidon module."""
url = "http://home.gna.org/gaupol/download.html"
debian = "sudo apt-get install python3-aeidon"
other = "python3 setup.py --user --without-gaupol clean install"
LOGGER.error(
"The aeidon module is missing!\n\n"
"Try '{0}' or the appropriate command for your package manager.\n\n"
"You can also download the tarball for gaupol (which includes "
"aeidon) at {1}. After downloading, unpack and run '{2}'."
.format(debian, url, other))
def remove_elements(target, indices):
"""Remove multiple elements from a list and return result.
This implementation is faster than the alternative below.
Also note the creation of a new list to avoid altering the
original. We don't have any current use for the original
intact list, but may in the future..."""
copied = list(target)
for index in reversed(indices):
del copied[index]
return copied
# def remove_elements(target, indices):
# """Remove multiple elements from a list and return result."""
# return [e for i, e in enumerate(target) if i not in indices]
def start_aeidon():
"""Prepare filenames and patterns then process subtitles with aeidon."""
extensions = ['ass', 'srt', 'ssa', 'sub']
Config.filenames = prep_files(Config.args, extensions)
Config.patterns = pattern_logic_aeidon()
for filename in Config.filenames:
AeidonProject(filename)
def start_srt():
"""Prepare filenames and patterns then process srt subtitles."""
extensions = ['srt']
Config.filenames = prep_files(Config.args, extensions)
Config.patterns = pattern_logic_srt()
for filename in Config.filenames:
SrtProject(filename)