MRM5 commited on
Commit
520c5f6
·
verified ·
1 Parent(s): fc9c39f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -75
app.py CHANGED
@@ -1,76 +1,88 @@
1
- import gradio as gr
2
- import tensorflow as tf
3
- import pickle
4
- import re
5
- import string
6
- import numpy as np
7
-
8
- # 1. Load the models and preprocessing assets
9
- # Baselines
10
- with open('models/nb_model.pkl', 'rb') as f:
11
- nb_model = pickle.load(f)
12
- with open('models/lr_model.pkl', 'rb') as f:
13
- lr_model = pickle.load(f)
14
-
15
- # Custom Deep Learning Model
16
- nn_model = tf.keras.models.load_model('models/sentiment_model.h5')
17
-
18
- # Preprocessing assets
19
- with open('models/tfidf_vectorizer.pkl', 'rb') as f:
20
- tfidf = pickle.load(f)
21
- with open('models/label_encoder.pkl', 'rb') as f:
22
- le = pickle.load(f)
23
-
24
- # 2. Preprocessing function (must match your notebook)
25
- def clean_tweet(text):
26
- text = text.lower()
27
- text = re.sub(r'http\S+|www\S+|https\S+', '', text, flags=re.MULTILINE)
28
- text = re.sub(r'@\w+', '', text)
29
- text = text.translate(str.maketrans('', '', string.punctuation))
30
- text = re.sub(r'\s+', ' ', text).strip()
31
- return text
32
-
33
- # 3. Unified prediction function
34
- def predict_sentiment(tweet, model_choice):
35
- cleaned_text = clean_tweet(tweet)
36
- vectorized_text = tfidf.transform([cleaned_text]).toarray()
37
-
38
- if model_choice == "Naive Bayes":
39
- pred = nb_model.predict(vectorized_text)[0]
40
- label = le.inverse_transform([pred])[0]
41
- elif model_choice == "Logistic Regression":
42
- pred = lr_model.predict(vectorized_text)[0]
43
- label = le.inverse_transform([pred])[0]
44
- else: # Custom MLP
45
- pred_probs = nn_model.predict(vectorized_text)
46
- label_idx = np.argmax(pred_probs)
47
- label = le.inverse_transform([label_idx])[0]
48
-
49
- return label
50
-
51
- # 4. Gradio Interface Layout
52
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
53
- gr.Markdown("# 🐦 Multi-Model Twitter Sentiment Analyzer")
54
- gr.Markdown("Compare how different algorithms interpret the sentiment of a tweet.")
55
-
56
- with gr.Row():
57
- with gr.Column():
58
- input_text = gr.Textbox(label="Enter Tweet", placeholder="I love the new update!")
59
- model_dropdown = gr.Dropdown(
60
- choices=["Naive Bayes", "Logistic Regression", "Custom Neural Network (MLP)"],
61
- label="Select Model",
62
- value="Custom Neural Network (MLP)"
63
- )
64
- submit_btn = gr.Button("Analyze Sentiment")
65
-
66
- with gr.Column():
67
- output_text = gr.Label(label="Result")
68
-
69
- submit_btn.click(
70
- fn=predict_sentiment,
71
- inputs=[input_text, model_dropdown],
72
- outputs=output_text
73
- )
74
-
75
- if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
76
  demo.launch()
 
1
+ import gradio as gr
2
+ import tensorflow as tf
3
+ import pickle
4
+ import re
5
+ import string
6
+ import numpy as np
7
+
8
+ # 1. Load the models and assets from the ROOT directory
9
+ # Loading Baselines
10
+ with open('nb_model.pkl', 'rb') as f:
11
+ nb_model = pickle.load(f)
12
+
13
+ with open('lr_model.pkl', 'rb') as f:
14
+ lr_model = pickle.load(f)
15
+
16
+ # Loading Custom Deep Learning Model
17
+ nn_model = tf.keras.models.load_model('sentiment_model.h5')
18
+
19
+ # Loading Preprocessing Assets
20
+ with open('tfidf_vectorizer.pkl', 'rb') as f:
21
+ tfidf = pickle.load(f)
22
+
23
+ with open('label_encoder.pkl', 'rb') as f:
24
+ le = pickle.load(f)
25
+
26
+ # 2. Text Cleaning Function (must be identical to your training notebook)
27
+ def clean_tweet(text):
28
+ if not isinstance(text, str):
29
+ return ""
30
+ text = text.lower()
31
+ # Remove URLs, mentions, and punctuation
32
+ text = re.sub(r'http\S+|www\S+|https\S+', '', text, flags=re.MULTILINE)
33
+ text = re.sub(r'@\w+', '', text)
34
+ text = text.translate(str.maketrans('', '', string.punctuation))
35
+ text = re.sub(r'\s+', ' ', text).strip()
36
+ return text
37
+
38
+ # 3. Prediction Logic
39
+ def predict_sentiment(tweet, model_choice):
40
+ cleaned_text = clean_tweet(tweet)
41
+ # Convert text to the same 5000-feature vector used in training
42
+ vectorized_text = tfidf.transform([cleaned_text]).toarray()
43
+
44
+ if model_choice == "Naive Bayes":
45
+ pred = nb_model.predict(vectorized_text)[0]
46
+ label = le.inverse_transform([pred])[0]
47
+ elif model_choice == "Logistic Regression":
48
+ pred = lr_model.predict(vectorized_text)[0]
49
+ label = le.inverse_transform([pred])[0]
50
+ else: # Custom Neural Network (MLP)
51
+ pred_probs = nn_model.predict(vectorized_text)
52
+ label_idx = np.argmax(pred_probs)
53
+ label = le.inverse_transform([label_idx])[0]
54
+
55
+ return f"Result: {label.upper()}"
56
+
57
+ # 4. Gradio UI Layout
58
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
59
+ gr.Markdown("# 🐦 Twitter Entity Sentiment Intelligence")
60
+ gr.Markdown("Compare the performance of three different algorithms on real-world noisy data.")
61
+
62
+ with gr.Row():
63
+ with gr.Column():
64
+ input_text = gr.Textbox(
65
+ label="Enter Tweet Content",
66
+ placeholder="e.g., I just bought the new @BrandX phone and I love it!",
67
+ lines=3
68
+ )
69
+ model_dropdown = gr.Dropdown(
70
+ choices=["Naive Bayes", "Logistic Regression", "Custom Neural Network (MLP)"],
71
+ label="Choose Algorithm",
72
+ value="Custom Neural Network (MLP)"
73
+ )
74
+ submit_btn = gr.Button("Analyze Sentiment", variant="primary")
75
+
76
+ with gr.Column():
77
+ output_text = gr.Label(label="Model Prediction")
78
+
79
+ # Interactive components
80
+ submit_btn.click(
81
+ fn=predict_sentiment,
82
+ inputs=[input_text, model_dropdown],
83
+ outputs=output_text
84
+ )
85
+
86
+ # Launch the app
87
+ if __name__ == "__main__":
88
  demo.launch()