示例#1
0
def setup():
    settings = defaultdict(lambda:[None])
    utils.speak("What is your name?")
    while settings['name'] == [None]:
        settings['name'] = utils.recordAudio()
    with open(os.path.join(path,'settings.json'), 'w') as f:
        json.dump(settings, f)
 def open(self, url):
     sentiments = VoiceAnalyzer().recognize()
     if sentiments:
         max_key = max(sentiments, key=sentiments.get)
         if max_key == 'neu' or max_key == 'pos':
             utils.speak(self.response)
             utils.open_url(url)
示例#3
0
def news_update(opt):
    # hourly news update
    # Update required: Headlines are not complete
    if (opt.news_enabled):
        speak(
            "Time for a short break {}. Your hourly news update would soon begin!"
            .format(opt.user))
        for topic in opt.news:
            news_url = "https://www.google.co.in/search?q=" + topic + "&tbm=nws&rct=j"
            r = requests.get(news_url)
            soup = BeautifulSoup(r.text, "html.parser")
            a = soup.findAll("a")
            arr = []
            for elm in a:
                if elm.has_attr("class"):
                    continue
                if len(elm["href"]) < 100:
                    continue
                arr.append(elm)
            arr2 = []
            for elm in soup.findAll("img"):
                if elm.parent.name == "a":
                    arr2.append(elm.parent)
            for link2 in arr2:
                for link1 in arr:
                    if link1['href'][:50] == link2['href'][:50]:
                        news = link1.get_text()
                        if (news):
                            speak(news)
示例#4
0
def take_rest(opt):
    if opt.priority != 'low':
        speak("Take a 10 second rest.")
        subprocess.call([
            "xset -display :0.0 dpms force off && sleep 10 && xset -display :0.0 dpms force on"
        ],
                        shell=True)
示例#5
0
文件: models.py 项目: shulinye/yoga
 def __call__(self, imbalance=[], prev=None, verbose=1, **kwargs) -> "Move":
     """Tells me which pose I'm supposed to do and how I'm supposed to do it.
     Also figures out next pose and deals with adding late moves"""
     print("\n" + colorama.Style.BRIGHT + self.title + colorama.Style.NORMAL)
     # Deal with imbalances
     if self.side:
         if self in imbalance: imbalance.remove(self)
         else: imbalance.append(self.otherside)
     if verbose >= 2:
         print(colorama.Fore.BLUE + utils.wrapper.fill('Prev: ' + '; '.join(map(str, prev))))
         print(colorama.Fore.MAGENTA + utils.wrapper.fill('Imbalances (%d): %s' % (len(imbalance), '; '.join(map(str,imbalance))))\
                 + colorama.Fore.RESET)
     if prev is not None: prev.append(self)
     # What is my next move?
     if 'nextMove' in kwargs:
         # Assume the caller knows what they're doing right now.
         # Should possibly assert that nextMove is a plausible nextMove
         nextMove = kwargs['nextMove']
         self.promoteLate(nextMove)
     else:
         for i in imbalance:
             if i in self.nextMove:
                 nextMove = i
                 break
         else:
             nextMove = self.notLast(prev)
     if nextMove is not None:
         print('Next Move: ' + nextMove.title)
         self.last = nextMove
         if verbose >= 1:
             print(colorama.Fore.CYAN + utils.wrapper.fill('My options were: ' + '; '.join(str(i) for i in self.nextMove)))
             print(colorama.Fore.GREEN + utils.wrapper.fill('Latemoves: ' + '; '.join(str(i) for i in self.lateMove)) + colorama.Fore.RESET)
     # Tell me what to do
     utils.speak(self.audio)
     time.sleep(0.3)
     for i in ('early', 'harder'):
         if i in kwargs and kwargs[i]: utils.speak(getattr(self, i, None))
     # How long am I supposed to do it?
     if 'time' in kwargs: t = kwargs['time']
     elif 'extended' in kwargs and kwargs['extended'] and self.extended_time: t = random.choice(self.extended_time)
     else: t = self.time
     # Actually count down
     if getattr(self, 'bind', None): utils.speak("Bind if you want to")
     if t > 5: utils.speak(str(t) + " seconds")
     if getattr(self, 'countdown', None): utils.countdown(t, incremental=True)
     else: utils.countdown(t)
     #record to file, if we were given a file
     if 'f' in kwargs and kwargs['f']:
         kwargs['f'].write('%s: %d' % (self.title, t))
         s = self.repCount()
         if s: kwargs['f'].write(' - %s reps' % s)
         kwargs['f'].write('\n')
         kwargs['f'].flush()
     if getattr(self, 'bind', None): utils.speak('Release bind')
     self.promoteLate()  # Add in options for harder followup moves next time
     return nextMove
示例#6
0
    def execute_command(self, cmd):
        utils.speak(response=self.response)
        output = subprocess.Popen(cmd,
                                  shell=True,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE).communicate()

        if str(output[1], 'utf-8') is not '':
            utils.speak(
                'I am sorry sir, The app which you are looking for is not installed in my database.'
            )
示例#7
0
    def _play_sound(self):
        self._start_time = time.time()

        # Either play back a recording or speak the text
        if self._play.type == 'play':
            self._parent.playback_recording_cb()
            self._poll_audio()
        elif self._speak.type == 'speak':
            bounds = self._parent.text_buffer.get_bounds()
            text = self._parent.text_buffer.get_text(bounds[0], bounds[1],
                                                     True)
            speak(text)
            self._next_image()
示例#8
0
    def _play_sound(self):
        self._start_time = time.time()

        # Either play back a recording or speak the text
        if self._play.type == 'play':
            self._parent.playback_recording_cb()
            self._poll_audio()
        elif self._speak.type == 'speak':
            bounds = self._parent.text_buffer.get_bounds()
            text = self._parent.text_buffer.get_text(
                bounds[0], bounds[1], True)
            speak(text)
            self._next_image()
示例#9
0
文件: mainmenu.py 项目: tyrylu/mpyw
def edit_decrease_indent(evt):
	expr = re.compile("^%s"%appenv.conf["indent"]["unit"], re.U + re.M)
	start = appenv.policko.Selection[0]
	end = appenv.policko.Selection[1]
	if start == end:
		lineno = appenv.policko.PositionToXY(appenv.policko.InsertionPoint)[1]
		start = appenv.policko.XYToPosition(0, lineno)
		len = appenv.policko.GetLineLength(lineno)
		end = start + len
	text = appenv.policko.GetRange(start, end)
	text = expr.sub("", text)
	appenv.policko.Replace(start, end, text)
	utils.speak(u"Úroveň {0}".format(utils.get_indent_level(text)))
示例#10
0
def salutation():
    hour = int(datetime.datetime.now().hour)
    if hour >= 0 and hour < 12:
        speak("Good Morning Sir !")

    elif hour >= 12 and hour < 18:
        speak("Good Afternoon Sir !")

    else:
        speak("Good Evening Sir !")

    assname = ("Bhagwan 1 point o")
    speak("I am your Assistant")
    speak(assname)
示例#11
0
文件: dawn.py 项目: cknduru/dawn
def main():
    weather.update_weather()

    h, m = utils.format_current_time()

    # split this up to make pronounciation more fluent?
    greeting = """Good morning. The time is {} {} and it is time to wake up.
The weather is {} so im sure it will be a lovely day. I have prepared a song to start the day. Remember to book
christmas holiday and that you have visitors at six o clock""".format(
        h, m, weather.last_weather)

    if event_manager.should_trigger():
        utils.speak(greeting)

        utils.play_song('/home/pi/Desktop/dawn/music/fr.mp3')
示例#12
0
文件: main.py 项目: sumukhamh/tourbot
    def goto(self, data, pub):
        # Send a goal
        goal = MoveBaseGoal()
        goal.target_pose.header.frame_id = 'map'

        self.goal_sent = True

        goal.target_pose.header.stamp = rospy.Time.now()

        goal.target_pose.pose = Pose(
            Point(data['point'][0], data['point'][1], 0.000),
            quats[data['ori']])

        # Start moving
        self.move_base.send_goal(goal)

        success = self.move_base.wait_for_result(rospy.Duration(100))

        state = self.move_base.get_state()

        if success and state == GoalStatus.SUCCEEDED:
            utils.Interact(data)
            self.goal_sent = False
            initial_pos_pub(
                pub, {
                    'pose': (data['point'][0], data['point'][1]),
                    'ori': quats[data['ori']]
                })

            if ((rospy.Time.now() - face_time_prev) >
                    rospy.Duration.from_sec(90)):
                print('Face not detected, tour ended')
                self.move_base.cancel_goal()
                return False

        else:
            utils.speak(
                'Please clear the way! If I am stuck, please give me a nudge')
            initial_pos_pub(
                pub, {
                    'pose': (current_pose.position.x, current_pose.position.y),
                    'ori': current_pose.orientation
                })
            return self.goto(data, pub)

        return True
示例#13
0
def process_command(sender, message):
    """Background task to send an email with Flask-Mail."""

    intent = parser.get_intent(message.lower())
    args = parser.get_entities(message, intent)
    print intent
    print args
    if intent == 'time':
        send_message(sender, time.strftime('%I:%M %p'))
    elif intent == 'expense' and 'interval' in args:
        result = p.process(intent, args)
        if args['exp_type'] == 'all':
            send_image(sender, 'plot.png', result, True)
        else:
            send_message(sender, result, False)
    elif intent == 'echo' and 'message' in args:
        speak(args['message'])
    elif intent == 'snap' or intent == 'stream':
        url_link = get_link(intent)
        send_message(sender, url_link, False)
    elif intent == 'email' and 'action' in args:
        result = p.process(intent, args)
        print result
        send_message(sender, result)
    elif intent == 'security' and 'action' in args:
        result = p.process(intent, args)
        send_message(sender, result)
    elif intent == 'stock' and 'company' in args:
        result = p.process(intent, args)
        send_message(sender, result)
    elif intent == 'weather' and 'city' in args:
        result = p.process(intent, args)
        send_message(sender, result)
    elif intent == 'switch' and 'action' in args:
        result = p.process(intent, args)
        send_message(sender, result)
    elif intent == 'route' and 'destination' in args:
        result = p.process(intent, args)
        send_message(sender, result, not args['directions'])
    elif intent == 'wiki' and 'query' in args:
        result = p.process(intent, args)
        send_message(sender, result)
    else:
        result = 'Sorry, I didnt get that.'
        send_message(sender, result)
    def launch(self):
        try:
            result = self.search()[0]

            title = html.unescape(result['snippet']['title'])

            if result['id']['kind'] == 'youtube#video':
                utils.speak(
                    f'I have found the video as {title}. Would you like to play it?'
                )
                url = f"https://youtu.be/{result['id']['videoId']}"
            elif result['id']['kind'] == 'youtube#channel':
                utils.speak(
                    f'I got a channel for you as {title}. Would you like to open it?'
                )
                url = f"https://www.youtube.com/channel/{result['id']['channelId']}"

            self.open(url)

        except HttpError as e:
            print(e)
    def translate(self):
        text, target = self.get_text_and_target()

        if target:
            try:
                translator = Translator(service_urls=['translate.googleapis.com'])
                text_to_translate = translator.translate(text, dest=target)
                text = text_to_translate.text

                speak = gTTS(text=text, lang=target, slow=False)
                speak.save(Translation.MP3_NAME)

                try:
                    playsound(Translation.MP3_NAME)
                    os.remove(Translation.MP3_NAME)
                except IOError:
                    pass
            except (sr.RequestError, sr.UnknownValueError) as e:
                print(e)
        else:
            utils.speak('The asked language is not supported by me.')
示例#16
0
def _conversation():
    with open("conversation.txt", 'r') as file:

        for _ in range(3):
            utils.speak(file.readline())
        
        user_info.append(input("Please enter your name: "))
        user_info.append(input("Please enter your home address: "))

        for _ in range(2):
            utils.speak(file.readline())

        user_info.append(utils.get_expenditure())

        start_analysis.set()

        for _ in range(9):
            utils.speak(file.readline())

        for _ in range(2):
            utils.speak(file.readline())
示例#17
0
 def run(self):
     new = AlarmTiming(self.input).get_expected_time()
     if new:
         new = datetime.strptime(new, "%Y-%m-%d %H:%M:00")
         print('Current time is : ' + str(datetime.now()))
         if datetime.now() > new:
             utils.speak('Alarm time is greater than current time sir.')
         else:
             utils.speak(self.response)
             while True:
                 now = datetime.now().strftime('%Y-%m-%d %H:%M:00')
                 now = datetime.strptime(now, "%Y-%m-%d %H:%M:00")
                 if now == new:
                     utils.speak('Sir, You need to wake up now.')
                     break
示例#18
0
def wandaV2(data, knownSkills, method):
    for skill in knownSkills:
        thingy = (e in data for e in skill[method])
        if any(thingy):
            if skill['responseType']=='text':
                utils.speak(skill['response'][0])
            else:
                args = list()
                for argument in skill['arguments']:
                    if argument==None:
                        break
                    args.append(eval(argument))
                utils.speak(getattr(utils , skill['response'][0])(args))
            return
    if data != [None]:
        if method=='trigger':                
            wandaV2(data,knownSkills, 'extendedTrigger')
        else:
            utils.speak(utils.default([data]))
    else:
        utils.stillStanding()
示例#19
0
def check_battery():
    # system battery
    response = subprocess.Popen(["acpi -a"],
                                shell=True,
                                stdout=subprocess.PIPE)
    power_onoff_response = response.stdout.readline()
    battery_level = subprocess.Popen(["acpi -b | grep -P -o '[0-9]+(?=%)'"],
                                     shell=True,
                                     stdout=subprocess.PIPE)
    battery = int(battery_level.stdout.readline())
    print(battery)
    if "on" in power_onoff_response:
        if (battery == 100):
            speak("Warning! Laptop is fully charged. Please unplug.")
        elif (battery > 80):
            speak("You should unplug your charger. Laptop battery is " +
                  str(battery) + "percent")
        else:
            print("Laptop charging")
    else:
        if (battery < 20):
            speak("Danger! Danger! Only " + str(battery) +
                  "percent battery left. Plug in your charger or I will die.")
示例#20
0
    def __event_cb(self, win, event):
        ''' The mouse button was pressed. Is it on a sprite? or
            there was a gesture. '''

        left = right = False

        if event.type in (Gdk.EventType.TOUCH_BEGIN,
                          Gdk.EventType.TOUCH_CANCEL,
                          Gdk.EventType.TOUCH_END,
                          Gdk.EventType.BUTTON_PRESS,
                          Gdk.EventType.BUTTON_RELEASE):

            x = int(event.get_coords()[1])
            y = int(event.get_coords()[2])

            if event.type in (Gdk.EventType.TOUCH_BEGIN,
                              Gdk.EventType.BUTTON_PRESS):
                self._prev_mouse_pos = (x, y)
            elif event.type in (Gdk.EventType.TOUCH_END,
                                Gdk.EventType.BUTTON_RELEASE):

                if self._parent.audio_process is not None:
                    self._parent.audio_process.terminate()
                    self._parent.audio_process = None
                    terminated_audio = True
                else:
                    terminated_audio = False

                if self.playing:
                    self.stop()

                new_mouse_pos = (x, y)
                mouse_movement = (new_mouse_pos[0] - self._prev_mouse_pos[0],
                                  new_mouse_pos[1] - self._prev_mouse_pos[1])

                # horizontal gestures only
                if (abs(mouse_movement[0]) / 5) > abs(mouse_movement[1]):
                    if abs(mouse_movement[0]) > abs(mouse_movement[1]):
                        if mouse_movement[0] < 0:
                            right = True
                        else:
                            left = True

        if event.type in (Gdk.EventType.TOUCH_END,
                          Gdk.EventType.BUTTON_RELEASE):
            spr = self._sprites.find_sprite((x, y))
            if left or right or spr is not None:
                if spr.type in ['record', 'play', 'play-inactive', 'speak',
                                'speak-inactive']:
                    if spr.type == 'record':
                        self._parent.record_cb()
                    elif spr.type == 'play' and not terminated_audio:
                        self._parent.playback_recording_cb()
                    elif spr.type == 'speak':
                        bounds = self._parent.text_buffer.get_bounds()
                        text = self._parent.text_buffer.get_text(
                            bounds[0], bounds[1], True)
                        speak(text)
                    return
                elif self._mode == 'array':
                    return

                self._parent.speak_text_cb()

                if self._parent.recording:
                    self._parent.record_cb()

                if (left or spr.type == 'prev') and self.current_image > 0:
                    self._Dots[self.current_image].hide()
                    self.current_image -= 1
                    self._Dots[self.current_image].set_layer(100)
                    if self.current_image == 0:
                        self._prev.set_image(
                            self._next_prev_pixbufs[PREV_INACTIVE])
                    self._next.set_image(self._next_prev_pixbufs[NEXT])
                elif (right or spr.type == 'next') and self.current_image < 8:
                    self._Dots[self.current_image].hide()
                    self.current_image += 1
                    self._Dots[self.current_image].set_layer(100)
                    if self.current_image == 8:
                        self._next.set_image(
                            self._next_prev_pixbufs[NEXT_INACTIVE])
                    self._prev.set_image(self._next_prev_pixbufs[PREV])
                elif spr.type not in ['prev', 'background'] and \
                        self.current_image < 8:
                    self._Dots[self.current_image].hide()
                    self.current_image += 1
                    self._Dots[self.current_image].set_layer(100)
                    if self.current_image == 8:
                        self._next.set_image(
                            self._next_prev_pixbufs[NEXT_INACTIVE])
                    self._prev.set_image(self._next_prev_pixbufs[PREV])
                self._parent.check_audio_status()
                self._parent.check_text_status()
                self._prev.set_layer(1)
                self._next.set_layer(1)
        return False
示例#21
0
def handle_query(query):
    try:
        if 'wikipedia' in query:
            speak('Searching Wikipedia...')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=3)
            speak("According to Wikipedia")
            print(results)
            speak(results)

        elif 'open youtube' in query:
            speak("Here you go to Youtube\n")
            webbrowser.open("youtube.com")

        elif 'open google' in query:
            speak("Here you go to Google\n")
            webbrowser.open("google.com")

        elif 'open stackoverflow' in query:
            speak("Here you go to Stack Over flow.Happy coding")
            webbrowser.open("stackoverflow.com")

        elif 'time' in query:
            strTime = datetime.datetime.now().strftime("% H:% M:% S")
            speak(f"Sir, the time is {strTime}")

        else:
            speak(f"Command {query} not recogonized")

    except Exception as e:
        print(f"Exception occured: {e}")
示例#22
0
文件: main.py 项目: shulinye/yoga
def main(**kwargs):
    defaults = {
            "time": 30,
            "difficulty": 1,
            "initial_move": "child",
            "warmup": True,
            "cooldown": True,
            "aerobics": 0,
            "strength": 0,
            "target": "plank",
            "verbose":1,
            "memory":5,
            "outfile": None,
            }
    defaults.update(kwargs)

    if defaults["outfile"]:
        f = open(defaults["outfile"], "a")
        f.write(str(datetime.datetime.now()) + "\n")
        f.write(str(defaults) + "\n")
    else:
        f = None
    utils.speak('Beginning in')
    utils.countdown(3)

    if defaults["verbose"] >= 2:
        print(utils.wrapper.fill(str(defaults)))
    elif defaults["verbose"] >= 1:
        print("Workout length:", defaults['time'], "minutes.", "Beginning in:")
    # setup
    total_time = defaults['time']*60
    movesGraph = moves.generateMoves(difficulty=defaults["difficulty"])
    stretches.defineStretches(movesGraph, difficulty=defaults["difficulty"])
    start = time.time()
    end = start + total_time

    class Times(Enum):
        warmup_end = start + min(max(45,total_time//15),300)
        halfway = start + total_time//2.4 - 30
        cooldown_begin = (end - max(60, total_time//5)) if defaults['cooldown'] else end


    imbalance = []
    prev = collections.deque([],defaults["memory"])
    try:
        pose = movesGraph[defaults['initial_move']]
    except KeyError:
        pose = movesGraph['child']

    try:
        #warmup
        if defaults["warmup"]:
            pose = pose(time=min(30,max(15, total_time//120+7)), imbalance=imbalance, prev=prev, verbose=defaults["verbose"], f=f)
            while time.time() < Times.warmup_end.value:
                pose = pose(imbalance=imbalance, extended=True, early=True, prev=prev, verbose=defaults["verbose"], f=f) #start slower
        #get me to my target:
        moves.linkMain(movesGraph, defaults['difficulty'])
        if defaults['aerobics']:
            strengthaerobics.linkAerobics(movesGraph, defaults["difficulty"], defaults["aerobics"])
        if defaults['strength']:
            strengthaerobics.linkStrength(movesGraph, defaults["difficulty"], defaults["strength"])
            if defaults['aerobics']:
                strengthaerobics.linkStrengthAerobics(movesGraph, defaults["difficulty"], defaults["strength"], defaults["aerobics"])
        if defaults['warmup']:
            pose = fixImbalance(pose, imbalance, maxTime=max(45,total_time//12.5), prev=prev, verbose=defaults['verbose'], f=f)
        imbalance = moves.unlinkWarmup(movesGraph, imbalance=imbalance, difficulty=defaults["difficulty"])
        try:
            target = movesGraph[defaults['target']]
        except KeyError:
            target = movesGraph['plank']
        pose = get_me_to(pose, target, imbalance=imbalance, playLast=False, prev=prev, verbose=defaults["verbose"], f=f)
        if defaults["warmup"]:
            utils.tee("Warmup Over: " + utils.prettyTime(time.time() - start), f, say="Alright, warmup over.")
        pose = pose(imbalance=imbalance, prev=prev, verbose=defaults["verbose"], f=f)
        #starting main part of workout
        while time.time() < Times.halfway.value:
            pose = fixImbalance(pose, imbalance, maxImbalance=10 + total_time//600, maxTime=max(60,total_time//12), prev=prev, verbose=defaults["verbose"], f=f)
            pose = pose(imbalance=imbalance, prev=prev, verbose=defaults["verbose"], f=f)
        #add harder poses in here
        if defaults["difficulty"] >= 1:
            moves.linkHarder(movesGraph, defaults["difficulty"])
            if defaults["strength"]:
                strengthaerobics.linkStrengthHarder(movesGraph, defaults["difficulty"], defaults["strength"])
        pose = fixImbalance(pose, imbalance, maxTime=max(60, total_time//10), prev=prev, verbose=defaults["verbose"], f=f)
        try:
            pose = get_me_to(pose, movesGraph[defaults['target']], imbalance=imbalance, prev=prev, verbose=defaults["verbose"], f=f)
        except KeyError:
            pass
        if defaults["verbose"] >= 1:
            utils.tee("Halfway point: " + utils.prettyTime(time.time()-start), f, say="We have reached the halway point")
        #end adding harder poses
        harder = defaults["difficulty"] >= 1
        while time.time() < Times.cooldown_begin.value:
            extendedChance = (time.time() - start)/total_time
            extended = random.random() < extendedChance
            pose = fixImbalance(pose, imbalance, maxImbalance=8+total_time//800, maxTime=max(110,total_time//10), prev=prev, verbose=defaults["verbose"], \
                    f=f, harder=harder)
            pose = pose(harder=harder, imbalance = imbalance, extended=extended, prev=prev, verbose=defaults["verbose"], f=f)
        moves.linkEnding(movesGraph)
        while time.time() < (end - max(60, total_time//10)):
            pose = fixImbalance(pose, imbalance, maxImbalance=max(1,total_time//800), maxTime=max(120, total_time//8), prev=prev, verbose=defaults["verbose"], f=f)
            pose = pose(imbalance = imbalance, prev=prev, verbose=defaults["verbose"], f=f)
        if defaults["cooldown"]:
            pose = fixImbalance(pose, imbalance, maxImbalance=1, maxTime=max(75, total_time//10+15), prev=prev, verbose=defaults["verbose"], f=f)
            utils.tee("Cooldown begins: " + utils.prettyTime(time.time() - start), f, say="Cooldown begins")
            stretches.linkCooldown(movesGraph, difficulty=defaults["difficulty"])
            if defaults["strength"]: strengthaerobics.linkStrengthCooldown(movesGraph,difficulty=defaults["difficulty"], strength = defaults["strength"])
            if defaults["aerobics"]: strengthaerobics.linkAerobicsCooldown(movesGraph,difficulty=defaults["difficulty"], aerobics = defaults["aerobics"])
            pose = get_me_to(pose, movesGraph['wheel'], imbalance=imbalance, prev=prev, verbose=defaults['verbose'], f=f)
        pose = fixImbalance(pose, imbalance, maxImbalance=1, maxTime=max(60, total_time//10), prev=prev, verbose=defaults['verbose'], f=f)
        while time.time() < (end-max(30, total_time//10)) if defaults["cooldown"] else end:
            #pose = pose(imbalance=imbalance, extended=True, prev=prev, verbose=defaults['verbose'], f=f)
            pose = fixImbalance(pose, imbalance, maxImbalance=1, maxTime=max(30, total_time//10), prev=prev, verbose=defaults['verbose'], f=f)
        if defaults['cooldown']:
            moves.linkSavasana(movesGraph, difficulty=defaults['difficulty'])
            pose = fixImbalance(pose, imbalance, maxImbalance=1, maxTime=max(30, total_time//10), prev=prev, verbose=defaults['verbose'], f=f)
            pose = get_me_to(pose, movesGraph['savasana'], imbalance=imbalance, prev=prev, verbose=defaults['verbose'], f=f)
    except (KeyboardInterrupt, BrokenPipeError):
        moves.linkSavasana(movesGraph, difficulty=defaults['difficulty'])
        pose = get_me_to(pose, movesGraph['savasana'], imbalance=imbalance, prev=prev, verbose=defaults['verbose'], f=f)
    finally:
        final_time = utils.prettyTime(time.time() - start)
        utils.tee('\nTotal Time: %s' % final_time, f=f, say='Done! Total time was %s' % final_time.replace('(','').replace(')',''))
        if f: f.close()
        sys.stdout.write(colorama.Style.RESET_ALL)
        print(utils.wrapper.fill(str(imbalance)))
    return imbalance
示例#23
0
    def __event_cb(self, win, event):
        ''' The mouse button was pressed. Is it on a sprite? or
            there was a gesture. '''

        left = right = False

        if event.type in (Gdk.EventType.TOUCH_BEGIN,
                          Gdk.EventType.TOUCH_CANCEL, Gdk.EventType.TOUCH_END,
                          Gdk.EventType.BUTTON_PRESS,
                          Gdk.EventType.BUTTON_RELEASE):

            x = int(event.get_coords()[1])
            y = int(event.get_coords()[2])

            if event.type in (Gdk.EventType.TOUCH_BEGIN,
                              Gdk.EventType.BUTTON_PRESS):
                self._prev_mouse_pos = (x, y)
            elif event.type in (Gdk.EventType.TOUCH_END,
                                Gdk.EventType.BUTTON_RELEASE):

                if self._parent.audio_process is not None:
                    self._parent.audio_process.terminate()
                    self._parent.audio_process = None
                    terminated_audio = True
                else:
                    terminated_audio = False

                if self.playing:
                    self.stop()

                new_mouse_pos = (x, y)
                mouse_movement = (new_mouse_pos[0] - self._prev_mouse_pos[0],
                                  new_mouse_pos[1] - self._prev_mouse_pos[1])

                # horizontal gestures only
                if (abs(mouse_movement[0]) / 5) > abs(mouse_movement[1]):
                    if abs(mouse_movement[0]) > abs(mouse_movement[1]):
                        if mouse_movement[0] < 0:
                            right = True
                        else:
                            left = True

        if event.type in (Gdk.EventType.TOUCH_END,
                          Gdk.EventType.BUTTON_RELEASE):
            spr = self._sprites.find_sprite((x, y))
            if left or right or spr is not None:
                if spr.type in [
                        'record', 'play', 'play-inactive', 'speak',
                        'speak-inactive'
                ]:
                    if spr.type == 'record':
                        self._parent.record_cb()
                    elif spr.type == 'play' and not terminated_audio:
                        self._parent.playback_recording_cb()
                    elif spr.type == 'speak':
                        bounds = self._parent.text_buffer.get_bounds()
                        text = self._parent.text_buffer.get_text(
                            bounds[0], bounds[1], True)
                        speak(text)
                    return
                elif self._mode == 'array':
                    return

                self._parent.speak_text_cb()

                if self._parent.recording:
                    self._parent.record_cb()

                if (left or spr.type == 'prev') and self.current_image > 0:
                    self._Dots[self.current_image].hide()
                    self.current_image -= 1
                    self._Dots[self.current_image].set_layer(100)
                    if self.current_image == 0:
                        self._prev.set_image(
                            self._next_prev_pixbufs[PREV_INACTIVE])
                    self._next.set_image(self._next_prev_pixbufs[NEXT])
                elif (right or spr.type == 'next') and self.current_image < 8:
                    self._Dots[self.current_image].hide()
                    self.current_image += 1
                    self._Dots[self.current_image].set_layer(100)
                    if self.current_image == 8:
                        self._next.set_image(
                            self._next_prev_pixbufs[NEXT_INACTIVE])
                    self._prev.set_image(self._next_prev_pixbufs[PREV])
                elif spr.type not in ['prev', 'background'] and \
                        self.current_image < 8:
                    self._Dots[self.current_image].hide()
                    self.current_image += 1
                    self._Dots[self.current_image].set_layer(100)
                    if self.current_image == 8:
                        self._next.set_image(
                            self._next_prev_pixbufs[NEXT_INACTIVE])
                    self._prev.set_image(self._next_prev_pixbufs[PREV])
                self._parent.check_audio_status()
                self._parent.check_text_status()
                self._prev.set_layer(1)
                self._next.set_layer(1)
        return False
示例#24
0
文件: mainmenu.py 项目: tyrylu/mpyw
def speak_indent(evt):
	line = appenv.policko.PositionToXY(appenv.policko.InsertionPoint)[1]
	text = appenv.policko.GetLineText(line)
	utils.speak(u"Úroveň {0}".format(utils.get_indent_level(text)))
from utils import speak, emotionPredict, openSongs, openMovieList
from audio_recorder import record

print("Welcome to the voice emotion recognition system")
speak("Welcome to the voice emotion recognition system")
speak("press 1 to start recording")
speak("press 2 to exit")

openSongs("hi")
option = int(input())
if option == 1:
    record()
    speak('Predicting the emotion')
    emotion = emotionPredict()
    speak(emotion)
    print('1. Recommend songs')
    print('2. Recommend movies')
    opt = int(input())
    if opt == 1:
        openSongs(emotion)
    else:
        openMovieList(emotion)
else:
    exit()
示例#26
0
文件: models.py 项目: shulinye/yoga
 def repCount(self) -> None:
     if getattr(self, 'countReps', None):
         utils.speak("How many reps?")
         return input("How many reps? ")
示例#27
0
文件: mainmenu.py 项目: tyrylu/mpyw
def speak_read_all(EVT):
	utils.speak(appenv.policko.Value)
示例#28
0
文件: mainmenu.py 项目: tyrylu/mpyw
def speak_read_to_end(evt):
	utils.speak(appenv.policko.GetRange(appenv.policko.InsertionPoint, appenv.policko.LastPosition))
示例#29
0
if __name__ == '__main__':
    words = model.words
    classes = model.classes

    training_model = TrainingModel(words, classes, model.data_x, model.data_y)
    trained_model = training_model.train()

    recognizer = sr.Recognizer()
    os = config.OS_NAME
    session = False
    while True:
        command = read_voice_cmd(recognizer)
        if command or command is not '':
            intent = training_model.get_intent(trained_model, command)
            response = TrainingModel.get_response(intent, config.DATA)
            print(intent, ' : ', response)

            if intent == 'greeting':
                utils.speak(response=response)
                session = True
            elif session and intent == 'applications':
                Applications(response).launch(command)
                session = False
            elif session and intent == 'youtube_search':
                YoutubeSearch(command, response).launch()
                session = False
            elif intent == 'alarm':
                Alarm(command, response).start()
            elif intent == 'translate':
                Translation(command).translate()
示例#30
0
def espis(opt, data):

    if "hi" in data or "hello" in data:
        speak(
            "Hey! I am ESPIS, or Extraordinarily Smart and Powerful Intelligent System, as the world would know me. How may I assist you?"
        )

    # intro
    elif "who are you" in data:
        # Extraordinarily Smart and Powerful Intelligent System
        speak(
            "My name is ESPIS, or Extraordinarily Smart and Powerful Intelligent System, as the world would know me. I have the solution to your every problem."
        )

    # intro
    elif "what can you do" in data:
        # Extraordinarily Smart and Powerful Intelligent System
        speak(
            "I can search for a movie in your laptop. Tell you the time. Show you any location. Play youtube music. Give you battery notifications. Give hourly news updates. And maintain a pretty good sense of humour throughout all this. What else do you need!"
        )

    elif ("who do you follow" in data or "who is your master" in data
          or "who invented you" in data):
        speak(
            "Mohit Pokharna! He is a very smart, highly intelligent and extremely charming person."
        )

    # greetings
    elif "how are you" in data:
        speak("Believe me when I say: Bhagwaan kasam, I am awesome!")

    # checking time
    elif "what time is it" in data:
        speak(
            "It is a good time for partying or eating a pizza or making a girlfriend. If you still wish to see the time as the world sees it, then the time is: "
            + ctime())

    # to see location on map
    elif "where is" in data:
        data = data.split(" ")
        for i in range(len(data) - 1):
            if data[i] == "where" and data[i + 1] == "is":
                location = data[i + 2]
        speak("Hold on, I will show you where " + location + " is.")
        os.system("firefox https://www.google.com/maps/place/" + location +
                  "/&amp;")

    # to see locations on map
    elif "show me" in data and "in" in data:
        data = data.split(" ")
        search = []
        initial = 10000
        for i, word in enumerate(data):
            if data[i] == "me":
                initial = i + 1
            if data[i] == "in":
                location = i + 1
        for i in range(len(data)):
            if i >= initial:
                search.append(data[i])
        searchlocation = ' '.join(search)
        speak("Hold on {}, I will show you ".format(opt.user) +
              searchlocation + ".")
        time.sleep(2)
        searchlocation = '+'.join(searchlocation.split(" "))
        os.system("firefox https://www.google.com/maps/search/" +
                  searchlocation)

    # check for movie
    elif "have this movie" in data:
        data = data.split(" ")
        mov_name = []
        flag = 0
        for i, word in enumerate(data):
            if word == "movie":
                mov_name_loc = i + 1
                flag = 1
                continue
            if flag == 1:
                mov_name.append(data[i])
        movie = ' '.join(mov_name)
        print(movie)
        speak("Hold on {}, I am searching for ".format(opt.user) + movie +
              ". You can grab a sandwich till then.")
        # right now only checking in Movies
        for root, dirs, files in os.walk('/home/{}/Downloads'.format(
                opt.user.lower())):
            for filename in files:
                if movie.lower() in filename.lower():
                    if root == "/home/{}/Downloads/Movies".format(
                            user.lower()):
                        root_word = "Downloads, Movies folder"
                    speak("Bingo the movie is located inside" + root)
                    flag = 2
                    break
        if flag == 1:
            speak(
                "Sorry {}, looks like you might need to use Netflix or F Movies!"
                .format(opt.user))

    # Youtube music
    elif opt.music_enabled or ("music" in data and "youtube" in data.lower()):
        speak("Do you have a particular mood?")
        if opt.audio:
            mood_reply = recordAudio()
        else:
            mood_reply = raw_input('\n>>')
        speak("Music mode on.")
        print(mood_reply)
        if "playlist" in mood_reply:
            play_playlist(mood_reply)
        elif "song" in mood_reply:
            play(mood_reply)
        elif opt.music != '':
            play(opt.music)
        else:
            play_random()

    else:
        speak("Sorry, your input could not be processed at this moment!")
示例#31
0
文件: main.py 项目: sumukhamh/tourbot
        sounds = utils.load_interaction(path+'narration.txt')
        for data in check_points:
            if(sounds[data['title']]):
                data['text']=sounds[data['title']]['text']
                data['funny']=sounds[data['title']]['funny']
            img=plt.imread(path+'images/'+data['title']+'.jpg')
            data['img']=img
        utils.speak('Welcome to the tour! It would be my pleasure to show you around! Please follow me')
        '''
        if (funny_flag):
            utils.open_file(path + 'videos_funny/start.mp4', 12)
        else:
            utils.open_file(path + 'videos_formal/start.mp4', 8)

        # Go to each checkpoint
        for check_point in check_points:
            success = navigator.goto(check_point, pub)
            if (not success):
                rospy.loginfo(
                    "Tour ended, The base failed to reach the desired pose")
                break

        # End of tour message
        rospy.loginfo("Tour completed!")
        utils.speak(
            'Tour complete, thank you! battery level is {} percentage'.format(
                battery_level))

    except rospy.ROSInterruptException:
        rospy.loginfo("Ctrl-C caught. Quitting")
示例#32
0
    global keys
    keys = defaultdict(int)

    if not os.path.exists(os.path.join(path,'settings.json')):
        setup()
    with open(os.path.join(path,'settings.json'), 'r') as f:
        settings = json.load(f)
    
    if os.path.exists(os.path.join(path,'keys.json')):
        with open(os.path.join(path,'keys.json'), 'r') as f:
            keys = json.load(f)
            keys = defaultdict(int, keys)
    
    if not os.path.exists(os.path.join(path,'models/nearest/theGrail.pkl')):
        utils.speak('Setting up. Please wait. This may take a while')
        os.system('./zoara.sh')

    global predictor
    predictor = loadPredicitonModel()

    global nearest
    nearest = loadNearestModel()
    nearestDepth = 1

    skills = setupSkills(os.path.join(path,'skillset'))

    for skill in skills:
        newTriggers = list()
        for trigger in skill['trigger']:
            words = trigger.split(' ')
示例#33
0
文件: mainmenu.py 项目: tyrylu/mpyw
def exit(evt):
	utils.promptsave()
	utils.speak(u"Nashledanou uživateli se jménem {0}. Doufám, že se ještě shledáme.".format(wx.GetUserName()))	
	appenv.app.ExitMainLoop()