nadish1210's picture
Upload 8 files
f75d9fd verified
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)