Delete training_nest
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- training_nest/down_thumb.py +0 -443
- training_nest/thumbnails/-FHkBz5X45A.jpg +0 -0
- training_nest/thumbnails/-OA19a2iZ8k.jpg +0 -0
- training_nest/thumbnails/-UBlj3lue28.jpg +0 -0
- training_nest/thumbnails/-XbEuSk607o.jpg +0 -0
- training_nest/thumbnails/-frlqbkTq-0.jpg +0 -0
- training_nest/thumbnails/-nc146I26SU.jpg +0 -0
- training_nest/thumbnails/-qhy0NyCM4E.jpg +0 -0
- training_nest/thumbnails/-zE1CsM-XLE.jpg +0 -0
- training_nest/thumbnails/0GGy4xFPK98.jpg +0 -0
- training_nest/thumbnails/0MSQLr1Gowg.jpg +0 -0
- training_nest/thumbnails/0W149qihMPc.jpg +0 -0
- training_nest/thumbnails/0WstANBX-Gk.jpg +0 -0
- training_nest/thumbnails/0xo2cHxyFOM.jpg +0 -0
- training_nest/thumbnails/15qPwAm0G9Y.jpg +0 -0
- training_nest/thumbnails/1zbuM_WFldU.jpg +0 -0
- training_nest/thumbnails/204122b7-5a.jpg +0 -0
- training_nest/thumbnails/24GfgNtnjXc.jpg +0 -0
- training_nest/thumbnails/26ZmKqLNSZ8.jpg +0 -0
- training_nest/thumbnails/2ShxUve0Fv0.jpg +0 -0
- training_nest/thumbnails/2eXyrJUSdq8.jpg +0 -0
- training_nest/thumbnails/2gLRFuX5yNE.jpg +0 -0
- training_nest/thumbnails/2qiDOHj80Po.jpg +0 -0
- training_nest/thumbnails/2sWFexuc7MI.jpg +0 -0
- training_nest/thumbnails/3BqYY5cqq6o.jpg +0 -0
- training_nest/thumbnails/3HAEEnZ2pps.jpg +0 -0
- training_nest/thumbnails/3mx7OSQnBZU.jpg +0 -0
- training_nest/thumbnails/3tW4E9F_Kvg.jpg +0 -0
- training_nest/thumbnails/40fbFJiek7s.jpg +0 -0
- training_nest/thumbnails/42lWmB3X4iI.jpg +0 -0
- training_nest/thumbnails/43o8KheiDRs.jpg +0 -0
- training_nest/thumbnails/4S56uEpQfdw.jpg +0 -0
- training_nest/thumbnails/4af25MQ4Ego.jpg +0 -0
- training_nest/thumbnails/4d0EGIt1SPc.jpg +0 -0
- training_nest/thumbnails/4e-M1boi-iA.jpg +0 -0
- training_nest/thumbnails/4ft2Q02R78Q.jpg +0 -0
- training_nest/thumbnails/4g7oJT1goDM.jpg +0 -0
- training_nest/thumbnails/506ecce6-da.jpg +0 -0
- training_nest/thumbnails/5kBu7z7Ye7M.jpg +0 -0
- training_nest/thumbnails/5ndQVyRAjpo.jpg +0 -0
- training_nest/thumbnails/5pfgNNOYBDU.jpg +0 -0
- training_nest/thumbnails/5wfeehVUGLc.jpg +0 -0
- training_nest/thumbnails/69G43L5G-RY.jpg +0 -0
- training_nest/thumbnails/6G1ztX7YKfA.jpg +0 -0
- training_nest/thumbnails/6GFiqLzeKJ4.jpg +0 -0
- training_nest/thumbnails/7j_cDYAfk1U.jpg +0 -0
- training_nest/thumbnails/7n1Su9AGqsE.jpg +0 -0
- training_nest/thumbnails/7ot-Z-Tg1RE.jpg +0 -0
- training_nest/thumbnails/7s4QX2H-3GI.jpg +0 -0
- training_nest/thumbnails/85fssN_8BIA.jpg +0 -0
training_nest/down_thumb.py
DELETED
|
@@ -1,443 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
-
import uuid
|
| 4 |
-
import aiohttp
|
| 5 |
-
import asyncio
|
| 6 |
-
from PIL import Image, ImageEnhance, UnidentifiedImageError
|
| 7 |
-
from io import BytesIO
|
| 8 |
-
import random
|
| 9 |
-
import time
|
| 10 |
-
from typing import Dict, Any
|
| 11 |
-
from dataclasses import dataclass, field
|
| 12 |
-
|
| 13 |
-
# -------- CONFIG --------
|
| 14 |
-
INPUT_JSON = "/content/thumbnail_title/unified_dataset.json" # Path to your JSON file
|
| 15 |
-
OUTPUT_DIR = "thumbnails" # Directory to save images
|
| 16 |
-
AUGMENT_RATIO = 0.01 # 1% augmentation (your original said 5% but value was 0.01)
|
| 17 |
-
MAX_CONCURRENT = 120 # Limit concurrent requests
|
| 18 |
-
RESUME = True # If True: resume where left off. If False: start from scratch (deletes OUTPUT_DIR)
|
| 19 |
-
MIN_VALID_IMAGE_BYTES = 20000 # Skip tiny/broken images
|
| 20 |
-
CHECKPOINT_FILE = "download_checkpoint.json" # Save statuses during download
|
| 21 |
-
RETRIES = 3
|
| 22 |
-
BACKOFF_BASE = 1.5 # exponential backoff multiplier
|
| 23 |
-
|
| 24 |
-
# -------- Helpers --------
|
| 25 |
-
def human_bytes(n: int) -> str:
|
| 26 |
-
# Convert bytes to human-readable string
|
| 27 |
-
for unit in ("B", "KB", "MB", "GB", "TB"):
|
| 28 |
-
if n < 1024:
|
| 29 |
-
return f"{n:.1f}{unit}"
|
| 30 |
-
n /= 1024
|
| 31 |
-
return f"{n:.1f}PB"
|
| 32 |
-
|
| 33 |
-
@dataclass
|
| 34 |
-
class ProgressTracker:
|
| 35 |
-
total_tasks: int = 0
|
| 36 |
-
completed: int = 0
|
| 37 |
-
succeeded: int = 0
|
| 38 |
-
failed: int = 0
|
| 39 |
-
active: int = 0
|
| 40 |
-
retries: int = 0
|
| 41 |
-
bytes_downloaded: int = 0
|
| 42 |
-
start_time: float = field(default_factory=time.time)
|
| 43 |
-
per_file_bytes: Dict[str, int] = field(default_factory=dict) # video_id -> bytes downloaded so far
|
| 44 |
-
lock: asyncio.Lock = field(default_factory=asyncio.Lock)
|
| 45 |
-
|
| 46 |
-
async def add_bytes(self, video_id: str, n: int):
|
| 47 |
-
async with self.lock:
|
| 48 |
-
self.bytes_downloaded += n
|
| 49 |
-
self.per_file_bytes[video_id] = self.per_file_bytes.get(video_id, 0) + n
|
| 50 |
-
|
| 51 |
-
async def start_task(self, video_id: str):
|
| 52 |
-
async with self.lock:
|
| 53 |
-
self.active += 1
|
| 54 |
-
self.per_file_bytes.setdefault(video_id, 0)
|
| 55 |
-
|
| 56 |
-
async def finish_task(self, video_id: str, success: bool):
|
| 57 |
-
async with self.lock:
|
| 58 |
-
self.active -= 1
|
| 59 |
-
self.completed += 1
|
| 60 |
-
if success:
|
| 61 |
-
self.succeeded += 1
|
| 62 |
-
else:
|
| 63 |
-
self.failed += 1
|
| 64 |
-
# cleanup per-file bytes
|
| 65 |
-
self.per_file_bytes.pop(video_id, None)
|
| 66 |
-
|
| 67 |
-
async def add_retry(self):
|
| 68 |
-
async with self.lock:
|
| 69 |
-
self.retries += 1
|
| 70 |
-
|
| 71 |
-
# -------- Download + Progress UI --------
|
| 72 |
-
async def show_progress(tracker: ProgressTracker, refresh_interval: float = 0.7):
|
| 73 |
-
"""Background task that prints progress summary periodically."""
|
| 74 |
-
try:
|
| 75 |
-
last_bytes = 0
|
| 76 |
-
last_time = time.time()
|
| 77 |
-
while True:
|
| 78 |
-
await asyncio.sleep(refresh_interval)
|
| 79 |
-
async with tracker.lock:
|
| 80 |
-
now = time.time()
|
| 81 |
-
elapsed = now - tracker.start_time
|
| 82 |
-
bytes_now = tracker.bytes_downloaded
|
| 83 |
-
delta_bytes = bytes_now - last_bytes
|
| 84 |
-
delta_time = now - last_time
|
| 85 |
-
speed = delta_bytes / delta_time if delta_time > 0 else 0.0
|
| 86 |
-
last_bytes = bytes_now
|
| 87 |
-
last_time = now
|
| 88 |
-
|
| 89 |
-
completed = tracker.completed
|
| 90 |
-
total = tracker.total_tasks
|
| 91 |
-
active = tracker.active
|
| 92 |
-
succeeded = tracker.succeeded
|
| 93 |
-
failed = tracker.failed
|
| 94 |
-
retries = tracker.retries
|
| 95 |
-
|
| 96 |
-
# ETA based on average speed (if some remaining and speed > 0)
|
| 97 |
-
remaining = total - completed
|
| 98 |
-
avg_speed = bytes_now / elapsed if elapsed > 0 else 0
|
| 99 |
-
eta = None
|
| 100 |
-
if avg_speed > 0 and remaining > 0:
|
| 101 |
-
# We don't know precise bytes remaining, so estimate by tasks left
|
| 102 |
-
# Use avg bytes per finished task to estimate bytes remaining
|
| 103 |
-
avg_bytes_per_task = (bytes_now / succeeded) if succeeded > 0 else 0
|
| 104 |
-
est_bytes_left = avg_bytes_per_task * remaining
|
| 105 |
-
eta = est_bytes_left / avg_speed if avg_speed > 0 else None
|
| 106 |
-
|
| 107 |
-
# Build status line
|
| 108 |
-
status_lines = []
|
| 109 |
-
status_lines.append(f"Completed: {completed}/{total} | Active: {active} | "
|
| 110 |
-
f"Succeeded: {succeeded} | Failed: {failed} | Retries: {retries}")
|
| 111 |
-
status_lines.append(f"Downloaded: {human_bytes(bytes_now)} | Speed: {human_bytes(int(speed))}/s | Elapsed: {int(elapsed)}s")
|
| 112 |
-
if eta:
|
| 113 |
-
status_lines.append(f"ETA (approx): {int(eta)}s")
|
| 114 |
-
# show up to 5 largest active file downloads
|
| 115 |
-
active_downloads = sorted(tracker.per_file_bytes.items(), key=lambda x: -x[1])[:5]
|
| 116 |
-
if active_downloads:
|
| 117 |
-
ad = " | ".join([f"{vid[:11]}:{human_bytes(b)}" for vid, b in active_downloads])
|
| 118 |
-
status_lines.append(f"Top active: {ad}")
|
| 119 |
-
# Print clean block
|
| 120 |
-
print("\n" + "-" * 80)
|
| 121 |
-
for line in status_lines:
|
| 122 |
-
print(line)
|
| 123 |
-
print("-" * 80)
|
| 124 |
-
except asyncio.CancelledError:
|
| 125 |
-
# clean exit
|
| 126 |
-
return
|
| 127 |
-
|
| 128 |
-
async def fetch_thumbnail(session: aiohttp.ClientSession, video_id: str, save_dir: str,
|
| 129 |
-
tracker: ProgressTracker, semaphore: asyncio.Semaphore,
|
| 130 |
-
checkpoint: Dict[str, Any]):
|
| 131 |
-
"""
|
| 132 |
-
Download YouTube thumbnail (tries maxres, sd, hq) with resume support (Range).
|
| 133 |
-
Writes to .part file and then atomic renames to .jpg only on successful verification.
|
| 134 |
-
Updates tracker with bytes downloaded.
|
| 135 |
-
Retries on failure.
|
| 136 |
-
"""
|
| 137 |
-
quality_urls = [
|
| 138 |
-
f"https://img.youtube.com/vi/{video_id}/maxresdefault.jpg",
|
| 139 |
-
f"https://img.youtube.com/vi/{video_id}/sddefault.jpg",
|
| 140 |
-
f"https://img.youtube.com/vi/{video_id}/hqdefault.jpg"
|
| 141 |
-
]
|
| 142 |
-
|
| 143 |
-
dest_path = os.path.join(save_dir, f"{video_id}.jpg")
|
| 144 |
-
part_path = dest_path + ".part"
|
| 145 |
-
|
| 146 |
-
# If final file exists and is large enough, skip
|
| 147 |
-
if os.path.exists(dest_path):
|
| 148 |
-
if os.path.getsize(dest_path) >= MIN_VALID_IMAGE_BYTES:
|
| 149 |
-
checkpoint[video_id] = {"status": "skipped_already_exists", "bytes": os.path.getsize(dest_path)}
|
| 150 |
-
return dest_path
|
| 151 |
-
else:
|
| 152 |
-
# remove tiny/broken file so it will be re-downloaded
|
| 153 |
-
try:
|
| 154 |
-
os.remove(dest_path)
|
| 155 |
-
except Exception:
|
| 156 |
-
pass
|
| 157 |
-
|
| 158 |
-
# Attempt resume from .part
|
| 159 |
-
existing_part_size = os.path.getsize(part_path) if os.path.exists(part_path) else 0
|
| 160 |
-
|
| 161 |
-
await tracker.start_task(video_id)
|
| 162 |
-
|
| 163 |
-
# Acquire semaphore for concurrent control
|
| 164 |
-
async with semaphore:
|
| 165 |
-
for url in quality_urls:
|
| 166 |
-
attempt = 0
|
| 167 |
-
current_part_size = existing_part_size
|
| 168 |
-
while attempt <= RETRIES:
|
| 169 |
-
try:
|
| 170 |
-
headers = {}
|
| 171 |
-
# If we have a partial file, request Range from existing size
|
| 172 |
-
if current_part_size > 0:
|
| 173 |
-
headers["Range"] = f"bytes={current_part_size}-"
|
| 174 |
-
|
| 175 |
-
async with session.get(url, headers=headers, timeout=aiohttp.ClientTimeout(total=60)) as resp:
|
| 176 |
-
# Accept 200 (fresh full file), 206 (partial content), maybe 416 (range not satisfiable)
|
| 177 |
-
if resp.status in (200, 206):
|
| 178 |
-
# Determine content length: if Range requested and got 206, content-length is remaining bytes
|
| 179 |
-
# We'll stream into the .part file in append mode
|
| 180 |
-
mode = "ab" if (resp.status == 206 or current_part_size > 0) else "wb"
|
| 181 |
-
# Prepare temp file
|
| 182 |
-
os.makedirs(save_dir, exist_ok=True)
|
| 183 |
-
with open(part_path, mode) as fh:
|
| 184 |
-
async for chunk in resp.content.iter_chunked(1024 * 16):
|
| 185 |
-
if not chunk:
|
| 186 |
-
continue
|
| 187 |
-
fh.write(chunk)
|
| 188 |
-
current_part_size += len(chunk)
|
| 189 |
-
await tracker.add_bytes(video_id, len(chunk))
|
| 190 |
-
# After stream complete, validate file size and attempt to open with PIL
|
| 191 |
-
try:
|
| 192 |
-
if os.path.getsize(part_path) >= MIN_VALID_IMAGE_BYTES:
|
| 193 |
-
# quick validation
|
| 194 |
-
with Image.open(part_path) as img:
|
| 195 |
-
img.verify() # verify without loading completely
|
| 196 |
-
# rename final
|
| 197 |
-
os.replace(part_path, dest_path)
|
| 198 |
-
checkpoint[video_id] = {"status": "downloaded", "bytes": os.path.getsize(dest_path)}
|
| 199 |
-
await tracker.finish_task(video_id, success=True)
|
| 200 |
-
return dest_path
|
| 201 |
-
else:
|
| 202 |
-
# too small — maybe this quality not available; try next quality
|
| 203 |
-
attempt += 1
|
| 204 |
-
await tracker.add_retry()
|
| 205 |
-
checkpoint[video_id] = {"status": "too_small", "bytes": os.path.getsize(part_path)}
|
| 206 |
-
# remove the part file to start fresh on next try, else we'll loop forever
|
| 207 |
-
try:
|
| 208 |
-
os.remove(part_path)
|
| 209 |
-
except Exception:
|
| 210 |
-
pass
|
| 211 |
-
current_part_size = 0
|
| 212 |
-
break # exit inner while and try next quality URL
|
| 213 |
-
except (UnidentifiedImageError, Exception) as e:
|
| 214 |
-
# corrupted content; try again / next quality
|
| 215 |
-
attempt += 1
|
| 216 |
-
await tracker.add_retry()
|
| 217 |
-
checkpoint[video_id] = {"status": "verify_failed", "error": str(e)}
|
| 218 |
-
# Remove the part and try again
|
| 219 |
-
try:
|
| 220 |
-
os.remove(part_path)
|
| 221 |
-
except Exception:
|
| 222 |
-
pass
|
| 223 |
-
current_part_size = 0
|
| 224 |
-
await asyncio.sleep((BACKOFF_BASE ** attempt) * 0.2)
|
| 225 |
-
continue
|
| 226 |
-
elif resp.status == 404:
|
| 227 |
-
# This quality not available; try next quality
|
| 228 |
-
break
|
| 229 |
-
elif resp.status == 416:
|
| 230 |
-
# Requested range not satisfiable, maybe server says file complete
|
| 231 |
-
# try to validate current part
|
| 232 |
-
try:
|
| 233 |
-
with Image.open(part_path) as img:
|
| 234 |
-
img.verify()
|
| 235 |
-
os.replace(part_path, dest_path)
|
| 236 |
-
checkpoint[video_id] = {"status": "downloaded_via_416", "bytes": os.path.getsize(dest_path)}
|
| 237 |
-
await tracker.finish_task(video_id, success=True)
|
| 238 |
-
return dest_path
|
| 239 |
-
except Exception:
|
| 240 |
-
attempt += 1
|
| 241 |
-
await tracker.add_retry()
|
| 242 |
-
try:
|
| 243 |
-
os.remove(part_path)
|
| 244 |
-
except Exception:
|
| 245 |
-
pass
|
| 246 |
-
current_part_size = 0
|
| 247 |
-
await asyncio.sleep((BACKOFF_BASE ** attempt) * 0.2)
|
| 248 |
-
continue
|
| 249 |
-
else:
|
| 250 |
-
# other status codes - treat as retryable for a few attempts
|
| 251 |
-
attempt += 1
|
| 252 |
-
await tracker.add_retry()
|
| 253 |
-
checkpoint[video_id] = {"status": "http_error", "status_code": resp.status}
|
| 254 |
-
await asyncio.sleep((BACKOFF_BASE ** attempt) * 0.2)
|
| 255 |
-
continue
|
| 256 |
-
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
|
| 257 |
-
attempt += 1
|
| 258 |
-
await tracker.add_retry()
|
| 259 |
-
checkpoint[video_id] = {"status": "network_error", "error": str(e), "attempt": attempt}
|
| 260 |
-
await asyncio.sleep((BACKOFF_BASE ** attempt) * 0.2)
|
| 261 |
-
continue
|
| 262 |
-
# exhausted retries for this quality, try next quality
|
| 263 |
-
# If we reach here, all qualities failed
|
| 264 |
-
await tracker.finish_task(video_id, success=False)
|
| 265 |
-
checkpoint[video_id] = {"status": "failed_all_qualities"}
|
| 266 |
-
return None
|
| 267 |
-
|
| 268 |
-
# -------- IMAGE AUGMENTATION --------
|
| 269 |
-
def get_class(view_count: int):
|
| 270 |
-
if 1_000 <= view_count < 10_000:
|
| 271 |
-
return "1k-10k"
|
| 272 |
-
elif 10_000 <= view_count < 100_000:
|
| 273 |
-
return "10k-100k"
|
| 274 |
-
elif 100_000 <= view_count < 1_000_000:
|
| 275 |
-
return "100k-1m"
|
| 276 |
-
elif view_count >= 1_000_000:
|
| 277 |
-
return "1m+"
|
| 278 |
-
else:
|
| 279 |
-
return None
|
| 280 |
-
|
| 281 |
-
def augment_image(image_path: str, new_id: str, save_dir: str):
|
| 282 |
-
"""Create augmented copy of an image (basic augmentations)."""
|
| 283 |
-
img = Image.open(image_path)
|
| 284 |
-
# Random augmentations
|
| 285 |
-
if random.random() > 0.5:
|
| 286 |
-
img = img.transpose(Image.FLIP_LEFT_RIGHT)
|
| 287 |
-
if random.random() > 0.5:
|
| 288 |
-
img = img.rotate(random.choice([5, -5, 10, -10]), expand=True)
|
| 289 |
-
enhancer = ImageEnhance.Brightness(img)
|
| 290 |
-
img = enhancer.enhance(random.uniform(0.8, 1.2))
|
| 291 |
-
new_path = os.path.join(save_dir, f"{new_id}.jpg")
|
| 292 |
-
img.save(new_path)
|
| 293 |
-
return new_path
|
| 294 |
-
|
| 295 |
-
# -------- MAIN --------
|
| 296 |
-
async def main():
|
| 297 |
-
# Prepare output
|
| 298 |
-
if not RESUME:
|
| 299 |
-
# start fresh: delete output dir if exists and any checkpoint
|
| 300 |
-
if os.path.exists(OUTPUT_DIR):
|
| 301 |
-
for fn in os.listdir(OUTPUT_DIR):
|
| 302 |
-
try:
|
| 303 |
-
os.remove(os.path.join(OUTPUT_DIR, fn))
|
| 304 |
-
except Exception:
|
| 305 |
-
pass
|
| 306 |
-
try:
|
| 307 |
-
if os.path.exists(CHECKPOINT_FILE):
|
| 308 |
-
os.remove(CHECKPOINT_FILE)
|
| 309 |
-
except Exception:
|
| 310 |
-
pass
|
| 311 |
-
|
| 312 |
-
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 313 |
-
|
| 314 |
-
# Load input json
|
| 315 |
-
with open(INPUT_JSON, "r", encoding="utf-8") as f:
|
| 316 |
-
data = json.load(f)
|
| 317 |
-
if isinstance(data, dict):
|
| 318 |
-
data = [data]
|
| 319 |
-
|
| 320 |
-
# Build list of entries to process
|
| 321 |
-
entries = data
|
| 322 |
-
|
| 323 |
-
# Build checkpoint dict from file if present
|
| 324 |
-
checkpoint = {}
|
| 325 |
-
if RESUME and os.path.exists(CHECKPOINT_FILE):
|
| 326 |
-
try:
|
| 327 |
-
with open(CHECKPOINT_FILE, "r", encoding="utf-8") as f:
|
| 328 |
-
checkpoint = json.load(f)
|
| 329 |
-
except Exception:
|
| 330 |
-
checkpoint = {}
|
| 331 |
-
|
| 332 |
-
# Create progress tracker
|
| 333 |
-
tracker = ProgressTracker(total_tasks=len(entries))
|
| 334 |
-
|
| 335 |
-
# Create aiohttp session and spawn download tasks
|
| 336 |
-
connector = aiohttp.TCPConnector(limit=MAX_CONCURRENT)
|
| 337 |
-
semaphore = asyncio.Semaphore(MAX_CONCURRENT)
|
| 338 |
-
|
| 339 |
-
# If some entries already have final files, we can pre-mark them in checkpoint to speed up progress
|
| 340 |
-
for e in entries:
|
| 341 |
-
vid = e.get("video_id")
|
| 342 |
-
if not vid:
|
| 343 |
-
continue
|
| 344 |
-
final_path = os.path.join(OUTPUT_DIR, f"{vid}.jpg")
|
| 345 |
-
if os.path.exists(final_path) and os.path.getsize(final_path) >= MIN_VALID_IMAGE_BYTES:
|
| 346 |
-
checkpoint.setdefault(vid, {"status": "downloaded_existing", "bytes": os.path.getsize(final_path)})
|
| 347 |
-
|
| 348 |
-
# Build tasks but skip those with existing success statuses in checkpoint (to resume)
|
| 349 |
-
to_download = []
|
| 350 |
-
for e in entries:
|
| 351 |
-
vid = e.get("video_id")
|
| 352 |
-
status = checkpoint.get(vid, {}).get("status")
|
| 353 |
-
if status and status.startswith("downloaded"):
|
| 354 |
-
# skip
|
| 355 |
-
await_tracker_finish = False
|
| 356 |
-
# mark as completed so progress counts it (we'll adjust completed counter)
|
| 357 |
-
# We'll just count these as succeeded already
|
| 358 |
-
tracker.completed += 1
|
| 359 |
-
tracker.succeeded += 1
|
| 360 |
-
b = checkpoint.get(vid, {}).get("bytes", 0)
|
| 361 |
-
tracker.bytes_downloaded += b
|
| 362 |
-
continue
|
| 363 |
-
to_download.append(e)
|
| 364 |
-
|
| 365 |
-
# Adjust tracker total_tasks to reflect remaining tasks; we still want total to show original number
|
| 366 |
-
tracker.total_tasks = len(entries)
|
| 367 |
-
|
| 368 |
-
async with aiohttp.ClientSession(connector=connector) as session:
|
| 369 |
-
# Start background progress display task
|
| 370 |
-
progress_task = asyncio.create_task(show_progress(tracker))
|
| 371 |
-
|
| 372 |
-
# Create download tasks
|
| 373 |
-
tasks = []
|
| 374 |
-
for e in to_download:
|
| 375 |
-
vid = e.get("video_id")
|
| 376 |
-
tasks.append(asyncio.create_task(fetch_thumbnail(session, vid, OUTPUT_DIR, tracker, semaphore, checkpoint)))
|
| 377 |
-
|
| 378 |
-
# Wait for all downloads to finish
|
| 379 |
-
results = []
|
| 380 |
-
if tasks:
|
| 381 |
-
for fut in asyncio.as_completed(tasks):
|
| 382 |
-
res = await fut
|
| 383 |
-
results.append(res)
|
| 384 |
-
# persist checkpoint occasionally
|
| 385 |
-
try:
|
| 386 |
-
with open(CHECKPOINT_FILE, "w", encoding="utf-8") as fh:
|
| 387 |
-
json.dump(checkpoint, fh, indent=2, ensure_ascii=False)
|
| 388 |
-
except Exception:
|
| 389 |
-
pass
|
| 390 |
-
|
| 391 |
-
# Cancel progress task and do a final print
|
| 392 |
-
progress_task.cancel()
|
| 393 |
-
try:
|
| 394 |
-
await progress_task
|
| 395 |
-
except asyncio.CancelledError:
|
| 396 |
-
pass
|
| 397 |
-
|
| 398 |
-
# Final checkpoint write
|
| 399 |
-
try:
|
| 400 |
-
with open(CHECKPOINT_FILE, "w", encoding="utf-8") as fh:
|
| 401 |
-
json.dump(checkpoint, fh, indent=2, ensure_ascii=False)
|
| 402 |
-
except Exception:
|
| 403 |
-
pass
|
| 404 |
-
|
| 405 |
-
# Build meta_data from all successful downloads (including those present before)
|
| 406 |
-
meta_data = []
|
| 407 |
-
for e in entries:
|
| 408 |
-
vid = e.get("video_id")
|
| 409 |
-
final_path = os.path.join(OUTPUT_DIR, f"{vid}.jpg")
|
| 410 |
-
if os.path.exists(final_path) and os.path.getsize(final_path) >= MIN_VALID_IMAGE_BYTES:
|
| 411 |
-
entry_copy = dict(e)
|
| 412 |
-
entry_copy["class"] = get_class(entry_copy.get("views", 0))
|
| 413 |
-
meta_data.append(entry_copy)
|
| 414 |
-
|
| 415 |
-
# Step 2: Augment AUGMENT_RATIO of data per class
|
| 416 |
-
print("Augmenting data...")
|
| 417 |
-
class_groups = {}
|
| 418 |
-
for e in meta_data:
|
| 419 |
-
if e["class"]:
|
| 420 |
-
class_groups.setdefault(e["class"], []).append(e)
|
| 421 |
-
|
| 422 |
-
for cls, items in class_groups.items():
|
| 423 |
-
n_aug = max(1, int(len(items) * AUGMENT_RATIO))
|
| 424 |
-
to_augment = random.sample(items, n_aug)
|
| 425 |
-
for e in to_augment:
|
| 426 |
-
new_id = str(uuid.uuid4())[:11]
|
| 427 |
-
img_path = os.path.join(OUTPUT_DIR, f"{e['video_id']}.jpg")
|
| 428 |
-
if not os.path.exists(img_path):
|
| 429 |
-
continue
|
| 430 |
-
augment_image(img_path, new_id, OUTPUT_DIR)
|
| 431 |
-
new_entry = dict(e)
|
| 432 |
-
new_entry["video_id"] = new_id
|
| 433 |
-
meta_data.append(new_entry)
|
| 434 |
-
|
| 435 |
-
# Step 3: Save updated metadata
|
| 436 |
-
with open("augmented_videos.json", "w", encoding="utf-8") as f:
|
| 437 |
-
json.dump(meta_data, f, indent=4, ensure_ascii=False)
|
| 438 |
-
|
| 439 |
-
print("✅ Done! Thumbnails and augmented data saved.")
|
| 440 |
-
print(f"Checkpoint saved to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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
training_nest/thumbnails/-FHkBz5X45A.jpg
DELETED
|
Binary file (70.2 kB)
|
|
|
training_nest/thumbnails/-OA19a2iZ8k.jpg
DELETED
|
Binary file (88.1 kB)
|
|
|
training_nest/thumbnails/-UBlj3lue28.jpg
DELETED
|
Binary file (43.1 kB)
|
|
|
training_nest/thumbnails/-XbEuSk607o.jpg
DELETED
|
Binary file (53.4 kB)
|
|
|
training_nest/thumbnails/-frlqbkTq-0.jpg
DELETED
|
Binary file (92.8 kB)
|
|
|
training_nest/thumbnails/-nc146I26SU.jpg
DELETED
|
Binary file (53 kB)
|
|
|
training_nest/thumbnails/-qhy0NyCM4E.jpg
DELETED
|
Binary file (85 kB)
|
|
|
training_nest/thumbnails/-zE1CsM-XLE.jpg
DELETED
|
Binary file (69.1 kB)
|
|
|
training_nest/thumbnails/0GGy4xFPK98.jpg
DELETED
|
Binary file (50.7 kB)
|
|
|
training_nest/thumbnails/0MSQLr1Gowg.jpg
DELETED
|
Binary file (90.7 kB)
|
|
|
training_nest/thumbnails/0W149qihMPc.jpg
DELETED
|
Binary file (62.6 kB)
|
|
|
training_nest/thumbnails/0WstANBX-Gk.jpg
DELETED
|
Binary file (99.1 kB)
|
|
|
training_nest/thumbnails/0xo2cHxyFOM.jpg
DELETED
|
Binary file (54.3 kB)
|
|
|
training_nest/thumbnails/15qPwAm0G9Y.jpg
DELETED
|
Binary file (55.1 kB)
|
|
|
training_nest/thumbnails/1zbuM_WFldU.jpg
DELETED
|
Binary file (79 kB)
|
|
|
training_nest/thumbnails/204122b7-5a.jpg
DELETED
|
Binary file (69.8 kB)
|
|
|
training_nest/thumbnails/24GfgNtnjXc.jpg
DELETED
|
Binary file (50.5 kB)
|
|
|
training_nest/thumbnails/26ZmKqLNSZ8.jpg
DELETED
|
Binary file (86 kB)
|
|
|
training_nest/thumbnails/2ShxUve0Fv0.jpg
DELETED
|
Binary file (66.9 kB)
|
|
|
training_nest/thumbnails/2eXyrJUSdq8.jpg
DELETED
|
Binary file (91.5 kB)
|
|
|
training_nest/thumbnails/2gLRFuX5yNE.jpg
DELETED
|
Binary file (65.6 kB)
|
|
|
training_nest/thumbnails/2qiDOHj80Po.jpg
DELETED
|
Binary file (54.1 kB)
|
|
|
training_nest/thumbnails/2sWFexuc7MI.jpg
DELETED
|
Binary file (83.2 kB)
|
|
|
training_nest/thumbnails/3BqYY5cqq6o.jpg
DELETED
|
Binary file (76.3 kB)
|
|
|
training_nest/thumbnails/3HAEEnZ2pps.jpg
DELETED
|
Binary file (80.5 kB)
|
|
|
training_nest/thumbnails/3mx7OSQnBZU.jpg
DELETED
|
Binary file (83.1 kB)
|
|
|
training_nest/thumbnails/3tW4E9F_Kvg.jpg
DELETED
|
Binary file (79.6 kB)
|
|
|
training_nest/thumbnails/40fbFJiek7s.jpg
DELETED
|
Binary file (79 kB)
|
|
|
training_nest/thumbnails/42lWmB3X4iI.jpg
DELETED
|
Binary file (80.2 kB)
|
|
|
training_nest/thumbnails/43o8KheiDRs.jpg
DELETED
|
Binary file (89.2 kB)
|
|
|
training_nest/thumbnails/4S56uEpQfdw.jpg
DELETED
|
Binary file (69.5 kB)
|
|
|
training_nest/thumbnails/4af25MQ4Ego.jpg
DELETED
|
Binary file (88.4 kB)
|
|
|
training_nest/thumbnails/4d0EGIt1SPc.jpg
DELETED
|
Binary file (86.1 kB)
|
|
|
training_nest/thumbnails/4e-M1boi-iA.jpg
DELETED
|
Binary file (80.5 kB)
|
|
|
training_nest/thumbnails/4ft2Q02R78Q.jpg
DELETED
|
Binary file (37.4 kB)
|
|
|
training_nest/thumbnails/4g7oJT1goDM.jpg
DELETED
|
Binary file (95.2 kB)
|
|
|
training_nest/thumbnails/506ecce6-da.jpg
DELETED
|
Binary file (80.4 kB)
|
|
|
training_nest/thumbnails/5kBu7z7Ye7M.jpg
DELETED
|
Binary file (82.4 kB)
|
|
|
training_nest/thumbnails/5ndQVyRAjpo.jpg
DELETED
|
Binary file (44.7 kB)
|
|
|
training_nest/thumbnails/5pfgNNOYBDU.jpg
DELETED
|
Binary file (98.4 kB)
|
|
|
training_nest/thumbnails/5wfeehVUGLc.jpg
DELETED
|
Binary file (53 kB)
|
|
|
training_nest/thumbnails/69G43L5G-RY.jpg
DELETED
|
Binary file (49.2 kB)
|
|
|
training_nest/thumbnails/6G1ztX7YKfA.jpg
DELETED
|
Binary file (77.6 kB)
|
|
|
training_nest/thumbnails/6GFiqLzeKJ4.jpg
DELETED
|
Binary file (76.9 kB)
|
|
|
training_nest/thumbnails/7j_cDYAfk1U.jpg
DELETED
|
Binary file (63 kB)
|
|
|
training_nest/thumbnails/7n1Su9AGqsE.jpg
DELETED
|
Binary file (95.3 kB)
|
|
|
training_nest/thumbnails/7ot-Z-Tg1RE.jpg
DELETED
|
Binary file (87.7 kB)
|
|
|
training_nest/thumbnails/7s4QX2H-3GI.jpg
DELETED
|
Binary file (94.7 kB)
|
|
|
training_nest/thumbnails/85fssN_8BIA.jpg
DELETED
|
Binary file (55.2 kB)
|
|
|