-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
272 lines (256 loc) · 13.9 KB
/
Copy pathapp.js
File metadata and controls
272 lines (256 loc) · 13.9 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
(function(){
"use strict";
var $=function(id){return document.getElementById(id);};
var stage=$("stage"), ctx=stage.getContext("2d",{willReadFrequently:true});
var holder=$("holder"), cropEl=$("crop");
var img=null, scale=1, sel=null;
var rawText="", cleanText="", activeTab="clean";
function clamp(v,a,b){return Math.max(a,Math.min(b,v));}
function cap(s){return s.charAt(0).toUpperCase()+s.slice(1);}
// theme
var savedTheme=null; try{savedTheme=localStorage.getItem("snip-theme");}catch(e){}
if(savedTheme) document.documentElement.setAttribute("data-theme",savedTheme);
syncThemeIcon();
$("themeBtn").onclick=function(){
var t=document.documentElement.getAttribute("data-theme")==="dark"?"light":"dark";
document.documentElement.setAttribute("data-theme",t);
try{localStorage.setItem("snip-theme",t);}catch(e){}
syncThemeIcon();
};
function syncThemeIcon(){ $("themeBtn").textContent=document.documentElement.getAttribute("data-theme")==="dark"?"☀️":"🌙"; }
// toasts
function toast(msg,type,ms){
type=type||"ok"; ms=ms||2200;
var t=document.createElement("div"); t.className="toast "+type;
var ic=type==="err"?"⚠️":type==="warn"?"⚡":"✅";
t.innerHTML=ic+" <span></span>"; t.querySelector("span").textContent=msg;
$("toasts").appendChild(t);
setTimeout(function(){t.style.opacity="0";t.style.transform="translateY(8px)";setTimeout(function(){t.remove();},250);},ms);
}
// feature detection
var hasScreen=!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia);
var hasCam=!!(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia)||('capture' in document.createElement('input'));
if(!hasScreen) $("btnScreen").disabled=true;
if(!hasCam) $("btnCamera").disabled=true;
$("featBadge").textContent=(hasScreen?"screen ✓":"screen n/a")+" · "+(hasCam?"camera ✓":"camera n/a");
$("capNote").textContent=hasScreen?"On phones screen-capture may be off — use Camera, Upload or Paste."
:"Screen-capture isn't available here — Camera, Upload and Paste are ready.";
// load image
function loadImage(src){
var url=(typeof src==="string")?src:URL.createObjectURL(src);
var im=new Image();
im.onload=function(){
img=im;
var maxW=Math.min(window.innerWidth-80,1000);
scale=im.width>maxW?maxW/im.width:1;
stage.width=im.width; stage.height=im.height;
stage.style.width=(im.width*scale)+"px"; stage.style.height=(im.height*scale)+"px";
ctx.drawImage(im,0,0);
sel=null; cropEl.style.display="none";
$("imgChip").textContent=im.width+" × "+im.height+" px";
$("cropCard").style.display="block";
$("status").textContent="Drag on the image to select a region, or extract the whole image.";
if(typeof src!=="string") URL.revokeObjectURL(url);
$("cropCard").scrollIntoView({behavior:"smooth",block:"start"});
};
im.onerror=function(){ toast("Couldn't load that image.","err"); };
im.src=url;
}
// cropper (pointer events: mouse + touch + pen)
var mode=null, startX=0, startY=0, orig=null;
function dispPt(e){
var r=stage.getBoundingClientRect();
return { x:clamp(e.clientX-r.left,0,stage.clientWidth), y:clamp(e.clientY-r.top,0,stage.clientHeight) };
}
holder.addEventListener("pointerdown",function(e){
if(!img) return;
var onHandle=e.target.classList.contains("h");
var onCrop=e.target===cropEl||e.target.classList.contains("dims");
holder.setPointerCapture(e.pointerId);
var p=dispPt(e);
if(onHandle){ var dir=null,cl=e.target.classList; ["nw","ne","sw","se","n","s","e","w"].forEach(function(c){if(cl.contains(c))dir=c;});
mode="resize:"+dir; orig={x:sel.x,y:sel.y,w:sel.w,h:sel.h}; startX=p.x; startY=p.y; }
else if(onCrop){ mode="move"; orig={x:sel.x,y:sel.y,w:sel.w,h:sel.h}; startX=p.x; startY=p.y; }
else { mode="new"; startX=p.x; startY=p.y; sel={x:p.x,y:p.y,w:0,h:0}; drawCrop(); }
e.preventDefault();
});
holder.addEventListener("pointermove",function(e){
if(!mode) return;
var p=dispPt(e), dx=p.x-startX, dy=p.y-startY, W=stage.clientWidth, H=stage.clientHeight;
if(mode==="new"){
sel={x:Math.min(startX,p.x),y:Math.min(startY,p.y),w:Math.abs(dx),h:Math.abs(dy)};
} else if(mode==="move"){
sel.x=clamp(orig.x+dx,0,W-orig.w); sel.y=clamp(orig.y+dy,0,H-orig.h);
} else if(mode.indexOf("resize")===0){
var d=mode.split(":")[1], x=orig.x, y=orig.y, w=orig.w, h=orig.h;
if(d.indexOf("e")>-1) w=clamp(orig.w+dx,10,W-orig.x);
if(d.indexOf("s")>-1) h=clamp(orig.h+dy,10,H-orig.y);
if(d.indexOf("w")>-1){ var nx=clamp(orig.x+dx,0,orig.x+orig.w-10); w=orig.w+(orig.x-nx); x=nx; }
if(d.indexOf("n")>-1){ var ny=clamp(orig.y+dy,0,orig.y+orig.h-10); h=orig.h+(orig.y-ny); y=ny; }
sel={x:x,y:y,w:w,h:h};
}
drawCrop(); e.preventDefault();
});
holder.addEventListener("pointerup",function(){
if(mode==="new" && sel && (sel.w<8||sel.h<8)){ sel=null; cropEl.style.display="none"; }
mode=null;
});
function drawCrop(){
if(!sel){cropEl.style.display="none";return;}
cropEl.style.display="block";
cropEl.style.left=sel.x+"px"; cropEl.style.top=sel.y+"px";
cropEl.style.width=sel.w+"px"; cropEl.style.height=sel.h+"px";
$("dims").textContent=Math.round(sel.w/scale)+" × "+Math.round(sel.h/scale)+" px";
}
// crop -> canvas (+ optional preprocess)
function regionCanvas(){
var r=sel?{x:sel.x/scale,y:sel.y/scale,w:sel.w/scale,h:sel.h/scale}:{x:0,y:0,w:img.width,h:img.height};
var area=r.w*r.h, up=area<(320*120)?2.5:area<(640*240)?1.6:1;
var c=document.createElement("canvas");
c.width=Math.max(1,Math.round(r.w*up)); c.height=Math.max(1,Math.round(r.h*up));
var cx=c.getContext("2d",{willReadFrequently:true});
cx.imageSmoothingEnabled=true; cx.imageSmoothingQuality="high";
cx.drawImage(img,r.x,r.y,r.w,r.h,0,0,c.width,c.height);
if($("enhance").checked) preprocess(c);
return c;
}
// grayscale -> auto-invert (dark bg) -> Otsu binarize => black text on white
function preprocess(c){
var cx=c.getContext("2d",{willReadFrequently:true});
var im=cx.getImageData(0,0,c.width,c.height), d=im.data, n=c.width*c.height;
var gray=new Float32Array(n), sum=0, i, p;
for(i=0,p=0;i<d.length;i+=4,p++){ var g=0.299*d[i]+0.587*d[i+1]+0.114*d[i+2]; gray[p]=g; sum+=g; }
var invert=(sum/n)<128;
var hist=new Array(256); for(i=0;i<256;i++) hist[i]=0;
for(p=0;p<n;p++) hist[Math.min(255,Math.round(gray[p]))]++;
var total=n,sumAll=0,t; for(t=0;t<256;t++) sumAll+=t*hist[t];
var sumB=0,wB=0,maxV=0,thr=127;
for(t=0;t<256;t++){ wB+=hist[t]; if(!wB)continue; var wF=total-wB; if(!wF)break;
sumB+=t*hist[t]; var mB=sumB/wB,mF=(sumAll-sumB)/wF,bv=wB*wF*(mB-mF)*(mB-mF);
if(bv>maxV){maxV=bv;thr=t;} }
for(i=0,p=0;i<d.length;i+=4,p++){
var isText=invert?(gray[p]>thr):(gray[p]<thr);
var v=isText?0:255; d[i]=d[i+1]=d[i+2]=v; d[i+3]=255;
}
cx.putImageData(im,0,0);
}
// OCR
var busy=false;
function runOCR(){
if(!img){ toast("Load an image first.","warn"); return; }
busy=true; setBusy(true);
$("outCard").style.display="block"; $("skeleton").style.display="block"; $("output").style.display="none";
$("progress").style.display="block"; setProgress(.02);
var lang=$("lang").value, psm=$("psm").value, t0=performance.now();
var canvas;
try{ canvas=regionCanvas(); }catch(err){ fail(err); return; }
setStatus("Loading OCR engine…");
Tesseract.createWorker(lang,1,{
logger:function(m){ if(m.status==="recognizing text") setProgress(.15+m.progress*.85);
setStatus(cap(m.status)+(m.progress?(" "+Math.round(m.progress*100)+"%"):"")); }
}).then(function(worker){
return worker.setParameters({tessedit_pageseg_mode:psm}).then(function(){
return worker.recognize(canvas);
}).then(function(res){
return worker.terminate().then(function(){return res;});
});
}).then(function(res){
var data=res.data;
rawText=(data.text||"").trim(); cleanText=cleanup(rawText);
var secs=((performance.now()-t0)/1000).toFixed(1);
var conf=data.confidence?Math.round(data.confidence):null;
showOutput();
var words=(cleanText.match(/\S+/g)||[]).length;
$("outMeta").textContent=words+" words · "+(conf!==null?conf+"% confidence · ":"")+secs+"s"+($("enhance").checked?" · enhanced":"");
if(rawText){ toast("Text extracted","ok"); setStatus("Done ✓"); }
else { toast("No text detected in that region.","warn"); setStatus("No text found."); }
done();
}).catch(fail);
function fail(err){ console.error(err); toast("OCR failed: "+((err&&err.message)||err),"err"); setStatus("OCR failed."); done(); }
function done(){ busy=false; setBusy(false); setProgress(1);
setTimeout(function(){$("progress").style.display="none";setProgress(0);},500);
$("skeleton").style.display="none"; $("output").style.display="block"; }
}
// clean text formatter
function cleanup(t){
if(!t) return "";
var s=t.replace(/\r/g,"");
s=s.replace(/(\w)[-‐]\n(\w)/g,"$1$2");
s=s.replace(/\n{3,}/g,"\n\n");
s=s.replace(/([a-z0-9,;:)])\n(?=[a-z0-9(])/g,"$1 ");
s=s.split("\n").map(function(l){return l.replace(/[ \t]+$/,"").replace(/^[ \t]+/,"");}).join("\n");
s=s.replace(/[ \t]{2,}/g," ");
return s.trim();
}
// output UI
function showOutput(){
$("outCard").style.display="block";
$("output").value=activeTab==="clean"?cleanText:rawText;
$("outCard").scrollIntoView({behavior:"smooth",block:"nearest"});
}
$("tabClean").onclick=function(){activeTab="clean";toggleTabs();$("output").value=cleanText;};
$("tabRaw").onclick=function(){activeTab="raw";toggleTabs();$("output").value=rawText;};
function toggleTabs(){$("tabClean").classList.toggle("active",activeTab==="clean");$("tabRaw").classList.toggle("active",activeTab==="raw");}
$("btnCopy").onclick=function(){
var v=$("output").value; if(!v){toast("Nothing to copy yet.","warn");return;}
if(navigator.clipboard&&navigator.clipboard.writeText){ navigator.clipboard.writeText(v).then(function(){toast("Copied to clipboard","ok");},function(){legacyCopy(v);}); }
else legacyCopy(v);
};
function legacyCopy(v){ $("output").select(); try{document.execCommand("copy");toast("Copied to clipboard","ok");}catch(e){toast("Copy failed","err");} }
$("btnDownload").onclick=function(){
var v=$("output").value; if(!v){toast("Nothing to download.","warn");return;}
var a=document.createElement("a"); a.href=URL.createObjectURL(new Blob([v],{type:"text/plain"}));
a.download="sniptext.txt"; a.click(); URL.revokeObjectURL(a.href); toast("Saved sniptext.txt","ok");
};
// inputs
$("btnUpload").onclick=function(){$("fileInput").click();};
$("fileInput").onchange=function(e){ if(e.target.files[0]) loadImage(e.target.files[0]); };
$("btnCamera").onclick=function(){$("camInput").click();};
$("camInput").onchange=function(e){ if(e.target.files[0]) loadImage(e.target.files[0]); };
$("btnPaste").onclick=function(){
if(!(navigator.clipboard&&navigator.clipboard.read)){ toast("Use Ctrl/Cmd+V to paste here.","warn"); return; }
navigator.clipboard.read().then(function(items){
for(var k=0;k<items.length;k++){ var ty=items[k].types.find(function(t){return t.indexOf("image/")===0;});
if(ty){ items[k].getType(ty).then(loadImage); return; } }
toast("No image in clipboard — copy a screenshot first.","warn");
}).catch(function(){ toast("Clipboard blocked — try Ctrl/Cmd+V or Upload.","warn"); });
};
window.addEventListener("paste",function(e){
var items=e.clipboardData&&e.clipboardData.items; if(!items)return;
for(var k=0;k<items.length;k++){ if(items[k].type.indexOf("image/")===0){ loadImage(items[k].getAsFile()); break; } }
});
$("btnScreen").onclick=function(){
if(!hasScreen)return;
navigator.mediaDevices.getDisplayMedia({video:true}).then(function(stream){
var v=document.createElement("video"); v.srcObject=stream; v.play();
setTimeout(function(){
var c=document.createElement("canvas"); c.width=v.videoWidth; c.height=v.videoHeight;
c.getContext("2d").drawImage(v,0,0); stream.getTracks().forEach(function(t){t.stop();});
c.toBlob(function(b){loadImage(b);},"image/png");
},300);
}).catch(function(){ toast("Screen capture cancelled.","warn"); });
};
// drag & drop
var dz=$("dropzone");
dz.onclick=function(){$("fileInput").click();};
["dragenter","dragover"].forEach(function(ev){dz.addEventListener(ev,function(e){e.preventDefault();dz.classList.add("drag");});});
["dragleave","drop"].forEach(function(ev){dz.addEventListener(ev,function(e){e.preventDefault();dz.classList.remove("drag");});});
dz.addEventListener("drop",function(e){ var f=e.dataTransfer.files[0];
if(f&&f.type.indexOf("image/")===0) loadImage(f); else toast("Please drop an image file.","warn"); });
// actions
$("btnExtractSel").onclick=function(){ if(busy)return; if(!sel){toast("Drag a region first, or use Whole image.","warn");return;} runOCR(); };
$("btnExtractAll").onclick=function(){ if(busy)return; sel=null; cropEl.style.display="none"; runOCR(); };
$("btnResetSel").onclick=function(){ sel=null; cropEl.style.display="none"; toast("Selection cleared","ok"); };
$("btnNew").onclick=function(){ img=null; sel=null; $("cropCard").style.display="none"; $("outCard").style.display="none"; $("inputCard").scrollIntoView({behavior:"smooth"}); };
// helpers
function setStatus(m){$("status").textContent=m||"";}
function setProgress(p){$("progressBar").style.width=Math.round((p||0)*100)+"%";}
function setBusy(b){ ["btnExtractSel","btnExtractAll"].forEach(function(id){$(id).disabled=b;});
$("btnExtractSel").innerHTML=b?'<span class="spin"></span> Extracting…':'✂️ Extract selection'; }
})();
// Register service worker (installable PWA + offline)
if ("serviceWorker" in navigator) {
window.addEventListener("load", function () {
navigator.serviceWorker.register("sw.js").catch(function () {});
});
}