-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
70 lines (55 loc) · 1.64 KB
/
main.py
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
61
62
63
64
65
66
67
68
69
import mysql.connector
import pandas as pd
from sklearn.neighbors import NearestNeighbors
from sklearn.feature_extraction.text import TfidfVectorizer
from flask import Flask, request, jsonify
import math
# mysql://root:moha@localhost:3306/khedma-market
# Establish connection to MySQL database
connection = mysql.connector.connect(
host="localhost",
user="root",
password='moha',
database="khedma-market",
port="3306",
auth_plugin='mysql_native_password'
)
# Retrieve gig data from the database
query = "SELECT id, title FROM gigs" # Fetch both gig ID and title
cursor = connection.cursor()
cursor.execute(query)
data = cursor.fetchall()
print(data)
# Close connection
cursor.close()
connection.close()
column_names = ['id', 'title']
data_df = pd.DataFrame(data, columns=column_names)
data_df=data_df.dropna()
data_df=data_df.reset_index()
print(data_df)
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(data_df['title'])
print(X)
# Train KNN model
k=int(math.sqrt(len(data_df)))
if k%2!=0:
k=k-1
if k == 0:
k = 1
knn_model = NearestNeighbors(n_neighbors=k, metric='cosine')
knn_model.fit(X)
app = Flask(__name__)
@app.route('/recommend', methods=['POST'])
def recommend_gigs():
query = request.json['query']
query_vector = vectorizer.transform([query])
distances, indices = knn_model.kneighbors(query_vector)
recommended_gigs = []
for idx in indices[0]:
gig_id = data_df['id'][idx]
gig_title = data_df['title'][idx]
recommended_gigs.append({'id': gig_id, 'title': gig_title})
return jsonify(recommended_gigs)
if __name__ == '__main__':
app.run(debug=True)