File size: 2,357 Bytes
0f1c341
aaf9b07
6487a45
aaf9b07
 
 
 
 
 
 
 
 
 
 
 
 
 
6487a45
aaf9b07
6487a45
aaf9b07
 
6487a45
 
bca5a82
aaf9b07
6487a45
aaf9b07
6487a45
aaf9b07
6487a45
cdf5643
bca5a82
aaf9b07
 
cbb33a8
 
aaf9b07
 
741c64f
 
6487a45
 
741c64f
aaf9b07
6608ecd
767816d
 
 
 
 
 
4fffde5
1
2
3
4
5
6
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
52
53
import gradio as gr
from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
import time

model_name = "ethanrom/a2"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)

pretrained_model_name = "roberta-large-mnli"
pretrained_tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name)
pretrained_model = pipeline("zero-shot-classification", model=pretrained_model_name, tokenizer=pretrained_tokenizer)
candidate_labels = ["negative", "positive", "no impact", "mixed"]


def predict_sentiment(text_input, model_selection):
    if model_selection == "Fine-tuned":
        inputs = tokenizer.encode_plus(text_input, return_tensors='pt')
        start_time = time.time()
        outputs = model(**inputs)
        end_time = time.time()
        logits = outputs.logits.detach().cpu().numpy()[0]
        predicted_class = int(logits.argmax())
        inference_time = end_time - start_time
        model_size = model.num_parameters()
        return candidate_labels[predicted_class], inference_time, model_size
    else:
        start_time = time.time()
        result = pretrained_model(text_input, candidate_labels)
        end_time = time.time()
        predicted_class = result["labels"][0]
        inference_time = end_time - start_time
        model_size = pretrained_model.model.num_parameters()
        return predicted_class, inference_time, model_size

inputs = [
    gr.inputs.Textbox("Enter text"),
    gr.inputs.Dropdown(["Pretrained", "Fine-tuned"], label="Select model"),
]

outputs = [
    gr.outputs.Textbox(label="Predicted Sentiment"),
    gr.outputs.Textbox(label="Inference Time (s)"),
    gr.outputs.Textbox(label="Model Size (params)"),
]

gr.Interface(fn=predict_sentiment, inputs=inputs, outputs=outputs, title="Sentiment Analysis", description="roberta-large-mnli fine tuned with poem_sentiment dataset for sentiment analysis", examples=[
        ["max laid his hand upon the old man's arm", "Pretrained"],
        ["the red sword sealed their vows!", "Fine-tuned"],
        ["and that is why, the lonesome day,", "Pretrained"],
        ["it flows so long as falls the rain", "Fine-tuned"],
        ["thy hands all cunning arts that women prize", "Pretrained"],
        ["on us lift up the light", "Fine-tuned"],
    ],).launch();