‍යුටුබ් විඩියොස් ඩවුන්ලොඩ කරගන්න පයිතන් ස්ක්‍රිප්ට් එකක්

SLHodahitha

Well-known member
  • Nov 8, 2017
    3,089
    2,979
    113
    ::0
    elakiri.com
    මට ඔන උනා ඔක්කොම බන කතා බාවනා කරන දෙවල් ටැබ් එකකට ඩවුන් ලොඩ් කරලා අහන්න දෙන්න. එකට මන් මෙවගේ එකක් ලියාගත්ත videos tika youtube eken eka parata download karaganna.

    ඔන කෙනෙකුට යුස් කරන්න මන් මෙතන දානවා.



    Python:
    from pytube import YouTube, Playlist
    from pytube.exceptions import VideoUnavailable
    from multiprocessing import Pool, freeze_support
    import os
    import time
    
    def remove_invalid_characters(text):
        # Replace or remove invalid characters
        invalid_characters = '<>:"/\\|?*'
        for char in invalid_characters:
            text = text.replace(char, '')
        return text
    
    def download_video(video_url):
        def on_progress(stream, chunk, remaining):
            total_size = stream.filesize
            bytes_downloaded = total_size - remaining
    
            # Calculate the download percentage
            progress = (bytes_downloaded / total_size) * 100
            print(f"Download progress for {video_url}: {progress:.2f}%")
    
        try:
            if "playlist" in video_url.lower():
                playlist = Playlist(video_url)
                playlist_title = remove_invalid_characters(playlist.title)[:50]  # Truncate title for file name
                output_path = 'videos/playlists'
    
                # Ensure the 'videos/playlists' directory exists
                if not os.path.exists(output_path):
                    os.makedirs(output_path)
    
                for video in playlist.videos:
                    file_name = "{}.mp4".format(remove_invalid_characters(video.title)[:50])
                    file_path = os.path.join(output_path, file_name)
    
                    # Check if the file already exists, if not, download it
                    if not os.path.isfile(file_path):
                        video.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').asc().first().download(filename=file_name, output_path=output_path)
                        print(f"Downloaded {file_name}")
                    else:
                        print(f"Video {file_name} already exists, skipping download.")
    
            else:
                yt = YouTube(video_url)
                video_title = remove_invalid_characters(yt.title)[:50]  # Truncate title for file name
                file_name = "{}.mp4".format(video_title)
                output_path = 'videos/singles'
    
                # Ensure the 'videos/singles' directory exists
                if not os.path.exists(output_path):
                    os.makedirs(output_path)
    
                # Check if the file already exists, if not, download it
                if not os.path.isfile(os.path.join(output_path, file_name)):
                    yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').asc().first().download(filename=file_name, output_path=output_path)
                    print(f"Downloaded {file_name}")
                else:
                    print(f"Video {file_name} already exists, skipping download.")
    
        except VideoUnavailable as e:
            print(f"Video {video_url} is unavailable: {e}")
        except Exception as e:
            print(f"An unexpected error occurred: {e}")
    
    if __name__ == '__main__':
        # Read video URLs from a file
        with open('video_ids.txt', 'r', encoding='utf-8') as file:
            urls_list = [line.strip() for line in file]
    
        # Use multiprocessing to download videos concurrently
        freeze_support()  # needed for Windows
        with Pool(4) as p:
            p.map(download_video, urls_list)

    video_ids.txt kiyala file ekak hadala ekata mehema dagattahama hari.

    Code:
    video_ids.txt
    
    https://www.youtube.com/watch?v=gcEIKp0glw4
    https://www.youtube.com/watch?v=Gx7OCySdFHg
    https://www.youtube.com/watch?v=7dOzEUt47_w
    https://www.youtube.com/watch?v=bmC64eZOnOw
    https://www.youtube.com/watch?v=xsOCUouw_94
    https://www.youtube.com/playlist?list=PLF26CCB1679908248


    Code:
    pip3 install pytube
    then run python3 yourscriptname.py

    https://pytube.io/en/latest/user/install.html
     

    SLHodahitha

    Well-known member
  • Nov 8, 2017
    3,089
    2,979
    113
    ::0
    elakiri.com
    චැට් ජීපීටී වගේ

    Ow, sinhala names tiyana kota program eka crash una files save une title eka aragena nisa. GPT karaya thama goda dala damme.

    # Replace or remove invalid characters
    invalid_characters = '<>:"/\\|?*'

    Programming danne nathi unath concept eka kiwama u wede karala denawa.
    eka sira.
     

    SLHodahitha

    Well-known member
  • Nov 8, 2017
    3,089
    2,979
    113
    ::0
    elakiri.com
    meken oya okkoma kraganna puluwan ne

    https://github.com/ytdl-org/youtube-dl
    thanks machan. man danan hitiye na meka

    උඹට ytdlp use කරන්න තිබ්බෙ pytube නැතුව. Pytube discontinued නෙ..
    thanks machan man danan hitiye na.
    ------ Post added on Nov 24, 2023 at 9:05 PM

    math code ekak hadagaththa start end time deela video eken kallak kapagaganda..
    ffmpeg da use kale?
    ------ Post added on Nov 24, 2023 at 9:06 PM
     
    • Like
    Reactions: rockmon

    garfieldzz

    Well-known member
  • May 28, 2014
    2,424
    3,043
    113
    ජෝන්ගෙ ගෙදර
    මෙන්න ෆෙරෙන් මගෙනුත් ටිකක් ... හ්ම්ම්:-)

    මේකෙන් playlist එකක්ම එකපාර ගන්න පුළුවන්.


    මේක mp3 වලට

    Code:
    from google.colab import drive
    drive.mount('/content/drive')
    ////////////////////////////////////////////////////////////////////////////////////////
    
    Single Videos
    
    !pip install yt-dlp pydub
    import os
    import shutil
    from pydub import AudioSegment
    import yt_dlp
    
    # Define the YouTube video URL and yt-dlp configuration
    video_url = 'https://youtube.com/watch?v=VIDEO_ID_HERE'  # Replace VIDEO_ID_HERE with the actual video ID
    output_dir = '/content/drive/MyDrive/Server2/Mp3'
    config = {
        'format': 'bestaudio/best',
        'outtmpl': f'{output_dir}/%(title)s.%(ext)s',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }]
    }
    
    # Download the audio stream from the video with yt-dlp
    with yt_dlp.YoutubeDL(config) as ydl:
        ydl.download([video_url])
    
    # Convert the downloaded file to MP3 and remove the original file
    for root, _, files in os.walk(output_dir):
        for file in files:
            if file.endswith('.webm'):
                webm_file = os.path.join(root, file)
                mp3_file = os.path.join(root, f"{os.path.splitext(file)[0]}.mp3")
    
                # Load the audio file with PyDub and export it as an MP3 file
                audio = AudioSegment.from_file(webm_file, format='webm')
                audio.export(mp3_file, format='mp3')
    
                # Delete the original audio file
                os.remove(webm_file)
    
    # Print success message
    print("Downloaded and converted the audio file.")
    
    /////////////////////////////////////////////////////////////////////////////////////////
    
    Entire Playlist
    
    !pip install yt-dlp pydub
    
    import os
    import shutil
    from pydub import AudioSegment
    import yt_dlp
    
    # Define the YouTube playlist URL and yt-dlp configuration
    playlist_url = 'https://youtube.com/playlist?list=PL_vv5lulznh3s9aO7Dk-BRtfxQAH09jhB'
    output_dir = '/content/drive/MyDrive/Music_Server/Remixes/DJ_Theesh'
    config = {
        'format': 'bestaudio/best',
        'outtmpl': f'{output_dir}/%(title)s.%(ext)s',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }]
    }
    
    # Download the audio streams from the playlist with yt-dlp
    with yt_dlp.YoutubeDL(config) as ydl:
        try:
            ydl.download([playlist_url])
        except Exception as e:
            print(f"Error while downloading: {e}")
    
    # Convert downloaded files to MP3 and remove the original files
    for root, _, files in os.walk(output_dir):
        for file in files:
            if file.endswith('.webm'):
                webm_file = os.path.join(root, file)
                mp3_file = os.path.join(root, f"{os.path.splitext(file)[0]}.mp3")
    
                # Check if the MP3 file already exists, if yes, skip downloading and conversion
                if os.path.exists(mp3_file):
                    print(f"File {mp3_file} already exists. Skipping...")
                    os.remove(webm_file)
                    continue
    
                try:
                    # Load the audio file with PyDub and export it as an MP3 file
                    audio = AudioSegment.from_file(webm_file, format='webm')
                    audio.export(mp3_file, format='mp3')
    
                    # Delete the original audio file
                    os.remove(webm_file)
                except Exception as e:
                    print(f"Error while converting {webm_file} to MP3: {e}")
                    continue
    
    # Print success message
    print("Downloaded and converted the audio files from the playlist.")

    මෙන්න වීඩියෝ වලට

    Code:
    ///////////////////////////////////////////////////////////////////////////////////
    
    from google.colab import drive
    drive.mount('/content/drive')
    ///////////////////////////////////////////////////////////////////////////////////
    
    !pip install pytube
    
    from pytube import Playlist
    import os
    
    # Set the URL of the YouTube playlist
    url = 'https://youtube.com/playlist?list=PLn5T02q8Os_vPbNjB9kzoYedjFgfWGxZk'
    playlist = Playlist(url)
    
    # Set the preferred resolution of the video stream to download
    preferred_resolution = '1080p'
    
    # Iterate over all the videos in the playlist
    for video in playlist.videos:
        try:
            # Get the video streams with the preferred resolution
            video_streams = video.streams.filter(res=preferred_resolution)
    
            # If no video streams with the preferred resolution are found, get the highest resolution video stream
            if not video_streams:
                video_stream = video.streams.get_highest_resolution()
            else:
                video_stream = video_streams.first()
    
            # If no video stream is found, skip to the next video
            if video_stream is None:
                print(f"No video streams found for {video.title}. Skipping.")
                continue
    
            # Download the video stream
            video_filename = video.title + '.mp4'
            video_stream.download(output_path="/content/drive/MyDrive/Tutorial's", filename=video_filename)
    
            # Print the filename of the downloaded file
            print(f"Downloaded video file: {video_filename}")
    
        except Exception as e:
            # Print the exception and move on to the next video
            print(f"An error occurred while processing {video.title}: {e}")
            continue
     

    Any.key

    Well-known member
  • Jul 13, 2017
    10,524
    12,937
    113
    මෙන්න ෆෙරෙන් මගෙනුත් ටිකක් ... හ්ම්ම්:-)

    මේකෙන් playlist එකක්ම එකපාර ගන්න පුළුවන්.


    මේක mp3 වලට

    Code:
    from google.colab import drive
    drive.mount('/content/drive')
    ////////////////////////////////////////////////////////////////////////////////////////
    
    Single Videos
    
    !pip install yt-dlp pydub
    import os
    import shutil
    from pydub import AudioSegment
    import yt_dlp
    
    # Define the YouTube video URL and yt-dlp configuration
    video_url = 'https://youtube.com/watch?v=VIDEO_ID_HERE'  # Replace VIDEO_ID_HERE with the actual video ID
    output_dir = '/content/drive/MyDrive/Server2/Mp3'
    config = {
        'format': 'bestaudio/best',
        'outtmpl': f'{output_dir}/%(title)s.%(ext)s',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }]
    }
    
    # Download the audio stream from the video with yt-dlp
    with yt_dlp.YoutubeDL(config) as ydl:
        ydl.download([video_url])
    
    # Convert the downloaded file to MP3 and remove the original file
    for root, _, files in os.walk(output_dir):
        for file in files:
            if file.endswith('.webm'):
                webm_file = os.path.join(root, file)
                mp3_file = os.path.join(root, f"{os.path.splitext(file)[0]}.mp3")
    
                # Load the audio file with PyDub and export it as an MP3 file
                audio = AudioSegment.from_file(webm_file, format='webm')
                audio.export(mp3_file, format='mp3')
    
                # Delete the original audio file
                os.remove(webm_file)
    
    # Print success message
    print("Downloaded and converted the audio file.")
    
    /////////////////////////////////////////////////////////////////////////////////////////
    
    Entire Playlist
    
    !pip install yt-dlp pydub
    
    import os
    import shutil
    from pydub import AudioSegment
    import yt_dlp
    
    # Define the YouTube playlist URL and yt-dlp configuration
    playlist_url = 'https://youtube.com/playlist?list=PL_vv5lulznh3s9aO7Dk-BRtfxQAH09jhB'
    output_dir = '/content/drive/MyDrive/Music_Server/Remixes/DJ_Theesh'
    config = {
        'format': 'bestaudio/best',
        'outtmpl': f'{output_dir}/%(title)s.%(ext)s',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }]
    }
    
    # Download the audio streams from the playlist with yt-dlp
    with yt_dlp.YoutubeDL(config) as ydl:
        try:
            ydl.download([playlist_url])
        except Exception as e:
            print(f"Error while downloading: {e}")
    
    # Convert downloaded files to MP3 and remove the original files
    for root, _, files in os.walk(output_dir):
        for file in files:
            if file.endswith('.webm'):
                webm_file = os.path.join(root, file)
                mp3_file = os.path.join(root, f"{os.path.splitext(file)[0]}.mp3")
    
                # Check if the MP3 file already exists, if yes, skip downloading and conversion
                if os.path.exists(mp3_file):
                    print(f"File {mp3_file} already exists. Skipping...")
                    os.remove(webm_file)
                    continue
    
                try:
                    # Load the audio file with PyDub and export it as an MP3 file
                    audio = AudioSegment.from_file(webm_file, format='webm')
                    audio.export(mp3_file, format='mp3')
    
                    # Delete the original audio file
                    os.remove(webm_file)
                except Exception as e:
                    print(f"Error while converting {webm_file} to MP3: {e}")
                    continue
    
    # Print success message
    print("Downloaded and converted the audio files from the playlist.")

    මෙන්න වීඩියෝ වලට

    Code:
    ///////////////////////////////////////////////////////////////////////////////////
    
    from google.colab import drive
    drive.mount('/content/drive')
    ///////////////////////////////////////////////////////////////////////////////////
    
    !pip install pytube
    
    from pytube import Playlist
    import os
    
    # Set the URL of the YouTube playlist
    url = 'https://youtube.com/playlist?list=PLn5T02q8Os_vPbNjB9kzoYedjFgfWGxZk'
    playlist = Playlist(url)
    
    # Set the preferred resolution of the video stream to download
    preferred_resolution = '1080p'
    
    # Iterate over all the videos in the playlist
    for video in playlist.videos:
        try:
            # Get the video streams with the preferred resolution
            video_streams = video.streams.filter(res=preferred_resolution)
    
            # If no video streams with the preferred resolution are found, get the highest resolution video stream
            if not video_streams:
                video_stream = video.streams.get_highest_resolution()
            else:
                video_stream = video_streams.first()
    
            # If no video stream is found, skip to the next video
            if video_stream is None:
                print(f"No video streams found for {video.title}. Skipping.")
                continue
    
            # Download the video stream
            video_filename = video.title + '.mp4'
            video_stream.download(output_path="/content/drive/MyDrive/Tutorial's", filename=video_filename)
    
            # Print the filename of the downloaded file
            print(f"Downloaded video file: {video_filename}")
    
        except Exception as e:
            # Print the exception and move on to the next video
            print(f"An error occurred while processing {video.title}: {e}")
            continue
    kallak ganna vidiyak nadda bro?