File size: 2,194 Bytes
f75d9fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 joblib
import preprocess

# Load the trained model
try:
    model = joblib.load("sentiment_model_best.pkl")
    print("Model loaded successfully.")
except FileNotFoundError:
    print("Error: Model file 'sentiment_model_best.pkl' not found. Please run train_model.py first.")
    model = None

def analyze_sentiment(text):
    if model is None:
        return "Model not loaded."
    
    # Preprocess
    clean_text = preprocess.preprocess_text(text)
    
    # Predict
    # The pipeline handles vectorization
    prediction = model.predict([clean_text])[0]
    
    # Get confidence scores if possible (LinearSVC uses decision_function, not predict_proba by default, 
    # but for simplicity we rely on the label. 
    # If we wanted proba, we'd need CalibratedClassifierCV or use LogisticRegression)
    
    return prediction

# Custom CSS for a nicer look
custom_css = """

body {background-color: #f0f2f5;}

.gradio-container {max-width: 700px !important; margin-top: 50px !important;}

h1 {text-align: center; color: #333;}

"""

with gr.Blocks(css=custom_css, title="Sentiment Analyzer") as demo:
    gr.Markdown("# 📊 Sentiment Analysis System")
    gr.Markdown("Enter a review or sentence below to analyze its sentiment (Positive, Negative, or Neutral).")
    
    with gr.Row():
        input_text = gr.Textbox(
            label="Input Text", 
            placeholder="Type something here... (e.g., 'The product is amazing!')",
            lines=3
        )
    
    with gr.Row():
        analyze_btn = gr.Button("Analyze Sentiment", variant="primary")
        
    with gr.Row():
        output_label = gr.Label(label="Predicted Sentiment")

    analyze_btn.click(fn=analyze_sentiment, inputs=input_text, outputs=output_label)

    gr.Markdown("---")
    gr.Markdown("### Examples")
    gr.Examples(
        examples=[
            ["I absolutely love this! It's fantastic."],
            ["This is the worst experience I've ever had."],
            ["It's average, nothing special."],
        ],
        inputs=input_text
    )

if __name__ == "__main__":
    demo.launch(share=False)