class DoubleSummarySchema(ma.ModelSchema): class Meta: fields = ('date', 'opponent1', 'opponent2', 'partner', 'match_won') model = DoubleMatch # exclude = ('w1', 'w2', 'l1', 'l2') partner = ma.Method('get_partner') opponent1 = ma.Method('get_opponent1') opponent2 = ma.Method('get_opponent2') match_won = ma.Method('get_matchwon') def get_matchwon(self, match): pid = int(self.context['player_id']) mp = { match.winner1_id: True, match.winner2_id: True, match.loser1_id: False, match.loser2_id: False, } return mp[pid] def get_partner(self, match): pid = int(self.context['player_id']) mp = { match.winner1_id: match.winner2_id, match.winner2_id: match.winner1_id, match.loser1_id: match.loser2_id, match.loser2_id: match.loser1_id, } return Player.query.get_or_404(mp[pid]).name def get_opponent1(self, match): pid = int(self.context['player_id']) mp = { match.winner1_id: match.loser1_id, match.winner2_id: match.loser2_id, match.loser1_id: match.winner1_id, match.loser2_id: match.winner2_id, } return Player.query.get_or_404(mp[pid]).name def get_opponent2(self, match): pid = int(self.context['player_id']) mp = { match.winner1_id: match.loser2_id, match.winner2_id: match.loser1_id, match.loser1_id: match.winner2_id, match.loser2_id: match.winner1_id, } return Player.query.get_or_404(mp[pid]).name
class ModelSchema(ma.Schema): class Meta: model = Model fields = ( "id", "user", "project_id", "name", "visibility", "dataset", "hyperparameters", "parameters", "metrics", "tags", "git", "created", "updated", "_links", ) ordered = True visibility = ma.Function(lambda obj: "private" if obj.private else "public") dataset = ma.Method("get_dataset_details") git = ma.Method("get_version_control_details") user = ma.Nested(UserSchema(exclude=("created", "updated", "email"))) tags = ma.Nested(TagSchema(exclude=("models", )), many=True) _links = ma.Hyperlinks({ "self": ma.URLFor("api.model", id="<id>", _external=True), "user": ma.URLFor("api.user", id="<user_id>", _external=True), "project": ma.URLFor("api.project", id="<project_id>", _external=True), "download": ma.URLFor("storage.download_model", id="<id>", _external=True), }) def get_dataset_details(self, obj): return { "name": obj.dataset_name, "description": obj.dataset_description } def get_version_control_details(self, obj): return { "active_branch": obj.git_active_branch, "commit_hash": obj.git_commit_hash, }
class UserSchema(ma.Schema): picture = ma.Method("get_picture_for_user") def get_picture_for_user(self, obj: User): return "https://www.gravatar.com/avatar/" + hashlib.md5( obj.email.lower().encode()).hexdigest() + "?d=mm" class Meta: fields = ('id', 'username', "picture")
class ImageSchema(ma.SQLAlchemySchema): class Meta: model = ImageModel() url = ma.Method(serialize='get_uri', deserialize='get_uri') filename = ma.auto_field() id = ma.auto_field() def get_uri(self, obj): return current_app.config["IMAGES_URL"] + obj.filename
class SingleSummarySchema(ma.ModelSchema): class Meta: fields = ('date', 'opponent', 'match_won') model = SingleMatch w = ma.Function( lambda match: Player.query.get_or_404(match.winner_id).name) l = ma.Function(lambda match: Player.query.get_or_404(match.loser_id).name) opponent = ma.Method('get_opponent') match_won = ma.Method('get_matchwon') def get_opponent(self, match): pid = int(self.context['player_id']) mp = {match.winner_id: match.l, match.loser_id: match.w} return mp[pid] def get_matchwon(self, match): pid = int(self.context['player_id']) mp = {match.winner_id: True, match.loser_id: False} return mp[pid]
class CommentSchema(ma.SQLAlchemySchema): class Meta: model = CommentModel id = ma.auto_field() content = ma.auto_field() wrote_datetime = ma.Method("get_abbreviated_datetime_as_string") upper_comment_id = ma.auto_field() writer = ma.Method("get_writer_with_check_anonymous") is_anonymous = ma.auto_field() wrote_post = ma.Nested("PostSchema", only=["id"]) is_mine = ma.Method("is_users") def get_abbreviated_datetime_as_string(self, obj): def _get_abbreviated_datetime_as_string(dt): if not isinstance(dt, datetime): raise AttributeError() diff_from_now = datetime.now() - dt if diff_from_now.days >= 1: return f"{dt.year:04d}.{dt.month:02d}.{dt.day:02d}." else: return f"{dt.hour:02d}:{dt.minute:02d}" return _get_abbreviated_datetime_as_string(obj.wrote_datetime) def get_writer_with_check_anonymous(self, obj): if obj.is_anonymous: return {"username": "******", "profile_image": None} else: from app.api.v1.user.model import UserSchema return UserSchema(only=["username", "profile_image"]).dump( obj.writer) def is_users(self, obj): return obj.uploader.email == get_jwt_identity()
class UserSchema(ma.SQLAlchemySchema): class Meta: model = UserModel() username = ma.auto_field() explain = ma.auto_field() # profile_image = ma.Nested("ImageSchema", only=["url", "filename"]) profile_image = ma.Method(serialize="get_profile_image") email = ma.auto_field() def get_profile_image(self, obj): image = obj.profile_image return None if image is None else image.id
class AnalysisSchema(ma.ModelSchema): class Meta: model = Analysis current_asset = ma.Float(required=True) current_liability = ma.Float(required=True) total_assets = ma.Float(required=True) third_party_liability = ma.Float(required=True) financial_obligations = ma.Float(required=True) net_sales = ma.Float(required=True) gross_utility = ma.Float(required=True) net_utility = ma.Float(required=True) status = EnumField(AnalysisStatus) entity_id = ma.Integer(required=True) # calculated fields current_ratio = ma.Method('get_current_ratio') net_work_capital = ma.Method('get_net_work_capital') gross_margin = ma.Method('get_gross_margin') net_margin = ma.Method('get_net_margin') debt_level = ma.Method('get_debt_level') financial_debt = ma.Method('get_financial_debt') def get_current_ratio(self, obj): current_ratio = obj.current_asset / obj.current_liability return round(current_ratio * 0.25, 2) def get_net_work_capital(self, obj): net_work_capital = obj.current_asset - obj.current_liability return round(net_work_capital, 2) def get_gross_margin(self, obj): gross_margin = obj.gross_utility / obj.net_sales return round(gross_margin * 0.25, 2) def get_net_margin(self, obj): net_margin = obj.net_utility / obj.net_sales return round(net_margin * 0.10, 2) def get_debt_level(self, obj): debt_level = obj.third_party_liability / obj.total_assets return round(debt_level * 0.30, 2) def get_financial_debt(self, obj): financial_debt = obj.financial_obligations / obj.net_sales return round(financial_debt * 0.10, 2)
class PostSchema(ma.SQLAlchemySchema): class Meta: model = PostModel images = ma.Method(serialize="get_image_ids", deserialize="get_image_ids") id = ma.auto_field() uploader = ma.Method("get_writer_with_check_anonymous") content = ma.auto_field() title = ma.auto_field() views = ma.auto_field() posted_datetime = ma.Method(serialize="get_abbreviated_datetime_as_string") is_anonymous = ma.auto_field() number_of_likes = ma.Method(serialize="get_number_of_postlikes") number_of_dislikes = ma.Method(serialize="get_number_of_postdislikes") posted_gallery = ma.Nested("GallerySchema") number_of_comments = ma.Method(serialize="get_number_of_comments") whether_exist_image = ma.Method(serialize="get_whether_image_exist") my_reaction = ma.Method(serialize="get_user_reaction") is_mine = ma.Method(serialize="is_users") def get_abbreviated_datetime_as_string(self, obj): def _get_abbreviated_datetime_as_string(dt): if not isinstance(dt, datetime): raise AttributeError() diff_from_now = datetime.now() - dt if diff_from_now.days >= 1: return f"{dt.year:04d}.{dt.month:02d}.{dt.day:02d}." else: return f"{dt.hour:02d}:{dt.minute:02d}" return _get_abbreviated_datetime_as_string(obj.posted_datetime) def get_writer_with_check_anonymous(self, obj): if obj.is_anonymous: return {"username": "******", "profile_image": None} else: from app.api.v1.user.model import UserSchema return UserSchema(only=["username", "profile_image"]).dump( obj.uploader) def get_image_ids(self, obj): list = [] for image in obj.images: list.append(image.id) return list def get_number_of_postlikes(self, obj): return len(obj.likes) def get_number_of_postdislikes(self, obj): return len(obj.dislikes) def get_number_of_comments(self, obj): return len(obj.comments) def get_whether_image_exist(self, obj): if not obj.images: return False else: return True def get_user_reaction(self, obj): user_id = get_jwt_identity() for like in obj.likes: if like.liker_id == user_id: return 'like' for dislike in obj.dislikes: if dislike.liker_id == user_id: return 'dislike' return 'none' def is_users(self, obj): return obj.uploader_id == get_jwt_identity()
class ProjectSchema(ma.Schema): # models = ma.Nested('ModelSchema', many=True) class Meta: model = Project fields = ( "id", "workspace_id", "name", "description", "all_hyperparameters", "all_parameters", "all_metrics", "all_users", "git_url", "updated", "created", "_links", ) ordered = True _links = ma.Hyperlinks({ "self": ma.URLFor("api.project", id="<id>", _external=True), "workspace": ma.URLFor("api.workspace", id="<workspace_id>", _external=True), }) all_hyperparameters = ma.Method("get_all_hyperparameters") all_parameters = ma.Method("get_all_parameters") all_metrics = ma.Method("get_all_metrics") all_users = ma.Method("get_all_users") def get_all_hyperparameters(self, obj): query = f"SELECT jsonb_object_keys(hyperparameters) from models WHERE project_id = {obj.id};" keys = db.engine.execute(query) output = [] for key in keys: output.append(key[0]) return output def get_all_parameters(self, obj): query = f"SELECT jsonb_object_keys(parameters) from models WHERE project_id = {obj.id};" keys = db.engine.execute(query) output = [] for key in keys: output.append(key[0]) return output def get_all_metrics(self, obj): query = f"SELECT jsonb_object_keys(metrics) from models WHERE project_id = {obj.id};" keys = db.engine.execute(query) output = [] for key in keys: output.append(key[0]) return output def get_all_users(self, obj): models = Model.query.filter_by(project_id=obj.id).distinct( Model.user_id) output = [] for model in models: output.append({ "id": model.user.id, "full_name": model.user.full_name }) return output