""" 扫描仓库中疑似硬编码坐标/ROI 的脚本。 输出 CSV 到 `tools/coords_report.csv`。 用法: python tools/scan_coords.py 原理: 使用简单正则匹配形如 (123, 456) 或 (100, 200, 300, 400) 的元组/列表。 """ from pathlib import Path import re import csv ROOT = Path(__file__).resolve().parents[1] OUT_CSV = ROOT / "tools" / "coords_report.csv" IGNORE_DIRS = {".git", "__pycache__", ".venv", "venv", "dist", "build"} # 常见坐标/ROI 正则(宽松) PATTERNS = [ re.compile(r"\(\s*\d{1,4}\s*,\s*\d{1,4}\s*\)"), # (123, 456) re.compile(r"\[\s*\d{1,4}\s*,\s*\d{1,4}\s*\]"), # [123, 456] re.compile( r"\(\s*\d{1,4}\s*,\s*\d{1,4}\s*,\s*\d{1,4}\s*,\s*\d{1,4}\s*\)" ), # (x1,y1,x2,y2) re.compile( r"\[\s*\d{1,4}\s*,\s*\d{1,4}\s*,\s*\d{1,4}\s*,\s*\d{1,4}\s*\]" ), # [x1,y1,x2,y2] ] # 额外关键词匹配(ROI 变量名等) KEYWORD_PATTERNS = [ re.compile(p, re.IGNORECASE) for p in [ r"coords?", r"roi", r"rect", r"left_up", r"right_down", r"crop", r"cut_pic", r"x1", r"y1", r"fudai_x", ] ] def scan_file(path: Path): results = [] try: text = path.read_text(encoding="utf-8") except Exception: return results lines = text.splitlines() for i, line in enumerate(lines, start=1): for pat in PATTERNS: for m in pat.finditer(line): # capture some context ctx = line.strip() results.append((str(path.relative_to(ROOT)), i, m.group(0), ctx)) # 额外按关键词收集可能的 ROI 定义行 if any(k.search(line) for k in KEYWORD_PATTERNS): # avoid duplicates: only add if it contains a digit if re.search(r"\d{2,4}", line): results.append( (str(path.relative_to(ROOT)), i, "[keyword_match]", line.strip()) ) return results def main(): rows = [] for f in ROOT.rglob("*"): if f.is_dir(): if f.name in IGNORE_DIRS: continue else: continue if f.suffix in {".py", ".pyx", ".txt", ".md", ".json", ".yaml", ".yml", ".cfg"}: if any(part in IGNORE_DIRS for part in f.parts): continue hits = scan_file(f) rows.extend(hits) OUT_CSV.parent.mkdir(parents=True, exist_ok=True) with OUT_CSV.open("w", encoding="utf-8", newline="") as csvf: writer = csv.writer(csvf) writer.writerow(["file", "line", "match", "context"]) for r in rows: writer.writerow(r) print(f"扫描完成,发现 {len(rows)} 条疑似坐标/ROI 行,输出到: {OUT_CSV}") if __name__ == "__main__": main()