"""Orchestrate pipeline stages (ingest → standardize → dedup → text → enrich → package).""" from __future__ import annotations import json import os import shutil from concurrent.futures import ProcessPoolExecutor, as_completed from pathlib import Path from typing import Any, Optional import cv2 from tqdm import tqdm from . import dedup, ingest, package, quality as quality_mod, sketch_fabric, standardize, taxonomy, text_noise from .config import PipelineConfig, load_config def _load_jsonl(path: Path) -> list[dict[str, Any]]: if not path.is_file(): return [] rows: list[dict[str, Any]] = [] with open(path, encoding="utf-8") as f: for line in f: line = line.strip() if line: rows.append(json.loads(line)) return rows def _save_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with open(path, "w", encoding="utf-8") as f: for r in rows: f.write(json.dumps(r, ensure_ascii=False) + "\n") def _default_workers(cfg: PipelineConfig) -> int: w = cfg.enrich.workers if w and w > 0: return w return max(1, (os.cpu_count() or 4) - 1) def stage_ingest(cfg: PipelineConfig) -> Path: cfg.output_root.mkdir(parents=True, exist_ok=True) out = ingest.run_ingest(cfg) idx = cfg.work_dir / "index.jsonl" if out.is_file(): rows = _load_jsonl(out) _save_jsonl(idx, rows) return cfg.work_dir / "index.jsonl" def stage_standardize(cfg: PipelineConfig) -> None: idx_path = cfg.work_dir / "index.jsonl" rows = _load_jsonl(idx_path) if not rows and cfg.raw_manifest_jsonl: rows = _load_jsonl(Path(cfg.raw_manifest_jsonl)) _save_jsonl(idx_path, rows) if not rows: raise FileNotFoundError( "No index rows. In pipeline_config.yaml, set non-empty paths under `sources` " "(`images_dir` / `images_dirs` pointing to folders that contain images), " "or set `raw_manifest_jsonl` to a JSONL manifest. " "The default template uses empty placeholders — you must replace them with real paths." ) cfg.train_dir.mkdir(parents=True, exist_ok=True) cfg.test_dir.mkdir(parents=True, exist_ok=True) for row in tqdm(rows, desc="standardize"): src = Path(row["image_path"]) if not src.is_file(): row["standardize_error"] = "missing_source_image" continue bgr = None if cfg.target_size > 0 or cfg.quality.enabled: bgr = standardize.read_image_bgr(src) if bgr is None: row["standardize_error"] = "read_fail" continue if cfg.quality.enabled: assert bgr is not None quality_mod.annotate_quality(row, bgr, cfg.quality.min_short_side_ratio) if row.get("quality_ok") is False: row["skip_reason"] = "quality_aspect" continue split = str(row.get("split") or "train").lower() gt = str(row.get("gt") or Path(row["image_path"]).name) dst_root = cfg.test_dir if split == "test" else cfg.train_dir # Keep original filename; if collision, rename and update `gt` accordingly. dst = dst_root / gt if dst.exists(): stem = Path(gt).stem ext = Path(gt).suffix src_tag = str(row.get("source_id") or "src") k = 1 while True: cand = dst_root / f"{stem}__{src_tag}__{k}{ext}" if not cand.exists(): dst = cand row["gt"] = dst.name row["id"] = dst.stem break k += 1 if cfg.target_size <= 0: # No resize: byte-copy original file. dst.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(src, dst) # Record size if possible (best-effort). bgr2 = cv2.imread(str(dst), cv2.IMREAD_COLOR) if bgr2 is not None: h2, w2 = bgr2.shape[:2] row["image_size"] = [int(w2), int(h2)] else: assert bgr is not None try: sq = standardize.letterbox_square_bgr(bgr, cfg.target_size) except Exception as e: row["standardize_error"] = str(e) continue standardize.write_image(dst, sq) row["image_size"] = [cfg.target_size, cfg.target_size] row["image_512"] = str(dst) for row in rows: ok = True if cfg.quality.enabled: ok = bool(row.get("quality_ok", True)) row["use_in_training"] = ok and not row.get("skip_reason") _save_jsonl(idx_path, rows) def stage_dedup(cfg: PipelineConfig) -> None: idx_path = cfg.work_dir / "index.jsonl" rows = _load_jsonl(idx_path) if not cfg.dedup.enabled: _save_jsonl(idx_path, rows) return without = [r for r in rows if not r.get("image_512")] for row in without: row.setdefault("dedup_status", "no_image") with_img = [r for r in rows if r.get("image_512")] updated, logs = dedup.cluster_duplicates(with_img, "image_512", cfg.dedup.hash_size) by_id = {r["id"]: r for r in without} for r in updated: by_id[r["id"]] = r merged = list(by_id.values()) for r in merged: st = r.get("dedup_status") if st == "duplicate": r["use_in_training"] = False elif st == "canonical": r["use_in_training"] = r.get("use_in_training", True) elif st == "hash_fail": r.setdefault("use_in_training", True) _save_jsonl(idx_path, merged) log_path = cfg.work_dir / "dedup_log.txt" log_path.write_text("\n".join(logs), encoding="utf-8") def stage_taxonomy(cfg: PipelineConfig) -> None: idx_path = cfg.work_dir / "index.jsonl" rows = _load_jsonl(idx_path) map_path = cfg.taxonomy.get("map_file") if cfg.taxonomy else None mp = taxonomy.load_taxonomy_map(Path(map_path) if map_path else None) for row in rows: raw = row.get("category_raw") or "" row["category_normalized"] = taxonomy.normalize_category(str(raw), mp) _save_jsonl(idx_path, rows) def stage_text(cfg: PipelineConfig) -> None: idx_path = cfg.work_dir / "index.jsonl" rows = _load_jsonl(idx_path) tc = cfg.text for row in rows: cap = row.get("caption") or row.get("caption_raw") or "" clean = text_noise.clean_caption(str(cap)) row["caption_clean"] = clean row["caption_noisy"] = text_noise.noisy_caption( clean, seed=tc.seed + hash(str(row["id"])) % (2**20), typo_prob=tc.typo_prob, token_dropout_prob=tc.token_dropout_prob, truncate_tail_prob=tc.truncate_tail_prob, ) _save_jsonl(idx_path, rows) def _enrich_job(args: tuple) -> tuple[str, Optional[str]]: row, cfg_dict = args cfg = cfg_dict # type: ignore from pathlib import Path as P rid = str(row["id"]) img_path = P(row["image_512"]) split = str(row.get("split") or "train").lower() out_sk = P(cfg["train_sketch_dir"] if split == "train" else cfg["test_sketch_dir"]) out_fb = P(cfg["train_fabric_dir"] if split == "train" else cfg["test_fabric_dir"]) stem = str(Path(str(row.get("gt") or rid)).stem) err: Optional[str] = None bgr = cv2.imread(str(img_path), cv2.IMREAD_COLOR) if bgr is None: return rid, "read_fail" _, err = sketch_fabric.process_one_sample( img_path, out_sk, out_fb, stem, int(cfg["fabric_patch"]), ) return stem, err def stage_enrich(cfg: PipelineConfig) -> None: idx_path = cfg.work_dir / "index.jsonl" rows = _load_jsonl(idx_path) # Only enrich TRAIN split. We intentionally do not create test_* modalities. rows = [ r for r in rows if r.get("use_in_training", True) and r.get("image_512") and str(r.get("split") or "train").lower() == "train" ] cfg.train_sketch_dir.mkdir(parents=True, exist_ok=True) cfg.train_fabric_dir.mkdir(parents=True, exist_ok=True) cfg_dict: dict[str, Any] = { "train_sketch_dir": str(cfg.train_sketch_dir), "train_fabric_dir": str(cfg.train_fabric_dir), "fabric_patch": cfg.enrich.fabric_patch, } jobs = [(r, cfg_dict) for r in rows] errs: list[tuple[str, str]] = [] n_workers = _default_workers(cfg) if n_workers <= 1: for job in tqdm(jobs, desc="enrich"): rid, err = _enrich_job(job) if err: errs.append((rid, err)) else: with ProcessPoolExecutor(max_workers=n_workers) as ex: futs = [ex.submit(_enrich_job, job) for job in jobs] for fut in tqdm(as_completed(futs), total=len(futs), desc="enrich"): rid, err = fut.result() if err: errs.append((rid, err)) if errs: p = cfg.work_dir / "enrich_errors.txt" p.write_text("\n".join(f"{a}\t{b}" for a, b in errs), encoding="utf-8") def stage_package(cfg: PipelineConfig) -> Path: idx_path = cfg.work_dir / "index.jsonl" rows = _load_jsonl(idx_path) outs = package.write_equifashion_style_outputs(rows, cfg) return outs["train_json"] def run_stages(cfg: PipelineConfig, stages: list[str]) -> None: order = ["ingest", "standardize", "dedup", "taxonomy", "text", "enrich", "package"] want = set(stages) if "all" in want: want = set(order) for name in order: if name not in want: continue if name == "ingest": stage_ingest(cfg) elif name == "standardize": stage_standardize(cfg) elif name == "dedup": stage_dedup(cfg) elif name == "taxonomy": stage_taxonomy(cfg) elif name == "text": stage_text(cfg) elif name == "enrich": stage_enrich(cfg) elif name == "package": out = stage_package(cfg) print(f"Wrote manifest: {out}") def main_cli() -> None: import argparse ap = argparse.ArgumentParser(description="EquiFashion-style data pipeline") ap.add_argument("--config", type=Path, default=Path("pipeline_config.yaml")) ap.add_argument( "--stage", default="all", help="Comma-separated: ingest,standardize,dedup,taxonomy,text,enrich,package,all", ) ap.add_argument("--init-config", action="store_true", help="Write defaults to --config and exit") args = ap.parse_args() if args.init_config: from .config import write_default_config write_default_config(args.config.resolve()) print(f"Wrote {args.config}") return cfg = load_config(args.config.resolve()) stages = [s.strip() for s in args.stage.split(",") if s.strip()] run_stages(cfg, stages)