abhinavsunil commited on
Commit
c1757e9
Β·
verified Β·
1 Parent(s): a44ad1e

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +78 -0
main.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pandas as pd
3
+ import faiss
4
+ import torch
5
+ import numpy as np
6
+ from fastapi import FastAPI
7
+ from sentence_transformers import SentenceTransformer
8
+ from huggingface_hub import snapshot_download
9
+
10
+ REPO_ID = "abhinavsunil/kitchenelite-recipe-model"
11
+ MODEL_CACHE = "/tmp/model_cache"
12
+ TOP_K = 5
13
+
14
+ app = FastAPI(title="KitchenElite Recipe Search API")
15
+
16
+ model = None
17
+ index = None
18
+ df = None
19
+
20
+
21
+ @app.on_event("startup")
22
+ def load_assets():
23
+ global model, index, df
24
+
25
+ print("πŸš€ Downloading model repo snapshot...")
26
+
27
+ local_dir = snapshot_download(
28
+ repo_id=REPO_ID,
29
+ local_dir=MODEL_CACHE,
30
+ local_dir_use_symlinks=False
31
+ )
32
+
33
+ print("πŸ“¦ Loading metadata...")
34
+ df = pd.read_parquet(os.path.join(local_dir, "metadata.parquet"))
35
+
36
+ print("πŸ“¦ Loading FAISS index...")
37
+ index = faiss.read_index(os.path.join(local_dir, "recipes.index"))
38
+
39
+ print("πŸ“¦ Loading SentenceTransformer model...")
40
+ model = SentenceTransformer(local_dir, device="cpu")
41
+
42
+ print("βœ… All assets loaded successfully!")
43
+
44
+
45
+ @app.get("/")
46
+ def home():
47
+ return {"status": "KitchenElite API Running πŸš€"}
48
+
49
+
50
+ @app.get("/search")
51
+ def search(query: str):
52
+ query_vector = model.encode([query])
53
+ faiss.normalize_L2(query_vector)
54
+
55
+ distances, indices = index.search(
56
+ query_vector.astype("float32"),
57
+ TOP_K
58
+ )
59
+
60
+ results = df.iloc[indices[0]]
61
+
62
+ output = []
63
+ for _, row in results.iterrows():
64
+ output.append({
65
+ "name": str(row["name"]),
66
+ "ingredients": (
67
+ list(row["ingredients"])
68
+ if isinstance(row["ingredients"], np.ndarray)
69
+ else row["ingredients"]
70
+ ),
71
+ "calories": float(row["calories"]),
72
+ "protein": float(row["protein"])
73
+ })
74
+
75
+ return {
76
+ "query": query,
77
+ "results": output
78
+ }