Spaces:
Runtime error
Runtime error
Add App
Browse files- emotion/app.py +78 -0
- emotion/class_names.txt +6 -0
- emotion/example_texts.txt +3 -0
- emotion/model.py +38 -0
- emotion/requirements.txt +4 -0
- emotion/roberta-base.pth +3 -0
emotion/app.py
ADDED
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
import torch
|
4 |
+
|
5 |
+
from model import create_roberta_model
|
6 |
+
from timeit import default_timer as timer
|
7 |
+
from typing import Tuple, Dict
|
8 |
+
|
9 |
+
# Setup class names
|
10 |
+
with open("class_names.txt", "r") as f:
|
11 |
+
class_names = [name.strip() for name in f.readlines()]
|
12 |
+
|
13 |
+
### Load example texts ###
|
14 |
+
example_texts = []
|
15 |
+
with open("example_texts.txt", "r") as file:
|
16 |
+
example_texts = [line.strip() for line in file.readlines()]
|
17 |
+
|
18 |
+
### Model and transforms preparation ###
|
19 |
+
# Create model and tokenizer
|
20 |
+
model, tokenizer = create_roberta_model(output_shape=len(class_names), print_summary=False)
|
21 |
+
|
22 |
+
# Load saved weights
|
23 |
+
model.load_state_dict(
|
24 |
+
torch.load(f="roberta-base.pth",
|
25 |
+
map_location=torch.device("cpu")) # load to CPU
|
26 |
+
)
|
27 |
+
|
28 |
+
### Predict function ###
|
29 |
+
def predict(text) -> Tuple[Dict, float]:
|
30 |
+
# Start a timer
|
31 |
+
start_time = timer()
|
32 |
+
|
33 |
+
# Set the model to eval
|
34 |
+
model.eval()
|
35 |
+
|
36 |
+
# Set up the inputs
|
37 |
+
inputs = tokenizer(text, padding="max_length", truncation=True, return_tensors='pt')
|
38 |
+
|
39 |
+
# Transform the input image for use with the model
|
40 |
+
X = tokenizer(**inputs).unsqueeze(0) # unsqueeze = add batch dimension on 0th index
|
41 |
+
|
42 |
+
# Put model into eval mode, make prediction
|
43 |
+
model.eval()
|
44 |
+
with torch.inference_mode():
|
45 |
+
# Pass tokenized text through the model and turn the prediction logits into probaiblities
|
46 |
+
pred_probs = torch.softmax(model(X).logits, dim=1)
|
47 |
+
|
48 |
+
# Create a prediction label and prediction probability dictionary
|
49 |
+
pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
|
50 |
+
|
51 |
+
# Calculate pred time
|
52 |
+
end_time = timer()
|
53 |
+
pred_time = round(end_time - start_time, 4)
|
54 |
+
|
55 |
+
# Return pred dict and pred time
|
56 |
+
return pred_labels_and_probs, pred_time
|
57 |
+
|
58 |
+
### 4. Gradio app ###
|
59 |
+
# Create title, description and article
|
60 |
+
title = "A roberta-base Classifier"
|
61 |
+
description = "[A roberta-base BERT based model](https://huggingface.co/roberta-base) text model to classify text on the [HuggingFace 🤗 dair-ai/emotion dataset](https://huggingface.co/datasets/dair-ai/emotion). [Source Code Found Here](https://colab.research.google.com/drive/1P7rfiDF1jfNHKmkB7WjHPi8PQBLQ4Ege?usp=sharing)"
|
62 |
+
article = "Built with [Gradio](https://github.com/gradio-app/gradio) and [PyTorch](https://pytorch.org/). [Source Code Found Here](https://colab.research.google.com/drive/1P7rfiDF1jfNHKmkB7WjHPi8PQBLQ4Ege?usp=sharing)"
|
63 |
+
|
64 |
+
# Create example list
|
65 |
+
example_list = [["examples/" + example] for example in os.listdir("examples")]
|
66 |
+
|
67 |
+
# Create the Gradio demo
|
68 |
+
demo = gr.Interface(fn=predict,
|
69 |
+
inputs=gr.Textbox(lines=2, placeholder="Type your text here..."),
|
70 |
+
outputs=[gr.Label(num_top_classes=5, label="Predictions"),
|
71 |
+
gr.Number(label="Prediction time (s)")],
|
72 |
+
examples=example_texts,
|
73 |
+
title=title,
|
74 |
+
description=description,
|
75 |
+
article=article)
|
76 |
+
|
77 |
+
# Launch the demo
|
78 |
+
demo.launch()
|
emotion/class_names.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
sadness
|
2 |
+
joy
|
3 |
+
love
|
4 |
+
anger
|
5 |
+
fear
|
6 |
+
surprise
|
emotion/example_texts.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
I'm feeling blue.
|
2 |
+
I hate driving to work!
|
3 |
+
I love walking in the park!
|
emotion/model.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torchinfo import summary
|
3 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
4 |
+
|
5 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
6 |
+
|
7 |
+
def model_input_wrapper(batch_size, sequence_length, tokenizer):
|
8 |
+
dummy_input_ids = torch.randint(0, tokenizer.vocab_size, (batch_size, sequence_length), dtype=torch.long)
|
9 |
+
dummy_attention_mask = torch.ones(batch_size, sequence_length, dtype=torch.long)
|
10 |
+
return {'input_ids': dummy_input_ids, 'attention_mask': dummy_attention_mask}
|
11 |
+
|
12 |
+
def create_roberta_model(output_shape:int=10, device=device, print_summary=True):
|
13 |
+
"""Creates a HuggingFace roberta-base model.
|
14 |
+
|
15 |
+
Args:
|
16 |
+
device: A torch.device
|
17 |
+
print_summary: A boolean to print the model summary
|
18 |
+
|
19 |
+
Returns:
|
20 |
+
A tuple of the model and tokenizer
|
21 |
+
"""
|
22 |
+
tokenizer = AutoTokenizer.from_pretrained('roberta-base')
|
23 |
+
model = AutoModelForSequenceClassification.from_pretrained('roberta-base')
|
24 |
+
|
25 |
+
# Partial Freeze to speed up training
|
26 |
+
for param in model.parameters():
|
27 |
+
param.requires_grad = False
|
28 |
+
|
29 |
+
for param in model.classifier.parameters():
|
30 |
+
param.requires_grad = True
|
31 |
+
|
32 |
+
model.classifier.out_proj = torch.nn.Linear(in_features=768, out_features=output_shape)
|
33 |
+
|
34 |
+
if print_summary:
|
35 |
+
sample_inputs = model_input_wrapper(1, 128, tokenizer)
|
36 |
+
print(summary(model, input_data=sample_inputs, verbose=0, col_names=["input_size", "output_size", "num_params", "trainable"], col_width=20, row_settings=["var_names"]))
|
37 |
+
|
38 |
+
return model.to(device), tokenizer
|
emotion/requirements.txt
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch==2.1.0
|
2 |
+
torchvision==0.16.0
|
3 |
+
gradio==3.50.2
|
4 |
+
transformers==4.35.0
|
emotion/roberta-base.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e5bd0ce37ac5ff9344629a01ecf8395078757659097cee9e3d7f7f7f0ed98f0f
|
3 |
+
size 498684833
|