-
Notifications
You must be signed in to change notification settings - Fork 1
/
JayI.py
executable file
·158 lines (134 loc) · 4.88 KB
/
JayI.py
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
#!/usr/bin/env python3
#
# JayI main executable.
#
# Made by reading-school-cs-club!
#
from datetime import datetime
from sys import exit
import os
import string, re
import csv
LIKE = "like "
KEYS = ["trigger", "answer"]
# the core
class JayI:
def __init__(self, filename="responses.csv", interactive=False):
self.filename = filename
self.learning = None
self.interactive = interactive
self.map = {}
try:
open(self.filename, "r+").close()
self.read_file()
except (IOError, FileNotFoundError):
self.reset()
def reset(self):
if os.path.exists(self.filename):
os.remove(self.filename)
self.init_file()
self.learn("Hello", "Hi")
self.learn("Hi", "Hello")
self.read_file()
def learn(self, key, value):
key = self.flatten(key)
self.map[key] = self.parse(value)
self.write_file(key, value)
def init_file(self):
with open(self.filename, "w+") as file:
writer = csv.DictWriter(file, fieldnames=KEYS, quoting=csv.QUOTE_ALL)
writer.writeheader()
def write_file(self, key, value):
with open(self.filename, "a+") as file:
writer = csv.DictWriter(file, fieldnames=KEYS, quoting=csv.QUOTE_ALL)
writer.writerow({ KEYS[0]: key, KEYS[1]: value })
def parse(self, value):
flattened = self.flatten(value)
if flattened.startswith(LIKE):
return self.link(flattened[len(LIKE):])
return value.strip()
def read_file(self):
self.map = {}
with open(self.filename, "r") as file:
reader = csv.DictReader(file)
for row in reader:
key = row[KEYS[0]]
value = row[KEYS[1]]
self.map[key] = self.parse(value)
@staticmethod
def flatten(phrase):
"""Simplify a phrase, stripping spacing & other characters."""
# replace all spacing (tabs, newlines, etc.) with space
flattened = re.sub(r"\s", " ", phrase)
# squeeze spaces, make it lowercase and strip out punctuation and excess spacing
return re.sub(r"\s\s+", " ", flattened).lower().translate(dict.fromkeys(map(ord, string.punctuation))).strip()
def link(self, trigger):
trigger = self.flatten(trigger)
def linker():
return self.respond(trigger)
return linker
@staticmethod
# find out my birthday
def birthday():
birthday = datetime.fromtimestamp(1423989360) # 15/02/2015
age = (datetime.utcnow() - birthday).days
return age
# the whole loop!
def respond(self, trigger):
learning = self.learning
self.learning = None
if not trigger.strip():
return
if learning:
self.learn(learning, trigger)
return
trigger = self.flatten(trigger)
if trigger in self.map:
learnt = self.map[trigger]
try:
return learnt()
except TypeError:
return learnt
if trigger == "bye":
msg = "Bye, see you soon!"
if self.interactive:
print(msg)
exit()
return msg
elif trigger == "delete all":
self.reset()
return
elif trigger == "where were you born":
self.learning = trigger
return "I'm not sure. Can you tell me?"
elif trigger in ["how old are you", "when were you born"]:
birthday = self.birthday()
day = "day" if birthday == 1 else "days"
return "I am %d %s old" % (birthday, day)
else:
self.learning = trigger
return "Sorry, that is not in my database. Suggest me a good response: "
if __name__ == "__main__":
print(r"""
_________________
|\________________\
\|_______ _____| __________ ___ ___
| | | |\_________\ |\__\ |\__\
____| | | | | _____ | | | | | | |
|\ ____| | | | | | |___ | | |___| | |
| | | | | |___| |___\ | | |___| | |
\|________| \|____________| \|_______| |
| | |
| | |
| | |
________| | |
| \_______\| |
\|__________|
Created and developed by readingschool-cs-club
Bringing Computers to Life
""")
Jay = JayI(interactive=True)
print("Hi there. You can talk to me.")
while True:
r = Jay.respond(input("> "))
r and print(r)