質問編集履歴

3

試したことを追加しました。

2023/01/07 15:50

投稿

sutamina
sutamina

スコア1

test CHANGED
File without changes
test CHANGED
@@ -9,6 +9,9 @@
9
9
 
10
10
  ### 画像
11
11
  ![イメージ説明](https://ddjkaamml8q8x.cloudfront.net/questions/2023-01-08/c6118365-229d-4984-867e-2e5a672dd622.jpeg)
12
+
13
+ ### 試したこと
14
+ 1.スマホでも認証のページを開いてみましたが、サーバが開けませんでした。
12
15
 
13
16
  ### ソースコード
14
17
  ```python

2

画像の追加

2023/01/07 15:49

投稿

sutamina
sutamina

スコア1

test CHANGED
File without changes
test CHANGED
@@ -7,7 +7,10 @@
7
7
  google chormeで「このサイトにアクセスできません localhostで接続が拒否されました。」と表示されています。
8
8
  safariで「サーバに接続できません」と表示されます。
9
9
 
10
+ ### 画像
11
+ ![イメージ説明](https://ddjkaamml8q8x.cloudfront.net/questions/2023-01-08/c6118365-229d-4984-867e-2e5a672dd622.jpeg)
12
+
10
- #ソースコード
13
+ ### ソースコード
11
14
  ```python
12
15
  import glob
13
16
  import numpy as np

1

読みやすくしました。

2023/01/07 15:47

投稿

sutamina
sutamina

スコア1

test CHANGED
File without changes
test CHANGED
@@ -7,6 +7,173 @@
7
7
  google chormeで「このサイトにアクセスできません localhostで接続が拒否されました。」と表示されています。
8
8
  safariで「サーバに接続できません」と表示されます。
9
9
 
10
+ #ソースコード
11
+ ```python
12
+ import glob
13
+ import numpy as np
14
+ from sklearn.preprocessing import MinMaxScaler
15
+ import streamlit as st
16
+ import os
17
+ import pandas as pd
18
+ import spotipy
19
+ import spotify_id as si
20
+ from spotipy.oauth2 import SpotifyOAuth
10
21
 
11
22
 
12
23
 
24
+ def main():
25
+ with st.form('送信フォーム'):
26
+ URL,genre,tempo,energy = initial_display()
27
+ submitted = st.form_submit_button("送信")
28
+
29
+ if submitted:
30
+ with st.spinner('プレイリスト取得中...'):
31
+ url_to_items(URL)
32
+ with st.spinner('楽曲情報取得中...'):
33
+ all_song_data,target_song_data = load_items(genre)
34
+ with st.spinner('推薦中...(10分かかる場合があります)'):
35
+ recommendation_ids = recommender(all_song_data,target_song_data,tempo,energy)
36
+ with st.spinner('プレイリスト作成中...'):
37
+ playlist_id = create_playlist(playlist_name='おすすめ',items=recommendation_ids)
38
+ st.write('作成したプレイリスト')
39
+ st.write('https://open.spotify.com/playlist/'+playlist_id)
40
+
41
+
42
+ #初期表示
43
+ def initial_display():
44
+ #タイトル表示
45
+ st.title('音楽推薦システム')
46
+ #Spotify Playlist の共有URLを入力
47
+ URL = st.text_input('URLを入力',value='https://open.spotify.com/playlist/2WYGH0TlgpPwIdMZp0zhVH?si=FM2FYSlgSXu0j-HtREpgcQ')
48
+
49
+ #ユーザが選択した要素
50
+ tempo = st.slider(label='テンポ',min_value=0,max_value=100,value=50)
51
+ energy = st.slider(label = 'エネルギー',min_value=0,max_value=100,value=50)
52
+
53
+ #ユーザが選択したジャンル
54
+ genre = st.selectbox('ジャンルを選択',('全て選択','ボカロ','J-POP'))
55
+
56
+ return URL,genre,tempo,energy
57
+
58
+
59
+ #プレイリスト共有URLからtarget_playlist_items.csvを作成する
60
+ def url_to_items(URL):
61
+ #共有URLからプレイリストidを抜き出す
62
+ target1 = 'playlist/'
63
+ target2 = '?'
64
+ idx1 = URL.find(target1)
65
+ idx2 = URL.find(target2)
66
+ playlist_id = URL[idx1+9:idx2]
67
+
68
+ #楽曲情報を格納するdataframe
69
+ items_df = pd.DataFrame()
70
+
71
+ #playlist_idからプレイリスト内の楽曲情報を取り出せる
72
+ playlist_items = sp.playlist_items(playlist_id)['items']
73
+
74
+ #playlist_itemsの各楽曲から解析情報を取り出す
75
+ for track in playlist_items:
76
+ result = sp.audio_features(track['track']['id'])
77
+ result[0]['name'] = track['track']['name']
78
+ item = pd.DataFrame(result[0].values(),index=result[0].keys()).T
79
+ item = item.set_index('name')
80
+ items_df = pd.concat([items_df,item])
81
+
82
+ #target_playlist_items.csvを作成
83
+ dir = os.path.dirname(__file__)
84
+ file_name = os.path.join(dir,'csvfiles','target_playlist_items.csv')
85
+ items_df.to_csv(file_name,encoding='utf-8',index=True)
86
+
87
+
88
+ def load_items(genre):
89
+ #選択されたジャンルによって取得する曲を選択
90
+ if genre == '全て選択':
91
+ song_path = glob.glob('/Users/iguchihiroto/Documents/programming/app/csvfiles/*/*.csv')
92
+ if genre == 'ボカロ':
93
+ song_path = glob.glob('/Users/iguchihiroto/Documents/programming/app/csvfiles/vocaloid/*.csv')
94
+ if genre == 'J-POP':
95
+ song_path = glob.glob('/Users/iguchihiroto/Documents/programming/app/csvfiles/Jpop/*.csv')
96
+
97
+ #all_song_data:ジャンルに対応した全ての楽曲のデータ
98
+ all_song_data = pd.DataFrame()
99
+ #ジャンルに対応した.csvのパスを取得
100
+ for path in song_path:
101
+ song_data = pd.read_csv(path)
102
+ all_song_data = pd.concat([all_song_data,song_data])
103
+
104
+ target_song_data = pd.read_csv('/Users/iguchihiroto/Documents/programming/app/csvfiles/target_playlist_items.csv')
105
+ #推薦の対象となる曲にnotice = 1をそれ以外にnotice = 0を
106
+ all_song_data['notice'] = 0
107
+ target_song_data['notice'] = 1
108
+ #列名の整頓
109
+ all_song_data = all_song_data.reindex(columns=['name','id','notice','danceability','energy',
110
+ 'loudness','speechiness','acousticness','instrumentalness','liveness','valence','tempo'])
111
+ target_song_data = target_song_data.reindex(columns=['name','id','notice','danceability','energy',
112
+ 'loudness','speechiness','acousticness','instrumentalness','liveness','valence','tempo'])
113
+
114
+ return all_song_data,target_song_data
115
+
116
+
117
+ def recommender(all_song_data,target_song_data,tempo,energy):
118
+ recommendation_ids = []
119
+ #全曲データにtargetデータの値を一曲ずつ入れて最近傍探索で一番近い曲を探す
120
+ for index,song_data in target_song_data.iterrows():
121
+ #合体したデータの格納先
122
+ ori_song_data = pd.DataFrame()
123
+ ori_song_data = all_song_data.append(song_data)
124
+ #正規化
125
+ minmax_sc = MinMaxScaler()
126
+ X = ori_song_data.loc[:,'danceability':'tempo']
127
+ X = minmax_sc.fit_transform(X)
128
+ ori_song_data.loc[:,'danceability':'tempo'] = X
129
+
130
+ #バイアス
131
+ tempo_bias = tempo*-0.015+2
132
+ energy_bias = energy*-0.015+2
133
+ ori_song_data['tempo']*=tempo_bias
134
+ ori_song_data['energy']*=energy_bias
135
+ #最近傍探索で一番近いものを探す
136
+ comparison_songs = ori_song_data[ori_song_data.notice == 0]
137
+ target_song = ori_song_data[ori_song_data.notice == 1]
138
+ np_target_song = target_song[['danceability','energy','loudness','speechiness','acousticness',
139
+ 'instrumentalness','liveness','valence','tempo']].values
140
+ #距離
141
+ dis = 9999
142
+ for index1,comparison_song in comparison_songs.iterrows():
143
+ np_comparison_song = comparison_song[['danceability','energy','loudness','speechiness','acousticness',
144
+ 'instrumentalness','liveness','valence','tempo']].values
145
+ new_dis = np.linalg.norm(np_target_song-np_comparison_song)
146
+ if new_dis < dis:
147
+ dis = new_dis
148
+ #一番近い曲のid
149
+ id = comparison_song['id']
150
+ #最近傍探索の結果のidをlistで
151
+ recommendation_ids.append(id)
152
+
153
+ return recommendation_ids
154
+
155
+
156
+ def create_playlist(playlist_name,items):
157
+ scope = "playlist-modify-public"
158
+ sp2 = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=si.id(),
159
+ client_secret=si.secret(),
160
+ redirect_uri="http://localhost:8888/callback",
161
+ scope=scope),
162
+ language='ja')
163
+
164
+ id = sp2.user_playlist_create(user='nohoarito_yuzu_334129',name=playlist_name)['id']
165
+ sp2.playlist_add_items(playlist_id=id,items = items)
166
+ return id
167
+
168
+
169
+ if __name__ == '__main__':
170
+ sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=si.id(),
171
+ client_secret=si.secret(),
172
+ redirect_uri="http://localhost:8888/callback",
173
+ scope="user-read-recently-played"),
174
+ language='ja')
175
+ main()
176
+ ```
177
+
178
+
179
+