Created
December 3, 2020 03:45
-
-
Save michaelasper/b8491c7376a035c4ac8cb1228d97320b to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
import json | |
import urllib.request | |
from datetime import datetime | |
import os | |
import isodate | |
def checkYear(time, year): | |
try: | |
date_to_check = datetime.strptime(time, "%Y-%m-%dT%H:%M:%S.%fZ") | |
except ValueError: | |
date_to_check = datetime.strptime(time, "%Y-%m-%dT%H:%M:%SZ") | |
return date_to_check.year == year | |
def getVideoLength(url): | |
temp = url.split('?v=') | |
video_id = temp[-1] | |
api_key = os.environ["API_KEY"] # free from https://console.developers.google.com/ | |
searchUrl = ( | |
"https://www.googleapis.com/youtube/v3/videos?id=" | |
+ video_id | |
+ "&key=" | |
+ api_key | |
+ "&part=contentDetails" | |
) | |
response = urllib.request.urlopen(searchUrl).read() | |
data = json.loads(response) | |
all_data = data["items"] | |
try: | |
contentDetails = all_data[0]["contentDetails"] | |
duration = contentDetails["duration"] | |
duration = isodate.parse_duration(duration) | |
video_dur = duration.total_seconds() | |
return video_dur | |
except: | |
return 0 | |
def run(year, file): | |
results = dict() | |
with open(file, encoding='utf-8') as f: | |
data = json.load(f) | |
for video in data: | |
try: | |
url = video["titleUrl"] | |
except KeyError: | |
pass # lazy handling, but usually video was deleted | |
if checkYear(video["time"], year): | |
if "subtitles" not in video: | |
pass | |
else: | |
youtuber = video["subtitles"][0]["name"] | |
if youtuber in results: | |
results[youtuber] += getVideoLength(url) | |
else: | |
results[youtuber] = getVideoLength(url) | |
top = sorted(results, key=results.get, reverse=True) | |
for v in top: | |
print(v, results[v]) | |
if __name__ == "__main__": | |
run(2020, "watch-history.json") # from google takeout |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment