Spaces:
Runtime error
Runtime error
add app
Browse files- app.py +46 -0
- requirements.txt +5 -0
app.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from statistics import mean
|
| 2 |
+
import random
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from transformers import BertModel, BertTokenizerFast
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
import gradio as gr
|
| 9 |
+
|
| 10 |
+
tokenizer = BertTokenizerFast.from_pretrained("setu4993/LaBSE")
|
| 11 |
+
model = BertModel.from_pretrained("setu4993/LaBSE")
|
| 12 |
+
model = model.eval()
|
| 13 |
+
|
| 14 |
+
def embed(text, tokenizer, model):
|
| 15 |
+
inputs = tokenizer(text, return_tensors="pt", padding=True)
|
| 16 |
+
with torch.no_grad():
|
| 17 |
+
outputs = model(**inputs)
|
| 18 |
+
return outputs.pooler_output
|
| 19 |
+
|
| 20 |
+
def similarity(embeddings_1, embeddings_2):
|
| 21 |
+
normalized_embeddings_1 = F.normalize(embeddings_1, p=2)
|
| 22 |
+
normalized_embeddings_2 = F.normalize(embeddings_2, p=2)
|
| 23 |
+
return torch.matmul(
|
| 24 |
+
normalized_embeddings_1, normalized_embeddings_2.transpose(0, 1)
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
def semantic_sim(sentence1, sentence2):
|
| 28 |
+
em1 = embed(sentence1, tokenizer, model)
|
| 29 |
+
em2 = embed(sentence2, tokenizer, model)
|
| 30 |
+
sim = int(float(similarity(em1, em2)*5))
|
| 31 |
+
out = ""
|
| 32 |
+
if sim == 5:
|
| 33 |
+
out = "Equivalent"
|
| 34 |
+
elif sim == 4:
|
| 35 |
+
out = "Mostly equivalent, unimportant details differ"
|
| 36 |
+
elif sim == 3:
|
| 37 |
+
out = "Roughly equivalent, important details differ or are missing"
|
| 38 |
+
elif sim == 2:
|
| 39 |
+
out = "Not equivalent, but share some details"
|
| 40 |
+
elif sim == 1:
|
| 41 |
+
out = "Same general topic, but not equivalent"
|
| 42 |
+
elif sim == 0:
|
| 43 |
+
out = "Completely dissimilar"
|
| 44 |
+
return out
|
| 45 |
+
|
| 46 |
+
iface = gr.Interface(fn=semantic_sim, inputs=["text", "text"], outputs=["text"]).launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
transformers
|
| 3 |
+
numpy
|
| 4 |
+
gradio
|
| 5 |
+
|