file_service.py 6.2 KB

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