-
Notifications
You must be signed in to change notification settings - Fork 5
/
naptha-demo.js
5576 lines (4526 loc) · 156 KB
/
naptha-demo.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
// I guess this happens to be the first file which gets included
// so I might as well use this to write a message here for whoever
// ends up reading this
// you're probably gonna be seeing it as one file, but rest assured
// (or afraid), that this is actually a compiled file, and I don't
// generally scroll through four thousand lines of code in order to
// find the valid_img() function.
// that said, the organization is still something that leaves a lot
// to be desired.
var global_params = {};
function extend_global(obj){
for(var i in obj){
global_params[i] = obj[i]
}
}
var storage_cache = {
warn_ocrad: true
};
function put_setting(name, val){
storage_cache[name] = val;
save_settings()
}
function get_setting(name){ return storage_cache[name] }
function loaded_user_id(){
if(location.hostname == "projectnaptha.com"){
var input = document.getElementById("project_naptha_user_token");
if(input){
input.value = global_params.user_id;
}
var is_installed = document.getElementById("project_naptha_is_installed");
if(is_installed) is_installed.style.display = '';
var not_installed = document.getElementById("project_naptha_not_installed");
if(not_installed) not_installed.style.display = 'none';
var injection = document.getElementById("project_naptha_inject_status")
if(injection){
injection.style.display = 'none'
var injection_load = document.getElementById("project_naptha_loading_status")
if(injection_load) injection_load.style.display = '';
var xhr = new XMLHttpRequest();
xhr.open('get', global_params.apiroot + 'webstatus?user=' + encodeURIComponent(global_params.user_id), true)
xhr.send(null)
xhr.onload = function(){
if(injection_load) injection_load.style.display = 'none';
injection.innerHTML = xhr.responseText
injection.style.display = ''
}
}
}
setTimeout(function(){
// console.log(Date.now() - get_setting('account_refresh'))
if(!(Date.now() - get_setting('account_refresh') < 24 * 60 * 1000)){
// it's expired now, lets request again
get_account_status();
}
}, 1000 + Math.floor(Math.random() * 10000))
}
function get_account_status(){
var xhr = new XMLHttpRequest();
xhr.open('GET', global_params.apiroot + 'status?user=' + encodeURIComponent(global_params.user_id), true)
xhr.send(null)
put_setting('account_refresh', Date.now())
xhr.onload = function(){
var account = JSON.parse(xhr.responseText);
put_setting('account', account)
console.log("updated account state", account)
}
}
function uuid(){
for(var i = 0, s, b = ''; i < 42; i++)
if(/\w/i.test(s = String.fromCharCode(48 + Math.floor(75 * Math.random())))) b += s;
return b;
}
/**
* Display an image in the console.
* @param {string} url The url of the image.
* @param {int} scale Scale factor on the image
* @return {null}
* http://dunxrion.github.io
*/
console.image = function(url, log) {
var img = new Image();
function getBox(width, height) {
return {
string: "+",
style: "font-size: 1px; padding: " + Math.floor(height/2) + "px " + Math.floor(width/2) + "px; line-height: " + height + "px;"
}
}
img.onload = function() {
var dim = getBox(this.width, this.height);
// console.log(log, url)
console.log("%c" + dim.string, dim.style + "background: url(" + url + "); background-size: " + (this.width) + "px " + (this.height) + "px; color: transparent;");
};
img.src = url;
};
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
// MIT license
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
if(typeof window != "undefined"){
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
|| window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
}());
// We the People of the United States,
// in Order to form a more perfect Union,
// establish Justice,
// insure domestic Tranquility,
// provide for the common defence,
// promote the general Welfare,
// and secure the Blessings of Liberty to ourselves and our Posterity,
// do ordain and establish this Constitution for the United States of America.
// well, this is a preamble, but of a slightly different sort, I guess.
extend_global({
num_workers: 2,
is_extension: true,
queue_expires: 1000 * 2, // two seconds
user_id: null,
version: /*NAPTHA_VERSION_START*/"0.8.0"/*NAPTHA_VERSION_END*/,
apiroot: "https://sky-lighter.appspot.com/api/",
prelookup: "https://ssl.projectnaptha.com/lookup"
})
extend_global({
ocrad_worker: 'src/ocrad.js/worker.js',
swt_worker: 'src/swt/worker.js',
inpaint_worker: 'src/inpaint.js/worker.js',
mask_worker: 'src/mask/worker.js',
is_extension: false,
simple_ids: true,
demo_mode: true,
queue_expires: 1000 * 2, // two seconds
user_id: "demo",
has_tts: false,
apiroot: "https://sky-lighter.appspot.com/api/",
prelookup: "https://ssl.projectnaptha.com/lookup"
})
// really, none of this matters
function save_settings(){
// localStorage.settings = JSON.stringify(storage_cache)
}
// Project Naptha: browser extension enables selecting, copying, and translating text from any image
// Project Naptha: a browser extension that enables text selection on any image
// PR open-sources Copytext, a library for handling spreadsheets as Python objects
// test
// window.addEventListener('message', function(e){
// receive(e.data)
// })
// for(var i = 0; i < document.images.length; i++){
// var image = im(document.images[i]);
// var num_chunks = Math.max(1, Math.ceil((image.height - image.params.chunk_overlap) / (image.params.chunk_size - image.params.chunk_overlap)));
// var chunks = []
// for(var j = 0; j < num_chunks; j++){
// chunks.push(j)
// }
// broadcast({
// type: 'qchunk',
// id: image.id,
// chunks: chunks
// })
// }
var precomputed_images = {};
function broadcast(data){
if(data.type == 'qchunk'){
var whitelist = ["chelsea", "equis", "hilighting", "irate", "nobody", "protobowl", "russia", "thiel", "tyger", "rose", "skid"]
if(data.id in precomputed_images || whitelist.indexOf(data.id) == -1){
}else{
precomputed_images[data.id] = {}
var xhr = new XMLHttpRequest()
xhr.open('GET', 'dat/' + data.id + '/regions.json', true)
xhr.onload = function(){
// console.log(xhr.responseText)
var res = JSON.parse(xhr.responseText)
precomputed_images[data.id] = res;
receive({
type: 'region',
id: data.id,
regions: res.regions,
chunks: res.chunks
})
}
xhr.send(null)
}
}else if(data.type == 'qpaint'){
var res = precomputed_images[data.id];
var url = 'dat/' + data.id + '/' + data.reg_id.replace(/[\:\-]/g, '') + '.png';
var tmp = new Image()
tmp.onload = function(){
// console.log('blah')
var pls = res._plaster[data.reg_id];
receive({
id: data.id,
type: 'painted',
plaster: url,
reg_id: data.reg_id,
colors: pls.colors,
x: pls.x,
y: pls.y,
width: pls.width,
height: pls.height
})
}
tmp.src = url;
}else if(data.type == 'qocr' && data.engine == "ocrad"){
// welp not implementented
// must tesseract
}else{
console.log(data)
}
}
onload = function(){
setTimeout(function(){
initial_selection()
}, 100)
}
function initial_selection(){
var image = im(document.getElementById('tyger'));
function is_loaded(){
sel.img = image.el;
sel.stack = [
[{
region: image.regions[1],
line: image.regions[1].lines[2],
word: image.regions[1].lines[2].words[3],
letter: image.regions[1].lines[2].words[3].letters[0],
}, null, Date.now()],
[{
region: image.regions[3],
}],
[null, {
region: image.regions[4],
line: image.regions[4].lines[1],
word: image.regions[4].lines[1].words[2],
letter: image.regions[4].lines[1].words[2].letters.slice(-1)[0]
}, Date.now()]
]
update_selection()
}
function check_loaded(){
if(image.regions.length == 0){
broadcast({
type: 'qchunk',
id: image.id,
time: Date.now(),
chunks: []
})
setTimeout(check_loaded, 100)
}else{
console.log()
is_loaded()
}
}
check_loaded();
}
// function broadcast(data){
// var fr = document.getElementById('project_naptha_core_frame')
// if(fr && fr.contentWindow){
// fr.contentWindow.postMessage(data, location.protocol + '//' + location.host)
// }else{
// // oops this shit dont exist yet
// broadcast_queue.unshift(data)
// if(!fr){
// var fr = document.createElement('iframe')
// fr.src = 'core.html'
// fr.id = 'project_naptha_core_frame'
// fr.style.display = 'none'
// get_container().appendChild(fr)
// }
// }
// }
// <iframe src="core.html" id="project_naptha_core_frame" style="display: none"></iframe>
var session_params = {
// show_chunks: true,
// show_regions: true,
// show_lines: true,
// show_contours: true
}
var default_params = {
// the kernel size for the gaussian blur before canny
kernel_size: 3,
// low and high thresh are parameters for the canny edge detector
low_thresh: 124,
high_thresh: 204,
// maximum stroke width, this is the number of iterations
// the core stroke width transform loop will go through
// before giving up and saying that there is no stroke here
max_stroke: 35,
// the maximum ratio between adjacent strokes for the
// connected components algorithm to consider part of the
// same actual letter
stroke_ratio: 2,
// this is the pixel connectivity required for stuff to happen
min_connectivity: 4,
// the minimum number of pixels in a connected component to
// be considered a candidate for an actual letter
min_area: 30, //default: 38
// maximum stroke width variation allowed within a letter
std_ratio: 0.83,
// maximum aspect ratio to still be considered a letter
// for instance, a really long line wouldn't be considered
// a letter (obviously if this number is too low, it'll start
// excluding l's 1's and i's which would be bad)
aspect_ratio: 10, // default: 8
// maximum ratio between the median thicknesses of adjacent
// letters to be considered part of the same line
thickness_ratio: 3,
// maximum ratio between adjacent letter heights to be considered
// part of the same line
height_ratio: 2.5, // original: 1.7
// for some reason it's much more effective with non-integer scales
scale: 1.3,
// scale: 1.8,
// text_angle: Math.PI / 6
letter_occlude_thresh: 7, //default 3
// otsu parameter for word breakage
breakdown_ratio: 0.4,
// something something making lines
elongate_ratio: 1.9,
// maximum number of surrounding pixels to explore during the
// flood fill swt augmentation stage
max_substroke: 15,
// linespacing things for spacing lines, used in forming paragraphs/regions
min_linespacing: 0.1, // this is for overlap
max_linespacing: 1.7,
// otsu breakdown ratio for splitting a paragraph
col_breakdown: 0.3,
// the maximum fraction of the width of the larger of two adjacent lines
// by which an alignment may be offset in one column
max_misalign: 0.1,
// the first one is frac of the smaller area, the second is frac of bigger area
col_mergethresh: 0.3,
lettersize: 0.4, // maximum difference between median letter weights of adjacent lines
// letter weight is defined as the number of pixels per letter divided by the width
// which is because quite often entire words get stuck together as one letter
// and medians are used because it's a more robust statistic, this actually works
// remarkably well as a metric
// debugs!?!?
debug: false,
chunk_size: 250,
chunk_overlap: 90,
}
var session_id = uuid()
var image_counter = 0;
var images = {};
function get_id(img){
if(!img) return;
// if you're passing an id, return the id
if(typeof img == 'string') return img;
function clean(str){
// return str.replace(/^.+:\/\//g, '').replace(/[^a-z.\/_]/gi, '')
return str.replace(/[^a-z0-9.\/_\-]/gi, '')
}
if(!('__naptha_id' in img)){
var readable = clean(img.src.replace(/^.*\/(.*)$/g, '$1').split('.')[0]);
img.__naptha_id = (image_counter++) + '**' + readable + '**' + clean(img.src) + '**' + session_id;
if(global_params.simple_ids){
img.__naptha_id = readable
}
}
return img.__naptha_id
}
function im(img){
var id = get_id(img)
if(id in images) return images[id];
function shallow(obj){
var new_obj = {};
for(var i in obj){
new_obj[i] = obj[i]
}
return new_obj;
}
var params = shallow(default_params);
var src = img.src;
if(!src) return null;
if(src.indexOf("http://localhost/Dropbox/Projects/naptha/") == 0 || global_params.demo_mode){
src = "demo:" + img.src.replace(/^.*\/(.*?)\..*?$/g, '$1')
}
var image = images[id] = {
id: id,
el: img,
width: Math.round(img.naturalWidth * params.scale),
height: Math.round(img.naturalHeight * params.scale),
src: src,
real_src: img.src,
chunks: [],
regions: [],
engine: 'default',
params: params
}
collect_contexts()
return image;
}
function receive(data){
if(data.type == 'getparam'){
var image = im(data.id)
broadcast({
type: 'gotparam',
id: image.id,
src: image.src,
real_src: image.real_src,
params: image.params,
initial_chunk: data.initial_chunk
})
}else if(data.type == 'region'){
var image = im(data.id)
// var old_regions = {}
// image.regions.forEach(function(e){ old_regions[e.id] = e; })
// // if you had an old, finished column, keep the same
// // object rather than replacing it with the exact
// // same new one
// image.regions = data.regions.map(function(e){
// if(e.id in old_regions && old_regions[e.id].finished){
// return old_regions[e.id]
// }else{
// return e
// }
// })
image.regions = data.regions
image.chunks = data.chunks
image.stitch_debug = data.stitch_debug
// if(sel.img && image.id == get_id(sel.img)){
// render_selection(image.el, get_selection(sel, image), image.params)
// }
update_selection()
draw_annotations(image.el, image)
}else if(data.type == 'painted'){
// console.log(data.reg_id)
var image = im(data.id)
var mask = new Image()
mask.style.webkitTransform = 'translateZ(0)'
mask.src = data.plaster;
if(!image.plaster) image.plaster = {};
image.plaster[data.reg_id] = {
mask: mask,
colors: data.colors,
x: data.x,
y: data.y,
width: data.width,
height: data.height,
finished: Date.now()
}
update_overlay(image.el)
init_layer(mask, 'plaster')
var sx = (image.el.width / image.el.naturalWidth),
sy = (image.el.height / image.el.naturalHeight);
mask.style.left = (sx * data.x) + 'px'
mask.style.top = (sy * data.y) + 'px'
mask.style.width = (sx * data.width) + 'px'
mask.style.height = (sy * data.height) + 'px'
mask.style.transition = 'opacity 1s'
mask.style.opacity = '0'
image.overlay.appendChild(mask)
// update_translations(image)
image.regions.forEach(function(region){
if(region.id == data.reg_id){
translate_region(image, region)
}
})
draw_overlays(image)
update_selection();
}else if(data.type == 'recognized'){
var image = im(data.id)
if(!image.ocr) image.ocr = {};
// console.log(data)
var plain_text = data.text;
try {
plain_text = JSON.parse(plain_text).text
} catch (err) {
if(data.enc == 'tesseract'){
data.enc = 'error'
}
}
if(data.enc == 'error' || /^ERROR/i.test(plain_text)){
image.regions.forEach(function(region){
if(region.id == data.reg_id){
error_message(image, region, plain_text)
}
})
delete image.ocr[data.reg_id]
return
}
if(data.enc == 'tesseract'){
var json = JSON.parse(data.text);
var raw = parseTesseract(json)
// if(!((image.lookup || {}).chunks || []).some(function(chunk){ return chunk.engine == data.engine })){
;((image.lookup || {}).chunks || []).push({
engine: data.engine,
meta: json.meta,
key: json.key
})
// }
}else{
var raw = data.raw;
}
var ocr = image.ocr[data.reg_id];
if(ocr._engine != data.engine) return;
ocr.finished = Date.now()
delete ocr.processing;
// ocr.colors = data.colors;
ocr.raw = raw
ocr.text = data.text;
var broken = raw.some(function(block){
return isNaN(block.x) || isNaN(block.y) || isNaN(block.w) || isNaN(block.h)
});
if(broken){
var ocr = image.ocr[data.reg_id];
ocr.raw = null;
ocr.error = true;
ocr.text = 'ERROR: ' + data.text;
}
if(check_selection()) modify_clipboard();
update_translations(image)
draw_overlays(image)
update_selection();
}
}
function virtualize_region(image, region){
function transform(region){
if(image.translate && region.id in image.translate && image.translate[region.id].finished && image.virtual && region.id in image.virtual){
var lang = (image.translate[region.id] || {}).language
if(lang && lang != 'erase') return image.virtual[region.id];
}
return region
}
if(region.map)
return region.map(transform);
return transform(region)
}
// function urlencode(obj){
// return Object.keys(obj).map(function(e){
// return e + '=' + encodeURIComponent(obj[e])
// }).join('&')
// }
function get_lookup_chunks(image, region){
function frac_intersect(a, b){
var width = Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0),
height = Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0);
var max_area = Math.max((1 + a.x1 - a.x0) * (1 + a.y1 - a.y0),
(1 + b.x1 - b.x0) * (1 + b.y1 - b.y0))
return (width > 0 && height > 0) ? (width * height / max_area) : 0;
}
var filtered = ((image.lookup || {}).chunks || []).filter(function(chunk){
// if(region.x0)
// chunk.meta
// check to see if its the right region
var meta = chunk.meta;
var intersect = frac_intersect({
x0: meta.x0 / meta.sws,
y0: meta.y0 / meta.sws,
x1: meta.x1 / meta.sws,
y1: meta.y1 / meta.sws
}, {
x0: region.x0 / image.params.scale,
y0: region.y0 / image.params.scale,
x1: region.x1 / image.params.scale,
y1: region.y1 / image.params.scale
});
// console.log(intersect, meta, region)
return meta.v == 3 && meta.dir == region.direction && intersect > 0.9
})
return filtered
}
function get_ocr_engine(image, region, def){
var ocr = image.ocr[region.id]
if(ocr.engine == 'default'){
var filtered = get_lookup_chunks(image, region)
// TODO: sort by popularity?
return (filtered[0] && filtered[0].engine) || def || 'ocrad'
// console.log(filtered, 'filteahz')
// return "ocrad"
}else{
return ocr.engine;
}
}
function ocr_region(image, col){
if(!image.ocr) image.ocr = {};
if(col.finished != true) return;
if(!(col.id in image.ocr)){
image.ocr[col.id] = {
engine: "default"
}
}
// console.log(col, "QUEUEING SOMETHING")
// TODO: there's some code which exists that
// filters out the virtual ones and it's like
// not this
if(col.virtual){
for(var i = 0; i < image.regions.length; i++){
if(image.regions[i].id == col.id)
col = image.regions[i];
}
}
var ocr = image.ocr[col.id];
// var eng = ocr.engine == 'default' ? 'tess:eng' : ocr.engine;
var eng = get_ocr_engine(image, col)
if(ocr._engine != eng){
ocr._engine = eng
delete ocr.finished;
delete ocr.processing;
}
if(ocr.finished || ocr.processing) return;
delete ocr.waiting;
var matches = get_lookup_chunks(image, col).filter(function(chunk){
return chunk.engine == eng
})
if(ocr._engine != 'ocrad'){
// gotta have lookup loaded or else cant do something
if(!image.lookup){
do_lookup(image)
}else if(image.lookup.error){
error_message(image, col, "Can't access lookup server.")
}else if(!image.lookup.finished){
setTimeout(function(){
ocr_region(image, col)
}, 100);
return;
}
}
if(matches.length > 0){
// TODO: figure out the ideal candidate
var chunk = matches[0];
var xhr = new XMLHttpRequest()
xhr.open('GET', global_params.apiroot + 'chunk?key=' + encodeURIComponent(chunk.key), true)
xhr.send()
xhr.onload = function(){
// var result = JSON.parse(xhr.responseText);
// console.log(parseTesseract(result))
receive({
type: 'recognized',
enc: 'tesseract',
reg_id: col.id,
id: image.id,
engine: eng,
text: xhr.responseText
})
}
}else{
queue_broadcast({
src: image.src,
type: 'qocr',
apiroot: global_params.apiroot,
region: col,
reg_id: col.id,
id: image.id,
engine: ocr._engine,
swtscale: image.params.scale,
swtwidth: image.width
})
}
// image.ocr[col.id] = { processing: Date.now() }
image.ocr[col.id].processing = Date.now()
}
var broadcast_queue = [], is_casting = false;
function queue_broadcast(data){
broadcast_queue.push(data)
if(!is_casting) dequeue_broadcast();
}
function dequeue_broadcast(){
is_casting = false
if(broadcast_queue.length){
broadcast(broadcast_queue.shift())
setTimeout(dequeue_broadcast, 500)
is_casting = true;
}
}
// this function takes a y_orig, that is, a y coordinate in terms of the
// dimensions of the original image and then returns an ordered list of
// chunks which may be involved (containing text pertaining to said coordinate)
// it may return up to two chunks, in which case the ordering refers to which
// block the text is "most likely" to reside on (but it could actually end
// up on the other one too)
function to_chunks(sY, image){
var num_chunks = Math.max(1, Math.ceil((image.height - image.params.chunk_overlap) / (image.params.chunk_size - image.params.chunk_overlap)))
var base = Math.min(num_chunks - 1, Math.floor(sY / (image.params.chunk_size - image.params.chunk_overlap)))
var offset = sY - base * (image.params.chunk_size - image.params.chunk_overlap);
if(base <= 0){
return [0]
}else if(offset < image.params.chunk_overlap / 2){
return [base - 1, base]
}else if(offset < image.params.chunk_overlap){
return [base, base - 1]
}else{
return [base]
}
}
function valid_image(img){
// disable this for small links!
if(!(
img &&
// !img.naptha_disable &&
img.tagName == 'IMG' &&
img.complete &&
img.width > 150 && img.naturalWidth > 150 &&
Math.min(img.width, img.naturalWidth) * Math.min(img.height, img.naturalHeight) > 19000 &&
img.height > 60 && img.naturalHeight > 60 &&
img.naturalWidth < 2000 &&
img.src.length < 300 && // no really long urls
img.ownerDocument.designMode != 'on' &&
/^(https?|file):/i.test(img.src) // http, https or file protocols
)) return false;
var n = img, is_link = false;
do {
if(n.naptha_disable) return false;
if(n.getAttribute('ocr') == 'off') return false;
if(global_params.is_extension){
if(n.getAttribute('ocr') == 'custom') return false;
}
if(n.tagName == 'A'){
is_link = true;
}
} while ( (n = n.parentNode) && n.getAttribute);
// this is kind of an odd test, it happens post-facto
// that is, it happens after it's already been validated
// and it might invalidate a valid image
if(is_link && img.__naptha_id){
var image = im(img);
// hopefully this aint recursive
var regpad = 10;
var total_area = 0;
image.regions.forEach(function(region){
total_area += (regpad * 2 + region.width) * (regpad * 2 + region.height)
})
var frac_text = total_area / (image.width * image.height);
if(frac_text > 0.85){
// if it's a link and mostly text, then dont interfere with it
return false;
}
}
return true
// /zoom/.test(img.style.cursor) == false // the blown up image pics have un-preventable zoom effcts
}
function image_layout(el){
var dim = el.getBoundingClientRect(),
cmp = window.getComputedStyle(el);
// if(dim.width == 0 || dim.height == 0){
// delete images[get_id(el)]
// dispose_overlay(el)
// }
function sty(prop){ return parseInt(cmp.getPropertyValue(prop), 10) }
var X = dim.left + sty('padding-left') + sty('border-left-width'),
Y = dim.top + sty('padding-top') + sty('border-top-width');
return {
width: el.width, height: el.height,
X: X, Y: Y,
left: pageXOffset + X, top: pageYOffset + Y
}
}
function extract_region(ocr, start, end){
var col = (start && start.region) || end.region;
if(ocr.error){
return [ ocr.text ];
}
if(!start || !start.line) start = { line: col.lines[0], region: col };
if(!end || !end.line) end = { line: col.lines[col.lines.length - 1], region: col };
if(start.line.id == end.line.id){
return [extract_line(ocr, start, end)]
}else{
var within = false;
return col.lines.map(function(line){
if(line.id == start.line.id){
within = true;
return extract_line(ocr, start, null)
}else if(line.id == end.line.id){
within = false;
return extract_line(ocr, null, end)
}else if(within){
return extract_line(ocr, { line: line, region: col })
}
return null
}).filter(function(e){ return e })
}
}
function extract_line(ocr, start, end){
var line = (start && start.line) || end.line; // one of them needs to have it defined
var region = (start && start.region) || end.region;
var letters = [].concat.apply([], line.words.map(function(word){ return word.letters }))
if(region.virtual){
return line.words.map(function(word){
return word.letters.filter(function(letter){