Esempio n. 1
0
def run(execution_context):
    """run the action"""
    pause_time = app.get_config('behavior.stop.pause_time')
    stop_reacts = app.get_config('behavior.stop.reacts')

    time.sleep(pause_time)
    tts.say_random(stop_reacts)
Esempio n. 2
0
def run(execution_context):
    """run the action"""
    FLAGS["stop"] = False
    openings = app.get_config('story.opening')
    no_story = app.get_config('story.no_story')
    pause_time = app.get_config('story.pause_time')
    stories = app.get_config('story.stories')
    tag = execution_context.event.get('tag', None)

    if tag is not None:
        # filter stories based on tags
        stories = list(filter(lambda story: tag in story.get('tags'), stories))

    if len(stories) == 0:
        tts.say_random(no_story)
        return

    tts.say_random(openings)

    time.sleep(pause_time)

    if FLAGS["stop"]:
        return

    story = stories[random.randint(0, len(stories) - 1)]
    with open('cache/stories/' + story.get('file')) as data_file:
        text = data_file.read()
        read_long_text(text)
Esempio n. 3
0
def run(execution_context):
    """run the action"""
    filtered_word_type = app.get_config('predict.filtered_word_types')
    remove_stop_words = app.get_config('train.remove_stop_words')

    data_name = execution_context.event.get('data_name', 'default')
    text = execution_context.event.get('text')
    if text is None:
        raise ValueError('text cannot be null')

    config = persist.get_data_config(data_name)
    tokenizer = TokenizerFactory.get_tokenizer(config.get('tokenizer'))

    if config.get('clean_text'):
        text = pre_process.clean_text(text, remove_stop_words)

    tokenized_text = tokenizer(text)
    result_word, result_proba = pre_process.predict(tokenized_text, data_name)

    LOGGER.warning('predict %s with probability %2f %%', result_word,
                   result_proba * 100)

    pos_tagged_text = nltk.pos_tag(nltk.word_tokenize(text))
    filtered_text = \
        [(w, word_type) for w, word_type in pos_tagged_text if not word_type in filtered_word_type]

    send_msg(result_word, result_proba, filtered_text)
Esempio n. 4
0
def say(texts, params=None, do_normalize=True):
    """Speak texts with a specified engine"""
    if texts is None:
        return
    if do_normalize:
        texts = normalize(texts, params)

    global LAST_SENTENCE
    LAST_SENTENCE = texts

    from app import APP_INSTANCE as app
    engine_name = app.get_config('engine.tts.engine')
    osx_voice = app.get_config('engine.tts.osx.voice')
    gtts_lang = app.get_config('engine.tts.gTTS.lang')
    mary_config = app.get_config('engine.tts.mary_tts')

    tts_engines = {
        'pyttsx': PyttsxEngine(),
        'gTTS': GTTSEngine(gtts_lang),
        'ev3': EV3TTSEngine(),
        'osx': OSXTTSEngine(osx_voice),
        'mary_tts': MaryTTS(mary_config)
    }
    engine = tts_engines.get(engine_name)
    if engine is None:
        logging.warning('engine not configured: ' + engine_name)
        return
    engine.say(texts)
Esempio n. 5
0
    def run(self, execution_context):
        from app import APP_INSTANCE as app
        app.reload_config()

        url = app.get_config('bot.url')
        msg = {'name': 'reload', 'args': {}}
        execution_context.finish('reload done')
        http.call(url, msg)
Esempio n. 6
0
 def run(self, execution_context):
     pattern = r'^[\w_]+$'
     bot_name = execution_context.event.get('bot')
     if bot_name is None or bot_name is '':
         raise ValueError('bot name cannot be null or empty')
     if not re.match(pattern, bot_name):
         raise ValueError('bot name can only contains alphanumeric characters and underscore')
     from app import APP_INSTANCE as app
     app.reload_config(bot_name)
     execution_context.finish('switched to ' + bot_name)
Esempio n. 7
0
def run(execution_context):
    """run the action"""
    event_name = execution_context.event_name.split('.')[1]
    config_name = 'behavior.inquire.' + event_name
    reacts = app.get_config(config_name)
    txt_no_data = app.get_config('behavior.inquire.no_data')
    if reacts is None or len(reacts) == 0:
        LOGGER.warning('No behavior configured for ' + config_name)
        tts.say_random(txt_no_data)
        return
    tts.say_random(reacts)
Esempio n. 8
0
def get_vectorizer(config):
    """get the vectorizer based on config"""
    vectorizer_config = app.get_config('train.vectorizer')
    tokenizer_config = config.get('tokenizer')
    tokenizer = TokenizerFactory.get_tokenizer(tokenizer_config)
    return VectorizerFactory.get_vectorizer(vectorizer_config,
                                            tokenizer=tokenizer)
Esempio n. 9
0
def create_api():
    """create a twitter api"""
    from twitter import OAuth, Twitter

    from app import APP_INSTANCE as app
    access_token = app.get_config('api.twitter.access_token')
    access_secret = app.get_config('api.twitter.access_secret')
    consumer_key = app.get_config('api.twitter.consumer_key')
    consumer_secret = app.get_config('api.twitter.consumer_secret')

    # temporary fix for certificate error
    ssl._create_default_https_context = ssl._create_unverified_context

    oauth = OAuth(access_token, access_secret, consumer_key, consumer_secret)

    # Initiate the connection to Twitter API
    return Twitter(auth=oauth)
Esempio n. 10
0
def get_fact(group):
    """get fact by name"""
    facts = app.get_config('facts')
    fact = facts.get(group)
    if fact is not None:
        return fact
    method = getattr(dynamic_facts, 'get_' + group, None)
    if method is None:
        return "unknown"
    return method()
Esempio n. 11
0
def find_song(song_id):
    """Find a song by id, or pick a random song if song_id is None"""
    songs = app.get_config('songs')

    if song_id is None:
        num_song = len(songs)
        rand_song_idx = random.randint(0, num_song - 1)
        return songs[rand_song_idx]
    else:
        return next(filter(lambda s: s.id == song_id, songs), None)
Esempio n. 12
0
def say(texts):
    """Speak texts with a specified engine"""
    texts = normalize(texts)

    engine_name = app.get_config('engine.tts.engine')
    osx_voice = app.get_config('engine.tts.osx.voice')
    gtts_lang = app.get_config('engine.tts.gTTS.lang')
    mary_config = app.get_config('engine.tts.mary_tts')

    tts_engines = {
        'pyttsx': PyttsxEngine(),
        'gTTS': GTTSEngine(gtts_lang),
        'ev3': EV3TTSEngine(),
        'osx': OSXTTSEngine(osx_voice),
        'mary_tts': MaryTTS(mary_config)
    }
    engine = tts_engines.get(engine_name)
    if engine is None:
        logging.warning('engine not configured: ' + engine_name)
        return
    engine.say(texts)
Esempio n. 13
0
def get_weather(city=None):
    """get weather forecast"""
    from app import APP_INSTANCE as app
    global CACHED_DATA
    time_to_live = app.get_config('api.weather.time_to_live')
    if has_cache(time_to_live):
        LOGGER.warning('Use cached weather data')
        return CACHED_DATA['CACHED_RESULT']
    app_id = app.get_config('api.weather.key')
    # TODO get city dynamically
    if city is None:
        city = app.get_config('api.weather.city')
    server_url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city + '&APPID=' + app_id
    res, content = http.call(server_url, None, 'GET')
    result = json.loads(content.decode('utf-8'))
    if result is None or result.get('cod') != 200:
        LOGGER.warning('Result from api server: ' + str(content))
        return None
    CACHED_DATA['CACHED_RESULT'] = result
    CACHED_DATA['CACHED_TIME'] = time.time()
    return result
Esempio n. 14
0
def parse_csv(reader, config):
    """parse the csv file"""
    remove_stop_words = app.get_config('train.remove_stop_words')
    input_texts = []
    output_texts = []

    for row in reader:
        text = row[0]
        if config.get('clean_text'):
            text = pre_process.clean_text(row[0], remove_stop_words)
        input_texts.append(text)
        row.pop(0)
        output_texts.append(",".join(row))
    return input_texts, output_texts
Esempio n. 15
0
def send_msg(result_word, result_proba, filtered_text):
    """send the message to bot"""
    url = app.get_config('bot.url')
    msg = {
        'name': result_word,
        'args': {
            'proba': result_proba,
            'tagged_text': filtered_text
        }
    }
    http_client = Http()
    content = http_client.request(
        uri=url,
        method='POST',
        headers={'Content-Type': 'application/json; charset=UTF-8'},
        body=json.dumps(msg),
    )
    LOGGER.warning('response from bot: %s', content)
Esempio n. 16
0
"""Simple REST server"""

from app import APP_INSTANCE as app
from bootstrap import ApplicationBootstrap

app.bootstrap = ApplicationBootstrap()

# export WSGI application
application = app.api

# run the application
app.run()
Esempio n. 17
0
def get_health_react():
    """get health react"""
    health = app.get_config('facts.health')
    reacts = app.get_config('behavior.health_react.' + health)
    return reacts[random.randint(0, len(reacts) - 1)]
Esempio n. 18
0
 def run(self, execution_context, _):
     """run the action"""
     from app import APP_INSTANCE as app
     app.reload_config()
     execution_context.finish()
Esempio n. 19
0
def get_health_react():
    """get health react"""
    from app import APP_INSTANCE as app
    health = app.get_config('facts.health')
    reacts = app.get_config('behavior.health_react.' + health)
    return reacts[random.randint(0, len(reacts) - 1)]
Esempio n. 20
0
 def run(self, execution_context):
     from app import APP_INSTANCE as app
     app.reload_config()
     execution_context.finish()
Esempio n. 21
0
def get_algorithm():
    """get the algorithm based on config"""
    algo_config = app.get_config('train.algorithm')
    return AlgorithmFactory.get_algorithm(algo_config)