hesha commited on
Commit
15e7ece
1 Parent(s): b002b0b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -0
app.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModel
3
+ import torch
4
+
5
+ tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2')
6
+ model = AutoModel.from_pretrained('sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2')
7
+
8
+ def mean_pooling(model_output, attention_mask):
9
+ token_embeddings = model_output[0]
10
+ input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
11
+ return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
12
+
13
+ def encode_sentences(sentences):
14
+ encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
15
+ with torch.no_grad():
16
+ model_output = model(**encoded_input)
17
+ sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
18
+ return sentence_embeddings.tolist()
19
+
20
+ demo = gr.Interface(fn=encode_sentences,
21
+ inputs="textbox",
22
+ outputs="text")
23
+
24
+ if __name__ == "__main__":
25
+ demo.launch()