file_service.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import datetime
  2. import hashlib
  3. import uuid
  4. from typing import Any, Literal, Union
  5. from flask_login import current_user # type: ignore
  6. from werkzeug.exceptions import NotFound
  7. from configs import dify_config
  8. from constants import (
  9. AUDIO_EXTENSIONS,
  10. DOCUMENT_EXTENSIONS,
  11. IMAGE_EXTENSIONS,
  12. VIDEO_EXTENSIONS,
  13. )
  14. from core.file import helpers as file_helpers
  15. from core.rag.extractor.extract_processor import ExtractProcessor
  16. from extensions.ext_database import db
  17. from extensions.ext_storage import storage
  18. from models.account import Account
  19. from models.enums import CreatedByRole
  20. from models.model import EndUser, UploadFile
  21. from .errors.file import FileTooLargeError, UnsupportedFileTypeError
  22. PREVIEW_WORDS_LIMIT = 3000
  23. class FileService:
  24. @staticmethod
  25. def upload_file(
  26. *,
  27. filename: str,
  28. content: bytes,
  29. mimetype: str,
  30. user: Union[Account, EndUser, Any],
  31. source: Literal["datasets"] | None = None,
  32. source_url: str = "",
  33. ) -> UploadFile:
  34. # get file extension
  35. extension = filename.split(".")[-1].lower()
  36. if len(filename) > 200:
  37. filename = filename.split(".")[0][:200] + "." + extension
  38. if source == "datasets" and extension not in DOCUMENT_EXTENSIONS:
  39. raise UnsupportedFileTypeError()
  40. # get file size
  41. file_size = len(content)
  42. # check if the file size is exceeded
  43. if not FileService.is_file_size_within_limit(extension=extension, file_size=file_size):
  44. raise FileTooLargeError
  45. # generate file key
  46. file_uuid = str(uuid.uuid4())
  47. if isinstance(user, Account):
  48. current_tenant_id = user.current_tenant_id
  49. else:
  50. # end_user
  51. current_tenant_id = user.tenant_id
  52. file_key = "upload_files/" + (current_tenant_id or "") + "/" + file_uuid + "." + extension
  53. # save file to storage
  54. storage.save(file_key, content)
  55. # save file to db
  56. upload_file = UploadFile(
  57. tenant_id=current_tenant_id or "",
  58. storage_type=dify_config.STORAGE_TYPE,
  59. key=file_key,
  60. name=filename,
  61. size=file_size,
  62. extension=extension,
  63. mime_type=mimetype,
  64. created_by_role=(CreatedByRole.ACCOUNT if isinstance(user, Account) else CreatedByRole.END_USER),
  65. created_by=user.id,
  66. created_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  67. used=False,
  68. hash=hashlib.sha3_256(content).hexdigest(),
  69. source_url=source_url,
  70. )
  71. db.session.add(upload_file)
  72. db.session.commit()
  73. return upload_file
  74. @staticmethod
  75. def is_file_size_within_limit(*, extension: str, file_size: int) -> bool:
  76. if extension in IMAGE_EXTENSIONS:
  77. file_size_limit = dify_config.UPLOAD_IMAGE_FILE_SIZE_LIMIT * 1024 * 1024
  78. elif extension in VIDEO_EXTENSIONS:
  79. file_size_limit = dify_config.UPLOAD_VIDEO_FILE_SIZE_LIMIT * 1024 * 1024
  80. elif extension in AUDIO_EXTENSIONS:
  81. file_size_limit = dify_config.UPLOAD_AUDIO_FILE_SIZE_LIMIT * 1024 * 1024
  82. else:
  83. file_size_limit = dify_config.UPLOAD_FILE_SIZE_LIMIT * 1024 * 1024
  84. return file_size <= file_size_limit
  85. @staticmethod
  86. def upload_text(text: str, text_name: str) -> UploadFile:
  87. if len(text_name) > 200:
  88. text_name = text_name[:200]
  89. # user uuid as file name
  90. file_uuid = str(uuid.uuid4())
  91. file_key = "upload_files/" + current_user.current_tenant_id + "/" + file_uuid + ".txt"
  92. # save file to storage
  93. storage.save(file_key, text.encode("utf-8"))
  94. # save file to db
  95. upload_file = UploadFile(
  96. tenant_id=current_user.current_tenant_id,
  97. storage_type=dify_config.STORAGE_TYPE,
  98. key=file_key,
  99. name=text_name,
  100. size=len(text),
  101. extension="txt",
  102. mime_type="text/plain",
  103. created_by=current_user.id,
  104. created_by_role=CreatedByRole.ACCOUNT,
  105. created_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  106. used=True,
  107. used_by=current_user.id,
  108. used_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  109. )
  110. db.session.add(upload_file)
  111. db.session.commit()
  112. return upload_file
  113. @staticmethod
  114. def get_file_preview(file_id: str):
  115. upload_file = db.session.query(UploadFile).filter(UploadFile.id == file_id).first()
  116. if not upload_file:
  117. raise NotFound("File not found")
  118. # extract text from file
  119. extension = upload_file.extension
  120. if extension.lower() not in DOCUMENT_EXTENSIONS:
  121. raise UnsupportedFileTypeError()
  122. text = ExtractProcessor.load_from_upload_file(upload_file, return_text=True)
  123. text = text[0:PREVIEW_WORDS_LIMIT] if text else ""
  124. return text
  125. @staticmethod
  126. def get_image_preview(file_id: str, timestamp: str, nonce: str, sign: str):
  127. result = file_helpers.verify_image_signature(
  128. upload_file_id=file_id, timestamp=timestamp, nonce=nonce, sign=sign
  129. )
  130. if not result:
  131. raise NotFound("File not found or signature is invalid")
  132. upload_file = db.session.query(UploadFile).filter(UploadFile.id == file_id).first()
  133. if not upload_file:
  134. raise NotFound("File not found or signature is invalid")
  135. # extract text from file
  136. extension = upload_file.extension
  137. if extension.lower() not in IMAGE_EXTENSIONS:
  138. raise UnsupportedFileTypeError()
  139. generator = storage.load(upload_file.key, stream=True)
  140. return generator, upload_file.mime_type
  141. @staticmethod
  142. def get_file_generator_by_file_id(file_id: str, timestamp: str, nonce: str, sign: str):
  143. result = file_helpers.verify_file_signature(upload_file_id=file_id, timestamp=timestamp, nonce=nonce, sign=sign)
  144. if not result:
  145. raise NotFound("File not found or signature is invalid")
  146. upload_file = db.session.query(UploadFile).filter(UploadFile.id == file_id).first()
  147. if not upload_file:
  148. raise NotFound("File not found or signature is invalid")
  149. generator = storage.load(upload_file.key, stream=True)
  150. return generator, upload_file
  151. @staticmethod
  152. def get_public_image_preview(file_id: str):
  153. upload_file = db.session.query(UploadFile).filter(UploadFile.id == file_id).first()
  154. if not upload_file:
  155. raise NotFound("File not found or signature is invalid")
  156. # extract text from file
  157. extension = upload_file.extension
  158. if extension.lower() not in IMAGE_EXTENSIONS:
  159. raise UnsupportedFileTypeError()
  160. generator = storage.load(upload_file.key)
  161. return generator, upload_file.mime_type