file_service.py 6.1 KB

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