File size: 2,108 Bytes
4fcd019 5b9a030 4fcd019 c5e3791 4fcd019 c5e3791 4fcd019 5b9a030 4fcd019 5b9a030 4fcd019 5b9a030 4fcd019 c5e3791 | 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 52 53 54 55 56 57 58 59 60 61 62 63 | """
Translation for TalkToDoc.
Translates patient input into English for the provider, and translates the
provider's reply back into the patient's selected language.
Uses the OpenAI API, via the official openai SDK.
MOCK_MODE: if set to "true" in the env file, this skips the real API call
entirely and returns the input text unchanged instead. This exists so
the whole app (Whisper, YarnGPT, MMS-TTS, the database, all the routing
and session logic) can be run and tested locally with zero cost and no
API key, before deciding to actually acquire one. It is not a substitute
for testing real translation quality, only for testing everything else.
"""
import os
from dotenv import load_dotenv
load_dotenv("env")
MOCK_MODE = os.environ.get("MOCK_MODE", "").lower() == "true"
if not MOCK_MODE:
from openai import OpenAI
_client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
SUPPORTED_LANGUAGES = ["english", "yoruba", "hausa", "igbo", "pidgin"]
MODEL = "gpt-5.6-terra"
def translate(text, source_language, target_language):
"""
text: the text to translate
source_language: one of "english", "yoruba", "hausa", "igbo", "pidgin"
target_language: one of "english", "yoruba", "hausa", "igbo", "pidgin"
Returns the translated text only.
"""
if MOCK_MODE:
if source_language.lower() == target_language.lower():
return text
return f"[MOCK, no real translation: {source_language} -> {target_language}] {text}"
prompt = (
f"Translate the following text from {source_language} to {target_language}. "
f"Reply with only the translated text and nothing else, no explanation.\n\n"
f"Text: {text}"
)
response = _client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt}],
)
return response.choices[0].message.content.strip()
if __name__ == "__main__":
import sys
if len(sys.argv) < 4:
print('Usage: python translation.py "text" source_language target_language')
else:
print(translate(sys.argv[1], sys.argv[2], sys.argv[3]))
|