Beispiel #1
0
def refreshGraphData(i):
	
	global happyCounter, sadCounter, happy, player, onPlay
	print("Refreshing Data.....")
	graphData = open("emotiondata.csv", "r").read()
	lines = graphData.split("\n")[-200:]
	xValues = []
	yValues = []
	faceIds = []
	smile = []
	
	
	for line in lines[1:]:
		happycounter = 0
		if len(line) > 1:
			cols = line.split(",")
			x = float(cols[0])  # Time
			y = float(cols[11]) # Joy
			fid = cols[1] # face ID
			sm = float(cols[20])
			xValues.append(x)
			yValues.append(y)
			faceIds.append(fid)
			smile.append(sm)
	
		
	#print(eyeClosure[-1])
	
	#deal with joy using counters
	if(faceIds[-1]!="nan"):
		if(onPlay==False):
			player = vlc.MediaPlayer(tracks[random.randint(0,3)])
			player.play()
			onPlay = True
		#print(eyeClosure[-2])
		if((yValues[-1] > 30) | (smile[-1] > 30)):   #Happy when Joy or smile, sad otherwise
			happyCounter += 1
			sadCounter = 0
		else:
			sadCounter += 1
			happyCounter = 0
		print("Happy: ",happyCounter)
		print("Sad: ", sadCounter)	
		if(happyCounter==15):
			if(happy==False):
				#call change/play/stop music a + aroma for happiness suggestion here 
				player.stop()
				player = vlc.MediaPlayer(tracks[random.randint(0,1)]) # play happy track randomly 0,1
				player.play()
				onPlay = True
				happy = True
				print("Changing to Happy Track")
				popmessage(aroma[random.randint(0,1)]) # suggest Aroma
				
			happyCounter = 0 # restart the counter when a person is already happy

		if(sadCounter==100):
			if(happy):
				#call change/play/stop music a + aroma for sadness suggestion here
				player.stop()
				player = vlc.MediaPlayer(tracks[random.randint(2,3)])
				player.play()
				onPlay = True
				happy = False
				print("Changing to Sad Track")
				popmessage(aroma[random.randint(2,3)]) # suggest Aroma

			sadCounter = 0 # restart the counter when a person is already sad
	else:
		player.stop()
		onPlay = False
Beispiel #2
0
import vlc
import time
from src.common.log import *

love = vlc.MediaPlayer("assets/sound/dingDong.mp3")
finishHim = vlc.MediaPlayer("assets/sound/finishHim.mp3")
mortalKombat = vlc.MediaPlayer("assets/sound/mortalKombat.mp3")
heroes = vlc.MediaPlayer("assets/sound/heroes.mp3")

if __name__ == "__main__":
    log.debug("sound running as main")
    mortalKombat.play()
    time.sleep(60)
Beispiel #3
0
 def __init__(self, **kwargs):
     self.player = vlc.MediaPlayer(settings.MUSIC)
     self.paused = True
     self.pause_time = 0
     self.initialized = False
     super().__init__(**kwargs)
def soundHello():
    p = vlc.MediaPlayer("attention.wav")
    r = "..."
    p.play()
    return r
import threading
import thread
import pygame
from tkFileDialog import askdirectory
from subprocess import call
import vlc

top = tk.Tk()  # take window
w = 800
h = 600
wscreen = top.winfo_screenwidth()
hscreen = top.winfo_screenheight()
x = (wscreen / 2) - (w / 2)  #set location of window to middle of screen
y = (hscreen / 2) - (h / 2)
top.geometry('%dx%d+%d+%d' % (w, h, x, y))
player = vlc.MediaPlayer("")

pygame.init()
pygame.mixer.init()
set = 0
playTill = 0  # just a flag
filename = ""
file = ''  #example
dirname = "/home/${USER}/"


def music(file):
    print file
    pygame.mixer.music.load(
        file)  # you can refer to https://www.pygame.org/docs/ref/music.html
    pygame.mixer.music.play()
def sound1():
    r = " "
    p1 = vlc.MediaPlayer("attention.wav")
    p1.play()
    return r
def sound3():
    r = " "
    p3 = vlc.MediaPlayer("crazy.wav")
    p3.play()
    return r
Beispiel #8
0
def play(id):
    """ Function to handle media player selection """
    is_found = False  # Is stream ID found?
    radio = False
    with open('links.txt') as f:
        for line in f:
            if line.startswith(id):
                link = line.split()
                url = link[2]
                is_found = True
                if (link[3] == 'r'):
                    radio = True
                else:
                    url = get_latest_episode_url(url, id)
    if (not (is_found)):
        print('\nInvalid Input!\n')
        main_menu()

    if (not (radio)):
        choice = input("\nDo you want to play this episode?(y/n): ")
        if (choice == 'n'):
            main_menu()
    player = vlc.MediaPlayer(url)
    player.play()

    try:
        while True:
            print("\nPlaying Audio Track...\n")
            print("~~Media Player Controls~~")
            print("p - Pause")
            print("c - Continue")
            print("s - Seek")
            print("i - Information about current track")
            print("m - Go back to main menu")
            print("l - See track lyrics")
            print("w - Write track information to file")
            print("q - Quit")
            i = input("\nEnter Choice: ")
            if i == 'p':
                player.pause()
                print("Current runtime percentage : ",
                      round(player.get_position() * 100, 2), "%")
            elif i == 'c':
                player.play()
            elif i == 'm':
                player.stop()
                main_menu()
            elif i == 's':
                player.pause()
                s = input("Enter seek position between 0 and 1.0 : ")
                player.set_position(float(s))
                player.play()
            elif i == 'i':
                try:
                    artist, track = get_media_info(player)
                    print("\nCurrent playing track -" + track + " by " +
                          artist)
                except:
                    print("Could not find media information")
            elif i == 'l':
                try:
                    artist, track = get_media_info(player)
                    print("~~~ Song Lyrics ~~~\n")
                    print(lyricwikia.get_lyrics(artist, track))
                    print("~~~~~~~~~~~~~~~~~~~\n")
                except:
                    print("Could not find lyrics")
            elif i == 'w':
                with open("Tracks_list.txt", "a+") as f:
                    ts = time.time()
                    f.write(media.get_meta(12))
                    f.write(" | ")
                    f.write(
                        datetime.datetime.fromtimestamp(ts).strftime(
                            '%Y-%m-%d %H:%M:%S'))
                    f.write("\n")
                f.close()
                print("\nWritten current running track information to file..")
            elif i == 'q':
                print("\nStopped playing the streaming station\n")
                player.stop()
                sys.exit()
    except KeyboardInterrupt:
        print("Stopped playing the streaming station")
        player.stop()
        sys.exit()
Beispiel #9
0
# importing vlc module
import vlc

# importing pafy module
import pafy

# url of the video
url = "https://www.youtube.com/watch?v=L5jI9I03q8E&list=RDL5jI9I03q8E&start_radio=1"

# creating pafy object of the video
video = pafy.new(url)

# getting best stream
best = video.getbest()

# creating vlc media player object
media = vlc.MediaPlayer(best.url)

# start playing video
media.play()
Beispiel #10
0
def playMel():
    global curMel, lenInterval
    for i in curMel:
        p = vlc.MediaPlayer('notes/' + i + ".mp3")
        p.play()
        time.sleep(float(lenInterval.get()))
Beispiel #11
0
import cv2
import sys
import vlc
from fastai.vision import *

model = load_learner(path='.', file='export.pkl')
face_cascade = cv2.CascadeClassifier('face.xml')
sound_path = './police.mp3'
sound = vlc.MediaPlayer(sound_path)
sound_playing = False
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 960)  #1280, 640
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 544)  #720, 480

while (True):
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.2, 5)  #detect faces
    no_masks = []
    for (x, y, w, h) in faces:
        sub_img = gray[y:y + h, x:x +
                       w]  #take part of image that contains the face only
        cv2.imwrite('to_be_deleted.jpg',
                    sub_img)  #save part of image that contains the face only
        img = open_image('to_be_deleted.jpg')  #load face image for prediction
        pred = model.predict(img)  # predict
        no_mask = pred[0].data.item() == 0
        no_masks.append(no_mask)
        mask_label = 'No Mask! :(' if no_mask else 'Mask ON :)'
        color = (0, 0, 255) if no_mask else (0, 255, 0)
        cv2.rectangle(frame, (x, y), (x + w, y + h), color,
Beispiel #12
0
    def __init__(self, master):

        # 视频和音频区域
        frame = Frame(master)
        frame.pack(side=RIGHT, fill=BOTH, expand=YES)

        frame1 = Frame(master)
        # frame1 = Frame(master,bg="gray")
        frame1.pack(side=LEFT, fill=BOTH, expand=YES)

        self.pwd = os.getcwd()

        self.pauseFlag = False

        # 获取PC机本地IP
        self.local_ip = "192.168.1.5"
        """
        播放画面区域 bg="Gainsboro"
        """

        self.lab_tmp = Label(frame1,
                             text="",
                             width=1,
                             fg="black",
                             font=("宋体", 12, "bold"),
                             justify="left")
        self.lab_tmp.grid(row=0, column=0, rowspan=1, sticky=W)

        self.show_video = Text(frame1,
                               width=150,
                               height=40,
                               wrap=WORD,
                               bd=3,
                               bg="white")
        self.show_video.grid(row=15,
                             column=1,
                             rowspan=1,
                             columnspan=3,
                             sticky=W)
        self.show_video.insert(END, "等待视频播放")
        self.media = vlc.MediaPlayer()

        self.bt_play = Button(
            frame1,
            text="视频播放",
            command=lambda: self.play_button(self.file_path, self.p_path),
            bd=2,
            width=49)
        self.bt_play.grid(row=16, column=1, rowspan=1, sticky=W)

        self.bt_pause = Button(
            frame1,
            text="视频暂停",
            command=lambda: self.pause_media(button=self.media),
            bd=2,
            width=48)
        self.bt_pause.grid(row=16, column=2, rowspan=1, sticky=W)

        self.bt_stop = Button(frame1,
                              text="视频停止",
                              command=lambda: self.stop_play_vlc(),
                              bd=2,
                              width=49)
        self.bt_stop.grid(row=16, column=3, rowspan=1, sticky=W)

        self.file_path = ''
        self.p_path = ''
        self.name = ''

        global e
        e = StringVar()

        if "Windows" == platform.system():
            # 主子设备视频播放
            self.media.set_hwnd(self.show_video.winfo_id())
        else:
            print("错误", "不支持此平台!")
            exit(-1)

        self.bt_play = Label(frame, text="")
        self.bt_play.grid(row=0, sticky=W)
        self.entry = Entry(frame, textvariable=e, bd=2, width=23)
        self.entry.grid(row=1, column=1, rowspan=1, sticky=W)
        e.set('请先进行语音分析')
        self.bt_play = Button(frame,
                              text="搜索",
                              command=lambda: self.search(self.p_path),
                              bd=2,
                              width=4)
        self.bt_play.grid(row=1, column=2, rowspan=1, sticky=W)

        self.bt_play = Button(frame,
                              text="打开文件",
                              command=lambda: self.fn_open_file(),
                              bd=3,
                              width=30)
        self.bt_play.grid(row=2, column=1, rowspan=1, columnspan=2, sticky=W)

        self.bt_open = Button(frame,
                              text="语音分析",
                              command=lambda: self.speech(self.file_path),
                              bd=3,
                              width=30)
        self.bt_open.grid(row=3, column=1, rowspan=1, columnspan=2, sticky=W)

        self.bt_stop = Button(frame,
                              text="敏感词审核",
                              command=lambda: self.nlpir(self.p_path),
                              bd=3,
                              width=30)
        self.bt_stop.grid(row=4, column=1, rowspan=1, columnspan=2, sticky=W)

        self.bt_stop = Button(frame,
                              text="获得知识点",
                              command=lambda: self.textrank(self.p_path),
                              bd=3,
                              width=30)
        self.bt_stop.grid(row=5, column=1, rowspan=1, columnspan=2, sticky=W)

        self.bt_stop = Button(
            frame,
            text="加入字幕",
            command=lambda: self.subtitles(self.p_path, self.file_path),
            bd=3,
            width=30)
        self.bt_stop.grid(row=6, column=1, rowspan=1, columnspan=2, sticky=W)

        self.text = scrolledtext.ScrolledText(frame,
                                              width=31,
                                              height=28,
                                              wrap=WORD,
                                              bd=3,
                                              bg="white")
        self.text.grid(row=7, column=1, rowspan=1, columnspan=2, sticky=W)
        self.text.insert(END, "请选择视频文件,并进行语音分析")
Beispiel #13
0
        songFile = "Twinkle Twinkle Little Star.mp3"
        return (songFile)
    elif (songName == "Down by the Bay"):
        songFile = "Down By The Bay.mp3"
        return (songFile)
    else:
        songFile = "none"
        return songFile


songName = get_song()
songState = get_state()
fileName = get_song_file(songName)

if (fileName != "none" and songState == "Play"):
    player = vlc.MediaPlayer(fileName)
    song_len = player.get_length()
    print("Playing ", fileName)
    print("Song length", song_len)
    player.play()
else:
    player = vlc.MediaPlayer()

while True:
    check_song = get_song()
    check_state = get_state()

    if (songName != check_song
            and check_song != "No Song Selected!"):  #change song
        player.stop()
        songName = check_song
#We import the VLC python bindings library
import vlc

#We set up GPIO using BCM numbering
GPIO.setmode(GPIO.BCM)

#We define the GPIO pins for each button
GPIO.setup(22, GPIO.IN)
GPIO.setup(23, GPIO.IN)
GPIO.setup(24, GPIO.IN)
GPIO.setup(25, GPIO.IN)
GPIO.setup(26, GPIO.IN)

#We create an object of the VLC class
player = vlc.MediaPlayer()

#We define the VLC playlist
#Add as many tracks as you need, just make sure to respect the formatting and put in the correct path!
#We use implied continuation of the list to make it easier to read.
playlist = [
    '/home/pi/title.mp3',
    '/home/pi/hint01.mp3',
    '/home/pi/hint02.mp3',
    '/home/pi/hint03.mp3',
    '/home/pi/hint04.mp3',
    '/home/pi/hint05.mp3',
    '/home/pi/error.mp3',
]

#Create variable to store user input
Beispiel #15
0
import vlc
import os

path = os.path.abspath(os.path.dirname(__file__))

quiz_jogo = pyfiglet.figlet_format("QUIZ JOGUINHO")
print(quiz_jogo, "\t\t\t\t\t\t\t\tTá em inglês fodase")

start = input("\nVamo começar? (s/n): ")

if start == "s":

    continua = "s"

    while continua == "s":
        gugu = vlc.MediaPlayer(path + "/resources/valendoooo.mp3")
        gugu.play()

        r = requests.get("https://opentdb.com/api.php?amount=1")

        content = r.content.decode("us-ascii")

        originalJson = json.loads(content)

        jsonVal = originalJson["results"][0]

        if jsonVal["type"] == "multiple":

            listMultiple = [
                jsonVal["correct_answer"], jsonVal["incorrect_answers"][0],
                jsonVal["incorrect_answers"][1],
        cv2.putText(img, str(confidence_display), (x + 5, y + h - 5), font, 1,
                    (255, 255, 0), 1)
        if round(100 - confidence) > 50 and confidence < 100:
            identification = True
            #playsound(mp3s.get(user_id))
            synthesis_input = texttospeech.types.SynthesisInput(
                text=speeches.get(id))
            voice = texttospeech.types.VoiceSelectionParams(
                language_code='fr-CA',
                ssml_gender=texttospeech.enums.SsmlVoiceGender.NEUTRAL)
            audio_config = texttospeech.types.AudioConfig(
                audio_encoding=texttospeech.enums.AudioEncoding.MP3)
            response = client.synthesize_speech(synthesis_input, voice,
                                                audio_config)
            mp3filepath = "mp3/" + id + ".mp3"
            with open(mp3filepath, 'wb') as out:
                out.write(response.audio_content)
            vlc.MediaPlayer(mp3filepath).play()
            break

    cv2.imshow('camera', img)

    k = cv2.waitKey(10) & 0xff  # Press 'ESC' for exiting video
    if k == 27:
        break

# Do a bit of cleanup
print("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()
Beispiel #17
0
import vlc
from time import sleep

player = vlc.MediaPlayer("/home/pi/roberts-radio/media/guitar.mp3")
player.play()
sleep(10)

Beispiel #18
0
    current_image = os.path.join(img_path, f"{current_index}.jpeg")
    current_recording = os.path.join(img_path, f"{current_index}.mp3")
    
    while True:
        try:

            current_stream = eng.dump_to(image2text(current_image), current_recording)
            #gtts.gTTS(image2text(current_image), lang='en').save(current_recording)
            break
        except FileNotFoundError:
            time.sleep(0.5)
    
    # for file in os.listdir(img_path):
    #     eng.set_io(i=file, o=output_dir)
    #     eng.speak()
    player = vlc.MediaPlayer(current_stream)
    print(f"On page {current_index+1}/{converter.length}".ljust(os.get_terminal_size().columns))
    # controls for the readout
    print(color(' P', bg='yellow', style='bold')+color(':play/pause', fg='#000', bg='yellow')+color(' ESC', bg='yellow', style='bold')+color(':exit ', fg='#000', bg='yellow'))
    while True:
        try:
            percent_completion = player.get_time()/(1e-12+player.get_length())
            pbar_length = max(os.get_terminal_size().columns-22,0)
            pbar = f"{str(int(100 * percent_completion)).rjust(3)}%"
            pbar += apply_gradient("█"*int(percent_completion * pbar_length), ["#FF0000","#00FF00"])
            pbar += " "*(pbar_length - int(percent_completion*pbar_length))
            
            if player.get_length() == -1:
                pbar = " "*pbar_length 

            print(get_formatted_duration(max(player.get_length(),0))+'/'+get_formatted_duration(max(player.get_time(),0))+' '+pbar, end="\r")
def sound2():
    r = " "
    p2 = vlc.MediaPlayer("angry.wav")
    p2.play()
    return r
Beispiel #20
0
class Radio(Thread):
    Path = "/home/pi/Documents/radio/"  #TODO
    sname = "stations.csv"  #TODO

    lcState = True
    pState = True

    i = 0
    period = 0.0
    stations = []
    cPlay = ""

    player = vlc.MediaPlayer()
    lcd = LCD.lcd()
    volume = 100  #keep track of the volume for the slider on the webpage

    nextPin = 6
    prevPin = 12
    pausePin = 16
    gp.setmode(gp.BCM)
    gp.setup(nextPin, gp.IN, pull_up_down=gp.PUD_DOWN)
    gp.setup(prevPin, gp.IN, pull_up_down=gp.PUD_DOWN)
    gp.setup(pausePin, gp.IN, pull_up_down=gp.PUD_DOWN)

    def __init__(self, i=0):

        Thread.__init__(self)

        self.i = i
        self.write("Loading Stations")
        self.stations = self.statLoad()
        self.Play()

    def write(self, s=''):  #write to the lcd
        l1 = ''  #line 1
        l2 = ''  #line 2

        if (len(s) > 16):
            l1 = s[:16]
            l2 = s[16:]
        else:
            l1 = s
        self.lcd.lcd_clear()
        self.lcd.lcd_display_string(l1, 1)
        self.lcd.lcd_display_string(l2, 2)
        if (s == ""):
            self.lcd.backlight(0)  #turn off the backlight
            self.lcState = False
        else:
            self.lcState = True

    def Play(self, der=0, i=-1):
        if i == -1:  #der specified
            self.i = self.i + der
            length = len(self.stations) - 1
            if (self.i < 0):
                self.i = length
            elif (self.i > length):
                self.i = 0
        else:  #specified a station
            self.i = i
        tmp = self.stations[self.i]

        self.cPlay = tmp[0]
        print("Playing %s" % self.cPlay)
        self.write(self.cPlay)
        self.period = time.time()

        try:  #try to play station
            self.player.stop()
            self.player = vlc.MediaPlayer(tmp[1])
            self.player.play()
            return 0
        except:
            print("ERROR PLAYING")
            return -1

    def statLoad(self):  #Save stations
        stations = []
        with open(self.Path + self.sname, 'r') as f:  #open the stations file
            lines = f.readlines()
            for i in lines:
                tmp = i.split(',')  #its a csv file
                tmpy = (tmp[0], tmp[1].rstrip())
                stations.append(tmpy)
            f.close()
        return stations

    def pause(self):
        tmp = self.stations[self.i][0]
        self.period = time.time()
        if (self.pState):
            self.write("Paused")
        else:
            self.write(tmp)  #write the name

        temp = self.pState
        self.player.set_pause(int(temp))
        self.pState = not temp

    def vol(self, vol):  #Change the volume
        self.volume = vol
        self.player.audio_set_volume(vol)

    def run(self):
        while (True):
            if (self.lcState and (int(time.time()) - self.period) >=
                    5):  #clear screen every 5 seconds if screen is on
                self.write()

            flag = False
            der = 1  #derection ha ha dir is keyword
            if (gp.input(self.pausePin)):
                self.pause()
                time.sleep(0.5)
            elif (gp.input(self.prevPin)):
                der = -1
                flag = True
            elif (gp.input(self.nextPin)):
                flag = True

            if (flag):  #play a diffrent staion
                self.Play(der)
                time.sleep(0.5)
def sound4():
    r = " "
    p4 = vlc.MediaPlayer("insane.wav")
    p4.play()
    return r
Beispiel #22
0
def peachAssistant(command):
    "if statements for executing commands"
    # open any website
    if 'open' in command:
        reg_ex = re.search('open (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            print(domain)
            url = 'https://www.' + domain
            webbrowser.open(url)
            peachResponse(
                'The website you have requested has been opened for you Sir.')
        else:
            peachResponse(
                'The website you have requested could not be opened.')
    # greetings
    elif 'hello' in command or 'hi' in command or 'hey' in command:
        day_time = int(strftime('%H'))
        if day_time < 12:
            peachResponse('Hello Sir. Good morning')
        elif 12 <= day_time < 18:
            peachResponse('Hello Sir. Good afternoon')
        else:
            peachResponse('Hello Sir. Good evening')
    # help  me
    elif 'help me' in command:
        peachResponse("""
        You can use these commands and I'll help you out:
        1. Open xyz.com : replace xyz with any website name
        2. Send email : Follow up questions such as recipient name, content will be asked in order.
        3. Current weather in city : Tells you the current condition and temperature in t
        4. Greetings
        5. play me a video : Plays song in your VLC media player
        6. news for today : reads top news of today
        7. time : Current system time
        8. top stories from google news (RSS feeds)
        9. tell me about xyz : tells you about xyz
        10. Play Picross on puzzle-nonogram.com
        11. Play Connect 4
        """)
    # joke
    elif 'joke' in command:
        res = requests.get('https://icanhazdadjoke.com/',
                           headers={"Accept": "application/json"})
        if res.status_code == requests.codes.ok:
            peachResponse(str(res.json()['joke']))
        else:
            peachResponse('oops!I ran out of jokes')
    # top stories from google news
    elif 'news for today' in command:
        try:
            news_url = "https://news.google.com/news/rss"
            Client = urlopen(news_url)
            xml_page = Client.read()
            Client.close()
            soup_page = soup(xml_page, "xml")
            news_list = soup_page.findAll("item")
            for news in news_list[:15]:
                peachResponse(news.title.text)
        except Exception as e:
            print(e)
    # current weather
    elif 'current weather' in command:
        reg_ex = re.search('current weather in (.*)', command)
        if reg_ex:
            city = reg_ex.group(1)
            owm = OWM(data.owmApi)  # our API key!
            obs = owm.weather_at_place(city)
            w = obs.get_weather()
            k = w.get_status()
            x = w.get_temperature(unit='celsius')
            response = '''Current weather in %s is %s.
             The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius''' % (
                city, k, x['temp_max'], x['temp_min'])
            peachResponse(response)
    # current time
    elif 'time' in command:
        import datetime
        now = datetime.datetime.now()
        peachResponse('Current time is %d hours %d minutes' %
                      (now.hour, now.minute))
    # email
    elif 'email' in command:
        peachResponse("Who is the recipient?")
        recipient = myCommand()
        # lookup for recipient's email id
        try:
            receiver_email = data.receiver_email[recipient.lower()]
            peachResponse('What should I send?')
            content = myCommand()
            send_mail(recipient, receiver_email, content)
            peachResponse(
                'Email has been sent successfully. You can check the inbox.')
        except KeyError:
            peachResponse('The email address could not be found.')

    # launch any system application
    elif 'launch' in command:
        launchApp(command)

    # play youtube song
    elif 'play me a song' in command or 'play a song' in command:
        peachResponse("Which song should I play, Sir ?")
        mysong = myCommand()
        if mysong:
            peachResponse("Please give me a minute")
            if (data.music_folder + "/" + mysong) in os.listdir(
                    data.music_folder):
                player = vlc.MediaPlayer(data.music_folder + '/' + mysong)
                player.play()
            else:
                flag = 0
                url = "https://www.youtube.com/results?search_query=" + mysong.replace(
                    ' ', '+')
                response = urlopen(url)
                html = response.read()
                soup1 = soup(html, "lxml")
                url_list = []
                for vid in soup1.findAll(attrs={'class': 'yt-uix-tile-link'}):
                    if ('https://www.youtube.com' + vid['href']
                        ).startswith("https://www.youtube.com/watch?v="):
                        flag = 1
                        final_url = 'https://www.youtube.com' + vid['href']
                        url_list.append(final_url)
                url = url_list[0]
                ydl_opts = {'outtmpl': data.music_folder + '/' + mysong}
                with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                    ydl.download([url])
                player = vlc.MediaPlayer(data.music_folder + '/' + mysong)
                player.play()

            com = myCommand()
            if 'stop' in com:
                player.stop()
            elif 'pause' in com:
                player.pause()
            else:
                player.play()

            if flag == 0:
                peachResponse('I have not found anything in Youtube !')

    # tell me about
    elif 'tell me about' in command or 'what is ' in command or 'define' in command:
        reg_ex = re.search('tell me about (.*)', command)
        try:
            if reg_ex:
                topic = reg_ex.group(1)
                try:
                    ny = wikipedia.summary(topic)
                except wikipedia.DisambiguationError as e:
                    t = random.choice(e.options)
                    ny = wikipedia.summary(t, sentences=4)
                peachResponse(ny)
        except Exception as e:
            print(e)
            peachResponse(e)

    # play nonogram puzzle
    elif 'nonogram' in command:
        peachResponse('Enjoy your game.')
        url = "https://www.puzzle-nonograms.com/"
        webbrowser.open(url)

    # play connect 4
    elif 'connect' in command:
        peachResponse('Would you like to play with a friend ?')
        ans = myCommand()
        if 'yes' in ans:
            from connect4 import connect4
            connect4.mainGame()
        else:
            peachResponse('You are up against me!')
            from connect4 import connect4_with_ai
            connect4_with_ai.mainGame()

    # hangman
    elif 'hangman' in command:
        from hangman import hangman_ai
        hangman_ai.play()
        peachResponse("I hope you had fun sir!")

    # chat with Peach!
    elif "let's talk" in command:
        from chatbot import chatgui
        chatgui.ChatGui()

    # to terminate the program
    elif 'bye' in command:
        peachResponse('Bye bye Sir. Have a nice day')
        sys.exit()
    # responding to thanks
    elif 'thanks' in command or 'thank you' in command:
        peachResponse("Your welcome!")
    else:
        if command != "":
            peachResponse("Sorry, I didn't understand!")
        center = (400, 400)
        img1 = pygame.transform.rotate(img, angle)
        size = img1.get_size()
        hSize = [n / 2 for n in size]
        pos = (center[0] - hSize[0], center[1] - hSize[1]
               )  # defines the center of the display
        img5 = pygame.transform.scale(img5, (20, 100))
        display.blit(img1, pos)
        display.blit(img5, (425, 0))
        pygame.display.update()
    pygame.display.quit()
    pygame.quit()


print("welcome lucky contestant too...")
sound1 = vlc.MediaPlayer("drumroll.mp3")  # opens drumroll file
sound1.play()  #plays drumroll file
time.sleep(
    4.46
)  # time is set too 4.46 so right after the drum roll ends, lines 37 to 44 show up
print(
    "               /$$                           /$$                  /$$$$$$         /$$$$$$                      /$$"
)
print(
    "              | $$                          | $$                 /$$__  $$       /$$__  $$                    | $$"
)
print(
    " /$$  /$$  /$$| $$$$$$$   /$$$$$$   /$$$$$$ | $$        /$$$$$$ | $$  \__/      | $$  \__//$$$$$$   /$$$$$$  /$$$$$$   /$$   /$$ /$$$$$$$   /$$$$$$"
)
print(
    "| $$ | $$ | $$| $$__  $$ /$$__  $$ /$$__  $$| $$       /$$__  $$| $$$$          | $$$$   /$$__  $$ /$$__  $$|_  $$_/  | $$  | $$| $$__  $$ /$$__  $$"
import glob
import os
from openal import *
import time
import vlc
list_of_files = glob.glob('/home/pi/Desktop/*')
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)

syscmnd = "ffmpeg -i " + latest_file + " /home/pi/Desktop/file_conv.mp3 -y"

os.system("{}".format(syscmnd))

player = vlc.MediaPlayer("/home/pi/Desktop/file_conv.mp3")
media_player = vlc.MediaPlayer()
media_player.audio_set_volume(300)
player.play()

time.sleep(10)
def playvideo(file):  #play video designated by file variable
    # comm =  "/home/aayushshivam7/python\ projects/pygam_vlc.py "
    # call(["python","pygam_vlc.py","abc.mp4"])
    global player
    player = vlc.MediaPlayer(file)
    player.play()
Beispiel #26
0
def main():
    closed_count = 0
    video_capture = cv2.VideoCapture(0)

    ret, frame = video_capture.read(0)
    # cv2.VideoCapture.release()
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
    rgb_small_frame = small_frame[:, :, ::-1]

    face_landmarks_list = face_recognition.face_landmarks(rgb_small_frame)
    process = True

    song = vlc.MediaPlayer('wakeup_loop.mp3')

    while True:
        ret, frame = video_capture.read(0)

        # get it into the correct format
        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
        rgb_small_frame = small_frame[:, :, ::-1]



        # get the correct face landmarks
        
        if process:
            face_landmarks_list = face_recognition.face_landmarks(rgb_small_frame)

            # put something here
            for face_landmark in face_landmarks_list:
                left_eye = face_landmark['left_eye']
                right_eye = face_landmark['right_eye']


                color = (255,0,0)
                thickness = 2

                cv2.rectangle(small_frame, left_eye[0], right_eye[-1], color, thickness)

                cv2.imshow('Video', small_frame)
                cv2.waitKey(1)

                ear_left = get_ear(left_eye)
                ear_right = get_ear(right_eye)

                closed = ear_left < 0.2 and ear_right < 0.2

                if (closed):
                    closed_count += 1

                else:
                    closed_count = 0

                if (closed_count >= 10):
                    print('wake up')

                    asleep = True
                    while (asleep): #continue this loop until they wake up and acknowledge music
                        song.play()
                        time.sleep(5)
                        song.stop() 

                        if (kb.is_pressed('space')):
                            asleep = False
                            google_directions()
                        
                    closed_count = 0

        process = not process
Beispiel #27
0
def Program():
    engine = pyttsx3.init('sapi5')
    engine.setProperty('volume', 1.0)
    engine.setProperty('rate', 200)
    client = wolframalpha.Client('P32Q9J-976AAG95X6')
    voices = engine.getProperty('voices')
    engine.setProperty('voice', voices[len(voices) - 1].id)

    def speak(audio):
        print('Anna: ' + audio)
        engine.say(audio)
        engine.runAndWait()

    def greetMe():
        currentH = int(datetime.datetime.now().hour)
        if currentH >= 0 and currentH < 12:
            speak('Good Morning!')

        if currentH >= 12 and currentH < 16:
            speak('Good Afternoon!')

        if currentH >= 16 and currentH != 0:
            speak('Good Evening!')

    def myCommand():
        r = sr.Recognizer()
        with sr.Microphone() as source:
            print("Listening...")
            r.pause_threshold = 1
            r.adjust_for_ambient_noise(source, duration=1)
            r.energy_threshold = 300
            audio = r.listen(source)
        try:
            query = r.recognize_google(audio, language='en-in')
            print('User: '******'\n')
        except sr.UnknownValueError:
            print("!")
            query = myCommand()
        return query

    def Command():
        r = sr.Recognizer()
        with sr.Microphone() as source:
            r.pause_threshold = 1
            r.adjust_for_ambient_noise(source, duration=1)
            r.energy_threshold = 300
            audio = r.listen(source)
        try:
            query = r.recognize_google(audio, language='en-in')
        except sr.UnknownValueError:
            query = Command()
        return query

    def online():
        speak('hello sir')
        speak('starting all system applications')
        speak('installing all drivers')
        speak('every driver is installed')
        speak('all systems have been started')
        speak('now i am online sir')

    def shutdown():
        speak('understood sir')
        speak('connecting to command prompt')
        speak('shutting down your computer')
        os.system('shutdown -s')

    def gooffline():
        speak('ok sir')
        speak('closing all systems')
        speak('disconnecting to servers')
        speak('going offline')
        quit()

    greetMe()
    online()
    speak('How may I help you?')
    while True:
        query = myCommand()
        query = query.lower()

        if 'open youtube' in query or 'youtube' in query:
            speak('okay')
            webbrowser.open('www.youtube.com')

        elif 'open google' in query or 'google' in query:
            speak('okay')
            webbrowser.open('www.google.co.in')

        elif 'open gmail' in query or 'gmail' in query:
            speak('okay')
            webbrowser.open('www.gmail.com')

        elif "what\'s up" in query or 'how are you' in query:
            stMsgs = [
                'Just doing my thing!', 'I am fine!', 'Nice!',
                'I am nice and full of energy'
            ]
            speak(random.choice(stMsgs))

        elif 'send mail' in query or 'send email' in query or 'email' in query:
            speak('Who is the recipient? ')
            recipient = myCommand()
            if 'me' in recipient:
                speak('What should I say? ')
                content = myCommand()
                receiver_email = '*****@*****.**'
            else:
                speak('Receiver Email Address please!')
                receiver_email = myCommand()
                speak('What should I say? ')
                content = myCommand()

            try:
                server = smtplib.SMTP('smtp.gmail.com', 587)
                server.ehlo()
                server.starttls()
                server.login("*****@*****.**", 'Sangam123@')
                server.sendmail('*****@*****.**', receiver_email,
                                content)
                server.close()
                speak('Email sent!')
            except:
                speak(
                    'Sorry Sir! I am unable to send your message at this moment!'
                )

        elif 'bye' in query or 'nothing' in query or 'abort' in query or 'stop' in query:
            gooffline()

        elif 'hello' in query:
            speak('Hello Sir')

        elif 'shutdown' in query:
            shutdown()

        elif 'play music' in query or 'next music' in query or 'music' in query:
            music_folder = "D:\\song\\1920_Evil_Returns_(2012)_IndiaMp3.Com\\1920 - Evil Returns (2012)\\songs\\"
            music = ["Apnaa", "Jaavedaan Hai", "Khud", "Majboor", "Uska"]
            random_music = music_folder + random.choice(music) + '.mp3'
            player = vlc.MediaPlayer(random_music)
            player.play()
            speak('Okay, here is your music! Enjoy!')
            while (Command() not in ["stop", "stop music"]):
                pass
            else:
                player.stop()
        else:
            query = query
            speak('Searching...')
            try:
                try:
                    res = client.query(query)
                    results = next(res.results).text
                    speak('WOLFRAM-ALPHA says - ')
                    speak('Got it.')
                    speak(results)

                except:
                    results = wikipedia.summary(query, sentences=2)
                    speak('Got it.')
                    speak('WIKIPEDIA says - ')
                    speak(results)

            except:
                webbrowser.open('www.google.com')
        nextmsgs = [
            'Next Command! Sir!', 'What more I can do for you sir!',
            'Anything else! Sir!', 'What else can i do',
            'Any more request sir...'
        ]
        speak(random.choice(nextmsgs))
Beispiel #28
0
# Open a system dialog box to select a video file
# root = Tk()
# root.filename =  filedialog.askopenfilename(title = "Select video file")
# print (root.filename)

# # Assign the file location to a variable
video_file = "Nas Daily about the student movement in Bangladesh right Now 😰-xgqaOFRP0Qk.mkv"

# # Clean up the dialog box
# root.destroy()

# Open a text file with the same name in write mode to record data
notepad = open("{0}.txt".format(video_file[:video_file.index('.')]), "w")

# Make the media player
player = vlc.MediaPlayer(video_file)

# Define listener functions


# on_press is called even when held down
def on_press(key):

    if key == Key.right:
        t = player.get_time()
        player.set_time(t + 5000)

    if key == Key.left:
        t = player.get_time()
        player.set_time(t - 5000)
import keras
import h5py
from keras.models import load_model

import numpy as np
import matplotlib.pyplot as plt
import matplotlib

# SKLEARN
from sklearn.model_selection import train_test_split
import vlc, easygui
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
media = easygui.fileopenbox(title="Choose media to open")
player = vlc.MediaPlayer(media)
image = "WIN_20181107_16_55_35_Pro.jpg"
model = load_model('my_model.h5')


def number_to_strings(a):
    switcher = {
        0: "Angry",
        1: "Disgust",
        2: "Fear",
        3: "Happy",
        4: "Sad",
        5: "Surprise",
        6: "Neutral",
    }
    return (switcher.get(a, "Invalid"))
Beispiel #30
0
	# First command line arg is image path. PNG format
	img = PhotoImage(file=emotion)
	img = img.subsample(1, 1)
	my_image = Label(root, image=img)
	my_image.pack()
	button = Button(root, text='OK', width=30, command=root.destroy)
	button.pack(padx=40, pady=40)
	button.config(bg='dark green', fg='white')
	button.config(font=('helvetica', 100, 'underline italic'))
	root.mainloop()


#start playing music at the beginning
tracks = ["MP3/14.mp3","MP3/35.mp3","MP3/02.mp3","MP3/10.mp3"]
aroma = ["aroma/peppermint.png","aroma/lemon.png","aroma/orange.png","aroma/lavender.png"]
player = vlc.MediaPlayer(tracks[random.randint(0,3)])
player.play()
onPlay = True
fig = plt.figure()
#fig.suptitle("Real Time Emotion Data updated in every 0.3 sec")
#ax1 = fig.add_subplot(111)


happyCounter = 0
sadCounter = 0
happy = False

def refreshGraphData(i):
	
	global happyCounter, sadCounter, happy, player, onPlay
	print("Refreshing Data.....")