File size: 2,242 Bytes
b3bb0f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!apt update && apt install -y ffmpeg
import yt_dlp
from smolagents import tool
import os

@tool
def youtube_audio_downloader(video_url:str) ->str :
    """
    This tool downloads the audio of a Youtube video given a Youtube Url and returns the downlaoded path.

    Args:
        video_url: URL of the Youtube video.
    """
    ydl_opts = {
    'format': 'bestaudio/best',
    'outtmpl': './downloads/%(title)s.%(ext)s',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
        }],
    }

    try:
        os.makedirs("./downloads", exist_ok=True)
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            info = ydl.extract_info(video_url, download=True)
            title = info['title']
            filepath = f"./downloads/{title}.mp3"
        return filepath
    except Exception as e:
        return f'error occured: {e}'
    

@tool
def youtube_video_downloader(video_url:str) ->str :
    """
    This tool downloads the Youtube video given a Youtube Url and returns the downlaoded path.

    Args:
        video_url: URL of the Youtube video.
    """
    ydl_opts = {
        #'format': 'bestvideo+bestaudio/best',
        'format': 'bestvideo[height<=720][vcodec^=avc1]+bestaudio[acodec^=mp4a]/best[ext=mp4]',
        'outtmpl': 'downloads/%(title)s.%(ext)s',
        'merge_output_format': 'mp4',

        'writesubtitles': True,              # Download user-provided subtitles
        'subtitleslangs': ['en'],            # Use your preferred language(s)
        'embedsubtitles': True,              # Enable embedding into video

        'postprocessors': [
            {'key': 'FFmpegEmbedSubtitle'}   # Actually does the embedding
        ]
    }

    try:
        os.makedirs("./downloads", exist_ok=True)

        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            info = ydl.extract_info(video_url, download=True)
            title = info.get('title')
            filepath = f"./downloads/{title}.mp4"
            if not os.path.exists(filepath):
                return f"Error: File not found after download: {filepath}"
        return filepath
    except Exception as e:
        return f'error occured while downloading the video: {e}'