def get_song_info(given_url="", local_dir=cur_dir, quality=1):
    """Returns song info for given YouTube url"""
    url = is_valid_youtube_url(given_url)
    yt = YouTube(url)
    raw_info = yt.get_video_data()
    if 'args' in raw_info:
        song_info = copy.copy(empty_record)
        song_info['url'] = url
        song_info['title'] = raw_info['args']['title']
        song_info['author'] = raw_info['args']['author']
        try:
            song_info['video_id'] = raw_info['args']['vid']
        except KeyError:
            song_info['video_id'] = url.replace(youtube_base_url, '')
        song_info['duration'] = int(raw_info['args']['length_seconds'])
        song_info['view_count'] = int(raw_info['args']['view_count'])
        song_info['thumbnail_url'] = raw_info['args']['thumbnail_url']
        filter_index = get_filter_index(quality, len(yt.filter()))
        video = yt.filter()[filter_index]
        local_file_name = "{0}.{1}".format(yt.filename, video.extension)
        local_file_path = os.path.join(local_dir, local_file_name)
        if os.path.exists(local_file_path):
            song_info['local_file_path'] = local_file_path
        return song_info
    else:
        return None
def download_single_video(save_dir, video_url):

    yt = YouTube(video_url)
    try:
        video = min(yt.filter('mp4'))
    except:
        video = min(yt.get_videos())
     
    # save_dir = "video/" + label + "/"
    if not (os.path.isdir(save_dir)):
        os.mkdir(save_dir)

    valid_chars = "-_ %s%s" % (string.ascii_letters, string.digits)
    filename = ''.join(c for c in yt.filename if c in valid_chars)

    filename = filename.replace('-','_')
    filename = filename.replace(' ','_')
    while(filename[-1] == '_'):
        filename = filename[:-1]

    if(os.path.isfile(save_dir + filename + '.' + video.extension)):
        return

    yt.set_filename(filename)
    video.download(save_dir)
Example #3
0
def downloadVideo(url, codec):
    try:
	yt = YouTube(url)
	vidName = str(yt.filename)
	start_time = time.time()
	if codec == 0:
	    print "(+) Codec: MP4"
            allVidFormat = yt.get_videos()
            higMp4Res = str(yt.filter('mp4')[-1]).split()[-3]
            print "\n(+) Name: %s" %vidName
            print "(+) URL: %s" %url
            print "(+) Resolution: %s" %higMp4Res
            video = yt.get('mp4', higMp4Res)
            print "(+) Downloading video"
            video.download('.')
            print "(+) Download complete"
	if codec == 1:
	    print "[youtube] Codec: MP3"
	    ydl = youtube_dl.YoutubeDL()
	    r = ydl.extract_info(url, download=False)	
	    options = {'format': 'bestaudio/best', 'extractaudio' : True, 'audioformat' : "best", 'outtmpl': r['title'], 'noplaylist' : True,} 
	    print "[youtube] Name: %s" % (vidName)
	    print "[youtube] Uploaded by: %s" % (r['uploader'])
	    print "[youtube] Likes: %s | Dislikes: %s" % (r['like_count'], r['dislike_count'])
	    print "[youtube] Views: %s" % (r['view_count']) 
	    with youtube_dl.YoutubeDL(options) as ydl:
	        ydl.download([url])
	    print("[youtube] Download Time: %s sec" % round((time.time() - start_time), 2))
	    print ""	
    except Exception as e:
        print "(-) Error: %s" %e
Example #4
0
File: app.py Project: MB6/flask_yt
def yt_api(yt_id):
    video = YouTube()
    try:
        video.url = "http://youtube.com/watch?v=%s" % yt_id
    except:
        return render_template('404.html'), 404
    return json.dumps({"%s-%s" % (video.resolution, video.extension) : video.url for video in video.videos})
Example #5
0
def download_videoFrom_youtube(url, savePath):
    yt = YouTube(url)
    pprint(yt.get_videos())
    print(yt.filename)
    #yt.set_filename()
    video = yt.get('mp4', '360p')
    video.download(savePath)
Example #6
0
    def fetch_video_by_url(self, url):
        '''Fetch video by url

        :param [str] url:
            The url linked to a YouTube video
        '''
        yt = YouTube(url)
        if(self.resolution == 'highest' or self.resolution == 'lowest'):
            video_list = yt.filter(self.extension)
            if(len(video_list) == 0):
                raise DoesNotExist("No videos met this criteria.")
            if(self.resolution == 'highest'):
                video = video_list[-1]
            else:
                video = video_list[0]
        else:
            result = []
            for v in yt.get_videos():
                if self.extension and v.extension != self.extension:
                    continue
                elif self.resolution and v.resolution != self.resolution:
                    continue
                else:
                    result.append(v)
            matches = len(result)
            if matches <= 0:
                raise DoesNotExist("No videos met this criteria.")
            elif matches == 1:
                video = result[0]
            else:
                raise MultipleObjectsReturned("Multiple videos met this criteria.")
        return video
Example #7
0
File: app.py Project: MB6/flask_yt
def yt_web(yt_id):
    video = YouTube()
    try:
        video.url = "http://youtube.com/watch?v=%s" % yt_id
    except:
        return render_template('404.html'), 404
    return render_template("webtable.html", videos=[("%s-%s" % (video.resolution, video.extension) , video.url) for video in video.videos])
Example #8
0
File: PyKo.py Project: eleweek/PyKo
def downloadSong(url):
    video = pafy.new(url)
    best = video.getbest(preftype="mp4")
    yt = YouTube()
    yt.url = url
    os.system('cls') # os.system('clear') for linux.
    print "Download URL fetched successfully!\n"
    print "1. Get the list of available streams"
    print "2. Get the highest resolution available"
    print "3. Start download the video\n"

    while True:
        print "Select an action: "
        action = raw_input("> ")

        if action == str(1):
            print "Availabile streams for the URL: \n"
            pprint(yt.videos)
            print "\n"

        elif action == str(2):
            print "Highest resolution is:"
            pprint(yt.filter('mp4')[-1])
            print "\n"

        elif action == str(3):
            print "Starting download: \n"
            best.download(quiet=False)
            print "Download finished!, the file has been downloaded to the same folder where the script is located."
            sys.exit(0)

        else:
            print "Not a valid option!\n"
def download_Video_Audio(path, vid_url, file_no):
    try:
        yt = YouTube(vid_url)
    except Exception as e:
        print("Error:", str(e), "- Skipping Video with url '"+vid_url+"'.")
        return

    try:  # Tries to find the video in 720p
        video = yt.get('mp4', '720p')
    except Exception:  # Sorts videos by resolution and picks the highest quality video if a 720p video doesn't exist
        video = sorted(yt.filter("mp4"), key=lambda video: int(video.resolution[:-1]), reverse=True)[0]

    print("downloading", yt.filename+" Video and Audio...")
    try:
        bar = progressBar()
        video.download(path, on_progress=bar.print_progress, on_finish=bar.print_end)
        print("successfully downloaded", yt.filename, "!")
    except OSError:
        print(yt.filename, "already exists in this directory! Skipping video...")

    try:
        os.rename(yt.filename+'.mp4',str(file_no)+'.mp4')
        aud= 'ffmpeg -i '+str(file_no)+'.mp4'+' '+str(file_no)+'.wav'
        final_audio='lame '+str(file_no)+'.wav'+' '+str(file_no)+'.mp3'
        os.system(aud)
        os.system(final_audio)
        os.remove(str(file_no)+'.wav')
        print("sucessfully converted",yt.filename, "into audio!")
    except OSError:
        print(yt.filename, "There is some problem with the file names...")
 def _download_file(self, video_id):
     file_path = self._build_file_path(video_id)
     if not os.path.isfile(file_path):
         yt = YouTube()
         yt.from_url("http://youtube.com/watch?v=" + video_id)
         yt.filter('mp4')[0].download(file_path)  # downloads the mp4 with lowest quality
     return file_path
Example #11
0
 def _download_file(self, video_id):
     file_path = self._build_file_path(video_id)
     if not os.path.isfile(file_path):
         yt = YouTube()
         yt.from_url("http://youtube.com/watch?v=" + video_id)
         video = yt.filter('mp4')[0]
         video.download(file_path)
     return file_path
Example #12
0
 def __init__(self,url):
     self.url = url
     yt = YouTube()
     yt.url = url
     video = yt.get('mp4', '480p')
     video = yt.get('mp4')
     video.download()
     self.name = (str(yt.filename) + ".mp4")
Example #13
0
def post_submit():
    yt = YouTube()
    url = request.form.get('url')
    yt.url = url
    video = yt.get('mp4', '360p')
    video.download('./')
    filename = yt.filename
    return redirect(url_for('index', filename=filename))
Example #14
0
 def youtube_download(video_ids):
     video_ids = video_ids.split('\n')
     for video_id in video_ids:
         yt = YouTube('https://www.youtube.com/watch?v=' + video_id)
         video = yt.get('mp4')
         name = yt.filename
         if not os.path.isfile('res/' + name + 'mp4'):
             video.download('res/')
         yield ('res/' + name + '.mp4', name)
Example #15
0
	def download_now(self, url, codec='mp4', location='/tmp/'):
		try:
			yt = YouTube(url)
			yt.get_videos()
			video = yt.filter(codec)[0]
			print 'file name:', video.filename
			video.download(location, on_progress=utils.print_status)
		except Exception, e:
			print "Error: Invalid URL or network problem or file exist"
Example #16
0
	def updateUi(self): 
		self.outtext.append("Download has started!!")
		yt = YouTube()
		yt.from_url(self.intext.toPlainText())
		yt.set_filename("Temp")
		video = yt.videos[0]
		video.download()
		self.outtext.append("Download Finished!!")
		pass
Example #17
0
	def download_now(self, url, codec='mp4', location='/tmp/'):
		try:
			yt = YouTube(self.url)
			yt.get_videos()
			video = yt.filter(codec)[0]
			video.download(location)
		except Exception, e:
			print e
			print "Error: Invalid URL or network problem"
Example #18
0
def download_youtube(url, timeout=0, chunk_size=config.DEFAULT_CHUNKSIZE):

    def _cleanup_filename(path):
        # removes the container type from the movie file
        # filename, placed automatically by pytube module.
        # this is an ``on_finish`` callback method from Video.download(..)
        pre, ext = os.path.splitext(path)
        os.rename(path, pre)

    def _sort_by_quality(v_list):
        # give better codecs a higher score than worse ones,
        # so that in resolution ties, the better codec is picked.
        boost = {
            'webm': 1.2,
            'mp4': 1.1,
            'flv': 1.0,
            '3gp': 0.7}
        video_scores = dict()
        for v in v_list:
            score = int(v.resolution.strip('pP')) * boost.get(v.extension.lower(), 0.9) + int(v.audio_bitrate)
            video_scores[score] = v
        return video_scores

    url = url.get('url', None)

    if not url:
        return None

    logger.info('downloading (youtube) video: ' + url)

    try:
        # get our Youtube Video instance given a url
        yt = YouTube(url)
        # generate a new temp movie name, so we can set the download
        # filename..and point the ``video.get(..)`` to the ``path`` portion.
        fullpath = gen_filename(config.DROP_FOLDER_LOCATION, extension='movie')
        path, name = os.path.split(fullpath)
        yt.set_filename(name)

        # no built in way to get BEST video option
        video_formats = _sort_by_quality(yt.get_videos())
        highest_quality = sorted(video_formats.items(), reverse=True)[0][1]  # [(score, Video<inst>), .., ..]

        # download that shit
        video = yt.get(highest_quality.extension, highest_quality.resolution, profile=highest_quality.profile)
        video.download(path, chunk_size=chunk_size, on_finish=_cleanup_filename)

    except Exception as e:
        # something went wrong...
        logger.error(e)
        return None

    else:
        # if the new file path is there, then it completed successfully,
        # otherwise return ``None`` to handle an error case given our JSON.
        return True if os.path.exists(fullpath) else None
Example #19
0
def get_vids_from_list(vidlist_file, path=None):
    if path == None:
        path = os.path.dirname(os.path.abspath(__file__))

    with open(vidlist_file) as vl:
        for video_url in vl:
            video_url = video_url.strip()
            yt = YouTube(video_url)
            video = yt.get('mp4', '720p')
            video.download(path)
def download_links(linkList, pathWrite):
	''' Download the links '''
	name_num = 0

	for l in linkList:
		y = YouTube(l)
		y.set_filename(str(name_num))
		video = y.get('mp4', '720p')
		video.download(pathWrite)
		name_num += 1
def download_video(video_url):  # this ffunction will take video url as input and download the corresponding video
    yt = YouTube(video_url)
    print("The available formats and quality of %s are as follows :" % yt.filename)
    pprint(yt.get_videos())
    vid_for = input("Please select appropriate file format and quality (e.g. flv 480p) : ")
    print("The download of %s in " % yt.filename + vid_for + " quality is starting")
    vid_for = vid_for.split(" ")
    video = yt.get(vid_for[0], resolution=vid_for[1])
    video.download("")
    print("Download Competed")
Example #22
0
def Download(songURI, bestQuality = False):
	filetype = "mp4"
	#Check if NAS is mounted
	nasDir = '/home/pi/music/yt/'
	bckDir = '/home/pi/musicBAK/'
	dirUse = nasDir
	if os.path.isdir(nasDir):
		#put bck files into nasDirs
		bakFiles = os.listdir(bckDir)
		for x in range(0,len(bakFiles)):
			shutil.copy(bckDir+bakFiles[x], nasDir+bakFiles[x])
			os.remove(bckDir+bakFiles[x])
	else:
		dirUse = bckDir

	#if input is null then return
	if songURI == "":
		return
	
	songURL = "https://www.youtube.com/watch?v="+songURI
	#use full url if that is given
	if  "youtube.com" in songURI:
		songURL = songURI
	try:
		yt = YouTube(songURL)
	except:
		print "ERROR: URL is not a video!"
	
	
	if bestQuality:
		video = yt.filter(filetype)[-1]
	else :
		video = yt.filter(filetype)[0]
	print "starting download to '" + dirUse + "'";
	
	try:
		video.download(dirUse);
		print "down succeeded"
	except:
		print "download failed:", sys.exc_info()
		

	if dirUse == nasDir:
		client = MPDClient()           # create client object
		client.connect("localhost", 6600)  # connect to localhost:6600
		#client.update("yt/"+yt.filename + "."+filetype)
		
		#Hack so that it will wait for the f*****g update.
		call(["mpc", "update",("yt/"+yt.filename+"."+filetype),"-w"])
		
		client.disconnect()
	
	time.sleep(0.1);
	
	return yt.filename + "."+filetype
Example #23
0
 def download_video(self, url):
     yt = YouTube(url)
     #~ video = yt.get('mp4')
     
     video = yt.filter('mp4')[-1]
     
     try:
         video.download(self.project_dir)
     except OSError:
         pass
     return self
def download(video_url_or_id, folder_path = "./"):
	if "youtube.com" in video_url_or_id:
		video_id = video_url_or_id.split("v=")[-1]
	elif "youtu.be" in video_url_or_id:
		video_id = video_url_or_id.split(".be/")[-1]
	else:
		video_id = video_url_or_id
	video_id = re.search("[\w-]+", video_id).group(0)

	yt = YouTube()
	yt.from_url("http://www.youtube.com/watch?v={}".format(video_id))
	yt.filter("mp4")[-1].download(path = folder_path, force_overwrite = True)
 def downloadVideo(self, videoList):
     ytVideo = videoList[0]
     yt = Ytdwn("http://www.youtube.com/watch?v=%s"%ytVideo._ident)
     filename = 'YT_%s' % ytVideo._ident
     yt.set_filename(filename)
     video = yt.filter(resolution='360p')[0]
     filepath = "%s/%s.%s" % (YOUTUBE_VIDEOS_LOCATION, filename, video.extension)
     if os.path.exists(filepath):
         os.remove(filepath)
     video.download(YOUTUBE_VIDEOS_LOCATION)
     ytVideo._file_path = filepath
     ytVideo.save()
Example #26
0
def fetch_video_qualtiy(url):
    """
    Fetch a list of available video qualities.

    :param url: Url to fetch available video options.
    :type url: :class:`str`
    :returns: Iterable of available video options.
    :rtype: Iterable of :class:`str`
    """
    youtube = YouTube(url)
    for element in youtube.get_videos():
        yield element
Example #27
0
 def download(self):
     """
     Downloads the YouTube video and sets the video's title.
     """
     yt = YouTube('https://www.youtube.com/watch?v={0}'.format(self.youtube_id))
     video = yt.filter('mp4')[-1]
     self.title = video.filename
     self.file_path = '{0}.mp4'.format(self.youtube_id)
     yt.set_filename(self.youtube_id)
     video.download(settings.YOUTUBE_DOWNLOAD_ROOT)
     self.downloaded = True
     self.save()
def dl_video(link):
    print("Downloading [" + link + "]")

    try:
        yt = YouTube(link)
        yt.filter('mp4')[-1].download('./')
        print("Done [" + link + "] (" + yt.filename + ")")
        return yt.filename
    except:
        print("Could not download: " + link)
        print(sys.exc_info()[0])
        return False
def download_links(linkList, pathWrite):
	''' Download the links '''
	name_num = 0

	for l in linkList:
		y = YouTube(l)
		y.set_filename(str(name_num))
		try:
			video = y.get('mp4', '720p')
			video.download(pathWrite)
			name_num += 1
		except:
			print("Video " + l + " does not meet criteria (mp4,720p)")
Example #30
0
Created on Sat Mar 27 10:23:31 2021

@author: Admin
"""
from pytube import YouTube

progress = 0


def showProgress(stream, chunk, bytes_remaining):
    size = stream.filesize

    global progress
    preProgress = progress
    currentProgress = (size - bytes_remaining) * 100 // size
    progress = currentProgress

    if progress == 100:
        print("下載完成")
        return

    if preProgress != progress:
        print("目前進度:" + str(progress) + "%")


yt = YouTube("https://www.youtube.com/watch?v=rAsdsomsKv4",
             on_progress_callback=showProgress)

stream = yt.streams.filter(res='360p').first()
#stream = yt.streams.all()
stream.download("video", "Frozen_360p_24fps")
Example #31
0
import json
import os
from pytube import YouTube

present_path = os.path.dirname(__file__)
with open("MUSIC_solo_videos.json") as f:
    data = json.load(f)
not_downloaded = []
classes = data['videos'].keys()
for class1 in classes:
    if not os.path.exists(os.path.join(present_path, class1)):
        os.makedirs(os.path.join(present_path, class1))
    videos = data['videos'][class1]
    for video in videos:

        print(video)
        try:
            YouTube("https://www.youtube.com/watch?v=" +
                    video).streams.first().download(
                        os.path.join(present_path, class1))

        except:
            not_downloaded.append({class1: video})
Example #32
0
from pytube import YouTube

url = 'https://youtu.be/u-GJBlpLoDE?list=RDu-GJBlpLoDE'

youtube = YouTube(url)

#To list only audio streams:
print(youtube.streams.filter(adaptive=True))

#To list only mp4 streams:
print(youtube.streams.filter(subtype='mp4'))
# pip install pytube3

from pytube import YouTube

link = input("Enter the link: ")
yt = YouTube(link)

#1 information
# print("Title: ", yt.title)
# print("Number of views: ", yt.views)
# print("Length of video: ", yt.length, "seconds")
# # print("Description: ", yt.description)
# print("Ratings: ", yt.rating)
# --------------------------------------------------------
# print(yt.streams)

#2 download video
# ys = yt.streams.get_highest_resolution()
# print("Downloading...")
# ys.download("")
# print("Download completed!")

#3 download only audio
# print(yt.streams.filter(only_audio=True))
# ys = yt.streams.get_by_itag("251")
# print("Downloading...")
# ys.download("audio")
# print("Download completed!")

#4 download korean captions
print(yt.captions)
Example #34
0
from pytube import YouTube

yt = YouTube('https://www.youtube.com/watch?v=7G6FfKXvZX8')
# yt.streams.get_highest_resolution().download()

yt.streams.filter(file_extension="mp4").all()

# 400 1440P video mp4
# yt.streams.get_by_itag(400).download(output_path="UE4_WOW_400")
# 140 audio/mp4 128kbps
# yt.streams.get_by_itag(140).download(output_path="TBC_Ret_Paladin_VoidReaver_2900DPS_140")

# 299 1080P60 video mp4
# 399 1080P video mp4
# yt.streams.get_by_itag(299).download(output_path="StromCity299")

yt.streams.get_by_itag(140).download(output_path="Fj-z1bakYMg140")
# yt.streams.get_by_itag(137).download(output_path="Fj-z1bakYMg")
# yt.streams.get_by_itag(299).download(output_path="Fj-z1bakYMg299")
# yt.streams.get_by_itag(399).download(output_path="Fj-z1bakYMg")
Example #35
0
def main():

    if WORKDIR:
        os.makedirs(WORKDIR, exist_ok=True)
        for f in glob.glob(str(Path('./') / '*.csv')):
            shutil.copy2(f, WORKDIR)
        os.chdir(WORKDIR)

    for highlight_sheet in Path('./').rglob('*.csv'):
        highlight = str(highlight_sheet)
        highlight = highlight[:highlight.index('.')]

        print(f'processing vids for {highlight}...')

        df = pd.read_csv(highlight_sheet)
        os.makedirs(highlight, exist_ok=True)

        # after grouping by link:
        # download each link, adding relevant timestamp rows as one entry in bout queue
        # iterate over bout queue, to clip timestamps out of respective video

        bout_queue = []

        for link, df_bout in df.groupby('link'):
            if pd.notna(link):
                # construct folder/file name
                try:
                    vid = YouTube(link)
                except:
                    print(f'pytube blew up on video: {link}')
                    continue
                name = prep_for_file_path(vid.title)
                folder_name = Path(highlight) / Path(name)

                bout_queue.append((df_bout, folder_name))

                if MAKE_VIDS:
                    # downloading the video if none exists in folder
                    if not [
                            v for v in folder_name.rglob('*.mp4')
                            if os.path.isfile(v)
                    ]:

                        os.makedirs(folder_name, exist_ok=True)
                        print(f'downloading {name}')

                        stream = (
                            vid.streams
                            # progressive: audio and video in one file
                            # mp4: to work with ffmpeg
                            .filter(progressive=True, file_extension='mp4')
                            # retrieve highest resolution
                            .order_by('resolution').desc().first())

                        stream.download(folder_name)
                    else:
                        print(f'video exists in {name}... skipping')

        if MAKE_CLIPS:

            for df_bout, folder_name in bout_queue:
                # required that there's a video in this directory!
                if not os.listdir(folder_name):
                    continue

                video_name = os.listdir(folder_name)[0]
                assert video_name

                offset_start = CLIP_WINDOW_START
                offset_end = CLIP_WINDOW_END
                if df_bout.replay.any():
                    print(
                        f'{video_name[:20]} has replay, increasing clip length'
                    )

                    offset_start = CLIP_WINDOW_START_REPLAY
                    offset_end = CLIP_WINDOW_END_REPLAY

                for i, series in df_bout.iterrows():
                    judgement = series['judgement']

                    if judgement in JUDGEMENT_TO_CLIP:
                        timestamp = series['timestamp']
                        min, sec = timestamp.split(':')
                        window = int(min) * 60 + int(sec)
                        window_start = window - offset_start
                        window_end = window + offset_end

                        desc = prep_for_file_path(series['description'])
                        blurb = f'{judgement}__{desc}'
                        if pd.notna(series['comment']):
                            comment = prep_for_file_path(
                                series['comment'][:10])
                            blurb += f'__{comment}'

                        vid_in_name = str(folder_name) + '/' + video_name
                        clip_out_name = f'{highlight}/{prep_for_file_path(video_name[:20])}__{blurb}.mp4'

                        ffmpeg_extract_subclip(vid_in_name, window_start,
                                               window_end, clip_out_name)
Example #36
0
from pytube import YouTube
import os

address = input("Enter the link:	")
SAVE_PATH = os.getcwd()  #to_do
yt = YouTube(address)

mp4files = yt.filter('mp4')

d_video = yt.get(mp4files[-1].extension, mp4files[-1].resolution)

d_video.download(SAVE_PATH)
from pytube import YouTube
s = input()
yt = YouTube(s)
#yt = yt.get('mp4', '720p')
t = yt.streams.filter(only_audio=True).all()
t[0].download()
Example #38
0
def downloadFile(url):
    name = YouTube(url).streams.first().download()
    newname = name.replace(' ','_')
    os.rename(name,newname)
    return newname
Example #39
0

def note(note):
    print('-' * 40 + f'\n{note}\n' + '-' * 40)


while True:
    clear()
    try:
        note(
            'inter the video or playlist url\nthen press inter to start downloading '
        )
        url = input()
        if 'playlist' not in url:
            try:
                video = YouTube(url)
                print('wait a second....')
                video.streams.filter(
                    type="video").get_highest_resolution().download()
                print('Done !')
                time.sleep(3)

            except Exception as e:
                print('an unvalued video url'), time.sleep(5), clear()
                continue
        elif 'playlist' in url:
            try:
                p = Playlist(url)
                os.mkdir(p.title)
                os.chdir(p.title)
                for video in p.videos:
_url = 'https://www.youtube.com/watch?v=QPXQlU7k6bQ'
_codec = 18
_fileName = 'Gladys.mp4'
_checkImages = 'MyFrames/frame__0.jpg'
"""
Info: https://pypi.org/project/pytube3/
"""
"""
DOWNLOAD VIDEO
"""

#Check if video file exists
if os.path.exists(_fileName) == False:
    #if not exists, then download
    video = YouTube(_url)

    video.streams.all()
    video.streams.filter(file_extension="mp4").all()
    out_File = video.streams.get_by_itag(_codec).download()

    #Change the name of the file
    os.rename(out_File, 'Gladys.mp4')
"""
EXTRACT FRAMES
"""
if os.path.exists(_checkImages) == False:
    #Check the name of the file and extract the frames
    fe = FrameExtractor(_fileName)

    #Set every how much frames we get an image
Example #41
0
def getData():
    addBtn.config(state=DISABLED)
    addBtn.config(bg="#273239")
    downloadBtn.config(state=DISABLED)
    global file_size
    i = 0
    task = len(downloadQueue)
    filePath = askdirectory()
    if filePath is None:
        downloadBtn.config(text="Directory inaccessible")
        return
    while not downloadQueue == []:
        url = downloadQueue.pop()
        res = resolutionQueue.pop()
        try:
            downloadBtn.config(text=f'Downloading {i+1} out of {task}')
            tube = YouTube(url, on_progress_callback=updateProgress)
            duration.config(text=getDuration(tube.length))
            views.config(text=getViews(float(tube.views)))
            quality.config(text=res)
            index = resolutions.index(res)
            if index < 7:
                vi = tube.streams.filter(res=res, progressive=True).first()
                if vi is None:
                    vi = tube.streams.filter(res=res,
                                             adaptive=True,
                                             subtype="mp4").first()
                    if vi is None:
                        alert.config(
                            text=
                            f'No match found for {res}! Downloading 720p instead'
                        )
                        yt = tube.streams.first()
                        file_size = yt.filesize
                        yt.download(filePath)
                    else:
                        alert.config(text=f'Downloading video in {res}')
                        file_size = vi.filesize
                        vi.download(filePath, filename='video')
                        alert.config(text="Downloading audio file now")
                        au = tube.streams.get_audio_only()
                        file_size = au.filesize
                        au.download(filePath, filename='audio')
                        outputVideo = os.path.join(filePath,
                                                   vi.default_filename)
                        inputVideo = os.path.join(filePath, 'video.mp4')
                        inputAudio = os.path.join(filePath, 'audio.mp4')
                        alert.config(text="Merging video and audio")
                        ffmpegCmd = subprocess.run(
                            f'ffmpeg -i "{inputVideo}" -i "{inputAudio}" -c copy -y "{outputVideo}"',
                            shell=True)
                        if ffmpegCmd.returncode:
                            raise MergeError
                        alert.config(text="Deleting temp files")
                        os.remove(inputVideo)
                        os.remove(inputAudio)
                else:
                    alert.config(text=f'Downloading video in {res}')
                    file_size = vi.filesize
                    vi.download(filePath)
            else:
                au = tube.streams.filter(only_audio=True, abr=res).first()
                if au is None:
                    alert.config(
                        text=
                        f'No match found for {res}! Downloading in 128kbps instead'
                    )
                    au = tube.streams.get_audio_only()
                    file_size = au.filesize
                    au.download(filePath)
                else:
                    alert.config(text=f'Downloading audio in {res}')
                    file_size = au.filesize
                    au.download(filePath)
            if getSrt(tube):
                open(tube.default_filename + '.srt',
                     'w').write(tube.captions['en'].generate_srt_captions())
            alert.config(text="Download complete")
        except MergeError:
            alert.config(text="Unknown error occured while merging")
        except PermissionError:
            alert.config(text="Directory inaccessible")
        except MemoryError:
            alert.config(text="Out of memroy")
        except:
            alert.config(text="Unknown error occured while downloading")
        finally:
            listbox.delete(END)
            i + 1
    downloadBtn.config(text="Download")
    downloadBtn.config(state=NORMAL)
    addBtn.config(state=NORMAL)
    duration.config(text="")
    views.config(text="")
    quality.config(text="")
    progress.config(text="")
    size.config(text="")
Example #42
0
#!/usr/local/bin/python

from pytube import YouTube

# Dependency for album cover download
#import requests

print('*****************Enter the YouTube URL*****************: ')
url = str(input())
yt = YouTube(url)

# Store some data about the downloaded song
video_title = yt.title
album_cover_art_url = yt.thumbnail_url

# Download the album cover and store it in current working directory
# Implement error handling - is it needed?
# print("*****************Downloading cover art*****************")
# album_cover_art_image = open('albumcover.jpg', 'wb')
# album_cover_art_image.write(requests.get(album_cover_art_url).content)
# album_cover_art_image.close()

print("*****************THUMBNAIL URL = " + album_cover_art_url)
print("*****************TITLE: " + video_title)

# Download the first stream and save it in the working directory with
# the original YouTube title
yt.streams.first().download(None, filename=video_title)
print("*****************Download has finished!*****************")

print("\n\n\n")
Example #43
0
        print("Playlist " + pl.title + " download started...")
        for video in pl.videos:
            print(video.title + " download in progress...")
            download_highest_resolution(video, pl.title)
            print(video.title + " download complete")
            vidNum += 1
        print("Playlist " + pl.title +
              " download completed, playlist located in folder " + pl.title)
    print("all playlists downloaded")

if type == "L":
    while True:
        try:
            numVids = int(
                input("Number of videos you would like to download: "))
            break
        except ValueError:
            print("Please enter integer")
    vids = []
    for x in range(numVids):
        link = input("Enter link of video " + str(x + 1) + ": ")
        vids.append(link)
    vidCount = 1
    for vid in vids:
        yt = YouTube(vid)
        print("Downloading " + yt.title + "...")
        download_highest_resolution(yt, yt.author)
        print(yt.title + " download complete, video located in folder " +
              yt.author)
        vidCount += 1
Example #44
0
def videotitle():
    Videolink = entry.get()
    yt = YouTube(Videolink)
    global videon
    videon = yt.title
Example #45
0
from pytube import YouTube
link = input("enter link:")
video = YouTube(link)
stream = video.streams.get_highest_resolution()
stream.download()
Example #46
0
def audio_download(audio):
    yt_obj = YouTube(str(audio))
    yt_obj.streams.get_audio_only().download(filename_prefix='mp3',
                                             output_path='songs\songs')
    print("downloaded")
Example #47
0
    def download(self, query, user_message=lambda text: True):
        match = self.yt_regex.search(query)
        if match:
            url = match.group(0)
        else:
            raise UnappropriateArgument()

        self.logger.info("Getting url: " + url)
        user_message("Загружаем информацию о видео...")

        media_dir = self.config.get("downloader", "media_dir", fallback="media")

        try:
            video = YouTube(url, on_progress_callback=self.video_download_progress)
            stream = video.streams.filter(only_audio=True).first()
        except Exception:
            traceback.print_exc()
            raise ApiError()
        video_id = video.video_id
        video_details = video.player_config_args.get('player_response', {}).get('videoDetails', {})
        if video_id is None:
            raise UrlProblem()
        try:
            video_title = html.unescape(video.title)
            self.logger.debug("Video title [using primary method]: " + video_title)
        except KeyError:
            video_title = html.unescape(video_details.get('title', 'Unknown YT video'))
            self.logger.debug("Video title [using fallback method]: " + video_title)

        video_title = remove_links(video_title)

        try:
            file_size = int(stream.filesize)
        except HTTPError as e:
            traceback.print_exc()
            raise BadReturnStatus(e.code)
        if file_size > 1000000 * self.config.getint("downloader", "max_file_size", fallback=self._default_max_size):
            raise MediaIsTooBig()

        file_dir = media_dir
        file_name = sanitize_file_name("youtube-" + str(video_id))

        seconds = video.length

        if seconds > self.config.getint("downloader", "max_duration", fallback=self._default_max_duration):
            raise MediaIsTooLong()

        self.download_status[str(video_id)] = {
            "start_time": time.time(),
            "last_update": time.time(),
            "file_size": file_size,
            "stream": stream,
            "title": video_title,
            "user_message": user_message,
        }

        file_path = os.path.join(file_dir, file_name) + ".mp4"
        if self.is_in_cache(file_path):
            self.logger.debug("Loading from cache: " + file_path)
            return file_path, video_title, "", seconds

        if not os.path.exists(file_dir):
            os.makedirs(file_dir)
            self.logger.debug("Media dir have been created: " + file_dir)

        self.logger.info("Downloading audio from video: " + video_id)
        user_message("Скачиваем...\n%s" % video_title)

        try:
            stream.download(output_path=file_dir, filename=file_name)
        except HTTPError as e:
            traceback.print_exc()
            raise BadReturnStatus(e.code)
        self.touch_without_creation(file_path)

        self.logger.debug("File stored in path: " + file_path)

        return file_path, video_title, "", seconds
from pytube import YouTube
yt_url = "https://www.youtube.com/watch?v=sAuEeM_6zpk"
yt_obj = YouTube(yt_url)

# fetch resolution
print("Fetch Resolution")
for stream in yt_obj.streams:
    print(stream)
print()

# filter data
print("Filter data")
filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')
for mp4_filter in filters:
    print(mp4_filter)

# Download video
filters.get_highest_resolution().download()
Example #49
0
several clips and let you annotate it'''

# Set up some folders
demo_folder = r'./'
clips_folder = r'./youtube_clips'
youtube_filename = 'youtube.mp4'

# Create the folders
if not os.path.exists(demo_folder):
    os.mkdir(demo_folder)
if not os.path.exists(clips_folder):
    os.mkdir(clips_folder)

# Download from youtube: "Women's Beam Final - London 2012 Olympics"
if not os.path.exists(os.path.join(demo_folder, 'youtube.mp4')):
    yt = YouTube('https://www.youtube.com/watch?v=VZvoufQy8qc')
    stream = yt.streams.filter(res='144p', mime_type='video/mp4').first()
    print('Downloading youtube file. This may take a while.\n' +
          'Let\'s be honest, this _will_ take a while...')
    stream.download(demo_folder, filename='youtube')

# Initialise the annotator
annotator = Annotator([{
    'name': 'result_table',
    'color': (0, 255, 0)
}, {
    'name': 'olympics_logo',
    'color': (0, 0, 255)
}, {
    'name': 'stretching',
    'color': (0, 255, 255)
Example #50
0
from pytube import YouTube

#yt = YouTube('https://youtube.com/watch?v=XJGiS83eQLk')
yt = YouTube('https://www.youtube.com/watch?v=XUkMY8Sp_AM')
for cap in yt.captions.all():
    print(cap)
caption = yt.captions.get_by_language_code('a.en')
print(caption.generate_srt_captions())
Example #51
0
# pip3 freeze | grep pytube
# pytube==7.0.18
# get the following document for usage guide
# https://python-pytube.readthedocs.io/en/stable/user/quickstart.html

from pytube import YouTube
yt = YouTube('https://www.youtube.com/watch?v=RwR1uif_uDg')
print(yt.title)
print(yt.streams.all())
stream = yt.streams.first()
stream.download('./tmp')

Example #52
0
def Confirm():
    Videolink = entry.get()
    yt = YouTube(Videolink)
    VideoName["text"] = "Title: " + yt.title
    print(yt.streams)
Example #53
0
    async def mp4process(self, ctx, link=None, resolution='720p'):
        def combine_audio(vidname, audname, outname, vid_fps):
            vid_clip = mpe.VideoFileClip(vidname)
            aud_clip = mpe.AudioFileClip(audname)
            final_clip = vid_clip.set_audio(aud_clip)
            final_clip.write_videofile(outname, fps=vid_fps)

        def mp4tomp3(file):
            base, ext = os.path.splitext(file)
            file_mp3 = base + '.mp3'
            os.rename(file, file_mp3)

        if link is None:
            await ctx.send('You must include a link!')
        else:
            try:
                yt = YouTube(link)
            except Exception or exceptions.VideoUnavailable:
                await ctx.send('Video is unavailable or not valid.')
            else:
                if yt.streams.filter(res=resolution,
                                     only_video=True).first() is None:
                    resolution = yt.streams.filter(only_video=True).order_by(
                        'resolution').last().resolution
                    await ctx.send(
                        'That video doesn\'t have that resolution, so it\'s converting the highest one'
                    )
                try:
                    await asyncio.sleep(15)

                    await ctx.send(
                        f'Converting Video: `{yt.title}` by `{yt.author}` at `{resolution}`'
                    )
                    invalids = [
                        '"', '*', '<', '>', ',', '?', '\\', '|', '/', ':',
                        'CON', 'PRN', 'AUX', 'NUL', 'COM1', 'COM2', 'COM3',
                        'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9', 'LPT1',
                        'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8',
                        'LPT9'
                    ]
                    vid_title = yt.title
                    fps = yt.streams.filter(res=resolution,
                                            only_video=True).first().fps
                    for char in vid_title:
                        if char in invalids:
                            vid_title = vid_title.replace(char, '')

                    await asyncio.sleep(0.1)

                    yt.streams.filter(res=resolution,
                                      only_video=True).first().download(
                                          temp_path, 'vid')
                    mp4tomp3(
                        yt.streams.filter(only_audio=True).first().download(
                            f'{temp_path}\\', 'aud'))

                    combine_audio(f'{temp_path}\\vid.mp4',
                                  f'{temp_path}\\aud.mp3',
                                  f'{temp_path}\\{vid_title}.mp4', fps)

                except exceptions.PytubeError or AttributeError:

                    await asyncio.sleep(0.1)

                    await ctx.send('That video doesn\'t have that resolution!')
                else:
                    if os.stat(
                            f'{temp_path}\\{vid_title}.mp4').st_size > 8000000:
                        print(os.stat(f'{temp_path}\\{vid_title}.mp4').st_size)
                        await ctx.send(
                            'Video file is too large (More than 8MB)! Please download at a lower resolution!'
                        )

                    else:
                        await ctx.send(
                            f'{ctx.author.mention} Done!',
                            file=discord.File(f'{temp_path}\\{vid_title}.mp4'))
                    os.remove(f'./temp/{vid_title}.mp4')
                    os.remove(f'./temp/vid.mp4')
                    os.remove(f'./temp/aud.mp3')
Example #54
0
 def connect(self):
     try:
         return YouTube(self.link)
     except Exception as e:
         return None
Example #55
0
def download_video(Video_name):
    yt_obj = YouTube(str(Video_name))
    filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')
    filters.get_highest_resolution().download()
    print("downloaded")
Example #56
0
def mp4():
    url = input("masukan link > ")
    v = YouTube(url)
    yt = v.streams.first()
    yt.download()
Example #57
0
import os.path
import sys
from pytube import YouTube

#url_path = sys.argv[1]
url_path = "?v=c5ZsSm45JV8"
home = os.path.expanduser("~")
folder_path = os.path.join(home, "Music/")

if len(sys.argv) > 1:
    folder_path = os.path.join(folder_path, sys.argv[2])
    if not os.path.isdir(folder_path):
        os.mkdir(folder_path)
# creating YouTube object
yt = YouTube(url_path)
print("Downloading")
# accessing audio streams of YouTube obj.(first one, more available)
stream = yt.streams.filter(only_audio=True).first()
# downloading a video would be: stream = yt.streams.first()

# download into working directory
stream.download(folder_path)
        progress_percent_to_print = 'Progress - >' + progress_percent_str[:6] + '%'

    print(progress_percent_to_print, end='\r')


def download_video(__yt__):
    if not os.path.exists(path):
        os.makedirs(path)

    if not os.path.exists(os.path.join(path_url + __yt__.title + '.mp3')):
        __yt__.streams.filter(only_audio=True).filter(
            subtype='mp4').order_by('abr').desc().first().download(path)
        return True
    else:
        return False


if links_list is not None:
    for l in links_list.split(','):
        yt = YouTube(l)
        yt.register_on_progress_callback(on_progress)

        print('Starting download of', yt.title)
        if download_video(yt):
            post_download(yt)
        else:
            print('Song already downloaded')

    total_path = 'C:' + path_url
    print('Check your downloaded songs on: ', total_path)
Example #59
0
from pytube import Playlist, YouTube
YouTube(link).streams.first().download('/storage/haibn/yt8m/test_video/)
Example #60
-1
def download_videos(test=True):
    manually_download = []
    positions = Week.objects.all()[0].position_set.all().order_by('position')
    songs = [p.song for p in positions][50:]
    for song in songs:
        if song.youtube_link:
            link = 'http://www.youtube.com/watch?v=' + song.youtube_link
            try:
                yt = YouTube(link)
                yt.set_filename("{} - {}".format(song.name, song.artist.name))
            except AgeRestricted:
                manually_download.append(link)
                print 'Song is age restricted, adding to manually_download list.'
                continue
            try:
                video_type = yt.filter('mp4')[-1]
                video = yt.get(video_type.extension, video_type.resolution)
            except Exception:
                traceback.print_exc()
                continue

            if not os.path.exists(os.path.abspath(os.path.join(settings.RAW_VIDEOS, video.filename + ".mp4"))):
                print 'Downloading video: {} - {}'.format(song, video_type.resolution)
                video.download(settings.RAW_VIDEOS)
            else:
                print 'Video: {} already downlaoded. Skipping.'.format(song)

    print 'Manually download these songs: %s' % manually_download