Views
No views yet
pip install tensorflow gensim nltk numpy scikit-learn1import numpy as np
2from tensorflow import keras
3from gensim.models import Word2Vec
4from nltk.tokenize import word_tokenize
5import pickle
6import re
7from huggingface_hub import hf_hub_download
8
9# Download model files
10model_path = hf_hub_download(repo_id="shreyaspulle98/emotion-classifier-20-emotions",
11 filename="best_model.keras")
12w2v_path = hf_hub_download(repo_id="shreyaspulle98/emotion-classifier-20-emotions",
13 filename="word2vec_optimized.model")
14encoder_path = hf_hub_download(repo_id="shreyaspulle98/emotion-classifier-20-emotions",
15 filename="label_encoder.pkl")
16
17# Load models
18w2v_model = Word2Vec.load(w2v_path)
19classifier = keras.models.load_model(model_path, compile=False)
20with open(encoder_path, 'rb') as f:
21 label_encoder = pickle.load(f)
22
23# Preprocessing function
24def preprocess_text(text):
25 text = str(text).lower()
26 text = re.sub(r'http\S+|www\S+|https\S+', '', text)
27 text = re.sub(r'@\w+', '', text)
28 text = re.sub(r'#\w+', '', text)
29 harmful_punctuation = '"#$%&()*+-/:;<=>@[\\]^_`{|}~'
30 text = text.translate(str.maketrans('', '', harmful_punctuation))
31 text = re.sub(r'\s+', ' ', text).strip()
32 return text
33
34# Sentence to vector
35def sentence_to_vector(sentence, w2v_model):
36 words = word_tokenize(sentence.lower())
37 word_vectors = [w2v_model.wv[word] for word in words if word in w2v_model.wv]
38 if len(word_vectors) == 0:
39 return np.zeros(w2v_model.wv.vector_size)
40 return np.mean(word_vectors, axis=0)
41
42# Prediction function
43def predict_emotion(text, top_k=5):
44 # Preprocess
45 cleaned = preprocess_text(text)
46
47 # Convert to vector
48 vector = sentence_to_vector(cleaned, w2v_model).reshape(1, -1)
49
50 # Predict
51 probs = classifier.predict(vector, verbose=0)[0]
52
53 # Get top-k predictions
54 top_indices = np.argsort(probs)[-top_k:][::-1]
55
56 results = []
57 for idx in top_indices:
58 emotion = label_encoder.inverse_transform([idx])[0]
59 confidence = float(probs[idx])
60 results.append({
61 'emotion': emotion,
62 'confidence': confidence,
63 'percentage': round(confidence * 100, 1)
64 })
65
66 return results
67
68# Example usage
69text = "I'm so excited about this amazing opportunity!"
70predictions = predict_emotion(text)
71
72print(f"Text: {text}")
73print("\nTop predictions:")
74for pred in predictions:
75 print(f" {pred['emotion']}: {pred['percentage']}%")Text: I'm so excited about this amazing opportunity!
Top predictions:
excitement: 78.5%
happiness: 12.3%
hope: 4.2%
gratitude: 2.8%
pride: 2.2%1tensorflow>=2.13.0
2gensim>=4.3.0
3nltk>=3.8.0
4numpy>=1.24.0
5scikit-learn>=1.3.01@model{emotion_classifier_20_2025,
2 author = {Shreyas Pulle},
3 title = {20-Emotion Text Classification Model},
4 year = {2025},
5 publisher = {HuggingFace},
6 url = {https://huggingface.co/shreyaspulle98/emotion-classifier-20-emotions}
7}