translator_app.py 14.4 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 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432

"""

# 方式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 Dict, List, Optional, Sequence, Union
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.qwen_mt_translate import Translator
from query.llm_translate import LLMTranslatorProvider
from query.deepl_provider import DeepLProvider
from config.services_config import get_translation_config

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Global translator instances cache (keyed by model)
_translators: Dict[str, object] = {}


def _resolve_default_model() -> str:
    """
    Resolve translator model from services.translation config first.

    Priority:
    1) TRANSLATION_MODEL env (explicit runtime override)
    2) services.translation.provider + providers.<provider>.model
    3) qwen-mt
    """
    env_model = (os.getenv("TRANSLATION_MODEL") or "").strip()
    if env_model:
        return env_model
    try:
        cfg = get_translation_config()
        provider = (cfg.provider or "").strip().lower()
        provider_cfg = cfg.get_provider_cfg() if hasattr(cfg, "get_provider_cfg") else {}
        model = (provider_cfg.get("model") or "").strip().lower() if isinstance(provider_cfg, dict) else ""
        if provider == "llm":
            return "llm"
        if provider in {"qwen-mt", "direct", "http"}:
            return model or "qwen-mt"
        if provider == "deepl":
            return "deepl"
    except Exception:
        pass
    return "qwen-mt"


def get_translator(model: str = "qwen") -> object:
    """Get or create translator instance for the specified model."""
    global _translators
    if model not in _translators:
        logger.info(f"Initializing translator with model: {model}...")
        normalized = (model or "qwen").strip().lower()
        if normalized in {"qwen", "qwen-mt", "qwen-mt-flash", "qwen-mt-flush"}:
            _translators[model] = Translator(model=normalized, use_cache=True, timeout=10)
        elif normalized == "deepl":
            _translators[model] = DeepLProvider(api_key=None, timeout=10.0)
        elif normalized == "llm":
            _translators[model] = LLMTranslatorProvider()
        else:
            raise ValueError(f"Unsupported model: {model}")
        logger.info(f"Translator initialized with model: {model}")
    return _translators[model]


# Request/Response models
class TranslationRequest(BaseModel):
    """Translation request model."""
    text: Union[str, List[str]] = Field(..., description="Text to translate (string or list of strings)")
    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(None, description="Translation model: qwen-mt | deepl | llm")
    context: Optional[str] = Field(None, description="Optional translation scene or context")
    prompt: Optional[str] = Field(None, description="Optional prompt override")

    class Config:
        json_schema_extra = {
            "example": {
                "text": "商品名称",
                "target_lang": "en",
                "source_lang": "zh",
                "model": "llm",
                "context": "sku_name"
            }
        }


class TranslationResponse(BaseModel):
    """Translation response model."""
    text: Union[str, List[str]] = Field(..., description="Original text (string or list)")
    target_lang: str = Field(..., description="Target language code")
    source_lang: Optional[str] = Field(None, description="Source language code (detected or provided)")
    translated_text: Union[str, List[Optional[str]]] = Field(
        ...,
        description="Translated text (string or list; list elements may be null on failure)",
    )
    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")
    default_model = _resolve_default_model()
    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)
        raise


@app.get("/health")
async def health_check():
    """Health check endpoint."""
    try:
        # 仅做轻量级本地检查,避免在健康检查中触发潜在的阻塞初始化或外部依赖
        default_model = _resolve_default_model()
        # 如果启动事件成功,默认模型通常会已经初始化到缓存中
        translator = _translators.get(default_model) or next(iter(_translators.values()), None)
        return {
            "status": "healthy",
            "service": "translation",
            "default_model": default_model,
            "available_models": list(_translators.keys()),
            "translator_initialized": translator is not None,
            "cache_enabled": bool(getattr(translator, "use_cache", 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.
    """
    # 允许 text 为字符串或字符串列表
    if isinstance(request.text, list):
        if not request.text:
            raise HTTPException(
                status_code=400,
                detail="Text list cannot be empty"
            )
    else:
        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 _resolve_default_model().lower()
    if model not in ["qwen", "qwen-mt", "deepl", "llm"]:
        raise HTTPException(
            status_code=400,
            detail="Invalid model. Supported models: 'qwen-mt', 'deepl', 'llm'"
        )
    
    try:
        # Get translator instance for the specified model
        translator = get_translator(model=model)
        raw_text = request.text

        # 如果是列表,并且底层 provider 声明支持 batch,则直接传 list
        if isinstance(raw_text, list) and getattr(translator, "supports_batch", False):
            try:
                translated_list = translator.translate(
                    text=raw_text,
                    target_lang=request.target_lang,
                    source_lang=request.source_lang,
                    context=request.context,
                    prompt=request.prompt,
                )
            except Exception as exc:
                logger.error("Batch translation failed: %s", exc, exc_info=True)
                # 回退到逐条拆分逻辑
                translated_list = None

            if translated_list is not None:
                # 规范化为 List[Optional[str]],并保证长度对应
                if not isinstance(translated_list, list):
                    raise HTTPException(
                        status_code=500,
                        detail="Batch translation provider returned non-list result",
                    )
                normalized: List[Optional[str]] = []
                for idx, item in enumerate(raw_text):
                    if idx < len(translated_list):
                        val = translated_list[idx]
                    else:
                        val = None
                    # 失败语义:失败位置为 None
                    normalized.append(val)

                return TranslationResponse(
                    text=raw_text,
                    target_lang=request.target_lang,
                    source_lang=request.source_lang,
                    translated_text=normalized,
                    status="success",
                    model=str(getattr(translator, "model", model)),
                )

        # 否则:统一走逐条拆分逻辑(包括不支持 batch 的 provider)
        if isinstance(raw_text, list):
            results: List[Optional[str]] = []
            for item in raw_text:
                if item is None or not str(item).strip():
                    # 空元素不视为失败,直接返回原值
                    results.append(item)  # type: ignore[arg-type]
                    continue
                try:
                    out = translator.translate(
                        text=str(item),
                        target_lang=request.target_lang,
                        source_lang=request.source_lang,
                        context=request.context,
                        prompt=request.prompt,
                    )
                except Exception as exc:
                    logger.warning("Per-item translation failed: %s", exc, exc_info=True)
                    out = None
                # 失败语义:该元素为 None
                results.append(out)

            return TranslationResponse(
                text=raw_text,
                target_lang=request.target_lang,
                source_lang=request.source_lang,
                translated_text=results,
                status="success",
                model=str(getattr(translator, "model", model)),
            )

        # 单文本模式:保持原有严格失败语义
        translated_text = translator.translate(
            text=raw_text,
            target_lang=request.target_lang,
            source_lang=request.source_lang,
            context=request.context,
            prompt=request.prompt,
        )

        if translated_text is None:
            raise HTTPException(
                status_code=500,
                detail="Translation failed"
            )

        return TranslationResponse(
            text=raw_text,
            target_lang=request.target_lang,
            source_lang=request.source_lang,
            translated_text=translated_text,
            status="success",
            model=str(getattr(translator, "model", 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
    )