rajababu15 commited on
Commit
ecce11e
1 Parent(s): 026caf7

Update3 app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -28
app.py CHANGED
@@ -1,39 +1,35 @@
1
  import gradio as gr
2
 
3
- import torch
4
- from sentence_transformers import SentenceTransformer, util
5
-
6
- import torch
7
  from sentence_transformers import SentenceTransformer, util
8
 
9
  def predict(body):
10
- """Extracts text1 and text2 from input body, computes sentence similarity, and returns the result as a dictionary.
11
-
12
- Args:
13
- body: A dictionary containing text1 and text2 as keys.
14
-
15
- Returns:
16
- A dictionary with the key "similarity score" containing the similarity between text1 and text2 as a float.
17
-
18
- Raises:
19
- ValueError: If the input body does not contain both text1 and text2 keys.
20
- """
21
-
22
- if "text1" not in body or "text2" not in body:
23
- raise ValueError("Input body must contain both 'text1' and 'text2' keys.")
24
-
25
- t1 = body["text1"]
26
- t2 = body["text2"]
27
-
28
  model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
29
 
30
- # Use model.encode directly for efficiency
31
- embeddings = model.encode([t1, t2], convert_to_tensor=True)
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)