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))