-
Notifications
You must be signed in to change notification settings - Fork 0
/
Teprolin.py
503 lines (417 loc) · 17.6 KB
/
Teprolin.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
import atexit
import inspect
import sys
import os
import requests, zipfile, io
from pathlib import Path
from time import gmtime
from filelock import FileLock
from enum import Enum
from TeproAlgo import TeproAlgo
from TeproDTO import TeproDTO
# Import all NLP apps that are implemented
from tnorm.TextNorm import TextNorm
from diac.DiacRestore import DiacRestore
from cubenlp.CubeNLP import CubeNLP
from udpipe.UDPipe import UDPipe
from ttsops.TTSOps import TTSOps
from ttl.TTLOps import TTLOps
from ner.NEROps import NEROps
from bioner.BioNEROps import BioNEROps
from TeproConfig import TEPROLIN_RESOURCES_FOLDER, DIACMODELFILE
# Statistic status
class SStatus(Enum):
# Read from file
EXISTING = 1
# Produced during runtime
ACQUIRED = 2
CONSTSTR1 = "' is not recognized. See class TeproAlgo."
CONSTSTR2 = "NLP app '"
# Author: Radu ION, (C) ICIA 2018-2020
class Teprolin(object):
"""This is the TEPROLIN platform that integrates all of the exposed
NLP apps and provides them as TeproApi objects.
The user only has to specify what operations he/she wants and, with each
NLP op, the algorithm to perform the op."""
statsFile = "teprolin-stats.txt"
statsLockFile = "teprolin-stats.txt.lock"
statsYear = "year"
statsMonth = "month"
statsDay = "day"
statsTokens = "tokens"
statsRequests = "requests"
# After how many requests to update
# the stats file such that the brother processes
# can update.
statsUpdateCounts = 10
resourcesDownloadLink = "https://relate.racai.ro/resources/teprolin/teprolin-resources.zip"
@staticmethod
def _installResources():
"""This method will check for the existence of the .teprolin folder
in the user's home folder. If there's no such folder, it is created
and resources are downloaded from RACAI's servers."""
teproFolder = Path(TEPROLIN_RESOURCES_FOLDER)
if not teproFolder.is_dir():
print("{0}.{1}[{2}]: creating the TEPROLIN resources folder {3}".
format(
Path(inspect.stack()[0].filename).stem,
inspect.stack()[0].function,
inspect.stack()[0].lineno,
TEPROLIN_RESOURCES_FOLDER
), file=sys.stderr, flush=True)
# Folder already exists in the .zip
teproFolder.mkdir(mode=0o755)
print("{0}.{1}[{2}]: downloading the resources @ {3}".
format(
Path(inspect.stack()[0].filename).stem,
inspect.stack()[0].function,
inspect.stack()[0].lineno,
Teprolin.resourcesDownloadLink
), file=sys.stderr, flush=True)
r = requests.get(Teprolin.resourcesDownloadLink)
if r.status_code == 200:
z = zipfile.ZipFile(io.BytesIO(r.content))
z.extractall(teproFolder)
if Path(DIACMODELFILE).is_file():
print("{0}.{1}[{2}]: installation OK".
format(
Path(inspect.stack()[0].filename).stem,
inspect.stack()[0].function,
inspect.stack()[0].lineno
), file=sys.stderr, flush=True)
else:
print("{0}.{1}[{2}]: expected file {3} wasn't found, please check".
format(
Path(inspect.stack()[0].filename).stem,
inspect.stack()[0].function,
inspect.stack()[0].lineno,
DIACMODELFILE
), file=sys.stderr, flush=True)
exit(1)
else:
print("{0}.{1}[{2}]: could not download the resources @ {3}".
format(
Path(inspect.stack()[0].filename).stem,
inspect.stack()[0].function,
inspect.stack()[0].lineno,
Teprolin.resourcesDownloadLink
), file=sys.stderr, flush=True)
exit(1)
def _startApps(self):
"""When you add a new NLP app, don't forget to add it here as well!"""
Teprolin._installResources()
tn = TextNorm()
dr = DiacRestore()
dr.loadResources()
cb = CubeNLP()
cb.createApp()
cb.loadResources()
udp = UDPipe()
udp.loadResources()
ttl = TTLOps()
ttl.createApp()
tts = TTSOps()
tts.createApp()
ner = NEROps()
bner = BioNEROps()
bner.createApp()
return [tn, dr, cb, udp, ttl, tts, ner, bner]
def _readStatsFile(self) -> list:
lock = FileLock(Teprolin.statsLockFile)
stats = []
with lock:
print("PID {0}-{1}.{2}[{3}]: reading the statistics from the file...".
format(
os.getpid(),
Path(inspect.stack()[0].filename).stem,
inspect.stack()[0].function,
inspect.stack()[0].lineno
), file=sys.stderr, flush=True)
with open(Teprolin.statsFile, mode="r") as f:
for line in f:
parts = line.split()
date = (
int(parts[0]),
int(parts[1]),
int(parts[2])
)
tkc = int(parts[3])
rqc = int(parts[4])
sts = SStatus.EXISTING
stats.append([date, tkc, rqc, sts])
# end with open
# end with lock
return stats
def _writeStatsFile(self):
toUpdate = False
for st in self._stats:
if st[3] == SStatus.ACQUIRED:
toUpdate = True
break
if not toUpdate:
return
exstats = self._readStatsFile()
lock = FileLock(Teprolin.statsLockFile)
uprec = 0
adrec = 0
with lock:
print("PID {0}-{1}.{2}[{3}]: updating the statistics in the file...".
format(
os.getpid(),
Path(inspect.stack()[0].filename).stem,
inspect.stack()[0].function,
inspect.stack()[0].lineno
), file=sys.stderr, flush=True)
with open(Teprolin.statsFile, mode="w") as f:
for x in exstats:
for i in range(len(self._stats)):
y = self._stats[i]
if y[0] == x[0]:
if y[3] == SStatus.ACQUIRED:
x[1] += y[1]
x[2] += y[2]
uprec += 1
# end if ACQUIRED
self._stats.pop(i)
break
# end if same day
# end for i
d = x[0]
t = x[1]
r = x[2]
f.write(" ".join(str(e) for e in d))
f.write(" ")
f.write(str(t))
f.write(" ")
f.write(str(r))
f.write("\n")
# end for x
for y in self._stats:
if y[3] == SStatus.ACQUIRED:
d = y[0]
t = y[1]
r = y[2]
f.write(" ".join(str(e) for e in d))
f.write(" ")
f.write(str(t))
f.write(" ")
f.write(str(r))
f.write("\n")
adrec += 1
# end for y
print("PID {0}-{1}.{2}[{3}]: updated {4} records and added {5} records.".
format(
os.getpid(),
Path(inspect.stack()[0].filename).stem,
inspect.stack()[0].function,
inspect.stack()[0].lineno,
uprec,
adrec
), file=sys.stderr, flush=True)
# end with open
def _indexOfAlgo(self, algo: str) -> int:
"""Given an algorithm name from TeproAlgo.getAvailableAlgorithms(),
get the index of the corresponding TeproApi object from self._apps."""
appi = -1
for i in range(len(self._apps)):
app = self._apps[i]
if app.getAlgoName() == algo:
appi = i
break
return appi
def _checkApiUniqueNames(self):
"""Each TeproApi object must have a unique algorithm name."""
for i in range(len(self._apps)):
ain = self._apps[i].getAlgoName()
for j in range(i + 1, len(self._apps)):
ajn = self._apps[j].getAlgoName()
if ain == ajn:
raise RuntimeError(CONSTSTR2 + ain +
"' found twice in self._apps. Each TeproApi object must have a unique name!")
def defaultConfiguration(self):
# Dictionary of operations to implementing algorithms (NLP app).
self._conf = {}
for op in TeproAlgo.getAvailableOperations():
self._conf[op] = TeproAlgo.getDefaultAlgoForOper(op)
print("{0}.{1}[{2}]: configuring operation '{3}' with algorithm '{4}'".
format(
Path(inspect.stack()[0].filename).stem,
inspect.stack()[0].function,
inspect.stack()[0].lineno,
op,
self._conf[op]
), file=sys.stderr, flush=True)
def __init__(self):
self._requests = 0
self._stats = self._readStatsFile()
self.defaultConfiguration()
self._apps = self._startApps()
self._checkApiUniqueNames()
atexit.register(self._destroyAllApps)
def getConfiguration(self, op: str = None):
if op is None:
# Just return the whole configuration
return self._conf
if op in self._conf:
# Or return the configuration for op,
# if not None
return self._conf[op]
else:
return None
def configure(self, op: str, algo: str):
availableOps = TeproAlgo.getAvailableOperations()
availableAlgos = TeproAlgo.getAvailableAlgorithms()
if op not in availableOps:
raise RuntimeError("Operation '" + op + CONSTSTR1)
if algo not in availableAlgos:
raise RuntimeError(CONSTSTR2 + algo + CONSTSTR1)
if not TeproAlgo.canPerform(algo, op):
raise RuntimeError(
CONSTSTR2 + algo + "' cannot perform operation '" + op + "'. See class TeproAlgo.")
print("{0}.{1}[{2}]: requesting operation '{3}' be performed with '{4}'".
format(
Path(inspect.stack()[0].filename).stem,
inspect.stack()[0].function,
inspect.stack()[0].lineno,
op,
algo
), file=sys.stderr, flush=True)
self._conf[op] = algo
def pcFull(self, text: str) -> TeproDTO:
"""This is the complete processing chain (pc), executing
all NLP ops enumerated in TeproAlgo."""
# Just run everything we know about on text.
return self.pcExec(text, TeproAlgo.getAvailableOperations())
def pcDiac(self, text: str) -> str:
"""This processing chain will insert diacritics in a text
which does not have them."""
# You can specify the whole call chain, if you know it.
return self.pcExec(text, [
TeproAlgo.getTextNormOperName(),
TeproAlgo.getDiacRestorationOperName()])
def pcLemma(self, text: str) -> TeproDTO:
"""This processing chain will do POS tagging and lemmatization
on the input text, splitting the text in sentences and tokens beforehand."""
# Or you can specify a few operations like 'lemmatization',
# pcExec will infer the dependencies.
return self.pcExec(text, [TeproAlgo.getLemmatizationOperName()])
def pcParse(self, text: str) -> TeproDTO:
"""This processing chain will do chunking and dependency parsing
on the input text, splitting the text in sentences and tokens and
doing POS tagging and lemmatization beforehand."""
return self.pcExec(text, [TeproAlgo.getDependencyParsingOperName()])
def pcExec(self, text: str, ops: list) -> TeproDTO:
"""This processing chain will make sure that the list of
requested operations (ops) are executed on the input text,
along with their required dependencies."""
availableOps = TeproAlgo.getAvailableOperations()
# 1. Check if all requested ops are valid
for op in ops:
if op not in availableOps:
raise RuntimeError("Operation '" + op + CONSTSTR1)
# 2. Increase the number of requests by 1
# with every call to this method.
self._requests += 1
configuredApps = []
# 2.1 Resolve all operation dependencies
expandedOps = TeproAlgo.resolveDependencies(ops)
# 3.1 Dynamically alter the configuration
# depending on exceptions. For instance
# ner-icia requires ttl-icia, not nlp-cube-adobe
TeproAlgo.reconfigureWithStrictRequirements(self._conf, expandedOps)
# 3.2 Get instantiated apps for the requested operations.
# Apps are added in the order provided by expandedOps,
# so no more app sorting is needed.
for op in expandedOps:
opi = self._indexOfAlgo(self._conf[op])
if opi >= 0:
app = self._apps[opi]
if app not in configuredApps:
configuredApps.append(app)
else:
print("{0}.{1}[{2}]: operation '{3}' is not supported yet.".
format(
Path(inspect.stack()[0].filename).stem,
inspect.stack()[0].function,
inspect.stack()[0].lineno,
op
), file=sys.stderr, flush=True)
# 5. Run all configured NLP apps in sequence on
# the dto object.
dto = TeproDTO(text, self._conf)
for app in configuredApps:
print("{0}.{1}[{2}]: running NLP app '{3}'".
format(
Path(inspect.stack()[0].filename).stem,
inspect.stack()[0].function,
inspect.stack()[0].lineno,
app.getAlgoName()
), file=sys.stderr, flush=True)
dto = app.doWork(dto)
# 6. Collect statistics
ts = gmtime()
if self._stats and \
self._stats[-1][0][0] == ts.tm_mday and \
self._stats[-1][0][1] == ts.tm_mon and \
self._stats[-1][0][2] == ts.tm_year:
self._stats[-1][1] += dto.getProcessedTokens()
self._stats[-1][2] += 1
self._stats[-1][3] = SStatus.ACQUIRED
else:
date = (ts.tm_mday, ts.tm_mon, ts.tm_year)
tkc = dto.getProcessedTokens()
self._stats.append(
[date, tkc, self._requests, SStatus.ACQUIRED])
# 7. Write stats every statsUpdateCounts requests
if self._requests % Teprolin.statsUpdateCounts == 0:
self._writeStatsFile()
self._stats = self._readStatsFile()
# 8. Work done, return the dto object.
return dto
def getStats(self, svalue: str, tvalue: str, hsize: int) -> list:
# By default, tokens statistics are returned.
sindex = 1
stats = []
if svalue == Teprolin.statsTokens:
sindex = 1
elif svalue == Teprolin.statsRequests:
sindex = 2
for i in range(len(self._stats) - 1, -1, -1):
s = self._stats[i]
dkey = ""
if tvalue == Teprolin.statsYear:
dkey = str(s[0][2])
elif tvalue == Teprolin.statsMonth:
dkey = "{0:02d}".format(s[0][1]) + "-" + str(s[0][2])
elif tvalue == Teprolin.statsDay:
dkey = "{0:02d}".format(
s[0][0]) + "-" + "{0:02d}".format(s[0][1]) + "-" + str(s[0][2])
else:
# By default, month stats
dkey = "{0:02d}".format(s[0][1]) + "-" + str(s[0][2])
freq = s[sindex]
if stats and stats[-1][0] == dkey:
stats[-1][1] += freq
else:
stats.append([dkey, freq])
if len(stats) > hsize:
break
# end for s
if len(stats) <= hsize:
return stats
else:
return stats[0:hsize]
def _destroyAllApps(self):
"""Destroys the instantiated NLP apps."""
# Also dump the latest statistics
# that this object has.
self._writeStatsFile()
for app in self._apps:
print("{0}.{1}[{2}]: destroying NLP app '{3}'".
format(
Path(inspect.stack()[0].filename).stem,
inspect.stack()[0].function,
inspect.stack()[0].lineno,
app.getAlgoName()
), file=sys.stderr, flush=True)
app.destroyApp()