coderwithcoffee/EXPERIMENTS
0
1import streamlit as st2import requests3import json4 5st.set_page_config(6 page_title="Sentiment Analysis App",7 page_icon="๐",8 layout="centered"9)10 11st.title("Sentiment Analysis App")12st.write("Enter text to analyze its sentiment using Hugging Face's API")13 14# API credentials input15api_key = st.text_input("Enter your Hugging Face API key:", type="password", help="Your Hugging Face API token")16 17# Model selection18model_options = {19 "DistilBERT (SST-2)": "distilbert/distilbert-base-uncased-finetuned-sst-2-english",20 "Twitter-roBERTa-base": "cardiffnlp/twitter-roberta-base-sentiment",21 "BERT-base-multilingual": "nlptown/bert-base-multilingual-uncased-sentiment"22}23selected_model = st.selectbox("Select a sentiment analysis model:", options=list(model_options.keys()))24 25# Text input area26text_input = st.text_area("Enter text to analyze:", height=150)27 28# Function to call the Hugging Face API29def analyze_sentiment(text, model, api_key):30 API_URL = f"https://api-inference.huggingface.co/models/{model}"31 headers = {32 "Authorization": f"Bearer {api_key}"33 }34 35 payload = {36 "inputs": text,37 }38 39 try:40 response = requests.post(API_URL, headers=headers, json=payload)41 return response.json()42 except Exception as e:43 return {"error": str(e)}44 45# Submit button46if st.button("Analyze Sentiment"):47 if not api_key:48 st.error("Please enter your Hugging Face API key")49 elif not text_input:50 st.error("Please enter some text to analyze")51 else:52 with st.spinner("Analyzing sentiment..."):53 selected_model_path = model_options[selected_model]54 result = analyze_sentiment(text_input, selected_model_path, api_key)55 56 # Process and display results57 try:58 if "error" in result:59 st.error(f"Error: {result['error']}")60 elif isinstance(result, list) and len(result) > 0:61 # Process the results62 if isinstance(result[0], list):63 items = result[0]64 else:65 items = result66 67 # Find the highest scoring sentiment68 highest_item = max(items, key=lambda x: x['score'])69 score = highest_item['score']70 label = highest_item['label'].lower()71 72 # Display emoji based on sentiment and score73 st.subheader("Sentiment:")74 col1, col2 = st.columns([1, 3])75 76 # Select emoji based on sentiment label and score77 if 'positive' in label or 'pos' in label or '5' in label or '4' in label:78 if score > 0.9:79 emoji = "๐"80 elif score > 0.7:81 emoji = "๐"82 else:83 emoji = "๐"84 sentiment_text = f"Positive ({score:.2f})"85 elif 'negative' in label or 'neg' in label or '1' in label or '2' in label:86 if score > 0.9:87 emoji = "๐ก"88 elif score > 0.7:89 emoji = "๐ "90 else:91 emoji = "โน"92 sentiment_text = f"Negative ({score:.2f})"93 else: # neutral or '3' in label94 emoji = "๐"95 sentiment_text = f"Neutral ({score:.2f})"96 97 with col1:98 st.markdown(f"<h1 style='font-size:4rem; text-align:center;'>{emoji}</h1>", unsafe_allow_html=True)99 with col2:100 st.markdown(f"<h2>{sentiment_text}</h2>", unsafe_allow_html=True)101 102 # Add confidence meter103 st.progress(score)104 else:105 st.warning("Unexpected response format. Please check your API key and try again.")106 st.json(result)107 except Exception as e:108 st.error(f"Error processing results: {str(e)}")109 st.json(result)110 111# Footer112st.markdown("---")113st.markdown("Built with Streamlit and Hugging Face API")