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
2365 lines (1989 loc) · 92.9 KB
/
Copy pathrivescript.py
File metadata and controls
2365 lines (1989 loc) · 92.9 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
#!/usr/bin/env python
import sys
import os
import re
import string
import random
import pprint
import copy
import codecs
from . import __version__
from . import python
import rivescript_pb2 as proto
# Common regular expressions.
re_equals = re.compile('\s*=\s*')
re_ws = re.compile('\s+')
re_objend = re.compile('^\s*<\s*object')
re_weight = re.compile('\{weight=(\d+)\}')
re_inherit = re.compile('\{inherits=(\d+)\}')
re_wilds = re.compile('[\s\*\#\_]+')
re_nasties = re.compile('[^A-Za-z0-9 ]')
# Version of RiveScript we support.
rs_version = 2.0
# Exportable constants.
RS_ERR_MATCH = "ERR: No Reply Matched"
RS_ERR_REPLY = "ERR: No Reply Found"
class RiveScript:
"""A RiveScript interpreter for Python 2 and 3."""
############################################################################
# Initialization and Utility Methods #
############################################################################
def __init__(self, debug=False, strict=True, depth=50, log="", utf8=False,
build=True):
"""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.
bool utf8: Enable UTF-8 support.
bool build: Compile RiveScript sources to binary (default True)"""
# Instance variables.
self._debug = debug # Debug mode
self._log = log # Debug log file
self._utf8 = utf8 # UTF-8 mode
self._protobuf = build # Use protocol buffers to encode rivec files
self._strict = strict # Strict mode
self._depth = depth # Recursion depth limit
self._gvars = {} # 'global' variables
self._bvars = {} # 'bot' variables
self._subs = {} # 'sub' variables
self._person = {} # 'person' variables
self._arrays = {} # 'array' variables
self._users = {} # 'user' variables
self._freeze = {} # frozen 'user' variables
self._includes = {} # included topics
self._lineage = {} # inherited topics
self._handlers = {} # Object handlers
self._objlangs = {} # Languages of objects used
self._topics = {} # Main reply structure
self._thats = {} # %Previous reply structure
self._sorted = {} # Sorted buffers
self._syntax = {} # Syntax tracking (filenames & line no.'s)
# "Current request" variables.
self._current_user = None # The current user ID.
# Define the default Python language handler.
self._handlers["python"] = python.PyRiveObjects()
self._say("Interpreter initialized.")
@classmethod
def VERSION(self=None):
"""Return the version number of the RiveScript library.
This may be called as either a class method of a method of a RiveScript object."""
return __version__
def _say(self, message):
if self._debug:
print("[RS] {}".format(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):
header = "[RS]"
if self._debug:
header = "[RS::Warning]"
if len(fname) and lineno > 0:
print(header, message, "at", fname, "line", lineno)
else:
print(header, message)
############################################################################
# Loading and Parsing Methods #
############################################################################
def load_directory(self, directory, ext=None):
"""Load RiveScript documents from a directory.
Provide `ext` as a list of extensions to search for. The default list
is `.rive`, `.rs`"""
self._say("Loading from directory: " + directory)
if ext is None:
# Use the default extensions - .rive is preferable.
ext = ['.rive', '.rs', '.rivec']
elif type(ext) == str:
# Backwards compatibility for ext being a string value.
ext = [ext]
if not os.path.isdir(directory):
self._warn("Error: " + directory + " is not a directory.")
return
# Only load one base-name of each file (i.e. the name without the
# extension), this way we can prefer to load .rive files with priority
# over the compiled .rivec ones.
load_map = set()
file_list = sorted(os.listdir(directory))
for extension in ext:
for item in file_list:
if item.lower().endswith(extension):
# Store that we've loaded a file with a name like this.
fname = item.lower().replace(extension, "")
if fname in load_map:
continue
load_map.add(fname)
# Load this file.
self.load_file(os.path.join(directory, item))
def load_file(self, filename, force_compile=False):
"""Load and parse a RiveScript document.
Provide force_compile=True to force compiling the RiveScript document to
binary, even if the source file hasn't been updated."""
self._say("Loading file: " + filename)
# Do we have a compiled file?
binary = False
rivec = filename + ".rivec"
parts = filename.split(".")
if len(parts) > 1:
if parts[-1].lower() == "rivec":
# The file they requested was ALREADY the compiled one!
binary = True
else:
# Make the binary version of the file name and check if it exists.
parts[-1] = "rivec"
rivec = ".".join(parts)
if os.path.isfile(rivec):
# Do we need to recompile? If the compiled file is newer, we
# do not recompile.
if os.path.getmtime(rivec) > os.path.getmtime(filename) and not force_compile:
self._say("Using compiled version {}".format(rivec))
binary = True
filename = rivec
# Are we parsing text, or binary?
if binary:
document = proto.Document()
fh = codecs.open(filename, 'rb')
document.ParseFromString(fh.read())
fh.close()
return self._parse(document, rivec)
else:
fh = codecs.open(filename, 'r', 'utf-8')
lines = fh.readlines()
fh.close()
self._say("Parsing " + str(len(lines)) + " lines of code from " + filename)
self._compile(filename, rivec, 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._compile("stream()", None, code)
def _compile(self, fname, outfile, code):
"""Compile RiveScript text into the Protocol Buffers binary format."""
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
objbuf = [] # Object contents buffer
ontrig = '' # The current trigger
# Prepare protocol buffers containers.
binDocument = proto.Document(version="2.0")
binTopics = dict() # Map of Topics
binMacros = dict() # Map of Macros
binTrigger = dict() # Pointer to the current 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):
binMacros[objname].code = "\n".join(objbuf)
objname = ''
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
# Do a lookahead for ^Continue 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 a ^Continue.
if lookCmd != '^':
break
# 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 == '^':
line += lookahead
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
# Most config types are simple key/value stores.
if type in ["global", "var", "sub", "person"]:
getattr(binDocument, type).add(key=var, value=value)
elif type == "array":
# 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', ' ')
binDocument.array.add(name=var, content=fields)
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.
type = 'topic'
name = '__begin__'
if type == 'topic':
# Starting a new topic.
ontrig = ''
topic = name
if not topic in binTopics:
binTopics[topic] = binDocument.topic.add(name=topic)
# 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 field in binTopics[topic].include:
binTopics[topic].include.append(field)
else:
if not field in binTopics[topic].inherit:
binTopics[topic].inherit.append(field)
elif type == 'object':
# If a field was provided, it should be the programming
# language.
lang = None
if len(fields) > 0:
lang = fields[0].lower()
ontrig = ''
binMacros[name] = binDocument.macro.add(name=name)
if lang:
binMacros[name].language = lang
objname = name
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
# All following commands will require a topic association.
if not topic in binTopics:
binTopics[topic] = binDocument.topic.add(name=topic)
if cmd == '+':
# + TRIGGER
self._say("\tTrigger pattern: " + line)
ontrig = line
binTrigger = binTopics[topic].trigger.add(
text=ontrig,
syntax=proto.Syntax(filename=fname, line=lineno),
)
elif cmd == '-':
# - REPLY
if ontrig == '':
self._warn("Response found before trigger", fname, lineno)
continue
self._say("\tResponse: " + line)
binTrigger.reply.add(
text=line,
syntax=proto.Syntax(filename=fname, line=lineno),
)
elif cmd == '%':
# % PREVIOUS
binTrigger.previous.add(
text=line,
syntax=proto.Syntax(filename=fname, line=lineno),
)
elif cmd == '^':
# ^ CONTINUE
pass # This was handled above.
elif cmd == '@':
# @ REDIRECT
self._say("\tRedirect response to " + line)
binTrigger.redirect.add(
text=line,
syntax=proto.Syntax(filename=fname, line=lineno),
)
elif cmd == '*':
# * CONDITION
self._say("\tAdding condition: " + line)
parts = line.split("=>")
binTrigger.condition.add(
condition=parts[0].strip(),
text=parts[1].strip(),
syntax=proto.Syntax(filename=fname, line=lineno),
)
elif cmd in ['!', '>', '<']:
pass # These were handled above
else:
self._warn("Unrecognized command \"" + cmd + "\"", fname, lineno)
continue
# Write the compiled output back to disk, if possible.
if outfile is not None and self._protobuf:
try:
fh = open(outfile, 'wb')
fh.write(binDocument.SerializeToString())
fh.close()
except:
pass
# Immediately parse the results.
return self._parse(binDocument, fname)
def _parse(self, document, fname):
"""Parse RiveScript code into memory."""
self._say("Loading RiveScript document into memory.")
# Version checking.
if float(document.version) > rs_version:
self._warn("Won't process replies from {}: RiveScript version is too high!".format(fname))
return
# Load in configuration data.
for config in ["global", "var", "sub", "person", "array"]:
for item in getattr(document, config):
if config == "array":
self._arrays[item.name] = item.content
else:
intvar = config
if config == "global":
intvar = "gvars"
elif config == "var":
intvar = "bvars"
elif config == "sub":
intvar = "subs"
getattr(self, "_{}".format(intvar))[item.key] = item.value
# Process the object macros.
for macro in document.macro:
# Do we have this language?
lang = macro.language or "python"
if lang in self._handlers:
self._objlangs[macro.name] = lang
self._handlers[lang].load(macro.name, macro.code.split("\n"))
# Go through all the topics.
for topic in document.topic:
self._say("Parsing topic from binary: {}".format(topic.name))
# Includes and Inherits.
for include in topic.include:
if not topic.name in self._includes:
self._includes[topic.name] = {}
self._includes[topic.name][include] = 1
for inherit in topic.inherit:
if not topic.name in self._lineage:
self._lineage[topic.name] = {}
self._lineage[topic.name][inherit] = 1
# TODO: handle when the "syntax" is missing (theoretically possible)
# Go through the topic's triggers.
for trigger in topic.trigger:
# Has a previous?
target = None
syntax = None
if trigger.previous:
# Multiple %Previous's can refer to the same trigger, so
# process one trigger for each one.
for previous in trigger.previous:
self._initTT("thats", topic.name, previous.text, trigger.text)
self._initTT("syntax", topic.name, trigger.text, "thats")
target = self._thats[topic.name][previous.text][trigger.text]
syntax = self._syntax["thats"][topic.name][trigger.text]
syntax["trigger"] = (trigger.syntax.filename, trigger.syntax.line)
self._handle_trigger_contents(trigger, target, syntax)
else:
self._initTT("topics", topic.name, trigger.text)
self._initTT("syntax", topic.name, trigger.text, "topics")
target = self._topics[topic.name][trigger.text]
syntax = self._syntax["topics"][topic.name][trigger.text]
syntax["trigger"] = (trigger.syntax.filename, trigger.syntax.line)
self._handle_trigger_contents(trigger, target, syntax)
def _handle_trigger_contents(self, trigger, target, syntax):
# Count replies & conditions.
repcnt = 0
concnt = 0
# Redirect?
for redirect in trigger.redirect:
target["redirect"] = redirect.text
syntax["redirect"] = (redirect.syntax.filename, redirect.syntax.line)
# Replies
for reply in trigger.reply:
target["reply"][repcnt] = reply.text
syntax["reply"][repcnt] = (reply.syntax.filename, reply.syntax.line)
repcnt += 1
# Conditions
for condition in trigger.condition:
target["condition"][concnt] = condition.condition + " => " + condition.text
syntax["condition"][concnt] = (condition.syntax.filename, condition.syntax.line)
concnt += 1
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":
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":
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
# 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"
# In UTF-8 mode, most symbols are allowed.
if self._utf8:
match = re.match(r'[A-Z\\.]', line)
if match:
return "Triggers can't contain uppercase letters, backslashes or dots in UTF-8 mode."
else:
match = re.match(r'[^a-z0-9(\|)\[\]*_#@{}<>=\s]', line)
if match:
return "Triggers may only contain lowercase letters, numbers, and these symbols: ( | ) [ ] * _ # @ { } < > ="
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 deparse(self):
"""Return the in-memory RiveScript document as a Python data structure.
This would be useful for developing a user interface for editing
RiveScript replies without having to edit the RiveScript code
manually."""
# Data to return.
result = {
"begin": {
"global": {},
"var": {},
"sub": {},
"person": {},
"array": {},
"triggers": {},
"that": {},
},
"topic": {},
"that": {},
"inherit": {},
"include": {},
}
# Populate the config fields.
if self._debug:
result["begin"]["global"]["debug"] = self._debug
if self._depth != 50:
result["begin"]["global"]["depth"] = 50
# Definitions
result["begin"]["var"] = self._bvars.copy()
result["begin"]["sub"] = self._subs.copy()
result["begin"]["person"] = self._person.copy()
result["begin"]["array"] = self._arrays.copy()
result["begin"]["global"].update(self._gvars.copy())
# Topic Triggers.
for topic in self._topics:
dest = {} # Where to place the topic info
if topic == "__begin__":
# Begin block.
dest = result["begin"]["triggers"]
else:
# Normal topic.
if not topic in result["topic"]:
result["topic"][topic] = {}
dest = result["topic"][topic]
# Copy the triggers.
for trig, data in self._topics[topic].iteritems():
dest[trig] = self._copy_trigger(trig, data)
# %Previous's.
for topic in self._thats:
dest = {} # Where to place the topic info
if topic == "__begin__":
# Begin block.
dest = result["begin"]["that"]
else:
# Normal topic.
if not topic in result["that"]:
result["that"][topic] = {}
dest = result["that"][topic]
# The "that" structure is backwards: bot reply, then trigger, then info.
for previous, pdata in self._thats[topic].iteritems():
for trig, data in pdata.iteritems():
dest[trig] = self._copy_trigger(trig, data, previous)
# Inherits/Includes.
for topic, data in self._lineage.iteritems():
result["inherit"][topic] = []
for inherit in data:
result["inherit"][topic].append(inherit)
for topic, data in self._includes.iteritems():
result["include"][topic] = []
for include in data:
result["include"][topic].append(include)
return result
def write(self, fh, deparsed=None):
"""Write the currently parsed RiveScript data into a file.
Pass either a file name (string) or a file handle object.
This uses `deparse()` to dump a representation of the loaded data and
writes it to the destination file. If you provide your own data as the
`deparsed` argument, it will use that data instead of calling
`deparse()` itself. This way you can use `deparse()`, edit the data,
and use that to write the RiveScript document (for example, to be used
by a user interface for editing RiveScript without writing the code
directly)."""
# Passed a string instead of a file handle?
if type(fh) is str:
fh = codecs.open(fh, "w", "utf-8")
# Deparse the loaded data.
if deparsed is None:
deparsed = self.deparse()
# Start at the beginning.
fh.write("// Written by rivescript.deparse()\n")
fh.write("! version = 2.0\n\n")
# Variables of all sorts!
for kind in ["global", "var", "sub", "person", "array"]:
if len(deparsed["begin"][kind].keys()) == 0:
continue
for var in sorted(deparsed["begin"][kind].keys()):
# Array types need to be separated by either spaces or pipes.
data = deparsed["begin"][kind][var]
if type(data) not in [str, unicode]:
needs_pipes = False
for test in data:
if " " in test:
needs_pipes = True
break
# Word-wrap the result, target width is 78 chars minus the
# kind, var, and spaces and equals sign.
if needs_pipes:
data = self._write_wrapped("|".join(data), sep="|")
else:
data = " ".join(data)
fh.write("! {kind} {var} = {data}\n".format(
kind=kind,
var=var,
data=data,
))
fh.write("\n")
# Begin block.
if len(deparsed["begin"]["triggers"].keys()):
fh.write("> begin\n\n")
self._write_triggers(fh, deparsed["begin"]["triggers"], indent="\t")
fh.write("< begin\n\n")
# The topics. Random first!
topics = ["random"]
topics.extend(sorted(deparsed["topic"].keys()))
done_random = False
for topic in topics:
if not topic in deparsed["topic"]: continue
if topic == "random" and done_random: continue
if topic == "random": done_random = True
tagged = False # Used > topic tag
if topic != "random" or topic in deparsed["include"] or topic in deparsed["inherit"]:
tagged = True
fh.write("> topic " + topic)
if topic in deparsed["inherit"]:
fh.write(" inherits " + " ".join(deparsed["inherit"][topic]))
if topic in deparsed["include"]:
fh.write(" includes " + " ".join(deparsed["include"][topic]))
fh.write("\n\n")
indent = "\t" if tagged else ""
self._write_triggers(fh, deparsed["topic"][topic], indent=indent)
# Any %Previous's?
if topic in deparsed["that"]:
self._write_triggers(fh, deparsed["that"][topic], indent=indent)
if tagged:
fh.write("< topic\n\n")
return True
def _copy_trigger(self, trig, data, previous=None):
"""Make copies of all data below a trigger."""
# Copied data.
dest = {}
if previous:
dest["previous"] = previous
if "redirect" in data and data["redirect"]:
# @Redirect
dest["redirect"] = data["redirect"]
if "condition" in data and len(data["condition"].keys()):
# *Condition
dest["condition"] = []
for i in sorted(data["condition"].keys()):
dest["condition"].append(data["condition"][i])
if "reply" in data and len(data["reply"].keys()):
# -Reply
dest["reply"] = []
for i in sorted(data["reply"].keys()):
dest["reply"].append(data["reply"][i])
return dest
def _write_triggers(self, fh, triggers, indent=""):
"""Write triggers to a file handle."""
for trig in sorted(triggers.keys()):
fh.write(indent + "+ " + self._write_wrapped(trig, indent=indent) + "\n")
d = triggers[trig]
if "previous" in d:
fh.write(indent + "% " + self._write_wrapped(d["previous"], indent=indent) + "\n")
if "condition" in d:
for cond in d["condition"]:
fh.write(indent + "* " + self._write_wrapped(cond, indent=indent) + "\n")
if "redirect" in d:
fh.write(indent + "@ " + self._write_wrapped(d["redirect"], indent=indent) + "\n")
if "reply" in d:
for reply in d["reply"]:
fh.write(indent + "- " + self._write_wrapped(reply, indent=indent) + "\n")
fh.write("\n")
def _write_wrapped(self, line, sep=" ", indent="", width=78):
"""Word-wrap a line of RiveScript code for being written to a file."""
words = line.split(sep)
lines = []
line = ""
buf = []
while len(words):
buf.append(words.pop(0))
line = sep.join(buf)
if len(line) > width:
# Need to word wrap!
words.insert(0, buf.pop()) # Undo
lines.append(sep.join(buf))
buf = []
line = ""
# Straggler?
if line:
lines.append(line)
# Returned output
result = lines.pop(0)
if len(lines):
eol = ""
if sep == " ":
eol = "\s"
for item in lines:
result += eol + "\n" + indent + "^ " + item
return result
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'] = {}
elif toplevel == 'syntax':
if not what in self._syntax:
self._syntax[what] = {}
if not topic in self._syntax[what]:
self._syntax[what][topic] = {}
if not trigger in self._syntax[what][topic]:
self._syntax[what][topic][trigger] = {}
self._syntax[what][topic][trigger]['reply'] = {}
self._syntax[what][topic][trigger]['condition'] = {}
self._syntax[what][topic][trigger]['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)