Ejemplo n.º 1
0
 def __init__(self, name, raw_name, sockyx=None):
     self.name = name
     self.raw_name = raw_name
     self.bind(sockyx)
     self.config = Config
     self.brain = brain
     self.path = NEURONS_DIR + '/' + raw_name
     self.log = getLogger(name)
Ejemplo n.º 2
0
import os, git
from flask import jsonify, make_response, app
from flask_jwt_extended import get_jwt_identity, create_access_token, get_jti
from flask_restful import Resource, reqparse
from onyx.decorators import login_required
from onyx.utils.log import getLogger
from onyx.extensions import db
from onyx.models import Tokens as TokenModel, to_dict, RevokedToken
from onyx.config import Config

log = getLogger('Tokens')


class Tokens(Resource):
    parser = reqparse.RequestParser(bundle_errors=True)
    parser.add_argument('name')
    parser.add_argument('id')

    @login_required
    def get(self):
        try:
            tokens = [to_dict(token) for token in TokenModel.query.all()]

            return jsonify(status="success", tokens=tokens)
        except Exception as e:
            return jsonify(status="error", message="{}".format(e))

    def post(self):
        try:
            args = self.parser.parse_args()
Ejemplo n.º 3
0
from onyx.brain.core import OnyxNeuron
from neurons.weather.api import *
from onyx.utils.log import getLogger

__author__ = 'Cassim Khouani'

LOGGER = getLogger("Weather")


class WeatherNeuron(OnyxNeuron):
    def __init__(self):
        super(WeatherNeuron, self).__init__(name="WeatherNeuron",
                                            raw_name="weather")

    def get_api(self):
        api = [{
            'route': '/neuron/weather/token',
            'class': WeatherToken
        }, {
            'route': '/neuron/weather/today',
            'class': WeatherToday
        }]
        return api

    def initialize(self):
        #Initialize the Neuron
        LOGGER.info("Weather init")

    def stop(self):
        pass
Ejemplo n.º 4
0
# -*- coding: utf-8 -*-
"""
Onyx Project
https://onyxlabs.fr
Software under licence Creative Commons 3.0 France
http://creativecommons.org/licenses/by-nc-sa/3.0/fr/
You may not use this software for commercial purposes.
@author :: Cassim Khouani
"""
import os, imp
from onyx.config import Config
from onyx.sockyx.message import Message
from onyx.utils.log import getLogger
from onyx.brain.brain import brain

logger = getLogger("Neurons")

BLACKLISTED_NEURONS = []
NEURONS_DIR = Config.NEURON_PATH
MainModule = '__init__'

def load_neuron(neuron_descriptor, sockyx):
    try:
        logger.info("ATTEMPTING TO LOAD NEURON: " + neuron_descriptor["name"])
        if neuron_descriptor['name'] in BLACKLISTED_NEURONS:
            logger.info("NEURON IS BLACKLISTED " + neuron_descriptor["name"])
            return None
        neuron_module = imp.load_module(neuron_descriptor["name"] + MainModule, *neuron_descriptor["info"])
        if (hasattr(neuron_module, 'create_neuron') and callable(neuron_module.create_neuron)):
            neuron = neuron_module.create_neuron()
            neuron.bind(sockyx)
Ejemplo n.º 5
0
import os, json
from flask import jsonify, make_response, app
from flask_jwt_extended import get_jwt_identity
from flask_restful import Resource, reqparse
from onyx.decorators import login_required
from onyx.utils.log import getLogger
from onyx.extensions import db
from onyx.models import Widgets as WidgetModel, to_dict
from onyx.config import Config

log = getLogger('Widgets')


class WidgetsStore(Resource):
    @login_required
    def get(self):
        try:
            all_widgets = []

            for root, dirs, files in os.walk(Config.NEURON_PATH):
                for name in files:
                    if name == "neuron_info.json":
                        full_path = os.path.join(root, name)
                        with open(full_path, 'r') as neuron_file:
                            neuron = json.load(neuron_file)
                            if 'widgets' in neuron:
                                for widget in neuron['widgets']:
                                    widget['type'] = 'neuron'
                                    all_widgets.append(widget)

            return jsonify(status="success", widgets=all_widgets)
Ejemplo n.º 6
0
http://creativecommons.org/licenses/by-nc-sa/3.0/fr/
You may not use this software for commercial purposes.
@author :: Cassim Khouani
"""
import onyx, sys, os, time

import threading
from threading import Thread

from onyx.utils.log import getLogger
from onyx.sockyx.client.ws import WebsocketClient
from onyx.sockyx.message import Message

global ws

LOG = getLogger('Client')

def handle_speak(event):
    utterance = event.data.get('utterance')
    print(">> " + utterance)

def handle_test(event):
    print(event.data['utterances'][0])

def handle_finish(event):
    print("Finish")

def connect():
    # Once the websocket has connected, just watch it for speak events
    ws.run_forever()
Ejemplo n.º 7
0
from neurons.calendar.api import *
from onyx.brain.core import OnyxNeuron
from onyx.utils.log import getLogger
from onyx.api.request import BearerAuth
import requests

from neurons.calendar.models.CalendarModel import Calendar as CalendarModel
from onyx.models import to_dict

__author__ = 'Cassim Khouani'

LOGGER = getLogger("Calendar")


class CalendarNeuron(OnyxNeuron):
    def __init__(self):
        super(CalendarNeuron, self).__init__(name="CalendarNeuron",
                                             raw_name="calendar")

    def get_api(self):
        api = [{
            'route': '/neuron/calendar',
            'class': Calendar
        }, {
            'route': '/neuron/calendar/today',
            'class': CalendarToday
        }, {
            'route': '/neuron/calendar/update',
            'class': UpdateCalendar
        }]
        return api
Ejemplo n.º 8
0
import os, git
from flask import jsonify, make_response, app
from flask_jwt_extended import get_jwt_identity
from flask_restful import Resource, reqparse
from onyx.decorators import login_required
from onyx.utils.log import getLogger
from onyx.extensions import db
from onyx.models import Notifications as NotifModel, to_dict
from onyx.config import Config

log = getLogger('Notifications')

class Notifications(Resource):
    parser = reqparse.RequestParser(bundle_errors=True)
    parser.add_argument('id')

    @login_required
    def get(self):
        try:
            user = get_jwt_identity()
            notifications = [to_dict(notification) for notification in NotifModel.query.filter_by(user=user['id']).limit(50)]

            return jsonify(status="success", notifications=notifications)
        except Exception as e:
            return jsonify(status="error", message="{}".format(e))

    @login_required
    def post(self):
        try:
            args = self.parser.parse_args()
Ejemplo n.º 9
0
import json, os, git, shutil
from flask import jsonify, make_response, app
from flask_restful import Resource, reqparse
from onyx.decorators import login_required
from onyx.brain.core import get_neuron
from onyx.utils.log import getLogger
from onyx.api.users import Nav

from onyx.config import Config

nav = Nav()
log = getLogger('Neurons')

class Neurons():

    def getAllNeurons(self, path):
        all_neurons = []

        for root, dirs, files in os.walk(path):
            for name in files:
                if name == "neuron_info.json":
                    full_path = os.path.join(root, name)
                    import_neuron_path = os.path.join(os.path.dirname(full_path), "dist", "index.js")
                    with open(full_path, 'r') as neuron_file:
                        neuron = json.load(neuron_file)
                        neuron["path"] = os.path.dirname(full_path)
                        #neuron["import_path"] = import_neuron_path

                        all_neurons.append(neuron)

        return all_neurons
Ejemplo n.º 10
0
import os, git
from flask import jsonify, make_response, app
from flask_restful import Resource, reqparse
from onyx.decorators import login_required
from onyx.utils.log import getLogger
from onyx.config import Config

log = getLogger('Settings')

class OnyxData(Resource):
    def get(self):
        try:
            if not os.listdir(Config.DATA_PATH) :
                # Download Data
                log.info('Downloading Onyx Data')
                git.Repo.clone_from('https://github.com/OnyxAI/onyx-data', Config.DATA_PATH)
            else:
                # Update Data
                log.info('Updating Onyx Data')
                data_folder = git.cmd.Git(Config.DATA_PATH)
                data_folder.pull()


            return jsonify(status="success")
        except Exception as e:
            return jsonify(status="error", message="{}".format(e))
Ejemplo n.º 11
0
import os, git
from flask import jsonify, app
from flask_restful import Resource, reqparse
from onyx.utils.log import getLogger
from onyx.models import User, to_dict
from onyx.config import Config
from onyx.extensions import db

from passlib.hash import sha256_crypt

log = getLogger('Install')


class Install(Resource):
    parser = reqparse.RequestParser(bundle_errors=True)
    parser.add_argument('username', required=True)
    parser.add_argument('email', required=True)
    parser.add_argument('password', required=True)
    parser.add_argument('language', required=True)
    parser.add_argument('firstname', required=True)
    parser.add_argument('lastname', required=True)

    def get(self):
        try:
            users = [to_dict(user) for user in User.query.all()]

            if len(users) > 0:
                return jsonify(status="success", isInstalled="true")
            return jsonify(status="success", isInstalled="false")
        except Exception as e:
            return jsonify(status="error", message="{}".format(e))
Ejemplo n.º 12
0
Archivo: users.py Proyecto: OnyxAI/onyx
from flask import jsonify, make_response
from flask_jwt_extended import jwt_required, jwt_refresh_token_required, create_access_token, create_refresh_token, get_jwt_identity, get_raw_jwt
from flask_restful import Resource, reqparse
from flask_restful.utils import cors

from onyx.utils.log import getLogger
from onyx.extensions import db
from onyx.decorators import login_required
from onyx.models import User, RevokedToken, Nav as NavModel, to_dict, Buttons as ButtonsModel
from passlib.hash import sha256_crypt

import json

log = getLogger('Users')


class GetAllUser(Resource):
    @login_required
    def get(self):
        try:
            return jsonify([to_dict(user) for user in User.query.all()])
        except Exception as e:
            return jsonify(status="error", message="{}".format(e)), 500


class GetUser(Resource):
    parser = reqparse.RequestParser(bundle_errors=True)
    parser.add_argument('id')

    @login_required
    def get(self):
Ejemplo n.º 13
0
import os, json
from flask import jsonify, make_response, app
from flask_jwt_extended import get_jwt_identity
from flask_restful import Resource, reqparse
from onyx.decorators import login_required
from onyx.utils.log import getLogger
from onyx.extensions import db
from onyx.models import Screen as ScreenModel, to_dict, ScreenLayouts as ScreenLayoutsModel
from onyx.config import Config

log = getLogger('Screen')


class ScreenStore(Resource):
    @login_required
    def get(self):
        try:
            all_screen = []

            for root, dirs, files in os.walk(Config.NEURON_PATH):
                for name in files:
                    if name == "neuron_info.json":
                        full_path = os.path.join(root, name)
                        with open(full_path, 'r') as neuron_file:
                            neuron = json.load(neuron_file)
                            if 'screen' in neuron:
                                for screen in neuron['screen']:
                                    screen['type'] = 'neuron'
                                    all_screen.append(screen)

            return jsonify(status="success", screen=all_screen)
Ejemplo n.º 14
0
from onyx.utils import play_wav, play_mp3
from onyx.utils.log import getLogger
from onyx.client.stt import STTFactory
from onyx.client.tts import TTSFactory

import threading
from threading import Thread

from onyx.sockyx.client.ws import WebsocketClient
from onyx.sockyx.message import Message

stt = STTFactory.create()
tts = TTSFactory.create()
token = config.API_TOKEN

LOG = getLogger('SpeechClient')
import speech_recognition as sr


def handle_speak(event):
    utterance = event.data.get('utterance')
    tts.execute(utterance)


def connect():
    ws.run_forever()


ws = WebsocketClient()
ws.on('speak', handle_speak)
Ejemplo n.º 15
0
Archivo: app.py Proyecto: OnyxAI/onyx
import os
from flask import Flask, Blueprint, jsonify, render_template, send_from_directory, request, redirect
from flask_cors import CORS
from flask_jwt_extended import JWTManager

from onyx.brain.core import get_api
from onyx.core import api, neurons_bp
from onyx.extensions import db
from onyx.app_config import DevConfig, Config
from onyx.models import RevokedToken

from onyx.utils.log import getLogger

to_reload = False
log = getLogger('ONYX')


def create_app(config=DevConfig):
    app = Flask(__name__, template_folder='../dist', static_folder='../dist')

    cors = CORS(app, resources={r"*": {"origins": "*"}})
    app.config.from_object(config)

    register_extensions(app)

    with app.app_context():
        db.create_all()

    return app

Ejemplo n.º 16
0
You may not use this software for commercial purposes.
@author :: Cassim Khouani
"""

import socket
import subprocess
import tempfile

import os
import os.path
import psutil
from os.path import dirname
from onyx.utils.log import getLogger
from onyx.config import Config

LOG = getLogger(__name__)


def record(file_path, duration, rate, channels):
    if duration > 0:
        return subprocess.Popen([
            "arecord", "-r",
            str(rate), "-c",
            str(channels), "-d",
            str(duration), file_path
        ])
    else:
        return subprocess.Popen(
            ["arecord", "-r",
             str(rate), "-c",
             str(channels), file_path])
Ejemplo n.º 17
0
Software under licence Creative Commons 3.0 France
http://creativecommons.org/licenses/by-nc-sa/3.0/fr/
You may not use this software for commercial purposes.
@author :: Cassim Khouani
"""
import os, sys, time, json
from os.path import join
from threading import Timer
from onyx.sockyx.client.ws import WebsocketClient
from onyx.sockyx.message import Message
from onyx.brain.core import NEURONS_DIR, MainModule, load_neuron, create_neuron_descriptor
from onyx.utils.log import getLogger
from onyx.utils import connected
from onyx.brain.brain import brain

logger = getLogger('Neuron')

ws = None
loaded_neurons = {}
neuron_reload_thread = None


def _load_neurons():
    global ws, loaded_neurons, neuron_reload_thread
    check_connection()

    # Creating a thread to launch and monitors all neurons
    neuron_reload_thread = Timer(0, _watch_neurons)
    neuron_reload_thread.daemon = True
    neuron_reload_thread.start()