def __init__(self): super(YoutubeSkill, self).__init__(name="YoutubeSkill") self.nextpage_url = None self.previouspage_url = None self.live_category = None self.recentList = deque() self.recentPageObject = {} self.nextSongList = None self.lastSong = None self.videoPageObject = {} self.isTitle = None self.trendCategoryList = {} self.newsCategoryList = {} self.musicCategoryList = {} self.techCategoryList = {} self.polCategoryList = {} self.gamingCategoryList = {} self.searchCategoryList = {} self.recentCategoryList = {} self.recentWatchListObj = {} self.storeDB = dirname(__file__) + '-recent.db' self.recent_db = JsonStorage(self.storeDB) self.ytkey = base64.b64decode( "QUl6YVN5RE9tSXhSemI0RzFhaXFzYnBaQ3IwQTlFN1NrT0pVRURr") pafy.set_api_key(self.ytkey) self.quackAPIWorker = "J0dvb2dsZWJvdC8yLjEgKCtodHRwOi8vd3d3Lmdvb2dsZS5jb20vYm90Lmh0bWwpJw==" self.quackagent = {'User-Agent': base64.b64decode(self.quackAPIWorker)} self.yts = YoutubeSearcher()
def __init__(self, parent=None): super(MainApp, self).__init__(parent) QMainWindow.__init__(self) pafy.set_api_key('AIzaSyByS0QBxm3r5M8JMy3bYQ3dtPAoOCj-dz0') self.setupUi(self) self.Handel_Ui() self.Handel_Buttons()
def init(): """ Initial setup. """ _process_cl_args() # set player to mpv or mplayer if found, otherwise unset suffix = ".exe" if mswin else "" mplayer, mpv = "mplayer" + suffix, "mpv" + suffix if not os.path.exists(g.CFFILE): if has_exefile(mpv): config.PLAYER.set(mpv) elif has_exefile(mplayer): config.PLAYER.set(mplayer) config.save() else: config.load() _init_readline() cache.load() _init_transcode() # ensure encoder is not set beyond range of available presets if config.ENCODER.get >= len(g.encoders): config.ENCODER.set("0") # check mpv/mplayer version if has_exefile(config.PLAYER.get): load_player_info(config.PLAYER.get) # setup colorama if has_colorama and mswin: # Colorama converts ansi escape codes to Windows system calls colorama.init() # find muxer app if mswin: g.muxapp = has_exefile("ffmpeg.exe") or has_exefile("avconv.exe") else: g.muxapp = has_exefile("ffmpeg") or has_exefile("avconv") # initialize MPRIS2 interface if config.MPRIS.get: try: from . import mpris conn1, conn2 = multiprocessing.Pipe() g.mprisctl = mpris.MprisConnection(conn1) t = multiprocessing.Process(target=mpris.main, args=(conn2,)) t.daemon = True t.start() except ImportError: print("could not load MPRIS interface. missing libraries.") # Make pafy use the same api key pafy.set_api_key(config.API_KEY.get)
async def volume(self, ctx, volume: float = 50): pafy.set_api_key(next(MusicBot.YOUTUBE_API)) if volume > 100: if await MusicBot.langueg(ctx) == "RUS": embed = discord.Embed( title=f"Максимум допустимое число это 100", color=0xf4680b) await ctx.send(embed=embed) elif await MusicBot.langueg(ctx) == "ENG": embed = discord.Embed( title=f"The maximum allowed number is 100", color=0xf4680b) await ctx.send(embed=embed) return else: volume = volume / 100 self.vol = volume self.voice.source.volume = self.vol if await MusicBot.langueg(ctx) == "RUS": embed = discord.Embed( title=f"`Горомкость сейчас: {int(self.vol*100)}%`", color=0xf4680b) embed.set_author( name=f"Пользователь {ctx.author.name} изменил громкость", icon_url=f"{ctx.author.avatar_url}") mess = await ctx.send(embed=embed) elif await MusicBot.langueg(ctx) == "ENG": embed = discord.Embed( title=f"`Volume now: {int(self.vol*100)}%`", color=0xf4680b) embed.set_author( name=f"User {ctx.author.name} changed the volume", icon_url=f"{ctx.author.avatar_url}") mess = await ctx.send(embed=embed) await asyncio.sleep(4) await mess.delete()
def set_api_key(): if const.args.youtube_api_key: key = const.args.youtube_api_key else: # Please respect this YouTube token :) key = "AIzaSyC6cEeKlxtOPybk9sEe5ksFN5sB-7wzYp0" pafy.set_api_key(key)
def youtube_download_video(video_id, output_path): url = YOUTUBE_VIDEO_URL_PREFIX + video_id try: pafy.set_api_key(DEVELOPER_KEY) video = pafy.new(url, basic=False) print("VIDEO INFORMATION") print(" video.title = %s" % video.title) print(" video.viewcount = %i" % video.viewcount) print(" video.author = %s" % video.author) print(" video.length = %i" % video.length) print(" video.duration = %s" % video.duration) print(" video.likes = %i" % video.likes) print(" video.dislikes = %i" % video.dislikes) video_best = video.getbest(preftype='mp4') output_file = os.path.join( output_path, video_id + "." + video_best.extension) video_best.download(filepath=output_file, quiet=True) except: print("Warning, unable to download video with id '%s'" % video_id) return False return True
def ready(self): # noinspection PyUnresolvedReferences import podcasts.signals import pafy from podify.settings import env api_key = env('API_KEY') pafy.set_api_key(api_key)
def run(self): play_thread = Thread(target=self.play_loop) play_thread.start() download_thread = Thread(target=self.download_loop) download_thread.start() pafy.set_api_key(config.YOUTUBE_API_KEY)
def __init__(self,url,path): self.allowed_symbols = re.sub('[/\\:?"<>|*]', '_', string.printable) self.playlist_author = '' self.playlist_title = '' self.playlist_size = 0 self.playlist_url = url self.dir_to_dl = path pafy.set_api_key('AIzaSyBHkNTjYXIDMR7TdoR7ZqgNiymYgvvt_pE')
def init(): """ Initial setup. """ _process_cl_args() # set player to mpv or mplayer if found, otherwise unset suffix = ".exe" if mswin else "" mplayer, mpv = "mplayer" + suffix, "mpv" + suffix if not os.path.exists(g.CFFILE): if has_exefile(mpv): config.PLAYER.set(mpv) elif has_exefile(mplayer): config.PLAYER.set(mplayer) config.save() else: config.load() _init_readline() cache.load() _init_transcode() # ensure encoder is not set beyond range of available presets if config.ENCODER.get >= len(g.encoders): config.ENCODER.set("0") # check mpv/mplayer version if has_exefile(config.PLAYER.get): load_player_info(config.PLAYER.get) # setup colorama if has_colorama and mswin: # Colorama converts ansi escape codes to Windows system calls colorama.init() # find muxer app if mswin: g.muxapp = has_exefile("ffmpeg.exe") or has_exefile("avconv.exe") else: g.muxapp = has_exefile("ffmpeg") or has_exefile("avconv") # initialize remote interface try: from . import mpris g.mprisctl, conn = multiprocessing.Pipe() t = multiprocessing.Process(target=mpris.main, args=(conn,)) t.daemon = True t.start() except ImportError: pass # Make pafy use the same api key pafy.set_api_key(config.API_KEY.get)
def get_video_data(url): """ Uses the Pafy library to get the duration of the youtube video. :param url: Url of the video link. :return: The duration of the video """ pafy.set_api_key(settings.YOUTUBE_API) video = pafy.new(url) return video.duration, video.videoid
def __init__(self): # self.flow = flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES) # self.credentials = flow.run_console() # self.client = None self.key = DEVELOPER_KEYS[0] self.client = build(SERVICE_NAME, VERSION, developerKey=self.key, cache_discovery=False) pafy.set_api_key(self.key)
def __init__(self): self.YT_API_KEY = vibes_settings["YT_API_KEY"] self.YT_CHANNEL_ID = vibes_settings["YT_CHANNEL_ID"] self.PLAYLISTS_URL = "https://www.googleapis.com/youtube/v3/playlists?key=%s&part=snippet&maxResults=50&channelId=%s" % ( self.YT_API_KEY, self.YT_CHANNEL_ID) self.PLAYLISTITEMS_URL = "https://www.googleapis.com/youtube/v3/playlistItems?key=%s&part=snippet&maxResults=50&playlistId=" % self.YT_API_KEY self.MAIN_DIR_PATH = vibes_settings["MAIN_DIR_PATH"] self.LIBRARY_PATH = self.MAIN_DIR_PATH + "/lib.json" self.COVER_ART_URL = "https://img.youtube.com/vi/%s/maxresdefault.jpg" if self.YT_API_KEY != "": pafy.set_api_key(self.YT_API_KEY)
def Download_return(self): # if urllib.request.urlopen(self.url).code == 200: pafy.set_api_key('AIzaSyCp0RX2L3eDzuNiPNJr34jom1-gUsj_ze0') video = pafy.new(self.url) stream = video.streams print(video.audiostreams) video_audio_streams = [] for s in stream: video_audio_streams.append({ 'resolution': s.resolution, 'extension': s.extension, # 'file_size': filesizeformat(s.get_filesize()), 'video_url': s.url + "&title=" + video.title }) stream_video = video.videostreams print('video stream') video_streams = [] for s in stream_video: video_streams.append({ 'resolution': s.resolution, 'extension': s.extension, # 'file_size': filesizeformat(s.get_filesize()), 'video_url': s.url + "&title=" + video.title }) stream_audio = video.audiostreams audio_streams = [] for s in stream_audio: audio_streams.append({ 'resolution': s.resolution, 'extension': s.extension, # 'file_size': filesizeformat(s.get_filesize()), 'video_url': s.url + "&title=" + video.title }) print('before context') context = { # 'form': form, 'title': video.title, 'streams': video_audio_streams, 'description': video.description, 'likes': video.likes, 'dislikes': video.dislikes, 'thumb': video.bigthumbhd, 'duration': video.duration, 'views': video.viewcount, 'stream_video': video_streams, 'stream_audio': audio_streams } self.context = context return
def get_download_url(request): ytApiKey = settings.YT_API_KEY pafy.set_api_key(ytApiKey) data = request.body.decode('utf-8') req_data = json.loads(data) videoid = req_data['videoid'] idx = int(req_data['idx']) stream_type = req_data['stream_type'] try: video = pafy.new(videoid) if stream_type == 'audio-mp3': stream = video.audiostreams[idx] _filename = video.title + \ str(stream.rawbitrate // 1000) + "."+stream.extension _filename = normalizeFilename(_filename) filepath_temp = os.path.join(settings.MEDIA_ROOT, _filename) stream.download(filepath=filepath_temp, quiet=True) sound = AudioSegment.from_file( os.path.join(settings.MEDIA_ROOT, _filename)) filepath_temp = os.path.join( settings.MEDIA_ROOT, _filename.replace("." + stream.extension, ".mp3")) sound.export(filepath_temp, format="mp3", bitrate=str(stream.rawbitrate // 1000) + "K") filepath_temp = "/media/" + \ _filename.replace("."+stream.extension, ".mp3") elif stream_type == 'audio': stream = video.audiostreams[idx] _filename = video.title + \ str(stream.rawbitrate // 1000) + "."+stream.extension _filename = normalizeFilename(_filename) filepath_temp = os.path.join(settings.MEDIA_ROOT, _filename) stream.download(filepath=filepath_temp, quiet=True) filepath_temp = "/media/" + _filename elif stream_type == 'video': stream = video.streams[idx] _filename = video.title + \ stream.resolution.split("x")[1]+"p" + "." + stream.extension _filename = normalizeFilename(_filename) filepath_temp = os.path.join(settings.MEDIA_ROOT, _filename) stream.download(filepath=filepath_temp, quiet=False) filepath_temp = "/media/" + _filename except Exception as e: print(e) return JsonResponse(status=400, data={'message': "could not find video/audio"}) return JsonResponse({'filepath': filepath_temp})
def __init__(self, bot): self.bot = bot self.client = None self.queue = [] try: self.token = import_module('secrets').youtube_key except NameError: self.token = environ['YOUTUBE_TOKEN'] pafy.set_api_key(self.token)
def set_new_key(): global current_api_key_index if current_api_key_index < len(const.config.youtube_api_keys): pafy.set_api_key(const.config.youtube_api_keys[current_api_key_index]) current_api_key_index = current_api_key_index + 1 return True else: return False
def __init__(self): # Set my YouTube API Key pafy.set_api_key("AIzaSyCnrbLP8V3zdMwG9kaTaCmeq49nNqyEpZ8") urllib.URLopener().retrieve("http://research.google.com/youtube8m/csv/train-labels-histogram.csv" , "labels.csv") #data variables self.sampleSeries = [] self.totalSeries = [] self.videoList = [] self.emptyFrames = [] self.tFrame = pd.DataFrame()
def __init__(self): self.queue = list() self.queue_index = -1 self.play_queue_order = list() self.play_modes = TizEnumeration(["NORMAL", "SHUFFLE"]) self.current_play_mode = self.play_modes.NORMAL self.now_playing_stream = None # Create multiprocess queues self.task_queue = Queue() self.done_queue = Queue() # Workers self.workers = list() pafy.set_api_key(API_KEY)
def get_results(q): results = [] qs = {'q': q, 'maxResults': 12, 'part': 'id,snippet'} pafy.set_api_key(os.environ['PAFY_API_KEY']) gdata = pafy.call_gdata('search', qs) with youtube_dl.YoutubeDL({'format': 'bestaudio/best'}) as ydl: for item in gdata['items']: try: result = {'extracted': False, 'id': item['id']['videoId'], 'title': item['snippet']['title']} results.append(result) except KeyError: pass return results
async def main(): from app.config.youtube import polling_rate, youtube_api_key, youtube_enabled logging.debug(f"Waiting for all other services to connect...") await asyncio.sleep(10 ) # sleep 10s to wait for rabbitmq server to go up async with create_client() as client: while True: [wait_time, api_key, enabled] = await asyncio.gather(polling_rate(), youtube_api_key(), youtube_enabled()) if not enabled: logging.info( f"YouTube module is disabled. Skipping detection loop." ) continue if api_key: pafy.set_api_key(api_key) logging.debug( f"YouTube module is enabled. Running YouTube detection loop." ) async for video in get_all_uploads(): logging.debug(f"Checking video '{video}' in uploads...") if not await is_new_video(video): logging.debug( f"Ignoring video '{video.title}' because it is not new." ) continue logging.info( f"New video '{video.title}' detected. Processing") await send_video( client, video, [ "new_video/discord", "new_video/podbean", "new_video/wordpress", ], ) await mark_video_as_processed(video) await asyncio.sleep(wait_time)
def main(args): """User-Agent will be set to 'github.com/jczhang/aurora' for transparency. Responses are cached to disk before parsing for troubleshooting and to prevent repeated requests. """ cache = args['--cache'] fresh = args['--fresh'] loglevel = args['--loglevel'] youtube_api_key = args['--youtube_api_key'] if youtube_api_key is not None: pafy.set_api_key(youtube_api_key) scraper = HooktheoryScraper(cache=cache, fresh=fresh, user_agent='github.com/jczhang/aurora', loglevel=loglevel) result = scraper.run(string.ascii_lowercase + string.digits) print(result)
def __init__(self): APIKEY = os.environ['APIKEY'] pafy.set_api_key(APIKEY) self.idx = 0 self.repeat = 0 self.autoplay = False self.status = 0 self.playList = [] self.isPsuse = False self.playlistText = [] self.statusChange = False self.mp = vlc.MediaPlayer() self.volumeControl = alsaaudio.Mixer() self.volume = int(self.volumeControl.getvolume()[0])
def check_api_key(key): """ Validate an API key by calling an API endpoint with no quota cost """ url = "https://www.googleapis.com/youtube/v3/i18nLanguages" query = {"part": "snippet", "fields": "items/id", "key": key} try: urlopen(url + "?" + urlencode(query)).read() message = "The key, '" + key + "' will now be used for API requests." # Make pafy use the same api key pafy.set_api_key(Config.API_KEY.get) return dict(valid=True, message=message) except HTTPError: message = "Invalid key or quota exceeded, '" + key + "'" return dict(valid=False, message=message)
def downloadVideo(videoLink): try: # Specifying an API key is optional # , as pafy includes one. However, # it is prefered that software calling pafy provides it’s own API key, # and the default may be removed in the future. pafy.set_api_key(yourApiKey) ytbVideo = pafy.new(videoLink) stream = ytbVideo.getbest(preftype="mp4") stream.download() print(ytbVideo.title, " downloaded...") except OSError: # if the video is labeled as private, then an error would occur and we won't be able to extract it pass
def __init__(self): ''' Objective : Initialize youtube API developer key, service name and version Input Parameter : - Return : - ''' developerKey = "Your Developer Key" youtubeApiServiceName = "youtube" youtubeApiVersion = "v3" pafy.set_api_key(developerKey) try: self.youtube = build(youtubeApiServiceName, youtubeApiVersion, developerKey=developerKey) except Exception as error: print(error)
def main(args): """User-Agent will indicate the source of the requests for transparency. Responses are cached to disk before parsing for troubleshooting and to prevent repeated requests. """ cache = args['--cache'] fresh = args['--fresh'] loglevel = args['--loglevel'] youtube_api_key = args['--youtube_api_key'] if youtube_api_key is not None: pafy.set_api_key(youtube_api_key) scraper = HooktheoryScraper(cache=cache, fresh=fresh, user_agent='github.com/caretcaret/aurora', loglevel=loglevel) result = scraper.run()
def ytdownloader(request): ytApiKey = settings.YT_API_KEY pafy.set_api_key(ytApiKey) video_url = request.GET['video_url'] try: video = pafy.new(video_url) except: context = {'error': "invalid url"} return render(request, 'youtube_from.html', context) video_audio_streams = [ { 'resolution': s.resolution.split("x")[1] + "p", # 360p,720p.. 'extension': s.extension, 'file_size': filesizeformat(s.get_filesize()), 'video_url': s.url + "&title=" + video.title } for s in video.streams ] audio_streams = [ { 'bitrate': s.rawbitrate // 1000, # bps -> kbps 'extension': s.extension, 'file_size': filesizeformat(s.get_filesize()), 'video_url': s.url + "&title=" + video.title } for s in video.audiostreams ] context = { 'streams': video_audio_streams, 'audio_streams': audio_streams, 'meta': { 'title': video.title, 'thumb': video.bigthumbhd.replace("http://", "https://"), 'duration': video.duration, 'published': video.published, 'viewcount': video.viewcount, 'videoid': video.videoid } } return render(request, 'download.html', context)
def pafy_download(url): if not url: url = "https://www.youtube.com/watch?v=-z4NS2zdrZc" # Here is to the Crazy Ones pafy.set_api_key("AIzaSyD5Q22HSOEJKYaNkObyb_38o_gLx24qu5Y") video = pafy.new(url) # print(f"videoid: {video.videoid}") # print(f"title: {video.title}") # print(f"description: {video.description}") # print(f"thumb: {video.thumb}") # print(f"duration: {video.duration}") # print(f"length: {video.length}") # print(f"author: {video.author}") # print(f"published: {video.published}") # print(f"rating: {video.rating}") # print(f"view count: {video.viewcount}") # print(f"likes: {video.likes}") # print(f"dislikes: {video.dislikes}") # print(f"keywords: {video.keywords}") download = VideoEpisode(title = video.title, description = video.description, subtitle = video.description, summary = htmlencode(video.description), video_id = video.videoid, author = video.author, image_url = video.thumb, published = video.published, keywords = video.keywords, media_size = globals()['filesize'], media_duration = video.length, position = 0, media_url = "https://cdn.listenbox.app/a/u4diDOUjKM4.m4a" ) print(download) create_rss(type="feed.xml", download=download)
def __init__(self,config): self.client=mpd.MPDClient(use_unicode=True) pafy.set_api_key(config['APIkey']) self.mhost=config['mpd host'] self.mport=config['mpd port'] self.client.connect(self.mhost,self.mport) self.client.clear() self.client.timeout=30 self.client.consume(1) self.playlist=[] self.alt=None self.loading=False self.update() self.playlistUp=threading.Thread(target=self.playlistSub) self.playlistUp.daemon=True self.playlistUp.start() self.statusUp=threading.Thread(target=self.statusSub) self.statusUp.daemon=True self.statusUp.start()
def main(arguments): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-y', '--youtube', help="YouTube Data API key") parser.add_argument('dir', help="Dataset directory", action=WriteableDir, default='.') args = parser.parse_args(arguments) api_key = args.youtube pafy.set_api_key(api_key) dataset_dir = args.dir run(dataset_dir)
def __init__(self): super(YoutubeSkill, self).__init__(name="YoutubeSkill") self.nextpage_url = None self.previouspage_url = None self.live_category = None self.recentList = deque() self.recentPageObject = {} self.nextSongList = None self.lastSong = None self.videoPageObject = {} self.isTitle = None self.newsCategoryList = {} self.musicCategoryList = {} self.techCategoryList = {} self.polCategoryList = {} self.gamingCategoryList = {} self.searchCategoryList = {} self.storeDB = dirname(__file__) + '-recent.db' self.recent_db = JsonStorage(self.storeDB) self.ytkey = base64.b64decode("QUl6YVN5RE9tSXhSemI0RzFhaXFzYnBaQ3IwQTlFN1NrT0pVRURr") pafy.set_api_key(self.ytkey)
def __init__(self, youtube_playlist_url, youtube_api_key, song_info_enabled=True): pafy.set_api_key(youtube_api_key) self.playlist = pafy.get_playlist2( youtube_playlist_url) # Pafy playlist object self.song_index = 0 # Current song index self.song_counter = 0 # Stores how many songs have been played, resets if every song has been played. self.total_songs = len( self.playlist) # Amount of songs in the Pafy object self.current_song = None # Stores the current song os.environ[ "VLC_VERBOSE"] = "-1" # Decrease verbosity of VLC error output, necessary because errors sometimes occur that spam the screen but otherwise have no effect self.vlc_player = vlc.MediaPlayer() # Stores the VLC object self.song_info_enabled = song_info_enabled # The current song information is printed when the song changes if this is enabled self.song_history = [] # Stores indexes of songs that have been played # User input self.cmds = CommandHandler( self) # Collects user input on another thread
#!/usr/bin/env python # coding:utf-8 # Copyright (C) dirlt import config as CF import string import pprint import urllib2 import traceback import os import re import pafy pafy.set_api_key(CF.YOUTUBE_API_KEY) import gevent # gevent.queue import urlparse def parse_videos_csv(fname='videos.tsv'): with open(fname) as fh: lines = map(lambda x: x.strip(), fh.readlines()) fields = lines[0].split('\t') records = [] for line in lines[1:]: if line.startswith('#'): continue item = line.split('\t') record = {} lessons = [] labels = [] record['lessons'] = lessons
) print (sys.argv) titulo = sys.argv[1] cuerpofoto = sys.argv[2] if titulo == "sync" and cuerpofoto == "videos": # videos videos = client.posts("perunalainen", type="video", limit=20) videos_list = videos['posts'] last_10 = [] for video in videos_list: last_10.append(video["permalink_url"][-11:]) pafy.set_api_key(youtube_key) v = "https://www.youtube.com/playlist?list=PL7rxKO9f1bIguuo1dPQRFu7bIr3eqFcij" playlist = pafy.get_playlist(v) tot = len(playlist['items']) count = 0 ids = [] while count < tot: objeto = playlist['items'][count]['playlist_meta']['encrypted_id'] ids.append(objeto) count = count + 1 for v in ids: if v in last_10: print "all sync" else: client.create_video('perunalainen', embed="https://www.youtube.com/watch?v="+v)