File size: 4,025 Bytes
b373569
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
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
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
import os
import json
import requests
import argparse
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
from tqdm import tqdm

DATA_DIR = Path("/home/adminuser/chungcat/data/raw/unsplash")
METADATA_DIR = Path("/home/adminuser/chungcat/data/raw/unsplash_meta")


def fetch_page(access_key, query, page, per_page=30, min_width=1024):
    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_image(photo, resolution="regular", save_dir=None):
    photo_id = photo["id"]
    url = photo["urls"][resolution]
    ext = "jpg"
    save_path = save_dir / f"{photo_id}.{ext}"

    if save_path.exists():
        return save_path, photo

    try:
        resp = requests.get(url, timeout=60)
        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):
    photo_id = photo["id"]
    meta = {
        "id": photo_id,
        "width": photo["width"],
        "height": photo["height"],
        "description": photo.get("description", ""),
        "alt_description": photo.get("alt_description", ""),
        "urls": photo["urls"],
        "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=100, resolution="regular", workers=8):
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    METADATA_DIR.mkdir(parents=True, exist_ok=True)

    total_downloaded = 0

    for query in queries:
        print(f"\n--- Crawling: '{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:
                print(f"No more results for '{query}' at page {page}")
                break

            with ThreadPoolExecutor(max_workers=workers) as executor:
                futures = []
                for photo in photos:
                    futures.append(
                        executor.submit(download_image, photo, resolution, DATA_DIR)
                    )

                for future in as_completed(futures):
                    path, photo = future.result()
                    if path:
                        save_metadata(photo, METADATA_DIR)
                        total_downloaded += 1

            if page % 10 == 0:
                print(f"  Page {page}, total downloaded: {total_downloaded}")

    print(f"\nDone! Total images: {total_downloaded}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Crawl Unsplash images")
    parser.add_argument("--access-key", required=True, help="Unsplash API access key")
    parser.add_argument(
        "--queries",
        nargs="+",
        default=[
            "landscape", "portrait", "architecture", "nature", "city",
            "food", "technology", "art", "abstract", "animals",
            "fashion", "interior", "street photography", "ocean", "mountain",
        ],
    )
    parser.add_argument("--max-pages", type=int, default=100)
    parser.add_argument(
        "--resolution",
        choices=["raw", "full", "regular", "small"],
        default="full",
        help="Image resolution (full=max quality)",
    )
    parser.add_argument("--workers", type=int, default=8)
    args = parser.parse_args()

    crawl(args.access_key, args.queries, args.max_pages, args.resolution, args.workers)