1from huggingface_hub import hf_hub_download
2
3model_path = hf_hub_download(repo_id="logasanjeev/sentiment-analysis-bilstm-luong", filename="sentiment_model.h5")
4tokenizer_path = hf_hub_download(repo_id="logasanjeev/sentiment-analysis-bilstm-luong", filename="tokenizer.pkl")
5encoder_path = hf_hub_download(repo_id="logasanjeev/sentiment-analysis-bilstm-luong", filename="label_encoder.pkl")
6config_path = hf_hub_download(repo_id="logasanjeev/sentiment-analysis-bilstm-luong", filename="config.json")
1import tensorflow as tf
2from tensorflow.keras.models import load_model
3from tensorflow.keras.preprocessing.sequence import pad_sequences
4import pickle, re, numpy as np
5import nltk
6from nltk.tokenize import word_tokenize
7from nltk.stem import WordNetLemmatizer
8import contractions
9
10# Setup
11nltk.download('punkt')
12nltk.download('wordnet')
13nltk.download('omw-1.4')
14lemmatizer = WordNetLemmatizer()
15
16# Custom Attention Layer
17class LuongAttention(tf.keras.layers.Layer):
18 def __init__(self, **kwargs):
19 super().__init__(**kwargs)
20 def build(self, input_shape):
21 self.W = self.add_weight("attention_weight", (input_shape[-1], input_shape[-1]), initializer="glorot_normal", trainable=True)
22 self.b = self.add_weight("attention_bias", (input_shape[-1],), initializer="zeros", trainable=True)
23 def call(self, inputs):
24 e = tf.keras.backend.tanh(tf.keras.backend.dot(inputs, self.W) + self.b)
25 alpha = tf.keras.backend.softmax(e, axis=1)
26 context = tf.keras.backend.sum(inputs * alpha, axis=1)
27 return context
28
29# Load Model
30model = load_model(model_path, custom_objects={"LuongAttention": LuongAttention, "focal_loss_fn": lambda y_true, y_pred: y_true})
31with open(tokenizer_path, "rb") as f: tokenizer = pickle.load(f)
32with open(encoder_path, "rb") as f: label_encoder = pickle.load(f)
33
34# Preprocess
35def clean_text(text):
36 text = contractions.fix(text).lower()
37 text = re.sub(r'http\S+|www\S+|https\S+|@\w+|#\w+|<.*?>+|
38|\w*\d\w*|[^\w\s]', '', text)
39 tokens = word_tokenize(' '.join(text.split()))
40 tokens = [lemmatizer.lemmatize(token, pos='v') for token in tokens]
41 return ' '.join(tokens).strip()
42
43# Predict
44def predict_sentiment(text):
45 cleaned = clean_text(text)
46 seq = tokenizer.texts_to_sequences([cleaned])
47 padded = pad_sequences(seq, maxlen=60, padding='post', truncating='post')
48 prob = model.predict(padded, verbose=0)[0][0]
49 threshold = 0.5173
50 label = (prob >= threshold).astype(int)
51 sentiment = label_encoder.inverse_transform([label])[0]
52 confidence = prob if sentiment.lower() == "positive" else 1 - prob
53 return sentiment, {"Negative": 1 - prob, "Positive": prob}, confidence
54
55# Example
56sentiment, probs, confidence = predict_sentiment("i wouldn't recommend it to anyone")
57print(f"Sentiment: {sentiment}, Confidence: {confidence:.4f}, Probabilities: {probs}")