forked from rwth-i6/returnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LmDataset.py
1841 lines (1643 loc) · 61.9 KB
/
LmDataset.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
# -*- coding: utf8 -*-
"""
Provides :class:`LmDataset`, :class:`TranslationDataset`,
and some related helpers.
"""
from __future__ import print_function
import os
import sys
from Dataset import DatasetSeq
from CachedDataset2 import CachedDataset2
import gzip
import xml.etree.ElementTree as ElementTree
from Util import parse_orthography, parse_orthography_into_symbols, load_json, BackendEngine, unicode
from Log import log
import numpy
import time
import re
import typing
from random import Random
class LmDataset(CachedDataset2):
"""
Dataset useful for language modeling.
Reads simple txt files.
"""
def __init__(self,
corpus_file,
orth_symbols_file=None,
orth_symbols_map_file=None,
orth_replace_map_file=None,
word_based=False,
word_end_symbol=None,
seq_end_symbol="[END]",
unknown_symbol="[UNKNOWN]",
parse_orth_opts=None,
phone_info=None,
add_random_phone_seqs=0,
auto_replace_unknown_symbol=False,
log_auto_replace_unknown_symbols=10,
log_skipped_seqs=10,
error_on_invalid_seq=True,
add_delayed_seq_data=False,
delayed_seq_data_start_symbol="[START]",
**kwargs):
"""
After initialization, the corpus is represented by self.orths (as a list of sequences).
The vocabulary is given by self.orth_symbols and self.orth_symbols_map gives the corresponding
mapping from symbol to integer index.
:param str|()->str|list[str]|()->list[str] corpus_file: Bliss XML or line-based txt. optionally can be gzip.
:param dict|None phone_info: if you want to get phone seqs, dict with lexicon_file etc. see PhoneSeqGenerator.
:param str|()->str|None orth_symbols_file: list of orthography symbols, if you want to get orth symbol seqs.
:param str|()->str|None orth_symbols_map_file: list of orth symbols, each line: "symbol index".
:param str|()->str|None orth_replace_map_file: JSON file with replacement dict for orth symbols.
:param bool word_based: whether to parse single words, or otherwise will be character based.
:param str|None word_end_symbol: If provided and if word_based is False (character based modeling), token to be used
to represent word ends.
:param str|None seq_end_symbol: what to add at the end, if given.
will be set as postfix=[seq_end_symbol] or postfix=[] for parse_orth_opts.
:param str|None unknown_symbol: token to represent unknown words.
:param dict[str]|None parse_orth_opts: kwargs for parse_orthography().
:param int add_random_phone_seqs: will add random seqs with the same len as the real seq as additional data.
:param bool|int log_auto_replace_unknown_symbols: write about auto-replacements with unknown symbol.
if this is an int, it will only log the first N replacements, and then keep quiet.
:param bool|int log_skipped_seqs: write about skipped seqs to logging, due to missing lexicon entry or so.
if this is an int, it will only log the first N entries, and then keep quiet.
:param bool error_on_invalid_seq: if there is a seq we would have to skip, error.
:param bool add_delayed_seq_data: will add another data-key "delayed" which will have the sequence.
delayed_seq_data_start_symbol + original_sequence[:-1].
:param str delayed_seq_data_start_symbol: used for add_delayed_seq_data.
"""
super(LmDataset, self).__init__(**kwargs)
if callable(corpus_file):
corpus_file = corpus_file()
if callable(orth_symbols_file):
orth_symbols_file = orth_symbols_file()
if callable(orth_symbols_map_file):
orth_symbols_map_file = orth_symbols_map_file()
if callable(orth_replace_map_file):
orth_replace_map_file = orth_replace_map_file()
print("LmDataset, loading file", corpus_file, file=log.v4)
self.word_based = word_based
self.word_end_symbol = word_end_symbol
self.seq_end_symbol = seq_end_symbol
self.unknown_symbol = unknown_symbol
self.parse_orth_opts = parse_orth_opts or {}
self.parse_orth_opts.setdefault("word_based", self.word_based)
if self.word_end_symbol and not self.word_based: # Character-based modeling and word_end_symbol is specified.
# In this case, sentences end with self.word_end_symbol followed by the self.seq_end_symbol.
self.parse_orth_opts.setdefault("postfix", [self.word_end_symbol, self.seq_end_symbol]
if self.seq_end_symbol is not None else [self.word_end_symbol])
else:
self.parse_orth_opts.setdefault("postfix", [self.seq_end_symbol] if self.seq_end_symbol is not None else [])
if orth_symbols_file:
assert not phone_info
assert not orth_symbols_map_file
orth_symbols = open(orth_symbols_file).read().splitlines()
self.orth_symbols_map = {sym: i for (i, sym) in enumerate(orth_symbols)}
self.orth_symbols = orth_symbols
self.labels["data"] = orth_symbols
self.seq_gen = None
if orth_symbols_map_file and orth_symbols_map_file.endswith('.pkl'):
import pickle
with open(orth_symbols_map_file, 'rb') as f:
self.orth_symbols_map = pickle.load(f)
self.orth_symbols = self.orth_symbols_map.keys()
self.labels["data"] = list(self.orth_symbols)
self.seq_gen = None
elif orth_symbols_map_file:
assert not phone_info
orth_symbols_imap_list = [(int(b), a)
for (a, b) in [l.split(None, 1)
for l in open(orth_symbols_map_file).read().splitlines()]]
orth_symbols_imap_list.sort()
assert orth_symbols_imap_list[0][0] == 0
assert orth_symbols_imap_list[-1][0] == len(orth_symbols_imap_list) - 1
self.orth_symbols_map = {sym: i for (i, sym) in orth_symbols_imap_list}
self.orth_symbols = [sym for (i, sym) in orth_symbols_imap_list]
self.labels["data"] = self.orth_symbols
self.seq_gen = None
else:
assert not orth_symbols_file
assert isinstance(phone_info, dict)
self.seq_gen = PhoneSeqGenerator(**phone_info)
self.orth_symbols = None
self.labels["data"] = self.seq_gen.get_class_labels()
if orth_replace_map_file:
orth_replace_map = load_json(filename=orth_replace_map_file)
assert isinstance(orth_replace_map, dict)
self.orth_replace_map = {key: parse_orthography_into_symbols(v, word_based=self.word_based)
for (key, v) in orth_replace_map.items()}
if self.orth_replace_map:
if len(self.orth_replace_map) <= 5:
print(" orth_replace_map: %r" % self.orth_replace_map, file=log.v5)
else:
print(" orth_replace_map: %i entries" % len(self.orth_replace_map), file=log.v5)
else:
self.orth_replace_map = {}
if word_end_symbol and not word_based: # Character-based modeling and word_end_symbol is specified.
self.orth_replace_map[" "] = [word_end_symbol] # Replace all spaces by word_end_symbol.
num_labels = len(self.labels["data"])
use_uint_types = False
if BackendEngine.is_tensorflow_selected():
use_uint_types = True
if num_labels <= 2 ** 7:
self.dtype = "int8"
elif num_labels <= 2 ** 8 and use_uint_types:
self.dtype = "uint8"
elif num_labels <= 2 ** 31:
self.dtype = "int32"
elif num_labels <= 2 ** 32 and use_uint_types:
self.dtype = "uint32"
elif num_labels <= 2 ** 61:
self.dtype = "int64"
elif num_labels <= 2 ** 62 and use_uint_types:
self.dtype = "uint64"
else:
raise Exception("cannot handle so much labels: %i" % num_labels)
self.num_outputs = {"data": [len(self.labels["data"]), 1]}
self.num_inputs = self.num_outputs["data"][0]
self.seq_order = None
self._tag_prefix = "line-" # sequence tag is "line-n", where n is the line number (to be compatible with translation) # nopep8
self.auto_replace_unknown_symbol = auto_replace_unknown_symbol
self.log_auto_replace_unknown_symbols = log_auto_replace_unknown_symbols
self.log_skipped_seqs = log_skipped_seqs
self.error_on_invalid_seq = error_on_invalid_seq
self.add_random_phone_seqs = add_random_phone_seqs
for i in range(add_random_phone_seqs):
self.num_outputs["random%i" % i] = self.num_outputs["data"]
self.add_delayed_seq_data = add_delayed_seq_data
self.delayed_seq_data_start_symbol = delayed_seq_data_start_symbol
if add_delayed_seq_data:
self.num_outputs["delayed"] = self.num_outputs["data"]
self.labels["delayed"] = self.labels["data"]
if isinstance(corpus_file, list): # If a list of files is provided, concatenate all.
self.orths = []
for file_name in corpus_file:
self.orths += read_corpus(file_name)
else:
self.orths = read_corpus(corpus_file)
# It's only estimated because we might filter some out or so.
self._estimated_num_seqs = len(self.orths) // self.partition_epoch
print(" done, loaded %i sequences" % len(self.orths), file=log.v4)
self.next_orth_idx = 0
self.next_seq_idx = 0
self.num_skipped = 0
self.num_unknown = 0
def get_data_keys(self):
"""
:rtype: list[str]
"""
return sorted(self.num_outputs.keys())
def get_target_list(self):
"""
Unfortunately, the logic is swapped around for this dataset.
"data" is the original data, which is usually the target,
and you would use "delayed" as inputs.
:rtype: list[str]
"""
return ["data"]
def get_data_dtype(self, key):
"""
:param str key:
:rtype: str
"""
return self.dtype
def init_seq_order(self, epoch=None, seq_list=None):
"""
If random_shuffle_epoch1, for epoch 1 with "random" ordering, we leave the given order as is.
Otherwise, this is mostly the default behavior.
:param int|None epoch:
:param list[str] | None seq_list: In case we want to set a predefined order.
:rtype: bool
:returns whether the order changed (True is always safe to return)
"""
if seq_list and not self.error_on_invalid_seq:
print("Setting error_on_invalid_seq to True since a seq_list is given. "
"Please activate auto_replace_unknown_symbol if you want to prevent invalid sequences!",
file=log.v4)
self.error_on_invalid_seq = True
super(LmDataset, self).init_seq_order(epoch=epoch, seq_list=seq_list)
if not epoch:
epoch = 1
if seq_list is not None:
self.seq_order = [int(s[len(self._tag_prefix):]) for s in seq_list]
else:
self.seq_order = self.get_seq_order_for_epoch(
epoch=epoch, num_seqs=len(self.orths), get_seq_len=lambda i: len(self.orths[i]))
self.next_orth_idx = 0
self.next_seq_idx = 0
self.num_skipped = 0
self.num_unknown = 0
if self.seq_gen:
self.seq_gen.random_seed(epoch)
return True
def _reduce_log_skipped_seqs(self):
if isinstance(self.log_skipped_seqs, bool):
return
assert isinstance(self.log_skipped_seqs, int)
assert self.log_skipped_seqs >= 1
self.log_skipped_seqs -= 1
if not self.log_skipped_seqs:
print("LmDataset: will stop logging about skipped sequences now", file=log.v4)
def _reduce_log_auto_replace_unknown_symbols(self):
if isinstance(self.log_auto_replace_unknown_symbols, bool):
return
assert isinstance(self.log_auto_replace_unknown_symbols, int)
assert self.log_auto_replace_unknown_symbols >= 1
self.log_auto_replace_unknown_symbols -= 1
if not self.log_auto_replace_unknown_symbols:
print("LmDataset: will stop logging about auto-replace with unknown symbol now", file=log.v4)
def _collect_single_seq(self, seq_idx):
"""
:type seq_idx: int
:rtype: DatasetSeq | None
:returns DatasetSeq or None if seq_idx >= num_seqs.
"""
while True:
if self.next_orth_idx >= len(self.seq_order):
assert self.next_seq_idx <= seq_idx, "We expect that we iterate through all seqs."
if self.num_skipped > 0:
print("LmDataset: reached end, skipped %i sequences" % self.num_skipped)
return None
assert self.next_seq_idx == seq_idx, "We expect that we iterate through all seqs."
true_idx = self.seq_order[self.next_orth_idx]
orth = self.orths[true_idx] # get sequence for the next index given by seq_order
seq_tag = (self._tag_prefix + str(true_idx))
self.next_orth_idx += 1
if orth == "</s>":
continue # special sentence end symbol. empty seq, ignore.
if self.seq_gen:
try:
phones = self.seq_gen.generate_seq(orth)
except KeyError as e:
if self.log_skipped_seqs:
print("LmDataset: skipping sequence %r because of missing lexicon entry: %s" % (orth, e), file=log.v4)
self._reduce_log_skipped_seqs()
if self.error_on_invalid_seq:
raise Exception("LmDataset: invalid seq %r, missing lexicon entry %r" % (orth, e))
self.num_skipped += 1
continue # try another seq
data = self.seq_gen.seq_to_class_idxs(phones, dtype=self.dtype)
elif self.orth_symbols:
orth_syms = parse_orthography(orth, **self.parse_orth_opts)
while True:
orth_syms = sum([self.orth_replace_map.get(s, [s]) for s in orth_syms], [])
i = 0
# For the character-based case, spaces have been replaced by word_end_symbol.
space_symbol = self.word_end_symbol if self.word_end_symbol and not self.word_based else " "
while i < len(orth_syms) - 1:
if orth_syms[i:i+2] == [space_symbol, space_symbol]:
orth_syms[i:i+2] = [space_symbol] # collapse two spaces
else:
i += 1
if self.auto_replace_unknown_symbol:
try:
list(map(self.orth_symbols_map.__getitem__, orth_syms)) # convert to list to trigger map (it's lazy)
except KeyError as e:
if sys.version_info >= (3, 0):
orth_sym = e.args[0]
else:
# noinspection PyUnresolvedReferences
orth_sym = e.message
if self.log_auto_replace_unknown_symbols:
print("LmDataset: unknown orth symbol %r, adding to orth_replace_map as %r" % (
orth_sym, self.unknown_symbol), file=log.v3)
self._reduce_log_auto_replace_unknown_symbols()
self.orth_replace_map[orth_sym] = [self.unknown_symbol] if self.unknown_symbol is not None else []
continue # try this seq again with updated orth_replace_map
break
self.num_unknown += orth_syms.count(self.unknown_symbol)
if self.word_based:
orth_debug_str = repr(orth_syms)
else:
orth_debug_str = repr("".join(orth_syms))
try:
data = numpy.array(list(map(self.orth_symbols_map.__getitem__, orth_syms)), dtype=self.dtype)
except KeyError as e:
if self.log_skipped_seqs:
print("LmDataset: skipping sequence %s because of missing orth symbol: %s" % (orth_debug_str, e),
file=log.v4)
self._reduce_log_skipped_seqs()
if self.error_on_invalid_seq:
raise Exception("LmDataset: invalid seq %s, missing orth symbol %s" % (orth_debug_str, e))
self.num_skipped += 1
continue # try another seq
else:
assert False
targets = {}
for i in range(self.add_random_phone_seqs):
assert self.seq_gen # not implemented atm for orths
phones = self.seq_gen.generate_garbage_seq(target_len=data.shape[0])
targets["random%i" % i] = self.seq_gen.seq_to_class_idxs(phones, dtype=self.dtype)
if self.add_delayed_seq_data:
targets["delayed"] = numpy.concatenate(
([self.orth_symbols_map[self.delayed_seq_data_start_symbol]], data[:-1])).astype(self.dtype)
assert targets["delayed"].shape == data.shape
self.next_seq_idx = seq_idx + 1
return DatasetSeq(seq_idx=seq_idx, features=data, targets=targets, seq_tag=seq_tag)
def _is_bliss(filename):
"""
:param str filename:
:rtype: bool
"""
try:
corpus_file = open(filename, 'rb')
if filename.endswith(".gz"):
corpus_file = gzip.GzipFile(fileobj=corpus_file)
context = iter(ElementTree.iterparse(corpus_file, events=('start', 'end')))
_, root = next(context) # get root element
assert isinstance(root, ElementTree.Element)
return root.tag == "corpus"
except IOError: # 'Not a gzipped file' or so
pass
except ElementTree.ParseError: # 'syntax error' or so
pass
return False
def _iter_bliss(filename, callback):
"""
:param str filename:
:param (str)->None callback:
"""
corpus_file = open(filename, 'rb')
if filename.endswith(".gz"):
corpus_file = gzip.GzipFile(fileobj=corpus_file)
def getelements(tag):
"""
Yield *tag* elements from *filename_or_file* xml incrementally.
:param str tag:
"""
context = iter(ElementTree.iterparse(corpus_file, events=('start', 'end')))
_, root = next(context) # get root element
tree_ = [root]
for event, elem_ in context:
if event == "start":
tree_ += [elem_]
elif event == "end":
assert tree_[-1] is elem_
tree_ = tree_[:-1]
if event == 'end' and elem_.tag == tag:
yield tree_, elem_
root.clear() # free memory
for tree, elem in getelements("segment"):
elem_orth = elem.find("orth")
orth_raw = elem_orth.text # should be unicode
orth_split = orth_raw.split()
orth = " ".join(orth_split)
callback(orth)
def _iter_txt(filename, callback):
"""
:param str filename:
:param (str)->None callback:
"""
f = open(filename, 'rb')
if filename.endswith(".gz"):
f = gzip.GzipFile(fileobj=f)
for line in f:
try:
line = line.decode("utf8")
except UnicodeDecodeError:
line = line.decode("latin_1") # or iso8859_15?
line = line.strip()
if not line:
continue
callback(line)
def iter_corpus(filename, callback):
"""
:param str filename:
:param ((str)->None) callback:
"""
if _is_bliss(filename):
iter_f = _iter_bliss
else:
iter_f = _iter_txt
iter_f(filename, callback)
def read_corpus(filename):
"""
:param str filename:
:return: list of orthographies
:rtype: list[str]
"""
out_list = []
iter_corpus(filename, out_list.append)
return out_list
class AllophoneState:
"""
Represents one allophone (phone with context) state (number, boundary).
In Sprint, see AllophoneStateAlphabet::index().
"""
id = None # u16 in Sprint. here just str
context_history = () # list[u16] of phone id. here just list[str]
context_future = () # list[u16] of phone id. here just list[str]
boundary = 0 # s16. flags. 1 -> initial (@i), 2 -> final (@f)
state = None # s16, e.g. 0,1,2
_attrs = ["id", "context_history", "context_future", "boundary", "state"]
# noinspection PyShadowingBuiltins
def __init__(self, id=None, state=None):
"""
:param str id: phone
:param int|None state:
"""
self.id = id
self.state = state
def format(self):
"""
:rtype: str
"""
s = "%s{%s+%s}" % (
self.id,
"-".join(self.context_history) or "#",
"-".join(self.context_future) or "#")
if self.boundary & 1:
s += "@i"
if self.boundary & 2:
s += "@f"
if self.state is not None:
s += ".%i" % self.state
return s
def __repr__(self):
return self.format()
def copy(self):
"""
:rtype: AllophoneState
"""
a = AllophoneState(id=self.id, state=self.state)
for attr in self._attrs:
if getattr(self, attr):
setattr(a, attr, getattr(self, attr))
return a
def mark_initial(self):
"""
Add flag to self.boundary.
"""
self.boundary = self.boundary | 1
def mark_final(self):
"""
Add flag to self.boundary.
"""
self.boundary = self.boundary | 2
def phoneme(self, ctx_offset, out_of_context_id=None):
"""
Phoneme::Id ContextPhonology::PhonemeInContext::phoneme(s16 pos) const {
if (pos == 0)
return phoneme_;
else if (pos > 0) {
if (u16(pos - 1) < context_.future.length())
return context_.future[pos - 1];
else
return Phoneme::term;
} else { verify(pos < 0);
if (u16(-1 - pos) < context_.history.length())
return context_.history[-1 - pos];
else
return Phoneme::term;
}
}
:param int ctx_offset: 0 for center, >0 for future, <0 for history
:param str|None out_of_context_id: what to return out of our context
:return: phone-id from the offset
:rtype: str
"""
if ctx_offset == 0:
return self.id
if ctx_offset > 0:
idx = ctx_offset - 1
if idx >= len(self.context_future):
return out_of_context_id
return self.context_future[idx]
if ctx_offset < 0:
idx = -ctx_offset - 1
if idx >= len(self.context_history):
return out_of_context_id
return self.context_history[idx]
assert False
def set_phoneme(self, ctx_offset, phone_id):
"""
:param int ctx_offset: 0 for center, >0 for future, <0 for history
:param str phone_id:
"""
if ctx_offset == 0:
self.id = phone_id
elif ctx_offset > 0:
idx = ctx_offset - 1
assert idx == len(self.context_future)
self.context_future = self.context_future + (phone_id,)
elif ctx_offset < 0:
idx = -ctx_offset - 1
assert idx == len(self.context_history)
self.context_history = self.context_history + (phone_id,)
def phone_idx(self, ctx_offset, phone_idxs):
"""
:param int ctx_offset: see self.phoneme()
:param dict[str,int] phone_idxs:
:rtype: int
"""
phone = self.phoneme(ctx_offset=ctx_offset)
if phone is None:
return 0 # by definition in the Sprint C++ code: static const Id term = 0;
else:
return phone_idxs[phone] + 1
def index(self, phone_idxs, num_states=3, context_length=1):
"""
See self.from_index() for the inverse function.
And see Sprint NoStateTyingDense::classify().
:param dict[str,int] phone_idxs:
:param int num_states: how much state per allophone
:param int context_length: how much left/right context
:rtype: int
"""
assert max(len(self.context_history), len(self.context_future)) <= context_length
assert 0 <= self.boundary < 4
assert 0 <= self.state < num_states
num_phones = max(phone_idxs.values()) + 1
num_phone_classes = num_phones + 1 # 0 is the special no-context symbol
result = 0
for i in range(2 * context_length + 1):
pos = i // 2
if i % 2 == 1:
pos = -pos - 1
result *= num_phone_classes
result += self.phone_idx(ctx_offset=pos, phone_idxs=phone_idxs)
result *= num_states
result += self.state
result *= 4
result += self.boundary
return result
@classmethod
def from_index(cls, index, phone_ids, num_states=3, context_length=1):
"""
Original Sprint C++ code:
Mm::MixtureIndex NoStateTyingDense::classify(const AllophoneState& a) const {
require_lt(a.allophone()->boundary, numBoundaryClasses_);
require_le(0, a.state());
require_lt(u32(a.state()), numStates_);
u32 result = 0;
for(u32 i = 0; i < 2 * contextLength_ + 1; ++i) { // context len is usually 1
// pos sequence: 0, -1, 1, [-2, 2, ...]
s16 pos = i / 2;
if(i % 2 == 1)
pos = -pos - 1;
result *= numPhoneClasses_;
u32 phoneIdx = a.allophone()->phoneme(pos);
require_lt(phoneIdx, numPhoneClasses_);
result += phoneIdx;
}
result *= numStates_;
result += u32(a.state());
result *= numBoundaryClasses_;
result += a.allophone()->boundary;
require_lt(result, nClasses_);
return result;
}
Note that there is also AllophoneStateAlphabet::allophoneState, via Am/ClassicStateModel.cc,
which unfortunately uses a different encoding.
See :func:`from_classic_index`.
:param int index:
:param dict[int,str] phone_ids: reverse-map from self.index(). idx -> id
:param int num_states: how much state per allophone
:param int context_length: how much left/right context
:rtype: int
:rtype: AllophoneState
"""
num_phones = max(phone_ids.keys()) + 1
num_phone_classes = num_phones + 1 # 0 is the special no-context symbol
code = index
result = AllophoneState()
result.boundary = code % 4
code //= 4
result.state = code % num_states
code //= num_states
for i in range(2 * context_length + 1):
pos = i // 2
if i % 2 == 1:
pos = -pos - 1
phone_idx = code % num_phone_classes
code //= num_phone_classes
result.set_phoneme(ctx_offset=pos, phone_id=phone_ids[phone_idx - 1] if phone_idx else "")
return result
@classmethod
def from_classic_index(cls, index, allophones, max_states=6):
"""
Via Sprint C++ Archiver.cc:getStateInfo():
const u32 max_states = 6; // TODO: should be increased for non-speech
for (state = 0; state < max_states; ++state) {
if (emission >= allophones_.size())
emission -= (1<<26);
else break;
}
:param int index:
:param int max_states:
:param dict[int,AllophoneState] allophones:
:rtype: AllophoneState
"""
emission = index
state = 0
while state < max_states:
if emission >= (1 << 26):
emission -= (1 << 26)
state += 1
else:
break
a = allophones[emission].copy()
a.state = state
return a
def __hash__(self):
return hash(tuple([getattr(self, a) for a in self._attrs]))
def __eq__(self, other):
for a in self._attrs:
if getattr(self, a) != getattr(other, a):
return False
return True
def __ne__(self, other):
return not self == other
class Lexicon:
"""
Lexicon. Map of words to phoneme sequences (can have multiple pronunciations).
"""
def __init__(self, filename):
"""
:param str filename:
"""
print("Loading lexicon", filename, file=log.v4)
lex_file = open(filename, 'rb')
if filename.endswith(".gz"):
lex_file = gzip.GzipFile(fileobj=lex_file)
self.phoneme_list = [] # type: typing.List[str]
self.phonemes = {} # type: typing.Dict[str,typing.Dict[str]] # phone -> {index, symbol, variation}
self.lemmas = {} # type: typing.Dict[str,typing.Dict[str]] # orth -> {orth, phons}
context = iter(ElementTree.iterparse(lex_file, events=('start', 'end')))
_, root = next(context) # get root element
tree = [root]
for event, elem in context:
if event == "start":
tree += [elem]
elif event == "end":
assert tree[-1] is elem
tree = tree[:-1]
if elem.tag == "phoneme":
symbol = elem.find("symbol").text.strip() # should be unicode
assert isinstance(symbol, (str, unicode))
if elem.find("variation") is not None:
variation = elem.find("variation").text.strip()
else:
variation = "context" # default
assert symbol not in self.phonemes
assert variation in ["context", "none"]
self.phoneme_list.append(symbol)
self.phonemes[symbol] = {"index": len(self.phonemes), "symbol": symbol, "variation": variation}
root.clear() # free memory
elif elem.tag == "phoneme-inventory":
print("Finished phoneme inventory, %i phonemes" % len(self.phonemes), file=log.v4)
root.clear() # free memory
elif elem.tag == "lemma":
for orth_elem in elem.findall("orth"):
orth = (orth_elem.text or "").strip()
phons = [{"phon": e.text.strip(), "score": float(e.attrib.get("score", 0))} for e in elem.findall("phon")]
assert orth not in self.lemmas
self.lemmas[orth] = {"orth": orth, "phons": phons}
root.clear() # free memory
print("Finished whole lexicon, %i lemmas" % len(self.lemmas), file=log.v4)
class StateTying:
"""
Clustering of (allophone) states into classes.
"""
def __init__(self, state_tying_file):
"""
:param str state_tying_file:
"""
self.allo_map = {} # allophone-state-str -> class-idx
self.class_map = {} # class-idx -> set(allophone-state-str)
ls = open(state_tying_file).read().splitlines()
for l in ls:
allo_str, class_idx_str = l.split()
class_idx = int(class_idx_str)
assert allo_str not in self.allo_map
self.allo_map[allo_str] = class_idx
self.class_map.setdefault(class_idx, set()).add(allo_str)
min_class_idx = min(self.class_map.keys())
max_class_idx = max(self.class_map.keys())
assert min_class_idx == 0
assert max_class_idx == len(self.class_map) - 1, "some classes are not represented"
self.num_classes = len(self.class_map)
class PhoneSeqGenerator:
"""
Generates phone sequences.
"""
def __init__(self, lexicon_file,
allo_num_states=3, allo_context_len=1,
state_tying_file=None,
add_silence_beginning=0.1, add_silence_between_words=0.1, add_silence_end=0.1,
repetition=0.9, silence_repetition=0.95):
"""
:param str lexicon_file: lexicon XML file
:param int allo_num_states: how much HMM states per allophone (all but silence)
:param int allo_context_len: how much context to store left and right. 1 -> triphone
:param str | None state_tying_file: for state-tying, if you want that
:param float add_silence_beginning: prob of adding silence at beginning
:param float add_silence_between_words: prob of adding silence between words
:param float add_silence_end: prob of adding silence at end
:param float repetition: prob of repeating an allophone
:param float silence_repetition: prob of repeating the silence allophone
"""
self.lexicon = Lexicon(lexicon_file)
self.phonemes = sorted(self.lexicon.phonemes.keys(), key=lambda s: self.lexicon.phonemes[s]["index"])
self.rnd = Random(0)
self.allo_num_states = allo_num_states
self.allo_context_len = allo_context_len
self.add_silence_beginning = add_silence_beginning
self.add_silence_between_words = add_silence_between_words
self.add_silence_end = add_silence_end
self.repetition = repetition
self.silence_repetition = silence_repetition
self.si_lemma = self.lexicon.lemmas["[SILENCE]"]
self.si_phone = self.si_lemma["phons"][0]["phon"]
if state_tying_file:
self.state_tying = StateTying(state_tying_file)
else:
self.state_tying = None
def random_seed(self, seed):
"""
:param int seed:
"""
self.rnd.seed(seed)
def get_class_labels(self):
"""
:rtype: list[str]
"""
if self.state_tying:
# State tying labels. Represented by some allophone state str.
return ["|".join(sorted(self.state_tying.class_map[i])) for i in range(self.state_tying.num_classes)]
else:
# The phonemes are the labels.
return self.phonemes
def seq_to_class_idxs(self, phones, dtype=None):
"""
:param list[AllophoneState] phones: list of allophone states
:param str dtype: eg "int32"
:rtype: numpy.ndarray
:returns 1D numpy array with the indices
"""
if dtype is None:
dtype = "int32"
if self.state_tying:
# State tying indices.
return numpy.array([self.state_tying.allo_map[a.format()] for a in phones], dtype=dtype)
else:
# Phoneme indices. This must be consistent with get_class_labels.
# It should not happen that we don't have some phoneme. The lexicon should not be inconsistent.
return numpy.array([self.lexicon.phonemes[p.id]["index"] for p in phones], dtype=dtype)
def _iter_orth(self, orth):
"""
:param str orth:
:rtype: typing.Iterator[typing.Dict[str]]
"""
if self.rnd.random() < self.add_silence_beginning:
yield self.si_lemma
symbols = list(orth.split())
i = 0
while i < len(symbols):
symbol = symbols[i]
try:
lemma = self.lexicon.lemmas[symbol]
except KeyError:
if "/" in symbol:
symbols[i:i+1] = symbol.split("/")
continue
if "-" in symbol:
symbols[i:i+1] = symbol.split("-")
continue
raise
i += 1
yield lemma
if i < len(symbols):
if self.rnd.random() < self.add_silence_between_words:
yield self.si_lemma
if self.rnd.random() < self.add_silence_end:
yield self.si_lemma
def orth_to_phones(self, orth):
"""
:param str orth:
:rtype: str
"""
phones = []
for lemma in self._iter_orth(orth):
phon = self.rnd.choice(lemma["phons"])
phones += [phon["phon"]]
return " ".join(phones)
# noinspection PyMethodMayBeStatic
def _phones_to_allos(self, phones):
for p in phones:
a = AllophoneState()
a.id = p
yield a
def _random_allo_silence(self, phone=None):
if phone is None:
phone = self.si_phone
while True:
a = AllophoneState()
a.id = phone
a.mark_initial()
a.mark_final()
a.state = 0 # silence only has one state
yield a
if self.rnd.random() >= self.silence_repetition:
break
def _allos_add_states(self, allos):
for _a in allos:
if _a.id == self.si_phone:
for a in self._random_allo_silence(_a.id):
yield a
else: # non-silence
for state in range(self.allo_num_states):
while True:
a = AllophoneState()
a.id = _a.id
a.context_history = _a.context_history
a.context_future = _a.context_future
a.boundary = _a.boundary
a.state = state
yield a
if self.rnd.random() >= self.repetition:
break
def _allos_set_context(self, allos):
"""
:param list[AllophoneState] allos:
"""
if self.allo_context_len == 0:
return
ctx = []
for a in allos:
if self.lexicon.phonemes[a.id]["variation"] == "context":
a.context_history = tuple(ctx)
ctx += [a.id]
ctx = ctx[-self.allo_context_len:]
else:
ctx = []
ctx = []
for a in reversed(allos):
if self.lexicon.phonemes[a.id]["variation"] == "context":
a.context_future = tuple(reversed(ctx))
ctx += [a.id]
ctx = ctx[-self.allo_context_len:]
else:
ctx = []
def generate_seq(self, orth):
"""
:param str orth: orthography as a str. orth.split() should give words in the lexicon
:rtype: list[AllophoneState]
:returns allophone state list. those will have repetitions etc
"""
allos = [] # type: typing.List[AllophoneState]
for lemma in self._iter_orth(orth):
phon = self.rnd.choice(lemma["phons"])
l_allos = list(self._phones_to_allos(phon["phon"].split()))
l_allos[0].mark_initial()
l_allos[-1].mark_final()
allos += l_allos
self._allos_set_context(allos)
allos = list(self._allos_add_states(allos))
return allos
def _random_phone_seq(self, prob_add=0.8):
while True:
yield self.rnd.choice(self.phonemes)
if self.rnd.random() >= prob_add:
break
def _random_allo_seq(self, prob_word_add=0.8):
allos = []
while True:
phones = self._random_phone_seq()
w_allos = list(self._phones_to_allos(phones))