170 lines
5.2 KiB
Python
170 lines
5.2 KiB
Python
"""Download Dognellaf/russian-road-signs and split it by video clip.
|
|
|
|
Frames from one clip stay in the same split. A random image split would put
|
|
neighboring frames into both train and val and inflate the metric.
|
|
|
|
Unlabeled videos are not downloaded. Images are not copied: train.txt and
|
|
val.txt point at the files already on disk.
|
|
|
|
python tools/prepare_hf_dataset.py
|
|
python tools/prepare_hf_dataset.py --split-only
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import re
|
|
from pathlib import Path
|
|
|
|
REPO_ID = "Dognellaf/russian-road-signs"
|
|
VAL_PERCENT = 15
|
|
|
|
_FRAME = re.compile(r"__frame-.*$", re.IGNORECASE)
|
|
_OUTPUT = re.compile(r"-output$", re.IGNORECASE)
|
|
_TAIL_INDEX = re.compile(r"__\d+_?$")
|
|
|
|
|
|
def clip_id(filename: str) -> str:
|
|
stem = Path(filename).stem
|
|
stem = _FRAME.sub("", stem)
|
|
stem = _OUTPUT.sub("", stem)
|
|
stem = _TAIL_INDEX.sub("", stem)
|
|
stem = stem.strip("_-")
|
|
return stem or Path(filename).stem
|
|
|
|
|
|
def _label_path(image: Path, root: Path) -> Path:
|
|
relative = image.relative_to(root)
|
|
return root / "labels" / relative.relative_to("images").with_suffix(".txt")
|
|
|
|
|
|
def collect_images(root: Path) -> list[Path]:
|
|
images_root = root / "images"
|
|
chosen: dict[str, Path] = {}
|
|
for image in images_root.rglob("*.jpg"):
|
|
label = _label_path(image, root)
|
|
if not label.is_file():
|
|
continue
|
|
current = chosen.get(image.name)
|
|
if current is None or len(image.parts) < len(current.parts):
|
|
chosen[image.name] = image
|
|
return sorted(chosen.values())
|
|
|
|
|
|
def write_splits(root: Path, val_percent: int = VAL_PERCENT) -> tuple[int, int]:
|
|
images = collect_images(root)
|
|
if not images:
|
|
raise SystemExit(f"No labeled images under {root / 'images'}")
|
|
|
|
clips: dict[str, list[Path]] = {}
|
|
for image in images:
|
|
clips.setdefault(clip_id(image.name), []).append(image)
|
|
|
|
train: list[Path] = []
|
|
val: list[Path] = []
|
|
for clip, frames in clips.items():
|
|
bucket = int(hashlib.sha256(clip.encode("utf-8")).hexdigest(), 16) % 100
|
|
target = val if bucket < val_percent else train
|
|
target.extend(frames)
|
|
|
|
split_dir = root / "splits"
|
|
split_dir.mkdir(parents=True, exist_ok=True)
|
|
_write_list(split_dir / "train.txt", root, train)
|
|
_write_list(split_dir / "val.txt", root, val)
|
|
_write_data_yaml(root)
|
|
_copy_labels(root)
|
|
print(
|
|
f"clips={len(clips)} train_images={len(train)} val_images={len(val)} "
|
|
f"root={root}"
|
|
)
|
|
return len(train), len(val)
|
|
|
|
|
|
def _write_list(path: Path, root: Path, images: list[Path]) -> None:
|
|
# Absolute paths. Ultralytics reads each line as-is and only turns a
|
|
# leading "./" into a path next to the txt file. A relative "images/..."
|
|
# line is then resolved from the process cwd, so the matching label is
|
|
# never found on Windows.
|
|
root = root.resolve()
|
|
lines = []
|
|
for image in images:
|
|
resolved = image.resolve()
|
|
resolved.relative_to(root)
|
|
lines.append(resolved.as_posix())
|
|
path.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8")
|
|
|
|
|
|
def _class_names(root: Path) -> list[str]:
|
|
classes = root / "classes.txt"
|
|
names = [line.strip() for line in classes.read_text(encoding="utf-8").splitlines()]
|
|
names = [name for name in names if name]
|
|
if not names:
|
|
raise SystemExit(f"{classes} is empty")
|
|
return names
|
|
|
|
|
|
def _write_data_yaml(root: Path) -> None:
|
|
names = _class_names(root)
|
|
lines = [
|
|
f"path: {root.as_posix()}",
|
|
"train: splits/train.txt",
|
|
"val: splits/val.txt",
|
|
"names:",
|
|
]
|
|
lines.extend(
|
|
f' {index}: "{name}"' for index, name in enumerate(names)
|
|
)
|
|
(root / "data.yaml").write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
|
|
|
|
def _copy_labels(root: Path) -> None:
|
|
destination = Path("assets/models/labels.txt")
|
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
destination.write_text("\n".join(_class_names(root)) + "\n", encoding="utf-8")
|
|
|
|
|
|
def download(root: Path) -> None:
|
|
from huggingface_hub import snapshot_download
|
|
|
|
snapshot_download(
|
|
repo_id=REPO_ID,
|
|
repo_type="dataset",
|
|
local_dir=str(root),
|
|
max_workers=32,
|
|
allow_patterns=[
|
|
"images/**",
|
|
"labels/**",
|
|
"classes.txt",
|
|
"LICENSE",
|
|
"README.md",
|
|
],
|
|
ignore_patterns=["unlabeled/**"],
|
|
)
|
|
|
|
|
|
def _self_test() -> None:
|
|
assert clip_id("00030002__2_-output__frame-0-00-27.67.jpg") == "00030002"
|
|
assert clip_id("00030002__15_-output__frame-0-01-10.67.jpg") == "00030002"
|
|
assert clip_id("0_inter-n-13__inter-n-13__10_.jpg") == "0_inter-n-13__inter-n-13"
|
|
assert clip_id("0_inter-n-13__inter-n-13__2_.jpg") == "0_inter-n-13__inter-n-13"
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--root", type=Path, default=Path("data/russian-road-signs"))
|
|
parser.add_argument("--split-only", action="store_true")
|
|
parser.add_argument("--self-test", action="store_true")
|
|
args = parser.parse_args()
|
|
if args.self_test:
|
|
_self_test()
|
|
print("clip id checks passed")
|
|
return
|
|
if not args.split_only:
|
|
download(args.root)
|
|
write_splits(args.root)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|