"""Build raw_index.jsonl by scanning configured source directories (with captions).""" from __future__ import annotations import json from pathlib import Path from typing import Dict, Optional from .config import PipelineConfig, SourceEntry def _load_caption_map(entry: SourceEntry) -> Dict[str, str]: """ Returns mapping from gt filename (basename) -> caption. """ if not entry.captions_file or entry.captions_format == "none": return {} p = Path(entry.captions_file).expanduser().resolve() if not p.is_file(): return {} fmt = entry.captions_format if fmt == "equifashion_json_list": data = json.loads(p.read_text(encoding="utf-8")) out: Dict[str, str] = {} for r in data or []: gt = str(r.get("gt", "")).strip() cap = str(r.get("caption", "")).strip() if gt: out[Path(gt).name] = cap return out if fmt == "deepfashion_json_dict": data = json.loads(p.read_text(encoding="utf-8")) if isinstance(data, dict): return {Path(k).name: str(v) for k, v in data.items()} return {} if fmt == "facad_jsonl": out: Dict[str, str] = {} with open(p, encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue try: r = json.loads(line) except Exception: continue img = str(r.get("image", "")).strip() txt = str(r.get("text", "")).strip() if img: out[Path(img).name] = txt return out return {} def scan_source(entry: SourceEntry) -> list[dict]: rows: list[dict] = [] exts = {e.lower() for e in entry.extensions} cap_map = _load_caption_map(entry) for dir_str in entry.images_dirs: root = Path(dir_str).expanduser().resolve() if not dir_str.strip() or not root.is_dir(): continue walker = root.rglob("*") if entry.recursive else root.glob("*") for p in walker: if not p.is_file(): continue if p.suffix.lower() not in exts: continue rel = str(p.relative_to(root)).replace("\\", "/") gt = Path(rel).name stem = Path(gt).stem rows.append( { "id": stem, "source_id": entry.id, "source_root": str(root), "image_path": str(p), "rel_path": rel, "gt": gt, "split": entry.split, "caption": cap_map.get(gt, ""), "category_raw": "", } ) return rows def run_ingest(cfg: PipelineConfig) -> Path: cfg.work_dir.mkdir(parents=True, exist_ok=True) out_path = cfg.work_dir / "raw_index.jsonl" rows: list[dict] = [] if cfg.raw_manifest_jsonl: src = Path(cfg.raw_manifest_jsonl).resolve() if src.is_file(): with open(src, encoding="utf-8") as f: for line in f: line = line.strip() if line: rows.append(json.loads(line)) for s in cfg.sources: rows.extend(scan_source(s)) with open(out_path, "w", encoding="utf-8") as f: for r in rows: f.write(json.dumps(r, ensure_ascii=False) + "\n") return out_path