1
0

compile_cython.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. """
  2. WaouW — Cython compilation script
  3. Compiles Python source files to native .so binaries for source code protection.
  4. Files that fail Cython compilation are compiled to .pyc (bytecode) as fallback.
  5. In both cases, the .py source file is removed from the image.
  6. Usage: python compile_cython.py [--clean]
  7. """
  8. import os
  9. import sys
  10. import shutil
  11. import subprocess
  12. import py_compile
  13. import compileall
  14. from pathlib import Path
  15. # Directories to compile
  16. COMPILE_DIRS = ["app/routers", "app/services", "app/core", "app/models", "app/api"]
  17. # Files to NEVER compile (must stay as .py)
  18. SKIP_FILES = {
  19. "__init__.py",
  20. "main.py",
  21. "conftest.py",
  22. "setup.py",
  23. }
  24. BASE_DIR = Path(__file__).parent
  25. def find_py_files():
  26. """Find all .py files eligible for compilation."""
  27. files = []
  28. for compile_dir in COMPILE_DIRS:
  29. dir_path = BASE_DIR / compile_dir
  30. if not dir_path.exists():
  31. continue
  32. for py_file in dir_path.rglob("*.py"):
  33. if py_file.name in SKIP_FILES:
  34. continue
  35. files.append(py_file)
  36. # Also compile top-level app files (tasks.py, etc.)
  37. for py_file in (BASE_DIR / "app").glob("*.py"):
  38. if py_file.name in SKIP_FILES:
  39. continue
  40. files.append(py_file)
  41. return files
  42. def try_cython_compile(py_file):
  43. """Try to compile a .py file to .so with Cython. Returns True on success."""
  44. try:
  45. setup_code = (
  46. "from setuptools import setup\n"
  47. "from Cython.Build import cythonize\n"
  48. "setup(ext_modules=cythonize(\n"
  49. f" '{py_file}',\n"
  50. " compiler_directives={'language_level': '3'},\n"
  51. "))\n"
  52. )
  53. setup_file = py_file.parent / f"_cython_setup_{py_file.stem}.py"
  54. setup_file.write_text(setup_code)
  55. result = subprocess.run(
  56. [sys.executable, str(setup_file), "build_ext", "--inplace"],
  57. capture_output=True,
  58. text=True,
  59. cwd=str(py_file.parent),
  60. timeout=120,
  61. )
  62. # Cleanup build artifacts
  63. setup_file.unlink(missing_ok=True)
  64. for f in py_file.parent.glob(f"{py_file.stem}*.c"):
  65. f.unlink(missing_ok=True)
  66. build_dir = py_file.parent / "build"
  67. if build_dir.exists():
  68. shutil.rmtree(build_dir)
  69. # Check if .so was created
  70. so_files = list(py_file.parent.glob(f"{py_file.stem}*.so"))
  71. return len(so_files) > 0
  72. except Exception:
  73. return False
  74. def compile_to_pyc(py_file):
  75. """Compile .py to .pyc (bytecode) as fallback. Returns True on success."""
  76. try:
  77. # Compile with optimization level 2 (strips docstrings + asserts)
  78. py_compile.compile(
  79. str(py_file),
  80. cfile=str(py_file) + "c", # file.pyc next to file.py
  81. optimize=2,
  82. )
  83. # Also create the __pycache__ version that Python imports
  84. compileall.compile_file(str(py_file), force=True, quiet=1, optimize=2)
  85. return True
  86. except Exception:
  87. return False
  88. def remove_py_source(py_file):
  89. """Remove the .py source file, keeping .so or .pyc."""
  90. py_file.unlink(missing_ok=True)
  91. def clean():
  92. """Remove all .so and .pyc files (revert to .py-only mode)."""
  93. count = 0
  94. for compile_dir in COMPILE_DIRS:
  95. dir_path = BASE_DIR / compile_dir
  96. if not dir_path.exists():
  97. continue
  98. for f in dir_path.rglob("*.so"):
  99. f.unlink()
  100. count += 1
  101. for f in dir_path.rglob("*.pyc"):
  102. if "__pycache__" not in str(f):
  103. f.unlink()
  104. count += 1
  105. print(f"Cleaned {count} compiled files")
  106. if __name__ == "__main__":
  107. if "--clean" in sys.argv:
  108. clean()
  109. sys.exit(0)
  110. print("WaouW Cython Compiler")
  111. print("=" * 40)
  112. files = find_py_files()
  113. print(f"Found {len(files)} files to compile\n")
  114. cython_ok = []
  115. pyc_ok = []
  116. failed = []
  117. for py_file in files:
  118. rel = py_file.relative_to(BASE_DIR)
  119. print(f" {rel} ... ", end="", flush=True)
  120. if try_cython_compile(py_file):
  121. print("SO (native binary)")
  122. cython_ok.append(py_file)
  123. remove_py_source(py_file)
  124. else:
  125. print("KEEP (.py - Cython failed)")
  126. failed.append(py_file)
  127. print(f"\n{'=' * 40}")
  128. print(f"Results:")
  129. print(f" .so (native): {len(cython_ok)}")
  130. print(f" .pyc (bytecode): {len(pyc_ok)}")
  131. print(f" .py (kept): {len(failed)}")
  132. print(f" Total: {len(files)}")
  133. if failed:
  134. print(f"\nKept as .py:")
  135. for f in failed:
  136. print(f" {f.relative_to(BASE_DIR)}")