import nltk
import torch
import requests
import feedparser
import sqlite3
import pandas as pd
import plotly.graph_objects as go
import numpy as np
from plotly.subplots import make_subplots
from datetime import datetime, timedelta
from nltk.sentiment import SentimentIntensityAnalyzer
from transformers import (
AutoTokenizer,
AutoModelForSequenceClassification,
pipeline
)
from concurrent.futures import ThreadPoolExecutor
from functools import lru_cache
import logging
from typing import List, Tuple, Set
from wordcloud import WordCloud
import seaborn as sns
from collections import Counter
import matplotlib.pyplot as plt
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import warnings
warnings.filterwarnings('ignore')
def _setup_database(self):
with sqlite3.connect(self.db_name) as conn:
conn.execute('''
CREATE TABLE IF NOT EXISTS sentiment_scores (
date TEXT,
time TEXT,
title TEXT,
summary TEXT,
score REAL
)
''')
# Add indexes for better query performance
conn.execute('CREATE INDEX IF NOT EXISTS idx_date ON sentiment_scores(date)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_title ON sentiment_scores(title)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_score ON sentiment_scores(score)')
def _setup_connection(self):
"""Setup persistent connection with optimized parameters"""
if not self.connection:
self.connection = sqlite3.connect(self.db_name, check_same_thread=False)
self.connection.execute('PRAGMA journal_mode=WAL') # Write-Ahead Logging
self.connection.execute('PRAGMA synchronous=NORMAL')
self.connection.execute('PRAGMA cache_size=-2000') # 2MB cache
self.connection.execute('PRAGMA temp_store=MEMORY')
def store_score(self, date: str, time: str, title: str, summary: str, score: float):
try:
self.connection.execute(
"INSERT INTO sentiment_scores VALUES (?, ?, ?, ?, ?)",
(date, time, title, summary, score)
)
self.connection.commit()
except Exception as e:
logging.error(f"Error storing score: {e}")
@lru_cache(maxsize=128)
def get_daily_average(self, date: str) -> float:
try:
result = self.connection.execute(
"SELECT AVG(score) FROM sentiment_scores WHERE date = ?",
(date,)
).fetchone()
return result[0] if result[0] is not None else 0.0
except Exception as e:
logging.error(f"Error getting daily average: {e}")
return 0.0
def get_headlines_with_scores(self, limit: int = 10) -> pd.DataFrame:
"""Retrieve recent headlines with their sentiment scores"""
try:
query = """
SELECT date, time, title, score
FROM sentiment_scores
ORDER BY date DESC, time DESC
LIMIT ?
"""
return pd.read_sql_query(query, self.connection, params=(limit,))
except Exception as e:
logging.error(f"Error retrieving headlines: {e}")
return pd.DataFrame()
def get_extreme_sentiment_headlines(self) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Get headlines with highest and lowest sentiment scores"""
try:
most_positive = pd.read_sql_query("""
SELECT date, time, title, score
FROM sentiment_scores
ORDER BY score DESC
LIMIT 5
""", self.connection)
most_negative = pd.read_sql_query("""
SELECT date, time, title, score
FROM sentiment_scores
ORDER BY score ASC
LIMIT 5
""", self.connection)
return most_positive, most_negative
except Exception as e:
logging.error(f"Error retrieving extreme headlines: {e}")
return pd.DataFrame(), pd.DataFrame()
def get_headline_stats(self) -> dict:
"""Get statistical information about headlines"""
try:
stats = {}
# Get average sentiment score
avg_query = "SELECT AVG(score) FROM sentiment_scores"
stats['average_sentiment'] = self.connection.execute(avg_query).fetchone()[0]
# Get total number of headlines
count_query = "SELECT COUNT(*) FROM sentiment_scores"
stats['total_headlines'] = self.connection.execute(count_query).fetchone()[0]
# Get date range
range_query = """
SELECT
MIN(date) as earliest_date,
MAX(date) as latest_date
FROM sentiment_scores
"""
earliest, latest = self.connection.execute(range_query).fetchone()
stats['date_range'] = f"{earliest} to {latest}"
return stats
except Exception as e:
logging.error(f"Error getting headline stats: {e}")
return {}
def close(self):
if self.connection:
self.connection.close()
class SentimentAnalyzer:
def init(self):
self._initialize_models()
self._setup_device()
# Generate visualizations
logging.info("Generating main dashboard...")
DataVisualizer.create_visualizations(DATABASE_NAME)
# Analyze headlines
logging.info("Analyzing headlines...")
analyze_headlines()
logging.info("Analysis complete!")
except Exception as e:
logging.error(f"Error during analysis: {e}")
raise
if name == "main":
run_analysis()
I have this code and this works great, except the scale on the Headline Length vs Sentiment plot is taking up the entire right side of the dashboard instead of being close to the subplot it is supposed to indicate. Can you fix this? Also, does this code remove any duplicate or very similar headlines?
I'm glad to hear that your code is working well! Let's address both of your concerns:
Fixing the Color Scale in the "Headline Length vs Sentiment" Plot
Handling Duplicate or Similar Headlines
1. Fixing the Color Scale in the "Headline Length vs Sentiment" Plot
Issue:
The color scale (colorbar) for the "Headline Length vs Sentiment" plot is taking up the entire right side of the dashboard instead of being positioned adjacent to its respective subplot.
Solution:
To position the colorbar specifically for the "Headline Length vs Sentiment" subplot, you need to adjust the colorbar properties, particularly the x and y positions. This ensures that the colorbar appears close to its corresponding plot rather than occupying the entire dashboard.
Here's how you can modify the _add_headline_length_vs_sentiment method within the DataVisualizer class:
Updated _add_headline_length_vs_sentiment Method
python
@staticmethod
def _add_headline_length_vs_sentiment(fig, df):
"""Add headline length vs sentiment visualization"""
df['title_length'] = df['title'].str.len()
fig.add_trace(
go.Scatter(
x=df['title_length'],
y=df['score'],
mode='markers',
name='Headline Length vs Sentiment',
marker=dict(
size=8,
color=df['score'],
colorscale='Viridis',
showscale=True,
colorbar=dict(
title="Sentiment Score",
x=1.05, # Adjust x position
y=0.5, # Adjust y position
len=0.5, # Adjust length of colorbar
thickness=15
)
)
),
row=3, col=2
)
fig.update_xaxes(title_text="Headline Length (characters)", row=3, col=2)
fig.update_yaxes(title_text="Sentiment Score", row=3, col=2)
Explanation of Changes:
colorbar Configuration:
x and y: Positions the colorbar relative to the subplot. Adjust x and y values as needed to fine-tune the placement.
len: Determines the length of the colorbar.
thickness: Sets the thickness of the colorbar.
title: Adds a title to the colorbar for clarity.
Example Adjustment:
You might need to tweak the x, y, len, and thickness values to best fit your dashboard's layout. Here's an example of how the colorbar can be positioned to the right of the subplot without overlapping other elements.
Full Updated DataVisualizer Class with Adjusted Method
python
Additional Tips:
Fine-Tuning:
You may need to adjust the x, y, len, and thickness parameters further based on how your dashboard looks. Using smaller len and different x positions can help fit the colorbar better.
Consistency:
Ensure that other plots do not have overlapping colorbars. If they do, you might need to set showscale=False for those that don't require a colorbar.
2. Handling Duplicate or Similar Headlines
Issue:
Currently, the code does not explicitly handle duplicate or very similar headlines. This means that if the RSS feed contains duplicate entries, they will be stored multiple times in your sentiment_scores table, potentially skewing your analysis.
Solution:
To prevent duplicate or highly similar headlines from being stored, you can implement a deduplication mechanism. Here's how you can modify your code to handle duplicates:
Approach 1: Enforce Uniqueness at the Database Level
Add a UNIQUE constraint to the title column in your sentiment_scores table. This ensures that duplicate titles are not inserted into the database.
Modify the _setup_database Method:
python
def _setup_database(self):
with sqlite3.connect(self.db_name) as conn:
conn.execute('''
CREATE TABLE IF NOT EXISTS sentiment_scores (
date TEXT,
time TEXT,
title TEXT UNIQUE, -- Enforce uniqueness on title
summary TEXT,
score REAL
)
''')
# Add indexes for better query performance
conn.execute('CREATE INDEX IF NOT EXISTS idx_date ON sentiment_scores(date)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_title ON sentiment_scores(title)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_score ON sentiment_scores(score)')
Update the store_score Method to Handle Integrity Errors:
python
def store_score(self, date: str, time: str, title: str, summary: str, score: float):
try:
self.connection.execute(
"INSERT INTO sentiment_scores VALUES (?, ?, ?, ?, ?)",
(date, time, title, summary, score)
)
self.connection.commit()
except sqlite3.IntegrityError:
logging.info(f"Duplicate headline found and skipped: {title}")
except Exception as e:
logging.error(f"Error storing score: {e}")
Explanation:
title TEXT UNIQUE:
This ensures that each title is unique in the table. Attempting to insert a duplicate title will raise an sqlite3.IntegrityError.
Handling IntegrityError:
When a duplicate is detected, the code logs the occurrence and skips inserting the duplicate headline.
Approach 2: Implement Similarity Checks Before Inserting
If you want to handle very similar headlines (not exact duplicates), you can use text similarity metrics (like Levenshtein distance or cosine similarity) to determine if a new headline is too similar to existing ones.
Note:
Implementing similarity checks can be computationally intensive, especially with a large number of headlines. It's recommended to use this approach with care and potentially only on a subset of data.
Example Implementation Using Levenshtein Distance:
First, install the python-Levenshtein library:
python
!pip install python-Levenshtein
Modify the DatabaseManager Class:
python
import Levenshtein
class DatabaseManager:
# ... (other methods)
def is_similar(self, new_title: str, threshold: float = 0.9) -> bool:
"""Check if the new_title is similar to any existing title in the database."""
try:
cursor = self.connection.cursor()
cursor.execute("SELECT title FROM sentiment_scores")
existing_titles = cursor.fetchall()
for (existing_title,) in existing_titles:
similarity = Levenshtein.ratio(new_title.lower(), existing_title.lower())
if similarity >= threshold:
return True
return False
except Exception as e:
logging.error(f"Error during similarity check: {e}")
return False
def store_score(self, date: str, time: str, title: str, summary: str, score: float):
try:
if self.is_similar(title):
logging.info(f"Similar headline found and skipped: {title}")
return
self.connection.execute(
"INSERT INTO sentiment_scores VALUES (?, ?, ?, ?, ?)",
(date, time, title, summary, score)
)
self.connection.commit()
except Exception as e:
logging.error(f"Error storing score: {e}")
Explanation:
is_similar Method:
Retrieves all existing titles from the database.
Compares the new title with each existing title using the Levenshtein ratio.
If the similarity ratio exceeds the threshold (e.g., 0.9), it considers them similar and skips insertion.
Threshold Adjustment:
You can adjust the threshold parameter to define what constitutes "very similar." A higher threshold (closer to 1) means stricter similarity checks.
Caution:
This method can be slow with a large dataset. For better performance, consider indexing or more efficient similarity search algorithms.
Summary of Changes
Color Scale Adjustment:
Modified the _add_headline_length_vs_sentiment method to position the colorbar adjacent to its subplot using the colorbar attributes x, y, len, and thickness.
Duplicate Handling:
Approach 1: Added a UNIQUE constraint on the title column and handled IntegrityError exceptions to skip duplicate entries.
Approach 2: Implemented a similarity check using Levenshtein distance to prevent insertion of very similar headlines.
Complete Updated Code Snippets
For clarity, here's how the relevant parts of your code should look after applying the above changes.
1. Updating the DatabaseManager Class
python
2. Updating the DataVisualizer Class
(Only the _add_headline_length_vs_sentiment method is modified as shown above. The rest of the class remains unchanged.)
3. Ensure Proper Installation of Dependencies
Make sure to install the python-Levenshtein library for similarity checks:
python
!pip install python-Levenshtein
Additional Recommendations
Batch Processing for Similarity Checks:
To improve performance, especially with large datasets, consider processing headlines in batches or using more efficient similarity search algorithms like MinHash or Locality-Sensitive Hashing (LSH).
Logging Enhancements:
Enhance logging to capture more details about duplicates and similarity checks, which can aid in debugging and monitoring.
Data Cleaning:
Implement additional data cleaning steps such as removing special characters, handling casing consistently, and trimming whitespace to improve the accuracy of similarity checks.
Dashboard Layout:
Continuously refine the dashboard layout to ensure all visual elements are clearly visible and well-organized, especially after adding features like deduplication.
By implementing these changes, your dashboard should display the color scale properly adjacent to the "Headline Length vs Sentiment" plot, and your database will handle duplicate or very similar headlines effectively. If you encounter any further issues or need additional enhancements, feel free to ask!
import sqlite3
import logging
import Levenshtein
from functools import lru_cache
import pandas as pd
class DatabaseManager:
def __init__(self, db_name: str):
self.db_name = db_name
self._setup_database()
self.connection = None
self._setup_connection()
def _setup_database(self):
with sqlite3.connect(self.db_name) as conn:
conn.execute('''
CREATE TABLE IF NOT EXISTS sentiment_scores (
date TEXT,
time TEXT,
title TEXT UNIQUE, -- Enforce uniqueness on title
summary TEXT,
score REAL
)
''')
# Add indexes for better query performance
conn.execute('CREATE INDEX IF NOT EXISTS idx_date ON sentiment_scores(date)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_title ON sentiment_scores(title)')
conn.execute('CREATE INDEX IF NOT EXISTS idx_score ON sentiment_scores(score)')
def _setup_connection(self):
"""Setup persistent connection with optimized parameters"""
if not self.connection:
self.connection = sqlite3.connect(self.db_name, check_same_thread=False)
self.connection.execute('PRAGMA journal_mode=WAL') # Write-Ahead Logging
self.connection.execute('PRAGMA synchronous=NORMAL')
self.connection.execute('PRAGMA cache_size=-2000') # 2MB cache
self.connection.execute('PRAGMA temp_store=MEMORY')
def is_similar(self, new_title: str, threshold: float = 0.9) -> bool:
"""Check if the new_title is similar to any existing title in the database."""
try:
cursor = self.connection.cursor()
cursor.execute("SELECT title FROM sentiment_scores")
existing_titles = cursor.fetchall()
for (existing_title,) in existing_titles:
similarity = Levenshtein.ratio(new_title.lower(), existing_title.lower())
if similarity >= threshold:
return True
return False
except Exception as e:
logging.error(f"Error during similarity check: {e}")
return False
def store_score(self, date: str, time: str, title: str, summary: str, score: float):
try:
if self.is_similar(title):
logging.info(f"Similar headline found and skipped: {title}")
return
self.connection.execute(
"INSERT INTO sentiment_scores VALUES (?, ?, ?, ?, ?)",
(date, time, title, summary, score)
)
self.connection.commit()
except sqlite3.IntegrityError:
logging.info(f"Duplicate headline found and skipped: {title}")
except Exception as e:
logging.error(f"Error storing score: {e}")
@lru_cache(maxsize=128)
def get_daily_average(self, date: str) -> float:
try:
result = self.connection.execute(
"SELECT AVG(score) FROM sentiment_scores WHERE date = ?",
(date,)
).fetchone()
return result[0] if result[0] is not None else 0.0
except Exception as e:
logging.error(f"Error getting daily average: {e}")
return 0.0
def get_headlines_with_scores(self, limit: int = 10) -> pd.DataFrame:
"""Retrieve recent headlines with their sentiment scores"""
try:
query = """
SELECT date, time, title, score
FROM sentiment_scores
ORDER BY date DESC, time DESC
LIMIT ?
"""
return pd.read_sql_query(query, self.connection, params=(limit,))
except Exception as e:
logging.error(f"Error retrieving headlines: {e}")
return pd.DataFrame()
def get_extreme_sentiment_headlines(self) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Get headlines with highest and lowest sentiment scores"""
try:
most_positive = pd.read_sql_query("""
SELECT date, time, title, score
FROM sentiment_scores
ORDER BY score DESC
LIMIT 5
""", self.connection)
most_negative = pd.read_sql_query("""
SELECT date, time, title, score
FROM sentiment_scores
ORDER BY score ASC
LIMIT 5
""", self.connection)
return most_positive, most_negative
except Exception as e:
logging.error(f"Error retrieving extreme headlines: {e}")
return pd.DataFrame(), pd.DataFrame()
def get_headline_stats(self) -> dict:
"""Get statistical information about headlines"""
try:
stats = {}
# Get average sentiment score
avg_query = "SELECT AVG(score) FROM sentiment_scores"
stats['average_sentiment'] = self.connection.execute(avg_query).fetchone()[0]
# Get total number of headlines
count_query = "SELECT COUNT(*) FROM sentiment_scores"
stats['total_headlines'] = self.connection.execute(count_query).fetchone()[0]
# Get date range
range_query = """
SELECT
MIN(date) as earliest_date,
MAX(date) as latest_date
FROM sentiment_scores
"""
earliest, latest = self.connection.execute(range_query).fetchone()
stats['date_range'] = f"{earliest} to {latest}"
return stats
except Exception as e:
logging.error(f"Error getting headline stats: {e}")
return {}
def close(self):
if self.connection:
self.connection.close()