build: CPU/GPU 双环境、产物命名与打包修复
交付:
· 产物按变体命名:CPU -> dist/ocr-server/,GPU -> dist/ocr-server-gpu/。
变体由构建环境实际装的 paddle 自动判断,不需要人工声明
· GPU 包额外加 --collect-binaries nvidia。漏收的后果实测是最难查的那种:
引擎能正常加载、设备也识别成 GPU,但第一次推理才报
cudnn64_9.dll error 126
· --copy-metadata 的发行包名随变体变化(paddlepaddle / paddlepaddle-gpu),
改由 scripts/paddle_env.py 动态取;写死任何一个在另一种环境下都打不出包
· 新增 scripts/prepare_release_config.py 按变体覆盖发布配置(用 Python 改写
以保持 UTF-8,PowerShell 的 Set-Content 会把中文注释写坏)
环境:
· paddle 从 pyproject 依赖里移除,改用 scripts/install_paddle.py 安装。
它没法写死:CPU/GPU 互斥,GPU 还得按显卡选 CUDA 通道(RTX 50 系必须 cu129)。
钉死 CPU 版时,uv sync / uv run / PyCharm 自动同步都会把装好的
paddlepaddle-gpu 静默挤掉、服务悄悄退回 CPU(实测踩过三次)
· 新增 scripts/switch_env.py:.venv(CPU)与 .venv-gpu(GPU)两套环境共存,
切换零成本;所有 uv run 补 --no-sync,打包改用 uv sync --inexact
· 预置模型扩到 8 套(v4/v5 × 服务端/移动端 × 检测/识别,约 398MB)
其它:
· scripts/start.* 先找发布包再退回源码环境;入口脚本名固定是 ocr-server
· benchmark_ocr.py 输出 segments 与 chars,换设备/模型时可直接比对召回
· .gitignore 覆盖 .venv-gpu/ 与 dist*/
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
+50
-32
@@ -1,5 +1,18 @@
|
||||
"""Benchmark the configured OCR pipeline without modifying model files."""
|
||||
"""Benchmark the configured OCR pipeline without modifying model files.
|
||||
|
||||
用法:
|
||||
uv run --no-sync python scripts/benchmark_ocr.py # 默认样例图
|
||||
uv run --no-sync python scripts/benchmark_ocr.py 你的图.png # 指定图片
|
||||
uv run --no-sync python scripts/benchmark_ocr.py 你的图.png 3 # 跑 3 次,报最快那次
|
||||
|
||||
⚠️ `--no-sync` 不能省:uv run 默认会按 pyproject.toml 同步环境,那里声明的是 CPU 版
|
||||
paddlepaddle,会把装好的 paddlepaddle-gpu 静默冲掉、退回 CPU——测速结果会失真。
|
||||
|
||||
改完 config.yaml 重新执行即可对比。调模型或参数时**重点看 chars**:
|
||||
速度变快但字符数掉得多,就是丢字了。
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from time import perf_counter
|
||||
|
||||
@@ -7,40 +20,45 @@ from ocr_server.config import Settings
|
||||
from ocr_server.ocr import OCRService
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
image_path = Path("http/fixtures/general_ocr_002.png")
|
||||
settings = Settings()
|
||||
service = OCRService(
|
||||
lang=settings.lang,
|
||||
device=settings.device,
|
||||
model_dir=settings.model_dir,
|
||||
det_model_name=settings.det_model_name,
|
||||
rec_model_name=settings.rec_model_name,
|
||||
text_det_limit_side_len=settings.text_det_limit_side_len,
|
||||
text_det_limit_type=settings.text_det_limit_type,
|
||||
text_det_thresh=settings.text_det_thresh,
|
||||
text_det_box_thresh=settings.text_det_box_thresh,
|
||||
text_det_unclip_ratio=settings.text_det_unclip_ratio,
|
||||
text_rec_score_thresh=settings.text_rec_score_thresh,
|
||||
text_recognition_batch_size=settings.text_recognition_batch_size,
|
||||
cpu_threads=settings.cpu_threads_resolved,
|
||||
enable_mkldnn=settings.enable_mkldnn,
|
||||
)
|
||||
service.prepare()
|
||||
|
||||
stages: list[str] = []
|
||||
def run_once(service: OCRService, image_path: Path) -> tuple[float, int, int, float, float]:
|
||||
marks: list[tuple[int, float]] = []
|
||||
started = perf_counter()
|
||||
|
||||
def on_progress(percent: int, message: str) -> None:
|
||||
stages.append(f"{percent}% {message}")
|
||||
marks.append((percent, perf_counter() - started))
|
||||
|
||||
started = perf_counter()
|
||||
lines = service.recognize(image_path, on_progress=on_progress)
|
||||
elapsed_ms = (perf_counter() - started) * 1000
|
||||
elapsed = perf_counter() - started
|
||||
texts = [item["text"] for item in lines if item.get("text")]
|
||||
detection = next((t for p, t in marks if p == 50), 0.0)
|
||||
recognition = next((t for p, t in marks if p == 80), 0.0)
|
||||
return elapsed, len(texts), sum(len(text) for text in texts), detection, recognition
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
image_path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(
|
||||
"http/fixtures/general_ocr_002.png"
|
||||
)
|
||||
repeats = int(sys.argv[2]) if len(sys.argv) > 2 else 1
|
||||
|
||||
settings = Settings()
|
||||
service = OCRService.from_settings(settings)
|
||||
service.prepare()
|
||||
|
||||
print(f"image={image_path}")
|
||||
print(f"cpu_threads={settings.cpu_threads_resolved} (config={settings.cpu_threads})")
|
||||
print(f"enable_mkldnn={settings.enable_mkldnn}")
|
||||
print(f"det={settings.det_model_name} rec={settings.rec_model_name}")
|
||||
print(f"elapsed_ms={elapsed_ms:.2f}")
|
||||
print(f"segments={len(lines)}")
|
||||
for stage in stages:
|
||||
print(f"stage={stage}")
|
||||
print(f"device={service._effective_device} (config={settings.device})")
|
||||
print(f"enable_mkldnn={settings.enable_mkldnn} cpu_threads={settings.cpu_threads_resolved}")
|
||||
print(f"text_det_limit_side_len={settings.text_det_limit_side_len} "
|
||||
f"text_recognition_batch_size={settings.text_recognition_batch_size}")
|
||||
|
||||
results = [run_once(service, image_path) for _ in range(repeats)]
|
||||
# 至少跑一次预热,避免把首次推理的算子编译时间算进去。
|
||||
if repeats == 1:
|
||||
print("(只跑一次,数值可能含首次推理的预热开销;建议传次数参数多跑几次)")
|
||||
elapsed, segments, chars, detection, recognition = min(results)
|
||||
print(f"elapsed_ms={elapsed * 1000:.2f}")
|
||||
print(f" detect_ms={detection * 1000:.2f}")
|
||||
print(f" recognize_ms={(recognition - detection) * 1000:.2f}")
|
||||
print(f"segments={segments}")
|
||||
print(f"chars={chars}")
|
||||
|
||||
@@ -16,7 +16,9 @@ if not exist "config.yaml" (
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
uv run python scripts\download_models.py
|
||||
rem --no-sync:uv run 默认会按 pyproject.toml 同步环境,那里声明的是 CPU 版
|
||||
rem paddlepaddle,会把装好的 paddlepaddle-gpu 冲掉。
|
||||
uv run --no-sync python scripts\download_models.py
|
||||
if errorlevel 1 (
|
||||
echo [ERROR] 模型下载失败。
|
||||
endlocal
|
||||
|
||||
@@ -10,7 +10,7 @@ fi
|
||||
|
||||
if command -v uv >/dev/null 2>&1; then
|
||||
printf '%s\n' '[OCR] 检查并下载缺失模型...'
|
||||
uv run python scripts/download_models.py
|
||||
uv run --no-sync python scripts/download_models.py
|
||||
elif [[ -x .venv/bin/python ]]; then
|
||||
printf '%s\n' '[OCR] 检查并下载缺失模型(使用 .venv)...'
|
||||
.venv/bin/python scripts/download_models.py
|
||||
|
||||
+35
-18
@@ -1,25 +1,42 @@
|
||||
"""Download PP-OCRv5 models into the project's configured model directory."""
|
||||
"""Download the staged PP-OCR models into the project's configured model directory.
|
||||
|
||||
交付包会预置多套检测/识别模型,方便在客户机器上只改 config.yaml 就能离线切换。
|
||||
已经完整的模型目录会被跳过(见 OCRService._is_complete_model),不会重复下载。
|
||||
"""
|
||||
|
||||
import shutil
|
||||
|
||||
from ocr_server.config import Settings
|
||||
from ocr_server.ocr import OCRService
|
||||
from ocr_server.ocr import STAGED_DET_MODELS, STAGED_REC_MODELS, OCRService
|
||||
|
||||
|
||||
def drop_download_stubs(settings: Settings) -> None:
|
||||
"""清理只含 .cache 的残壳目录(上次下载中断留下的)。
|
||||
|
||||
只删这种明确的失败残留,不碰任何带真实权重文件的目录。
|
||||
"""
|
||||
official_dir = settings.model_dir.resolve() / "official_models"
|
||||
if not official_dir.is_dir():
|
||||
return
|
||||
for path in sorted(official_dir.iterdir()):
|
||||
if not path.is_dir():
|
||||
continue
|
||||
entries = {item.name for item in path.iterdir()}
|
||||
if entries and entries <= {".cache"}:
|
||||
print(f"清理下载残留目录: {path.name}")
|
||||
shutil.rmtree(path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
settings = Settings()
|
||||
OCRService(
|
||||
lang=settings.lang,
|
||||
device=settings.device,
|
||||
model_dir=settings.model_dir,
|
||||
det_model_name=settings.det_model_name,
|
||||
rec_model_name=settings.rec_model_name,
|
||||
text_det_limit_side_len=settings.text_det_limit_side_len,
|
||||
text_det_limit_type=settings.text_det_limit_type,
|
||||
text_det_thresh=settings.text_det_thresh,
|
||||
text_det_box_thresh=settings.text_det_box_thresh,
|
||||
text_det_unclip_ratio=settings.text_det_unclip_ratio,
|
||||
text_rec_score_thresh=settings.text_rec_score_thresh,
|
||||
text_recognition_batch_size=settings.text_recognition_batch_size,
|
||||
cpu_threads=settings.cpu_threads_resolved,
|
||||
enable_mkldnn=settings.enable_mkldnn,
|
||||
).prepare()
|
||||
drop_download_stubs(settings)
|
||||
|
||||
combos = [(det, settings.rec_model_name) for det in STAGED_DET_MODELS]
|
||||
combos += [(settings.det_model_name, rec) for rec in STAGED_REC_MODELS]
|
||||
for det_model, rec_model in combos:
|
||||
print(f"检查模型 det={det_model} rec={rec_model}")
|
||||
OCRService.from_settings(
|
||||
settings, det_model_name=det_model, rec_model_name=rec_model
|
||||
).prepare()
|
||||
|
||||
print(f"Models are ready in: {settings.model_dir.resolve()}")
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
"""安装 paddlepaddle(CPU 版或 GPU 版)。
|
||||
|
||||
paddlepaddle 不在 pyproject.toml 的依赖里,原因见那里的注释:CPU/GPU 两个发行包
|
||||
互斥、GPU 版还要按显卡选 CUDA 通道,写死任何一个都会被 `uv sync` / PyCharm 自动同步
|
||||
冲掉。所以单独用这个脚本安装。
|
||||
|
||||
用法:
|
||||
python scripts/install_paddle.py # 自动:检测到 NVIDIA 显卡就装 GPU 版,否则 CPU 版
|
||||
python scripts/install_paddle.py --cpu # 强制 CPU 版
|
||||
python scripts/install_paddle.py --gpu # 强制 GPU 版,CUDA 通道按显卡自动推荐
|
||||
python scripts/install_paddle.py --gpu --cuda cu126 # 指定 CUDA 通道
|
||||
python scripts/install_paddle.py --gpu --version 3.2.2 # 指定版本
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
DEFAULT_VERSION = "3.2.2"
|
||||
SUPPORTED_CUDA = ("cu118", "cu126", "cu129")
|
||||
INDEX_TEMPLATE = "https://www.paddlepaddle.org.cn/packages/stable/{cuda}/"
|
||||
CPU_PACKAGE = "paddlepaddle"
|
||||
GPU_PACKAGE = "paddlepaddle-gpu"
|
||||
BOTH_PACKAGES = (CPU_PACKAGE, GPU_PACKAGE)
|
||||
|
||||
# paddlepaddle-gpu 会顺带装上的 CUDA 运行库(约 3GB)。装 CPU 版时一并清理,
|
||||
# 否则环境里会白留着几个 G 的 .venv 体积。
|
||||
NVIDIA_PACKAGES = (
|
||||
"nvidia-cublas-cu12",
|
||||
"nvidia-cuda-runtime-cu12",
|
||||
"nvidia-cudnn-cu12",
|
||||
"nvidia-cufft-cu12",
|
||||
"nvidia-curand-cu12",
|
||||
"nvidia-cusolver-cu12",
|
||||
"nvidia-cusparse-cu12",
|
||||
"nvidia-nvjitlink-cu12",
|
||||
)
|
||||
|
||||
|
||||
def run(command: list[str], check: bool = True) -> subprocess.CompletedProcess[str]:
|
||||
print(f" $ {' '.join(command)}", flush=True)
|
||||
result = subprocess.run(command, capture_output=True, text=True, encoding="utf-8")
|
||||
if result.stdout.strip():
|
||||
print(" " + result.stdout.strip().replace("\n", "\n "))
|
||||
if result.stderr.strip():
|
||||
print(" " + result.stderr.strip().replace("\n", "\n "))
|
||||
if check and result.returncode != 0:
|
||||
raise SystemExit(result.returncode)
|
||||
return result
|
||||
|
||||
|
||||
def pip_command(*args: str, python: str | None = None) -> list[str]:
|
||||
"""优先用 uv pip,没有 uv 就退回 pip。python 指定目标解释器(多环境时用)。"""
|
||||
uv = subprocess.run(
|
||||
["uv", "--version"], capture_output=True, text=True, check=False
|
||||
)
|
||||
if uv.returncode == 0:
|
||||
base = ["uv", "pip", *args]
|
||||
if python:
|
||||
base += ["--python", python]
|
||||
return base
|
||||
target = python or sys.executable
|
||||
return [target, "-m", "pip", *args]
|
||||
|
||||
|
||||
def detect_gpu_name() -> str | None:
|
||||
"""读 nvidia-smi 拿显卡型号;没有 NVIDIA 卡或没装驱动时返回 None。"""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=20,
|
||||
check=False,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return None
|
||||
if result.returncode != 0:
|
||||
return None
|
||||
first = result.stdout.strip().splitlines()
|
||||
return first[0].strip() if first and first[0].strip() else None
|
||||
|
||||
|
||||
def recommend_cuda(gpu_name: str | None) -> str:
|
||||
"""按显卡型号推荐 CUDA 通道。
|
||||
|
||||
RTX 50 系是 Blackwell(sm_120),只有 cu129 的内核包含它;装 cu118/cu126 会
|
||||
在推理时报 Mismatched GPU Architecture。
|
||||
"""
|
||||
if not gpu_name:
|
||||
return "cu126"
|
||||
upper = gpu_name.upper()
|
||||
if re.search(r"RTX\s*50\d0", upper):
|
||||
return "cu129"
|
||||
if re.search(r"RTX\s*[34]0\d0", upper):
|
||||
return "cu126"
|
||||
return "cu118"
|
||||
|
||||
|
||||
def explain_uninstall_failure(output: str) -> None:
|
||||
if "拒绝访问" in output or "Access is denied" in output or "os error 5" in output:
|
||||
print(
|
||||
"\n[错误] 卸载旧版失败:文件被占用。\n"
|
||||
" 最常见的原因是 OCR 服务正在运行,或者 PyCharm 的 Python 控制台\n"
|
||||
" 导入过 paddle。请先停掉它们再重试。",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="安装 paddlepaddle(CPU 或 GPU 版)")
|
||||
group = parser.add_mutually_exclusive_group()
|
||||
group.add_argument("--cpu", action="store_true", help="强制安装 CPU 版")
|
||||
group.add_argument("--gpu", action="store_true", help="强制安装 GPU 版")
|
||||
parser.add_argument(
|
||||
"--cuda",
|
||||
choices=SUPPORTED_CUDA,
|
||||
help=f"GPU 版的 CUDA 通道({' / '.join(SUPPORTED_CUDA)}),默认按显卡型号推荐",
|
||||
)
|
||||
parser.add_argument("--version", default=DEFAULT_VERSION, help="paddle 版本,默认 3.2.2")
|
||||
parser.add_argument(
|
||||
"--dry-run", action="store_true", help="只打印将要执行的安装方案,不做任何改动"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--python",
|
||||
help="目标解释器路径(多套虚拟环境时用),默认当前环境",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
gpu_name = detect_gpu_name()
|
||||
use_gpu = args.gpu or (not args.cpu and gpu_name is not None)
|
||||
cuda = args.cuda or recommend_cuda(gpu_name)
|
||||
|
||||
print("检测到显卡:" + (gpu_name or "无 NVIDIA 显卡"))
|
||||
print(f"安装目标:{'GPU 版' if use_gpu else 'CPU 版'}"
|
||||
+ (f"(CUDA 通道 {cuda})" if use_gpu else ""))
|
||||
if use_gpu and not gpu_name:
|
||||
print(" ⚠️ 没检测到 NVIDIA 显卡,但仍按要求装 GPU 版;")
|
||||
print(" 这样装在无卡机器上可能连 import 都失败,请确认目标机器。")
|
||||
|
||||
if args.dry_run:
|
||||
package = GPU_PACKAGE if use_gpu else CPU_PACKAGE
|
||||
print(f"\n[dry-run] 将安装 {package}=={args.version}"
|
||||
+ (f",来源 {INDEX_TEMPLATE.format(cuda=cuda)}" if use_gpu else ""))
|
||||
return 0
|
||||
|
||||
# 装 CPU 版时顺带清掉 GPU 版拖进来的 CUDA 运行库;装 GPU 版时不用管(本来就要装)。
|
||||
to_remove = BOTH_PACKAGES if use_gpu else (*BOTH_PACKAGES, *NVIDIA_PACKAGES)
|
||||
print("\n[1/2] 卸载已有的 " + " / ".join(to_remove))
|
||||
result = run(pip_command("uninstall", *to_remove, python=args.python), check=False)
|
||||
explain_uninstall_failure((result.stdout or "") + (result.stderr or ""))
|
||||
if result.returncode != 0:
|
||||
return result.returncode
|
||||
|
||||
print(f"\n[2/2] 安装 {GPU_PACKAGE if use_gpu else CPU_PACKAGE}=={args.version}")
|
||||
if use_gpu:
|
||||
command = pip_command(
|
||||
"install",
|
||||
f"{GPU_PACKAGE}=={args.version}",
|
||||
# 用 extra-index-url 而不是 index-url:paddlepaddle-gpu 只在官方源上,
|
||||
# 但它的依赖(numpy 等)还得从 PyPI 取。
|
||||
"--extra-index-url",
|
||||
INDEX_TEMPLATE.format(cuda=cuda),
|
||||
python=args.python,
|
||||
)
|
||||
else:
|
||||
command = pip_command(
|
||||
"install", f"{CPU_PACKAGE}=={args.version}", python=args.python
|
||||
)
|
||||
run(command)
|
||||
|
||||
print("\n完成。验证方式:")
|
||||
if use_gpu:
|
||||
print(" python -c \"import paddle; print(paddle.device.is_compiled_with_cuda())\"")
|
||||
print(" config.yaml 里 device: auto 即可自动走 GPU")
|
||||
else:
|
||||
print(" config.yaml 里 device: cpu(或 auto,无卡时自动用 CPU)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+104
-11
@@ -1,16 +1,28 @@
|
||||
#!/usr/bin/env bash
|
||||
# 打包 Ubuntu/Linux 发布包(--onedir 目录形式)。
|
||||
#
|
||||
# CPU / GPU 两个变体由**构建环境里装的 paddlepaddle 版本**自动决定,不需要手动指定:
|
||||
# 装了 paddlepaddle -> CPU 包,输出到 dist/
|
||||
# 装了 paddlepaddle-gpu -> GPU 包,dist/ocr-server-gpu/,且 config.yaml 的 device 预置为 auto
|
||||
# GPU 包的同一个分发包在没显卡的机器上也能启动(会自动回落 CPU,见 README)。
|
||||
#
|
||||
# 关键参数说明,改动前请先读:
|
||||
# --collect-all paddle/paddlex/paddleocr Paddle 的原生库与配置必须整体收集,缺一个就跑不起来
|
||||
# --collect-all pyclipper/pypdfium2/shapely/bidi
|
||||
# 检测后处理与识别的必需依赖,漏了会在推理时报错
|
||||
# --copy-metadata * PaddleX 通过 importlib.metadata 检查依赖,
|
||||
# 缺元数据会误判「依赖未安装」
|
||||
# 缺元数据会误判「依赖未安装」。
|
||||
# ⚠️ paddle 的发行包名随变体变化(paddlepaddle /
|
||||
# paddlepaddle-gpu),写死会打不出包,
|
||||
# 所以由 scripts/paddle_env.py 动态取。
|
||||
# --additional-hooks-dir scripts 启用 scripts/hook-imagesize.py
|
||||
# --hidden-import imagesize 源码环境下按需导入,打包时必须显式声明
|
||||
#
|
||||
# 必须在 Linux 上执行:PyInstaller 不能交叉编译,Windows 上无法生成 ELF 二进制。
|
||||
#
|
||||
# 用法:
|
||||
# ./scripts/package-ubuntu.sh # 按环境自动判断变体
|
||||
# ./scripts/package-ubuntu.sh --gpu # 断言必须是 GPU 版 paddle
|
||||
set -euo pipefail
|
||||
|
||||
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
@@ -21,14 +33,85 @@ if [[ "$(uname -s)" != "Linux" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
uv sync --dev --python 3.12
|
||||
rm -rf build dist
|
||||
REQUIRE_GPU=0
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--gpu) REQUIRE_GPU=1 ;;
|
||||
*)
|
||||
printf '未知参数:%s\n' "$arg" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
uv run pyinstaller --noconfirm --clean --onedir --name ocr-server \
|
||||
# --inexact + --no-install-package paddlepaddle:只同步除 paddle 以外的依赖。
|
||||
# pyproject.toml 里声明的是 CPU 版 paddlepaddle,裸跑 uv sync 会「卸载
|
||||
# paddlepaddle-gpu 和全部 nvidia-* 运行库、装回 CPU 版」,把 GPU 环境悄悄冲掉;
|
||||
# 而单独用 --no-install-package 又会把 paddlepaddle-gpu 当多余包删掉。
|
||||
# 这两个参数合用才能保住当前装的 paddle 变体(实测 dry-run 为 no changes)。
|
||||
uv sync --dev --inexact --no-install-package paddlepaddle --python 3.12
|
||||
|
||||
# ── 判断变体 ──────────────────────────────────────────────────
|
||||
VARIANT="$(uv run --no-sync python scripts/paddle_env.py variant)"
|
||||
PADDLE_DIST="$(uv run --no-sync python scripts/paddle_env.py distribution)"
|
||||
if [[ "$VARIANT" == "missing" ]]; then
|
||||
printf '%s\n' '环境里没有安装 paddlepaddle,请先执行 uv sync。' >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$REQUIRE_GPU" == "1" && "$VARIANT" != "gpu" ]]; then
|
||||
cat >&2 <<EOF
|
||||
要求打 GPU 包,但当前环境装的是 ${VARIANT} 版 paddle(发行包 ${PADDLE_DIST})。
|
||||
请先换 GPU 版(版本必须同为 3.2.x):
|
||||
uv run --no-sync python scripts/install_paddle.py --gpu
|
||||
# (install_paddle.py 会自动识别显卡并选对 CUDA 通道)
|
||||
⚠️ RTX 50 系必须用 cu129,cu118 / cu126 不含 sm_120 内核,装了会在推理时报
|
||||
Mismatched GPU Architecture。40/30 系 cu126 / cu129 均可。
|
||||
详见 README「CPU / GPU 切换」。
|
||||
EOF
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 变体由构建环境里实际装的 paddle 决定,没有「强制」开关——
|
||||
# 产物里打进的就是当前环境的 paddle,改了名字也不会变,只会误导。
|
||||
BUILD_VARIANT="$VARIANT"
|
||||
|
||||
# 产物命名:CPU 版叫 ocr-server,GPU 版叫 ocr-server-gpu,都放在 dist 下,
|
||||
# 两个发布包一眼能分辨,也不会互相覆盖。
|
||||
DIST_PATH="dist"
|
||||
APP_NAME="ocr-server"
|
||||
if [[ "$BUILD_VARIANT" == "gpu" ]]; then
|
||||
APP_NAME="ocr-server-gpu"
|
||||
# 预置 auto 而不是 gpu:机器有卡就用卡、拿不到 CUDA 设备就回落 CPU,两种情况都不会把服务卡死。
|
||||
CONFIG_OVERRIDE="device=auto"
|
||||
else
|
||||
CONFIG_OVERRIDE=""
|
||||
fi
|
||||
RELEASE_DIR="$PROJECT_ROOT/$DIST_PATH/$APP_NAME"
|
||||
|
||||
printf '构建变体:%s(paddle 发行包 %s)\n' "$BUILD_VARIANT" "$PADDLE_DIST"
|
||||
printf '输出目录:%s\n' "$RELEASE_DIR"
|
||||
|
||||
# 只清当前变体的目录和 build,别把另一个变体的产物一起删了
|
||||
rm -rf build "$RELEASE_DIR"
|
||||
|
||||
# GPU 版必须额外收 nvidia 命名空间:paddlepaddle-gpu 的 CUDA 运行库(cudnn / cublas /
|
||||
# cufft 等)装在独立的 nvidia-* 发行包里,`--collect-all paddle` 收不到它们。
|
||||
# 漏收的后果实测是:引擎能加载、设备识别成 GPU,但第一次推理就报
|
||||
# `PreconditionNotMetError: cudnn64_9.dll ... error code is 126`。
|
||||
# 收进来的落点是 _internal/nvidia/<包>/bin,正好是 paddle 在 __init__.py 里
|
||||
# 用 os.add_dll_directory 寻找的路径(os.path.dirname(paddle.__file__)/../nvidia)。
|
||||
EXTRA_COLLECT=()
|
||||
if [[ "$BUILD_VARIANT" == "gpu" ]]; then
|
||||
EXTRA_COLLECT=(--collect-binaries nvidia)
|
||||
fi
|
||||
|
||||
uv run --no-sync pyinstaller --noconfirm --clean --onedir --name "$APP_NAME" \
|
||||
--distpath "$DIST_PATH" \
|
||||
--paths src \
|
||||
--collect-all paddleocr \
|
||||
--collect-all paddlex \
|
||||
--collect-all paddle \
|
||||
"${EXTRA_COLLECT[@]+"${EXTRA_COLLECT[@]}"}" \
|
||||
--collect-all cv2 \
|
||||
--collect-all PIL \
|
||||
--collect-all pyclipper \
|
||||
@@ -38,7 +121,7 @@ uv run pyinstaller --noconfirm --clean --onedir --name ocr-server \
|
||||
--hidden-import paddlex.inference.models.text_detection.processors \
|
||||
--copy-metadata paddlex \
|
||||
--copy-metadata paddleocr \
|
||||
--copy-metadata paddlepaddle \
|
||||
--copy-metadata "$PADDLE_DIST" \
|
||||
--copy-metadata imagesize \
|
||||
--add-data 'config.yaml:.' \
|
||||
--add-data 'http:http' \
|
||||
@@ -49,17 +132,27 @@ uv run pyinstaller --noconfirm --clean --onedir --name ocr-server \
|
||||
--hidden-import ocr_server.config \
|
||||
scripts/packaged_entry.py
|
||||
|
||||
cp -f config.yaml dist/ocr-server/config.yaml
|
||||
cp -a models dist/ocr-server/models
|
||||
chmod +x dist/ocr-server/ocr-server
|
||||
# shellcheck disable=SC2086
|
||||
uv run --no-sync python scripts/prepare_release_config.py config.yaml "$RELEASE_DIR/config.yaml" $CONFIG_OVERRIDE
|
||||
cp -a models "$RELEASE_DIR/models"
|
||||
chmod +x "$RELEASE_DIR/ocr-server"
|
||||
|
||||
BIN="$PROJECT_ROOT/dist/ocr-server/ocr-server"
|
||||
BIN="$RELEASE_DIR/$APP_NAME"
|
||||
if [[ ! -x "$BIN" ]]; then
|
||||
printf '打包失败:未生成 %s\n' "$BIN" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf '\nUbuntu 发布目录:%s\n' "$PROJECT_ROOT/dist/ocr-server"
|
||||
printf '%s\n' '启动:dist/ocr-server/ocr-server'
|
||||
TOTAL_MB="$(du -sm "$RELEASE_DIR" | cut -f1)"
|
||||
|
||||
printf '\nUbuntu 发布目录:%s\n' "$RELEASE_DIR"
|
||||
printf '变体:%s\n' "$BUILD_VARIANT"
|
||||
printf '%s\n' '启动:'"$RELEASE_DIR/$APP_NAME"
|
||||
printf '整个发布目录体积:%s MB\n' "$TOTAL_MB"
|
||||
printf '二进制 SHA256:%s\n' "$(sha256sum "$BIN" | cut -d' ' -f1)"
|
||||
if [[ "$BUILD_VARIANT" == "gpu" ]]; then
|
||||
printf '%s\n' '已把发布包里的 config.yaml 预置为 device: auto;有可用显卡时用 GPU,否则自动用 CPU。'
|
||||
else
|
||||
printf '%s\n' 'CPU 包。客户机若要用 GPU,需要改用 GPU 版分发包(用 paddlepaddle-gpu 环境重新打包)。'
|
||||
fi
|
||||
printf '%s\n' '(发布时要连 _internal 和 models 一起复制,不能只替换二进制)'
|
||||
|
||||
+90
-12
@@ -1,39 +1,102 @@
|
||||
# 打包 Windows 发布包(--onedir 目录形式)。
|
||||
#
|
||||
# CPU / GPU 两个变体由**构建环境里装的 paddlepaddle 版本**自动决定,不需要手动指定:
|
||||
# 装了 paddlepaddle -> CPU 包,dist\ocr-server\
|
||||
# 装了 paddlepaddle-gpu -> GPU 包,dist\ocr-server-gpu\,且 config.yaml 的 device 预置为 auto
|
||||
# GPU 包在装了 GPU 版 paddle 的机器上走显卡,拿不到 CUDA 设备时回落 CPU(见 README)。
|
||||
#
|
||||
# 关键参数说明,改动前请先读:
|
||||
# --collect-all paddle/paddlex/paddleocr Paddle 的原生库与配置必须整体收集,缺一个就跑不起来
|
||||
# --collect-all pyclipper/pypdfium2/shapely/bidi
|
||||
# 检测后处理与识别的必需依赖,漏了会在推理时报错
|
||||
# --copy-metadata * PaddleX 通过 importlib.metadata 检查依赖,
|
||||
# 缺元数据会误判「依赖未安装」
|
||||
# 缺元数据会误判「依赖未安装」。
|
||||
# ⚠️ paddle 的发行包名随变体变化(paddlepaddle /
|
||||
# paddlepaddle-gpu),写死会打不出包,
|
||||
# 所以由 scripts/paddle_env.py 动态取。
|
||||
# --additional-hooks-dir scripts 启用 scripts/hook-imagesize.py
|
||||
# --hidden-import imagesize 源码环境下按需导入,打包时必须显式声明
|
||||
#
|
||||
# 发布包为 --onedir:模型与 config.yaml 外置,便于替换;不要只替换 exe,_internal 也要一起更新。
|
||||
param(
|
||||
[switch]$Clean,
|
||||
# 输出目录,默认 dist。若 dist 被其它进程当作工作目录占用(Windows 会锁住该目录),
|
||||
# 可指定别处构建,再把内容搬回去,例如:
|
||||
# 断言当前环境必须是 GPU 版 paddle。不传时按实际安装的版本自动判断。
|
||||
[switch]$Gpu,
|
||||
# 输出根目录,默认 dist。变体决定其下的应用目录名:ocr-server / ocr-server-gpu。
|
||||
# 若 dist 被其它进程当作工作目录占用(Windows 会锁住该目录),可指定别处构建:
|
||||
# .\scripts\package-windows.ps1 -DistPath build\pyi-dist
|
||||
[string]$DistPath = "dist"
|
||||
[string]$DistPath
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$ProjectRoot = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $ProjectRoot
|
||||
$ReleaseDir = Join-Path $ProjectRoot "$DistPath\ocr-server"
|
||||
|
||||
# --inexact + --no-install-package paddlepaddle:只同步除 paddle 以外的依赖。
|
||||
# pyproject.toml 里声明的是 CPU 版 paddlepaddle,裸跑 uv sync 会「卸载
|
||||
# paddlepaddle-gpu 和全部 nvidia-* 运行库、装回 CPU 版」,把 GPU 环境悄悄冲掉;
|
||||
# 而单独用 --no-install-package 又会把 paddlepaddle-gpu 当多余包删掉。
|
||||
# 这两个参数合用才能保住当前装的 paddle 变体(实测 dry-run 为 no changes)。
|
||||
uv sync --dev --inexact --no-install-package paddlepaddle
|
||||
|
||||
# ── 判断变体 ──────────────────────────────────────────────────
|
||||
$Variant = (uv run --no-sync python scripts/paddle_env.py variant).Trim()
|
||||
$PaddleDist = (uv run --no-sync python scripts/paddle_env.py distribution).Trim()
|
||||
if ($Variant -eq "missing") {
|
||||
throw "环境里没有安装 paddlepaddle,请先执行 uv sync。"
|
||||
}
|
||||
if ($Gpu -and $Variant -ne "gpu") {
|
||||
throw @"
|
||||
要求打 GPU 包,但当前环境装的是 $Variant 版 paddle(发行包 $PaddleDist)。
|
||||
请先换 GPU 版(版本必须同为 3.2.x):
|
||||
uv run --no-sync python scripts/install_paddle.py --gpu
|
||||
# (install_paddle.py 会自动识别显卡并选对 CUDA 通道)
|
||||
⚠️ RTX 50 系必须用 cu129,cu118 / cu126 不含 sm_120 内核,装了会在推理时报
|
||||
Mismatched GPU Architecture。40/30 系 cu126 / cu129 均可。
|
||||
详见 README「CPU / GPU 切换」。
|
||||
"@
|
||||
}
|
||||
# 变体由构建环境里实际装的 paddle 决定,没有「强制」开关——
|
||||
# 产物里打进的就是当前环境的 paddle,改了名字也不会变,只会误导。
|
||||
$BuildVariant = $Variant
|
||||
# GPU 包预置 device: auto 而不是 gpu:客户机有卡就用卡、没卡就回落 CPU,
|
||||
# 两种情况都不会把服务卡死,日志里也会明确打出实际选了哪个。
|
||||
if ($BuildVariant -eq "gpu") { $ConfigOverride = "device=auto" } else { $ConfigOverride = $null }
|
||||
|
||||
if (-not $PSBoundParameters.ContainsKey("DistPath") -or [string]::IsNullOrWhiteSpace($DistPath)) {
|
||||
$DistPath = "dist"
|
||||
}
|
||||
# 产物命名:CPU 版叫 ocr-server,GPU 版叫 ocr-server-gpu,都放在 dist 下,
|
||||
# 两个发布包一眼能分辨,也不会互相覆盖。
|
||||
$AppName = if ($BuildVariant -eq "gpu") { "ocr-server-gpu" } else { "ocr-server" }
|
||||
$ReleaseDir = Join-Path $ProjectRoot "$DistPath\$AppName"
|
||||
|
||||
Write-Host "构建变体:$BuildVariant(paddle 发行包 $PaddleDist)"
|
||||
Write-Host "输出目录:$ReleaseDir"
|
||||
|
||||
if ($Clean) {
|
||||
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue build, dist
|
||||
# 只清当前变体的目录,别把另一个变体的产物一起删了
|
||||
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue build, $ReleaseDir
|
||||
}
|
||||
|
||||
uv sync --dev
|
||||
uv run pyinstaller --noconfirm --clean --onedir --name ocr-server `
|
||||
# GPU 版必须额外收 nvidia 命名空间:paddlepaddle-gpu 的 CUDA 运行库(cudnn / cublas /
|
||||
# cufft 等)装在独立的 nvidia-* 发行包里,`--collect-all paddle` 收不到它们。
|
||||
# 漏收的后果实测是:引擎能加载、设备识别成 GPU,但第一次推理就报
|
||||
# `PreconditionNotMetError: cudnn64_9.dll ... error code is 126`。
|
||||
# 收进来的落点是 _internal/nvidia/<包>/bin,正好是 paddle 在 __init__.py 里
|
||||
# 用 os.add_dll_directory 寻找的路径(os.path.dirname(paddle.__file__)/../nvidia)。
|
||||
$ExtraCollect = @()
|
||||
if ($BuildVariant -eq "gpu") {
|
||||
$ExtraCollect = @("--collect-binaries", "nvidia")
|
||||
}
|
||||
|
||||
uv run --no-sync pyinstaller --noconfirm --clean --onedir --name $AppName `
|
||||
--distpath $DistPath `
|
||||
--paths src `
|
||||
--collect-all paddleocr `
|
||||
--collect-all paddlex `
|
||||
--collect-all paddle `
|
||||
@ExtraCollect `
|
||||
--collect-all cv2 `
|
||||
--collect-all PIL `
|
||||
--collect-all pyclipper `
|
||||
@@ -43,7 +106,7 @@ uv run pyinstaller --noconfirm --clean --onedir --name ocr-server `
|
||||
--hidden-import paddlex.inference.models.text_detection.processors `
|
||||
--copy-metadata paddlex `
|
||||
--copy-metadata paddleocr `
|
||||
--copy-metadata paddlepaddle `
|
||||
--copy-metadata $PaddleDist `
|
||||
--copy-metadata imagesize `
|
||||
--add-data "config.yaml;." `
|
||||
--add-data "http;http" `
|
||||
@@ -54,20 +117,35 @@ uv run pyinstaller --noconfirm --clean --onedir --name ocr-server `
|
||||
--hidden-import ocr_server.config `
|
||||
scripts/packaged_entry.py
|
||||
|
||||
Copy-Item -Force config.yaml (Join-Path $ReleaseDir "config.yaml")
|
||||
$ConfigArgs = @(
|
||||
"scripts/prepare_release_config.py",
|
||||
"config.yaml",
|
||||
(Join-Path $ReleaseDir "config.yaml")
|
||||
)
|
||||
if ($ConfigOverride) { $ConfigArgs += $ConfigOverride }
|
||||
uv run --no-sync python @ConfigArgs
|
||||
|
||||
if (Test-Path models) {
|
||||
Copy-Item -Recurse -Force models (Join-Path $ReleaseDir "models")
|
||||
}
|
||||
|
||||
$Exe = Join-Path $ReleaseDir "ocr-server.exe"
|
||||
$Exe = Join-Path $ReleaseDir "$AppName.exe"
|
||||
if (-not (Test-Path $Exe)) {
|
||||
throw "打包失败:未生成 $Exe"
|
||||
}
|
||||
$Hash = (Get-FileHash -Algorithm SHA256 $Exe).Hash.ToLower()
|
||||
$TotalMB = (Get-ChildItem -Recurse -File $ReleaseDir | Measure-Object -Property Length -Sum).Sum / 1MB
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Windows 发布目录:$ReleaseDir"
|
||||
Write-Host "启动:$DistPath\ocr-server\ocr-server.exe"
|
||||
Write-Host "变体:$BuildVariant"
|
||||
Write-Host "启动:$DistPath\$AppName\$AppName.exe"
|
||||
Write-Host ("整个发布目录体积:{0:N1} MB" -f $TotalMB)
|
||||
Write-Host ("exe 体积:{0:N1} MB" -f ((Get-Item $Exe).Length / 1MB))
|
||||
Write-Host "exe SHA256:$Hash"
|
||||
if ($BuildVariant -eq "gpu") {
|
||||
Write-Host "已把发布包里的 config.yaml 预置为 device: auto;有可用显卡时用 GPU,否则自动用 CPU。"
|
||||
} else {
|
||||
Write-Host "CPU 包。客户机若要用 GPU,需要改用 GPU 版分发包(用 paddlepaddle-gpu 环境重新打包)。"
|
||||
}
|
||||
Write-Host "(发布时要连 _internal 和 models 一起复制,不能只替换 exe)"
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""报告当前构建环境里的 paddlepaddle 变体,供打包脚本选择 CPU/GPU 产物。
|
||||
|
||||
用法(打包脚本内部调用):
|
||||
python scripts/paddle_env.py variant -> cpu / gpu / missing
|
||||
python scripts/paddle_env.py distribution -> paddlepaddle / paddlepaddle-gpu
|
||||
|
||||
`distribution` 用于 --copy-metadata:PyPI 上 CPU 版发行包叫 paddlepaddle,
|
||||
GPU 版叫 paddlepaddle-gpu,写死任何一个在另一种环境下都会打包失败。
|
||||
"""
|
||||
|
||||
import importlib.metadata
|
||||
import importlib.util
|
||||
import sys
|
||||
|
||||
CPU_DISTRIBUTION = "paddlepaddle"
|
||||
GPU_DISTRIBUTION = "paddlepaddle-gpu"
|
||||
|
||||
|
||||
def detect_variant() -> str:
|
||||
if importlib.util.find_spec("paddle") is None:
|
||||
return "missing"
|
||||
import paddle
|
||||
|
||||
return "gpu" if paddle.device.is_compiled_with_cuda() else "cpu"
|
||||
|
||||
|
||||
def detect_distribution() -> str:
|
||||
"""返回实际安装的发行包名。"""
|
||||
for name in (CPU_DISTRIBUTION, GPU_DISTRIBUTION):
|
||||
try:
|
||||
importlib.metadata.version(name)
|
||||
except importlib.metadata.PackageNotFoundError:
|
||||
continue
|
||||
return name
|
||||
return ""
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 2 or sys.argv[1] not in {"variant", "distribution"}:
|
||||
print(__doc__.strip(), file=sys.stderr)
|
||||
return 2
|
||||
if sys.argv[1] == "variant":
|
||||
print(detect_variant())
|
||||
return 0
|
||||
distribution = detect_distribution()
|
||||
if not distribution:
|
||||
print("未找到已安装的 paddlepaddle / paddlepaddle-gpu", file=sys.stderr)
|
||||
return 1
|
||||
print(distribution)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,46 @@
|
||||
"""把 config.yaml 复制进发布目录,并按发布变体覆盖若干顶层配置项。
|
||||
|
||||
用法:
|
||||
python scripts/prepare_release_config.py <源> <目标> [键=值 ...]
|
||||
例如 GPU 包:
|
||||
python scripts/prepare_release_config.py config.yaml dist/ocr-server-gpu/config.yaml device=gpu
|
||||
|
||||
用 Python 而不是 shell 改写,是为了保持 UTF-8 编码——config.yaml 里有大量中文注释,
|
||||
PowerShell 5.1 的 Set-Content 默认按 ANSI 写,会把注释写坏。
|
||||
"""
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def apply_override(text: str, key: str, value: str) -> str:
|
||||
pattern = re.compile(rf"^{re.escape(key)}:.*$", re.MULTILINE)
|
||||
if pattern.search(text):
|
||||
return pattern.sub(f"{key}: {value}", text, count=1)
|
||||
# 源文件里没有这一项(例如被注释掉了),追加到末尾。
|
||||
return text.rstrip("\n") + f"\n{key}: {value}\n"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) < 3:
|
||||
print(__doc__.strip(), file=sys.stderr)
|
||||
return 2
|
||||
source, target = Path(sys.argv[1]), Path(sys.argv[2])
|
||||
text = source.read_text(encoding="utf-8")
|
||||
|
||||
for pair in sys.argv[3:]:
|
||||
if "=" not in pair:
|
||||
print(f"覆盖项格式应为 键=值,收到 {pair!r}", file=sys.stderr)
|
||||
return 2
|
||||
key, value = pair.split("=", 1)
|
||||
text = apply_override(text, key.strip(), value.strip())
|
||||
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(text, encoding="utf-8")
|
||||
print(f"已写入发布配置 {target}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+18
-2
@@ -2,15 +2,31 @@
|
||||
setlocal
|
||||
cd /d "%~dp0.."
|
||||
|
||||
rem 优先跑发布包:CPU 版 dist\ocr-server,GPU 版 dist\ocr-server-gpu。
|
||||
rem 两个都存在时用 CPU 版(GPU 包只有装了 GPU 版 paddle 的机器才能用,见 README)。
|
||||
rem 想直接跑 GPU 包就写全路径:dist\ocr-server-gpu\ocr-server-gpu.exe
|
||||
if exist "dist\ocr-server\ocr-server.exe" (
|
||||
"dist\ocr-server\ocr-server.exe"
|
||||
exit /b %errorlevel%
|
||||
)
|
||||
if exist "dist\ocr-server-gpu\ocr-server-gpu.exe" (
|
||||
"dist\ocr-server-gpu\ocr-server-gpu.exe"
|
||||
exit /b %errorlevel%
|
||||
)
|
||||
|
||||
rem 优先直接跑 .venv 里的入口脚本:直接执行不会触发 uv 的环境同步。
|
||||
rem 必须这样做的原因:uv run 会先按 pyproject.toml 同步环境,而 paddle 不在依赖里,
|
||||
rem 同步会把它整个移除(实测)。入口脚本名固定是 ocr-server,与变体无关。
|
||||
if exist ".venv\Scripts\ocr-server.exe" (
|
||||
".venv\Scripts\ocr-server.exe"
|
||||
exit /b %errorlevel%
|
||||
)
|
||||
|
||||
where uv >nul 2>nul
|
||||
if errorlevel 1 (
|
||||
echo 未找到打包程序,也未安装 uv。
|
||||
echo 未找到发布包,也未安装 uv。请先运行 scripts\package-windows.ps1 或 scripts/switch_env.py --cpu。
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
uv run ocr-server
|
||||
rem --no-sync 是必须的,理由同上。环境尚未建好时,请先运行一次 scripts/switch_env.py --cpu。
|
||||
uv run --no-sync ocr-server
|
||||
|
||||
+19
-5
@@ -1,15 +1,29 @@
|
||||
$ErrorActionPreference = "Stop"
|
||||
$ProjectRoot = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $ProjectRoot
|
||||
$PackagedExe = Join-Path $ProjectRoot "dist\ocr-server\ocr-server.exe"
|
||||
# 优先跑发布包:CPU 版 dist\ocr-server,GPU 版 dist\ocr-server-gpu。
|
||||
# 两个都存在时用 CPU 版(GPU 包只有装了 GPU 版 paddle 的机器才能用,见 README)。
|
||||
# 想直接跑 GPU 包就写全路径:dist\ocr-server-gpu\ocr-server-gpu.exe
|
||||
foreach ($Candidate in @("dist\ocr-server\ocr-server.exe", "dist\ocr-server-gpu\ocr-server-gpu.exe")) {
|
||||
$PackagedExe = Join-Path $ProjectRoot $Candidate
|
||||
if (Test-Path $PackagedExe) {
|
||||
& $PackagedExe
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
}
|
||||
|
||||
if (Test-Path $PackagedExe) {
|
||||
& $PackagedExe
|
||||
# 优先直接跑 .venv 里的入口脚本:直接执行不会触发 uv 的环境同步。
|
||||
# 必须这样做的原因:uv run 会先按 pyproject.toml 同步环境,而 paddle 不在依赖里,
|
||||
# 同步会把它整个移除(实测)。入口脚本名固定是 ocr-server,与变体无关。
|
||||
$VenvExe = Join-Path $ProjectRoot ".venv\Scripts\ocr-server.exe"
|
||||
if (Test-Path $VenvExe) {
|
||||
& $VenvExe
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
|
||||
if (-not (Get-Command uv -ErrorAction SilentlyContinue)) {
|
||||
throw "未找到打包程序,也未安装 uv。请先运行 scripts/package-windows.ps1 或安装 uv。"
|
||||
throw "未找到发布包,也未安装 uv。请先运行 scripts/package-windows.ps1 或 scripts/switch_env.py --cpu。"
|
||||
}
|
||||
|
||||
uv run ocr-server
|
||||
# --no-sync 是必须的,理由同上。环境尚未建好时,请先运行一次 scripts/switch_env.py --cpu。
|
||||
uv run --no-sync ocr-server
|
||||
|
||||
+18
-8
@@ -3,17 +3,27 @@ set -euo pipefail
|
||||
|
||||
cd "$(dirname "${BASH_SOURCE[0]}")/.."
|
||||
|
||||
if [[ -x dist/ocr-server/ocr-server ]]; then
|
||||
exec dist/ocr-server/ocr-server
|
||||
fi
|
||||
|
||||
if command -v uv >/dev/null 2>&1; then
|
||||
exec uv run ocr-server
|
||||
fi
|
||||
# 优先跑发布包:CPU 版 dist/ocr-server,GPU 版 dist/ocr-server-gpu。
|
||||
# 两个都存在时用 CPU 版(GPU 包只有装了 GPU 版 paddle 的机器才能用,见 README)。
|
||||
# 想直接跑 GPU 包就写全路径:dist/ocr-server-gpu/ocr-server-gpu
|
||||
for candidate in dist/ocr-server/ocr-server dist/ocr-server-gpu/ocr-server-gpu; do
|
||||
if [[ -x "$candidate" ]]; then
|
||||
exec "$candidate"
|
||||
fi
|
||||
done
|
||||
|
||||
# 优先直接跑 .venv 里的入口脚本:直接执行不会触发 uv 的环境同步。
|
||||
# 必须这样做的原因:`uv run` 会先按 pyproject.toml 同步环境,而 paddle 不在依赖里,
|
||||
# 同步会把它整个移除(实测)。注意入口脚本名固定是 ocr-server,
|
||||
# 由 pyproject.toml 的 [project.scripts] 决定,与 CPU/GPU 变体无关。
|
||||
if [[ -x .venv/bin/ocr-server ]]; then
|
||||
exec .venv/bin/ocr-server
|
||||
fi
|
||||
|
||||
printf '%s\n' '未找到 uv 或 .venv/bin/ocr-server,请先运行 scripts/package-ubuntu.sh 或安装项目依赖。' >&2
|
||||
if command -v uv >/dev/null 2>&1; then
|
||||
# --no-sync 是必须的,理由同上。环境尚未建好时,请先运行 scripts/switch_env.py --cpu。
|
||||
exec uv run --no-sync ocr-server
|
||||
fi
|
||||
|
||||
printf '%s\n' '未找到发布包、.venv/bin/ocr-server,也没装 uv。请先运行 scripts/package-ubuntu.sh 或 scripts/switch_env.py --cpu。' >&2
|
||||
exit 1
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
"""在 CPU / GPU 两套虚拟环境之间切换。
|
||||
|
||||
.venv CPU 环境
|
||||
.venv-gpu GPU 环境
|
||||
|
||||
两套环境**同时存在**,切换只是「用哪个跑哪个」,不需要卸载重装。之所以不做成
|
||||
一个环境来回切:paddlepaddle 与 paddlepaddle-gpu 互斥(都提供 `paddle` 顶层包和
|
||||
同一批文件),而且 GPU 版还要带上约 3GB 的 CUDA 运行库,反复装卸很浪费。
|
||||
|
||||
用法:
|
||||
python scripts/switch_env.py --cpu # 建立/更新 CPU 环境
|
||||
python scripts/switch_env.py --gpu # 建立/更新 GPU 环境(通道按显卡自动推荐)
|
||||
python scripts/switch_env.py --gpu --cuda cu126 # 指定 CUDA 通道
|
||||
python scripts/switch_env.py --list # 只看两套环境的现状,不做改动
|
||||
|
||||
建好之后怎么用(入口脚本名固定是 ocr-server,由 pyproject.toml 的 [project.scripts]
|
||||
决定,与 CPU/GPU 变体无关,变的只是所在的虚拟环境目录):
|
||||
启动服务(CPU):.venv\\Scripts\\ocr-server.exe
|
||||
启动服务(GPU):.venv-gpu\\Scripts\\ocr-server.exe
|
||||
打 GPU 包(产出 dist\\ocr-server-gpu\\):
|
||||
$env:UV_PROJECT_ENVIRONMENT=".venv-gpu"; .\\scripts\\package-windows.ps1
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
SCRIPTS_DIR = PROJECT_ROOT / "scripts"
|
||||
|
||||
CPU_VENV = ".venv"
|
||||
GPU_VENV = ".venv-gpu"
|
||||
|
||||
|
||||
def venv_python(relative: str) -> Path:
|
||||
if os.name == "nt":
|
||||
return PROJECT_ROOT / relative / "Scripts" / "python.exe"
|
||||
return PROJECT_ROOT / relative / "bin" / "python"
|
||||
|
||||
|
||||
def run(command: list[str], env: dict[str, str] | None = None) -> int:
|
||||
print(f" $ {' '.join(command)}", flush=True)
|
||||
return subprocess.run(command, cwd=PROJECT_ROOT, env=env, check=False).returncode
|
||||
|
||||
|
||||
def sync_venv(relative: str) -> int:
|
||||
"""把项目依赖同步进指定虚拟环境。
|
||||
|
||||
`--inexact` 不能省:paddle 不在 pyproject 的依赖里,普通 sync 会把手动装进去的
|
||||
paddlepaddle / paddlepaddle-gpu 当成「多余包」删掉。
|
||||
"""
|
||||
venv_path = (PROJECT_ROOT / relative).resolve()
|
||||
env = {**os.environ, "UV_PROJECT_ENVIRONMENT": str(venv_path)}
|
||||
print(f"[同步依赖] {relative}")
|
||||
return run(["uv", "sync", "--dev", "--inexact"], env=env)
|
||||
|
||||
|
||||
def describe(relative: str) -> str:
|
||||
python = venv_python(relative)
|
||||
if not python.is_file():
|
||||
return "未创建"
|
||||
probe = (
|
||||
"import importlib.metadata as md\n"
|
||||
"found = []\n"
|
||||
"for name in ('paddlepaddle', 'paddlepaddle-gpu'):\n"
|
||||
" try:\n"
|
||||
" found.append(f'{name}=={md.version(name)}')\n"
|
||||
" except md.PackageNotFoundError:\n"
|
||||
" pass\n"
|
||||
"if not found:\n"
|
||||
" print('未安装 paddle')\n"
|
||||
"else:\n"
|
||||
" import paddle\n"
|
||||
" cuda = paddle.device.is_compiled_with_cuda()\n"
|
||||
" count = paddle.device.cuda.device_count() if cuda else 0\n"
|
||||
" print(','.join(found) + f' | CUDA 可用:{cuda},GPU 数:{count}')\n"
|
||||
)
|
||||
result = subprocess.run(
|
||||
[str(python), "-c", probe],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
cwd=PROJECT_ROOT,
|
||||
check=False,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
return "paddle 状态未知(导入失败)"
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="在 CPU / GPU 两套虚拟环境之间切换")
|
||||
group = parser.add_mutually_exclusive_group()
|
||||
group.add_argument("--cpu", action="store_true", help=f"建立/更新 CPU 环境({CPU_VENV})")
|
||||
group.add_argument("--gpu", action="store_true", help=f"建立/更新 GPU 环境({GPU_VENV})")
|
||||
group.add_argument("--list", action="store_true", help="只查看现状")
|
||||
parser.add_argument("--cuda", choices=("cu118", "cu126", "cu129"), help="GPU 版的 CUDA 通道")
|
||||
parser.add_argument("--version", help="paddle 版本,默认 3.2.2")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.list or not (args.cpu or args.gpu):
|
||||
if not args.list:
|
||||
parser.print_help()
|
||||
return 2
|
||||
print(f"CPU 环境 {CPU_VENV:10} {describe(CPU_VENV)}")
|
||||
print(f"GPU 环境 {GPU_VENV:10} {describe(GPU_VENV)}")
|
||||
return 0
|
||||
|
||||
relative = CPU_VENV if args.cpu else GPU_VENV
|
||||
if args.cuda and args.cpu:
|
||||
print("--cuda 只在 --gpu 时有意义", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
if sync_venv(relative) != 0:
|
||||
return 1
|
||||
|
||||
print(f"[安装 paddle] {relative}")
|
||||
command = [
|
||||
sys.executable,
|
||||
str(SCRIPTS_DIR / "install_paddle.py"),
|
||||
"--python",
|
||||
str(venv_python(relative)),
|
||||
]
|
||||
command.append("--cpu" if args.cpu else "--gpu")
|
||||
if args.cuda:
|
||||
command += ["--cuda", args.cuda]
|
||||
if args.version:
|
||||
command += ["--version", args.version]
|
||||
if run(command) != 0:
|
||||
return 1
|
||||
|
||||
# 入口脚本名固定是 ocr-server(见 pyproject.toml 的 [project.scripts]),
|
||||
# 和所在环境是 CPU 还是 GPU 无关。
|
||||
executable = "Scripts\\ocr-server.exe" if os.name == "nt" else "bin/ocr-server"
|
||||
print(f"\n{relative} 就绪。")
|
||||
print(f" 启动:{relative}/{executable}")
|
||||
if args.cpu:
|
||||
print(' 打 CPU 包:直接运行 scripts/package-windows.ps1(产出 dist/ocr-server/)')
|
||||
else:
|
||||
print(
|
||||
" 打 GPU 包:设 UV_PROJECT_ENVIRONMENT=.venv-gpu 后运行 scripts/package-windows.ps1"
|
||||
"(产出 dist/ocr-server-gpu/)"
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user