mnhkahn commited on
Commit
4f0c607
·
1 Parent(s): 3d03d3f

feat(翻译): 添加双向翻译功能并改进错误处理

Browse files

添加英文到中文的翻译器,支持通过toLang参数选择翻译方向
增加错误处理逻辑,当翻译失败时记录错误并返回500状态码

Files changed (1) hide show
  1. app.py +25 -4
app.py CHANGED
@@ -349,7 +349,10 @@ structure_model = load_structure_model(device)
349
  # 初始化翻译器
350
  from transformers import pipeline
351
 
352
- translator = pipeline("translation", model="Helsinki-NLP/opus-mt-zh-en")
 
 
 
353
 
354
  # 初始化文本转语音模型
355
  from fastapi.responses import FileResponse
@@ -431,9 +434,27 @@ async def upload_text(file: UploadFile = File(...)):
431
 
432
 
433
  @app.get("/translate")
434
- async def translate(text: str = Query(..., description="Text to translate")):
435
- translation = translator(text)
436
- return {"translation": translation}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
 
438
 
439
  @app.get("/text-to-speech")
 
349
  # 初始化翻译器
350
  from transformers import pipeline
351
 
352
+ # 中文到英文翻译器
353
+ translator_zh_en = pipeline("translation", model="Helsinki-NLP/opus-mt-zh-en")
354
+ # 英文到中文翻译器
355
+ translator_en_zh = pipeline("translation", model="Helsinki-NLP/opus-mt-en-zh")
356
 
357
  # 初始化文本转语音模型
358
  from fastapi.responses import FileResponse
 
434
 
435
 
436
  @app.get("/translate")
437
+ async def translate(
438
+ text: str = Query(..., description="Text to translate"),
439
+ toLang: str = Query("English", description="Target language: English or Chinese"),
440
+ ):
441
+ """
442
+ 翻译文本到指定语言。
443
+
444
+ - **text**: 需要翻译的文本
445
+ - **toLang**: 目标语言 (English 或 Chinese)
446
+ """
447
+ try:
448
+ if toLang.lower() == "chinese":
449
+ # 英文到中文翻译
450
+ translation = translator_en_zh(text)
451
+ else:
452
+ # 中文到英文翻译
453
+ translation = translator_zh_en(text)
454
+ return {"translation": translation}
455
+ except Exception as e:
456
+ logger.error(f"Translation error: {e}")
457
+ raise HTTPException(status_code=500, detail=f"服务器内部错误: {e}")
458
 
459
 
460
  @app.get("/text-to-speech")