本文整理匯總了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)
示例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
示例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)
示例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
示例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)
示例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()
示例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()
示例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'])
示例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.'
示例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"))
示例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)
示例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)
示例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)})))
示例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)
示例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