| 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/pexels") |
| METADATA_DIR = Path("/home/adminuser/chungcat/data/raw/pexels_meta") |
|
|
|
|
| def fetch_page(api_key, query, page, per_page=80, min_width=1024): |
| url = "https://api.pexels.com/v1/search" |
| headers = {"Authorization": api_key} |
| params = {"query": query, "page": page, "per_page": per_page} |
| resp = requests.get(url, headers=headers, params=params, timeout=30) |
| resp.raise_for_status() |
| photos = resp.json()["photos"] |
| return [p for p in photos if p["width"] >= min_width] |
|
|
|
|
| def download_image(photo, save_dir): |
| photo_id = photo["id"] |
| url = photo["src"]["original"] |
| save_path = save_dir / f"{photo_id}.jpg" |
|
|
| 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): |
| meta = { |
| "id": photo["id"], |
| "width": photo["width"], |
| "height": photo["height"], |
| "alt": photo.get("alt", ""), |
| "photographer": photo["photographer"], |
| "src": photo["src"], |
| } |
| meta_path = meta_dir / f"{photo['id']}.json" |
| meta_path.write_text(json.dumps(meta, ensure_ascii=False)) |
|
|
|
|
| def crawl(api_key, queries, max_pages=100, 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(api_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_image, 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_downloaded += 1 |
|
|
| if page % 10 == 0: |
| print(f" Page {page}, total: {total_downloaded}") |
|
|
| print(f"\nDone! Total images: {total_downloaded}") |
|
|
|
|
| if __name__ == "__main__": |
| parser = argparse.ArgumentParser(description="Crawl Pexels images") |
| parser.add_argument("--api-key", required=True, help="Pexels API 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("--workers", type=int, default=8) |
| args = parser.parse_args() |
|
|
| crawl(args.api_key, args.queries, args.max_pages, args.workers) |
|
|