| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164 |
- """
- 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)}")
|