project1 / app.py
rajababu15's picture
Update3 app.py
ecce11e verified
import gradio as gr
import json
from sentence_transformers import SentenceTransformer, util
def predict(body):
# Check if body is a string and try to convert it to a dictionary
if isinstance(body, str):
try:
body = json.loads(body)
except json.JSONDecodeError:
return {"error": "Invalid input format. Please provide a dictionary or a valid JSON string."}
# Extract text1 and text2 from the body
t1 = body.get("text1")
t2 = body.get("text2")
# Check if text1 and text2 are not None
if t1 is None or t2 is None:
return {"error": "Missing text1 or text2 in the input."}
# Initialize the model
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
# Compute embeddings for both texts
embedding_1 = model.encode(t1, convert_to_tensor=True)
embedding_2 = model.encode(t2, convert_to_tensor=True)
# Compute the cosine similarity
similarity_score = util.pytorch_cos_sim(embedding_1, embedding_2)
# Return the result in the desired format
return {"similarity score": similarity_score.item()}
iface = gr.Interface(fn=predict, inputs="text", outputs="text")
iface.launch(share=True)