Files
my-botty/build.py
alexpolo1 3d11947bf2 ocr: bundle Tesseract into release for click-and-run OCR
Make the standalone exe work with OCR out of the box — no separate
Tesseract install, no tesserocr DLL hell. Verified end-to-end: built the
exe, ran it frozen with the system Tesseract blinded, confirmed it
resolves the bundled binary and reads text ("CHAM RUNE").

- ocr.py: resolve an _APP_BASE (exe dir when frozen, else cwd) and prefer
  a bundled <exe_dir>/tesseract/tesseract.exe over PATH / Program Files.
  Resolve assets/tessdata to an absolute path so OCR no longer depends on
  the current working dir. Applies to both the tesserocr and pytesseract
  paths.
- build.py: copy a portable Tesseract (exe + DLLs) from TESSERACT_DIR
  (default C:\Program Files\Tesseract-OCR) into <release>/tesseract/. Our
  trained models in assets/tessdata are used via --tessdata-dir, so their
  tessdata is skipped. Warns (non-fatal) if Tesseract isn't present.
- ci.yml: choco install tesseract before the build so the bundle is
  reproducible on the runner; verify it landed in the release dir.
- test/conftest.py: apply the SSL cert-store workaround so pytest can be
  collected on Windows boxes with a corrupted cert store (no-op on CI).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-20 10:49:25 +02:00

155 lines
6.5 KiB
Python

import os
import shutil
from pathlib import Path
from src.version import __version__
import argparse
import getpass
import random
from cryptography.fernet import Fernet
import string
parser = argparse.ArgumentParser(description="Build Botty")
parser.add_argument(
"-v" , "--version",
type=str,
help="New release version e.g. 0.4.2",
default=""
)
parser.add_argument(
"-c", "--conda_path",
type=str,
help="Path to local conda e.g. C:\\Users\\USER\\miniconda3",
default=f"C:\\Users\\{getpass.getuser()}\\miniconda3")
parser.add_argument(
"-r", "--random_name",
action='store_true',
help="Will generate a random name for the botty exe")
parser.add_argument(
"-k", "--use_key",
action='store_true',
help="Will build with encryption key")
args = parser.parse_args()
# clean up
def clean_up():
# pyinstaller
if os.path.exists("build"):
shutil.rmtree("build")
if os.path.exists("main.spec"):
os.remove("main.spec")
if os.path.exists("health_manager.spec"):
os.remove("health_manager.spec")
if os.path.exists("shopper.spec"):
os.remove("shopper.spec")
if __name__ == "__main__":
new_version_code = None
if args.version != "":
print(f"Releasing new version: {args.version}")
os.system(f"git checkout -b new-release-v{args.version}")
botty_dir = f"botty_v{args.version}"
version_code = ""
with open('src/version.py', 'r') as f:
version_code = f.read()
version_code = version_code.split("=")
new_version_code = f"{version_code[0]}= '{args.version}'"
with open('src/version.py', 'w') as f:
f.write(new_version_code)
else:
botty_dir = f"botty_v{__version__}"
print(f"Building version: {__version__}")
clean_up()
if os.path.exists(botty_dir):
for path in Path(botty_dir).glob("**/*"):
if path.is_file():
os.remove(path)
elif path.is_dir():
shutil.rmtree(path)
shutil.rmtree(botty_dir)
for exe in ["main.py", "shopper.py"]:
key_cmd = " "
if args.use_key:
key = Fernet.generate_key().decode("utf-8")
key_cmd = " --key " + key
botty_env = os.path.join(args.conda_path, "envs", "botty")
pyinstaller_exe = os.path.join(botty_env, "Scripts", "pyinstaller.exe")
# Conda ships native DLLs (ffi-8/liblzma/libbz2 for _ctypes/_lzma/_bz2,
# plus leptonica/tesseract52 for tesserocr) in Library\bin and DLLs.
# PyInstaller resolves binary dependencies via the PATH (NOT --paths,
# which only affects Python module imports). If these dirs aren't on
# PATH the built exe crashes at import with
# "DLL load failed while importing _ctypes". Prepend them for both
# local and CI builds.
dll_dirs = [
os.path.join(botty_env, "Library", "bin"),
os.path.join(botty_env, "Library", "lib"),
os.path.join(botty_env, "DLLs"),
]
os.environ["PATH"] = os.pathsep.join(dll_dirs) + os.pathsep + os.environ.get("PATH", "")
installer_cmd = f'{pyinstaller_exe} --onefile --noconsole --distpath {botty_dir}{key_cmd} --exclude-module graphviz --exclude-module keyboard --exclude-module mouse --exclude-module pyclick --exclude-module mouseinfo --paths .\\src --paths "{botty_env}\\Lib\\site-packages" src\\{exe}'
ret = os.system(installer_cmd)
if ret != 0:
raise RuntimeError(f"PyInstaller failed for {exe} (exit {ret})")
os.makedirs(f"{botty_dir}/config", exist_ok=True)
with open(f"{botty_dir}/config/custom.ini", "w") as f:
f.write("; Add parameters you want to overwrite from param.ini here")
shutil.copy("config/game.ini", f"{botty_dir}/config/")
shutil.copy("config/params.ini", f"{botty_dir}/config/")
shutil.copy("config/shop.ini", f"{botty_dir}/config/")
shutil.copy("config/default.bnip", f"{botty_dir}/config/")
os.makedirs(f"{botty_dir}/config/bnip", exist_ok=True)
shutil.copy("README.md", f"{botty_dir}/")
shutil.copytree("assets", f"{botty_dir}/assets")
shutil.copytree("src", f"{botty_dir}/src")
shutil.copy("environment.yml", f"{botty_dir}/")
shutil.copy("install.bat", f"{botty_dir}/")
shutil.copy("find_python.bat", f"{botty_dir}/")
shutil.copy("run_botty.bat", f"{botty_dir}/")
shutil.copy("run.bat", f"{botty_dir}/")
if os.path.exists("dependencies"):
shutil.copytree("dependencies", f"{botty_dir}/dependencies")
# Bundle a portable Tesseract so the standalone exe is click-and-run with
# working OCR and no separate install. ocr.py prefers <exe_dir>/tesseract/
# tesseract.exe. Source: TESSERACT_DIR env or the default UB Mannheim path.
# Skipped (with a warning) if not present — the bot still works once the
# user runs install.bat, which sets OCR up the conda way.
tesseract_src = os.environ.get("TESSERACT_DIR", r"C:\Program Files\Tesseract-OCR")
tess_exe = os.path.join(tesseract_src, "tesseract.exe")
if os.path.isfile(tess_exe):
print(f"Bundling Tesseract from {tesseract_src}")
# Copy the exe + DLLs; skip their tessdata (we ship our own trained
# models in assets/tessdata and pass --tessdata-dir to point at them).
os.makedirs(f"{botty_dir}/tesseract", exist_ok=True)
for entry in os.listdir(tesseract_src):
src = os.path.join(tesseract_src, entry)
if os.path.isfile(src) and entry.lower().endswith((".exe", ".dll")):
shutil.copy(src, f"{botty_dir}/tesseract/")
else:
print(f"WARNING: Tesseract not found at {tesseract_src} — release will "
f"rely on install.bat for OCR setup. Set TESSERACT_DIR to bundle it.")
clean_up()
if args.random_name:
print("Generate random names")
new_name = ''.join(random.choices(string.ascii_letters, k=random.randint(6, 14)))
os.rename(f'{botty_dir}/main.exe', f'{botty_dir}/{new_name}.exe')
# Rename main.exe to avoid Warden flagging the obvious name
# In CI/production builds (env BOTTY_NO_RENAME=1) keep main.exe as-is
if not args.random_name and not os.environ.get("BOTTY_NO_RENAME"):
new_name = ''.join(random.choices(string.ascii_lowercase + string.digits, k=8))
os.rename(f'{botty_dir}/main.exe', f'{botty_dir}/{new_name}.exe')
print(f"Renamed main.exe -> {new_name}.exe")
if new_version_code is not None:
os.system(f'git add .')
os.system(f'git commit -m "Bump version to v{args.version}"')