To enforce that only French input is accepted and show an error if the input is in any other language, you can use the Azure Translator Detect API before attempting translation. Here's how to modify your code.
import requests, uuid, json
# Add your key and endpoint
key = "<key>"
endpoint = "https://api.cognitive.microsofttranslator.com/" #text translation endpoint
location = "northeurope"
# Input text
input_text = "Hello, friend! What did you do today?"
xt = "Bonjour Monsier Manas"
# Step 1: Detect language
detect_url = endpoint + "/detect"
detect_headers = {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
detect_body = [{'text': input_text}]
detect_response = requests.post(detect_url, params={'api-version': '3.0'}, headers=detect_headers, json=detect_body)
detected_language = detect_response.json()[0]['language']
# Step 2: Validate and translate if French
if detected_language == 'fr':
translate_url = endpoint + "/translate"
translate_params = {
'api-version': '3.0',
'from': 'fr',
'to': ['sq']
}
translate_headers = detect_headers # Same headers
translate_body = [{'text': input_text}]
translate_response = requests.post(translate_url, params=translate_params, headers=translate_headers, json=translate_body)
print(json.dumps(translate_response.json(), sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))
else:
print(f"Error: Only French input is accepted. Detected language was '{detected_language}'ptu.")
#output
Error: Only French input is accepted. Detected language was 'en'.
Reference used -
https://free.blessedness.top/en-us/azure/ai-services/translator/text-translation/reference/v3/detect
Hope it helps address the issue.
Thank you