File size: 4,464 Bytes
5e2be0b 4dda5cd 5e2be0b 4dda5cd |
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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
import streamlit as st
import requests
import json
st.set_page_config(
page_title="Sentiment Analysis App",
page_icon="π",
layout="centered"
)
st.title("Sentiment Analysis App")
st.write("Enter text to analyze its sentiment using Hugging Face's API")
# API credentials input
api_key = st.text_input("Enter your Hugging Face API key:", type="password", help="Your Hugging Face API token")
# Model selection
model_options = {
"DistilBERT (SST-2)": "distilbert/distilbert-base-uncased-finetuned-sst-2-english",
"Twitter-roBERTa-base": "cardiffnlp/twitter-roberta-base-sentiment",
"BERT-base-multilingual": "nlptown/bert-base-multilingual-uncased-sentiment"
}
selected_model = st.selectbox("Select a sentiment analysis model:", options=list(model_options.keys()))
# Text input area
text_input = st.text_area("Enter text to analyze:", height=150)
# Function to call the Hugging Face API
def analyze_sentiment(text, model, api_key):
API_URL = f"https://api-inference.huggingface.co/models/{model}"
headers = {
"Authorization": f"Bearer {api_key}"
}
payload = {
"inputs": text,
}
try:
response = requests.post(API_URL, headers=headers, json=payload)
return response.json()
except Exception as e:
return {"error": str(e)}
# Submit button
if st.button("Analyze Sentiment"):
if not api_key:
st.error("Please enter your Hugging Face API key")
elif not text_input:
st.error("Please enter some text to analyze")
else:
with st.spinner("Analyzing sentiment..."):
selected_model_path = model_options[selected_model]
result = analyze_sentiment(text_input, selected_model_path, api_key)
# Process and display results
try:
if "error" in result:
st.error(f"Error: {result['error']}")
elif isinstance(result, list) and len(result) > 0:
# Process the results
if isinstance(result[0], list):
items = result[0]
else:
items = result
# Find the highest scoring sentiment
highest_item = max(items, key=lambda x: x['score'])
score = highest_item['score']
label = highest_item['label'].lower()
# Display emoji based on sentiment and score
st.subheader("Sentiment:")
col1, col2 = st.columns([1, 3])
# Select emoji based on sentiment label and score
if 'positive' in label or 'pos' in label or '5' in label or '4' in label:
if score > 0.9:
emoji = "π"
elif score > 0.7:
emoji = "π"
else:
emoji = "π"
sentiment_text = f"Positive ({score:.2f})"
elif 'negative' in label or 'neg' in label or '1' in label or '2' in label:
if score > 0.9:
emoji = "π‘"
elif score > 0.7:
emoji = "π "
else:
emoji = "βΉ"
sentiment_text = f"Negative ({score:.2f})"
else: # neutral or '3' in label
emoji = "π"
sentiment_text = f"Neutral ({score:.2f})"
with col1:
st.markdown(f"<h1 style='font-size:4rem; text-align:center;'>{emoji}</h1>", unsafe_allow_html=True)
with col2:
st.markdown(f"<h2>{sentiment_text}</h2>", unsafe_allow_html=True)
# Add confidence meter
st.progress(score)
else:
st.warning("Unexpected response format. Please check your API key and try again.")
st.json(result)
except Exception as e:
st.error(f"Error processing results: {str(e)}")
st.json(result)
# Footer
st.markdown("---")
st.markdown("Built with Streamlit and Hugging Face API")
|