-
Notifications
You must be signed in to change notification settings - Fork 0
/
ellySurvey.py
executable file
·537 lines (420 loc) · 16.3 KB
/
ellySurvey.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
#!/usr/bin/python4
# PyElly - rule-based tool for analyzing natural language (Python v3.8)
#
# ellySurvey.py : 14nov2019 CPM
# ------------------------------------------------------------------------------
# Copyright (c) 2019, Clinton Prentiss Mah
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# -----------------------------------------------------------------------------
"""
running PyElly tokenization to classify tokens in a text data file
"""
import sys
import codecs
import ellyConfiguration
import ellyDefinition
import ellyToken
import ellyChar
import ellyException
import substitutionBuffer
import entityExtractor
import simpleTransform
import nameRecognition
import punctuationRecognizer
import vocabularyTable
import symbolTable
interact = sys.stdin.isatty() # to check for redirection of stdin (=0)
rules = ellyDefinition.grammar # for saving grammar rules
vocabulary = vocabularyTable.vocabulary # for saving compiled vocabulary
# source text files
_rules = [ '.g.elly' , '.m.elly' , '.p.elly' , '.n.elly' , '.h.elly' ,
'.stl.elly' , '.ptl.elly' ]
_vocabulary = [ vocabularyTable.source ]
#
# dummy classes for parseTree required by entityExtractor,
# vocabularyTable, and patternTable
#
class Tree(object):
"""
support ParseTree attribute and method for
pattern match and entity extraction
attributes:
lastph
"""
class Phrase(object):
"""
emulate parseTreeBase.Phrase
attributes:
lens
"""
def __init__ ( self ):
"""
initialization
arguments:
self
"""
self.lens = 0
def __init__ ( self ):
"""
initialization
arguments:
self
"""
self.lastph = Tree.Phrase()
def addLiteralPhrase ( self , cat , fet , dvd=False , cap=False ):
"""
required dummy method
arguments:
self
cat
fet
dvd
cap
"""
# print ( 'addLiteralPhrase cat=' , cat , 'fet=' , fet.hexadecimal(False) , file=sys.stderr )
return
def addLiteralPhraseWithSemantics (self,typ,sxs,sms,bia,gen=None,dvd=False,cap=False):
""" dummy method
"""
ph = Tree.Phrase()
self.lastph = ph
return True
#
# main class for processing text file to get tokens
#
class EllySurvey(object):
"""
base class for token analysis of input data
attributes:
sbu - input buffer with macro substitutions
gtb - grammar table
vtb - vocabulary table
rul - grammar definitions
pat - pattern definitions
iex - entity extractors
trs - simple transformation
pnc - punctuation recognizer
ptr - dummy parse tree
tks - token list for output
"""
def __init__ ( self , system ):
"""
initialization of processing rules
arguments:
system - root name of PyElly tables to load
"""
nfail = 0 # error count for reporting
self.rul = None
self.tks = None # token list for output
self.ptr = Tree()
try:
self.rul = ellyDefinition.Grammar(system,True,None)
except ellyException.TableFailure:
nfail += 1
d = self.rul # language rules
self.gtb = d.gtb if d != None else None
mtb = d.mtb if d != None else None
self.sbu = substitutionBuffer.SubstitutionBuffer(mtb)
try:
inflx = self.sbu.stemmer
except AttributeError:
inflx = None
if d != None:
d.man.suff.infl = inflx # define root restoration logic
stb = d.stb if d != None else symbolTable.SymbolTable()
try:
voc = ellyDefinition.Vocabulary(system,True,stb)
except ellyException.TableFailure:
nfail += 1
if nfail > 0:
print ( 'exiting: table generation FAILures' , file=sys.stderr )
sys.exit(1)
self.vtb = voc.vtb
self.pnc = punctuationRecognizer.PunctuationRecognizer(stb)
self.iex = entityExtractor.EntityExtractor(self.ptr,stb) # set up extractors
self.trs = simpleTransform.SimpleTransform()
ntabl = d.ntb
if ntabl != None and ntabl.filled():
nameRecognition.setUp(ntabl)
ellyConfiguration.extractors.append( [ nameRecognition.scan , 'name' ] )
def survey ( self , text ):
"""
Elly processing of text input for tokens only
arguments:
self -
text - list of Unicode chars to extract tokens from
"""
self.tks = [ ] # initialize token list
if len(text) == 0: # if no text, done
return
# print ( 'text=' , text )
self.sbu.refill(text) # put text to translate into input buffer
# print ( self.sbu )
while self._lookUpNext():
# print ( 'current text chars=' , self.sbu.buffer )
pass
#
# reworked local methods from ellyBase
#
def _lookUpNext ( self ):
"""
look up next segment in input buffer by various means
arguments:
self
returns:
True on success, False otherwise
"""
self.sbu.skipSpaces() # skip leading spaces
s = self.sbu.buffer
if len(s) == 0: # check for end of input
return False # if so, done
if self.trs != None: # preanalysis of number expressions
self.trs.rewriteNumber(s)
self.sbu.expand() # apply macro substitutions
s = self.sbu.buffer
# print ( 'expanded len=' , len(s) )
# print ( 'sbu=' , s )
if len(s) == 0: return True # macros can empty out buffer
k = self.sbu.findBreak() # try to find first component for lookup
if k == 0:
k = 1 # must have at least one char in token
kl = len(s)
if k + 1 < kl and s[k] == '+' and s[k+1] == ' ':
k += 1 # recognize possible prefix
# print ( 'len(s)=' , kl , 'k=' , k , 's=', s )
mr = self._scanText(k) # text matching
mx = mr[0]
mty = mr[1]
chs = mr[2] # any vocabulary element matched
suf = mr[3] # any suffix removed in matching
s = self.sbu.buffer
# print ( 'mx=' , mx , 'len(s)=' , len(s), 'k=' , k )
# print ( 's=' , s )
if ( k < mx or
k == mx and suf != '' ): # next token cannot be as long as already seen?
if len(chs) > 0:
self.sbu.skip(mx)
if suf != '':
self.sbu.prepend(suf)
else:
chs = self.sbu.extract(mx)
to = ellyToken.EllyToken(''.join(chs))
self.tks.append([ mty , to ])
return True
wsk = self.sbu.buffer[:k]
# print ( 'wsk=' , wsk )
rws = ''.join(wsk).lower()
found = rws in self.gtb.dctn
if found:
# print ( 'found internally' )
mty += 'Id'
if found or mx > 0:
self.sbu.skip(k)
to = ellyToken.EllyToken(rws)
if len(suf) > 1: # change token to show suffix properly
# print ( 'suf=' , suf )
cs = suf[1] # first char in suffix after '-'
rt = to.root # this is a list!
lk = -1 # start at last char in token
while rt[lk] != cs: lk -= 1
sn = len(rt) + lk # where to divide suffix from root
# print ( 'sn=' , sn , rt )
to.root = rt[:sn] # root without suffix
self.sbu.prepend(suf) # restore suffix to input for processing
self.tks.append([ mty , to ])
return True
# print ( 'extract token' )
self._extractToken(mx,mty) # single-word matching with analysis
return True
def _scanText ( self , k ):
"""
try to match in buffer regardless of word boundaries
using Elly vocabulary and pattern tables and also
running Elly entity extractors
arguments:
self -
k - length of first component in buffer
returns:
match parameters [ text span of match , match types , vocabulary match chars , suffix removed ]
"""
# print ( '_scanText k=' , k )
sb = self.sbu.buffer # input buffer
# match status
nspan = 0 # total span of match
mtype = '' # no match type yet
vmchs = [ ] # chars of vocabulary entry matched
suffx = '' # any suffix removed in match
lm = len(sb) # scan limit
# print ( 'next component=' , sb[:k] , ', context=' , sb[k:lm] )
if self.vtb != None: # look in external dictionary first, if it exists
if k > 1: # is first component a single char?
ks = k # if not, use this for indexing
else:
ks = 1 # otherwise, add on any following alphanumeric
while ks < lm: #
if not ellyChar.isLetterOrDigit(sb[ks]):
break
ks += 1
ss = ''.join(sb[:ks]) # where to start for indexing
# print ( 'ss=' , ss )
n = vocabularyTable.delimitKey(ss) # get actual indexing
# print ( 'n=' , n )
rl = self.vtb.lookUp(sb,n) # get list of the longest matches
if len(rl) > 0: #
# print ( 'len(rl)=' , len(rl) )
r0 = rl[0] # look at first record
nspan = r0.nspan # should be same for all matches
mtype = 'Vt'
vmchs = r0.vem.chs #
suffx = r0.suffx #
# print ( 'vocabulary m=' , nspan )
d = self.rul # grammar rule definitions
m = d.ptb.match(sb,self.ptr) # try entity by pattern match next
# print ( 'pattern m=' , m )
if nspan < m:
nspan = m # on longer match, update maximum
mtype = 'Fa'
elif m > 0 and nspan == m:
mtype = 'VtFa'
# print ( 'mtype=' , mtype )
m = self.iex.run(sb) # try entity extractors next
# print ( 'extractor m=' , m )
if nspan < m:
nspan = m # on longer match, update maximum
mtype = 'Ee'
elif m > 0 and nspan == m:
mtype += 'Ee' # unchanged match length, add type
# print ( 'maximum match=' , nspan )
# print ( 'mtype=' , mtype )
# print ( 'input=' , self.sbu.buffer[:nspan] )
return [ nspan , mtype , vmchs , suffx ]
def _simpleTableLookUp ( self , ws ):
"""
simple external dictionary lookup
arguments:
self -
ws - single-word string
returns:
True if matches found, False otherwise
"""
# print ( 'look up [' + ws + '] externally' )
vs = self.vtb.lookUpSingleWord(ws) # look up token as word externally
# print ( len(vs) , 'candidates' )
return len(vs) > 0
def _extractToken ( self , mnl , mty ):
"""
extract next token from input buffer and look up in grammar table
arguments:
self -
mnl - minimum match
mty - matches already made
"""
d = self.rul # grammar rule definitions
buff = self.sbu # input source
# print ( 'buff=' , buff )
try:
w = buff.getNext() # extract next token
# print ( 'survey:' , w )
if w == None: return
ws = ''.join(w.root)
except ellyException.StemmingError as e:
print ( 'FATAL error' , e , file=sys.stderr )
sys.exit(1)
# print ( 'token ws=' , ws )
if len(ws) >= mnl:
if len(mty) == 0 or mty[0] != 'V':
if self._simpleTableLookUp(ws) > 0:
mty += 'Vt'
if ws in self.rul.gtb.dctn: # look up internally regardless
mty += 'Id'
if len(mty) > 0: # if any success, we are done
self.tks.append([ mty , w ])
return
if mnl > 0: # go no further if we had matches at start
return
dvdd = False
if d.man.analyze(w): # any analysis possible?
root = ''.join(w.root) # if so, get parts of analysis
tan = w.pres + [ root ] + w.sufs
dvdd = len(w.pres) > 0 or len(w.sufs) > 0
# print ( 'token analysis=' , tan )
while len(tan) > 0: # and put back into input
xs = tan.pop()
buff.prepend(xs)
buff.prepend(' ')
w = buff.getNext() # get token again with stemming and macros
ws = ''.join(w.root)
if len(ws) < mnl: return
if self._simpleTableLookUp(ws): # external lookup
mty = 'Vt'
if ws in self.rul.gtb.dctn: # internal lookup
mty += 'Id'
if len(mty) > 0: # if any success, we are done
w.dvdd = dvdd
self.tks.append([ mty , w ])
return
if self.pnc.match(w.root): # check if next token is punctuation
mty = 'Pu'
else:
mty = 'Un'
self.tks.append([ mty , w ])
#
# unit test
#
if __name__ == '__main__':
so = sys.stdout
si = sys.stdin
try:
syst = sys.argv[1] if len(sys.argv) > 1 else 'test' # which rule definitions to run
except ValueError as e:
print ( e , file=sys.stderr )
sys.exit(1)
try:
es = EllySurvey(syst)
except ellyException.TableFailure:
print ( 'cannot initialize rules and vocabulary' , file=sys.stderr )
sys.exit(1)
so.write('\n')
while True: # translate successive lines of text as sentences for testing
if interact:
so.write('> ')
so.flush()
l = si.readline()
if len(l) == 0: break
if l[0] == '\n': continue
es.survey(l)
ltok = es.tks
if ltok == None:
print ( '????' , file=sys.stderr )
else:
for x in ltok:
so.write(x[0] + ' ')
wx = x[1]
wr = ''.join(wx.getRoot())
wo = wx.getOrig()
so.write(wr)
if wr != wo:
so.write('/' + wx.getOrig())
so.write('\n')
so.flush()