-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathupload_video.py
155 lines (124 loc) · 4.75 KB
/
upload_video.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
"""Based on / Used https://www.youtube.com/watch?v=PnSTIg83eyk"""
from __future__ import unicode_literals
import youtube_dl
import os
import shutil
import time
import pandas as pd
import http.client
import httplib2
import random
import time
from video_details import Video
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload
from google_auth_oauthlib.flow import InstalledAppFlow
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
def download_video(twitchClipLinks):
os.chdir('Video')
ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([twitchClipLinks])
os.chdir('..')
def manage_file():
files = os.listdir(os.curdir)
for file in files:
if '.mp4' in file:
os.rename(file, file.translate(str.maketrans('', '',
'0123456789-')))
files = os.listdir(os.curdir)
for file in files:
if '.mp' in file:
newfile = file.replace('.mp', '.mp4')
os.rename(file, newfile)
shutil.move(newfile, 'Video')
class YoutubeUpload:
def __init__(self):
self.MAX_RETRIES = 10
self.RETRIABLE_EXCEPTIONS = (
httplib2.HttpLib2Error,
IOError,
http.client.NotConnected,
http.client.IncompleteRead,
http.client.ImproperConnectionState,
http.client.CannotSendRequest,
http.client.CannotSendHeader,
http.client.ResponseNotReady,
http.client.BadStatusLine,
)
self.RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
self.CLIENT_SECRETS_FILE = 'client_secrets.json'
self.SCOPES = ['https://www.googleapis.com/auth/youtube.upload']
self.API_SERVICE_NAME = 'youtube'
self.API_VERSION = 'v3'
def get_authenticated_service(self):
credential_path = os.path.join('credentials.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = \
client.flow_from_clientsecrets(self.CLIENT_SECRETS_FILE,
self.SCOPES)
credentials = tools.run_flow(flow, store)
return build(self.API_SERVICE_NAME, self.API_VERSION,
credentials=credentials)
def initialize_upload(self, youtube, options):
tags = (options.keywords.split(','
) if options.keywords else None)
body = dict(snippet=dict(title=options.getFileName('video'
).split('.', 1)[0],
description=options.description, tags=tags,
categoryId=options.category),
status=dict(privacyStatus=options.privacyStatus))
videoPath = 'Video/{}'.format(options.getFileName('video'))
insert_request = \
youtube.videos().insert(part=','.join(body.keys()),
body=body,
media_body=MediaFileUpload(videoPath,
chunksize=-1, resumable=True))
self.resumable_upload(insert_request, options)
def resumable_upload(self, request, options):
response = None
error = None
while response is None:
try:
print('Uploading file...')
_, response = request.next_chunk()
if response is None:
exit('The upload failed with an unexpected response: {}'.format(response))
elif 'id' in response:
print ('The video with the id {} was successfully uploaded!'.format(response['id']))
except HttpError as e:
if e.resp.status in self.RETRIABLE_STATUS_CODES:
error = 'A retriable HTTP error {} occurred:\n{}'.format((e.resp.status, e.content))
else:
raise
if error is not None:
print(error)
retry = 0
retry += 1
if retry > self.MAX_RETRIES:
exit('No longer attempting to retry.')
max_sleep = 2 ** retry
sleep_seconds = random.random() * max_sleep
print('Sleeping {} seconds and then retrying...'.format(sleep_seconds))
time.sleep(sleep_seconds)
def get_data():
df = pd.read_excel('twitch_data.xlsx')
return df['url'][0]
def main():
video_url = get_data()
download_video(video_url)
manage_file()
youtubeUpload = YoutubeUpload()
args = Video()
authentication = youtubeUpload.get_authenticated_service()
try:
youtubeUpload.initialize_upload(authentication, args)
except HttpError as e:
print('An HTTP error {} occurred:\n{}'.format((e.resp.status, e.content)))
if __name__ == '__main__':
main()