MacroIC commited on
Commit
0bb52c6
·
verified ·
1 Parent(s): 2abd79a

Upload clip_coordinates.py

Browse files
Files changed (1) hide show
  1. clip_coordinates.py +150 -0
clip_coordinates.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Batch-clamp four-point detection coordinates; dry-run unless --apply is set.
2
+
3
+ Example:
4
+ python clip_coordinates.py --apply
5
+ Default bounds: x in [0,447], y in [0,415] for a 448x416 image.
6
+ Use --max-x 448 --max-y 416 only if your format uses continuous image-edge coordinates.
7
+ """
8
+ import argparse
9
+ import hashlib
10
+ import json
11
+ import math
12
+ import os
13
+ from pathlib import Path
14
+ import re
15
+ import shutil
16
+ import tempfile
17
+ from datetime import datetime
18
+
19
+
20
+ def transform(data, path, max_x, max_y):
21
+ output = []
22
+ changed_rows = changed_values = upper = negative = rows = 0
23
+ for number, line in enumerate(data.splitlines(keepends=True), 1):
24
+ # Preserve a UTF-8 BOM, whitespace, line endings, class ID and confidence.
25
+ prefix = b'\xef\xbb\xbf' if number == 1 and line.startswith(b'\xef\xbb\xbf') else b''
26
+ body = line[len(prefix):]
27
+ tokens = list(re.finditer(rb'\S+', body))
28
+ if not tokens:
29
+ output.append(line)
30
+ continue
31
+ if len(tokens) != 10:
32
+ raise ValueError(f'{path}:{number}: expected 10 fields, got {len(tokens)}')
33
+ rows += 1
34
+ replacements = []
35
+ for i, token in enumerate(tokens[:8]):
36
+ value = float(token.group())
37
+ if not math.isfinite(value):
38
+ raise ValueError(f'{path}:{number}: non-finite coordinate')
39
+ limit = max_x if i % 2 == 0 else max_y
40
+ clipped = min(limit, max(0, value))
41
+ if clipped != value:
42
+ # Retain fixed-point precision of the original coordinate.
43
+ raw = token.group().decode('ascii')
44
+ precision = len(raw.split('.')[1]) if '.' in raw and 'e' not in raw.lower() else 6
45
+ replacements.append((token.start(), token.end(), f'{clipped:.{precision}f}'.encode('ascii')))
46
+ upper += value > limit
47
+ negative += value < 0
48
+ if replacements:
49
+ changed_rows += 1
50
+ changed_values += len(replacements)
51
+ for start, end, replacement in reversed(replacements):
52
+ body = body[:start] + replacement + body[end:]
53
+ output.append(prefix + body)
54
+ return b''.join(output), dict(rows=rows, changed_rows=changed_rows,
55
+ changed_values=changed_values,
56
+ upper_coordinates=upper, negative_coordinates=negative)
57
+
58
+
59
+ def atomic_write(path, data):
60
+ fd, name = tempfile.mkstemp(prefix='.clip-', suffix='.tmp', dir=path.parent)
61
+ try:
62
+ with os.fdopen(fd, 'wb') as stream:
63
+ stream.write(data)
64
+ stream.flush()
65
+ os.fsync(stream.fileno())
66
+ os.replace(name, path)
67
+ finally:
68
+ if os.path.exists(name):
69
+ os.unlink(name)
70
+
71
+
72
+ def main():
73
+ parser = argparse.ArgumentParser(description=__doc__)
74
+ parser.add_argument('--root', type=Path, default=Path(r'D:\寅家验收\Perception'))
75
+ parser.add_argument('--max-x', type=float, default=447)
76
+ parser.add_argument('--max-y', type=float, default=415)
77
+ parser.add_argument('--apply', action='store_true')
78
+ parser.add_argument('--backup-dir', type=Path)
79
+ parser.add_argument('--report', type=Path)
80
+ args = parser.parse_args()
81
+ if not all(math.isfinite(v) and v > 0 for v in (args.max_x, args.max_y)):
82
+ parser.error('Bounds must be positive and finite')
83
+ root = args.root.resolve(strict=True)
84
+ directories = [root / name for name in ('Vehicle_A', 'Vehicle_B')]
85
+ if not all(p.is_dir() for p in directories):
86
+ parser.error('Both Vehicle_A and Vehicle_B directories are required')
87
+ plan = []
88
+ stats = {}
89
+ # Validate EVERY file before modifying any source file.
90
+ for directory in directories:
91
+ totals = dict(files=0, rows=0, changed_files=0, changed_rows=0,
92
+ changed_values=0, upper_coordinates=0, negative_coordinates=0)
93
+ paths = []
94
+ for parent, _, names in os.walk(directory):
95
+ paths.extend(Path(parent) / name for name in names if name.lower().endswith('.txt'))
96
+ for index, path in enumerate(sorted(paths), 1):
97
+ if index % 2000 == 0:
98
+ print(f'Checking {directory.name}: {index}/{len(paths)} TXT files', flush=True)
99
+ resolved = path.resolve(strict=True)
100
+ if not resolved.is_relative_to(directory.resolve()):
101
+ raise ValueError(f'File resolves outside intended directory: {path}')
102
+ original = path.read_bytes()
103
+ updated, counts = transform(original, path, args.max_x, args.max_y)
104
+ totals['files'] += 1
105
+ for key, value in counts.items():
106
+ totals[key] += value
107
+ if original != updated:
108
+ totals['changed_files'] += 1
109
+ plan.append((path, original, updated, counts))
110
+ stats[directory.name] = totals
111
+ print(f'Checked {directory.name}: {totals}', flush=True)
112
+ report = dict(mode='apply' if args.apply else 'dry-run', root=str(root),
113
+ bounds=dict(x=[0, args.max_x], y=[0, args.max_y]), statistics=stats)
114
+ if args.apply and plan:
115
+ backup = (args.backup_dir or Path(__file__).resolve().parent / 'coordinate_backups' /
116
+ datetime.now().strftime('%Y%m%d_%H%M%S_%f')).resolve()
117
+ if backup.is_relative_to(root):
118
+ raise ValueError('Backup directory must be outside the source root')
119
+ backup.mkdir(parents=True, exist_ok=False)
120
+ # Back up ALL affected files before the first overwrite.
121
+ for path, original, _, _ in plan:
122
+ if path.read_bytes() != original:
123
+ raise RuntimeError(f'Source changed during preflight: {path}')
124
+ dest = backup / path.relative_to(root)
125
+ dest.parent.mkdir(parents=True, exist_ok=True)
126
+ shutil.copy2(path, dest)
127
+ if dest.read_bytes() != original:
128
+ raise RuntimeError(f'Backup verification failed: {path}')
129
+ print(f'Backed up {len(plan)} files to {backup}', flush=True)
130
+ report['backup_directory'] = str(backup)
131
+ report['modified_files'] = []
132
+ for path, original, updated, counts in plan:
133
+ if path.read_bytes() != original:
134
+ raise RuntimeError(f'Source changed before overwrite: {path}')
135
+ atomic_write(path, updated)
136
+ actual = path.read_bytes()
137
+ if actual != updated or transform(actual, path, args.max_x, args.max_y)[1]['changed_values']:
138
+ raise RuntimeError(f'Post-write verification failed: {path}')
139
+ report['modified_files'].append(dict(path=str(path), **counts,
140
+ original_sha256=hashlib.sha256(original).hexdigest(),
141
+ clipped_sha256=hashlib.sha256(updated).hexdigest()))
142
+ report['verification'] = 'All modified files match expected bytes and have in-range coordinates.'
143
+ if args.report:
144
+ args.report.parent.mkdir(parents=True, exist_ok=True)
145
+ args.report.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
146
+ print(json.dumps({k: v for k, v in report.items() if k != 'modified_files'}, ensure_ascii=False, indent=2))
147
+
148
+
149
+ if __name__ == '__main__':
150
+ main()