File size: 1,426 Bytes
925332b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
import joblib
import tensorflow as tf
import json
import warnings

warnings.filterwarnings("ignore", category=UserWarning)

MODEL_PATH = "best_bilstm_model.h5"
TOKENIZER_PATH = "tokenizer_raw.pkl"
LABELENC_PATH = "label_encoder_raw.pkl"

# Load model & assets
model = tf.keras.models.load_model(MODEL_PATH)
tokenizer = joblib.load(TOKENIZER_PATH)
label_encoder = joblib.load(LABELENC_PATH)
labels = [str(label) for label in label_encoder.classes_]

def predict_emotion(text):
    if not text.strip():
        return {"error": "No input text provided"}

    # Tokenize & pad
    seq = tokenizer.texts_to_sequences([text])
    max_vocab_index = len(tokenizer.word_index)
    filtered_seq = [[idx for idx in sequence if idx < max_vocab_index] for sequence in seq]

    if not filtered_seq[0]:
        return {"warning": "Text contains only unknown words"}

    padded = tf.keras.preprocessing.sequence.pad_sequences(filtered_seq, maxlen=model.input_shape[1])
    probs = model.predict(padded, verbose=0)[0]
    top_index = int(np.argmax(probs))
    top_label = labels[top_index]
    top_conf = float(probs[top_index])
    all_probs = {labels[i]: float(probs[i]) for i in range(len(labels))}
    sorted_probs = dict(sorted(all_probs.items(), key=lambda x: x[1], reverse=True))

    return {
        "predicted_emotion": top_label,
        "confidence": top_conf,
        "all_probabilities": sorted_probs
    }