forked from taoyds/spider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluation.py
1174 lines (986 loc) · 33.8 KB
/
evaluation.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
################################
# val: number(float)/string(str)/sql(dict)
# col_unit: (agg_id, col_id, isDistinct(bool))
# val_unit: (unit_op, col_unit1, col_unit2)
# table_unit: (table_type, col_unit/sql)
# cond_unit: (not_op, op_id, val_unit, val1, val2)
# condition: [cond_unit1, 'and'/'or', cond_unit2, ...]
# sql {
# 'select': (isDistinct(bool), [(agg_id, val_unit), (agg_id, val_unit), ...])
# 'from': {'table_units': [table_unit1, table_unit2, ...], 'conds': condition}
# 'where': condition
# 'groupBy': [col_unit1, col_unit2, ...]
# 'orderBy': ('asc'/'desc', [val_unit1, val_unit2, ...])
# 'having': condition
# 'limit': None/limit value
# 'intersect': None/sql
# 'except': None/sql
# 'union': None/sql
# }
################################
from __future__ import print_function
import os, sys
import json
import sqlite3
import traceback
import argparse
from process_sql import (
tokenize,
get_schema,
get_tables_with_alias,
Schema,
get_sql,
scan_alias,
)
# Flag to disable value evaluation
DISABLE_VALUE = True
# Flag to disable distinct in select evaluation
DISABLE_DISTINCT = True
CLAUSE_KEYWORDS = (
"select",
"from",
"where",
"group",
"order",
"limit",
"intersect",
"union",
"except",
)
JOIN_KEYWORDS = ("join", "on", "as")
WHERE_OPS = (
"not",
"between",
"=",
">",
"<",
">=",
"<=",
"!=",
"in",
"like",
"is",
"exists",
)
UNIT_OPS = ("none", "-", "+", "*", "/")
AGG_OPS = ("none", "max", "min", "count", "sum", "avg")
TABLE_TYPE = {
"sql": "sql",
"table_unit": "table_unit",
}
COND_OPS = ("and", "or")
SQL_OPS = ("intersect", "union", "except")
ORDER_OPS = ("desc", "asc")
HARDNESS = {
"component1": ("where", "group", "order", "limit", "join", "or", "like"),
"component2": ("except", "union", "intersect"),
}
def condition_has_or(conds):
return "or" in conds[1::2]
def condition_has_like(conds):
return WHERE_OPS.index("like") in [cond_unit[1] for cond_unit in conds[::2]]
def condition_has_sql(conds):
for cond_unit in conds[::2]:
val1, val2 = cond_unit[3], cond_unit[4]
if val1 is not None and type(val1) is dict:
return True
if val2 is not None and type(val2) is dict:
return True
return False
def val_has_op(val_unit):
return val_unit[0] != UNIT_OPS.index("none")
def has_agg(unit):
return unit[0] != AGG_OPS.index("none")
def accuracy(count, total):
if count == total:
return 1
return 0
def recall(count, total):
if count == total:
return 1
return 0
def F1(acc, rec):
if (acc + rec) == 0:
return 0
return (2.0 * acc * rec) / (acc + rec)
def get_scores(count, pred_total, label_total):
if pred_total != label_total:
return 0, 0, 0
elif count == pred_total:
return 1, 1, 1
return 0, 0, 0
def eval_sel(pred, label):
pred_sel = pred["select"][1]
label_sel = label["select"][1]
label_wo_agg = [unit[1] for unit in label_sel]
pred_total = len(pred_sel)
label_total = len(label_sel)
cnt = 0
cnt_wo_agg = 0
for unit in pred_sel:
if unit in label_sel:
cnt += 1
label_sel.remove(unit)
if unit[1] in label_wo_agg:
cnt_wo_agg += 1
label_wo_agg.remove(unit[1])
return label_total, pred_total, cnt, cnt_wo_agg
def eval_where(pred, label):
pred_conds = [unit for unit in pred["where"][::2]]
label_conds = [unit for unit in label["where"][::2]]
label_wo_agg = [unit[2] for unit in label_conds]
pred_total = len(pred_conds)
label_total = len(label_conds)
cnt = 0
cnt_wo_agg = 0
for unit in pred_conds:
if unit in label_conds:
cnt += 1
label_conds.remove(unit)
if unit[2] in label_wo_agg:
cnt_wo_agg += 1
label_wo_agg.remove(unit[2])
return label_total, pred_total, cnt, cnt_wo_agg
def eval_group(pred, label):
pred_cols = [unit[1] for unit in pred["groupBy"]]
label_cols = [unit[1] for unit in label["groupBy"]]
pred_total = len(pred_cols)
label_total = len(label_cols)
cnt = 0
pred_cols = [pred.split(".")[1] if "." in pred else pred for pred in pred_cols]
label_cols = [
label.split(".")[1] if "." in label else label for label in label_cols
]
for col in pred_cols:
if col in label_cols:
cnt += 1
label_cols.remove(col)
return label_total, pred_total, cnt
def eval_having(pred, label):
pred_total = label_total = cnt = 0
if len(pred["groupBy"]) > 0:
pred_total = 1
if len(label["groupBy"]) > 0:
label_total = 1
pred_cols = [unit[1] for unit in pred["groupBy"]]
label_cols = [unit[1] for unit in label["groupBy"]]
if (
pred_total == label_total == 1
and pred_cols == label_cols
and pred["having"] == label["having"]
):
cnt = 1
return label_total, pred_total, cnt
def eval_order(pred, label):
pred_total = label_total = cnt = 0
if len(pred["orderBy"]) > 0:
pred_total = 1
if len(label["orderBy"]) > 0:
label_total = 1
if (
len(label["orderBy"]) > 0
and pred["orderBy"] == label["orderBy"]
and (
(pred["limit"] is None and label["limit"] is None)
or (pred["limit"] is not None and label["limit"] is not None)
)
):
cnt = 1
return label_total, pred_total, cnt
def eval_and_or(pred, label):
pred_ao = pred["where"][1::2]
label_ao = label["where"][1::2]
pred_ao = set(pred_ao)
label_ao = set(label_ao)
if pred_ao == label_ao:
return 1, 1, 1
return len(pred_ao), len(label_ao), 0
def get_nestedSQL(sql):
nested = []
for cond_unit in sql["from"]["conds"][::2] + sql["where"][::2] + sql["having"][::2]:
if type(cond_unit[3]) is dict:
nested.append(cond_unit[3])
if type(cond_unit[4]) is dict:
nested.append(cond_unit[4])
if sql["intersect"] is not None:
nested.append(sql["intersect"])
if sql["except"] is not None:
nested.append(sql["except"])
if sql["union"] is not None:
nested.append(sql["union"])
return nested
def eval_nested(pred, label):
label_total = 0
pred_total = 0
cnt = 0
if pred is not None:
pred_total += 1
if label is not None:
label_total += 1
if pred is not None and label is not None:
cnt += Evaluator().eval_exact_match(pred, label)
return label_total, pred_total, cnt
def eval_IUEN(pred, label):
lt1, pt1, cnt1 = eval_nested(pred["intersect"], label["intersect"])
lt2, pt2, cnt2 = eval_nested(pred["except"], label["except"])
lt3, pt3, cnt3 = eval_nested(pred["union"], label["union"])
label_total = lt1 + lt2 + lt3
pred_total = pt1 + pt2 + pt3
cnt = cnt1 + cnt2 + cnt3
return label_total, pred_total, cnt
def get_keywords(sql):
res = set()
if len(sql["where"]) > 0:
res.add("where")
if len(sql["groupBy"]) > 0:
res.add("group")
if len(sql["having"]) > 0:
res.add("having")
if len(sql["orderBy"]) > 0:
res.add(sql["orderBy"][0])
res.add("order")
if sql["limit"] is not None:
res.add("limit")
if sql["except"] is not None:
res.add("except")
if sql["union"] is not None:
res.add("union")
if sql["intersect"] is not None:
res.add("intersect")
# or keyword
ao = sql["from"]["conds"][1::2] + sql["where"][1::2] + sql["having"][1::2]
if len([token for token in ao if token == "or"]) > 0:
res.add("or")
cond_units = sql["from"]["conds"][::2] + sql["where"][::2] + sql["having"][::2]
# not keyword
if len([cond_unit for cond_unit in cond_units if cond_unit[0]]) > 0:
res.add("not")
# in keyword
if (
len(
[
cond_unit
for cond_unit in cond_units
if cond_unit[1] == WHERE_OPS.index("in")
]
)
> 0
):
res.add("in")
# like keyword
if (
len(
[
cond_unit
for cond_unit in cond_units
if cond_unit[1] == WHERE_OPS.index("like")
]
)
> 0
):
res.add("like")
return res
def eval_keywords(pred, label):
pred_keywords = get_keywords(pred)
label_keywords = get_keywords(label)
pred_total = len(pred_keywords)
label_total = len(label_keywords)
cnt = 0
for k in pred_keywords:
if k in label_keywords:
cnt += 1
return label_total, pred_total, cnt
def count_agg(units):
return len([unit for unit in units if has_agg(unit)])
def count_component1(sql):
count = 0
if len(sql["where"]) > 0:
count += 1
if len(sql["groupBy"]) > 0:
count += 1
if len(sql["orderBy"]) > 0:
count += 1
if sql["limit"] is not None:
count += 1
if len(sql["from"]["table_units"]) > 0: # JOIN
count += len(sql["from"]["table_units"]) - 1
ao = sql["from"]["conds"][1::2] + sql["where"][1::2] + sql["having"][1::2]
count += len([token for token in ao if token == "or"])
cond_units = sql["from"]["conds"][::2] + sql["where"][::2] + sql["having"][::2]
count += len(
[
cond_unit
for cond_unit in cond_units
if cond_unit[1] == WHERE_OPS.index("like")
]
)
return count
def count_component2(sql):
nested = get_nestedSQL(sql)
return len(nested)
def count_others(sql):
count = 0
# number of aggregation
agg_count = count_agg(sql["select"][1])
agg_count += count_agg(sql["where"][::2])
agg_count += count_agg(sql["groupBy"])
if len(sql["orderBy"]) > 0:
agg_count += count_agg(
[unit[1] for unit in sql["orderBy"][1] if unit[1]]
+ [unit[2] for unit in sql["orderBy"][1] if unit[2]]
)
agg_count += count_agg(sql["having"])
if agg_count > 1:
count += 1
# number of select columns
if len(sql["select"][1]) > 1:
count += 1
# number of where conditions
if len(sql["where"]) > 1:
count += 1
# number of group by clauses
if len(sql["groupBy"]) > 1:
count += 1
return count
class Evaluator:
"""A simple evaluator"""
def __init__(self):
self.partial_scores = None
def eval_hardness(self, sql):
count_comp1_ = count_component1(sql)
count_comp2_ = count_component2(sql)
count_others_ = count_others(sql)
if count_comp1_ <= 1 and count_others_ == 0 and count_comp2_ == 0:
return "easy"
elif (count_others_ <= 2 and count_comp1_ <= 1 and count_comp2_ == 0) or (
count_comp1_ <= 2 and count_others_ < 2 and count_comp2_ == 0
):
return "medium"
elif (
(count_others_ > 2 and count_comp1_ <= 2 and count_comp2_ == 0)
or (2 < count_comp1_ <= 3 and count_others_ <= 2 and count_comp2_ == 0)
or (count_comp1_ <= 1 and count_others_ == 0 and count_comp2_ <= 1)
):
return "hard"
else:
return "extra"
def eval_exact_match(self, pred, label):
partial_scores = self.eval_partial_match(pred, label)
self.partial_scores = partial_scores
for _, score in partial_scores.items():
if score["f1"] != 1:
return 0
if len(label["from"]["table_units"]) > 0:
label_tables = sorted(label["from"]["table_units"])
pred_tables = sorted(pred["from"]["table_units"])
return label_tables == pred_tables
return 1
def eval_partial_match(self, pred, label):
res = {}
label_total, pred_total, cnt, cnt_wo_agg = eval_sel(pred, label)
acc, rec, f1 = get_scores(cnt, pred_total, label_total)
res["select"] = {
"acc": acc,
"rec": rec,
"f1": f1,
"label_total": label_total,
"pred_total": pred_total,
}
acc, rec, f1 = get_scores(cnt_wo_agg, pred_total, label_total)
res["select(no AGG)"] = {
"acc": acc,
"rec": rec,
"f1": f1,
"label_total": label_total,
"pred_total": pred_total,
}
label_total, pred_total, cnt, cnt_wo_agg = eval_where(pred, label)
acc, rec, f1 = get_scores(cnt, pred_total, label_total)
res["where"] = {
"acc": acc,
"rec": rec,
"f1": f1,
"label_total": label_total,
"pred_total": pred_total,
}
acc, rec, f1 = get_scores(cnt_wo_agg, pred_total, label_total)
res["where(no OP)"] = {
"acc": acc,
"rec": rec,
"f1": f1,
"label_total": label_total,
"pred_total": pred_total,
}
label_total, pred_total, cnt = eval_group(pred, label)
acc, rec, f1 = get_scores(cnt, pred_total, label_total)
res["group(no Having)"] = {
"acc": acc,
"rec": rec,
"f1": f1,
"label_total": label_total,
"pred_total": pred_total,
}
label_total, pred_total, cnt = eval_having(pred, label)
acc, rec, f1 = get_scores(cnt, pred_total, label_total)
res["group"] = {
"acc": acc,
"rec": rec,
"f1": f1,
"label_total": label_total,
"pred_total": pred_total,
}
label_total, pred_total, cnt = eval_order(pred, label)
acc, rec, f1 = get_scores(cnt, pred_total, label_total)
res["order"] = {
"acc": acc,
"rec": rec,
"f1": f1,
"label_total": label_total,
"pred_total": pred_total,
}
label_total, pred_total, cnt = eval_and_or(pred, label)
acc, rec, f1 = get_scores(cnt, pred_total, label_total)
res["and/or"] = {
"acc": acc,
"rec": rec,
"f1": f1,
"label_total": label_total,
"pred_total": pred_total,
}
label_total, pred_total, cnt = eval_IUEN(pred, label)
acc, rec, f1 = get_scores(cnt, pred_total, label_total)
res["IUEN"] = {
"acc": acc,
"rec": rec,
"f1": f1,
"label_total": label_total,
"pred_total": pred_total,
}
label_total, pred_total, cnt = eval_keywords(pred, label)
acc, rec, f1 = get_scores(cnt, pred_total, label_total)
res["keywords"] = {
"acc": acc,
"rec": rec,
"f1": f1,
"label_total": label_total,
"pred_total": pred_total,
}
return res
def isValidSQL(sql, db):
conn = sqlite3.connect(db)
cursor = conn.cursor()
try:
cursor.execute(sql)
except:
return False
return True
def print_scores(scores, etype):
levels = ["easy", "medium", "hard", "extra", "all"]
partial_types = [
"select",
"select(no AGG)",
"where",
"where(no OP)",
"group(no Having)",
"group",
"order",
"and/or",
"IUEN",
"keywords",
]
print("{:20} {:20} {:20} {:20} {:20} {:20}".format("", *levels))
counts = [scores[level]["count"] for level in levels]
print("{:20} {:<20d} {:<20d} {:<20d} {:<20d} {:<20d}".format("count", *counts))
if etype in ["all", "exec"]:
print("===================== EXECUTION ACCURACY =====================")
this_scores = [scores[level]["exec"] for level in levels]
print(
"{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format(
"execution", *this_scores
)
)
if etype in ["all", "match"]:
print("\n====================== EXACT MATCHING ACCURACY =====================")
exact_scores = [scores[level]["exact"] for level in levels]
print(
"{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format(
"exact match", *exact_scores
)
)
print("\n---------------------PARTIAL MATCHING ACCURACY----------------------")
for type_ in partial_types:
this_scores = [scores[level]["partial"][type_]["acc"] for level in levels]
print(
"{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format(
type_, *this_scores
)
)
print("---------------------- PARTIAL MATCHING RECALL ----------------------")
for type_ in partial_types:
this_scores = [scores[level]["partial"][type_]["rec"] for level in levels]
print(
"{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format(
type_, *this_scores
)
)
print("---------------------- PARTIAL MATCHING F1 --------------------------")
for type_ in partial_types:
this_scores = [scores[level]["partial"][type_]["f1"] for level in levels]
print(
"{:20} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f} {:<20.3f}".format(
type_, *this_scores
)
)
sql_keywords = [
"add",
"all",
"alter",
"and",
"as",
"asc",
"avg",
"between",
"by",
"char",
"column",
"count",
"create",
"delete",
"desc",
"distinct",
"drop",
"exists",
"except",
"from",
"group",
"having",
"in",
"index",
"inner",
"insert",
"intersect",
"into",
"is",
"join",
"left",
"like",
"limit",
"max",
"min",
"not",
"null",
"on",
"or",
"order",
"outer",
"select",
"set",
"sum",
"table",
"union",
"update",
"values",
"where",
]
sql_symbols = ["*", ",", ";", "(", ")", ">", "<", "=", "!", ">=", "<=", "!="]
def isfloat(str):
try:
float(str)
return True
except:
return False
def add_double_flashes(sql_str):
global sql_keywords, sql_symbols
toks = tokenize(sql_str)
words = []
aliases = list(scan_alias(toks).keys())
for tok in toks:
if tok in sql_keywords + sql_symbols + aliases or isfloat(tok):
words.append(tok)
elif (
tok.count(".") == 1 and " " not in tok and tok[0] != '"' and tok[-1] != '"'
): # case < "Computer Info. Systems"
alias, name = tok.split(".")
if alias in aliases:
words.append(alias + "." + '"' + name + '"')
else: # case "vai trò.mô tả về vai trò"
words.append('"' + alias + '"' + "." + '"' + name + '"')
else: # case < "2", = "Hello World"
words.append('"' + tok + '"')
sql_str = " ".join(words)
sql_str = sql_str.replace('" "', " ")
sql_str = sql_str.replace('""', '"') # = "Hello World"
return sql_str
def evaluate(gold, predict, db_dir, etype, kmaps):
with open(gold, encoding="utf-8") as f:
glist = [l.strip().split("\t") for l in f.readlines() if len(l.strip()) > 0]
with open(predict, encoding="utf-8") as f:
plist = [l.strip().split("\t") for l in f.readlines() if len(l.strip()) > 0]
glist = [(add_double_flashes(sql_str), db_id) for sql_str, db_id in glist]
# plist = [("select max(Share),min(Share) from performance where Type != 'terminal'", "orchestra")]
# glist = [("SELECT max(SHARE) , min(SHARE) FROM performance WHERE TYPE != 'Live final'", "orchestra")]
evaluator = Evaluator()
levels = ["easy", "medium", "hard", "extra", "all"]
partial_types = [
"select",
"select(no AGG)",
"where",
"where(no OP)",
"group(no Having)",
"group",
"order",
"and/or",
"IUEN",
"keywords",
]
entries = []
scores = {}
for level in levels:
scores[level] = {"count": 0, "partial": {}, "exact": 0.0}
scores[level]["exec"] = 0
for type_ in partial_types:
scores[level]["partial"][type_] = {
"acc": 0.0,
"rec": 0.0,
"f1": 0.0,
"acc_count": 0,
"rec_count": 0,
}
eval_err_num = 0
for p, g in zip(plist, glist):
p_str = p[0]
g_str, db = g
db_name = db
db = os.path.join(db_dir, db, db + ".sqlite")
schema = Schema(get_schema(db))
# print("g_sql", g_str)
g_sql = get_sql(schema, g_str)
hardness = evaluator.eval_hardness(g_sql)
scores[hardness]["count"] += 1
scores["all"]["count"] += 1
try:
p_str = add_double_flashes(p_str)
p_sql = get_sql(schema, p_str)
except:
# If p_sql is not valid, then we will use an empty sql to evaluate with the correct sql
p_sql = {
"except": None,
"from": {"conds": [], "table_units": []},
"groupBy": [],
"having": [],
"intersect": None,
"limit": None,
"orderBy": [],
"select": [False, []],
"union": None,
"where": [],
}
eval_err_num += 1
print("eval_err_num:{}".format(eval_err_num))
# rebuild sql for value evaluation
kmap = kmaps[db_name]
g_valid_col_units = build_valid_col_units(g_sql["from"]["table_units"], schema)
g_sql = rebuild_sql_val(g_sql)
g_sql = rebuild_sql_col(g_valid_col_units, g_sql, kmap)
p_valid_col_units = build_valid_col_units(p_sql["from"]["table_units"], schema)
p_sql = rebuild_sql_val(p_sql)
p_sql = rebuild_sql_col(p_valid_col_units, p_sql, kmap)
if etype in ["all", "exec"]:
exec_score = eval_exec_match(db, p_str, g_str, p_sql, g_sql)
if exec_score:
scores[hardness]["exec"] += 1.0
scores["all"]["exec"] += 1.0
if etype in ["all", "match"]:
exact_score = evaluator.eval_exact_match(p_sql, g_sql)
partial_scores = evaluator.partial_scores
if exact_score == 0:
print("{} pred: {}".format(hardness, p_str))
print("{} gold: {}".format(hardness, g_str))
print("")
scores[hardness]["exact"] += exact_score
scores["all"]["exact"] += exact_score
for type_ in partial_types:
if partial_scores[type_]["pred_total"] > 0:
scores[hardness]["partial"][type_]["acc"] += partial_scores[type_][
"acc"
]
scores[hardness]["partial"][type_]["acc_count"] += 1
if partial_scores[type_]["label_total"] > 0:
scores[hardness]["partial"][type_]["rec"] += partial_scores[type_][
"rec"
]
scores[hardness]["partial"][type_]["rec_count"] += 1
scores[hardness]["partial"][type_]["f1"] += partial_scores[type_]["f1"]
if partial_scores[type_]["pred_total"] > 0:
scores["all"]["partial"][type_]["acc"] += partial_scores[type_][
"acc"
]
scores["all"]["partial"][type_]["acc_count"] += 1
if partial_scores[type_]["label_total"] > 0:
scores["all"]["partial"][type_]["rec"] += partial_scores[type_][
"rec"
]
scores["all"]["partial"][type_]["rec_count"] += 1
scores["all"]["partial"][type_]["f1"] += partial_scores[type_]["f1"]
entries.append(
{
"predictSQL": p_str,
"goldSQL": g_str,
"hardness": hardness,
"exact": exact_score,
"partial": partial_scores,
}
)
for level in levels:
if scores[level]["count"] == 0:
continue
if etype in ["all", "exec"]:
scores[level]["exec"] /= scores[level]["count"]
if etype in ["all", "match"]:
scores[level]["exact"] /= scores[level]["count"]
for type_ in partial_types:
if scores[level]["partial"][type_]["acc_count"] == 0:
scores[level]["partial"][type_]["acc"] = 0
else:
scores[level]["partial"][type_]["acc"] = (
scores[level]["partial"][type_]["acc"]
/ scores[level]["partial"][type_]["acc_count"]
* 1.0
)
if scores[level]["partial"][type_]["rec_count"] == 0:
scores[level]["partial"][type_]["rec"] = 0
else:
scores[level]["partial"][type_]["rec"] = (
scores[level]["partial"][type_]["rec"]
/ scores[level]["partial"][type_]["rec_count"]
* 1.0
)
if (
scores[level]["partial"][type_]["acc"] == 0
and scores[level]["partial"][type_]["rec"] == 0
):
scores[level]["partial"][type_]["f1"] = 1
else:
scores[level]["partial"][type_]["f1"] = (
2.0
* scores[level]["partial"][type_]["acc"]
* scores[level]["partial"][type_]["rec"]
/ (
scores[level]["partial"][type_]["rec"]
+ scores[level]["partial"][type_]["acc"]
)
)
print_scores(scores, etype)
def eval_exec_match(db, p_str, g_str, pred, gold):
"""
return 1 if the values between prediction and gold are matching
in the corresponding index. Currently not support multiple col_unit(pairs).
"""
conn = sqlite3.connect(db)
cursor = conn.cursor()
try:
cursor.execute(p_str)
p_res = cursor.fetchall()
except:
return False
cursor.execute(g_str)
q_res = cursor.fetchall()
def res_map(res, val_units):
rmap = {}
for idx, val_unit in enumerate(val_units):
key = (
tuple(val_unit[1])
if not val_unit[2]
else (val_unit[0], tuple(val_unit[1]), tuple(val_unit[2]))
)
rmap[key] = [r[idx] for r in res]
return rmap
p_val_units = [unit[1] for unit in pred["select"][1]]
q_val_units = [unit[1] for unit in gold["select"][1]]
return res_map(p_res, p_val_units) == res_map(q_res, q_val_units)
# Rebuild SQL functions for value evaluation
def rebuild_cond_unit_val(cond_unit):
if cond_unit is None or not DISABLE_VALUE:
return cond_unit
not_op, op_id, val_unit, val1, val2 = cond_unit
if type(val1) is not dict:
val1 = None
else:
val1 = rebuild_sql_val(val1)
if type(val2) is not dict:
val2 = None
else:
val2 = rebuild_sql_val(val2)
return not_op, op_id, val_unit, val1, val2
def rebuild_condition_val(condition):
if condition is None or not DISABLE_VALUE:
return condition
res = []
for idx, it in enumerate(condition):
if idx % 2 == 0:
res.append(rebuild_cond_unit_val(it))
else:
res.append(it)
return res
def rebuild_sql_val(sql):
if sql is None or not DISABLE_VALUE:
return sql
sql["from"]["conds"] = rebuild_condition_val(sql["from"]["conds"])
sql["having"] = rebuild_condition_val(sql["having"])
sql["where"] = rebuild_condition_val(sql["where"])
sql["intersect"] = rebuild_sql_val(sql["intersect"])
sql["except"] = rebuild_sql_val(sql["except"])
sql["union"] = rebuild_sql_val(sql["union"])
return sql
# Rebuild SQL functions for foreign key evaluation
def build_valid_col_units(table_units, schema):
col_ids = [
table_unit[1]
for table_unit in table_units
if table_unit[0] == TABLE_TYPE["table_unit"]
]
prefixs = [col_id[:-2] for col_id in col_ids]
valid_col_units = []
for value in schema.idMap.values():
if "." in value and value[: value.index(".")] in prefixs:
valid_col_units.append(value)
return valid_col_units
def rebuild_col_unit_col(valid_col_units, col_unit, kmap):
if col_unit is None:
return col_unit
agg_id, col_id, distinct = col_unit
if col_id in kmap and col_id in valid_col_units:
col_id = kmap[col_id]