auto-save 2026-05-13 09:37 (~4)
This commit is contained in:
40
api/main.py
40
api/main.py
@@ -462,6 +462,46 @@ class CreateJobReq(BaseModel):
|
||||
url: str
|
||||
|
||||
|
||||
class TranslateReq(BaseModel):
|
||||
text: str
|
||||
target: Literal["en", "zh"] = "en"
|
||||
|
||||
|
||||
@app.post("/translate")
|
||||
def translate_text(req: TranslateReq) -> dict:
|
||||
"""单条文本翻译(给生图自定义提取元素 zh→en 用)"""
|
||||
import re as _re
|
||||
text = req.text.strip()
|
||||
if not text:
|
||||
return {"text": ""}
|
||||
if not LLM_API_KEY:
|
||||
raise HTTPException(503, "LLM_API_KEY 未配置")
|
||||
|
||||
target_label = "English" if req.target == "en" else "Simplified Chinese"
|
||||
prompt = (
|
||||
f"Translate the following text into concise {target_label}, suitable as an element "
|
||||
"label in an image-generation prompt. Output only the translation itself — no quotes, "
|
||||
"no punctuation, no explanation, no markdown.\n\n"
|
||||
f"Input: {text}"
|
||||
)
|
||||
try:
|
||||
resp = llm().chat.completions.create(
|
||||
model=TRANSLATE_MODEL,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
temperature=0.2,
|
||||
max_tokens=200,
|
||||
)
|
||||
out = (resp.choices[0].message.content or "").strip()
|
||||
if not out:
|
||||
rc = getattr(resp.choices[0].message, "reasoning_content", "") or ""
|
||||
if rc:
|
||||
out = rc.strip().splitlines()[-1].strip()
|
||||
out = _re.sub(r'^[\'"「『]+|[\'"」』]+$', "", out).strip()
|
||||
return {"text": out}
|
||||
except Exception as e:
|
||||
raise HTTPException(500, f"translate failed: {e}")
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health() -> dict:
|
||||
return {
|
||||
|
||||
Reference in New Issue
Block a user