|
|
|
import pickle |
|
from keras.models import load_model |
|
from keras.preprocessing.sequence import pad_sequences |
|
|
|
|
|
NEGATIVE = 'Negative' |
|
POSITIVE = 'Positive' |
|
MAX_LEN = 300 |
|
MODEL_PATH = 'sentiment_analysis_model.h5' |
|
TOKENIZER_PATH = 'tokenizer.pickle' |
|
|
|
|
|
with open(TOKENIZER_PATH, 'rb') as handle: |
|
tokenizer = pickle.load(handle) |
|
|
|
|
|
model = load_model(MODEL_PATH) |
|
|
|
|
|
def encode_texts(text_list): |
|
""" |
|
Encodes a list of texts into padded sequences using the tokenizer. |
|
Parameters: |
|
text_list (list of str): A list of texts to encode. |
|
Returns: |
|
numpy.ndarray: Padded sequences ready for model input. |
|
""" |
|
|
|
return pad_sequences(tokenizer.texts_to_sequences(text_list), maxlen=MAX_LEN) |
|
|
|
|
|
def predict_sentiments(text_list): |
|
""" |
|
Predicts sentiments for a list of texts using the loaded model. |
|
Parameters: |
|
text_list (list of str): A list of texts to analyze. |
|
Returns: |
|
list of str: A list of sentiment predictions ('Positive' or 'Negative'). |
|
""" |
|
|
|
encoded_inputs = encode_texts(text_list) |
|
predictions = model.predict(encoded_inputs) |
|
|
|
|
|
sentiments = [] |
|
for predict in predictions: |
|
if predict < 0.5: |
|
sentiments.append(NEGATIVE) |
|
else: |
|
sentiments.append(POSITIVE) |
|
|
|
return sentiments |
|
|