import requests | |
# Define the translation function | |
def translate_text(source_text, source_lang="en", target_lang="hi"): | |
# API endpoint (replace with the actual endpoint if available) | |
api_url = "https://ai4bharat.iitm.ac.in/translate" # Placeholder URL | |
# Prepare payload and headers | |
payload = { | |
"service": "ai4bharat/indictrans--gpu-t4", | |
"source_language": source_lang, | |
"target_language": target_lang, | |
"text": source_text, | |
"enable_transliteration": True | |
} | |
headers = { | |
"Content-Type": "application/json" | |
} | |
# Send a POST request to the API | |
response = requests.post(api_url, json=payload, headers=headers) | |
# Handle the response | |
if response.status_code == 200: | |
translated_text = response.json().get("translated_text", "Translation failed") | |
return translated_text | |
else: | |
print(f"Error {response.status_code}: {response.text}") | |
return None | |
# Example usage | |
source_text = "Hello, how are you?" | |
source_language = "en" # English | |
target_language = "hi" # Hindi | |
translated_output = translate_text(source_text, source_language, target_language) | |
print(f"Translated Text: {translated_output}") | |