Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
David Muñoz committed Jan 5, 2017
0 parents commit acd6d3c
Show file tree
Hide file tree
Showing 7 changed files with 179 additions and 0 deletions.
20 changes: 20 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#
# Copyright (c) 2017 David Muñoz Díaz <[email protected]
#
# 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.
1 change: 1 addition & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
include LICENSE
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
zoe python lib
==============

A Zoe agent library for python
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[bdist_wheel]
universal = 1
15 changes: 15 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from setuptools import setup, find_packages

setup(
name = 'zoe-lib-python',
version = '0.1.0',
description = 'Python library for Zoe assistant',
author = 'David Muñoz Díaz',
author_email='[email protected]',
license = 'MIT',
packages = find_packages(),
keywords = 'guluc3m zoe gul-zoe world-domination',
install_requires = [
'pika >= 0.10.0'
]
)
7 changes: 7 additions & 0 deletions zoe/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# -*- coding: utf-8 -*-
#
# This file is part of Zoe Assistant
# Licensed under MIT license - see LICENSE file
#

from zoe.deco import *
130 changes: 130 additions & 0 deletions zoe/deco.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# -*- coding: utf-8 -*-
#
# This file is part of Zoe Assistant
# Licensed under MIT license - see LICENSE file
#

import logging
import pika
import json
import sys
import os

url = os.environ.get('RABBITMQ_URL')
logging.basicConfig(level = logging.INFO)

class RabbitMQClient:
QUEUE = 'zoemessages'
ROUTING_KEY = 'zoemessages'
EXCHANGE = ''

def __init__(self, url, handler):
self._url = url
self._handler = handler

def run(self):
params = pika.URLParameters(self._url)
params.socket_timeout = 5
self._connection = pika.BlockingConnection(params)
self._channel = self._connection.channel()
self._channel.queue_declare(queue = self.QUEUE)
self._channel.basic_consume(self._handler, queue = self.QUEUE, no_ack = True)
self._channel.start_consuming()

def send(self, msg):
if self._channel:
self._channel.basic_publish(exchange = self.EXCHANGE, routing_key = self.ROUTING_KEY, body = msg)


class DecoratedAgent:
def __init__(self, name, agent):
self._name = name
self._agent = agent
self._logger = logging.getLogger(name)
self._candidates = []
for m in dir(agent):
k = getattr(agent, m)
if hasattr(k, "__zoe__intent__"):
self._candidates.append(k)
if hasattr(k, "__zoe__intent__any__"):
self._candidates.append(k)
self._listener = RabbitMQClient(url, self.incoming)
self._listener.run()

def sendbus(self, json):
self._listener.send(json)

def substitute(self, old, new):
""" replaces a dict's contents with the ones in another dict """
old.clear()
old.update(new)

def tojson(self, dic):
""" guess what """
return json.dumps(dic)

def fromjson(self, st):
""" guess what """
return json.loads(st)

def innerintent(self, intent):
""" finds the innermost intent to solve.
Traverses the intent tree, accumulating all objects,
and returns the first one that is actually an intent.
Yes, this can be optimized, but who cares.
"""
a = []
def traverse(intent, acc):
if 'payloads' in intent:
for p in intent['payloads']:
traverse(p, acc)
acc.append(intent)
traverse(intent, a)
for i in a:
if 'intent' in i:
return i

def incoming(self, ch, method, properties, body):
incoming = self.fromjson(body.decode('utf-8'))
if (len(incoming) == 0):
return
inner = self.innerintent(incoming)
intentName = inner['intent']
chosen = None
for c in self._candidates:
if hasattr(c, '__zoe__intent__') and c.__zoe__intent__ == intentName:
chosen = c
break
if hasattr(c, '__zoe__intent__any__'):
chosen = c
break
if not chosen:
return
ret = chosen(inner)
if not ret:
return
self.substitute(inner, ret)
self.sendbus(self.tojson(incoming))

class Intent:
def __init__(self, name):
self._name = name

def __call__(self, f):
setattr(f, '__zoe__intent__', self._name)
return f

class Any:
def __init__(self):
pass

def __call__(self, f):
setattr(f, '__zoe__intent__any__', True)
return f

class Agent:
def __init__(self, name):
self._name = name

def __call__(self, i):
DecoratedAgent(self._name, i())

0 comments on commit acd6d3c

Please sign in to comment.