forked from x4nth055/pythoncode-tutorials
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
Latest commit
154 lines (136 loc) · 5 KB
/
Copy pathutils.py
File metadata and controls
154 lines (136 loc) · 5 KB
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
fromgoogleapiclient.discoveryimportbuild
fromgoogle_auth_oauthlib.flowimportInstalledAppFlow
fromgoogle.auth.transport.requestsimportRequest
importurllib.parseasp
importre
importos
importpickle
SCOPES= ["https://www.googleapis.com/auth/youtube.force-ssl"]
defyoutube_authenticate():
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] ="1"
api_service_name="youtube"
api_version="v3"
client_secrets_file="credentials.json"
creds=None
# the file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first time
ifos.path.exists("token.pickle"):
withopen("token.pickle", "rb") astoken:
creds=pickle.load(token)
# if there are no (valid) credentials availablle, let the user log in.
ifnotcredsornotcreds.valid:
ifcredsandcreds.expiredandcreds.refresh_token:
creds.refresh(Request())
else:
flow=InstalledAppFlow.from_client_secrets_file(client_secrets_file, SCOPES)
creds=flow.run_local_server(port=0)
# save the credentials for the next run
withopen("token.pickle", "wb") astoken:
pickle.dump(creds, token)
returnbuild(api_service_name, api_version, credentials=creds)
defget_channel_details(youtube, **kwargs):
returnyoutube.channels().list(
part="statistics,snippet,contentDetails",
**kwargs
).execute()
defsearch(youtube, **kwargs):
returnyoutube.search().list(
part="snippet",
**kwargs
).execute()
defget_video_details(youtube, **kwargs):
returnyoutube.videos().list(
part="snippet,contentDetails,statistics",
**kwargs
).execute()
defprint_video_infos(video_response):
items=video_response.get("items")[0]
# get the snippet, statistics & content details from the video response
snippet=items["snippet"]
statistics=items["statistics"]
content_details=items["contentDetails"]
# get infos from the snippet
channel_title=snippet["channelTitle"]
title=snippet["title"]
description=snippet["description"]
publish_time=snippet["publishedAt"]
# get stats infos
comment_count=statistics["commentCount"]
like_count=statistics["likeCount"]
dislike_count=statistics["dislikeCount"]
view_count=statistics["viewCount"]
# get duration from content details
duration=content_details["duration"]
# duration in the form of something like 'PT5H50M15S'
# parsing it to be something like '5:50:15'
parsed_duration=re.search(f"PT(\d+H)?(\d+M)?(\d+S)", duration).groups()
duration_str=""
fordinparsed_duration:
ifd:
duration_str+=f"{d[:-1]}:"
duration_str=duration_str.strip(":")
print(f"""
Title: {title}
Description: {description}
Channel Title: {channel_title}
Publish time: {publish_time}
Duration: {duration_str}
Number of comments: {comment_count}
Number of likes: {like_count}
Number of dislikes: {dislike_count}
Number of views: {view_count}
""")
defparse_channel_url(url):
"""
This function takes channel `url` to check whether it includes a
channel ID, user ID or channel name
"""
path=p.urlparse(url).path
id=path.split("/")[-1]
if"/c/"inpath:
return"c", id
elif"/channel/"inpath:
return"channel", id
elif"/user/"inpath:
return"user", id
defget_channel_id_by_url(youtube, url):
"""
Returns channel ID of a given `id` and `method`
- `method` (str): can be 'c', 'channel', 'user'
- `id` (str): if method is 'c', then `id` is display name
if method is 'channel', then it's channel id
if method is 'user', then it's username
"""
# parse the channel URL
method, id=parse_channel_url(url)
ifmethod=="channel":
# if it's a channel ID, then just return it
returnid
elifmethod=="user":
# if it's a user ID, make a request to get the channel ID
response=get_channel_details(youtube, forUsername=id)
items=response.get("items")
ifitems:
channel_id=items[0].get("id")
returnchannel_id
elifmethod=="c":
# if it's a channel name, search for the channel using the name
# may be inaccurate
response=search(youtube, q=id, maxResults=1)
items=response.get("items")
ifitems:
channel_id=items[0]["snippet"]["channelId"]
returnchannel_id
raiseException(f"Cannot find ID:{id} with {method} method")
defget_video_id_by_url(url):
"""
Return the Video ID from the video `url`
"""
# split URL parts
parsed_url=p.urlparse(url)
# get the video ID by parsing the query of the URL
video_id=p.parse_qs(parsed_url.query).get("v")
ifvideo_id:
returnvideo_id[0]
else:
raiseException(f"Wasn't able to parse video URL: {url}")