Upload index.html
Browse files- index.html +140 -0
index.html
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<title>Sentiment AI Analyzer</title>
|
| 7 |
+
<style>
|
| 8 |
+
:root{color-scheme:light dark;--bg:#101827;--card:#1a2638;--text:#e9eef7;--muted:#9aa9bc;--accent:#6c9cff;--border:#34445b}
|
| 9 |
+
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font-family:system-ui,-apple-system,Segoe UI,sans-serif;padding:24px}
|
| 10 |
+
main{max-width:950px;margin:auto}h1{margin:0 0 8px}p{color:var(--muted)}.card{background:var(--card);border:1px solid var(--border);border-radius:16px;padding:20px;margin:18px 0}
|
| 11 |
+
textarea{width:100%;min-height:140px;padding:14px;border-radius:12px;border:1px solid var(--border);background:var(--bg);color:var(--text);font:inherit}
|
| 12 |
+
button{padding:10px 14px;border-radius:10px;border:1px solid var(--border);background:#263852;color:var(--text);cursor:pointer;margin:5px 5px 5px 0}button.primary{background:var(--accent);color:#081222;border:0;font-weight:700}
|
| 13 |
+
.row{display:flex;gap:14px;flex-wrap:wrap}.row>*{flex:1;min-width:180px}.score{margin:12px 0}.bar{height:12px;border-radius:8px;background:#34445b;overflow:hidden}.fill{height:100%;background:var(--accent);width:0}.muted{color:var(--muted);font-size:.9rem}.history-item{border:1px solid var(--border);padding:12px;border-radius:12px;margin:10px 0;overflow-wrap:anywhere}.hidden{display:none}.status{padding:10px;border-radius:8px;background:#263852;margin:10px 0}
|
| 14 |
+
body.light{--bg:#f3f6fb;--card:#ffffff;--text:#182233;--muted:#5b6778;--accent:#3977e8;--border:#d2dbe8}input,select{background:var(--bg);color:var(--text);border:1px solid var(--border)}\n</style>
|
| 15 |
+
</head>
|
| 16 |
+
<body>
|
| 17 |
+
<main>
|
| 18 |
+
<div class="row" style="align-items:center"><div><h1>💬 Sentiment AI Analyzer 3.0</h1></div><div style="text-align:right"><button id="themeBtn">🌙 Toggle theme</button></div></div>
|
| 19 |
+
<p>Analyze text sentiment with a Hugging Face model directly in your browser.</p>
|
| 20 |
+
<div class="card">
|
| 21 |
+
<label for="textInput"><strong>Enter text to analyze</strong></label>
|
| 22 |
+
<textarea id="textInput" placeholder="Type or paste your text here..."></textarea>
|
| 23 |
+
<p class="muted"><span id="wordCount">0</span> words · <span id="charCount">0</span> characters</p>
|
| 24 |
+
<div>
|
| 25 |
+
<button class="primary" id="analyzeBtn">🔍 Analyze Sentiment</button><button id="clearBtn">Clear text</button>
|
| 26 |
+
<button class="example" data-text="I absolutely love this product. It works wonderfully!">Positive example</button>
|
| 27 |
+
<button class="example" data-text="This was a terrible experience and I am very disappointed.">Negative example</button>
|
| 28 |
+
<button class="example" data-text="The service was okay, nothing special.">Neutral-ish example</button>
|
| 29 |
+
</div><div id="status" class="status">Loading sentiment model…</div>
|
| 30 |
+
</div>
|
| 31 |
+
<div id="results" class="card hidden">
|
| 32 |
+
<h2>Analysis Result</h2><h3 id="resultLabel"></h3>
|
| 33 |
+
<div class="score"><strong>Positive: <span id="positiveText"></span></strong><div class="bar"><div class="fill" id="positiveBar"></div></div></div>
|
| 34 |
+
<div class="score"><strong>Neutral*: <span id="neutralText"></span></strong><div class="bar"><div class="fill" id="neutralBar"></div></div></div>
|
| 35 |
+
<div class="score"><strong>Negative: <span id="negativeText"></span></strong><div class="bar"><div class="fill" id="negativeBar"></div></div></div>
|
| 36 |
+
<p class="muted">*Neutral is a heuristic estimate based on the binary model's confidence, not a genuine third model class.</p>
|
| 37 |
+
</div>
|
| 38 |
+
<div class="card" id="batchCard">
|
| 39 |
+
<h2>📦 Batch Analysis</h2>
|
| 40 |
+
<p class="muted">Analyze multiple sentences at once. Enter one text per line.</p>
|
| 41 |
+
<textarea id="batchInput" placeholder="One text per line..." style="min-height:110px"></textarea>
|
| 42 |
+
<button id="batchAnalyzeBtn" class="primary">Analyze Batch</button>
|
| 43 |
+
<button id="batchExportBtn">Export batch results CSV</button><div id="batchResults"></div>
|
| 44 |
+
</div>
|
| 45 |
+
<div class="card" id="analyticsCard">
|
| 46 |
+
<h2>📊 Analytics Dashboard</h2>
|
| 47 |
+
<div class="row"><div><strong>Total analyses</strong><h3 id="totalAnalyses">0</h3></div><div><strong>Positive</strong><h3 id="positiveCount">0</h3></div><div><strong>Negative</strong><h3 id="negativeCount">0</h3></div><div><strong>Neutral-ish</strong><h3 id="neutralCount">0</h3></div></div>
|
| 48 |
+
<div class="score"><strong>Positive proportion</strong><div class="bar"><div class="fill" id="analyticsPositive"></div></div></div>
|
| 49 |
+
<div class="score"><strong>Negative proportion</strong><div class="bar"><div class="fill" id="analyticsNegative"></div></div></div>
|
| 50 |
+
<div class="score"><strong>Neutral-ish proportion</strong><div class="bar"><div class="fill" id="analyticsNeutral"></div></div></div>
|
| 51 |
+
</div>
|
| 52 |
+
<div class="card"><h3>📈 Sentiment trend</h3><canvas id="trendCanvas" width="900" height="240" style="width:100%;max-width:900px"></canvas><p class="muted">Trend is based on saved analyses in chronological order.</p></div>
|
| 53 |
+
<div class="card">
|
| 54 |
+
<div class="row" style="align-items:center"><div><h2>📜 History</h2><p class="muted">Saved in this browser · up to 100 entries</p></div><div><button id="exportCsvBtn">Export CSV</button><button id="exportJsonBtn">Export JSON</button><button id="historyClearBtn">Clear history</button></div></div>
|
| 55 |
+
<div class="row"><div><input id="historySearch" placeholder="Search history…" style="width:100%;padding:10px;border-radius:8px"></div><div><select id="historyFilter" style="padding:10px;border-radius:8px;width:100%"><option value="all">All sentiments</option><option value="Positive">Positive</option><option value="Negative">Negative</option></select></div></div><div id="historyList"></div>
|
| 56 |
+
</div>
|
| 57 |
+
</main>
|
| 58 |
+
<script type="module">
|
| 59 |
+
import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.7.2';
|
| 60 |
+
|
| 61 |
+
const textInput=document.getElementById('textInput');
|
| 62 |
+
let history=JSON.parse(localStorage.getItem('sentimentHistory')||'[]');
|
| 63 |
+
let classifier=null;
|
| 64 |
+
|
| 65 |
+
function updateCounter(){const t=textInput.value;document.getElementById('wordCount').textContent=t.trim()?t.trim().split(/\s+/).length:0;document.getElementById('charCount').textContent=t.length;}
|
| 66 |
+
function setStatus(msg){document.getElementById('status').textContent=msg;}
|
| 67 |
+
async function loadModel(){try{setStatus('Loading model (first run may take a while)…');classifier=await pipeline('sentiment-analysis','Xenova/distilbert-base-uncased-finetuned-sst-2-english');setStatus('Model ready. Enter text and click Analyze.');}catch(e){setStatus('Model loading failed: '+e.message);}}
|
| 68 |
+
function renderAnalytics(){
|
| 69 |
+
const total=history.length, pos=history.filter(x=>x.label==='Positive').length, neg=history.filter(x=>x.label==='Negative').length, neu=Math.max(0,total-pos-neg);
|
| 70 |
+
document.getElementById('totalAnalyses').textContent=total;
|
| 71 |
+
document.getElementById('positiveCount').textContent=pos;
|
| 72 |
+
document.getElementById('negativeCount').textContent=neg;
|
| 73 |
+
document.getElementById('neutralCount').textContent=neu;
|
| 74 |
+
document.getElementById('analyticsPositive').style.width=(total?pos/total*100:0)+'%';
|
| 75 |
+
document.getElementById('analyticsNegative').style.width=(total?neg/total*100:0)+'%';
|
| 76 |
+
document.getElementById('analyticsNeutral').style.width=(total?neu/total*100:0)+'%';
|
| 77 |
+
drawTrend();
|
| 78 |
+
}
|
| 79 |
+
function drawTrend(){
|
| 80 |
+
const canvas=document.getElementById('trendCanvas');if(!canvas)return;
|
| 81 |
+
const ctx=canvas.getContext('2d'),w=canvas.width,h=canvas.height;
|
| 82 |
+
ctx.clearRect(0,0,w,h);ctx.strokeStyle=getComputedStyle(document.body).getPropertyValue('--border');ctx.lineWidth=1;
|
| 83 |
+
for(let i=1;i<4;i++){ctx.beginPath();ctx.moveTo(0,h*i/4);ctx.lineTo(w,h*i/4);ctx.stroke();}
|
| 84 |
+
if(!history.length){ctx.fillStyle=getComputedStyle(document.body).getPropertyValue('--muted');ctx.fillText('No history yet',20,30);return;}
|
| 85 |
+
const chronological=[...history].reverse().slice(-50);
|
| 86 |
+
ctx.strokeStyle=getComputedStyle(document.body).getPropertyValue('--accent');ctx.lineWidth=3;ctx.beginPath();
|
| 87 |
+
chronological.forEach((r,i)=>{const val=Number(r.positive||0)-Number(r.negative||0);const x=chronological.length===1?w/2:i*(w-20)/(chronological.length-1)+10;const y=h/2-val*(h/2-20);if(i===0)ctx.moveTo(x,y);else ctx.lineTo(x,y);});ctx.stroke();
|
| 88 |
+
}
|
| 89 |
+
function renderHistory(){
|
| 90 |
+
const el=document.getElementById('historyList');if(!history.length){el.innerHTML='<p class="muted">No analyses yet.</p>';renderAnalytics();return;}
|
| 91 |
+
const q=(document.getElementById('historySearch')?.value||'').toLowerCase(),f=document.getElementById('historyFilter')?.value||'all';
|
| 92 |
+
const shown=history.filter(item=>(f==='all'||item.label===f)&&String(item.text).toLowerCase().includes(q));
|
| 93 |
+
el.innerHTML=shown.map((item,i)=>`<div class="history-item"><strong>${escapeHtml(item.label)}</strong> · ${escapeHtml(item.time)}<p>${escapeHtml(item.text)}</p><small>Positive ${pct(item.positive)} · Neutral ${pct(item.neutral)} · Negative ${pct(item.negative)}</small></div>`).join('')||'<p class="muted">No matching history.</p>';renderAnalytics();
|
| 94 |
+
}
|
| 95 |
+
function escapeHtml(s){return String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));}
|
| 96 |
+
function pct(v){return (Number(v||0)*100).toFixed(1)+'%';}
|
| 97 |
+
function showResults(text,label,scores,confidence){document.getElementById('results').classList.remove('hidden');document.getElementById('resultLabel').textContent=label+' ('+pct(confidence)+' model confidence)';for(const k of ['positive','neutral','negative']){document.getElementById(k+'Text').textContent=pct(scores[k]);document.getElementById(k+'Bar').style.width=(scores[k]*100)+'%';}
|
| 98 |
+
history.unshift({text,label,positive:scores.positive,neutral:scores.neutral,negative:scores.negative,confidence,time:new Date().toLocaleString()});
|
| 99 |
+
history=history.slice(0,100);
|
| 100 |
+
localStorage.setItem('sentimentHistory',JSON.stringify(history));
|
| 101 |
+
renderHistory();}
|
| 102 |
+
async function analyze(){const text=textInput.value.trim();if(!text){setStatus('Please enter some text first.');return;}if(!classifier){setStatus('Model is not ready yet.');return;}setStatus('Analyzing…');try{const out=await classifier(text.slice(0,5000));const raw=out[0];const isPositive=raw.label.toUpperCase().includes('POS');const confidence=raw.score;const scores={positive:isPositive?confidence:0,negative:isPositive?0:confidence,neutral:Math.max(0,1-confidence)};if(scores.neutral<.15)scores.neutral=0;const label=isPositive?'Positive':'Negative';showResults(text,label,scores,confidence);setStatus('Analysis complete.');}catch(e){setStatus('Analysis error: '+e.message);}}
|
| 103 |
+
textInput.addEventListener('input',updateCounter);
|
| 104 |
+
document.getElementById('analyzeBtn').addEventListener('click',analyze);
|
| 105 |
+
document.getElementById('clearBtn').addEventListener('click',()=>{textInput.value='';updateCounter();document.getElementById('results').classList.add('hidden');setStatus(classifier?'Model ready. Enter text and click Analyze.':'Loading model…');});
|
| 106 |
+
document.querySelectorAll('.example').forEach(btn=>btn.addEventListener('click',()=>{textInput.value=btn.dataset.text;updateCounter();}));
|
| 107 |
+
document.getElementById('historyClearBtn').addEventListener('click',()=>{history=[];localStorage.removeItem('sentimentHistory');renderHistory();});
|
| 108 |
+
document.getElementById('batchAnalyzeBtn').addEventListener('click',async()=>{
|
| 109 |
+
const lines=document.getElementById('batchInput').value.split(/\\r?\\n/).map(x=>x.trim()).filter(Boolean);
|
| 110 |
+
const out=document.getElementById('batchResults');
|
| 111 |
+
if(!lines.length){out.innerHTML='<p class="muted">Enter one or more lines first.</p>';return;}
|
| 112 |
+
if(!classifier){out.innerHTML='<p class="muted">Model is still loading.</p>';return;}
|
| 113 |
+
out.textContent='Analyzing '+lines.length+' item(s)…';
|
| 114 |
+
const records=[];
|
| 115 |
+
for(const text of lines.slice(0,100)){
|
| 116 |
+
try{
|
| 117 |
+
const pred=(await classifier(text.slice(0,5000)))[0],positive=pred.label.toUpperCase().includes('POS'),confidence=pred.score;
|
| 118 |
+
const scores={positive:positive?confidence:0,negative:positive?0:confidence,neutral:Math.max(0,1-confidence)};
|
| 119 |
+
if(scores.neutral<.15)scores.neutral=0;
|
| 120 |
+
records.push({text,label:positive?'Positive':'Negative',positive:scores.positive,neutral:scores.neutral,negative:scores.negative,confidence,time:new Date().toLocaleString()});
|
| 121 |
+
}catch(err){records.push({text,label:'Error',positive:0,neutral:0,negative:0,confidence:0,time:new Date().toLocaleString(),error:err.message});}
|
| 122 |
+
}
|
| 123 |
+
history.unshift(...records.filter(r=>r.label!=='Error'));
|
| 124 |
+
history=history.slice(0,100);localStorage.setItem('sentimentHistory',JSON.stringify(history));renderHistory();
|
| 125 |
+
window.lastBatchRecords=records;out.innerHTML=records.map(r=>'<div class="history-item"><strong>'+escapeHtml(r.label)+'</strong><p>'+escapeHtml(r.text)+'</p><small>Positive '+pct(r.positive)+' · Neutral '+pct(r.neutral)+' · Negative '+pct(r.negative)+'</small></div>').join('');
|
| 126 |
+
});
|
| 127 |
+
document.getElementById('batchExportBtn').addEventListener('click',()=>{const rows=window.lastBatchRecords||[];if(!rows.length){setStatus('Run batch analysis first.');return;}const csv=[['text','label','positive','neutral','negative','confidence','time'],...rows.map(x=>[x.text,x.label,x.positive,x.neutral,x.negative,x.confidence,x.time])].map(r=>r.map(v=>'"'+String(v??'').replace(/"/g,'""')+'"').join(',')).join('\\n');download('batch_results.csv',csv,'text/csv');});
|
| 128 |
+
document.getElementById('historySearch').addEventListener('input',renderHistory);
|
| 129 |
+
document.getElementById('historyFilter').addEventListener('change',renderHistory);
|
| 130 |
+
const savedTheme=localStorage.getItem('sentimentTheme')||'dark';if(savedTheme==='light')document.body.classList.add('light');
|
| 131 |
+
document.getElementById('themeBtn').addEventListener('click',()=>{document.body.classList.toggle('light');localStorage.setItem('sentimentTheme',document.body.classList.contains('light')?'light':'dark');drawTrend();});
|
| 132 |
+
function download(filename,content,type){const blob=new Blob([content],{type}),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download=filename;a.click();URL.revokeObjectURL(url);}
|
| 133 |
+
document.getElementById('exportJsonBtn').addEventListener('click',()=>download('sentiment_history.json',JSON.stringify(history,null,2),'application/json'));
|
| 134 |
+
document.getElementById('exportCsvBtn').addEventListener('click',()=>{const rows=[['time','label','text','positive','neutral','negative','confidence'],...history.map(x=>[x.time,x.label,x.text,x.positive,x.neutral,x.negative,x.confidence])];const csv=rows.map(r=>r.map(v=>'"'+String(v??'').replace(/"/g,'""')+'"').join(',')).join('\n');download('sentiment_history.csv',csv,'text/csv');});
|
| 135 |
+
renderHistory();
|
| 136 |
+
loadModel();
|
| 137 |
+
updateCounter();
|
| 138 |
+
</script>
|
| 139 |
+
</body>
|
| 140 |
+
</html>
|