File size: 2,047 Bytes
78661be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"""
server.py - Simple local test runner for ACRA backend.

Automatically runs inside the local .venv virtualenv, frees port 8000,
and starts Uvicorn cleanly.
"""

from pathlib import Path
import os
import subprocess
import sys
import time

# Must be set before uvicorn imports the app (which imports NumPy / ONNX).
os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE")
os.environ.setdefault("OMP_NUM_THREADS", "1")
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
os.environ.setdefault("MKL_NUM_THREADS", "1")

# Auto-reexec inside .venv if launched with system/external Python
_script_dir = Path(__file__).resolve().parent
_venv_python = _script_dir / ".venv" / "Scripts" / "python.exe"
if _venv_python.exists() and Path(sys.executable).resolve() != _venv_python.resolve():
    os.chdir(_script_dir)
    sys.exit(subprocess.call([str(_venv_python)] + sys.argv))

import uvicorn


def free_port(port: int = 8000):
    """Free port before starting to avoid conflicts."""
    if sys.platform != "win32":
        return
    try:
        out = subprocess.check_output(["netstat", "-ano"], text=True, stderr=subprocess.DEVNULL)
        for line in out.splitlines():
            if f":{port}" in line and "LISTENING" in line:
                pid = line.strip().split()[-1]
                if int(pid) != os.getpid():
                    subprocess.run(["taskkill", "/PID", pid, "/F", "/T"], capture_output=True)
        time.sleep(0.5)
    except Exception:
        pass


if __name__ == "__main__":
    os.chdir(_script_dir)
    free_port(8000)

    print("\n" + "=" * 55)
    print("  ACRA Backend Server (Local Testing)")
    print("=" * 55)
    print("  * URL:        http://127.0.0.1:8000")
    print("  * Health:     http://127.0.0.1:8000/health")
    print("  * API Docs:   http://127.0.0.1:8000/docs")
    print("  * Press Ctrl+C anytime to stop.")
    print("=" * 55 + "\n")

    try:
        uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=False)
    except KeyboardInterrupt:
        print("\n[ACRA] Backend stopped cleanly.")