[email protected] commited on
Commit
6d6f559
·
1 Parent(s): ea77c7d

added endpoint cosine-similarity

Browse files
Files changed (2) hide show
  1. __pycache__/main.cpython-310.pyc +0 -0
  2. main.py +42 -0
__pycache__/main.cpython-310.pyc CHANGED
Binary files a/__pycache__/main.cpython-310.pyc and b/__pycache__/main.cpython-310.pyc differ
 
main.py CHANGED
@@ -1,3 +1,4 @@
 
1
  from fastapi import FastAPI
2
  import joblib
3
  from sentence_transformers import SentenceTransformer
@@ -25,3 +26,44 @@ def get_dimension(message: str):
25
  prediction = loaded_model.predict(message_embedding)
26
  return {"Predicted Category": f"{prediction[0]}"}
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sentence_transformers import SentenceTransformer, util
2
  from fastapi import FastAPI
3
  import joblib
4
  from sentence_transformers import SentenceTransformer
 
26
  prediction = loaded_model.predict(message_embedding)
27
  return {"Predicted Category": f"{prediction[0]}"}
28
 
29
+
30
+ @app.post("/cosine-similarity")
31
+ def calculate_cosine_similarity(sentence1:str, sentence2:str):
32
+
33
+ embeddings = model.encode([sentence1, sentence2])
34
+
35
+ cosine_sim = util.cos_sim(embeddings[0], embeddings[1])
36
+ # return str(cosine_sim[0])
37
+ return round(cosine_sim.item(), 3)
38
+
39
+
40
+
41
+
42
+ # Example usage:
43
+ # sentence_a = "The cat sat on the mat."
44
+ # sentence_b = "A feline rested on the rug."
45
+ # similarity = calculate_cosine_similarity(sentence_a, sentence_b)
46
+
47
+ # if similarity is not None:
48
+ # print(f"Cosine similarity between sentence_a and sentence_b: {similarity}")
49
+
50
+ # sentence_c = "This is a completely different sentence."
51
+ # similarity_ac = calculate_cosine_similarity(sentence_a, sentence_c)
52
+
53
+ # if similarity_ac is not None:
54
+ # print(
55
+ # f"Cosine similarity between sentence_a and sentence_c: {similarity_ac}")
56
+
57
+
58
+ # # Using a different model (you'll need to install it if you haven't already):
59
+ # similarity_different_model = calculate_cosine_similarity(
60
+ # sentence_a, sentence_b, model_name="all-MiniLM-L6-v2")
61
+ # if similarity_different_model is not None:
62
+ # print(f"Cosine similarity (different model): {similarity_different_model}")
63
+
64
+ # # Example of error handling if model name is wrong
65
+ # similarity_error = calculate_cosine_similarity(
66
+ # sentence_a, sentence_b, model_name="wrong-model-name")
67
+
68
+ # if similarity_error is not None:
69
+ # print(f"Cosine similarity (wrong model name): {similarity_error}")