ConSenBert / app.py
SoloAlphus's picture
Update app.py
a2c2c8c verified
import gradio as gr
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
from scipy.special import softmax
model_name = "SoloAlphus/ConSenBert-V1"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)
def analyze_sentiment(text, entity):
input_text = text + "[SEP]" + entity
inputs = tokenizer(input_text, return_tensors="pt", truncation=True, max_length=512, padding=True)
with torch.no_grad():
outputs = model(**inputs)
scores = outputs.logits.squeeze().numpy()
scores = softmax(scores)
labels = ['Negative', 'Neutral', 'Positive']
result = {label: float(score) for label, score in zip(labels, scores)}
predicted_sentiment = max(result, key=result.get)
return result, predicted_sentiment
def gradio_interface(comment, entity):
sentiment_scores, predicted_sentiment = analyze_sentiment(comment, entity)
return sentiment_scores, predicted_sentiment
examples = [
["abc product looks much better compared to xyz product!", "xyz"],
["I love Apple for their out standing products in the market!", "Samsung"],
["Rekha is a good dancer, but Sheela is extraordinary when it comes to dancing!", "Sheela"]
]
interface = gr.Interface(fn=gradio_interface,
inputs=["text", "text"],
outputs=["json", "text"],
title="ConSenBERT - Context based Sentiment Analysis using RoBERTa",
description="Enter a comment and an entity to analyze the sentiment. \n \n Do like my model and space if you like my work! 🤗",
examples=examples)
interface.launch()