memoryai's picture
Upload folder using huggingface_hub
b373569 verified
"""
Crawl high-resolution 4K images for super-resolution training.
Uses Unsplash API filtering for images >= 3840px width.
"""
import os
import json
import requests
import argparse
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
DATA_DIR = Path("/home/adminuser/chungcat/data/raw/4k")
METADATA_DIR = Path("/home/adminuser/chungcat/data/raw/4k_meta")
MIN_WIDTH = 3840
def fetch_page(access_key, query, page, per_page=30):
url = "https://api.unsplash.com/search/photos"
params = {
"query": query,
"page": page,
"per_page": per_page,
"client_id": access_key,
}
resp = requests.get(url, params=params, timeout=30)
resp.raise_for_status()
results = resp.json()["results"]
return [r for r in results if r["width"] >= MIN_WIDTH]
def download_raw(photo, save_dir):
photo_id = photo["id"]
url = photo["urls"]["raw"]
save_path = save_dir / f"{photo_id}.jpg"
if save_path.exists():
return save_path, photo
try:
resp = requests.get(url, timeout=120)
resp.raise_for_status()
save_path.write_bytes(resp.content)
return save_path, photo
except Exception as e:
print(f"Failed {photo_id}: {e}")
return None, photo
def save_metadata(photo, meta_dir):
meta = {
"id": photo["id"],
"width": photo["width"],
"height": photo["height"],
"description": photo.get("description", ""),
"alt_description": photo.get("alt_description", ""),
"user": photo["user"]["name"],
"tags": [t.get("title", "") for t in photo.get("tags", [])],
}
meta_path = meta_dir / f"{photo['id']}.json"
meta_path.write_text(json.dumps(meta, ensure_ascii=False))
def crawl(access_key, queries, max_pages=200, workers=4):
DATA_DIR.mkdir(parents=True, exist_ok=True)
METADATA_DIR.mkdir(parents=True, exist_ok=True)
total = 0
for query in queries:
print(f"\n--- Crawling 4K: '{query}' ---")
for page in range(1, max_pages + 1):
try:
photos = fetch_page(access_key, query, page)
except Exception as e:
print(f"Page {page} failed: {e}")
break
if not photos:
break
with ThreadPoolExecutor(max_workers=workers) as executor:
futures = [
executor.submit(download_raw, photo, DATA_DIR)
for photo in photos
]
for future in as_completed(futures):
path, photo = future.result()
if path:
save_metadata(photo, METADATA_DIR)
total += 1
if page % 10 == 0:
print(f" Page {page}, total 4K images: {total}")
print(f"\nDone! Total 4K images: {total}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Crawl 4K images for SR training")
parser.add_argument("--access-key", required=True, help="Unsplash API access key")
parser.add_argument(
"--queries",
nargs="+",
default=[
"4k wallpaper", "high resolution landscape", "8k nature",
"ultra hd photography", "4k portrait", "high resolution architecture",
"macro photography", "aerial photography", "4k city",
"high resolution texture", "4k abstract", "detailed photography",
],
)
parser.add_argument("--max-pages", type=int, default=200)
parser.add_argument("--workers", type=int, default=4)
args = parser.parse_args()
crawl(args.access_key, args.queries, args.max_pages, args.workers)