本地部署离线翻译(LibreTranslate)
步骤 1:准备环境
条件准备:python3、pip、Git
检查当前版本
python3 --version#如果没有就安装(Ubuntu/CentOS 根据自己系统安装)
#Ubuntu / Debian 安装:
sudo apt update
sudo apt install -y software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install -y python3.10 python3.10-venv python3.10-dev python3-pip#CentOS / Rocky / RHEL 安装:
sudo yum install -y gcc openssl-devel bzip2-devel libffi-devel zlib-devel wget make
cd /usr/src
sudo wget https://www.python.org/ftp/python/3.10.14/Python-3.10.14.tgz
sudo tar xzf Python-3.10.14.tgz
cd Python-3.10.14
sudo ./configure --enable-optimizations
sudo make altinstall#安装完成执行
python3.10 --version
步骤 2:克隆 LibreTranslate 源码
git clone https://github.com/LibreTranslate/LibreTranslate.git
cd LibreTranslate
步骤 3:创建虚拟环境:
python3 -m venv venv
source venv/bin/activate
pip install -e . --no-cache-dir
步骤 4:安装语言模型
python3 scripts/install_models.py --load_only_lang_codes zh,en
步骤 5:创建启动脚本 保存为 libretranslate_start.sh
,并加执行权限 chmod +x libretranslate_start.sh
#!/bin/bashPORT=5000
TRANSLATE_DIR="/mnt/data/translate/LibreTranslate"
VENV_DIR="$TRANSLATE_DIR/venv"
LOG_FILE="$TRANSLATE_DIR/server.log"# 1. 检查端口是否已被占用
PID=$(lsof -ti tcp:$PORT)if [ -n "$PID" ]; thenecho "Port $PORT is in use (PID: $PID). Stopping existing process..."kill -9 $PIDsleep 2
fi# 2. 激活虚拟环境
source "$VENV_DIR/bin/activate"# 3. 启动 LibreTranslate 后台服务(使用 gunicorn)
cd "$TRANSLATE_DIR"
echo "Starting LibreTranslate on port $PORT..."
nohup gunicorn -c scripts/gunicorn_conf.py main:app > "$LOG_FILE" 2>&1 &
echo "LibreTranslate started. Logs at: $LOG_FILE"
ps:可能启动会遇到一些问题
1.nohup: failed to run command 'gunicorn': No such file or directory
解决方案:安装 gunicorn 到虚拟环境中:
source /mnt/data/translate/LibreTranslate/venv/bin/activate #根据自己安装目录更改目录
pip install gunicorn
2.Worker (pid:1576427) exited with code 4 [2025-05-27 08:13:00 +0000] [1576422] [ERROR] Shutting down: Master [2025-05-27 08:13:00 +0000] [1576422] [ERROR] Reason: App failed to load.
进入安装目录添加类wsgi.py
from libretranslate.main import get_args
from libretranslate.app import create_appargs = get_args()
app = create_app(args)
3.出现监听的端口是8080,而不是5000
修改配置文件 scripts/gunicorn_conf.py
#在import下方bind端口
bind = "0.0.0.0:5000"
使用启动命令
nohup gunicorn -c scripts/gunicorn_conf.py wsgi:app > server.log 2>&1 &
最后接口测试:
curl -X POST http://localhost:5000/translate \
-H "Content-Type: application/json" \
-d '{"q": "你好,世界", "source": "zh", "target": "en"}'
{"translatedText":"Hello, world"}