test_translation.py
9.01 KB
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
#!/usr/bin/env python3
"""
Translation function test script.
Test content:
1. Translation prompt configuration loading
2. Synchronous translation (indexing scenario)
3. Asynchronous translation (query scenario)
4. Usage of different prompts
5. Cache functionality
6. DeepL Context parameter usage
"""
import sys
import os
from pathlib import Path
# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))
from config import ConfigLoader
from query.translator import Translator
import logging
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def test_config_loading():
"""Test configuration loading"""
print("\n" + "="*60)
print("Test 1: Configuration loading")
print("="*60)
try:
config_loader = ConfigLoader()
config = config_loader.load_config()
print(f"✓ Configuration loaded successfully")
print(f" Translation service: {config.query_config.translation_service}")
print(f" Translation prompt configuration:")
for key, value in config.query_config.translation_prompts.items():
print(f" {key}: {value[:60]}..." if len(value) > 60 else f" {key}: {value}")
return config
except Exception as e:
print(f"✗ Configuration loading failed: {e}")
import traceback
traceback.print_exc()
return None
def test_translator_sync(config):
"""Test synchronous translation (indexing scenario)"""
print("\n" + "="*60)
print("Test 2: Synchronous translation (indexing scenario)")
print("="*60)
if not config:
print("✗ Skipped: Configuration not loaded")
return None
try:
translator = Translator(
api_key=config.query_config.translation_api_key,
use_cache=True,
glossary_id=config.query_config.translation_glossary_id,
translation_context=config.query_config.translation_context
)
# 测试商品标题翻译(使用product_title提示词)
test_texts = [
("蓝牙耳机", "zh", "en", "product_title"),
("Wireless Headphones", "en", "zh", "product_title"),
]
for text, source_lang, target_lang, prompt_type in test_texts:
if prompt_type == "product_title":
if target_lang == "zh":
prompt = config.query_config.translation_prompts.get('product_title_zh')
else:
prompt = config.query_config.translation_prompts.get('product_title_en')
else:
if target_lang == "zh":
prompt = config.query_config.translation_prompts.get('default_zh')
else:
prompt = config.query_config.translation_prompts.get('default_en')
print(f"\nTranslation test:")
print(f" Original text ({source_lang}): {text}")
print(f" Target language: {target_lang}")
print(f" Prompt: {prompt[:50] if prompt else 'None'}...")
result = translator.translate(
text,
target_lang=target_lang,
source_lang=source_lang,
prompt=prompt
)
if result:
print(f" Result: {result}")
print(f" ✓ Translation successful")
else:
print(f" ⚠ Translation returned None (possibly mock mode or no API key)")
return translator
except Exception as e:
print(f"✗ Synchronous translation test failed: {e}")
import traceback
traceback.print_exc()
return None
def test_translator_async(config, translator):
"""Test asynchronous translation (query scenario)"""
print("\n" + "="*60)
print("Test 3: Asynchronous translation (query scenario)")
print("="*60)
if not config or not translator:
print("✗ Skipped: Configuration or translator not initialized")
return
try:
query_text = "手机"
target_langs = ['en']
source_lang = 'zh'
query_prompt = config.query_config.translation_prompts.get('query_zh')
print(f"Query text: {query_text}")
print(f"Target languages: {target_langs}")
print(f"Prompt: {query_prompt}")
# 异步模式(立即返回,后台翻译)
results = translator.translate_multi(
query_text,
target_langs,
source_lang=source_lang,
context=config.query_config.translation_context,
async_mode=True,
prompt=query_prompt
)
print(f"\nAsynchronous translation results:")
for lang, translation in results.items():
if translation:
print(f" {lang}: {translation} (cache hit)")
else:
print(f" {lang}: None (translating in background...)")
# 同步模式(等待完成)
print(f"\nSynchronous translation (waiting for completion):")
results_sync = translator.translate_multi(
query_text,
target_langs,
source_lang=source_lang,
context=config.query_config.translation_context,
async_mode=False,
prompt=query_prompt
)
for lang, translation in results_sync.items():
print(f" {lang}: {translation}")
except Exception as e:
print(f"✗ Asynchronous translation test failed: {e}")
import traceback
traceback.print_exc()
def test_cache():
"""测试缓存功能"""
print("\n" + "="*60)
print("Test 4: Cache functionality")
print("="*60)
try:
config_loader = ConfigLoader()
config = config_loader.load_config()
translator = Translator(
api_key=config.query_config.translation_api_key,
use_cache=True
)
test_text = "测试文本"
target_lang = "en"
source_lang = "zh"
prompt = config.query_config.translation_prompts.get('default_zh')
print(f"First translation (should call API or return mock):")
result1 = translator.translate(test_text, target_lang, source_lang, prompt=prompt)
print(f" Result: {result1}")
print(f"\nSecond translation (should use cache):")
result2 = translator.translate(test_text, target_lang, source_lang, prompt=prompt)
print(f" Result: {result2}")
if result1 == result2:
print(f" ✓ Cache functionality working properly")
else:
print(f" ⚠ Cache might have issues")
except Exception as e:
print(f"✗ Cache test failed: {e}")
import traceback
traceback.print_exc()
def test_context_parameter():
"""Test DeepL Context parameter usage"""
print("\n" + "="*60)
print("Test 5: DeepL Context parameter")
print("="*60)
try:
config_loader = ConfigLoader()
config = config_loader.load_config()
translator = Translator(
api_key=config.query_config.translation_api_key,
use_cache=False # 禁用缓存以便测试
)
# 测试带context和不带context的翻译
text = "手机"
prompt = config.query_config.translation_prompts.get('query_zh')
print(f"Test text: {text}")
print(f"Prompt (as context): {prompt}")
# 带context的翻译
result_with_context = translator.translate(
text,
target_lang='en',
source_lang='zh',
prompt=prompt
)
print(f"\nTranslation result with context: {result_with_context}")
# 不带context的翻译
result_without_context = translator.translate(
text,
target_lang='en',
source_lang='zh',
prompt=None
)
print(f"Translation result without context: {result_without_context}")
print(f"\n✓ Context parameter test completed")
print(f" Note: According to DeepL API, context parameter affects translation but does not participate in translation itself")
except Exception as e:
print(f"✗ Context parameter test failed: {e}")
import traceback
traceback.print_exc()
def main():
"""Main test function"""
print("="*60)
print("Translation function test")
print("="*60)
# 测试1: 配置加载
config = test_config_loading()
# 测试2: 同步翻译
translator = test_translator_sync(config)
# 测试3: 异步翻译
test_translator_async(config, translator)
# 测试4: 缓存功能
test_cache()
# 测试5: Context参数
test_context_parameter()
print("\n" + "="*60)
print("Test completed")
print("="*60)
if __name__ == '__main__':
main()