Beispiel #1
0
# -*- coding: utf-8 -*-

import os
from skimage import io  # @UnresolvedImport
from skimage.transform import resize as ski_resize  # @UnresolvedImport

from monu.logger import getLogger

log = getLogger(__file__)


def resize(in_file, out_file, height=200):
    if os.path.exists(out_file):
        return True
    img = io.imread(in_file)
    ow = 1.0 * len(img)
    oh = 1.0 * len(img[0])
    width = int(height * ow / oh)
    height = int(height)
    img = ski_resize(img, (width, height))
    try:
        io.imsave(out_file, img)
    except Exception as e:
        log.critical('Error: %s', e)
        return False
    return True
Beispiel #2
0
# -*- coding: utf-8 -*-

import flask
from flask_restful import Resource
from bson import ObjectId, json_util

from monu.srv.authentication import requires_auth
from monu import mdb
from monu.logger import getLogger

log = getLogger('src.res.tag')


class Tag(Resource):
    @requires_auth
    def get(self, key=None, value=None):
        with mdb.util.open() as handle:
            if key == '_id':
                value = ObjectId(value)
            response = []
            search = {}
            if key is not None:
                search = {key: value}
            for doc in handle.tag.find(search):
                mdb.util.astrid(doc)
                response.append(doc)
        return flask.Response(response=json_util.dumps(response),
                              status=200,
                              mimetype="application/json")
Beispiel #3
0
# -*- coding: utf-8 -*-

import flask
from flask_restful import Resource
from monu.logger import getLogger
from monu.srv.authentication import requires_auth
from bson import json_util, ObjectId
from monu import mdb

log = getLogger('srv.res.ingredient')


class Ingredient(Resource):
    @requires_auth
    def get(self, key=None, value=None):
        response = []
        search = {}
        if key is not None:
            if key == '_id':
                value = ObjectId(value)
            search = {key: value}
        with mdb.util.open() as handle:
            for doc in mdb.util.find(handle.ingredient, search):
                doc = mdb.util.astrid(doc)
                if 'tag' in doc:
                    [mdb.util.astrid(tag) for tag in doc['tag']]
                response.append(doc)
            js = json_util.dumps(response)
        return flask.Response(response=js,
                              status=200,
                              mimetype="application/json")
Beispiel #4
0
# -*- coding: utf-8 -*-

from monu.logger import getLogger
from monu.mdb.insert import insert

log = getLogger('mdb.replace')


class replace(object):
    """
    Modify raw json for mongo insert
    """

    @classmethod
    def child(cls, db, js):
        if 'child' not in js or not isinstance(js['child'], list):
            return False
        for child in js['child']:
            recipe = insert.recipe(db, child)
        return True

    @classmethod
    def recipe(cls, db, js):
        pass

    @classmethod
    def ingredient(cls, db, data):
        if 'ingredient' not in data or data['ingredient'] is None:
            return
        for ingredient in data['ingredient']:
            if 'name' in ingredient and isinstance(ingredient['name'], basestring):
Beispiel #5
0
# -*- coding: utf-8 -*-

import os
import json
import monu
from monu.util import file_as_string
from monu.logger import getLogger
from pymongo import MongoClient
import bson
from monu.conf import conf
from monu.mdb.replace import replace

log = getLogger('monu.mdb.common')

schema_path = os.path.join(monu.base_path, 'monu', 'data', 'schema')
collection_path = os.path.join(schema_path, 'collection')

VALID_COLLECTION = [u'ingredient', u'recipe', u'tag']


class Error(object):
    class InvalidCollection(Exception):
        pass


def astrid(data):
    if data is not None and '_id' in data and data[
            '_id'] is not None and data['_id'] != '':
        data['_id'] = str(data['_id'])
    return data
Beispiel #6
0
# -*- coding: utf-8 -*-

import flask
from flask_restful import Resource
from bson import ObjectId, json_util

from monu.logger import getLogger
from monu.srv.authentication import requires_auth
from monu.mdb import common as mdb
from monu.srv.common import digestify

log = getLogger('srv.res.recipe')


class Recipe(Resource):
    @requires_auth
    def get(self, key=None, value=None):
        if key == '_id':
            value = ObjectId(value)
        response = []
        search = {}
        if key is not None:
            search = {key: value}
        digest = False
        if key is None:
            digest = True
        with mdb.open() as handle:
            for doc in mdb.find(handle.recipe, search):
                if 'tag' in doc and doc['tag'] is not None:
                    nt = []
                    for tag in doc['tag']:
Beispiel #7
0
# -*- coding: utf-8 -*-

from monu.logger import getLogger
from datetime import datetime

log = getLogger(__name__)

__FORMAT_GMT__ = '%a, %d %b %Y %H:%M:%S GMT'


def sgetattr(resource, name):
    try:
        return getattr(resource, name)
    except Exception as e:
        log.critical('Error: %s', e)
    return None


def column_convert(column, output):
    """Convertit les données en fonction du type de colonne
    """
    if output is None:
        return None
    if column.name in ['until', 'created_on', 'respond_on', 'updated_on']:
        return output.strftime(__FORMAT_GMT__)
    return output


def res2dct(resource, safe=True, debug=True):
    """Database row to dictionary"""
    data = {}
Beispiel #8
0
# -*- coding: utf-8 -*-

import os
import re
from datetime import datetime
import uuid
import flask
from flask_restful import Resource
from monu.conf import conf
from monu.logger import getLogger
from monu.srv.authentication import requires_auth
from monu.srv.argument import parser_factory
from monu.mdb import common as db

log = getLogger('res')

__RE_FLAGS__ = re.UNICODE & re.IGNORECASE
__AES_KEYLENGTH__ = 32
PUBUUID = str(uuid.uuid4())

parser = parser_factory()
utcnow = datetime.utcnow


class File(Resource):
    @staticmethod
    def get(name=None):
        parser = parser_factory(namespace='file',
                                locations=['values', 'json', 'headers'])
        args = parser.parse_args()
        path = os.path.join(conf.get('backend.storage', 'path'), name)
Beispiel #9
0
# -*- coding: utf-8 -*-

from bson.code import Code
from monu.logger import getLogger

log = getLogger('mdb.redux')

CODE = {
    'sum': Code('function(key, values) {'
                ' var total = 0;'
                ' for(var i = 0; i < values.length; i++) {'
                '     total += values[i];'
                ' }'
                ' return total;'
                '}')
}


def tag(db, collection):
    m = Code('function () {'
             '   if (this.tag === undefined) {'
             '       return;'
             '   }'
             '   this.tag.forEach(function(z){'
             '       emit(z, 1);'
             '   });'
             '}')
    r = Code('function(key, values) {'
             ' var total = 0;'
             ' for(var i = 0; i < values.length; i++) {'
             '     total += values[i];'
Beispiel #10
0
# -*- coding: utf-8 -*-

import os
import json
import monu
from monu.util import file_as_string
from monu.logger import getLogger
from pymongo import MongoClient
import bson
from monu.conf import conf
from monu.mdb.replace import replace

log = getLogger('monu.mdb.common')

schema_path = os.path.join(monu.base_path, 'monu', 'data', 'schema')
collection_path = os.path.join(schema_path, 'collection')

VALID_COLLECTION = [u'ingredient', u'recipe', u'tag']


class Error(object):
    class InvalidCollection(Exception):
        pass


def astrid(data):
    if data is not None and '_id' in data and data['_id'] is not None and data['_id'] != '':
        data['_id'] = str(data['_id'])
    return data

Beispiel #11
0
# -*- coding: utf-8 -*-

import os
import re
from datetime import datetime
import uuid
import flask
from flask_restful import Resource
from monu.conf import conf
from monu.logger import getLogger
from monu.srv.authentication import requires_auth
from monu.srv.argument import parser_factory
from monu.mdb import common as db

log = getLogger('res')

__RE_FLAGS__ = re.UNICODE & re.IGNORECASE
__AES_KEYLENGTH__ = 32
PUBUUID = str(uuid.uuid4())

parser = parser_factory()
utcnow = datetime.utcnow


class File(Resource):
    @staticmethod
    def get(name=None):
        parser = parser_factory(namespace='file',
                                locations=['values', 'json', 'headers'])
        args = parser.parse_args()
        path = os.path.join(conf.get('backend.storage', 'path'), name)
Beispiel #12
0
# -*- coding: utf-8 -*-

from bson.code import Code
from monu.logger import getLogger

log = getLogger('mdb.redux')

CODE = {
    'sum':
    Code('function(key, values) {'
         ' var total = 0;'
         ' for(var i = 0; i < values.length; i++) {'
         '     total += values[i];'
         ' }'
         ' return total;'
         '}')
}


def tag(db, collection):
    m = Code('function () {'
             '   if (this.tag === undefined) {'
             '       return;'
             '   }'
             '   this.tag.forEach(function(z){'
             '       emit(z, 1);'
             '   });'
             '}')
    r = Code('function(key, values) {'
             ' var total = 0;'
             ' for(var i = 0; i < values.length; i++) {'
Beispiel #13
0
# -*- coding: utf-8 -*-

from flask_restful import Resource

from monu.logger import getLogger
from monu.mdb import common as db
from monu.schema import SCHEMA

log = getLogger('srv.res.schema')


class Schema(Resource):
    @staticmethod
    def get(name=None):
        if name is None:
            return SCHEMA
        return db.get_schema(db.open(), name)