/
classifiers.js
2758 lines (2089 loc) · 121 KB
/
classifiers.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
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
/**
* Create a new classifier for the NLU server.
*
* This is the file where the classifier specification (type, options, etc.) is defined.
*
* The selection of which classifier to actually use is made in the bottom of this file.
*
*
* @author Erel Segal-Halevi
* @since 2013-08
*/
var _ = require('underscore')._;
var extend = require('util')._extend;
var fs = require('fs');
var limdu = require("limdu");
var trainutils = require('./utils/bars')
var distance = require('./utils/distance')
var rules = require("./research/rule-based/rules.js")
var natural = require('natural');
var classifiers = limdu.classifiers;
var ftrs = limdu.features;
var Hierarchy = require(__dirname+'/Hierarchy');
var bars = require('./utils/bars')
var execSync = require('child_process').execSync
var async_adapter = require('./utils/async_adapter')
var async = require('async');
var stopwords = JSON.parse(fs.readFileSync(__dirname+'/stopwords.txt', 'UTF-8')).concat(JSON.parse(fs.readFileSync(__dirname+'/smart.json', 'UTF-8')))
var log_file = "./logs/" + process.pid
var Lemmatizer = require('javascript-lemmatizer')
var lemmatizer = new Lemmatizer();
var antonyms = {}
//var data = fs.readFileSync("./antonyms.txt", 'utf8').split("\n")
/*_.each(data, function(value, key, list){
var value1 = value.split(",")
antonyms[value1[0]] = value1[1]
antonyms[value1[1]] = value1[0]
}, this)
*/
var old_unused_tokenizer = {tokenize: function(sentence) { return sentence.split(/[ \t,;:.!?]/).filter(function(a){return !!a}); }}
var tokenizer = new natural.RegexpTokenizer({pattern: /[^a-zA-Z0-9\-\?]+/});
console.vlog = function(data) { fs.appendFileSync(log_file, data + '\n', 'utf8') };
// var tokenizer = new natural.WordTokenizer({'pattern':(/(\W+|\%)/)}); // WordTokenizer, TreebankWordTokenizer, WordPunctTokenizer
// var ngrams = new natural.NGrams.ngrams()
// var enhance = function (classifierType, featureExtractor, inputSplitter, featureLookupTable, labelLookupTable, preProcessor, postProcessor, TestSplitLabel, multiplyFeaturesByIDF, featureExpansion, featureExpansionScale, featureExpansionPhrase, featureFine, expansionParam) {
var enhance = function (classifierType, featureExtractor, inputSplitter, featureLookupTable, labelLookupTable, preProcessor, postProcessor, TestSplitLabel, multiplyFeaturesByIDF, featureOptions) {
// var enhance = function (classifierType, featureLookupTable, labelLookupTable) {
return classifiers.EnhancedClassifier.bind(0, {
normalizer: normalizer,
inputSplitter: inputSplitter,
featureOptions:featureOptions,
// featureExpansion: featureExpansion,
// featureExpansionScale: featureExpansionScale,
// featureExpansionPhrase: featureExpansionPhrase,
// featureFine: featureFine,feExpansion
// expansionParam: expansionParam,
// stopwords: JSON.parse(fs.readFileSync(__dirname+'/stopwords.txt', 'UTF-8')).concat(JSON.parse(fs.readFileSync(__dirname+'/smart.json', 'UTF-8'))),
// spellChecker: [require('wordsworth').getInstance(), require('wordsworth').getInstance()],
featureExtractor: featureExtractor,
featureLookupTable: featureLookupTable,
labelLookupTable: labelLookupTable,
// featureExtractorForClassification: [
// ftrs.Hypernyms(JSON.parse(fs.readFileSync(__dirname + '/knowledgeresources/hypernyms.json'))),
// ],
multiplyFeaturesByIDF: multiplyFeaturesByIDF,
// multiplyFeaturesByIDF: false,
TfIdfImpl: natural.TfIdf,
// tokenizer: new natural.RegexpTokenizer({pattern: /[^a-zA-Z0-9%'$,]+/}),
//minFeatureDocumentFrequency: 2,
// pastTrainingSamples: [], // to enable retraining
classifierType: classifierType,
preProcessor: preProcessor,
postProcessor: postProcessor,
});
};
var regexpNormalizer = ftrs.RegexpNormalizer(
JSON.parse(fs.readFileSync(__dirname+'/knowledgeresources/BiuNormalizations.json')));
// var regexpNormalizer_simple = ftrs.RegexpNormalizer(
// JSON.parse(fs.readFileSync(__dirname+'/knowledgeresources/SimpleNormalizations.json')));
// output: only intent
// and only single labeled or null output
// shoud be prepared for train(input and output) and test(input)
// sentence is a hash and not an array
// lemma and pos are required
function getRule(text)
{
/* if (!('tokens' in sen))
{
console.vlog("DEBUGRULE: for some reason tokens is not in the sentence " + JSON.stringify(sen, null, 4))
throw new Error("DEBUGRULE: for some reason tokens is not in the sentence " + JSON.stringify(sen, null, 4))
}
*/
// var sentence = JSON.parse(JSON.stringify(sen))
console.vlog("getRule: sentence: "+text)
// change tokens
var tokenizer = new natural.RegexpTokenizer({pattern: /[^\%a-zA-Z0-9\-\?]+/});
text = regexpNormalizer(text.toLowerCase())
var tkns = natural.NGrams.ngrams(tokenizer.tokenize(text), 1)
var sentence = {}
sentence['tokens'] = []
_.each(tkns, function(value, key, list){
sentence['tokens'].push({
"word": value[0],
// "lemma": value[0]
"lemma": (lemmatizer.only_lemmas(value[0]).length > 0 ? lemmatizer.only_lemmas(value[0])[0]: value[0])
})
}, this)
console.vlog("getRule: enrich lemma: "+JSON.stringify(sentence['tokens'], null, 4))
// first fix % sign
_.each(sentence['tokens'], function(token, key, list){
if (_.isNull(token))
throw new Error("DEBUGRULE: token is null: " + JSON.stringify(sentence, null, 4))
if (key > 0)
if (token.lemma=='%')
{
sentence['tokens'][key-1].lemma = sentence['tokens'][key-1].lemma + "%"
sentence['tokens'][key-1].word = sentence['tokens'][key-1].word + "%"
}
if (key > 0)
if ((token.lemma == 'agreement') && (sentence['tokens'][key-1]["lemma"] == "no"))
{
sentence['tokens'][key-1].lemma = "no agreement"
sentence['tokens'][key-1].word = "no agreement"
}
if (key > 0)
if ((token.lemma == 'car') && (sentence['tokens'][key-1]["lemma"] == "no"))
{
sentence['tokens'][key-1].lemma = "no car"
sentence['tokens'][key-1].word = "no car"
}
}, this)
// filter punct symbols
var temp = JSON.parse(JSON.stringify(sentence['tokens']))
sentence['tokens'] = []
_.each(temp, function(token, key, list){
// if (!('pos' in token))
// throw new Error('DEBUGRULE: pos is not in the token')
if (!('lemma' in token))
throw new Error('DEBUGRULE: lemma is not in the token')
// if (!('word' in token))
// throw new Error('DEBUGRULE: word is not in the token')
if ((token.lemma!='.')&&(token.lemma!=',')&&(token.lemma!='%')&&(token.lemma!='$')&&(token.lemma!=':'))
sentence['tokens'].push(token)
}, this)
// if (sentence['tokens'].length == 0)
// throw new Error("DEBUGRULE: for some reason tokens is empty")
var RuleValues = {
'Salary': [['60000','60,000 USD'],['90000','90,000 USD'],['120000','120,000 USD']],
'Pension Fund': [['0%','0%'],['10%','10%'],['15%','15%'],['20%','20%']],
'Promotion Possibilities': [['fast','Fast promotion track'],['slow','Slow promotion track']],
'Working Hours': [['8','8 hours', '8 hour'],['9','9 hours', '9 hour'],['10','10 hours', '10 hour']],
'Job Description': [['QA','QA'],['Programmer','Programmer'],['Team','Team Manager'],['Project','Project Manager']]
// 'Job Description': ['QA','Programmer','Team Manager','Project Manager'],
//'Leased Car': ['Without leased car', 'With leased car', 'No agreement']
// 'Leased Car': [['without','Without leased car'], ['with', 'With leased car'], ['agreement','No agreement']]
}
var arAttrVal = ['000','salary','pension','fund','promotion','possibilities','working','hours','hour',
'job','description','60000','90000','120000','usd','fast','slow','track','8','9','10',
'qa','programmer','team','project','manager','agreement',
'0%','10%','15%','20%', 'no agreement', 'position','workday', 'with', 'car', 'no car', 'leased', 'without',
'quick', 'rental', 'taxi', 'vehicles', 'vehicle', 'rent-a-car', 'rented', 'wages', 'wage', 'pay', 'fee', 'non-rented', "programmers", "cars", "managers", "managers", "cars", "programmers", "promosions", "opportunities", "positions", "lease", "position", "positions"]
// arAttrVal = arAttrVal.concat(['no car', "company car", "leased", "car", "leased", "with", "without"])
var ar_values = {}
var ar_attrs = {}
// check the salary
sentence['tokens'] = _.map(sentence['tokens'], function(unigram){ unigram.lemma = unigram.lemma.replace(/[,.]/g,''); return unigram });
sentence['tokens'] = _.map(sentence['tokens'], function(unigram){ unigram.lemma = unigram.lemma.replace(/0k/g,'0000'); return unigram });
sentence['tokens'] = _.map(sentence['tokens'], function(unigram){ if (unigram.lemma == "90") {unigram.lemma = "90000"; return unigram}
else if (unigram.lemma=="60") {unigram.lemma = "60000"; return unigram}
else if (unigram.lemma=="120") {unigram.lemma = "120000"; return unigram}
else return unigram});
var cleaned = JSON.parse(JSON.stringify(sentence))
var unigrams = _.map(sentence['tokens'], function(token){ return token.lemma.toLowerCase()});
// var words = _.map(sentence['tokens'], function(token){ return token.word.toLowerCase()});
_.each(RuleValues, function(values, attr, list){
// the biggest intersection
if (_.intersection(unigrams, attr.toLowerCase().split(" ")).length != 0)
ar_attrs[attr] = 1
_.each(values, function(value, key, list){
var temp = []
if (!_.isArray(value))
{
temp.push(value)
temp.push(value)
}
else
temp=value
if (_.intersection(unigrams, temp[0].toLowerCase().split(" ")).length != 0)
{
ar_attrs[attr] = 1
ar_values[temp[1]] = 1
}
}, this)
}, this)
if (unigrams.indexOf("no car")!=-1)
{
ar_attrs["Leased Car"]= 1
ar_values['Without leased car']=1
}
if (unigrams.indexOf("car")!=-1)
{
ar_attrs["Leased Car"]= 1
if (unigrams.indexOf("without")!=-1) ar_values['Without leased car']=1
if (unigrams.indexOf("with")!=-1) ar_values['With leased car']=1
if (unigrams.indexOf("no")!=-1) ar_values['Without leased car']=1
/*if ('basic-dependencies' in sentence)
{
_.each(sentence['basic-dependencies'], function(dep, key, list){
if ((dep['dep']=='neg')&&(['car','leased'].indexOf(dep['governorGloss']!=-1)))
ar_values['Without leased car']=1
}, this)
}
*/
if (unigrams.indexOf("agreement")!=-1)
{
delete ar_values['With leased car']
delete ar_values['Without leased car']
}
}
// work around for missing car
if (("Leased Car" in ar_attrs) || ("Pension Fund" in ar_attrs) || ("Promotion Possibilities" in ar_attrs))
if (unigrams.indexOf("no agreement")!=-1)
ar_values["No agreement"]=1
if ("Leased Car" in ar_attrs)
if (!("With leased car" in ar_values))
if (!("Without leased car" in ar_values))
if (!("No agreement" in ar_values))
if (unigrams.indexOf("car")!=-1)
ar_values["With leased car"]=1
cleaned['tokens'] = []
_.each(sentence['tokens'], function(token, key, list){
if (arAttrVal.indexOf(token.lemma.toLowerCase())==-1)
cleaned['tokens'].push(token)
}, this)
return {
'labels':[_.unique(_.keys(ar_attrs)), _.unique(_.keys(ar_values))],
'cleaned': cleaned
}
}
// convert array of sentences into one sentence
function preProcessor_onlyIntent(value)
{
var initial = value
if ("input" in value)
{
if (value.input.sentences.length > 1)
{
console.vlog(process.pid + "DEBUG: the train instance is filtered due to multiple sentences "+initial.output)
return undefined
}
// clean all the attr and values stuff from the sentence
// every fe... clean by itself
// value.input.sentences = getRule(value.input.sentences[0]).cleaned
value.input.sentences = value.input.sentences[0]
}
if ("output" in value)
{
value.output = _.map(value.output, Hierarchy.splitPartEquallyIntent);
value.output = _.unique(_.flatten(value.output))
if (value.output.length > 1)
{
console.log(process.pid + "DEBUG: the train instance is filtered "+initial.output)
return undefined
}
else
return value
}
else
return value
/*var initial = value
if (_.isObject(value))
{
// it's from test and it's object
if ("text" in value)
{
console.log("its test")
var sentence = rules.generatesentence({'input':value.text, 'found': rules.findData(value.text)})['generated']
sentence = sentence.replace(/<VALUE>/g,'').replace(/<ATTRIBUTE>/g,'').replace(/NIS/,'').replace(/nis/,'').replace(/track/,'').replace(/USD/,'').trim()
value.text = sentence
return value
}
// it's from train
if ("input" in value)
{
value.output = _.map(value.output, Hierarchy.splitPartEquallyIntent);
value.output = _.unique(_.flatten(value.output))
if (value.output.length > 1)
{
console.log(process.pid + "DEBUG: the train instance is filtered "+initial.output)
return undefined
}
// text in input
if (_.isObject(value.input))
{
var sentence = rules.generatesentence({'input':value.input.text, 'found': rules.findData(value.input.text)})['generated']
sentence = sentence.replace(/<VALUE>/g,'').replace(/<ATTRIBUTE>/g,'').replace(/NIS/,'').replace(/nis/,'').replace(/track/,'').replace(/USD/,'').trim()
value.input.text = sentence
return value
}
else
{
var sentence = rules.generatesentence({'input':value.input, 'found': rules.findData(value.input)})['generated']
sentence = sentence.replace(/<VALUE>/g,'').replace(/<ATTRIBUTE>/g,'').replace(/NIS/,'').replace(/nis/,'').replace(/track/,'').replace(/USD/,'').trim()
value.input = sentence
return value
}
}
}
else
{
// it's just string from test
sentence_clean = rules.generatesentence({'input':value, 'found': rules.findData(value)})['generated']
sentence_clean = sentence_clean.replace(/<VALUE>/g,'').replace(/<ATTRIBUTE>/g,'').replace(/NIS/,'').replace(/nis/,'').replace(/track/,'').replace(/USD/,'').trim()
return sentence_clean
}
*/
}
function postProcessor(sample,classes)
{
// console.log(JSON.stringify(sample, null, 4))
if (!('context' in sample))
throw new Error("context is not in the sampe "+ sample)
if (!_.isArray(classes))
classes = [classes]
if (classes.length > 1)
console.log("DEBUGPOST: more than one intent "+ classes)
feContext(sample, {}, false, {'offered': true, 'unoffered':true}, function(err, feat){
console.log("DEBUGPOST: features to find uniffered "+feat)
if ('UNOFFEREDVALUE' in feat)
{
console.log("DEBUGPOST: unoffered is inside")
var index = classes.indexOf("Accept");
if (index !== -1)
classes[index] = "Offer"
console.log("DEBUGPOST: classes "+classes)
}
})
// no accept:true after reject
if (sample['context'].length > 0)
{
if (_.keys(JSON.parse(sample['context'][0]))[0] == "Reject")
{
var index = classes.indexOf("Accept");
if (index !== -1)
classes[index] = "NoIntent"
}
}
var attrval = getRule(sample.sentences).labels
console.log("DEBUGPOST: classes before check "+classes+classes.length)
if ((attrval[1].length > 0) && (classes.length==0))
{
console.log("DEBUGPOST: Offer was added as default intent")
classes.push("Offer")
}
console.log("DEBUGPOST: classes after check"+classes+classes.length)
console.log("DEBUGPOST: labels "+JSON.stringify(attrval))
return bars.coverfilter(bars.generate_possible_labels(bars.resolve_emptiness_rule([classes, attrval[0], attrval[1]])))
}
/*
function postProcessor(sample,classes)
{
// console.log(JSON.stringify(classes, null, 4))
if (!_.isArray(classes))
classes = [classes]
if (classes.length > 1)
console.log("WARNING")
var attrval = rules.findData(sample)
var attrs = []
var values = []
_.each(attrval[0], function(value, key, list){
attrs.push(value[0])
}, this)
_.each(attrval[1], function(value, key, list){
values.push(value[0])
}, this)
console.log("rulezzz")
console.log(JSON.stringify(attrval, null, 4))
// console.log(JSON.stringify(attrval, null, 4))
// console.log(JSON.stringify(classes, null, 4))
// console.log(JSON.stringify(attrs, null, 4))
// console.log(JSON.stringify(values, null, 4))
var labels = bars.coverfilter(bars.generate_possible_labels(bars.resolve_emptiness_rule([classes, attrs, values])))
// console.log(JSON.stringify(labels, null, 4))
// console.log("==========================================")
return labels
}
*/
function normalizer1(sentence) {
var truth = require("./research/rule-based/truth_utils.js")
var truth_filename = "../truth_teller/sentence_to_truthteller.txt"
sentence = sentence.toLowerCase().trim();
sentence = regexpNormalizer(sentence)
// if ((sentence.indexOf("+")==-1) && (sentence.indexOf("-")==-1))
// {
// console.log("verbnegation")
// var verbs = truth.verbnegation(sentence.replace('without','no'), truth_filename)
// }
// sentence = rules.generatesentence({'input':sentence, 'found': rules.findData(sentence)})['generated']
/*_.each(verbs, function(value, key, list){
if (value['polarity'] == 'P')
{
if (sentence.indexOf(value['form']+" ") != -1)
sentence = sentence.replace(value['form']+" ", value['form']+"+ ")
else
sentence = sentence.replace(" "+value['form'], " "+value['form']+"+")
}
else
{
if (sentence.indexOf(value['form']+" ") != -1)
sentence = sentence.replace(value['form']+" ", value['form']+"- ")
else
sentence = sentence.replace(" "+value['form'], " "+value['form']+"-")
}
}, this)*/
sentence = sentence.replace(/<VALUE>/g,'')
sentence = sentence.replace(/<ATTRIBUTE>/g,'')
sentence = sentence.trim()
// console.log("normalized")
// console.log(sentence)
// sentence = sentence.replace(/\s+/g,' ')
return sentence
}
function normalizer(sentence) {
// console.log("norm")
// console.log(sentence)
// if (_.isObject(sentence))
// sentence.text = regexpNormalizer(sentence.text.toLowerCase().trim())
// else
if (_.isUndefined(sentence))
{
throw new Error("For some reason sentence is undefined")
process.exit(0)
}
sentence = regexpNormalizer(sentence.toLowerCase().trim())
// console.log(sentence)
// sentence = rules.generatesentence({'input':sentence, 'found': rules.findData(sentence)})['generated']
// sentence = sentence.replace(/[\<,\>]/g,' ')
// sentence = sentence.replace(/\n/g,' ')
// sentence = sentence.replace(/<ATTRIBUTE>/g,'')
// sentence = regexpNormalizer_simple(sentence)
return sentence
}
var regexpString = "([,.;?!]| and | if | however | but )"; // to capture the delimiters
var regexp = new RegExp(regexpString, "i");
var delimitersToInclude = {"?":true};
function inputSplitter(text) {
if (_.isObject(text)) text = text.text
console.log(JSON.stringify(text, null, 4))
var normalizedParts = [];
if (/^and/i.test(text)) { // special treatment to a sentence that starts with "and"
normalizedParts.push("and");
text = text.replace(/^and\s*/,"");
}
var parts = text.split(regexp);
for (var i=0; i<parts.length; i+=2) {
parts[i] = parts[i].trim();
var part = parts[i];
if (i+1<parts.length) {
var delimiter = parts[i+1];
if (delimitersToInclude[delimiter])
part += " " + delimiter;
}
if (part.length>0)
normalizedParts.push(part);
}
console.log(JSON.stringify(normalizedParts, null, 4))
console.log("-------------------------------")
return normalizedParts;
}
// function featureExtractorB(sentence, features) {
// var words = tokenizer.tokenize(sentence);
// var feature = natural.NGrams.ngrams(words, 2)
// _.each(feature, function(feat, key, list){ features[feat.join(" ")] = 1 }, this)
// return features;
// }
/*function featureExtractorU(sentence, features) {
var corp = sentence.match(/\<\w*\.*\w*\>/g)
var sentence = sentence.replace(/\<\w*\.*\w*\>/g," ")
var words = tokenizer.tokenize(sentence);
var feature = natural.NGrams.ngrams(words, 1)
_.each(feature, function(feat, key, list){
// if (!bars.isstopword(feat.join(" ")))
features[feat.join(" ")] = 1 }
,this)
_.each(corp, function(co, key, list){
features[co] = 1
}, this)
return features;
}
*/
// function featureExtractorUB(sentence, features) {
// var words = tokenizer.tokenize(sentence);
// // var feature = natural.NGrams.ngrams(words, 1).concat(natural.NGrams.ngrams(words, 2, '[start]', '[end]'))
// var feature = natural.NGrams.ngrams(words, 1).concat(natural.NGrams.ngrams(words, 2))
// _.each(feature, function(feat, key, list){ features[feat.join(" ")] = 1 }, this)
// return features;
// }
// if train then true
/*function feExpansion(sample, features, train, featureOptions, callback) {
// featureOptions.scale
// featureOptions.relation
// featureOptions.allow_offer
// featureOptions.expand_test
// featureOptions.best_results
var sentence = ""
var innerFeatures = JSON.parse(JSON.stringify(features))
if (_.isObject(sample))
if ("input" in sample)
sentence = sample.input.text
else
sentence = sample.text
else
sentence = sample
if (!('input' in sample))
{
var sampleTemp = {}
sampleTemp['input']= sample
sample=sampleTemp
}
if (!('sentences' in sample['input']))
throw new Error("sentences not in the sample")
console.log(process.pid + " DEBUG: train: "+train + " options: "+JSON.stringify(featureOptions))
sentence = sentence.toLowerCase().trim()
var words = tokenizer.tokenize(sentence);
var unigrams = _.flatten(natural.NGrams.ngrams(words, 1))
//_.each(unigrams, function(unigram, key, list){ if (stopwords.indexOf(unigram)==-1) features[unigram] = 1 }, this)
// _.each(unigrams, function(unigram, key, list){ if (stopwords.indexOf(unigram)==-1) features[unigram] = 1 }, this)
_.each(unigrams, function(unigram, key, list){ innerFeatures[unigram] = 1 }, this)
// if (((!featureOptions.expand_test) && (train)) || (featureOptions.expand_test))
// {
async.waterfall([
function(callbackl1){
if (((!featureOptions.expand_test) && (train)) || (featureOptions.expand_test))
{
console.log("DEBUG: train"+train + " unigrams "+unigrams)
callbackl1(null)
}
else
{
console.log(process.pid + " DEBUG: callback classify noexpansion"+ train +" "+ _.keys(features))
callback(null, innerFeatures)
}
},
function(callbackl) {
if ((!featureOptions.allow_offer)&&(train))
{
if (sample.output[0] == "Offer")
{
console.log("Offer no expansion")
callback(null, innerFeatures)
}
}
var poses = {}
var roots = []
console.log("DEBUG train" + train)
_.each(sample['input']['sentences'], function(sentence, key, list){
_.each(sentence['tokens'], function(token, key, list){
poses[token.word.toLowerCase()] = token.pos
}, this)
_.each(sentence['basic-dependencies'], function(dep, key, list){
if (dep.dep == "ROOT")
roots.push(dep.dependentGloss.toLowerCase())
}, this)
}, this)
console.log("poses train" + train + " " + JSON.stringify(poses))
callbackl(null, poses, roots);
},
function(poses, roots, callbackll) {
async.forEachOfSeries(unigrams, function(unigram, dind, callback2){
// async.forEachOfSeries(_.keys(poses), function(unigram, dind, callback2){
if (((!featureOptions.onlyroot) && (stopwords.indexOf(unigram)==-1))
|| ((featureOptions.onlyroot) && (roots.indexOf(unigram)!=-1)))
{
if (!(unigram in poses))
throw new Error(unigram + " is not found in "+poses)
async_adapter.getppdb(unigram, poses[unigram], featureOptions.scale, featureOptions.relation, function(err, results){
console.log("getppdb train" + train + " "+JSON.stringify(unigram))
// get rid of phrases
console.log(process.pid + " DEBUG EXP: results with phrases "+results.length)
results = _.filter(results, function(num){ return num[0].indexOf(" ") == -1 })
console.log(process.pid + " DEBUG EXP: results without phrases "+results.length)
results = _.map(results, function(num){ return num[0] });
results = _.uniq(results)
if (!_.isUndefined(featureOptions.best_results))
results = results.slice(0, featureOptions.best_results)
_.each(results, function(expan, key, list){
innerFeatures[expan.toLowerCase()] = 1
}, this)
callback2()
})
}
else
callback2()
}, function(err){callbackll()})
}],
function (err, result) {
console.log(process.pid + " DEBUG EXP: "+unigrams+ " EXPANSIONED "+_.keys(innerFeatures)+ " train"+train+" featureOptions"+JSON.stringify(featureOptions))
callback(null, innerFeatures)
});
// }
// else
// {
// console.log(process.pid + " DEBUG: callback classify noexpansion"+ train +" "+ _.keys(features))
// return callback(null, features)
// }
}
*/
// as a feature source it gets it from upper feature extraction level
function feExpansion(sample_or, features, train, featureOptions, callback) {
// featureOptions.scale
// featureOptions.relation
var sample = JSON.parse(JSON.stringify(sample_or))
if (!('allow_offer' in featureOptions)) throw new Error("allow_offer is not in the featureOptions")
if (!('expand_test' in featureOptions)) throw new Error("expand_test is not in the featureOptions")
if (!('best_results' in featureOptions)) throw new Error("best_results is not in the featureOptions")
var sentence = ""
var innerFeatures = JSON.parse(JSON.stringify(features))
var output = []
if (!("input" in sample))
{
var temp = JSON.parse(JSON.stringify(sample))
var sample ={'input':temp}
}
if (!('sentences' in sample['input']))
throw new Error("sentences not in the sample")
console.vlog("DEBUGEXP: START: train: "+train + " options: "+JSON.stringify(featureOptions)+ "text: "+sample.input.text)
//console.vlog("DEBUGEXP: START: sample: "+JSON.stringify(sample, null, 4))
var cleaned = getRule(sample["input"]["sentences"]).cleaned
var cleaned_tokens = _.map(cleaned.tokens, function(num){ return num.word; });
// feAsync(sample, {}, train, {}, function(err, featuresAsync){
// innerFeatures = _.extend(innerFeatures, featuresAsync)
async.waterfall([
function(callbackl1){
if (((!featureOptions.expand_test) && (train)) || (featureOptions.expand_test))
{
callbackl1(null)
}
else
{
console.vlog("DEBUGEXP: callback classify noexpansion"+ train +" "+ _.keys(features))
callback(null, innerFeatures)
}
},
function(callbackl) {
console.vlog("DEBUGEXP: continue")
if ((!featureOptions.allow_offer)&&(train))
{
if (sample.output[0] == "Offer")
{
console.vlog("Offer no expansion")
callback(null, innerFeatures)
}
}
var poses = {}
var roots = []
// console.vlog("DEBUG train" + train)
_.each(sample['input']['sentences']['tokens'], function(token, key, list){
// _.each(sentence['tokens'], function(token, key, list){
poses[token.word.toLowerCase()] = {
'pos':token.pos,
'lemma': token.lemma.toLowerCase(),
'word': token.word.toLowerCase(),
'neg': false
}
}, this)
// console.vlog("DEBUGEXP: found tokens: "+JSON.stringify(poses, null, 4))
_.each(sample['input']['sentences']['basic-dependencies'], function(dep, key, list){
if (dep.dep == "ROOT")
roots.push(dep.dependentGloss.toLowerCase())
// if (dep.dep == "xcomp")
// roots.push(dep.dependentGloss.toLowerCase())
if (dep.dep == "neg")
{
poses[dep.governorGloss.toLowerCase()]["neg"] = true
delete poses[dep.dependentGloss.toLowerCase()]
}
}, this)
// }, this)
// eliminate number from root
var roots = _.filter(roots, function(num){ return num.indexOf("0") == -1 });
console.vlog("DEBUGEXP: words to expand: " + roots)
// console.vlog("DEBUGEXP: poses: " + JSON.stringify(poses))
callbackl(null, poses, roots);
},
function(poses, roots, callbackll) {
// var allowedpos = ["vb","vbd","vbg","vbn","vbp","vbz","uh","wp","wdt"]
async.forEachOfSeries(poses, function(token, unigram, callback2){
// async.forEachOfSeries(_.keys(poses), function(unigram, dind, callback2){
if (((!featureOptions.onlyroot) && (stopwords.indexOf(unigram)==-1))
//|| ((featureOptions.onlyroot) && (roots.indexOf(unigram)!=-1) && (allowedpos.indexOf(token.pos.toLowerCase())!=-1) && (cleaned_tokens.indexOf(unigram)!=-1)))
|| ((featureOptions.onlyroot) && (roots.indexOf(unigram)!=-1) && (cleaned_tokens.indexOf(unigram)!=-1)))
{
// we any case we are taking lemma and verb so take VB pos tag
// if ((featureOptions.onlyroot) && (token.pos.toLowerCase().indexOf("vb")!=-1))
// token.pos = "VB"
// if (!(unigram in poses))
// throw new Error(unigram + " is not found in "+poses)
console.vlog("DEBUGEXP: ready to expand train:" + train + " "+JSON.stringify(token))
async_adapter.getppdb(token.lemma, token.pos, featureOptions.scale, featureOptions.relation, function(err, results){
// async_adapter.getwordnet(token.lemma, token.pos, function(err, results){
// get rid of phrases
console.vlog("DEBUGEXP: number of results with phrases "+results.length)
results = _.filter(results, function(num){ return num[0].indexOf(" ") == -1 })
console.vlog("DEBUGEXP: number of results without phrases "+results.length)
results = _.map(results, function(num){ return num[0] });
results = _.uniq(results)
if (!_.isUndefined(featureOptions.best_results))
results = results.slice(0, featureOptions.best_results)
console.vlog("DEBUGEXP: results to add for token:"+ JSON.stringify(token)+ " results:"+JSON.stringify(results))
console.log("DEBUGEXP: results to add for token:"+ JSON.stringify(token)+ " results:"+JSON.stringify(results))
//Lem.lemmatize(results, function(err, lemmas) {
_.each(results, function(expan, key, list){
var temp = JSON.parse(JSON.stringify(innerFeatures))
if (token.neg)
expan+="-"
delete temp[token.word+"-"]
delete temp[token.word]
// innerFeatures[expan.toLowerCase()] = 1
temp[expan.toLowerCase()] = 1
output.push(JSON.parse(JSON.stringify((temp))))
console.vlog("DEBUGEXP: temp: "+JSON.stringify(temp))
}, this)
// console.vlog("DEBUGEXP: permanent features "+JSON.stringify(innerFeatures))
callback2()
// })
})
}
else
callback2()
}, function(err){callbackll()})
}],
function (err, result) {
// callback(null, innerFeatures)
console.vlog("DEBUGEXP: finish with "+output.length +" generated instances")
callback(null, output)
});
// }
// else
// {
// console.log(process.pid + " DEBUG: callback classify noexpansion"+ train +" "+ _.keys(features))
// return callback(null, features)
// }
// })
}
// as a feature source it gets it from upper feature extraction level
function feExpansionW(sample_or, features, train, featureOptions, callback) {
// featureOptions.scale
// featureOptions.relation
var sample = JSON.parse(JSON.stringify(sample_or))
if (!('allow_offer' in featureOptions)) throw new Error("allow_offer is not in the featureOptions")
if (!('expand_test' in featureOptions)) throw new Error("expand_test is not in the featureOptions")
if (!('best_results' in featureOptions)) throw new Error("best_results is not in the featureOptions")
var sentence = ""
var innerFeatures = JSON.parse(JSON.stringify(features))
var output = []
if (!("input" in sample))
{
var temp = JSON.parse(JSON.stringify(sample))
var sample ={'input':temp}
}
if (!('sentences' in sample['input']))
throw new Error("sentences not in the sample")
console.vlog("DEBUGEXP: START: train: "+train + " options: "+JSON.stringify(featureOptions)+ "text: "+sample.input.text)
//console.vlog("DEBUGEXP: START: sample: "+JSON.stringify(sample, null, 4))
var cleaned = getRule(sample["input"]["sentences"]).cleaned
var cleaned_tokens = _.map(cleaned.tokens, function(num){ return num.word; });
// feAsync(sample, {}, train, {}, function(err, featuresAsync){
// innerFeatures = _.extend(innerFeatures, featuresAsync)
async.waterfall([
function(callbackl1){
if (((!featureOptions.expand_test) && (train)) || (featureOptions.expand_test))
{
callbackl1(null)
}
else
{
console.vlog("DEBUGEXP: callback classify noexpansion"+ train +" "+ _.keys(features))
callback(null, innerFeatures)
}
},
function(callbackl) {
console.vlog("DEBUGEXP: continue")
if ((!featureOptions.allow_offer)&&(train))
{
if (sample.output[0] == "Offer")