本文整理汇总了Python中wit.Wit类的典型用法代码示例。如果您正苦于以下问题:Python Wit类的具体用法?Python Wit怎么用?Python Wit使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Wit类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: __init__
def __init__(self, lisa_client, listener):
# Init thread class
threading.Thread.__init__(self)
self._stopevent = threading.Event()
self.lisa_client = lisa_client
self.configuration = ConfigManagerSingleton.get().getConfiguration()
self.pipeline = listener.get_pipeline()
self.capture_buffers = deque([])
self.running_state = False
self.wit = Wit(self.configuration['wit_token'])
self.wit_confidence = 0.5
if self.configuration.has_key('confidence'):
self.wit_confidence = self.configuration['wit_confidence']
self.record_time_start = 0
self.record_time_end = 0
# Get app sink
self.rec_sink = self.pipeline.get_by_name('rec_sink')
self.rec_sink.connect('new-buffer', self._capture_audio_buffer)
# Configure vader
# Using vader on pocketsphinx branch and not a vader on record branch,
# because vader forces stream to 8KHz, so record quality would be worst
vader = self.pipeline.get_by_name('vad_asr')
vader.connect('vader-start', self._vader_start)
vader.connect('vader-stop', self._vader_stop)
# Get elements to connect/disconnect pockesphinx during record
self.asr_tee = self.pipeline.get_by_name('asr_tee')
self.asr_sink = self.pipeline.get_by_name('asr_sink')
self.asr = self.pipeline.get_by_name('asr')
self.asr_tee.unlink(self.asr_sink)
# Start thread
self.start()
开发者ID:Seraf,项目名称:LISA-CLIENT-Linux,代码行数:36,代码来源:recorder.py
示例17: LisaResource
#.........这里部分代码省略.........
command = ['pico2wave', '-w', temp, '-l', language, '--', message]
try:
call(command)
#combined_sound.append(content)
except OSError:
log.err()
return self.create_response(request, { 'status' : 'failure' }, HttpNotModified)
f = open(temp,"rb")
combined_sound.append(f.read())
f.close()
os.remove(temp)
self.log_throttled_access(request)
return HttpResponse(''.join(combined_sound), content_type="audio/mpeg", mimetype="audio/mpeg")
def engine_reload(self, request, **kwargs):
self.method_check(request, allowed=['get'])
self.is_authenticated(request)
self.throttle_check(request)
from tastypie.http import HttpAccepted, HttpNotModified
try:
LisaFactorySingleton.get().LisaReload()
except:
log.err()
return self.create_response(request, { 'status' : 'failure' }, HttpNotModified)
self.log_throttled_access(request)
return self.create_response(request, { 'status': 'success', 'log': "L.I.S.A Engine reloaded"}, HttpAccepted)
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)
def scheduler_reload(self, request, **kwargs):
self.method_check(request, allowed=['get'])
self.is_authenticated(request)
self.throttle_check(request)
from tastypie.http import HttpAccepted, HttpNotModified
try:
LisaFactorySingleton.get().SchedReload()
except:
log.err()
return self.create_response(request, { 'status' : 'failure' }, HttpNotModified)
self.log_throttled_access(request)
return self.create_response(request, {'status': 'success', 'log': 'L.I.S.A Task Scheduler reloaded'},
HttpAccepted)
def configuration(self, request, **kwargs):
self.method_check(request, allowed=['get'])
self.is_authenticated(request)
self.throttle_check(request)
开发者ID:baiyishr,项目名称:LISA,代码行数:66,代码来源:apilisa.py
示例18: Recorder
class Recorder(threading.Thread):
def __init__(self, lisa_client, listener):
# Init thread class
threading.Thread.__init__(self)
self._stopevent = threading.Event()
self.lisa_client = lisa_client
self.configuration = ConfigManagerSingleton.get().getConfiguration()
self.pipeline = listener.get_pipeline()
self.capture_buffers = deque([])
self.running_state = False
self.wit = Wit(self.configuration['wit_token'])
self.wit_confidence = 0.5
if self.configuration.has_key('confidence'):
self.wit_confidence = self.configuration['wit_confidence']
self.record_time_start = 0
self.record_time_end = 0
# Get app sink
self.rec_sink = self.pipeline.get_by_name('rec_sink')
self.rec_sink.connect('new-buffer', self._capture_audio_buffer)
# Configure vader
# Using vader on pocketsphinx branch and not a vader on record branch,
# because vader forces stream to 8KHz, so record quality would be worst
vader = self.pipeline.get_by_name('vad_asr')
vader.connect('vader-start', self._vader_start)
vader.connect('vader-stop', self._vader_stop)
# Get elements to connect/disconnect pockesphinx during record
self.asr_tee = self.pipeline.get_by_name('asr_tee')
self.asr_sink = self.pipeline.get_by_name('asr_sink')
self.asr = self.pipeline.get_by_name('asr')
self.asr_tee.unlink(self.asr_sink)
# Start thread
self.start()
def stop(self):
# Raise stop event
self.running_state = False
self._stopevent.set()
def get_running_state(self):
"""
Is the recorder recording?
"""
return self.running_state
def set_running_state(self, running):
"""
Start/Stop a voice record
"""
if running == True and self.running_state == False:
self.running_state = True
# Disconnect pocketsphinx from pipeline
self.asr_tee.link(self.asr_sink)
self.asr_tee.unlink(self.asr)
elif running == True and self.running_state == True:
self.running_state = False
def run(self):
"""
Recorder main loop
"""
CONTENT_TYPE = 'audio/mpeg3'
result = ""
retry = 1
# Thread loop
while not self._stopevent.isSet():
# Wait record order
if self.running_state == False:
sleep(.1)
continue
# Activate capture, wait for 2s of silence before cancelling
wit_e = None
self.record_time_start = 0
self.record_time_end = time.time() + 2
self.capture_buffers.clear()
result = ""
print '\n [Recording]' + ' ' * 20 + '[Recording]'
# Send captured voice to wit
try:
result = self.wit.post_speech(data = self._read_audio_buffer(), content_type=CONTENT_TYPE)
except Exception as e:
wit_e = e
# If record was stopped during recording
if self.running_state == True:
# If Wit did not succeeded
if len(result) == 0 or result.has_key('outcome') == False or result['outcome'].has_key('confidence') == False or result['outcome']['confidence'] < self.wit_confidence:
if wit_e is not None:
log.err("Wit exception : " + str(e))
# If retry is available and vader detected an utterance
#.........这里部分代码省略.........
开发者ID:Seraf,项目名称:LISA-CLIENT-Linux,代码行数:101,代码来源:recorder.py
示例19: say
from wit import Wit
access_token = 'YOUR_ACCESS_TOKEN'
def say(session_id, msg):
print(msg)
def merge(context, entities):
return context
def error(session_id, msg):
print('Oops, I don\'t know what to do.')
actions = {
'say': say,
'merge': merge,
'error': error,
}
client = Wit(access_token, actions)
session_id = 'my-user-id-42'
client.run_actions(session_id, 'your message', {})
开发者ID:Liferenko,项目名称:pywit,代码行数:25,代码来源:template.py
示例20: Recorder
class Recorder(threading.Thread):
"""
Continuous recording class.
"""
#-----------------------------------------------------------------------------
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)
#-----------------------------------------------------------------------------
def setRunningState(self, state, rec_sink = None):
self.running_state = state
# Get app sink
if rec_sink is not None and self.rec_sink is not rec_sink:
self.rec_sink = rec_sink
self.rec_sink.connect('new-buffer', self._captureAudioBuffer)
#-----------------------------------------------------------------------------
def stop(self):
# Raise stop event
self._stopevent.set()
#-----------------------------------------------------------------------------
def activate(self):
"""
Called to activate current utter as a record
"""
# Activate record
if self.record['started'] == True:
self.record['activated'] = True
#-----------------------------------------------------------------------------
def setContinuousMode(self, enabled, wit_context = None):
"""
Called to activate continous record mode
"""
# Activate record
self.continuous_mode = enabled
self.wit_context = wit_context
#-----------------------------------------------------------------------------
def run(self):
"""
Recorder main loop
"""
# Encoded format
CONTENT_TYPE = 'audio/mpeg3'
# Thread loop
while not self._stopevent.isSet():
# Test if record is ended
if self.record['started'] == True and self.record['ended'] == False and self.record['end'] <= time():
# If current record was not activated before end
if self.record['activated'] == False and self.continuous_mode == False:
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"
#.........这里部分代码省略.........
开发者ID:gdumee,项目名称:LISA-CLIENT-Linux,代码行数:101,代码来源:recorder.py
注:本文中的wit.Wit类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论