Skip to content

Commit

Permalink
add: openai translate
Browse files Browse the repository at this point in the history
  • Loading branch information
Lin-jun-xiang committed Jan 13, 2025
1 parent 60858d4 commit e3e36f9
Show file tree
Hide file tree
Showing 6 changed files with 58 additions and 36 deletions.
3 changes: 2 additions & 1 deletion .github/workflows/translate-readme.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ jobs:
uses: ./
with:
token: ${{ secrets.Action_Bot }} # Your token
zhipuai: ${{ secrets.zhipuai_api_key }} # Your zhipuai api key if use zhipuai instead of g4f
zhipuai: ${{ secrets.zhipuai_api_key }} # Optional: Your zhipuai api key if use zhipuai
openai: ${{ secrets.openai_api_key }} # Optional: Your openai api key if use openai
langs: "en,zh-TW,zh-CN,French" # You can define any langs
42 changes: 23 additions & 19 deletions README.zh-TW.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,16 @@
# How to use ?

> [!IMPORTANT]
> 由於生成式 AI 模型每次翻譯結果都有機率出現問題,建議使用分支測試,並多嘗試幾次
> 由於生成式 AI 模型每次翻譯結果都有機率出現問題,建議使用分支執行,最後 Merge 回主支
> [!WARNING]
> 如果你遇到如下錯誤: `Error: Input required and not supplied: token`,請根據下方步驟二確定已建立 `Token`,或者 `Token` 是否已經過期!
1. 單擊 :star: 圖標將此項目添加到您的 Github 存儲庫 .

2. 設置你的 `Github Token`:
2. 設置你的 `Github Token` (**必須**):

* [創建一個新的 **`Github Secret Token`**](https://github.com/settings/tokens/new)
1. [創建一個新的 **`Github Secret Token`**](https://github.com/settings/tokens/new)
* 設置
* 開發者設置
* 個人訪問令牌 - `Tokens(classic)`
Expand All @@ -47,7 +47,7 @@

<img src="https://github.com/Lin-jun-xiang/action-translate-readme/assets/63782903/b7487b49-817c-4925-b94a-bdb7b025a0c2" width=" 60%" />

* 創建一個新的 **`repository secret`**
2. 將 Github Token 添加至 **`repository secret`**
* 在您的存儲庫中 - `settings`
* `Securits and variables`
* `Actions`
Expand All @@ -56,19 +56,24 @@

<img src="https://github.com/Lin-jun-xiang/action-translate-readme/assets/63782903/27dc7bcd-633f-431e-98e8-387b97ecd47c" width=" 60%" />

3. GPT 模型選擇
3. GPT 翻譯模型選擇 (**可選的**)

* `g4f`: **預設**使用 `g4f` 來進行 OpenAI 調用,並完成翻譯任務。
* `zhipuai`: 如果需要穩定翻譯,你可以在[智譜AI平台](https://open.bigmodel.cn/dev/howuse/introduction)註冊帳號,並[申請 API KEY](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys),這是一個完全免費、無須信用卡的 GPT 模型方案
* 如果要使用該方案,請仿照步驟2申請 Github Token 的方式,將智譜AI的 API KEY 添加至 Repo 中作為環境變數
* `g4f`: **預設**使用**免費** `g4f` 來進行 OpenAI 調用,並完成翻譯任務。
* `zhipuai`: 如果需要**免費且穩定翻譯**,你可以在[Zhipuai AI平台](https://open.bigmodel.cn/dev/howuse/introduction)註冊帳號,並[申請 API KEY](https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys),這是一個完全免費、無須信用卡的 GPT 模型方案
* 如果要使用該方案,請仿照**步驟2-2**添加 Github Token 的方式,**Zhipuai AI的 API KEY 添加至 GitHub Repos 的 Secrets 中**

<img src="static/images/2025-01-02-11-25-45.png" width="60%" />

<img src="static/images/2025-01-02-11-26-28.png" width="60%" />

* `openai`: **保證高質量且穩定的品質**,如果您有 OPENAI API KEY,則會使用 `gpt-4o` 作為模型翻譯。
* 如果要使用該方案,請仿照**步驟2-2**添加 Github Token 的方式,將 **OpenAI 的 API KEY 添加至 GitHub Repos 的 Secrets 中**

<img src="static/images/2025-01-13-10-13-51.png" width="60%" />

4. 在目錄 `.github/workflows/your_action.yml`. 中創建您的操作示例,你可以直接複製以下:

```
```yaml
# .github/workflows/translate.yml
name: Translate Readme

Expand All @@ -89,19 +94,23 @@
uses: Lin-jun-xiang/action-translate-readme@v2 # Based on the tag
with:
token: ${{ secrets.Action_Bot }} # Based on step2 name
zhipuai: ${{ secrets.zhipuai_api_key }} # Based on step3
zhipuai: ${{ secrets.zhipuai_api_key }} # Optional: Based on step3
openai: ${{ secrets.openai_api_key }} # Optional: Based on step3
langs: "en,zh-TW,zh-CN,French,Arabic" # You can define any langs
```
在`.yml`中有三個參數要特別注意:
`.yml`中有幾個參數要特別注意:

* `token`: 根據步驟2,在repos中建立的token
* `zhipuai`: gpt 的提供者,若有提供則使用智譜AI平台的模型,反之預設使用 `g4f`,需要在 repos 中建立
* `langs`: 想要產生的語言版本,務必用`,`分隔不同語言,例如:
* `token`: 用於授權操作的 GitHub Token (根據步驟二添加)。
* `zhipuai`: Zhipuai API,根據步驟三添加 (可選)
* `openai`: OpenAI API,根據步驟三添加 (可選)
* `langs`: 指定要翻譯的語言,務必用`,`分隔不同語言,例如:
* `"en"`: 僅翻譯英文版
* `"en,zh-TW"`: 翻譯英文、繁體中文
* `"French,Arabic"`: 翻譯法文、阿拉伯文

> PS: `zhipuai`, `openai` 如果都未添加至 GitHub Secrets 中,則會使用 `g4f` 進行翻譯。

5. 現在你可以更新 `README.md`,它會自動生成一個翻譯版本!

---
Expand All @@ -112,9 +121,4 @@

---

# Results of Test Document
* 查看[測試文檔](https://github.com/Lin-jun-xiang/vscode-extensions-best/tree/main)
* 使用我們的工具更新測試文檔
<a href="#top">Back to top</a>
6 changes: 2 additions & 4 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,15 @@ runs:
- name: Install Dependencies
shell: bash
run: |
pip install PyExecJS
pip install -U g4f
pip install -U zhipuai
pip install --upgrade tenacity
pip install -r requirements.txt
- name: Translate README
shell: bash
working-directory: .
run: |
export LANGS=${{ inputs.langs }}
export ZHIPUAI_API_KEY=${{ inputs.zhipuai }}
export OPENAI_API_KEY=${{ inputs.openai }}
python $GITHUB_ACTION_PATH/translation.py
- name: Git Commit
Expand Down
5 changes: 5 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
PyExecJS
g4f
zhipuai
openai
tenacity
Binary file added static/images/2025-01-13-10-13-51.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
38 changes: 26 additions & 12 deletions translation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,19 @@
import subprocess

import g4f
from openai import AsyncOpenAI
from tenacity import retry, stop_after_attempt
from zhipuai import ZhipuAI

g4f.debug.logging = True

LAGNS = os.environ.get('LANGS').split(',')
ZHIPUAI_API_KEY = os.environ.get('ZHIPUAI_API_KEY', '')
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY', '')

zhipuai_client = ZhipuAI(api_key=ZHIPUAI_API_KEY)
openai_client = AsyncOpenAI(api_key=OPENAI_API_KEY)


def run_shell_command(command: str) -> tuple:
result = subprocess.run(
Expand All @@ -23,18 +29,16 @@ def run_shell_command(command: str) -> tuple:
return result.returncode, result.stdout, result.stderr


async def async_zhipuai(query: str):
client = ZhipuAI(api_key=ZHIPUAI_API_KEY)

response = client.chat.asyncCompletions.create(
async def async_zhipuai(messages: list):
response = zhipuai_client.chat.asyncCompletions.create(
model="glm-4-plus",
messages=[{"role": "user", "content": query}],
messages=messages,
)
task_id = response.id

task_status = ''
while task_status not in ('SUCCESS', 'FAILED'):
result_response = client.chat.asyncCompletions.retrieve_completion_result(
result_response = zhipuai_client.chat.asyncCompletions.retrieve_completion_result(
id=task_id
)
task_status = result_response.task_status
Expand All @@ -47,16 +51,26 @@ async def async_zhipuai(query: str):
@retry(stop=stop_after_attempt(5))
async def chat_completion(query: str) -> str:
response = ''
if not ZHIPUAI_API_KEY:
messages = [{"role": "user", "content": query}]
if ZHIPUAI_API_KEY:
print('Using zhipuai.')
response = await async_zhipuai(messages)
response = response.choices[0].message.content

elif OPENAI_API_KEY:
print('Using openai.')
response = await openai_client.chat.completions.create(
model='gpt-4o',
messages=messages,
)
response = response.choices[0].message.content

else:
print('Using g4f.')
response = await g4f.ChatCompletion.create_async(
model="gpt-4o",
messages=[{"role": "user", "content": query}],
messages=messages,
)
else:
print('Using zhipuai.')
response = await async_zhipuai(query)
response = response.choices[0].message.content
if response == '' or response is None:
raise Exception
return response
Expand Down

0 comments on commit e3e36f9

Please sign in to comment.