Created
September 9, 2024 14:28
-
-
Save yetanotherchris/7d4cf26b3cea7629b3f3116b139d8252 to your computer and use it in GitHub Desktop.
Retrieve Youtube video title, author, duration (as Markdown)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import isodate # To parse ISO 8601 durations | |
# Create an API key in Google Cloud: API/Service Details/Credentials | |
API_KEY = 'mykey' | |
VIDEO_IDS = [ | |
'KZSD3lauzDo', 'puddZhRgRNI', 'YJTjtoKGCYo', '-PjtJeMvsFI', 'KZSD3lauzDo', | |
'puddZhRgRNI', 'YJTjtoKGCYo', '-PjtJeMvsFI', 'KZSD3lauzDo', 'puddZhRgRNI', | |
'YJTjtoKGCYo', '-PjtJeMvsFI' | |
] | |
def get_video_details(video_id): | |
url = f"https://www.googleapis.com/youtube/v3/videos?id={video_id}&part=snippet,contentDetails,statistics,status&key={API_KEY}" | |
response = requests.get(url) | |
return response.json() | |
def get_video_title(data): | |
if 'items' in data and len(data['items']) > 0: | |
title = data['items'][0]['snippet']['title'] | |
return title | |
return None | |
def get_video_author(data): | |
data = get_video_details(video_id) | |
if 'items' in data and len(data['items']) > 0: | |
author = data['items'][0]['snippet']['channelTitle'] | |
return author | |
return None | |
def get_video_duration(data): | |
if 'items' in data and len(data['items']) > 0: | |
duration = data['items'][0]['contentDetails']['duration'] | |
return duration | |
return None | |
def convert_duration(iso_duration): | |
duration = isodate.parse_duration(iso_duration) | |
total_seconds = int(duration.total_seconds()) | |
hours, remainder = divmod(total_seconds, 3600) | |
minutes, seconds = divmod(remainder, 60) | |
if hours > 0: | |
return f"{hours}:{minutes:02}:{seconds:02}" | |
else: | |
return f"{minutes}:{seconds:02}" | |
output = "" | |
for video_id in VIDEO_IDS: | |
data = get_video_details(video_id) | |
iso_duration = get_video_duration(data) | |
videoTitle = get_video_title(data) | |
videoAuthor = get_video_author(data) | |
readable_duration = "" | |
if iso_duration: | |
readable_duration = " (" + convert_duration(iso_duration) + ")" | |
url = f"https://www.youtube.com/watch?v={video_id}" | |
line = f"- [{videoAuthor} - {videoTitle}{readable_duration}]({url})" | |
output += line + "\n" | |
with open("Output.md", "w") as text_file: | |
text_file.write(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment