Yashashvibhardwaj commited on
Commit
575e2d2
·
verified ·
1 Parent(s): a93aa09

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +11 -11
main.py CHANGED
@@ -16,16 +16,16 @@ os.environ["SENTENCE_TRANSFORMERS_HOME"] = "./cache"
16
 
17
  app = FastAPI()
18
 
19
- # Enable CORS (for frontend)
20
  app.add_middleware(
21
  CORSMiddleware,
22
- allow_origins=["*"], # you can restrict to your Netlify domain later
23
  allow_credentials=True,
24
  allow_methods=["*"],
25
  allow_headers=["*"],
26
  )
27
 
28
- # Load products directly from products.json
29
  with open("products.json", "r", encoding="utf-8") as f:
30
  products = json.load(f)
31
 
@@ -49,12 +49,12 @@ def search_text(query: str = Form(...), top_k: int = 5, min_score: float = 0.0):
49
  """
50
  Search products using text query.
51
  """
52
- query_emb = model.encode([query], convert_to_numpy=True)
53
- distances, indices = index.search(query_emb, top_k)
54
 
55
  results = []
56
- for dist, idx in zip(distances[0], indices[0]):
57
- score = float(1 - dist) # convert distance to similarity (optional)
58
  if score >= min_score:
59
  item = products[idx].copy()
60
  item["score"] = score
@@ -82,12 +82,12 @@ async def search_image(
82
  else:
83
  return {"error": "No image provided"}
84
 
85
- image_emb = model.encode([image], convert_to_numpy=True)
86
- distances, indices = index.search(image_emb, top_k)
87
 
88
  results = []
89
- for dist, idx in zip(distances[0], indices[0]):
90
- score = float(1 - dist) # convert distance to similarity
91
  if score >= min_score:
92
  item = products[idx].copy()
93
  item["score"] = score
 
16
 
17
  app = FastAPI()
18
 
19
+ # Enable CORS (so Netlify frontend can call)
20
  app.add_middleware(
21
  CORSMiddleware,
22
+ allow_origins=["*"], # can restrict to Netlify domain later
23
  allow_credentials=True,
24
  allow_methods=["*"],
25
  allow_headers=["*"],
26
  )
27
 
28
+ # Load products
29
  with open("products.json", "r", encoding="utf-8") as f:
30
  products = json.load(f)
31
 
 
49
  """
50
  Search products using text query.
51
  """
52
+ query_emb = model.encode([query], convert_to_numpy=True, normalize_embeddings=True)
53
+ sims, indices = index.search(query_emb, top_k)
54
 
55
  results = []
56
+ for sim, idx in zip(sims[0], indices[0]):
57
+ score = float(sim) # already cosine similarity (0–1)
58
  if score >= min_score:
59
  item = products[idx].copy()
60
  item["score"] = score
 
82
  else:
83
  return {"error": "No image provided"}
84
 
85
+ image_emb = model.encode([image], convert_to_numpy=True, normalize_embeddings=True)
86
+ sims, indices = index.search(image_emb, top_k)
87
 
88
  results = []
89
+ for sim, idx in zip(sims[0], indices[0]):
90
+ score = float(sim) # cosine similarity
91
  if score >= min_score:
92
  item = products[idx].copy()
93
  item["score"] = score