added integration tests and repository pattern for image, model and visual communication DTOs
Code Quality Pipeline / Check Code (pull_request) Failing after 3m21s
Code Quality Pipeline / Check Code (pull_request) Failing after 3m21s
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
from .hexadecimal_string import HexadecimalString
|
||||
from .image_data import ImageData
|
||||
from .model_data import ModelData
|
||||
from .visual_communication_data import (
|
||||
VisualCommunicationData,
|
||||
VisualCommunicationValues,
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Definition of BytesIO Pydantic Annotation."""
|
||||
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from pydantic.json_schema import JsonSchemaValue
|
||||
from pydantic_core import core_schema
|
||||
|
||||
|
||||
class BytesIOPydanticAnnotation:
|
||||
"""Pydantic annotation that defines input validation, as well as general
|
||||
and json serialization."""
|
||||
|
||||
@classmethod
|
||||
def validate_input(cls, v: Any, handler) -> BytesIO:
|
||||
"""Pydantic-related function to validate input on instantiation."""
|
||||
if isinstance(v, BytesIO):
|
||||
return v
|
||||
s = handler(v)
|
||||
return BytesIO(s)
|
||||
|
||||
@classmethod
|
||||
def __get_pydantic_core_schema__(
|
||||
cls,
|
||||
source_type,
|
||||
_handler,
|
||||
) -> core_schema.CoreSchema:
|
||||
assert source_type is BytesIO
|
||||
return core_schema.no_info_wrap_validator_function(
|
||||
function=cls.validate_input,
|
||||
schema=core_schema.str_schema(),
|
||||
serialization=core_schema.to_string_ser_schema(),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def __get_pydantic_json_schema__(cls, _core_schema, handler) -> JsonSchemaValue:
|
||||
return handler(core_schema.str_schema())
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Definition of Checksum DTO."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
|
||||
class HexadecimalString(str):
|
||||
"""Hexadecimal-string class."""
|
||||
|
||||
def __new__(cls, string):
|
||||
# ensure proper input format
|
||||
pattern = r'[0-9-a-fA-F]{32}'
|
||||
match = re.match(pattern, string)
|
||||
if match is None:
|
||||
raise ValueError(f'format does not match a hexadecimal-string: {string}')
|
||||
return super().__new__(cls, string)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
class_name = self.__class__.__name__
|
||||
return f"{class_name}('{self}')"
|
||||
|
||||
def __reduce__(self):
|
||||
return self.__class__, (self,)
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Definition of HexadecimalString Pydantic Annotation."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from pydantic.json_schema import JsonSchemaValue
|
||||
from pydantic_core import core_schema
|
||||
|
||||
from .hexadecimal_string import HexadecimalString
|
||||
|
||||
|
||||
class HexadecimalStringPydanticAnnotation:
|
||||
"""Pydantic annotation that defines input validation, as well as general
|
||||
and json serialization."""
|
||||
|
||||
@classmethod
|
||||
def validate_input(cls, v: Any, handler) -> HexadecimalString:
|
||||
"""Pydantic-related function to validate input on instantiation."""
|
||||
if isinstance(v, HexadecimalString):
|
||||
return v
|
||||
s = handler(v)
|
||||
return HexadecimalString(s)
|
||||
|
||||
@classmethod
|
||||
def __get_pydantic_core_schema__(
|
||||
cls,
|
||||
source_type,
|
||||
_handler,
|
||||
) -> core_schema.CoreSchema:
|
||||
assert source_type is HexadecimalString
|
||||
return core_schema.no_info_wrap_validator_function(
|
||||
function=cls.validate_input,
|
||||
schema=core_schema.str_schema(),
|
||||
serialization=core_schema.to_string_ser_schema(),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def __get_pydantic_json_schema__(cls, _core_schema, handler) -> JsonSchemaValue:
|
||||
return handler(core_schema.str_schema())
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Definition of VisualData DTO."""
|
||||
|
||||
from typing import Annotated
|
||||
|
||||
from PIL import Image
|
||||
from pydantic import Field
|
||||
|
||||
from .image_pydantic_annotation import ImagePydanticAnnotation
|
||||
from .type_checking_base_model import TypeCheckingBaseModel
|
||||
|
||||
|
||||
class ImageData(TypeCheckingBaseModel):
|
||||
"""Visual data class."""
|
||||
|
||||
image: Annotated[Image.Image, ImagePydanticAnnotation]
|
||||
name: str = Field(min_length=1)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Definition of BytesIO Pydantic Annotation."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from PIL import Image
|
||||
from pydantic.json_schema import JsonSchemaValue
|
||||
from pydantic_core import core_schema
|
||||
|
||||
|
||||
class ImagePydanticAnnotation:
|
||||
"""Pydantic annotation that defines input validation, as well as general
|
||||
and json serialization."""
|
||||
|
||||
@classmethod
|
||||
def validate_input(cls, v: Any, handler) -> Image.Image:
|
||||
"""Pydantic-related function to validate input on instantiation."""
|
||||
if isinstance(v, Image.Image):
|
||||
return v
|
||||
s = handler(v)
|
||||
return Image.open(s)
|
||||
|
||||
@classmethod
|
||||
def __get_pydantic_core_schema__(
|
||||
cls,
|
||||
source_type,
|
||||
_handler,
|
||||
) -> core_schema.CoreSchema:
|
||||
assert source_type is Image.Image
|
||||
return core_schema.no_info_wrap_validator_function(
|
||||
function=cls.validate_input,
|
||||
schema=core_schema.str_schema(),
|
||||
serialization=core_schema.to_string_ser_schema(),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def __get_pydantic_json_schema__(cls, _core_schema, handler) -> JsonSchemaValue:
|
||||
return handler(core_schema.str_schema())
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Definition of ModelData DTO."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from hashlib import md5
|
||||
from io import BytesIO
|
||||
from typing import Annotated
|
||||
|
||||
import torch
|
||||
from pydantic import Field
|
||||
|
||||
from .bytes_io_pydantic_annotation import BytesIOPydanticAnnotation
|
||||
from .hexadecimal_string import HexadecimalString
|
||||
from .hexadecimal_string_pydantic_annotation import HexadecimalStringPydanticAnnotation
|
||||
from .type_checking_base_model import TypeCheckingBaseModel
|
||||
|
||||
|
||||
class ModelData(TypeCheckingBaseModel):
|
||||
"""Model Data DTO."""
|
||||
|
||||
buffer: Annotated[BytesIO, BytesIOPydanticAnnotation]
|
||||
buffer_checksum: Annotated[HexadecimalString, HexadecimalStringPydanticAnnotation]
|
||||
class_name: str = Field(
|
||||
min_length=1,
|
||||
description='name of model class to generate data.',
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def calculate_checksum(buffer: BytesIO) -> HexadecimalString:
|
||||
"""Calculate buffer checksum."""
|
||||
checksum = md5(buffer.getbuffer()).hexdigest()
|
||||
return HexadecimalString(checksum)
|
||||
|
||||
@staticmethod
|
||||
def model_to_buffer(model: torch.nn.Module) -> BytesIO:
|
||||
"""Save model to buffer."""
|
||||
assert isinstance(model, torch.nn.Module)
|
||||
buffer = BytesIO()
|
||||
torch.save(model.state_dict(), buffer)
|
||||
return buffer
|
||||
|
||||
@classmethod
|
||||
def from_model(cls, model: torch.nn.Module) -> ModelData:
|
||||
"""Instantiate from torch module."""
|
||||
assert isinstance(model, torch.nn.Module)
|
||||
# get model name
|
||||
class_name = type(model).__name__
|
||||
# save data to buffer
|
||||
buffer = cls.model_to_buffer(model)
|
||||
buffer = BytesIO()
|
||||
torch.save(model.state_dict(), buffer)
|
||||
# calculate checksum
|
||||
buffer_checksum = cls.calculate_checksum(buffer)
|
||||
# instantiate from buffer
|
||||
data = cls(
|
||||
buffer=buffer,
|
||||
buffer_checksum=buffer_checksum,
|
||||
class_name=class_name,
|
||||
)
|
||||
return data
|
||||
@@ -0,0 +1,12 @@
|
||||
"""Definition of TypeCheckingBaseModel class."""
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
|
||||
class TypeCheckingBaseModel(BaseModel):
|
||||
"""BaseModel with added type checking on input types."""
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_assignment=True, # argument type checking
|
||||
frozen=True, # ensure data immutability
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
from .visual_communication_data import VisualCommunicationData
|
||||
from .visual_communication_values import VisualCommunicationValues
|
||||
@@ -0,0 +1,11 @@
|
||||
"""Definition of AngleValues DTO."""
|
||||
|
||||
from .values_model import ValuesModel
|
||||
|
||||
|
||||
class AngleValues(ValuesModel):
|
||||
"""Angle values DTO."""
|
||||
|
||||
high: float
|
||||
eye_level: float
|
||||
low: float
|
||||
@@ -0,0 +1,10 @@
|
||||
"""Definition of ContactValues DTO."""
|
||||
|
||||
from .values_model import ValuesModel
|
||||
|
||||
|
||||
class ContactValues(ValuesModel):
|
||||
"""Contact values DTO."""
|
||||
|
||||
offer: float
|
||||
demand: float
|
||||
@@ -0,0 +1,11 @@
|
||||
"""Definition of DistanceValues DTO."""
|
||||
|
||||
from .values_model import ValuesModel
|
||||
|
||||
|
||||
class DistanceValues(ValuesModel):
|
||||
"""Distance values DTO."""
|
||||
|
||||
long: float
|
||||
medium: float
|
||||
close: float
|
||||
@@ -0,0 +1,12 @@
|
||||
"""Definition of FramingValues DTO."""
|
||||
|
||||
from .values_model import ValuesModel
|
||||
|
||||
|
||||
class FramingValues(ValuesModel):
|
||||
"""Framing values DTO."""
|
||||
|
||||
frame_lines: float
|
||||
empty_space: float
|
||||
colour_contrast: float
|
||||
form_contrast: float
|
||||
@@ -0,0 +1,11 @@
|
||||
"""Definition of InformationValueValues DTO."""
|
||||
|
||||
from .values_model import ValuesModel
|
||||
|
||||
|
||||
class InformationValueValues(ValuesModel):
|
||||
"""Information value values DTO."""
|
||||
|
||||
given_new: float
|
||||
ideal_real: float
|
||||
central_marginal: float
|
||||
@@ -0,0 +1,11 @@
|
||||
"""Definition of ModalityColorValues DTO."""
|
||||
|
||||
from .values_model import ValuesModel
|
||||
|
||||
|
||||
class ModalityColorValues(ValuesModel):
|
||||
"""Modality color values DTO."""
|
||||
|
||||
high: float
|
||||
medium: float
|
||||
low: float
|
||||
@@ -0,0 +1,11 @@
|
||||
"""Definition of ModalityDepthValues DTO."""
|
||||
|
||||
from .values_model import ValuesModel
|
||||
|
||||
|
||||
class ModalityDepthValues(ValuesModel):
|
||||
"""Modality depth values DTO."""
|
||||
|
||||
high: float
|
||||
medium: float
|
||||
low: float
|
||||
@@ -0,0 +1,11 @@
|
||||
"""Definition of ModalityLightingValues DTO."""
|
||||
|
||||
from .values_model import ValuesModel
|
||||
|
||||
|
||||
class ModalityLightingValues(ValuesModel):
|
||||
"""Modality lighting values DTO."""
|
||||
|
||||
high: float
|
||||
medium: float
|
||||
low: float
|
||||
@@ -0,0 +1,10 @@
|
||||
"""Definition of PointOfViewValues DTO."""
|
||||
|
||||
from .values_model import ValuesModel
|
||||
|
||||
|
||||
class PointOfViewValues(ValuesModel):
|
||||
"""Point-of-view values DTO."""
|
||||
|
||||
frontal: float
|
||||
oblique: float
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Definition of SalienceValues DTO."""
|
||||
|
||||
from .values_model import ValuesModel
|
||||
|
||||
|
||||
class SalienceValues(ValuesModel):
|
||||
"""Salience values DTO."""
|
||||
|
||||
size: float
|
||||
colour: float
|
||||
tone: float
|
||||
form: float
|
||||
positioning: float
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Definition of ValuesModel base class."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
class ValuesModel(BaseModel):
|
||||
"""ValuesModel base class."""
|
||||
|
||||
model_config = ConfigDict(
|
||||
validate_assignment=True, # argument type checking
|
||||
frozen=True, # ensure data immutability
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def list_fields(cls) -> list[str]:
|
||||
"""List options that are stored as attributes."""
|
||||
return list(cls.model_fields.keys())
|
||||
|
||||
@classmethod
|
||||
def from_random(cls):
|
||||
"""Instantiate with random numbers."""
|
||||
kwargs = {field: random.random() for field in cls.list_fields()}
|
||||
return cls(**kwargs)
|
||||
|
||||
@classmethod
|
||||
def from_choice(cls, option: str) -> ValuesModel:
|
||||
"""Instantiate from choice."""
|
||||
assert isinstance(option, str)
|
||||
assert len(option) > 0
|
||||
allowed_options_list = cls.list_fields()
|
||||
if option not in allowed_options_list:
|
||||
raise ValueError(f'option {option} must be in {allowed_options_list}')
|
||||
# generate field values
|
||||
kwargs = {field: 0 for field in allowed_options_list}
|
||||
# set chosen value to max probability
|
||||
kwargs[option] = 1
|
||||
return cls(**kwargs)
|
||||
|
||||
@classmethod
|
||||
def from_tensor(cls, tensor: Tensor):
|
||||
"""Instantiate from list of values."""
|
||||
assert tensor.size(dim=0) == 1, f'tensor batch larger than 1: {tensor}'
|
||||
data_list = [float(t.item()) for t in tensor[0]]
|
||||
kwargs = dict(zip(cls.list_fields(), data_list))
|
||||
return cls(**kwargs)
|
||||
|
||||
def highest_score_field(self) -> str:
|
||||
"""Return name of field with highest score."""
|
||||
model_dict = self.model_dump()
|
||||
return max(model_dict, key=lambda k: model_dict[k])
|
||||
|
||||
def highest_score_value(self) -> float:
|
||||
"""Return value of field with highest score."""
|
||||
model_dict = self.model_dump()
|
||||
return max(model_dict.values())
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Definition of VisualCommunicationData DTO."""
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from ..type_checking_base_model import TypeCheckingBaseModel
|
||||
from .visual_communication_values import VisualCommunicationValues
|
||||
|
||||
|
||||
class VisualCommunicationData(TypeCheckingBaseModel):
|
||||
"""Visual communication data class."""
|
||||
|
||||
name: str = Field(min_length=1)
|
||||
annotation: VisualCommunicationValues | None = None
|
||||
prediction: VisualCommunicationValues | None = None
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Definition of VisualCommunicationValues DTO."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from ..type_checking_base_model import TypeCheckingBaseModel
|
||||
from .angle_values import AngleValues
|
||||
from .contact_values import ContactValues
|
||||
from .distance_values import DistanceValues
|
||||
from .framing_values import FramingValues
|
||||
from .information_value_values import InformationValueValues
|
||||
from .modality_color_values import ModalityColorValues
|
||||
from .modality_depth_values import ModalityDepthValues
|
||||
from .modality_lighting_values import ModalityLightingValues
|
||||
from .point_of_view_values import PointOfViewValues
|
||||
from .salience_values import SalienceValues
|
||||
from .visual_syntax_values import VisualSyntaxValues
|
||||
|
||||
|
||||
class VisualCommunicationValues(TypeCheckingBaseModel):
|
||||
"""Visual communication values class."""
|
||||
|
||||
visual_syntax: VisualSyntaxValues
|
||||
contact: ContactValues
|
||||
angle: AngleValues
|
||||
point_of_view: PointOfViewValues
|
||||
distance: DistanceValues
|
||||
modality_lighting: ModalityLightingValues
|
||||
modality_color: ModalityColorValues
|
||||
modality_depth: ModalityDepthValues
|
||||
information_value: InformationValueValues
|
||||
framing: FramingValues
|
||||
salience: SalienceValues
|
||||
|
||||
@classmethod
|
||||
def from_random(cls) -> VisualCommunicationValues:
|
||||
"""Create a random instance."""
|
||||
return cls(
|
||||
visual_syntax=VisualSyntaxValues.from_random(),
|
||||
contact=ContactValues.from_random(),
|
||||
angle=AngleValues.from_random(),
|
||||
point_of_view=PointOfViewValues.from_random(),
|
||||
distance=DistanceValues.from_random(),
|
||||
modality_lighting=ModalityLightingValues.from_random(),
|
||||
modality_color=ModalityColorValues.from_random(),
|
||||
modality_depth=ModalityDepthValues.from_random(),
|
||||
information_value=InformationValueValues.from_random(),
|
||||
framing=FramingValues.from_random(),
|
||||
salience=SalienceValues.from_random(),
|
||||
)
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Definition of VisualSyntaxValues DTO."""
|
||||
|
||||
from .values_model import ValuesModel
|
||||
|
||||
|
||||
class VisualSyntaxValues(ValuesModel):
|
||||
"""Visual syntax values DTO."""
|
||||
|
||||
non_transactional_action: float
|
||||
non_transactional_reaction: float
|
||||
unidirectional_transactional_action: float
|
||||
unidirectional_transactional_reaction: float
|
||||
bidirectional_transactional_action: float
|
||||
bidirectional_transactional_reaction: float
|
||||
conversion: float
|
||||
speech_process: float
|
||||
classification_overt_taxonomy: float
|
||||
analytical_exhaustive: float
|
||||
analytical_disarranged: float
|
||||
analytical_temporal: float
|
||||
analytical_distributed: float
|
||||
analytical_topological: float
|
||||
analytical_exploded: float
|
||||
analytical_inclusive: float
|
||||
symbolic_suggestive: float
|
||||
symbolic_attributive: float
|
||||
Reference in New Issue
Block a user