Tahir5 commited on
Commit
886afc7
Β·
verified Β·
1 Parent(s): 1c96590

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -2
app.py CHANGED
@@ -1,4 +1,54 @@
1
  import streamlit as st
 
 
 
 
2
 
3
- x = st.slider('Select a value')
4
- st.write(x, 'squared is', x * x)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer, AutoConfig
3
+ import numpy as np
4
+ from scipy.special import softmax
5
+ from collections import Counter
6
 
7
+ # Load model and tokenizer
8
+ MODEL = "cardiffnlp/twitter-roberta-base-sentiment-latest"
9
+ tokenizer = AutoTokenizer.from_pretrained(MODEL)
10
+ config = AutoConfig.from_pretrained(MODEL)
11
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL)
12
+
13
+ def analyze_sentiment_for_sentences(sentences):
14
+ sentiments = []
15
+ for sentence in sentences:
16
+ encoded_input = tokenizer(sentence, return_tensors='pt')
17
+ output = model(**encoded_input)
18
+ scores = output[0][0].detach().numpy()
19
+ scores = softmax(scores)
20
+ highest_sentiment_idx = np.argmax(scores)
21
+ highest_sentiment_label = config.id2label[highest_sentiment_idx]
22
+ sentiments.append(highest_sentiment_label)
23
+ return sentiments
24
+
25
+ def calculate_sentiment_percentages(sentiments):
26
+ sentiment_counts = Counter(sentiments)
27
+ total_sentiments = len(sentiments)
28
+ sentiment_percentages = {"😊 positive": 0, "😐 neutral": 0, "πŸ˜” negative": 0}
29
+ for sentiment, count in sentiment_counts.items():
30
+ if sentiment == "positive":
31
+ sentiment_percentages["😊 positive"] = (count / total_sentiments) * 100
32
+ elif sentiment == "neutral":
33
+ sentiment_percentages["😐 neutral"] = (count / total_sentiments) * 100
34
+ else:
35
+ sentiment_percentages["πŸ˜” negative"] = (count / total_sentiments) * 100
36
+ return sentiment_percentages
37
+
38
+ # Streamlit UI
39
+ st.title("✨ Sentiment Analysis Web App")
40
+ st.write("Enter sentences below to analyze their sentiment.")
41
+
42
+ # User input
43
+ user_input = st.text_area("Enter sentences (one per line):")
44
+ if st.button("Analyze Sentiment"):
45
+ if user_input.strip():
46
+ sentences = user_input.split("\n")
47
+ sentences = [s.strip() for s in sentences if s.strip()]
48
+ sentiments = analyze_sentiment_for_sentences(sentences)
49
+ sentiment_percentages = calculate_sentiment_percentages(sentiments)
50
+
51
+ st.subheader("πŸ“Š Sentiment Analysis Results")
52
+ st.write(sentiment_percentages)
53
+ else:
54
+ st.warning("⚠️ Please enter at least one sentence.")