awacke1 commited on
Commit
e8ed5c0
·
verified ·
1 Parent(s): aacd8a4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -0
app.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from sentence_transformers import SentenceTransformer
3
+ from sklearn.metrics.pairwise import cosine_similarity
4
+
5
+ model = SentenceTransformer("sentence-t5-base")
6
+
7
+
8
+ def inference(
9
+ base_text: str = "",
10
+ compare_text: str = "",
11
+ exponent: int = 1,
12
+ progress=gr.Progress(),
13
+ ):
14
+ progress(0, "Computing embeddings...")
15
+ base_embedding = model.encode(base_text)
16
+ compare_embedding = model.encode(compare_text)
17
+
18
+ progress(0.5, "Computing similarity score...")
19
+ cos_sim = cosine_similarity([base_embedding], [compare_embedding])
20
+ score = cos_sim.item() ** exponent
21
+ score = float(f"{score:.5f}")
22
+
23
+ sim_type = "Cosine Similarity" if exponent == 1 else f"Sharpened Cosine Similarity (Exp: {exponent})"
24
+
25
+ return sim_type, score
26
+
27
+
28
+ if __name__ == '__main__':
29
+ demo = gr.Interface(
30
+ fn=inference,
31
+ title="Sentence Similarity",
32
+ description="Calculate Sharpened Confine Similarity between two sentences by sentence-t5-base.",
33
+ inputs=[
34
+ gr.Textbox(label="Base Sentence", placeholder="The sentence to compare against.", value="Improve this text:"),
35
+ gr.Textbox(label="Compare Sentence", placeholder="The sentence to compare.", value="Improve the text:"),
36
+ gr.Radio(label="Exponent", choices=[1, 2, 3], value=3),
37
+ ],
38
+ outputs=[
39
+ gr.Label(label="Type"),
40
+ gr.Label(label="Similarity Score"),
41
+ ],
42
+ examples=[
43
+ ["Improve this text:", "Improve the text:", 3],
44
+ ["Puppies are young pet dogs that are both playful and cuddly.",
45
+ "Young, playful, and cuddly pet dogs are known as puppies.", 3],
46
+ ["James loved to play piano, a habit inherited from his father.",
47
+ "The piano was quite heavy, making it hard for James to carry.", 3],
48
+ ],
49
+ cache_examples=True,
50
+ )
51
+ demo.launch()