質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

Q&A

解決済

1回答

1208閲覧

webアプリのAPI認証が進みません

sutamina

総合スコア1

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

0グッド

0クリップ

投稿2023/01/07 15:39

編集2023/01/07 15:50

前提

spotify APIとstreamlitを使ってWebアプリを制作しています。streamlitを使ってweb上に公開することはできたのですが、ローカル環境でできていたAPI認証がうまくいきません。リダイレクトuriにlocalhost:8888を指定していますが、認証の時にこのサイトにアクセスできませんと表示されて認証が進みません。

発生している問題・エラーメッセージ

google chormeで「このサイトにアクセスできません localhostで接続が拒否されました。」と表示されています。
safariで「サーバに接続できません」と表示されます。

画像

イメージ説明

試したこと

1.スマホでも認証のページを開いてみましたが、サーバが開けませんでした。

ソースコード

python

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

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

yuma.inaura

2023/01/07 15:53

Webで公開してるのに何故localhostなんでしょう?
sutamina

2023/01/07 16:04

webアプリの時にlocalhostを使ってはうまくいきませんか? 不勉強で申し訳ないです。 なんでも教えてください。
yuma.inaura

2023/01/07 16:05

localhostは自分のPCだけで動いてるやつです
sutamina

2023/01/07 16:10

なるほど... つまりローカル環境だと自分のPCでアプリを動かしているからうまく行ったけどWebで公開していると自分のPCじゃないからうまく行かないってことですね ありがとうございます。 ただ、APIの認証でリダイレクトURIを設定しないといけないんですが、通例ではどのようなURIを設定しているかご存知ですか?それとも自分で好きなのに設定して大丈夫なんでしょうか? よろしくお願いいたします
guest

回答1

0

自己解決

解決法

トークンの取得方法を変更しました。
https://spotipy.readthedocs.io/en/latest/

投稿2023/01/07 20:28

sutamina

総合スコア1

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問