Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,277 +1,254 @@
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
-
import zipfile
|
| 3 |
import tempfile
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
-
import
|
| 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 |
-
return
|
| 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 |
-
return df, out_xlsx, plot1_img, plot2_img, plot3_img, plot4_img
|
| 253 |
-
|
| 254 |
-
# ---------------------------
|
| 255 |
-
# Gradio Interface
|
| 256 |
-
# ---------------------------
|
| 257 |
-
demo = gr.Interface(
|
| 258 |
-
fn=classify_zip_and_analyze_color,
|
| 259 |
-
inputs=gr.File(file_types=[".zip"], label="Upload ZIP of images"),
|
| 260 |
-
outputs=[
|
| 261 |
-
gr.Dataframe(
|
| 262 |
-
headers=["Filename", "Top 3 Predictions", "Confidence",
|
| 263 |
-
"Dominant Color", "Basic Color", "Face Info", "Thumbnail"],
|
| 264 |
-
datatype=["str","str","str","str","str","str","pil"]
|
| 265 |
-
),
|
| 266 |
-
gr.File(label="Download XLSX"),
|
| 267 |
-
gr.Image(type="pil", label="Basic Color Frequency"),
|
| 268 |
-
gr.Image(type="pil", label="Top Prediction Distribution"),
|
| 269 |
-
gr.Image(type="pil", label="Gender Distribution (Weighted β€90%)"),
|
| 270 |
-
gr.Image(type="pil", label="Age Distribution by Gender"),
|
| 271 |
-
],
|
| 272 |
-
title="Image Classifier with Color & Face Analysis",
|
| 273 |
-
description="Upload a ZIP of images. Classifies images, analyzes dominant color, detects/characterizes faces (age, gender, emotion), and shows thumbnails.",
|
| 274 |
-
)
|
| 275 |
|
| 276 |
if __name__ == "__main__":
|
| 277 |
-
demo.launch(
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import requests
|
| 3 |
import os
|
|
|
|
| 4 |
import tempfile
|
| 5 |
+
import shutil
|
| 6 |
+
import urllib.request
|
| 7 |
+
import isodate
|
| 8 |
+
import datetime
|
| 9 |
+
|
| 10 |
+
# --- IMPORTANT: Ensure this environment variable is set ---
|
| 11 |
+
API_KEY = os.getenv("YOUTUBE_API_KEY")
|
| 12 |
+
BASE_URL = "https://www.googleapis.com/youtube/v3"
|
| 13 |
+
|
| 14 |
+
# -----------------------
|
| 15 |
+
# API Usage Tracker
|
| 16 |
+
# -----------------------
|
| 17 |
+
API_USAGE = {"units": 0}
|
| 18 |
+
|
| 19 |
+
def api_get(url, cost, **kwargs):
|
| 20 |
+
"""Wrapper to count quota usage"""
|
| 21 |
+
API_USAGE["units"] += cost
|
| 22 |
+
r = requests.get(url, **kwargs)
|
| 23 |
+
return r
|
| 24 |
+
|
| 25 |
+
# -----------------------
|
| 26 |
+
# Helper Functions (Simplified)
|
| 27 |
+
# -----------------------
|
| 28 |
+
def parse_duration(duration_str):
|
| 29 |
+
try:
|
| 30 |
+
return int(isodate.parse_duration(duration_str).total_seconds())
|
| 31 |
+
except Exception:
|
| 32 |
+
return 0
|
| 33 |
+
|
| 34 |
+
def get_channel_info(channel_id):
|
| 35 |
+
"""Fetches channel snippet (including title) (Cost: 1)."""
|
| 36 |
+
r = api_get(f"{BASE_URL}/channels?part=snippet&id={channel_id}&key={API_KEY}", 1)
|
| 37 |
+
if r.status_code == 200 and 'items' in r.json() and r.json()['items']:
|
| 38 |
+
return r.json()['items'][0]['snippet']
|
| 39 |
+
return None
|
| 40 |
+
|
| 41 |
+
def extract_channel_id(url: str):
|
| 42 |
+
"""Extracts the Channel ID from various YouTube URLs."""
|
| 43 |
+
if "channel/" in url:
|
| 44 |
+
return url.split("channel/")[1].split("/")[0]
|
| 45 |
+
elif "/@" in url:
|
| 46 |
+
handle = url.split("/@")[1].split("/")[0]
|
| 47 |
+
r = api_get(f"{BASE_URL}/search?part=snippet&type=channel&q={handle}&key={API_KEY}", 100)
|
| 48 |
+
if r.status_code != 200: return None
|
| 49 |
+
data = r.json()
|
| 50 |
+
if "items" in data and data["items"]:
|
| 51 |
+
return data["items"][0]["snippet"]["channelId"]
|
| 52 |
+
elif "user/" in url:
|
| 53 |
+
username = url.split("user/")[1].split("/")[0]
|
| 54 |
+
r = api_get(f"{BASE_URL}/channels?part=id&forUsername={username}&key={API_KEY}", 1)
|
| 55 |
+
if r.status_code != 200: return None
|
| 56 |
+
data = r.json()
|
| 57 |
+
if "items" in data and data["items"]:
|
| 58 |
+
return data["items"][0]["id"]
|
| 59 |
+
return None
|
| 60 |
+
|
| 61 |
+
def get_uploads_playlist(channel_id):
|
| 62 |
+
"""Fetches the 'uploads' playlist ID for a given channel (Cost: 1)."""
|
| 63 |
+
r = api_get(f"{BASE_URL}/channels?part=contentDetails&id={channel_id}&key={API_KEY}", 1).json()
|
| 64 |
+
return r['items'][0]['contentDetails']['relatedPlaylists']['uploads']
|
| 65 |
+
|
| 66 |
+
# -----------------------
|
| 67 |
+
# Fetch and Filter Video IDs
|
| 68 |
+
# -----------------------
|
| 69 |
+
def filter_video_ids(video_ids, mode="videos"):
|
| 70 |
+
"""Filters a list of video IDs based on their duration (Cost: 1 unit per 50 videos)."""
|
| 71 |
+
selected = []
|
| 72 |
+
for i in range(0, len(video_ids), 50):
|
| 73 |
+
batch = video_ids[i:i+50]
|
| 74 |
+
r = api_get(f"{BASE_URL}/videos?part=contentDetails&id={','.join(batch)}&key={API_KEY}", 1).json()
|
| 75 |
+
|
| 76 |
+
for item in r.get("items", []):
|
| 77 |
+
if 'contentDetails' not in item: continue
|
| 78 |
+
duration = parse_duration(item["contentDetails"]["duration"])
|
| 79 |
+
vid = item["id"]
|
| 80 |
+
|
| 81 |
+
if mode == "videos":
|
| 82 |
+
if duration >= 60:
|
| 83 |
+
selected.append(vid)
|
| 84 |
+
elif mode == "shorts":
|
| 85 |
+
if duration < 60:
|
| 86 |
+
selected.append(vid)
|
| 87 |
+
elif mode == "all":
|
| 88 |
+
selected.append(vid)
|
| 89 |
+
|
| 90 |
+
return selected
|
| 91 |
+
|
| 92 |
+
def get_playlist_video_ids(playlist_id, max_videos=50, mode="videos"):
|
| 93 |
+
"""Pulls video IDs from a playlist and filters them until max_videos is reached."""
|
| 94 |
+
video_ids = []
|
| 95 |
+
next_page = None
|
| 96 |
+
|
| 97 |
+
while len(video_ids) < max_videos:
|
| 98 |
+
fetch_count = 50
|
| 99 |
+
url = f"{BASE_URL}/playlistItems?part=snippet&playlistId={playlist_id}&maxResults={fetch_count}&key={API_KEY}"
|
| 100 |
+
if next_page: url += f"&pageToken={next_page}"
|
| 101 |
+
|
| 102 |
+
r = api_get(url, 1).json()
|
| 103 |
+
raw_ids = [item["snippet"]["resourceId"]["videoId"] for item in r.get("items", [])]
|
| 104 |
+
filtered_ids = filter_video_ids(raw_ids, mode=mode)
|
| 105 |
+
|
| 106 |
+
remaining_slots = max_videos - len(video_ids)
|
| 107 |
+
video_ids.extend(filtered_ids[:remaining_slots])
|
| 108 |
+
|
| 109 |
+
next_page = r.get("nextPageToken")
|
| 110 |
+
if not next_page or len(raw_ids) == 0:
|
| 111 |
+
break
|
| 112 |
+
|
| 113 |
+
return video_ids[:max_videos]
|
| 114 |
+
|
| 115 |
+
def get_live_video_ids(channel_id, max_videos=50):
|
| 116 |
+
"""Fetches completed live streams (Cost: 100)."""
|
| 117 |
+
video_ids = []
|
| 118 |
+
url = f"{BASE_URL}/search?part=id&channelId={channel_id}&eventType=completed&type=video&maxResults={max_videos}&key={API_KEY}"
|
| 119 |
+
r = api_get(url, 100).json()
|
| 120 |
+
for item in r.get("items", []):
|
| 121 |
+
video_ids.append(item["id"]["videoId"])
|
| 122 |
+
return video_ids
|
| 123 |
+
|
| 124 |
+
# -----------------------
|
| 125 |
+
# Thumbnails Download and Prep
|
| 126 |
+
# -----------------------
|
| 127 |
+
def download_thumbnails(video_ids):
|
| 128 |
+
"""Downloads thumbnails to a temp directory (Cost: 1 unit per 50 thumbnails)."""
|
| 129 |
+
tmp_dir = tempfile.mkdtemp()
|
| 130 |
+
thumb_paths = []
|
| 131 |
+
for i in range(0, len(video_ids), 50):
|
| 132 |
+
batch = video_ids[i:i+50]
|
| 133 |
+
r = api_get(f"{BASE_URL}/videos?part=snippet&id={','.join(batch)}&key={API_KEY}", 1).json()
|
| 134 |
+
for item in r.get("items", []):
|
| 135 |
+
if 'snippet' not in item: continue
|
| 136 |
+
snippet = item['snippet']
|
| 137 |
+
thumbnails = snippet['thumbnails']
|
| 138 |
+
thumb_url = thumbnails.get("maxres", thumbnails.get("standard", thumbnails.get("high", thumbnails.get("default"))))["url"]
|
| 139 |
+
|
| 140 |
+
# Use the video title for the filename for better context in gr.Files
|
| 141 |
+
title_safe = "".join(c if c.isalnum() or c in (' ', '_') else '_' for c in snippet['title']).strip().replace(' ', '_')
|
| 142 |
+
filename = os.path.join(tmp_dir, f"{title_safe}_{item['id']}.jpg")
|
| 143 |
+
|
| 144 |
+
urllib.request.urlretrieve(thumb_url, filename)
|
| 145 |
+
thumb_paths.append(filename)
|
| 146 |
+
return tmp_dir, thumb_paths
|
| 147 |
+
|
| 148 |
+
def fetch_channel_thumbnails(channel_url, max_videos, page_mode):
|
| 149 |
+
"""Main function to orchestrate video fetching and thumbnail download."""
|
| 150 |
+
channel_id = extract_channel_id(channel_url)
|
| 151 |
+
if not channel_id:
|
| 152 |
+
return "β Could not extract channel ID", None, None, None
|
| 153 |
+
|
| 154 |
+
channel_info = get_channel_info(channel_id)
|
| 155 |
+
if not channel_info:
|
| 156 |
+
return "β Could not fetch channel info", None, None, None
|
| 157 |
+
|
| 158 |
+
channel_name = channel_info.get("title", "unknown_channel")
|
| 159 |
+
|
| 160 |
+
if page_mode in ["videos", "shorts", "all"]:
|
| 161 |
+
try:
|
| 162 |
+
playlist_id = get_uploads_playlist(channel_id)
|
| 163 |
+
except Exception:
|
| 164 |
+
return "β Could not find channel 'uploads' playlist ID", None, None, None
|
| 165 |
+
video_ids = get_playlist_video_ids(playlist_id, max_videos=max_videos, mode=page_mode)
|
| 166 |
+
|
| 167 |
+
elif page_mode == "live":
|
| 168 |
+
video_ids = get_live_video_ids(channel_id, max_videos=max_videos)
|
| 169 |
+
else:
|
| 170 |
+
return "β Unknown mode", None, None, None
|
| 171 |
+
|
| 172 |
+
if not video_ids:
|
| 173 |
+
return f"β No {page_mode} found", None, None, None
|
| 174 |
+
|
| 175 |
+
tmp_dir, thumbs = download_thumbnails(video_ids)
|
| 176 |
+
return f"β
Fetched {len(thumbs)} {page_mode}", thumbs, tmp_dir, channel_name
|
| 177 |
+
|
| 178 |
+
def prepare_zip(thumb_dir, channel_name):
|
| 179 |
+
"""Creates a zip archive with a custom filename."""
|
| 180 |
+
safe_channel_name = "".join(c if c.isalnum() or c in (' ', '_') else '_' for c in channel_name).strip().replace(' ', '_')
|
| 181 |
+
date_str = datetime.datetime.now().strftime("%Y%m%d")
|
| 182 |
+
|
| 183 |
+
zip_filename_base = f"{safe_channel_name}_Thumbnails_{date_str}"
|
| 184 |
+
zip_path_no_ext = os.path.join(tempfile.gettempdir(), zip_filename_base)
|
| 185 |
+
|
| 186 |
+
shutil.make_archive(zip_path_no_ext, 'zip', thumb_dir)
|
| 187 |
+
|
| 188 |
+
final_zip_path = zip_path_no_ext + ".zip"
|
| 189 |
+
return final_zip_path
|
| 190 |
+
|
| 191 |
+
# -----------------------
|
| 192 |
+
# Generator for live status updates
|
| 193 |
+
# -----------------------
|
| 194 |
+
def fetch_and_zip_progress(channel_url, max_videos, page_mode):
|
| 195 |
+
API_USAGE["units"] = 0
|
| 196 |
+
yield f"Starting fetch... | API quota used: {API_USAGE['units']} units", [], None, gr.File(visible=False) # π‘ Added gr.File update
|
| 197 |
+
|
| 198 |
+
status, thumbs, tmp_dir, channel_name = fetch_channel_thumbnails(channel_url, max_videos, page_mode)
|
| 199 |
+
quota_used = API_USAGE["units"]
|
| 200 |
+
|
| 201 |
+
final_status = status.replace("videos", "long-form videos (>= 60s)") if page_mode == "videos" else status
|
| 202 |
+
final_status = final_status.replace("shorts", "shorts (< 60s)") if page_mode == "shorts" else final_status
|
| 203 |
+
|
| 204 |
+
zip_file = None
|
| 205 |
+
if thumbs:
|
| 206 |
+
zip_file = prepare_zip(tmp_dir, channel_name)
|
| 207 |
+
|
| 208 |
+
elif tmp_dir and os.path.isdir(tmp_dir):
|
| 209 |
+
shutil.rmtree(tmp_dir)
|
| 210 |
+
|
| 211 |
+
# π‘ IMPORTANT: Now yielding a list of file paths (thumbs) and the zip file path.
|
| 212 |
+
# The 'thumbs' list goes to gr.Files.
|
| 213 |
+
yield f"{final_status} | API quota used: {quota_used} units", thumbs, zip_file, gr.File(visible=True) # π‘ Set visible=True on success
|
| 214 |
+
|
| 215 |
+
# -----------------------
|
| 216 |
+
# Gradio Interface (Modified)
|
| 217 |
+
# -----------------------
|
| 218 |
+
with gr.Blocks() as demo:
|
| 219 |
+
gr.Markdown("## π¬ YouTube Channel Thumbnails Downloader (Files Preview)")
|
| 220 |
+
gr.Markdown("Thumbnails are now listed as individual files. Click the filename to preview/download.")
|
| 221 |
+
|
| 222 |
+
url_input = gr.Textbox(label="YouTube Channel URL", placeholder="https://www.youtube.com/@roisinmurphyofficial")
|
| 223 |
+
page_selector = gr.Dropdown(
|
| 224 |
+
choices=["videos", "shorts", "live", "all"],
|
| 225 |
+
value="videos",
|
| 226 |
+
label="Page to Collect"
|
| 227 |
+
)
|
| 228 |
+
max_videos_slider = gr.Slider(minimum=1, maximum=100, step=1, value=20, label="Max Items to Fetch")
|
| 229 |
+
start_btn = gr.Button("π Start Collect")
|
| 230 |
+
|
| 231 |
+
status_output = gr.Textbox(label="Status")
|
| 232 |
+
|
| 233 |
+
# π‘ REPLACED gr.Gallery with gr.Files
|
| 234 |
+
thumbs_list = gr.Files(
|
| 235 |
+
label="Thumbnails Preview and Download (Click name for preview)",
|
| 236 |
+
file_count="multiple", # Allows multiple files
|
| 237 |
+
type="filepath", # Returns the path, which is what we need
|
| 238 |
+
visible=True # Ensure it's visible initially
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
download_btn = gr.File(label="Download All Thumbnails (ZIP)")
|
| 242 |
+
|
| 243 |
+
start_btn.click(
|
| 244 |
+
fetch_and_zip_progress,
|
| 245 |
+
inputs=[url_input, max_videos_slider, page_selector],
|
| 246 |
+
# π‘ Updated output targets to match the new return values
|
| 247 |
+
outputs=[status_output, thumbs_list, download_btn, download_btn]
|
| 248 |
+
# Note: Added download_btn twice as the generator yields 4 items,
|
| 249 |
+
# but the last one is a gr.File update to hide/show the component.
|
| 250 |
+
# This is a slightly awkward necessity of Gradio's generator API.
|
| 251 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
|
| 253 |
if __name__ == "__main__":
|
| 254 |
+
demo.launch()
|