File size: 2,754 Bytes
e872dac
 
 
 
 
 
 
dd7604b
 
e872dac
195c8b6
f9a2cc9
195c8b6
 
 
 
 
f9a2cc9
 
e872dac
 
 
 
 
 
 
 
 
 
 
 
 
dbe5dae
 
 
 
 
 
 
 
 
 
 
e872dac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbe5dae
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import gradio as gr
import pickle
import ftfy
import re
import torch
import numpy as np
from transformers import DistilBertTokenizer, DistilBertModel
from huggingface_hub import hf_hub_download, login
import os

# Obtener el token de Hugging Face desde la variable de entorno
hf_token = os.getenv("HF_TOKEN")

if hf_token is None:
    raise ValueError("HF_TOKEN no est谩 configurado en las variables de entorno.")

# Iniciar sesi贸n en Hugging Face Hub
login(token=hf_token)

def corregir_codificacion(texto):
    if isinstance(texto, str):
        return ftfy.fix_text(texto)
    return texto

def preprocesar_texto(texto):
    texto = texto.lower()
    texto = re.sub(r'\d+', '', texto)
    texto = re.sub(r'[^\w\s]', '', texto)
    return texto

class ClasificadorOpiniones:
    def __init__(self):
        try:
            model_path = hf_hub_download(repo_id="begoach1/opinion_classifier", filename="modelo_clasificador_reentrenado_lp_ros.pkl", use_auth_token=hf_token)
            with open(model_path, 'rb') as f:
                self.clf_combined = pickle.load(f)
        except FileNotFoundError:
            raise RuntimeError("El archivo del modelo no se encuentra.")
        except pickle.UnpicklingError:
            raise RuntimeError("Error al deserializar el modelo. Aseg煤rate de que el archivo no est茅 corrupto y que la versi贸n de scikit-learn sea compatible.")
        except Exception as e:
            raise RuntimeError(f"Error al descargar o cargar el modelo: {e}")
        
        self.tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-multilingual-cased')
        self.model = DistilBertModel.from_pretrained('distilbert-base-multilingual-cased')

    def clasificar_opinion(self, texto):
        texto = corregir_codificacion(texto)
        texto = preprocesar_texto(texto)
        tokens = self.tokenizer(texto, padding=True, truncation=True, return_tensors='pt')
        with torch.no_grad():
            outputs = self.model(**tokens)
        encoded_text = outputs.last_hidden_state[:, 0, :].numpy()
        prediccion = self.clf_combined.predict(encoded_text)
        etiquetas = ['queja', 'sugerencia', 'agradecimiento', 'felicitacion', 'ninguna', 'cambio_positivo_personal']
        resultado = dict(zip(etiquetas, prediccion[0]))
        return resultado

def clasificar(texto):
    clasificador = ClasificadorOpiniones()
    resultado = clasificador.clasificar_opinion(texto)
    return resultado

iface = gr.Interface(
    fn=clasificar,
    inputs=gr.Textbox(lines=2, placeholder="Escribe tu opini贸n aqu铆..."),
    outputs=gr.JSON(),
    title="Clasificador de Opiniones Multietiqueta",
    description="Ingresa un texto de opini贸n para obtener las etiquetas correspondientes."
)

iface.launch()