file_service.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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', 'docx', 'csv']
  20. UNSTRUSTURED_ALLOWED_EXTENSIONS = ['txt', 'markdown', 'md', 'pdf', 'html', 'htm', 'xlsx',
  21. 'docx', 'csv', 'eml', 'msg', 'pptx', 'ppt', 'xml']
  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 + IMAGE_EXTENSIONS if etl_type == 'Unstructured' \
  29. else ALLOWED_EXTENSIONS + IMAGE_EXTENSIONS
  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. etl_type = current_app.config['ETL_TYPE']
  110. allowed_extensions = UNSTRUSTURED_ALLOWED_EXTENSIONS if etl_type == 'Unstructured' else ALLOWED_EXTENSIONS
  111. if extension.lower() not in allowed_extensions:
  112. raise UnsupportedFileTypeError()
  113. text = ExtractProcessor.load_from_upload_file(upload_file, return_text=True)
  114. text = text[0:PREVIEW_WORDS_LIMIT] if text else ''
  115. return text
  116. @staticmethod
  117. def get_image_preview(file_id: str, timestamp: str, nonce: str, sign: str) -> tuple[Generator, str]:
  118. result = UploadFileParser.verify_image_file_signature(file_id, timestamp, nonce, sign)
  119. if not result:
  120. raise NotFound("File not found or signature is invalid")
  121. upload_file = db.session.query(UploadFile) \
  122. .filter(UploadFile.id == file_id) \
  123. .first()
  124. if not upload_file:
  125. raise NotFound("File not found or signature is invalid")
  126. # extract text from file
  127. extension = upload_file.extension
  128. if extension.lower() not in IMAGE_EXTENSIONS:
  129. raise UnsupportedFileTypeError()
  130. generator = storage.load(upload_file.key, stream=True)
  131. return generator, upload_file.mime_type
  132. @staticmethod
  133. def get_public_image_preview(file_id: str) -> tuple[Generator, str]:
  134. upload_file = db.session.query(UploadFile) \
  135. .filter(UploadFile.id == file_id) \
  136. .first()
  137. if not upload_file:
  138. raise NotFound("File not found or signature is invalid")
  139. # extract text from file
  140. extension = upload_file.extension
  141. if extension.lower() not in IMAGE_EXTENSIONS:
  142. raise UnsupportedFileTypeError()
  143. generator = storage.load(upload_file.key)
  144. return generator, upload_file.mime_type