File size: 2,056 Bytes
3980db1 e793bea e1814e1 e793bea ec269de e1814e1 e793bea e1814e1 f56ddba c9f838a f56ddba ec269de f56ddba ec269de f56ddba ec269de babc77e f56ddba ec269de f56ddba e1814e1 8845d36 ec269de 8845d36 3980db1 8845d36 c9f838a ec269de 8845d36 3980db1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
import os
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from transformers import pipeline
# β
Load Sentiment Analysis Model
sentiment_analyzer = pipeline("sentiment-analysis")
def analyze_sentiment(text):
"""Analyzes sentiment and returns sentiment label with confidence."""
result = sentiment_analyzer(text)[0]
return result['label'], result['score']
def generate_sentiment_graph(sentiments):
"""Creates a bar chart for sentiment analysis results."""
assets_dir = "assets"
# β
Ensure 'assets/' is a folder
if os.path.exists(assets_dir) and not os.path.isdir(assets_dir):
os.remove(assets_dir) # Delete if it's a file
os.makedirs(assets_dir) # Recreate as a folder
elif not os.path.exists(assets_dir):
os.makedirs(assets_dir)
# β
Extract sentiment data
labels = [s[0] for s in sentiments]
scores = [s[1] for s in sentiments]
# β
Create bar chart
plt.figure(figsize=(6, 3))
plt.bar(labels, scores, color=["green" if lbl == "POSITIVE" else "red" for lbl in labels])
plt.xlabel("Sentiment")
plt.ylabel("Confidence Score")
plt.title("Sentiment Analysis Results")
# β
Save the graph inside 'assets/' folder
graph_path = os.path.join(assets_dir, "sentiment_graph.png")
plt.savefig(graph_path)
plt.close()
return graph_path
def generate_wordcloud(text):
"""Generates a word cloud and ensures 'assets/' is always a folder."""
assets_dir = "assets"
# β
Ensure 'assets/' is a folder
if os.path.exists(assets_dir) and not os.path.isdir(assets_dir):
os.remove(assets_dir) # Delete if it's a file
os.makedirs(assets_dir) # Recreate as a folder
elif not os.path.exists(assets_dir):
os.makedirs(assets_dir)
# β
Generate and save Word Cloud
wordcloud = WordCloud(width=800, height=400, background_color="white").generate(text)
wordcloud_path = os.path.join(assets_dir, "wordcloud.png")
wordcloud.to_file(wordcloud_path)
return wordcloud_path
|