Spaces:
Sleeping
Sleeping
improve file organization
Browse filesFiles changed (8)
- app.py+9-52
- src/preprocess.py → src/clean.pyRenamed+48-115
- src/config.pyAdded+38
- src/embedding_loader.pyAdded+33
- src/loader.py+50-97
- src/nlp.pyAdded+50
- src/predict.pyAdded+41
- src/utils.pyAdded+26
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960import torchimport numpy as npimport gradio as grfrom src.loader import get_model, EmbeddingLoaderfrom src.preprocess import clean_text, preprocesamiento, apply_poolinglangs = ["es", "en"]models = ["SVM", "NB", "LR", "SWEM", "MLP", "RNN", "LSTM"]POLARITY = {"NEGATIVE": 0,"NEUTRAL": 1,"POSITIVE": 2}MAP = {0: "NEGATIVE",1: "NEUTRAL",2: "POSITIVE"}pooling = {"es": "max","en": "aver"}def predict(lang:str, model_name: str, text: str):input = clean_text(text, lang)input = preprocesamiento([input], True, lang) # list[str]embedding_model = Noneif model_name in ["SWEM", "MLP", "RNN", "LSTM"]:input = [input[0].split()] # list[str]embedding_model = EmbeddingLoader(lang)input = embedding_model.get_embeddings(input) # list[list[float32]]if model_name in ["SWEM", "MLP"]:input = apply_pooling(input, embedding_model.vector_size(), pooling[lang]) # list[list[float64]]if model_name in ["MLP", "RNN", "LSTM"]:input = torch.tensor(np.array(input), dtype=torch.float32)if model_name in ["RNN", "LSTM"]:length = torch.tensor([len(input)])input = torch.nn.utils.rnn.pad_sequence(input, batch_first=True, padding_value=0)clf = get_model(lang, model_name, embedding_model)if model_name in ["RNN", "LSTM"]:return MAP[clf.predict(input, length)[0]]return MAP[clf.predict(input)[0]]with gr.Blocks() as demo:gr.Markdown("# Análisis de Sentimientos")lang = gr.Radio(choices=langs, label="Lang", value=langs[0])model = gr.Dropdown(choices=models, label="Model", interactive=True)text = gr.Textbox(label="Text")output = gr.Label(label="Output")predict_btn = gr.Button("Predict")predict_btn.click(fn=predict, inputs=[lang, model, text], outputs=output)demo.launch()1234567891011121314151617import gradio as grfrom src.config import langs, modelsfrom src.predict import predictwith gr.Blocks() as demo:gr.Markdown("# Análisis de Sentimientos")# Mostrar el lenguaje y modelo en la misma líneawith gr.Row():lang = gr.Radio(choices=langs, label="Lang", value=langs[0])model = gr.Dropdown(choices=models, label="Model", interactive=True)text = gr.Textbox(label="Input")output = gr.Label(label="Output")predict_btn = gr.Button("Predict")predict_btn.click(fn=predict, inputs=[lang, model, text], outputs=output)demo.launch()
1234567891011121314151617181920212223242526272829303132336 unmodified lines40414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011121 unmodified lines133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205import reimport spacyimport osfrom symspellpy import SymSpellimport unicodedataimport numpy as npfrom bs4 import BeautifulSoupfrom nltk.stem import SnowballStemmerdef replace_nbsp(texto: str):"""Reemplazar el símbolo por un espacio regular"""return re.sub(r'[\xa0]', ' ', str(texto))def replace_quotes(text:str):"""Reemplazar comillas dobles por comillas simples"""texto = re.sub(r'"', "'", text)texto = re.sub(r'[“”]', "'", texto) # Para comillas curvastexto = re.sub(r'"', "'", texto) # Para la entidad HTMLreturn textodef remove_html(text: str):# clean_text = re.sub(r'<[^>]+>', '', text)soup = BeautifulSoup(text, 'html.parser')clean_text = soup.get_text() # Extraer texto de código htmlreturn clean_textdef normalize_text(text: str):"""Convertir texto en negritas, cursivas a su forma normal yUnír unir acentos6 unmodified linestext = unicodedata.normalize("NFC", text)return textdef replace_url(text:str, value='url'):"""Reemplazar una url por otro valor"""return re.sub(r'https?://\S+|www\.\S+', value, text)def remove_punctuation(text: str):return re.sub(r'[!"#&\'*+,-./<=>?@:;_%&¿<>()[\\]^`{|}~]', '', text)def filter_text(text: str):pattern = re.compile(r'([a-zA-ZáéíóúüÁÉÍÓÚÜñÑ0-9]+)', re.UNICODE)return ' '.join(pattern.findall(text))def replace_whitespaces(text: str):"""Reemplazar espacios consecutivos, al inicio, final o intermedios por uno solo"""return re.sub(r'\s+', ' ', text).strip()SYMSPELL_DICTIONARIES_PATHS = {"en": os.path.join(os.getcwd(), "src", "en-80k.txt"),"es": os.path.join(os.getcwd(), "src", "es-100l.txt")}spell_es = SymSpell(max_dictionary_edit_distance=2, # Distancia de búsquedaprefix_length=7 # Prefijos de palabras)load = spell_es.load_dictionary(SYMSPELL_DICTIONARIES_PATHS["es"],term_index=0, # posicion donde se encuentran los terminoscount_index=1, # posicion donde se encuentran las frecuenciasencoding="utf-8")if not load: print("[sympellpy]: No ha sido posible cargar el diccionario en español")spell_en = SymSpell(max_dictionary_edit_distance=2, # Distancia de búsquedaprefix_length=7 # Prefijos de palabras)load = spell_en.load_dictionary(SYMSPELL_DICTIONARIES_PATHS["en"],term_index=0, # posicion donde se encuentran los terminoscount_index=1, # posicion donde se encuentran las frecuenciasencoding="utf-8")if not load: print("[sympellpy]: No ha sido posible cargar el diccionario en inglés")spellers = {"es": spell_es,"en": spell_en}def spell(texto, lang="es"):if lang not in SYMSPELL_DICTIONARIES_PATHS.keys():print(f"Idioma no soportado: {lang}")return Nonespell = spellers[lang]sugerencias = spell.lookup_compound(texto,max_edit_distance=2,ignore_non_words=True, # ignorar caracteres como números)return sugerencias[0].termdef clean_text(text: str, lang="es"):"""Mantienen letras en español, acentos y algunos signos de puntuación.Elimina emojis21 unmodified lines# Remover stopwords# text = get_no_stopwords(text, lang)return textSPACY_NAME_MODELS = {"en": "en_core_web_sm","es": "es_core_news_sm"}spacy_models = {"es": spacy.load(SPACY_NAME_MODELS["es"]),"en": spacy.load(SPACY_NAME_MODELS["en"])}stemmers_names = {"en": "english","es": "spanish"}def stemming_pipe(documentos: list[list[str]], lang: str="es"):if lang not in stemmers_names.keys():print(f"Idioma no soportado: {lang}")return Nonestemmer = SnowballStemmer(stemmers_names[lang])return list(map(lambda tokens_documento: [stemmer.stem(token) for token in tokens_documento],documentos))def preprocesamiento(documentos: list[str], stemming=True, lang="es") -> list[str]:nlp = spacy_models[lang]documentos_preprocesados = []docs = nlp.pipe(documentos)for doc in docs: # procesamiento de documentosdoc_preprocesado = []for token in doc:# filtrar lemas de palabras que no sean stopwords o signos de puntuacionif not token.is_stop and not token.is_punct:doc_preprocesado.append(token.lemma_)documentos_preprocesados.append(doc_preprocesado)if stemming:documentos_preprocesados = stemming_pipe(documentos_preprocesados, lang)# devolver stems separados por espaciosdocumentos_preprocesados = [" ".join(docs) for docs in documentos_preprocesados]return documentos_preprocesadosdef aver_pooling(embeddings: np.array, embeddings_dim):if not embeddings is None:return np.mean(embeddings, axis=0)return np.zeros(embeddings_dim)def max_pooling(embeddings: np.array, embeddings_dim):if not embeddings is None:return np.max(embeddings, axis=0)return np.zeros(embeddings_dim)def apply_pooling(list_embeddings: list[np.ndarray], embeddings_dim, pooling="aver"):x_pooling = Noneif pooling== "aver":x_pooling = np.array([aver_pooling(embeddings, embeddings_dim) for embeddings in list_embeddings])else: # pooling='max'x_pooling = np.array([max_pooling(embeddings, embeddings_dim) for embeddings in list_embeddings])return x_pooling12345678910111213141516171819202122232425262728293031326 unmodified lines3940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311421 unmodified lines136137138import reimport osfrom symspellpy import SymSpellimport unicodedatafrom bs4 import BeautifulSoupdef replace_nbsp(texto: str):"""Reemplazar el símbolo por un espacio regular"""return re.sub(r"[\xa0]", " ", str(texto))def replace_quotes(text: str):"""Reemplazar comillas dobles por comillas simples"""texto = re.sub(r'"', "'", text)texto = re.sub(r"[“”]", "'", texto) # Para comillas curvastexto = re.sub(r""", "'", texto) # Para la entidad HTMLreturn textodef remove_html(text: str):# clean_text = re.sub(r'<[^>]+>', '', text)soup = BeautifulSoup(text, "html.parser")clean_text = soup.get_text() # Extraer texto de código htmlreturn clean_textdef normalize_text(text: str):"""Convertir texto en negritas, cursivas a su forma normal yUnír unir acentos6 unmodified linestext = unicodedata.normalize("NFC", text)return textdef replace_url(text: str, value="url"):"""Reemplazar una url por otro valor"""return re.sub(r"https?://\S+|www\.\S+", value, text)def remove_punctuation(text: str):return re.sub(r'[!"#&\'*+,-./<=>?@:;_%&¿<>()[\\]^`{|}~]', "", text)def filter_text(text: str):pattern = re.compile(r"([a-zA-ZáéíóúüÁÉÍÓÚÜñÑ0-9]+)", re.UNICODE)return " ".join(pattern.findall(text))def replace_whitespaces(text: str):"""Reemplazar espacios consecutivos, al inicio, final o intermedios por uno solo"""return re.sub(r"\s+", " ", text).strip()SYMSPELL_DICTIONARIES_PATHS = {"en": os.path.join(os.getcwd(), "src", "en-80k.txt"),"es": os.path.join(os.getcwd(), "src", "es-100l.txt"),}spell_es = SymSpell(max_dictionary_edit_distance=2, # Distancia de búsquedaprefix_length=7, # Prefijos de palabras)load = spell_es.load_dictionary(SYMSPELL_DICTIONARIES_PATHS["es"],term_index=0, # posicion donde se encuentran los terminoscount_index=1, # posicion donde se encuentran las frecuenciasencoding="utf-8",)if not load:print("[sympellpy]: No ha sido posible cargar el diccionario en español")spell_en = SymSpell(max_dictionary_edit_distance=2, # Distancia de búsquedaprefix_length=7, # Prefijos de palabras)load = spell_en.load_dictionary(SYMSPELL_DICTIONARIES_PATHS["en"],term_index=0, # posicion donde se encuentran los terminoscount_index=1, # posicion donde se encuentran las frecuenciasencoding="utf-8",)if not load:print("[sympellpy]: No ha sido posible cargar el diccionario en inglés")spellers = {"es": spell_es, "en": spell_en}def spell(texto, lang="es"):if lang not in SYMSPELL_DICTIONARIES_PATHS.keys():print(f"Idioma no soportado: {lang}")return Nonespell = spellers[lang]sugerencias = spell.lookup_compound(texto,max_edit_distance=2,ignore_non_words=True, # ignorar caracteres como números)return sugerencias[0].termdef clean_text(text: str, lang="es"):"""Mantienen letras en español, acentos y algunos signos de puntuación.Elimina emojis21 unmodified lines# Remover stopwords# text = get_no_stopwords(text, lang)return text
1234567891011121314151617181920212223242526272829303132333435363738import os
# UI --------------------------------------------------------------------------langs = ["es", "en"]models = ["SVM", "NB", "LR", "SWEM", "MLP", "RNN", "LSTM"]
cwd = os.getcwd()models_en_dir = os.path.join(cwd, "models", "en")models_es_dir = os.path.join(cwd, "models", "es")
# Embeddings -----------------------------------------------------------------embeddings_path = { "es": os.path.join(models_es_dir, "embeddings.bin"), "en": os.path.join(models_en_dir, "embeddings.bin"),}
AVG_POOLING = "aver"MAX_POOLING = "max"
LABEL_TO_INDEX = {"NEGATIVE": 0, "NEUTRAL": 1, "POSITIVE": 2}INDEX_TO_LABEL = {0: "NEGATIVE", 1: "NEUTRAL", 2: "POSITIVE"}
langs_dir = { "es": os.path.join("models", "es", "classifiers"), "en": os.path.join("models", "en", "classifiers"),}
models_name = { "SVM": "svm_sentiment.pkl", "NB": "nb_sentiment.pkl", "LR": "lr_sentiment.pkl", "SWEM": "swem_sentiment.pkl", "MLP": "mlp_sentiment.pt", "RNN": "rnn_sentiment.pt", "LSTM": "lstm_sentiment.pt",}123456789101112131415161718192021222324252627282930313233import gensimimport numpy as np
from src.config import embeddings_path
class EmbeddingLoader: def __init__(self, lang: str, type: str = "w2v"): self.word_vectors = None
path = embeddings_path[lang]
if type == "w2v": self.word_vectors = gensim.models.KeyedVectors.load_word2vec_format( path, binary=True )
def get_word_vectors(self): return self.word_vectors
def vector_size(self): return self.word_vectors.vector_size
def get_embedding(self, word: str): if word in self.word_vectors: return self.word_vectors[word] # numpy.ndarray return np.zeros(self.word_vectors.vector_size)
def get_embeddings(self, tokens_list: list[list[str]]): embeddings = [] for tokens in tokens_list: embeddings.append(np.array([self.get_embedding(token) for token in tokens])) return embeddings # list[ndarray[ndarray[float]]]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596012 unmodified lines73747576777879808182838485868788894 unmodified lines9495969798991001011021031041051061071081091101111121131148 unmodified lines1231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561572 unmodified lines160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207import osimport joblibimport gensimimport torchimport numpy as npcwd = os.getcwd()langs_dir = {"es": os.path.join("models", "es", "classifiers"),"en": os.path.join("models", "en", "classifiers"),}embeddings_path = {"es": os.path.join("models", "es", "embeddings", "w2v_embeddings_tiktok_sentences.bin"),"en": os.path.join("models", "en", "embeddings", "w2v_embeddings_twitter.bin")}models_name = {"SVM": "svm_pipeline.pkl","NB": "nb_pipeline.pkl","LR": "lr_pipeline.pkl","SWEM": "swem_model.pkl","MLP": "mlp_swem_model.pth","RNN": "rnn_model.pth","LSTM": "lstm_model.pth",}class ModelArgs:input_size: inthidden_size: int # rnnnum_layers: int = 1 # rnnhidden_layers: list # mlpoutput_size: intnonlinearity: str = 'tanh' # 'tanh' | 'relu'dropout:int = 0class MLPClassifier:def __init__(self, model):self.model = model # MLPModelCustom()def predict(self, x: torch.Tensor):self.model.eval()with torch.torch.no_grad(): # no calcular gradienteoutput = self.model(x) # (batch_size, output_size)pred = torch.nn.functional.softmax(output, dim=1).squeeze()return [torch.argmax(pred).tolist()]class RNNClassifier:def __init__(self, base_model):self.model = base_model # MLPModelCustom()def predict(self, x: torch.Tensor, length):self.model.eval() # Desactiva Dropoutwith torch.torch.no_grad(): # no calcular gradienteoutput = self.model(x, length) # (batch_size, output_size)pred = torch.nn.functional.softmax(output, dim=1).squeeze()return [torch.argmax(pred).tolist()]12 unmodified linesen_model_args.output_size = 3en_model_args.dropout = 0.20model_args = {"es": es_model_args,"en": en_model_args}def get_model(lang, model_name, embedding_model=None):dir_name = langs_dir[lang]model_path = models_name[model_name]path = os.path.join(cwd, dir_name, model_path)if model_name in {"SVM", "NB", "LR", "SWEM"}:return joblib.load(path)4 unmodified linesif model_name == "MLP":model = MLPModelCustom(args)state_dict = torch.load(path, map_location=device)model.load_state_dict(state_dict)return MLPClassifier(model)if model_name == "RNN":model = RNNModel(args)state_dict = torch.load(path, map_location=device)model.load_state_dict(state_dict)return RNNClassifier(model)if model_name == "LSTM":model = LSTMModel(args)state_dict = torch.load(path, map_location=device)model.load_state_dict(state_dict)return RNNClassifier(model)class MLPModelCustom(torch.nn.Module):def __init__ (self, model_args):super().__init__()layers = []previous_dim = model_args.input_size8 unmodified linesdef forward(self, x):return self.network(x)class RNNModel(torch.nn.Module):def __init__(self, model_args: ModelArgs):super().__init__()self.rnn = torch.nn.RNN(input_size = model_args.input_size, # Número de características por palabra | Tamaño de los embeddingshidden_size = model_args.hidden_size, # Número de características/neuronas de la capa recurrentenum_layers = model_args.num_layers, # Núumero de capas recurrentesnonlinearity = model_args.nonlinearity, # 'relu' deafult: 'tanh'dropout = model_args.dropout, # Porcentaje de neuronas desactivadas durante el entrenamientobatch_first = True # Los tensores de entrada y salida tienen las dimensiones (batch, seq, feature))self.fc = torch.nn.Linear(model_args.hidden_size, # Número de características de entradamodel_args.output_size # Número de clases)def forward(self, x, lengths):packed_x = torch.nn.utils.rnn.pack_padded_sequence(x,lengths,batch_first=True,enforce_sorted=False)packed_output, hidden = self.rnn(packed_x)h_n = hidden[-1] # tomar la salida de la última capa rnnreturn self.fc(h_n)class LSTMModel(torch.nn.Module):def __init__(self, model_args: ModelArgs):super().__init__()2 unmodified lineshidden_size=model_args.hidden_size,num_layers=model_args.num_layers,dropout=model_args.dropout,batch_first=True)self.fc = torch.nn.Linear(in_features=model_args.hidden_size,out_features=model_args.output_size)def forward(self, x, lengths):packed_input_sequences = torch.nn.utils.rnn.pack_padded_sequence(x,lengths,batch_first=True,enforce_sorted=False)packed_output_sequences, (hidden, cell) = self.lstm(packed_input_sequences)h_n = hidden[-1] # Tomar el estado oculto final de la última capareturn self.fc(h_n) # (batch_size, output_size)class EmbeddingLoader:def __init__(self, lang: str, type: str='w2v'):self.word_vectors = Nonepath = os.path.join(cwd, embeddings_path[lang])if type == 'w2v':self.word_vectors = gensim.models.KeyedVectors.load_word2vec_format(path, binary=True)def get_word_vectors(self):return self.word_vectorsdef vector_size(self):return self.word_vectors.vector_sizedef get_embedding(self, word: str):if word in self.word_vectors:return self.word_vectors[word] # numpy.ndarrayreturn np.zeros(self.word_vectors.vector_size)def get_embeddings(self, tokens_list: list[list[str]]):embeddings = []for tokens in tokens_list:embeddings.append(np.array([self.get_embedding(token) for token in tokens]))return embeddings # list[ndarray[ndarray[float]]]12345678910111213141516171819202122232425262728293031323334353637383940414212 unmodified lines5556575859606162636465666768694 unmodified lines747576777879808182838485868788899091929394959697988 unmodified lines1071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391402 unmodified lines143144145146147148149150151152153154155156157158159160import osimport joblibimport torchfrom src.config import langs_dir, models_namecwd = os.getcwd()class ModelArgs:input_size: inthidden_size: int # rnnnum_layers: int = 1 # rnnhidden_layers: list # mlpoutput_size: intnonlinearity: str = "tanh" # 'tanh' | 'relu'dropout: int = 0class MLPClassifier:def __init__(self, model):self.model = model # MLPModelCustom()def predict(self, x: torch.Tensor):self.model.eval()with torch.torch.no_grad(): # no calcular gradienteoutput = self.model(x) # (batch_size, output_size)pred = torch.nn.functional.softmax(output, dim=1).squeeze()return [torch.argmax(pred).tolist()]class RNNClassifier:def __init__(self, base_model):self.model = base_model # MLPModelCustom()def predict(self, x: torch.Tensor, length):self.model.eval() # Desactiva Dropoutwith torch.torch.no_grad(): # no calcular gradienteoutput = self.model(x, length) # (batch_size, output_size)pred = torch.nn.functional.softmax(output, dim=1).squeeze()return [torch.argmax(pred).tolist()]12 unmodified linesen_model_args.output_size = 3en_model_args.dropout = 0.20model_args = {"es": es_model_args, "en": en_model_args}def get_model(lang, model_name, embedding_model=None):dir_name = langs_dir[lang]model_path = models_name[model_name]path = os.path.join(cwd, dir_name, model_path)if model_name in {"SVM", "NB", "LR", "SWEM"}:return joblib.load(path)4 unmodified linesif model_name == "MLP":model = MLPModelCustom(args)state_dict = torch.load(path, map_location=device)# model.load_state_dict(state_dict)model.load_state_dict(state_dict["model_state_dict"])return MLPClassifier(model)if model_name == "RNN":model = RNNModel(args)state_dict = torch.load(path, map_location=device)# model.load_state_dict(state_dict)model.load_state_dict(state_dict["model_state_dict"])return RNNClassifier(model)if model_name == "LSTM":model = LSTMModel(args)state_dict = torch.load(path, map_location=device)# model.load_state_dict(state_dict)model.load_state_dict(state_dict["model_state_dict"])return RNNClassifier(model)class MLPModelCustom(torch.nn.Module):def __init__(self, model_args):super().__init__()layers = []previous_dim = model_args.input_size8 unmodified linesdef forward(self, x):return self.network(x)class RNNModel(torch.nn.Module):def __init__(self, model_args: ModelArgs):super().__init__()self.rnn = torch.nn.RNN(input_size=model_args.input_size, # Número de características por palabra | Tamaño de los embeddingshidden_size=model_args.hidden_size, # Número de características/neuronas de la capa recurrentenum_layers=model_args.num_layers, # Núumero de capas recurrentesnonlinearity=model_args.nonlinearity, # 'relu' deafult: 'tanh'dropout=model_args.dropout, # Porcentaje de neuronas desactivadas durante el entrenamientobatch_first=True, # Los tensores de entrada y salida tienen las dimensiones (batch, seq, feature))self.fc = torch.nn.Linear(model_args.hidden_size, # Número de características de entradamodel_args.output_size, # Número de clases)def forward(self, x, lengths):packed_x = torch.nn.utils.rnn.pack_padded_sequence(x, lengths, batch_first=True, enforce_sorted=False)packed_output, hidden = self.rnn(packed_x)h_n = hidden[-1] # tomar la salida de la última capa rnnreturn self.fc(h_n)class LSTMModel(torch.nn.Module):def __init__(self, model_args: ModelArgs):super().__init__()2 unmodified lineshidden_size=model_args.hidden_size,num_layers=model_args.num_layers,dropout=model_args.dropout,batch_first=True,)self.fc = torch.nn.Linear(in_features=model_args.hidden_size, out_features=model_args.output_size)def forward(self, x, lengths):packed_input_sequences = torch.nn.utils.rnn.pack_padded_sequence(x, lengths, batch_first=True, enforce_sorted=False)packed_output_sequences, (hidden, cell) = self.lstm(packed_input_sequences)h_n = hidden[-1] # Tomar el estado oculto final de la última capareturn self.fc(h_n) # (batch_size, output_size)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950import spacyfrom nltk.stem import SnowballStemmer
SPACY_NAME_MODELS = {"en": "en_core_web_sm", "es": "es_core_news_sm"}spacy_models = { "es": spacy.load(SPACY_NAME_MODELS["es"]), "en": spacy.load(SPACY_NAME_MODELS["en"]),}
stemmers_names = {"en": "english", "es": "spanish"}
def stemming_pipe(documentos: list[list[str]], lang: str = "es"): if lang not in stemmers_names.keys(): print(f"Idioma no soportado: {lang}") return None
stemmer = SnowballStemmer(stemmers_names[lang]) return list( map( lambda tokens_documento: [ stemmer.stem(token) for token in tokens_documento ], documentos, ) )
def preprocess(documentos: list[str], stemming=True, lang="es") -> list[str]: nlp = spacy_models[lang]
documentos_preprocesados = []
docs = nlp.pipe(documentos)
for doc in docs: # procesamiento de documentos doc_preprocesado = [] for token in doc: # filtrar lemas de palabras que no sean stopwords o signos de puntuacion if not token.is_stop and not token.is_punct: doc_preprocesado.append(token.lemma_) documentos_preprocesados.append(doc_preprocesado)
if stemming: documentos_preprocesados = stemming_pipe(documentos_preprocesados, lang)
# devolver stems separados por espacios documentos_preprocesados = [" ".join(docs) for docs in documentos_preprocesados]
return documentos_preprocesados1234567891011121314151617181920212223242526272829303132333435363738394041import torchimport numpy as np
from src.loader import get_modelfrom src.config import AVG_POOLING, INDEX_TO_LABELfrom src.nlp import preprocessfrom src.clean import clean_textfrom src.embedding_loader import EmbeddingLoaderfrom src.utils import apply_pooling
models_with_embeddings = ["SWEM", "MLP", "RNN", "LSTM"]models_with_pooling = ["SWEM", "MLP"]
def predict(lang: str, model_name: str, text: str): input = clean_text(text, lang) input = preprocess([input], True, lang) # list[str] embedding_model = None
if model_name in models_with_embeddings: input = [input[0].split()] # list[str] embedding_model = EmbeddingLoader(lang) input = embedding_model.get_embeddings(input) # list[list[float32]]
if model_name in models_with_pooling: input = apply_pooling( input, embedding_model.vector_size(), AVG_POOLING ) # list[list[float64]] if model_name in ["MLP", "RNN", "LSTM"]: input = torch.tensor(np.array(input), dtype=torch.float32) if model_name in ["RNN", "LSTM"]: length = torch.tensor([len(input)]) input = torch.nn.utils.rnn.pad_sequence( input, batch_first=True, padding_value=0 )
clf = get_model(lang, model_name, embedding_model)
if model_name in ["RNN", "LSTM"]: return INDEX_TO_LABEL[clf.predict(input, length)[0]] return INDEX_TO_LABEL[clf.predict(input)[0]]1234567891011121314151617181920212223242526import numpy as np
def aver_pooling(embeddings: np.array, embeddings_dim): if not embeddings is None: return np.mean(embeddings, axis=0) return np.zeros(embeddings_dim)
def max_pooling(embeddings: np.array, embeddings_dim): if not embeddings is None: return np.max(embeddings, axis=0) return np.zeros(embeddings_dim)
def apply_pooling(list_embeddings: list[np.ndarray], embeddings_dim, pooling="aver"): x_pooling = None if pooling == "aver": x_pooling = np.array( [aver_pooling(embeddings, embeddings_dim) for embeddings in list_embeddings] ) else: # pooling='max' x_pooling = np.array( [max_pooling(embeddings, embeddings_dim) for embeddings in list_embeddings] ) return x_poolingapp.py+9-52
src/preprocess.py → src/clean.pyRenamed+48-115
src/config.pyAdded+38
src/embedding_loader.pyAdded+33
src/loader.py+50-97
src/nlp.pyAdded+50
src/predict.pyAdded+41
src/utils.pyAdded+26