amariayudha commited on
Commit
a4e0170
·
verified ·
1 Parent(s): 4da7830

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -0
app.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import torch
3
+ from transformers import BertTokenizer, BertForSequenceClassification
4
+
5
+ # Set the title of the app
6
+ st.title('Sentiment Analysis with BERT')
7
+
8
+ # Load the tokenizer and model
9
+ model_dir = './saved_model/' # Update this path if your model is saved elsewhere
10
+
11
+ @st.cache_resource
12
+ def load_model():
13
+ tokenizer = BertTokenizer.from_pretrained(model_dir)
14
+ model = BertForSequenceClassification.from_pretrained(model_dir)
15
+ model.eval()
16
+ # Move the model to the appropriate device
17
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
18
+ model.to(device)
19
+ return tokenizer, model, device
20
+
21
+ tokenizer, model, device = load_model()
22
+
23
+ # Function to perform sentiment analysis
24
+ def predict_sentiment(texts):
25
+ # Tokenize and encode the texts
26
+ inputs = tokenizer(
27
+ texts,
28
+ padding=True,
29
+ truncation=True,
30
+ max_length=128,
31
+ return_tensors='pt'
32
+ )
33
+
34
+ # Move inputs to the same device as the model
35
+ inputs = {key: val.to(device) for key, val in inputs.items()}
36
+
37
+ # Perform inference
38
+ with torch.no_grad():
39
+ outputs = model(**inputs)
40
+ logits = outputs.logits
41
+ probabilities = torch.softmax(logits, dim=-1)
42
+ predicted_classes = torch.argmax(probabilities, dim=-1)
43
+ confidences = torch.max(probabilities, dim=-1).values
44
+
45
+ # Map predictions to labels
46
+ label_map = {0: 'Negative', 1: 'Positive'}
47
+ predicted_labels = [label_map[pred.item()] for pred in predicted_classes]
48
+ confidences = confidences.cpu().numpy()
49
+
50
+ return predicted_labels, confidences
51
+
52
+ # Example texts (if you want to include them in the app)
53
+ example_texts = [
54
+ "The bouquet was absolutely stunning! Fresh flowers and beautiful arrangement.",
55
+ "Delivery was late and the flowers were wilted. Very disappointed.",
56
+ "Great service and reasonable prices. Will order again!",
57
+ "The flowers didn't look like the picture at all. False advertising.",
58
+ "Prompt delivery and the roses lasted for weeks. Excellent quality!",
59
+ "Customer service was unhelpful when I had an issue with my order.",
60
+ "The arrangement was okay, but overpriced for what I received.",
61
+ "Impressed with the variety of flowers available. Something for every occasion!",
62
+ "The online ordering process was confusing and frustrating.",
63
+ "Received compliments on the centerpiece all night. Thank you for making our event special!",
64
+ ]
65
+
66
+ # Add a select box for example texts
67
+ selected_example = st.selectbox("Or select an example text:", [""] + example_texts)
68
+
69
+ # Text input from the user
70
+ if selected_example != "":
71
+ user_input = selected_example
72
+ else:
73
+ user_input = st.text_area("Enter text for sentiment analysis:", "")
74
+
75
+ if st.button("Analyze"):
76
+ if user_input.strip() == "":
77
+ st.warning("Please enter text to analyze.")
78
+ else:
79
+ with st.spinner('Analyzing...'):
80
+ # Since the function expects a list of texts, wrap the user_input in a list
81
+ labels, confidences = predict_sentiment([user_input])
82
+ label = labels[0]
83
+ confidence = confidences[0]
84
+ st.success(f"Predicted Sentiment: **{label}**")
85
+ st.info(f"Confidence: {confidence * 100:.2f}%")
86
+ st.write(f"Text: {user_input}")