|
| 1 | +import os |
| 2 | +import numpy as np |
| 3 | +from flask import Flask, jsonify, request |
| 4 | +from implicit.als import AlternatingLeastSquares |
| 5 | +from implicit.datasets.lastfm import get_lastfm |
| 6 | +from implicit.nearest_neighbours import bm25_weight |
| 7 | + |
| 8 | + |
| 9 | +app = Flask(__name__) |
| 10 | + |
| 11 | +model = AlternatingLeastSquares(factors=50, dtype=np.float32) |
| 12 | + |
| 13 | + |
| 14 | +try: |
| 15 | + artists = np.load("artists.npy", allow_pickle=True) |
| 16 | + model = model.load("model.npz") |
| 17 | +except Exception as e: |
| 18 | + print(e) |
| 19 | + # Load lastfm dataset and fit model |
| 20 | + artists, _, plays = get_lastfm() |
| 21 | + plays = bm25_weight(plays, K1=100, B=0.8).tocsr() |
| 22 | + user_plays = plays.T.tocsr() |
| 23 | + model.fit(user_plays[:2000]) |
| 24 | + model.save("model") |
| 25 | + np.save("artists", artists) |
| 26 | + |
| 27 | + |
| 28 | +@app.route('/recommend', methods=['POST']) |
| 29 | +def recommend(): |
| 30 | + # Parse JSON request body |
| 31 | + req_data = request.form |
| 32 | + artist_name = req_data['artist'] |
| 33 | + |
| 34 | + # Get artist ID |
| 35 | + artist_id = None |
| 36 | + for i, a in enumerate(artists): |
| 37 | + if a.lower() == artist_name.lower(): |
| 38 | + artist_id = i |
| 39 | + break |
| 40 | + |
| 41 | + if artist_id is None: |
| 42 | + return jsonify({'error': 'Artist not found'}) |
| 43 | + |
| 44 | + # Get recommended artists |
| 45 | + similar_ids, _ = model.similar_items(artist_id, N=10) |
| 46 | + similar_artists = [artists[i] for i in similar_ids] |
| 47 | + |
| 48 | + return jsonify({'similar_artists': similar_artists}) |
| 49 | + |
| 50 | + |
| 51 | +@app.route("/") |
| 52 | +def index(): |
| 53 | + return ''' |
| 54 | +<!DOCTYPE html> |
| 55 | +<html> |
| 56 | + <head> |
| 57 | + <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> |
| 58 | + </head> |
| 59 | + <body style="display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f8f9fa;"> |
| 60 | + <div style="width: 40%; text-align: center;"> |
| 61 | + <h1 style="color: #4a4a4a; margin-bottom: 30px;">Recommendation API</h1> |
| 62 | + <form action="/recommend" method="POST" style="display: flex; flex-direction: column; align-items: center;"> |
| 63 | + <label for="artist" style="color: #4a4a4a; margin-bottom: 10px;">Artist name:</label> |
| 64 | + <input type="text" id="artist" name="artist" required autofocus class="form-control" style="margin-bottom: 15px;"> |
| 65 | + <input type="submit" value="Get recommendations" class="btn btn-primary"> |
| 66 | + </form> |
| 67 | + </div> |
| 68 | + </body> |
| 69 | +</html>''' |
| 70 | + |
| 71 | + |
| 72 | +if os.getenv("DEFANG_FQDN"): |
| 73 | + print("FQDN:", "https://"+os.getenv("DEFANG_FQDN")) |
| 74 | + |
| 75 | + |
| 76 | +if __name__ == '__main__': |
| 77 | + app.run(debug=True, host='0.0.0.0') |
0 commit comments