jpjp9292 commited on
Commit
fd6962d
Β·
verified Β·
1 Parent(s): 620a065

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -122
app.py CHANGED
@@ -2,6 +2,8 @@ import streamlit as st
2
  import yt_dlp
3
  import os
4
  from pathlib import Path
 
 
5
 
6
  # νŽ˜μ΄μ§€ μ„€μ •
7
  st.set_page_config(page_title="Simple YouTube Downloader", page_icon="πŸ“Ί")
@@ -11,15 +13,35 @@ st.title("Simple YouTube Downloader πŸ“Ί")
11
  output_dir = Path("downloads")
12
  output_dir.mkdir(exist_ok=True)
13
 
14
- def reset_form():
15
- st.session_state.url = ""
16
-
 
17
  def download_video(url, progress_bar, status_text):
18
  try:
 
 
 
 
 
 
 
19
  ydl_opts = {
20
- 'format': 'best', # 졜고 ν’ˆμ§ˆμ˜ 톡합 포맷
21
  'outtmpl': str(output_dir / '%(title)s.%(ext)s'),
22
- 'quiet': True
 
 
 
 
 
 
 
 
 
 
 
 
23
  }
24
 
25
  def progress_hook(d):
@@ -36,17 +58,36 @@ def download_video(url, progress_bar, status_text):
36
 
37
  ydl_opts['progress_hooks'] = [progress_hook]
38
 
39
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
40
- info = ydl.extract_info(url, download=True)
41
- filename = ydl.prepare_filename(info)
42
- return filename
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  except Exception as e:
45
  st.error(f"였λ₯˜ λ°œμƒ: {str(e)}")
46
  return None
47
 
48
  # 메인 UI
49
- video_url = st.text_input("YouTube URL μž…λ ₯:", key="url",
 
 
 
 
50
  placeholder="https://www.youtube.com/watch?v=...")
51
 
52
  col1, col2 = st.columns(2)
@@ -72,115 +113,5 @@ with col1:
72
 
73
  with col2:
74
  if st.button("μ΄ˆκΈ°ν™”"):
75
- reset_form()
76
-
77
-
78
- # import streamlit as st
79
- # import yt_dlp
80
- # import os
81
- # from pathlib import Path
82
-
83
- # # Set page config
84
- # st.set_page_config(page_title="YouTube Video Downloader", page_icon="πŸ“Ί")
85
-
86
- # # Set the title of the app
87
- # st.title("YouTube Video Downloader πŸ“Ί")
88
-
89
- # # Create output directory if it doesn't exist
90
- # output_dir = Path("downloads")
91
- # output_dir.mkdir(exist_ok=True)
92
-
93
- # # Input field for YouTube video URL
94
- # video_url = st.text_input("Enter YouTube Video URL:", placeholder="https://www.youtube.com/watch?v=...")
95
-
96
- # # Function to download video
97
- # def download_video(url):
98
- # try:
99
-
100
- # ydl_opts = {
101
- # 'format': 'bestvideo+bestaudio/best',
102
- # 'outtmpl': str(output_dir / '%(title)s.%(ext)s'),
103
- # 'merge_output_format': 'webm',
104
- # 'quiet': False, # Change to False to see more detailed error output
105
- # 'no_warnings': False,
106
- # 'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
107
- # 'referer': 'https://www.youtube.com/',
108
- # 'cookiefile': 'youtube.com_cookies.txt', # Ensure this file path is correct
109
- # 'socket_timeout': 30,
110
- # 'http_chunk_size': 10485760, # 10MB
111
- # 'retries': 10, # Increase retry attempts
112
- # 'headers': {
113
- # 'Accept-Language': 'en-US,en;q=0.9',
114
- # 'Accept-Encoding': 'gzip, deflate, br',
115
- # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
116
- # 'Upgrade-Insecure-Requests': '1',
117
- # }
118
- # }
119
-
120
- # # Progress placeholder
121
- # progress_bar = st.progress(0)
122
- # status_text = st.empty()
123
-
124
- # def progress_hook(d):
125
- # if d['status'] == 'downloading':
126
- # try:
127
- # progress = d['downloaded_bytes'] / d['total_bytes']
128
- # progress_bar.progress(progress)
129
- # status_text.text(f"Downloading: {progress:.1%}")
130
- # except:
131
- # status_text.text("Downloading... (size unknown)")
132
- # elif d['status'] == 'finished':
133
- # progress_bar.progress(1.0)
134
- # status_text.text("Processing...")
135
-
136
- # ydl_opts['progress_hooks'] = [progress_hook]
137
-
138
- # with yt_dlp.YoutubeDL(ydl_opts) as ydl:
139
- # info = ydl.extract_info(url, download=True)
140
- # filename = ydl.prepare_filename(info)
141
- # return filename
142
-
143
- # except Exception as e:
144
- # st.error(f"An error occurred: {str(e)}")
145
- # return None
146
-
147
- # # Download button
148
- # if st.button("Download"):
149
- # if video_url:
150
- # try:
151
- # with st.spinner("Preparing download..."):
152
- # downloaded_file_path = download_video(video_url)
153
-
154
- # if downloaded_file_path and os.path.exists(downloaded_file_path):
155
- # with open(downloaded_file_path, 'rb') as file:
156
- # st.download_button(
157
- # label="Click here to download",
158
- # data=file,
159
- # file_name=os.path.basename(downloaded_file_path),
160
- # mime="application/octet-stream"
161
- # )
162
- # st.success("βœ… Download ready!")
163
- # else:
164
- # st.error("❌ Download failed. Please try again.")
165
- # except Exception as e:
166
- # st.error(f"❌ An error occurred: {str(e)}")
167
- # else:
168
- # st.warning("⚠️ Please enter a valid YouTube URL.")
169
-
170
- # # Help section
171
- # with st.expander("ℹ️ Help & Troubleshooting"):
172
- # st.markdown("""
173
- # **If you're experiencing download issues:**
174
-
175
- # 1. Cookie Authentication Method:
176
- # - Install a browser extension like "Get cookies.txt"
177
- # - Visit YouTube and ensure you're logged in
178
- # - Export cookies to 'youtube.com_cookies.txt'
179
- # - Place the file in the same directory as this app
180
-
181
- # 2. Alternative Solutions:
182
- # - Try different videos
183
- # - Check if the video is public/not age-restricted
184
- # - Try again later if YouTube is blocking requests
185
- # """)
186
-
 
2
  import yt_dlp
3
  import os
4
  from pathlib import Path
5
+ import random
6
+ import time
7
 
8
  # νŽ˜μ΄μ§€ μ„€μ •
9
  st.set_page_config(page_title="Simple YouTube Downloader", page_icon="πŸ“Ί")
 
13
  output_dir = Path("downloads")
14
  output_dir.mkdir(exist_ok=True)
15
 
16
+ def reset_input():
17
+ # session_state λŒ€μ‹  빈 λ¬Έμžμ—΄ λ°˜ν™˜
18
+ return ""
19
+
20
  def download_video(url, progress_bar, status_text):
21
  try:
22
+ # User Agent λͺ©λ‘
23
+ user_agents = [
24
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
25
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2.1 Safari/605.1.15',
26
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101 Firefox/122.0'
27
+ ]
28
+
29
  ydl_opts = {
30
+ 'format': 'best',
31
  'outtmpl': str(output_dir / '%(title)s.%(ext)s'),
32
+ 'quiet': True,
33
+ 'no_warnings': True,
34
+ # 봇 감지 우회 μ„€μ •
35
+ 'user_agent': random.choice(user_agents),
36
+ 'referer': 'https://www.youtube.com/',
37
+ 'http_chunk_size': random.randint(10000000, 15000000),
38
+ 'retries': 3,
39
+ 'sleep_interval': 1,
40
+ 'max_sleep_interval': 5,
41
+ 'headers': {
42
+ 'Accept-Language': 'en-US,en;q=0.9',
43
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
44
+ }
45
  }
46
 
47
  def progress_hook(d):
 
58
 
59
  ydl_opts['progress_hooks'] = [progress_hook]
60
 
61
+ # μž¬μ‹œλ„ 둜직 μΆ”κ°€
62
+ for attempt in range(3):
63
+ try:
64
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
65
+ info = ydl.extract_info(url, download=True)
66
+ filename = ydl.prepare_filename(info)
67
+ return filename
68
+ except yt_dlp.utils.ExtractorError as e:
69
+ if "Sign in to confirm you're not a bot" in str(e):
70
+ status_text.text(f"봇 감지 우회 쀑... ({attempt + 1}/3)")
71
+ time.sleep(random.uniform(3, 5))
72
+ continue
73
+ raise e
74
+ except Exception as e:
75
+ if attempt < 2:
76
+ status_text.text(f"μž¬μ‹œλ„ 쀑... ({attempt + 1}/3)")
77
+ time.sleep(2)
78
+ continue
79
+ raise e
80
 
81
  except Exception as e:
82
  st.error(f"였λ₯˜ λ°œμƒ: {str(e)}")
83
  return None
84
 
85
  # 메인 UI
86
+ if 'video_url' not in st.session_state:
87
+ st.session_state.video_url = ""
88
+
89
+ video_url = st.text_input("YouTube URL μž…λ ₯:",
90
+ value=st.session_state.video_url,
91
  placeholder="https://www.youtube.com/watch?v=...")
92
 
93
  col1, col2 = st.columns(2)
 
113
 
114
  with col2:
115
  if st.button("μ΄ˆκΈ°ν™”"):
116
+ st.session_state.video_url = ""
117
+ st.rerun()