Skip to content

Instantly share code, notes, and snippets.

@kheengz
Created January 15, 2025 21:57
Show Gist options
  • Save kheengz/e3851873458217fbefefb29c93a4ae2e to your computer and use it in GitHub Desktop.
Save kheengz/e3851873458217fbefefb29c93a4ae2e to your computer and use it in GitHub Desktop.
Here's an example of a real-time sentiment analysis tool for X posts, leveraging AI. This could be used to identify trends, moderate content, or enhance user engagement.
import express, { Request, Response } from 'express';
import { Pipeline, pipeline } from '@huggingface/hub';
import { Client } from 'twitter-api-sdk';
const app = express();
app.use(express.json());
// Set up Hugging Face sentiment analysis pipeline
const sentimentAnalyzer: Pipeline = pipeline('sentiment-analysis');
// Twitter API credentials (replace with your credentials)
const CONSUMER_KEY = "your_consumer_key";
const CONSUMER_SECRET = "your_consumer_secret";
const ACCESS_TOKEN = "your_access_token";
const ACCESS_SECRET = "your_access_secret";
// Set up Twitter API client
const twitterClient = new Client({
appKey: CONSUMER_KEY,
appSecret: CONSUMER_SECRET,
accessToken: ACCESS_TOKEN,
accessSecret: ACCESS_SECRET,
});
app.post('/analyze', async (req: Request, res: Response) => {
const { text } = req.body;
if (!text) {
return res.status(400).json({ error: 'No text provided' });
}
try {
const result = await sentimentAnalyzer(text);
res.json({ text, sentiment: result });
} catch (error) {
res.status(500).json({ error: 'Error analyzing sentiment' });
}
});
app.post('/stream', async (req: Request, res: Response) => {
const { keywords } = req.body;
if (!keywords || !Array.isArray(keywords)) {
return res.status(400).json({ error: 'No keywords provided or invalid format' });
}
try {
twitterClient.stream('tweets/search/stream', {
expansions: 'author_id',
query: keywords.join(' OR '),
}).then(stream => {
stream.on('data', (data: any) => {
const text = data.data.text;
sentimentAnalyzer(text).then(sentiment => {
console.log(`Tweet: ${text}\nSentiment: ${JSON.stringify(sentiment)}\n`);
});
});
stream.on('error', (error: any) => {
console.error('Stream error:', error);
});
});
res.json({ message: 'Streaming started for keywords', keywords });
} catch (error) {
res.status(500).json({ error: 'Error starting stream' });
}
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment