JuanPabloAnselmo
commited on
Commit
•
7d83daf
1
Parent(s):
1181e89
Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import AutoTokenizer, AutoModel
|
3 |
+
import torch
|
4 |
+
from torch import nn
|
5 |
+
import torch.nn.functional as F
|
6 |
+
|
7 |
+
|
8 |
+
# Creo la clase del modelo
|
9 |
+
class RobertaModel(nn.Module):
|
10 |
+
|
11 |
+
def __init__(self, n_classes: int = 2):
|
12 |
+
super().__init__()
|
13 |
+
self.roberta = AutoModel.from_pretrained("xlm-roberta-base") #Modelo transformer
|
14 |
+
self.dropout = nn.Dropout(p=0.3) #Dropout para disminuir el overfitting
|
15 |
+
self.linear = nn.Linear(self.roberta.config.hidden_size, self.roberta.config.hidden_size) # 1er capa linear
|
16 |
+
self.classification = nn.Linear(self.roberta.config.hidden_size, n_classes) # 2da capa linear
|
17 |
+
|
18 |
+
def forward(self, input_ids, attention_mask):
|
19 |
+
#Roberta layer
|
20 |
+
cls_output = self.roberta(input_ids=input_ids, attention_mask=attention_mask)
|
21 |
+
pooled_output = torch.mean(cls_output.last_hidden_state, 1)
|
22 |
+
|
23 |
+
|
24 |
+
# NN
|
25 |
+
pooled_output = self.linear(pooled_output) # Primera capa
|
26 |
+
pooled_output = F.relu(pooled_output) # Funcion de activacion relu
|
27 |
+
pooled_output = self.dropout(pooled_output) # Dropout
|
28 |
+
output = self.classification(pooled_output) #Segunda capa
|
29 |
+
|
30 |
+
return output
|
31 |
+
|
32 |
+
model = RobertaModel()
|
33 |
+
|
34 |
+
# Cargo los pesos ya entrenados del modelo
|
35 |
+
|
36 |
+
model.load_state_dict(
|
37 |
+
torch.load(
|
38 |
+
f="Modelo_Amazon_review.pt",
|
39 |
+
map_location=torch.device("cpu") # Cambio modelo a cpu
|
40 |
+
)
|
41 |
+
)
|
42 |
+
|
43 |
+
# Cargo modelo para el Tokenizer
|
44 |
+
|
45 |
+
tokenizer = AutoTokenizer.from_pretrained('xlm-roberta-base')
|
46 |
+
|
47 |
+
|
48 |
+
# Creo funcion para predecir
|
49 |
+
|
50 |
+
def predict(review_text):
|
51 |
+
pred = {}
|
52 |
+
|
53 |
+
encoding_review = tokenizer.encode_plus(
|
54 |
+
review_text,
|
55 |
+
max_length = 250, #Maximo del larogo del texto
|
56 |
+
truncation = True, # Truncar texto
|
57 |
+
add_special_tokens = True, #Agregar tokens especiales
|
58 |
+
return_token_type_ids = False, # Que no devuelva los ids de esos tokens
|
59 |
+
padding = "max_length", # Que realice padding hasta el maximo alrgo
|
60 |
+
return_attention_mask = True, #Que devuelva la mascara de atencion
|
61 |
+
return_tensors = 'pt' # Que los tensores que devuelve sean Pytorch
|
62 |
+
)
|
63 |
+
|
64 |
+
input_ids = encoding_review['input_ids']
|
65 |
+
attention_mask = encoding_review['attention_mask']
|
66 |
+
output = model(input_ids, attention_mask)
|
67 |
+
_, prediction = torch.max(output, dim=1)
|
68 |
+
if prediction == 0:
|
69 |
+
pred["label"] = "Negativo"
|
70 |
+
pred["score"] = f"{torch.softmax(output, dim=1)[0][0].item()*100:.2f}%"
|
71 |
+
else:
|
72 |
+
pred["label"] = "Positivo"
|
73 |
+
pred["score"] = f"{torch.softmax(output, dim=1)[0][1].item()*100:.2f}%"
|
74 |
+
|
75 |
+
return pred["label"], pred["score"]
|
76 |
+
|
77 |
+
# Funcion para crear interfaz
|
78 |
+
|
79 |
+
amazon_app = gr.Interface(
|
80 |
+
fn=predict,
|
81 |
+
inputs=gr.Textbox(label="Introduce tu reseña aquí:", placeholder="Escribe aquí..."),
|
82 |
+
outputs=[gr.Label(label="Predicción"), gr.Label(label="Puntaje")],
|
83 |
+
title="Análisis de sentimientos de reseñas de productos en Español",
|
84 |
+
description="Ingresa una reseña de algun producto y obtén una predicción sobre si su sentimiento es positivo o negativo. (Max. 250 caracteres)",
|
85 |
+
theme="Agora",
|
86 |
+
#layout="vertical",
|
87 |
+
#interpretation="default",
|
88 |
+
allow_flagging=False,
|
89 |
+
analytics_enabled=False
|
90 |
+
)
|
91 |
+
|
92 |
+
# Ejecuta la aplicación
|
93 |
+
amazon_app.launch()
|