-
Notifications
You must be signed in to change notification settings - Fork 21
/
addnlp.py
1612 lines (1341 loc) · 54.1 KB
/
addnlp.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
"""Add data from an NLP pipeline.
When you have used `tf.convert.tei` to convert a TEI data source into a TF dataset,
the situation with words and sentences is usually not satisfactory.
In most TEI sources, words and sentences are not explicitly marked up, and it is
really hard to build token detection and sentence boundary detection into the
conversion program.
There is a better way.
You can use this module to have tokens, sentences and entities detected by NLP pipelines
(currently only Spacy is supported).
The NLP output will then be transformed to nodes and attributes and inserted in
the TF dataset as a new version.
The original slots in the TF dataset (characters) will be discarded, because the
new tokens will be used as slots.
!!! caution "Complications"
It is possible that tokens cross element boundaries.
If we did not do anything about that, we would loose resolution, especially in the
case of inline formatting within tokens. We could not express that anymore.
That's why we split the tokens across element boundaries.
However, we then loose the correspondence between tokens and words.
To overcome that, we turn the tokens into two types:
* atomic tokens, by default type `t`
* full tokens, by default type `token`
**This is work in progress. Details of the workflow may change rather often!**
## Requirements
* The initial data set should be one that has characters as slots.
* The version of the initial data should end with the string `pre`, e.g.
`0.8pre`.
## Effect
* A new version of the data (whose label is the old version minus the `pre`)
will be produced:
* with new node types `sentence` and `token`;
* with `token` as slot type;
* with the old slot type removed;
* with the feature that contains the text of the slots removed;
* with other slot features translated to equally named features on `token`;
* with other node and edge features translated faithfully to the new situation.
## Homework
* The new data needs a slightly different TF app than the original version.
You can generate that with the program that created the TF from the TEI,
typically
python tfFromTei.py apptoken
# Usage
## Command-line
``` sh
tf-addnlp tasks params flags
```
## From Python
``` python
from tf.convert.addnlp import NLPipeline
from tf.app import use
ORG = "yourOrg"
REPO = "yourRepo"
Apre = use(f"{ORG}/{REPO}:clone", checkout="clone")
NLP = NLPipeline(**params, **flags)
NLP.loadApp(Apre)
NLP.task(**tasks, **flags)
```
For the tasks, parameters and flags, see
`TASKS`, `PARAMS`, `FLAGS` and expand the code.
The parameters have defaults that are exactly suited to corpora that have been
converted from TEI by `tf.convert.tei`.
## Examples
Exactly how you can call the methods of this module is demonstrated in the small
corpus of 14 letter by the Dutch artist Piet Mondriaan.
* [Mondriaan](https://nbviewer.org/github/annotation/mondriaan/blob/master/programs/convertExpress.ipynb).
"""
import sys
import re
# from copy import deepcopy
from ..capable import CheckImport
from .recorder import Recorder
from .helpers import CONVERSION_METHODS, CM_NLP
from ..advanced.app import loadApp
from ..tools.xmlschema import Analysis
from ..tools.myspacy import nlpOutput
from ..dataset import modify
from ..core.helpers import console
from ..core.files import initTree, dirMake
from ..core.timestamp import DEEP, TERSE
from ..core.command import readArgs
from ..lib import writeList, readList
HELP = "Add NLP-generated features to a TF dataset."
TASKS = dict(
plaintext="make a plain text for the NLP tools",
lingo="run the NLP tool on the plain text",
ingest="ingest the results of the NLP tool in the dataset",
all=None,
)
"""Possible tasks."""
PARAMS = dict(
lang=("Set up the NLP tool for this language", "en"),
slotFeature=(
"When generating text, use this feature to obtain text from slots",
"ch",
),
removeSlotFeatures=(
"Discardable slot features. Will not be translated to atomic token features",
"ch",
),
emptyFeature=("Feature to identify empty slots.", "empty"),
ignoreTypes=(
"Node types that will be ignored when generating the plain text.",
"word",
),
outOfFlow=(
"These node types will be put in separate text flows in the plain text.",
"note,orig,del",
),
tkType=("The node type for the atomic tokens.", "t"),
tokenType=("The node type for the full tokens.", "token"),
tokenFeatures=(
(
"The features in the token output by the NLP: "
"1: token content; 2: space after the token (if any), ..."
),
"str,after,pos,morph,lemma",
),
tokenNFeature=(
"The feature that will hold the sequence number of the token.",
"",
),
sentenceBarriers=("Elements that trigger a sentence boundary.", "div,p"),
sentenceSkipFlow=("The flows that are not fed to sentence detection.", "orig,del"),
sentenceType=("The node type for the sentences", "sentence"),
sentenceFeatures=("", ""),
sentenceNFeature=(
"The feature that will hold the sequence number of the sentence",
"nsent",
),
entityType=("The node type for the entities.", "ent"),
entityFeatures=(
(
"The features in the entity output by the NLP: "
"1: entity content; 2: entity kind, ..."
),
"estr,kind",
),
entityNFeature=(
"The feature that will hold the sequence number of the entity",
"",
),
)
"""Possible parameters."""
FLAGS = dict(
ner=("Whether to do named entity recognition during NLP", False, 2),
parser=("Whether to run the NLP parser", False, 2),
write=(
(
"whether to write the generated files "
"with plain text and node positions to disk"
),
False,
2,
),
verbose=("Produce less or more progress and reporting messages", -1, 3),
)
"""Possible flags."""
SENT_END = "Foo bar"
class NLPipeline(CheckImport):
def __init__(
self,
app=None,
lang=PARAMS["lang"][1],
slotFeature=PARAMS["slotFeature"][1],
removeSlotFeatures=PARAMS["removeSlotFeatures"][1],
emptyFeature=PARAMS["emptyFeature"][1],
ignoreTypes=PARAMS["ignoreTypes"][1],
outOfFlow=PARAMS["outOfFlow"][1],
tkType=PARAMS["tkType"][1],
tokenFeatures=PARAMS["tokenFeatures"][1],
tokenNFeature=PARAMS["tokenNFeature"][1],
tokenType=PARAMS["tokenType"][1],
sentenceBarriers=PARAMS["sentenceBarriers"][1],
sentenceSkipFlow=PARAMS["sentenceSkipFlow"][1],
sentenceType=PARAMS["sentenceType"][1],
sentenceFeatures=PARAMS["sentenceFeatures"][1],
sentenceNFeature=PARAMS["sentenceNFeature"][1],
entityType=PARAMS["entityType"][1],
entityFeatures=PARAMS["entityFeatures"][1],
entityNFeature=PARAMS["entityNFeature"][1],
ner=FLAGS["ner"][1],
parser=FLAGS["parser"][1],
verbose=FLAGS["verbose"][1],
write=FLAGS["write"][1],
):
"""Enrich a TF dataset with annotations generated by an NLP pipeline.
Parameters
----------
lang: string, optional en
The language for which the NLP tool will be set up
app: object, None
A loaded TF app. If None, the TF App that is nearby in the file system
will be loaded.
We assume that the original data resides in the current
version, which has the string `pre` appended to it,
e.g. in version `1.3pre`.
We create a new version of the dataset, with the same number,
but without the `pre`.
slotFeature: string, optional ch
The feature on slots that provides the text of a slot to be included
in the generated text.
removeSlotFeatures: string
A tuple is distilled from comma-separated values.
The names of features defined on original slots that do not have to be
carried over to the new slots of type of the atomic tokens.
There should be at least one feature: the character content of the slot.
emptyFeature: string, optional "empty"
Name of feature that identifies the empty slots.
ignoreTypes: set, optional "word"
A set is distilled from comma-separated values.
Node types that will be ignored when generating the plain text.
outOfFlow: string, optional "note,orig,del"
A set is distilled from comma-separated values.
A set of node types whose content will be put in separate text flows at
the end of the document.
sentenceSkipFlow: string, optional "orig,del"
A set is distilled from comma-separated values.
The elements whose flows in the sentence stream should be ignored
tkType: string, optional t
The node type for the atomic tokens
tokenType: string, optional token
The node type for the full tokens
tokenFeatures: tuple, optional ("str", "after")
A tuple is distilled from comma-separated values.
The names of the features that the atomic token stream contains.
There must be at least two features:
the first one should give the token content, the second one the non-token
material until the next token.
The rest are additional features that the pipeline might supply.
tokenNFeature: string, optional None
If not None, the name of the atomic token feature that will hold the
sequence number of the atomic token in the data stream, starting at 1.
sentenceType: string, optional sentence
The node type for the sentences
sentenceFeatures: tuple, optional ()
A tuple is distilled from comma-separated values.
The names of the features that the sentence stream contains.
sentenceNFeature: string, optional nsent
If not None, the name of the sentence feature that will hold the
sequence number of the sentence in the data stream, starting at 1.
ner: boolean, optional False
Whether to perform named entity recognition during NLP processing.
parser: boolean, optional False
Whether to run the NLP parser.
entityType: string, optional ent
The node type for the full entities
entityFeatures: tuple, optional ("str", "kind")
A tuple is distilled from comma-separated values.
The names of the features that the entity stream contains.
There must be at least two features:
the first one should give the entity content, the second one the entity
kind (or label).
The rest are additional features that the pipeline might supply.
entityNFeature: string, optional None
If not None, the name of the entity feature that will hold the
sequence number of the entity in the data stream, starting at 1.
"""
super().__init__("lxml", "spacy")
if not self.importOK(hint=True):
return
def makeString(s):
return None if not s else s
def makeSet(s):
return set() if not s else set(s.split(","))
def makeTuple(s):
return tuple() if not s else tuple(s.split(","))
self.good = True
self.app = app
self.lang = makeString(lang)
self.slotFeature = makeString(slotFeature)
self.removeSlotFeatures = makeTuple(removeSlotFeatures)
self.emptyFeature = makeString(emptyFeature)
self.ignoreTypes = makeSet(ignoreTypes)
self.outOfFlow = makeSet(outOfFlow)
self.tkType = makeString(tkType)
self.tokenFeatures = makeTuple(tokenFeatures)
self.tokenNFeature = makeString(tokenNFeature)
self.tokenType = makeString(tokenType)
self.sentenceBarriers = makeSet(sentenceBarriers)
self.sentenceSkipFlow = makeSet(sentenceSkipFlow)
self.sentenceType = makeString(sentenceType)
self.sentenceFeatures = makeTuple(sentenceFeatures)
self.sentenceNFeature = makeString(sentenceNFeature)
self.entityType = makeString(entityType)
self.entityFeatures = makeTuple(entityFeatures)
self.entityNFeature = makeString(entityNFeature)
self.ner = ner
self.parser = parser
self.verbose = verbose
self.write = write
def loadApp(self, app=None, verbose=None):
"""Loads a given TF app or loads the TF app based on the working directory.
After loading, all slots where non-slot node boundaries occur are computed,
except for nodes of type word.
Parameters
----------
app: object, optional None
The handle to the original TF dataset, already loaded.
If not given, we load the TF app that is nearby in the file system.
verbose: integer, optional None
Produce more progress and reporting messages
If not passed, take the verbose member of this object.
"""
if not self.importOK():
return
ignoreTypes = self.ignoreTypes
if verbose is not None:
self.verbose = verbose
verbose = self.verbose
if app is None:
if self.app is None:
app = loadApp(silent=DEEP)
self.app = app
else:
app = self.app
else:
self.app = app
self.app = app
version = app.version
if verbose >= 0:
console(f"Input data has version {version}")
repoDir = app.repoLocation
txtDir = f"{repoDir}/_temp/txt/{version}"
dirMake(txtDir)
self.txtDir = txtDir
self.tokenFile = f"{txtDir}/tokens.tsv"
self.sentenceFile = f"{txtDir}/sentences.tsv"
self.entityFile = f"{txtDir}/entities.tsv"
self.textPath = f"{txtDir}/plain.txt"
if verbose >= 0:
console("Compute element boundaries")
api = app.api
F = api.F
E = api.E
firstSlots = set()
lastSlots = set()
for node, slots in E.oslots.items():
if F.otype.v(node) in ignoreTypes:
continue
firstSlots.add(slots[0])
lastSlots.add(slots[-1])
self.firstSlots = firstSlots
self.lastSlots = lastSlots
if verbose >= 0:
console(f"{len(firstSlots):>6} start positions")
console(f"{len(lastSlots):>6} end positions")
def getElementInfo(self, verbose=None):
"""Analyse the schema.
The XML schema has useful information about the XML elements that
occur in the source. Here we extract that information and make it
fast-accessible.
Parameters
----------
verbose: integer, optional None
Produce more progress and reporting messages
If not passed, take the verbose member of this object.
Returns
-------
dict
Keyed by element name (without namespaces), where the value
for each name is a tuple of booleans: whether the element is simple
or complex; whether the element allows mixed content or only pure content.
"""
if not self.importOK(hint=True):
return
if verbose is not None:
self.verbose = verbose
verbose = self.verbose
self.elementDefs = {}
self.mixedTypes = {}
A = Analysis(verbose=verbose)
baseSchema = A.getBaseSchema()["xsd"]
A.getElementInfo(baseSchema, [])
elementDefs = A.elementDefs
self.mixedTypes = {
x for (x, (typ, mixed)) in elementDefs[(baseSchema, None)].items() if mixed
}
def generatePlain(self):
"""Generates a plain text out of a data source.
The text is generated in such a way that out of flow elements are collected
and put at the end. Examples of such elements are notes.
Leaving them at their original positions will interfere with sentence detection.
We separate the flows clearly in the output, so that they are discernible
in the output of the NLP pipeline.
Afterwards, when we collect the tokens, we will notice which tokens
cross element boundaries and need to be split into atomic tokens.
Returns
-------
tuple
The result is a tuple consisting of
* *text*: the generated text
* *positions*: a list of nodes such that list item `i` contains
the original slot that corresponds to the character `i` in the
generated text (counting from zero).
"""
if not self.importOK(hint=True):
return (None, None)
slotFeature = self.slotFeature
emptyFeature = self.emptyFeature
ignoreTypes = self.ignoreTypes
outOfFlow = self.outOfFlow
sentenceBarriers = self.sentenceBarriers
verbose = self.verbose
write = self.write
app = self.app
info = app.info
indent = app.indent
api = app.api
F = api.F
Fs = api.Fs
N = api.N
T = api.T
sentenceBreakRe = re.compile(r"[.!?]")
info("Generating a plain text with positions ...", force=verbose >= 0)
self.getElementInfo()
mixedTypes = self.mixedTypes
flows = {elem: [] for elem in outOfFlow}
flows[""] = []
flowStack = [""]
nTypeStack = []
def finishSentence(flowContent):
nContent = len(flowContent)
lnw = None # last non white position
for i in range(nContent - 1, -1, -1):
item = flowContent[i]
if type(item) is not str or item.strip() == "":
continue
else:
lnw = i
break
if lnw is None:
return
# note that every slot appears in the sequence preceded by a neg int
# and followed by a pos int
# Material outside slots may be followed and preceded by other strings
# We have to make sure that what we add, falls outside any slot.
# We do that by inspecting the following item:
# if that is a positive int, we are in a slot so we have to insert material
# after that int
# If the following item is a string or a negative int,
# so we can insert right after the point where we are.
if not sentenceBreakRe.match(flowContent[lnw]):
offset = 1
if lnw < nContent - 1:
following = flowContent[lnw + 1]
if type(following) is int and following > 0:
offset = 2
flowContent.insert(lnw + offset, ".")
lnw += 1
if not any(ch == "\n" for ch in flowContent[lnw + 1 :]):
flowContent.append("\n")
emptySlots = 0
Femptyv = Fs(emptyFeature).v
Fchv = Fs(slotFeature).v
sectionTypes = T.sectionTypes
for n, kind in N.walk(events=True):
nType = F.otype.v(n)
if nType in ignoreTypes:
continue
isOutFlow = nType in outOfFlow
if kind is None: # slot type
if Femptyv(n):
emptySlots += 1
ch = "○"
else:
ch = Fchv(n)
flows[flowStack[-1]].extend([-n, ch, n])
elif kind: # end node
if isOutFlow:
flow = flowStack.pop()
else:
flow = flowStack[-1]
flowContent = flows[flow]
if flow:
finishSentence(flowContent)
else:
if nType == "teiHeader":
finishSentence(flowContent)
flowContent.append(f" \n xxx. \n{SENT_END}. \nEnd meta. \n\n")
elif nType in sectionTypes or nType in sentenceBarriers:
finishSentence(flowContent)
flowContent.append(
f" \n xxx. \n{SENT_END}. \nEnd {nType}. \n\n"
)
else:
if any(nTp == "teiHeader" for nTp in nTypeStack) and not any(
nTp in mixedTypes for nTp in nTypeStack[0:-1]
):
finishSentence(flowContent)
nTypeStack.pop()
else: # start node
nTypeStack.append(nType)
if isOutFlow:
flowStack.append(nType)
flow = flowStack[-1]
flowContent = flows[flow]
if isOutFlow:
flowContent.append(f" \n{SENT_END}. \nItem {flow}. \n")
else:
if nType == "teiHeader":
flowContent.append(f" \n{SENT_END}. \nBegin meta. \n\n")
elif nType in sectionTypes:
flowContent.append(f" \n{SENT_END}. \nBegin {nType}. \n\n")
else:
if any(nTp == "teiHeader" for nTp in nTypeStack) and not any(
nTp in mixedTypes for nTp in nTypeStack[0:-1]
):
flowContent.append(f"{nType}. ")
indent(level=True)
info(f"Found {emptySlots} empty slots", tm=False, force=verbose >= 0)
rec = Recorder(app.api)
for flow in sorted(flows):
items = flows[flow]
if len(items) == 0:
continue
rec.add(f" \n{SENT_END}. \nBegin flow {flow if flow else 'main'}. \n\n")
for item in items:
if type(item) is int:
if item < 0:
rec.start(-item)
else:
rec.end(item)
else:
rec.add(item)
rec.add(
f" \n xxx. \n{SENT_END}. \nEnd flow {flow if flow else 'main'}. \n\n"
)
info(
(
f"recorded flow {flow if flow else 'main':<10} "
f"with {len(items):>6} items"
),
tm=False,
force=verbose >= 0,
)
indent(level=False)
if write:
textPath = self.textPath
rec.write(textPath)
info(
f"Done. Generated text and positions written to {textPath}",
force=verbose >= 0,
)
else:
info("Done", force=verbose >= 0)
return (rec.text(), rec.positions(simple=True))
def lingo(self, *args, **kwargs):
if not self.importOK():
return ()
return nlpOutput(*args, **kwargs)
def ingest(
self,
isTk,
isEnt,
positions,
stream,
tp,
features,
nFeature=None,
skipBlanks=False,
skipFlows=None,
emptyFeature=None,
):
"""Ingests a stream of NLP data and transforms it into nodes and features.
The data is a stream of values associated with a spans of text.
For each span a node will be created of the given type, and a feature
of the given name will assign a value to that span.
The value assigned is by default the value that is present in the data stream,
but it is possible to specify a method to change the value.
!!! caution
The plain text on which the NLP pipeline has run may not correspond
exactly with the text as defined by the corpus.
When the plain text was generated, some extra convenience material
may have been inserted.
Items in the stream that refer to these pieces of text will be ignored.
When items refer partly to proper corpus text and partly to
convenience text, they will be narrowed down to the proper text.
!!! caution
The plain text may exhibit another order of material than the proper corpus
text. For example, notes may have been collected and moved out of the
main text flow to the end of the text.
That means that if an item specifies a span in the plain text, it may
not refer to a single span in the proper text, but to various spans.
We take care to map all spans in the generated plain text back to *sets*
of slots in the proper text.
Parameters
----------
isTk: boolean
Whether the data specifies (atomic) tokens or something else.
Tokens are special because they are intended to become the new slot type.
isEnt: boolean
Whether the data specifies entities or something else.
Entities are special because they come with a text string which may contain
generated text that must be stripped.
positions: list
which slot node corresponds to which position in the plain text.
stream: list of tuple
The tuples should consist of
* `start`: a start number (character position in the plain text,
starting at `0`)
* `end`: an end number (character position in the plain text plus one)
* `values`: values for feature assignment
tp: string
The type of the nodes that will be generated.
features: tuple
The names of the features that will be generated.
nFeature: string, optional None
If not None, the name of a feature that will hold the sequence number of
the element in the data stream, starting at 1.
emptyFeature: string, optional empty
Name of feature that identifies the empty slots.
skipBlanks: boolean, optional False
If True, rows whose text component is only white-space will be skipped.
skipFlows: set
set of elements whose resulting data in the stream should be ignored
Returns
-------
tuple
We deliver the following pieces of information in a tuple:
* the last node
* the mapping of the new nodes to the slots they occupy;
* the data of the new features.
However, when we deliver the token results, they come in two such tuples:
one for the atomic tokens and one for the full tokens.
"""
if not self.importOK():
return (
(
(None, None, None),
(None, None, None),
)
if isTk
else (None, None, None)
)
slotFeature = self.slotFeature
firstSlots = self.firstSlots
lastSlots = self.lastSlots
verbose = self.verbose
app = self.app
info = app.info
indent = app.indent
F = app.api.F
Fs = app.api.Fs
Fotypev = F.otype.v
slotType = F.otype.slotType
Fslotv = Fs(slotFeature).v
if emptyFeature is not None:
Femptyv = Fs(emptyFeature).v
Femptys = Fs(emptyFeature).s
doN = nFeature is not None
slotLinks = {}
if isTk:
featuresData = {feat: {} for feat in features[0:2]}
tokenFeaturesData = {feat: {} for feat in features}
else:
featuresData = {feat: {} for feat in features}
if nFeature is not None:
featuresData[nFeature] = {}
if emptyFeature is not None:
featuresData[emptyFeature] = {}
if isTk:
featTk = featuresData[features[0]]
featTkAfter = featuresData[features[1]]
featToken = tokenFeaturesData[features[0]]
featTokenAfter = tokenFeaturesData[features[1]]
tokenLinks = {}
if isEnt:
featEnt = featuresData[features[0]]
whiteMultipleRe = re.compile(r"^[ \n]{2,}$", re.S)
node = 0
token = 0
itemsOutside = []
itemsEmpty = []
info(
f"generating {tp}-nodes with features {', '.join(featuresData)}",
force=verbose >= 0,
)
indent(level=True)
numRe = re.compile(r"[0-9]")
def addTk(last, sAfter):
"""Add an atomic token node to the dataset under construction.
Parameters
----------
last: boolean
Whether this is the last atomic token in the full token.
In that case, the *after* attribute on the token data must be added
as a feature on this atomic token.
"""
nonlocal node
nonlocal curTkSlots
nonlocal curTkValue
node += 1
slotLinks[node] = curTkSlots
featTk[node] = curTkValue
# for (feat, val) in zip(features[2:], vals[2:]):
# featuresData[feat][node] = val
# if doN:
# featuresData[nFeature][node] = node
if last:
after = vals[1] if sAfter is not None else ""
featTkAfter[node] = after
curTkSlots = []
curTkValue = ""
def addToken(last, sAfter):
nonlocal token
nonlocal curTokenSlots
nonlocal curTokenValue
token += 1
tokenLinks[token] = curTokenSlots
featToken[token] = curTokenValue
for feat, val in zip(features[2:], vals[2:]):
tokenFeaturesData[feat][token] = val
if doN:
tokenFeaturesData[nFeature][token] = token
if last:
after = vals[1] if sAfter is not None else ""
featTokenAfter[token] = after
curTokenSlots = []
curTokenValue = ""
def addSlot(slot):
nonlocal node
node += 1
slotLinks[node] = [slot]
featTk[node] = Fslotv(slot)
if Femptyv(slot):
featuresData[emptyFeature][node] = 1
def addEnt(myText):
nonlocal node
if numRe.search(myText):
return
node += 1
slotLinks[node] = mySlots
featEnt[node] = myText
for feat, val in zip(features[1:], vals[1:]):
featuresData[feat][node] = val.replace("\n", " ").strip()
if doN:
featuresData[nFeature][node] = node
def addItem():
nonlocal node
node += 1
slotLinks[node] = mySlots
for feat, val in zip(features, vals):
featuresData[feat][node] = val
if doN:
featuresData[nFeature][node] = node
# First we identify all the empty slots, provided we are doing tokens
if isTk:
emptySlots = (
{s for s in Femptys(1) if Fotypev(s) == slotType}
if emptyFeature
else set()
)
emptyWithinTk = 0
spaceWithinTk = 0
boundaryWithinTk = 0
# for slot in sorted(emptySlots):
# addSlot(slot)
# now the data from the NLP pipeline
flowBeginRe = re.compile(rf" \n{SENT_END}\. \nBegin flow (\w+)\. ")
flowEndRe = re.compile(rf" \n xxx. \n{SENT_END}\. \nEnd flow (\w+)\. ")
skipping = False
flow = None
for i, (b, e, *vals) in enumerate(stream):
if skipFlows is not None:
text = vals[0]
if skipping:
match = flowEndRe.match(text)
if match:
flow = match.group(1)
skipping = False
flow = None
continue
else:
match = flowBeginRe.match(text)
if match:
flow = match.group(1)
skipping = flow in skipFlows
continue
if skipping:
continue
mySlots = set()
for j in range(b, e):
s = positions[j]
if s is not None:
mySlots.add(s)
if len(mySlots) == 0:
if doN:
vals.append(i + 1)
itemsOutside.append((i, b, e, *vals))
continue
if skipBlanks and len(vals):
slotsOrdered = sorted(mySlots)
nSlots = len(slotsOrdered)
start = min(
(
i
for (i, s) in enumerate(slotsOrdered)
if Fslotv(s) not in {" ", "\t", "\n"}
),
default=nSlots,
)
end = max(
(
i + 1
for (i, s) in enumerate(slotsOrdered)
if Fslotv(s) not in {" ", "\t", "\n"}
),
default=0,
)
if end <= start:
itemsEmpty.append((i, b, e, *vals))
continue
mySlots = slotsOrdered[start:end]
else:
mySlots = sorted(mySlots)
curTkValue = ""
curTkSlots = []
curTokenValue = ""
curTokenSlots = []
nMySlots = len(mySlots)
if isTk:
# we might need to split tokens:
# * at points that correspond to empty slots