JuanPabloAnselmo commited on
Commit
1181e89
verified
1 Parent(s): a0a27dc

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -94
app.py DELETED
@@ -1,94 +0,0 @@
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
-
80
-
81
- amazon_app = gr.Interface(
82
- fn=predict,
83
- inputs=gr.inputs.Textbox(label="Introduce tu rese帽a aqu铆:", placeholder="Escribe aqu铆..."),
84
- outputs=[gr.outputs.Label(label="Predicci贸n"), gr.outputs.Label(label="Puntaje")],
85
- title="An谩lisis de sentimientos de rese帽as de productos en Espa帽ol",
86
- 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)",
87
- theme=gr.themes.Soft(),
88
- layout="vertical",
89
- allow_flagging=False,
90
- analytics_enabled=True
91
- )
92
-
93
- # Ejecuta la aplicaci贸n
94
- amazon_app.launch()