Error when creating an Action to summarize youtube videos

Hi!

Can someone help me with this error,

Error “Image build for im-qzhImKiVUQH9kLinLwCYN1 failed with the exception: task exited with failure, status = exit status: 1”

Code


import requests

def summaryvideo(url_video: str):
“”"
Resume un video de youtube

Args:
    url_video (string): URL del video
"""

# Insert your PYTHON code below. You can access environment variables using os.environ[].
# Currently, only the requests library is supported, but more libraries will be available soon.
# Use print statements or return values to display results to the user.
# If you save a png, pdf, csv, jpg, webp, gif, or html file in the root directory, it will be automatically displayed to the user.
# You do not have to call this function as the bot will automatically call and fill in the parameters.

Importar las bibliotecas necesarias

import os
import pytube
import speech_recognition as sr
import nltk
from nltk.tokenize import sent_tokenize
from nltk.corpus import stopwords
from collections import Counter
from moviepy.editor import AudioFileClip
import tempfile

nltk.download(‘punkt’)
nltk.download(‘stopwords’)

def download_video(url_video, save_path):
“”“Descarga un video de YouTube y guarda solo el audio.”“”
try:
yt = pytube.YouTube(url_video)
stream = yt.streams.filter(only_audio=True).first()
audio_path = stream.download(output_path=save_path)
return audio_path
except Exception as e:
print(f"Error al descargar el video: {e}")
return None

def extract_audio(video_path):
“”“Convierte el archivo de video a solo audio en formato WAV.”“”
try:
audio_path = tempfile.mktemp(suffix=‘.wav’)
clip = AudioFileClip(video_path)
clip.write_audiofile(audio_path)
clip.close()
return audio_path
except Exception as e:
print(f"Error al extraer audio: {e}")
return None

def transcribe_audio(audio_path):
“”“Transcribe el audio a texto usando SpeechRecognition.”“”
recognizer = sr.Recognizer()
with sr.AudioFile(audio_path) as source:
audio = recognizer.record(source)
try:
text = recognizer.recognize_google(audio, language=“es-ES”)
return text
except sr.UnknownValueError:
print(“No se pudo entender el audio.”)
return “”
except sr.RequestError as e:
print(f"Error en el servicio de reconocimiento: {e}")
return “”

def summarize_text(text):
“”“Resume el texto transcrito usando NLP.”“”
sentences = sent_tokenize(text)
stop_words = set(stopwords.words(“spanish”))

# Tokenización y conteo de frecuencia de palabras
words = [word.lower() for word in nltk.word_tokenize(text) if word.isalnum()]
filtered_words = [word for word in words if word not in stop_words]
word_counts = Counter(filtered_words)

# Ponderación de oraciones por importancia
sentence_scores = {}
for sentence in sentences:
    for word in nltk.word_tokenize(sentence.lower()):
        if word in word_counts:
            if sentence not in sentence_scores:
                sentence_scores[sentence] = word_counts[word]
            else:
                sentence_scores[sentence] += word_counts[word]

# Seleccionar las oraciones con puntuación más alta
summary_sentences = sorted(sentence_scores, key=sentence_scores.get, reverse=True)[:3]
summary = " ".join(summary_sentences)
return summary

def summarize_video(url_video):
“”“Ejecuta el proceso completo para resumir el video.”“”
# Directorio temporal para guardar el archivo descargado
with tempfile.TemporaryDirectory() as temp_dir:
print(“Descargando el video…”)
video_path = download_video(url_video, temp_dir)
if not video_path:
return “No se pudo descargar el video.”

    print("Extrayendo el audio...")
    audio_path = extract_audio(video_path)
    if not audio_path:
        return "No se pudo extraer el audio del video."

    print("Transcribiendo el audio...")
    text = transcribe_audio(audio_path)
    if not text:
        return "No se pudo transcribir el audio."

    print("Resumiendo el contenido...")
    summary = summarize_text(text)
    return summary

Ejemplo de uso

url_video = “https://www.youtube.com/watch?v=abcdefghijk
resultado = summarize_video(url_video)
print(“Resumen del video:”, resultado)

Why are you trying to build an action to summarize youtube videos?

If you simply past in a link and ask for a summary, the tool will provide one.

Hi,

Because when I try it from a form, I get the following message:

“Unfortunately, I do not have the ability to view videos or access media content, so I am unable to view the video from the link provided. However, if you can describe the content of the video to me, I will be happy to help you summarize it based on the parameters you mentioned. Forward!”

You have succeeded? you have entered a youtube URL from a form and got the summary? Can you show me how?

Thank you,

It doesn’t work in the builder, but everywhere else it should work fine. Try this tool. You can clone it and see it’s very simple. It won’t work 100% of the time, sometimes YT will block the request and it’ll say it can’t. But I’d say it works with 80% of videos.

Your action might also work, but it looks very complex, unfortunately we don’t have the bandwidth to directly assist you with it.

I ran it 10 times and none of them worked.

Thanks anyway.