File size: 1,198 Bytes
85cde41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

import gradio as gr
import torch
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity

model = SentenceTransformer(
    "sentence-transformers/sentence-t5-base",
    device="cuda" if torch.cuda.is_available() else "cpu"
)


def get_metrics(vec1, vec2):
    sim = float(cosine_similarity(vec1, vec2)[0][0])

    scs = abs((sim) ** 3)
    m = {
        "cosine_similarity": round(sim, 4),
        "scs": round(scs, 4)
    }
    return m


def compute(text1, text2):

    texts = [text1, text2]

    embeddings = model.encode(
        texts,
        show_progress_bar=False,
        convert_to_numpy=True,
        normalize_embeddings=True,
    )

    return get_metrics(embeddings[0].reshape(1, -1), embeddings[1].reshape(1, -1))


with gr.Blocks() as demo:
    with gr.Row():
        text1 = gr.Textbox(label="Enter Text 1")
        text2 = gr.Textbox(label="Enter Text 2")

    with gr.Column():
        submit_btn = gr.Button("Submit")

        output = gr.JSON(
            label="Score",
        )

    # # callback ---
    submit_btn.click(
        fn=compute,
        inputs=[text1, text2],
        outputs=output
    )


demo.launch()