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
2513 lines (2124 loc) · 99.7 KB
/
Copy pathrivescript.py
File metadata and controls
2513 lines (2124 loc) · 99.7 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
# The MIT License (MIT)
#
# Copyright (c) 2015 Noah Petherbridge
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import unicode_literals
from six import text_type
import sys
import os
import re
import string
import random
import pprint
import copy
import codecs
from . import __version__
from . import python
# Common regular expressions.
class RE(object):
equals = re.compile('\s*=\s*')
ws = re.compile('\s+')
objend = re.compile('^\s*<\s*object')
weight = re.compile('\{weight=(\d+)\}')
inherit = re.compile('\{inherits=(\d+)\}')
wilds = re.compile('[\s\*\#\_]+')
nasties = re.compile('[^A-Za-z0-9 ]')
crlf = re.compile('<crlf>')
literal_w = re.compile(r'\\w')
array = re.compile(r'\@(.+?)\b')
def_syntax = re.compile(r'^.+(?:\s+.+|)\s*=\s*.+?$')
name_syntax = re.compile(r'[^a-z0-9_\-\s]')
utf8_trig = re.compile(r'[A-Z\\.]')
trig_syntax = re.compile(r'[^a-z0-9(\|)\[\]*_#@{}<>=\s]')
cond_syntax = re.compile(r'^.+?\s*(?:==|eq|!=|ne|<>|<|<=|>|>=)\s*.+?=>.+?$')
utf8_meta = re.compile(r'[\\<>]')
utf8_punct = re.compile(r'[.?,!;:@#$%^&*()]')
cond_split = re.compile(r'\s*=>\s*')
cond_parse = re.compile(r'^(.+?)\s+(==|eq|!=|ne|<>|<|<=|>|>=)\s+(.+?)$')
topic_tag = re.compile(r'\{topic=(.+?)\}')
set_tag = re.compile(r'<set (.+?)=(.+?)>')
bot_tag = re.compile(r'<bot (.+?)>')
get_tag = re.compile(r'<get (.+?)>')
star_tags = re.compile(r'<star(\d+)>')
botstars = re.compile(r'<botstar(\d+)>')
input_tags = re.compile(r'<input([1-9])>')
reply_tags = re.compile(r'<reply([1-9])>')
random_tags = re.compile(r'\{random\}(.+?)\{/random\}')
redir_tag = re.compile(r'\{@(.+?)\}')
tag_search = re.compile(r'<([^<]+?)>')
placeholder = re.compile(r'\x00(\d+)\x00')
zero_star = re.compile(r'^\*$')
optionals = re.compile(r'\[(.+?)\]')
# 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]"
RS_ERR_DEEP_RECURSION = "[ERR: Deep recursion detected]"
RS_ERR_OBJECT = "[ERR: Error when executing Python object]"
RS_ERR_OBJECT_HANDLER = "[ERR: No Object Handler]"
RS_ERR_OBJECT_MISSING = "[ERR: Object Not Found]"
class RiveScript(object):
"""A RiveScript interpreter for Python 2 and 3."""
# Concatenation mode characters.
_concat_modes = dict(
none="",
space=" ",
newline="\n",
)
############################################################################
# Initialization and Utility Methods #
############################################################################
def __init__(self, debug=False, strict=True, depth=50, log="", utf8=False):
"""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."""
# Instance variables.
self._debug = debug # Debug mode
self._log = log # Debug log file
self._utf8 = utf8 # UTF-8 mode
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)
self._regexc = { # Precomputed regexes for speed optimizations.
"trigger": {},
"subs": {},
"person": {},
}
# "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 or 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']
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
for item in os.listdir(directory):
for extension in ext:
if item.lower().endswith(extension):
# Load this file.
self.load_file(os.path.join(directory, item))
break
def load_file(self, filename):
"""Load and parse a RiveScript document."""
self._say("Loading file: " + filename)
fh = codecs.open(filename, 'r', 'utf-8')
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` can either be a string containing RiveScript code or an array
of lines of RiveScript code."""
self._say("Streaming code.")
if type(code) in [str, text_type]:
code = code.split("\n")
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
isThat = '' # Is a %Previous trigger
# Local (file scoped) parser options.
local_options = dict(
concat="none", # Concat mode for ^Continue command
)
# Read each line.
for lp, line in enumerate(code):
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 += self._concat_modes.get(
local_options["concat"], ""
) + 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(RE.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 == 'local':
# Local file-scoped parser options.
self._say("\tSet parser option " + var + " = " + value)
local_options[var] = value
elif 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('\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
# Precompile the regexp.
self._precompile_substitution("subs", var)
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
# Precompile the regexp.
self._precompile_substitution("person", var)
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 name not in self._includes:
self._includes[name] = {}
self._includes[name][field] = 1
else:
if name not 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 is None:
self._warn("Trying to parse unknown programming language", fname, lineno)
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)
self._initTT('syntax', topic, line, 'thats')
self._syntax['thats'][topic][line]['trigger'] = (fname, lineno)
else:
self._initTT('topics', topic, line)
self._initTT('syntax', topic, line, 'topic')
self._syntax['topic'][topic][line]['trigger'] = (fname, lineno)
ontrig = line
repcnt = 0
concnt = 0
# Pre-compile the trigger's regexp if possible.
self._precompile_regexp(ontrig)
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
self._syntax['thats'][topic][ontrig]['reply'][repcnt] = (fname, lineno)
else:
self._topics[topic][ontrig]['reply'][repcnt] = line
self._syntax['topic'][topic][ontrig]['reply'][repcnt] = (fname, lineno)
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
self._syntax['thats'][topic][ontrig]['redirect'] = (fname, lineno)
else:
self._topics[topic][ontrig]['redirect'] = line
self._syntax['topic'][topic][ontrig]['redirect'] = (fname, lineno)
elif cmd == '*':
# * CONDITION
self._say("\tAdding condition: " + line)
if len(isThat):
self._thats[topic][isThat][ontrig]['condition'][concnt] = line
self._syntax['thats'][topic][ontrig]['condition'][concnt] = (fname, lineno)
else:
self._topics[topic][ontrig]['condition'][concnt] = line
self._syntax['topic'][topic][ontrig]['condition'][concnt] = (fname, lineno)
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(RE.def_syntax, 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(RE.name_syntax, line)
if match:
return "Topics should be lowercased and contain only numbers and letters"
elif parts[0] == "object":
match = re.match(RE.name_syntax, 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 += 1
elif char == ')':
parens -= 1
elif char == '[':
square += 1
elif char == ']':
square -= 1
elif char == '{':
curly += 1
elif char == '}':
curly -= 1
elif char == '<':
angle += 1
elif char == '>':
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(RE.utf8_trig, line)
if match:
return "Triggers can't contain uppercase letters, backslashes or dots in UTF-8 mode."
else:
match = re.match(RE.trig_syntax, 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(RE.cond_syntax, 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 topic not 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 topic not 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, text_type]:
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.
width = 78 - len(kind) - len(var) - 4
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 topic not 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 topic not in self._topics:
self._topics[topic] = {}
if trigger not in self._topics[topic]:
self._topics[topic][trigger] = {}
self._topics[topic][trigger]['reply'] = {}
self._topics[topic][trigger]['condition'] = {}
self._topics[topic][trigger]['redirect'] = None