Delete index.html
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Sentiment AI Analyzer</title><style>:root{color-scheme:light dark;--bg:#101827;--card:#1a2638;--text:#e9eef7;--muted:#9aa9bc;--accent:#6c9cff;--border:#34445b}*{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}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}textarea{width:100%;min-height:140px;padding:14px;border-radius:12px;border:1px solid var(--border);background:var(--bg);color:var(--text);font:inherit}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}.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}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@media print{body{background:white;color:black;padding:0}.card{background:white;color:black;border:1px solid #ccc;break-inside:avoid}button,input,textarea,.muted{display:none!important}main{max-width:100%}}</style></head><body><main><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><p>Analyze text sentiment with a three-class Hugging Face model directly in your browser.</p><div class="card"><label for="textInput"><strong>Enter text to analyze</strong></label><textarea id="textInput" placeholder="Type or paste your text here..."></textarea><p class="muted"><span id="wordCount">0</span> words · <span id="charCount">0</span> characters</p><div><button class="primary" id="analyzeBtn">🔍 Analyze Sentiment</button><button id="clearBtn">Clear text</button><button class="example" data-text="I absolutely love this product. It works wonderfully!">Positive example</button><button class="example" data-text="This was a terrible experience and I am very disappointed.">Negative example</button><button class="example" data-text="The service was okay, nothing special.">Neutral-ish example</button></div><div id="status" class="status">Loading sentiment model…</div></div><div id="results" class="card hidden"><h2>Analysis Result</h2><h3 id="resultLabel"></h3><div class="score"><strong>Positive: <span id="positiveText"></span></strong><div class="bar"><div class="fill" id="positiveBar"></div></div></div><div class="score"><strong>Neutral*: <span id="neutralText"></span></strong><div class="bar"><div class="fill" id="neutralBar"></div></div></div><div class="score"><strong>Negative: <span id="negativeText"></span></strong><div class="bar"><div class="fill" id="negativeBar"></div></div></div><p class="muted">Scores now come from a three-class model: Positive, Neutral and Negative.</p></div><div class="card" id="uploadCard"><h2>📄 Upload CSV Reviews</h2><p class="muted">Upload a CSV file containing a text column (column names such as text, review, comment, or message are detected automatically).</p><input id="csvUpload" type="file" accept=".csv,text/csv"><button id="csvAnalyzeBtn" class="primary">Analyze CSV</button><div id="csvResults"></div></div><div class="card" id="batchCard"><h2>📦 Batch Analysis</h2><p class="muted">Analyze multiple sentences at once. Enter one text per line.</p><textarea id="batchInput" placeholder="One text per line..." style="min-height:110px"></textarea><button id="batchAnalyzeBtn" class="primary">Analyze Batch</button><button id="batchExportBtn">Export batch results CSV</button><div id="batchResults"></div></div><div class="card" id="analyticsCard"><h2>📊 Analytics Dashboard</h2><button id="reportBtn">🖨️ Print / Save Report as PDF</button><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><div class="score"><strong>Positive proportion</strong><div class="bar"><div class="fill" id="analyticsPositive"></div></div></div><div class="score"><strong>Negative proportion</strong><div class="bar"><div class="fill" id="analyticsNegative"></div></div></div><div class="score"><strong>Neutral-ish proportion</strong><div class="bar"><div class="fill" id="analyticsNeutral"></div></div></div></div><div class="card"><h3>📅 Date-based statistics</h3><div id="dateStats"></div></div><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><div class="card"><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><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></div></main><script type="module">import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.7.2';
const textInput=document.getElementById('textInput');let history=JSON.parse(localStorage.getItem('sentimentHistory')||'[]');let classifier=null;
function updateCounter(){const t=textInput.value;document.getElementById('wordCount').textContent=t.trim()?t.trim().split(/\s+/).length:0;document.getElementById('charCount').textContent=t.length;}function setStatus(msg){document.getElementById('status').textContent=msg;}async function loadModel(){try{setStatus('Loading model (first run may take a while)…');classifier=await pipeline('sentiment-analysis','Xenova/twitter-roberta-base-sentiment-latest');setStatus('Model ready. Enter text and click Analyze.');}catch(e){setStatus('Model loading failed: '+e.message);}}function renderAnalytics(){ 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); document.getElementById('totalAnalyses').textContent=total; document.getElementById('positiveCount').textContent=pos; document.getElementById('negativeCount').textContent=neg; document.getElementById('neutralCount').textContent=neu; document.getElementById('analyticsPositive').style.width=(total?pos/total*100:0)+'%'; document.getElementById('analyticsNegative').style.width=(total?neg/total*100:0)+'%'; document.getElementById('analyticsNeutral').style.width=(total?neu/total*100:0)+'%'; drawTrend();}function drawTrend(){ const canvas=document.getElementById('trendCanvas');if(!canvas)return; const ctx=canvas.getContext('2d'),w=canvas.width,h=canvas.height; ctx.clearRect(0,0,w,h);ctx.strokeStyle=getComputedStyle(document.body).getPropertyValue('--border');ctx.lineWidth=1; for(let i=1;i<4;i++){ctx.beginPath();ctx.moveTo(0,h*i/4);ctx.lineTo(w,h*i/4);ctx.stroke();} if(!history.length){ctx.fillStyle=getComputedStyle(document.body).getPropertyValue('--muted');ctx.fillText('No history yet',20,30);return;} const chronological=[...history].reverse().slice(-50); ctx.strokeStyle=getComputedStyle(document.body).getPropertyValue('--accent');ctx.lineWidth=3;ctx.beginPath(); 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();}function renderHistory(){ const el=document.getElementById('historyList');if(!history.length){el.innerHTML='<p class="muted">No analyses yet.</p>';renderAnalytics();return;} const q=(document.getElementById('historySearch')?.value||'').toLowerCase(),f=document.getElementById('historyFilter')?.value||'all'; const shown=history.filter(item=>(f==='all'||item.label===f)&&String(item.text).toLowerCase().includes(q)); 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();}function escapeHtml(s){return String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));}function pct(v){return (Number(v||0)*100).toFixed(1)+'%';}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)+'%';}history.unshift({text,label,positive:scores.positive,neutral:scores.neutral,negative:scores.negative,confidence,time:new Date().toLocaleString()});history=history.slice(0,100);localStorage.setItem('sentimentHistory',JSON.stringify(history));renderHistory();}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),{top_k:null});const items=Array.isArray(out[0])?out[0]:out;const findScore=(patterns)=>{const item=items.find(x=>patterns.some(p=>String(x.label).toUpperCase().includes(p)));return item?Number(item.score):0;};const scores={negative:findScore(['NEG']),neutral:findScore(['NEU']),positive:findScore(['POS'])};const label=Object.entries(scores).sort((a,b)=>b[1]-a[1])[0][0];const confidence=scores[label];showResults(text,label.charAt(0).toUpperCase()+label.slice(1),scores,confidence);setStatus('Analysis complete.');}catch(e){setStatus('Analysis error: '+e.message);}}textInput.addEventListener('input',updateCounter);document.getElementById('analyzeBtn').addEventListener('click',analyze);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…');});document.querySelectorAll('.example').forEach(btn=>btn.addEventListener('click',()=>{textInput.value=btn.dataset.text;updateCounter();}));document.getElementById('historyClearBtn').addEventListener('click',()=>{history=[];localStorage.removeItem('sentimentHistory');renderHistory();});document.getElementById('batchAnalyzeBtn').addEventListener('click',async()=>{ const lines=document.getElementById('batchInput').value.split(/\\r?\\n/).map(x=>x.trim()).filter(Boolean); const out=document.getElementById('batchResults'); if(!lines.length){out.innerHTML='<p class="muted">Enter one or more lines first.</p>';return;} if(!classifier){out.innerHTML='<p class="muted">Model is still loading.</p>';return;} out.textContent='Analyzing '+lines.length+' item(s)…'; const records=[]; for(const text of lines.slice(0,100)){ try{ const pred=await classifier(text.slice(0,5000),{top_k:null});const items=Array.isArray(pred[0])?pred[0]:pred; const findScore=(patterns)=>{const item=items.find(x=>patterns.some(p=>String(x.label).toUpperCase().includes(p)));return item?Number(item.score):0;}; const scores={negative:findScore(['NEG']),neutral:findScore(['NEU']),positive:findScore(['POS'])}; const label=Object.entries(scores).sort((a,b)=>b[1]-a[1])[0][0],confidence=scores[label]; records.push({text,label:label.charAt(0).toUpperCase()+label.slice(1),positive:scores.positive,neutral:scores.neutral,negative:scores.negative,confidence,time:new Date().toLocaleString()}); }catch(err){records.push({text,label:'Error',positive:0,neutral:0,negative:0,confidence:0,time:new Date().toLocaleString(),error:err.message});} } history.unshift(...records.filter(r=>r.label!=='Error')); history=history.slice(0,100);localStorage.setItem('sentimentHistory',JSON.stringify(history));renderHistory(); 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('');});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');});document.getElementById('historySearch').addEventListener('input',renderHistory);document.getElementById('historyFilter').addEventListener('change',renderHistory);const savedTheme=localStorage.getItem('sentimentTheme')||'dark';if(savedTheme==='light')document.body.classList.add('light');document.getElementById('themeBtn').addEventListener('click',()=>{document.body.classList.toggle('light');localStorage.setItem('sentimentTheme',document.body.classList.contains('light')?'light':'dark');drawTrend();});document.getElementById('reportBtn').addEventListener('click',()=>window.print());document.getElementById('csvAnalyzeBtn').addEventListener('click',async()=>{ const file=document.getElementById('csvUpload').files[0],out=document.getElementById('csvResults'); if(!file){out.innerHTML='<p>Please choose a CSV file.</p>';return;} if(!classifier){out.innerHTML='<p>Model is still loading.</p>';return;} out.textContent='Reading CSV…'; const raw=await file.text(),rows=raw.split(/\\r?\\n/).filter(x=>x.trim()); if(rows.length<2){out.textContent='CSV appears empty.';return;} const parseLine=line=>line.split(',').map(v=>v.trim().replace(/^"|"$/g,'')); const header=parseLine(rows[0]).map(x=>x.toLowerCase()); let idx=header.findIndex(x=>['text','review','comment','message','content','sentence'].includes(x)); if(idx<0)idx=0; const texts=rows.slice(1).map(line=>parseLine(line)[idx]).filter(Boolean).slice(0,100); const records=[]; for(const text of texts){ try{const pred=await classifier(text.slice(0,5000),{top_k:null}),items=Array.isArray(pred[0])?pred[0]:pred; const findScore=patterns=>{const item=items.find(x=>patterns.some(p=>String(x.label).toUpperCase().includes(p)));return item?Number(item.score):0;}; const scores={negative:findScore(['NEG']),neutral:findScore(['NEU']),positive:findScore(['POS'])}; const label=Object.entries(scores).sort((a,b)=>b[1]-a[1])[0][0],confidence=scores[label]; records.push({text,label:label.charAt(0).toUpperCase()+label.slice(1),positive:scores.positive,neutral:scores.neutral,negative:scores.negative,confidence,time:new Date().toLocaleString()}); }catch(e){records.push({text,label:'Error',positive:0,neutral:0,negative:0,confidence:0,time:new Date().toLocaleString()});} } window.lastBatchRecords=records;history.unshift(...records.filter(r=>r.label!=='Error'));history=history.slice(0,100);localStorage.setItem('sentimentHistory',JSON.stringify(history));renderHistory(); out.innerHTML='<p>Processed '+records.length+' rows (maximum 100 rows per upload).</p>'+records.map(r=>'<div class="history-item"><strong>'+escapeHtml(r.label)+'</strong><p>'+escapeHtml(r.text)+'</p></div>').join('');});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);}document.getElementById('exportJsonBtn').addEventListener('click',()=>download('sentiment_history.json',JSON.stringify(history,null,2),'application/json'));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');});renderHistory();loadModel();updateCounter();</script></body></html>index.htmlDeleted-175