ubaid477 commited on
Commit
609199b
·
verified ·
1 Parent(s): 1e6dbe5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -0
app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from torch import Tensor
5
+ from transformers import AutoTokenizer, AutoModel
6
+
7
+ def last_token_pool(last_hidden_states: Tensor,
8
+ attention_mask: Tensor) -> Tensor:
9
+ left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
10
+ if left_padding:
11
+ return last_hidden_states[:, -1]
12
+ else:
13
+ sequence_lengths = attention_mask.sum(dim=1) - 1
14
+ batch_size = last_hidden_states.shape[0]
15
+ return last_hidden_states[torch.arange(batch_size, device=last_hidden_states.device), sequence_lengths]
16
+
17
+ def get_similarity_scores(queries: list, passages: list, model, tokenizer):
18
+ tokenizer.add_eos_token = True
19
+
20
+ max_length = 4096
21
+ input_texts = queries + passages
22
+ batch_dict = tokenizer(input_texts, max_length=max_length - 1, padding=True, truncation=True, return_tensors="pt")
23
+ outputs = model(**batch_dict)
24
+ embeddings = last_token_pool(outputs.last_hidden_state, batch_dict['attention_mask'])
25
+
26
+ embeddings = F.normalize(embeddings, p=2, dim=1)
27
+ scores = (embeddings[:len(queries)] @ embeddings[len(queries):].T) * 100
28
+ return scores.tolist()
29
+
30
+ def similarity_ui(keyName, field1, field2, field3):
31
+ task = 'Given a keyName, find similarity score against provided fields'
32
+ queries = [
33
+ keyName
34
+ ]
35
+ passages = [
36
+ field1,
37
+ field2,
38
+ field3
39
+ ]
40
+
41
+ scores = get_similarity_scores(queries, passages, model, tokenizer)
42
+ return {'Similarity Scores': scores}
43
+
44
+ # Load model and tokenizer
45
+ tokenizer = AutoTokenizer.from_pretrained('Salesforce/SFR-Embedding-Mistral')
46
+ model = AutoModel.from_pretrained('Salesforce/SFR-Embedding-Mistral')
47
+
48
+ # Create Gradio Interface
49
+ gr.Interface(
50
+ fn=similarity_ui,
51
+ inputs=["text", "text","text","text",],
52
+ outputs="text",
53
+ title="Similarity Score Calculator",
54
+ description="Enter a Key Name and 3 Fields to find similarity scores"
55
+ ).launch()