-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlcquad_query_aug_script_with_time.py
More file actions
3239 lines (2819 loc) · 113 KB
/
lcquad_query_aug_script_with_time.py
File metadata and controls
3239 lines (2819 loc) · 113 KB
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
#!/usr/bin/env python
# coding: utf-8
#### py377
'''
#### disable log output
import logging, sys
logging.disable(sys.maxsize)
'''
import pandas as pd
import numpy as np
import os
import sqlite_utils
from tqdm import tqdm
from timer import timer
from functools import partial, reduce, lru_cache
from rdflib.graph import Graph
from rdflib_hdt import HDTStore
import json
import os
os.environ["DP_SKIP_NLTK_DOWNLOAD"] = "True"
from deeppavlov import configs
from deeppavlov.core.commands.utils import *
from deeppavlov.core.commands.infer import *
from deeppavlov.core.common.file import *
from deeppavlov.models.kbqa.wiki_parser import *
from scipy.special import softmax
import pandas as pd
import numpy as np
import os
import json
from deeppavlov import configs, build_model
import numpy as np
#pd.set_option('display.max_colwidth', -1)
import inspect
from scipy.special import softmax
from deeppavlov.core.commands.infer import *
from deeppavlov.core.common.file import *
import re
from rapidfuzz import fuzz
from collections import defaultdict
from functools import reduce
from itertools import permutations
from itertools import product
import sys
#sys.path.insert(0, "/Users/svjack/temp/ner_trans")
#sys.path.insert(0, "/temp/ner_trans")
from trans_emb_utils import *
from only_fix_script_ser import *
import difflib
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.corpus import wordnet
import sqlite_utils
'''
sys.path.insert(0, "../kbqa-explore/")
zh_linker_entities = load_pickle("../kbqa-explore/linker_entities.pkl")
'''
#sys.path.insert(0, "kbqa-explore/")
sys.path.insert(0, ".")
zh_linker_entities = load_pickle("kbqa-explore/linker_entities.pkl")
@timer()
def load_data():
train_df = pd.read_json("train.json")
test_df = pd.read_json("test.json")
lcquad_2_0_df = pd.read_json("lcquad_2_0.json")
df = pd.concat(list(map(lambda x: x[["question", "sparql_wikidata"]], [train_df, test_df, lcquad_2_0_df])), axis = 0).drop_duplicates()
df = df[["question", "sparql_wikidata"]]
df = df.dropna().drop_duplicates()
return df
@timer()
def load_property_info_df(dump_path = "property_info_df.pkl"):
if os.path.exists(dump_path):
return load_pickle(dump_path)
property_info_df = pd.read_json("property_info.json", lines = True)
property_info_s = property_info_df.apply(lambda x: list(filter(lambda y: not pd.isna(y) ,x.tolist()))[0], axis = 1)
property_info_df = pd.DataFrame(property_info_s.values.tolist())
property_info_df["info_dict"] = property_info_df["entities"].map(
lambda x: info_extracter(x)
)
property_info_df["en_info"] = property_info_df["info_dict"].map(
lambda x: x.get("en", [])
).map(lambda x: map(clean_single_str, x)).map(list).map(
lambda l: filter(lambda ele: not desc_matcher(ele), l)
).map(list)
property_info_df["zh_info"] = property_info_df["info_dict"].map(
lambda x: x.get("zh", [])
).map(lambda x: map(clean_single_str, x)).map(list).map(
lambda l: filter(lambda ele: not desc_matcher(ele), l)
).map(list)
property_info_df["pid"] = property_info_df["entities"].map(
lambda x: list(x.keys())[0]
)
property_info_df = property_info_df[["pid", "en_info", "zh_info"]]
save_pickle(
property_info_df, dump_path
)
return property_info_df
@timer()
def load_pid_relate_entity_df(generate_dict = True, dump_path = "pid_tuple_on_s_dict.pkl"):
if generate_dict and os.path.exists(dump_path):
return load_pickle(dump_path)
pid_relate_entity_df = pd.read_json("lcquad_pid_relate_entity.json")
#pid_relate_entity_df = pd.read_json("pid_relate_entity.json")
pid_relate_entity_df["pid"] = pid_relate_entity_df["l"].map(
lambda x: x["pid"]
)
pid_relate_entity_df["s"] = pid_relate_entity_df["l"].map(
lambda x: x["s"]
)
pid_relate_entity_df = pid_relate_entity_df[["pid", "s"]]
if generate_dict:
t2 = pid_relate_entity_df ,produce_pid_tuple_on_s_dict(pid_relate_entity_df)
save_pickle(
t2, dump_path
)
return t2
return pid_relate_entity_df
'''
[['"When position did Angela Merkel hold on November 10, 1994?"',
0,
'SELECT ?obj WHERE { wd:E1 p:R1 ?s . ?s ps:R1 ?obj . ?s ?p ?x filter(contains(?x, N)) }'],
['"What is the boiling point of pressure copper as 4703.0?"',
1,
'SELECT ?value WHERE { wd:E1 p:R1 ?s . ?s ps:R1 ?x filter(contains(?x, N)) . ?s ?p ?value }'],
['"When did Robert De Niro reside in Marbletown?"',
2,
'SELECT ?value WHERE { wd:E1 p:R1 ?s . ?s ps:R1 wd:E2 . ?s ?p ?value }'],
['"What are the coordinates for the geographic center of Michigan,
'as determined by the center of gravity of the surface?"',
3,
'SELECT ?obj WHERE { wd:E1 p:R1 ?s . ?s ps:R1 ?obj . ?s ?p wd:E2 }'],
['"How many dimensions have a Captain America?"',
4,
'SELECT (COUNT(?obj) AS ?value ) { wd:E1 wdt:R1 ?obj }'],
['"Which Class IB flammable liquid has the least lower flammable limit?"',
5,
'SELECT ?ent WHERE { ?ent wdt:P31 wd:T1 . ?ent wdt:R1 ?obj } ORDER BY ASC(?obj) LIMIT 5'],
['"Which member state of the International Centre for Settlement of Investment Disputes has the maximum inflation rate?"',
6,
'SELECT ?ent WHERE { ?ent wdt:P31 wd:T1 . ?ent wdt:R1 ?obj . ?ent wdt:R2 wd:E1 } ORDER BY ASC(?obj) LIMIT 5'],
['"What periodical literature does Delta Air Lines use as a moutpiece?"',
7,
'SELECT ?ent WHERE { wd:E1 wdt:R1 ?ent }']]
'''
wiki_prefix = '''
PREFIX bd: <http://www.bigdata.com/rdf#>
PREFIX cc: <http://creativecommons.org/ns#>
PREFIX dct: <http://purl.org/dc/terms/>
PREFIX geo: <http://www.opengis.net/ont/geosparql#>
PREFIX ontolex: <http://www.w3.org/ns/lemon/ontolex#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX p: <http://www.wikidata.org/prop/>
PREFIX pq: <http://www.wikidata.org/prop/qualifier/>
PREFIX pqn: <http://www.wikidata.org/prop/qualifier/value-normalized/>
PREFIX pqv: <http://www.wikidata.org/prop/qualifier/value/>
PREFIX pr: <http://www.wikidata.org/prop/reference/>
PREFIX prn: <http://www.wikidata.org/prop/reference/value-normalized/>
PREFIX prov: <http://www.w3.org/ns/prov#>
PREFIX prv: <http://www.wikidata.org/prop/reference/value/>
PREFIX ps: <http://www.wikidata.org/prop/statement/>
PREFIX psn: <http://www.wikidata.org/prop/statement/value-normalized/>
PREFIX psv: <http://www.wikidata.org/prop/statement/value/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX schema: <http://schema.org/>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdata: <http://www.wikidata.org/wiki/Special:EntityData/>
PREFIX wdno: <http://www.wikidata.org/prop/novalue/>
PREFIX wdref: <http://www.wikidata.org/reference/>
PREFIX wds: <http://www.wikidata.org/entity/statement/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX wdtn: <http://www.wikidata.org/prop/direct-normalized/>
PREFIX wdv: <http://www.wikidata.org/value/>
PREFIX wikibase: <http://wikiba.se/ontology#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
'''
prefix_s = pd.Series(wiki_prefix.split("\n")).map(
lambda x: x if x.startswith("PREFIX") else np.nan
).dropna().map(
lambda x: re.findall("PREFIX (.*): <", x)
).map(lambda x: x[0])
prefix_url_dict = dict(map(
lambda y: (y.split(" ")[1].replace(":", ""), y.split(" ")[2].strip()[1:-1])
,filter(
lambda x: x.strip()
, wiki_prefix.split("\n"))))
#### entity and property info get by http:
#### not recommand when import only_fix_script_sel SpawnProcess in NerFix pools slow.
re_format = r"{'language': '(.+?)', 'value': '(.+?)'}"
@timer()
def info_extracter(dict_str, lang_filter_list = ["en", "zh"], as_dict = True):
if type(dict_str) == type({}):
dict_str = str(dict_str)
df = pd.DataFrame(re.findall(re_format, dict_str), columns = ["lang", "val"])
df = df[
df["lang"].map(
lambda x: any(map(lambda y: x.lower().startswith(y), lang_filter_list))
)
]
df["lang"] = df["lang"].map(
lambda x: x[:2].lower()
)
df = df.drop_duplicates()
df = df.groupby("lang")["val"].apply(list).reset_index()
if as_dict:
return dict(df[["lang", "val"]].values.tolist())
return df
@timer()
def clean_single_str(str_):
return re.sub("[\((].*?[\))]", "", str_)
@timer()
def http_get_wiki_entity_property_info_by_id(id_):
#### id_, en_info, zh_info = http_get_wiki_entity_property_info_by_id("Q56599233")
#### id_, en_info, zh_info = http_get_wiki_entity_property_info_by_id("P10")
assert type(id_) == type("") and (id_.startswith("Q") or id_.startswith("P"))
url_format = "https://www.wikidata.org/wiki/Special:EntityData/{}.json"
pid_info_dict = pd.read_json(url_format.format(id_)).to_dict()
#return pid_info_dict
dict_str = str(pid_info_dict)
info_dict = info_extracter(dict_str)
zh_info = list(map(clean_single_str ,info_dict.get("zh", [])))
en_info = list(map(clean_single_str ,info_dict.get("en", [])))
return (id_, en_info, zh_info)
@timer()
def produce_data_dict_for_search(id_seed, dump_path = "info_data_dict.json"):
if os.path.exists(dump_path):
with open(dump_path, "r") as f:
data_dict = json.load(f)
else:
data_dict = {}
assert type(id_seed) == type([])
assert all(map(lambda x: x.startswith("Q") or x.startswith("P"), id_seed))
need_id_seed = list(filter(lambda id_: id_ not in data_dict, id_seed))
for id_ in need_id_seed:
try:
id_, en_info, zh_info = http_get_wiki_entity_property_info_by_id(id_)
except:
print("err : {}".format(id_))
continue
print(id_)
dump_ele = {
"en": en_info,
"zh": zh_info
}
data_dict[id_] = dump_ele
with open(dump_path, "w") as f:
json.dump(data_dict, f)
return data_dict
#### cp multi_lang_kb_dict.db produce by ner_trans
#### create table en_zh_so_search as select s, substr(o, 2, length(o) - 2) as o, lang from en_zh_so;
#### create index ss_index on en_zh_so_search (s);
#### create index oo_index on en_zh_so_search (o);
assert os.path.exists("multi_lang_kb_dict.db")
wiki_entity_db = sqlite_utils.Database("multi_lang_kb_dict.db")
assert "en_zh_so_search" in wiki_entity_db.table_names()
@timer()
def retrieve_all_kb_part(query, prefix_s, prefix_url_dict, fullfill_with_url = True):
req = prefix_s.map(
lambda x: ("{}:[PQ][0-9]+".format(x))
).map(
lambda y: re.findall(y, query)
).explode().dropna().drop_duplicates().tolist()
if fullfill_with_url:
req = pd.Series(req).map(
lambda x: prefix_url_dict[x.split(":")[0]] + x.split(":")[1]
).tolist()
return req
@timer()
def retrieve_all_kb_part_wide(query, prefix_s):
query_tokens = list(filter(lambda x:
x.strip() and "http" not in x
,re.split(r"[\{\} \.]", query)))
req = set([])
for token in query_tokens:
l = prefix_s.map(
lambda x: ("({}:.+)?".format(x))
).map(
lambda y: re.findall(y, token)
).explode().dropna().drop_duplicates().tolist()
for ele in l:
req.add(ele)
req = sorted(filter(lambda x: x.strip() ,req))
return req
@timer()
def find_query_direction_format(entity ,direction = "forw"):
#### "forw" :: entity format
#### "backw" :: attribute (prop) format
assert direction in ["forw", "backw"]
if direction == "forw":
query = [f"http://www.wikidata.org/entity/{entity}", "", ""]
else:
query = ["", "", f"http://www.wikidata.org/entity/{entity}"]
return query
@timer()
def one_part_g_producer(one_part_string,
format_ = "nt"
):
from uuid import uuid1
from rdflib import Graph
tmp_f_name = "{}.{}".format(uuid1(), format_)
with open(tmp_f_name, "w") as f:
f.write(one_part_string)
g = Graph()
g.parse(tmp_f_name, format=format_)
os.remove(tmp_f_name)
return g
@timer()
def py_dumpNtriple(
subject, predicate, object_
):
#### java rdfhdt dumpNtriple python format
out =[]
s0 = subject[0]
if s0=='_' or s0 =='<':
out.append(subject);
else:
out.append('<')
out.append(subject)
out.append('>')
p0 = predicate[0]
if p0=='<':
out.append(' ')
out.append(predicate)
out.append(' ');
else:
out.append(" <")
out.append(predicate)
out.append("> ")
o0 = object_[0]
if o0=='"':
#out.append(object_)
####
#UnicodeEscape.escapeString(object.toString(), out);
#out.append(json.dumps([object_])[1:-1])
out.append(object_)
out.append(" .\n");
elif o0=='_' or o0=='<':
out.append(object_)
out.append(" .\n")
else:
out.append('<')
out.append(object_)
out.append("> .\n")
return "".join(out)
#@lru_cache(maxsize=52428800)
@timer()
def search_triples_with_parse(source ,query, return_df = True, skip_some_o = True):
assert hasattr(source, "search_triples")
iter_, num = source.search_triples(*query)
req = []
for s, p, o in iter_:
o = fix_o(o)
if skip_some_o:
if "\n" in o:
continue
nt_str = py_dumpNtriple(s, p, o)
req.append(nt_str)
g = one_part_g_producer("".join(req))
if return_df:
return pd.DataFrame(g.__iter__(), columns = ["s", "p", "o"])
return g
@timer()
def desc_matcher(x):
return bool(re.findall(r"(P\d+)", x))
@timer()
def find_query_prop_format(prop, prop_format = "http://www.wikidata.org/prop/direct/{}"):
query = ["", prop_format.format(prop), ""]
return query
@timer()
def entity_property_search(prop):
direct_df, statement_df, prop_df = [None] * 3
try:
direct_df = search_triples_with_parse(
wiki_parser.document,
find_query_prop_format(prop, "http://www.wikidata.org/prop/direct/{}"), limit = 10240)
except:
direct_df = pd.DataFrame(columns = ["s", "p", "o"])
pass
try:
statement_df = search_triples_with_parse(
wiki_parser.document,
find_query_prop_format(prop, "http://www.wikidata.org/prop/statement/{}"), limit = 10240)
except:
statement_df = pd.DataFrame(columns = ["s", "p", "o"])
try:
prop_df = search_triples_with_parse(
wiki_parser.document,
find_query_prop_format(prop, "http://www.wikidata.org/prop/{}"), limit = 10240)
except:
prop_df = pd.DataFrame(columns = ["s", "p", "o"])
def row_filter(t3_row):
s, p, o = t3_row
s = str(s)
o_s = str(o)
s_sp = s.split("/")
os_sp = o_s.split("/")
return (len(s_sp) >= 2 and s_sp[-2] == "entity" and "entity/Q" in s and len(os_sp) >= 2 and os_sp[-1].startswith("Q")) or (hasattr(o, "language") and type(o.language) == type("") and "zh" in o.language)
direct_df, statement_df, prop_df = map(lambda x: x[
x.apply(row_filter, axis = 1)
], [direct_df, statement_df, prop_df])
all_s_entity = pd.Series(direct_df["s"].tolist() + statement_df["s"].tolist() + prop_df["s"].tolist()).map(
lambda x: str(x).split("/")[-1] if "entity/Q" in str(x) and str(x).split("/")[-1].startswith("Q") else np.nan
).dropna().drop_duplicates()
all_o_entity = pd.Series(direct_df["o"].tolist() + statement_df["o"].tolist() + prop_df["o"].tolist()).map(
lambda x: str(x).split("/")[-1] if "entity/Q" in str(x) and str(x).split("/")[-1].startswith("Q") else np.nan
).dropna().drop_duplicates()
####return all_s_entity
err_ = []
all_s_zh = []
for ele in all_s_entity:
try:
t_ele = search_triples_with_parse(
wiki_parser.document,
find_query_direction_format(ele, direction="forw"))["o"].map(
lambda x: str(x) if hasattr(x, "language") and type(x.language) == type("") and "zh" in x.language else np.nan
).dropna().drop_duplicates().tolist()
all_s_zh.append(t_ele)
except:
err_.append(ele)
all_s_zh = pd.Series(all_s_zh).explode().dropna().drop_duplicates()
all_o_zh = []
for ele in all_o_entity:
try:
t_ele = search_triples_with_parse(
wiki_parser.document,
find_query_direction_format(ele, direction="forw"))["o"].map(
lambda x: str(x) if hasattr(x, "language") and type(x.language) == type("") and "zh" in x.language else np.nan
).dropna().drop_duplicates().tolist()
all_o_zh.append(t_ele)
except:
err_.append(ele)
all_o_zh = pd.Series(all_o_zh).explode().dropna().drop_duplicates()
return (direct_df, statement_df, prop_df, all_s_zh, all_o_zh, err_)
@timer()
def fix_o(o, rm_char = ["\\"]):
if not o.startswith('"'):
return o
#print(o)
assert o.startswith('"')
num = []
for i in range(len(o)):
c = o[i]
if c == '"':
num.append(i)
assert len(num) >= 2
rm_num = num[1:-1]
return "".join(
map(lambda ii: o[ii], filter(lambda i: i not in rm_num and o[i] not in rm_char, range(len(o))))
)
@timer()
def one_part_g_producer(one_part_string,
format_ = "nt"
):
from uuid import uuid1
from rdflib import Graph
tmp_f_name = "{}.{}".format(uuid1(), format_)
with open(tmp_f_name, "w") as f:
f.write(one_part_string)
g = Graph()
g.parse(tmp_f_name, format=format_)
os.remove(tmp_f_name)
return g
'''
wiki_parser = WikiParser(
wiki_filename = "/Users/svjack/.deeppavlov/downloads/wikidata/wikidata.hdt",
lang = "",
)
'''
###/Volumes/TOSHIBA EXT/temp/.deeppavlov/downloads/wikidata
'''
wiki_parser = WikiParser(
wiki_filename = "/Volumes/TOSHIBA EXT/temp/.deeppavlov/downloads/wikidata/wikidata.hdt",
lang = "",
)
'''
wiki_parser = WikiParser(
wiki_filename = "kbqa-explore/wikidata.hdt",
lang = "",
)
re_format = r"{'language': '(.+?)', 'value': '(.+?)'}"
@timer()
def info_extracter(dict_str, lang_filter_list = ["en", "zh"], as_dict = True):
if type(dict_str) == type({}):
dict_str = str(dict_str)
df = pd.DataFrame(re.findall(re_format, dict_str), columns = ["lang", "val"])
df = df[
df["lang"].map(
lambda x: any(map(lambda y: x.lower().startswith(y), lang_filter_list))
)
]
df["lang"] = df["lang"].map(
lambda x: x[:2].lower()
)
df = df.drop_duplicates()
df = df.groupby("lang")["val"].apply(list).reset_index()
if as_dict:
return dict(df[["lang", "val"]].values.tolist())
return df
@timer()
def clean_single_str(str_):
return re.sub("[\((].*?[\))]", "", str_)
@timer()
def merge_nest_list(nest_list, threshold = 0):
req = []
for ele in nest_list:
if not req:
req.extend(ele)
else:
b, e = ele
if b - req[-1] <= threshold:
req.append(e)
return [req[0], req[-1]]
@timer()
def get_match_blk_by_diff(a, b, filter_size = 0,
threshold = 0
):
s = difflib.SequenceMatcher(lambda x: None,
a,
b)
m_blocks = list(filter(lambda m: m.size > filter_size,
s.get_matching_blocks()))
def m_block_to_b(m_blocks):
b_part = list(map(lambda m: [m.b, m.b + m.size], m_blocks))
return b_part
b_part = m_block_to_b(m_blocks)
if not b_part:
return ""
bb, ee = merge_nest_list(b_part, threshold=threshold)
return b[bb:ee]
@timer()
def get_match_blk(a, b, threshold_bnd = [0, 10], match_first_end = True):
'''
get_match_blk("成交楼面均价", "平均溢价率小于10的成交楼面平均价格是多少")
'''
req_list = []
for thre in range(threshold_bnd[0], threshold_bnd[-1]):
ret = get_match_blk_by_diff(a, b, threshold=thre)
#print("ret :", ret)
if ret and ret in b:
req_list.append(ret)
if ret:
if match_first_end:
if ret.startswith(a[0]) and ret.endswith(a[-1]):
req_list.append(ret)
else:
req_list.append(ret)
#print("req_list :", req_list)
if req_list:
first_ele = sorted(req_list, key=lambda x: -1 * len(x))[0]
if fuzz.ratio(first_ele.lower(), a.lower()) >= 50:
return first_ele
ele_a, ele_a_score = cut_compare(first_ele.lower(), a.lower())
if ele_a_score > 0.7:
return first_ele
return None
@timer()
def get_match_intersection(a, b, threshold_bnd = [0, 5], match_first_end = True):
'''
get_match_blk("成交楼面均价", "平均溢价率小于10的成交楼面平均价格是多少")
'''
req_list = []
for thre in range(threshold_bnd[0], threshold_bnd[-1]):
ret = get_match_blk_by_diff(a, b, threshold=thre)
#print("ret :", ret)
if ret and ret in b:
req_list.append(ret)
if ret:
if match_first_end:
if ret.startswith(a[0]) and ret.endswith(a[-1]):
req_list.append(ret)
else:
req_list.append(ret)
#print("req_list :", req_list)
if req_list:
first_ele = sorted(req_list, key=lambda x: -1 * len(x))[0]
return first_ele
return None
@timer()
def get_match_intersection_fill_gap(a, b, c,
threshold_bnd = [0, 5],
match_first_end = True,
):
x = get_match_intersection(a, b, threshold_bnd = threshold_bnd, match_first_end = match_first_end)
return x
if type(x) != type("") or len(x.strip()) == 0:
return x
assert type(x) == type("")
if x not in c:
return x
def process_token(token, rm_char_list = ["?"]):
for rm_c in rm_char_list:
token = token.replace(rm_c, "")
return token
c_x_sp = c.split(x)
assert len(c_x_sp) >= 2
c_x_sp_ = []
for idx in range(len(c_x_sp)):
if idx in [0, len(c_x_sp) - 1]:
c_x_sp_.append(c_x_sp[idx])
else:
xx = c_x_sp[idx]
xx = x if not xx else xx
c_x_sp_.append(xx)
c_x_sp = c_x_sp_
c_x_sp_l = pd.Series(unzip_string(c_x_sp)).map(
lambda t2: (
t2[0].split(" ")[-1] if t2[0].strip() else t2[0],
t2[1].split(" ")[0] if t2[1].strip() else t2[1]
)
).map(
lambda tt2: (process_token(tt2[0]), process_token(tt2[1]))
).map(
lambda ttt2: ttt2[0] + x + ttt2[1]
).map(
lambda y: y.strip()
).tolist()
assert c_x_sp_l
req = sorted(c_x_sp_l, key = len)[0]
assert req in c
assert phrase_validation(c, req)
return req
@timer()
def generate_score_percentile_slice(score_df, score_col = "fuzz", threshold = 5):
max_score = score_df[score_col].max()
max_ratio = int((score_df[score_df[score_col] == max_score].shape[0] / score_df.shape[0]) * 100)
threshold = max(threshold, max_ratio)
score_p = np.percentile(score_df[score_col].values, 100 - threshold)
return score_df[
score_df[score_col] >= score_p
]
@timer()
def sent_list_match_to_df(en_sent, l, slice_by_perc_head = True):
assert type(en_sent) == type("")
assert type(l) == type([])
assert bool(l)
df = pd.DataFrame(
pd.Series(l).map(
lambda x: (x ,get_match_intersection_fill_gap(en_sent, x, en_sent))
).values.tolist()
)
df.columns = ["string", "inter_str"]
df = df[
df.apply(lambda x: None not in x.tolist() and
all(map(lambda y: bool(y.strip()), x))
, axis = 1)
]
if not df.size:
return None
df["score"] = df.apply(lambda s: fuzz.ratio(*s.tolist()), axis = 1)
req = df.sort_values(by = "score", ascending = False)
if slice_by_perc_head:
return generate_score_percentile_slice(req, "score", 1)
return req
@timer()
def sent_list_match_to_df_with_bnd(en_sent, l, slice_by_perc_head = True, upper_bnd = 5):
assert upper_bnd > 0
assert type(en_sent) == type("")
assert type(l) == type([])
assert bool(l)
df = pd.DataFrame(
pd.Series(l).map(
lambda x: (x ,get_match_intersection_fill_gap(en_sent, x, en_sent, threshold_bnd = [0, upper_bnd]))
).values.tolist()
)
df.columns = ["string", "inter_str"]
df = df[
df.apply(lambda x: None not in x.tolist() and
all(map(lambda y: bool(y.strip()), x))
, axis = 1)
]
if not df.size:
return None
df["score"] = df.apply(lambda s: fuzz.ratio(*s.tolist())
, axis = 1)
req = df.sort_values(by = "score", ascending = False)
if slice_by_perc_head:
return generate_score_percentile_slice(req, "score", 1)
return req
@timer()
def sent_list_match_to_df_bnd_cat(
en_sent, l, slice_by_perc_head = True, upper_bnd = 5,
length_ratio_threshold = 0.5
):
assert upper_bnd > 0
req = []
for i in range(1, upper_bnd):
df = sent_list_match_to_df_with_bnd(
en_sent,
l
, False, i
)
if not hasattr(df, "size") or df.size == 0:
continue
df["bnd"] = i
df["in_sent"] = df["inter_str"].map(lambda x: x in en_sent)
df["is_phrase"] = df["inter_str"].map(
lambda x: phrase_validation(en_sent, x.strip()) if (en_sent.strip() and x.strip()) else False
)
req.append(df)
if not req:
return None
df = pd.concat(req, axis = 0).sort_values(by = ["is_phrase", "in_sent", "score"],
ascending = False)
df = drop_duplicates_by_col(df, "string")[["string", "inter_str", "score"]]
df["fuzz"] = df["score"]
df["score"] = df.shape[0] - np.arange(df.shape[0])
df_tmp = df.copy()
df_tmp["inter_str_ratio"] = df_tmp.apply(lambda x: len(x["inter_str"]) / len(x["string"]), axis = 1)
df_tmp = df_tmp[
df_tmp["inter_str_ratio"] >= length_ratio_threshold
]
if df_tmp.size > 0:
df = df_tmp
else:
pass
df = df[["string", "inter_str", "score"]]
req = df
if slice_by_perc_head:
return generate_score_percentile_slice(req, "score", 1)
return df
@timer()
def lemmatize_one_token(token, wn = WordNetLemmatizer(),
all_stem_keys = list(wordnet.MORPHOLOGICAL_SUBSTITUTIONS.keys()),
major_key = "v"
):
assert type(token) == type("")
assert major_key in all_stem_keys
major_token = wn.lemmatize(token, major_key)
if major_token != token:
return major_token
return sorted(map(lambda k: wn.lemmatize(token, k),
set(all_stem_keys).difference(
set([major_key])
)
),
key = len
)[0]
@timer()
def lemma_score_match_it(en_sent, en_info, wn = WordNetLemmatizer(),
slice_by_perc_head = True
):
sent_trans = " ".join(list(filter(lambda x: x.strip() ,
map(lambda y:
lemmatize_one_token(process_token(y))
,en_sent.split(" "))
)
))
sent_info_match_df = sent_list_match_to_df_bnd_cat(en_sent, en_info, False)
#sent_info_match_df = sent_list_match_to_df(en_sent, en_info, False)
if sent_info_match_df is None or not sent_info_match_df.size:
return None
sent_info_match_df["is_in"] = sent_info_match_df.apply(
lambda s:
lemmatize_one_token(sorted(filter(lambda x: x.strip() ,
s["inter_str"].strip().split(" ")), key = len, reverse = True)[0]) in sent_trans if\
sorted(filter(lambda x: x.strip() ,
s["inter_str"].strip().split(" ")), key = len, reverse = True) else False
, axis = 1
)
sent_info_match_df["is_phrase"] = sent_info_match_df.apply(
lambda s: phrase_validation(s["string"].strip(), s["inter_str"].strip()), axis = 1
)
sent_info_match_df = sent_info_match_df.sort_values(
by = ["is_phrase", "is_in", "score"], ascending = False
)
if not sent_info_match_df.size:
return None
if slice_by_perc_head:
return sent_info_match_df.head(1)
return sent_info_match_df
@timer()
def guess_sim_representation(en_sent, entity_prop_dict, retrieve_top1 = True,
use_lemma = True
):
assert type(en_sent) == type("")
assert type(entity_prop_dict) == type({})
req_entity_prop_dict = {}
for k, v in entity_prop_dict.items():
assert type(v) == type([])
if use_lemma:
req_entity_prop_dict[k] = lemma_score_match_it(en_sent, v, slice_by_perc_head = True)
else:
req_entity_prop_dict[k] = sent_list_match_to_df_bnd_cat(en_sent, v, True)
#req_entity_prop_dict[k] = sent_list_match_to_df(en_sent, v, True)
req = {}
for k in req_entity_prop_dict.keys():
if req_entity_prop_dict[k] is None:
continue
else:
assert hasattr(req_entity_prop_dict[k], "size")
assert req_entity_prop_dict[k].size > 0
req_entity_prop_dict[k]["fuzz"] = req_entity_prop_dict[k]["string"].map(
lambda x: fuzz.ratio(en_sent, x)
)
req_entity_prop_dict[k]["fuzz_score"] = req_entity_prop_dict[k].apply(
lambda s: s["fuzz"] * s["score"]
, axis = 1)
req_entity_prop_dict[k] = req_entity_prop_dict[k].sort_values(
by = "fuzz_score", ascending = False
)
if retrieve_top1:
req_entity_prop_dict[k] = req_entity_prop_dict[k][["string", "inter_str"]].iloc[0].tolist()
req[k] = req_entity_prop_dict[k]
return req
#return req_entity_prop_dict
@timer()
def guess_sim_representation_by_score(en_sent, entity_prop_dict, agg_func = sum):
use_lemma_dict = guess_sim_representation(en_sent, entity_prop_dict, use_lemma = True)
ori_dict = guess_sim_representation(en_sent, entity_prop_dict, use_lemma = False)
if not use_lemma_dict:
if ori_dict:
return ori_dict
if not ori_dict:
if use_lemma_dict:
return use_lemma_dict
if not ori_dict and not use_lemma_dict:
return {}
def process_token(token, rm_char_list = ["?"]):
for rm_c in rm_char_list:
token = token.replace(rm_c, "")
return token
sent_tokens = list(filter(lambda x: lemmatize_one_token(x.strip().lower()) ,
map(lambda y: process_token(y) ,en_sent.split(" "))
)
)
#print(sent_tokens)
def dict_to_set(dict_):
dict_s = set(reduce(lambda a, b:a + b ,dict_.values()))
dict_s = set(map(lambda y: y.lower() ,
reduce(lambda a, b : a + b ,map(lambda x: x.split(" "),
dict_s))))
dict_s = set(map(lemmatize_one_token, dict_s))
return dict_s
use_lemma_score = agg_func(map(lambda y: fuzz.ratio(y[0], y[1])
,filter(lambda x: len(x) == 2 ,use_lemma_dict.values())))
use_lemma_s = dict_to_set(use_lemma_dict)
#use_lemma_cnt = len(list(filter(lambda x: x in use_lemma_s, sent_tokens)))
#use_lemma_cnt = max(map(lambda y: max(map(lambda z: fuzz.ratio(y, z), use_lemma_s)), sent_tokens))
use_lemma_cnt = sum(map(lambda y: max(map(lambda z: fuzz.ratio(y, z), use_lemma_s)), sent_tokens))
use_lemma_score = use_lemma_cnt * use_lemma_score
#print(use_lemma_dict, use_lemma_s ,use_lemma_cnt, use_lemma_score)
ori_score = agg_func(map(lambda y: fuzz.ratio(y[0], y[1])
,filter(lambda x: len(x) == 2 ,ori_dict.values())))
ori_s = dict_to_set(ori_dict)
#ori_cnt = len(list(filter(lambda x: x in ori_s, sent_tokens)))
#ori_cnt = max(map(lambda y: max(map(lambda z: fuzz.ratio(y, z), ori_s)), sent_tokens))
ori_cnt = sum(map(lambda y: max(map(lambda z: fuzz.ratio(y, z), ori_s)), sent_tokens))
ori_score = ori_cnt * ori_score
#print(ori_dict, ori_s ,ori_cnt, ori_score)
return use_lemma_dict if use_lemma_score > ori_score else ori_dict
@timer()
def map_reduce_guess_sim_representation_by_score(en_sent, entity_prop_dict):
dict__ = {}
entity_prop_dict = deepcopy(entity_prop_dict)
entity_prop_dict_ = {}
for k, v in entity_prop_dict.items():
assert type(v) == type([])
v_in = list(filter(lambda x: x in en_sent, v))
if v_in:
v_in_ele = sorted(v_in, key = len, reverse = True)[0]
assert type(v_in_ele) == type("")
dict__[k] = [v_in_ele, v_in_ele]
else:
entity_prop_dict_[k] = v
entity_prop_dict = entity_prop_dict_
if entity_prop_dict:
req = {}
for k, v in entity_prop_dict.items():
assert type(v) == type([])
req[k] = list(map(lambda x: x.lower(), v))
dict_lower = dict(reduce(lambda a, b: a + b ,map(lambda x:
list(guess_sim_representation_by_score(en_sent ,dict([x])).items())
,req.items())))
#print("dict_lower :")
#print(dict_lower)
dict_ = dict(reduce(lambda a, b: a + b ,map(lambda x:
list(guess_sim_representation_by_score(en_sent ,dict([x])).items())
,entity_prop_dict.items())))
#print("dict_ :")
#print(dict_)
all_keys_set = set(dict_lower.keys()).union(set(dict_.keys()))
dict_emp = {}
dict_lower_emp = {}
for k in all_keys_set:
v_ = dict_.get(k, None)