<commit_before>import os
import base64
import json
from abc import abstractproperty
from pliers.stimuli.text import TextStim, ComplexTextStim
from pliers.converters.audio import AudioToTextConverter
from pliers.converters.image import ImageToTextConverter

from six.moves.urllib.parse import urlencode
from six.moves.urllib.request import Request, urlopen
from six.moves.urllib.error import URLError, HTTPError


class SpeechRecognitionAPIConverter(AudioToTextConverter):
    ''' Uses the SpeechRecognition API, which interacts with several APIs, 
    like Google and Wit, to run speech-to-text transcription on an audio file.
    Args:
        api_key (str): API key. Must be passed explicitly or stored in
            the environment variable specified in the environ_key field.
    '''

    @abstractproperty
    def environ_key(self):
        pass

    @abstractproperty
    def recognize_method(self):
        pass

    def __init__(self, api_key=None):
        import speech_recognition as sr
        if api_key is None:
            try:
                api_key = os.environ[self.environ_key]
            except KeyError:
                raise ValueError("A valid API key must be passed when "
                                 "a SpeechRecognitionAPIConverter is initialized.")
        self.recognizer = sr.Recognizer()
        self.api_key = api_key

    def _convert(self, audio):
        import speech_recognition as sr
        with sr.AudioFile(audio.filename) as source:
            clip = self.recognizer.record(source)
        text = getattr(self.recognizer, self.recognize_method)(clip, self.api_key)
        return ComplexTextStim(text=text)


class WitTranscriptionConverter(SpeechRecognitionAPIConverter):
    
    @property
    def environ_key(self):
        return 'WIT_AI_API_KEY'

    @property
    def recognize_method(self):
        return 'recognize_wit'


class GoogleSpeechAPIConverter(SpeechRecognitionAPIConverter):

    @property
    def environ_key(self):
        return 'GOOGLE_APPLICATION_CREDENTIALS'

    @property
    def recognize_method(self):
        return 'recognize_google_cloud'


class IBMSpeechAPIConverter(AudioToTextConverter):
    ''' Uses the IBM Watson Text to Speech API to run speech-to-text 
    transcription on an audio file.

    Args:
        username (str): API credential username. Must be passed explicitly
            or stored in the environment variable specified in the environ_key
            field.
        password (str): API credential password. Must be passed explicitly
            or stored in the environment variable specified in the environ_key
            field.
    '''

    def __init__(self, username=None, password=None):
        super(IBMSpeechAPIConverter, self).__init__()
        import speech_recognition as sr
        if username is None or password is None:
            try:
                username = os.environ['IBM_USERNAME']
                password = os.environ['IBM_PASSWORD']
            except KeyError:
                raise ValueError("A valid API key must be passed when "
                                 "a SpeechRecognitionConverter is initialized.")
        self.recognizer = sr.Recognizer()
        self.username = username
        self.password = password

    def _convert(self, audio):
        import speech_recognition as sr<commit_msg>simplified properties<commit_after>import os
import base64
import json
from abc import abstractproperty
from pliers.stimuli.text import TextStim, ComplexTextStim
from pliers.converters.audio import AudioToTextConverter
from pliers.converters.image import ImageToTextConverter

from six.moves.urllib.parse import urlencode
from six.moves.urllib.request import Request, urlopen
from six.moves.urllib.error import URLError, HTTPError


class SpeechRecognitionAPIConverter(AudioToTextConverter):
    ''' Uses the SpeechRecognition API, which interacts with several APIs, 
    like Google and Wit, to run speech-to-text transcription on an audio file.
    Args:
        api_key (str): API key. Must be passed explicitly or stored in
            the environment variable specified in the environ_key field.
    '''

    @abstractproperty
    def environ_key(self):
        pass

    @abstractproperty
    def recognize_method(self):
        pass

    def __init__(self, api_key=None):
        import speech_recognition as sr
        if api_key is None:
            try:
                api_key = os.environ[self.environ_key]
            except KeyError:
                raise ValueError("A valid API key must be passed when "
                                 "a SpeechRecognitionAPIConverter is initialized.")
        self.recognizer = sr.Recognizer()
        self.api_key = api_key

    def _convert(self, audio):
        import speech_recognition as sr
        with sr.AudioFile(audio.filename) as source:
            clip = self.recognizer.record(source)
        text = getattr(self.recognizer, self.recognize_method)(clip, self.api_key)
        return ComplexTextStim(text=text)


class WitTranscriptionConverter(SpeechRecognitionAPIConverter):
    
    environ_key = 'WIT_AI_API_KEY'
    recognize_method ='recognize_wit'


class GoogleSpeechAPIConverter(SpeechRecognitionAPIConverter):

    environ_key = 'GOOGLE_APPLICATION_CREDENTIALS'
    recognize_method = 'recognize_google_cloud'


class IBMSpeechAPIConverter(AudioToTextConverter):
    ''' Uses the IBM Watson Text to Speech API to run speech-to-text 
    transcription on an audio file.

    Args:
        username (str): API credential username. Must be passed explicitly
            or stored in the environment variable specified in the environ_key
            field.
        password (str): API credential password. Must be passed explicitly
            or stored in the environment variable specified in the environ_key
            field.
    '''

    def __init__(self, username=None, password=None):
        super(IBMSpeechAPIConverter, self).__init__()
        import speech_recognition as sr
        if username is None or password is None:
            try:
                username = os.environ['IBM_USERNAME']
                password = os.environ['IBM_PASSWORD']
            except KeyError:
                raise ValueError("A valid API key must be passed when "
                                 "a SpeechRecognitionConverter is initialized.")
        self.recognizer = sr.Recognizer()
        self.username = username
        self.password = password

    def _convert(self, audio):
        import speech_recognition as sr
{'fraction_non_alphanumeric': 0.06090283091048202, 'fraction_numerical': 0.000612088752869166, 'mean_word_length': 2.678109172763084, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5361966', 'n_tokens_mistral': 1772, 'n_tokens_neox': 1694, 'n_words': 536}