file_service.py 6.5 KB

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