variables.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. def to_object(self):
  42. return {k: v.to_object() for k, v in self.value.items()}
  43. class ArrayVariable(Variable):
  44. value_type: SegmentType = SegmentType.ARRAY
  45. value: Sequence[Variable]
  46. @property
  47. def markdown(self) -> str:
  48. return '\n'.join(['- ' + item.markdown for item in self.value])
  49. def to_object(self):
  50. return [v.to_object() for v in self.value]
  51. class FileVariable(Variable):
  52. value_type: SegmentType = SegmentType.FILE
  53. # TODO: embed FileVar in this model.
  54. value: FileVar
  55. @property
  56. def markdown(self) -> str:
  57. return self.value.to_markdown()
  58. class SecretVariable(StringVariable):
  59. value_type: SegmentType = SegmentType.SECRET
  60. @property
  61. def log(self) -> str:
  62. return encrypter.obfuscated_token(self.value)
  63. class NoneVariable(NoneSegment, Variable):
  64. value_type: SegmentType = SegmentType.NONE
  65. value: None = None