File size: 2,258 Bytes
520c5f6
 
 
 
 
 
 
0741577
 
 
 
 
 
 
520c5f6
 
0741577
 
 
 
520c5f6
0741577
520c5f6
 
 
 
 
68525cf
520c5f6
0741577
520c5f6
68525cf
 
520c5f6
 
68525cf
520c5f6
 
68525cf
520c5f6
aeed49e
68525cf
 
520c5f6
0741577
520c5f6
c771984
 
 
0741577
 
 
c771984
0741577
 
 
 
 
 
 
c771984
 
 
 
0741577
520c5f6
c771984
520c5f6
0741577
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import gradio as gr
import tensorflow as tf
import pickle
import re
import string
import numpy as np

# 1. LOAD ASSETS (Assumes files are in the root directory)
with open('nb_model.pkl', 'rb') as f: 
    nb_model = pickle.load(f)
with open('lr_model.pkl', 'rb') as f: 
    lr_model = pickle.load(f)

# Load Custom MLP
nn_model = tf.keras.models.load_model('sentiment_model.h5')

with open('tfidf_vectorizer.pkl', 'rb') as f: 
    tfidf = pickle.load(f)
with open('label_encoder.pkl', 'rb') as f: 
    le = pickle.load(f)

# 2. SIMPLE CLEANING FUNCTION
def clean_tweet(text):
    text = text.lower()
    text = re.sub(r'http\S+|www\S+|https\S+', '', text, flags=re.MULTILINE)
    text = re.sub(r'@\w+', '', text)
    text = text.translate(str.maketrans('', '', string.punctuation))
    return re.sub(r'\s+', ' ', text).strip()

# 3. PREDICTION LOGIC
def predict_sentiment(tweet, model_choice):
    cleaned = clean_tweet(tweet)
    vec = tfidf.transform([cleaned]).toarray()
    
    if model_choice == "Naive Bayes":
        pred = nb_model.predict(vec)[0]
        label = le.inverse_transform([pred])[0]
    elif model_choice == "Logistic Regression":
        pred = lr_model.predict(vec)[0]
        label = le.inverse_transform([pred])[0]
    else: 
        probs = nn_model.predict(vec)
        label = le.inverse_transform([np.argmax(probs)])[0]
    
    return f"Sentiment: {label.upper()}"

# 4. AESTHETIC INTERFACE
# We use a built-in soft theme for a clean, modern look.
# The 'css' argument hides the 'Share via Link' button.
demo = gr.Interface(
    fn=predict_sentiment,
    inputs=[
        gr.Textbox(label="Enter Tweet Content", lines=3, placeholder="Type a tweet here..."),
        gr.Dropdown(
            ["Naive Bayes", "Logistic Regression", "Custom Neural Network (MLP)"], 
            label="Select Model", 
            value="Custom Neural Network (MLP)"
        )
    ],
    outputs=gr.Text(label="Analysis Result"),
    title=" Twitter Entity Sentiment Analyzer",
    description="Enter a tweet to detect its sentiment (Positive, Negative, Neutral, or Irrelevant) using your chosen AI model.",
    theme=gr.themes.Soft(),
    css=".share-button { display: none !important; }"
)

# 5. LAUNCH
if __name__ == "__main__":
    demo.launch()