Spaces:
Running
Running
Fix browser input tensor BigInt handling
Browse files- index.html +2 -2
index.html
CHANGED
|
@@ -23,8 +23,8 @@ const $=id=>document.getElementById(id), text=$('text'), status=$('status'); let
|
|
| 23 |
examples.forEach(([id,t])=>{let b=document.createElement('button');b.className='chip';b.textContent=`ID ${id} · ${t.slice(0, thirty=32)}${t.length>32?'…':''}`;b.onclick=()=>{text.value=t;text.focus()};$('examples').appendChild(b)});
|
| 24 |
function basicTokenize(input){return input.toLowerCase().replace(/([!"#$%&'()*+,-./:;<=>?@[\\\]^_`{|}~])/g,' $1 ').trim().split(/\\s+/).filter(Boolean)}
|
| 25 |
function wordPiece(word){if(vocab[word]!==undefined)return [word];let pieces=[];let start=0;while(start<word.length){let end=word.length,found=null;while(start<end){let part=word.slice(start,end);if(start>0)part='##'+part;if(vocab[part]!==undefined){found=part;break}end--}if(found===null)return ['[UNK]'];pieces.push(found);start=end}return pieces}
|
| 26 |
-
function encode(input){let tokens=['[CLS]'];for(const word of basicTokenize(input))tokens.push(...wordPiece(word));tokens
|
| 27 |
async function load(){try{status.textContent='正在加载分词表和量化模型…';let [vocabText]=await Promise.all([fetch('./vocab.txt').then(r=>{if(!r.ok)throw Error('无法加载词表');return r.text()}),]);vocab={};vocabText.split(/\\r?\\n/).forEach((t,i)=>{if(t)vocab[t]=i});session=await ort.InferenceSession.create(MODEL,{executionProviders:['wasm']});status.className='meta';status.textContent='已就绪 · 模型在浏览器本地运行'}catch(e){status.className='meta error';status.textContent='模型加载失败:'+e.message}}
|
| 28 |
-
async function classify(){if(!session||!vocab){status.textContent='模型仍在加载,请稍候…';return}if(!text.value.trim()){status.className='meta error';status.textContent='请先输入文本。';return}status.className='meta loading';status.textContent='正在本地分类…';try{let enc=encode(text.value),feeds={input_ids:new ort.Tensor('int64',BigInt64Array.from(enc.ids.map(BigInt)),[1,128]),attention_mask:new ort.Tensor('int64',BigInt64Array.from(enc.mask.map(BigInt)),[1,128]),token_type_ids:new ort.Tensor('int64',BigInt64Array.from(
|
| 29 |
$('run').onclick=classify;$('clear').onclick=()=>{text.value='';$('result').hidden=true;status.textContent='已就绪 · 模型在浏览器本地运行'};load();
|
| 30 |
</script></body></html>
|
|
|
|
| 23 |
examples.forEach(([id,t])=>{let b=document.createElement('button');b.className='chip';b.textContent=`ID ${id} · ${t.slice(0, thirty=32)}${t.length>32?'…':''}`;b.onclick=()=>{text.value=t;text.focus()};$('examples').appendChild(b)});
|
| 24 |
function basicTokenize(input){return input.toLowerCase().replace(/([!"#$%&'()*+,-./:;<=>?@[\\\]^_`{|}~])/g,' $1 ').trim().split(/\\s+/).filter(Boolean)}
|
| 25 |
function wordPiece(word){if(vocab[word]!==undefined)return [word];let pieces=[];let start=0;while(start<word.length){let end=word.length,found=null;while(start<end){let part=word.slice(start,end);if(start>0)part='##'+part;if(vocab[part]!==undefined){found=part;break}end--}if(found===null)return ['[UNK]'];pieces.push(found);start=end}return pieces}
|
| 26 |
+
function encode(input){const unk=Number.isInteger(vocab['[UNK]'])?vocab['[UNK]']:100;const pad=Number.isInteger(vocab['[PAD]'])?vocab['[PAD]']:0;const cls=Number.isInteger(vocab['[CLS]'])?vocab['[CLS]']:101;const sep=Number.isInteger(vocab['[SEP]'])?vocab['[SEP]']:102;let tokens=['[CLS]'];for(const word of basicTokenize(input))tokens.push(...wordPiece(word));tokens=tokens.slice(0,126);tokens.push('[SEP]');let ids=tokens.map(t=>Number.isInteger(vocab[t])?vocab[t]:unk);while(ids.length<128)ids.push(pad);ids[0]=cls;ids[tokens.length-1]=sep;let mask=ids.map((_,i)=>i<tokens.length?1:0);return {ids,mask}}
|
| 27 |
async function load(){try{status.textContent='正在加载分词表和量化模型…';let [vocabText]=await Promise.all([fetch('./vocab.txt').then(r=>{if(!r.ok)throw Error('无法加载词表');return r.text()}),]);vocab={};vocabText.split(/\\r?\\n/).forEach((t,i)=>{if(t)vocab[t]=i});session=await ort.InferenceSession.create(MODEL,{executionProviders:['wasm']});status.className='meta';status.textContent='已就绪 · 模型在浏览器本地运行'}catch(e){status.className='meta error';status.textContent='模型加载失败:'+e.message}}
|
| 28 |
+
async function classify(){if(!session||!vocab){status.textContent='模型仍在加载,请稍候…';return}if(!text.value.trim()){status.className='meta error';status.textContent='请先输入文本。';return}status.className='meta loading';status.textContent='正在本地分类…';try{let enc=encode(text.value),feeds={input_ids:new ort.Tensor('int64',BigInt64Array.from(enc.ids.map(v=>BigInt(v))),[1,128]),attention_mask:new ort.Tensor('int64',BigInt64Array.from(enc.mask.map(v=>BigInt(v))),[1,128]),token_type_ids:new ort.Tensor('int64',BigInt64Array.from(Array(128).fill(0).map(()=>0n)),[1,128])};let out=await session.run(feeds);let logits=Array.from(out.logits.data), ex=Math.max(...logits), probs=logits.map(x=>Math.exp(x-ex));let sum=probs.reduce((a,b)=>a+b,0);probs=probs.map(x=>x/sum);let i=probs[1]>probs[0]?1:0, conf=probs[i];$('prediction').textContent=LABELS[i];$('confidence').textContent=(conf*100).toFixed(1)+'%';$('confidence-bar').style.width=(conf*100)+'%';$('details').textContent=`非灾害 ${(probs[0]*100).toFixed(1)}% · 灾害 ${(probs[1]*100).toFixed(1)}%`;$('result').hidden=false;status.className='meta';status.textContent='完成 · 文本未发送到服务器'}catch(e){status.className='meta error';status.textContent='推理失败:'+e.message}}
|
| 29 |
$('run').onclick=classify;$('clear').onclick=()=>{text.value='';$('result').hidden=true;status.textContent='已就绪 · 模型在浏览器本地运行'};load();
|
| 30 |
</script></body></html>
|