file_factory.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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, helpers
  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. upload_file_id = mapping.get("upload_file_id")
  138. if upload_file_id:
  139. try:
  140. uuid.UUID(upload_file_id)
  141. except ValueError:
  142. raise ValueError("Invalid upload file id format")
  143. stmt = select(UploadFile).where(
  144. UploadFile.id == upload_file_id,
  145. UploadFile.tenant_id == tenant_id,
  146. )
  147. upload_file = db.session.scalar(stmt)
  148. if upload_file is None:
  149. raise ValueError("Invalid upload file")
  150. file_type = FileType(mapping.get("type", "custom"))
  151. file_type = _standardize_file_type(
  152. file_type, extension="." + upload_file.extension, mime_type=upload_file.mime_type
  153. )
  154. return File(
  155. id=mapping.get("id"),
  156. filename=upload_file.name,
  157. extension="." + upload_file.extension,
  158. mime_type=upload_file.mime_type,
  159. tenant_id=tenant_id,
  160. type=file_type,
  161. transfer_method=transfer_method,
  162. remote_url=helpers.get_signed_file_url(upload_file_id=str(upload_file_id)),
  163. related_id=mapping.get("upload_file_id"),
  164. size=upload_file.size,
  165. storage_key=upload_file.key,
  166. )
  167. url = mapping.get("url") or mapping.get("remote_url")
  168. if not url:
  169. raise ValueError("Invalid file url")
  170. mime_type, filename, file_size = _get_remote_file_info(url)
  171. extension = mimetypes.guess_extension(mime_type) or "." + filename.split(".")[-1] if "." in filename else ".bin"
  172. file_type = FileType(mapping.get("type", "custom"))
  173. file_type = _standardize_file_type(file_type, extension=extension, mime_type=mime_type)
  174. return File(
  175. id=mapping.get("id"),
  176. filename=filename,
  177. tenant_id=tenant_id,
  178. type=file_type,
  179. transfer_method=transfer_method,
  180. remote_url=url,
  181. mime_type=mime_type,
  182. extension=extension,
  183. size=file_size,
  184. storage_key="",
  185. )
  186. def _get_remote_file_info(url: str):
  187. file_size = -1
  188. filename = url.split("/")[-1].split("?")[0] or "unknown_file"
  189. mime_type = mimetypes.guess_type(filename)[0] or ""
  190. resp = ssrf_proxy.head(url, follow_redirects=True)
  191. resp = cast(httpx.Response, resp)
  192. if resp.status_code == httpx.codes.OK:
  193. if content_disposition := resp.headers.get("Content-Disposition"):
  194. filename = str(content_disposition.split("filename=")[-1].strip('"'))
  195. file_size = int(resp.headers.get("Content-Length", file_size))
  196. mime_type = mime_type or str(resp.headers.get("Content-Type", ""))
  197. return mime_type, filename, file_size
  198. def _build_from_tool_file(
  199. *,
  200. mapping: Mapping[str, Any],
  201. tenant_id: str,
  202. transfer_method: FileTransferMethod,
  203. ) -> File:
  204. tool_file = (
  205. db.session.query(ToolFile)
  206. .filter(
  207. ToolFile.id == mapping.get("tool_file_id"),
  208. ToolFile.tenant_id == tenant_id,
  209. )
  210. .first()
  211. )
  212. if tool_file is None:
  213. raise ValueError(f"ToolFile {mapping.get('tool_file_id')} not found")
  214. extension = "." + tool_file.file_key.split(".")[-1] if "." in tool_file.file_key else ".bin"
  215. file_type = FileType(mapping.get("type", "custom"))
  216. file_type = _standardize_file_type(file_type, extension=extension, mime_type=tool_file.mimetype)
  217. return File(
  218. id=mapping.get("id"),
  219. tenant_id=tenant_id,
  220. filename=tool_file.name,
  221. type=file_type,
  222. transfer_method=transfer_method,
  223. remote_url=tool_file.original_url,
  224. related_id=tool_file.id,
  225. extension=extension,
  226. mime_type=tool_file.mimetype,
  227. size=tool_file.size,
  228. storage_key=tool_file.file_key,
  229. )
  230. def _is_file_valid_with_config(
  231. *,
  232. input_file_type: str,
  233. file_extension: str,
  234. file_transfer_method: FileTransferMethod,
  235. config: FileUploadConfig,
  236. ) -> bool:
  237. if (
  238. config.allowed_file_types
  239. and input_file_type not in config.allowed_file_types
  240. and input_file_type != FileType.CUSTOM
  241. ):
  242. return False
  243. if (
  244. input_file_type == FileType.CUSTOM
  245. and config.allowed_file_extensions is not None
  246. and file_extension not in config.allowed_file_extensions
  247. ):
  248. return False
  249. if input_file_type == FileType.IMAGE:
  250. if (
  251. config.image_config
  252. and config.image_config.transfer_methods
  253. and file_transfer_method not in config.image_config.transfer_methods
  254. ):
  255. return False
  256. elif config.allowed_file_upload_methods and file_transfer_method not in config.allowed_file_upload_methods:
  257. return False
  258. return True
  259. def _standardize_file_type(file_type: FileType, /, *, extension: str = "", mime_type: str = "") -> FileType:
  260. """
  261. If custom type, try to guess the file type by extension and mime_type.
  262. """
  263. if file_type != FileType.CUSTOM:
  264. return FileType(file_type)
  265. guessed_type = None
  266. if extension:
  267. guessed_type = _get_file_type_by_extension(extension)
  268. if guessed_type is None and mime_type:
  269. guessed_type = _get_file_type_by_mimetype(mime_type)
  270. return guessed_type or FileType.CUSTOM
  271. def _get_file_type_by_extension(extension: str) -> FileType | None:
  272. extension = extension.lstrip(".")
  273. if extension in IMAGE_EXTENSIONS:
  274. return FileType.IMAGE
  275. elif extension in VIDEO_EXTENSIONS:
  276. return FileType.VIDEO
  277. elif extension in AUDIO_EXTENSIONS:
  278. return FileType.AUDIO
  279. elif extension in DOCUMENT_EXTENSIONS:
  280. return FileType.DOCUMENT
  281. return None
  282. def _get_file_type_by_mimetype(mime_type: str) -> FileType | None:
  283. if "image" in mime_type:
  284. file_type = FileType.IMAGE
  285. elif "video" in mime_type:
  286. file_type = FileType.VIDEO
  287. elif "audio" in mime_type:
  288. file_type = FileType.AUDIO
  289. elif "text" in mime_type or "pdf" in mime_type:
  290. file_type = FileType.DOCUMENT
  291. else:
  292. file_type = FileType.CUSTOM
  293. return file_type
  294. def get_file_type_by_mime_type(mime_type: str) -> FileType:
  295. return _get_file_type_by_mimetype(mime_type) or FileType.CUSTOM