nikhil061307 commited on
Commit
f9e3fbe
·
verified ·
1 Parent(s): 0455e68

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -0
app.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModel
3
+ import torch
4
+ import torch.nn.functional as F
5
+
6
+ # Load model + tokenizer with trust_remote_code
7
+ model_name = "nikhil061307/contrastive-learning-bert-added-token-v5"
8
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
9
+ model = AutoModel.from_pretrained(model_name, trust_remote_code=True)
10
+
11
+ def encode(text):
12
+ inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
13
+ with torch.no_grad():
14
+ outputs = model(**inputs)
15
+ embedding = outputs.last_hidden_state.mean(dim=1)
16
+ return embedding
17
+
18
+ def compute_similarity(sentence1, sentence2):
19
+ emb1 = encode(sentence1)
20
+ emb2 = encode(sentence2)
21
+ similarity = F.cosine_similarity(emb1, emb2).item()
22
+ return {"similarity": round(similarity, 4)}
23
+
24
+ demo = gr.Interface(
25
+ fn=compute_similarity,
26
+ inputs=[
27
+ gr.Textbox(lines=2, placeholder="Enter first sentence..."),
28
+ gr.Textbox(lines=2, placeholder="Enter second sentence...")
29
+ ],
30
+ outputs="json",
31
+ title="Contrastive Learning BERT Similarity",
32
+ description="Enter two sentences to compute semantic similarity using your fine-tuned BERT model."
33
+ )
34
+
35
+ if __name__ == "__main__":
36
+ demo.launch()