Update with examples and cleaner logic
Browse files
app.py
CHANGED
|
@@ -2,80 +2,132 @@ import gradio as gr
|
|
| 2 |
import torch
|
| 3 |
from transformers import DebertaV2Model, DebertaV2Config, AutoTokenizer, PreTrainedModel
|
| 4 |
from transformers.models.deberta.modeling_deberta import ContextPooler
|
| 5 |
-
from transformers import pipeline
|
| 6 |
import torch.nn as nn
|
| 7 |
|
| 8 |
-
#
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
#
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
def
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
def analyze(text):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
# Tokenize
|
| 58 |
-
inputs = tokenizer(text,
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
return {
|
| 70 |
-
'Positive': f"{
|
| 71 |
'Sent-Subj OBJ': f"{p1[0]:.2%}", 'Sent-Subj SUBJ': f"{p1[1]:.2%}",
|
| 72 |
'TextOnly OBJ': f"{p2[0]:.2%}", 'TextOnly SUBJ': f"{p2[1]:.2%}"
|
| 73 |
}
|
| 74 |
|
| 75 |
-
#
|
| 76 |
-
theme
|
| 77 |
-
|
| 78 |
-
with gr.Blocks(theme=theme, css="""
|
| 79 |
#result_table td { padding: 8px; font-size: 1rem; }
|
| 80 |
#header { text-align: center; font-size: 2rem; font-weight: bold; margin-bottom: 10px; }
|
| 81 |
""") as demo:
|
|
@@ -90,9 +142,16 @@ with gr.Blocks(theme=theme, css="""
|
|
| 90 |
table = gr.Dataframe(headers=["Metric", "Value"], datatype=["str","str"], interactive=False, elem_id="result_table")
|
| 91 |
with gr.TabItem("About ℹ️"):
|
| 92 |
gr.Markdown("This dashboard uses two DeBERTa-based models (with and without sentiment integration) to detect subjectivity, alongside sentiment scores from an XLM-RoBERTa model.")
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
# Link inputs to outputs
|
| 95 |
btn.click(fn=analyze, inputs=txt, outputs=[chart, table])
|
| 96 |
|
| 97 |
-
|
| 98 |
-
demo.queue().launch(server_name="0.0.0.0", share=True)
|
|
|
|
| 2 |
import torch
|
| 3 |
from transformers import DebertaV2Model, DebertaV2Config, AutoTokenizer, PreTrainedModel
|
| 4 |
from transformers.models.deberta.modeling_deberta import ContextPooler
|
| 5 |
+
from transformers import pipeline, AutoModelForSequenceClassification
|
| 6 |
import torch.nn as nn
|
| 7 |
|
| 8 |
+
# Define the model and tokenizer
|
| 9 |
+
model_card = "microsoft/mdeberta-v3-base"
|
| 10 |
+
subjectivity_only_model = "MatteoFasulo/mdeberta-v3-base-subjectivity-multilingual-no-arabic"
|
| 11 |
+
sentiment_model = "MatteoFasulo/mdeberta-v3-base-subjectivity-sentiment-multilingual-no-arabic"
|
| 12 |
+
|
| 13 |
+
# Define some examples for the Gradio interface (cached to run on-the-fly)
|
| 14 |
+
examples = [
|
| 15 |
+
['Example1'],
|
| 16 |
+
['Example2'],
|
| 17 |
+
['Example3'],
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
# Custom model class for combining sentiment analysis with subjectivity detection
|
| 21 |
+
class CustomModel(PreTrainedModel):
|
| 22 |
+
config_class = DebertaV2Config
|
| 23 |
+
|
| 24 |
+
def __init__(self, config, sentiment_dim=3, num_labels=2, *args, **kwargs):
|
| 25 |
+
super().__init__(config, *args, **kwargs)
|
| 26 |
+
self.deberta = DebertaV2Model(config)
|
| 27 |
+
self.pooler = ContextPooler(config)
|
| 28 |
+
output_dim = self.pooler.output_dim
|
| 29 |
+
self.dropout = nn.Dropout(0.1)
|
| 30 |
+
|
| 31 |
+
self.classifier = nn.Linear(output_dim + sentiment_dim, num_labels)
|
| 32 |
+
|
| 33 |
+
def forward(self, input_ids, positive, neutral, negative, token_type_ids=None, attention_mask=None, labels=None):
|
| 34 |
+
outputs = self.deberta(input_ids=input_ids, attention_mask=attention_mask)
|
| 35 |
+
|
| 36 |
+
encoder_layer = outputs[0]
|
| 37 |
+
pooled_output = self.pooler(encoder_layer)
|
| 38 |
+
|
| 39 |
+
# Sentiment features as a single tensor
|
| 40 |
+
sentiment_features = torch.stack((positive, neutral, negative), dim=1) # Shape: (batch_size, 3)
|
| 41 |
+
|
| 42 |
+
# Combine CLS embedding with sentiment features
|
| 43 |
+
combined_features = torch.cat((pooled_output, sentiment_features), dim=1)
|
| 44 |
+
|
| 45 |
+
# Classification head
|
| 46 |
+
logits = self.classifier(self.dropout(combined_features))
|
| 47 |
+
|
| 48 |
+
return {'logits': logits}
|
| 49 |
+
|
| 50 |
+
# Load the pre-trained tokenizer
|
| 51 |
+
def load_tokenizer(model_name: str):
|
| 52 |
+
return AutoTokenizer.from_pretrained(model_name)
|
| 53 |
+
|
| 54 |
+
# Load the pre-trained model
|
| 55 |
+
def load_model(model_name: str):
|
| 56 |
+
|
| 57 |
+
if 'sentiment' in model_name:
|
| 58 |
+
config = DebertaV2Config.from_pretrained(
|
| 59 |
+
model_name,
|
| 60 |
+
num_labels=2,
|
| 61 |
+
id2label={0: 'OBJ', 1: 'SUBJ'},
|
| 62 |
+
label2id={'OBJ': 0, 'SUBJ': 1},
|
| 63 |
+
output_attentions=False,
|
| 64 |
+
output_hidden_states=False
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
model = CustomModel(config=config, sentiment_dim=3, num_labels=2).from_pretrained(model_name)
|
| 68 |
+
|
| 69 |
+
else:
|
| 70 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 71 |
+
model_name,
|
| 72 |
+
num_labels=2,
|
| 73 |
+
id2label={0: 'OBJ', 1: 'SUBJ'},
|
| 74 |
+
label2id={'OBJ': 0, 'SUBJ': 1},
|
| 75 |
+
output_attentions=False,
|
| 76 |
+
output_hidden_states=False
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
return model
|
| 80 |
+
|
| 81 |
+
# Get sentiment values using a pre-trained sentiment analysis model
|
| 82 |
+
def get_sentiment_values(text: str):
|
| 83 |
+
pipe = pipeline("sentiment-analysis", model="cardiffnlp/twitter-xlm-roberta-base-sentiment", tokenizer="cardiffnlp/twitter-xlm-roberta-base-sentiment", top_k=None)
|
| 84 |
+
sentiments = pipe(text)[0]
|
| 85 |
+
return {k:v for k,v in [(list(sentiment.values())[0], list(sentiment.values())[1]) for sentiment in sentiments]}
|
| 86 |
+
|
| 87 |
+
# Modify the predict_subjectivity function to return additional information
|
| 88 |
def analyze(text):
|
| 89 |
+
# Extract sentiment values
|
| 90 |
+
sentiment_values = get_sentiment_values(text)
|
| 91 |
+
|
| 92 |
+
# Load the tokenizer and model
|
| 93 |
+
tokenizer = load_tokenizer(model_card)
|
| 94 |
+
sentiment_model = load_model(sentiment_model)
|
| 95 |
+
subjectivity_model = load_model(subjectivity_only_model)
|
| 96 |
+
|
| 97 |
# Tokenize
|
| 98 |
+
inputs = tokenizer(text, padding=True, truncation=True, max_length=256, return_tensors='pt')
|
| 99 |
+
|
| 100 |
+
# Get the sentiment values
|
| 101 |
+
positive = sentiment_values['positive']
|
| 102 |
+
neutral = sentiment_values['neutral']
|
| 103 |
+
negative = sentiment_values['negative']
|
| 104 |
+
# Convert sentiment values to tensors
|
| 105 |
+
inputs['positive'] = torch.tensor(positive).unsqueeze(0)
|
| 106 |
+
inputs['neutral'] = torch.tensor(neutral).unsqueeze(0)
|
| 107 |
+
inputs['negative'] = torch.tensor(negative).unsqueeze(0)
|
| 108 |
+
|
| 109 |
+
# Get the sentiment model outputs
|
| 110 |
+
outputs1 = sentiment_model(**inputs)
|
| 111 |
+
logits1 = outputs1.get('logits')
|
| 112 |
+
|
| 113 |
+
# Calculate probabilities using softmax
|
| 114 |
+
p1 = torch.nn.functional.softmax(logits1, dim=1)[0]
|
| 115 |
+
|
| 116 |
+
# Get the subjectivity model outputs
|
| 117 |
+
outputs2 = subjectivity_model(**inputs)
|
| 118 |
+
logits2 = outputs2.get('logits')
|
| 119 |
+
# Calculate probabilities using softmax
|
| 120 |
+
p2 = torch.nn.functional.softmax(logits2, dim=1)[0]
|
| 121 |
+
|
| 122 |
+
# Format the output
|
| 123 |
return {
|
| 124 |
+
'Positive': f"{positive:.2%}", 'Neutral': f"{neutral:.2%}", 'Negative': f"{negative:.2%}",
|
| 125 |
'Sent-Subj OBJ': f"{p1[0]:.2%}", 'Sent-Subj SUBJ': f"{p1[1]:.2%}",
|
| 126 |
'TextOnly OBJ': f"{p2[0]:.2%}", 'TextOnly SUBJ': f"{p2[1]:.2%}"
|
| 127 |
}
|
| 128 |
|
| 129 |
+
# Update the Gradio interface
|
| 130 |
+
with gr.Blocks(theme=gr.themes.Soft(), css="""
|
|
|
|
|
|
|
| 131 |
#result_table td { padding: 8px; font-size: 1rem; }
|
| 132 |
#header { text-align: center; font-size: 2rem; font-weight: bold; margin-bottom: 10px; }
|
| 133 |
""") as demo:
|
|
|
|
| 142 |
table = gr.Dataframe(headers=["Metric", "Value"], datatype=["str","str"], interactive=False, elem_id="result_table")
|
| 143 |
with gr.TabItem("About ℹ️"):
|
| 144 |
gr.Markdown("This dashboard uses two DeBERTa-based models (with and without sentiment integration) to detect subjectivity, alongside sentiment scores from an XLM-RoBERTa model.")
|
| 145 |
+
with gr.Row():
|
| 146 |
+
gr.Markdown("### Examples:")
|
| 147 |
+
gr.Examples(
|
| 148 |
+
examples=examples,
|
| 149 |
+
inputs=txt,
|
| 150 |
+
label="Examples",
|
| 151 |
+
elem_id="example_list",
|
| 152 |
+
cache_examples=True,
|
| 153 |
+
)
|
| 154 |
# Link inputs to outputs
|
| 155 |
btn.click(fn=analyze, inputs=txt, outputs=[chart, table])
|
| 156 |
|
| 157 |
+
demo.queue().launch(server_name="0.0.0.0", share=True)
|
|
|