#!/usr/bin/env python3
"""Convert Pascal VOC XML files to one YOLO txt file per image.

The converter validates image dimensions, classes and normalized box bounds.  It
keeps source file stems, so a split manifest can be applied after conversion.
"""
from __future__ import annotations
import argparse
import xml.etree.ElementTree as ET
from pathlib import Path

CLASSES = ["crazing", "inclusion", "patches", "pitted_surface", "rolled-in_scale", "scratches"]

def convert(xml: Path, out: Path, strict=True) -> int:
    root = ET.parse(xml).getroot()
    size = root.find("size")
    w, h = int(size.findtext("width")), int(size.findtext("height"))
    if w <= 0 or h <= 0:
        raise ValueError(f"invalid image size in {xml}")
    rows = []
    for obj in root.findall("object"):
        name = obj.findtext("name", "").strip()
        if name not in CLASSES:
            if strict: raise ValueError(f"unknown class {name!r} in {xml}")
            continue
        b = obj.find("bndbox")
        xmin, ymin = float(b.findtext("xmin")), float(b.findtext("ymin"))
        xmax, ymax = float(b.findtext("xmax")), float(b.findtext("ymax"))
        if not (0 <= xmin < xmax <= w and 0 <= ymin < ymax <= h):
            raise ValueError(f"out-of-bounds box {(xmin,ymin,xmax,ymax)} in {xml} ({w}x{h})")
        xc, yc = (xmin+xmax)/(2*w), (ymin+ymax)/(2*h)
        bw, bh = (xmax-xmin)/w, (ymax-ymin)/h
        rows.append(f"{CLASSES.index(name)} {xc:.8f} {yc:.8f} {bw:.8f} {bh:.8f}")
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text("\n".join(rows) + ("\n" if rows else ""))
    return len(rows)

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--annotations", type=Path, required=True)
    ap.add_argument("--output", type=Path, required=True)
    args = ap.parse_args()
    n = boxes = 0
    for xml in sorted(args.annotations.glob("*.xml")):
        boxes += convert(xml, args.output / f"{xml.stem}.txt")
        n += 1
    print(f"converted {n} XML files and {boxes} boxes")

if __name__ == "__main__": main()
