当前位置: 首页>>代码示例>>Python>>正文


Python wit.Wit类代码示例

本文整理汇总了Python中wit.Wit的典型用法代码示例。如果您正苦于以下问题:Python Wit类的具体用法?Python Wit怎么用?Python Wit使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Wit类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: event_loop

def event_loop():

    wit = Wit(wit_token())
    my_mic = Mic(DEFAULT_DICT, DEFAULT_LANG, DEFAULT_DICT, DEFAULT_LANG)

    while True:
        # listen for activation hotword
        try:
            threshold, text = my_mic.passiveListen(PERSONA)
        except:
            continue

        # detected hotword
        if threshold:
            audio_file = activeListenFile(threshold)
            if audio_file:
                data = None
                try:
                    # retrieve wit intent
                    data = wit.post_speech(open(audio_file))
                    # send to handler service
                    raise NotImplementedError('no handler code yet')
                except Exception as e:
                    print "Exception in audio_file handling:"
                    print str(e)
                    if data:
                        print "Data: "
                        print pprint(data)
开发者ID:justjake,项目名称:ear,代码行数:28,代码来源:main.py

示例2: PostTextString

 def PostTextString(self, text):
   # Form a text query for Wit
   w = Wit(self.witToken)
   try:
     return WitAiQueryResponse(w.get_message(text))
   except:
     raise
开发者ID:liamw9534,项目名称:SpotifyVoice,代码行数:7,代码来源:WitAiSpeechDecode.py

示例3: chat

def chat(bot, update):
    user_id = update.message.from_user.id
    answer = update.message.text

    if answer == 'О марафонах':
        text = "Марафоны - это круто!"
        bot.sendMessage(user_id, text=text, reply_markup=main_kbd)     
    elif answer == 'Категории':
        text = "Пока категории вопросов не созданы. Вы можете ввести вопрос самостоятельно"
        bot.sendMessage(user_id, text=text, reply_markup=main_kbd)
    elif answer == 'Моя программа':
        text = "Подождите, какая еще программа? Вы же даже не знаете, что такое марафон. Сначала узнайте, а потом уже спрашивайте про программу!"
        bot.sendMessage(user_id, text=text, reply_markup=main_kbd)
    elif answer == 'INFO':
        text = "Появление информации ожидается в скором времени"
        bot.sendMessage(user_id, text=text, reply_markup=main_kbd)
    else:
        actions = dict()
        client = Wit(access_token=wit_token, actions=actions)
        client_answer = client.message(answer)
        try:
            if client_answer['entities']['intent'][0]['confidence'] < 0.6:
                text = "К сожалению, ответ на этот вопрос мне не известен. Попробуйте другой вопрос."
                bot.sendMessage(user_id, text=text, reply_markup=main_kbd)
            else:
                codec = client_answer['entities']['intent'][0]['value']
                text = dictionary[codec]
                bot.sendMessage(user_id, text=text, reply_markup=main_kbd)
        except KeyError:
            text = "К сожалению, ответ на этот вопрос мне не известен. Попробуйте другой вопрос."
            bot.sendMessage(user_id, text=text, reply_markup=main_kbd)
开发者ID:EremeykinS,项目名称:MaraphonBot,代码行数:31,代码来源:bot.py

示例4: DecodeWaveFile

 def DecodeWaveFile(self, waveFileName):
   """Build a speech decode request around Wit"""
   # Form a query for Wit speech recognition
   w = Wit(self.witToken)
   try:
     audio = open(waveFileName)
     return WitAiQueryResponse(w.post_speech(audio))
   except:
     raise
开发者ID:liamw9534,项目名称:SpotifyVoice,代码行数:9,代码来源:WitAiSpeechDecode.py

示例5: send_message

def send_message(recipient, text):

    client = Wit(WITAI_TOKEN, actions)

    session_id = 'my-user-id-42'
    context0 = client.run_actions(session_id, text, {})
    print(context0)

    data = {
        "recipient": {"id": recipient},
        "message": {"text": WitAi_returnMessage}
    }
    resp = requests.post("https://graph.facebook.com/v2.6/me/messages?access_token=" + ACCESS_TOKEN, json=data)
    print(resp.content)
开发者ID:SemihY,项目名称:facebookbot,代码行数:14,代码来源:flaskfacebookbot.py

示例6: main

def main():
    if len(sys.argv) != 2:
        print('usage: python ' + sys.argv[0] + ' <wit-token>')
        exit(1)
    access_token = sys.argv[1]

    def send(request, response):
        print(response['text'])

    actions = {
        'send': send,
    }

    client = Wit(access_token=access_token, actions=actions)
    client.interactive()
开发者ID:malachite-sprite,项目名称:roberts,代码行数:15,代码来源:main.py

示例7: facebookBot

def facebookBot(request):
    try:
        if 'hub.verify_token' in request.GET:
            if request.GET['hub.verify_token'] == models.Config.get('FacebookVerifyToken'):
                if 'hub.challenge' in request.GET:
                    return HttpResponse(request.GET['hub.challenge'])
                return HttpResponse("KO")
        body = json.loads(request.body)
        for entry in body['entry']:
            for message in entry['messaging']:
                if 'is_echo' not in message and 'message' in message:
                    senderId = message['sender']['id']
                    client = Wit(access_token=models.Config.get('WitToken'), actions=actions)
                    client.run_actions("session_%s" % senderId, message['message']['text'], {'senderId': senderId})
    except Exception, e:
        traceback.print_exc()
开发者ID:marchandivan,项目名称:Room-Monitoring-Rest-Api,代码行数:16,代码来源:views.py

示例8: __init__

 def __init__(self, lisa=None):
     self.lisa = lisa
     self.configuration = configuration
     mongo = MongoClient(host=self.configuration['database']['server'],
                         port=self.configuration['database']['port'])
     self.database = mongo.lisa
     self.wit = Wit(self.configuration['wit_token'])
开发者ID:Acruxx,项目名称:LISA,代码行数:7,代码来源:intents.py

示例9: do

def do(text):
    witClient = Wit(access_token='Z2M5NG4DUAOD3IH24BNQSXGM4LGIK4PU')
    wolframClient = wolframalpha.Client('5G696A-TT6AEK7L74')
    response = witClient.message(text)
    intent = response['entities']['intent'][0]['value']
    if intent == 'weather':
        loc = Nominatim()
        loc = loc.geocode(response['entities']['location'][0]['value'])
        forecast = forecastio.load_forecast('17e86a360729736b727899a8135e33ad',loc.latitude, loc.longitude)
        return forecast.hourly().summary
    elif intent == 'greeting':
        return random.choice(greetings)
    elif intent == 'wikipedia':
        return wikipedia.summary(response['entities']['contact'][0]['value'], sentences=1)
    elif intent == 'curse':
        return 'Fuck you too!'
    else:
        return 'I did not understand what you said.'
开发者ID:thephantomblu,项目名称:jarvis,代码行数:18,代码来源:jarvis.py

示例10: __init__

    def __init__(self, wit_key, rive, bot, nyt_api, mongo):
        self.BOT = bot
        self.NYT_API = nyt_api

        self.wit_actions = {}
        self.wit_client = Wit(access_token=wit_key, actions=self.wit_actions)
        self.wit_empty_response = {'entities': []}
        self.WIT_SEARCH_QUERY_CONFIDENCE_THRESH = 0.5

        self.RIVE = rive

        self.MONGO = mongo

        self.emojis = pickle.load(open("message_processor/unicode_emoji.pickle", "rb"))
开发者ID:innainu,项目名称:climatechangebot,代码行数:14,代码来源:message_processor.py

示例11: processText

def processText(token, text, sessionId, funcs=None, context=None):
    out = []
    
    def say(session_id, context, msg):
        out.append(msg)

    def error(session_id, context, msg):
        print(u"aiwitutils.processText.error: [{msg}]".format(msg=msg))
        pass
    
    actions = dict(funcs) if isinstance(funcs, dict) else {}
    actions["say"] = say
    actions["error"] = error
    
    if "merge" not in actions:
        actions["merge"] = _mergeDefault
    
    client = Wit(token, actions)
    
    inCtx = context if context else {}
    
    outerCtx = client.run_actions(sessionId, text, inCtx)

    return (out, outerCtx)
开发者ID:yaalaa,项目名称:juxy,代码行数:24,代码来源:aiwitutils.py

示例12: witintents

    def witintents(self, request, **kwargs):
        self.method_check(request, allowed=['get'])
        self.is_authenticated(request)
        self.throttle_check(request)
        self.wit = Wit(configuration['wit_token'])

        from tastypie.http import HttpAccepted, HttpNotModified

        try:
            intents = self.wit.get_intents()
        except:
            log.err()
            return self.create_response(request, { 'status' : 'failure' }, HttpNotModified)
        self.log_throttled_access(request)
        return self.create_response(request, { 'status': 'success', 'intents': intents}, HttpAccepted)
开发者ID:baiyishr,项目名称:LISA,代码行数:15,代码来源:apilisa.py

示例13: RulesEngine

class RulesEngine():
    def __init__(self):
        client = MongoClient(configuration['database']['server'], configuration['database']['port'])
        self.database = client.lisa

        self.wit = Wit(configuration['wit_server_token'])

    def Rules(self, jsonData, lisaprotocol):
        rulescollection = self.database.rules
        intentscollection = self.database.intents
        if "outcome" in jsonData.keys():
            jsonInput = {}
            jsonInput['outcome'] = jsonData['outcome']
        else:
            jsonInput = self.wit.get_message(unicode(jsonData['body']))
        jsonInput['from'], jsonInput['type'], jsonInput['zone'] = jsonData['from'], jsonData['type'], jsonData['zone']

        if configuration['debug']['debug_before_before_rule']:
            log.msg(unicode(_("Before 'before' rule: %(jsonInput)s" % {'jsonInput': str(jsonInput)})))
        for rule in rulescollection.find({"enabled": True, "before": {"$ne":None}}).sort([("order", 1)]):
            exec(rule['before'])
        if configuration['debug']['debug_after_before_rule']:
            log.msg(unicode(_("After 'before' rule: %(jsonInput)s" % {'jsonInput': str(jsonInput)})))
        if configuration['debug']['debug_wit']:
            log.msg("WIT: " + str(jsonInput['outcome']))

        oIntent = intentscollection.find_one({"name": jsonInput['outcome']['intent']})
        if oIntent and jsonInput['outcome']['confidence'] >= configuration['wit_confidence']:
            instance = namedAny(str(oIntent["module"]))()
            methodToCall = getattr(instance, oIntent['function'])
            jsonOutput = methodToCall(jsonInput)
        else:
            jsonOutput = {}
            jsonOutput['plugin'] = "None"
            jsonOutput['method'] = "None"
            jsonOutput['body'] = _("I have not the right plugin installed to answer you correctly")
        jsonOutput['from'] = jsonData['from']
        if configuration['debug']['debug_before_after_rule']:
            log.msg(unicode(_("Before 'after' rule: %(jsonOutput)s" % {'jsonOutput': str(jsonOutput)})))
        for rule in rulescollection.find({"enabled": True, "after": {"$ne":None}}).sort([("order", 1)]):
            exec(rule['after'])
            #todo it doesn't check if the condition of the rule after has matched to end the rules
            if rule['end']:
                break
        if configuration['debug']['debug_after_after_rule']:
            log.msg(unicode(_("After 'after' rule: %(jsonOutput)s" % {'jsonOutput': str(jsonOutput)})))
开发者ID:amreha2002,项目名称:LISA,代码行数:46,代码来源:rulesengine.py

示例14: __init__

    def __init__(self, factory):
        # Init thread class
        threading.Thread.__init__(self)
        self._stopevent = threading.Event()
        self.running_state = False
        self.rec_sink = None

        self.factory = factory
        self.configuration = ConfigManager.getConfiguration()
        self.wit = Wit(self.configuration['wit_token'])
        self.wit_context = None
        self.record = {'activated' : False, 'start' : 0, 'started' : False, 'end' : 0, 'ended' : False, 'buffers' : deque({})}
        self.continuous_mode = False
        self.temp_file = "/tmp/asr_sound"

        # Start thread
        threading.Thread.start(self)
开发者ID:gdumee,项目名称:LISA-CLIENT-Linux,代码行数:17,代码来源:recorder.py

示例15: WitMiddleware

class WitMiddleware(MiddlewareMixin):
    WIT_DATA_KEY = "_wit"
    WIT_CONTEXT_KEY = "_context"

    def __init__(self, *args, **kwargs):
        from wit import Wit
        self.access_token = kwargs.pop("access_token", None)
        self.actions = kwargs.pop("actions", {})
        self.client = Wit(access_token=self.access_token, actions=self.actions)
        super().__init__(*args, **kwargs)

    def process_request(self, request: BotRequest):
        if request.text:
            user_data = request.user_storage.get(request.user_id)
            wit_data = user_data.get(self.WIT_DATA_KEY, {})
            context = wit_data.get(self.WIT_CONTEXT_KEY, {})

            result_context = self.client.run_actions(str(request.user_id), request.text, context)
            wit_data[self.WIT_CONTEXT_KEY] = result_context
开发者ID:python-bot,项目名称:python-bot,代码行数:19,代码来源:wit_middleware.py


注:本文中的wit.Wit类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。