file_service.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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:
  53. raise UnsupportedFileTypeError()
  54. elif only_image and extension.lower() not in IMAGE_EXTENSIONS:
  55. raise UnsupportedFileTypeError()
  56. # read file content
  57. file_content = file.read()
  58. # get file size
  59. file_size = len(file_content)
  60. if extension.lower() in IMAGE_EXTENSIONS:
  61. file_size_limit = dify_config.UPLOAD_IMAGE_FILE_SIZE_LIMIT * 1024 * 1024
  62. else:
  63. file_size_limit = dify_config.UPLOAD_FILE_SIZE_LIMIT * 1024 * 1024
  64. if file_size > file_size_limit:
  65. message = f"File size exceeded. {file_size} > {file_size_limit}"
  66. raise FileTooLargeError(message)
  67. # user uuid as file name
  68. file_uuid = str(uuid.uuid4())
  69. if isinstance(user, Account):
  70. current_tenant_id = user.current_tenant_id
  71. else:
  72. # end_user
  73. current_tenant_id = user.tenant_id
  74. file_key = "upload_files/" + current_tenant_id + "/" + file_uuid + "." + extension
  75. # save file to storage
  76. storage.save(file_key, file_content)
  77. # save file to db
  78. upload_file = UploadFile(
  79. tenant_id=current_tenant_id,
  80. storage_type=dify_config.STORAGE_TYPE,
  81. key=file_key,
  82. name=filename,
  83. size=file_size,
  84. extension=extension,
  85. mime_type=file.mimetype,
  86. created_by_role=("account" if isinstance(user, Account) else "end_user"),
  87. created_by=user.id,
  88. created_at=datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None),
  89. used=False,
  90. hash=hashlib.sha3_256(file_content).hexdigest(),
  91. )
  92. db.session.add(upload_file)
  93. db.session.commit()
  94. return upload_file
  95. @staticmethod
  96. def upload_text(text: str, text_name: str) -> UploadFile:
  97. if len(text_name) > 200:
  98. text_name = text_name[:200]
  99. # user uuid as file name
  100. file_uuid = str(uuid.uuid4())
  101. file_key = "upload_files/" + current_user.current_tenant_id + "/" + file_uuid + ".txt"
  102. # save file to storage
  103. storage.save(file_key, text.encode("utf-8"))
  104. # save file to db
  105. upload_file = UploadFile(
  106. tenant_id=current_user.current_tenant_id,
  107. storage_type=dify_config.STORAGE_TYPE,
  108. key=file_key,
  109. name=text_name,
  110. size=len(text),
  111. extension="txt",
  112. mime_type="text/plain",
  113. created_by=current_user.id,
  114. created_at=datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None),
  115. used=True,
  116. used_by=current_user.id,
  117. used_at=datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None),
  118. )
  119. db.session.add(upload_file)
  120. db.session.commit()
  121. return upload_file
  122. @staticmethod
  123. def get_file_preview(file_id: str) -> str:
  124. upload_file = db.session.query(UploadFile).filter(UploadFile.id == file_id).first()
  125. if not upload_file:
  126. raise NotFound("File not found")
  127. # extract text from file
  128. extension = upload_file.extension
  129. etl_type = dify_config.ETL_TYPE
  130. allowed_extensions = UNSTRUCTURED_ALLOWED_EXTENSIONS if etl_type == "Unstructured" else ALLOWED_EXTENSIONS
  131. if extension.lower() not in allowed_extensions:
  132. raise UnsupportedFileTypeError()
  133. text = ExtractProcessor.load_from_upload_file(upload_file, return_text=True)
  134. text = text[0:PREVIEW_WORDS_LIMIT] if text else ""
  135. return text
  136. @staticmethod
  137. def get_image_preview(file_id: str, timestamp: str, nonce: str, sign: str) -> tuple[Generator, str]:
  138. result = UploadFileParser.verify_image_file_signature(file_id, timestamp, nonce, sign)
  139. if not result:
  140. raise NotFound("File not found or signature is invalid")
  141. upload_file = db.session.query(UploadFile).filter(UploadFile.id == file_id).first()
  142. if not upload_file:
  143. raise NotFound("File not found or signature is invalid")
  144. # extract text from file
  145. extension = upload_file.extension
  146. if extension.lower() not in IMAGE_EXTENSIONS:
  147. raise UnsupportedFileTypeError()
  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