garvitcpp commited on
Commit
398778b
·
verified ·
1 Parent(s): 28925d3

Upload 19 files

Browse files
.gitattributes ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ Backend/data/scaled_df.csv filter=lfs diff=lfs merge=lfs -text
2
+ Backend/data/tracks.csv filter=lfs diff=lfs merge=lfs -text
3
+ Backend/ml_models/label_encoder_album.joblib filter=lfs diff=lfs merge=lfs -text
Backend/.flaskenv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ FLASK_APP=run
2
+ FLASK_ENV=development
Backend/.gitignore ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Created by https://www.toptal.com/developers/gitignore/api/python
2
+ # Edit at https://www.toptal.com/developers/gitignore?templates=python
3
+
4
+ ### Python ###
5
+ # Byte-compiled / optimized / DLL files
6
+ __pycache__/
7
+ *.py[cod]
8
+ *$py.class
9
+
10
+ # C extensions
11
+ *.so
12
+
13
+ # Distribution / packaging
14
+ .Python
15
+ build/
16
+ develop-eggs/
17
+ dist/
18
+ downloads/
19
+ eggs/
20
+ .eggs/
21
+ lib/
22
+ lib64/
23
+ parts/
24
+ sdist/
25
+ var/
26
+ wheels/
27
+ share/python-wheels/
28
+ *.egg-info/
29
+ .installed.cfg
30
+ *.egg
31
+ MANIFEST
32
+
33
+ # PyInstaller
34
+ # Usually these files are written by a python script from a template
35
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
36
+ *.manifest
37
+ *.spec
38
+
39
+ # Installer logs
40
+ pip-log.txt
41
+ pip-delete-this-directory.txt
42
+
43
+ # Unit test / coverage reports
44
+ htmlcov/
45
+ .tox/
46
+ .nox/
47
+ .coverage
48
+ .coverage.*
49
+ .cache
50
+ nosetests.xml
51
+ coverage.xml
52
+ *.cover
53
+ *.py,cover
54
+ .hypothesis/
55
+ .pytest_cache/
56
+ cover/
57
+
58
+ # Translations
59
+ *.mo
60
+ *.pot
61
+
62
+ # Django stuff:
63
+ *.log
64
+ local_settings.py
65
+ db.sqlite3
66
+ db.sqlite3-journal
67
+
68
+ # Flask stuff:
69
+ instance/
70
+ .webassets-cache
71
+
72
+ # Scrapy stuff:
73
+ .scrapy
74
+
75
+ # Sphinx documentation
76
+ docs/_build/
77
+
78
+ # PyBuilder
79
+ .pybuilder/
80
+ target/
81
+
82
+ # Jupyter Notebook
83
+ .ipynb_checkpoints
84
+
85
+ # IPython
86
+ profile_default/
87
+ ipython_config.py
88
+
89
+ # pyenv
90
+ # For a library or package, you might want to ignore these files since the code is
91
+ # intended to run in multiple environments; otherwise, check them in:
92
+ # .python-version
93
+
94
+ # pipenv
95
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
96
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
97
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
98
+ # install all needed dependencies.
99
+ #Pipfile.lock
100
+
101
+ # poetry
102
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
103
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
104
+ # commonly ignored for libraries.
105
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
106
+ #poetry.lock
107
+
108
+ # pdm
109
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
110
+ #pdm.lock
111
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
112
+ # in version control.
113
+ # https://pdm.fming.dev/#use-with-ide
114
+ .pdm.toml
115
+
116
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
117
+ __pypackages__/
118
+
119
+ # Celery stuff
120
+ celerybeat-schedule
121
+ celerybeat.pid
122
+
123
+ # SageMath parsed files
124
+ *.sage.py
125
+
126
+ # Environments
127
+ .env
128
+ .venv
129
+ env/
130
+ venv/
131
+ ENV/
132
+ env.bak/
133
+ venv.bak/
134
+
135
+ # Spyder project settings
136
+ .spyderproject
137
+ .spyproject
138
+
139
+ # Rope project settings
140
+ .ropeproject
141
+
142
+ # mkdocs documentation
143
+ /site
144
+
145
+ # mypy
146
+ .mypy_cache/
147
+ .dmypy.json
148
+ dmypy.json
149
+
150
+ # Pyre type checker
151
+ .pyre/
152
+
153
+ # pytype static type analyzer
154
+ .pytype/
155
+
156
+ # Cython debug symbols
157
+ cython_debug/
158
+
159
+ # PyCharm
160
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
161
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
162
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
163
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
164
+ #.idea/
165
+
166
+ ### Python Patch ###
167
+ # Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
168
+ poetry.toml
169
+
170
+ # ruff
171
+ .ruff_cache/
172
+
173
+ # LSP config files
174
+ pyrightconfig.json
175
+
176
+ # End of https://www.toptal.com/developers/gitignore/api/python
177
+ Chat
178
+
179
+ New Conversation
180
+ 🤓 Explain a complex thing
181
+
182
+ Explain Artificial Intelligence so that I can explain it to my six-year-old child.
183
+
184
+
185
+ 🧠 Get suggestions and create new ideas
186
+
187
+ Please give me the best 10 travel ideas around the world
188
+
189
+
190
+ 💭 Translate, summarize, fix grammar and more…
191
+
192
+ Translate "I love you into" French
193
+
194
+
195
+ coin image
196
+ 10
197
+ Upgrade
198
+
199
+
200
+ gpt image
201
+ GPT-3.5
202
+ Ask me anything...
203
+
204
+
205
+ Make a Review & Earn Credit ❤
206
+ Chat
207
+ Ask
208
+ Search
209
+ Write
210
+ Image
211
+ ChatPDF
212
+ Vision
213
+ Full Page
214
+ Invite & Earn
215
+
216
+
Backend/app/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask
2
+ from flask_cors import CORS
3
+ from config import Config
4
+ import logging
5
+
6
+ def create_app(config_class=Config):
7
+ app = Flask(__name__)
8
+ app.config.from_object(config_class)
9
+
10
+ # Configure CORS
11
+ CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)
12
+
13
+ # Configure logging
14
+ logging.basicConfig(level=logging.INFO)
15
+
16
+ # Register blueprints
17
+ from app.routes.recommendation import bp as recommendation_bp
18
+ app.register_blueprint(recommendation_bp)
19
+
20
+ return app
Backend/app/models/__init__.py ADDED
File without changes
Backend/app/models/ml_models.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from joblib import load
3
+ import os
4
+ import logging
5
+ from config import Config
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ class MLModels:
10
+ _instance = None
11
+ _is_loaded = False
12
+
13
+ def __new__(cls):
14
+ if cls._instance is None:
15
+ cls._instance = super(MLModels, cls).__new__(cls)
16
+ cls._instance._initialized = False
17
+ return cls._instance
18
+
19
+ def __init__(self):
20
+ if self._initialized:
21
+ return
22
+
23
+ self.tracks = None
24
+ self.scaled_df = None
25
+ self.scaler = None
26
+ self.kmeans = None
27
+ self.label_encoder_artists = None
28
+ self.label_encoder_genre = None
29
+ self._initialized = True
30
+
31
+ def load_models(self):
32
+ """Load all required models and data if not already loaded"""
33
+ if not self._is_loaded:
34
+ try:
35
+ logger.info("Loading data and models...")
36
+
37
+ # Use Config paths
38
+ self.tracks = pd.read_csv(os.path.join(Config.DATA_DIR, 'tracks.csv'))
39
+ self.scaled_df = pd.read_csv(os.path.join(Config.DATA_DIR, 'scaled_df.csv'))
40
+ self.scaler = load(os.path.join(Config.MODEL_DIR, 'scaler.joblib'))
41
+ self.kmeans = load(os.path.join(Config.MODEL_DIR, 'revibe.joblib'))
42
+ self.label_encoder_artists = load(os.path.join(Config.MODEL_DIR, 'label_encoder_artists.joblib'))
43
+ self.label_encoder_genre = load(os.path.join(Config.MODEL_DIR, 'label_encoder_genre.joblib'))
44
+
45
+ self._is_loaded = True
46
+ logger.info("Data and models loaded successfully")
47
+ except Exception as e:
48
+ logger.error(f"Error loading models: {str(e)}")
49
+ raise
50
+
51
+ @property
52
+ def is_loaded(self):
53
+ return self._is_loaded
Backend/app/routes/__init__.py ADDED
File without changes
Backend/app/routes/recommendation.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Blueprint, jsonify, request
2
+ from app.services.recommendation import RecommendationService
3
+ import logging
4
+
5
+ bp = Blueprint('recommendation', __name__)
6
+ logger = logging.getLogger(__name__)
7
+
8
+ @bp.route('/health', methods=['GET'])
9
+ def health_check():
10
+ return jsonify({'status': 'healthy'}), 200
11
+
12
+ @bp.route('/recommend', methods=['POST'])
13
+ def recommend():
14
+ try:
15
+ data = request.get_json()
16
+ song_input = data.get('song', '').strip()
17
+ artist_input = data.get('artist', '').strip()
18
+ genre_input = data.get('genre', '').strip()
19
+
20
+ recommendation_service = RecommendationService()
21
+
22
+ if song_input:
23
+ recommendations = recommendation_service.get_recommendations_by_song(song_input)
24
+ elif artist_input and genre_input:
25
+ recommendations = recommendation_service.get_recommendations_by_artist_and_genre(artist_input, genre_input)
26
+ else:
27
+ return jsonify({'error': 'Invalid input. Please provide either a song or both artist and genre.'}), 400
28
+
29
+ if isinstance(recommendations, dict) and 'error' in recommendations:
30
+ return jsonify(recommendations), 400
31
+
32
+ return jsonify(recommendations)
33
+
34
+ except Exception as e:
35
+ logger.error(f"An error occurred: {str(e)}", exc_info=True)
36
+ return jsonify({'error': str(e)}), 500
Backend/app/services/__init__.py ADDED
File without changes
Backend/app/services/recommendation.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from app.models.ml_models import MLModels
3
+
4
+ class RecommendationService:
5
+ def __init__(self):
6
+ self.ml_models = MLModels()
7
+ # Ensure data is loaded
8
+ self.ml_models.load_models()
9
+
10
+ def get_recommendations_by_song(self, song_input):
11
+ tracks = self.ml_models.tracks
12
+ scaled_df = self.ml_models.scaled_df
13
+
14
+ parts = song_input.rsplit(' - ', 1)
15
+ if len(parts) != 2:
16
+ return {'error': "Invalid song input format. Please use 'Song Name - Artist Name'."}
17
+
18
+ song_name, artist_from_input = parts
19
+ matching_songs = tracks[(tracks['track_name'].str.contains(song_name, case=False, na=False)) &
20
+ (tracks['artists'].str.contains(artist_from_input, case=False, na=False))]
21
+
22
+ if len(matching_songs) == 0:
23
+ return {'error': "No matching songs found."}
24
+
25
+ selected_song_idx = matching_songs.index[0]
26
+ selected_song_cluster = scaled_df.loc[selected_song_idx, 'cluster']
27
+ cluster_songs = scaled_df[scaled_df['cluster'] == selected_song_cluster]
28
+
29
+ recommendations = cluster_songs.sample(min(10, len(cluster_songs)))
30
+ recommendations = recommendations.sample(min(5, len(recommendations)))
31
+
32
+ return self._format_recommendations(recommendations)
33
+
34
+ def get_recommendations_by_artist_and_genre(self, artist_name, genre):
35
+ tracks = self.ml_models.tracks
36
+ scaled_df = self.ml_models.scaled_df
37
+ scaler = self.ml_models.scaler
38
+ kmeans = self.ml_models.kmeans
39
+
40
+ matching_songs = tracks[(tracks['track_genre'].str.lower().str.contains(genre.lower(), na=False)) |
41
+ (tracks['artists'].str.lower().str.contains(artist_name.lower(), na=False))]
42
+
43
+ if len(matching_songs) == 0:
44
+ return {'error': "No matching songs found for the given artist or genre."}
45
+
46
+ avg_features = matching_songs.loc[:, ['tempo', 'loudness', 'danceability', 'energy', 'acousticness',
47
+ 'instrumentalness', 'speechiness', 'liveness', 'valence']].mean().values
48
+
49
+ input_df = pd.DataFrame({
50
+ 'tempo': [avg_features[0]],
51
+ 'loudness': [avg_features[1]],
52
+ 'track_genre_encoded': [tracks['track_genre_encoded'].mean()],
53
+ 'artists_encoded': [tracks['artists_encoded'].mean()],
54
+ 'danceability': [avg_features[2]],
55
+ 'energy': [avg_features[3]],
56
+ 'acousticness': [avg_features[4]],
57
+ 'instrumentalness': [avg_features[5]],
58
+ 'speechiness': [avg_features[6]],
59
+ 'liveness': [avg_features[7]],
60
+ 'valence': [avg_features[8]]
61
+ })
62
+
63
+ input_features = scaler.transform(input_df)
64
+ closest_cluster = kmeans.predict(input_features)[0]
65
+ cluster_songs = scaled_df[scaled_df['cluster'] == closest_cluster]
66
+
67
+ recommendations = cluster_songs.sample(min(10, len(cluster_songs)))
68
+ recommendations = recommendations.sample(min(5, len(recommendations)))
69
+
70
+ return self._format_recommendations(recommendations)
71
+
72
+ def _format_recommendations(self, recommendations):
73
+ tracks = self.ml_models.tracks
74
+ recommended_song_names = tracks.loc[recommendations.index, 'track_name']
75
+ recommended_artist_names = tracks.loc[recommendations.index, 'artists']
76
+
77
+ return [{'song_name': song_name, 'artist': artist}
78
+ for song_name, artist in zip(recommended_song_names, recommended_artist_names)]
Backend/commands.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ Backend\my_project_env\Scripts\activate
2
+ cd C:\Users\garvi\Desktop\Website\Backend
3
+ python index.py
Backend/config.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ class Config:
4
+ DEBUG = os.environ.get('FLASK_DEBUG', 'False') == 'True'
5
+ PORT = int(os.environ.get('PORT', 5000))
6
+ DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
7
+ MODEL_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ml_models')
Backend/data/scaled_df.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f865fb27a3ea090a8605fb6f653179bd81783a3ce28c75e48d30b9da5b64f363
3
+ size 24877337
Backend/data/tracks.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3bf489cb06b71aded845531b012597943e64cc235c620368415ae3a6e9d95f12
3
+ size 17551645
Backend/ml_models/label_encoder_album.joblib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:249235edb343d58ffc9546ffcd993fe052d10d0cc077058365450bc4a17a8d6c
3
+ size 1429578
Backend/ml_models/label_encoder_artists.joblib ADDED
Binary file (991 kB). View file
 
Backend/ml_models/label_encoder_genre.joblib ADDED
Binary file (2.12 kB). View file
 
Backend/ml_models/revibe.joblib ADDED
Binary file (457 kB). View file
 
Backend/ml_models/scaler.joblib ADDED
Binary file (1.36 kB). View file
 
Backend/run.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from app import create_app
2
+
3
+ app = create_app()
4
+
5
+ if __name__ == '__main__':
6
+ app.run(host='0.0.0.0', port=app.config['PORT'])