import json import re import shutil from datetime import datetime from pathlib import Path ROOT = Path("/mnt/nas/zhangyiming/database/rlbench/train") JSON_DIR = ROOT / "json" BACKUP_DIR = ROOT / "json_bak_pic_num" FRONT_RE = re.compile(r"front_(\d+)\.png$") def is_training_json(path: Path) -> bool: if path.name.endswith("_statistics.json"): return False if path.name == "train_statistics.json": return False return path.suffix == ".json" def get_pic_num(front_pic: str, cache: dict[Path, int]) -> int: pic_path = Path(front_pic) episode_dir = pic_path.parent if episode_dir in cache: return cache[episode_dir] max_idx = None for image_path in episode_dir.glob("front_*.png"): match = FRONT_RE.match(image_path.name) if match: idx = int(match.group(1)) max_idx = idx if max_idx is None else max(max_idx, idx) if max_idx is None: raise FileNotFoundError(f"No front_*.png images found in {episode_dir}") cache[episode_dir] = max_idx return max_idx def main() -> None: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") backup_dir = BACKUP_DIR / timestamp backup_dir.mkdir(parents=True, exist_ok=False) image_count_cache = {} processed = {} for json_path in sorted(JSON_DIR.glob("*.json")): if not is_training_json(json_path): continue backup_path = backup_dir / json_path.name shutil.copy2(json_path, backup_path) with json_path.open("r", encoding="utf-8") as f: records = json.load(f) for record in records: if "front_pic" not in record: raise KeyError(f"{json_path} has a record without front_pic") record["pic_num"] = get_pic_num(record["front_pic"], image_count_cache) tmp_path = json_path.with_suffix(".json.tmp") with tmp_path.open("w", encoding="utf-8") as f: json.dump(records, f, ensure_ascii=False, indent=2) tmp_path.replace(json_path) processed[json_path.name] = len(records) summary_path = backup_dir / "pic_num_update_summary.json" with summary_path.open("w", encoding="utf-8") as f: json.dump( { "backup_dir": str(backup_dir), "processed": processed, }, f, ensure_ascii=False, indent=2, ) print(json.dumps({"backup_dir": str(backup_dir), "processed": processed}, ensure_ascii=False, indent=2)) if __name__ == "__main__": main()