researchlens / app.js
Hugdrigo's picture
Upload 5 files
e03836d verified
Raw History Blame Contribute Delete
3.95 kB
const $ = (id)=>document.getElementById(id);
const examples={
es:'La inteligencia artificial generativa está transformando la investigación académica, la educación superior y el análisis empresarial. Las universidades exploran nuevas formas de integrar herramientas de IA en la escritura, la búsqueda bibliográfica y la evaluación. Al mismo tiempo, las organizaciones deben establecer políticas claras sobre transparencia, privacidad, calidad de datos y uso responsable. Este escenario exige combinar competencias técnicas con criterio metodológico y conocimiento del contexto institucional.',
en:'International trade and regional integration are increasingly shaped by digital infrastructure, data governance and automation. Firms operating across Latin America need tools that can turn complex documents into actionable insights while preserving methodological transparency. Applied NLP can support decision-making by surfacing recurring concepts, summarizing long texts and identifying thematic signals.',
pt:'A transformação digital está mudando a gestão, a educação e a pesquisa. Ferramentas de análise de texto podem apoiar organizações e universidades ao identificar temas, palavras-chave e padrões de linguagem em documentos extensos. A adoção responsável exige atenção à privacidade, à qualidade dos dados e às limitações metodológicas dos sistemas automatizados.'
};
function escapeHtml(s){return s.replace(/[&<>'"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[c]));}
function renderBars(items){ if(!items.length)return '<div class="muted">No strong topic signals detected.</div>'; const max=Math.max(...items.map(x=>x.score||x.frequency)); return items.map(x=>{const val=x.score??x.frequency; const label=x.topic??x.term; return `<div class="barrow"><span>${escapeHtml(label)}</span><div class="bar"><i style="width:${Math.max(4,val/max*100)}%"></i></div><b>${val}</b></div>`}).join(''); }
function render(result){
$('metrics').innerHTML=[['Language',result.language],['Words',result.words.toLocaleString()],['Sentences',result.sentences],['Paragraphs',result.paragraphs],['Reading time',`${result.readingTime} min`],['Avg. sentence',`${result.avgSentence} words`],['Lexical diversity',result.lexicalDiversity]].map(([a,b])=>`<div class="metric"><span>${a}</span><strong>${b}</strong></div>`).join('');
$('summary').textContent=result.summary;
$('keywords').innerHTML=renderBars(result.keywords.slice(0,12));
$('topics').innerHTML=renderBars(result.topics.slice(0,8));
$('results').hidden=false;
}
async function readFile(file){
if(!file)return '';
if(/\.(txt|md)$/i.test(file.name)) return await file.text();
if(/\.pdf$/i.test(file.name)){
if(!window.pdfjsLib) throw new Error('PDF parser could not load. Paste the text instead or retry with internet access.');
const buf=await file.arrayBuffer(); const pdf=await pdfjsLib.getDocument({data:buf}).promise; let text='';
for(let i=1;i<=pdf.numPages;i++){const p=await pdf.getPage(i); const c=await p.getTextContent(); text+=c.items.map(x=>x.str).join(' ')+'\n\n';}
if(!text.trim()) throw new Error('No extractable text found. Scanned PDFs require OCR.');
return text;
}
throw new Error('Supported files: PDF, TXT and Markdown.');
}
$('analyze').addEventListener('click',async()=>{
try{$('status').textContent='Analyzing…'; let text=$('text').value; const f=$('file').files[0]; if(f) text=await readFile(f); const result=ResearchLensEngine.analyzeText(text); render(result); $('status').textContent='Analysis complete. All NLP ran locally in your browser.';}catch(e){$('status').textContent=e.message;}
});
document.querySelectorAll('[data-example]').forEach(b=>b.addEventListener('click',()=>{$('text').value=examples[b.dataset.example];}));
$('clear').addEventListener('click',()=>{$('text').value='';$('file').value='';$('results').hidden=true;$('status').textContent='Ready.';});