Test_Sentiments / app.py
NitinSethi786's picture
Update app.py
793288c verified
Raw History Blame Contribute Delete
2.51 kB
import streamlit as st
from transformers import pipeline
from transformers.pipelines import PipelineException
st.set_page_config(page_title="Sentiment Tester", layout="centered")
st.title("Sentiment Tester")
st.write("Enter text below and get a model's sentiment prediction (positive / negative).")
# Cache the pipeline so it doesn't reload on every interaction
@st.cache_resource
def load_sentiment_pipeline(model_name: str = "distilbert-base-uncased-finetuned-sst-2-english"):
try:
return pipeline("sentiment-analysis", model=model_name)
except Exception as e:
raise PipelineException(f"Failed to load model {model_name}: {e}")
model_option = st.selectbox(
"Choose model (smaller = faster):",
(
"distilbert-base-uncased-finetuned-sst-2-english",
"nlptown/bert-base-multilingual-uncased-sentiment"
)
)
with st.spinner("Loading model (this happens once)..."):
try:
sentiment_analyzer = load_sentiment_pipeline(model_option)
except Exception as e:
st.error(f"Error loading model: {e}")
st.stop()
text = st.text_area("Enter text to analyze:", height=150)
col1, col2 = st.columns([3, 1])
with col2:
run_btn = st.button("Analyze")
if run_btn:
if not text or not text.strip():
st.warning("Please enter some text first.")
else:
with st.spinner("Analyzing..."):
try:
results = sentiment_analyzer(text)
# pipeline returns a list for single input in new transformers versions
if isinstance(results, list) and len(results) > 0:
r = results[0]
else:
r = results
label = r.get("label", "N/A")
score = r.get("score", None)
st.subheader("Result")
st.write(f"**Label:** {label}")
if score is not None:
st.write(f"**Confidence:** {score:.3f}")
# Friendly interpretation
if "neg" in label.lower() or "1" in str(label).lower():
st.info("Interpretation: Mostly negative sentiment.")
elif "pos" in label.lower() or "5" in str(label).lower():
st.success("Interpretation: Mostly positive sentiment.")
else:
st.write("Interpretation: Neutral / mixed / model-specific label.")
except Exception as e:
st.error(f"Error while analyzing: {e}")