Files
wordloop/backend/services/translation_service.py
T
John bd7635986a Initial commit: WordLoop 单词学习应用
Vue 前端 + FastAPI 后端,含部署脚本与词典数据。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-04 14:30:53 -07:00

86 lines
2.5 KiB
Python

import re
from typing import Optional
from sqlalchemy.orm import Session
from services.dictionary_service import dictionary_service
def contains_chinese(text: str) -> bool:
return bool(re.search(r"[\u4e00-\u9fff]", text))
class TranslationService:
"""翻译服务:优先查离线词典表,未命中时返回占位结果(暂不接入外部 API)。"""
def translate(self, db: Session, text: str) -> dict:
text = text.strip()
if not text:
raise ValueError("输入不能为空")
if contains_chinese(text):
return self._zh_to_en(db, text)
return self._en_to_zh(db, text)
def _en_to_zh(self, db: Session, text: str) -> dict:
entry = dictionary_service.lookup_en(db, text)
if entry:
return self._build_response(
text,
entry.zh,
"en",
"zh",
entry.phonetic,
entry.example_en,
entry.example_cn,
)
return self._placeholder(text, text, "en", "zh")
def _zh_to_en(self, db: Session, text: str) -> dict:
entry = dictionary_service.lookup_zh(db, text)
if entry:
return self._build_response(
text,
entry.lemma_en,
"zh",
"en",
entry.phonetic,
entry.example_en,
entry.example_cn,
)
return self._placeholder(text, f"[{text}]", "zh", "en")
def _build_response(
self,
source: str,
target: str,
source_lang: str,
target_lang: str,
phonetic: Optional[str],
example_en: Optional[str],
example_cn: Optional[str],
) -> dict:
return {
"source_text": source,
"target_text": target,
"source_lang": source_lang,
"target_lang": target_lang,
"phonetic": phonetic,
"example_en": example_en,
"example_cn": example_cn,
}
def _placeholder(self, source: str, target: str, source_lang: str, target_lang: str) -> dict:
return {
"source_text": source,
"target_text": target,
"source_lang": source_lang,
"target_lang": target_lang,
"phonetic": None,
"example_en": f"Example with {target}." if target_lang == "en" else None,
"example_cn": f"包含「{source}」的例句。" if source_lang == "zh" else None,
}
translation_service = TranslationService()