Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,232 +1,196 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
import yt_dlp
|
3 |
-
import
|
4 |
-
import
|
5 |
-
import
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
class
|
12 |
def __init__(self):
|
13 |
-
self.
|
|
|
|
|
|
|
14 |
|
15 |
def is_valid_youtube_url(self, url):
|
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 |
-
return report.strip()
|
79 |
-
|
80 |
-
def get_video_info(self, url, progress=gr.Progress(), cookiefile=None):
|
81 |
-
if not url or not url.strip():
|
82 |
-
return None, "β Please enter a YouTube URL"
|
83 |
-
|
84 |
if not self.is_valid_youtube_url(url):
|
85 |
-
return
|
86 |
-
|
87 |
-
try:
|
88 |
-
progress(0.2, desc="Fetching video information...")
|
89 |
-
ydl_opts = {
|
90 |
-
'noplaylist': True,
|
91 |
-
'extract_flat': False,
|
92 |
-
}
|
93 |
-
if cookiefile:
|
94 |
-
ydl_opts['cookiefile'] = cookiefile
|
95 |
-
|
96 |
-
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
97 |
-
try:
|
98 |
-
info = ydl.extract_info(url, download=False)
|
99 |
-
video_info = {
|
100 |
-
'title': info.get('title', 'Unknown'),
|
101 |
-
'description': info.get('description', 'No description available'),
|
102 |
-
'duration': info.get('duration', 0),
|
103 |
-
'view_count': info.get('view_count', 0),
|
104 |
-
'like_count': info.get('like_count', 0),
|
105 |
-
'comment_count': info.get('comment_count', 0),
|
106 |
-
'upload_date': info.get('upload_date', ''),
|
107 |
-
'uploader': info.get('uploader', 'Unknown'),
|
108 |
-
'channel': info.get('channel', 'Unknown'),
|
109 |
-
'channel_followers': info.get('channel_follower_count', 0),
|
110 |
-
'tags': info.get('tags', []),
|
111 |
-
'categories': info.get('categories', []),
|
112 |
-
'thumbnail': info.get('thumbnail', ''),
|
113 |
-
'webpage_url': info.get('webpage_url', url)
|
114 |
-
}
|
115 |
-
progress(1.0, desc="Information retrieved!")
|
116 |
-
return video_info, "β
Video information retrieved successfully"
|
117 |
-
except yt_dlp.DownloadError as e:
|
118 |
-
error_msg = str(e)
|
119 |
-
if "Video unavailable" in error_msg:
|
120 |
-
return None, "β Video is unavailable or private"
|
121 |
-
elif "age-restricted" in error_msg.lower():
|
122 |
-
return None, "β Video is age-restricted"
|
123 |
-
else:
|
124 |
-
return None, f"β Failed to get video info: {error_msg}"
|
125 |
-
except Exception as e:
|
126 |
-
return None, f"β An unexpected error occurred: {str(e)}"
|
127 |
-
|
128 |
-
def download_video(self, url, progress=gr.Progress(), cookiefile=None):
|
129 |
-
if not url or not url.strip():
|
130 |
-
return None, "β Please enter a YouTube URL"
|
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 |
if __name__ == "__main__":
|
229 |
-
|
230 |
-
import atexit
|
231 |
-
atexit.register(downloader.cleanup)
|
232 |
-
demo.launch()
|
|
|
1 |
+
import os
|
2 |
import gradio as gr
|
3 |
import yt_dlp
|
4 |
+
import webvtt
|
5 |
+
import google.generativeai as genai
|
6 |
+
from datetime import datetime
|
7 |
+
|
8 |
+
genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) # Set your Gemini API key in environment
|
9 |
+
MODEL_ID = "gemini-1.5-flash-latest"
|
10 |
+
model = genai.GenerativeModel(model_name=MODEL_ID)
|
11 |
+
|
12 |
+
class VideoAnalyzer:
|
13 |
def __init__(self):
|
14 |
+
self.temp_dir = "temp_subs"
|
15 |
+
os.makedirs(self.temp_dir, exist_ok=True)
|
16 |
+
self.downloads_dir = os.path.join(os.path.expanduser("~"), "Downloads", "YT_Reports")
|
17 |
+
os.makedirs(self.downloads_dir, exist_ok=True)
|
18 |
|
19 |
def is_valid_youtube_url(self, url):
|
20 |
+
return "youtube.com" in url or "youtu.be" in url
|
21 |
+
|
22 |
+
def download_info_and_subs(self, url, cookiefile=None):
|
23 |
+
ydl_opts = {
|
24 |
+
'writesubtitles': True,
|
25 |
+
'writeautomaticsub': True,
|
26 |
+
'subtitleslangs': ['en', 'en-HI', 'hi'],
|
27 |
+
'skip_download': True,
|
28 |
+
'outtmpl': os.path.join(self.temp_dir, 'video'),
|
29 |
+
}
|
30 |
+
if cookiefile:
|
31 |
+
ydl_opts['cookiefile'] = cookiefile
|
32 |
+
|
33 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
34 |
+
info = ydl.extract_info(url, download=False)
|
35 |
+
subs = info.get('automatic_captions') or info.get('subtitles')
|
36 |
+
return info if subs else None, info
|
37 |
+
|
38 |
+
def extract_captions(self, vtt_path):
|
39 |
+
captions = []
|
40 |
+
for caption in webvtt.read(vtt_path):
|
41 |
+
text = caption.text.strip().replace("\n", " ")
|
42 |
+
captions.append(f"[{caption.start} - {caption.end}]: {text}")
|
43 |
+
return captions
|
44 |
+
|
45 |
+
def generate_scene_descriptions(self, captions):
|
46 |
+
prompt = """You are a visual scene narrator. Turn the following subtitles into timestamped scene descriptions.
|
47 |
+
Use natural language and visual imagination. Avoid brand names.
|
48 |
+
|
49 |
+
Example output:
|
50 |
+
* **[0:00-0:01]:** A young woman with dark hair, wearing a red shirt, sits at a desk in a modern office...
|
51 |
+
|
52 |
+
Now convert these subtitles:
|
53 |
+
|
54 |
+
"""
|
55 |
+
prompt += "\n".join(captions[:20]) # Limit to first 20 captions
|
56 |
+
|
57 |
+
response = model.generate_content(prompt)
|
58 |
+
return response.text
|
59 |
+
|
60 |
+
def detect_influencer_status(self, info):
|
61 |
+
prompt = f"""You are a media analyst. Based on this metadata, tell if this channel is a famous influencer, brand, or regular user.
|
62 |
+
|
63 |
+
Channel: {info.get('channel', '')}
|
64 |
+
Uploader: {info.get('uploader', '')}
|
65 |
+
Subscribers: {info.get('channel_followers', 0)}
|
66 |
+
Title: {info.get('title', '')}
|
67 |
+
Description: {info.get('description', '')}
|
68 |
+
|
69 |
+
Respond with 1 line like 'Famous Influencer', 'Verified Brand Channel', or 'Regular Content Creator'."""
|
70 |
+
result = model.generate_content(prompt)
|
71 |
+
return result.text.strip()
|
72 |
+
|
73 |
+
def format_number(self, num):
|
74 |
+
if not num: return "0"
|
75 |
+
if num >= 1_000_000_000: return f"{num / 1_000_000_000:.1f}B"
|
76 |
+
elif num >= 1_000_000: return f"{num / 1_000_000:.1f}M"
|
77 |
+
elif num >= 1_000: return f"{num / 1_000:.1f}K"
|
78 |
+
return str(num)
|
79 |
+
|
80 |
+
def analyze(self, url, cookiefile=None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
if not self.is_valid_youtube_url(url):
|
82 |
+
return "β Invalid YouTube URL."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
|
84 |
+
info, raw_info = self.download_info_and_subs(url, cookiefile)
|
85 |
+
if not info:
|
86 |
+
return "β Subtitles not found for this video."
|
87 |
+
|
88 |
+
vtt_path = None
|
89 |
+
for file in os.listdir(self.temp_dir):
|
90 |
+
if file.endswith(".vtt"):
|
91 |
+
vtt_path = os.path.join(self.temp_dir, file)
|
92 |
+
break
|
93 |
+
|
94 |
+
if not vtt_path:
|
95 |
+
return "β Subtitle file not found."
|
96 |
+
|
97 |
+
captions = self.extract_captions(vtt_path)
|
98 |
+
scene_block = self.generate_scene_descriptions(captions)
|
99 |
+
|
100 |
+
duration = raw_info.get('duration', 0)
|
101 |
+
duration_str = f"{duration//3600}:{(duration%3600)//60:02d}:{duration%60:02d}" if duration else "Unknown"
|
102 |
+
upload_date = raw_info.get('upload_date', '')
|
103 |
+
formatted_date = f"{upload_date[:4]}-{upload_date[4:6]}-{upload_date[6:8]}" if len(upload_date) == 8 else "Unknown"
|
104 |
+
|
105 |
+
view_count = raw_info.get('view_count', 0)
|
106 |
+
like_count = raw_info.get('like_count', 0)
|
107 |
+
dislike_count = raw_info.get('dislike_count', 0)
|
108 |
+
comment_count = raw_info.get('comment_count', 0)
|
109 |
+
subscriber_count = raw_info.get('channel_followers', 0)
|
110 |
+
engagement_rate = (like_count / view_count) * 100 if view_count else 0
|
111 |
+
like_ratio = (like_count / (like_count + dislike_count)) * 100 if (like_count + dislike_count) else 0
|
112 |
+
comment_ratio = (comment_count / view_count) * 100 if view_count else 0
|
113 |
+
|
114 |
+
influencer_status = self.detect_influencer_status(raw_info)
|
115 |
+
|
116 |
+
summary = f"""
|
117 |
+
π BASIC INFORMATION
|
118 |
+
{'β'*30}
|
119 |
+
πΉ **Title:** {raw_info.get('title', 'Unknown')}
|
120 |
+
πΊ **Channel:** {raw_info.get('channel', 'Unknown')}
|
121 |
+
π€ **Uploader:** {raw_info.get('uploader', 'Unknown')}
|
122 |
+
π
**Upload Date:** {formatted_date}
|
123 |
+
β±οΈ **Duration:** {duration_str}
|
124 |
+
π **Video ID:** {raw_info.get('id', 'Unknown')}
|
125 |
+
π **Video URL:** {raw_info.get('webpage_url', 'Unknown')}
|
126 |
+
|
127 |
+
π PERFORMANCE METRICS
|
128 |
+
{'β'*30}
|
129 |
+
π **Views:** {self.format_number(view_count)} ({view_count:,} exact)
|
130 |
+
π **Likes:** {self.format_number(like_count)} ({like_count:,} exact)
|
131 |
+
π **Dislikes:** {self.format_number(dislike_count)} ({dislike_count:,} exact)
|
132 |
+
π¬ **Comments:** {self.format_number(comment_count)} ({comment_count:,} exact)
|
133 |
+
π₯ **Subscribers:** {self.format_number(subscriber_count)} ({subscriber_count:,} exact)
|
134 |
+
π **Engagement Rate:** {engagement_rate:.2f}% (likes/views)
|
135 |
+
β€οΈ **Like Ratio:** {like_ratio:.1f}% (likes vs total reactions)
|
136 |
+
π **Comment Ratio:** {comment_ratio:.3f}% (comments/views)
|
137 |
+
|
138 |
+
π INFLUENCER STATUS
|
139 |
+
{'β'*30}
|
140 |
+
{influencer_status}
|
141 |
+
|
142 |
+
π¬ SCENE-BY-SCENE BREAKDOWN
|
143 |
+
{'β'*30}
|
144 |
+
{scene_block}
|
145 |
+
""".strip()
|
146 |
+
|
147 |
+
return summary
|
148 |
+
|
149 |
+
def download_video(self, url, quality="best", audio_only=False, cookiefile=None):
|
150 |
+
ydl_opts = {
|
151 |
+
'outtmpl': os.path.join(self.downloads_dir, '%(title)s.%(ext)s'),
|
152 |
+
'format': 'bestaudio/best' if audio_only else 'best',
|
153 |
+
'noplaylist': True
|
154 |
+
}
|
155 |
+
if cookiefile:
|
156 |
+
ydl_opts['cookiefile'] = cookiefile
|
157 |
+
|
158 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
159 |
+
info = ydl.extract_info(url, download=True)
|
160 |
+
filename = ydl.prepare_filename(info)
|
161 |
+
return filename
|
162 |
+
|
163 |
+
analyzer = VideoAnalyzer()
|
164 |
+
|
165 |
+
def analyze_video(url, cookies_file):
|
166 |
+
cookiefile = cookies_file.name if cookies_file else None
|
167 |
+
return analyzer.analyze(url, cookiefile)
|
168 |
+
|
169 |
+
def download_video(url, quality, audio_only, cookies_file):
|
170 |
+
cookiefile = cookies_file.name if cookies_file else None
|
171 |
+
return analyzer.download_video(url, quality, audio_only, cookiefile)
|
172 |
+
|
173 |
+
with gr.Blocks(title="YouTube Analyzer + Downloader") as iface:
|
174 |
+
gr.Markdown("# π¬ YouTube Video Analyzer + Downloader")
|
175 |
+
url = gr.Textbox(label="YouTube URL")
|
176 |
+
cookies = gr.File(label="Upload cookies.txt (Optional)", file_types=[".txt"], type="file")
|
177 |
+
|
178 |
+
with gr.Tab("π Analyze Video"):
|
179 |
+
analyze_btn = gr.Button("Analyze")
|
180 |
+
analysis_output = gr.Textbox(label="Analysis Report", lines=40, show_copy_button=True)
|
181 |
+
analyze_btn.click(fn=analyze_video, inputs=[url, cookies], outputs=analysis_output)
|
182 |
+
|
183 |
+
with gr.Tab("β¬οΈ Download Video"):
|
184 |
+
quality = gr.Dropdown(["best", "720p", "480p"], label="Quality", value="best")
|
185 |
+
audio_only = gr.Checkbox(label="Audio Only", value=False)
|
186 |
+
download_btn = gr.Button("Download")
|
187 |
+
download_output = gr.Textbox(label="Download Status")
|
188 |
+
|
189 |
+
def handle_download(url, quality, audio_only, cookies_file):
|
190 |
+
path = download_video(url, quality, audio_only, cookies_file)
|
191 |
+
return f"β
Downloaded to: {path}"
|
192 |
+
|
193 |
+
download_btn.click(fn=handle_download, inputs=[url, quality, audio_only, cookies], outputs=download_output)
|
194 |
|
195 |
if __name__ == "__main__":
|
196 |
+
iface.launch(debug=True)
|
|
|
|
|
|