{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "22754f82", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "c:\\Users\\leclouxj\\Projects\\Python\\RecipeRecommendation\\.venv\\Lib\\site-packages\\tqdm\\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", " from .autonotebook import tqdm as notebook_tqdm\n" ] } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "from sentence_transformers import SentenceTransformer\n", "import faiss\n", "import json" ] }, { "cell_type": "code", "execution_count": 2, "id": "bd46d56d", "metadata": {}, "outputs": [], "source": [ "with open(\"./Data/recipes_raw_nosource_ar.json\", \"r\", encoding=\"utf-8\") as f:\n", " data = json.load(f)\n", "recipes = list(data.values())\n", "ids = {i: recipe for i, recipe in enumerate(recipes)}\n", "with open(\"ids.json\", \"w\") as f:\n", " json.dump(ids, f, indent=4)" ] }, { "cell_type": "code", "execution_count": 75, "id": "7ec08885", "metadata": {}, "outputs": [], "source": [ "model = SentenceTransformer(\"all-MiniLM-L6-v2\")\n", "embeddings = model.encode(recipes)" ] }, { "cell_type": "code", "execution_count": 116, "id": "1a20013a", "metadata": {}, "outputs": [], "source": [ "query = ['Chinese fried chicken']\n", "query_vector = model.encode(query)" ] }, { "cell_type": "code", "execution_count": 117, "id": "91e2f38b", "metadata": {}, "outputs": [], "source": [ "index = faiss.IndexFlatL2(model.get_sentence_embedding_dimension())\n", "index.add(embeddings)\n", "faiss.write_index(index, \"embeddings.index\")" ] }, { "cell_type": "code", "execution_count": 118, "id": "4ba2ac63", "metadata": {}, "outputs": [], "source": [ "index = faiss.read_index(\"embeddings.index\")\n", "D, I = index.search(query_vector, 1)\n", "\n", "recipe = ids[I[0][0]]\n", "with open(\"recipe.json\", \"w\", encoding=\"utf-8\") as f:\n", " json.dump(recipe, f, indent=4, ensure_ascii=False)\n" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.0" } }, "nbformat": 4, "nbformat_minor": 5 }