forked from Complete-Coding/JavaScript_Complete_YouTube
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
145 lines (128 loc) · 5.72 KB
/
Copy pathapp.py
File metadata and controls
145 lines (128 loc) · 5.72 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import streamlit as st
import pandas as pd
import numpy as np
from textblob import TextBlob
import emoji
import warnings
from transformers import pipeline
from langdetect import detect
from googletrans import Translator
warnings.simplefilter('ignore')
# Load emoji sentiment data
df_emoji = pd.read_csv("Emoji_Sentiment_Data.csv", usecols=['Emoji', 'Negative', 'Neutral', 'Positive'])
# Process emoji sentiment data
polarity_list = []
for index, row in df_emoji.iterrows():
polarity = 0
arg_1 = row['Positive'] > row['Negative']
arg_2 = row['Positive'] == row['Negative'] and row['Neutral'] % 2 != 0
if arg_1 or arg_2:
polarity = 1
polarity_list.append(polarity)
new_df_emoji = pd.DataFrame(polarity_list, columns=['sentiment'])
new_df_emoji['emoji'] = df_emoji['Emoji'].values
# Function to extract text and emojis from input
def extract_text_and_emoji(text):
remove_keys = ('@', 'http://', 'https://', '&', '#')
clean_text = ' '.join(txt for txt in text.split() if not txt.startswith(remove_keys))
allchars = [str for str in text]
emoji_list = [c for c in allchars if c in emoji.EMOJI_DATA]
clean_text = ' '.join([str for str in clean_text.split() if not any(i in str for i in emoji_list)])
clean_emoji = ''.join([str for str in text.split() if any(i in str for i in emoji_list)])
return clean_text, clean_emoji
# Function to detect language and translate text to English
def detect_and_translate2(text):
translator = Translator()
lang = translator.detect(text).lang
trans = translator.translate(text, src=lang, dest='en')
return trans.text
# Initialize sentiment analysis pipeline
sentiment_pipeline = pipeline('sentiment-analysis')
# Function to get sentiment of text
def get_sentiment(s_input):
results = sentiment_pipeline(s_input)
pred_senti = results[0]['label']
return 1 if pred_senti == 'POSITIVE' else 0
# Function to get sentiment of emojis
def get_emoji_sentiment(emoji_ls, emoji_df=new_df_emoji):
emoji_val_ls = []
for e in emoji_ls:
get_emo_senti = [row['sentiment'] for index, row in emoji_df.iterrows() if row['emoji'] == e]
emoji_val_ls.append(get_emo_senti[0] if get_emo_senti else 0)
return emoji_val_ls
# Function to analyze emotion of text
def analyze_emotion(text):
blob = TextBlob(text)
sentiment = blob.sentiment
if sentiment.polarity > 0:
if sentiment.subjectivity > 0.5:
return "joy"
else:
return "surprise"
elif sentiment.polarity < 0:
if sentiment.subjectivity > 0.5:
return "anger"
else:
return "sadness"
else:
return "neutral"
# Function to get sentiment and emotion of text and emojis
def get_text_emoji_sentiment(input_text):
ext_text, ext_emoji = extract_text_and_emoji(input_text)
if ext_text.strip() == "" and ext_emoji.strip() != "":
# Only emojis are present
senti_emoji_values = get_emoji_sentiment(ext_emoji, new_df_emoji)
senti_emoji_value_sum = sum(senti_emoji_values)
print_emo_val_avg = 0 if len(ext_emoji) == 0 else senti_emoji_value_sum / len(ext_emoji)
senti_truth = "Positive" if print_emo_val_avg >= 0.5 else "Negative"
emoji_sentiments = dict(zip(ext_emoji, senti_emoji_values))
return senti_truth, "N/A", "N/A", emoji_sentiments
else:
lang = detect(ext_text)
if lang != "en":
ext_text = detect_and_translate2(ext_text)
senti_text = get_sentiment(ext_text)
senti_emoji_value = sum(get_emoji_sentiment(ext_emoji, new_df_emoji))
print_emo_val_avg = 0 if len(ext_emoji) == 0 else senti_emoji_value / len(ext_emoji)
senti_avg = (senti_emoji_value + senti_text) / (len(ext_emoji) + 1)
senti_truth = "Positive" if senti_avg >= 0.5 else "Negative"
emtext = analyze_emotion(ext_text)
return senti_truth, emtext, ext_text, {}
# Streamlit frontend
st.title('Text and Emoji Sentiment Analysis')
user_input = st.text_input("Enter tweet with emojis in your language:")
uploaded_excel = st.file_uploader("Or upload an Excel file containing tweets:", type="xlsx")
if user_input:
sentiment, emotion, tran, emoji_sentiments = get_text_emoji_sentiment(user_input)
if tran == "N/A":
st.write(f"Only emojis detected: {user_input}")
st.write(f"Emoji Sentiment: {sentiment}")
st.write("Detailed Emoji Sentiments:")
for emoji_char, senti_val in emoji_sentiments.items():
senti_text = "Positive" if senti_val == 1 else "Negative"
st.write(f"{emoji_char}: {senti_text}")
else:
st.write(f"Translated tweet: {tran}")
st.write(f"Overall Sentiment: {sentiment}")
st.write(f"Text Emotion: {emotion}")
elif uploaded_excel:
df = pd.read_excel(uploaded_excel)
if 'tweet' in df.columns:
for tweet in df['tweet']:
if tweet.strip():
sentiment, emotion, tran, emoji_sentiments = get_text_emoji_sentiment(tweet)
st.write(f"Tweet: {tweet}")
if tran == "N/A":
st.write(f"Only emojis detected")
st.write(f"Emoji Sentiment: {sentiment}")
st.write("Detailed Emoji Sentiments:")
for emoji_char, senti_val in emoji_sentiments.items():
senti_text = "Positive" if senti_val == 1 else "Negative"
st.write(f"{emoji_char}: {senti_text}")
else:
st.write(f"Translated tweet: {tran}")
st.write(f"Overall Sentiment: {sentiment}")
st.write(f"Text Emotion: {emotion}")
st.write("\n")
else:
st.write("Excel file does not contain 'tweet' column.")