from rest_framework import serializers from fwd_api.constant.common import TEMPLATE_BOX_TYPE, FolderFileType from fwd_api.models.OcrTemplate import OcrTemplate from fwd_api.models.OcrTemplateBox import OcrTemplateBox from fwd_api.utils import file as FileUtils class TemplateBoxResponse(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(required=False) coordinates = serializers.SerializerMethodField() def get_coordinates(self, obj: OcrTemplateBox): if not obj.coordinates: return [] list_box = obj.coordinates.split(",") return list_box class TemplateResponse(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(required=False) data_boxs = serializers.SerializerMethodField() anchor_boxs = serializers.SerializerMethodField() file_url = serializers.SerializerMethodField() def get_file_url(self, obj: OcrTemplate): return FileUtils.build_url(FolderFileType.TEMPLATES.value, str(obj.id), obj.subscription.user.id) def get_data_boxs(self, obj: OcrTemplate): data = OcrTemplateBox.objects.filter(template=obj, type=TEMPLATE_BOX_TYPE.DATA.value) if len(data) == 0: return [] return TemplateBoxResponse(data, many=True).data def get_anchor_boxs(self, obj: OcrTemplate): data = OcrTemplateBox.objects.filter(template=obj, type=TEMPLATE_BOX_TYPE.ANCHOR.value) if len(data) == 0: return [] return TemplateBoxResponse(data, many=True).data