file_factory.py 9.1 KB

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