variables.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import json
  2. from collections.abc import Mapping, Sequence
  3. from pydantic import Field
  4. from core.file.file_obj import FileVar
  5. from core.helper import encrypter
  6. from .segments import NoneSegment, Segment, StringSegment
  7. from .types import SegmentType
  8. class Variable(Segment):
  9. """
  10. A variable is a segment that has a name.
  11. """
  12. id: str = Field(
  13. default='',
  14. description="Unique identity for variable. It's only used by environment variables now.",
  15. )
  16. name: str
  17. description: str = Field(default='', description='Description of the variable.')
  18. class StringVariable(StringSegment, Variable):
  19. pass
  20. class FloatVariable(Variable):
  21. value_type: SegmentType = SegmentType.NUMBER
  22. value: float
  23. class IntegerVariable(Variable):
  24. value_type: SegmentType = SegmentType.NUMBER
  25. value: int
  26. class ObjectVariable(Variable):
  27. value_type: SegmentType = SegmentType.OBJECT
  28. value: Mapping[str, Variable]
  29. @property
  30. def text(self) -> str:
  31. # TODO: Process variables.
  32. return json.dumps(self.model_dump()['value'], ensure_ascii=False)
  33. @property
  34. def log(self) -> str:
  35. # TODO: Process variables.
  36. return json.dumps(self.model_dump()['value'], ensure_ascii=False, indent=2)
  37. @property
  38. def markdown(self) -> str:
  39. # TODO: Use markdown code block
  40. return json.dumps(self.model_dump()['value'], ensure_ascii=False, indent=2)
  41. class ArrayVariable(Variable):
  42. value_type: SegmentType = SegmentType.ARRAY
  43. value: Sequence[Variable]
  44. @property
  45. def markdown(self) -> str:
  46. return '\n'.join(['- ' + item.markdown for item in self.value])
  47. class FileVariable(Variable):
  48. value_type: SegmentType = SegmentType.FILE
  49. # TODO: embed FileVar in this model.
  50. value: FileVar
  51. @property
  52. def markdown(self) -> str:
  53. return self.value.to_markdown()
  54. class SecretVariable(StringVariable):
  55. value_type: SegmentType = SegmentType.SECRET
  56. @property
  57. def log(self) -> str:
  58. return encrypter.obfuscated_token(self.value)
  59. class NoneVariable(NoneSegment, Variable):
  60. value_type: SegmentType = SegmentType.NONE
  61. value: None = None