Spaces:
Runtime error
Runtime error
File size: 7,864 Bytes
9f48ffe 77cfd0e 9f48ffe dfcec68 9f48ffe dfcec68 9f48ffe | 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 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | #!/usr/bin/env python
# coding: utf-8
# In[41]:
import pandas as pd
import nltk
nltk.download('stopwords')
nltk.download('punkt')
import numpy as np
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
stop_words = set(stopwords.words("english"))
# In[42]:
data = pd.read_csv("sentimentdataset.csv")
data.drop(columns = [i for i in data.columns if i not in ["Text","Sentiment"]], inplace = True)
# In[ ]:
def extract_words(sentence):
cleaned_text = [w.lower() for w in word_tokenize(sentence) if w.lower() not in stop_words]
return cleaned_text
# In[ ]:
def vocab(corpus):
vocabulary = []
for doc in corpus:
words = extract_words(doc)
vocabulary.extend(words)
vocabulary = sorted(list(set(vocabulary)))
return vocabulary
# In[ ]:
def bow(sentence, vocabulary):
words = extract_words(sentence)
bag = np.zeros(len(vocabulary))
for word in words:
for i, vocab in enumerate(vocabulary):
if vocab == word:
bag[i] += 1
return bag
# In[ ]:
vocabulary = vocab(data.Text.to_list())
# In[ ]:
arrays = np.empty((0, len(vocabulary)), int)
for val in data.Text.to_list():
bow_representation = bow(val, vocabulary)
arrays = np.append(arrays, [bow_representation], axis=0)
# In[ ]:
from sklearn.preprocessing import LabelEncoder
label_encoder = LabelEncoder()
data['Encoded_Sentiment'] = label_encoder.fit_transform(data['Sentiment'])
# In[ ]:
print("Mapping of original labels to encoded labels:")
for original_label, encoded_label in zip(label_encoder.classes_, label_encoder.transform(label_encoder.classes_)):
print(f"{original_label}: {encoded_label}")
# In[ ]:
X = arrays
y = data['Encoded_Sentiment']
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Initialize the Random Forest model
rf_classifier = RandomForestClassifier(n_estimators=100, random_state=42)
# Train the model on the training set
rf_classifier.fit(X, y)
Labels = dict(zip(label_encoder.transform(label_encoder.classes_),label_encoder.classes_))
def pred(text):
bag = bow(text, vocabulary)
input_array = np.array([bag])
y_pred = rf_classifier.predict(input_array)
return y_pred
# inputt = input("Enter the Text input: ")
# predicted_label = pred(inputt)[0]
# print("Predicted Label:", Labels[predicted_label])
# In[ ]:
import streamlit as st
# In[43]:
emojis = {
' Acceptance ': 'π',
' Acceptance ': 'π',
' Accomplishment ': 'π',
' Admiration ': 'π',
' Admiration ': 'π',
' Admiration ': 'π',
' Adoration ': 'π',
' Adrenaline ': 'π€―',
' Adventure ': 'π',
' Affection ': 'β€οΈ',
' Amazement ': 'π²',
' Ambivalence ': 'π',
' Ambivalence ': 'π',
' Amusement ': 'π',
' Amusement ': 'π',
' Anger ': 'π‘',
' Anticipation ': 'π¬',
' Anticipation ': 'π¬',
' Anxiety ': 'π°',
' Anxiety ': 'π°',
' Appreciation ': 'π',
' Apprehensive ': 'π',
' Arousal ': 'π',
' ArtisticBurst ': 'π¨',
' Awe ': 'π²',
' Awe ': 'π²',
' Awe ': 'π²',
' Awe ': 'π²',
' Bad ': 'π',
' Betrayal ': 'π',
' Betrayal ': 'π',
' Bitter ': 'π',
' Bitterness ': 'π',
' Bittersweet ': 'ππ',
' Blessed ': 'π',
' Boredom ': 'π',
' Boredom ': 'π',
' Breakthrough ': 'π',
' Calmness ': 'π',
' Calmness ': 'π',
' Captivation ': 'π',
' Celebration ': 'π',
' Celestial Wonder ': 'π',
' Challenge ': 'πͺ',
' Charm ': 'π',
' Colorful ': 'π¨',
' Compassion': 'β€οΈ',
' Compassion ': 'β€οΈ',
' Compassionate ': 'β€οΈ',
' Confidence ': 'π',
' Confident ': 'π',
' Confusion ': 'π',
' Confusion ': 'π',
' Confusion ': 'π',
' Connection ': 'π',
' Contemplation ': 'π€',
' Contentment ': 'π',
' Contentment ': 'π',
' Coziness ': 'π ',
' Creative Inspiration ': 'π¨',
' Creativity ': 'π¨',
' Creativity ': 'π¨',
' Culinary Adventure ': 'π½οΈ',
' CulinaryOdyssey ': 'π½οΈ',
' Curiosity ': 'π€',
' Curiosity ': 'π€',
' Curiosity ': 'π€',
' Curiosity ': 'π€',
' Curiosity ': 'π€',
' Darkness ': 'π',
' Dazzle ': 'β¨',
' Desolation ': 'π',
' Despair ': 'π’',
' Despair ': 'π’',
' Despair ': 'π’',
' Despair ': 'π’',
' Desperation ': 'π',
' Determination ': 'πͺ',
' Determination ': 'πͺ',
' Devastated ': 'π',
' Disappointed ': 'π',
' Disappointment ': 'π',
' Disgust ': 'π€’',
' Disgust ': 'π€’',
' Disgust ': 'π€’',
' Dismissive ': 'π',
' DreamChaser ': 'π',
' Ecstasy ': 'π',
' Elation ': 'π',
' Elation ': 'π',
' Elegance ': 'π',
' Embarrassed ': 'π³',
' Emotion ': 'π',
' EmotionalStorm ': 'π±',
' Empathetic ': 'β€οΈ',
' Empowerment ': 'πͺ',
' Enchantment ': 'π',
' Enchantment ': 'π',
' Energy ': 'β‘',
' Engagement ': 'π',
' Enjoyment ': 'π',
' Enthusiasm ': 'π',
' Enthusiasm ': 'π',
' Envious ': 'π ',
' Envisioning History ': 'π°',
' Envy ': 'π ',
' Euphoria ': 'π',
' Euphoria ': 'π',
' Euphoria ': 'π',
' Euphoria ': 'π',
' Excitement ': 'π',
' Excitement ': 'π',
' Excitement ': 'π',
' Exhaustion ': 'π©',
' Exploration ': 'π',
' Fear ': 'π¨',
' Fearful ': 'π¨',
' FestiveJoy ': 'π',
' Free-spirited ': 'π¦',
' Freedom ': 'π½',
' Friendship ': 'π«',
' Frustrated ': 'π€',
' Frustration ': 'π€',
' Frustration ': 'π€',
' Fulfillment ': 'π',
' Fulfillment ': 'π'}
def main():
background_image = 'https://miro.medium.com/v2/resize:fit:689/0*xv_GA6M5AX3NQztr.jpg'
html_code = f"""
<style>
body {{
background-image: url('{background_image}');
background-size: cover;
background-position: center;
background-repeat: no-repeat;
height: 100vh; /* Set the height of the background to fill the viewport */
margin: 0; /* Remove default body margin */
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}}
.stApp {{
background: none; /* Remove Streamlit app background */
}}
</style>
"""
st.markdown(html_code, unsafe_allow_html=True)
st.title("Text Sentiment Classifier")
selected_text = st.selectbox("Select Text", data['Text'].tolist())
if st.button("Predict"):
predicted_label = pred(selected_text)[0]
try:
st.write(f'<p style="color: #000000;">{Labels[predicted_label]}</p>', unsafe_allow_html=True)
except:
st.write(f'<p style="color: #000000;">{Labels[predicted_label]}</p>', unsafe_allow_html=True)
if __name__ == "__main__":
main()
|