Spaces:
Sleeping
Sleeping
Download RecipeRecommender.py from leclouxj/RecipeRecommender: direct link, hf CLI and curl.
- Browser
- Download file 1.74 kB
-
https://huggingface.co/spaces/leclouxj/RecipeRecommender/resolve/main/RecipeRecommender.py
- Command line
-
hf download hf://spaces/leclouxj/RecipeRecommender/RecipeRecommender.py
-
curl -L -o RecipeRecommender.py https://huggingface.co/spaces/leclouxj/RecipeRecommender/resolve/main/RecipeRecommender.py
1.74 kB
| from sentence_transformers import SentenceTransformer | |
| import faiss | |
| import json | |
| from fastapi import FastAPI, Query | |
| from fastapi.middleware.cors import CORSMiddleware | |
| def search(query_vector, ids): | |
| index = faiss.read_index("embeddings.index") | |
| D, I = index.search(query_vector, 1) | |
| recipe = ids[str(I[0][0])] | |
| return recipe | |
| def generate_query(query): | |
| model = SentenceTransformer("all-MiniLM-L6-v2") | |
| return model.encode([query]) | |
| def clean_recipe(obj): | |
| if isinstance(obj, dict): | |
| return {k: clean_recipe(v) for k, v in obj.items()} | |
| if isinstance(obj, list): | |
| cleaned = [] | |
| for item in obj: | |
| item_clean = clean_recipe(item) | |
| if isinstance(item_clean, str): | |
| item_clean = item_clean.replace("ADVERTISEMENT", "").strip() | |
| if item_clean: | |
| cleaned.append(item_clean) | |
| else: | |
| cleaned.append(item_clean) | |
| return cleaned | |
| if isinstance(obj, str): | |
| return obj.replace("ADVERTISEMENT", "").strip() | |
| return obj | |
| def main(query: str): | |
| with open("./ids.json", "r", encoding="utf-8") as f: | |
| ids = json.load(f) | |
| return search(generate_query(query), ids) | |
| if __name__ == '__main__': | |
| main("") | |
| app = FastAPI() | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["https://recipe-recommender-123.netlify.app/"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| def run_operation(query: str = Query(...)): | |
| result = main(query) | |
| result = clean_recipe(result) | |
| return {"Result" : result} | |
| #uvicorn backend.RecipeRecommender:app --reload | |