本文整理汇总了Python中rivescript.RiveScript.load_directory方法的典型用法代码示例。如果您正苦于以下问题:Python RiveScript.load_directory方法的具体用法?Python RiveScript.load_directory怎么用?Python RiveScript.load_directory使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rivescript.RiveScript
的用法示例。
在下文中一共展示了RiveScript.load_directory方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: bot_talk
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import load_directory [as 别名]
def bot_talk():
from rivescript import RiveScript
import sys, os
bot = RiveScript(utf8=True)
bot.load_directory("/home/mate/Downloads/web2py/applications/saria/static/riverscript/brain/")
#bot.load_directory("/home/relsi/Projetos/Web2py/pris/applications/saria/static/riverscript/brain")
bot.sort_replies()
msg = request.post_vars.chat_text
reply = bot.reply("localuser", msg.decode('utf-8'))
return reply
示例2: bot
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import load_directory [as 别名]
class bot():
"""This is a bare minimal example for how to write your own RiveScript bot!
For a more full-fledged example, try running: `python rivescript brain`
This will run the built-in Interactive Mode of the RiveScript library. It has
some more advanced features like supporting JSON for communication with the
bot. See `python rivescript --help` for more info.
example.py is just a simple script that loads the RiveScript documents from
the 'brain/' folder, and lets you chat with the bot.
Type /quit when you're done to exit this example.
"""
def __init__(self):
self.currentOperation = None
self.rs = RiveScript()
self.rs.load_directory(os.path.dirname(__file__) + "/rep_src")
self.rs.sort_replies()
def sanitizeUserQuery(self, userQuery):
return userQuery
def identifyOperation(self, userQuery):
"""
function identifyOperation(string: userQuery)
Output: ([keywords_in_input], [action_in_input])
"""
userQuery = self.sanitizeUserQuery(userQuery)
queryTokens = nltk.word_tokenize(userQuery)
pos = nltk.pos_tag(queryTokens)
keywords = []
verbs = []
adjective = []
for w in pos:
if w[1] == 'NN' or w[1] == 'NNP':
keywords.append(str(w[0]))
if w[1] == 'VB' or w[1] == 'VBD' or w[1] == 'VBN':
verbs.append(w[0])
if w[1] == 'JJ':
adjective.append(w[0])
# print(str(keywords).rsplit() + " " + str(verbs).rsplit() + " " + str(adjective).rsplit())
return (keywords, verbs, adjective)
def reply(self, user, msg):
# t = self.identifyOperation(msg)
# print(' '.join(t[0] + t[1] + t[2]))
return self.rs.reply(user, msg)
示例3: Aplicacion
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import load_directory [as 别名]
class Aplicacion(wx.Frame):
def __init__(self):
self.Ventana()
self.Agente()
# self.Respuesta("begin")
def Agente(self):
self.agente = RiveScript()
self.agente.load_directory("./recursos")
self.agente.sort_replies()
self.lector = Dispatch("SAPI.SpVoice")
if time.localtime().tm_hour < 12:
self.agente.set_variable("time", "dia")
else:
if time.localtime().tm_hour < 18:
self.agente.set_variable("time", "tarde")
else:
self.agente.set_variable("time", "noche")
def Ventana(self):
wx.Frame.__init__(self, None, style= wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX)
self.panel = wx.Panel(self)
self.texto = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE | wx.TE_READONLY, size= (293,350), pos = (5,5))
self.linea = wx.TextCtrl(self.panel, style=wx.TE_NO_VSCROLL | TE_PROCESS_ENTER, size= (200,50), pos = (10,365))
self.boton = wx.BitmapButton(self.panel, bitmap = wx.Bitmap("recursos\_enviar.png"), pos = (220, 360))
self.etiqueta = wx.StaticText(self.panel, label = "Proyecto Inteligencia Artificial - ULA, A2012 ", pos = (5, 425))
self.Bind(wx.EVT_TEXT_ENTER, self.Pregunta, self.linea)
self.Bind(wx.EVT_BUTTON, self.Pregunta, self.boton)
self.linea.SetFocus()
self.SetTitle("Representante de Atencion al Cliente")
self.SetSize((320,480))
self.Centre()
self.Show()
def Pregunta(self, evento):
self.texto.AppendText(" "+ str(self.linea.GetValue()).capitalize() + "\n")
self.Respuesta(self.linea.GetValue().__str__())
def Respuesta(self, texto):
bot = self.agente.reply("rac", texto)
self.linea.Clear()
self.texto.AppendText(str(bot) + "\n")
self.lector.Speak(bot)
示例4: RiveScript
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import load_directory [as 别名]
#!/usr/bin/python
import re
from flask import Flask, jsonify, render_template, request
from rivescript import RiveScript
from rivescript import sentences
rs = RiveScript(debug=False, utf8=True)
rs.load_directory("./brain_zh")
rs.sort_replies()
rs.train()
app = Flask(__name__)
@app.route('/reply')
def get_reply():
user = re.sub(ur'\W', '', request.remote_addr)
line = request.args.get('l','')
user = user.strip()
res = []
req = []
if user != '':
for msg in sentences(line):
if msg.strip() == '':
continue
reply = rs.reply(user, msg)
req.append(msg)
res.append(reply)
return jsonify(req=req, reply=res)
示例5: RiveScript
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import load_directory [as 别名]
os.path.dirname(__file__),
"..", "..",
))
sys.path.append(os.path.join(
os.path.dirname(__file__),
"..", "..",
"contrib", "redis",
))
from rivescript import RiveScript
from rivescript_redis import RedisSessionManager
bot = RiveScript(
session_manager=RedisSessionManager(),
)
bot.load_directory("../brain")
bot.sort_replies()
print("""RiveScript Redis Session Storage Example
This example uses a Redis server to store user variables. For the sake of the
example, choose a username to store your variables under. You can re-run this
script with the same username (or a different one!) and verify that your
variables are kept around!
Type '/quit' to quit.
""")
username = input("What is your username? ").strip()
if len(username) == 0:
print("You need to enter one! This script will exit now.")
示例6: RiveScript
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import load_directory [as 别名]
#!/usr/bin/python
from rivescript import RiveScript
rs = RiveScript()
rs.load_directory("../eg/brain/")
rs.sort_replies()
"""This is a bare minimal example for how to write your own RiveScript bot!
For a more full-fledged example, try running: `python rivescript brain`
This will run the built-in Interactive Mode of the RiveScript library. It has
some more advanced features like supporting JSON for communication with the
bot. See `python rivescript --help` for more info.
example.py is just a simple script that loads the RiveScript documents from
the 'brain/' folder, and lets you chat with the bot.
Type /quit when you're done to exit this example.
"""
print"""
"""
while True:
msg = raw_input("Vous > ")
if msg == '/quit':
quit()
示例7: AdmiralBot
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import load_directory [as 别名]
class AdmiralBot(object):
"""Chatbot instance for Admiral."""
###
# Initialization and Configuration
###
def __init__(self, debug=False, config="settings.yml",
defaults="defaults.yml", log_console=True):
"""Initialize the Admiral chatbot.
Parameters:
* debug: Enable debug logging to the console.
* config: The configuration file to use (default settings.yml)
* defaults: The name of the default config file (defaults.yml)
* log_console: Write logs to the console (STDOUT) as well as to the
log file on disk (default True).
"""
# Configurable parameters.
self.debug = debug
self.config = config
self.config_defaults = defaults
# Internal state variables.
self.running = False # Whether we're up and running
self.c = dict() # App configuration
self.bots = dict() # Individual bot interfaces
self.rs = None # RiveScript brain
# Load the bot's config.
self.load_config()
self.log = Logger(filename=self.c.logging.status,
console=log_console,
log_format=self.c.logging.format)
if debug:
self.log.set_level(logging.DEBUG)
self.log.debug("Debug logging enabled.")
# Run post-config initialization routines.
self.setup()
def load_config(self):
"""Load the configuration file from disk."""
project_settings = YamlSettings(self.config_defaults, self.config,
default_section="admiral")
self.c = project_settings.get_settings()
###
# Initial Setup Steps
###
def setup(self):
"""Run the setup steps."""
self.log.info("Welcome to Admiral.")
# Initialize the RiveScript brain.
self.reload_brain()
# Scan through the interfaces and find active bots.
self.log.info("Setting up interfaces...")
for interface in self.c.interfaces:
if not interface.enabled:
continue
if interface.id in self.bots:
self.panic("Duplicate ID: you have two or more interfaces "
"that use the ID name `{}` in your bot settings. You "
"should pick a unique ID name for each interface!")
self.bots[interface.id] = interface
# Get the interface class.
module = Interface.import_interface(interface.interface)
self.bots[interface.id].inst = module(master=self)
self.bots[interface.id].inst.setup(interface)
def reload_brain(self):
"""(Re)load the RiveScript brain for the bot."""
self.log.info("Loading RiveScript brain from {}".format(
self.c.personality.replies
))
self.rs = RiveScript(
debug=self.c.debug.rivescript,
utf8=True,
)
self.rs.load_directory(self.c.personality.replies)
self.rs.sort_replies()
###
# Start, stop, run commands.
###
def start(self):
"""Start up all the bots."""
if not self.running:
for name, bot in self.bots.items():
bot.inst.connect()
self.running = True
#.........这里部分代码省略.........
示例8: RiveScript
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import load_directory [as 别名]
# Manipulate sys.path to be able to import rivescript from this git repo.
# Otherwise you'd have to `pip install rivescript`
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "..", ".."))
from flask import Flask, request, redirect
from rivescript import RiveScript
import twilio.twiml
# Set up the RiveScript bot. This loads the replies from "../brain", or,
# the "brain" folder in the "eg" folder of this git repository.
bot = RiveScript()
bot.load_directory(
os.path.join(os.path.dirname(__file__), "..", "brain")
)
bot.sort_replies()
app = Flask(__name__)
@app.route("/twilio", methods=["GET", "POST"])
def hello_rivescript():
"""Receive an inbound SMS and send a reply from RiveScript."""
from_number = request.values.get("From", "unknown")
message = request.values.get("Body")
reply = "(Internal error)"
# Get a reply from RiveScript.
if message:
示例9: RiveScript
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import load_directory [as 别名]
from rivescript import RiveScript
bot = RiveScript()
bot.load_directory("../public/brain/")
bot.load_directory("../public/brain/commands")
bot.sort_replies()
while True:
msg = input("You> ")
if msg == "/quit":
quit()
reply = bot.reply("localuser", msg)
print("Bot>", reply)
示例10: Flask
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import load_directory [as 别名]
from message_processor.message_processor import MessageProcessor, ExternalApiParser
from nyt_interface.nyt_interface import NytimesApi
app = Flask(__name__)
mongo = PyMongo(app)
app.config.from_object("config.DevelopmentConfig")
app.config.from_pyfile("local.cfg")
bot = BotInterface(app.config['FB_API_VERSION'], app.config['FB_ACCESS_TOKEN'])
nyt_api = NytimesApi(app.config['NYT_KEY'])
rive = RiveScript()
rive.load_directory(
os.path.join(os.path.dirname(__file__), "message_processor", "rivescripts")
)
rive.sort_replies()
# external_api_parser = ExternalApiParser(app.config['WIT_KEY'], app.config['API_AI_KEY'], bot, nyt_api)
external_api_parser = ExternalApiParser(app.config['WIT_KEY'], rive, bot, nyt_api, mongo)
msgproc = MessageProcessor(bot, external_api_parser, app.config)
@app.route("/")
def index():
return render_template('messenger.html')
# return success(status=200, message="Hello world from climatechangebot!")
@app.route("/privacy")
示例11: RiveScript
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import load_directory [as 别名]
#!/usr/bin/python
# -*- coding: utf-8 -*-
from rivescript import RiveScript
rs = RiveScript(utf8 = True)
rs.load_directory("./cerveau")
rs.sort_replies()
while True:
msg = raw_input("Vous > ")
if msg == '/quit':
quit()
reply = u"{0}".format(rs.reply("localuser", msg))
print(u"Aria > {0}".format(reply))
示例12: onMessage
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import load_directory [as 别名]
def onMessage(self, messageProtocolEntity):
#send receipt otherwise we keep receiving the same message over and over
client = MongoClient()
db = client.data
if True:
rs=RiveScript()
rs.load_directory("./brain")
rs.sort_replies()
messageOut = ""
#print(messageProtocolEntity.getType() )
if messageProtocolEntity.getType() == "text":
#self.output(message.getBody(), tag = "%s [%s]"%(message.getFrom(), formattedDate))
"""
c = check()
para = messageProtocolEntity.getBody()
messageOut =c.func(para)
"""
messageOut = messageProtocolEntity.getBody()+' '
print(messageOut)
elif messageProtocolEntity.getType() == "media":
#self.getMediaMessageBody(messageProtocolEntity)
if self.onMediaMessage(messageProtocolEntity) == 1:
messageOut = "location code one "
elif self.onMediaMessage(messageProtocolEntity) == 2:
messageOut = "image code one "
elif self.onMediaMessage(messageProtocolEntity) == 3:
messageOut = "vcard recieved "
else:
messageOut = "location code zero "
else:
messageOut = "Unknown message type %s " % messageProtocolEntity.getType()
print(messageOut.toProtocolTreeNode())
messageOut=formstring(messageOut)
print(messageOut)
reply=rs.reply("localuser",messageOut)
receipt = OutgoingReceiptProtocolEntity(messageProtocolEntity.getId(), messageProtocolEntity.getFrom(), 'read', messageProtocolEntity.getParticipant())
result = db.session.find({"from":messageProtocolEntity.getFrom()})
if result.count() == 1:
stime= datetime.datetime.now().hour*60+datetime.datetime.now().minute
print(stime)
if stime<=result[0]['expiry']:
#Customer in citizen
r = db.session.find({"from":messageProtocolEntity.getFrom()})
qid = r[0]['qid']
if messageProtocolEntity.getType() == "text":
db.query.update({"_id":qid},{"$set":{"text":db.query.find({"_id":qid})[0]['text']+[messageProtocolEntity.getBody()]}})
elif messageProtocolEntity.getMediaType() == "image":
db.query.update({"_id":qid},{"$set":{"image":db.query.find({"_id":qid})[0]['image']+[messageProtocolEntity.url]}})
elif messageProtocolEntity.getMediaType() == "location":
db.query.update({"_id":qid},{"$set":{"location":db.query.find({"_id":qid})[0]['location']+[[messageProtocolEntity.getLatitude(), messageProtocolEntity.getLongitude()]]}})
elif messageProtocolEntity.getMediaType() == "vcard":
db.query.update({"_id":qid},{"$set":{"vcard":db.query.find({"_id":qid})[0]['vcard']+[messageProtocolEntity.getCardData()]}})
else:
db.query.update({"_id":qid},{"$set":{"text":db.query.find({"_id":qid})[0]['text']+[messageProtocolEntity.getBody()]}})
outgoingMessageProtocolEntity = TextMessageProtocolEntity(reply,
to = messageProtocolEntity.getFrom())
self.toLower(receipt)
self.toLower(outgoingMessageProtocolEntity)
else:
r = db.session.find({"from":messageProtocolEntity.getFrom()})
qid = r[0]['qid']
db.session.remove({"from":messageProtocolEntity.getFrom()})
outgoingMessageProtocolEntity = TextMessageProtocolEntity("Your complaint id:"+str(qid)+"\n\nYour session has been expired!!\nYou need to register again.",to = messageProtocolEntity.getFrom())
self.toLower(receipt)
self.toLower(outgoingMessageProtocolEntity)
else:
outgoingMessageProtocolEntity = TextMessageProtocolEntity("I need your location to register you",
to = messageProtocolEntity.getFrom())
self.toLower(receipt)
self.toLower(outgoingMessageProtocolEntity)
示例13: BotInterface
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import load_directory [as 别名]
from rivescript import RiveScript
from bot_interface.bot_interface import BotInterface
from message_processor.message_processor import ExternalApiParser, MessageProcessor
from nyt_interface.nyt_interface import NytimesApi
from pymongo import MongoClient
config = ConfigParser.ConfigParser()
config.read("local_test_config.cfg")
bot = BotInterface(Config.FB_API_VERSION, config.get('SECRET', 'fb_access_token'))
nyt_api = NytimesApi(config.get('NYTIMES', 'nyt_key'))
rive = RiveScript()
rive.load_directory(
os.path.join(os.path.dirname(__file__), "..", "rivescripts")
)
rive.sort_replies()
mongo = MongoClient()
mongo = mongo.app
external_api_parser = ExternalApiParser(config.get('WITAI', 'wit_key'),
rive, bot, nyt_api, mongo)
Config = {'DEBUG': True, 'NYT_NUM_ARTICLES_RETURNED': 3}
msgproc = MessageProcessor(bot, external_api_parser, Config)
recipient_id = config.get('SECRET', 'fb_test_recipient_id')
class TestMessageProcessor(unittest.TestCase):
示例14: RiveBot
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import load_directory [as 别名]
class RiveBot(object):
"""An example RiveScript bot using callbacks to manage user session data.
This example assumes single user per RiveScript instance and as
such it's suitable for use in stateless services (e.g. in web apps
receiving webhooks). Just init, get reply and teardown. Of course,
it will also work in RTM implementations with custom longer-lived
bot threads.
Session state is persisted to a single JSON file. This wouldn't be
thread-safe in a concurrent environment (e.g. web server). In such
case it would be recommended to subclass SessionStore and implement
database persistence (preferably via one of great Python ORMs such
as SQLAlchemy or peewee).
"""
def __init__(self, script_dir, user, ss, debug=False):
self._user = user
self._redirect = None
# init RiveScript
self._rs = RiveScript(debug=debug)
self._rs.load_directory(script_dir)
self._rs.sort_replies()
# restore session
if isinstance(ss, SessionStore):
self._ss = ss
else:
raise RuntimeError("RiveBot init error: provided session store object is not a SessionStore instance.")
self._restore_session()
# register event callbacks
self._rs.on('topic', self._topic_cb)
self._rs.on('uservar', self._uservar_cb)
def _topic_cb(self, user, topic, redirect=None):
"""Topic callback.
This is a single-user-per-rive (stateless instance) scenario; in a multi-user
scenario within a single thread, callback functions should delegate the
execution to proper user session objects.
"""
log.debug("Topic callback: user={}, topic={}, redirect={}".format(user, topic, redirect))
self._session.set_topic(topic, redirect)
def _uservar_cb(self, user, name, value):
"""Topic callback. See comment for `_topic_cb()`"""
log.debug("User variable callback: user={}, name={}, value={}".format(user, name, value))
self._session.set_variable(name, value)
def _restore_session(self):
self._session = self._ss.load(self._user)
# set saved user variables
for name, value in self._session.variables():
self._rs.set_uservar(self._user, name, value)
# set saved topic
topic = self._session.get_topic()
if topic:
if '/' in topic:
topic, self._redirect = topic.split('/')
self._rs.set_topic(self._user, topic)
def _save_session(self):
self._ss.save(self._session)
def run(self):
log.info("RiveBot starting...")
if self._redirect:
# Repeat saved redirect so that the user gets the context
# after session restart.
redir_reply = self._rs.redirect(self._user, self._redirect)
print("bot> Welcome back!")
print("bot>", redir_reply)
while True:
msg = raw_input("{}> ".format(self._user))
if msg == '/quit':
self.stop()
break
reply = self._rs.reply(self._user, msg)
print("bot>", reply)
def stop(self):
log.info("RiveBot shutting down...")
print("\nbot> Bye.")
self._save_session()
示例15: RiveScript
# 需要导入模块: from rivescript import RiveScript [as 别名]
# 或者: from rivescript.RiveScript import load_directory [as 别名]
#!/usr/bin/python
from rivescript import RiveScript
rs = RiveScript()
rs.load_directory(".")
rs.sort_replies()
print """This is a bare minimal example for how to write your own RiveScript bot!
For a more full-fledged example, try running: `l`
This will run the built-in Interactive Mode of the RiveScript library. It has
some more advanced features like supporting JSON for communication with the
bot. See `python rivescript --help` for more info.
Type /quit when you're done to exit this example.
"""
while True:
msg = raw_input("You> ")
if msg == '/quit':
quit()
reply = rs.reply("localuser", msg)
print "Bot>", reply