Spaces:
Sleeping
Sleeping
Changed to Text embeddings
Browse files
app.py
CHANGED
|
@@ -1,31 +1,46 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import torch.nn.functional as F
|
| 3 |
-
from transformers import AutoTokenizer, AutoModel, AutoImageProcessor
|
| 4 |
-
import gradio as gr
|
| 5 |
-
import spaces
|
| 6 |
-
|
| 7 |
-
processor = AutoImageProcessor.from_pretrained("nomic-ai/nomic-embed-vision-v1.5")
|
| 8 |
-
vision_model = AutoModel.from_pretrained("nomic-ai/nomic-embed-vision-v1.5", trust_remote_code=True)
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
demo.launch(show_api=True)
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
from transformers import AutoTokenizer, AutoModel, AutoImageProcessor
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import spaces
|
| 6 |
+
|
| 7 |
+
processor = AutoImageProcessor.from_pretrained("nomic-ai/nomic-embed-vision-v1.5")
|
| 8 |
+
vision_model = AutoModel.from_pretrained("nomic-ai/nomic-embed-vision-v1.5", trust_remote_code=True)
|
| 9 |
+
|
| 10 |
+
tokenizer = AutoTokenizer.from_pretrained('nomic-ai/nomic-embed-text-v1.5')
|
| 11 |
+
text_model = AutoModel.from_pretrained('nomic-ai/nomic-embed-text-v1.5', trust_remote_code=True)
|
| 12 |
+
text_model.eval()
|
| 13 |
+
|
| 14 |
+
def mean_pooling(model_output, attention_mask):
|
| 15 |
+
token_embeddings = model_output[0]
|
| 16 |
+
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
|
| 17 |
+
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
|
| 18 |
+
|
| 19 |
+
@spaces.GPU
|
| 20 |
+
def TxtEmbed(text):
|
| 21 |
+
|
| 22 |
+
sentences = [text]
|
| 23 |
+
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
|
| 24 |
+
|
| 25 |
+
with torch.no_grad():
|
| 26 |
+
model_output = text_model(**encoded_input)
|
| 27 |
+
|
| 28 |
+
text_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
|
| 29 |
+
text_embeddings = F.layer_norm(text_embeddings, normalized_shape=(text_embeddings.shape[1],))
|
| 30 |
+
text_embeddings = F.normalize(text_embeddings, p=2, dim=1)
|
| 31 |
+
|
| 32 |
+
return text_embeddings.to_list();
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
with gr.Blocks() as demo:
|
| 38 |
+
txt = gr.Text();
|
| 39 |
+
out = gr.Text();
|
| 40 |
+
|
| 41 |
+
btn = gr.Button("Gerar embeddings")
|
| 42 |
+
btn.click(TxtEmbed, [txt], [out])
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
if __name__ == "__main__":
|
| 46 |
demo.launch(show_api=True)
|