Update app.py
Browse files
app.py
CHANGED
@@ -2,39 +2,27 @@ import gradio as gr
|
|
2 |
from transformers import BertForSequenceClassification, BertTokenizer
|
3 |
import torch
|
4 |
|
5 |
-
# Load the model and tokenizer outside the prediction function, this ensures they are loaded once and used during inference
|
6 |
model_name = "ArunNyp7/sentimentclassifier-finetuned-bert"
|
7 |
model = BertForSequenceClassification.from_pretrained(model_name)
|
8 |
tokenizer = BertTokenizer.from_pretrained(model_name)
|
9 |
|
10 |
-
# Define the prediction function
|
11 |
def classify_sentiment(text):
|
12 |
-
# Tokenize the input text
|
13 |
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=256)
|
14 |
|
15 |
-
# Perform inference
|
16 |
with torch.no_grad():
|
17 |
outputs = model(**inputs)
|
18 |
logits = outputs.logits
|
19 |
prediction = torch.argmax(logits, dim=-1).item()
|
20 |
|
21 |
-
# Map the prediction index to the corresponding sentiment label
|
22 |
labels = {0: "Negative", 1: "Neutral", 2: "Positive"}
|
23 |
return labels[prediction]
|
24 |
|
25 |
-
# Define Gradio Interface using Blocks (this ensures everything is inside a correct Gradio context)
|
26 |
with gr.Blocks() as demo:
|
27 |
gr.Markdown("### Sentiment Classification using Fine-Tuned BERT Model")
|
28 |
|
29 |
-
# Input box for the text
|
30 |
text_input = gr.Textbox(label="Enter Text", placeholder="Type here...", lines=2)
|
31 |
-
|
32 |
-
# Output label for the prediction
|
33 |
sentiment_output = gr.Label()
|
34 |
-
|
35 |
-
# Define the Button and its action
|
36 |
submit_btn = gr.Button("Classify Sentiment")
|
37 |
submit_btn.click(fn=classify_sentiment, inputs=text_input, outputs=sentiment_output)
|
38 |
|
39 |
-
# Launch the interface
|
40 |
demo.launch(share=False)
|
|
|
2 |
from transformers import BertForSequenceClassification, BertTokenizer
|
3 |
import torch
|
4 |
|
|
|
5 |
model_name = "ArunNyp7/sentimentclassifier-finetuned-bert"
|
6 |
model = BertForSequenceClassification.from_pretrained(model_name)
|
7 |
tokenizer = BertTokenizer.from_pretrained(model_name)
|
8 |
|
|
|
9 |
def classify_sentiment(text):
|
|
|
10 |
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=256)
|
11 |
|
|
|
12 |
with torch.no_grad():
|
13 |
outputs = model(**inputs)
|
14 |
logits = outputs.logits
|
15 |
prediction = torch.argmax(logits, dim=-1).item()
|
16 |
|
|
|
17 |
labels = {0: "Negative", 1: "Neutral", 2: "Positive"}
|
18 |
return labels[prediction]
|
19 |
|
|
|
20 |
with gr.Blocks() as demo:
|
21 |
gr.Markdown("### Sentiment Classification using Fine-Tuned BERT Model")
|
22 |
|
|
|
23 |
text_input = gr.Textbox(label="Enter Text", placeholder="Type here...", lines=2)
|
|
|
|
|
24 |
sentiment_output = gr.Label()
|
|
|
|
|
25 |
submit_btn = gr.Button("Classify Sentiment")
|
26 |
submit_btn.click(fn=classify_sentiment, inputs=text_input, outputs=sentiment_output)
|
27 |
|
|
|
28 |
demo.launch(share=False)
|