-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNLGPipeline.ts
More file actions
852 lines (746 loc) · 26.9 KB
/
NLGPipeline.ts
File metadata and controls
852 lines (746 loc) · 26.9 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
import HuggingFace, { FillMaskReturn } from "huggingface";
import { templateString } from "../../../helpers/helperFunctions";
import { knowledgeGraph, structuredKnowledgeGraph, IStructuredKnowledgeGraph } from "./knowledgeGraphReader";
import { attachRuntimes, getFunctionRuntimes } from "./benchmark";
import * as dotenv from "dotenv";
import path from "path";
import {
SubJoinType,
IStructuredQuery,
IJoinInstruction,
IOrderByColumns,
IColumns,
IHavingClause,
IConstraintColumns,
IAliasDictionary,
AggregateType,
} from "./types";
dotenv.config({ path: path.join(__dirname, ".env") });
export class NLGPipeline {
private baselineNlParser: BaselineNLParser;
private nlParser: NLParser;
private maskfiller = new MaskFiller();
constructor(language: string) {
this.baselineNlParser = new BaselineNLParser(baselineTemplatesPerLanguage[language]);
this.nlParser = new NLParser(templatesPerLanguage[language]);
}
// @attachRuntimes("translateQuery")
public async translateQuery(query: IStructuredQuery) {
const baselineNlQuery = this.baselineNlParser.parse(query);
const nlQuery = this.nlParser.parse(query);
const unMaskedNlQuery = await this.maskfiller.fillMasks(nlQuery);
return {
baselineNlQuery,
unMaskedNlQuery,
};
}
}
interface ITemplates {
[countryCode: string]: INLTemplate;
}
interface IConjunctions {
"&": string;
"|": string;
}
interface INLTemplate {
conjunctions: IConjunctions;
joinTemplate: IJoinTemplate;
operatorTemplate: IOperatorTemplate;
aggregationTemplate: IAggregationTemplate;
booleanTemplate: string;
columnTemplate: IColumnTemplate;
constraintTemplate: IConstraintTemplate;
havingTemplate: IHavingTemplate;
groupByTemplate: IGroupByTemplate;
orderByTemplate: IOrderByTemplate;
}
interface IJoinTemplate {
nonJoinStartingPhrase: string;
joinStartingPhrase: string;
joinTypes: {
[key in SubJoinType]: string;
};
}
interface IOperatorTemplate {
BETWEEN: string;
"<>": string;
"<": string;
">": string;
"<=": string;
">=": string;
"=": string;
LIKE: ILIKEConstraint;
"NOT LIKE": ILIKEConstraint;
NULL: string;
"NOT NULL": string;
}
type IAggregationTemplate = {
[key in AggregateType]: string;
};
interface IColumnTemplate {
columnStartingPhrasePlural: string;
columnStartingPhraseSingular: string;
columnEndingPhrase: string;
}
interface IConstraintTemplate {
startingPhrase: string;
endingPhrase: string;
LIKEOperatorFallback: { include: string; exclude: string };
}
interface ILIKEConstraint {
[key: number]: string;
}
interface IHavingTemplate {
startingPhrase: string;
endingPhrase: string;
}
interface IGroupByTemplate {
startingPhrase: string;
endingPhrase: string;
}
interface IOrderByTemplate {
startingPhrase: string;
endingPhrase: string;
direction: {
DESC: string;
ASC: string;
};
}
export const baselineTemplatesPerLanguage: ITemplates = {
de: {
conjunctions: {
"&": " and ",
"|": " or ",
},
joinTemplate: {
nonJoinStartingPhrase: "Use table ${table}.",
joinStartingPhrase: "Form",
joinTypes: {
"RIGHT OUTER JOIN":
"the intersection that contains all entries of ${source} and the corresponding entries of ${target}",
"LEFT OUTER JOIN":
"the intersection that contains all entries of ${target} and the corresponding entries of ${source}",
// "CROSS JOIN": "the cross product of the tables ${source} and ${target}",
"INNER JOIN": "the intersection that contains the corresponding entries of the tables ${source} and ${target}",
},
},
booleanTemplate: "",
aggregationTemplate: {
SUM: "the sum of ${column}",
AVG: "the average of ${column}",
MAX: "the maximum of ${column}",
MIN: "the minimum of ${column}",
COUNT: "the amount of ${column}",
},
operatorTemplate: {
BETWEEN: "is between ${value1} and ${value2}",
"<>": "doesn't equal",
"<": "is smaller than",
">": "is greater than",
"<=": "is smaller or equal than",
">=": "is greater or equal than",
"=": "equals",
LIKE: {
0: "contains '${value}'",
1: "ends with '${value}'",
2: "starts with '${value}'",
},
"NOT LIKE": {
0: "doesn't contain '${value}'",
1: "doesn't end with '${value}'",
2: "doesn't start with'${value}'",
},
NULL: "NULL",
"NOT NULL": "not NULL",
},
columnTemplate: {
columnStartingPhrasePlural: "Return the columns",
columnStartingPhraseSingular: "Return the column",
columnEndingPhrase: "",
},
constraintTemplate: {
startingPhrase: "Only return the data for which",
endingPhrase: "is true",
LIKEOperatorFallback: { exclude: "contains any string", include: "contains an empty string" },
},
groupByTemplate: {
startingPhrase: "Group the result by",
endingPhrase: "",
},
havingTemplate: {
startingPhrase: "A further constraint is",
endingPhrase: "",
},
orderByTemplate: {
startingPhrase: "Sort the result",
endingPhrase: "",
direction: {
ASC: "ascending",
DESC: "descending",
},
},
},
};
class BaselineNLParser {
constructor(private template: INLTemplate) {}
// @attachRuntimes("parseBaseline")
public parse({ columns, join, whereClause, havingClause, groupBy, orderBy }: IStructuredQuery) {
const {
joinTemplate,
conjunctions,
aggregationTemplate,
operatorTemplate,
columnTemplate,
constraintTemplate,
groupByTemplate,
havingTemplate,
booleanTemplate,
orderByTemplate,
} = this.template;
const parsedJoin = this.parseJoin(join, joinTemplate, conjunctions);
const parsedColumns = this.parseColumns(columns, columnTemplate, aggregationTemplate, conjunctions);
const parsedWhereClause = this.parseWhereClause(whereClause, constraintTemplate, operatorTemplate, conjunctions);
const parsedGroupBy = this.parseGroupBy(groupBy, groupByTemplate, conjunctions);
const parsedHavingClause = this.parseHavingClause(
havingClause,
havingTemplate,
aggregationTemplate,
operatorTemplate
);
const parsedOrderBy = this.parseOrderBy(orderBy, orderByTemplate, conjunctions, booleanTemplate);
const nlQuery = `${parsedJoin} ${parsedColumns} ${parsedWhereClause} ${parsedHavingClause} ${parsedGroupBy} ${parsedOrderBy}`;
return nlQuery;
}
private handleConjunction(parsedColumns: string, conjunctions: IConjunctions) {
const conjunctionInsertionIndex = parsedColumns.lastIndexOf(", ");
if (~conjunctionInsertionIndex) {
parsedColumns =
parsedColumns.substring(0, conjunctionInsertionIndex) +
conjunctions["&"] +
parsedColumns.substring(conjunctionInsertionIndex + 2);
}
return parsedColumns;
}
private parseJoin(joinInstruction: IJoinInstruction, joinTemplate: IJoinTemplate, conjunctions: IConjunctions) {
const { table, path } = joinInstruction;
let source = table;
const joins = path.map((edge) => {
const target = edge.table as string;
const joinType = joinTemplate.joinTypes[edge.type];
const join = templateString(joinType, { source: [source], target: [target] });
source = target;
return join;
});
let joinStatement = templateString(joinTemplate.nonJoinStartingPhrase, { table: [table] });
if (joins.length) {
joinStatement = `${joinTemplate.joinStartingPhrase} ${joins.join(conjunctions["&"])}.`;
}
return joinStatement;
}
private parseColumns(
columnsPerTable: IColumns,
columnTemplate: IColumnTemplate,
aggregationTemplate: IAggregationTemplate,
conjunctions: IConjunctions
) {
const flattened = Object.entries(columnsPerTable).reduce((flattened, [table, columns]) => {
const parsedColumns = columns.map((column) => {
const { aggregation, name } = column;
let parsedColumn = name;
if (aggregation) {
parsedColumn = templateString(aggregationTemplate[aggregation], { column: [name] });
}
return parsedColumn;
});
return [...flattened, ...parsedColumns];
}, []);
const startingPhrase =
flattened.length > 1 ? columnTemplate.columnStartingPhrasePlural : columnTemplate.columnStartingPhraseSingular;
let parsedColumns = this.handleConjunction(flattened.join(", "), conjunctions);
return `${startingPhrase} ${parsedColumns}${columnTemplate.columnEndingPhrase}.`;
}
// TODO cleanup this messy code
private parseWhereClause(
columnsPerTable: IConstraintColumns,
constraintTemplate: IConstraintTemplate,
operatorTemplate: IOperatorTemplate,
conjunctions: IConjunctions
) {
const likeConstraints: Array<string> = [];
const flattened = Object.entries(columnsPerTable).reduce((flattened, [table, columns]) => {
const parsedColumns = columns.reduce((parsedConstraints, column) => {
const { constraint, name } = column;
const operator = constraint.operator as keyof IOperatorTemplate;
const values = constraint.values as Array<string>;
let parsedConstraint = `${name} ${operatorTemplate[operator]} '${values[0]}'`;
if (operator === "BETWEEN") {
const [value1, value2] = values;
parsedConstraint =
`${name} is ` + templateString(operatorTemplate["BETWEEN"], { value1: [value1], value2: [value2] });
} else if (/LIKE/i.test(operator)) {
let likeConstraint;
const [value] = values;
const cleanedValue = value.replace(/%/g, "");
if (!value) {
const exclude = /NOT/i.test(operator);
if (exclude) {
likeConstraint = `${name} ${constraintTemplate.LIKEOperatorFallback.exclude}`;
} else {
likeConstraint = `${name} ${constraintTemplate.LIKEOperatorFallback.include}`;
}
} else {
let option;
if (/%\w+/i.test(value)) option = 2;
else if (/\w+%/i.test(value)) option = 1;
else option = 0;
const constraint = templateString(operatorTemplate[operator][option], { value: [cleanedValue] });
likeConstraint = `${name} ${constraint}`;
}
likeConstraints.push(likeConstraint);
parsedConstraint = "";
} else if (/NULL/i.test(operator)) {
parsedConstraint = `${name} ${operatorTemplate[operator]}`;
}
if (parsedConstraint) parsedConstraints.push(parsedConstraint);
return parsedConstraints;
}, []);
return [...flattened, ...parsedColumns];
}, []);
const constraints = flattened.join(", ");
const joinedLikeConstraints = likeConstraints.join(", ");
if (!flattened.length && !likeConstraints.length) return "";
else if (!flattened.length) {
return `${constraintTemplate.startingPhrase} ${joinedLikeConstraints}.`;
} else if (!likeConstraints.length) {
return `${constraintTemplate.startingPhrase} ${constraints} ${constraintTemplate.endingPhrase}.`;
}
return `${constraintTemplate.startingPhrase} ${constraints} ${constraintTemplate.endingPhrase} ${conjunctions[
"&"
].trim()} ${joinedLikeConstraints}.`.replace(/, ([^,]*)$/, " and $1");
}
private parseGroupBy(groupBy: IColumns, groupByTemplate: IGroupByTemplate, conjunctions: IConjunctions) {
const flattened = Object.entries(groupBy).reduce((flattened, [table, columns]) => {
const parsedColumns = columns.map((column) => {
const { name } = column;
return name;
});
return [...flattened, ...parsedColumns];
}, []);
if (!flattened.length) return "";
let parsedColumns = this.handleConjunction(flattened.join(", "), conjunctions);
return `${groupByTemplate.startingPhrase} ${parsedColumns}${groupByTemplate.endingPhrase}.`;
}
private parseHavingClause(
havingClause: IHavingClause,
havingTemplate: IHavingTemplate,
aggregationTemplate: IAggregationTemplate,
operatorTemplate: IOperatorTemplate
) {
const flattened = Object.entries(havingClause).reduce((flattened, [table, columnsPerTable]) => {
const parsedColumns = columnsPerTable.map((column) => {
const { aggregation, name, constraint } = column;
const operator = constraint.operator as keyof IOperatorTemplate;
const values = constraint.values as Array<string>;
const aggregationString = templateString(aggregationTemplate[aggregation], { column: [name] });
let parsedConstraint = `${operatorTemplate[operator]} '${values[0]}'`;
if (operator === "BETWEEN") {
const [value1, value2] = values;
parsedConstraint = templateString(operatorTemplate["BETWEEN"], { value1: [value1], value2: [value2] });
}
return `${aggregationString} ${parsedConstraint}`;
});
return [...flattened, ...parsedColumns];
}, []);
if (!flattened.length) return "";
const constraint = flattened.join(", ");
return `${havingTemplate.startingPhrase} ${constraint} ${havingTemplate.endingPhrase}.`;
}
private parseOrderBy(
orderBy: IOrderByColumns,
orderByTemplate: IOrderByTemplate,
conjunctions: IConjunctions,
booleanTemplate: string
) {
const flattened = Object.entries(orderBy).reduce((flattened, [table, columns]) => {
const parsedColumns = columns.map((column) => {
const { name } = column;
const orderBy = column.orderBy as keyof IOrderByTemplate["direction"];
return `${orderByTemplate.direction[orderBy]} by ${name}`;
});
return [...flattened, ...parsedColumns];
}, []);
if (!flattened.length) return "";
let parsedColumns = this.handleConjunction(flattened.join(", "), conjunctions);
return `${orderByTemplate.startingPhrase} ${parsedColumns}${orderByTemplate.endingPhrase}.`;
}
}
export const templatesPerLanguage: ITemplates = {
de: {
conjunctions: {
"&": " and ",
"|": " or ",
},
joinTemplate: {
nonJoinStartingPhrase: "",
joinStartingPhrase: "",
joinTypes: {
"RIGHT OUTER JOIN": "${target} and [MASK] ${source}, even if [MASK] have no ${target}",
"LEFT OUTER JOIN": "${source} and [MASK] ${target}, even if [MASK] have no ${source}",
// "CROSS JOIN": "das kartesische Produkt der Tabellen ${source} und ${target}",
"INNER JOIN": "${source} and [MASK] corresponding ${target}",
},
},
booleanTemplate: "wether the ${table} is ${column} or not",
aggregationTemplate: {
SUM: "the sum of ${column}",
AVG: "the average of ${column}",
MAX: "the maximum of ${column}",
MIN: "the minimum of ${column}",
COUNT: "the count of ${column}",
},
operatorTemplate: {
BETWEEN: "is between ${value1} and ${value2}",
"<>": "is not",
"<": "is smaller than",
">": "is larger than",
"<=": "is smaller or the same as",
">=": "is greater or the same as",
"=": "is",
LIKE: {
0: "contains '${value}'",
1: "ends with '${value}'",
2: "starts with '${value}'",
},
"NOT LIKE": {
0: "doesn't contain '${value}'",
1: "doesn't end with '${value}'",
2: "doesn't start with '${value}'",
},
NULL: "NULL",
"NOT NULL": "not NULL",
},
columnTemplate: {
columnStartingPhrasePlural: "",
columnStartingPhraseSingular: "",
columnEndingPhrase: "",
},
constraintTemplate: {
startingPhrase: "",
endingPhrase: "",
LIKEOperatorFallback: { exclude: "contains any string", include: "contains an empty string" },
},
groupByTemplate: {
startingPhrase: "Group the result by",
endingPhrase: "",
},
havingTemplate: {
startingPhrase: "",
endingPhrase: "",
},
orderByTemplate: {
startingPhrase: "Sort the result by ",
endingPhrase: "",
direction: {
ASC: "in ascending order",
DESC: "in descending order",
},
},
},
};
class NLParser {
constructor(private template: INLTemplate) {}
// @attachRuntimes("parseNL")
public parse({ columns, join, whereClause, havingClause, groupBy, orderBy, aliasDictionary }: IStructuredQuery) {
const {
joinTemplate,
conjunctions,
aggregationTemplate,
operatorTemplate,
columnTemplate,
constraintTemplate,
booleanTemplate,
groupByTemplate,
havingTemplate,
orderByTemplate,
} = this.template;
const parsedJoin = this.parseJoin(join, joinTemplate, conjunctions, aliasDictionary);
const parsedColumns = this.parseColumns(
columns,
columnTemplate,
aggregationTemplate,
conjunctions,
booleanTemplate
);
const parsedWhereClause = this.parseWhereClause(whereClause, constraintTemplate, operatorTemplate, conjunctions);
const parsedHavingClause = this.parseHavingClause(
havingClause,
havingTemplate,
aggregationTemplate,
operatorTemplate
);
const parsedOrderBy = this.parseOrderBy(orderBy, orderByTemplate, conjunctions, booleanTemplate);
const nlQuery = `Find ${parsedColumns} for all ${parsedJoin} [MASK]${parsedWhereClause} ${parsedHavingClause}${parsedOrderBy}`;
return nlQuery;
}
private handleConjunction(parsedColumns: string, conjunctions: IConjunctions) {
const conjunctionInsertionIndex = parsedColumns.lastIndexOf(", ");
if (~conjunctionInsertionIndex) {
parsedColumns =
parsedColumns.substring(0, conjunctionInsertionIndex) +
conjunctions["&"] +
parsedColumns.substring(conjunctionInsertionIndex + 2);
}
return parsedColumns;
}
private parseJoin(
joinInstruction: IJoinInstruction,
joinTemplate: IJoinTemplate,
conjunctions: IConjunctions,
aliasDictionary: IAliasDictionary
) {
const junctionTables = ["person_title", "person_profession", "title_genre"];
const { table, path } = joinInstruction;
const tableTypeLookup = Object.entries(structuredKnowledgeGraph).reduce((tableTypeLookup, [tableType, tables]) => {
Object.keys(tables).forEach((tableName) => (tableTypeLookup[tableName] = tableType));
return tableTypeLookup;
}, {} as { [key: string]: string });
const tablesInJoin = [table, ...path.map((node) => node.table)];
const { majorEntities, minorEntities, majorAttributes, minorAttributes, semanticEdges } = tablesInJoin.reduce(
(mappedTables, table) => {
const tableType = tableTypeLookup[table];
if (tableType) {
if (!(tableType in mappedTables)) {
mappedTables[tableType] = {};
}
mappedTables[tableType][table] = structuredKnowledgeGraph[tableType][table];
}
return mappedTables;
},
{} as IStructuredKnowledgeGraph
);
if (Object.keys(majorEntities).length === 1) {
const majorTable = Object.values(majorEntities)[0];
const { sing, plur } = majorTable.alias[0];
return `${plur}`;
} else {
const startTable = Object.keys(majorEntities)[0];
if (startTable === "person") {
return "persons and the titles they were involved with";
} else {
return "titles and the persons that were involved with them";
}
}
// let source = table;
// const joins = path.map((edge) => {
// const target = edge.table as string;
// const joinType = joinTemplate.joinTypes[edge.type];
// let join = "";
// if (junctionTables.includes(source)) {
// join = target;
// } else if (junctionTables.includes(target)) {
// join = source;
// } else {
// join = templateString(joinType, { source: [source], target: [target] });
// }
// source = target;
// return join;
// });
// let joinStatement = templateString(joinTemplate.nonJoinStartingPhrase, { table: [table] });
// if (joins.length) {
// joinStatement = `${joins.join(conjunctions["&"])} [MASK]`;
// }
// return joinStatement;
}
private parseColumns(
columnsPerTable: IColumns,
columnTemplate: IColumnTemplate,
aggregationTemplate: IAggregationTemplate,
conjunctions: IConjunctions,
booleanTemplate: string
) {
const { minorAttributes, majorEntities } = structuredKnowledgeGraph;
const flattened = Object.entries(columnsPerTable).reduce((flattened, [table, columns]) => {
const parsedColumns = columns.map((column) => {
const { aggregation, name } = column;
const semanticName = minorAttributes[name].alias[0].plur;
const determiner = "the ";
let parsedColumn = `${determiner}${semanticName}`;
const booleanColumns = ["is_adult"];
if (booleanColumns.includes(name)) {
const semanticTableName = majorEntities[table].alias[0].plur;
parsedColumn = templateString(booleanTemplate, { column: [semanticName], table: [semanticTableName] });
}
if (aggregation) {
parsedColumn = templateString(aggregationTemplate[aggregation], { column: [semanticName] });
}
return parsedColumn;
});
return [...flattened, ...parsedColumns];
}, []);
const startingPhrase =
flattened.length > 1 ? columnTemplate.columnStartingPhrasePlural : columnTemplate.columnStartingPhraseSingular;
let parsedColumns = this.handleConjunction(flattened.join(", "), conjunctions);
return `${startingPhrase}${parsedColumns}`;
}
// TODO cleanup this messy code
private parseWhereClause(
columnsPerTable: IConstraintColumns,
constraintTemplate: IConstraintTemplate,
operatorTemplate: IOperatorTemplate,
conjunctions: IConjunctions
) {
const { minorAttributes } = structuredKnowledgeGraph;
const likeConstraints: Array<string> = [];
const flattened = Object.entries(columnsPerTable).reduce((flattened, [table, columns]) => {
const parsedColumns = columns.reduce((parsedConstraints, column) => {
const { constraint, name } = column;
const operator = constraint.operator as keyof IOperatorTemplate;
const values = constraint.values as Array<string>;
const semanticName = minorAttributes[name].alias[0].sing;
let parsedConstraint = `the ${semanticName} ${operatorTemplate[operator]} '${values[0]}'`;
if (operator === "BETWEEN") {
const [value1, value2] = values;
parsedConstraint =
`the ${semanticName} ` +
templateString(operatorTemplate["BETWEEN"], { value1: [value1], value2: [value2] });
} else if (/LIKE/i.test(operator)) {
let likeConstraint;
const [value] = values;
const cleanedValue = value.replace(/%/g, "");
if (!value) {
const exclude = /NOT/i.test(operator);
if (exclude) {
likeConstraint = `the ${semanticName} ${constraintTemplate.LIKEOperatorFallback.exclude}`;
} else {
likeConstraint = `the ${semanticName} ${constraintTemplate.LIKEOperatorFallback.include}`;
}
} else {
let option;
if (/%\w+/i.test(value)) option = 2;
else if (/\w+%/i.test(value)) option = 1;
else option = 0;
const constraint = templateString(operatorTemplate[operator][option], { value: [cleanedValue] });
likeConstraint = `the ${semanticName} ${constraint}`;
}
likeConstraints.push(likeConstraint);
parsedConstraint = "";
} else if (/NULL/i.test(operator)) {
parsedConstraint = `the ${semanticName} ${operatorTemplate[operator]}`;
}
if (parsedConstraint) parsedConstraints.push(parsedConstraint);
return parsedConstraints;
}, []);
return [...flattened, ...parsedColumns];
}, []);
const constraints = flattened.join(", ");
const joinedLikeConstraints = likeConstraints.join(", ");
if (!flattened.length && !likeConstraints.length) return "";
else if (!flattened.length) {
return `${constraintTemplate.startingPhrase} ${joinedLikeConstraints}.`;
} else if (!likeConstraints.length) {
return `${constraintTemplate.startingPhrase} ${constraints}${constraintTemplate.endingPhrase}.`;
}
return `${constraintTemplate.startingPhrase}${constraints} ${constraintTemplate.endingPhrase} ${conjunctions[
"&"
].trim()} ${joinedLikeConstraints}.`.replace(/, ([^,]*)$/, " and $1");
}
private parseGroupBy(groupBy: IColumns, groupByTemplate: IGroupByTemplate, conjunctions: IConjunctions) {
const flattened = Object.entries(groupBy).reduce((flattened, [table, columns]) => {
const parsedColumns = columns.map((column) => {
const { name } = column;
return name;
});
return [...flattened, ...parsedColumns];
}, []);
if (!flattened.length) return "";
let parsedColumns = this.handleConjunction(flattened.join(", "), conjunctions);
return `${groupByTemplate.startingPhrase} ${parsedColumns}${groupByTemplate.endingPhrase}.`;
}
private parseHavingClause(
havingClause: IHavingClause,
havingTemplate: IHavingTemplate,
aggregationTemplate: IAggregationTemplate,
operatorTemplate: IOperatorTemplate
) {
const flattened = Object.entries(havingClause).reduce((flattened, [table, columnsPerTable]) => {
const parsedColumns = columnsPerTable.map((column) => {
const { aggregation, name, constraint } = column;
const operator = constraint.operator as keyof IOperatorTemplate;
const values = constraint.values as Array<string>;
const aggregationString = templateString(aggregationTemplate[aggregation], { column: [name] });
let parsedConstraint = `${operatorTemplate[operator]} '${values[0]}'`;
if (operator === "BETWEEN") {
const [value1, value2] = values;
parsedConstraint = templateString(operatorTemplate["BETWEEN"], { value1: [value1], value2: [value2] });
}
return `${aggregationString} ${parsedConstraint}`;
});
return [...flattened, ...parsedColumns];
}, []);
if (!flattened.length) return "";
const constraint = flattened.join(", ");
return `${havingTemplate.startingPhrase} ${constraint} ${havingTemplate.endingPhrase}.`;
}
private parseOrderBy(
orderBy: IOrderByColumns,
orderByTemplate: IOrderByTemplate,
conjunctions: IConjunctions,
booleanTemplate: string
) {
const { minorAttributes, majorEntities } = structuredKnowledgeGraph;
const flattened = Object.entries(orderBy).reduce((flattened, [table, columns]) => {
const parsedColumns = columns.map((column) => {
const { name } = column;
const semanticName = minorAttributes[name].alias[0].sing;
const orderBy = column.orderBy as keyof IOrderByTemplate["direction"];
const booleanColumns = ["is_adult"];
const determiner = booleanColumns.includes(name) ? "" : "the ";
let orderByStatement = `${determiner}${semanticName} ${orderByTemplate.direction[orderBy]}`;
if (booleanColumns.includes(name)) {
const semanticTableName = majorEntities[table].alias[0].plur;
orderByStatement =
templateString(booleanTemplate, { column: [name], table: [semanticTableName] }) +
` ${orderByTemplate.direction[orderBy]}`;
}
return orderByStatement;
});
return [...flattened, ...parsedColumns];
}, []);
if (!flattened.length) return "";
let parsedColumns = this.handleConjunction(flattened.join(", "), conjunctions);
return `${orderByTemplate.startingPhrase}${parsedColumns}${orderByTemplate.endingPhrase}.`;
}
}
/**
* Ease-of-use implementation for replicability. Uses the existing free API and hardware of the Huggingface Transformer platform.
* But without a proper API token, the rate limit may be reached relatively quickly.
*
* Fills in [MASK]-tokens with suggested tokens by the BERT model.
*/
class MaskFiller {
private hf: HuggingFace;
private stopTokens: Array<string> = [".", ",", ";", "?", "!", "|", ":"];
constructor() {
this.hf = new HuggingFace(process.env.HUGGINGFACE_TOKEN || "");
}
// @attachRuntimes("fillMask")
public async fillMasks(sequence: string): Promise<string> {
const splitSequence = this.splitAtMask(sequence);
let unmaskedSequence = splitSequence.shift();
while (splitSequence.length) {
let partialSequence = splitSequence.shift();
const result = await this.hf.fillMask({
model: "bert-large-uncased",
inputs: `${unmaskedSequence}[MASK]${partialSequence}`,
});
const unmaskedToken = result
.filter((suggestion) => !this.stopTokens.includes(suggestion.token_str))
.shift().token_str;
unmaskedSequence = `${unmaskedSequence}[MASK]${partialSequence}`.replace("[MASK]", unmaskedToken);
}
return unmaskedSequence;
}
private splitAtMask(sequence: string): Array<string> {
return sequence.split("[MASK]");
}
}