def get_url(MSD, api_key, history, similar_lst): api = yapi.YoutubeAPI(api_key) query = [] for sim in similar_lst: song_id = sim[0] title, artist = MSD[song_id]['title'], MSD[song_id]['artist'] query.append('{0} {1}'.format(title, artist)) urls = [] for q in query: status = history.get(q, 0) if status: result = history[q] else: while 1: i = 0 try: x = api.video_search(q, max_results=1) break except Exception as e: print('Error : {0} . Sleeping for {1} seconds'.format( e, 2**i)) i += 1 sleep(2**i) result = [ v['videoId'] for v in [vars(z['id']) for z in [vars(y) for y in vars(x)['items']]] ][0] urls.append(result) history[q] = result return history, urls
def fetch_youtube_metadata_for_songs(songs): updated_songs = [] unmodified_songs = songs youtube_ids = [song['youtube_id'] for song in songs if song.get('youtube_id')] max_ids_per_query = 50 id_chunks = [youtube_ids[x:x + max_ids_per_query] for x in range(0, len(youtube_ids), max_ids_per_query)] video_items = [] for ids in id_chunks: try: api = yapi.YoutubeAPI(settings.YOUTUBE_API_KEY) video_items = video_items + api.get_video_list_info(ids).items except AttributeError as e: raise Exception( 'Unable to query Youtube API. Possibly over quota.') for item in video_items: metadata = song_metadata_from_youtube_video_item(item) song = [song for song in unmodified_songs if song.get( 'youtube_id') == metadata.get('youtube_id')][0] updated_songs.append( update_song_with_metadata_dict(song, metadata)) unmodified_songs.remove(song) return updated_songs + unmodified_songs
def get_api(self): result = None self.current_api_num += 1 values = self.api_key_dict.values() if self.current_api_num < len(values): result = yapi.YoutubeAPI(values[self.current_api_num]) print "change_to_api:" + values[self.current_api_num] return result
def main(): input_file = sys.argv[1] output_file = sys.argv[2] api_key = readfile(sys.argv[3])[0] channel_names = readfile(input_file) api = yapi.YoutubeAPI(api_key) all_videos = [x for x in list(get_all_channel_videos(api, channel_names)) if len(x) > 0] all_videos = np.concatenate(all_videos) df = pd.DataFrame(all_videos) df.columns = ["video_id", "video_title", "description", "tags", "channel", "thumbnail"] df.to_csv(output_file, index=False)
def test_song_metadata_from_youtube_video_item_returns_valid_metadata_dict(self): example_yt_id = 'hQVTIJBZook' example_video_item = None try: api = yapi.YoutubeAPI(settings.YOUTUBE_API_KEY) example_video_item = api.get_video_info(example_yt_id).items[0] except AttributeError as e: raise Exception( 'Unable to query Youtube API. Possibly over quota.') result = fetch_songs.song_metadata_from_youtube_video_item( example_video_item) self.assertEqual(result['youtube_id'], example_yt_id)
def search(bot, update): DEVELOPER_KEY = 'AIzaSyDGRbEc7qbGJ59Vsv68fL0aHml1FYpX_1g' import yapi api = yapi.YoutubeAPI(DEVELOPER_KEY) keyword = update.message.text.split('/search')[1] print(keyword) results = api.general_search(keyword, max_results=5) import json results = json.loads(results) result = '' global id id = '' for i in range(5): result += str(i) + " - " + results['items'][i]['snippet']['title'] + " \n \n" id += results['items'][i]['id']['videoId'] + " \n" print(result) bot.send_message(chat_id=update.message.chat_id, text=result) bot.send_message(chat_id=update.message.chat_id, text='Você quer baixar o video? Qual resultado quer baixar?\nDigite Sim (e o número que deseja)\nExemplo: Sim 5')
#!/usr/bin/python3 import time, colorama, os, pickle, sys, yapi, youtube_dl data = "download.data" api = yapi.YoutubeAPI("AIzaSyAJMzX_t_tRoiSBs7-PS8eSnn6wdK9L1Us") try: with open(data, "rb") as file: directory2 = pickle.load(file) dire = True print(directory2) except: dire = False colorama.init def start(): print(colorama.Fore.WHITE + "Youtube downloader") time.sleep(1) print(colorama.Style.RESET_ALL) print(colorama.Fore.RED + "By Blinc") print("version 1.9:") print(colorama.Fore.BLUE + "Канкатенация решает") print(colorama.Style.RESET_ALL) def dir(): if dire == False: try: directory = input("Папка: ") what = input("Запомнить дерикторию ? (y/n): ") if what == "y": with open(data, "wb") as file:
def authenticate(api_key): api = yapi.YoutubeAPI(api_key) return api
import datetime import yapi from flask import Blueprint, render_template, request from flask_security import current_user, login_required from app import db from config import api_key from models import Inquiry, User search = Blueprint('search', __name__, template_folder='templates') api = yapi.YoutubeAPI(api_key) @search.route("/") @login_required def search_videos(): q = request.args.get('q') videos_id_list = [] if q: user = current_user inquiry = Inquiry( body=q, timestamp=datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), user_id=user.id) db.session.add(inquiry) db.session.commit()
def Video_to_frame(self, MainWindow): while True: url = "https://www.youtube.com/watch?v=WwjUv4uuFn0" api = yapi.YoutubeAPI('') video_name="" results = api.general_search(video_name, max_results=2) str_results=str(results) i=0 TrueOrFalse=False video_id="" while True: try : if "'" in str_results[i]: if "=" in str_results[i-1]: if "d" in str_results[i-2]: if "I" in str_results[i-3]: if "o" in str_results[i-4]: i=i+1 TrueOrFalse=True break i=i+1 except IndexError as e: print("error") break while TrueOrFalse: if "'" in str_results[i]: break else : video_id=video_id+str_results[i] i=i+1 url = url+video_id try : vPafy = pafy.new(url) self.video_name_label.setText(vPafy.title) video_length=vPafy.length/60 except Exception as e : self.video_viewer_label.setText("Error") self.start=False print(video_length/60) play = vPafy.getbest(preftype="mp4") cap = cv2.VideoCapture(play.url) while self.start: self.ret, self.frame = cap.read() if self.ret: self.rgbImage = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB) self.convertToQtFormat = QImage(self.rgbImage.data, self.rgbImage.shape[1], self.rgbImage.shape[0], QImage.Format_RGB888) self.pixmap = QPixmap(self.convertToQtFormat) self.p = self.pixmap.scaled(400, 225, QtCore.Qt.IgnoreAspectRatio) self.video_viewer_label.setPixmap(self.p) self.video_viewer_label.update() sleep(0.0001) #Youtube 영상 1프레임당 0.0001초 else : break if self.start_or_stop: break cap.release() cv2.destroyAllWindows()