-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtubelex.py
executable file
·1609 lines (1412 loc) · 57.6 KB
/
tubelex.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
import re
import os
import sys
from collections.abc import Iterator, Iterable, Callable
from typing import Optional
from collections import Counter, defaultdict
from collections.abc import Container
from urllib.request import urlretrieve
from contextlib import contextmanager
from zipfile import ZipFile
from itertools import chain, groupby, compress, islice
import argparse
import json
from os.path import splitext
from tqdm import tqdm # type: ignore
import numpy as np
import pandas as pd # type: ignore
from sklearn.feature_extraction.text import TfidfVectorizer # type: ignore
from sklearn.metrics.pairwise import linear_kernel # type: ignore
import fasttext # type: ignore
from lang_utils import (
match_relaxed_word, iter_tokenize_word_num,
iter_tokenized_replace_num, iter_tagged_replace_num,
add_tagger_arg_group, tagger_from_args,
OPT_BASE_LEMMA_READING_POS, POSTagger,
sub_smart_apos, repl_smart_apos,
NORMALIZE_FULLWIDTH_TILDE
)
from freq_utils import Storage, WordCounterGroup
from vtt import VTTCleaner, sub_space
from replacer import Replacer
import hkust_mtsc
from unicodedata import normalize as unicode_normalize
import pysbd
import pysbd_indonesian # Adds Indonesian support even if "unused" import
# We use the smaller model from
# https://fasttext.cc/docs/en/language-identification.html
FT_LID_MODEL_PATH = 'lid.176.ftz'
FT_LID_MODEL_URL = (
'https://dl.fbaipublicfiles.com/fasttext/supervised-models/lid.176.ftz'
)
def make_lang_label(lang: str) -> list[str]:
return [f'__label__{lang}']
def nfkc_lower(s: str) -> str:
return unicode_normalize('NFKC', s).lower()
MIN_LANG_FREQ = 0.95
SIMILARITY_LIMIT = 0.95
MIN_LANG_CHARS_FREQ = 0.7
MIN_NONEMPTY_LINES = 3
SUB_SUFFIX = '.vtt' # input
DATA_SUFFIX = '.txt' # intermediate data
CLEAN_PATH_FMT = 'corpus/clean-%s'
UNIQUE_PATH_FMT = 'corpus/unique-%s'
# Defaults for CLI arguments:
DATA_PATH_FMT = 'jtubespeech-subtitles/video/%s/vtt'
SUBLIST_PATH_FMT = 'jtubespeech-subtitles/sub/%s/%s_sample.csv'
DEFAULT_FREQ_PATH_FMT = 'frequencies/tubelex-%s%%.tsv'
DEFAULT_TOK_PATH_FMT = 'corpus/tokenized-%s.txt'
DEFAULT_VLIST_PATH_FMT = 'corpus/videos-%s.csv'
DEFAULT_CHANNEL_STATS_PATH_FMT = 'frequencies/tubelex-%s-channels.tsv'
DEFAULT_REM_ADDR_PATH_FMT = 'frequencies/tubelex-%s-removed-addresses.json'
DEFAULT_MIN_VIDEOS = 0
DEFAULT_MIN_CHANNELS = 0
DEFAULT_STANZA_FORCE_SPLIT_LEN = 1024
LINEAR_KERNEL_CHUNK_SIZE = 10000
Tokenizer = Callable[[str], list[str]]
TokenizerTagger = Callable[[str], list[tuple[str, str]]]
WordFilter = Callable[[str], bool]
NA_POS = 'N/A'
CAT_ID2CATEGORY = {
'autos': 'Autos & Vehicles',
'comedy': 'Comedy',
'education': 'Education',
'entertainment': 'Entertainment',
'film': 'Film & Animation',
'gaming': 'Gaming',
'howto': 'Howto & Style',
'music': 'Music',
'news': 'News & Politics',
'nonprofits': 'Nonprofits & Activism',
'people': 'People & Blogs',
'pets': 'Pets & Animals',
'science': 'Science & Technology',
'sports': 'Sports',
'travel': 'Travel & Events'
}
# Assume that [.?!] followed by a whitespace (or end of string) or two newlines
# split a sentence, as they typically do in languages using Western punctuation
# in Stanza:
PAT_STANZA_SENT_SPLIT = re.compile(r'[.?!](\s|$)|\n\n|$')
def force_split_iter(s: str, max_len: int) -> Iterator[str]:
r'''
Force split substrings longer than `max_len` not containing PAT_STANZA_SENT_SPLIT.
>>> list(force_split_iter('XXXyyyZZZ', 3)) # no spaces and linebreaks
['XXX', 'yyy', 'ZZZ']
>>> list(force_split_iter('XXX yyy\nZ', 3)) # spaces and linebreaks
['XXX', 'yyy', 'Z']
>>> list(force_split_iter('XX\nyy zz\nUUUw', 3)) # mix and shorter sequences
['XX', 'yy', 'zz', 'UUU', 'w']
>>> list(force_split_iter('XX\n\nyy\n\nzz\n\nUUU. w', 3)) # has sentence splits
['XX\n\nyy\n\nzz\n\nUUU. w']
>>> list(force_split_iter('UUU.', 3)) # trailing dot (not followed by \s)
['UUU.']
'''
prev_ss = 0
prev_force = 0
for m in PAT_STANZA_SENT_SPLIT.finditer(s):
ss_start, ss_end = m.span()
while ss_start - prev_ss > max_len:
# Span between two splits too long:
must_split = s[prev_ss:prev_ss + max_len + 1]
# Find the last possible place to force split (ideally a newline):
force_pos = must_split.rfind('\n')
force_len = 1
if force_pos == -1:
force_pos = must_split.rfind(' ')
if force_pos == -1:
force_pos = max_len
force_len = 0
force_start = prev_ss + force_pos # index in s
# Split:
yield s[prev_force:force_start]
prev_force = force_start + force_len # do not include the newline/space
prev_ss = prev_force
prev_ss = ss_end
yield s[prev_force:]
def force_split(s: str, max_len: int) -> str:
return '\n\n'.join(force_split_iter(s, max_len))
def stanza_sentences_workaround(
nlp # : stanza.Pipeline
): # -> Callable[[str], Iterable['stanza.models.common.doc.Sentence']]
'''
Workaround for this bug: https://github.com/stanfordnlp/stanza/issues/1401
'''
def nlp_sentences(s: str):
try:
sentences = nlp(s).sentences # list
# Sometimes inexplicably results in:
#
# RuntimeError: Length of all samples has to be greater than 0, but found
# an element in 'lengths' that is <= 0
except RuntimeError:
# Workaround:
chunks = s.split('\n\n')
try:
sentences = chain.from_iterable(
map(lambda chunk: nlp(chunk).sentences, chunks)
)
except RuntimeError as e:
sys.stderr.write(
f'Irrecoverable RuntimeError in NLP pipeline:\n\n'
f's = "{s}"\n\n'
f'chunks = {chunks}\n\n'
)
raise e
return sentences # list or iterator
return nlp_sentences
def linear_kernel_piecewise(x, max_size=LINEAR_KERNEL_CHUNK_SIZE, wrapper=None):
# To support sparse matrices we split manually (not using np.array_split).
# Note: Row slicing is efficient for CSR (Compressed Sparse Row).
pieces = [x[i:i + max_size] for i in range(0, x.shape[0], max_size)]
if wrapper:
pieces = wrapper(pieces)
return np.concatenate([linear_kernel(p, x) for p in pieces])
def add_tokenizer_arg_group(
parser: argparse.ArgumentParser,
unique_tokenization: bool = False,
title='Tokenization options'
):
group = parser.add_argument_group(title=title)
group.add_argument(
'--tokenization', choices=['regex', 'treebank'], default=None, help=(
'Use other tokenization for frequency counting than the default Stanza'
'(StanfordNLP) for languages other than Chinese or Japanese. '
'Treebank requires English.'
)
)
if unique_tokenization:
group.add_argument(
'--unique-tokenization', choices=['regex', 'stanza', 'treebank'],
default=None, help=(
'Use other tokenization for deduplication (--uniqe) than the default '
'treebank for English and regex for languages other than Chinese or '
'Japanese. Treebank requires English.'
)
)
group.add_argument(
'--pos', '-P', action='store_true',
help='Add most common POS to frequencies'
)
group.add_argument(
'--extended-pos', '-X', action='store_true',
help=(
'Tag compound verbs, compound particles, auxiliaries, mimetic words in '
'Japanese.'
)
)
group.add_argument(
'--form', choices=['surface', 'base', 'lemma'], default='surface',
help=(
'Recorded word form: surface, base form, or lemma '
'(base form in standard orthography). Affects --unique and --frequencies.'
)
)
group.add_argument(
'--stanza-force-split', type=int,
dest='split_len', default=DEFAULT_STANZA_FORCE_SPLIT_LEN,
help=(
'When using Stanza tokenization, force split sequences without sentence '
'boundaries longer than SPLIT_LEN. '
'(Default: {DEFAULT_STANZA_FORCE_SPLIT_LEN}.)'
)
)
group.add_argument(
'--no-smart-apostrophe', action='store_false', dest='smart_apostrophe', help=(
'Do not heuristically convert right single quote "’" to apostrophe "\'" '
'before English tokenization.'
)
)
group.add_argument(
'--no-filter-tokens', action='store_false', dest='filter_tokens', help=(
'Do not filter tokens, do not replace numbers. (Does not apply to regex.)'
)
)
add_tagger_arg_group(group)
def parse() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=(
'Process subtitles from jtubespeech-subtitles or jtubespeech and '
'compute word frequencies'
))
parser.add_argument(
'--tf-idf-ngram-min', dest='nmin', type=int, default=1,
help='Consider n-grams where n>=NMIN for TF-IDF.'
)
parser.add_argument(
'--tf-idf-ngram-max', dest='nmax', type=int, default=1,
help='Consider n-grams where n<=NMAX for TF-IDF.'
)
parser.add_argument(
'--language', type=str, default='ja',
help='Language (2-letter code, default: ja).'
)
parser.add_argument(
'--identifier', type=str, default=None,
help='Identifier (instead of language and category) for corpus files.'
)
add_tokenizer_arg_group(parser, unique_tokenization=True)
parser.add_argument(
'--tokenized-files', type=str, default=None,
help=(
'Compute frequencies from tokenized files in a specified directory'
'(e.g. SubIMDB; see README; requires --frequencies and --output).'
)
)
parser.add_argument(
'--laborotvspeech', action='store_true',
help=(
'Tokenized files are LaboroTVSpeech (see README).'
)
)
parser.add_argument(
'--hkust-mtsc', action='store_true',
help=(
'Tokenized files are HKUST-MCTS (see README).'
)
)
parser.add_argument(
'--no-filter-cc-descriptions', action='store_false',
dest='filter_cc_descriptions', help=(
'Do not filter CC descriptions in brackets (e.g. "[Music]", "[Applause]").'
)
)
parser.add_argument(
'--data', type=str, default=None,
help='Data path (default: jtubespeech-subtitles, based on language).'
)
parser.add_argument(
'--list', type=str, default=None,
help='List path (default: jtubespeech-subtitles sample, based on language).'
)
parser.add_argument(
'--limit-categories', '-C', nargs='+', choices=CAT_ID2CATEGORY, default=None,
help='Limit the list to certain categories (default: all)'
)
parser.add_argument(
'--start-index', type=int, default=None,
help='Index of the first file to process.'
)
parser.add_argument(
'--stop-index', type=int, default=None,
help='Index of the first file not to process.'
)
parser.add_argument('--clean', '-c', action='store_true', help='Clean up data')
parser.add_argument('--unique', '-u', action='store_true', help='Deduplicate data')
final_step = parser.add_mutually_exclusive_group()
final_step.add_argument(
'--frequencies', '-f', action='store_true',
help='Compute frequencies'
)
final_step.add_argument(
'--video-list', '-l', action='store_true',
help='Dump video IDs and metadata actually used for the corpus.'
)
final_step.add_argument(
'--tokenize', '-t', action='store_true',
help=(
'Tokenize (create data suitable for training embeddings instead of '
'counting frequencies).'
)
)
parser.add_argument(
'--no-categories', action='store_false', dest='categories',
help='Do not add video categories'
)
parser.add_argument(
'--min-videos', type=int, default=DEFAULT_MIN_VIDEOS, help=(
f'Minimum videos for the word to be counted (default: {DEFAULT_MIN_VIDEOS})'
)
)
parser.add_argument(
'--min-channels', type=int, default=DEFAULT_MIN_CHANNELS, help=(
f'Minimum channels for the word to be counted (default: '
f'{DEFAULT_MIN_CHANNELS})'
)
)
Storage.add_arg_group(parser, 'Compression options', zip_suffix=True)
parser.add_argument(
'--output', '-o', type=str, default=None,
help=(
'Output filename for --frequencies, --video-list, and --tokenize. '
'If the placeholder "%%" is present, it is replaced with a string '
'identifying the normalization. Otherwise, output only unnormalized data.'
)
)
parser.add_argument(
'--channel-stats', type=str, default=None,
help='Output filename for channel stats (computed together with frequencies)'
)
parser.add_argument(
'--removed-addresses', type=str, default=None,
help='Output filename for removed addresses.'
)
parser.add_argument(
'--verbose', '-v', action='store_true', help=(
'Print verbose per-file information for cleanup. '
'Print tokens when computing frequencies.'
)
)
return parser.parse_args()
@contextmanager
def get_write_file(path: str, storage: Storage) -> Iterator[Callable[[str, str], None]]:
try:
write_file: Callable[[str, str], None]
if storage.zip_compression is not None:
zf = ZipFile(path + '.zip', 'w', storage.zip_compression)
write_file = zf.writestr # type: ignore
else:
os.makedirs(path, exist_ok=True)
def write_file(fname: str, contents: str) -> None:
with open(os.path.join(path, fname), 'w') as f:
f.write(contents)
yield write_file
finally:
if storage.zip_compression is not None:
zf.close()
PAT_ENGLISH_SEQ = re.compile(
r'[\u0020-\u007E]+' # Printable ASCII
)
PAT_LATIN_SEQ = re.compile(
r'[\u0020-\u007E' # Printable ASCII
r'\u00A0-\u024F' # Latin-1, Latin Extended-A, Latin Extended-B
r'\u0300-\u030F]+' # Some(!) combining diacritics
)
PAT_CHINESE_SEQ = re.compile(
r'[ ' # ASCII space (we replace all white space with ASCII space)
r'\u3400-\u4DB5\u4E00-\u9FCB\uF900-\uFA6A' # {Han}
r'\u2E80-\u2FD5' # Han radicals
r'\u3000-\u303F' # CJK Symbols and Punctuation
r'\uFF01-\uFF5E]+' # FW Alphanumeric and Punctuation (basically FW ASCII)
)
PAT_JAPANESE_SEQ = re.compile(
# Based on http://www.localizingjapan.com/blog/2012/01/20/regular-expressions-for-\
# japanese-text/
# We give it a little benefit of doubt by including all kanji and even radicals,
# which still could be indicative of Japanese or Chinese text.
r'[ ' # ASCII space (we replace all white space with ASCII space)
r'\u3041-\u3096' # Hiragana
r'\u30A0-\u30FF' # Katakana (full-width)
r'\u3400-\u4DB5\u4E00-\u9FCB\uF900-\uFA6A' # {Han} (Kanji incl. Chinese-only)
r'\u2E80-\u2FD5' # Han/Kanji radicals
r'\uFF5F-\uFF9F' # HW Katakana and punctutation
r'\u3000-\u303F' # CJK Symbols and Punctuation
r'\u31F0-\u31FF\u3220-\u3243\u3280-\u337F' # Misc. Japanese Symbols and Characters
r'\uFF01-\uFF5E]+' # FW Alphanumeric and Punctuation (basically FW ASCII)
)
LANG2PAT_SEQ = {
'en': PAT_ENGLISH_SEQ,
'zh': PAT_CHINESE_SEQ,
'ja': PAT_JAPANESE_SEQ
}
PAT_INVALID_TAG = re.compile(
# invalid but frequent HTML tags (would have been escaped as </> in VTT)
r'<(font|FONT|[biu])( [^>]*)?>|'
r'</(font|FONT|[biu])>|'
# in some Udacity videos:
r'\[br\]'
)
invalid_tag_subn = PAT_INVALID_TAG.subn
def invalid_tag_subn_verbose(repl: str, s: str) -> tuple[int, str]:
t, n = invalid_tag_subn(repl, s)
if n:
print(f'INVALID TAGS ({n}): {s}')
return (t, n)
PAT_NEWLINES = re.compile(r'\n+')
def repl_newlines_for_tokenization(m: re.Match) -> str:
return (' ' if (len(m.group()) == 1) else '\n')
def convert_newlines_for_tokenization(s: str) -> str:
return PAT_NEWLINES.sub(repl_newlines_for_tokenization, s)
class SubCleaner(VTTCleaner):
pat_seq: re.Pattern
n_removed_tags: int
n_lines_empty: int
n_lines_nonl: int
n_chars: int
n_chars_l: int
'''
Clean and filter lines via the __call__ method. Counts (instance variables) reflect
the last call (non-cumulative). Counts are not set until the iterator is exhausted.
'''
def __init__(self, lang: str, verbose: bool = False):
# TODO: We assume (extended) Latin alphabet for languages other than en/zh/ja
super().__init__(verbose=verbose)
self.pat_seq = LANG2PAT_SEQ.get(lang, PAT_LATIN_SEQ)
def _extra_cleanup(
self, lines: Iterable[str], delays_as_empty: bool = True
) -> Iterator[str]:
n_removed_tags = 0
n_lines_empty = 0
tag_subn = (
invalid_tag_subn_verbose if self.verbose else
invalid_tag_subn
)
for line in lines:
if delays_as_empty and not line:
# Preserve empty lines representing delays
yield line
continue
# Remove formatting tags:
line, n_tags = tag_subn('', line)
# Re-normalize whitespace:
line = sub_space(' ', line)
n_removed_tags += n_tags
if not line or line == ' ':
n_lines_empty += 1
continue # ignore empty line
yield line
self.n_removed_tags = n_removed_tags
self.n_lines_empty = n_lines_empty
def __call__(
self, lines: Iterable[str], delays_as_empty: bool = True
) -> Iterator[str]:
# Reset the counts, and set them only if the iterator is exhausted
# (safety measure)
if hasattr(self, 'n_removed_tags'):
del self.n_removed_tags
del self.n_lines_empty
del self.n_lines_nonl
del self.n_chars
del self.n_chars_l
n_lines_nonl = 0
n_chars = 0
n_chars_l = 0
pat_seq_sub = self.pat_seq.sub # for speed
for line in self._extra_cleanup(
super().__call__(lines, delays_as_empty=delays_as_empty),
delays_as_empty=delays_as_empty
):
if delays_as_empty and not line:
# Preserve empty lines representing delays
yield line
continue
line_n_chars = len(line)
# The fastest way to count (non-)`lang` characters in a mostly
# `lang` text is to remove sequences of `lang` characters using
# a (compiled) regex:
line_n_chars_l = line_n_chars - len(pat_seq_sub('', line))
if not line_n_chars_l:
n_lines_nonl += 1
continue
n_chars += line_n_chars
n_chars_l += line_n_chars_l
yield line
self.n_lines_nonl = n_lines_nonl
self.n_chars = n_chars
self.n_chars_l = n_chars_l
@property
def lang_char_frequency_in_filtered_lines(self) -> float:
n = self.n_chars
return (self.n_chars_l / n) if n else 0
def dir_files(
path: str,
suffix: Optional[str] = DATA_SUFFIX
) -> Iterator[tuple[str, str]]:
for root, _subdirs, files in os.walk(path):
for file in files:
if (
suffix is None or
file.endswith(suffix)
):
yield root, file
def filter_dir_files(
dfs: Iterator[tuple[str, str]], videoids: Container[str]
) -> Iterator[tuple[str, str]]:
return filter(
lambda df: splitext(df[1])[0] in videoids,
dfs
)
DEFAULT_ENCODING = 'utf-8'
@contextmanager
def get_files_contents(
path: str, storage: Storage, any_suffix: bool = False,
filenames: Optional[Iterable[str]] = None,
encoding: str = DEFAULT_ENCODING
):
zf = None
try:
if storage.zip_compression is not None:
zf = ZipFile(path + '.zip', 'r')
files = (
filenames if (filenames is not None) else
zf.namelist()
)
def iter_contents(start_index=None, stop_index=None):
for file in files[start_index:stop_index]:
yield zf.read(file).decode(encoding)
elif filenames:
files = filenames
def iter_contents(start_index=None, stop_index=None):
for file in files[start_index:stop_index]:
with open(os.path.join(path, file), encoding=encoding) as f:
yield f.read()
else:
dfs = list(dir_files(
path,
suffix=(None if any_suffix else DATA_SUFFIX)
))
files = [f for _d, f in dfs]
def iter_contents(start_index=None, stop_index=None):
for directory, file in dfs[start_index:stop_index]:
with open(os.path.join(directory, file), encoding=encoding) as f:
try:
yield f.read()
except Exception:
raise Exception(f'{f.name}')
yield (files, iter_contents)
finally:
if zf is not None:
zf.close()
def do_clean(
lang: str,
identifier: str,
storage: Storage,
sublist: pd.DataFrame, # for filtering files
data_path: str,
start_index: Optional[int],
stop_index: Optional[int],
verbose: bool
) -> None:
if not os.path.exists(FT_LID_MODEL_PATH):
urlretrieve(FT_LID_MODEL_URL, filename=FT_LID_MODEL_PATH)
lid_model = fasttext.load_model(FT_LID_MODEL_PATH)
lang_label = make_lang_label(lang)
videoids = set(sublist.index) # Faster than index
dfs = list(
filter_dir_files(dir_files(data_path, suffix=SUB_SUFFIX), videoids)
)[start_index:stop_index]
n_list = len(sublist)
n_total = len(dfs)
n_short = 0
n_nonlc = 0
n_lid = 0
n_valid = 0
n_valid_removed_tags = 0
n_valid_lines_empty = 0
n_valid_lines_nonl = 0
n_valid_lines_valid = 0
vtt_n_cues = 0
vtt_n_empty = 0
vtt_n_repeat = 0
vtt_n_scroll = 0
cleaner = SubCleaner(lang, verbose=verbose)
with get_write_file(CLEAN_PATH_FMT % identifier, storage) as write_file:
for directory, file in tqdm(
desc='Cleaning',
iterable=dfs
):
# clean each line, and remove repeated or empty lines
with open(os.path.join(directory, file)) as f:
lines = list(cleaner(f))
if verbose:
print(file)
print(cleaner)
n_lines = len(lines)
# Exclude short files based non-empty lines:
min_or_less_lines = len(list(
islice(filter(None, lines), 0, MIN_NONEMPTY_LINES)
))
if min_or_less_lines < MIN_NONEMPTY_LINES:
if verbose:
print(f'EXCLUDE FILE: lines = {min_or_less_lines}')
n_short += 1
continue
# Filter by `lang` char frequency:
if cleaner.lang_char_frequency_in_filtered_lines < MIN_LANG_CHARS_FREQ:
n_nonlc += 1
if verbose:
print(f'EXCLUDE FILE: lang char freq = '
f'{cleaner.lang_char_frequency_in_filtered_lines}')
continue
# Filter by `lang` line frequency:
# Deciding on `lang`-labeled line frequency is actually stricter than
# deciding based on the whole document (which could get a high `lang`
# probability even though many lines are not `lang`.
#
# Additionally, we are ignoring the probabilities.
# labels, probs = lid_model.predict(lines)
# lang_probs = [p for l, p in zip(labels, probs) if l == lang_label]
# lang_prob = np.concatenate(lang_probs).mean() if lang_probs else 0
labels, __probs = lid_model.predict(lines)
lengths = list(map(len, lines))
lang_freq = sum(compress(
lengths,
(l == lang_label for l in labels)
)) / sum(lengths) # weighted by line length
if lang_freq < MIN_LANG_FREQ:
n_lid += 1
if verbose:
print(f'EXCLUDE FILE: detected lang = {lang_freq}')
continue
n_valid_removed_tags += cleaner.n_removed_tags
n_valid_lines_empty += cleaner.n_lines_empty
n_valid_lines_nonl += cleaner.n_lines_nonl
n_valid_lines_valid += n_lines
vtt_n_cues += cleaner.n_cues
vtt_n_empty += cleaner.n_empty
vtt_n_repeat += cleaner.n_repeat
vtt_n_scroll += cleaner.n_scroll
text = '\n'.join(chain(lines, ('',))) # adds trailing \n
out_file = file.removesuffix(SUB_SUFFIX) + DATA_SUFFIX
write_file(out_file, text)
n_valid += 1
n_valid_lines_total = (
n_valid_lines_empty + n_valid_lines_nonl + n_valid_lines_valid
)
print('Cleaning stats:')
print('* video IDs in the list:')
print(f' {n_list}')
print('* files:')
print(f' {n_total} total')
print(f' {n_short} too short (<{MIN_NONEMPTY_LINES} lines)')
print(f' {n_nonlc} not enough {lang} characters (<{MIN_LANG_CHARS_FREQ} '
f'characters of the corresponding charset)')
print(f' {n_lid} not enough detected {lang} (<{MIN_LANG_FREQ})')
print(f' {n_valid} valid files after cleaning')
print('* sequences removed from valid files:')
print(f' {n_valid_removed_tags} tags')
print('* lines in valid files:')
print(f' {n_valid_lines_total} total lines')
print(f' {n_valid_lines_empty} whitespace-only lines')
print(f' {n_valid_lines_nonl} lines composed of non-{lang} characters')
print(f' {n_valid_lines_valid} valid lines after cleaning')
print('* VTT cue cleanup:')
print(f' {vtt_n_cues} total cues')
print(f' {vtt_n_empty} empty cues')
print(f' {vtt_n_repeat} repeated cues')
print(f' {vtt_n_scroll} scrolling cues')
print()
def do_unique(
lang: str,
identifier: str,
storage: Storage,
start_index: Optional[int],
stop_index: Optional[int],
tokenize: Tokenizer,
ngram_range: tuple[int, int],
max_matching: bool = False
) -> None:
with \
get_write_file(UNIQUE_PATH_FMT % identifier, storage) as write_file, \
get_files_contents(CLEAN_PATH_FMT % identifier, storage) as files_contents:
files, iter_contents = files_contents
tfidf = TfidfVectorizer(
tokenizer=tokenize,
ngram_range=ngram_range
).fit_transform(
tqdm(
desc='Building TF-IDF',
iterable=iter_contents(start_index, stop_index),
total=len(files[start_index:stop_index])
)
)
# Cosine similarity:
# tf-idf is normalized so we only need to compute the mutual dot-product
# of the vectors, i.e. linear kernel:
sim = linear_kernel_piecewise(
tfidf,
wrapper=lambda pcs: tqdm(desc='Computing similarity', iterable=pcs)
)
sim = np.tril(sim, -1) # under diagonal only
# print('Similarity histogram:')
# print(np.histogram(sim, bins=20))
# print()
dup = np.tril(sim, -1) >= SIMILARITY_LIMIT
dup_is, dup_lower_js = np.where(dup)
dup_indices = set()
# In practice, it is rarely the case, but is generally not necessary to
# remove all the duplicates.
# E.g. assume the pairs (1, 2) and (2, 3), but not (1, 3) are duplicates.
# After removing 2, it is no longer necessary to remove 3.)
# We have such "removed" duplicates in `dup_indices`.
for i, ijs in groupby(
zip(dup_is, dup_lower_js),
lambda ij: ij[0]
):
# Note: all(j<i for j in js) because of np.tril()
if any((j not in dup_indices) for _, j in ijs):
# Similar to a j<i that hasn't been already removed
dup_indices.add(i)
# else:
# We have already removed all j<i to which i is similar.
# Thus we can keep i.
# Creating a minimum list of duplicates = Minimum Vortex Cover (NP hard).
# https://en.wikipedia.org/wiki/Vertex_cover
#
# In theory going vertex-by-vertex as we do, could result in a larger cover than
# the well-known maximum matching 2-approximation, but for our data the cover is
# actually smaller. More importantly vertex-by-vertex approach guarantees that
# we keep (i.e. do not add into cover/`dup_indices`) at least one node from
# each conneted subgraph.
#
# For our data, the maximmum matching 2-approximation (code below) removes
# 2318 documents instead of just 1686.
#
# TODO use something that combines the virtues of both?
#
# for i, ijs in groupby(
# zip(dup_is, dup_lower_js),
# lambda ij: ij[0]
# ):
# for _, j in ijs:
# if j not in dup_indices:
# dup_indices.add(i)
# dup_indices.add(j)
# break
print(f'Duplicate (similarity >= {SIMILARITY_LIMIT}) stats:')
print(f' {len(files[start_index:stop_index])} total')
print(f' {len(dup_indices)} duplicates removed')
print(f' {len(files[start_index:stop_index])-len(dup_indices)} valid files')
print()
sorted_dup_indices = sorted(dup_indices)
# To list duplicate pairs and their similarities:
# for i, j in zip(dup_is, dup_lower_js):
# print(files[i], files[j], sim[i,j])
# To check that there are no duplicates now:
# no_dups = np.delete(
# np.delete(dup, sorted_dup_indices, axis=0),
# sorted_dup_indices, axis=1
# )
# test_dup_i = np.where(no_dups)[0]
# assert len(test_dup_i)==0, test_dup_i
iter_dup = iter(sorted_dup_indices)
next_dup = next(iter_dup, None)
for i, (file, text) in tqdm(
desc='Copying valid files',
iterable=enumerate(zip(files[start_index:stop_index],
iter_contents(start_index, stop_index))),
total=len(files[start_index:stop_index])
):
if i == next_dup:
next_dup = next(iter_dup, None)
else:
write_file(file, text)
LABOROTV_FILES = [
'LaboroTVSpeech_v1.0b/data/train/text.csv',
'LaboroTVSpeech_v1.0b/data/dev/text.csv',
'LaboroTVSpeech_v2.0b/data/train/text.csv',
'LaboroTVSpeech_v2.0b/data/dev/text.csv'
]
LABOROTV_SEG_PAT = re.compile(r'\+\w+\s*')
def do_frequencies(
lang: str,
identifier: str,
storage: Storage,
sublist: Optional[pd.DataFrame], # for channel ids or categories
tokenized_files: Optional[str],
tokenize: Optional[Tokenizer],
categories: bool,
pos_tag: Optional[TokenizerTagger],
filter_cc_descriptions: bool,
start_index: Optional[int],
stop_index: Optional[int],
path: Optional[str],
channel_stats_path: Optional[str],
removed_addresses_path: Optional[str],
min_videos: int,
min_channels: int,
verbose: bool,
laborotv: bool = False,
hkust: bool = False
) -> None:
assert (tokenize is not None) != (pos_tag is not None), (tokenize, pos_tag)
cat_ids = None
if sublist is not None:
channel_ids = sublist[
# backward compatibility with the original JTubeSpeech
'channelid' if 'channelid' in sublist else
'channel_id'
]
ch2n = Counter(channel_ids)
n_no_channel = ch2n.pop('', 0)
n2chn = Counter(ch2n.values())
n_channels_and_no_channels = len(ch2n) + n_no_channel
with open(
channel_stats_path or (DEFAULT_CHANNEL_STATS_PATH_FMT % lang), 'wt'
) as f:
f.write('videos_in_channel\tchannels\n')
for n, chn in sorted(n2chn.items()):
f.write(f'{n}\t{chn}\n')
f.write(f'NO_CHANNEL_ID\t{n_no_channel}\n')
if categories:
cat2id = {cat: cat_id for cat_id, cat in CAT_ID2CATEGORY.items()}
cat_ids = sublist['categories'].apply(cat2id.__getitem__)
else:
# Only warn and fall back to not outputting categories:
sys.stderr.write('Cannot count frequencies by category, missing sublist.\n')
categories = False
channel_ids = None
n_channels_and_no_channels = None
freq_path: str = path or ((DEFAULT_FREQ_PATH_FMT % identifier) + storage.suffix)
normalize = '%' in freq_path
counters = WordCounterGroup(
normalize=normalize,
channels=(channel_ids is not None),
pos=(pos_tag is not None),
categories=categories
)
replaced_counter = Counter()
removed_addresses = defaultdict(list)
with get_files_contents(
tokenized_files or (UNIQUE_PATH_FMT % identifier),
storage,
any_suffix=(tokenized_files is not None and not hkust),
filenames=(LABOROTV_FILES if laborotv else None),
encoding=(hkust_mtsc.ENCODING if hkust else DEFAULT_ENCODING)
) as files_contents:
files, iter_contents = files_contents
n_videos = len(files[start_index:stop_index])
assert n_videos, 'Something went wrong, no subtitles found.'
for video_no, (file, text) in tqdm(
desc='Computing frequencies',
iterable=enumerate(zip(files[start_index:stop_index],
iter_contents(start_index, stop_index))),
total=n_videos
):
replacer = Replacer(replaced_counter, removed_addresses)
video_id = file.removesuffix(DATA_SUFFIX)
# Videos without a channel id are counted as unique 1-video channels:
channel_id = (
(channel_ids.loc[video_id] or video_no)
if (channel_ids is not None) else None
)
# Category ID:
cat_id = (
cat_ids.loc[video_id]
if (cat_ids is not None) else None
)
if tokenized_files is None: