-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathLLMS_translation.py
249 lines (230 loc) · 8.86 KB
/
LLMS_translation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import asyncio
import aiohttp
import load_config
class Openai_translation:
def __init__(self, model):
config = load_config.load_config()
self.api_key = config['translation_services']['openai']['auth_key']
self.url = "https://api.openai.com/v1/chat/completions"
self.headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
self.model = config['translation_services']['openai']['model_name']
async def translate_single(self, session, text, original_lang, target_lang):
"""单个文本的异步翻译"""
payload = {
"model": self.model,
"messages": [
{
"role": "system",
"content": f"You are a professional translator. Translate from {original_lang} to {target_lang}.Return only the translations"
},
{
"role": "user",
"content": text
}
],
"response_format": {
"type": "text"
},
"temperature": 0.3,
"top_p": 0.9
}
try:
async with session.post(self.url, headers=self.headers, json=payload) as response:
if response.status == 200:
result = await response.json()
return result['choices'][0]['message']['content'].strip()
else:
print(f"Error: {response.status}")
return ""
except Exception as e:
print(f"Error in translation: {e}")
return ""
async def translate(self, texts, original_lang, target_lang):
"""异步批量翻译"""
async with aiohttp.ClientSession() as session:
tasks = [
self.translate_single(session, text, original_lang, target_lang)
for text in texts
]
return await asyncio.gather(*tasks)
class Deepseek_translation:
def __init__(self):
config = load_config.load_config()
self.api_key = config['translation_services']['deepseek']['auth_key']
self.url = "https://ark.cn-beijing.volces.com/api/v3/chat/completions"
self.headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
self.model = config['translation_services']['deepseek']['model_name']
async def translate_single(self, session, text, original_lang, target_lang):
"""单个文本的异步翻译"""
payload = {
"model": self.model,
"messages": [
{
"role": "system",
"content": f"You are a professional translator. Translate from {original_lang} to {target_lang}.Return only the translations"
},
{
"role": "user",
"content": text
}
],
"temperature": 0.3,
"top_p": 0.9
}
try:
async with session.post(self.url, headers=self.headers, json=payload) as response:
if response.status == 200:
result = await response.json()
return result['choices'][0]['message']['content'].strip()
else:
print(f"Error: {response.status}")
return ""
except Exception as e:
print(f"Error in translation: {e}")
return ""
async def translate(self, texts, original_lang, target_lang):
"""异步批量翻译"""
async with aiohttp.ClientSession() as session:
tasks = [
self.translate_single(session, text, original_lang, target_lang)
for text in texts
]
return await asyncio.gather(*tasks)
class Doubao_translation:
def __init__(self):
config = load_config.load_config()
self.api_key = config['translation_services']['Doubao']['auth_key']
self.url = "https://ark.cn-beijing.volces.com/api/v3/chat/completions"
self.headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
self.model = config['translation_services']['Doubao']['model_name']
async def translate_single(self, session, text, original_lang, target_lang):
"""单个文本的异步翻译"""
payload = {
"model": self.model,
"messages": [
{
"role": "system",
"content": f"You are a professional translator. Translate from {original_lang} to {target_lang}.Return only the translations"
},
{
"role": "user",
"content": text
}
],
"temperature": 0.3,
"top_p": 0.9
}
try:
async with session.post(self.url, headers=self.headers, json=payload) as response:
if response.status == 200:
result = await response.json()
return result['choices'][0]['message']['content'].strip()
else:
print(f"Error: {response.status}")
return ""
except Exception as e:
print(f"Error in translation: {e}")
return ""
async def translate(self, texts, original_lang, target_lang):
"""异步批量翻译"""
async with aiohttp.ClientSession() as session:
tasks = [
self.translate_single(session, text, original_lang, target_lang)
for text in texts
]
return await asyncio.gather(*tasks)
class Qwen_translation:
def __init__(self):
config = load_config.load_config()
self.api_key = config['translation_services']['Qwen']['auth_key']
self.url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
self.headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
self.model = config['translation_services']['Qwen']['model_name']
async def translate_single(self, session, text, original_lang, target_lang):
"""单个文本的异步翻译"""
payload = {
"model": self.model,
"messages": [
{
"role": "system",
"content": f"You are a professional translator. Translate from {original_lang} to {target_lang}.Return only the translations"
},
{
"role": "user",
"content": text
}
],
"temperature": 0.3,
"top_p": 0.9
}
try:
async with session.post(self.url, headers=self.headers, json=payload) as response:
if response.status == 200:
result = await response.json()
return result['choices'][0]['message']['content'].strip()
else:
print(f"Error: {response.status}")
return ""
except Exception as e:
print(f"Error in translation: {e}")
return ""
async def translate(self, texts, original_lang, target_lang):
"""异步批量翻译"""
async with aiohttp.ClientSession() as session:
tasks = [
self.translate_single(session, text, original_lang, target_lang)
for text in texts
]
return await asyncio.gather(*tasks)
# 测试代码
async def main():
texts = [
"Hello, how are you?",
"What's the weather like today?",
"I love programming",
"Python is awesome",
"Machine learning is interesting"
]
# OpenAI翻译测试
openai_translator = Openai_translation("gpt-3.5-turbo")
translated_openai = await openai_translator.translate(
texts=texts,
original_lang="en",
target_lang="zh"
)
print("OpenAI translations:")
for src, tgt in zip(texts, translated_openai):
print(f"{src} -> {tgt}")
# DeepSeek翻译测试
deepseek_translator = Deepseek_translation()
translated_deepseek = await deepseek_translator.translate(
texts=texts,
original_lang="en",
target_lang="zh"
)
print("\nDeepSeek translations:")
for src, tgt in zip(texts, translated_deepseek):
print(f"{src} -> {tgt}")
qwen_translator = Qwen_translation()
translated_deepseek = await qwen_translator.translate(
texts=texts,
original_lang="en",
target_lang="zh"
)
print("\nQwen translations:")
for src, tgt in zip(texts, translated_deepseek):
print(f"{src} -> {tgt}")
if __name__ == "__main__":
asyncio.run(main())