lexicalspace commited on
Commit
9e6a33f
·
verified ·
1 Parent(s): f619c35

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -53
app.py CHANGED
@@ -1,9 +1,7 @@
1
  import streamlit as st
2
- import os
 
3
  import time
4
- from pytube import YouTube
5
- from pytube.exceptions import RegexMatchError, VideoUnavailable
6
- import ffmpeg
7
  from PIL import Image
8
  import io
9
  import re
@@ -30,79 +28,68 @@ app_mode = st.sidebar.radio(
30
  )
31
 
32
  # ==========================================
33
- # VIEW 1: YOUTUBE DOWNLOADER (Pytube Version)
34
  # ==========================================
35
  if app_mode == "YouTube Downloader":
36
  st.title("🎥 YouTube Media Extractor")
37
- st.info("Download Video (720p/1080p) or Audio (MP3).")
38
 
39
  url = st.text_input("Paste YouTube URL", placeholder="https://youtube.com/watch?v=...")
40
 
41
  col1, col2 = st.columns(2)
42
  with col1:
 
43
  format_type = st.radio("Format", ["Video (MP4)", "Audio Only (MP3)"])
44
 
45
  if url and st.button("🚀 Process Media"):
46
  status_area = st.empty()
47
- status_area.info("⏳ Connecting to YouTube...")
48
 
49
  try:
50
- # 1. Initialize Pytube Object
51
- yt = YouTube(url)
 
 
 
 
 
52
 
53
- # This triggers the network call - if it fails here, the IP is blocked.
54
- video_title = yt.title
55
- status_area.info(f"✅ Found: {video_title}")
56
-
57
- timestamp = int(time.time())
58
- filename = f"{timestamp}_{re.sub(r'[^a-zA-Z0-9]', '', video_title)}"
59
- final_path = ""
60
 
61
- # 2. Download Logic
62
- if format_type == "Video (MP4)":
63
- # Get highest resolution progressive stream (audio+video combined)
64
- # Pytube progressive streams are usually max 720p but safest/most stable
65
- stream = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first()
66
- final_path = stream.download(filename=filename + ".mp4")
67
-
68
- else: # Audio Only
69
- # Get audio only stream
70
- stream = yt.streams.filter(only_audio=True).first()
71
- downloaded_file = stream.download(filename=filename + ".mp4")
72
-
73
- # Rename to mp3 (Pytube downloads audio as mp4/webm container)
74
- base, ext = os.path.splitext(downloaded_file)
75
- final_path = base + ".mp3"
76
- os.rename(downloaded_file, final_path)
77
 
78
- # 3. Serve File
79
- if os.path.exists(final_path):
80
- status_area.success("✅ Download Ready!")
81
 
82
- with open(final_path, "rb") as f:
83
- file_bytes = f.read()
84
- st.download_button(
85
- label=f"⬇️ Download {format_type}",
86
- data=file_bytes,
87
- file_name=os.path.basename(final_path),
88
- mime="video/mp4" if "Video" in format_type else "audio/mpeg"
89
- )
90
 
91
- # Cleanup
92
- os.remove(final_path)
 
 
 
 
 
 
 
93
  else:
94
- st.error("Processing failed during save.")
95
 
96
- except RegexMatchError:
97
- st.error("Invalid URL. Please check the link.")
98
- except VideoUnavailable:
99
- st.error("Video is unavailable (Private or Region Blocked).")
100
  except Exception as e:
101
- # If this prints a network error again, the server IP is definitely banned.
102
- st.error(f"Error: {str(e)}")
103
 
104
  # ==========================================
105
- # VIEW 2: WEBMASTER TOOLKIT
106
  # ==========================================
107
  elif app_mode == "Webmaster Toolkit":
108
  st.title("⚡ Webmaster's Toolkit")
 
1
  import streamlit as st
2
+ import requests
3
+ import json
4
  import time
 
 
 
5
  from PIL import Image
6
  import io
7
  import re
 
28
  )
29
 
30
  # ==========================================
31
+ # VIEW 1: YOUTUBE DOWNLOADER (API Version)
32
  # ==========================================
33
  if app_mode == "YouTube Downloader":
34
  st.title("🎥 YouTube Media Extractor")
35
+ st.info("High-Speed Downloader (Powered by Cobalt API)")
36
 
37
  url = st.text_input("Paste YouTube URL", placeholder="https://youtube.com/watch?v=...")
38
 
39
  col1, col2 = st.columns(2)
40
  with col1:
41
+ # Cobalt supports various qualities. We'll map them simple.
42
  format_type = st.radio("Format", ["Video (MP4)", "Audio Only (MP3)"])
43
 
44
  if url and st.button("🚀 Process Media"):
45
  status_area = st.empty()
46
+ status_area.info("⏳ Contacting processing server...")
47
 
48
  try:
49
+ # Cobalt API Configuration
50
+ api_url = "https://api.cobalt.tools/api/json"
51
+ headers = {
52
+ "Accept": "application/json",
53
+ "Content-Type": "application/json",
54
+ "User-Agent": "LexicalTools/1.0"
55
+ }
56
 
57
+ payload = {
58
+ "url": url,
59
+ "vCodec": "h264",
60
+ "vQuality": "1080",
61
+ "aFormat": "mp3",
62
+ "isAudioOnly": True if "Audio" in format_type else False
63
+ }
64
 
65
+ # Send Request
66
+ response = requests.post(api_url, headers=headers, json=payload)
67
+ data = response.json()
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
+ if "url" in data:
70
+ download_link = data["url"]
71
+ status_area.success("✅ Media Ready!")
72
 
73
+ # Show a Direct Download Link (Fastest method)
74
+ st.link_button(f"⬇️ Click to Download {format_type}", download_link)
 
 
 
 
 
 
75
 
76
+ # Optional: Preview
77
+ if "Audio" not in format_type:
78
+ st.video(download_link)
79
+ else:
80
+ st.audio(download_link)
81
+
82
+ elif "text" in data:
83
+ # API returned an error message
84
+ st.error(f"Server Error: {data['text']}")
85
  else:
86
+ st.error("Unknown error from processing server.")
87
 
 
 
 
 
88
  except Exception as e:
89
+ st.error(f"Connection Error: {str(e)}")
 
90
 
91
  # ==========================================
92
+ # VIEW 2: WEBMASTER TOOLKIT (Existing)
93
  # ==========================================
94
  elif app_mode == "Webmaster Toolkit":
95
  st.title("⚡ Webmaster's Toolkit")