import torch import torch.nn.functional as F from transformers import AutoTokenizer, AutoModel, AutoImageProcessor import gradio as gr import spaces model = AutoModel.from_pretrained('neuralmind/bert-base-portuguese-cased') tokenizer = AutoTokenizer.from_pretrained('neuralmind/bert-base-portuguese-cased', do_lower_case=False) # processor = AutoImageProcessor.from_pretrained("nomic-ai/nomic-embed-vision-v1.5") # vision_model = AutoModel.from_pretrained("nomic-ai/nomic-embed-vision-v1.5", trust_remote_code=True) # tokenizer = AutoTokenizer.from_pretrained('nomic-ai/nomic-embed-text-v1.5') # text_model = AutoModel.from_pretrained('nomic-ai/nomic-embed-text-v1.5', trust_remote_code=True) # text_model.eval() def mean_pooling(model_output, attention_mask): token_embeddings = model_output[0] input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float() return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9) @spaces.GPU def TxtEmbed(text): import torch input_ids = tokenizer.encode(text, return_tensors='pt') with torch.no_grad(): outs = model(input_ids) encoded = outs[0][0, 1:-1] # Ignore [CLS] and [SEP] special tokens # sentences = [text] # encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt') # # with torch.no_grad(): # model_output = text_model(**encoded_input) # # text_embeddings = mean_pooling(model_output, encoded_input['attention_mask']) # text_embeddings = F.layer_norm(text_embeddings, normalized_shape=(text_embeddings.shape[1],)) # text_embeddings = F.normalize(text_embeddings, p=2, dim=1) return (encoded.tolist())[0]; with gr.Blocks() as demo: txt = gr.Text(); out = gr.Text(); btn = gr.Button("Gerar embeddings") btn.click(TxtEmbed, [txt], [out]) if __name__ == "__main__": demo.launch(show_api=True)