zafirabdullah12 commited on
Commit
d5b3c4c
·
verified ·
1 Parent(s): bbce936

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +61 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import nltk
3
+ import pickle
4
+ import string
5
+ import numpy as np
6
+ import gradio as gr
7
+
8
+ from nltk.corpus import stopwords
9
+ from keras.models import load_model
10
+ from keras.preprocessing.sequence import pad_sequences
11
+
12
+ nltk.download('stopwords')
13
+
14
+ # Load Model and Tokenizer
15
+ model = load_model("sentiment_analysis_best.keras")
16
+
17
+ with open("tokenizer.pkl", "rb") as f:
18
+ tokenizer = pickle.load(f)
19
+
20
+ MAX_LEN = 100
21
+
22
+ negations = {"not", "no", "nor", "never", "n't"}
23
+ stop_words = set(stopwords.words("english")) - negations
24
+
25
+ # Preprocessing Function
26
+ def preprocess(text):
27
+ text = text.lower()
28
+ text = re.sub(r"\d+", "", text)
29
+ text = text.translate(str.maketrans('', '', string.punctuation))
30
+ words = [w for w in text.split() if w not in stop_words]
31
+ return " ".join(words)
32
+
33
+ # Prediction Function
34
+ def predict_sentiment(text):
35
+ text = preprocess(text)
36
+ seq = tokenizer.texts_to_sequences([text])
37
+ pad = pad_sequences(seq, maxlen=MAX_LEN, padding='post')
38
+ pred = model.predict(pad)
39
+
40
+ label_idx = np.argmax(pred, axis=1)[0]
41
+ confidence = pred[0][label_idx] * 100
42
+
43
+ labels = ["Negative", "Positive", "Neutral"]
44
+
45
+ return f"{labels[label_idx]} {confidence:.2f}%"
46
+
47
+ # Gradio Interface
48
+ interface = gr.Interface(
49
+ fn=predict_sentiment,
50
+ inputs=gr.Textbox(lines=3, placeholder="Type your sentence here..."),
51
+ outputs=gr.Textbox(label="Prediction"),
52
+ title="Sentiment Analysis System",
53
+ description="Outputs sentiment analysis along with model confidence.",
54
+ examples=[
55
+ ["I really love this product"],
56
+ ["This is the worst experience ever"],
57
+ ["It is okay, not good not bad"]
58
+ ]
59
+ )
60
+
61
+ interface.launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ numpy
2
+ nltk
3
+ tensorflow
4
+ keras
5
+ gradio