translator_app.py
9.31 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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
"""
# 方式1:直接运行
python api/translator_app.py
# 方式2:使用 uvicorn
uvicorn api.translator_app:app --host 0.0.0.0 --port 6006 --reload
使用说明:
Translation HTTP Service
This service provides a RESTful API for text translation using Qwen (default) or DeepL API.
The service runs on port 6006 and provides a simple translation endpoint.
API Endpoint:
POST /translate
Request Body (JSON):
{
"text": "要翻译的文本",
"target_lang": "en", # Required: target language code (zh, en, ru, etc.)
"source_lang": "zh", # Optional: source language code (auto-detect if not provided)
"model": "qwen" # Optional: translation model ("qwen" or "deepl", default: "qwen")
}
Response (JSON):
{
"text": "要翻译的文本",
"target_lang": "en",
"source_lang": "zh",
"translated_text": "Text to translate",
"status": "success"
}
Usage Examples:
1. Translate Chinese to English:
curl -X POST http://localhost:6006/translate \
-H "Content-Type: application/json" \
-d '{
"text": "商品名称",
"target_lang": "en",
"source_lang": "zh"
}'
2. Translate with auto-detection:
curl -X POST http://localhost:6006/translate \
-H "Content-Type: application/json" \
-d '{
"text": "Product name",
"target_lang": "zh"
}'
3. Translate using DeepL model:
curl -X POST http://localhost:6006/translate \
-H "Content-Type: application/json" \
-d '{
"text": "商品名称",
"target_lang": "en",
"source_lang": "zh",
"model": "deepl"
}'
4. Translate Russian to English:
curl -X POST http://localhost:6006/translate \
-H "Content-Type: application/json" \
-d '{
"text": "Название товара",
"target_lang": "en",
"source_lang": "ru"
}'
Health Check:
GET /health
curl http://localhost:6006/health
Start the service:
python api/translator_app.py
# or
uvicorn api.translator_app:app --host 0.0.0.0 --port 6006 --reload
"""
import os
import sys
import logging
import argparse
import uvicorn
from typing import Optional, Dict
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from query.translator import Translator
from config.env_config import DEEPL_AUTH_KEY, DASHSCOPE_API_KEY, REDIS_CONFIG
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Fixed translation prompt
TRANSLATION_PROMPT = "Translate the original text into an English product SKU name. Requirements: Ensure accurate and complete transmission of the original information, with concise, clear, authentic, and professional language."
# Global translator instances cache (keyed by model)
_translators: Dict[str, Translator] = {}
def get_translator(model: str = "qwen") -> Translator:
"""Get or create translator instance for the specified model."""
global _translators
if model not in _translators:
logger.info(f"Initializing translator with model: {model}...")
_translators[model] = Translator(
model=model,
use_cache=True,
timeout=10
)
logger.info(f"Translator initialized with model: {model}")
return _translators[model]
# Request/Response models
class TranslationRequest(BaseModel):
"""Translation request model."""
text: str = Field(..., description="Text to translate")
target_lang: str = Field(..., description="Target language code (zh, en, ru, etc.)")
source_lang: Optional[str] = Field(None, description="Source language code (optional, auto-detect if not provided)")
model: Optional[str] = Field("qwen", description="Translation model: 'qwen' (default) or 'deepl'")
class Config:
json_schema_extra = {
"example": {
"text": "商品名称",
"target_lang": "en",
"source_lang": "zh",
"model": "qwen"
}
}
class TranslationResponse(BaseModel):
"""Translation response model."""
text: str = Field(..., description="Original text")
target_lang: str = Field(..., description="Target language code")
source_lang: Optional[str] = Field(None, description="Source language code (detected or provided)")
translated_text: str = Field(..., description="Translated text")
status: str = Field(..., description="Translation status")
model: str = Field(..., description="Translation model used")
# Create FastAPI app
app = FastAPI(
title="Translation Service API",
description="RESTful API for text translation using Qwen (default) or DeepL",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc"
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
async def startup_event():
"""Initialize translator on startup."""
logger.info("Starting Translation Service API on port 6006")
# Get default model from environment variable or use 'qwen'
default_model = os.getenv("TRANSLATION_MODEL", "qwen")
try:
get_translator(model=default_model)
logger.info(f"Translation service ready with default model: {default_model}")
except Exception as e:
logger.error(f"Failed to initialize translator: {e}", exc_info=True)
@app.get("/health")
async def health_check():
"""Health check endpoint."""
try:
default_model = os.getenv("TRANSLATION_MODEL", "qwen")
translator = get_translator(model=default_model)
return {
"status": "healthy",
"service": "translation",
"default_model": default_model,
"available_models": list(_translators.keys()),
"translator_initialized": translator is not None,
"cache_enabled": translator.use_cache if translator else False
}
except Exception as e:
logger.error(f"Health check failed: {e}")
return JSONResponse(
status_code=503,
content={
"status": "unhealthy",
"error": str(e)
}
)
@app.post("/translate", response_model=TranslationResponse)
async def translate(request: TranslationRequest):
"""
Translate text to target language.
Uses a fixed prompt optimized for product SKU name translation.
The translation is cached in Redis for performance.
Supports both Qwen (default) and DeepL models via the 'model' parameter.
"""
if not request.text or not request.text.strip():
raise HTTPException(
status_code=400,
detail="Text cannot be empty"
)
if not request.target_lang:
raise HTTPException(
status_code=400,
detail="target_lang is required"
)
# Validate model parameter
model = request.model.lower() if request.model else "qwen"
if model not in ['qwen', 'deepl']:
raise HTTPException(
status_code=400,
detail=f"Invalid model: {model}. Supported models: 'qwen', 'deepl'"
)
try:
# Get translator instance for the specified model
translator = get_translator(model=model)
# Translate using the fixed prompt
translated_text = translator.translate(
text=request.text,
target_lang=request.target_lang,
source_lang=request.source_lang,
prompt=TRANSLATION_PROMPT
)
if translated_text is None:
raise HTTPException(
status_code=500,
detail="Translation failed"
)
return TranslationResponse(
text=request.text,
target_lang=request.target_lang,
source_lang=request.source_lang,
translated_text=translated_text,
status="success",
model=translator.model
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Translation error: {e}", exc_info=True)
raise HTTPException(
status_code=500,
detail=f"Translation error: {str(e)}"
)
@app.get("/")
async def root():
"""Root endpoint with API information."""
return {
"service": "Translation Service API",
"version": "1.0.0",
"status": "running",
"endpoints": {
"translate": "POST /translate",
"health": "GET /health",
"docs": "GET /docs"
}
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Start translation API service')
parser.add_argument('--host', default='0.0.0.0', help='Host to bind to')
parser.add_argument('--port', type=int, default=6006, help='Port to bind to')
parser.add_argument('--reload', action='store_true', help='Enable auto-reload')
args = parser.parse_args()
# Run server
uvicorn.run(
"api.translator_app:app",
host=args.host,
port=args.port,
reload=args.reload
)