"""Harvesting engine: query search engines (icrawler / HTTP fallback) and download raw image binaries. Flow: 1. Build query list from queries.yaml matrix. 2. For each query and engine: - Skip if `harvest_runs` records the run as done. - Surface image URLs and store in `sources` and `hits` tables via `manifest.add_hit`. - Record completed run in `harvest_runs`. 3. Download pending URLs into `data/originals/`, computing SHA-256 ID. 4. Register downloaded files in `images` table with status 'downloaded'. """ from __future__ import annotations import hashlib import logging import mimetypes import urllib.request import urllib.error from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path from typing import Sequence from tqdm import tqdm from .manifest import Manifest, normalize_url from .queries import QuerySpec, build_queries log = logging.getLogger(__name__) HEADERS = { "User-Agent": ( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" ), "Accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8", } EXT_MAP = { "image/jpeg": ".jpg", "image/jpg": ".jpg", "image/png": ".png", "image/webp": ".webp", "image/gif": ".gif", "image/bmp": ".bmp", "image/tiff": ".tif", "image/heic": ".heic", "image/heif": ".heif", } def download_single_url( source: dict, originals_dir: Path, timeout: float = 10.0 ) -> tuple[dict, str | None, str | None, int | None, str | None]: """Download raw binary for one URL. Returns (source, image_id, filepath, http_status, error_message). """ url = source["url"] url_norm = source["url_norm"] req = urllib.request.Request(url, headers=HEADERS) try: with urllib.request.urlopen(req, timeout=timeout) as resp: content_type = resp.headers.get("Content-Type", "").split(";")[0].strip().lower() data = resp.read() http_status = resp.status except urllib.error.HTTPError as exc: return source, None, None, exc.code, f"HTTPError: {exc.code}" except Exception as exc: return source, None, None, None, f"{type(exc).__name__}: {exc}" if len(data) < 500: return source, None, None, http_status, "file_too_small_raw" sha = hashlib.sha256(data).hexdigest() image_id = sha[:16] ext = EXT_MAP.get(content_type) or Path(url).suffix.lower() if not ext or len(ext) > 5 or ext not in (".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp", ".tif", ".heic"): ext = ".jpg" dst = originals_dir / f"{image_id}{ext}" if not dst.exists(): originals_dir.mkdir(parents=True, exist_ok=True) tmp = dst.with_name(dst.name + f".tmp") tmp.write_bytes(data) tmp.replace(dst) return source, image_id, str(dst), http_status, None def download_pending_sources( manifest: Manifest, originals_dir: Path, data_dir: Path, cfg: dict ) -> dict[str, int]: """Download pending URLs from manifest into `originals_dir`.""" ccfg = cfg.get("crawler", {}) workers = int(ccfg.get("threads", 4)) timeout = float(ccfg.get("timeout", 10.0)) pending = manifest.pending_sources() stats = {"downloaded": 0, "download_failed": 0} if not pending: log.info("crawler: no pending sources to download") return stats log.info("crawler: downloading %d pending URL(s)", len(pending)) def work(src: dict): return download_single_url(src, originals_dir, timeout=timeout) with ThreadPoolExecutor(max_workers=workers) as ex: futures = [ex.submit(work, s) for s in pending] with manifest.transaction(): for fut in tqdm(as_completed(futures), total=len(futures), desc="download", unit="url"): src, image_id, dst_path, http_status, err = fut.result() if err is None and image_id and dst_path: data_file = Path(dst_path) data = data_file.read_bytes() sha = hashlib.sha256(data).hexdigest() rel_path = str(data_file.relative_to(data_dir)) manifest.add_image( image_id=image_id, sha256=sha, origin="web", source_ref=src["url"], orig_path=rel_path, orig_format=data_file.suffix.lstrip(".").lower(), filesize=len(data), status="downloaded", ) manifest.mark_source( src["url_norm"], status="downloaded", http_status=http_status, image_id=image_id, attempts=1, ) stats["downloaded"] += 1 else: manifest.mark_source( src["url_norm"], status="failed", http_status=http_status, error=err, attempts=1, ) stats["download_failed"] += 1 log.info("crawler download stats: %s", stats) return stats def run_icrawler_harvest( manifest: Manifest, queries: Sequence[QuerySpec], data_dir: Path, engine_name: str = "bing", max_num: int = 50, force: bool = False, filter_classes: set[str] | Sequence[str] | None = None, ) -> dict[str, int]: """Harvest image binaries using icrawler, save to data/originals, and register in manifest.""" stats = {"runs": 0, "urls_found": 0, "urls_new": 0, "images_harvested": 0} try: if engine_name.lower() == "bing": from icrawler.builtin import BingImageCrawler as CrawlerEngine elif engine_name.lower() == "flickr": from icrawler.builtin import FlickrImageCrawler as CrawlerEngine elif engine_name.lower() == "baidu": from icrawler.builtin import BaiduImageCrawler as CrawlerEngine else: log.warning("Unknown engine '%s', defaulting to Bing", engine_name) from icrawler.builtin import BingImageCrawler as CrawlerEngine except ImportError: log.warning("icrawler is not installed; skipping search engine crawling") return stats import tempfile import shutil originals_dir = data_dir / "originals" originals_dir.mkdir(parents=True, exist_ok=True) filter_set = set(filter_classes) if filter_classes else None for qspec in queries: if filter_set and qspec.class_hint not in filter_set: continue if not force and manifest.run_done(engine_name, qspec.query): log.debug("Skip harvest done run: %s / %s", engine_name, qspec.query) continue tmp_dir = Path(tempfile.mkdtemp(prefix="icrawler_")) try: crawler = CrawlerEngine( downloader_threads=8, storage={"root_dir": str(tmp_dir)}, log_level=logging.WARNING, ) crawler.crawl(keyword=qspec.query, max_num=max_num) found_count = 0 new_count = 0 with manifest.transaction(): for img_file in tmp_dir.glob("*"): if img_file.is_file() and img_file.stat().st_size > 500: found_count += 1 data = img_file.read_bytes() sha = hashlib.sha256(data).hexdigest() image_id = sha[:16] ext = img_file.suffix.lower() if not ext or len(ext) > 5 or ext not in (".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp"): ext = ".jpg" dst_file = originals_dir / f"{image_id}{ext}" if not dst_file.exists(): dst_file.write_bytes(data) source_url = f"icrawler://{engine_name}/{qspec.class_hint}/{image_id}" is_new = manifest.add_hit( source_url, engine_name, qspec.query, class_hint=qspec.class_hint, lang=qspec.lang ) if is_new: new_count += 1 rel_path = str(dst_file.relative_to(data_dir)) manifest.add_image( image_id=image_id, sha256=sha, origin="web", source_ref=source_url, orig_path=rel_path, orig_format=ext.lstrip("."), filesize=len(data), status="downloaded", ) manifest.mark_source( source_url, status="downloaded", image_id=image_id, ) stats["images_harvested"] += 1 manifest.record_run( engine_name, qspec.query, qspec.class_hint, max_num, found_count, new_count ) stats["runs"] += 1 stats["urls_found"] += found_count stats["urls_new"] += new_count except Exception as exc: log.error("icrawler harvest failed for %s (%s): %s", qspec.query, engine_name, exc) finally: shutil.rmtree(tmp_dir, ignore_errors=True) log.info("harvest stats (%s): %s", engine_name, stats) return stats def run( manifest: Manifest, cfg: dict, data_dir: Path, engine: str = "bing", max_num: int = 50, force: bool = False, filter_classes: set[str] | Sequence[str] | None = None ) -> dict[str, int]: """Full crawler workflow: harvest queries and download raw images.""" qcfg = cfg.get("queries") or {} if not qcfg: from .config import load_queries qcfg = load_queries(cfg) queries = build_queries(qcfg) harvest_stats = run_icrawler_harvest(manifest, queries, data_dir, engine_name=engine, max_num=max_num, force=force, filter_classes=filter_classes) originals_dir = data_dir / "originals" download_stats = download_pending_sources(manifest, originals_dir, data_dir, cfg) return {**harvest_stats, **download_stats}