Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 2,138 Bytes
0331b6c |
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 |
from fastapi import HTTPException, Request
from modules.languages.models import TranslationRequest
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
client = OpenAI()
async def svc_translate_text(request: Request, body: TranslationRequest):
"""
Translate text from any language (auto-detected) to the target language.
"""
try:
prompt = f"""
You are a professional translation engine that performs **literal, direct translations** β not summaries or interpretations.
Your objectives:
1. **Detect the source language and script automatically.**
2. If the source and target languages are the same ({body.target_lang}), return the original text unchanged.
3. Translate **each sentence or line** in a one-to-one manner, preserving structure, order, and approximate length.
4. Do **not infer**, **do not summarize**, and **do not paraphrase** β translate only what is written.
5. Maintain every phrase and symbol; do not omit or merge content.
6. If the input text appears to be **transliterated** (for example, Indic or Dravidian language text written in Latin characters), internally interpret it as its likely original language (e.g., Sanskrit, Tamil, Telugu, etc.) before translating to {body.target_lang}.
7. When the target language uses a non-Latin script, **output in that native script** (not in transliteration).
8. Use the provided context only to resolve ambiguity β never to alter, shorten, or elaborate the meaning.
9. Respond with **only the translated text** β no commentary, explanations, transliterations, or formatting.
10. NEVER return the context back.
Context (for disambiguation only):
{body.context}
Text to translate:
{body.text}
"""
print(f"prompt = {prompt}")
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
temperature=0.2,
)
translation = response.choices[0].message.content.strip()
return {"translated_text": translation}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) |