file_service.py 6.9 KB

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