file_manager.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. import base64
  2. from configs import dify_config
  3. from core.file import file_repository
  4. from core.helper import ssrf_proxy
  5. from core.model_runtime.entities import AudioPromptMessageContent, ImagePromptMessageContent
  6. from extensions.ext_database import db
  7. from extensions.ext_storage import storage
  8. from . import helpers
  9. from .enums import FileAttribute
  10. from .models import File, FileTransferMethod, FileType
  11. from .tool_file_parser import ToolFileParser
  12. def get_attr(*, file: File, attr: FileAttribute):
  13. match attr:
  14. case FileAttribute.TYPE:
  15. return file.type.value
  16. case FileAttribute.SIZE:
  17. return file.size
  18. case FileAttribute.NAME:
  19. return file.filename
  20. case FileAttribute.MIME_TYPE:
  21. return file.mime_type
  22. case FileAttribute.TRANSFER_METHOD:
  23. return file.transfer_method.value
  24. case FileAttribute.URL:
  25. return file.remote_url
  26. case FileAttribute.EXTENSION:
  27. return file.extension
  28. case _:
  29. raise ValueError(f"Invalid file attribute: {attr}")
  30. def to_prompt_message_content(f: File, /):
  31. """
  32. Convert a File object to an ImagePromptMessageContent object.
  33. This function takes a File object and converts it to an ImagePromptMessageContent
  34. object, which can be used as a prompt for image-based AI models.
  35. Args:
  36. file (File): The File object to convert. Must be of type FileType.IMAGE.
  37. Returns:
  38. ImagePromptMessageContent: An object containing the image data and detail level.
  39. Raises:
  40. ValueError: If the file is not an image or if the file data is missing.
  41. Note:
  42. The detail level of the image prompt is determined by the file's extra_config.
  43. If not specified, it defaults to ImagePromptMessageContent.DETAIL.LOW.
  44. """
  45. match f.type:
  46. case FileType.IMAGE:
  47. if dify_config.MULTIMODAL_SEND_IMAGE_FORMAT == "url":
  48. data = _to_url(f)
  49. else:
  50. data = _to_base64_data_string(f)
  51. if f._extra_config and f._extra_config.image_config and f._extra_config.image_config.detail:
  52. detail = f._extra_config.image_config.detail
  53. else:
  54. detail = ImagePromptMessageContent.DETAIL.LOW
  55. return ImagePromptMessageContent(data=data, detail=detail)
  56. case FileType.AUDIO:
  57. encoded_string = _file_to_encoded_string(f)
  58. if f.extension is None:
  59. raise ValueError("Missing file extension")
  60. return AudioPromptMessageContent(data=encoded_string, format=f.extension.lstrip("."))
  61. case _:
  62. raise ValueError(f"file type {f.type} is not supported")
  63. def download(f: File, /):
  64. upload_file = file_repository.get_upload_file(session=db.session(), file=f)
  65. return _download_file_content(upload_file.key)
  66. def _download_file_content(path: str, /):
  67. """
  68. Download and return the contents of a file as bytes.
  69. This function loads the file from storage and ensures it's in bytes format.
  70. Args:
  71. path (str): The path to the file in storage.
  72. Returns:
  73. bytes: The contents of the file as a bytes object.
  74. Raises:
  75. ValueError: If the loaded file is not a bytes object.
  76. """
  77. data = storage.load(path, stream=False)
  78. if not isinstance(data, bytes):
  79. raise ValueError(f"file {path} is not a bytes object")
  80. return data
  81. def _get_encoded_string(f: File, /):
  82. match f.transfer_method:
  83. case FileTransferMethod.REMOTE_URL:
  84. response = ssrf_proxy.get(f.remote_url)
  85. response.raise_for_status()
  86. content = response.content
  87. encoded_string = base64.b64encode(content).decode("utf-8")
  88. return encoded_string
  89. case FileTransferMethod.LOCAL_FILE:
  90. upload_file = file_repository.get_upload_file(session=db.session(), file=f)
  91. data = _download_file_content(upload_file.key)
  92. encoded_string = base64.b64encode(data).decode("utf-8")
  93. return encoded_string
  94. case FileTransferMethod.TOOL_FILE:
  95. tool_file = file_repository.get_tool_file(session=db.session(), file=f)
  96. data = _download_file_content(tool_file.file_key)
  97. encoded_string = base64.b64encode(data).decode("utf-8")
  98. return encoded_string
  99. case _:
  100. raise ValueError(f"Unsupported transfer method: {f.transfer_method}")
  101. def _to_base64_data_string(f: File, /):
  102. encoded_string = _get_encoded_string(f)
  103. return f"data:{f.mime_type};base64,{encoded_string}"
  104. def _file_to_encoded_string(f: File, /):
  105. match f.type:
  106. case FileType.IMAGE:
  107. return _to_base64_data_string(f)
  108. case FileType.AUDIO:
  109. return _get_encoded_string(f)
  110. case _:
  111. raise ValueError(f"file type {f.type} is not supported")
  112. def _to_url(f: File, /):
  113. if f.transfer_method == FileTransferMethod.REMOTE_URL:
  114. if f.remote_url is None:
  115. raise ValueError("Missing file remote_url")
  116. return f.remote_url
  117. elif f.transfer_method == FileTransferMethod.LOCAL_FILE:
  118. if f.related_id is None:
  119. raise ValueError("Missing file related_id")
  120. return helpers.get_signed_file_url(upload_file_id=f.related_id)
  121. elif f.transfer_method == FileTransferMethod.TOOL_FILE:
  122. # add sign url
  123. if f.related_id is None or f.extension is None:
  124. raise ValueError("Missing file related_id or extension")
  125. return ToolFileParser.get_tool_file_manager().sign_file(tool_file_id=f.related_id, extension=f.extension)
  126. else:
  127. raise ValueError(f"Unsupported transfer method: {f.transfer_method}")