Download app.js from Battlettt/smishield: direct link, hf CLI and curl.
- Browser
- Download file 15.9 kB
-
https://huggingface.co/spaces/Battlettt/smishield/resolve/main/app.js
- Command line
-
hf download hf://spaces/Battlettt/smishield/app.js
-
curl -L -o app.js https://huggingface.co/spaces/Battlettt/smishield/resolve/main/app.js
15.9 kB
| ;(()=>{var b="__url__",y="__shorturl__",w="__currency__",k="__longnum__";var V=["bit.ly","tinyurl.com","goo.gl","t.co","ow.ly","is.gd","buff.ly","rebrand.ly","cutt.ly","shorturl.at","tiny.cc","rb.gy","bl.ink","t.ly","s.id","v.gd","short.io","tiny.one","lnkd.in","qr.ae"],U="[^ \\t\\n\\r\\f\\v]",J="(?:com|net|org|info|biz|co|uk|ly|gl|gd|cc|gy|at|io|me|link|ink|id|in|ae|one|us|xyz|top|ru|cn)",z=`(?:https?://|www\\.)${U}+|(?<![a-z0-9.-])(?:[a-z0-9-]+\\.)+${J}(?![a-z0-9-])(?:/${U}*)?`,C=`(${z})|([\xA3$\u20AC])|([a-z0-9]+)`,W=/^[0-9]+$/;function M(e){let t=e.replace(/^https?:\/\//,"").replace(/^www\./,"");return t=t.split("/")[0].split("?")[0],t.replace(/[^a-z0-9]+$/,"")}function S(e){return V.includes(e)}function Z(e){let t=[],o=new RegExp(C,"g");for(let n of e.toLowerCase().matchAll(o)){let[,i,s,c]=n;i!==void 0?(t.push(b),S(M(i))&&t.push(y)):s!==void 0?t.push(w):c!==void 0&&t.push(W.test(c)&&c.length>=5?k:c)}return t}function F(e){let t=Z(e),o=[...t];for(let n=0;n+1<t.length;n++)o.push(`${t[n]} ${t[n+1]}`);return o}function I(e){let t=new RegExp(z,"g");return[...e.toLowerCase().matchAll(t)].map(o=>{let n=M(o[0]);return{url:o[0],domain:n,shortened:S(n)}})}function K(e){let t=e;if(!t||t.format!=="smishield-tfidf-logreg")throw new Error("Not a smishield model file");let o=t.vocabulary.length;if(t.idf.length!==o||t.coef.length!==o)throw new Error(`Model arrays disagree: vocab=${o} idf=${t.idf.length} coef=${t.coef.length}`);if(t.tfidf.norm!=="l2")throw new Error(`Unsupported norm ${t.tfidf.norm}`);let n=new Map;return t.vocabulary.forEach((i,s)=>n.set(i,s)),{raw:t,index:n}}function X(e,t){let o=new Map;for(let c of F(t)){let r=e.index.get(c);r!==void 0&&o.set(r,(o.get(r)??0)+1)}let n=new Map,i=0;for(let[c,r]of o){let l=(e.raw.tfidf.sublinearTf?1+Math.log(r):r)*e.raw.idf[c];n.set(c,l),i+=l*l}let s=Math.sqrt(i);if(s>0)for(let[c,r]of n)n.set(c,r/s);return n}function Q(e){if(e>=0)return 1/(1+Math.exp(-e));let t=Math.exp(e);return t/(1+t)}function x(e,t){let o=X(e,t),{coef:n,intercept:i,vocabulary:s,threshold:c}=e.raw,r=i,a=[];for(let[d,m]of o){let g=n[d];r+=m*g,a.push({term:s[d],weight:m,coef:g,contribution:m*g})}a.sort((d,m)=>Math.abs(m.contribution)-Math.abs(d.contribution));let l=Q(r),u=l>=c;return{label:u?"spam":"ham",isSpam:u,probability:l,confidence:u?l:1-l,logit:r,contributions:a}}function E(e){let t=[],o=new RegExp(C,"g");for(let n of e.toLowerCase().matchAll(o)){let[i,s,c,r]=n,a=n.index??0,l=a+i.length;if(s!==void 0)t.push({token:b,start:a,end:l}),S(M(s))&&t.push({token:y,start:a,end:l});else if(c!==void 0)t.push({token:w,start:a,end:l});else if(r!==void 0){let u=/^[0-9]+$/.test(r)&&r.length>=5;t.push({token:u?k:r,start:a,end:l})}}return t}function H(e,t,o){let n=E(e),i=new Map,s=(r,a,l,u)=>{if(i.has(r.start))return;let d=r.token===b||r.token===y||r.end-r.start>16;i.set(r.start,{start:r.start,end:r.end,kind:a,exhibit:l,term:u.term,contribution:u.contribution,link:d})},c=(r,a)=>{r.forEach((l,u)=>{let d=l.term.split(" ");for(let m=0;m<n.length;m++)d.length===1?n[m].token===d[0]&&s(n[m],a,u+1,l):m+1<n.length&&n[m].token===d[0]&&n[m+1].token===d[1]&&(s(n[m],a,u+1,l),s(n[m+1],a,u+1,l))})};return c(t,"spam"),c(o,"ham"),[...i.values()].sort((r,a)=>r.start-a.start)}function j(e,t,o=160){let n=t.toLowerCase(),i=E(t),s=[];i.forEach((l,u)=>{u+1<i.length&&i[u+1].start===l.start||s.push(u+1)});let c=Math.max(1,Math.ceil(s.length/(o-1))),r=s.filter((l,u)=>u%c===0||u===s.length-1),a=[{tokens:0,probability:x(e,"").probability}];for(let l of r){let u=i[l-1].end,d=l===i.length?x(e,t).probability:x(e,n.slice(0,u)).probability;a.push({tokens:l,probability:d})}return a}var te=["act now","limited time","urgent","urgently","immediately","right away","asap","expires","expiring","expire","expired","final notice","final attempt","last chance","today only","hurry","don't miss","dont miss","now or never","respond now","call now","reply now","claim now","click now","action required","deadline","before midnight","ends tonight","ends today"],ne=[/within [0-9]+ ?(?:hours?|hrs?|mins?|minutes?|days?)(?![a-z])/g,/valid (?:for )?(?:only )?[0-9]+ ?(?:hours?|hrs?|mins?|minutes?|days?)(?![a-z])/g],re=["won","win","winner","winning","prize","claim","cash","reward","free","bonus","gift card","giftcard","voucher","award","jackpot","lottery","congratulations","congrats","selected","guaranteed","refund","rebate","loan","cashback"],oe=[/[£$€] ?[0-9][0-9,.]*/g,/[0-9][0-9,.]* ?(?:pounds|dollars|euros|usd|gbp)/g],se=["verify","verification","account","suspended","locked","blocked","password","pin","login","log in","sign in","bank","unpaid","overdue","payment","confirm your","update your","security alert","unusual activity","delivery","parcel","package","redelivery","customs fee","toll","tax"],ie=[/(?<![0-9])09[0-9]{8,9}(?![0-9])/g,/(?<![0-9])087[0-9]{7,8}(?![0-9])/g,/(?:text|txt|send|reply|sms)(?: [a-z0-9]+){0,3} to [0-9]{4,6}(?![0-9])/g,/[0-9]+p ?(?:\/|per) ?(?:msg|min|text|sms|wk|week)/g];function ae(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function N(e,t){let o=[];for(let n of t)new RegExp(`(?<![a-z])${ae(n)}(?![a-z])`).test(e)&&o.push(n);return o}function _(e,t){let o=new Set;for(let n of t)for(let i of e.matchAll(n))o.add(i[0].trim());return[...o]}function ce(e){let t=e.trim();if(!t)return null;let o=[],n=t.replace(/[^0-9]/g,""),i=/^\+?[0-9 ()-]+$/.test(t);return/^[^@\s]+@[^@\s]+\.[a-z]{2,}$/i.test(t)?o.push("sent from an email address (email-to-SMS gateways are common for bulk spam)"):i&&n.length>=4&&n.length<=6?o.push(`short code ${n} (used for bulk and premium-rate messaging)`):i&&(n.length>15||n.length>0&&n.length<4)?o.push(`number has an unusual length (${n.length} digits)`):!i&&/[a-z][0-9]|[0-9][a-z]/i.test(t)&&/[01345]/.test(t)&&o.push(`"${t}" mixes letters and look-alike digits, as in brand impersonation (e.g. AMAZ0N)`),o.length===0?null:{id:"suspicious-sender",label:"Suspicious sender pattern",detail:o.join("; "),evidence:[t]}}function le(e,t=""){let o=e.toLowerCase(),n=[],i=I(e),s=i.filter(m=>m.shortened);s.length>0&&n.push({id:"shortened-url",label:"Shortened URL",detail:`link shortener (${[...new Set(s.map(m=>m.domain))].join(", ")}) hides the real destination`,evidence:s.map(m=>m.url)});let c=i.filter(m=>!m.shortened);c.length>0&&n.push({id:"link",label:"Contains a link",detail:`links to ${[...new Set(c.map(m=>m.domain))].join(", ")}; check it before tapping`,evidence:c.map(m=>m.url)});let r=[...N(o,te),..._(o,ne)];r.length>0&&n.push({id:"urgency",label:"Urgency language",detail:`pressure to act quickly: ${$(r)}`,evidence:r});let a=[...N(o,re),..._(o,oe)];a.length>0&&n.push({id:"prize-money",label:"Prize / money language",detail:`promises of money or prizes: ${$(a)}`,evidence:a});let l=N(o,se);l.length>0&&n.push({id:"account-security",label:"Account / payment / delivery language",detail:`common smishing lures: ${$(l)}`,evidence:l});let u=_(o,ie);u.length>0&&n.push({id:"premium-number",label:"Premium-rate number or short code",detail:`asks you to call or text a paid or bulk-messaging number: ${$(u)}`,evidence:u});let d=ce(t);return d&&n.push(d),n}function $(e,t=4){let o=[...new Set(e)],n=o.slice(0,t).map(i=>`"${i}"`);return o.length>t?`${n.join(", ")} and ${o.length-t} more`:n.join(", ")}function v(e){return e.split(" ").map(t=>{switch(t){case b:return"[link]";case y:return"[short link]";case w:return"[\xA3/$/\u20AC]";case k:return"[phone number/short code]";default:return t}}).join(" ")}function L(e){let t=Math.round(e*100);return t>=100?">99%":`${t}%`}function D(e){return e.length<=1?e.join(""):`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function G(e,t,o=""){let n=x(e,t),i=le(t,o),s=n.contributions.filter(d=>d.contribution>0).slice(0,5),c=n.contributions.filter(d=>d.contribution<0).slice(0,5),r=L(n.confidence),a=d=>d.slice(0,4).map(m=>`"${v(m.term)}"`).join(", "),l=i.map(d=>d.label.charAt(0).toLowerCase()+d.label.slice(1)),u;if(n.isSpam){let d=[...l];s.length>0&&d.push(`wording the model associates with spam (${a(s)})`),u=`Likely spam/smishing (${r} confidence). `+(d.length>0?`Main signals: ${D(d)}.`:"")}else u=`Likely legitimate (${r} confidence). `+(c.length>0?`The wording resembles ordinary personal messages (${a(c)}).`:"The model found little that resembles known spam."),i.length>0&&(u+=` However, some warning signs are present (${D(l)}); the model's score stayed below the spam threshold, so still be careful with links and requests.`);return{score:n,signals:i,spamTerms:s,hamTerms:c,summary:u.trim()}}var ue={smishing:{text:"USPS: Your package is on hold due to an unpaid shipping fee. Act now, limited time: https://bit.ly/3Pq9xZ",sender:"usps-alert@notify-mail.com"},prize:{text:"URGENT! We are trying to contact U. Todays draw shows that you have won a \xA3800 prize GUARANTEED. Call 09050003091 from land line. Claim C52. Valid 12hrs only",sender:"80086"},legit:{text:"Hey, are we still ok for dinner tonight? I'll bring the wine. Running about 10 mins late",sender:""}},A=600,P=570,de=12,me=216,pe=.15;function p(e){let t=document.getElementById(e);if(!t)throw new Error(`#${e} missing`);return t}function h(e,t,o){let n=document.createElement(e);return t!==void 0&&(n.textContent=t),o&&(n.className=o),n}var f=(e,t=1)=>`${(e*100).toFixed(t)}%`,Y=()=>window.matchMedia("(prefers-reduced-motion: reduce)").matches,O=e=>de+(1-e)*me;function ge(e,t){let o=p("transcript");o.replaceChildren();let n=e.toLowerCase().length===e.length?t:[],i=0;n.forEach((s,c)=>{s.start>i&&o.append(document.createTextNode(e.slice(i,s.start)));let r=h("span",e.slice(s.start,s.end)),a=`v${c%3+1}`;r.className=s.kind==="spam"?`mark mark-spam ${s.link?"mark-link":a}`:"mark mark-ham",r.style.setProperty("--i",String(c));let l=s.contribution>0?"+":"";r.title=`${s.kind==="spam"?"Exhibit against":"Exhibit in favour"} ${s.exhibit}: "${v(s.term)}" ${l}${s.contribution.toFixed(2)}`;let u=h("sup",String(s.exhibit));u.setAttribute("aria-hidden","true"),r.append(u),o.append(r),i=s.end}),i<e.length&&o.append(document.createTextNode(e.slice(i)))}function q(e,t,o){let n=p(e);n.replaceChildren(),t.length===0&&n.append(h("li",o,"none"));for(let i of t){let s=h("li"),c=i.contribution>0?"+":"";s.append(h("span",v(i.term),"term"),h("span",`${c}${i.contribution.toFixed(2)}`,"weight")),n.append(s)}}function he(e,t){let o=p("result"),n=e.score.probability;o.hidden=!1,o.classList.remove("spam","ham"),o.classList.add(e.score.isSpam?"spam":"ham"),p("verdict").textContent=e.score.isSpam?"Deception indicated":"No deception indicated",p("probability").textContent=f(n),p("confidence").textContent=L(e.score.confidence),p("tokens-read").textContent=String(E(t).length);let i=p("close-call"),s=Math.abs(n-.5);if(s<pe){i.hidden=!1;let r=(s*100).toFixed(1);i.textContent=`Close call: the needle settled ${r} points ${n>=.5?"above":"below"} the threshold. Treat this finding with care.`}else i.hidden=!0;p("summary").textContent=e.summary,ge(t,H(t,e.spamTerms,e.hamTerms)),q("spam-terms",e.spamTerms,"No words pushed toward spam."),q("ham-terms",e.hamTerms,"No words pushed toward legitimate.");let c=p("signals");c.replaceChildren(),e.signals.length===0&&c.append(h("li","No pattern-based warning signs found.","none"));for(let r of e.signals){let a=h("li");a.append(h("strong",r.label),document.createTextNode(`: ${r.detail}`)),c.append(a)}}function fe(e,t){let o=e[e.length-1].tokens||1,n=[],i=Math.floor(t);for(let s=0;s<=Math.min(i,e.length-1);s++){let c=e[s];n.push(`${s===0?"M":"L"}${(c.tokens/o*P).toFixed(2)} ${O(c.probability).toFixed(2)}`)}if(i<e.length-1){let s=e[i],c=e[i+1],r=t-i,a=(s.tokens+(c.tokens-s.tokens)*r)/o*P,l=O(s.probability+(c.probability-s.probability)*r);n.push(`L${a.toFixed(2)} ${l.toFixed(2)}`)}return n.join(" ")}function be(e,t){let o=Math.min(Math.max(0,t),e.length-1),n=e[e.length-1].tokens||1,i=Math.min(Math.floor(o),e.length-1),s=e[i],c=e[Math.min(i+1,e.length-1)],r=o-i,a=s.probability+(c.probability-s.probability)*r;return{x:(s.tokens+(c.tokens-s.tokens)*r)/n*(P/A),y:O(a)/240,p:a}}var R=0;function ye(e,t){cancelAnimationFrame(R);let o=p("chart-wrap"),n=p("trace"),i=p("pen"),s=p("pen-arm"),c=p("readout");o.classList.remove("idle");let r=m=>{let g=be(e,m);n.setAttribute("d",fe(e,m)),i.style.left=`${g.x*100}%`,i.style.top=`${g.y*100}%`;let T=(g.y*240).toFixed(2);s.setAttribute("x1",String(g.x*A)),s.setAttribute("x2",String(A)),s.setAttribute("y1",T),s.setAttribute("y2",T),c.textContent=f(g.p)},a=e.length-1;if(Y()||a===0){r(a),t();return}let l=Math.min(2600,Math.max(1100,400+e.length*22)),u=performance.now();i.classList.add("writing");let d=m=>{let g=Math.min(1,Math.max(0,(m-u)/l)),T=1-Math.pow(1-g,2.2);r(T*a),g<1?R=requestAnimationFrame(d):(i.classList.remove("writing"),t())};R=requestAnimationFrame(d)}function xe(e){p("m-f1").textContent=f(e.test.f1),p("m-accuracy").textContent=f(e.test.accuracy),p("m-precision").textContent=f(e.test.precision),p("m-recall").textContent=f(e.test.recall),p("cal-test").textContent=e.split.test.toLocaleString("en");let t=e.test.confusionMatrix;p("cm-tn").textContent=String(t.trueNegatives),p("cm-fp").textContent=String(t.falsePositives),p("cm-fn").textContent=String(t.falseNegatives),p("cm-tp").textContent=String(t.truePositives),p("metrics-note").textContent=`Held-out stratified 20% split: ${e.split.test.toLocaleString("en")} messages (${e.split.testHam} legitimate, ${e.split.testSpam} spam) of the ${e.dataset.messages.toLocaleString("en")}-message SMS Spam Collection. Trained on the other ${e.split.train.toLocaleString("en")} (seed ${e.split.seed}), ${e.model.vocabularySize.toLocaleString("en")}-term vocabulary, C=${e.model.C}, scikit-learn ${e.model.sklearnVersion}.`}async function B(e){let t=await fetch(e);if(!t.ok)throw new Error(`${e}: HTTP ${t.status}`);return await t.json()}async function we(){let e=p("status"),t=p("analyze"),o=p("message"),n=p("sender"),i=[...document.querySelectorAll("[data-example]")];i.forEach(r=>r.setAttribute("aria-pressed","false")),p("chart-wrap").classList.add("idle");let s;try{let[r,a]=await Promise.all([B("model.json"),B("metrics.json")]);s=K(r),xe(a)}catch(r){e.textContent=`Could not load the model (${r.message}). If you opened index.html directly from disk, serve the docs/ folder over HTTP instead (for example: npm run serve).`,e.className="status error";return}e.textContent=`Model ready: ${s.raw.vocabulary.length.toLocaleString("en")} features, scored on this device.`,t.disabled=!1;let c=()=>{let r=o.value.trim();if(!r){e.textContent="Paste a message into the phone first, or open a case file.",e.className="status error",o.focus();return}e.className="status",e.textContent="Examined locally in your browser. Nothing was sent anywhere.";let a=G(s,r,n.value),l=j(s,r),u=p("result");he(a,r),u.classList.remove("reveal"),u.classList.add("waiting");let d=a.score.isSpam?"Deception indicated: likely spam or smishing.":"No deception indicated: likely legitimate.";p("announce").textContent=`${d} Spam probability ${f(a.score.probability)}.`,p("chart-desc").textContent=`The needle started at ${f(l[0].probability)} (the model's starting point with no words) and settled at ${f(a.score.probability)} after reading ${l[l.length-1].tokens} tokens. ${a.score.isSpam?"It finished above":"It finished below"} the 50% threshold.`,window.matchMedia("(max-width: 860px)").matches&&p("chart-heading").scrollIntoView({behavior:Y()?"auto":"smooth",block:"start"}),ye(l,()=>{u.classList.remove("waiting"),u.offsetWidth,u.classList.add("reveal")})};t.addEventListener("click",c),o.addEventListener("keydown",r=>{r.key==="Enter"&&(r.ctrlKey||r.metaKey)&&(r.preventDefault(),c())}),o.addEventListener("input",()=>i.forEach(r=>r.setAttribute("aria-pressed","false"))),i.forEach(r=>{r.addEventListener("click",()=>{let a=ue[r.dataset.example??""];a&&(o.value=a.text,n.value=a.sender,i.forEach(l=>l.setAttribute("aria-pressed",String(l===r))),c())})})}we();})(); | |
| //# sourceMappingURL=app.js.map | |