file_service.py 6.3 KB

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