You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.6 KiB

2 years ago
2 years ago
2 years ago
  1. import abc
  2. from typing import Any, Dict
  3. from pydantic import UUID4, BaseModel, validator
  4. from examples.models import Example
  5. from projects.models import Project
  6. class BaseData(BaseModel, abc.ABC):
  7. filename: str
  8. upload_name: str
  9. uuid: UUID4
  10. meta: Dict[Any, Any] = {}
  11. def __init__(self, **data):
  12. super().__init__(**data)
  13. @classmethod
  14. def parse(cls, example_uuid: UUID4, filename: str, upload_name: str, text: str = "", **kwargs):
  15. return cls(uuid=example_uuid, filename=filename, upload_name=upload_name, text=text, meta=kwargs)
  16. def __hash__(self):
  17. return hash(tuple(self.dict()))
  18. @abc.abstractmethod
  19. def create(self, project: Project) -> Example:
  20. raise NotImplementedError("Please implement this method in the subclass.")
  21. class TextData(BaseData):
  22. text: str
  23. @validator("text")
  24. def text_is_not_empty(cls, value: str):
  25. if value:
  26. return value
  27. else:
  28. raise ValueError("The empty text is not allowed.")
  29. def create(self, project: Project) -> Example:
  30. return Example(
  31. uuid=self.uuid,
  32. project=project,
  33. filename=self.filename,
  34. upload_name=self.upload_name,
  35. text=self.text,
  36. meta=self.meta,
  37. )
  38. class BinaryData(BaseData):
  39. def create(self, project: Project) -> Example:
  40. return Example(
  41. uuid=self.uuid,
  42. project=project,
  43. filename=self.filename,
  44. upload_name=self.upload_name,
  45. text=None,
  46. meta=self.meta,
  47. )