コード例 #1
0
def run_extractor(target_img, vid_ext, path_output_dir, num_results=10):
    #image
    target = cv2.cvtColor(target_img, cv2.COLOR_BGR2GRAY)
    top_n_frames = extract_top_frames(video, "out", target, num_results)

    #video
    yt('http://youtube.com/watch?v=%s' % vid_ext).streams.filter(
        subtype='mp4').first().download("./videos", filename=vid_ext)

    #debug
    app.logger.debug(target_img)
    app.logger.debug(os.getcwd())
    app.logger.debug(os.listdir("."))
    app.logger.debug(os.listdir("./static"))
    app.logger.debug(os.listdir("./static/in"))
    app.logger.debug(os.listdir("./videos"))
    app.logger.debug(os.listdir("/tmp"))

    for img_ind in range(len(top_n_frames)):
        if top_n_frames[img_ind] is None:
            break
        #print ("Rank %d: Frame %s with distance %f"%(img_ind, top_n_frames[img_ind][1], top_n_frames[img_ind][0]))
        cv2.imwrite(
            os.path.join(path_output_dir,
                         '%s.png' % (top_n_frames[img_ind][1])),
            top_n_frames[img_ind][3])
        cv2.imwrite(
            os.path.join(path_output_dir,
                         '%s_proc.png' % (top_n_frames[img_ind][1])),
            top_n_frames[img_ind][4])
    return top_n_frames
コード例 #2
0
def downloadVid():
    global entry
    link = entry.get()
    try:
        yt(link).streams.first().download(SAVE_PATH)
    except:
        print('An error occurred')
    print(yt(link).title + ' successfully downloaded!')
コード例 #3
0
ファイル: downloader.py プロジェクト: brando5393/YT_video_dl
 def download_video(self, url):
     try:
         if url != None or "":
             yt(url).streams.get_highest_resolution().download(
                 "./downloads")
             print(f"Starting your download of {yt(url).title}")
         else:
             print(
                 f"Sorry but your request to download the video {yt(url).title} could not be completed at this time. Please try again later, thank you."
             )
     except:
         pass
コード例 #4
0
ファイル: ytb.py プロジェクト: Legenda24/YT-Thumbnail-Bot
async def gyt(_, msg):
    try:
        vid_url = msg.matches[0].group(0)
        yt_vid = yt(vid_url)

        vid_turl = yt_vid.thumbnail_url
        vid_title = yt_vid.title
        vid_author = yt_vid.author
        vid_length = timedelta(seconds=yt_vid.length)
        vid_pdate = yt_vid.publish_date.strftime("%Y-%m-%d")

        kb = InlineKeyboardMarkup([[
            InlineKeyboardButton("🔗Link",
                                 url=f"https://youtu.be/{vid_url[-11:]}")
        ]])
        await msg.reply_photo(
            vid_turl,
            caption=f"""🎬 **{vid_title}**
👤 `{vid_author}`

⏳ **{vid_length}**
🗓 `{vid_pdate}`""",
            quote=True,
            reply_markup=kb,
        )
    except VideoUnavailable:
        await msg.reply("**Invalid video link!**", quote=True)
コード例 #5
0
def File_nam(url):
    try:
        link = yt(url)
        title, thumbnail_url, video_length = link.title, link.thumbnail_url, link.length
        filtered_link = link.streams.filter(progressive = True)
        for arrt in filtered_link:
            res = getattr(arrt,'resolution') 
            mime_type = getattr(arrt,'mime_type')
            print(res,mime_type)
        print(title,thumbnail_url,video_length)
    except TypeError:
        link = yt(url)
        title, thumbnail_url, video_length = link.title, link.thumbnail_url, link.length
        filtered_link = link.streams.filter(progressive = True)
        resolution, video_format = getattr(filtered_link,'resolution'),getattr(filtered_link,'mime_type')
        print(title,thumbnail_url,video_length,video_format,resolution)
コード例 #6
0
ファイル: downloader.py プロジェクト: scslmd/Sublacer
def download_video(link, output_path, file_name):
    """
    A function that downloads a youtube video
    """
    vid = yt(link)
    stream = vid.streams.filter(progressive=True, file_extension='mp4').first()
    stream.download(output_path, filename=file_name)
コード例 #7
0
ファイル: utils.py プロジェクト: aquacash5/PodTube
def get_youtube_url(video_id):
    if video_id in video_links and video_links[video_id]['expire'] > datetime.now():
        return video_links[video_id]['url']
    yt_video = yt(f'http://www.youtube.com/watch?v={video_id}')
    video_url = max(yt_video.filter('mp4'), key=get_resolution).url
    parts = {part.split('=')[0]: part.split('=')[1] for part in video_url.split('?')[-1].split('&')}
    link = {'url': video_url, 'expire': datetime.fromtimestamp(int(parts['expire']))}
    video_links[video_id] = link
    return link['url']
コード例 #8
0
    def get_name(self, link_vid=None):

        '''
            Retorna el nombre del video.
        '''

        self.link_vid = link_vid
        title = yt(self.link_vid)
        return title.title 
コード例 #9
0
def go_pytube():
    try:
        go_yt = yt(yt_url)
        name = safe_filename(go_yt.title)
        print(u'名稱:', name)
        return go_yt, name
    except reME:
        print(u'不正常的網址...')
        e = input(u'按下 Enter按鍵 離開')
        exit()
コード例 #10
0
 def download_aud(self, ref_url=None):
     '''
         Escoge la mejor calidad de audio y la descarga.
     '''
     try:
         self.ref_url = ref_url
         stream = yt(self.ref_url)
         self.audio = stream.streams.order_by('abr').last()
         self.audio.download()
     except:
         return 'Error: URL no valido'
コード例 #11
0
 def downloading(self):
     global select
     var = url.get()
     choice = n.get()
     video = yt(var, on_progress_callback=self.progress_func)
     if choice == choices[0]:
         select = video.streams.filter(progressive=True).first()
     elif choice == choices[1]:
         select = video.streams.filter(progressive=True).last()
     elif choice == choices[2]:
         select = video.streams.filter(only_audio=True).first()
     select.download(file_name)
コード例 #12
0
def download_playlist(var1):
    for i in tqdm(var1): 
        try: 
            x = yt(i)
        except ex.VideoUnavailable:
            print("cant download")
        else:
            #print("downloading : {i} ")
            audio = x.streams.get_audio_only()
            audio.download(r"C:\Users\ASUS\music")
    for fi in glob.glob("*.mp4"):
       os.rename(fi, fi[:-3] + "mp3")
    return "Done"
コード例 #13
0
def youtube_results(ext, target):
    yt('http://youtube.com/watch?v=%s' %
       ext).streams.filter(subtype='mp4').first().download("./videos",
                                                           filename=ext)

    results = similar_engine.run_extractor("static/in/%s" % (target),
                                           "videos/" + ext + ".mp4",
                                           "static/out/%s" % ext)
    app.logger.debug("\nframes extracted")

    try:
        os.mkdir("static/out/%s" % ext)
        results = similar_engine.run_extractor("static/in/%s" % (target),
                                               "videos/" + ext + ".mp4",
                                               "static/out/%s" % ext)
        with open("static/out/%s/results" % ext, "wb") as f:
            pickle.dump(results, f)
    except:
        with open("static/out/%s/results" % ext, "rb") as f:
            results = pickle.load(f)
    return render_template("results.html",
                           youtube_ext=ext,
                           timestamps=results,
                           target=os.path.join('/static/in', target))
コード例 #14
0
ファイル: utils.py プロジェクト: padok/PodTube
def get_youtube_url(video_id):
    if video_id in video_links and video_links[video_id][
            'expire'] > datetime.now():
        return video_links[video_id]['url']
    yt_video = yt(f'http://www.youtube.com/watch?v={video_id}')
    video_url = max(yt_video.filter('mp4'), key=get_resolution).url
    parts = {
        part.split('=')[0]: part.split('=')[1]
        for part in video_url.split('?')[-1].split('&')
    }
    link = {
        'url': video_url,
        'expire': datetime.fromtimestamp(int(parts['expire']))
    }
    video_links[video_id] = link
    return link['url']
コード例 #15
0
def inti():
    link = input('Masukkan Link>> ')
    name = input('Masukkan Nama File>> ')
    pip = name + '.mp4'
    kontol = name + '.mp3'
    spinner = Halo(text='Sedang Mengkonversi', spinner='dots')
    spinner.start()
    if os.name == 'posix':
        lokasi = os.getcwd() + '/'
    else:
        print("maaf platform anda tidak support")
    suk = yt(link)
    print(suk.title)
    suk.streams.filter(only_audio=True).first().download(filename=name)
    spinner.stop()
    os.system("mv {} {}".format(pip, kontol))
コード例 #16
0
    def comprobar_url(self, url=None):

        '''
            Verifica si la url de una playlist o un video independiente.
        '''

        self.url = url

        if '&list' in url:
            try:
                self.plist = pl(self.url)
                return True
            except:
                return 'Error: Url no valido'
        else:
            try:
                self.list = yt(self.url)
                return True
            except pytube.exceptions.RegexMatchError:
                return 'Error: URL no valido'
コード例 #17
0
    def convert_aud(self, aud_ext=None):

        '''
            Cambia la extencion del archivo a mp3
        '''

        self.aud_ext = yt(aud_ext).title

        for a in '\\/<>"?|*:':
            self.aud_ext = self.aud_ext.replace(a, '')

        self.act_ext = ''
        self.new_ext = self.aud_ext
        self.new_ext += '.mp3'

        for entry in os.scandir():
            if not entry.name.startswith('.') and entry.is_file():
                if self.aud_ext in entry.name:
                    self.act_ext = entry.name
                    break

        os.replace(self.act_ext, self.new_ext)
コード例 #18
0
ファイル: simple.py プロジェクト: lustered/cuteplayer
def download_url():
    try:
        if path.isdir(download_dir): 
            pass
    except FileNotFoundError:
        os.mkdir(download_dir)

    url_inserted = entry.get()
    isvalid_domain = False
    if valid.url(url_inserted) and 'youtube' in url_inserted:
        isvalid_domain = True
        print('[Valid URL]')

    if url_inserted and isvalid_domain:
        video = yt(url_inserted)
        cwd = os.getcwd()
        ls = os.listdir(cwd)
        exists = False

        for x in range(len(ls)):
            if video.title in ls[x]:
                exists = True

        if exists:
            print("file exists and video won't be downloaded")
        else: 
            warningMessage.grid_forget()
            print('[[**** Video Downloading ****]]')
            call(["youtube-dl --extract-audio --audio-format mp3 \
                 -o '%s' %s" % (full_download,url_inserted)], shell = True)
            print("[Song: %s \tDownloaded" % (video.title))
    else:
        print('** Please enter a valid URL **')
        warningMessage.grid(column = 3, row = 5)


    entry.delete(0,'end')
    entry.focus()
コード例 #19
0
ファイル: craw.py プロジェクト: sanjusci/algos
    def run(self, *args, **kwargs):
        final_path = '{}'.format(SAVE_DIRECTORY)
        if self.channel:
            final_path = final_path + '{}'.format(self.channel_id)
        if not os.path.exists(final_path):
            os.makedirs(final_path)
            os.chmod(final_path, 755)

        if self.channel_id:
            url = '{}{}{}{}'.format(YOUTUBE_URL, CHANNEL, self.channel_id,
                                    VIDEOS)
            __get_object = rq.get(url=url)
            text = __get_object.text
            status_code = __get_object.status_code
            if status_code == 200:
                dt = {}
                b = bs(text, features="html.parser")
                for link in b.find_all('a'):
                    if 'watch' in link.get('href'):
                        dt.update({
                            link.get('href'):
                            YOUTUBE_URL + '{}'.format(link.get('href'))
                        })
                self.video_urls.extend(dt.values())
            else:
                print(status_code)
                print(text)
        os.chdir(final_path)
        if len(self.video_urls):
            for url in self.video_urls:
                try:
                    t = yt(url, on_progress_callback=self.on_progress)
                    t.streams.filter(progressive=True, file_extension='mp4')\
                        .order_by('resolution')\
                        .desc()\
                        .first().download()
                except Exception as e:
                    print("Error in video download: {}".format(e))
コード例 #20
0
def main():
    if len(argv) == 1: url = input('YouTube video URL:> ')
    else: url = argv[1]
    video = yt(url)
    video.register_on_progress_callback(progreso)

    stream = video.streams.filter(only_audio=True).first()
    descripcion = video.description
    duracion = video.length

    paresTiempoCancion = getPares(descripcion)

    if search('\d{1,2}:\d{1,2}', paresTiempoCancion[0][1]):
        [x.reverse() for x in paresTiempoCancion]
    elif search('\d{1,2}:\d{1,2}', paresTiempoCancion[0][0]):
        pass
    else:
        salir('Mmmm... problemas con el formato', paresTiempoCancion)

    print('Descargando:\n')
    fileName = stream.download('Downloads/')

    split(fileName, paresTiempoCancion, duracion)
コード例 #21
0
from selenium import webdriver
import time
from pytube import YouTube as yt
import os
from selenium.webdriver.chrome.options import Options  

ydl_opts = {} 
    
url = input("Enter youtube playlist link : ")
chrome_options = Options()  
chrome_options.add_argument("--headless")  

driver = webdriver.Chrome(options=chrome_options)
driver.get(url)
time.sleep(5)
playlist=[]
videos=driver.find_elements_by_id('video-title')
for video in videos:
    link=video.get_attribute("href")
    end=link.find("&")
    link=link[:end]
    playlist.append(link)
os.chdir('C:/Users/Trideep/Downloads') 

for link in playlist:
    print(link)
    vid=yt(link)
    vid.streams.get_highest_resolution().download()
    print(vid.title+" has been successfully downloaded !!")
driver.close()
コード例 #22
0
                        '--res',
                        type=str,
                        help='resolution of the video')
    args = parser.parse_args()
    isPlaylist = False  # Playlist or not
    playlist_videos = []
    isMultiple = False  # Multiple URLS or not
    multiple_videos = []
    url = args.url
    try:
        if 'playlist' in url:
            videos = playlist_to_watch_urls(url)
            for video in videos:
                url = "https://www.youtube.com/watch?v=" + video
                playlist_videos.append(
                    yt(url, on_progress_callback=on_progress))
            isPlaylist = True
        elif ',' in url:
            urls = url.split(',')
            for url in urls:
                multiple_videos.append(
                    yt(url, on_progress_callback=on_progress))
            isMultiple = True
        else:
            video = yt(url, on_progress_callback=on_progress)
    except:
        print(red + '[-] Invalid URL!')
        print(reset)
        exit(0)

    type = args.type
コード例 #23
0
import PySimpleGUI as sg
from pytube import YouTube as yt

sg.theme("LightBrown7")
layout = [[sg.Text("Enter the link of the video you want to download!")],
          [sg.Input()],
          [
              sg.Text("Wait until the video is downloaded!",
                      size=(40, 1),
                      key="resp")
          ], [sg.Button('Video'),
              sg.Button('Audio'),
              sg.Button('Quit')]]

window = sg.Window("YouTube Video Downloader", layout)

while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED or event == "Quit":
        break

    if event == "Video":
        yt(values[0]).streams.first().download()

    else:
        yt(values[0]).streams.filter(only_audio=True).first().download()

    window["resp"].update("Done!")
window.close()
コード例 #24
0
ファイル: youtube_mp3.py プロジェクト: manish33scss/pytube
Created on Sat Mar 13 23:50:42 2021

@author: ASUS
"""

from pytube import Playlist as pt
from tqdm import tqdm
from pytube import YouTube as yt
import os, glob
import pytube.exceptions as ex
var1 = pt(
    "https://www.youtube.com/playlist?list=PL2Iefjpn3w-Mg_QIF6Eivl_Fl1XshaSSQ")

#where to save
SAVE_PATH = r"C:\Users\ASUS\music"  #to_do
os.chdir(SAVE_PATH)

for i in tqdm(var1):
    try:
        x = yt(i)
    except ex.VideoUnavailable:
        print("cant download")
    else:
        #print("downloading : {i} ")
        audio = x.streams.get_audio_only()
        audio.download(r"C:\Users\ASUS\music")
for fi in glob.glob("*.mp4"):
    os.rename(fi, fi[:-3] + "mp3")

print("completed")
コード例 #25
0
#Downloading video from Youtube

from pytube import YouTube as yt
video_link = "https://www.youtube.com/watch?v=YWcu_8xPSs8"
vid = yt(video_link)
stream = vid.streams.first()  #Getting the first stream
stream.download()
'''Now we have our data in the form of a video which is nothing 
but a group of frames( images). Since we are going to solve this problem using image classification.
We need to extract the images from the video'''

import cv2
'''Opens the video File'''
cap = cv2.VideoCapture('D:\\Interviews\\video\\1.mp4')
i = 0
image = 'x'
ret = 1
while ret:
    ret, frame = cap.read()
    if ret == False:
        break
    cv2.imwrite("frame%d.jpg" % i, frame)
    i += 1
cap.release()
cv2.destroyAllWindows()

#After this the video will be divided into individual frames.In this problem I have taken only two class,amitabh or no amitabh
'''Input data and preprocessing'''
'''We have data in the form of images.To prepare this data for the neural network,We need to do some preprocessing'''
from tqdm import tqdm
import cv2
コード例 #26
0
    DASH = yt.streams.filter(adaptive=True).all()
    audio = yt.streams.filter(only_audio=True).all()
    mp4 = yt.streams.filter(file_extension='mp4').all()
    #prog_stream = progressive.streams.first()

    #Progress720 = yt.streams.get_by_res('720p')
    print(progressive)
    print(DASH)
    print(audio)
    print(mp4)
    progressive[0].download()
    #audio.download()
    #mp4.download()
    #Progress720.download()


"""       
def Defined_User(url):
    url = input(" Enter an url :" ,url)
    print (" The url is ", url)
    
"""
if __name__ == '__main__':
    yt = yt("https://www.youtube.com/watch?v=9bZkp7q19f0")
    Procedure2_3(yt)
    Procedure_4(yt)
    #url = input("Enter an url:")
    #print(" The url is ", url)
    #url = input("Enter he directory:")
    #print(" The url is ", url)
コード例 #27
0
def checker(source, urll, str_id):
    with open("{}/Video_Key.csv".format(os.getcwd()), "w") as fw:
        fw.write(str_id)
    countnum = 0
    berror = "They Blocked Temporarily...Try_Again_Later"
    global sel
    while True:
        agent = {
            'User-Agent':
            "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1"
        }
        urllib3.disable_warnings()
        try:
            req = requests.get(url=source,
                               headers=agent,
                               verify=False,
                               timeout=6)
            req.close()
        except requests.exceptions.ConnectionError:
            print("CHECK internet Connection...!")
            None
        except requests.exceptions.ReadTimeout:
            print("Time_Out_{}".format(berror))
            sys.exit(0)
        soup = bs(req.content, 'lxml')
        try:
            aum = soup.find_all("div", {'id': 'initial-data'})[0]
            jsn = json.loads(aum.string)
        except Exception:
            print("No_Data_{}".format(berror))
            sys.exit(0)
        sle = jsn["contents"]["singleColumnBrowseResultsRenderer"]["tabs"][1]
        itm = sle["tabRenderer"]["content"]["sectionListRenderer"]["contents"][
            0]["itemSectionRenderer"]
        holder = []
        for tmp in range(30):
            try:
                con3 = itm["contents"][tmp]
                fil = [
                    con3["compactVideoRenderer"]["title"]["runs"][0]["text"]
                ]
                fi = con3["compactVideoRenderer"]["videoId"]
                holder.append(fi)
            except IndexError:
                pass
        newfile = pd.DataFrame({"chan": holder})
        with open("{}/Video_Key.csv".format(os.getcwd()), "r") as fl:
            fle = fl.readlines()
            chh = fle[0]
            sam = newfile[newfile["chan"].str.contains(chh)]
            ttt = sam.T
        try:
            amount = int(ttt.columns[0])
            countnum = countnum + 1
            print("COUNT:[{}] | [{}]:Videos Found !".format(countnum, amount),
                  end="\r")
            newlink = newfile.head(amount)
            linkss = []
            unq = []
            for f, lk in newlink.iterrows():
                unq.append(lk['chan'])
                linkss.append(urll + str(lk["chan"]))
            for tf in linkss:
                print("\n{}Plz wait it Downloading...".format("\t" * 2),
                      end="\r")
                try:
                    urls = yt(tf).streams.all()
                    sep = urls[0]
                    red = sep.default_filename[:35]
                    sep.download('{}'.format(os.getcwd()), filename=red)
                except pytube.exceptions.VideoUnavailable:
                    print("They Upload properly {}".format(tf))
                    None
                except pytube.exceptions.RegexMatchError:
                    print("URL pattern NOT fit...! {}".format(tf))
                    None
                print("{}DownLoaded!!!".format(" " * 30))
                asc = unq[0]
                with open("{}/Video_Key.csv".format(os.getcwd()), "w") as fw:
                    fw.write(asc)
        except IndexError:
            None
        sleep(int(random.randint(6, 18)))
コード例 #28
0
                            cd, trainingdata + "/" + "image_" + tail + "_" +
                            str(count)) + ".jpg", fpos)

            #if ret and count % frameRate == 0:
            #    cv2.imwrite(os.path.join(cd,trainingdata+"/"+"image_"+tail+"_"+str(count))+".jpg",frame)
            count += 1


# create a dataset using youtube as a source.

from pytube import YouTube as yt

links = ["https://www.youtube.com/watch?v=PdCgmL1EocU"]

for link in links:
    v = yt(link)
    print("Downloading from ", link)
    try:
        #attempt to download in 720p, 1080p too large of a download
        v.streams.filter(mime_type="video/mp4", res="720p").first().download()
    except Exception as e:
        #720p not available, download any version
        v.streams.filter(mime_type="video/mp4").first().download()
    print("Downloaded ", link)

# get all videos from folder

for file in os.listdir(cd):
    if file.endswith("mp4"):
        print("Classifying faces on ", file)
        path = os.path.join(cd, file)
コード例 #29
0
from pytube import YouTube as yt

url = 'https://www.youtube.com/watch?v=TYcyqgS_LRg'

try:
    youtube = yt(url)
    video = youtube.streams.get_highest_resolution()
    video.download(
        'C:/Users/????/Downloads'
    )  #Informar caminho onde deseja salvar os vídeos; a pasta do projeto é default
    print("Vídeo foi gravado com sucesso!")
except Exception as err:
    print('Vídeo não foi baixado. Ocorreu o seguinte erro: ' + str(err))
コード例 #30
0
def File_name(url):
    link = yt(url)
    title, thumbnail_url, length = link.title, link.thumbnail_url, link.length
    return  link, title, thumbnail_url, length