Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
3 |
+
import torch
|
4 |
+
import torch.nn.functional as F
|
5 |
+
|
6 |
+
#Initializing the tuned BERT model and tokenizer.
|
7 |
+
model = AutoModelForSequenceClassification.from_pretrained("BERTTuned")
|
8 |
+
tokenizer = AutoTokenizer.from_pretrained("Tokenizer")
|
9 |
+
|
10 |
+
def predict_sentiment(text):
|
11 |
+
#Tokenizing the input text and preparing it for the model.
|
12 |
+
inputs = tokenizer(text, padding=True, truncation=True, max_length=512, return_tensors="pt")
|
13 |
+
|
14 |
+
#Generating predictions from the model.
|
15 |
+
with torch.no_grad():
|
16 |
+
outputs = model(**inputs)
|
17 |
+
logits = outputs.logits
|
18 |
+
|
19 |
+
#Converting the model logits to probabilities for easier interpretation.
|
20 |
+
probabilities = F.softmax(logits, dim=1).squeeze()
|
21 |
+
|
22 |
+
#Mapping the models output to something readable.
|
23 |
+
sentiment_mapping = {0: "Negative", 1: "Positive"}
|
24 |
+
predicted_class_index = torch.argmax(probabilities).item()
|
25 |
+
predicted_probability = probabilities[predicted_class_index].item()
|
26 |
+
predicted_sentiment = sentiment_mapping[predicted_class_index]
|
27 |
+
|
28 |
+
#Returning the predicted sentiment and probability.
|
29 |
+
return predicted_sentiment, f"{predicted_probability:.4f}"
|
30 |
+
|
31 |
+
#Setting up a Gradio interface.
|
32 |
+
iface = gr.Interface(
|
33 |
+
fn=predict_sentiment,
|
34 |
+
inputs=gr.Textbox(lines=2, placeholder="Enter text here..."),
|
35 |
+
outputs=[gr.Label(label="Predicted Sentiment"), gr.Textbox(label="Probability")],
|
36 |
+
title="Sentiment Analysis",
|
37 |
+
description="Enter a text to predict its sentiment.",
|
38 |
+
allow_flagging="never"
|
39 |
+
)
|
40 |
+
|
41 |
+
if __name__ == "__main__":
|
42 |
+
iface.launch()
|