-
Notifications
You must be signed in to change notification settings - Fork 21
/
kernel.py
563 lines (453 loc) · 18.1 KB
/
kernel.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
"""
.. include:: ../../docs/server/kernel.md
"""
import sys
import pickle
from functools import reduce
import rpyc
from rpyc.utils.server import ThreadedServer
from ..core.helpers import console
from ..advanced.app import findApp
from ..advanced.highlight import getPassageHighlights
from ..advanced.search import runSearch, runSearchCondensed
from ..advanced.helpers import getResultsX
from ..advanced.tables import compose, composeP, composeT
from .command import argKernel
TF_DONE = "TF setup done."
TF_ERROR = "Could not set up TF"
# KERNEL CREATION
def makeTfKernel(app, appName, port):
if not app.api:
console(f"{TF_ERROR}")
return False
TF = app.api.TF
reset = TF.reset
cache = TF.cache
reset()
cache = {}
console(f"{TF_DONE}\nKernel listening at port {port}")
class TfKernel(rpyc.Service):
def on_connect(self, conn):
self.app = app
pass
def on_disconnect(self, conn):
self.app = None
pass
def exposed_monitor(self):
"""A utility function that spits out some information from the kernel
to the outside world.
At this moment it is only used for debugging, but later it can be useful
to monitor the kernel or manage it while it remains running.
"""
app = self.app
api = app.api
S = api.S
searchExe = getattr(S, "exe", None)
if searchExe:
searchExe = searchExe.outerTemplate
_msgCache = cache(_asString=True)
data = dict(searchExe=searchExe, _msgCache=_msgCache)
return data
def exposed_header(self):
"""Fetches all the stuff to create a header.
This is shown after loading a data set.
It contains links to data and documentation of the data source.
"""
app = self.app
return app.header()
def exposed_provenance(self):
"""Fetches provenance metadata to be shown on exported data pages.
"""
app = self.app
aContext = app.context
commit = aContext.commit
appProvenance = ((("name", appName), ("commit", commit)),)
return (appProvenance, app.provenance)
def exposed_setNames(self):
"""Gets the names of the custom sets that the kernel has loaded.
The kernel can load additional sets of data triggered by the
`--sets=` command line argument with which the kernel
was started.
A web server kan use this informatiomn to write out provenance info.
"""
app = self.app
return (
tuple(sorted(app.sets.keys()))
if hasattr(app, "sets") and type(app.sets) is dict
else ()
)
def exposed_css(self):
"""Delivers the CSS code to be inserted on the browser page.
"""
app = self.app
return f'<style type="text/css">{app.loadCss()}</style>'
def exposed_context(self):
"""Fetches the TF app context settings for the corpus.
"""
return pickle.dumps(app.context)
def exposed_passage(
self,
features,
query,
sec0,
sec1=None,
sec2=None,
opened=set(),
getx=None,
**options,
):
"""Gets passages, i.e. sections of level 1 (chapter-like).
The material will be displayed as a sequence of plain
representations of the sec2s (verse-like), which can be expanded to pretty
displays when the user chooses to do so.
Parameters
----------
features: string | iterable
The features that should be displayed in pretty displays when expanding
a plain representation of a sec2 into a pretty display
query: string
The query whose results should be highlighted in the passage display.
sec0: string | int
The level 0 section (book)-like label in which the passage occurs
sec1: string | int, optional `None`
The level 1 section (chapter)-like label to fetch
sec2: string | int, optional `None`
The level 2 section (verse-like) label that should get focus
opened: set, optional, `set()`
The set of items that are currently expanded into pretty display
getx: string | int, optional `None`
If given, only a single sec2 (verse) will be fetched, but in pretty
display.
`getx` is the identifier (section label, verse number) of the item/
options: dict
Additional, optional display options, see `tf.advanced.options`.
"""
app = self.app
api = app.api
F = api.F
L = api.L
T = api.T
aContext = app.context
browseNavLevel = aContext.browseNavLevel
browseContentPretty = aContext.browseContentPretty
sectionFeatureTypes = T.sectionFeatureTypes
sec0Type = T.sectionTypes[0]
sec1Type = T.sectionTypes[1]
sectionDepth = len(T.sectionTypes)
browseNavLevel = min((sectionDepth, browseNavLevel))
finalSecType = T.sectionTypes[browseNavLevel]
finalSec = (sec0, sec1, sec2)[browseNavLevel]
if sec0:
if sectionFeatureTypes[0] == "int":
sec0 = int(sec0)
if sec1 and browseNavLevel == 2:
if sectionFeatureTypes[1] == "int":
sec1 = int(sec1)
sec0Node = T.nodeFromSection((sec0,)) if sec0 else None
sec1Node = T.nodeFromSection((sec0, sec1)) if sec0 and sec1 else None
contentNode = (sec0Node, sec1Node)[browseNavLevel - 1]
if getx is not None:
if sectionFeatureTypes[browseNavLevel] == "int":
getx = int(getx)
sec0s = tuple(T.sectionFromNode(s)[0] for s in F.otype.s(sec0Type))
sec1s = ()
if browseNavLevel == 2:
sec1s = (
()
if sec0Node is None
else tuple(
T.sectionFromNode(s)[1] for s in L.d(sec0Node, otype=sec1Type)
)
)
items = (
contentNode
if browseContentPretty
else L.d(contentNode, otype=finalSecType)
if contentNode
else []
)
highlights = (
getPassageHighlights(app, contentNode, query, cache) if items else set()
)
passage = ""
if items:
passage = composeP(
app,
browseNavLevel,
finalSecType,
features,
items,
opened,
finalSec,
getx=getx,
highlights=highlights,
**options,
)
return (passage, sec0Type, pickle.dumps((sec0s, sec1s)), browseNavLevel)
def exposed_rawSearch(self, query):
app = self.app
rawSearch = app.api.S.search
(results, messages) = rawSearch(query, _msgCache=True)
if messages:
# console(messages, error=True)
results = ()
else:
results = tuple(sorted(results))
# console(f'{len(results)} results')
return (results, messages)
def exposed_table(
self, kind, task, features, opened=set(), getx=None, **options,
):
"""Fetches material corresponding to a list of sections or tuples of nodes.
Parameters
----------
kind: string
Either `sections` or `tuples`:
whether to find section material or tuple material.
task: iterable
The list of things (sections or tuples) to retrieve the material for;
Typically coming from the *section pad* / *node pad* in the browser.
features: string | iterable
The features that should be displayed in pretty displays when expanding
a plain representation of a sec2 into a pretty display
opened: set, optional, `set()`
The set of items that are currently expanded into pretty display
getx: string | int, optional `None`
If given, only a single sec2 (verse) will be fetched, but in pretty
display.
`getx` is the identifier (section label, verse number) of the item/
options: dict
Additional, optional display options, see `tf.advanced.options`.
"""
app = self.app
if kind == "sections":
results = []
messages = []
if task:
lines = task.split("\n")
for (i, line) in enumerate(lines):
line = line.strip()
node = app.nodeFromSectionStr(line)
if type(node) is not int:
messages.append(str(node))
else:
results.append((i + 1, (node,)))
results = tuple(results)
messages = "\n".join(messages)
elif kind == "tuples":
results = ()
messages = ""
if task:
lines = task.split("\n")
try:
results = tuple(
(i + 1, tuple(int(n) for n in t.strip().split(",")))
for (i, t) in enumerate(lines)
if t.strip()
)
except Exception as e:
messages = f"{e}"
allResults = ((None, kind),) + results
table = composeT(app, features, allResults, opened, getx=getx, **options)
return (table, messages)
def exposed_search(
self, query, batch, position=1, opened=set(), getx=None, **options,
):
"""Executes a TF search template, retrieves formatted results.
The very work horse of this API.
Formatted results for additional nodes and sections are also retrieved.
Parameters
----------
query: string
The query whose results should be highlighted in the passage display.
Typically coming from the *search pad* in the browser.
batch: int
The number of table rows to show on one page in the browser.
position: integer, optional `1`
The position that is in focus in the browser.
The navigation links take this position as the central point,
and enable the user to navigate to neighbouring results,
in ever bigger strides.
opened: set, optional, `set()`
The set of items that are currently expanded into pretty display.
Normally, only the information to provide a *plain*
representation of a result is being fetched,
but for the opened ones information is gathered for
pretty displays.
getx: string | int, optional `None`
If given, only a single sec2 (verse) will be fetched, but in pretty
display.
`getx` is the identifier (section label, verse number) of the item/
"""
app = self.app
display = app.display
dContext = display.distill(options)
condensed = dContext.condensed
condenseType = dContext.condenseType
total = 0
results = ()
messages = ""
if query:
(results, messages, features) = (
runSearchCondensed(app, query, cache, condenseType)
if condensed and condenseType
else runSearch(app, query, cache)
)
if messages:
results = ()
total += len(results)
(start, end) = _batchAround(total, position, batch)
selectedResults = results[start - 1 : end]
opened = set(opened)
before = {n for n in opened if n > 0 and n < start}
after = {n for n in opened if n > end and n <= len(results)}
beforeResults = tuple((n, results[n - 1]) for n in sorted(before))
afterResults = tuple((n, results[n - 1]) for n in sorted(after))
allResults = (
((None, "results"),)
+ beforeResults
+ tuple((i + start, r) for (i, r) in enumerate(selectedResults))
+ afterResults
)
features = set(reduce(set.union, (x[1] for x in features), set()))
featureStr = " ".join(sorted(features))
table = compose(
app,
allResults,
featureStr,
position,
opened,
start=start,
getx=getx,
**options,
)
return (table, messages, featureStr, start, total)
def exposed_csvs(self, query, tuples, sections, **options):
"""Gets query results etc. in plain csv format.
The query results, tuples, and sections are retrieved, as in
`exposed_search`, but this function only needs some features per node.
"""
app = self.app
display = app.display
dContext = display.distill(options)
fmt = dContext.fmt
condensed = dContext.condensed
condenseType = dContext.condenseType
sectionResults = []
if sections:
sectionLines = sections.split("\n")
for sectionLine in sectionLines:
sectionLine = sectionLine.strip()
node = app.nodeFromSectionStr(sectionLine)
if type(node) is int:
sectionResults.append((node,))
sectionResults = tuple(sectionResults)
tupleResults = ()
if tuples:
tupleLines = tuples.split("\n")
try:
tupleResults = tuple(
tuple(int(n) for n in t.strip().split(","))
for t in tupleLines
if t.strip()
)
except Exception:
pass
queryResults = ()
queryMessages = ""
features = ()
if query:
(queryResults, queryMessages, features) = runSearch(app, query, cache)
(queryResultsC, queryMessagesC, featuresC) = (
runSearchCondensed(app, query, cache, condenseType)
if not queryMessages and condensed and condenseType
else (None, None, None)
)
if queryMessages:
queryResults = ()
if queryMessagesC:
queryResultsC = ()
csvs = (
("sections", sectionResults),
("nodes", tupleResults),
("results", queryResults),
)
if condensed and condenseType:
csvs += ((f"resultsBy{condenseType}", queryResultsC),)
resultsX = getResultsX(app, queryResults, features, condenseType, fmt=fmt,)
return (queryMessages, pickle.dumps(csvs), pickle.dumps(resultsX))
return TfKernel()
return ThreadedServer(
TfKernel(),
port=int(port),
protocol_config={
# 'allow_pickle': True,
# 'allow_public_attrs': True,
},
)
# KERNEL CONNECTION
def makeTfConnection(host, port, timeout):
class TfConnection(object):
def connect(self):
try:
connection = rpyc.connect(
host, port, config=dict(sync_request_timeout=timeout)
)
self.connection = connection
except ConnectionRefusedError as e:
self.connection = None
return str(e)
return connection.root
return TfConnection()
# TOP LEVEL
def main(cargs=sys.argv):
args = argKernel(cargs)
if not args:
return
(dataSource, portKernel) = args
appName = dataSource["appName"]
checkout = dataSource["checkout"]
checkoutApp = dataSource["checkoutApp"]
moduleRefs = dataSource["moduleRefs"]
locations = dataSource["locations"]
modules = dataSource["modules"]
setFile = dataSource["setFile"]
if checkout is None:
checkout = ""
console(f"Setting up TF kernel for {appName} {moduleRefs or ''} {setFile or ''}")
app = findApp(
appName,
checkoutApp,
True,
checkout=checkout,
mod=moduleRefs,
locations=locations,
modules=modules,
setFile=setFile,
)
if app is None:
return
kernel = makeTfKernel(app, appName, portKernel)
if kernel:
server = ThreadedServer(
kernel,
port=int(portKernel),
protocol_config={
# 'allow_pickle': True,
# 'allow_public_attrs': True,
},
)
server.start()
# LOWER LEVEL
def _batchAround(nResults, position, batch):
halfBatch = int((batch + 1) / 2)
left = min(max(position - halfBatch, 1), nResults)
right = max(min(position + halfBatch, nResults), 1)
discrepancy = batch - (right - left + 1)
if discrepancy != 0:
right += discrepancy
if right > nResults:
right = nResults
return (left, right)
if __name__ == "__main__":
main()