Skip to content

Commit

Permalink
progress on #104 and #109
Browse files Browse the repository at this point in the history
Many improvements in communication.Memory to find queries.
  • Loading branch information
jmmelko committed Feb 25, 2020
1 parent 91b94f5 commit c3cf4a8
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 92 deletions.
37 changes: 19 additions & 18 deletions python/command_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,32 +33,33 @@ def get_name(self):
def receive(self, *args, **kwargs):
self.communicator.receive(*args, **kwargs)

self.prompt_queries()


def prompt_queries(self, queries=None):
def execute_queries(self, queries=None):

if queries == None:
queries = self.communicator.recall(('unreplied', 'invalid_reply'))
try:
queries[0]
except TypeError:
queries = [queries]

self.communicator.memory.clean()
queries = self.communicator.recall_unsatisfied(filters=('to_me'))
else:
if not isinstance(queries,(list,tuple)):
queries = [queries]
print('%%%%I AM MUSIC-COG AND HERE ARE MY UNSATISFIED QUERIES:%%%%')
self.communicator.memory.print_out(filters=('to_me'))

for q in queries:
question = self.communicator.query_to_discord()
question = self.communicator.query_to_discord(q)
print('%%YOU ARE BEING PROMPTED%%%')
answer = input(question)
q.reply_to(answer)


return True


player = CommandLinePlayer()

maker = MusicSheetMaker()

q = player.communicator.formulate_known('create_song', recipient=maker)
player.communicator.send(q, recipient=maker)
q = player.communicator.send_known_query('create_song', recipient=maker)
#player.communicator.send(q, recipient=maker)

maker.execute_queries()

Expand All @@ -68,10 +69,10 @@ def prompt_queries(self, queries=None):

#player.communicator.memory.store(q)

print('\n\n')
player.communicator.print_memory()
print('\n')
maker.communicator.print_memory()
print('\n\n%%%Player memory:')
player.communicator.memory.print_out()
print('\n%%%Maker memory:')
maker.communicator.memory.print_out()



Expand Down
87 changes: 51 additions & 36 deletions python/communication.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,13 +126,14 @@ def __init__(self, sender=None, recipient=None, question=None, foreword=None, af

def __str__(self):
string = '<' + self.__class__.__name__ + ' ' + str(self.get_identifier()) + ' from ' + str(
self.sender) + ' to ' + str(
self.recipient) + ': ' + repr(self.question) + ', ' + str(self.reply_type) + ' expected'
self.sender.get_name()) + ' to ' + str(
self.recipient.get_name()) + ': ' + repr(self.question) + ', ' + str(self.reply_type) + ' expected'
try:
self.get_limits()[0]
string += ', within ' + str(self.limits)
except (TypeError, IndexError):
pass
string += ', answered=' + str(self.get_is_replied())
string += '>'

return string
Expand Down Expand Up @@ -234,8 +235,8 @@ def get_list_and_sanitize(obj):

if locutor_name not in self.valid_locutors_names:
locutor_ok = False
print(locutor_name)
print(self.valid_locutors_names)
#print(locutor_name)
#print(self.valid_locutors_names)
print('locutor is not in internal validation list')

if allowed != 'all':
Expand Down Expand Up @@ -596,16 +597,20 @@ class QueryMemory:
Note that erasing a Query here does *not* delete the object in Python
"""

def __init__(self, topic=None):
def __init__(self, owner, topic=None):

self.owner = owner
self.queries = []
self.topic = topic # A topic for this specific memory object
self.query_filters = {
'replied': lambda q: q.get_is_replied(),
'sent': lambda q: q.get_is_sent(),
'unreplied': lambda q: not q.get_is_replied(),
'unsent': lambda q: not q.get_is_sent(),
'valid_reply': lambda q: q.get_reply_validity(), 'invalid_reply': lambda q: not q.get_reply_validity()}
'valid_reply': lambda q: q.get_reply_validity(), 'invalid_reply': lambda q: not q.get_reply_validity(),
'from_me': lambda q: q.get_sender()==self.owner,
'to_me': lambda q: q.get_recipient()==self.owner,
}

def __str__(self):

Expand All @@ -616,6 +621,14 @@ def __len__(self):

return len(self.queries)

def print_out(self, filters=None, criterion=None):

print(self)
for i,q in enumerate(self.recall(filters=filters,criterion=criterion)):
print('----query#'+str(i)+'----')
print(q)
print('---------------')

def recall_filtered(self, filters=None):

if filters is None:
Expand Down Expand Up @@ -662,23 +675,23 @@ def recall_last_sent(self, filters=None):
else:
return None

def recall_by_identifier(self, identifier):
def recall_by_identifier(self, identifier, filters=None):
"""
Recalls Queries with the given identifier
"""
q_found = []
for query in self.queries:
if query.get_identifier() == identifier:
q_found += [query]
return q_found
queries = self.recall_filtered(filters)
return [q for q in queries if q.get_identifier() == identifier]

def has_query(self, criterion=None):
def recall_by_sender(self, sender, filters=None):
queries = self.recall_filtered(filters)
return [q for q in queries if q.get_sender() == sender]

def recall_by_recipient(self, recipient, filters=None):
queries = self.recall_filtered(filters)
return [q for q in queries if q.get_recipient() == sender]

q_found = self.recall(criterion)
if len(q_found) > 0:
return True
else:
return False
def has_query(self, criterion=None, filters=None):
return len(self.recall(criterion=criterion, filters=filters) > 0)

def recall(self, criterion=None, filters=None):
"""
Expand All @@ -702,28 +715,30 @@ def recall(self, criterion=None, filters=None):
for q in queries: # Maybe criterion is an attribute, some text for instance
attr_vals = list(q.__dict__.values())
if criterion in attr_vals:
q_found.append(q)
q_found += [q]

return q_found

def recall_unsent(self):

qlist = [q for q in self.queries if q.get_is_sent() == False]
return qlist

def recall_replied(self):

return [q for q in self.queries if q.get_is_replied()]

def recall_unreplied(self):
def recall_unsent(self, filters=None):
queries = self.recall_filtered(filters)
return [q for q in queries if q.get_is_sent() == False]

return [q for q in self.queries if not q.get_is_replied()]
def recall_replied(self, filters=None):
queries = self.recall_filtered(filters)
return [q for q in queries if q.get_is_replied()]

def recall_by_invalid_reply(self):
def recall_unreplied(self, filters=None):
queries = self.recall_filtered(filters)
return [q for q in queries if not q.get_is_replied()]

q_replied = self.recall_replied()
def recall_by_invalid_reply(self, filters=None):
q_replied = self.recall_replied(filters=filters)
return [q for q in q_replied if not q.reply.get_validity()]

def recall_unsatisfied(self, filters=None):
queries = self.recall_filtered(filters)
return [q for q in queries if (not q.get_is_replied() or not q.get_reply_validity())]

def recall_repeated(self, filters=None):
"""
Recall queries that have been stored twice or more
Expand All @@ -750,7 +765,7 @@ def recall_repeated(self, filters=None):
return repeated


def erase_repeated(self, filters):
def erase_repeated(self, filters=None):
"""
Erase repeated Queries, keeping the most recent in time
"""
Expand All @@ -764,13 +779,13 @@ def erase_repeated(self, filters):
for q in repeated[0:-1]:
self.queries.remove(q)
return True
except (KeyError, TypeError):
except (IndexError, TypeError):
return False

def store(self, query):

# TODO: add support for storing Information
print(self)
#print(self)
if isinstance(query, Query):
self.queries.append(query)
elif isinstance(query, (list, tuple)):
Expand Down Expand Up @@ -804,7 +819,7 @@ def erase(self, criterion=None):

def clean(self):

self.erase_repeated('unreplied')
self.erase_repeated(filters=('unreplied'))
#for q in self.recall_by_invalid_reply():
# self.queries.remove(q)
self.topological_sort()
Expand Down
48 changes: 21 additions & 27 deletions python/communicator.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class Communicator():

def __init__(self, owner):
self.owner = owner
self.memory = QueryMemory()
self.memory = QueryMemory(self.owner)
self.name = self.owner.get_name()

# A dictionary of standard queries arguments
Expand Down Expand Up @@ -82,7 +82,7 @@ def get_name(self):
# print('RETURNING 4')
# return default_handler_function

def formulate_known(self, known_query_name, recipient):
def send_known_query(self, known_query_name, recipient):

try:
known_query_name = known_query_name.lower().replace(' ', '_')
Expand All @@ -98,9 +98,11 @@ def formulate_known(self, known_query_name, recipient):
method_args['recipient'] = recipient
query_method = getattr(communication, method_name)
q = query_method(**method_args)
return q
self.memory.store(q)
q.check_sender(allowed=self.owner)
q.send(recipient=recipient)


'''
def send(self, communication_objects, recipient=None):
try:
Expand All @@ -120,27 +122,26 @@ def send_query(self, query, recipient):
query.check_sender(allowed=self.owner)#TODO: previously self.get_name()
query.send(recipient=recipient)
'''

def receive(self, queries):

try:
queries[0]
except TypeError:
if not isinstance(queries,(list,tuple)):
queries = [queries]

for query in queries:
query.check_recipient(allowed=self.owner)
# print('I am ' + self.get_name() + ', storing a query upon receipt.')
self.memory.store(query)
# TODO: check for duplicates
for q in queries:
if q.check_recipient(allowed=self.owner):
# print('I am ' + self.get_name() + ', storing a query upon receipt.')
self.memory.store(q)
# TODO: check for duplicates

def query_to_discord(self, obj):
question = obj.get_result()
return question
question = obj.get_result()
return question

def discord_to_query(self, obj):
return

def translate(self, obj):
Expand Down Expand Up @@ -202,23 +203,16 @@ def formulate_song_messages(self, recipient=None):
foreword=None,
afterword=None, reply_type=ReplyType.TEXT, limits=None)
self.memory.store(q_transcript_writer)

def ask_song_overwrite(self, recipient):
def query_song_overwrite(self, recipient):

q = QueryBoolean(sender=self, recipient=recipient, foreword='A Song already exist in memory.', question='Do you want to overwrite it?', reply_type=ReplyType.TEXT)
self.memory.store(q)
q.send(recipient=recipient)
return q

def send_unsent_queries(self, recipient=None):

for q in self.memory.recall_unsent():
q.send(recipient)

def print_memory(self):

print(self)
for q in self.memory.recall():
print(q)

def get_memory(self):
return self.memory

26 changes: 15 additions & 11 deletions python/music_sheet_maker.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,21 +43,24 @@ def init_working_directory(self):
def receive(self, *args, **kwargs):
self.communicator.receive(*args, **kwargs)

# self.communicator.print_memory()


def execute_queries(self):

self.communicator.memory.clean()

queries = self.communicator.recall_unreplied()
def execute_queries(self, queries=None):

if queries == None:
self.communicator.memory.clean()
queries = self.communicator.memory.recall_unsatisfied()
queries = self.communicator.recall_unsatisfied(filters=('to_me'))
else:
if not isinstance(queries,(list,tuple)):
queries = [queries]
print('%%%%I AM MAKER AND HERE ARE MY UNSATISFIED QUERIES:%%%%')
self.communicator.memory.print_out(filters=('to_me'))
for q in queries:
try:
query_name = q.get_result()
#print('This one is unreplied to :+query_name')
known_query = self.communicator.known_queries[query_name]
print('self.'+known_query['handler']+'(sender='+q.get_sender().get_name()+')')
#print('self.'+known_query['handler']+'(sender='+q.get_sender().get_name()+')')
result = eval('self.'+known_query['handler']+'(sender=q.get_sender())')
q.reply_to(result)
except KeyError:
Expand All @@ -72,9 +75,10 @@ def create_song(self, **kwargs):
raise MusicMakerError('No recipient specified for the Song')

if self.song is not None:
overwrite = self.communicator.ask_song_overwrite(recipient=recipient)


q = self.communicator.query_song_overwrite(recipient=recipient)
#print('%%%%%DEBUG')
#print(recipient)
recipient.execute_queries()
#self.set_parser(SongParser(self))
#os.chdir(self.directory_base)

Expand Down

0 comments on commit c3cf4a8

Please sign in to comment.