Your script for analyzing emotions in YouTube comments using DistilBERT within a FastAPI application is well-structured and covers the essential functionalities required for fetching comments, processing them, and returning the analysis results. However, considering your constraints—limited computational resources on a non-M1/M2 MacBook and the intention to implement Retrieval-Augmented Generation (RAG)—there are several areas where optimizations and adjustments can enhance performance, accuracy, and resource efficiency.
1. Clarifying RAG Usage
Issue:
You mentioned wanting to use RAG (Retrieval-Augmented Generation) alongside DistilBERT. However, the current script solely utilizes DistilBERT for emotion classification without integrating any retrieval or generation mechanisms characteristic of RAG.
Recommendation:
If RAG is a part of your intended architecture, you'd typically incorporate a retrieval component that fetches relevant documents or information to augment the generation or classification process. For your use case—emotion classification of YouTube comments—RAG might be unnecessary unless you plan to generate contextual responses or further enrich the analysis with external data.
Action Steps:
- Evaluate Necessity: Determine if RAG truly adds value to your emotion classification task. If not, focusing solely on optimizing DistilBERT might be more efficient.
- Implement RAG (If Needed): Should you proceed with RAG, consider integrating retrieval from a pre-defined corpus relevant to YouTube comments or emotions to enhance classification accuracy or provide richer context.
2. Model Selection and Optimization
Issue:
Using distilbert-base-uncased-finetuned-sst-2-english is suitable for binary sentiment analysis (positive/negative). If your goal is to perform more nuanced emotion classification (e.g., happy, sad, angry), this model might be insufficient.
Recommendation:
- Choose an Appropriate Model: Select a model fine-tuned for multi-class emotion classification. Models like
nateraw/bert-base-uncased-emotion or other emotion-specific transformers are better suited.
- Consider Further Distillation or Quantization: To reduce computational load, explore further distilling the model or applying quantization techniques to make it lighter and faster without significantly compromising accuracy.
Action Steps:
# Example: Using an emotion-specific model
from transformers import AutoModelForSequenceClassification, AutoTokenizer
class EmotionAnalyzer:
def __init__(self, model_name='nateraw/bert-base-uncased-emotion', device=None):
...
self.model = AutoModelForSequenceClassification.from_pretrained(model_name)
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
...
def map_label_to_emotion(self, label):
# Update based on the specific model's label mapping
emotion_map = {
0: "Sadness",
1: "Joy",
2: "Love",
3: "Anger",
4: "Fear",
5: "Surprise"
}
return emotion_map.get(label, "Unknown")
3. Enhancing Performance with Batch Processing
Issue:
Processing each comment individually can be inefficient, especially with a large number of comments, leading to longer response times and higher CPU usage.
Recommendation:
Implement batch processing to handle multiple comments simultaneously. Batching leverages parallelism and reduces the overhead associated with multiple forward passes through the model.
Action Steps:
from typing import List
class EmotionAnalyzer:
...
def analyze_emotions_batch(self, texts: List[str]):
"""Analyze emotions for a batch of texts using DistilBERT."""
logger.info(f"Analyzing emotions for a batch of {len(texts)} texts.")
inputs = self.tokenizer(texts, return_tensors="pt", truncation=True, max_length=512, padding=True)
inputs = {k: v.to(self.device) for k, v in inputs.items()}
with torch.no_grad():
outputs = self.model(**inputs)
logits = outputs.logits
predicted_labels = torch.argmax(logits, dim=1).tolist()
emotions = [self.map_label_to_emotion(label) for label in predicted_labels]
logger.info(f"Extracted emotions for the batch.")
return emotions, ["Analysis complete."] * len(texts)
Adjust the Endpoint:
@app.post("/analyze_emotion/", summary="Analyze emotions in YouTube video comments")
async def analyze_emotion(request: EmotionRequest):
...
emotions, generated_texts = emotion_analyzer.analyze_emotions_batch(comments_filtered)
for comment, emotion, generated_text in zip(comments_filtered, emotions, generated_texts):
results.append({
"comment": comment,
"emotion": emotion,
"generated_text": generated_text
})
...
4. Limiting the Number of Comments to Analyze
Issue:
Fetching and processing a very large number of comments can strain limited resources, leading to slow responses or even system crashes.
Recommendation:
Introduce a configurable limit on the number of comments to analyze per request. This prevents overloading your system and ensures consistent performance.
Action Steps:
class EmotionRequest(BaseModel):
video_id: str
max_comments: int = 100 # Default to 100, configurable by the user
@app.post("/analyze_emotion/", summary="Analyze emotions in YouTube video comments")
async def analyze_emotion(request: EmotionRequest):
...
comments = get_video_comments(request.video_id, max_comments=request.max_comments)
...
Modify get_video_comments:
def get_video_comments(video_id, max_comments=100):
...
while 'nextPageToken' in response and len(comments) < max_comments:
...
# Adjust the loop to break when max_comments is reached
for item in response.get('items', []):
if len(comments) >= max_comments:
break
comment = item['snippet']['topLevelComment']['snippet']['textDisplay']
comments.append(comment)
...
5. Improving URL Detection
Issue:
The contains_url function uses a regex pattern that might not cover all edge cases or could be too broad/narrow, affecting accuracy in detecting URLs.
Recommendation:
Leverage more robust URL detection methods or libraries to ensure accurate identification of URLs within comments.
Action Steps:
6. Handling YouTube API Quotas and Errors
Issue:
The script currently logs HTTP errors but returns a 404 status when no comments are found, which might not accurately reflect the nature of the error (e.g., network issues vs. genuinely no comments).
Recommendation:
Differentiate between errors fetching comments and genuinely having no comments. Return appropriate HTTP status codes and messages based on the error type.
Action Steps:
from fastapi.responses import JSONResponse
@app.post("/analyze_emotion/", summary="Analyze emotions in YouTube video comments")
async def analyze_emotion(request: EmotionRequest):
...
try:
comments = get_video_comments(request.video_id, max_comments=request.max_comments)
except HttpError as e:
logger.error(f"YouTube API error: {e}")
raise HTTPException(status_code=e.resp.status, detail=f"YouTube API error: {e.content}")
except Exception as e:
logger.error(f"Unexpected error: {e}")
raise HTTPException(status_code=500, detail="Internal Server Error")
if not comments:
logger.warning(f"No comments found for video_id: {request.video_id}")
raise HTTPException(status_code=404, detail="No comments found for this video ID.")
...
7. Reducing Response Payload Size
Issue:
Returning a large number of comments with their associated emotions can result in a hefty response payload, potentially leading to longer transmission times and higher memory usage.
Recommendation:
- Paginate Responses: Implement pagination to return results in manageable chunks.
- Allow Clients to Specify Fields: Let clients choose which fields they need to reduce unnecessary data transfer.
Action Steps:
- Implement Pagination:
class EmotionRequest(BaseModel):
video_id: str
max_comments: int = 100
page: int = 1
page_size: int = 20
@app.post("/analyze_emotion/", summary="Analyze emotions in YouTube video comments")
async def analyze_emotion(request: EmotionRequest):
...
start = (request.page - 1) * request.page_size
end = start + request.page_size
paginated_comments = comments[start:end]
...
return {
"page": request.page,
"page_size": request.page_size,
"total_comments": len(comments),
"results": results
}
8. Leveraging Asynchronous Processing
Issue:
While FastAPI supports asynchronous endpoints, the current implementation uses synchronous calls for fetching comments and processing emotions, which can block the event loop and degrade performance.
Recommendation:
- Use Asynchronous I/O: Make YouTube API calls asynchronously to improve throughput.
- Leverage Background Tasks: For intensive processing tasks, consider using background workers to handle emotion analysis without blocking the main thread.
Action Steps:
-
Use httpx for Asynchronous HTTP Requests:
import httpx
async def get_youtube_service_async():
"""Asynchronously build and return the YouTube service object."""
# Note: Google API client library may not support async directly
# Consider using httpx or aiohttp to interact with YouTube API endpoints asynchronously
pass # Implementation would require a different approach
Note: The googleapiclient library does not natively support asynchronous operations. You might need to switch to an async-compatible library or handle async calls in a different manner, possibly using threads or processes.
-
Use Background Tasks for Emotion Analysis:
from fastapi import BackgroundTasks
@app.post("/analyze_emotion/", summary="Analyze emotions in YouTube video comments")
async def analyze_emotion(request: EmotionRequest, background_tasks: BackgroundTasks):
...
background_tasks.add_task(process_emotions, comments)
return {"message": "Emotion analysis in progress."}
def process_emotions(comments):
# Perform the emotion analysis here
pass
Caution: Proper synchronization and state management are required to handle background tasks effectively.
9. Refactoring for Improved Maintainability
Issue:
As the application grows, maintaining a monolithic script can become cumbersome, making debugging and enhancements more challenging.
Recommendation:
- Modularize the Code: Split the script into separate modules for configurations, models, utilities, and API routes.
- Use Dependency Injection: Leverage FastAPI's dependency injection to manage shared resources like the
EmotionAnalyzer instance.
Action Steps:
-
Structure the Project:
project/
├── main.py
├── config.py
├── models/
│ └── emotion_analyzer.py
├── utils/
│ ├── youtube_api.py
│ └── text_processing.py
└── requirements.txt
-
Example emotion_analyzer.py:
import logging
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
logger = logging.getLogger(__name__)
class EmotionAnalyzer:
def __init__(self, model_name='nateraw/bert-base-uncased-emotion', device=None):
...
def analyze_emotions_batch(self, texts: List[str]):
...
def map_label_to_emotion(self, label):
...
-
Inject Dependencies in main.py:
from fastapi import FastAPI, Depends
from models.emotion_analyzer import EmotionAnalyzer
app = FastAPI(...)
def get_emotion_analyzer():
return EmotionAnalyzer()
@app.post("/analyze_emotion/", ...)
async def analyze_emotion(request: EmotionRequest, analyzer: EmotionAnalyzer = Depends(get_emotion_analyzer)):
...
10. Additional Best Practices
-
Environment Variables for Configuration: Instead of config.py, consider using environment variables for sensitive information like API keys. Libraries like python-dotenv can help manage this.
-
Error Reporting to Clients: Provide meaningful error messages and distinguish between different error types to aid clients in troubleshooting.
-
Testing and Validation: Implement unit and integration tests to ensure each component works as expected, especially when handling edge cases like videos with no comments or malformed data.
Final Adjusted Script Example
Here's a revised version of your script incorporating some of the recommendations:
import logging
import re
from typing import List
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import validators
import os
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Configuration
YOUTUBE_API_KEY = os.getenv('YOUTUBE_API_KEY') # Ensure you set this environment variable
# Define a FastAPI application
app = FastAPI(
title="YouTube Video Emotion Analyzer",
description="Analyze emotions in YouTube video comments using DistilBERT.",
version="1.0.0"
)
# Define a Pydantic model for input data
class EmotionRequest(BaseModel):
video_id: str # Accepts the video ID from the request body
max_comments: int = 100
page: int = 1
page_size: int = 20
class EmotionAnalyzer:
def __init__(self, model_name='nateraw/bert-base-uncased-emotion', device=None):
logger.info(f"Initializing EmotionAnalyzer with model: {model_name}")
# Set device
if device:
self.device = device
else:
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
logger.info(f"Using device: {self.device}")
# Load the model and tokenizer
try:
logger.info("Loading Emotion model...")
self.model = AutoModelForSequenceClassification.from_pretrained(model_name)
self.model.to(self.device)
logger.info("Model loaded successfully.")
except Exception as e:
logger.error(f"Error loading model: {e}")
raise
try:
logger.info("Loading tokenizer...")
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
logger.info("Tokenizer loaded successfully.")
except Exception as e:
logger.error(f"Error loading tokenizer: {e}")
raise
def analyze_emotions_batch(self, texts: List[str]):
"""Analyze emotions for a batch of texts using the Emotion model."""
logger.info(f"Analyzing emotions for a batch of {len(texts)} texts.")
inputs = self.tokenizer(texts, return_tensors="pt", truncation=True, max_length=512, padding=True)
inputs = {k: v.to(self.device) for k, v in inputs.items()}
with torch.no_grad():
outputs = self.model(**inputs)
logits = outputs.logits
predicted_labels = torch.argmax(logits, dim=1).tolist()
emotions = [self.map_label_to_emotion(label) for label in predicted_labels]
logger.info(f"Extracted emotions for the batch.")
return emotions, ["Analysis complete."] * len(texts)
def map_label_to_emotion(self, label):
"""Map model output label to emotion string."""
emotion_map = {
0: "Sadness",
1: "Joy",
2: "Love",
3: "Anger",
4: "Fear",
5: "Surprise"
}
return emotion_map.get(label, "Unknown")
# Dependency Injection for EmotionAnalyzer
def get_emotion_analyzer():
return EmotionAnalyzer()
# YouTube API setup
def get_youtube_service():
"""Build and return the YouTube service object."""
return build('youtube', 'v3', developerKey=YOUTUBE_API_KEY)
def get_video_comments(video_id, max_comments=100):
"""Fetch comments from a YouTube video using the video_id."""
youtube = get_youtube_service()
comments = []
try:
logger.info(f"Fetching comments for video_id: {video_id}")
response = youtube.commentThreads().list(
part='snippet',
videoId=video_id,
textFormat='plainText',
maxResults=100
).execute()
# Process the response to extract comments
for item in response.get('items', []):
comment = item['snippet']['topLevelComment']['snippet']['textDisplay']
comments.append(comment)
if len(comments) >= max_comments:
break
# Handle pagination if more comments are available
while 'nextPageToken' in response and len(comments) < max_comments:
logger.info("Fetching next page of comments...")
response = youtube.commentThreads().list(
part='snippet',
videoId=video_id,
textFormat='plainText',
maxResults=100,
pageToken=response['nextPageToken']
).execute()
for item in response.get('items', []):
comment = item['snippet']['topLevelComment']['snippet']['textDisplay']
comments.append(comment)
if len(comments) >= max_comments:
break
except HttpError as e:
logger.error(f"HTTP error fetching comments: {e}")
raise
except Exception as e:
logger.error(f"Unexpected error fetching comments: {e}")
raise
logger.info(f"Total comments fetched: {len(comments)}")
return comments
# Helper function to detect URLs in text
def contains_url(text):
"""Check if the text contains any URL using validators."""
words = text.split()
for word in words:
if validators.url(word):
return True
return False
@app.post("/analyze_emotion/", summary="Analyze emotions in YouTube video comments")
async def analyze_emotion(request: EmotionRequest, analyzer: EmotionAnalyzer = Depends(get_emotion_analyzer)):
"""
Analyze emotions for comments from a YouTube video.
- **video_id**: The ID of the YouTube video to analyze
- **max_comments**: Maximum number of comments to analyze (default: 100)
- **page**: Page number for pagination (default: 1)
- **page_size**: Number of comments per page (default: 20)
"""
logger.info(f"Received request to analyze video_id: {request.video_id}")
try:
comments = get_video_comments(request.video_id, max_comments=request.max_comments)
except HttpError as e:
logger.error(f"YouTube API error: {e}")
raise HTTPException(status_code=e.resp.status, detail="Error fetching comments from YouTube API.")
except Exception as e:
logger.error(f"Unexpected error: {e}")
raise HTTPException(status_code=500, detail="Internal Server Error.")
if not comments:
logger.warning(f"No comments found for video_id: {request.video_id}")
raise HTTPException(status_code=404, detail="No comments found for this video ID.")
# Implement pagination
start = (request.page - 1) * request.page_size
end = start + request.page_size
paginated_comments = comments[start:end]
results = []
texts_to_analyze = []
indices = []
# First pass: Identify comments without URLs
for idx, comment in enumerate(paginated_comments):
if contains_url(comment):
results.append({
"comment": comment,
"emotion": "Neutral",
"generated_text": "Comment contains a link; marked as Neutral."
})
else:
texts_to_analyze.append(comment)
indices.append(idx)
# Analyze emotions in batch
if texts_to_analyze:
emotions, generated_texts = analyzer.analyze_emotions_batch(texts_to_analyze)
for i, emotion in enumerate(emotions):
results.append({
"comment": texts_to_analyze[i],
"emotion": emotion,
"generated_text": generated_texts[i]
})
return {
"page": request.page,
"page_size": request.page_size,
"total_comments": len(comments),
"results": results
}
Final Thoughts
Your initial script lays a solid foundation for the intended functionality. By implementing the above recommendations, you can enhance the application's performance, ensure scalability, and better manage resource constraints inherent to non-M1/M2 MacBooks. Additionally, refining model selection and processing logic will lead to more accurate and meaningful emotion analysis of YouTube comments.
Ensure you thoroughly test each component, especially when handling large volumes of data or integrating new models. Monitoring performance and iterating based on observed bottlenecks will further optimize the application's efficiency and reliability.