File size: 11,944 Bytes
11a414e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Unified CLI entry point for E-Waste dataset harvest and pipeline processing.

Subcommands:
  harvest   Query search engines and download raw images
  validate  Verify image integrity, dimensions, format, and aspect ratios
  process   Normalize images (EXIF transpose, alpha composite, JPEG q95)
  dedup     Multi-layer deduplication (exact SHA-256 + flip-aware pHash/dHash)
  report    Print pipeline statistics and summary report
  export    Export SQLite manifest metadata to JSONL
"""
from __future__ import annotations

import argparse
import json
import logging
import os
import sys
from pathlib import Path

# Auto-reexec inside project .venv if not already active
_script_dir = Path(__file__).resolve().parent
_venv_python = _script_dir / ".venv" / "bin" / "python3"
if _venv_python.exists() and sys.executable != str(_venv_python):
    os.execv(str(_venv_python), [str(_venv_python)] + sys.argv)

from pipeline.config import get_paths, load_config, setup_logging, load_queries
from pipeline.manifest import Manifest
from pipeline import validator, processor, dedup, crawler, splitter

log = logging.getLogger("scraper")


def cmd_harvest(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
    force = getattr(args, "force", False)
    log.info("Starting harvest (engine=%s, max_num=%d, force=%s)...", args.engine, args.max_num, force)
    stats = crawler.run(manifest, cfg, paths.data, engine=args.engine, max_num=args.max_num, force=force)
    print(json.dumps(stats, indent=2))
    return 0


def cmd_validate(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
    force = getattr(args, "force", False)
    log.info("Starting validation (force=%s)...", force)
    stats = validator.run(manifest, cfg, paths.data, force=force)
    print(json.dumps(stats, indent=2))
    return 0


def cmd_process(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
    log.info("Starting normalization processing...")
    stats = processor.run(manifest, cfg, paths.data, paths.images)
    print(json.dumps(stats, indent=2))
    return 0


def cmd_dedup(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
    log.info("Starting deduplication...")
    stats = dedup.run(manifest, cfg, paths.data)
    if args.semantic:
        log.info("Running semantic CLIP clustering...")
        sem_stats = dedup.run_semantic(manifest, cfg)
        stats.update(sem_stats)
    print(json.dumps(stats, indent=2))
    return 0


def cmd_report(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
    by_status = manifest.count_by("status")
    by_discard = manifest.count_by("discard_reason", where="status='discarded'")
    class_hints = manifest.class_hints_by_image()

    hint_counts: dict[str, int] = {}
    for hints in class_hints.values():
        for h in hints:
            hint_counts[h] = hint_counts.get(h, 0) + 1

    report_data = {
        "status_distribution": by_status,
        "discard_reasons": by_discard,
        "class_hint_counts": hint_counts,
        "total_images": sum(by_status.values()),
    }

    if args.json:
        print(json.dumps(report_data, indent=2))
    else:
        print("\n=== E-Waste Dataset Pipeline Summary Report ===")
        print(f"Total Images Tracked: {report_data['total_images']}")
        print("\nStatus Distribution:")
        for k, v in by_status.items():
            print(f"  {k:15s}: {v}")
        if by_discard:
            print("\nDiscard Reasons:")
            for k, v in by_discard.items():
                print(f"  {k:20s}: {v}")
        if hint_counts:
            print("\nClass Hints (via Search Provenance):")
            for k, v in sorted(hint_counts.items()):
                print(f"  {k:20s}: {v}")
        print("================================================\n")

    # Save summary report to file
    paths.reports.mkdir(parents=True, exist_ok=True)
    report_file = paths.reports / "summary.json"
    report_file.write_text(json.dumps(report_data, indent=2), encoding="utf-8")
    log.info("Wrote summary report to %s", report_file)
    return 0


def cmd_export(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
    out_path = Path(args.output) if args.output else paths.manifest_jsonl
    log.info("Exporting manifest to %s...", out_path)
    count = manifest.export_jsonl(out_path)
    log.info("Exported %d image metadata entries to %s", count, out_path)
    return 0


def cmd_split(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
    log.info("Starting cluster-aware dataset splitting (train=%.2f, val=%.2f, test=%.2f)...", args.train_ratio, args.val_ratio, args.test_ratio)
    stats = splitter.run(
        manifest, cfg, paths.data, paths.splits,
        train_ratio=args.train_ratio, val_ratio=args.val_ratio, test_ratio=args.test_ratio
    )
    print(json.dumps(stats, indent=2))
    return 0


def cmd_all(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
    log.info("Running complete pipeline: harvest -> validate -> process -> dedup -> report")
    cmd_harvest(args, cfg, manifest, paths)
    cmd_validate(args, cfg, manifest, paths)
    cmd_process(args, cfg, manifest, paths)
    cmd_dedup(args, cfg, manifest, paths)
    return cmd_report(args, cfg, manifest, paths)


def cmd_auto(args: argparse.Namespace, cfg: dict, manifest: Manifest, paths: get_paths) -> int:
    target = getattr(args, "target_per_class", 1500)
    engines = ["bing", "flickr", "baidu"]
    all_classes = set(cfg.get("queries", {}).get("classes", {}).keys()) or {
        "cpu_socket", "gold_finger", "ic_chip", "tantalum_capacitor", "desoldered_zone"
    }
    log.info("Starting automated target loop: goal=%d valid images for ALL classes (%s)", target, sorted(all_classes))

    iteration = 0
    while True:
        iteration += 1
        valid_counts = manifest.valid_counts_by_class()
        log.info("Iteration %d - Current valid counts per class: %s", iteration, valid_counts)

        unsatisfied = {c: target - valid_counts.get(c, 0) for c in all_classes if valid_counts.get(c, 0) < target}
        if not unsatisfied:
            log.info("SUCCESS: All classes reached target of %d valid images!", target)
            break

        log.info("Iteration %d - Deficit classes remaining to satisfy: %s", iteration, unsatisfied)
        
        eng = engines[(iteration - 1) % len(engines)]
        log.info("Harvesting batch for deficit classes using engine=%s (max_num=%d)...", eng, args.max_num)
        
        crawler.run(manifest, cfg, paths.data, engine=eng, max_num=args.max_num, force=True, filter_classes=set(unsatisfied.keys()))
        validator.run(manifest, cfg, paths.data)
        processor.run(manifest, cfg, paths.data, paths.images)
        dedup.run(manifest, cfg, paths.data)

        v_now = manifest.valid_counts_by_class()
        still_needed = {c: target - v_now.get(c, 0) for c in all_classes if v_now.get(c, 0) < target}
        if not still_needed:
            log.info("SUCCESS: All classes reached target of %d valid images!", target)
            break

    return cmd_report(args, cfg, manifest, paths)


def main() -> int:
    parser = argparse.ArgumentParser(description="E-Waste PCB Dataset Harvester & Preprocessing Pipeline")
    parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose DEBUG logging")
    parser.add_argument("-c", "--config", type=str, help="Path to config.yaml file")

    subparsers = parser.add_subparsers(dest="command", required=True, help="Pipeline subcommand")

    # auto
    p_auto = subparsers.add_parser("auto", help="Automated loop: harvest/validate/process/dedup until ALL classes reach target count")
    p_auto.add_argument("--target-per-class", type=int, default=1500, help="Target valid images per class (default: 1500)")
    p_auto.add_argument("--max-num", type=int, default=50, help="Max images per query per batch")
    p_auto.add_argument("--semantic", action="store_true", help="Also run semantic CLIP clustering in dedup stage")
    p_auto.add_argument("--json", action="store_true", help="Output summary report as raw JSON")

    # all
    p_all = subparsers.add_parser("all", help="Run full pipeline: harvest -> validate -> process -> dedup -> report")
    p_all.add_argument("--engine", default="bing", choices=["bing", "flickr", "baidu"], help="Crawler engine")
    p_all.add_argument("--max-num", type=int, default=50, help="Max images per query")
    p_all.add_argument("-f", "--force", action="store_true", help="Force re-harvest queries even if already recorded as done")
    p_all.add_argument("--semantic", action="store_true", help="Also run semantic CLIP clustering in dedup stage")
    p_all.add_argument("--json", action="store_true", help="Output summary report as raw JSON")

    # harvest
    p_harvest = subparsers.add_parser("harvest", help="Harvest images from web search engines")
    p_harvest.add_argument("--engine", default="bing", choices=["bing", "flickr", "baidu"], help="Crawler engine")
    p_harvest.add_argument("--max-num", type=int, default=50, help="Max images per query")
    p_harvest.add_argument("-f", "--force", action="store_true", help="Force re-harvest queries even if already recorded as done")

    # validate
    p_validate = subparsers.add_parser("validate", help="Validate raw images for integrity and dimensions")
    p_validate.add_argument("-f", "--force", action="store_true", help="Re-check previously validated images for AI metadata")

    # process
    subparsers.add_parser("process", help="Normalize images (EXIF, alpha composite, JPEG q95)")

    # dedup
    p_dedup = subparsers.add_parser("dedup", help="Deduplicate images (exact + pHash/dHash)")
    p_dedup.add_argument("--semantic", action="store_true", help="Also run semantic CLIP clustering")

    # report
    p_report = subparsers.add_parser("report", help="Display dataset statistics summary")
    p_report.add_argument("--json", action="store_true", help="Output summary as raw JSON")

    # export
    p_export = subparsers.add_parser("export", help="Export manifest metadata to JSONL file")
    p_export.add_argument("-o", "--output", type=str, help="Output path for jsonl export")

    # split
    p_split = subparsers.add_parser("split", help="Partition dataset into leak-free train/val/test splits")
    p_split.add_argument("--train-ratio", type=float, default=0.70, help="Train split ratio (default: 0.70)")
    p_split.add_argument("--val-ratio", type=float, default=0.15, help="Val split ratio (default: 0.15)")
    p_split.add_argument("--test-ratio", type=float, default=0.15, help="Test split ratio (default: 0.15)")

    args = parser.parse_args()
    setup_logging(verbose=args.verbose)

    cfg = load_config(args.config)
    paths = get_paths(cfg)
    paths.ensure()

    with Manifest(paths.manifest_db) as manifest:
        if args.command == "auto":
            return cmd_auto(args, cfg, manifest, paths)
        elif args.command == "all":
            return cmd_all(args, cfg, manifest, paths)
        elif args.command == "harvest":
            return cmd_harvest(args, cfg, manifest, paths)
        elif args.command == "validate":
            return cmd_validate(args, cfg, manifest, paths)
        elif args.command == "process":
            return cmd_process(args, cfg, manifest, paths)
        elif args.command == "dedup":
            return cmd_dedup(args, cfg, manifest, paths)
        elif args.command == "split":
            return cmd_split(args, cfg, manifest, paths)
        elif args.command == "report":
            return cmd_report(args, cfg, manifest, paths)
        elif args.command == "export":
            return cmd_export(args, cfg, manifest, paths)

    return 0


if __name__ == "__main__":
    sys.exit(main())