{
"cells": [
{
"cell_type": "markdown",
"id": "9b37365737140463",
"metadata": {
"collapsed": false,
"id": "9b37365737140463"
},
"source": [
"# UD03 · Notebook 11 — Prototipo de asistente virtual\n",
"\n",
"Esta práctica propone la creación de un prototipo del sistema de traducción que permite recibir órdenes en un idioma y ejecutarlos en otro idioma. Por ejemplo, el usuario podría decir \"open the door\" y el sistema respondería \"abre la puerta\". Este prototipo se basará en el uso de modelos de HugginFace previamente entrenados para la traducción y la síntesis de voz."
]
},
{
"cell_type": "markdown",
"id": "9936077d0223c66f",
"metadata": {
"collapsed": false,
"id": "9936077d0223c66f"
},
"source": [
"## Buscar modelos previamente entrenados\n",
"\n",
"El primer paso es buscar modelos previamente entrenados para las tareas solicitadas. Investigue Huggingface para seleccionar modelos que mejor satisfagan las necesidades del prototipo.\n",
"\n",
"Cuando haya seleccionado los modelos, modifique las siguientes variables para incluirlas en el prototipo:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c82d304a41b86f34",
"metadata": {
"ExecuteTime": {
"end_time": "2024-02-12T12:12:15.937726Z",
"start_time": "2024-02-12T12:12:15.876568Z"
},
"id": "c82d304a41b86f34"
},
"outputs": [],
"source": [
"# Modelo de voz de texto\n",
"\n",
"MODELO_VOZ_A_TEXTO = \"\"\n",
"\n",
"# Model de traducción ingles a español\n",
"\n",
"MODELO_TRADUCCION = \"\"\n",
"\n",
"# Modelo de texto a voz\n",
"\n",
"MODELO_TEXTO_A_VOZ = \"\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**trampas técnicas de este ejercicio**\n",
"\n",
"\n",
"- **Cargar el audio**: `asr(\"OpenTheDoor.wav\")` puede fallar con\n",
" `ffmpeg was not found` si tu entorno no tiene `ffmpeg` instalado (el contenedor de la unidad\n",
" no lo trae). Alternativa sin `ffmpeg`: carga el audio tú mismo con `librosa` o `soundfile`\n",
" y pásaselo al *pipeline* como diccionario `{\"array\": ..., \"sampling_rate\": ...}`.\n",
"- **La frecuencia de muestreo**: Whisper espera **16.000 Hz**, y `OpenTheDoor.wav` no está a\n",
" esa frecuencia. Si la cargas con `librosa.load(ruta, sr=16000)`, el propio `librosa` la\n",
" remuestrea al vuelo.\n",
"- **La traducción**: en las versiones recientes de `transformers`, `pipeline(\"translation\",\n",
" model=...)` **ya no existe** como tarea genérica. Para un modelo Marian como\n",
" `Helsinki-NLP/opus-mt-en-es`, usa directamente `AutoTokenizer` +\n",
" `AutoModelForSeq2SeqLM.generate(...)`. Necesitarás además `pip install sentencepiece`.\n",
""
]
},
{
"cell_type": "markdown",
"id": "243cf421240069fa",
"metadata": {
"collapsed": false,
"id": "243cf421240069fa"
},
"source": [
"## Implementación del prototipo\n",
"\n",
"Una vez que se seleccionan los modelos previamente entrenados, implementa el prototipo.Para hacer esto, puede seguir los siguientes pasos:\n",
"\n",
"1. Cree una función que, dada una orden de voz, lo transforme en texto (_Automatic Speech Recognition_ ASR). Para hacer esto, puede usar el modelo `MODELO_VOZ_A_TEXTO` previamente seleccionado. Como ejemplo, puede usar el siguiente archivo de voz: [OpenTheDoor.wav](OpenTheDoor.wav)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "338ba3514989899f",
"metadata": {
"ExecuteTime": {
"start_time": "2024-02-12T12:12:15.938435Z"
},
"colab": {
"base_uri": "https://localhost:8080/",
"height": 209
},
"id": "338ba3514989899f",
"is_executing": true,
"outputId": "26ea95c7-0dbb-4b1c-c826-d65d4fe153b4"
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/usr/local/lib/python3.11/dist-packages/huggingface_hub/utils/_auth.py:94: UserWarning: \n",
"The secret `HF_TOKEN` does not exist in your Colab secrets.\n",
"To authenticate with the Hugging Face Hub, create a token in your settings tab (https://huggingface.co/settings/tokens), set it as secret in your Google Colab and restart your session.\n",
"You will be able to reuse this secret in all of your notebooks.\n",
"Please note that authentication is recommended but still optional to access public models or datasets.\n",
" warnings.warn(\n",
"Device set to use cpu\n",
"/usr/local/lib/python3.11/dist-packages/transformers/models/whisper/generation_whisper.py:573: FutureWarning: The input name `inputs` is deprecated. Please make sure to use `input_features` instead.\n",
" warnings.warn(\n",
"You have passed language=english, but also have set `forced_decoder_ids` to [[1, None], [2, 50359]] which creates a conflict. `forced_decoder_ids` will be ignored in favor of language=english.\n"
]
},
{
"data": {
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
},
"text/plain": [
"' Open the door.'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Creamos la tubería para la conversión de voz a texto\n",
"from transformers import pipeline\n",
"\n",
"\n",
"\n",
"# Convertimos la voz en texto\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "8af0a933321b4a91",
"metadata": {
"collapsed": false,
"id": "8af0a933321b4a91"
},
"source": [
"2. Crea una función que, dado un texto y un idioma, lo traduce al español (_machine translation_). Para hacer esto, puede usar el modelo `MODELO_TRADUCCION` seleccionado anteriormente. Como ejemplo, puede usar el siguiente pedido en texto: \"Abra la puerta\"."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1bd3c8ff42a90ec",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 88
},
"id": "1bd3c8ff42a90ec",
"is_executing": true,
"outputId": "73c9e428-b6e3-4b0b-b877-45671a19a32a"
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/usr/local/lib/python3.11/dist-packages/transformers/models/marian/tokenization_marian.py:175: UserWarning: Recommended: pip install sacremoses.\n",
" warnings.warn(\"Recommended: pip install sacremoses.\")\n",
"Device set to use cpu\n"
]
},
{
"data": {
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
},
"text/plain": [
"'Abre la puerta.'"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Creamos la tubería para la traducción\n",
"\n",
"\n",
"\n",
"# Traducimos el texto al español\n",
"\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "7508ebc5f4f49b64",
"metadata": {
"collapsed": false,
"id": "7508ebc5f4f49b64"
},
"source": [
"3. Crea una función que, dado un texto, lo sintetice en voz (_Text to speech_). Para hacer esto, puede usar el modelo `MODELO_TEXTO_A_VOZ` seleccionado anteriormente. Como ejemplo, puede usar el texto \"abre la puerta\"."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "78e6d98ccacc786c",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "78e6d98ccacc786c",
"is_executing": true,
"outputId": "ec27d306-6304-4318-de3e-fc7f144cee7a"
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Device set to use cpu\n"
]
}
],
"source": [
"# Creamos la tubería para la síntesis de voz\n",
"\n",
"\n",
"\n",
"# Sintetizamos el texto en voz\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "ng0-gZ-oRjY2",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 76
},
"id": "ng0-gZ-oRjY2",
"outputId": "78e9c60a-e280-407c-ad9a-9bd964db7a5b"
},
"outputs": [
{
"data": {
"text/html": [
"\n",
" \n",
" "
],
"text/plain": [
""
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# mostramos el texto sintetizado como un reproductor\n",
"\n",
"from IPython.display import Audio\n",
"\n",
"Audio(out[\"audio\"], rate=out['sampling_rate'])"
]
},
{
"cell_type": "markdown",
"id": "gzPwaMiHcHiS",
"metadata": {
"id": "gzPwaMiHcHiS"
},
"source": [
"4.- Une las tres funciones anteriores en una sola función que, dada una voz y un idioma, lo transforma en texto, lo traduce en otro idioma y la sintetizando en la voz. Como ejemplo, puede usar el siguiente audio de voz: [OpenTheDoor.wav](OpenTheDoor.wav)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "RM2xBgS4cswx",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 145
},
"id": "RM2xBgS4cswx",
"outputId": "dc5e3311-c56e-4d7d-bba6-828090a84138"
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/usr/local/lib/python3.11/dist-packages/transformers/models/whisper/generation_whisper.py:573: FutureWarning: The input name `inputs` is deprecated. Please make sure to use `input_features` instead.\n",
" warnings.warn(\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"text from audio: Open the door.\n",
"text in spanish: Abre la puerta.\n"
]
},
{
"data": {
"text/html": [
"\n",
" \n",
" "
],
"text/plain": [
""
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Aquí generamos una funcion que lo aglutine todo\n",
"\n",
"from IPython.display import Audio\n",
"\n",
"\n",
"def assistant(voice_order):\n",
" # Convertimos la voz a texto\n",
"\n",
"\n",
" # Traducimos el texto al español\n",
"\n",
"\n",
" # Sintetizamos el texto en voz\n",
"\n",
"\n",
"\n",
" return out\n",
"\n",
"out = assistant(\"OpenTheDoor.wav\")\n",
"\n",
"Audio(out[\"audio\"], rate=out['sampling_rate'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Entrega\n",
"\n",
"Completa y ejecuta el notebook entero (todas las celdas, sin errores) antes de subirlo a la tarea\n",
"correspondiente en Moodle."
]
}
],
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}