-
Notifications
You must be signed in to change notification settings - Fork 21
/
camera_module.js
2096 lines (1676 loc) · 61 KB
/
camera_module.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
import './tesseract/tesseract.min.js';
//import { createWorker } from './camerajs/tesseract.min.js';
//Tesseract.createWorker
// https://cdn.jsdelivr.net/npm/[email protected]/tesseract-core-simd-lstm.wasm.js
// https://cdn.jsdelivr.net/npm/[email protected]/tesseract-core-simd.wasm.js
//let my_task = null;
// [
// '<|endoftext|><image>\n\n' +
// 'Question: Describe this image.\n\n' +
// 'Answer: A hand is holding a white book titled "The Little Book of Deep Learning" against a backdrop of a balcony with a railing and a view of a building and trees.<|endoftext|>'
// ]
/*
window.do_image_processing = async function (task){
if(typeof task == 'undefined' || task == null){
console.error("do_image_processing: invalid task: ", task);
return false
}
if(typeof task.sub_type != 'string'){
console.error("do_image_processing: no task.variant provided");
task['sub_type'] = 'ocr';
}
window.do_ocr(task);
});
*/
const video_el = document.getElementById("camera-video");
const video_canvas_el = document.getElementById("video-canvas");
const video_context = video_canvas_el.getContext('2d', { willReadFrequently: true });
const ocr_languages_lookup = {
"afr": "Afrikaans",
"amh": "Amharic",
"ara": "Arabic",
"asm": "Assamese",
"aze": "Azerbaijani",
"aze_cyrl": "Azerbaijani - Cyrillic",
"bel": "Belarusian",
"ben": "Bengali",
"bod": "Tibetan",
"bos": "Bosnian",
"bul": "Bulgarian",
"cat": "Catalan; Valencian",
"ceb": "Cebuano",
"ces": "Czech",
"chi_sim": "Chinese - Simplified",
"chi_tra": "Chinese - Traditional",
"chr": "Cherokee",
"cym": "Welsh",
"dan": "Danish",
"deu": "German",
"dzo": "Dzongkha",
"ell": "Greek, Modern (1453-)",
"eng": "English",
"enm": "English, Middle (1100-1500)",
"epo": "Esperanto",
"est": "Estonian",
"eus": "Basque",
"fas": "Persian",
"fin": "Finnish",
"fra": "French",
"frk": "German Fraktur",
"frm": "French, Middle (ca. 1400-1600)",
"gle": "Irish",
"glg": "Galician",
"grc": "Greek, Ancient (-1453)",
"guj": "Gujarati",
"hat": "Haitian; Haitian Creole",
"heb": "Hebrew",
"hin": "Hindi",
"hrv": "Croatian",
"hun": "Hungarian",
"iku": "Inuktitut",
"ind": "Indonesian",
"isl": "Icelandic",
"ita": "Italian",
"ita_old": "Italian - Old",
"jav": "Javanese",
"jpn": "Japanese",
"kan": "Kannada",
"kat": "Georgian",
"kat_old": "Georgian - Old",
"kaz": "Kazakh",
"khm": "Central Khmer",
"kir": "Kirghiz; Kyrgyz",
"kor": "Korean",
"kur": "Kurdish",
"lao": "Lao",
"lat": "Latin",
"lav": "Latvian",
"lit": "Lithuanian",
"mal": "Malayalam",
"mar": "Marathi",
"mkd": "Macedonian",
"mlt": "Maltese",
"msa": "Malay",
"mya": "Burmese",
"nep": "Nepali",
"nld": "Dutch; Flemish",
"nor": "Norwegian",
"ori": "Oriya",
"pan": "Panjabi; Punjabi",
"pol": "Polish",
"por": "Portuguese",
"pus": "Pushto; Pashto",
"ron": "Romanian; Moldavian; Moldovan",
"rus": "Russian",
"san": "Sanskrit",
"sin": "Sinhala; Sinhalese",
"slk": "Slovak",
"slv": "Slovenian",
"spa": "Spanish; Castilian",
"spa_old": "Spanish; Castilian - Old",
"sqi": "Albanian",
"srp": "Serbian",
"srp_latn": "Serbian - Latin",
"swa": "Swahili",
"swe": "Swedish",
"syr": "Syriac",
"tam": "Tamil",
"tel": "Telugu",
"tgk": "Tajik",
"tgl": "Tagalog",
"tha": "Thai",
"tir": "Tigrinya",
"tur": "Turkish",
"uig": "Uighur; Uyghur",
"ukr": "Ukrainian",
"urd": "Urdu",
"uzb": "Uzbek",
"uzb_cyrl": "Uzbek - Cyrillic",
"vie": "Vietnamese",
"yid": "Yiddish"
}
window.do_ocr = async function (task,language=null){
//console.log("in do_ocr. task,language: ", task,language);
if(typeof task == 'undefined' || task == null){
console.error("do_ocr: invalid task: ", task);
return false
}
if(typeof task.image_blob == 'undefined'){
console.error("do_ocr: aborting, task had no image: ", task);
return false
}
if(language == null){
if(typeof task.output_language == 'string'){
//console.log("do_ocr: using task's output_language: ", task.output_language);
}
else{
//console.log("do_ocr: using user's current language: ", window.settings.language);
language = window.settings.language;
}
if(language=='en'){language = 'eng'};
}
//console.log("do_ocr: language: ", language);
if(language.length == 2){
console.error("do_ocr: language code was still 2 characters long, may have to change to 3 character version: ", language);
}
//console.log("do_ocr: language: ", language);
const worker = await Tesseract.createWorker(language);
const ret = await worker.recognize(task.image_blob); //{progress: function(e){console.log(e)}}
//console.log("do_ocr: extracted text: ", ret, ret.data.text);
await worker.terminate();
//console.log("ocr done, calling handle_completed_task");
window.handle_completed_task(task,ret.data.text);
/*
Tesseract.recognize("https://yoursite/image.jpg", {
lang: 'ind',
tessedit_char_blacklist: 'e'
})
.progress(function(message){ console.log(message) })
.then(function(result) { console.log(result) });
*/
}
window.start_camera = function (simple=false){
//console.log("in start_camera. simple: ", simple);
document.body.classList.add('show-camera');
document.body.classList.remove('prepare-translate-document');
document.body.classList.remove('prepare-sumarize-document');
window.camera_on = true;
window.busy_starting_camera = true;
window.video_stream_meta = null;
window.camera_width = 1920;
window.camera_height = 1080;
window.camera_ratio = null;
let video_settings = {
width: { min: 640, ideal: 2160, max: 3840 },
height: { min: 480, ideal: 3840, max: 3840 },
facingMode: "environment",
}
if(simple){
//console.log("window.start_camera: going the simple route");
video_settings = true; // just give any video
}
return new Promise((resolve, reject) => {
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
window.busy_starting_camera = true;
navigator.mediaDevices.getUserMedia({
/*
// jscanify example. It needs as much resolution as possible. https://github.com/puffinsoft/jscanify/issues/19
const constraints = {
facingMode: 'environment',
advanced: [
{ width: { exact: 2560 } },
{ width: { exact: 1920 } },
{ width: { exact: 1280 } },
{ width: { exact: 1024 } },
{ width: { exact: 900 } },
{ width: { exact: 800 } },
{ width: { exact: 640 } },
{ width: { exact: 320 } },
],
};
*/
video: video_settings,
//video: true,
audio: false
}).then((stream) => {
//console.log("got camera stream");
video_el.srcObject = stream;
window.analyze_video_stream(stream);
//return true
//video.play();
resolve(true);
})
.catch((err) => {
console.error("Error starting camera: ", err);
if(simple == false && ('' + err).indexOf('verconstrained') != -1){
console.error("The error was an 'overconstrainedError'. Let's try again with simpler demands. ");
window.start_camera(true)
.then((value) => {
//console.log("using simpler camera contraints solved the problem with getting the video stream");
})
.catch((err) => {
console.error("using simpler camera contraints did not solve the problem with getting the video stream");
})
}
else{
window.camera_streaming = false;
window.busy_starting_camera = false;
flash_message(get_translation("Could_not_open_camera"),3000,'fail');
reject(false);
//return false
}
})
}
else{
flash_message(get_translation('Could_not_access_a_camera'),3000,'fail');
window.busy_starting_camera = false;
reject(false);
}
})
}
window.stop_camera = async function (){
//console.log("in stop_camera");
//window.continuous_ocr_enabled = false;
document.body.classList.remove('show-camera');
document.body.classList.remove('doing-ocr');
document.body.classList.remove('doing-image-to-text');
document.body.classList.remove('show-rewrite');
let stream = video_el.srcObject;
let tracks = stream.getTracks();
tracks.forEach(function(track) {
track.stop();
});
video_el.srcObject = null;
window.camera_streaming = false;
window.camera_on = false;
window.busy_starting_camera = false;
window.last_time_continuous_image_to_text_started = null;
//window.continuous_image_to_text_enabled = false;
};
/*
function onSave() {
context.drawImage(video, 0, 0, 640, 480);
canvas.toBlob((blob) => {
//const timestamp = Date.now().toString();
const a = document.createElement("a");
document.body.append(a);
//a.href = URL.createObjectURL(blob);
a.target = "_blank";
img = URL.createObjectURL(blob);
//a.click();
//console.log(img);
a.remove();
Tesseract.recognize(
'https://tesseract.projectnaptha.com/img/eng_bw.png',
'eng',
{ logger: m => console.log(m) }
).then(({ data: { text } }) => {
console.log(text);
})
});
}
*/
window.take_picture = async function (task={}){
//console.log("in take_picture. task: ", task);
if(typeof task == 'object' && task != null){
//console.log("writing video frame into canvas");
video_context.drawImage(video_el, 0, 0, window.camera_width, window.camera_height);
if(typeof task.origin == 'undefined'){
//console.log("take_picture: setting camera as task origin");
task['origin'] = 'camera';
}
if(typeof task.state == 'string'){
if(task.state == 'should_ocr'){
if(window.settings.docs.open == null){
let ocr_document_filename = get_translation('Text_from_photo') + ' ' + make_date_string() + '.txt'
create_new_document(get_translation("Photo_to_text_results") + ":\n\n", ocr_document_filename);
task['file'] = {'folder':folder,'filename':ocr_document_filename};
}
else{
task['file'] = window.settings.docs.open;
}
task.destination = 'document';
}
}
if(typeof task.image_blob == 'undefined' && typeof task.audio == 'undefined' && typeof task.recorded_audio == 'undefined'){
//console.log("take_picture: updated task before adding image data: ", JSON.stringify(task,null,4));
}
if(typeof task.prompt == 'undefined'){
task['prompt'] = null;
}
let mime_type = 'image/png';
if(typeof task.image_mime_type != 'string'){
task['image_mime_type'] = mime_type;
}
else{
mime_type = task.image_mime_type;
}
//console.log("take_picture: adding image data to task, with mime_type: ", mime_type);
//console.log("video_context: ", video_context);
//task['image_blob'] = video_canvas_el.toDataURL(mime_type);
video_canvas_el.toBlob((blob) => {
//console.log("video_canvas_el: toBlob result: ", blob);
task['image_blob'] = blob;
task['image_mime_type'] = 'image/jpeg';
if(typeof task.type != 'string'){
task['type'] = 'save_image';
}
if(typeof task.state != 'string'){
task['state'] = 'save_image';
}
//console.log("take_picture: adding task: ", task);
return window.add_task(task);//window.add_image_task(task);
}, 'image/jpeg', 0.95);
//canvas.toBlob(function(blob){...}, 'image/jpeg', 0.95);
}
else{
console.error("take_picture: invalid task provided: ", task);
}
return false;
}
//
// O C R
//
window.ocr_blobs = [];
window.perform_ocr_on_blobs = async function (blobs){
if(blobs == null){
blobs = window.ocr_blobs;
}
console.error("perform_ocr_on_blobs: BLOBS,window.ocr_scans: ", blobs, window.ocr_scans);
let merge_result = null;
document.body.classList.add('doing-ocr-scan');
live_ocr_scans_container_el.innerHTML = '';
try{
for(let b = 0; b < blobs.length; b++){
const blob = blobs[b];
let ocr_language = 'eng';
if(window.settings.language == 'nl'){
ocr_language = 'nld';
}
const worker = await Tesseract.createWorker();
const ret = await worker.recognize(blob); //{progress: function(e){console.log(e)}}
//console.log("continuous_ocr: extracted text: ", ret, ret.data.text);
if(typeof ret.data.text != 'string'){
console.error("OCR worker did not return a string. ret.data.text: ", ret.data.text);
continue
}
window.ocr_scans.push(ret.data.text);
camera_ocr_scan_progress_el.value = b / window.settings.ocr_scan_intensity;
let new_scan_result_el = document.createElement('textarea');
new_scan_result_el.classList.add('camera-ocr-snippet');
new_scan_result_el.value = ret.data.text
live_ocr_scans_container_el.appendChild(new_scan_result_el);
/*
if(window.doing_ocr_scan){ // this counts down from 7 to 0
window.ocr_scans.push(ret.data.text);
doing_ocr_scan_counter_el.textContent = window.doing_ocr_scan;
window.merge_ocr_scans(window.ocr_scans);
camera_container_el.classList.add('show-flasher');
setTimeout(() => {
camera_container_el.classList.remove('show-flasher');
},10)
}
else{
if(window.settings.settings_complexity != 'normal'){
live_ocr_output_el.value = ret.data.text;
}
// TODO: remove
//live_ocr_output_el.value = ret.data.text;
window.continuous_ocr_scans.push(ret.data.text);
if(window.continuous_ocr_scans.length == window.settings.continuous_ocr_scan_intensity){
window.merge_ocr_scans(window.continuous_ocr_scans);
//doing_ocr_scan_counter_el.textContent = window.continuous_ocr_scans.length - window.settings.continuous_ocr_scan_intensity;
window.continuous_ocr_scans = [];
}
//doing_ocr_scan_counter_el.textContent = window.doing_ocr_scan;
camera_ocr_scan_progress_el.value = window.continuous_ocr_scans.length / window.settings.continuous_ocr_scan_intensity;
if(window.ocr_scans.length){
//console.log("should attempt to merge the OCR scans now: ", window.ocr_scans);
window.merge_ocr_scans(window.ocr_scans);
document.body.classList.remove('doing-ocr-scan');
camera_container_el.classList.add('ocr-scan-complete');
}
doing_ocr_scan_counter_el.textContent = '';
}
*/
await worker.terminate();
if(b == 0){
live_ocr_output_el.value = ret.data.text;
}
else{
merge_result = window.merge_ocr_scans(window.ocr_scans);
}
window.textAreaAdjust(live_ocr_output_el);
}
//console.log("perform_ocr_on_blobs: merge_result: ", merge_result);
// Find out which scan most accurately resembled the merged result
if(typeof merge_result == 'string' && merge_result.length > 5){
let highest_similarity_score = 0;
let best_scan = -1;
if(typeof merge_result == 'string' && merge_result.length){
for(let x = 0; x < window.ocr_scans.length; x++){
const similarity_score = similarity(window.ocr_scans[x],merge_result);
//console.log("OCR similarity_score: ", similarity_score);
if(similarity_score > highest_similarity_score){
highest_similarity_score = similarity_score;
best_scan = x;
}
}
}
//console.log("perform_ocr_on_blobs: of the scans, when OCR-ed this picture best matched the resulting merged text: ", best_scan);
if(typeof best_scan == 'number' && best_scan != 1){
let save_ocr_image_task = {
'prompt':null,
'type':'save_image',
'state':'save_image',
'image_mime_type':'image/jpeg',
'image_blob':blobs[best_scan]
}
//console.log("perform_ocr_on_blobs: adding save_image task: ", task);
window.add_task(save_ocr_image_task);//window.add_image_task(task);
}
/*
if(document.body.classList.contains('show-rewrite')){
}
*/
rewrite_dialog_selected_text_el.textContent = merge_result;
}
// Optionally, translate the output
if(typeof merge_result == 'string' && translation_details_el.open){
if(merge_result.length > 10){
document.body.classList.add('doing-translation');
let ocr_translation_task = {
'prompt':null,
'text':merge_result,
'origin':'ocr',
'assistant':'translator',
'type':'translation',
'state':'should_translation',
'desired_results':1,
'results':[],
'output_language': window.settings.output_language,
'destination':'ocr', //window.active_destination,
'file':window.settings.docs.open
};
if(window.settings.auto_detect_input_language == false){
ocr_translation_task['input_language'] = window.settings.input_language;
ocr_translation_task['translation_details'] = get_translation_model_details_from_languages(window.settings.input_language,window.settings.output_language);
}
//console.log("ocr_translation_task: ", ocr_translation_task);
window.add_and_do_translation(ocr_translation_task, window.settings.auto_detect_input_language )
.then((translation_result) => {
//console.log("ocr translation result: ", translation_result);
})
.catch((err) => {
console.error("caught error from add_and_do_translation: ", err);
})
}
else{
console.warn("merged text was too short too translate. merge_result: ", merge_result);
}
}
}
catch(err){
console.error("caught error doing/merging OCR scans");
}
document.body.classList.remove('doing-ocr-scan');
}
// The main OCR scan function. Not just for running continuously
// async function do_continuous_ocr(){
window.do_continuous_ocr = async function (){
//console.log("in do_continuous_ocr. window.doing_ocr_scan,window.continuous_ocr_enabled: ", window.doing_ocr_scan, window.continuous_ocr_enabled);
window.only_allow_voice_commands = true;
try{
if(window.opencv_jscanify){
//console.log("do_continuous_ocr: opencv_jscanify available: ", window.opencv_jscanify);
//window.detect_page_in_video();
//camera_overlay_context.scale(1,1);
//window.should_do_camera_ocr_scan = window.settings.ocr_scan_intensity;
//window.doing_ocr_scan--;
}
else{
video_context.drawImage(video_el, 0, 0, window.camera_width, window.camera_height);
video_canvas_el.toBlob( async (blob) => {
//console.log("continuous_ocr: video_canvas_el: toBlob result: ", blob);
window.ocr_blobs.push(blob);
//console.log("continuous_ocr: ret.data.text: ", ret.data.text);
if(window.doing_ocr_scan){
window.doing_ocr_scan--;
setTimeout(() => {
window.do_continuous_ocr();
},100);
}
else{
setTimeout(() => {
//console.log("do_continuous_ocr: 500ms have passed. window.settings.continuous_ocr_scan,window.continuous_ocr_enabled: ", window.settings.continuous_ocr_scan, window.continuous_ocr_enabled)
if(window.settings.continuous_ocr_scan && window.continuous_ocr_enabled){
//window.do_continuous_ocr();
}
},200);
}
window.post_ocr_blob_addition();
}, 'image/jpeg', 0.95);
}
if(window.last_time_continuous_image_to_text_started == null){
window.last_time_continuous_image_to_text_started = Date.now();
}
}
catch(err){
console.error("do_continuous_ocr: caught error: ", err);
if(window.settings.continuous_ocr_scan && window.continuous_ocr_enabled){
setTimeout(() => {
//console.log("do_continuous_ocr: 2 seconds ago an error occured. Trying to call do_continuous_ocr again.");
do_continuous_ocr();
},2000);
}
}
}
function removeDuplicates(arr) {
let unique = [];
arr.forEach(element => {
if (!unique.includes(element)) {
unique.push(element);
}
});
return unique;
}
window.merge_ocr_scans = function(scans=null){
if(typeof scans == 'undefined' || scans == null || !Array.isArray(scans)){
console.error("merge_ocr_scans: no valid scans array provided");
return false
}
//console.log("in merge_ocr_scans. scans: ", scans.length, scans);
let scan_data = [];
let line_data = {};
let all_lines = [];
let word_data = {};
let scan_scores = [];
let line_scores = {}
let certain_words = [];
let certain_chunks = [];
let newliner = '[!NEWLINE_WAS_HERE!]';
let chunk_lines = [];
let output_text = null;
const findOverlap = (a, b, retry = true) => {
// If one of the two strings is empty, return the other one. This ensures
// that empty strings in the collection do not influence the result.
if (!a || !b) return a || b;
// Find the position in a, of the first character of b
let i = a.indexOf(b[0]);
while (i > -1) { // As long as there is such an occurrence...
// Calculate what the size of the overlapping part would be:
// This is either the size of the remaining part of a, or
// the size of b, when it is a real substring of a:
let size = Math.min(a.length - i, b.length);
// See if we have an overlap at this position:
if (a.slice(i).slice(0, size) === b.slice(0, size)) {
// Yes! Include the "overflowing" part of b:
return a + b.slice(size);
}
// No match. Try a next position:
i = a.indexOf(b[0], i+1);
}
// The start of b does not overlap with the end of a, so try
// the opposite:
if (retry) return findOverlap(b, a, false); // reversed args
// If this was already the reversed case, then just concatenate
return b+a; //''; //null; //b+a; // Reverse again
}
/*
* findLongestOverlap:
* find information about the two strings that have the longest overlap.
* Input:
* collection: an array of strings
* Returns:
* An object with 4 properties:
* merged: the merged string, not repeating the overlapping part
* i, j: the two indexes in the collection of the contributing strings
* overlapSize: number of characters that are part of the overlap
* Example:
* findLongestOverlap(["abcdef", "defghi", "cdefg"]) returns:
* { merged: "abcdefg", i: 0, j: 2, overlapSize: 4 }
*/
const findLongestOverlap = (collection) => {
// Initialise the "best" overlap we have so far (we don't have any yet)
let longest = { overlapSize: -1 };
// Iterate all pairs from the collection:
for (let j = 1; j < collection.length; j++) {
let b = collection[j];
for (let i = 0; i < j; i++) {
let a = collection[i];
//let threshold = 0;
/*
if(a.indexOf(newliner) == -1 && b.indexOf(newliner) == -1){
continue
}
let merged = null;
if(a.endsWith(newliner) && b.startsWith(newliner)){
}
else{
merged = findOverlap(b,a, false);
}
else if(!a.startsWith(newliner) && !b.endsWith(newliner)){
merged = findOverlap(a,b, false);
}
*/
/*
if(a.endsWith(newliner) && b.startsWith(newliner)){
merged = findOverlap(a,b,false);
threshold = newliner.length + 2; // avoid glueing together string by just the newline
}
else if(a.startsWith(newliner) && b.endsWith(newliner)){
merged = findOverlap(a,b);
threshold = newliner.length + 2; // avoid glueing together string by just the newline
}
else{
merged = findOverlap(a,b);
}
*/
const merged = findOverlap(a,b);
/*
if(merged == null){
merged = findOverlap(b,a,false);
}
*/
//if(threshold > 1){
//console.log("merged: ", merged);
//console.log("threshold: ", threshold);
//}
//console.log("findOverlap found: ", merged);
// Derive the size of the overlap from the merged string:
if(typeof merged == 'string'){ // && merged.indexOf(newliner) != -1
const overlapSize = a.length + b.length - merged.length;
//console.log("overlapSize vs threshold: ", overlapSize, threshold);
// Did we improve?
if (overlapSize > longest.overlapSize) { // && overlapSize > threshold
// Yes! So keep track of all info we need:
longest = { merged, i, j, overlapSize };
//console.log("findLongestOverlap: longest: ", longest);
}
}
}
}
return longest;
}
/*
* reduceToOne:
* merge a series of strings, merging via the greatest overlaps first.
* Input:
* any number of arguments: all strings
* Returns:
* A single string, which represents the merge
*/
var reduceToOne = (...newline_chunks) => { // Grab all arguments as an array
// Repeat until the collection is reduced to one element
//const original_collection = collection;
let new_certain_chunks = [];
//let final_certain_chunks = [];
//let newline_chunks = [];
//let add_back_later = [];
for (let i = newline_chunks.length - 1; i >=0; --i ) {
//console.log("testing for merge: ", i, newline_chunks[i]);
// Get information from best possible pair-merge:
const { merged, i, j, overlapSize } = findLongestOverlap(newline_chunks);
console.log("merged, i, j, overlapSize: ", merged, i, j, overlapSize);
if(typeof merged == 'string'){
// Remove the original two strings having the longest overlap
if(typeof overlapSize == 'number' && overlapSize > 1){
new_certain_chunks.push(merged);
}
else{
//new_certain_chunks.push(newline_chunks[i]);
}
//console.log("merged: ", merged);
if(merged.length){
newline_chunks.splice(j, 1);
newline_chunks.splice(i, 1);
newline_chunks.push(merged);
}
}
else{
console.error("merged was not a string: ", typeof merged);
}
//console.log("new_certain_chunks: ", new_certain_chunks);
}
//console.error("new_certain_chunks: ", JSON.stringify(new_certain_chunks,null,4 ));
for(let c = new_certain_chunks.length - 1; c >= 0; --c){
for(let cc = new_certain_chunks.length - 1; cc >= 0; --cc){
if(new_certain_chunks[c].length > new_certain_chunks[cc].length && new_certain_chunks[c].indexOf(new_certain_chunks[cc]) != -1){
new_certain_chunks.splice(cc,1);
c--;
}
}
}
if(new_certain_chunks.length > 1){
console.log("going to remove duplicated from new_certain_chunks: ", new_certain_chunks.length, JSON.stringify(new_certain_chunks,null,4));
new_certain_chunks = removeDuplicates(new_certain_chunks);
//console.warn("FINAL new_certain_chunks: ", new_certain_chunks);
}
return new_certain_chunks;
/*
final_certain_chunks = final_certain_chunks.concat(new_certain_chunks);
new_certain_chunks = new_certain_chunks.concat(add_back_later);
console.log("new_certain_chunks with the other parts added back in: ", new_certain_chunks.length, JSON.stringify(new_certain_chunks,null,4));
//for (let i = new_certain_chunks.length; --i; ) {
for (let ii = new_certain_chunks.length -1; ii >= 0; --ii ) {
// Get information from best possible pair-merge:
const { merged, ia, j, overlapSize } = findLongestOverlap(new_certain_chunks);
// Remove the original two strings having the longest overlap
if(typeof merged == 'string'){
if(typeof overlapSize == 'number' && overlapSize > 1){
console.log("adding merger to final_certain_chunks: ", merged);
final_certain_chunks.push(merged);
}
//console.log("merged: ", merged);
if(merged.length){
new_certain_chunks.splice(j, 1);
new_certain_chunks.splice(ia, 1);
new_certain_chunks.push(merged);
}
}
else{
console.error("final_certain_chunks: merged was not a string, it was: ", typeof merged);
}
console.log("final_certain_chunks: ", final_certain_chunks);
}
for(let c = final_certain_chunks.length - 1; c >= 0; --c){
for(let cc = final_certain_chunks.length - 1; cc >= 0; --cc){
if(final_certain_chunks[c].length > final_certain_chunks[cc].length && final_certain_chunks[c].indexOf(final_certain_chunks[cc]) != -1){
final_certain_chunks.splice(cc,1);
c--;
}
}
}
if(final_certain_chunks.length > 1){
console.log("going to remove duplicated from final_certain_chunks: ", final_certain_chunks.length, JSON.stringify(final_certain_chunks,null,4));
final_certain_chunks = removeDuplicates(final_certain_chunks);
//console.warn("FINAL new_certain_chunks: ", new_certain_chunks);
}
// Return the single string that remains
return final_certain_chunks; // [0];
*/
}
let longest_lines_count = 0;
let shortest_lines_count = 10000;
for(let s = 0; s < scans.length; s++){
scan_scores.push(0);
// Do some minor cleanup of the data
scans[s] = scans[s].replaceAll(' | ',' ');
scans[s] = scans[s].replaceAll(' í ',' ');
scans[s] = scans[s].replaceAll(' : ',' ');
scans[s] = scans[s].replaceAll(' ] ',' ');
scans[s] = scans[s].replaceAll(' ] ',' ');
scans[s] = scans[s].replaceAll(' |\n',' \n');
scans[s] = scans[s].replaceAll(' í\n',' \n');