Пример #1
0
 async def getSong(self, videoId: str) -> Dict:
     song_meta = {"videoId": videoId}
     video = Video.get(videoId)
     song_meta["url"] = self.fetcher.get(video, 251)
     song_meta["title"] = video["title"]
     song_meta["lengthSeconds"] = int(
         video["streamingData"]["adaptiveFormats"][0]
         ["approxDurationMs"]) // 1000
     if video["description"].endswith("Auto-generated by YouTube."):
         try:
             description = video["description"].split("\n\n")
             for i, detail in enumerate(description):
                 description[i] = codecs.escape_decode(detail)[0].decode(
                     "utf_8")
             song_meta["provider"] = description[0].replace(
                 "Provided to YouTube by ", "")
             song_meta["artists"] = [
                 artist for artist in description[1].split(" · ")[1:]
             ]
             song_meta["copyright"] = description[3]
             song_meta["release"] = (None if len(description) < 5 else
                                     description[4].replace(
                                         "Released on: ", ""))
             song_meta["production"] = (None if len(description) < 6 else [
                 pub for pub in description[5].split("\n")
             ])
         except (KeyError, IndexError):
             pass
     return song_meta
Пример #2
0
def specific(request, title):
    #   try:
    data = Course.objects.get(id=title)
    data1 = {'data': data}
    if data.web == 'youtube':
        p = Playlist(data.link)
        datam = {}
        i = 0
        datam['link'] = data.link
        for url in p.video_urls[:3]:
            video = Video.get(url, mode=ResultMode.dict)
            datam['title' + str(i)] = video['title']
            datam['rating' + str(i)] = video['averageRating']
            datam['desc' + str(i)] = video['description']
            img = video['thumbnails']
            img = img[0]
            datam['img' + str(i)] = img['url']
            viewcount = video['viewCount']
            datam['vc' + str(i)] = viewcount['text']
            i += 1
        return render(request, 'maintemps/coursedetailyoutube.html', datam)
    else:
        return render(request, 'maintemps/coursedetailcoursera.html', data1)


#    except:
#return HttpResponse('error')
Пример #3
0
def downloadMethod(chat_id, user_id, vid_id, amount):
    if not amount:
        url = "https://www.youtube.com/watch?v=" + vid_id
        caption = f"<a href='{url}'><b>كيف تريد تنزيل الفيديو</b></a>"
        photo = requests.get(
            Video.getInfo(url)['thumbnails'][-1]['url']).content
    else:
        amount = int(amount)
        url = "https://www.youtube.com/playlist?list=" + vid_id
        if amount == 1:
            nameOFamount = "فيديو"
        elif amount == 2:
            nameOFamount = "فيديوهين"
        elif amount <= 10:
            nameOFamount = f"{amount} فيديوهات"
        else:
            nameOFamount = f"{amount} فيديو"

        caption = f"<a href='{url}'><b>كيف تريد تنزيل {nameOFamount}  من قائمة التشغيل📥</b></a>"
        try:
            photo = requests.get(
                Video.getInfo(Playlist(url).video_urls[0])['thumbnails'][-1]
                ['url']).content
        except:
            photo = requests.get(
                "https://i.pinimg.com/originals/09/0c/06/090c0658afb2350efff9c2ac705d5fe9.jpg"
            ).content
    markup = types.InlineKeyboardMarkup()
    markup.add(
        types.InlineKeyboardButton(
            text="ملف صوتي 💿",
            callback_data=f"DM F {user_id} {vid_id} {amount}"),
        types.InlineKeyboardButton(
            text="تسجيل صوتي 🎙",
            callback_data=f"DM V {user_id} {vid_id} {amount}"))
    markup.add(
        types.InlineKeyboardButton(text="الغاء التنزيل ⭕️",
                                   callback_data=f"DM cancel {user_id}"))
    bot.send_photo(chat_id=chat_id,
                   photo=photo,
                   caption=caption,
                   reply_markup=markup,
                   parse_mode="HTML")
Пример #4
0
def _get_playlist(url):
    playlist = Playlist.getVideos(url)
    for video in playlist["videos"]:
        url = video["link"]
        try:
            duration = video["duration"]
            video = Video.get(url)
            stream = fetcher.get(video, itag)
            yield (video["title"], duration, stream, url)
        except Exception as e:
            print(e)
Пример #5
0
    def get_youtube_info(cls, youtube_identifier):
        if youtube_identifier.startswith("https://www.youtube.com/watch?v="):
            youtube_identifier = youtube_identifier[32:]
        try:
            info = json.loads(
                YTVideo.getInfo('https://youtu.be/%s' % youtube_identifier, mode=ResultMode.json)
            )
        except TypeError:
            raise Exception("Invalid youtube video id")

        breaker, c = Breaker.objects.get_or_create(name=info['channel']['name'])
        date = info['publishDate']

        return {
            'youtube_identifier': youtube_identifier,
            "breaker": breaker,
            "date": datetime.datetime.strptime(date, "%Y-%m-%d")
        }
Пример #6
0
    def parse_url(self, url="", local=False, playlist=False, skip=0):
        videos = {}

        if local is False:
            fetcher = StreamURLFetcher()

            if playlist is True:
                playlist_data = Playlist.getVideos(url)
                videos_list = [x['link'] for x in playlist_data['videos']]
                videos_list = videos_list[skip:]
            else:
                if isinstance(url, list):
                    videos_list = url
                else:
                    videos_list = [url]

            for video_url in videos_list:
                video = Video.get(video_url)
                url = fetcher.get(video, 22)

                video = clean_for_directory(video['title'])

                videos[video] = url
        # If pulling from local
        else:
            if playlist is True:
                videos_list = os.listdir('input')
                videos_list.remove('.gitkeep')
                videos_list = videos_list[skip:]
            else:
                if isinstance(url, list):
                    videos_list = url
                else:
                    videos_list = [url]

            for video_file in videos_list:
                video_path = os.path.join('input', video_file)

                video = os.path.splitext(video_file)[0]

                videos[video] = video_path

        return videos
Пример #7
0
def get(name_or_url):
    if "youtu" in name_or_url:  # detect youtube link
        url = name_or_url
        if "playlist" in url:
            yield from _get_playlist(url)
            return
    else:
        result = VideosSearch(name_or_url, limit=1).result()["result"]
        if not result:
            yield ()
            return
        url = result[0]["link"]
        print(url)
    fetcher = StreamURLFetcher()
    video = Video.get(url)
    stream = fetcher.get(video, itag)
    duration = convert_duration(
        int(float(video["streamingData"]["formats"][0]["approxDurationMs"]) // 1000)
    )
    yield (video["title"], duration, stream, url)
Пример #8
0
#import search_courses
#courses=search_courses.simple_search(search_phrase='machine learning',type='list')
#courses = courses[0]
#print(courses)

from youtubesearchpython import Video, ResultMode

video = Video.get('https://www.youtube.com/watch?v=z0GKGpObgPY',
                  mode=ResultMode.dict)
print(video['description'])
Пример #9
0
async def _(event):
    "To search songs"
    reply_to_id = await reply_id(event)
    reply = await event.get_reply_message()
    if event.pattern_match.group(2):
        query = event.pattern_match.group(2)
    elif reply and reply.message:
        query = reply.message
    else:
        return await edit_or_reply(event, "`What I am Supposed to find `")
    cat = base64.b64decode("QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==")
    catevent = await edit_or_reply(event, "`wi8..! I am finding your song....`")
    video_link = await yt_search(str(query))
    if not url(video_link):
        return await catevent.edit(
            f"Sorry!. I can't find any related video/audio for `{query}`"
        )
    cmd = event.pattern_match.group(1)
    q = "320k" if cmd == "320" else "128k"
    song_cmd = song_dl.format(QUALITY=q, video_link=video_link)
    # thumb_cmd = thumb_dl.format(video_link=video_link)
    name_cmd = name_dl.format(video_link=video_link)
    try:
        cat = Get(cat)
        await event.client(cat)
    except BaseException:
        pass
    stderr = (await _catutils.runcmd(song_cmd))[1]
    if stderr:
        return await catevent.edit(f"**Error :** `{stderr}`")
    catname, stderr = (await _catutils.runcmd(name_cmd))[:2]
    if stderr:
        return await catevent.edit(f"**Error :** `{stderr}`")
    # stderr = (await runcmd(thumb_cmd))[1]
    catname = os.path.splitext(catname)[0]
    # if stderr:
    #    return await catevent.edit(f"**Error :** `{stderr}`")
    song_file = Path(f"{catname}.mp3")
    if not os.path.exists(song_file):
        return await catevent.edit(
            f"Sorry!. I can't find any related video/audio for `{query}`"
        )
    await catevent.edit("`yeah..! i found something wi8..🥰`")
    catthumb = Path(f"{catname}.jpg")
    if not os.path.exists(catthumb):
        catthumb = Path(f"{catname}.webp")
    elif not os.path.exists(catthumb):
        catthumb = None
    ytdata = Video.get(video_link)
    await event.client.send_file(
        event.chat_id,
        song_file,
        force_document=False,
        caption=f"**Title:** `{ytdata['title']}`",
        thumb=catthumb,
        supports_streaming=True,
        reply_to=reply_to_id,
    )
    await catevent.delete()
    for files in (catthumb, song_file):
        if files and os.path.exists(files):
            os.remove(files)
Пример #10
0
def main():
    local = args.video
    playlist = args.playlist
    url = args.url
    videos_to_skip = args.videos_to_skip

    # if(url == ''):
    #     if(not local):
    #       playlist = pafy.get_playlist(playlist_url)
    #       videos = []
    #       for item_i in (playlist['items']):
    #         videos.append(item_i['pafy'].videoid)
    #         v = pafy.new(videos[videos_to_skip])
    #         play = v.getbest(preftype="mp4")
    #         cap = cv2.VideoCapture(play.url)
    #     elif(local):
    #         videos = os.listdir('../input')
    #         videos.remove('.gitkeep')
    #         video = videos[videos_to_skip]
    #         cap = cv2.VideoCapture("../input/%s" % video)
    # else:
    #     play = pafy.new(url.split('v=')[1]).getbest(preftype="mp4")
    #     cap = cv2.VideoCapture(play.url)
    videos = {}
    if local is False:
        fetcher = StreamURLFetcher()

        if playlist is True:
            playlist_data = Playlist.getVideos(url)
            videos_list = [x['link'] for x in playlist_data['videos']]
            videos_list = videos_list[skip:]
        else:
            if isinstance(url, list):
                videos_list = url
            else:
                videos_list = [url]

        for video_url in videos_list:
            video = Video.get(video_url)
            url = fetcher.get(video, 22)

            # video = clean_for_directory(video['title'])

            videos[video['title']] = url
    # If pulling from local
    else:
        if playlist is True:
            videos_list = os.listdir('input')
            videos_list.remove('.gitkeep')
            videos_list = videos_list[skip:]
        else:
            if isinstance(url, list):
                videos_list = url
            else:
                videos_list = [url]

        for video_file in videos_list:
            video_path = os.path.join('input', video_file)

            video = os.path.splitext(video_file)[0]

            videos[video] = video_path

    cap = cv2.VideoCapture(videos[video['title']])

    while (True):
        frame_input = input("Skip how many frames?: (q to continue) ")
        if (frame_input.lower() in ('q', 'quit')):
            break
        # Sets video to frame frames_to_skip. Change until you have a frame where desired champion is isolated
        cap.set(1, int(frame_input))
        ret, frame = cap.read()
        cv2.imshow("Is the champion isolated?", frame)
        cv2.waitKey()

    cv2.destroyAllWindows()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    champ = input("Champion Name: ")

    count = 0
    while (True):
        count += 1
        input0 = input("Y-coordinate upper: (q to quit) ")
        if (input0.lower() in ('q', 'quit')):
            print("%s Successfully Added" % champ)
            break
        else:
            input1 = int(input("Y-coordinate lower: "))
            input2 = int(input("X-coordinate left: "))
            input3 = int(input("X-coordinate right: "))
        # Change these dimensions until you only have the desired champion in an ~14x14px image
        cropped = gray[int(input0):input1, input2:input3]

        cv2.destroyAllWindows()
        # Check image is ok
        cv2.imshow("Attempt #%s" % count, cropped)
        cv2.waitKey()

    # Saves image in correct directory
    cv2.imwrite('../assets/%s.jpg' % champ, cropped)
Пример #11
0
def main():
    local = args.video
    playlist = args.playlist
    url = args.url
    videos_to_skip = args.videos_to_skip

    # if(url == ''):
    #     if(not local):
    #       playlist = pafy.get_playlist(playlist_url)
    #       videos = []
    #       for item_i in (playlist['items']):
    #         videos.append(item_i['pafy'].videoid)
    #         v = pafy.new(videos[videos_to_skip])
    #         play = v.getbest(preftype="mp4")
    #         cap = cv2.VideoCapture(play.url)
    #     elif(local):
    #         videos = os.listdir('../input')
    #         videos.remove('.gitkeep')
    #         video = videos[videos_to_skip]
    #         cap = cv2.VideoCapture("../input/%s" % video)
    # else:
    #     play = pafy.new(url.split('v=')[1]).getbest(preftype="mp4")
    #     cap = cv2.VideoCapture(play.url)

    videos = {}
    if local is False:
        fetcher = StreamURLFetcher()

        if playlist is True:
            playlist_data = Playlist.getVideos(url)
            videos_list = [x['link'] for x in playlist_data['videos']]
            videos_list = videos_list[skip:]
        else:
            if isinstance(url, list):
                videos_list = url
            else:
                videos_list = [url]

        for video_url in videos_list:
            video = Video.get(video_url)
            url = fetcher.get(video, 22)

            # video = clean_for_directory(video['title'])

            videos[video['title']] = url
    # If pulling from local
    else:
        if playlist is True:
            videos_list = os.listdir('input')
            videos_list.remove('.gitkeep')
            videos_list = videos_list[skip:]
        else:
            if isinstance(url, list):
                videos_list = url
            else:
                videos_list = [url]

        for video_file in videos_list:
            video_path = os.path.join('input', video_file)

            video = os.path.splitext(video_file)[0]

            videos[video] = video_path

    cap = cv2.VideoCapture(videos[video['title']])

    while (True):
        frame_input = input(
            "Skip how many frames?: (q if image shows all players at level 1) "
        )
        if (frame_input.lower() in ('q', 'quit')):
            break
        # Sets video to frame frames_to_skip. Change until you have a frame where desired champion is isolated
        cap.set(1, int(frame_input))
        ret, frame = cap.read()
        cv2.imshow("All players level 1?", frame)
        cv2.waitKey()

    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # 5 different vertical coordinates for 5 different roles
    locations = [110, 180, 247, 315, 383]

    print("""
        Numbers: 
        1  : Blue side toplaner
        2  : Blue side jungler
        3  : Blue side midlaner
        4  : Blue side ADC
        5  : Blue side support

        6  : Red side toplaner
        7  : Red side jungler
        8  : Red side midlaner
        9  : Red side ADC
        10 : Red side support
    """)

    while (True):
        # 1-5 blue side Top-Support, 6-10 red side Top-Support
        try:
            i = int(input("Number (q to exit):\n")) - 1
        except:
            break
        # Champion name
        name = input("Champ:\n")
        x = 25
        y = 45
        col = "blue"
        if (i >= 5):  # If champ is on red side
            x = 1235
            y = 1255
            col = "red"

        # Crop image to portrait
        cropped = gray[locations[i % 5]:(locations[i % 5] + 20), x:y]

        # Save image to directory
        cv2.imwrite(
            '../assets/tracking/champ_classifying/%s/%s.jpg' % (col, name),
            cropped)
        print("%s saved to %s side" % (name, col))