Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <p>
<label for="newTopic">Enter New Topic: 
	<input id="newTopic"></label> <button id="addTopic">Add Topic</button>
</p>

<div id="results">
</div>

<div id="status"></div>
              
            
!

CSS

              
                div#status {
	font-style: italic;
}

div.result {
	border-style:solid;
	border-width:thin;
	margin-bottom: 10px;
	padding: 10px;
}
              
            
!

JS

              
                import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.0.2';

let $status, $results, $newTopic;
let classifier, topics=[];
// interval for how often to check in miliseconds
const INTERVAL = 30000;

document.addEventListener('DOMContentLoaded', init, false);

async function init() {
	$status = document.querySelector('#status');
	$newTopic = document.querySelector('#newTopic');
	$results = document.querySelector('#results');
	
	document.querySelector('#addTopic').addEventListener('click', () => {
		let newTopic = $newTopic.value.trim().replaceAll('"','');
		if(newTopic !== '') topics.push(newTopic);
		$newTopic.value = '';
		
		if(topics.length === 1) checkTopics();
	});
	
	// warn user and load up transformers
	$status.innerHTML = 'Loading sentiment analyzer...';
	classifier = await pipeline('sentiment-analysis');
	$status.innerHTML = '';
	
}

async function checkTopics() {
	console.log('checkTopics');
	if(topics.length === 0) return;
	$status.innerHTML = 'Loading Bluesky data for topics.';
	let responses = [];
	topics.forEach(t => {
		responses.push(getSentiment(t));
	});
	console.log('fired off calls for each topic');
	let results = await Promise.all(responses);
	
	console.log('all done', results);
	$status.innerHTML = '';
	renderResults(results);
	setTimeout(checkTopics, INTERVAL);
}

async function getSentiment(topic) {
	console.log(`Get sentiment for ${topic}`);
	let sentimentTotal = 0;
	
	let req = await fetch(`https://public.api.bsky.app/xrpc/app.bsky.feed.searchPosts?q=${encodeURIComponent(topic)}&lang=en`);
	let data = (await req.json()).posts;
	console.log(`Posts found: ${data.length}`);
	for(let i=0; i<data.length; i++) {
		let sentiment = (await classifier(data[i].record.text))[0];
		//console.log(`Sentiment for ${data[i].record.text} is ${JSON.stringify(sentiment)}`); 
		if(sentiment.label === 'NEGATIVE') sentiment.score = -1 * sentiment.score;
		sentimentTotal += sentiment.score;
	}
	let avgSentiment = sentimentTotal / data.length;
	console.log(`Total sentiment, ${sentimentTotal}, avg ${avgSentiment}`);
	return { topic: topic, sentiment: avgSentiment, total:data.length,  generated: new Date() };
}

function renderResults(results) {
	
	/*
	It's possible a user clicks remove while we were loading 
	stuff, so we'll do a quick sanity check.
	*/
	results = results.filter(r => topics.includes(r.topic));
	
	let s = '';
	results.forEach(r => {
		
			s += `
			<div class="result" data-topic="${r.topic}">
<h2>Sentiment Analysis for: ${r.topic}</h2>
<p>
Average was <strong>${r.sentiment>0?'POSITIVE':'NEGATIVE'}</strong> (Average Score: ${r.sentiment} over ${r.total} items)<br>
Generated: ${dateFormat(r.generated)}
</p>
<p>
<button class="removeBtn" data-topic="${r.topic}">Remove from Analysis</button>
</p>
			</div>`;
	});

	$results.innerHTML = s;
	document.querySelectorAll('button.removeBtn').forEach(d => {
		d.addEventListener('click', removeItem);
	});
}

function dateFormat(d) {
	return new Intl.DateTimeFormat('en-US', { dateStyle:'medium', timeStyle:'long' }).format(d);
}

function removeItem(r) {
	let topic = r.target.dataset.topic;
	console.log('remove', topic);
	document.querySelector(`[data-topic="${topic}"]`).remove();
	console.log(topics);
	topics = topics.filter(t => t !== topic);
	console.log(topics);
}
              
            
!
999px

Console