pythonintermediate

Real-Time Translation Pipeline with OpenAI

Build a language detection and translation pipeline using GPT for multi-language support.

python
from openai import OpenAI
from typing import Optional

client = OpenAI()

def detect_and_translate(text: str, target_lang: str = 'English') -> dict:
    detect_resp = client.chat.completions.create(
        model='gpt-4o-mini',
        response_format={'type': 'json_object'},
        messages=[{
            'role': 'user',
            'content': f'Detect the language of this text and return JSON {{"language": "..."}}: {text!r}'
        }],
    )
    import json
    source_lang = json.loads(detect_resp.choices[0].message.content)['language']

    if source_lang.lower() == target_lang.lower():
        return {'source': source_lang, 'target': target_lang, 'translation': text, 'same_language': True}

    trans_resp = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[{'role':'system','content':f'Translate to {target_lang}. Return only the translation.'},{'role':'user','content':text}],
    )
    return {'source': source_lang, 'target': target_lang, 'translation': trans_resp.choices[0].message.content}

for sample in ['Bonjour le monde!', 'ๆ—ฅๆœฌ่ชžใฎใƒ†ใ‚นใƒˆ', 'Hello World']:
    result = detect_and_translate(sample)
    print(f'{sample!r} ({result["source"]}) -> {result["translation"]}')

Use Cases

  • multilingual apps
  • auto-translation
  • language detection

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.