Exemple #1
0
def download_by_id(vid_id):
    """
    Download a YouTube video given the video's ID, and return the path to the
    video. If the video has already been downloaded, then return the path to
    that file without redownloading.
    """
    if not os.path.isdir(MP4_DIR):
        os.mkdir(MP4_DIR)
    if not os.path.isdir(MP3_DIR):
        os.mkdir(MP3_DIR)

    url = "https://www.youtube.com/watch?v=%s" % vid_id
    yt = YouTube(url)
    yt.filename = vid_id

    # Check if the mp3 already exists
    mp3_output = os.path.join(MP3_DIR, yt.filename + ".mp3")
    if os.path.exists(mp3_output):
        return mp3_output

    # Download full video
    mp4_output = os.path.join(MP4_DIR, yt.filename + ".mp4")
    if not os.path.exists(mp4_output):
        vid = yt.filter('mp4')[-1]
        vid.download(MP4_DIR)

    # Extract audio from video
    mp3_output = os.path.join(MP3_DIR, vid_id + ".mp3")
    if not os.path.exists(mp3_output):
        command = "ffmpeg -i \"%s\" -ab 160k -ac 2 -ar 44100 -vn \"%s\"" % (
            mp4_output, mp3_output)
        subprocess.call(command, shell=True)

    return mp3_output
def saveVideo(URL, directory, filename):
    yt = YouTube()
    yt.url = URL
    yt.filename = filename
    video = getVideo(URL, yt)
    if type(video) != None:
        video.download(directory)
    else:
        print "Pick another video! This one didn't work :("
Exemple #3
0
def create_audio_file(audio_fname, our_id, video_url):
    yt = YouTube(video_url)
    yt.filename = our_id
    v = yt.get('mp4', '360p')

    download_dir = '/tmp'
    v.download(download_dir)
    video_fname = os.path.join(download_dir, our_id + '.mp4')
    subprocess.check_call(['ffmpeg', '-i', video_fname, '-vn', '-c:a', 'copy', audio_fname])

    os.unlink(video_fname)
Exemple #4
0
def download(args):
    """
	Downloads youtube video

	args		:	parsed command line arguments

	"""

    # Call the YoutTube Function
    youtube = YouTube()

    # Set the video url
    try:
        youtube.url = args['u']

    # Catch invalid YouTube URLs
    except YouTubeError:
        print "\n\nError:  Failed on ('{}').\nCheck for valid YouTube URL.\n\n".format(
            args['u'])
        exit(2)

    # Create menu of video format/resolution options
    video_option_selection = menu(map(str, youtube.videos))

    # Extract video types into a list of a single string
    video_format = re.findall(r'\(.(\w{3,4})\)', video_option_selection)[0]
    video_resolution = re.findall(r'-\s*(\w{3,4})', video_option_selection)[0]

    # Set filename if -f/--filename option is given
    if args['f']:
        youtube.filename = args['f']

    # Set the video format
    try:
        set_video_format_res = youtube.get(video_format, video_resolution)

    # Catch multiple videos returned error
    except MultipleObjectsReturned:
        print '\n\nError: More than one video returned.\n\n'
        exit(1)

    # Download video
    download_video = set_video_format_res.download(
        args['dir'],
        on_progress=print_status,
        on_finish=video_to_mp3 if args['c'] else None)

    # Delete original video file if -do/--delete and -c/--convert is given
    if args['c'] and args['do']:

        # Call remove_original
        remove_original(youtube.filename, args['dir'], video_format)
Exemple #5
0
def downloadFisicalFile(youtubeId, idName):
	yt = YouTube()
	yt.url = ("http://www.youtube.com/watch?v=" + youtubeId)
	yt.filename = idName
	video = 0
	if len(yt.filter('mp4')) > 0:
		if len(yt.filter(resolution='720p')) > 0:
			video = yt.get('mp4','720p')
		else:
			video = yt.get('mp4')

		video.download("tempvideo/")
	else:
		cocomo.printJson("no se puede descargar el archivo", "error")
Exemple #6
0
def download(args):
	"""
	Downloads youtube video

	args		:	parsed command line arguments

	"""

	# Call the YoutTube Function
	youtube			=	YouTube()

	# Set the video url
	try:
		youtube.url		=	args['u']

	# Catch invalid YouTube URLs
	except YouTubeError:
		print "\n\nError:  Failed on ('{}').\nCheck for valid YouTube URL.\n\n".format(args['u'])
		exit(2)

	# Create menu of video format/resolution options
	video_option_selection	=	menu(map(str, youtube.videos))

	# Extract video types into a list of a single string
	video_format 		=	re.findall(r'\(.(\w{3,4})\)', video_option_selection)[0]
	video_resolution	=	re.findall(r'-\s*(\w{3,4})', video_option_selection)[0]

	# Set filename if -f/--filename option is given
	if args['f']:
		youtube.filename		=		args['f']

	# Set the video format	
	try:
		set_video_format_res	=	youtube.get(video_format, video_resolution)

	# Catch multiple videos returned error
	except MultipleObjectsReturned:
		print '\n\nError: More than one video returned.\n\n'
		exit(1)

	# Download video
	download_video		=	set_video_format_res.download(args['dir'],
						on_progress=print_status, 
						on_finish=video_to_mp3 if args['c'] else None)

	# Delete original video file if -do/--delete and -c/--convert is given
	if args['c'] and args['do']:
	
	# Call remove_original 
		remove_original(youtube.filename, args['dir'], video_format)
Exemple #7
0
def convert():

    if (request.form):
        url = request.form['url']

        yt = YouTube()
        yt.url = url
        name = yt.filename.encode("UTF-8")
        yt.filename = base64.b64encode(name)


        mp4 = yt.filename
        mp3name = base64.b64decode(yt.filename)

        #check against db
        db = get_db()
        cur = db.execute('select id,timesdownloaded from songs where base64name=? order by id desc', (mp4+".mp3",))
        one = cur.fetchone()

        if(one):
            db.execute('update songs set timesdownloaded=?, lastdownload=? WHERE base64name=?',[one[1]+1, datetime.datetime.now(), mp4+'.mp3' ])
            db.commit()
            return jsonify({'location': 1, "name":mp3name+".mp3"})

        video = yt.get('mp4', '360p')
        video.download('/tmp/')


        call(["ffmpeg -i /tmp/"+mp4+".mp4 -b:a 128K -vn /tmp/"+mp4+".mp3"],shell=True)


        db = get_db()
        db.execute('insert into songs (songname, base64name, dateconverted, timesdownloaded, lastdownload) values (?, ?, ?, ?, ?)',
                 [mp3name+".mp3", mp4+".mp3", datetime.datetime.now(), 1, datetime.datetime.now()])

        db.commit()

        shutil.copy2("/tmp/"+mp4+".mp3", "static/songs/"+mp3name+".mp3")
        os.remove("/tmp/"+mp4+".mp3")
        os.remove("/tmp/"+mp4+".mp4")

        return jsonify({'location': 1, "name":mp3name+".mp3"})

    return jsonify({'message': "There was an error. Something is missing in input."})
def download_yt_video(yt_url, filename, path, sim=False):
    global needs
    global gots
    yt = YouTube()
    yt.url = yt_url
    yt.filename = u'{}'.format(filename.replace('/', '-').replace(':', ','))
    if os.path.isfile(os.path.join(path, u'{}.mp4'.format(yt.filename))):
        print('              Got it!')
        gots += 1
    else:
        if sim:
            print('              Need It!')
            needs += 1
        else:
            print('              Downloading... ', end='')
            max_res = yt.filter('mp4')[-1].resolution
            video = yt.get('mp4', max_res)
            video.download(path, verbose=False)
            print('Done!')
            gots += 1
Exemple #9
0
def download_video_yt(link, output_path):
    """
    :param link: a Youtube link
    :param output_path: path where the downloaded video is saved
    :return:
    """
    try:
        video_folder = output_path  # folder where videos are put
        yt = YouTube(link)  # get the video
        video = yt.get('mp4', '360p')  # select the video in mp4 format
        yt.filename=re.sub(' ', '-', yt.filename)
        new_path=os.path.join(output_path, remove_accents(yt.filename))

        if not os.path.exists(new_path):  # We use this condition to see if the video has already been treated
            os.makedirs(new_path)
            yt.set_filename('Video')
            video.download(new_path)  # downloads the video

        return new_path  # return the path of the folder where the video has been downloaded
    except:
        print('The link is not valid !')
        return False
Exemple #10
0
def download_yt_video(url):
    if not os.path.isdir(MP4_DIR):
        os.mkdir(MP4_DIR)
    if not os.path.isdir(MP3_DIR):
        os.mkdir(MP3_DIR)

    yt = YouTube(url)
    yt.filename = ''.join([i if ord(i) < 128 else '' for i in yt.filename])

    mp4_output = os.path.join(MP4_DIR, yt.filename + ".mp4")
    if os.path.exists(mp4_output):
        os.remove(mp4_output)

    vid = yt.filter('mp4')[-1]
    vid.download(MP4_DIR)

    mp3_output = os.path.join(MP3_DIR, yt.filename + ".mp3")
    if os.path.exists(mp3_output):
        os.remove(mp3_output)
    command = "ffmpeg -i \"%s\" -ab 160k -ac 2 -ar 44100 -vn \"%s\"" % (
        mp4_output, mp3_output)
    print(command)
    subprocess.call(command, shell=True)
    return mp3_output
Exemple #11
0
        v = x.video_codec
        e = x.extension
        r = x.resolution
        vDict.update({count: [v, e, r]})
        print("{}. Format: {:<20} || Extension: .{:<20} || Resolution: {:^10}".
              format(count, v, e, r))

    try:
        videoKey = input("Select the number of the video:> ")
        assert re.match(r"^[^a-zA-Z]", videoKey), "Ambiguous Entry."
        videoKey = int(videoKey)
        assert videoKey in vDict.keys(), "Invalid Number"
    except (AssertionError, ValueError):
        print("Expected a number from the provided list.")
        sys.exit()
    targetVid.filename = input("Save file as:> ")
    targetVid.filename = targetVid.filename + "." + vDict[videoKey][1]
    video = targetVid.get(vDict[videoKey][1], vDict[videoKey][2])
    downloadOK = input("Download(yes-ok/no):> ")
    if not re.match(r"(yes|ok)", downloadOK):
        sys.exit()
    else:
        try:
            downloadURL(targetVid.filename, video.url)
            sys.stdout.write(chr(27) + "[?25h")
        except KeyboardInterrupt:
            print("\nDeleteing file....")
            os.remove(targetVid.filename)
            sys.stdout.write(chr(27) + "[?25h")
            sys.exit()
Exemple #12
0
from __future__ import print_function
from pytube import YouTube
from pprint import pprint



yt = YouTube()

yt.url = "http://www.youtube.com/watch?v=Ik-RsDGPI5Y"
pprint(yt.videos)
# view the auto generated filename:

print(yt.filename)
yt.filename = 'Dancing'
video = yt.get('mp4', '720p')
video.download('/home/user/') #video.download('/tmp/')
Exemple #13
0
def process_wamap_video_links():
    # Make sure we are in the correct current directory
    # Starts in the Models folder
    w2py_folder = os.path.abspath(__file__)
    # print("Running File: " + app_folder)
    w2py_folder = os.path.dirname(w2py_folder)
    # app folder
    w2py_folder = os.path.dirname(w2py_folder)
    app_folder = w2py_folder
    # Applications folder
    w2py_folder = os.path.dirname(w2py_folder)
    # Root folder
    w2py_folder = os.path.dirname(w2py_folder)
    print("W2Py Folder: " + w2py_folder)

    # Ensure the wamap folder exists
    wamap_folder = os.path.join(app_folder, "static")
    wamap_folder = os.path.join(wamap_folder, "media")
    wamap_folder = os.path.join(wamap_folder, "wamap")

    if os.path.isdir(wamap_folder) is not True:
        os.mkdir(wamap_folder)

    process_count = 50
    last_row = 0

    while process_count > 0:
        process_count -= 1

        had_errors = False
        item = db(db.wamap_videos.downloaded == False).select().first()
        db.commit()
        ret = ""
        if item is None:
            ret += "Out of wamap items to process"
            print("Done processing videos.")
            return dict(ret=ret)

        print("-----------------------\n")
        print("Processing " + str(item.source_url) + "\n")
        last_row = item.id

        yt_url = item.source_url
        if ('youtube.com' in yt_url or 'youtu.be'
                in yt_url) and "admin.correctionsed.com" not in yt_url:
            # check if the file already exists
            vidfile = os.path.join(wamap_folder,
                                   "wamap_" + str(item.media_guid))
            # print("Checking vid file: " + vidfile + ".mp4")
            if os.path.exists(vidfile + ".mp4") is not True:
                # print("Downloading video: " + str(yt_url))
                # download the video
                try:
                    os.chdir(wamap_folder)
                    # Store the original link in a link file
                    meta = {'media_guid': item.media_guid, 'yt_url': yt_url}
                    meta_json = dumps(meta)
                    #f = os_open("wamap_" + str(item.media_guid) + ".link", os.O_TRUNC|os.O_WRONLY|os.O_CREAT)
                    #os.write(f, meta_json)
                    #os.close(f)
                    f = open("wamap_" + str(item.media_guid) + ".link", "w")
                    f.write(meta_json)
                    f.close()

                    # Download the video from the internet
                    yt = YouTube(proxies=get_youtube_proxies())
                    yt_url = yt_url.replace("!!1", "").replace(
                        "!!0", "")  # because some urls end up with the
                    # field separator still in it
                    if "/embed/" in yt_url:
                        # Embedded link doesn't return correctly, change it back
                        # to normal link
                        yt_url = yt_url.replace("/embed/", "/watch?v=")
                    yt.url = yt_url
                    yt.filename = "wamap_" + str(item.media_guid)
                    f = yt.filter('mp4')[-1]
                    f.download()
                except Exception as e:
                    print(" ****** Error fetching movie ****** " + str(e))
                    had_errors = True
                os.chdir(w2py_folder)
            else:
                pass
                # print("Video already downloaded " + str(vidfile))

            # update wamap db??
            if had_errors is not True:
                if os.path.exists(vidfile + ".mp4") is True:
                    new_url = "https://admin.correctionsed.com/media/wmplay/" + str(
                        item.media_guid)
                    # print(" Updating (" + str(yt_url) + ") to point to (" + new_url + ")")
                    db(db.wamap_videos.id == item.id).update(new_url=new_url)
                    db.commit()

                    db_wamap = DAL(
                        'mysql://*****:*****@wamap.correctionsed.com/imathsdb'
                    )

                    # Update all locations...
                    # DEBUG TODO -
                    # imas_inlinetext (text column)
                    sql = "UPDATE imas_inlinetext SET `text`=REPLACE(`text`, '" + yt_url + "', '" + new_url + "') WHERE `text` like '%" + yt_url + "%'"
                    # print(sql)
                    db_wamap.executesql(sql)

                    # imas_assessments (intro colum  youtube embed link?)
                    sql = "UPDATE imas_assessments SET `intro`=REPLACE(`intro`, '" + yt_url + "', '" + new_url + "') WHERE `intro` like '%" + yt_url + "%'"
                    # print(sql)
                    db_wamap.executesql(sql)

                    # imas_linkedtext (summary column)
                    sql = "UPDATE imas_linkedtext SET `summary`=REPLACE(`summary`, '" + yt_url + "', '" + new_url + "') WHERE `summary` like '%" + yt_url + "%'"
                    # print(sql)
                    db_wamap.executesql(sql)

                    # imas_linkedtext (text column)
                    sql = "UPDATE imas_linkedtext SET `text`=REPLACE(`text`, '" + yt_url + "', '" + new_url + "') WHERE `text` like '%" + yt_url + "%'"
                    # print(sql)
                    db_wamap.executesql(sql)

                    # imas_questionset (control)
                    sql = "UPDATE imas_questionset SET `control`=REPLACE(`control`, '" + yt_url + "', '" + new_url + "') WHERE `control` like '%" + yt_url + "%'"
                    #print(sql)
                    db_wamap.executesql(sql)

                    # imas_questionset (qtext)
                    sql = "UPDATE imas_questionset SET `qtext`=REPLACE(`qtext`, '" + yt_url + "', '" + new_url + "') WHERE `qtext` like '%" + yt_url + "%'"
                    #print(sql)
                    db_wamap.executesql(sql)

                    # imas_questionset (extref)
                    sql = "UPDATE imas_questionset SET `extref`=REPLACE(`extref`, '" + yt_url + "', '" + new_url + "') WHERE `extref` like '%" + yt_url + "%'"
                    # print(sql)
                    db_wamap.executesql(sql)

                    db_wamap.commit()
                    db_wamap.close()
        else:
            print("No youtube link found (" + str(item.source_url) + ")")

        db(db.wamap_videos.id == item.id).update(downloaded=True)
        db.commit()

    return dict(ret=ret, last_row=last_row)
  for count, x in enumerate(targetVid.videos, 1):
    v = x.video_codec
    e = x.extension
    r = x.resolution
    vDict.update({count:[v, e, r]})
    print("{}. Format: {:<20} || Extension: .{:<20} || Resolution: {:^10}".format(count, v, e, r))

  try:
    videoKey = input("Select the number of the video:> ")
    assert re.match(r"^[^a-zA-Z]", videoKey), "Ambiguous Entry."
    videoKey = int(videoKey)
    assert videoKey in vDict.keys(), "Invalid Number"
  except (AssertionError, ValueError):
    print("Expected a number from the provided list.")
    sys.exit()
  targetVid.filename = input("Save file as:> ")
  targetVid.filename = targetVid.filename + "." + vDict[videoKey][1]
  video = targetVid.get(vDict[videoKey][1], vDict[videoKey][2])
  downloadOK = input("Download(yes-ok/no):> ")
  if not re.match(r"(yes|ok)", downloadOK):
    sys.exit()
  else:
    try:
      downloadURL(targetVid.filename, video.url)
      sys.stdout.write(chr(27) + "[?25h")
    except KeyboardInterrupt:
      print("\nDeleteing file....")
      os.remove(targetVid.filename)
      sys.stdout.write(chr(27) + "[?25h")
      sys.exit()
Exemple #15
0
#!/usr/bin/python
import os, sys
from pprint import pprint

sys.path.insert(0, '.')

from pytube import YouTube

sys.stderr.write( 'ok' )

yt = YouTube()

# Set the video URL.
yt.url = "http://www.youtube.com/watch?v=Ik-RsDGPI5Y"
yt.url = sys.argv[1]

pprint(yt.videos)

print yt.filename

yt.filename = 'Dancing Scene from Pulp Fiction'

pprint(yt.filter('flv'))
pprint(yt.filter('mp4'))

print yt.filter('mp4')[-1]

video = yt.get('mp4', '720p')

video.download('/tmp/', fhd=sys.stdout)
Exemple #16
0
# <Video: H.264 (.flv) - 480p>,
# <Video: H.264 (.mp4) - 360p>,
# <Video: H.264 (.mp4) - 720p>,
# <Video: VP8 (.webm) - 360p>,
# <Video: VP8 (.webm) - 480p>]

# The filename is automatically generated based on the video title.
# You can override this by manually setting the filename.

# view the auto generated filename:
print yt.filename

#Pulp Fiction - Dancing Scene [HD]

# set the filename:
yt.filename = 'minobrnauki_1.mp4'

# You can also filter the criteria by filetype.

pprint(yt.filter('flv'))

#[<Video: Sorenson H.263 (.flv) - 240p>,
# <Video: H.264 (.flv) - 360p>,
# <Video: H.264 (.flv) - 480p>]

# notice that the list is ordered by lowest resolution to highest. If you 
# wanted the highest resolution available for a specific file type, you
# can simply do: 
print yt.filter('mp4')[-1]
#<Video: H.264 (.mp4) - 720p>
Exemple #17
0
def index():
    
    yt = YouTube()
    
    # Set the video URL.
    ret = ""
    tmpurl = "http://youtu.be/BthR2vlqrLo!!1"
    tmpurl = tmpurl.replace("/embed/", "/watch?v=")
    yt.url = tmpurl
    
    ret += str(yt.videos)
    yt.filename = "tempvid"
    # Get the highest res mp4
    ret += str(type(yt.filter('mp4')))
    f = yt.filter('mp4')[-1]
    
    try:
        f.download()
    except Exception as e:
        ret += str(e)
    
    #test = {}
    #ret = isinstance(test, dict)
    
    #AD.Connect()
    

    #cn="cn=ropulsipher,OU=CSE,OU=Faculty,DC=cbcc,DC=pencollege,DC=net"
    #cn_name = AD.GetNameFromLDAPPath(cn)
    
    #ret = ""
    
    #p1 = AD.GetParentLDAPPath(cn, 1)
    #p2 = AD.GetParentLDAPPath(cn, 2)
    
    #r = AD._ldap.search_s(p2, ldap.SCOPE_SUBTREE, "(name=" + str(p2) + ")" , ['distinguishedName'])
    #AD._errors.append("Found Object : " + str(r))
    
    #cn = "OU=CSE," + cn
    #ret = AD.MakePathCN(cn)
    
    #ret = AD.CreateUser('walshb', cn)
    
    #errors = AD._errors
    
    #AD.Close()
    
    #path = sys.path
    #a = Util.ParseName("bob smith")
    #b = Student.GetQuota("777777")

    #c = Student.QueueActiveDirectoryImports("SIMPLE SHEET")
    #d = Student.ProcessADStudent()

    #e = AD.GetCN("OU=Students,DC=cbcc,DC=pencollege,DC=net")
    #f = AD.GetCN("CN=s777777,OU=Students,DC=cbcc,DC=pencollege,DC=net")
    #createou = AD.CreateOU("OU=StudentsTest,DC=cbcc,DC=pencollege,DC=net")
    #creategroup = AD.CreateGroup("CN=TestGroup,OU=StudentsTest,DC=cbcc,DC=pencollege,DC=net")
    #createdn = AD.GetDN("1st", "2nd")
    #createuser = AD.CreateUser("s777777", "OU=StudentsTest,DC=cbcc,DC=pencollege,DC=net")
    #addtogroup = AD.AddUserToGroup("CN=s777777,OU=StudentsTest,DC=cbcc,DC=pencollege,DC=net", "CN=TestGroup,OU=StudentsTest,DC=cbcc,DC=pencollege,DC=net")
    #setpassword = AD.SetPassword("CN=s777777,OU=StudentsTest,DC=cbcc,DC=pencollege,DC=net", "SID7777772")    
    #enableuser = AD.EnableUser("CN=s777777,OU=StudentsTest,DC=cbcc,DC=pencollege,DC=net")
    #updateuser = AD.UpdateUserInfo("CN=s777777,OU=StudentsTest,DC=cbcc,DC=pencollege,DC=net", "*****@*****.**", "bob", "smith", "smith, bob", description="Student account", id_number="s777777", home_drive_letter="", home_directory="", login_script="", profile_path="",  ts_allow_login='******')
    #disableuser = AD.DisableUser("CN=s777777,OU=StudentsTest,DC=cbcc,DC=pencollege,DC=net")
    
    #setpass = AD.SetPassword("CN=s777780,OU=Students,DC=cbcc,DC=pencollege,DC=net", "123f")
    
    #groupdn = AD.GetLDAPObject("CN=Students,OU=StudentGroups,DC=cbcc,DC=pencollege,DC=net")
    #cn = AD.GetLDAPObject("OU=StudentGroups,DC=cbcc,DC=pencollege,DC=net")
    #setpass = Faculty.SetPassword("walshb", "12345612ABC")
    #ad_errors = AD._errors

    return dict(vars=locals())
Exemple #18
0
from __future__ import print_function
from pytube import YouTube
from pprint import pprint

yt = YouTube()

yt.url = "http://www.youtube.com/watch?v=Ik-RsDGPI5Y"
pprint(yt.videos)
# view the auto generated filename:

print(yt.filename)
yt.filename = 'Dancing'
video = yt.get('mp4', '720p')
video.download('/home/user/')  #video.download('/tmp/')
Exemple #19
0
from __future__ import print_function
from pytube import YouTube

yt = YouTube()
# Set the video URL.
yt.url = raw_input("Enter url: ")
# yt.url = "http://www.youtube.com/watch?v=Ik-RsDGPI5Y"

print("Video Name: %s" % yt.filename)
yt.filename = "video"
video = yt.get("mp4", "720p")
video.download("video")
Exemple #20
0
# <Video: H.264 (.flv) - 480p>,
# <Video: H.264 (.mp4) - 360p>,
# <Video: H.264 (.mp4) - 720p>,
# <Video: VP8 (.webm) - 360p>,
# <Video: VP8 (.webm) - 480p>]

# The filename is automatically generated based on the video title.
# You can override this by manually setting the filename.

# view the auto generated filename:
print yt.filename

#Pulp Fiction - Dancing Scene [HD]

# set the filename:
yt.filename = 'minobrnauki_1.mp4'

# You can also filter the criteria by filetype.

pprint(yt.filter('flv'))

#[<Video: Sorenson H.263 (.flv) - 240p>,
# <Video: H.264 (.flv) - 360p>,
# <Video: H.264 (.flv) - 480p>]

# notice that the list is ordered by lowest resolution to highest. If you
# wanted the highest resolution available for a specific file type, you
# can simply do:
print yt.filter('mp4')[-1]
#<Video: H.264 (.mp4) - 720p>
Exemple #21
0
'''27 Jul 2015'''
from cStringIO import StringIO
import sys,io,os,time
global sys
import Tkinter as tk
from Tkinter import StringVar
from PIL import Image,ImageDraw,ImageFont,ImageTk
import numpy as np
global np,tk,Image,ImageDraw,ImageFont,ImageTk
global win,frame1,j,text,Picture1,Picture2,Picture2_1,Picture3,task,dotask,Font2,v
global Button,Button_im,Button_p,Button_im_p,Button_a,Button_im_a,Button_v,Button_im_v
if not os.path.isfile("9Things.mp4"):
	from pytube import YouTube
	yt=YouTube()
	yt.url="https://www.youtube.com/watch?v=4nP4PJL-9bg"
	yt.filename="9Things"
	video=yt.get('mp4')
	video.download()
FFMPEG_BIN = "ffmpeg.exe"
import subprocess as sp
Picture3=[]
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = mystdout = StringIO()
sys.stderr = mystderr = StringIO()
for i in range(10):
	if os.path.isfile("out"+str(i)+".jpg"):
		# from StackOverflow.com Q#6996603 answer by RichieHindle 9 Aug 2011
		os.remove("out"+str(i)+".jpg")
	if i>5:
		ss=str((i-5)*10)
Exemple #22
0
#!/usr/bin/python
import os, sys
from pprint import pprint

sys.path.insert(0, '.')

from pytube import YouTube

sys.stderr.write('ok')

yt = YouTube()

# Set the video URL.
yt.url = "http://www.youtube.com/watch?v=Ik-RsDGPI5Y"
yt.url = sys.argv[1]

pprint(yt.videos)

print yt.filename

yt.filename = 'Dancing Scene from Pulp Fiction'

pprint(yt.filter('flv'))
pprint(yt.filter('mp4'))

print yt.filter('mp4')[-1]

video = yt.get('mp4', '720p')

video.download('/tmp/', fhd=sys.stdout)
Exemple #23
0
def _main():
    parser = argparse.ArgumentParser(description='YouTube video downloader')
    parser.add_argument("url", help="The URL of the Video to be downloaded")
    parser.add_argument("--extension", "-e",
                        help="The requested format of the video", dest="ext")
    parser.add_argument("--resolution", "-r",
                        help="The requested resolution", dest="res")
    parser.add_argument("--path", "-p",
                        help="The path to save the video to.", dest="path")
    parser.add_argument("--filename", "-f",
                        dest="filename",
                        help=("The filename, without extension, "
                              "to save the video in."))

    args = parser.parse_args()

    yt =  YouTube()
    try:
        yt.url = args.url
    except YouTubeError:
        print "Incorrect video URL."
        sys.exit(1)

    if args.filename:
        yt.filename = args.filename

    if args.ext and args.res:
        # There's only ope video that matches both so get it
        vid = yt.get(args.ext, args.res)
        # Check if there's a video returned
        if not vid:
            print "There's no video with the specified format/resolution combination."
            sys.exit(1)

    elif args.ext:
        # There are several videos with the same extension
        videos = yt.filter(extension=args.ext)
        # Check if we have a video
        if not videos:
            print "There are no videos in the specified format."
            sys.exit(1)
        # Select the highest resolution one
        vid = max(videos)
    elif args.res:
        # There might be several videos in the same resolution
        videos = yt.filter(res=args.res)
        # Check if we have a video
        if not videos:
            print "There are no videos in the specified in the specified resolution."
            sys.exit(1)
        # Select the highest resolution one
        vid = max(videos)
    else:
        # If nothing is specified get the highest resolution one
        vid = max(yt.videos)

    try:
        vid.download(path=args.path, on_progress=print_status)
    except KeyboardInterrupt:
        print "Download interrupted."
        sys.exit(1)
Exemple #24
0
            'https://www.youtube.com/watch?v=jEpbjve5iHk', 'https://www.youtube.com/watch?v=tTihyXaz4Bo',
            'https://www.youtube.com/watch?v=2CdivtU5ytY', 'https://www.youtube.com/watch?v=ZvWftlp7TKY',
            'https://www.youtube.com/watch?v=WX03ODuzkSY', 'https://www.youtube.com/watch?v=Bcv46xKJH98',
            'http://egghead.io/lessons/angularjs-animating-with-javascript', 'http://egghead.io/lessons/angularjs-animating-the-angular-way',
            # 50 ... currently goes all the way to 77 with no more on YouTube
            )

    uris_len = len(uris)
    for idx, uri in enumerate(uris):
        print 'Processing: {0:02d} / {1}\n({2})\n'.format(idx+1, uris_len, uri)
        
        if uri[12:19] != 'youtube':
            continue   # Not a YouTube link, but we still need idx incremented for filenames
        
        yt = YouTube()
        yt.url = uri
        yt.filename = '{0:02d}{1}'.format(idx, yt.filename[23:])

        video = None
        if not video:
            video = yt.get('mp4', '1440p')
        if not video:
            video = yt.get('mp4', '1080p')
        if not video:
            video = yt.get('mp4', '720p')
        #if not video:
        #    exit("Couldn't find high-quality download")

        if video:
            video.download(realpath(''))