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


Python Wit.get_message方法代码示例

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


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

示例1: PostTextString

# 需要导入模块: from wit import Wit [as 别名]
# 或者: from wit.Wit import get_message [as 别名]
 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,代码行数:9,代码来源:WitAiSpeechDecode.py

示例2: RulesEngine

# 需要导入模块: from wit import Wit [as 别名]
# 或者: from wit.Wit import get_message [as 别名]
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,代码行数:48,代码来源:rulesengine.py

示例3: ClientFactory

# 需要导入模块: from wit import Wit [as 别名]
# 或者: from wit.Wit import get_message [as 别名]

#.........这里部分代码省略.........
            client = self.clients[client_uid]

            # Each client has its own context
            client['context'] = NeoContext(client_uid = client_uid)

            # Add client to zone
            found_flag = False
            for c in self.zones[zone_uid]['client_uids']:
                if c == client['uid']:
                    found_flag = True
                    break
            if found_flag == False:
                self.zones[zone_uid]['client_uids'].append(client['uid'])

        # Release access
        self._lock.release()

        return client

    #-----------------------------------------------------------------------------
    @classmethod
    def parseChat(cls, jsonData, client_uid):
        # Create singleton
        if cls.__instance is None:
            cls.__instance = ClientFactory()
        self = cls.__instance

        # If input has already a decoded intent
        if jsonData.has_key("outcome") == True:
            jsonInput = {}
            jsonInput['outcome'] = jsonData['outcome']
        elif len(jsonData['body']) > 0:
            # Ask Wit for intent decoding
            jsonInput = self.wit.get_message(unicode(jsonData['body']))
        else:
            # No input => no output
            return

        # Initialize output from input
        jsonInput['from'], jsonInput['type'], jsonInput['zone'] = jsonData['from'], jsonData['type'], jsonData['zone']

        # Show wit result
        if configuration['debug']['debug_wit']:
            log.msg("WIT: " + str(jsonInput['outcome']))

        # Execute intent
        client = cls.getClient(client_uid)
        intent = PluginManager.getIntent(intent_name = jsonInput['outcome']['intent'])
        if intent is not None:
            # Call plugin
            client['context'].parse(jsonInput = jsonInput, plugin_name = intent.plugin_name, method_name = intent.method_name)
        else:
            # Parse without intent
            client['context'].parse(jsonInput = jsonInput)

    #-----------------------------------------------------------------------------
    @classmethod
    def getClient(cls, client_uid):
        # Get singleton
        if cls.__instance is None:
            return None

        # Return client
        return cls.__instance.clients[client_uid]

    #-----------------------------------------------------------------------------
开发者ID:gdumee,项目名称:LISA,代码行数:70,代码来源:server.py

示例4: Recorder

# 需要导入模块: from wit import Wit [as 别名]
# 或者: from wit.Wit import get_message [as 别名]

#.........这里部分代码省略.........
                    self.record['start'] = 0
                    self.record['started'] = False
                    self.record['end'] = 0
                    self.record['ended'] = False
                    self.record['activated'] = False

                    continue

                # Current record is activated and already ended
                self.record['ended'] = True

            # If current record is not activated
            if self.running_state == False or self.record['started'] == False or (self.record['activated'] == False and self.continuous_mode == False):
                sleep(.1)
                continue

            # Send activated record to Wit
            wit_e = None
            result = ""
            try:
                if self.configuration['asr'] == "ispeech":
                    for b in self._readAudioBuffer(file_mode = True):
                        pass
                    params= {}
                    params["action"] = "recognize"
                    params["apikey"] = "developerdemokeydeveloperdemokey"
                    params["freeform"] = "3"
                    params["locale"] = "fr-FR"
                    params["output"] = "json"
                    params["content-type"] = "speex"
                    params["speexmode"] = "2"
                    params["audio"] = base64.b64encode(open(self.temp_file, 'rt').read()).replace(b'\n',b'')
                    result = requests.get("http://api.ispeech.org/api/rest?" + urlencode(params))
                    result = self.wit.get_message(query = result.json()['text'], context = self.wit_context)

                elif self.configuration['asr'] == "google":
                    for b in self._readAudioBuffer(file_mode = True):
                        pass
                    url = 'https://www.google.com/speech-api/v2/recognize?output=json&lang=fr-fr&key=AIzaSyCQv4U1mTaw_r_j1bWb1peeaTihzV0q-EQ'
                    audio = open(self.temp_file, "rb").read()
                    header = {"Content-Type": "audio/x-flac; rate=16000"}
                    post = urlopen(Request(url, audio, header))
                    result = loads(post.read().split("\n")[1])['result'][0]['alternative'][0]['transcript']
                    result = self.wit.get_message(query = result, context = self.wit_context)

                # Defautl Wit
                else:
                    result = self.wit.post_speech(data = self._readAudioBuffer(), content_type = CONTENT_TYPE, context = self.wit_context)

                result['msg_body'] = result['msg_body'].encode("utf-8")
            except Exception as e:
                wit_e = e

            # If record was stopped during Wit access
            if self._stopevent.isSet():
                break

            # Question mode
            if len(result) > 0 and self.continuous_mode == True and result.has_key('msg_body') == True and len(result['msg_body']) > 0:
                # Send answer
                self.factory.sendChatToServer(message = result['msg_body'], outcome = result['outcome'])
            # If Wit did not succeeded
            elif len(result) == 0 or result.has_key('outcome') == False or result['outcome'].has_key('confidence') == False or result['outcome']['confidence'] < self.configuration['wit_confidence']:
                if wit_e is not None:
                    log.err("Wit exception : {0}".format(str(e)))
                elif len(result) == 0:
开发者ID:gdumee,项目名称:LISA-CLIENT-Linux,代码行数:70,代码来源:recorder.py


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