Azure AI Tutorial 10 : Dịch Văn Bản Và Âm Thanh
Xử lý ngôn ngữ tự nhiên đã trở thành một trong những keyword trong machine learning nói riêng, AI nói chung. Và xử lý đa ngôn ngữ là một trong những task khó khăn của NLP.
Có rất nhiều giải pháp đưa ra tìm người biết nhiều ngôn ngữ để phiên dịch giữa các ngôn ngữ. Tuy nhiên vì điều kiện khan hiếm nguồn lực nên chúng ta cần công cụ máy học để làm điều đó.
Từ đó dịch tự động hay còn gọi là dịch máy ngày càng được phát triển và sử dụng nhiều hơn.
Chúng ta cùng đi vào khám phá và thực hành các dịch vụ translation của Azure nào.
1. Tạo Cognitive Service Resource
Tương tự như các bài trước. Xem tại đây nhé.
2. Tạo notebook
- Copy key, endpoint và cog_region
cog_key = '0afbab280c9f42e589143a683845a0c5'
cog_endpoint = 'https://mvcognitiveservice.cognitiveservices.azure.com/'
cog_location = 'westus'
3. Dịch đoạn văn bản
Đơn giản là chúng ta có 1 đoạn text từ ngôn ngữ này, sang ngôn ngữ khác.
Đặc biệt ở phần Translation này chúng ta không cần install thư viện mà chỉ sử dụng REST để gửi request thông qua HTTP. Và thông tin trả về sẽ thuộc JSON format.
def translate_text(cog_region, cog_key, text, to_lang='vi', from_lang='en'):
import requests, uuid, json
# Create the URL for the Text Translator service REST request
path = 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0'
params = '&from={}&to={}'.format(from_lang, to_lang)
constructed_url = path + params
# Prepare the request headers with Cognitive Services resource key and region
headers = {
'Ocp-Apim-Subscription-Key': cog_key,
'Ocp-Apim-Subscription-Region':cog_region,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# Add the text to be translated to the body
body = [{
'text': text
}]
# Get the translation
request = requests.post(constructed_url, headers=headers, json=body)
response = request.json()
return response[0]["translations"][0]["text"]
# Test the function
text_to_translate = "My name is Vinh"
translation = translate_text(cog_region, cog_key, text_to_translate, to_lang=vi, from_lang='en')
print('{} -> {}'.format(text_to_translate,translation))
Output:
My name is Vinh -> Tên tôi là Vinh
3.2 Thử dịch ngôn ngữ Ý
text_to_translate = "My Name is Vinh"
translation = translate_text(cog_region, cog_key, text_to_translate, to_lang='it-IT', from_lang='en-GB')
print('{} -> {}'.format(text_to_translate,translation))
Output: My Name is Vinh -> Mi chiamo Vinh
3.3. Thử dịch qua tiếng Trung
text_to_translate = "My name is Vinh"
translation = translate_text(cog_region, cog_key, text_to_translate, to_lang='zh-CN', from_lang='en-US')
print('{} -> {}'.format(text_to_translate,translation))
Output: My name is Vinh -> 我叫文
4. Dịch từ giọng nói
Tương tự như bài trước chúng ta cần thêm thư viện để hỗ trợ giọng nói. Nếu chưa có cần install nhé
! pip install azure.cognitiveservices.speech
Tiếp theo chúng ta cần 1 file âm thanh. Mình có thu âm để sẵn và nói : My Name is Vinh
Tiếp theo chạy code test thử nào.
# Create a function to translate audio in one language to text in another
def translate_speech(cog_region, cog_key, audio_file=None, to_lang='fr-FR', from_lang='en-US'):
from azure.cognitiveservices.speech import SpeechConfig, AudioConfig, ResultReason
from azure.cognitiveservices.speech.translation import SpeechTranslationConfig, TranslationRecognizer
# Configure the speech translation service
translation_config = SpeechTranslationConfig(subscription=cog_key, region=cog_region)
translation_config.speech_recognition_language = from_lang
translation_config.add_target_language(to_lang)
# Configure audio input
if audio_file is None:
audio_config = AudioConfig() # Use default input (microphone)
else:
audio_config = AudioConfig(filename=audio_file) # Use file input
# Create a translation recognizer and use it to translate speech input
recognizer = TranslationRecognizer(translation_config, audio_config)
result = recognizer.recognize_once()
# Did we get it?
translation = ''
speech_text = ''
if result.reason == ResultReason.TranslatedSpeech:
speech_text = result.text
translation = result.translations[to_lang]
elif result.reason == ResultReason.RecognizedSpeech:
speech_text = result.text
translation = 'Unable to translate speech'
else:
translation = 'Unknown'
speech_text = 'Unknown'
# rturn the translation
return speech_text, translation
# Test the function
import os, IPython
file_name = 'vinh1.wav'
file_path = os.path.join('data', 'translation', file_name)
speech, translated_speech = translate_speech(cog_region, cog_key, file_path, to_lang='vi', from_lang='en-US')
result = '{} -> {}'.format(speech, translated_speech)
# Play audio and show translated text
IPython.display.display(IPython.display.Audio(file_path, autoplay=True),
IPython.display.HTML(result))
Output: Hello, my name is Vivian. -> Xin chào, tên tôi là Vivian.
Chắc trong quá trình nhận dạng giọng nói. Tên mình là "Vinh" mà nó nhận diện thành Vivian.. Anyway azure đã hoàn thành tốt công việc translation.
Chúc các bạn thành công!