""" WaouW — Cython compilation script Compiles Python source files to native .so binaries for source code protection. Files that fail Cython compilation are compiled to .pyc (bytecode) as fallback. In both cases, the .py source file is removed from the image. Usage: python compile_cython.py [--clean] """ import os import sys import shutil import subprocess import py_compile import compileall from pathlib import Path # Directories to compile COMPILE_DIRS = ["app/routers", "app/services", "app/core", "app/models", "app/api"] # Files to NEVER compile (must stay as .py) SKIP_FILES = { "__init__.py", "main.py", "conftest.py", "setup.py", } BASE_DIR = Path(__file__).parent def find_py_files(): """Find all .py files eligible for compilation.""" files = [] for compile_dir in COMPILE_DIRS: dir_path = BASE_DIR / compile_dir if not dir_path.exists(): continue for py_file in dir_path.rglob("*.py"): if py_file.name in SKIP_FILES: continue files.append(py_file) # Also compile top-level app files (tasks.py, etc.) for py_file in (BASE_DIR / "app").glob("*.py"): if py_file.name in SKIP_FILES: continue files.append(py_file) return files def try_cython_compile(py_file): """Try to compile a .py file to .so with Cython. Returns True on success.""" try: setup_code = ( "from setuptools import setup\n" "from Cython.Build import cythonize\n" "setup(ext_modules=cythonize(\n" f" '{py_file}',\n" " compiler_directives={'language_level': '3'},\n" "))\n" ) setup_file = py_file.parent / f"_cython_setup_{py_file.stem}.py" setup_file.write_text(setup_code) result = subprocess.run( [sys.executable, str(setup_file), "build_ext", "--inplace"], capture_output=True, text=True, cwd=str(py_file.parent), timeout=120, ) # Cleanup build artifacts setup_file.unlink(missing_ok=True) for f in py_file.parent.glob(f"{py_file.stem}*.c"): f.unlink(missing_ok=True) build_dir = py_file.parent / "build" if build_dir.exists(): shutil.rmtree(build_dir) # Check if .so was created so_files = list(py_file.parent.glob(f"{py_file.stem}*.so")) return len(so_files) > 0 except Exception: return False def compile_to_pyc(py_file): """Compile .py to .pyc (bytecode) as fallback. Returns True on success.""" try: # Compile with optimization level 2 (strips docstrings + asserts) py_compile.compile( str(py_file), cfile=str(py_file) + "c", # file.pyc next to file.py optimize=2, ) # Also create the __pycache__ version that Python imports compileall.compile_file(str(py_file), force=True, quiet=1, optimize=2) return True except Exception: return False def remove_py_source(py_file): """Remove the .py source file, keeping .so or .pyc.""" py_file.unlink(missing_ok=True) def clean(): """Remove all .so and .pyc files (revert to .py-only mode).""" count = 0 for compile_dir in COMPILE_DIRS: dir_path = BASE_DIR / compile_dir if not dir_path.exists(): continue for f in dir_path.rglob("*.so"): f.unlink() count += 1 for f in dir_path.rglob("*.pyc"): if "__pycache__" not in str(f): f.unlink() count += 1 print(f"Cleaned {count} compiled files") if __name__ == "__main__": if "--clean" in sys.argv: clean() sys.exit(0) print("WaouW Cython Compiler") print("=" * 40) files = find_py_files() print(f"Found {len(files)} files to compile\n") cython_ok = [] pyc_ok = [] failed = [] for py_file in files: rel = py_file.relative_to(BASE_DIR) print(f" {rel} ... ", end="", flush=True) if try_cython_compile(py_file): print("SO (native binary)") cython_ok.append(py_file) remove_py_source(py_file) else: print("KEEP (.py - Cython failed)") failed.append(py_file) print(f"\n{'=' * 40}") print(f"Results:") print(f" .so (native): {len(cython_ok)}") print(f" .pyc (bytecode): {len(pyc_ok)}") print(f" .py (kept): {len(failed)}") print(f" Total: {len(files)}") if failed: print(f"\nKept as .py:") for f in failed: print(f" {f.relative_to(BASE_DIR)}")