Spaces:
Runtime error
Runtime error
j-hartmann
commited on
Commit
•
6a48f6a
1
Parent(s):
a778510
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import pandas as pd
|
3 |
+
import numpy as np
|
4 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer
|
5 |
+
|
6 |
+
|
7 |
+
# summary function - test for single gradio function interfrace
|
8 |
+
def bulk_function(filename):
|
9 |
+
# Create class for data preparation
|
10 |
+
class SimpleDataset:
|
11 |
+
def __init__(self, tokenized_texts):
|
12 |
+
self.tokenized_texts = tokenized_texts
|
13 |
+
|
14 |
+
def __len__(self):
|
15 |
+
return len(self.tokenized_texts["input_ids"])
|
16 |
+
|
17 |
+
def __getitem__(self, idx):
|
18 |
+
return {k: v[idx] for k, v in self.tokenized_texts.items()}
|
19 |
+
|
20 |
+
# load tokenizer and model, create trainer
|
21 |
+
model_name = "j-hartmann/emotion-english-distilroberta-base"
|
22 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
23 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
24 |
+
trainer = Trainer(model=model)
|
25 |
+
print(filename, type(filename))
|
26 |
+
print(filename.name)
|
27 |
+
|
28 |
+
|
29 |
+
# check type of input file
|
30 |
+
if filename.name.split(".")[1] == "csv":
|
31 |
+
print("entered")
|
32 |
+
# read file, drop index if exists
|
33 |
+
df_input = pd.read_csv(filename.name, index_col=False)
|
34 |
+
if df_input.columns[0] == "Unnamed: 0":
|
35 |
+
df_input = df_input.drop("Unnamed: 0", axis=1)
|
36 |
+
elif filename.name.split(".")[1] == "xlsx":
|
37 |
+
df_input = pd.read_excel(filename.name, index_col=False)
|
38 |
+
# handle Unnamed
|
39 |
+
if df_input.columns[0] == "Unnamed: 0":
|
40 |
+
df_input = df_input.drop("Unnamed: 0", axis=1)
|
41 |
+
else:
|
42 |
+
return
|
43 |
+
|
44 |
+
|
45 |
+
# read csv
|
46 |
+
# even if index given, drop it
|
47 |
+
#df_input = pd.read_csv(filename.name, index_col=False)
|
48 |
+
#print("df_input", df_input)
|
49 |
+
|
50 |
+
# expect csv format to be in:
|
51 |
+
# 1: ID
|
52 |
+
# 2: Texts
|
53 |
+
# no index
|
54 |
+
# store ids in ordered list
|
55 |
+
ids = df_input[df_input.columns[0]].to_list()
|
56 |
+
|
57 |
+
# store sentences in ordered list
|
58 |
+
# expects sentences to be in second col
|
59 |
+
# of csv with two cols
|
60 |
+
lines_s = df_input[df_input.columns[1]].to_list()
|
61 |
+
|
62 |
+
# Tokenize texts and create prediction data set
|
63 |
+
tokenized_texts = tokenizer(lines_s,truncation=True,padding=True)
|
64 |
+
pred_dataset = SimpleDataset(tokenized_texts)
|
65 |
+
|
66 |
+
# Run predictions -> predict whole df
|
67 |
+
predictions = trainer.predict(pred_dataset)
|
68 |
+
|
69 |
+
# Transform predictions to labels
|
70 |
+
preds = predictions.predictions.argmax(-1)
|
71 |
+
labels = pd.Series(preds).map(model.config.id2label)
|
72 |
+
scores = (np.exp(predictions[0])/np.exp(predictions[0]).sum(-1,keepdims=True)).max(1)
|
73 |
+
|
74 |
+
# round scores
|
75 |
+
scores_rounded = [round(score, 3) for score in scores]
|
76 |
+
|
77 |
+
# scores raw
|
78 |
+
temp = (np.exp(predictions[0])/np.exp(predictions[0]).sum(-1,keepdims=True))
|
79 |
+
|
80 |
+
# container
|
81 |
+
anger = []
|
82 |
+
disgust = []
|
83 |
+
fear = []
|
84 |
+
joy = []
|
85 |
+
neutral = []
|
86 |
+
sadness = []
|
87 |
+
surprise = []
|
88 |
+
|
89 |
+
# extract scores (as many entries as exist in pred_texts)
|
90 |
+
for i in range(len(lines_s)):
|
91 |
+
anger.append(round(temp[i][0], 3))
|
92 |
+
disgust.append(round(temp[i][1], 3))
|
93 |
+
fear.append(round(temp[i][2], 3))
|
94 |
+
joy.append(round(temp[i][3], 3))
|
95 |
+
neutral.append(round(temp[i][4], 3))
|
96 |
+
sadness.append(round(temp[i][5], 3))
|
97 |
+
surprise.append(round(temp[i][6], 3))
|
98 |
+
|
99 |
+
# define df
|
100 |
+
df = pd.DataFrame(list(zip(ids,lines_s,labels,scores_rounded, anger, disgust, fear, joy, neutral, sadness, surprise)), columns=[df_input.columns[0], df_input.columns[1],'max_label','max_score', 'anger', 'disgust', 'fear', 'joy', 'neutral', 'sadness', 'surprise'])
|
101 |
+
print(df)
|
102 |
+
# save results to csv
|
103 |
+
YOUR_FILENAME = filename.name.split(".")[0] + "_emotion_predictions" + ".csv" # name your output file
|
104 |
+
df.to_csv(YOUR_FILENAME, index=False)
|
105 |
+
|
106 |
+
# return dataframe for space output
|
107 |
+
return YOUR_FILENAME
|
108 |
+
|
109 |
+
gr.Interface(bulk_function, inputs=[gr.inputs.File(file_count="single", type="file", label="Upload file", optional=False),],
|
110 |
+
outputs=[gr.outputs.File(label="Output file")],
|
111 |
+
# examples=[["YOUR_FILENAME.csv"]], # computes, doesn't export df so far
|
112 |
+
theme="huggingface",
|
113 |
+
title="Apply MindMiner to Your CSV",
|
114 |
+
description="Upload csv file with 2 columns (in order): (a) ID column, (b) text column. The script returns a new file that includes both the ID column and text column together with the mind perception predictions using MindMiner.",
|
115 |
+
allow_flagging=False,
|
116 |
+
).launch(debug=True)
|