Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

file_service.py 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. import datetime
  2. import hashlib
  3. import os
  4. import uuid
  5. from typing import Any, Literal, Union
  6. from flask_login import current_user
  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 CreatorUserRole
  21. from models.model import EndUser, UploadFile
  22. from .errors.file import FileTooLargeError, UnsupportedFileTypeError
  23. PREVIEW_WORDS_LIMIT = 3000
  24. class FileService:
  25. @staticmethod
  26. def upload_file(
  27. *,
  28. filename: str,
  29. content: bytes,
  30. mimetype: str,
  31. user: Union[Account, EndUser, Any],
  32. source: Literal["datasets"] | None = None,
  33. source_url: str = "",
  34. ) -> UploadFile:
  35. # get file extension
  36. extension = os.path.splitext(filename)[1].lstrip(".").lower()
  37. # check if filename contains invalid characters
  38. if any(c in filename for c in ["/", "\\", ":", "*", "?", '"', "<", ">", "|"]):
  39. raise ValueError("Filename contains invalid characters")
  40. if len(filename) > 200:
  41. filename = filename.split(".")[0][:200] + "." + extension
  42. if source == "datasets" and extension not in DOCUMENT_EXTENSIONS:
  43. raise UnsupportedFileTypeError()
  44. # get file size
  45. file_size = len(content)
  46. # check if the file size is exceeded
  47. if not FileService.is_file_size_within_limit(extension=extension, file_size=file_size):
  48. raise FileTooLargeError
  49. # generate file key
  50. file_uuid = str(uuid.uuid4())
  51. if isinstance(user, Account):
  52. current_tenant_id = user.current_tenant_id
  53. else:
  54. # end_user
  55. current_tenant_id = user.tenant_id
  56. file_key = "upload_files/" + (current_tenant_id or "") + "/" + file_uuid + "." + extension
  57. # save file to storage
  58. storage.save(file_key, content)
  59. # save file to db
  60. upload_file = UploadFile(
  61. tenant_id=current_tenant_id or "",
  62. storage_type=dify_config.STORAGE_TYPE,
  63. key=file_key,
  64. name=filename,
  65. size=file_size,
  66. extension=extension,
  67. mime_type=mimetype,
  68. created_by_role=(CreatorUserRole.ACCOUNT if isinstance(user, Account) else CreatorUserRole.END_USER),
  69. created_by=user.id,
  70. created_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  71. used=False,
  72. hash=hashlib.sha3_256(content).hexdigest(),
  73. source_url=source_url,
  74. )
  75. db.session.add(upload_file)
  76. db.session.commit()
  77. if not upload_file.source_url:
  78. upload_file.source_url = file_helpers.get_signed_file_url(upload_file_id=upload_file.id)
  79. db.session.add(upload_file)
  80. db.session.commit()
  81. return upload_file
  82. @staticmethod
  83. def is_file_size_within_limit(*, extension: str, file_size: int) -> bool:
  84. if extension in IMAGE_EXTENSIONS:
  85. file_size_limit = dify_config.UPLOAD_IMAGE_FILE_SIZE_LIMIT * 1024 * 1024
  86. elif extension in VIDEO_EXTENSIONS:
  87. file_size_limit = dify_config.UPLOAD_VIDEO_FILE_SIZE_LIMIT * 1024 * 1024
  88. elif extension in AUDIO_EXTENSIONS:
  89. file_size_limit = dify_config.UPLOAD_AUDIO_FILE_SIZE_LIMIT * 1024 * 1024
  90. else:
  91. file_size_limit = dify_config.UPLOAD_FILE_SIZE_LIMIT * 1024 * 1024
  92. return file_size <= file_size_limit
  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_by_role=CreatorUserRole.ACCOUNT,
  113. created_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  114. used=True,
  115. used_by=current_user.id,
  116. used_at=datetime.datetime.now(datetime.UTC).replace(tzinfo=None),
  117. )
  118. db.session.add(upload_file)
  119. db.session.commit()
  120. return upload_file
  121. @staticmethod
  122. def get_file_preview(file_id: str):
  123. upload_file = db.session.query(UploadFile).filter(UploadFile.id == file_id).first()
  124. if not upload_file:
  125. raise NotFound("File not found")
  126. # extract text from file
  127. extension = upload_file.extension
  128. if extension.lower() not in DOCUMENT_EXTENSIONS:
  129. raise UnsupportedFileTypeError()
  130. text = ExtractProcessor.load_from_upload_file(upload_file, return_text=True)
  131. text = text[0:PREVIEW_WORDS_LIMIT] if text else ""
  132. return text
  133. @staticmethod
  134. def get_image_preview(file_id: str, timestamp: str, nonce: str, sign: str):
  135. result = file_helpers.verify_image_signature(
  136. upload_file_id=file_id, timestamp=timestamp, nonce=nonce, sign=sign
  137. )
  138. if not result:
  139. raise NotFound("File not found or signature is invalid")
  140. upload_file = db.session.query(UploadFile).filter(UploadFile.id == file_id).first()
  141. if not upload_file:
  142. raise NotFound("File not found or signature is invalid")
  143. # extract text from file
  144. extension = upload_file.extension
  145. if extension.lower() not in IMAGE_EXTENSIONS:
  146. raise UnsupportedFileTypeError()
  147. generator = storage.load(upload_file.key, stream=True)
  148. return generator, upload_file.mime_type
  149. @staticmethod
  150. def get_file_generator_by_file_id(file_id: str, timestamp: str, nonce: str, sign: str):
  151. result = file_helpers.verify_file_signature(upload_file_id=file_id, timestamp=timestamp, nonce=nonce, sign=sign)
  152. if not result:
  153. raise NotFound("File not found or signature is invalid")
  154. upload_file = db.session.query(UploadFile).filter(UploadFile.id == file_id).first()
  155. if not upload_file:
  156. raise NotFound("File not found or signature is invalid")
  157. generator = storage.load(upload_file.key, stream=True)
  158. return generator, upload_file
  159. @staticmethod
  160. def get_public_image_preview(file_id: str):
  161. upload_file = db.session.query(UploadFile).filter(UploadFile.id == file_id).first()
  162. if not upload_file:
  163. raise NotFound("File not found or signature is invalid")
  164. # extract text from file
  165. extension = upload_file.extension
  166. if extension.lower() not in IMAGE_EXTENSIONS:
  167. raise UnsupportedFileTypeError()
  168. generator = storage.load(upload_file.key)
  169. return generator, upload_file.mime_type