File size: 2,340 Bytes
5bfed7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pickle
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.sequence import pad_sequences
import sys

# Constants
MAX_SEQUENCE_LENGTH = 100

def load_resources():
    try:
        # Load the model
        model = load_model('emotion_model.h5')
        
        # Load the tokenizer
        with open('tokenizer.pickle', 'rb') as handle:
            tokenizer = pickle.load(handle)
            
        # Load the label encoder classes
        with open('label_encoder_classes.npy', 'rb') as f:
            classes = np.load(f, allow_pickle=True)
            
        return model, tokenizer, classes
    except Exception as e:
        print(f"Error loading resources: {e}")
        return None, None, None

def predict_emotion(text, model, tokenizer, classes):
    # Tokenize and pad the input text
    sequences = tokenizer.texts_to_sequences([text])
    data = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH)
    
    # Predict
    prediction = model.predict(data)
    predicted_class_index = np.argmax(prediction)
    predicted_emotion = classes[predicted_class_index]
    confidence = prediction[0][predicted_class_index]
    
    return predicted_emotion, confidence

if __name__ == "__main__":
    model, tokenizer, classes = load_resources()
    
    if model and tokenizer and classes is not None:
        if len(sys.argv) > 1:
            # Command line mode
            text = " ".join(sys.argv[1:])
            emotion, confidence = predict_emotion(text, model, tokenizer, classes)
            print(f"Input: {text}")
            print(f"Predicted Entity: {emotion}")
            print(f"Confidence: {confidence:.2f}")
        else:
            # Interactive mode
            print("Model loaded successfully.")
            print("Type a sentence to analyze its emotion (or 'quit' to exit).")
            
            while True:
                user_input = input("\nEnter text: ")
                if user_input.lower() == 'quit':
                    break
                
                emotion, confidence = predict_emotion(user_input, model, tokenizer, classes)
                print(f"Predicted Entity: {emotion}")
                print(f"Confidence: {confidence:.2f}")