first commit
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
"""Export an Ultralytics YOLO detect model for this Flutter app.
|
||||
|
||||
Class names must be traffic-sign numbers from the Russian traffic rules,
|
||||
for example 3.27 or 1.23. Their order becomes assets/models/labels.txt.
|
||||
|
||||
The app reads float32 NHWC input [1, N, N, 3]. Do not export half or int8.
|
||||
|
||||
python tools/export_signs_model.py best.pt --imgsz 320
|
||||
|
||||
If the installed Ultralytics build no longer accepts format=tflite, the
|
||||
script retries format=litert. Both write a .tflite file.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("weights", type=Path)
|
||||
parser.add_argument("--imgsz", type=int, default=320)
|
||||
args = parser.parse_args()
|
||||
|
||||
from ultralytics import YOLO
|
||||
|
||||
model = YOLO(str(args.weights))
|
||||
try:
|
||||
exported = model.export(format="tflite", imgsz=args.imgsz)
|
||||
except Exception:
|
||||
exported = model.export(format="litert", imgsz=args.imgsz)
|
||||
|
||||
names = model.names
|
||||
ordered = [str(names[index]) for index in range(len(names))]
|
||||
labels_path = Path("assets/models/labels.txt")
|
||||
labels_path.write_text("\n".join(ordered) + "\n", encoding="utf-8")
|
||||
print(f"Exported: {exported}")
|
||||
print(f"Wrote {labels_path} ({len(ordered)} classes)")
|
||||
print("Copy the .tflite file to assets/models/signs.tflite and rebuild.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Download GOST sign diagrams from the drom.ru PDD page into assets/signs.
|
||||
|
||||
The page text is not copied. Only the SVG drawings are saved, and only for
|
||||
sign numbers that exist in the app catalog.
|
||||
|
||||
python tools/fetch_drom_sign_svgs.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from html.parser import HTMLParser
|
||||
from pathlib import Path
|
||||
|
||||
PAGE_URL = "https://www.drom.ru/pdd/pdd/signs/"
|
||||
CATALOG = Path("lib/data/catalog/sign_definitions.dart")
|
||||
ASSET_DIR = Path("assets/signs")
|
||||
INDEX = Path("lib/data/catalog/sign_image_assets.dart")
|
||||
CODE = re.compile(r"\d+\.\d+(?:\.\d+)*")
|
||||
CATALOG_CODE = re.compile(r"_s\(\s*'([^']+)'")
|
||||
|
||||
|
||||
class _SignPage(HTMLParser):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.depth = 0
|
||||
self.capture_title = False
|
||||
self.title: list[str] = []
|
||||
self.images: list[str] = []
|
||||
self.found: list[tuple[list[str], str]] = []
|
||||
|
||||
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||
attributes = {key: value or "" for key, value in attrs}
|
||||
classes = set(attributes.get("class", "").split())
|
||||
if tag == "div":
|
||||
if self.depth == 0 and "pub" in classes:
|
||||
self.depth = 1
|
||||
self.images = []
|
||||
self.title = []
|
||||
self.capture_title = False
|
||||
elif self.depth:
|
||||
self.depth += 1
|
||||
if self.depth and tag == "img":
|
||||
src = attributes.get("src", "")
|
||||
if src.endswith(".svg"):
|
||||
self.images.append(src)
|
||||
if self.depth and tag == "h4":
|
||||
self.capture_title = True
|
||||
self.title = []
|
||||
|
||||
def handle_endtag(self, tag: str) -> None:
|
||||
if tag == "h4":
|
||||
self.capture_title = False
|
||||
if tag == "div" and self.depth:
|
||||
self.depth -= 1
|
||||
if self.depth == 0 and self.images:
|
||||
self.found.append((self.images, "".join(self.title)))
|
||||
|
||||
def handle_data(self, data: str) -> None:
|
||||
if self.capture_title:
|
||||
self.title.append(data)
|
||||
|
||||
|
||||
def catalog_codes() -> list[str]:
|
||||
text = CATALOG.read_text(encoding="utf-8")
|
||||
return CATALOG_CODE.findall(text)
|
||||
|
||||
|
||||
def sign_urls(html: str) -> dict[str, str]:
|
||||
parser = _SignPage()
|
||||
parser.feed(html)
|
||||
chosen: dict[str, str] = {}
|
||||
for images, title in parser.found:
|
||||
codes = CODE.findall(title)
|
||||
if not images or not codes:
|
||||
continue
|
||||
if len(images) == len(codes):
|
||||
pairs = zip(codes, images)
|
||||
else:
|
||||
pairs = ((code, images[0]) for code in codes)
|
||||
for code, src in pairs:
|
||||
chosen.setdefault(code, src)
|
||||
return chosen
|
||||
|
||||
|
||||
def download(url: str, destination: Path) -> None:
|
||||
request = urllib.request.Request(url, headers={"User-Agent": "sign-checker"})
|
||||
with urllib.request.urlopen(request, timeout=60) as response:
|
||||
payload = response.read()
|
||||
if not payload.lstrip().startswith(b"<svg") and b"<svg" not in payload[:200]:
|
||||
raise RuntimeError(f"{url} is not an SVG")
|
||||
destination.write_bytes(payload)
|
||||
|
||||
|
||||
def write_index(codes: list[str]) -> None:
|
||||
lines = [
|
||||
"// Generated by tools/fetch_drom_sign_svgs.py.",
|
||||
"const Set<String> signImageAssets = {",
|
||||
]
|
||||
lines.extend(f" '{code}'," for code in codes)
|
||||
lines.append("};")
|
||||
lines.append("")
|
||||
INDEX.write_text("\n".join(lines), encoding="utf-8")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
request = urllib.request.Request(PAGE_URL, headers={"User-Agent": "sign-checker"})
|
||||
with urllib.request.urlopen(request, timeout=60) as response:
|
||||
html = response.read().decode("cp1251")
|
||||
urls = sign_urls(html)
|
||||
wanted = [code for code in catalog_codes() if not code.startswith("signal.")]
|
||||
for code in list(wanted):
|
||||
if code in urls:
|
||||
continue
|
||||
parent = max(
|
||||
(name for name in urls if code.startswith(name + ".")),
|
||||
key=len,
|
||||
default="",
|
||||
)
|
||||
if parent:
|
||||
urls[code] = urls[parent]
|
||||
ASSET_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
saved: list[str] = []
|
||||
missing: list[str] = []
|
||||
jobs: list[tuple[str, str, Path]] = []
|
||||
for code in wanted:
|
||||
url = urls.get(code)
|
||||
if url is None:
|
||||
missing.append(code)
|
||||
continue
|
||||
jobs.append((code, url, ASSET_DIR / f"{code}.svg"))
|
||||
|
||||
def fetch(job: tuple[str, str, Path]) -> str:
|
||||
code, url, destination = job
|
||||
if destination.is_file() and destination.stat().st_size > 100:
|
||||
return code
|
||||
download(url, destination)
|
||||
return code
|
||||
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
saved = list(pool.map(fetch, jobs))
|
||||
|
||||
write_index(saved)
|
||||
print(f"saved={len(saved)} missing={len(missing)}")
|
||||
if missing:
|
||||
print("missing: " + ", ".join(missing))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,169 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Train a float32 YOLO detector on the prepared Russian sign dataset.
|
||||
|
||||
Expects tools/prepare_hf_dataset.py to have written data/russian-road-signs/data.yaml.
|
||||
Exports signs.tflite into assets/models and rewrites labels.txt from the
|
||||
trained class order.
|
||||
|
||||
python tools/train_signs_model.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"--data",
|
||||
type=Path,
|
||||
default=Path("data/russian-road-signs/data.yaml"),
|
||||
)
|
||||
parser.add_argument("--model", default="yolo11n.pt")
|
||||
parser.add_argument("--imgsz", type=int, default=320)
|
||||
parser.add_argument("--epochs", type=int, default=40)
|
||||
parser.add_argument("--batch", type=int, default=32)
|
||||
parser.add_argument("--device", default="0")
|
||||
parser.add_argument(
|
||||
"--weights",
|
||||
type=Path,
|
||||
default=None,
|
||||
help="Skip training and export this checkpoint to float32 TFLite.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
if args.weights is None and not args.data.is_file():
|
||||
raise SystemExit(f"Missing {args.data}. Run tools/prepare_hf_dataset.py first.")
|
||||
|
||||
from ultralytics import YOLO
|
||||
|
||||
if args.weights is None:
|
||||
model = YOLO(args.model)
|
||||
result = model.train(
|
||||
data=str(args.data),
|
||||
imgsz=args.imgsz,
|
||||
epochs=args.epochs,
|
||||
batch=args.batch,
|
||||
device=args.device,
|
||||
workers=4,
|
||||
patience=8,
|
||||
project="runs/signs",
|
||||
name="yolo11n-russian-signs",
|
||||
exist_ok=True,
|
||||
)
|
||||
weights = Path(result.save_dir) / "weights" / "best.pt"
|
||||
else:
|
||||
weights = args.weights
|
||||
if not weights.is_file():
|
||||
raise SystemExit(f"Missing weights: {weights}")
|
||||
|
||||
trained = YOLO(str(weights))
|
||||
# LiteRT export is Linux/macOS only. On Windows the SavedModel path
|
||||
# still writes a float32 .tflite via onnx2tf.
|
||||
exported = Path(
|
||||
trained.export(format="saved_model", imgsz=args.imgsz, half=False, int8=False)
|
||||
)
|
||||
|
||||
tflite = _find_tflite(exported)
|
||||
destination = Path("assets/models/signs.tflite")
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(tflite, destination)
|
||||
|
||||
names = trained.names
|
||||
ordered = [str(names[index]) for index in range(len(names))]
|
||||
Path("assets/models/labels.txt").write_text(
|
||||
"\n".join(ordered) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
print(f"Copied {tflite} -> {destination}")
|
||||
|
||||
|
||||
def _find_tflite(exported: Path) -> Path:
|
||||
candidates: list[Path] = []
|
||||
if exported.suffix == ".tflite" and exported.is_file():
|
||||
candidates.append(exported)
|
||||
search_root = exported if exported.is_dir() else exported.parent
|
||||
candidates.extend(search_root.rglob("*.tflite"))
|
||||
float32 = [
|
||||
path
|
||||
for path in candidates
|
||||
if "float32" in path.name and "float16" not in path.name and "int8" not in path.name
|
||||
]
|
||||
if float32:
|
||||
return float32[0]
|
||||
plain = [
|
||||
path
|
||||
for path in candidates
|
||||
if "float16" not in path.name and "int8" not in path.name and "quant" not in path.name
|
||||
]
|
||||
if plain:
|
||||
return plain[0]
|
||||
raise SystemExit(f"Export finished but no float32 .tflite file was found near {exported}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user