Ejemplo n.º 1
0
def Spinx():
    
    r = sr.Recognizer()
    with sr.WavFile("voice.wav") as source:             
        audio = r.record(source)
        
    t = 0
    try:
        t = r.recognize_sphinx(audio)
        print(t) 
    except LookupError:                                
        print("Could not understand audio")
    except sr.UnknownValueError:
        print("Sphinx could not understand audio")
    except sr.RequestError as e:
        print("Sphinx error; {0}".format(e))
        
    if t==("hi"):
        sp.Play_Hello()
    elif t==("time"):
        sp.Play_Current_Time()
    elif t==("how are you"):
        sp.Play_HRU()
    elif t==("settings"):
        sp.Play_Current_Settings()
Ejemplo n.º 2
0
class MissionPlayer(object):
    '''
    This class can be fed with an event (ie phase1start)
    and plays then the according sound file in the appropriate langauge.
    '''

    def __init__(self):
        self.player = SoundPlayer()
        self.player.play('test.ogg')
        
    def getSoundInLanguage(self, fileName):
        
Ejemplo n.º 3
0
    def __init__(self, url, contact):
        super().__init__(url)
        self.updater_thread = None  # this will contain the auto fetching thread
        self.working_dir = BASE_WORKING_DIR + r"/Whatsapp/"
        self.contact = contact
        self.auto_update = False
        self.lock = Lock()

        # init notification sound player
        dir_path = os.path.dirname(os.path.realpath(__file__))
        self.sp = SoundPlayer(dir_path + NOTIFICATION_SOUND)

        Env.createFolder(self.working_dir)
Ejemplo n.º 4
0
def Google():
    
    r = sr.Recognizer()
    with sr.WavFile("voice.wav") as source:              # use "test.wav" as the audio source
       audio = r.record(source)                        # extract audio data from the file

    t = 0
    
    try:
        t = r.recognize_google(audio,language = "ru-RU", key = "AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw")
        print(t)   # recognize speech using Google Speech Recognition
    except LookupError:                                 # speech is unintelligible
        print("Could not understand audio")
        return False
    except sr.UnknownValueError:
        print("Google could not understand audio")
        return False
        #pass
    except sr.RequestError as e:
        print("Google error; {0}".format(e))
        return False
    if t  == 0:
        print("Error")
    elif t==("Привет") or t==("привет") or t==("Hi") or t==("Hello"): #Hi
        sp.Play_Hello()
    elif t==("Скажи время") or t==("Текущее время") or t==("Current time") or t==("Tell time"):
        sp.Play_Current_Time()
    elif t==("Как дела") or t==("How are you"):
        sp.Play_HRU()
    elif t==("Скажи настройки") or t==("Текущие настройки") or t==("Current settings"):
        sp.Play_Current_Settings()
    elif t.find("Привет") != -1 or t.find("привет") != -1 or t.find("Hi") != -1 or t.find("Hello") != -1: #Hi
        sp.Play_Hello()
    elif t.find("Время") != -1 or t.find("время") != -1:
        sp.Play_Current_Time()
    elif t.find("Как дела") != -1 or t.find("как дела") != -1 or t.find("How are you") != -1 or t.find("how are you") != -1:
        sp.Play_HRU()
    elif t.find("Настройки") != -1 or t.find("настройки") != -1 or t.find("Опции") != -1 or t.find("опции") != -1:
        sp.Play_Current_Settings()
    else:
        return False
     
    return True
Ejemplo n.º 5
0
 def OpenAudio(self, path):
     if self.sound is not None:
         del self.sound
         self.sound = None
     # self.soundPath = str(path.encode("utf-8"))
     self.soundPath = path  # .encode('latin-1', 'replace')
     self.sound = SoundPlayer.SoundPlayer(self.soundPath, self.parent)
     if self.sound.IsValid():
         print("valid sound")
         self.soundDuration = int(self.sound.Duration() * self.fps)
         print(("self.sound.Duration(): %d" % int(self.sound.Duration())))
         print(("frameRate: %d" % int(self.fps)))
         print(("soundDuration1: %d" % self.soundDuration))
         if self.soundDuration < self.sound.Duration() * self.fps:
             self.soundDuration += 1
             print(("soundDuration2: %d" % self.soundDuration))
     else:
         self.sound = None
Ejemplo n.º 6
0
    def ListenForCommand(self):
        L.debug('Listening for a voice command')

        RecognizedCommand = ''
        RecognizedCommand = STT.SpeechToText()

        if RecognizedCommand != '':
            CommandRegExPattern = r'\b%s\b' % Settings.GeneralKnowledgeTriggerPhrase
            CommandRegExResult = re.search(CommandRegExPattern,
                                           RecognizedCommand, re.IGNORECASE)

            SP.PlayAudioFile(FileName='EndBeep.mp3')

            if (CommandRegExResult) and (Settings.UseGeneralKnowledge):
                if Settings.GeneralKnowledgeEngine.lower() == 'apiai':
                    OR.QueryApiAI(RecognizedCommand)
            else:
                VoiceCommandItemURL = ''

                if Settings.Port.strip() != '':
                    TrimmedHostAndPort = Settings.HostName.strip(
                    ) + ':' + Settings.Port.strip()
                else:
                    TrimmedHostAndPort = Settings.HostName.strip()

                if Settings.SSLConnection:
                    URLPrefix = 'https://'
                else:
                    URLPrefix = 'http://'

                VoiceCommandItemURL = URLPrefix + TrimmedHostAndPort + '/CMD?' + Settings.VoiceCommandItem + '=' + '"' + RecognizedCommand + '"'

                if (Settings.Username.strip() !=
                        '') and (Settings.Password.strip() != ''):
                    HTTPGetResult = requests.get(
                        VoiceCommandItemURL,
                        auth=(Settings.Username.strip(),
                              Settings.Password.strip()))
                else:
                    HTTPGetResult = requests.get(VoiceCommandItemURL)
Ejemplo n.º 7
0
    def ListenForWakeUp(self):
        TTSReady = random.choice(
            open(Settings.FinalizationDataFile).readlines())
        M.ProcessMessage(TTSReady)

        while True:
            L.debug('Listening for a wake-up phrase')

            RecognizedWakeUp = ''
            RecognizedWakeUp = STT.SpeechToText(Settings.UseOfflineWakeUp)

            WakeUpRegExPattern = r'\b%s\b' % Settings.WakeUpPhrase
            WakeUpRegExResult = re.search(WakeUpRegExPattern, RecognizedWakeUp,
                                          re.IGNORECASE)

            if WakeUpRegExResult:
                if Settings.UseTextToSpeech:
                    TTSGreeting = random.choice(
                        open(Settings.GreetingDataFile).readlines())
                    M.ProcessMessage(TTSGreeting)
                else:
                    SP.PlayAudioFile(FileName='StartBeep.mp3')

                self.ListenForCommand()
stopper = Event()
stopper.clear()
clientConnected = False

global phoneStatus
phoneStatus = "FREE"

aesCipher = AESCipher()

while True:

    while not KeypadManager.q.empty():
        messageFromKeypad = KeypadManager.q.get()
        if messageFromKeypad == "A":
            if phoneStatus == "FREE":
                SoundPlayer.play_ringing_sound_on_another_thread()
                if clientConnected == True:
                    phoneStatus = "BUSY"
                    print("MAIN KEYBOARD: A")
                    processHTTPStreaming = startCall()
                    stopper_message = "STOP_RINGING"
                    t = Timer(30.0, ringingTimeout)
                    t.start()

            else:
                print(phoneStatus)

        if messageFromKeypad == "B":
            if phoneStatus == "FREE":
                SoundPlayer.play_ringing_sound_on_another_thread()
                phoneStatus = "BUSY"
Ejemplo n.º 9
0
class WhatsappPageCrawler(PageCrawler):
    def __init__(self, url, contact):
        super().__init__(url)
        self.updater_thread = None  # this will contain the auto fetching thread
        self.working_dir = BASE_WORKING_DIR + r"/Whatsapp/"
        self.contact = contact
        self.auto_update = False
        self.lock = Lock()

        # init notification sound player
        dir_path = os.path.dirname(os.path.realpath(__file__))
        self.sp = SoundPlayer(dir_path + NOTIFICATION_SOUND)

        Env.createFolder(self.working_dir)

    def startAutolFetch(self, interval):
        # start auto fetching data
        if not self.lock.locked():
            self.lock.acquire()
            if not self.auto_update and not self.updater_thread:
                self.updater_thread = threading.Thread(
                    target=self.__fetchWithInterval, args=(interval, ))
                self.auto_update = True
                self.updater_thread.start()
        else:
            raise RuntimeError("Auto fetch is already started")

    def stopAutolFetch(self):
        # stop the auto fetch, if started

        self.auto_update = False
        self.updater_thread = None
        self.lock.acquire(
        )  # wait for the fetching thread to end and release the lock
        self.lock.release()

    def __fetchWithInterval(self, interval):
        # returns a dictionary of a time fetched and status keys

        driver = self.initDriver()
        file_name = self.working_dir + self.contact + ".pickle"
        prev_status = False  # will be indication to play notification sound

        while self.auto_update:

            status = self.checkStatusOfContact(driver, self.contact)
            data = (datetime.now(), status)
            Env.appendToPickle(file_name, data)

            if status and not prev_status:  # if the user was offline, and than logged in to be online
                self.sp.play()  # play notification sound
                print("playing")
            prev_status = status

            time_to_sleep = interval
            while self.auto_update and time_to_sleep > 0:  # to ensure faster reaction to stop the auto update
                time.sleep(
                    1)  # sleep for a second, then check if you need to stop
                time_to_sleep -= 1

        driver.quit()
        self.lock.release()

    def initDriver(self):
        # init a chrome driver to connect whatsapp web, then click on the requested contact

        options = webdriver.ChromeOptions()
        options.add_argument(
            r"user-data-dir={}".format(CHROME_COOKIES_PATH)
        )  # use an existing chrome data, with whatsapp web cookies
        driver = webdriver.Chrome(options=options)
        driver.get(self.url)

        try:
            # search the contact in the search box
            wait_for_search_box = WebDriverWait(driver, 30).until(
                EC.presence_of_element_located((By.XPATH, r"//input")))
            input_element = driver.find_elements(By.XPATH, r"//input")[0]
            input_element.send_keys(self.contact)
            input_element.send_keys(Keys.ENTER)

            wait_for_contact = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located(
                    (By.XPATH, r"//span[text()='{}']".format(self.contact))))
            time.sleep(3)
            driver.find_elements(By.XPATH, r"//span[text()='{}']".format(
                self.contact))[0].click(
                )  # click on the contact name to enter conversation

            return driver

        except:
            driver.quit()
            raise RuntimeError("could not initialize driver properly")

    def checkStatusOfContact(self, driver, contact):
        # checks whether the contact appears as online in the current driver state

        try:
            # if the user is connected, a span that contains the word "online" exists
            WebDriverWait(driver, 0).until(
                EC.presence_of_element_located(
                    (By.XPATH, r"//span[text()='{}']".format("online"))))
            status = True
        except:
            status = False

        return status
Ejemplo n.º 10
0
 def __init__(self):
     self.player = SoundPlayer()
     self.player.play('test.ogg')
Ejemplo n.º 11
0
 def __init__(self):
     self.soundPlayer = SoundPlayer.SoundPlayer()