-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathgcpd.py
More file actions
388 lines (338 loc) · 18.4 KB
/
gcpd.py
File metadata and controls
388 lines (338 loc) · 18.4 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
import os
import re
import sys
import tempfile
from urllib.parse import urljoin
import aiohttp
import asyncio
from tqdm import tqdm
import subprocess
import argparse
import time
MAX_PARALLEL_DOWNLOADS = 4 # Максимальное кол-во параллельных загрузок сегментов
def merge_video_audio(video_file, audio_file, output_file):
"""Объединение видео и аудио дорожек в один MP4 файл"""
print("Объединение видео и аудио дорожек...")
try:
subprocess.run(
['ffmpeg', '-i', video_file, '-i', audio_file, '-c', 'copy', '-shortest', output_file],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
print(f"Объединение завершено: {output_file}")
return True
except subprocess.CalledProcessError as e:
print(f"Ошибка при объединении: {e}")
return False
async def download_kinescope_tracks(video_url, audio_url, result_file):
"""Скачивание и объединение отдельных видео/аудио дорожек Kinescope"""
video_m3u8 = video_url
audio_m3u8 = audio_url
with tempfile.TemporaryDirectory() as tmpdir:
video_file = os.path.join(tmpdir, 'video.mp4')
audio_file = os.path.join(tmpdir, 'audio.mp4')
print(f"Скачивание видео дорожки...")
print(f"URL: {video_m3u8}")
subprocess.run([
'yt-dlp', '--add-header', 'Referer:https://kinescope.io',
'--add-header', 'Origin:https://kinescope.io',
'-o', video_file, video_m3u8
], check=True)
print(f"\nСкачивание аудио дорожки...")
print(f"URL: {audio_m3u8}")
subprocess.run([
'yt-dlp', '--add-header', 'Referer:https://kinescope.io',
'--add-header', 'Origin:https://kinescope.io',
'-o', audio_file, audio_m3u8
], check=True)
output_file = result_file if result_file.endswith('.mp4') else result_file + '.mp4'
if merge_video_audio(video_file, audio_file, output_file):
print(f"Готово: {output_file}")
else:
print("Не удалось объединить дорожки")
async def download_file(session, url, destination, progress_bar):
async with session.get(url) as response:
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
with open(destination, 'wb') as file:
downloaded = 0
async for chunk in response.content.iter_chunked(64*1024):
file.write(chunk)
downloaded += len(chunk)
progress_bar.update(len(chunk))
async def download_segment(session, ts_url, tmpdir, idx, overall_progress, semaphore, count_segments=False):
async with semaphore:
ts_file = os.path.join(tmpdir, f'{idx:05}.ts')
retry_count = 3
for _ in range(retry_count):
try:
async with session.get(ts_url) as response:
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
with tqdm(total=total_size, desc=f"Сегмент {idx+1}", unit="B", unit_scale=True, leave=False) as pbar:
with open(ts_file, 'wb') as file:
async for chunk in response.content.iter_chunked(64*1024):
file.write(chunk)
pbar.update(len(chunk))
if not count_segments:
overall_progress.update(len(chunk))
if count_segments:
overall_progress.update(1)
return ts_file
except aiohttp.ClientError:
if _ == retry_count - 1:
raise
await asyncio.sleep(1)
async def get_total_size(session, urls):
total_size = 0
async with session.head(urls[0]) as response:
size = int(response.headers.get('content-length', 0))
if size == 0:
return None
for url in tqdm(urls, desc="Получение размеров файлов", unit="file"):
async with session.head(url) as response:
total_size += int(response.headers.get('content-length', 0))
return total_size
def _parse_resolution(resolution_str):
"""Parse RESOLUTION=WxH to (width, height); return (0, 0) if missing/invalid."""
if not resolution_str:
return (0, 0)
m = re.match(r'(\d+)x(\d+)', resolution_str.strip())
return (int(m.group(1)), int(m.group(2))) if m else (0, 0)
def resolve_master_playlist(content, base_url):
"""
Parse HLS master playlist (#EXT-X-STREAM-INF), resolve relative URIs against base_url,
and return the URL of the highest quality variant (by resolution height, then bandwidth).
"""
variants = []
lines = content.strip().split('\n')
i = 0
while i < len(lines):
line = lines[i]
if line.startswith('#EXT-X-STREAM-INF:'):
attrs = {}
rest = line[len('#EXT-X-STREAM-INF:'):].strip()
for part in rest.split(','):
part = part.strip()
if '=' in part:
k, v = part.split('=', 1)
attrs[k.strip()] = v.strip()
resolution = attrs.get('RESOLUTION', '')
bandwidth = int(attrs.get('BANDWIDTH', 0) or '0')
width, height = _parse_resolution(resolution)
i += 1
if i < len(lines) and not lines[i].startswith('#'):
uri = lines[i].strip()
if uri:
resolved = urljoin(base_url, uri)
variants.append((resolved, height, bandwidth))
i += 1
continue
i += 1
if not variants:
return None
variants.sort(key=lambda v: (v[1], v[2]), reverse=True)
return variants[0][0]
def convert_to_mp4(result_file, max_retries=3):
mp4_file = result_file + '.mp4'
retry_count = 0
while retry_count < max_retries:
print(f"Попытка конвертации в MP4 ({retry_count + 1}/{max_retries})...")
try:
process = subprocess.Popen(
['ffmpeg', '-i', result_file, '-c', 'copy', mp4_file],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=False
)
while True:
output = process.stderr.readline()
if output == b'' and process.poll() is not None:
break
if output:
try:
line = output.decode('utf-8').strip()
except UnicodeDecodeError:
line = output.decode('utf-8', errors='replace').strip()
if "Duration" in line or "time=" in line:
print(line)
if process.returncode == 0:
print(f"Конвертация завершена. Результат здесь:\n{mp4_file}")
os.remove(result_file)
print(f"Файл {result_file} удалён.")
return True
else:
error_output = process.stderr.read()
try:
error_output = error_output.decode('utf-8')
except UnicodeDecodeError:
error_output = error_output.decode('utf-8', errors='replace')
print(f"Ошибка при конвертации файла: {error_output}")
if os.path.exists(mp4_file):
os.remove(mp4_file)
print(f"Неполный файл {mp4_file} удалён.")
retry_count += 1
if retry_count < max_retries:
print(f"Повторная попытка через 5 секунд...")
time.sleep(5)
else:
print("Достигнуто максимальное количество попыток. Конвертация не удалась.")
return False
except Exception as e:
print(f"Произошла ошибка: {str(e)}")
if os.path.exists(mp4_file):
os.remove(mp4_file)
print(f"Неполный файл {mp4_file} удалён.")
retry_count += 1
if retry_count < max_retries:
print(f"Повторная попытка через 5 секунд...")
time.sleep(5)
else:
print("Достигнуто максимальное количество попыток. Конвертация не удалась.")
return False
return False
async def main(url, result_file, no_pre_download):
async with aiohttp.ClientSession() as session:
with tempfile.TemporaryDirectory() as tmpdir:
main_playlist = os.path.join(tmpdir, 'main_playlist.m3u8')
print("Загрузка основного плейлиста...")
with tqdm(total=None, desc="Основной плейлист", unit="B", unit_scale=True) as pbar:
await download_file(session, url, main_playlist, pbar)
with open(main_playlist, 'r', encoding='utf-8') as f:
main_playlist_content = f.read()
if '#EXT-X-STREAM-INF' in main_playlist_content:
best_variant_url = resolve_master_playlist(main_playlist_content, url)
if best_variant_url:
print("Обнаружен мастер-плейлист, загрузка лучшего варианта качества...")
with tqdm(total=None, desc="Плейлист варианта", unit="B", unit_scale=True) as pbar:
await download_file(session, best_variant_url, main_playlist, pbar)
with open(main_playlist, 'r', encoding='utf-8') as f:
main_playlist_content = f.read()
ts_or_bin_pattern = re.compile(r'^https?://.*\.(ts|bin)', re.MULTILINE)
second_playlist = os.path.join(tmpdir, 'second_playlist.m3u8')
if ts_or_bin_pattern.search(main_playlist_content):
with open(second_playlist, 'w', encoding='utf-8') as f:
f.write(main_playlist_content)
else:
tail = main_playlist_content.strip().split('\n')[-1]
if not re.match(r'^https?://', tail):
print("В содержимом заданной ссылки нет прямых ссылок на файлы *.bin (*.ts) (первый вариант),")
print("также последняя строка в ней не содержит ссылки на другой плей-лист (второй вариант).")
print("Либо указана неправильная ссылка, либо GetCourse изменил алгоритмы.")
print("Если уверены, что дело в изменившихся алгоритмах GetCourse, опишите проблему здесь:")
print("https://github.com/mikhailnov/getcourse-video-downloader/issues (на русском).")
print("Если уверены, что это ошибка скрипта, то опишите проблему здесь:")
print("https://github.com/snhplayer/GetCoursePythonDownloader/issues")
return
print("Загрузка вторичного плейлиста...")
with tqdm(total=None, desc="Вторичный плейлист", unit="B", unit_scale=True) as pbar:
await download_file(session, tail, second_playlist, pbar)
with open(second_playlist, 'r', encoding='utf-8') as f:
lines = f.readlines()
ts_urls = [line.strip() for line in lines if re.match(r'^https?://', line.strip())]
print(f"Число сегментов для загрузки: {len(ts_urls)}")
total_size = None
if not no_pre_download:
total_size = await get_total_size(session, ts_urls)
semaphore = asyncio.Semaphore(MAX_PARALLEL_DOWNLOADS)
if no_pre_download:
overall_pbar = tqdm(total=len(ts_urls), desc="Общий прогресс", unit="сегмент")
else:
overall_pbar = tqdm(total=total_size, desc="Общий прогресс", unit="B", unit_scale=True)
tasks = [download_segment(session, ts_url, tmpdir, idx, overall_pbar, semaphore, count_segments=no_pre_download)
for idx, ts_url in enumerate(ts_urls)]
ts_files = []
for task in asyncio.as_completed(tasks):
ts_file = await task
ts_files.append(ts_file)
overall_pbar.close()
print("Объединение сегментов...")
with open(result_file, 'wb') as result:
for ts_file in tqdm(sorted(ts_files), desc="Объединение", unit="file"):
with open(ts_file, 'rb') as ts:
result.write(ts.read())
print(f"Скачивание завершено. Результат здесь:\n{result_file}")
if convert_to_mp4(result_file):
print("Конвертация успешно завершена.")
else:
print("Не удалось выполнить конвертацию после нескольких попыток.")
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Download and process video segments.')
parser.add_argument('--pd', action='store_false', dest='no_pre_download',
help='Включить предварительную загрузку размеров (по умолчанию отключено)')
parser.add_argument('-f', type=str, dest='file',
help='Указать файл где находятся ссылки плей-листов и имена выходных файлов', default=False)
args = parser.parse_args()
if args.file != False:
url = ""
result_file = ""
if not os.path.exists(args.file):
print("Файл для скачивания не существует")
exit(-1)
lines = [line.strip() for line in open(args.file, encoding="utf-8") if line.strip()]
i = 0
def is_kinescope_video_url(s):
return s.startswith("http") and "kinescope.io" in s and "type=video" in s
def is_kinescope_audio_url(s):
return s.startswith("http") and "kinescope.io" in s and "type=audio" in s
def is_getcourse_url(s):
if not (s and s.startswith("http")):
return False
if is_kinescope_video_url(s) or is_kinescope_audio_url(s):
return False
return (
"playlist.servicecdn.ru" in s
or "/api/playlist/master/" in s
or ".m3u8" in s
)
while i < len(lines):
line = lines[i]
# TITLE: затем блок GetCourse URL
if line.startswith("TITLE:"):
current_page_title = line[6:].strip() or "video"
i += 1
urls = []
while i < len(lines) and is_getcourse_url(lines[i]):
urls.append(lines[i])
i += 1
for j, u in enumerate(urls):
result_file = f"{current_page_title} - {j + 1}"
print("Скачивание плей-листа: ", u)
print("В файл: ", result_file)
asyncio.run(main(u, result_file, args.no_pre_download))
continue
# Kinescope: video URL, audio URL, name
if is_kinescope_video_url(line) and i + 2 < len(lines):
next_url = lines[i + 1]
if is_kinescope_audio_url(next_url):
video_url = line
audio_url = next_url
result_file = lines[i + 2] if i + 2 < len(lines) else "output"
print(f"Обнаружены Kinescope дорожки")
print(f"Видео: {video_url}")
print(f"Аудио: {audio_url}")
print(f"Выходной файл: {result_file}")
asyncio.run(download_kinescope_tracks(video_url, audio_url, result_file))
i += 3
continue
# Обычный m3u8 плейлист (legacy: url, name)
if is_getcourse_url(line):
url = line
result_file = lines[i + 1] if i + 1 < len(lines) else "output"
print("Скачивание плей-листа: ", url)
print("В файл: ", result_file)
asyncio.run(main(url, result_file, args.no_pre_download))
i += 2
continue
i += 1
else:
while True:
url = input("Введите ссылку (плейлист или видео Kinescope): ")
if 'kinescope.io' in url and 'type=video' in url:
audio_url = input("Введите ссылку на аудио дорожку: ")
result_file = input("Введите имя выходного файла: ")
asyncio.run(download_kinescope_tracks(url, audio_url, result_file))
else:
result_file = input("Введите имя выходного файла: ")
asyncio.run(main(url, result_file, args.no_pre_download))