-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaidata.htm
More file actions
801 lines (738 loc) · 40.5 KB
/
Copy pathaidata.htm
File metadata and controls
801 lines (738 loc) · 40.5 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link REL="SHORTCUT ICON" HREF="img/favicon.ico">
<title>AI Training Data Loader</title>
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="lib/papaparse.min.js"></script>
<script src="nlp.js"></script>
</head>
<style>
body { font-family:Segoe UI,Verdana,Geneva,sans-serif;font-size:16px; margin:20px; }
.lz-is { border-radius:16px; padding:0 8px; height: 24px; border:1px solid #999; font-size: 13px; text-align:center; }
.lz-bs { display:inline-block; border-radius:16px; padding:0 16px; border:1px solid #999; font-size: 13px;
cursor:pointer; z-index:2; padding-bottom:1px; color:#000; background-color: #eee; font-weight:600; }
.lz-bsg { cursor: pointer; color:#fff; text-align: center; border-radius: 16px; display: inline-block; user-select: none;
font-size: 13px; background-color: #999; padding: 2px 8px 2px 8px; }
.lz-confirm { position: absolute; width: 300px; padding: 16px; left: calc(50% - 150px); top: calc(50% - 50px); user-select: none;
border-radius: 8px; background-color: #fff; border: 1px solid #999; box-shadow: 4px 2px 12px 2px #aaa; }
</style>
<body>
<input type="file" id="lz-tempFile" accept=".csv,.CSV" style="display:none">
<input type="file" id="lz-trainFile" accept=".csv,.CSV,.yml" style="display:none">
<input type="file" id="lz-testFile" accept=".csv,.CSV,.yml" style="display:none">
<input type="file" id="lz-augmentFile" accept=".csv,.CSV,.yml" style="display:none">
<div style="width:66%;margin:0 auto;text-align:center">
<img src="img/logo.png" style="width:25%">
<hr>
AI: <select class="lz-is" id="lz-aiType">
<option>Wit</option><option>Dialog-ES</option><!option>Dialog-CX</!option>
</select> 
Activity: <select class="lz-is" id="lz-dataset">
<option>Test</option><option>Activity4</option><option>Activity3</option><option>Activity2</option>
</select> 
<div class="lz-bs" id="lz-testData">Test data</div>
<div class="lz-bs" id="lz-trainData">Train data</div>
<div class="lz-bs" id="lz-deleteData">Delete data</div>
<div class="lz-bs" id="lz-augmentData">Augment data</div>
</p>
<hr><br>
Type test remark here: <input type="input" class="lz-is" style="width:50%" id="lz-utter"/> <span id="lz-result"></span>
<br><br><hr><br>
<p id="outp" style="text-align:left"></p>
</div>
<script>
/////////////////////////////////////////////////////////////////////////////////////////////////
// APP
/////////////////////////////////////////////////////////////////////////////////////////////////
let rawData=[], intents=[], session=[], keyWords=[], vocab=[]; uvocab=[];
let nData=[]; // Holds augmented data
let nlp=new NLP(); // Alloc NLP class
let ws=null; // Socket server
let aiType="wit"; // AI type
let modelName="Test"; // AI Model to use
let witToken={},dfToken={};
witToken.Activity2="3VVZ-X-FEZSKKSSZS-X-OTY53FE2-X-AQMA3MF26W".replace(/-X-/g,""); // Activity 2
witToken.Activity3="FDFR3T-X-S7ELJPI6QCIGV-X-ZPKE-X-A2X65Q6JS".replace(/-X-/g,""); // Activity 3
witToken.Activity4="4XRYT-X-245DCKOI-X-647DEFUBZ3PG6-X-KOGZCI".replace(/-X-/g,""); // Activity 4
witToken.Test="POQILB6-X-KVNPU3PR665-X-V3PPL3CXU-X-CU6E4".replace(/-X-/g,""); // Wit test
dfToken.Test="ceadb93e-da17-448f-beb4-638fe5a367df"; // DF test
$(document).ready(function() { // ON PAGE LOADED
InitSocketServer();
$("#lz-testData").on("click",()=> { $("#lz-testFile").trigger("click"); } ); // ON TEST TRAINING DATA
$("#lz-deleteData").on("click", ()=> { // ON DELETE TRAINING DATA
if ((window.location.host == "localhost") || (modelName == "Test")) // Only allow localy or the test activity
DeleteTrainingData(); // Delete data
}); 77
$("#lz-trainData").on("click", ()=> { // ON TRAIN DATA
if ((window.location.host == "localhost") || (modelName == "Test")) // Only allow localy or the test activity
$("#lz-trainFile").trigger("click");
});
$("#lz-augmentData").on("click", ()=> { $("#lz-augmentFile").trigger("click")}); // ON AUGMENT TRAINING DATA
$("#lz-dataset").on("change", ()=> { modelName=$("#lz-dataset").val(); }); // ON DATASET CHANGE
$("#lz-aiType").on("change", ()=> { aiType=$("#lz-aiType").val().toLowerCase(); }); // ON AI CHANGE
$("#lz-tempFile").on("change",(e)=>{ // ON TEMP FILE LOAD
ImportCSV(e); // Read file
$("#lz-tempFile").val(""); // Clear value
});
$("#lz-trainFile").on("change",(e)=>{ // ON TRAIN FILE LOAD
TrainData(e); // Read file
$("#lz-trainFile").val(""); // Clear value
});
$("#lz-augmentFile").on("change",(e)=>{ // ON AUGMENT FILE LOAD
AugmentData(e); // Read file
$("#lz-augmentFile").val(""); // Clear value
});
$("#lz-testFile").on("change",(e)=>{ // ON TEST FILE LOAD
TestData(e); // Read file
$("#lz-testFile").val(""); // Clear value
});
$("#lz-utter").on("change",(e)=>{ // ON TEST REMARK
InferIntents([{remark:$("#lz-utter").val()}],(r)=>{
trace(r)
$("#lz-result").html(`<b>${r.intent}</b> at ${Math.round(r.confidence*100)}%`);
});
});
$(window).on("keydown",function(e) { // HANDLE KEYPRESS
if ((e.which == 81) && e.ctrlKey) { // Test key (CTL-Q)
}
});
});
async function TrainData(e) // TRAIN DATA
{
let holdPct=0;
let holds=[],d=[];
let file=e.target.files[0]; // Point at file
if (!file) return; // Quit if bad
let reader=new FileReader(); // Init reader
reader.readAsText(file); // Read file
reader.onload=(e)=>{ // When loaded
let s=e.target.result; // Point at raw data
let uniqueIntents=[]; // Hold unique intents used
s=s.replace(/\(V1\).+?,/,"valued,"); // Normalize V1 variance name
s=s.replace(/\(V2\).+?,/,"language,"); // V2
s=s.replace(/\(V3\).+?,/,"knowledge,"); // V3
s=s.replace(/\(V4\).+?,/,"thinking,"); // V4
let i,j,k,re,d=Papa.parse(s.replace(/[!|?]/g,"."),{ header:true, skipEmptyLines:true }).data; // Parse CSV using papa lib
SaveResponseFile(d); // Save student responses to new CSV file
if (holdPct) { // If holding some out
v=groupBy(d,"intent"); // Group by intent
d=[]; // Clear array
for (intent in v) { // For each intent
k=Math.round(v[intent].length/(v[intent].length*holdPct)); // Hold increment
trace(Math.round(v[intent].length),k)
for (i=0;i<v[intent].length;++i) { // For each intent
if (i%k) d.push(v[intent][i]); // Train this one
else holds.push(v[intent][i]); // Hold this one
}
}
if (holds.length) { // If any holds
let fields=["intent","remark","note"]; // Field names
let str=Papa.unparse(holds,{ header:true, skipEmptyLines:true, columns:fields }); // Make CSV using lib
SaveTextAsFile("holds.csv",str); // Write file
}
}
for (i=0;i<d.length;++i) { // For each remark
if (d[i].remark == "") { d.splice(i,1); continue; } // No remark
if (d[i].intent == "") { d.splice(i,1); continue; } // No intent
if (d[i].intent == "r") { d.splice(i,1); continue; } // No intent
if (d[i].intent) uniqueIntents.push(d[i].intent); // Get intent
d[i].remark=CleanRemark(d[i].remark); // Clean up remark
}
uniqueIntents=[... new Set(uniqueIntents)]; // Make unique
if (aiType == "wit") { // WIT.AI
ConfirmBox("Are your sure?","Old data must be deleted first.",()=>{ // Confirm
TrainWit(d,uniqueIntents); // Add intents and utterances
});
}
else if (aiType == "dialog-es") { // DIALOGFLOW-ES
TrainDialog(d,uniqueIntents); // Load and make training data
}
else if (aiType == "dialog-cx") { // DIALOGFLOW-CX
TrainDialogCX(d,uniqueIntents); // Load and make training data
}
};
function groupBy(arr, property) { // GROUP
return arr.reduce((acc, cur) => {
acc[cur[property]] = [...acc[cur[property]] || [], cur];
return acc;
}, {});
}
}
function CleanRemark(remark) // CLEAN UP REMARK
{
let i,re;
let studentNames=["Oliver","Sharleen","Luis","Jazmin","Chris","Farrah"]; // Student names
if (!remark) return(""); // No remark
for (i=0;i<studentNames.length;++i) { // For each name
re=new RegExp(studentNames[i],"ig"); // Make name regex
remark=remark.replace(re,""); // Replace names with blank
}
remark=remark.toLowerCase(); // Make l/c
remark=remark.replace(/\,\-\.|\!\?|\'|"]|'/g,""); // Remove punctuation
remark=remark.replace(/&/g,"and"); // No &
// remark=remark.replace(/\r/g,""); // No CR
// remark=remark.replace(/\n/g,""); // No LF
return remark; // Return cleaned remark
}
async function AugmentData(e) // AuGMENT DATA
{
let file=e.target.files[0]; // Point at file
if (!file) return; // Quit if bad
let i;
let reader=new FileReader(); // Init reader
reader.readAsText(file); // Read file
reader.onload=(e)=>{ // When loaded
nData=[]; // Start fresh
LoadingIcon(true); // Show loading icon
$("#lz-loadingIconText").html("<b>0%</b>"); // Show progress
let d=Papa.parse(e.target.result.replace(/[!|?]/g,"."),{ header:true, skipEmptyLines:true }).data; // Parse CSV using papa lib
for (i=0;i<d.length;++i) { // For each remark
if (!d[i].remark) { d.splice(i,1); continue; } // No remark
if (!d[i].intent) { d.splice(i,1); continue; } // No intent
}
let tot=d.length; // Total
Augment(d,(r1)=>{ // Mid way
$("#lz-loadingIconText").html("<b>"+(100-Math.floor(d.length*100/tot))+"%</b>"); // Show progress
},
(r2)=>{ // Done
let fields=["intent","remark","note"]; // Field names
nData=[... new Set(nData)]; // Cull dupes
let str=Papa.unparse(nData,{ header:true, skipEmptyLines:true, columns:fields }); // Make CSV using lib
SaveTextAsFile("augmented.csv",str); // Write file
Sound("ding"); // Ding
LoadingIcon(false); // Hide loading icon
});
};
}
function DeleteTrainingData() // DELETE TRAINING DATA
{
ConfirmBox("Are your sure?","",()=>{ // Confirm
LoadingIcon(true); // Start loading icon
if (aiType == "wit") { // WIT.AI
WitGetUtterances((d)=>{ // Get utterance list
WitDeleteUtternances(d,(r)=>{ trace(r); $("#lz-loadingIconText").html("<b>Remarks</b>"); }); // Delete existing utterances
});
WitGetIntents((d)=>{ // Get intents list
WitDeleteIntents(d,(r)=>{ trace(r); },(r)=>{ trace(r); Sound("ding"); LoadingIcon(false); }); // Delete existing intents
});
}
});
}
async function TestData(e) // TEST DATA
{
let i,k,o,v,id,str,s="";
let file=e.target.files[0]; // Point at file
if (!file) return; // Quit if bad
let reader=new FileReader(); // Init reader
reader.readAsText(file); // Read file
reader.onload=(e)=>{ // When loaded
LoadingIcon(true); // Show loading icon
let count=0,notFound=0; // Counts
let orig=[];
let d=Papa.parse(e.target.result, { header:true, skipEmptyLines:true }).data; // Parse CSV using papa lib
for (i=0;i<d.length;++i) orig.push(d[i]); // Copy
let tot=d.length; // Total
InferIntents(d, (res)=>{ // On each inference
i=(tot-d.length-1); // Current index
if (res.intent == "efault Fallback Intent") res.intent=res.confidence=0; // Not found
orig[i].intent=orig[i].intent.toLowerCase(); // Force LC
orig[i].confidence=res.confidence; // Save confidence
orig[i].infer=res.intent; // Save inferred intent
orig[i].match=(res.intent == orig[i].intent) ? 1 : 0; // Do they match?
if (res.confidence < .4) orig[i].match=-1; // Not properly inferred
count+=orig[i].match; // Add to count
$("#lz-loadingIconText").html("<b>"+Math.floor(i/tot*100)+"%</b>"); // Show progress
if (!d.length) { // If last one
Sound("ding"); // Ding
LoadingIcon(false); // Hide loading icon
let fields=["intent","remark","note","confidence","infer","match"]; // Field names
str=Papa.unparse(orig,{ header:true, skipEmptyLines:true, columns:fields });// Make CSV using lib
SaveTextAsFile("test.csv",str); // Write file
let results=[];
for (i=0;i<orig.length;++i) { // For each utterance
if (!results[orig[i].intent]) { // First one
results[orig[i].intent]={}; // Add obj
results[orig[i].intent].tot=0; // Init
results[orig[i].intent].match=0;
}
if (orig[i].match == 1) results[orig[i].intent].match++; // If a match
if (orig[i].match == -1) notFound++; // Add to bad count
results[orig[i].intent].tot++; // Add to count
}
for (o in results)
s+=o.toUpperCase()+" "+results[o].match+"/"+results[o].tot+" has "+Math.round(results[o].match/results[o].tot*100)+"% accuracy<br>"; // Intent accuracy
s+="<br>"+Math.round(count/tot*100)+"% total accuracy"; // Total accuracy
s+="<br>"+notFound+" Not categorized"; // Uncategorized
$("#outp").html(s.replace(/\t|\n|\r/g,"")); // Show stats
}
});
}
}
async function InferIntents(msgs, callback) // GET RESPONSE FROM AI
{
try {
let m=msgs.shift(); // Remove from list
m.remark=CleanRemark(m.remark); // Clean remark
let inference={ text:m.text, labeled:m.intent, intent:0, confidence:0 }; // Null inference
if (aiType == "rasa") { // If RASA
const response=await fetch("https://lizasim.com:5005/model/parse", { // Fetch data
method:"POST", // POST
body: JSON.stringify({text:m.remark}) // Payload
});
let res=await response.json(); // Get response
inference.intent=res.intent.name.substr(1); // Intent
inference.confidence=res.intent.confidence; // Confidence
inference.labeled=m.intent; // Labeled intent
callback(inference); // Return inference object
if (msgs.length) InferIntents(msgs, callback) // Recurse, if not last
}
else if (aiType == "dialog-es") { // If DIALOGFLOW
let p=new Promise((resolve, reject) => {
setTimeout(()=>{ws.send("Test|DIALOGFLOW-ES|ADMIN|INFER|activity3-viod|"+m.remark.substring(0,255))},500);
ws.onmessage=(e)=>{ // If a ws message
if (!e.data) return; // Quit if no data
let v=event.data.split("|"); // Get params
if (v[1] != "DIALOGFLOW") return; // Not a dialogflow inference
resolve(v) }; // Resolve promise
}).then(res =>{ // On resolution
inference.intent=res[2].substr(1); // Intent
inference.confidence=res[3]; // Confidence
callback(inference); // Return inference
if (msgs.length) InferIntents(msgs, callback) // Recurse, if not last
});
}
else if (aiType == "dialog-cx") { // If DIALOGFLOW-CX
let p=new Promise((resolve, reject) => {
setTimeout(()=>{ws.send("Test|DIALOGFLOW-CX|ADMIN|INFER|"+dfToken[modelName]+"|"+m.remark.substring(0,255))},500);
ws.onmessage=(e)=>{ // If a ws message
if (!e.data) return; // Quit if no data
let v=event.data.split("|"); // Get params
if (v[1] != "DIALOGFLOW-CX") return; // Not a dialogflow inference
resolve(v) }; // Resolve promise
}).then(res =>{ // On resolution
inference.intent=res[2].substr(1); // Intent
inference.confidence=res[3]; // Confidence
callback(inference); // Return inference
if (msgs.length) InferIntents(msgs, callback) // Recurse, if not last
});
}
else if (aiType == "dialog-es") { // If DIALOGFLOW-ES
let p=new Promise((resolve, reject) => {
trace(m)
setTimeout(()=>{ws.send("Test|DIALOGFLOW-ES|ADMIN|INFER|"+dfToken[modelName]+"|"+m.remark.substring(0,255))},500);
ws.onmessage=(e)=>{ // If a ws message
if (!e.data) return; // Quit if no data
let v=event.data.split("|"); // Get params
if (v[1] != "DIALOGFLOW-ES") return; // Not a dialogflow inference
resolve(v) }; // Resolve promise
}).then(res =>{ // On resolution
inference.intent=res[2].substr(1); // Intent
inference.confidence=res[3]; // Confidence
callback(inference); // Return inference
if (msgs.length) InferIntents(msgs, callback) // Recurse, if not last
});
}
else if (aiType == "wit") { // If WIT
let url="https://api.wit.ai/message?v=20210922&n=3&q="+m.remark.substring(0,255); // URL
const response=await fetch(url, { headers:{ Authorization:'Bearer '+witToken[modelName], 'Content-Type':'application/json'} }); // Send remark to wit
let res=await response.json(); // Get response
if (res.intents.length) { // If an intent found
trace(res)
inference.intent=res.intents[0].name.substring(1); // Get intent
inference.confidence=res.intents[0].confidence; // Confidence
}
callback(inference); // Return response
if (msgs.length) setTimeout(()=>{ InferIntents(msgs, callback);},200); // Recurse, if not last and add delay
}
} catch(e) {trace(e)}
}
function InitSocketServer() // INIT SOCKET SERVER
{
if (window.location.host == "localhost") ws=new WebSocket('ws://'+window.location.host+':8080'); // Open insecure websocket
else ws=new WebSocket('wss://'+window.location.host+':8082'); // Secure
ws.onclose=()=> { console.log('disconnected'); ws=null; Sound("delete") }; // ON CLOSE
ws.onerror=(e)=> { console.log('error',e); }; // ON ERROR
ws.onopen=()=> { console.log('connected'); }; // ON OPEN
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// OUTPUT
/////////////////////////////////////////////////////////////////////////////////////////////////
function FindPreviousResponse(ind) // GET PREVIOUS STUDENT RESPONSE
{
while (--ind >= 0) { // Search backwards
if (rawData[ind].speaker != "Teacher") // If not a teacher
return rawData[ind].text; // Return previous response
}
return ""; // No previous response
}
function ImportCSV(e) { // IMPORT SESSION FROM CSV
let i,d="";
let file=e.target.files[0]; // Point at file
if (!file) return; // Quit if bad
let reader=new FileReader(); // Init reader
reader.readAsText(file); // Read file
reader.onload=(e)=>{ // When loaded
let csv=Papa.parse(e.target.result, { header:false, skipEmptyLines:true }).data; // Parse CSV using papa lib
for (i=0;i<csv.length;++i) { // For each line
if (csv[i][8] == "Teacher") { // Only remarks
if (csv[i][11] == "1") s=csv[i][11]; // Original correction
else if (csv[i][11] == "2") s=csv[i][13]; // Double correction
else s=csv[i][10]; // No correction, use original
if (s.length < 4) continue; // Skip if too short
s=nlp.CleanRemark(s); // Make line
d+=" - "+s+"\n"; // Add
}
}
trace(d)
Sound("ding"); // Ding
};
}
function SaveResponseFile(f) // EXTRACT AND SAVE STUDENT RESPONSES
{
let i,v=[];
let fields=["intent","student","response","valued","language","knowledge","thinking","action","understanding"]; // Field names
for (i=0;i<f.length;++i) // For each responses
if (f[i].response && f[i].intent) v.push(f[i]); // If there, add it
let str=Papa.unparse(v,{ header:true, skipEmptyLines:true, columns:fields }); // Make CSV using lib
SaveTextAsFile("responses.csv",str); // Write file
}
///////////////////////////////////////////////////////////////////////////////////////////////
// WIT
/////////////////////////////////////////////////////////////////////////////////////////////////
async function TrainWit(d, newIntents) // TRAIN WIT
{
LoadingIcon(true); // Show loading icon
let tot=d.length; // Total to train
WitGetIntents((ins)=>{ // Get intents list
if (ins.length) {
WitDeleteIntents(ins,(r)=>{},()=>{ // Delete intents recursively
WitAddIntents(newIntents,()=>{},()=>{ // Add intents recursively
WitTrain(d, (r1,r2)=>{ // Start sending via recursion
trace(r1,r2); // Log
$("#lz-loadingIconText").html("<b>Added<br>"+r2+"%</b>"); // Show progress
if (!d.length) { // If last one
Sound("ding"); // Ding
LoadingIcon(false); // Hide loading icon
}
});
});
});
}
else{
WitAddIntents(newIntents,()=>{},()=>{ // Add intents recursively
WitTrain(d, (r1,r2)=>{ // Start sending via recursion
trace(r1,r2); // Log
$("#lz-loadingIconText").html("<b>"+(100-Math.floor(d.length*100/tot))+"%</b>"); // Show progress
if (!d.length) { // If last one
Sound("ding"); // Ding
LoadingIcon(false); // Hide loading icon
}
});
});
}
});
}
function WitGetUtterances(callback) // GET ARRAY OF UTTERANCES
{
const url="https://api.wit.ai/utterances?v=20210922&limit=10000"; // URL
const response=fetch(url, { // Send command to wit
headers: { Authorization:'Bearer '+witToken[modelName], 'Content-Type':'application/json'}
})
.then(res => res.json()).then(res =>{callback(res); }); // Send data back
}
async function WitGetIntents(callback) // GET ARRAY OF INTENTS
{
const url="https://api.wit.ai/intents?v=20210922&limit=10000"; // URL
const response=fetch(url, { // Send command to wit
headers: { Authorization:'Bearer '+witToken[modelName], 'Content-Type':'application/json'}
})
.then(res => res.json()).then(res =>{callback(res); }); // Send data back
}
function WitDeleteUtternances(utterances, callback) // DELETE UTTERANCES FROM SERVER
{
const url="https://api.wit.ai/utterances?v=20210922"; // URL
const response=fetch(url, { // Send command to wit
method:"DELETE",
headers: { Authorization:'Bearer '+witToken[modelName], 'Content-Type':'application/json'},
body: JSON.stringify(utterances)
})
.then(res => res.json()).then(res =>{callback(res); }); // Send data back
}
async function WitDeleteIntents(msgs, callback, done) // DELETE INTENT FROM SERVER
{
let m=msgs.shift(); // Remove from list and save first
if (!m) return; // Nothing to do
trace("Deleted: "+m.name); // Log
const url="https://api.wit.ai/intents/"+m.name+"?v=20210922"; // URL
const response=await fetch(url, { // Send remark to wit
method:"DELETE",
headers: { Authorization:'Bearer '+witToken[modelName], 'Content-Type':'application/json'},
});
let res=await response.json(); // Get response
$("#lz-loadingIconText").html("<b>"+m.name+"</b>");
if (msgs.length) setTimeout(()=>{ WitDeleteIntents(msgs, callback, done) },500); // Recurse, if not last
else done("Finished deleting intents");
}
async function WitTrain(msgs, callback, done) // SEND REMARK TO WIT TO TRAIN
{
// for (let i=480;i<600;i+=10) SaveTextAsFile("r"+i+".json",`{ "name": "r${i}", }`);
let res=null,inference={ text:"", intent:0, confidence:0 }; // Null inference
let m=msgs.shift(); // Remove from list and save first
if (!isNaN(m.intent)) m.intent="r"+m.intent; // Numbers need to be prefixed with a letter
const url="https://api.wit.ai/utterances?v=20210922"; // URL
let body=[{ text:m.remark.substring(0,255), intent:m.intent.toLowerCase(), entities:[], traits: [] }]; // Make body
const response=await fetch(url, { // Send remark to wit
method:"POST",
headers: { Authorization:'Bearer '+witToken[modelName], 'Content-Type':'application/json'},
body: JSON.stringify(body)
});
res=await response.json(); // Get response
callback(m,res); // Return responss
if (msgs.length) setTimeout(()=>{ WitTrain(msgs, callback, done) },500); // Recurse, if not last
}
async function WitAddIntents(msgs, callback, done) // SEND REMARK TO WIT TO TRAIN
{
let m=msgs.shift(); // Remove from list and save first
if (!m) return; // Nothing to do
if (!isNaN(m)) m="r"+m; // Numbers need to be prefixed with a letter
const url="https://api.wit.ai/intents?v=20210922"; // URL
let body={ name:m.toLowerCase()}; // Make body
const response=await fetch(url, { // Send remark to wit
method:"POST",
headers: { Authorization:'Bearer '+witToken[modelName], 'Content-Type':'application/json'},
body: JSON.stringify(body)
});
let res=await response.json(); // Get response
trace(res)
$("#lz-loadingIconText").html("<b>"+res.name+"</b>");
if (msgs.length) setTimeout(()=>{ WitAddIntents(msgs, callback, done) },500); // Recurse, if not last
else done("Intents trained");
}
///////////////////////////////////////////////////////////////////////////////////////////////
// DIALOGFLOW
/////////////////////////////////////////////////////////////////////////////////////////////////
function TrainDialog(d, uniqueIntents) // MAKE DIALOGFLOW INTENT FILE
{
let intent,str,i,s;
for (i=0;i<uniqueIntents.length;i++) SaveTextAsFile("r"+uniqueIntents[i]+".json",`{ "name":"r${uniqueIntents[i]}", "auto":true }`);
let v=groupBy(d,"intent"); // Group by intent
for (intent in v) { // For each intent
str="[\n";
for (i=0;i<v[intent].length;++i) { // For each one wanted
s=v[intent][i].remark.replace(/"/g,""); // No quotes
s=s.replace(/'/g,"\\u0027"); // Escape apos
str+=`{ "data": [{ "text": "${s}", "userDefined": false }], "isTemplate": false, "count": 1, "lang": "en", "updated": 0 },\n`;
}
str=str.slice(0,-2)+"\n]";
SaveTextAsFile("r"+intent+"_usersays_en.json",str); // Write intent file
}
function groupBy(arr, property) { // GROUP
return arr.reduce((acc, cur) => {
acc[cur[property]] = [...acc[cur[property]] || [], cur];
return acc;
}, {});
}
}
function TrainDialogCX(data, uniqueIntents) // MAKE DIALOGFLOW INTENT FILE
{
let intent,i,j,s,d=[];
let v=groupBy(data,"intent"); // Group by intent
let fields=["Intent Display Name","Language","Phrase"]; // Field names
for (intent in v) { // For each intent
for (i=0;i<v[intent].length;++i) { // For each one wanted
s=v[intent][i].remark.trim(); // No trim phrase
if (s) d.push({ "Intent Display Name":i ? "" : "r"+intent, Language:i ? "" : "en", Phrase:s}); // Add intent/lang on 1st, phrase
}
}
let str=Papa.unparse(d,{ header:true, skipEmptyLines:true, columns:fields }); // Make CSV using lib
SaveTextAsFile("dfcx-training.csv",str); // Write training file
function groupBy(arr, property) { // GROUP
return arr.reduce((acc, cur) => {
acc[cur[property]] = [...acc[cur[property]] || [], cur];
return acc;
}, {});
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
// OPENAI
/////////////////////////////////////////////////////////////////////////////////////////////////
function OpenAIPrompt(prompt, callback) // GET RESPONSE FROM AI
{
let body={ messages: [{ role: 'user', content: prompt }], model: "gpt-3.5-turbo", n:1 };
const url="https://api.openai.com/v1/chat/completions";
let token="sk-SPyelk-X-E2cNhrllzy-X-fRi8T3Bl-X-bkFJ55dW-X-pOjcNEm5D-X-bmKi6oQ".replace(/-X-/g,""); // Get token
fetch(url,{ method:"POST",
headers: { Authorization:'Bearer '+token, 'Content-Type':'application/json'},
body: JSON.stringify(body)
})
.then(res => res.json()).then(res =>{ trace(res);
callback(res.choices[0].message.content); })
}
async function Augment(msgs, callback, done) // SEND REMARK TO OPENAI TO AUGMENT
{
let i,m=msgs.shift(); // Remove from list and save first
let s="Give me 7 other ways to say the following sentence and limit to 10 words:\""+m.remark+"\". "; // Make prompt
s+="Then give me 3 other ways to say the the same sentence and limit to 5 words. ";
let body={ messages: [{ role: 'user', content:s }], model: "gpt-3.5-turbo", n:1}; // Payload
const url="https://api.openai.com/v1/chat/completions"; // Endpoint
let token="sk-SPyelk-X-E2cNhrllzy-X-fRi8T3Bl-X-bkFJ55dW-X-pOjcNEm5D-X-bmKi6oQ".replace(/-X-/g,""); // Get token
fetch(url,{ method:"POST",
headers: { Authorization:'Bearer '+token, 'Content-Type':'application/json'},
body: JSON.stringify(body)
})
.then(res => res.json()).then(res =>{
trace(res)
nData.push({ intent: m.intent, remark:m.remark.trim(), note:"---- ORIGINAL -----"}); // Add original remark
let v=res.choices[0].message.content.split("\n"); // Make into array
for (i=0;i<v.length;++i) if (v[i]) nData.push({ intent:m.intent, remark:v[i].substring(2).trim(), note:"augment"} ); // Add augments
trace(res)
callback(res); // Return respones
if (msgs.length) setTimeout(()=>{ Augment(msgs, callback, done) },1500); // Recurse, if not last after waiting
else done(res); // Call done
})
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// HELPERS
/////////////////////////////////////////////////////////////////////////////////////////////////
function trace(msg, p1, p2, p3, p4) // CONSOLE
{
if (p4 != undefined)
console.log(msg,p1,p2,p3,p4);
else if (p3 != undefined)
console.log(msg,p1,p2,p3);
else if (p2 != undefined)
console.log(msg,p1,p2);
else if (p1 != undefined)
console.log(msg,p1);
else
console.log(msg);
}
function Sound(sound, mute) // PLAY SOUND
{
var snd=new Audio(); // Init audio object
if (sound.match(/\.mp3/i)) snd=new Audio(sound) // If an MP3 file
else snd=new Audio("img/"+sound+".mp3"); // Use built in mp3
if (!mute) { // If not initing or muting
snd.volume=100/100; // Set volume
snd.play(); // Play it
}
}
function SaveTextAsFile(file, contents) // SAVE TEXT TO LOCAL FILE
{
if (file.charAt(0) == "*") { // If asking
GetTextBox("Type file name","", file.substr(1), (s)=>{ SaveTextAsFile(s, contents); }); // Ask for name
return; // Quit
}
var textFileAsBlob=new Blob([contents], {type:'text/plain'});
var downloadLink=document.createElement("a");
downloadLink.download=file;
downloadLink.innerHTML="Download File";
downloadLink.href=window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick=()=>{ downloadLink.remove(); };
downloadLink.style.display="none";
downloadLink.id="tdll";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function GetTextBox(title, content, def, callback) // GET TEXT LINE BOX
{
$("#confirmBoxDiv").remove(); // Remove
$("body").append("<div class='lz-confirm' id='confirmBoxDiv'></div>"); // Add box
var str="<img src='img/smlogo.png' width='64' style='vertical-align:-8px'/> ";
str+="<span style='font-size:14px; color:#666'><b>"+title+"</b></span><br><br>";
str+="<p>"+content+"<p>";
str+="<p><input class='lz-is' style='width:75%' type='text' id='gtBoxTt' value='"+def+"'></p>";
str+="<div id='dialogOK' class='lz-bs'>OK</div>";
str+="<div id='dialogCancel' class='lz-bs' style='margin-left:8px;background-color:#999'>Cancel</div></div>";
$("#confirmBoxDiv").html(str); // Add to div
$("#gtBoxTt").focus(); // Focus on button
$("#gtBoxTt").on("change", function() { callback($("#gtBoxTt").val()); $("#confirmBoxDiv").remove(); }); // ONE ENTER
$("#dialogOK").on("click", function() { callback($("#gtBoxTt").val()); $("#confirmBoxDiv").remove(); }); // ON OK
$("#dialogCancel").on("click", function() { $("#confirmBoxDiv").remove(); }); // ON CANCEL
}
function ConfirmBox(title, content, callback, callback2) // CONFIRMATION BOX
{
Sound("ding"); // Ding sound
$("#confirmBoxDiv").remove(); // Remove
$("body").append("<div class='lz-confirm' id='confirmBoxDiv'></div>"); // Add dialog
var str="<img src='img/smlogo.png' width='64'>"; // Logo
str+="<span style='font-size:16px;float:right;color:#b9220a;margin-top:6px'><b>"+title+"</b></span><br>"; // Title
str+="<p>"+content+"<p>";
str+="<div style='float:right'><div id='confirmOK' class='lz-bs'>OK</div>";
str+="<div id='confirmCancel' class='lz-bs' style='margin-left:8px;background-color:#999'>Cancel</div></div>";
$("#confirmBoxDiv").html(str);
$("#confirmOK").on("click", function() { // ON OK BUT
$("#confirmBoxDiv").remove(); // Remove
if (callback) callback(); // If callback defined, run it
});
$("#confirmCancel").on("click", function() { // ON CANCEL BUT
$("#confirmBoxDiv").remove(); // Remove
if (callback2) callback2(); // If callback defined, run it
Sound("delete"); // Delete sound
});
}
function TimecodeToSeconds(timecode) // CONVERT TIMECODE TO MILLISECONDS
{
if (!timecode) return 0;
let t=0;
let v=timecode.match(/(\d*):(\d*):(\d*)\.*(\d*)/); // Parse
// t+=v[1]*60*60*1000; // Get hours
t+=v[2]*60*1000; // Get mins
t+=v[3]*1000; // Get secs
if (v[4]) t+=v[4]/1000; // Ms
return t; // Return time in ms
}
function LoadingIcon(mode) // SHOW/HIDE LOADING ICON
{
if (!mode) { // If hiding
$("#lz-loadingIcon").remove(); // Remove it
return; // Quit
}
let str="<div id='lz-loadingIcon' style='position:absolute;top:calc(50% - 64px);left:calc(50% - 64px);z-index:5000;text-align:center'>";
str+="<img src='img/loading.gif' width='128'>"; // Img
str+="<div id='lz-loadingIconText' style='margin-top:-78px;color:#999'></div></div>"; // Progress
$("body").append(str); // Add icon to container
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// KEYS / VOCAB
/////////////////////////////////////////////////////////////////////////////////////////////////
let keySyns=[];
MakeActionKeys()
function MakeActionKeys()
{
let i,v;
v=(`strategy,strategies,policy,policies,procedure,procedures,approach,approaches,approaching,blueprint,program,stratagem,stratagems,
plan,plans,planning,guideline,guidance,scheme,schema,organize,organization,tenet,path,pathway,avenue,agenda,agendas,agendum,channel,channels,modus,operandi,maneuver,
process,prototype,archetype,model,theory,theories,structure,structures,arrange,arrangement,arranging,classify,classification,clue,incorporate,integrate,
sort,proposal,propose,codify,codification,layout,design,designs,coordinate,create,creating,created,establish,standardize,figured,skill,skills,
rule,rules,construct,constructs,constructed,constructing,invent,technique,progression,unfolding,architecture,catalog,catalogue,alphabetize,pattern,
method,manner,mechanism,rubric,routine,scenario,outline,synopsis,summary,summarize,rundown,run-down,review,recap,recapitulation,
analysis,keyword,keywords,key_word,sequence.chronological,timeline,concept,concepts,conceptualize,context,
contextualize,revise,revision,sum,sum-up,take-away,takeaway`).replace(/\t|\n|\r/g,"").split(",");
for (i=0;i<v.length;++i) keySyns[v[i]]="key_500";
v=(`explain,explaining,explains,clarify,simplify,formulate,solve,determine,reason,reasoning,enlighten,decode,descrypt,unscramble,portray,comment,assert,disclose,depict,identify,find,pinpoint,
expound,exemplify,represent,annotate,annotating,delineate,define,designate,illustrate,reveal,tell,elucidate,paraphrase,unravel,untangle,describe,mean,
symbolize,exhibit,embody,epitomize,utter,communicate,declare,divulge,impart,notify,specify,expose,proclaim`).replace(/\t|\n|\r/g,"").split(",");
for (i=0;i<v.length;++i) keySyns[v[i]]="key_500";
v=(`opine,believe,posit,presume,feel,imagine,envisage,envision,visualize,perceive,anticipate,foresee,realize,suppose,pretend,hypothesis,
hypothesize,speculate,estimate,presuppose,judge,guess,divine,stab,surmise, rekon,decipher,deduce,infer,postulate,venture,conjecture,predict,
guesstimate,ascertain`).replace(/\t|\n|\r/g,"").split(",");
for (i=0;i<v.length;++i) keySyns[v[i]]="key_500";
v=(`understand,glean,know,get,comprehend,comprehension,learn,fathom,deem,grasp,master,point,recognize,distinguish,information,inform`).replace(/\t|\n|\r/g,"").split(",");
for (i=0;i<v.length;++i) keySyns[v[i]]="key_500";
v=(`prior,previous,previously,back`).replace(/\t|\n|\r/g,"").split(",");
for (i=0;i<v.length;++i) keySyns[v[i]]="key_500";
v=(`compare,correlate,contrast,diverge,vary,equal,than,less,fewer,reduced,greater,increrase,increased,higher,added,larger,more,improve,improved,enhance,enhanced,
raise,raised,better,worse,changed,modify,modified,next,last,later,before,previous,previously,since,former,afterward,afterwards,subsequently,since,after,shift,
differ,differed,difference`).replace(/\t|\n|\r/g,"").split(",");
for (i=0;i<v.length;++i) keySyns[v[i]]="key_500";
v=(`reflect,contemplate,think,consider,interpret,decide,decision,characterize,argue,claim,advocate,suggest,remember,remind,recollect,invoke,
theorize,suspect,scrutinize,conclude,conclusion,concede,ponder`).replace(/\t|\n|\r/g,"").split(",");
for (i=0;i<v.length;++i) keySyns[v[i]]="key_500";
}
</script>
</body>
</html>