Spaces:
Paused
Paused
cal commited on
Commit Β·
7ffa586
1
Parent(s): 8f3ad14
update error
Browse files- src/streamlit_app.py +133 -69
src/streamlit_app.py
CHANGED
|
@@ -5,84 +5,107 @@ import pandas as pd
|
|
| 5 |
import plotly.express as px
|
| 6 |
from googleapiclient.discovery import build
|
| 7 |
from transformers import pipeline
|
| 8 |
-
from typing import Union
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
#
|
|
|
|
| 12 |
os.environ['STREAMLIT_SERVER_BROWSER_CACHE_PATH'] = '/tmp/.streamlit_browser_cache'
|
| 13 |
os.environ['STREAMLIT_SERVER_LIB_CACHE_PATH'] = '/tmp/.streamlit_lib_cache'
|
| 14 |
os.environ['STREAMLIT_SERVER_STATIC_CACHE_PATH'] = '/tmp/.streamlit_static_cache'
|
| 15 |
-
|
| 16 |
os.environ['MPLCONFIGDIR'] = '/tmp/.config/matplotlib'
|
| 17 |
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
|
|
|
| 20 |
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
|
| 21 |
|
| 22 |
-
#
|
| 23 |
st.set_page_config(
|
| 24 |
layout="wide",
|
| 25 |
page_title="YouTube Comment Sentiment Analyzer",
|
| 26 |
-
page_icon="https://upload.wikimedia.org/wikipedia/commons/4/47/Google_pixel_logo.svg"
|
| 27 |
)
|
| 28 |
|
| 29 |
-
# ---
|
| 30 |
st.sidebar.subheader("Environment Variables (for debugging):")
|
| 31 |
st.sidebar.write(f"HF_HOME: {os.environ.get('HF_HOME')}")
|
| 32 |
st.sidebar.write(f"TRANSFORMERS_CACHE: {os.environ.get('TRANSFORMERS_CACHE')}")
|
| 33 |
-
st.sidebar.write(f"HF_HUB_CACHE: {os.environ.get('HUGGINGFACE_HUB_CACHE')}")
|
| 34 |
st.sidebar.write(f"YOUTUBE_API_KEY present: {bool(os.environ.get('YOUTUBE_API_KEY'))}")
|
| 35 |
-
# --- End debugger
|
| 36 |
|
|
|
|
| 37 |
YOUTUBE_URL_REGEX = re.compile(
|
| 38 |
r"(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^\"&?\/\s]{11})"
|
| 39 |
)
|
| 40 |
|
| 41 |
def get_video_id(youtube_url: str) -> Union[str, None]:
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
match = YOUTUBE_URL_REGEX.search(youtube_url)
|
| 44 |
return match.group(1) if match else None
|
| 45 |
|
| 46 |
def fetch_comments(video_id: str, api_key: str, max_comments: int = 500) -> list[str]:
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
try:
|
| 49 |
-
# YouTube API service client
|
| 50 |
youtube = build("youtube", "v3", developerKey=api_key)
|
| 51 |
comments = []
|
| 52 |
next_page_token = None
|
| 53 |
fetched_count = 0
|
| 54 |
|
| 55 |
-
|
| 56 |
while fetched_count < max_comments:
|
| 57 |
-
|
| 58 |
request = youtube.commentThreads().list(
|
| 59 |
-
part="snippet",
|
| 60 |
-
videoId=video_id,
|
| 61 |
-
maxResults=100,
|
| 62 |
-
pageToken=next_page_token,
|
| 63 |
-
textFormat="plainText"
|
| 64 |
)
|
| 65 |
-
response = request.execute()
|
| 66 |
|
| 67 |
-
# comment
|
| 68 |
for item in response.get("items", []):
|
| 69 |
-
|
| 70 |
comment_text = item["snippet"]["topLevelComment"]["snippet"]["textDisplay"]
|
| 71 |
comments.append(comment_text)
|
| 72 |
fetched_count += 1
|
| 73 |
if fetched_count >= max_comments:
|
| 74 |
-
break
|
| 75 |
|
| 76 |
-
|
| 77 |
next_page_token = response.get("nextPageToken")
|
| 78 |
if not next_page_token:
|
| 79 |
-
break
|
| 80 |
|
| 81 |
return comments
|
| 82 |
|
| 83 |
except Exception as e:
|
| 84 |
-
#
|
| 85 |
print(f"Error fetching comments: {e}")
|
|
|
|
| 86 |
st.error(f"An error occurred while fetching comments: {e}")
|
| 87 |
if "disabled comments" in str(e).lower():
|
| 88 |
st.info("Comments might be disabled for this video, or it's a Live Chat replay.")
|
|
@@ -90,81 +113,120 @@ def fetch_comments(video_id: str, api_key: str, max_comments: int = 500) -> list
|
|
| 90 |
st.info("You might have hit your YouTube Data API daily quota.")
|
| 91 |
return []
|
| 92 |
|
| 93 |
-
# Sentiment
|
|
|
|
| 94 |
SENTIMENT_MODEL_NAME = "distilbert-base-uncased-finetuned-sst-2-english"
|
| 95 |
|
| 96 |
# Using the explicitly set environment for my cache directory.
|
| 97 |
-
#
|
| 98 |
HF_CACHE_DIR = os.environ.get('HUGGINGFACE_HUB_CACHE', '/tmp/huggingface_models_cache')
|
| 99 |
|
| 100 |
-
|
| 101 |
@st.cache_resource
|
| 102 |
def load_sentiment_model():
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
| 104 |
try:
|
|
|
|
| 105 |
sentiment_pipeline = pipeline(
|
| 106 |
-
"sentiment-analysis",
|
| 107 |
-
model=SENTIMENT_MODEL_NAME,
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
#
|
|
|
|
| 111 |
)
|
| 112 |
return sentiment_pipeline
|
| 113 |
except Exception as e:
|
|
|
|
| 114 |
st.error(f"Error loading sentiment model: {e}")
|
|
|
|
| 115 |
st.info(f"Please ensure the model '{SENTIMENT_MODEL_NAME}' is available and compatible.")
|
| 116 |
-
st.info(f"The model was attempted to be cached to: {HF_CACHE_DIR}.")
|
| 117 |
-
st.info("If the issue persists,
|
|
|
|
|
|
|
|
|
|
| 118 |
st.stop() # Stop the Streamlit app execution gracefully if the model can't load
|
| 119 |
|
| 120 |
def analyze_sentiments(comments: list[str], sentiment_pipeline) -> pd.DataFrame:
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
if not comments:
|
| 123 |
-
return pd.DataFrame()
|
| 124 |
|
| 125 |
comment_data = []
|
| 126 |
for comment_text in comments:
|
|
|
|
| 127 |
if not comment_text.strip():
|
| 128 |
-
continue
|
| 129 |
|
| 130 |
sentiment_results = sentiment_pipeline(comment_text)
|
| 131 |
|
|
|
|
| 132 |
if sentiment_results and sentiment_results[0]:
|
|
|
|
|
|
|
| 133 |
main_sentiment = sentiment_results[0][0]['label']
|
| 134 |
score = sentiment_results[0][0]['score']
|
| 135 |
|
| 136 |
comment_data.append({
|
| 137 |
"Comment": comment_text,
|
| 138 |
"Sentiment": main_sentiment,
|
| 139 |
-
"Score": round(score, 4)
|
| 140 |
})
|
| 141 |
-
|
| 142 |
return pd.DataFrame(comment_data)
|
| 143 |
|
| 144 |
def plot_sentiment_distribution(sentiment_df: pd.DataFrame):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
if sentiment_df.empty:
|
| 146 |
st.warning("No sentiment data to plot distribution.")
|
| 147 |
return
|
|
|
|
|
|
|
| 148 |
sentiment_counts = sentiment_df['Sentiment'].value_counts().reset_index()
|
| 149 |
sentiment_counts.columns = ['Sentiment', 'Count']
|
| 150 |
-
|
| 151 |
-
|
|
|
|
| 152 |
fig = px.bar(
|
| 153 |
sentiment_counts,
|
| 154 |
x='Sentiment',
|
| 155 |
y='Count',
|
| 156 |
title='Distribution of Comment Sentiments',
|
| 157 |
-
color='Sentiment',
|
| 158 |
-
color_discrete_map=color_map,
|
| 159 |
-
text='Count'
|
| 160 |
)
|
| 161 |
-
|
|
|
|
| 162 |
fig.update_traces(texttemplate='%{text}', textposition='outside')
|
| 163 |
fig.update_layout(xaxis_title="Sentiment", yaxis_title="Number of Comments")
|
| 164 |
|
| 165 |
st.plotly_chart(fig, use_container_width=True)
|
| 166 |
|
| 167 |
def display_sentiment_scores(sentiment_df: pd.DataFrame):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
if sentiment_df.empty:
|
| 169 |
st.info("No comments available to display individual sentiment scores.")
|
| 170 |
return
|
|
@@ -173,35 +235,37 @@ def display_sentiment_scores(sentiment_df: pd.DataFrame):
|
|
| 173 |
st.dataframe(sentiment_df, use_container_width=True)
|
| 174 |
|
| 175 |
|
| 176 |
-
#
|
| 177 |
YOUTUBE_API_KEY = os.environ.get("YOUTUBE_API_KEY")
|
| 178 |
|
| 179 |
st.title("π₯ (Phoenix) YouTube Comment Sentiment Checker")
|
| 180 |
-
st.markdown("
|
| 181 |
|
|
|
|
| 182 |
if not YOUTUBE_API_KEY:
|
| 183 |
-
st.warning("π¨ **YouTube API Key not found!** Please add `YOUTUBE_API_KEY` to your Hugging Face Space secrets.")
|
| 184 |
-
st.info("Instructions
|
| 185 |
-
st.stop()
|
| 186 |
-
|
| 187 |
|
|
|
|
| 188 |
with st.spinner("π Loading sentiment model... This might take a moment if it's the first run (downloading model)."):
|
| 189 |
-
sentiment_classifier = load_sentiment_model()
|
| 190 |
|
|
|
|
| 191 |
youtube_url = st.text_input(
|
| 192 |
"π Enter YouTube Video URL:",
|
| 193 |
-
"https://www.youtube.com/watch?v=dQw4w9WgXcQ",
|
| 194 |
help="e.g., https://www.youtube.com/watch?v=dQw4w9WgXcQ"
|
| 195 |
)
|
| 196 |
|
| 197 |
-
|
| 198 |
max_comments = st.slider(
|
| 199 |
"π Max Comments to Fetch (approx.):",
|
| 200 |
min_value=50, max_value=2000, value=500, step=50,
|
| 201 |
help="Fetching more comments takes longer and uses more API quota."
|
| 202 |
)
|
| 203 |
|
| 204 |
-
#
|
| 205 |
if st.button("β¨ Analyze Comments", type="primary"):
|
| 206 |
if not youtube_url:
|
| 207 |
st.error("β Please enter a YouTube video URL to analyze.")
|
|
@@ -211,8 +275,8 @@ if st.button("β¨ Analyze Comments", type="primary"):
|
|
| 211 |
st.error("β Invalid YouTube URL. Please make sure it's a valid video URL (e.g., starts with youtube.com/watch?v= or youtu.be/).")
|
| 212 |
else:
|
| 213 |
st.info(f"Fetching comments for video ID: `{video_id}`")
|
| 214 |
-
|
| 215 |
-
#
|
| 216 |
with st.spinner(f"π₯ Fetching up to {max_comments} comments from YouTube..."):
|
| 217 |
comments = fetch_comments(video_id, YOUTUBE_API_KEY, max_comments)
|
| 218 |
|
|
@@ -221,30 +285,30 @@ if st.button("β¨ Analyze Comments", type="primary"):
|
|
| 221 |
else:
|
| 222 |
st.success(f"β
Successfully fetched {len(comments)} comments.")
|
| 223 |
|
| 224 |
-
#
|
| 225 |
with st.spinner("π§ Analyzing sentiment of comments..."):
|
| 226 |
sentiment_df = analyze_sentiments(comments, sentiment_classifier)
|
| 227 |
|
| 228 |
if sentiment_df.empty:
|
| 229 |
st.info("No comments were successfully analyzed for sentiment.")
|
| 230 |
else:
|
| 231 |
-
#
|
| 232 |
st.subheader("π Sentiment Analysis Results:")
|
| 233 |
|
| 234 |
-
# Display summary
|
| 235 |
total_analyzed = len(sentiment_df)
|
| 236 |
positive_count = sentiment_df[sentiment_df['Sentiment'] == 'POSITIVE'].shape[0]
|
| 237 |
negative_count = sentiment_df[sentiment_df['Sentiment'] == 'NEGATIVE'].shape[0]
|
| 238 |
-
|
| 239 |
st.write(f"**Total comments analyzed:** `{total_analyzed}`")
|
| 240 |
st.write(f"**Positive sentiments:** `{positive_count}` ({(positive_count/total_analyzed*100):.1f}%)")
|
| 241 |
st.write(f"**Negative sentiments:** `{negative_count}` ({(negative_count/total_analyzed*100):.1f}%)")
|
| 242 |
-
|
| 243 |
-
#
|
| 244 |
plot_sentiment_distribution(sentiment_df)
|
| 245 |
|
| 246 |
-
#
|
| 247 |
display_sentiment_scores(sentiment_df)
|
| 248 |
|
| 249 |
st.markdown("---")
|
| 250 |
-
st.markdown("This is a Build Up project developed last night with β€οΈ as an example of a modular addition to support the reporting of TFGBV platforms in Kenya .")
|
|
|
|
| 5 |
import plotly.express as px
|
| 6 |
from googleapiclient.discovery import build
|
| 7 |
from transformers import pipeline
|
| 8 |
+
from typing import Union
|
| 9 |
|
| 10 |
+
# Set environment variables for cache directories
|
| 11 |
+
# This helps manage where Streamlit and Hugging Face cache files are stored,
|
| 12 |
+
# especially useful in environments like Hugging Face Spaces.
|
| 13 |
os.environ['STREAMLIT_SERVER_BROWSER_CACHE_PATH'] = '/tmp/.streamlit_browser_cache'
|
| 14 |
os.environ['STREAMLIT_SERVER_LIB_CACHE_PATH'] = '/tmp/.streamlit_lib_cache'
|
| 15 |
os.environ['STREAMLIT_SERVER_STATIC_CACHE_PATH'] = '/tmp/.streamlit_static_cache'
|
|
|
|
| 16 |
os.environ['MPLCONFIGDIR'] = '/tmp/.config/matplotlib'
|
| 17 |
|
| 18 |
+
# IMPORTANT: Changing this cache directory name (e.g., to _v5, _v6)
|
| 19 |
+
# will force Hugging Face to re-download all models, effectively clearing
|
| 20 |
+
# any potentially corrupted cached models.
|
| 21 |
+
# Incrementing to _v6 to ensure a completely fresh start for the cache.
|
| 22 |
+
os.environ['HUGGINGFACE_HUB_CACHE'] = '/tmp/huggingface_models_cache_v6'
|
| 23 |
|
| 24 |
+
# Suppress TensorFlow OneDNN optimization warnings if TensorFlow is installed
|
| 25 |
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
|
| 26 |
|
| 27 |
+
# Configure Streamlit page settings
|
| 28 |
st.set_page_config(
|
| 29 |
layout="wide",
|
| 30 |
page_title="YouTube Comment Sentiment Analyzer",
|
| 31 |
+
page_icon="https://upload.wikimedia.org/wikipedia/commons/4/47/Google_pixel_logo.svg"
|
| 32 |
)
|
| 33 |
|
| 34 |
+
# --- Debugger visualization (for environment variables) ---
|
| 35 |
st.sidebar.subheader("Environment Variables (for debugging):")
|
| 36 |
st.sidebar.write(f"HF_HOME: {os.environ.get('HF_HOME')}")
|
| 37 |
st.sidebar.write(f"TRANSFORMERS_CACHE: {os.environ.get('TRANSFORMERS_CACHE')}")
|
| 38 |
+
st.sidebar.write(f"HF_HUB_CACHE: {os.environ.get('HUGGINGFACE_HUB_CACHE')}")
|
| 39 |
st.sidebar.write(f"YOUTUBE_API_KEY present: {bool(os.environ.get('YOUTUBE_API_KEY'))}")
|
| 40 |
+
# --- End debugger ---
|
| 41 |
|
| 42 |
+
# Regex to extract YouTube video ID from various URL formats
|
| 43 |
YOUTUBE_URL_REGEX = re.compile(
|
| 44 |
r"(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^\"&?\/\s]{11})"
|
| 45 |
)
|
| 46 |
|
| 47 |
def get_video_id(youtube_url: str) -> Union[str, None]:
|
| 48 |
+
"""
|
| 49 |
+
Extracts the YouTube video ID from a given URL.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
youtube_url (str): The URL of the YouTube video.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
Union[str, None]: The 11-character video ID if found, otherwise None.
|
| 56 |
+
"""
|
| 57 |
match = YOUTUBE_URL_REGEX.search(youtube_url)
|
| 58 |
return match.group(1) if match else None
|
| 59 |
|
| 60 |
def fetch_comments(video_id: str, api_key: str, max_comments: int = 500) -> list[str]:
|
| 61 |
+
"""
|
| 62 |
+
Fetches comments for a given YouTube video ID using the YouTube Data API.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
video_id (str): The ID of the YouTube video.
|
| 66 |
+
api_key (str): Your Google/YouTube Data API key.
|
| 67 |
+
max_comments (int): The maximum number of comments to fetch.
|
| 68 |
+
|
| 69 |
+
Returns:
|
| 70 |
+
list[str]: A list of fetched comment texts.
|
| 71 |
+
"""
|
| 72 |
try:
|
| 73 |
+
# Initialize YouTube API service client
|
| 74 |
youtube = build("youtube", "v3", developerKey=api_key)
|
| 75 |
comments = []
|
| 76 |
next_page_token = None
|
| 77 |
fetched_count = 0
|
| 78 |
|
| 79 |
+
# Loop to fetch comments page by page until max_comments is reached or no more pages
|
| 80 |
while fetched_count < max_comments:
|
|
|
|
| 81 |
request = youtube.commentThreads().list(
|
| 82 |
+
part="snippet",
|
| 83 |
+
videoId=video_id,
|
| 84 |
+
maxResults=100, # Max results per page allowed by API
|
| 85 |
+
pageToken=next_page_token,
|
| 86 |
+
textFormat="plainText"
|
| 87 |
)
|
| 88 |
+
response = request.execute()
|
| 89 |
|
| 90 |
+
# Extract comment text from the response
|
| 91 |
for item in response.get("items", []):
|
|
|
|
| 92 |
comment_text = item["snippet"]["topLevelComment"]["snippet"]["textDisplay"]
|
| 93 |
comments.append(comment_text)
|
| 94 |
fetched_count += 1
|
| 95 |
if fetched_count >= max_comments:
|
| 96 |
+
break
|
| 97 |
|
| 98 |
+
# Get token for the next page of comments
|
| 99 |
next_page_token = response.get("nextPageToken")
|
| 100 |
if not next_page_token:
|
| 101 |
+
break # No more pages
|
| 102 |
|
| 103 |
return comments
|
| 104 |
|
| 105 |
except Exception as e:
|
| 106 |
+
# Log the error for debugging in the console/logs
|
| 107 |
print(f"Error fetching comments: {e}")
|
| 108 |
+
# Display user-friendly error messages in Streamlit
|
| 109 |
st.error(f"An error occurred while fetching comments: {e}")
|
| 110 |
if "disabled comments" in str(e).lower():
|
| 111 |
st.info("Comments might be disabled for this video, or it's a Live Chat replay.")
|
|
|
|
| 113 |
st.info("You might have hit your YouTube Data API daily quota.")
|
| 114 |
return []
|
| 115 |
|
| 116 |
+
# Sentiment analysis model name. This is the standard DistilBERT SST-2 finetuned model.
|
| 117 |
+
# If you intended to use the 'tiny' version, change this to "sshleifer/tiny-distilbert-base-uncased-finetuned-sst-2-english"
|
| 118 |
SENTIMENT_MODEL_NAME = "distilbert-base-uncased-finetuned-sst-2-english"
|
| 119 |
|
| 120 |
# Using the explicitly set environment for my cache directory.
|
| 121 |
+
# In case of errors, fallback to a default /tmp path.
|
| 122 |
HF_CACHE_DIR = os.environ.get('HUGGINGFACE_HUB_CACHE', '/tmp/huggingface_models_cache')
|
| 123 |
|
|
|
|
| 124 |
@st.cache_resource
|
| 125 |
def load_sentiment_model():
|
| 126 |
+
"""
|
| 127 |
+
Loads the sentiment analysis model using the Hugging Face transformers pipeline.
|
| 128 |
+
This function is cached by Streamlit to avoid re-loading the model on every rerun.
|
| 129 |
+
"""
|
| 130 |
try:
|
| 131 |
+
# Initialize the sentiment analysis pipeline
|
| 132 |
sentiment_pipeline = pipeline(
|
| 133 |
+
"sentiment-analysis",
|
| 134 |
+
model=SENTIMENT_MODEL_NAME,
|
| 135 |
+
tokenizer=SENTIMENT_MODEL_NAME,
|
| 136 |
+
top_k=None, # Get scores for all labels (POSITIVE, NEGATIVE)
|
| 137 |
+
# The HUGGINGFACE_HUB_CACHE environment variable is automatically respected by pipeline
|
| 138 |
+
# Removed force_download and local_files_only to simplify and rely on cache path change.
|
| 139 |
)
|
| 140 |
return sentiment_pipeline
|
| 141 |
except Exception as e:
|
| 142 |
+
# Provide detailed error messages to the user
|
| 143 |
st.error(f"Error loading sentiment model: {e}")
|
| 144 |
+
st.info(f"The app attempted to load model: '{SENTIMENT_MODEL_NAME}'.")
|
| 145 |
st.info(f"Please ensure the model '{SENTIMENT_MODEL_NAME}' is available and compatible.")
|
| 146 |
+
st.info(f"The model was attempted to be cached to: `{HF_CACHE_DIR}`.")
|
| 147 |
+
st.info("If the issue persists, consider these steps:")
|
| 148 |
+
st.info("1. **Check your internet connection** to ensure a stable download.")
|
| 149 |
+
st.info(f"2. **Force a fresh download** by changing the `HUGGINGFACE_HUB_CACHE` env var in your Space settings or directly in the `streamlit_app.py` file (e.g., to `/tmp/huggingface_models_cache_v7`).")
|
| 150 |
+
st.info("3. **Verify model availability** on Hugging Face Hub: `https://huggingface.co/{SENTIMENT_MODEL_NAME}`.")
|
| 151 |
st.stop() # Stop the Streamlit app execution gracefully if the model can't load
|
| 152 |
|
| 153 |
def analyze_sentiments(comments: list[str], sentiment_pipeline) -> pd.DataFrame:
|
| 154 |
+
"""
|
| 155 |
+
Analyzes the sentiment of a list of comments using the provided sentiment pipeline.
|
| 156 |
+
|
| 157 |
+
Args:
|
| 158 |
+
comments (list[str]): A list of comment texts.
|
| 159 |
+
sentiment_pipeline: The loaded Hugging Face sentiment analysis pipeline.
|
| 160 |
+
|
| 161 |
+
Returns:
|
| 162 |
+
pd.DataFrame: A DataFrame containing comments, their predicted sentiment, and score.
|
| 163 |
+
"""
|
| 164 |
if not comments:
|
| 165 |
+
return pd.DataFrame()
|
| 166 |
|
| 167 |
comment_data = []
|
| 168 |
for comment_text in comments:
|
| 169 |
+
# Skip empty or whitespace-only comments
|
| 170 |
if not comment_text.strip():
|
| 171 |
+
continue
|
| 172 |
|
| 173 |
sentiment_results = sentiment_pipeline(comment_text)
|
| 174 |
|
| 175 |
+
# Extract the main sentiment (POSITIVE/NEGATIVE) and its score
|
| 176 |
if sentiment_results and sentiment_results[0]:
|
| 177 |
+
# The model returns a list of dictionaries, usually sorted by score.
|
| 178 |
+
# We take the first one as the most confident prediction.
|
| 179 |
main_sentiment = sentiment_results[0][0]['label']
|
| 180 |
score = sentiment_results[0][0]['score']
|
| 181 |
|
| 182 |
comment_data.append({
|
| 183 |
"Comment": comment_text,
|
| 184 |
"Sentiment": main_sentiment,
|
| 185 |
+
"Score": round(score, 4)
|
| 186 |
})
|
| 187 |
+
|
| 188 |
return pd.DataFrame(comment_data)
|
| 189 |
|
| 190 |
def plot_sentiment_distribution(sentiment_df: pd.DataFrame):
|
| 191 |
+
"""
|
| 192 |
+
Plots the distribution of sentiments using a bar chart.
|
| 193 |
+
|
| 194 |
+
Args:
|
| 195 |
+
sentiment_df (pd.DataFrame): DataFrame containing sentiment analysis results.
|
| 196 |
+
"""
|
| 197 |
if sentiment_df.empty:
|
| 198 |
st.warning("No sentiment data to plot distribution.")
|
| 199 |
return
|
| 200 |
+
|
| 201 |
+
# Calculate counts for each sentiment label
|
| 202 |
sentiment_counts = sentiment_df['Sentiment'].value_counts().reset_index()
|
| 203 |
sentiment_counts.columns = ['Sentiment', 'Count']
|
| 204 |
+
|
| 205 |
+
# Define colors for the plot (Distilbert-base-uncased-finetuned-sst-2-english is binary)
|
| 206 |
+
color_map = {'POSITIVE': 'green', 'NEGATIVE': 'red'}
|
| 207 |
fig = px.bar(
|
| 208 |
sentiment_counts,
|
| 209 |
x='Sentiment',
|
| 210 |
y='Count',
|
| 211 |
title='Distribution of Comment Sentiments',
|
| 212 |
+
color='Sentiment',
|
| 213 |
+
color_discrete_map=color_map,
|
| 214 |
+
text='Count' # Display count value on top of bars
|
| 215 |
)
|
| 216 |
+
|
| 217 |
+
# Update layout for better readability
|
| 218 |
fig.update_traces(texttemplate='%{text}', textposition='outside')
|
| 219 |
fig.update_layout(xaxis_title="Sentiment", yaxis_title="Number of Comments")
|
| 220 |
|
| 221 |
st.plotly_chart(fig, use_container_width=True)
|
| 222 |
|
| 223 |
def display_sentiment_scores(sentiment_df: pd.DataFrame):
|
| 224 |
+
"""
|
| 225 |
+
Displays individual comment sentiments in a Streamlit DataFrame.
|
| 226 |
+
|
| 227 |
+
Args:
|
| 228 |
+
sentiment_df (pd.DataFrame): DataFrame containing sentiment analysis results.
|
| 229 |
+
"""
|
| 230 |
if sentiment_df.empty:
|
| 231 |
st.info("No comments available to display individual sentiment scores.")
|
| 232 |
return
|
|
|
|
| 235 |
st.dataframe(sentiment_df, use_container_width=True)
|
| 236 |
|
| 237 |
|
| 238 |
+
# --- Main Application Logic ---
|
| 239 |
YOUTUBE_API_KEY = os.environ.get("YOUTUBE_API_KEY")
|
| 240 |
|
| 241 |
st.title("π₯ (Phoenix) YouTube Comment Sentiment Checker")
|
| 242 |
+
st.markdown("Have you been attacked on YouTube? Report this by entering the YouTube video URL to fetch its comments and analyze their sentiment (Positive/Negative).")
|
| 243 |
|
| 244 |
+
# Check if API key is set
|
| 245 |
if not YOUTUBE_API_KEY:
|
| 246 |
+
st.warning("π¨ **YouTube API Key not found!** Please add `YOUTUBE_API_KEY` to your Hugging Face Space secrets or environment variables.")
|
| 247 |
+
st.info("Instructions on how to add secrets to Hugging Face Spaces can be found in their documentation.")
|
| 248 |
+
st.stop() # Stop execution if API key is missing
|
|
|
|
| 249 |
|
| 250 |
+
# Load the sentiment model with a spinner
|
| 251 |
with st.spinner("π Loading sentiment model... This might take a moment if it's the first run (downloading model)."):
|
| 252 |
+
sentiment_classifier = load_sentiment_model()
|
| 253 |
|
| 254 |
+
# User input for YouTube URL
|
| 255 |
youtube_url = st.text_input(
|
| 256 |
"π Enter YouTube Video URL:",
|
| 257 |
+
"https://www.youtube.com/watch?v=dQw4w9WgXcQ", # Example URL (Rick Astley - Never Gonna Give You Up)
|
| 258 |
help="e.g., https://www.youtube.com/watch?v=dQw4w9WgXcQ"
|
| 259 |
)
|
| 260 |
|
| 261 |
+
# Slider for maximum comments to fetch
|
| 262 |
max_comments = st.slider(
|
| 263 |
"π Max Comments to Fetch (approx.):",
|
| 264 |
min_value=50, max_value=2000, value=500, step=50,
|
| 265 |
help="Fetching more comments takes longer and uses more API quota."
|
| 266 |
)
|
| 267 |
|
| 268 |
+
# Button to trigger analysis
|
| 269 |
if st.button("β¨ Analyze Comments", type="primary"):
|
| 270 |
if not youtube_url:
|
| 271 |
st.error("β Please enter a YouTube video URL to analyze.")
|
|
|
|
| 275 |
st.error("β Invalid YouTube URL. Please make sure it's a valid video URL (e.g., starts with youtube.com/watch?v= or youtu.be/).")
|
| 276 |
else:
|
| 277 |
st.info(f"Fetching comments for video ID: `{video_id}`")
|
| 278 |
+
|
| 279 |
+
# Fetch comments with a spinner
|
| 280 |
with st.spinner(f"π₯ Fetching up to {max_comments} comments from YouTube..."):
|
| 281 |
comments = fetch_comments(video_id, YOUTUBE_API_KEY, max_comments)
|
| 282 |
|
|
|
|
| 285 |
else:
|
| 286 |
st.success(f"β
Successfully fetched {len(comments)} comments.")
|
| 287 |
|
| 288 |
+
# Analyze sentiments with a spinner
|
| 289 |
with st.spinner("π§ Analyzing sentiment of comments..."):
|
| 290 |
sentiment_df = analyze_sentiments(comments, sentiment_classifier)
|
| 291 |
|
| 292 |
if sentiment_df.empty:
|
| 293 |
st.info("No comments were successfully analyzed for sentiment.")
|
| 294 |
else:
|
| 295 |
+
# Display results
|
| 296 |
st.subheader("π Sentiment Analysis Results:")
|
| 297 |
|
| 298 |
+
# Display summary statistics
|
| 299 |
total_analyzed = len(sentiment_df)
|
| 300 |
positive_count = sentiment_df[sentiment_df['Sentiment'] == 'POSITIVE'].shape[0]
|
| 301 |
negative_count = sentiment_df[sentiment_df['Sentiment'] == 'NEGATIVE'].shape[0]
|
| 302 |
+
|
| 303 |
st.write(f"**Total comments analyzed:** `{total_analyzed}`")
|
| 304 |
st.write(f"**Positive sentiments:** `{positive_count}` ({(positive_count/total_analyzed*100):.1f}%)")
|
| 305 |
st.write(f"**Negative sentiments:** `{negative_count}` ({(negative_count/total_analyzed*100):.1f}%)")
|
| 306 |
+
|
| 307 |
+
# Plot sentiment distribution
|
| 308 |
plot_sentiment_distribution(sentiment_df)
|
| 309 |
|
| 310 |
+
# Display individual sentiment scores
|
| 311 |
display_sentiment_scores(sentiment_df)
|
| 312 |
|
| 313 |
st.markdown("---")
|
| 314 |
+
st.markdown("This is a Build Up project developed last night with β€οΈ as an example of a modular addition to support the reporting of TFGBV platforms in Kenya .")
|