(+351) 21 24 10006  ·  info@bconcepts.pt
Carnaxide, Lisboa

Cómo crear un servicio de traducción multimodal en Azure AI & Machine Learning

João Barros 20 de November de 2026 5 min de lectura

Esta guía muestra cómo crear un servicio sencillo de traducción multimodal en Azure AI & Machine Learning: extraer texto de imágenes, transcribir audio y traducir a otro idioma. Útil para automatizar subtitulado, soporte en atención al cliente o procesado de contenidos multimedia.

Requisitos previos

  • Cuenta Azure con permisos para crear recursos (Cognitive Services / Azure ML).
  • Azure CLI instalada y autenticada (az login).
  • Python 3.8+ y pip.
  • Clave y endpoint de Azure AI Vision y de Azure AI Speech o un recurso único que soporte ambos.
  • Editor de texto y ficheros de ejemplo: imagen con texto y fichero de audio corto (wav).

Paso 1: Explicar la arquitectura y elegir servicios

Por qué: es importante comprender las piezas. Vamos a usar Azure AI Vision para extraer texto de imágenes (OCR), Azure AI Speech para transcribir audio y Azure AI Language Translator (o el endpoint integrado del recurso Language) para traducir texto. El flujo es: obtener texto (imagen/audio) → normalizar → traducir → devolver resultado.

Paso 2: Preparar el entorno Python

Instalar las librerías oficiales y configurar variables de entorno para las claves y endpoints. Esto simplifica llamadas HTTP/SDK.

pip install azure-ai-formrecognizer azure-cognitiveservices-speech requests python-dotenv # criar .env com AZURE_VISION_KEY, AZURE_VISION_ENDPOINT, AZURE_SPEECH_KEY, AZURE_SPEECH_REGION, AZURE_TRANSLATOR_KEY, AZURE_TRANSLATOR_ENDPOINT 

Paso 3: Extraer texto de una imagen con Azure AI Vision (OCR)

Usar el endpoint de OCR o Form Recognizer/Read API. Ejemplo mínimo en Python usando el Read API por HTTP para mantenerlo simple y compatible.

import os, time, requests
from dotenv import load_dotenv
load_dotenv()
VISION_ENDPOINT = os.getenv('AZURE_VISION_ENDPOINT')
VISION_KEY = os.getenv('AZURE_VISION_KEY')
headers = {'Ocp-Apim-Subscription-Key': VISION_KEY, 'Content-Type': 'application/octet-stream'}
img_path = 'sample.jpg'
with open(img_path, 'rb') as f:
    data = f.read()
resp = requests.post(VISION_ENDPOINT + '/vision/v3.2/read/analyze', headers=headers, data=data)
operation_location = resp.headers.get('Operation-Location')
status = ''
while status != 'succeeded':
    time.sleep(1)
    r = requests.get(operation_location, headers={'Ocp-Apim-Subscription-Key': VISION_KEY})
    result = r.json()
    status = result['status']
texts = []
if status == 'succeeded':
    for readResult in result['analyzeResult']['readResults']:
        for line in readResult['lines']:
            texts.append(line['text'])
image_text = '\n'.join(texts)
print('Texto extraído:', image_text)

Paso 4: Transcribir audio con Azure AI Speech

Usar el SDK azure-cognitiveservices-speech para transcribir un fichero WAV local a texto. Mantenemos el ejemplo síncrono para ficheros pequeños.

import azure.cognitiveservices.speech as speechsdk
SPEECH_KEY = os.getenv('AZURE_SPEECH_KEY')
SPEECH_REGION = os.getenv('AZURE_SPEECH_REGION')
audio_file = 'sample.wav'
speech_config = speechsdk.SpeechConfig(subscription=SPEECH_KEY, region=SPEECH_REGION)
audio_input = speechsdk.AudioConfig(filename=audio_file)
speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config, audio_config=audio_input)
result = speech_recognizer.recognize_once()
if result.reason == speechsdk.ResultReason.RecognizedSpeech:
    audio_text = result.text
else:
    audio_text = ''
print('Transcripción:', audio_text)

Paso 5: Traducir texto con Azure Translator (o Azure AI Language)

Enviar el texto extraído/transcrito al endpoint de traducción. Ejemplo en HTTP para el servicio Translator Text.

TRANSLATOR_KEY = os.getenv('AZURE_TRANSLATOR_KEY')
TRANSLATOR_ENDPOINT = os.getenv('AZURE_TRANSLATOR_ENDPOINT')
params = {'api-version': '3.0', 'to': 'pt'}
headers = {'Ocp-Apim-Subscription-Key': TRANSLATOR_KEY, 'Content-Type': 'application/json'}
# traduzir imagem
body = [{'text': image_text}]
resp = requests.post(TRANSLATOR_ENDPOINT + '/translate', params=params, headers=headers, json=body)
translated_image = resp.json()[0]['translations'][0]['text']
# traduzir áudio
body2 = [{'text': audio_text}]
resp2 = requests.post(TRANSLATOR_ENDPOINT + '/translate', params=params, headers=headers, json=body2)
translated_audio = resp2.json()[0]['translations'][0]['text']
print('Imagem traduzida:', translated_image)
print('Áudio traduzido:', translated_audio)

Paso 6: Unir el flujo y gestionar errores comunes

Combine los pasos en un script que decida la fuente (imagen/audio) y ejecute OCR → traducción o transcripción → traducción. Errores comunes: claves incorrectas, endpoints inválidos, ficheros con formato no soportado. Verifique el estado HTTP y los mensajes en el JSON de error.

# Exemplo esquemático: chamar funções extract_text_from_image(), transcribe_audio(), translate_text()
# Tratar exceções, verificar resp.status_code e campos de erro antes de aceder ao JSON

Verificar el resultado

Confirme que recibe texto legible de la imagen y del audio y que las traducciones tienen sentido. Pruebe con varias imágenes (diferentes fuentes, idiomas) y ficheros de audio. Verifique tiempos de respuesta y mensajes de error en el terminal. Si obtiene códigos 401/403, confirme las claves; si obtiene 429, está excediendo el límite y debe reducir la tasa de llamadas o usar un plan superior.

Conclusión

Ahora dispone de un servicio básico de traducción multimodal en Azure AI & Machine Learning que combina Azure AI Vision, Azure AI Speech y Translator. Siguientes pasos: mejorar la normalización del texto, añadir detección automática de idioma, paralelizar llamadas para mayor escala e integrar en un endpoint Azure Functions o Azure ML endpoint para producción. Consejo: registre los payloads y tiempos para optimizar costes y rendimiento — ¿qué flujo multimodal quiere automatizar primero?