"""Batch-clamp four-point detection coordinates; dry-run unless --apply is set. Example: python clip_coordinates.py --apply Default bounds: x in [0,447], y in [0,415] for a 448x416 image. Use --max-x 448 --max-y 416 only if your format uses continuous image-edge coordinates. """ import argparse import hashlib import json import math import os from pathlib import Path import re import shutil import tempfile from datetime import datetime def transform(data, path, max_x, max_y): output = [] changed_rows = changed_values = upper = negative = rows = 0 for number, line in enumerate(data.splitlines(keepends=True), 1): # Preserve a UTF-8 BOM, whitespace, line endings, class ID and confidence. prefix = b'\xef\xbb\xbf' if number == 1 and line.startswith(b'\xef\xbb\xbf') else b'' body = line[len(prefix):] tokens = list(re.finditer(rb'\S+', body)) if not tokens: output.append(line) continue if len(tokens) != 10: raise ValueError(f'{path}:{number}: expected 10 fields, got {len(tokens)}') rows += 1 replacements = [] for i, token in enumerate(tokens[:8]): value = float(token.group()) if not math.isfinite(value): raise ValueError(f'{path}:{number}: non-finite coordinate') limit = max_x if i % 2 == 0 else max_y clipped = min(limit, max(0, value)) if clipped != value: # Retain fixed-point precision of the original coordinate. raw = token.group().decode('ascii') precision = len(raw.split('.')[1]) if '.' in raw and 'e' not in raw.lower() else 6 replacements.append((token.start(), token.end(), f'{clipped:.{precision}f}'.encode('ascii'))) upper += value > limit negative += value < 0 if replacements: changed_rows += 1 changed_values += len(replacements) for start, end, replacement in reversed(replacements): body = body[:start] + replacement + body[end:] output.append(prefix + body) return b''.join(output), dict(rows=rows, changed_rows=changed_rows, changed_values=changed_values, upper_coordinates=upper, negative_coordinates=negative) def atomic_write(path, data): fd, name = tempfile.mkstemp(prefix='.clip-', suffix='.tmp', dir=path.parent) try: with os.fdopen(fd, 'wb') as stream: stream.write(data) stream.flush() os.fsync(stream.fileno()) os.replace(name, path) finally: if os.path.exists(name): os.unlink(name) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--root', type=Path, default=Path(r'D:\寅家验收\Perception')) parser.add_argument('--max-x', type=float, default=447) parser.add_argument('--max-y', type=float, default=415) parser.add_argument('--apply', action='store_true') parser.add_argument('--backup-dir', type=Path) parser.add_argument('--report', type=Path) args = parser.parse_args() if not all(math.isfinite(v) and v > 0 for v in (args.max_x, args.max_y)): parser.error('Bounds must be positive and finite') root = args.root.resolve(strict=True) directories = [root / name for name in ('Vehicle_A', 'Vehicle_B')] if not all(p.is_dir() for p in directories): parser.error('Both Vehicle_A and Vehicle_B directories are required') plan = [] stats = {} # Validate EVERY file before modifying any source file. for directory in directories: totals = dict(files=0, rows=0, changed_files=0, changed_rows=0, changed_values=0, upper_coordinates=0, negative_coordinates=0) paths = [] for parent, _, names in os.walk(directory): paths.extend(Path(parent) / name for name in names if name.lower().endswith('.txt')) for index, path in enumerate(sorted(paths), 1): if index % 2000 == 0: print(f'Checking {directory.name}: {index}/{len(paths)} TXT files', flush=True) resolved = path.resolve(strict=True) if not resolved.is_relative_to(directory.resolve()): raise ValueError(f'File resolves outside intended directory: {path}') original = path.read_bytes() updated, counts = transform(original, path, args.max_x, args.max_y) totals['files'] += 1 for key, value in counts.items(): totals[key] += value if original != updated: totals['changed_files'] += 1 plan.append((path, original, updated, counts)) stats[directory.name] = totals print(f'Checked {directory.name}: {totals}', flush=True) report = dict(mode='apply' if args.apply else 'dry-run', root=str(root), bounds=dict(x=[0, args.max_x], y=[0, args.max_y]), statistics=stats) if args.apply and plan: backup = (args.backup_dir or Path(__file__).resolve().parent / 'coordinate_backups' / datetime.now().strftime('%Y%m%d_%H%M%S_%f')).resolve() if backup.is_relative_to(root): raise ValueError('Backup directory must be outside the source root') backup.mkdir(parents=True, exist_ok=False) # Back up ALL affected files before the first overwrite. for path, original, _, _ in plan: if path.read_bytes() != original: raise RuntimeError(f'Source changed during preflight: {path}') dest = backup / path.relative_to(root) dest.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(path, dest) if dest.read_bytes() != original: raise RuntimeError(f'Backup verification failed: {path}') print(f'Backed up {len(plan)} files to {backup}', flush=True) report['backup_directory'] = str(backup) report['modified_files'] = [] for path, original, updated, counts in plan: if path.read_bytes() != original: raise RuntimeError(f'Source changed before overwrite: {path}') atomic_write(path, updated) actual = path.read_bytes() if actual != updated or transform(actual, path, args.max_x, args.max_y)[1]['changed_values']: raise RuntimeError(f'Post-write verification failed: {path}') report['modified_files'].append(dict(path=str(path), **counts, original_sha256=hashlib.sha256(original).hexdigest(), clipped_sha256=hashlib.sha256(updated).hexdigest())) report['verification'] = 'All modified files match expected bytes and have in-range coordinates.' if args.report: args.report.parent.mkdir(parents=True, exist_ok=True) args.report.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8') print(json.dumps({k: v for k, v in report.items() if k != 'modified_files'}, ensure_ascii=False, indent=2)) if __name__ == '__main__': main()