Download inference.py from ketir/Emotion-Detection-BiLSTM: direct link, hf CLI and curl.
- Browser
- Download file 1.43 kB
-
https://huggingface.co/ketir/Emotion-Detection-BiLSTM/resolve/main/inference.py
- Command line
-
hf download hf://ketir/Emotion-Detection-BiLSTM/inference.py
-
curl -L -o inference.py https://huggingface.co/ketir/Emotion-Detection-BiLSTM/resolve/main/inference.py
1.43 kB
| 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 | |
| } | |