Skip to content

Instantly share code, notes, and snippets.

@hemulin
Created August 3, 2018 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hemulin/a208e6ffc63a7f8965b32aa6a3d68db1 to your computer and use it in GitHub Desktop.
Save hemulin/a208e6ffc63a7f8965b32aa6a3d68db1 to your computer and use it in GitHub Desktop.
Youtube data api v3 playlist keyword generator POC. WIP
#!/usr/bin/python
###########################################
# Don't forget to pip install --upgrade google-api-python-clien
#
### USAGE: python search.py --q beatles ###
###########################################
import json
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps
# tab of
# https://cloud.google.com/console
# Please ensure that you have enabled the YouTube Data API for your project.
DEVELOPER_KEY = "<YOUR-DEVELOPER-KEY-HERE>"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
def main(args):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY)
playlists = playlist_search(youtube, args)
videosMap = {}
for p in playlists:
items_map = playlist_items_list_by_playlist_id(youtube,
part='snippet,contentDetails',
maxResults=25,
playlistId=p['id'])
for element in items_map:
if element['id'] in videosMap:
videosMap[element['id']]['occurence'] += 1
else:
videosMap[element['id']] = {
'title': element['title'],
'occurence': 1
}
videosMap = sorted(videosMap.items(),
key=lambda k_v: k_v[1]['occurence'], reverse=False)
print(json.dumps(videosMap, indent=4))
def playlist_search(client, options):
# Call the search.list method to retrieve results matching the specified
# query term.
search_response = client.search().list(
q=options.q,
part="id,snippet",
type='playlist',
order='viewCount',
# order='relevance',
maxResults=options.max_results
).execute()
playlists = []
# Add each result to the appropriate list, and then display the lists of
# matching videos, channels, and playlists.
for search_result in search_response.get("items", []):
playlists.append(
{
'id': search_result["id"]["playlistId"],
'title': search_result["snippet"]["title"]
})
# for p in playlists:
# print(
# 'https://www.youtube.com/playlist?list={} {}'.format(p['id'], p['title']))
return playlists
def playlist_items_list_by_playlist_id(client, **kwargs):
# See full sample for function
kwargs = remove_empty_kwargs(**kwargs)
response = client.playlistItems().list(
**kwargs
).execute()
videoIdsTitles = []
items = response['items']
for i in items:
videoIdsTitles.append(
{
'id': 'https://www.youtube.com/watch?v={}'.format(i['contentDetails']['videoId']),
'title': i['snippet']['title']
}
)
# print(json.dumps(videoIdsTitles, indent=4))
return videoIdsTitles
def remove_empty_kwargs(**kwargs):
good_kwargs = {}
if kwargs is not None:
for key, value in kwargs.items():
if value:
good_kwargs[key] = value
return good_kwargs
if __name__ == "__main__":
argparser.add_argument("--q", help="Search term",
default="CC5ca6Hsb2Q")
argparser.add_argument("--max-results", help="Max results", default=25)
args = argparser.parse_args()
try:
main(args)
except HttpError as e:
print("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment