Spaces:
Sleeping
Sleeping
rajababu15
commited on
Commit
•
ecce11e
1
Parent(s):
026caf7
Update3 app.py
Browse files
app.py
CHANGED
@@ -1,39 +1,35 @@
|
|
1 |
import gradio as gr
|
2 |
|
3 |
-
import
|
4 |
-
from sentence_transformers import SentenceTransformer, util
|
5 |
-
|
6 |
-
import torch
|
7 |
from sentence_transformers import SentenceTransformer, util
|
8 |
|
9 |
def predict(body):
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
if
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
t2 = body["text2"]
|
27 |
-
|
28 |
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
29 |
|
30 |
-
#
|
31 |
-
|
32 |
-
|
33 |
-
similarity = util.pytorch_cos_sim(embeddings[0], embeddings[1])
|
34 |
-
|
35 |
-
return {"similarity score": float(similarity.item())} # Extract scalar value from tensor
|
36 |
|
|
|
|
|
37 |
|
|
|
|
|
38 |
iface = gr.Interface(fn=predict, inputs="text", outputs="text")
|
39 |
iface.launch(share=True)
|
|
|
1 |
import gradio as gr
|
2 |
|
3 |
+
import json
|
|
|
|
|
|
|
4 |
from sentence_transformers import SentenceTransformer, util
|
5 |
|
6 |
def predict(body):
|
7 |
+
# Check if body is a string and try to convert it to a dictionary
|
8 |
+
if isinstance(body, str):
|
9 |
+
try:
|
10 |
+
body = json.loads(body)
|
11 |
+
except json.JSONDecodeError:
|
12 |
+
return {"error": "Invalid input format. Please provide a dictionary or a valid JSON string."}
|
13 |
+
|
14 |
+
# Extract text1 and text2 from the body
|
15 |
+
t1 = body.get("text1")
|
16 |
+
t2 = body.get("text2")
|
17 |
+
|
18 |
+
# Check if text1 and text2 are not None
|
19 |
+
if t1 is None or t2 is None:
|
20 |
+
return {"error": "Missing text1 or text2 in the input."}
|
21 |
+
|
22 |
+
# Initialize the model
|
|
|
|
|
23 |
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
24 |
|
25 |
+
# Compute embeddings for both texts
|
26 |
+
embedding_1 = model.encode(t1, convert_to_tensor=True)
|
27 |
+
embedding_2 = model.encode(t2, convert_to_tensor=True)
|
|
|
|
|
|
|
28 |
|
29 |
+
# Compute the cosine similarity
|
30 |
+
similarity_score = util.pytorch_cos_sim(embedding_1, embedding_2)
|
31 |
|
32 |
+
# Return the result in the desired format
|
33 |
+
return {"similarity score": similarity_score.item()}
|
34 |
iface = gr.Interface(fn=predict, inputs="text", outputs="text")
|
35 |
iface.launch(share=True)
|