portalniy-dev commited on
Commit
3560597
·
verified ·
1 Parent(s): 3fba2c3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -24
app.py CHANGED
@@ -10,10 +10,12 @@ def download_media(url, resolution, media_format):
10
  output_path = "downloads"
11
  os.makedirs(output_path, exist_ok=True)
12
 
 
 
 
13
  if media_format == "mp3":
14
- # Скачиваем аудио
15
  audio_stream = yt.streams.get_audio_only()
16
- out_file = audio_stream.download(output_path=output_path)
17
  base, _ = os.path.splitext(out_file)
18
  new_file = f"{base}.mp3"
19
  os.rename(out_file, new_file)
@@ -21,60 +23,60 @@ def download_media(url, resolution, media_format):
21
 
22
  else: # mp4
23
  if resolution in ["1080p", "4k"]:
24
- # Для высоких разрешений скачиваем видео и аудио отдельно
25
  video_stream = yt.streams.filter(res=resolution, file_extension="mp4", type="video").first()
26
  audio_stream = yt.streams.get_audio_only()
27
 
28
  if not video_stream or not audio_stream:
29
- raise Exception("Не удалось найти подходящие потоки")
30
 
31
- # Скачиваем компоненты
32
  video_path = video_stream.download(output_path=output_path, filename_prefix="video_")
33
  audio_path = audio_stream.download(output_path=output_path, filename_prefix="audio_")
34
 
35
- # Объединяем с помощью FFmpeg
36
- output_file = os.path.join(output_path, f"{yt.title}.mp4")
37
  subprocess.run([
38
  'ffmpeg', '-i', video_path, '-i', audio_path,
39
  '-c:v', 'copy', '-c:a', 'aac', '-strict', 'experimental',
40
  output_file
41
  ], check=True)
42
 
43
- # Удаляем временные файлы
44
  os.remove(video_path)
45
  os.remove(audio_path)
46
  return output_file
47
 
48
  else:
49
- # Для низких разрешений используем прогрессивные потоки
50
  stream = yt.streams.filter(res=resolution, file_extension="mp4", progressive=True).first()
51
  if not stream:
52
- raise Exception("Не удалось найти подходящий поток")
53
- return stream.download(output_path=output_path)
54
 
55
- except RegexMatchError:
56
- return "Ошибка: Некорректная ссылка на YouTube"
57
- except VideoUnavailable:
58
- return "Ошибка: Видео недоступно"
59
  except Exception as e:
60
- return f"Ошибка: {str(e)}"
 
61
 
62
- # Создаем интерфейс
63
  with gr.Blocks() as app:
64
  gr.Markdown("## YouTube Video Downloader")
65
  with gr.Row():
66
  url = gr.Textbox(label="YouTube URL")
67
- resolution = gr.Dropdown(["144p", "360p", "720p", "1080p", "4k"], label="Разрешение")
68
- media_format = gr.Dropdown(["mp4", "mp3"], label="Формат")
69
 
70
- download_button = gr.Button("Скачать")
71
- output = gr.File(label="Скачанный файл")
 
 
 
 
 
 
 
72
 
73
  download_button.click(
74
- fn=download_media,
75
  inputs=[url, resolution, media_format],
76
- outputs=output
77
  )
78
 
79
  if __name__ == "__main__":
80
- app.launch()
 
10
  output_path = "downloads"
11
  os.makedirs(output_path, exist_ok=True)
12
 
13
+ # Очищаем название файла от недопустимых символов
14
+ title = "".join(c for c in yt.title if c.isalnum() or c in (' ', '_')).rstrip()
15
+
16
  if media_format == "mp3":
 
17
  audio_stream = yt.streams.get_audio_only()
18
+ out_file = audio_stream.download(output_path=output_path, filename=title)
19
  base, _ = os.path.splitext(out_file)
20
  new_file = f"{base}.mp3"
21
  os.rename(out_file, new_file)
 
23
 
24
  else: # mp4
25
  if resolution in ["1080p", "4k"]:
26
+ # Для высоких разрешений
27
  video_stream = yt.streams.filter(res=resolution, file_extension="mp4", type="video").first()
28
  audio_stream = yt.streams.get_audio_only()
29
 
30
  if not video_stream or not audio_stream:
31
+ raise Exception("Required streams not found")
32
 
 
33
  video_path = video_stream.download(output_path=output_path, filename_prefix="video_")
34
  audio_path = audio_stream.download(output_path=output_path, filename_prefix="audio_")
35
 
36
+ output_file = os.path.join(output_path, f"{title}.mp4")
 
37
  subprocess.run([
38
  'ffmpeg', '-i', video_path, '-i', audio_path,
39
  '-c:v', 'copy', '-c:a', 'aac', '-strict', 'experimental',
40
  output_file
41
  ], check=True)
42
 
 
43
  os.remove(video_path)
44
  os.remove(audio_path)
45
  return output_file
46
 
47
  else:
 
48
  stream = yt.streams.filter(res=resolution, file_extension="mp4", progressive=True).first()
49
  if not stream:
50
+ raise Exception("Stream not found")
51
+ return stream.download(output_path=output_path, filename=title + ".mp4")
52
 
 
 
 
 
53
  except Exception as e:
54
+ print(f"Error: {str(e)}")
55
+ return None # Возвращаем None вместо строки с ошибкой
56
 
57
+ # Создаем интерфейс с отдельным компонентом для ошибок
58
  with gr.Blocks() as app:
59
  gr.Markdown("## YouTube Video Downloader")
60
  with gr.Row():
61
  url = gr.Textbox(label="YouTube URL")
62
+ resolution = gr.Dropdown(["144p", "360p", "720p", "1080p", "4k"], label="Resolution")
63
+ media_format = gr.Dropdown(["mp4", "mp3"], label="Format")
64
 
65
+ download_button = gr.Button("Download")
66
+ output_file = gr.File(label="Downloaded File")
67
+ error_output = gr.Textbox(label="Error Message", visible=False)
68
+
69
+ def handle_download(url, resolution, media_format):
70
+ result = download_media(url, resolution, media_format)
71
+ if result and os.path.exists(result):
72
+ return [result, gr.Textbox(visible=False)]
73
+ return [None, gr.Textbox(value="Error: Failed to download. Possible reasons:\n- Invalid URL\n- Restricted content\n- Unavailable format", visible=True)]
74
 
75
  download_button.click(
76
+ fn=handle_download,
77
  inputs=[url, resolution, media_format],
78
+ outputs=[output_file, error_output]
79
  )
80
 
81
  if __name__ == "__main__":
82
+ app.launch(share=True) # Добавлен параметр share=True