Esempio n. 1
0
class UserSchema(Schema):
    id = fields.Integer(required=True)
    full_name = fields.String(required=True)
    email = fields.String(required=True)
    manager = fields.Boolean(required=True)
    editor = fields.Boolean(required=True)
    submitter = fields.Boolean(required=True)
    roles = fields.List(fields.Nested(RoleSchema), required=True)
Esempio n. 2
0
class TrainArgsSchemaPro(Schema):
    class Meta:
        unknown = INCLUDE  # supports extra parameters

    batch_size_per_device = fields.Integer(
        missing=64, description='Batch size for each GPU.', required=False)
    dataset = fields.Str(
        missing='synthetic_data',
        enum=['synthetic_data', 'imagenet', 'imagenet_mini', 'cifar10'],
        description='Dataset to perform training on. \
                         synthetic_data: randomly generated ImageNet-like \
                         images; imagenet_mini: 3% of the real ImageNet \
                         dataset',
        required=False)
    model = fields.Str(missing='resnet50 (ImageNet)',
                       enum=[
                           'googlenet (ImageNet)', 'inception3 (ImageNet)',
                           'mobilenet (ImageNet)', 'overfeat (ImageNet)',
                           'resnet50 (ImageNet)', 'resnet152 (ImageNet)',
                           'vgg16 (ImageNet)', 'vgg19 (ImageNet)',
                           'resnet56 (Cifar10)', 'resnet110 (Cifar10)',
                           'alexnet (ImageNet, Cifar10)'
                       ],
                       description='CNN model for training. N.B. Models only \
                       support specific data sets, given in brackets. \
                       synthetic_data can only be processed by ImageNet models.',
                       required=False)
    num_gpus = fields.Integer(missing=1,
                              description='Number of GPUs to train on \
                              (one node only). If set to zero, CPU is used.',
                              required=False)
    num_epochs = fields.Float(missing=NUM_EPOCHS,
                              description='Number of epochs to \
                              train on (float value, < 1.0 allowed).',
                              required=False)
    optimizer = fields.Str(missing='sgd',
                           enum=['sgd', 'momentum', 'rmsprop', 'adam'],
                           description='Optimizer to use.',
                           required=False)
    use_fp16 = fields.Boolean(missing=False,
                              enum=[False, True],
                              description='Use 16-bit floats for certain \
                              tensors instead of 32-bit floats. ',
                              required=False)
    weight_decay = fields.Float(missing=4.0e-5,
                                description='Weight decay factor for training',
                                required=False)
    evaluation = fields.Boolean(missing=True,
                                enum=[False, True],
                                description='Perform evaluation after the \
                                benchmark in order to get accuracy results \
                                (only meaningful on real data sets!).',
                                required=False)
    if_cleanup = fields.Boolean(missing=False,
                                enum=[False, True],
                                description='If to delete training and \
                              evaluation directories.',
                                required=False)
Esempio n. 3
0
class TagSchema(Schema):
    id = fields.Integer(required=True)
    code = fields.String(required=True)
    title = fields.String(required=True)
    color = fields.String()
    system = fields.Boolean()
    verbose_title = fields.String()
    is_used_in_revision = fields.Boolean()
    url = fields.String()
class DataDictResource(Resource):
    @api.doc("generate_patient_data_dict")
    @use_args({"as_file": fields.Boolean(missing=False)})
    def get(self, args):
        """Provide Clinic Statistics"""
        patientDataDict_df = dataDictMaker(
            dateFormat="%d-%m-%Y",
            joinArrayBy=", ",
            calculateAgeAsStr=True,
            convertUUID=True,
        )

        if args["as_file"]:
            # create an output stream
            output = BytesIO()

            with pd.ExcelWriter(output, engine="xlsxwriter") as writer:
                patientDataDict_df.to_excel(writer, sheet_name="DataDict")

            output.seek(0)

            return send_file(
                output,
                attachment_filename="data_dict.xlsx",
                as_attachment=True,
            )

        else:
            table_data = {
                "colHeaders": list(patientDataDict_df.columns),
                "data": patientDataDict_df.values.tolist(),
            }

            return table_data, 200
Esempio n. 5
0
class TrainArgsSchema(Schema):
    class Meta:
        unknown = INCLUDE  # supports extra parameters

    train_epochs = fields.Integer(
        required=False,
        missing=10,
        description="Number of training epochs")

    batch_size = fields.Integer(
        missing=16,
        description='Global Batch size',
        required=False)

    num_gpus =  fields.Integer(
        missing=1,
        validate=gpus_must_exist,
        description='Number of GPUs to use, if available (0 = CPU)',
        required=False)
    
    upload_back = fields.Boolean(
        missing=False,
        enum=[False, True],
        description='Either upload a trained graph back to the remote storage (True) or not (False, default)',
        required=False)
Esempio n. 6
0
class OddsList(Resource):

    odds_args = {
        'odds_name': fields.String(),
        'odds_type': fields.String(),
        'sport': fields.String(),
        'per_page': fields.Integer(),
        'page': fields.Integer(),
        'filter_name': fields.String(),
        'active': fields.Boolean(),
    }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._default_response = {
            'status': 'fail',
            'message': 'Invalid payload.',
        }

        self._create_odds_schema = CreateOddsSchema()

    @use_args(odds_args)
    @json_response
    def get(self, query_params):
        return get_odds_by(**query_params), 200

    @json_response
    def post(self):
        req = request.get_json()
        errors = self._create_odds_schema.validate(req)
        if errors:
            return self._default_response, 422
        return create_entity(Odds(**req))
Esempio n. 7
0
class ModelsApiPredict(Resource):
    @doc(description=dedent("""
            Predict document categorization with a previously trained model

            **Parameters**
             - `max_result_categories` : the maximum number of categories in the results
             - `sort` : sort by the score of the most likely class
             - `ml_output` : type of the output in ['decision_function', 'probability'], only affects ML methods.
             - `nn_metric` : The similarity returned by nearest neighbor classifier in ['cosine', 'jaccard', 'cosine_norm', 'jaccard_norm'].
             - `min_score` : filter out results below a similarity threashold
            """))
    @use_args({
        'max_result_categories': wfields.Int(missing=1),
        'sort': wfields.Boolean(missing=False),
        'ml_output': wfields.Str(missing='probability'),
        'nn_metric': wfields.Str(missing='jaccard_norm'),
        'min_score': wfields.Number(missing=-1)
    })
    @marshal_with(CategorizationPredictSchema())
    def get(self, mid, **args):

        sort = args.pop('sort')
        max_result_categories = args.pop('max_result_categories')
        min_score = args.pop("min_score")
        cat = _CategorizerWrapper(self._cache_dir, mid=mid)
        y_res, nn_res = cat.predict(**args)
        res = _CategorizerWrapper.to_dict(
            y_res,
            nn_res,
            cat.le.classes_,
            cat.fe.db.data,
            sort=sort,
            max_result_categories=max_result_categories,
            min_score=min_score)
        return res
Esempio n. 8
0
class ServerInfoApi(Resource):
    @doc(description="Return FreeDiscovery server information "
         " (versions, etc).")
    @marshal_with(
        argmap2schema({
            'version':
            wfields.Nested({'number': wfields.Str()}),
            'env':
            wfields.Nested({'python_version': wfields.Str()}),
            'config':
            wfields.Nested({
                'cache_dir': wfields.Str(),
                'debug': wfields.Boolean(),
                'hostname': wfields.Str(),
                'log_file': wfields.Str(),
                'n_workers': wfields.Int(),
                'port': wfields.Int(),
                'server': wfields.Str()
            })
        }))
    def get(self):
        out = {'version': {}, 'env': {}}

        out['version']['number'] = __version__
        out['env']['python_version'] = sys.version
        out['config'] = self._fd_config
        return out
Esempio n. 9
0
class AdminPayModeConfigView(AdminBaseView):
    """后台-商铺的支付方式设置"""
    @AdminBaseView.permission_required(
        [AdminBaseView.staff_permissions.ADMIN_CONFIG])
    @use_args(
        {
            "key":
            fields.String(
                required=True,
                validate=[validate.OneOf(["weixin_jsapi", "on_delivery"])],
                comment="设置的字段名",
            ),
            "value":
            fields.Boolean(required=True, comment="设置的字段值"),
        },
        location="json")
    def put(self, request, args):
        shop = self.current_shop
        config_info = {args.get("key"): args.get("value")}
        is_wx = "weixin_jsapi" in config_info.keys()
        # 未认证或者未开通线上支付时,还是可以点击关闭货到付款按钮
        if is_wx and shop.cerify_active != ShopVerifyActive.YES:
            return self.send_fail(error_text="已认证的商铺才可申请开通在线支付,您的店铺暂未认证,请前往认证")
        if is_wx and shop.pay_active != ShopPayActive.YES:
            return self.send_fail(error_text="店铺未开通线上支付")
        some_config = update_some_config_by_shop_id(shop.id, config_info)
        # 最少需要保留一种支付方式
        if not some_config.weixin_jsapi and not some_config.on_delivery:
            return self.send_fail(error_text="至少保留一种商城支付方式,否则客户无法支付")
        return self.send_success()
Esempio n. 10
0
class AdminConfigMsgNotifyView(AdminBaseView):
    """后台-设置-消息通知-获取&修改店铺消息通知设置"""
    @AdminBaseView.permission_required(
        [AdminBaseView.staff_permissions.ADMIN_CONFIG])
    def get(self, request):
        shop_id = self.current_shop.id
        msg_notify = get_msg_notify_by_shop_id(shop_id)
        msg_notify = MsgNotifySerializer(msg_notify).data
        return self.send_success(data=msg_notify)

    @AdminBaseView.permission_required(
        [AdminBaseView.staff_permissions.ADMIN_CONFIG])
    @use_args(
        {
            "field":
            fields.String(
                required=True,
                validate=[validate.OneOf(msg_notify_field_list)],
                comment="更改的字段",
            ),
            "value":
            fields.Boolean(required=True, comment="更改的值"),
        },
        location="json")
    def put(self, request, args):
        shop_id = self.current_shop.id
        msg_notify_info = {args.get("field"): args.get("value")}
        update_msg_notify_by_shop_id(shop_id, msg_notify_info)
        return self.send_success()
Esempio n. 11
0
class EventSpanResource(ProtectedResource, GrampsJSONEncoder):
    """Event date span resource."""
    @property
    def db_handle(self) -> DbReadBase:
        """Get the database instance."""
        return get_db_handle()

    @use_args(
        {
            "as_age":
            fields.Boolean(missing=True),
            "locale":
            fields.Str(missing=None, validate=validate.Length(min=1, max=5)),
            "precision":
            fields.Integer(missing=2, validate=validate.Range(min=1, max=3)),
        },
        location="query",
    )
    def get(self, args: Dict, handle1: Handle, handle2: Handle) -> Response:
        """Get the time span between two event dates."""
        try:
            event1 = self.db_handle.get_event_from_handle(handle1)
            event2 = self.db_handle.get_event_from_handle(handle2)
        except HandleError:
            abort(404)

        locale = get_locale_for_language(args["locale"], default=True)
        span = (Span(event1.date,
                     event2.date).format(precision=args["precision"],
                                         as_age=args["as_age"],
                                         dlocale=locale).strip("()"))
        return self.response(200, {"span": str(span)})
Esempio n. 12
0
class AdminDeliveryConfigMethodView(AdminBaseView):
    """后台-订单-开启/关闭配送或者自提"""

    @use_args(
        {
            "home_on": fields.Boolean(comment="配送模式是否开启"),
            "pick_on": fields.Boolean(comment="自提模式是否开启"),
        },
        location="json"
    )
    def put(self, request, args):
        if not args:
            return self.send_fail(error_text="请选择配送设置项目")
        success, msg = update_delivery_config(self.current_shop.id, args)
        if not success:
            return self.send_fail(error_text=msg)
        return self.send_success()
Esempio n. 13
0
class PodcastDetailsSchema(Schema):
    id = fields.Int(required=True)
    name = fields.Str(required=True)
    description = fields.Str(required=True)
    created_at = fields.DateTime(required=True)
    image_url = fields.URL()
    rss_link = fields.URL()
    download_automatically = fields.Boolean(default=True)
    episodes_count = fields.Integer(default=0)
Esempio n. 14
0
class EventInfoSchema(Schema):
    title = fields.String(required=True)
    url = fields.URL(schemes={'http', 'https'}, required=True)
    can_disconnect = fields.Boolean(required=True, default=True)
    service = fields.Nested(
        EventInfoServiceSchema,
        required=True,
        default=SERVICE_INFO,
    )
Esempio n. 15
0
class PatientResource(Resource):
    @api.doc("get_patient")
    @use_args(
        {
            "patient_uuid": fields.UUID(location="view_args"),
            "only_dermographic": fields.Boolean(
                location="querystring", missing=False
            ),
        }
    )
    def get(self, args, **kwargs):
        """Get patient with the UUID"""
        if args["only_dermographic"]:
            patient_schema = PatientSchema(
                many=False, exclude=PatientModel.relationship_keys
            )

        else:
            patient_schema = PatientSchema(many=False)

        patient = PatientModel.query.filter_by(id=args["patient_uuid"]).first()

        return patient_schema.dump(patient), 200

    @api.doc("modify_existing_patient")
    def patch(self, patient_uuid):
        """Modify patient with the UUID"""
        patient_schema = PatientSchema(many=False)

        patient_payload = parser.parse(PatientSchema, request)
        patient_payload = patient_schema.dump(patient_payload)

        patient = PatientModel.query.filter_by(id=patient_uuid).first()

        if patient:
            patient.update(**patient_payload)

            db.session.add(patient)
            db.session.commit()

            return patient_schema.dump(patient), 200

        else:
            abort(404, "Patient not found.")

    @api.doc("delete_existing_patient")
    def delete(self, patient_uuid):
        """Delete patient with the UUID"""
        patient = PatientModel.query.filter_by(id=patient_uuid).first()

        if patient:
            patient.deleted = True

            db.session.add(patient)
            db.session.commit()

        return None, 204
Esempio n. 16
0
class DatasetsApiElement(Resource):

    @use_args({'return_file_path': wfields.Boolean()})
    @marshal_with(DatasetSchema())
    def get(self, name, **args):
        from ..datasets import load_dataset
        res = load_dataset(name, self._cache_dir, verbose=True,
                load_ground_truth=True, verify_checksum=False, **args)
        return res
Esempio n. 17
0
class TrainArgsSchema(Schema):
    class Meta:
        unknown = INCLUDE  # support 'full_paths' parameter
        
    model_name = fields.Str(
        required=True,
        description="Name of the style image e.g. 'name.jpg' in nextcloud. This will also be the name of the model."
    )
    
    upload_model = fields.Boolean(
        required=False,
        missing = 2,
        description="Upload model to nextcloud."
    )
    
    epochs = fields.Int(
        required=False,
        missing = 2,
        description="Number of training epochs."
    )
    
    learning_rate = fields.Float(
        required=False,
        missing = 0.003,
        description="Learning rate."
    )
    
    batch_size = fields.Int(
        required=False,
        missing = 4,
        description="Batch size for training."
    )
    
    content_weight = fields.Float(
        required=False,
        missing = 1e5,
        description="Weight for content-loss."
    )
    
    style_weight = fields.Float(
        required=False,
        missing = 1e10,
        description="Number of iterations on the network to compute the gradients."
    )
    
    size_train_img = fields.Int(
        required=False,
        missing = 256,
        description="Size of training images, default is 256 X 256"
    )
    
    log_interval = fields.Int(
        required=False,
        missing = 200,
        description="Number of images after which the training loss is logged."
    )
Esempio n. 18
0
class ComparisonGetParams(Schema):
    contributions = fields.DelimitedList(fields.String(),
                                         required=True,
                                         validate=validate.Length(min=2))

    response_hash = fields.String()

    save_response = fields.Boolean()

    type = fields.String()
Esempio n. 19
0
    class MyRegisterView(RegisterView):

        post_args = {
            **RegisterView.post_args, 'active': fields.Boolean(required=True)
        }

        @use_kwargs(post_args)
        def post(self, **kwargs):
            """Register a user."""
            return super(MyRegisterView, self).post(**kwargs)
Esempio n. 20
0
class AdminDeliveryConfigPickView(AdminBaseView):
    """后台-订单-自提设置"""

    # 参数校验
    def validate_time(self):
        try:
            datetime.datetime.strptime(self, "%H:%M")
        except Exception:
            return False
        return True

    @use_args(
        {
            "pick_service_amount": fields.Float(required=True, comment="自提模式服务费"),
            "pick_minimum_free_amount": fields.Float(
                required=True, comment="自提模式免服务费最小金额"
            ),
            "pick_today_on": fields.Boolean(required=True, comment="今天自提是否开启"),
            "pick_tomorrow_on": fields.Boolean(required=True, comment="明天自提是否开启"),
            "pick_periods": fields.Nested(
                {
                    "from_time": fields.String(
                        required=True, comment="自提起始时间", validate=validate_time
                    ),
                    "to_time": fields.String(
                        required=True, comment="自提终止时间", validate=validate_time
                    ),
                },
                many=True,
                validate=[validate.Length(1)],
                unknown=True,
                comment="自提时段",
            ),
        },
        location="json"
    )
    def put(self, request, args):
        success, msg = update_delivery_config(
            self.current_shop.id, args, self.current_user.id
        )
        if not success:
            return self.send_fail(error_text=msg)
        return self.send_success()
Esempio n. 21
0
class AdminConfigReceiptBrcodeActiveView(AdminBaseView):
    """后台-设置-小票设置-打印订单号条码"""
    @AdminBaseView.permission_required(
        [AdminBaseView.staff_permissions.ADMIN_CONFIG])
    @use_args(
        {"brcode_active": fields.Boolean(required=True, comment="打印单号条码")},
        location="json")
    def put(self, request, args):
        args["brcode_active"] = int(args.get("brcode_active", 1))
        shop_id = self.current_shop.id
        update_receipt_by_shop_id(shop_id, args)
        return self.send_success()
Esempio n. 22
0
class FilterSchema(Schema):
    """Structure for a filter."""

    function = fields.Str(
        required=False,
        missing="and",
        validate=validate.OneOf(["and", "or", "xor", "one"]),
    )
    invert = fields.Boolean(required=False, missing=False)
    rules = fields.List(fields.Nested(RuleSchema),
                        required=True,
                        validate=validate.Length(min=1))
Esempio n. 23
0
class RelationResource(ProtectedResource, GrampsJSONEncoder):
    """Relation resource."""
    @property
    def db_handle(self) -> DbReadBase:
        """Get the database instance."""
        return get_dbstate().db

    @use_args(
        {
            "depth": fields.Integer(),
            "all": fields.Boolean()
        },
        location="query",
    )
    def get(self, args: Dict, handle1: Handle, handle2: Handle) -> Response:
        """Get the relationship between two people."""
        db_handle = self.db_handle
        person1 = get_person_by_handle(db_handle, handle1)
        if person1 is None:
            abort(404)

        person2 = get_person_by_handle(db_handle, handle2)
        if person2 is None:
            abort(404)

        calc = RelationshipCalculator()
        if "depth" in args:
            calc.set_depth(args["depth"])

        if "all" in args and args["all"]:
            data = calc.get_all_relationships(db_handle, person1, person2)
            index = 0
            result = []
            while index < len(data[0]):
                result.append({
                    "relationship_string": data[0][index],
                    "common_ancestors": data[1][index],
                })
                index = index + 1
            return self.response(200, result)

        data = calc.get_one_relationship(db_handle,
                                         person1,
                                         person2,
                                         extra_info=True)
        return self.response(
            200,
            {
                "relationship_string": data[0],
                "distance_common_origin": data[1],
                "distance_common_other": data[2],
            },
        )
Esempio n. 24
0
class EventInfoSchema(Schema):
    title = fields.String(required=True)
    url = fields.URL(schemes={"http", "https"}, required=True)
    can_disconnect = fields.Boolean(required=True, default=True)
    service = fields.Nested(
        {
            "version": fields.String(),
            "name": fields.String()
        },
        required=True,
        default=SERVICE_INFO,
    )
Esempio n. 25
0
class UserConfigAutoArchiveController(Resource):
    put_body = {"auto_archive": fields.Boolean(data_key="autoArchive", required=True)}

    @jwt.requires_auth
    @use_args(put_body, location="json")
    def put(self, put_args):
        """Update user config option for gmail_auto_archive"""
        do_auto_archive = put_args["auto_archive"]
        user_config = user_manager.set_auto_archive_config(g.user, do_auto_archive)
        user_manager.commit_changes()
        if user_config:
            return responses.success(user_config.to_json())
        return responses.error("Something went wrong")
Esempio n. 26
0
def search_args():
    """Defines and validates params for index"""
    return {
        "search": fields.String(missing=None),
        "team_id": fields.UUID(missing=None),
        "types": fields.String(load_from="type", missing="image"),
        "pipeline": fields.Integer(),
        "start_date": fields.DateTime(),
        "end_date": fields.DateTime(),
        "offset": fields.Integer(missing=0),
        "limit": fields.Integer(missing=12),
        "notify_clients": fields.Boolean(missing=False),
    }
Esempio n. 27
0
    def build_schema(self, model):

        # Get the full list of parent classes from model to object
        classes = inspect.getmro(model)

        starting_point = False
        # Iterate in reversed order to start from object
        for c in reversed(classes):
            # Skip all parentes up to StructuredNode and StructuredRel (included)
            if not starting_point:
                # Found the starting point, next class will be descended up to model
                if c == StructuredNode or c == StructuredRel:
                    starting_point = True
                # skip all parent up to StructuredNode and StructuredRel INCLUDED
                continue

            # Iterate all class attributes to find neomodel properties
            for attribute in c.__dict__:
                prop = getattr(c, attribute)

                if not isinstance(prop, properties.Property):
                    continue

                # self.fields can be None when the special value * is given in input
                if self.fields and attribute not in self.fields:
                    continue

                # log.info("Including property {}.{}", model.__name__, attribute)
                if isinstance(prop, properties.StringProperty):
                    if prop.choices is None:
                        self.declared_fields[attribute] = fields.Str()
                    else:
                        self.declared_fields[attribute] = Neo4jChoice(
                            prop.choices)

                elif isinstance(prop, properties.BooleanProperty):
                    self.declared_fields[attribute] = fields.Boolean()
                elif isinstance(prop, properties.IntegerProperty):
                    self.declared_fields[attribute] = fields.Integer()
                elif isinstance(prop, properties.EmailProperty):
                    self.declared_fields[attribute] = fields.Email()
                elif isinstance(prop, properties.DateTimeProperty):
                    self.declared_fields[attribute] = fields.AwareDateTime()
                elif isinstance(prop, properties.UniqueIdProperty):
                    self.declared_fields[attribute] = fields.Str()
                else:  # pragma: no cover
                    log.error(
                        "Unsupport neomodel property: {}, fallback to StringProperty",
                        prop.__class__.__name__,
                    )
                    self.declared_fields[attribute] = fields.Str()
Esempio n. 28
0
class DefaultTypeResource(ProtectedResource, GrampsJSONEncoder):
    """Default type resource."""
    @use_args(
        {
            "locale": fields.Boolean(missing=False),
        },
        location="query",
    )
    def get(self, args: Dict, datatype: str) -> Response:
        """Return a list of values for a default type."""
        result = get_default_types(datatype, args["locale"])
        if result is None:
            abort(404)
        return self.response(200, result)
Esempio n. 29
0
class TachographGenerationScopeSchema(Schema):
    company_ids = fields.List(fields.Int(),
                              required=True,
                              validate=lambda l: len(l) > 0)
    user_ids = fields.List(fields.Int(), required=False)
    min_date = fields.Date(required=True)
    max_date = fields.Date(required=True)
    with_digital_signatures = fields.Boolean(required=False)

    @validates_schema
    def check_period_is_small_enough(self, data, **kwargs):
        if data["max_date"] - data["min_date"] > timedelta(days=60):
            raise ValidationError(
                "The requested period should be less than 60 days")
Esempio n. 30
0
class DefaultTypesResource(ProtectedResource, GrampsJSONEncoder):
    """Default types resource."""
    @use_args(
        {
            "locale": fields.Boolean(missing=False),
        },
        location="query",
    )
    def get(self, args: Dict) -> Response:
        """Return a list of available default types."""
        result = {}
        for datatype in _DEFAULT_RECORD_TYPES:
            result.update(
                {datatype: get_default_types(datatype, args["locale"])})
        return self.response(200, result)