message_file_parser.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. from typing import Union
  2. import requests
  3. from core.app.app_config.entities import FileExtraConfig
  4. from core.file.file_obj import FileBelongsTo, FileTransferMethod, FileType, FileVar
  5. from extensions.ext_database import db
  6. from models.account import Account
  7. from models.model import EndUser, MessageFile, UploadFile
  8. from services.file_service import IMAGE_EXTENSIONS
  9. class MessageFileParser:
  10. def __init__(self, tenant_id: str, app_id: str) -> None:
  11. self.tenant_id = tenant_id
  12. self.app_id = app_id
  13. def validate_and_transform_files_arg(self, files: list[dict], file_extra_config: FileExtraConfig,
  14. user: Union[Account, EndUser]) -> list[FileVar]:
  15. """
  16. validate and transform files arg
  17. :param files:
  18. :param file_extra_config:
  19. :param user:
  20. :return:
  21. """
  22. for file in files:
  23. if not isinstance(file, dict):
  24. raise ValueError('Invalid file format, must be dict')
  25. if not file.get('type'):
  26. raise ValueError('Missing file type')
  27. FileType.value_of(file.get('type'))
  28. if not file.get('transfer_method'):
  29. raise ValueError('Missing file transfer method')
  30. FileTransferMethod.value_of(file.get('transfer_method'))
  31. if file.get('transfer_method') == FileTransferMethod.REMOTE_URL.value:
  32. if not file.get('url'):
  33. raise ValueError('Missing file url')
  34. if not file.get('url').startswith('http'):
  35. raise ValueError('Invalid file url')
  36. if file.get('transfer_method') == FileTransferMethod.LOCAL_FILE.value and not file.get('upload_file_id'):
  37. raise ValueError('Missing file upload_file_id')
  38. if file.get('transform_method') == FileTransferMethod.TOOL_FILE.value and not file.get('tool_file_id'):
  39. raise ValueError('Missing file tool_file_id')
  40. # transform files to file objs
  41. type_file_objs = self._to_file_objs(files, file_extra_config)
  42. # validate files
  43. new_files = []
  44. for file_type, file_objs in type_file_objs.items():
  45. if file_type == FileType.IMAGE:
  46. # parse and validate files
  47. image_config = file_extra_config.image_config
  48. # check if image file feature is enabled
  49. if not image_config:
  50. continue
  51. # Validate number of files
  52. if len(files) > image_config['number_limits']:
  53. raise ValueError(f"Number of image files exceeds the maximum limit {image_config['number_limits']}")
  54. for file_obj in file_objs:
  55. # Validate transfer method
  56. if file_obj.transfer_method.value not in image_config['transfer_methods']:
  57. raise ValueError(f'Invalid transfer method: {file_obj.transfer_method.value}')
  58. # Validate file type
  59. if file_obj.type != FileType.IMAGE:
  60. raise ValueError(f'Invalid file type: {file_obj.type}')
  61. if file_obj.transfer_method == FileTransferMethod.REMOTE_URL:
  62. # check remote url valid and is image
  63. result, error = self._check_image_remote_url(file_obj.url)
  64. if result is False:
  65. raise ValueError(error)
  66. elif file_obj.transfer_method == FileTransferMethod.LOCAL_FILE:
  67. # get upload file from upload_file_id
  68. upload_file = (db.session.query(UploadFile)
  69. .filter(
  70. UploadFile.id == file_obj.related_id,
  71. UploadFile.tenant_id == self.tenant_id,
  72. UploadFile.created_by == user.id,
  73. UploadFile.created_by_role == ('account' if isinstance(user, Account) else 'end_user'),
  74. UploadFile.extension.in_(IMAGE_EXTENSIONS)
  75. ).first())
  76. # check upload file is belong to tenant and user
  77. if not upload_file:
  78. raise ValueError('Invalid upload file')
  79. new_files.append(file_obj)
  80. # return all file objs
  81. return new_files
  82. def transform_message_files(self, files: list[MessageFile], file_extra_config: FileExtraConfig) -> list[FileVar]:
  83. """
  84. transform message files
  85. :param files:
  86. :param file_extra_config:
  87. :return:
  88. """
  89. # transform files to file objs
  90. type_file_objs = self._to_file_objs(files, file_extra_config)
  91. # return all file objs
  92. return [file_obj for file_objs in type_file_objs.values() for file_obj in file_objs]
  93. def _to_file_objs(self, files: list[Union[dict, MessageFile]],
  94. file_extra_config: FileExtraConfig) -> dict[FileType, list[FileVar]]:
  95. """
  96. transform files to file objs
  97. :param files:
  98. :param file_extra_config:
  99. :return:
  100. """
  101. type_file_objs: dict[FileType, list[FileVar]] = {
  102. # Currently only support image
  103. FileType.IMAGE: []
  104. }
  105. if not files:
  106. return type_file_objs
  107. # group by file type and convert file args or message files to FileObj
  108. for file in files:
  109. if isinstance(file, MessageFile):
  110. if file.belongs_to == FileBelongsTo.ASSISTANT.value:
  111. continue
  112. file_obj = self._to_file_obj(file, file_extra_config)
  113. if file_obj.type not in type_file_objs:
  114. continue
  115. type_file_objs[file_obj.type].append(file_obj)
  116. return type_file_objs
  117. def _to_file_obj(self, file: Union[dict, MessageFile], file_extra_config: FileExtraConfig) -> FileVar:
  118. """
  119. transform file to file obj
  120. :param file:
  121. :return:
  122. """
  123. if isinstance(file, dict):
  124. transfer_method = FileTransferMethod.value_of(file.get('transfer_method'))
  125. if transfer_method != FileTransferMethod.TOOL_FILE:
  126. return FileVar(
  127. tenant_id=self.tenant_id,
  128. type=FileType.value_of(file.get('type')),
  129. transfer_method=transfer_method,
  130. url=file.get('url') if transfer_method == FileTransferMethod.REMOTE_URL else None,
  131. related_id=file.get('upload_file_id') if transfer_method == FileTransferMethod.LOCAL_FILE else None,
  132. extra_config=file_extra_config
  133. )
  134. return FileVar(
  135. tenant_id=self.tenant_id,
  136. type=FileType.value_of(file.get('type')),
  137. transfer_method=transfer_method,
  138. url=None,
  139. related_id=file.get('tool_file_id'),
  140. extra_config=file_extra_config
  141. )
  142. else:
  143. return FileVar(
  144. id=file.id,
  145. tenant_id=self.tenant_id,
  146. type=FileType.value_of(file.type),
  147. transfer_method=FileTransferMethod.value_of(file.transfer_method),
  148. url=file.url,
  149. related_id=file.upload_file_id or None,
  150. extra_config=file_extra_config
  151. )
  152. def _check_image_remote_url(self, url):
  153. try:
  154. headers = {
  155. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
  156. }
  157. response = requests.head(url, headers=headers, allow_redirects=True)
  158. if response.status_code in {200, 304}:
  159. return True, ""
  160. else:
  161. return False, "URL does not exist."
  162. except requests.RequestException as e:
  163. return False, f"Error checking URL: {e}"