Esempio n. 1
0
    def StartTracking(self):
        print('Starting Tracker')

        self.ProcessDelay = QTimer()
        self.ProcessDelay.timeout.connect(self.ShowMousePosition)

        try:

            self.ProcessDelay.start(500)
            while self.ContinueProcessing:
                x, y = pyautogui.position()

                self.strPositn = ''
                self.strPositn += 'Mouse X: '
                self.strPositn += str(x).rjust(4)
                self.strPositn += ' Mouse Y: '
                self.strPositn += str(y).rjust(4)

                QCoreApplication.processEvents()

                time.sleep(0.750)
                if self.EndProcess:

                    self.ProcessDelay.stop()
                    self.ContinueProcessing = False
        except KeyboardInterrupt:

            print('Error Occurred Program Aborting')
Esempio n. 2
0
    def getSerialAck(self):
        string = ""
        succeeded = False

        self.serialState = SerialState.WaitingToStart
        currentSerialString = ""
        currentCheckSum = bytearray(2)

        while(self.serialTimeoutTimer.remainingTime()>0):
            QCoreApplication.processEvents()
            self.processCheckStopRequest()
            if self.serialState == SerialState.WaitingToStart:
                newByte = self.serialPort.read()
                if len(newByte) == 1:
                    if newByte[0] == STARTING_BYTE:
                        self.serialState = SerialState.WaitingForString
            
            if self.serialState == SerialState.WaitingForString:
                newBytes = self.serialPort.read_until(b'\0')
                if len(newBytes) >= 1:
                    for i in range (len(newBytes)):
                        if newBytes[i] == STARTING_BYTE:
                            pass
                        else:
                            currentSerialString = currentSerialString + newBytes[i:].decode("utf-8")
                            if newBytes[-1] == 0x00:
                                self.serialState = SerialState.WaitingForChecksum1
                            break
            
            if self.serialState == SerialState.WaitingForChecksum1:
                newByte = self.serialPort.read()
                if len(newByte) == 1:
                    currentCheckSum[0] = newByte[0]
                    self.serialState = SerialState.WaitingForChecksum2
                
            if self.serialState == SerialState.WaitingForChecksum2:
                newByte = self.serialPort.read()
                if len(newByte) == 1:
                    currentCheckSum[1] = newByte[0]
                    self.serialState = SerialState.CommandDone

            if self.serialState == SerialState.CommandDone:
                # check the message integrity
                receivedCommandCrc = Crc16()
                receivedCommandCrc.process(currentSerialString.encode('utf-8'))
                receivedCommandCrcBytes = receivedCommandCrc.finalbytes()
                
                # print("Checksum Calc based on {}".format(currentSerialString.encode('utf-8')))
                # print("Checksum Received: {}, Calculated: {}".format(currentCheckSum, receivedCommandCrcBytes))
                if receivedCommandCrcBytes == currentCheckSum:
                    succeeded = True
                    string = currentSerialString.split(":")[1].rstrip(' \t\r\n\0')
                    if string == "None":
                        string = ""
                else:
                    self.log("Acknowledgment Failed, received: {}".format(currentSerialString.rstrip("\t\r\n\0")), type="ERROR")
                    string = currentSerialString
                break

        return succeeded, string
Esempio n. 3
0
    def on_perform_clicked(self):
        if self.__dataset is None:
            self.show_error(self.tr("Dataset has not been loaded."))
            return

        self.perform_button.setEnabled(False)
        self.perform_with_customized_ems_button.setEnabled(False)
        resolver = EMMAResolver()
        resolver_setting = self.neural_setting.setting
        results = []
        n_members_list = self.n_members_list
        self.progress_bar.setRange(0, len(n_members_list))
        self.progress_bar.setValue(0)
        self.progress_bar.setFormat(self.tr("Performing EMMA [%v/%m]"))
        QCoreApplication.processEvents()
        for i, n_members in enumerate(n_members_list):
            result = resolver.try_fit(self.__dataset, self.distribution_type,
                                      n_members, resolver_setting)
            results.append(result)
            self.progress_bar.setValue(i + 1)
            QCoreApplication.processEvents()

        self.add_results(results)
        self.progress_bar.setFormat(self.tr("Finished"))
        self.perform_button.setEnabled(True)
        self.perform_with_customized_ems_button.setEnabled(True)
        if len(results) > 1:
            self.emma_summary_chart.show_distances(results)
            self.emma_summary_chart.show()
Esempio n. 4
0
    def __init__(self, soundfile, parent):
        self.soundfile = soundfile
        self.isplaying = False
        self.time = 0  # current audio position in frames
        self.audio = QMediaPlayer()
        self.decoder = QAudioDecoder()
        self.is_loaded = False
        self.volume = 100
        self.isplaying = False
        self.decoded_audio = {}
        self.only_samples = []
        self.decoding_is_finished = False
        self.max_bits = 32768
        self.signed = False
        # File Loading is Asynchronous, so we need to be creative here, doesn't need to be duration but it works
        self.audio.durationChanged.connect(self.on_durationChanged)
        self.decoder.finished.connect(self.decode_finished_signal)
        self.audio.setMedia(QUrl.fromLocalFile(soundfile))
        self.decoder.setSourceFilename(soundfile)  # strangely inconsistent file-handling
        # It will hang here forever if we don't process the events.
        while not self.is_loaded:
            QCoreApplication.processEvents()
            time.sleep(0.1)

        self.decode_audio()
        self.np_data = np.array(self.only_samples)
        if not self.signed:  # don't ask me why this fixes 8 bit samples...
            self.np_data = self.np_data - self.max_bits / 2
        print(len(self.only_samples))
        print(self.max_bits)
        self.isvalid = True
Esempio n. 5
0
 def stop(self):
     """
     Perform stop operation
     :return: None
     """
     logger.internal("entering stop operation, old state %s",
                     FilterState.state2str(self._state))
     assertMainThread()
     while self._operationInProgress and self._state != FilterState.ACTIVE:
         QCoreApplication.processEvents()
     if self._state != FilterState.ACTIVE:
         logger.warning("Unexpected state %s",
                        FilterState.state2str(self._state))
         raise FilterStateMachineError(self._state, FilterState.STOPPING)
     self._operationInProgress = True
     self._state = FilterState.STOPPING
     for itc in self._interThreadConns:
         # set connections in active mode.
         itc.setStopped(True)
     self.performOperation.emit("stop", Barrier(len(self._threads)))
     while self._state == FilterState.STOPPING:
         logger.internal("stopping ... %s",
                         FilterState.state2str(self._state))
         QCoreApplication.processEvents()
     self._operationInProgress = False
     logger.internal("leaving stop operation, new state %s",
                     FilterState.state2str(self._state))
Esempio n. 6
0
    async def KEAlive(self, finishedState):
        while finishedState.is_set():
            QCoreApplication.processEvents()
            trio.sleep(0.1)
        return

        return
Esempio n. 7
0
def waitForSignal(signal, callback=None, timeout=None):
    """
    Waits for the given signal. If a callback is given, it will be called with the signal's arguments until the
    return value of the callback evaluates to true. If a timeout is given (in seconds), a TimeoutError will be
    thrown after the time has elapsed.
    :param signal: a Qt signal to be waited for, suitable for slot connections.
    :param callback: a callable called
    :param timeout: an optional timeout in seconds.
    :return: None
    """
    _received = False
    _sigArgs = None
    def _slot(*args, **kw):
        nonlocal _received, _sigArgs
        _sigArgs = args
        if callback is None:
            _received = True
        else:
            if callback(*args, **kw):
                _received = True
    if not signal.connect(_slot, Qt.QueuedConnection):
        raise NexTInternalError("cannot connect the signal.")
    t0 = time.perf_counter()
    while not _received:
        QCoreApplication.processEvents()
        if timeout is not None and time.perf_counter() - t0 > timeout:
            signal.disconnect(_slot)
            raise TimeoutError()
    signal.disconnect(_slot)
    return _sigArgs
Esempio n. 8
0
    def compute_map(self):
        if self.map is None:
            start = time()
            self.map_button.setText(
                self.tr('Computing heatmap, please wait...'))
            modify_font(self.map_button, bold=False, italic=True)
            QCoreApplication.processEvents()

            mapp, valid, range0, range1, imgsize, other = noiseprint_blind_post(
                self.noise, self.image0)
            if mapp is None:
                QMessageBox.critical(self, self.tr('Error'),
                                     self.tr('Too many invalid blocks!'))
                return
            self.map = cv.applyColorMap(
                genMappUint8(mapp, valid, range0, range1, imgsize),
                cv.COLORMAP_JET)
            self.map_viewer.update_processed(self.map)
            elapsed = time() - start

            self.map_button.setText(
                self.tr('Heatmap computed ({:.1f} s)'.format(elapsed)))
            modify_font(self.map_button, bold=False, italic=False)
            self.map_button.setCheckable(True)
        self.map_button.setChecked(True)
        self.noise_viewer.viewChanged.connect(self.map_viewer.changeView)
        self.map_viewer.viewChanged.connect(self.noise_viewer.changeView)
Esempio n. 9
0
 def test_execute_forward_archives_output_files(self):
     with TemporaryDirectory() as temp_dir:
         script_dir = pathlib.Path(temp_dir, "scripts")
         script_dir.mkdir()
         script_file_name = self._write_output_script(script_dir)
         script_files = [script_file_name]
         output_files = ["out.dat", "subdir/out.txt"]
         app_settings = _MockSettings()
         logger = mock.MagicMock()
         tool_specification = PythonTool(
             "Python tool",
             "Python",
             str(script_dir),
             script_files,
             app_settings,
             None,
             logger,
             outputfiles=output_files,
         )
         work_dir = pathlib.Path(temp_dir, "work")
         work_dir.mkdir()
         archive_dir = pathlib.Path(temp_dir, "archive")
         archive_dir.mkdir()
         executable = ExecutableItem("Create files", str(work_dir),
                                     str(archive_dir), tool_specification,
                                     [], logger)
         executable.execute([], ExecutionDirection.FORWARD)
         while executable._tool_instance is not None:
             QCoreApplication.processEvents()
         archives = list(archive_dir.iterdir())
         self.assertEqual(len(archives), 1)
         self.assertNotEqual(archives[0].name, "failed")
         self.assertTrue(pathlib.Path(archives[0], "out.dat").exists())
         self.assertTrue(
             pathlib.Path(archives[0], "subdir", "out.txt").exists())
Esempio n. 10
0
def get_dirnames(app=None):

    from PySide2.QtCore import Qt, QCoreApplication
    from PySide2.QtWidgets import QApplication, QFileDialog, QTreeView, QListView, QAbstractItemView
    from pathlib import Path

    if not app:
        app = QApplication(sys.argv)
    # file_dialog = QFileDialog()
    # file_dialog.setWindowFlags(Qt.WindowStaysOnTopHint)
    # file_location = file_dialog.getOpenFileNames()

    file_dialog = QFileDialog()
    file_dialog.setFileMode(QFileDialog.DirectoryOnly)
    file_dialog.setOption(QFileDialog.DontUseNativeDialog, True)
    file_view = file_dialog.findChild(QListView, 'listView')

    # to make it possible to select multiple directories:
    if file_view:
        file_view.setSelectionMode(QAbstractItemView.MultiSelection)
    f_tree_view = file_dialog.findChild(QTreeView)
    if f_tree_view:
        f_tree_view.setSelectionMode(QAbstractItemView.MultiSelection)

    if file_dialog.exec():
        paths = file_dialog.selectedFiles()

        QCoreApplication.processEvents()
        for path in paths:
            yield Path(path)
Esempio n. 11
0
def async_run_await_result(function, *args, **kwargs):
    future_obj = thread_pool.submit(function, *args, **kwargs)
    while not future_obj.done():
        QCoreApplication.processEvents()
        time.sleep(0.1)
    future_result = future_obj.result()
    return future_result
Esempio n. 12
0
 def _sendCommand(self, command, payload, timeout=SERIAL_COMMAND_TIMEOUT, max_retry=SERIAL_COMMAND_MAX_TRIALS):
     if not command in SERIAL_COMMANDS:
         print("The command provided {} is not a valid serial command".format(command))
         return FAILURE_CODE
     sendBuffer = bytearray()
     sendBuffer.append(STARTING_BYTE)
     sendString = command + ":" + payload
     sendBuffer.extend(sendString.encode("utf-8"))
     sendBuffer.append(0x00)
     newChecksum = Crc16()
     # print("Checksum Calc based on {}".format(sendBuffer[1:]))
     newChecksum.process(sendBuffer[1:])
     checksumBytes = newChecksum.finalbytes()
     sendBuffer.extend(checksumBytes)
     # print(len(sendBuffer))
     for attempt in range(max_retry):
         if attempt != 0:
             self.log(f"Attempt #{attempt+1} to send the command {command} with payload {payload}", type="DEBUG")
             QCoreApplication.processEvents()
         # t = time.time()
         try:
             self.serialPort.flushInput()
             self.serialPort.write(sendBuffer)
         except SerialTimeoutException:
             self.serialPort.flushOutput()
             continue
         self.serialTimeoutTimer.setInterval(timeout)
         self.serialTimeoutTimer.start()
         succeeded, string = self.getSerialAck()
         # print("The time spent from sending a command to receiving a reply (or timeouting) is ",time.time()-t)
         if succeeded:
             return string
         elif not succeeded and "EXCEPTION" in string:
             break 
     return FAILURE_CODE
Esempio n. 13
0
 def save_callback(i, n):
     if progress.wasCanceled():
         nonlocal canceled
         canceled = True
         raise StopIteration()
     progress.setValue((i+1)/n*100)
     QCoreApplication.processEvents()
Esempio n. 14
0
 def updateStatus(self, status, isError=False):
     newLine = QLabel(('ERROR' if isError else 'STATUS') + f': {status}')
     newLine.setWordWrap(True)
     self.statusText.addWidget(newLine)
     self.statusWidget.setLayout(self.statusText)
     QCoreApplication.processEvents()
     QCoreApplication.processEvents()
     self.statusTextScroll.verticalScrollBar().setValue(self.statusTextScroll.verticalScrollBar().maximum() + 1)
Esempio n. 15
0
    def rerender_wppf(self):
        HexrdConfig().wppf_data = list(self.wppf_object.spectrum_sim.data)
        HexrdConfig().rerender_wppf.emit()

        # Process events to make sure it visually updates.
        # If this causes issues, we can post self.wppf_object.RefineCycle()
        # calls to the event loop in the future instead.
        QCoreApplication.processEvents()
Esempio n. 16
0
 async def pullOutput(self, proc):
     x = await proc.stdout.receive_some()
     x = x.decode()
     result = ''
     while (x != ''):
         QCoreApplication.processEvents()
         result = result + x
         x = await proc.stdout.receive_some()
         x = x.decode()
     return result
Esempio n. 17
0
    def on_shotgun_export(self, sg_password: str):
        """on_shotgun_export will export a the latest sequence revision to
        shotgun. Will first retrieve all the media info per shots from flix_ui,
        and will start creating or reusing projects / sequence / shots and version per shot from
        shotgun_ui, It will then export a quicktime per shot from flix_ui and will upload it to shotgun

        Arguments:
            sg_password {str} -- Shotgun password
        """
        if self.wg_flix_ui.is_authenticated() is False:
            self.__error('you need to be authenticated to Flix')
            return

        self.__init_progress(2)

        try:
            self.__update_progress('get media object per shots', False)
            mo_per_shots = self.wg_flix_ui.get_media_object_per_shots(
                self.__update_progress)
            if mo_per_shots is None:
                return

            self.progress.setRange(0, 2 + len(mo_per_shots) * 2)
            self.progress.repaint()
            QCoreApplication.processEvents()

            _, _, show_tc = self.wg_flix_ui.get_selected_show()
            _, seq_rev_nbr, seq_tc = self.wg_flix_ui.get_selected_sequence()
            # Create project / sequence / shot and version in Shotgun
            self.__update_progress('push to shotgun', False)
            shot_to_file = self.wg_shotgun_ui.export_to_version(
                mo_per_shots.keys(), sg_password, show_tc, seq_rev_nbr, seq_tc,
                self.__update_progress)

            temp_folder = tempfile.gettempdir()
            for shot in shot_to_file:
                self.__update_progress(
                    'download quicktime for shot {0}'.format(shot), False)
                mov_path = os.path.join(temp_folder,
                                        shot_to_file[shot]['mov_name'])
                if sys.platform == 'win32' or sys.platform == 'cygwin':
                    mov_path = mov_path.replace('\\', '\\\\')
                # Download quictime from Flix
                self.wg_flix_ui.get_flix_api().download_media_object(
                    mov_path, mo_per_shots[shot].get('mov'))
                # Upload quicktime to shotgun version
                self.__update_progress(
                    'upload quicktime to shotgun for shot {0}'.format(shot),
                    False)
                self.wg_shotgun_ui.get_shotgun_api().upload_movie(
                    shot_to_file[shot]['version'], mov_path)
        except progress_canceled:
            print('progress cancelled')
            return
        self.__info('Latest sequence revision exported to shotgun')
Esempio n. 18
0
 def decode_audio(self):
     self.decoder.start()
     while not self.decoding_is_finished:
         QCoreApplication.processEvents()
         if self.decoder.bufferAvailable():
             tempdata = self.decoder.read()
             # We use the Pointer Address to get a cffi Pointer to the data (hopefully)
             cast_data = self.audioformat_to_datatype(tempdata.format())
             possible_data = ffi.cast("{1}[{0}]".format(tempdata.sampleCount(), cast_data), int(tempdata.constData()))
             self.only_samples.extend(possible_data)
             self.decoded_audio[self.decoder.position()] = [possible_data, len(possible_data), tempdata.byteCount(), tempdata.format()]
Esempio n. 19
0
 def _wait_for_segment_end(self, newstart, newlength):
     start = newstart * 1000.0
     length = newlength * 1000.0
     end = start + length
     while self.audio.position() < end:
         if not self.isplaying:
             return 0
         QCoreApplication.processEvents()
         time.sleep(0.001)
     self.audio.stop()
     self.isplaying = False
Esempio n. 20
0
 def start_simulation(self):
     for i in range(1, (self.settings_bridge.epochs + 1)):
         self.epoch_bridge.epoch = i
         for j in range(101):
             self.epoch_bridge.progress = j
             QCoreApplication.processEvents()
             time.sleep(0.01)
         self.epoch_bridge.test_accuracy = min((i * i) * 3.978, 100)
         self.epoch_bridge.test_loss = 1 / i
         self.epoch_done.emit(self.epoch_bridge.epoch,
                              self.epoch_bridge.test_loss)
         print('This is gonna be a longer Log message. Epoch ' + str(i) +
               ' done')
Esempio n. 21
0
 def _wait_for_segment_end(self, newstart, newlength):
     start = newstart * 1000.0
     length = newlength * 1000.0
     end = start + length
     print(start)
     print(length)
     print(end)
     while self.audio.position() < end:
         QCoreApplication.processEvents()
         print(self.audio.position())
         time.sleep(0.001)
     self.audio.stop()
     self.isplaying = False
Esempio n. 22
0
    def __init__(self, soundfile, parent):
        self.soundfile = soundfile
        self.isplaying = False
        self.time = 0  # current audio position in frames
        self.audio = QMediaPlayer()
        self.is_loaded = False
        self.volume = 100
        self.isplaying = False
        self.max_bits = 32768
        # File Loading is Asynchronous, so we need to be creative here, doesn't need to be duration but it works
        self.audio.durationChanged.connect(self.on_durationChanged)
        # self.decoder.finished.connect(self.decode_finished_signal)
        self.audio.setMedia(QUrl.fromLocalFile(soundfile))
        # self.decoder.setSourceFilename(soundfile)  # strangely inconsistent file-handling
        # It will hang here forever if we don't process the events.
        while not self.is_loaded:
            QCoreApplication.processEvents()
            time.sleep(0.1)

        self.isvalid = True
        self.pydubfile = None
        if AudioSegment:
            if which("ffmpeg") is not None:
                AudioSegment.converter = which("ffmpeg")
            elif which("avconv") is not None:
                AudioSegment.converter = which("avconv")
            else:
                if platform.system() == "Windows":
                    AudioSegment.converter = os.path.join(
                        get_main_dir(), "ffmpeg.exe")
                    # AudioSegment.converter = os.path.dirname(os.path.realpath(__file__)) + "\\ffmpeg.exe"
                else:
                    # TODO: Check if we have ffmpeg or avconv installed
                    AudioSegment.converter = "ffmpeg"

        try:
            if AudioSegment:
                print(self.soundfile)
                self.pydubfile = AudioSegment.from_file(
                    self.soundfile,
                    format=os.path.splitext(self.soundfile)[1][1:])
            else:
                self.wave_reference = wave.open(self.soundfile)

            self.isvalid = True

        except:
            traceback.print_exc()
            self.wave_reference = None
            self.isvalid = False
Esempio n. 23
0
 def show_pairing(self, code: str, device_response: Callable[[], bool]) -> bool:
     dialog = BitBox02PairingDialog(code, device_response)
     dialog.show()
     # render the window since the next operation is blocking
     while True:
         QCoreApplication.processEvents()
         if dialog.painted:
             break
         time.sleep(0.1)
     if not device_response():
         return False
     dialog.enable_buttons()
     dialog.exec_()
     return dialog.result() == QDialog.Accepted
Esempio n. 24
0
        def multiThreadUIMain():
            # 这里采用了一个deepcopy的对象去做另一线程,该线程不涉及任何类的修改操作
            # 这样做很不值得,但是如果在另一线程中使用self.vs会因为线程锁定而无法被pickle存储,即使线程已经关闭
            jc = copy.deepcopy(self.job_config)

            class SJT(QThread):
                def __init__(self, job_submit_confg, *args):
                    super().__init__()
                    self.status = None
                    self.jc = job_submit_confg
                    self.args = args

                def run(self):
                    self.status = self.jc.submit_job(self.args)

            thread = SJT(jc, self.selected_items)
            thread.start()
            #QMessageBox.information(self.main_window, "提示", "任务提交中......")
            error_msg = "任务提交失败,请检查\n1:服务器路径设置是否正确\n2:各文件路径是否有效\n3:Key Library是否按照说明书要求设置"
            while True:
                q = thread.status
                if q == None:
                    QCoreApplication.processEvents()
                    continue
                elif q == 1:
                    try:
                        # 提交成功才更新节点信息
                        thread.quit()
                        thread.wait()
                        del thread

                        info = jc.update_XVI_nodel_info()
                        if info == False:
                            QMessageBox.information(self.main_window, "提示",
                                                    "节点信息获取失败")
                        self.vsp.update_xvi_item_info()
                        self.update_xsd_files_information()

                        QMessageBox.information(self.main_window, '提示',
                                                "任务已提交,若获取到任务节点信息即为提交成功")
                        return
                    except:
                        traceback.print_exc()
                        QMessageBox.critical(self.main_window, "错误", error_msg)
                        return

                elif q == 0:
                    QMessageBox.critical(self.main_window, "错误", error_msg)
                    return
Esempio n. 25
0
 def create(self):
     """
     Perform create operation
     :return:None
     """
     assertMainThread()
     while self._operationInProgress and self._state != FilterState.CONSTRUCTING:
         QCoreApplication.processEvents()
     if self._state != FilterState.CONSTRUCTING:
         raise FilterStateMachineError(self._state,
                                       FilterState.CONSTRUCTING)
     self._operationInProgress = True
     self.performOperation.emit("create", Barrier(len(self._threads)))
     while self._state == FilterState.CONSTRUCTING:
         QCoreApplication.processEvents()
     self._operationInProgress = False
Esempio n. 26
0
    def closeEvent(self, event):
        Logger().debug("Chiusura applicazione")

        if isinstance(self.obs, Observer):
            if self.obs.isAlive():
                Logger().info("Chiusura Observer")
                self.obs.stop()
                self.obs.join()
                Logger().info("Observer thread terminato")

        res = QMetaObject.invokeMethod(self.tailer, "stopProcess",
                                       Qt.BlockingQueuedConnection)
        QCoreApplication.processEvents()
        self.tailer.thread().wait()
        Logger().debug("Tailer listener thread terminato")
        super(MainWindow, self).closeEvent(event)
Esempio n. 27
0
    def __init__(self, soundfile, parent):
        self.soundfile = soundfile
        self.isplaying = False
        self.time = 0  # current audio position in frames
        self.audio = QMediaPlayer()
        self.is_loaded = False
        self.volume = 100
        self.isplaying = False
        self.max_bits = 32768
        # File Loading is Asynchronous, so we need to be creative here, doesn't need to be duration but it works
        self.audio.durationChanged.connect(self.on_durationChanged)
        # self.decoder.finished.connect(self.decode_finished_signal)
        self.audio.setMedia(QUrl.fromLocalFile(soundfile))
        # self.decoder.setSourceFilename(soundfile)  # strangely inconsistent file-handling
        # It will hang here forever if we don't process the events.
        self.audio_file = audioread.audio_open(self.soundfile)
        self.audio_data = []
        for buf in self.audio_file:
            self.audio_data.extend(
                struct.unpack("<{}H".format(int(len(list(buf)) / 2)), buf))
        print(self.audio_data)
        print(len(self.audio_data))
        print(len(self.audio_data) / self.audio_file.samplerate)
        print(self.audio_file.duration)
        print(self.audio_file.channels)
        print("DATAEND")
        while not self.is_loaded:
            QCoreApplication.processEvents()
            time.sleep(0.1)

        self.isvalid = True
        self.pydubfile = None
        if AudioSegment:
            if which("ffmpeg") is not None:
                AudioSegment.converter = which("ffmpeg")
            elif which("avconv") is not None:
                AudioSegment.converter = which("avconv")
            else:
                if platform.system() == "Windows":
                    AudioSegment.converter = os.path.join(
                        get_main_dir(), "ffmpeg.exe")
                    # AudioSegment.converter = os.path.dirname(os.path.realpath(__file__)) + "\\ffmpeg.exe"
                else:
                    # TODO: Check if we have ffmpeg or avconv installed
                    AudioSegment.converter = "ffmpeg"

        self.isvalid = True
Esempio n. 28
0
    def display(self, msg=None, pos=None):
        format_dict = self.format_dict
        elapsed_str = self.format_interval(format_dict['elapsed'])

        rate = format_dict['rate']
        remaining = (self.total - self.n) / rate if rate and self.total else 0
        remaining_str = self.format_interval(remaining) if rate else '??:??'

        time_str = f'Time remaining:\t{remaining_str}\nTime elapsed:\t{elapsed_str}'

        if not self._cancel_event.is_set():
            self.dialog.setMaximum(self.total)
            if self.postfix:
                self.dialog.setLabelText(time_str + '\n\n' + self.postfix)
            else:
                self.dialog.setLabelText(time_str)
            self.dialog.setValue(self.n)
        QCoreApplication.processEvents()
Esempio n. 29
0
def get_dirname(app=None):

    from PySide2.QtCore import Qt, QCoreApplication
    from PySide2.QtWidgets import QApplication, QFileDialog
    from pathlib import Path

    app = QApplication(sys.argv)
    file_dialog = QFileDialog()
    file_dialog.setWindowFlags(Qt.WindowStaysOnTopHint)
    file_location = file_dialog.getExistingDirectory()

    if file_location:
        QCoreApplication.processEvents()
        return Path(file_location)

    else:

        return None
Esempio n. 30
0
 def decode_audio(self):
     self.decoder.start()
     while not self.decoding_is_finished:
         QCoreApplication.processEvents()
         if self.decoder.bufferAvailable():
             tempdata = self.decoder.read()
             # We use the Pointer Address to get a cffi Pointer to the data (hopefully)
             cast_data = self.audioformat_to_datatype(tempdata.format())
             possible_data = ffi.cast(
                 "{1}[{0}]".format(tempdata.sampleCount(), cast_data),
                 int(tempdata.constData()))
             self.only_samples.extend(possible_data)
             self.decoded_audio[self.decoder.position()] = [
                 possible_data,
                 len(possible_data),
                 tempdata.byteCount(),
                 tempdata.format()
             ]
Esempio n. 31
0
    def __init__(self, soundfile, parent):
        self.soundfile = soundfile
        self.isplaying = False
        self.time = 0  # current audio position in frames
        self.audio = QMediaPlayer()
        self.decoder = QAudioDecoder()
        self.is_loaded = False
        self.volume = 100
        self.isplaying = False
        self.decoded_audio = {}
        self.only_samples = []
        self.decoding_is_finished = False
        self.max_bits = 32768
        self.signed = False
        # File Loading is Asynchronous, so we need to be creative here, doesn't need to be duration but it works
        self.audio.durationChanged.connect(self.on_durationChanged)
        self.decoder.finished.connect(self.decode_finished_signal)
        self.audio.setMedia(QUrl.fromLocalFile(soundfile))
        self.decoder.setSourceFilename(
            soundfile)  # strangely inconsistent file-handling
        self.top_level_widget = None

        for widget in QtWidgets.QApplication.topLevelWidgets():
            if "lip_sync_frame" in dir(widget):
                self.top_level_widget = widget
        self.top_level_widget.lip_sync_frame.status_progress.show()
        self.top_level_widget.lip_sync_frame.status_progress.reset()
        self.top_level_widget.lip_sync_frame.status_progress.setMinimum(0)
        self.top_level_widget.lip_sync_frame.status_progress.setMaximum(0)
        # It will hang here forever if we don't process the events.
        while not self.is_loaded:
            QCoreApplication.processEvents()
            time.sleep(0.01)
        self.top_level_widget.lip_sync_frame.status_progress.setMaximum(
            self.decoder.duration())
        self.decode_audio(
            self.top_level_widget.lip_sync_frame.status_bar_progress)
        self.top_level_widget.lip_sync_frame.status_progress.hide()
        self.np_data = np.array(self.only_samples)
        if not self.signed:  # don't ask me why this fixes 8 bit samples...
            self.np_data = self.np_data - self.max_bits / 2
        print(len(self.only_samples))
        print(self.max_bits)
        self.isvalid = True
Esempio n. 32
0
    def __update_progress(self, message: str, skip_step: bool = True):
        """update_progress will update the progress message
        and will return False if the progress is 'canceled' by the user

        Arguments:
            message {str} -- Message to show in the progress

            skip_step {bool} -- Will skip the step (default: {True})
        """
        next_value = self.progress_start
        if skip_step is False:
            next_value = next_value + 1
        self.progress_start = next_value
        self.progress.setValue(next_value)
        self.progress.setLabelText(message)
        self.progress.repaint()
        QCoreApplication.processEvents()
        if self.progress.wasCanceled():
            raise progress_canceled
Esempio n. 33
0
    def on_show_all_clicked(self):
        if self.n_clusters > 20:
            self.show_warning(
                self.
                tr("N_clusters is greater than 20, it will generate too much windows on your screen."
                   ))

        dataset, X, linkage_matrix, dendrogram_res = self.__last_result
        flags = fcluster(linkage_matrix, self.n_clusters, criterion="maxclust")
        flag_set = set(flags)
        rect = QApplication.primaryScreen().availableGeometry()
        x0 = rect.x()
        y0 = rect.y()
        max_w = rect.width()
        max_h = rect.height()
        span = 20
        epoch = 0
        w = 400
        h = 300
        x = x0 + epoch % 10 * 20 + span
        y = y0 + epoch % 10 * 20 + span
        span = 20
        for flag in flag_set:
            samples = []
            for sample, in_this_cluster in zip(dataset.samples,
                                               np.equal(flags, flag)):
                if in_this_cluster:
                    samples.append(sample)
            chart = FrequencyCurveChart(parent=self, toolbar=True)
            chart.show_samples(samples,
                               append=False,
                               title=self.tr("Cluster{0}").format(flag))
            chart.setGeometry(x, y, w, h)
            x += w + span
            if x > max_w - w:
                x = x0 + epoch % 10 * 40 + span
                y += h + span
            if y > max_h - h:
                epoch += 1
                x = x0 + epoch % 10 * 40 + span
                y = x0 + epoch % 10 * 40 + span
            chart.show()
            QCoreApplication.processEvents()
Esempio n. 34
0
    def __init__(self, soundfile, parent):
        self.soundfile = soundfile
        self.isplaying = False
        self.time = 0  # current audio position in frames
        self.audio = QMediaPlayer()
        self.decoder = QAudioDecoder()
        self.is_loaded = False
        self.volume = 100
        self.isplaying = False
        self.decoded_audio = {}
        self.only_samples = []
        self.decoding_is_finished = False
        self.max_bits = 32768
        # File Loading is Asynchronous, so we need to be creative here, doesn't need to be duration but it works
        self.audio.durationChanged.connect(self.on_durationChanged)
        #self.decoder.finished.connect(self.decode_finished_signal)
        self.audio.setMedia(QUrl.fromLocalFile(soundfile))
        #self.decoder.setSourceFilename(soundfile)  # strangely inconsistent file-handling
        # It will hang here forever if we don't process the events.
        while not self.is_loaded:
            QCoreApplication.processEvents()
            time.sleep(0.1)

        #self.decode_audio()
        #self.np_data = np.array(self.only_samples)
        #self.np_data = np.abs(self.np_data / self.max_bits)
        # A simple normalisation, with this the samples should all be between 0 and 1
        # for i in self.decoded_audio.items():
        #     self.only_samples.extend(i[1][0])
        # t = []
        # for i in self.only_samples:
        #     if i != []:
        #         t.append(i + -(min(self.only_samples)))
        #
        # t2 = []
        # for i in t:
        #     t2.append(i / max(t))
        # self.only_samples = t2
        #print(len(self.only_samples))
        #print(self.max_bits)


        self.isvalid = True
        self.pydubfile = None
        if AudioSegment:
            if which("ffmpeg") is not None:
                AudioSegment.converter = which("ffmpeg")
            elif which("avconv") is not None:
                AudioSegment.converter = which("avconv")
            else:
                if platform.system() == "Windows":
                    AudioSegment.converter = os.path.join(get_main_dir(), "ffmpeg.exe")
                    #AudioSegment.converter = os.path.dirname(os.path.realpath(__file__)) + "\\ffmpeg.exe"
                else:
                    # TODO: Check if we have ffmpeg or avconv installed
                    AudioSegment.converter = "ffmpeg"

        try:
            if AudioSegment:
                print(self.soundfile)
                self.pydubfile = AudioSegment.from_file(self.soundfile, format=os.path.splitext(self.soundfile)[1][1:])
            else:
                self.wave_reference = wave.open(self.soundfile)

            self.isvalid = True

        except:
            traceback.print_exc()
            self.wave_reference = None
            self.isvalid = False