import sys import shutil from pathlib import Path def auto_fix_indentation(path: Path, indent_size: int = 4) -> int: """Naively fix lines whose indentation is not deeper than a preceding colon line. Heuristic: - When a line endswith ':' (non-blank, non-comment), the next non-empty line that is not an 'else/elif/except/finally' should be indented strictly more. - If it is not, increase its leading spaces to (prev_indent + indent_size). This is a best-effort fixer for common mistakes that cause IndentationError. """ lines = path.read_text(encoding="utf-8").splitlines() fixes = 0 def leading_spaces(s: str) -> int: return len(s) - len(s.lstrip(" ")) for i in range(len(lines) - 1): cur = lines[i] nxt = lines[i + 1] cur_strip = cur.strip() nxt_strip = nxt.strip() if not cur_strip: continue if cur_strip.startswith("#"): continue if not cur_strip.endswith(":"): continue # skip multi-colon lines like dicts etc. Simple heuristic: has space before colon. # We still treat most control statements/defs. # Skip the next line if it's empty or a comment. if not nxt_strip or nxt_strip.startswith("#"): continue # If next line is a peer control keyword, don't force indent. if nxt_strip.startswith(("else:", "elif ", "except", "finally:")): continue cur_indent = leading_spaces(cur) nxt_indent = leading_spaces(nxt) expected = cur_indent + indent_size if nxt_indent <= cur_indent: lines[i + 1] = " " * expected + nxt_strip fixes += 1 if fixes: path.write_text("\n".join(lines), encoding="utf-8") return fixes def main(): target = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("douyin_fudai.py") if not target.exists(): print(f"File not found: {target}") sys.exit(1) backup = target.with_suffix(target.suffix + ".bak") shutil.copyfile(target, backup) fixes = auto_fix_indentation(target) print(f"Auto-fix done. Applied {fixes} indentation adjustments.") print(f"Backup saved to: {backup}") if __name__ == "__main__": main()