file_service.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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 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.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(file: FileStorage, user: Union[Account, EndUser]) -> UploadFile:
  27. # get file name
  28. filename = file.filename
  29. if not filename:
  30. raise FileNotExistsError
  31. extension = filename.split(".")[-1]
  32. if len(filename) > 200:
  33. filename = filename.split(".")[0][:200] + "." + extension
  34. # read file content
  35. file_content = file.read()
  36. # get file size
  37. file_size = len(file_content)
  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. # check if the file size is exceeded
  48. if file_size > file_size_limit:
  49. message = f"File size exceeded. {file_size} > {file_size_limit}"
  50. raise FileTooLargeError(message)
  51. # generate file key
  52. file_uuid = str(uuid.uuid4())
  53. if isinstance(user, Account):
  54. current_tenant_id = user.current_tenant_id
  55. else:
  56. # end_user
  57. current_tenant_id = user.tenant_id
  58. file_key = "upload_files/" + current_tenant_id + "/" + file_uuid + "." + extension
  59. # save file to storage
  60. storage.save(file_key, file_content)
  61. # save file to db
  62. upload_file = UploadFile(
  63. tenant_id=current_tenant_id,
  64. storage_type=dify_config.STORAGE_TYPE,
  65. key=file_key,
  66. name=filename,
  67. size=file_size,
  68. extension=extension,
  69. mime_type=file.mimetype,
  70. created_by_role=("account" if isinstance(user, Account) else "end_user"),
  71. created_by=user.id,
  72. created_at=datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None),
  73. used=False,
  74. hash=hashlib.sha3_256(file_content).hexdigest(),
  75. )
  76. db.session.add(upload_file)
  77. db.session.commit()
  78. return upload_file
  79. @staticmethod
  80. def upload_text(text: str, text_name: str) -> UploadFile:
  81. if len(text_name) > 200:
  82. text_name = text_name[:200]
  83. # user uuid as file name
  84. file_uuid = str(uuid.uuid4())
  85. file_key = "upload_files/" + current_user.current_tenant_id + "/" + file_uuid + ".txt"
  86. # save file to storage
  87. storage.save(file_key, text.encode("utf-8"))
  88. # save file to db
  89. upload_file = UploadFile(
  90. tenant_id=current_user.current_tenant_id,
  91. storage_type=dify_config.STORAGE_TYPE,
  92. key=file_key,
  93. name=text_name,
  94. size=len(text),
  95. extension="txt",
  96. mime_type="text/plain",
  97. created_by=current_user.id,
  98. created_at=datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None),
  99. used=True,
  100. used_by=current_user.id,
  101. used_at=datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None),
  102. )
  103. db.session.add(upload_file)
  104. db.session.commit()
  105. return upload_file
  106. @staticmethod
  107. def get_file_preview(file_id: str) -> str:
  108. upload_file = db.session.query(UploadFile).filter(UploadFile.id == file_id).first()
  109. if not upload_file:
  110. raise NotFound("File not found")
  111. # extract text from file
  112. extension = upload_file.extension
  113. if extension.lower() not in DOCUMENT_EXTENSIONS:
  114. raise UnsupportedFileTypeError()
  115. text = ExtractProcessor.load_from_upload_file(upload_file, return_text=True)
  116. text = text[0:PREVIEW_WORDS_LIMIT] if text else ""
  117. return text
  118. @staticmethod
  119. def get_image_preview(file_id: str, timestamp: str, nonce: str, sign: str):
  120. result = file_helpers.verify_image_signature(
  121. upload_file_id=file_id, timestamp=timestamp, nonce=nonce, sign=sign
  122. )
  123. if not result:
  124. raise NotFound("File not found or signature is invalid")
  125. upload_file = db.session.query(UploadFile).filter(UploadFile.id == file_id).first()
  126. if not upload_file:
  127. raise NotFound("File not found or signature is invalid")
  128. # extract text from file
  129. extension = upload_file.extension
  130. if extension.lower() not in IMAGE_EXTENSIONS:
  131. raise UnsupportedFileTypeError()
  132. generator = storage.load(upload_file.key, stream=True)
  133. return generator, upload_file.mime_type
  134. @staticmethod
  135. def get_signed_file_preview(file_id: str, timestamp: str, nonce: str, sign: str):
  136. result = file_helpers.verify_file_signature(upload_file_id=file_id, timestamp=timestamp, nonce=nonce, sign=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. generator = storage.load(upload_file.key, stream=True)
  143. return generator, upload_file.mime_type
  144. @staticmethod
  145. def get_public_image_preview(file_id: str) -> tuple[Generator, str]:
  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. # extract text from file
  150. extension = upload_file.extension
  151. if extension.lower() not in IMAGE_EXTENSIONS:
  152. raise UnsupportedFileTypeError()
  153. generator = storage.load(upload_file.key)
  154. return generator, upload_file.mime_type