-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
56 lines (44 loc) · 1.59 KB
/
app.py
File metadata and controls
56 lines (44 loc) · 1.59 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
from flask import Flask, request, jsonify
import pandas as pd
from sentence_transformers import SentenceTransformer
import numpy as np
import faiss
from flask_cors import CORS
import re
import unicodedata
import string
def clean_text(text):
if not isinstance(text, str):
text = str(text) if text is not None else ""
text = unicodedata.normalize('NFKC', text)
text = ''.join(c for c in text if c in string.printable)
text = re.sub(r'\s+', ' ', text).strip()
return text
print("Loading data and model...")
df = pd.read_csv('data.csv')
model = SentenceTransformer("all-MiniLM-L6-v2")
loaded_index = faiss.read_index('index_file.index')
app = Flask(__name__)
CORS(app)
@app.route('/recommend', methods=['POST'])
def recommend_games():
user_query = request.json.get("query")
user_query = clean_text(user_query) if user_query else None
top_n = request.json.get("top_n", 5)
if not user_query:
return jsonify({"error": "Query not provided."}), 400
query_embedding = model.encode([user_query], convert_to_numpy=True)
query_embedding = query_embedding / np.linalg.norm(query_embedding)
distances, indices = loaded_index.search(query_embedding, top_n)
recommendations = []
for idx, dist in zip(indices[0], distances[0]):
game_info = {
"cover": df.iloc[idx]["cover"],
"score": float(dist)
}
recommendations.append(game_info)
return jsonify({"recommendations": recommendations})
if __name__ == '__main__':
import os
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)