├── .gitignore ├── .local └── .gitignore ├── LICENSE ├── README.md ├── README_EN.md ├── requirements.txt ├── set.ini ├── start.py └── test.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | .git 3 | .github 4 | .idea 5 | dev 6 | venv 7 | dist 8 | source 9 | build 10 | __pycache__ 11 | *.spec 12 | *.ui 13 | *.bak 14 | *.7z 15 | *.zip 16 | db -------------------------------------------------------------------------------- /.local/.gitignore: -------------------------------------------------------------------------------- 1 | cache 2 | share -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 okmyworld 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 本项目不再更新,请使用上游项目 2 | 3 | https://github.com/LibreTranslate/LibreTranslate 4 | 5 | ---- 6 | ---- 7 | 8 | 9 | # Offine-Text-Translate 本地离线文字翻译 10 | 11 | 支持多语言的本地离线文字翻译Api工具 12 | 13 | > 14 | > 15 | > 本项目是基于 [开源项目LibreTranslate](https://github.com/LibreTranslate/LibreTranslate) 的再封装,目的是提供一个容易在本地机器上直接部署的翻译Api服务,无需docker,并提供 Windows 预编译exe包,不必部署,双击可用,方便新手和小白使用。 16 | > 17 | > 第一次启动需要下载模型,后续即可离线运行 18 | > 19 | > 如果你想使用原生LibreTranslate项目或想部署在docker,请访问 https://github.com/LibreTranslate/LibreTranslate 20 | > 21 | 22 | ![image](https://github.com/jianchang512/ott/assets/3378335/97ff6814-4480-4238-b37b-62f84c42204d) 23 | 24 | 25 | ## Windows预编译exe下载使用 26 | 27 | 1. [点击下载window预编译包](https://github.com/jianchang512/ott/releases/download/) ,解压到无空格的英文目录下,双击 start.exe 28 | 29 | 2. 第一次启动后会自动下载模型,如果你无法打开 `https://raw.githubusercontent.com` 这个地址,必须在 set.ini 中 `PROXY=` 设置代理地址,否则无法下载。当然你也可以选择从百度网盘下载已打包好的模型,解压后将里面的 **.local** 文件夹复制到本软件目录下,覆盖同名文件夹 '.local', [点击去百度网盘下载模型](https://pan.baidu.com/s/1SZHtoTXDIVNG8xlOgANIow?pwd=33gn) 30 | 31 | 32 | 3. 可以自己编写程序请求该Api服务,实现替代百度翻译等功能,或者填写到一些需要翻译功能的软件中,比如若要用在[视频翻译配音软件](https://github.com/jianchang512/pyvideotrans) 中,在软件菜单-设置-OTT中填写 服务器地址和端口即可,默认地址是 `http://127.0.0.1:9911` 33 | 34 | ## Window上源码部署 35 | 36 | 0. 首先到 python.org 网站下载 python3.9+ 版本并安装,建议安装 3.10,在安装时仔细查看,选中 “Add ... Path”复选框,以方便后续使用。 37 | 38 | 1. 安装window git客户端,[点击去下载git](https://git-scm.com/download/win) ,选择下载 64-bit Git for Windows Setup,下载后双击安装,一路下一步直到完成 39 | 40 | 2. 创建一个空目录,比如在 D盘 下创建目录 ott,然后进入该目录 `D:/ott`,在文件夹地址栏输入 `cmd` 后回车,在打开的cmd黑窗口中输入 `git clone https://github.com/jianchang512/ott .` 回车执行. 41 | 42 | 3. 创建虚拟环境,在刚刚的cmd窗口中继续输入命令 `python -m venv venv` 回车 43 | 44 | > 此处注意:如果提示 "python 不是内部或外部命令,也不是可运行的程序" ,说明 第0步 安装python时未选中复选框,重新双击已下载的 Python安装包,选择“Modify”,然后注意选中“Add ... Path”。 45 | > 46 | > 重新安装python完毕后,**必须关闭已打开的cmd窗口**,否则可能还是提示命令未找到,然后进入`D:/ott`,地址栏输入`cmd`回车,再重新执行`python -m venv venv` 47 | > 48 | 49 | 4. 上步命令执行成后,继续输入 `.\venv\scripts\activate` 回车,再执行 `pip install -r requirements.txt --no-deps`, 如果提示“not found version xxx”,请将将镜像源改为pip官方或者阿里云镜像 50 | 51 | 5. 如果需要启用cuda加速翻译,则继续分别执行 52 | 53 | `pip uninstall -y torch` 54 | 55 | `pip install torch==2.1.2 --index-url https://download.pytorch.org/whl/cu121` 56 | 57 | 6. 在set.ini中设置代理 PROXY=代理地址,比如如果你的代理地址是 `http://127.0.0.1:10189`,那么填写后`PROXY=http://127.0.0.1:10189` 58 | 59 | 7. 执行启动服务命令,`python start.py` 60 | 61 | ## Mac 或 Linux 部署 62 | 63 | 0. 先确认是否安装了正确的python版本3.9+和git, `python -V` or `python3 -V` 64 | 65 | 1. 创建空目录并进入,比如 `/data/ott && cd /data/ott`, 然后拉取源码 `git clone https://github.com/jianchang512/ott .` 66 | 67 | 2. 创建虚拟环境并激活 `python3 -m venv venv && . ./venv/bin/activate` 68 | 69 | 3. 安装依赖,`pip3 install -r requirements.txt --no-deps`,如果提示“not found”,同样将镜像改为 pip官方或阿里云镜像 70 | 71 | 4. 如果要启用cuda加速翻译,则继续执行 72 | 73 | `pip3 uninstall -y torch` 74 | 75 | `pip3 install torch==2.1.2 --index-url https://download.pytorch.org/whl/cu121` 76 | 77 | 5. 在 she.ini中设置代理地址 78 | 79 | 6. 启动服务 `python3 start.py` 80 | 81 | 注意如果你的python执行命令不是`python3`,上面命令中的 python3需替换为对应的命令比如 `python` 82 | 83 | ## Api接口使用 84 | 85 | 86 | 假如你部署的地址和端口是 `http://127.0.0.1:9911` 87 | 88 | API地址:`http://127.0.0.1:9911/translate` 89 | 90 | 支持的语言代码: zh=中文简 zt=中文繁 en=英语 fr=法语 de=德语 ja=日语 ko=韩语 ru=俄语 es=西班牙语 th=泰国语 it=意大利语 pt=葡萄牙语 ar=阿拉伯语 tr=土耳其语 hi=印度语 91 | 92 | 请求方法:POST 93 | 94 | 请求数据: q=待翻译文本,source=文本原始语言代码可填auto自动识别,target=要翻译到的目标语言代码 95 | 96 | 返回数据: 返回json数据,正确时 `{translatedText:"翻译后结果"}`,出错时`{error:"错误原因"}` 97 | 98 | 99 | **python requests 请求示例** 100 | 101 | ``` 102 | 103 | import requests 104 | 105 | result=requests.post("http://127.0.0.1:9911/translate",json={"q":"你好啊我的朋友","source":"zh","target":"en"}) 106 | print(result.json()) 107 | 108 | # 输出如下 109 | {'translatedText': 'Hello, my friend'} 110 | 111 | # 错误时返回 112 | {'error':'错误原因'} 113 | 114 | ``` 115 | 116 | 117 | 118 | **Javascripts fetch请求** 119 | ``` 120 | fetch("http://127.0.0.1:9911/translate", { 121 | method: "POST", 122 | body: JSON.stringify({ 123 | q: "Hello!", // 请求翻译的文本 124 | source: "en",//原始语言,或者填写 'auto' 自动检测 125 | target: "zh"//目标语言 126 | }), 127 | headers: { "Content-Type": "application/json" } 128 | }); 129 | 130 | // 返回json相应 131 | { 132 | "translatedText": "你好!" // translatedText 字段中是翻译后的文本 133 | } 134 | 135 | # 错误时返回 136 | {'error':'错误原因'} 137 | ``` 138 | 139 | **Javascripts jQuery ajax 请求** 140 | 141 | ``` 142 | $.post("http://127.0.0.1:9911/translate", { 143 | q: "Hello!", // 请求翻译的文本 144 | source: "en",//原始语言,或者填写 'auto' 自动检测 145 | target: "zh"//目标语言 146 | }, 147 | function(res){ 148 | console.log(res) 149 | } 150 | ); 151 | 152 | // 返回json相应 153 | { 154 | "translatedText": "你好!" // translatedText 字段中是翻译后的文本 155 | } 156 | 157 | # 错误时返回 158 | 159 | {'error':'错误原因'} 160 | 161 | ``` 162 | 163 | **php curl** 164 | 165 | ``` 166 | 167 | $data = array( 168 | 'q' => 'Hello', 169 | 'source' => 'auto', 170 | 'target' => 'zh' 171 | ); 172 | 173 | $json = json_encode($data); 174 | $url = 'http://127.0.0.1:9911/translate'; 175 | $ch = curl_init($url); 176 | 177 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 178 | curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 179 | curl_setopt($ch, CURLOPT_POSTFIELDS, $json); 180 | curl_setopt($ch, CURLOPT_HTTPHEADER, array( 181 | 'Content-Type: application/json', 182 | 'Content-Length: ' . strlen($json) 183 | )); 184 | 185 | $response = curl_exec($ch); 186 | if(curl_errno($ch)) { 187 | echo 'Error: ' . curl_error($ch); 188 | } else { 189 | echo $response; 190 | } 191 | curl_close($ch); 192 | 193 | #返回 194 | { 195 | "translatedText": "你好!" // translatedText 字段中是翻译后的文本 196 | } 197 | 198 | # 错误时返回 199 | {'error':'错误原因'} 200 | 201 | ``` 202 | 203 | 204 | ## 对 argostranslate 的修改 205 | 206 | 207 | 208 | 1. 修改了 `\venv\Lib\site-packages\argostranslate\networking.py` 的 get 方法,当下载失败时,抛出异常,以实现下载模式出错时提醒使用代理 209 | 210 | 211 | ``` 212 | def get(url: str, retry_count: int = 3) -> bytes | None: 213 | """Downloads data from a url and returns it 214 | 215 | Args: 216 | url: The url to download (http, https) 217 | retry_count: The number of retries to attempt if the initial download fails. 218 | If retry_count is 0 the download will only be attempted once. 219 | 220 | Returns: 221 | The downloaded data, None is returned if the download fails 222 | """ 223 | if get_protocol(url) not in supported_protocols: 224 | return None 225 | info(f"Get {url}") 226 | print(f'{url=}') 227 | download_attempts_count = 0 228 | 229 | while download_attempts_count <= retry_count: 230 | try: 231 | req = urllib.request.Request( 232 | url, 233 | headers={"User-Agent": USER_AGENT}, 234 | ) 235 | response = urllib.request.urlopen(req) 236 | data = response.read() 237 | info(f"Got {url}") 238 | return data 239 | except Exception as err: 240 | download_attempts_count += 1 241 | # 增加抛出异常 ++ 242 | raise Exception('download error') 243 | error(err) 244 | # 增加抛出异常 ++ 245 | raise Exception('download error') 246 | return None 247 | ``` 248 | 249 | 2. `\venv\Lib\site-packages\argostranslate\package.py` 250 | 251 | 注释掉无法连接raw.githubusercontent.com时的报错,已在入口文件做了处理 252 | 253 | 254 | ``` 255 | def update_package_index(): 256 | """Downloads remote package index""" 257 | with package_lock: 258 | try: 259 | response = urllib.request.urlopen(settings.remote_package_index) 260 | except Exception as err: 261 | # 注释掉错误输出,已在入口文件获取了index.json,此处如果无法连接则不再输出错误,避免造成小白迷惑 262 | #error(err) -- 263 | return 264 | data = response.read() 265 | with open(settings.local_package_index, "wb") as f: 266 | f.write(data) 267 | ``` 268 | 269 | 270 | ## CUDA 加速支持 271 | 272 | **安装CUDA工具** [详细安装方法](https://juejin.cn/post/7318704408727519270) 273 | 274 | 275 | 安装好CUDA后,如果有问题,执行 `pip uninstall -y torch`,然后执行`pip install torch==2.1.2 --index-url https://download.pytorch.org/whl/cu121`。 276 | 277 | 278 | 有时会遇到“cublasxx.dll不存在”的错误, 或者未遇到此错误,并且CUDA配置正确,但始终出现识别错误,需要下载 cuBLAS,然后将dll文件复制到系统目录下 279 | 280 | [点击下载 cuBLAS](https://github.com/jianchang512/stt/releases/download/0.0/cuBLAS_win.7z),解压后将里面的dll文件复制到 C:/Windows/System32下 281 | 282 | 283 | ## 基于以下开源项目 284 | 285 | 286 | 1. https://github.com/LibreTranslate/LibreTranslate 287 | 288 | 2. https://github.com/argosopentech/argos-translate 289 | -------------------------------------------------------------------------------- /README_EN.md: -------------------------------------------------------------------------------- 1 | [简体中文](./README.md) 2 | 3 | # Offine-Text-Translate Local Offline Text Translation 4 | 5 | Supports multi-language local offline text translation Api tool 6 | 7 | > 8 | > 9 | > This project is a re-encapsulation based on [Open Source Project LibreTranslate](https://github.com/LibreTranslate/LibreTranslate), the purpose is to provide a translation Api service that can be easily directly deployed on local machines without the need for docker, and provide Windows precompiled exe package, no need to deploy, can be used by double-clicking, convenient for beginners and non-tech savvy users. 10 | > 11 | > The first launch needs to download the model, and subsequent operation can be offline. 12 | > 13 | > If you want to use the original LibreTranslate project or want to deploy on docker, please visit https://github.com/LibreTranslate/LibreTranslate 14 | > 15 | 16 | ![image](https://github.com/jianchang512/ott/assets/3378335/2965176e-8f03-49bb-803e-2fdefbadfe7e) 17 | 18 | 19 | ## Windows precompiled exe Download and Use 20 | 21 | 1. [Click to download the Windows precompiled package](https://github.com/jianchang512/ott), unzip to an English directory without spaces, and double-click start.exe. 22 | 23 | 2. After the first launch, the model will be automatically downloaded. If you can't open `https://raw.githubusercontent.com`, you must set the proxy address in `PROXY=` in set.ini, otherwise, it can't be downloaded. Of course, you can also choose to download the packaged model from Baidu network disk, unzip and overwrite the **.local** folder inside to the root directory of this software, [click to download the model from Baidu network disk](https://pan.baidu.com/s/1h5upbQIQw3LmUU6-3-YRbw?pwd=72bj). 24 | 25 | 26 | 3. You can write your own program to request this Api service, to implement Baidu translation and other functions, or fill in some software that needs translation functions. If you want to use it in [video translation dubbing software](https://github.com/jianchang512/pyvideotrans) , fill in the server address and port in OTT in the software menu. The default address is `http://127.0.0.1:9911`. 27 | 28 | ## Windows up Source Code Deployment 29 | 30 | 0. First go to the python.org website to download the python3.9+ version and install it, it is recommended to install 3.10. When installing, carefully check and tick the "Add ... Path" checkbox for convenience. 31 | 32 | 1. Install Windows git client, [click to download git](https://git-scm.com/download/win), select to download 64-bit Git for Windows Setup, double-click to install, follow through steps until completion. 33 | 34 | 2. Create an empty directory, such as the ott directory under the D drive, then enter the directory `D:/ott`, enter `cmd` in the address bar and press enter, in the opened cmd black window, enter `git clone https://github.com/jianchang512/ott .` and press enter. 35 | 36 | 3. Create a virtual environment, continue to enter the command `python -m venv venv` in the cmd window and press enter. 37 | 38 | > Pay attention here: If it prompts "python is not an internal or external command, also not a runnable program", it indicates that the checkbox was not ticked when installing python in step 0. Click the downloaded Python installer again, choose "Modify", and make sure to tick "Add ... Path". 39 | > 40 | > After reinstalling python, **You must close the opened cmd window**, then enter`D:/ott`, enter`cmd` in the address bar and press enter, then execute `python -m venv venv` 41 | > 42 | 43 | 4. After executing the command in the previous step, continue to enter `.\venv\scripts\activate` and press enter, then execute `pip install -r requirements.txt --no-deps`. If it prompts "not found version xxx", please change the mirror source to pip official or Aliyun mirror. 44 | 45 | 5. If you need to enable cuda acceleration translation, continue to execute 46 | 47 | `pip uninstall -y torch` 48 | 49 | `pip install torch==2.1.2 --index-url https://download.pytorch.org/whl/cu121` 50 | 51 | 6. Set proxy address in set.ini PROXY=proxy address, for example if your proxy address is `http://127.0.0.1:10189`, then you should fill in `PROXY=http://127.0.0.1:10189` 52 | 53 | 7. Execute the command to start the service, `python start.py` 54 | 55 | ## Mac or Linux Deployment 56 | 57 | 0. First confirm whether the correct version python3.9+ and git is installed, `python -V` or `python3 -V` 58 | 59 | 1. Create an empty directory and enter, for example `/data/ott && cd /data/ott`, then pull the source code `git clone https://github.com/jianchang512/ott .` 60 | 61 | 2. Create a virtual environment and activate it `python3 -m venv venv && . ./venv/bin/activate` 62 | 63 | 3. Install dependency, `pip3 install -r requirements.txt --no-deps`. If it prompts "not found ", change the mirror to pip official or Aliyun mirror likewise. 64 | 65 | 4. If cuda acceleration translation needs to be enabled, continue to execute 66 | 67 | `pip3 uninstall -y torch` 68 | 69 | `pip3 install torch==2.1.2 --index-url https://download.pytorch.org/whl/cu121` 70 | 71 | 5. Set proxy address in she.ini 72 | 73 | 6. Start service `python3 start.py` 74 | 75 | Please note if your python execution command is not`python3`, the python3 in the above commands should be replaced with your corresponding command. 76 | 77 | ## Api Interface Usage 78 | 79 | Assume your deployment address and port is `http://127.0.0.1:9911` 80 | 81 | 82 | API address: `http://127.0.0.1:9911/translate` 83 | 84 | 85 | Language code: zh=Simplified Chinese / zt=Traditional Chinese / en=English / fr=French / de=German / ja=Japanese / ko=Korean / ru=Russian / es=Spanish / th=Thai / it=Italian / pt=Portuguese / ar=Arabic / tr=Turkish / hi=Hindi 86 | 87 | 88 | Request method: POST 89 | 90 | Request data: `q`=text to be translated, `source`=text original language code can be filled in auto automatic recognition, `target`=target language code to be translated to 91 | 92 | Return data: Return JSON data, when correct, '{translatedText: "translated result'} ', when error,' {error:" error reason '}'` 93 | 94 | 95 | **Python requests request example** 96 | 97 | ``` 98 | 99 | import requests 100 | 101 | result=requests.post("http://127.0.0.1:9911/translate",json={"q":"Hello, my friend","source":"en","target":"zh"}) 102 | print(result.json()) 103 | 104 | #The output is as follows 105 | {'translatedText': '你好,我的朋友'} 106 | 107 | #When error returns 108 | {'error':'Error cause'} 109 | 110 | ``` 111 | 112 | 113 | 114 | **JavaScripts fetch request** 115 | 116 | ``` 117 | fetch("http://127.0.0.1:9911/translate", { 118 | method: "POST", 119 | body: JSON.stringify({ 120 | q: "Hello!", // The text to translate 121 | source: "en",// original language, or 'auto' for auto detect 122 | target: "zh"// target language 123 | }), 124 | headers: { "Content-Type": "application/json" } 125 | }); 126 | 127 | // Returns json response 128 | { 129 | "translatedText": "你好!" // The translated text is in the transloatedText field 130 | } 131 | 132 | #When error returns 133 | {'error':'Error cause'} 134 | ``` 135 | 136 | **JavaScripts jQuery ajax request** 137 | 138 | ``` 139 | $.post("http://127.0.0.1:9911/translate", { 140 | q: "Hello!", // The text to translate 141 | source: "en",// original language, or 'auto' for auto detect 142 | target: "zh"// target language 143 | }, 144 | function(res){ 145 | console.log(res) 146 | } 147 | ); 148 | 149 | // Returns json response 150 | { 151 | "translatedText": "你好!" // The translated text is in the translatedText field 152 | } 153 | 154 | #When error returns 155 | 156 | {'error':'Error cause'} 157 | 158 | ``` 159 | 160 | **PHP curl** 161 | 162 | ``` 163 | 164 | $data = array( 165 | 'q' => 'Hello', 166 | 'source' => 'auto', 167 | 'target' => 'zh' 168 | ); 169 | 170 | $json = json_encode($data); 171 | $url = 'http://127.0.0.1:9911/translate'; 172 | $ch = curl_init($url); 173 | 174 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 175 | curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 176 | curl_setopt($ch, CURLOPT_POSTFIELDS, $json); 177 | curl_setopt($ch, CURLOPT_HTTPHEADER, array( 178 | 'Content-Type: application/json', 179 | 'Content-Length: ' . strlen($json) 180 | )); 181 | 182 | $response = curl_exec($ch); 183 | if(curl_errno($ch)) { 184 | echo 'Error: ' . curl_error($ch); 185 | } else { 186 | echo $response; 187 | } 188 | curl_close($ch); 189 | 190 | #Return 191 | { 192 | "translatedText": "你好!" // The translated text is in the translatedText field 193 | } 194 | 195 | #When error returns 196 | {'error':'Error cause'} 197 | 198 | ``` 199 | 200 | 201 | 202 | ## Modifications to Argostranslate 203 | 204 | 1. Modified the get method in `\venv\Lib\site-packages\argostranslate\networking.py`. When the download fails, an exception is thrown to remind the user to use a proxy in case of a download mode error. 205 | 206 | 207 | ``` 208 | def get (url: str, retry_count: int = 3) - > bytes | None: 209 | """Downloads data from a url and returns it 210 | 211 | Args: 212 | url: The url to download (http, https) 213 | retry_count: The number of retries to attempt if the initial download fails. 214 | If retry_count is 0 the download will only be attempted once. 215 | 216 | Returns: 217 | The downloaded data, None is returned if the download fails 218 | """ 219 | if get_protocol (url) not in supported_protocols: 220 | return None 221 | info (f"Get {url}") 222 | print (f'{url=}') 223 | download_attempts_count = 0 224 | 225 | while download_attempts_count <= retry_count: 226 | try: 227 | req = urllib.request.Request( 228 | url, 229 | headers={"User-Agent": USER_AGENT}, 230 | ) 231 | response = urllib.request.urlopen(req) 232 | data = response.read() 233 | info (f"Got {url}") 234 | return data 235 | except Exception as err: 236 | download_attempts_count += 1 237 | # Add exception throw ++ 238 | raise Exception ('download error') 239 | error (err) 240 | # Add exception throw ++ 241 | raise Exception ('download error') 242 | return None 243 | ``` 244 | 245 | 2. `\venv\Lib\site-packages\argostranslate\package.py` 246 | 247 | Comment out the error when you can't connect to raw.github.com. This has been handled in the entry file. 248 | 249 | 250 | ``` 251 | def update_package_index (): 252 | """Download remote package index""" 253 | with package_lock : 254 | try : 255 | response = urllib. request. urlopen (settings. remote_package_index) 256 | except Exception as err : 257 | # Comment out the error output, the index. json has been obtained in the entry file, if it can't be connected here, it will not output the error, to avoid causing confusion for the layman 258 | #error (err) -- 259 | return 260 | data = response. read () 261 | with open (settings. local_package_index, "wb") as f : 262 | f. write (data) 263 | ``` 264 | 265 | ## CUDA Acceleration Support 266 | 267 | **Install CUDA Tools** [Detailed Installation Method](https://juejin.cn/post/7318704408727519270) 268 | 269 | 270 | After installing CUDA, if there are problems, run `pip uninstall -y torch`, and then run `pip install torch==2.1.2 --index-url https://download.pytorch.org/whl/cu121`. 271 | 272 | 273 | Sometimes you will encounter an error that "cublasxx.dll does not exist", or even if this error does not occur, and CUDA is configured correctly, but the recognition is always wrong, you need to download cuBLAS, and then copy the dll file to the system directory 274 | 275 | [Click to Download cuBLAS](https://github.com/jianchang512/stt/releases/download/0.0/cuBLAS_win.7z), unzip and copy the dll files to C:/Windows/System32 276 | 277 | 278 | ## Based on the following open source project 279 | 280 | 1. https://github.com/LibreTranslate/LibreTranslate 281 | 282 | 2. https://github.com/argosopentech/argos-translate 283 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | altgraph 2 | appdirs==1.4.4 3 | APScheduler 4 | argos-translate-files 5 | argostranslate 6 | async-timeout==4.0.3 7 | Babel==2.14.0 8 | beautifulsoup4==4.9.3 9 | cachelib==0.10.2 10 | certifi==2023.11.17 11 | charset-normalizer==3.3.2 12 | click==8.1.7 13 | colorama==0.4.6 14 | commonmark==0.9.1 15 | ctranslate2==3.20.0 16 | Deprecated==1.2.14 17 | expiringdict==1.2.2 18 | filelock==3.13.1 19 | fsspec==2023.4.0 20 | idna==3.6 21 | importlib-resources==6.1.1 22 | itsdangerous==2.1.2 23 | joblib==1.3.2 24 | langdetect 25 | LexiLang 26 | libretranslate 27 | limits==3.7.0 28 | lxml==5.1.0 29 | MarkupSafe==2.1.4 30 | Morfessor==2.0.6 31 | mpmath==1.3.0 32 | networkx==3.2.1 33 | numpy==1.26.3 34 | packaging==23.1 35 | pefile==2023.2.7 36 | polib==1.1.1 37 | prometheus-client==0.15.0 38 | protobuf==4.25.2 39 | Pygments==2.17.2 40 | pyinstaller==6.3.0 41 | pyinstaller-hooks-contrib==2024.0 42 | pytz==2023.3.post1 43 | pywin32-ctypes==0.2.2 44 | PyYAML==6.0.1 45 | redis==4.4.4 46 | regex==2023.12.25 47 | requests==2.31.0 48 | rich==12.6.0 49 | sacremoses==0.0.53 50 | sentencepiece==0.1.99 51 | six==1.16.0 52 | soupsieve==2.5 53 | stanza==1.1.1 54 | sympy==1.12 55 | torch==2.1.2 56 | tqdm==4.66.1 57 | translatehtml==1.5.2 58 | typing_extensions==4.9.0 59 | tzdata==2023.4 60 | tzlocal==5.2 61 | urllib3==2.1.0 62 | waitress==2.1.2 63 | Werkzeug==2.3.8 64 | wrapt==1.16.0 65 | -------------------------------------------------------------------------------- /set.ini: -------------------------------------------------------------------------------- 1 | ;第一启动需要下载模型,国内地区需要填写代理地址,比如 v2ray默认地址是 http://127.0.0.1:10809 clash默认http://127.0.0.1:7890 2 | PROXY= 3 | ;要绑定到的地址,本机127.0.0.1 或者 192.168.等局域网ip等,默认127.0.0.1 4 | HOST=127.0.0.1 5 | ;绑定到的端口 6 | PORT=9911 7 | ;使用到的语言模型, zh=中文简 zt=中文繁 en=英语 fr=法语 de=德语 ja=日语 ko=韩语 ru=俄语 es=西班牙语 th=泰国语 it=意大利语 pt=葡萄牙语 ar=阿拉伯语 tr=土耳其语 hi=印度语 8 | ;如果用不到的语言可以删掉 9 | LANG=zh,en,zt,fr,de,ja,ko,ru,es,th,it,pt,ar,tr,hi 10 | -------------------------------------------------------------------------------- /start.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import sys 4 | import requests 5 | ROOT = os.getcwd() 6 | # 初始化代理和数据地址 7 | def init(sets): 8 | if "PROXY" in sets and sets['PROXY']: 9 | os.environ['http_proxy']='http://'+sets["PROXY"].replace("http://",'http://').strip() 10 | os.environ['https_proxy']='http://'+sets["PROXY"].replace("http://",'http://').strip() 11 | os.environ['SNAP']=ROOT 12 | os.environ['SNAP_USER_DATA']=ROOT 13 | #解析 set.ini 14 | def parse_init(): 15 | settings = {} 16 | file = os.path.join(ROOT, 'set.ini') 17 | if os.path.exists(file): 18 | with open(file, 'r', encoding="utf-8") as f: 19 | # 遍历.ini文件中的每个section 20 | for it in f.readlines(): 21 | it = it.strip() 22 | if it.startswith(';') or it.startswith('#'): 23 | continue 24 | key,value = it.split('=', 1) 25 | # 遍历每个section中的每个option 26 | key = key.strip() 27 | value = value.strip() 28 | if re.match(r'^\d+$', value): 29 | settings[key] = int(value) 30 | elif value.lower() == 'true': 31 | settings[key] = True 32 | elif value.lower() == 'false': 33 | settings[key] = False 34 | else: 35 | tmp = str(value.lower()).replace(',',',') 36 | settings[key]=tmp 37 | return settings 38 | settings=parse_init() 39 | init(settings) 40 | 41 | def testgithub(): 42 | # 判断能否连通 raw.githubusercontent.com 43 | # 如果存在 index.json则视为连通, 也就是仅需第一次下载模式使用代理,其他情况下可无需代理 44 | path=os.path.join(ROOT,'.local/cache/argos-translate') 45 | os.makedirs(path,exist_ok=True) 46 | cache=os.path.join(path,'index.json') 47 | if os.path.exists(cache) and os.path.getsize(cache)>0: 48 | return True 49 | try: 50 | print("测试下载模型") 51 | proxy=None 52 | server=settings['PROXY'] 53 | if server: 54 | proxy={ 55 | "http":server, 56 | "https":server 57 | } 58 | print(f'代理: {"无" if not proxy else server}') 59 | res=requests.get("https://raw.githubusercontent.com/argosopentech/argospm-index/main/index.json", proxies=proxy) 60 | if res.status_code!=200: 61 | raise Exception(f"status_code={res.status_code}") 62 | with open(cache,'w',encoding='utf-8') as f: 63 | f.write(res.text) 64 | except Exception as e: 65 | msg='第一次启动需要下载模型,请设置代理地址' if not settings['PROXY'] else f'你设置的代理地址不正确:{settings["PROXY"]},请正确设置代理,以便下载模型' 66 | print(f"\n=======\n无法下载模型,{msg}\n\n{e}\n\n") 67 | return False 68 | print('测试通过,准备下载模型,模型可能较大,确保网络稳定') 69 | return True 70 | 71 | 72 | def run(): 73 | try: 74 | sys.argv.extend(["--host",settings['HOST'],"--port",str(settings['PORT']),"--load-only",settings['LANG'],"--update"]) 75 | # 不存在 index.json 并且无法连接 raw.githubusercontent.com,则停止执行 76 | if not testgithub(): 77 | return 78 | from libretranslate.main import main 79 | main() 80 | except Exception as e: 81 | err=str(e) 82 | if re.search(r'download error',err,re.I): 83 | msg='第一次启动需要下载模型,请设置代理地址' if not settings['PROXY'] else f'你设置的代理地址不正确:{settings["PROXY"]},请正确设置代理,以便下载模型' 84 | print(f"\n=======\n无法下载模型,{msg}\n{err}\n\n") 85 | else: 86 | print(err) 87 | sys.exit() 88 | 89 | 90 | if __name__=='__main__': 91 | run() -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | result=requests.post("http://127.0.0.1:9911/translate",json={"q":"你好啊我的朋友","source":"zh","target":"en"}) 4 | print(result.json()) --------------------------------------------------------------------------------