VAYULearn
Colour theme
Investigate a failure
VAYU Learn

Kafka & Streaming

Real-Time YouTube Sentiment Analysis with Kafka,TextBlob,BERT & Azure (Live Dashboard)

💡This end-to-end project performs real-time sentiment analysis on YouTube video comments and live-stream chats using TextBlob, BERT, and…

Kafka & StreamingDatabricks & Lakehouse

💡This end-to-end project performs real-time sentiment analysis on YouTube video comments and live-stream chats using TextBlob, BERT, and Azure Cognitive Services — powered by Kafka streaming and a live Streamlit dashboard.

⚡ Subtopics Covered

💡 This project walks through every moving piece of a real-time ML + streaming system.

  • Architecture overview (Kafka + YouTube API + BERT + Azure + Streamlit)
  • How the pipeline works end-to-end
  • Kafka setup (Aiven, SSL-secured)
  • YouTube Video & Live Chat ingestion
  • Three sentiment engines (TextBlob, BERT, Azure NLP)
  • Real-time dashboard (Streamlit)
  • Producer + Analyzer + Visualizer flows
  • Latency breakdown: API, inference, Kafka lag
  • Scaling + deployment notes
  • Best practices & production considerations
  • Full code walkthrough (Python)
  • Conclusion + What’s next

🧾 TL;DR — The Project in 60 Seconds

You input a YouTube video or live-stream URL → the system fetches live comments → sends them to SSL-secured Kafka topics → analyzes sentiment using TextBlob, BERT, or Azure Cognitive Services → streams results live into a Streamlit dashboard with:
- sentiment distribution
- real-time pie charts
- word cloud
- comment counts
- switchable sentiment engines
This is a complete real-time data + ML + streaming dashboard — production-ready and cloud-friendly.

📐 1. Architecture Diagram

The following diagram shows how comments flow from YouTube into Kafka, through sentiment engines, and finally into a live Streamlit dashboard.

Image 1 - Architecture Block Diagram

Above image shows End-to-end architecture combining YouTube API ingestion, Kafka streaming, sentiment engines (TextBlob, BERT, Azure), and a real-time Streamlit dashboard


🚀 2. Introduction — Why This Project Matters

YouTube generates millions of comments per minute.
For content creators, brands, and monitoring teams, real-time sentiment is gold:

  • Track audience mood
  • Trigger alerts during live events
  • Detect toxicity or spam
  • Analyze viewer engagement
  • Evaluate reactions to product launches

This project lets you do real-time sentiment analysis using three engines:

✔ TextBlob — Fast & lightweight

✔ Multilingual BERT — Highly accurate deep learning model

✔ Azure Text Analytics — Enterprise-grade NLP API

Combined with Kafka’s streaming backbone and Streamlit’s reactive UI, this becomes a fully real-time system.

📺 Video & Live Stream Support — Real-Time on Both Sources

This system doesn’t just analyze comments from standard uploaded YouTube videos — it also supports real-time analysis of live-stream chat messages.

Thanks to YouTube’s liveStreamingDetails and activeLiveChatId APIs, the pipeline automatically detects whether the provided URL is:

  • A normal YouTube video (historical or recent), or
  • An active live-stream (chat messages updating every few seconds)

…and seamlessly switches into the correct ingestion mode.

This makes the project ideal for:

  • Live event monitoring
  • Product launch sentiment
  • Gaming/eSports streams
  • News broadcasts
  • Webinars and conference streams
  • Creator–audience engagement dashboards

🧑‍💻 Author Note

This project was originally built as my Major Project during university, where I focused on designing real-time data pipelines using Kafka, BERT, and cloud NLP services. I’ve since enhanced and productionized it with better architecture, SSL-secured Kafka, and multi-model sentiment engines.

🛠️ 3. Technologies Used

The following table summarizes the core components used in the YouTube Sentiment Analysis pipeline and their roles in the system:

Table 1 — Key components of the Real-Time YouTube Sentiment Analysis pipeline and their functional roles

🧩 4. Unified Architecture — How It Works

  1. YouTube URL input
    → extract video ID
    → detect if it’s a video or a live stream
  2. Fetcher thread
    → Pulls comments
    → Sends raw comment text into Kafka
    → Passes each comment to sentiment engine
  3. Sentiment engines (user selectable):
  • TextBlob → polarity-based
  • BERT → transformer inference
  • Azure → cloud-based API

4. Streamlit visualizer
→ Pie chart updates
→ Word cloud updates
→ Comment counter increments
→ Engine switch updates pipeline instantly

5. Kafka topics for downstream processing:

  • youtube-video-comments
  • youtube-live-comments

This makes the system extendable for Spark, Flink, or ML pipelines.


🧪 5. Latency Breakdown

Real-time streaming requires understanding latency sources.

✔ 1. YouTube API Latency

  • Comments (videos): 0.2–0.5s
  • Live chat: 1–5s refresh window
  • Rate limited at ~10,000 units/day

✔ 2. Kafka Publish Latency

  • Aiven Kafka with SSL
  • Typical producer send time: 5–20 ms
  • Flush adds extra ~10–40 ms

✔ 3. Sentiment Engine Latency

TextBlob: ~2–4 ms per comment
BERT CPU: ~100–250 ms
BERT GPU: ~10–30 ms
Azure API: 80–200 ms round-trip

✔ 4. Streamlit UI Latency

  • UI refresh: ~1 second
  • Wordcloud generation: ~300–500 ms
  • Pie chart generation: ~100–200 ms

✔ Total End-to-End Lag

Video comments: 1–2 seconds
Live chat: 3–7 seconds

This is real-time enough for behavior monitoring, moderation, dashboards, and alerts.


🛠️ 6. Setup Instructions

6.1 Prerequisites

  • Python 3.8+
  • YouTube Data API key
  • Aiven Kafka with SSL
  • Azure Text Analytics credentials
  • GPU (optional for BERT speed)

6.2 Environment Variables

Create .env:

YOUTUBE_API_KEY=your_key
AZURE_KEY=your_azure_key
AZURE_ENDPOINT=https://your-resource.cognitiveservices.azure.com/
KAFKA_BOOTSTRAP_SERVERS=your_aiven_bootstrap
AIVEN_CA_PATH=/path/to/ca.pem
AIVEN_CERT_PATH=/path/to/service.cert
AIVEN_KEY_PATH=/path/to/service.key

6.3 Dependencies

pip install -r requirements.txt

Requirements.txt

streamlit==1.35.0
python-dotenv==1.0.1
kafka-python==2.0.2
google-api-python-client==2.121.0
textblob==0.17.1
transformers==4.40.1
torch==2.3.0
azure-ai-textanalytics==5.3.0
azure-core==1.30.1
matplotlib==3.8.4
wordcloud==1.9.3
nltk==3.8.1

⚙️ 7. Full Project Code (Cleaned & Optimized)

import os
import streamlit as st
from kafka import KafkaProducer
from googleapiclient.discovery import build
from textblob import TextBlob
from transformers import BertTokenizer, BertForSequenceClassification
import torch
from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential
import threading
import time
import re
import matplotlib.pyplot as plt
from collections import defaultdict
from wordcloud import WordCloud
from kafka.errors import KafkaError
from googleapiclient.errors import HttpError
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# YouTube Data API
YOUTUBE_API_KEY = os.getenv("YOUTUBE_API_KEY")
youtube = build('youtube', 'v3', developerKey=YOUTUBE_API_KEY)

# Sentiment counts
sentiment_counts = defaultdict(int)
comments_processed = 0
all_comments_text = []

# Load BERT model
tokenizer = BertTokenizer.from_pretrained('nlptown/bert-base-multilingual-uncased-sentiment')
model = BertForSequenceClassification.from_pretrained('nlptown/bert-base-multilingual-uncased-sentiment')

# Azure Setup
azure_key = os.getenv("AZURE_KEY")
azure_endpoint = os.getenv("AZURE_ENDPOINT")

def authenticate_client():
ta_credential = AzureKeyCredential(azure_key)
return TextAnalyticsClient(endpoint=azure_endpoint, credential=ta_credential)

client = authenticate_client()

# Kafka Producer (Aiven)
producer = None

def create_kafka_producer():
global producer
try:
producer = KafkaProducer(
bootstrap_servers=os.getenv("KAFKA_BOOTSTRAP_SERVERS"),
security_protocol='SSL',
ssl_cafile=os.getenv("AIVEN_CA_PATH"),
ssl_certfile=os.getenv("AIVEN_CERT_PATH"),
ssl_keyfile=os.getenv("AIVEN_KEY_PATH")
)
except KafkaError as e:
st.error(f"Kafka producer creation failed: {e}")

# Sentiment Analysis
def analyze_sentiment_textblob(comment):
blob = TextBlob(comment)
return blob.sentiment.polarity

def analyze_sentiment_bert(comment):
inputs = tokenizer(comment, return_tensors='pt', truncation=True, padding=True)
outputs = model(**inputs)
logits = outputs.logits
sentiment_score = torch.softmax(logits, dim=1).tolist()[0]
return sentiment_score

def analyze_sentiment_azure(comment):
try:
response = client.analyze_sentiment(documents=[comment])[0]
return response.sentiment.capitalize()
except Exception as e:
print(f"Azure API Error: {e}")
return 'Neutral'

def categorize_sentiment_textblob(score):
if score > 0.1:
return 'Positive'
elif score < -0.1:
return 'Negative'
else:
return 'Neutral'

def categorize_sentiment_bert(score):
positive, neutral, negative = score[4], score[2], score[0]
if positive > max(neutral, negative):
return 'Positive'
elif negative > max(positive, neutral):
return 'Negative'
else:
return 'Neutral'

def save_sentiment_to_db(sentiment_category):
sentiment_counts[sentiment_category] += 1

def generate_pie_chart(sentiment_counts, chart_container):
labels = list(sentiment_counts.keys())
sizes = list(sentiment_counts.values())

if sum(sizes) == 0:
chart_container.write("No sentiment data available.")
return

fig, ax = plt.subplots(figsize=(6, 4))
ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140)
ax.axis('equal')
chart_container.pyplot(fig)

def generate_word_cloud(all_comments_text, cloud_container):
if not all_comments_text:
cloud_container.write("No comments data available.")
return

text = ' '.join(all_comments_text)
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)

fig, ax = plt.subplots(figsize=(10, 6))
ax.imshow(wordcloud, interpolation='bilinear')
ax.axis('off')
cloud_container.pyplot(fig)

def fetch_video_comments_and_analyze(video_id, analysis_method):
global comments_processed, all_comments_text
request = youtube.commentThreads().list(
videoId=video_id,
part='snippet',
maxResults=100
)

while request is not None:
try:
response = request.execute()
for item in response.get('items', []):
comment = item['snippet']['topLevelComment']['snippet']['textDisplay']
all_comments_text.append(comment)
comments_processed += 1

sentiment_score, sentiment_category = analyze_comment(comment, analysis_method)

if producer is None:
create_kafka_producer()

producer.send('youtube-video-comments', value=comment.encode('utf-8'))
producer.flush()

save_sentiment_to_db(sentiment_category)

request = youtube.commentThreads().list_next(request, response)

except HttpError as e:
if e.resp.status == 403 and 'commentsDisabled' in str(e):
st.error("Comments are disabled for this video.")
else:
st.error(f"Error fetching comments: {e}")
break

def get_live_chat_id(video_id):
try:
response = youtube.videos().list(
part='liveStreamingDetails',
id=video_id
).execute()

if 'items' in response and len(response['items']) > 0:
live_stream_details = response['items'][0].get('liveStreamingDetails', None)
if live_stream_details and 'activeLiveChatId' in live_stream_details:
return live_stream_details['activeLiveChatId']
except Exception as e:
st.error(f"Error fetching live chat ID: {e}")
return None

def fetch_live_chat_comments_and_analyze(live_chat_id, analysis_method):
global comments_processed, all_comments_text
request = youtube.liveChatMessages().list(
liveChatId=live_chat_id,
part='snippet,authorDetails',
maxResults=200
)

while True:
try:
response = request.execute()
for item in response.get('items', []):
if 'displayMessage' in item['snippet']:
comment = item['snippet']['displayMessage']
all_comments_text.append(comment)
comments_processed += 1

sentiment_score, sentiment_category = analyze_comment(comment, analysis_method)

if producer is None:
create_kafka_producer()

producer.send('youtube-live-comments', value=comment.encode('utf-8'))
producer.flush()

save_sentiment_to_db(sentiment_category)

time.sleep(5)

except HttpError as e:
if e.resp.status == 403:
st.error("Live chat is disabled for this stream.")
else:
st.error(f"An error occurred: {e}")
break
except Exception as e:
print(f"Error fetching live chat comments: {e}")
time.sleep(5)

def analyze_comment(comment, analysis_method):
sentiment_score = None
sentiment_category = None

if analysis_method == "TextBlob":
sentiment_score = analyze_sentiment_textblob(comment)
sentiment_category = categorize_sentiment_textblob(sentiment_score)
elif analysis_method == "BERT":
sentiment_score = analyze_sentiment_bert(comment)
sentiment_category = categorize_sentiment_bert(sentiment_score)
elif analysis_method == "Azure":
sentiment_category = analyze_sentiment_azure(comment)

return sentiment_score, sentiment_category

def extract_video_id(url):
match = re.search(r'v=([a-zA-Z0-9_-]+)', url)
return match.group(1) if match else None

def start_streamlit_dashboard():
st.title("YouTube Video/Live Stream Sentiment Analysis with Aiven Kafka")

video_url = st.text_input("Enter YouTube Video/Live Stream URL:", "")
analysis_method = st.selectbox("Choose Sentiment Analysis Method", ["TextBlob", "BERT", "Azure"])

chart_container = st.empty()
cloud_container = st.empty()
count_container = st.empty()

if video_url:
video_id = extract_video_id(video_url)
if video_id:
create_kafka_producer()
live_chat_id = get_live_chat_id(video_id)
if live_chat_id:
st.write(f"Analyzing live chat comments for live stream ID: {video_id} using {analysis_method}...")
threading.Thread(target=fetch_live_chat_comments_and_analyze, args=(live_chat_id, analysis_method), daemon=True).start()
else:
st.write(f"Analyzing video comments for ID: {video_id} using {analysis_method}...")
threading.Thread(target=fetch_video_comments_and_analyze, args=(video_id, analysis_method), daemon=True).start()

while True:
count_container.write(f"Comments Processed: {comments_processed}")
generate_pie_chart(sentiment_counts, chart_container)
generate_word_cloud(all_comments_text, cloud_container)
time.sleep(5)
else:
st.error("Invalid YouTube URL.")

if __name__ == "__main__":
start_streamlit_dashboard()

🗂️ GitHub Repository

For the complete project structure, updated code, SSL configuration examples, dashboard assets, and architecture diagram, visit the official project repository:

🔗 GitHub

This repository includes:

  • Full project source code
  • Streamlit app & UI assets
  • Architecture diagrams
  • requirements.txt
  • Detailed README with setup instructions

📊 8. Real-Time Dashboards (Streamlit)

8.1 TextBlob Dashboard View

The following image shows real-time sentiment analysis for both standard YouTube videos and live-stream chat messages using the TextBlob engine:

Image 2 : Streamlit Dashboard — TextBlob

Above image shows Side-by-side Streamlit dashboards showing TextBlob-based sentiment analysis for standard YouTube video comments (left) and real-time live-stream chat messages (right).

8.2 BERT Dashboard View

The following image demonstrates multilingual BERT-powered sentiment inference for both uploaded videos and live-stream chat messages:

Image 3: Streamlit Dashboard — BERT

Above image shows Streamlit dashboards using BERT (HuggingFace Transformers) for sentiment classification on standard YouTube video comments (left) and live-stream chat data (right).

8.3 Azure Cognitive Services Dashboard View

The following image shows Azure Text Analytics performing enterprise-grade sentiment scoring on both video comments and live chat streams:

Image 4: Streamlit Dashboard — Azure Cognitive Services

Above image shows Streamlit dashboards visualizing Azure Cognitive Services sentiment analysis for standard YouTube video comments (left) and live-stream chat messages (right).


📦 9. Kafka Topics

  • youtube-video-comments
  • youtube-live-comments

Topics are decoupled so teams can attach Spark or Flink jobs later.


🏗️ 10. Real-World Scaling Considerations

✔ API Limits

YouTube rate limits → implement exponential backoff.

✔ Model Scaling

  • Use GPU for BERT
  • Use batch inference for throughput

✔ Kafka Scaling

  • Add partitions for higher throughput
  • Enable idempotent producer
  • Configure linger.ms for batching

✔ Dashboard Scaling

Switch Streamlit → FastAPI + React for large-scale production.


🧭 11. Conclusion

This project demonstrates a state-of-the-art real-time sentiment analysis pipeline:

  • YouTube API for ingestion
  • Aiven Kafka for secure, scalable streaming
  • Three sentiment engines: TextBlob, BERT, Azure NLP
  • Streamlit for real-time visualization
  • SSL-secured producers
  • Real-time wordcloud + pie charts

You now have a flexible foundation for:

  • Moderation systems
  • Live social media monitoring
  • Trending analysis
  • Real-time alerts
  • Customer engagement tracking

This is a production-ready, extensible, cloud-native system with multiple ML paths.


🔥 Next in Series

“Project Walkthrough: Real-Time Traffic Analytics with Kafka, PostgreSQL, ARIMA & XGBoost”

A real-time traffic congestion → ML-based anomaly detection → streaming visuals project.


🔔 Follow for More

If you found this helpful, follow TheDataForge for your daily Spark, Databricks in Data Engineering ,Machine Learning and real-world data engineering content⚡

Let’s connect — I post daily Big Data & Spark insights at DataForgeX on X.
💬 Comment below:
Which sentiment engine are you planning to use first — TextBlob, BERT, or Azure Cognitive Services?


🏷️ Tags

#Kafka #AivenKafka #YouTubeAPI #SentimentAnalysis #BERT #AzureCognitiveServices #RealTimeStreaming #Streamlit #BigData #NLP #Transformers #MachineLearning #DataEngineering #RealTimeAnalytics #DataForge #YouTubeSentiment