Update main.py
Browse files
main.py
CHANGED
|
@@ -16,16 +16,16 @@ os.environ["SENTENCE_TRANSFORMERS_HOME"] = "./cache"
|
|
| 16 |
|
| 17 |
app = FastAPI()
|
| 18 |
|
| 19 |
-
# Enable CORS (
|
| 20 |
app.add_middleware(
|
| 21 |
CORSMiddleware,
|
| 22 |
-
allow_origins=["*"], #
|
| 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,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 |
-
|
| 54 |
|
| 55 |
results = []
|
| 56 |
-
for
|
| 57 |
-
score = float(
|
| 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 |
-
|
| 87 |
|
| 88 |
results = []
|
| 89 |
-
for
|
| 90 |
-
score = float(
|
| 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
|