low-high-reference / scripts /training /prepare_ditto_pairs.py
Ouzhang's picture
Upload scripts/training/prepare_ditto_pairs.py with huggingface_hub
bc4301b verified
Raw
History Blame Contribute Delete
15.7 kB
from __future__ import annotations
import argparse
import csv
import json
import re
import shutil
import subprocess
from collections import Counter
from pathlib import Path
from typing import Any
DEFAULT_CSVS = [
"global.csv",
"global+local.csv",
"global_freeform3.csv",
"global_style.csv",
"local.csv",
"local_replace.csv",
"sim2real.csv",
]
DEFAULT_EXCLUDE_KEYWORDS = [
"anime",
"cartoon",
"comic",
"manga",
"ghibli",
"pixar",
"disney",
"illustration",
"japanese cartoon",
"cel-shaded",
"cel shaded",
"silhouette",
]
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Prepare Ditto low/high/prompt pairs and optionally materialize a training-ready pair-dir."
)
parser.add_argument("--dataset-root", type=Path, default=Path("datas/Ditto-1M"))
parser.add_argument("--output", type=Path, required=True, help="Output JSONL manifest path.")
parser.add_argument("--summary-output", type=Path, default=None)
parser.add_argument("--csv-names", nargs="*", default=DEFAULT_CSVS)
parser.add_argument("--task-prefixes", nargs="*", default=[])
parser.add_argument("--exclude-keywords", nargs="*", default=DEFAULT_EXCLUDE_KEYWORDS)
parser.add_argument("--include-existing-only", action="store_true")
parser.add_argument("--dedupe-by", choices=["high", "low_high_prompt", "none"], default="high")
parser.add_argument("--limit", type=int, default=0)
parser.add_argument("--offset", type=int, default=0)
parser.add_argument("--sample-id-prefix", default="ditto_pair")
parser.add_argument("--materialize-pair-dir", type=Path, default=None)
parser.add_argument("--materialize-low", action="store_true")
parser.add_argument("--materialize-high", action="store_true")
parser.add_argument("--materialize-reference", action="store_true")
parser.add_argument("--overwrite-existing", action="store_true")
parser.add_argument("--strict-materialize", action="store_true")
parser.add_argument("--materialize-limit", type=int, default=0)
parser.add_argument("--skip-copy-if-present", action="store_true")
parser.add_argument("--compact-pair-json", action="store_true", help="Write pair.json in compact low/high/prompt format.")
return parser.parse_args()
def _csv_task_family(csv_name: str, high_rel: str) -> str:
if csv_name == "sim2real.csv":
return "sim2real"
if high_rel.startswith("global_freeform1/"):
return "global_freeform1"
if high_rel.startswith("global_freeform2/"):
return "global_freeform2"
if high_rel.startswith("global_freeform3/"):
return "global_freeform3"
if high_rel.startswith("global_style1/") or high_rel.startswith("global_style2/"):
return "global_style"
if high_rel.startswith("local/"):
return "local"
return csv_name.replace(".csv", "")
def _dedupe_key(kind: str, row: dict[str, str]) -> str:
if kind == "none":
return ""
if kind == "high":
return str(row.get("video", "") or "")
return "||".join(
[
str(row.get("vace_video", "") or ""),
str(row.get("video", "") or ""),
str(row.get("prompt", "") or ""),
]
)
def _matches_prefixes(high_rel: str, prefixes: list[str]) -> bool:
if not prefixes:
return True
return any(high_rel.startswith(prefix) for prefix in prefixes)
def _contains_excluded_keyword(prompt: str, keywords: list[str]) -> bool:
prompt_lower = prompt.lower()
return any(keyword.lower() in prompt_lower for keyword in keywords)
def _record_from_row(
dataset_root: Path,
csv_name: str,
row_index: int,
row: dict[str, str],
) -> dict[str, Any]:
high_rel = str(row.get("video", "") or "").strip().lstrip("./")
low_rel = str(row.get("vace_video", "") or "").strip().lstrip("./")
prompt = str(row.get("prompt", "") or "").strip()
reference_rel = str(row.get("vace_reference_image", "") or "").strip().lstrip("./")
low_path = dataset_root / "videos" / low_rel
high_path = dataset_root / "videos" / high_rel
reference_path = dataset_root / "videos" / reference_rel if reference_rel else None
task_family = _csv_task_family(csv_name, high_rel)
source_bucket = low_rel.split("/", 1)[0] if "/" in low_rel else low_rel
target_bucket = high_rel.split("/", 1)[0] if "/" in high_rel else high_rel
return {
"source_csv": csv_name,
"row_index": row_index,
"task_family": task_family,
"source_bucket": source_bucket,
"target_bucket": target_bucket,
"prompt": prompt,
"low_video_relpath": low_rel,
"high_video_relpath": high_rel,
"reference_relpath": reference_rel,
"low_video_path": str(low_path),
"high_video_path": str(high_path),
"reference_path": str(reference_path) if reference_path is not None else "",
"low_exists": low_path.exists(),
"high_exists": high_path.exists(),
"reference_exists": reference_path.exists() if reference_path is not None else False,
}
def _contiguous_parts(directory: Path, prefix: str) -> list[Path]:
parts: list[tuple[int, Path]] = []
for path in directory.glob(f"{prefix}.*"):
match = re.search(r"\.(\d+)$", path.name)
if match:
parts.append((int(match.group(1)), path))
parts.sort(key=lambda item: item[0])
contiguous: list[Path] = []
expected = 1
for index, path in parts:
if index != expected:
break
contiguous.append(path)
expected += 1
return contiguous
def _archive_parts_for_bucket(dataset_root: Path, bucket: str) -> list[Path]:
bucket_dir = dataset_root / "videos" / bucket
prefix = f"{bucket}.tar.gz"
return _contiguous_parts(bucket_dir, prefix)
def _copy_if_present(src: Path, dst: Path, overwrite: bool) -> bool:
if not src.exists():
return False
if dst.exists() and not overwrite:
return True
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dst)
return True
def _symlink_or_copy(src: Path, dst: Path, overwrite: bool) -> bool:
if not src.exists():
return False
if dst.exists() or dst.is_symlink():
if not overwrite:
return True
dst.unlink()
dst.parent.mkdir(parents=True, exist_ok=True)
try:
dst.symlink_to(src)
except OSError:
shutil.copy2(src, dst)
return True
def _extract_from_archive(parts: list[Path], relpath: str, dst: Path) -> bool:
if not parts:
return False
dst.parent.mkdir(parents=True, exist_ok=True)
joined = " ".join(str(path) for path in parts)
rel = relpath.lstrip("./")
cmd = f"cat {joined} | tar -xzf - -O ./{rel} > {shlex_quote(str(dst))}"
completed = subprocess.run(cmd, shell=True, executable="/bin/bash")
if completed.returncode != 0:
if dst.exists():
dst.unlink()
return False
return True
def shlex_quote(text: str) -> str:
import shlex
return shlex.quote(text)
def _materialize_one(
dataset_root: Path,
relpath: str,
out_path: Path,
*,
bucket_override: str | None = None,
overwrite: bool,
skip_copy_if_present: bool,
) -> tuple[bool, str]:
rel = relpath.strip().lstrip("./")
if not rel:
return False, "missing_relpath"
if out_path.exists() and not overwrite:
return True, "already_exists"
direct_src = dataset_root / "videos" / rel
if direct_src.exists():
if skip_copy_if_present:
return (_symlink_or_copy(direct_src, out_path, overwrite), "linked_direct")
return (_copy_if_present(direct_src, out_path, overwrite), "copied_direct")
bucket = bucket_override or (rel.split("/", 1)[0] if "/" in rel else "")
if not bucket:
return False, "missing_bucket"
parts = _archive_parts_for_bucket(dataset_root, bucket)
ok = _extract_from_archive(parts, rel, out_path)
return ok, "extracted_archive" if ok else f"extract_failed:{bucket}"
def _materialize_pair_dir(args: argparse.Namespace, records: list[dict[str, Any]]) -> dict[str, Any]:
pair_dir = args.materialize_pair_dir
assert pair_dir is not None
pair_dir.mkdir(parents=True, exist_ok=True)
low_dir = pair_dir / "low"
high_dir = pair_dir / "high"
ref_dir = pair_dir / "reference"
low_dir.mkdir(parents=True, exist_ok=True)
high_dir.mkdir(parents=True, exist_ok=True)
if args.materialize_reference:
ref_dir.mkdir(parents=True, exist_ok=True)
selected = records[: args.materialize_limit] if args.materialize_limit > 0 else list(records)
manifest: list[dict[str, Any]] = []
compact_pairs: list[dict[str, Any]] = []
skipped = Counter()
for record in selected:
low_rel = str(record["low_video_relpath"])
high_rel = str(record["high_video_relpath"])
ref_rel = str(record.get("reference_relpath", "") or "")
low_name = Path(low_rel).name
high_path = Path(high_rel)
high_name = str(high_path) if len(high_path.parts) > 1 else high_path.name
ref_name = Path(ref_rel).name if ref_rel else ""
low_ok = True
high_ok = True
ref_ok = True
if args.materialize_low:
low_ok, low_reason = _materialize_one(
args.dataset_root,
low_rel,
low_dir / low_name,
bucket_override="source",
overwrite=args.overwrite_existing,
skip_copy_if_present=args.skip_copy_if_present,
)
if not low_ok:
skipped[f"low::{low_reason}"] += 1
if args.materialize_high:
high_ok, high_reason = _materialize_one(
args.dataset_root,
high_rel,
high_dir / high_name,
overwrite=args.overwrite_existing,
skip_copy_if_present=args.skip_copy_if_present,
)
if not high_ok:
skipped[f"high::{high_reason}"] += 1
if args.materialize_reference and ref_rel:
ref_ok, ref_reason = _materialize_one(
args.dataset_root,
ref_rel,
ref_dir / ref_name,
overwrite=args.overwrite_existing,
skip_copy_if_present=args.skip_copy_if_present,
)
if not ref_ok:
skipped[f"ref::{ref_reason}"] += 1
if args.strict_materialize and not (low_ok and high_ok and ref_ok):
continue
manifest.append(
{
"sample_id": record["sample_id"],
"row_index": record["row_index"],
"source_csv": record["source_csv"],
"task_family": record["task_family"],
"prompt": record["prompt"],
"low_rel": low_rel,
"high_rel": high_rel,
"ref_rel": ref_rel,
"low_video_path": record["low_video_path"],
"high_video_path": record["high_video_path"],
"reference_path": record["reference_path"],
"low_materialized": str((low_dir / low_name)) if args.materialize_low and low_ok else "",
"high_materialized": str((high_dir / high_name)) if args.materialize_high and high_ok else "",
"reference_materialized": str((ref_dir / ref_name)) if args.materialize_reference and ref_rel and ref_ok else "",
}
)
compact_pairs.append(
{
"sample_id": record["sample_id"],
"prompt": record["prompt"],
"low": f"low/{low_name}" if args.materialize_low and low_ok else "",
"high": f"high/{high_name}" if args.materialize_high and high_ok else "",
"low_rel": low_rel,
"high_rel": high_rel,
}
)
manifest_path = pair_dir / "manifest.json"
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
pair_json_path = pair_dir / "pair.json"
pair_json_path.write_text(json.dumps(compact_pairs, ensure_ascii=False, indent=2), encoding="utf-8")
return {
"pair_dir": str(pair_dir),
"manifest_path": str(manifest_path),
"pair_json_path": str(pair_json_path),
"materialized_count": len(manifest),
"materialize_skipped": dict(skipped),
}
def main() -> None:
args = parse_args()
csv_dir = args.dataset_root / "csvs_for_DiffSynth"
records: list[dict[str, Any]] = []
seen: set[str] = set()
skipped = Counter()
for csv_name in args.csv_names:
csv_path = csv_dir / csv_name
if not csv_path.exists():
skipped["missing_csv"] += 1
continue
with csv_path.open("r", encoding="utf-8", newline="") as f:
reader = csv.DictReader(f)
for row_index, row in enumerate(reader):
high_rel = str(row.get("video", "") or "").strip()
prompt = str(row.get("prompt", "") or "").strip()
if not high_rel:
skipped["missing_high_rel"] += 1
continue
if not _matches_prefixes(high_rel, args.task_prefixes):
skipped["prefix_filtered"] += 1
continue
if args.exclude_keywords and _contains_excluded_keyword(prompt, args.exclude_keywords):
skipped["keyword_filtered"] += 1
continue
key = _dedupe_key(args.dedupe_by, row)
if key and key in seen:
skipped["deduped"] += 1
continue
record = _record_from_row(args.dataset_root, csv_name, row_index, row)
if args.include_existing_only and not (record["low_exists"] and record["high_exists"]):
skipped["missing_files"] += 1
continue
if key:
seen.add(key)
records.append(record)
if args.offset > 0:
records = records[args.offset :]
if args.limit > 0:
records = records[: args.limit]
for idx, record in enumerate(records, start=1):
record["sample_id"] = f"{args.sample_id_prefix}_{idx:06d}"
args.output.parent.mkdir(parents=True, exist_ok=True)
with args.output.open("w", encoding="utf-8") as f:
for record in records:
f.write(json.dumps(record, ensure_ascii=False) + "\n")
summary: dict[str, Any] = {
"count": len(records),
"dataset_root": str(args.dataset_root),
"output": str(args.output),
"csv_names": args.csv_names,
"task_prefixes": args.task_prefixes,
"include_existing_only": args.include_existing_only,
"dedupe_by": args.dedupe_by,
"task_family_counts": dict(Counter(str(record["task_family"]) for record in records)),
"target_bucket_counts": dict(Counter(str(record["target_bucket"]) for record in records)),
"skipped": dict(skipped),
}
if args.materialize_pair_dir is not None:
materialize_summary = _materialize_pair_dir(args, records)
summary["materialize"] = materialize_summary
summary_path = args.summary_output or args.output.with_suffix(".summary.json")
summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps(summary, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()