768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
"""
# 方式1:直接运行
python api/translator_app.py
# 方式2:使用 uvicorn
uvicorn api.translator_app:app --host 0.0.0.0 --port 6006 --reload
使用说明:
Translation HTTP Service
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
14
|
This service provides a RESTful API for text translation using Qwen (default) or DeepL API.
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
15
16
17
18
19
20
21
22
23
|
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.)
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
24
25
|
"source_lang": "zh", # Optional: source language code (auto-detect if not provided)
"model": "qwen" # Optional: translation model ("qwen" or "deepl", default: "qwen")
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
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
|
}
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"
}'
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
56
57
58
59
60
61
62
63
64
65
66
|
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:
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
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
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
91
|
from typing import Optional, Dict
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
92
93
94
95
96
97
98
99
100
|
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
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
101
|
from config.env_config import DEEPL_AUTH_KEY, DASHSCOPE_API_KEY, REDIS_CONFIG
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
102
103
104
105
106
107
108
109
110
111
112
|
# 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."
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
113
114
|
# Global translator instances cache (keyed by model)
_translators: Dict[str, Translator] = {}
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
115
116
|
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
117
118
119
120
121
122
123
|
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,
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
124
125
126
|
use_cache=True,
timeout=10
)
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
127
128
|
logger.info(f"Translator initialized with model: {model}")
return _translators[model]
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
129
130
131
132
133
134
135
136
|
# 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)")
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
137
|
model: Optional[str] = Field("qwen", description="Translation model: 'qwen' (default) or 'deepl'")
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
138
139
140
141
142
143
|
class Config:
json_schema_extra = {
"example": {
"text": "商品名称",
"target_lang": "en",
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
144
145
|
"source_lang": "zh",
"model": "qwen"
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
146
147
148
149
150
151
152
153
154
155
156
|
}
}
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")
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
157
|
model: str = Field(..., description="Translation model used")
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
158
159
160
161
162
|
# Create FastAPI app
app = FastAPI(
title="Translation Service API",
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
163
|
description="RESTful API for text translation using Qwen (default) or DeepL",
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
|
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")
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
183
184
|
# Get default model from environment variable or use 'qwen'
default_model = os.getenv("TRANSLATION_MODEL", "qwen")
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
185
|
try:
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
186
187
|
get_translator(model=default_model)
logger.info(f"Translation service ready with default model: {default_model}")
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
188
189
190
191
192
193
194
195
196
|
except Exception as e:
logger.error(f"Failed to initialize translator: {e}", exc_info=True)
logger.warning("Service will start but translation may not work correctly")
@app.get("/health")
async def health_check():
"""Health check endpoint."""
try:
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
197
198
|
default_model = os.getenv("TRANSLATION_MODEL", "qwen")
translator = get_translator(model=default_model)
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
199
200
201
|
return {
"status": "healthy",
"service": "translation",
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
202
203
|
"default_model": default_model,
"available_models": list(_translators.keys()),
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
|
"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.
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
225
226
|
Supports both Qwen (default) and DeepL models via the 'model' parameter.
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
227
228
229
230
231
232
233
234
235
236
237
238
239
|
"""
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"
)
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
240
241
242
243
244
245
246
247
|
# 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'"
)
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
248
|
try:
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
249
250
|
# Get translator instance for the specified model
translator = get_translator(model=model)
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
|
# 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,
|
3cd09b3b
tangwang
翻译接口改为调用qwen-mt-f...
|
271
272
|
status="success",
model=translator.model
|
768ad710
tangwang
MySQL到ES字段映射说明-业务...
|
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
|
)
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
)
|