Skip to content

Commit

Permalink
ADD ai translate
Browse files Browse the repository at this point in the history
  • Loading branch information
sunwu51 committed Sep 17, 2024
1 parent 2a7eb85 commit b6f7336
Show file tree
Hide file tree
Showing 8 changed files with 320 additions and 0 deletions.
54 changes: 54 additions & 0 deletions 24.09/translate/utools-translator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# uTools Translator Plugin

This is an advanced translator plugin for uTools that provides both Google Translate and AI translation capabilities. It offers a user-friendly interface with left-right layout for input and dual translation output.

## Features

- Left-right layout with input on the left and translation results on the right
- Dual translation output: Google Translate and AI translation
- Automatic language detection
- Smart translation:
- If input is Chinese, translates to English
- If input is any other language, translates to Chinese
- Utilizes Google Translate API for accurate translations
- AI translation powered by https://api.siliconflow.cn/v1 (implementation required)

## Installation

1. Copy the `utools-translator` folder to your uTools plugin directory.
2. Restart uTools or refresh the plugin list.

## Usage

1. Open uTools and type "翻译" or "translate" to activate the plugin.
2. Enter the text you want to translate in the left text area.
3. The plugin will automatically detect the language:
- If you enter Chinese text, it will be translated to English.
- If you enter text in any other language, it will be translated to Chinese.
4. Translation results will appear automatically on the right side:
- The top section shows the Google Translate result
- The bottom section shows the AI translation result

## Adding a Logo

To add a logo to your plugin:

1. Create a 256x256 pixel image for your logo.
2. Save it as `logo.png` in the `utools-translator` directory.
3. Make sure the `logo.png` file is referenced correctly in the `plugin.json` file.

## Customization

You can customize the plugin by modifying the following files:

- `index.html`: Change the HTML structure
- `styles.css`: Modify the appearance
- `script.js`: Alter the translation logic or add new features
- `plugin.json`: Update plugin metadata or change activation keywords

## Important Note

- This plugin uses the unofficial Google Translate API. For production use, consider using an official translation API with proper authentication.
- The AI translation feature requires implementation. You need to replace the placeholder function in `script.js` with the actual API call to https://api.siliconflow.cn/v1.

Enjoy seamless bilingual translation with your enhanced uTools plugin!
27 changes: 27 additions & 0 deletions 24.09/translate/utools-translator/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>uTools Translator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<div class="input-container">
<textarea id="sourceText" placeholder="输入要翻译的文本"></textarea>
</div>
<div class="output-container">
<div class="translation-section">
<h3>Google 翻译</h3>
<div id="googleTranslatedText" class="translated-text"></div>
</div>
<div class="translation-section">
<h3>AI 翻译</h3>
<div id="aiTranslatedText" class="translated-text"></div>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Binary file added 24.09/translate/utools-translator/logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
18 changes: 18 additions & 0 deletions 24.09/translate/utools-translator/plugin.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"pluginName": "简易翻译",
"description": "左右布局的翻译工具,使用Google翻译API",
"author": "Claude",
"version": "0.0.1",
"logo": "logo.png",
"main": "index.html",
"features": [
{
"code": "translator",
"explain": "简易翻译工具",
"cmds": [
"翻译",
"translate"
]
}
]
}
4 changes: 4 additions & 0 deletions 24.09/translate/utools-translator/preload.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// This file is required by uTools, but we don't need any preload logic for this plugin
window.preload = {
// You can add any necessary preload logic here if needed in the future
};
95 changes: 95 additions & 0 deletions 24.09/translate/utools-translator/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
const sourceText = document.getElementById('sourceText');
const googleTranslatedText = document.getElementById('googleTranslatedText');
const aiTranslatedText = document.getElementById('aiTranslatedText');

let typingTimer;
const doneTypingInterval = 1000; // 1 second

sourceText.addEventListener('input', function () {
clearTimeout(typingTimer);
typingTimer = setTimeout(() => {
translateTextGoogle();
translateTextAI();
}, doneTypingInterval);
});

async function translateTextGoogle() {
const text = sourceText.value;
if (!text) {
googleTranslatedText.textContent = '';
return;
}

try {
// First, detect the language
const detectResponse = await fetch(`https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&dt=t&q=${encodeURIComponent(text)}`);
const detectData = await detectResponse.json();
const detectedLang = detectData[2];

// Determine target language based on detected language
const targetLang = detectedLang === 'zh-CN' ? 'en' : 'zh-CN';

// Perform the translation
const translateResponse = await fetch(`https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${targetLang}&dt=t&q=${encodeURIComponent(text)}`);
const translateData = await translateResponse.json();
const translatedResult = translateData[0].map(item => item[0]).join('');

googleTranslatedText.textContent = translatedResult;
} catch (error) {
console.error('Google translation error:', error);
googleTranslatedText.textContent = '谷歌翻译出错,请稍后再试。';
}
}

async function translateTextAI() {
const text = sourceText.value;
if (!text) {
aiTranslatedText.textContent = '';
return;
}

try {
// Placeholder for AI translation
// The actual implementation will be provided by the user
// aiTranslatedText.textContent = 'AI 翻译功能尚未实现。请替换此函数以调用 https://api.siliconflow.cn/v1 API。';
const options = {
method: 'POST',
headers: {
accept: 'application/json',
'content-type': 'application/json',
authorization: 'Bearer xxx'
},
body: JSON.stringify({
model: 'Qwen/Qwen2-57B-A14B-Instruct',
messages: [
{
role: 'system',
content: '你是一个翻译助手,用户输入中文,你直接返回翻译的英文结果,用户如果输入非中文,你直接将其翻译为中文。不需要其他解释,只返回结果。'
},
{
role: 'user',
content: text
}
]
})
};
const response = await fetch('https://api.siliconflow.cn/v1/chat/completions', options).then(response => response.json())
aiTranslatedText.textContent = response.choices[0].message.content
} catch (error) {
console.error('AI translation error:', error);
aiTranslatedText.textContent = 'AI 翻译出错,请稍后再试。';
}
}

// Initialize uTools plugin
window.exports = {
"translator": {
mode: "none",
args: {
enter: (action) => {
// This function will be called when the plugin is activated
console.log('Translator plugin activated');
}
}
}
};
71 changes: 71 additions & 0 deletions 24.09/translate/utools-translator/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
body, html {
margin: 0;
padding: 0;
height: 100%;
font-family: Arial, sans-serif;
}

.container {
display: flex;
height: 100%;
}

.input-container, .output-container {
flex: 1;
padding: 20px;
box-sizing: border-box;
}

.input-container {
border-right: 1px solid #ccc;
}

.output-container {
display: flex;
flex-direction: column;
}

textarea {
width: 100%;
height: 100%;
border: none;
resize: none;
font-size: 16px;
}

.translation-section {
flex: 1;
margin-bottom: 20px;
}

.translation-section h3 {
margin-top: 0;
padding-bottom: 5px;
border-bottom: 1px solid #ccc;
}

.translated-text {
font-size: 16px;
white-space: pre-wrap;
word-wrap: break-word;
height: calc(100% - 30px);
overflow-y: auto;
}

/* Scrollbar styles */
::-webkit-scrollbar {
width: 8px;
}

::-webkit-scrollbar-track {
background: #f1f1f1;
}

::-webkit-scrollbar-thumb {
background: #888;
border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
background: #555;
}
51 changes: 51 additions & 0 deletions 24.09/用ai写一个ai翻译插件.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
---
title: 用ai写一个ai翻译插件
date: 2024-09-17 11:55:00+8
tags:
- ai
- llm
- extention
- tools
- translate
---
最近发现utools工具中常用的翻译插件不好使了,下载了百度翻译、有道翻译的插件,但是发现需要提供百度/有道的key才能访问,比较麻烦,其他第三方的又怕哪天不能用了,干脆就自己写一个插件算了。

![image](https://i.imgur.com/C2yzFK3.png)

![image](https://i.imgur.com/Cw5adR0.png)
# 使用ai来写
这里我们使用到`vscode` + `claude-dev`插件,并配置了`claude-3.5-sonet`这个编程效果较好的模型。

![image](https://i.imgur.com/QHe9dpU.png)

直接浏览器打开`index.html`,如下可以看到已经能实现英文翻译为中文的操作了,并且从`script.js`中能看到使用的就是`google翻译`的api。

![image](https://i.imgur.com/Nk9BORo.gif)

# 改进
上面的页面有几个问题:
- 1 只支持英文转中文,不支持中转英。
- 2 只用到了谷歌翻译,没梯子的话就用不了。

继续给`claude-dev`提需求,让他支持中英互译,效果很不错:

![img](https://i.imgur.com/L9L0550.gif)

然后我们提供一个ai翻译的接口,但是ai翻译的代码需要提供token等,我们让`claude`把这部分代码空出来,由我们自己来实现,效果同样很好:

![image](https://i.imgur.com/VLf4lW3.png)

接下来我们把需要调用`ai翻译`的部分补全,直接到`silicon cloud`用自己的token,在api文档中,让他给生成js代码。

![image](https://i.imgur.com/rvHIJ86.png)

替换原来的占位代码,测试效果也不错。

![image](https://i.imgur.com/JGDFxoH.png)

# 收尾
最后需要找个画图的ai给画一个可爱的logo,然后用utools加载就可以了。

![image](https://i.imgur.com/Ll5Qqhe.gif)

详细代码在[translate](https://github.com/sunwu51/notebook/tree/master/24.09/translate)目录下,只不过`script.js#L60`需要替换成自己的token。

0 comments on commit b6f7336

Please sign in to comment.