forked from spraakbanken/korp-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkorp.py
4136 lines (3446 loc) · 162 KB
/
korp.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
"""
A WSGI application for querying corpora available on the server.
It mainly acts as a wrapper for the CQP Query Language of Corpus Workbench.
Configuration is done by editing config.py.
https://spraakbanken.gu.se/korp/
"""
# Skip monkey patching if run through gunicorn (which does the patching for us)
import os
if "gunicorn" not in os.environ.get("SERVER_SOFTWARE", ""):
from gevent import monkey
monkey.patch_all(subprocess=False) # Patching needs to be done as early as possible, before other imports
from gevent.pywsgi import WSGIServer
from gevent.threadpool import ThreadPool
from gevent.queue import Queue, Empty
# gunicorn patches everything, and gevent's subprocess module can't be used in
# native threads other than the main one, so we need to un-patch the subprocess module.
from importlib import reload
import subprocess
reload(subprocess)
from concurrent import futures
from concurrent.futures import ThreadPoolExecutor
from collections import defaultdict, OrderedDict
from dateutil.relativedelta import relativedelta
from copy import deepcopy
from pathlib import Path
from typing import Union, Optional
import datetime
import uuid
import binascii
import sys
import glob
import time
import re
import json
import zlib
import urllib.request
import urllib.parse
import urllib.error
import base64
import hashlib
import itertools
import traceback
import functools
import math
import random
import korppluginlib
import config
import yaml
try:
import pylibmc
except ImportError:
print("Could not load pylibmc. Caching will be disabled.")
cache_disabled = True
else:
cache_disabled = False
from flask import Flask, request, Response, stream_with_context, copy_current_request_context
from flask_mysqldb import MySQL
from flask_cors import CORS
################################################################################
# Nothing needs to be changed in this file. Use config.py for configuration.
# The version of this script
KORP_VERSION = "8.1.0"
# Special symbols used by this script; they must NOT be in the corpus
END_OF_LINE = "-::-EOL-::-"
LEFT_DELIM = "---:::"
RIGHT_DELIM = ":::---"
# Regular expressions for parsing parameters
IS_NUMBER = re.compile(r"^\d+$")
IS_IDENT = re.compile(r"^[\w\-,|]+$")
QUERY_DELIM = ","
################################################################################
app = Flask(__name__)
CORS(app)
# Configure database connection
app.config["MYSQL_HOST"] = config.DBHOST
app.config["MYSQL_USER"] = config.DBUSER
app.config["MYSQL_PASSWORD"] = config.DBPASSWORD
app.config["MYSQL_DB"] = config.DBNAME
app.config["MYSQL_PORT"] = config.DBPORT
app.config["MYSQL_CHARSET"] = config.DBCHARSET
app.config["MYSQL_USE_UNICODE"] = True
app.config["MYSQL_CURSORCLASS"] = "DictCursor"
mysql = MySQL(app)
def main_handler(generator):
"""Decorator wrapping all WSGI endpoints, handling errors and formatting.
Global parameters are
- callback: an identifier that the result should be wrapped in
- encoding: the encoding for interacting with the corpus (default: UTF-8)
- indent: pretty-print the result with a specific indentation
- debug: if set, return some extra information (for debugging)
"""
@functools.wraps(generator) # Copy original function's information, needed by Flask
def decorated(args=None, *pargs, **kwargs):
internal = args is not None
if not internal:
if request.is_json:
args = request.get_json()
else:
args = request.values.to_dict()
args["internal"] = internal
if not isinstance(args.get("cache"), bool):
args["cache"] = bool(not cache_disabled and
not args.get("cache", "").lower() == "false" and
config.CACHE_DIR and os.path.exists(config.CACHE_DIR) and
config.MEMCACHED_SERVERS)
if internal:
# Function is internally used
return generator(args, *pargs, **kwargs)
else:
# Function is called externally
plugin_caller = korppluginlib.KorpCallbackPluginCaller()
def error_handler():
"""Format exception info for output to user."""
exc = sys.exc_info()
if isinstance(exc[1], CustomTracebackException):
exc = exc[1].exception
error = {"ERROR": {"type": exc[0].__name__,
"value": str(exc[1])
}}
if "debug" in args:
error["ERROR"]["traceback"] = "".join(traceback.format_exception(*exc)).splitlines()
plugin_caller.raise_event("error", error, exc)
return error
def incremental_json(ff):
"""Incrementally yield result as JSON."""
result_len = 0
if callback:
result_len += len(callback) + 1
yield callback + "("
result_len += 2
yield "{\n"
try:
for response in ff:
if not response:
# Yield whitespace to prevent timeout
result_len += 2
yield " \n"
else:
response = plugin_caller.filter_value(
"filter_result", response)
output = json.dumps(response)[1:-1] + ",\n"
result_len += len(output)
yield output
except GeneratorExit:
raise
except:
error = error_handler()
output = json.dumps(error)[1:-1] + ",\n"
result_len += len(output)
yield output
endtime = time.time()
elapsed_time = endtime - starttime
output = json.dumps({"time": elapsed_time})[1:] + "\n"
result_len += len(output)
yield output
if callback:
result_len += 1
yield ")"
plugin_caller.raise_event(
"exit_handler", endtime, elapsed_time, result_len)
plugin_caller.cleanup()
def full_json(ff):
"""Yield full JSON at the end, but until then keep returning newlines to prevent timeout."""
result = {}
try:
for response in ff:
if not response:
# Yield whitespace to prevent timeout
yield " \n"
else:
result.update(response)
except GeneratorExit:
raise
except:
result = error_handler()
endtime = time.time()
elapsed_time = endtime - starttime
result["time"] = elapsed_time
result = plugin_caller.filter_value("filter_result", result)
if callback:
result = callback + "(" + json.dumps(result, indent=indent) + ")"
else:
result = json.dumps(result, indent=indent)
plugin_caller.raise_event(
"exit_handler", endtime, elapsed_time, len(result))
yield result
plugin_caller.cleanup()
def make_custom_response(ff):
"""Return a Response with custom mimetype and/or headers.
The view function ff should yield a dict with the
following keys recognized:
- "content": the actual content;
- "mimetype" (default: "text/html"): possible MIME type; and
- "headers": possible other headers as a list of pairs
(header, value).
Note that setting incremental=True does not have any effect.
"""
result = {}
try:
for response in ff:
if response:
result.update(response)
except GeneratorExit:
raise
except:
# Return error information as JSON
result["content"] = json.dumps(error_handler(),
indent=indent)
result["mimetype"] = "application/json"
# Filter only the content. Should we also allow filtering the
# headers and/or mimetype, using separate hook points?
result["content"] = plugin_caller.filter_value(
"filter_result", result["content"])
endtime = time.time()
elapsed_time = endtime - starttime
plugin_caller.raise_event(
"exit_handler", endtime, elapsed_time, len(result["content"]))
plugin_caller.cleanup()
return Response(result.get("content"),
headers=result.get("headers"),
mimetype=result.get("mimetype"))
starttime = time.time()
plugin_caller.raise_event("enter_handler", args, starttime)
args = plugin_caller.filter_value("filter_args", args)
incremental = parse_bool(args, "incremental", False)
callback = args.get("callback")
indent = int(args.get("indent", 0))
if getattr(generator, "use_custom_headers", None):
# Custom headers and/or MIME type (non-JSON)
return make_custom_response(generator(args, *pargs, **kwargs))
elif incremental:
# Incremental response
return Response(stream_with_context(incremental_json(generator(args, *pargs, **kwargs))),
mimetype="application/json")
else:
# We still use a streaming response even when non-incremental, to prevent timeouts
return Response(stream_with_context(full_json(generator(args, *pargs, **kwargs))),
mimetype="application/json")
return decorated
def prevent_timeout(generator):
"""Decorator for long-running functions that might otherwise timeout."""
@functools.wraps(generator)
def decorated(args=None, *pargs, **kwargs):
if args["internal"]:
# Internally used
yield from generator(args, *pargs, **kwargs)
return
def f(queue):
for response in generator(args, *pargs, **kwargs):
queue.put(response)
queue.put("DONE")
timeout = 15
q = Queue()
@copy_current_request_context
def error_catcher(g, *pargs, **kwargs):
try:
g(*pargs, **kwargs)
except Exception as e:
q.put(sys.exc_info())
pool = ThreadPool(1)
pool.spawn(error_catcher, f, q)
while True:
try:
msg = q.get(block=True, timeout=timeout)
if msg == "DONE":
break
elif isinstance(msg, tuple):
raise CustomTracebackException(msg)
else:
yield msg
except Empty:
yield {}
return decorated
def use_custom_headers(generator):
"""Decorator for view functions possibly yielding a non-JSON result.
A view function with attribute use_custom_headers = True is
treated specially in main_handler: the actual content is assumed
to be in the value for the key "content" of the result dict, MIME
type in "mimetype" and possible other headers as a list of pairs
(header, value) in "headers".
"""
generator.use_custom_headers = True
return generator
################################################################################
# ARGUMENT PARSING
################################################################################
def parse_corpora(args):
corpora = args.get("corpus", [])
sort = parse_bool(args, "sort_corpora", config.SORT_CORPORA_DEFAULT)
if isinstance(corpora, str):
corpora = corpora.upper().split(QUERY_DELIM)
if sort:
return sorted(set(corpora))
else:
# Unique elements, keeping order: https://stackoverflow.com/a/480227
seen = set()
return [c for c in corpora if not (c in seen or seen.add(c))]
def parse_within(args):
within = defaultdict(lambda: args.get("default_within"))
if args.get("within"):
if ":" not in args.get("within"):
raise ValueError("Malformed value for key 'within'.")
within.update({x.split(":")[0].upper(): x.split(":")[1] for x in args.get("within").split(QUERY_DELIM)})
return within
def parse_cqp_subcqp(args):
cqp = [args.get(key) for key in sorted([k for k in args.keys() if k.startswith("cqp")],
key=lambda x: int(x[3:]) if len(x) > 3 else 0)]
subcqp = [args.get(key) for key in sorted([k for k in args.keys() if k.startswith("subcqp")],
key=lambda x: int(x[6:]) if len(x) > 6 else 0)]
return cqp, subcqp
################################################################################
# INFO
################################################################################
@app.route("/sleep", methods=["GET", "POST"])
@main_handler
@prevent_timeout
def sleep(args):
t = int(args.get("t", 5))
for x in range(t):
time.sleep(1)
yield {"%d" % x: x}
@app.route("/")
@app.route("/info", methods=["GET", "POST"])
@main_handler
def info(args):
"""Get version information about list of available corpora."""
strict = parse_bool(args, "strict", False)
if args["cache"]:
with mc_pool.reserve() as mc:
result = mc.get("%s:info_%s" % (cache_prefix(), int(strict)))
if result:
if "debug" in args:
result.setdefault("DEBUG", {})
result["DEBUG"]["cache_read"] = True
yield result
return
corpora = run_cqp("show corpora;")
version = next(corpora)
# CQP "show corpora" lists all corpora in the registry, but some
# of them might nevertheless cause a "corpus undefined" error in
# CQP, for example, because of missing data, so filter them out.
# However, with a large number of corpora, filtering slows down
# the info command, so it can be disabled with the parameter
# strict=false. Caching the results of filter_undefined_corpora
# helps, though.
if strict:
corpora, _ = filter_undefined_corpora(list(corpora), args)
protected = get_protected_corpora()
result = {"version": KORP_VERSION, "cqp_version": version, "corpora": list(corpora), "protected_corpora": protected}
if config.INFO_SHOW_PLUGINS:
result["plugins"] = korppluginlib.get_loaded_plugins(
names_only=(config.INFO_SHOW_PLUGINS == "names"))
if args["cache"]:
with mc_pool.reserve() as mc:
added = mc.add("%s:info_%s" % (cache_prefix(), int(strict)), result)
if added and "debug" in args:
result.setdefault("DEBUG", {})
result["DEBUG"]["cache_saved"] = True
yield result
@app.route("/corpus_info", methods=["GET", "POST"])
@main_handler
def corpus_info(args, no_combined_cache=False):
"""Get information about a specific corpus or corpora."""
assert_key("corpus", args, IS_IDENT, True)
corpora = parse_corpora(args)
report_undefined_corpora = parse_bool(
args, "report_undefined_corpora", False)
# Check if whole query is cached
if args["cache"]:
checksum_combined = get_hash((sorted(corpora), report_undefined_corpora))
save_cache = []
combined_cache_key = "%s:info_%s" % (cache_prefix(), checksum_combined)
with mc_pool.reserve() as mc:
result = mc.get(combined_cache_key)
if result:
if "debug" in args:
result.setdefault("DEBUG", {})
result["DEBUG"]["cache_read"] = True
result["DEBUG"]["checksum"] = checksum_combined
yield result
return
result = {"corpora": {}}
total_size = 0
total_sentences = 0
cmd = []
if report_undefined_corpora:
corpora, undefined_corpora = filter_undefined_corpora(corpora, args)
for corpus in corpora:
# Check if corpus is cached
if args["cache"]:
with mc_pool.reserve() as mc:
corpus_result = mc.get("%s:info" % cache_prefix(corpus))
if corpus_result:
result["corpora"][corpus] = corpus_result
else:
save_cache.append(corpus)
if corpus not in result["corpora"]:
cmd += ["%s;" % corpus]
cmd += show_attributes()
cmd += ["info; .EOL.;"]
if cmd:
cmd += ["exit;"]
# Call the CQP binary
lines = run_cqp(cmd)
# Skip CQP version
next(lines)
for corpus in corpora:
if corpus in result["corpora"]:
total_size += int(result["corpora"][corpus]["info"]["Size"])
sentences = result["corpora"][corpus]["info"].get("Sentences", "")
if sentences.isdigit():
total_sentences += int(sentences)
continue
# Read attributes
attrs = read_attributes(lines)
# Corpus information
info = {}
for line in lines:
if line == END_OF_LINE:
break
if ":" in line and not line.endswith(":"):
infokey, infoval = (x.strip() for x in line.split(":", 1))
info[infokey] = infoval
if infokey == "Size":
total_size += int(infoval)
elif infokey == "Sentences" and infoval.isdigit():
total_sentences += int(infoval)
result["corpora"][corpus] = {"attrs": attrs, "info": info}
if args["cache"]:
if corpus in save_cache:
with mc_pool.reserve() as mc:
mc.add("%s:info" % cache_prefix(corpus), result["corpora"][corpus])
result["total_size"] = total_size
result["total_sentences"] = total_sentences
if report_undefined_corpora:
result["undefined_corpora"] = undefined_corpora
if args["cache"] and not no_combined_cache:
# Cache whole query
with mc_pool.reserve() as mc:
try:
saved = mc.add(combined_cache_key, result)
except pylibmc.TooBig:
pass
else:
if saved and "debug" in args:
result.setdefault("DEBUG", {})
result["DEBUG"]["cache_saved"] = True
yield result
def filter_undefined_corpora(corpora, args, strict=True):
"""Return a pair of a list of defined and a list of undefined corpora
in the argument corpora. If strict, try to select each corpus in
CQP, otherwise only check the files in the CWB registry directory.
"""
# Caching
if args["cache"]:
checksum_combined = get_hash((corpora, strict))
save_cache = []
combined_cache_key = (
"%s:corpora_defined_%s" % (cache_prefix(), checksum_combined))
with mc_pool.reserve() as mc:
result = mc.get(combined_cache_key)
if result:
# Since this is not the result of a command, we cannot
# add debug information on using cache to the result.
return result
defined = []
undefined = []
if strict:
# Stricter: detects corpora that have a registry file but
# whose data makes CQP regard them as undefined when trying to
# use them.
cqp = [corpus.upper() + ";" for corpus in corpora]
cqp += ["exit"]
lines = run_cqp(cqp, errors="report")
for line in lines:
if line.startswith("CQP Error:"):
matchobj = re.match(
r"CQP Error: Corpus ``(.*?)'' is undefined", line)
if matchobj:
undefined.append(str(matchobj.group(1)))
else:
# SKip the rest
break
if undefined:
undefined_set = set(undefined)
defined = [corpus for corpus in corpora
if corpus not in undefined_set]
else:
defined = corpora
else:
# It is somewhat faster but less reliable to check the
# registry only.
registry_files = set(os.listdir(config.CWB_REGISTRY))
defined = [corpus for corpus in corpora
if corpus.lower() in registry_files]
undefined = [corpus for corpus in corpora
if corpus.lower() not in registry_files]
result = (defined, undefined)
if args["cache"]:
with mc_pool.reserve() as mc:
try:
saved = mc.add(combined_cache_key, result)
except pylibmc.TooBig:
pass
return result
################################################################################
# QUERY
################################################################################
@app.route("/query_sample", methods=["GET", "POST"])
@main_handler
@prevent_timeout
def query_sample(args):
"""Run a sequential query in the selected corpora in random order until at least one
hit is found, and then abort the query. Use to get a random sample sentence."""
corpora = parse_corpora(args)
# Randomize corpus order
random.shuffle(corpora)
for i in range(len(corpora)):
corpus = corpora[i]
check_authentication([corpus])
args["corpus"] = corpus
args["sort"] = "random"
result = generator_to_dict(query(args))
if result["hits"] > 0:
yield result
return
yield result
@app.route("/query", methods=["GET", "POST"])
@main_handler
@prevent_timeout
def query(args):
"""Perform a CQP query and return a number of matches."""
assert_key("cqp", args, r"", True)
assert_key("corpus", args, IS_IDENT, True)
assert_key("start", args, IS_NUMBER)
assert_key("end", args, IS_NUMBER)
# assert_key("context", args, r"^\d+ [\w-]+$")
assert_key("show", args, IS_IDENT)
assert_key("show_struct", args, IS_IDENT)
# assert_key("within", args, IS_IDENT)
assert_key("cut", args, IS_NUMBER)
assert_key("sort", args, r"")
assert_key("incremental", args, r"(true|false)")
incremental = parse_bool(args, "incremental", False)
free_search = not parse_bool(args, "in_order", True)
use_cache = args["cache"]
cut = args.get("cut")
corpora = parse_corpora(args)
check_authentication(corpora)
show = args.get("show") or [] # We don't use .get("show", []) since "show" might be the empty string.
if isinstance(show, str):
show = show.split(QUERY_DELIM)
show = set(show + ["word"])
show_structs = args.get("show_struct") or []
if isinstance(show_structs, str):
show_structs = show_structs.split(QUERY_DELIM)
show_structs = set(show_structs)
expand_prequeries = parse_bool(args, "expand_prequeries", True)
start, end = int(args.get("start") or 0), int(args.get("end") or 9)
if config.MAX_KWIC_ROWS and end - start >= config.MAX_KWIC_ROWS:
raise ValueError("At most %d KWIC rows can be returned per call." % config.MAX_KWIC_ROWS)
within = parse_within(args)
# Parse "context"/"left_context"/"right_context"/"default_context"
default_context = args.get("default_context") or "10 words"
context = defaultdict(lambda: (default_context,))
contexts = {}
for c in ("left_context", "right_context", "context"):
cv = args.get(c, "")
if cv:
if ":" not in cv:
raise ValueError("Malformed value for key '%s'." % c)
contexts[c] = {x.split(":")[0].upper(): x.split(":")[1] for x in cv.split(QUERY_DELIM)}
else:
contexts[c] = {}
for corpus in set(k for v in contexts.values() for k in v.keys()):
if corpus in contexts["left_context"] or corpus in contexts["right_context"]:
context[corpus] = (contexts["left_context"].get(corpus, default_context),
contexts["right_context"].get(corpus, default_context))
else:
context[corpus] = (contexts["context"].get(corpus, default_context),)
sort = args.get("sort")
sort_random_seed = args.get("random_seed")
# Sort numbered CQP-queries numerically
cqp, _ = parse_cqp_subcqp(args)
if len(cqp) > 1 and expand_prequeries and not all(within[c] for c in corpora):
raise ValueError("Multiple CQP queries requires 'within' or 'expand_prequeries=false'")
# Parameters used for all queries
queryparams = {"free_search": free_search,
"use_cache": use_cache,
"show": show,
"show_structs": show_structs,
"expand_prequeries": expand_prequeries,
"cut": cut,
"cqp": cqp,
"sort": sort,
"random_seed": sort_random_seed
}
result = {"kwic": []}
# Checksum for whole query, used to verify 'query_data' from the client
checksum = get_hash((sorted(corpora),
cqp,
sorted(within.items()),
cut,
expand_prequeries,
free_search))
debug = {}
if "debug" in args:
debug["checksum"] = checksum
ns = Namespace()
ns.total_hits = 0
statistics = {}
saved_statistics = {}
query_data = args.get("query_data")
if query_data:
try:
query_data = zlib.decompress(base64.b64decode(
query_data.replace("\\n", "\n").replace("-", "+").replace("_", "/"))).decode("UTF-8")
except:
if "debug" in args:
debug["query_data_unparseable"] = True
else:
if "debug" in args:
debug["query_data_read"] = True
saved_checksum, stats_temp = query_data.split(";", 1)
if saved_checksum == checksum:
for pair in stats_temp.split(";"):
corpus, hits = pair.split(":")
saved_statistics[corpus] = int(hits)
elif "debug" in args:
debug["query_data_checksum_mismatch"] = True
if use_cache and not saved_statistics:
# Query data parsing failed or was missing, so look for cached hits instead
for corpus in corpora:
corpus_checksum = get_hash((cqp,
within[corpus],
cut,
expand_prequeries,
free_search))
with mc_pool.reserve() as mc:
cached_corpus_hits = mc.get("%s:query_size_%s" % (cache_prefix(corpus.split("|")[0]), corpus_checksum))
if cached_corpus_hits is not None:
saved_statistics[corpus] = cached_corpus_hits
ns.start_local = start
ns.end_local = end
if saved_statistics:
if "debug" in args:
debug["cache_coverage"] = "%d/%d" % (len(saved_statistics), len(corpora))
complete_hits = set(corpora) == set(saved_statistics.keys())
else:
complete_hits = False
if complete_hits:
# We have saved_statistics available for all corpora, so calculate which
# corpora need to be queried and then query them in parallel.
corpora_hits = which_hits(corpora, saved_statistics, start, end)
ns.total_hits = sum(saved_statistics.values())
statistics = saved_statistics
corpora_kwics = {}
ns.progress_count = 0
if len(corpora_hits) == 0:
pass
elif len(corpora_hits) == 1:
# If only hits in one corpus, it is faster to not use threads
corpus, hits = list(corpora_hits.items())[0]
result["kwic"], _ = query_and_parse(corpus, within=within[corpus], context=context[corpus],
start=hits[0], end=hits[1], **queryparams)
else:
if incremental:
yield {"progress_corpora": list(corpora_hits.keys())}
with ThreadPoolExecutor(max_workers=config.PARALLEL_THREADS) as executor:
# The query worker is outside the request context, so we pass
# the current request object to it, so that the plugin hook
# points in run_cqp can use it, without raising a "Working
# outside of request context" exception.
future_query = dict(
(executor.submit(query_and_parse, corpus, within=within[corpus], context=context[corpus],
start=corpora_hits[corpus][0], end=corpora_hits[corpus][1],
request=request._get_current_object(),
**queryparams),
corpus)
for corpus in corpora_hits)
for future in futures.as_completed(future_query):
corpus = future_query[future]
if future.exception() is not None:
raise CQPError(future.exception())
else:
kwic, _ = future.result()
corpora_kwics[corpus] = kwic
if incremental:
yield {"progress_%d" % ns.progress_count: {"corpus": corpus,
"hits": corpora_hits[corpus][1] -
corpora_hits[corpus][0] + 1}}
ns.progress_count += 1
for corpus in corpora:
if corpus in corpora_hits.keys():
result["kwic"].extend(corpora_kwics[corpus])
else:
# saved_statistics is missing or incomplete, so we need to query the corpora in
# serial until we have the needed rows, and then query the remaining corpora
# in parallel to get number of hits.
if incremental:
yield {"progress_corpora": corpora}
ns.progress_count = 0
ns.rest_corpora = []
# Serial until we've got all the requested rows
for i, corpus in enumerate(corpora):
if ns.end_local < 0:
ns.rest_corpora = corpora[i:]
break
skip_corpus = False
if corpus in saved_statistics:
nr_hits = saved_statistics[corpus]
if nr_hits - 1 < ns.start_local:
kwic = []
skip_corpus = True
if not skip_corpus:
kwic, nr_hits = query_and_parse(corpus, within=within[corpus], context=context[corpus],
start=ns.start_local, end=ns.end_local, **queryparams)
statistics[corpus] = nr_hits
ns.total_hits += nr_hits
# Calculate which hits from next corpus we need, if any
ns.start_local -= nr_hits
ns.end_local -= nr_hits
if ns.start_local < 0:
ns.start_local = 0
result["kwic"].extend(kwic)
if incremental:
yield {"progress_%d" % ns.progress_count: {"corpus": corpus, "hits": nr_hits}}
ns.progress_count += 1
if incremental:
yield result
result = {}
if ns.rest_corpora:
if saved_statistics:
for corpus in ns.rest_corpora:
if corpus in saved_statistics:
statistics[corpus] = saved_statistics[corpus]
ns.total_hits += saved_statistics[corpus]
with ThreadPoolExecutor(max_workers=config.PARALLEL_THREADS) as executor:
# The query worker is outside the request context, so we pass
# the current request object to it, so that the plugin hook
# points in run_cqp can use it, without raising a "Working
# outside of request context" exception.
#
# In this particular case, an approach defining an inner
# function calling query_corpus and decorated with
# @copy_current_request_context would also seem to work, but in
# other similar places, it would raise a "popped wrong context"
# exception, even when setting
# app.config["PRESERVE_CONTEXT_ON_EXCEPTION"] = False. Why?
future_query = dict(
(executor.submit(query_corpus, corpus, within=within[corpus],
context=context[corpus], start=0, end=0, no_results=True,
request=request._get_current_object(),
**queryparams),
corpus)
for corpus in ns.rest_corpora if corpus not in saved_statistics)
for future in futures.as_completed(future_query):
corpus = future_query[future]
if future.exception() is not None:
raise CQPError(future.exception())
else:
_, nr_hits, _ = future.result()
statistics[corpus] = nr_hits
ns.total_hits += nr_hits
if incremental:
yield {"progress_%d" % ns.progress_count: {"corpus": corpus, "hits": nr_hits}}
ns.progress_count += 1
if "debug" in args:
debug["cqp"] = cqp
result["hits"] = ns.total_hits
result["corpus_hits"] = statistics
result["corpus_order"] = corpora
result["query_data"] = binascii.b2a_base64(zlib.compress(
bytes(checksum + ";" + ";".join("%s:%d" % (c, h) for c, h in statistics.items()),
"utf-8"))).decode("utf-8").replace("+", "-").replace("/", "_")
if debug:
result["DEBUG"] = debug
yield result
@app.route("/optimize", methods=["GET", "POST"])
@main_handler
def optimize(args):
assert_key("cqp", args, r"", True)
cqpparams = {"within": args.get("within") or "sentence"}
if args.get("cut"):
cqpparams["cut"] = args["cut"]
free_search = not parse_bool(args, "in_order", True)
cqp = args["cqp"]
result = {"cqp": query_optimize(cqp, cqpparams, find_match=False, expand=False, free_search=free_search)}
yield result
def query_optimize(cqp, cqpparams, find_match=True, expand=True, free_search=False):
"""Optimize simple queries with multiple words by converting them to MU queries.
Optimization only works for queries with at least two tokens, or one token preceded
by one or more wildcards. The query also must use "within".
Return a tuple (return code, query)
0 = optimization successful
1 = optimization not needed (e.g. single word searches)
2 = optimization not possible (e.g. searches with repetition of non-wildcards)
"""
# Split query into tokens
tokens, rest = parse_cqp(cqp)
within = cqpparams.get("within")
leading_wildcards = False
# Don't allow wildcards in free searches
if free_search:
if any([token.startswith("[]") for token in tokens]):
raise CQPError("Wildcards not allowed in free order query.")
else:
# Remove leading and trailing wildcards since they will only slow us down
while tokens and tokens[0].startswith("[]"):
leading_wildcards = True
del tokens[0]
while tokens and tokens[-1].startswith("[]"):
del tokens[-1]
if len(tokens) == 0 or (len(tokens) == 1 and not leading_wildcards):
# Query doesn't benefit from optimization
return 1, make_query(make_cqp(cqp, **cqpparams))
elif rest or not within:
# Couldn't optimize this query
return 2, make_query(make_cqp(cqp, **cqpparams))
cmd = ["MU"]
wildcards = {}
for i in range(len(tokens) - 1):
if tokens[i].startswith("[]"):
n1 = n2 = None
if tokens[i] == "[]":
n1 = n2 = 1
elif re.search(r"{\s*(\d+)\s*,\s*(\d*)\s*}$", tokens[i]):
n = re.search(r"{\s*(\d+)\s*,\s*(\d*)\s*}$", tokens[i]).groups()
n1 = int(n[0])
n2 = int(n[1]) if n[1] else 9999
elif re.search(r"{\s*(\d*)\s*}$", tokens[i]):
n1 = n2 = int(re.search(r"{\s*(\d*)\s*}$", tokens[i]).groups()[0])
if n1 is not None:
wildcards[i] = (n1, n2)
continue
elif re.search(r"{.*?}$", tokens[i]):
# Repetition for anything other than wildcards can't be optimized
return 2, make_query(make_cqp(cqp, **cqpparams))
cmd[0] += " (meet %s" % (tokens[i])
if re.search(r"{.*?}$", tokens[-1]):