file_service.py 6.7 KB

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