file_factory.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. import mimetypes
  2. from collections.abc import Callable, Mapping, Sequence
  3. from typing import Any, cast
  4. import httpx
  5. from sqlalchemy import select
  6. from constants import AUDIO_EXTENSIONS, DOCUMENT_EXTENSIONS, IMAGE_EXTENSIONS, VIDEO_EXTENSIONS
  7. from core.file import File, FileBelongsTo, FileTransferMethod, FileType, FileUploadConfig
  8. from core.helper import ssrf_proxy
  9. from extensions.ext_database import db
  10. from models import MessageFile, ToolFile, UploadFile
  11. def build_from_message_files(
  12. *,
  13. message_files: Sequence["MessageFile"],
  14. tenant_id: str,
  15. config: FileUploadConfig,
  16. ) -> Sequence[File]:
  17. results = [
  18. build_from_message_file(message_file=file, tenant_id=tenant_id, config=config)
  19. for file in message_files
  20. if file.belongs_to != FileBelongsTo.ASSISTANT
  21. ]
  22. return results
  23. def build_from_message_file(
  24. *,
  25. message_file: "MessageFile",
  26. tenant_id: str,
  27. config: FileUploadConfig,
  28. ):
  29. mapping = {
  30. "transfer_method": message_file.transfer_method,
  31. "url": message_file.url,
  32. "id": message_file.id,
  33. "type": message_file.type,
  34. "upload_file_id": message_file.upload_file_id,
  35. }
  36. return build_from_mapping(
  37. mapping=mapping,
  38. tenant_id=tenant_id,
  39. config=config,
  40. )
  41. def build_from_mapping(
  42. *,
  43. mapping: Mapping[str, Any],
  44. tenant_id: str,
  45. config: FileUploadConfig | None = None,
  46. ) -> File:
  47. config = config or FileUploadConfig()
  48. transfer_method = FileTransferMethod.value_of(mapping.get("transfer_method"))
  49. build_functions: dict[FileTransferMethod, Callable] = {
  50. FileTransferMethod.LOCAL_FILE: _build_from_local_file,
  51. FileTransferMethod.REMOTE_URL: _build_from_remote_url,
  52. FileTransferMethod.TOOL_FILE: _build_from_tool_file,
  53. }
  54. build_func = build_functions.get(transfer_method)
  55. if not build_func:
  56. raise ValueError(f"Invalid file transfer method: {transfer_method}")
  57. file = build_func(
  58. mapping=mapping,
  59. tenant_id=tenant_id,
  60. transfer_method=transfer_method,
  61. )
  62. if not _is_file_valid_with_config(
  63. input_file_type=mapping.get("type", FileType.CUSTOM),
  64. file_extension=file.extension,
  65. file_transfer_method=file.transfer_method,
  66. config=config,
  67. ):
  68. raise ValueError(f"File validation failed for file: {file.filename}")
  69. return file
  70. def build_from_mappings(
  71. *,
  72. mappings: Sequence[Mapping[str, Any]],
  73. config: FileUploadConfig | None,
  74. tenant_id: str,
  75. ) -> Sequence[File]:
  76. if not config:
  77. return []
  78. files = [
  79. build_from_mapping(
  80. mapping=mapping,
  81. tenant_id=tenant_id,
  82. config=config,
  83. )
  84. for mapping in mappings
  85. ]
  86. if (
  87. # If image config is set.
  88. config.image_config
  89. # And the number of image files exceeds the maximum limit
  90. and sum(1 for _ in (filter(lambda x: x.type == FileType.IMAGE, files))) > config.image_config.number_limits
  91. ):
  92. raise ValueError(f"Number of image files exceeds the maximum limit {config.image_config.number_limits}")
  93. if config.number_limits and len(files) > config.number_limits:
  94. raise ValueError(f"Number of files exceeds the maximum limit {config.number_limits}")
  95. return files
  96. def _build_from_local_file(
  97. *,
  98. mapping: Mapping[str, Any],
  99. tenant_id: str,
  100. transfer_method: FileTransferMethod,
  101. ) -> File:
  102. stmt = select(UploadFile).where(
  103. UploadFile.id == mapping.get("upload_file_id"),
  104. UploadFile.tenant_id == tenant_id,
  105. )
  106. row = db.session.scalar(stmt)
  107. if row is None:
  108. raise ValueError("Invalid upload file")
  109. file_type = FileType(mapping.get("type"))
  110. file_type = _standardize_file_type(file_type, extension="." + row.extension, mime_type=row.mime_type)
  111. return File(
  112. id=mapping.get("id"),
  113. filename=row.name,
  114. extension="." + row.extension,
  115. mime_type=row.mime_type,
  116. tenant_id=tenant_id,
  117. type=file_type,
  118. transfer_method=transfer_method,
  119. remote_url=row.source_url,
  120. related_id=mapping.get("upload_file_id"),
  121. size=row.size,
  122. )
  123. def _build_from_remote_url(
  124. *,
  125. mapping: Mapping[str, Any],
  126. tenant_id: str,
  127. transfer_method: FileTransferMethod,
  128. ) -> File:
  129. url = mapping.get("url")
  130. if not url:
  131. raise ValueError("Invalid file url")
  132. mime_type, filename, file_size = _get_remote_file_info(url)
  133. extension = mimetypes.guess_extension(mime_type) or "." + filename.split(".")[-1] if "." in filename else ".bin"
  134. file_type = FileType(mapping.get("type"))
  135. file_type = _standardize_file_type(file_type, extension=extension, mime_type=mime_type)
  136. return File(
  137. id=mapping.get("id"),
  138. filename=filename,
  139. tenant_id=tenant_id,
  140. type=file_type,
  141. transfer_method=transfer_method,
  142. remote_url=url,
  143. mime_type=mime_type,
  144. extension=extension,
  145. size=file_size,
  146. )
  147. def _get_remote_file_info(url: str):
  148. file_size = -1
  149. filename = url.split("/")[-1].split("?")[0] or "unknown_file"
  150. mime_type = mimetypes.guess_type(filename)[0] or ""
  151. resp = ssrf_proxy.head(url, follow_redirects=True)
  152. resp = cast(httpx.Response, resp)
  153. if resp.status_code == httpx.codes.OK:
  154. if content_disposition := resp.headers.get("Content-Disposition"):
  155. filename = str(content_disposition.split("filename=")[-1].strip('"'))
  156. file_size = int(resp.headers.get("Content-Length", file_size))
  157. mime_type = mime_type or str(resp.headers.get("Content-Type", ""))
  158. return mime_type, filename, file_size
  159. def _build_from_tool_file(
  160. *,
  161. mapping: Mapping[str, Any],
  162. tenant_id: str,
  163. transfer_method: FileTransferMethod,
  164. ) -> File:
  165. tool_file = (
  166. db.session.query(ToolFile)
  167. .filter(
  168. ToolFile.id == mapping.get("tool_file_id"),
  169. ToolFile.tenant_id == tenant_id,
  170. )
  171. .first()
  172. )
  173. if tool_file is None:
  174. raise ValueError(f"ToolFile {mapping.get('tool_file_id')} not found")
  175. extension = "." + tool_file.file_key.split(".")[-1] if "." in tool_file.file_key else ".bin"
  176. file_type = FileType(mapping.get("type"))
  177. file_type = _standardize_file_type(file_type, extension=extension, mime_type=tool_file.mimetype)
  178. return File(
  179. id=mapping.get("id"),
  180. tenant_id=tenant_id,
  181. filename=tool_file.name,
  182. type=file_type,
  183. transfer_method=transfer_method,
  184. remote_url=tool_file.original_url,
  185. related_id=tool_file.id,
  186. extension=extension,
  187. mime_type=tool_file.mimetype,
  188. size=tool_file.size,
  189. )
  190. def _is_file_valid_with_config(
  191. *,
  192. input_file_type: str,
  193. file_extension: str,
  194. file_transfer_method: FileTransferMethod,
  195. config: FileUploadConfig,
  196. ) -> bool:
  197. if (
  198. config.allowed_file_types
  199. and input_file_type not in config.allowed_file_types
  200. and input_file_type != FileType.CUSTOM
  201. ):
  202. return False
  203. if config.allowed_file_extensions and file_extension not in config.allowed_file_extensions:
  204. return False
  205. if config.allowed_file_upload_methods and file_transfer_method not in config.allowed_file_upload_methods:
  206. return False
  207. if input_file_type == FileType.IMAGE and config.image_config:
  208. if config.image_config.transfer_methods and file_transfer_method not in config.image_config.transfer_methods:
  209. return False
  210. return True
  211. def _standardize_file_type(file_type: FileType, /, *, extension: str = "", mime_type: str = "") -> FileType:
  212. """
  213. If custom type, try to guess the file type by extension and mime_type.
  214. """
  215. if file_type != FileType.CUSTOM:
  216. return FileType(file_type)
  217. guessed_type = None
  218. if extension:
  219. guessed_type = _get_file_type_by_extension(extension)
  220. if guessed_type is None and mime_type:
  221. guessed_type = _get_file_type_by_mimetype(mime_type)
  222. return guessed_type or FileType.CUSTOM
  223. def _get_file_type_by_extension(extension: str) -> FileType | None:
  224. extension = extension.lstrip(".")
  225. if extension in IMAGE_EXTENSIONS:
  226. return FileType.IMAGE
  227. elif extension in VIDEO_EXTENSIONS:
  228. return FileType.VIDEO
  229. elif extension in AUDIO_EXTENSIONS:
  230. return FileType.AUDIO
  231. elif extension in DOCUMENT_EXTENSIONS:
  232. return FileType.DOCUMENT
  233. def _get_file_type_by_mimetype(mime_type: str) -> FileType | None:
  234. if "image" in mime_type:
  235. file_type = FileType.IMAGE
  236. elif "video" in mime_type:
  237. file_type = FileType.VIDEO
  238. elif "audio" in mime_type:
  239. file_type = FileType.AUDIO
  240. elif "text" in mime_type or "pdf" in mime_type:
  241. file_type = FileType.DOCUMENT
  242. else:
  243. file_type = FileType.CUSTOM
  244. return file_type