91 lines
4.5 KiB
Python
91 lines
4.5 KiB
Python
"""Build the application-local Windows x64 hand-eye runtime, without pip.
|
|
|
|
Run with the already validated Python 3.12 environment. Only NumPy/OpenCV
|
|
packages and their licenses are copied; no venv/Anaconda paths are retained.
|
|
The output is a fresh directory; deployment is handled by qmake/CMake.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import importlib.metadata
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import sysconfig
|
|
import urllib.request
|
|
import zipfile
|
|
|
|
VERSION = '3.12.4'
|
|
ARCHIVE = f'python-{VERSION}-embed-amd64.zip'
|
|
URL = f'https://www.python.org/ftp/python/{VERSION}/{ARCHIVE}'
|
|
SHA256 = '15fea3c9367653a85086fe37216b4d1a1c78688fa5e1587e1db0b0f658856564'
|
|
PACKAGES = {'numpy': '2.5.2', 'opencv-contrib-python': '4.11.0.86'}
|
|
|
|
|
|
def main():
|
|
root = Path(__file__).resolve().parents[1]
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--output', type=Path, default=root/'third_party/handeye-runtime')
|
|
parser.add_argument('--archive', type=Path, default=root/'third_party/handeye-downloads'/ARCHIVE)
|
|
args = parser.parse_args()
|
|
if os.name != 'nt' or sys.version_info[:2] != (3, 12) or struct.calcsize('P') != 8:
|
|
parser.error('Use the validated Windows x64 Python 3.12 environment')
|
|
if args.output.exists():
|
|
parser.error('Output already exists; select a new --output directory for a rebuild')
|
|
site = Path(sysconfig.get_path('purelib')).resolve()
|
|
distributions = {}
|
|
for name, version in PACKAGES.items():
|
|
distribution = importlib.metadata.distribution(name)
|
|
if distribution.version != version:
|
|
parser.error(f'{name}: expected {version}, found {distribution.version}')
|
|
metadata = [p for p in distribution.files if str(p).endswith('.dist-info/METADATA')]
|
|
if len(metadata) != 1:
|
|
parser.error(f'{name}: missing distribution metadata and licenses')
|
|
distributions[name] = distribution.locate_file(metadata[0]).parent
|
|
if not args.archive.exists():
|
|
args.archive.parent.mkdir(parents=True, exist_ok=True)
|
|
urllib.request.urlretrieve(URL, args.archive)
|
|
if hashlib.sha256(args.archive.read_bytes()).hexdigest() != SHA256:
|
|
parser.error('Python archive SHA256 mismatch')
|
|
output = args.output.resolve()
|
|
output.mkdir(parents=True)
|
|
with zipfile.ZipFile(args.archive) as archive:
|
|
# Official archive has flat paths; reject traversal before extracting.
|
|
for name in archive.namelist():
|
|
if not (output/name).resolve().is_relative_to(output):
|
|
raise ValueError('Unsafe archive entry')
|
|
archive.extractall(output)
|
|
target = output/'Lib/site-packages'
|
|
target.mkdir(parents=True)
|
|
for name in ('numpy', 'numpy.libs', 'cv2'):
|
|
shutil.copytree(site/name, target/name,
|
|
ignore=shutil.ignore_patterns('__pycache__', '*.pyc', 'tests'))
|
|
for metadata in distributions.values():
|
|
shutil.copytree(metadata, target/metadata.name)
|
|
# All paths resolve relative to python312.dll. Do not import site or run
|
|
# user .pth files; dependency DLL loaders are part of NumPy/OpenCV.
|
|
(output/'python312._pth').write_text('python312.zip\n.\nLib/site-packages\n', encoding='ascii')
|
|
probe = ('import sys,json,numpy,cv2; '
|
|
'assert hasattr(cv2,"aruco"); '
|
|
'print(json.dumps(dict(python=sys.version,numpy=numpy.__version__,opencv=cv2.__version__)))')
|
|
env = dict(os.environ, PYTHONHOME='invalid-external-python', PYTHONPATH='invalid-external-packages',
|
|
PATH=os.path.join(os.environ['SystemRoot'], 'System32'))
|
|
result = subprocess.run([str(output/'python.exe'), '-I', '-B', '-c', probe],
|
|
cwd=output, env=env, check=True, capture_output=True, text=True)
|
|
manifest = dict(schema=1, platform='windows-amd64', python=VERSION,
|
|
python_archive_url=URL, python_archive_sha256=SHA256, packages=PACKAGES,
|
|
probe=json.loads(result.stdout))
|
|
manifest['files'] = {str(p.relative_to(output)).replace('\\', '/'):
|
|
hashlib.sha256(p.read_bytes()).hexdigest()
|
|
for p in sorted(output.rglob('*')) if p.is_file()}
|
|
(output/'manifest.json').write_text(json.dumps(manifest, indent=2), encoding='utf-8')
|
|
print(json.dumps(dict(runtime=str(output), files=len(manifest['files']),
|
|
size_mb=round(sum(p.stat().st_size for p in output.rglob('*') if p.is_file())/1048576, 1))))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|