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