本文整理汇总了Python中adapt.engine.IntentDeterminationEngine类的典型用法代码示例。如果您正苦于以下问题:Python IntentDeterminationEngine类的具体用法?Python IntentDeterminationEngine怎么用?Python IntentDeterminationEngine使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了IntentDeterminationEngine类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: IntentEngineTests
class IntentEngineTests(unittest.TestCase):
def setUp(self):
self.engine = IntentDeterminationEngine()
def testRegisterIntentParser(self):
assert len(self.engine.intent_parsers) == 0
try:
self.engine.register_intent_parser("NOTAPARSER")
assert "Did not fail to register invalid intent parser" and False
except ValueError, e:
pass
parser = IntentBuilder("Intent").build()
self.engine.register_intent_parser(parser)
assert len(self.engine.intent_parsers) == 1
示例2: __init__
def __init__(self, emitter):
self.config = Configuration.get().get('context', {})
self.engine = IntentDeterminationEngine()
# Dictionary for translating a skill id to a name
self.skill_names = {}
# Context related intializations
self.context_keywords = self.config.get('keywords', [])
self.context_max_frames = self.config.get('max_frames', 3)
self.context_timeout = self.config.get('timeout', 2)
self.context_greedy = self.config.get('greedy', False)
self.context_manager = ContextManager(self.context_timeout)
self.emitter = emitter
self.emitter.on('register_vocab', self.handle_register_vocab)
self.emitter.on('register_intent', self.handle_register_intent)
self.emitter.on('recognizer_loop:utterance', self.handle_utterance)
self.emitter.on('detach_intent', self.handle_detach_intent)
self.emitter.on('detach_skill', self.handle_detach_skill)
# Context related handlers
self.emitter.on('add_context', self.handle_add_context)
self.emitter.on('remove_context', self.handle_remove_context)
self.emitter.on('clear_context', self.handle_clear_context)
# Converse method
self.emitter.on('skill.converse.response',
self.handle_converse_response)
self.emitter.on('mycroft.speech.recognition.unknown',
self.reset_converse)
self.emitter.on('mycroft.skills.loaded', self.update_skill_name_dict)
def add_active_skill_handler(message):
self.add_active_skill(message.data['skill_id'])
self.emitter.on('active_skill_request', add_active_skill_handler)
self.active_skills = [] # [skill_id , timestamp]
self.converse_timeout = 5 # minutes to prune active_skills
示例3: IntentSkill
class IntentSkill(MycroftSkill):
def __init__(self):
MycroftSkill.__init__(self, name="IntentSkill")
self.engine = IntentDeterminationEngine()
def initialize(self):
self.emitter.on('register_vocab', self.handle_register_vocab)
self.emitter.on('register_intent', self.handle_register_intent)
self.emitter.on('recognizer_loop:utterance', self.handle_utterance)
self.emitter.on('detach_intent', self.handle_detach_intent)
def handle_utterance(self, message):
utterances = message.metadata.get('utterances', '')
best_intent = None
for utterance in utterances:
try:
best_intent = next(self.engine.determine_intent(utterance, num_results=100))
best_intent['utterance'] = utterance # TODO - Should Adapt handle this?
except StopIteration, e:
continue
if best_intent and best_intent.get('confidence', 0.0) > 0.0:
reply = message.reply(best_intent.get('intent_type'), metadata=best_intent)
self.emitter.emit(reply)
elif len(utterances) == 1:
self.emitter.emit(Message("intent_failure", metadata={"utterance": utterances[0]}))
else:
self.emitter.emit(Message("multi_utterance_intent_failure", metadata={"utterances": utterances}))
示例4: __init__
def __init__(self, emitter):
self.engine = IntentDeterminationEngine()
self.emitter = emitter
self.emitter.on('register_vocab', self.handle_register_vocab)
self.emitter.on('register_intent', self.handle_register_intent)
self.emitter.on('recognizer_loop:utterance', self.handle_utterance)
self.emitter.on('detach_intent', self.handle_detach_intent)
self.emitter.on('detach_skill', self.handle_detach_skill)
示例5: get_intent
def get_intent(message):
engine = IntentDeterminationEngine()
keywords = [
'service',
'med',
'clinic',
'walk in',
]
for key in keywords:
engine.register_entity(key, "KeyWords")
print(os.getcwd())
with open(os.getcwd() + '/home/addresses.csv', 'rb') as csvfile:
records = csv.reader(csvfile, delimiter=',')
street_number = []
street_name = []
for row in records:
street_number.append(row[8])
street_name.append(row[11])
for key in street_number:
engine.register_entity(key, "StreetNumber")
for key in street_name:
engine.register_entity(key, "StreetName")
address_intent = IntentBuilder("AddressIntent")\
.require("KeyWords")\
.optionally("StreetNumber")\
.optionally("StreetName")\
.build()
engine.register_intent_parser(address_intent)
for intent in engine.determine_intent(''.join(message)):
return intent
示例6: IntentService
class IntentService(object):
def __init__(self, emitter):
self.engine = IntentDeterminationEngine()
self.emitter = emitter
self.emitter.on('register_vocab', self.handle_register_vocab)
self.emitter.on('register_intent', self.handle_register_intent)
self.emitter.on('recognizer_loop:utterance', self.handle_utterance)
self.emitter.on('detach_intent', self.handle_detach_intent)
self.emitter.on('detach_skill', self.handle_detach_skill)
def handle_utterance(self, message):
# Get language of the utterance
lang = message.data.get('lang', None)
if not lang:
lang = "en-us"
utterances = message.data.get('utterances', '')
best_intent = None
for utterance in utterances:
try:
# normalize() changes "it's a boy" to "it is boy", etc.
best_intent = next(self.engine.determine_intent(
normalize(utterance, lang), 100))
# TODO - Should Adapt handle this?
best_intent['utterance'] = utterance
except StopIteration, e:
logger.exception(e)
continue
if best_intent and best_intent.get('confidence', 0.0) > 0.0:
reply = message.reply(
best_intent.get('intent_type'), best_intent)
self.emitter.emit(reply)
elif len(utterances) == 1:
self.emitter.emit(Message("intent_failure", {
"utterance": utterances[0],
"lang": lang
}))
else:
self.emitter.emit(Message("multi_utterance_intent_failure", {
"utterances": utterances,
"lang": lang
}))
示例7: __init__
def __init__(self, emitter):
self.config = Configuration.get().get('context', {})
self.engine = IntentDeterminationEngine()
self.context_keywords = self.config.get('keywords', [])
self.context_max_frames = self.config.get('max_frames', 3)
self.context_timeout = self.config.get('timeout', 2)
self.context_greedy = self.config.get('greedy', False)
self.context_manager = ContextManager(self.context_timeout)
self.emitter = emitter
self.emitter.on('register_vocab', self.handle_register_vocab)
self.emitter.on('register_intent', self.handle_register_intent)
self.emitter.on('recognizer_loop:utterance', self.handle_utterance)
self.emitter.on('detach_intent', self.handle_detach_intent)
self.emitter.on('detach_skill', self.handle_detach_skill)
# Context related handlers
self.emitter.on('add_context', self.handle_add_context)
self.emitter.on('remove_context', self.handle_remove_context)
self.emitter.on('clear_context', self.handle_clear_context)
# Converse method
self.emitter.on('skill.converse.response',
self.handle_converse_response)
self.active_skills = [] # [skill_id , timestamp]
self.converse_timeout = 5 # minutes to prune active_skills
示例8: __init__
class input_engine:
"""Manages the intent engine and natural language input parser"""
def __init__(self):
self.engine = IntentDeterminationEngine()
def register_entity(self, keywords, name):
"""Registers an intenty to be found in an input"""
for k in keywords:
self.engine.register_entity(k, name)
def register_intent(self, intent):
"""Registers an intent that can be found in an input"""
self.engine.register_intent_parser(intent)
def get_intent(self, input_string):
"""Returns an intent from an input string if one is found"""
intent = self.engine.determine_intent(input_string)
for intent in self.engine.determine_intent(input_string):
if intent.get("confidence") > 0:
return intent
return None
示例9: IntentSkill
class IntentSkill(BoomerSkill):
def __init__(self):
BoomerSkill.__init__(self, name="IntentSkill")
self.engine = IntentDeterminationEngine()
def initialize(self):
self.emitter.on('register_vocab', self.handle_register_vocab)
self.emitter.on('register_intent', self.handle_register_intent)
self.emitter.on('recognizer_loop:utterance', self.handle_utterance)
self.emitter.on('detach_intent', self.handle_detach_intent)
def handle_utterance(self, message):
timer = Stopwatch()
timer.start()
metrics = MetricsAggregator()
utterances = message.data.get('utterances', '')
best_intent = None
for utterance in utterances:
metrics.increment("utterances.count")
for intent in self.engine.determine_intent(
utterance, num_results=100):
metrics.increment("intents.count")
intent['utterance'] = utterance
best_confidence = best_intent.get('confidence') \
if best_intent else 0.0
cur_confidence = intent.get('confidence', 0.0)
if best_confidence < cur_confidence:
best_intent = intent
if best_intent and best_intent.get('confidence', 0.0) > 0.0:
reply = message.reply(
best_intent.get('intent_type'), data=best_intent)
self.emitter.emit(reply)
elif len(utterances) == 1:
self.emitter.emit(
Message("intent_failure",
data={"utterance": utterances[0]}))
else:
self.emitter.emit(
Message("multi_utterance_intent_failure",
data={"utterances": utterances}))
metrics.timer("parse.time", timer.stop())
metrics.flush()
def handle_register_vocab(self, message):
start_concept = message.data.get('start')
end_concept = message.data.get('end')
regex_str = message.data.get('regex')
alias_of = message.data.get('alias_of')
if regex_str:
self.engine.register_regex_entity(regex_str)
else:
self.engine.register_entity(
start_concept, end_concept, alias_of=alias_of)
def handle_register_intent(self, message):
intent = open_intent_envelope(message)
self.engine.register_intent_parser(intent)
def handle_detach_intent(self, message):
intent_name = message.data.get('intent_name')
new_parsers = [
p for p in self.engine.intent_parsers if p.name != intent_name]
self.engine.intent_parsers = new_parsers
def stop(self):
pass
示例10: Flask
from flask import request
from adapt.entity_tagger import EntityTagger
from adapt.tools.text.tokenizer import EnglishTokenizer
from adapt.tools.text.trie import Trie
from adapt.intent import IntentBuilder
from adapt.parser import Parser
from adapt.engine import IntentDeterminationEngine
app = Flask(__name__)
tokenizer = EnglishTokenizer()
trie = Trie()
tagger = EntityTagger(trie, tokenizer)
parser = Parser(tokenizer, tagger)
engine = IntentDeterminationEngine()
# create and register weather vocabulary
weather_keyword = [
"weather"
]
for wk in weather_keyword:
engine.register_entity(wk, "WeatherKeyword")
weather_types = [
"snow",
"rain",
"wind",
"sleet",
"sun"
示例11: len
import json
import sys
# If there's a second argument given, use that to insert an import path
# This enables users to use their own Adapt installation directories.
if len(sys.argv) > 2:
sys.path.insert(0, sys.argv[2])
from adapt.intent import IntentBuilder
from adapt.engine import IntentDeterminationEngine
engine = IntentDeterminationEngine()
schema = json.loads(sys.argv[1])
for entity in schema["entities"]:
if entity["type"] == "string":
for value in entity["values"]:
engine.register_entity(value, entity["name"])
elif entity["type"] == "regex":
engine.register_regex_entity(entity["pattern"])
for intent in schema["intents"]:
ib = IntentBuilder(intent["name"].encode("utf-8"))
for requirement in intent["requirements"]:
ib.require(requirement["entity"], requirement["attribute"])
for optional in intent["optionals"]:
ib.optionally(optional["entity"], optional["attribute"])
engine.register_intent_parser(ib.build())
if __name__ == "__main__":
示例12: skyAdapt
def skyAdapt():
engine = IntentDeterminationEngine()
#dota vocabulary
dota_keywords = [ 'dota', 'dotes', 'dote']
for dk in dota_keywords:
engine.register_entity(dk, "DotaKeyword")
happening_keywords = [
'happening',
'anyone up for',
'when is',
'what time',
'tonight',
'this evening?',
'anyone about for',
'around',
'want to',
'fancy some',
'playing some',
'anyone playing'
]
for hk in happening_keywords:
engine.register_entity(hk, "HappeningKeyword")
dota_query_intent = IntentBuilder("DotaIntent")\
.require("DotaKeyword")\
.require("HappeningKeyword")\
.build()
stack_intent_words = [
'stack',
'stacked'
]
for sik in stack_intent_words:
engine.register_entity(hk, "StackKeyword")
stack_optionals = [
'are we',
'do we have a',
'how many',
'who\'s playing'
]
for osk in stack_optionals:
engine.register_entity(hk, "StackOptionalKeyword")
stack_intent = IntentBuilder("StackIntent")\
.require("StackKeyword")\
.optionally("StackOptionalKeyword")\
.build()
engine.register_regex_entity("at (?P<Time>.*)")
new_dota_intent = IntentBuilder("NewDotaIntent")\
.require("DotaKeyword")\
.require("Time")\
.build()
engine.register_intent_parser(dota_query_intent)
engine.register_intent_parser(stack_intent)
engine.register_intent_parser(new_dota_intent)
return engine
示例13: IntentService
class IntentService(object):
def __init__(self, emitter):
self.config = ConfigurationManager.get().get('context', {})
self.engine = IntentDeterminationEngine()
self.context_keywords = self.config.get('keywords', ['Location'])
self.context_max_frames = self.config.get('max_frames', 3)
self.context_timeout = self.config.get('timeout', 2)
self.context_greedy = self.config.get('greedy', False)
self.context_manager = ContextManager(self.context_timeout)
self.emitter = emitter
self.emitter.on('register_vocab', self.handle_register_vocab)
self.emitter.on('register_intent', self.handle_register_intent)
self.emitter.on('recognizer_loop:utterance', self.handle_utterance)
self.emitter.on('detach_intent', self.handle_detach_intent)
self.emitter.on('detach_skill', self.handle_detach_skill)
# Context related handlers
self.emitter.on('add_context', self.handle_add_context)
self.emitter.on('remove_context', self.handle_remove_context)
self.emitter.on('clear_context', self.handle_clear_context)
# Converse method
self.emitter.on('skill.converse.response',
self.handle_converse_response)
self.active_skills = [] # [skill_id , timestamp]
self.converse_timeout = 5 # minutes to prune active_skills
def do_converse(self, utterances, skill_id, lang):
self.emitter.emit(Message("skill.converse.request", {
"skill_id": skill_id, "utterances": utterances, "lang": lang}))
self.waiting = True
self.result = False
start_time = time.time()
t = 0
while self.waiting and t < 5:
t = time.time() - start_time
time.sleep(0.1)
self.waiting = False
return self.result
def handle_converse_response(self, message):
# id = message.data["skill_id"]
# no need to crosscheck id because waiting before new request is made
# no other skill will make this request is safe assumption
result = message.data["result"]
self.result = result
self.waiting = False
def remove_active_skill(self, skill_id):
for skill in self.active_skills:
if skill[0] == skill_id:
self.active_skills.remove(skill)
def add_active_skill(self, skill_id):
# search the list for an existing entry that already contains it
# and remove that reference
self.remove_active_skill(skill_id)
# add skill with timestamp to start of skill_list
self.active_skills.insert(0, [skill_id, time.time()])
def update_context(self, intent):
"""
updates context with keyword from the intent.
NOTE: This method currently won't handle one_of intent keywords
since it's not using quite the same format as other intent
keywords. This is under investigation in adapt, PR pending.
Args:
intent: Intent to scan for keywords
"""
for tag in intent['__tags__']:
if 'entities' not in tag:
continue
context_entity = tag['entities'][0]
if self.context_greedy:
self.context_manager.inject_context(context_entity)
elif context_entity['data'][0][1] in self.context_keywords:
self.context_manager.inject_context(context_entity)
def handle_utterance(self, message):
# Get language of the utterance
lang = message.data.get('lang', None)
if not lang:
lang = "en-us"
utterances = message.data.get('utterances', '')
# check for conversation time-out
self.active_skills = [skill for skill in self.active_skills
if time.time() - skill[
1] <= self.converse_timeout * 60]
# check if any skill wants to handle utterance
for skill in self.active_skills:
if self.do_converse(utterances, skill[0], lang):
# update timestamp, or there will be a timeout where
# intent stops conversing whether its being used or not
self.add_active_skill(skill[0])
return
# no skill wants to handle utterance
#.........这里部分代码省略.........
示例14: Flask
from flask import request
from adapt.entity_tagger import EntityTagger
from adapt.tools.text.tokenizer import EnglishTokenizer
from adapt.tools.text.trie import Trie
from adapt.intent import IntentBuilder
from adapt.parser import Parser
from adapt.engine import IntentDeterminationEngine
app = Flask(__name__)
tokenizer = EnglishTokenizer()
trie = Trie()
tagger = EntityTagger(trie, tokenizer)
parser = Parser(tokenizer, tagger)
engine = IntentDeterminationEngine()
# create and register weather vocabulary
error_keyword = [
"error",
"e",
"E"
]
for er in error_keyword:
engine.register_entity(er, "ErrorKeyword")
error_types = [
"E16",
"E17",
"E19",
示例15: setUp
def setUp(self):
self.context_manager = ContextManager()
self.engine = IntentDeterminationEngine()