# 🔧 Solución para Error "Requested format is not available" ## ❌ Problema ```json { "detail": "Error de yt-dlp al obtener metadatos: ERROR: [youtube] 6hini9Xz_fc: Requested format is not available. Use --list-formats for a list of available formats" } ``` Este error ocurre cuando: 1. El video no tiene subtítulos en el formato json3 solicitado 2. El video tiene subtítulos pero en otro formato (srv3, vtt, etc.) 3. El video no está disponible o tiene restricciones --- ## ✅ Solución Implementada He mejorado el código para: ### 1. **Aceptar Múltiples Formatos de Subtítulos** Ahora el sistema acepta: - **json3** (JSON format 3 de YouTube) - **srv3** (Server format 3) - **vtt** (WebVTT format) ### 2. **Búsqueda Inteligente de Subtítulos** El sistema busca en orden: 1. `requested_subtitles` (subtítulos solicitados) 2. `automatic_captions` (subtítulos automáticos) 3. `subtitles` (subtítulos manuales) ### 3. **Parser Flexible** Nueva función `parse_subtitle_format()` que maneja: - JSON3: Formato estructurado de YouTube - SRV3: Similar a JSON3 - VTT: Formato de texto WebVTT --- ## 🚀 Actualizar el Sistema ### Método 1: Script Automático ```bash ./docker-update-system.sh ``` ### Método 2: Manual ```bash # 1. Detener servicios docker-compose down # 2. Reconstruir con los cambios docker-compose build --no-cache # 3. Iniciar docker-compose up -d # 4. Verificar logs docker-compose logs -f tubescript_api ``` --- ## 🧪 Probar la Solución ### Test con el video que falló: ```bash # Probar el video específico curl -X GET "http://localhost:8080/transcript/6hini9Xz_fc?lang=es" ``` ### Test con otros videos: ```bash # Video de noticias (usualmente tiene subtítulos) curl -X GET "http://localhost:8080/transcript/jNQXAC9IVRw?lang=en" # Video popular curl -X GET "http://localhost:8080/transcript/dQw4w9WgXcQ?lang=en" ``` --- ## 🔍 Diagnóstico del Problema ### Verificar Formatos Disponibles ```bash # Entrar al contenedor docker exec -it tubescript_api /bin/bash # Ver formatos disponibles para un video yt-dlp --list-subs https://www.youtube.com/watch?v=6hini9Xz_fc # Intentar con diferentes formatos yt-dlp --skip-download --write-auto-subs --sub-langs "es.*" \ --dump-json https://www.youtube.com/watch?v=6hini9Xz_fc ``` ### Ver Logs Detallados ```bash # Ver últimos errores del API docker logs tubescript_api 2>&1 | grep -i "error" | tail -20 # Ver todo el log del último intento docker logs tubescript_api 2>&1 | tail -100 ``` --- ## 💡 Mejoras Implementadas en el Código ### Antes: ```python command = [ "yt-dlp", "--skip-download", "--write-auto-subs", "--sub-format", "json3", # ❌ Solo json3 "--sub-langs", f"{lang}.*", "--dump-json", url ] ``` ### Después: ```python command = [ "yt-dlp", "--skip-download", "--write-auto-subs", # ✅ Sin forzar formato "--write-subs", # ✅ También manuales "--sub-langs", f"{lang}.*", "--dump-json", url ] # ✅ Busca en múltiples fuentes for subtitle_option in automatic_captions[lang_key]: ext = subtitle_option.get('ext', '') if ext in ['json3', 'srv3', 'vtt']: # ✅ Acepta múltiples formatos requested_subs = {lang_key: subtitle_option} break ``` --- ## 📊 Formatos de Subtítulos Soportados | Formato | Descripción | Soporte | |---------|-------------|---------| | **json3** | JSON estructurado de YouTube | ✅ Completo | | **srv3** | Server format de YouTube | ✅ Completo | | **vtt** | WebVTT (texto plano) | ✅ Básico | | **ttml** | Timed Text Markup Language | ⏳ Futuro | | **srt** | SubRip format | ⏳ Futuro | --- ## ⚠️ Casos Especiales ### Video Sin Subtítulos Si un video no tiene subtítulos en ningún formato: ```json { "detail": "No se encontraron subtítulos para el idioma 'es'. El video puede no tener subtítulos disponibles." } ``` **Solución:** Probar con otro idioma o verificar que el video tenga subtítulos. ### Video con Restricciones Si el video tiene restricciones geográficas o de edad: ```json { "detail": "Acceso denegado (HTTP 403). El video puede tener restricciones geográficas o de edad. Intenta agregar cookies.txt." } ``` **Solución:** Agregar cookies.txt de tu cuenta de YouTube. ### Video Privado o Eliminado ```json { "detail": "Error de yt-dlp al obtener metadatos: ERROR: [youtube] Video unavailable" } ``` **Solución:** Verificar que el video esté disponible públicamente. --- ## 🎯 Ejemplo de Uso Completo ### 1. Actualizar Sistema ```bash ./docker-update-system.sh ``` ### 2. Probar Endpoint ```bash # Con cURL curl -X GET "http://localhost:8080/transcript/6hini9Xz_fc?lang=es" | jq # Con HTTPie http GET localhost:8080/transcript/6hini9Xz_fc lang==es # Con Python import requests response = requests.get("http://localhost:8080/transcript/6hini9Xz_fc?lang=es") print(response.json()) ``` ### 3. Procesar Respuesta ```python import requests video_id = "6hini9Xz_fc" response = requests.get(f"http://localhost:8080/transcript/{video_id}?lang=es") if response.status_code == 200: data = response.json() print(f"✅ Se obtuvieron {data['count']} segmentos de subtítulos") # Mostrar primeros 5 segmentos for segment in data['segments'][:5]: print(f"{segment['start']:.1f}s: {segment['text']}") else: print(f"❌ Error: {response.json()['detail']}") ``` --- ## 🔄 Nuevo Flujo de Procesamiento ``` 1. Solicitar metadatos sin forzar formato ↓ 2. Buscar en requested_subtitles ↓ Si no hay 3. Buscar en automatic_captions ↓ Para cada idioma 4. Buscar formato: json3, srv3, o vtt ↓ Si encuentra 5. Descargar subtítulos ↓ 6. Detectar formato automáticamente ↓ 7. Parsear según formato: - JSON3 → clean_youtube_json() - SRV3 → clean_youtube_json() - VTT → parse_vtt_format() ↓ 8. Retornar formato estándar ``` --- ## 📝 Formato de Salida Estándar Independientemente del formato de entrada, la salida siempre es: ```json { "video_id": "6hini9Xz_fc", "count": 150, "segments": [ { "start": 0.0, "duration": 2.5, "text": "Texto del subtítulo" }, { "start": 2.5, "duration": 3.0, "text": "Siguiente segmento" } ] } ``` --- ## ✅ Checklist de Solución - [x] ✅ Remover `--sub-format json3` del comando yt-dlp - [x] ✅ Agregar búsqueda en múltiples fuentes - [x] ✅ Soportar formatos json3, srv3, vtt - [x] ✅ Crear función `parse_subtitle_format()` - [x] ✅ Manejar errores específicos por formato - [x] ✅ Documentar la solución - [ ] ⏳ Actualizar tu sistema - [ ] ⏳ Probar con el video problemático - [ ] ⏳ Verificar logs --- ## 🎉 Resumen ### Problema: - ❌ Solo buscaba formato json3 - ❌ No manejaba videos sin ese formato ### Solución: - ✅ Busca en múltiples formatos (json3, srv3, vtt) - ✅ Parser flexible para cada formato - ✅ Búsqueda inteligente en múltiples fuentes - ✅ Mensajes de error claros ### Próximo Paso: ```bash # Actualiza tu sistema ./docker-update-system.sh # Prueba el endpoint curl -X GET "http://localhost:8080/transcript/6hini9Xz_fc?lang=es" ``` --- **TubeScript API Pro © 2026** Soporte Multi-Formato de Subtítulos Implementado ✅