file_service.py 6.9 KB

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