file_service.py 6.3 KB

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