forked from aichaos/rivescript-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrivescript.py
More file actions
2155 lines (1835 loc) · 83.4 KB
/
Copy pathrivescript.py
File metadata and controls
2155 lines (1835 loc) · 83.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pyRiveScript - A RiveScript interpreter written in Python.
VERSION = '1.01'
import os
import glob
import re
import string
import random
import pprint
import copy
import sys
import getopt
import json
# Common regular expressions.
re_equals = re.compile('\s*=\s*')
re_ws = re.compile('\s+')
re_objend = re.compile('<\s*object')
re_weight = re.compile('\{weight=(\d+)\}')
re_inherit = re.compile('\{inherits=(\d+)\}')
re_wilds = re.compile('[\s\*\#\_]+')
re_rot13 = re.compile('<rot13sub>(.+?)<bus31tor>')
re_nasties = re.compile('[^A-Za-z0-9 ]')
# Version of RiveScript we support.
rs_version = 2.0
class PyRiveObjects:
"""A RiveScript object handler for Python code."""
_objects = {} # The cache of objects loaded
def __init__(self):
pass
def load(self, name, code):
"""Prepare a Python code object given by the RiveScript interpreter."""
# We need to make a dynamic Python method.
source = "def RSOBJ(rs, args):\n"
for line in code:
source = source + "\t" + line + "\n"
try:
exec source
self._objects[name] = RSOBJ
except:
print "Failed to load code from object " + name
def call(self, rs, name, fields):
"""Invoke a previously loaded object."""
# Call the dynamic method.
func = self._objects[name]
reply = ''
try:
reply = func(rs, fields)
except:
reply = '[ERR: Error when executing Python object]'
return reply
class RiveScript:
"""A RiveScript interpreter for Python 2."""
_debug = False # Debug mode
_strict = True # Strict mode
_logf = '' # Log file for debugging
_depth = 50 # Recursion depth limit
_gvars = {} # 'global' variables
_bvars = {} # 'bot' variables
_subs = {} # 'sub' variables
_person = {} # 'person' variables
_arrays = {} # 'array' variables
_users = {} # 'user' variables
_freeze = {} # frozen 'user' variables
_includes = {} # included topics
_lineage = {} # inherited topics
_handlers = {} # Object handlers
_objlangs = {} # Languages of objects used
_topics = {} # Main reply structure
_thats = {} # %Previous reply structure
_sorted = {} # Sorted buffers
############################################################################
# Initialization and Utility Methods #
############################################################################
def __init__(self, debug=False, strict=True, depth=50, log=""):
"""Initialize a new RiveScript interpreter.
bool debug: Specify a debug mode.
bool strict: Strict mode (RS syntax errors are fatal)
str log: Specify a log file for debug output to go to (instead of STDOUT).
int depth: Specify the recursion depth limit."""
self._debug = debug
self._strict = strict
self._depth = depth
self._log = log
# Define the default Python language handler.
self._handlers["python"] = PyRiveObjects()
self._say("Interpreter initialized.")
def _say(self, message):
if self._debug:
print "[RS]", message
if self._log:
# Log it to the file.
fh = open(self._log, 'a')
fh.write("[RS] " + message + "\n")
fh.close()
def _warn(self, message, fname='', lineno=0):
if self._debug:
print "[RS::Warning]",
else:
print "[RS]",
if len(fname) and lineno > 0:
print message, "at", fname, "line", lineno
else:
print message
############################################################################
# Loading and Parsing Methods #
############################################################################
def load_directory(self, directory, ext='.rs'):
"""Load RiveScript documents from a directory."""
self._say("Loading from directory: " + directory + "/*" + ext)
if not os.path.isdir(directory):
self._warn("Error: " + directory + " is not a directory.")
return
for item in glob.glob( os.path.join(directory, '*'+ext) ):
self.load_file( item )
def load_file(self, filename):
"""Load and parse a RiveScript document."""
self._say("Loading file: " + filename)
fh = open(filename, 'r')
lines = fh.readlines()
fh.close()
self._say("Parsing " + str(len(lines)) + " lines of code from " + filename)
self._parse(filename, lines)
def stream(self, code):
"""Stream in RiveScript source code dynamically.
`code` should be an array of lines of RiveScript code."""
self._say("Streaming code.")
self._parse("stream()", code)
def _parse(self, fname, code):
"""Parse RiveScript code into memory."""
self._say("Parsing code")
# Track temporary variables.
topic = 'random' # Default topic=random
lineno = 0 # Line numbers for syntax tracking
comment = False # In a multi-line comment
inobj = False # In an object
objname = '' # The name of the object we're in
objlang = '' # The programming language of the object
objbuf = [] # Object contents buffer
ontrig = '' # The current trigger
repcnt = 0 # Reply counter
concnt = 0 # Condition counter
lastcmd = '' # Last command code
isThat = '' # Is a %Previous trigger
# Read each line.
for lp, line in enumerate(code):
lineno = lineno + 1
self._say("Line: " + line + " (topic: " + topic + ") incomment: " + str(inobj))
if len(line.strip()) == 0: # Skip blank lines
continue
# In an object?
if inobj:
if re.match(re_objend, line):
# End the object.
if len(objname):
# Call the object's handler.
if objlang in self._handlers:
self._objlangs[objname] = objlang;
self._handlers[objlang].load(objname, objbuf)
else:
self._warn("Object creation failed: no handler for " + objlang, fname, lineno)
objname = ''
objlang = ''
objbuf = []
inobj = False
else:
objbuf.append(line)
continue
line = line.strip() # Trim excess space. We do it down here so we
# don't mess up python objects!
# Look for comments.
if line[:2] == '//': # A single-line comment.
continue
elif line[0] == '#':
self._warn("Using the # symbol for comments is deprecated", fname, lineno)
elif line[:2] == '/*': # Start of a multi-line comment.
if not '*/' in line: # Cancel if the end is here too.
comment = True
continue
elif '*/' in line:
comment = False
continue
if comment:
continue
# Separate the command from the data.
if len(line) < 2:
self._warn("Weird single-character line '" + line + "' found.", fname, lineno)
continue
cmd = line[0]
line = line[1:].strip()
# Ignore inline comments if there's a space before and after
# the // symbols.
if " // " in line:
line = line.split(" // ")[0].strip()
# Run a syntax check on this line.
syntax_error = self.check_syntax(cmd, line)
if syntax_error:
# There was a syntax error! Are we enforcing strict mode?
syntax_error = "Syntax error in " + fname + " line " + str(lineno) + ": " \
+ syntax_error + " (near: " + cmd + " " + line + ")"
if self._strict:
raise Exception(syntax_error)
else:
self._warn(syntax_error)
return # Don't try to continue
# Reset the %Previous state if this is a new +Trigger.
if cmd == '+':
isThat = ''
# Do a lookahead for ^Continue and %Previous commands.
for i in range(lp + 1, len(code)):
lookahead = code[i].strip()
if len(lookahead) < 2:
continue
lookCmd = lookahead[0]
lookahead = lookahead[1:].strip()
# Only continue if the lookahead line has any data.
if len(lookahead) != 0:
# The lookahead command has to be either a % or a ^.
if lookCmd != '^' and lookCmd != '%':
break
# If the current command is a +, see if the following is
# a %.
if cmd == '+':
if lookCmd == '%':
isThat = lookahead
break
else:
isThat = ''
# If the current command is a ! and the next command(s) are
# ^, we'll tack each extension on as a line break (which is
# useful information for arrays).
if cmd == '!':
if lookCmd == '^':
line += "<crlf>" + lookahead
continue
# If the current command is not a ^ and the line after is
# not a %, but the line after IS a ^, then tack it on to the
# end of the current line.
if cmd != '^' and lookCmd != '%':
if lookCmd == '^':
line += lookahead
else:
break
self._say("Command: " + cmd + "; line: " + line)
# Handle the types of RiveScript commands.
if cmd == '!':
# ! DEFINE
halves = re.split(re_equals, line, 2)
left = re.split(re_ws, halves[0].strip(), 2)
value, type, var = '', '', ''
if len(halves) == 2:
value = halves[1].strip()
if len(left) >= 1:
type = left[0].strip()
if len(left) >= 2:
var = ' '.join(left[1:]).strip()
# Remove 'fake' line breaks unless this is an array.
if type != 'array':
value = re.sub(r'<crlf>', '', value)
# Handle version numbers.
if type == 'version':
# Verify we support it.
try:
if float(value) > rs_version:
self._warn("Unsupported RiveScript version. We only support " + rs_version, fname, lineno)
return
except:
self._warn("Error parsing RiveScript version number: not a number", fname, lineno)
continue
# All other types of defines require a variable and value name.
if len(var) == 0:
self._warn("Undefined variable name", fname, lineno)
continue
elif len(value) == 0:
self._warn("Undefined variable value", fname, lineno)
continue
# Handle the rest of the types.
if type == 'global':
# 'Global' variables
self._say("\tSet global " + var + " = " + value)
if value == '<undef>':
try:
del(self._gvars[var])
except:
self._warn("Failed to delete missing global variable", fname, lineno)
else:
self._gvars[var] = value
# Handle flipping debug and depth vars.
if var == 'debug':
if value.lower() == 'true':
value = True
else:
value = False
self._debug = value
elif var == 'depth':
try:
self._depth = int(value)
except:
self._warn("Failed to set 'depth' because the value isn't a number!", fname, lineno)
elif var == 'strict':
if value.lower() == 'true':
self._strict = True
else:
self._strict = False
elif type == 'var':
# Bot variables
self._say("\tSet bot variable " + var + " = " + value)
if value == '<undef>':
try:
del(self._bvars[var])
except:
self._warn("Failed to delete missing bot variable", fname, lineno)
else:
self._bvars[var] = value
elif type == 'array':
# Arrays
self._say("\tArray " + var + " = " + value)
if value == '<undef>':
try:
del(self._arrays[var])
except:
self._warn("Failed to delete missing array", fname, lineno)
continue
# Did this have multiple parts?
parts = value.split("<crlf>")
# Process each line of array data.
fields = []
for val in parts:
if '|' in val:
fields.extend( val.split('|') )
else:
fields.extend( re.split(re_ws, val) )
# Convert any remaining '\s' escape codes into spaces.
for f in fields:
f = f.replace(r'\s', ' ')
self._arrays[var] = fields
elif type == 'sub':
# Substitutions
self._say("\tSubstitution " + var + " => " + value)
if value == '<undef>':
try:
del(self._subs[var])
except:
self._warn("Failed to delete missing substitution", fname, lineno)
else:
self._subs[var] = value
elif type == 'person':
# Person Substitutions
self._say("\tPerson Substitution " + var + " => " + value)
if value == '<undef>':
try:
del(self._person[var])
except:
self._warn("Failed to delete missing person substitution", fname, lineno)
else:
self._person[var] = value
else:
self._warn("Unknown definition type '" + type + "'", fname, lineno)
elif cmd == '>':
# > LABEL
temp = re.split(re_ws, line)
type = temp[0]
name = ''
fields = []
if len(temp) >= 2:
name = temp[1]
if len(temp) >= 3:
fields = temp[2:]
# Handle the label types.
if type == 'begin':
# The BEGIN block.
self._say("\tFound the BEGIN block.")
type = 'topic'
name = '__begin__'
if type == 'topic':
# Starting a new topic.
self._say("\tSet topic to " + name)
ontrig = ''
topic = name
# Does this topic include or inherit another one?
mode = '' # or 'inherits' or 'includes'
if len(fields) >= 2:
for field in fields:
if field == 'includes':
mode = 'includes'
elif field == 'inherits':
mode = 'inherits'
elif mode != '':
# This topic is either inherited or included.
if mode == 'includes':
if not name in self._includes:
self._includes[name] = {}
self._includes[name][field] = 1
else:
if not name in self._lineage:
self._lineage[name] = {}
self._lineage[name][field] = 1
elif type == 'object':
# If a field was provided, it should be the programming
# language.
lang = None
if len(fields) > 0:
lang = fields[0].lower()
# Only try to parse a language we support.
ontrig = ''
if lang == None:
self._warn("Trying to parse unknown programming language", fname, fileno)
lang = 'python' # Assume it's Python.
# See if we have a defined handler for this language.
if lang in self._handlers:
# We have a handler, so start loading the code.
objname = name
objlang = lang
objbuf = []
inobj = True
else:
# We don't have a handler, just ignore it.
objname = ''
objlang = ''
objbuf = []
inobj = True
else:
self._warn("Unknown label type '" + type + "'", fname, lineno)
elif cmd == '<':
# < LABEL
type = line
if type == 'begin' or type == 'topic':
self._say("\tEnd topic label.")
topic = 'random'
elif type == 'object':
self._say("\tEnd object label.")
inobj = False
elif cmd == '+':
# + TRIGGER
self._say("\tTrigger pattern: " + line)
if len(isThat):
self._initTT('thats', topic, isThat, line)
else:
self._initTT('topics', topic, line)
ontrig = line
repcnt = 0
concnt = 0
elif cmd == '-':
# - REPLY
if ontrig == '':
self._warn("Response found before trigger", fname, lineno)
continue
self._say("\tResponse: " + line)
if len(isThat):
self._thats[topic][isThat][ontrig]['reply'][repcnt] = line
else:
self._topics[topic][ontrig]['reply'][repcnt] = line
repcnt = repcnt + 1
elif cmd == '%':
# % PREVIOUS
pass # This was handled above.
elif cmd == '^':
# ^ CONTINUE
pass # This was handled above.
elif cmd == '@':
# @ REDIRECT
self._say("\tRedirect response to " + line)
if len(isThat):
self._thats[topic][isThat][ontrig]['redirect'] = line
else:
self._topics[topic][ontrig]['redirect'] = line
elif cmd == '*':
# * CONDITION
self._say("\tAdding condition: " + line)
if len(isThat):
self._thats[topic][isThat][ontrig]['condition'][concnt] = line
else:
self._topics[topic][ontrig]['condition'][concnt] = line
concnt = concnt + 1
else:
self._warn("Unrecognized command \"" + cmd + "\"", fname, lineno)
continue
def check_syntax(self, cmd, line):
"""Syntax check a RiveScript command and line.
Returns a syntax error string on error; None otherwise."""
# Run syntax checks based on the type of command.
if cmd == '!':
# ! Definition
# - Must be formatted like this:
# ! type name = value
# OR
# ! type = value
match = re.match(r'^.+(?:\s+.+|)\s*=\s*.+?$', line)
if not match:
return "Invalid format for !Definition line: must be '! type name = value' OR '! type = value'"
elif cmd == '>':
# > Label
# - The "begin" label must have only one argument ("begin")
# - "topic" labels must be lowercased but can inherit other topics (a-z0-9_\s)
# - "object" labels must follow the same rules as "topic", but don't need to be lowercase
parts = re.split(" ", line, 2)
if parts[0] == "begin" and len(parts) > 1:
return "The 'begin' label takes no additional arguments, should be verbatim '> begin'"
elif parts[0] == "topic":
rest = ' '.join(parts)
match = re.match(r'[^a-z0-9_\-\s]', line)
if match:
return "Topics should be lowercased and contain only numbers and letters"
elif parts[0] == "object":
rest = ' '.join(parts)
match = re.match(r'[^A-Za-z0-9_\-\s]', line)
if match:
return "Objects can only contain numbers and letters"
elif cmd == '+' or cmd == '%' or cmd == '@':
# + Trigger, % Previous, @ Redirect
# This one is strict. The triggers are to be run through the regexp engine,
# therefore it should be acceptable for the regexp engine.
# - Entirely lowercase
# - No symbols except: ( | ) [ ] * _ # @ { } < > =
# - All brackets should be matched
parens = 0 # Open parenthesis
square = 0 # Open square brackets
curly = 0 # Open curly brackets
angle = 0 # Open angled brackets
# Look for obvious errors.
match = re.match(r'[^a-z0-9(|)\[\]*_#@{}<>=\s]', line)
if match:
return "Triggers may only contain lowercase letters, numbers, and these symbols: ( | ) [ ] * _ # @ { } < > ="
# Count brackets.
for char in line:
if char == '(':
parens = parens + 1
elif char == ')':
parens = parens - 1
elif char == '[':
square = square + 1
elif char == ']':
square = square - 1
elif char == '{':
curly = curly + 1
elif char == '}':
curly = curly - 1
elif char == '<':
angle = angle + 1
elif char == '>':
angle = angle - 1
# Any mismatches?
if parens != 0:
return "Unmatched parenthesis brackets"
elif square != 0:
return "Unmatched square brackets"
elif curly != 0:
return "Unmatched curly brackets"
elif angle != 0:
return "Unmatched angle brackets"
elif cmd == '-' or cmd == '^' or cmd == '/':
# - Trigger, ^ Continue, / Comment
# These commands take verbatim arguments, so their syntax is loose.
pass
elif cmd == '*':
# * Condition
# Syntax for a conditional is as follows:
# * value symbol value => response
match = re.match(r'^.+?\s*(?:==|eq|!=|ne|<>|<|<=|>|>=)\s*.+?=>.+?$', line)
if not match:
return "Invalid format for !Condition: should be like '* value symbol value => response'"
return None
def _initTT(self, toplevel, topic, trigger, what=''):
"""Initialize a Topic Tree data structure."""
if toplevel == 'topics':
if not topic in self._topics:
self._topics[topic] = {}
if not trigger in self._topics[topic]:
self._topics[topic][trigger] = {}
self._topics[topic][trigger]['reply'] = {}
self._topics[topic][trigger]['condition'] = {}
self._topics[topic][trigger]['redirect'] = None
elif toplevel == 'thats':
if not topic in self._thats:
self._thats[topic] = {}
if not trigger in self._thats[topic]:
self._thats[topic][trigger] = {}
if not what in self._thats[topic][trigger]:
self._thats[topic][trigger][what] = {}
self._thats[topic][trigger][what]['reply'] = {}
self._thats[topic][trigger][what]['condition'] = {}
self._thats[topic][trigger][what]['redirect'] = {}
############################################################################
# Sorting Methods #
############################################################################
def sort_replies(self, thats=False):
"""Sort the loaded triggers."""
# This method can sort both triggers and that's.
triglvl = None
sortlvl = None
if thats:
triglvl = self._thats
sortlvl = 'thats'
else:
triglvl = self._topics
sortlvl = 'topics'
# (Re)Initialize the sort cache.
self._sorted[sortlvl] = {}
self._say("Sorting triggers...")
# Loop through all the topics.
for topic in triglvl:
self._say("Analyzing topic " + topic)
# Collect a list of all the triggers we're going to need to worry
# about. If this topic inherits another topic, we need to
# recursively add those to the list.
alltrig = self._topic_triggers(topic, triglvl)
# Keep in mind here that there is a difference between 'includes'
# and 'inherits' -- topics that inherit other topics are able to
# OVERRIDE triggers that appear in the inherited topic. This means
# that if the top topic has a trigger of simply '*', then *NO*
# triggers are capable of matching in ANY inherited topic, because
# even though * has the lowest sorting priority, it has an automatic
# priority over all inherited topics.
#
# The _topic_triggers method takes this into account. All topics
# that inherit other topics will have their triggers prefixed with
# a fictional {inherits} tag, which would start at {inherits=0} and
# increment if the topic tree has other inheriting topics. So we can
# use this tag to make sure topics that inherit things will have
# their triggers always be on top of the stack, from inherits=0 to
# inherits=n.
# Sort these triggers.
running = self._sort_trigger_set(alltrig)
# Save this topic's sorted list.
if not sortlvl in self._sorted:
self._sorted[sortlvl] = {}
self._sorted[sortlvl][topic] = running
# And do it all again for %Previous!
if thats != True:
# This will sort the %Previous lines to best match the bot's last reply.
self.sort_replies(True)
# If any of those %Previous's had more than one +trigger for them,
# this will sort all those +triggers to pair back the best human
# interaction.
self._sort_that_triggers()
# Also sort both kinds of substitutions.
self._sort_list('subs', self._subs)
self._sort_list('person', self._person)
def _sort_that_triggers(self):
"""Make a sorted list of triggers that correspond to %Previous groups."""
self._say("Sorting reverse triggers for %Previous groups...")
if not "that_trig" in self._sorted:
self._sorted["that_trig"] = {}
for topic in self._thats:
if not topic in self._sorted["that_trig"]:
self._sorted["that_trig"][topic] = {}
for bottrig in self._thats[topic]:
if not bottrig in self._sorted["that_trig"][topic]:
self._sorted["that_trig"][topic][bottrig] = []
triggers = self._sort_trigger_set(self._thats[topic][bottrig].keys())
self._sorted["that_trig"][topic][bottrig] = triggers
def _sort_trigger_set(self, triggers):
"""Sort a group of triggers in optimal sorting order."""
# Create a priority map.
prior = {
0: [] # Default priority=0
}
for trig in triggers:
match, weight = re.search(re_weight, trig), 0
if match:
weight = int(match.group(1))
if not weight in prior:
prior[weight] = []
prior[weight].append(trig)
# Keep a running list of sorted triggers for this topic.
running = []
# Sort them by priority.
for p in sorted(prior.keys(), reverse=True):
self._say("\tSorting triggers with priority " + str(p))
# So, some of these triggers may include {inherits} tags, if they
# came form a topic which inherits another topic. Lower inherits
# values mean higher priority on the stack.
inherits = -1 # -1 means no {inherits} tag
highest_inherits = -1 # highest inheritence number seen
# Loop through and categorize these triggers.
track = {
inherits: self._init_sort_track()
}
for trig in prior[p]:
self._say("\t\tLooking at trigger: " + trig)
# See if it has an inherits tag.
match = re.search(re_inherit, trig)
if match:
inherits = int(match.group(1))
if inherits > highest_inherits:
highest_inherits = inherits
self._say("\t\t\tTrigger belongs to a topic which inherits other topics: level=" + str(inherits))
trig = re.sub(re_inherit, "", trig)
else:
inherits = -1
# If this is the first time we've seen this inheritence level,
# initialize its track structure.
if not inherits in track:
track[inherits] = self._init_sort_track()
# Start inspecting the trigger's contents.
if '_' in trig:
# Alphabetic wildcard included.
cnt = self._word_count(trig)
self._say("\t\t\tHas a _ wildcard with " + str(cnt) + " words.")
if cnt > 1:
if not cnt in track[inherits]['alpha']:
track[inherits]['alpha'][cnt] = []
track[inherits]['alpha'][cnt].append(trig)
else:
track[inherits]['under'].append(trig)
elif '#' in trig:
# Numeric wildcard included.
cnt = self._word_count(trig)
self._say("\t\t\tHas a # wildcard with " + str(cnt) + " words.")
if cnt > 1:
if not cnt in track[inherits]['number']:
track[inherits]['number'][cnt] = []
track[inherits]['number'][cnt].append(trig)
else:
track[inherits]['pound'].append(trig)
elif '*' in trig:
# Wildcard included.
cnt = self._word_count(trig)
self._say("\t\t\tHas a * wildcard with " + str(cnt) + " words.")
if cnt > 1:
if not cnt in track[inherits]['wild']:
track[inherits]['wild'][cnt] = []
track[inherits]['wild'][cnt].append(trig)
else:
track[inherits]['star'].append(trig)
elif '[' in trig:
# Optionals included.
cnt = self._word_count(trig)
self._say("\t\t\tHas optionals and " + str(cnt) + " words.")
if not cnt in track[inherits]['option']:
track[inherits]['option'][cnt] = []
track[inherits]['option'][cnt].append(trig)
else:
# Totally atomic.
cnt = self._word_count(trig)
self._say("\t\t\tTotally atomic and " + str(cnt) + " words.")
if not cnt in track[inherits]['atomic']:
track[inherits]['atomic'][cnt] = []
track[inherits]['atomic'][cnt].append(trig)
# Move the no-{inherits} triggers to the bottom of the stack.
track[ (highest_inherits + 1) ] = track[-1]
del(track[-1])
# Add this group to the sort list.
for ip in sorted(track.keys()):
self._say("ip=" + str(ip))
for kind in [ 'atomic', 'option', 'alpha', 'number', 'wild' ]:
for i in sorted(track[ip][kind], reverse=True):
running.extend( track[ip][kind][i] )
running.extend( sorted(track[ip]['under'], key=len, reverse=True) )
running.extend( sorted(track[ip]['pound'], key=len, reverse=True) )
running.extend( sorted(track[ip]['star'], key=len, reverse=True) )
return running
def _sort_list(self, name, items):
"""Sort a simple list by number of words and length."""
def by_length(word1, word2):
return len(word2)-len(word1)
# Initialize the list sort buffer.
if not "lists" in self._sorted:
self._sorted["lists"] = {}
self._sorted["lists"][name] = []
# Track by number of words.
track = {}
# Loop through each item.
for item in items:
# Count the words.
cword = self._word_count(item, all=True)
if not cword in track:
track[cword] = []
track[cword].append(item)
# Sort them.
output = []
for count in sorted(track.keys(), reverse=True):
sort = sorted(track[count], cmp=by_length)
output.extend(sort)
self._sorted["lists"][name] = output
def _init_sort_track(self):
"""Returns a new dict for keeping track of triggers for sorting."""
return {
'atomic': {}, # Sort by number of whole words
'option': {}, # Sort optionals by number of words
'alpha': {}, # Sort alpha wildcards by no. of words
'number': {}, # Sort number wildcards by no. of words
'wild': {}, # Sort wildcards by no. of words
'pound': [], # Triggers of just #
'under': [], # Triggers of just _
'star': [] # Triggers of just *
}
############################################################################
# Public Configuration Methods #
############################################################################
def set_handler(self, language, obj):
"""Define a custom language handler for RiveScript objects.
language: The lowercased name of the programming language,
e.g. python, javascript, perl
obj: An instance of a class object that provides the following interface:
class MyObjectHandler:
def __init__(self):
pass
def load(self, name, code):
# name = the name of the object from the RiveScript code
# code = the source code of the object
def call(self, rs, name, fields):
# rs = the current RiveScript interpreter object
# name = the name of the object being called
# fields = array of arguments passed to the object
return reply
Pass in a None value for the object to delete an existing handler (for example,
to prevent Python code from being able to be run by default).
Look in the `eg` folder of the rivescript-python distribution for an example
script that sets up a JavaScript language handler."""
# Allow them to delete a handler too.
if obj == None:
if language in self._handlers:
del self._handlers[language]
else:
self._handlers[language] = obj
def set_subroutine(self, name, code):
"""Define a Python object from your program.
This is equivalent to having an object defined in the RiveScript code, except
your Python code is defining it instead. `name` is the name of the object, and
`code` is a Python function (a `def`) that accepts rs,args as its parameters.
This method is only available if there is a Python handler set up (which there
is by default, unless you've called set_handler("python", None))."""
# Do we have a Python handler?
if 'python' in self._handlers:
self._handlers['python']._objects[name] = code
else:
self._warn("Can't set_subroutine: no Python object handler!")
def set_global(self, name, value):
"""Set a global variable.
Equivalent to `! global` in RiveScript code. Set to None to delete."""
if value == None:
# Unset the variable.
if name in self._gvars:
del self._gvars[name]
self._gvars[name] = value
def set_variable(self, name, value):
"""Set a bot variable.
Equivalent to `! var` in RiveScript code. Set to None to delete."""
if value == None:
# Unset the variable.
if name in self._bvars:
del self._bvars[name]
self._bvars[name] = value
def set_substitution(self, what, rep):
"""Set a substitution.
Equivalent to `! sub` in RiveScript code. Set to None to delete."""
if rep == None:
# Unset the variable.
if what in self._subs:
del self._subs[what]
self._subs[what] = rep
def set_person(self, what, rep):
"""Set a person substitution.
Equivalent to `! person` in RiveScript code. Set to None to delete."""
if rep == None:
# Unset the variable.
if what in self._person:
del self._person[what]
self._person[what] = rep
def set_uservar(self, user, name, value):
"""Set a variable for a user."""
if not user in self._users:
self._users[user] = {"topic": "random"}
self._users[user][name] = value
def get_uservar(self, user, name):
"""Get a variable about a user.