-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.py
80 lines (58 loc) · 1.73 KB
/
app.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
70
71
72
73
74
75
76
77
78
79
80
from jina import DocumentArray, Flow
from jina.types.document.generators import from_files
import os
import csv
import requests
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
def save_song_from_track(sp, track_id):
try:
track = sp.track(track_id)
except Exception:
return
if track["preview_url"] is None:
return
try:
res = requests.get(track["preview_url"])
except Exception:
return
if not res.ok or not res.content:
return
with open(f"data/{track_id}.mp3", "wb") as f:
f.write(res.content)
def generate_data():
if not os.path.exists("data"):
os.makedirs("data")
if len(os.listdir("data")) != 0:
print("Data alredy present")
return
print("Populating data")
auth_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(auth_manager=auth_manager)
with open("genres_v2.csv") as f:
TOTAL_LIMIT = 15
curr_limit = 0
csv_reader = csv.DictReader(f)
for row in csv_reader:
save_song_from_track(sp, row["id"])
curr_limit += 1
if curr_limit > TOTAL_LIMIT:
break
print("Data populated!")
def check_query(resp):
for d in resp.docs:
print(f"{d.uri}, {len(d.chunks)}")
for m in d.matches:
print(f'+- {m.uri}: {m.scores["cosine"].value:.6f}, {m.tags}')
def main():
generate_data()
docs = DocumentArray(from_files("data/*.mp3"))
f = Flow.load_config("flow.yml")
with f:
f.post(on="/index", inputs=docs)
f.post(on="/search", inputs=docs, on_done=check_query)
f.protocol = "http"
f.cors = True
f.block()
if __name__ == "__main__":
main()