-
Notifications
You must be signed in to change notification settings - Fork 37
/
text_processor.py
1762 lines (1445 loc) · 62.4 KB
/
text_processor.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 python3
"""Tokenizes, verbalizes, and phonemizes text and SSML"""
import functools
import logging
import re
import typing
import xml.etree.ElementTree as etree
from decimal import Decimal
from pathlib import Path
from xml.sax import saxutils
import babel
import babel.numbers
import dateparser
import networkx as nx
from gruut_ipa import IPA, Pronunciation
from num2words import num2words
from gruut.const import (
DATA_PROP,
PHONEMES_TYPE,
REGEX_PATTERN,
BreakNode,
BreakType,
BreakWordNode,
EndElement,
GraphType,
IgnoreNode,
InterpretAs,
InterpretAsFormat,
Node,
ParagraphNode,
PunctuationWordNode,
Sentence,
SentenceNode,
SpeakNode,
TextProcessorSettings,
Word,
WordNode,
WordRole,
)
from gruut.lang import get_settings
from gruut.utils import (
attrib_no_namespace,
leaves,
pipeline_split,
pipeline_transform,
resolve_lang,
tag_no_namespace,
text_and_elements,
)
# -----------------------------------------------------------------------------
_LOGGER = logging.getLogger("gruut.text_processor")
# -----------------------------------------------------------------------------
class TextProcessor:
"""Tokenizes, verbalizes, and phonemizes text and SSML"""
def __init__(
self,
default_lang: str = "en_US",
model_prefix: str = "",
lang_dirs: typing.Optional[typing.Dict[str, typing.Union[str, Path]]] = None,
search_dirs: typing.Optional[typing.Iterable[typing.Union[str, Path]]] = None,
settings: typing.Optional[
typing.MutableMapping[str, TextProcessorSettings]
] = None,
**kwargs,
):
self.default_lang = default_lang
self.default_settings_kwargs = kwargs
self.model_prefix = model_prefix
self.search_dirs = search_dirs
if lang_dirs is None:
lang_dirs = {}
# Convert to Paths
self.lang_dirs = {
dir_lang: Path(dir_path) for dir_lang, dir_path in lang_dirs.items()
}
if settings is None:
settings = {}
self.settings = settings
def sentences(
self,
graph: GraphType,
root: Node,
major_breaks: bool = True,
minor_breaks: bool = True,
punctuations: bool = True,
explicit_lang: bool = True,
phonemes: bool = True,
break_phonemes: bool = True,
pos: bool = True,
) -> typing.Iterable[Sentence]:
"""Processes text and returns each sentence"""
def get_lang(lang: str) -> str:
if explicit_lang or (lang != self.default_lang):
return lang
# Implicit default language
return ""
def make_sentence(
node: Node, words: typing.Sequence[Word], sent_idx: int
) -> Sentence:
settings = self.get_settings(node.lang)
text_with_ws = "".join(w.text_with_ws for w in words)
text = settings.normalize_whitespace(text_with_ws)
sent_voice = ""
# Get voice used across all words
for word in words:
if word.voice:
if sent_voice and (sent_voice != word.voice):
# Multiple voices
sent_voice = ""
break
sent_voice = word.voice
if sent_voice:
# Set voice on all words
for word in words:
word.voice = sent_voice
return Sentence(
idx=sent_idx,
text=text,
text_with_ws=text_with_ws,
lang=get_lang(node.lang),
voice=sent_voice,
words=words,
)
sent_idx: int = 0
word_idx: int = 0
words: typing.List[Word] = []
last_sentence_node: typing.Optional[Node] = None
for dfs_node in nx.dfs_preorder_nodes(graph, root.node):
node = graph.nodes[dfs_node][DATA_PROP]
if isinstance(node, SentenceNode):
if words and (last_sentence_node is not None):
yield make_sentence(last_sentence_node, words, sent_idx)
sent_idx += 1
word_idx = 0
words = []
last_sentence_node = node
elif graph.out_degree(dfs_node) == 0:
if isinstance(node, WordNode):
word = typing.cast(WordNode, node)
words.append(
Word(
idx=word_idx,
sent_idx=sent_idx,
text=word.text,
text_with_ws=word.text_with_ws,
phonemes=word.phonemes if phonemes else None,
pos=word.pos if pos else None,
lang=get_lang(node.lang),
voice=node.voice,
)
)
word_idx += 1
elif isinstance(node, BreakWordNode):
break_word = typing.cast(BreakWordNode, node)
is_minor_break = break_word.break_type == BreakType.MINOR
is_major_break = break_word.break_type == BreakType.MAJOR
if (minor_breaks and is_minor_break) or (
major_breaks and is_major_break
):
words.append(
Word(
idx=word_idx,
sent_idx=sent_idx,
text=break_word.text,
text_with_ws=break_word.text_with_ws,
phonemes=self._phonemes_for_break(
break_word.break_type, lang=break_word.lang
)
if phonemes and break_phonemes
else None,
is_minor_break=is_minor_break,
is_major_break=is_major_break,
lang=get_lang(node.lang),
)
)
word_idx += 1
elif punctuations and isinstance(node, PunctuationWordNode):
punct_word = typing.cast(PunctuationWordNode, node)
words.append(
Word(
idx=word_idx,
sent_idx=sent_idx,
text=punct_word.text,
text_with_ws=punct_word.text_with_ws,
is_punctuation=True,
lang=get_lang(punct_word.lang),
)
)
word_idx += 1
if words and (last_sentence_node is not None):
yield make_sentence(last_sentence_node, words, sent_idx)
def words(self, graph: GraphType, root: Node, **kwargs) -> typing.Iterable[Word]:
"""Processes text and returns each word"""
for sent in self.sentences(graph, root, **kwargs):
for word in sent:
yield word
def get_settings(self, lang: typing.Optional[str] = None) -> TextProcessorSettings:
"""Gets or creates settings for a language"""
lang = lang or self.default_lang
lang_settings = self.settings.get(lang)
if lang_settings is not None:
return lang_settings
# Try again with resolved language
resolved_lang = resolve_lang(lang)
lang_settings = self.settings.get(resolved_lang)
if lang_settings is not None:
# Patch for the future
self.settings[lang] = self.settings[resolved_lang]
return lang_settings
_LOGGER.debug(
"No settings for language %s (%s). Creating default settings.",
lang,
resolved_lang,
)
# Create default settings for language
lang_dir = self.lang_dirs.get(lang)
lang_settings = get_settings(
lang,
lang_dir=lang_dir,
model_prefix=self.model_prefix,
search_dirs=self.search_dirs,
**self.default_settings_kwargs,
)
self.settings[lang] = lang_settings
self.settings[resolved_lang] = lang_settings
return lang_settings
# -------------------------------------------------------------------------
# Processing
# -------------------------------------------------------------------------
def __call__(self, *args, **kwargs):
"""Processes text or SSML"""
return self.process(*args, **kwargs)
def process(
self,
text: str,
lang: typing.Optional[str] = None,
ssml: bool = False,
pos: bool = True,
phonemize: bool = True,
post_process: bool = True,
add_speak_tag: bool = True,
detect_numbers: bool = True,
detect_currency: bool = True,
detect_dates: bool = True,
verbalize_numbers: bool = True,
verbalize_currency: bool = True,
verbalize_dates: bool = True,
) -> typing.Tuple[GraphType, Node]:
"""
Processes text or SSML
Args:
text: input text or SSML (ssml=True)
lang: default language of input text
ssml: True if input text is SSML
pos: False if part of speech tagging should be disabled
phonemize: False if phonemization should be disabled
post_process: False if sentence/graph post-processing should be disabled
add_speak_tag: False if <speak> should not automatically be added to input text
Returns:
graph, root: text graph and root node
"""
if not ssml:
# Not XML
text = saxutils.escape(text)
if add_speak_tag and (not text.lstrip().startswith("<")):
# Wrap in <speak> tag
text = f"<speak>{text}</speak>"
root_element = etree.fromstring(text)
graph = typing.cast(GraphType, nx.DiGraph())
# Parse XML
last_paragraph: typing.Optional[ParagraphNode] = None
last_sentence: typing.Optional[SentenceNode] = None
last_speak: typing.Optional[SpeakNode] = None
root: typing.Optional[SpeakNode] = None
# [voice]
voice_stack: typing.List[str] = []
# [(interpret_as, format)]
say_as_stack: typing.List[typing.Tuple[str, str]] = []
# [(tag, lang)]
lang_stack: typing.List[typing.Tuple[str, str]] = []
current_lang: str = lang or self.default_lang
# True if currently inside <w> or <token>
in_word: bool = False
# True if current word is the last one
is_last_word: bool = False
# Current word's role
word_role: typing.Optional[str] = None
# Alias from <sub>
last_alias: typing.Optional[str] = None
# Used to skip <metadata>
skip_elements: bool = False
# Phonemes to use for next word(s)
word_phonemes: typing.Optional[typing.List[typing.List[str]]] = None
# Create __init__ args for new Node
def scope_kwargs(target_class):
scope = {}
if voice_stack:
scope["voice"] = voice_stack[-1]
scope["lang"] = current_lang
if target_class is WordNode:
if say_as_stack:
scope["interpret_as"], scope["format"] = say_as_stack[-1]
if word_role is not None:
scope["role"] = word_role
return scope
# Process sub-elements and text chunks
for elem_or_text in text_and_elements(root_element):
if isinstance(elem_or_text, str):
if skip_elements:
# Inside <metadata>
continue
# Text chunk
text = typing.cast(str, elem_or_text)
if last_alias is not None:
# Iniside a <sub>
text = last_alias
if last_speak is None:
# Implicit <speak>
last_speak = SpeakNode(node=len(graph), implicit=True)
graph.add_node(last_speak.node, data=last_speak)
if root is None:
root = last_speak
assert last_speak is not None
if last_paragraph is None:
# Implicit <p>
p_node = ParagraphNode(
node=len(graph), implicit=True, **scope_kwargs(ParagraphNode)
)
graph.add_node(p_node.node, data=p_node)
graph.add_edge(last_speak.node, p_node.node)
last_paragraph = p_node
assert last_paragraph is not None
if last_sentence is None:
# Implicit <s>
s_node = SentenceNode(
node=len(graph), implicit=True, **scope_kwargs(SentenceNode)
)
graph.add_node(s_node.node, data=s_node)
graph.add_edge(last_paragraph.node, s_node.node)
last_sentence = s_node
assert last_sentence is not None
if in_word:
# No splitting
word_text = text
settings = self.get_settings(current_lang)
if (
settings.keep_whitespace
and (not is_last_word)
and (not word_text.endswith(settings.join_str))
):
word_text += settings.join_str
word_kwargs = scope_kwargs(WordNode)
if word_phonemes:
word_kwargs["phonemes"] = word_phonemes.pop()
word_text_norm = settings.normalize_whitespace(word_text)
word_node = WordNode(
node=len(graph),
text=word_text_norm,
text_with_ws=word_text,
in_lexicon=self._is_word_in_lexicon(word_text_norm, settings),
**word_kwargs,
)
graph.add_node(word_node.node, data=word_node)
graph.add_edge(last_sentence.node, word_node.node)
else:
# Split by whitespace
self._pipeline_tokenize(
graph,
last_sentence,
text,
word_phonemes=word_phonemes,
scope_kwargs=scope_kwargs(WordNode),
)
elif isinstance(elem_or_text, EndElement):
# End of an element (e.g., </s>)
end_elem = typing.cast(EndElement, elem_or_text)
end_tag = tag_no_namespace(end_elem.element.tag)
if end_tag == "voice":
if voice_stack:
voice_stack.pop()
elif end_tag == "say-as":
if say_as_stack:
say_as_stack.pop()
else:
if lang_stack and (lang_stack[-1][0] == end_tag):
lang_stack.pop()
if lang_stack:
current_lang = lang_stack[-1][1] # tag, lang
else:
current_lang = self.default_lang
if end_tag in {"w", "token"}:
# End of word
in_word = False
is_last_word = False
word_role = None
elif end_tag == "s":
# End of sentence
last_sentence = None
elif end_tag == "p":
# End of paragraph
last_paragraph = None
elif end_tag == "speak":
# End of speak
last_speak = root
elif end_tag == "s":
# End of sub
last_alias = None
elif end_tag in {"metadata", "meta"}:
# End of metadata
skip_elements = False
elif end_tag == "phoneme":
# End of phoneme
word_phonemes = None
else:
if skip_elements:
# Inside <metadata>
continue
# Start of an element (e.g., <p>)
elem, elem_metadata = elem_or_text
elem = typing.cast(etree.Element, elem)
# Optional metadata for the element
elem_metadata = typing.cast(
typing.Optional[typing.Dict[str, typing.Any]], elem_metadata
)
elem_tag = tag_no_namespace(elem.tag)
if elem_tag == "speak":
# Explicit <speak>
maybe_lang = attrib_no_namespace(elem, "lang")
if maybe_lang:
lang_stack.append((elem_tag, maybe_lang))
current_lang = maybe_lang
speak_node = SpeakNode(
node=len(graph), element=elem, **scope_kwargs(SpeakNode)
)
if root is None:
root = speak_node
graph.add_node(speak_node.node, data=root)
last_speak = root
elif elem_tag == "voice":
# Set voice scope
voice_name = attrib_no_namespace(elem, "name")
voice_stack.append(voice_name)
elif elem_tag == "p":
# Explicit paragraph
if last_speak is None:
# Implicit <speak>
last_speak = SpeakNode(node=len(graph), implicit=True)
graph.add_node(last_speak.node, data=last_speak)
if root is None:
root = last_speak
assert last_speak is not None
maybe_lang = attrib_no_namespace(elem, "lang")
if maybe_lang:
lang_stack.append((elem_tag, maybe_lang))
current_lang = maybe_lang
p_node = ParagraphNode(
node=len(graph), element=elem, **scope_kwargs(ParagraphNode)
)
graph.add_node(p_node.node, data=p_node)
graph.add_edge(last_speak.node, p_node.node)
last_paragraph = p_node
elif elem_tag == "s":
# Explicit sentence
if last_speak is None:
# Implicit <speak>
last_speak = SpeakNode(node=len(graph), implicit=True)
graph.add_node(last_speak.node, data=last_speak)
if root is None:
root = last_speak
assert last_speak is not None
if last_paragraph is None:
# Implicit paragraph
p_node = ParagraphNode(
node=len(graph), **scope_kwargs(ParagraphNode)
)
graph.add_node(p_node.node, data=p_node)
graph.add_edge(last_speak.node, p_node.node)
last_paragraph = p_node
maybe_lang = attrib_no_namespace(elem, "lang")
if maybe_lang:
lang_stack.append((elem_tag, maybe_lang))
current_lang = maybe_lang
s_node = SentenceNode(
node=len(graph), element=elem, **scope_kwargs(SentenceNode)
)
graph.add_node(s_node.node, data=s_node)
graph.add_edge(last_paragraph.node, s_node.node)
last_sentence = s_node
elif elem_tag in {"w", "token"}:
# Explicit word
in_word = True
is_last_word = (
elem_metadata.get("is_last", False) if elem_metadata else False
)
maybe_lang = attrib_no_namespace(elem, "lang")
if maybe_lang:
lang_stack.append((elem_tag, maybe_lang))
current_lang = maybe_lang
word_role = attrib_no_namespace(elem, "role")
elif elem_tag == "break":
# Break
last_target = last_sentence or last_paragraph or last_speak
assert last_target is not None
break_node = BreakNode(
node=len(graph),
element=elem,
time=attrib_no_namespace(elem, "time", ""),
)
graph.add_node(break_node.node, data=break_node)
graph.add_edge(last_target.node, break_node.node)
elif elem_tag == "say-as":
say_as_stack.append(
(
attrib_no_namespace(elem, "interpret-as", ""),
attrib_no_namespace(elem, "format", ""),
)
)
elif elem_tag == "sub":
# Sub
last_alias = attrib_no_namespace(elem, "alias", "")
elif elem_tag in {"metadata", "meta"}:
# Metadata
skip_elements = True
elif elem_tag == "phoneme":
# Phonemes
word_phonemes_strs = attrib_no_namespace(elem, "ph", "").split()
word_phonemes_alphabet = (
attrib_no_namespace(elem, "alphabet", "").strip().lower()
)
if word_phonemes_strs:
if word_phonemes_alphabet == "ipa":
# Split IPA intelligently (grouping elongation, stress, etc.)
word_phonemes = [
[p.text for p in Pronunciation.from_string(phoneme_str)]
for phoneme_str in word_phonemes_strs
]
else:
# Assume graphemes = phonemes
word_phonemes = [
list(phoneme_str) for phoneme_str in word_phonemes_strs
]
else:
word_phonemes = None
elif elem_tag == "lang":
# Set language
maybe_lang = attrib_no_namespace(elem, "lang", "")
if maybe_lang:
lang_stack.append((elem_tag, maybe_lang))
current_lang = maybe_lang
assert root is not None
# Do replacements before minor/major breaks
pipeline_split(self._split_replacements, graph, root)
# Split punctuations 1/2 (quotes, etc.) before breaks
pipeline_split(self._split_punctuations, graph, root)
# Split on minor breaks (commas, etc.)
pipeline_split(self._split_minor_breaks, graph, root)
# Expand abbrevations before major breaks
pipeline_split(self._split_abbreviations, graph, root)
# Break apart initialisms 1/2 (e.g., TTS or T.T.S.) before major breaks
split_initialism = functools.partial(
self._split_initialism, phonemize=phonemize
)
pipeline_split(split_initialism, graph, root)
# Split on major breaks (periods, etc.)
pipeline_split(self._split_major_breaks, graph, root)
# Split punctuations 2/2 (quotes, etc.) after breaks
pipeline_split(self._split_punctuations, graph, root)
# Break apart initialisms 2/2 (e.g., TTS. or T.T.S..) after major breaks
pipeline_split(split_initialism, graph, root)
# Break apart sentences using BreakWordNodes
self._break_sentences(graph, root)
# spell-out (e.g., abc -> a b c) before number expansion
pipeline_split(self._split_spell_out, graph, root)
# Transform text into known classes
if detect_numbers:
pipeline_transform(self._transform_number, graph, root)
if detect_currency:
pipeline_transform(self._transform_currency, graph, root)
if detect_dates:
pipeline_transform(self._transform_date, graph, root)
# Verbalize known classes
if verbalize_numbers:
pipeline_transform(self._verbalize_number, graph, root)
if verbalize_currency:
pipeline_transform(self._verbalize_currency, graph, root)
if verbalize_dates:
pipeline_transform(self._verbalize_date, graph, root)
if verbalize_numbers or verbalize_currency or verbalize_dates:
# Final split on minor breaks since numbers/dates can have commas, etc.
pipeline_split(self._split_minor_breaks, graph, root)
# Break apart words
pipeline_split(self._break_words, graph, root)
# Ignore non-words
pipeline_split(self._split_ignore_non_words, graph, root)
# Gather words from leaves of the tree, group by sentence
def process_sentence(words: typing.List[WordNode]):
if pos:
pos_settings = self.get_settings(node.lang)
if pos_settings.get_parts_of_speech is not None:
pos_tags = pos_settings.get_parts_of_speech(
[word.text for word in words]
)
for word, pos_tag in zip(words, pos_tags):
word.pos = pos_tag
if not word.role:
word.role = f"gruut:{pos_tag}"
if phonemize:
# Add phonemes to word
for word in words:
if word.phonemes:
# Word already has phonemes
continue
phonemize_settings = self.get_settings(word.lang)
if phonemize_settings.lookup_phonemes is not None:
word.phonemes = phonemize_settings.lookup_phonemes(
word.text, word.role
)
if (not word.phonemes) and (
phonemize_settings.guess_phonemes is not None
):
word.phonemes = phonemize_settings.guess_phonemes(
word.text, word.role
)
# Process tree leaves
sentence_words: typing.List[WordNode] = []
for dfs_node in nx.dfs_preorder_nodes(graph, root.node):
node = graph.nodes[dfs_node][DATA_PROP]
if isinstance(node, SentenceNode):
if sentence_words:
process_sentence(sentence_words)
sentence_words = []
elif graph.out_degree(dfs_node) == 0:
if isinstance(node, WordNode):
word_node = typing.cast(WordNode, node)
sentence_words.append(word_node)
if sentence_words:
# Final sentence
process_sentence(sentence_words)
sentence_words = []
if post_process:
# Post-process sentences
for dfs_node in nx.dfs_preorder_nodes(graph, root.node):
node = graph.nodes[dfs_node][DATA_PROP]
if isinstance(node, SentenceNode):
sent_node = typing.cast(SentenceNode, node)
sent_settings = self.get_settings(sent_node.lang)
if sent_settings.post_process_sentence is not None:
sent_settings.post_process_sentence(
graph, sent_node, sent_settings
)
# Post process entire graph
self.post_process_graph(graph, root)
return graph, root
def post_process_graph(self, graph: GraphType, root: Node):
"""User-defined post-processing of entire graph"""
pass
# -------------------------------------------------------------------------
# Pipeline (custom)
# -------------------------------------------------------------------------
def _break_sentences(self, graph: GraphType, root: Node):
"""Break sentences apart at BreakWordNode(break_type="major") nodes."""
# This involves:
# 1. Identifying where in the edge list of sentence the break occurs
# 2. Creating a new sentence next to the existing one in the parent paragraph
# 3. Moving everything after the break into the new sentence
for leaf_node in list(leaves(graph, root)):
if not isinstance(leaf_node, BreakWordNode):
# Not a break
continue
break_word_node = typing.cast(BreakWordNode, leaf_node)
if break_word_node.break_type != BreakType.MAJOR:
# Not a major break
continue
# Get the path from the break up to the nearest sentence
parent_node: int = next(iter(graph.predecessors(break_word_node.node)))
parent: Node = graph.nodes[parent_node][DATA_PROP]
s_path: typing.List[Node] = [parent]
while not isinstance(parent, SentenceNode):
parent_node = next(iter(graph.predecessors(parent_node)))
parent = graph.nodes[parent_node][DATA_PROP]
s_path.append(parent)
# Should at least be [WordNode, SentenceNode]
assert len(s_path) >= 2
s_node = s_path[-1]
assert isinstance(s_node, SentenceNode)
if not s_node.implicit:
# Don't break apart explicit sentences
continue
# Probably a WordNode
below_s_node = s_path[-2]
# Edges after the break will need to be moved to the new sentence
s_edges = list(graph.out_edges(s_node.node))
break_edge_idx = s_edges.index((s_node.node, below_s_node.node))
edges_to_move = s_edges[break_edge_idx + 1 :]
if not edges_to_move:
# Final sentence, nothing to move
continue
# Locate parent paragraph so we can create a new sentence
p_node = self._find_parent(graph, s_node, ParagraphNode)
assert p_node is not None
# Find the index of the edge between the paragraph and the current sentence
p_s_edge = (p_node.node, s_node.node)
p_edges = list(graph.out_edges(p_node.node))
s_edge_idx = p_edges.index(p_s_edge)
# Remove existing edges from the paragraph
graph.remove_edges_from(p_edges)
# Create a sentence and add an edge to it right after the current sentence
new_s_node = SentenceNode(node=len(graph), implicit=True)
graph.add_node(new_s_node.node, data=new_s_node)
p_edges.insert(s_edge_idx + 1, (p_node.node, new_s_node.node))
# Insert paragraph edges with new sentence
graph.add_edges_from(p_edges)
# Move edges from current sentence to new sentence
graph.remove_edges_from(edges_to_move)
graph.add_edges_from([(new_s_node.node, v) for (u, v) in edges_to_move])
def _break_words(self, graph: GraphType, node: Node):
"""Break apart words according to work breaks pattern"""
if not isinstance(node, WordNode):
return
word = typing.cast(WordNode, node)
if word.interpret_as or word.in_lexicon or (not word.implicit):
# Don't interpret words that are spoken for or explicit words (<w>)
return
settings = self.get_settings(word.lang)
if settings.word_breaks_pattern is None:
# No pattern set for this language
return
parts = settings.word_breaks_pattern.split(word.text)
if len(parts) < 2:
# Didn't split
return
# Preserve whitespace
first_ws, last_ws = settings.get_whitespace(word.text_with_ws)
last_part_idx = len(parts) - 1
for part_idx, part_text in enumerate(parts):
part_text_norm = settings.normalize_whitespace(part_text)
if not part_text_norm:
continue
if settings.keep_whitespace:
if part_idx == 0:
part_text = first_ws + part_text
if part_idx == last_part_idx:
part_text += last_ws
else:
part_text += settings.join_str
yield WordNode, {
"text": part_text_norm,
"text_with_ws": part_text,
"implicit": True,
"lang": word.lang,
"in_lexicon": self._is_word_in_lexicon(part_text_norm, settings),
}
def _split_punctuations(self, graph: GraphType, node: Node):
if not isinstance(node, WordNode):
return
word = typing.cast(WordNode, node)
if word.interpret_as or word.in_lexicon:
# Don't interpret words that are spoken for
return
settings = self.get_settings(word.lang)
if (settings.begin_punctuations_pattern is None) and (
settings.end_punctuations_pattern is None
):
# No punctuation patterns
return
word_text = word.text
first_ws, last_ws = settings.get_whitespace(word.text_with_ws)
has_punctuation = False
# Punctuations at the beginning of the word
if settings.begin_punctuations_pattern is not None:
# Split into begin punctuation and rest of word
parts = list(
filter(
None,
settings.begin_punctuations_pattern.split(word_text, maxsplit=1),
)
)
first_word = True
while word_text and (len(parts) == 2):
punct_text, word_text = parts
if first_word:
# Preserve leadingwhitespace
punct_text = first_ws + punct_text
first_word = False
punct_text_norm = settings.normalize_whitespace(punct_text)
has_punctuation = True
yield PunctuationWordNode, {
"text": punct_text_norm,
"text_with_ws": punct_text,
"implicit": True,
"lang": word.lang,
}
parts = list(
filter(
None,
settings.begin_punctuations_pattern.split(
word_text, maxsplit=1
),
)
)
# Punctuations at the end of the word
end_punctuations: typing.List[str] = []
if settings.end_punctuations_pattern is not None:
# Split into rest of word and end punctuation
parts = list(
filter(
None, settings.end_punctuations_pattern.split(word_text, maxsplit=1)
)
)
while word_text and (len(parts) == 2):
word_text, punct_text = parts
has_punctuation = True
end_punctuations.append(punct_text)
parts = list(
filter(
None,
settings.end_punctuations_pattern.split(word_text, maxsplit=1),
)
)
if not has_punctuation:
# Leave word as-is
return
if settings.keep_whitespace and (not end_punctuations):
# Preserve trailing whitespace
word_text = word_text + last_ws
word_text_norm = settings.normalize_whitespace(word_text)
if word_text:
yield WordNode, {
"text": word_text_norm,
"text_with_ws": word_text,
"implicit": True,
"lang": word.lang,
"in_lexicon": self._is_word_in_lexicon(word_text_norm, settings),