Skip to content

Instantly share code, notes, and snippets.

@B0073D
Last active January 21, 2016 15:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save B0073D/ea5922a124cb493877d3 to your computer and use it in GitHub Desktop.
Save B0073D/ea5922a124cb493877d3 to your computer and use it in GitHub Desktop.
Early work for Sopel Adapt integration. This could be one possible way for Adapt to be used in a 'simple' manner.
import sopel.module
import sopel.formatting
# Adapt imports:
import json
from adapt.intent import IntentBuilder
from adapt.engine import IntentDeterminationEngine
def adapter(*intent_list):
"""Decorator. This adds some values to the decorated function which adapt can use later on."""
def add_attribute(function):
if not hasattr(function, "adapt"):
function.adapt = []
function.adapt.extend(intent_list)
return function
return add_attribute
@sopel.module.commands('hey')
@sopel.module.rule('$nickname[:,](.*)')
def adapt_attention(bot, trigger):
adapt_funcs = []
for priority in ('high', 'medium', 'low'):
items = bot._callables[priority].items()
for regexp, funcs in items:
for func in funcs:
if hasattr(func, 'adapt') and func.__name__ != adapt_attention:
print "Got one: " + str(func)
adapt_funcs.append(func)
if len(adapt_funcs) > 0:
engine = IntentDeterminationEngine()
intent_funcs = {}
for func in adapt_funcs:
enginesettings = func.adapt[0]
print(json.dumps(enginesettings, indent=4))
if enginesettings['intentname'] not in intent_funcs:
intent_funcs[enginesettings['intentname']] = {}
intent_funcs[enginesettings['intentname']]['func'] = func
intent_funcs[enginesettings['intentname']]['struct'] = enginesettings
for entity in enginesettings['keywordarrays'].keys():
for keyword in enginesettings['keywordarrays'][entity]:
engine.register_entity(keyword, entity)
for regex in enginesettings['regexes']:
engine.register_regex_entity(regex)
intent = IntentBuilder(enginesettings['intentname'])
for construct in enginesettings['blueprint']:
if construct[0] == 'req':
intent = intent.require(construct[1])
elif construct[0] == 'opt':
intent = intent.optionally(construct[1])
intent = intent.build()
engine.register_intent_parser(intent)
for possibleintent in engine.determine_intent(trigger):
if possibleintent and possibleintent.get('confidence') > 0:
print(json.dumps(possibleintent, indent=4))
print trigger.group
class FakeTrigger(object): # Cannot change Trigger class easily so using a fake trigger class.
# TODO FakeTrigger needs a proper replacement.
tmp_group = ['', '', None]
def group(self, index):
return self.tmp_group[index]
newtrigger = FakeTrigger()
newtrigger.tmp_group = ['', '', None]
for output in intent_funcs[possibleintent['intent_type']]['struct']['output']:
if output in possibleintent:
newtrigger.tmp_group = ['', '', possibleintent[output]]
intent_funcs[possibleintent['intent_type']]['func'](bot, newtrigger)
maybeitworked_adapt_settings = {
'intentname': 'MaybeItWorked',
'keywordarrays': {
'WorkedKeywords': ['worked', 'functioned', 'work', 'function'],
'MaybeKeywords': ['maybe', 'perhaps']
},
'regexes': [],
'blueprint': [
('req', 'WorkedKeywords'),
('opt', 'MaybeKeywords')
],
'output': []
}
@adapter(maybeitworked_adapt_settings)
@sopel.module.commands('maybeitworked')
def maybe_it_worked(bot, trigger):
bot.say('Maybe it worked...')
icecream_adapt_settings = {
'intentname': 'Icecream',
'keywordarrays': {
'IcecreamKeywords': ['icecream', 'ice', 'cream', 'function'],
'FlavourKeywords': ['Chocolate', 'vanilla', 'charamel', 'strawberry']
},
'regexes': [],
'blueprint': [
('req', 'IcecreamKeywords'),
('opt', 'FlavourKeywords')
],
'output': ['FlavourKeywords']
}
@adapter(icecream_adapt_settings)
@sopel.module.commands('icecream')
def icecream(bot, trigger):
icecreamstring = 'Here, have some icecream'
if trigger.group(2):
icecreamstring += " it's " + trigger.group(2).rstrip(' ')
bot.say(icecreamstring)
weather_adapt_settings = {
'intentname': 'Weather',
'keywordarrays': {
'WeatherKeywords': ['weather', 'temperature']
},
'regexes': ["in (?P<Location>.*)"],
'blueprint': [
('req', 'WeatherKeywords'),
('req', 'Location')
],
'output': ['Location']
}
@adapter(weather_adapt_settings)
@sopel.module.commands('adaptweather')
def fancy_weather(bot, trigger):
if trigger.group(2) is None:
bot.say('Usage: .adaptweather <location>')
return
bot.say('Do I look like I know the weather for ' + trigger.group(2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment