示例#1
0
def query():
  query = {
    'q': 'Honorable Minister Louis Farrakhan',
    'max_results': '200',
    'videoDuration': 'long',
    'type': 'video'
  }
  search.youtube_search(query)
示例#2
0
def youtube_download_by_keyword(keyword, max_results):
    videos, _, _ = youtube_search(keyword, max_results)
    print("Videos:\n", "\n".join(map(lambda x: x.split('\t')[0], videos)))
    for video in videos:
        ID = video.split('\t')[1]
        query = 'https://www.youtube.com/watch?v=' + ID
        youtube_download_by_url(query)
示例#3
0
def upload():
    if request.method == "POST":
        query = request.form.get("search_term")
        res = youtube_search(query)

    return render_template('index.html',
                           tables=[res.to_html(classes="table_color")])
示例#4
0
def grab_videos(keyword, token=None):
    res = search.youtube_search(keyword, max_results=50, token=token)
    token = res[0]
    videos = res[1]
    video_dict = {}

    for video_data in videos:
        # print(json.dumps(video_data, indent=4, sort_keys=True))
        video_id = video_data['id']['videoId']
        video_title = video_data['snippet']['title']
        video_dict[video_id] = video_title
    print("search returned " + str(len(videos)) + " videos")
    return token, video_dict
def HandleSongRequest():
#	Search for the song
	results=search.youtube_search(request.values.get('Body', None))
	id=results[0]
	title=results[1]
	filename=id+".m4a"	

#	Download the song
	call(['youtube-dl','-o',filename,'-x',id])
			
#	Play the song
	call(['omxplayer',filename])
	
#	Delete the file
	call(['rm',filename])		
def play_audio(s_words, v_type):
  logging.debug('play_audio()')
  logging.debug('search words are: ' + s_words)
  logging.debug('v_type is: ' + v_type)
  
  #Search words on Youtube
  logging.info('Search audio request: '+ s_words)
  result, title = search.youtube_search(s_words, v_type)
 
  if result:
      global player
      player = mpv.MPV(ytdl=True, vid=False)
      
      # Play only audio stream from the playlist results
      if v_type == 'playlist':
          logging.debug('Result search\n' + '\n'.join(result))
          n=0
          while n<len(result):
              player.playlist_append(result[n])
              n += 1
          player.playlist_pos = 0
          player.loop_playlist = '1'
          # Vocalise and play result found
          synth_mp3.synth_mp3_file("Résultat trouvé. La compilation " + title + " est en cours de lecture...")
          #synth_mp3.synth_mp3_file("Ma petite Maryam...tu es très belle et tu as de jolis cheveux")
          logging.info('Vocalise audio result')

          # Play only audio stream from the vids results
          logging.info('Play playlist results')
          player.playlist
          #player.playlist_next('weak')
          return

      logging.debug('Result search : ' + result)
      
      # Vocalise and play result found
      logging.info('Vocalise audio result')
      synth_mp3.synth_mp3_file("Résultat trouvé. L'Audio " + title + " est en cours de lecture...")
      #synth_mp3.synth_mp3_file("Ma petite Maryam, tu es très belle et tu as de jolis cheveux")

      # Play only audio stream from the vids results      
      logging.info('Play audio result')
      player.play(result)
from search import youtube_search
# arguments to be passed to build function
DEVELOPER_KEY = "AIzaSyBamznAT1rjDBvppZ3ws8tcf5jViLLMbYw"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

# creating youtube resource object for interacting with API
youtube = build(YOUTUBE_API_SERVICE_NAME,
                YOUTUBE_API_VERSION,
                developerKey=DEVELOPER_KEY)

i = 0
result = []

if __name__ == "__main__":
    id1 = youtube_search("Justin Bieber Baby")
    print len(id1)
    for vid_id in id1:
        result.append(get_comment_threads(youtube, vid_id))
        fileName = "file" + str(i) + ".txt"
        f = open(fileName, 'w+')
        for j in range(0, len(result[i])):
            f.write(result[i][j].encode('ascii', 'ignore'))

        payload = {
            'id': search_result["id"]["videoId"],
            'part': 'contentDetails,statistics,snippet',
            'key': DEVELOPER_KEY
        }
        1 = requests.Session().get(
            'http://www.googleapis.com/youtube/v3/videos', params=payload)
示例#8
0
import os
import search
import time

if __name__ == "__main__":
    try:
        want = "huaweigt"
        your_dir = "/home/yangxiaoyu/youtube_download"
        result = {}
        search_option = {
            "q": want,
            "max_results": "2"
        }
        #获取到所有的 'Videos'  'Channels'  'Playlists' 信息
        result = search.youtube_search(search_option)
        VideosList = result['Videos']
        ChannelsList = result['Channels']
        Playlists = result['Playlists']

        #构造downloadID
        download_link = "https://youtu.be/"
        for i in VideosList:
            i['videoId'] = download_link + i['videoId']

        #for i in VideosList:
        #    print('video_title:'+i['video_title']+":\nvideoId:"+i['videoId']+"\n");

        if not os.path.exists(your_dir):
            os.makedirs(your_dir)

        today_dir = your_dir + "/" + want + "/" + time.strftime(
示例#9
0
    postest_feats = [(bag_of_words(positive_review), 'pos')
                     for positive_review in positive_reviews]
    test_neg = len(negtest_feats)
    test_pos = len(postest_feats)
    testfeats = negtest_feats[:test_neg] + postest_feats[:test_pos]

    while (flag == 1
           ):  #this flag is set so that user gets option to pass another query
        i = 0  #i is set for indexing the 10 extracted videos
        result = [
        ]  #double dimensional array to store 100 comments of each video
        pos_neg_list = [
        ]  #this list stores the positive and negative counts of all 10 videos as a tuple
        query = raw_input('enter a query word:')
        (vid_ids,
         vid_titles, vid_likes, vid_dislikes, comment_count) = youtube_search(
             query)  #youtube_search function returns five parameters
        print("no. of videos", len(vid_ids))

        nb_classifier = NaiveBayesClassifier.train(trainfeats)
        #nb_precisions, nb_recalls= precision_recall(nb_classifier, testfeats)

        refsets = collections.defaultdict(set)
        testsets = collections.defaultdict(set)
        for i, (feats, label) in enumerate(testfeats):
            refsets[label].add(i)
            observed = nb_classifier.classify(feats)
            testsets[observed].add(i)

        print("Accuracy:", nltk.classify.accuracy(nb_classifier, testfeats))
        print("Positive Precision:", precision(refsets['pos'],
                                               testsets['pos']))
示例#10
0
def getVideos():
    query = request.form['query']
    titles, vidids = youtube_search(query);
    return jsonify([titles, vidids])
示例#11
0
def test_youtube_search(capsys):
    search.youtube_search('Google', 25)

    out, _ = capsys.readouterr()

    assert 'Google' in out
示例#12
0
def response(voice_data, q, n):
    try:
        import main
        if main.run == True or main.crun == True:
            import random #used for random
            import speaker

            # 1: greeting and convos
            if main.person_says(["hey","hi","hello"]):
                counters()
                greeting = ["hey, how can I help you " + main.person_obj.name, "hey, what's up? " + main.person_obj.name, "I'm listening " + main.person_obj.name, "how can I help you? " + main.person_obj.name, "hello " + main.person_obj.name]
                greet = greeting[random.randint(0,len(greeting)-1)]
                q.put(main.asis_obj.name + ": " + greet + "\n")
                speaker.speech_output(greet)

            elif main.person_says(["good morning","good evening","good afternoon","good noon", "goodnight"]):
                counters()
                import times
                times.greeter(q) 

            elif main.person_says(["how are you","what's up"]):
                counters()
                treating = ["I am doing great, " + main.person_obj.name + ". How are you?", "I am fine, " + main.person_obj.name + ". What about you?", "I'm listening to you, " + main.person_obj.name + ". Do you need some help?"]
                treat = treating[random.randint(0,len(treating)-1)]
                q.put(main.asis_obj.name + ": " + treat + "\n")
                speaker.speech_output(treat)

            elif main.person_says(["you're nice", "fine", "i'm good", "thank you", "thanks", "thankyou", "alright"]):
                counters()
                replying = ["That's nice to hear.", "I am happy to hear that.", "I am glad to hear that."]
                reply = replying[random.randint(0,len(replying)-1)]
                q.put(main.asis_obj.name + ": " + reply + "\n")
                speaker.speech_output(reply)

            elif main.person_says(["joke","jokes", "make me laugh"]):
                counters()
                replying = ["Why don't scientists trust atoms? Because........ they make up everything! hehe", "Why doesn't the sun go to college? ..... Because it has a million degrees! buhahaha",
                            "I have many jokes about unemployed people..... sadly none of them work. lol",
                            "What do you call a singing laptop?...... Its A Dell!",
                            "Some people think prison is one word......... but to robbers it's the whole sentence.",
                            "Why couldn't the leopard play hide and seek?...............Because he was always spotted. lol",
                            "I needed a password eight characters long..............So I picked Snow White and the Seven Dwarves. Buhahaha"]
                reply = replying[random.randint(0,len(replying)-1)]
                q.put(main.asis_obj.name + ": " + reply + "\n")
                speaker.speech_output(reply)

            # 2: naming each other and name changes
            elif main.person_says(["what is your name","what's your name","tell me your name"]):
                counters()
                import names
                names.chatbot_name(q)

            elif main.person_says(["what is my name","what's my name","tell me my name"]):
                counters()
                import names
                names.user_name(q)

            elif main.person_says(["change my name"]):
                counters()
                import names
                names.change_name(q)
    
            # 3: quitting program
            elif main.person_says(["exit", "quit", "goodbye", "bye", "bye bye"]):
                counters()
                q.put(main.asis_obj.name + ": " + "Bye! I will miss you! " + main.person_obj.name + "\n")
                speaker.speech_output("Bye! I will miss you! " + main.person_obj.name)
                import sys #used for exiting the program
                try:
                    sys.exit(0)
                except SystemExit as e:
                    sys.exit(e)

            # 4: ask time
            elif main.person_says(["what's the time", "what is the time", "what is current time", "tell me the time","what time"]):
                counters()
                import times
                times.time_speaker(q)

            elif main.person_says(["what's the date", "what is the date", "what is today's adte", "tell me the date","what date"]):
                counters()
                import times
                times.date_speaker(q)
    
            # 5: search google
            elif main.person_says(["search for", "search"]) and 'youtube' not in main.voice_data and 'weather' not in main.voice_data and 'price' not in main.voice_data:
                counters()
                import search
                search.google_search(q)

            # 6: search youtube
            elif main.person_says(["youtube"]):
                counters()
                import search
                search.youtube_search(q)

            #7 rock paper scisorrs
            elif main.person_says(["game"]) and n == 1:
                counters()
                import game
                game.game_rps(q)

            #8 screenshot
            elif main.person_says(["capture my screen","screenshot"]):
                counters()
                import pyautogui #used for screenshot
                myScreenshot = pyautogui.screenshot()
                myScreenshot.save('D:/screen.png')
                speaker.speech_output("The screen has been captured and placed in drive D as screen.png")

            #9 calculation
            elif main.person_says(["plus","minus","multiply","divide","power","+","-", "x", "*","/", "add", "subtract"]):
                counters()
                import calc
                calc.calculate(q)

            #10: search prices of items
            elif main.person_says(["price of", "price for", "price"]):
                counters()
                import search
                search.price_search(q)

            #11 weather
            elif main.person_says(["weather"]):
                counters()
                import search
                search.weather_search(q)

            #12 definitions
            elif main.person_says(["definition", "definitions", "what is"]):
                counters()
                import search
                search.definitions(q)

            #13 Go background
            elif main.person_says(["go to background", "goto background", "go background"]):
                counters()
                import background
                import speaker
                q.put(main.asis_obj.name + ": " + "I'm going background. Call my name if you need help." + "\n")
                speaker.speech_output("I'm going background. Call my name if you need help.")
                main.brun = True
                background.background_loop(q)

            #14 opening apps
            elif main.person_says(["app", "application"]):
                counters()       
                import apps
                apps.open_app()

            #15 play songs
            elif main.person_says(["sing me a song", "play a song", "play song"]):
                counters()
                from playsound import playsound
                playsound('song/song.mp3')        

            else:
                if main.error_count0 == main.error_count:
                    main.empty_count += 1
                    #print("RE Non-Related = " + str(main.empty_count))

                if main.empty_count > 3:
                   counters()
                   import speaker
                   q.put(main.asis_obj.name + ": " + "I'm going background. Call my name if you need help." + "\n")
                   speaker.speech_output("I'm going background. Call my name if you need help.")
                   import background
                   main.brun = True
                   background.bg_play(q)
                main.error_count0 = main.error_count
    except:
        pass
示例#13
0
    # 0:月曜日,プレイリストのリセットは1,-1を入れて実行
    0: [0],
    1: [1],
    2: [2],
    3: [1],
    4: [3],
    5: [1],
    6: [4],
    -1: [1]
}

#今日の曜日を取得
weekday = datetime.date.today().weekday()
weekday_name = calendar.day_name[weekday]
print(weekday_name)

for category in weekday_categories[weekday]:  #今日更新するプレイリストの番号
    #更新前のプレイリストを全削除
    Items = search_playlistitems(ids[category])
    for resourceId in Items:
        reset_playlist(resourceId)
    #カラオケランキングを取得
    titles, artists = get_karaokerank(url=urls[category],
                                      video_num=video_nums[category])
    #youtbeで動画を検索
    for rank in range(len(titles)):
        videoid = youtube_search(video_title=titles[rank] + artists[rank])
        #プレイリストに追加
        if videoid is not None:
            insert_resource(ids[category], videoid)