示例#1
0
def FileFinder(file_name):
    file_name = hope(file_name)
    print(Back.YELLOW + Fore.BLACK + "[log] Recognized", file_name)
    try:
        Path = find_file_in_all_drives(file_name)
        os.startfile(Path)
    except:
        say("File not found")
示例#2
0
    def __correcto_cb(self, button, imagen1, imagen2, button1, button2, button3):
        parser = SafeConfigParser()
        parser.read('config.ini')
        
        if button.get_label() == parser.get('Pregunta' + str(self.indice), 'Respuesta'):
		    voice.say('Opcion correcta')
		    
		    if self.ITERACION == self.indice:
		           self.indice = 0
		    self.resetear(imagen1, imagen2, button1, button2, button3)
        else:
		    voice.say('Opcion incorrecta - Intente de nuevo')
示例#3
0
def execute_cmd(cmd):
    if 'время' in cmd:  #Time Mashine
        now = datetime.datetime.now()
        say("Now" + str(now.hour) + str(now.minute))
    elif 'найди' in cmd:  #Internet Browsing
        cmd = cmd.replace('найди', '')
        chrome(cmd)
    elif 'открой файл' in cmd:  #FileFinder (Need to rewrite!)
        cmd = cmd.replace('открой файл', '')
        FileFinder(cmd)
    elif 'запиши заметку' in cmd:  #Notepad
        say("I'm listening")
        UserText = ''
        while UserText != "конец":
            UserText += recognizer()
            notepad(UserText)
        sp.Popen(['notepad', "note.txt"])
    elif 'запусти' in cmd:  #StartApp
        cmd = cmd.replace('запусти ', '')
        try:
            StartApp(cmd)
        except:
            say("Program name not recognized")
    else:  #Internet Browsing
        chrome(cmd)
示例#4
0
文件: commands.py 项目: Aeva/voice
def say_command():
    """
    This is a wrapper for voice.say to enable a 'say' shell command.
    """

    bio = """
    This command provides a simple interface for various
    text-to-speech engines in GNU/Linux.
    """

    parser = argparse.ArgumentParser(description=bio)
    parser.add_argument(
        "message", metavar="message", type=str, nargs='?',
        default=get_input(), help="Message to be read aloud.")
    parser.add_argument(
        '--engine', metavar="engine", type=str, nargs=1, default="any",
        help="Override the default speech engine.")
    parser.add_argument(
        '--voice', metavar="voice", type=str, nargs=1, default="any",
        help="Override the default voice for the speech engine.")
    parser.add_argument(
        '--list-engines', default=False, action="store_true",
        help="List available speech engines.")
    parser.add_argument(
        '--list-voices', default=False, action="store_true",
        help="List available voices for the given or default engine.")
    parser.add_argument(
        '-e', default=False, action="store_true",
        help="Shorthand for --engine=espeak.")

    # parse args
    args = parser.parse_args()

    # string args
    message = clean_arg(args.message)
    use_engine, use_voice = engine_args(args)

    if message:
        voice.say(message, use_voice, use_engine)
示例#5
0
def upload(message):
    if message.chat.id == config.admin_chat:
        try:
            n = int(message.text[8:])
        except:
            bot.send_message(message.chat.id, 'enter number')
            return
        anekdots = aneks.get(n)

        number = 0
        errors = 0
        start = 3844
        for i in range(start, len(anekdots)):
            try:
                token = config.token_yandex[number]
                errors = 0
                files = open('ids.txt', 'a')
                file = say(anekdots[i], token)
                audio = open(file, 'rb')
                msg = bot.send_audio(message.chat.id, audio)
                print(msg.audio.file_id, file=files)
                files.close()
                path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                    file)
                os.remove(path)
                print(i, 'ready')
                time.sleep(1)
            except:
                bot.send_message(message.chat.id,
                                 'SOME STRANGE ERROR' + str(i))
                errors += 1
                if errors >= 5:
                    bot.send_message(
                        message.chat.id,
                        'OOOps, lots of errors, using the next token and sleeping 20 secs'
                    )
                    if number >= len(config.token_yandex):
                        bot.send_message(message.chat.id, 'no more tokens((')
                        files.close()
                        return
                    number += 1
                    time.sleep(20)
    else:
        bot.send_message(message.chat.id, 'You-re not admin')
def create_person():
    say('What is your name?')
    name = listen()
    name = name.split(' ')[-1]

    say('Let me get this right, your name is {}?'.format(name))
    if 'yes' in listen():
        say('Im going to scan your face for 20 seconds please remain still and remain in the frame'
            )

        capture_timer = Timer()

        settings['face-capture'] = True
        settings['username'] = name

        print(capture_timer.get_new_time())
        main()
示例#7
0
import voice

import speech_recognition as sr
r = sr.Recognizer()
r.energy_threshold = 1000

print("Listening...")
with sr.Microphone() as source:             # use the default microphone as the audio source
    audio = r.listen(source)                # listen for the first phrase and extract it into audio data

print("Received: %3.1f" % (len(audio.data) / float(audio.rate)))
try:
    print("Recognized:\n\n\t" + r.recognize(audio))  # recognize speech using Google Speech Recognition
    voice.say("OK, understood!")
except LookupError:
    print("Error: could not understand audio.")      # speech is unintelligible
    voice.say("Didn't quite catch that.")
示例#8
0
文件: commands.py 项目: Aeva/voice
def read_to_me():
    """
    Implements the "readtome" shell command.  Given a url and maybe
    something like an xpath query or just a dom id, the command will
    download the page and then read the contents.
    """

    bio = """
    Readtome is a tool for downloading a webpage and piping its textual
    content to a text-to-speech engine."""

    parser = argparse.ArgumentParser(description=bio)
    parser.add_argument(
        "url", metavar="url", type=str, nargs='?',
        help="Url to be read aloud.")
    parser.add_argument(
        '--id', metavar="dom_id", type=str, nargs=1, default="",
        help="Dom id to be used as the root element for reading from.")
    parser.add_argument(
        '--xpath', metavar="xpath", type=str, nargs=1, default="",
        help="Xpath query for the root element to read from.")
    parser.add_argument(
        '--engine', metavar="engine", type=str, nargs=1, default="any",
        help="Override the default speech engine.")
    parser.add_argument(
        '--voice', metavar="voice", type=str, nargs=1, default="any",
        help="Override the default voice for the speech engine.")
    parser.add_argument(
        '--list-engines', default=False, action="store_true",
        help="List available speech engines.")
    parser.add_argument(
        '--list-voices', default=False, action="store_true",
        help="List available voices for the given or default engine.")
    parser.add_argument(
        '-e', default=False, action="store_true",
        help="Shorthand for --engine=espeak.")

    # parse args
    args = parser.parse_args()

    # string args
    url = clean_arg(args.url)
    dom_id = clean_arg(args.id)
    xpath = clean_arg(args.xpath)
    use_engine, use_voice = engine_args(args)

    if not url:
        print "You must provide a url."
        exit()
        
    print "Downloading {0} ...".format(url)
    req = requests.get(url)
    if not req.status_code == requests.codes.ok:
        import httplib
        status_text = httplib.responses[req.status_code]
        print "Error {0}: {1}".format(req.status_code, status_text)
        exit()

    print "Parsing text from webpage..."
    dom = lxml.html.fromstring(req.text)
    read = ""

    if dom_id:
        query = "//*[@id='{0}']".format(dom_id)
        found = dom.xpath(query)
        if found:
            read = found[0].text_content().strip()
    elif xpath:
        found = dom.xpath(xpath)
        if found:
            read = found[0].text_content().strip()
    else:
        body = dom.find("body")
        read = body.text_content().strip()
    if read:
        print "Sending message to text-to-speech engine!"
        voice.say(read, use_voice, use_engine)
    else:
        print "Nothing to say :("
示例#9
0
def ideate():
    big_idea = idea.invent()
    print("NEW IDEA: \t" + big_idea)
    printer.output(big_idea)
    voice.say(big_idea)
示例#10
0
async def run_engine(uid, ws):
    game: GameObject = games[uid]
    board = game.board.copy()
    await start_engine(game, ws)
    if not game.should_run():
        return

    # Reset old arrows when engine is about to run
    game.arrows.clear()
    # print(board)
    limit: chess.engine.Limit = chess.engine.Limit()
    use_depth = settings.config.getboolean("gui", "use_depth")
    use_time = settings.config.getboolean("gui", "use_time")
    use_nodes = settings.config.getboolean("gui", "use_nodes")
    if use_depth:
        limit.depth = settings.config.getint("gui", "depth")
    if use_time:
        limit.time = settings.config.getfloat("gui", "time")
    if use_nodes:
        limit.nodes = settings.config.getint("gui", "nodes")

    if not use_depth and not use_time and not use_nodes:
        limit.depth = 8
        await ws.send(
            serialize_message("error",
                              "No limit set, using default depth of 8"))

    if settings.config.getboolean("gui", "clear_log"):
        try:
            debug_log_file = settings.engine_config.get(
                "engine", "debug log file")
            open(debug_log_file, "w").close()
        except Exception:
            pass

    # Set latest ECO for current board
    eco_name = eco.get_name(board.epd())
    if eco_name != "":
        game.eco = eco_name

    # Look for opening moves from books
    opening_moves = []
    if settings.config.getboolean("gui", "use_book"):
        bookfiles = books.load_books("books")
        for bookfile in bookfiles:
            read_book(bookfile, opening_moves, board, [], 0)

    if len(opening_moves) > 0:
        opening_moves = sorted(opening_moves,
                               key=lambda x: sum([y.weight for y in x]),
                               reverse=True)

        best_san = board.san(opening_moves[0][0].move)
        best_piece = chess.piece_name(
            board.piece_at(
                opening_moves[0][0].move.from_square).piece_type).capitalize()
        mate_in = None

        opening_dict = defaultdict(list)

        for move, *reply in opening_moves:
            reply = reply[0] if len(reply) > 0 else None
            raw_keys = [x.raw_move for x in opening_dict]
            raw_key = move.raw_move

            # If the raw has already been added
            if raw_key in raw_keys:
                # No need to do anything if there is no reply anyway
                if reply:
                    # Find the raw move and append reply to there instead
                    existing_key = None
                    for key in opening_dict:
                        if key.raw_move == raw_key:
                            existing_key = key
                    if existing_key:
                        # Check if the list contains raw_move of the reply already
                        raw_moves = [
                            x.raw_move for x in opening_dict[existing_key]
                        ]
                        raw_move = reply.raw_move
                        if raw_move not in raw_moves:
                            opening_dict[key].append(reply)
            else:
                if reply:
                    opening_dict[move].append(reply)
                else:
                    opening_dict[move] = []

        multi_pv = []
        list_index = 0
        for move, replies in opening_dict.items():
            list_index += 1
            score = move.weight
            pv = []
            lan = []
            pv.append(board.san(move.move))
            lan.append(board.lan(move.move))
            arrow = drawing.get_arrow(move.move, board.turn, 0)
            game.arrows[list_index].append(arrow)
            board.push(move.move)
            # Get EPD after the first push is moved
            epd = board.epd()
            opponents_turn = board.turn
            for reply in replies:
                pv.append(board.san(reply.move))
                lan.append(board.lan(reply.move))
                arrow = drawing.get_arrow(reply.move, opponents_turn, 1)
                game.arrows[list_index].append(arrow)
            # Unwind the move stack
            board.pop()
            line = {
                "multipv": list_index,
                "score": score,
                "pv": pv,
                "lan": lan,
                "eco": eco.get_name(epd),
            }

            multi_pv.append(line)
        await ws.send(
            serialize_message(
                "multipv", {
                    "multipv": multi_pv,
                    "turn": board.turn,
                    "current_eco": game.eco,
                    "book": True,
                    "best_piece": best_piece
                }))
    else:
        # If there no opening moves were found, use engine to analyse instead
        if game.engine is None:
            print(
                "Trying to analyse but engine has not been initialized, check engine path."
            )
            await ws.send(
                serialize_message(
                    "error",
                    "Trying to analyse but engine has not been initialized, check engine path."
                ))
            return

        multi_pv = settings.config.getint("gui", "multipv")
        print("Starting analysis with limit", limit, "for", multi_pv, "pv(s)")
        try:
            game.analysing = True
            results = await game.engine.analyse(board=board,
                                                limit=limit,
                                                multipv=multi_pv,
                                                game=uid,
                                                info=chess.engine.INFO_ALL)
        except Exception as err:
            print("Engine analysis failed.")
            if DEBUG:
                print(err)
            return
        finally:
            game.analysing = False

        if results is None or results[0] is None:
            print("Analysis stopped before results, returning...")
            return

        best_move = results[0].pv[0]
        best_san = board.san(best_move)
        best_piece = chess.piece_name(
            board.piece_at(best_move.from_square).piece_type).capitalize()
        mate_in = results[0].score.relative.moves if results[0].score.is_mate(
        ) else None

        multipv_data = []
        for multi_pv in results:
            move_counter = 0
            pv = []
            lan_pv = []
            epd = ""

            for index, move in enumerate(multi_pv.pv):
                san = board.san(move)
                lan = board.lan(move)
                arrow = drawing.get_arrow(move, board.turn, move_counter // 2)
                pv_index = 1 if multi_pv.multipv is None else multi_pv.multipv
                game.arrows[pv_index].append(arrow)

                pv.append(san)
                lan_pv.append(lan)
                board.push(move)

                # Get EPD for the first move
                if index == 0:
                    epd = board.epd()

                move_counter += 1

            for _ in range(move_counter):
                board.pop()

            if multi_pv.score.is_mate():
                score = "#" + str(multi_pv.score.relative.moves)
            else:
                score = multi_pv.score.relative.cp

            unit = {
                "multipv": multi_pv.multipv,
                "pv": pv,
                "lan": lan_pv,
                "score": score,
                "eco": eco.get_name(epd),
            }
            multipv_data.append(unit)
        await ws.send(
            serialize_message(
                "multipv",
                {
                    "multipv": multipv_data,
                    "turn": board.turn,
                    "current_eco": game.eco,
                    "book": False,
                    "best_piece": best_piece
                },
            ))

    if DEBUG:
        print(
            "Best move:", best_piece if settings.config.getboolean(
                "gui", "piece_only") else best_san)
        if mate_in is not None:
            print("Mate in", mate_in)

    if settings.config.getboolean("gui", "draw_board"):
        svg = drawing.draw_svg_board(game, 1)
        await ws.send(serialize_message("board", svg))

    if settings.config.getboolean("gui", "use_voice"):
        if settings.config.getboolean("gui", "piece_only"):
            voice.say(best_piece, True)
        else:
            voice.say(best_san, False)
    game.missed_moves = False
示例#11
0
def start_workout(min=5, max=10):
    number = random.randint(min, max)
    print(number)
    voice.say("You are going to do " + str(number) + " pushups")
    time.sleep(.5)
    voice.say("Three")
    time.sleep(1.9)
    voice.say("Two")
    time.sleep(1.9)
    voice.say("One")
    time.sleep(1.9)
    voice.say("Go!")

    
    #print("This is your robot coach. Lets do some pushups")
    #min = int(raw_input("Enter the minimum amount of pushups you are willing to do\n"))
    #max = int(raw_input("Enter the maximum amount of pushups you are willing to do\n"))
    for i in range(number):
            robot.forward()
            time.sleep(.4)
            robot.stop()
            robot.backward()
            time.sleep(.5)
            robot.stop()
            time.sleep(1)
            voice.say(str(i+1))
示例#12
0
 def __sobre_boton_cb(self, button):
     voice.say(button.get_label())
示例#13
0
def answer_positively(question, answer):
    voice.say(answer)
    voice.say(question["a"][answer])
    say_do_another()
示例#14
0
def answer_negatively(question, answer):
    voice.say(answer)
    if answer in question["incorrect"]:
        voice.say(question["incorrect"][answer])
    else:
        voice.say(question["incorrect"]["default"])
示例#15
0
def say_question():
    global question_last_said
    question_last_said = calendar.timegm(time.gmtime())
    voice.say(current_question["q"])
示例#16
0
def register():
    say('I see a person but I dont quiet know who you are...')
    say('Would you like me to remember you?')
    if 'yes' in listen():
        create_person()
示例#17
0
import serial
import voice
import time
import socket
from datetime import datetime
TCP_IP='localhost'
TCP_PORT = 3007

sock = socket.socket(socket.AF_INET,
							socket.SOCK_STREAM)
#sock.connect((TCP_IP, TCP_PORT));
#buffer = 1024


while(True):
    current = datetime.now().hour
    if(current == 3):
        #play()
        voice.say("Wakeup Collin.") 
        voice.say("Its time to build me")


示例#18
0
import voice

import speech_recognition as sr
r = sr.Recognizer()
r.energy_threshold = 1000

print("Listening...")
with sr.Microphone(
) as source:  # use the default microphone as the audio source
    audio = r.listen(
        source)  # listen for the first phrase and extract it into audio data

print("Received: %3.1f" % (len(audio.data) / float(audio.rate)))
try:
    print(
        "Recognized:\n\n\t" +
        r.recognize(audio))  # recognize speech using Google Speech Recognition
    voice.say("OK, understood!")
except LookupError:
    print("Error: could not understand audio.")  # speech is unintelligible
    voice.say("Didn't quite catch that.")