file_manager.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. if f.transfer_method == FileTransferMethod.TOOL_FILE:
  65. tool_file = file_repository.get_tool_file(session=db.session(), file=f)
  66. return _download_file_content(tool_file.file_key)
  67. elif f.transfer_method == FileTransferMethod.LOCAL_FILE:
  68. upload_file = file_repository.get_upload_file(session=db.session(), file=f)
  69. return _download_file_content(upload_file.key)
  70. # remote file
  71. response = ssrf_proxy.get(f.remote_url, follow_redirects=True)
  72. response.raise_for_status()
  73. return response.content
  74. def _download_file_content(path: str, /):
  75. """
  76. Download and return the contents of a file as bytes.
  77. This function loads the file from storage and ensures it's in bytes format.
  78. Args:
  79. path (str): The path to the file in storage.
  80. Returns:
  81. bytes: The contents of the file as a bytes object.
  82. Raises:
  83. ValueError: If the loaded file is not a bytes object.
  84. """
  85. data = storage.load(path, stream=False)
  86. if not isinstance(data, bytes):
  87. raise ValueError(f"file {path} is not a bytes object")
  88. return data
  89. def _get_encoded_string(f: File, /):
  90. match f.transfer_method:
  91. case FileTransferMethod.REMOTE_URL:
  92. response = ssrf_proxy.get(f.remote_url)
  93. response.raise_for_status()
  94. content = response.content
  95. encoded_string = base64.b64encode(content).decode("utf-8")
  96. return encoded_string
  97. case FileTransferMethod.LOCAL_FILE:
  98. upload_file = file_repository.get_upload_file(session=db.session(), file=f)
  99. data = _download_file_content(upload_file.key)
  100. encoded_string = base64.b64encode(data).decode("utf-8")
  101. return encoded_string
  102. case FileTransferMethod.TOOL_FILE:
  103. tool_file = file_repository.get_tool_file(session=db.session(), file=f)
  104. data = _download_file_content(tool_file.file_key)
  105. encoded_string = base64.b64encode(data).decode("utf-8")
  106. return encoded_string
  107. case _:
  108. raise ValueError(f"Unsupported transfer method: {f.transfer_method}")
  109. def _to_base64_data_string(f: File, /):
  110. encoded_string = _get_encoded_string(f)
  111. return f"data:{f.mime_type};base64,{encoded_string}"
  112. def _file_to_encoded_string(f: File, /):
  113. match f.type:
  114. case FileType.IMAGE:
  115. return _to_base64_data_string(f)
  116. case FileType.AUDIO:
  117. return _get_encoded_string(f)
  118. case _:
  119. raise ValueError(f"file type {f.type} is not supported")
  120. def _to_url(f: File, /):
  121. if f.transfer_method == FileTransferMethod.REMOTE_URL:
  122. if f.remote_url is None:
  123. raise ValueError("Missing file remote_url")
  124. return f.remote_url
  125. elif f.transfer_method == FileTransferMethod.LOCAL_FILE:
  126. if f.related_id is None:
  127. raise ValueError("Missing file related_id")
  128. return helpers.get_signed_file_url(upload_file_id=f.related_id)
  129. elif f.transfer_method == FileTransferMethod.TOOL_FILE:
  130. # add sign url
  131. if f.related_id is None or f.extension is None:
  132. raise ValueError("Missing file related_id or extension")
  133. return ToolFileParser.get_tool_file_manager().sign_file(tool_file_id=f.related_id, extension=f.extension)
  134. else:
  135. raise ValueError(f"Unsupported transfer method: {f.transfer_method}")