playground-11 / app.py
orlandopozo's picture
Update footer
a998e33 verified
import streamlit as st
from transformers import AutoTokenizer, TFAutoModelForSequenceClassification
import tensorflow as tf
# Constants
MODEL_NAME = "distilbert-base-uncased-finetuned-sst-2-english" # Pre-trained model for sentiment analysis
# Load the tokenizer and model
@st.cache_resource
def load_model():
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = TFAutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
return tokenizer, model
# Function to classify text
def classify_text(input_text, tokenizer, model):
inputs = tokenizer(input_text, return_tensors="tf", truncation=True, padding=True)
outputs = model(inputs)
logits = outputs.logits
probabilities = tf.nn.softmax(logits, axis=-1)
return probabilities.numpy()
# Streamlit UI
def main():
st.title("Hugging Face + TensorFlow: Sentiment Analysis Demo")
st.write("Analyze the sentiment of a given text using a Hugging Face pre-trained model with TensorFlow.")
# User input
user_input = st.text_area("Enter your text below:", height=150)
if st.button("Analyze"):
if user_input.strip():
with st.spinner("Analyzing sentiment..."):
tokenizer, model = load_model()
probabilities = classify_text(user_input, tokenizer, model)
st.success("Analysis Complete!")
# Display probabilities
labels = ["Negative", "Positive"]
results = {labels[i]: float(probabilities[0][i]) for i in range(len(labels))}
st.write("### Sentiment Probabilities")
st.json(results)
# Display prediction
predicted_label = labels[tf.argmax(probabilities[0])]
st.write(f"### Predicted Sentiment: `{predicted_label}`")
else:
st.warning("Please enter some text to analyze.")
# Footer
st.markdown("---")
st.markdown("**Built with Hugging Face Transformers and TensorFlow.**")
if __name__ == "__main__":
main()