Spaces:
Sleeping
Sleeping
File size: 2,506 Bytes
6e393a5 793288c 6e393a5 793288c 6e393a5 793288c 6e393a5 793288c | 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 | 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}")
|