-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmenu.py
More file actions
60 lines (46 loc) ยท 2.17 KB
/
menu.py
File metadata and controls
60 lines (46 loc) ยท 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from flask import Flask, request, jsonify
from flask_cors import CORS
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
app = Flask(__name__)
CORS(app)
# CSV ๋ฐ์ดํฐ ๋ก๋
file_path = "./utils/TB_RECIPE_SEARCH_241226.csv"
df = pd.read_csv(file_path, encoding="utf-8")
# ํ์ํ ์ปฌ๋ผ๋ง ์ถ์ถ (๋ ์ํผ ์ ๋ชฉ, ์ฌ๋ฃ)
df = df[['RCP_TTL', 'CKG_MTRL_CN']].dropna()
# ํ
์คํธ ์ ์ (๋ถํ์ํ ๋ฌธ์ ์ ๊ฑฐ)
df['CKG_MTRL_CN'] = df['CKG_MTRL_CN'].str.replace(r'\[์ฌ๋ฃ\]|\d+|\|', '', regex=True)
# TF-IDF ๋ฒกํฐ ๋ณํ๊ธฐ ์์ฑ
vectorizer = TfidfVectorizer()
ingredient_vectors = vectorizer.fit_transform(df["CKG_MTRL_CN"]) # ๋ชจ๋ ๋ ์ํผ์ ์ฌ๋ฃ๋ฅผ ๋ฒกํฐํ
def find_top_recipes(user_ingredients, top_n=3):
"""์ฌ์ฉ์๊ฐ ์
๋ ฅํ ์ฌ๋ฃ ๋ฆฌ์คํธ์ ๊ฐ์ฅ ์ ์ฌํ ์์ N๊ฐ ๋ ์ํผ๋ฅผ ์ฐพ์"""
user_query = " ".join(user_ingredients) # ์ฌ์ฉ์ ์
๋ ฅ์ ๋ฌธ์์ด๋ก ๋ณํ
user_vector = vectorizer.transform([user_query]) # ์ฌ์ฉ์ ์
๋ ฅ์ ๋ฒกํฐ๋ก ๋ณํ
# ์ฝ์ฌ์ธ ์ ์ฌ๋ ๊ณ์ฐ
similarities = cosine_similarity(user_vector, ingredient_vectors).flatten()
# ์์ top 3๊ฐ ์ธ๋ฑ์ค ๊ฐ์ ธ์ค๊ธฐ
top_indices = similarities.argsort()[-top_n:][::-1] # ์ ์ฌ๋๊ฐ ๋์ ์์ผ๋ก ์ ๋ ฌ
# ์์ ์ถ์ฒ ๋ ์ํผ ๋ฆฌ์คํธ ๋ฐํ
top_recipes = []
for idx in top_indices:
top_recipes.append({
"recipe_title": df.iloc[idx]["RCP_TTL"],
"ingredients": df.iloc[idx]["CKG_MTRL_CN"]
})
return top_recipes
# Flask API ์๋ํฌ์ธํธ ์ค์
@app.route("/recommend", methods=["POST"])
def recommend():
"""์ฌ์ฉ์๊ฐ ์
๋ ฅํ ์ฌ๋ฃ ๋ฆฌ์คํธ๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ๊ฐ์ฅ ์ ์ฌํ ์์ 3๊ฐ ๋ ์ํผ ์ถ์ฒ"""
data = request.get_json()
user_ingredients = data.get("ingredients", [])
if not user_ingredients:
return jsonify({"error": "์ฌ๋ฃ ๋ชฉ๋ก์ด ๋น์ด ์์ต๋๋ค."}), 400
top_recipes = find_top_recipes(user_ingredients, top_n=3)
return jsonify(top_recipes)
# Flask ์๋ฒ ์คํ
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)