harshj0506 commited on
Commit
91ed67a
1 Parent(s): c8d2a84

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -0
app.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from transformers import DistilBertTokenizerFast, DistilBertForSequenceClassification
3
+ import torch
4
+ import torch.nn.functional as F
5
+
6
+ # Load the fine-tuned model and tokenizer
7
+ model_path = "finetuned_model"
8
+ tokenizer_path = "finetuned_tokenizer"
9
+
10
+ @st.cache_resource
11
+ def load_model():
12
+ model = DistilBertForSequenceClassification.from_pretrained(model_path)
13
+ tokenizer = DistilBertTokenizerFast.from_pretrained(tokenizer_path)
14
+ return model, tokenizer
15
+
16
+ model, tokenizer = load_model()
17
+
18
+ def predict_sentiment(text):
19
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
20
+ model.to(device)
21
+
22
+ tokenized = tokenizer(text, truncation=True, padding=True, return_tensors='pt').to(device)
23
+ outputs = model(**tokenized)
24
+
25
+ probs = F.softmax(outputs.logits, dim=-1)
26
+ preds = torch.argmax(outputs.logits, dim=-1).item()
27
+ probs_max = probs.max().detach().cpu().numpy()
28
+
29
+ prediction = "Positive" if preds == 1 else "Negative"
30
+ return prediction, probs_max * 100
31
+
32
+ st.title("Sentiment Analysis App")
33
+ text = st.text_area("Enter your text:")
34
+
35
+ if st.button("Predict Sentiment"):
36
+ if text:
37
+ sentiment, confidence = predict_sentiment(text)
38
+ st.write(f"Sentiment: {sentiment}")
39
+ st.write(f"Confidence: {confidence:.2f}%")
40
+ else:
41
+ st.write("Please enter some text.")