def _generator(self, q):

        while not self.closed:
            # Use a blocking get() to ensure there's at least one chunk of
            # data, and stop iteration if the chunk is None, indicating the
            # end of the audio stream.
            chunk = q.get()
            if chunk is None:
                return
            audioData = [chunk]

            # Now consume whatever other data's still buffered.
            while True:
                try:
                    chunk = q.get(block=False)
                    if chunk is None:
                        return
                    audioData.append(chunk)
                except queue.Empty:
                    break
                except:
                    break

            audioData = b''.join(audioData)
            yield audioData

        logger.debug('microphone generator loop exited')
    def __enter__(self):
        logger.debug('MicrophoneStream.enter ENTER')
        self.closed = False
        try:
            self._audio_stream = self._audio_interface.open(
                input_device_index=self._inputDeviceIndex,
                format=self._format,
                channels=self._num_channels,
                rate=self._rate,
                input=True,
                frames_per_buffer=self._chunk_size,
                # Run the audio stream asynchronously to fill the buffer object.
                # This is necessary so that the input device's buffer doesn't
                # overflow while the calling thread makes network requests, etc.
                stream_callback=self._fill_buff,
            )
        except OSError:
            logger.error("microphone __enter__.OSError")
            self.closed = True
            raise Exception("Microphone Not Functioning")

        self.initRecording()
        logger.debug('MicrophoneStream.enter EXIT')

        return self
示例#3
0
 def canceled(self, evt):
     logger.debug(
         'microsoftTranscribe.ProcessEvents.CANCELED: {}'.format(evt))
     logger.error(
         'microsoftTranscribe terminated. Ensure you have the correct API Key and service region.'
     )
     self.responseQueue.put('canceled')
 def saveRecording(self):
     logger.debug("microphoneStream.saveRecording ENTER")
     # Record the audio file
     if self._wavfile is not None:
         audioGenerator = self.recordingGenerator()
         for audioData in audioGenerator:
             self._wavfile.writeframes(audioData)
     logger.debug("microphoneStream.saveRecording EXIT")
    def run(self):
        if self._ONLINE:
            logger.warn("Transcribe Engine already Started")
            return

        logger.info(
            "Transcribe Engine Starting with the %s%s Speech-To-Text Service" %
            (speakreader.CONFIG.SPEECH_TO_TEXT_SERVICE[0].upper(),
             speakreader.CONFIG.SPEECH_TO_TEXT_SERVICE[1:]))

        FILENAME_DATESTRING = datetime.datetime.now().strftime(
            FILENAME_DATE_FORMAT)
        TRANSCRIPT_FILENAME = FILENAME_PREFIX + FILENAME_DATESTRING + "." + TRANSCRIPT_FILENAME_SUFFIX
        RECORDING_FILENAME = FILENAME_PREFIX + FILENAME_DATESTRING + "." + RECORDING_FILENAME_SUFFIX
        tf = os.path.join(speakreader.CONFIG.TRANSCRIPTS_FOLDER,
                          TRANSCRIPT_FILENAME)
        self.queueManager.transcriptHandler.setFileName(tf)

        try:
            self.microphoneStream = MicrophoneStream(
                speakreader.CONFIG.INPUT_DEVICE)
            self.microphoneStream.recordingFilename = RECORDING_FILENAME
            self.microphoneStream.meterQueue = self.queueManager.meterHandler.getReceiverQueue(
            )
        except Exception as e:
            logger.debug("MicrophoneStream Exception: %s" % e)
            self.transcriptQueue.put_nowait(self.OFFLINE_MESSAGE)
            return

        if speakreader.CONFIG.SPEECH_TO_TEXT_SERVICE == 'google' and self.GOOGLE_SERVICE:
            transcribeService = googleTranscribe(self.microphoneStream)
        elif speakreader.CONFIG.SPEECH_TO_TEXT_SERVICE == 'IBM' and self.IBM_SERVICE:
            transcribeService = ibmTranscribe(self.microphoneStream)
        elif speakreader.CONFIG.SPEECH_TO_TEXT_SERVICE == 'microsoft' and self.MICROSOFT_SERVICE:
            transcribeService = microsoftTranscribe(self.microphoneStream)
        else:
            logger.warn(
                "No Supported Transcribe Service Selected. Can't start Transcribe Engine."
            )
            return

        self.transcriptFile = open(tf, "a+")
        self.transcriptQueue.put_nowait(self.ONLINE_MESSAGE)
        self._ONLINE = True

        try:
            with self.microphoneStream as stream:
                while self._ONLINE:
                    responses = transcribeService.transcribe()
                    self.process_responses(responses)
                logger.info("Transcription Engine Stream Closed")
        except Exception as e:
            logger.error(e)

        self.transcriptFile.close()
        self.transcriptQueue.put_nowait(self.OFFLINE_MESSAGE)
        self._ONLINE = False
        logger.info("Transcribe Engine Terminated")
示例#6
0
 def delete(path, days):
     try:
         days = int(days)
     except ValueError:
         return
     delete_date = datetime.datetime.now() - datetime.timedelta(days=days)
     with os.scandir(path=path) as files:
         for file in files:
             file_info = file.stat()
             if datetime.datetime.fromtimestamp(file_info.st_ctime) < delete_date:
                 filename = os.path.join(path, file.name)
                 logger.debug("Deleting: %s" % filename)
                 os.remove(filename)
示例#7
0
 def eventSource(type, listenerQueue, remoteIP, sessionID):
     while self.SR.transcribeEngine.queueManager.is_initialized:
         try:
             data = listenerQueue.get(timeout=2)
             if data is None:
                 close_event = json.dumps({"event": "close"})
                 yield 'data: {}\n\n'.format(close_event)
                 break
             yield 'data: {}\n\n'.format(json.dumps(data))
         except queue.Empty:
             continue
     logger.debug("Exiting " + type.capitalize() +
                  " Listener loop for IP: " + remoteIP +
                  " with sessionID: " + sessionID)
示例#8
0
 def recognize_using_websocket(self, *args):
     logger.debug("ibmTransribe.recognize_using_websocket ENTER")
     self.speech_to_text.recognize_using_websocket(
         audio=self.audio_source,
         content_type='audio/l16; rate=%s' % self.audio_device._outputSampleRate,
         recognize_callback=self.mycallback,
         interim_results=True,
         max_alternatives=1,
         inactivity_timeout=-1,
         smart_formatting=True,
         word_alternatives_threshold=0.75,
         profanity_filter=bool(speakreader.CONFIG.ENABLE_CENSORSHIP),
     )
     logger.debug("ibmTransribe.recognize_using_websocket EXIT")
    def transcribe(self):
        # Generator to return transcription results

        if not self.is_supported:
            return

        logger.debug("googleTranscribe.transcribe ENTER")

        while True:
            audio_generator = self.audio_device.streamGenerator()

            requests = (speech.StreamingRecognizeRequest(
                audio_content=content, ) for content in audio_generator)

            responses = self.client.streaming_recognize(
                requests=requests, config=self.streaming_config)

            try:
                for response in responses:
                    if not response.results:
                        continue

                    result = response.results[0]

                    if not result.is_final and not speakreader.CONFIG.SHOW_INTERIM_RESULTS:
                        continue

                    if not result.alternatives:
                        continue

                    transcript = {
                        'transcript': result.alternatives[0].transcript,
                        'is_final': result.is_final,
                    }

                    yield transcript

                logger.debug("googleTranscribe.transcribe EXIT")
                break

            except exceptions.OutOfRange:
                """ Google Cloud limits stream to about 5 minutes. Just loop. """
                continue
            except exceptions.DeadlineExceeded:
                """ Google Cloud limits stream to about 5 minutes. Just loop. """
                continue
示例#10
0
    def transcribe(self):
        if not self.is_supported:
            return
        # Generator to return transcription results
        logger.debug("microsoftTranscribe.transcribe Enter")

        audio_format = speechsdk.audio.AudioStreamFormat(
            samples_per_second=16000, bits_per_sample=16, channels=1)

        audio_stream_callback = AudioStreamCallback(
            self.audio_device._streamBuff)

        audio_stream = speechsdk.audio.PullAudioInputStream(
            audio_stream_callback, audio_format)
        self.audio_config = speechsdk.audio.AudioConfig(stream=audio_stream)

        self.speech_recognizer = speechsdk.SpeechRecognizer(
            speech_config=self.speech_config, audio_config=self.audio_config)

        # Connect callbacks to the events fired by the speech recognizer
        self.speech_recognizer.recognizing.connect(
            self.eventProcessor.recognizing)
        self.speech_recognizer.recognized.connect(
            self.eventProcessor.recognized)
        self.speech_recognizer.session_started.connect(
            self.eventProcessor.session_started)
        self.speech_recognizer.session_stopped.connect(
            self.eventProcessor.session_stopped)
        self.speech_recognizer.canceled.connect(self.eventProcessor.canceled)

        # Start continuous speech recognition
        self.speech_recognizer.start_continuous_recognition()

        while True:
            response = self.eventProcessor.responseQueue.get()
            if response is None:
                self.speech_recognizer.stop_continuous_recognition()
                self.audio_device.closed = True
                break
            if response == 'canceled':
                self.audio_device.closed = True
                break

            yield response

        logger.debug("microsoftTranscribe.transcribe Exit")
示例#11
0
    def transcribe(self):
        if not self.is_supported:
            return
        # Generator to return transcription results
        logger.debug('ibmTranscribe.transcribe ENTER')

        recognize_thread = Thread(target=self.recognize_using_websocket, args=())
        recognize_thread.start()

        while True:
            response = self.mycallback.responseQueue.get()
            if response is None:
                break
            yield response

        self.audio_source.completed_recording()
        recognize_thread.join()
        logger.debug('ibmTranscribe.transcribe EXIT')
示例#12
0
    def __exit__(self, type, value, traceback):
        if self.closed:
            return
        logger.debug('MicrophoneStream.exit ENTER')
        self._audio_stream.stop_stream()
        self._audio_stream.close()
        self._streamBuff.put(None)
        if speakreader.CONFIG.SAVE_RECORDINGS:
            self._recordingBuff.put(None)
        self.closed = True
        # Signal the generator to terminate so that the client's
        # streaming_recognize method will not block the process termination.
        self._audio_interface.terminate()

        if self._wavfile is not None:
            self._wavfile.close()
            self._wavfile = None

        logger.debug('MicrophoneStream.exit EXIT')
示例#13
0
    def checkForUpdate(self):
        # Check for new versions
        if speakreader.CONFIG.CHECK_GITHUB:
            self._check_github()
        else:
            self.LATEST_VERSION_HASH = self.INSTALLED_VERSION_HASH

        if not self.INSTALLED_VERSION_HASH:
            self.UPDATE_AVAILABLE = True
        elif self.COMMITS_BEHIND > 0 and speakreader.GITHUB_BRANCH in ('master', 'beta') and \
                speakreader.VERSION_RELEASE != self.LATEST_RELEASE:
            self.UPDATE_AVAILABLE = 'release'
        elif self.COMMITS_BEHIND > 0 and self.INSTALLED_VERSION_HASH != self.LATEST_VERSION_HASH:
            self.UPDATE_AVAILABLE = 'commit'
        else:
            self.UPDATE_AVAILABLE = False

        if logger.VERBOSE:
            d = self.__dict__
            for k, v in d.items():
                logger.debug(str(k) + ": " + str(v))
示例#14
0
    def _exec_command(self, cmd, cwd=None):
        if cwd is None:
            cwd = speakreader.PROG_DIR
        logger.debug('Trying to execute: "' + cmd + '" with shell in ' + cwd)
        p = subprocess.Popen(cmd,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT,
                             cwd=cwd,
                             shell=True)

        while True:
            out = p.stdout.readline().decode('utf-8').replace('\r',
                                                              '').replace(
                                                                  '\n', '')
            return_code = p.poll()
            if out == '' and return_code is not None:
                break

            if out != '':
                yield out

        if return_code:
            raise subprocess.CalledProcessError(return_code, cmd)
示例#15
0
    def initRecording(self):
        logger.debug("microphoneStream.initRecording ENTER")
        if speakreader.CONFIG.SAVE_RECORDINGS:
            wavfile = os.path.join(speakreader.CONFIG.RECORDINGS_FOLDER,
                                   self.recordingFilename)
            try:
                w = wave.open(wavfile, 'rb')
                data = w.readframes(w.getnframes())
                self._wavfile = wave.open(wavfile, 'wb')
                self._wavfile.setparams(w.getparams())
                w.close()
                self._wavfile.writeframes(data)
            except FileNotFoundError:
                self._wavfile = wave.open(wavfile, 'wb')
                self._wavfile.setnchannels(self._num_channels)
                self._wavfile.setsampwidth(2)
                self._wavfile.setframerate(self._outputSampleRate)

            recordingThread = Thread(target=self.saveRecording,
                                     args=(),
                                     name='recordingThread')
            recordingThread.start()
        logger.debug("microphoneStream.initRecording EXIT")
示例#16
0
    def runGit(self, args):
        if speakreader.CONFIG.GIT_PATH:
            git_locations = ['"' + speakreader.CONFIG.GIT_PATH + '"']
        else:
            git_locations = ['git']

        output = err = None

        for cur_git in git_locations:
            cmd = cur_git + ' ' + args

            try:
                logger.debug('Trying to execute: "' + cmd +
                             '" with shell in ' + speakreader.PROG_DIR)
                p = subprocess.Popen(cmd,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.STDOUT,
                                     shell=True,
                                     cwd=speakreader.PROG_DIR)
                output, err = p.communicate()
                output = output.decode('utf-8').strip()

                for line in output.split('\n'):
                    if line:
                        logger.debug('Git output: ' + line)

            except OSError:
                logger.debug('Command failed: %s', cmd)
                continue

            if 'not found' in output or "not recognized as an internal or external command" in output:
                logger.debug('Unable to find git with command ' + cmd)
                output = None
            elif 'fatal:' in output or err:
                logger.error(
                    'Git returned bad info. Are you sure this is a git installation?'
                )
                output = None
            elif output:
                break

        return (output, err)
示例#17
0
 def on_inactivity_timeout(self, error):
     logger.debug('ibmTranscribe.ProcessResponses.Inactivity timeout: {}'.format(error))
示例#18
0
 def session_stopped(self, evt):
     logger.debug(
         'microsoftTranscribe.ProcessEvents.SESSION_STOPPED {}'.format(evt))
     self.responseQueue.put(None)
示例#19
0
 def session_started(self, evt):
     logger.debug(
         'microsoftTranscribe.ProcessEvents.SESSION_STARTED: {}'.format(
             evt))
示例#20
0
    def __init__(self, input_device):
        logger.debug('MicrophoneStream INIT')
        self._audio_interface = pyaudio.PyAudio()
        self._inputDeviceName = input_device
        self._inputDeviceIndex = None
        self._num_channels = 1
        self._format = pyaudio.paInt16
        self._outputSampleRate = SAMPLERATE

        self.meterQueue = None
        self.meter_peak_np = np.empty(0, dtype=np.int16)
        self.meter_time = float(0)

        self.recordingFilename = None

        numdevices = self._audio_interface.get_default_host_api_info().get(
            'deviceCount')
        defaultHostAPIindex = self._audio_interface.get_default_host_api_info(
        ).get('index')
        defaultInputDeviceIndex = self._audio_interface.get_default_input_device_info(
        ).get('index')
        defaultInputDeviceName = self._audio_interface.get_default_input_device_info(
        ).get('name')

        for i in range(0, numdevices):
            inputDevice = self._audio_interface.get_device_info_by_host_api_device_index(
                defaultHostAPIindex, i)
            if self._inputDeviceName == inputDevice.get('name'):
                self._inputDeviceIndex = inputDevice.get('index')
                break

        if self._inputDeviceIndex is None:
            self._inputDeviceName = defaultInputDeviceName
            self._inputDeviceIndex = defaultInputDeviceIndex

        deviceInfo = self._audio_interface.get_device_info_by_index(
            self._inputDeviceIndex)
        self._rate = int(deviceInfo.get('defaultSampleRate'))

        try:
            if self._audio_interface.is_format_supported(
                    self._outputSampleRate,
                    input_device=self._inputDeviceIndex,
                    input_channels=self._num_channels,
                    input_format=self._format):
                self._rate = self._outputSampleRate
        except ValueError:
            pass

        self.resampler = sr.Resampler()
        self.resampler_ratio = self._outputSampleRate / self._rate

        self._chunk_size = int(self._rate / 10)

        self._wavfile = None

        # Create a thread-safe buffer of audio data
        self._streamBuff = queue.Queue()
        self._recordingBuff = queue.Queue()
        self.closed = True

        # 2 bytes in 16 bit samples
        self._bytes_per_sample = 2 * self._num_channels
        self._bytes_per_second = self._rate * self._bytes_per_sample

        self._bytes_per_chunk = (self._chunk_size * self._bytes_per_sample)
        self._chunks_per_second = (self._bytes_per_second //
                                   self._bytes_per_chunk)
示例#21
0
 def on_listening(self):
     logger.debug('ibmTranscribe.ProcessResponses.Listening Service is listening')
示例#22
0
    def __init__(self, initOptions):
        if SpeakReader._INITIALIZED:
            return

        with INIT_LOCK:

            global PROG_DIR
            PROG_DIR = initOptions['prog_dir']

            global DATA_DIR
            DATA_DIR = initOptions['data_dir']

            global CONFIG
            CONFIG = initOptions['config']
            assert CONFIG is not None

            if isinstance(initOptions['http_port'], int):
                self.HTTP_PORT = initOptions['http_port']
            else:
                self.HTTP_PORT = int(CONFIG.HTTP_PORT)

            if self.HTTP_PORT < 21 or self.HTTP_PORT > 65535:
                logger.warn("HTTP_PORT out of bounds: 21 < %s < 65535", self.HTTP_PORT)
                self.HTTP_PORT = 8880

            # Check if pyOpenSSL is installed. It is required for certificate generation
            # and for CherryPy.
            if CONFIG.ENABLE_HTTPS:
                try:
                    import OpenSSL
                except ImportError:
                    logger.warn("The pyOpenSSL module is missing. Install this "
                                "module to enable HTTPS. HTTPS will be disabled.")
                    CONFIG.ENABLE_HTTPS = False

                if not CONFIG.HTTPS_CERT:
                    CONFIG.HTTPS_CERT = os.path.join(DATA_DIR, 'server.crt')
                if not CONFIG.HTTPS_KEY:
                    CONFIG.HTTPS_KEY = os.path.join(DATA_DIR, 'server.key')

                if not (os.path.exists(CONFIG.HTTPS_CERT) and os.path.exists(CONFIG.HTTPS_KEY)):
                    logger.warn("Disabled HTTPS because of missing certificate and key.")
                    CONFIG.ENABLE_HTTPS = False

            # Check if we has a jwt_secret
            if CONFIG.JWT_SECRET == '' or not CONFIG.JWT_SECRET:
                logger.debug("Generating JWT secret...")
                CONFIG.JWT_SECRET = generate_uuid()
                CONFIG.write()

            ###################################################################################################
            #  Get Version Information and check for updates
            ###################################################################################################
            self.versionInfo = Version()

            ###################################################################################################
            #  Get the Input Device
            ###################################################################################################
            self.get_input_device()

            ###################################################################################################
            #  Initialize the Transcribe Engine
            ###################################################################################################
            self.transcribeEngine = TranscribeEngine()

            if CONFIG.START_TRANSCRIBE_ON_STARTUP :
                self.startTranscribeEngine()

            ###################################################################################################
            #  Initialize the webserver
            ###################################################################################################
            logger.info('WebServer Initializing')
            webServerOptions = {
                'config': CONFIG,
                'prog_dir': PROG_DIR,
                'data_dir': DATA_DIR,
                'http_port': self.HTTP_PORT,
            }
            self.webServer = webstart.initialize(webServerOptions)
            self.webServer.root.SR = self
            cherrypy.server.start()

            # Launch the WebBrowser
            if CONFIG.LAUNCH_BROWSER and not initOptions['nolaunch']:
                launch_browser(CONFIG.HTTP_HOST, self.HTTP_PORT, CONFIG.HTTP_ROOT + 'manage')

            ###################################################################################################
            #  Run cleanup of old logs, transcripts, and recordings and start a scheduler to run every 24 hours
            ###################################################################################################
            self.cleanup_files()
            self.scheduler = BackgroundScheduler()
            self.scheduler.add_job(self.cleanup_files, 'interval', hours=24)
            self.scheduler.start()

            SpeakReader._INITIALIZED = True
示例#23
0
    def update(self):
        if speakreader.CONFIG.SERVER_ENVIRONMENT.lower() != 'production':
            logger.info(
                "Updating bypassed because this is not a production environment"
            )
            return False

        if not self.UPDATE_AVAILABLE:
            logger.info("No Updates Available")
            return False

        if self.INSTALL_TYPE == 'git':

            output, err = self.runGit(
                'diff --name-only %s/%s' %
                (speakreader.CONFIG.GIT_REMOTE, speakreader.CONFIG.GIT_BRANCH))

            if output == '':
                logger.debug("No differences found from the origin")

            elif output == 'requirements.txt':
                logger.warn(
                    'Requirements file is out of sync. Restoring to original.')
                output, err = self.runGit('checkout %s/%s requirements.txt' %
                                          (speakreader.CONFIG.GIT_REMOTE,
                                           speakreader.CONFIG.GIT_BRANCH))
            else:
                logger.error("Differences Found. Unable to update.")
                logger.info('Output: ' + str(output))
                return False

            output, err = self.runGit('pull ' + speakreader.CONFIG.GIT_REMOTE +
                                      ' ' + speakreader.CONFIG.GIT_BRANCH)

            if not output:
                logger.error('Unable to download latest version')
                return False

            for line in output.split('\n'):
                if 'Already up-to-date.' in line:
                    logger.info('No update available, not updating')
                    logger.info('Output: ' + str(output))
                    return False
                elif line.endswith(('Aborting', 'Aborting.')):
                    logger.error('Unable to update from git: ' + line)
                    logger.info('Output: ' + str(output))
                    return False

        else:
            tar_download_url = 'https://api.github.com/repos/{}/{}/tarball/{}'.format(
                speakreader.CONFIG.GIT_USER, speakreader.CONFIG.GIT_REPO,
                speakreader.CONFIG.GIT_BRANCH)
            if speakreader.CONFIG.GIT_TOKEN:
                tar_download_url = tar_download_url + '?access_token=%s' % speakreader.CONFIG.GIT_TOKEN
            update_dir = os.path.join(speakreader.PROG_DIR, 'update')
            version_path = os.path.join(speakreader.PROG_DIR, 'version.txt')

            logger.info('Downloading update from: ' + tar_download_url)
            try:
                data = requests.get(tar_download_url, timeout=10)
            except Exception as e:
                logger.warn('Failed to establish a connection to GitHub')
                return False

            if not data:
                logger.error(
                    "Unable to retrieve new version from '%s', can't update",
                    tar_download_url)
                return False

            download_name = speakreader.CONFIG.GIT_BRANCH + '-github'
            tar_download_path = os.path.join(speakreader.PROG_DIR,
                                             download_name)

            # Save tar to disk
            with open(tar_download_path, 'wb') as f:
                f.write(data.content)

            # Extract the tar to update folder
            logger.info('Extracting file: ' + tar_download_path)
            tar = tarfile.open(tar_download_path)
            tar.extractall(update_dir)
            tar.close()

            # Delete the tar.gz
            logger.info('Deleting file: ' + tar_download_path)
            os.remove(tar_download_path)

            # Find update dir name
            update_dir_contents = [
                x for x in os.listdir(update_dir)
                if os.path.isdir(os.path.join(update_dir, x))
            ]
            if len(update_dir_contents) != 1:
                logger.error("Invalid update data, update failed: " +
                             str(update_dir_contents))
                return False
            content_dir = os.path.join(update_dir, update_dir_contents[0])

            # walk temp folder and move files to main folder
            for dirname, dirnames, filenames in os.walk(content_dir):
                dirname = dirname[len(content_dir) + 1:]
                for curfile in filenames:
                    old_path = os.path.join(content_dir, dirname, curfile)
                    new_path = os.path.join(speakreader.PROG_DIR, dirname,
                                            curfile)

                    if os.path.isfile(new_path):
                        os.remove(new_path)
                    os.renames(old_path, new_path)

            # Update version.txt
            try:
                with open(version_path, 'w') as f:
                    f.write(str(self.LATEST_VERSION_HASH))
            except IOError as e:
                logger.error(
                    "Unable to write current version to version.txt, update not complete: %s"
                    % e)
                return False

        self.pip_update()
        self.pip_sync()
        logger.info("Update Complete")
        return True
示例#24
0
    def _check_github(self):

        self.COMMITS_BEHIND = 0

        # Get the latest version available from github
        logger.debug('Retrieving latest version information from GitHub')
        url = 'https://api.github.com/repos/%s/%s/commits/%s' % (
            speakreader.CONFIG.GIT_USER, speakreader.CONFIG.GIT_REPO,
            speakreader.CONFIG.GIT_BRANCH)
        if speakreader.CONFIG.GIT_TOKEN:
            url = url + '?access_token=%s' % speakreader.CONFIG.GIT_TOKEN
        try:
            response = requests.get(url, timeout=10)
        except Exception as e:
            logger.warn('Failed to establish a connection to GitHub')
            return

        if response.ok:
            version = response.json()
        else:
            logger.warn(
                'Could not get the latest version information from GitHub for '
                + speakreader.CONFIG.GIT_REMOTE + '/' +
                speakreader.CONFIG.GIT_BRANCH +
                '. Are you running a local development version?')
            return

        self.LATEST_VERSION_HASH = version['sha']

        # See how many commits behind we are
        if not self.INSTALLED_VERSION_HASH:
            logger.info(
                'You are running an unknown version of SpeakReader. Run the updater to identify your version'
            )
            self.LATEST_RELEASE = "Unknown"
            return

        # Get latest release tag
        logger.debug('Retrieving latest release information from GitHub')
        url = 'https://api.github.com/repos/%s/%s/releases' % (
            speakreader.CONFIG.GIT_USER, speakreader.CONFIG.GIT_REPO)
        if speakreader.CONFIG.GIT_TOKEN:
            url = url + '?access_token=%s' % speakreader.CONFIG.GIT_TOKEN
        try:
            response = requests.get(url, timeout=10)
        except Exception as e:
            logger.warn('Failed to establish a connection to GitHub')
            return

        if response.ok:
            releases = response.json()
        else:
            logger.warn('Could not get releases from GitHub.')
            return

        if speakreader.CONFIG.GIT_BRANCH == 'master':
            release = next((r for r in releases if not r['prerelease']),
                           releases[0])
        elif speakreader.CONFIG.GIT_BRANCH == 'beta':
            release = next((r for r in releases), releases[0])
        else:
            release = releases[0]

        self.LATEST_RELEASE = release['tag_name']
        url = 'https://github.com/%s/%s/releases/tag/%s' \
              % (speakreader.CONFIG.GIT_USER, speakreader.CONFIG.GIT_REPO, self.LATEST_RELEASE)
        if speakreader.CONFIG.GIT_TOKEN:
            url = url + '?access_token=%s' % speakreader.CONFIG.GIT_TOKEN
        self.LATEST_RELEASE_URL = url

        logger.info("Installed release is %s - %s" %
                    (self.INSTALLED_RELEASE, self.INSTALLED_VERSION_HASH))
        logger.info("   Latest release is %s - %s" %
                    (self.LATEST_RELEASE, self.LATEST_VERSION_HASH))

        if self.LATEST_VERSION_HASH == self.INSTALLED_VERSION_HASH:
            logger.info('SpeakReader is up to date')
            return

        logger.debug(
            'Comparing currently installed version with latest GitHub version')
        url = 'https://api.github.com/repos/%s/%s/compare/%s...%s' % (
            speakreader.CONFIG.GIT_USER, speakreader.CONFIG.GIT_REPO,
            self.LATEST_VERSION_HASH, self.INSTALLED_VERSION_HASH)
        if speakreader.CONFIG.GIT_TOKEN:
            url = url + '?access_token=%s' % speakreader.CONFIG.GIT_TOKEN
        try:
            response = requests.get(url, timeout=10)
        except Exception as e:
            logger.warn('Failed to establish a connection to GitHub')
            return

        if response.ok:
            commits = response.json()
        else:
            logger.warn('Could not get commits behind from GitHub.')
            return

        try:
            self.COMMITS_BEHIND = int(commits['behind_by'])
            logger.debug("In total, %d commits behind", self.COMMITS_BEHIND)
        except KeyError:
            logger.info(
                'Cannot compare versions. Are you running a local development version?'
            )
            self.COMMITS_BEHIND = 0

        if self.COMMITS_BEHIND > 0:
            logger.info('Updates Available. You are %s commits behind' %
                        self.COMMITS_BEHIND)
        elif self.COMMITS_BEHIND == 0:
            logger.info('SpeakReader is up to date')
示例#25
0
 def __init__(self):
     logger.debug("microsoftTranscribe.ProcessEvents.Init")
     self.responseQueue = Queue(maxsize=100)
示例#26
0
 def __init__(self):
     logger.debug("ibmTranscribe.ProcessResponse.Init ENTER")
     self.responseQueue = Queue(maxsize=100)
     RecognizeCallback.__init__(self)
示例#27
0
 def on_close(self):
     self.responseQueue.put_nowait(None)
     logger.debug("ibmTranscribe.ProcessResponses.Close Connection closed")
示例#28
0
 def on_connected(self):
     logger.debug('ibmTranscribe.ProcessResponses.Connection successful')