-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyoutube_account.py
More file actions
398 lines (344 loc) · 14.8 KB
/
Copy pathyoutube_account.py
File metadata and controls
398 lines (344 loc) · 14.8 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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import html
import os
import pickle
import google_auth_oauthlib
import googleapiclient.errors
import google.auth.exceptions
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# YouTube API configuration
scopes = ["https://www.googleapis.com/auth/youtube"]
api_service_name = "youtube"
api_version = "v3"
class YoutubeApi:
def __init__(self):
self.credentials = None
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
self.page_videos = []
self.all_videos_cache = [] # Cache for when ALL option is selected
self.youtube = None
self.channel_thumbnail = ''
self.channel_name = ''
self.uploads_id = ''
self.next_page_token = None
self.page_tokens = {} # Store page tokens for efficient pagination
self.results_per_page = 10
self.per_page_option_index = 0
self.current_page = 1
self.videos_trimmed = 0
self.videos_skipped = 0
self.errorStr = ''
self.total_video_count = 0
self.allowed_languages = []
self.code_to_name = {
"af": "Afrikaans",
"am": "Amharic",
"ar": "Arabic",
"az": "Azerbaijani",
"be": "Belarusian",
"bg": "Bulgarian",
"bn": "Bangla",
"bs": "Bosnian",
"ca": "Catalan",
"cs": "Czech",
"da": "Danish",
"de": "German",
"en": "English",
"es": "Spanish",
"et": "Estonian",
"eu": "Basque",
"fa": "Persian",
"fi": "Finnish",
"fr": "French",
"gl": "Galician",
"gu": "Gujarati",
"hi": "Hindi",
"hr": "Croatian",
"hu": "Hungarian",
"hy": "Armenian",
"id": "Indonesian",
"is": "Icelandic",
"it": "Italian",
"iw": "Hebrew",
"ja": "Japanese",
"ka": "Georgian",
"kk": "Kazakh",
"km": "Khmer",
"kn": "Kannada",
"ko": "Korean",
"ky": "Kyrgyz",
"lo": "Lao",
"lt": "Lithuanian",
"lv": "Latvian",
"mk": "Macedonian",
"ml": "Malayalam",
"mn": "Mongolian",
"mr": "Marathi",
"ms": "Malay",
"my": "Burmese",
"no": "Norwegian",
"ne": "Nepali",
"nl": "Dutch",
"or": "Odia",
"pa": "Punjabi",
"pl": "Polish",
"pt": "Portuguese",
"ro": "Romanian",
"ru": "Russian",
"si": "Sinhala",
"sk": "Slovak",
"sl": "Slovenian",
"sq": "Albanian",
"sr": "Serbian",
"sv": "Swedish",
"sw": "Swahili",
"ta": "Tamil",
"te": "Telugu",
"th": "Thai",
"tr": "Turkish",
"uk": "Ukrainian",
"ur": "Urdu",
"vi": "Vietnamese",
"zh-CN": "Chinese (China)",
"zh-TW": "Chinese (Taiwan)",
}
self.name_to_code = {val: key for (key, val) in self.code_to_name.items()}
self.check_credentials()
self.youtube = googleapiclient.discovery.build(
api_service_name, api_version, credentials=self.credentials)
self.set_uploads_id()
if self.errorStr == '':
self.get_total_video_count()
# We don't need to load the page here, home() will do it.
# self.set_video_page(1)
@property
def num_pages(self):
if self.results_per_page == -1: # "ALL" option
return 1
return max(1, (self.total_video_count + self.results_per_page - 1) // self.results_per_page)
def check_credentials(self):
"""Check and refresh OAuth credentials"""
if os.path.exists('token.pickle'):
with open("token.pickle", "rb") as token:
self.credentials = pickle.load(token)
if not self.credentials or not self.credentials.valid:
if self.credentials and self.credentials.expired and self.credentials.refresh_token:
try:
self.credentials.refresh(Request())
except google.auth.exceptions.RefreshError:
self.credentials = None
if not self.credentials:
# Get credentials and create an API client
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
client_secrets_file="config/account_client_secrets_main.json", scopes=scopes)
flow.run_local_server(port=8080, prompt='consent', authorization_prompt_message='')
self.credentials = flow.credentials
with open("token.pickle", "wb") as token_file:
pickle.dump(self.credentials, token_file)
# --- NUEVO MÉTODO AÑADIDO ---
def clear_video_cache(self):
"""Clears all in-memory video data to force a re-fetch on the next page load."""
self.page_videos = []
self.all_videos_cache = []
self.page_tokens = {} # Important to reset this as well
print("In-memory video cache cleared.")
# --- FIN DEL NUEVO MÉTODO ---
def set_channel_data(self, channel_response):
"""Extract channel information from API response"""
if channel_response.get("items"):
self.channel_thumbnail = channel_response["items"][0]['snippet']['thumbnails']['default']['url']
self.channel_name = channel_response["items"][0]['snippet']['title']
def get_total_video_count(self):
"""Get total number of videos in channel without fetching all video details"""
try:
playlist_response = self.youtube.playlists().list(
id=self.uploads_id,
part='contentDetails'
).execute()
if playlist_response.get("items"):
self.total_video_count = playlist_response["items"][0]["contentDetails"]["itemCount"]
else:
response = self.youtube.playlistItems().list(
playlistId=self.uploads_id,
part='id',
maxResults=1
).execute()
self.total_video_count = response.get('pageInfo', {}).get('totalResults', 0)
except googleapiclient.errors.HttpError as e:
self.errorStr = e.error_details[0]['reason']
self.total_video_count = 0
def set_video_page(self, page):
"""Load videos for a specific page on demand"""
# Only fetch if the cache for the current page is empty
if not self.page_videos:
self.current_page = page
if self.results_per_page == -1: # "ALL" option
self.load_all_videos()
else:
self.load_page_videos(page)
def load_page_videos(self, page):
"""Load videos for a specific page efficiently"""
try:
page_token = self.get_page_token_for_page(page)
videos_response = self.youtube.playlistItems().list(
playlistId=self.uploads_id,
part='snippet',
maxResults=self.results_per_page,
pageToken=page_token
).execute()
if videos_response.get("nextPageToken"):
self.page_tokens[page + 1] = videos_response["nextPageToken"]
for item in videos_response["items"]:
video_id = item["snippet"]["resourceId"]["videoId"]
localizations = self.get_video_localizations(video_id)
new_video = Video(
item["snippet"]["title"],
video_id,
item["snippet"]["description"],
item["snippet"]["thumbnails"]["default"]['url'],
localizations
)
self.page_videos.append(new_video)
except googleapiclient.errors.HttpError as e:
self.errorStr = e.error_details[0]['reason']
def get_page_token_for_page(self, page):
"""Get the appropriate page token for a given page number"""
if page == 1:
return None
if page in self.page_tokens:
return self.page_tokens[page]
current_page = 1
page_token = None
while current_page < page:
response = self.youtube.playlistItems().list(
playlistId=self.uploads_id,
part='id',
maxResults=self.results_per_page,
pageToken=page_token
).execute()
page_token = response.get("nextPageToken")
current_page += 1
if page_token:
self.page_tokens[current_page] = page_token
else:
break
return page_token
def load_all_videos(self):
"""Load all videos when 'ALL' option is selected"""
self.page_videos = []
self.all_videos_cache = []
page_token = None
try:
while True:
videos_response = self.youtube.playlistItems().list(
playlistId=self.uploads_id,
part='snippet',
maxResults=50,
pageToken=page_token
).execute()
for item in videos_response["items"]:
video_id = item["snippet"]["resourceId"]["videoId"]
localizations = self.get_video_localizations(video_id)
new_video = Video(
item["snippet"]["title"],
video_id,
item["snippet"]["description"],
item["snippet"]["thumbnails"]["default"]['url'],
localizations
)
self.page_videos.append(new_video)
self.all_videos_cache.append(new_video)
page_token = videos_response.get("nextPageToken")
if not page_token:
break
except googleapiclient.errors.HttpError as e:
self.errorStr = e.error_details[0]['reason']
def set_uploads_id(self):
"""Get the uploads playlist ID for the authenticated channel"""
try:
channel_response = self.youtube.channels().list(
part="snippet",
mine=True
).execute()
self.set_channel_data(channel_response)
channel_id = channel_response["items"][0]["id"]
uploads_response = self.youtube.channels().list(
id=channel_id,
part='contentDetails'
).execute()
self.uploads_id = uploads_response["items"][0]["contentDetails"]["relatedPlaylists"]["uploads"]
except googleapiclient.errors.HttpError as e:
self.errorStr = e.error_details[0]['reason']
def set_video_localization(self, video_id, language_code, language, title, description, trim_checked,
default_title):
"""Add or update localization for a video"""
if language_code == '':
return
video = {}
language = language.strip()
print(f"Translating '{default_title}' to '{language}'")
if trim_checked:
if len(title) > 99:
title = title[:98]
self.videos_trimmed += 1
print(f"Title for video '{default_title}' was too long, trimmed")
if len(description) > 4999:
description = description[:4998]
self.videos_trimmed += 1
print(f"Description for video '{default_title}' was too long, trimmed")
else:
if len(title) > 99 or len(description) > 4999:
self.videos_skipped += 1
print(f"Video '{default_title}' skipped for language '{language}' due to length.")
return
try:
results = self.youtube.videos().list(
part='snippet,localizations',
id=video_id
).execute()
video = results['items'][0]
if 'defaultLanguage' not in video['snippet']:
video['snippet']['defaultLanguage'] = 'en'
if 'localizations' not in video:
video['localizations'] = {}
video['localizations'][language_code] = {
'title': html.unescape(title.replace('\\n', '\n')),
'description': html.unescape(description.replace('\\n', '\n'))
}
self.youtube.videos().update(
part='snippet,localizations',
body=video
).execute()
except googleapiclient.errors.HttpError as e:
self.errorStr = e.error_details[0]['reason']
print(f"Error updating video: {e.error_details}")
def get_video_localizations(self, video_id):
"""Get existing localizations for a video"""
try:
results = self.youtube.videos().list(
part='localizations',
id=video_id
).execute()
if not results['items']:
return []
localizations = list(results['items'][0].get('localizations', {}).keys())
for i in range(len(localizations)):
if 'en-' in localizations[i]:
localizations[i] = "en"
return list(set(localizations))
except googleapiclient.errors.HttpError as e:
print(f"Error getting localizations for video {video_id}: {e}")
return []
class Video:
"""Represents a YouTube video with translation data"""
def __init__(self, title, vid_id, desc, thumb_url, curr_langs):
self.video_title = title
self.id = vid_id
self.description = desc
self.thumbnail_url = thumb_url
self.current_languages = curr_langs if curr_langs else []
self.language_names = []
@property
def num_languages(self):
return len(self.current_languages)