File size: 10,550 Bytes
693bf28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
"""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=2,
                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}