PPIRD / data /unsupervised_train_edge /explore_unsupervised_train.py
haifan-gong's picture
Upload unsupervised_train_edge (patent/product/imagenet1k-edge)
4926be6 verified
Raw
History Blame Contribute Delete
14.8 kB
#!/usr/bin/env python3
"""Explore and extract IDAMA unsupervised_train sharded tar archives.
Data layout (this directory):
patent/shard_XXXX.tar product/shard_XXXX.tar
manifest.jsonl summary.json
_filelists/<cat>/shard_XXXX.txt
Images are UAED edge maps (grayscale JPEG) from:
/data2/gonghaifan/UAED/results/train
Examples:
python explore_unsupervised_train.py summary
python explore_unsupervised_train.py list-tar patent 0 --limit 10
python explore_unsupervised_train.py sample --category patent -n 5 -o /tmp/preview
python explore_unsupervised_train.py extract --category product --shard 0 -o /tmp/shard0
python explore_unsupervised_train.py verify --category patent --shard 0
"""
from __future__ import annotations
import argparse
import json
import random
import sys
import tarfile
from collections import Counter
from pathlib import Path
from typing import Iterator
SCRIPT_DIR = Path(__file__).resolve().parent
DEFAULT_ROOT = SCRIPT_DIR
def load_summary(root: Path) -> dict:
path = root / "summary.json"
if not path.is_file():
raise FileNotFoundError(f"Missing {path}")
return json.loads(path.read_text(encoding="utf-8"))
def tar_path(root: Path, category: str, shard_id: int, gzip: bool = False) -> Path:
ext = ".tar.gz" if gzip else ".tar"
return root / category / f"shard_{shard_id:04d}{ext}"
def iter_manifest(
root: Path,
*,
category: str | None = None,
shard_id: int | None = None,
) -> Iterator[dict]:
path = root / "manifest.jsonl"
if not path.is_file():
raise FileNotFoundError(f"Missing {path}")
with path.open(encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
rec = json.loads(line)
if category is not None and rec.get("category") != category:
continue
if shard_id is not None and rec.get("shard_id") != shard_id:
continue
yield rec
def cmd_summary(args: argparse.Namespace) -> int:
root: Path = args.root
summary = load_summary(root)
counts = summary.get("counts", {})
plan = summary.get("shard_plan", {})
print("=== unsupervised_train 数据集概览 ===\n")
print(f"数据根目录: {root.resolve()}")
print(f"原始来源: {summary.get('source', '?')}")
print(f"打包输出: {summary.get('output', '?')}")
print(f"压缩格式: {'tar.gz' if summary.get('gzip') else 'tar (未 gzip)'}")
print(f"分片总数: {summary.get('num_shards_requested', '?')}")
print(f"全部校验通过: {summary.get('all_shards_verified', '?')}")
print()
print("类别统计:")
total = 0
for cat in ("patent", "product", "other"):
n = counts.get(cat, 0)
if n:
print(f" {cat:8s} {n:>10,} 张 -> {plan.get(cat, 0)} 个 tar 分片")
total += n
print(f" {'合计':8s} {total:>10,} 张")
print()
print("命名规则:")
print(" patent US/CN/EP/... 专利号 + _序号.jpg,如 US10000225_1.jpg")
print(" product product_img_... 产品边缘图")
print()
print("单条 manifest 字段: category, shard_id, tar, member, source")
print()
shards = summary.get("shards", [])
if shards:
print("分片体积 (前 3 / 后 3):")
for rec in shards[:3] + shards[-3:]:
mb = rec.get("tar_bytes", 0) / (1024 * 1024)
print(
f" {rec['tar']:40s} {rec['num_files']:>7,} 文件 {mb:>7.1f} MiB"
)
manifest = root / "manifest.jsonl"
if manifest.is_file():
print(f"\nmanifest.jsonl: {manifest.stat().st_size / (1024**2):.1f} MiB")
return 0
def cmd_list_shards(args: argparse.Namespace) -> int:
summary = load_summary(args.root)
for rec in summary.get("shards", []):
if args.category and rec["category"] != args.category:
continue
mb = rec.get("tar_bytes", 0) / (1024 * 1024)
print(f"{rec['category']:7s} shard {rec['shard_id']:4d} "
f"{rec['num_files']:7,} files {mb:8.1f} MiB {rec['tar']}")
return 0
def cmd_list_tar(args: argparse.Namespace) -> int:
root: Path = args.root
summary = load_summary(root)
gzip = bool(summary.get("gzip"))
path = tar_path(root, args.category, args.shard, gzip=gzip)
if not path.is_file():
print(f"Not found: {path}", file=sys.stderr)
return 1
limit = args.limit
with tarfile.open(path, "r:gz" if gzip else "r:") as tf:
names = tf.getnames()
for i, name in enumerate(names):
if i >= limit:
print(f"... ({len(names) - limit} more members)")
break
print(name)
return 0
def cmd_extract(args: argparse.Namespace) -> int:
root: Path = args.root
summary = load_summary(root)
gzip = bool(summary.get("gzip"))
out: Path = args.output
out.mkdir(parents=True, exist_ok=True)
shards: list[tuple[str, int]] = []
if args.category is not None and args.shard is not None:
shards = [(args.category, args.shard)]
elif args.category is not None:
n = summary.get("shard_plan", {}).get(args.category, 0)
shards = [(args.category, i) for i in range(n)]
else:
for rec in summary.get("shards", []):
shards.append((rec["category"], rec["shard_id"]))
members_filter: set[str] | None = None
if args.members_file:
members_filter = {
line.strip()
for line in Path(args.members_file).read_text(encoding="utf-8").splitlines()
if line.strip()
}
extracted = 0
for category, shard_id in shards:
tar_p = tar_path(root, category, shard_id, gzip=gzip)
if not tar_p.is_file():
print(f"Skip missing: {tar_p}", file=sys.stderr)
continue
shard_out = out if args.flat else out / category
shard_out.mkdir(parents=True, exist_ok=True)
print(f"Extracting {tar_p} -> {shard_out}")
with tarfile.open(tar_p, "r:gz" if gzip else "r:") as tf:
for member in tf.getmembers():
if not member.isfile():
continue
if members_filter is not None and member.name not in members_filter:
continue
dest = shard_out / Path(member.name).name
if dest.exists() and not args.overwrite:
continue
tf.extract(member, path=shard_out)
extracted += 1
if args.max_files and extracted >= args.max_files:
print(f"Reached --max-files {args.max_files}")
return 0
print(f"Done. Extracted {extracted} file(s) under {out.resolve()}")
return 0
def cmd_sample(args: argparse.Namespace) -> int:
root: Path = args.root
records: list[dict] = []
# Reservoir-style: collect matching lines (may be large for full category)
for rec in iter_manifest(root, category=args.category, shard_id=args.shard):
records.append(rec)
if args.pool_size and len(records) >= args.pool_size:
break
if not records:
print("No manifest records matched.", file=sys.stderr)
return 1
if args.seed is not None:
random.seed(args.seed)
n = min(args.num, len(records))
picks = random.sample(records, n) if len(records) > n else records
out: Path = args.output
out.mkdir(parents=True, exist_ok=True)
summary = load_summary(root)
gzip = bool(summary.get("gzip"))
meta_path = out / "samples.jsonl"
with meta_path.open("w", encoding="utf-8") as meta_fh:
for rec in picks:
tar_p = root / rec["tar"]
member = rec["member"]
cat = rec["category"]
dest_dir = out / cat if not args.flat else out
dest_dir.mkdir(parents=True, exist_ok=True)
dest = dest_dir / Path(member).name
with tarfile.open(tar_p, "r:gz" if gzip else "r:") as tf:
fobj = tf.extractfile(member)
if fobj is None:
print(f"Missing member {member} in {tar_p}", file=sys.stderr)
continue
dest.write_bytes(fobj.read())
meta_fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
info = inspect_image(dest)
print(f" {cat}/{member} -> {dest.name} {info}")
print(f"\nWrote {len(picks)} image(s) and {meta_path}")
return 0
def inspect_image(path: Path) -> str:
try:
from PIL import Image
except ImportError:
return f"({path.stat().st_size} bytes, install Pillow for size/mode)"
with Image.open(path) as img:
return f"{img.size[0]}x{img.size[1]} mode={img.mode}"
def cmd_verify(args: argparse.Namespace) -> int:
root: Path = args.root
summary = load_summary(root)
gzip = bool(summary.get("gzip"))
shards = summary.get("shards", [])
if args.category:
shards = [s for s in shards if s["category"] == args.category]
if args.shard is not None:
shards = [s for s in shards if s["shard_id"] == args.shard]
ok = True
for rec in shards:
cat, sid = rec["category"], rec["shard_id"]
tar_p = tar_path(root, cat, sid, gzip=gzip)
expected = rec["num_files"]
if not tar_p.is_file():
print(f"FAIL missing tar: {tar_p}")
ok = False
continue
with tarfile.open(tar_p, "r:gz" if gzip else "r:") as tf:
n = sum(1 for m in tf.getmembers() if m.isfile())
status = "OK" if n == expected else "MISMATCH"
if n != expected:
ok = False
print(f"{status:8s} {rec['tar']:35s} tar={n:,} expected={expected:,}")
if args.check_manifest:
m_count = sum(1 for _ in iter_manifest(root, category=cat, shard_id=sid))
if m_count != expected:
print(f" manifest lines={m_count:,} (expected {expected:,})")
ok = False
return 0 if ok else 1
def cmd_manifest_lookup(args: argparse.Namespace) -> int:
root: Path = args.root
hits = 0
for rec in iter_manifest(root):
member = rec.get("member", "")
source = rec.get("source", "")
if args.member and args.member not in member:
continue
if args.source_substr and args.source_substr not in source:
continue
print(json.dumps(rec, ensure_ascii=False))
hits += 1
if args.limit and hits >= args.limit:
break
if hits == 0:
print("No matches.", file=sys.stderr)
return 1
return 0
def cmd_stats(args: argparse.Namespace) -> int:
"""Quick manifest statistics (streams full manifest)."""
root: Path = args.root
cats: Counter[str] = Counter()
shards: Counter[tuple[str, int]] = Counter()
n = 0
for rec in iter_manifest(root):
cats[rec["category"]] += 1
shards[(rec["category"], rec["shard_id"])] += 1
n += 1
print(f"manifest entries: {n:,}")
for cat, c in cats.most_common():
print(f" {cat}: {c:,}")
if args.verbose:
for (cat, sid), c in sorted(shards.items()):
print(f" {cat} shard {sid:4d}: {c:,}")
return 0
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"--root",
type=Path,
default=DEFAULT_ROOT,
help=f"Dataset root (default: {DEFAULT_ROOT})",
)
sub = parser.add_subparsers(dest="command", required=True)
p_sum = sub.add_parser("summary", help="Print dataset overview from summary.json")
p_sum.set_defaults(func=cmd_summary)
p_ls = sub.add_parser("list-shards", help="List all tar shards")
p_ls.add_argument("--category", choices=("patent", "product"))
p_ls.set_defaults(func=cmd_list_shards)
p_lt = sub.add_parser("list-tar", help="List member names inside one tar")
p_lt.add_argument("category", choices=("patent", "product"))
p_lt.add_argument("shard", type=int)
p_lt.add_argument("--limit", type=int, default=20)
p_lt.set_defaults(func=cmd_list_tar)
p_ex = sub.add_parser("extract", help="Extract tar shard(s) to disk")
p_ex.add_argument("-o", "--output", type=Path, required=True)
p_ex.add_argument("--category", choices=("patent", "product"))
p_ex.add_argument("--shard", type=int, help="Single shard id (use with --category)")
p_ex.add_argument("--flat", action="store_true", help="Do not create category subdirs")
p_ex.add_argument("--overwrite", action="store_true")
p_ex.add_argument("--max-files", type=int, help="Stop after N files")
p_ex.add_argument("--members-file", type=Path, help="Only extract listed basenames")
p_ex.set_defaults(func=cmd_extract)
p_sa = sub.add_parser("sample", help="Randomly extract a few images for inspection")
p_sa.add_argument("-o", "--output", type=Path, required=True)
p_sa.add_argument("--category", choices=("patent", "product"))
p_sa.add_argument("--shard", type=int)
p_sa.add_argument("-n", "--num", type=int, default=8)
p_sa.add_argument("--seed", type=int, default=42)
p_sa.add_argument("--pool-size", type=int, default=200_000,
help="Max manifest lines to scan before sampling")
p_sa.add_argument("--flat", action="store_true")
p_sa.set_defaults(func=cmd_sample)
p_vf = sub.add_parser("verify", help="Verify tar member counts vs summary.json")
p_vf.add_argument("--category", choices=("patent", "product"))
p_vf.add_argument("--shard", type=int)
p_vf.add_argument("--check-manifest", action="store_true")
p_vf.set_defaults(func=cmd_verify)
p_lk = sub.add_parser("lookup", help="Search manifest by member or source substring")
p_lk.add_argument("--member", help="Substring of tar member name")
p_lk.add_argument("--source-substr", help="Substring of original source path")
p_lk.add_argument("--limit", type=int, default=10)
p_lk.set_defaults(func=cmd_manifest_lookup)
p_st = sub.add_parser("stats", help="Count manifest entries by category/shard")
p_st.add_argument("--verbose", action="store_true")
p_st.set_defaults(func=cmd_stats)
return parser
def main() -> int:
parser = build_parser()
args = parser.parse_args()
if not args.root.is_dir():
print(f"Dataset root not found: {args.root}", file=sys.stderr)
return 1
return int(args.func(args))
if __name__ == "__main__":
raise SystemExit(main())