-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
401 lines (330 loc) · 11.2 KB
/
index.js
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
// This is the new and improved mysql Version, smaller and MUCH faster
var async = require("async");
var Knex = require("knex");
var _ = require("underscore");
var debug = require("debug")("ConceptNet");
var stopwords = ["for", "like", "use", "an", "if", "of", "to", "the", "is", "a", "i", "are", "and", "who", "what", "where", "when","how", "would", "which", "or", "do", "my", "bob"];
var basicFind = function() {
return knex('assertion')
.join('concept as c1', 'c1.id', '=' ,'assertion.concept1_id', 'left')
.join('concept as c2', 'c2.id', '=' ,'assertion.concept2_id', 'left')
.join('surfaceform as f1', 'f1.id', '=' ,'assertion.best_surface1_id', 'left')
.join('surfaceform as f2', 'f2.id', '=' ,'assertion.best_surface2_id', 'left')
.join('frame as frame', 'frame.id', '=' ,'assertion.best_frame_id', 'left')
.join('rawassertion as raw', 'raw.id', '=' ,'assertion.best_raw_id', 'left')
.join('sentence', 'sentence.id', '=' ,'raw.sentence_id', 'left')
.select('c1.text as c1_text', 'c2.text as c2_text', 'c2.num_assertions', 'f1.text as frame1', 'f2.text as frame2', 'sentence.text as sentense', 'frame.text as frame_text' )
.where('assertion.score', '>', 0)
.whereNotNull('f1.text')
.whereNotNull('f2.text')
.orderBy('c2.num_assertions', 'desc')
.limit(90).clone();
};
var capableOf = function() {
return basicFind().andWhere('assertion.relation_id', 8).clone();
}
var hasPrerequisite = function() {
return basicFind().andWhere('assertion.relation_id', 3).clone();
}
var causes = function() {
return basicFind().andWhere('assertion.relation_id', 18).clone();
}
var atLocation = function() {
return basicFind().andWhere('assertion.relation_id', 6).clone();
}
var hasProperty = function() {
return basicFind().andWhere('assertion.relation_id', 20).clone();
}
var usedFor = function() {
return basicFind().andWhere('assertion.relation_id', 7).clone();
}
var isA = function() {
return basicFind().andWhere('assertion.relation_id', 5).clone();
}
// Generic Fwd / Back
var basicForward = function(term) {
return basicFind().andWhere('c1.text', term).clone();
}
var basicReverse = function(term) {
return basicFind().andWhere('c2.text', term).clone();
}
// Relationship Fwd / Back
var hasPrerequisiteForward = function(term, callback) {
hasPrerequisite().andWhere('c1.text', term).exec(callback);
}
var hasPrerequisiteReverse = function(term, callback) {
hasPrerequisite().andWhere('c2.text', term).exec(callback);
}
var causesForward = function(term, callback) {
causes().andWhere('c1.text', term).exec(callback);
}
var causesReverse = function(term, callback) {
causes().andWhere('c1.text', term).exec(callback);
}
var atLocationForward = function(term, callback) {
atLocation().andWhere('c1.text', term).exec(callback);
}
var atLocationReverse = function(term, callback) {
atLocation().andWhere('c2.text', term).exec(callback);
}
var hasPropertyForward = function(term, callback) {
hasProperty().andWhere('c1.text', term).exec(callback);
}
var hasPropertyReverse = function(term, callback) {
hasProperty().andWhere('c2.text', term).exec(callback);
}
var usedForForward = function(term, callback) {
usedFor().andWhere('c1.text', term).exec(callback);
}
var usedForReverse = function(term, callback) {
usedFor().andWhere('c2.text', term).exec(callback);
}
var isAForward = function(term, callback) {
isA().andWhere('c1.text', term).exec(callback);
}
var isAReverse = function(term, callback) {
isA().andWhere('c2.text', term).exec(callback);
}
var capableOfForward = function(term, callback) {
capableOf().andWhere('c1.text', term).exec(callback);
}
var capableOfReverse = function(term, callback) {
capableOf().andWhere('c2.text', term).exec(callback);
}
var getAssertion = function(term1, term2, callback) {
basicForward(term1).andWhere('c2.text', term2).exec(callback);
}
var assertionLookupForward = function(term, callback) {
basicForward(term).exec(callback);
}
// PUT IN or PUT ON
// What do you use to put X in
// food => dish
// nail => hammer
// car => garage
var putConcept = function(term, callback) {
debug("IN Put with", term);
usedForReverse(term, function(err, concepts){
var map = {};
var itor = function(item, cb) {
var concept = item.c1_text;
usedForForward(concept, function(err, concepts2) {
map[concept] = 0;
for (var n = 0; n < concepts2.length; n++) {
if (concepts2[n].c2_text.indexOf(term) !== -1) {
map[concept] += 1;
}
}
cb(null, map);
});
}
if (concepts.length != 0) {
async.map(concepts, itor, function(err, result){
var set = result[0];
var keysSorted = Object.keys(set).sort(function(a,b){return set[b]-set[a]});
debug("Sorted Set", keysSorted);
// TODO, if the top items are equal maybe pick one randomly
callback(null, keysSorted[0]);
});
} else {
callback(null, null);
}
});
}
var assersionTest = function(term1, term2, cb ) {
isAForward(term1, function(err, concepts2) {
var lcount = 0, ecount = 0;
for (var i = 0; i < concepts2.length; i++) {
if (concepts2[i].c2_text == term2) {
ecount++
}
if (concepts2[i].c2_text.indexOf(term2) !== -1) {
lcount++
}
}
// console.log(term1, term2, lcount, ecount)
cb(null, (lcount + (ecount * 3 ) / concepts2.length))
});
}
var resolveFact = function(term1, term2, cb ) {
isAForward(term1, function(err, concepts2) {
// Remove dups
var uniq = _.uniq(concepts2.map(function(item){return item.c2_text}));
var map = [];
var itor = function(concept, callback) {
assersionTest(concept, term2, function(err, val){
if (val > 0.01) {
map.push([concept, val]);
}
callback(null)
});
}
async.each(uniq, itor, function() {
var keysSorted = map.sort(function(a,b){return b[1] - a[1]});
debug("resolveFact", keysSorted);
if (keysSorted.length != 0)
cb(null, keysSorted[0][0]);
else {
cb(null, null);
}
});
});
}
var resolveFacts = function(array, term2, cb) {
debug("ResolveFacts", array, term2);
var itor = function(item, next) {
resolveFact(item, term2, function(err, res){
if (res) {
next(null, item);
} else {
next(null);
}
});
}
async.map(array, itor, function(err, res){
var arr = _.uniq(res);
arr = arr.filter(function(n){ return n != undefined });
cb(null, arr);
});
}
var conceptLookup = function(msg, callback) {
var words1 = ngrams(msg, 1);
var words2 = ngrams(msg, 2);
var words3 = ngrams(msg, 3);
words2 = words2.concat(words1);
words3 = words3.concat(words2);
words3 = _.map(words3, function(key, item) { return key.join(" "); });
words3 = _.reject(words3, function(word) { return _.contains(stopwords, word.toLowerCase()) });
debug("Searching Concepts for", words3);
var itor = function(item, cb) {
knex('concept')
.select('text', 'num_assertions', 'visible')
.where('num_assertions', '!=', 0)
.andWhere('text', item )
.exec(function(err, res){
cb(err, res);
});
}
async.mapSeries(words3, itor, function(err, res){
var concepts = _.filter(_.flatten(res), Boolean);
var newWords = _.map(_.filter(concepts, Boolean), function(item){ return item.text});
newWords = _.reject(newWords, function(word) { return _.contains(stopwords, word) });
callback(null, concepts)
});
}
var relatedConceptsArray = function(terms, callback) {
var t = [];
var itor = function(term, done) {
isAForward(term, function(err, result){
var map = [];
_.each(result, function(item){
map.push(item.c2_text)
// map.push({text:item.c2_text, num: item.num_assertions})
});
done(null, map);
});
}
async.map(terms, itor, function(err, res){
var selectedIntersection = _.intersection.apply(_, res);
callback(null, selectedIntersection);
});
}
// How are 2 concepts Related
// Returns an array of objects with num_assersions
var relatedConcepts = function(term1, term2, callback) {
var terms = [];
isAForward(term1, function(err, res1){
isAForward(term2, function(err, res2){
var map1 = [], map2 = [];
_.each(res1, function(item){
map1.push({text:item.c2_text, num: item.num_assertions})
});
_.each(res2, function(item){
map2.push({text:item.c2_text, num: item.num_assertions})
});
var results = _.uniq(_.intersect(map1, map2));
callback(null, results)
});
});
}
// Return an array of items with the filterSet removed
var filterConcepts = function(items, filter, callback) {
var itor = function(item, done) {
assersionTest(item, filter, done);
}
async.map(items, itor, function(err, data) {
var newList = _.filter(items, function(k,v) { return (data[v] !== 0 && !isNaN(data[v])) });
callback(null, newList);
});
}
var constructSurface = function(term1, term2, callback) {
getAssertion(term1, term2, function(err, fullconcept){
var x = getRandomInt(0, fullconcept.length - 1);
callback(null, fullconcept[x].sentense);
});
};
module.exports = function(options) {
options = options || {}
knex = Knex.initialize({
client: 'mysql',
connection: {
host : options.host || "localhost",
user : options.user || "root",
password : options.pass || "",
database : options.database || "conceptnet"
}
});
return {
basicReverse: basicReverse,
basicForward: basicForward,
// Forward, Reverse Relations
hasPrerequisiteForward: hasPrerequisiteForward,
hasPrerequisiteReverse: hasPrerequisiteReverse,
causesForward: causesForward,
causesReverse: causesReverse,
atLocationForward: atLocationForward,
atLocationReverse: atLocationReverse,
hasPropertyForward: hasPropertyForward,
hasPropertyReverse: hasPropertyReverse,
isAForward: isAForward,
isAReverse: isAReverse,
usedForForward: usedForForward,
usedForReverse: usedForReverse,
capableOfForward: capableOfForward,
capableOfReverse: capableOfReverse,
// More complicated things :)
putConcept: putConcept,
constructSurface : constructSurface,
relatedConcepts: relatedConcepts,
relatedConceptsArray: relatedConceptsArray,
conceptLookup: conceptLookup,
resolveFact: resolveFact,
resolveFacts: resolveFacts,
filterConcepts: filterConcepts,
assersionTest: assersionTest,
assertionLookupForward: assertionLookupForward
}
}
// Helper, intersect Objects
_.intersect = function(array) {
var slice = Array.prototype.slice; // added this line as a utility
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.any(other, function(element) { return _.isEqual(element, item); });
});
});
};
var getRandomInt = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
var ngrams = function(sequence, n) {
var result = [], words = [], count;
words = sequence.split(/\W+/);
words = _.without(words, '', ' ')
count = _.max([0, words.length - n + 1]);
for (var i = 0; i < count; i++) {
result.push(words.slice(i, i + n));
}
return result;
};