-
Notifications
You must be signed in to change notification settings - Fork 0
/
youtube_client.py
183 lines (141 loc) · 6.29 KB
/
youtube_client.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import os
from requests import request
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
import requests
import urllib
search_token="BQCowN_TBBVyFPmrHwI6xmCf5CnZRyaY2OmZW8_y8qDT3vJaJb3q48RhgXtf38UoFyP40qQCAtXD0ueDMQvTxdHe50nJg6aeQW6heUoN3MgwPPOvrOs18FhGxkitPIXZyEjE1UrfOp7ccBWcBfSZkXDMJ_5mLbEQkF6nRsEn5A6SJqopHUjr1QiXs_Rnlrdy50o"
songs=[]
all_song_info = {}
def get_spotify_uri(song_name,artist):
query=urllib.parse.quote(f'{artist} {song_name}')
url ="https://api.spotify.com/v1/search?q={}&type=track".format(query)
response = requests.get(url,headers={
"Content-Type":"application/json","Authorization": "Bearer {}".format(search_token)
})
response_json = response.json()
songs = response_json["tracks"]["items"]
#only use the first song
try:
uri = songs[0]["uri"]
except IndexError:
uri = 'null'
return uri
# class Playlist(object):
# def __init__(self,id,title):
# self.id=id
# self.title=title
class Song(object):
def __init__(self,artist,track):
self.artist=artist
self.track=track
class YoutubeClient(object):
def __init__(self,project_id):
# CLIENT_SECRETS_FILE = 'client_secret.json'
# This OAuth 2.0 access scope allows for full read/write access to the
# authenticated user's account.
SCOPES = ['https://www.googleapis.com/auth/youtube']
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'
os.environ["OUATHLIB_INSECURE_TRANSPORT"]="1"
client_secrets_file="YOUR_CLIENT_SECRET.json"
# ACTIONS = ('get', 'list', 'set')
# Authorize the request and store authorization credentials.
flow = InstalledAppFlow.from_client_secrets_file(client_secrets_file, SCOPES)
# flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(credentials_location, SCOPES)
credentials = flow.run_console()
youtube_client=build(API_SERVICE_NAME, API_VERSION, credentials = credentials)
self.youtube_client = youtube_client
def get_playlists(self):
playlist_id='PLxWiyJISqBm_mgJ0JvNVXgO-1zemacgvf'#paste id herer
pl_request = self.youtube_client.playlistItems().list(
part='content Details',playlistId=playlist_id,maxResults=50,
)
pl_response = pl_request.execute()
# nextPageToken =pl_response.get('nextPageToken')
return pl_response
# to iterate over every video in the playlist and get the ID.
def get_vedios_from_playlist(self, pl_response):
vid_ids = []
for item in pl_response['items']:
vid_ids.append(item['contentDetails']['videoId'])
vid_request = self.youtube_client.videos().list(
part="snippet",id=",".join(vid_ids)
)
vid_response = vid_request.execute()
# save video title, youtube URL
for item in vid_response["items"]:
video_title = item["snippet"]["title"]
print (video_title)
youtube_url = "https://www.youtube.com/watch?v={}".format(item["id"])
print(youtube_url)
x,y=video_title.split('-')
print(y)
print(x)
spotify_uri = get_spotify_uri(y,x)
print(spotify_uri)
if(spotify_uri!='null'):
all_song_info[video_title] = {"youtube_url": youtube_url, "song_name": y, "spotify_uri": spotify_uri}
print(len(all_song_info))
print(all_song_info)
return all_song_info
# artist.append(x)
# song_name.append(y)
# print (video_title)
# youtube_url = "https://www.youtube.com/watch?v={}".format(item["id"])
# #use youtube_dl to collect the song_name and artist name
# video = youtube_dl.YoutubeDL({}).extract_info(youtube_url,download=False)
# try:
# #extract the track name, artist and the spotify uri and save them in our dict
# song_name = video["track"]
# print(song_name)
# artist = video["artist"]
# print(artist)
# except KeyError as e:
# print("Current song details are unavailable ")
# print(len(all_song_info))
# print(all_song_info)
# return all_song_info
# def get_playlists(self):
# request=self.youtube_client.playlists().list(
# # part="content Details",
# part="id, snippet",
# # playlistId="playlist_id",
# maxResults=50,
# mine=True,
# # pageToken=nextPageToken
# )
# response =request.execute()
# playlists = [Playlist(item['id'],item['snippet']['title']) for item in response['items']]
# return playlists
# def get_vedios_from_playlist(self, playlist_id):
# # vedio_id=[]
# # for item in playlists:
# # vedio_id.appen
# songs=[]
# request = self.youtube_client.playlistItems().list(
# playlistId=playlist_id,
# part="id,snippet"
# )
# response=request.execute()
# for item in response['items']:
# vedio_id=item['snippet']['resourceId']['videoId']
# artist,track = self.get_artist_and_music_from_vedio(vedio_id)
# if artist and track:
# songs.append(Song(artist,track))
# return songs
# def get_artist_and_music_from_vedio(self,vedio_id):
# youtube_url=f"https://www.youtube.com/watch?v={vedio_id}"
# video = youtube_dl.YoutubeDL({'quiet':True}).extract_info(
# youtube_url,
# download=False
# )
# try:
# track=video["track"]
# print(track)
# artist=video["artist"]
# print(artist)
# return artist,track
# except:
# print("details not available")
# return None