ilhamsyahids commited on
Commit
18f7052
·
1 Parent(s): 8136595

init application

Browse files

Signed-off-by: Ilham Syahid S <ilhamsyahids@gmail.com>

Files changed (1) hide show
  1. app.py +88 -0
app.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import gradio as gr
3
+ from numpy import dot
4
+ from numpy.linalg import norm
5
+ from os import environ
6
+
7
+ num_of_sentences = 2
8
+
9
+ endpoint = environ.get("ENDPOINT", "")
10
+ api_key = environ.get("API_KEY", "")
11
+
12
+
13
+ def cos_sim(a, b):
14
+ return dot(a, b) / (norm(a) * norm(b))
15
+
16
+
17
+ def get_embeddings(model, text):
18
+ # make POST request to the endpoint
19
+ response = requests.post(
20
+ f"{endpoint}/{model}",
21
+ json={"text": text},
22
+ headers={"Authorization": "Bearer " + api_key},
23
+ )
24
+
25
+ return response.json()["vector"]
26
+
27
+
28
+ def calculate_similarities(model, text, *sentences):
29
+ # get embeddings for the input text
30
+ text_embedding = get_embeddings(model, text)
31
+
32
+ # get embeddings for the input sentences
33
+ sentences_embeddings = [get_embeddings(model, sentence) for sentence in sentences]
34
+
35
+ # calculate cosine similarity between the input text and the input sentences
36
+ similarities = {}
37
+ for sentence, sentence_embedding in zip(sentences, sentences_embeddings):
38
+ similarities[sentence] = cos_sim(text_embedding, sentence_embedding)
39
+
40
+ return similarities
41
+
42
+
43
+ demo = gr.Blocks()
44
+
45
+ with demo:
46
+ with gr.Row():
47
+ with gr.Column():
48
+ model = gr.inputs.Radio(
49
+ ["roberta", "ada"], default="roberta", label="Model"
50
+ )
51
+
52
+ text = gr.Textbox(lines=3, label="Input Text")
53
+
54
+ inp_sentences = [
55
+ gr.Textbox(lines=3, label="Sentence " + str(i + 1))
56
+ for i in range(num_of_sentences)
57
+ ]
58
+ btn = gr.Button(text="Submit")
59
+
60
+ with gr.Column():
61
+ output = gr.Label(label="Output", show_label=False)
62
+
63
+ # submit btn
64
+ btn.click(
65
+ calculate_similarities,
66
+ inputs=[model, text, *inp_sentences],
67
+ outputs=[output],
68
+ )
69
+
70
+ gr.Examples(
71
+ examples=[
72
+ ["roberta", "This is happy person", "هذا شخص سعيد", "هذه قطة سعيدة"],
73
+ ["roberta", "car", "camry", "toyota"],
74
+ ["roberta", "هذا شخص سعيد", "هذه قطة سعيدة", "This is happy person"],
75
+ ["roberta", "ihpone for sale", "iphone for sale", "camry for sale"],
76
+ ["ada", "camry", "toy", "toyota"],
77
+ ["ada", "This is happy person", "هذا شخص سعيد", "هذه قطة سعيدة"],
78
+ ["ada", "هذا شخص سعيد", "هذه قطة سعيدة", "This is happy person"],
79
+ ["ada", "ihpone for sale", "iphone for sale", "camry for sale"],
80
+ ],
81
+ inputs=[model, text, *inp_sentences],
82
+ outputs=output,
83
+ fn=calculate_similarities,
84
+ # cache_examples=True,
85
+ )
86
+
87
+ if __name__ == "__main__":
88
+ demo.launch()