file_service.py 6.8 KB

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